document360-writer 0.5.272 → 0.5.273

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 +226 -224
  2. package/package.json +2 -2
package/dist/cli.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- var Ak=Object.defineProperty;var Jr=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var $h=(e,t)=>{for(var n in t)Ak(e,n,{get:t[n],enumerable:!0})};import bn from"picocolors";var ae,Ek,Nk,Dk,vh,Zr,f,O,H,q,Z,ve,Be,me,re=Jr(()=>{"use strict";ae="#7f56d9",[Ek,Nk,Dk]=[127,86,217],vh=e=>bn.isColorSupported?`\x1B[38;2;${Ek};${Nk};${Dk}m${e}\x1B[39m`:e,Zr=e=>bn.bold(vh(e)),f=e=>bn.dim(e),O=e=>bn.red(e),H=e=>bn.yellow(e),q=e=>bn.green(e),Z=vh,ve=e=>bn.gray(e),Be=e=>bn.bold(e),me=(e,t)=>`${e} ${t}`});import{existsSync as Ko,writeFileSync as vn,readFileSync as E$,readdirSync as N$}from"node:fs";import{join as Kh}from"node:path";import{devHintsGuidePath as Ci,hintsDir as zh,hooksDir as Xh,architectureDir as ef,messagesDir as Zl,creatorNotesPath as Qh,devhintsStatePath as tf,directivesPath as Jh,DIRECTIVES_HEADER as D$,roadmapPath as Zh,ROADMAP_HEADER as j$,ensureDir as os,writeMessage as I$,listOpenForDev as L$,stampDone as O$}from"document360-engine";function nf(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
2
+ var Lk=Object.defineProperty;var Zr=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var Sh=(e,t)=>{for(var n in t)Lk(e,n,{get:t[n],enumerable:!0})};import bn from"picocolors";var ae,Ok,_k,Mk,Ph,es,f,_,H,q,Z,Re,Be,ge,re=Zr(()=>{"use strict";ae="#7f56d9",[Ok,_k,Mk]=[127,86,217],Ph=e=>bn.isColorSupported?`\x1B[38;2;${Ok};${_k};${Mk}m${e}\x1B[39m`:e,es=e=>bn.bold(Ph(e)),f=e=>bn.dim(e),_=e=>bn.red(e),H=e=>bn.yellow(e),q=e=>bn.green(e),Z=Ph,Re=e=>bn.gray(e),Be=e=>bn.bold(e),ge=(e,t)=>`${e} ${t}`});import{existsSync as zo,writeFileSync as vn,readFileSync as M$,readdirSync as F$}from"node:fs";import{join as Xh}from"node:path";import{devHintsGuidePath as Ci,hintsDir as Qh,hooksDir as Jh,architectureDir as nf,messagesDir as nc,creatorNotesPath as Zh,devhintsStatePath as of,directivesPath as ef,DIRECTIVES_HEADER as U$,roadmapPath as tf,ROADMAP_HEADER as W$,ensureDir as rs,writeMessage as B$,listOpenForDev as H$,stampDone as G$}from"document360-engine";function rf(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
3
3
 
4
- <!-- devhints script v${Ie} \xB7 maintained by document360-writer (/devhints). -->
4
+ <!-- devhints script v${Le} \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
@@ -235,7 +235,7 @@ do it**:
235
235
  **Do NOT write or action the documentation yourself** \u2014 same boundary as Part 2. Writing the article is the
236
236
  docs agent's job; it actions open directives on its next \`/catch-up\` (as drafts) and flips each to \`[done]\`
237
237
  with the article it wrote. You are only the relay so the ask is captured durably and travels via git.
238
- `}function M$(){return`# Creator notes (optional \u2014 for the docs agent and the builder)
238
+ `}function V$(){return`# Creator notes (optional \u2014 for the docs agent and the builder)
239
239
 
240
240
  <!-- The ORIGINAL CREATOR's context. Most repos leave this empty \u2014 that's fine.
241
241
  The builder agent reads this FIRST and treats it as authoritative when writing the architecture
@@ -249,12 +249,12 @@ Anything only a human knows that would help document this product. For example:
249
249
  - Gotchas or non-obvious behavior.
250
250
 
251
251
  (Replace these examples with your notes, or leave the file as-is to skip \u2014 it's optional.)
252
- `}function Xo(e){os(zh(e)),os(ef(e)),os(Zl(e));for(let n of[zh(e),Zl(e)]){let o=Kh(n,".gitkeep");Ko(o)||vn(o,`# Keeps this document360-writer inbox tracked in git even when empty.
253
- `)}Ko(Qh(e))||vn(Qh(e),M$()),Ko(Jh(e))||vn(Jh(e),D$),Ko(Zh(e))||vn(Zh(e),j$),vn(Ci(e),nf()),os(Xh(e)),vn(Kh(Xh(e),"open-questions.mjs"),_$);let t=Ut(e);return rf(e,new Date().toISOString()),t}async function of(e,t){for(let n of Qo(Xo(t.cwd)))console.log(n);return{kind:"continue"}}function ro(){return[`This is document360-writer's dev hand-off setup (v${Ie}).`,'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; `git pull` at session start FIRST, because the docs"," agent may be on another machine and its questions only reach you when you pull; 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). FIRST run `git pull` (fast-forward) if this repo has a remote \u2014 the docs"," agent may be a different person on a different machine, so their questions for you only EXIST in your",' checkout once you pull; skipping it makes an empty mailbox look like "no questions". If the pull'," cannot fast-forward, say so and continue rather than merging or rebasing to force it. Then 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": ${Ie},`,' "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. Finish with a RECEIPT of what this run actually changed, then the right next step. Two parts.",""," (a) The receipt. A heading line, then one short bullet per thing that CHANGED \u2014 omit any bullet"," that did not happen, so a run that changed little stays three lines rather than ten. Report"," OUTCOMES, not the steps you took. Cover, where applicable: the protocol version you moved to; the"," architecture brief (created / N files updated / unchanged); how many docs questions you answered"," (and how many were `[discovery]`); how many hints you dropped \u2014 and when none, add one clause",' saying WHY, so "0 hints" reads as a judgement rather than an omission; whether you added to'," CREATOR-NOTES.md; whether you wired the session-start hook; and the commit you pushed. Shape:"," \u2705 Hand-off refreshed (protocol v11 \u2192 v12)"," \u2022 architecture brief: 2 files updated"," \u2022 answered 3 docs questions (1 [discovery])"," \u2022 dropped 0 hints \u2014 only internal test anchors changed"," \u2022 committed + pushed: <short sha>",' Say "\u2705 Setup complete" instead when this was the first-time setup (no brief existed before).',""," (b) The next step \u2014 chosen by what you are actually HANDING OVER. Do not print a command in every"," case, and never invent one to look helpful:"," \u2022 You answered a question, dropped a hint, or relayed an owner directive \u2192 the docs agent has a"," queue to fold in. Print, fenced on its own line so it copies cleanly:"," ```"," /catch-up"," ```"," \u2022 The docs folder configured in `.d360-writer/config.json` (default `.d360-writer/user-docs/`) is"," absent or empty \u2192 this repo has no docs yet, so it is a cold start:"," ```"," write the docs for this repo"," ```"," \u2022 You handed over NOTHING (no answers, no hints, no directives) and docs already exist \u2192 print NO",' command. Say: "Nothing new to hand over. Switch back to the document360-writer terminal \u2014 it',' will show you where things stand." The docs agent picks its own next action from the whole'," picture (its documentation campaign, coverage gaps, what is still unpublished); a command"," guessed from your side would override one it already knows to be better.",' When you DO print a block, precede it with "Back in the document360-writer terminal, paste this:"',' \u2014 or "Now switch to the document360-writer terminal and paste this:" on first-time setup.'].join(`
254
- `)}function tc(e){try{let t=E$(tf(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function rf(e,t){let o={...tc(e)??{},emittedVersion:Ie,emittedAt:t};vn(tf(e),`${JSON.stringify(o,null,2)}
255
- `)}function an(e){try{return N$(ef(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function Ut(e){let n=tc(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<Ie?"stale":"current",completedVersion:n}}function F$(e){let t=new RegExp(`${ec.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(\\d+)\\)`).exec(e);return t?Number(t[1]):null}function Si(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,supersededRequests:[],toVersion:Ie};try{if(!Ko(Ci(e)))return n;let o=tc(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;if(Ie>r&&(os(Zl(e)),vn(Ci(e),nf()),rf(e,t),n.guideRefreshed=!0),Ie>s){let i=L$(e).filter(l=>l.kind==="request"&&l.subject.startsWith(ec)),a=i.filter(l=>(F$(l.subject)??Ie)>=Ie);for(let l of i.filter(d=>!a.includes(d)))O$(e,l.file,{doneAt:t,answeredBy:"docs"}),n.supersededRequests.push(l.subject);a.length===0&&(I$(e,{id:`onb${Ie}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${ec}${Ie})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${Ie}${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:","",ro()].join(`
256
- `)}),n.notifiedBuilder=!0)}}catch{}return n}function Pi(e){if(!Ko(Ci(e)))return[];let t=Ut(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${Ie}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,zo,ro(),zo,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function nc(){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(`
257
- `)}function Ti(){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):",zo,nc(),zo]}function Qo(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${Ie}.`," 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):",zo,ro(),zo,"","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 zo,Ie,_$,ec,xn=Jr(()=>{"use strict";zo="-".repeat(64),Ie=12,_$=`#!/usr/bin/env node
252
+ `}function Qo(e){rs(Qh(e)),rs(nf(e)),rs(nc(e));for(let n of[Qh(e),nc(e)]){let o=Xh(n,".gitkeep");zo(o)||vn(o,`# Keeps this document360-writer inbox tracked in git even when empty.
253
+ `)}zo(Zh(e))||vn(Zh(e),V$()),zo(ef(e))||vn(ef(e),U$),zo(tf(e))||vn(tf(e),W$),vn(Ci(e),rf()),rs(Jh(e)),vn(Xh(Jh(e),"open-questions.mjs"),q$);let t=Ut(e);return af(e,new Date().toISOString()),t}async function sf(e,t){for(let n of Jo(Qo(t.cwd)))console.log(n);return{kind:"continue"}}function so(){return[`This is document360-writer's dev hand-off setup (v${Le}).`,'Connect this repository to document360-writer (its "docs agent" \u2014 a separate tool that writes this',"product's user documentation from your code, but needs your intent). This prompt is SAFE TO RUN MORE","THAN ONCE \u2014 paste it again whenever the product changes. At each step: create what is missing, reconcile","what already exists, and never duplicate, clobber a refined file, or delete human-written notes. In order:","","1. Read `.d360-writer/DEV-HINTS-GUIDE.md` \u2014 the full dev\u2192docs hand-off protocol (Parts 1\u20136). Follow it.","2. Architecture brief in `.d360-writer/architecture/` (per the guide). First read"," `.d360-writer/architecture/CREATOR-NOTES.md` and treat it as authoritative (it may be empty; never"," modify it). Then:"," \u2022 If no brief exists yet, write it now \u2014 a USER-DOC-enabling brief: product intent, user-facing"," surfaces, features and why a user reaches for each, roles/permission gating, core workflows,"," terminology \u2014 every claim citing the source file(s) that prove it. Skip internals (services, data"," access, infra, build/CI, tests)."," \u2022 If a brief already exists, UPDATE it to match the current code: add new surfaces/features, correct"," what changed, remove what was deleted \u2014 but preserve accurate existing content and any human edits."," Do NOT rewrite it from scratch. If nothing changed, leave it as is.","3. Persist the ongoing rule so teammates' agents inherit it: this repo's agent-memory file (CLAUDE.md,"," or AGENTS.md \u2014 whichever this repo already uses; create CLAUDE.md if neither exists) should contain a",' short "Documentation hand-off" section saying: on every user-facing change, drop a hint file in'," `.d360-writer/hints/` and keep `.d360-writer/architecture/` current \u2014 and SURFACE each hint drop in"," your reply (name the file + the one-line surface), never silently; NEVER write or publish the"," user-facing articles yourself (that is the docs agent's job \u2014 you only hand off); each session,"," check `.d360-writer/messages/` for open questions from the docs agent and answer them promptly and"," in full \u2014 an open docs question BLOCKS the documentation, and `[discovery]` questions define the"," whole product brief, so answer those in depth; `git pull` at session start FIRST, because the docs"," agent may be on another machine and its questions only reach you when you pull; 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). FIRST run `git pull` (fast-forward) if this repo has a remote \u2014 the docs"," agent may be a different person on a different machine, so their questions for you only EXIST in your",' checkout once you pull; skipping it makes an empty mailbox look like "no questions". If the pull'," cannot fast-forward, say so and continue rather than merging or rebasing to force it. Then check"," `.d360-writer/messages/` for open questions addressed to you"," (`from: docs`, `status: open`). Answer each IN FULL \u2014 an open docs question blocks the documentation,"," and `[discovery]`-tagged questions (what the product is, who it's for, its core mental model,"," misconceptions, positioning, terminology) define the whole product brief, so answer those in depth."," Fold durable facts into the architecture brief and drop a reply (`from: dev`, `kind: answer`,"," `re: <id>`) \u2014 then set the question's frontmatter `status: done`. If there are none, continue.","6. Then STOP and ask me for tribal knowledge \u2014 present it as a clearly-marked, standalone prompt on its"," own line (NOT buried in prose) and WAIT for my reply before doing anything else. Use this shape:",' "\u23F8 YOUR INPUT NEEDED \u2014 Any tribal knowledge that would help document this product? (folder map,',` terminology, what to prioritize or skip, gotchas.) Type it below, or reply 'none' / 'carry on' to skip."`," If I give you anything, phrase it clearly and append it to `.d360-writer/architecture/CREATOR-NOTES.md`"," (keep the existing header comment and every note already there; only add). If I say 'none'/'carry on', continue.",`7. Record completion: write/merge \`.d360-writer/devhints-state.json\` with {"completedVersion": ${Le},`,' "completedAt": "<UTC now>", "completedCommit": "<current HEAD short sha>"} (preserve any other keys'," already in the file, e.g. emittedAt). Include this file in the commit from step 3.","8. Finish with a RECEIPT of what this run actually changed, then the right next step. Two parts.",""," (a) The receipt. A heading line, then one short bullet per thing that CHANGED \u2014 omit any bullet"," that did not happen, so a run that changed little stays three lines rather than ten. Report"," OUTCOMES, not the steps you took. Cover, where applicable: the protocol version you moved to; the"," architecture brief (created / N files updated / unchanged); how many docs questions you answered"," (and how many were `[discovery]`); how many hints you dropped \u2014 and when none, add one clause",' saying WHY, so "0 hints" reads as a judgement rather than an omission; whether you added to'," CREATOR-NOTES.md; whether you wired the session-start hook; and the commit you pushed. Shape:"," \u2705 Hand-off refreshed (protocol v11 \u2192 v12)"," \u2022 architecture brief: 2 files updated"," \u2022 answered 3 docs questions (1 [discovery])"," \u2022 dropped 0 hints \u2014 only internal test anchors changed"," \u2022 committed + pushed: <short sha>",' Say "\u2705 Setup complete" instead when this was the first-time setup (no brief existed before).',""," (b) The next step \u2014 chosen by what you are actually HANDING OVER. Do not print a command in every"," case, and never invent one to look helpful:"," \u2022 You answered a question, dropped a hint, or relayed an owner directive \u2192 the docs agent has a"," queue to fold in. Print, fenced on its own line so it copies cleanly:"," ```"," /catch-up"," ```"," \u2022 The docs folder configured in `.d360-writer/config.json` (default `.d360-writer/user-docs/`) is"," absent or empty \u2192 this repo has no docs yet, so it is a cold start:"," ```"," write the docs for this repo"," ```"," \u2022 You handed over NOTHING (no answers, no hints, no directives) and docs already exist \u2192 print NO",' command. Say: "Nothing new to hand over. Switch back to the document360-writer terminal \u2014 it',' will show you where things stand." The docs agent picks its own next action from the whole'," picture (its documentation campaign, coverage gaps, what is still unpublished); a command"," guessed from your side would override one it already knows to be better.",' When you DO print a block, precede it with "Back in the document360-writer terminal, paste this:"',' \u2014 or "Now switch to the document360-writer terminal and paste this:" on first-time setup.'].join(`
254
+ `)}function rc(e){try{let t=M$(of(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function af(e,t){let o={...rc(e)??{},emittedVersion:Le,emittedAt:t};vn(of(e),`${JSON.stringify(o,null,2)}
255
+ `)}function an(e){try{return F$(nf(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function Ut(e){let n=rc(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<Le?"stale":"current",completedVersion:n}}function Y$(e){let t=new RegExp(`${oc.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(\\d+)\\)`).exec(e);return t?Number(t[1]):null}function Si(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,supersededRequests:[],toVersion:Le};try{if(!zo(Ci(e)))return n;let o=rc(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;if(Le>r&&(rs(nc(e)),vn(Ci(e),rf()),af(e,t),n.guideRefreshed=!0),Le>s){let i=H$(e).filter(l=>l.kind==="request"&&l.subject.startsWith(oc)),a=i.filter(l=>(Y$(l.subject)??Le)>=Le);for(let l of i.filter(d=>!a.includes(d)))G$(e,l.file,{doneAt:t,answeredBy:"docs"}),n.supersededRequests.push(l.subject);a.length===0&&(B$(e,{id:`onb${Le}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${oc}${Le})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${Le}${s?` (you last completed v${s})`:""}.`,"Re-run the hand-off so the docs agent and this repo stay in step \u2014 run this prompt here:","",so()].join(`
256
+ `)}),n.notifiedBuilder=!0)}}catch{}return n}function Pi(e){if(!zo(Ci(e)))return[];let t=Ut(e);return t.status==="current"?[]:[`\u{1F514} Your builder agent ${t.completedVersion?`is on v${t.completedVersion}`:"hasn't completed the hand-off yet"} \u2014 d360-writer's dev\u2194docs protocol is now v${Le}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,Xo,so(),Xo,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function sc(){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(`
257
+ `)}function Ti(){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):",Xo,sc(),Xo]}function Jo(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${Le}.`," Have them run the prompt below again \u2014 it now sets up two-way messages + on-demand docs.",""]:[],"\u2713 Wrote .d360-writer/DEV-HINTS-GUIDE.md + the .d360-writer/architecture/ (brief), .d360-writer/hints/, and .d360-writer/messages/ inboxes.","","\u{1F4CB} Copy this one prompt and run it in your repo's coding agent (Claude Code / Codex / Cursor):",Xo,so(),Xo,"","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 Xo,Le,q$,oc,xn=Zr(()=>{"use strict";Xo="-".repeat(64),Le=12,q$=`#!/usr/bin/env node
258
258
  // d360-writer \u2014 session-start nudge for the builder ("John"). Surfaces open questions the docs agent
259
259
  // ("Julie") left in .d360-writer/messages/ so they get answered, not forgotten. Self-contained (no deps);
260
260
  // wired into your coding agent's session-start trigger by /devhints. See .d360-writer/DEV-HINTS-GUIDE.md.
@@ -292,94 +292,94 @@ try {
292
292
  } catch {
293
293
  /* a session-start nudge must never break the session */
294
294
  }
295
- `;ec="Re-run dev\u2194docs onboarding (protocol v"});var wf={};$h(wf,{initCommand:()=>sc,scaffoldInit:()=>oc,writeWriterGitignore:()=>rc});import{input as rs,confirm as U$}from"@inquirer/prompts";import{basename as lf,join as Ai}from"node:path";import{existsSync as Jo,readFileSync as cf,readdirSync as W$,writeFileSync as sf}from"node:fs";import{writeProjectConfig as uf,readProjectConfig as B$,projectConfigPath as df,writerDir as H$,DEFAULT_DOCS_DIR as pf,DEFAULT_CAPTURE_DIR as hf,DEFAULT_OUTPUT_DIR as ff}from"document360-engine";function oc(e,t="berlin"){let n=df(e);if(Jo(n))return{created:!1,path:n,profileName:""};let o={projectId:mf(e)??lf(e),docsDir:pf,captureDir:hf,outputDir:ff,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:gf(e)};return uf(o,e),rc(e),{created:!0,path:n,profileName:t}}function rc(e){let t=Ai(H$(e),".gitignore"),n="# Local/transient \u2014 the config files here ARE meant to be committed.";if(!Jo(t)){sf(t,[n,...af,""].join(`
296
- `),"utf8");return}let o;try{o=cf(t,"utf8")}catch{return}let r=new Set(o.split(/\r?\n/).map(l=>l.trim())),s=af.filter(l=>!r.has(l)&&!r.has(l.replace(/\/$/,"")));if(s.length===0)return;let i=/\r\n/.test(o)?`\r
295
+ `;oc="Re-run dev\u2194docs onboarding (protocol v"});var bf={};Sh(bf,{initCommand:()=>lc,scaffoldInit:()=>ic,writeWriterGitignore:()=>ac});import{input as ss,confirm as K$}from"@inquirer/prompts";import{basename as uf,join as Ai}from"node:path";import{existsSync as Zo,readFileSync as df,readdirSync as z$,writeFileSync as lf}from"node:fs";import{writeProjectConfig as pf,readProjectConfig as X$,projectConfigPath as hf,writerDir as Q$,DEFAULT_DOCS_DIR as ff,DEFAULT_CAPTURE_DIR as mf,DEFAULT_OUTPUT_DIR as gf}from"document360-engine";function ic(e,t="berlin"){let n=hf(e);if(Zo(n))return{created:!1,path:n,profileName:""};let o={projectId:wf(e)??uf(e),docsDir:ff,captureDir:mf,outputDir:gf,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:yf(e)};return pf(o,e),ac(e),{created:!0,path:n,profileName:t}}function ac(e){let t=Ai(Q$(e),".gitignore"),n="# Local/transient \u2014 the config files here ARE meant to be committed.";if(!Zo(t)){lf(t,[n,...cf,""].join(`
296
+ `),"utf8");return}let o;try{o=df(t,"utf8")}catch{return}let r=new Set(o.split(/\r?\n/).map(l=>l.trim())),s=cf.filter(l=>!r.has(l)&&!r.has(l.replace(/\/$/,"")));if(s.length===0)return;let i=/\r\n/.test(o)?`\r
297
297
  `:`
298
298
  `,a=o.endsWith(`
299
- `)?"":i;sf(t,`${o}${a}${s.join(i)}${i}`,"utf8")}async function sc(){let e=process.cwd(),t=df(e);if(Jo(t)&&!await U$({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let n=mf(e)??lf(e),o=await rs({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await rs({message:"Capture directory (where document360-capture .spec.ts files live):",default:hf}),s=await rs({message:"Screenshot output directory:",default:ff}),i=await rs({message:"Default connection profile name:",default:"berlin"}),a=await rs({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),l={projectId:o,docsDir:pf,captureDir:r,outputDir:s,profiles:{[i]:{connection:{environment:a},production:!1}},defaultProfile:i,authoritativeSourceFiles:gf(e)},d=B$(e);d?.terminologyGlossary&&(l.terminologyGlossary=d.terminologyGlossary),uf(l,e),rc(e);let g=Xo(e);console.log(""),console.log(q(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${Z(`d360-writer login --profile ${i}`)} ${f("(sign in; project & workspace auto-selected)")}`),console.log("");for(let w of Qo(g))console.log(w);return console.log(""),console.log(`${f("Then ask:")} ${Z('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function mf(e){let t=Ai(e,"package.json");if(!Jo(t))return null;try{return JSON.parse(cf(t,"utf8")).name??null}catch{return null}}function gf(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Jo(Ai(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Ai(e,n);Jo(o)&&!G$(o)&&t.push(n)}return t}function G$(e){try{return W$(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var af,Ei=Jr(()=>{"use strict";re();xn();af=[".sessions/","cache/"]});import{createRequire as iv}from"node:module";import{existsSync as av,readFileSync as lv}from"node:fs";import{dirname as Sf,join as Pf}from"node:path";function dt(){let e;try{e=cv.resolve("document360-capture/helpers")}catch{return null}let t=Sf(e);for(let n=0;n<5&&!av(Pf(t,"package.json"));n++)t=Sf(t);try{let n=JSON.parse(lv(Pf(t,"package.json"),"utf8"));return n.name==="document360-capture"&&n.version?n.version:null}catch{return null}}var cv,Zo=Jr(()=>{"use strict";cv=iv(import.meta.url)});var Gg={};$h(Gg,{doctorCommand:()=>Rs,renderDoctorChecks:()=>Hg,runDoctorChecks:()=>Bg});import{existsSync as QR}from"node:fs";import{d360GetAll as JR,getAccessToken as ZR,isExpired as va,loadProfileMap as eC,loadTokens as tC,listStoredSessions as nC,tokensProjectId as Ku,packageSkillsDir as Wg,ENGINE_VERSION as oC,projectConfigPath as rC,readProjectConfig as sC,DEFAULT_DOCS_DIR as iC,fetchManifestSummary as aC,resolveActiveProfile as lC,classifyClaudeAuth as cC,CLAUDE_CODE_SETUP_HINT as xa,resolveModelSetting as uC,probeModel as dC,probeAgentTurn as pC,stderrHeadline as hC,detectAppType as fC,playbookSkillName as mC,D360AuthError as gC,applyStructureOrder as wC}from"document360-engine";async function Bg(e,t){let n=[],o=dt();n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${oC}${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=cC();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. ${xa}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:xa});let i=uC(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 D=await dC(e,i.model??void 0);if(D.ok){n.push({level:"ok",label:`Model reachable \u2014 replied in ${(D.latencyMs/1e3).toFixed(1)}s`});let L=await pC(e,i.model??void 0);if(L.ok)n.push({level:"ok",label:`Agent turn works \u2014 ran with your skills and tools in ${(L.latencyMs/1e3).toFixed(1)}s`});else{let B=hC(L.stderr),M=/auth|sign.?in|login|credential|token|401|expired/i.test(`${L.error??""} ${L.stderr??""}`);if(n.push({level:"fail",label:L.timedOut?"Agent turn never finished \u2014 the model answers, but a real turn with your skills and tools hangs":M?"Agent turn failed \u2014 your Claude sign-in has expired, so every /write, /review and /catch-up will do nothing":`Agent turn produced nothing \u2014 the model answers, but a real turn with your skills and tools ${L.producedNothing?"ends instantly with no output":`fails: ${L.error}`}`,fix:(B?`Claude Code said: "${B}". `:"")+(M?`Sign in again, then re-run /doctor. ${xa}`:"This is the failure behind an empty /write, /review or /catch-up. Run /logs for the whole thing \u2014 it offers to copy it so you can send it to the team.")}),M){let X=n.find(z=>z.label.startsWith("Claude auth:"));X&&(X.level="warn",X.label="Claude auth: a sign-in exists on this machine, but it is no longer valid",X.fix=`Sign in again. ${xa}`)}}}else D.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 ${D.error??"no output"} (a docs turn will end with 0 tokens / no output)`,fix:'Check sign-in, the selected model (/model), and network access to the Claude endpoint; confirm with: claude -p "say hi"'})}let a=sC(e);if(!a)return n.push({level:"fail",label:`No ${rC(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${a.projectId}`});let l=(a.docsDir??iC).replace(/\/+$/,"");n.push(a.mode==="engineer"?{level:"warn",label:"Mode: engineer \u2014 agent may modify any source file (dogfooding)",fix:'Remove "mode" from .d360-writer/config.json for the writer-mode boundary'}:{level:"ok",label:`Mode: writer \u2014 edits limited to ${l}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let d=a.authoritativeSourceFiles??[];n.push(d.length>0?{level:"ok",label:`Sources: docs grounded in ${d.length} path(s) (${d.slice(0,3).join(", ")}${d.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 g=a.appType??fC(e);if(g){let D=a.appType?"from config":"auto-detected",L=g==="web"||g==="cli";n.push({level:"ok",label:`Genre: ${g} (${D})${L?` \u2192 ${mC(g)} 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 w;try{w=lC(e),n.push({level:"ok",label:`Profile: ${w.name} (${w.connection.name})${w.production?" \u26A0 PRODUCTION":""}`})}catch(D){return n.push({level:"fail",label:`Profile config: ${D.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let k=tC(w.name,w.project.projectId),S=nC(w.name).filter(D=>{let L=Ku(D);return!!L&&L!==w.project.projectId&&!(va(D)&&!D.refreshToken)}),v=w.project.projectName?`"${w.project.projectName}"`:"this project";k?va(k)&&!k.refreshToken?n.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):va(k)?n.push({level:"ok",label:"Document360: logged in (access token expired \u2014 refreshes automatically on the next call)"}):n.push({level:"ok",label:`Document360: logged in to ${v} (until ${new Date(k.expiresAt).toLocaleString()})`}):n.push(S.length>0?{level:"fail",label:`Document360: not signed in to ${v} \u2014 signed in to ${S.map(D=>D.projectName?`"${D.projectName}"`:(Ku(D)??"").slice(0,8)+"\u2026").join(", ")} instead`,fix:`Run: /login and pick ${v} \u2014 each project needs its own sign-in, and both are then kept`}:{level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${w.name})`}),S.length>0&&n.push({level:"ok",label:`Other Document360 projects signed in on this machine: ${S.map(D=>D.projectName?`"${D.projectName}"`:(Ku(D)??"").slice(0,8)+"\u2026").join(", ")} (kept \u2014 each repo uses its own)`}),n.push(w.project.workspaceId?{level:"ok",label:`Workspace: ${w.project.workspaceName??w.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let C=eC(e,w.name);C?C.projectId&&w.project.projectId&&C.projectId!==w.project.projectId?n.push({level:"fail",label:`Category map projectId (${C.projectId}) \u2260 profile projectId (${w.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(C.articles).length} articles, ${Object.keys(C.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${w.name}" (created on first /push)`}),n.push(QR(Wg())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${Wg()}`,fix:"Reinstall document360-writer (broken install)"});let T=Ut(e);if(T.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${Ie})`}):T.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${T.completedVersion}, current is v${Ie}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),k&&(!va(k)||k.refreshToken)){let D={profile:w.name,connection:w.connection,projectId:w.project.projectId,projectName:w.project.projectName};try{await ZR(D);let B=await JR(D,"/v3/projects");n.push({level:"ok",label:`API reachable (${w.connection.apiUrl}) \u2014 ${B.length} project(s) visible`})}catch(B){n.push({level:"fail",label:`API call failed: ${B.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let L=C?.projectId??w.project.projectId;if(L&&w.project.workspaceId){try{let B=await aC(D,L,w.project.workspaceId);if(B){let M=(B.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Your Document360 project: reachable on ${w.connection.name} (${B.languages?.length??0} language${(B.languages?.length??0)===1?"":"s"}) \xB7 version ${M||"(none)"}`})}else n.push({level:"ok",label:`Workspace sync manifest: not live on ${w.connection.name} yet \u2014 sync uses the per-article path (nothing to do)`})}catch(B){B instanceof gC||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(B.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${w.project.projectName??L})`,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 (${B.message.slice(0,80)})`})}try{let B=await wC({cwd:e,profileName:w.name,dryRun:!0}),M=B.categoriesReordered+B.articlesReordered;if(B.skipped==="no category map")n.push({level:"ok",label:"Reading order: nothing to check yet (no articles published)"});else if(B.skipped)n.push({level:"warn",label:`Reading order: can't be checked (${B.skipped})`,fix:"Your article order on Document360 may not match your structure \u2014 /push syncs it once this resolves"});else if(B.unverified)n.push({level:"warn",label:`Reading order: ${B.unverified} of your articles aren't listed by Document360, so their order can't be set`,fix:"Usually means those articles are not live yet (the listing returns published articles). /publish takes them live, then /push re-syncs the order"});else if(M>0){let X=[B.categoriesReordered>0?`${B.categoriesReordered} categor${B.categoriesReordered===1?"y":"ies"}`:"",B.articlesReordered>0?`${B.articlesReordered} article${B.articlesReordered===1?"":"s"}`:""].filter(Boolean);n.push({level:"warn",label:`Reading order: ${X.join(" + ")} out of order on Document360`,fix:"Run /push \u2014 it re-syncs the order from your NN- folder/file prefixes"})}else n.push({level:"ok",label:"Reading order: Document360 matches your structure"});if(B.orphans?.length){let X=B.orphans;n.push({level:"warn",label:`${X.length} article${X.length===1?"":"s"} on Document360 ${X.length===1?"is":"are"} not in your docs folder: ${X.slice(0,3).map(z=>z.path).join(", ")}${X.length>3?`, +${X.length-3} more`:""}`,fix:"/retire <path> takes one off your readers \xB7 /pull <path> brings one back into your docs folder \u2014 until you choose, it stays live and d360-writer leaves it alone"})}}catch(B){n.push({level:"warn",label:`Reading order: check failed (${B.message.slice(0,80)})`})}}}return n}function Hg(e){let t=[""];for(let r of e){let s=r.level==="ok"?q("\u2713"):r.level==="warn"?H("\u26A0"):O("\u2717");t.push(` ${s} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("fix:")} ${Z(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?q(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):O(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function Rs(e,t){console.log(f("Running checks\u2026"));for(let n of Hg(await Bg(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var Ra=Jr(()=>{"use strict";xn();re();Zo()});import{Command as QD}from"commander";import{createRequire as JD}from"node:module";import{AUTH_MODES as ZD}from"document360-engine";import{input as zk}from"@inquirer/prompts";import{loginPkce as Xk,refreshTokens as Qk,toStoredTokens as Eh,clearTokens as Jk,decodeJwtClaims as Th,isExpired as Zk,loadTokens as Nh,saveTokens as Dh,listStoredSessions as Gl,tokensProjectId as $n,rememberSessionProject as Ah,resolveActiveProfile as ns,setProfileProject as e$,readProjectConfig as t$}from"document360-engine";re();import{select as jk}from"@inquirer/prompts";import{resolveActiveProfile as Ik,setProfileProject as Lk,resolveProjectId as Ok,listWorkspaces as _k}from"document360-engine";async function es(e,t){let n=Ik(e,t),o={profile:n.name,connection:n.connection,projectId:n.project.projectId,projectName:n.project.projectName},r=n.project.projectId??Ok(o);return{workspaces:await _k(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var xh=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function Bl(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 fi(e,t,n,o,r){Lk(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function Rh(e,t,n){let o;try{o=await es(e,n)}catch(s){return console.log(O(`Could not list workspaces: ${s.message}`)),1}let r=Bl(o.workspaces,t);return r?(fi(e,o.profile,o.projectId,r.id,r.name),console.log(q(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(O(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function Yo(e,t){let n;try{n=await es(e,t)}catch(d){console.log(O(`Could not list workspaces: ${d.message}`));return}let{workspaces:o,projectId:r,profile:s,current:i}=n;if(o.length===0){console.log(f("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let d of o)console.log(` ${d.id===i?Z("\u25CF"):" "} ${xh(d)} ${f(d.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let a=await jk({message:"Select the Document360 workspace for this repo:",choices:o.map(d=>({name:`${xh(d)}${d.id===i?" (current)":""}`,value:d.id}))}),l=o.find(d=>d.id===a);fi(e,s,r,a,l?.name),console.log(q(`\u2713 Workspace set to "${l?.name??a}" for profile "${s}".`))}re();import{select as Mk}from"@inquirer/prompts";import{resolveActiveProfile as Fk,setProfileProject as Uk,listProjects as Wk}from"document360-engine";async function sn(e,t){let n=Fk(e,t),o={profile:n.name,connection:n.connection};return{projects:await Wk(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var Ch=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Hl(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 mi(e,t,n,o){Uk(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function Sh(e,t,n){let o;try{o=await sn(e,n)}catch(s){return console.log(O(`Could not list projects: ${s.message}`)),1}let r=Hl(o.projects,t);return r?(mi(e,o.profile,r.id,r.name),console.log(q(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log(O(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function gi(e,t){let n;try{n=await sn(e,t)}catch(l){console.log(O(`Could not list projects: ${l.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(f("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let l of o)console.log(` ${l.id===s?Z("\u25CF"):" "} ${Ch(l)} ${f(l.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let i=await Mk({message:"Select the Document360 project for this repo:",choices:o.map(l=>({name:`${Ch(l)}${l.id===s?" (current)":""}`,value:l.id}))}),a=o.find(l=>l.id===i);mi(e,r,i,a?.name),console.log(q(`\u2713 Project set to "${a?.name??i}" for profile "${r}". Next: pick a workspace.`))}re();import Bk from"picocolors";function Hk(e=process.env){return e.FORCE_HYPERLINK==="0"||!Bk.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 Gk(e,t=e,n){return Hk(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var qk=/https?:\/\/[^\s\x1b]+/g;function ts(e,t){return e.replace(qk,n=>Gk(n,n,t))}import{readProjectConfig as Ph,sunsetEnvironment as Vk,resolveActiveProfile as Yk}from"document360-engine";function Kk(e,t){let n=Ph(e);return Object.entries(n?.profiles??{}).find(([,o])=>(o.connection?.environment??"berlin")===t)?.[0]??null}function kn(e,t){try{if(!Ph(e))return null;let n=Yk(e,t),o=Vk(n.connection.name);if(!o)return null;let r=Kk(e,o.replacement);return{name:o.name,replacement:o.replacement,why:o.why,replacementProfile:r,cmd:r?`/profile ${r}`:`/profile add ${o.replacement}`}}catch{return null}}function jh(e){return{...Th(e.idToken)??{},...Th(e.accessToken)??{}}}function wi(e){let t=jh(e),n=t.email??t.preferred_username??t.sub??"unknown",o=$n(e),r=e.projectName?` \xB7 project "${e.projectName}"`:o?` \xB7 project ${o}`:"";return`${n}${r}`}async function ql(e,t,n){n&&Ah(e,t,n);try{let{projects:o}=await sn(process.cwd(),e);for(let r of Gl(e)){let s=$n(r);s&&Ah(e,s,o.find(i=>i.id===s)?.name)}}catch{}}function n$(e,t,n){let o=$n(e);if(!o||!t||o===t)return null;let r=n?`"${n}"`:t.slice(0,8)+"\u2026";return`\u26A0 You signed in to project ${e.projectName?`"${e.projectName}"`:o.slice(0,8)+"\u2026"}, but this repo's docs live in ${r}. Run /login again and pick ${r} (or /project to point this repo somewhere else).`}async function yi(e){let t=ns(process.cwd(),e.profile),n=t.connection;console.log(f(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=kn(process.cwd(),e.profile);o&&(console.log(H(`\u26A0 ${o.why} \u2014 and signing in does NOT change it (the environment comes from the profile, not the login).`)),console.log(H(` To move: ${o.cmd}${o.replacementProfile?"":", then /login"}`)));let r=await Xk(n,{manual:e.manual,promptForRedirect:g=>zk({message:g})},g=>console.log(ts(g))),s=Eh(t.name,r);Dh(s),await Vl(s,t.name,g=>console.log(f(g)));let i=$n(s),a=ns(process.cwd(),e.profile).project;i&&await ql(t.name,i,a.projectId===i?a.projectName:void 0);let l=Nh(t.name,i??void 0)??s;console.log(""),console.log(q(`\u2713 Logged in to "${t.name}" as ${wi(l)}`));let d=n$(l,a.projectId,a.projectName);if(d&&console.log(H(d)),console.log(f(` access token expires: ${s.expiresAt}`)),console.log(f(` refresh token: ${s.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{t$(process.cwd())?.profiles?.[t.name]&&(console.log(""),await Yo(process.cwd(),t.name))}catch{}}async function Vl(e,t,n){let r=jh(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(ns(process.cwd(),t).project.projectId)return;let i;try{let{projects:a}=await sn(process.cwd(),t);i=a.find(l=>l.id===r)?.name}catch{}e$(process.cwd(),t,{projectId:r,projectName:i}),n(` Project "${i??r}" written to profile "${t}".`)}catch{}}async function Ih(e){let t=ns(process.cwd(),e.profile),n=t.connection,o=Nh(t.name,t.project.projectId);if(!o){console.log(O(`Not logged in to Document360 (profile "${t.name}").`));let r=Gl(t.name).filter(s=>$n(s)&&$n(s)!==t.project.projectId);r.length>0&&console.log(f(`This repo's project needs its own sign-in. Signed in on this machine: ${r.map(s=>s.projectName??$n(s)).join(", ")}`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${Z(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${wi(o)}`),Zk(o))if(o.refreshToken)try{let r=Eh(t.name,await Qk(n,o.refreshToken));Dh(r),console.log(q(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(H(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(H("Session expired (no refresh token).")),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(f(` expires: ${o.expiresAt}`))}async function Lh(e){let t=ns(process.cwd(),e.profile),n=e.allProjects?void 0:t.project.projectId,o=t.project.projectName?`"${t.project.projectName}"`:`profile "${t.name}"`;if(Jk(t.name,n)){console.log(q(e.allProjects?`\u2713 Logged out of every Document360 project for profile "${t.name}".`:`\u2713 Logged out of ${o}.`));let r=Gl(t.name).filter(s=>$n(s)).length;r>0&&console.log(f(`Still signed in to ${r} other project${r===1?"":"s"} on this machine.`))}else console.log(f(`No Document360 session for ${o} \u2014 nothing to do.`))}re();import{readProjectConfig as Oh,writeProjectConfig as o$,resolveActiveProfile as r$,loadTokens as s$,isExpired as i$}from"document360-engine";function bi(e){let t=Oh(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(O("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?Z("\u25CF "):" ",s=o.production?H(" \u26A0 PRODUCTION"):"",i=o.connection.environment??"(inline)",a=s$(n,o.project?.projectId),l=a?i$(a)&&!a.refreshToken?H("expired"):f("logged in"):f("not logged in");console.log(`${r}${Z(n)} \u2192 ${i}${s} [${l}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function ki(e,t){let n=Oh(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(O(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,o$(n,e);let o=n.profiles[t].production?H(" \u26A0 PRODUCTION"):"";console.log(q(`\u2713 Default profile is now "${t}"${o}`))}function $i(e,t){try{let n=r$(e,t);console.log(""),console.log(`Profile ${Z(n.name)}${n.production?H(" \u26A0 PRODUCTION"):""}`),console.log(f(` api: ${n.connection.apiUrl}`)),console.log(f(` identity: ${n.connection.authorizationUrl}`)),console.log(f(` clientId: ${n.connection.clientId}`)),console.log(f(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(f(` project: ${n.project.projectId??"(set at login)"}`)),console.log(f(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(O(n.message)),process.exitCode=1}}re();import{existsSync as Fh,readdirSync as a$,readFileSync as l$,statSync as c$}from"node:fs";import{join as Uh}from"node:path";import{apiLogDir as u$}from"document360-engine";var d$=30,p$=12e3;function h$(e){if(!Fh(e))return{api:[],crash:[]};try{let t=a$(e);return{api:t.filter(n=>n.endsWith(".jsonl")).sort().reverse(),crash:t.filter(n=>/^crash-\d{4}-\d{2}-\d{2}\.log$/.test(n)).sort().reverse()}}catch{return{api:[],crash:[]}}}var f$=/·\s*(empty-turn|agent-subprocess|uncaught|unhandled)\s*===/i,m$=/·\s*FATAL\s*·/i,g$=e=>m$.test(e)||f$.test(e);function w$(e){let n=e.split(/\n(?==== \d{4}-\d{2}-\d{2}T)/).map(s=>s.trim()).filter(Boolean).filter(s=>s.startsWith("==="));if(n.length===0)return null;let o=[...n].reverse().find(g$),r=o??n[n.length-1];return{text:r,when:/^=== (\S+)/.exec(r)?.[1]??"",count:n.length,notable:!!o}}function y$(e,t){let n=t[0];if(!n)return null;try{return w$(l$(Uh(e,n),"utf8"))}catch{return null}}function _h(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}var Mh=(e,t)=>{try{return`${(c$(Uh(e,t)).size/1024).toFixed(1)} KB`}catch{return""}};function Yl(){let e=u$(),{api:t,crash:n}=h$(e),o=y$(e,n),r=[];if(o){let s=o.text.split(/\r?\n/),i=s.slice(0,d$);r.push(o.notable?me("\u2717",`The last thing that went wrong \u2014 ${_h(o.when)}:`):me("\u2139",`Nothing has failed. The most recent note d360-writer recorded \u2014 ${_h(o.when)}:`)),r.push("");for(let a of i)r.push(` ${a}`);s.length>i.length&&r.push(f(` \u2026${s.length-i.length} more line${s.length-i.length===1?"":"s"} \u2014 the whole thing is in ${n[0]}, and c copies all of it.`)),r.push(""),o.count>1&&r.push(f(` ${o.count} entries recorded today; this is the one worth reading.`)),o.notable&&r.push(f(" If this is not obviously your own doing, send it to the team \u2014 it names what failed.")),r.push("")}else n.length===0&&(r.push(me("\u2713","Nothing has failed \u2014 d360-writer has recorded no problems.")),r.push(""));if(r.push(`Logs live in ${Z(e)}`),!Fh(e)||t.length===0&&n.length===0)return r.push(f(" Nothing here yet \u2014 logs appear after the first Document360 call.")),{lines:r,copyText:null,notable:!1};if(n.length>0){r.push(""),r.push(`Problem logs ${f("(send these if something crashed or a run did nothing)")}:`);for(let s of n.slice(0,14))r.push(` ${O(s)} ${f(Mh(e,s))}`)}if(t.length>0){r.push(""),r.push("Document360 call logs:");for(let s of t.slice(0,14))r.push(` ${s} ${f(Mh(e,s))}`)}return r.push(""),r.push(f("Failed calls include what was sent and returned (sign-in details removed, 4 KB cap).")),r.push(f("Set D360_LOG_BODIES=1 to record successful calls too.")),{lines:r,copyText:o?o.text.slice(0,p$):null,notable:!!o?.notable}}async function Wh(){return Kl(),{kind:"continue"}}function Kl(){let{lines:e,copyText:t}=Yl();console.log("");for(let n of e)console.log(n);t&&console.log(f("Inside d360-writer, /logs offers to copy this for you.")),console.log("")}re();import{createSession as b$,resolveAuth as k$,findByName as $$,slugify as v$,touchSession as x$,upsertSession as R$,resolveActiveProfile as C$}from"document360-engine";async function Bh(e,t,n,o,r,s){let i=k$(n);i.kind==="none"&&(console.error(""),console.error(O("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${Z("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${Z("d360-writer --auth subscription")}`),process.exit(2)),i.kind==="subscription"&&console.error(f("Using your Claude subscription (no API key set)."));let a=null;try{a=C$(e,r)}catch(k){console.error(O(`Document360 profile error: ${k.message}`)),process.exit(2)}a.production&&(console.error(H(`\u26A0 Profile "${a.name}" is PRODUCTION.`)),s||(console.error(O("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(f(" --yes given \u2014 proceeding against production.")));let l;if(o){let k=$$(e,o);k||(console.error(O(`No saved session matches "${o}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),l=k.uuid,console.error(f(`Resuming "${k.name}"`))}let d=b$({cwd:e,resume:l,profileName:r,allowProdWrites:s===!0}),g=l??null,w=1;for await(let k of d.send(t))switch(k.type){case"session":if(!g){g=k.sessionId;let S=new Date().toISOString();R$({uuid:g,name:v$(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:S,updatedAt:S})}break;case"text":process.stdout.write(k.delta);break;case"tool":console.error(ve(` \u2699 ${k.name}`));break;case"result":w=k.ok?0:1,console.error(f(`(${k.inputTokens}\u2192${k.outputTokens} tokens`+(k.costUsd>0?`, $${k.costUsd<.01?k.costUsd.toFixed(4):k.costUsd.toFixed(2)}`:"")+")")),k.ok||console.error(O("agent finished with an error result"));break;case"error":console.error(""),console.error(O(`agent error: ${k.message}`)),process.exit(1)}g&&x$(g),process.stdout.write(`
300
- `),process.exit(w)}import{createInterface as yE}from"node:readline/promises";import{createSession as lp,resolveAuth as bE,getSession as kE,setTitle as $E,slugify as vE,touchSession as Yy,upsertSession as xE,generateTitle as RE,resolveActiveProfile as Ky,resolveModelSetting as CE,readProjectConfig as SE,readUserConfig as PE,resolveAndPersistAppType as TE,decodeJwtClaims as Gy,isExpired as AE,loadTokens as EE,isDirectiveMention as NE,stripDirectiveMention as DE,appendDirective as jE,reconcileUpgradeActions as IE,stampArticles as LE,snapshotArticles as OE,listArticleFiles as _E,applyStructureOrder as ME,orderSyncLine as FE,computeSyncStatus as UE}from"document360-engine";import{ENGINE_VERSION as T$}from"document360-engine";function Vt(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 vi(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 a of Vt(`${i+1}. ${s.feature}`,76))o.push(n(a));o.push(n());for(let a of Vt(s.why,73))o.push(n(` ${a}`));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}function xi(e){return[`\u26A0 ${e} screenshot${e===1?"":"s"} that hide${e===1?"s":""} sensitive areas ${e===1?"is":"are"} back to needing a check.`," A blacked-out area only covered the first matching spot on the screen \u2014 so on a list or a table, the",` rows below it were still readable. Blackouts now cover every match, and ${e===1?"that picture needs":"those pictures need"} a fresh look.`].join(`
301
- `)}var ut=[{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 twice exits"},{t:"dim",s:"tab runs the suggestion \xB7 1-9 pick from a list \xB7 c copies whatever was offered for copying"}]},{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",s:"Analyze the latest code changes, read the notes left by your coding agent, and update the documentation. Everything lands as a draft."},{t:"cmd",name:"/review --fix",s:"A senior editor reads every article and applies its fixes. Required before anything goes live \u2014 these were written by an AI."},{t:"cmd",name:"/review --blocked --fix",s:"The same editorial pass over only the articles publishing is blocked on \u2014 after a run that rewrote two of forty, this reads those two."},{t:"cmd",name:"/review --stale --fix",s:"The same pass over every article the current editor has not read yet \u2014 never reviewed, or reviewed before the editor last improved. Run it twice and the second run does nothing, so it is the safe way to catch a knowledge base up."},{t:"cmd",name:"/push --all",s:"Save the reviewed articles to Document360, as drafts."},{t:"cmd",name:"/publish --all",s:"Take those drafts live to your readers \u2014 it lists what will become visible and asks first."},{t:"dim",s:" (/catch-up --push runs the writing and the save back-to-back; going live stays a deliberate step)"},{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:"/comments",s:"The comments reviewers left on passages of your articles in the Document360 portal. You get a table \u2014 category, article, how many comments \u2014 and pick a number to read that article's comments in full (the highlighted passage beside what they said), then answer them or go back to the list. `a` answers everything. Each article is fixed, pushed to Document360 as an updated draft, and answered in the thread. Threads are left OPEN for the reviewer to close once they've checked the change; add --resolve to close the ones fully handled. --answered lists the ones already waiting on your reviewers; --full re-reads every article instead of only the ones that can have changed."},{t:"cmd",name:"/inbox",s:"Review and act on messages left by your coding agent."},{t:"cmd",name:"/ask <question>",s:"Ask your developers something the code cannot tell you: why a feature exists, when to use it, whether it can be undone. Costs nothing and does not stop your work."}]},{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:"/push",s:"Save the articles to Document360 as drafts. Requires an editorial review first \u2014 /review --fix."},{t:"cmd",name:"/push --preview <path>",s:"Show exactly what Document360 would receive for one article \u2014 details at the top and title removed, screenshots in place, links resolved. Sends nothing."},{t:"cmd",name:"/publish",s:"Take the drafts live to your readers, once they have been signed off."},{t:"cmd",name:"/status",s:"What stands between your work and your readers: which articles no editor has read, which break a blocking style rule, which would show placeholder text, and which are saved as drafts your readers cannot see yet. Each group names the one command that clears it. Costs nothing and calls nothing \u2014 run it before you publish, not after. --all shows every article gate by gate."},{t:"cmd",name:"/retire <path>",s:"Take an article off your readers: it stops being visible on Document360 and nothing offers to publish it again. Nothing is deleted \u2014 the article, its history and every reviewer comment stay, so a retirement is always reversible. Bare /retire lists what is worth retiring. /push puts one back."},{t:"cmd",name:"/terms",s:'Is your knowledge base calling the same thing by the same name? It reads every article and reports terms spelled more than one way, short names that might be an abbreviation of a longer one, and titles out of step with the rest of their kind. This is the consistency an editor reading three articles at a time structurally cannot see. Costs nothing. --approve "<term>" records your choice so every later run enforces it.'}]},{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 and takes the shots."},{t:"step",n:4,s:"The callouts are drawn on straight after, no browser needed. /screenshot annotate finishes any that were left, and re-draws after you reword a callout or change the marker style."},{t:"step",n:5,s:"Each finished picture is then checked automatically: D360-Writer looks at it and marks it \u2714 verified, or flags what is wrong and fixes the spec for you."},{t:"step",n:6,s:"Run /push --screenshots \u2014 it re-saves the articles with finished shots so the images embed on Document360. Put a category in front (/push 04-publishing --screenshots) to re-save only that one."},{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 annotate",s:"Draw the callouts on shots already taken (<id>, a path, or --all). No browser and no sign-in \u2014 it re-uses the pictures you have, so it takes about a second each. --force re-draws ones that are already finished."},{t:"cmd",name:"/screenshot verify",s:"Look at the finished 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 \u25C8 to verify \xB7 \u25CF to annotate \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. \u25CF to annotate means the browser has taken the shot but the callouts are not on it yet, so there is nothing to publish; \u25C8 to verify means the picture is finished and waiting to be looked at. It counts as done once it has been judged fit for the article."},{t:"gap"},{t:"sub",s:"When a shot does not produce a usable image"},{t:"text",s:"\u25CF to annotate means the shot was taken but the callouts were never drawn on \u2014 the browser work is already paid for, so /screenshot annotate finishes it in about a second."},{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. One sign-in per project, all kept \u2014 switching repos never signs you out of the others."},{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, grouped by the part of the job: progress + the next step (`--all` also shows replaced steps, `done` marks the next step finished)."},{t:"cmd",name:"/catch-up",s:"Do all pending work \u2192 drafts (--push then saves them to Document360)."},{t:"cmd",name:"/share",s:"Exchange work with your team: get your builder's latest, send yours (automatic; `off` to stop)."},{t:"cmd",name:"/push",s:"Save to Document360 as drafts (--all or a path). Needs /review --fix first."},{t:"cmd",name:"/publish",s:"Take the drafts live to your readers (--all or a path). Lists them and asks first."},{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 \u2014 one at a time, or all at once)."},{t:"cmd",name:"/comments",s:"Reviewer comments on your articles \u2014 a table by article; pick one to read it, then answer (--resolve also closes the threads)."},{t:"cmd",name:"/inbox",s:"Act on your coding agent's messages."},{t:"cmd",name:"/ask",s:"Ask your developers what the code cannot answer."},{t:"gap"},{t:"sub",s:"Quality \u2014 before you publish"},{t:"cmd",name:"/style-guide",s:"Choose the writing rules your docs are held to \u2014 the Microsoft or Google style guide, or just the house rules. Adopting one records what your articles already contain, so nothing you have written suddenly breaks. `keep` settles on the rules you already have, so the question stops being asked. `pull` brings your Document360 project's own style guide down so the writer works to it; `learn` reads what your reviewers keep asking for and turns the general parts into standing rules the writer follows from then on; `compile` turns mechanical statements into checks and tells you which parts only an editor can judge."},{t:"cmd",name:"/lint",s:"The machine pass: leaked internals, invented commands, stale facts, AI-tells, em dashes, callout shape. Costs nothing to run; --fix has the agent correct what it found, which is a real pass over every article that has an issue. --blocked narrows both to the errors that block publishing, leaving warnings and suggestions alone."},{t:"cmd",name:"/review",s:"The editor pass: a senior editor reads the articles against the house style guide and judges what no rule can. --fix applies the corrections, --blocked narrows to the articles publishing is blocked on, --stale to the ones the current editor has not read. Required before anything goes live."},{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:"/verbose",s:"Raw transcript: every tool call, path and full result (bare: toggle)."},{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 \u2014 and a real agent turn, so a setup that looks fine but cannot actually write anything is caught here rather than by an empty `/write`."},{t:"cmd",name:"/logs",s:"Shows the most recent problem d360-writer recorded, in full, and where the logs are kept. Run it whenever a command did nothing or something crashed: the reason is in there. Press `c` to copy it and send it to the team."},{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."}]}],Hh=24;function zl(e){let t=e.filter(n=>n.t==="cmd").map(n=>n.name.length);return t.length===0?Hh:Math.min(Hh,Math.max(...t))}function Ri(e,t,n,o){let r=" ".repeat(2+n+1),s=Math.max(24,o-r.length-2),i=Vt(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 S$(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=Ri(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(`
302
- `)}case"gap":return""}}function Gh(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 ut){n.push(`\u2500\u2500 ${o.label} \u2500\u2500`,"");let r=zl(o.rows);for(let s of o.rows)n.push(S$(s,r,100));n.push("")}return n.push("Tip: anything not starting with / goes to the agent."),n}function Xl(e,t){return Vt(e,Math.max(10,Math.max(20,t)-2))}function P$(e,t,n){let o=Math.max(20,n),r=s=>Math.max(1,Xl(s,o).length);switch(e.t){case"gap":return 1;case"cmd":{let s=Ri(e.name,e.s,t,o);return s.nameOwnLine?1+s.descLines.length:1+Math.max(0,s.descLines.length-1)}case"step":return r(`${e.n}. ${e.s}`);default:return r(e.s)}}function qh(e,t){let n=Math.min(Math.max(0,t.scroll),Math.max(0,e.length-1)),o=[],r=0;for(let s=n;s<e.length;s++){let i=P$(e[s],t.nameW,t.width);if(r+i>t.budget&&o.length>0)break;o.push(e[s]),r+=i}return{visible:o,above:n,below:e.length-n-o.length,start:n}}function Vh(e){let n=r=>Math.max(1,Math.ceil(r/Math.max(10,e.inner))),o=n(e.barWidth)+n(e.barWidth)+1+1+n(e.footerWidth)+7;return Math.max(3,Math.min(22,(e.rows||24)-o))}async function Ql(e=[],t){console.log("");let n=t?.version?{version:t.version,engineVersion:T$}:void 0;for(let o of Gh(n))console.log(o);return console.log(""),console.log("Reporting a problem? Run `/logs` \u2014 it shows the last problem and offers to copy it."),console.log(""),{kind:"continue"}}re();import{getSession as A$}from"document360-engine";async function Yh(e,t){let n=t.currentUuid(),o=n?A$(n):void 0;return console.log(o?f(`
299
+ `)?"":i;lf(t,`${o}${a}${s.join(i)}${i}`,"utf8")}async function lc(){let e=process.cwd(),t=hf(e);if(Zo(t)&&!await K$({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let n=wf(e)??uf(e),o=await ss({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await ss({message:"Capture directory (where document360-capture .spec.ts files live):",default:mf}),s=await ss({message:"Screenshot output directory:",default:gf}),i=await ss({message:"Default connection profile name:",default:"berlin"}),a=await ss({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),l={projectId:o,docsDir:ff,captureDir:r,outputDir:s,profiles:{[i]:{connection:{environment:a},production:!1}},defaultProfile:i,authoritativeSourceFiles:yf(e)},d=X$(e);d?.terminologyGlossary&&(l.terminologyGlossary=d.terminologyGlossary),pf(l,e),ac(e);let w=Qo(e);console.log(""),console.log(q(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${Z(`d360-writer login --profile ${i}`)} ${f("(sign in; project & workspace auto-selected)")}`),console.log("");for(let m of Jo(w))console.log(m);return console.log(""),console.log(`${f("Then ask:")} ${Z('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function wf(e){let t=Ai(e,"package.json");if(!Zo(t))return null;try{return JSON.parse(df(t,"utf8")).name??null}catch{return null}}function yf(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Zo(Ai(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Ai(e,n);Zo(o)&&!J$(o)&&t.push(n)}return t}function J$(e){try{return z$(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var cf,Ei=Zr(()=>{"use strict";re();xn();cf=[".sessions/","cache/"]});import{createRequire as pv}from"node:module";import{existsSync as hv,readFileSync as fv}from"node:fs";import{dirname as Af,join as Ef}from"node:path";function dt(){let e;try{e=mv.resolve("document360-capture/helpers")}catch{return null}let t=Af(e);for(let n=0;n<5&&!hv(Ef(t,"package.json"));n++)t=Af(t);try{let n=JSON.parse(fv(Ef(t,"package.json"),"utf8"));return n.name==="document360-capture"&&n.version?n.version:null}catch{return null}}var mv,er=Zr(()=>{"use strict";mv=pv(import.meta.url)});var Kg={};Sh(Kg,{doctorCommand:()=>Cs,renderDoctorChecks:()=>Yg,runDoctorChecks:()=>Vg});import{existsSync as sC}from"node:fs";import{d360GetAll as iC,getAccessToken as aC,isExpired as xa,loadProfileMap as lC,loadTokens as cC,listStoredSessions as uC,tokensProjectId as Zu,packageSkillsDir as qg,ENGINE_VERSION as dC,projectConfigPath as pC,readProjectConfig as hC,DEFAULT_DOCS_DIR as fC,fetchManifestSummary as mC,resolveActiveProfile as gC,classifyClaudeAuth as wC,CLAUDE_CODE_SETUP_HINT as Ra,resolveModelSetting as yC,probeModel as bC,probeAgentTurn as kC,stderrHeadline as $C,detectAppType as vC,playbookSkillName as xC,D360AuthError as RC,applyStructureOrder as CC}from"document360-engine";async function Vg(e,t){let n=[],o=dt();n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${dC}${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=wC();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. ${Ra}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:Ra});let i=yC(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 D=await bC(e,i.model??void 0);if(D.ok){n.push({level:"ok",label:`Model reachable \u2014 replied in ${(D.latencyMs/1e3).toFixed(1)}s`});let N=await kC(e,i.model??void 0);if(N.ok)n.push({level:"ok",label:`Agent turn works \u2014 ran with your skills and tools in ${(N.latencyMs/1e3).toFixed(1)}s`});else{let U=$C(N.stderr),O=/auth|sign.?in|login|credential|token|401|expired/i.test(`${N.error??""} ${N.stderr??""}`);if(n.push({level:"fail",label:N.timedOut?"Agent turn never finished \u2014 the model answers, but a real turn with your skills and tools hangs":O?"Agent turn failed \u2014 your Claude sign-in has expired, so every /write, /review and /catch-up will do nothing":`Agent turn produced nothing \u2014 the model answers, but a real turn with your skills and tools ${N.producedNothing?"ends instantly with no output":`fails: ${N.error}`}`,fix:(U?`Claude Code said: "${U}". `:"")+(O?`Sign in again, then re-run /doctor. ${Ra}`:"This is the failure behind an empty /write, /review or /catch-up. Run /logs for the whole thing \u2014 it offers to copy it so you can send it to the team.")}),O){let Q=n.find(z=>z.label.startsWith("Claude auth:"));Q&&(Q.level="warn",Q.label="Claude auth: a sign-in exists on this machine, but it is no longer valid",Q.fix=`Sign in again. ${Ra}`)}}}else D.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 ${D.error??"no output"} (a docs turn will end with 0 tokens / no output)`,fix:'Check sign-in, the selected model (/model), and network access to the Claude endpoint; confirm with: claude -p "say hi"'})}let a=hC(e);if(!a)return n.push({level:"fail",label:`No ${pC(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${a.projectId}`});let l=(a.docsDir??fC).replace(/\/+$/,"");n.push(a.mode==="engineer"?{level:"warn",label:"Mode: engineer \u2014 agent may modify any source file (dogfooding)",fix:'Remove "mode" from .d360-writer/config.json for the writer-mode boundary'}:{level:"ok",label:`Mode: writer \u2014 edits limited to ${l}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let d=a.authoritativeSourceFiles??[];n.push(d.length>0?{level:"ok",label:`Sources: docs grounded in ${d.length} path(s) (${d.slice(0,3).join(", ")}${d.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 w=a.appType??vC(e);if(w){let D=a.appType?"from config":"auto-detected",N=w==="web"||w==="cli";n.push({level:"ok",label:`Genre: ${w} (${D})${N?` \u2192 ${xC(w)} 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 m;try{m=gC(e),n.push({level:"ok",label:`Profile: ${m.name} (${m.connection.name})${m.production?" \u26A0 PRODUCTION":""}`})}catch(D){return n.push({level:"fail",label:`Profile config: ${D.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let $=cC(m.name,m.project.projectId),S=uC(m.name).filter(D=>{let N=Zu(D);return!!N&&N!==m.project.projectId&&!(xa(D)&&!D.refreshToken)}),R=m.project.projectName?`"${m.project.projectName}"`:"this project";$?xa($)&&!$.refreshToken?n.push({level:"fail",label:$.refreshRejectedAt?`Document360: session ended \u2014 Document360 refused to renew it (${new Date($.refreshRejectedAt).toLocaleString()})`:"Document360: session expired (no refresh token)",fix:"/login"}):xa($)?n.push({level:"ok",label:"Document360: logged in (access token expired \u2014 refreshes automatically on the next call)"}):n.push({level:"ok",label:`Document360: logged in to ${R} (until ${new Date($.expiresAt).toLocaleString()})`}):n.push(S.length>0?{level:"fail",label:`Document360: not signed in to ${R} \u2014 signed in to ${S.map(D=>D.projectName?`"${D.projectName}"`:(Zu(D)??"").slice(0,8)+"\u2026").join(", ")} instead`,fix:`Run: /login and pick ${R} \u2014 each project needs its own sign-in, and both are then kept`}:{level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${m.name})`}),S.length>0&&n.push({level:"ok",label:`Other Document360 projects signed in on this machine: ${S.map(D=>D.projectName?`"${D.projectName}"`:(Zu(D)??"").slice(0,8)+"\u2026").join(", ")} (kept \u2014 each repo uses its own)`}),n.push(m.project.workspaceId?{level:"ok",label:`Workspace: ${m.project.workspaceName??m.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let C=lC(e,m.name);C?C.projectId&&m.project.projectId&&C.projectId!==m.project.projectId?n.push({level:"fail",label:`Category map projectId (${C.projectId}) \u2260 profile projectId (${m.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(C.articles).length} articles, ${Object.keys(C.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${m.name}" (created on first /push)`}),n.push(sC(qg())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${qg()}`,fix:"Reinstall document360-writer (broken install)"});let A=Ut(e);if(A.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${Le})`}):A.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${A.completedVersion}, current is v${Le}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),$&&(!xa($)||$.refreshToken)){let D={profile:m.name,connection:m.connection,projectId:m.project.projectId,projectName:m.project.projectName};try{await aC(D);let U=await iC(D,"/v3/projects");n.push({level:"ok",label:`API reachable (${m.connection.apiUrl}) \u2014 ${U.length} project(s) visible`})}catch(U){n.push({level:"fail",label:`API call failed: ${U.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let N=C?.projectId??m.project.projectId;if(N&&m.project.workspaceId){try{let U=await mC(D,N,m.project.workspaceId);if(U){let O=(U.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Your Document360 project: reachable on ${m.connection.name} (${U.languages?.length??0} language${(U.languages?.length??0)===1?"":"s"}) \xB7 version ${O||"(none)"}`})}else n.push({level:"ok",label:`Workspace sync manifest: not live on ${m.connection.name} yet \u2014 sync uses the per-article path (nothing to do)`})}catch(U){U instanceof RC||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(U.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${m.project.projectName??N})`,fix:"Run /login and pick this repo's project \u2014 your token is scoped to another project"}):n.push({level:"warn",label:`Workspace sync manifest: probe failed (${U.message.slice(0,80)})`})}try{let U=await CC({cwd:e,profileName:m.name,dryRun:!0}),O=U.categoriesReordered+U.articlesReordered;if(U.skipped==="no category map")n.push({level:"ok",label:"Reading order: nothing to check yet (no articles published)"});else if(U.skipped)n.push({level:"warn",label:`Reading order: can't be checked (${U.skipped})`,fix:"Your article order on Document360 may not match your structure \u2014 /push syncs it once this resolves"});else if(U.unverified)n.push({level:"warn",label:`Reading order: ${U.unverified} of your articles aren't listed by Document360, so their order can't be set`,fix:"Usually means those articles are not live yet (the listing returns published articles). /publish takes them live, then /push re-syncs the order"});else if(O>0){let Q=[U.categoriesReordered>0?`${U.categoriesReordered} categor${U.categoriesReordered===1?"y":"ies"}`:"",U.articlesReordered>0?`${U.articlesReordered} article${U.articlesReordered===1?"":"s"}`:""].filter(Boolean);n.push({level:"warn",label:`Reading order: ${Q.join(" + ")} out of order on Document360`,fix:"Run /push \u2014 it re-syncs the order from your NN- folder/file prefixes"})}else n.push({level:"ok",label:"Reading order: Document360 matches your structure"});if(U.orphans?.length){let Q=U.orphans;n.push({level:"warn",label:`${Q.length} article${Q.length===1?"":"s"} on Document360 ${Q.length===1?"is":"are"} not in your docs folder: ${Q.slice(0,3).map(z=>z.path).join(", ")}${Q.length>3?`, +${Q.length-3} more`:""}`,fix:"/retire <path> takes one off your readers \xB7 /pull <path> brings one back into your docs folder \u2014 until you choose, it stays live and d360-writer leaves it alone"})}}catch(U){n.push({level:"warn",label:`Reading order: check failed (${U.message.slice(0,80)})`})}}}return n}function Yg(e){let t=[""];for(let r of e){let s=r.level==="ok"?q("\u2713"):r.level==="warn"?H("\u26A0"):_("\u2717");t.push(` ${s} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("fix:")} ${Z(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?q(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):_(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function Cs(e,t){console.log(f("Running checks\u2026"));for(let n of Yg(await Vg(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var Ca=Zr(()=>{"use strict";xn();re();er()});import{Command as l1}from"commander";import{createRequire as c1}from"node:module";import{AUTH_MODES as u1}from"document360-engine";import{input as t$}from"@inquirer/prompts";import{loginPkce as n$,getAccessToken as o$,toStoredTokens as r$,clearTokens as s$,decodeJwtClaims as jh,isExpired as i$,loadTokens as Vl,saveTokens as a$,listStoredSessions as Yl,tokensProjectId as $n,rememberSessionProject as Ih,resolveActiveProfile as os,setProfileProject as l$,readProjectConfig as c$}from"document360-engine";re();import{select as Fk}from"@inquirer/prompts";import{resolveActiveProfile as Uk,setProfileProject as Wk,resolveProjectId as Bk,listWorkspaces as Hk}from"document360-engine";async function ts(e,t){let n=Uk(e,t),o={profile:n.name,connection:n.connection,projectId:n.project.projectId,projectName:n.project.projectName},r=n.project.projectId??Bk(o);return{workspaces:await Hk(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var Th=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function Gl(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 fi(e,t,n,o,r){Wk(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function Ah(e,t,n){let o;try{o=await ts(e,n)}catch(s){return console.log(_(`Could not list workspaces: ${s.message}`)),1}let r=Gl(o.workspaces,t);return r?(fi(e,o.profile,o.projectId,r.id,r.name),console.log(q(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(_(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function Ko(e,t){let n;try{n=await ts(e,t)}catch(d){console.log(_(`Could not list workspaces: ${d.message}`));return}let{workspaces:o,projectId:r,profile:s,current:i}=n;if(o.length===0){console.log(f("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let d of o)console.log(` ${d.id===i?Z("\u25CF"):" "} ${Th(d)} ${f(d.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let a=await Fk({message:"Select the Document360 workspace for this repo:",choices:o.map(d=>({name:`${Th(d)}${d.id===i?" (current)":""}`,value:d.id}))}),l=o.find(d=>d.id===a);fi(e,s,r,a,l?.name),console.log(q(`\u2713 Workspace set to "${l?.name??a}" for profile "${s}".`))}re();import{select as Gk}from"@inquirer/prompts";import{resolveActiveProfile as qk,setProfileProject as Vk,listProjects as Yk}from"document360-engine";async function sn(e,t){let n=qk(e,t),o={profile:n.name,connection:n.connection};return{projects:await Yk(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var Eh=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function ql(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 mi(e,t,n,o){Vk(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function Nh(e,t,n){let o;try{o=await sn(e,n)}catch(s){return console.log(_(`Could not list projects: ${s.message}`)),1}let r=ql(o.projects,t);return r?(mi(e,o.profile,r.id,r.name),console.log(q(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log(_(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function gi(e,t){let n;try{n=await sn(e,t)}catch(l){console.log(_(`Could not list projects: ${l.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(f("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let l of o)console.log(` ${l.id===s?Z("\u25CF"):" "} ${Eh(l)} ${f(l.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let i=await Gk({message:"Select the Document360 project for this repo:",choices:o.map(l=>({name:`${Eh(l)}${l.id===s?" (current)":""}`,value:l.id}))}),a=o.find(l=>l.id===i);mi(e,r,i,a?.name),console.log(q(`\u2713 Project set to "${a?.name??i}" for profile "${r}". Next: pick a workspace.`))}re();import Kk from"picocolors";function zk(e=process.env){return e.FORCE_HYPERLINK==="0"||!Kk.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 Xk(e,t=e,n){return zk(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Qk=/https?:\/\/[^\s\x1b]+/g;function ns(e,t){return e.replace(Qk,n=>Xk(n,n,t))}import{readProjectConfig as Dh,sunsetEnvironment as Jk,resolveActiveProfile as Zk}from"document360-engine";function e$(e,t){let n=Dh(e);return Object.entries(n?.profiles??{}).find(([,o])=>(o.connection?.environment??"berlin")===t)?.[0]??null}function kn(e,t){try{if(!Dh(e))return null;let n=Zk(e,t),o=Jk(n.connection.name);if(!o)return null;let r=e$(e,o.replacement);return{name:o.name,replacement:o.replacement,why:o.why,replacementProfile:r,cmd:r?`/profile ${r}`:`/profile add ${o.replacement}`}}catch{return null}}function Lh(e){return{...jh(e.idToken)??{},...jh(e.accessToken)??{}}}function wi(e){let t=Lh(e),n=t.email??t.preferred_username??t.sub??"unknown",o=$n(e),r=e.projectName?` \xB7 project "${e.projectName}"`:o?` \xB7 project ${o}`:"";return`${n}${r}`}async function Kl(e,t,n){n&&Ih(e,t,n);try{let{projects:o}=await sn(process.cwd(),e);for(let r of Yl(e)){let s=$n(r);s&&Ih(e,s,o.find(i=>i.id===s)?.name)}}catch{}}function u$(e,t,n){let o=$n(e);if(!o||!t||o===t)return null;let r=n?`"${n}"`:t.slice(0,8)+"\u2026";return`\u26A0 You signed in to project ${e.projectName?`"${e.projectName}"`:o.slice(0,8)+"\u2026"}, but this repo's docs live in ${r}. Run /login again and pick ${r} (or /project to point this repo somewhere else).`}async function yi(e){let t=os(process.cwd(),e.profile),n=t.connection;console.log(f(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=kn(process.cwd(),e.profile);o&&(console.log(H(`\u26A0 ${o.why} \u2014 and signing in does NOT change it (the environment comes from the profile, not the login).`)),console.log(H(` To move: ${o.cmd}${o.replacementProfile?"":", then /login"}`)));let r=await n$(n,{manual:e.manual,promptForRedirect:w=>t$({message:w})},w=>console.log(ns(w))),s=r$(t.name,r);a$(s),await zl(s,t.name,w=>console.log(f(w)));let i=$n(s),a=os(process.cwd(),e.profile).project;i&&await Kl(t.name,i,a.projectId===i?a.projectName:void 0);let l=Vl(t.name,i??void 0)??s;console.log(""),console.log(q(`\u2713 Logged in to "${t.name}" as ${wi(l)}`));let d=u$(l,a.projectId,a.projectName);if(d&&console.log(H(d)),console.log(f(` access token expires: ${s.expiresAt}`)),console.log(f(` refresh token: ${s.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{c$(process.cwd())?.profiles?.[t.name]&&(console.log(""),await Ko(process.cwd(),t.name))}catch{}}async function zl(e,t,n){let r=Lh(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(os(process.cwd(),t).project.projectId)return;let i;try{let{projects:a}=await sn(process.cwd(),t);i=a.find(l=>l.id===r)?.name}catch{}l$(process.cwd(),t,{projectId:r,projectName:i}),n(` Project "${i??r}" written to profile "${t}".`)}catch{}}async function Oh(e){let t=os(process.cwd(),e.profile),n=t.connection,o=Vl(t.name,t.project.projectId);if(!o){console.log(_(`Not logged in to Document360 (profile "${t.name}").`));let r=Yl(t.name).filter(s=>$n(s)&&$n(s)!==t.project.projectId);r.length>0&&console.log(f(`This repo's project needs its own sign-in. Signed in on this machine: ${r.map(s=>s.projectName??$n(s)).join(", ")}`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${Z(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${wi(o)}`),i$(o))if(o.refreshToken)try{await o$({profile:t.name,connection:n,projectId:t.project.projectId,projectName:t.project.projectName});let r=Vl(t.name,t.project.projectId);console.log(q(`\u2713 Session refreshed${r?` \u2014 expires ${r.expiresAt}`:""}`))}catch(r){console.log(H(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(H("Session expired (no refresh token).")),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(f(` expires: ${o.expiresAt}`))}async function _h(e){let t=os(process.cwd(),e.profile),n=e.allProjects?void 0:t.project.projectId,o=t.project.projectName?`"${t.project.projectName}"`:`profile "${t.name}"`;if(s$(t.name,n)){console.log(q(e.allProjects?`\u2713 Logged out of every Document360 project for profile "${t.name}".`:`\u2713 Logged out of ${o}.`));let r=Yl(t.name).filter(s=>$n(s)).length;r>0&&console.log(f(`Still signed in to ${r} other project${r===1?"":"s"} on this machine.`))}else console.log(f(`No Document360 session for ${o} \u2014 nothing to do.`))}re();import{readProjectConfig as Mh,writeProjectConfig as d$,resolveActiveProfile as p$,loadTokens as h$,isExpired as f$}from"document360-engine";function bi(e){let t=Mh(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(_("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?Z("\u25CF "):" ",s=o.production?H(" \u26A0 PRODUCTION"):"",i=o.connection.environment??"(inline)",a=h$(n,o.project?.projectId),l=a?f$(a)&&!a.refreshToken?H("expired"):f("logged in"):f("not logged in");console.log(`${r}${Z(n)} \u2192 ${i}${s} [${l}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function ki(e,t){let n=Mh(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(_(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,d$(n,e);let o=n.profiles[t].production?H(" \u26A0 PRODUCTION"):"";console.log(q(`\u2713 Default profile is now "${t}"${o}`))}function $i(e,t){try{let n=p$(e,t);console.log(""),console.log(`Profile ${Z(n.name)}${n.production?H(" \u26A0 PRODUCTION"):""}`),console.log(f(` api: ${n.connection.apiUrl}`)),console.log(f(` identity: ${n.connection.authorizationUrl}`)),console.log(f(` clientId: ${n.connection.clientId}`)),console.log(f(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(f(` project: ${n.project.projectId??"(set at login)"}`)),console.log(f(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(_(n.message)),process.exitCode=1}}re();import{existsSync as Wh,readdirSync as m$,readFileSync as g$,statSync as w$}from"node:fs";import{join as Bh}from"node:path";import{apiLogDir as y$}from"document360-engine";var b$=30,k$=12e3;function $$(e){if(!Wh(e))return{api:[],crash:[]};try{let t=m$(e);return{api:t.filter(n=>n.endsWith(".jsonl")).sort().reverse(),crash:t.filter(n=>/^crash-\d{4}-\d{2}-\d{2}\.log$/.test(n)).sort().reverse()}}catch{return{api:[],crash:[]}}}var v$=/·\s*(empty-turn|agent-subprocess|uncaught|unhandled)\s*===/i,x$=/·\s*FATAL\s*·/i,R$=e=>x$.test(e)||v$.test(e);function C$(e){let n=e.split(/\n(?==== \d{4}-\d{2}-\d{2}T)/).map(s=>s.trim()).filter(Boolean).filter(s=>s.startsWith("==="));if(n.length===0)return null;let o=[...n].reverse().find(R$),r=o??n[n.length-1];return{text:r,when:/^=== (\S+)/.exec(r)?.[1]??"",count:n.length,notable:!!o}}function S$(e,t){let n=t[0];if(!n)return null;try{return C$(g$(Bh(e,n),"utf8"))}catch{return null}}function Fh(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}var Uh=(e,t)=>{try{return`${(w$(Bh(e,t)).size/1024).toFixed(1)} KB`}catch{return""}};function Xl(){let e=y$(),{api:t,crash:n}=$$(e),o=S$(e,n),r=[];if(o){let s=o.text.split(/\r?\n/),i=s.slice(0,b$);r.push(o.notable?ge("\u2717",`The last thing that went wrong \u2014 ${Fh(o.when)}:`):ge("\u2139",`Nothing has failed. The most recent note d360-writer recorded \u2014 ${Fh(o.when)}:`)),r.push("");for(let a of i)r.push(` ${a}`);s.length>i.length&&r.push(f(` \u2026${s.length-i.length} more line${s.length-i.length===1?"":"s"} \u2014 the whole thing is in ${n[0]}, and c copies all of it.`)),r.push(""),o.count>1&&r.push(f(` ${o.count} entries recorded today; this is the one worth reading.`)),o.notable&&r.push(f(" If this is not obviously your own doing, send it to the team \u2014 it names what failed.")),r.push("")}else n.length===0&&(r.push(ge("\u2713","Nothing has failed \u2014 d360-writer has recorded no problems.")),r.push(""));if(r.push(`Logs live in ${Z(e)}`),!Wh(e)||t.length===0&&n.length===0)return r.push(f(" Nothing here yet \u2014 logs appear after the first Document360 call.")),{lines:r,copyText:null,notable:!1};if(n.length>0){r.push(""),r.push(`Problem logs ${f("(send these if something crashed or a run did nothing)")}:`);for(let s of n.slice(0,14))r.push(` ${_(s)} ${f(Uh(e,s))}`)}if(t.length>0){r.push(""),r.push("Document360 call logs:");for(let s of t.slice(0,14))r.push(` ${s} ${f(Uh(e,s))}`)}return r.push(""),r.push(f("Failed calls include what was sent and returned (sign-in details removed, 4 KB cap).")),r.push(f("Set D360_LOG_BODIES=1 to record successful calls too.")),{lines:r,copyText:o?o.text.slice(0,k$):null,notable:!!o?.notable}}async function Hh(){return Ql(),{kind:"continue"}}function Ql(){let{lines:e,copyText:t}=Xl();console.log("");for(let n of e)console.log(n);t&&console.log(f("Inside d360-writer, /logs offers to copy this for you.")),console.log("")}re();import{createSession as P$,resolveAuth as T$,findByName as A$,slugify as E$,touchSession as N$,upsertSession as D$,resolveActiveProfile as j$}from"document360-engine";async function Gh(e,t,n,o,r,s){let i=T$(n);i.kind==="none"&&(console.error(""),console.error(_("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${Z("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${Z("d360-writer --auth subscription")}`),process.exit(2)),i.kind==="subscription"&&console.error(f("Using your Claude subscription (no API key set)."));let a=null;try{a=j$(e,r)}catch($){console.error(_(`Document360 profile error: ${$.message}`)),process.exit(2)}a.production&&(console.error(H(`\u26A0 Profile "${a.name}" is PRODUCTION.`)),s||(console.error(_("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(f(" --yes given \u2014 proceeding against production.")));let l;if(o){let $=A$(e,o);$||(console.error(_(`No saved session matches "${o}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),l=$.uuid,console.error(f(`Resuming "${$.name}"`))}let d=P$({cwd:e,resume:l,profileName:r,allowProdWrites:s===!0}),w=l??null,m=1;for await(let $ of d.send(t))switch($.type){case"session":if(!w){w=$.sessionId;let S=new Date().toISOString();D$({uuid:w,name:E$(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:S,updatedAt:S})}break;case"text":process.stdout.write($.delta);break;case"tool":console.error(Re(` \u2699 ${$.name}`));break;case"result":m=$.ok?0:1,console.error(f(`(${$.inputTokens}\u2192${$.outputTokens} tokens`+($.costUsd>0?`, $${$.costUsd<.01?$.costUsd.toFixed(4):$.costUsd.toFixed(2)}`:"")+")")),$.ok||console.error(_("agent finished with an error result"));break;case"error":console.error(""),console.error(_(`agent error: ${$.message}`)),process.exit(1)}w&&N$(w),process.stdout.write(`
300
+ `),process.exit(m)}import{createInterface as PE}from"node:readline/promises";import{createSession as hp,resolveAuth as TE,getSession as AE,setTitle as EE,slugify as NE,touchSession as Zy,upsertSession as DE,generateTitle as jE,resolveActiveProfile as eb,resolveModelSetting as IE,readProjectConfig as LE,readUserConfig as OE,resolveAndPersistAppType as _E,decodeJwtClaims as Xy,isExpired as ME,loadTokens as FE,isDirectiveMention as UE,stripDirectiveMention as WE,appendDirective as BE,reconcileUpgradeActions as HE,stampArticles as GE,snapshotArticles as qE,listArticleFiles as VE,applyStructureOrder as YE,orderSyncLine as KE,computeSyncStatus as zE}from"document360-engine";import{ENGINE_VERSION as O$}from"document360-engine";function Vt(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 vi(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 a of Vt(`${i+1}. ${s.feature}`,76))o.push(n(a));o.push(n());for(let a of Vt(s.why,73))o.push(n(` ${a}`));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}function xi(e){return[`\u26A0 ${e} screenshot${e===1?"":"s"} that hide${e===1?"s":""} sensitive areas ${e===1?"is":"are"} back to needing a check.`," A blacked-out area only covered the first matching spot on the screen \u2014 so on a list or a table, the",` rows below it were still readable. Blackouts now cover every match, and ${e===1?"that picture needs":"those pictures need"} a fresh look.`].join(`
301
+ `)}var ut=[{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 twice exits"},{t:"dim",s:"tab runs the suggestion \xB7 1-9 pick from a list \xB7 c copies whatever was offered for copying"}]},{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",s:"Analyze the latest code changes, read the notes left by your coding agent, and update the documentation. Everything lands as a draft."},{t:"cmd",name:"/review --fix",s:"A senior editor reads every article and applies its fixes. Required before anything goes live \u2014 these were written by an AI."},{t:"cmd",name:"/review --blocked --fix",s:"The same editorial pass over only the articles publishing is blocked on \u2014 after a run that rewrote two of forty, this reads those two."},{t:"cmd",name:"/review --stale --fix",s:"The same pass over every article the current editor has not read yet \u2014 never reviewed, or reviewed before the editor last improved. Run it twice and the second run does nothing, so it is the safe way to catch a knowledge base up."},{t:"cmd",name:"/push --all",s:"Save the reviewed articles to Document360, as drafts."},{t:"cmd",name:"/publish --all",s:"Take those drafts live to your readers \u2014 it lists what will become visible and asks first."},{t:"dim",s:" (/catch-up --push runs the writing and the save back-to-back; going live stays a deliberate step)"},{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:"/comments",s:"The comments reviewers left on passages of your articles in the Document360 portal. You get a table \u2014 category, article, how many comments \u2014 and pick a number to read that article's comments in full (the highlighted passage beside what they said), then answer them or go back to the list. `a` answers everything. Each article is fixed, pushed to Document360 as an updated draft, and answered in the thread. Threads are left OPEN for the reviewer to close once they've checked the change; add --resolve to close the ones fully handled. --answered lists the ones already waiting on your reviewers; --full re-reads every article instead of only the ones that can have changed."},{t:"cmd",name:"/inbox",s:"Review and act on messages left by your coding agent."},{t:"cmd",name:"/ask <question>",s:"Ask your developers something the code cannot tell you: why a feature exists, when to use it, whether it can be undone. Costs nothing and does not stop your work."}]},{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:"/push",s:"Save the articles to Document360 as drafts. Requires an editorial review first \u2014 /review --fix."},{t:"cmd",name:"/push --preview <path>",s:"Show exactly what Document360 would receive for one article \u2014 details at the top and title removed, screenshots in place, links resolved. Sends nothing."},{t:"cmd",name:"/publish",s:"Take the drafts live to your readers, once they have been signed off."},{t:"cmd",name:"/status",s:"What stands between your work and your readers: which articles no editor has read, which break a blocking style rule, which would show placeholder text, and which are saved as drafts your readers cannot see yet. Each group names the one command that clears it. Costs nothing and calls nothing \u2014 run it before you publish, not after. --all shows every article gate by gate."},{t:"cmd",name:"/retire <path>",s:"Take an article off your readers: it stops being visible on Document360 and nothing offers to publish it again. Nothing is deleted \u2014 the article, its history and every reviewer comment stay, so a retirement is always reversible. Bare /retire lists what is worth retiring. /push puts one back."},{t:"cmd",name:"/terms",s:'Is your knowledge base calling the same thing by the same name? It reads every article and reports terms spelled more than one way, short names that might be an abbreviation of a longer one, and titles out of step with the rest of their kind. This is the consistency an editor reading three articles at a time structurally cannot see. Costs nothing. --approve "<term>" records your choice so every later run enforces it.'}]},{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 and takes the shots."},{t:"step",n:4,s:"The callouts are drawn on straight after, no browser needed. /screenshot annotate finishes any that were left, and re-draws after you reword a callout or change the marker style."},{t:"step",n:5,s:"Each finished picture is then checked automatically: D360-Writer looks at it and marks it \u2714 verified, or flags what is wrong and fixes the spec for you."},{t:"step",n:6,s:"Run /push --screenshots \u2014 it re-saves the articles with finished shots so the images embed on Document360. Put a category in front (/push 04-publishing --screenshots) to re-save only that one."},{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 annotate",s:"Draw the callouts on shots already taken (<id>, a path, or --all). No browser and no sign-in \u2014 it re-uses the pictures you have, so it takes about a second each. --force re-draws ones that are already finished."},{t:"cmd",name:"/screenshot verify",s:"Look at the finished 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 \u25C8 to verify \xB7 \u25CF to annotate \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. \u25CF to annotate means the browser has taken the shot but the callouts are not on it yet, so there is nothing to publish; \u25C8 to verify means the picture is finished and waiting to be looked at. It counts as done once it has been judged fit for the article."},{t:"gap"},{t:"sub",s:"When a shot does not produce a usable image"},{t:"text",s:"\u25CF to annotate means the shot was taken but the callouts were never drawn on \u2014 the browser work is already paid for, so /screenshot annotate finishes it in about a second."},{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. One sign-in per project, all kept \u2014 switching repos never signs you out of the others."},{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, grouped by the part of the job: progress + the next step (`--all` also shows replaced steps, `done` marks the next step finished)."},{t:"cmd",name:"/catch-up",s:"Do all pending work \u2192 drafts (--push then saves them to Document360)."},{t:"cmd",name:"/share",s:"Exchange work with your team: get your builder's latest, send yours (automatic; `off` to stop)."},{t:"cmd",name:"/push",s:"Save to Document360 as drafts (--all or a path). Needs /review --fix first."},{t:"cmd",name:"/publish",s:"Take the drafts live to your readers (--all or a path). Lists them and asks first."},{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 \u2014 one at a time, or all at once)."},{t:"cmd",name:"/comments",s:"Reviewer comments on your articles \u2014 a table by article; pick one to read it, then answer (--resolve also closes the threads)."},{t:"cmd",name:"/inbox",s:"Act on your coding agent's messages."},{t:"cmd",name:"/ask",s:"Ask your developers what the code cannot answer."},{t:"gap"},{t:"sub",s:"Quality \u2014 before you publish"},{t:"cmd",name:"/style-guide",s:"Choose the writing rules your docs are held to \u2014 the Microsoft or Google style guide, or just the house rules. Adopting one records what your articles already contain, so nothing you have written suddenly breaks. `keep` settles on the rules you already have, so the question stops being asked. `pull` brings your Document360 project's own style guide down so the writer works to it; `learn` reads what your reviewers keep asking for and turns the general parts into standing rules the writer follows from then on; `compile` turns mechanical statements into checks and tells you which parts only an editor can judge."},{t:"cmd",name:"/lint",s:"The machine pass: leaked internals, invented commands, stale facts, AI-tells, em dashes, callout shape. Costs nothing to run; --fix has the agent correct what it found, which is a real pass over every article that has an issue. --blocked narrows both to the errors that block publishing, leaving warnings and suggestions alone."},{t:"cmd",name:"/review",s:"The editor pass: a senior editor reads the articles against the house style guide and judges what no rule can. --fix applies the corrections, --blocked narrows to the articles publishing is blocked on, --stale to the ones the current editor has not read. Required before anything goes live."},{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:"/verbose",s:"Raw transcript: every tool call, path and full result (bare: toggle)."},{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 \u2014 and a real agent turn, so a setup that looks fine but cannot actually write anything is caught here rather than by an empty `/write`."},{t:"cmd",name:"/logs",s:"Shows the most recent problem d360-writer recorded, in full, and where the logs are kept. Run it whenever a command did nothing or something crashed: the reason is in there. Press `c` to copy it and send it to the team."},{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."}]}],qh=24;function Jl(e){let t=e.filter(n=>n.t==="cmd").map(n=>n.name.length);return t.length===0?qh:Math.min(qh,Math.max(...t))}function Ri(e,t,n,o){let r=" ".repeat(2+n+1),s=Math.max(24,o-r.length-2),i=Vt(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 I$(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=Ri(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(`
302
+ `)}case"gap":return""}}function Vh(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 ut){n.push(`\u2500\u2500 ${o.label} \u2500\u2500`,"");let r=Jl(o.rows);for(let s of o.rows)n.push(I$(s,r,100));n.push("")}return n.push("Tip: anything not starting with / goes to the agent."),n}function Zl(e,t){return Vt(e,Math.max(10,Math.max(20,t)-2))}function L$(e,t,n){let o=Math.max(20,n),r=s=>Math.max(1,Zl(s,o).length);switch(e.t){case"gap":return 1;case"cmd":{let s=Ri(e.name,e.s,t,o);return s.nameOwnLine?1+s.descLines.length:1+Math.max(0,s.descLines.length-1)}case"step":return r(`${e.n}. ${e.s}`);default:return r(e.s)}}function Yh(e,t){let n=Math.min(Math.max(0,t.scroll),Math.max(0,e.length-1)),o=[],r=0;for(let s=n;s<e.length;s++){let i=L$(e[s],t.nameW,t.width);if(r+i>t.budget&&o.length>0)break;o.push(e[s]),r+=i}return{visible:o,above:n,below:e.length-n-o.length,start:n}}function Kh(e){let n=r=>Math.max(1,Math.ceil(r/Math.max(10,e.inner))),o=n(e.barWidth)+n(e.barWidth)+1+1+n(e.footerWidth)+7;return Math.max(3,Math.min(22,(e.rows||24)-o))}async function ec(e=[],t){console.log("");let n=t?.version?{version:t.version,engineVersion:O$}:void 0;for(let o of Vh(n))console.log(o);return console.log(""),console.log("Reporting a problem? Run `/logs` \u2014 it shows the last problem and offers to copy it."),console.log(""),{kind:"continue"}}re();import{getSession as _$}from"document360-engine";async function zh(e,t){let n=t.currentUuid(),o=n?_$(n):void 0;return console.log(o?f(`
303
303
  (conversation reset \u2014 "${o.name}" is still available via /resume)
304
304
  `):f(`
305
305
  (conversation reset \u2014 agent will start fresh on the next prompt)
306
- `)),{kind:"clear"}}async function Jl(){return{kind:"exit"}}Ei();re();import{readMcpConfig as ic,writeMcpConfig as yf}from"document360-engine";async function Ni(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(q$(),{kind:"continue"}):t==="add"?(V$(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(Y$(e.slice(1)),{kind:"continue"}):(console.log(O(`Unknown /mcp subcommand: ${t}`)),console.log(f("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function q$(){let e=ic(),t=Object.keys(e.servers);if(t.length===0){console.log(f(`
306
+ `)),{kind:"clear"}}async function tc(){return{kind:"exit"}}Ei();re();import{readMcpConfig as cc,writeMcpConfig as kf}from"document360-engine";async function Ni(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(Z$(),{kind:"continue"}):t==="add"?(ev(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(tv(e.slice(1)),{kind:"continue"}):(console.log(_(`Unknown /mcp subcommand: ${t}`)),console.log(f("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function Z$(){let e=cc(),t=Object.keys(e.servers);if(t.length===0){console.log(f(`
307
307
  No MCP servers registered. Add one with /mcp add <name> <type> <ref>
308
- `));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(` ${Z(n)} ${f("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?f(` [headers: ${r.join(", ")}]`):"";console.log(` ${Z(n)} ${f(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function V$(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(O("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(O(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=ic(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let i={};for(let a=1;a<o.length;a++)if(o[a]==="-H"||o[a]==="--header"){let l=o[++a],d=l?.match(/^([^:=]+)[:=](.+)$/);if(!d){console.log(O(`-H expects key:value (no spaces). Got: ${l??"(nothing)"}`));return}i[d[1].trim()]=d[2].trim()}else{console.log(O(`Unexpected argument: ${o[a]}. 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,yf(r),console.log(""),console.log(q(`\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(f(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function Y$(e){let t=e[0];if(!t){console.log(O("Usage: /mcp remove <name>"));return}let n=ic();if(!n.servers[t]){console.log(O(`No server named "${t}".`));return}delete n.servers[t],yf(n),console.log(q(`\u2713 Removed "${t}".`)),console.log(f(" Run /clear to drop it from the current session immediately."))}re();import{readFileSync as C0}from"node:fs";import{join as S0}from"node:path";import{select as P0}from"@inquirer/prompts";import{computeSyncStatus as Qi,planPartitions as T0,relatedArticlePaths as A0,loadProfileMap as km,draftPendingPaths as E0,resolveActiveProfile as Lc,unreviewedPaths as N0,styleErrorPaths as $m,publishGateVerdict as D0,publishGateLines as j0,pushArticles as I0,pushArticle as L0,PUSH_POOL_SIZE as O0,SKIP_STYLE_FLAG as _0,listArticleFiles as vm,ensureFeedbackChannel as M0,FEEDBACK_CATEGORY_NAME as ym,resolveCrossLinks as F0,applyStructureOrder as xm,orderSyncLine as Rm,applyRelatedArticles as Cm,relatedSyncLine as Sm}from"document360-engine";import{readFileSync as K$}from"node:fs";import{resolve as z$}from"node:path";import{prettyFolderName as bf}from"document360-engine";var Rn=bf;function Di(e){return e.replace(/\\/g,"/").split("/").slice(0,-1).join("/")}function ss(e){let t=e.replace(/\\/g,"/").split("/").pop()??e;return bf(t.replace(/\.md$/i,""))}function ji(e,t){try{return/^#\s+(.+)$/m.exec(K$(z$(e,t),"utf8"))?.[1]?.trim()??null}catch{return null}}import{resolveActiveProfile as X$,loadTokens as Q$,isExpired as kf,listStoredSessions as J$,tokensProjectId as lc}from"document360-engine";function Z$(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function ac(e,t){return t?`"${t}"`:e?Z$(e):"this project"}function ev(e,t){return t?J$(e).filter(n=>{let o=lc(n);return!!o&&o!==t&&!(kf(n)&&!n.refreshToken)}):[]}function qe(e,t){try{let n=X$(e,t),o=n.project.projectId,r=ac(o,n.project.projectName),s=Q$(n.name,o);if(!s){let a=ev(n.name,o);return a.length>0?{ok:!1,reason:`You're signed in to Document360 project ${a.map(d=>ac(lc(d)??void 0,d.projectName)).join(", ")}, and this repo's docs live in ${r}. A sign-in covers one project, so ${r} needs its own \u2014 run /login and pick it. Both stay signed in after that, so switching between repos won't ask again.`}:{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`}}if(kf(s)&&!s.refreshToken)return{ok:!1,reason:`Your Document360 session for ${r} expired. Run /login.`};let i=lc(s);return o&&i&&i!==o?{ok:!1,reason:`Your Document360 session is signed into a different project than this repo's ${r} (the session is for ${ac(i,s.projectName)}). Run /login and pick ${r}.`}:{ok:!0}}catch{return{ok:!0}}}import{existsSync as Ff,readFileSync as vc}from"node:fs";import{isAbsolute as Mi,join as Fi,resolve as Ui}from"node:path";import I from"picocolors";import Oi from"string-width";import{readProjectConfig as Sn,screenshotPlaceholderIds as Uf,screenshotMarkerProblemsInDocs as Rv,DEFAULT_CAPTURE_DIR as Wi,DEFAULT_OUTPUT_DIR as xc,DEFAULT_DOCS_DIR as Rc,resolveOutputDir as Wf,migrateShotLayout as Cv,reviewIsCurrent as Sv,anchorPresent as Pv,annotationCurrent as Tv,captureLanded as Av,shotArtifacts as Ev,RAW_SUBDIR as Nv,ANNOTATED_SUBDIR as Dv}from"document360-engine";import{createHash as cc}from"node:crypto";import{readFileSync as vf,writeFileSync as tv}from"node:fs";import{join as nv}from"node:path";import{captureStatePath as xf}from"document360-engine";var $f={version:1,shots:{}};function ov(e){return e.replace(/^/,"").replace(/\r\n?/g,`
308
+ `));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(` ${Z(n)} ${f("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?f(` [headers: ${r.join(", ")}]`):"";console.log(` ${Z(n)} ${f(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function ev(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(_("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(_(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=cc(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let i={};for(let a=1;a<o.length;a++)if(o[a]==="-H"||o[a]==="--header"){let l=o[++a],d=l?.match(/^([^:=]+)[:=](.+)$/);if(!d){console.log(_(`-H expects key:value (no spaces). Got: ${l??"(nothing)"}`));return}i[d[1].trim()]=d[2].trim()}else{console.log(_(`Unexpected argument: ${o[a]}. 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,kf(r),console.log(""),console.log(q(`\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(f(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function tv(e){let t=e[0];if(!t){console.log(_("Usage: /mcp remove <name>"));return}let n=cc();if(!n.servers[t]){console.log(_(`No server named "${t}".`));return}delete n.servers[t],kf(n),console.log(q(`\u2713 Removed "${t}".`)),console.log(f(" Run /clear to drop it from the current session immediately."))}re();import{readFileSync as N0}from"node:fs";import{join as D0}from"node:path";import{select as j0}from"@inquirer/prompts";import{computeSyncStatus as Ji,planPartitions as I0,relatedArticlePaths as L0,loadProfileMap as Rm,draftPendingPaths as O0,resolveActiveProfile as Uc,unreviewedPaths as _0,styleErrorPaths as Cm,publishGateVerdict as M0,publishGateLines as F0,pushArticles as U0,pushArticle as W0,PUSH_POOL_SIZE as B0,SKIP_STYLE_FLAG as H0,listArticleFiles as Sm,docsRootOf as G0,ensureFeedbackChannel as q0,FEEDBACK_CATEGORY_NAME as $m,resolveCrossLinks as V0,applyStructureOrder as Pm,orderSyncLine as Tm,applyRelatedArticles as Am,relatedSyncLine as Em}from"document360-engine";import{readFileSync as nv}from"node:fs";import{resolve as ov}from"node:path";import{prettyFolderName as $f}from"document360-engine";var Rn=$f;function Di(e){return e.replace(/\\/g,"/").split("/").slice(0,-1).join("/")}function is(e){let t=e.replace(/\\/g,"/").split("/").pop()??e;return $f(t.replace(/\.md$/i,""))}function ji(e,t){try{return/^#\s+(.+)$/m.exec(nv(ov(e,t),"utf8"))?.[1]?.trim()??null}catch{return null}}import{resolveActiveProfile as vf,loadTokens as xf,isExpired as pc,listStoredSessions as rv,tokensProjectId as dc}from"document360-engine";function Ii(e,t){try{let n=vf(e,t),o=xf(n.name,n.project.projectId);return!o||pc(o)?!1:He(e,t).ok}catch{return!1}}function sv(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function uc(e,t){return t?`"${t}"`:e?sv(e):"this project"}function iv(e,t){return t?rv(e).filter(n=>{let o=dc(n);return!!o&&o!==t&&!(pc(n)&&!n.refreshToken)}):[]}function He(e,t){try{let n=vf(e,t),o=n.project.projectId,r=uc(o,n.project.projectName),s=xf(n.name,o);if(!s){let a=iv(n.name,o);return a.length>0?{ok:!1,reason:`You're signed in to Document360 project ${a.map(d=>uc(dc(d)??void 0,d.projectName)).join(", ")}, and this repo's docs live in ${r}. A sign-in covers one project, so ${r} needs its own \u2014 run /login and pick it. Both stay signed in after that, so switching between repos won't ask again.`}:{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`}}if(pc(s)&&!s.refreshToken)return{ok:!1,reason:`Your Document360 session for ${r} expired. Run /login.`};let i=dc(s);return o&&i&&i!==o?{ok:!1,reason:`Your Document360 session is signed into a different project than this repo's ${r} (the session is for ${uc(i,s.projectName)}). Run /login and pick ${r}.`}:{ok:!0}}catch{return{ok:!0}}}import{existsSync as Bf,readFileSync as Sc}from"node:fs";import{isAbsolute as Fi,join as Ui,resolve as Wi}from"node:path";import L from"picocolors";import _i from"string-width";import{readProjectConfig as Sn,screenshotPlaceholderIds as Hf,screenshotMarkerProblemsInDocs as Ev,DEFAULT_CAPTURE_DIR as Bi,DEFAULT_OUTPUT_DIR as Pc,DEFAULT_DOCS_DIR as Tc,resolveOutputDir as Gf,migrateShotLayout as Nv,reviewIsCurrent as Dv,anchorPresent as jv,annotationCurrent as Iv,captureLanded as Lv,shotArtifacts as Ov,RAW_SUBDIR as _v,ANNOTATED_SUBDIR as Mv}from"document360-engine";import{createHash as hc}from"node:crypto";import{readFileSync as Cf,writeFileSync as av}from"node:fs";import{join as lv}from"node:path";import{captureStatePath as Sf}from"document360-engine";var Rf={version:1,shots:{}};function cv(e){return e.replace(/^/,"").replace(/\r\n?/g,`
309
309
  `).replace(/\n+$/,`
310
- `)}function Rf(e){return cc("sha1").update(ov(e)).digest("hex").slice(0,12)}function rv(e){return cc("sha1").update(e).digest("hex").slice(0,12)}function Ii(e){try{let t=JSON.parse(vf(nv(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(a=>`${a}=${s[a]}`).join("&");return cc("sha1").update(`${o}|${r?.connection?.startUrl??""}|${i}`).digest("hex").slice(0,12)}catch{return null}}function ln(e){try{let t=JSON.parse(vf(xf(e),"utf8").replace(/^/,""));return!t||typeof t!="object"||t.version!==1||!t.shots?{...$f,shots:{}}:{version:1,shots:t.shots}}catch{return{...$f,shots:{}}}}function sv(e,t){tv(xf(e),`${JSON.stringify(t,null,2)}
311
- `,"utf8")}function uc(e){return e&&/data-testid|\btest-?id\b|has(?:n't| not) landed/i.test(e)?"testid":"data"}function Li(e,t,n){if(t.length===0)return;let o=ln(e),r=Ii(e);for(let s of t){let i=s.specSource?Rf(s.specSource):void 0;o.shots[s.id]={outcome:s.outcome,at:n,...s.reason?{reason:s.reason}:{},...s.outcome==="skipped"?{blockedBy:uc(s.reason)}:{},...i?{specHash:i}:{},...r?{envHash:r}:{}}}sv(e,o)}function dc(e,t,n,o){let r=e.shots[t];return!r||n===null||!r.specHash||r.specHash!==Rf(n)&&r.specHash!==rv(n)||o&&r.envHash&&r.envHash!==o?null:r}function Cf(e){let t=ln(e).shots;return Object.keys(t).filter(n=>t[n].outcome==="failed").sort()}function pc(e,t,n){let o=dc(ln(e),t,n,Ii(e));return!o||o.outcome==="captured"||!o.reason?null:{outcome:o.outcome,reason:o.reason}}Zo();import{existsSync as uv,readFileSync as Af,readdirSync as Ef,writeFileSync as dv}from"node:fs";import{isAbsolute as pv,join as Nf,resolve as hv}from"node:path";import{readProjectConfig as fv,DEFAULT_CAPTURE_DIR as mv}from"document360-engine";var Tf="0.2.25";function er(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 gv=/^([ \t]*)await\s+([^\n;]+?)\.screenshot\(\{\s*path:\s*PLACEHOLDER\.saveTo\s*(?:,\s*fullPage:\s*(?:true|false)\s*)?,?\s*\}\)\s*;?[ \t]*$/m,wv=/^[ \t]*await\s+dumpAnnotations\(\s*page\s*,\s*PLACEHOLDER\s*\)\s*;?[ \t]*\r?\n?/m,Df="(?:'([^']+)'|\"([^\"]+)\"|`([^`]+)`)",yv=new RegExp(`^page\\s*\\.\\s*locator\\(\\s*${Df}\\s*\\)$`),jf=e=>e[1]??e[2]??e[3]??null,bv=/^[A-Za-z_$][\w$]*$/;function kv(e,t){let o=new RegExp(`\\bconst\\s+${t}\\s*=\\s*page\\s*\\.\\s*locator\\(\\s*${Df}\\s*\\)\\s*;`).exec(e);return o?jf(o):null}function $v(e,t){let n=t.trim();if(n==="page")return null;let o=yv.exec(n);if(o){let r=jf(o);return r?{selector:r}:{unresolved:!0}}if(bv.test(n)){let r=kv(e,n);return r?{selector:r}:{unresolved:!0}}return{unresolved:!0}}function If(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=gv.exec(e);if(!n)return null;let[o,r="",s=""]=n,i=$v(e,s);if(i===null)return null;if("unresolved"in i)return{unresolved:s.trim()};let a=/^([ \t]*)saveTo:\s*.+,[ \t]*$/m.exec(e);if(!a)return null;let l=i.selector.includes("'")?'"':"'",d=e.replace(a[0],`${a[0]}
312
- ${a[1]??" "}clipTo: ${l}${i.selector}${l},`);return d=d.replace(o,`${r}await captureShot(page, PLACEHOLDER);`),d=d.replace(wv,""),d=d.replace(/\bdumpAnnotations\b(?=[^\n]*from 'document360-capture\/helpers')/,"captureShot"),/from 'document360-capture\/helpers'/.test(d)&&!/\bcaptureShot\b[^\n]*from 'document360-capture\/helpers'/.test(d)&&(d=d.replace(/import \{([^}]*)\} from 'document360-capture\/helpers'/,(g,w)=>`import {${w.replace(/\s*$/,"")}, captureShot } from 'document360-capture/helpers'`)),{next:d,selector:i.selector}}function vv(e){try{return Ef(e).filter(t=>t.endsWith(".spec.ts")).some(t=>{try{let n=If(Af(Nf(e,t),"utf8"));return n!==null&&!("unresolved"in n)}catch{return!1}})}catch{return!1}}function xv(e){let t=fv(e)?.captureDir??mv;return pv(t)?t:hv(e,t)}function Lf(e,t){let n={migrated:[],skipped:[]},o=xv(e);if(!uv(o))return n;let r=t?.captureVersion===void 0?dt():t.captureVersion;if(!er(r,Tf))return vv(o)?{...n,heldBackForCapture:{installed:r,required:Tf}}:n;let s;try{s=Ef(o).filter(i=>i.endsWith(".spec.ts"))}catch{return n}for(let i of s.sort()){let a=i.slice(0,-8),l=Nf(o,i);try{let d=Af(l,"utf8"),g=If(d);if(g===null)continue;if("unresolved"in g){n.skipped.push({id:a,receiver:g.unresolved});continue}dv(l,g.next,"utf8"),n.migrated.push(a)}catch{}}return n}function Of(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.
310
+ `)}function Pf(e){return hc("sha1").update(cv(e)).digest("hex").slice(0,12)}function uv(e){return hc("sha1").update(e).digest("hex").slice(0,12)}function Li(e){try{let t=JSON.parse(Cf(lv(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(a=>`${a}=${s[a]}`).join("&");return hc("sha1").update(`${o}|${r?.connection?.startUrl??""}|${i}`).digest("hex").slice(0,12)}catch{return null}}function ln(e){try{let t=JSON.parse(Cf(Sf(e),"utf8").replace(/^/,""));return!t||typeof t!="object"||t.version!==1||!t.shots?{...Rf,shots:{}}:{version:1,shots:t.shots}}catch{return{...Rf,shots:{}}}}function dv(e,t){av(Sf(e),`${JSON.stringify(t,null,2)}
311
+ `,"utf8")}function fc(e){return e&&/data-testid|\btest-?id\b|has(?:n't| not) landed/i.test(e)?"testid":"data"}function Oi(e,t,n){if(t.length===0)return;let o=ln(e),r=Li(e);for(let s of t){let i=s.specSource?Pf(s.specSource):void 0;o.shots[s.id]={outcome:s.outcome,at:n,...s.reason?{reason:s.reason}:{},...s.outcome==="skipped"?{blockedBy:fc(s.reason)}:{},...i?{specHash:i}:{},...r?{envHash:r}:{}}}dv(e,o)}function mc(e,t,n,o){let r=e.shots[t];return!r||n===null||!r.specHash||r.specHash!==Pf(n)&&r.specHash!==uv(n)||o&&r.envHash&&r.envHash!==o?null:r}function Tf(e){let t=ln(e).shots;return Object.keys(t).filter(n=>t[n].outcome==="failed").sort()}function gc(e,t,n){let o=mc(ln(e),t,n,Li(e));return!o||o.outcome==="captured"||!o.reason?null:{outcome:o.outcome,reason:o.reason}}er();import{existsSync as gv,readFileSync as Df,readdirSync as jf,writeFileSync as wv}from"node:fs";import{isAbsolute as yv,join as If,resolve as bv}from"node:path";import{readProjectConfig as kv,DEFAULT_CAPTURE_DIR as $v}from"document360-engine";var Nf="0.2.25";function tr(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 vv=/^([ \t]*)await\s+([^\n;]+?)\.screenshot\(\{\s*path:\s*PLACEHOLDER\.saveTo\s*(?:,\s*fullPage:\s*(?:true|false)\s*)?,?\s*\}\)\s*;?[ \t]*$/m,xv=/^[ \t]*await\s+dumpAnnotations\(\s*page\s*,\s*PLACEHOLDER\s*\)\s*;?[ \t]*\r?\n?/m,Lf="(?:'([^']+)'|\"([^\"]+)\"|`([^`]+)`)",Rv=new RegExp(`^page\\s*\\.\\s*locator\\(\\s*${Lf}\\s*\\)$`),Of=e=>e[1]??e[2]??e[3]??null,Cv=/^[A-Za-z_$][\w$]*$/;function Sv(e,t){let o=new RegExp(`\\bconst\\s+${t}\\s*=\\s*page\\s*\\.\\s*locator\\(\\s*${Lf}\\s*\\)\\s*;`).exec(e);return o?Of(o):null}function Pv(e,t){let n=t.trim();if(n==="page")return null;let o=Rv.exec(n);if(o){let r=Of(o);return r?{selector:r}:{unresolved:!0}}if(Cv.test(n)){let r=Sv(e,n);return r?{selector:r}:{unresolved:!0}}return{unresolved:!0}}function _f(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=vv.exec(e);if(!n)return null;let[o,r="",s=""]=n,i=Pv(e,s);if(i===null)return null;if("unresolved"in i)return{unresolved:s.trim()};let a=/^([ \t]*)saveTo:\s*.+,[ \t]*$/m.exec(e);if(!a)return null;let l=i.selector.includes("'")?'"':"'",d=e.replace(a[0],`${a[0]}
312
+ ${a[1]??" "}clipTo: ${l}${i.selector}${l},`);return d=d.replace(o,`${r}await captureShot(page, PLACEHOLDER);`),d=d.replace(xv,""),d=d.replace(/\bdumpAnnotations\b(?=[^\n]*from 'document360-capture\/helpers')/,"captureShot"),/from 'document360-capture\/helpers'/.test(d)&&!/\bcaptureShot\b[^\n]*from 'document360-capture\/helpers'/.test(d)&&(d=d.replace(/import \{([^}]*)\} from 'document360-capture\/helpers'/,(w,m)=>`import {${m.replace(/\s*$/,"")}, captureShot } from 'document360-capture/helpers'`)),{next:d,selector:i.selector}}function Tv(e){try{return jf(e).filter(t=>t.endsWith(".spec.ts")).some(t=>{try{let n=_f(Df(If(e,t),"utf8"));return n!==null&&!("unresolved"in n)}catch{return!1}})}catch{return!1}}function Av(e){let t=kv(e)?.captureDir??$v;return yv(t)?t:bv(e,t)}function Mf(e,t){let n={migrated:[],skipped:[]},o=Av(e);if(!gv(o))return n;let r=t?.captureVersion===void 0?dt():t.captureVersion;if(!tr(r,Nf))return Tv(o)?{...n,heldBackForCapture:{installed:r,required:Nf}}:n;let s;try{s=jf(o).filter(i=>i.endsWith(".spec.ts"))}catch{return n}for(let i of s.sort()){let a=i.slice(0,-8),l=If(o,i);try{let d=Df(l,"utf8"),w=_f(d);if(w===null)continue;if("unresolved"in w){n.skipped.push({id:a,receiver:w.unresolved});continue}wv(l,w.next,"utf8"),n.migrated.push(a)}catch{}}return n}function Ff(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
313
  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(`
314
- `)}function Pe(e,t,n){return`${e}${n?` ${n}`:""}${t?` ${t}`:""}`}function Yt(e){if(e.length===0)return;let t=e.map(r=>r.replace(/\\/g,"/"));if(t.length===1)return t[0];let n=r=>r.split("/").slice(0,-1).join("/"),o=n(t[0]);if(o!=="")return t.every(r=>n(r)===o)?o:void 0}Zo();var Bf=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function _f(e){let t=e.includes("--detail")||e.includes("-d"),n=e.find(o=>o!=="--detail"&&o!=="-d");return{mode:"list",scope:n?Bf(n):void 0,...t?{detail:!0}:{}}}function is(e){let t=(e[0]??"").toLowerCase();if(t==="capture")return{mode:"capture",rest:e.slice(1)};if(t==="annotate")return{mode:"annotate",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 _f(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 _f(o.slice(1));let r=o[0];return r?r==="--all"?{mode:"all",setup:n}:/[\\/]/.test(r)||r.endsWith(".md")?{mode:"scope",scope:Bf(r),setup:n}:{mode:"single",id:r}:{mode:"list",picker:!0}}function _e(e,t,n){let o=Sn(e),r=o?.captureDir??Wi,s=o?.outputDir??xc,i=(w,k)=>Mi(w)?Fi(w,k):Ui(e,w,k),a=ln(e),l=n?.captureVersion===void 0?dt():n.captureVersion,d=er(l,Vf),g=Ii(e);return Uf(e,{scope:t}).map(({id:w,file:k})=>{let S=i(r,`${w}.spec.ts`),v=null;if(Ff(S))try{v=vc(S,"utf8")}catch{}let C=Wf(e,s),T=Ev(C,w),D=Tv(T),L=Av(T),B=v===null?null:dc(a,w,v,g),M=a.shots[w]?.review,X=D&&Sv(M,T.annotatedMtimeMs)?M:void 0,z=v!==null&&Lv(v),de=D&&X?.verdict==="ok"?"verified":D&&X?.verdict==="rejected"?"rejected":D?"annotated":L?"captured":v===null?"placeholder":z||B?.outcome==="skipped"?"blocked":B?.outcome==="failed"?"broken":"spec",be=v===null?void 0:Gf(v),$e=z?_v(v):B?.reason,Ce=z?"testid":B?.outcome==="skipped"?uc(B.reason):void 0,fe=v===null?[]:Ov(e,v);return{id:w,file:k,state:de,...be?{mutates:be.mutates,...be.declared?{}:{undeclared:!0}}:{},...v!==null&&mc(v).length>0?{unguardedWaits:mc(v)}:{},...v!==null&&fc(v).length>0?{unverifiedForce:fc(v)}:{},...v!==null&&gc(v).length>0?{handRolled:gc(v)}:{},...v!==null&&yc(v).length>0?{stalePause:yc(v)}:{},...v!==null&&d&&wc(v).length>0?{bareGoto:wc(v)}:{},...fe.length>0?{staleAnchor:fe}:{},...de==="blocked"||de==="broken"?{...$e?{reason:$e}:{},...Ce?{blockedBy:Ce}:{}}:{},...de==="rejected"?{...X?.reason?{reason:X.reason}:{},...X?.repaired?{repaired:!0}:{}}:{}}})}function jv(e){let t=Sn(e)?.outputDir??xc;return Cv(Wf(e,t))}function so(e){let t=jv(e),n=Sn(e)?.outputDir??xc,o=[];t>0&&o.push(`\u2195 Tidied ${t} screenshot file${t===1?"":"s"} into ${n}/{${Nv},${Dv}} \u2014 annotated/ is what publishes, raw/ is the pre-annotation intermediate.`);let r=Of(Lf(e));return r&&o.push(r),o.length>0?o.join(`
315
- `):null}function io(e,t){let n=Sn(e)?.captureDir??Wi,o=Mi(n)?Fi(n,`${t}.spec.ts`):Ui(e,n,`${t}.spec.ts`);try{return vc(o,"utf8")}catch{return null}}function Hf(e,t){let n=Sn(e)?.captureDir??Wi;return Ff(Mi(n)?Fi(n,`${t}.spec.ts`):Ui(e,n,`${t}.spec.ts`))}function Iv(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 Gf(e){let t=e.split(/\r?\n/),n=t.findIndex(a=>/^\s*\/\/\s*CAPTURE-SAFETY:\s*(readonly|mutates)\b/i.test(a)),o=n>=0?/^\s*\/\/\s*CAPTURE-SAFETY:\s*(readonly|mutates)\b[\s—:–-]*(.*)$/i.exec(t[n]):null;if(o){let a=Iv(t,n,o[2]??"");return{mutates:o[1].toLowerCase()==="mutates",declared:!0,what:a||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 Lv(e){return/(^|\n)\s*test\.skip\s*\(\s*['"`]/.test(e)}function qf(e){let t=[];for(let n of e.matchAll(/\/\/\s*CAPTURE-TODO:\s*(\{.*\})\s*$/gm))try{let o=JSON.parse(n[1]);o&&typeof o=="object"&&t.push(o)}catch{}return t}function Ov(e,t){let n=[];for(let o of qf(t))Pv(e,o.file,o.anchor)===!1&&n.push(o.testid??o.file??"unnamed request");return[...new Set(n)]}function _v(e){let{testid:t,file:n}=qf(e)[0]??{};return`Inert until your developers add ${t?`data-testid="${t}"${n?` in ${n}`:""}`:"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 as(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 fc(e,t=10){let n=as(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(`
316
- `))||o.push(r+1));return o}function mc(e){let t=[],n=as(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 gc(e){let t=[];for(let[n,o]of as(e).entries())(/\.screenshot\s*\(/.test(o)||/\bdumpAnnotations\s*\(/.test(o))&&t.push(n+1);return t}var Vf="0.2.28";function wc(e){let t=[];for(let[n,o]of as(e).entries())/\.goto\s*\(/.test(o)&&t.push(n+1);return t}function yc(e,t=6){let n=as(e),o=[];for(let[r,s]of n.entries()){if(!/waitForTimeout\s*\(/.test(s))continue;let i=n.slice(r+1,r+1+t).join(`
314
+ `)}function Ce(e,t,n){return`${e}${n?` ${n}`:""}${t?` ${t}`:""}`}function Yt(e){if(e.length===0)return;let t=e.map(r=>r.replace(/\\/g,"/"));if(t.length===1)return t[0];let n=r=>r.split("/").slice(0,-1).join("/"),o=n(t[0]);if(o!=="")return t.every(r=>n(r)===o)?o:void 0}er();var qf=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Uf(e){let t=e.includes("--detail")||e.includes("-d"),n=e.find(o=>o!=="--detail"&&o!=="-d");return{mode:"list",scope:n?qf(n):void 0,...t?{detail:!0}:{}}}function as(e){let t=(e[0]??"").toLowerCase();if(t==="capture")return{mode:"capture",rest:e.slice(1)};if(t==="annotate")return{mode:"annotate",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 Uf(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 Uf(o.slice(1));let r=o[0];return r?r==="--all"?{mode:"all",setup:n}:/[\\/]/.test(r)||r.endsWith(".md")?{mode:"scope",scope:qf(r),setup:n}:{mode:"single",id:r}:{mode:"list",picker:!0}}function _e(e,t,n){let o=Sn(e),r=o?.captureDir??Bi,s=o?.outputDir??Pc,i=(m,$)=>Fi(m)?Ui(m,$):Wi(e,m,$),a=ln(e),l=n?.captureVersion===void 0?dt():n.captureVersion,d=tr(l,zf),w=Li(e);return Hf(e,{scope:t}).map(({id:m,file:$})=>{let S=i(r,`${m}.spec.ts`),R=null;if(Bf(S))try{R=Sc(S,"utf8")}catch{}let C=Gf(e,s),A=Ov(C,m),D=Iv(A),N=Lv(A),U=R===null?null:mc(a,m,R,w),O=a.shots[m]?.review,Q=D&&Dv(O,A.annotatedMtimeMs)?O:void 0,z=R!==null&&Wv(R),de=D&&Q?.verdict==="ok"?"verified":D&&Q?.verdict==="rejected"?"rejected":D?"annotated":N?"captured":R===null?"placeholder":z||U?.outcome==="skipped"?"blocked":U?.outcome==="failed"?"broken":"spec",ke=R===null?void 0:Yf(R),xe=z?Hv(R):U?.reason,Pe=z?"testid":U?.outcome==="skipped"?fc(U.reason):void 0,fe=R===null?[]:Bv(e,R);return{id:m,file:$,state:de,...ke?{mutates:ke.mutates,...ke.declared?{}:{undeclared:!0}}:{},...R!==null&&bc(R).length>0?{unguardedWaits:bc(R)}:{},...R!==null&&yc(R).length>0?{unverifiedForce:yc(R)}:{},...R!==null&&kc(R).length>0?{handRolled:kc(R)}:{},...R!==null&&vc(R).length>0?{stalePause:vc(R)}:{},...R!==null&&d&&$c(R).length>0?{bareGoto:$c(R)}:{},...fe.length>0?{staleAnchor:fe}:{},...de==="blocked"||de==="broken"?{...xe?{reason:xe}:{},...Pe?{blockedBy:Pe}:{}}:{},...de==="rejected"?{...Q?.reason?{reason:Q.reason}:{},...Q?.repaired?{repaired:!0}:{}}:{}}})}function Fv(e){let t=Sn(e)?.outputDir??Pc;return Nv(Gf(e,t))}function io(e){let t=Fv(e),n=Sn(e)?.outputDir??Pc,o=[];t>0&&o.push(`\u2195 Tidied ${t} screenshot file${t===1?"":"s"} into ${n}/{${_v},${Mv}} \u2014 annotated/ is what publishes, raw/ is the pre-annotation intermediate.`);let r=Ff(Mf(e));return r&&o.push(r),o.length>0?o.join(`
315
+ `):null}function ao(e,t){let n=Sn(e)?.captureDir??Bi,o=Fi(n)?Ui(n,`${t}.spec.ts`):Wi(e,n,`${t}.spec.ts`);try{return Sc(o,"utf8")}catch{return null}}function Vf(e,t){let n=Sn(e)?.captureDir??Bi;return Bf(Fi(n)?Ui(n,`${t}.spec.ts`):Wi(e,n,`${t}.spec.ts`))}function Uv(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 Yf(e){let t=e.split(/\r?\n/),n=t.findIndex(a=>/^\s*\/\/\s*CAPTURE-SAFETY:\s*(readonly|mutates)\b/i.test(a)),o=n>=0?/^\s*\/\/\s*CAPTURE-SAFETY:\s*(readonly|mutates)\b[\s—:–-]*(.*)$/i.exec(t[n]):null;if(o){let a=Uv(t,n,o[2]??"");return{mutates:o[1].toLowerCase()==="mutates",declared:!0,what:a||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 Wv(e){return/(^|\n)\s*test\.skip\s*\(\s*['"`]/.test(e)}function Kf(e){let t=[];for(let n of e.matchAll(/\/\/\s*CAPTURE-TODO:\s*(\{.*\})\s*$/gm))try{let o=JSON.parse(n[1]);o&&typeof o=="object"&&t.push(o)}catch{}return t}function Bv(e,t){let n=[];for(let o of Kf(t))jv(e,o.file,o.anchor)===!1&&n.push(o.testid??o.file??"unnamed request");return[...new Set(n)]}function Hv(e){let{testid:t,file:n}=Kf(e)[0]??{};return`Inert until your developers add ${t?`data-testid="${t}"${n?` in ${n}`:""}`:"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 ls(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 yc(e,t=10){let n=ls(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(`
316
+ `))||o.push(r+1));return o}function bc(e){let t=[],n=ls(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 kc(e){let t=[];for(let[n,o]of ls(e).entries())(/\.screenshot\s*\(/.test(o)||/\bdumpAnnotations\s*\(/.test(o))&&t.push(n+1);return t}var zf="0.2.28";function $c(e){let t=[];for(let[n,o]of ls(e).entries())/\.goto\s*\(/.test(o)&&t.push(n+1);return t}function vc(e,t=6){let n=ls(e),o=[];for(let[r,s]of n.entries()){if(!/waitForTimeout\s*\(/.test(s))continue;let i=n.slice(r+1,r+1+t).join(`
317
317
  `);if(!/test\.skip\s*\(/.test(i)||!/\.count\s*\(\s*\)/.test(i))continue;let a=n.slice(Math.max(0,r-t),r+1).join(`
318
- `);/\.waitFor\s*\(|Promise\.race\s*\(|waitForFunction\s*\(|waitForSelector\s*\(/.test(a)||o.push(r+1)}return o}function Cc(e,t){let n=g=>`line${g.length===1?"":"s"} ${g.join(", ")}`,o=[],r=t?.captureVersion===void 0?dt():t.captureVersion,s=er(r,Vf)?wc(e):[];s.length>0&&o.push(`- ${n(s)}: navigates with a bare page.goto(). EVERY navigation must go through gotoResilient (from document360-capture/helpers) \u2014 \`await gotoResilient(page)\` for the start URL, \`await gotoResilient(page, "/route")\` mid-spec. Under a bulk run goto's default "load" wait never fires and the spec dies at 60s on that line.`);let i=mc(e);i.length>0&&o.push(`- ${n(i)}: a .waitFor() whose timeout is not swallowed, so a missing prerequisite hard-fails instead of skipping. Add .catch(() => {}), then read the element and test.skip with a reason.`);let a=gc(e);a.length>0&&o.push(`- ${n(a)}: takes its own screenshot (or calls dumpAnnotations) instead of captureShot(page, PLACEHOLDER). On a cropped shot that misplaces every callout and nothing errors.`);let l=yc(e);l.length>0&&o.push(`- ${n(l)}: the "data is missing" decision rests on a fixed waitForTimeout, so staged data can read as absent. Give the element a bounded chance to appear first, then count.`);let d=fc(e);return d.length>0&&o.push(`- ${n(d)}: click({ force: true }) with no assertion that it worked, so a no-op click photographs the unchanged screen. Assert the expected result immediately after, guarded, and skip if it never arrives.`),/CAPTURE-SAFETY:/.test(e)||o.push("- no CAPTURE-SAFETY marker: add exactly one `// CAPTURE-SAFETY: readonly` or `// CAPTURE-SAFETY: mutates \u2014 <what>; cleanup: <how>` at the top."),o}function Yf(e,t){return e.length===0?[]:[t,...e,"These are SEPARATE from whatever else you were asked to fix \u2014 clear them in the same pass. They were","found by scanning the file, so they are facts about it, not suggestions.",""]}function Kf(e){return(e??"").trim().replace(/[.\s]+$/,"")}function zf(e,t){let n=Sn(e)?.captureDir??Wi,o=Mi(n)?Fi(n,`${t}.spec.ts`):Ui(e,n,`${t}.spec.ts`);try{return Gf(vc(o,"utf8"))}catch{return{mutates:!1,declared:!1}}}var Mv=["annotated","verified","rejected"],Fv=e=>Mv.includes(e);function Uv(e){return[...new Set(e.filter(t=>Fv(t.state)).map(t=>t.file))].sort()}function Bi(e,t){let n=Uv(e);if(!t)return n;let o=t.replace(/\\/g,"/").replace(/\/+$/,"");return n.filter(r=>{let s=r.replace(/\\/g,"/");return s===o||s.startsWith(`${o}/`)||s.endsWith(`/${o}`)})}function Hi(e,t){let n=e.filter(s=>s.state==="captured");if(n.length===0)return null;let o=Math.max(...n.map(s=>s.id.length)),r=n.length===1;return[`${J("\u26A0",I.yellow)}${n.length} screenshot${r?" has":"s have"} been taken but the callouts aren't drawn on yet, so ${r?"it has":"they have"} no picture to publish:`,...n.map(s=>` ${I.yellow(s.id.padEnd(o))}`),` Publishing without ${r?"it":"them"}. Finish ${r?"it":"them"} first: ${I.bold(Pe("/screenshot annotate","",t))}`].join(`
319
- `)}function Gi(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[`${J("\u26A0",I.yellow)}${t.length} screenshot${t.length===1?"":"s"} failed verification:`,...t.map(o=>` ${I.magenta(o.id.padEnd(n))} ${I.gray(nr(o.reason??"no reason recorded"))}`),` Publishing anyway. Fix + re-capture: ${I.bold("/screenshot capture --failed")}`].join(`
320
- `)}var Wv={placeholder:"\u25CB",spec:"\u25D0",blocked:"\u2298",broken:"\u2717",captured:"\u25CF",annotated:"\u25C8",verified:"\u2714",rejected:"\u2691"},Bv={placeholder:I.gray,spec:I.yellow,blocked:I.cyan,broken:I.red,captured:I.yellow,annotated:I.blue,verified:I.green,rejected:I.magenta},Hv=` ${I.green("\u2714 verified")} ${I.blue("\u25C8 to verify")} ${I.yellow("\u25CF to annotate")} ${I.yellow("\u25D0 ready")} ${I.magenta("\u2691 rejected")} ${I.cyan("\u2298 blocked")} ${I.red("\u2717 broken")} ${I.gray("\u25CB to spec")}`;function J(e,t=n=>n){return`${t(e)} `}function nr(e){return e.replace(/\s+/g," ").trim().replace(/^Prerequisites? not met[:—-]?\s*/i,"")}function qi(e){let t=nr(e),n=/^(.*?[a-z0-9)"'”’])\.(?:\s|$)/i.exec(t);return(n?n[1]:t).trim()}function ls(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=qi(o),i=`${r} ${s.toLowerCase()}`,a=t.get(i)??{reason:s,blockedBy:r,ids:[]};t.has(i)||t.set(i,a),a.ids.push(n.id)}return[...t.values()].sort((n,o)=>o.ids.length-n.ids.length||n.reason.localeCompare(o.reason))}function Xf(e){let t=ls(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((a,l)=>a+l.ids.length,0);r.push(` ${I.bold("Stage this data")} ${I.gray(`\u2014 unblocks ${s} shot${s===1?"":"s"} in ${n.length} action${n.length===1?"":"s"}`)}`);let i=8;for(let a of n.slice(0,i)){let l=Vt(a.reason,86);r.push(` ${I.cyan(Cn(`${a.ids.length}\xD7`,4))} ${l[0]??""}`);for(let g of l.slice(1))r.push(` ${g}`);let d=a.ids.slice(0,4).join(" \xB7 ");r.push(I.gray(` ${d}${a.ids.length>4?` \xB7 +${a.ids.length-4} more`:""}`))}n.length>i&&r.push(I.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,a)=>i+a.ids.length,0);r.push(` ${J("\u2298",I.cyan)}${s} shot${s===1?"":"s"} need${s===1?"s":""} a data-testid from your developers \u2014 ${I.bold("/screenshot checklist")} builds the hand-off.`)}return r}function Sc(e){if(e.length===0)return[];let t=e.slice(0,6),n=e.length;return["",` ${J("\u26A0",I.yellow)}${n} screenshot marker${n===1?"":"s"} will be ignored \u2014 ${n===1?"it is":"they are"} not shaped the way the publish step needs`+I.gray(`, so ${n===1?"that picture":"those pictures"} would never be taken`),...t.map(o=>I.gray(` ${o.file}:${o.line} \u2014 ${o.reason}`)),...n>t.length?[I.gray(` \u2026and ${n-t.length} more`)]:[],I.gray(" Usually a reviewer comment wrapped around it. A marker must start its own line and carry an id:.")]}function Qf(e,t){let n=e.filter(i=>(i.staleAnchor?.length??0)>0);if(n.length===0)return[];let o=[...new Set(n.flatMap(i=>i.staleAnchor))],r=o.length,s=["",` ${J("\u26A0",I.yellow)}${r} selector request${r===1?"":"s"} quote${r===1?"s":""} source code that has since changed`+I.gray(" \u2014 your developers would go looking for something that isn't there any more"),I.gray(` Refresh the hand-off before sending it: ${I.bold("/screenshot checklist")}`)];return t&&s.push(I.gray(` ${o.slice(0,8).join(" \xB7 ")}${r>8?` \xB7 +${r-8} more`:""}`)),s}function Jf(e,t,n){let o=e.filter(g=>(g.unguardedWaits?.length??0)>0),r=e.filter(g=>g.undeclared),s=e.filter(g=>(g.handRolled?.length??0)>0),i=e.filter(g=>(g.stalePause?.length??0)>0),a=e.filter(g=>(g.bareGoto?.length??0)>0);if(o.length===0&&r.length===0&&s.length===0&&i.length===0&&a.length===0)return[];let l=["",` ${J("\u26A0",I.yellow)}Some specs were written before later reliability fixes:`],d=(g,w)=>` ${g.slice(0,8).map(w).join(" \xB7 ")}${g.length>8?` \xB7 +${g.length-8} more`:""}`;if(o.length>0){let g=o.length;l.push(I.gray(` ${g} crash${g===1?"es":""} instead of telling you what to stage when the data ${g===1?"it needs":"they need"} is missing`)),t&&l.push(I.gray(d(o,w=>`${w.id}:${w.unguardedWaits.join(",")}`)))}if(a.length>0){let g=a.length;l.push(I.gray(` ${g} open${g===1?"s":""} pages the slow way, so ${g===1?"it stalls":"they stall"} for a minute and give up when several shots run at once`)),t&&l.push(I.gray(d(a,w=>`${w.id}:${w.bareGoto.join(",")}`)))}if(i.length>0){let g=i.length;l.push(I.gray(` ${g} decide${g===1?"s":""} "the data is missing" from a fixed pause, so data you HAVE staged can read as absent`)),t&&l.push(I.gray(d(i,w=>`${w.id}:${w.stalePause.join(",")}`)))}if(s.length>0){let g=s.length;l.push(I.gray(` ${g} take${g===1?"s":""} ${g===1?"its":"their"} own screenshot instead of the one call that positions the callouts too \u2014 on a cropped shot the numbers land in the wrong places, and nothing reports it`)),t&&l.push(I.gray(d(s,w=>`${w.id}:${w.handRolled.join(",")}`)))}if(r.length>0){let g=r.length,w=r.filter(k=>k.mutates).length;l.push(I.gray(` ${g} do${g===1?"es":""} not say whether ${g===1?"it changes":"they change"} data in your app`+(w>0?`, so ${w===1?"one is":`${w} are`} left out of bulk runs to be safe`:""))),t&&l.push(I.gray(d(r,k=>k.id)))}return n?.commandInLead||l.push(I.gray(` Re-write them all with the current rules: ${I.bold("/screenshot author --all")}`)),l}function Zf(e){let t=e.filter(n=>(n.unverifiedForce?.length??0)>0);return t.length===0?[]:["",` ${J("\u26A0",I.red)}${t.length} spec${t.length===1?"":"s"} force-click past Playwright's safety checks without asserting the result`+I.gray(" \u2014 if the click lands on nothing, the shot photographs the unchanged screen"),I.gray(` ${t.slice(0,6).map(n=>`${n.id}:${n.unverifiedForce.join(",")}`).join(" \xB7 ")}${t.length>6?` \xB7 +${t.length-6} more`:""}`),I.gray(` Re-author to check what the click did: ${I.bold("/screenshot author <id>")}`)]}var _i=(e,t)=>e.length>=t?e:e+" ".repeat(t-e.length),Cn=(e,t)=>e.length>=t?e:" ".repeat(t-e.length)+e;function em(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 Gv=new Set(["and","or","of","the","to","a","an","in","on","for","with","vs"]),qv=new Set(["ai","api","cli","ui","ux","url","id","http","https","json","xml","sdk","csv","pdf","oauth","sso","mfa","io","faq"]);function Vv(e){return e.replace(/[-_]+/g," ").trim().split(/\s+/).filter(Boolean).map((n,o)=>{let r=n.toLowerCase();return qv.has(r)?r.toUpperCase():o>0&&Gv.has(r)?r:r.charAt(0).toUpperCase()+r.slice(1)}).join(" ")}function bc(e){if(!e)return{num:"",name:"(docs root)"};let t=/^(\d+)[-_](.+)$/.exec(e);return{num:t?t[1]:"",name:Vv(t?t[2]:e)}}function Yv(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).pop()??e}function Mf(e,t,n){let o=t>0?Math.round(e/t*n):0;return I.green("\u2588".repeat(o))+I.gray("\u2591".repeat(Math.max(0,n-o)))}function Kv(e,t){let n=t>0?Math.round(e/t*100):0,o=Cn(`${n}%`,4);return n===100?I.green(o):n>0?I.yellow(o):I.gray(o)}function tm(e,t){let n=new Map;for(let o of e){let r=em(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 Pc(e,t){let n=T=>e.filter(D=>D.state===T).length,o=n("captured"),r=n("placeholder"),s=n("spec"),i=n("annotated"),a=n("blocked"),l=n("broken"),d=n("rejected"),g=e.filter(T=>T.state==="spec"&&T.mutates).length,w=s>g,k=e.filter(T=>(T.unguardedWaits?.length??0)>0||(T.bareGoto?.length??0)>0).length,S=e.filter(T=>(T.stalePause?.length??0)>0||(T.handRolled?.length??0)>0).length,v=s>0||a>0||l>0,C=(T,D="")=>Pe(T,D,t);return o>0?{key:"annotate",cmd:C("/screenshot annotate")}:r>0?{key:"toSpec",cmd:t?`/screenshot author ${t}`:"/screenshot author --all"}:k>0&&v?{key:"crashy",cmd:t?`/screenshot author ${t}`:"/screenshot author --all"}:S>0&&v?{key:"wrongOutput",cmd:t?`/screenshot author ${t}`:"/screenshot author --all"}:s>0&&(w||i===0)?{key:"ready",cmd:C("/screenshot capture")}:i>0&&s>0?{key:"verify",cmd:C("/screenshot verify")}:a>0?{key:"blocked",cmd:C("/screenshot capture","--blocked")}:l>0?{key:"broken",cmd:`/screenshot ${e.find(T=>T.state==="broken").id}`}:i>0?{key:"verify",cmd:C("/screenshot verify")}:d>0?{key:"rejected",cmd:C("/screenshot capture","--failed")}:{key:"done",cmd:t?`/push ${t}`:"/push"}}function zv(e,t,n=[]){let o=(ee,ge)=>ee.filter(ke=>ke.state===ge).length,r=e.length,s=o(e,"verified"),i=o(e,"annotated"),a=o(e,"captured"),l=o(e,"rejected"),d=o(e,"spec"),g=o(e,"blocked"),w=o(e,"broken"),k=o(e,"placeholder"),S=new Set(e.map(ee=>ee.file)).size,v=tm(e,t),C=[];C.push(` ${I.bold("Screenshots")} ${I.green(`${s}/${r} verified`)} ${I.gray("\xB7")} ${i>0?I.blue(`${i} to verify`):I.gray("0 to verify")}`+(a>0?` ${I.gray("\xB7")} ${I.yellow(`${a} to annotate`)}`:"")+(l>0?` ${I.gray("\xB7")} ${I.magenta(`${l} rejected`)}`:"")+` ${I.gray("\xB7")} ${d>0?I.yellow(`${d} ready`):I.gray("0 ready")}`+(g>0?` ${I.gray("\xB7")} ${I.cyan(`${g} blocked`)}`:"")+(w>0?` ${I.gray("\xB7")} ${I.red(`${w} broken`)}`:"")+` ${I.gray("\xB7")} ${k>0?I.red(`${k} to spec`):I.gray("0 to spec")} `+I.gray(`across ${S} article${S===1?"":"s"}`));let T=r>0?Math.round(s/r*100):0;C.push(` [${Mf(s,r,32)}] ${I.bold(`${T}%`)}`),C.push("");let D=v.map(([ee])=>bc(ee)),L=Math.min(32,Math.max(7,...D.map(ee=>ee.name.length))),B=ee=>ee.length>L?`${ee.slice(0,L-1)}\u2026`:_i(ee,L),M=[...a>0?[{head:"To annotate",w:11,state:"captured",color:I.yellow}]:[],...i>0?[{head:"To verify",w:9,state:"annotated",color:I.blue}]:[],...l>0?[{head:"Rejected",w:8,state:"rejected",color:I.magenta}]:[],{head:"Ready",w:5,state:"spec",color:I.yellow},...g>0?[{head:"Blocked",w:7,state:"blocked",color:I.cyan}]:[],...w>0?[{head:"Broken",w:6,state:"broken",color:I.red}]:[],{head:"To spec",w:7,state:"placeholder",color:I.red}];C.push(I.gray(` ${_i("#",2)} ${_i("Chapter",L)} ${Cn("Verified",8)} ${M.map(ee=>Cn(ee.head,ee.w)).join(" ")} Progress`));for(let[ee,[,ge]]of v.entries()){let ke=o(ge,"verified"),Ye=ge.length,{num:fn,name:mn}=D[ee],At=ke===Ye,gt=B(mn),Dr=M.map(tt=>{let $o=o(ge,tt.state);return $o>0?tt.color(Cn(String($o),tt.w)):I.gray(Cn("\u2014",tt.w))}).join(" ");C.push(` ${I.cyan(_i(fn,2))} ${At?I.green(gt):ke>0?gt:I.gray(gt)} ${At?I.green(Cn(`${ke}/${Ye}`,8)):Cn(`${ke}/${Ye}`,8)} ${Dr} ${Mf(ke,Ye,10)} ${Kv(ke,Ye)}`)}C.push("");let X=w>0?` ${I.gray("\xB7")} ${w} spec${w===1?"":"s"} broken \u2014 ${I.bold(`/screenshot ${e.find(ee=>ee.state==="broken").id}`)} re-authors ${w===1?"it":"the first"}`:"",z=e.filter(ee=>ee.state==="spec"&&ee.mutates).length,de=d>z,be=e.filter(ee=>(ee.unguardedWaits?.length??0)>0||(ee.bareGoto?.length??0)>0).length,$e=e.filter(ee=>(ee.stalePause?.length??0)>0||(ee.handRolled?.length??0)>0).length,Ce=d>0||g>0||w>0,fe=!1,se=Pc(e).key;if(se==="annotate")C.push(` ${J("\u25C8",I.blue)}${a} shot${a===1?"":"s"} taken but not drawn on \u2014 run ${I.bold("/screenshot annotate")}`+I.gray(` \u2014 no browser, seconds; the callouts are what make ${a===1?"it":"them"} publishable`)+X);else if(se==="toSpec")C.push(` ${J("\u2192",I.yellow)}${k} placeholder${k===1?"":"s"} still need a spec \u2014 run ${I.bold("/screenshot author --all")}${X}`);else if(se==="crashy")fe=!0,C.push(` ${J("\u2192",I.yellow)}${be} spec${be===1?"":"s"} would crash mid-run \u2014 re-write ${be===1?"it":"them"} first: ${I.bold("/screenshot author --all")}`+I.gray(` \xB7 then ${I.bold("/screenshot capture")} (no browser time wasted on ${be===1?"a shot":"shots"} that can't finish)`)+X);else if(se==="wrongOutput")fe=!0,C.push(` ${J("\u2192",I.yellow)}${$e} spec${$e===1?"":"s"} would shoot the wrong thing \u2014 re-write ${$e===1?"it":"them"} first: ${I.bold("/screenshot author --all")}`+I.gray(` \xB7 then ${I.bold("/screenshot capture")} (a false skip or a misplaced callout costs the same browser time as a good shot)`)+X);else if(se==="ready"){let ee=z>0?I.gray(` \u2014 ${d-z} in one go; ${z} write${z===1?"s":""} real data and run${z===1?"s":""} one at a time`):"";C.push(` ${J("\u2192",I.yellow)}${d} spec${d===1?"":"s"} ready to capture \u2014 run ${I.bold("/screenshot capture")}${ee}${X}`)}else if(se==="verify"&&d>0)C.push(` ${J("\u2192",I.blue)}${i} shot${i===1?"":"s"} awaiting verification \u2014 run ${I.bold("/screenshot verify")}`+I.gray(" \u2014 no browser needed")+I.gray(` \xB7 ${d} ready spec${d===1?"":"s"} write real data, so ${d===1?"it runs":"each runs"} only when named: /screenshot capture <id>`)+X);else if(se==="blocked")C.push(` ${J("\u2192",I.cyan)}${g} shot${g===1?"":"s"} blocked \u2014 stage the data below, then ${I.bold("/screenshot capture --blocked")}${X}`);else if(se==="broken")C.push(` ${J("\u2192",I.red)}${w} spec${w===1?"":"s"} broken \u2014 ${I.bold(`/screenshot ${e.find(ee=>ee.state==="broken").id}`)} re-authors ${w===1?"it":"the first"} (re-capturing fails the same way)`);else if(se==="verify")C.push(` ${J("\u2192",I.blue)}${i} shot${i===1?"":"s"} awaiting verification \u2014 run ${I.bold("/screenshot verify")}`+I.gray(" \u2014 it checks each picture against what its article needs (no browser, no re-capture)"));else if(se==="rejected"){let ee=e.filter(ge=>ge.state==="rejected"&&ge.repaired).length;C.push(` ${J("\u2691",I.magenta)}${l} shot${l===1?"":"s"} failed review \u2014 `+(ee>0?`${ee} spec${ee===1?"":"s"} already repaired; re-capture with ${I.bold("/screenshot capture --failed")}`:`see the reasons below, then ${I.bold("/screenshot capture --failed")}`))}else C.push(` ${J("\u2713",I.green)}all ${r} verified \u2014 ${I.bold("/push")} embeds them in the articles`);if(s>0&&s<r){let ee=v.filter(([,ge])=>ge.every(ke=>ke.state!=="verified")).map(([ge])=>{let{num:ke,name:Ye}=bc(ge);return ke?`${ke} ${Ye}`:Ye});ee.length>0&&C.push(I.gray(` Furthest behind: ${ee.slice(0,5).join(" \xB7 ")}${ee.length>5?" \u2026":""} (0% verified)`))}return C.push(...Xf(e),...Zf(e),...Jf(e,!1,{commandInLead:fe}),...Qf(e,!1),...Sc(n)),C.push(""),C.push(I.gray(" Drill in: /screenshot list <chapter#> \xB7 /screenshot list --detail (all)")),C}function Xv(e,t,n,o=[]){let r=new Set(e.map(d=>d.file)),s=e.filter(d=>d.state==="verified").length,i=e.filter(d=>d.state==="annotated").length,a=e.filter(d=>d.state==="captured").length,l=[` ${I.bold("Screenshots")}: ${e.length} placeholder${e.length===1?"":"s"} across ${r.size} article${r.size===1?"":"s"} \xB7 ${I.green(`${s} verified`)}${i>0?I.blue(` \xB7 ${i} to verify`):""}${a>0?I.yellow(` \xB7 ${a} to annotate`):""}${n?I.gray(` \xB7 scope ${n}`):""}`,""];for(let[d,g]of tm(e,t)){let w=g.filter(T=>T.state==="verified").length,{num:k,name:S}=bc(d),v=k?`${k} \xB7 ${S}`:S;l.push(` ${I.bold(v)} ${I.gray(`(${w}/${g.length})`)}`);let C=new Map;for(let T of g){let D=Yv(T.file),L=C.get(D)??[];C.has(D)||C.set(D,L),L.push(T)}for(let T of[...C.keys()].sort()){l.push(I.gray(` ${T}`));for(let D of C.get(T)){let L=Bv[D.state];if(l.push(` ${J(Wv[D.state],L)}${L(D.id)}`),(D.state==="blocked"||D.state==="broken"||D.state==="rejected")&&D.reason){for(let B of Vt(nr(D.reason),84))l.push(I.gray(` ${B}`));D.state==="rejected"&&l.push(I.gray(` ${D.repaired?"spec repaired \u2014 re-capture to confirm":"spec not yet repaired"}`))}}}}return l.push(...Xf(e),...Zf(e),...Jf(e,!0),...Qf(e,!0),...Sc(o)),l.push("",Hv),l}function Vi(e,t){let n=t?.scope,o=t?.markerProblems??[];if(e.length===0)return[n?`No screenshot placeholders under ${n}.`:"No screenshot placeholders found in the docs.",...Sc(o)];let r=t?.docsDir??Rc;return t?.detail||n?Xv(e,r,n,o):zv(e,r,o)}function Tc(e,t){if(!t||!/^\d+$/.test(t))return t;let n=Sn(e)?.docsDir??Rc,o=String(Number(t));for(let{file:r}of Uf(e)){let s=em(r,n),i=/^(\d+)/.exec(s);if(i&&String(Number(i[1]))===o)return s}return t}function nm(e,t){let r=e.map(a=>" ".repeat(a.depth)+a.label),s=Math.max(0,...e.map((a,l)=>a.note?Oi(r[l]):0)),i=Math.min(s,Math.max(0,t-2-24));return e.map((a,l)=>{let d=r[l];if(!a.note)return{head:d,note:""};let g=Math.max(2,i+2-Oi(d)),w=a.note.trim(),k=t-Oi(d)-g;return{head:d+" ".repeat(g),note:k>1&&Oi(w)>k?`${w.slice(0,k-1)}\u2026`:w}})}function Qv(e){let t=e.replace(/\\/g,"/").split("/").filter(Boolean),n=t.pop()??e;return{category:t.pop()??"(docs root)",article:n}}function tr(e,t,n){let o=new Map;for(let s of t){let{category:i,article:a}=Qv(s.file),l=o.get(i)??new Map;o.set(i,l);let d=l.get(a)??[];l.set(a,d),d.push(s)}let r=s=>n!=="capture"||!s.mutates;for(let s of[...o.keys()].sort()){let i=o.get(s),a=[...i.values()].flat().filter(r).map(d=>d.id),l=a.length>0;l&&e.push({kind:"category",action:n,label:`${s} (${a.length})`,ids:a,depth:1});for(let d of[...i.keys()].sort()){let g=i.get(d),w=g.filter(r).map(v=>v.id),k=w.length>0;k&&e.push({kind:"article",action:n,label:`${d} (${w.length})`,ids:w,depth:l?2:1});let S=(l?1:0)+(k?1:0)+1;for(let v of g){let C=n==="capture"&&v.mutates?" \u26A0 creates real data \u2014 runs only alone":void 0;e.push({kind:"shot",action:n,label:v.id,ids:[v.id],depth:S,...C?{note:C}:{}})}}}}function hc(e){return e?nr(e):""}function Ac(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((a,l)=>a.id.localeCompare(l.id)))e.push({kind:"shot",action:"capture",label:i.id,ids:[i.id],depth:1,note:` \u2298 ${hc(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((a,l)=>a.id.localeCompare(l.id)))e.push({kind:"shot",action:"author",label:i.id,ids:[i.id],depth:1,note:` \u2717 re-authors \u2014 ${hc(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((a,l)=>a.id.localeCompare(l.id))){let a=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 ${a} \u2014 ${hc(i.reason)}`})}}function om(e){let t=e.filter(i=>i.state==="placeholder"),n=e.filter(i=>i.state==="spec"),o=[];t.length>1&&o.push({kind:"all",action:"author",label:`Author all ${t.length} remaining specs`,ids:t.map(i=>i.id),depth:0}),tr(o,t,"author");let r=n.filter(i=>!i.mutates);r.length>1&&o.push({kind:"all",action:"capture",label:`Capture all ${r.length} ready specs`,ids:r.map(i=>i.id),depth:0}),tr(o,n,"capture");let s=e.filter(i=>i.state==="captured");return s.length>1&&o.push({kind:"all",action:"annotate",label:`Draw the callouts on all ${s.length} shots`,ids:s.map(i=>i.id),depth:0}),tr(o,s,"annotate"),Ac(o,e.filter(i=>i.state==="blocked"),e.filter(i=>i.state==="broken"),e.filter(i=>i.state==="rejected")),o}var kc=["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 captureShot() 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."," (f) An element that is RENDERED can still be EMPTY. A component may mount an input/textarea/pane",' with no content and fill it when its fetch resolves, so waitFor({state:"visible"}) proves the'," node exists, not that the data arrived \u2014 reading inputValue()/textContent() right after can"," catch the pre-fetch empty state and false-skip data that IS there. When the decision rests on"," a VALUE rather than on presence, wait for the value: page.waitForFunction(sel => { const el =",' document.querySelector(sel); return !!el && (el.value ?? el.textContent ?? "").trim() !== ""; },',' "<selector>", { timeout: 10_000 }).catch(() => {}) \u2014 THEN read it and skip on empty.'," (g) NEVER take the screenshot yourself. `captureShot(page, PLACEHOLDER)` is the only capture call:"," it shoots AND resolves the callout positions in one pass, so they cannot disagree. A"," page.screenshot()/locator.screenshot() + dumpAnnotations() pair measures coordinates against"," the whole page while a cropped image starts at the crop corner, so every pin and highlight is"," offset \u2014 and nothing errors, so the spec reports success and the picture is wrong."," (h) EVERY navigation goes through `gotoResilient` (from document360-capture/helpers), never a bare",' page.goto(): `await gotoResilient(page)` for the start URL, `gotoResilient(page, "/route")`',` mid-spec. Under a bulk run, sibling specs saturate the network and goto's default "load" wait`," never fires \u2014 four specs died on that identical first line, each patched by hand.","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."," That consistency applies WITHIN one spec too, and a spec with 2+ test.skip calls needs two checks:"," (a) does a LATER branch's reason still HOLD, given what passing the earlier guard already proved?",` A later branch that reuses an earlier one's reason verbatim ("sign in as an owner\u2026") when`," reaching it proves that condition passed does not just read oddly \u2014 it misdiagnoses the cause"," and sends the reader to fix something that is already fine."," (b) do multiple branches for the SAME prerequisite (found 0 vs found fewer than N) open with one"," identical sentence? Divergent openings defeat the grouping even within a single spec.","Before you finish, re-read each spec you wrote and check every rule above line by line."].join(`
321
- `);function Jv(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 $c="MANDATORY, check before you finish: every spec you write or touch must carry exactly one `// CAPTURE-SAFETY: readonly` or `// CAPTURE-SAFETY: mutates: <what it creates>; cleanup: <how>` line at the top. Re-read each file you wrote and add it if missing; a spec without it is classified by guesswork. A fail-by-design spec (the app rejects the input) is `readonly`.";function rm(e,t,n){let o=e.paths,r=o.filter(l=>t?.get(l)?.outcome==="failed"),s=o.filter(l=>t?.get(l)?.outcome==="skipped"),i=l=>`- ${l}: ${t.get(l).reason.replace(/\s+/g," ").trim()}`,a=o.filter(l=>(n?.get(l)?.length??0)>0);return["Run the emit-screenshot-spec skill to author the document360-capture spec for EACH of these","SCREENSHOT placeholder ids:",e.paths.map(l=>`- ${l}`).join(`
322
- `),"",...r.length>0?["REPAIR: 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).",...r.map(i),""]:[],...s.length>0?["REPAIR: 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, so 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.",...s.map(i),""]:[],...a.flatMap(l=>Yf(n.get(l),`RULE VIOLATIONS already in ${l}'s existing spec \u2014 fix every one:`)),"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.",kc,$c].join(`
323
- `)}async function Yi(e,t,n){let o=is(e),r=so(t?.cwd??process.cwd());if(r&&console.log(I.gray(r)),o.mode==="list"){let l=t?.cwd??process.cwd(),d=Tc(l,o.scope),g=Sn(l)?.docsDir??Rc,w=_e(l,d),k=Rv(l,d?{scope:d}:{});for(let S of Vi(w,{scope:d,detail:o.detail,docsDir:g,markerProblems:k}))console.log(S);return{kind:"continue"}}if(o.mode==="single"){let l=io(t?.cwd??process.cwd(),o.id),d=l===null?[]:Cc(l);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: spec path, data to`,"stage, dev requests only if any, and the capture command; no grounding narration.",kc,$c,...n?.prior?["",...Jv(n.prior)]:[],...d.length>0?["",...Yf(d,"RULE VIOLATIONS already in the existing spec \u2014 fix every one:")]:[]].join(`
324
- `),display:`/screenshot ${o.id}`}}if(o.mode==="capture"||o.mode==="annotate"||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.`,kc,$c].join(`
325
- `),a=o.mode==="scope"?`/screenshot ${o.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:i,display:a}}import{readDocsPlan as t0,readProjectConfig as n0,listOpenHints as o0,listOpenForDocs as r0,listOpenDirectives as s0,loadOpenCommentCount as i0,resolveActiveProfile as a0,DEFAULT_DOCS_DIR as l0}from"document360-engine";import{statSync as Zv}from"node:fs";import{resolve as e0}from"node:path";function Pn(e,t,n){return n.filter(o=>{try{return Zv(e0(e,t,o)).size===0}catch{return!0}})}var ao=e=>e===1?"":"s";function c0(e){try{let t=(n0(e)?.docsDir??l0).replace(/\/+$/,""),n=t0(e,t);return n.length===0?0:Pn(e,t,n.map(o=>o.path)).length}catch{return 0}}function u0(e){try{return i0(e,a0(e).name)}catch{return 0}}function d0(e){let t=s=>{try{return s().length}catch{return 0}},n=t(()=>o0(e)),o=t(()=>r0(e)),r=t(()=>s0(e));return{hints:n,messages:o,directives:r,total:n+o+r}}function sm(e,t){let n=t?.just,o=d0(e);if(o.total>0&&n!=="/catch-up"){let i=[];return o.hints>0&&i.push(`${o.hints} hint${ao(o.hints)}`),o.messages>0&&i.push(`${o.messages} message${ao(o.messages)}`),o.directives>0&&i.push(`${o.directives} request${ao(o.directives)}`),{cmd:"/catch-up",short:`Your builder left ${i.join(" and ")} waiting`,text:`Your builder left ${i.join(" and ")} waiting. /catch-up clears that first \u2014 it rewrites articles, so reviewing or sending anything up before it runs is work you would do twice.`}}let r=u0(e);if(r>0&&n!=="/comments")return{cmd:"/comments",short:`${r} reviewer comment${ao(r)} ${r===1?"is":"are"} waiting on your articles`,text:`${r} reviewer comment${ao(r)} ${r===1?"is":"are"} waiting on your articles. /comments answers ${r===1?"it":"them"} first \u2014 answering rewrites the passages they marked up, so reviewing or sending anything up before it runs is work you would do twice.`};let s=c0(e);return s>0&&n!=="/write"?{cmd:"/write",short:`${s} planned article${ao(s)} ${s===1?"is":"are"} still unwritten`,text:`${s} planned article${ao(s)} ${s===1?"is":"are"} still unwritten. /write finish${s===1?"es it":"es them"} first, so one review pass and one save cover everything together instead of running twice.`}:null}import{modernizeLegacyCommandLine as p0}from"document360-engine";var h0=new Set(["--scope","--concurrency","--model"]),f0=new Set(["/screenshot","/style-guide"]),m0=e=>e.trim().replace(/\s+/g," ").toLowerCase();function Ki(e){let t=m0(p0(e));if(!t.startsWith("/"))return null;let n=t.split(" ").filter(Boolean),o=n[0],r=1,s;f0.has(o)&&n[1]&&!n[1].startsWith("-")&&(s=n[1],r=2);let i=new Set,a;for(;r<n.length;r++){let l=n[r];if(l.startsWith("--")){let d=l.indexOf("=");if(d!==-1){let g=l.slice(0,d);i.add(g),g==="--scope"&&(a=l.slice(d+1)||void 0);continue}if(i.add(l),h0.has(l)){let g=n[r+1];g!==void 0&&!g.startsWith("-")&&(l==="--scope"&&(a=g),r++)}continue}if(l.startsWith("-")){i.add(l);continue}a??=l}return{cmd:o,...s?{sub:s}:{},flags:i,...a?{scope:a.replace(/\/+$/,"")}:{}}}function Ec(e){switch(e.cmd){case"/review":case"/lint":return e.flags.has("--fix");case"/write":return!e.flags.has("--preview")&&!e.flags.has("--dry-run");case"/comments":return e.flags.has("--answer");case"/screenshot":return e.sub==="author"||e.sub==="capture"||e.sub==="annotate"||e.sub==="verify";case"/style-guide":return e.sub==="use"||e.sub==="keep"||e.sub==="compile"||e.sub==="learn";case"/push":case"/publish":case"/convert":case"/catch-up":case"/discover":case"/document":case"/pull":case"/reorder":return!0;default:return!1}}var g0=new Set(["--all"]),w0=new Set(["--concurrency","--model","--verbose","--quiet"]),y0=new Set(["--scope"]);function im(e){return[...e.flags].filter(t=>!g0.has(t)&&!w0.has(t)&&!y0.has(t)).sort().join(" ")}function am(e,t){if(!t)return!1;let n=Ki(e),o=Ki(t);return!n||!o||n.cmd!==o.cmd||n.sub!==o.sub||!Ec(n)||im(n)!==im(o)?!1:n.scope===void 0||n.scope===o.scope}function Kt(e){return e.aborted||e.blocked||e.allEmpty||e.bailedEmpty||e.producedNothing||(e.leftBehind??0)>0||e.failed>0||e.notRun>0?!1:e.verifiedComplete?!0:e.partitions>=1}import{listRoadmap as cs,roadmapProgress as hm,stampRoadmapDone as R0}from"document360-engine";re();re();import{ROADMAP_STAGES as lm}from"document360-engine";var cm=[...lm,"other"],b0=[[/^\/screenshot\b/,"capture"],[/^\/style-guide\b/,"decide"],[/^\/genre\b/,"decide"],[/^\/scope\b/,"decide"],[/^\/discover\b/,"plan"],[/^\/plan\b/,"plan"],[/^\/audit\b/,"plan"],[/^\/write\b/,"write"],[/^\/catch-up\b/,"write"],[/^\/document\b/,"write"],[/^\/review\b/,"edit"],[/^\/comments\b/,"edit"],[/^\/lint\b/,"lint"],[/^\/push\b/,"save"],[/^\/pull\b/,"save"],[/^\/publish\b/,"golive"]];function Nc(e){let t=(e.stage??"").trim().toLowerCase();if(lm.includes(t))return t;let n=(e.run??"").trim().toLowerCase();if(n.startsWith("/")){for(let[o,r]of b0)if(o.test(n))return r}return"other"}function zi(e){return Nc(e)==="capture"}var k0={decide:"Decide",plan:"Plan",capture:"Screenshots",write:"Write",edit:"Edit",lint:"Style rules",save:"Save to Document360",golive:"Go live",other:"Other steps"};function um(e){return e.status==="done"&&!!e.replacedBy}var jc=e=>(e.run??"").trim().replace(/\s+/g," ").toLowerCase();function $0(e){let t=[];for(let o of e){let r=jc(o);r&&!t.includes(r)&&t.push(r)}let n=o=>{let r=jc(o);return r?t.indexOf(r):t.length};return e.map((o,r)=>({s:o,i:r})).sort((o,r)=>n(o.s)-n(r.s)||o.i-r.i).map(o=>o.s)}function v0(e){let t=new Map;for(let o of e){let r=Nc(o),s=t.get(r);s?s.push(o):t.set(r,[o])}let n=[];for(let o of cm){let r=t.get(o);!r||r.length===0||n.push({key:o,label:k0[o],steps:$0(r),done:r.filter(s=>s.status==="done").length})}return n}var Dc=" ",dm=e=>e.trim().toLowerCase();function x0(e,t){let n=Math.max(20,t.width-Dc.length),o=e.status==="done"?q("\u2713"):ve("\u25CB"),r=e.status==="done"?f:t.isNext?Z:g=>g,s=Vt(e.title.trim(),n);s.length===0&&s.push("");let i=[];t.showRun&&e.run?.trim()&&i.push(e.run.trim()),t.showReplaced&&e.replacedBy&&i.push(`replaced by \u201C${e.replacedBy}\u201D`);let a=i.map(g=>` \xB7 ${g}`).join(""),l=s.map((g,w)=>w===0?` ${o} ${r(g)}`:`${Dc}${r(g)}`);if(!a)return l;if((s[s.length-1]??"").length+a.length<=n)return l[l.length-1]+=ve(a),l;for(let g of i)l.push(`${Dc}${ve(`\xB7 ${g}`)}`);return l}function pm(e,t={}){let n=Math.max(40,t.width??80),o=t.all?e:e.filter(a=>!um(a)),r=e.length-o.length,s=e.filter(a=>a.status==="done").length,i=[Z(`Docs roadmap \u2014 ${s} of ${e.length} step${e.length===1?"":"s"} done`)];for(let a of v0(o)){i.push(""),i.push(` ${Be(a.label)}${ve(` \xB7 ${a.done} of ${a.steps.length}`)}`);let l="";for(let d of a.steps){let g=jc(d);i.push(...x0(d,{width:n,showRun:!!g&&g!==l,isNext:!!t.next&&dm(d.title)===dm(t.next.title),showReplaced:!!t.all&&um(d)})),l=g}}return i.push(""),i.push(t.next?`Next: ${t.next.title}${t.next.run?` \u2014 ${t.next.run}`:""}`:"Campaign complete \u2014 the docs agent adds new steps as the app changes."),r>0&&i.push(f(`(+${r} step${r===1?"":"s"} closed because a later pass replaced ${r===1?"it":"them"} \u2014 /roadmap --all lists ${r===1?"it":"them"}.)`)),i}function Ic(e,t={}){let n=cs(e);if(n.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 o=hm(e),r=pm(n,{width:t.width,all:t.all,next:o.next});return r.push(f("(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.)")),n.some(s=>s.stepId)&&r.push(f('(d360-writer keeps the wording of its own steps current \u2014 add a "keep:" line to one to leave your version alone.)')),r}function or(e,t){let n=cs(e).filter(d=>d.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=d=>d.trim().toLowerCase(),s=n.find(d=>r(d.title)===r(o)),i=o?s?[s]:n.filter(d=>r(d.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:
318
+ `);/\.waitFor\s*\(|Promise\.race\s*\(|waitForFunction\s*\(|waitForSelector\s*\(/.test(a)||o.push(r+1)}return o}function Ac(e,t){let n=w=>`line${w.length===1?"":"s"} ${w.join(", ")}`,o=[],r=t?.captureVersion===void 0?dt():t.captureVersion,s=tr(r,zf)?$c(e):[];s.length>0&&o.push(`- ${n(s)}: navigates with a bare page.goto(). EVERY navigation must go through gotoResilient (from document360-capture/helpers) \u2014 \`await gotoResilient(page)\` for the start URL, \`await gotoResilient(page, "/route")\` mid-spec. Under a bulk run goto's default "load" wait never fires and the spec dies at 60s on that line.`);let i=bc(e);i.length>0&&o.push(`- ${n(i)}: a .waitFor() whose timeout is not swallowed, so a missing prerequisite hard-fails instead of skipping. Add .catch(() => {}), then read the element and test.skip with a reason.`);let a=kc(e);a.length>0&&o.push(`- ${n(a)}: takes its own screenshot (or calls dumpAnnotations) instead of captureShot(page, PLACEHOLDER). On a cropped shot that misplaces every callout and nothing errors.`);let l=vc(e);l.length>0&&o.push(`- ${n(l)}: the "data is missing" decision rests on a fixed waitForTimeout, so staged data can read as absent. Give the element a bounded chance to appear first, then count.`);let d=yc(e);return d.length>0&&o.push(`- ${n(d)}: click({ force: true }) with no assertion that it worked, so a no-op click photographs the unchanged screen. Assert the expected result immediately after, guarded, and skip if it never arrives.`),/CAPTURE-SAFETY:/.test(e)||o.push("- no CAPTURE-SAFETY marker: add exactly one `// CAPTURE-SAFETY: readonly` or `// CAPTURE-SAFETY: mutates \u2014 <what>; cleanup: <how>` at the top."),o}function Xf(e,t){return e.length===0?[]:[t,...e,"These are SEPARATE from whatever else you were asked to fix \u2014 clear them in the same pass. They were","found by scanning the file, so they are facts about it, not suggestions.",""]}function Qf(e){return(e??"").trim().replace(/[.\s]+$/,"")}function Jf(e,t){let n=Sn(e)?.captureDir??Bi,o=Fi(n)?Ui(n,`${t}.spec.ts`):Wi(e,n,`${t}.spec.ts`);try{return Yf(Sc(o,"utf8"))}catch{return{mutates:!1,declared:!1}}}var Gv=["annotated","verified","rejected"],qv=e=>Gv.includes(e);function Vv(e){return[...new Set(e.filter(t=>qv(t.state)).map(t=>t.file))].sort()}function Hi(e,t){let n=Vv(e);if(!t)return n;let o=t.replace(/\\/g,"/").replace(/\/+$/,"");return n.filter(r=>{let s=r.replace(/\\/g,"/");return s===o||s.startsWith(`${o}/`)||s.endsWith(`/${o}`)})}function Gi(e,t){let n=e.filter(s=>s.state==="captured");if(n.length===0)return null;let o=Math.max(...n.map(s=>s.id.length)),r=n.length===1;return[`${J("\u26A0",L.yellow)}${n.length} screenshot${r?" has":"s have"} been taken but the callouts aren't drawn on yet, so ${r?"it has":"they have"} no picture to publish:`,...n.map(s=>` ${L.yellow(s.id.padEnd(o))}`),` Publishing without ${r?"it":"them"}. Finish ${r?"it":"them"} first: ${L.bold(Ce("/screenshot annotate","",t))}`].join(`
319
+ `)}function qi(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[`${J("\u26A0",L.yellow)}${t.length} screenshot${t.length===1?"":"s"} failed verification:`,...t.map(o=>` ${L.magenta(o.id.padEnd(n))} ${L.gray(or(o.reason??"no reason recorded"))}`),` Publishing anyway. Fix + re-capture: ${L.bold("/screenshot capture --failed")}`].join(`
320
+ `)}var Yv={placeholder:"\u25CB",spec:"\u25D0",blocked:"\u2298",broken:"\u2717",captured:"\u25CF",annotated:"\u25C8",verified:"\u2714",rejected:"\u2691"},Kv={placeholder:L.gray,spec:L.yellow,blocked:L.cyan,broken:L.red,captured:L.yellow,annotated:L.blue,verified:L.green,rejected:L.magenta},zv=` ${L.green("\u2714 verified")} ${L.blue("\u25C8 to verify")} ${L.yellow("\u25CF to annotate")} ${L.yellow("\u25D0 ready")} ${L.magenta("\u2691 rejected")} ${L.cyan("\u2298 blocked")} ${L.red("\u2717 broken")} ${L.gray("\u25CB to spec")}`;function J(e,t=n=>n){return`${t(e)} `}function or(e){return e.replace(/\s+/g," ").trim().replace(/^Prerequisites? not met[:—-]?\s*/i,"")}function Vi(e){let t=or(e),n=/^(.*?[a-z0-9)"'”’])\.(?:\s|$)/i.exec(t);return(n?n[1]:t).trim()}function cs(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=Vi(o),i=`${r} ${s.toLowerCase()}`,a=t.get(i)??{reason:s,blockedBy:r,ids:[]};t.has(i)||t.set(i,a),a.ids.push(n.id)}return[...t.values()].sort((n,o)=>o.ids.length-n.ids.length||n.reason.localeCompare(o.reason))}function Zf(e){let t=cs(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((a,l)=>a+l.ids.length,0);r.push(` ${L.bold("Stage this data")} ${L.gray(`\u2014 unblocks ${s} shot${s===1?"":"s"} in ${n.length} action${n.length===1?"":"s"}`)}`);let i=8;for(let a of n.slice(0,i)){let l=Vt(a.reason,86);r.push(` ${L.cyan(Cn(`${a.ids.length}\xD7`,4))} ${l[0]??""}`);for(let w of l.slice(1))r.push(` ${w}`);let d=a.ids.slice(0,4).join(" \xB7 ");r.push(L.gray(` ${d}${a.ids.length>4?` \xB7 +${a.ids.length-4} more`:""}`))}n.length>i&&r.push(L.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,a)=>i+a.ids.length,0);r.push(` ${J("\u2298",L.cyan)}${s} shot${s===1?"":"s"} need${s===1?"s":""} a data-testid from your developers \u2014 ${L.bold("/screenshot checklist")} builds the hand-off.`)}return r}function Ec(e){if(e.length===0)return[];let t=e.slice(0,6),n=e.length;return["",` ${J("\u26A0",L.yellow)}${n} screenshot marker${n===1?"":"s"} will be ignored \u2014 ${n===1?"it is":"they are"} not shaped the way the publish step needs`+L.gray(`, so ${n===1?"that picture":"those pictures"} would never be taken`),...t.map(o=>L.gray(` ${o.file}:${o.line} \u2014 ${o.reason}`)),...n>t.length?[L.gray(` \u2026and ${n-t.length} more`)]:[],L.gray(" Usually a reviewer comment wrapped around it. A marker must start its own line and carry an id:.")]}function em(e,t){let n=e.filter(i=>(i.staleAnchor?.length??0)>0);if(n.length===0)return[];let o=[...new Set(n.flatMap(i=>i.staleAnchor))],r=o.length,s=["",` ${J("\u26A0",L.yellow)}${r} selector request${r===1?"":"s"} quote${r===1?"s":""} source code that has since changed`+L.gray(" \u2014 your developers would go looking for something that isn't there any more"),L.gray(` Refresh the hand-off before sending it: ${L.bold("/screenshot checklist")}`)];return t&&s.push(L.gray(` ${o.slice(0,8).join(" \xB7 ")}${r>8?` \xB7 +${r-8} more`:""}`)),s}function tm(e,t,n){let o=e.filter(w=>(w.unguardedWaits?.length??0)>0),r=e.filter(w=>w.undeclared),s=e.filter(w=>(w.handRolled?.length??0)>0),i=e.filter(w=>(w.stalePause?.length??0)>0),a=e.filter(w=>(w.bareGoto?.length??0)>0);if(o.length===0&&r.length===0&&s.length===0&&i.length===0&&a.length===0)return[];let l=["",` ${J("\u26A0",L.yellow)}Some specs were written before later reliability fixes:`],d=(w,m)=>` ${w.slice(0,8).map(m).join(" \xB7 ")}${w.length>8?` \xB7 +${w.length-8} more`:""}`;if(o.length>0){let w=o.length;l.push(L.gray(` ${w} crash${w===1?"es":""} instead of telling you what to stage when the data ${w===1?"it needs":"they need"} is missing`)),t&&l.push(L.gray(d(o,m=>`${m.id}:${m.unguardedWaits.join(",")}`)))}if(a.length>0){let w=a.length;l.push(L.gray(` ${w} open${w===1?"s":""} pages the slow way, so ${w===1?"it stalls":"they stall"} for a minute and give up when several shots run at once`)),t&&l.push(L.gray(d(a,m=>`${m.id}:${m.bareGoto.join(",")}`)))}if(i.length>0){let w=i.length;l.push(L.gray(` ${w} decide${w===1?"s":""} "the data is missing" from a fixed pause, so data you HAVE staged can read as absent`)),t&&l.push(L.gray(d(i,m=>`${m.id}:${m.stalePause.join(",")}`)))}if(s.length>0){let w=s.length;l.push(L.gray(` ${w} take${w===1?"s":""} ${w===1?"its":"their"} own screenshot instead of the one call that positions the callouts too \u2014 on a cropped shot the numbers land in the wrong places, and nothing reports it`)),t&&l.push(L.gray(d(s,m=>`${m.id}:${m.handRolled.join(",")}`)))}if(r.length>0){let w=r.length,m=r.filter($=>$.mutates).length;l.push(L.gray(` ${w} do${w===1?"es":""} not say whether ${w===1?"it changes":"they change"} data in your app`+(m>0?`, so ${m===1?"one is":`${m} are`} left out of bulk runs to be safe`:""))),t&&l.push(L.gray(d(r,$=>$.id)))}return n?.commandInLead||l.push(L.gray(` Re-write them all with the current rules: ${L.bold("/screenshot author --all")}`)),l}function nm(e){let t=e.filter(n=>(n.unverifiedForce?.length??0)>0);return t.length===0?[]:["",` ${J("\u26A0",L.red)}${t.length} spec${t.length===1?"":"s"} force-click past Playwright's safety checks without asserting the result`+L.gray(" \u2014 if the click lands on nothing, the shot photographs the unchanged screen"),L.gray(` ${t.slice(0,6).map(n=>`${n.id}:${n.unverifiedForce.join(",")}`).join(" \xB7 ")}${t.length>6?` \xB7 +${t.length-6} more`:""}`),L.gray(` Re-author to check what the click did: ${L.bold("/screenshot author <id>")}`)]}var Mi=(e,t)=>e.length>=t?e:e+" ".repeat(t-e.length),Cn=(e,t)=>e.length>=t?e:" ".repeat(t-e.length)+e;function om(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 Xv=new Set(["and","or","of","the","to","a","an","in","on","for","with","vs"]),Qv=new Set(["ai","api","cli","ui","ux","url","id","http","https","json","xml","sdk","csv","pdf","oauth","sso","mfa","io","faq"]);function Jv(e){return e.replace(/[-_]+/g," ").trim().split(/\s+/).filter(Boolean).map((n,o)=>{let r=n.toLowerCase();return Qv.has(r)?r.toUpperCase():o>0&&Xv.has(r)?r:r.charAt(0).toUpperCase()+r.slice(1)}).join(" ")}function xc(e){if(!e)return{num:"",name:"(docs root)"};let t=/^(\d+)[-_](.+)$/.exec(e);return{num:t?t[1]:"",name:Jv(t?t[2]:e)}}function Zv(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).pop()??e}function Wf(e,t,n){let o=t>0?Math.round(e/t*n):0;return L.green("\u2588".repeat(o))+L.gray("\u2591".repeat(Math.max(0,n-o)))}function e0(e,t){let n=t>0?Math.round(e/t*100):0,o=Cn(`${n}%`,4);return n===100?L.green(o):n>0?L.yellow(o):L.gray(o)}function rm(e,t){let n=new Map;for(let o of e){let r=om(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 Nc(e,t){let n=A=>e.filter(D=>D.state===A).length,o=n("captured"),r=n("placeholder"),s=n("spec"),i=n("annotated"),a=n("blocked"),l=n("broken"),d=n("rejected"),w=e.filter(A=>A.state==="spec"&&A.mutates).length,m=s>w,$=e.filter(A=>(A.unguardedWaits?.length??0)>0||(A.bareGoto?.length??0)>0).length,S=e.filter(A=>(A.stalePause?.length??0)>0||(A.handRolled?.length??0)>0).length,R=s>0||a>0||l>0,C=(A,D="")=>Ce(A,D,t);return o>0?{key:"annotate",cmd:C("/screenshot annotate")}:r>0?{key:"toSpec",cmd:t?`/screenshot author ${t}`:"/screenshot author --all"}:$>0&&R?{key:"crashy",cmd:t?`/screenshot author ${t}`:"/screenshot author --all"}:S>0&&R?{key:"wrongOutput",cmd:t?`/screenshot author ${t}`:"/screenshot author --all"}:s>0&&(m||i===0)?{key:"ready",cmd:C("/screenshot capture")}:i>0&&s>0?{key:"verify",cmd:C("/screenshot verify")}:a>0?{key:"blocked",cmd:C("/screenshot capture","--blocked")}:l>0?{key:"broken",cmd:`/screenshot ${e.find(A=>A.state==="broken").id}`}:i>0?{key:"verify",cmd:C("/screenshot verify")}:d>0?{key:"rejected",cmd:C("/screenshot capture","--failed")}:{key:"done",cmd:t?`/push ${t}`:"/push"}}function t0(e,t,n=[]){let o=(te,we)=>te.filter($e=>$e.state===we).length,r=e.length,s=o(e,"verified"),i=o(e,"annotated"),a=o(e,"captured"),l=o(e,"rejected"),d=o(e,"spec"),w=o(e,"blocked"),m=o(e,"broken"),$=o(e,"placeholder"),S=new Set(e.map(te=>te.file)).size,R=rm(e,t),C=[];C.push(` ${L.bold("Screenshots")} ${L.green(`${s}/${r} verified`)} ${L.gray("\xB7")} ${i>0?L.blue(`${i} to verify`):L.gray("0 to verify")}`+(a>0?` ${L.gray("\xB7")} ${L.yellow(`${a} to annotate`)}`:"")+(l>0?` ${L.gray("\xB7")} ${L.magenta(`${l} rejected`)}`:"")+` ${L.gray("\xB7")} ${d>0?L.yellow(`${d} ready`):L.gray("0 ready")}`+(w>0?` ${L.gray("\xB7")} ${L.cyan(`${w} blocked`)}`:"")+(m>0?` ${L.gray("\xB7")} ${L.red(`${m} broken`)}`:"")+` ${L.gray("\xB7")} ${$>0?L.red(`${$} to spec`):L.gray("0 to spec")} `+L.gray(`across ${S} article${S===1?"":"s"}`));let A=r>0?Math.round(s/r*100):0;C.push(` [${Wf(s,r,32)}] ${L.bold(`${A}%`)}`),C.push("");let D=R.map(([te])=>xc(te)),N=Math.min(32,Math.max(7,...D.map(te=>te.name.length))),U=te=>te.length>N?`${te.slice(0,N-1)}\u2026`:Mi(te,N),O=[...a>0?[{head:"To annotate",w:11,state:"captured",color:L.yellow}]:[],...i>0?[{head:"To verify",w:9,state:"annotated",color:L.blue}]:[],...l>0?[{head:"Rejected",w:8,state:"rejected",color:L.magenta}]:[],{head:"Ready",w:5,state:"spec",color:L.yellow},...w>0?[{head:"Blocked",w:7,state:"blocked",color:L.cyan}]:[],...m>0?[{head:"Broken",w:6,state:"broken",color:L.red}]:[],{head:"To spec",w:7,state:"placeholder",color:L.red}];C.push(L.gray(` ${Mi("#",2)} ${Mi("Chapter",N)} ${Cn("Verified",8)} ${O.map(te=>Cn(te.head,te.w)).join(" ")} Progress`));for(let[te,[,we]]of R.entries()){let $e=o(we,"verified"),Ye=we.length,{num:fn,name:mn}=D[te],At=$e===Ye,gt=U(mn),jr=O.map(tt=>{let xo=o(we,tt.state);return xo>0?tt.color(Cn(String(xo),tt.w)):L.gray(Cn("\u2014",tt.w))}).join(" ");C.push(` ${L.cyan(Mi(fn,2))} ${At?L.green(gt):$e>0?gt:L.gray(gt)} ${At?L.green(Cn(`${$e}/${Ye}`,8)):Cn(`${$e}/${Ye}`,8)} ${jr} ${Wf($e,Ye,10)} ${e0($e,Ye)}`)}C.push("");let Q=m>0?` ${L.gray("\xB7")} ${m} spec${m===1?"":"s"} broken \u2014 ${L.bold(`/screenshot ${e.find(te=>te.state==="broken").id}`)} re-authors ${m===1?"it":"the first"}`:"",z=e.filter(te=>te.state==="spec"&&te.mutates).length,de=d>z,ke=e.filter(te=>(te.unguardedWaits?.length??0)>0||(te.bareGoto?.length??0)>0).length,xe=e.filter(te=>(te.stalePause?.length??0)>0||(te.handRolled?.length??0)>0).length,Pe=d>0||w>0||m>0,fe=!1,se=Nc(e).key;if(se==="annotate")C.push(` ${J("\u25C8",L.blue)}${a} shot${a===1?"":"s"} taken but not drawn on \u2014 run ${L.bold("/screenshot annotate")}`+L.gray(` \u2014 no browser, seconds; the callouts are what make ${a===1?"it":"them"} publishable`)+Q);else if(se==="toSpec")C.push(` ${J("\u2192",L.yellow)}${$} placeholder${$===1?"":"s"} still need a spec \u2014 run ${L.bold("/screenshot author --all")}${Q}`);else if(se==="crashy")fe=!0,C.push(` ${J("\u2192",L.yellow)}${ke} spec${ke===1?"":"s"} would crash mid-run \u2014 re-write ${ke===1?"it":"them"} first: ${L.bold("/screenshot author --all")}`+L.gray(` \xB7 then ${L.bold("/screenshot capture")} (no browser time wasted on ${ke===1?"a shot":"shots"} that can't finish)`)+Q);else if(se==="wrongOutput")fe=!0,C.push(` ${J("\u2192",L.yellow)}${xe} spec${xe===1?"":"s"} would shoot the wrong thing \u2014 re-write ${xe===1?"it":"them"} first: ${L.bold("/screenshot author --all")}`+L.gray(` \xB7 then ${L.bold("/screenshot capture")} (a false skip or a misplaced callout costs the same browser time as a good shot)`)+Q);else if(se==="ready"){let te=z>0?L.gray(` \u2014 ${d-z} in one go; ${z} write${z===1?"s":""} real data and run${z===1?"s":""} one at a time`):"";C.push(` ${J("\u2192",L.yellow)}${d} spec${d===1?"":"s"} ready to capture \u2014 run ${L.bold("/screenshot capture")}${te}${Q}`)}else if(se==="verify"&&d>0)C.push(` ${J("\u2192",L.blue)}${i} shot${i===1?"":"s"} awaiting verification \u2014 run ${L.bold("/screenshot verify")}`+L.gray(" \u2014 no browser needed")+L.gray(` \xB7 ${d} ready spec${d===1?"":"s"} write real data, so ${d===1?"it runs":"each runs"} only when named: /screenshot capture <id>`)+Q);else if(se==="blocked")C.push(` ${J("\u2192",L.cyan)}${w} shot${w===1?"":"s"} blocked \u2014 stage the data below, then ${L.bold("/screenshot capture --blocked")}${Q}`);else if(se==="broken")C.push(` ${J("\u2192",L.red)}${m} spec${m===1?"":"s"} broken \u2014 ${L.bold(`/screenshot ${e.find(te=>te.state==="broken").id}`)} re-authors ${m===1?"it":"the first"} (re-capturing fails the same way)`);else if(se==="verify")C.push(` ${J("\u2192",L.blue)}${i} shot${i===1?"":"s"} awaiting verification \u2014 run ${L.bold("/screenshot verify")}`+L.gray(" \u2014 it checks each picture against what its article needs (no browser, no re-capture)"));else if(se==="rejected"){let te=e.filter(we=>we.state==="rejected"&&we.repaired).length;C.push(` ${J("\u2691",L.magenta)}${l} shot${l===1?"":"s"} failed review \u2014 `+(te>0?`${te} spec${te===1?"":"s"} already repaired; re-capture with ${L.bold("/screenshot capture --failed")}`:`see the reasons below, then ${L.bold("/screenshot capture --failed")}`))}else C.push(` ${J("\u2713",L.green)}all ${r} verified \u2014 ${L.bold("/push")} embeds them in the articles`);if(s>0&&s<r){let te=R.filter(([,we])=>we.every($e=>$e.state!=="verified")).map(([we])=>{let{num:$e,name:Ye}=xc(we);return $e?`${$e} ${Ye}`:Ye});te.length>0&&C.push(L.gray(` Furthest behind: ${te.slice(0,5).join(" \xB7 ")}${te.length>5?" \u2026":""} (0% verified)`))}return C.push(...Zf(e),...nm(e),...tm(e,!1,{commandInLead:fe}),...em(e,!1),...Ec(n)),C.push(""),C.push(L.gray(" Drill in: /screenshot list <chapter#> \xB7 /screenshot list --detail (all)")),C}function n0(e,t,n,o=[]){let r=new Set(e.map(d=>d.file)),s=e.filter(d=>d.state==="verified").length,i=e.filter(d=>d.state==="annotated").length,a=e.filter(d=>d.state==="captured").length,l=[` ${L.bold("Screenshots")}: ${e.length} placeholder${e.length===1?"":"s"} across ${r.size} article${r.size===1?"":"s"} \xB7 ${L.green(`${s} verified`)}${i>0?L.blue(` \xB7 ${i} to verify`):""}${a>0?L.yellow(` \xB7 ${a} to annotate`):""}${n?L.gray(` \xB7 scope ${n}`):""}`,""];for(let[d,w]of rm(e,t)){let m=w.filter(A=>A.state==="verified").length,{num:$,name:S}=xc(d),R=$?`${$} \xB7 ${S}`:S;l.push(` ${L.bold(R)} ${L.gray(`(${m}/${w.length})`)}`);let C=new Map;for(let A of w){let D=Zv(A.file),N=C.get(D)??[];C.has(D)||C.set(D,N),N.push(A)}for(let A of[...C.keys()].sort()){l.push(L.gray(` ${A}`));for(let D of C.get(A)){let N=Kv[D.state];if(l.push(` ${J(Yv[D.state],N)}${N(D.id)}`),(D.state==="blocked"||D.state==="broken"||D.state==="rejected")&&D.reason){for(let U of Vt(or(D.reason),84))l.push(L.gray(` ${U}`));D.state==="rejected"&&l.push(L.gray(` ${D.repaired?"spec repaired \u2014 re-capture to confirm":"spec not yet repaired"}`))}}}}return l.push(...Zf(e),...nm(e),...tm(e,!0),...em(e,!0),...Ec(o)),l.push("",zv),l}function Yi(e,t){let n=t?.scope,o=t?.markerProblems??[];if(e.length===0)return[n?`No screenshot placeholders under ${n}.`:"No screenshot placeholders found in the docs.",...Ec(o)];let r=t?.docsDir??Tc;return t?.detail||n?n0(e,r,n,o):t0(e,r,o)}function Dc(e,t){if(!t||!/^\d+$/.test(t))return t;let n=Sn(e)?.docsDir??Tc,o=String(Number(t));for(let{file:r}of Hf(e)){let s=om(r,n),i=/^(\d+)/.exec(s);if(i&&String(Number(i[1]))===o)return s}return t}function sm(e,t){let r=e.map(a=>" ".repeat(a.depth)+a.label),s=Math.max(0,...e.map((a,l)=>a.note?_i(r[l]):0)),i=Math.min(s,Math.max(0,t-2-24));return e.map((a,l)=>{let d=r[l];if(!a.note)return{head:d,note:""};let w=Math.max(2,i+2-_i(d)),m=a.note.trim(),$=t-_i(d)-w;return{head:d+" ".repeat(w),note:$>1&&_i(m)>$?`${m.slice(0,$-1)}\u2026`:m}})}function o0(e){let t=e.replace(/\\/g,"/").split("/").filter(Boolean),n=t.pop()??e;return{category:t.pop()??"(docs root)",article:n}}function nr(e,t,n){let o=new Map;for(let s of t){let{category:i,article:a}=o0(s.file),l=o.get(i)??new Map;o.set(i,l);let d=l.get(a)??[];l.set(a,d),d.push(s)}let r=s=>n!=="capture"||!s.mutates;for(let s of[...o.keys()].sort()){let i=o.get(s),a=[...i.values()].flat().filter(r).map(d=>d.id),l=a.length>0;l&&e.push({kind:"category",action:n,label:`${s} (${a.length})`,ids:a,depth:1});for(let d of[...i.keys()].sort()){let w=i.get(d),m=w.filter(r).map(R=>R.id),$=m.length>0;$&&e.push({kind:"article",action:n,label:`${d} (${m.length})`,ids:m,depth:l?2:1});let S=(l?1:0)+($?1:0)+1;for(let R of w){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:S,...C?{note:C}:{}})}}}}function wc(e){return e?or(e):""}function jc(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((a,l)=>a.id.localeCompare(l.id)))e.push({kind:"shot",action:"capture",label:i.id,ids:[i.id],depth:1,note:` \u2298 ${wc(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((a,l)=>a.id.localeCompare(l.id)))e.push({kind:"shot",action:"author",label:i.id,ids:[i.id],depth:1,note:` \u2717 re-authors \u2014 ${wc(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((a,l)=>a.id.localeCompare(l.id))){let a=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 ${a} \u2014 ${wc(i.reason)}`})}}function im(e){let t=e.filter(i=>i.state==="placeholder"),n=e.filter(i=>i.state==="spec"),o=[];t.length>1&&o.push({kind:"all",action:"author",label:`Author all ${t.length} remaining specs`,ids:t.map(i=>i.id),depth:0}),nr(o,t,"author");let r=n.filter(i=>!i.mutates);r.length>1&&o.push({kind:"all",action:"capture",label:`Capture all ${r.length} ready specs`,ids:r.map(i=>i.id),depth:0}),nr(o,n,"capture");let s=e.filter(i=>i.state==="captured");return s.length>1&&o.push({kind:"all",action:"annotate",label:`Draw the callouts on all ${s.length} shots`,ids:s.map(i=>i.id),depth:0}),nr(o,s,"annotate"),jc(o,e.filter(i=>i.state==="blocked"),e.filter(i=>i.state==="broken"),e.filter(i=>i.state==="rejected")),o}var Rc=["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 captureShot() 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."," (f) An element that is RENDERED can still be EMPTY. A component may mount an input/textarea/pane",' with no content and fill it when its fetch resolves, so waitFor({state:"visible"}) proves the'," node exists, not that the data arrived \u2014 reading inputValue()/textContent() right after can"," catch the pre-fetch empty state and false-skip data that IS there. When the decision rests on"," a VALUE rather than on presence, wait for the value: page.waitForFunction(sel => { const el =",' document.querySelector(sel); return !!el && (el.value ?? el.textContent ?? "").trim() !== ""; },',' "<selector>", { timeout: 10_000 }).catch(() => {}) \u2014 THEN read it and skip on empty.'," (g) NEVER take the screenshot yourself. `captureShot(page, PLACEHOLDER)` is the only capture call:"," it shoots AND resolves the callout positions in one pass, so they cannot disagree. A"," page.screenshot()/locator.screenshot() + dumpAnnotations() pair measures coordinates against"," the whole page while a cropped image starts at the crop corner, so every pin and highlight is"," offset \u2014 and nothing errors, so the spec reports success and the picture is wrong."," (h) EVERY navigation goes through `gotoResilient` (from document360-capture/helpers), never a bare",' page.goto(): `await gotoResilient(page)` for the start URL, `gotoResilient(page, "/route")`',` mid-spec. Under a bulk run, sibling specs saturate the network and goto's default "load" wait`," never fires \u2014 four specs died on that identical first line, each patched by hand.","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."," That consistency applies WITHIN one spec too, and a spec with 2+ test.skip calls needs two checks:"," (a) does a LATER branch's reason still HOLD, given what passing the earlier guard already proved?",` A later branch that reuses an earlier one's reason verbatim ("sign in as an owner\u2026") when`," reaching it proves that condition passed does not just read oddly \u2014 it misdiagnoses the cause"," and sends the reader to fix something that is already fine."," (b) do multiple branches for the SAME prerequisite (found 0 vs found fewer than N) open with one"," identical sentence? Divergent openings defeat the grouping even within a single spec.","Before you finish, re-read each spec you wrote and check every rule above line by line."].join(`
321
+ `);function r0(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 Cc="MANDATORY, check before you finish: every spec you write or touch must carry exactly one `// CAPTURE-SAFETY: readonly` or `// CAPTURE-SAFETY: mutates: <what it creates>; cleanup: <how>` line at the top. Re-read each file you wrote and add it if missing; a spec without it is classified by guesswork. A fail-by-design spec (the app rejects the input) is `readonly`.";function am(e,t,n){let o=e.paths,r=o.filter(l=>t?.get(l)?.outcome==="failed"),s=o.filter(l=>t?.get(l)?.outcome==="skipped"),i=l=>`- ${l}: ${t.get(l).reason.replace(/\s+/g," ").trim()}`,a=o.filter(l=>(n?.get(l)?.length??0)>0);return["Run the emit-screenshot-spec skill to author the document360-capture spec for EACH of these","SCREENSHOT placeholder ids:",e.paths.map(l=>`- ${l}`).join(`
322
+ `),"",...r.length>0?["REPAIR: 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).",...r.map(i),""]:[],...s.length>0?["REPAIR: 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, so 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.",...s.map(i),""]:[],...a.flatMap(l=>Xf(n.get(l),`RULE VIOLATIONS already in ${l}'s existing spec \u2014 fix every one:`)),"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.",Rc,Cc].join(`
323
+ `)}async function Ki(e,t,n){let o=as(e),r=io(t?.cwd??process.cwd());if(r&&console.log(L.gray(r)),o.mode==="list"){let l=t?.cwd??process.cwd(),d=Dc(l,o.scope),w=Sn(l)?.docsDir??Tc,m=_e(l,d),$=Ev(l,d?{scope:d}:{});for(let S of Yi(m,{scope:d,detail:o.detail,docsDir:w,markerProblems:$}))console.log(S);return{kind:"continue"}}if(o.mode==="single"){let l=ao(t?.cwd??process.cwd(),o.id),d=l===null?[]:Ac(l);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: spec path, data to`,"stage, dev requests only if any, and the capture command; no grounding narration.",Rc,Cc,...n?.prior?["",...r0(n.prior)]:[],...d.length>0?["",...Xf(d,"RULE VIOLATIONS already in the existing spec \u2014 fix every one:")]:[]].join(`
324
+ `),display:`/screenshot ${o.id}`}}if(o.mode==="capture"||o.mode==="annotate"||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.`,Rc,Cc].join(`
325
+ `),a=o.mode==="scope"?`/screenshot ${o.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:i,display:a}}import{readDocsPlan as a0,readProjectConfig as l0,listOpenHints as c0,listOpenForDocs as u0,listOpenDirectives as d0,loadOpenCommentCount as p0,resolveActiveProfile as h0,DEFAULT_DOCS_DIR as f0}from"document360-engine";import{statSync as s0}from"node:fs";import{resolve as i0}from"node:path";function Pn(e,t,n){return n.filter(o=>{try{return s0(i0(e,t,o)).size===0}catch{return!0}})}var lo=e=>e===1?"":"s";function m0(e){try{let t=(l0(e)?.docsDir??f0).replace(/\/+$/,""),n=a0(e,t);return n.length===0?0:Pn(e,t,n.map(o=>o.path)).length}catch{return 0}}function g0(e){try{return p0(e,h0(e).name)}catch{return 0}}function w0(e){let t=s=>{try{return s().length}catch{return 0}},n=t(()=>c0(e)),o=t(()=>u0(e)),r=t(()=>d0(e));return{hints:n,messages:o,directives:r,total:n+o+r}}function lm(e,t){let n=t?.just,o=w0(e);if(o.total>0&&n!=="/catch-up"){let i=[];return o.hints>0&&i.push(`${o.hints} hint${lo(o.hints)}`),o.messages>0&&i.push(`${o.messages} message${lo(o.messages)}`),o.directives>0&&i.push(`${o.directives} request${lo(o.directives)}`),{cmd:"/catch-up",short:`Your builder left ${i.join(" and ")} waiting`,text:`Your builder left ${i.join(" and ")} waiting. /catch-up clears that first \u2014 it rewrites articles, so reviewing or sending anything up before it runs is work you would do twice.`}}let r=g0(e);if(r>0&&n!=="/comments")return{cmd:"/comments",short:`${r} reviewer comment${lo(r)} ${r===1?"is":"are"} waiting on your articles`,text:`${r} reviewer comment${lo(r)} ${r===1?"is":"are"} waiting on your articles. /comments answers ${r===1?"it":"them"} first \u2014 answering rewrites the passages they marked up, so reviewing or sending anything up before it runs is work you would do twice.`};let s=m0(e);return s>0&&n!=="/write"?{cmd:"/write",short:`${s} planned article${lo(s)} ${s===1?"is":"are"} still unwritten`,text:`${s} planned article${lo(s)} ${s===1?"is":"are"} still unwritten. /write finish${s===1?"es it":"es them"} first, so one review pass and one save cover everything together instead of running twice.`}:null}import{modernizeLegacyCommandLine as y0}from"document360-engine";var b0=new Set(["--scope","--concurrency","--model"]),k0=new Set(["/screenshot","/style-guide"]),$0=e=>e.trim().replace(/\s+/g," ").toLowerCase();function zi(e){let t=$0(y0(e));if(!t.startsWith("/"))return null;let n=t.split(" ").filter(Boolean),o=n[0],r=1,s;k0.has(o)&&n[1]&&!n[1].startsWith("-")&&(s=n[1],r=2);let i=new Set,a;for(;r<n.length;r++){let l=n[r];if(l.startsWith("--")){let d=l.indexOf("=");if(d!==-1){let w=l.slice(0,d);i.add(w),w==="--scope"&&(a=l.slice(d+1)||void 0);continue}if(i.add(l),b0.has(l)){let w=n[r+1];w!==void 0&&!w.startsWith("-")&&(l==="--scope"&&(a=w),r++)}continue}if(l.startsWith("-")){i.add(l);continue}a??=l}return{cmd:o,...s?{sub:s}:{},flags:i,...a?{scope:a.replace(/\/+$/,"")}:{}}}function Ic(e){switch(e.cmd){case"/review":case"/lint":return e.flags.has("--fix");case"/write":return!e.flags.has("--preview")&&!e.flags.has("--dry-run");case"/comments":return e.flags.has("--answer");case"/screenshot":return e.sub==="author"||e.sub==="capture"||e.sub==="annotate"||e.sub==="verify";case"/style-guide":return e.sub==="use"||e.sub==="keep"||e.sub==="compile"||e.sub==="learn";case"/push":case"/publish":case"/convert":case"/catch-up":case"/discover":case"/document":case"/pull":case"/reorder":return!0;default:return!1}}var v0=new Set(["--all"]),x0=new Set(["--concurrency","--model","--verbose","--quiet"]),R0=new Set(["--scope"]);function cm(e){return[...e.flags].filter(t=>!v0.has(t)&&!x0.has(t)&&!R0.has(t)).sort().join(" ")}function um(e,t){if(!t)return!1;let n=zi(e),o=zi(t);return!n||!o||n.cmd!==o.cmd||n.sub!==o.sub||!Ic(n)||cm(n)!==cm(o)?!1:n.scope===void 0||n.scope===o.scope}function Kt(e){return e.aborted||e.blocked||e.allEmpty||e.bailedEmpty||e.producedNothing||(e.leftBehind??0)>0||e.failed>0||e.notRun>0?!1:e.verifiedComplete?!0:e.partitions>=1}import{listRoadmap as us,roadmapProgress as gm,stampRoadmapDone as E0}from"document360-engine";re();re();import{ROADMAP_STAGES as dm}from"document360-engine";var pm=[...dm,"other"],C0=[[/^\/screenshot\b/,"capture"],[/^\/style-guide\b/,"decide"],[/^\/genre\b/,"decide"],[/^\/scope\b/,"decide"],[/^\/discover\b/,"plan"],[/^\/plan\b/,"plan"],[/^\/audit\b/,"plan"],[/^\/write\b/,"write"],[/^\/catch-up\b/,"write"],[/^\/document\b/,"write"],[/^\/review\b/,"edit"],[/^\/comments\b/,"edit"],[/^\/lint\b/,"lint"],[/^\/push\b/,"save"],[/^\/pull\b/,"save"],[/^\/publish\b/,"golive"]];function Lc(e){let t=(e.stage??"").trim().toLowerCase();if(dm.includes(t))return t;let n=(e.run??"").trim().toLowerCase();if(n.startsWith("/")){for(let[o,r]of C0)if(o.test(n))return r}return"other"}function Xi(e){return Lc(e)==="capture"}var S0={decide:"Decide",plan:"Plan",capture:"Screenshots",write:"Write",edit:"Edit",lint:"Style rules",save:"Save to Document360",golive:"Go live",other:"Other steps"};function hm(e){return e.status==="done"&&!!e.replacedBy}var _c=e=>(e.run??"").trim().replace(/\s+/g," ").toLowerCase();function P0(e){let t=[];for(let o of e){let r=_c(o);r&&!t.includes(r)&&t.push(r)}let n=o=>{let r=_c(o);return r?t.indexOf(r):t.length};return e.map((o,r)=>({s:o,i:r})).sort((o,r)=>n(o.s)-n(r.s)||o.i-r.i).map(o=>o.s)}function T0(e){let t=new Map;for(let o of e){let r=Lc(o),s=t.get(r);s?s.push(o):t.set(r,[o])}let n=[];for(let o of pm){let r=t.get(o);!r||r.length===0||n.push({key:o,label:S0[o],steps:P0(r),done:r.filter(s=>s.status==="done").length})}return n}var Oc=" ",fm=e=>e.trim().toLowerCase();function A0(e,t){let n=Math.max(20,t.width-Oc.length),o=e.status==="done"?q("\u2713"):Re("\u25CB"),r=e.status==="done"?f:t.isNext?Z:w=>w,s=Vt(e.title.trim(),n);s.length===0&&s.push("");let i=[];t.showRun&&e.run?.trim()&&i.push(e.run.trim()),t.showReplaced&&e.replacedBy&&i.push(`replaced by \u201C${e.replacedBy}\u201D`);let a=i.map(w=>` \xB7 ${w}`).join(""),l=s.map((w,m)=>m===0?` ${o} ${r(w)}`:`${Oc}${r(w)}`);if(!a)return l;if((s[s.length-1]??"").length+a.length<=n)return l[l.length-1]+=Re(a),l;for(let w of i)l.push(`${Oc}${Re(`\xB7 ${w}`)}`);return l}function mm(e,t={}){let n=Math.max(40,t.width??80),o=t.all?e:e.filter(a=>!hm(a)),r=e.length-o.length,s=e.filter(a=>a.status==="done").length,i=[Z(`Docs roadmap \u2014 ${s} of ${e.length} step${e.length===1?"":"s"} done`)];for(let a of T0(o)){i.push(""),i.push(` ${Be(a.label)}${Re(` \xB7 ${a.done} of ${a.steps.length}`)}`);let l="";for(let d of a.steps){let w=_c(d);i.push(...A0(d,{width:n,showRun:!!w&&w!==l,isNext:!!t.next&&fm(d.title)===fm(t.next.title),showReplaced:!!t.all&&hm(d)})),l=w}}return i.push(""),i.push(t.next?`Next: ${t.next.title}${t.next.run?` \u2014 ${t.next.run}`:""}`:"Campaign complete \u2014 the docs agent adds new steps as the app changes."),r>0&&i.push(f(`(+${r} step${r===1?"":"s"} closed because a later pass replaced ${r===1?"it":"them"} \u2014 /roadmap --all lists ${r===1?"it":"them"}.)`)),i}function Mc(e,t={}){let n=us(e);if(n.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 o=gm(e),r=mm(n,{width:t.width,all:t.all,next:o.next});return r.push(f("(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.)")),n.some(s=>s.stepId)&&r.push(f('(d360-writer keeps the wording of its own steps current \u2014 add a "keep:" line to one to leave your version alone.)')),r}function rr(e,t){let n=us(e).filter(d=>d.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=d=>d.trim().toLowerCase(),s=n.find(d=>r(d.title)===r(o)),i=o?s?[s]:n.filter(d=>r(d.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:
326
326
  ${i.map(d=>` \u25CB ${d.title}`).join(`
327
327
  `)}`};if(i.length===0)return{ok:!1,line:`No open step matches "${o}". Open steps:
328
328
  ${n.map(d=>` \u25CB ${d.title}`).join(`
329
- `)}`};let a=i[0].title;R0(e,a,{doneAt:new Date().toISOString()});let l=hm(e)?.next;return{ok:!0,line:`\u2713 Marked done: ${a}${l?` \u2014 next up: ${l.title}${l.run?` (${l.run})`:""}`:" \u2014 that was the last step: campaign complete."}`}}function fm(e,t){let n=r=>r.trim().replace(/\s+/g," ").toLowerCase(),o=n(t);return o.startsWith("/")?cs(e).find(r=>r.status==="open"&&!!r.run&&n(r.run)===o)??null:null}function mm(e,t){let n=(Array.isArray(t)?t:[t]).filter(s=>s.trim().startsWith("/"));if(n.length===0)return[];let o=new Set,r=[];for(let s of cs(e))s.status==="open"&&n.some(i=>am(i,s.run))&&(o.has(s.title)||(o.add(s.title),r.push(s.title)));return r}function vt(e,t){if(!t)return[];try{let n=mm(e,t).filter(o=>or(e,o).ok);return n.length===0?[]:n.length===1?[`\u2713 That completed a docs-campaign step \u2014 marked done: ${n[0]}`]:[`\u2713 That completed ${n.length} docs-campaign steps \u2014 marked done:`,...n.map(o=>` \u2022 ${o}`)]}catch{return[]}}function Xi(e,t){let n=mm(e,t);if(n.length===0)return null;let o=n.map(r=>`"${r}"`).join(", ");return[n.length===1?`Note: this command executes the open docs-roadmap step ${o}.`:`Note: this command executes ${n.length} open docs-roadmap steps: ${o}.`,`Close the loop IN THE SAME TURN the goal state is reached: call d360_roadmap_done with exactly the title of EACH step it completed (${o}), then tell the user they are marked done \u2014 including when you find the goal already holds ("no action needed" completes the STEP, not just the turn). Leave one open ONLY if its work is genuinely incomplete, and say exactly what remains.`].join(`
330
- `)}function gm(e,t){let n=t.trim().toLowerCase();if(!n)return null;let o=cs(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:
329
+ `)}`};let a=i[0].title;E0(e,a,{doneAt:new Date().toISOString()});let l=gm(e)?.next;return{ok:!0,line:`\u2713 Marked done: ${a}${l?` \u2014 next up: ${l.title}${l.run?` (${l.run})`:""}`:" \u2014 that was the last step: campaign complete."}`}}function wm(e,t){let n=r=>r.trim().replace(/\s+/g," ").toLowerCase(),o=n(t);return o.startsWith("/")?us(e).find(r=>r.status==="open"&&!!r.run&&n(r.run)===o)??null:null}function ym(e,t){let n=(Array.isArray(t)?t:[t]).filter(s=>s.trim().startsWith("/"));if(n.length===0)return[];let o=new Set,r=[];for(let s of us(e))s.status==="open"&&n.some(i=>um(i,s.run))&&(o.has(s.title)||(o.add(s.title),r.push(s.title)));return r}function vt(e,t){if(!t)return[];try{let n=ym(e,t).filter(o=>rr(e,o).ok);return n.length===0?[]:n.length===1?[`\u2713 That completed a docs-campaign step \u2014 marked done: ${n[0]}`]:[`\u2713 That completed ${n.length} docs-campaign steps \u2014 marked done:`,...n.map(o=>` \u2022 ${o}`)]}catch{return[]}}function Qi(e,t){let n=ym(e,t);if(n.length===0)return null;let o=n.map(r=>`"${r}"`).join(", ");return[n.length===1?`Note: this command executes the open docs-roadmap step ${o}.`:`Note: this command executes ${n.length} open docs-roadmap steps: ${o}.`,`Close the loop IN THE SAME TURN the goal state is reached: call d360_roadmap_done with exactly the title of EACH step it completed (${o}), then tell the user they are marked done \u2014 including when you find the goal already holds ("no action needed" completes the STEP, not just the turn). Leave one open ONLY if its work is genuinely incomplete, and say exactly what remains.`].join(`
330
+ `)}function bm(e,t){let n=t.trim().toLowerCase();if(!n)return null;let o=us(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:
331
331
  ${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(`
332
- `):null}async function wm(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let o=or(n,e.slice(1).join(" ").trim());return console.log(o.ok?q(o.line):H(o.line)),{kind:"continue"}}for(let o of Ic(n,{all:e.some(r=>r.toLowerCase()==="--all")}))console.log(o);return{kind:"continue"}}var bm={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 pushing overwrites the portal edit"};function Oc(e){return e.filter(t=>t.path!==null&&t.status in bm&&!t.link).map(t=>({path:t.path,label:bm[t.status]}))}function lo(e){let t=Oc(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 us(e){let t=e!==1;return`\u26A0 ${e} conflict${t?"s":""} NOT pushed (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 /push <path> to keep yours, /pull <path> to take the portal's).`}function rr(e,t){let n=E0(e,t).length;return n===0?null:`\u2139 ${n} article${n===1?"":"s"} ${n===1?"is":"are"} saved on Document360 as a draft and not live yet \u2014 readers still see the previous version. /publish takes ${n===1?"it":"them"} live once ${n===1?"it has":"they have"} been signed off.`}function Ji(e){return e.filter(t=>t.link).length}function _c(e,t){try{let n=km(e,Lc(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=F0(C0(S0(e,r),"utf8"),r,n).unresolved}catch{}return o===0?null:`\u2139 ${o} cross-link${o===1?"":"s"} point to pages that aren't on Document360 yet \u2014 they show as plain text for now and turn into links once those pages are pushed.`}catch{return null}}function Pm(e,t=[]){let n=[];e.length>1&&n.push({kind:"all",label:`Push 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,a)=>i.path.localeCompare(a.path));n.push({kind:"category",label:`${Rn(r)} (${s.length})`,paths:s.map(i=>i.path),indent:!1});for(let i of s){let a=i.path.replace(/\\/g,"/").split("/").pop()??i.path;n.push({kind:"article",label:a,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}async function ds(e,t){try{let n=Lc(e,t),o=n.project.projectId,r=n.project.workspaceId;if(!o||!r)return null;let s=await M0({profile:n.name,connection:n.connection,projectId:o,projectName:n.project.projectName},{cwd:e,profile:n.name,projectPath:`/v3/projects/${o}`,workspaceId:r,verifyHidden:!1});if(s.kind!=="created")return null;if(s.hidden!=="confirmed"){let i=s.seeded.length===0?" Its internal articles were NOT created, because that would put docs-agent scaffolding in front of your readers.":"";return`\u26A0 Created the "${ym}" folder on Document360 for reviewer feedback, but could NOT confirm it is hidden from readers.${i} Open its category settings in the portal and turn on "Hide from readers", then run /catch-up.`}return`\u2139 Created a hidden "${ym}" folder on Document360 \u2014 it's where your reviewers leave feedback for d360-writer to action (confirmed hidden from readers; its README explains how). /catch-up picks up what they write.`}catch{return null}}var xt="--skip-review";function ps(e,t){return N0(e,t)}function Zi(e,t){try{return ps(e,vm(e,t)).length}catch{return 0}}function Bt(e,t,n="",o,r){let s=Zi(e,o),i=ea(e,o),a=o?` ${o}`:"",l=o?"/push":"/push --all",d=sm(e,{just:r}),g=!!o&&o.endsWith(".md"),w=d&&g?` (${d.short} \u2014 ${d.cmd} once this page is delivered.)`:"";if(d&&!g){let v=s>0?` (${s} article${s===1?"":"s"}${o&&!o.endsWith(".md")?` in ${o}`:""} ${s===1?"carries":"carry"} text no editor has read, so ${s===1?"it cannot":"they cannot"} be sent up until /review${a} --blocked --fix runs \u2014 that can wait until the writing is done.)`:i>0?` (${i} article${i===1?"":"s"} break${i===1?"s":""} house style rules that block sending up \u2014 /lint${a} --blocked --fix clears that whenever you want.)`:"";return{text:`${n}${d.text}${v}`,cmd:d.cmd}}if(s===0&&i===0)return w?{...t,text:`${t.text}${w}`}:t;let k=o&&!o.endsWith(".md")?` in ${o}`:"";if(s>0){let v=s===1?"":"s",C=i>0?` ${i} also break house style rules \u2014 /lint${a} --blocked --fix clears those afterwards.`:"",T=`/review${a} --blocked --fix`;return{text:`${n}${s} article${v}${k} ${s===1?"carries":"carry"} text no editor has read, so pushing ${s===1?"it is":"them is"} blocked. ${T} reads ${s===1?"it":"just those"} and applies its fixes.${C} Then ${l}.${w}`,cmd:T}}return{text:`${n}${i} article${i===1?"":"s"}${k} break${i===1?"s":""} house style rules that block publishing. /lint${a} --blocked --fix corrects them in place \u2014 finding them costs nothing \u2014 then ${l}.${w}`,cmd:`/lint${a} --blocked --fix`}}function ea(e,t){try{return $m(e,vm(e,t)).length}catch{return 0}}function Tm(e,t){return $m(e,t)}function Mc(e,t,n){try{let o=km(e,Lc(e,n).name);if(!o)return 0;let r=i=>i.replace(/\\/g,"/"),s=new Set(Object.keys(o.articles??{}).map(r));return t.filter(i=>s.has(r(i))).length}catch{return 0}}function Fc(e,t){let n=`/push${t.scope?` ${t.scope}`:" --all"}`,o=l=>`${l} article${l===1?"":"s"}`,r=[],s=e.pushed.length,i=t.elapsedMs!==void 0?` \xB7 ${W0(t.elapsedMs)}`:"",a=e.screenshotsUploaded>0?` \xB7 ${e.screenshotsUploaded} screenshot${e.screenshotsUploaded===1?"":"s"} uploaded`:"";if(s===0&&e.failed.length===0?r.push("Nothing was pushed \u2014 no articles were sent."):t.recorded<s?(r.push(`Pushed ${t.recorded}/${o(s)}${a}${i}.`),r.push(`${s-t.recorded} article${s-t.recorded===1?"":"s"} reported success but ${s-t.recorded===1?"is":"are"} not recorded in the category map \u2014 re-run ${n}.`)):(r.push(`Pushed ${o(s)}${e.created>0?` (${e.created} new)`:""}${a}${i}.`),r.push(`Saved on Document360 as draft${s===1?"":"s"} \u2014 readers don't see ${s===1?"it":"them"} until /publish takes ${s===1?"it":"them"} live.`)),e.failed.length>0){let l=e.failed.filter(d=>d.refused);r.push(`${e.failed.length} article${e.failed.length===1?"":"s"} could not be pushed:`);for(let d of e.failed)r.push(` \u2717 ${d.path} \u2014 ${d.error}`);l.length<e.failed.length&&r.push(`Re-run ${n} to retry the rest \u2014 articles already saved are sent again only if they changed.`)}if(e.notRun.length>0&&r.push(`\u26A0 ${o(e.notRun.length)} never started (the run was stopped): ${U0(e.notRun)}`),e.missingShots.length>0){let l=e.missingShots.flatMap(d=>d.ids);r.push(`\u26A0 ${l.length} screenshot${l.length===1?"":"s"} in ${o(e.missingShots.length)} ${l.length===1?"has":"have"} not been taken, so the description was published instead: /screenshot capture`)}return t.conflictsSkipped&&t.conflictsSkipped>0&&r.push(us(t.conflictsSkipped)),r}var U0=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`;function W0(e){let t=Math.round(e/1e3);return t<60?`${t}s`:`${Math.floor(t/60)}m ${String(t%60).padStart(2,"0")}s`}async function Wt(e,t,n=0,o){let r=D0(e.cwd,t,{allowUnreviewed:o?.skipReview===!0,allowStyleErrors:o?.skipStyle===!0});if(!r.clear){for(let a of j0(r,t.length,{act:"push"}))console.log(H(a));return{kind:"continue"}}let s={aborted:!1,partitions:0,failed:0,notRun:0,producedNothing:!0},i=async(a,l)=>{let d=Date.now();console.log(f(l?`Resolving cross-links in ${a.length} article${a.length===1?"":"s"} whose targets published this run (second pass)\u2026`:`Pushing ${a.length} article${a.length===1?"":"s"} to Document360 (${O0} at a time)\u2026`));let g=await I0({cwd:e.cwd,...e.profileName?{profileName:e.profileName}:{},paths:a,allowProdWrites:e.allowProdWrites?.()===!0,...o?.allowUnpullable===!0?{allowUnpullable:!0}:{},onEvent:T=>{T.type==="article_done"?console.log(q(` \u2713 ${T.result.path}${T.result.action==="created"?" (new)":""}`)):T.type==="article_failed"&&console.log(O(` \u2717 ${T.failure.path} \u2014 ${T.failure.error}`))}});console.log("");let w=Mc(e.cwd,a,e.profileName);l||(s={aborted:g.aborted,partitions:T0(a).length,failed:g.failed.length,notRun:g.notRun.length,producedNothing:g.pushed.length===0,verifiedComplete:w>=a.length,leftBehind:n});let k=g.pushed.length>0;for(let T of Fc(g,{recorded:w,elapsedMs:Date.now()-d,...l?{}:{conflictsSkipped:n},...o?.scope?{scope:o.scope}:{}}))console.log(k&&g.failed.length===0?q(T):H(T));if(!k)return g.aborted;let S=_c(e.cwd,e.profileName);S&&console.log(f(S));let v=rr(e.cwd,e.profileName);v&&console.log(f(v));try{let T=Rm(await xm({cwd:e.cwd,profileName:e.profileName,onRateLimit:D=>console.log(f(` Document360 rate limit \u2014 waiting ${Math.ceil(D.waitMs/1e3)}s\u2026`))}));T&&console.log(T.startsWith("\u26A0")?H(T):f(T))}catch{}try{let T=Sm(await Cm({cwd:e.cwd,profileName:e.profileName}));T&&console.log(f(T))}catch{}let C=await ds(e.cwd,e.profileName);return C&&console.log(f(C)),g.aborted};try{if(!await i(t,!1)){let l=await Uc(e.cwd,e.profileName,t);if(l.length>0&&await i(l,!0),Kt(s))for(let d of vt(e.cwd,o?.scope?`/push ${o.scope}`:"/push --all"))console.log(q(d))}}catch(a){console.log(O(`Push run failed: ${a.message}`))}return console.log(""),{kind:"continue"}}async function ta(e,t,n){let o=A0(e,n);if(o.length===0)return[];let r=new Set(Oc((await Qi({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function Uc(e,t,n){try{let o=new Set(n),r=await Qi({cwd:e,profileName:t});return Oc(r.entries).map(s=>s.path).filter(s=>o.has(s))}catch{return[]}}async function B0(e,t,n){try{let o=await L0({cwd:e,...t?{profileName:t}:{},relPath:n.replace(/\\/g,"/"),preview:!0});console.log(""),console.log(q(`${o.title}`)),console.log(f(`${o.path} \xB7 ${o.articleId?`updates article ${o.articleId}`:"would be created as a new article"}`)),o.shots.length>0&&console.log(f(`${o.shots.length} screenshot${o.shots.length===1?"":"s"} embedded: ${o.shots.map(r=>r.id).join(", ")}`)),o.missingShots.length>0&&console.log(H(`\u26A0 ${o.missingShots.length} screenshot${o.missingShots.length===1?"":"s"} not taken yet \u2014 the description publishes instead: ${o.missingShots.join(", ")}`)),console.log(f("\u2500".repeat(Math.min(80,Math.max(20,(process.stdout.columns??80)-1))))),console.log(o.body),console.log(f("\u2500".repeat(Math.min(80,Math.max(20,(process.stdout.columns??80)-1))))),console.log(f(`Nothing was sent. Run /push ${o.path} to save it as a draft.`))}catch(o){console.log(O(o.message))}return{kind:"continue"}}async function na(e,t){let n=qe(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(O(n.reason)),{kind:"continue"};let o=e.includes(xt),r=e.includes(_0);if(e.includes("--preview")){let i=e.find(a=>!a.startsWith("--"));return i?await B0(t?.cwd??process.cwd(),t?.profileName,i):(console.log(O("Which article? Use /push --preview <path> \u2014 a preview is per article.")),{kind:"continue"})}let s=e[0];if(e.includes("--screenshots")||e.includes("--shots")){let i=t?.cwd??process.cwd(),a=e.find(S=>!S.startsWith("--")),l=_e(i),d=Bi(l,a);if(d.length===0){let S=l.filter(v=>v.state==="captured").length;return console.log(f(S>0?`${S} screenshot${S===1?" has":"s have"} been taken but the callouts aren't drawn on yet, so there is nothing to embed \u2014 /screenshot annotate finishes ${S===1?"it":"them"}.`:a?`No captured screenshots in ${a} \u2014 /push --screenshots covers the whole knowledge base.`:"No captured screenshots yet \u2014 /screenshot capture first.")),{kind:"continue"}}let g=Hi(l,a);g&&console.log(g);let w=Gi(l);w&&console.log(w);let k=Pe("","--screenshots",a).trim();return await Wt(t??{cwd:process.cwd()},d,0,{skipReview:o,skipStyle:r,scope:k})}if(s==="--related"&&e[1]){if(!t)return{kind:"continue"};let i=await ta(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return i.length===0?(console.log(q("\u2713 All related articles are already on Document360.")),{kind:"continue"}):await Wt(t,i,0,{skipReview:o,skipStyle:r,scope:`--related ${e[1]}`})}if(s==="--all"){console.log(f("Checking what needs pushing\u2026"));try{let i=await Qi({cwd:t?.cwd??process.cwd()}),{clean:a,conflicts:l}=lo(i.entries),d=Ji(i.entries),g=e.includes("--force")&&l.length>0;d>0&&console.log(H(`\u26A0 ${d} article(s) already exist on Document360 but aren't linked \u2014 left out (pushing would duplicate them). Run /catch-up or ask me to link them first.`)),l.length>0&&!g&&console.log(H(us(l.length)));let w=g?[...a,...l]:a;if(w.length===0){if(l.length>0){let S=rr(t?.cwd??process.cwd(),t?.profileName);return S&&console.log(f(S)),console.log(f("Resolve the conflicts: /resolve")),{kind:"continue"}}console.log(q(d>0?"\u2713 Nothing else is ahead of Document360 to push.":"\u2713 Nothing is ahead of Document360 \u2014 nothing to push."));let k=rr(t?.cwd??process.cwd(),t?.profileName);if(k&&console.log(f(k)),t)try{let S=Rm(await xm({cwd:t.cwd,profileName:t.profileName,onRateLimit:C=>console.log(f(` Document360 rate limit \u2014 waiting ${Math.ceil(C.waitMs/1e3)}s\u2026`))}));S&&console.log(S.startsWith("\u26A0")?H(S):f(S));let v=Sm(await Cm({cwd:t.cwd,profileName:t.profileName}));v&&console.log(f(v))}catch{}return{kind:"continue"}}return await Wt(t??{cwd:process.cwd()},w.map(k=>k.path),g?0:l.length,{skipReview:o,skipStyle:r,allowUnpullable:g})}catch(i){return console.log(O(`Could not compute sync status: ${i.message}`)),{kind:"continue"}}}if(s&&s.startsWith("--")&&(s=e.find(i=>!i.startsWith("--"))??""),!s){console.log(f("Checking what needs pushing\u2026"));let i,a=0;try{let l=await Qi({cwd:t?.cwd??process.cwd()}),{clean:d,conflicts:g}=lo(l.entries);i=d,a=g.length;let w=Ji(l.entries);if(w>0&&console.log(H(`\u26A0 ${w} article(s) already exist on Document360 but aren't linked \u2014 left out (pushing would duplicate them). Run /catch-up or ask me to link them first.`)),g.length>0&&console.log(H(us(g.length))),i.length===0&&g.length>0)return console.log(f("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(l){return console.log(O(`Could not compute sync status: ${l.message}`)),console.log(f("Push a specific article: /push <article-path>")),{kind:"continue"}}if(i.length===0)return console.log(q("\u2713 Nothing is ahead of Document360 \u2014 nothing to push.")),console.log(f(" (Articles without a sync base are unverified \u2014 push those by path if needed.)")),{kind:"continue"};if(!process.stdin.isTTY||!t){for(let l of i)console.log(` ${l.path} ${f(`(${l.label})`)}`);return console.log(f("Run: /push <article-path>")),{kind:"continue"}}try{s=await t.withPausedInput(()=>P0({message:"Push which article?",choices:[...i.length>1?[{name:`All ${i.length} candidates`,value:"--all",description:"one agent run over every candidate"}]:[],...i.map(l=>({name:l.path,value:l.path,description:l.label}))]}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}if(s==="--all")return await Wt(t,i.map(l=>l.path),a,{skipReview:o,skipStyle:r})}return await Wt(t??{cwd:process.cwd()},[s],0,{skipReview:o,skipStyle:r,scope:s})}re();import{select as G0}from"@inquirer/prompts";import{computeSyncStatus as q0,localAheadPaths as V0,pendingDrafts as Y0,publishArticleLive as K0,publishGateVerdict as z0,publishGateLines as X0,resolveActiveProfile as wI,SKIP_STYLE_FLAG as Q0,SKIP_SHOTS_FLAG as J0}from"document360-engine";var H0={check:"/check is now /lint (same command).",publish:"/publish now means taking drafts LIVE to readers \u2014 saving your local edits to Document360 is /push."},Am=new Set;function cn(e){let t=H0[e.replace(/^\//,"")];return!t||Am.has(e)?null:(Am.add(e),t)}var Z0=150,ex=e=>e>0?new Promise(t=>setTimeout(t,e)):Promise.resolve(),Bc=e=>e===1?"":"s",Wc=e=>e.replace(/\\/g,"/").split("/").pop()??e;function Hc(e){return e.includes("--screenshots")||e.includes("--shots")||e[0]==="--related"}async function Gc(e,t,n){await q0({cwd:e,profileName:t});let o=n?n.replace(/\\/g,"/").replace(/\/+$/,""):null;return Y0(e,t).filter(r=>!o||r.path===o||r.path.startsWith(`${o}/`)).map(r=>({...r,label:tx(e,r.path)}))}function tx(e,t){let n=ji(e,t)??ss(t),o=Di(t),r=o?Rn(o):"";return r?`${r} \u203A ${n}`:n}function nx(e){let t=Math.min(58,Math.max(...e.map(n=>n.label.length),20));return e.map(n=>` ${n.label.padEnd(t)} ${n.version?`draft v${n.version} \u2192 live`:"draft \u2192 live"}`)}function qc(e,t,n){let r=[`\u2713 Nothing is waiting to go live${n?` in ${n}`:""} \u2014 readers are seeing the latest version of every article.`],s=n?n.replace(/\\/g,"/").replace(/\/+$/,""):null,i=V0(e,t).filter(a=>!s||a===s||a.startsWith(`${s}/`)).length;return i>0&&r.push(`${i} article${Bc(i)} ${i===1?"has":"have"} local edits that aren't on Document360 yet \u2014 that's /push${n?` ${n}`:""}.`),{lines:r,ahead:i}}async function Vc(e,t,n,o={}){let r={published:[],blocked:[],failed:[]},s=0;for(let i of n){o.onProgress?.(s,n.length,i.label);let a=await K0({articleId:i.articleId,cwd:e,profileName:t,allowUnreviewed:o.skipReview===!0,allowStyleErrors:o.skipStyle===!0});a.ok?r.published.push({path:i.path,...a.url?{url:a.url}:{}}):a.blocked?r.blocked.push({path:i.path,message:a.message}):r.failed.push({path:i.path,message:a.error.message}),s+=1,s<n.length&&await ex(Z0)}return r}function Yc(e){let{published:t,blocked:n,failed:o}=e,r=[];if(t.length>0){r.push(`\u2713 ${t.length} article${Bc(t.length)} ${t.length===1?"is":"are"} now live \u2014 readers see ${t.length===1?"it":"them"} now.`);let s=t.filter(i=>i.url);for(let i of s.slice(0,3))r.push(` \u2B95 ${i.url}`);s.length>3&&r.push(` \u2B95 \u2026and ${s.length-3} more`)}if(n.length>0){r.push(`\u2717 ${n.length} refused by the publish gates \u2014 still ${n.length===1?"a draft":"drafts"}, nothing was lost:`);for(let s of n.slice(0,3))r.push(` \xB7 ${Wc(s.path)}`);n.length>3&&r.push(` \xB7 \u2026and ${n.length-3} more`),r.push(" /status names what is blocking each one, and the command that clears it. It costs nothing.")}if(o.length>0){r.push(`\u2717 ${o.length} failed \u2014 ${o.length===1?"it is":"they are"} still a draft, so re-running /publish retries ${o.length===1?"it":"them"}:`);for(let s of o.slice(0,3))r.push(` \xB7 ${Wc(s.path)} \u2014 ${s.message}`);o.length>3&&r.push(` \xB7 \u2026and ${o.length-3} more`)}return r.length===0&&r.push("Nothing was published."),r}async function Em(e,t){let n=t?.cwd??process.cwd(),o=cn("publish");if(Hc(e))return o&&console.log(f(`\u2192 ${o}`)),console.log(f("Running /push\u2026")),na(e,t);let r=qe(n,t?.profileName);if(!r.ok)return console.log(O(r.reason)),{kind:"continue"};o&&console.log(f(`\u2192 ${o}`));let s=e.includes(xt),i=e.includes(Q0),a=e.includes(J0),l=e.includes("--all"),d=e.find(v=>!v.startsWith("--"));console.log(f("Checking what is waiting to go live\u2026"));let g;try{g=await Gc(n,t?.profileName,d)}catch(v){return console.log(O(`Could not check Document360: ${v.message}`)),{kind:"continue"}}if(g.length===0){for(let v of qc(n,t?.profileName,d).lines)console.log(v.startsWith("\u2713")?q(v):f(v));return{kind:"continue"}}let w=z0(n,g.map(v=>v.path),{allowUnreviewed:s,allowStyleErrors:i,checkScreenshots:!0,allowPlaceholders:a});if(!w.clear){for(let v of X0(w,g.length,{scope:d,act:"publish"}))console.log(H(v));return{kind:"continue"}}console.log(""),console.log(`${g.length} draft${Bc(g.length)} ${g.length===1?"is":"are"} ahead of what readers see:`);for(let v of nx(g.slice(0,12)))console.log(f(v));g.length>12&&console.log(f(` \u2026and ${g.length-12} more`)),console.log("");let k=g;if(!l){let v=await G0({message:"Publish live to your readers?",choices:[{name:`Yes \u2014 publish all ${g.length} live`,value:"all"},...g.slice(0,8).map(C=>({name:`Just ${C.label}`,value:C.path})),{name:"No \u2014 leave them as drafts",value:"none"}]});if(v==="none")return console.log(f("Left as drafts. Nothing changed.")),{kind:"continue"};v!=="all"&&(k=g.filter(C=>C.path===v))}let S=await Vc(n,t?.profileName,k,{skipReview:s,skipStyle:i,onProgress:(v,C,T)=>console.log(f(` \u25B8 ${v+1}/${C} ${Wc(T)}\u2026`))});console.log("");for(let v of Yc(S))console.log(v.startsWith("\u2713")?q(v):v.startsWith("\u2717")?H(v):f(v));return{kind:"continue"}}import{loadKnownConflicts as ox,localArticleTitle as rx,resolveActiveProfile as sx}from"document360-engine";function ix(e,t){let n=rx(e,t);return n||(t.split(/[\\/]/).pop()??t).replace(/\.md$/,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ")}function oa(e,t){let n=[];try{n=ox(e,sx(e,t).name)}catch{return null}if(n.length===0)return null;let o=n.length,r=n.slice(0,3).map(i=>ix(e,i)),s=o>3?`${r.join(", ")} and ${o-3} more`:r.join(", ");return{paths:n,note:`\u26A0 ${o} article${o===1?"":"s"} ${o===1?"has":"have"} been changed both here and on Document360 (${s}), so your local copy is not a reliable picture of what your readers have. An audit over it could tell you to write an article that already exists, or miss one that needs your decision \u2014 so it needs ${o===1?"that":"those"} settled first.`}}var sr={cmd:"/resolve",reason:"it walks each one with you \u2014 keep yours, take the portal's, or skip"};async function hs(e){if(e?.cwd){let n=oa(e.cwd,e.profileName);if(n)return{kind:"audit-blocked",note:n.note,lead:sr}}return{kind:"forward-to-agent",prompt:["Run the gap-analysis skill against this repo.","","Follow its stages in order:","1. d360_sync_status first; 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, in plain words, never the internal status word \u2014 and tell the user to run /resolve, which walks the affected articles one at a time (keep the local copy, take the portal's, or skip). Do NOT ask them to report back to you: they will run /resolve and then /audit again.","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: 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, so backfill them.","4. Output the proposal table: | Article (path or proposed title) | Action (create | update | retire | link) | Reason | Evidence | Scope |, then stamp consumed hints.","","Do not start writing or updating any article yet; the proposal table is the deliverable."].join(`
333
- `),display:"/audit"}}re();import{readProjectConfig as ax}from"document360-engine";function Kc(){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: 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, with every claim cited to its grounding, 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;'," 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(`
334
- `)}async function Nm(e,t){let n=t?.cwd??process.cwd();return ax(n)?{kind:"forward-to-agent",prompt:Kc(),display:"/discover"}:(console.log(O("No d360-writer config here. Run /init first.")),{kind:"continue"})}re();import{checkbox as lx}from"@inquirer/prompts";import{inventoryRepo as cx,readProjectConfig as Dm,writeProjectConfig as ux}from"document360-engine";function zc(e,t){let n=Dm(e);n&&(n.authoritativeSourceFiles=t,ux(n,e))}function ra(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 jm(e,t){let n=t?.cwd??process.cwd();if(!Dm(n))return console.log(O("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=cx(n);if(o.length===0)return console.log(f('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(Z("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${f(ra(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>lx({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${ra(s)})`,value:s.path,checked:s.recommended})),pageSize:20}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}if(r.length===0)return console.log(f("Nothing selected \u2014 scope unchanged.")),{kind:"continue"};zc(n,r),console.log(q(`\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"}}re();import{confirm as kx}from"@inquirer/prompts";import{applyPull as Zc,computeSyncStatus as qm,compareRemoteSources as $x,planPull as Vm,planImport as vx,applyImport as xx,establishBaselines as Rx,rebaselineServerMeta as Cx,D360AuthError as Sx}from"document360-engine";re();var Im=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /push <path>):",paint:O,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /push <path>:",paint:H,mark:"M"},{status:"remote-ahead",header:"Changed on Document360 \u2014 pull with /pull <path> (or just /pull):",paint:Z,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:O,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:O,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint:ve,mark:"X"},{status:"untracked-local",header:"New here \u2014 not on Document360 yet (publish to add them):",paint:f,mark:"?"},{status:"untracked-remote",header:"On Document360 \u2014 not in your local docs yet (run /pull to import them):",paint:f,mark:"?"},{status:"unknown-base",header:"Tracked, not yet compared \u2014 run /pull --baseline to set a baseline (or the next publish/pull sets one):",paint:ve,mark:"\xB7"}];function dx(e){return e.path?e.path:`${e.title??"(untitled)"} ${ve(`[${e.articleId}]`)}`}function px(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 sa(e,t){let n=[],o=e.entries.filter(g=>g.link);if(o.length>0){n.push(""),n.push(Be("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let g of o)n.push(` ${H("~")} ${H(g.path??"")} ${ve(`\u2192 "${g.link.title}"`)}`)}for(let g of Im){let w=e.entries.filter(k=>k.status===g.status&&!(g.status==="untracked-local"&&k.link));if(w.length!==0){n.push(""),n.push(Be(g.header));for(let k of w)n.push(` ${g.paint(g.mark)} ${g.paint(dx(k))}${k.detail?ve(` (${k.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"},a=o.length,l=s===r?q("\u2713 everything up to date"):[r>0?q(`\u2713 ${r} up to date`):null,a>0?`${a} to link`:null,...Im.map(g=>{let w=(e.counts[g.status]??0)-(g.status==="untracked-local"?a:0);return w>0?`${w} ${i[g.status]}`:null})].filter(Boolean).join(ve(" \xB7 ")),d=t!==void 0?` \xB7 synced in ${px(t)}`:"";return n.push(l+ve(` \xB7 ${s} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${d}`)),n}import{structuredPatch as hx}from"diff";import Lm from"picocolors";var fx=80,ir=400,mx="\x1B[48;2;74;28;28m",gx="\x1B[48;2;24;66;24m",Om="\x1B[49m",Xc=e=>String(e).padStart(5);function _m(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}function Mm(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 Rt(e,t,n,o=fx){let r=v=>{let C=v.replace(/\r\n/g,`
332
+ `):null}async function km(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let o=rr(n,e.slice(1).join(" ").trim());return console.log(o.ok?q(o.line):H(o.line)),{kind:"continue"}}for(let o of Mc(n,{all:e.some(r=>r.toLowerCase()==="--all")}))console.log(o);return{kind:"continue"}}var vm={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 pushing overwrites the portal edit"};function Wc(e){return e.filter(t=>t.path!==null&&t.status in vm&&!t.link).map(t=>({path:t.path,label:vm[t.status]}))}function co(e){let t=Wc(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 ds(e){let t=e!==1;return`\u26A0 ${e} conflict${t?"s":""} NOT pushed (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 /push <path> to keep yours, /pull <path> to take the portal's).`}function sr(e,t){let n=O0(e,t).length;return n===0?null:`\u2139 ${n} article${n===1?"":"s"} ${n===1?"is":"are"} saved on Document360 as a draft and not live yet \u2014 readers still see the previous version. /publish takes ${n===1?"it":"them"} live once ${n===1?"it has":"they have"} been signed off.`}function Zi(e){return e.filter(t=>t.link).length}function Bc(e,t){try{let n=Rm(e,Uc(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=V0(N0(D0(e,r),"utf8"),r,n).unresolved}catch{}return o===0?null:`\u2139 ${o} cross-link${o===1?"":"s"} point to pages that aren't on Document360 yet \u2014 they show as plain text for now and turn into links once those pages are pushed.`}catch{return null}}function Nm(e,t=[]){let n=[];e.length>1&&n.push({kind:"all",label:`Push 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,a)=>i.path.localeCompare(a.path));n.push({kind:"category",label:`${Rn(r)} (${s.length})`,paths:s.map(i=>i.path),indent:!1});for(let i of s){let a=i.path.replace(/\\/g,"/").split("/").pop()??i.path;n.push({kind:"article",label:a,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}async function ps(e,t){try{let n=Uc(e,t),o=n.project.projectId,r=n.project.workspaceId;if(!o||!r)return null;let s=await q0({profile:n.name,connection:n.connection,projectId:o,projectName:n.project.projectName},{cwd:e,profile:n.name,projectPath:`/v3/projects/${o}`,workspaceId:r,verifyHidden:!1});if(s.kind!=="created")return null;if(s.hidden!=="confirmed"){let i=s.seeded.length===0?" Its internal articles were NOT created, because that would put docs-agent scaffolding in front of your readers.":"";return`\u26A0 Created the "${$m}" folder on Document360 for reviewer feedback, but could NOT confirm it is hidden from readers.${i} Open its category settings in the portal and turn on "Hide from readers", then run /catch-up.`}return`\u2139 Created a hidden "${$m}" folder on Document360 \u2014 it's where your reviewers leave feedback for d360-writer to action (confirmed hidden from readers; its README explains how). /catch-up picks up what they write.`}catch{return null}}var xt="--skip-review";function hs(e,t){return _0(e,t)}function ea(e,t){try{return hs(e,Sm(e,t)).length}catch{return 0}}function Bt(e,t,n="",o,r){let s=ea(e,o),i=ta(e,o),a=o?` ${o}`:"",l=o?"/push":"/push --all",d=lm(e,{just:r}),w=!!o&&o.endsWith(".md"),m=d&&w?` (${d.short} \u2014 ${d.cmd} once this page is delivered.)`:"";if(d&&!w){let R=s>0?` (${s} article${s===1?"":"s"}${o&&!o.endsWith(".md")?` in ${o}`:""} ${s===1?"carries":"carry"} text no editor has read, so ${s===1?"it cannot":"they cannot"} be sent up until /review${a} --blocked --fix runs \u2014 that can wait until the writing is done.)`:i>0?` (${i} article${i===1?"":"s"} break${i===1?"s":""} house style rules that block sending up \u2014 /lint${a} --blocked --fix clears that whenever you want.)`:"";return{text:`${n}${d.text}${R}`,cmd:d.cmd}}if(s===0&&i===0)return m?{...t,text:`${t.text}${m}`}:t;let $=o&&!o.endsWith(".md")?` in ${o}`:"";if(s>0){let R=s===1?"":"s",C=i>0?` ${i} also break house style rules \u2014 /lint${a} --blocked --fix clears those afterwards.`:"",A=`/review${a} --blocked --fix`;return{text:`${n}${s} article${R}${$} ${s===1?"carries":"carry"} text no editor has read, so pushing ${s===1?"it is":"them is"} blocked. ${A} reads ${s===1?"it":"just those"} and applies its fixes.${C} Then ${l}.${m}`,cmd:A}}return{text:`${n}${i} article${i===1?"":"s"}${$} break${i===1?"s":""} house style rules that block publishing. /lint${a} --blocked --fix corrects them in place \u2014 finding them costs nothing \u2014 then ${l}.${m}`,cmd:`/lint${a} --blocked --fix`}}function ta(e,t){try{return Cm(e,Sm(e,t)).length}catch{return 0}}function Dm(e,t){return Cm(e,t)}function Hc(e,t,n){try{let o=Rm(e,Uc(e,n).name);if(!o)return 0;let r=i=>i.replace(/\\/g,"/"),s=new Set(Object.keys(o.articles??{}).map(r));return t.filter(i=>s.has(r(i))).length}catch{return 0}}function Gc(e,t){let n=`/push${t.scope?` ${t.scope}`:" --all"}`,o=l=>`${l} article${l===1?"":"s"}`,r=[],s=e.pushed.length,i=t.elapsedMs!==void 0?` \xB7 ${z0(t.elapsedMs)}`:"",a=e.screenshotsUploaded>0?` \xB7 ${e.screenshotsUploaded} screenshot${e.screenshotsUploaded===1?"":"s"} uploaded`:"";if(s===0&&e.failed.length===0?r.push("Nothing was pushed \u2014 no articles were sent."):t.recorded<s?(r.push(`Pushed ${t.recorded}/${o(s)}${a}${i}.`),r.push(`${s-t.recorded} article${s-t.recorded===1?"":"s"} reported success but ${s-t.recorded===1?"is":"are"} not recorded in the category map \u2014 re-run ${n}.`)):(r.push(`Pushed ${o(s)}${e.created>0?` (${e.created} new)`:""}${a}${i}.`),r.push(`Saved on Document360 as draft${s===1?"":"s"} \u2014 readers don't see ${s===1?"it":"them"} until /publish takes ${s===1?"it":"them"} live.`)),e.stopped&&r.push(`Stopped: ${e.stopped.streak} articles in a row could not reach Document360${e.notRun.length>0?`, so the remaining ${e.notRun.length} ${e.notRun.length===1?"was":"were"} not attempted`:""}.`),e.failed.length>0){let l=e.failed.filter(m=>m.refused),d=K0(e.failed,t.docsRoot),w=e.failed.length;if(d.length===1&&w>1)r.push(`${o(w)} could not be pushed \u2014 all with the same error: ${d[0].error}`),r.push(...xm(d[0].paths," \u2717 "));else{r.push(`${o(w)} could not be pushed:`);for(let m of d)m.paths.length===1?r.push(` \u2717 ${m.paths[0]} \u2014 ${m.error}`):(r.push(` \u2717 ${o(m.paths.length)} \u2014 ${m.error}`),r.push(...xm(m.paths," ")))}l.length<e.failed.length&&(e.stopped?r.push(`Nothing was lost \u2014 your articles are unchanged. Re-run ${n} when Document360 is back.`):r.push(`Re-run ${n} to retry the rest \u2014 articles already saved are sent again only if they changed.`))}if(e.notRun.length>0&&!e.stopped&&r.push(`\u26A0 ${o(e.notRun.length)} never started (the run was stopped): ${Y0(e.notRun)}`),e.missingShots.length>0){let l=e.missingShots.flatMap(d=>d.ids);r.push(`\u26A0 ${l.length} screenshot${l.length===1?"":"s"} in ${o(e.missingShots.length)} ${l.length===1?"has":"have"} not been taken, so the description was published instead: /screenshot capture`)}return t.conflictsSkipped&&t.conflictsSkipped>0&&r.push(ds(t.conflictsSkipped)),r}var Y0=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Fc=5;function xm(e,t){let n=e.slice(0,Fc).map(o=>`${t}${o}`);return e.length>Fc&&n.push(`${" ".repeat(t.length)}\u2026 +${e.length-Fc} more`),n}function K0(e,t){let n=t?`${t.replace(/\\/g,"/").replace(/\/+$/,"")}/`:null,o=s=>{let i=s.replace(/\\/g,"/");return n&&i.startsWith(n)?i.slice(n.length):i},r=new Map;for(let s of e){let i=r.get(s.error);i?i.push(o(s.path)):r.set(s.error,[o(s.path)])}return[...r.entries()].map(([s,i])=>({error:s,paths:i})).sort((s,i)=>i.paths.length-s.paths.length)}function z0(e){let t=Math.round(e/1e3);return t<60?`${t}s`:`${Math.floor(t/60)}m ${String(t%60).padStart(2,"0")}s`}async function Wt(e,t,n=0,o){let r=M0(e.cwd,t,{allowUnreviewed:o?.skipReview===!0,allowStyleErrors:o?.skipStyle===!0});if(!r.clear){for(let l of F0(r,t.length,{act:"push"}))console.log(H(l));return{kind:"continue"}}let s={aborted:!1,partitions:0,failed:0,notRun:0,producedNothing:!0},i={retryable:0,stopped:!1},a=async(l,d)=>{let w=Date.now();console.log(f(d?`Resolving cross-links in ${l.length} article${l.length===1?"":"s"} whose targets published this run (second pass)\u2026`:`Pushing ${l.length} article${l.length===1?"":"s"} to Document360 (${B0} at a time)\u2026`));let m=await U0({cwd:e.cwd,...e.profileName?{profileName:e.profileName}:{},paths:l,allowProdWrites:e.allowProdWrites?.()===!0,...o?.allowUnpullable===!0?{allowUnpullable:!0}:{},onEvent:N=>{N.type==="article_done"?console.log(q(` \u2713 ${N.result.path}${N.result.action==="created"?" (new)":""}`)):N.type==="article_failed"&&console.log(_(` \u2717 ${N.failure.path}`))}});console.log("");let $=Hc(e.cwd,l,e.profileName);d||(i={retryable:m.failed.filter(N=>!N.refused).length,stopped:!!m.stopped},s={aborted:m.aborted||!!m.stopped,partitions:I0(l).length,failed:m.failed.length,notRun:m.notRun.length,producedNothing:m.pushed.length===0,verifiedComplete:$>=l.length,leftBehind:n});let S=m.pushed.length>0;for(let N of Gc(m,{recorded:$,elapsedMs:Date.now()-w,docsRoot:G0(e.cwd),...d?{}:{conflictsSkipped:n},...o?.scope?{scope:o.scope}:{}}))console.log(S&&m.failed.length===0?q(N):H(N));let R=m.aborted||!!m.stopped;if(!S)return R;let C=Bc(e.cwd,e.profileName);C&&console.log(f(C));let A=sr(e.cwd,e.profileName);if(A&&console.log(f(A)),R)return R;try{let N=Tm(await Pm({cwd:e.cwd,profileName:e.profileName,onRateLimit:U=>console.log(f(` Document360 rate limit \u2014 waiting ${Math.ceil(U.waitMs/1e3)}s\u2026`))}));N&&console.log(N.startsWith("\u26A0")?H(N):f(N))}catch{}try{let N=Em(await Am({cwd:e.cwd,profileName:e.profileName}));N&&console.log(f(N))}catch{}let D=await ps(e.cwd,e.profileName);return D&&console.log(f(D)),R};try{if(!await a(t,!1)){let d=await qc(e.cwd,e.profileName,t);if(d.length>0&&await a(d,!0),Kt(s))for(let w of vt(e.cwd,o?.scope?`/push ${o.scope}`:"/push --all"))console.log(q(w))}}catch(l){console.log(_(`Push run failed: ${l.message}`))}if(console.log(""),i.retryable>0){let l=Ce("/push",o?.scope?"":"--all",o?.scope);return console.log(f(i.stopped?`Next: ${l} \u2014 your articles are unchanged, so it picks up where the run left off.`:`Next: ${l} \u2014 retries the ${i.retryable} article${i.retryable===1?"":"s"} that could not be saved.`)),{kind:"continue",ownNext:!0}}return{kind:"continue"}}async function na(e,t,n){let o=L0(e,n);if(o.length===0)return[];let r=new Set(Wc((await Ji({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function qc(e,t,n){try{let o=new Set(n),r=await Ji({cwd:e,profileName:t});return Wc(r.entries).map(s=>s.path).filter(s=>o.has(s))}catch{return[]}}async function X0(e,t,n){try{let o=await W0({cwd:e,...t?{profileName:t}:{},relPath:n.replace(/\\/g,"/"),preview:!0});console.log(""),console.log(q(`${o.title}`)),console.log(f(`${o.path} \xB7 ${o.articleId?`updates article ${o.articleId}`:"would be created as a new article"}`)),o.shots.length>0&&console.log(f(`${o.shots.length} screenshot${o.shots.length===1?"":"s"} embedded: ${o.shots.map(r=>r.id).join(", ")}`)),o.missingShots.length>0&&console.log(H(`\u26A0 ${o.missingShots.length} screenshot${o.missingShots.length===1?"":"s"} not taken yet \u2014 the description publishes instead: ${o.missingShots.join(", ")}`)),console.log(f("\u2500".repeat(Math.min(80,Math.max(20,(process.stdout.columns??80)-1))))),console.log(o.body),console.log(f("\u2500".repeat(Math.min(80,Math.max(20,(process.stdout.columns??80)-1))))),console.log(f(`Nothing was sent. Run /push ${o.path} to save it as a draft.`))}catch(o){console.log(_(o.message))}return{kind:"continue"}}async function oa(e,t){let n=He(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(_(n.reason)),{kind:"continue"};let o=e.includes(xt),r=e.includes(H0);if(e.includes("--preview")){let i=e.find(a=>!a.startsWith("--"));return i?await X0(t?.cwd??process.cwd(),t?.profileName,i):(console.log(_("Which article? Use /push --preview <path> \u2014 a preview is per article.")),{kind:"continue"})}let s=e[0];if(e.includes("--screenshots")||e.includes("--shots")){let i=t?.cwd??process.cwd(),a=e.find(S=>!S.startsWith("--")),l=_e(i),d=Hi(l,a);if(d.length===0){let S=l.filter(R=>R.state==="captured").length;return console.log(f(S>0?`${S} screenshot${S===1?" has":"s have"} been taken but the callouts aren't drawn on yet, so there is nothing to embed \u2014 /screenshot annotate finishes ${S===1?"it":"them"}.`:a?`No captured screenshots in ${a} \u2014 /push --screenshots covers the whole knowledge base.`:"No captured screenshots yet \u2014 /screenshot capture first.")),{kind:"continue"}}let w=Gi(l,a);w&&console.log(w);let m=qi(l);m&&console.log(m);let $=Ce("","--screenshots",a).trim();return await Wt(t??{cwd:process.cwd()},d,0,{skipReview:o,skipStyle:r,scope:$})}if(s==="--related"&&e[1]){if(!t)return{kind:"continue"};let i=await na(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return i.length===0?(console.log(q("\u2713 All related articles are already on Document360.")),{kind:"continue"}):await Wt(t,i,0,{skipReview:o,skipStyle:r,scope:`--related ${e[1]}`})}if(s==="--all"){console.log(f("Checking what needs pushing\u2026"));try{let i=await Ji({cwd:t?.cwd??process.cwd()}),{clean:a,conflicts:l}=co(i.entries),d=Zi(i.entries),w=e.includes("--force")&&l.length>0;d>0&&console.log(H(`\u26A0 ${d} article(s) already exist on Document360 but aren't linked \u2014 left out (pushing would duplicate them). Run /catch-up or ask me to link them first.`)),l.length>0&&!w&&console.log(H(ds(l.length)));let m=w?[...a,...l]:a;if(m.length===0){if(l.length>0){let S=sr(t?.cwd??process.cwd(),t?.profileName);return S&&console.log(f(S)),console.log(f("Resolve the conflicts: /resolve")),{kind:"continue"}}console.log(q(d>0?"\u2713 Nothing else is ahead of Document360 to push.":"\u2713 Nothing is ahead of Document360 \u2014 nothing to push."));let $=sr(t?.cwd??process.cwd(),t?.profileName);if($&&console.log(f($)),t)try{let S=Tm(await Pm({cwd:t.cwd,profileName:t.profileName,onRateLimit:C=>console.log(f(` Document360 rate limit \u2014 waiting ${Math.ceil(C.waitMs/1e3)}s\u2026`))}));S&&console.log(S.startsWith("\u26A0")?H(S):f(S));let R=Em(await Am({cwd:t.cwd,profileName:t.profileName}));R&&console.log(f(R))}catch{}return{kind:"continue"}}return await Wt(t??{cwd:process.cwd()},m.map($=>$.path),w?0:l.length,{skipReview:o,skipStyle:r,allowUnpullable:w})}catch(i){return console.log(_(`Could not compute sync status: ${i.message}`)),{kind:"continue"}}}if(s&&s.startsWith("--")&&(s=e.find(i=>!i.startsWith("--"))??""),!s){console.log(f("Checking what needs pushing\u2026"));let i,a=0;try{let l=await Ji({cwd:t?.cwd??process.cwd()}),{clean:d,conflicts:w}=co(l.entries);i=d,a=w.length;let m=Zi(l.entries);if(m>0&&console.log(H(`\u26A0 ${m} article(s) already exist on Document360 but aren't linked \u2014 left out (pushing would duplicate them). Run /catch-up or ask me to link them first.`)),w.length>0&&console.log(H(ds(w.length))),i.length===0&&w.length>0)return console.log(f("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(l){return console.log(_(`Could not compute sync status: ${l.message}`)),console.log(f("Push a specific article: /push <article-path>")),{kind:"continue"}}if(i.length===0)return console.log(q("\u2713 Nothing is ahead of Document360 \u2014 nothing to push.")),console.log(f(" (Articles without a sync base are unverified \u2014 push those by path if needed.)")),{kind:"continue"};if(!process.stdin.isTTY||!t){for(let l of i)console.log(` ${l.path} ${f(`(${l.label})`)}`);return console.log(f("Run: /push <article-path>")),{kind:"continue"}}try{s=await t.withPausedInput(()=>j0({message:"Push which article?",choices:[...i.length>1?[{name:`All ${i.length} candidates`,value:"--all",description:"one agent run over every candidate"}]:[],...i.map(l=>({name:l.path,value:l.path,description:l.label}))]}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}if(s==="--all")return await Wt(t,i.map(l=>l.path),a,{skipReview:o,skipStyle:r})}return await Wt(t??{cwd:process.cwd()},[s],0,{skipReview:o,skipStyle:r,scope:s})}re();import{select as J0}from"@inquirer/prompts";import{computeSyncStatus as Z0,localAheadPaths as ex,pendingDrafts as tx,publishArticleLive as nx,publishGateVerdict as ox,publishGateLines as rx,resolveActiveProfile as TI,SKIP_STYLE_FLAG as sx,SKIP_SHOTS_FLAG as ix}from"document360-engine";var Q0={check:"/check is now /lint (same command).",publish:"/publish now means taking drafts LIVE to readers \u2014 saving your local edits to Document360 is /push."},jm=new Set;function cn(e){let t=Q0[e.replace(/^\//,"")];return!t||jm.has(e)?null:(jm.add(e),t)}var ax=150,lx=e=>e>0?new Promise(t=>setTimeout(t,e)):Promise.resolve(),Yc=e=>e===1?"":"s",Vc=e=>e.replace(/\\/g,"/").split("/").pop()??e;function Kc(e){return e.includes("--screenshots")||e.includes("--shots")||e[0]==="--related"}async function zc(e,t,n){await Z0({cwd:e,profileName:t});let o=n?n.replace(/\\/g,"/").replace(/\/+$/,""):null;return tx(e,t).filter(r=>!o||r.path===o||r.path.startsWith(`${o}/`)).map(r=>({...r,label:cx(e,r.path)}))}function cx(e,t){let n=ji(e,t)??is(t),o=Di(t),r=o?Rn(o):"";return r?`${r} \u203A ${n}`:n}function ux(e){let t=Math.min(58,Math.max(...e.map(n=>n.label.length),20));return e.map(n=>` ${n.label.padEnd(t)} ${n.version?`draft v${n.version} \u2192 live`:"draft \u2192 live"}`)}function Xc(e,t,n){let r=[`\u2713 Nothing is waiting to go live${n?` in ${n}`:""} \u2014 readers are seeing the latest version of every article.`],s=n?n.replace(/\\/g,"/").replace(/\/+$/,""):null,i=ex(e,t).filter(a=>!s||a===s||a.startsWith(`${s}/`)).length;return i>0&&r.push(`${i} article${Yc(i)} ${i===1?"has":"have"} local edits that aren't on Document360 yet \u2014 that's /push${n?` ${n}`:""}.`),{lines:r,ahead:i}}async function Qc(e,t,n,o={}){let r={published:[],blocked:[],failed:[]},s=0;for(let i of n){o.onProgress?.(s,n.length,i.label);let a=await nx({articleId:i.articleId,cwd:e,profileName:t,allowUnreviewed:o.skipReview===!0,allowStyleErrors:o.skipStyle===!0});a.ok?r.published.push({path:i.path,...a.url?{url:a.url}:{}}):a.blocked?r.blocked.push({path:i.path,message:a.message}):r.failed.push({path:i.path,message:a.error.message}),s+=1,s<n.length&&await lx(ax)}return r}function Jc(e){let{published:t,blocked:n,failed:o}=e,r=[];if(t.length>0){r.push(`\u2713 ${t.length} article${Yc(t.length)} ${t.length===1?"is":"are"} now live \u2014 readers see ${t.length===1?"it":"them"} now.`);let s=t.filter(i=>i.url);for(let i of s.slice(0,3))r.push(` \u2B95 ${i.url}`);s.length>3&&r.push(` \u2B95 \u2026and ${s.length-3} more`)}if(n.length>0){r.push(`\u2717 ${n.length} refused by the publish gates \u2014 still ${n.length===1?"a draft":"drafts"}, nothing was lost:`);for(let s of n.slice(0,3))r.push(` \xB7 ${Vc(s.path)}`);n.length>3&&r.push(` \xB7 \u2026and ${n.length-3} more`),r.push(" /status names what is blocking each one, and the command that clears it. It costs nothing.")}if(o.length>0){r.push(`\u2717 ${o.length} failed \u2014 ${o.length===1?"it is":"they are"} still a draft, so re-running /publish retries ${o.length===1?"it":"them"}:`);for(let s of o.slice(0,3))r.push(` \xB7 ${Vc(s.path)} \u2014 ${s.message}`);o.length>3&&r.push(` \xB7 \u2026and ${o.length-3} more`)}return r.length===0&&r.push("Nothing was published."),r}async function Im(e,t){let n=t?.cwd??process.cwd(),o=cn("publish");if(Kc(e))return o&&console.log(f(`\u2192 ${o}`)),console.log(f("Running /push\u2026")),oa(e,t);let r=He(n,t?.profileName);if(!r.ok)return console.log(_(r.reason)),{kind:"continue"};o&&console.log(f(`\u2192 ${o}`));let s=e.includes(xt),i=e.includes(sx),a=e.includes(ix),l=e.includes("--all"),d=e.find(R=>!R.startsWith("--"));console.log(f("Checking what is waiting to go live\u2026"));let w;try{w=await zc(n,t?.profileName,d)}catch(R){return console.log(_(`Could not check Document360: ${R.message}`)),{kind:"continue"}}if(w.length===0){for(let R of Xc(n,t?.profileName,d).lines)console.log(R.startsWith("\u2713")?q(R):f(R));return{kind:"continue"}}let m=ox(n,w.map(R=>R.path),{allowUnreviewed:s,allowStyleErrors:i,checkScreenshots:!0,allowPlaceholders:a});if(!m.clear){for(let R of rx(m,w.length,{scope:d,act:"publish"}))console.log(H(R));return{kind:"continue"}}console.log(""),console.log(`${w.length} draft${Yc(w.length)} ${w.length===1?"is":"are"} ahead of what readers see:`);for(let R of ux(w.slice(0,12)))console.log(f(R));w.length>12&&console.log(f(` \u2026and ${w.length-12} more`)),console.log("");let $=w;if(!l){let R=await J0({message:"Publish live to your readers?",choices:[{name:`Yes \u2014 publish all ${w.length} live`,value:"all"},...w.slice(0,8).map(C=>({name:`Just ${C.label}`,value:C.path})),{name:"No \u2014 leave them as drafts",value:"none"}]});if(R==="none")return console.log(f("Left as drafts. Nothing changed.")),{kind:"continue"};R!=="all"&&($=w.filter(C=>C.path===R))}let S=await Qc(n,t?.profileName,$,{skipReview:s,skipStyle:i,onProgress:(R,C,A)=>console.log(f(` \u25B8 ${R+1}/${C} ${Vc(A)}\u2026`))});console.log("");for(let R of Jc(S))console.log(R.startsWith("\u2713")?q(R):R.startsWith("\u2717")?H(R):f(R));return{kind:"continue"}}import{loadKnownConflicts as dx,localArticleTitle as px,resolveActiveProfile as hx}from"document360-engine";function fx(e,t){let n=px(e,t);return n||(t.split(/[\\/]/).pop()??t).replace(/\.md$/,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ")}function ra(e,t){let n=[];try{n=dx(e,hx(e,t).name)}catch{return null}if(n.length===0)return null;let o=n.length,r=n.slice(0,3).map(i=>fx(e,i)),s=o>3?`${r.join(", ")} and ${o-3} more`:r.join(", ");return{paths:n,note:`\u26A0 ${o} article${o===1?"":"s"} ${o===1?"has":"have"} been changed both here and on Document360 (${s}), so your local copy is not a reliable picture of what your readers have. An audit over it could tell you to write an article that already exists, or miss one that needs your decision \u2014 so it needs ${o===1?"that":"those"} settled first.`}}var ir={cmd:"/resolve",reason:"it walks each one with you \u2014 keep yours, take the portal's, or skip"};async function fs(e){if(e?.cwd){let n=ra(e.cwd,e.profileName);if(n)return{kind:"audit-blocked",note:n.note,lead:ir}}return{kind:"forward-to-agent",prompt:["Run the gap-analysis skill against this repo.","","Follow its stages in order:","1. d360_sync_status first; 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, in plain words, never the internal status word \u2014 and tell the user to run /resolve, which walks the affected articles one at a time (keep the local copy, take the portal's, or skip). Do NOT ask them to report back to you: they will run /resolve and then /audit again.","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: 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, so backfill them.","4. Output the proposal table: | Article (path or proposed title) | Action (create | update | retire | link) | Reason | Evidence | Scope |, then stamp consumed hints.","","Do not start writing or updating any article yet; the proposal table is the deliverable."].join(`
333
+ `),display:"/audit"}}re();import{readProjectConfig as mx}from"document360-engine";function Zc(){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: 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, with every claim cited to its grounding, 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;'," 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(`
334
+ `)}async function Lm(e,t){let n=t?.cwd??process.cwd();return mx(n)?{kind:"forward-to-agent",prompt:Zc(),display:"/discover"}:(console.log(_("No d360-writer config here. Run /init first.")),{kind:"continue"})}re();import{checkbox as gx}from"@inquirer/prompts";import{inventoryRepo as wx,readProjectConfig as Om,writeProjectConfig as yx}from"document360-engine";function eu(e,t){let n=Om(e);n&&(n.authoritativeSourceFiles=t,yx(n,e))}function sa(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 _m(e,t){let n=t?.cwd??process.cwd();if(!Om(n))return console.log(_("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=wx(n);if(o.length===0)return console.log(f('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(Z("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${f(sa(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>gx({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${sa(s)})`,value:s.path,checked:s.recommended})),pageSize:20}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}if(r.length===0)return console.log(f("Nothing selected \u2014 scope unchanged.")),{kind:"continue"};eu(n,r),console.log(q(`\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"}}re();import{confirm as Tx}from"@inquirer/prompts";import{applyPull as ru,computeSyncStatus as zm,compareRemoteSources as Ax,planPull as Xm,planImport as Ex,applyImport as Nx,establishBaselines as Dx,rebaselineServerMeta as jx,D360AuthError as Ix}from"document360-engine";re();var Mm=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /push <path>):",paint:_,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /push <path>:",paint:H,mark:"M"},{status:"remote-ahead",header:"Changed on Document360 \u2014 pull with /pull <path> (or just /pull):",paint:Z,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:_,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:_,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint:Re,mark:"X"},{status:"untracked-local",header:"New here \u2014 not on Document360 yet (publish to add them):",paint:f,mark:"?"},{status:"untracked-remote",header:"On Document360 \u2014 not in your local docs yet (run /pull to import them):",paint:f,mark:"?"},{status:"unknown-base",header:"Tracked, not yet compared \u2014 run /pull --baseline to set a baseline (or the next publish/pull sets one):",paint:Re,mark:"\xB7"}];function bx(e){return e.path?e.path:`${e.title??"(untitled)"} ${Re(`[${e.articleId}]`)}`}function kx(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 ia(e,t){let n=[],o=e.entries.filter(w=>w.link);if(o.length>0){n.push(""),n.push(Be("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let w of o)n.push(` ${H("~")} ${H(w.path??"")} ${Re(`\u2192 "${w.link.title}"`)}`)}for(let w of Mm){let m=e.entries.filter($=>$.status===w.status&&!(w.status==="untracked-local"&&$.link));if(m.length!==0){n.push(""),n.push(Be(w.header));for(let $ of m)n.push(` ${w.paint(w.mark)} ${w.paint(bx($))}${$.detail?Re(` (${$.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"},a=o.length,l=s===r?q("\u2713 everything up to date"):[r>0?q(`\u2713 ${r} up to date`):null,a>0?`${a} to link`:null,...Mm.map(w=>{let m=(e.counts[w.status]??0)-(w.status==="untracked-local"?a:0);return m>0?`${m} ${i[w.status]}`:null})].filter(Boolean).join(Re(" \xB7 ")),d=t!==void 0?` \xB7 synced in ${kx(t)}`:"";return n.push(l+Re(` \xB7 ${s} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${d}`)),n}import{structuredPatch as $x}from"diff";import Fm from"picocolors";var vx=80,ar=400,xx="\x1B[48;2;74;28;28m",Rx="\x1B[48;2;24;66;24m",Um="\x1B[49m",tu=e=>String(e).padStart(5);function Wm(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}function Bm(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 Rt(e,t,n,o=vx){let r=R=>{let C=R.replace(/\r\n/g,`
335
335
  `);return C.endsWith(`
336
336
  `)||C===""?C:C+`
337
- `},s=r(e),i=r(t);if(s===i)return null;let a=Math.max(20,n-10),l=hx("a","b",s,i,"","",{context:3}),d=0,g=0,w=[];l.hunks.forEach((v,C)=>{C>0&&w.push(Lm.gray(" \u2026"));let T=v.oldStart,D=v.newStart,L=[],B=[],M=()=>{for(let X=0;X<L.length;X++){let z=X<B.length?_m(L[X],B[X]):void 0;g++,w.push(`${mx}${Xc(T++)} - ${Mm(L[X],a,z)}${Om}`)}for(let X=0;X<B.length;X++){let z=X<L.length?_m(L[X],B[X]):void 0;d++,w.push(`${gx}${Xc(D++)} + ${Mm(B[X],a,z)}${Om}`)}L=[],B=[]};for(let X of v.lines){let z=X[0],de=X.slice(1);z==="-"?L.push(de):z==="+"?B.push(de):(M(),w.push(Lm.gray(Xc(D))+" "+de.slice(0,a)),T++,D++)}M()});let k=Math.max(1,o),S=w.slice(0,k);return{added:d,removed:g,lines:S,hidden:Math.max(0,w.length-k)}}import{select as Bm}from"@inquirer/prompts";import{applyPull as Hm,computeSyncStatus as wx,isPullWouldBlankError as Um,localArticleTitle as yx,planPull as Wm}from"document360-engine";function ia(){return["Document360 will not give this article back as markdown \u2014 it is not on the Markdown (Editor 3.0) editor, so there is no portal copy to show you or to take.","Your local copy is intact, and publishing it over the portal settles this. Skipping leaves the article flagged, and it will be waiting again next time."]}function aa(){return"Publish your copy over the portal (settles it) \xB7 Skip?"}function Fm(){return"(l publish yours \xB7 s skip \u2014 anything else stops, keeping your answers so far)"}function la(e){if(e.length===0)return[];let t=e.length,n=e.slice(0,3).join(", ")+(t>3?`, +${t-3} more`:"");return[`${t} article${t===1?"":"s"} stay${t===1?"s":""} flagged \u2014 Document360 cannot hand ${t===1?"its":"their"} markdown back: ${n}`,"Two ways out: run /resolve and press l to publish your copy over the portal, or ask your Document360 admin to move the article back to the Markdown (Editor 3.0) editor, then run /resolve again."]}function Qc(e){return`Cannot take the portal copy of ${e} \u2014 Document360 will not return it as markdown. Left as it was.`}re();var ca=e=>e===1?"":"s";async function Jc(e,t,n=1){console.log(""),console.log(`${Z("\u25CF")} ${Be(t.title)} ${ve(`(${t.path})`)}`);for(let i of t.notes)console.log(H(` \u26A0 ${i}`));let o=Rt(t.oldContent,t.newContent,Math.max(40,(process.stdout.columns??80)-1),ir);if(o){console.log(ve(` \u23BF local \u2192 portal: +${o.added} / -${o.removed} line${ca(o.added+o.removed)}`));for(let i of o.lines)console.log(i);o.hidden>0&&console.log(f(` \u2026 +${o.hidden} more diff lines`))}else console.log(f(" Local already matches the portal content \u2014 resolving just advances the sync base."));let r=n>1,s=await e.withPausedInput(()=>Bm({message:`Conflict \u2014 ${t.path}${r?` (${n} left)`:""}`,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"},...r?[{name:`Keep local for ALL ${n} remaining`,value:"local-all"},{name:`Take portal for ALL ${n} remaining`,value:"portal-all"},{name:`Skip ALL ${n} remaining`,value:"skip-all"}]:[]]})).catch(()=>"skip");return s==="portal"?(Hm({cwd:e.cwd,profileName:e.profileName},t),console.log(q(" \u2713 Took the portal copy (local overwritten, sync base advanced).")),"took-portal"):s==="local"?"keep-local":s==="skip"?(console.log(f(" Skipped \u2014 still a conflict.")),"skipped"):s==="local-all"?"keep-local-all":s==="portal-all"?"took-portal-all":"skipped-all"}async function bx(e,t){console.log(""),console.log(`${Z("\u25CF")} ${Be(yx(e.cwd,t)??t)} ${ve(`(${t})`)}`);for(let o of ia())console.log(H(` \u26A0 ${o}`));return await e.withPausedInput(()=>Bm({message:aa(),choices:[{name:"Publish your copy over the portal (settles it)",value:"local"},{name:"Skip (leave it a conflict)",value:"skip"}]})).catch(()=>"skip")==="local"?"keep-local":(console.log(f(" Skipped \u2014 still a conflict.")),"skipped")}async function Gm(e,t){let n=qe(t.cwd,t.profileName);if(!n.ok)return console.log(O(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let s=(await wx({cwd:t.cwd,profileName:t.profileName})).entries.filter(l=>l.status==="conflict"&&l.path).map(l=>l.path);if(o){if(!s.includes(o))return console.log(q(`${o} isn't in conflict \u2014 nothing to resolve.`)),{kind:"continue"};s=[o]}if(s.length===0)return console.log(q("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let i=[],a=[];for(let[l,d]of s.entries()){let g;try{g=await Wm({cwd:t.cwd,profileName:t.profileName,relPath:d})}catch(S){if(!Um(S))throw S;await bx(t,d)==="keep-local"?i.push(d):a.push(d);continue}let w=await Jc(t,g,s.length-l);if(w==="keep-local"&&i.push(d),!w.endsWith("-all"))continue;let k=s.slice(l);if(w==="keep-local-all")i.push(...k),console.log(f(` Keeping local for all ${k.length} \u2014 publishing them over the portal.`));else if(w==="took-portal-all"){let S=0;for(let v of k)try{Hm({cwd:t.cwd,profileName:t.profileName},await Wm({cwd:t.cwd,profileName:t.profileName,relPath:v})),S++}catch(C){console.log(O(` \u2717 ${v}: ${C.message}`)),Um(C)&&a.push(v)}console.log(q(` \u2713 Took the portal copy of ${S} article${ca(S)} (local overwritten, sync base advanced).`))}else console.log(f(` Skipped all ${k.length} \u2014 still conflict${ca(k.length)}.`));break}for(let l of la(a))console.log(H(`\u26A0 ${l}`));if(i.length>0)return console.log(f(`Publishing ${i.length} kept-local article${ca(i.length)} over the portal\u2026`)),await Wt(t,i,0,{allowUnpullable:!0})}catch(r){console.log(O(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function Ym(e,t){let n=qe(t.cwd,t.profileName);if(!n.ok)return console.log(O(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await Px(t),{kind:"continue"};if(o==="--baseline")return await Tx(t,e.filter(i=>i!=="--baseline")),{kind:"continue"};if(o==="--compare")return await Ax(t),{kind:"continue"};if(o)return console.log(O(`Unknown option: ${o}`)),console.log(f("Usage: /pull pull portal edits + import new portal articles")),console.log(f(" /pull <path> pull one article (or resolve a conflict)")),console.log(f(" /pull --status drift report only (no writes)")),console.log(f(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await Ex(t,r),{kind:"continue"};console.log(f("Pulling changes from Document360\u2026"));let s=await eu({cwd:t.cwd,profileName:t.profileName});for(let i of tu(s))console.log(i.tone==="ok"?q(i.text):i.tone==="warn"?H(i.text):f(i.text));console.log("")}catch(r){r instanceof Sx?console.log(O(r.message)):console.log(O(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function eu(e){let t=await qm({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 Vm({cwd:e.cwd,profileName:e.profileName,relPath:o.path});Zc({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 vx({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});xx({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 ua=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,co=e=>e===1?"":"s";function tu(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${co(e.pulled.length)} into local: ${ua(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${co(e.imported.length)}: ${ua(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${co(e.toPublish)} changed locally \u2014 /push saves them to Document360.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${co(e.conflicts.length)} changed both here and on Document360 \u2014 left untouched. Resolve them: /resolve (or /push <path> to keep yours, /pull <path> to take the portal's). (${ua(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${co(e.failed.length)} failed: ${ua(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 Px(e){console.log(f("Checking Document360 for drift\u2026"));let t=Date.now(),n=await qm({cwd:e.cwd,profileName:e.profileName});for(let o of sa(n,Date.now()-t))console.log(o);console.log("")}async function Tx(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(f(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await Rx({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await Cx({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(q("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(q(`\u2713 Recorded ${o.baselined.length} article(s) as matching Document360 \u2014 they read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(q(`\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(f(` - ${s.path} (${s.reason})`))}}async function Ax(e){console.log(f("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await $x({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${Be(String(t.legacyCount))} \xB7 Manifest: ${Be(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(q("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(O(`\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(f(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function Ex(e,t){let n=t.replace(/\\/g,"/"),o=await Vm({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await Jc(e,o)==="keep-local"&&(console.log(f(`Publishing ${o.path} over the portal\u2026`)),await Wt(e,[o.path]));return}console.log(""),console.log(`${Z("\u25CF")} ${Be(o.title)} ${ve(`(${o.path})`)}`);for(let i of o.notes)console.log(H(` \u26A0 ${i}`));let r=Rt(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1),ir);if(!r){console.log(f(" Local file already matches the remote content \u2014 advancing the sync base only.")),Zc({cwd:e.cwd,profileName:e.profileName},o);return}console.log(ve(` \u23BF Added ${r.added} line${co(r.added)}, removed ${r.removed} line${co(r.removed)}`));for(let i of r.lines)console.log(i);if(r.hidden>0&&console.log(f(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>kx({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(f(" Skipped."));return}Zc({cwd:e.cwd,profileName:e.profileName},o),console.log(q(` \u2713 Pulled ${o.path} (sync base advanced).`))}re();import{statSync as Bx}from"node:fs";import{resolve as Hx}from"node:path";import{estimateBulkCost as Gx,planPartitions as qx,readProjectConfig as Vx,resolveModelForOperation as Yx,runPartitioned as Kx,trackedArticlePaths as zx}from"document360-engine";function Tn(e,t){return e.aborted?null:e.blocked?[`\u2717 ${t} didn\u2019t start \u2014 ${e.blocked}.`,"Nothing was changed. Fix that, then re-run."]:e.allEmpty?[`\u2717 ${t} did nothing \u2014 every batch produced no output, so no agent actually ran.`,"Run /doctor \u2014 it runs a real turn with your skills and tools and reports what failed. /logs shows Claude Code\u2019s own error, which was recorded either way, and offers to copy it.","A Claude usage or session limit also does this, and it ends every turn instantly \u2014 if you have just hit one, wait for the reset and re-run."]:null}function Km(e){return!e.bailedEmpty||!e.notRun?null:`\u26A0 Stopped early \u2014 ${e.notRun} batch${e.notRun===1?" was":"es were"} not attempted, because two in a row produced no output (that is systemic, not this work: usually a Claude usage limit). Re-run to finish the rest; anything already done is skipped.`}var ar=class{activeMs=0;last=0;timer=null;startedAt=0;stopped=null;start(t=Date.now()){this.timer||(this.startedAt=t,this.last=t,this.timer=setInterval(()=>this.tick(),1e3),this.timer.unref?.())}tick(t=Date.now()){let n=t-this.last;this.last=t,!(n<=0)&&(this.activeMs+=Math.min(n,5e3))}stop(t=Date.now()){return this.stopped?this.stopped:(this.timer&&(clearInterval(this.timer),this.timer=null),this.tick(t),this.stopped={activeSeconds:Math.max(0,Math.round(this.activeMs/1e3)),elapsedSeconds:Math.max(0,Math.round((t-this.startedAt)/1e3))},this.stopped)}};function da(e,t){let n=t-e;return n>=300&&n>=t*.2}function Ct(e,t,n,o=Date.now(),r){let s=t.reduce((a,l)=>a+(l.inputTokens??0),0),i=t.reduce((a,l)=>a+(l.cacheReadTokens??0),0);return{seconds:Math.max(0,Math.round((o-e)/1e3)),outputTokens:t.reduce((a,l)=>a+l.outputTokens,0),inputTokens:s,...s>0?{cachedPct:Math.round(i/s*100)}:{},...r!==void 0?{activeSeconds:r}:{},costUsd:n}}function Nx(e){return e.activeSeconds!==void 0&&da(e.activeSeconds,e.seconds)?`${nu(e.seconds)} elapsed \xB7 ${nu(e.activeSeconds)} working`:nu(e.seconds)}var zm=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:`${e}`,nu=e=>{if(e<60)return`${e}s`;let t=Math.floor(e/60);return t<60?`${t}m ${e%60}s`:`${Math.floor(t/60)}h ${t%60}m`};function zt(e){let t=e.cachedPct!==void 0?`, ${e.cachedPct}% cached`:"",n=e.costUsd>0?`, this turn ${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"";return` (took ${Nx(e)}, ${zm(e.inputTokens)}\u2192${zm(e.outputTokens)} tokens${t}${n})`}import we from"picocolors";import iu from"wrap-ansi";import au from"string-width";re();import An from"picocolors";import ha from"wrap-ansi";import pa from"string-width";var uo=[{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>] [--push]",desc:"Document a shipped change \u2014 the agent picks the action (new section/article/update); bare: act on builder requests. --push then saves the result to Document360 as drafts, which still needs an editorial review first",group:"docs"},{name:"write",usage:"/write [--preview|--scope <cat>|<path>] [--rewrite] [--concurrency N] [--skip-style]",desc:"Write the planned articles in parallel (starts immediately; --preview shows plan + cost first; --rewrite regenerates already-written articles; --concurrency default 3). Anything that would block publishing is corrected in one automatic pass before the run finishes; --skip-style leaves it to /lint",group:"docs"},{name:"screenshot",usage:"/screenshot [author|capture|annotate|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); annotate: draw the callouts on shots already taken, no browser needed (--all --force re-draws after a wording or style change); verify: judge the finished pictures and mark them verified (both run 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:"push",usage:"/push [path|--all|[<category>] --screenshots] [--preview] [--skip-review]",desc:"Save your articles to Document360 as drafts \u2014 readers don't see them until /publish (no arg: pick; --all: every candidate; --screenshots: re-save articles with captured shots so images embed, optionally narrowed to one category; --preview <path>: show exactly what would be sent, and send nothing). Blocked until each article has had /review --fix \u2014 AI-written text gets an editor first; --skip-review overrides deliberately",group:"publish"},{name:"publish",usage:"/publish [path|<category>|--all] [--skip-review]",desc:"Take the drafts on Document360 LIVE to your readers (the portal's own Publish). Always lists what would become visible and asks first; no arg or a category narrows it. Needs an editorial review \u2014 /review --blocked --fix",group:"publish"},{name:"style-guide",usage:"/style-guide [list | use <preset> | keep | pull [<n>] | learn | compile | explain <rule>]",desc:"Choose the writing rules your docs are held to. Bare: what is active now; list: every pack you can turn on; use: switch packs (records what is already there so nothing suddenly breaks); keep: settle on the rules you have today; pull: bring your Document360 project's own style guide down; learn: turn what your reviewers keep asking for into standing rules; compile: turn its mechanical statements into checks; explain: what one rule means and how to silence it",group:"docs"},{name:"lint",usage:"/lint [<category|path>] [--blocked] [--fix] [--full]",desc:"Lint the docs against the house rules: leaked internals, invented commands, stale facts, AI-tells, em dashes, callout shape (deterministic, no tokens). Every finding names the rule that produced it. Scope to a category/path; --blocked narrows to the errors that block publishing and leaves warnings and suggestions alone; --fix has the agent correct them in place; --full lists every finding instead of a capped summary",group:"docs"},{name:"review",usage:"/review [<category|path> | --all | --blocked | --stale] [--fix]",desc:"Independent senior-editor review: style guide, terminology/voice, grammar/clarity, structure, improvement suggestions. Bare: pick a category or everything; --blocked reads only the articles publishing is blocked on; --stale reads the ones the current editor has not read yet, so running it twice costs nothing; --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 /push",group:"docs"},{name:"structure",usage:"/structure",desc:"Show the documentation reading order (categories \u2192 articles) as it will appear on Document360",group:"docs"},{name:"status",usage:"/status [--all]",desc:'What stands between your work and your readers, before you spend anything: which articles no editor has read, which break a style rule your config makes blocking, which would show "[Screenshot: \u2026]" text to a reader, which are in conflict with the portal, and which are saved as drafts readers cannot see yet. Each group names the one command that clears it. Reads local files and the last sync \u2014 no network, no tokens. --all lists every article gate by gate',group:"publish"},{name:"retire",usage:"/retire [<path>]",desc:"Take an article off your readers on Document360 \u2014 it stops being visible, and nothing offers to publish it again. Nothing is deleted: the article, its version history and every reviewer comment stay. Bare: lists what is worth retiring (articles on Document360 that are no longer in your docs folder). /push puts one back \u2014 reviving is a publish like any other",group:"publish"},{name:"terms",usage:'/terms [<category>] [--all] [--approve "<term>"]',desc:"Is your knowledge base calling the same thing by the same name? Reads every article and reports terms spelled more than one way, short names that may be the long name abbreviated, and article titles out of step with the rest of their kind \u2014 the consistency an editor reading three articles at a time cannot see. Costs nothing and calls nothing. --approve records a spelling as the approved one, so every later run enforces it",group:"docs"},{name:"roadmap",usage:"/roadmap [--all | done [step]]",desc:"Show the docs campaign (the multi-session plan the agent maintains), grouped by the part of the job \u2014 progress + next step; `--all` also lists the steps a later pass replaced; `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:"ask",usage:"/ask <question>",desc:"Ask your developers something the code cannot tell you: why a feature exists, when to use it, whether it can be undone",group:"publish"},{name:"share",usage:"/share [status|on|off]",desc:"Share your docs work with the team: get your builder's latest, then save + send yours (runs automatically; `off` leaves it to your coding agent)",group:"publish"},{name:"catch-up",usage:"/catch-up [--push]",desc:"Process ALL pending work (builder hints + requests + Document360 portal drift) \u2192 write \u2192 save to Document360 as drafts. --push does that last step for you, which still needs an editorial review first. For code changes, that's /audit",group:"publish"},{name:"comments",usage:"/comments [<article>] [--scope <category>] [--answer] [--all] [--resolve] [--answered] [--full]",desc:"Reviewer comments left on passages of your articles in the Document360 portal \u2014 bare: a table by article, pick a number to read its comments in full, then answer or go back; --answer: fix, push the draft, reply (threads stay open unless you add --resolve); --full re-reads every article",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 (push), take portal (pull), or skip \u2014 per article, or one answer for all remaining. 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:"verbose",usage:"/verbose [on|off]",desc:"Show the raw transcript \u2014 every tool call with its file path and full result, instead of article-shaped cards with my bookkeeping collapsed (bare: toggle)",group:"setup"},{name:"logout",usage:"/logout [--all-projects]",desc:"Sign out of this project + clear its 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, and a real agent turn",group:"setup"},{name:"logs",usage:"/logs",desc:"Show the most recent problem d360-writer recorded, and where the logs are \u2014 press c to copy it for the team",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"}],Xm={"/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","/push":"save your articles to Document360 as drafts","/publish":"take the signed-off drafts live to your readers","/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, draw the callouts)","/doctor":"run a health check","/logs":"show the last problem, and copy it for the team","/style-guide":"choose the writing rules your docs are held to","/lint":"check the docs against those rules (costs nothing)"};function Qm(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(Xm[n])return Xm[n];let o=uo.find(r=>r.name===t);return o?o.desc:""}function Jm(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return uo.filter(n=>n.name.startsWith(t))}function Zm(e){let t=0,n="";for(let o of e){if(o==="["){t++;continue}if(o==="]"){t=Math.max(0,t-1);continue}t===0&&(n+=o)}return/<[^>]+>/.test(n)}var Dx=new RegExp(`^\\s*/(?:${uo.map(e=>e.name).join("|")})(?:\\s|$)`),eg=e=>Dx.test(e),tg=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),ng=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),og=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function jx(e){let t=e.replace(/\r/g,"").split(`
338
- `),n=[],o=0;for(;o<t.length;){let r=t[o];if(/^\s*```/.test(r)){let a=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)a.push(t[o++]);o++,n.push({kind:"code",lines:a});continue}if(tg(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&ng(t[o+1])){let a=og(r);o+=2;let l=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)l.push(og(t[o++]));n.push({kind:"table",header:a,rows:l});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 a=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);){let l=t[o++];a.push({ordered:/^\s*\d+\.\s+/.test(l),text:l.replace(/^\s*([-*]|\d+\.)\s+/,"")})}n.push({kind:"list",items:a});continue}if(r.trim()===""){o++;continue}if(eg(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])&&!eg(t[o])&&!tg(t[o])&&!(t[o].includes("|")&&o+1<t.length&&ng(t[o+1]));)i.push(t[o++]);n.push({kind:"para",text:i.join(" ")})}return n}function ou(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?An.bold(t.slice(2,-2)):t.startsWith("`")?Z(t.slice(1,-1)):An.italic(t.slice(1,-1)))}var Ix=(e,t)=>e+" ".repeat(Math.max(0,t-pa(e)));function fs(e,t,n,o={}){return rg(e,t,n,o)}function rg(e,t,n,o={}){let r=e.length,s=T=>Math.max(0,...T.split(`
339
- `).map(D=>pa(D))),i=e.map((T,D)=>Math.max(pa(T),...t.map(L=>s(L[D]??"")))),a=Math.max(24,n),l=3*r+1,d=[...i],g=()=>d.reduce((T,D)=>T+D,0)+l,w=0;for(;g()>a&&w++<1e4;){let T=-1,D=6;for(let L=0;L<r;L++)d[L]>D&&(D=d[L],T=L);if(T===-1)break;d[T]-=1}let k=(T,D,L)=>An.gray(T+d.map(B=>"\u2500".repeat(B+2)).join(D)+L),S=An.gray("\u2502"),v=(T,D)=>{let L=d.map((z,de)=>{let be=T[de]??"",$e=D?An.bold(be):o.plain?be:ou(be);return be.includes(`
340
- `)?$e.split(`
341
- `).flatMap(Ce=>ha(Ce,z,{hard:!0}).split(`
342
- `)):ha($e,z,{hard:!0}).split(`
343
- `)}),B=Math.max(...L.map(z=>z.length)),M=[],X=(z,de,be)=>o.align?.[be]==="right"?" ".repeat(Math.max(0,de-pa(z)))+z:Ix(z,de);for(let z=0;z<B;z++)M.push(d.map((de,be)=>`${S} ${X(L[be][z]??"",de,be)} `).join("")+S);return M.join(`
344
- `)},C=[k("\u250C","\u252C","\u2510"),v(e,!0)];return C.push(t.length===0?k("\u2514","\u2534","\u2518"):k("\u251C","\u253C","\u2524")),t.forEach((T,D)=>{C.push(v(T,!1)),C.push(D===t.length-1?k("\u2514","\u2534","\u2518"):k("\u251C","\u253C","\u2524"))}),C.join(`
345
- `)}function Lx(e,t){switch(e.kind){case"heading":return An.bold(e.text);case"hr":return An.gray("\u2500".repeat(t));case"para":return ha(ou(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="",...a]=ha(ou(o.text),Math.max(10,t-s.length)).split(`
337
+ `},s=r(e),i=r(t);if(s===i)return null;let a=Math.max(20,n-10),l=$x("a","b",s,i,"","",{context:3}),d=0,w=0,m=[];l.hunks.forEach((R,C)=>{C>0&&m.push(Fm.gray(" \u2026"));let A=R.oldStart,D=R.newStart,N=[],U=[],O=()=>{for(let Q=0;Q<N.length;Q++){let z=Q<U.length?Wm(N[Q],U[Q]):void 0;w++,m.push(`${xx}${tu(A++)} - ${Bm(N[Q],a,z)}${Um}`)}for(let Q=0;Q<U.length;Q++){let z=Q<N.length?Wm(N[Q],U[Q]):void 0;d++,m.push(`${Rx}${tu(D++)} + ${Bm(U[Q],a,z)}${Um}`)}N=[],U=[]};for(let Q of R.lines){let z=Q[0],de=Q.slice(1);z==="-"?N.push(de):z==="+"?U.push(de):(O(),m.push(Fm.gray(tu(D))+" "+de.slice(0,a)),A++,D++)}O()});let $=Math.max(1,o),S=m.slice(0,$);return{added:d,removed:w,lines:S,hidden:Math.max(0,m.length-$)}}import{select as Vm}from"@inquirer/prompts";import{applyPull as Ym,computeSyncStatus as Cx,isPullWouldBlankError as Gm,localArticleTitle as Sx,planPull as qm}from"document360-engine";function aa(){return["Document360 will not give this article back as markdown \u2014 it is not on the Markdown (Editor 3.0) editor, so there is no portal copy to show you or to take.","Your local copy is intact, and publishing it over the portal settles this. Skipping leaves the article flagged, and it will be waiting again next time."]}function la(){return"Publish your copy over the portal (settles it) \xB7 Skip?"}function Hm(){return"(l publish yours \xB7 s skip \u2014 anything else stops, keeping your answers so far)"}function ca(e){if(e.length===0)return[];let t=e.length,n=e.slice(0,3).join(", ")+(t>3?`, +${t-3} more`:"");return[`${t} article${t===1?"":"s"} stay${t===1?"s":""} flagged \u2014 Document360 cannot hand ${t===1?"its":"their"} markdown back: ${n}`,"Two ways out: run /resolve and press l to publish your copy over the portal, or ask your Document360 admin to move the article back to the Markdown (Editor 3.0) editor, then run /resolve again."]}function nu(e){return`Cannot take the portal copy of ${e} \u2014 Document360 will not return it as markdown. Left as it was.`}re();var ua=e=>e===1?"":"s";async function ou(e,t,n=1){console.log(""),console.log(`${Z("\u25CF")} ${Be(t.title)} ${Re(`(${t.path})`)}`);for(let i of t.notes)console.log(H(` \u26A0 ${i}`));let o=Rt(t.oldContent,t.newContent,Math.max(40,(process.stdout.columns??80)-1),ar);if(o){console.log(Re(` \u23BF local \u2192 portal: +${o.added} / -${o.removed} line${ua(o.added+o.removed)}`));for(let i of o.lines)console.log(i);o.hidden>0&&console.log(f(` \u2026 +${o.hidden} more diff lines`))}else console.log(f(" Local already matches the portal content \u2014 resolving just advances the sync base."));let r=n>1,s=await e.withPausedInput(()=>Vm({message:`Conflict \u2014 ${t.path}${r?` (${n} left)`:""}`,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"},...r?[{name:`Keep local for ALL ${n} remaining`,value:"local-all"},{name:`Take portal for ALL ${n} remaining`,value:"portal-all"},{name:`Skip ALL ${n} remaining`,value:"skip-all"}]:[]]})).catch(()=>"skip");return s==="portal"?(Ym({cwd:e.cwd,profileName:e.profileName},t),console.log(q(" \u2713 Took the portal copy (local overwritten, sync base advanced).")),"took-portal"):s==="local"?"keep-local":s==="skip"?(console.log(f(" Skipped \u2014 still a conflict.")),"skipped"):s==="local-all"?"keep-local-all":s==="portal-all"?"took-portal-all":"skipped-all"}async function Px(e,t){console.log(""),console.log(`${Z("\u25CF")} ${Be(Sx(e.cwd,t)??t)} ${Re(`(${t})`)}`);for(let o of aa())console.log(H(` \u26A0 ${o}`));return await e.withPausedInput(()=>Vm({message:la(),choices:[{name:"Publish your copy over the portal (settles it)",value:"local"},{name:"Skip (leave it a conflict)",value:"skip"}]})).catch(()=>"skip")==="local"?"keep-local":(console.log(f(" Skipped \u2014 still a conflict.")),"skipped")}async function Km(e,t){let n=He(t.cwd,t.profileName);if(!n.ok)return console.log(_(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let s=(await Cx({cwd:t.cwd,profileName:t.profileName})).entries.filter(l=>l.status==="conflict"&&l.path).map(l=>l.path);if(o){if(!s.includes(o))return console.log(q(`${o} isn't in conflict \u2014 nothing to resolve.`)),{kind:"continue"};s=[o]}if(s.length===0)return console.log(q("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let i=[],a=[];for(let[l,d]of s.entries()){let w;try{w=await qm({cwd:t.cwd,profileName:t.profileName,relPath:d})}catch(S){if(!Gm(S))throw S;await Px(t,d)==="keep-local"?i.push(d):a.push(d);continue}let m=await ou(t,w,s.length-l);if(m==="keep-local"&&i.push(d),!m.endsWith("-all"))continue;let $=s.slice(l);if(m==="keep-local-all")i.push(...$),console.log(f(` Keeping local for all ${$.length} \u2014 publishing them over the portal.`));else if(m==="took-portal-all"){let S=0;for(let R of $)try{Ym({cwd:t.cwd,profileName:t.profileName},await qm({cwd:t.cwd,profileName:t.profileName,relPath:R})),S++}catch(C){console.log(_(` \u2717 ${R}: ${C.message}`)),Gm(C)&&a.push(R)}console.log(q(` \u2713 Took the portal copy of ${S} article${ua(S)} (local overwritten, sync base advanced).`))}else console.log(f(` Skipped all ${$.length} \u2014 still conflict${ua($.length)}.`));break}for(let l of ca(a))console.log(H(`\u26A0 ${l}`));if(i.length>0)return console.log(f(`Publishing ${i.length} kept-local article${ua(i.length)} over the portal\u2026`)),await Wt(t,i,0,{allowUnpullable:!0})}catch(r){console.log(_(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function Qm(e,t){let n=He(t.cwd,t.profileName);if(!n.ok)return console.log(_(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await Lx(t),{kind:"continue"};if(o==="--baseline")return await Ox(t,e.filter(i=>i!=="--baseline")),{kind:"continue"};if(o==="--compare")return await _x(t),{kind:"continue"};if(o)return console.log(_(`Unknown option: ${o}`)),console.log(f("Usage: /pull pull portal edits + import new portal articles")),console.log(f(" /pull <path> pull one article (or resolve a conflict)")),console.log(f(" /pull --status drift report only (no writes)")),console.log(f(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await Mx(t,r),{kind:"continue"};console.log(f("Pulling changes from Document360\u2026"));let s=await su({cwd:t.cwd,profileName:t.profileName});for(let i of iu(s))console.log(i.tone==="ok"?q(i.text):i.tone==="warn"?H(i.text):f(i.text));console.log("")}catch(r){r instanceof Ix?console.log(_(r.message)):console.log(_(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function su(e){let t=await zm({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 Xm({cwd:e.cwd,profileName:e.profileName,relPath:o.path});ru({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 Ex({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});Nx({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 da=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,uo=e=>e===1?"":"s";function iu(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${uo(e.pulled.length)} into local: ${da(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${uo(e.imported.length)}: ${da(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${uo(e.toPublish)} changed locally \u2014 /push saves them to Document360.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${uo(e.conflicts.length)} changed both here and on Document360 \u2014 left untouched. Resolve them: /resolve (or /push <path> to keep yours, /pull <path> to take the portal's). (${da(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${uo(e.failed.length)} failed: ${da(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 Lx(e){console.log(f("Checking Document360 for drift\u2026"));let t=Date.now(),n=await zm({cwd:e.cwd,profileName:e.profileName});for(let o of ia(n,Date.now()-t))console.log(o);console.log("")}async function Ox(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(f(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await Dx({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await jx({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(q("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(q(`\u2713 Recorded ${o.baselined.length} article(s) as matching Document360 \u2014 they read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(q(`\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(f(` - ${s.path} (${s.reason})`))}}async function _x(e){console.log(f("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await Ax({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${Be(String(t.legacyCount))} \xB7 Manifest: ${Be(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(q("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(_(`\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(f(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function Mx(e,t){let n=t.replace(/\\/g,"/"),o=await Xm({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await ou(e,o)==="keep-local"&&(console.log(f(`Publishing ${o.path} over the portal\u2026`)),await Wt(e,[o.path]));return}console.log(""),console.log(`${Z("\u25CF")} ${Be(o.title)} ${Re(`(${o.path})`)}`);for(let i of o.notes)console.log(H(` \u26A0 ${i}`));let r=Rt(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1),ar);if(!r){console.log(f(" Local file already matches the remote content \u2014 advancing the sync base only.")),ru({cwd:e.cwd,profileName:e.profileName},o);return}console.log(Re(` \u23BF Added ${r.added} line${uo(r.added)}, removed ${r.removed} line${uo(r.removed)}`));for(let i of r.lines)console.log(i);if(r.hidden>0&&console.log(f(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>Tx({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(f(" Skipped."));return}ru({cwd:e.cwd,profileName:e.profileName},o),console.log(q(` \u2713 Pulled ${o.path} (sync base advanced).`))}re();import{statSync as Xx}from"node:fs";import{resolve as Qx}from"node:path";import{estimateBulkCost as Jx,planPartitions as Zx,readProjectConfig as eR,resolveModelForOperation as tR,runPartitioned as nR,trackedArticlePaths as oR}from"document360-engine";function Tn(e,t){return e.aborted?null:e.blocked?[`\u2717 ${t} didn\u2019t start \u2014 ${e.blocked}.`,"Nothing was changed. Fix that, then re-run."]:e.allEmpty?[`\u2717 ${t} did nothing \u2014 every batch produced no output, so no agent actually ran.`,"Run /doctor \u2014 it runs a real turn with your skills and tools and reports what failed. /logs shows Claude Code\u2019s own error, which was recorded either way, and offers to copy it.","A Claude usage or session limit also does this, and it ends every turn instantly \u2014 if you have just hit one, wait for the reset and re-run."]:null}function Jm(e){return!e.bailedEmpty||!e.notRun?null:`\u26A0 Stopped early \u2014 ${e.notRun} batch${e.notRun===1?" was":"es were"} not attempted, because two in a row produced no output (that is systemic, not this work: usually a Claude usage limit). Re-run to finish the rest; anything already done is skipped.`}var lr=class{activeMs=0;last=0;timer=null;startedAt=0;stopped=null;start(t=Date.now()){this.timer||(this.startedAt=t,this.last=t,this.timer=setInterval(()=>this.tick(),1e3),this.timer.unref?.())}tick(t=Date.now()){let n=t-this.last;this.last=t,!(n<=0)&&(this.activeMs+=Math.min(n,5e3))}stop(t=Date.now()){return this.stopped?this.stopped:(this.timer&&(clearInterval(this.timer),this.timer=null),this.tick(t),this.stopped={activeSeconds:Math.max(0,Math.round(this.activeMs/1e3)),elapsedSeconds:Math.max(0,Math.round((t-this.startedAt)/1e3))},this.stopped)}};function pa(e,t){let n=t-e;return n>=300&&n>=t*.2}function Ct(e,t,n,o=Date.now(),r){let s=t.reduce((a,l)=>a+(l.inputTokens??0),0),i=t.reduce((a,l)=>a+(l.cacheReadTokens??0),0);return{seconds:Math.max(0,Math.round((o-e)/1e3)),outputTokens:t.reduce((a,l)=>a+l.outputTokens,0),inputTokens:s,...s>0?{cachedPct:Math.round(i/s*100)}:{},...r!==void 0?{activeSeconds:r}:{},costUsd:n}}function Fx(e){return e.activeSeconds!==void 0&&pa(e.activeSeconds,e.seconds)?`${au(e.seconds)} elapsed \xB7 ${au(e.activeSeconds)} working`:au(e.seconds)}var Zm=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:`${e}`,au=e=>{if(e<60)return`${e}s`;let t=Math.floor(e/60);return t<60?`${t}m ${e%60}s`:`${Math.floor(t/60)}h ${t%60}m`};function zt(e){let t=e.cachedPct!==void 0?`, ${e.cachedPct}% cached`:"",n=e.costUsd>0?`, this turn ${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"";return` (took ${Fx(e)}, ${Zm(e.inputTokens)}\u2192${Zm(e.outputTokens)} tokens${t}${n})`}import ye from"picocolors";import du from"wrap-ansi";import pu from"string-width";re();import An from"picocolors";import fa from"wrap-ansi";import ha from"string-width";var po=[{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>] [--push]",desc:"Document a shipped change \u2014 the agent picks the action (new section/article/update); bare: act on builder requests. --push then saves the result to Document360 as drafts, which still needs an editorial review first",group:"docs"},{name:"write",usage:"/write [--preview|--scope <cat>|<path>] [--rewrite] [--concurrency N] [--skip-style]",desc:"Write the planned articles in parallel (starts immediately; --preview shows plan + cost first; --rewrite regenerates already-written articles; --concurrency default 3). Anything that would block publishing is corrected in one automatic pass before the run finishes; --skip-style leaves it to /lint",group:"docs"},{name:"screenshot",usage:"/screenshot [author|capture|annotate|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); annotate: draw the callouts on shots already taken, no browser needed (--all --force re-draws after a wording or style change); verify: judge the finished pictures and mark them verified (both run 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:"push",usage:"/push [path|--all|[<category>] --screenshots] [--preview] [--skip-review]",desc:"Save your articles to Document360 as drafts \u2014 readers don't see them until /publish (no arg: pick; --all: every candidate; --screenshots: re-save articles with captured shots so images embed, optionally narrowed to one category; --preview <path>: show exactly what would be sent, and send nothing). Blocked until each article has had /review --fix \u2014 AI-written text gets an editor first; --skip-review overrides deliberately",group:"publish"},{name:"publish",usage:"/publish [path|<category>|--all] [--skip-review]",desc:"Take the drafts on Document360 LIVE to your readers (the portal's own Publish). Always lists what would become visible and asks first; no arg or a category narrows it. Needs an editorial review \u2014 /review --blocked --fix",group:"publish"},{name:"style-guide",usage:"/style-guide [list | use <preset> | keep | pull [<n>] | learn | compile | explain <rule>]",desc:"Choose the writing rules your docs are held to. Bare: what is active now; list: every pack you can turn on; use: switch packs (records what is already there so nothing suddenly breaks); keep: settle on the rules you have today; pull: bring your Document360 project's own style guide down; learn: turn what your reviewers keep asking for into standing rules; compile: turn its mechanical statements into checks; explain: what one rule means and how to silence it",group:"docs"},{name:"lint",usage:"/lint [<category|path>] [--blocked] [--fix] [--full]",desc:"Lint the docs against the house rules: leaked internals, invented commands, stale facts, AI-tells, em dashes, callout shape (deterministic, no tokens). Every finding names the rule that produced it. Scope to a category/path; --blocked narrows to the errors that block publishing and leaves warnings and suggestions alone; --fix has the agent correct them in place; --full lists every finding instead of a capped summary",group:"docs"},{name:"review",usage:"/review [<category|path> | --all | --blocked | --stale] [--fix]",desc:"Independent senior-editor review: style guide, terminology/voice, grammar/clarity, structure, improvement suggestions. Bare: pick a category or everything; --blocked reads only the articles publishing is blocked on; --stale reads the ones the current editor has not read yet, so running it twice costs nothing; --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 /push",group:"docs"},{name:"structure",usage:"/structure",desc:"Show the documentation reading order (categories \u2192 articles) as it will appear on Document360",group:"docs"},{name:"status",usage:"/status [--all]",desc:'What stands between your work and your readers, before you spend anything: which articles no editor has read, which break a style rule your config makes blocking, which would show "[Screenshot: \u2026]" text to a reader, which are in conflict with the portal, and which are saved as drafts readers cannot see yet. Each group names the one command that clears it. Reads local files and the last sync \u2014 no network, no tokens. --all lists every article gate by gate',group:"publish"},{name:"retire",usage:"/retire [<path>]",desc:"Take an article off your readers on Document360 \u2014 it stops being visible, and nothing offers to publish it again. Nothing is deleted: the article, its version history and every reviewer comment stay. Bare: lists what is worth retiring (articles on Document360 that are no longer in your docs folder). /push puts one back \u2014 reviving is a publish like any other",group:"publish"},{name:"terms",usage:'/terms [<category>] [--all] [--approve "<term>"]',desc:"Is your knowledge base calling the same thing by the same name? Reads every article and reports terms spelled more than one way, short names that may be the long name abbreviated, and article titles out of step with the rest of their kind \u2014 the consistency an editor reading three articles at a time cannot see. Costs nothing and calls nothing. --approve records a spelling as the approved one, so every later run enforces it",group:"docs"},{name:"roadmap",usage:"/roadmap [--all | done [step]]",desc:"Show the docs campaign (the multi-session plan the agent maintains), grouped by the part of the job \u2014 progress + next step; `--all` also lists the steps a later pass replaced; `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:"ask",usage:"/ask <question>",desc:"Ask your developers something the code cannot tell you: why a feature exists, when to use it, whether it can be undone",group:"publish"},{name:"share",usage:"/share [status|on|off]",desc:"Share your docs work with the team: get your builder's latest, then save + send yours (runs automatically; `off` leaves it to your coding agent)",group:"publish"},{name:"catch-up",usage:"/catch-up [--push]",desc:"Process ALL pending work (builder hints + requests + Document360 portal drift) \u2192 write \u2192 save to Document360 as drafts. --push does that last step for you, which still needs an editorial review first. For code changes, that's /audit",group:"publish"},{name:"comments",usage:"/comments [<article>] [--scope <category>] [--answer] [--all] [--resolve] [--answered] [--full]",desc:"Reviewer comments left on passages of your articles in the Document360 portal \u2014 bare: a table by article, pick a number to read its comments in full, then answer or go back; --answer: fix, push the draft, reply (threads stay open unless you add --resolve); --full re-reads every article",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 (push), take portal (pull), or skip \u2014 per article, or one answer for all remaining. 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:"verbose",usage:"/verbose [on|off]",desc:"Show the raw transcript \u2014 every tool call with its file path and full result, instead of article-shaped cards with my bookkeeping collapsed (bare: toggle)",group:"setup"},{name:"logout",usage:"/logout [--all-projects]",desc:"Sign out of this project + clear its 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, and a real agent turn",group:"setup"},{name:"logs",usage:"/logs",desc:"Show the most recent problem d360-writer recorded, and where the logs are \u2014 press c to copy it for the team",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"}],eg={"/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","/push":"save your articles to Document360 as drafts","/publish":"take the signed-off drafts live to your readers","/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, draw the callouts)","/doctor":"run a health check","/logs":"show the last problem, and copy it for the team","/style-guide":"choose the writing rules your docs are held to","/lint":"check the docs against those rules (costs nothing)"};function tg(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(eg[n])return eg[n];let o=po.find(r=>r.name===t);return o?o.desc:""}function ng(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return po.filter(n=>n.name.startsWith(t))}function og(e){let t=0,n="";for(let o of e){if(o==="["){t++;continue}if(o==="]"){t=Math.max(0,t-1);continue}t===0&&(n+=o)}return/<[^>]+>/.test(n)}var Ux=new RegExp(`^\\s*/(?:${po.map(e=>e.name).join("|")})(?:\\s|$)`),rg=e=>Ux.test(e),sg=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),ig=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),ag=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function Wx(e){let t=e.replace(/\r/g,"").split(`
338
+ `),n=[],o=0;for(;o<t.length;){let r=t[o];if(/^\s*```/.test(r)){let a=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)a.push(t[o++]);o++,n.push({kind:"code",lines:a});continue}if(sg(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&ig(t[o+1])){let a=ag(r);o+=2;let l=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)l.push(ag(t[o++]));n.push({kind:"table",header:a,rows:l});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 a=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);){let l=t[o++];a.push({ordered:/^\s*\d+\.\s+/.test(l),text:l.replace(/^\s*([-*]|\d+\.)\s+/,"")})}n.push({kind:"list",items:a});continue}if(r.trim()===""){o++;continue}if(rg(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])&&!rg(t[o])&&!sg(t[o])&&!(t[o].includes("|")&&o+1<t.length&&ig(t[o+1]));)i.push(t[o++]);n.push({kind:"para",text:i.join(" ")})}return n}function lu(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?An.bold(t.slice(2,-2)):t.startsWith("`")?Z(t.slice(1,-1)):An.italic(t.slice(1,-1)))}var Bx=(e,t)=>e+" ".repeat(Math.max(0,t-ha(e)));function ms(e,t,n,o={}){return lg(e,t,n,o)}function lg(e,t,n,o={}){let r=e.length,s=A=>Math.max(0,...A.split(`
339
+ `).map(D=>ha(D))),i=e.map((A,D)=>Math.max(ha(A),...t.map(N=>s(N[D]??"")))),a=Math.max(24,n),l=3*r+1,d=[...i],w=()=>d.reduce((A,D)=>A+D,0)+l,m=0;for(;w()>a&&m++<1e4;){let A=-1,D=6;for(let N=0;N<r;N++)d[N]>D&&(D=d[N],A=N);if(A===-1)break;d[A]-=1}let $=(A,D,N)=>An.gray(A+d.map(U=>"\u2500".repeat(U+2)).join(D)+N),S=An.gray("\u2502"),R=(A,D)=>{let N=d.map((z,de)=>{let ke=A[de]??"",xe=D?An.bold(ke):o.plain?ke:lu(ke);return ke.includes(`
340
+ `)?xe.split(`
341
+ `).flatMap(Pe=>fa(Pe,z,{hard:!0}).split(`
342
+ `)):fa(xe,z,{hard:!0}).split(`
343
+ `)}),U=Math.max(...N.map(z=>z.length)),O=[],Q=(z,de,ke)=>o.align?.[ke]==="right"?" ".repeat(Math.max(0,de-ha(z)))+z:Bx(z,de);for(let z=0;z<U;z++)O.push(d.map((de,ke)=>`${S} ${Q(N[ke][z]??"",de,ke)} `).join("")+S);return O.join(`
344
+ `)},C=[$("\u250C","\u252C","\u2510"),R(e,!0)];return C.push(t.length===0?$("\u2514","\u2534","\u2518"):$("\u251C","\u253C","\u2524")),t.forEach((A,D)=>{C.push(R(A,!1)),C.push(D===t.length-1?$("\u2514","\u2534","\u2518"):$("\u251C","\u253C","\u2524"))}),C.join(`
345
+ `)}function Hx(e,t){switch(e.kind){case"heading":return An.bold(e.text);case"hr":return An.gray("\u2500".repeat(t));case"para":return fa(lu(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="",...a]=fa(lu(o.text),Math.max(10,t-s.length)).split(`
346
346
  `);return` ${r} ${i}`+a.map(l=>`
347
347
  ${s}${l}`).join("")}).join(`
348
348
  `)}case"code":return e.lines.map(n=>An.gray(" "+n)).join(`
349
- `);case"table":return rg(e.header,e.rows,t)}}function ru(e,t){let n=Math.max(20,t);return jx(e).map(o=>Lx(o,n)).join(`
350
-
351
- `)}re();import Ox from"picocolors";var _x=[127,86,217],Mx=[22,38,43],sg={T:_x,E:Mx},ms=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],su=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,Fx=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function ig(){if(!Ox.isColorSupported)return[];let e=ms[0].length,t=[];for(let n=0;n<ms.length;n+=2){let o="";for(let r=0;r<e;r++){let s=sg[ms[n][r]],i=n+1<ms.length?sg[ms[n+1][r]]:void 0;s&&i?o+=`${su(s)}${Fx(i)}\u2580\x1B[49m\x1B[39m`:s?o+=`${su(s)}\u2580\x1B[39m`:i?o+=`${su(i)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function gs(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 En(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function lg(e,t,n){let o=e>0&&e<=n?e:t;return Math.max(0,Math.floor((n-o)/1e3))}function St(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function cr(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var lr=(e,t)=>` ${e.padEnd(13)}${t}`;function Ux(e,t){let n=[Zr("\u270E document360-writer")+we.gray(` v${e.version} \xB7 engine v${e.engineVersion}${e.captureVersion?` \xB7 capture v${e.captureVersion}`:""}`),we.gray(" Reads your code, writes your docs."),"",lr("Claude:",`${e.claude}${we.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),lr("Document360:",e.configured?e.loggedOut?we.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?we.gray(` (${e.sessionHint})`):""}`:we.yellow("not set up \u2014 run /init")),lr("Profile:",e.configured?`${e.profile}${we.gray(` (${e.apiUrl})`)}${e.prod?we.bold(we.yellow(" \u26A0 PRODUCTION")):""}`:we.gray("\u2014 (run /init)")),lr("Project:",e.project),lr("Mode:",we.gray(e.mode)),lr("cwd:",we.gray(e.cwd))],o=ig();if(o.length===0)return n.join(`
352
- `);let r=2,s=3,i=au(o[0]);if(!(t>=r+i+s+Math.max(...n.map(g=>au(g)))))return[...o.map(g=>" "+g),...n].join(`
353
- `);let l=Math.max(0,Math.floor((n.length-o.length)/2)),d=[];for(let g=0;g<Math.max(o.length+l,n.length);g++){let w=o[g-l]??" ".repeat(i);d.push((" ".repeat(r)+w+" ".repeat(s)+(n[g]??"")).trimEnd())}return d.join(`
354
- `)}var Wx={error:we.red,warn:we.yellow,ok:we.green,info:we.gray},ag=9;function lu(e){return e.length>=ag?`${e} `:e.padEnd(ag)}function fa(e){return e.replace(/^(\s*• |)([^\x00-\x7F][\u{1F000}-\u{1FAFF}‍️]*) (?=\S)/gmu,"$1$2 ")}function cu(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return Ux(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",s=Math.max(10,n-4),i=50,a=e.text.split(`
355
- `).flatMap(d=>iu(d,s,{hard:!0}).split(`
356
- `)),l=Math.max(0,a.length-i);return l>0&&(a=[...a.slice(0,i),we.dim(`\u2026 +${l} more lines`)]),`
357
- `+a.map((d,g)=>o+(g===0?Z(" \u276F "):" ")+d+" ".repeat(Math.max(0,s-au(d))+1)+r).join(`
349
+ `);case"table":return lg(e.header,e.rows,t)}}function cu(e,t){let n=Math.max(20,t);return Wx(e).map(o=>Hx(o,n)).join(`
350
+
351
+ `)}re();import Gx from"picocolors";var qx=[127,86,217],Vx=[22,38,43],cg={T:qx,E:Vx},gs=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],uu=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,Yx=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function ug(){if(!Gx.isColorSupported)return[];let e=gs[0].length,t=[];for(let n=0;n<gs.length;n+=2){let o="";for(let r=0;r<e;r++){let s=cg[gs[n][r]],i=n+1<gs.length?cg[gs[n+1][r]]:void 0;s&&i?o+=`${uu(s)}${Yx(i)}\u2580\x1B[49m\x1B[39m`:s?o+=`${uu(s)}\u2580\x1B[39m`:i?o+=`${uu(i)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function ws(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 En(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function pg(e,t,n){let o=e>0&&e<=n?e:t;return Math.max(0,Math.floor((n-o)/1e3))}function St(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function ur(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var cr=(e,t)=>` ${e.padEnd(13)}${t}`;function Kx(e,t){let n=[es("\u270E document360-writer")+ye.gray(` v${e.version} \xB7 engine v${e.engineVersion}${e.captureVersion?` \xB7 capture v${e.captureVersion}`:""}`),ye.gray(" Reads your code, writes your docs."),"",cr("Claude:",`${e.claude}${ye.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),cr("Document360:",e.configured?e.loggedOut?ye.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?ye.gray(` (${e.sessionHint})`):""}`:ye.yellow("not set up \u2014 run /init")),cr("Profile:",e.configured?`${e.profile}${ye.gray(` (${e.apiUrl})`)}${e.prod?ye.bold(ye.yellow(" \u26A0 PRODUCTION")):""}`:ye.gray("\u2014 (run /init)")),cr("Project:",e.project),cr("Mode:",ye.gray(e.mode)),cr("cwd:",ye.gray(e.cwd))],o=ug();if(o.length===0)return n.join(`
352
+ `);let r=2,s=3,i=pu(o[0]);if(!(t>=r+i+s+Math.max(...n.map(w=>pu(w)))))return[...o.map(w=>" "+w),...n].join(`
353
+ `);let l=Math.max(0,Math.floor((n.length-o.length)/2)),d=[];for(let w=0;w<Math.max(o.length+l,n.length);w++){let m=o[w-l]??" ".repeat(i);d.push((" ".repeat(r)+m+" ".repeat(s)+(n[w]??"")).trimEnd())}return d.join(`
354
+ `)}var zx={error:ye.red,warn:ye.yellow,ok:ye.green,info:ye.gray},dg=9;function hu(e){return e.length>=dg?`${e} `:e.padEnd(dg)}function ma(e){return e.replace(/^(\s*• |)([^\x00-\x7F][\u{1F000}-\u{1FAFF}‍️]*) (?=\S)/gmu,"$1$2 ")}function fu(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return Kx(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",s=Math.max(10,n-4),i=50,a=e.text.split(`
355
+ `).flatMap(d=>du(d,s,{hard:!0}).split(`
356
+ `)),l=Math.max(0,a.length-i);return l>0&&(a=[...a.slice(0,i),ye.dim(`\u2026 +${l} more lines`)]),`
357
+ `+a.map((d,w)=>o+(w===0?Z(" \u276F "):" ")+d+" ".repeat(Math.max(0,s-pu(d))+1)+r).join(`
358
358
  `)}case"assistant":return`
359
- `+ru(e.text,n);case"tool":{let o=e.arg!==null?we.gray(`${e.sep}(${e.arg})`):"";return`
360
- `+iu(we.gray("\u25CF ")+e.title+o,n)}case"doc":{let o=[e.category,e.note].filter(s=>!!s).map(s=>we.gray(` \xB7 ${s}`)),r=e.loud?we.gray(" \xB7 ")+we.bold(we.yellow(e.loud)):"";return`
361
- `+iu(we.green("\u25CF ")+Z(we.bold(lu(e.verb)))+we.bold(e.title)+o.join("")+r,n)}case"tool-result":{let o=e.isError?we.red:we.gray,r=e.lines.map((s,i)=>o((i===0?" \u23BF ":" ")+s));return e.hidden>0&&r.push(we.dim(` \u2026 +${e.hidden} lines`)),r.join(`
362
- `)}case"diff":{let o=i=>i===1?"":"s",s=[we.gray(` \u23BF Added ${e.added} line${o(e.added)}, removed ${e.removed} line${o(e.removed)}`),...e.lines];return e.hidden>0&&s.push(we.dim(` \u2026 +${e.hidden} more diff lines`)),s.join(`
363
- `)}case"link":return e.lines.map(o=>Z(ts(` \u2B95 ${o}`))).join(`
359
+ `+cu(e.text,n);case"tool":{let o=e.arg!==null?ye.gray(`${e.sep}(${e.arg})`):"";return`
360
+ `+du(ye.gray("\u25CF ")+e.title+o,n)}case"doc":{let o=[e.category,e.note].filter(s=>!!s).map(s=>ye.gray(` \xB7 ${s}`)),r=e.loud?ye.gray(" \xB7 ")+ye.bold(ye.yellow(e.loud)):"";return`
361
+ `+du(ye.green("\u25CF ")+Z(ye.bold(hu(e.verb)))+ye.bold(e.title)+o.join("")+r,n)}case"tool-result":{let o=e.isError?ye.red:ye.gray,r=e.lines.map((s,i)=>o((i===0?" \u23BF ":" ")+s));return e.hidden>0&&r.push(ye.dim(` \u2026 +${e.hidden} lines`)),r.join(`
362
+ `)}case"diff":{let o=i=>i===1?"":"s",s=[ye.gray(` \u23BF Added ${e.added} line${o(e.added)}, removed ${e.removed} line${o(e.removed)}`),...e.lines];return e.hidden>0&&s.push(ye.dim(` \u2026 +${e.hidden} more diff lines`)),s.join(`
363
+ `)}case"link":return e.lines.map(o=>Z(ns(` \u2B95 ${o}`))).join(`
364
364
  `);case"preview":return`
365
- `+Zr(`\u25A3 Preview \u2014 ${e.name}`)+`
365
+ `+es(`\u25A3 Preview \u2014 ${e.name}`)+`
366
366
 
367
- `+ru(e.text,n);case"note":return`
368
- `+Wx[e.tone](ts(fa(e.text)));case"block":return`
369
- `+e.text;case"done":{let o=e.inTokens&&e.inTokens>0?` \xB7 ${gs(e.inTokens)} in${e.cachedPct!=null?` (${e.cachedPct}% cached)`:""}`:"",r=e.activeSeconds!==void 0&&da(e.activeSeconds,e.seconds)?`${En(e.seconds)} elapsed \xB7 ${En(e.activeSeconds)} working`:En(e.seconds),s=e.costUsd>0?` \xB7 this turn ${St(e.costUsd)}`+(e.sessionCostUsd!==void 0&&e.sessionCostUsd>e.costUsd?` \xB7 session ${St(e.sessionCostUsd)}`:""):"";return`
370
- `+(e.ok?we.magenta("\u2736 "):we.red("\u2736 "))+we.gray(`Cooked for ${r} \xB7 ${gs(e.tokens)} tokens out${o}${s}`)}}}function cg(e,t,n){let o=e.map(i=>cu(i,t));if(n===void 0||n<=0)return o.join(`
367
+ `+cu(e.text,n);case"note":return`
368
+ `+zx[e.tone](ns(ma(e.text)));case"block":return`
369
+ `+e.text;case"done":{let o=e.inTokens&&e.inTokens>0?` \xB7 ${ws(e.inTokens)} in${e.cachedPct!=null?` (${e.cachedPct}% cached)`:""}`:"",r=e.activeSeconds!==void 0&&pa(e.activeSeconds,e.seconds)?`${En(e.seconds)} elapsed \xB7 ${En(e.activeSeconds)} working`:En(e.seconds),s=e.costUsd>0?` \xB7 this turn ${St(e.costUsd)}`+(e.sessionCostUsd!==void 0&&e.sessionCostUsd>e.costUsd?` \xB7 session ${St(e.sessionCostUsd)}`:""):"";return`
370
+ `+(e.ok?ye.magenta("\u2736 "):ye.red("\u2736 "))+ye.gray(`Cooked for ${r} \xB7 ${ws(e.tokens)} tokens out${o}${s}`)}}}function hg(e,t,n){let o=e.map(i=>fu(i,t));if(n===void 0||n<=0)return o.join(`
371
371
  `);let r=[],s=0;for(let i=o.length-1;i>=0;i--){let a=o[i].split(`
372
372
  `).length;if(r.length>0&&s+a>n)break;r.unshift(o[i]),s+=a}return r.join(`
373
- `)}var uu=3;function du(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 pu(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function hu(e,t){return t.map(n=>{let o=0;try{o=Bx(Hx(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function fu(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, so be efficient:
373
+ `)}var mu=3;function gu(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 wu(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function yu(e,t){return t.map(n=>{let o=0;try{o=Xx(Qx(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function bu(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, so be efficient:
374
374
  - Read ONLY the article files listed below. Do NOT read source code, other articles, or fetch the live portal; you already have everything you need.
375
375
  - 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.
376
376
  - 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.
377
377
  - Work only on these files:
378
378
  `+e.paths.map(t=>`- ${t}`).join(`
379
- `)}function mu(e,t,n){let o=e.reduce((a,l)=>a+l.paths.length,0),[r,s]=t.usd;return[`Convert ${o} article${o===1?"":"s"} to DFM in ${e.length} batch${e.length===1?"":"es"} (\u2264${n} agents at once):`,...e.map(a=>` \u2022 ${a.label} \u2014 ${a.paths.length} article${a.paths.length===1?"":"s"}`),"",`Estimated cost: ${St(r)}\u2013${St(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function gu(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,C)=>v+o(C),0),a=r.reduce((v,C)=>v+o(C),0),l=e.reduce((v,C)=>v+C.costUsd,0),d=e.reduce((v,C)=>v+C.outputTokens,0),g=n==="api"?`${St(l)} total`:cr(d),w=`${r.length}/${e.length} batch${e.length===1?"":"es"} completed`,k=v=>`${v} article${v===1?"":"s"}`,S=[];if(s.length===0)S.push(`Converted ${k(i)} (${w}) successfully \xB7 ${g}.`);else{S.push(`Converted ${a}/${k(i)} (${w}) \xB7 ${g}.`),S.push(`${s.length} batch${s.length===1?"":"es"} failed \u2014 re-run /convert to retry:`);for(let v of s)S.push(` \u2717 ${v.label}${v.error?` \u2014 ${v.error}`:""}`)}return S}async function ug(e,t){if(!Vx(t.cwd))return console.log(O("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=du(e),r=zx(t.cwd,t.profileName);if(r.length===0)return console.log(O("No tracked articles in d360-category-map.json. Save some to Document360 first (/push), then /convert.")),{kind:"continue"};let s=pu(r,n);if(s.length===0)return console.log(O(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let i=qx(s),a=`/convert${n?` --scope ${n}`:""} --run`,{model:l,forced:d}=Yx(t.cwd,"light");if(!o){let w=Gx({files:hu(t.cwd,s),op:"convert",model:l});n&&console.log(f(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let k of mu(i,w,uu))console.log(k);return console.log(f(`Model: ${l}${d?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(f(`Run ${a} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Converting ${s.length} articles in ${i.length} batches (\u2264${uu} agents at once) on ${l}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let g=Date.now();try{for await(let w of Kx({cwd:t.cwd,partitions:i,promptFor:fu,concurrency:uu,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:l}))if(w.type==="partition_status")w.status==="running"?console.log(f(` \u25B8 ${w.label} \u2014 converting\u2026`)):w.status==="done"?console.log(q(` \u2713 ${w.label}`)):console.log(O(` \u2717 ${w.label}`));else if(w.type==="run_done"){console.log("");let k=process.env.ANTHROPIC_API_KEY?"api":"subscription",S=Tn(w,"The conversion");for(let v of S??gu(w.results,i,k))console.log(S||!w.ok?H(v):q(v));console.log(f(zt(Ct(g,w.results,w.totalCostUsd))))}}catch(w){console.log(O(`Convert run failed: ${w.message}`))}return console.log(""),{kind:"continue"}}import{statSync as kR}from"node:fs";import{resolve as $R}from"node:path";import{estimateBulkCost as vR,lintDocs as xR,planFindingPartitions as RR,planPartitions as CR,readDocsPlan as SR,readProjectConfig as Tu,DEFAULT_DOCS_DIR as Rg,resolveModelForOperation as kg,runPartitioned as $g,partitionCoverage as vg,stampArticles as xg,readReviewerNotes as PR,renderNotesForPrompt as TR,notesForPath as AR,CONTENT_CAP_VERSION as ER}from"document360-engine";re();import{lintDocs as $u,guidanceForRules as Jx,planFindingPartitions as Zx,runPartitioned as eR,partitionCoverage as tR,resolveModelForOperation as nR,stampArticles as oR,applyDeterministicFixes as rR,isMechanical as sR}from"document360-engine";import{CONTENT_CAP_VERSION as dg}from"document360-engine";function pg(e){let t=e.trim().split(/\s+/);return t.includes("--fix")?t[0]==="/review"?"review":t[0]==="/lint"||t[0]==="/check"?"lint":null:null}function hg(e){return e.trim().split(/\s+/).slice(1).find(t=>!t.startsWith("--"))}function it(e){return e==="review"?{reviewedCap:dg}:{checkedCap:dg}}import{gateFixTarget as Xx}from"document360-engine";var yu=e=>"ruleId"in e,ma=e=>yu(e)?e.severity:"warning",Nn=e=>e===1?"":"s";function bu(e,t){let n=t??Xx(e),o=n?` ${n}`:"";return e.unreviewed.length>0?`/review${o} --blocked --fix`:`/lint${o} --blocked --fix`}var wu=new Map;var Qx=e=>yu(e)?e.fp||`${e.ruleId}:${e.path}:${e.line}:${e.term}`:`${e.kind}:${e.path}:${e.line}`;function ws(e){let{cwd:t,after:n,scope:o,aborted:r,blocked:s}=e,i=n.filter(S=>ma(S)==="error").length,a=n.filter(S=>ma(S)==="warning").length,l=n.filter(S=>ma(S)==="suggestion").length,d=Pe("/lint","--blocked --fix",o);if(r){let S=Pe("/lint",s?"--blocked --fix":"--fix",o);return{text:`Stopped. Nothing else changed \u2014 ${S} picks up where this left off.`,cmd:S}}if(i>0){let S=n.filter(L=>ma(L)==="error"),v=new Set(S.map(L=>L.path)).size,C=`${t}::${o??""}`,T=S.map(Qx).sort().join("|"),D=wu.get(C)===T;if(wu.set(C,T),D){let L=Pe("/lint","--blocked --full",o),B=[...new Set(S.filter(yu).map(M=>M.ruleId))];return{text:`The same ${i} error${Nn(i)} in ${v} article${Nn(v)} survived two ${d} passes, so a third would change nothing \u2014 ${i===1?"it needs":"they need"} a person. ${L} shows ${i===1?"it":"them"} in place. If ${B.length===1?`${B[0]} is`:"a rule is"} wrong for your product, switch it off in .d360-writer/config.json under "styleGuide": { "rules": { "<rule>": "off" } }.`,cmd:L}}return{text:`${i} error${Nn(i)} in ${v} article${Nn(v)} still block${i===1?"s":""} publishing. ${d} has another go at ${i===1?"it":"just those"} \u2014 if a second pass leaves the same ones, they need a human eye.`,cmd:d}}wu.delete(`${t}::${o??""}`);let g=a>0&&l>0?`${a} warning${Nn(a)} and ${l} suggestion${Nn(l)} remain (neither blocks publishing). `:a>0?`${a} warning${Nn(a)} remain${a===1?"s":""}, which ${a===1?"does":"do"} not block publishing. `:l>0?`${l} suggestion${Nn(l)} remain${l===1?"s":""} \u2014 ${l===1?"it is":"they are"} judgment calls and ${l===1?"does":"do"} not block publishing. `:"",w=g===""?"\u2713 Nothing left to fix. ":`\u2713 ${g}`,k=o?"/push":"/push --all";return Bt(t,{text:`${w}Nothing is blocking${o?` in ${o}`:""} \u2014 ${k} saves the articles to Document360 as drafts.`,cmd:k},w,o)}var wa={error:0,warning:1,suggestion:2},iR={error:"\u2717",warning:"\u26A0",suggestion:"\xB7"},aR=10,lR=8,cR=96,fg=34,Xt=e=>"ruleId"in e,Dn=e=>Xt(e)?e.severity:"warning",vu=e=>Xt(e)?e.ruleId:e.kind,po=e=>e.fileLine??e.line;function un(e){return e.includes("--blocked")}function dn(e,t){return un(t)?e.filter(n=>Dn(n)==="error"):e}function ys(e,t){return`/lint${t?` ${t}`:""}${un(e)?" --blocked":""} --fix`}function ku(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function ga(e){let t={error:0,warning:0,suggestion:0};for(let n of e)t[Dn(n)]++;return t}function mg(e){let t=[];for(let n of["error","warning","suggestion"])e[n]>0&&t.push(`${e[n]} ${n}${e[n]===1?"":"s"}`);return t.join(" \xB7 ")}function bs(e,t={}){let n=t.baselined?[]:e.filter(w=>Xt(w)&&w.baselined),o=t.baselined?e:e.filter(w=>!(Xt(w)&&w.baselined)),r=n.length>0?[me("\u2139",`${n.length} issue${n.length===1?"":"s"} ${n.length===1?"was":"were"} already in your articles when you chose this style guide, so ${n.length===1?"it never blocks":"they never block"} publishing. /lint --baselined shows ${n.length===1?"it":"them"}.`)]:[];if(o.length===0)return[me("\u2713","No issues found \u2014 no leaked internals, unknown commands, stale version facts, AI-tells, em dashes, or broken callouts in the docs."),...r];let s=new Map;for(let w of o){let k=s.get(w.path)??[];k.push(w),s.set(w.path,k)}let i=ga(o),a=[me("\u26A0",`${o.length} issue${o.length===1?"":"s"} in ${s.size} article${s.size===1?"":"s"} \u2014 ${mg(i)}.`),""],l=[...s.entries()].sort((w,k)=>{let S=ga(w[1]);return ga(k[1]).error-S.error||k[1].length-w[1].length||w[0].localeCompare(k[0])}),d=t.full?l:l.slice(0,aR);for(let[w,k]of d){a.push(` ${w} ${f(mg(ga(k)))}`);let S=new Map;for(let D of k){let L=vu(D),B=S.get(L)??[];B.push(D),S.set(L,B)}let v=[...S.entries()].sort((D,L)=>wa[Dn(D[1][0])]-wa[Dn(L[1][0])]||L[1].length-D[1].length||D[0].localeCompare(L[0])),C=t.full?v:v.slice(0,lR);for(let[D,L]of C){let B=[...L].sort((se,ee)=>po(se)-po(ee)),M=iR[Dn(B[0])],z=new Set(B.map(se=>se.term)).size===1?` ${ku(`"${B[0].term}"`,fg)}`:"",de=B.length>1?f(` \xD7${B.length}`):"",be=t.full?B[0].message:ku(B[0].message,cR);a.push(` ${M} ${D}${de}${z}`),a.push(` ${f(be)}`);let $e=B.map(se=>z?`L${po(se)}`:`L${po(se)} ${ku(`"${se.term}"`,fg)}`),Ce=t.full?$e:$e.slice(0,12),fe=$e.length-Ce.length;a.push(` ${f(Ce.join(", ")+(fe>0?` \u2026+${fe}`:""))}`)}let T=v.length-C.length;T>0&&a.push(f(` \u2026${T} more rule${T===1?"":"s"} fired here (/lint ${w} --full)`)),a.push("")}let g=l.length-d.length;return g>0&&(a.push(f(` \u2026and ${g} more article${g===1?"":"s"} (/lint <category> narrows \xB7 /lint --full lists every one)`)),a.push("")),a.push(...r),a}var uR=200;function ya(e){let n=[...e.filter(l=>!(Xt(l)&&l.baselined))].sort((l,d)=>wa[Dn(l)]-wa[Dn(d)]||l.path.localeCompare(d.path)||po(l)-po(d)),o=n.slice(0,uR),r=n.length-o.length,s=new Map;for(let l of o){let d=s.get(l.path)??[];d.push(l),s.set(l.path,d)}let i=[...s.entries()].map(([l,d])=>[l,...d.map(g=>` - L${po(g)} [${vu(g)}] (${Dn(g)}): "${g.term}": ${g.message}`)].join(`
379
+ `)}function ku(e,t,n){let o=e.reduce((a,l)=>a+l.paths.length,0),[r,s]=t.usd;return[`Convert ${o} article${o===1?"":"s"} to DFM in ${e.length} batch${e.length===1?"":"es"} (\u2264${n} agents at once):`,...e.map(a=>` \u2022 ${a.label} \u2014 ${a.paths.length} article${a.paths.length===1?"":"s"}`),"",`Estimated cost: ${St(r)}\u2013${St(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function $u(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),a=r.reduce((R,C)=>R+o(C),0),l=e.reduce((R,C)=>R+C.costUsd,0),d=e.reduce((R,C)=>R+C.outputTokens,0),w=n==="api"?`${St(l)} total`:ur(d),m=`${r.length}/${e.length} batch${e.length===1?"":"es"} completed`,$=R=>`${R} article${R===1?"":"s"}`,S=[];if(s.length===0)S.push(`Converted ${$(i)} (${m}) successfully \xB7 ${w}.`);else{S.push(`Converted ${a}/${$(i)} (${m}) \xB7 ${w}.`),S.push(`${s.length} batch${s.length===1?"":"es"} failed \u2014 re-run /convert to retry:`);for(let R of s)S.push(` \u2717 ${R.label}${R.error?` \u2014 ${R.error}`:""}`)}return S}async function fg(e,t){if(!eR(t.cwd))return console.log(_("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=gu(e),r=oR(t.cwd,t.profileName);if(r.length===0)return console.log(_("No tracked articles in d360-category-map.json. Save some to Document360 first (/push), then /convert.")),{kind:"continue"};let s=wu(r,n);if(s.length===0)return console.log(_(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let i=Zx(s),a=`/convert${n?` --scope ${n}`:""} --run`,{model:l,forced:d}=tR(t.cwd,"light");if(!o){let m=Jx({files:yu(t.cwd,s),op:"convert",model:l});n&&console.log(f(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let $ of ku(i,m,mu))console.log($);return console.log(f(`Model: ${l}${d?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(f(`Run ${a} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Converting ${s.length} articles in ${i.length} batches (\u2264${mu} agents at once) on ${l}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let w=Date.now();try{for await(let m of nR({cwd:t.cwd,partitions:i,promptFor:bu,concurrency:mu,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:l}))if(m.type==="partition_status")m.status==="running"?console.log(f(` \u25B8 ${m.label} \u2014 converting\u2026`)):m.status==="done"?console.log(q(` \u2713 ${m.label}`)):console.log(_(` \u2717 ${m.label}`));else if(m.type==="run_done"){console.log("");let $=process.env.ANTHROPIC_API_KEY?"api":"subscription",S=Tn(m,"The conversion");for(let R of S??$u(m.results,i,$))console.log(S||!m.ok?H(R):q(R));console.log(f(zt(Ct(w,m.results,m.totalCostUsd))))}}catch(m){console.log(_(`Convert run failed: ${m.message}`))}return console.log(""),{kind:"continue"}}import{statSync as TR}from"node:fs";import{resolve as AR}from"node:path";import{estimateBulkCost as ER,lintDocs as NR,planFindingPartitions as DR,planPartitions as jR,readDocsPlan as IR,readProjectConfig as ju,DEFAULT_DOCS_DIR as Tg,resolveModelForOperation as Rg,runPartitioned as Cg,partitionCoverage as Sg,stampArticles as Pg,readReviewerNotes as LR,renderNotesForPrompt as OR,notesForPath as _R,CONTENT_CAP_VERSION as MR}from"document360-engine";re();import{lintDocs as Su,guidanceForRules as iR,planFindingPartitions as aR,runPartitioned as lR,partitionCoverage as cR,resolveModelForOperation as uR,stampArticles as dR,applyDeterministicFixes as pR,isMechanical as hR}from"document360-engine";import{CONTENT_CAP_VERSION as mg}from"document360-engine";function gg(e){let t=e.trim().split(/\s+/);return t.includes("--fix")?t[0]==="/review"?"review":t[0]==="/lint"||t[0]==="/check"?"lint":null:null}function wg(e){return e.trim().split(/\s+/).slice(1).find(t=>!t.startsWith("--"))}function it(e){return e==="review"?{reviewedCap:mg}:{checkedCap:mg}}import{gateFixTarget as rR}from"document360-engine";var xu=e=>"ruleId"in e,ga=e=>xu(e)?e.severity:"warning",Nn=e=>e===1?"":"s";function Ru(e,t){let n=t??rR(e),o=n?` ${n}`:"";return e.unreviewed.length>0?`/review${o} --blocked --fix`:`/lint${o} --blocked --fix`}var vu=new Map;var sR=e=>xu(e)?e.fp||`${e.ruleId}:${e.path}:${e.line}:${e.term}`:`${e.kind}:${e.path}:${e.line}`;function ys(e){let{cwd:t,after:n,scope:o,aborted:r,blocked:s}=e,i=n.filter(S=>ga(S)==="error").length,a=n.filter(S=>ga(S)==="warning").length,l=n.filter(S=>ga(S)==="suggestion").length,d=Ce("/lint","--blocked --fix",o);if(r){let S=Ce("/lint",s?"--blocked --fix":"--fix",o);return{text:`Stopped. Nothing else changed \u2014 ${S} picks up where this left off.`,cmd:S}}if(i>0){let S=n.filter(N=>ga(N)==="error"),R=new Set(S.map(N=>N.path)).size,C=`${t}::${o??""}`,A=S.map(sR).sort().join("|"),D=vu.get(C)===A;if(vu.set(C,A),D){let N=Ce("/lint","--blocked --full",o),U=[...new Set(S.filter(xu).map(O=>O.ruleId))];return{text:`The same ${i} error${Nn(i)} in ${R} article${Nn(R)} survived two ${d} passes, so a third would change nothing \u2014 ${i===1?"it needs":"they need"} a person. ${N} shows ${i===1?"it":"them"} in place. If ${U.length===1?`${U[0]} is`:"a rule is"} wrong for your product, switch it off in .d360-writer/config.json under "styleGuide": { "rules": { "<rule>": "off" } }.`,cmd:N}}return{text:`${i} error${Nn(i)} in ${R} article${Nn(R)} still block${i===1?"s":""} publishing. ${d} has another go at ${i===1?"it":"just those"} \u2014 if a second pass leaves the same ones, they need a human eye.`,cmd:d}}vu.delete(`${t}::${o??""}`);let w=a>0&&l>0?`${a} warning${Nn(a)} and ${l} suggestion${Nn(l)} remain (neither blocks publishing). `:a>0?`${a} warning${Nn(a)} remain${a===1?"s":""}, which ${a===1?"does":"do"} not block publishing. `:l>0?`${l} suggestion${Nn(l)} remain${l===1?"s":""} \u2014 ${l===1?"it is":"they are"} judgment calls and ${l===1?"does":"do"} not block publishing. `:"",m=w===""?"\u2713 Nothing left to fix. ":`\u2713 ${w}`,$=o?"/push":"/push --all";return Bt(t,{text:`${m}Nothing is blocking${o?` in ${o}`:""} \u2014 ${$} saves the articles to Document360 as drafts.`,cmd:$},m,o)}var ya={error:0,warning:1,suggestion:2},fR={error:"\u2717",warning:"\u26A0",suggestion:"\xB7"},mR=10,gR=8,wR=96,yg=34,Xt=e=>"ruleId"in e,Dn=e=>Xt(e)?e.severity:"warning",Pu=e=>Xt(e)?e.ruleId:e.kind,ho=e=>e.fileLine??e.line;function un(e){return e.includes("--blocked")}function dn(e,t){return un(t)?e.filter(n=>Dn(n)==="error"):e}function bs(e,t){return`/lint${t?` ${t}`:""}${un(e)?" --blocked":""} --fix`}function Cu(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function wa(e){let t={error:0,warning:0,suggestion:0};for(let n of e)t[Dn(n)]++;return t}function bg(e){let t=[];for(let n of["error","warning","suggestion"])e[n]>0&&t.push(`${e[n]} ${n}${e[n]===1?"":"s"}`);return t.join(" \xB7 ")}function ks(e,t={}){let n=t.baselined?[]:e.filter(m=>Xt(m)&&m.baselined),o=t.baselined?e:e.filter(m=>!(Xt(m)&&m.baselined)),r=n.length>0?[ge("\u2139",`${n.length} issue${n.length===1?"":"s"} ${n.length===1?"was":"were"} already in your articles when you chose this style guide, so ${n.length===1?"it never blocks":"they never block"} publishing. /lint --baselined shows ${n.length===1?"it":"them"}.`)]:[];if(o.length===0)return[ge("\u2713","No issues found \u2014 no leaked internals, unknown commands, stale version facts, AI-tells, em dashes, or broken callouts in the docs."),...r];let s=new Map;for(let m of o){let $=s.get(m.path)??[];$.push(m),s.set(m.path,$)}let i=wa(o),a=[ge("\u26A0",`${o.length} issue${o.length===1?"":"s"} in ${s.size} article${s.size===1?"":"s"} \u2014 ${bg(i)}.`),""],l=[...s.entries()].sort((m,$)=>{let S=wa(m[1]);return wa($[1]).error-S.error||$[1].length-m[1].length||m[0].localeCompare($[0])}),d=t.full?l:l.slice(0,mR);for(let[m,$]of d){a.push(` ${m} ${f(bg(wa($)))}`);let S=new Map;for(let D of $){let N=Pu(D),U=S.get(N)??[];U.push(D),S.set(N,U)}let R=[...S.entries()].sort((D,N)=>ya[Dn(D[1][0])]-ya[Dn(N[1][0])]||N[1].length-D[1].length||D[0].localeCompare(N[0])),C=t.full?R:R.slice(0,gR);for(let[D,N]of C){let U=[...N].sort((se,te)=>ho(se)-ho(te)),O=fR[Dn(U[0])],z=new Set(U.map(se=>se.term)).size===1?` ${Cu(`"${U[0].term}"`,yg)}`:"",de=U.length>1?f(` \xD7${U.length}`):"",ke=t.full?U[0].message:Cu(U[0].message,wR);a.push(` ${O} ${D}${de}${z}`),a.push(` ${f(ke)}`);let xe=U.map(se=>z?`L${ho(se)}`:`L${ho(se)} ${Cu(`"${se.term}"`,yg)}`),Pe=t.full?xe:xe.slice(0,12),fe=xe.length-Pe.length;a.push(` ${f(Pe.join(", ")+(fe>0?` \u2026+${fe}`:""))}`)}let A=R.length-C.length;A>0&&a.push(f(` \u2026${A} more rule${A===1?"":"s"} fired here (/lint ${m} --full)`)),a.push("")}let w=l.length-d.length;return w>0&&(a.push(f(` \u2026and ${w} more article${w===1?"":"s"} (/lint <category> narrows \xB7 /lint --full lists every one)`)),a.push("")),a.push(...r),a}var yR=200;function ba(e){let n=[...e.filter(l=>!(Xt(l)&&l.baselined))].sort((l,d)=>ya[Dn(l)]-ya[Dn(d)]||l.path.localeCompare(d.path)||ho(l)-ho(d)),o=n.slice(0,yR),r=n.length-o.length,s=new Map;for(let l of o){let d=s.get(l.path)??[];d.push(l),s.set(l.path,d)}let i=[...s.entries()].map(([l,d])=>[l,...d.map(w=>` - L${ho(w)} [${Pu(w)}] (${Dn(w)}): "${w.term}": ${w.message}`)].join(`
380
380
  `)).join(`
381
- `),a=Jx(o.map(l=>({id:vu(l),message:l.message,link:Xt(l)?l.link:void 0})));return["The documentation linter found issues in already-written articles. FIX each one by EDITING the","article in place. Do not rewrite whole articles; just resolve the flagged problems. Ground every change","in the actual product source (the authoritativeSourceFiles); never invent.","","Errors are listed first: those are defects of fact or structure, and they matter most.","",...a.length>0?["How to fix, by rule:",...a,""]:[],"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.","",...r>0?[`Note: ${r} further finding${r===1?"":"s"} were left out of this batch to keep it actionable. Run /lint --fix again afterwards to pick them up.`,""]:[],"Issues:",i].join(`
382
- `)}var ur=3;function dr(e,t,n){let o=n.filter(a=>!(Xt(a)&&a.baselined)),r=dn(o,t).filter(a=>Xt(a)&&sR(a));if(r.length===0)return{fixed:0,skipped:0,lines:[],paths:[]};let s=rR(e,r),i=[];if(s.fixed.length>0){let a=new Set(s.fixed.map(l=>l.path)).size;i.push(q(me("\u2713",`Fixed ${s.fixed.length} ${s.fixed.length===1?"issue":"issues"} in ${a} ${a===1?"article":"articles"} \u2014 a straight swap, so no model and no cost.`)))}return s.skipped.length>0&&i.push(f(` ${s.skipped.length} could not be applied automatically (${s.skipped[0].reason}) \u2014 left for the editor pass.`)),{fixed:s.fixed.length,skipped:s.skipped.length,lines:i,paths:s.paths}}function xu(e,t,n){let o=dn(n.filter(a=>!(Xt(a)&&a.baselined)),t);if(o.length===0)return null;let r=t.find(a=>!a.startsWith("--")),s=ys(t,r),i=Zx(o);return i.length<=1?{kind:"single",prompt:ya(o),display:s,findings:o.length}:{kind:"partitioned",partitions:i,display:s,articles:new Set(o.map(a=>a.path)).size,findings:o.length,promptFor:a=>{let l=new Set(a.paths);return ya(o.filter(d=>l.has(d.path)))}}}function Ru(e,t,n){let o=t.find(l=>!l.startsWith("--")),r=o?` in ${o}`:"",s=n.filter(l=>!(Xt(l)&&l.baselined)),i=new Set(s.map(l=>l.path)).size;return{lines:un(t)?s.length===0?[`\u2713 Nothing is blocking publishing${r} \u2014 no style errors at all.`]:[`\u2713 Nothing is blocking publishing${r}. The ${s.length} issue${s.length===1?"":"s"} left ${s.length===1?"is a warning or a suggestion":"are warnings and suggestions"}, which never block it.`,` /lint${o?` ${o}`:""} --fix clears ${s.length===1?"it":"those"} too \u2014 ${s.length} issue${s.length===1?"":"s"} across ${i} article${i===1?"":"s"}.`]:[`\u2713 Nothing to fix${r} \u2014 the docs are already clean.`],closed:vt(e,ys(t,o))}}async function dR(e,t,n,o=[]){let{model:r}=nR(e.cwd,"standard");console.log(f(`Fixing ${t.findings} issue${t.findings===1?"":"s"} across ${t.articles} article${t.articles===1?"":"s"} in ${t.partitions.length} batches (\u2264${ur} at once) on ${r}\u2026`));let s=[],i=Date.now(),a={aborted:!1,partitions:0,failed:0,notRun:0,producedNothing:!0};try{for await(let w of eR({cwd:e.cwd,partitions:t.partitions,promptFor:t.promptFor,concurrency:ur,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:r}))if(w.type==="partition_status")w.status==="running"?console.log(f(` \u25B8 ${w.label} \u2014 fixing\u2026`)):w.status==="done"?console.log(q(` \u2713 ${w.label}`)):console.log(O(` \u2717 ${w.label}`));else if(w.type==="run_done"){let k=tR(t.partitions,w.results);a={aborted:!!w.aborted,partitions:t.partitions.length,failed:k.failed.length,notRun:k.notRun.length,...w.blocked?{blocked:w.blocked}:{},...w.allEmpty?{allEmpty:!0}:{},...w.bailedEmpty?{bailedEmpty:!0}:{}},console.log(f(zt(Ct(i,w.results,w.totalCostUsd)))),k.failed.length&&console.log(H(`\u26A0 ${k.failed.length} batch${k.failed.length===1?"":"es"} not fixed: ${k.failed.map(S=>S.label).join(", ")}`)),k.notRun.length&&console.log(H(`\u26A0 ${k.notRun.length} batch${k.notRun.length===1?"":"es"} never started \u2014 their articles are untouched.`)),w.blocked&&console.log(H(`\u26A0 ${w.blocked}`)),w.allEmpty&&console.log(H("\u26A0 No turn produced any work this run \u2014 nothing was changed.")),!w.allEmpty&&!w.blocked&&s.push(...k.covered)}}catch(w){return console.log(O(`Fix run failed: ${w.message}`)),{kind:"continue"}}if(s.length>0)try{oR(e.cwd,s,it("lint"))}catch{}let l=$u({cwd:e.cwd,scope:n}).filter(w=>!w.baselined),d=dn(l,o);console.log("");for(let w of bs(d))console.log(d.length===0?q(w):H(w));if(Kt(a))for(let w of vt(e.cwd,ys(o,n)))console.log(q(w));let g=ws({cwd:e.cwd,after:d,before:t.findings,scope:n,blocked:un(o)});return console.log(""),console.log(f(g.text)),{kind:"continue",ownNext:!0}}async function Cu(e,t){let n=e.includes("--fix"),o=e.find(a=>!a.startsWith("--")),r=o?` ${o}`:"",s=$u({cwd:t.cwd,scope:o});if(n){let a=dr(t.cwd,e,s);for(let g of a.lines)console.log(g);let l=a.fixed>0?$u({cwd:t.cwd,scope:o}):s,d=xu(t.cwd,e,l);if(!d){let g=Ru(t.cwd,e,l);console.log(q(g.lines[0]));for(let w of g.lines.slice(1))console.log(f(w));for(let w of g.closed)console.log(q(w));return{kind:"continue",ownNext:!0}}return d.kind==="partitioned"?dR(t,d,o,e):(console.log(f(`Fixing ${d.findings} doc issue${d.findings===1?"":"s"} (run /lint again after to confirm)\u2026`)),{kind:"forward-to-agent",prompt:d.prompt,display:d.display})}let i=dn(s,e);console.log(f("Linting the docs (engine internals, unknown commands, stale facts, AI-tells, em dashes, callout shape)\u2026"));for(let a of bs(i,{full:e.includes("--full"),baselined:e.includes("--baselined")}))console.log(i.length===0?q(a):H(a));return i.length>0&&console.log(f(`Run /lint${r}${un(e)?" --blocked":""} --fix to have the agent correct these.`)),console.log(""),{kind:"continue",ownNext:i.length>0}}var gg=async(e,t)=>{let n=cn("check");return n&&console.log(f(`\u2192 ${n}`)),Cu(e,t)};re();import{readProjectConfig as pR,loadProfileMap as hR,resolveActiveProfile as fR,desiredCategoryOrder as mR,desiredArticleOrder as gR,DEFAULT_DOCS_DIR as wR}from"document360-engine";var Su=e=>e.replace(/\\/g,"/"),wg=e=>Su(e).split("/").pop()??e;function Pu(e){let t=wg(e),n=t.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return n?n.charAt(0).toUpperCase()+n.slice(1):t}var yR=Pu;function ks(e,t){try{let n=pR(e);if(!n)return[];let o=fR(e,t),r=hR(e,o.name);if(!r)return[];let s=Su(n.docsDir??wR).replace(/\/+$/,""),i=new Map;for(let l of gR(r))i.set(l.categoryPath,(i.get(l.categoryPath)??0)+1);let a=[];for(let l of mR(r)){let d=Su(l.path),g=d.startsWith(`${s}/`)?d.slice(s.length+1):d===s?"":d;g&&a.push({token:g,label:yR(wg(d)),count:i.get(l.path)??0})}return a}catch{return[]}}function yg(e,t){let n=ks(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 jn(e,t){if(t.includes("--all")||t.includes("--blocked")||t.includes("--stale")||t.some(n=>n.startsWith("--scope="))||t.includes("--scope")&&!$s(t))return!1;for(let n=0;n<t.length;n++){let o=t[n];if(o.startsWith("--")){bR.has(o)&&n++;continue}return!1}return e==="write"?!t.includes("--preview")&&!t.includes("--dry-run"):e==="review"||e==="reorder"}var bR=new Set(["--scope","--concurrency"]);function pr(e,t,n,o,r){if(r=r??ks(e,o),r.length<=1)return[];let s=n.filter(d=>d.startsWith("--")).join(" "),i=s?` ${s}`:"",a=`/${t}${i} --all`.replace(/\s+/g," "),l=d=>t==="write"?`/write --scope ${d}${i}`:`/${t} ${d}${i}`;return[`Bare /${t} covers the WHOLE knowledge base (${r.reduce((d,g)=>d+g.count,0)} articles). Pick a target:`,` ${a} (everything)`,...r.map(d=>` ${l(d.token)} (${d.label} \xB7 ${d.count} article${d.count===1?"":"s"})`)]}function $s(e){let t=e.indexOf("--scope");if(t===-1)return!1;let n=e[t+1];return n===void 0||n.startsWith("-")}function bg(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 NR=3,DR=8;function Au(e){return e===void 0||!Number.isFinite(e)?NR:Math.max(1,Math.min(Math.floor(e),DR))}function vs(e){let t,n,o=!1,r=!1,s,i=l=>{let d=Number(l);return l!==void 0&&Number.isFinite(d)?d:void 0};for(let l=0;l<e.length;l++){let d=e[l];if(d==="--preview"||d==="--dry-run")o=!0;else if(d==="--rewrite"||d==="--force")r=!0;else{if(d==="--run"||d==="--yes"||d==="--all")continue;d==="--scope"?t=e[++l]:d?.startsWith("--scope=")?t=d.slice(8):d==="--concurrency"?s=i(e[++l]):d?.startsWith("--concurrency=")?s=i(d.slice(14)):d&&!d.startsWith("--")&&(n=d)}}let a=l=>l?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:a(t),path:a(n),preview:o,concurrency:s,rewrite:r}}function jR(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function IR(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Eu(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+=kR($R(e,i)).size}catch{}return{path:r,bytes:s}})}function Nu(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, and its structure is NOT the target; match only the project's voice/terminology.\n- PRESERVE REVIEWER ANCHORS. If the existing file contains `:comment[some text]{id=\"\u2026\"}` markers, each one is where a reviewer left a comment. Carry every marker into your new text, wrapping whatever passage now makes the point the old one made, and keep its `id` exactly. Dropping a marker silently detaches that reviewer's comment from the article \u2014 they keep the note and lose the place.\n":"",r=n.reviewerNotes?.trim()?`
381
+ `),a=iR(o.map(l=>({id:Pu(l),message:l.message,link:Xt(l)?l.link:void 0})));return["The documentation linter found issues in already-written articles. FIX each one by EDITING the","article in place. Do not rewrite whole articles; just resolve the flagged problems. Ground every change","in the actual product source (the authoritativeSourceFiles); never invent.","","Errors are listed first: those are defects of fact or structure, and they matter most.","",...a.length>0?["How to fix, by rule:",...a,""]:[],"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.","",...r>0?[`Note: ${r} further finding${r===1?"":"s"} were left out of this batch to keep it actionable. Run /lint --fix again afterwards to pick them up.`,""]:[],"Issues:",i].join(`
382
+ `)}var dr=3;function pr(e,t,n){let o=n.filter(a=>!(Xt(a)&&a.baselined)),r=dn(o,t).filter(a=>Xt(a)&&hR(a));if(r.length===0)return{fixed:0,skipped:0,lines:[],paths:[]};let s=pR(e,r),i=[];if(s.fixed.length>0){let a=new Set(s.fixed.map(l=>l.path)).size;i.push(q(ge("\u2713",`Fixed ${s.fixed.length} ${s.fixed.length===1?"issue":"issues"} in ${a} ${a===1?"article":"articles"} \u2014 a straight swap, so no model and no cost.`)))}return s.skipped.length>0&&i.push(f(` ${s.skipped.length} could not be applied automatically (${s.skipped[0].reason}) \u2014 left for the editor pass.`)),{fixed:s.fixed.length,skipped:s.skipped.length,lines:i,paths:s.paths}}function Tu(e,t,n){let o=dn(n.filter(a=>!(Xt(a)&&a.baselined)),t);if(o.length===0)return null;let r=t.find(a=>!a.startsWith("--")),s=bs(t,r),i=aR(o);return i.length<=1?{kind:"single",prompt:ba(o),display:s,findings:o.length}:{kind:"partitioned",partitions:i,display:s,articles:new Set(o.map(a=>a.path)).size,findings:o.length,promptFor:a=>{let l=new Set(a.paths);return ba(o.filter(d=>l.has(d.path)))}}}function Au(e,t,n){let o=t.find(l=>!l.startsWith("--")),r=o?` in ${o}`:"",s=n.filter(l=>!(Xt(l)&&l.baselined)),i=new Set(s.map(l=>l.path)).size;return{lines:un(t)?s.length===0?[`\u2713 Nothing is blocking publishing${r} \u2014 no style errors at all.`]:[`\u2713 Nothing is blocking publishing${r}. The ${s.length} issue${s.length===1?"":"s"} left ${s.length===1?"is a warning or a suggestion":"are warnings and suggestions"}, which never block it.`,` /lint${o?` ${o}`:""} --fix clears ${s.length===1?"it":"those"} too \u2014 ${s.length} issue${s.length===1?"":"s"} across ${i} article${i===1?"":"s"}.`]:[`\u2713 Nothing to fix${r} \u2014 the docs are already clean.`],closed:vt(e,bs(t,o))}}async function bR(e,t,n,o=[]){let{model:r}=uR(e.cwd,"standard");console.log(f(`Fixing ${t.findings} issue${t.findings===1?"":"s"} across ${t.articles} article${t.articles===1?"":"s"} in ${t.partitions.length} batches (\u2264${dr} at once) on ${r}\u2026`));let s=[],i=Date.now(),a={aborted:!1,partitions:0,failed:0,notRun:0,producedNothing:!0};try{for await(let m of lR({cwd:e.cwd,partitions:t.partitions,promptFor:t.promptFor,concurrency:dr,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:r}))if(m.type==="partition_status")m.status==="running"?console.log(f(` \u25B8 ${m.label} \u2014 fixing\u2026`)):m.status==="done"?console.log(q(` \u2713 ${m.label}`)):console.log(_(` \u2717 ${m.label}`));else if(m.type==="run_done"){let $=cR(t.partitions,m.results);a={aborted:!!m.aborted,partitions:t.partitions.length,failed:$.failed.length,notRun:$.notRun.length,...m.blocked?{blocked:m.blocked}:{},...m.allEmpty?{allEmpty:!0}:{},...m.bailedEmpty?{bailedEmpty:!0}:{}},console.log(f(zt(Ct(i,m.results,m.totalCostUsd)))),$.failed.length&&console.log(H(`\u26A0 ${$.failed.length} batch${$.failed.length===1?"":"es"} not fixed: ${$.failed.map(S=>S.label).join(", ")}`)),$.notRun.length&&console.log(H(`\u26A0 ${$.notRun.length} batch${$.notRun.length===1?"":"es"} never started \u2014 their articles are untouched.`)),m.blocked&&console.log(H(`\u26A0 ${m.blocked}`)),m.allEmpty&&console.log(H("\u26A0 No turn produced any work this run \u2014 nothing was changed.")),!m.allEmpty&&!m.blocked&&s.push(...$.covered)}}catch(m){return console.log(_(`Fix run failed: ${m.message}`)),{kind:"continue"}}if(s.length>0)try{dR(e.cwd,s,it("lint"))}catch{}let l=Su({cwd:e.cwd,scope:n}).filter(m=>!m.baselined),d=dn(l,o);console.log("");for(let m of ks(d))console.log(d.length===0?q(m):H(m));if(Kt(a))for(let m of vt(e.cwd,bs(o,n)))console.log(q(m));let w=ys({cwd:e.cwd,after:d,before:t.findings,scope:n,blocked:un(o)});return console.log(""),console.log(f(w.text)),{kind:"continue",ownNext:!0}}async function Eu(e,t){let n=e.includes("--fix"),o=e.find(a=>!a.startsWith("--")),r=o?` ${o}`:"",s=Su({cwd:t.cwd,scope:o});if(n){let a=pr(t.cwd,e,s);for(let w of a.lines)console.log(w);let l=a.fixed>0?Su({cwd:t.cwd,scope:o}):s,d=Tu(t.cwd,e,l);if(!d){let w=Au(t.cwd,e,l);console.log(q(w.lines[0]));for(let m of w.lines.slice(1))console.log(f(m));for(let m of w.closed)console.log(q(m));return{kind:"continue",ownNext:!0}}return d.kind==="partitioned"?bR(t,d,o,e):(console.log(f(`Fixing ${d.findings} doc issue${d.findings===1?"":"s"} (run /lint again after to confirm)\u2026`)),{kind:"forward-to-agent",prompt:d.prompt,display:d.display})}let i=dn(s,e);console.log(f("Linting the docs (engine internals, unknown commands, stale facts, AI-tells, em dashes, callout shape)\u2026"));for(let a of ks(i,{full:e.includes("--full"),baselined:e.includes("--baselined")}))console.log(i.length===0?q(a):H(a));return i.length>0&&console.log(f(`Run /lint${r}${un(e)?" --blocked":""} --fix to have the agent correct these.`)),console.log(""),{kind:"continue",ownNext:i.length>0}}var kg=async(e,t)=>{let n=cn("check");return n&&console.log(f(`\u2192 ${n}`)),Eu(e,t)};re();import{readProjectConfig as kR,loadProfileMap as $R,resolveActiveProfile as vR,desiredCategoryOrder as xR,desiredArticleOrder as RR,DEFAULT_DOCS_DIR as CR}from"document360-engine";var Nu=e=>e.replace(/\\/g,"/"),$g=e=>Nu(e).split("/").pop()??e;function Du(e){let t=$g(e),n=t.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return n?n.charAt(0).toUpperCase()+n.slice(1):t}var SR=Du;function $s(e,t){try{let n=kR(e);if(!n)return[];let o=vR(e,t),r=$R(e,o.name);if(!r)return[];let s=Nu(n.docsDir??CR).replace(/\/+$/,""),i=new Map;for(let l of RR(r))i.set(l.categoryPath,(i.get(l.categoryPath)??0)+1);let a=[];for(let l of xR(r)){let d=Nu(l.path),w=d.startsWith(`${s}/`)?d.slice(s.length+1):d===s?"":d;w&&a.push({token:w,label:SR($g(d)),count:i.get(l.path)??0})}return a}catch{return[]}}function vg(e,t){let n=$s(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 jn(e,t){if(t.includes("--all")||t.includes("--blocked")||t.includes("--stale")||t.some(n=>n.startsWith("--scope="))||t.includes("--scope")&&!vs(t))return!1;for(let n=0;n<t.length;n++){let o=t[n];if(o.startsWith("--")){PR.has(o)&&n++;continue}return!1}return e==="write"?!t.includes("--preview")&&!t.includes("--dry-run"):e==="review"||e==="reorder"}var PR=new Set(["--scope","--concurrency"]);function hr(e,t,n,o,r){if(r=r??$s(e,o),r.length<=1)return[];let s=n.filter(d=>d.startsWith("--")).join(" "),i=s?` ${s}`:"",a=`/${t}${i} --all`.replace(/\s+/g," "),l=d=>t==="write"?`/write --scope ${d}${i}`:`/${t} ${d}${i}`;return[`Bare /${t} covers the WHOLE knowledge base (${r.reduce((d,w)=>d+w.count,0)} articles). Pick a target:`,` ${a} (everything)`,...r.map(d=>` ${l(d.token)} (${d.label} \xB7 ${d.count} article${d.count===1?"":"s"})`)]}function vs(e){let t=e.indexOf("--scope");if(t===-1)return!1;let n=e[t+1];return n===void 0||n.startsWith("-")}function xg(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 FR=3,UR=8;function Iu(e){return e===void 0||!Number.isFinite(e)?FR:Math.max(1,Math.min(Math.floor(e),UR))}function xs(e){let t,n,o=!1,r=!1,s,i=l=>{let d=Number(l);return l!==void 0&&Number.isFinite(d)?d:void 0};for(let l=0;l<e.length;l++){let d=e[l];if(d==="--preview"||d==="--dry-run")o=!0;else if(d==="--rewrite"||d==="--force")r=!0;else{if(d==="--run"||d==="--yes"||d==="--all")continue;d==="--scope"?t=e[++l]:d?.startsWith("--scope=")?t=d.slice(8):d==="--concurrency"?s=i(e[++l]):d?.startsWith("--concurrency=")?s=i(d.slice(14)):d&&!d.startsWith("--")&&(n=d)}}let a=l=>l?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:a(t),path:a(n),preview:o,concurrency:s,rewrite:r}}function WR(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function BR(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Lu(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+=TR(AR(e,i)).size}catch{}return{path:r,bytes:s}})}function Ou(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, and its structure is NOT the target; match only the project's voice/terminology.\n- PRESERVE REVIEWER ANCHORS. If the existing file contains `:comment[some text]{id=\"\u2026\"}` markers, each one is where a reviewer left a comment. Carry every marker into your new text, wrapping whatever passage now makes the point the old one made, and keep its `id` exactly. Dropping a marker silently detaches that reviewer's comment from the article \u2014 they keep the note and lose the place.\n":"",r=n.reviewerNotes?.trim()?`
383
383
  WHAT REVIEWERS HAVE ASKED FOR ON THESE ARTICLES \u2014 apply each one as you write. These are real comments from the people who own these docs, so an article that ignores them will simply come back:
384
384
  `+n.reviewerNotes.trim()+`
385
385
  `:"";return`Run the write-article skill to author EACH documentation article listed below. For each path:
@@ -391,171 +391,173 @@ WHAT REVIEWERS HAVE ASKED FOR ON THESE ARTICLES \u2014 apply each one as you wri
391
391
  - Each article is independent. Do NOT write, edit, or publish any article not in this list, and do NOT publish to Document360; these are local drafts.
392
392
  Articles:
393
393
  `+e.paths.map(s=>`- ${s}`).join(`
394
- `)+r}function Du(e,t,n){let o=e.reduce((i,a)=>i+a.paths.length,0),[r,s]=t.usd;return[`Write ${o} article${o===1?"":"s"} in ${e.length} batch${e.length===1?"":"es"} (\u2264${n} agents at once):`,...e.map(i=>` \u2022 ${i.label} \u2014 ${i.paths.length} article${i.paths.length===1?"":"s"}`),"",`Estimated cost: ${St(r)}\u2013${St(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function ju(e,t,n,o){let r=C=>t[C.index]?.paths.length??0,s=e.filter(C=>C.ok),i=e.filter(C=>!C.ok),a=e.reduce((C,T)=>C+r(T),0),l=s.reduce((C,T)=>C+r(T),0),d=e.reduce((C,T)=>C+T.costUsd,0),g=e.reduce((C,T)=>C+T.outputTokens,0),w=n==="api"?`${St(d)} total`:cr(g),k=`${s.length}/${e.length} batch${e.length===1?"":"es"} completed`,S=C=>`${C} article${C===1?"":"s"}`,v=[];if(i.length===0){v.push(`Wrote ${S(a)} (${k}) successfully \xB7 ${w}.`);let C=o?` ${o}`:"",T=o?"/push":"/push --all",D=o?`/screenshot author ${o}`:"/screenshot author --all";v.push("Next \u2014 an editorial review, because these were written by an AI:"),v.push(`/review${C} --fix`),v.push(`It reads every article and applies its fixes; ${T} then pushes them up (add screenshots first with ${D} if you want them).`)}else{v.push(`Wrote ${l}/${S(a)} (${k}) \xB7 ${w}.`),v.push(`${i.length} batch${i.length===1?"":"es"} failed \u2014 re-run /write${o?` --scope ${o}`:""} to retry the rest:`);for(let C of i)v.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return v}function hr(e,t,n){try{return xR({cwd:e,paths:n.map(o=>`${t}/${o}`)}).filter(o=>!o.baselined)}catch{return[]}}function Iu(e){if(e.length===0)return null;let t=new Set(e.map(r=>r.path)).size,n=e.filter(r=>r.severity==="error").length,o=n>0?`${n} of them error${n===1?"":"s"} \u2014 `:"";return`\u26A0 Lint: ${e.length} issue${e.length===1?"":"s"} in ${t} of the new article${t===1?"":"s"} (${o}/lint --fix corrects them).`}function Lu(e){let t=e.filter(o=>o.severity==="error");if(t.length===0)return null;let n=RR(t);return n.length===0?null:{errors:t,partitions:n,articles:new Set(t.map(o=>o.path)).size,promptFor:o=>{let r=new Set(o.paths);return ya(t.filter(s=>r.has(s.path)))}}}function Ou(e,t){let n=t.filter(r=>r.severity==="error").length,o=t.length-n;return n===0?[`\u2713 Style: all ${e} error${e===1?"":"s"} fixed.${o>0?` ${o} warning${o===1?"":"s"}/suggestion${o===1?"":"s"} remain \u2014 /lint lists them.`:""}`]:[`\u26A0 Style: ${n} of ${e} error${e===1?"":"s"} remain, in ${new Set(t.filter(r=>r.severity==="error").map(r=>r.path)).size} article(s).`," /lint --blocked --fix retries them. Exactly one automatic pass runs, so a loop can never spin here."]}function ba(e,t,n){let o=(Tu(e)?.docsDir??Rg).replace(/\/+$/,""),r=t.map(a=>a.path);if(n.path){let a=jR(n.path,o);return r.includes(a)?{docsDir:o,targets:[a],planCount:r.length}:{docsDir:o,targets:[],planCount:r.length,reason:`"${a}" isn't in the docs plan (.d360-writer/plan.json).`}}let s=IR(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=Pn(e,o,s);if(i.length===0){let a=n.scope?` under "${n.scope}"`:"",l=n.scope?` --scope ${n.scope}`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${a} are already written. Use /write <path> to rewrite one, or /write${l} --rewrite to regenerate them all.`}}return{docsDir:o,targets:i,planCount:r.length}}function _u(e,t,n){let{targets:o}=ba(e,t,{rewrite:n?.rewrite}),r=new Map;for(let s of o){let i=s.split("/");if(i.length<2)continue;let a=i[0];r.set(a,(r.get(a)??0)+1)}return[...r].map(([s,i])=>({token:s,label:Pu(s),count:i}))}async function Cg(e,t){if(!Tu(t.cwd))return console.log(O("No d360-writer config here. Run /init first.")),{kind:"continue"};if($s(e)){for(let M of yg(t.cwd,t.profileName))console.log(f(M));return{kind:"continue"}}let n=SR(t.cwd,(Tu(t.cwd)?.docsDir??Rg).replace(/\/+$/,""));if(n.length===0)return console.log(O("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};if(jn("write",e)){let M=_u(t.cwd,n,{rewrite:vs(e).rewrite}),X=pr(t.cwd,"write",e,t.profileName,M);if(X.length>0){for(let z of X)console.log(f(z));return{kind:"continue"}}}let{scope:o,path:r,preview:s,concurrency:i,rewrite:a}=vs(e),{docsDir:l,targets:d,reason:g,rewriting:w}=ba(t.cwd,n,{scope:o,path:r,rewrite:a});if(d.length===0)return console.log(g?H(g):H("Nothing to write.")),{kind:"continue"};w&&console.log(H(`--rewrite: regenerating ${d.length} already-written article${d.length===1?"":"s"} (overwrites them; git has your baseline).`));let k=CR(d),S=Au(i),{model:v,forced:C}=kg(t.cwd,"standard"),T=!!r;if(s&&!T){let M=vR({files:Eu(t.cwd,n,d),op:"write",model:v});o&&console.log(f(`Scope: ${o} (${d.length} pending).`));for(let X of Du(k,M,S))console.log(X);return console.log(f(`Model: ${v}${C?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(f(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}let D=PR(t.cwd),L=d.filter(M=>AR(D,M).length>0).length;L>0&&console.log(f(` ${L} of these ${L===1?"has":"have"} reviewer comments \u2014 the writer gets them.`)),console.log(f(`Writing ${d.length} article${d.length===1?"":"s"} in ${k.length} batch${k.length===1?"":"es"} (\u2264${S} agents at once) on ${v}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let B=Date.now();try{for await(let M of $g({cwd:t.cwd,partitions:k,promptFor:X=>Nu(X,l,{rewrite:w||T,reviewerNotes:TR(D,X.paths)}),concurrency:S,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:v}))if(M.type==="partition_status")M.status==="running"?console.log(f(` \u25B8 ${M.label} \u2014 writing\u2026`)):M.status==="done"?console.log(q(` \u2713 ${M.label}`)):console.log(O(` \u2717 ${M.label}`));else if(M.type==="run_done"){console.log("");let X=process.env.ANTHROPIC_API_KEY?"api":"subscription",z=Tn(M,"The write");if(z){for(let Ce of z)console.log(H(Ce));continue}for(let Ce of ju(M.results,k,X,o??r))console.log(M.ok?q(Ce):H(Ce));if(console.log(f(zt(Ct(B,M.results,M.totalCostUsd)))),M.ok)try{xg(t.cwd,d.map(Ce=>`${l}/${Ce}`),{writtenCap:ER,reviewedCap:0,checkedCap:0})}catch{}let de=hr(t.cwd,l,d),be=Iu(de);be&&console.log(H(be));let $e=e.includes("--skip-style")?null:Lu(de);if($e){console.log(f(`Fixing ${$e.errors.length} style error(s) in ${$e.articles} article(s) \u2014 one pass\u2026`));let{model:Ce}=kg(t.cwd,"standard"),fe=[];try{for await(let se of $g({cwd:t.cwd,partitions:$e.partitions,promptFor:$e.promptFor,concurrency:3,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:Ce}))if(se.type==="partition_status"&&se.status!=="running")console.log(se.status==="done"?q(` \u2713 ${se.label}`):O(` \u2717 ${se.label}`));else if(se.type==="run_done"&&!se.allEmpty&&!se.blocked){let ee=vg($e.partitions,se.results);ee.notRun.length&&console.log(H(`\u26A0 ${ee.notRun.length} style-fix batch${ee.notRun.length===1?"":"es"} never started \u2014 their articles are untouched.`)),fe.push(...ee.covered)}}catch(se){console.log(H(`Style fix pass failed: ${se.message}`))}if(fe.length>0)try{xg(t.cwd,fe,it("lint"))}catch{}for(let se of Ou($e.errors.length,hr(t.cwd,l,d)))console.log(se.startsWith("\u2713")?q(se):H(se))}{let Ce=vg(k,M.results),fe={aborted:!!M.aborted,partitions:k.length,failed:Ce.failed.length,notRun:Ce.notRun.length,leftBehind:hr(t.cwd,l,d).filter(se=>se.severity==="error").length,...M.blocked?{blocked:M.blocked}:{},...M.allEmpty?{allEmpty:!0}:{},...M.bailedEmpty?{bailedEmpty:!0}:{}};if(Kt(fe)){let se=`/write${o?` --scope ${o}`:""}${e.includes("--rewrite")?" --rewrite":""}`;for(let ee of vt(t.cwd,se))console.log(q(ee))}}}}catch(M){console.log(O(`Write run failed: ${M.message}`))}return console.log(""),{kind:"continue"}}re();import{existsSync as LR,readdirSync as Sg,statSync as Pg}from"node:fs";import{join as Tg}from"node:path";import{inputDir as OR,readProjectConfig as _R}from"document360-engine";var Ag=/\.(md|markdown|pdf|txt)$/i;function Mu(e){let t=OR(e);if(!LR(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of Sg(t)){let s=Tg(t,r),i=!1;try{i=Pg(s).isDirectory()}catch{continue}if(i){if(r.startsWith("."))continue;let a=MR(s);a>0&&n.push({name:r,docCount:a})}else Ag.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function MR(e){let t=0;for(let n of Sg(e))try{Pg(Tg(e,n)).isFile()&&Ag.test(n)&&t++}catch{}return t}function Fu(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 ka(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, and 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(`
395
- `)}var Uu="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function Eg(e,t){let n=t?.cwd??process.cwd();if(!_R(n))return console.log(O("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=Mu(n);if(o.length===0&&r===0)return console.log(f(Uu)),{kind:"continue"};let s=e.join(" ").trim();if(!s){if(o.length>1){console.log(f("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let l of o)console.log(` ${l.name} ${f(`(${l.docCount} doc${l.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let a=o[0]?.name??"";return{kind:"forward-to-agent",prompt:ka(a),display:a?`/draft ${a}`:"/draft"}}let i=Fu(o,s);return{kind:"forward-to-agent",prompt:ka(i??"",i?void 0:s),display:`/draft ${s}`}}re();import{listOpenForDocs as FR,readProjectConfig as UR}from"document360-engine";function Wu(e){try{return FR(e).filter(t=>t.kind==="request").length}catch{return 0}}function Bu(e){let t=e.includes("--push")||e.includes("--publish"),n=e.includes(xt),o=e.filter(r=>!r.startsWith("--")).join(" ").trim();return{push:t,skipReview:n,what:o}}function Hu(e){let t=["Run the document-handoff skill.",""];return e?t.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: 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."):t.push("No description was given, so 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."),t.push("","Draft only; 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.join(`
396
- `)}var Gu="Nothing to document yet. Say what changed: /document <what you shipped>, or have the builder drop a request via their /devhints hand-off.";async function Ng(e,t){let n=t?.cwd??process.cwd();if(!UR(n))return console.log(O("No d360-writer config here. Run /init first.")),{kind:"continue"};let{push:o,what:r}=Bu(e);if(!r&&Wu(n)===0)return console.log(f(Gu)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --push":""}`;return{kind:"forward-to-agent",prompt:Hu(r),display:s}}re();import{search as WR}from"@inquirer/prompts";import{findByName as BR,getSession as HR,listSessions as GR,relativeTime as jg}from"document360-engine";async function Ig(e,t){let n=GR(t.cwd).filter(o=>o.uuid!==t.currentUuid());if(n.length===0)return console.log(f("No saved sessions for this repo yet \u2014 sessions auto-save as you work.")),{kind:"continue"};if(e.length>0){let o=e.join(" "),r=BR(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(O(`No session matches "${o}".`)),Dg(n),{kind:"continue"})}if(!process.stdin.isTTY)return Dg(n),console.log(f("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>WR({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let i=(s??"").toLowerCase();return n.filter(a=>!i||a.name.toLowerCase().includes(i)||a.firstPrompt.toLowerCase().includes(i)).map(a=>({name:`${a.name} ${jg(a.updatedAt)}`,value:a.uuid,description:a.firstPrompt.slice(0,100)}))}})),r=HR(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function Dg(e){console.log("");for(let t of e.slice(0,15))console.log(` ${Z(t.name)} ${f(jg(t.updatedAt))}`),console.log(` ${f(t.firstPrompt.slice(0,80))}`);console.log("")}re();import{renameSession as qR}from"document360-engine";function qu(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 Lg(e,t){let n=qu(e.join(" "));if(!n)return console.log(O("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(qR(o,n)?console.log(q(`\u2713 Session renamed to "${n}"`)):console.log(O("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(q(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as Og,readProjectConfig as VR,writeProjectConfig as YR}from"document360-engine";re();function Vu(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=VR(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 Og().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},YR(o,e),null):`Unknown environment "${r}". Known: ${Og().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function _g(e,t){let n=e[0];if(!n)return bi(t.cwd),{kind:"continue"};if(n==="add"){let o=Vu(t.cwd,e[1],e[2]);return o?(console.log(O(o)),{kind:"continue"}):(console.log(q(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${Z(`/profile ${e[1]}`)} then ${Z("/login")}`),console.log(f(" Until you switch, this repo keeps using the current profile\u2019s environment.")),{kind:"continue"})}return ki(t.cwd,n),$i(t.cwd,n),console.log(f(" Restarting agent for the new profile\u2026")),{kind:"clear"}}re();import{select as KR}from"@inquirer/prompts";import{readProjectConfig as zR,readUserConfig as Mg,resolveModelSetting as Yu,writeUserConfig as Fg}from"document360-engine";var Pt=[{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 $a(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=Pt.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function XR(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 xs(e,t){let n=()=>Yu(e).model;if(t==="default"){let s=Mg();return s.defaultModel?(delete s.defaultModel,Fg(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${Yu(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}}Fg({...Mg(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=zR(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 Ug(e,t){let n=e[0]?.trim();if(!n){let i=Yu(t.cwd);if(!process.stdin.isTTY)return console.log(`${Be("Model:")} ${Z(i.model)}${i.source==="auto"?f(" (auto)"):""}`),console.log(f(` source: ${XR(i)}`)),console.log(f(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let a=$a(i),l;try{l=await t.withPausedInput(()=>KR({message:`Select model (current: ${i.model}${i.source==="auto"?" \xB7 auto":""})`,default:Pt[a].value,choices:Pt.map((k,S)=>({name:`${k.label}${S===a?" \u2714":""}`,value:k.value,description:k.desc}))}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}let{lines:d,changed:g,effective:w}=xs(t.cwd,l??"default");for(let k of d)console.log(k.startsWith("\u26A0")?H(k):k.startsWith("\u2713")?q(k):f(k));return g&&await t.setModel(w),{kind:"continue"}}let{lines:o,changed:r,effective:s}=xs(t.cwd,n);for(let i of o)console.log(i.startsWith("\u26A0")?H(i):i.startsWith("\u2713")?q(i):f(i));return r&&await t.setModel(s),{kind:"continue"}}Ra();async function qg(e,t){return await t.withPausedInput(()=>Yo(t.cwd)),{kind:"clear"}}async function Vg(e,t){return await t.withPausedInput(()=>gi(t.cwd,t.profileName)),{kind:"clear"}}re();import{resolveActiveProfile as yC}from"document360-engine";async function Yg(e,t){let n=!1;try{n=yC(t.cwd).production}catch{}return n?(console.log(H("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(f("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}re();var Kg=async(e,t)=>{try{await t.withPausedInput(()=>yi({}))}catch(n){console.log(O(`Login failed: ${n.message}`))}return{kind:"continue"}};import{resolveActiveProfile as bC,clearTokens as kC,clearProfileProject as $C,listStoredSessions as vC,tokensProjectId as xC}from"document360-engine";re();async function zg(e,t){let n,o,r,s;try{let w=bC(t.cwd,t.profileName);n=w.name,o=w.connection.name,r=w.project.projectId,s=w.project.projectName}catch(w){return console.log(O(w.message)),{kind:"continue"}}let i=e.includes("--all-projects"),a=vC(n).filter(w=>{let k=xC(w);return!!k&&k!==r}).length,l=kC(n,i?void 0:r);$C(t.cwd,n);let d=i||a===0?"":` Your sign-in for ${a} other project${a===1?"":"s"} is untouched (/logout --all-projects clears those too).`;console.log(l?i?q(`\u2713 Signed out of every Document360 project for "${n}" and cleared this repo's project/workspace selection.`):q(`\u2713 Signed out of ${s?`"${s}"`:`"${n}"`} and cleared its project/workspace selection.${d}`):f(`Profile "${n}" was not signed in. Cleared any project/workspace selection.${d}`)),console.log(f(`Run /login to sign back in to "${n}" (the ${o} environment) and pick a project.`));let g=kn(t.cwd,t.profileName);return console.log(g?H(`\u26A0 ${g.why}. Signing out doesn\u2019t change the environment \u2014 ${g.cmd} does.`):f(" Different environment? That comes from the profile, not the login \u2014 /profile add <environment>.")),{kind:"continue"}}import{existsSync as Jg,readFileSync as Xu}from"node:fs";import{homedir as DC}from"node:os";import{basename as jC,join as Ps}from"node:path";import{readProjectConfig as IC,DEFAULT_OUTPUT_DIR as LC,existingAnnotatedShotPath as w3,resolveOutputDir as OC,shotArtifacts as _C}from"document360-engine";import pt from"picocolors";import{annotationsPath as RC,resolveOutputDir as CC,readProjectConfig as SC,DEFAULT_OUTPUT_DIR as PC,existingAnnotatedShotPath as TC}from"document360-engine";function AC(e){let n=e.filter(o=>o!=="--all"&&o!=="-a").find(o=>!o.startsWith("-"));return n?{mode:"single",id:n}:{mode:"all"}}function Cs(e){return e.filter(t=>t.state==="annotated").map(t=>t.id)}function Qt(e,t){let n=CC(e,SC(e)?.outputDir??PC),o=new Map(_e(e).map(i=>[i.id,i])),r=i=>i.replace(`${e}\\`,"").replace(`${e}/`,"").replace(/\\/g,"/"),s=t.map(i=>{let a=o.get(i)?.file??"(unknown article)";return[`- ${i}`,` image: ${r(TC(n,i))}`,` facts: ${r(RC(n,i))}`,` article: ${a}`].join(`
394
+ `)+r}function _u(e,t,n){let o=e.reduce((i,a)=>i+a.paths.length,0),[r,s]=t.usd;return[`Write ${o} article${o===1?"":"s"} in ${e.length} batch${e.length===1?"":"es"} (\u2264${n} agents at once):`,...e.map(i=>` \u2022 ${i.label} \u2014 ${i.paths.length} article${i.paths.length===1?"":"s"}`),"",`Estimated cost: ${St(r)}\u2013${St(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function Mu(e,t,n,o){let r=C=>t[C.index]?.paths.length??0,s=e.filter(C=>C.ok),i=e.filter(C=>!C.ok),a=e.reduce((C,A)=>C+r(A),0),l=s.reduce((C,A)=>C+r(A),0),d=e.reduce((C,A)=>C+A.costUsd,0),w=e.reduce((C,A)=>C+A.outputTokens,0),m=n==="api"?`${St(d)} total`:ur(w),$=`${s.length}/${e.length} batch${e.length===1?"":"es"} completed`,S=C=>`${C} article${C===1?"":"s"}`,R=[];if(i.length===0){R.push(`Wrote ${S(a)} (${$}) successfully \xB7 ${m}.`);let C=o?` ${o}`:"",A=o?"/push":"/push --all",D=o?`/screenshot author ${o}`:"/screenshot author --all";R.push("Next \u2014 an editorial review, because these were written by an AI:"),R.push(`/review${C} --fix`),R.push(`It reads every article and applies its fixes; ${A} then pushes them up (add screenshots first with ${D} if you want them).`)}else{R.push(`Wrote ${l}/${S(a)} (${$}) \xB7 ${m}.`),R.push(`${i.length} batch${i.length===1?"":"es"} failed \u2014 re-run /write${o?` --scope ${o}`:""} to retry the rest:`);for(let C of i)R.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return R}function fr(e,t,n){try{return NR({cwd:e,paths:n.map(o=>`${t}/${o}`)}).filter(o=>!o.baselined)}catch{return[]}}function Fu(e){if(e.length===0)return null;let t=new Set(e.map(r=>r.path)).size,n=e.filter(r=>r.severity==="error").length,o=n>0?`${n} of them error${n===1?"":"s"} \u2014 `:"";return`\u26A0 Lint: ${e.length} issue${e.length===1?"":"s"} in ${t} of the new article${t===1?"":"s"} (${o}/lint --fix corrects them).`}function Uu(e){let t=e.filter(o=>o.severity==="error");if(t.length===0)return null;let n=DR(t);return n.length===0?null:{errors:t,partitions:n,articles:new Set(t.map(o=>o.path)).size,promptFor:o=>{let r=new Set(o.paths);return ba(t.filter(s=>r.has(s.path)))}}}function Wu(e,t){let n=t.filter(r=>r.severity==="error").length,o=t.length-n;return n===0?[`\u2713 Style: all ${e} error${e===1?"":"s"} fixed.${o>0?` ${o} warning${o===1?"":"s"}/suggestion${o===1?"":"s"} remain \u2014 /lint lists them.`:""}`]:[`\u26A0 Style: ${n} of ${e} error${e===1?"":"s"} remain, in ${new Set(t.filter(r=>r.severity==="error").map(r=>r.path)).size} article(s).`," /lint --blocked --fix retries them. Exactly one automatic pass runs, so a loop can never spin here."]}function ka(e,t,n){let o=(ju(e)?.docsDir??Tg).replace(/\/+$/,""),r=t.map(a=>a.path);if(n.path){let a=WR(n.path,o);return r.includes(a)?{docsDir:o,targets:[a],planCount:r.length}:{docsDir:o,targets:[],planCount:r.length,reason:`"${a}" isn't in the docs plan (.d360-writer/plan.json).`}}let s=BR(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=Pn(e,o,s);if(i.length===0){let a=n.scope?` under "${n.scope}"`:"",l=n.scope?` --scope ${n.scope}`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${a} are already written. Use /write <path> to rewrite one, or /write${l} --rewrite to regenerate them all.`}}return{docsDir:o,targets:i,planCount:r.length}}function Bu(e,t,n){let{targets:o}=ka(e,t,{rewrite:n?.rewrite}),r=new Map;for(let s of o){let i=s.split("/");if(i.length<2)continue;let a=i[0];r.set(a,(r.get(a)??0)+1)}return[...r].map(([s,i])=>({token:s,label:Du(s),count:i}))}async function Ag(e,t){if(!ju(t.cwd))return console.log(_("No d360-writer config here. Run /init first.")),{kind:"continue"};if(vs(e)){for(let O of vg(t.cwd,t.profileName))console.log(f(O));return{kind:"continue"}}let n=IR(t.cwd,(ju(t.cwd)?.docsDir??Tg).replace(/\/+$/,""));if(n.length===0)return console.log(_("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};if(jn("write",e)){let O=Bu(t.cwd,n,{rewrite:xs(e).rewrite}),Q=hr(t.cwd,"write",e,t.profileName,O);if(Q.length>0){for(let z of Q)console.log(f(z));return{kind:"continue"}}}let{scope:o,path:r,preview:s,concurrency:i,rewrite:a}=xs(e),{docsDir:l,targets:d,reason:w,rewriting:m}=ka(t.cwd,n,{scope:o,path:r,rewrite:a});if(d.length===0)return console.log(w?H(w):H("Nothing to write.")),{kind:"continue"};m&&console.log(H(`--rewrite: regenerating ${d.length} already-written article${d.length===1?"":"s"} (overwrites them; git has your baseline).`));let $=jR(d),S=Iu(i),{model:R,forced:C}=Rg(t.cwd,"standard"),A=!!r;if(s&&!A){let O=ER({files:Lu(t.cwd,n,d),op:"write",model:R});o&&console.log(f(`Scope: ${o} (${d.length} pending).`));for(let Q of _u($,O,S))console.log(Q);return console.log(f(`Model: ${R}${C?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(f(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}let D=LR(t.cwd),N=d.filter(O=>_R(D,O).length>0).length;N>0&&console.log(f(` ${N} of these ${N===1?"has":"have"} reviewer comments \u2014 the writer gets them.`)),console.log(f(`Writing ${d.length} article${d.length===1?"":"s"} in ${$.length} batch${$.length===1?"":"es"} (\u2264${S} agents at once) on ${R}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let U=Date.now();try{for await(let O of Cg({cwd:t.cwd,partitions:$,promptFor:Q=>Ou(Q,l,{rewrite:m||A,reviewerNotes:OR(D,Q.paths)}),concurrency:S,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:R}))if(O.type==="partition_status")O.status==="running"?console.log(f(` \u25B8 ${O.label} \u2014 writing\u2026`)):O.status==="done"?console.log(q(` \u2713 ${O.label}`)):console.log(_(` \u2717 ${O.label}`));else if(O.type==="run_done"){console.log("");let Q=process.env.ANTHROPIC_API_KEY?"api":"subscription",z=Tn(O,"The write");if(z){for(let Pe of z)console.log(H(Pe));continue}for(let Pe of Mu(O.results,$,Q,o??r))console.log(O.ok?q(Pe):H(Pe));if(console.log(f(zt(Ct(U,O.results,O.totalCostUsd)))),O.ok)try{Pg(t.cwd,d.map(Pe=>`${l}/${Pe}`),{writtenCap:MR,reviewedCap:0,checkedCap:0})}catch{}let de=fr(t.cwd,l,d),ke=Fu(de);ke&&console.log(H(ke));let xe=e.includes("--skip-style")?null:Uu(de);if(xe){console.log(f(`Fixing ${xe.errors.length} style error(s) in ${xe.articles} article(s) \u2014 one pass\u2026`));let{model:Pe}=Rg(t.cwd,"standard"),fe=[];try{for await(let se of Cg({cwd:t.cwd,partitions:xe.partitions,promptFor:xe.promptFor,concurrency:3,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:Pe}))if(se.type==="partition_status"&&se.status!=="running")console.log(se.status==="done"?q(` \u2713 ${se.label}`):_(` \u2717 ${se.label}`));else if(se.type==="run_done"&&!se.allEmpty&&!se.blocked){let te=Sg(xe.partitions,se.results);te.notRun.length&&console.log(H(`\u26A0 ${te.notRun.length} style-fix batch${te.notRun.length===1?"":"es"} never started \u2014 their articles are untouched.`)),fe.push(...te.covered)}}catch(se){console.log(H(`Style fix pass failed: ${se.message}`))}if(fe.length>0)try{Pg(t.cwd,fe,it("lint"))}catch{}for(let se of Wu(xe.errors.length,fr(t.cwd,l,d)))console.log(se.startsWith("\u2713")?q(se):H(se))}{let Pe=Sg($,O.results),fe={aborted:!!O.aborted,partitions:$.length,failed:Pe.failed.length,notRun:Pe.notRun.length,leftBehind:fr(t.cwd,l,d).filter(se=>se.severity==="error").length,...O.blocked?{blocked:O.blocked}:{},...O.allEmpty?{allEmpty:!0}:{},...O.bailedEmpty?{bailedEmpty:!0}:{}};if(Kt(fe)){let se=`/write${o?` --scope ${o}`:""}${e.includes("--rewrite")?" --rewrite":""}`;for(let te of vt(t.cwd,se))console.log(q(te))}}}}catch(O){console.log(_(`Write run failed: ${O.message}`))}return console.log(""),{kind:"continue"}}re();import{existsSync as HR,readdirSync as Eg,statSync as Ng}from"node:fs";import{join as Dg}from"node:path";import{inputDir as GR,readProjectConfig as qR}from"document360-engine";var jg=/\.(md|markdown|pdf|txt)$/i;function Hu(e){let t=GR(e);if(!HR(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of Eg(t)){let s=Dg(t,r),i=!1;try{i=Ng(s).isDirectory()}catch{continue}if(i){if(r.startsWith("."))continue;let a=VR(s);a>0&&n.push({name:r,docCount:a})}else jg.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function VR(e){let t=0;for(let n of Eg(e))try{Ng(Dg(e,n)).isFile()&&jg.test(n)&&t++}catch{}return t}function Gu(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 $a(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, and 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(`
395
+ `)}var qu="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function Ig(e,t){let n=t?.cwd??process.cwd();if(!qR(n))return console.log(_("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=Hu(n);if(o.length===0&&r===0)return console.log(f(qu)),{kind:"continue"};let s=e.join(" ").trim();if(!s){if(o.length>1){console.log(f("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let l of o)console.log(` ${l.name} ${f(`(${l.docCount} doc${l.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let a=o[0]?.name??"";return{kind:"forward-to-agent",prompt:$a(a),display:a?`/draft ${a}`:"/draft"}}let i=Gu(o,s);return{kind:"forward-to-agent",prompt:$a(i??"",i?void 0:s),display:`/draft ${s}`}}re();import{listOpenForDocs as YR,readProjectConfig as KR}from"document360-engine";function Vu(e){try{return YR(e).filter(t=>t.kind==="request").length}catch{return 0}}function Yu(e){let t=e.includes("--push")||e.includes("--publish"),n=e.includes(xt),o=e.filter(r=>!r.startsWith("--")).join(" ").trim();return{push:t,skipReview:n,what:o}}function Ku(e){let t=["Run the document-handoff skill.",""];return e?t.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: 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."):t.push("No description was given, so 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."),t.push("","Draft only; 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.join(`
396
+ `)}var zu="Nothing to document yet. Say what changed: /document <what you shipped>, or have the builder drop a request via their /devhints hand-off.";async function Lg(e,t){let n=t?.cwd??process.cwd();if(!KR(n))return console.log(_("No d360-writer config here. Run /init first.")),{kind:"continue"};let{push:o,what:r}=Yu(e);if(!r&&Vu(n)===0)return console.log(f(zu)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --push":""}`;return{kind:"forward-to-agent",prompt:Ku(r),display:s}}re();import{search as zR}from"@inquirer/prompts";import{findByName as XR,getSession as QR,listSessions as JR,relativeTime as _g}from"document360-engine";async function Mg(e,t){let n=JR(t.cwd).filter(o=>o.uuid!==t.currentUuid());if(n.length===0)return console.log(f("No saved sessions for this repo yet \u2014 sessions auto-save as you work.")),{kind:"continue"};if(e.length>0){let o=e.join(" "),r=XR(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(_(`No session matches "${o}".`)),Og(n),{kind:"continue"})}if(!process.stdin.isTTY)return Og(n),console.log(f("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>zR({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let i=(s??"").toLowerCase();return n.filter(a=>!i||a.name.toLowerCase().includes(i)||a.firstPrompt.toLowerCase().includes(i)).map(a=>({name:`${a.name} ${_g(a.updatedAt)}`,value:a.uuid,description:a.firstPrompt.slice(0,100)}))}})),r=QR(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function Og(e){console.log("");for(let t of e.slice(0,15))console.log(` ${Z(t.name)} ${f(_g(t.updatedAt))}`),console.log(` ${f(t.firstPrompt.slice(0,80))}`);console.log("")}re();import{renameSession as ZR}from"document360-engine";function Xu(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 Fg(e,t){let n=Xu(e.join(" "));if(!n)return console.log(_("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(ZR(o,n)?console.log(q(`\u2713 Session renamed to "${n}"`)):console.log(_("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(q(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as Ug,readProjectConfig as eC,writeProjectConfig as tC}from"document360-engine";re();function Qu(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=eC(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 Ug().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},tC(o,e),null):`Unknown environment "${r}". Known: ${Ug().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function Wg(e,t){let n=e[0];if(!n)return bi(t.cwd),{kind:"continue"};if(n==="add"){let o=Qu(t.cwd,e[1],e[2]);return o?(console.log(_(o)),{kind:"continue"}):(console.log(q(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${Z(`/profile ${e[1]}`)} then ${Z("/login")}`),console.log(f(" Until you switch, this repo keeps using the current profile\u2019s environment.")),{kind:"continue"})}return ki(t.cwd,n),$i(t.cwd,n),console.log(f(" Restarting agent for the new profile\u2026")),{kind:"clear"}}re();import{select as nC}from"@inquirer/prompts";import{readProjectConfig as oC,readUserConfig as Bg,resolveModelSetting as Ju,writeUserConfig as Hg}from"document360-engine";var Pt=[{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 va(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=Pt.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function rC(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 Rs(e,t){let n=()=>Ju(e).model;if(t==="default"){let s=Bg();return s.defaultModel?(delete s.defaultModel,Hg(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${Ju(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}}Hg({...Bg(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=oC(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 Gg(e,t){let n=e[0]?.trim();if(!n){let i=Ju(t.cwd);if(!process.stdin.isTTY)return console.log(`${Be("Model:")} ${Z(i.model)}${i.source==="auto"?f(" (auto)"):""}`),console.log(f(` source: ${rC(i)}`)),console.log(f(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let a=va(i),l;try{l=await t.withPausedInput(()=>nC({message:`Select model (current: ${i.model}${i.source==="auto"?" \xB7 auto":""})`,default:Pt[a].value,choices:Pt.map(($,S)=>({name:`${$.label}${S===a?" \u2714":""}`,value:$.value,description:$.desc}))}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}let{lines:d,changed:w,effective:m}=Rs(t.cwd,l??"default");for(let $ of d)console.log($.startsWith("\u26A0")?H($):$.startsWith("\u2713")?q($):f($));return w&&await t.setModel(m),{kind:"continue"}}let{lines:o,changed:r,effective:s}=Rs(t.cwd,n);for(let i of o)console.log(i.startsWith("\u26A0")?H(i):i.startsWith("\u2713")?q(i):f(i));return r&&await t.setModel(s),{kind:"continue"}}Ca();async function zg(e,t){return await t.withPausedInput(()=>Ko(t.cwd)),{kind:"clear"}}async function Xg(e,t){return await t.withPausedInput(()=>gi(t.cwd,t.profileName)),{kind:"clear"}}re();import{resolveActiveProfile as SC}from"document360-engine";async function Qg(e,t){let n=!1;try{n=SC(t.cwd).production}catch{}return n?(console.log(H("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(f("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}re();var Jg=async(e,t)=>{try{await t.withPausedInput(()=>yi({}))}catch(n){if(console.log(_(`Login failed: ${n.message}`)),!Ii(t.cwd,t.profileName))return console.log(f("Your Document360 session still isn't working \u2014 run /login to try again.")),{kind:"continue",ownNext:!0}}return{kind:"continue"}};import{resolveActiveProfile as PC,clearTokens as TC,clearProfileProject as AC,listStoredSessions as EC,tokensProjectId as NC}from"document360-engine";re();async function Zg(e,t){let n,o,r,s;try{let m=PC(t.cwd,t.profileName);n=m.name,o=m.connection.name,r=m.project.projectId,s=m.project.projectName}catch(m){return console.log(_(m.message)),{kind:"continue"}}let i=e.includes("--all-projects"),a=EC(n).filter(m=>{let $=NC(m);return!!$&&$!==r}).length,l=TC(n,i?void 0:r);AC(t.cwd,n);let d=i||a===0?"":` Your sign-in for ${a} other project${a===1?"":"s"} is untouched (/logout --all-projects clears those too).`;console.log(l?i?q(`\u2713 Signed out of every Document360 project for "${n}" and cleared this repo's project/workspace selection.`):q(`\u2713 Signed out of ${s?`"${s}"`:`"${n}"`} and cleared its project/workspace selection.${d}`):f(`Profile "${n}" was not signed in. Cleared any project/workspace selection.${d}`)),console.log(f(`Run /login to sign back in to "${n}" (the ${o} environment) and pick a project.`));let w=kn(t.cwd,t.profileName);return console.log(w?H(`\u26A0 ${w.why}. Signing out doesn\u2019t change the environment \u2014 ${w.cmd} does.`):f(" Different environment? That comes from the profile, not the login \u2014 /profile add <environment>.")),{kind:"continue"}}import{existsSync as nw,readFileSync as td}from"node:fs";import{homedir as UC}from"node:os";import{basename as WC,join as Ts}from"node:path";import{readProjectConfig as BC,DEFAULT_OUTPUT_DIR as HC,existingAnnotatedShotPath as A3,resolveOutputDir as GC,shotArtifacts as qC}from"document360-engine";import pt from"picocolors";import{annotationsPath as DC,resolveOutputDir as jC,readProjectConfig as IC,DEFAULT_OUTPUT_DIR as LC,existingAnnotatedShotPath as OC}from"document360-engine";function _C(e){let n=e.filter(o=>o!=="--all"&&o!=="-a").find(o=>!o.startsWith("-"));return n?{mode:"single",id:n}:{mode:"all"}}function Ss(e){return e.filter(t=>t.state==="annotated").map(t=>t.id)}function Qt(e,t){let n=jC(e,IC(e)?.outputDir??LC),o=new Map(_e(e).map(i=>[i.id,i])),r=i=>i.replace(`${e}\\`,"").replace(`${e}/`,"").replace(/\\/g,"/"),s=t.map(i=>{let a=o.get(i)?.file??"(unknown article)";return[`- ${i}`,` image: ${r(OC(n,i))}`,` facts: ${r(DC(n,i))}`,` article: ${a}`].join(`
397
397
  `)}).join(`
398
398
  `);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; 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,"," boxes that fell outside the frame, how many elements each highlight/redaction selector covered,"," and whether the page was still loading when the shutter fired).","3. Read the article to see what the placeholder promises the reader at that point.","4. Record a verdict with d360_verify_screenshot; 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; an exact receipt is printed from","your recorded verdicts right after your report, so any number you state can only contradict it."].join(`
399
- `)}function In(e){return`${J("\u2192",pt.blue)}Verifying ${e} new screenshot${e===1?"":"s"} (reading each image)\u2026`}var EC=(e,t=88)=>{let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n};function fr(e,t){if(t.length===0)return[];let n=ln(e).shots,o=[],r=[],s=[];for(let a of t){let l=n[a]?.review;l?l.verdict==="ok"?o.push(a):r.push({id:a,reason:l.reason??"no reason recorded",repaired:!!l.repaired}):s.push(a)}let i=[""];if(i.push(`${J("\u2714",pt.green)}${pt.green(`${o.length} verified`)}`+(r.length>0?` ${pt.magenta(`\u2691 ${r.length} flagged`)}`:"")+(s.length>0?` ${pt.yellow(`? ${s.length} not verified`)}`:"")+pt.gray(` ${t.length} shot${t.length===1?"":"s"} in this pass`)),r.length>0){let a=Math.max(...r.map(d=>d.id.length));for(let d of r)i.push(` ${pt.magenta(d.id.padEnd(a))} ${pt.gray(EC(d.reason))}`);let l=r.filter(d=>d.repaired).length;i.push(`${J("\u2192",pt.magenta)}Re-capture the ${r.length} flagged: ${pt.bold("/screenshot capture --failed")}`+(l<r.length?pt.gray(` (${r.length-l} still need${r.length-l===1?"s":""} a spec fix first)`):""))}return s.length>0&&i.push(`${J("\u26A0",pt.yellow)}No verdict recorded for ${s.slice(0,3).join(", ")}${s.length>3?`, +${s.length-3}`:""} \u2014 still awaiting verification. Run ${pt.bold("/screenshot verify")} again.`),i}async function Xg(e,t){let n=t?.cwd??process.cwd(),o=so(n);o&&console.log(o);let r=_e(n),s=AC(e);if(s.mode==="single"){let a=r.find(l=>l.id===s.id);return a?a.state==="captured"?(console.log(`"${s.id}" has been taken but the callouts aren't drawn on yet \u2014 /screenshot annotate ${s.id} finishes it.`),{kind:"continue"}):["annotated","verified","rejected"].includes(a.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=Cs(r);if(i.length===0){let a=r.filter(g=>g.state==="verified").length,l=r.filter(g=>g.state==="rejected").length,d=r.filter(g=>g.state==="captured").length;return console.log(d>0?`${d} shot${d===1?" is":"s are"} taken but not drawn on yet \u2014 /screenshot annotate finishes ${d===1?"it":"them"}, then there'll be something to verify.`:l>0?`Nothing left to verify. ${l} shot${l===1?"":"s"} failed verification \u2014 re-capture with: /screenshot capture --failed`:a>0?`All ${a} captured shot${a===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"}}import{spawn as Qg}from"node:child_process";var zu="d360-capture";function NC(e,t){if(t&&typeof e.pid=="number")try{process.kill(-e.pid,"SIGTERM");return}catch{}try{e.kill()}catch{}}function Ss(e){let t=process.platform==="win32",n=!t&&e.stdio==="pipe";return new Promise((o,r)=>{let s=t?Qg(`${zu} ${e.args.join(" ")}`,{cwd:e.cwd,shell:!0,stdio:e.stdio==="inherit"?"inherit":["ignore","pipe","pipe"],env:{...process.env,NO_UPDATE_NOTIFIER:"1"}}):Qg(zu,e.args,{cwd:e.cwd,shell:!1,detached:e.stdio==="pipe",stdio:e.stdio==="inherit"?"inherit":["ignore","pipe","pipe"],env:{...process.env,NO_UPDATE_NOTIFIER:"1"}}),i="";e.stdio==="pipe"&&(s.stdout?.on("data",l=>{i+=l.toString()}),s.stderr?.on("data",l=>{i+=l.toString()}));let a=()=>NC(s,n);e.signal?.addEventListener("abort",a,{once:!0}),s.on("error",l=>{if(e.signal?.removeEventListener("abort",a),l.code==="ENOENT"){o({exitCode:127,output:`${i}
400
- ${zu}: command not found`.trim()});return}r(l)}),s.on("close",l=>{e.signal?.removeEventListener("abort",a),o({exitCode:l??1,output:i})})})}var MC=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Qu(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:MC(t),retryBlocked:n}:{mode:"single",id:t}:{mode:"picker"}}function As(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("annotated"),...o("verified"),...o("rejected")].sort(),blocked:o("blocked"),broken:o("broken"),rejected:o("rejected"),rows:n}}function Zg(e){let t=e.filter(s=>s.state==="spec"),n=e.filter(s=>s.state==="annotated"||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}),tr(o,t,"capture"),Ac(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,a)=>i.id.localeCompare(a.id))){let i=s.state==="verified"?" \u2714 verified \u2014 re-capture":" \u25C8 to verify \u2014 re-capture";o.push({kind:"shot",action:"capture",label:s.id,ids:[s.id],depth:1,note:i})}return o}function Ju(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([...Cf(e).filter(r=>n.has(r)),...o])].sort()}function Zu(e,t){let n=e.length;if(n===0)return null;let o=ls(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(`
401
- `)}function FC(e,t){let n=IC(e)?.outputDir??LC;return _C(OC(e,n),t)}function ed(e,t,n,o){let r=FC(e,t);return(r.annotationsMtimeMs??0)>=o&&r.rawMtimeMs!==void 0?"captured":n===0?"skipped":"failed"}function ew(e){let t=/⊘[^\n—]*—\s*(.+)/.exec(e);return t?t[1].trim():null}var UC=/element is not (?:enabled|visible|stable|editable)|intercepts pointer events|outside of the viewport|element is not attached/i;function tw(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=>UC.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(`
402
- `):td(e)}function td(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(`
403
- `)}var WC=/^[A-Za-z0-9._-]+$/;function nd(e){return WC.test(e.id)?Ss({args:["capture",e.id],cwd:e.cwd,stdio:e.stdio,signal:e.signal}):Promise.reject(new Error(`Not a valid spec id: "${e.id}"`))}function nw(e,t=DC()){try{let n=JSON.parse(Xu(Ps(e,".d360-writer","capture.json"),"utf8").replace(/^/,"")),o=n.projectId;if(!o)try{o=JSON.parse(Xu(Ps(e,"package.json"),"utf8")).name}catch{}o||=jC(e);let r=Object.keys(n.profiles??{}),s=n.defaultProfile??(r.length===1?r[0]:r.includes("staging")?"staging":r[0]);return s?Jg(Ps(t,".document360-capture","auth-states",o,`${s}.json`)):!0}catch{return!0}}function ow(e){return Ss({args:["auth","--auto"],cwd:e.cwd,stdio:"pipe",signal:e.signal})}function od(e,t){return e===127||/is not recognized as an internal or external command|command not found/i.test(t)}function rw(e){try{let t=JSON.parse(Xu(Ps(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 ho(e){return Jg(Ps(e,".d360-writer","capture.json"))}function rd(){return["Screenshot capture is not configured in this repo yet (no `.d360-writer/capture.json`). Set it up","conversationally, and 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, 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: 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`, adding/updating 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(`
404
- `)}function sw(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(", ")}
405
- /screenshot list --detail shows what each one needs`}function iw(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):Ts(r?.reason)!==Ts(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):qi(r?.reason??"")!==qi(o.detail??"")?n.blockedNewReason.push(o.id):n.blockedAsBefore.push(o.id))}return n}function Ts(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 aw(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?nr(o.detail):"no reason recorded"}`)}function mr(e,t=2){return e.length<=t?e.join(" \xB7 "):`${e.slice(0,t).join(" \xB7 ")} \xB7 +${e.length-t}`}function lw(e,t){if(!t)return[];let n=[],o=(i,a,l,d)=>{a>0&&n.push({glyph:i,label:`${a} ${l}`,tail:d})};if(o("\u2713",e.newlyCaptured.length,"newly captured",mr(e.newlyCaptured)),o("\u2717",e.newlyBroken.length,"newly broken",mr(e.newlyBroken)),o("\u2192",e.repairedNowBlocked.length,"repaired",`no longer broken \u2014 only data stands in the way \xB7 ${mr(e.repairedNowBlocked)}`),o("\u2298",e.newlyBlocked.length,"newly blocked",mr(e.newlyBlocked)),o("\u2192",e.blockedNewReason.length,"blocked on something new",`an earlier step now passes \xB7 ${mr(e.blockedNewReason)}`),o("\u2192",e.brokeDifferently.length,"broken differently",`the previous cause is fixed \xB7 ${mr(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 cw(e){let t=e.results.filter(S=>S.outcome==="captured"),n=e.results.filter(S=>S.outcome==="skipped"),o=e.results.filter(S=>S.outcome==="failed"),r=e.unannotated??[],s=S=>S===1?"":"s";if(t.length+n.length+o.length===0)return null;let i=e.articles.length===1?`/push ${e.articles[0]}`:Pe("/push","--screenshots",Yt(e.articles)),a=e.ids.length===1?`/screenshot capture ${e.ids[0]}`:"/screenshot capture",l=o[0]?.id,d=[];o.length>0&&d.push({glyph:"\u2717",cmd:`/screenshot ${l}`,why:`re-author the ${o.length===1?"broken spec":`first of ${o.length} broken specs`} \u2014 re-running fails the same way`});let g=Pe("/screenshot annotate","",r.length===1?r[0]:void 0);r.length>0&&d.push({glyph:"\u25C8",cmd:g,why:`draw the callouts on ${r.length} shot${s(r.length)} \u2014 no browser, seconds; ${r.length===1?"it cannot":"they cannot"} publish until drawn`}),n.length>0&&d.push({glyph:"\u2298",cmd:"/screenshot list",why:`what to stage for the ${n.length} blocked shot${s(n.length)}`}),t.length>0&&r.length<t.length&&d.push({glyph:"\u2713",cmd:i,why:`embed the ${t.length-r.length} new PNG${s(t.length-r.length)}`});let w=Math.max(...d.map(S=>S.cmd.length));return{note:d.map(S=>`${S.glyph} ${S.cmd.padEnd(w)} ${S.why}`).join(`
406
- `),cmd:o.length>0?`/screenshot ${l}`:r.length>0?g:t.length>0?i:a,tone:o.length>0||r.length>0?"warn":"info"}}function uw(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 sd(e,t){let n=t?.cwd??process.cwd(),o=Qu(e);if(!ho(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:a}=As(n,o.mode==="scope"?o.scope:void 0),l=Ju(n,a),d=(o.mode==="all"||o.mode==="scope")&&o.retryBlocked,g=o.mode==="single"?[o.id]:o.mode==="failed"?l:o.mode==="blocked"?i:o.mode==="picker"?r:[...r,...s,...d?i:[]];if(g.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(!d&&o.mode!=="single"&&o.mode!=="failed"&&o.mode!=="blocked"){let C=Zu(a.filter(T=>T.state==="blocked"),"/screenshot capture --blocked");C&&console.log(C)}let w=Date.now(),k=[];for(let C of g){console.log(`\u25B6 ${C}`);try{let{exitCode:T}=await nd({cwd:n,id:C,stdio:"inherit"});k.push({id:C,outcome:ed(n,C,T,w)})}catch(T){if(T.code==="ENOENT")return console.log("d360-capture is not installed. Run: npm i -g document360-capture"),{kind:"continue"};k.push({id:C,outcome:"failed",detail:T.message})}}let S=C=>k.filter(T=>T.outcome===C).length;console.log(`\u2713 ${S("captured")} captured \xB7 \u2298 ${S("skipped")} skipped \xB7 \u2717 ${S("failed")} failed`);let v=k.filter(C=>C.outcome==="captured");return Li(n,k.map(C=>({id:C.id,outcome:C.outcome,reason:C.detail,specSource:io(n,C.id)})),new Date().toISOString()),v.length>0?(console.log(In(v.length)),{kind:"forward-to-agent",prompt:Qt(n,v.map(C=>C.id)),display:"/screenshot verify"}):{kind:"continue"}}import{readProjectConfig as BC,DEFAULT_OUTPUT_DIR as HC,resolveOutputDir as GC,shotArtifacts as qC,annotationCurrent as VC}from"document360-engine";Zo();var dw="0.2.29";function Ca(e=dt()){return er(e,dw)}function id(e){let t=e.includes("--force")||e.includes("-f"),n=e.includes("--all")||e.includes("-a"),o=e.find(r=>!r.startsWith("-"));return n?{mode:"all",force:t}:o?o.includes("/")||o.includes("\\")||o.endsWith(".md")?{mode:"scope",scope:o.replace(/\\/g,"/").replace(/\/+$/,""),force:t}:{mode:"single",id:o}:{mode:"pending"}}function ad(e,t){let n=_e(e,t);return{pending:n.filter(o=>o.state==="captured").map(o=>o.id),done:n.filter(o=>o.state==="annotated"||o.state==="verified"||o.state==="rejected").map(o=>o.id),rows:n}}var YC=/^[A-Za-z0-9._-]+$/;function KC(e){if(!YC.test(e.id))return Promise.reject(new Error(`Not a valid spec id: "${e.id}"`));let t=["annotate",e.id,...e.force?["--force"]:[]];return Ss({args:t,cwd:e.cwd,stdio:e.stdio,signal:e.signal})}function zC(e,t,n,o){let r=GC(e,BC(e)?.outputDir??HC),s=qC(r,t);return(s.annotatedMtimeMs??0)>=o?"annotated":n===0&&VC(s)?"skipped":"failed"}function ld(e){return e===null?"d360-capture is not installed, so there is nothing to draw with. Install it, then run /screenshot annotate again.":`The installed d360-capture (${e}) draws the callouts during the capture itself, so there is no separate step to run. Run /update to move to ${dw} or later, then /screenshot annotate becomes available.`}var Sa=8;function pw(e){let t=e.results.filter(o=>o.outcome==="failed"),n=e.results.filter(o=>o.outcome==="annotated");return t.length>0?{glyph:"\u2717",cmd:Pe("/screenshot capture","",t.length===1?t[0].id:void 0),why:`${t.length} could not be drawn \u2014 taking ${t.length===1?"it":"them"} again rebuilds the boxes`}:n.length===0?null:e.voidedVerdicts>Sa?{glyph:"\u25C8",cmd:Pe("/screenshot verify","",e.scope),why:`${e.voidedVerdicts} verified shots were re-drawn, so their verdicts no longer describe the picture on disk`}:{glyph:"\u25C8",cmd:Pe("/screenshot verify","",e.scope),why:`${n.length} picture${n.length===1?"":"s"} ready to check \u2014 no browser needed`}}async function cd(e){let t=Date.now(),n=[];for(let o of e.ids){if(e.signal?.aborted)break;e.onStart?.(o);try{let{exitCode:r,output:s}=await KC({cwd:e.cwd,id:o,...e.force?{force:!0}:{},...e.signal?{signal:e.signal}:{},stdio:"pipe"}),i=zC(e.cwd,o,r,t);n.push({id:o,outcome:i,...i==="failed"?{detail:XC(s)}:{}}),e.onDone?.(o,i)}catch(r){if(r.code==="ENOENT")return{results:n,cliMissing:!0};n.push({id:o,outcome:"failed",detail:r.message}),e.onDone?.(o,"failed")}}return{results:n}}async function ud(e,t){let n=t?.cwd??process.cwd(),o=id(e);if(!ho(n))return console.log("Screenshot capture is not set up in this repo yet. Run: d360-capture init"),{kind:"continue"};let r=dt();if(!Ca(r))return console.log(ld(r)),{kind:"continue"};let s=so(n);s&&console.log(s);let i=o.mode==="scope"?o.scope:void 0,{pending:a,done:l,rows:d}=ad(n,i),g=o.mode==="all"||o.mode==="scope"?o.force:!1,w=o.mode==="single"?[o.id]:g?[...a,...l]:a;if(w.length===0){let B=l.length>0;return console.log(B?`Every shot${i?` under ${i}`:""} is already drawn. Re-draw them anyway: /screenshot annotate --all --force`:"No shots have been taken yet \u2014 /screenshot capture takes them first."),{kind:"continue"}}let k=new Set(d.filter(B=>B.state==="verified").map(B=>B.id)),{results:S,cliMissing:v}=await cd({cwd:n,ids:w,force:g});if(v)return console.log("d360-capture is not installed. Run: npm i -g document360-capture"),{kind:"continue"};let C=B=>S.filter(M=>M.outcome===B).length;console.log(`\u2713 ${C("annotated")} annotated`+(C("skipped")?` \xB7 ${C("skipped")} already current`:"")+(C("failed")?` \xB7 \u2717 ${C("failed")} failed`:""));for(let B of S.filter(M=>M.outcome==="failed"))console.log(` \u2717 ${B.id}${B.detail?` \u2014 ${B.detail}`:""}`);let T=S.filter(B=>B.outcome==="annotated").map(B=>B.id);if(T.length===0)return{kind:"continue"};let D=T.filter(B=>k.has(B)).length;if(D>Sa)return console.log(`\u26A0 ${D} verified shots were re-drawn, so their verdicts no longer describe the picture on disk.
407
- Check them when you're ready: ${Pe("/screenshot verify","",i)}`),{kind:"continue"};let L=T.filter(B=>!k.has(B)||D>0);return L.length===0?{kind:"continue"}:(console.log(In(L.length)),{kind:"forward-to-agent",prompt:Qt(n,L),display:"/screenshot verify"})}function XC(e){return e.split(/\r?\n/).map(n=>n.trim()).filter(n=>n.length>0&&!/^[▶✓↕]/.test(n)).at(-1)}re();import{existsSync as QC}from"node:fs";import{join as JC}from"node:path";import{builderChannelWired as ZC,driftedAnchors as eS,readTestidRequests as tS,testidHandoffPrompt as nS,testidRequestPaths as oS,writerDir as rS}from"document360-engine";async function gr(e,t){let n=t?.cwd;if(n){let r=sS(n);if(r){for(let s of r)console.log(s);return{kind:"continue",ownNext:!0}}}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.","","This run is also the RE-VERIFY pass for open selector requests: for every CAPTURE-TODO anchor, check the","snippet is still in its named file (an unrelated refactor can invalidate it with nobody touching the spec).","Where it is gone, re-locate the element and rewrite that CAPTURE-TODO with a current anchor and line.","or set anchorVerified:false when you cannot confirm it. /screenshot list --detail names the drifted ones."].join(`
408
- `),display:"/screenshot checklist"}}function sS(e){let t;try{t=_e(e)}catch{return null}let n=QC(JC(rS(e),"capture.json")),o=t.some(i=>i.state!=="placeholder");if(n||o)return null;let r=t.length,s=new Set(t.map(i=>i.file)).size;return r===0?[`${J("\u25CB",f)}No screenshots are planned yet, so there is nothing to stage.`,f(" A screenshot is planned by the article that needs it. /write adds the placeholders as it writes.")]:[`${J("\u25CB",f)}${r} screenshot${r===1?"":"s"} planned across ${s} article${s===1?"":"s"} \u2014 none captured, none with a spec, and no capture setup yet.`,f(" There is nothing to stage from yet: a checklist is built from what each spec needs, and no specs exist."),f(" /screenshot author writes the specs. Come back to /screenshot checklist once they exist and it will"),f(" tell you what data to stage and which test ids your developers still owe you."),"",f(" Free \u2014 this read your files and called nothing.")]}var hw="-".repeat(64);function fw(e){let t=tS(e);if(t.length===0)return null;let{mdRel:n}=oS(e),o=t.length,r=new Set(t.map(g=>g.file).filter(Boolean)).size,s=`${o} data-testid attribute${o===1?"":"s"}`,i=`${r} source file${r===1?"":"s"}`,a=nS(e,o),l=eS(t).length,d=l>0?[` \u26A0 ${l} of ${l===1?"them quotes":"them quote"} code that has changed since \u2014 still likely right,`,` but ${l===1?"it says":"they say"} so, and ${l===1?"asks":"ask"} to be found by description instead.`]:[];return ZC(e)?{prompt:a,lines:[`\u{1F4CB} Developer hand-off \u2014 ${s} requested across ${i}.`,...d," Left in your builder's inbox: their coding agent is told about it at its next session, so",` there is nothing for you to relay. Detail: ${n}`]}:{prompt:a,lines:[`\u{1F4CB} Developer hand-off \u2014 ${s} requested across ${i}.`,...d,"\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."," (Run /devhints once and requests like this reach your builder on their own.)","",hw,a,hw]}}xn();re();import{listOpenForDocs as iS,readProjectConfig as aS}from"document360-engine";function dd(e){try{return iS(e).length}catch{return 0}}function pd(){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: 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, setting 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: 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; 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(`
409
- `)}async function mw(e,t){let n=t?.cwd??process.cwd();return aS(n)?dd(n)===0?(console.log(f("Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)")),{kind:"continue"}):{kind:"forward-to-agent",prompt:pd(),display:"/inbox"}:(console.log(O("No d360-writer config here. Run /init first.")),{kind:"continue"})}re();import{askBuilder as lS,openGapQuestions as gw,readProjectConfig as cS}from"document360-engine";function Es(e){try{return gw(e).length}catch{return 0}}function hd(e,t){let n=[`\u2713 Question filed for your developers: .d360-writer/messages/${e}`," It is committed and pushed with your docs, so it reaches them wherever they work. Their answer comes"," back the same way, and /inbox folds it into the article for you."];return t>1&&n.push(` ${t} of your questions are now waiting for an answer.`),n}function fd(e){let t=["Ask your developers something the code cannot tell you: why a feature exists, when to use it, what it","affects, or whether it can be undone.",""," /ask I can document how a refund works, but not whether it can be reversed or who should approve it","","The question is written to your docs folder and travels to them with your next save. You do not have to","stop working: keep writing what you can ground, and /inbox folds the answer in when it arrives."];if(e.length>0){t.push("",`Still waiting on ${e.length} question${e.length===1?"":"s"}:`);for(let n of e.slice(0,5))t.push(` \xB7 ${n.subject.replace(/^\[gap\]\s*/,"")}`);e.length>5&&t.push(` \xB7 \u2026and ${e.length-5} more`)}return t}async function ww(e,t,n){let o=t?.cwd??process.cwd();if(!cS(o))return console.log(O("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e.join(" ").trim();if(r===""){for(let s of fd(gw(o)))console.log(s.startsWith(" \xB7")?f(s):s);return{kind:"continue",ownNext:!0}}try{let s=lS(o,{question:r,...n?{article:n}:{}}),i=Es(o);for(let a of hd(s.file,i))console.log(a.startsWith("\u2713")?q(a):f(a))}catch(s){console.log(H(`Could not file the question: ${s.message}`))}return{kind:"continue",ownNext:!0}}re();import{listOpenHints as gS,listOpenForDocs as wS,listOpenDirectives as yS,readProjectConfig as $w,computeSyncStatus as bS,planPull as kS,applyPull as $S,planImport as vS,applyImport as xS,pullDocsUpdates as RS,handoffAvailable as CS,readProductBriefState as SS,readDiscoveryQueue as PS}from"document360-engine";re();import{readProjectConfig as uS,writeProjectConfig as yw,reconcileDocsGit as dS,pullDocsUpdates as pS,probeGitState as hS,resolveGitHandoff as bw,handoffAvailable as fS}from"document360-engine";var Ns=e=>e===1?"":"s";function Ln(e,t){let n=o=>{let r=(o??"").split(`
410
- `).map(s=>s.trim()).filter(Boolean).slice(-1)[0];return r?` \u2014 ${r}`:""};switch(e){case"no-git":return"This folder is not a git repository, so there is nowhere to share to. Your docs are still saved on this machine.";case"detached-head":return"This repo is not on a branch right now. Ask your builder to check out a branch, then run /share.";case"mid-operation":return"A merge or rebase is in progress here. Finish or cancel it first, then run /share.";case"no-upstream":return"This branch has no remote yet, so there is nowhere to send your work. Ask your builder to run: git push -u origin HEAD";case"disabled":return"Sharing is switched off for this repo. Turn it on: /share on";case"diverged":return"Your work and your builder's have both moved on, so they can't be combined automatically. Your work is committed and safe \u2014 ask your builder to merge the branch.";case"rejected":return"Someone pushed to this branch first, so your work could not be sent. It IS committed and safe \u2014 try /share again in a moment, or ask your builder to merge the branch.";case"auth":return"Git could not sign in to the remote. Ask your builder to set up your git credentials, then run /share.";case"network":return"Could not reach the remote. Check your connection, then run /share again.";case"hook-failed":return`This repo's own commit checks rejected the change${n(t)}. Ask your builder to take a look \u2014 your docs are safe on this machine.`;case"failed":return`Git could not finish the share${n(t)}. Your docs are safe on this machine \u2014 run /share to try again, or show this line to your builder.`}}function Pa(e,t){let n=bw(t);if(!n.commit)return[{tone:"info",text:"Sharing: off \u2014 d360-writer leaves its work for your coding agent to commit."},{tone:"info",text:"Turn it on: /share on"}];let o=hS(e);if(!o)return[{tone:"info",text:"Sharing: unavailable \u2014 this folder is not a git repository."}];if(!o.upstream)return[{tone:"warn",text:J("\u26A0")+`This branch (${o.branch??"detached"}) has no remote, so your work can't reach your team yet.`},{tone:"info",text:"Ask your builder to run: git push -u origin HEAD"}];let r=n.push===!0?"on":n.push==="unconfirmed"?"not set up yet":"off",s=[{tone:"info",text:`Sharing: ${o.branch} \u2192 ${o.upstream} \xB7 saving: on \xB7 sending: ${r}`}];return o.ahead>0?s.push({tone:"warn",text:J("\u26A0")+`${o.ahead} change${Ns(o.ahead)} not shared yet \u2014 run /share`}):s.push({tone:"ok",text:J("\u2713")+"Everything is shared with your team."}),s}function md(e,t,n){yw({...t,gitHandoff:{commit:n,push:n}},e);let o=n?{tone:"ok",text:J("\u2713")+"Sharing on \u2014 d360-writer will save and send its own work from now on."}:{tone:"ok",text:J("\u2713")+"Sharing off \u2014 d360-writer will leave its work for your coding agent to commit."};return n?[o,...Pa(e,{...t,gitHandoff:{commit:!0,push:!0}})]:[o]}async function Ta(e,t){let n=[],o=bw(t);if(!o.commit)return{lines:[{tone:"info",text:Ln("disabled")}],changed:!1};let r=t;o.push==="unconfirmed"&&fS(e,t)&&(r={...t,gitHandoff:{commit:!0,push:!0}},yw(r,e),n.push({tone:"info",text:"Sharing is now set up for this repo \u2014 d360-writer will keep doing this automatically."}));let s=await pS(e);if(s.ok&&s.pulled>0){let d=[s.newHints>0?`${s.newHints} new hint${Ns(s.newHints)}`:null,s.newMessages>0?`${s.newMessages} new message${Ns(s.newMessages)}`:null].filter(Boolean);n.push({tone:"ok",text:J("\u2B07")+`Got your builder's latest${d.length?` \u2014 ${d.join(", ")}`:""}.`})}else!s.ok&&s.reason!=="no-upstream"&&s.reason!=="no-git"&&n.push({tone:"warn",text:J("\u26A0")+Ln(s.reason,s.detail)});let i=await dS(e,r);if(i.commit&&!i.commit.ok)return n.push({tone:"warn",text:J("\u26A0")+Ln(i.commit.reason,i.commit.detail)}),{lines:n,changed:!1};let a=i.commit?.ok?i.commit.committed.length:0;if(a>0&&n.push({tone:"ok",text:J("\u2713")+`Saved ${a} change${Ns(a)} to the docs folder.`}),i.push&&!i.push.ok)return n.push({tone:"warn",text:J("\u26A0")+Ln(i.push.reason,i.push.detail)}),{lines:n,changed:a>0};let l=i.push?.ok?i.push.pushed:0;return l>0?n.push({tone:"ok",text:J("\u2B06")+`Shared ${l} change set${Ns(l)} with your team.`}):a===0&&(s.ok&&s.pulled===0)?n.push({tone:"ok",text:J("\u2713")+"Everything is already shared with your team."}):a>0&&!i.push&&n.push({tone:"info",text:"Saved on this machine only. /share on lets d360-writer send it to your team too."}),{lines:n,changed:a>0||l>0||s.ok&&s.pulled>0}}var mS={ok:q,info:ve,warn:H,error:O};async function kw(e,t){let n=t.cwd,o=uS(n);if(!o)return console.log(O("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase(),s=a=>{for(let l of a)console.log(mS[l.tone](l.text))};if(r==="status")return s(Pa(n,o)),{kind:"continue"};if(r==="on"||r==="off")return s(md(n,o,r==="on")),{kind:"continue"};if(r)return console.log(O(`Unknown option "${r}". Use /share, /share status, /share on, or /share off.`)),{kind:"continue"};console.log(f("Exchanging work with your team\u2026"));let{lines:i}=await Ta(n,o);return s(i),{kind:"continue"}}function pn(e){let t=0,n=0,o=0,r=0;try{t=gS(e).length}catch{}try{let s=wS(e);n=s.filter(i=>i.kind==="request").length,o=s.filter(i=>i.kind==="answer").length}catch{}try{r=yS(e).length}catch{}return{hints:t,requests:n,answers:o,directives:r}}async function wd(e){let t=$w(e);if(!t)return[];if(!CS(e,t))return[];let n=await RS(e);if(n.ok){if(n.pulled===0)return[];let o=[n.newHints>0?`${n.newHints} new hint${n.newHints===1?"":"s"}`:null,n.newMessages>0?`${n.newMessages} new message${n.newMessages===1?"":"s"}`:null].filter(Boolean);return[{tone:"ok",text:`\u2B07 Got your builder's latest${o.length?` \u2014 ${o.join(", ")}`:""}.`}]}return n.reason==="no-upstream"||n.reason==="no-git"?[]:[{tone:"warn",text:`\u26A0 Couldn't get your builder's latest first \u2014 ${Ln(n.reason,n.detail)}`}]}function Aa(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 yd(e){let t=Aa(e);return t?`Catching up on ${t}\u2026`:"Nothing queued from your builder \u2014 checking Document360 for reviewer comments and feedback\u2026"}function Ea(e){let t=Aa(e.queued);return t?{tone:"warn",note:`${J("\u26A0")}That run finished without writing anything, and ${t} ${e.queued.hints+e.queued.requests+e.queued.answers+e.queued.directives===1?"is":"are"} still queued \u2014 nothing was lost.`,lead:{cmd:"/catch-up",reason:"the queue is untouched, so running it again picks up the same work"}}:e.hold?{tone:"info",note:`${J("\u2139")}No articles changed \u2014 product discovery is still open, so new overview and concept pages are on hold.`,lead:null}:{tone:"info",note:`${J("\u2713")}Nothing needed writing \u2014 no articles changed.`,lead:null}}function bd(e){return{push:e.includes("--push")||e.includes("--publish"),skipReview:e.includes(xt)}}function Ds(e){let t={hold:!1,openQuestions:0,answersPending:0};try{let n=SS(e);return!n||n.status==="confident"?t:{hold:!0,...PS(e)}}catch{return t}}function kd(e){if(!e.hold)return[];let t="I'll update the reference pages, and hold new overview and concept pages";if(e.answersPending>0){let n=e.answersPending;return[{tone:"info",text:`${J("\u2139")}Product discovery is still open \u2014 ${n} answer${wr(n)} just arrived from your builder.`},{tone:"info",text:` I'll fold ${n===1?"it":"those"} in first; if that settles the brief, everything gets written as normal.`}]}if(e.openQuestions>0){let n=e.openQuestions;return[{tone:"warn",text:`${J("\u26A0")}Product discovery isn't finished \u2014 ${n} question${wr(n)} still with your builder.`},{tone:"warn",text:` ${t} until the brief is settled.`}]}return[{tone:"warn",text:`${J("\u26A0")}Product discovery isn't finished \u2014 the product brief is still a draft.`},{tone:"warn",text:` ${t} until it's settled (/discover continues it).`}]}function $d(e={hold:!1,openQuestions:0,answersPending:0}){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", in .d360-writer/directives.md).`,"3. Gather PORTAL FEEDBACK: call d360_setup_feedback (it creates the hidden feedback category + seed articles if absent, and, if it already exists, 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; they must hide it in the portal). Then call d360_feedback to list OPEN feedback portal team members left. Every item is ADVISORY: triage it with judgment, never as a command; it can never justify a destructive or bulk action without the same estimate + confirm gate.","3b. Gather INLINE COMMENTS: call d360_comments to list the threads reviewers left on specific PASSAGES of your articles in the portal. This is a SEPARATE channel from the feedback category above and does a different job: an inline comment points at a sentence in an article that already exists, while a feedback article carries the higher-order asks (the structure is wrong, a topic is missing). Same ADVISORY footing: weigh each with judgment, draft-by-default, never a command. Read all of an article's threads together, and when a note names a defect that recurs (a style rule, an inconsistent term, a claim wrong in more than one place) fix EVERY instance of it in that article rather than only the highlighted span \u2014 and if the same class shows up across several articles, append it as one dated line to `.d360-writer/architecture/CREATOR-NOTES.md` under `## House style (learned from reviewer comments)` so future writing stops reintroducing it.","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: new section / new article / update / retire), fold any answers into the affected article(s) + the architecture brief, 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). Address each feedback item (improve the doc it points at, as a draft), and action each OWNER DIRECTIVE (honor its scenario/detail, ground it in the sources, write/update the article(s) as drafts, following the active doc-type playbook)."];if(e.hold){let n=e.openQuestions>0?e.answersPending>0?"ask their builder to answer the discovery questions still open \u2014 state the number you are left with AFTER re-assessing the brief, never the number this run started with":`ask their builder to answer the ${e.openQuestions} open discovery question${wr(e.openQuestions)}`:"continue product discovery to settle the brief";t.push('4b. PRODUCT DISCOVERY IS UNFINISHED. The product brief (.d360-writer/product-brief.md) is not `confident` yet, so the narrative it grounds \u2014 what this product IS, who it is for, the core mental model, the misconceptions, the positioning \u2014 is not settled. Decide what follows AFTER step 4, never before: if the answers you just folded in completed the brief and you flipped it to `confident`, this instruction and 4c are VOID \u2014 write everything as normal. Otherwise HOLD the articles whose shape or framing would change once the brief is confident (overview/introduction, concept and explanation pages, getting-started, positioning, "who it is for") and write everything else normally \u2014 a changed flag, a new subcommand, a corrected behaviour, a deprecation or a screenshot on an EXISTING reference page does not need the brief. The test for each candidate article: would you rewrite this page after reading a finished brief? If yes, hold it; if no, write it.',`4c. A HELD item MUST stay queued. Do NOT stamp its hint consumed, do NOT mark its message done, and do NOT flip its directive to done in step 7 \u2014 the open hint IS the queue, so stamping one you did not write means that article is never written at all. In your closing summary, name every page you held in plain words, say their hints stay queued so nothing is lost, and give exactly one next step: ${n}.`)}return t.push("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 LOCAL loop (bookkeeping in the repo; nothing here is visible to a reviewer):"," \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), including a step whose work you can verify an EARLIER session already completed but left unstamped, and append a step (d360_roadmap_add, with its run: command) for real new campaign work this run revealed; never delete existing steps;"," \u2022 for the Creator-notes feedback item (is_creator_notes:true): do NOT reply in it; 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; 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.)","10. NOW answer the people who asked, AFTER the push (steps 8-9), never before. A reviewer reads your reply in the portal and then looks at the article to check it, so replying first promises a change they cannot see. For anything whose push failed, do NOT reply on it; leave it outstanding and report it."," \u2022 for each INLINE COMMENT you actioned: call d360_comment_respond with its comment_id + article_id and a `reply` saying in plain words what you changed \u2014 in the reviewer's terms, mentioning where you applied the same fix more widely. Do NOT pass `resolve`: replying is your job, closing the thread is theirs, and they can only decide it is settled after seeing the change (your answer is recorded either way, so it will not come back at you). NEVER edit the reviewer's own comment text;"," \u2022 for each portal feedback item you actioned: append a short note at the BOTTOM of that feedback article via d360_update_article: `**d360-writer response:** \u2713 actioned in <article> (<date>)` (or `declined: <reason>`), NEVER overwriting the person's own text, then call d360_feedback_done(article_id, resulting_articles)."),t.push("Leave everything as DRAFTS for review; do not publish live. Publishing is a separate, reviewed step: articles you write here have not been read by an editor yet, so making them visible to readers is never part of this run. Tell the user what is waiting as a draft.",'Do NOT end with slash commands or a "what to do next" line. The tool prints the next step itself, scoped to what this run changed, and a second suggestion from you competes with it (yours will be the broader, more expensive one, because you cannot see how much was touched). Report what you did and stop.'),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, just plain sentences about what changed and what is worth their attention."),t.join(`
411
- `)}var TS={status:bS,plan:kS,apply:$S,planImport:vS,applyImport:xS};async function vd(e,t=TS){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 gd=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,wr=e=>e===1?"":"s";function xd(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=[];e.pulled.length&&t.push(`\u2713 Pulled ${e.pulled.length} portal edit${wr(e.pulled.length)} into local: ${gd(e.pulled)}`),e.imported.length&&t.push(`\u2713 Imported ${e.imported.length} new portal article${wr(e.imported.length)} into local drafts: ${gd(e.imported)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${wr(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${gd(e.conflicts)}`);for(let n of e.failed.slice(0,3))t.push(`\u26A0 ${n.path}: ${n.error}`);return e.failed.length>3&&t.push(`\u26A0 \u2026and ${e.failed.length-3} more left for /pull.`),t}async function vw(e,t){let n=t?.cwd??process.cwd();if(!$w(n))return console.log(O("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=qe(n,t?.profileName);if(!o.ok)return console.log(O(o.reason)),{kind:"continue"};let{push:r}=bd(e);for(let a of await wd(n))console.log(a.tone==="ok"?q(a.text):H(a.text));console.log(f("Reconciling with Document360 (pulling any portal changes)\u2026"));let s=await vd({cwd:n,profileName:t?.profileName});for(let a of xd(s))console.log(a.startsWith("\u2713")?q(a):a.startsWith("\u2139")?f(a):H(a));let i=Ds(n);for(let a of kd(i))console.log(a.tone==="warn"?H(a.text):f(a.text));return console.log(f(yd(pn(n)))),{kind:"forward-to-agent",prompt:$d(i),display:`/catch-up${r?" --push":""}`}}re();import{resolveActiveProfile as jS,resolveProjectId as IS,loadProfileMap as LS,readCommentLedger as OS,isCommentOpen as _S,saveOpenCommentCount as MS,loadCommentSweepMemory as FS,recordCommentSweep as US,planCommentSweep as WS,sweepOpenComments as BS,loadUserNames as HS,writeReviewerNotes as GS,sweptFromResult as qS,needsFullArchivePass as VS,reviewerNotesPath as YS,commentHtmlToText as xw,annotatedText as KS,readProjectConfig as zS,loadPortalLabels as XS,portalBreadcrumb as Cd,portalCategoryPath as QS,resolveModelForOperation as JS,runPartitioned as ZS,snapshotArticles as eP,EMPTY_PORTAL_LABELS as tP}from"document360-engine";import Te from"picocolors";import{CONTENT_CAP_VERSION as AS,stampArticles as ES,articlesChangedSince as NS,docsRootOf as DS}from"document360-engine";function fo(e,t,n="",o){let r=[];try{r=NS(e,t)}catch{return{changed:[],cta:null}}if(r.length===0)return{changed:[],cta:null};try{ES(e,r,{writtenCap:AS,reviewedCap:0,checkedCap:0})}catch{}let s=DS(e),i=g=>{let w=g.replace(/\\/g,"/");return w.startsWith(`${s}/`)?w.slice(s.length+1):w},a=Yt(r.map(i)),l=r.length,d=a?"/push":"/push --all";try{return{changed:r,cta:Bt(e,{text:`${n}${l} article${l===1?"":"s"} updated \u2014 ${d} saves ${l===1?"it":"them"} to Document360 as ${l===1?"a draft":"drafts"}.`,cmd:d},n,a,o)}}catch{return{changed:r,cta:null}}}var Cw=300,js=3;function nP(e,t){let n=Di(e).toLowerCase(),o=t.trim().replace(/\\/g,"/").replace(/^\/+|\/+$/g,"").toLowerCase();if(!o||n===o||n.endsWith(`/${o}`))return!0;let r=n.split("/").pop()??n;return r.startsWith(`${o}-`)||r===o||Rn(n).toLowerCase()===o}async function Na(e,t,n={}){let o=jS(e,t),r={profile:o.name,connection:o.connection,projectId:o.project.projectId,projectName:o.project.projectName},s=IS(r,o.project.projectId),i=LS(e,o.name);if(!i)return{threads:[],answered:[],labels:tP,scanned:0,failed:[],truncated:0,skipped:0,archived:!1};let a=OS(e,o.name),l=new Set(Object.values(a).map(z=>z.articlePath).filter(z=>!!z)),d=Object.keys(a).length===0||l.size>0,g=n.articleIds?.length?new Set(n.articleIds):null,w=!!(g||n.path||n.scope),k=Object.entries(i.articles).filter(([,z])=>!!z.id).filter(([z,de])=>g?g.has(de.id):n.path?z.replace(/\\/g,"/")===n.path.replace(/\\/g,"/"):n.scope?nP(z,n.scope):!0).map(([z,de])=>({articleId:de.id,path:z,title:ji(e,z),answered:w||(d?l.has(z):!0)})),S=k.slice(0,Cw),v=await XS(r,s,o.project.workspaceId,{cwd:e,profile:o.name}),C=w||n.full?{read:S,skipped:[]}:WS(S,{live:v.live,stateOf:z=>v.articles.get(z),memory:FS(e,o.name),alwaysRead:new Set(k.filter(z=>l.has(z.path)).map(z=>z.articleId))}),T=o.project.languageCode,D=VS(e)||!!n.full,L=await BS(r,s,C.read,{isOpen:(z,de)=>_S(a,z.id??"",de,z),...T?{langCode:T}:{},...n.onProgress?{onProgress:n.onProgress}:{},...D?{includeResolved:D}:{}}),B=L.threads.length>0||L.answered.length>0?await HS(r,s):new Map,M=GS(e,qS(L.threads,L.answered,z=>Cd(v,z)),{userNames:B,ourReplyIds:Object.values(a).flatMap(z=>z.replyIds??[]),...D?{completeFor:C.read.filter(z=>!L.failed.some(de=>de.articleId===z.articleId)).map(z=>z.articleId)}:{}});w||MS(e,o.name,L.threads.length);let X=new Map;for(let z of[...L.threads,...L.answered])X.set(z.articleId,(X.get(z.articleId)??0)+1);return US(e,o.name,{live:v.live,read:C.read.map(z=>z.articleId),failedIds:L.failed.map(z=>z.articleId),threadCounts:X,latestVersionOf:z=>v.articles.get(z)?.latestVersion}),{threads:L.threads,answered:L.answered,labels:v,scanned:L.scanned,failed:L.failed,truncated:Math.max(0,k.length-S.length),skipped:C.skipped.length,archived:M}}function oP(e,t=96){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n}var Rw=500;function rP(e){let t=KS(e.comment);if(!t)return"a passage";let n=t.replace(/\s+/g," ").trim();if(n.length<=Rw)return e.comment.commented_text_truncated?`\u201C${n}\u2026\u201D
412
- (Document360 sends the first 500 characters of a highlight)`:`\u201C${n}\u201D`;let o=n.slice(0,Rw).trimEnd(),r=n.length-o.length;return`\u201C${o}\u2026\u201D
413
- (+${r} more character${r===1?"":"s"}${e.comment.commented_text_truncated?", and Document360 caps a highlight at 500":""})`}function sP(e,t){let n=QS(t,e.articleId);return n.length>0?n.join(" \u203A "):e.path?Rn(e.path):""}function iP(e,t){return t.articles.get(e.articleId)?.title?.trim()||e.title||(e.path?ss(e.path):e.articleId)}function aP(e,t){return Cd(t,e.articleId,{category:e.path?Rn(e.path):null,title:e.title??(e.path?ss(e.path):null)})??e.path??e.articleId}function mo(e,t){let n=new Map;for(let o of e){let r=n.get(o.articleId);r||(r={articleId:o.articleId,path:o.path,category:sP(o,t),title:iP(o,t),label:aP(o,t),threads:[]},n.set(o.articleId,r)),r.threads.push(o)}return[...n.values()].sort((o,r)=>o.category.localeCompare(r.category)||o.title.localeCompare(r.title))}var lP=100,cP=120,Sw=(e,t)=>Math.max(40,Math.min(e??96,t));function Pw(e){let t=s=>s===1?"":"s",n=new Set(e.threads.map(s=>s.articleId)).size,o=e.answered.length,r=[`${e.threads.length} open`,`${n} article${t(n)}`];return o>0&&r.push(`${o} answered, awaiting reviewer`),r.push(e.skipped>0?`${e.scanned} of ${e.scanned+e.skipped} articles re-read`:`${e.scanned} checked`),`${Te.bold("Reviewer comments")} ${r.join(` ${Te.gray("\xB7")} `)}`}function Rd(e){let t=[],n=o=>o===1?"":"s";if(e.skipped>0&&t.push(Te.gray(` ${e.skipped} article${n(e.skipped)} weren\u2019t re-read \u2014 nobody has drafted or commented on them since your last check, so they can\u2019t have new comments. /comments --full reads every one.`)),e.failed.length){t.push(`${J("\u26A0",Te.yellow)}${e.failed.length} article${n(e.failed.length)} couldn\u2019t be checked this time \u2014 they may have comments too:`);for(let o of e.failed.slice(0,5)){let r=Cd(e.labels,o.articleId,{title:o.title})??o.title??o.articleId;t.push(` ${Te.gray(`${r} \u2014 ${oP(o.error,60)}`)}`)}e.failed.length>5&&t.push(` ${Te.gray(`+${e.failed.length-5} more`)}`),t.push(Te.gray(" Run /comments again to retry them."))}return e.truncated&&t.push(`${J("\u26A0",Te.yellow)}Checked the first ${Cw} articles; ${e.truncated} not checked this run.`),e.archived&&(e.threads.length>0||e.answered.length>0)?t.push(Te.gray(` Everything reviewers have written is kept in ${YS(".").replace(/\\/g,"/").replace(/^\.\//,"")} \u2014 it outlives a rewrite.`)):!e.archived&&(e.threads.length>0||e.answered.length>0)&&t.push(`${J("\u26A0",Te.yellow)}Couldn\u2019t write the reviewer-notes file, so Document360 is still the only copy of these notes.`),t}function Is(e,t={}){let n=[],o=a=>a===1?"":"s",r=e.answered.length,s=()=>{if(!(!t.showAnswered||r===0)){n.push(` ${Te.gray(`Answered, waiting on the reviewer (${r})`)}`);for(let a of mo(e.answered,e.labels))n.push(` ${Te.gray(`${a.label} \u2014 ${a.threads.length} thread${o(a.threads.length)}`)}`);n.push("")}};if(e.threads.length===0){let a=r>0?` ${Te.gray("\xB7")} ${r} answered, awaiting reviewer`:"",l=e.scanned+e.skipped;return n.push(e.skipped>0?`${J("\u2713",Te.green)}No open reviewer comments in the ${e.scanned} article${o(e.scanned)} checked ${Te.gray("\xB7")} ${e.skipped} of ${l} not checked${a}`:`${J("\u2713",Te.green)}No open reviewer comments across ${e.scanned} article${o(e.scanned)}.${a}`),r>0?(n.push(Te.gray(` Those ${r} are answered and left open on purpose \u2014 the reviewer closes them once they\u2019ve checked the change.`)),t.showAnswered||n.push(Te.gray(" /comments --answered lists them."))):n.push(Te.gray(" Reviewers leave these by highlighting text in a draft in the Document360 portal and commenting on it.")),n.push(""),s(),n.push(...Rd(e)),n}let i=mo(e.threads,e.labels);return n.push(Pw(e)),n.push(""),n.push(fs(["#","Category","Article","Comments"],i.map((a,l)=>[`${l+1}`,a.category||"(root)",a.title,`${a.threads.length}`]),Sw(t.width,lP),{plain:!0,align:["left","left","left","right"]})),n.push(""),s(),n.push(...Rd(e)),n}function Da(e,t={}){let n=s=>s===1?"":"s",o=[`${Te.gray("Category:")} ${e.category||"(root)"}`,`${Te.gray("Article: ")} ${Te.bold(e.title)}`,Te.gray(`${e.threads.length} comment${n(e.threads.length)} from your reviewers`),""],r=e.threads.map(s=>{let i=[xw(s.comment.comment)||"(empty comment)"];for(let a of s.comment.replies??[])i.push(`\u21B3 ${xw(a.comment)}`);return s.comment.status==="reopened"&&i.push("(reopened \u2014 you answered this once and the reviewer came back)"),s.canResolve||i.push("(you can reply to this one, but your role can\u2019t resolve it)"),[rP(s),i.join(`
414
- `)]});return o.push(fs(["Annotated text","Comment"],r,Sw(t.width,cP),{plain:!0})),o.push(""),o}function ja(e){let t=e.reduce((r,s)=>r+s.threads.length,0),n=r=>r===1?"":"s",o=[{kind:"all",label:`All articles \u2014 answer all ${t} comment${n(t)}`,groups:e}];return e.forEach((r,s)=>{o.push({kind:"article",n:s+1,label:r.title,note:`${r.threads.length} comment${n(r.threads.length)}`,group:r})}),o}function Sd(e,t={}){let n=mo(e.threads,e.labels);if(t.full&&n.length===1){let o=n[0];return[Pw(e),"",...Da(o,t),...Rd(e)]}return Is(e,t)}function uP(e){return["1. Read ALL the open threads on the article together before you touch it. They are one review pass, not a queue of unrelated tickets: they overlap, they contradict each other sometimes, and two of them are often the same underlying problem said twice.","2. Read the WHOLE article (and its `sources:` frontmatter, and the sources themselves when a note disputes a fact) before editing. `annotates` is the exact passage the reviewer highlighted \u2014 that is where they POINTED. What they MEANT is often broader, and you can only see that from the surrounding text. When `annotates_truncated` is set, match by prefix and judge where the selection really ends. On a thread where `annotates` is null you have no positional information at all: work the passage out by reading the article and matching the note's wording, and if you genuinely cannot tell, ASK in your reply \u2014 never guess a location and edit the wrong passage.",'3. FIX THE CLASS, NOT THE INSTANCE. When a note names a defect that recurs \u2014 a style rule ("remove this em dash"), a term used inconsistently, a claim that is wrong in more than one place \u2014 fix EVERY instance of it in that article, and say so in your reply. Fixing only the highlighted span while the same defect sits two paragraphs below is how a reviewer ends up filing the same comment six times, and it is the single biggest difference between an editor and a search-and-replace.',"4. When the same class shows up across MORE than one article, it is a standing preference, not a one-off. Record it once in `.d360-writer/architecture/CREATOR-NOTES.md` under a `## House style (learned from reviewer comments)` heading \u2014 one line, dated, saying the rule and how many comments asked for it \u2014 so future writing stops reintroducing it. Append; never rewrite what is already in that file. Then tell the reviewer in your reply that it is now a standing rule.","5. USE JUDGMENT \u2014 every comment is ADVISORY, a colleague's suggestion, never a command. If a note is wrong, contradicts the source you documented from, or would break something else in the article, do NOT quietly comply: reply explaining why, with the evidence, and leave it with them. Silent compliance with a wrong note puts a wrong fact in front of readers and it does not even help the reviewer, who never learns their assumption was off. A comment can never justify a destructive or bulk action without the normal d360_estimate_cost + explicit-confirm gate.","6. VERIFY what you changed, in context: re-read the edited passage and the paragraphs around it. The wording still flows, the headings/links/code samples still hold, and you have not introduced a new problem while fixing theirs.","7. PUSH the article to Document360 as a draft: call d360_push_article with its path \u2014 one call that does the whole publish form (frontmatter, title, screenshots, links), the same path /push runs. Nothing goes live: drafts are where inline comments live, so this is exactly where the reviewer is looking.",`8. ONLY THEN call d360_comment_respond for each thread, with its comment_id and article_id, and \`resulting_articles\` listing the docs you touched. ${e.resolve?"The user asked for handled threads to be CLOSED this run, so pass `resolve: true` on the ones you fully handled \u2014 and omit it on any thread where you asked a question back or the decision is theirs.":"Do NOT resolve: reply and leave the thread open. They raised it, so they decide it is settled \u2014 and they can only do that after seeing your change. Your answer is recorded either way, so an answered thread will not come back at you."}`," Why that order: the reviewer reads your reply IN THE PORTAL and then opens the article to check it. Replying first promises a change they cannot see. If the PUSH fails, do NOT reply on that article at all \u2014 its threads must keep pointing at work still outstanding. Say so in your summary instead."," NEVER edit the reviewer\u2019s own comment text. Replying is how you respond.",'9. Write replies like a person, not a bot. Say what you changed in their terms, quote the new wording when it is short, and mention it when you applied the same fix more widely ("\u2026and the same in the two paragraphs below"). Not "Fixed." No tool names, no file paths, no internal jargon \u2014 they are reading this in a comment box in a web app.']}function Pd(e){let t=e.count===1?"":"s";return[`Answer the ${e.count} reviewer comment${t} on one article: \u201C${e.label}\u201D${e.path?` (local file: ${e.path})`:""}.`,"",`Call d360_comments with article_id "${e.articleId}" to read its open threads \u2014 scope it to that id, never sweep the whole knowledge base, which costs one API read per article. A thread whose status is \`reopened\` is one you already answered and the reviewer was NOT satisfied with, so read its replies \u2014 yours included \u2014 before touching the article, and do not simply repeat the previous fix.`,"",...uP({resolve:e.resolve}),"","End with one line per thread: what the reviewer asked, what you changed, and whether you left it with them. Plain sentences for a technical writer \u2014 no tool names, no internal file names. Then say the updated article is now a draft in Document360, so the reviewers can see the changes where they left their comments, and that it stays a draft \u2014 readers keep seeing the previous version \u2014 until someone asks for it to be published live."].join(`
415
- `)}function Td(e){let t={answer:!1,resolve:!1,all:!1,showAnswered:!1,scope:{}};for(let n=0;n<e.length;n++){let o=e[n];o==="--answer"?t.answer=!0:o==="--resolve"?t.resolve=!0:o==="--all"?t.all=!0:o==="--full"?t.scope.full=!0:o==="--answered"||o==="--waiting"?t.showAnswered=!0:o==="--scope"?t.scope.scope=e[++n]:o.startsWith("--scope=")?t.scope.scope=o.slice(8):o.startsWith("-")||(t.scope.path=o)}return t.all&&(t.answer=!0),t.scope.scope===void 0&&delete t.scope.scope,t.scope.path===void 0&&delete t.scope.path,t}async function dP(e,t,n){if(t.length===0)return{kind:"continue"};let o=t.reduce((w,k)=>w+k.threads.length,0),{model:r}=JS(e.cwd,"standard"),s=new Map(t.map(w=>[w.label,w])),i=t.map(w=>({label:w.label,paths:w.path?[w.path]:[]}));console.log(f(`Answering ${o} comment${o===1?"":"s"} across ${i.length} article${i.length===1?"":"s"} (\u2264${js} agents at once) on ${r}. Each article is fixed, pushed to Document360 as a draft, then answered${n.resolve?" and resolved":" \u2014 the threads stay open for your reviewers to close"}\u2026`));let a=Date.now(),l=eP(e.cwd);try{for await(let w of ZS({cwd:e.cwd,partitions:i,promptFor:k=>{let S=s.get(k.label);return Pd({articleId:S.articleId,label:S.label,path:S.path,count:S.threads.length,resolve:n.resolve})},concurrency:js,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),allowCommentResolve:n.resolve,model:r}))if(w.type==="partition_status")w.status==="running"?console.log(f(` \u25B8 ${w.label} \u2014 answering\u2026`)):w.status==="done"?console.log(q(` \u2713 ${w.label}`)):console.log(O(` \u2717 ${w.label}`));else if(w.type==="run_done"){let k=w.results.filter(S=>!S.ok);console.log(""),console.log(`${w.results.length-k.length}/${i.length} article${i.length===1?"":"s"} answered.`),k.length&&console.log(H(`\u26A0 ${k.length} left untouched (their comments are still open, so nothing was promised to those reviewers): ${k.map(S=>S.label).join(", ")}`)),w.blocked&&console.log(H(`\u26A0 ${w.blocked}`)),w.allEmpty&&console.log(H("\u26A0 No agent produced any work this run \u2014 nothing was changed or answered.")),console.log(f(zt(Ct(a,w.results,w.totalCostUsd))))}}catch(w){console.log(O(`Answering comments failed: ${w.message}`))}let g=fo(e.cwd,l,"","/comments").changed.length;return g>0&&console.log(`${g} article${g===1?"":"s"} changed, and that new text has not been read by an editor \u2014 ${g===1?"it":"they"} can go live once /review has been over ${g===1?"it":"them"}.`),{kind:"continue"}}async function Tw(e,t){let n=t?.cwd??process.cwd();if(!zS(n))return console.log(O("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=qe(n,t?.profileName);if(!o.ok)return console.log(O(o.reason)),{kind:"continue"};let r=Td(e);console.log(f("Checking Document360 for reviewer comments\u2026"));let s;try{s=await Na(n,t?.profileName,r.scope)}catch(a){return console.log(O(`Couldn\u2019t read comments from Document360: ${a.message}`)),{kind:"continue"}}for(let a of Sd(s,{full:!!r.scope.path,showAnswered:r.showAnswered}))console.log(a);if(s.threads.length===0)return{kind:"continue"};if(r.answer&&t)return dP(t,mo(s.threads,s.labels),{resolve:r.resolve});let i=mo(s.threads,s.labels)[0];return console.log(`${J("\u2192",Te.yellow)}${Te.bold("/comments <article>")} shows one article\u2019s comments in full `+Te.gray(i?.path?`(e.g. /comments ${i.path})`:"(by its local path)")),console.log(`${J("\u2192",Te.yellow)}${Te.bold("/comments --answer")} fixes each one, updates the draft in Document360, then replies in the thread `+Te.gray("(one article at a time: /comments --answer <article>, or --scope <category>)")),{kind:"continue"}}re();import{spawn as Aw}from"node:child_process";import{mkdirSync as pP,openSync as hP,readFileSync as fP}from"node:fs";import{dirname as mP,join as gP}from"node:path";import{logsDir as wP}from"document360-engine";var yr="document360-writer",Ls=`npm i -g ${yr}@latest`,yP="document360-capture";function bP(){return new Promise(e=>{try{let t=Aw("d360-capture --version",{stdio:"ignore",shell:!0,windowsHide:!0});t.on("error",()=>e(!1)),t.on("close",n=>e(n===0))}catch{e(!1)}})}function Ia(){return gP(wP(),"self-update.log")}function La(e){return/\bEACCES\b|permission denied|EPERM|operation not permitted/i.test(e)?process.platform==="win32"?`Permission denied. Run ${Ls} from an Administrator terminal.`:`Permission denied \u2014 your global npm folder isn't writable. Either run sudo ${Ls} , or (better) switch to a Node version manager such as nvm or fnm so global installs need no sudo.`:/ENOTFOUND|EAI_AGAIN|ETIMEDOUT|ECONNRESET|network/i.test(e)?`Couldn't reach the npm registry. Check your connection or proxy, then run: ${Ls}`:/EBADENGINE|Unsupported engine/i.test(e)?`Your Node version is too old for this release. Install Node 20 or later, then run: ${Ls}`:`Run manually: ${Ls}`}function kP(e,t=6){return e.split(/\r?\n/).map(n=>n.trimEnd()).filter(Boolean).slice(-t).join(`
416
- `)}async function Oa(){let e=process.platform==="win32",n=await bP()?[yr,yP]:[yr],o=Ia(),r=null;try{pP(mP(o),{recursive:!0}),r=hP(o,"w")}catch{r=null}let s=()=>{try{return kP(fP(o,"utf8"))}catch{return""}};return new Promise(i=>{try{let a=Aw(`npm i -g ${n.map(l=>`${l}@latest`).join(" ")}`,{stdio:r===null?"ignore":["ignore",r,r],shell:!0,detached:!e,windowsHide:!0});a.on("error",l=>i({ok:!1,output:`${String(l)}
417
- ${s()}`.trim(),packages:n})),a.on("close",l=>i({ok:l===0,output:l===0?"":s(),packages:n})),e||a.unref()}catch(a){i({ok:!1,output:String(a),packages:n})}})}async function Ew(){console.log(f("Updating the d360-writer toolchain\u2026"));let e=await Oa();return e.ok?(console.log(q(`\u2713 Updated ${e.packages.join(" + ")}. Exit (/exit) and relaunch d360-writer to apply.`)),{kind:"continue"}):(console.log(O(`Update failed. ${La(e.output)}`)),e.output&&console.log(f(e.output)),console.log(f(`Full output: ${Ia()}`)),{kind:"continue"})}re();xn();import{existsSync as Ad,rmSync as $P}from"node:fs";import{basename as Nw,resolve as Ed}from"node:path";import{execFileSync as vP}from"node:child_process";import{input as xP}from"@inquirer/prompts";import{readProjectConfig as RP,devHintsGuidePath as CP}from"document360-engine";var SP=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],PP=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),_a=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),Dw=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function jw(e){let t=_a(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:Dw(t)?!0:PP.has(t)}function Nd(e){let t=null;try{t=RP(e)}catch{t=null}let n=new Set(SP);for(let o of[_a(t?.docsDir),_a(t?.captureDir),_a(t?.outputDir)])o&&Dw(o)&&n.add(o);return[...n].filter(o=>jw(o)&&Ad(Ed(e,o)))}function Dd(e,t){let n=[],o=[];for(let r of t){if(!jw(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{$P(Ed(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function Iw(e,t){try{return vP("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
418
- `).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function TP(e){return Iw(e,".d360-writer/hints")}function AP(e){return Iw(e,".d360-writer/messages")}function jd(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=TP(e),o=AP(e),r=Ad(Ed(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: ${Nw(e)}`]}async function Lw(e,t){let n=Nd(t.cwd);for(let l of jd(t.cwd,n))console.log(n.length===0?f(l):l);if(n.length===0)return{kind:"continue"};let o=Nw(t.cwd);if((await t.withPausedInput(()=>xP({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(H("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=Ad(CP(t.cwd)),{removed:i,failed:a}=Dd(t.cwd,n);console.log(q(`\u2713 Reset complete \u2014 removed ${i.length} item${i.length===1?"":"s"}. The repo is back to its original state.`));for(let l of a)console.log(O(` \u2717 ${l.path}: ${l.error}`));if(s){for(let l of Ti())console.log(l);console.log(f("(Select and copy the prompt above to paste into your coding agent.)"))}return console.log(f("Set up d360-writer again with /init (then /login, /workspace).")),{kind:"continue"}}re();import{buildBaseline as EP,buildRegistry as Od,clearRegistryCache as NP,lintArticles as _d,listAvailablePacks as Mw,readProjectConfig as wo,readStyleBaseline as DP,resolveActivePacks as Fw,styleGuidePath as Uw,writeProjectConfig as Md,writeStyleBaseline as jP,activeRuleSet as IP,buildStyleCompilePrompt as LP,loadStyleGuide as OP,loadHouseRules as _P,buildStyleLearnPrompt as MP,reviewerNotesPath as FP,listStyleGuides as UP,getStyleGuide as WP,resolveActiveProfile as BP,resolveProjectId as HP,styleGuideSettled as GP,STYLE_GUIDE_MAX_CHARS as Ow,BUILTIN_RULES as Ma,ALWAYS_ON_PACK as go}from"document360-engine";import{existsSync as Fd,mkdirSync as qP,readFileSync as Ww,writeFileSync as _w}from"node:fs";import{dirname as VP}from"node:path";import{createHash as YP}from"node:crypto";function Fa(e){let t=e.filter(o=>!o.startsWith("--")),n=(t[0]??"").toLowerCase();return n==="list"?{sub:"list"}:n==="use"?{sub:"use",value:t.slice(1).join(" ")}:n==="keep"?{sub:"keep"}:n==="explain"?{sub:"explain",value:t[1]}:n==="pull"?{sub:"pull",value:t[1]}:n==="compile"?{sub:"compile"}:n==="learn"?{sub:"learn"}:{sub:"show"}}function KP(e){try{return fm(e,"/style-guide")?.title??null}catch{return null}}function Ud(e){try{return!GP(wo(e)?.styleGuide)}catch{return!1}}function Bw(e){let t=KP(e);if(!t)return null;try{return or(e,t).ok?me("\u2713",`That settles a docs-campaign step \u2014 marked done: ${t}`):null}catch{return null}}function zP(e){let t=wo(e)??{projectId:""},n=Fw(t.styleGuide).filter(s=>s!==go);Md({...t,styleGuide:{...t.styleGuide,decidedAt:new Date().toISOString()}},e);let o=[me("\u2713",n.length>0?`Keeping ${n.join(", ")} \u2014 plus the built-in checks, which are always on.`:"Keeping the built-in checks only \u2014 the correctness rules and the anti-slop rules, both always on."),f(" Change your mind any time: /style-guide use microsoft \xB7 see the options: /style-guide list")],r=Bw(e);return r&&o.push(r),o}var Os="House";async function XP(e,t,n){let o,r;try{let C=BP(e,n);o={profile:C.name,connection:C.connection,projectId:C.project.projectId,projectName:C.project.projectName},r=await HP(o,C.project?.projectId)}catch(C){return{lines:[me("\u2717",`Not signed in to Document360: ${C instanceof Error?C.message:String(C)}`),f(" Run /login first.")],restart:!1}}let s=await UP(o,r);if(s.kind!=="ok")return{lines:[me("\u26A0",`Document360 didn't return your style guides \u2014 ${s.reason}.`),f(" Nothing is blocked. Your house style guide lives at .d360-writer/style-guide.md \u2014 write or paste"),f(" it there directly, and /review and the writer both read it. /style-guide compile then turns its"),f(" mechanical parts into checks.")],restart:!1};if(s.guides.length===0)return{lines:[me("\u2139","This Document360 project has no style guides yet."),f(" Admins create them in the portal, or write your own at .d360-writer/style-guide.md.")],restart:!1};if(!t)return{lines:["Style guides in this Document360 project:","",...s.guides.map((T,D)=>{let L=[T.language_code,T.created_by_name,T.created_at?.slice(0,10)].filter(Boolean).join(" \xB7 ");return` ${D+1} ${T.name??T.id}${T.is_default?f(" (default)"):""}${L?f(` ${L}`):""}`}),"",f(" Pull one: /style-guide pull 1 (or paste its id)")],restart:!1};let i=Number(t),a=Number.isInteger(i)&&i>=1&&i<=s.guides.length?s.guides[i-1]:s.guides.find(C=>C.id===t);if(!a)return{lines:[me("\u2717",`No style guide numbered or identified by "${t}". Run /style-guide pull to list them.`)],restart:!1};let l=await WP(o,r,a.id,{langCode:a.language_code});if(l.kind!=="ok"){let C=l.kind==="notFound"?"Document360 could not find it (style guides are per language)":l.reason;return{lines:[me("\u2717",`Could not read "${a.name??a.id}" \u2014 ${C}.`)],restart:!1}}let d=(l.guide.content??"").trim();if(!d)return{lines:[me("\u26A0",`"${a.name??a.id}" has no content yet \u2014 nothing to pull.`)],restart:!1};let g=Uw(e),w=[];if(Fd(g))try{_w(`${g}.bak`,Ww(g,"utf8"),"utf8"),w.push(f(" Your previous guide is at .d360-writer/style-guide.md.bak"))}catch{}let k=d.length>Ow?d.slice(0,Ow):d,S=`<!-- Pulled from Document360: "${a.name??a.id}" (${new Date().toISOString().slice(0,10)}). Edit freely \u2014 /style-guide pull overwrites this file. -->
419
-
420
- `;qP(VP(g),{recursive:!0}),_w(g,`${S}${k}
421
- `,"utf8");let v=wo(e)??{projectId:""};return Md({...v,styleGuide:{...v.styleGuide,pulledFrom:{styleGuideId:a.id,name:a.name??a.id,pulledAt:new Date().toISOString(),contentHash:YP("sha1").update(k).digest("hex").slice(0,16)}}},e),{lines:[me("\u2713",`Pulled "${a.name??a.id}" into .d360-writer/style-guide.md (${k.length.toLocaleString()} characters).`),...w,f(" This is PROSE, not rules \u2014 /review judges against it, and the writer now writes to it."),f(" Turn its mechanical parts into checks: /style-guide compile"),f(" Restarting the agent so it writes to the new guide\u2026")],restart:!0}}function QP(e){let t=Od(e).rules.filter(n=>n.pack.toLowerCase()===Os.toLowerCase()).map(n=>n.id);return{prompt:LP({guide:OP(e),packName:Os,existingRuleIds:t}),display:"/style-guide compile"}}function JP(e){let t=FP(e),n=Fd(t)?Ww(t,"utf8").trim():"";return!n||!/^## /m.test(n)?{kind:"nothing",lines:[me("\u2139","No reviewer comments have been read yet, so there is nothing to learn from."),f(" Reviewers comment on your drafts in Document360; /comments reads them, and every read"),f(" keeps a copy in .d360-writer/reviewer-notes.md. Run /comments first.")]}:{kind:"run",prompt:MP({notes:n,existingRules:_P(e),houseRulesFile:".d360-writer/house-rules.md"}),display:"/style-guide learn"}}function Hw(){return[f(" Read what it wrote: git diff .d360-writer/house-rules.md"),f(" These rules apply from now on \u2014 the writer follows them and /review judges against them."),f(" Disagree with one? Delete the line. It is your file, and nothing regenerates it."),f(" Restarting the agent so it writes to the new rules\u2026")]}function Gw(){return[f(` Review what it wrote: git diff .d360-writer/styles/${Os}/`),f(` Anything it could not check mechanically is listed in .d360-writer/styles/${Os}/UNCHECKABLE.md \u2014 /review judges those.`),f(` Turn them on when you are happy: /style-guide use ${Os.toLowerCase()} (they start as warnings, never blocking)`)]}var ht=(e,t)=>`${e} ${t}${e===1?"":"s"}`,Id=e=>/^v\d/i.test(e)?e:`v${e}`;function qw(e){let t={error:0,warning:0,suggestion:0};for(let n of e)t[n.severity]=(t[n.severity]??0)+1;return["error","warning","suggestion"].filter(n=>t[n]>0).map(n=>`${t[n]} ${n}`).join(" \xB7 ")}function ZP(e){let n=wo(e)?.styleGuide?.pulledFrom;return n?`.d360-writer/style-guide.md \u2014 pulled ${n.pulledAt.slice(0,10)} from "${n.name}"`:Fd(Uw(e))?".d360-writer/style-guide.md (yours)":"the built-in default"}function eT(e){let t=wo(e),n=Od(e),o=(t?.styleGuide?.packs??[]).filter(Boolean),r=n.packs.filter(l=>l.name.toLowerCase()===go),s=n.packs.filter(l=>l.name.toLowerCase()!==go),i=[`Style guide: ${ZP(e)}`,`Rule packs: ${s.length>0?s.map(l=>`${l.name.toLowerCase()} ${Id(l.version)}`).join(", "):f("none chosen")}`,`Always on: ${f(`d360 (correctness, built in \u2014 ${ht(Ma.length,"rule")})`)}`];for(let l of r)i.push(` ${f(`${l.name.toLowerCase()} ${Id(l.version)} (anti-slop \u2014 ${ht(l.ruleCount,"rule")})`)}`);r.length>0&&(i.push(f(" Every article here is machine-written, so these cannot be switched off by")),i.push(f(" choosing another pack. styleGuide.humanise: false turns them off deliberately.")));let a=[...Ma.map(l=>({severity:l.severity})),...n.rules.map(l=>({severity:l.severity}))];i.push("",`${ht(a.length,"rule")} active \xB7 ${qw(a)}`);try{let l=_d({cwd:e}),d=l.findings.filter(w=>!w.baselined),g=d.filter(w=>w.severity==="error").length;i.push(""),i.push(g===0?me("\u2713",`No style errors across the docs${d.length>0?`, though ${ht(d.length,"other issue")} ${d.length===1?"is":"are"} reported`:""}.`):me("\u2717",`${ht(g,"style error")} \u2014 /lint --blocked shows them, /lint --blocked --fix corrects them.`)),l.baselinedCount>0&&i.push(me("\u2139",`${ht(l.baselinedCount,"issue")} ${l.baselinedCount===1?"was":"were"} already in your articles when this style guide was chosen, so ${l.baselinedCount===1?"it never blocks":"they never block"} publishing.`)),l.ruleErrors.length>0&&i.push(me("\u26A0",`${ht(l.ruleErrors.length,"rule")} could not be loaded: ${l.ruleErrors.slice(0,2).map(w=>`${w.ruleId} (${w.reason})`).join("; ")}`))}catch{}return i.push(""),i.push(f(" See them all: /style-guide list \xB7 change: /style-guide use <preset> \xB7 one rule: /style-guide explain <rule>")),Ud(e)&&(i.push(""),i.push("Nobody has settled this yet, and it is a decision \u2014 nothing above changed anything:"),i.push(" Happy with these rules? /style-guide keep"),i.push(" Want a stricter standard? /style-guide use microsoft (or google)"),i.push(f(" Worth settling now rather than later: it shapes every article written from here, and")),i.push(f(" changing it once a knowledge base exists means going back over what is already written."))),i}function Ld(e){let t=wo(e),n=new Set(Fw(t?.styleGuide)),o=Mw(e),r=["Rule packs you can turn on:",""],s=Math.max(12,...o.map(i=>i.name.length));for(let i of o){let a=i.name.toLowerCase(),l=n.has(a),d=a===go,g=l?"\u2713":"\xB7",w=d?f("(always on)"):l?f("(active)"):"",k=i.local?f(" [yours]"):"";r.push(` ${g} ${a.padEnd(s)}${k} ${i.description??""}`),r.push(` ${f(`${ht(i.rules.length,"rule")} \xB7 ${qw(i.rules)} \xB7 ${Id(i.version)}`)} ${w}`),i.errors.length>0&&r.push(me("\u26A0",`${ht(i.errors.length,"rule")} in this pack could not be loaded \u2014 /style-guide explain names them.`))}return o.every(i=>i.name.toLowerCase()===go)&&(r.push(""),r.push(f(" The Microsoft and Google style guides are not installed in this build yet."))),r.push(""),r.push(f(" Turn one on: /style-guide use <name> (this replaces the chosen set, it does not add to it)")),r.push(f(" Several: /style-guide use microsoft,google")),r.push(f(" Back to none: /style-guide use none")),r}function tT(e,t){if(!t)return[me("\u26A0","Name a rule: /style-guide explain Humanise.EmDash")];let n=Od(e),o=Ma.find(d=>d.id.toLowerCase()===t.toLowerCase()),r=n.rules.find(d=>d.id.toLowerCase()===t.toLowerCase());if(!o&&!r){let d=[...Ma.map(g=>g.id),...n.rules.map(g=>g.id)].filter(g=>g.toLowerCase().includes(t.toLowerCase())).slice(0,5);return[me("\u26A0",`No active rule called "${t}".`),...d.length>0?[f(` Did you mean: ${d.join(", ")}`)]:[f(" /style-guide list shows the active packs.")]]}let s=o?.id??r.id,i=o?.severity??r.severity,a=o?"built in (correctness \u2014 always on)":`pack: ${r.pack.toLowerCase()}`,l=[`${s} ${i} \xB7 ${a}`,""];l.push(` ${o?.summary??r.message}`),r?.link&&l.push(f(` ${r.link}`)),r?.degraded&&(l.push(""),l.push(me("\u26A0",`This rule is translated approximately: ${r.degraded}. It may match slightly more than the original does.`)));try{let d=_d({cwd:e}).findings.filter(w=>w.ruleId===s),g=d.filter(w=>!w.baselined);l.push(""),l.push(d.length===0?" Currently: no findings.":` Currently: ${ht(g.length,"finding")}${d.length!==g.length?`, plus ${d.length-g.length} baselined and hidden`:""}.`)}catch{}return l.push(""),o?(l.push(f(" Built-in checks are grounded in your product's own source and cannot be switched off \u2014 they")),l.push(f(" catch defects of fact, not matters of taste."))):(l.push(i==="error"?f(' This one BLOCKS publishing \u2014 your config sets it to "error" deliberately.'):f(" Style rules never block publishing. Fix it when you want to; it will not hold a page back.")),l.push(f(` Silence it everywhere: add "${s}": "off" to styleGuide.rules in .d360-writer/config.json`)),i!=="error"&&l.push(f(" Silence one passage: <!-- vale "+s+" = NO --> \u2026 <!-- vale "+s+" = YES -->"))),l}function nT(e,t){let n=(t??"").trim();if(!n)return{lines:[me("\u26A0","Name the packs to use: /style-guide use microsoft (or `none`)"),...Ld(e)],restart:!1};let o=n.toLowerCase()==="none"?[]:n.split(/[,\s]+/).map(d=>d.trim().toLowerCase()).filter(Boolean),r=new Map(Mw(e).map(d=>[d.name.toLowerCase(),d])),s=o.filter(d=>!r.has(d));if(s.length>0)return{lines:[me("\u2717",`No rule pack named ${s.map(d=>`"${d}"`).join(", ")}.`),"",...Ld(e)],restart:!1};let i=wo(e)??{projectId:""};Md({...i,styleGuide:{...i.styleGuide,packs:o,decidedAt:new Date().toISOString()}},e),NP();let a=[me("\u2192",`Switching to: ${o.length>0?o.join(", "):"the built-in checks only"}${o.includes(go)?"":` (+ ${go}, always on)`}\u2026`)];try{let d=_d({cwd:e}),g=new Set(d.findings.map(w=>w.path)).size;if(d.findings.length===0)a.push(me("\u2713",g===0?"No articles yet \u2014 everything you write from here is held to the full set.":"Nothing to record: your articles are already clean against these rules."));else{let w=DP(e),k=EP(d.findings,IP(e));jP(e,k),a.push(me("\u2713",`Recorded ${ht(d.findings.length,"existing issue")} across ${ht(g,"article")} as accepted.`),f(" .d360-writer/style-baseline.json \u2014 commit it. It defines what the publish gate lets through, and a"),f(" teammate with a different copy gets a different answer from the same gate."),me("\u2713","Nothing is blocked today. New writing, and any paragraph you edit, is held to the full set.")),a.push(me("\u2139",`Those ${ht(g,"article")} do not follow ${o.join(", ")} \u2014 they are exempt, not compliant.`),f(" To bring them up to it: /review --all --fix, then /lint --all --fix. That is a pass over every"),f(" article and it costs accordingly \u2014 which is why this is worth settling before a knowledge base exists.")),w&&a.push(f(` (Replaced the baseline recorded ${w.createdAt.slice(0,10)}.)`))}}catch(d){a.push(me("\u26A0",`The packs are active, but recording what was already there failed: ${d instanceof Error?d.message:String(d)}`)),a.push(f(" Run /lint to see the current state before publishing."))}let l=Bw(e);return l&&a.push(l),a.push(f(" Restarting the agent so it writes to the new rules\u2026")),{lines:a,restart:!0}}async function Ua(e,t){let{sub:n,value:o}=Fa(e),r=s=>{for(let i of s)console.log(i);console.log("")};switch(n){case"list":return r(Ld(t.cwd)),{kind:"continue"};case"explain":return r(tT(t.cwd,o)),{kind:"continue"};case"use":{let s=nT(t.cwd,o);return r(s.lines),s.restart?{kind:"clear"}:{kind:"continue"}}case"keep":return r(zP(t.cwd)),{kind:"continue"};case"pull":{let s=await XP(t.cwd,o,t.profileName);return r(s.lines),s.restart?{kind:"clear"}:{kind:"continue"}}case"compile":{let s=QP(t.cwd);return{kind:"forward-to-agent",prompt:s.prompt,display:s.display}}case"learn":{let s=JP(t.cwd);return s.kind==="nothing"?(r(s.lines),{kind:"continue"}):{kind:"forward-to-agent",prompt:s.prompt,display:s.display}}default:return r(eT(t.cwd)),{kind:"continue"}}}re();import{lintDocs as Ba,loadStyleGuide as ny,buildReviewPrompt as oy,hasCaptureArtifacts as ry,readProjectConfig as sy,DEFAULT_DOCS_DIR as iy,listArticleFiles as br,normalizeScope as wT,planPartitions as yT,runPartitioned as bT,partitionCoverage as kT,resolveModelForOperation as $T,stampArticles as vT,reviewStalePaths as xT,readReviewerNotes as ay,renderNotesForPrompt as ly,readDocsPlan as RT,CONTENT_CAP_VERSION as CT}from"document360-engine";import{listArticleFiles as oT,lintDocs as rT,planFindingPartitions as sT,planPartitions as iT,readDocsPlan as aT,readProjectConfig as lT,runRate as Vw,DEFAULT_DOCS_DIR as cT}from"document360-engine";function Yw(e){switch(e.cmd){case"/review":return{concurrency:_n,maxPerPartition:Bd,minutesPerBatch:5};case"/write":return{concurrency:3,minutesPerBatch:4};case"/lint":return{concurrency:3,minutesPerBatch:2};default:return{concurrency:3,minutesPerBatch:2}}}function uT(e,t){let n=rT({cwd:e,scope:t.scope}).filter(s=>!s.baselined),o=t.flags.has("--blocked")?n.filter(s=>s.severity==="error"):n;if(o.length===0)return null;let r=new Set(o.map(s=>s.path)).size;return{lead:`${o.length} issue${o.length===1?"":"s"} \xB7 ${r} article${r===1?"":"s"}`,articles:r,batches:sT(o).length}}function dT(e,t){try{if(t.cmd==="/write"){let n=(lT(e)?.docsDir??cT).replace(/\/+$/,""),o=aT(e,n).map(s=>s.path);if(o.length===0)return null;let r=t.scope?o.filter(s=>s===t.scope||s.startsWith(`${t.scope}/`)):o;return t.flags.has("--rewrite")?r:Pn(e,n,r)}return t.cmd==="/review"?yo(e,[...t.flags],t.scope):oT(e,t.scope)}catch{return null}}function Kw(e,t){let n=On(e,t);if(!n)return null;let o=n.indexOf(" batch");if(o<0)return null;let r=n.lastIndexOf("\xB7 ",o);return r<0?n:n.slice(r+2)}function On(e,t){let n=Ki(t);if(!n||!Ec(n))return null;let o=Yw(n),r=n.cmd==="/lint"?Wd(()=>uT(e,n)):null,s=r?null:dT(e,n),i=r?r.articles:s?.length??0;if(n.cmd==="/lint"?!r||i<4:!s||i<4)return null;let a=r?r.batches:iT(s,o.maxPerPartition?{maxPerPartition:o.maxPerPartition}:void 0).length,l=Math.ceil(a/o.concurrency),d=Wd(()=>Vw(e,n.cmd)),g=l*(d?.minutesPerWave??o.minutesPerBatch),w=r?r.lead:`${i} articles`,k=d?.usdPerArticle!==void 0?` \xB7 ~${Jw(i*d.usdPerArticle)}`:"";return`${w} \xB7 ${a} batch${a===1?"":"es"} \xB7 ~${Qw(g)}${k}`}var zw=.7,Xw=1.4;function Qw(e){let t=Math.max(1,Math.round(e*zw)),n=Math.max(t,Math.round(e*Xw));if(n<90)return`${t}\u2013${n} min`;let o=r=>r<60?`0h ${r}m`:`${Math.floor(r/60)}h ${r%60}m`;return`${o(t)}\u2013${o(n)}`}function Jw(e){let t=e*zw,n=e*Xw;return n>=10?`$${Math.round(t)}\u2013${Math.round(n)}`:`$${t.toFixed(2)}\u2013${n.toFixed(2)}`}function Wd(e){try{return e()}catch{return null}}function Wa(e,t,n,o){if(n<4||o<1)return null;let r=Yw({cmd:t,scope:void 0,flags:new Set,args:[]}),s=Math.ceil(o/r.concurrency),i=Wd(()=>Vw(e,t)),a=s*(i?.minutesPerWave??r.minutesPerBatch),l=i?.usdPerArticle!==void 0?` \xB7 ~${Jw(n*i.usdPerArticle)}`:"";return`~${Qw(a)}${l}`}import{renderGapsForPrompt as cy}from"document360-engine";import{recordRunSample as ST}from"document360-engine";re();import{readProjectConfig as pT,loadProfileMap as hT,resolveActiveProfile as fT,desiredCategoryOrder as mT,desiredArticleOrder as gT}from"document360-engine";function Zw(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}var ey=e=>e.replace(/\\/g,"/").split("/").pop()??e;function _s(e,t){try{if(!pT(e))return[];let n=fT(e,t),o=hT(e,n.name);if(!o)return[];let r=new Map;for(let i of gT(o)){let a=r.get(i.categoryPath);a?a.push(i):r.set(i.categoryPath,[i])}let s=[];for(let i of mT(o)){s.push(Zw(ey(i.path)));for(let a of(r.get(i.path)??[]).sort((l,d)=>l.order-d.order))s.push(` ${Zw(ey(a.path))}`)}return s}catch{return[]}}async function ty(e,t){let n=_s(t.cwd,t.profileName);if(n.length===0)return console.log(f("No documentation structure yet \u2014 run /init and author some articles first.")),{kind:"continue"};console.log(Z("Documentation order (categories \u2192 articles):"));for(let o of n)console.log(o);return console.log(""),{kind:"continue"}}function Hd(e,t){return ps(e,br(e,t))}function Gd(e,t){return xT(e,br(e,t),CT)}function Ms(e){return e.includes("--blocked")||e.includes("--stale")}function yo(e,t,n){return t.includes("--blocked")?Hd(e,n):t.includes("--stale")?Gd(e,n):br(e,n)}function uy(e,t,n){let o;try{o=RT(e)}catch{return[]}let r=new Map(o.map(i=>[i.path.replace(/\\/g,"/"),i])),s=[];for(let i of n){let a=i.replace(/\\/g,"/").replace(`${t}/`,""),l=r.get(a);l&&s.push({path:i,type:l.type,...l.purpose?{purpose:l.purpose}:{}})}return s}function dy(e,t){let n=sy(e);if(!n)return null;let o=(n.docsDir??iy).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),s=Ms(t),i=t.find(T=>!T.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),a=Ba({cwd:e}),l=i?wT(o,i):"",d=l?a.filter(T=>T.path===`${o}/${l}`||T.path.startsWith(`${o}/${l}/`)):a,g=s?yo(e,t,i):void 0,w=g?d.filter(T=>g.includes(T.path)):d,k=i||s?"":_s(e).join(`
422
- `),S=ry(e,n),v=oy({docsRoot:o,scope:i,styleGuide:ny(e),deterministicFindings:w,fix:r,structure:k||void 0,screenshots:S,...g?{paths:g}:{},reviewerNotes:ly(ay(e),g??br(e,i)),openGaps:cy(e,g??br(e,i)),planRows:uy(e,o,g??br(e,i))}),C=t.includes("--blocked")?" --blocked":t.includes("--stale")?" --stale":"";return{prompt:v,display:`/review${i?` ${i}`:""}${C}${r?" --fix":""}`}}var PT=e=>"ruleId"in e,_n=3,Bd=3;function qd(e,t){let n=dy(e,t);if(!n)return null;let o=t.find(S=>!S.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),r=yo(e,t,o),s=yT(r,{maxPerPartition:Bd});if(s.length<=1)return{kind:"single",...n};let i=sy(e),a=(i?.docsDir??iy).replace(/\\/g,"/").replace(/\/+$/,""),l=t.includes("--fix"),d=ny(e),g=Ba({cwd:e}),w=ay(e),k=ry(e,i);return{kind:"partitioned",partitions:s,articles:r.length,wholeKb:!o&&!Ms(t),display:n.display,promptFor:S=>{let v=new Set(S.paths);return oy({docsRoot:a,styleGuide:d,deterministicFindings:g.filter(C=>v.has(C.path)),fix:l,screenshots:k,paths:S.paths,reviewerNotes:ly(w,S.paths),openGaps:cy(e,S.paths),planRows:uy(e,a,S.paths)})}}}function Vd(e,t){if(!Ms(t))return null;let n=t.find(w=>!w.startsWith("--"));if(yo(e,t,n).length>0)return null;let o=t.includes("--blocked"),r=!!n&&n.endsWith(".md"),s=n?r?" here":` in ${n}`:"",a=o?`\u2713 Nothing is blocked${s} \u2014 ${n&&r?"it has":"every article has"} been through an editorial read.`:`\u2713 ${r?"This article has":`Every article${s} has`} already been read by the current editor \u2014 nothing to re-read.`,l=`/push${n?` ${n}`:" --all"}`,d=Bt(e,{text:`${l} saves ${r?"it":"what has changed"} to Document360 as ${r?"a draft":"drafts"}.`,cmd:l},"",n,"/review"),g=vt(e,dy(e,t)?.display??"");return{lines:[a,` ${d.text}`],closed:g,cta:d}}async function py(e,t){let n=Vd(t.cwd,e);if(n){console.log(q(n.lines[0]));for(let r of n.lines.slice(1))console.log(f(r));for(let r of n.closed)console.log(q(r));return{kind:"continue",ownNext:!0}}if(jn("review",e)){let r=pr(t.cwd,"review",e,t.profileName);if(r.length>0){for(let s of r)console.log(f(s));return{kind:"continue"}}}let o=qd(t.cwd,e);return o?o.kind==="single"?{kind:"forward-to-agent",prompt:o.prompt,display:o.display}:await TT(t,o,e.includes("--fix"),e.find(r=>!r.startsWith("--"))):(console.log(O("No d360-writer config here. Run /init first.")),{kind:"continue"})}async function TT(e,t,n,o){let{model:r}=$T(e.cwd,"standard"),s=Wa(e.cwd,"/review",t.articles,t.partitions.length);console.log(f(`Reviewing ${t.articles} article${t.articles===1?"":"s"} in ${t.partitions.length} batches (\u2264${_n} editors at once) on ${r}${n?", applying fixes":", report only"}${s?` \xB7 ${s}`:""}\u2026`));let i=Date.now(),a=new ar;a.start();let l={aborted:!1,partitions:0,failed:0,notRun:0,producedNothing:!0};try{for await(let k of bT({cwd:e.cwd,partitions:t.partitions,promptFor:t.promptFor,concurrency:_n,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:r,scope:"review"}))if(k.type==="partition_status")k.status==="running"?console.log(f(` \u25B8 ${k.label} \u2014 reviewing\u2026`)):k.status==="done"?console.log(q(` \u2713 ${k.label}`)):console.log(O(` \u2717 ${k.label}`));else if(k.type==="run_done"){let S=kT(t.partitions,k.results);l={aborted:!!k.aborted,partitions:t.partitions.length,failed:S.failed.length,notRun:S.notRun.length,...k.blocked?{blocked:k.blocked}:{},...k.allEmpty?{allEmpty:!0}:{},...k.bailedEmpty?{bailedEmpty:!0}:{}},console.log(""),console.log(`${k.results.length-S.failed.length}/${t.partitions.length} batches reviewed.`),S.failed.length&&console.log(H(`\u26A0 ${S.failed.length} not reviewed: ${S.failed.map(C=>C.label).join(", ")}`)),S.notRun.length&&console.log(H(`\u26A0 ${S.notRun.length} batch${S.notRun.length===1?"":"es"} never started \u2014 their articles are untouched.`)),k.blocked&&console.log(H(`\u26A0 ${k.blocked}`)),k.allEmpty&&console.log(H("\u26A0 No editor produced any work this run \u2014 nothing was reviewed or changed."));for(let C of Yd(t))console.log(f(C));if(n&&!k.allEmpty&&!k.blocked)try{vT(e.cwd,S.covered,it("review"))}catch{}let v=a.stop();if(console.log(f(zt(Ct(i,k.results,k.totalCostUsd,Date.now(),v.activeSeconds)))),!k.allEmpty&&!k.blocked){let C=k.results.filter(T=>T.ok).length;ST(e.cwd,"review",{articles:S.covered.length,waves:Math.ceil(C/Math.max(1,_n)),seconds:v.activeSeconds,costUsd:k.totalCostUsd})}}}catch(k){return a.stop(),console.log(O(`Review failed: ${k.message}`)),{kind:"continue"}}if(a.stop(),n&&Kt(l))for(let k of vt(e.cwd,t.display))console.log(q(k));if(!n)return{kind:"continue"};let d=dr(e.cwd,["--fix"],Ba({cwd:e.cwd,scope:o}));for(let k of d.lines)console.log(k);let w=Ba({cwd:e.cwd,scope:o}).filter(k=>!k.baselined).filter(k=>PT(k)&&k.severity==="error");if(console.log(""),w.length>0){let k=Pe("/lint","--blocked --fix",o);console.log(f(`Editor applied its fixes, but ${w.length} style error${w.length===1?"":"s"} remain \u2014 ${k} clears them (finding them costs nothing, one pass corrects them). It is the last paid pass before publishing: anything still standing after a second attempt is reported for a person rather than run again.`))}else console.log(f(Bt(e.cwd,{text:"\u2713 Reviewed and fixed. /push --all saves the articles to Document360 as drafts.",cmd:"/push --all"},"",o).text));return{kind:"continue",ownNext:!0}}function Yd(e){return e.partitions.length<2?[]:[`Each editor saw one slice of the docs, so reading order and terminology drift ${e.wholeKb?"ACROSS categories":"ACROSS the rest of the knowledge base"} were not judged.`,"/structure shows the reading order if you want to check it yourself."]}re();import{readProjectConfig as AT}from"document360-engine";function Kd(e,t){if(!AT(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: 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 /push."].filter(Boolean).join(`
423
- `),display:`/reorder${n?` ${n}`:""}`}}async function hy(e,t){if(jn("reorder",e)){let o=pr(t.cwd,"reorder",e,t.profileName);if(o.length>0){for(let r of o)console.log(f(r));return{kind:"continue"}}}let n=Kd(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(O("No d360-writer config here. Run /init first.")),{kind:"continue"})}re();import{computeReadiness as ET,readinessPlaceholderPlaces as NT}from"document360-engine";import He from"picocolors";var zd=5;function Xe(e,t=58){let n=e.replace(/\\/g,"/");return n.length<=t?n:`\u2026${n.slice(n.length-t+1)}`}function DT(e){let t=[],n=e.verdict;if(e.conflicts.length>0&&t.push({glyph:"\u2717",paint:He.red,title:`Changed here and on Document360 (${e.conflicts.length})`,fix:"/resolve",items:e.conflicts.map(o=>Xe(o))}),n.unreviewed.length>0&&t.push({glyph:"\u2717",paint:He.red,title:`Never read by an editor (${n.unreviewed.length})`,fix:"/review --blocked --fix",items:n.unreviewed.map(o=>Xe(o))}),n.styleErrors.length>0){let o=n.styleErrors.reduce((r,s)=>r+s.errors,0);t.push({glyph:"\u2717",paint:He.red,title:`Break house style rules your config makes blocking (${o} error${o===1?"":"s"})`,fix:"/lint --blocked --fix",items:n.styleErrors.map(r=>`${Xe(r.path)} (${r.errors})`)})}if(n.placeholders.length>0){let o=NT(e);t.push({glyph:"\u2717",paint:He.red,title:`Would show "[Screenshot: \u2026]" to your readers (${n.placeholders.length} article${n.placeholders.length===1?"":"s"}, ${o} place${o===1?"":"s"})`,fix:"/screenshot",items:n.placeholders.map(r=>`${Xe(r.path)} (${r.missingShots.length+r.orphans})`)})}return t}function jT(e){let t=e.verdict,n=[];return e.conflicts.length===0&&n.push(`${J("\u2713",He.green)}Nothing is in conflict with Document360`),t.unreviewed.length===0&&n.push(`${J("\u2713",He.green)}Every article has been read by an editor`),t.styleErrors.length===0&&n.push(`${J("\u2713",He.green)}House style: nothing blocking`),t.placeholders.length===0&&n.push(`${J("\u2713",He.green)}No placeholder text would reach a reader`),n}function IT(e,t){if(e.rows.length===0)return[];let n=r=>r?He.green("\u2713"):He.red("\u2717"),o=e.rows.map((r,s)=>[String(s+1),Xe(r.path,46),n(r.reviewed),r.styleErrors===0?He.green("\u2713"):He.red(`\u2717 ${r.styleErrors}`),r.placeholders===0?He.green("\u2713"):He.red(`\u2717 ${r.placeholders}`),r.conflict?He.red("conflict"):r.draftPending?He.yellow("draft"):r.localAhead?f("not saved"):f("\u2014")]);return fs(["#","Article","Read","Style","Pictures","Document360"],o,t).split(`
424
- `)}function Xd(e,t={}){let n=ET(e,t.profileName),o=[];if(n.rows.length===0)return o.push(Z("Publish readiness")),o.push(""),o.push(n.tracked===0?`${J("\u25CB",He.gray)}No articles are tracked yet. /write authors them, /push saves them to Document360.`:`${J("\u2713",He.green)}All ${n.tracked} articles are live and unchanged \u2014 nothing is waiting on you.`),n.orphans.length>0&&o.push(...fy(n)),o.push(""),o.push(f(" Free \u2014 /status reads your local files and the last sync. It calls nothing.")),o;let r=n.rows.length,s=n.blocked.length;o.push(Z("Publish readiness")+f(` ${r} article${r===1?"":"s"} not yet settled with readers \xB7 ${s===0?"nothing blocked":`${s} blocked`}`)),o.push(""),t.all&&(o.push(...IT(n,t.width??100)),o.push(""));for(let l of DT(n)){o.push(` ${J(l.glyph,l.paint)}${l.title}${l.fix?f(` ${l.fix}`):""}`);for(let d of l.items.slice(0,zd))o.push(f(` ${d}`));l.items.length>zd&&o.push(f(` \u2026and ${l.items.length-zd} more`)),o.push("")}let i=jT(n);if(i.length>0){for(let l of i)o.push(` ${l}`);o.push("")}let a=n.rows.filter(l=>l.localAhead).length;return a>0&&o.push(f(` ${a} changed here \u2014 /push saves ${a===1?"it":"them"} to Document360 as ${a===1?"a draft":"drafts"}. Readers see nothing until then.`)),n.draftPending.length>0&&o.push(f(` ${n.draftPending.length} saved on Document360 as ${n.draftPending.length===1?"a draft":"drafts"} and not live \u2014 /publish takes ${n.draftPending.length===1?"it":"them"} to your readers.`)),n.orphans.length>0&&o.push(...fy(n)),!t.all&&n.rows.length>0&&o.push(f(" /status --all shows every article, gate by gate.")),o.push(""),o.push(f(" Free \u2014 /status reads your local files and the last sync. It calls nothing.")),o}function fy(e){let t=e.orphans.length;return[f(` ${t} article${t===1?"":"s"} on Document360 ${t===1?"is":"are"} not in your docs folder (${Xe(e.orphans[0].path,40)}${t>1?`, +${t-1} more`:""}) \u2014 /doctor lists ${t===1?"it":"them"}.`)]}async function my(e,t){let n=e.some(o=>o==="--all"||o==="--full");for(let o of Xd(t.cwd,{profileName:t.profileName,all:n}))console.log(o);return{kind:"continue",ownNext:!0}}re();import{computeReadiness as LT,retireArticle as OT,retiredPaths as _T,normalizeScope as MT}from"document360-engine";import{select as FT}from"@inquirer/prompts";function Qd(e,t){let n=LT(e,t),o=_T(e,t),r=[Z("Take an article off your readers"),""];if(n.orphans.length>0){r.push(` ${J("\u25CB",f)}On Document360, but not in your docs folder \u2014 the usual reason to retire:`);for(let s of n.orphans.slice(0,8))r.push(f(` ${Xe(s.path)}`));n.orphans.length>8&&r.push(f(` \u2026and ${n.orphans.length-8} more`)),r.push("")}if(o.length>0){r.push(` ${J("\u2713",f)}Already retired \u2014 readers do not see ${o.length===1?"it":"these"}:`);for(let s of o.slice(0,5))r.push(f(` ${Xe(s)}`));o.length>5&&r.push(f(` \u2026and ${o.length-5} more`)),r.push("")}return n.orphans.length===0&&o.length===0&&(r.push(f(" Nothing obvious to retire \u2014 every tracked article is still in your docs folder.")),r.push("")),r.push(f(" /retire <path> takes one off your readers. Any tracked article can be named, not just these.")),r.push(f(" Nothing is deleted: the article, its history and every reviewer comment stay on Document360.")),r.push(f(" /push puts one back \u2014 reviving is a publish like any other, with the same review.")),r}async function gy(e,t){let n=t.cwd,o=e.find(a=>!a.startsWith("-"));if(!o){for(let a of Qd(n,t.profileName))console.log(a);return{kind:"continue",ownNext:!0}}let r=MT(n,o)||o;if(!(e.includes("--yes")||e.includes("-y"))&&(console.log(""),console.log(H(`This takes "${Xe(r)}" off your readers on Document360.`)),console.log(f(" The article, its history and every reviewer comment stay \u2014 nothing is deleted.")),console.log(f(" /push puts it back later if you change your mind.")),console.log(""),await FT({message:"Take it off your readers?",choices:[{name:"No \u2014 leave it as it is",value:"no"},{name:"Yes \u2014 readers stop seeing it",value:"yes"}]})!=="yes"))return console.log(f("Nothing changed.")),{kind:"continue",ownNext:!0};let i=await OT({cwd:n,path:r,profileName:t.profileName,now:new Date().toISOString()});return i.ok?(console.log(i.alreadyHidden?`${J("\u2713")}"${Xe(r)}" was already invisible to readers. Recorded as retired, so nothing will offer to publish it again.`:`${J("\u2713")}"${Xe(r)}" is no longer visible to your readers.`),console.log(f(" It is still on Document360 with its history and comments intact. /push puts it back.")),{kind:"continue",ownNext:!0}):(console.log(O(`${J("\u2717")}Could not retire "${Xe(r)}" \u2014 ${i.error.message}`)),{kind:"continue",ownNext:!0})}re();import{scanTerminology as wy,approvalBlockedReason as yy,readProjectConfig as UT,writeProjectConfig as WT,termKey as Jd,HEAD_NOUN_CAP as BT}from"document360-engine";import Ht from"picocolors";var HT=3,GT=e=>e.uses.map(t=>`${Ht.bold(t.form)} ${f(`${t.files.length} article${t.files.length===1?"":"s"}`)}`).join(f(" \xB7 "));function Zd(e,t={}){let n=wy(e,t.scope?{scope:t.scope}:{}),o=[];if(n.scanned===0)return[Z("Terminology"),"",`${J("\u25CB",f)}No articles to read yet.`,""];let r=n.variance.length+n.headings.length;if(o.push(Z("Terminology")+f(` ${n.scanned} article${n.scanned===1?"":"s"} read \xB7 ${r===0?"nothing inconsistent":`${r} to look at`}`)),o.push(""),n.variance.length>0){o.push(` ${J("\u2717",Ht.red)}The same term, spelled more than one way`);for(let s of n.variance){o.push(` ${GT(s)}`);let i=s.uses[s.uses.length-1],a=i.files.slice(0,HT);o.push(f(` "${i.form}" is in ${a.map(d=>Xe(d,40)).join(", ")}${i.files.length>a.length?`, +${i.files.length-a.length} more`:""}`));let l=yy(s);l?o.push(f(` ${l}`)):o.push(f(` /terms --approve "${s.uses[0].form}" makes that the approved spelling`))}o.push("")}if(n.headNouns.length>0){let s=t.all?n.headNouns:n.headNouns.slice(0,BT);o.push(` ${J("\u25CB",f)}Possibly the same thing under a short name \u2014 ${Ht.italic("your call")}`);for(let i of s)o.push(f(` ${i.uses.map(a=>a.form).join(" \xB7 ")}`));n.headNouns.length>s.length&&o.push(f(` \u2026and ${n.headNouns.length-s.length} more \u2014 /terms --all lists them`)),o.push(f(' A shared word is not proof of a shared meaning: "billing history" and "history" are')),o.push(f(" different things. Nothing is flagged as wrong here.")),o.push("")}if(n.headings.length>0){o.push(` ${J("\u26A0",Ht.yellow)}Titles out of step with the rest of their kind`);for(let s of n.headings)o.push(` ${Ht.bold(s.title)} ${f(`\u2014 ${Xe(s.path,40)}`)}`),o.push(f(` the other ${s.peers} ${s.type} article${s.peers===1?"":"s"} look like "${s.example}"; this one starts ${qT(s.shape)}`));o.push("")}return r===0&&n.headNouns.length===0&&(o.push(` ${J("\u2713",Ht.green)}Every term is spelled one way, and every title matches its kind.`),o.push("")),o.push(f(' This compares spellings, not meanings: two different words for one thing (say "nav" and')),o.push(f(' "rail") look unrelated to it. Add the pair to your approved terms and every run enforces it.')),o.push(f(" Free \u2014 this read your articles and called nothing.")),o}function qT(e){return e==="gerund"?"with an -ing word":e==="how-to"?'with "How to"':"differently"}function ep(e,t,n){let o=n??wy(e),r=Jd(t),s=o.variance.find(w=>w.uses.some(k=>Jd(k.form)===r));if(!s)return{wrote:!1,lines:[`${J("\u2717",Ht.red)}"${t}" is not one of the terms with competing spellings. /terms lists them.`]};let i=yy(s);if(i)return{wrote:!1,lines:[`${J("\u2717",Ht.red)}That one cannot be recorded: ${i}.`,f(` The spellings in play are ${s.uses.map(w=>`"${w.form}"`).join(" and ")}.`)]};let a=s.uses.find(w=>Jd(w.form)===r).form,l=s.uses.filter(w=>w.form!==a).map(w=>w.form),d=UT(e);if(!d)return{wrote:!1,lines:[`${J("\u2717",Ht.red)}No project configuration here \u2014 run /init first.`]};let g={...d.terminologyGlossary??{}};for(let w of l)g[w]=a;return WT({...d,terminologyGlossary:g},e),{wrote:!0,lines:[`${J("\u2713",Ht.green)}"${a}" is now the approved spelling.`,f(` Added to your approved terms: ${l.map(w=>`"${w}" \u2192 "${a}"`).join(", ")}`),f(" Every run enforces it from now on, and /lint --fix corrects the others for free.")]}}async function by(e,t){let n=e.findIndex(s=>s==="--approve");if(n!==-1){let s=e[n+1];if(!s)return console.log(`${J("\u2717",Ht.red)}Name the spelling to approve, e.g. /terms --approve "drop-down".`),{kind:"continue",ownNext:!0};for(let i of ep(t.cwd,s.replace(/^["']|["']$/g,"")).lines)console.log(i);return{kind:"continue",ownNext:!0}}let o=e.includes("--all"),r=e.find(s=>!s.startsWith("--"));for(let s of Zd(t.cwd,{...r?{scope:r}:{},all:o}))console.log(s);return{kind:"continue",ownNext:!0}}re();import{readProjectConfig as VT,writeProjectConfig as ky,isAppType as YT,playbookSkillName as KT,detectAppType as $y}from"document360-engine";var vy=["web","cli","service","library"],zT=new Set(["web","cli"]);function tp(e){return zT.has(e)?`${KT(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function Ha(e,t){let n=t.cwd,o=VT(n);if(!o)return console.log(O("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let s=o.appType??$y(n);if(s){let i=o.appType?"set in config":"auto-detected";console.log(`${Z("Genre:")} ${s} (${i}) \u2014 ${tp(s)}`)}else console.log(H("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(f(`Set it: /genre <${vy.join("|")}> \xB7 revert to auto-detect: /genre auto`)),{kind:"continue"}}if(r==="auto"||r==="clear"){if(!o.appType)return console.log(f("Already on auto-detect (no genre set in config).")),{kind:"continue"};let{appType:s,...i}=o;ky(i,n);let a=$y(n);return console.log(q(`\u2713 Genre reset to auto-detect \u2014 now: ${a?`${a} (${tp(a)})`:"unclassified (no playbook)"}.`)),console.log(f(" Restarting the agent so the loaded playbook matches\u2026")),{kind:"clear"}}return YT(r)?(ky({...o,appType:r},n),console.log(q(`\u2713 Genre set to ${r} \u2014 ${tp(r)}.`)),console.log(f(" Restarting the agent so the playbook loads\u2026")),{kind:"clear"}):(console.log(O(`Unknown genre "${r}". Choose one of: ${vy.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}var xy={help:Ql,"?":Ql,clear:Yh,exit:Jl,quit:Jl,init:sc,mcp:Ni,push:na,publish:Em,audit:(e,t)=>hs({cwd:t.cwd,profileName:t.profileName}),discover:Nm,scope:jm,pull:Ym,resolve:Gm,convert:ug,write:Cg,draft:Eg,document:Ng,resume:Ig,rename:Lg,profile:_g,model:Ug,doctor:Rs,logs:Wh,workspace:qg,project:Vg,"allow-prod":Yg,login:Kg,logout:zg,screenshot:async(e,t)=>{let n=is(e);return n.mode==="capture"?sd(n.rest,t):n.mode==="annotate"?ud(n.rest,t):n.mode==="verify"?Xg(n.rest,t):n.mode==="checklist"?gr(e,t):Yi(e,t)},capture:sd,annotate:ud,"capture-setup":gr,devhints:of,inbox:mw,ask:ww,"catch-up":vw,comments:Tw,update:Ew,reset:Lw,lint:Cu,check:gg,"style-guide":Ua,review:py,reorder:hy,structure:ty,status:my,retire:gy,terms:by,genre:Ha,roadmap:wm,share:kw};function Ry(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}import{spawnSync as XT}from"node:child_process";import{recordAnalyzedCommit as QT,resolveActiveProfile as JT}from"document360-engine";function ZT(e){try{let t=XT("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8",timeout:1200}),n=(t.stdout||"").trim();return t.status===0&&n?n:null}catch{return null}}function Fs(e,t){try{let n=ZT(e);if(!n)return null;let o=JT(e,t);return QT(e,o.name,n)?n:null}catch{return null}}xn();var Cy="Or just tell me what to write or update.";function eA(e,t,n={}){let o=n.onlyScreenshots?"\u2713 Your writing is done \u2014 nothing is waiting to be written, reviewed, saved or taken live. Readers are seeing every article you have.":"\u2713 That\u2019s the full round trip \u2014 nothing is waiting to be written, reviewed, saved or taken live. Readers are seeing every article you have.";return n.listed?o:`${o}
425
-
426
- Optional from here: ${e} of your ${t} docs campaign step${ye(t)} ${e===1?"is":"are"} still open (/roadmap shows them).`}var tA="Screenshots are the only thing still open \u2014 a separate job, and none of it changes your text:",nA="Optional depth, when you want it:",oA="Writing",rA="Screenshots \u2014 a separate job from the writing";function sA(e,t){let n=t?`Press 1\u2013${e} to fill one in \u2014 nothing runs on its own.`:"Run one of the commands above when you want to.";return`Nothing is waiting${e>0?", and none of the above is owed":""}. ${e>0?`${n} `:""}I\u2019ll pick up new hints from your builder, or code that moved, next time you\u2019re in.`}var iA='\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 ye(e){return e===1?"":"s"}function aA(e,t){if(!e||!t)return!1;let n=o=>o.trim().replace(/\s+/g," ").toLowerCase();return n(e)===n(t)}function kr(e,t=0){let n=t>=2?` \xB7 1\u2013${t} to pick another`:"";return e.kind==="cmd"?`\u21E5 tab to run ${e.cmd}${n} \xB7 or just ask me anything\u2026`:e.kind==="answer"&&e.options>=2?`1\u2013${e.options} to answer \xB7 or just ask me anything\u2026`:null}function Py(e,t){return e.length===t.length&&e.every((n,o)=>n===t[o])}function Sy(e,t=150,n=1){let o=(e??"").replace(/\s+/g," ").trim();if(!o)return null;let r=/[.!?]\s+(?=["“'(A-Z])/g,s=o;for(let l=0;l<n;l++){let d=r.exec(o);if(!d)break;s=o.slice(0,d.index+1)}if(s.length<=t)return s;let i=s.slice(0,t),a=i.lastIndexOf(" ");return`${(a>t*.6?i.slice(0,a):i).replace(/[,;:]$/,"")}\u2026`}function $r(e){if(e.kind==="answer")return e.options>=2?`Answer above (1\u2013${e.options}), or say what you want instead.`:"Answer above, or say what you want instead.";let t=e.detail?` ${e.detail.replace(/\s*$/,"").replace(/([^.!?…])$/,"$1.")}`:"";return e.kind==="cmd"?`I\u2019d start with ${e.cmd} \u2014 ${e.reason}.${t}`:`Just tell me: \u201C${e.text}\u201D \u2014 ${e.reason}.${t}`}var qa={title:"What kind of product is this repo? (sets the doc-craft playbook \u2014 otherwise the docs stay generic)",lead:"Pick the genre below \u2014 one keypress, and it shapes everything I write.",exclusive:!0,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 lA(e,t){let n=[];if(e.sunsetEnv){let r=e.sunsetEnv,s=r.replacementProfile?`/profile ${r.replacementProfile}`:`/profile add ${r.replacement}`;n.push({key:"environment",bullet:`this repo publishes to the ${r.name} environment, which is being retired (${r.replacement} is the current one)`,lead:{kind:"cmd",cmd:s,reason:r.replacementProfile?`it switches to your ${r.replacement} profile (then /login if it asks)`:`it creates a ${r.replacement} profile and switches to it (then /login picks the project)`},picker:null,follow:null,tone:"warn"})}if(e.devhints!=="current"&&e.builderStarted){let r=e.devhintsToVersion?`v${e.devhintsToVersion}`:"a newer version",s=e.devhints==="stale"&&e.devhintsCompletedVersion?` (your builder is on v${e.devhintsCompletedVersion})`:"";n.push({key:"devhints",bullet:`dev\u2194docs protocol moved to ${r}${s} \u2014 your docs aren\u2019t blocked`,lead:{kind:"cmd",cmd:"/devhints",reason:`one paste updates your builder to ${r}`},picker:null,follow:"Also run /devhints when you get a second \u2014 your builder\u2019s protocol is behind.",tone:"warn"})}if(e.genreUnknown&&n.push({key:"genre",bullet:"the doc genre isn\u2019t set \u2014 I can\u2019t load the right doc-craft playbook yet",lead:null,picker:qa,follow:"Then pick the doc genre below (it sets the playbook I write with)."}),e.styleRules){let r=e.styleRules.articles;n.push({key:"styleRules",bullet:r>0?`the writing rules for these docs were never settled \u2014 and ${r} article${ye(r)} ${r===1?"is":"are"} already written to them`:"the writing rules for these docs aren\u2019t settled yet \u2014 worth answering before I write anything",lead:null,picker:{title:r>0?`Which writing rules should these docs follow? (${r} article${ye(r)} already written \u2014 changing this later means rewriting them)`:"Which writing rules should these docs follow? (this shapes every article I write)",lead:r>0?"Settle the writing rules below \u2014 one keypress. Keeping what you have is the usual answer once articles exist.":"Settle the writing rules below \u2014 one keypress, before I write anything to them.",exclusive:!0,options:e.styleRules.presets},follow:"Then settle the writing rules below \u2014 it shapes every article, and it gets dearer to change the longer it waits."})}if(e.discovery&&e.discovery.status!=="confident"){let r=e.discovery.openQuestions;e.discovery.status==="pending"?n.push({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/push steps)."}):r>0?n.push({key:"discovery",bullet:`product discovery is waiting on ${r} answer${ye(r)} 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."}):e.discovery.answersPending===0&&n.push({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 r=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",s=[];e.directives>0&&s.push(`${e.directives} owner directive${ye(e.directives)} waiting`);let i=e.discovery&&e.discovery.status!=="confident"?e.discovery.answersPending:0,a=i>0?` (${i} settle${i===1?"s":""} the product brief)`:"";e.pendingText&&s.push(`your builder left ${e.pendingText}${a}`),n.push({key:"catchup",bullet:s.join(`
427
- \u2022 `),lead:{kind:"cmd",cmd:"/catch-up",reason:r},picker:null,follow:"Then /catch-up clears what\u2019s queued for the docs.",dependsOn:["discovery"]})}if(e.openComments>0){let r=e.openComments;n.push({key:"comments",bullet:`${r} reviewer comment${ye(r)} waiting on your articles`,lead:{kind:"cmd",cmd:"/comments",reason:"it shows what reviewers marked up in the portal, then lets you take it an article at a time"},picker:null,follow:`Then /comments shows the ${r} reviewer comment${ye(r)} waiting on your articles.`})}if(e.conflicts>0){let r=e.conflicts;n.push({key:"resolve",bullet:`${r} article${ye(r)} changed both here and on Document360 \u2014 /push skips ${r===1?"it":"these"}, and an audit can't trust your local copy until ${r===1?"it is":"they are"} settled`,lead:{kind:"cmd",cmd:"/resolve",reason:"it walks each one with you \u2014 keep yours, take the portal's, or skip"},picker:null,follow:`Then /resolve settles the ${r} article${ye(r)} changed in both places (keep yours / take the portal's / skip).`})}if(e.behind>0){let r=e.behind;n.push({key:"audit",bullet:`${r} code change${ye(r)} 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 ${r} newer commit${ye(r)}.`,blockedBy:["resolve"]})}if(e.hasDocs&&e.pendingWrites>0){let r=e.pendingWrites;n.push({key:"write",bullet:`${r} planned article${ye(r)} still unwritten`,lead:{kind:"cmd",cmd:"/write",reason:"it finishes the articles already planned"},picker:null,follow:`Then /write finishes the ${r} planned article${ye(r)}.`,dependsOn:["genre","discovery","catchup","audit"]})}if(e.unreviewed>0){let r=e.unreviewed,s=Pe("/review","--blocked --fix",e.unreviewedScope);n.push({key:"review",bullet:`${r} article${ye(r)} not yet live ${r===1?"carries":"carry"} text no editor has read`,lead:{kind:"cmd",cmd:s,reason:"these were written by an AI \u2014 it reads each one and applies its fixes, and nothing can be sent up or taken live until it has"},picker:null,follow:`Then ${s} reviews the ${r} unreviewed article${ye(r)} \u2014 nothing reaches your readers until it has.`,dependsOn:["catchup","comments"]})}if(e.styleErrors>0){let r=e.styleErrors,s=Pe("/lint","--blocked --fix",e.styleErrorScope);n.push({key:"styleguide",bullet:`${r} article${ye(r)} not yet live break${r===1?"s":""} house style rules that block publishing`,lead:{kind:"cmd",cmd:s,reason:"finding them costs nothing and one pass corrects them in place \u2014 nothing can be sent up or taken live until it has"},picker:null,follow:`Then ${s} clears the style errors on ${r} article${ye(r)} \u2014 nothing reaches your readers until it has.`,dependsOn:["catchup","comments","review"]})}let o=e.shotsToAnnotate>0?{key:"annotate",bullet:`${e.shotsToAnnotate} screenshot${ye(e.shotsToAnnotate)} ${e.shotsToAnnotate===1?"has":"have"} been taken but ${e.shotsToAnnotate===1?"is":"are"} not finished \u2014 the callouts aren't drawn on, so ${e.shotsToAnnotate===1?"it cannot":"they cannot"} be published`,lead:{kind:"cmd",cmd:"/screenshot annotate",reason:"it draws the callouts on \u2014 no browser, about a second per picture"},picker:null,follow:`Then /screenshot annotate finishes the ${e.shotsToAnnotate} screenshot${ye(e.shotsToAnnotate)} already taken.`}:e.shotsToRecapture>0?{key:"annotate",bullet:`${e.shotsToRecapture} screenshot${ye(e.shotsToRecapture)} ${e.shotsToRecapture===1?"has":"have"} a plan for what to point at but no picture \u2014 the picture has to be taken again before anything can be drawn on it`,lead:{kind:"cmd",cmd:"/screenshot capture",reason:"it takes the picture again in a browser, and the callouts are drawn on straight after"},picker:null,follow:`Then /screenshot capture re-takes the ${e.shotsToRecapture} missing picture${ye(e.shotsToRecapture)}.`}:null;if(o&&e.localAhead>0&&n.push(o),e.localAhead>0){let r=e.localAhead;n.push({key:"publish",bullet:`${r} article${ye(r)} changed locally \u2014 ready to send to Document360`,lead:{kind:"cmd",cmd:"/push",reason:`it saves your ${r} local edit${ye(r)} to Document360 as drafts`},picker:null,follow:`Then /push saves your ${r} local edit${ye(r)} to Document360.`,dependsOn:["discovery","comments","audit","annotate"],blockedBy:["review","styleguide"]})}if(e.draftAhead>0){let r=e.draftAhead;n.push({key:"golive",bullet:`${r} article${ye(r)} ${r===1?"is":"are"} saved on Document360 but not live \u2014 your readers still see the previous version`,lead:{kind:"cmd",cmd:"/publish",reason:`it takes the ${r} draft${ye(r)} live to your readers \u2014 it lists them and asks first`},picker:null,follow:`Then /publish takes the ${r} draft${ye(r)} live \u2014 until it does, readers see the previous version.`,dependsOn:["comments"],blockedBy:["review","styleguide"]})}if(o&&e.localAhead===0&&n.push(o),e.hasDocs&&e.roadmap?.next){let r=e.roadmap,s=r.next,i=s.run?t?.scaleFor?.(s.run)??null:null,a=s.run?i:Sy(s.body),l=s.run?i??void 0:Sy(s.body,340,2)??void 0,d=`docs campaign: ${r.done} of ${r.total} step${ye(r.total)} done`,g=!!s.run&&aA(s.run,e.lastCommand);n.push(g?{key:"roadmap",bullet:`${d} \u2014 \u201C${s.title}\u201D is waiting on you
399
+ `)}function In(e){return`${J("\u2192",pt.blue)}Verifying ${e} new screenshot${e===1?"":"s"} (reading each image)\u2026`}var MC=(e,t=88)=>{let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n};function mr(e,t){if(t.length===0)return[];let n=ln(e).shots,o=[],r=[],s=[];for(let a of t){let l=n[a]?.review;l?l.verdict==="ok"?o.push(a):r.push({id:a,reason:l.reason??"no reason recorded",repaired:!!l.repaired}):s.push(a)}let i=[""];if(i.push(`${J("\u2714",pt.green)}${pt.green(`${o.length} verified`)}`+(r.length>0?` ${pt.magenta(`\u2691 ${r.length} flagged`)}`:"")+(s.length>0?` ${pt.yellow(`? ${s.length} not verified`)}`:"")+pt.gray(` ${t.length} shot${t.length===1?"":"s"} in this pass`)),r.length>0){let a=Math.max(...r.map(d=>d.id.length));for(let d of r)i.push(` ${pt.magenta(d.id.padEnd(a))} ${pt.gray(MC(d.reason))}`);let l=r.filter(d=>d.repaired).length;i.push(`${J("\u2192",pt.magenta)}Re-capture the ${r.length} flagged: ${pt.bold("/screenshot capture --failed")}`+(l<r.length?pt.gray(` (${r.length-l} still need${r.length-l===1?"s":""} a spec fix first)`):""))}return s.length>0&&i.push(`${J("\u26A0",pt.yellow)}No verdict recorded for ${s.slice(0,3).join(", ")}${s.length>3?`, +${s.length-3}`:""} \u2014 still awaiting verification. Run ${pt.bold("/screenshot verify")} again.`),i}async function ew(e,t){let n=t?.cwd??process.cwd(),o=io(n);o&&console.log(o);let r=_e(n),s=_C(e);if(s.mode==="single"){let a=r.find(l=>l.id===s.id);return a?a.state==="captured"?(console.log(`"${s.id}" has been taken but the callouts aren't drawn on yet \u2014 /screenshot annotate ${s.id} finishes it.`),{kind:"continue"}):["annotated","verified","rejected"].includes(a.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=Ss(r);if(i.length===0){let a=r.filter(w=>w.state==="verified").length,l=r.filter(w=>w.state==="rejected").length,d=r.filter(w=>w.state==="captured").length;return console.log(d>0?`${d} shot${d===1?" is":"s are"} taken but not drawn on yet \u2014 /screenshot annotate finishes ${d===1?"it":"them"}, then there'll be something to verify.`:l>0?`Nothing left to verify. ${l} shot${l===1?"":"s"} failed verification \u2014 re-capture with: /screenshot capture --failed`:a>0?`All ${a} captured shot${a===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"}}import{spawn as tw}from"node:child_process";var ed="d360-capture";function FC(e,t){if(t&&typeof e.pid=="number")try{process.kill(-e.pid,"SIGTERM");return}catch{}try{e.kill()}catch{}}function Ps(e){let t=process.platform==="win32",n=!t&&e.stdio==="pipe";return new Promise((o,r)=>{let s=t?tw(`${ed} ${e.args.join(" ")}`,{cwd:e.cwd,shell:!0,stdio:e.stdio==="inherit"?"inherit":["ignore","pipe","pipe"],env:{...process.env,NO_UPDATE_NOTIFIER:"1"}}):tw(ed,e.args,{cwd:e.cwd,shell:!1,detached:e.stdio==="pipe",stdio:e.stdio==="inherit"?"inherit":["ignore","pipe","pipe"],env:{...process.env,NO_UPDATE_NOTIFIER:"1"}}),i="";e.stdio==="pipe"&&(s.stdout?.on("data",l=>{i+=l.toString()}),s.stderr?.on("data",l=>{i+=l.toString()}));let a=()=>FC(s,n);e.signal?.addEventListener("abort",a,{once:!0}),s.on("error",l=>{if(e.signal?.removeEventListener("abort",a),l.code==="ENOENT"){o({exitCode:127,output:`${i}
400
+ ${ed}: command not found`.trim()});return}r(l)}),s.on("close",l=>{e.signal?.removeEventListener("abort",a),o({exitCode:l??1,output:i})})})}var VC=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function nd(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:VC(t),retryBlocked:n}:{mode:"single",id:t}:{mode:"picker"}}function Es(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("annotated"),...o("verified"),...o("rejected")].sort(),blocked:o("blocked"),broken:o("broken"),rejected:o("rejected"),rows:n}}function ow(e){let t=e.filter(s=>s.state==="spec"),n=e.filter(s=>s.state==="annotated"||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}),nr(o,t,"capture"),jc(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,a)=>i.id.localeCompare(a.id))){let i=s.state==="verified"?" \u2714 verified \u2014 re-capture":" \u25C8 to verify \u2014 re-capture";o.push({kind:"shot",action:"capture",label:s.id,ids:[s.id],depth:1,note:i})}return o}function od(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([...Tf(e).filter(r=>n.has(r)),...o])].sort()}function rd(e,t){let n=e.length;if(n===0)return null;let o=cs(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(`
401
+ `)}function YC(e,t){let n=BC(e)?.outputDir??HC;return qC(GC(e,n),t)}function sd(e,t,n,o){let r=YC(e,t);return(r.annotationsMtimeMs??0)>=o&&r.rawMtimeMs!==void 0?"captured":n===0?"skipped":"failed"}function rw(e){let t=/⊘[^\n—]*—\s*(.+)/.exec(e);return t?t[1].trim():null}var KC=/element is not (?:enabled|visible|stable|editable)|intercepts pointer events|outside of the viewport|element is not attached/i;function sw(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=>KC.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(`
402
+ `):id(e)}function id(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(`
403
+ `)}var zC=/^[A-Za-z0-9._-]+$/;function ad(e){return zC.test(e.id)?Ps({args:["capture",e.id],cwd:e.cwd,stdio:e.stdio,signal:e.signal}):Promise.reject(new Error(`Not a valid spec id: "${e.id}"`))}function iw(e,t=UC()){try{let n=JSON.parse(td(Ts(e,".d360-writer","capture.json"),"utf8").replace(/^/,"")),o=n.projectId;if(!o)try{o=JSON.parse(td(Ts(e,"package.json"),"utf8")).name}catch{}o||=WC(e);let r=Object.keys(n.profiles??{}),s=n.defaultProfile??(r.length===1?r[0]:r.includes("staging")?"staging":r[0]);return s?nw(Ts(t,".document360-capture","auth-states",o,`${s}.json`)):!0}catch{return!0}}function aw(e){return Ps({args:["auth","--auto"],cwd:e.cwd,stdio:"pipe",signal:e.signal})}function ld(e,t){return e===127||/is not recognized as an internal or external command|command not found/i.test(t)}function lw(e){try{let t=JSON.parse(td(Ts(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 fo(e){return nw(Ts(e,".d360-writer","capture.json"))}function cd(){return["Screenshot capture is not configured in this repo yet (no `.d360-writer/capture.json`). Set it up","conversationally, and 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, 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: 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`, adding/updating 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(`
404
+ `)}function cw(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(", ")}
405
+ /screenshot list --detail shows what each one needs`}function uw(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):As(r?.reason)!==As(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):Vi(r?.reason??"")!==Vi(o.detail??"")?n.blockedNewReason.push(o.id):n.blockedAsBefore.push(o.id))}return n}function As(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 dw(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?or(o.detail):"no reason recorded"}`)}function gr(e,t=2){return e.length<=t?e.join(" \xB7 "):`${e.slice(0,t).join(" \xB7 ")} \xB7 +${e.length-t}`}function pw(e,t){if(!t)return[];let n=[],o=(i,a,l,d)=>{a>0&&n.push({glyph:i,label:`${a} ${l}`,tail:d})};if(o("\u2713",e.newlyCaptured.length,"newly captured",gr(e.newlyCaptured)),o("\u2717",e.newlyBroken.length,"newly broken",gr(e.newlyBroken)),o("\u2192",e.repairedNowBlocked.length,"repaired",`no longer broken \u2014 only data stands in the way \xB7 ${gr(e.repairedNowBlocked)}`),o("\u2298",e.newlyBlocked.length,"newly blocked",gr(e.newlyBlocked)),o("\u2192",e.blockedNewReason.length,"blocked on something new",`an earlier step now passes \xB7 ${gr(e.blockedNewReason)}`),o("\u2192",e.brokeDifferently.length,"broken differently",`the previous cause is fixed \xB7 ${gr(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 hw(e){let t=e.results.filter(S=>S.outcome==="captured"),n=e.results.filter(S=>S.outcome==="skipped"),o=e.results.filter(S=>S.outcome==="failed"),r=e.unannotated??[],s=S=>S===1?"":"s";if(t.length+n.length+o.length===0)return null;let i=e.articles.length===1?`/push ${e.articles[0]}`:Ce("/push","--screenshots",Yt(e.articles)),a=e.ids.length===1?`/screenshot capture ${e.ids[0]}`:"/screenshot capture",l=o[0]?.id,d=[];o.length>0&&d.push({glyph:"\u2717",cmd:`/screenshot ${l}`,why:`re-author the ${o.length===1?"broken spec":`first of ${o.length} broken specs`} \u2014 re-running fails the same way`});let w=Ce("/screenshot annotate","",r.length===1?r[0]:void 0);r.length>0&&d.push({glyph:"\u25C8",cmd:w,why:`draw the callouts on ${r.length} shot${s(r.length)} \u2014 no browser, seconds; ${r.length===1?"it cannot":"they cannot"} publish until drawn`}),n.length>0&&d.push({glyph:"\u2298",cmd:"/screenshot list",why:`what to stage for the ${n.length} blocked shot${s(n.length)}`}),t.length>0&&r.length<t.length&&d.push({glyph:"\u2713",cmd:i,why:`embed the ${t.length-r.length} new PNG${s(t.length-r.length)}`});let m=Math.max(...d.map(S=>S.cmd.length));return{note:d.map(S=>`${S.glyph} ${S.cmd.padEnd(m)} ${S.why}`).join(`
406
+ `),cmd:o.length>0?`/screenshot ${l}`:r.length>0?w:t.length>0?i:a,tone:o.length>0||r.length>0?"warn":"info"}}function fw(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 ud(e,t){let n=t?.cwd??process.cwd(),o=nd(e);if(!fo(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:a}=Es(n,o.mode==="scope"?o.scope:void 0),l=od(n,a),d=(o.mode==="all"||o.mode==="scope")&&o.retryBlocked,w=o.mode==="single"?[o.id]:o.mode==="failed"?l:o.mode==="blocked"?i:o.mode==="picker"?r:[...r,...s,...d?i:[]];if(w.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(!d&&o.mode!=="single"&&o.mode!=="failed"&&o.mode!=="blocked"){let C=rd(a.filter(A=>A.state==="blocked"),"/screenshot capture --blocked");C&&console.log(C)}let m=Date.now(),$=[];for(let C of w){console.log(`\u25B6 ${C}`);try{let{exitCode:A}=await ad({cwd:n,id:C,stdio:"inherit"});$.push({id:C,outcome:sd(n,C,A,m)})}catch(A){if(A.code==="ENOENT")return console.log("d360-capture is not installed. Run: npm i -g document360-capture"),{kind:"continue"};$.push({id:C,outcome:"failed",detail:A.message})}}let S=C=>$.filter(A=>A.outcome===C).length;console.log(`\u2713 ${S("captured")} captured \xB7 \u2298 ${S("skipped")} skipped \xB7 \u2717 ${S("failed")} failed`);let R=$.filter(C=>C.outcome==="captured");return Oi(n,$.map(C=>({id:C.id,outcome:C.outcome,reason:C.detail,specSource:ao(n,C.id)})),new Date().toISOString()),R.length>0?(console.log(In(R.length)),{kind:"forward-to-agent",prompt:Qt(n,R.map(C=>C.id)),display:"/screenshot verify"}):{kind:"continue"}}import{readProjectConfig as XC,DEFAULT_OUTPUT_DIR as QC,resolveOutputDir as JC,shotArtifacts as ZC,annotationCurrent as eS}from"document360-engine";er();var mw="0.2.29";function Sa(e=dt()){return tr(e,mw)}function dd(e){let t=e.includes("--force")||e.includes("-f"),n=e.includes("--all")||e.includes("-a"),o=e.find(r=>!r.startsWith("-"));return n?{mode:"all",force:t}:o?o.includes("/")||o.includes("\\")||o.endsWith(".md")?{mode:"scope",scope:o.replace(/\\/g,"/").replace(/\/+$/,""),force:t}:{mode:"single",id:o}:{mode:"pending"}}function pd(e,t){let n=_e(e,t);return{pending:n.filter(o=>o.state==="captured").map(o=>o.id),done:n.filter(o=>o.state==="annotated"||o.state==="verified"||o.state==="rejected").map(o=>o.id),rows:n}}var tS=/^[A-Za-z0-9._-]+$/;function nS(e){if(!tS.test(e.id))return Promise.reject(new Error(`Not a valid spec id: "${e.id}"`));let t=["annotate",e.id,...e.force?["--force"]:[]];return Ps({args:t,cwd:e.cwd,stdio:e.stdio,signal:e.signal})}function oS(e,t,n,o){let r=JC(e,XC(e)?.outputDir??QC),s=ZC(r,t);return(s.annotatedMtimeMs??0)>=o?"annotated":n===0&&eS(s)?"skipped":"failed"}function hd(e){return e===null?"d360-capture is not installed, so there is nothing to draw with. Install it, then run /screenshot annotate again.":`The installed d360-capture (${e}) draws the callouts during the capture itself, so there is no separate step to run. Run /update to move to ${mw} or later, then /screenshot annotate becomes available.`}var Pa=8;function gw(e){let t=e.results.filter(o=>o.outcome==="failed"),n=e.results.filter(o=>o.outcome==="annotated");return t.length>0?{glyph:"\u2717",cmd:Ce("/screenshot capture","",t.length===1?t[0].id:void 0),why:`${t.length} could not be drawn \u2014 taking ${t.length===1?"it":"them"} again rebuilds the boxes`}:n.length===0?null:e.voidedVerdicts>Pa?{glyph:"\u25C8",cmd:Ce("/screenshot verify","",e.scope),why:`${e.voidedVerdicts} verified shots were re-drawn, so their verdicts no longer describe the picture on disk`}:{glyph:"\u25C8",cmd:Ce("/screenshot verify","",e.scope),why:`${n.length} picture${n.length===1?"":"s"} ready to check \u2014 no browser needed`}}async function fd(e){let t=Date.now(),n=[];for(let o of e.ids){if(e.signal?.aborted)break;e.onStart?.(o);try{let{exitCode:r,output:s}=await nS({cwd:e.cwd,id:o,...e.force?{force:!0}:{},...e.signal?{signal:e.signal}:{},stdio:"pipe"}),i=oS(e.cwd,o,r,t);n.push({id:o,outcome:i,...i==="failed"?{detail:rS(s)}:{}}),e.onDone?.(o,i)}catch(r){if(r.code==="ENOENT")return{results:n,cliMissing:!0};n.push({id:o,outcome:"failed",detail:r.message}),e.onDone?.(o,"failed")}}return{results:n}}async function md(e,t){let n=t?.cwd??process.cwd(),o=dd(e);if(!fo(n))return console.log("Screenshot capture is not set up in this repo yet. Run: d360-capture init"),{kind:"continue"};let r=dt();if(!Sa(r))return console.log(hd(r)),{kind:"continue"};let s=io(n);s&&console.log(s);let i=o.mode==="scope"?o.scope:void 0,{pending:a,done:l,rows:d}=pd(n,i),w=o.mode==="all"||o.mode==="scope"?o.force:!1,m=o.mode==="single"?[o.id]:w?[...a,...l]:a;if(m.length===0){let U=l.length>0;return console.log(U?`Every shot${i?` under ${i}`:""} is already drawn. Re-draw them anyway: /screenshot annotate --all --force`:"No shots have been taken yet \u2014 /screenshot capture takes them first."),{kind:"continue"}}let $=new Set(d.filter(U=>U.state==="verified").map(U=>U.id)),{results:S,cliMissing:R}=await fd({cwd:n,ids:m,force:w});if(R)return console.log("d360-capture is not installed. Run: npm i -g document360-capture"),{kind:"continue"};let C=U=>S.filter(O=>O.outcome===U).length;console.log(`\u2713 ${C("annotated")} annotated`+(C("skipped")?` \xB7 ${C("skipped")} already current`:"")+(C("failed")?` \xB7 \u2717 ${C("failed")} failed`:""));for(let U of S.filter(O=>O.outcome==="failed"))console.log(` \u2717 ${U.id}${U.detail?` \u2014 ${U.detail}`:""}`);let A=S.filter(U=>U.outcome==="annotated").map(U=>U.id);if(A.length===0)return{kind:"continue"};let D=A.filter(U=>$.has(U)).length;if(D>Pa)return console.log(`\u26A0 ${D} verified shots were re-drawn, so their verdicts no longer describe the picture on disk.
407
+ Check them when you're ready: ${Ce("/screenshot verify","",i)}`),{kind:"continue"};let N=A.filter(U=>!$.has(U)||D>0);return N.length===0?{kind:"continue"}:(console.log(In(N.length)),{kind:"forward-to-agent",prompt:Qt(n,N),display:"/screenshot verify"})}function rS(e){return e.split(/\r?\n/).map(n=>n.trim()).filter(n=>n.length>0&&!/^[▶✓↕]/.test(n)).at(-1)}re();import{existsSync as sS}from"node:fs";import{join as iS}from"node:path";import{builderChannelWired as aS,driftedAnchors as lS,readTestidRequests as cS,testidHandoffPrompt as uS,testidRequestPaths as dS,writerDir as pS}from"document360-engine";async function wr(e,t){let n=t?.cwd;if(n){let r=hS(n);if(r){for(let s of r)console.log(s);return{kind:"continue",ownNext:!0}}}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.","","This run is also the RE-VERIFY pass for open selector requests: for every CAPTURE-TODO anchor, check the","snippet is still in its named file (an unrelated refactor can invalidate it with nobody touching the spec).","Where it is gone, re-locate the element and rewrite that CAPTURE-TODO with a current anchor and line.","or set anchorVerified:false when you cannot confirm it. /screenshot list --detail names the drifted ones."].join(`
408
+ `),display:"/screenshot checklist"}}function hS(e){let t;try{t=_e(e)}catch{return null}let n=sS(iS(pS(e),"capture.json")),o=t.some(i=>i.state!=="placeholder");if(n||o)return null;let r=t.length,s=new Set(t.map(i=>i.file)).size;return r===0?[`${J("\u25CB",f)}No screenshots are planned yet, so there is nothing to stage.`,f(" A screenshot is planned by the article that needs it. /write adds the placeholders as it writes.")]:[`${J("\u25CB",f)}${r} screenshot${r===1?"":"s"} planned across ${s} article${s===1?"":"s"} \u2014 none captured, none with a spec, and no capture setup yet.`,f(" There is nothing to stage from yet: a checklist is built from what each spec needs, and no specs exist."),f(" /screenshot author writes the specs. Come back to /screenshot checklist once they exist and it will"),f(" tell you what data to stage and which test ids your developers still owe you."),"",f(" Free \u2014 this read your files and called nothing.")]}var ww="-".repeat(64);function yw(e){let t=cS(e);if(t.length===0)return null;let{mdRel:n}=dS(e),o=t.length,r=new Set(t.map(w=>w.file).filter(Boolean)).size,s=`${o} data-testid attribute${o===1?"":"s"}`,i=`${r} source file${r===1?"":"s"}`,a=uS(e,o),l=lS(t).length,d=l>0?[` \u26A0 ${l} of ${l===1?"them quotes":"them quote"} code that has changed since \u2014 still likely right,`,` but ${l===1?"it says":"they say"} so, and ${l===1?"asks":"ask"} to be found by description instead.`]:[];return aS(e)?{prompt:a,lines:[`\u{1F4CB} Developer hand-off \u2014 ${s} requested across ${i}.`,...d," Left in your builder's inbox: their coding agent is told about it at its next session, so",` there is nothing for you to relay. Detail: ${n}`]}:{prompt:a,lines:[`\u{1F4CB} Developer hand-off \u2014 ${s} requested across ${i}.`,...d,"\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."," (Run /devhints once and requests like this reach your builder on their own.)","",ww,a,ww]}}xn();re();import{listOpenForDocs as fS,readProjectConfig as mS}from"document360-engine";function gd(e){try{return fS(e).length}catch{return 0}}function wd(){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: 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, setting 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: 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; 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(`
409
+ `)}async function bw(e,t){let n=t?.cwd??process.cwd();return mS(n)?gd(n)===0?(console.log(f("Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)")),{kind:"continue"}):{kind:"forward-to-agent",prompt:wd(),display:"/inbox"}:(console.log(_("No d360-writer config here. Run /init first.")),{kind:"continue"})}re();import{askBuilder as gS,openGapQuestions as kw,readProjectConfig as wS}from"document360-engine";function Ns(e){try{return kw(e).length}catch{return 0}}function yd(e,t){let n=[`\u2713 Question filed for your developers: .d360-writer/messages/${e}`," It is committed and pushed with your docs, so it reaches them wherever they work. Their answer comes"," back the same way, and /inbox folds it into the article for you."];return t>1&&n.push(` ${t} of your questions are now waiting for an answer.`),n}function bd(e){let t=["Ask your developers something the code cannot tell you: why a feature exists, when to use it, what it","affects, or whether it can be undone.",""," /ask I can document how a refund works, but not whether it can be reversed or who should approve it","","The question is written to your docs folder and travels to them with your next save. You do not have to","stop working: keep writing what you can ground, and /inbox folds the answer in when it arrives."];if(e.length>0){t.push("",`Still waiting on ${e.length} question${e.length===1?"":"s"}:`);for(let n of e.slice(0,5))t.push(` \xB7 ${n.subject.replace(/^\[gap\]\s*/,"")}`);e.length>5&&t.push(` \xB7 \u2026and ${e.length-5} more`)}return t}async function $w(e,t,n){let o=t?.cwd??process.cwd();if(!wS(o))return console.log(_("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e.join(" ").trim();if(r===""){for(let s of bd(kw(o)))console.log(s.startsWith(" \xB7")?f(s):s);return{kind:"continue",ownNext:!0}}try{let s=gS(o,{question:r,...n?{article:n}:{}}),i=Ns(o);for(let a of yd(s.file,i))console.log(a.startsWith("\u2713")?q(a):f(a))}catch(s){console.log(H(`Could not file the question: ${s.message}`))}return{kind:"continue",ownNext:!0}}re();import{listOpenHints as RS,listOpenForDocs as CS,listOpenDirectives as SS,readProjectConfig as Cw,computeSyncStatus as PS,planPull as TS,applyPull as AS,planImport as ES,applyImport as NS,pullDocsUpdates as DS,handoffAvailable as jS,readProductBriefState as IS,readDiscoveryQueue as LS}from"document360-engine";re();import{readProjectConfig as yS,writeProjectConfig as vw,reconcileDocsGit as bS,pullDocsUpdates as kS,probeGitState as $S,resolveGitHandoff as xw,handoffAvailable as vS}from"document360-engine";var Ds=e=>e===1?"":"s";function Ln(e,t){let n=o=>{let r=(o??"").split(`
410
+ `).map(s=>s.trim()).filter(Boolean).slice(-1)[0];return r?` \u2014 ${r}`:""};switch(e){case"no-git":return"This folder is not a git repository, so there is nowhere to share to. Your docs are still saved on this machine.";case"detached-head":return"This repo is not on a branch right now. Ask your builder to check out a branch, then run /share.";case"mid-operation":return"A merge or rebase is in progress here. Finish or cancel it first, then run /share.";case"no-upstream":return"This branch has no remote yet, so there is nowhere to send your work. Ask your builder to run: git push -u origin HEAD";case"disabled":return"Sharing is switched off for this repo. Turn it on: /share on";case"diverged":return"Your work and your builder's have both moved on, so they can't be combined automatically. Your work is committed and safe \u2014 ask your builder to merge the branch.";case"rejected":return"Someone pushed to this branch first, so your work could not be sent. It IS committed and safe \u2014 try /share again in a moment, or ask your builder to merge the branch.";case"auth":return"Git could not sign in to the remote. Ask your builder to set up your git credentials, then run /share.";case"network":return"Could not reach the remote. Check your connection, then run /share again.";case"hook-failed":return`This repo's own commit checks rejected the change${n(t)}. Ask your builder to take a look \u2014 your docs are safe on this machine.`;case"failed":return`Git could not finish the share${n(t)}. Your docs are safe on this machine \u2014 run /share to try again, or show this line to your builder.`}}function Ta(e,t){let n=xw(t);if(!n.commit)return[{tone:"info",text:"Sharing: off \u2014 d360-writer leaves its work for your coding agent to commit."},{tone:"info",text:"Turn it on: /share on"}];let o=$S(e);if(!o)return[{tone:"info",text:"Sharing: unavailable \u2014 this folder is not a git repository."}];if(!o.upstream)return[{tone:"warn",text:J("\u26A0")+`This branch (${o.branch??"detached"}) has no remote, so your work can't reach your team yet.`},{tone:"info",text:"Ask your builder to run: git push -u origin HEAD"}];let r=n.push===!0?"on":n.push==="unconfirmed"?"not set up yet":"off",s=[{tone:"info",text:`Sharing: ${o.branch} \u2192 ${o.upstream} \xB7 saving: on \xB7 sending: ${r}`}];return o.ahead>0?s.push({tone:"warn",text:J("\u26A0")+`${o.ahead} change${Ds(o.ahead)} not shared yet \u2014 run /share`}):s.push({tone:"ok",text:J("\u2713")+"Everything is shared with your team."}),s}function kd(e,t,n){vw({...t,gitHandoff:{commit:n,push:n}},e);let o=n?{tone:"ok",text:J("\u2713")+"Sharing on \u2014 d360-writer will save and send its own work from now on."}:{tone:"ok",text:J("\u2713")+"Sharing off \u2014 d360-writer will leave its work for your coding agent to commit."};return n?[o,...Ta(e,{...t,gitHandoff:{commit:!0,push:!0}})]:[o]}async function Aa(e,t){let n=[],o=xw(t);if(!o.commit)return{lines:[{tone:"info",text:Ln("disabled")}],changed:!1};let r=t;o.push==="unconfirmed"&&vS(e,t)&&(r={...t,gitHandoff:{commit:!0,push:!0}},vw(r,e),n.push({tone:"info",text:"Sharing is now set up for this repo \u2014 d360-writer will keep doing this automatically."}));let s=await kS(e);if(s.ok&&s.pulled>0){let d=[s.newHints>0?`${s.newHints} new hint${Ds(s.newHints)}`:null,s.newMessages>0?`${s.newMessages} new message${Ds(s.newMessages)}`:null].filter(Boolean);n.push({tone:"ok",text:J("\u2B07")+`Got your builder's latest${d.length?` \u2014 ${d.join(", ")}`:""}.`})}else!s.ok&&s.reason!=="no-upstream"&&s.reason!=="no-git"&&n.push({tone:"warn",text:J("\u26A0")+Ln(s.reason,s.detail)});let i=await bS(e,r);if(i.commit&&!i.commit.ok)return n.push({tone:"warn",text:J("\u26A0")+Ln(i.commit.reason,i.commit.detail)}),{lines:n,changed:!1};let a=i.commit?.ok?i.commit.committed.length:0;if(a>0&&n.push({tone:"ok",text:J("\u2713")+`Saved ${a} change${Ds(a)} to the docs folder.`}),i.push&&!i.push.ok)return n.push({tone:"warn",text:J("\u26A0")+Ln(i.push.reason,i.push.detail)}),{lines:n,changed:a>0};let l=i.push?.ok?i.push.pushed:0;return l>0?n.push({tone:"ok",text:J("\u2B06")+`Shared ${l} change set${Ds(l)} with your team.`}):a===0&&(s.ok&&s.pulled===0)?n.push({tone:"ok",text:J("\u2713")+"Everything is already shared with your team."}):a>0&&!i.push&&n.push({tone:"info",text:"Saved on this machine only. /share on lets d360-writer send it to your team too."}),{lines:n,changed:a>0||l>0||s.ok&&s.pulled>0}}var xS={ok:q,info:Re,warn:H,error:_};async function Rw(e,t){let n=t.cwd,o=yS(n);if(!o)return console.log(_("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase(),s=a=>{for(let l of a)console.log(xS[l.tone](l.text))};if(r==="status")return s(Ta(n,o)),{kind:"continue"};if(r==="on"||r==="off")return s(kd(n,o,r==="on")),{kind:"continue"};if(r)return console.log(_(`Unknown option "${r}". Use /share, /share status, /share on, or /share off.`)),{kind:"continue"};console.log(f("Exchanging work with your team\u2026"));let{lines:i}=await Aa(n,o);return s(i),{kind:"continue"}}function pn(e){let t=0,n=0,o=0,r=0;try{t=RS(e).length}catch{}try{let s=CS(e);n=s.filter(i=>i.kind==="request").length,o=s.filter(i=>i.kind==="answer").length}catch{}try{r=SS(e).length}catch{}return{hints:t,requests:n,answers:o,directives:r}}async function vd(e){let t=Cw(e);if(!t)return[];if(!jS(e,t))return[];let n=await DS(e);if(n.ok){if(n.pulled===0)return[];let o=[n.newHints>0?`${n.newHints} new hint${n.newHints===1?"":"s"}`:null,n.newMessages>0?`${n.newMessages} new message${n.newMessages===1?"":"s"}`:null].filter(Boolean);return[{tone:"ok",text:`\u2B07 Got your builder's latest${o.length?` \u2014 ${o.join(", ")}`:""}.`}]}return n.reason==="no-upstream"||n.reason==="no-git"?[]:[{tone:"warn",text:`\u26A0 Couldn't get your builder's latest first \u2014 ${Ln(n.reason,n.detail)}`}]}function Ea(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 xd(e){let t=Ea(e);return t?`Catching up on ${t}\u2026`:"Nothing queued from your builder \u2014 checking Document360 for reviewer comments and feedback\u2026"}function Na(e){let t=Ea(e.queued);return t?{tone:"warn",note:`${J("\u26A0")}That run finished without writing anything, and ${t} ${e.queued.hints+e.queued.requests+e.queued.answers+e.queued.directives===1?"is":"are"} still queued \u2014 nothing was lost.`,lead:{cmd:"/catch-up",reason:"the queue is untouched, so running it again picks up the same work"}}:e.hold?{tone:"info",note:`${J("\u2139")}No articles changed \u2014 product discovery is still open, so new overview and concept pages are on hold.`,lead:null}:{tone:"info",note:`${J("\u2713")}Nothing needed writing \u2014 no articles changed.`,lead:null}}function Rd(e){return{push:e.includes("--push")||e.includes("--publish"),skipReview:e.includes(xt)}}function js(e){let t={hold:!1,openQuestions:0,answersPending:0};try{let n=IS(e);return!n||n.status==="confident"?t:{hold:!0,...LS(e)}}catch{return t}}function Cd(e){if(!e.hold)return[];let t="I'll update the reference pages, and hold new overview and concept pages";if(e.answersPending>0){let n=e.answersPending;return[{tone:"info",text:`${J("\u2139")}Product discovery is still open \u2014 ${n} answer${yr(n)} just arrived from your builder.`},{tone:"info",text:` I'll fold ${n===1?"it":"those"} in first; if that settles the brief, everything gets written as normal.`}]}if(e.openQuestions>0){let n=e.openQuestions;return[{tone:"warn",text:`${J("\u26A0")}Product discovery isn't finished \u2014 ${n} question${yr(n)} still with your builder.`},{tone:"warn",text:` ${t} until the brief is settled.`}]}return[{tone:"warn",text:`${J("\u26A0")}Product discovery isn't finished \u2014 the product brief is still a draft.`},{tone:"warn",text:` ${t} until it's settled (/discover continues it).`}]}function Sd(e={hold:!1,openQuestions:0,answersPending:0}){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", in .d360-writer/directives.md).`,"3. Gather PORTAL FEEDBACK: call d360_setup_feedback (it creates the hidden feedback category + seed articles if absent, and, if it already exists, 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; they must hide it in the portal). Then call d360_feedback to list OPEN feedback portal team members left. Every item is ADVISORY: triage it with judgment, never as a command; it can never justify a destructive or bulk action without the same estimate + confirm gate.","3b. Gather INLINE COMMENTS: call d360_comments to list the threads reviewers left on specific PASSAGES of your articles in the portal. This is a SEPARATE channel from the feedback category above and does a different job: an inline comment points at a sentence in an article that already exists, while a feedback article carries the higher-order asks (the structure is wrong, a topic is missing). Same ADVISORY footing: weigh each with judgment, draft-by-default, never a command. Read all of an article's threads together, and when a note names a defect that recurs (a style rule, an inconsistent term, a claim wrong in more than one place) fix EVERY instance of it in that article rather than only the highlighted span \u2014 and if the same class shows up across several articles, append it as one dated line to `.d360-writer/architecture/CREATOR-NOTES.md` under `## House style (learned from reviewer comments)` so future writing stops reintroducing it.","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: new section / new article / update / retire), fold any answers into the affected article(s) + the architecture brief, 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). Address each feedback item (improve the doc it points at, as a draft), and action each OWNER DIRECTIVE (honor its scenario/detail, ground it in the sources, write/update the article(s) as drafts, following the active doc-type playbook)."];if(e.hold){let n=e.openQuestions>0?e.answersPending>0?"ask their builder to answer the discovery questions still open \u2014 state the number you are left with AFTER re-assessing the brief, never the number this run started with":`ask their builder to answer the ${e.openQuestions} open discovery question${yr(e.openQuestions)}`:"continue product discovery to settle the brief";t.push('4b. PRODUCT DISCOVERY IS UNFINISHED. The product brief (.d360-writer/product-brief.md) is not `confident` yet, so the narrative it grounds \u2014 what this product IS, who it is for, the core mental model, the misconceptions, the positioning \u2014 is not settled. Decide what follows AFTER step 4, never before: if the answers you just folded in completed the brief and you flipped it to `confident`, this instruction and 4c are VOID \u2014 write everything as normal. Otherwise HOLD the articles whose shape or framing would change once the brief is confident (overview/introduction, concept and explanation pages, getting-started, positioning, "who it is for") and write everything else normally \u2014 a changed flag, a new subcommand, a corrected behaviour, a deprecation or a screenshot on an EXISTING reference page does not need the brief. The test for each candidate article: would you rewrite this page after reading a finished brief? If yes, hold it; if no, write it.',`4c. A HELD item MUST stay queued. Do NOT stamp its hint consumed, do NOT mark its message done, and do NOT flip its directive to done in step 7 \u2014 the open hint IS the queue, so stamping one you did not write means that article is never written at all. In your closing summary, name every page you held in plain words, say their hints stay queued so nothing is lost, and give exactly one next step: ${n}.`)}return t.push("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 LOCAL loop (bookkeeping in the repo; nothing here is visible to a reviewer):"," \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), including a step whose work you can verify an EARLIER session already completed but left unstamped, and append a step (d360_roadmap_add, with its run: command) for real new campaign work this run revealed; never delete existing steps;"," \u2022 for the Creator-notes feedback item (is_creator_notes:true): do NOT reply in it; 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; 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.)","10. NOW answer the people who asked, AFTER the push (steps 8-9), never before. A reviewer reads your reply in the portal and then looks at the article to check it, so replying first promises a change they cannot see. For anything whose push failed, do NOT reply on it; leave it outstanding and report it."," \u2022 for each INLINE COMMENT you actioned: call d360_comment_respond with its comment_id + article_id and a `reply` saying in plain words what you changed \u2014 in the reviewer's terms, mentioning where you applied the same fix more widely. Do NOT pass `resolve`: replying is your job, closing the thread is theirs, and they can only decide it is settled after seeing the change (your answer is recorded either way, so it will not come back at you). NEVER edit the reviewer's own comment text;"," \u2022 for each portal feedback item you actioned: append a short note at the BOTTOM of that feedback article via d360_update_article: `**d360-writer response:** \u2713 actioned in <article> (<date>)` (or `declined: <reason>`), NEVER overwriting the person's own text, then call d360_feedback_done(article_id, resulting_articles)."),t.push("Leave everything as DRAFTS for review; do not publish live. Publishing is a separate, reviewed step: articles you write here have not been read by an editor yet, so making them visible to readers is never part of this run. Tell the user what is waiting as a draft.",'Do NOT end with slash commands or a "what to do next" line. The tool prints the next step itself, scoped to what this run changed, and a second suggestion from you competes with it (yours will be the broader, more expensive one, because you cannot see how much was touched). Report what you did and stop.'),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, just plain sentences about what changed and what is worth their attention."),t.join(`
411
+ `)}var OS={status:PS,plan:TS,apply:AS,planImport:ES,applyImport:NS};async function Pd(e,t=OS){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 $d=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,yr=e=>e===1?"":"s";function Td(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=[];e.pulled.length&&t.push(`\u2713 Pulled ${e.pulled.length} portal edit${yr(e.pulled.length)} into local: ${$d(e.pulled)}`),e.imported.length&&t.push(`\u2713 Imported ${e.imported.length} new portal article${yr(e.imported.length)} into local drafts: ${$d(e.imported)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${yr(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${$d(e.conflicts)}`);for(let n of e.failed.slice(0,3))t.push(`\u26A0 ${n.path}: ${n.error}`);return e.failed.length>3&&t.push(`\u26A0 \u2026and ${e.failed.length-3} more left for /pull.`),t}async function Sw(e,t){let n=t?.cwd??process.cwd();if(!Cw(n))return console.log(_("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=He(n,t?.profileName);if(!o.ok)return console.log(_(o.reason)),{kind:"continue"};let{push:r}=Rd(e);for(let a of await vd(n))console.log(a.tone==="ok"?q(a.text):H(a.text));console.log(f("Reconciling with Document360 (pulling any portal changes)\u2026"));let s=await Pd({cwd:n,profileName:t?.profileName});for(let a of Td(s))console.log(a.startsWith("\u2713")?q(a):a.startsWith("\u2139")?f(a):H(a));let i=js(n);for(let a of Cd(i))console.log(a.tone==="warn"?H(a.text):f(a.text));return console.log(f(xd(pn(n)))),{kind:"forward-to-agent",prompt:Sd(i),display:`/catch-up${r?" --push":""}`}}re();import{resolveActiveProfile as WS,resolveProjectId as BS,loadProfileMap as HS,readCommentLedger as GS,isCommentOpen as qS,saveOpenCommentCount as VS,loadCommentSweepMemory as YS,recordCommentSweep as KS,planCommentSweep as zS,sweepOpenComments as XS,loadUserNames as QS,writeReviewerNotes as JS,sweptFromResult as ZS,needsFullArchivePass as eP,reviewerNotesPath as tP,commentHtmlToText as Pw,annotatedText as nP,readProjectConfig as oP,loadPortalLabels as rP,portalBreadcrumb as Ed,portalCategoryPath as sP,resolveModelForOperation as iP,runPartitioned as aP,snapshotArticles as lP,EMPTY_PORTAL_LABELS as cP}from"document360-engine";import Ae from"picocolors";import{CONTENT_CAP_VERSION as _S,stampArticles as MS,articlesChangedSince as FS,docsRootOf as US}from"document360-engine";function mo(e,t,n="",o){let r=[];try{r=FS(e,t)}catch{return{changed:[],cta:null}}if(r.length===0)return{changed:[],cta:null};try{MS(e,r,{writtenCap:_S,reviewedCap:0,checkedCap:0})}catch{}let s=US(e),i=w=>{let m=w.replace(/\\/g,"/");return m.startsWith(`${s}/`)?m.slice(s.length+1):m},a=Yt(r.map(i)),l=r.length,d=a?"/push":"/push --all";try{return{changed:r,cta:Bt(e,{text:`${n}${l} article${l===1?"":"s"} updated \u2014 ${d} saves ${l===1?"it":"them"} to Document360 as ${l===1?"a draft":"drafts"}.`,cmd:d},n,a,o)}}catch{return{changed:r,cta:null}}}var Aw=300,Is=3;function uP(e,t){let n=Di(e).toLowerCase(),o=t.trim().replace(/\\/g,"/").replace(/^\/+|\/+$/g,"").toLowerCase();if(!o||n===o||n.endsWith(`/${o}`))return!0;let r=n.split("/").pop()??n;return r.startsWith(`${o}-`)||r===o||Rn(n).toLowerCase()===o}async function Da(e,t,n={}){let o=WS(e,t),r={profile:o.name,connection:o.connection,projectId:o.project.projectId,projectName:o.project.projectName},s=BS(r,o.project.projectId),i=HS(e,o.name);if(!i)return{threads:[],answered:[],labels:cP,scanned:0,failed:[],truncated:0,skipped:0,archived:!1};let a=GS(e,o.name),l=new Set(Object.values(a).map(z=>z.articlePath).filter(z=>!!z)),d=Object.keys(a).length===0||l.size>0,w=n.articleIds?.length?new Set(n.articleIds):null,m=!!(w||n.path||n.scope),$=Object.entries(i.articles).filter(([,z])=>!!z.id).filter(([z,de])=>w?w.has(de.id):n.path?z.replace(/\\/g,"/")===n.path.replace(/\\/g,"/"):n.scope?uP(z,n.scope):!0).map(([z,de])=>({articleId:de.id,path:z,title:ji(e,z),answered:m||(d?l.has(z):!0)})),S=$.slice(0,Aw),R=await rP(r,s,o.project.workspaceId,{cwd:e,profile:o.name}),C=m||n.full?{read:S,skipped:[]}:zS(S,{live:R.live,stateOf:z=>R.articles.get(z),memory:YS(e,o.name),alwaysRead:new Set($.filter(z=>l.has(z.path)).map(z=>z.articleId))}),A=o.project.languageCode,D=eP(e)||!!n.full,N=await XS(r,s,C.read,{isOpen:(z,de)=>qS(a,z.id??"",de,z),...A?{langCode:A}:{},...n.onProgress?{onProgress:n.onProgress}:{},...D?{includeResolved:D}:{}}),U=N.threads.length>0||N.answered.length>0?await QS(r,s):new Map,O=JS(e,ZS(N.threads,N.answered,z=>Ed(R,z)),{userNames:U,ourReplyIds:Object.values(a).flatMap(z=>z.replyIds??[]),...D?{completeFor:C.read.filter(z=>!N.failed.some(de=>de.articleId===z.articleId)).map(z=>z.articleId)}:{}});m||VS(e,o.name,N.threads.length);let Q=new Map;for(let z of[...N.threads,...N.answered])Q.set(z.articleId,(Q.get(z.articleId)??0)+1);return KS(e,o.name,{live:R.live,read:C.read.map(z=>z.articleId),failedIds:N.failed.map(z=>z.articleId),threadCounts:Q,latestVersionOf:z=>R.articles.get(z)?.latestVersion}),{threads:N.threads,answered:N.answered,labels:R,scanned:N.scanned,failed:N.failed,truncated:Math.max(0,$.length-S.length),skipped:C.skipped.length,archived:O}}function dP(e,t=96){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n}var Tw=500;function pP(e){let t=nP(e.comment);if(!t)return"a passage";let n=t.replace(/\s+/g," ").trim();if(n.length<=Tw)return e.comment.commented_text_truncated?`\u201C${n}\u2026\u201D
412
+ (Document360 sends the first 500 characters of a highlight)`:`\u201C${n}\u201D`;let o=n.slice(0,Tw).trimEnd(),r=n.length-o.length;return`\u201C${o}\u2026\u201D
413
+ (+${r} more character${r===1?"":"s"}${e.comment.commented_text_truncated?", and Document360 caps a highlight at 500":""})`}function hP(e,t){let n=sP(t,e.articleId);return n.length>0?n.join(" \u203A "):e.path?Rn(e.path):""}function fP(e,t){return t.articles.get(e.articleId)?.title?.trim()||e.title||(e.path?is(e.path):e.articleId)}function mP(e,t){return Ed(t,e.articleId,{category:e.path?Rn(e.path):null,title:e.title??(e.path?is(e.path):null)})??e.path??e.articleId}function go(e,t){let n=new Map;for(let o of e){let r=n.get(o.articleId);r||(r={articleId:o.articleId,path:o.path,category:hP(o,t),title:fP(o,t),label:mP(o,t),threads:[]},n.set(o.articleId,r)),r.threads.push(o)}return[...n.values()].sort((o,r)=>o.category.localeCompare(r.category)||o.title.localeCompare(r.title))}var gP=100,wP=120,Ew=(e,t)=>Math.max(40,Math.min(e??96,t));function Nw(e){let t=s=>s===1?"":"s",n=new Set(e.threads.map(s=>s.articleId)).size,o=e.answered.length,r=[`${e.threads.length} open`,`${n} article${t(n)}`];return o>0&&r.push(`${o} answered, awaiting reviewer`),r.push(e.skipped>0?`${e.scanned} of ${e.scanned+e.skipped} articles re-read`:`${e.scanned} checked`),`${Ae.bold("Reviewer comments")} ${r.join(` ${Ae.gray("\xB7")} `)}`}function Ad(e){let t=[],n=o=>o===1?"":"s";if(e.skipped>0&&t.push(Ae.gray(` ${e.skipped} article${n(e.skipped)} weren\u2019t re-read \u2014 nobody has drafted or commented on them since your last check, so they can\u2019t have new comments. /comments --full reads every one.`)),e.failed.length){t.push(`${J("\u26A0",Ae.yellow)}${e.failed.length} article${n(e.failed.length)} couldn\u2019t be checked this time \u2014 they may have comments too:`);for(let o of e.failed.slice(0,5)){let r=Ed(e.labels,o.articleId,{title:o.title})??o.title??o.articleId;t.push(` ${Ae.gray(`${r} \u2014 ${dP(o.error,60)}`)}`)}e.failed.length>5&&t.push(` ${Ae.gray(`+${e.failed.length-5} more`)}`),t.push(Ae.gray(" Run /comments again to retry them."))}return e.truncated&&t.push(`${J("\u26A0",Ae.yellow)}Checked the first ${Aw} articles; ${e.truncated} not checked this run.`),e.archived&&(e.threads.length>0||e.answered.length>0)?t.push(Ae.gray(` Everything reviewers have written is kept in ${tP(".").replace(/\\/g,"/").replace(/^\.\//,"")} \u2014 it outlives a rewrite.`)):!e.archived&&(e.threads.length>0||e.answered.length>0)&&t.push(`${J("\u26A0",Ae.yellow)}Couldn\u2019t write the reviewer-notes file, so Document360 is still the only copy of these notes.`),t}function Ls(e,t={}){let n=[],o=a=>a===1?"":"s",r=e.answered.length,s=()=>{if(!(!t.showAnswered||r===0)){n.push(` ${Ae.gray(`Answered, waiting on the reviewer (${r})`)}`);for(let a of go(e.answered,e.labels))n.push(` ${Ae.gray(`${a.label} \u2014 ${a.threads.length} thread${o(a.threads.length)}`)}`);n.push("")}};if(e.threads.length===0){let a=r>0?` ${Ae.gray("\xB7")} ${r} answered, awaiting reviewer`:"",l=e.scanned+e.skipped;return n.push(e.skipped>0?`${J("\u2713",Ae.green)}No open reviewer comments in the ${e.scanned} article${o(e.scanned)} checked ${Ae.gray("\xB7")} ${e.skipped} of ${l} not checked${a}`:`${J("\u2713",Ae.green)}No open reviewer comments across ${e.scanned} article${o(e.scanned)}.${a}`),r>0?(n.push(Ae.gray(` Those ${r} are answered and left open on purpose \u2014 the reviewer closes them once they\u2019ve checked the change.`)),t.showAnswered||n.push(Ae.gray(" /comments --answered lists them."))):n.push(Ae.gray(" Reviewers leave these by highlighting text in a draft in the Document360 portal and commenting on it.")),n.push(""),s(),n.push(...Ad(e)),n}let i=go(e.threads,e.labels);return n.push(Nw(e)),n.push(""),n.push(ms(["#","Category","Article","Comments"],i.map((a,l)=>[`${l+1}`,a.category||"(root)",a.title,`${a.threads.length}`]),Ew(t.width,gP),{plain:!0,align:["left","left","left","right"]})),n.push(""),s(),n.push(...Ad(e)),n}function ja(e,t={}){let n=s=>s===1?"":"s",o=[`${Ae.gray("Category:")} ${e.category||"(root)"}`,`${Ae.gray("Article: ")} ${Ae.bold(e.title)}`,Ae.gray(`${e.threads.length} comment${n(e.threads.length)} from your reviewers`),""],r=e.threads.map(s=>{let i=[Pw(s.comment.comment)||"(empty comment)"];for(let a of s.comment.replies??[])i.push(`\u21B3 ${Pw(a.comment)}`);return s.comment.status==="reopened"&&i.push("(reopened \u2014 you answered this once and the reviewer came back)"),s.canResolve||i.push("(you can reply to this one, but your role can\u2019t resolve it)"),[pP(s),i.join(`
414
+ `)]});return o.push(ms(["Annotated text","Comment"],r,Ew(t.width,wP),{plain:!0})),o.push(""),o}function Ia(e){let t=e.reduce((r,s)=>r+s.threads.length,0),n=r=>r===1?"":"s",o=[{kind:"all",label:`All articles \u2014 answer all ${t} comment${n(t)}`,groups:e}];return e.forEach((r,s)=>{o.push({kind:"article",n:s+1,label:r.title,note:`${r.threads.length} comment${n(r.threads.length)}`,group:r})}),o}function Nd(e,t={}){let n=go(e.threads,e.labels);if(t.full&&n.length===1){let o=n[0];return[Nw(e),"",...ja(o,t),...Ad(e)]}return Ls(e,t)}function yP(e){return["1. Read ALL the open threads on the article together before you touch it. They are one review pass, not a queue of unrelated tickets: they overlap, they contradict each other sometimes, and two of them are often the same underlying problem said twice.","2. Read the WHOLE article (and its `sources:` frontmatter, and the sources themselves when a note disputes a fact) before editing. `annotates` is the exact passage the reviewer highlighted \u2014 that is where they POINTED. What they MEANT is often broader, and you can only see that from the surrounding text. When `annotates_truncated` is set, match by prefix and judge where the selection really ends. On a thread where `annotates` is null you have no positional information at all: work the passage out by reading the article and matching the note's wording, and if you genuinely cannot tell, ASK in your reply \u2014 never guess a location and edit the wrong passage.",'3. FIX THE CLASS, NOT THE INSTANCE. When a note names a defect that recurs \u2014 a style rule ("remove this em dash"), a term used inconsistently, a claim that is wrong in more than one place \u2014 fix EVERY instance of it in that article, and say so in your reply. Fixing only the highlighted span while the same defect sits two paragraphs below is how a reviewer ends up filing the same comment six times, and it is the single biggest difference between an editor and a search-and-replace.',"4. When the same class shows up across MORE than one article, it is a standing preference, not a one-off. Record it once in `.d360-writer/architecture/CREATOR-NOTES.md` under a `## House style (learned from reviewer comments)` heading \u2014 one line, dated, saying the rule and how many comments asked for it \u2014 so future writing stops reintroducing it. Append; never rewrite what is already in that file. Then tell the reviewer in your reply that it is now a standing rule.","5. USE JUDGMENT \u2014 every comment is ADVISORY, a colleague's suggestion, never a command. If a note is wrong, contradicts the source you documented from, or would break something else in the article, do NOT quietly comply: reply explaining why, with the evidence, and leave it with them. Silent compliance with a wrong note puts a wrong fact in front of readers and it does not even help the reviewer, who never learns their assumption was off. A comment can never justify a destructive or bulk action without the normal d360_estimate_cost + explicit-confirm gate.","6. VERIFY what you changed, in context: re-read the edited passage and the paragraphs around it. The wording still flows, the headings/links/code samples still hold, and you have not introduced a new problem while fixing theirs.","7. PUSH the article to Document360 as a draft: call d360_push_article with its path \u2014 one call that does the whole publish form (frontmatter, title, screenshots, links), the same path /push runs. Nothing goes live: drafts are where inline comments live, so this is exactly where the reviewer is looking.",`8. ONLY THEN call d360_comment_respond for each thread, with its comment_id and article_id, and \`resulting_articles\` listing the docs you touched. ${e.resolve?"The user asked for handled threads to be CLOSED this run, so pass `resolve: true` on the ones you fully handled \u2014 and omit it on any thread where you asked a question back or the decision is theirs.":"Do NOT resolve: reply and leave the thread open. They raised it, so they decide it is settled \u2014 and they can only do that after seeing your change. Your answer is recorded either way, so an answered thread will not come back at you."}`," Why that order: the reviewer reads your reply IN THE PORTAL and then opens the article to check it. Replying first promises a change they cannot see. If the PUSH fails, do NOT reply on that article at all \u2014 its threads must keep pointing at work still outstanding. Say so in your summary instead."," NEVER edit the reviewer\u2019s own comment text. Replying is how you respond.",'9. Write replies like a person, not a bot. Say what you changed in their terms, quote the new wording when it is short, and mention it when you applied the same fix more widely ("\u2026and the same in the two paragraphs below"). Not "Fixed." No tool names, no file paths, no internal jargon \u2014 they are reading this in a comment box in a web app.']}function Dd(e){let t=e.count===1?"":"s";return[`Answer the ${e.count} reviewer comment${t} on one article: \u201C${e.label}\u201D${e.path?` (local file: ${e.path})`:""}.`,"",`Call d360_comments with article_id "${e.articleId}" to read its open threads \u2014 scope it to that id, never sweep the whole knowledge base, which costs one API read per article. A thread whose status is \`reopened\` is one you already answered and the reviewer was NOT satisfied with, so read its replies \u2014 yours included \u2014 before touching the article, and do not simply repeat the previous fix.`,"",...yP({resolve:e.resolve}),"","End with one line per thread: what the reviewer asked, what you changed, and whether you left it with them. Plain sentences for a technical writer \u2014 no tool names, no internal file names. Then say the updated article is now a draft in Document360, so the reviewers can see the changes where they left their comments, and that it stays a draft \u2014 readers keep seeing the previous version \u2014 until someone asks for it to be published live."].join(`
415
+ `)}function jd(e){let t={answer:!1,resolve:!1,all:!1,showAnswered:!1,scope:{}};for(let n=0;n<e.length;n++){let o=e[n];o==="--answer"?t.answer=!0:o==="--resolve"?t.resolve=!0:o==="--all"?t.all=!0:o==="--full"?t.scope.full=!0:o==="--answered"||o==="--waiting"?t.showAnswered=!0:o==="--scope"?t.scope.scope=e[++n]:o.startsWith("--scope=")?t.scope.scope=o.slice(8):o.startsWith("-")||(t.scope.path=o)}return t.all&&(t.answer=!0),t.scope.scope===void 0&&delete t.scope.scope,t.scope.path===void 0&&delete t.scope.path,t}async function bP(e,t,n){if(t.length===0)return{kind:"continue"};let o=t.reduce((m,$)=>m+$.threads.length,0),{model:r}=iP(e.cwd,"standard"),s=new Map(t.map(m=>[m.label,m])),i=t.map(m=>({label:m.label,paths:m.path?[m.path]:[]}));console.log(f(`Answering ${o} comment${o===1?"":"s"} across ${i.length} article${i.length===1?"":"s"} (\u2264${Is} agents at once) on ${r}. Each article is fixed, pushed to Document360 as a draft, then answered${n.resolve?" and resolved":" \u2014 the threads stay open for your reviewers to close"}\u2026`));let a=Date.now(),l=lP(e.cwd);try{for await(let m of aP({cwd:e.cwd,partitions:i,promptFor:$=>{let S=s.get($.label);return Dd({articleId:S.articleId,label:S.label,path:S.path,count:S.threads.length,resolve:n.resolve})},concurrency:Is,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),allowCommentResolve:n.resolve,model:r}))if(m.type==="partition_status")m.status==="running"?console.log(f(` \u25B8 ${m.label} \u2014 answering\u2026`)):m.status==="done"?console.log(q(` \u2713 ${m.label}`)):console.log(_(` \u2717 ${m.label}`));else if(m.type==="run_done"){let $=m.results.filter(S=>!S.ok);console.log(""),console.log(`${m.results.length-$.length}/${i.length} article${i.length===1?"":"s"} answered.`),$.length&&console.log(H(`\u26A0 ${$.length} left untouched (their comments are still open, so nothing was promised to those reviewers): ${$.map(S=>S.label).join(", ")}`)),m.blocked&&console.log(H(`\u26A0 ${m.blocked}`)),m.allEmpty&&console.log(H("\u26A0 No agent produced any work this run \u2014 nothing was changed or answered.")),console.log(f(zt(Ct(a,m.results,m.totalCostUsd))))}}catch(m){console.log(_(`Answering comments failed: ${m.message}`))}let w=mo(e.cwd,l,"","/comments").changed.length;return w>0&&console.log(`${w} article${w===1?"":"s"} changed, and that new text has not been read by an editor \u2014 ${w===1?"it":"they"} can go live once /review has been over ${w===1?"it":"them"}.`),{kind:"continue"}}async function Dw(e,t){let n=t?.cwd??process.cwd();if(!oP(n))return console.log(_("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=He(n,t?.profileName);if(!o.ok)return console.log(_(o.reason)),{kind:"continue"};let r=jd(e);console.log(f("Checking Document360 for reviewer comments\u2026"));let s;try{s=await Da(n,t?.profileName,r.scope)}catch(a){return console.log(_(`Couldn\u2019t read comments from Document360: ${a.message}`)),{kind:"continue"}}for(let a of Nd(s,{full:!!r.scope.path,showAnswered:r.showAnswered}))console.log(a);if(s.threads.length===0)return{kind:"continue"};if(r.answer&&t)return bP(t,go(s.threads,s.labels),{resolve:r.resolve});let i=go(s.threads,s.labels)[0];return console.log(`${J("\u2192",Ae.yellow)}${Ae.bold("/comments <article>")} shows one article\u2019s comments in full `+Ae.gray(i?.path?`(e.g. /comments ${i.path})`:"(by its local path)")),console.log(`${J("\u2192",Ae.yellow)}${Ae.bold("/comments --answer")} fixes each one, updates the draft in Document360, then replies in the thread `+Ae.gray("(one article at a time: /comments --answer <article>, or --scope <category>)")),{kind:"continue"}}re();import{spawn as jw}from"node:child_process";import{mkdirSync as kP,openSync as $P,readFileSync as vP}from"node:fs";import{dirname as xP,join as RP}from"node:path";import{logsDir as CP}from"document360-engine";var br="document360-writer",Os=`npm i -g ${br}@latest`,SP="document360-capture";function PP(){return new Promise(e=>{try{let t=jw("d360-capture --version",{stdio:"ignore",shell:!0,windowsHide:!0});t.on("error",()=>e(!1)),t.on("close",n=>e(n===0))}catch{e(!1)}})}function La(){return RP(CP(),"self-update.log")}function Oa(e){return/\bEACCES\b|permission denied|EPERM|operation not permitted/i.test(e)?process.platform==="win32"?`Permission denied. Run ${Os} from an Administrator terminal.`:`Permission denied \u2014 your global npm folder isn't writable. Either run sudo ${Os} , or (better) switch to a Node version manager such as nvm or fnm so global installs need no sudo.`:/ENOTFOUND|EAI_AGAIN|ETIMEDOUT|ECONNRESET|network/i.test(e)?`Couldn't reach the npm registry. Check your connection or proxy, then run: ${Os}`:/EBADENGINE|Unsupported engine/i.test(e)?`Your Node version is too old for this release. Install Node 20 or later, then run: ${Os}`:`Run manually: ${Os}`}function TP(e,t=6){return e.split(/\r?\n/).map(n=>n.trimEnd()).filter(Boolean).slice(-t).join(`
416
+ `)}async function _a(){let e=process.platform==="win32",n=await PP()?[br,SP]:[br],o=La(),r=null;try{kP(xP(o),{recursive:!0}),r=$P(o,"w")}catch{r=null}let s=()=>{try{return TP(vP(o,"utf8"))}catch{return""}};return new Promise(i=>{try{let a=jw(`npm i -g ${n.map(l=>`${l}@latest`).join(" ")}`,{stdio:r===null?"ignore":["ignore",r,r],shell:!0,detached:!e,windowsHide:!0});a.on("error",l=>i({ok:!1,output:`${String(l)}
417
+ ${s()}`.trim(),packages:n})),a.on("close",l=>i({ok:l===0,output:l===0?"":s(),packages:n})),e||a.unref()}catch(a){i({ok:!1,output:String(a),packages:n})}})}async function Iw(){console.log(f("Updating the d360-writer toolchain\u2026"));let e=await _a();return e.ok?(console.log(q(`\u2713 Updated ${e.packages.join(" + ")}. Exit (/exit) and relaunch d360-writer to apply.`)),{kind:"continue"}):(console.log(_(`Update failed. ${Oa(e.output)}`)),e.output&&console.log(f(e.output)),console.log(f(`Full output: ${La()}`)),{kind:"continue"})}re();xn();import{existsSync as Id,rmSync as AP}from"node:fs";import{basename as Lw,resolve as Ld}from"node:path";import{execFileSync as EP}from"node:child_process";import{input as NP}from"@inquirer/prompts";import{readProjectConfig as DP,devHintsGuidePath as jP}from"document360-engine";var IP=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],LP=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),Ma=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),Ow=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function _w(e){let t=Ma(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:Ow(t)?!0:LP.has(t)}function Od(e){let t=null;try{t=DP(e)}catch{t=null}let n=new Set(IP);for(let o of[Ma(t?.docsDir),Ma(t?.captureDir),Ma(t?.outputDir)])o&&Ow(o)&&n.add(o);return[...n].filter(o=>_w(o)&&Id(Ld(e,o)))}function _d(e,t){let n=[],o=[];for(let r of t){if(!_w(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{AP(Ld(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function Mw(e,t){try{return EP("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
418
+ `).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function OP(e){return Mw(e,".d360-writer/hints")}function _P(e){return Mw(e,".d360-writer/messages")}function Md(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=OP(e),o=_P(e),r=Id(Ld(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: ${Lw(e)}`]}async function Fw(e,t){let n=Od(t.cwd);for(let l of Md(t.cwd,n))console.log(n.length===0?f(l):l);if(n.length===0)return{kind:"continue"};let o=Lw(t.cwd);if((await t.withPausedInput(()=>NP({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(H("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=Id(jP(t.cwd)),{removed:i,failed:a}=_d(t.cwd,n);console.log(q(`\u2713 Reset complete \u2014 removed ${i.length} item${i.length===1?"":"s"}. The repo is back to its original state.`));for(let l of a)console.log(_(` \u2717 ${l.path}: ${l.error}`));if(s){for(let l of Ti())console.log(l);console.log(f("(Select and copy the prompt above to paste into your coding agent.)"))}return console.log(f("Set up d360-writer again with /init (then /login, /workspace).")),{kind:"continue"}}re();import{buildBaseline as MP,buildRegistry as Wd,clearRegistryCache as FP,lintArticles as Bd,listAvailablePacks as Bw,readProjectConfig as yo,readStyleBaseline as UP,resolveActivePacks as Hw,styleGuidePath as Gw,writeProjectConfig as Hd,writeStyleBaseline as WP,activeRuleSet as BP,buildStyleCompilePrompt as HP,loadStyleGuide as GP,loadHouseRules as qP,buildStyleLearnPrompt as VP,reviewerNotesPath as YP,listStyleGuides as KP,getStyleGuide as zP,resolveActiveProfile as XP,resolveProjectId as QP,styleGuideSettled as JP,STYLE_GUIDE_MAX_CHARS as Uw,BUILTIN_RULES as Fa,ALWAYS_ON_PACK as wo}from"document360-engine";import{existsSync as Gd,mkdirSync as ZP,readFileSync as qw,writeFileSync as Ww}from"node:fs";import{dirname as eT}from"node:path";import{createHash as tT}from"node:crypto";function Ua(e){let t=e.filter(o=>!o.startsWith("--")),n=(t[0]??"").toLowerCase();return n==="list"?{sub:"list"}:n==="use"?{sub:"use",value:t.slice(1).join(" ")}:n==="keep"?{sub:"keep"}:n==="explain"?{sub:"explain",value:t[1]}:n==="pull"?{sub:"pull",value:t[1]}:n==="compile"?{sub:"compile"}:n==="learn"?{sub:"learn"}:{sub:"show"}}function nT(e){try{return wm(e,"/style-guide")?.title??null}catch{return null}}function qd(e){try{return!JP(yo(e)?.styleGuide)}catch{return!1}}function Vw(e){let t=nT(e);if(!t)return null;try{return rr(e,t).ok?ge("\u2713",`That settles a docs-campaign step \u2014 marked done: ${t}`):null}catch{return null}}function oT(e){let t=yo(e)??{projectId:""},n=Hw(t.styleGuide).filter(s=>s!==wo);Hd({...t,styleGuide:{...t.styleGuide,decidedAt:new Date().toISOString()}},e);let o=[ge("\u2713",n.length>0?`Keeping ${n.join(", ")} \u2014 plus the built-in checks, which are always on.`:"Keeping the built-in checks only \u2014 the correctness rules and the anti-slop rules, both always on."),f(" Change your mind any time: /style-guide use microsoft \xB7 see the options: /style-guide list")],r=Vw(e);return r&&o.push(r),o}var _s="House";async function rT(e,t,n){let o,r;try{let C=XP(e,n);o={profile:C.name,connection:C.connection,projectId:C.project.projectId,projectName:C.project.projectName},r=await QP(o,C.project?.projectId)}catch(C){return{lines:[ge("\u2717",`Not signed in to Document360: ${C instanceof Error?C.message:String(C)}`),f(" Run /login first.")],restart:!1}}let s=await KP(o,r);if(s.kind!=="ok")return{lines:[ge("\u26A0",`Document360 didn't return your style guides \u2014 ${s.reason}.`),f(" Nothing is blocked. Your house style guide lives at .d360-writer/style-guide.md \u2014 write or paste"),f(" it there directly, and /review and the writer both read it. /style-guide compile then turns its"),f(" mechanical parts into checks.")],restart:!1};if(s.guides.length===0)return{lines:[ge("\u2139","This Document360 project has no style guides yet."),f(" Admins create them in the portal, or write your own at .d360-writer/style-guide.md.")],restart:!1};if(!t)return{lines:["Style guides in this Document360 project:","",...s.guides.map((A,D)=>{let N=[A.language_code,A.created_by_name,A.created_at?.slice(0,10)].filter(Boolean).join(" \xB7 ");return` ${D+1} ${A.name??A.id}${A.is_default?f(" (default)"):""}${N?f(` ${N}`):""}`}),"",f(" Pull one: /style-guide pull 1 (or paste its id)")],restart:!1};let i=Number(t),a=Number.isInteger(i)&&i>=1&&i<=s.guides.length?s.guides[i-1]:s.guides.find(C=>C.id===t);if(!a)return{lines:[ge("\u2717",`No style guide numbered or identified by "${t}". Run /style-guide pull to list them.`)],restart:!1};let l=await zP(o,r,a.id,{langCode:a.language_code});if(l.kind!=="ok"){let C=l.kind==="notFound"?"Document360 could not find it (style guides are per language)":l.reason;return{lines:[ge("\u2717",`Could not read "${a.name??a.id}" \u2014 ${C}.`)],restart:!1}}let d=(l.guide.content??"").trim();if(!d)return{lines:[ge("\u26A0",`"${a.name??a.id}" has no content yet \u2014 nothing to pull.`)],restart:!1};let w=Gw(e),m=[];if(Gd(w))try{Ww(`${w}.bak`,qw(w,"utf8"),"utf8"),m.push(f(" Your previous guide is at .d360-writer/style-guide.md.bak"))}catch{}let $=d.length>Uw?d.slice(0,Uw):d,S=`<!-- Pulled from Document360: "${a.name??a.id}" (${new Date().toISOString().slice(0,10)}). Edit freely \u2014 /style-guide pull overwrites this file. -->
419
+
420
+ `;ZP(eT(w),{recursive:!0}),Ww(w,`${S}${$}
421
+ `,"utf8");let R=yo(e)??{projectId:""};return Hd({...R,styleGuide:{...R.styleGuide,pulledFrom:{styleGuideId:a.id,name:a.name??a.id,pulledAt:new Date().toISOString(),contentHash:tT("sha1").update($).digest("hex").slice(0,16)}}},e),{lines:[ge("\u2713",`Pulled "${a.name??a.id}" into .d360-writer/style-guide.md (${$.length.toLocaleString()} characters).`),...m,f(" This is PROSE, not rules \u2014 /review judges against it, and the writer now writes to it."),f(" Turn its mechanical parts into checks: /style-guide compile"),f(" Restarting the agent so it writes to the new guide\u2026")],restart:!0}}function sT(e){let t=Wd(e).rules.filter(n=>n.pack.toLowerCase()===_s.toLowerCase()).map(n=>n.id);return{prompt:HP({guide:GP(e),packName:_s,existingRuleIds:t}),display:"/style-guide compile"}}function iT(e){let t=YP(e),n=Gd(t)?qw(t,"utf8").trim():"";return!n||!/^## /m.test(n)?{kind:"nothing",lines:[ge("\u2139","No reviewer comments have been read yet, so there is nothing to learn from."),f(" Reviewers comment on your drafts in Document360; /comments reads them, and every read"),f(" keeps a copy in .d360-writer/reviewer-notes.md. Run /comments first.")]}:{kind:"run",prompt:VP({notes:n,existingRules:qP(e),houseRulesFile:".d360-writer/house-rules.md"}),display:"/style-guide learn"}}function Yw(){return[f(" Read what it wrote: git diff .d360-writer/house-rules.md"),f(" These rules apply from now on \u2014 the writer follows them and /review judges against them."),f(" Disagree with one? Delete the line. It is your file, and nothing regenerates it."),f(" Restarting the agent so it writes to the new rules\u2026")]}function Kw(){return[f(` Review what it wrote: git diff .d360-writer/styles/${_s}/`),f(` Anything it could not check mechanically is listed in .d360-writer/styles/${_s}/UNCHECKABLE.md \u2014 /review judges those.`),f(` Turn them on when you are happy: /style-guide use ${_s.toLowerCase()} (they start as warnings, never blocking)`)]}var ht=(e,t)=>`${e} ${t}${e===1?"":"s"}`,Fd=e=>/^v\d/i.test(e)?e:`v${e}`;function zw(e){let t={error:0,warning:0,suggestion:0};for(let n of e)t[n.severity]=(t[n.severity]??0)+1;return["error","warning","suggestion"].filter(n=>t[n]>0).map(n=>`${t[n]} ${n}`).join(" \xB7 ")}function aT(e){let n=yo(e)?.styleGuide?.pulledFrom;return n?`.d360-writer/style-guide.md \u2014 pulled ${n.pulledAt.slice(0,10)} from "${n.name}"`:Gd(Gw(e))?".d360-writer/style-guide.md (yours)":"the built-in default"}function lT(e){let t=yo(e),n=Wd(e),o=(t?.styleGuide?.packs??[]).filter(Boolean),r=n.packs.filter(l=>l.name.toLowerCase()===wo),s=n.packs.filter(l=>l.name.toLowerCase()!==wo),i=[`Style guide: ${aT(e)}`,`Rule packs: ${s.length>0?s.map(l=>`${l.name.toLowerCase()} ${Fd(l.version)}`).join(", "):f("none chosen")}`,`Always on: ${f(`d360 (correctness, built in \u2014 ${ht(Fa.length,"rule")})`)}`];for(let l of r)i.push(` ${f(`${l.name.toLowerCase()} ${Fd(l.version)} (anti-slop \u2014 ${ht(l.ruleCount,"rule")})`)}`);r.length>0&&(i.push(f(" Every article here is machine-written, so these cannot be switched off by")),i.push(f(" choosing another pack. styleGuide.humanise: false turns them off deliberately.")));let a=[...Fa.map(l=>({severity:l.severity})),...n.rules.map(l=>({severity:l.severity}))];i.push("",`${ht(a.length,"rule")} active \xB7 ${zw(a)}`);try{let l=Bd({cwd:e}),d=l.findings.filter(m=>!m.baselined),w=d.filter(m=>m.severity==="error").length;i.push(""),i.push(w===0?ge("\u2713",`No style errors across the docs${d.length>0?`, though ${ht(d.length,"other issue")} ${d.length===1?"is":"are"} reported`:""}.`):ge("\u2717",`${ht(w,"style error")} \u2014 /lint --blocked shows them, /lint --blocked --fix corrects them.`)),l.baselinedCount>0&&i.push(ge("\u2139",`${ht(l.baselinedCount,"issue")} ${l.baselinedCount===1?"was":"were"} already in your articles when this style guide was chosen, so ${l.baselinedCount===1?"it never blocks":"they never block"} publishing.`)),l.ruleErrors.length>0&&i.push(ge("\u26A0",`${ht(l.ruleErrors.length,"rule")} could not be loaded: ${l.ruleErrors.slice(0,2).map(m=>`${m.ruleId} (${m.reason})`).join("; ")}`))}catch{}return i.push(""),i.push(f(" See them all: /style-guide list \xB7 change: /style-guide use <preset> \xB7 one rule: /style-guide explain <rule>")),qd(e)&&(i.push(""),i.push("Nobody has settled this yet, and it is a decision \u2014 nothing above changed anything:"),i.push(" Happy with these rules? /style-guide keep"),i.push(" Want a stricter standard? /style-guide use microsoft (or google)"),i.push(f(" Worth settling now rather than later: it shapes every article written from here, and")),i.push(f(" changing it once a knowledge base exists means going back over what is already written."))),i}function Ud(e){let t=yo(e),n=new Set(Hw(t?.styleGuide)),o=Bw(e),r=["Rule packs you can turn on:",""],s=Math.max(12,...o.map(i=>i.name.length));for(let i of o){let a=i.name.toLowerCase(),l=n.has(a),d=a===wo,w=l?"\u2713":"\xB7",m=d?f("(always on)"):l?f("(active)"):"",$=i.local?f(" [yours]"):"";r.push(` ${w} ${a.padEnd(s)}${$} ${i.description??""}`),r.push(` ${f(`${ht(i.rules.length,"rule")} \xB7 ${zw(i.rules)} \xB7 ${Fd(i.version)}`)} ${m}`),i.errors.length>0&&r.push(ge("\u26A0",`${ht(i.errors.length,"rule")} in this pack could not be loaded \u2014 /style-guide explain names them.`))}return o.every(i=>i.name.toLowerCase()===wo)&&(r.push(""),r.push(f(" The Microsoft and Google style guides are not installed in this build yet."))),r.push(""),r.push(f(" Turn one on: /style-guide use <name> (this replaces the chosen set, it does not add to it)")),r.push(f(" Several: /style-guide use microsoft,google")),r.push(f(" Back to none: /style-guide use none")),r}function cT(e,t){if(!t)return[ge("\u26A0","Name a rule: /style-guide explain Humanise.EmDash")];let n=Wd(e),o=Fa.find(d=>d.id.toLowerCase()===t.toLowerCase()),r=n.rules.find(d=>d.id.toLowerCase()===t.toLowerCase());if(!o&&!r){let d=[...Fa.map(w=>w.id),...n.rules.map(w=>w.id)].filter(w=>w.toLowerCase().includes(t.toLowerCase())).slice(0,5);return[ge("\u26A0",`No active rule called "${t}".`),...d.length>0?[f(` Did you mean: ${d.join(", ")}`)]:[f(" /style-guide list shows the active packs.")]]}let s=o?.id??r.id,i=o?.severity??r.severity,a=o?"built in (correctness \u2014 always on)":`pack: ${r.pack.toLowerCase()}`,l=[`${s} ${i} \xB7 ${a}`,""];l.push(` ${o?.summary??r.message}`),r?.link&&l.push(f(` ${r.link}`)),r?.degraded&&(l.push(""),l.push(ge("\u26A0",`This rule is translated approximately: ${r.degraded}. It may match slightly more than the original does.`)));try{let d=Bd({cwd:e}).findings.filter(m=>m.ruleId===s),w=d.filter(m=>!m.baselined);l.push(""),l.push(d.length===0?" Currently: no findings.":` Currently: ${ht(w.length,"finding")}${d.length!==w.length?`, plus ${d.length-w.length} baselined and hidden`:""}.`)}catch{}return l.push(""),o?(l.push(f(" Built-in checks are grounded in your product's own source and cannot be switched off \u2014 they")),l.push(f(" catch defects of fact, not matters of taste."))):(l.push(i==="error"?f(' This one BLOCKS publishing \u2014 your config sets it to "error" deliberately.'):f(" Style rules never block publishing. Fix it when you want to; it will not hold a page back.")),l.push(f(` Silence it everywhere: add "${s}": "off" to styleGuide.rules in .d360-writer/config.json`)),i!=="error"&&l.push(f(" Silence one passage: <!-- vale "+s+" = NO --> \u2026 <!-- vale "+s+" = YES -->"))),l}function uT(e,t){let n=(t??"").trim();if(!n)return{lines:[ge("\u26A0","Name the packs to use: /style-guide use microsoft (or `none`)"),...Ud(e)],restart:!1};let o=n.toLowerCase()==="none"?[]:n.split(/[,\s]+/).map(d=>d.trim().toLowerCase()).filter(Boolean),r=new Map(Bw(e).map(d=>[d.name.toLowerCase(),d])),s=o.filter(d=>!r.has(d));if(s.length>0)return{lines:[ge("\u2717",`No rule pack named ${s.map(d=>`"${d}"`).join(", ")}.`),"",...Ud(e)],restart:!1};let i=yo(e)??{projectId:""};Hd({...i,styleGuide:{...i.styleGuide,packs:o,decidedAt:new Date().toISOString()}},e),FP();let a=[ge("\u2192",`Switching to: ${o.length>0?o.join(", "):"the built-in checks only"}${o.includes(wo)?"":` (+ ${wo}, always on)`}\u2026`)];try{let d=Bd({cwd:e}),w=new Set(d.findings.map(m=>m.path)).size;if(d.findings.length===0)a.push(ge("\u2713",w===0?"No articles yet \u2014 everything you write from here is held to the full set.":"Nothing to record: your articles are already clean against these rules."));else{let m=UP(e),$=MP(d.findings,BP(e));WP(e,$),a.push(ge("\u2713",`Recorded ${ht(d.findings.length,"existing issue")} across ${ht(w,"article")} as accepted.`),f(" .d360-writer/style-baseline.json \u2014 commit it. It defines what the publish gate lets through, and a"),f(" teammate with a different copy gets a different answer from the same gate."),ge("\u2713","Nothing is blocked today. New writing, and any paragraph you edit, is held to the full set.")),a.push(ge("\u2139",`Those ${ht(w,"article")} do not follow ${o.join(", ")} \u2014 they are exempt, not compliant.`),f(" To bring them up to it: /review --all --fix, then /lint --all --fix. That is a pass over every"),f(" article and it costs accordingly \u2014 which is why this is worth settling before a knowledge base exists.")),m&&a.push(f(` (Replaced the baseline recorded ${m.createdAt.slice(0,10)}.)`))}}catch(d){a.push(ge("\u26A0",`The packs are active, but recording what was already there failed: ${d instanceof Error?d.message:String(d)}`)),a.push(f(" Run /lint to see the current state before publishing."))}let l=Vw(e);return l&&a.push(l),a.push(f(" Restarting the agent so it writes to the new rules\u2026")),{lines:a,restart:!0}}async function Wa(e,t){let{sub:n,value:o}=Ua(e),r=s=>{for(let i of s)console.log(i);console.log("")};switch(n){case"list":return r(Ud(t.cwd)),{kind:"continue"};case"explain":return r(cT(t.cwd,o)),{kind:"continue"};case"use":{let s=uT(t.cwd,o);return r(s.lines),s.restart?{kind:"clear"}:{kind:"continue"}}case"keep":return r(oT(t.cwd)),{kind:"continue"};case"pull":{let s=await rT(t.cwd,o,t.profileName);return r(s.lines),s.restart?{kind:"clear"}:{kind:"continue"}}case"compile":{let s=sT(t.cwd);return{kind:"forward-to-agent",prompt:s.prompt,display:s.display}}case"learn":{let s=iT(t.cwd);return s.kind==="nothing"?(r(s.lines),{kind:"continue"}):{kind:"forward-to-agent",prompt:s.prompt,display:s.display}}default:return r(lT(t.cwd)),{kind:"continue"}}}re();import{lintDocs as Ha,loadStyleGuide as iy,buildReviewPrompt as ay,hasCaptureArtifacts as ly,readProjectConfig as cy,DEFAULT_DOCS_DIR as uy,listArticleFiles as kr,normalizeScope as CT,planPartitions as ST,runPartitioned as PT,partitionCoverage as TT,resolveModelForOperation as AT,stampArticles as ET,reviewStalePaths as NT,readReviewerNotes as dy,renderNotesForPrompt as py,readDocsPlan as DT,CONTENT_CAP_VERSION as jT}from"document360-engine";import{listArticleFiles as dT,lintDocs as pT,planFindingPartitions as hT,planPartitions as fT,readDocsPlan as mT,readProjectConfig as gT,runRate as Xw,DEFAULT_DOCS_DIR as wT}from"document360-engine";function Qw(e){switch(e.cmd){case"/review":return{concurrency:_n,maxPerPartition:Yd,minutesPerBatch:5};case"/write":return{concurrency:3,minutesPerBatch:4};case"/lint":return{concurrency:3,minutesPerBatch:2};default:return{concurrency:3,minutesPerBatch:2}}}function yT(e,t){let n=pT({cwd:e,scope:t.scope}).filter(s=>!s.baselined),o=t.flags.has("--blocked")?n.filter(s=>s.severity==="error"):n;if(o.length===0)return null;let r=new Set(o.map(s=>s.path)).size;return{lead:`${o.length} issue${o.length===1?"":"s"} \xB7 ${r} article${r===1?"":"s"}`,articles:r,batches:hT(o).length}}function bT(e,t){try{if(t.cmd==="/write"){let n=(gT(e)?.docsDir??wT).replace(/\/+$/,""),o=mT(e,n).map(s=>s.path);if(o.length===0)return null;let r=t.scope?o.filter(s=>s===t.scope||s.startsWith(`${t.scope}/`)):o;return t.flags.has("--rewrite")?r:Pn(e,n,r)}return t.cmd==="/review"?bo(e,[...t.flags],t.scope):dT(e,t.scope)}catch{return null}}function Jw(e,t){let n=On(e,t);if(!n)return null;let o=n.indexOf(" batch");if(o<0)return null;let r=n.lastIndexOf("\xB7 ",o);return r<0?n:n.slice(r+2)}function On(e,t){let n=zi(t);if(!n||!Ic(n))return null;let o=Qw(n),r=n.cmd==="/lint"?Vd(()=>yT(e,n)):null,s=r?null:bT(e,n),i=r?r.articles:s?.length??0;if(n.cmd==="/lint"?!r||i<4:!s||i<4)return null;let a=r?r.batches:fT(s,o.maxPerPartition?{maxPerPartition:o.maxPerPartition}:void 0).length,l=Math.ceil(a/o.concurrency),d=Vd(()=>Xw(e,n.cmd)),w=l*(d?.minutesPerWave??o.minutesPerBatch),m=r?r.lead:`${i} articles`,$=d?.usdPerArticle!==void 0?` \xB7 ~${ny(i*d.usdPerArticle)}`:"";return`${m} \xB7 ${a} batch${a===1?"":"es"} \xB7 ~${ty(w)}${$}`}var Zw=.7,ey=1.4;function ty(e){let t=Math.max(1,Math.round(e*Zw)),n=Math.max(t,Math.round(e*ey));if(n<90)return`${t}\u2013${n} min`;let o=r=>r<60?`0h ${r}m`:`${Math.floor(r/60)}h ${r%60}m`;return`${o(t)}\u2013${o(n)}`}function ny(e){let t=e*Zw,n=e*ey;return n>=10?`$${Math.round(t)}\u2013${Math.round(n)}`:`$${t.toFixed(2)}\u2013${n.toFixed(2)}`}function Vd(e){try{return e()}catch{return null}}function Ba(e,t,n,o){if(n<4||o<1)return null;let r=Qw({cmd:t,scope:void 0,flags:new Set,args:[]}),s=Math.ceil(o/r.concurrency),i=Vd(()=>Xw(e,t)),a=s*(i?.minutesPerWave??r.minutesPerBatch),l=i?.usdPerArticle!==void 0?` \xB7 ~${ny(n*i.usdPerArticle)}`:"";return`~${ty(a)}${l}`}import{renderGapsForPrompt as hy}from"document360-engine";import{recordRunSample as IT}from"document360-engine";re();import{readProjectConfig as kT,loadProfileMap as $T,resolveActiveProfile as vT,desiredCategoryOrder as xT,desiredArticleOrder as RT}from"document360-engine";function oy(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}var ry=e=>e.replace(/\\/g,"/").split("/").pop()??e;function Ms(e,t){try{if(!kT(e))return[];let n=vT(e,t),o=$T(e,n.name);if(!o)return[];let r=new Map;for(let i of RT(o)){let a=r.get(i.categoryPath);a?a.push(i):r.set(i.categoryPath,[i])}let s=[];for(let i of xT(o)){s.push(oy(ry(i.path)));for(let a of(r.get(i.path)??[]).sort((l,d)=>l.order-d.order))s.push(` ${oy(ry(a.path))}`)}return s}catch{return[]}}async function sy(e,t){let n=Ms(t.cwd,t.profileName);if(n.length===0)return console.log(f("No documentation structure yet \u2014 run /init and author some articles first.")),{kind:"continue"};console.log(Z("Documentation order (categories \u2192 articles):"));for(let o of n)console.log(o);return console.log(""),{kind:"continue"}}function Kd(e,t){return hs(e,kr(e,t))}function zd(e,t){return NT(e,kr(e,t),jT)}function Fs(e){return e.includes("--blocked")||e.includes("--stale")}function bo(e,t,n){return t.includes("--blocked")?Kd(e,n):t.includes("--stale")?zd(e,n):kr(e,n)}function fy(e,t,n){let o;try{o=DT(e)}catch{return[]}let r=new Map(o.map(i=>[i.path.replace(/\\/g,"/"),i])),s=[];for(let i of n){let a=i.replace(/\\/g,"/").replace(`${t}/`,""),l=r.get(a);l&&s.push({path:i,type:l.type,...l.purpose?{purpose:l.purpose}:{}})}return s}function my(e,t){let n=cy(e);if(!n)return null;let o=(n.docsDir??uy).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),s=Fs(t),i=t.find(A=>!A.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),a=Ha({cwd:e}),l=i?CT(o,i):"",d=l?a.filter(A=>A.path===`${o}/${l}`||A.path.startsWith(`${o}/${l}/`)):a,w=s?bo(e,t,i):void 0,m=w?d.filter(A=>w.includes(A.path)):d,$=i||s?"":Ms(e).join(`
422
+ `),S=ly(e,n),R=ay({docsRoot:o,scope:i,styleGuide:iy(e),deterministicFindings:m,fix:r,structure:$||void 0,screenshots:S,...w?{paths:w}:{},reviewerNotes:py(dy(e),w??kr(e,i)),openGaps:hy(e,w??kr(e,i)),planRows:fy(e,o,w??kr(e,i))}),C=t.includes("--blocked")?" --blocked":t.includes("--stale")?" --stale":"";return{prompt:R,display:`/review${i?` ${i}`:""}${C}${r?" --fix":""}`}}var LT=e=>"ruleId"in e,_n=3,Yd=3;function Xd(e,t){let n=my(e,t);if(!n)return null;let o=t.find(S=>!S.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),r=bo(e,t,o),s=ST(r,{maxPerPartition:Yd});if(s.length<=1)return{kind:"single",...n};let i=cy(e),a=(i?.docsDir??uy).replace(/\\/g,"/").replace(/\/+$/,""),l=t.includes("--fix"),d=iy(e),w=Ha({cwd:e}),m=dy(e),$=ly(e,i);return{kind:"partitioned",partitions:s,articles:r.length,wholeKb:!o&&!Fs(t),display:n.display,promptFor:S=>{let R=new Set(S.paths);return ay({docsRoot:a,styleGuide:d,deterministicFindings:w.filter(C=>R.has(C.path)),fix:l,screenshots:$,paths:S.paths,reviewerNotes:py(m,S.paths),openGaps:hy(e,S.paths),planRows:fy(e,a,S.paths)})}}}function Qd(e,t){if(!Fs(t))return null;let n=t.find(m=>!m.startsWith("--"));if(bo(e,t,n).length>0)return null;let o=t.includes("--blocked"),r=!!n&&n.endsWith(".md"),s=n?r?" here":` in ${n}`:"",a=o?`\u2713 Nothing is blocked${s} \u2014 ${n&&r?"it has":"every article has"} been through an editorial read.`:`\u2713 ${r?"This article has":`Every article${s} has`} already been read by the current editor \u2014 nothing to re-read.`,l=`/push${n?` ${n}`:" --all"}`,d=Bt(e,{text:`${l} saves ${r?"it":"what has changed"} to Document360 as ${r?"a draft":"drafts"}.`,cmd:l},"",n,"/review"),w=vt(e,my(e,t)?.display??"");return{lines:[a,` ${d.text}`],closed:w,cta:d}}async function gy(e,t){let n=Qd(t.cwd,e);if(n){console.log(q(n.lines[0]));for(let r of n.lines.slice(1))console.log(f(r));for(let r of n.closed)console.log(q(r));return{kind:"continue",ownNext:!0}}if(jn("review",e)){let r=hr(t.cwd,"review",e,t.profileName);if(r.length>0){for(let s of r)console.log(f(s));return{kind:"continue"}}}let o=Xd(t.cwd,e);return o?o.kind==="single"?{kind:"forward-to-agent",prompt:o.prompt,display:o.display}:await OT(t,o,e.includes("--fix"),e.find(r=>!r.startsWith("--"))):(console.log(_("No d360-writer config here. Run /init first.")),{kind:"continue"})}async function OT(e,t,n,o){let{model:r}=AT(e.cwd,"standard"),s=Ba(e.cwd,"/review",t.articles,t.partitions.length);console.log(f(`Reviewing ${t.articles} article${t.articles===1?"":"s"} in ${t.partitions.length} batches (\u2264${_n} editors at once) on ${r}${n?", applying fixes":", report only"}${s?` \xB7 ${s}`:""}\u2026`));let i=Date.now(),a=new lr;a.start();let l={aborted:!1,partitions:0,failed:0,notRun:0,producedNothing:!0};try{for await(let $ of PT({cwd:e.cwd,partitions:t.partitions,promptFor:t.promptFor,concurrency:_n,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:r,scope:"review"}))if($.type==="partition_status")$.status==="running"?console.log(f(` \u25B8 ${$.label} \u2014 reviewing\u2026`)):$.status==="done"?console.log(q(` \u2713 ${$.label}`)):console.log(_(` \u2717 ${$.label}`));else if($.type==="run_done"){let S=TT(t.partitions,$.results);l={aborted:!!$.aborted,partitions:t.partitions.length,failed:S.failed.length,notRun:S.notRun.length,...$.blocked?{blocked:$.blocked}:{},...$.allEmpty?{allEmpty:!0}:{},...$.bailedEmpty?{bailedEmpty:!0}:{}},console.log(""),console.log(`${$.results.length-S.failed.length}/${t.partitions.length} batches reviewed.`),S.failed.length&&console.log(H(`\u26A0 ${S.failed.length} not reviewed: ${S.failed.map(C=>C.label).join(", ")}`)),S.notRun.length&&console.log(H(`\u26A0 ${S.notRun.length} batch${S.notRun.length===1?"":"es"} never started \u2014 their articles are untouched.`)),$.blocked&&console.log(H(`\u26A0 ${$.blocked}`)),$.allEmpty&&console.log(H("\u26A0 No editor produced any work this run \u2014 nothing was reviewed or changed."));for(let C of Jd(t))console.log(f(C));if(n&&!$.allEmpty&&!$.blocked)try{ET(e.cwd,S.covered,it("review"))}catch{}let R=a.stop();if(console.log(f(zt(Ct(i,$.results,$.totalCostUsd,Date.now(),R.activeSeconds)))),!$.allEmpty&&!$.blocked){let C=$.results.filter(A=>A.ok).length;IT(e.cwd,"review",{articles:S.covered.length,waves:Math.ceil(C/Math.max(1,_n)),seconds:R.activeSeconds,costUsd:$.totalCostUsd})}}}catch($){return a.stop(),console.log(_(`Review failed: ${$.message}`)),{kind:"continue"}}if(a.stop(),n&&Kt(l))for(let $ of vt(e.cwd,t.display))console.log(q($));if(!n)return{kind:"continue"};let d=pr(e.cwd,["--fix"],Ha({cwd:e.cwd,scope:o}));for(let $ of d.lines)console.log($);let m=Ha({cwd:e.cwd,scope:o}).filter($=>!$.baselined).filter($=>LT($)&&$.severity==="error");if(console.log(""),m.length>0){let $=Ce("/lint","--blocked --fix",o);console.log(f(`Editor applied its fixes, but ${m.length} style error${m.length===1?"":"s"} remain \u2014 ${$} clears them (finding them costs nothing, one pass corrects them). It is the last paid pass before publishing: anything still standing after a second attempt is reported for a person rather than run again.`))}else console.log(f(Bt(e.cwd,{text:"\u2713 Reviewed and fixed. /push --all saves the articles to Document360 as drafts.",cmd:"/push --all"},"",o).text));return{kind:"continue",ownNext:!0}}function Jd(e){return e.partitions.length<2?[]:[`Each editor saw one slice of the docs, so reading order and terminology drift ${e.wholeKb?"ACROSS categories":"ACROSS the rest of the knowledge base"} were not judged.`,"/structure shows the reading order if you want to check it yourself."]}re();import{readProjectConfig as _T}from"document360-engine";function Zd(e,t){if(!_T(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: 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 /push."].filter(Boolean).join(`
423
+ `),display:`/reorder${n?` ${n}`:""}`}}async function wy(e,t){if(jn("reorder",e)){let o=hr(t.cwd,"reorder",e,t.profileName);if(o.length>0){for(let r of o)console.log(f(r));return{kind:"continue"}}}let n=Zd(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(_("No d360-writer config here. Run /init first.")),{kind:"continue"})}re();import{computeReadiness as MT,readinessPlaceholderPlaces as FT}from"document360-engine";import Ge from"picocolors";var ep=5;function Xe(e,t=58){let n=e.replace(/\\/g,"/");return n.length<=t?n:`\u2026${n.slice(n.length-t+1)}`}function UT(e){let t=[],n=e.verdict;if(e.conflicts.length>0&&t.push({glyph:"\u2717",paint:Ge.red,title:`Changed here and on Document360 (${e.conflicts.length})`,fix:"/resolve",items:e.conflicts.map(o=>Xe(o))}),n.unreviewed.length>0&&t.push({glyph:"\u2717",paint:Ge.red,title:`Never read by an editor (${n.unreviewed.length})`,fix:"/review --blocked --fix",items:n.unreviewed.map(o=>Xe(o))}),n.styleErrors.length>0){let o=n.styleErrors.reduce((r,s)=>r+s.errors,0);t.push({glyph:"\u2717",paint:Ge.red,title:`Break house style rules your config makes blocking (${o} error${o===1?"":"s"})`,fix:"/lint --blocked --fix",items:n.styleErrors.map(r=>`${Xe(r.path)} (${r.errors})`)})}if(n.placeholders.length>0){let o=FT(e);t.push({glyph:"\u2717",paint:Ge.red,title:`Would show "[Screenshot: \u2026]" to your readers (${n.placeholders.length} article${n.placeholders.length===1?"":"s"}, ${o} place${o===1?"":"s"})`,fix:"/screenshot",items:n.placeholders.map(r=>`${Xe(r.path)} (${r.missingShots.length+r.orphans})`)})}return t}function WT(e){let t=e.verdict,n=[];return e.conflicts.length===0&&n.push(`${J("\u2713",Ge.green)}Nothing is in conflict with Document360`),t.unreviewed.length===0&&n.push(`${J("\u2713",Ge.green)}Every article has been read by an editor`),t.styleErrors.length===0&&n.push(`${J("\u2713",Ge.green)}House style: nothing blocking`),t.placeholders.length===0&&n.push(`${J("\u2713",Ge.green)}No placeholder text would reach a reader`),n}function BT(e,t){if(e.rows.length===0)return[];let n=r=>r?Ge.green("\u2713"):Ge.red("\u2717"),o=e.rows.map((r,s)=>[String(s+1),Xe(r.path,46),n(r.reviewed),r.styleErrors===0?Ge.green("\u2713"):Ge.red(`\u2717 ${r.styleErrors}`),r.placeholders===0?Ge.green("\u2713"):Ge.red(`\u2717 ${r.placeholders}`),r.conflict?Ge.red("conflict"):r.draftPending?Ge.yellow("draft"):r.localAhead?f("not saved"):f("\u2014")]);return ms(["#","Article","Read","Style","Pictures","Document360"],o,t).split(`
424
+ `)}function tp(e,t={}){let n=MT(e,t.profileName),o=[];if(n.rows.length===0)return o.push(Z("Publish readiness")),o.push(""),o.push(n.tracked===0?`${J("\u25CB",Ge.gray)}No articles are tracked yet. /write authors them, /push saves them to Document360.`:`${J("\u2713",Ge.green)}All ${n.tracked} articles are live and unchanged \u2014 nothing is waiting on you.`),n.orphans.length>0&&o.push(...yy(n)),o.push(""),o.push(f(" Free \u2014 /status reads your local files and the last sync. It calls nothing.")),o;let r=n.rows.length,s=n.blocked.length;o.push(Z("Publish readiness")+f(` ${r} article${r===1?"":"s"} not yet settled with readers \xB7 ${s===0?"nothing blocked":`${s} blocked`}`)),o.push(""),t.all&&(o.push(...BT(n,t.width??100)),o.push(""));for(let l of UT(n)){o.push(` ${J(l.glyph,l.paint)}${l.title}${l.fix?f(` ${l.fix}`):""}`);for(let d of l.items.slice(0,ep))o.push(f(` ${d}`));l.items.length>ep&&o.push(f(` \u2026and ${l.items.length-ep} more`)),o.push("")}let i=WT(n);if(i.length>0){for(let l of i)o.push(` ${l}`);o.push("")}let a=n.rows.filter(l=>l.localAhead).length;return a>0&&o.push(f(` ${a} changed here \u2014 /push saves ${a===1?"it":"them"} to Document360 as ${a===1?"a draft":"drafts"}. Readers see nothing until then.`)),n.draftPending.length>0&&o.push(f(` ${n.draftPending.length} saved on Document360 as ${n.draftPending.length===1?"a draft":"drafts"} and not live \u2014 /publish takes ${n.draftPending.length===1?"it":"them"} to your readers.`)),n.orphans.length>0&&o.push(...yy(n)),!t.all&&n.rows.length>0&&o.push(f(" /status --all shows every article, gate by gate.")),o.push(""),o.push(f(" Free \u2014 /status reads your local files and the last sync. It calls nothing.")),o}function yy(e){let t=e.orphans.length;return[f(` ${t} article${t===1?"":"s"} on Document360 ${t===1?"is":"are"} not in your docs folder (${Xe(e.orphans[0].path,40)}${t>1?`, +${t-1} more`:""}) \u2014 /doctor lists ${t===1?"it":"them"}.`)]}async function by(e,t){let n=e.some(o=>o==="--all"||o==="--full");for(let o of tp(t.cwd,{profileName:t.profileName,all:n}))console.log(o);return{kind:"continue",ownNext:!0}}re();import{computeReadiness as HT,retireArticle as GT,retiredPaths as qT,normalizeScope as VT}from"document360-engine";import{select as YT}from"@inquirer/prompts";function np(e,t){let n=HT(e,t),o=qT(e,t),r=[Z("Take an article off your readers"),""];if(n.orphans.length>0){r.push(` ${J("\u25CB",f)}On Document360, but not in your docs folder \u2014 the usual reason to retire:`);for(let s of n.orphans.slice(0,8))r.push(f(` ${Xe(s.path)}`));n.orphans.length>8&&r.push(f(` \u2026and ${n.orphans.length-8} more`)),r.push("")}if(o.length>0){r.push(` ${J("\u2713",f)}Already retired \u2014 readers do not see ${o.length===1?"it":"these"}:`);for(let s of o.slice(0,5))r.push(f(` ${Xe(s)}`));o.length>5&&r.push(f(` \u2026and ${o.length-5} more`)),r.push("")}return n.orphans.length===0&&o.length===0&&(r.push(f(" Nothing obvious to retire \u2014 every tracked article is still in your docs folder.")),r.push("")),r.push(f(" /retire <path> takes one off your readers. Any tracked article can be named, not just these.")),r.push(f(" Nothing is deleted: the article, its history and every reviewer comment stay on Document360.")),r.push(f(" /push puts one back \u2014 reviving is a publish like any other, with the same review.")),r}async function ky(e,t){let n=t.cwd,o=e.find(a=>!a.startsWith("-"));if(!o){for(let a of np(n,t.profileName))console.log(a);return{kind:"continue",ownNext:!0}}let r=VT(n,o)||o;if(!(e.includes("--yes")||e.includes("-y"))&&(console.log(""),console.log(H(`This takes "${Xe(r)}" off your readers on Document360.`)),console.log(f(" The article, its history and every reviewer comment stay \u2014 nothing is deleted.")),console.log(f(" /push puts it back later if you change your mind.")),console.log(""),await YT({message:"Take it off your readers?",choices:[{name:"No \u2014 leave it as it is",value:"no"},{name:"Yes \u2014 readers stop seeing it",value:"yes"}]})!=="yes"))return console.log(f("Nothing changed.")),{kind:"continue",ownNext:!0};let i=await GT({cwd:n,path:r,profileName:t.profileName,now:new Date().toISOString()});return i.ok?(console.log(i.alreadyHidden?`${J("\u2713")}"${Xe(r)}" was already invisible to readers. Recorded as retired, so nothing will offer to publish it again.`:`${J("\u2713")}"${Xe(r)}" is no longer visible to your readers.`),console.log(f(" It is still on Document360 with its history and comments intact. /push puts it back.")),{kind:"continue",ownNext:!0}):(console.log(_(`${J("\u2717")}Could not retire "${Xe(r)}" \u2014 ${i.error.message}`)),{kind:"continue",ownNext:!0})}re();import{scanTerminology as $y,approvalBlockedReason as vy,readProjectConfig as KT,writeProjectConfig as zT,termKey as op,HEAD_NOUN_CAP as XT}from"document360-engine";import Ht from"picocolors";var QT=3,JT=e=>e.uses.map(t=>`${Ht.bold(t.form)} ${f(`${t.files.length} article${t.files.length===1?"":"s"}`)}`).join(f(" \xB7 "));function rp(e,t={}){let n=$y(e,t.scope?{scope:t.scope}:{}),o=[];if(n.scanned===0)return[Z("Terminology"),"",`${J("\u25CB",f)}No articles to read yet.`,""];let r=n.variance.length+n.headings.length;if(o.push(Z("Terminology")+f(` ${n.scanned} article${n.scanned===1?"":"s"} read \xB7 ${r===0?"nothing inconsistent":`${r} to look at`}`)),o.push(""),n.variance.length>0){o.push(` ${J("\u2717",Ht.red)}The same term, spelled more than one way`);for(let s of n.variance){o.push(` ${JT(s)}`);let i=s.uses[s.uses.length-1],a=i.files.slice(0,QT);o.push(f(` "${i.form}" is in ${a.map(d=>Xe(d,40)).join(", ")}${i.files.length>a.length?`, +${i.files.length-a.length} more`:""}`));let l=vy(s);l?o.push(f(` ${l}`)):o.push(f(` /terms --approve "${s.uses[0].form}" makes that the approved spelling`))}o.push("")}if(n.headNouns.length>0){let s=t.all?n.headNouns:n.headNouns.slice(0,XT);o.push(` ${J("\u25CB",f)}Possibly the same thing under a short name \u2014 ${Ht.italic("your call")}`);for(let i of s)o.push(f(` ${i.uses.map(a=>a.form).join(" \xB7 ")}`));n.headNouns.length>s.length&&o.push(f(` \u2026and ${n.headNouns.length-s.length} more \u2014 /terms --all lists them`)),o.push(f(' A shared word is not proof of a shared meaning: "billing history" and "history" are')),o.push(f(" different things. Nothing is flagged as wrong here.")),o.push("")}if(n.headings.length>0){o.push(` ${J("\u26A0",Ht.yellow)}Titles out of step with the rest of their kind`);for(let s of n.headings)o.push(` ${Ht.bold(s.title)} ${f(`\u2014 ${Xe(s.path,40)}`)}`),o.push(f(` the other ${s.peers} ${s.type} article${s.peers===1?"":"s"} look like "${s.example}"; this one starts ${ZT(s.shape)}`));o.push("")}return r===0&&n.headNouns.length===0&&(o.push(` ${J("\u2713",Ht.green)}Every term is spelled one way, and every title matches its kind.`),o.push("")),o.push(f(' This compares spellings, not meanings: two different words for one thing (say "nav" and')),o.push(f(' "rail") look unrelated to it. Add the pair to your approved terms and every run enforces it.')),o.push(f(" Free \u2014 this read your articles and called nothing.")),o}function ZT(e){return e==="gerund"?"with an -ing word":e==="how-to"?'with "How to"':"differently"}function sp(e,t,n){let o=n??$y(e),r=op(t),s=o.variance.find(m=>m.uses.some($=>op($.form)===r));if(!s)return{wrote:!1,lines:[`${J("\u2717",Ht.red)}"${t}" is not one of the terms with competing spellings. /terms lists them.`]};let i=vy(s);if(i)return{wrote:!1,lines:[`${J("\u2717",Ht.red)}That one cannot be recorded: ${i}.`,f(` The spellings in play are ${s.uses.map(m=>`"${m.form}"`).join(" and ")}.`)]};let a=s.uses.find(m=>op(m.form)===r).form,l=s.uses.filter(m=>m.form!==a).map(m=>m.form),d=KT(e);if(!d)return{wrote:!1,lines:[`${J("\u2717",Ht.red)}No project configuration here \u2014 run /init first.`]};let w={...d.terminologyGlossary??{}};for(let m of l)w[m]=a;return zT({...d,terminologyGlossary:w},e),{wrote:!0,lines:[`${J("\u2713",Ht.green)}"${a}" is now the approved spelling.`,f(` Added to your approved terms: ${l.map(m=>`"${m}" \u2192 "${a}"`).join(", ")}`),f(" Every run enforces it from now on, and /lint --fix corrects the others for free.")]}}async function xy(e,t){let n=e.findIndex(s=>s==="--approve");if(n!==-1){let s=e[n+1];if(!s)return console.log(`${J("\u2717",Ht.red)}Name the spelling to approve, e.g. /terms --approve "drop-down".`),{kind:"continue",ownNext:!0};for(let i of sp(t.cwd,s.replace(/^["']|["']$/g,"")).lines)console.log(i);return{kind:"continue",ownNext:!0}}let o=e.includes("--all"),r=e.find(s=>!s.startsWith("--"));for(let s of rp(t.cwd,{...r?{scope:r}:{},all:o}))console.log(s);return{kind:"continue",ownNext:!0}}re();import{readProjectConfig as eA,writeProjectConfig as Ry,isAppType as tA,playbookSkillName as nA,detectAppType as Cy}from"document360-engine";var Sy=["web","cli","service","library"],oA=new Set(["web","cli"]);function ip(e){return oA.has(e)?`${nA(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function Ga(e,t){let n=t.cwd,o=eA(n);if(!o)return console.log(_("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let s=o.appType??Cy(n);if(s){let i=o.appType?"set in config":"auto-detected";console.log(`${Z("Genre:")} ${s} (${i}) \u2014 ${ip(s)}`)}else console.log(H("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(f(`Set it: /genre <${Sy.join("|")}> \xB7 revert to auto-detect: /genre auto`)),{kind:"continue"}}if(r==="auto"||r==="clear"){if(!o.appType)return console.log(f("Already on auto-detect (no genre set in config).")),{kind:"continue"};let{appType:s,...i}=o;Ry(i,n);let a=Cy(n);return console.log(q(`\u2713 Genre reset to auto-detect \u2014 now: ${a?`${a} (${ip(a)})`:"unclassified (no playbook)"}.`)),console.log(f(" Restarting the agent so the loaded playbook matches\u2026")),{kind:"clear"}}return tA(r)?(Ry({...o,appType:r},n),console.log(q(`\u2713 Genre set to ${r} \u2014 ${ip(r)}.`)),console.log(f(" Restarting the agent so the playbook loads\u2026")),{kind:"clear"}):(console.log(_(`Unknown genre "${r}". Choose one of: ${Sy.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}var Py={help:ec,"?":ec,clear:zh,exit:tc,quit:tc,init:lc,mcp:Ni,push:oa,publish:Im,audit:(e,t)=>fs({cwd:t.cwd,profileName:t.profileName}),discover:Lm,scope:_m,pull:Qm,resolve:Km,convert:fg,write:Ag,draft:Ig,document:Lg,resume:Mg,rename:Fg,profile:Wg,model:Gg,doctor:Cs,logs:Hh,workspace:zg,project:Xg,"allow-prod":Qg,login:Jg,logout:Zg,screenshot:async(e,t)=>{let n=as(e);return n.mode==="capture"?ud(n.rest,t):n.mode==="annotate"?md(n.rest,t):n.mode==="verify"?ew(n.rest,t):n.mode==="checklist"?wr(e,t):Ki(e,t)},capture:ud,annotate:md,"capture-setup":wr,devhints:sf,inbox:bw,ask:$w,"catch-up":Sw,comments:Dw,update:Iw,reset:Fw,lint:Eu,check:kg,"style-guide":Wa,review:gy,reorder:wy,structure:sy,status:by,retire:ky,terms:xy,genre:Ga,roadmap:km,share:Rw};function Ty(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}import{spawnSync as rA}from"node:child_process";import{recordAnalyzedCommit as sA,resolveActiveProfile as iA}from"document360-engine";function aA(e){try{let t=rA("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8",timeout:1200}),n=(t.stdout||"").trim();return t.status===0&&n?n:null}catch{return null}}function Us(e,t){try{let n=aA(e);if(!n)return null;let o=iA(e,t);return sA(e,o.name,n)?n:null}catch{return null}}xn();var Ay="Or just tell me what to write or update.";function lA(e,t,n={}){let o=n.onlyScreenshots?"\u2713 Your writing is done \u2014 nothing is waiting to be written, reviewed, saved or taken live. Readers are seeing every article you have.":"\u2713 That\u2019s the full round trip \u2014 nothing is waiting to be written, reviewed, saved or taken live. Readers are seeing every article you have.";return n.listed?o:`${o}
425
+
426
+ Optional from here: ${e} of your ${t} docs campaign step${be(t)} ${e===1?"is":"are"} still open (/roadmap shows them).`}var cA="Screenshots are the only thing still open \u2014 a separate job, and none of it changes your text:",uA="Optional depth, when you want it:",dA="Writing",pA="Screenshots \u2014 a separate job from the writing";function hA(e,t){let n=t?`Press 1\u2013${e} to fill one in \u2014 nothing runs on its own.`:"Run one of the commands above when you want to.";return`Nothing is waiting${e>0?", and none of the above is owed":""}. ${e>0?`${n} `:""}I\u2019ll pick up new hints from your builder, or code that moved, next time you\u2019re in.`}var fA='\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 be(e){return e===1?"":"s"}function mA(e,t){if(!e||!t)return!1;let n=o=>o.trim().replace(/\s+/g," ").toLowerCase();return n(e)===n(t)}function $r(e,t=0){let n=t>=2?` \xB7 1\u2013${t} to pick another`:"";return e.kind==="cmd"?`\u21E5 tab to run ${e.cmd}${n} \xB7 or just ask me anything\u2026`:e.kind==="answer"&&e.options>=2?`1\u2013${e.options} to answer \xB7 or just ask me anything\u2026`:null}function Ny(e,t){return e.length===t.length&&e.every((n,o)=>n===t[o])}function Ey(e,t=150,n=1){let o=(e??"").replace(/\s+/g," ").trim();if(!o)return null;let r=/[.!?]\s+(?=["“'(A-Z])/g,s=o;for(let l=0;l<n;l++){let d=r.exec(o);if(!d)break;s=o.slice(0,d.index+1)}if(s.length<=t)return s;let i=s.slice(0,t),a=i.lastIndexOf(" ");return`${(a>t*.6?i.slice(0,a):i).replace(/[,;:]$/,"")}\u2026`}function vr(e){if(e.kind==="answer")return e.options>=2?`Answer above (1\u2013${e.options}), or say what you want instead.`:"Answer above, or say what you want instead.";let t=e.detail?` ${e.detail.replace(/\s*$/,"").replace(/([^.!?…])$/,"$1.")}`:"";return e.kind==="cmd"?`I\u2019d start with ${e.cmd} \u2014 ${e.reason}.${t}`:`Just tell me: \u201C${e.text}\u201D \u2014 ${e.reason}.${t}`}var Va={title:"What kind of product is this repo? (sets the doc-craft playbook \u2014 otherwise the docs stay generic)",lead:"Pick the genre below \u2014 one keypress, and it shapes everything I write.",exclusive:!0,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 gA(e,t){let n=[];if(e.sunsetEnv){let r=e.sunsetEnv,s=r.replacementProfile?`/profile ${r.replacementProfile}`:`/profile add ${r.replacement}`;n.push({key:"environment",bullet:`this repo publishes to the ${r.name} environment, which is being retired (${r.replacement} is the current one)`,lead:{kind:"cmd",cmd:s,reason:r.replacementProfile?`it switches to your ${r.replacement} profile (then /login if it asks)`:`it creates a ${r.replacement} profile and switches to it (then /login picks the project)`},picker:null,follow:null,tone:"warn"})}if(e.devhints!=="current"&&e.builderStarted){let r=e.devhintsToVersion?`v${e.devhintsToVersion}`:"a newer version",s=e.devhints==="stale"&&e.devhintsCompletedVersion?` (your builder is on v${e.devhintsCompletedVersion})`:"";n.push({key:"devhints",bullet:`dev\u2194docs protocol moved to ${r}${s} \u2014 your docs aren\u2019t blocked`,lead:{kind:"cmd",cmd:"/devhints",reason:`one paste updates your builder to ${r}`},picker:null,follow:"Also run /devhints when you get a second \u2014 your builder\u2019s protocol is behind.",tone:"warn"})}if(e.genreUnknown&&n.push({key:"genre",bullet:"the doc genre isn\u2019t set \u2014 I can\u2019t load the right doc-craft playbook yet",lead:null,picker:Va,follow:"Then pick the doc genre below (it sets the playbook I write with)."}),e.styleRules){let r=e.styleRules.articles;n.push({key:"styleRules",bullet:r>0?`the writing rules for these docs were never settled \u2014 and ${r} article${be(r)} ${r===1?"is":"are"} already written to them`:"the writing rules for these docs aren\u2019t settled yet \u2014 worth answering before I write anything",lead:null,picker:{title:r>0?`Which writing rules should these docs follow? (${r} article${be(r)} already written \u2014 changing this later means rewriting them)`:"Which writing rules should these docs follow? (this shapes every article I write)",lead:r>0?"Settle the writing rules below \u2014 one keypress. Keeping what you have is the usual answer once articles exist.":"Settle the writing rules below \u2014 one keypress, before I write anything to them.",exclusive:!0,options:e.styleRules.presets},follow:"Then settle the writing rules below \u2014 it shapes every article, and it gets dearer to change the longer it waits."})}if(e.discovery&&e.discovery.status!=="confident"){let r=e.discovery.openQuestions;e.discovery.status==="pending"?n.push({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/push steps)."}):r>0?n.push({key:"discovery",bullet:`product discovery is waiting on ${r} answer${be(r)} 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."}):e.discovery.answersPending===0&&n.push({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 r=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",s=[];e.directives>0&&s.push(`${e.directives} owner directive${be(e.directives)} waiting`);let i=e.discovery&&e.discovery.status!=="confident"?e.discovery.answersPending:0,a=i>0?` (${i} settle${i===1?"s":""} the product brief)`:"";e.pendingText&&s.push(`your builder left ${e.pendingText}${a}`),n.push({key:"catchup",bullet:s.join(`
427
+ \u2022 `),lead:{kind:"cmd",cmd:"/catch-up",reason:r},picker:null,follow:"Then /catch-up clears what\u2019s queued for the docs.",dependsOn:["discovery"]})}if(e.openComments>0){let r=e.openComments;n.push({key:"comments",bullet:`${r} reviewer comment${be(r)} waiting on your articles`,lead:{kind:"cmd",cmd:"/comments",reason:"it shows what reviewers marked up in the portal, then lets you take it an article at a time"},picker:null,follow:`Then /comments shows the ${r} reviewer comment${be(r)} waiting on your articles.`})}if(e.conflicts>0){let r=e.conflicts;n.push({key:"resolve",bullet:`${r} article${be(r)} changed both here and on Document360 \u2014 /push skips ${r===1?"it":"these"}, and an audit can't trust your local copy until ${r===1?"it is":"they are"} settled`,lead:{kind:"cmd",cmd:"/resolve",reason:"it walks each one with you \u2014 keep yours, take the portal's, or skip"},picker:null,follow:`Then /resolve settles the ${r} article${be(r)} changed in both places (keep yours / take the portal's / skip).`})}if(e.behind>0){let r=e.behind;n.push({key:"audit",bullet:`${r} code change${be(r)} 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 ${r} newer commit${be(r)}.`,blockedBy:["resolve"]})}if(e.hasDocs&&e.pendingWrites>0){let r=e.pendingWrites;n.push({key:"write",bullet:`${r} planned article${be(r)} still unwritten`,lead:{kind:"cmd",cmd:"/write",reason:"it finishes the articles already planned"},picker:null,follow:`Then /write finishes the ${r} planned article${be(r)}.`,dependsOn:["genre","discovery","catchup","audit"]})}if(e.unreviewed>0){let r=e.unreviewed,s=Ce("/review","--blocked --fix",e.unreviewedScope);n.push({key:"review",bullet:`${r} article${be(r)} not yet live ${r===1?"carries":"carry"} text no editor has read`,lead:{kind:"cmd",cmd:s,reason:"these were written by an AI \u2014 it reads each one and applies its fixes, and nothing can be sent up or taken live until it has"},picker:null,follow:`Then ${s} reviews the ${r} unreviewed article${be(r)} \u2014 nothing reaches your readers until it has.`,dependsOn:["catchup","comments"]})}if(e.styleErrors>0){let r=e.styleErrors,s=Ce("/lint","--blocked --fix",e.styleErrorScope);n.push({key:"styleguide",bullet:`${r} article${be(r)} not yet live break${r===1?"s":""} house style rules that block publishing`,lead:{kind:"cmd",cmd:s,reason:"finding them costs nothing and one pass corrects them in place \u2014 nothing can be sent up or taken live until it has"},picker:null,follow:`Then ${s} clears the style errors on ${r} article${be(r)} \u2014 nothing reaches your readers until it has.`,dependsOn:["catchup","comments","review"]})}let o=e.shotsToAnnotate>0?{key:"annotate",bullet:`${e.shotsToAnnotate} screenshot${be(e.shotsToAnnotate)} ${e.shotsToAnnotate===1?"has":"have"} been taken but ${e.shotsToAnnotate===1?"is":"are"} not finished \u2014 the callouts aren't drawn on, so ${e.shotsToAnnotate===1?"it cannot":"they cannot"} be published`,lead:{kind:"cmd",cmd:"/screenshot annotate",reason:"it draws the callouts on \u2014 no browser, about a second per picture"},picker:null,follow:`Then /screenshot annotate finishes the ${e.shotsToAnnotate} screenshot${be(e.shotsToAnnotate)} already taken.`}:e.shotsToRecapture>0?{key:"annotate",bullet:`${e.shotsToRecapture} screenshot${be(e.shotsToRecapture)} ${e.shotsToRecapture===1?"has":"have"} a plan for what to point at but no picture \u2014 the picture has to be taken again before anything can be drawn on it`,lead:{kind:"cmd",cmd:"/screenshot capture",reason:"it takes the picture again in a browser, and the callouts are drawn on straight after"},picker:null,follow:`Then /screenshot capture re-takes the ${e.shotsToRecapture} missing picture${be(e.shotsToRecapture)}.`}:null;if(o&&e.localAhead>0&&n.push(o),e.localAhead>0){let r=e.localAhead;n.push({key:"publish",bullet:`${r} article${be(r)} changed locally \u2014 ready to send to Document360`,lead:{kind:"cmd",cmd:"/push",reason:`it saves your ${r} local edit${be(r)} to Document360 as drafts`},picker:null,follow:`Then /push saves your ${r} local edit${be(r)} to Document360.`,dependsOn:["discovery","comments","audit","annotate"],blockedBy:["review","styleguide"]})}if(e.draftAhead>0){let r=e.draftAhead;n.push({key:"golive",bullet:`${r} article${be(r)} ${r===1?"is":"are"} saved on Document360 but not live \u2014 your readers still see the previous version`,lead:{kind:"cmd",cmd:"/publish",reason:`it takes the ${r} draft${be(r)} live to your readers \u2014 it lists them and asks first`},picker:null,follow:`Then /publish takes the ${r} draft${be(r)} live \u2014 until it does, readers see the previous version.`,dependsOn:["comments"],blockedBy:["review","styleguide"]})}if(o&&e.localAhead===0&&n.push(o),e.hasDocs&&e.roadmap?.next){let r=e.roadmap,s=r.next,i=s.run?t?.scaleFor?.(s.run)??null:null,a=s.run?i:Ey(s.body),l=s.run?i??void 0:Ey(s.body,340,2)??void 0,d=`docs campaign: ${r.done} of ${r.total} step${be(r.total)} done`,w=!!s.run&&mA(s.run,e.lastCommand);n.push(w?{key:"roadmap",bullet:`${d} \u2014 \u201C${s.title}\u201D is waiting on you
428
428
  \u2022 You just ran ${s.run}. It showed you where things stand; the step stays open until you act on what it showed, or close it with /roadmap done.`,lead:null,picker:null,follow:null}:{key:"roadmap",bullet:`${d} \u2014 next: ${s.title}${a?`
429
429
  \u2022 ${a}`:""}`,lead:s.run?{kind:"cmd",cmd:s.run,reason:"it\u2019s the next step of your docs campaign",...l?{detail:l}:{}}:{kind:"prompt",text:s.title,reason:"it\u2019s the next step of your docs campaign",...l?{detail:l}:{}},picker:null,follow:`Then the campaign continues: ${s.title} (/roadmap shows all ${r.total} steps).`,dependsOn:["genre","discovery","audit"],rowBullet:`${d} \u2014 this is next${a?`
430
430
  \u2022 ${a}`:""}`})}if(e.handoff){let r=Math.max(e.handoff.unpushed,e.handoff.uncommitted>0?1:0),s=e.handoff.unpushed;r>0&&e.handoff.pushConsent==="unconfirmed"?n.push({key:"share",bullet:e.shareExplained?"your docs work is saved on this machine only \u2014 your team can't see it yet":["your docs work is saved on this machine only \u2014 your team can't see it yet","d360-writer keeps everything it produces in .d360-writer/ \u2014 your articles, the map linking","them to Document360, and the channel your builder leaves hints and answers in. It saves that","to git for you automatically, but it won't send anything to your team until you say so."].join(`
431
- `),lead:{kind:"cmd",cmd:"/share",reason:"it sends your saved work to your team and brings back your builder's latest; after this once, I keep doing it for you"},picker:null,follow:null}):s>0&&n.push({key:"share",bullet:`\u26A0 ${s} docs change set${ye(s)} saved but not sent \u2014 someone else pushed to this branch first (your work is safe)`,lead:{kind:"cmd",cmd:"/share",reason:"it retries sending your saved work; if it keeps failing, your builder can merge the branch"},picker:null,follow:null})}else if(e.uncommittedDocs>0){let r=e.uncommittedDocs;n.push({key:"commit",bullet:`\u26A0 ${r} uncommitted change${ye(r)} under .d360-writer/ \u2014 tell your coding agent: "commit d360-writer's work"`,lead:null,picker:null,follow:null})}return n}function Ty(e){return e.find(t=>t.lead||t.picker)??null}function cA(e){return e.kind==="cmd"?e.cmd:e.kind==="prompt"?`\u201C${e.text}\u201D`:""}function Us(e){return e.kind==="cmd"?e.cmd:e.kind==="prompt"?e.text:null}function uA(e){return Us(e)??""}function dA(e,t,n){let o=a=>(a??[]).map(l=>t.get(l)).filter(l=>l!==void 0&&l<n),r=a=>a.length===1?`${a[0]}`:`${a.slice(0,-1).join(", ")} and ${a[a.length-1]}`,s=o(e.blockedBy);if(s.length>0)return` (needs ${r(s)} first)`;let i=o(e.dependsOn);return i.length>0?` (better after ${r(i)})`:""}function Ga(e,t,n,o=null,r,s=0){if(r&&r.length>0){let v=r.filter(zi),C=r.filter(M=>!zi(M)),T=[...C,...v],D=(M,X)=>` ${X+1}. ${M.title}${M.run?` \xB7 ${M.run}`:""}`,L;return v.length===0||C.length===0?L=[e,...T.map(D)].join(`
432
- `):L=[e,"",` ${oA}`,...C.map((M,X)=>D(M,X)),"",` ${rA}`,...v.map((M,X)=>D(M,C.length+X))].join(`
433
- `),{note:[...o?[o]:[],L,sA(T.length,n),Cy].join(`
434
-
435
- `),menu:T.map(M=>M.run??M.title)}}let i=Ty(t),a=i?.picker?[]:t.filter(v=>v.lead),l=a.length>=2?a:[],d=new Map(l.map((v,C)=>[v.key,C+1])),g=[];i?.lead?g.push($r(i.lead)):i?.picker&&g.push(i.picker.lead);for(let v of t.filter(C=>C!==i&&!C.lead).slice(0,2))v.follow&&g.push(v.follow);l.length>=2&&n&&g.push(`Press 1\u2013${l.length} to pick a different one \u2014 the number fills the box, enter runs it.`);let w=g.join(" "),k=t.filter(v=>v.bullet).map(v=>{let C=d.get(v.key),[T="",...D]=(C&&v.lead?.kind==="prompt"&&v.rowBullet?v.rowBullet:v.bullet).split(`
436
- \u2022 `),L=v===i&&v.lead?.kind!=="answer"&&v.lead?.detail?[]:D;if(C&&v.lead){let X=T.replace(/^→\s+/,"");return[` ${C}. ${cA(v.lead)} \u2014 ${X}${dA(v,d,C)}`,...L.map(de=>` ${de}`)].join(`
437
- `)}let B=v.lead?.kind==="cmd"?v.lead.cmd:null;return` \u2022 ${[T,...L].join(`
438
- \u2022 `)}${B&&!w.includes(B)?` \u2014 ${B}`:""}`}),S=o?[o,[e,...k].join(`
439
- `)]:[[e,...k].join(`
440
- `)];if(g.length&&S.push(g.join(" ")),s>0){let v=s;S.push(`${v} question${ye(v)} you asked your developers ${v===1?"is":"are"} still unanswered. Their reply arrives with your docs the next time either of you shares, and /inbox folds it in. Nothing is blocked meanwhile.`)}return S.push(Cy),{note:S.join(`
441
-
442
- `),menu:l.map(v=>uA(v.lead))}}function Ws(e,t){let n=t?.pickable===!0,o=S=>t?.header?`${t.header}
443
-
444
- ${S}`:S;if(!e.ready)return{kind:"idle"};if(e.pendingAnswer)return{kind:"recommend",rec:{note:null,settled:null,tone:"info",lead:e.pendingAnswer.options>=2?{kind:"answer",options:e.pendingAnswer.options,reason:"the agent is waiting on your pick"}:null,picker:null,menu:[]}};let r=lA(e,t),s=r.length===1&&r[0].key==="roadmap"&&!!r[0].lead&&!!e.roadmap&&!!e.roadmap.next,i=s?e.roadmap.open?.length?e.roadmap.open:[e.roadmap.next]:[],a=i.length>0&&i.every(zi)&&e.roadmap.total-e.roadmap.done===i.length,l=s?eA(e.roadmap.total-e.roadmap.done,e.roadmap.total,{listed:i.length>0,onlyScreenshots:a}):null;if(!e.hasDocs){let S=Ty(r);if(S&&(S.lead?.kind==="cmd"||S.picker)){let v=Ga(t?.header??"\u{1F4ED} No docs yet for this repo \u2014 here\u2019s where things stand:",r,n,null,void 0,e.outboundQuestions);return{kind:"recommend",rec:{note:v.note,settled:null,tone:S.tone??"info",lead:S.lead,picker:S.picker,menu:v.menu}}}return{kind:"recommend",rec:{note:o(iA),settled:null,tone:"info",lead:{kind:"prompt",text:"write the docs for this repo",reason:"I\u2019ll read the code and draft a structure"},picker:null,menu:[]}}}if(r.length===0){let S=e.roadmap&&!e.roadmap.next?` Docs campaign complete \u2014 all ${e.roadmap.total} step${ye(e.roadmap.total)} done (/roadmap).`:"";return{kind:"recommend",rec:{note:o(`Welcome back. Your ${e.tracked} tracked article${ye(e.tracked)} for \u201C${e.profileName}\u201D are all in sync \u2014 /audit re-checks the code, /pull brings down portal edits.${S}`),settled:null,tone:"info",lead:null,picker:null,menu:[]}}}let d=r.filter(S=>S.lead||S.picker),g=d[0]??null;if(!g){let S=Ga(t?.header??"Welcome back \u2014 where your docs stand:",r,n,null,void 0,e.outboundQuestions);return{kind:"recommend",rec:{note:S.note,settled:null,tone:"info",lead:null,picker:null,menu:S.menu}}}if((g.key==="audit"||d[1]?.key==="audit")&&e.behind>0&&e.autoAudit&&e.allowAutoAudit)return{kind:"autoAudit",note:o(`\u{1F4CB} ${e.behind} code change${ye(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`)};if(l){let S=Ga(a?tA:nA,r,n,l,i,e.outboundQuestions);return{kind:"recommend",rec:{note:S.note,settled:l,tone:"info",lead:null,picker:null,menu:S.menu}}}let k=Ga(t?.header??"Welcome back \u2014 where your docs stand:",r,n,l,void 0,e.outboundQuestions);return{kind:"recommend",rec:{note:k.note,settled:l,tone:g.tone??"info",lead:g.lead,picker:g.picker,menu:k.menu}}}import{existsSync as Va,readdirSync as rp}from"node:fs";import{spawnSync as pA}from"node:child_process";import{join as Ya}from"node:path";import{readProjectConfig as op,resolveActiveProfile as Ny,loadTokens as hA,isExpired as fA,loadProfileMap as Dy,localAheadPaths as mA,loadKnownConflicts as gA,draftPendingPaths as wA,loadOpenCommentCount as yA,readDocsPlan as bA,devHintsGuidePath as kA,DEFAULT_DOCS_DIR as Ka,roadmapProgress as $A,listRoadmap as Ay,readProductBriefState as vA,readDiscoveryQueue as xA,reconcileCommitRequest as RA,reconcileTestidRequest as CA,snapshotHandoff as SA,shareExplainedPath as PA,unannotatedShotIds as TA,shotsNeedingRecapture as AA,resolveOutputDir as EA,DEFAULT_OUTPUT_DIR as NA,WRITER_DIRNAME as np,styleGuideSettled as DA,listAvailablePacks as jA,listArticleFiles as IA}from"document360-engine";xn();var LA=5;function Ey(e){try{return rp(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function sp(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>Ey(Ya(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&Ey(Ya(e,o)))}function ip(e,t){try{let n=op(e);if(!n)return!1;let o=Ny(e,t),r=Dy(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=Ya(e,(n.docsDir??Ka).replace(/\/+$/,""));return!!(Va(s)&&rp(s).length>0||Va(kA(e)))}catch{return!1}}function OA(e){let t=[`:(exclude)${np}`],n=(e.docsDir??Ka).replace(/\\/g,"/").replace(/\/+$/,"");return n&&!n.startsWith(`${np}/`)&&n!==np&&t.push(`:(exclude)${n}`),t}function _A(e,t,n){try{let o=pA("git",["rev-list","--count",`${t}..HEAD`,"--",".",...OA(n)],{cwd:e,encoding:"utf8",timeout:1200});return o.status===0&&parseInt((o.stdout||"").trim(),10)||0}catch{return 0}}function Bs(e,t,n){try{let o=op(e);if(!o)return null;let r=Ny(e,t),s=hA(r.name,r.project.projectId),i=!!s&&(!fA(s)||!!s.refreshToken),a=ip(e,t)||!sp(e,o.authoritativeSourceFiles),l=Dy(e,r.name),d=l?Object.keys(l.articles).length:0,g=Ya(e,(o.docsDir??Ka).replace(/\/+$/,"")),w=!1;try{w=Va(g)&&rp(g).length>0}catch{}let k=l?.lastAnalyzedCommit?_A(e,l.lastAnalyzedCommit,o):0,S=0;try{let Ae=(o.docsDir??Ka).replace(/\/+$/,""),Ue=bA(e,Ae);Ue.length>0&&(S=Pn(e,Ae,Ue.map(Et=>Et.path)).length)}catch{}let v=pn(e),C=Aa({...v,directives:0}),T=mA(e,t),D=new Set(gA(e,r.name)),L=T.filter(Ae=>D.has(Ae)).length,B=T.length-L,M=new Set(T),X=wA(e,t).filter(Ae=>!M.has(Ae)),z=X.length,de=[...T.filter(Ae=>!D.has(Ae)),...X],be=ps(e,de),$e=be.length,Ce=Yt(be),fe=null;try{if(!DA(o.styleGuide)){let Ae=jA(e).filter(Ue=>Ue.name.toLowerCase()!=="humanise");fe={articles:IA(e).length,presets:[{cmd:"/style-guide keep",desc:"the built-in rules only \u2014 correctness and anti-slop checks (nothing changes)"},...Ae.map(Ue=>({cmd:`/style-guide use ${Ue.name.toLowerCase()}`,desc:`${Ue.name} style guide \u2014 ${Ue.rules.length} more rules`}))]}}}catch{}let se=0,ee;try{let Ae=Tm(e,de);se=Ae.length,ee=Yt(Ae)}catch{}let ge=0,ke=0;try{let Ae=EA(e,op(e)?.outputDir??NA);ge=TA(Ae).length,ke=AA(Ae).length}catch{}let Ye=yA(e,r.name),fn=Ut(e),mn=$A(e),At=mn?{...mn,open:Ay(e).filter(Ae=>Ae.status==="open").slice(0,LA).map(Ae=>({title:Ae.title,...Ae.run?{run:Ae.run}:{},...Ae.stage?{stage:Ae.stage}:{}}))}:null,gt=SA(e,o),Dr=RA(e,new Date().toISOString(),{supersededByHandoff:gt!==null});CA(e,new Date().toISOString());let tt=kn(e,t),$o=tt?{name:tt.name,replacement:tt.replacement,replacementProfile:tt.replacementProfile}:null,Wn=vA(e),vo=xA(e),xo=Wn?{status:Wn.status,openQuestions:vo.openQuestions,answersPending:vo.answersPending}:null;return!xo&&w&&Ay(e).some(Ue=>Ue.status==="open"&&(Ue.run??"").trim()==="/discover")&&(xo={status:"pending",openQuestions:0,answersPending:0}),{ready:i&&a&&!n.claudeMissing,hasDocs:w,tracked:d,pendingText:C,directives:v.directives,behind:k,pendingWrites:S,localAhead:B,unreviewed:$e,unreviewedScope:Ce,styleErrors:se,shotsToAnnotate:ge,shotsToRecapture:ke,styleErrorScope:ee,draftAhead:z,conflicts:L,openComments:Ye,outboundQuestions:Es(e),autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:fn.status,devhintsCompletedVersion:fn.completedVersion,devhintsToVersion:Ie,builderStarted:an(e),genreUnknown:n.genreUnknown,pendingAnswer:n.pendingAnswer??null,lastCommand:n.lastCommand??null,styleRules:fe,roadmap:At,discovery:xo,uncommittedDocs:Dr.dirty.length,handoff:gt,shareExplained:Va(PA(e)),sunsetEnv:$o}}catch{return null}}re();import{existsSync as UA,readFileSync as WA}from"node:fs";import{isAbsolute as BA,join as HA}from"node:path";import{DEFAULT_DOCS_DIR as GA,findPathByArticleId as qA,isArticleDocPath as VA,loadProfileMap as YA,readProjectConfig as KA,resolveActiveProfile as zA}from"document360-engine";function MA(){return process.platform==="win32"||process.platform==="darwin"}var FA=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function za(e,t){let n=e.replace(/\\/g,"/"),o=`${FA(t)}/`,[r,s]=MA()?[n.toLowerCase(),o.toLowerCase()]:[n,o];return r.startsWith(s)?n.slice(o.length):null}var XA=70;function QA(e,t){return{docsRoot:()=>(KA(e)?.docsDir??GA).replace(/\\/g,"/").replace(/\/+$/,""),read:n=>{try{let o=BA(n)?n:HA(e,n);return UA(o)?WA(o,"utf8"):null}catch{return null}},pathForArticleId:n=>{try{let o=YA(e,zA(e,t).name);return o?qA(o,n):null}catch{return null}}}}var Hs=(e,t=XA)=>{let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"};function Gs(e){if(!e)return null;let t=!1;for(let n of e.split(`
445
- `)){let o=n.trimEnd();if(/^\s*(```|~~~)/.test(o)){t=!t;continue}if(t)continue;let r=/^#\s+(\S.*)$/.exec(o);if(r)return Hs(r[1])}return null}var JA=new Set(["a","an","and","as","at","but","by","for","in","of","on","or","the","to","vs","with"]),ZA=new Set(["ai","api","cli","css","csv","dfm","faq","html","http","https","id","json","mcp","pdf","sdk","sso","ui","url","ux","yaml","ado","qa"]);function jy(e,t,n){let o=e.toLowerCase();return ZA.has(o)?e.toUpperCase():!t&&JA.has(o)?o:!t&&!n?e:e.charAt(0).toUpperCase()+e.slice(1)}var Iy=e=>e.replace(/^\d+[-_.]/,"").split(/[-_]/).filter(Boolean);function eE(e){let t=Iy(e);return t.length===0?e:t.map((n,o)=>jy(n,o===0,!0)).join(" ")}function Ly(e){let t=typeof e=="string"&&e?e.replace(/\\/g,"/"):null;if(!t)return null;let n=t.split("/").filter(Boolean);return n.length<2?null:eE(n[n.length-2])}function Oy(e){let t=e.replace(/\\/g,"/").split("/").pop()??e,n=Iy(t.replace(/\.(md|markdown)$/i,""));return n.length===0?t:n.map((o,r)=>jy(o,r===0,!1)).join(" ")}var Tt=e=>typeof e=="string"&&e?e:null,tE=e=>typeof e=="string"&&e.length>=8?`id ${e.slice(0,8)}\u2026`:null;function nE(e,t){return za(e,t)??e.replace(/\\/g,"/")}function oE(e,t){let n=Rt(e,t,200);return n?`+${n.added} \u2212${n.removed}`:"no change"}var rE=new Set(["Edit","MultiEdit","Write"]);function sE(e,t,n,o){if(!rE.has(e))return null;let r=Tt(t.file_path);if(!r)return null;let s=nE(r,n),i=o.docsRoot();if(!(s===i||s.startsWith(`${i}/`)))return null;let a=s.slice(i.length+1);if(!a||!VA(a))return null;let l=Ly(a),d=o.read(s),g=v=>Gs(v)??Gs(d)??Oy(a);if(e==="Write"){let v=Tt(t.content)??"",C=g(v);if(d===null){let T=v.replace(/\n$/,"").split(`
446
- `).length;return{verb:"Draft",title:C,category:l,note:`new, ${T} lines`}}return{verb:"Rewrite",title:C,category:l,note:oE(d,v)}}let w=Array.isArray(t.edits)?t.edits.map(v=>({from:Tt(v.old_string)??"",to:Tt(v.new_string)??""})):[{from:Tt(t.old_string)??"",to:Tt(t.new_string)??""}],k=w.reduce((v,C)=>{let T=Rt(C.from,C.to,200);return T?{added:v.added+T.added,removed:v.removed+T.removed}:v},{added:0,removed:0}),S=k.added===0&&k.removed===0?"no change":`+${k.added} \u2212${k.removed}`;return{verb:"Update",title:g(w.map(v=>v.to).join(`
447
- `)),category:l,note:S}}function iE(e,t,n){let o=()=>{let r=Tt(t.article_id),s=r?n.pathForArticleId(r):null;return(s?Gs(n.read(s)):null)??(s?Oy(s):tE(r)??"article")};switch(e){case"d360_create_article":{let r=Tt(t.title);return r?{verb:"Create",title:Hs(r),category:Ly(t.local_path),note:"Document360 draft"}:null}case"d360_update_article":return{verb:"Update",title:Tt(t.title)?Hs(Tt(t.title)):o(),category:null,note:"Document360 draft"};case"d360_fork_article":return{verb:"Fork",title:o(),category:null,note:"new Document360 draft"};case"d360_publish_article":{let r=t.version_number;return{verb:"Publish",title:o(),category:null,note:typeof r=="number"?`v${r}`:null,loud:"LIVE"}}case"d360_unpublish_article":return{verb:"Unpublish",title:o(),category:null,note:"back to draft, removed from readers"};case"d360_create_category":{let r=Tt(t.name);return r?{verb:"Create",title:Hs(r),category:null,note:"Document360 category"}:null}case"d360_upload_drive_file":{let r=Tt(t.file_path);if(!r)return null;let s=r.replace(/\\/g,"/").split("/").pop()??r;return{verb:"Upload",title:Hs(s),category:null,note:"Document360 Drive",keepResult:!0}}default:return null}}function Xa(e,t,n,o,r=QA(n,o)){try{let s="mcp__document360__";return e.startsWith(s)?iE(e.slice(s.length),t,r):sE(e,t,n,r)}catch{return null}}var aE={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"},My=160,ap=200,Fy=40;function Mn(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:lE(n)?"\u2026"+n.slice(n.length-(t-1)):n.slice(0,t-1)+"\u2026"}function lE(e){return!e.includes(" ")&&/[/\\]/.test(e)}function _y(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}: ${Mn(typeof r=="string"?r:JSON.stringify(r),Fy)}`);return t.length>4&&n.push("\u2026"),Mn(n.join(", "),My)}var cE=new Set(["file_path","notebook_path"]);function uE(e,t){return t?za(e.replace(/\\/g,"/").replace(/\/+$/,""),t)??e:e}var Uy=e=>typeof e=="string"&&e?e:null;function dE(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});return e==="d360_sync_status"?n("Check sync status",null):null}function Qa(e,t,n){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,s="",...i]=e.split("__"),a=i.join("__");if(s==="document360"){let g=dE(a,t);if(g)return g}let l=a.replace(/^d360_/,"").replace(/_/g," ");return{title:`${s==="document360"?"Document360":s.charAt(0).toUpperCase()+s.slice(1)}: ${l}`,sep:" ",arg:_y(t)}}let o=aE[e],r=o?t[o]:void 0;if(typeof r=="string"&&r){let s=o&&cE.has(o)?uE(r,n):r;return{title:e,sep:"",arg:Mn(s,My)}}return{title:e,sep:"",arg:_y(t)}}function pE(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 hE(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(pE).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>Mn(r,ap))]}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}: ${Mn(String(r),Fy)}`);return n.length>0?[Mn(n.join(" \xB7 "),ap)]:null}return null}function fE(e){let t=Uy(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function mE(e,t,n){switch(e){case"d360_create_article":{let o=fE(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=Uy(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 ${Mn(o[0],120)}`:""}`]}default:return null}}var Wy=new Set(["Edit","Write","MultiEdit","NotebookEdit"]);function gE(e){return e.replace(/^\s*\d+\t/,"")}function wE(e,t){if(Wy.has(e))return[];let n=t.split(`
448
- `);if(e==="Read"){let o=n.length,r=Gs(n.map(gE).join(`
449
- `));return[`${o} line${o===1?"":"s"}${r?` \xB7 ${r}`:""}`]}if(e==="Glob"){if(/^no files found/i.test(t))return null;let o=n.filter(r=>r.trim()).length;return[`${o} file${o===1?"":"s"}`]}return e==="Grep"&&/^Found \d+/.test(n[0]??"")?[n[0]]:null}function Ja(e,t=4,n,o){let r=e.replace(/\r\n/g,`
450
- `).trimEnd();if(n&&Wy.has(n))return{lines:[],hidden:0};if(!r)return{lines:["(no output)"],hidden:0};if(n&&!n.startsWith("mcp__")){let i=wE(n,r);if(i)return{lines:i,hidden:0}}if(n?.startsWith("mcp__document360__")){let i=mE(n.slice(18),o,r);if(i)return{lines:i,hidden:0}}let s=hE(r)??r.split(`
451
- `);return{lines:s.slice(0,t).map(i=>Mn(i,ap)),hidden:Math.max(0,s.length-t)}}function Za(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function el(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 By(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 tl(e){return By(e,"url")}function nl(e){return By(e,"preview_url")}function Hy(e,t){try{let o=JSON.parse(t),s=(Array.isArray(o)?o[0]:o)?.title;if(typeof s=="string"&&s.trim())return s.trim()}catch{}if(typeof e.title=="string"&&e.title.trim())return e.title.trim();let n=e.local_path;return typeof n=="string"&&n.trim()?(n.replace(/\\/g,"/").split("/").pop()??n).replace(/\.(md|markdown)$/i,""):null}var zy=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/,cp=null;function qy(){return cp===null&&(cp=PE().verboseTranscript===!0),cp}function WE(e,t,n,o){if(zy.test(e))try{let r=Ky(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,i=el(t,n),a=tl(n);e.endsWith("publish_article")&&a&&console.log(Z(` \u2B95 Live: ${a}`));let l=nl(n);l?console.log(Z(` \u2B95 Preview: ${l}`)):i&&s&&console.log(Z(` \u2B95 Preview: ${Za(r.connection.portalUrl,s,i,r.project.languageCode??"en")}`))}catch{}}async function Xy(e=process.cwd(),t="auto",n,o){let r=bE(t);r.kind==="none"&&(console.error(""),console.error(O("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${Z("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${Z('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${Z("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${Z("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),BE(e,n),r.kind==="subscription"&&(r.stored?console.log(f(" Using your Claude subscription (no API key set).")):console.log(f(" No API key or stored Claude Code login found \u2014 trying your Claude session anyway.")),console.log(""));let s=!1,i=lp({cwd:e,profileName:n,allowProdWrites:s}),a={uuid:null,firstPrompt:null,titleFired:!1},l=yE({input:process.stdin,output:process.stdout}),d=[],g=null,w=!1;l.on("line",v=>{if(g){let C=g;g=null,C(v)}else d.push(v)}),l.on("close",()=>{if(w=!0,g){let v=g;g=null,v(null)}});function k(){return d.length>0?Promise.resolve(d.shift()):w?Promise.resolve(null):(process.stdout.write(Z("> ")),new Promise(v=>{g=v}))}let S={cwd:e,version:o,profileName:n,allowProdWrites:()=>s,restartAgent:()=>{i.close(),i=lp({cwd:e,profileName:n,allowProdWrites:s}),a={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>a.uuid,setPendingName:v=>{a.pendingName=v},setModel:async v=>i.setModel(v),withPausedInput:async v=>{l.pause();try{return await v()}finally{l.resume()}}};try{for(;;){let v=await k();if(v===null)break;let C=v.trim();if(C){if(C.startsWith("/")){let T=Ry(C);if(!T)continue;let D=xy[T.name];if(!D){console.log(O(`Unknown command: /${T.name}`)),console.log(f("Type /help for the list."));continue}let L=await D(T.args,S);if(L.kind==="exit")break;if(L.kind==="clear"){S.restartAgent();continue}if(L.kind==="allow-prod"){s=!0,S.restartAgent(),console.log(q("\u2713 Production writes authorized for this session.")),console.log("");continue}if(L.kind==="resume"){i.close(),i=lp({cwd:e,resume:L.uuid,profileName:n,allowProdWrites:s});let B=kE(L.uuid);a={uuid:L.uuid,firstPrompt:B?.firstPrompt??null,titleFired:!0},Yy(L.uuid),console.log(q(`\u2713 Resumed "${L.name}"`)),console.log("");continue}if(L.kind==="audit-blocked"){console.log(H(L.note)),console.log(f(` Run: ${L.lead.cmd} \u2014 ${L.lead.reason}.`)),console.log("");continue}if(L.kind==="forward-to-agent"){a.firstPrompt||(a.firstPrompt=L.display??L.prompt);let B=L.display??"",M=B.trim().split(/\s+/),X=pg(B),z=X?_E(e,hg(B)):[],de=M[0]==="/screenshot"&&(M[1]==="verify"||M[1]==="review"),be=de?M[2]&&!M[2].startsWith("--")?[M[2]]:Cs(_e(e)):[],$e=M[0]==="/catch-up"&&!X,Ce=$e?OE(e):null,fe=$e?pn(e):null,se=$e?Ds(e).hold:!1,ee=L.prompt;if(B.startsWith("/"))try{let ge=Xi(e,B);ge&&(ee=`${ee}
452
-
453
- ${ge}`)}catch{}if(await up(i,ee,r,a,e,n),X)try{LE(e,z,it(X))}catch{}if(Ce){let ge=fo(e,Ce,"",M[0]);if(ge.cta)console.log(f(ge.cta.text));else if(fe){let ke=Ea({queued:fe,hold:se});ke.note&&console.log(ke.tone==="warn"?H(ke.note):f(ke.note)),ke.lead&&console.log(f(` Run ${ke.lead.cmd} \u2014 ${ke.lead.reason}.`))}}if(M[0]==="/audit"&&!M.includes("--auto")&&Fs(e,n),de&&be.length>0)try{for(let ge of fr(e,be))console.log(ge)}catch{}if(M[0]==="/push"){let ge=await ds(e,n);ge&&console.log(f(ge))}if((M[0]==="/catch-up"||M[0]==="/document")&&(M.includes("--push")||M.includes("--publish")))try{let ge=await UE({cwd:e,profileName:n}),{clean:ke,conflicts:Ye}=lo(ge.entries);ke.length===0?console.log(f("Nothing new to push \u2014 everything is already up to date on Document360.")):await Wt(S,ke.map(fn=>fn.path),Ye.length,{skipReview:M.includes(xt)})}catch(ge){console.log(H(`Couldn't check what to push (${ge.message}) \u2014 your drafts are saved; run /push when ready.`))}}else L.kind==="continue"&&L.ownNext||HE(e,n);continue}if(NE(C)){let T=DE(C);if(T){try{jE(e,{title:T,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}a.firstPrompt||(a.firstPrompt=C),await up(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,a,e,n);continue}}a.firstPrompt||(a.firstPrompt=C),await up(i,C,r,a,e,n)}}}finally{i.close(),l.close()}}function BE(e,t){console.log(""),console.log(Zr("document360-writer")),console.log(f(` cwd: ${e}`));let n=CE(e);if(console.log(f(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(GE(e,t)),!SE(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(Si(e),!an(e))for(let r of Pi(e))console.log(H(` ${r}`))}catch{}try{let r=TE(e);r.persisted&&r.appType?console.log(f(` \u2713 Detected a ${r.appType} app \u2014 enabled the ${r.appType}-doc-playbook (change with /genre).`)):r.source==="unknown"&&(o=!0)}catch{}try{let r=IE(e);for(let s of vi(r.applied))console.log(H(` ${s}`));if(r.reopenedForRedaction)for(let s of xi(r.reopenedForRedaction).split(/\r?\n/))console.log(H(` ${s}`))}catch{}try{let r=Bs(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:o}),s=r?Ws(r,{pickable:!1,scaleFor:i=>On(e,i)}):null;if(s?.kind==="recommend"&&s.rec.note){let i=s.rec.tone==="warn"?H:f;for(let a of fa(s.rec.note).split(`
454
- `))console.log(i(` ${a}`));s.rec.picker&&console.log(Z(` Pick one: ${s.rec.picker.options.map(a=>a.cmd).join(" \xB7 ")}`))}}catch{}}console.log(f(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}var Vy=!1;function HE(e,t){try{let n=Bs(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:!1}),o=n?Ws(n,{scaleFor:r=>On(e,r)}):null;if(o?.kind!=="recommend")return;if(o.rec.settled&&!Vy){Vy=!0;for(let r of fa(o.rec.settled).split(`
455
- `))console.log(q(` ${r}`))}else o.rec.settled&&!o.rec.lead&&console.log(f(" Nothing is waiting. /roadmap lists the optional campaign steps."));o.rec.lead&&console.log(f(` Next: ${$r(o.rec.lead)}`))}catch{}}function GE(e,t){try{let n=Ky(e,t),o=n.production?H(" \u26A0 PRODUCTION"):"",r=EE(n.name,n.project.projectId);if(!r)return f(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...Gy(r.idToken)??{},...Gy(r.accessToken)??{}},i=s.email??s.preferred_username??"signed in";return AE(r)&&!r.refreshToken?H(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):f(` Document360: ${i} \xB7 profile "${n.name}"${o}`)}catch(n){return f(` Document360: ${n.message.split(".")[0]}`)}}function qE(){console.error(""),console.error(`Sign in with your Claude subscription: run ${Z("claude")} once, then retry.`),console.error(` (No Claude Code? ${Z("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${Z("https://console.anthropic.com/settings/keys")}`)}function VE(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;xE({uuid:t,name:r??vE(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function YE(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||RE(o,t).then(r=>{r&&$E(n,r)}).catch(()=>{})}async function up(e,t,n,o,r,s){let i=new Map,a=!1;for await(let l of e.send(t))l.type==="tool"&&zy.test(l.name)&&(a=!0),KE(l,o,r,n,i,s);if(a)try{let l=FE(await ME({cwd:r,profileName:s}));l&&console.log(l.startsWith("\u26A0")?H(l):l)}catch{}}function KE(e,t,n,o,r,s){switch(e.type){case"session":t.uuid||VE(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let i=qy()?null:Xa(e.name,e.input,n,s);if(i){process.stdout.write(`
456
-
457
- `);let l=[i.category,i.note].filter(g=>!!g).map(g=>ve(` \xB7 ${g}`)),d=i.loud?ve(" \xB7 ")+Be(H(i.loud)):"";console.log(`${q("\u25CF")} ${Z(Be(lu(i.verb)))}${Be(i.title)}${l.join("")}${d}`),r.set(e.id,{name:e.name,input:e.input,doc:!0,keepResult:i.keepResult});break}let a=Qa(e.name,e.input,process.cwd());a&&(process.stdout.write(`
458
-
459
- `),console.log(`${ve("\u25CF")} ${a.title}${a.arg!==null?ve(`${a.sep}(${a.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let i=Rt(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!i)break;let a=l=>l===1?"":"s";console.log(ve(` \u23BF Added ${i.added} line${a(i.added)}, removed ${i.removed} line${a(i.removed)}`));for(let l of i.lines)console.log(l);i.hidden>0&&console.log(f(` \u2026 +${i.hidden} more diff lines`));break}case"tool_result":{let i=r.get(e.id);if(!i)break;r.delete(e.id);let l=i.doc&&!i.keepResult&&!e.isError?{lines:[],hidden:0}:Ja(e.output,4,e.isError||qy()?void 0:i.name,i.input),d=e.isError?O:ve;l.lines.forEach((g,w)=>console.log(d((w===0?" \u23BF ":" ")+g))),l.hidden>0&&console.log(f(` \u2026 +${l.hidden} lines`)),e.isError||WE(i.name,i.input,e.output,n);break}case"result":{process.stdout.write(`
460
- `);let i=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(f(` (${gs(i)}\u2192${gs(e.outputTokens)} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(Yy(t.uuid),t.titleFired||YE(t,n));break}case"error":console.error(""),e.kind==="limit"?console.log(H(`\u23F3 ${e.message}`)):console.error(O(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&qE();break}}import{render as VD}from"ink";import{resolveAuth as YD}from"document360-engine";import{useCallback as te,useEffect as at,useMemo as vp,useRef as le,useState as ce}from"react";import{Box as je,Text as Y,useApp as CN,useInput as SN,useStdout as PN}from"ink";import{existsSync as Cr,readFileSync as hl,readdirSync as TN,writeFileSync as AN}from"node:fs";import{basename as Ys,dirname as EN,isAbsolute as NN,join as xp}from"node:path";import{createSession as Mb,classifyClaudeAuth as Np,CLAUDE_CODE_SETUP_HINT as DN,loginPkce as jN,toStoredTokens as IN,saveTokens as LN,getAccessToken as ON,resolveActiveProfile as mt,resolveProjectId as _N,getArticle as MN,decodeJwtClaims as Er,isExpired as ko,loadTokens as Un,clearTokens as FN,rememberSessionProject as UN,listStoredSessions as WN,tokensProjectId as Fb,clearProfileProject as BN,setTitle as HN,slugify as GN,touchSession as Rp,upsertSession as qN,generateTitle as Ub,findByName as VN,listSessions as YN,renameSession as KN,suggestNextAction as zN,readProjectConfig as Re,writeProjectConfig as Wb,readUserConfig as Bb,writeUserConfig as XN,resolveAndPersistAppType as QN,detectAppType as Hb,resolveModelSetting as Dp,loadProfileMap as Gb,applyPull as fl,computeSyncStatus as ml,lintDocs as Sr,compareRemoteSources as JN,planPull as qb,recordRunSample as ZN,pushArticles as eD,pushArticle as tD,PUSH_POOL_SIZE as nD,isPullWouldBlankError as Vb,localArticleTitle as Yb,establishBaselines as oD,rebaselineServerMeta as rD,inventoryRepo as sD,knownEnvironments as iD,currentEnvironments as Kb,sunsetEnvironment as zb,resolveEnvironment as aD,planPartitions as Cp,partitionEvenly as lD,screenshotPlaceholderIds as cD,trackedArticlePaths as uD,runPartitioned as Ks,partitionCoverage as Sp,estimateBulkCost as Xb,resolveModelForOperation as zs,readDocsPlan as Qb,checkForUpdate as dD,detectInstallKind as pD,isSelfUpdatable as hD,devHintsGuidePath as Jb,toolFeedbackPath as Zb,reconcileToolFeedback as fD,reconcileUpgradeActions as mD,stampArticles as Pr,snapshotArticles as ek,listArticleFiles as gD,CONTENT_CAP_VERSION as wD,ENGINE_VERSION as ck,DEFAULT_DOCS_DIR as jp,setProfileProject as yD,writeCrashLog as bD,applyStructureOrder as Pp,orderSyncLine as Tp,applyRelatedArticles as tk,relatedSyncLine as nk,reconcileDocsGit as kD,shareExplainedPath as $D,ensureDir as vD}from"document360-engine";Zo();xn();import{spawn as Qy}from"node:child_process";function zE(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function XE(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?Qy([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):Qy(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 dp(e){for(let[t,n]of zE())if(await XE(t,n,e))return!0;return!1}var Jy=/\b(?:reply|respond|answer)\s+with\s+(?:the\s+|a\s+)?(?:number|option|\d+)\b|\bpick one\b|\bpress the number\b|\b(?:tell me|let me know)\s+which\b|\bsay the number\b/i;function Zy(e){let t=e.replace(/\s+$/,"").split(`
461
- `),n=0;for(let s=t.length-1;s>=0;s--){let i=t[s];if(/^\s{0,3}\d{1,2}[.)]\s+\S/.test(i)){n++;continue}if(!(n>0&&/^\s+\S/.test(i)))break}return n<2?0:t.filter(s=>/^\s{0,3}\d{1,2}[.)]\s+\S/.test(s)).slice(-n).every((s,i)=>Number(/^\s{0,3}(\d{1,2})/.exec(s)[1])===i+1)?n:0}var QE=/\b(?:once|after|when)\s+(?:you|you've|you have|they|those|these|that)\b[^.!?]{0,80}\b(?:tell me|let me know|come back|ask me|say the word|run\s+\/|then\s+\/)|\b(?:tell me|let me know)\s+(?:when|once|and)\b|\bi'?ll\s+(?:wait|stand by|pick (?:it|this) up)\b|\bcome back to me\b|\bthen\s+(?:ask|tell)\s+me\b/i;function eb(e){let t=e.trimEnd();if(!t)return null;let n=Zy(t);return n>=2?{options:n}:/\?[\s*_"')\]]*$/.test(t)||Jy.test(t)||QE.test(t)?{options:0}:null}function pp(e,t){if(t.closed)return e;let n=e.split(`
462
- `),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){Jy.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(`
463
- `)}var JE=/^(?:(?:run|use|try|execute)\s+)?['"`*]?(\/[a-z][a-z-]*)['"`*]?((?:\s+(?:--?[a-z][\w-]*|\S*[/\\]\S*|\d{1,3}[-_][\w.-]*|[\w.-]+\.(?:md|markdown)))*)/i;function ZE(e,t){let n=Zy(e);return n<2?[]:e.replace(/\s+$/,"").split(`
464
- `).filter(s=>/^\s{0,3}\d{1,2}[.)]\s+\S/.test(s)).slice(-n).map(s=>{let i=s.replace(/^\s{0,3}\d{1,2}[.)]\s+/,"").trim(),a=JE.exec(i);if(!a)return null;let l=a[1].slice(1).toLowerCase();return t.has(l)?`${a[1]}${(a[2]??"").replace(/\s+/g," ").trimEnd()}`:null})}function tb(e,t){let n=ZE(e,t);return n.length<2||n.some(o=>o===null)?null:n}function eN(e){let t=e.split(`
465
- `).map(o=>o.trim()).filter(o=>o.length>3),n=t[t.length-1];return n?n.length>160?`${n.slice(0,157)}\u2026`:n:null}function vr(e){if(e.usageLimit)return`${e.label}: ${e.usageLimit}`;let t=e.stderrTail?eN(e.stderrTail):null;return t?`${e.label} last said: ${t}`:`${e.label} has said nothing since. Whatever it is, it is recorded: d360-writer logs. Stopping keeps every batch already finished.`}var tN={la:"local","l all":"local","local all":"local",pa:"portal","p all":"portal","portal all":"portal",sa:"skip","s all":"skip","skip all":"skip"},nN={L:"local",P:"portal",S:"skip"},oN={ya:"write","y all":"write","yes all":"write",na:"skip","n all":"skip","no all":"skip"},rN={Y:"write",N:"skip"};function nb(e,t,n){let o=e.trim(),r=o.toLowerCase().replace(/\s+/g," ");return t[r]??(o.length===1?n[o]??null:null)}function ol(e){return nb(e,tN,nN)}function ob(e){return nb(e,oN,rN)}function hp(e,t){let n=t?.max??12,o=t?.chrome??8;return Math.max(3,Math.min(n,(e??24)-o))}function rl(e,t,n){if(e<=n)return{start:0,end:e,above:0,below:0};let o=Math.min(Math.max(0,t),e-1),r=Math.min(Math.max(0,o-Math.floor(n/2)),e-n),s=r+n;return{start:r,end:s,above:r,below:e-s}}function fp(e,t,n,o=Date.now()){let s=e.value>0&&o-e.at<900?e.value*10+t:0,i=s>=1&&s<=n?s:t>=1&&t<=n?t:0;return i===0?{index:null,memory:{value:0,at:o}}:{index:i-1,memory:{value:i,at:o}}}function rb(e){return e<2?null:`1-${e}`}function ft(e){let t=[];if(e.multi)t.push("\u2191\u2193 move","space toggle");else{t.push("\u2191\u2193 move");let n=e.rows===void 0?null:rb(e.rows);n&&t.push(`${n} jump to a row`)}return t.push(...e.extra??[]),t.push(`enter ${e.verb}`),t.push(`esc ${e.cancel??"cancel"}`),t.join(" \xB7 ")}function sb(e){if(e.multi)return"pick with space, then enter to save \xB7 esc to cancel\u2026";let t=e.rows===void 0?null:rb(e.rows);return`choose one below \u2014 \u2191\u2193 then enter to ${e.verb}${t?", or type its number":""} \xB7 esc to ${e.cancel??"cancel"}\u2026`}var sN=[/\bfile does not exist\b/i,/\bno such file or directory\b/i,/\bENOENT\b/,/\bno (files? )?(were )?found\b/i,/\bfound 0 (files?|matches|results)\b/i,/\bno matches\b/i,/\bdid not match any\b/i,/\bno results?\b/i],iN=[/\bpermission denied\b/i,/\bEACCES\b/,/\bEPERM\b/,/\bnot authori[sz]ed\b/i,/\bunauthori[sz]ed\b/i,/\bforbidden\b/i,/\brefus(ed|ing)\b/i,/\bblocked\b/i,/\bwriter mode\b/i,/\bHTTP [45]\d\d\b/],aN=/^(read|glob|grep|ls|search|notebookread)$/i;function ib(e,t){return!e||!aN.test(e.trim())||iN.some(n=>n.test(t))?!1:sN.some(n=>n.test(t))}import{existsSync as lN,mkdirSync as cN,readFileSync as uN,writeFileSync as dN}from"node:fs";import{join as ab}from"node:path";import{writerDir as pN}from"document360-engine";function lb(e){return ab(pN(e),".sessions")}function cb(e,t){return ab(lb(e),`${t}.json`)}function ub(e,t,n){try{cN(lb(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");dN(cb(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function mp(e,t){try{let n=cb(e,t);if(!lN(n))return[];let o=JSON.parse(uN(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var hN=e=>`\x1B]0;${e}\x07`,fN=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function db(e){process.stdout.isTTY&&process.stdout.write(e)}function xr(e){db(hN(e))}function sl(e){db(fN(e))}var il=["\xB7 "," \xB7"],al="\u{1F7E3}";Ra();var pb=()=>({fingerprint:null,counts:null,settled:0,spokenBaseline:null,lastSpokeAt:null,awaySince:null}),mN={hints:0,requests:0,answers:0,directives:0};function gp(e,t){let n=e??mN;return{hints:Math.max(0,t.hints-n.hints),requests:Math.max(0,t.requests-n.requests),answers:Math.max(0,t.answers-n.answers),directives:Math.max(0,t.directives-n.directives)}}var ll=e=>e.hints===0&&e.requests===0&&e.answers===0&&e.directives===0,hb=e=>e.hints+e.requests+e.answers+e.directives,wp=(e,t)=>e-t>=6e5;function fb(e){let{now:t,lastInputAt:n,fingerprint:o,counts:r,occupied:s,prev:i}=e,a=wp(t,n),d=i.fingerprint!==null&&i.fingerprint!==o?0:i.settled+1,g={...i,fingerprint:o,counts:r,settled:d,awaySince:a?i.awaySince??t:null,spokenBaseline:i.spokenBaseline??r};if(a){let k=gp(g.spokenBaseline,r);return{memory:g,speak:null,waiting:ll(k)?null:k}}if(s)return{memory:g,speak:null,waiting:null};if(d<2)return{memory:g,speak:null,waiting:null};let w=gp(i.spokenBaseline,r);return ll(w)?{memory:g,speak:null,waiting:null}:i.lastSpokeAt!==null&&t-i.lastSpokeAt<6e5?{memory:g,speak:null,waiting:null}:{memory:{...g,spokenBaseline:r,lastSpokeAt:t,settled:d},speak:w,waiting:null}}function mb(e,t,n){if(e.awaySince===null)return{kind:"none",memory:e};let o=t-e.awaySince,r=gp(e.spokenBaseline,n),s={...e,awaySince:null,counts:n,spokenBaseline:n,lastSpokeAt:ll(r)?e.lastSpokeAt:t};return ll(r)?{kind:"none",memory:s}:{kind:o>=36e5?"briefing":"delta",memory:s,delta:r,awayMs:o}}function qs(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===0?"":t.length===1?t[0]:`${t.slice(0,-1).join(", ")} and ${t.at(-1)}`}function yp(e){let t=Math.round(e/6e4);if(t<45)return`${t} minutes`;let n=Math.round(e/36e5);if(n<20)return`${n} hour${n===1?"":"s"}`;let o=Math.round(n/24);return o<=1?"a day":`${o} days`}function gb(e){return`\u{1F4E5} ${qs(e)} just arrived from your builder \u2014 /catch-up folds ${hb(e)===1?"it":"them"} into the docs.`}function wb(e,t){return`\u{1F4E5} While you were away (${yp(t)}): ${qs(e)} from your builder \u2014 /catch-up folds ${hb(e)===1?"it":"them"} into the docs.`}function yb(e){return`\u{1F4E5} ${qs(e)} waiting from your builder \xB7 tab to run /catch-up\u2026`}Ei();import{publishGateVerdict as Ap,publishGateLines as Ep,SKIP_STYLE_FLAG as ok,SKIP_SHOTS_FLAG as xD}from"document360-engine";import{askBuilder as RD,openGapQuestions as CD}from"document360-engine";import{retireArticle as SD,normalizeScope as PD}from"document360-engine";re();import{Box as Vs,Text as Me}from"ink";import{jsx as Fe,jsxs as Rr}from"react/jsx-runtime";function gN({row:e,nameW:t,width:n}){let o=s=>Xl(s,n),r=(s,i)=>Fe(Vs,{flexDirection:"column",children:s.map(i)});switch(e.t){case"head":return r(o(e.s),(s,i)=>Fe(Me,{color:ae,bold:!0,children:s},i));case"text":return r(o(e.s),(s,i)=>Fe(Me,{children:s},i));case"dim":return r(o(e.s),(s,i)=>Fe(Me,{dimColor:!0,children:s},i));case"sub":return r(o(e.s),(s,i)=>Fe(Me,{bold:!0,dimColor:!0,children:s},i));case"good":return r(o(e.s),(s,i)=>Fe(Me,{color:"green",children:s},i));case"step":{let s=o(`${e.n}. ${e.s}`);return Fe(Vs,{flexDirection:"column",children:s.map((i,a)=>a===0?Rr(Me,{children:[Fe(Me,{color:ae,children:`${e.n}. `}),i.slice(`${e.n}. `.length)]},a):Fe(Me,{children:i},a))})}case"cmd":{let s=Ri(e.name,e.s,t,n),i=s.descLines.slice(s.nameOwnLine?0:1);return Rr(Vs,{flexDirection:"column",children:[Rr(Me,{children:[" ",Fe(Me,{color:ae,children:s.nameCell}),!s.nameOwnLine&&Fe(Me,{dimColor:!0,children:` ${s.descLines[0]??""}`})]}),i.map((a,l)=>Fe(Me,{dimColor:!0,children:`${s.indent}${a}`},l))]})}case"gap":return Fe(Me,{children:" "})}}function bb({tab:e,scroll:t,rows:n,width:o,version:r,engineVersion:s}){let i=ut[e]??ut[0],a=zl(i.rows),l=Math.max(20,o-2),d=6+ut.reduce((T,D)=>T+D.label.length+4,0),g="\u2500".repeat(Math.min(d,l)),w=`\u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 \u2191\u2193 scroll \xB7 esc close \xB7 d360-writer v${r} \xB7 engine v${s}`,k=Vh({rows:n,inner:l,barWidth:d,footerWidth:w.length}),{visible:S,above:v,below:C}=qh(i.rows,{width:o,budget:k,scroll:t,nameW:a});return Rr(Vs,{flexDirection:"column",paddingX:1,children:[Rr(Me,{children:[Fe(Me,{color:ae,bold:!0,children:"Help "}),ut.map((T,D)=>D===e?Fe(Me,{color:"white",backgroundColor:ae,bold:!0,children:` ${T.label} `},T.key):Fe(Me,{dimColor:!0,children:` ${T.label} `},T.key))]}),Fe(Me,{color:ae,children:g}),Rr(Vs,{flexDirection:"column",marginTop:1,children:[v>0?Fe(Me,{dimColor:!0,children:`\u22EF ${v} more above`}):null,S.map((T,D)=>Fe(gN,{row:T,nameW:a,width:o},v+D)),C>0?Fe(Me,{dimColor:!0,children:`\u22EF ${C} more below`}):null]}),Fe(Me,{dimColor:!0,children:`
466
- \u2190/\u2192 or tab switch \xB7 1-5 jump${v+C>0?" \xB7 \u2191\u2193 scroll":""} \xB7 esc close \xB7 d360-writer v${r} \xB7 engine v${s}`})]})}var wN=/^(?:\d+[.)]|[-*•])\s+/;function kb(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
467
- `)){let i=s.trim().replace(wN,""),a=i.match(/^`([^`]+)`$/);a&&(i=a[1].trim());let l=i.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!l||!o.has(l[1].toLowerCase()))continue;let d=`/${l[1].toLowerCase()}${l[2]?` ${l[2]}`:""}`;if(r.includes(d)||r.push(d),r.length>=n)break}return r}re();function bo(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function Ve(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function cl(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var yN=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function bp(e,t,n){if(!yN.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 kp(e){return e.replace(/^[\w.-]+\//,"")}var ul=16,$b={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function Fn(e){return typeof e=="string"?e:e.cmd}function vb(e){return typeof e=="string"?void 0:e.desc}function $p(e){return e.trim().split(/\s+/).slice(1).join(" ")}function xb(e,t){let n=$p(t);return e.some(r=>Fn(r).trim()===t.trim()||!!n&&$p(Fn(r))===n)?e.filter(r=>Fn(r).trim()!==t.trim()&&!(n&&$p(Fn(r))===n)):[]}import{isDirectiveMention as TD,stripDirectiveMention as AD,appendDirective as ED,reconcileTestidRequest as ND,builderChannelWired as DD,pendingFingerprint as jD}from"document360-engine";var bN=/\[Pasted text #\d+ \+\d+ lines?\]/g;function Rb(e){return e.replace(/\r\n?/g,`
468
- `)}function Cb(e){return e.includes(`
469
- `)||e.length>200}function Sb(e,t){let n=t.split(`
470
- `).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function Pb(e,t){return e.replace(bN,n=>t.get(n)??n)}function Tb(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function dl(e,t){let n=Math.max(1,t),o=[],r=0;for(let s of e.split(`
471
- `)){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 pl(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function Ab(e,t,n){let o=pl(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 Eb(e,t,n){let o=e[pl(e,t)];return n==="start"?o.start:o.end}var kN=new Set(["Edit","Write","MultiEdit","NotebookEdit"]),Nb={hint:"hint",message:"message",state:"state file",roadmap:"roadmap",directive:"directives",feedback:"tool-feedback"},$N=new Set(["hint","message","state"]),vN=["hint","message","roadmap","directive","feedback","state"];function xN(e){return e.startsWith("hints/")?"hint":e.startsWith("messages/")?"message":e==="roadmap.md"?"roadmap":e==="directives.md"?"directive":/^tool-feedback(-archived)?\.md$/.test(e)?"feedback":e.startsWith("cache/")||e.startsWith(".sessions/")||/^(plan|devhints-state|upgrade-state|category-map)\.json$/.test(e)?"state":null}function Db(e,t){let n=e==="Read"?"read":kN.has(e)?"updated":null;if(!n)return null;let o=t.file_path??t.notebook_path;if(typeof o!="string"||!o)return null;let r=o.replace(/\\/g,"/").toLowerCase(),s=".d360-writer/",i=r.lastIndexOf(s);if(i<0)return null;let a=xN(r.slice(i+s.length));return a?{category:a,verb:n,path:r}:null}function jb(e){let t=new Map,n=new Set;for(let r of e)r.verb==="updated"&&n.add(r.path);for(let r of e){if(r.verb==="read"&&n.has(r.path))continue;let s=`${r.category}:${r.verb}`,i=t.get(s);i||t.set(s,i=new Set),i.add(r.path)}let o=[];for(let r of vN)for(let s of["updated","read"]){let i=t.get(`${r}:${s}`)?.size??0;i!==0&&o.push($N.has(r)?`${i} ${Nb[r]}${i===1?"":"s"} ${s}`:`${Nb[r]} ${s}`)}return o.length>0?o.join(" \xB7 "):null}function Ib(e,t,n){let o=Math.max(1,n),r=e.split(`
431
+ `),lead:{kind:"cmd",cmd:"/share",reason:"it sends your saved work to your team and brings back your builder's latest; after this once, I keep doing it for you"},picker:null,follow:null}):s>0&&n.push({key:"share",bullet:`\u26A0 ${s} docs change set${be(s)} saved but not sent \u2014 someone else pushed to this branch first (your work is safe)`,lead:{kind:"cmd",cmd:"/share",reason:"it retries sending your saved work; if it keeps failing, your builder can merge the branch"},picker:null,follow:null})}else if(e.uncommittedDocs>0){let r=e.uncommittedDocs;n.push({key:"commit",bullet:`\u26A0 ${r} uncommitted change${be(r)} under .d360-writer/ \u2014 tell your coding agent: "commit d360-writer's work"`,lead:null,picker:null,follow:null})}return n}function Dy(e){return e.find(t=>t.lead||t.picker)??null}function wA(e){return e.kind==="cmd"?e.cmd:e.kind==="prompt"?`\u201C${e.text}\u201D`:""}function Ws(e){return e.kind==="cmd"?e.cmd:e.kind==="prompt"?e.text:null}function yA(e){return Ws(e)??""}function bA(e,t,n){let o=a=>(a??[]).map(l=>t.get(l)).filter(l=>l!==void 0&&l<n),r=a=>a.length===1?`${a[0]}`:`${a.slice(0,-1).join(", ")} and ${a[a.length-1]}`,s=o(e.blockedBy);if(s.length>0)return` (needs ${r(s)} first)`;let i=o(e.dependsOn);return i.length>0?` (better after ${r(i)})`:""}function qa(e,t,n,o=null,r,s=0){if(r&&r.length>0){let R=r.filter(Xi),C=r.filter(O=>!Xi(O)),A=[...C,...R],D=(O,Q)=>` ${Q+1}. ${O.title}${O.run?` \xB7 ${O.run}`:""}`,N;return R.length===0||C.length===0?N=[e,...A.map(D)].join(`
432
+ `):N=[e,"",` ${dA}`,...C.map((O,Q)=>D(O,Q)),"",` ${pA}`,...R.map((O,Q)=>D(O,C.length+Q))].join(`
433
+ `),{note:[...o?[o]:[],N,hA(A.length,n),Ay].join(`
434
+
435
+ `),menu:A.map(O=>O.run??O.title)}}let i=Dy(t),a=i?.picker?[]:t.filter(R=>R.lead),l=a.length>=2?a:[],d=new Map(l.map((R,C)=>[R.key,C+1])),w=[];i?.lead?w.push(vr(i.lead)):i?.picker&&w.push(i.picker.lead);for(let R of t.filter(C=>C!==i&&!C.lead).slice(0,2))R.follow&&w.push(R.follow);l.length>=2&&n&&w.push(`Press 1\u2013${l.length} to pick a different one \u2014 the number fills the box, enter runs it.`);let m=w.join(" "),$=t.filter(R=>R.bullet).map(R=>{let C=d.get(R.key),[A="",...D]=(C&&R.lead?.kind==="prompt"&&R.rowBullet?R.rowBullet:R.bullet).split(`
436
+ \u2022 `),N=R===i&&R.lead?.kind!=="answer"&&R.lead?.detail?[]:D;if(C&&R.lead){let Q=A.replace(/^→\s+/,"");return[` ${C}. ${wA(R.lead)} \u2014 ${Q}${bA(R,d,C)}`,...N.map(de=>` ${de}`)].join(`
437
+ `)}let U=R.lead?.kind==="cmd"?R.lead.cmd:null;return` \u2022 ${[A,...N].join(`
438
+ \u2022 `)}${U&&!m.includes(U)?` \u2014 ${U}`:""}`}),S=o?[o,[e,...$].join(`
439
+ `)]:[[e,...$].join(`
440
+ `)];if(w.length&&S.push(w.join(" ")),s>0){let R=s;S.push(`${R} question${be(R)} you asked your developers ${R===1?"is":"are"} still unanswered. Their reply arrives with your docs the next time either of you shares, and /inbox folds it in. Nothing is blocked meanwhile.`)}return S.push(Ay),{note:S.join(`
441
+
442
+ `),menu:l.map(R=>yA(R.lead))}}function Bs(e,t){let n=t?.pickable===!0,o=S=>t?.header?`${t.header}
443
+
444
+ ${S}`:S;if(!e.ready)return{kind:"idle"};if(e.pendingAnswer)return{kind:"recommend",rec:{note:null,settled:null,tone:"info",lead:e.pendingAnswer.options>=2?{kind:"answer",options:e.pendingAnswer.options,reason:"the agent is waiting on your pick"}:null,picker:null,menu:[]}};let r=gA(e,t),s=r.length===1&&r[0].key==="roadmap"&&!!r[0].lead&&!!e.roadmap&&!!e.roadmap.next,i=s?e.roadmap.open?.length?e.roadmap.open:[e.roadmap.next]:[],a=i.length>0&&i.every(Xi)&&e.roadmap.total-e.roadmap.done===i.length,l=s?lA(e.roadmap.total-e.roadmap.done,e.roadmap.total,{listed:i.length>0,onlyScreenshots:a}):null;if(!e.hasDocs){let S=Dy(r);if(S&&(S.lead?.kind==="cmd"||S.picker)){let R=qa(t?.header??"\u{1F4ED} No docs yet for this repo \u2014 here\u2019s where things stand:",r,n,null,void 0,e.outboundQuestions);return{kind:"recommend",rec:{note:R.note,settled:null,tone:S.tone??"info",lead:S.lead,picker:S.picker,menu:R.menu}}}return{kind:"recommend",rec:{note:o(fA),settled:null,tone:"info",lead:{kind:"prompt",text:"write the docs for this repo",reason:"I\u2019ll read the code and draft a structure"},picker:null,menu:[]}}}if(r.length===0){let S=e.roadmap&&!e.roadmap.next?` Docs campaign complete \u2014 all ${e.roadmap.total} step${be(e.roadmap.total)} done (/roadmap).`:"";return{kind:"recommend",rec:{note:o(`Welcome back. Your ${e.tracked} tracked article${be(e.tracked)} for \u201C${e.profileName}\u201D are all in sync \u2014 /audit re-checks the code, /pull brings down portal edits.${S}`),settled:null,tone:"info",lead:null,picker:null,menu:[]}}}let d=r.filter(S=>S.lead||S.picker),w=d[0]??null;if(!w){let S=qa(t?.header??"Welcome back \u2014 where your docs stand:",r,n,null,void 0,e.outboundQuestions);return{kind:"recommend",rec:{note:S.note,settled:null,tone:"info",lead:null,picker:null,menu:S.menu}}}if((w.key==="audit"||d[1]?.key==="audit")&&e.behind>0&&e.autoAudit&&e.allowAutoAudit)return{kind:"autoAudit",note:o(`\u{1F4CB} ${e.behind} code change${be(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`)};if(l){let S=qa(a?cA:uA,r,n,l,i,e.outboundQuestions);return{kind:"recommend",rec:{note:S.note,settled:l,tone:"info",lead:null,picker:null,menu:S.menu}}}let $=qa(t?.header??"Welcome back \u2014 where your docs stand:",r,n,l,void 0,e.outboundQuestions);return{kind:"recommend",rec:{note:$.note,settled:l,tone:w.tone??"info",lead:w.lead,picker:w.picker,menu:$.menu}}}import{existsSync as Ya,readdirSync as cp}from"node:fs";import{spawnSync as kA}from"node:child_process";import{join as Ka}from"node:path";import{readProjectConfig as lp,resolveActiveProfile as Ly,loadTokens as $A,isExpired as vA,loadProfileMap as Oy,localAheadPaths as xA,loadKnownConflicts as RA,draftPendingPaths as CA,loadOpenCommentCount as SA,readDocsPlan as PA,devHintsGuidePath as TA,DEFAULT_DOCS_DIR as za,roadmapProgress as AA,listRoadmap as jy,readProductBriefState as EA,readDiscoveryQueue as NA,reconcileCommitRequest as DA,reconcileTestidRequest as jA,snapshotHandoff as IA,shareExplainedPath as LA,unannotatedShotIds as OA,shotsNeedingRecapture as _A,resolveOutputDir as MA,DEFAULT_OUTPUT_DIR as FA,WRITER_DIRNAME as ap,styleGuideSettled as UA,listAvailablePacks as WA,listArticleFiles as BA}from"document360-engine";xn();var HA=5;function Iy(e){try{return cp(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function up(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>Iy(Ka(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&Iy(Ka(e,o)))}function dp(e,t){try{let n=lp(e);if(!n)return!1;let o=Ly(e,t),r=Oy(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=Ka(e,(n.docsDir??za).replace(/\/+$/,""));return!!(Ya(s)&&cp(s).length>0||Ya(TA(e)))}catch{return!1}}function GA(e){let t=[`:(exclude)${ap}`],n=(e.docsDir??za).replace(/\\/g,"/").replace(/\/+$/,"");return n&&!n.startsWith(`${ap}/`)&&n!==ap&&t.push(`:(exclude)${n}`),t}function qA(e,t,n){try{let o=kA("git",["rev-list","--count",`${t}..HEAD`,"--",".",...GA(n)],{cwd:e,encoding:"utf8",timeout:1200});return o.status===0&&parseInt((o.stdout||"").trim(),10)||0}catch{return 0}}function Hs(e,t,n){try{let o=lp(e);if(!o)return null;let r=Ly(e,t),s=$A(r.name,r.project.projectId),i=!!s&&(!vA(s)||!!s.refreshToken),a=dp(e,t)||!up(e,o.authoritativeSourceFiles),l=Oy(e,r.name),d=l?Object.keys(l.articles).length:0,w=Ka(e,(o.docsDir??za).replace(/\/+$/,"")),m=!1;try{m=Ya(w)&&cp(w).length>0}catch{}let $=l?.lastAnalyzedCommit?qA(e,l.lastAnalyzedCommit,o):0,S=0;try{let Ne=(o.docsDir??za).replace(/\/+$/,""),Ue=PA(e,Ne);Ue.length>0&&(S=Pn(e,Ne,Ue.map(Et=>Et.path)).length)}catch{}let R=pn(e),C=Ea({...R,directives:0}),A=xA(e,t),D=new Set(RA(e,r.name)),N=A.filter(Ne=>D.has(Ne)).length,U=A.length-N,O=new Set(A),Q=CA(e,t).filter(Ne=>!O.has(Ne)),z=Q.length,de=[...A.filter(Ne=>!D.has(Ne)),...Q],ke=hs(e,de),xe=ke.length,Pe=Yt(ke),fe=null;try{if(!UA(o.styleGuide)){let Ne=WA(e).filter(Ue=>Ue.name.toLowerCase()!=="humanise");fe={articles:BA(e).length,presets:[{cmd:"/style-guide keep",desc:"the built-in rules only \u2014 correctness and anti-slop checks (nothing changes)"},...Ne.map(Ue=>({cmd:`/style-guide use ${Ue.name.toLowerCase()}`,desc:`${Ue.name} style guide \u2014 ${Ue.rules.length} more rules`}))]}}}catch{}let se=0,te;try{let Ne=Dm(e,de);se=Ne.length,te=Yt(Ne)}catch{}let we=0,$e=0;try{let Ne=MA(e,lp(e)?.outputDir??FA);we=OA(Ne).length,$e=_A(Ne).length}catch{}let Ye=SA(e,r.name),fn=Ut(e),mn=AA(e),At=mn?{...mn,open:jy(e).filter(Ne=>Ne.status==="open").slice(0,HA).map(Ne=>({title:Ne.title,...Ne.run?{run:Ne.run}:{},...Ne.stage?{stage:Ne.stage}:{}}))}:null,gt=IA(e,o),jr=DA(e,new Date().toISOString(),{supersededByHandoff:gt!==null});jA(e,new Date().toISOString());let tt=kn(e,t),xo=tt?{name:tt.name,replacement:tt.replacement,replacementProfile:tt.replacementProfile}:null,Wn=EA(e),Ro=NA(e),Co=Wn?{status:Wn.status,openQuestions:Ro.openQuestions,answersPending:Ro.answersPending}:null;return!Co&&m&&jy(e).some(Ue=>Ue.status==="open"&&(Ue.run??"").trim()==="/discover")&&(Co={status:"pending",openQuestions:0,answersPending:0}),{ready:i&&a&&!n.claudeMissing,hasDocs:m,tracked:d,pendingText:C,directives:R.directives,behind:$,pendingWrites:S,localAhead:U,unreviewed:xe,unreviewedScope:Pe,styleErrors:se,shotsToAnnotate:we,shotsToRecapture:$e,styleErrorScope:te,draftAhead:z,conflicts:N,openComments:Ye,outboundQuestions:Ns(e),autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:fn.status,devhintsCompletedVersion:fn.completedVersion,devhintsToVersion:Le,builderStarted:an(e),genreUnknown:n.genreUnknown,pendingAnswer:n.pendingAnswer??null,lastCommand:n.lastCommand??null,styleRules:fe,roadmap:At,discovery:Co,uncommittedDocs:jr.dirty.length,handoff:gt,shareExplained:Ya(LA(e)),sunsetEnv:xo}}catch{return null}}re();import{existsSync as KA,readFileSync as zA}from"node:fs";import{isAbsolute as XA,join as QA}from"node:path";import{DEFAULT_DOCS_DIR as JA,findPathByArticleId as ZA,isArticleDocPath as eE,loadProfileMap as tE,readProjectConfig as nE,resolveActiveProfile as oE}from"document360-engine";function VA(){return process.platform==="win32"||process.platform==="darwin"}var YA=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Xa(e,t){let n=e.replace(/\\/g,"/"),o=`${YA(t)}/`,[r,s]=VA()?[n.toLowerCase(),o.toLowerCase()]:[n,o];return r.startsWith(s)?n.slice(o.length):null}var My=70;function rE(e,t){return{docsRoot:()=>(nE(e)?.docsDir??JA).replace(/\\/g,"/").replace(/\/+$/,""),read:n=>{try{let o=XA(n)?n:QA(e,n);return KA(o)?zA(o,"utf8"):null}catch{return null}},pathForArticleId:n=>{try{let o=tE(e,oE(e,t).name);return o?ZA(o,n):null}catch{return null}}}}var ko=(e,t=My)=>{let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"};function Gs(e){if(!e)return null;let t=!1;for(let n of e.split(`
445
+ `)){let o=n.trimEnd();if(/^\s*(```|~~~)/.test(o)){t=!t;continue}if(t)continue;let r=/^#\s+(\S.*)$/.exec(o);if(r)return ko(r[1])}return null}var sE=new Set(["a","an","and","as","at","but","by","for","in","of","on","or","the","to","vs","with"]),iE=new Set(["ai","api","cli","css","csv","dfm","faq","html","http","https","id","json","mcp","pdf","sdk","sso","ui","url","ux","yaml","ado","qa"]);function Fy(e,t,n){let o=e.toLowerCase();return iE.has(o)?e.toUpperCase():!t&&sE.has(o)?o:!t&&!n?e:e.charAt(0).toUpperCase()+e.slice(1)}var Uy=e=>e.replace(/^\d+[-_.]/,"").split(/[-_]/).filter(Boolean);function aE(e){let t=Uy(e);return t.length===0?e:t.map((n,o)=>Fy(n,o===0,!0)).join(" ")}function Wy(e){let t=typeof e=="string"&&e?e.replace(/\\/g,"/"):null;if(!t)return null;let n=t.split("/").filter(Boolean);return n.length<2?null:aE(n[n.length-2])}function By(e){let t=e.replace(/\\/g,"/").split("/").pop()??e,n=Uy(t.replace(/\.(md|markdown)$/i,""));return n.length===0?t:n.map((o,r)=>Fy(o,r===0,!1)).join(" ")}var lE=46;function cE(e,t){let n=0,o=!1,r=null;for(let s of e.split(`
446
+ `)){if(n>t)break;let i=s.trimEnd();if(/^\s*(```|~~~)/.test(i))o=!o;else if(!o){let a=/^(#{2,6})\s+(\S.*)$/.exec(i);a&&(r=ko(a[2],My))}n+=s.length+1}return r}function _y(e){for(let t of e.split(`
447
+ `)){let n=t.replace(/^\s*(#{1,6}\s+|[-*+]\s+|>\s+|\d+[.)]\s+)/,"").replace(/^\s*\|/,"").trim();if(n)return ko(n,lE)}return null}var Tt=e=>typeof e=="string"&&e?e:null,uE=e=>typeof e=="string"&&e.length>=8?`id ${e.slice(0,8)}\u2026`:null;function dE(e,t){return Xa(e,t)??e.replace(/\\/g,"/")}function pE(e,t){let n=Rt(e,t,200);return n?`+${n.added} \u2212${n.removed}`:"no change"}var hE=new Set(["Edit","MultiEdit","Write"]);function fE(e,t,n,o){if(!hE.has(e))return null;let r=Tt(t.file_path);if(!r)return null;let s=dE(r,n),i=o.docsRoot();if(!(s===i||s.startsWith(`${i}/`)))return null;let a=s.slice(i.length+1);if(!a||!eE(a))return null;let l=Wy(a),d=o.read(s),w=O=>Gs(O)??Gs(d)??By(a);if(e==="Write"){let O=Tt(t.content)??"",Q=w(O);if(d===null){let z=O.replace(/\n$/,"").split(`
448
+ `).length;return{verb:"Draft",title:Q,category:l,note:`new, ${z} lines`,articleKey:s}}return{verb:"Rewrite",title:Q,category:l,note:pE(d,O),articleKey:s}}let m=Array.isArray(t.edits)?t.edits.map(O=>({from:Tt(O.old_string)??"",to:Tt(O.new_string)??""})):[{from:Tt(t.old_string)??"",to:Tt(t.new_string)??""}],$=m.reduce((O,Q)=>{let z=Rt(Q.from,Q.to,200);return z?{added:O.added+z.added,removed:O.removed+z.removed}:O},{added:0,removed:0}),S=$.added===0&&$.removed===0?"no change":`+${$.added} \u2212${$.removed}`,R=m[0],C=R&&d?cE(d,d.indexOf(R.from)):null,A=R?_y(R.to)??_y(R.from):null,D=m.length>1?` +${m.length-1} more`:"",N=A?`\u201C${A}\u201D${D}`:D.trim()||null,U=C?{title:`\u21B3 ${C}`,category:N,note:S}:N?{title:`\u21B3 ${N}`,category:null,note:S}:null;return{verb:"Update",title:w(m.map(O=>O.to).join(`
449
+ `)),category:l,note:S,articleKey:s,...U?{repeat:U}:{}}}function mE(e,t,n){let o=()=>{let r=Tt(t.article_id),s=r?n.pathForArticleId(r):null;return(s?Gs(n.read(s)):null)??(s?By(s):uE(r)??"article")};switch(e){case"d360_create_article":{let r=Tt(t.title);return r?{verb:"Create",title:ko(r),category:Wy(t.local_path),note:"Document360 draft"}:null}case"d360_update_article":return{verb:"Update",title:Tt(t.title)?ko(Tt(t.title)):o(),category:null,note:"Document360 draft"};case"d360_fork_article":return{verb:"Fork",title:o(),category:null,note:"new Document360 draft"};case"d360_publish_article":{let r=t.version_number;return{verb:"Publish",title:o(),category:null,note:typeof r=="number"?`v${r}`:null,loud:"LIVE"}}case"d360_unpublish_article":return{verb:"Unpublish",title:o(),category:null,note:"back to draft, removed from readers"};case"d360_create_category":{let r=Tt(t.name);return r?{verb:"Create",title:ko(r),category:null,note:"Document360 category"}:null}case"d360_upload_drive_file":{let r=Tt(t.file_path);if(!r)return null;let s=r.replace(/\\/g,"/").split("/").pop()??r;return{verb:"Upload",title:ko(s),category:null,note:"Document360 Drive",keepResult:!0}}default:return null}}function Qa(e,t,n,o,r=rE(n,o)){try{let s="mcp__document360__";return e.startsWith(s)?mE(e.slice(s.length),t,r):fE(e,t,n,r)}catch{return null}}var gE={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"},Gy=160,pp=200,qy=40;function Mn(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:wE(n)?"\u2026"+n.slice(n.length-(t-1)):n.slice(0,t-1)+"\u2026"}function wE(e){return!e.includes(" ")&&/[/\\]/.test(e)}function Hy(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}: ${Mn(typeof r=="string"?r:JSON.stringify(r),qy)}`);return t.length>4&&n.push("\u2026"),Mn(n.join(", "),Gy)}var yE=new Set(["file_path","notebook_path"]);function bE(e,t){return t?Xa(e.replace(/\\/g,"/").replace(/\/+$/,""),t)??e:e}var Vy=e=>typeof e=="string"&&e?e:null;function kE(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});return e==="d360_sync_status"?n("Check sync status",null):null}function Ja(e,t,n){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,s="",...i]=e.split("__"),a=i.join("__");if(s==="document360"){let w=kE(a,t);if(w)return w}let l=a.replace(/^d360_/,"").replace(/_/g," ");return{title:`${s==="document360"?"Document360":s.charAt(0).toUpperCase()+s.slice(1)}: ${l}`,sep:" ",arg:Hy(t)}}let o=gE[e],r=o?t[o]:void 0;if(typeof r=="string"&&r){let s=o&&yE.has(o)?bE(r,n):r;return{title:e,sep:"",arg:Mn(s,Gy)}}return{title:e,sep:"",arg:Hy(t)}}function $E(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 vE(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map($E).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>Mn(r,pp))]}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}: ${Mn(String(r),qy)}`);return n.length>0?[Mn(n.join(" \xB7 "),pp)]:null}return null}function xE(e){let t=Vy(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function RE(e,t,n){switch(e){case"d360_create_article":{let o=xE(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=Vy(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 ${Mn(o[0],120)}`:""}`]}default:return null}}var Yy=new Set(["Edit","Write","MultiEdit","NotebookEdit"]);function CE(e){return e.replace(/^\s*\d+\t/,"")}function SE(e,t){if(Yy.has(e))return[];let n=t.split(`
450
+ `);if(e==="Read"){let o=n.length,r=Gs(n.map(CE).join(`
451
+ `));return[`${o} line${o===1?"":"s"}${r?` \xB7 ${r}`:""}`]}if(e==="Glob"){if(/^no files found/i.test(t))return null;let o=n.filter(r=>r.trim()).length;return[`${o} file${o===1?"":"s"}`]}return e==="Grep"&&/^Found \d+/.test(n[0]??"")?[n[0]]:null}function Za(e,t=4,n,o){let r=e.replace(/\r\n/g,`
452
+ `).trimEnd();if(n&&Yy.has(n))return{lines:[],hidden:0};if(!r)return{lines:["(no output)"],hidden:0};if(n&&!n.startsWith("mcp__")){let i=SE(n,r);if(i)return{lines:i,hidden:0}}if(n?.startsWith("mcp__document360__")){let i=RE(n.slice(18),o,r);if(i)return{lines:i,hidden:0}}let s=vE(r)??r.split(`
453
+ `);return{lines:s.slice(0,t).map(i=>Mn(i,pp)),hidden:Math.max(0,s.length-t)}}function el(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function tl(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 Ky(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 nl(e){return Ky(e,"url")}function ol(e){return Ky(e,"preview_url")}function zy(e,t){try{let o=JSON.parse(t),s=(Array.isArray(o)?o[0]:o)?.title;if(typeof s=="string"&&s.trim())return s.trim()}catch{}if(typeof e.title=="string"&&e.title.trim())return e.title.trim();let n=e.local_path;return typeof n=="string"&&n.trim()?(n.replace(/\\/g,"/").split("/").pop()??n).replace(/\.(md|markdown)$/i,""):null}var tb=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/,fp=null;function Qy(){return fp===null&&(fp=OE().verboseTranscript===!0),fp}function XE(e,t,n,o){if(tb.test(e))try{let r=eb(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,i=tl(t,n),a=nl(n);e.endsWith("publish_article")&&a&&console.log(Z(` \u2B95 Live: ${a}`));let l=ol(n);l?console.log(Z(` \u2B95 Preview: ${l}`)):i&&s&&console.log(Z(` \u2B95 Preview: ${el(r.connection.portalUrl,s,i,r.project.languageCode??"en")}`))}catch{}}async function nb(e=process.cwd(),t="auto",n,o){let r=TE(t);r.kind==="none"&&(console.error(""),console.error(_("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${Z("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${Z('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${Z("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${Z("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),QE(e,n),r.kind==="subscription"&&(r.stored?console.log(f(" Using your Claude subscription (no API key set).")):console.log(f(" No API key or stored Claude Code login found \u2014 trying your Claude session anyway.")),console.log(""));let s=!1,i=hp({cwd:e,profileName:n,allowProdWrites:s}),a={uuid:null,firstPrompt:null,titleFired:!1},l=PE({input:process.stdin,output:process.stdout}),d=[],w=null,m=!1;l.on("line",R=>{if(w){let C=w;w=null,C(R)}else d.push(R)}),l.on("close",()=>{if(m=!0,w){let R=w;w=null,R(null)}});function $(){return d.length>0?Promise.resolve(d.shift()):m?Promise.resolve(null):(process.stdout.write(Z("> ")),new Promise(R=>{w=R}))}let S={cwd:e,version:o,profileName:n,allowProdWrites:()=>s,restartAgent:()=>{i.close(),i=hp({cwd:e,profileName:n,allowProdWrites:s}),a={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>a.uuid,setPendingName:R=>{a.pendingName=R},setModel:async R=>i.setModel(R),withPausedInput:async R=>{l.pause();try{return await R()}finally{l.resume()}}};try{for(;;){let R=await $();if(R===null)break;let C=R.trim();if(C){if(C.startsWith("/")){let A=Ty(C);if(!A)continue;let D=Py[A.name];if(!D){console.log(_(`Unknown command: /${A.name}`)),console.log(f("Type /help for the list."));continue}let N=await D(A.args,S);if(N.kind==="exit")break;if(N.kind==="clear"){S.restartAgent();continue}if(N.kind==="allow-prod"){s=!0,S.restartAgent(),console.log(q("\u2713 Production writes authorized for this session.")),console.log("");continue}if(N.kind==="resume"){i.close(),i=hp({cwd:e,resume:N.uuid,profileName:n,allowProdWrites:s});let U=AE(N.uuid);a={uuid:N.uuid,firstPrompt:U?.firstPrompt??null,titleFired:!0},Zy(N.uuid),console.log(q(`\u2713 Resumed "${N.name}"`)),console.log("");continue}if(N.kind==="audit-blocked"){console.log(H(N.note)),console.log(f(` Run: ${N.lead.cmd} \u2014 ${N.lead.reason}.`)),console.log("");continue}if(N.kind==="forward-to-agent"){a.firstPrompt||(a.firstPrompt=N.display??N.prompt);let U=N.display??"",O=U.trim().split(/\s+/),Q=gg(U),z=Q?VE(e,wg(U)):[],de=O[0]==="/screenshot"&&(O[1]==="verify"||O[1]==="review"),ke=de?O[2]&&!O[2].startsWith("--")?[O[2]]:Ss(_e(e)):[],xe=O[0]==="/catch-up"&&!Q,Pe=xe?qE(e):null,fe=xe?pn(e):null,se=xe?js(e).hold:!1,te=N.prompt;if(U.startsWith("/"))try{let we=Qi(e,U);we&&(te=`${te}
454
+
455
+ ${we}`)}catch{}if(await mp(i,te,r,a,e,n),Q)try{GE(e,z,it(Q))}catch{}if(Pe){let we=mo(e,Pe,"",O[0]);if(we.cta)console.log(f(we.cta.text));else if(fe){let $e=Na({queued:fe,hold:se});$e.note&&console.log($e.tone==="warn"?H($e.note):f($e.note)),$e.lead&&console.log(f(` Run ${$e.lead.cmd} \u2014 ${$e.lead.reason}.`))}}if(O[0]==="/audit"&&!O.includes("--auto")&&Us(e,n),de&&ke.length>0)try{for(let we of mr(e,ke))console.log(we)}catch{}if(O[0]==="/push"){let we=await ps(e,n);we&&console.log(f(we))}if((O[0]==="/catch-up"||O[0]==="/document")&&(O.includes("--push")||O.includes("--publish")))try{let we=await zE({cwd:e,profileName:n}),{clean:$e,conflicts:Ye}=co(we.entries);$e.length===0?console.log(f("Nothing new to push \u2014 everything is already up to date on Document360.")):await Wt(S,$e.map(fn=>fn.path),Ye.length,{skipReview:O.includes(xt)})}catch(we){console.log(H(`Couldn't check what to push (${we.message}) \u2014 your drafts are saved; run /push when ready.`))}}else N.kind==="continue"&&N.ownNext||JE(e,n);continue}if(UE(C)){let A=WE(C);if(A){try{BE(e,{title:A,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}a.firstPrompt||(a.firstPrompt=C),await mp(i,`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${A}". 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 "${A}" and the article path(s) you wrote.`,r,a,e,n);continue}}a.firstPrompt||(a.firstPrompt=C),await mp(i,C,r,a,e,n)}}}finally{i.close(),l.close()}}function QE(e,t){console.log(""),console.log(es("document360-writer")),console.log(f(` cwd: ${e}`));let n=IE(e);if(console.log(f(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(ZE(e,t)),!LE(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(Si(e),!an(e))for(let r of Pi(e))console.log(H(` ${r}`))}catch{}try{let r=_E(e);r.persisted&&r.appType?console.log(f(` \u2713 Detected a ${r.appType} app \u2014 enabled the ${r.appType}-doc-playbook (change with /genre).`)):r.source==="unknown"&&(o=!0)}catch{}try{let r=HE(e);for(let s of vi(r.applied))console.log(H(` ${s}`));if(r.reopenedForRedaction)for(let s of xi(r.reopenedForRedaction).split(/\r?\n/))console.log(H(` ${s}`))}catch{}try{let r=Hs(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:o}),s=r?Bs(r,{pickable:!1,scaleFor:i=>On(e,i)}):null;if(s?.kind==="recommend"&&s.rec.note){let i=s.rec.tone==="warn"?H:f;for(let a of ma(s.rec.note).split(`
456
+ `))console.log(i(` ${a}`));s.rec.picker&&console.log(Z(` Pick one: ${s.rec.picker.options.map(a=>a.cmd).join(" \xB7 ")}`))}}catch{}}console.log(f(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}var Jy=!1;function JE(e,t){try{let n=Hs(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:!1}),o=n?Bs(n,{scaleFor:r=>On(e,r)}):null;if(o?.kind!=="recommend")return;if(o.rec.settled&&!Jy){Jy=!0;for(let r of ma(o.rec.settled).split(`
457
+ `))console.log(q(` ${r}`))}else o.rec.settled&&!o.rec.lead&&console.log(f(" Nothing is waiting. /roadmap lists the optional campaign steps."));o.rec.lead&&console.log(f(` Next: ${vr(o.rec.lead)}`))}catch{}}function ZE(e,t){try{let n=eb(e,t),o=n.production?H(" \u26A0 PRODUCTION"):"",r=FE(n.name,n.project.projectId);if(!r)return f(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...Xy(r.idToken)??{},...Xy(r.accessToken)??{}},i=s.email??s.preferred_username??"signed in";return ME(r)&&!r.refreshToken?H(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):f(` Document360: ${i} \xB7 profile "${n.name}"${o}`)}catch(n){return f(` Document360: ${n.message.split(".")[0]}`)}}function eN(){console.error(""),console.error(`Sign in with your Claude subscription: run ${Z("claude")} once, then retry.`),console.error(` (No Claude Code? ${Z("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${Z("https://console.anthropic.com/settings/keys")}`)}function tN(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;DE({uuid:t,name:r??NE(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function nN(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||jE(o,t).then(r=>{r&&EE(n,r)}).catch(()=>{})}async function mp(e,t,n,o,r,s){let i=new Map,a=!1;for await(let l of e.send(t))l.type==="tool"&&tb.test(l.name)&&(a=!0),oN(l,o,r,n,i,s);if(a)try{let l=KE(await YE({cwd:r,profileName:s}));l&&console.log(l.startsWith("\u26A0")?H(l):l)}catch{}}function oN(e,t,n,o,r,s){switch(e.type){case"session":t.uuid||tN(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let i=Qy()?null:Qa(e.name,e.input,n,s);if(i){process.stdout.write(`
458
+
459
+ `);let l=[i.category,i.note].filter(w=>!!w).map(w=>Re(` \xB7 ${w}`)),d=i.loud?Re(" \xB7 ")+Be(H(i.loud)):"";console.log(`${q("\u25CF")} ${Z(Be(hu(i.verb)))}${Be(i.title)}${l.join("")}${d}`),r.set(e.id,{name:e.name,input:e.input,doc:!0,keepResult:i.keepResult});break}let a=Ja(e.name,e.input,process.cwd());a&&(process.stdout.write(`
460
+
461
+ `),console.log(`${Re("\u25CF")} ${a.title}${a.arg!==null?Re(`${a.sep}(${a.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let i=Rt(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!i)break;let a=l=>l===1?"":"s";console.log(Re(` \u23BF Added ${i.added} line${a(i.added)}, removed ${i.removed} line${a(i.removed)}`));for(let l of i.lines)console.log(l);i.hidden>0&&console.log(f(` \u2026 +${i.hidden} more diff lines`));break}case"tool_result":{let i=r.get(e.id);if(!i)break;r.delete(e.id);let l=i.doc&&!i.keepResult&&!e.isError?{lines:[],hidden:0}:Za(e.output,4,e.isError||Qy()?void 0:i.name,i.input),d=e.isError?_:Re;l.lines.forEach((w,m)=>console.log(d((m===0?" \u23BF ":" ")+w))),l.hidden>0&&console.log(f(` \u2026 +${l.hidden} lines`)),e.isError||XE(i.name,i.input,e.output,n);break}case"result":{process.stdout.write(`
462
+ `);let i=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(f(` (${ws(i)}\u2192${ws(e.outputTokens)} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(Zy(t.uuid),t.titleFired||nN(t,n));break}case"error":console.error(""),e.kind==="limit"?console.log(H(`\u23F3 ${e.message}`)):console.error(_(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&eN();break}}import{render as o1}from"ink";import{resolveAuth as r1}from"document360-engine";import{useCallback as ne,useEffect as at,useMemo as Pp,useRef as ie,useState as le}from"react";import{Box as je,Text as K,useApp as IN,useInput as LN,useStdout as ON}from"ink";import{existsSync as Sr,readFileSync as fl,readdirSync as _N,writeFileSync as MN}from"node:fs";import{basename as Ys,dirname as FN,isAbsolute as UN,join as Tp}from"node:path";import{createSession as Gb,classifyClaudeAuth as Op,CLAUDE_CODE_SETUP_HINT as WN,loginPkce as BN,toStoredTokens as HN,saveTokens as GN,getAccessToken as qN,D360AuthError as VN,resolveActiveProfile as mt,resolveProjectId as YN,getArticle as KN,decodeJwtClaims as Nr,isExpired as vo,loadTokens as Un,clearTokens as zN,rememberSessionProject as XN,listStoredSessions as QN,tokensProjectId as qb,clearProfileProject as JN,setTitle as ZN,slugify as eD,touchSession as Ap,upsertSession as tD,generateTitle as Vb,findByName as nD,listSessions as oD,renameSession as rD,suggestNextAction as sD,readProjectConfig as Se,writeProjectConfig as Yb,readUserConfig as Kb,writeUserConfig as iD,resolveAndPersistAppType as aD,detectAppType as zb,resolveModelSetting as _p,loadProfileMap as Xb,applyPull as ml,computeSyncStatus as gl,lintDocs as Pr,compareRemoteSources as lD,planPull as Qb,recordRunSample as cD,pushArticles as uD,pushArticle as dD,PUSH_POOL_SIZE as pD,isPullWouldBlankError as Jb,localArticleTitle as Zb,establishBaselines as hD,rebaselineServerMeta as fD,inventoryRepo as mD,knownEnvironments as gD,currentEnvironments as ek,sunsetEnvironment as tk,resolveEnvironment as wD,planPartitions as Ep,partitionEvenly as yD,screenshotPlaceholderIds as bD,trackedArticlePaths as kD,runPartitioned as Ks,partitionCoverage as Np,estimateBulkCost as nk,resolveModelForOperation as zs,readDocsPlan as ok,checkForUpdate as $D,detectInstallKind as vD,isSelfUpdatable as xD,devHintsGuidePath as rk,toolFeedbackPath as sk,reconcileToolFeedback as RD,reconcileUpgradeActions as CD,stampArticles as Tr,snapshotArticles as ik,listArticleFiles as SD,CONTENT_CAP_VERSION as PD,ENGINE_VERSION as mk,DEFAULT_DOCS_DIR as Mp,docsRootOf as TD,setProfileProject as AD,writeCrashLog as ED,applyStructureOrder as Dp,orderSyncLine as jp,applyRelatedArticles as ak,relatedSyncLine as lk,reconcileDocsGit as ND,shareExplainedPath as DD,ensureDir as jD}from"document360-engine";er();xn();import{spawn as ob}from"node:child_process";function rN(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function sN(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?ob([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):ob(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 gp(e){for(let[t,n]of rN())if(await sN(t,n,e))return!0;return!1}var rb=/\b(?:reply|respond|answer)\s+with\s+(?:the\s+|a\s+)?(?:number|option|\d+)\b|\bpick one\b|\bpress the number\b|\b(?:tell me|let me know)\s+which\b|\bsay the number\b/i;function sb(e){let t=e.replace(/\s+$/,"").split(`
463
+ `),n=0;for(let s=t.length-1;s>=0;s--){let i=t[s];if(/^\s{0,3}\d{1,2}[.)]\s+\S/.test(i)){n++;continue}if(!(n>0&&/^\s+\S/.test(i)))break}return n<2?0:t.filter(s=>/^\s{0,3}\d{1,2}[.)]\s+\S/.test(s)).slice(-n).every((s,i)=>Number(/^\s{0,3}(\d{1,2})/.exec(s)[1])===i+1)?n:0}var iN=/\b(?:once|after|when)\s+(?:you|you've|you have|they|those|these|that)\b[^.!?]{0,80}\b(?:tell me|let me know|come back|ask me|say the word|run\s+\/|then\s+\/)|\b(?:tell me|let me know)\s+(?:when|once|and)\b|\bi'?ll\s+(?:wait|stand by|pick (?:it|this) up)\b|\bcome back to me\b|\bthen\s+(?:ask|tell)\s+me\b/i;function ib(e){let t=e.trimEnd();if(!t)return null;let n=sb(t);return n>=2?{options:n}:/\?[\s*_"')\]]*$/.test(t)||rb.test(t)||iN.test(t)?{options:0}:null}function wp(e,t){if(t.closed)return e;let n=e.split(`
464
+ `),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){rb.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(`
465
+ `)}var aN=/^(?:(?:run|use|try|execute)\s+)?['"`*]?(\/[a-z][a-z-]*)['"`*]?((?:\s+(?:--?[a-z][\w-]*|\S*[/\\]\S*|\d{1,3}[-_][\w.-]*|[\w.-]+\.(?:md|markdown)))*)/i;function lN(e,t){let n=sb(e);return n<2?[]:e.replace(/\s+$/,"").split(`
466
+ `).filter(s=>/^\s{0,3}\d{1,2}[.)]\s+\S/.test(s)).slice(-n).map(s=>{let i=s.replace(/^\s{0,3}\d{1,2}[.)]\s+/,"").trim(),a=aN.exec(i);if(!a)return null;let l=a[1].slice(1).toLowerCase();return t.has(l)?`${a[1]}${(a[2]??"").replace(/\s+/g," ").trimEnd()}`:null})}function ab(e,t){let n=lN(e,t);return n.length<2||n.some(o=>o===null)?null:n}function cN(e){let t=e.split(`
467
+ `).map(o=>o.trim()).filter(o=>o.length>3),n=t[t.length-1];return n?n.length>160?`${n.slice(0,157)}\u2026`:n:null}function xr(e){if(e.usageLimit)return`${e.label}: ${e.usageLimit}`;let t=e.stderrTail?cN(e.stderrTail):null;return t?`${e.label} last said: ${t}`:`${e.label} has said nothing since. Whatever it is, it is recorded: d360-writer logs. Stopping keeps every batch already finished.`}var uN={la:"local","l all":"local","local all":"local",pa:"portal","p all":"portal","portal all":"portal",sa:"skip","s all":"skip","skip all":"skip"},dN={L:"local",P:"portal",S:"skip"},pN={ya:"write","y all":"write","yes all":"write",na:"skip","n all":"skip","no all":"skip"},hN={Y:"write",N:"skip"};function lb(e,t,n){let o=e.trim(),r=o.toLowerCase().replace(/\s+/g," ");return t[r]??(o.length===1?n[o]??null:null)}function rl(e){return lb(e,uN,dN)}function cb(e){return lb(e,pN,hN)}function yp(e,t){let n=t?.max??12,o=t?.chrome??8;return Math.max(3,Math.min(n,(e??24)-o))}function sl(e,t,n){if(e<=n)return{start:0,end:e,above:0,below:0};let o=Math.min(Math.max(0,t),e-1),r=Math.min(Math.max(0,o-Math.floor(n/2)),e-n),s=r+n;return{start:r,end:s,above:r,below:e-s}}function bp(e,t,n,o=Date.now()){let s=e.value>0&&o-e.at<900?e.value*10+t:0,i=s>=1&&s<=n?s:t>=1&&t<=n?t:0;return i===0?{index:null,memory:{value:0,at:o}}:{index:i-1,memory:{value:i,at:o}}}function ub(e){return e<2?null:`1-${e}`}function ft(e){let t=[];if(e.multi)t.push("\u2191\u2193 move","space toggle");else{t.push("\u2191\u2193 move");let n=e.rows===void 0?null:ub(e.rows);n&&t.push(`${n} jump to a row`)}return t.push(...e.extra??[]),t.push(`enter ${e.verb}`),t.push(`esc ${e.cancel??"cancel"}`),t.join(" \xB7 ")}function db(e){if(e.multi)return"pick with space, then enter to save \xB7 esc to cancel\u2026";let t=e.rows===void 0?null:ub(e.rows);return`choose one below \u2014 \u2191\u2193 then enter to ${e.verb}${t?", or type its number":""} \xB7 esc to ${e.cancel??"cancel"}\u2026`}var fN=[/\bfile does not exist\b/i,/\bno such file or directory\b/i,/\bENOENT\b/,/\bno (files? )?(were )?found\b/i,/\bfound 0 (files?|matches|results)\b/i,/\bno matches\b/i,/\bdid not match any\b/i,/\bno results?\b/i],mN=[/\bpermission denied\b/i,/\bEACCES\b/,/\bEPERM\b/,/\bnot authori[sz]ed\b/i,/\bunauthori[sz]ed\b/i,/\bforbidden\b/i,/\brefus(ed|ing)\b/i,/\bblocked\b/i,/\bwriter mode\b/i,/\bHTTP [45]\d\d\b/],gN=/^(read|glob|grep|ls|search|notebookread)$/i;function pb(e,t){return!e||!gN.test(e.trim())||mN.some(n=>n.test(t))?!1:fN.some(n=>n.test(t))}import{existsSync as wN,mkdirSync as yN,readFileSync as bN,writeFileSync as kN}from"node:fs";import{join as hb}from"node:path";import{writerDir as $N}from"document360-engine";function fb(e){return hb($N(e),".sessions")}function mb(e,t){return hb(fb(e),`${t}.json`)}function gb(e,t,n){try{yN(fb(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");kN(mb(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function kp(e,t){try{let n=mb(e,t);if(!wN(n))return[];let o=JSON.parse(bN(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var vN=e=>`\x1B]0;${e}\x07`,xN=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function wb(e){process.stdout.isTTY&&process.stdout.write(e)}function Rr(e){wb(vN(e))}function il(e){wb(xN(e))}var al=["\xB7 "," \xB7"],ll="\u{1F7E3}";Ca();var yb=()=>({fingerprint:null,counts:null,settled:0,spokenBaseline:null,lastSpokeAt:null,awaySince:null}),RN={hints:0,requests:0,answers:0,directives:0};function $p(e,t){let n=e??RN;return{hints:Math.max(0,t.hints-n.hints),requests:Math.max(0,t.requests-n.requests),answers:Math.max(0,t.answers-n.answers),directives:Math.max(0,t.directives-n.directives)}}var cl=e=>e.hints===0&&e.requests===0&&e.answers===0&&e.directives===0,bb=e=>e.hints+e.requests+e.answers+e.directives,vp=(e,t)=>e-t>=6e5;function kb(e){let{now:t,lastInputAt:n,fingerprint:o,counts:r,occupied:s,prev:i}=e,a=vp(t,n),d=i.fingerprint!==null&&i.fingerprint!==o?0:i.settled+1,w={...i,fingerprint:o,counts:r,settled:d,awaySince:a?i.awaySince??t:null,spokenBaseline:i.spokenBaseline??r};if(a){let $=$p(w.spokenBaseline,r);return{memory:w,speak:null,waiting:cl($)?null:$}}if(s)return{memory:w,speak:null,waiting:null};if(d<2)return{memory:w,speak:null,waiting:null};let m=$p(i.spokenBaseline,r);return cl(m)?{memory:w,speak:null,waiting:null}:i.lastSpokeAt!==null&&t-i.lastSpokeAt<6e5?{memory:w,speak:null,waiting:null}:{memory:{...w,spokenBaseline:r,lastSpokeAt:t,settled:d},speak:m,waiting:null}}function $b(e,t,n){if(e.awaySince===null)return{kind:"none",memory:e};let o=t-e.awaySince,r=$p(e.spokenBaseline,n),s={...e,awaySince:null,counts:n,spokenBaseline:n,lastSpokeAt:cl(r)?e.lastSpokeAt:t};return cl(r)?{kind:"none",memory:s}:{kind:o>=36e5?"briefing":"delta",memory:s,delta:r,awayMs:o}}function qs(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===0?"":t.length===1?t[0]:`${t.slice(0,-1).join(", ")} and ${t.at(-1)}`}function xp(e){let t=Math.round(e/6e4);if(t<45)return`${t} minutes`;let n=Math.round(e/36e5);if(n<20)return`${n} hour${n===1?"":"s"}`;let o=Math.round(n/24);return o<=1?"a day":`${o} days`}function vb(e){return`\u{1F4E5} ${qs(e)} just arrived from your builder \u2014 /catch-up folds ${bb(e)===1?"it":"them"} into the docs.`}function xb(e,t){return`\u{1F4E5} While you were away (${xp(t)}): ${qs(e)} from your builder \u2014 /catch-up folds ${bb(e)===1?"it":"them"} into the docs.`}function Rb(e){return`\u{1F4E5} ${qs(e)} waiting from your builder \xB7 tab to run /catch-up\u2026`}Ei();import{publishGateVerdict as Ip,publishGateLines as Lp,SKIP_STYLE_FLAG as ck,SKIP_SHOTS_FLAG as ID}from"document360-engine";import{askBuilder as LD,openGapQuestions as OD}from"document360-engine";import{retireArticle as _D,normalizeScope as MD}from"document360-engine";re();import{Box as Vs,Text as Me}from"ink";import{jsx as Fe,jsxs as Cr}from"react/jsx-runtime";function CN({row:e,nameW:t,width:n}){let o=s=>Zl(s,n),r=(s,i)=>Fe(Vs,{flexDirection:"column",children:s.map(i)});switch(e.t){case"head":return r(o(e.s),(s,i)=>Fe(Me,{color:ae,bold:!0,children:s},i));case"text":return r(o(e.s),(s,i)=>Fe(Me,{children:s},i));case"dim":return r(o(e.s),(s,i)=>Fe(Me,{dimColor:!0,children:s},i));case"sub":return r(o(e.s),(s,i)=>Fe(Me,{bold:!0,dimColor:!0,children:s},i));case"good":return r(o(e.s),(s,i)=>Fe(Me,{color:"green",children:s},i));case"step":{let s=o(`${e.n}. ${e.s}`);return Fe(Vs,{flexDirection:"column",children:s.map((i,a)=>a===0?Cr(Me,{children:[Fe(Me,{color:ae,children:`${e.n}. `}),i.slice(`${e.n}. `.length)]},a):Fe(Me,{children:i},a))})}case"cmd":{let s=Ri(e.name,e.s,t,n),i=s.descLines.slice(s.nameOwnLine?0:1);return Cr(Vs,{flexDirection:"column",children:[Cr(Me,{children:[" ",Fe(Me,{color:ae,children:s.nameCell}),!s.nameOwnLine&&Fe(Me,{dimColor:!0,children:` ${s.descLines[0]??""}`})]}),i.map((a,l)=>Fe(Me,{dimColor:!0,children:`${s.indent}${a}`},l))]})}case"gap":return Fe(Me,{children:" "})}}function Cb({tab:e,scroll:t,rows:n,width:o,version:r,engineVersion:s}){let i=ut[e]??ut[0],a=Jl(i.rows),l=Math.max(20,o-2),d=6+ut.reduce((A,D)=>A+D.label.length+4,0),w="\u2500".repeat(Math.min(d,l)),m=`\u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 \u2191\u2193 scroll \xB7 esc close \xB7 d360-writer v${r} \xB7 engine v${s}`,$=Kh({rows:n,inner:l,barWidth:d,footerWidth:m.length}),{visible:S,above:R,below:C}=Yh(i.rows,{width:o,budget:$,scroll:t,nameW:a});return Cr(Vs,{flexDirection:"column",paddingX:1,children:[Cr(Me,{children:[Fe(Me,{color:ae,bold:!0,children:"Help "}),ut.map((A,D)=>D===e?Fe(Me,{color:"white",backgroundColor:ae,bold:!0,children:` ${A.label} `},A.key):Fe(Me,{dimColor:!0,children:` ${A.label} `},A.key))]}),Fe(Me,{color:ae,children:w}),Cr(Vs,{flexDirection:"column",marginTop:1,children:[R>0?Fe(Me,{dimColor:!0,children:`\u22EF ${R} more above`}):null,S.map((A,D)=>Fe(CN,{row:A,nameW:a,width:o},R+D)),C>0?Fe(Me,{dimColor:!0,children:`\u22EF ${C} more below`}):null]}),Fe(Me,{dimColor:!0,children:`
468
+ \u2190/\u2192 or tab switch \xB7 1-5 jump${R+C>0?" \xB7 \u2191\u2193 scroll":""} \xB7 esc close \xB7 d360-writer v${r} \xB7 engine v${s}`})]})}var SN=/^(?:\d+[.)]|[-*•])\s+/;function Sb(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
469
+ `)){let i=s.trim().replace(SN,""),a=i.match(/^`([^`]+)`$/);a&&(i=a[1].trim());let l=i.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!l||!o.has(l[1].toLowerCase()))continue;let d=`/${l[1].toLowerCase()}${l[2]?` ${l[2]}`:""}`;if(r.includes(d)||r.push(d),r.length>=n)break}return r}re();function $o(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function Ve(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function ul(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var PN=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function Rp(e,t,n){if(!PN.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 Cp(e){return e.replace(/^[\w.-]+\//,"")}var dl=16,Pb={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function Fn(e){return typeof e=="string"?e:e.cmd}function Tb(e){return typeof e=="string"?void 0:e.desc}function Sp(e){return e.trim().split(/\s+/).slice(1).join(" ")}function Ab(e,t){let n=Sp(t);return e.some(r=>Fn(r).trim()===t.trim()||!!n&&Sp(Fn(r))===n)?e.filter(r=>Fn(r).trim()!==t.trim()&&!(n&&Sp(Fn(r))===n)):[]}import{isDirectiveMention as FD,stripDirectiveMention as UD,appendDirective as WD,reconcileTestidRequest as BD,builderChannelWired as HD,pendingFingerprint as GD}from"document360-engine";var TN=/\[Pasted text #\d+ \+\d+ lines?\]/g;function Eb(e){return e.replace(/\r\n?/g,`
470
+ `)}function Nb(e){return e.includes(`
471
+ `)||e.length>200}function Db(e,t){let n=t.split(`
472
+ `).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function jb(e,t){return e.replace(TN,n=>t.get(n)??n)}function Ib(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function pl(e,t){let n=Math.max(1,t),o=[],r=0;for(let s of e.split(`
473
+ `)){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 hl(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function Lb(e,t,n){let o=hl(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 Ob(e,t,n){let o=e[hl(e,t)];return n==="start"?o.start:o.end}var AN=new Set(["Edit","Write","MultiEdit","NotebookEdit"]),_b={hint:"hint",message:"message",state:"state file",roadmap:"roadmap",directive:"directives",feedback:"tool-feedback"},EN=new Set(["hint","message","state"]),NN=["hint","message","roadmap","directive","feedback","state"];function DN(e){return e.startsWith("hints/")?"hint":e.startsWith("messages/")?"message":e==="roadmap.md"?"roadmap":e==="directives.md"?"directive":/^tool-feedback(-archived)?\.md$/.test(e)?"feedback":e.startsWith("cache/")||e.startsWith(".sessions/")||/^(plan|devhints-state|upgrade-state|category-map)\.json$/.test(e)?"state":null}function Mb(e,t){let n=e==="Read"?"read":AN.has(e)?"updated":null;if(!n)return null;let o=t.file_path??t.notebook_path;if(typeof o!="string"||!o)return null;let r=o.replace(/\\/g,"/").toLowerCase(),s=".d360-writer/",i=r.lastIndexOf(s);if(i<0)return null;let a=DN(r.slice(i+s.length));return a?{category:a,verb:n,path:r}:null}function Fb(e){let t=new Map,n=new Set;for(let r of e)r.verb==="updated"&&n.add(r.path);for(let r of e){if(r.verb==="read"&&n.has(r.path))continue;let s=`${r.category}:${r.verb}`,i=t.get(s);i||t.set(s,i=new Set),i.add(r.path)}let o=[];for(let r of NN)for(let s of["updated","read"]){let i=t.get(`${r}:${s}`)?.size??0;i!==0&&o.push(EN.has(r)?`${i} ${_b[r]}${i===1?"":"s"} ${s}`:`${_b[r]} ${s}`)}return o.length>0?o.join(" \xB7 "):null}function Ub(e,t,n){let o=Math.max(1,n),r=e.split(`
472
474
  `),s=0;for(let i=r.length-1;i>=0;i--){let a=r[i];if(s+=Math.max(1,Math.ceil(a.length/o)),s>=t){let l=s-t;return{text:[l>0?a.slice(l*o):a,...r.slice(i+1)].join(`
473
- `),truncated:i>0||l>0}}}return{text:e,truncated:!1}}function Lb(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 Ob(e){let t=!1,n=0,o=0;for(let r of e.split(`
474
- `)){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 Ar,jsx as V,jsxs as ue}from"react/jsx-runtime";var ID={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL",auto:"auto \u2014 right-sized for docs \xB7 /model to change"},rk=` 1. /init \u2014 pick your Document360 environment & scaffold config
475
+ `),truncated:i>0||l>0}}}return{text:e,truncated:!1}}function Wb(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 Bb(e){let t=!1,n=0,o=0;for(let r of e.split(`
476
+ `)){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 Er,jsx as V,jsxs as ue}from"react/jsx-runtime";var qD={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL",auto:"auto \u2014 right-sized for docs \xB7 /model to change"},uk=` 1. /init \u2014 pick your Document360 environment & scaffold config
475
477
  2. /login \u2014 sign in & pick your Document360 project (workspace auto-selected)
476
- 3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function LD(e,t,n,o){let r=Np(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=Dp(e),a=Re(e),l=(a?.docsDir??jp).replace(/\/+$/,""),d=a?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${l}/ + config`,g={version:t,engineVersion:ck,captureVersion:dt(),claude:s,model:i.model,modelSource:ID[i.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:a!==null,mode:d};if(a===null)return g;try{let w=mt(e,o);g.profile=w.name,g.apiUrl=w.connection.apiUrl,g.prod=w.production,g.project=w.project.projectName??w.project.projectId??"(chosen at login)";let k=Un(w.name,w.project.projectId);if(k){let S={...Er(k.idToken)??{},...Er(k.accessToken)??{}},v=S.email??S.preferred_username??"signed in";ko(k)?k.refreshToken&&(g.who=v,g.loggedOut=!1,g.sessionHint="session expired \u2014 refreshing\u2026"):(g.who=v,g.loggedOut=!1,g.sessionHint=`session valid until ${new Date(k.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return g}var OD=e=>e.mode==="local-only"?e.path:e.plan.path;function _D(e,t){try{let n=mt(e,t),o=Un(n.name,n.project.projectId);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...Er(o.idToken)??{},...Er(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return ko(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 sk=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],Nr=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],MD="Ask me to write or update an article\u2026",ik=2e3,FD=new Set(uo.map(e=>e.name));function Tr({ch:e,dim:t}){let[n,o]=ce(!0);return at(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),V(Y,{inverse:n,color:t&&!n?"gray":void 0,children:e})}function hn({rows:e,cursor:t,cap:n,render:o}){let r=rl(e.length,t,n);return ue(Ar,{children:[r.above>0?V(Y,{color:"gray",children:` \u22EF ${r.above} more above`}):null,e.slice(r.start,r.end).map((s,i)=>o(s,r.start+i,r.start+i===t)),r.below>0?V(Y,{color:"gray",children:` \u22EF ${r.below} more below`}):null]})}var ak=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function lk(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var UD=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function WD({startTime:e,chars:t}){let[n,o]=ce(0),r=le(Date.now());at(()=>{let d=setInterval(()=>o(g=>g+1),120);return()=>clearInterval(d)},[]);let s=Nr[n%Nr.length],i=sk[Math.floor(n/16)%sk.length],a=lg(e,r.current,Date.now()),l=Math.round(t/4);return ue(je,{children:[V(Y,{color:ae,children:` ${s} ${i}\u2026 `}),V(Y,{color:"gray",children:`(${En(a)} \xB7 ~${l} tokens \xB7 esc to interrupt)`})]})}function BD({text:e}){let[t,n]=ce(0);return at(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),V(je,{paddingX:1,children:V(Y,{color:ae,children:`${Nr[t%Nr.length]} ${e}`})})}var HD=12e4;function GD({p:e}){let[t,n]=ce(0);at(()=>{let D=setInterval(()=>n(L=>L+1),150);return()=>clearInterval(D)},[]);let o=Nr[t%Nr.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),i=Math.round(e.chars/4),a=Date.now()-e.lastAt>=HD,l=e.verb??"Converting",d=e.unit??"article",g=e.rows.reduce((D,L)=>D+L.items,0),w=e.rows.reduce((D,L)=>D+(L.status==="done"?L.items:L.itemsDone??0),0),k=l.toLowerCase(),S=e.rows,v=0;if(S.length>ul){let D=S.findIndex(B=>B.status==="active"||B.status==="pending"),L=Math.max(0,Math.min(D-2,S.length-ul));v=S.slice(0,L).filter(B=>B.status==="done").length,S=S.slice(L,L+ul)}let C=Math.min(40,Math.max(...S.map(D=>kp(D.label).length),0)),T=D=>D==="failed"?"red":D==="active"?ae:void 0;return ue(je,{flexDirection:"column",children:[ue(je,{children:[V(Y,{color:ae,children:` ${o} ${l} ${g} ${d}${g===1?"":"s"} `}),V(Y,{color:"gray",children:e.agentless?`\xB7 ${w}/${g} ${d}${g===1?"":"s"} \xB7 ${En(r)} \xB7 esc to stop`:`\xB7 ${w}/${g} ${d}${g===1?"":"s"} \xB7 ${e.done}/${e.total} batch${e.total===1?"":"es"} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${i} tokens \xB7 ${En(r)} \xB7 esc to stop`})]}),v>0&&V(Y,{dimColor:!0,children:` \u2714 +${v} done`}),S.map(D=>ue(Y,{color:T(D.status),dimColor:D.status==="done"||D.status==="pending",children:[` ${$b[D.status]} ${kp(D.label).padEnd(C)}`,D.status==="active"&&D.itemsDone!==void 0?` (${D.itemsDone}/${D.items} ${d}${D.items===1?"":"s"})`:D.status!=="pending"?` (${D.items} ${d}${D.items===1?"":"s"})`:"",D.status==="active"?` \u2190 ${k}\u2026`:""]},D.label)),a&&V(Y,{color:"yellow",children:` \u26A0 no activity for ${En(s)} \u2014 press esc to stop if it's wedged`}),a&&e.stalledNote?V(Y,{color:"yellow",children:` ${e.stalledNote}`}):null]})}var qD=10800*1e3;function uk({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=CN(),[s,i]=ce(n),[a,l]=ce(null),[d,g]=ce({text:"",pos:0}),w=d.text,k=te(u=>{g(p=>{let c=typeof u=="function"?u(p.text):u;return{text:c,pos:c.length}})},[]),S=te(u=>{g(p=>({text:p.text.slice(0,p.pos)+u+p.text.slice(p.pos),pos:p.pos+u.length}))},[]),v=te(()=>{g(u=>{if(u.pos===0)return u;let p=u.text.slice(0,u.pos),c=Tb(p)??p.slice(0,-1);return{text:c+u.text.slice(u.pos),pos:c.length}})},[]),[C,T]=ce(!1),[D,L]=ce(!1),[B,M]=ce(0),[X,z]=ce(!1),[de,be]=ce(null),[$e,Ce]=ce(null),[fe,se]=ce([]),ee=le(!1),ge=le(!1),ke=le(null),Ye=le(!1),[fn,mn]=ce(!1),At=le(!1),gt=le(0),[Dr,tt]=ce(!1),[$o,Wn]=ce(!1),[vo,xo]=ce(null),[Ae,Ue]=ce(0),Et=le(0),[wl,Ro]=ce(0),[Co,Xs]=ce(null),[So,jr]=ce(null),Mp=le(new Map),gk=le(0),Po=le([]),Nt=le(null);Nt.current===null&&(Nt.current=Mb({cwd:e,profileName:s,allowProdWrites:!1}));let Jt=le({uuid:null,firstPrompt:null,titleFired:!1}),Ir=le(new Map),Fp=le(null),Qs=le(Bb().verboseTranscript===!0),gn=le(!1),yl=le([]),Ee=le([]),Zt=le([]),Dt=le([]),Lr=le(null),[Up,Bn]=ce(null),bl=le(null),[wn,Hn]=ce(null),[jt,To]=ce(null),[It,Ao]=ce(null),[Ke,Eo]=ce(null),[nt,Gn]=ce(null),[wt,No]=ce(null),[Lt,Do]=ce(null),[Ot,qn]=ce(null),[yt,en]=ce(null),[Qe,Or]=ce(null),Wp=le({value:0,at:0}),Bp=le({value:0,at:0}),tn=te((u,p)=>{let{index:c,memory:m}=fp(Bp.current,Number(u),p);return Bp.current=m,c},[]),[lt,Vn]=ce(null),[Hp,jo]=ce(null);at(()=>jr(null),[fe]);let[bt,Yn]=ce(null),[ot,Io]=ce(null),[Gp,kl]=ce([]),Kn=le([]),_r=le(!1),Mr=le(null),$l=le(null),[wk,qp]=ce(!1),Le=le(null),[Lo,he]=ce(null),[Vp,We]=ce(null),Js=le(!1),Fr=le(null),Oo=le(null),[kt,zn]=ce(null),[Ur,Xn]=ce(null),Wr=!!(It||Ke||nt||wt||Lt||Ot||yt||Qe||lt||bt||ot||kt||Ur),Yp=Lt?{verb:"publish live",cancel:"leave as drafts",rows:Lt.rows.length+1}:wt?{verb:"push as drafts",rows:wt.rows.length}:lt?{verb:"choose it",rows:lt.rows.length}:Ot?{verb:"run it",rows:Ot.rows.length}:yt?{verb:"open it",cancel:"close",rows:yt.rows.length-1}:Ke?{verb:"switch",rows:Ke.rows.length}:nt?{verb:"switch",rows:nt.rows.length}:It?{verb:"use it",rows:It.rows.length}:jt?{verb:"switch",rows:jt.rows.length,extra:["s this session only"]}:wn?{verb:"use it",rows:Pt.length}:ot?{verb:"save",multi:!0}:null,[Kp,Qn]=ce(0),[Br,Jn]=ce(0),[yk,zp]=ce(0),vl=vp(()=>{try{let u=Dp(e);return u.source==="auto"?`${u.model} (auto)`:u.model}catch{return null}},[e,yk]),{stdout:ze}=PN(),[,bk]=ce(0),Xp=le(`${ze.columns??80}x${ze.rows??24}`),Ge=te(()=>Math.max(20,(ze.columns??80)-1),[ze]),Zs=te(u=>{Po.current.push(u);let p=cu(u,Ge());_o.current+=p.split(`
477
- `).length+1,console.log(p)},[Ge]),xl=le([]),ei=te(()=>{let u=xl.current;if(u.length===0)return;xl.current=[];let p=jb(u);p&&Zs({kind:"note",tone:"info",text:`\u25CF Housekeeping ${p}`})},[Zs]),h=te(u=>{ei(),Zs(u)},[Zs,ei]),rt=le({printed:[],armed:[],printedAt:0}),ti=le(null),Rl=le([]),_o=le(0),Je=te((u,p)=>{gt.current++,rt.current.armed=[],be(u),Ce(p??null)},[]),_t=te(()=>{gt.current++,rt.current.armed=[],be(null),Ce(null)},[]),Hr=te(u=>{gt.current++,rt.current.armed=[],be(null),Ce(u)},[]),oe=te(u=>Je(u,kr({kind:"cmd",cmd:u,reason:""})),[Je]),nn=te((u,p)=>{if(!p?.silent&&u.note&&h({kind:"note",tone:p?.tone??u.tone,text:u.note}),!p?.silent&&u.note?.includes(".d360-writer/ \u2014 your articles"))try{let A=$D(e);vD(EN(A)),AN(A,`${new Date().toISOString()}
478
- `)}catch{}u.picker&&(se(u.picker.options.map(A=>({cmd:A.cmd,desc:A.desc}))),jo(u.picker.title),Rl.current=u.picker.exclusive?u.picker.options.map(A=>A.cmd.trim()):[]),!p?.silent&&u.note&&(rt.current.printed=u.menu,rt.current.printedAt=_o.current);let m=_o.current-rt.current.printedAt<Math.max(8,(ze.rows??24)-4)&&Py(rt.current.printed,u.menu)?u.menu:[];u.lead?(u.lead.kind==="answer"?Hr(kr(u.lead,m.length)):Je(u.lead.kind==="cmd"?u.lead.cmd:u.lead.text,kr(u.lead,m.length)),!p?.silent&&u.note&&(ti.current=Us(u.lead))):!p?.silent&&!u.picker&&(_t(),m.length>0&&Hr(`1\u2013${m.length} to pick a campaign step \xB7 nothing is waiting \xB7 or just ask me anything\u2026`)),rt.current.armed=m},[h,Je,Hr,e,ze]),Ne=te((u,p,c="info")=>{rt.current.armed=[],u&&h({kind:"note",tone:c,text:u}),p&&(p.kind==="answer"?Hr(kr(p)):Je(p.kind==="cmd"?p.cmd:p.text,kr(p)),ti.current=u?Us(p):null)},[h,Je,Hr]),Mo=te((u,p,c,m="info")=>{if(u.producedNothing){Ne("Nothing was changed \u2014 the agent produced no output, so this command did nothing at all.",{kind:"cmd",cmd:"/doctor",reason:"it checks Claude sign-in + whether the model is reachable from this machine"},"warn");return}u.handedBack||Ne(p,c,m)},[Ne]),[Gr,Cl]=ce(null),[kk,Qp]=ce(!1),on=te((u,p)=>{Cl(u),Qp(!1),h({kind:"note",tone:"info",text:p?.hint??"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[h]),Sl=te(()=>{ND(e,new Date().toISOString());let u=fw(e);u&&(h({kind:"note",tone:"info",text:u.lines.join(`
479
- `)}),on(u.prompt,DD(e)?{hint:"\u2328 Press c to copy the request \u2014 only if you want to hand it over now; your builder already has it."}:void 0))},[e,h,on]),Pl=le(!1),Tl=te(async()=>{try{if(Pl.current||!hD(pD())||Re(e)?.mode==="engineer")return;let u=await dD({pkg:yr,currentVersion:o,force:!0});if(!u.updateAvailable||!u.latest)return;Pl.current=!0,h({kind:"note",tone:"info",text:`\u2B06 Updating ${yr} ${u.current} \u2192 ${u.latest}\u2026 (wait for the \u2713 before you /exit)`}),Wn(!0);let p=await Oa().finally(()=>Wn(!1));p.ok?(h({kind:"note",tone:"ok",text:`\u2713 Updated to v${u.latest} \u2014 run /exit, then relaunch to apply.`}),oe("/exit"),xo(u.latest)):h({kind:"note",tone:"warn",text:`Update available (v${u.latest}) but auto-update failed. ${La(p.output)}`})}catch{}},[e,o,h,oe]),qr=le(!1),Al=le(null),Jp=te(async u=>{if(!qr.current)try{let p=Re(e);if(!p)return;let c=Zp.current;if(!c)return;if(c.pushConsent!=="on"){if(c.uncommitted===0)return;qr.current=!0;try{let A=await kD(e,p);if(A.commit?.ok)Al.current=null;else if(A.commit&&!A.commit.ok){let W=`${A.commit.reason}:${A.commit.detail??""}`;Al.current!==W&&(Al.current=W,h({kind:"note",tone:"warn",text:`\u26A0 Couldn't save your docs work to git \u2014 ${Ln(A.commit.reason,A.commit.detail)}`}))}}finally{qr.current=!1}return}if(c.uncommitted===0&&c.unpushed===0&&!u.pull)return;qr.current=!0;try{let{lines:A,changed:W}=await Ta(e,p);for(let G of A)G.tone==="warn"||G.tone==="error"?h({kind:"note",tone:G.tone,text:G.text}):G.text.includes("\u2B07")&&h({kind:"note",tone:G.tone,text:G.text});W&&M(G=>G+1)}finally{qr.current=!1}}catch{}},[e,h]),Zn=te(u=>{let p=qe(e,s);return p.ok?!0:(h({kind:"note",tone:"warn",text:p.reason}),Oo.current=u,oe("/login"),!1)},[e,s,h,oe]),[ni,El]=ce(null),Zp=le(null),eh=le(null),Mt=te((u,p)=>{let c=Bs(e,s,{claudeMissing:Np(t).state==="missing",allowAutoAudit:u,genreUnknown:Ye.current,pendingAnswer:ke.current,lastCommand:eh.current});return Zp.current=c?.handoff??null,c?Ws(c,{header:p,pickable:!0,scaleFor:m=>On(e,m)}):{kind:"idle"}},[e,s,t]),Nl=le(Date.now()),Vr=le(pb()),th=le(0),[nh,oh]=ce(null),Yr=le(!0),Fo=le(!1),oi=le(0),Kr=le(0);at(()=>{let u=setInterval(()=>{if(Yr.current){oi.current=0,Kr.current=0;return}if(!C)try{if(!Cr(Jb(e)))return;if(Ut(e).status==="current"){Yr.current=!0,oi.current=0,Kr.current=0;let c=Fo.current?`\u2713 Your builder finished the protocol update (v${Ie}) \u2014 the dev\u2194docs hand-off is current again. Here\u2019s where your docs stand:`:"\u2713 Your builder finished the hand-off \u2014 the architecture brief is in. I can read this repo now and write accurate docs. Here\u2019s where things stand:",m=Mt(!1,c),A=m.kind==="recommend"?m.rec:null;Cl(null),A?.note?nn(A,{tone:"ok"}):(h({kind:"note",tone:"ok",text:`${c}${A?.lead?` ${$r(A.lead)}`:""}`}),A?.lead||A?.picker?nn(A,{silent:!0}):Fo.current||Je("write the docs for this repo")),M(W=>W+1);return}if(Fo.current)return;oi.current+=1;let p=oi.current;if((p===4||p%15===0)&&Kr.current<3){Kr.current+=1;let c=Kr.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";h({kind:"note",tone:"info",text:an(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${c}`:`\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.${c}`})}}catch{}},4e3);return()=>clearInterval(u)},[e,C,h,Mt,nn,Je]),at(()=>{let u=Up??Ys(e);if(!C){sl(0),xr(`${al} ${u}`);return}sl(3);let p=0;xr(`${il[0]} ${u}`);let c=setInterval(()=>{p=(p+1)%il.length,xr(`${il[p]} ${u}`)},400);return()=>clearInterval(c)},[C,e,Up]),at(()=>()=>sl(0),[]),at(()=>{let u=performance.now(),p=[],c=(y,$)=>{let R=performance.now();try{return $()}finally{let b=Math.round(performance.now()-R);b>=80&&p.push(`${y}: ${b}ms`)}};h({kind:"banner",info:c("banner",()=>LD(e,o,t,s))});let m=Np(t).state==="missing";if(m&&h({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.
480
- ${DN}
481
- Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!Re(e)){h({kind:"note",tone:"info",text:`Welcome! This repo isn't set up for d360-writer yet \u2014 three steps and you're writing docs:
482
- ${rk}`}),oe(m?"/doctor":"/init");return}m&&oe("/doctor");try{let y=mt(e,s);y.project.projectId&&UN(y.name,y.project.projectId,y.project.projectName);let $=Un(y.name,y.project.projectId),R=qe(e,s);$&&ko($)&&$.refreshToken?ON({profile:y.name,connection:y.connection,projectId:y.project.projectId,projectName:y.project.projectName}).then(()=>{h({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),M(b=>b+1)}).catch(()=>{h({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 sign in again with /login."}),oe("/login")}):R.ok||(h({kind:"note",tone:"warn",text:R.reason}),oe("/login"))}catch{}try{let y=Re(e),$=mt(e,s),R=Un($.name,$.project.projectId);y&&R&&!ko(R)&&sp(e,y.authoritativeSourceFiles)&&!ip(e,s)&&(h({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),oe("/scope"))}catch{}try{let y=c("resolve-genre",()=>QN(e));y.persisted&&y.appType?h({kind:"note",tone:"ok",text:`\u2713 Detected a ${y.appType} app \u2014 enabled the ${y.appType}-doc-playbook (change with /genre, or edit .d360-writer/config.json).`}):y.source==="unknown"&&Re(e)&&(Ye.current=!0)}catch{}let A=Ut(e);try{if(c("reconcile-devhints",()=>Si(e)),A.status!=="current"&&!an(e)){let y=Pi(e);y.length&&(h({kind:"note",tone:"warn",text:y.join(`
483
- `)}),on(ro()),Yr.current=!1,Fo.current=!1)}}catch{}try{let y=c("reconcile-feedback",()=>fD(e));y.archived>0&&h({kind:"note",tone:"ok",text:`\u2713 Tidied ${y.archived} resolved item${y.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${y.open>0?`; ${y.open} still open`:""}.`})}catch{}try{let y=c("upgrade-actions",()=>mD(e));y.applied.length>0&&h({kind:"note",tone:"warn",text:vi(y.applied).join(`
484
- `)}),y.reopenedForRedaction&&h({kind:"note",tone:"warn",text:xi(y.reopenedForRedaction)})}catch{}let W=c("ready-decision",()=>Mt(!0));W.kind==="autoAudit"?(h({kind:"note",tone:"info",text:W.note}),hs({cwd:e,profileName:s}).then(y=>{if(y.kind==="audit-blocked"){Ne(y.note,{kind:"cmd",cmd:y.lead.cmd,reason:y.lead.reason},"warn");return}y.kind!=="forward-to-agent"||!y.prompt||Se(y.prompt,{display:y.display,quietUser:!0}).then($=>{if($.producedNothing)return;let R=oa(e,s);if(R){Ne(R.note,{kind:"cmd",cmd:sr.cmd,reason:sr.reason},"warn"),M(b=>b+1);return}Fs(e,s),M(b=>b+1)})})):W.kind==="recommend"&&nn(W.rec);let G=Math.round(performance.now()-u);G>=800&&bD({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${G}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${p.length?p.join(`
478
+ 3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function VD(e,t,n,o){let r=Op(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=_p(e),a=Se(e),l=(a?.docsDir??Mp).replace(/\/+$/,""),d=a?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${l}/ + config`,w={version:t,engineVersion:mk,captureVersion:dt(),claude:s,model:i.model,modelSource:qD[i.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:a!==null,mode:d};if(a===null)return w;try{let m=mt(e,o);w.profile=m.name,w.apiUrl=m.connection.apiUrl,w.prod=m.production,w.project=m.project.projectName??m.project.projectId??"(chosen at login)";let $=Un(m.name,m.project.projectId);if($){let S={...Nr($.idToken)??{},...Nr($.accessToken)??{}},R=S.email??S.preferred_username??"signed in";vo($)?$.refreshToken&&(w.who=R,w.loggedOut=!1,w.sessionHint="session expired \u2014 refreshing\u2026"):(w.who=R,w.loggedOut=!1,w.sessionHint=`session valid until ${new Date($.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return w}var YD=e=>e.mode==="local-only"?e.path:e.plan.path;function KD(e,t){try{let n=mt(e,t),o=Un(n.name,n.project.projectId);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...Nr(o.idToken)??{},...Nr(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return vo(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 dk=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],Dr=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],zD="Ask me to write or update an article\u2026",pk=2e3,XD=new Set(po.map(e=>e.name));function Ar({ch:e,dim:t}){let[n,o]=le(!0);return at(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),V(K,{inverse:n,color:t&&!n?"gray":void 0,children:e})}function hn({rows:e,cursor:t,cap:n,render:o}){let r=sl(e.length,t,n);return ue(Er,{children:[r.above>0?V(K,{color:"gray",children:` \u22EF ${r.above} more above`}):null,e.slice(r.start,r.end).map((s,i)=>o(s,r.start+i,r.start+i===t)),r.below>0?V(K,{color:"gray",children:` \u22EF ${r.below} more below`}):null]})}var hk=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function fk(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var QD=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function JD({startTime:e,chars:t}){let[n,o]=le(0),r=ie(Date.now());at(()=>{let d=setInterval(()=>o(w=>w+1),120);return()=>clearInterval(d)},[]);let s=Dr[n%Dr.length],i=dk[Math.floor(n/16)%dk.length],a=pg(e,r.current,Date.now()),l=Math.round(t/4);return ue(je,{children:[V(K,{color:ae,children:` ${s} ${i}\u2026 `}),V(K,{color:"gray",children:`(${En(a)} \xB7 ~${l} tokens \xB7 esc to interrupt)`})]})}function ZD({text:e}){let[t,n]=le(0);return at(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),V(je,{paddingX:1,children:V(K,{color:ae,children:`${Dr[t%Dr.length]} ${e}`})})}var e1=12e4;function t1({p:e}){let[t,n]=le(0);at(()=>{let D=setInterval(()=>n(N=>N+1),150);return()=>clearInterval(D)},[]);let o=Dr[t%Dr.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),i=Math.round(e.chars/4),a=Date.now()-e.lastAt>=e1,l=e.verb??"Converting",d=e.unit??"article",w=e.rows.reduce((D,N)=>D+N.items,0),m=e.rows.reduce((D,N)=>D+(N.status==="done"?N.items:N.itemsDone??0),0),$=l.toLowerCase(),S=e.rows,R=0;if(S.length>dl){let D=S.findIndex(U=>U.status==="active"||U.status==="pending"),N=Math.max(0,Math.min(D-2,S.length-dl));R=S.slice(0,N).filter(U=>U.status==="done").length,S=S.slice(N,N+dl)}let C=Math.min(40,Math.max(...S.map(D=>Cp(D.label).length),0)),A=D=>D==="failed"?"red":D==="active"?ae:void 0;return ue(je,{flexDirection:"column",children:[ue(je,{children:[V(K,{color:ae,children:` ${o} ${l} ${w} ${d}${w===1?"":"s"} `}),V(K,{color:"gray",children:e.agentless?`\xB7 ${m}/${w} ${d}${w===1?"":"s"} \xB7 ${En(r)} \xB7 esc to stop`:`\xB7 ${m}/${w} ${d}${w===1?"":"s"} \xB7 ${e.done}/${e.total} batch${e.total===1?"":"es"} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${i} tokens \xB7 ${En(r)} \xB7 esc to stop`})]}),R>0&&V(K,{dimColor:!0,children:` \u2714 +${R} done`}),S.map(D=>ue(K,{color:A(D.status),dimColor:D.status==="done"||D.status==="pending",children:[` ${Pb[D.status]} ${Cp(D.label).padEnd(C)}`,D.status==="active"&&D.itemsDone!==void 0?` (${D.itemsDone}/${D.items} ${d}${D.items===1?"":"s"})`:D.status!=="pending"?` (${D.items} ${d}${D.items===1?"":"s"})`:"",D.status==="active"?` \u2190 ${$}\u2026`:""]},D.label)),a&&V(K,{color:"yellow",children:` \u26A0 no activity for ${En(s)} \u2014 press esc to stop if it's wedged`}),a&&e.stalledNote?V(K,{color:"yellow",children:` ${e.stalledNote}`}):null]})}var n1=10800*1e3;function gk({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=IN(),[s,i]=le(n),[a,l]=le(null),[d,w]=le({text:"",pos:0}),m=d.text,$=ne(u=>{w(p=>{let c=typeof u=="function"?u(p.text):u;return{text:c,pos:c.length}})},[]),S=ne(u=>{w(p=>({text:p.text.slice(0,p.pos)+u+p.text.slice(p.pos),pos:p.pos+u.length}))},[]),R=ne(()=>{w(u=>{if(u.pos===0)return u;let p=u.text.slice(0,u.pos),c=Ib(p)??p.slice(0,-1);return{text:c+u.text.slice(u.pos),pos:c.length}})},[]),[C,A]=le(!1),[D,N]=le(!1),[U,O]=le(0),[Q,z]=le(!1),[de,ke]=le(null),[xe,Pe]=le(null),[fe,se]=le([]),te=ie(!1),we=ie(!1),$e=ie(null),Ye=ie(!1),[fn,mn]=le(!1),At=ie(!1),gt=ie(0),[jr,tt]=le(!1),[xo,Wn]=le(!1),[Ro,Co]=le(null),[Ne,Ue]=le(0),Et=ie(0),[yl,So]=le(0),[Po,Xs]=le(null),[To,Ir]=le(null),Hp=ie(new Map),vk=ie(0),Ao=ie([]),Nt=ie(null);Nt.current===null&&(Nt.current=Gb({cwd:e,profileName:s,allowProdWrites:!1}));let Jt=ie({uuid:null,firstPrompt:null,titleFired:!1}),Lr=ie(new Map),Gp=ie(null),bl=ie(null),Qs=ie(Kb().verboseTranscript===!0),gn=ie(!1),kl=ie([]),De=ie([]),Zt=ie([]),Dt=ie([]),Or=ie(null),[qp,Bn]=le(null),$l=ie(null),[wn,Hn]=le(null),[jt,Eo]=le(null),[It,No]=le(null),[Ke,Do]=le(null),[nt,Gn]=le(null),[wt,jo]=le(null),[Lt,Io]=le(null),[Ot,qn]=le(null),[yt,en]=le(null),[Qe,_r]=le(null),Vp=ie({value:0,at:0}),Yp=ie({value:0,at:0}),tn=ne((u,p)=>{let{index:c,memory:g}=bp(Yp.current,Number(u),p);return Yp.current=g,c},[]),[lt,Vn]=le(null),[Kp,Lo]=le(null);at(()=>Ir(null),[fe]);let[bt,Yn]=le(null),[ot,Oo]=le(null),[zp,vl]=le([]),Kn=ie([]),Mr=ie(!1),Fr=ie(null),xl=ie(null),[xk,Xp]=le(!1),Oe=ie(null),[_o,pe]=le(null),[Qp,We]=le(null),Js=ie(!1),Ur=ie(null),zn=ie(null),[kt,Xn]=le(null),[Wr,Qn]=le(null),Br=!!(It||Ke||nt||wt||Lt||Ot||yt||Qe||lt||bt||ot||kt||Wr),Jp=Lt?{verb:"publish live",cancel:"leave as drafts",rows:Lt.rows.length+1}:wt?{verb:"push as drafts",rows:wt.rows.length}:lt?{verb:"choose it",rows:lt.rows.length}:Ot?{verb:"run it",rows:Ot.rows.length}:yt?{verb:"open it",cancel:"close",rows:yt.rows.length-1}:Ke?{verb:"switch",rows:Ke.rows.length}:nt?{verb:"switch",rows:nt.rows.length}:It?{verb:"use it",rows:It.rows.length}:jt?{verb:"switch",rows:jt.rows.length,extra:["s this session only"]}:wn?{verb:"use it",rows:Pt.length}:ot?{verb:"save",multi:!0}:null,[Zp,Jn]=le(0),[Hr,Zn]=le(0),[Rk,eh]=le(0),Rl=Pp(()=>{try{let u=_p(e);return u.source==="auto"?`${u.model} (auto)`:u.model}catch{return null}},[e,Rk]),{stdout:ze}=ON(),[,Ck]=le(0),th=ie(`${ze.columns??80}x${ze.rows??24}`),qe=ne(()=>Math.max(20,(ze.columns??80)-1),[ze]),Zs=ne(u=>{Ao.current.push(u);let p=fu(u,qe());Mo.current+=p.split(`
479
+ `).length+1,console.log(p)},[qe]),Cl=ie([]),ei=ne(()=>{let u=Cl.current;if(u.length===0)return;Cl.current=[];let p=Fb(u);p&&Zs({kind:"note",tone:"info",text:`\u25CF Housekeeping ${p}`})},[Zs]),h=ne(u=>{ei(),Zs(u)},[Zs,ei]),rt=ie({printed:[],armed:[],printedAt:0}),ti=ie(null),Sl=ie([]),Mo=ie(0),Je=ne((u,p)=>{gt.current++,rt.current.armed=[],ke(u),Pe(p??null)},[]),_t=ne(()=>{gt.current++,rt.current.armed=[],ke(null),Pe(null)},[]),Gr=ne(u=>{gt.current++,rt.current.armed=[],ke(null),Pe(u)},[]),oe=ne(u=>Je(u,$r({kind:"cmd",cmd:u,reason:""})),[Je]),nn=ne((u,p)=>{if(!p?.silent&&u.note&&h({kind:"note",tone:p?.tone??u.tone,text:u.note}),!p?.silent&&u.note?.includes(".d360-writer/ \u2014 your articles"))try{let T=DD(e);jD(FN(T)),MN(T,`${new Date().toISOString()}
480
+ `)}catch{}u.picker&&(se(u.picker.options.map(T=>({cmd:T.cmd,desc:T.desc}))),Lo(u.picker.title),Sl.current=u.picker.exclusive?u.picker.options.map(T=>T.cmd.trim()):[]),!p?.silent&&u.note&&(rt.current.printed=u.menu,rt.current.printedAt=Mo.current);let g=Mo.current-rt.current.printedAt<Math.max(8,(ze.rows??24)-4)&&Ny(rt.current.printed,u.menu)?u.menu:[];u.lead?(u.lead.kind==="answer"?Gr($r(u.lead,g.length)):Je(u.lead.kind==="cmd"?u.lead.cmd:u.lead.text,$r(u.lead,g.length)),!p?.silent&&u.note&&(ti.current=Ws(u.lead))):!p?.silent&&!u.picker&&(_t(),g.length>0&&Gr(`1\u2013${g.length} to pick a campaign step \xB7 nothing is waiting \xB7 or just ask me anything\u2026`)),rt.current.armed=g},[h,Je,Gr,e,ze]),Ee=ne((u,p,c="info")=>{rt.current.armed=[],u&&h({kind:"note",tone:c,text:u}),p&&(p.kind==="answer"?Gr($r(p)):Je(p.kind==="cmd"?p.cmd:p.text,$r(p)),ti.current=u?Ws(p):null)},[h,Je,Gr]),Fo=ne((u,p,c,g="info")=>{if(u.producedNothing){Ee("Nothing was changed \u2014 the agent produced no output, so this command did nothing at all.",{kind:"cmd",cmd:"/doctor",reason:"it checks Claude sign-in + whether the model is reachable from this machine"},"warn");return}u.handedBack||Ee(p,c,g)},[Ee]),[qr,Pl]=le(null),[Sk,nh]=le(!1),on=ne((u,p)=>{Pl(u),nh(!1),h({kind:"note",tone:"info",text:p?.hint??"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[h]),Tl=ne(()=>{BD(e,new Date().toISOString());let u=yw(e);u&&(h({kind:"note",tone:"info",text:u.lines.join(`
481
+ `)}),on(u.prompt,HD(e)?{hint:"\u2328 Press c to copy the request \u2014 only if you want to hand it over now; your builder already has it."}:void 0))},[e,h,on]),Al=ie(!1),El=ne(async()=>{try{if(Al.current||!xD(vD())||Se(e)?.mode==="engineer")return;let u=await $D({pkg:br,currentVersion:o,force:!0});if(!u.updateAvailable||!u.latest)return;Al.current=!0,h({kind:"note",tone:"info",text:`\u2B06 Updating ${br} ${u.current} \u2192 ${u.latest}\u2026 (wait for the \u2713 before you /exit)`}),Wn(!0);let p=await _a().finally(()=>Wn(!1));p.ok?(h({kind:"note",tone:"ok",text:`\u2713 Updated to v${u.latest} \u2014 run /exit, then relaunch to apply.`}),oe("/exit"),Co(u.latest)):h({kind:"note",tone:"warn",text:`Update available (v${u.latest}) but auto-update failed. ${Oa(p.output)}`})}catch{}},[e,o,h,oe]),Vr=ie(!1),Nl=ie(null),oh=ne(async u=>{if(!Vr.current)try{let p=Se(e);if(!p)return;let c=rh.current;if(!c)return;if(c.pushConsent!=="on"){if(c.uncommitted===0)return;Vr.current=!0;try{let T=await ND(e,p);if(T.commit?.ok)Nl.current=null;else if(T.commit&&!T.commit.ok){let W=`${T.commit.reason}:${T.commit.detail??""}`;Nl.current!==W&&(Nl.current=W,h({kind:"note",tone:"warn",text:`\u26A0 Couldn't save your docs work to git \u2014 ${Ln(T.commit.reason,T.commit.detail)}`}))}}finally{Vr.current=!1}return}if(c.uncommitted===0&&c.unpushed===0&&!u.pull)return;Vr.current=!0;try{let{lines:T,changed:W}=await Aa(e,p);for(let B of T)B.tone==="warn"||B.tone==="error"?h({kind:"note",tone:B.tone,text:B.text}):B.text.includes("\u2B07")&&h({kind:"note",tone:B.tone,text:B.text});W&&O(B=>B+1)}finally{Vr.current=!1}}catch{}},[e,h]),eo=ne(u=>{let p=He(e,s);return p.ok?!0:(h({kind:"note",tone:"warn",text:p.reason}),zn.current=u,oe("/login"),!1)},[e,s,h,oe]),[ni,Dl]=le(null),rh=ie(null),sh=ie(null),Mt=ne((u,p)=>{let c=Hs(e,s,{claudeMissing:Op(t).state==="missing",allowAutoAudit:u,genreUnknown:Ye.current,pendingAnswer:$e.current,lastCommand:sh.current});return rh.current=c?.handoff??null,c?Bs(c,{header:p,pickable:!0,scaleFor:g=>On(e,g)}):{kind:"idle"}},[e,s,t]),jl=ie(Date.now()),Yr=ie(yb()),ih=ie(0),[ah,lh]=le(null),Kr=ie(!0),Uo=ie(!1),oi=ie(0),zr=ie(0);at(()=>{let u=setInterval(()=>{if(Kr.current){oi.current=0,zr.current=0;return}if(!C)try{if(!Sr(rk(e)))return;if(Ut(e).status==="current"){Kr.current=!0,oi.current=0,zr.current=0;let c=Uo.current?`\u2713 Your builder finished the protocol update (v${Le}) \u2014 the dev\u2194docs hand-off is current again. Here\u2019s where your docs stand:`:"\u2713 Your builder finished the hand-off \u2014 the architecture brief is in. I can read this repo now and write accurate docs. Here\u2019s where things stand:",g=Mt(!1,c),T=g.kind==="recommend"?g.rec:null;Pl(null),T?.note?nn(T,{tone:"ok"}):(h({kind:"note",tone:"ok",text:`${c}${T?.lead?` ${vr(T.lead)}`:""}`}),T?.lead||T?.picker?nn(T,{silent:!0}):Uo.current||Je("write the docs for this repo")),O(W=>W+1);return}if(Uo.current)return;oi.current+=1;let p=oi.current;if((p===4||p%15===0)&&zr.current<3){zr.current+=1;let c=zr.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";h({kind:"note",tone:"info",text:an(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${c}`:`\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.${c}`})}}catch{}},4e3);return()=>clearInterval(u)},[e,C,h,Mt,nn,Je]),at(()=>{let u=qp??Ys(e);if(!C){il(0),Rr(`${ll} ${u}`);return}il(3);let p=0;Rr(`${al[0]} ${u}`);let c=setInterval(()=>{p=(p+1)%al.length,Rr(`${al[p]} ${u}`)},400);return()=>clearInterval(c)},[C,e,qp]),at(()=>()=>il(0),[]),at(()=>{let u=performance.now(),p=[],c=(b,k)=>{let x=performance.now();try{return k()}finally{let y=Math.round(performance.now()-x);y>=80&&p.push(`${b}: ${y}ms`)}};h({kind:"banner",info:c("banner",()=>VD(e,o,t,s))});let g=Op(t).state==="missing";if(g&&h({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.
482
+ ${WN}
483
+ Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!Se(e)){h({kind:"note",tone:"info",text:`Welcome! This repo isn't set up for d360-writer yet \u2014 three steps and you're writing docs:
484
+ ${uk}`}),oe(g?"/doctor":"/init");return}g&&oe("/doctor");try{let b=mt(e,s);b.project.projectId&&XN(b.name,b.project.projectId,b.project.projectName);let k=Un(b.name,b.project.projectId),x=He(e,s);k&&vo(k)&&k.refreshToken?qN({profile:b.name,connection:b.connection,projectId:b.project.projectId,projectName:b.project.projectName}).then(()=>{h({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),O(y=>y+1)}).catch(y=>{if(y instanceof VN&&y.transient){h({kind:"note",tone:"warn",text:"Couldn't reach Document360 to renew your session \u2014 your sign-in is intact, and I'll try again on your next command."});return}h({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 sign in again with /login."}),oe("/login"),O(v=>v+1)}):x.ok||(h({kind:"note",tone:"warn",text:x.reason}),oe("/login"))}catch{}try{let b=Se(e),k=mt(e,s),x=Un(k.name,k.project.projectId);b&&x&&!vo(x)&&up(e,b.authoritativeSourceFiles)&&!dp(e,s)&&(h({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),oe("/scope"))}catch{}try{let b=c("resolve-genre",()=>aD(e));b.persisted&&b.appType?h({kind:"note",tone:"ok",text:`\u2713 Detected a ${b.appType} app \u2014 enabled the ${b.appType}-doc-playbook (change with /genre, or edit .d360-writer/config.json).`}):b.source==="unknown"&&Se(e)&&(Ye.current=!0)}catch{}let T=Ut(e);try{if(c("reconcile-devhints",()=>Si(e)),T.status!=="current"&&!an(e)){let b=Pi(e);b.length&&(h({kind:"note",tone:"warn",text:b.join(`
485
+ `)}),on(so()),Kr.current=!1,Uo.current=!1)}}catch{}try{let b=c("reconcile-feedback",()=>RD(e));b.archived>0&&h({kind:"note",tone:"ok",text:`\u2713 Tidied ${b.archived} resolved item${b.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${b.open>0?`; ${b.open} still open`:""}.`})}catch{}try{let b=c("upgrade-actions",()=>CD(e));b.applied.length>0&&h({kind:"note",tone:"warn",text:vi(b.applied).join(`
486
+ `)}),b.reopenedForRedaction&&h({kind:"note",tone:"warn",text:xi(b.reopenedForRedaction)})}catch{}let W=c("ready-decision",()=>Mt(!0));W.kind==="autoAudit"?(h({kind:"note",tone:"info",text:W.note}),fs({cwd:e,profileName:s}).then(b=>{if(b.kind==="audit-blocked"){Ee(b.note,{kind:"cmd",cmd:b.lead.cmd,reason:b.lead.reason},"warn");return}b.kind!=="forward-to-agent"||!b.prompt||Te(b.prompt,{display:b.display,quietUser:!0}).then(k=>{if(k.producedNothing)return;let x=ra(e,s);if(x){Ee(x.note,{kind:"cmd",cmd:ir.cmd,reason:ir.reason},"warn"),O(y=>y+1);return}Us(e,s),O(y=>y+1)})})):W.kind==="recommend"&&nn(W.rec);let B=Math.round(performance.now()-u);B>=800&&ED({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${B}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${p.length?p.join(`
485
487
  `):"no single phase \u226580ms"}
486
- cwd: ${e}`}),Tl(),Jp({pull:!0})},[]),at(()=>{let u=setInterval(()=>{Tl()},qD);return()=>clearInterval(u)},[Tl]),at(()=>{let u=setInterval(()=>{try{let p=Date.now(),c=wp(p,Nl.current);if(th.current+=1,c&&th.current%Math.round(3e5/6e4)!==0)return;let m=jD(e),A=Vr.current,W=m===A.fingerprint&&A.counts?A.counts:pn(e),G=fb({now:p,lastInputAt:Nl.current,fingerprint:m,counts:W,occupied:C||X||fe.length>0||w!==""||Wr||Ee.current.length>0,prev:A});if(Vr.current=G.memory,oh(G.waiting),G.speak){h({kind:"note",tone:"info",text:gb(G.speak)});let y=Mt(!1);y.kind==="recommend"&&nn(y.rec,{silent:!0})}}catch{}},6e4);return()=>clearInterval(u)},[e,C,X,fe.length,w,Wr,h,Mt,nn]),at(()=>{if(C||X||ee.current||de!==null||fe.length>0||w!==""||Gr!==null||Ee.current.length>0||Lr.current||Wr)return;let u=Mt(!1);if(u.kind==="recommend"&&(u.rec.lead||u.rec.picker||u.rec.menu.length>0)){nn(u.rec,{silent:!0});let p=u.rec.lead,c=p?Us(p):u.rec.settled?"settled":null;c&&c!==ti.current&&(ti.current=c,u.rec.settled&&h({kind:"note",tone:"ok",text:u.rec.settled}),p&&h({kind:"note",tone:"info",text:$r(p)}))}Jp({pull:!1})},[C,X,de,fe,w,Gr,Wr,B,Mt,fn]),at(()=>{let u=null,p=null,c=()=>{u&&clearTimeout(u),u=setTimeout(()=>{u=null;let m=`${ze.columns??80}x${ze.rows??24}`;m!==Xp.current&&(Xp.current=m,bk(A=>A+1),p&&clearTimeout(p),p=setTimeout(()=>{p=null;let A=Math.max(8,(ze.rows??24)-2);console.log("\x1B[?2026h\x1B[H\x1B[2J"+cg(Po.current,Ge(),A)+"\x1B[?2026l")},80))},400)};return ze.on("resize",c),()=>{u&&clearTimeout(u),p&&clearTimeout(p),ze.off("resize",c)}},[ze,Ge]);let st=Math.max(20,(ze.columns??80)-1),rh=vp(()=>_D(e,s),[e,s,B]),Dl=(()=>{if($o)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(vo!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${vo?` v${vo}`:""}\u2026`,isSetup:!0};if(Yp)return{text:sb(Yp),isSetup:!0};if(ni)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(Gr)return kk?{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 \u2014 then paste it into your coding agent\u2026",isSetup:!0};if(nh)return{text:yb(nh),isSetup:!0};if(Ee.current.length>0){let m=Ee.current.length,A=Ee.current[0].mode;return A==="local-only"?{text:"l publish yours over the portal \xB7 s skip \xB7 anything else cancels\u2026",isSetup:!0}:A==="conflict"?{text:m>1?`l keep local \xB7 p take portal \xB7 s skip \xB7 la/pa/sa for all ${m}\u2026`:"l keep local \xB7 p take portal \xB7 s skip \xB7 anything else cancels\u2026",isSetup:!0}:{text:m>1?`y to write \xB7 n to skip \xB7 ya/na for all ${m}\u2026`:"y to write \xB7 n to skip \xB7 anything else cancels\u2026",isSetup:!0}}let u=Re(e);if(!u)return{text:"Run /init to set up this repo (or /help)\u2026",isSetup:!0};let p=xp(e,(u.docsDir??jp).replace(/\/+$/,"")),c=(()=>{try{return Cr(p)&&TN(p).length>0}catch{return!1}})();try{let m=mt(e,s),A=Un(m.name,m.project.projectId);if(!(!!A&&!(ko(A)&&!A.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&&!c)return{text:"Pick a workspace with /workspace\u2026",isSetup:!0}}catch{}return c?{text:MD,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),rn=Jm(w),sh=rn.length>0&&!C,$k=12,qt=hp(ze.rows),vk=ze.rows??24,ih=hp(ze.rows,{max:$k}),ri=Math.min(wl,Math.max(0,rn.length-1)),eo=rl(rn.length,ri,ih).start,jl=rn.slice(eo,eo+ih),Il=a!==null?Ib(a,8,st):null,si=bt?bt.paths.filter(u=>!bt.query||u.toLowerCase().includes(bt.query.toLowerCase())).slice(0,8):[],ii=kt?kt.sessions.filter(u=>{let p=kt.query.toLowerCase();return!p||u.name.toLowerCase().includes(p)||u.firstPrompt.toLowerCase().includes(p)}).slice(0,8):[],Ze=te((u,p)=>{Nt.current?.close(),Nt.current=Mb({cwd:e,resume:u,profileName:p??s,allowProdWrites:gn.current}),u||(Jt.current={uuid:null,firstPrompt:null,titleFired:!1},Bn(null)),Qn(0),Jn(0)},[e,s]),ah=te((u,p,c)=>{if(ak.test(u))try{let m=mt(e,s),A=typeof p.project_id=="string"&&p.project_id||m.project.projectId,W=el(p,c),G=[],y=Hy(p,c),$=y?`${y} \u2014 `:"",R=tl(c);u.endsWith("publish_article")&&R&&G.push(`${$}Live: ${R}`);let b=nl(c);b?G.push(`${$}Preview: ${b}`):W&&A&&G.push(`${$}Preview: ${Za(m.connection.portalUrl,A,W,m.project.languageCode??"en")}`),G.length>0&&h({kind:"link",lines:G})}catch{}},[e,s,h]),Se=te(async(u,p)=>{tt(!0),ee.current=!1,ge.current=!1,ke.current=null,_t(),se([]),jo(null),Cl(null);let c=gt.current;if(p?.display?.startsWith("/"))try{let E=Xi(e,p.display);E&&(u=`${u}
487
-
488
- ${E}`)}catch{}p?.quietUser||h({kind:"user",text:p?.echoDisplay&&p.display?p.display:u});let m=Jt.current;m.firstPrompt||(m.firstPrompt=p?.display??u),Et.current=Date.now(),Ue(0),T(!0),Ir.current.clear();let A="",W=!1,G=!1,y=!1,$=!1,R="",b={num:0,closed:!1,cueSeen:!1},x=null,P=()=>{x||(x=setTimeout(()=>{x=null,l(R.length>0?R:null)},60))},j=()=>{x&&clearTimeout(x),x=null,l(null)},N=(E=!1)=>{let{head:K,keep:_}=Lb(R,E);K.trim()&&h({kind:"assistant",text:pp(K.trimEnd(),b)}),R=_,j()};try{for await(let E of Nt.current.send(u))if(E.type==="session"){if(!m.uuid){m.uuid=E.sessionId;let K=new Date().toISOString(),_=bl.current,F=_??GN(m.firstPrompt??"session");qN({uuid:E.sessionId,name:F,renamed:!!_,titled:!1,cwd:e,firstPrompt:m.firstPrompt??"",createdAt:K,updatedAt:K}),Bn(F),bl.current=null}}else if(E.type==="text"){R+=E.delta,A+=E.delta;let K=Ob(R);if(K>0){let _=R.slice(0,K).trimEnd();_&&h({kind:"assistant",text:pp(_,b)}),R=R.slice(K)}P(),Ue(_=>_+E.delta.length)}else if(E.type==="tool"){W=!0,ak.test(E.name)&&(G=!0);let _=(pe=>typeof pe=="string"&&pe?pe.replace(/\\/g,"/").toLowerCase():null)(E.input.file_path??E.input.notebook_path),F=["Edit","Write","MultiEdit","NotebookEdit"].includes(E.name),U=E.name==="Read"&&_!==null&&_===Fp.current;Fp.current=F?_:null;let ie=Qs.current,ne=ie?null:Db(E.name,E.input),De=ie?null:Xa(E.name,E.input,e,s);if(ne)xl.current.push(ne);else if(De)N(),h({kind:"doc",verb:De.verb,title:De.title,category:De.category,note:De.note,...De.loud?{loud:De.loud}:{}}),Ir.current.set(E.id,{name:E.name,input:E.input,doc:!0,keepResult:De.keepResult});else if(U)N(),h({kind:"tool",title:"Read",sep:"",arg:"re-checking the file it just edited"});else{let pe=Qa(E.name,E.input,e);pe&&(N(),h({kind:"tool",title:pe.title,sep:pe.sep,arg:pe.arg}),Ir.current.set(E.id,{name:E.name,input:E.input}))}}else if(E.type==="article_diff"){let K=Rt(E.oldContent,E.newContent,Ge());K&&(N(),h({kind:"diff",added:K.added,removed:K.removed,lines:K.lines,hidden:K.hidden}))}else if(E.type==="tool_result"){E.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(E.output)&&(Js.current=!0);let K=Ir.current.get(E.id);if(K){Ir.current.delete(E.id),N();let F=K.doc&&!K.keepResult&&!E.isError?{lines:[],hidden:0}:Ja(E.output,4,E.isError||Qs.current?void 0:K.name,K.input),U=E.isError&&ib(K.name,E.output);F.lines.length>0&&h({kind:"tool-result",lines:F.lines,hidden:F.hidden,isError:E.isError&&!U}),E.isError||ah(K.name,K.input,E.output)}}else if(E.type==="result"){N(!0),Qn(U=>U+E.outputTokens),Jn(U=>Math.max(U,E.sessionCostUsd));let K=E.inputTokens+E.cacheReadTokens+E.cacheCreationTokens;if(h({kind:"done",seconds:Math.round((Date.now()-Et.current)/1e3),tokens:E.outputTokens,costUsd:E.costUsd,sessionCostUsd:Math.max(Br,E.sessionCostUsd),ok:E.ok,...K>0?{inTokens:K,cachedPct:Math.round(E.cacheReadTokens/K*100)}:{}}),!y&&!W&&!A.trim()&&!_r.current&&($=!0,h({kind:"note",tone:"warn",text:"The agent produced no output \u2014 nothing ran this turn. Run /doctor: it runs a real turn with your skills and tools and reports what failed. Claude Code\u2019s own error was written either way \u2014 /logs shows it, and offers to copy it for the team."})),E.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(A))try{let U=Zb(e);if(Cr(U)){let ie=hl(U,"utf8").trim();ie&&(El(ie),h({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{}let _=E.ok?eb(A):null;ge.current=_!==null,ke.current=_;let F=E.ok?tb(A,FD):null;if(F)mn(!1),At.current=!1,se(F);else if(E.ok&&(b.cueSeen||(_?.options??0)>=2))mn(!0),At.current=!0,se([]);else if(_)se([]);else{let U=E.ok?kb(A,uo.map(ie=>ie.name)):[];if(U.length>0)oe(U[0]);else if(E.ok&&A.trim()&&!ge.current){let ie=Mt(!1);ie.kind==="recommend"&&(ie.rec.lead||ie.rec.picker)||zN(u,A,e).then(ne=>{ne&&gt.current===c&&Je(ne)}).catch(()=>{})}}if(m.uuid&&(Rp(m.uuid),!m.titleFired)){m.titleFired=!0;let U=m.uuid,ie=m.firstPrompt;ie&&Ub(ie,e).then(ne=>{ne&&(HN(U,ne),Bn(ne))}).catch(()=>{})}}else E.type==="error"&&(N(!0),y=!0,E.kind==="auth"&&(Js.current=!0),h(E.kind==="limit"?{kind:"note",text:`\u23F3 ${E.message}`,tone:"warn"}:{kind:"note",text:`agent error: ${E.message}`,tone:"error"}))}finally{if(T(!1),j(),ei(),G)try{let E=Tp(await Pp({cwd:e,profileName:s,onRateLimit:K=>We(`Document360 rate limit \u2014 waiting ${Math.ceil(K.waitMs/1e3)}s\u2026`)}));E&&h({kind:"note",tone:E.startsWith("\u26A0")?"warn":"info",text:E})}catch{}finally{We(null)}M(E=>E+1),Jt.current.uuid&&ub(e,Jt.current.uuid,Po.current),Js.current?(Js.current=!1,Fr.current=p?.display??u,Je("/login","\u21E5 tab to run /login \u2014 then I\u2019ll re-send your last prompt\u2026")):Fr.current=null,_r.current&&(_r.current=!1,Kn.current.length>0&&(h({kind:"note",tone:"info",text:`(${Kn.current.length} queued message(s) discarded)`}),Kn.current=[],kl([])),h({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}return{producedNothing:$,handedBack:ke.current!==null}},[e,h,ah,Ge,Je,oe,_t,Mt,ei]),ai=te(async()=>{try{We("Checking Document360 for new reviewer comments\u2026"),await Na(e,s,{onProgress:(u,p)=>We(`Checking Document360 for new reviewer comments\u2026 ${u}/${p}`)})}catch{}finally{We(null)}},[e,s]),ct=te(async(u,p=0,c)=>{let m=Ap(e,u,{allowUnreviewed:c?.skipReview===!0,allowStyleErrors:c?.skipStyle===!0});if(!m.clear){h({kind:"note",tone:"warn",text:Ep(m,u.length,{act:"push"}).join(`
489
- `)}),oe(bu(m));return}Et.current=Date.now(),Ue(0),T(!0);let A=new AbortController;Le.current=A;let W={aborted:!1,partitions:0,failed:0,notRun:0,producedNothing:!0},G=async(y,$)=>{let R=Cp(y),b=new Map;for(let U of R)for(let ie of U.paths)b.set(ie,U.label);let x=new Map(R.map(U=>[U.label,U.paths.length])),P=new Set,j=Date.now();he({verb:"Pushing",unit:"article",total:y.length,done:0,active:[],rows:bo(R),tools:0,chars:0,lastAt:Date.now(),startedAt:j,agentless:!0}),h({kind:"note",tone:"info",text:$?`Resolving cross-links in ${y.length} article${y.length===1?"":"s"} whose targets were saved this run (second pass)\u2026 (esc to stop)`:`Pushing ${y.length} article${y.length===1?"":"s"} to Document360 (${nD} at a time)\u2026 (esc to stop)`});let N=await eD({cwd:e,profileName:s,paths:y,allowProdWrites:gn.current,...c?.allowUnpullable===!0?{allowUnpullable:!0}:{},signal:A.signal,onEvent:U=>{let ie=U.type==="article_done"?U.result.path:U.type==="article_failed"?U.failure.path:U.path,ne=b.get(ie);if(!ne)return;if(U.type==="article_start"){he(pe=>pe&&!pe.active.includes(ne)?{...pe,active:[...pe.active,ne],rows:Ve(pe.rows,ne,"active"),lastAt:Date.now()}:pe&&{...pe,lastAt:Date.now()});return}U.type==="article_failed"&&P.add(ne);let De=(x.get(ne)??1)-1;x.set(ne,De),he(pe=>{if(!pe)return pe;let Q={...pe,done:pe.done+1,rows:cl(pe.rows,ne),lastAt:Date.now()};return De>0?Q:{...Q,active:Q.active.filter(xe=>xe!==ne),rows:Ve(Q.rows,ne,P.has(ne)?"failed":"done")}})}}),E=N.aborted,K=Mc(e,y,s);$||(W={aborted:E,partitions:R.length,failed:N.failed.length,notRun:N.notRun.length,producedNothing:N.pushed.length===0,verifiedComplete:K>=y.length,leftBehind:p});let _=N.pushed.length>0;h({kind:"note",tone:E||N.failed.length>0||!_?"warn":"ok",text:(E?"Stopped. ":"")+Fc(N,{recorded:K,elapsedMs:Date.now()-j,...$?{}:{conflictsSkipped:p},...c?.scope?{scope:c.scope}:{}}).join(`
490
- `)});let F=_c(e,s);if(F&&h({kind:"note",tone:"info",text:F}),!E&&_){let U=rr(e,s);U&&h({kind:"note",tone:"info",text:U});try{let ne=await Pp({cwd:e,profileName:s,onRateLimit:pe=>We(`Document360 rate limit \u2014 waiting ${Math.ceil(pe.waitMs/1e3)}s\u2026`)}),De=Tp(ne);De?h({kind:"note",tone:De.startsWith("\u26A0")?"warn":"info",text:De}):ne.skipped&&h({kind:"note",tone:"warn",text:`Order sync skipped: ${ne.skipped}`})}catch(ne){h({kind:"note",tone:"warn",text:`Order sync failed: ${ne.message}`})}finally{We(null)}try{let ne=nk(await tk({cwd:e,profileName:s}));ne&&h({kind:"note",tone:"info",text:ne})}catch(ne){h({kind:"note",tone:"warn",text:`Related-articles sync failed: ${ne.message}`})}let ie=await ds(e,s);ie&&h({kind:"note",tone:"info",text:ie})}return E};try{if(!await G(u,!1)){let $=await Uc(e,s,u);$.length>0&&await G($,!0),yn(c?.scope?`/push ${c.scope}`:"/push --all",W),p>0&&Ne(null,{kind:"cmd",cmd:"/resolve",reason:`${p} conflict${p===1?"":"s"} still need settling \u2014 they were left untouched`},"warn")}}catch(y){h({kind:"note",tone:"error",text:`Publish run failed: ${y.message}`})}finally{Le.current=null,he(null),await ai(),T(!1),M(y=>y+1)}},[e,s,h,t,Ne,ai]),Uo=te(u=>h({kind:"block",text:u.join(`
491
- `)}),[h]),Wo=te((u,p,c,m,A)=>{let W=Ct(u,p,c,Date.now(),A);h({kind:"done",seconds:W.seconds,tokens:W.outputTokens,costUsd:W.costUsd,ok:m,...W.activeSeconds!==void 0?{activeSeconds:W.activeSeconds}:{},sessionCostUsd:Br+c,...W.inputTokens>0?{inTokens:W.inputTokens,...W.cachedPct!==void 0?{cachedPct:W.cachedPct}:{}}:{}})},[h,Br]),li=te(async u=>{let p=zs(e,"standard");Et.current=Date.now(),Ue(0),T(!0);let c=new AbortController;Le.current=c;let m=Date.now(),A=new ar;A.start(),he({verb:u.verb,unit:"article",total:u.partitions.length,done:0,active:[],rows:bo(u.partitions),tools:0,chars:0,lastAt:Date.now(),startedAt:m}),h({kind:"note",tone:"info",text:`${u.headline} on ${p.model}\u2026 (esc to stop)`});let W=!0,G=[],y=!1,$={aborted:!1,partitions:0,failed:0,notRun:0,producedNothing:!0},R=new Set;try{for await(let b of Ks({cwd:e,partitions:u.partitions,promptFor:u.promptFor,concurrency:u.concurrency,profileName:s,allowProdWrites:gn.current,model:p.model,signal:c.signal,scope:u.scope}))if(b.type==="partition_status")b.status==="running"?he(x=>x&&{...x,active:[...x.active,b.label],rows:Ve(x.rows,b.label,"active"),lastAt:Date.now()}):he(x=>x&&{...x,active:x.active.filter(P=>P!==b.label),done:x.done+1,rows:Ve(x.rows,b.label,b.status==="done"?"done":"failed"),lastAt:Date.now()});else if(b.type==="partition_stalled"){let x=vr(b);he(P=>P&&x?{...P,stalledNote:x}:P)}else if(b.type==="partition_event"){let x=null;if(b.event.type==="tool"){let P=bp(b.event.name,b.event.input,u.partitions[b.index]?.paths??[]);P&&!R.has(P)&&(R.add(P),x=b.label)}he(P=>{if(!P)return P;let j={...P,lastAt:Date.now()};return b.event.type==="tool"?j.tools=P.tools+1:b.event.type==="text"&&(j.chars=P.chars+b.event.delta.length),x&&(j.rows=cl(j.rows,x)),j})}else if(b.type==="run_done"){Jn(N=>N+b.totalCostUsd),Qn(N=>N+b.results.reduce((E,K)=>E+K.outputTokens,0));let x=Sp(u.partitions,b.results);W=!!b.allEmpty||!!b.blocked,y=!!b.aborted,$={aborted:!!b.aborted,partitions:u.partitions.length,failed:x.failed.length,notRun:x.notRun.length,...b.blocked?{blocked:b.blocked}:{},...b.allEmpty?{allEmpty:!0}:{},...b.bailedEmpty?{bailedEmpty:!0}:{}};let P=[`${b.aborted?"Stopped. ":""}${b.results.length-x.failed.length}/${u.partitions.length} batches ${u.doneNoun}.`,...x.failed.length?[`\u26A0 ${x.failed.length} not ${u.doneNoun} \u2014 their articles are unchanged: ${x.failed.map(N=>N.label).join(", ")}`]:[],...x.notRun.length?[`\u26A0 ${x.notRun.length} batch${x.notRun.length===1?"":"es"} never started \u2014 their articles are untouched.`]:[],...b.blocked?[`\u26A0 ${b.blocked}`]:[],...b.allEmpty?[u.emptyNote??"\u26A0 No turn produced any work this run \u2014 nothing was changed."]:[],...u.caveatLines??[]];h({kind:"note",tone:b.aborted||x.failed.length||x.notRun.length||b.blocked||b.allEmpty?"warn":"ok",text:P.join(`
492
- `)});let j=A.stop();if(Wo(m,b.results,b.totalCostUsd,!y&&!W&&!x.failed.length,j.activeSeconds),u.calibrateAs){let N=b.results.filter(E=>E.ok).length;ZN(e,u.calibrateAs,{articles:x.covered.length,waves:Math.ceil(N/Math.max(1,u.concurrency)),seconds:j.activeSeconds,costUsd:b.totalCostUsd})}W||(G=x.covered)}}catch(b){h({kind:"note",tone:"error",text:`${u.verb} failed: ${b.message}`})}finally{A.stop(),Le.current=null,he(null),T(!1),M(b=>b+1)}return{producedNothing:W,covered:G,aborted:y,outcome:$}},[e,s,h,Wo]),xk=te(async(u,p)=>{let c=await li({partitions:u.partitions,promptFor:u.promptFor,concurrency:_n,verb:"Reviewing",doneNoun:"reviewed",headline:`Reviewing ${u.articles} article${u.articles===1?"":"s"} in ${u.partitions.length} batches (\u2264${_n} editors at once)${p?", applying fixes as they go":", report only"}`+(()=>{let m=Wa(e,"/review",u.articles,u.partitions.length);return m?` \xB7 ${m}`:""})(),caveatLines:Yd(u),emptyNote:"\u26A0 No editor produced any work this run \u2014 nothing was reviewed or changed.",calibrateAs:"/review",scope:"review"});if(p&&c.covered.length>0)try{Pr(e,c.covered,it("review"))}catch{}return{producedNothing:c.producedNothing,aborted:c.aborted,outcome:c.outcome}},[e,li]),Ll=te(async(u,p)=>{if(u.length===0)return;let c=u.reduce((R,b)=>R+b.threads.length,0),m=new Map,A=u.map(R=>(m.set(R.label,R),{label:R.label,paths:R.path?[R.path]:[]})),W=zs(e,"standard");Et.current=Date.now(),Ue(0),T(!0);let G=new AbortController;Le.current=G;let y=Date.now(),$=ek(e);he({verb:"Answering",unit:"article",total:A.length,done:0,active:[],rows:bo(A),tools:0,chars:0,lastAt:Date.now(),startedAt:y}),h({kind:"note",tone:"info",text:`Answering ${c} comment${c===1?"":"s"} across ${A.length} article${A.length===1?"":"s"} (\u2264${js} agents at once) on ${W.model}. Each article is fixed, pushed to Document360 as a draft, then answered in the thread${p.resolve?" and resolved":" \u2014 the threads stay open for your reviewers to close"}\u2026 (esc to stop)`});try{for await(let R of Ks({cwd:e,partitions:A,promptFor:b=>{let x=m.get(b.label);return Pd({articleId:x.articleId,label:x.label,path:x.path,count:x.threads.length,resolve:p.resolve})},concurrency:js,profileName:s,allowProdWrites:gn.current,allowCommentResolve:p.resolve,model:W.model,signal:G.signal}))if(R.type==="partition_status")R.status==="running"?he(b=>b&&{...b,active:[...b.active,R.label],rows:Ve(b.rows,R.label,"active"),lastAt:Date.now()}):he(b=>b&&{...b,active:b.active.filter(x=>x!==R.label),done:b.done+1,rows:Ve(b.rows,R.label,R.status==="done"?"done":"failed"),lastAt:Date.now()});else if(R.type==="partition_stalled"){let b=vr(R);he(x=>x&&b?{...x,stalledNote:b}:x)}else if(R.type==="partition_event")he(b=>{if(!b)return b;let x={...b,lastAt:Date.now()};return R.event.type==="tool"?x.tools=b.tools+1:R.event.type==="text"&&(x.chars=b.chars+R.event.delta.length),x});else if(R.type==="run_done"){Jn(_=>_+R.totalCostUsd),Qn(_=>_+R.results.reduce((F,U)=>F+U.outputTokens,0));let b=Sp(A,R.results),x=R.results.length-b.failed.length,P=R.aborted?"Stopped. ":"",j=[...b.failed.map(_=>_.label),...b.notRun.map(_=>_.label)],N=[`${P}${x}/${A.length} article${A.length===1?"":"s"} answered.`,...j.length?[`\u26A0 ${j.length} left untouched (their threads are still open, which is correct \u2014 nothing was promised to those reviewers): ${j.join(", ")}`]:[],...R.blocked?[`\u26A0 ${R.blocked}`]:[],...R.allEmpty?["\u26A0 No agent produced any work this run \u2014 nothing was changed or answered."]:[]];h({kind:"note",tone:R.aborted||j.length||R.blocked||R.allEmpty?"warn":"ok",text:N.join(`
493
- `)}),Wo(y,R.results,R.totalCostUsd,!R.aborted&&!j.length&&!R.blocked&&!R.allEmpty);let E=new Set(j),K=[...p.rest??[],...u.filter(_=>E.has(_.label))];if(K.length>0&&!R.aborted&&p.report){let _=K.reduce((U,ie)=>U+ie.threads.length,0);h({kind:"note",tone:"info",text:`${_} comment${_===1?"":"s"} on ${K.length} other article${K.length===1?"":"s"} still open \u2014 pick the next one, or esc to stop here.`});let F={...p.report,threads:K.flatMap(U=>U.threads)};Uo(Is(F,{width:Ge()})),en({cursor:0,rows:ja(K),groups:K,resolve:p.resolve,report:F})}else if(K.length>0&&!R.aborted){let _=K.map(U=>U.path).filter(U=>!!U),F=_.length===K.length?Yt(_):void 0;oe(F?_.length===1?`/comments ${F}`:`/comments --scope ${F}`:"/comments")}}}catch(R){h({kind:"note",tone:"error",text:`Answering comments failed: ${R.message}`})}finally{let b=fo(e,$,"","/comments").changed.length;b>0&&h({kind:"note",tone:"info",text:`${b} article${b===1?"":"s"} changed, and that new text has not been read by an editor \u2014 ${b===1?"it":"they"} can go live once /review has been over ${b===1?"it":"them"}.`}),Le.current=null,he(null),T(!1),M(x=>x+1)}},[e,s,h,Ne,oe,Uo,Ge]),Ol=te(async(u,p)=>{if(!(p?.skipReview===!0||p?.skipStyle===!0)){let m=Ap(e,[u],{});if(!m.clear){h({kind:"note",tone:"warn",text:Ep(m,1,{act:"push"}).join(`
494
- `)}),oe(bu(m,u));return}}await ct([u],0,{skipReview:p?.skipReview,skipStyle:p?.skipStyle,scope:u});try{let m=await ta(e,s,u.replace(/\\/g,"/"));m.length>0&&(jo(`Related articles not yet saved to Document360 (${m.length}):`),se([`/push --related ${u}`,...m.map(A=>`/push ${A}`)]))}catch{}},[e,s,Se,ct]),Rk=te(async(u,p)=>{T(!0);try{let c=await Vc(e,s,u,{skipReview:p.skipReview,skipStyle:p.skipStyle,onProgress:(A,W,G)=>We(`Publishing ${A+1}/${W} \u2014 ${G}\u2026`)}),m=c.blocked.length+c.failed.length;h({kind:"note",tone:m>0?"warn":"ok",text:Yc(c).join(`
495
- `)}),c.blocked.length>0?oe("/review --blocked --fix"):Ne(null,null)}catch(c){h({kind:"note",tone:"error",text:`Publishing failed: ${c.message}`})}finally{We(null),await ai(),T(!1),M(c=>c+1)}},[e,s,h,oe,Ne,ai]),lh=te(async u=>{try{let p=await ml({cwd:e,profileName:s}),{clean:c,conflicts:m}=lo(p.entries);if(c.length===0){h({kind:"note",tone:"info",text:"Nothing new to save \u2014 everything is already up to date on Document360."});return}await ct(c.map(A=>A.path),m.length,{skipReview:u?.skipReview,skipStyle:u?.skipStyle})}catch(p){h({kind:"note",tone:"warn",text:`Couldn\u2019t check what to save (${p.message}) \u2014 your articles are written; run /push when ready.`})}},[e,s,ct]),yn=te((u,p)=>{if(!(p&&!Kt(p)))for(let c of vt(e,u))h({kind:"note",tone:"ok",text:c})},[e,h]),ch=te(async(u,p)=>{let m=lD(u,3),A=zs(e,"standard"),W=new Map,G=new Map;for(let b of u){let x=io(e,b),P=pc(e,b,x);if(P&&W.set(b,P),x!==null){let j=Cc(x);j.length>0&&G.set(b,j)}}Et.current=Date.now(),Ue(0),T(!0);let y=new AbortController;Le.current=y;let $=Date.now();he({verb:"Authoring",unit:"spec",total:m.length,done:0,active:[],rows:bo(m),tools:0,chars:0,lastAt:Date.now(),startedAt:$}),h({kind:"note",tone:"info",text:`Authoring ${u.length} screenshot spec${u.length===1?"":"s"} in ${m.length} batch${m.length===1?"":"es"} (\u22646 agents at once) on ${A.model}${A.forced?" (forced)":""}\u2026 (esc to stop)`});let R=!1;try{for await(let b of Ks({cwd:e,partitions:m,promptFor:x=>rm(x,W,G),concurrency:6,profileName:s,allowProdWrites:gn.current,model:A.model,signal:y.signal}))if(b.type==="partition_status")b.status==="running"?he(x=>x&&{...x,active:[...x.active,b.label],rows:Ve(x.rows,b.label,"active"),lastAt:Date.now()}):he(x=>x&&{...x,active:x.active.filter(P=>P!==b.label),done:x.done+1,rows:Ve(x.rows,b.label,b.status==="done"?"done":"failed"),lastAt:Date.now()});else if(b.type==="partition_stalled"){let x=vr(b);he(P=>P&&x?{...P,stalledNote:x}:P)}else if(b.type==="partition_event")he(x=>{if(!x)return x;let P={...x,lastAt:Date.now()};return b.event.type==="tool"?P.tools=x.tools+1:b.event.type==="text"&&(P.chars=x.chars+b.event.delta.length),P});else if(b.type==="run_done"){Jn(E=>E+b.totalCostUsd),Qn(E=>E+b.results.reduce((K,_)=>K+_.outputTokens,0));let x=b.results.filter(E=>E.ok).length,P=b.aborted?"Stopped. ":"";R=!b.aborted&&p.setup;let j=b.aborted?"":R?" Refreshing the staging checklist\u2026":` Next: /screenshot capture${p.scope?` ${p.scope}`:" --all"} (or /screenshot checklist first for the staging checklist).`,N=Tn(b,"Spec authoring");h({kind:"note",tone:N||b.aborted?"warn":b.ok?"ok":"warn",text:N?N.join(`
496
- `):`${P}Authored specs \u2014 ${x}/${b.results.length} batches ok.${j}`}),Wo($,b.results,b.totalCostUsd,!N&&!b.aborted&&b.ok),N&&(oe("/doctor"),R=!1),!b.aborted&&b.ok&&!N&&yn(p.runLine)}}catch(b){h({kind:"note",tone:"error",text:`Spec authoring failed: ${b.message}`})}finally{Le.current=null,he(null),T(!1),M(b=>b+1)}if(R){let b=await gr();b.kind==="forward-to-agent"&&b.prompt&&await Se(b.prompt,{display:b.display,quietUser:!0}),Sl()}},[e,s,h,Se,yn,Sl]),uh=te(async u=>{let p=pc(e,u,io(e,u))??void 0,c=await Yi([u],void 0,{prior:p});c.kind==="forward-to-agent"&&c.prompt&&await Se(c.prompt,{display:c.display,quietUser:!0}),Hf(e,u)&&Ne(`Spec ready \u2014 /screenshot capture ${u} takes the screenshot; bare /screenshot picks the next shot.`,{kind:"cmd",cmd:`/screenshot capture ${u}`,reason:""})},[e,Se,Ne]),ci=te(async(u,p)=>{if(u.length===0)return{drawn:[],undrawn:[],cliMissing:!1};T(!0);let c=new AbortController;Le.current=c,he({verb:"Drawing callouts",unit:"screenshot",total:u.length,done:0,active:[],rows:u.map(x=>({label:x,items:1,status:"pending"})),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()});let m=[],A=!1;try{let x=await cd({cwd:e,ids:u,...p.force?{force:!0}:{},signal:c.signal,onStart:P=>he(j=>j&&{...j,active:[P],rows:Ve(j.rows,P,"active"),lastAt:Date.now()}),onDone:(P,j)=>he(N=>N&&{...N,active:[],done:N.done+1,rows:Ve(N.rows,P,j==="failed"?"failed":"done"),lastAt:Date.now()})});m=x.results,A=x.cliMissing??!1}catch(x){h({kind:"note",tone:"error",text:`Drawing the callouts failed: ${x.message}`})}finally{Le.current=null,he(null),T(!1),M(x=>x+1)}if(A)return h({kind:"note",tone:"error",text:"d360-capture is not installed on this machine. Run: npm i -g document360-capture \u2014 then /screenshot annotate."}),{drawn:[],undrawn:u,cliMissing:!0};let W=m.filter(x=>x.outcome==="annotated").map(x=>x.id),G=m.filter(x=>x.outcome==="skipped").map(x=>x.id),y=u.filter(x=>!W.includes(x)&&!G.includes(x));if(h({kind:"note",tone:y.length?"warn":"ok",text:[`\u25C8 ${W.length} drawn`,G.length?`${G.length} already current`:"",y.length?`\u2717 ${y.length} not drawn`:""].filter(Boolean).join(" ")}),y.length>0){let x=Math.max(...y.map(P=>P.length));h({kind:"note",tone:"warn",text:y.map(P=>`\u2717 ${P.padEnd(x)} ${Ts(m.find(j=>j.id===P)?.detail)||"no picture was produced"}`).join(`
488
+ cwd: ${e}`}),El(),oh({pull:!0})},[]),at(()=>{let u=setInterval(()=>{El()},n1);return()=>clearInterval(u)},[El]),at(()=>{let u=setInterval(()=>{try{let p=Date.now(),c=vp(p,jl.current);if(ih.current+=1,c&&ih.current%Math.round(3e5/6e4)!==0)return;let g=GD(e),T=Yr.current,W=g===T.fingerprint&&T.counts?T.counts:pn(e),B=kb({now:p,lastInputAt:jl.current,fingerprint:g,counts:W,occupied:C||Q||fe.length>0||m!==""||Br||De.current.length>0,prev:T});if(Yr.current=B.memory,lh(B.waiting),B.speak){h({kind:"note",tone:"info",text:vb(B.speak)});let b=Mt(!1);b.kind==="recommend"&&nn(b.rec,{silent:!0})}}catch{}},6e4);return()=>clearInterval(u)},[e,C,Q,fe.length,m,Br,h,Mt,nn]),at(()=>{if(C||Q||te.current||de!==null||fe.length>0||m!==""||qr!==null||De.current.length>0||Or.current||Br)return;let u=Mt(!1);if(u.kind==="recommend"&&(u.rec.lead||u.rec.picker||u.rec.menu.length>0)){nn(u.rec,{silent:!0});let p=u.rec.lead,c=p?Ws(p):u.rec.settled?"settled":null;c&&c!==ti.current&&(ti.current=c,u.rec.settled&&h({kind:"note",tone:"ok",text:u.rec.settled}),p&&h({kind:"note",tone:"info",text:vr(p)}))}oh({pull:!1})},[C,Q,de,fe,m,qr,Br,U,Mt,fn]),at(()=>{let u=null,p=null,c=()=>{u&&clearTimeout(u),u=setTimeout(()=>{u=null;let g=`${ze.columns??80}x${ze.rows??24}`;g!==th.current&&(th.current=g,Ck(T=>T+1),p&&clearTimeout(p),p=setTimeout(()=>{p=null;let T=Math.max(8,(ze.rows??24)-2);console.log("\x1B[?2026h\x1B[H\x1B[2J"+hg(Ao.current,qe(),T)+"\x1B[?2026l")},80))},400)};return ze.on("resize",c),()=>{u&&clearTimeout(u),p&&clearTimeout(p),ze.off("resize",c)}},[ze,qe]);let st=Math.max(20,(ze.columns??80)-1),ch=Pp(()=>KD(e,s),[e,s,U]),Il=(()=>{if(xo)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(Ro!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${Ro?` v${Ro}`:""}\u2026`,isSetup:!0};if(Jp)return{text:db(Jp),isSetup:!0};if(ni)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(qr)return Sk?{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 \u2014 then paste it into your coding agent\u2026",isSetup:!0};if(ah)return{text:Rb(ah),isSetup:!0};if(De.current.length>0){let g=De.current.length,T=De.current[0].mode;return T==="local-only"?{text:"l publish yours over the portal \xB7 s skip \xB7 anything else cancels\u2026",isSetup:!0}:T==="conflict"?{text:g>1?`l keep local \xB7 p take portal \xB7 s skip \xB7 la/pa/sa for all ${g}\u2026`:"l keep local \xB7 p take portal \xB7 s skip \xB7 anything else cancels\u2026",isSetup:!0}:{text:g>1?`y to write \xB7 n to skip \xB7 ya/na for all ${g}\u2026`:"y to write \xB7 n to skip \xB7 anything else cancels\u2026",isSetup:!0}}let u=Se(e);if(!u)return{text:"Run /init to set up this repo (or /help)\u2026",isSetup:!0};let p=Tp(e,(u.docsDir??Mp).replace(/\/+$/,"")),c=(()=>{try{return Sr(p)&&_N(p).length>0}catch{return!1}})();try{let g=mt(e,s),T=Un(g.name,g.project.projectId);if(!(!!T&&!(vo(T)&&!T.refreshToken)))return{text:`Sign in with /login (profile "${g.name}")\u2026`,isSetup:!0};if(!g.project.projectId)return{text:"Sign in to Document360 to pick your project\u2026",isSetup:!0};if(!g.project.workspaceId&&!c)return{text:"Pick a workspace with /workspace\u2026",isSetup:!0}}catch{}return c?{text:zD,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),rn=ng(m),uh=rn.length>0&&!C,Pk=12,qt=yp(ze.rows),Tk=ze.rows??24,dh=yp(ze.rows,{max:Pk}),ri=Math.min(yl,Math.max(0,rn.length-1)),to=sl(rn.length,ri,dh).start,Ll=rn.slice(to,to+dh),Ol=a!==null?Ub(a,8,st):null,si=bt?bt.paths.filter(u=>!bt.query||u.toLowerCase().includes(bt.query.toLowerCase())).slice(0,8):[],ii=kt?kt.sessions.filter(u=>{let p=kt.query.toLowerCase();return!p||u.name.toLowerCase().includes(p)||u.firstPrompt.toLowerCase().includes(p)}).slice(0,8):[],Ze=ne((u,p)=>{Nt.current?.close(),Nt.current=Gb({cwd:e,resume:u,profileName:p??s,allowProdWrites:gn.current}),u||(Jt.current={uuid:null,firstPrompt:null,titleFired:!1},Bn(null)),Jn(0),Zn(0)},[e,s]),ph=ne((u,p,c)=>{if(hk.test(u))try{let g=mt(e,s),T=typeof p.project_id=="string"&&p.project_id||g.project.projectId,W=tl(p,c),B=[],b=zy(p,c),k=b?`${b} \u2014 `:"",x=nl(c);u.endsWith("publish_article")&&x&&B.push(`${k}Live: ${x}`);let y=ol(c);y?B.push(`${k}Preview: ${y}`):W&&T&&B.push(`${k}Preview: ${el(g.connection.portalUrl,T,W,g.project.languageCode??"en")}`),B.length>0&&h({kind:"link",lines:B})}catch{}},[e,s,h]),Te=ne(async(u,p)=>{tt(!0),te.current=!1,we.current=!1,$e.current=null,_t(),se([]),Lo(null),Pl(null);let c=gt.current;if(p?.display?.startsWith("/"))try{let E=Qi(e,p.display);E&&(u=`${u}
489
+
490
+ ${E}`)}catch{}p?.quietUser||h({kind:"user",text:p?.echoDisplay&&p.display?p.display:u});let g=Jt.current;g.firstPrompt||(g.firstPrompt=p?.display??u),Et.current=Date.now(),Ue(0),A(!0),Lr.current.clear(),bl.current=null;let T="",W=!1,B=!1,b=!1,k=!1,x="",y={num:0,closed:!1,cueSeen:!1},v=null,P=()=>{v||(v=setTimeout(()=>{v=null,l(x.length>0?x:null)},60))},j=()=>{v&&clearTimeout(v),v=null,l(null)},I=(E=!1)=>{let{head:Y,keep:M}=Wb(x,E);Y.trim()&&h({kind:"assistant",text:wp(Y.trimEnd(),y)}),x=M,j()};try{for await(let E of Nt.current.send(u))if(E.type==="session"){if(!g.uuid){g.uuid=E.sessionId;let Y=new Date().toISOString(),M=$l.current,F=M??eD(g.firstPrompt??"session");tD({uuid:E.sessionId,name:F,renamed:!!M,titled:!1,cwd:e,firstPrompt:g.firstPrompt??"",createdAt:Y,updatedAt:Y}),Bn(F),$l.current=null}}else if(E.type==="text"){x+=E.delta,T+=E.delta;let Y=Bb(x);if(Y>0){let M=x.slice(0,Y).trimEnd();M&&h({kind:"assistant",text:wp(M,y)}),x=x.slice(Y)}P(),Ue(M=>M+E.delta.length)}else if(E.type==="tool"){W=!0,hk.test(E.name)&&(B=!0);let M=(me=>typeof me=="string"&&me?me.replace(/\\/g,"/").toLowerCase():null)(E.input.file_path??E.input.notebook_path),F=["Edit","Write","MultiEdit","NotebookEdit"].includes(E.name),G=E.name==="Read"&&M!==null&&M===Gp.current;Gp.current=F?M:null;let ee=Qs.current,ce=ee?null:Mb(E.name,E.input),he=ee?null:Qa(E.name,E.input,e,s);if(ce)Cl.current.push(ce);else if(he){I();let me=he.repeat&&he.articleKey&&he.articleKey===bl.current?he.repeat:he;bl.current=he.articleKey??null,h({kind:"doc",verb:he.verb,title:me.title,category:me.category,note:me.note,...he.loud?{loud:he.loud}:{}}),Lr.current.set(E.id,{name:E.name,input:E.input,doc:!0,keepResult:he.keepResult})}else if(G)I(),h({kind:"tool",title:"Read",sep:"",arg:"re-checking the file it just edited"});else{let me=Ja(E.name,E.input,e);me&&(I(),h({kind:"tool",title:me.title,sep:me.sep,arg:me.arg}),Lr.current.set(E.id,{name:E.name,input:E.input}))}}else if(E.type==="article_diff"){let Y=Rt(E.oldContent,E.newContent,qe());Y&&(I(),h({kind:"diff",added:Y.added,removed:Y.removed,lines:Y.lines,hidden:Y.hidden}))}else if(E.type==="tool_result"){E.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(E.output)&&(Js.current=!0);let Y=Lr.current.get(E.id);if(Y){Lr.current.delete(E.id),I();let F=Y.doc&&!Y.keepResult&&!E.isError?{lines:[],hidden:0}:Za(E.output,4,E.isError||Qs.current?void 0:Y.name,Y.input),G=E.isError&&pb(Y.name,E.output);F.lines.length>0&&h({kind:"tool-result",lines:F.lines,hidden:F.hidden,isError:E.isError&&!G}),E.isError||ph(Y.name,Y.input,E.output)}}else if(E.type==="result"){I(!0),Jn(G=>G+E.outputTokens),Zn(G=>Math.max(G,E.sessionCostUsd));let Y=E.inputTokens+E.cacheReadTokens+E.cacheCreationTokens;if(h({kind:"done",seconds:Math.round((Date.now()-Et.current)/1e3),tokens:E.outputTokens,costUsd:E.costUsd,sessionCostUsd:Math.max(Hr,E.sessionCostUsd),ok:E.ok,...Y>0?{inTokens:Y,cachedPct:Math.round(E.cacheReadTokens/Y*100)}:{}}),!b&&!W&&!T.trim()&&!Mr.current&&(k=!0,h({kind:"note",tone:"warn",text:"The agent produced no output \u2014 nothing ran this turn. Run /doctor: it runs a real turn with your skills and tools and reports what failed. Claude Code\u2019s own error was written either way \u2014 /logs shows it, and offers to copy it for the team."})),E.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(T))try{let G=sk(e);if(Sr(G)){let ee=fl(G,"utf8").trim();ee&&(Dl(ee),h({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{}let M=E.ok?ib(T):null;we.current=M!==null,$e.current=M;let F=E.ok?ab(T,XD):null;if(F)mn(!1),At.current=!1,se(F);else if(E.ok&&(y.cueSeen||(M?.options??0)>=2))mn(!0),At.current=!0,se([]);else if(M)se([]);else{let G=E.ok?Sb(T,po.map(ee=>ee.name)):[];if(G.length>0)oe(G[0]);else if(E.ok&&T.trim()&&!we.current){let ee=Mt(!1);ee.kind==="recommend"&&(ee.rec.lead||ee.rec.picker)||sD(u,T,e).then(ce=>{ce&&gt.current===c&&Je(ce)}).catch(()=>{})}}if(g.uuid&&(Ap(g.uuid),!g.titleFired)){g.titleFired=!0;let G=g.uuid,ee=g.firstPrompt;ee&&Vb(ee,e).then(ce=>{ce&&(ZN(G,ce),Bn(ce))}).catch(()=>{})}}else E.type==="error"&&(I(!0),b=!0,E.kind==="auth"&&(Js.current=!0),h(E.kind==="limit"?{kind:"note",text:`\u23F3 ${E.message}`,tone:"warn"}:{kind:"note",text:`agent error: ${E.message}`,tone:"error"}))}finally{if(A(!1),j(),ei(),B)try{let E=jp(await Dp({cwd:e,profileName:s,onRateLimit:Y=>We(`Document360 rate limit \u2014 waiting ${Math.ceil(Y.waitMs/1e3)}s\u2026`)}));E&&h({kind:"note",tone:E.startsWith("\u26A0")?"warn":"info",text:E})}catch{}finally{We(null)}O(E=>E+1),Jt.current.uuid&&gb(e,Jt.current.uuid,Ao.current),Js.current?(Js.current=!1,Ur.current=p?.display??u,Je("/login","\u21E5 tab to run /login \u2014 then I\u2019ll re-send your last prompt\u2026")):Ur.current=null,Mr.current&&(Mr.current=!1,Kn.current.length>0&&(h({kind:"note",tone:"info",text:`(${Kn.current.length} queued message(s) discarded)`}),Kn.current=[],vl([])),h({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}return{producedNothing:k,handedBack:$e.current!==null}},[e,h,ph,qe,Je,oe,_t,Mt,ei]),ai=ne(async()=>{try{We("Checking Document360 for new reviewer comments\u2026"),await Da(e,s,{onProgress:(u,p)=>We(`Checking Document360 for new reviewer comments\u2026 ${u}/${p}`)})}catch{}finally{We(null)}},[e,s]),ct=ne(async(u,p=0,c)=>{let g=Ip(e,u,{allowUnreviewed:c?.skipReview===!0,allowStyleErrors:c?.skipStyle===!0});if(!g.clear){h({kind:"note",tone:"warn",text:Lp(g,u.length,{act:"push"}).join(`
491
+ `)}),oe(Ru(g));return}Et.current=Date.now(),Ue(0),A(!0);let T=new AbortController;Oe.current=T;let W={aborted:!1,partitions:0,failed:0,notRun:0,producedNothing:!0},B={retryable:0,stopped:!1},b=async(k,x)=>{let y=Ep(k),v=new Map;for(let ee of y)for(let ce of ee.paths)v.set(ce,ee.label);let P=new Map(y.map(ee=>[ee.label,ee.paths.length])),j=new Set,I=Date.now();pe({verb:"Pushing",unit:"article",total:k.length,done:0,active:[],rows:$o(y),tools:0,chars:0,lastAt:Date.now(),startedAt:I,agentless:!0}),h({kind:"note",tone:"info",text:x?`Resolving cross-links in ${k.length} article${k.length===1?"":"s"} whose targets were saved this run (second pass)\u2026 (esc to stop)`:`Pushing ${k.length} article${k.length===1?"":"s"} to Document360 (${pD} at a time)\u2026 (esc to stop)`});let E=await uD({cwd:e,profileName:s,paths:k,allowProdWrites:gn.current,...c?.allowUnpullable===!0?{allowUnpullable:!0}:{},signal:T.signal,onEvent:ee=>{let ce=ee.type==="article_done"?ee.result.path:ee.type==="article_failed"?ee.failure.path:ee.path,he=v.get(ce);if(!he)return;if(ee.type==="article_start"){pe(X=>X&&!X.active.includes(he)?{...X,active:[...X.active,he],rows:Ve(X.rows,he,"active"),lastAt:Date.now()}:X&&{...X,lastAt:Date.now()});return}ee.type==="article_failed"&&j.add(he);let me=(P.get(he)??1)-1;P.set(he,me),pe(X=>{if(!X)return X;let ve={...X,done:X.done+1,rows:ul(X.rows,he),lastAt:Date.now()};return me>0?ve:{...ve,active:ve.active.filter(Ie=>Ie!==he),rows:Ve(ve.rows,he,j.has(he)?"failed":"done")}})}}),Y=E.aborted||!!E.stopped,M=Hc(e,k,s);x||(W={aborted:Y,partitions:y.length,failed:E.failed.length,notRun:E.notRun.length,producedNothing:E.pushed.length===0,verifiedComplete:M>=k.length,leftBehind:p});let F=E.pushed.length>0;h({kind:"note",tone:Y||E.failed.length>0||!F?"warn":"ok",text:(Y?"Stopped. ":"")+Gc(E,{recorded:M,elapsedMs:Date.now()-I,docsRoot:TD(e),...x?{}:{conflictsSkipped:p},...c?.scope?{scope:c.scope}:{}}).join(`
492
+ `)}),x||(B={retryable:E.failed.filter(ee=>!ee.refused).length,stopped:!!E.stopped});let G=Bc(e,s);if(G&&h({kind:"note",tone:"info",text:G}),F){let ee=sr(e,s);ee&&h({kind:"note",tone:"info",text:ee})}if(!Y&&F){try{let ce=await Dp({cwd:e,profileName:s,onRateLimit:me=>We(`Document360 rate limit \u2014 waiting ${Math.ceil(me.waitMs/1e3)}s\u2026`)}),he=jp(ce);he?h({kind:"note",tone:he.startsWith("\u26A0")?"warn":"info",text:he}):ce.skipped&&h({kind:"note",tone:"warn",text:`Order sync skipped: ${ce.skipped}`})}catch(ce){h({kind:"note",tone:"warn",text:`Order sync failed: ${ce.message}`})}finally{We(null)}try{let ce=lk(await ak({cwd:e,profileName:s}));ce&&h({kind:"note",tone:"info",text:ce})}catch(ce){h({kind:"note",tone:"warn",text:`Related-articles sync failed: ${ce.message}`})}let ee=await ps(e,s);ee&&h({kind:"note",tone:"info",text:ee})}return Y};try{let k=await b(u,!1);if(!k){let y=await qc(e,s,u);y.length>0&&await b(y,!0),yn(c?.scope?`/push ${c.scope}`:"/push --all",W)}let x=Ce("/push",c?.scope?"":"--all",c?.scope);B.retryable>0?Ee(null,{kind:"cmd",cmd:x,reason:B.stopped?"Document360 stopped answering \u2014 your articles are unchanged, so this picks up where the run left off":`${B.retryable} article${B.retryable===1?"":"s"} could not be saved \u2014 this retries them`},"warn"):!k&&p>0&&Ee(null,{kind:"cmd",cmd:"/resolve",reason:`${p} conflict${p===1?"":"s"} still need settling \u2014 they were left untouched`},"warn")}catch(k){h({kind:"note",tone:"error",text:`Publish run failed: ${k.message}`})}finally{Oe.current=null,pe(null),await ai(),A(!1),O(k=>k+1)}},[e,s,h,t,Ee,ai]),Wo=ne(u=>h({kind:"block",text:u.join(`
493
+ `)}),[h]),Bo=ne((u,p,c,g,T)=>{let W=Ct(u,p,c,Date.now(),T);h({kind:"done",seconds:W.seconds,tokens:W.outputTokens,costUsd:W.costUsd,ok:g,...W.activeSeconds!==void 0?{activeSeconds:W.activeSeconds}:{},sessionCostUsd:Hr+c,...W.inputTokens>0?{inTokens:W.inputTokens,...W.cachedPct!==void 0?{cachedPct:W.cachedPct}:{}}:{}})},[h,Hr]),li=ne(async u=>{let p=zs(e,"standard");Et.current=Date.now(),Ue(0),A(!0);let c=new AbortController;Oe.current=c;let g=Date.now(),T=new lr;T.start(),pe({verb:u.verb,unit:"article",total:u.partitions.length,done:0,active:[],rows:$o(u.partitions),tools:0,chars:0,lastAt:Date.now(),startedAt:g}),h({kind:"note",tone:"info",text:`${u.headline} on ${p.model}\u2026 (esc to stop)`});let W=!0,B=[],b=!1,k={aborted:!1,partitions:0,failed:0,notRun:0,producedNothing:!0},x=new Set;try{for await(let y of Ks({cwd:e,partitions:u.partitions,promptFor:u.promptFor,concurrency:u.concurrency,profileName:s,allowProdWrites:gn.current,model:p.model,signal:c.signal,scope:u.scope}))if(y.type==="partition_status")y.status==="running"?pe(v=>v&&{...v,active:[...v.active,y.label],rows:Ve(v.rows,y.label,"active"),lastAt:Date.now()}):pe(v=>v&&{...v,active:v.active.filter(P=>P!==y.label),done:v.done+1,rows:Ve(v.rows,y.label,y.status==="done"?"done":"failed"),lastAt:Date.now()});else if(y.type==="partition_stalled"){let v=xr(y);pe(P=>P&&v?{...P,stalledNote:v}:P)}else if(y.type==="partition_event"){let v=null;if(y.event.type==="tool"){let P=Rp(y.event.name,y.event.input,u.partitions[y.index]?.paths??[]);P&&!x.has(P)&&(x.add(P),v=y.label)}pe(P=>{if(!P)return P;let j={...P,lastAt:Date.now()};return y.event.type==="tool"?j.tools=P.tools+1:y.event.type==="text"&&(j.chars=P.chars+y.event.delta.length),v&&(j.rows=ul(j.rows,v)),j})}else if(y.type==="run_done"){Zn(I=>I+y.totalCostUsd),Jn(I=>I+y.results.reduce((E,Y)=>E+Y.outputTokens,0));let v=Np(u.partitions,y.results);W=!!y.allEmpty||!!y.blocked,b=!!y.aborted,k={aborted:!!y.aborted,partitions:u.partitions.length,failed:v.failed.length,notRun:v.notRun.length,...y.blocked?{blocked:y.blocked}:{},...y.allEmpty?{allEmpty:!0}:{},...y.bailedEmpty?{bailedEmpty:!0}:{}};let P=[`${y.aborted?"Stopped. ":""}${y.results.length-v.failed.length}/${u.partitions.length} batches ${u.doneNoun}.`,...v.failed.length?[`\u26A0 ${v.failed.length} not ${u.doneNoun} \u2014 their articles are unchanged: ${v.failed.map(I=>I.label).join(", ")}`]:[],...v.notRun.length?[`\u26A0 ${v.notRun.length} batch${v.notRun.length===1?"":"es"} never started \u2014 their articles are untouched.`]:[],...y.blocked?[`\u26A0 ${y.blocked}`]:[],...y.allEmpty?[u.emptyNote??"\u26A0 No turn produced any work this run \u2014 nothing was changed."]:[],...u.caveatLines??[]];h({kind:"note",tone:y.aborted||v.failed.length||v.notRun.length||y.blocked||y.allEmpty?"warn":"ok",text:P.join(`
494
+ `)});let j=T.stop();if(Bo(g,y.results,y.totalCostUsd,!b&&!W&&!v.failed.length,j.activeSeconds),u.calibrateAs){let I=y.results.filter(E=>E.ok).length;cD(e,u.calibrateAs,{articles:v.covered.length,waves:Math.ceil(I/Math.max(1,u.concurrency)),seconds:j.activeSeconds,costUsd:y.totalCostUsd})}W||(B=v.covered)}}catch(y){h({kind:"note",tone:"error",text:`${u.verb} failed: ${y.message}`})}finally{T.stop(),Oe.current=null,pe(null),A(!1),O(y=>y+1)}return{producedNothing:W,covered:B,aborted:b,outcome:k}},[e,s,h,Bo]),Ak=ne(async(u,p)=>{let c=await li({partitions:u.partitions,promptFor:u.promptFor,concurrency:_n,verb:"Reviewing",doneNoun:"reviewed",headline:`Reviewing ${u.articles} article${u.articles===1?"":"s"} in ${u.partitions.length} batches (\u2264${_n} editors at once)${p?", applying fixes as they go":", report only"}`+(()=>{let g=Ba(e,"/review",u.articles,u.partitions.length);return g?` \xB7 ${g}`:""})(),caveatLines:Jd(u),emptyNote:"\u26A0 No editor produced any work this run \u2014 nothing was reviewed or changed.",calibrateAs:"/review",scope:"review"});if(p&&c.covered.length>0)try{Tr(e,c.covered,it("review"))}catch{}return{producedNothing:c.producedNothing,aborted:c.aborted,outcome:c.outcome}},[e,li]),_l=ne(async(u,p)=>{if(u.length===0)return;let c=u.reduce((x,y)=>x+y.threads.length,0),g=new Map,T=u.map(x=>(g.set(x.label,x),{label:x.label,paths:x.path?[x.path]:[]})),W=zs(e,"standard");Et.current=Date.now(),Ue(0),A(!0);let B=new AbortController;Oe.current=B;let b=Date.now(),k=ik(e);pe({verb:"Answering",unit:"article",total:T.length,done:0,active:[],rows:$o(T),tools:0,chars:0,lastAt:Date.now(),startedAt:b}),h({kind:"note",tone:"info",text:`Answering ${c} comment${c===1?"":"s"} across ${T.length} article${T.length===1?"":"s"} (\u2264${Is} agents at once) on ${W.model}. Each article is fixed, pushed to Document360 as a draft, then answered in the thread${p.resolve?" and resolved":" \u2014 the threads stay open for your reviewers to close"}\u2026 (esc to stop)`});try{for await(let x of Ks({cwd:e,partitions:T,promptFor:y=>{let v=g.get(y.label);return Dd({articleId:v.articleId,label:v.label,path:v.path,count:v.threads.length,resolve:p.resolve})},concurrency:Is,profileName:s,allowProdWrites:gn.current,allowCommentResolve:p.resolve,model:W.model,signal:B.signal}))if(x.type==="partition_status")x.status==="running"?pe(y=>y&&{...y,active:[...y.active,x.label],rows:Ve(y.rows,x.label,"active"),lastAt:Date.now()}):pe(y=>y&&{...y,active:y.active.filter(v=>v!==x.label),done:y.done+1,rows:Ve(y.rows,x.label,x.status==="done"?"done":"failed"),lastAt:Date.now()});else if(x.type==="partition_stalled"){let y=xr(x);pe(v=>v&&y?{...v,stalledNote:y}:v)}else if(x.type==="partition_event")pe(y=>{if(!y)return y;let v={...y,lastAt:Date.now()};return x.event.type==="tool"?v.tools=y.tools+1:x.event.type==="text"&&(v.chars=y.chars+x.event.delta.length),v});else if(x.type==="run_done"){Zn(M=>M+x.totalCostUsd),Jn(M=>M+x.results.reduce((F,G)=>F+G.outputTokens,0));let y=Np(T,x.results),v=x.results.length-y.failed.length,P=x.aborted?"Stopped. ":"",j=[...y.failed.map(M=>M.label),...y.notRun.map(M=>M.label)],I=[`${P}${v}/${T.length} article${T.length===1?"":"s"} answered.`,...j.length?[`\u26A0 ${j.length} left untouched (their threads are still open, which is correct \u2014 nothing was promised to those reviewers): ${j.join(", ")}`]:[],...x.blocked?[`\u26A0 ${x.blocked}`]:[],...x.allEmpty?["\u26A0 No agent produced any work this run \u2014 nothing was changed or answered."]:[]];h({kind:"note",tone:x.aborted||j.length||x.blocked||x.allEmpty?"warn":"ok",text:I.join(`
495
+ `)}),Bo(b,x.results,x.totalCostUsd,!x.aborted&&!j.length&&!x.blocked&&!x.allEmpty);let E=new Set(j),Y=[...p.rest??[],...u.filter(M=>E.has(M.label))];if(Y.length>0&&!x.aborted&&p.report){let M=Y.reduce((G,ee)=>G+ee.threads.length,0);h({kind:"note",tone:"info",text:`${M} comment${M===1?"":"s"} on ${Y.length} other article${Y.length===1?"":"s"} still open \u2014 pick the next one, or esc to stop here.`});let F={...p.report,threads:Y.flatMap(G=>G.threads)};Wo(Ls(F,{width:qe()})),en({cursor:0,rows:Ia(Y),groups:Y,resolve:p.resolve,report:F})}else if(Y.length>0&&!x.aborted){let M=Y.map(G=>G.path).filter(G=>!!G),F=M.length===Y.length?Yt(M):void 0;oe(F?M.length===1?`/comments ${F}`:`/comments --scope ${F}`:"/comments")}}}catch(x){h({kind:"note",tone:"error",text:`Answering comments failed: ${x.message}`})}finally{let y=mo(e,k,"","/comments").changed.length;y>0&&h({kind:"note",tone:"info",text:`${y} article${y===1?"":"s"} changed, and that new text has not been read by an editor \u2014 ${y===1?"it":"they"} can go live once /review has been over ${y===1?"it":"them"}.`}),Oe.current=null,pe(null),A(!1),O(v=>v+1)}},[e,s,h,Ee,oe,Wo,qe]),Ml=ne(async(u,p)=>{if(!(p?.skipReview===!0||p?.skipStyle===!0)){let g=Ip(e,[u],{});if(!g.clear){h({kind:"note",tone:"warn",text:Lp(g,1,{act:"push"}).join(`
496
+ `)}),oe(Ru(g,u));return}}await ct([u],0,{skipReview:p?.skipReview,skipStyle:p?.skipStyle,scope:u});try{let g=await na(e,s,u.replace(/\\/g,"/"));g.length>0&&(Lo(`Related articles not yet saved to Document360 (${g.length}):`),se([`/push --related ${u}`,...g.map(T=>`/push ${T}`)]))}catch{}},[e,s,Te,ct]),Ek=ne(async(u,p)=>{A(!0);try{let c=await Qc(e,s,u,{skipReview:p.skipReview,skipStyle:p.skipStyle,onProgress:(T,W,B)=>We(`Publishing ${T+1}/${W} \u2014 ${B}\u2026`)}),g=c.blocked.length+c.failed.length;h({kind:"note",tone:g>0?"warn":"ok",text:Jc(c).join(`
497
+ `)}),c.blocked.length>0?oe("/review --blocked --fix"):Ee(null,null)}catch(c){h({kind:"note",tone:"error",text:`Publishing failed: ${c.message}`})}finally{We(null),await ai(),A(!1),O(c=>c+1)}},[e,s,h,oe,Ee,ai]),hh=ne(async u=>{try{let p=await gl({cwd:e,profileName:s}),{clean:c,conflicts:g}=co(p.entries);if(c.length===0){h({kind:"note",tone:"info",text:"Nothing new to save \u2014 everything is already up to date on Document360."});return}await ct(c.map(T=>T.path),g.length,{skipReview:u?.skipReview,skipStyle:u?.skipStyle})}catch(p){h({kind:"note",tone:"warn",text:`Couldn\u2019t check what to save (${p.message}) \u2014 your articles are written; run /push when ready.`})}},[e,s,ct]),yn=ne((u,p)=>{if(!(p&&!Kt(p)))for(let c of vt(e,u))h({kind:"note",tone:"ok",text:c})},[e,h]),fh=ne(async(u,p)=>{let g=yD(u,3),T=zs(e,"standard"),W=new Map,B=new Map;for(let y of u){let v=ao(e,y),P=gc(e,y,v);if(P&&W.set(y,P),v!==null){let j=Ac(v);j.length>0&&B.set(y,j)}}Et.current=Date.now(),Ue(0),A(!0);let b=new AbortController;Oe.current=b;let k=Date.now();pe({verb:"Authoring",unit:"spec",total:g.length,done:0,active:[],rows:$o(g),tools:0,chars:0,lastAt:Date.now(),startedAt:k}),h({kind:"note",tone:"info",text:`Authoring ${u.length} screenshot spec${u.length===1?"":"s"} in ${g.length} batch${g.length===1?"":"es"} (\u22646 agents at once) on ${T.model}${T.forced?" (forced)":""}\u2026 (esc to stop)`});let x=!1;try{for await(let y of Ks({cwd:e,partitions:g,promptFor:v=>am(v,W,B),concurrency:6,profileName:s,allowProdWrites:gn.current,model:T.model,signal:b.signal}))if(y.type==="partition_status")y.status==="running"?pe(v=>v&&{...v,active:[...v.active,y.label],rows:Ve(v.rows,y.label,"active"),lastAt:Date.now()}):pe(v=>v&&{...v,active:v.active.filter(P=>P!==y.label),done:v.done+1,rows:Ve(v.rows,y.label,y.status==="done"?"done":"failed"),lastAt:Date.now()});else if(y.type==="partition_stalled"){let v=xr(y);pe(P=>P&&v?{...P,stalledNote:v}:P)}else if(y.type==="partition_event")pe(v=>{if(!v)return v;let P={...v,lastAt:Date.now()};return y.event.type==="tool"?P.tools=v.tools+1:y.event.type==="text"&&(P.chars=v.chars+y.event.delta.length),P});else if(y.type==="run_done"){Zn(E=>E+y.totalCostUsd),Jn(E=>E+y.results.reduce((Y,M)=>Y+M.outputTokens,0));let v=y.results.filter(E=>E.ok).length,P=y.aborted?"Stopped. ":"";x=!y.aborted&&p.setup;let j=y.aborted?"":x?" Refreshing the staging checklist\u2026":` Next: /screenshot capture${p.scope?` ${p.scope}`:" --all"} (or /screenshot checklist first for the staging checklist).`,I=Tn(y,"Spec authoring");h({kind:"note",tone:I||y.aborted?"warn":y.ok?"ok":"warn",text:I?I.join(`
498
+ `):`${P}Authored specs \u2014 ${v}/${y.results.length} batches ok.${j}`}),Bo(k,y.results,y.totalCostUsd,!I&&!y.aborted&&y.ok),I&&(oe("/doctor"),x=!1),!y.aborted&&y.ok&&!I&&yn(p.runLine)}}catch(y){h({kind:"note",tone:"error",text:`Spec authoring failed: ${y.message}`})}finally{Oe.current=null,pe(null),A(!1),O(y=>y+1)}if(x){let y=await wr();y.kind==="forward-to-agent"&&y.prompt&&await Te(y.prompt,{display:y.display,quietUser:!0}),Tl()}},[e,s,h,Te,yn,Tl]),mh=ne(async u=>{let p=gc(e,u,ao(e,u))??void 0,c=await Ki([u],void 0,{prior:p});c.kind==="forward-to-agent"&&c.prompt&&await Te(c.prompt,{display:c.display,quietUser:!0}),Vf(e,u)&&Ee(`Spec ready \u2014 /screenshot capture ${u} takes the screenshot; bare /screenshot picks the next shot.`,{kind:"cmd",cmd:`/screenshot capture ${u}`,reason:""})},[e,Te,Ee]),ci=ne(async(u,p)=>{if(u.length===0)return{drawn:[],undrawn:[],cliMissing:!1};A(!0);let c=new AbortController;Oe.current=c,pe({verb:"Drawing callouts",unit:"screenshot",total:u.length,done:0,active:[],rows:u.map(v=>({label:v,items:1,status:"pending"})),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()});let g=[],T=!1;try{let v=await fd({cwd:e,ids:u,...p.force?{force:!0}:{},signal:c.signal,onStart:P=>pe(j=>j&&{...j,active:[P],rows:Ve(j.rows,P,"active"),lastAt:Date.now()}),onDone:(P,j)=>pe(I=>I&&{...I,active:[],done:I.done+1,rows:Ve(I.rows,P,j==="failed"?"failed":"done"),lastAt:Date.now()})});g=v.results,T=v.cliMissing??!1}catch(v){h({kind:"note",tone:"error",text:`Drawing the callouts failed: ${v.message}`})}finally{Oe.current=null,pe(null),A(!1),O(v=>v+1)}if(T)return h({kind:"note",tone:"error",text:"d360-capture is not installed on this machine. Run: npm i -g document360-capture \u2014 then /screenshot annotate."}),{drawn:[],undrawn:u,cliMissing:!0};let W=g.filter(v=>v.outcome==="annotated").map(v=>v.id),B=g.filter(v=>v.outcome==="skipped").map(v=>v.id),b=u.filter(v=>!W.includes(v)&&!B.includes(v));if(h({kind:"note",tone:b.length?"warn":"ok",text:[`\u25C8 ${W.length} drawn`,B.length?`${B.length} already current`:"",b.length?`\u2717 ${b.length} not drawn`:""].filter(Boolean).join(" ")}),b.length>0){let v=Math.max(...b.map(P=>P.length));h({kind:"note",tone:"warn",text:b.map(P=>`\u2717 ${P.padEnd(v)} ${As(g.find(j=>j.id===P)?.detail)||"no picture was produced"}`).join(`
497
499
  `)+`
498
- ${y.length===1?"It has":"They have"} no publishable picture yet. Re-take the shot: /screenshot capture`})}if(p.chainVerify===!1||W.length===0)return{drawn:W,undrawn:y,cliMissing:!1};let $=W.filter(x=>p.verifiedBefore.has(x)).length;if($>Sa){let x=pw({results:m,voidedVerdicts:$,...p.scope?{scope:p.scope}:{}});return x&&Ne(`${x.glyph} ${x.cmd} ${x.why}`,{kind:"cmd",cmd:x.cmd,reason:""},"warn"),{drawn:W,undrawn:y,cliMissing:!1}}let R=W.filter(x=>!p.verifiedBefore.has(x)||$>0);if(R.length===0)return{drawn:W,undrawn:y,cliMissing:!1};h({kind:"note",tone:"info",text:In(R.length)}),await Se(Qt(e,R),{display:"/screenshot verify",quietUser:!0});let b=fr(e,R);return b.length>0&&h({kind:"note",tone:"info",text:b.join(`
499
- `)}),{drawn:W,undrawn:y,cliMissing:!1}},[e,h,Ne,Se]),zr=te(async(u,p)=>{if(!ho(e)){await Se(rd(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(!nw(e)){h({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),We("Waiting for you to finish logging in (browser window)\u2026");let F=new AbortController;Le.current=F;let U;try{U=await ow({cwd:e,signal:F.signal})}catch(ie){h({kind:"note",tone:"error",text:`Could not launch the login: ${ie.message}`});return}finally{Le.current=null,We(null),T(!1)}if(U.exitCode!==0){od(U.exitCode,U.output)?h({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(U.output)?h({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."}):h({kind:"note",tone:F.signal.aborted?"warn":"error",text:F.signal.aborted?"Login cancelled \u2014 nothing saved.":`Login did not complete:
500
- ${td(U.output)}`});return}h({kind:"note",tone:"ok",text:"\u2713 Login saved \u2014 continuing with the capture."})}let c=new Map(u.map(F=>[F,zf(e,F)])),m=0;if(u.length>1){let F=u.filter(U=>c.get(U).mutates);if(F.length>0&&(m=F.length,u=u.filter(U=>!c.get(U).mutates),u.length===0)){h({kind:"note",tone:"warn",text:`\u26A0 All ${F.length} spec${F.length===1?"":"s"} in scope write real data, so a bulk run has nothing to do. Run one deliberately: /screenshot capture ${F[0]}`});return}}else if(u.length===1&&c.get(u[0]).mutates){let F=c.get(u[0]),U=rw(e);h({kind:"note",tone:"warn",text:`\u26A0 This capture performs a REAL write in your app${F.what?`: ${Kf(F.what)}`:F.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. `+(U.production?`This profile is PRODUCTION \u2014 the write lands in the LIVE tenant${U.url?` (${U.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 A=new AbortController;Le.current=A;let W=u.map(F=>({label:F,items:1,status:"pending"}));he({verb:"Capturing",unit:"screenshot",total:u.length,done:0,active:[],rows:W,tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()});let G=ln(e),y=Object.keys(G.shots).length>0,$=sw(p?.heldBackBlocked??[],m);h({kind:"note",tone:"info",text:`Capturing ${u.length} screenshot${u.length===1?"":"s"} with d360-capture (a real browser drives your app)\u2026 (esc to stop)`+($?`
501
- ${$}`:"")});let R=Date.now(),b=[];try{for(let F of u){if(A.signal.aborted)break;he(pe=>pe&&{...pe,active:[F],rows:Ve(pe.rows,F,"active"),lastAt:Date.now()});let{exitCode:U,output:ie}=await nd({cwd:e,id:F,signal:A.signal,stdio:"pipe"});if(od(U,ie)){h({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 ne=A.signal.aborted&&U!==0?"failed":ed(e,F,U,R),De=ne==="captured"?void 0:ne==="skipped"?ew(ie)??"a data prerequisite isn't met \u2014 the spec's skip reason names what to stage":tw(ie);b.push({id:F,outcome:ne,detail:De}),he(pe=>pe&&{...pe,active:[],done:pe.done+1,rows:Ve(pe.rows,F,ne==="captured"?"done":"failed"),lastAt:Date.now()})}}catch(F){h({kind:"note",tone:"error",text:`Capture run failed: ${F.message}`})}finally{Le.current=null,he(null),T(!1),M(F=>F+1)}if(b.length===0)return;let x=b.filter(F=>F.outcome==="captured"),P=b.filter(F=>F.outcome==="skipped"),j=b.filter(F=>F.outcome==="failed"),N=u.length-b.length;h({kind:"note",tone:j.length?"warn":x.length?"ok":"info",text:[`\u2713 ${x.length} captured`,P.length?`\u2298 ${P.length} blocked`:"",j.length?`\u2717 ${j.length} broken`:"",N?`${N} not run (stopped)`:""].filter(Boolean).join(" ")+` ${b.length} run${m>0?` \xB7 ${m} held back`:""}`+lw(iw(G,b),y).map(F=>`
502
- ${F}`).join("")});let E=aw(P);if(E.length>0&&h({kind:"note",tone:"info",text:E.join(`
503
- `)}),j.length>0){let F=Math.max(...j.map(U=>U.id.length));h({kind:"note",tone:"error",text:j.map(U=>`\u2717 ${U.id.padEnd(F)} ${Ts(U.detail)}`).join(`
504
- `)})}Li(e,b.map(F=>({id:F.id,outcome:F.outcome,reason:F.detail,specSource:io(e,F.id)})),new Date().toISOString()),b.length===u.length&&j.length===0&&P.length===0&&yn(p?.runLine);let K=[];if(x.length>0&&Ca()){let F=await ci(x.map(U=>U.id),{verifiedBefore:new Set});if(F.cliMissing||(K=F.undrawn,F.drawn.length>0))return}else if(x.length>0){h({kind:"note",tone:"info",text:In(x.length)}),await Se(Qt(e,x.map(U=>U.id)),{display:"/screenshot verify",quietUser:!0});let F=fr(e,x.map(U=>U.id));F.length>0&&h({kind:"note",tone:"info",text:F.join(`
505
- `)});return}let _=cw({results:b,ids:u,articles:uw(e,x.map(F=>F.id)),...K.length>0?{unannotated:K}:{}});_&&Ne(_.note,{kind:"cmd",cmd:_.cmd,reason:""},_.tone)},[e,h,Ne,Se,yn,ci]),_l=te(u=>{let p=Un(u);if(!p||ko(p)&&!p.refreshToken)return null;let c={...Er(p.idToken)??{},...Er(p.accessToken)??{}};return c.email??c.preferred_username??"signed in"},[]),Ml=te((u,p)=>{if(p){let c=Re(e);c&&(c.defaultProfile=u,Wb(c,e))}i(u),Ze(void 0,u),h({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${u}"${p?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),_l(u)||(h({kind:"note",tone:"warn",text:`Profile "${u}" is not signed in \u2014 sign in with /login.`}),oe("/login")),M(c=>c+1)},[e,h,Ze,_l,oe]),ui=te((u,p,c)=>{fi(e,u,p,c.id,c.name),h({kind:"note",tone:"ok",text:`Switched to workspace "${c.name??c.id}" (agent restarted).`}),Ze(),Gb(e,u)||(h({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),h({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:"}),h({kind:"note",tone:"info",text:Qo(Xo(e)).join(`
506
- `)}),on(ro()),Yr.current=Ut(e).status==="current",Fo.current=an(e),h({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,h,Ze,on]),di=te(async u=>{let p;try{p=await es(e,u)}catch{h({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),oe("/workspace");return}if(p.workspaces.length===0){h({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let c=p.workspaces.filter(A=>(A.workspace_type??"").toLowerCase()!=="apidocumentation"),m=c.length>0?c:p.workspaces;if(m.length===1){let A=m[0],W=p.workspaces.length-m.length;h({kind:"note",tone:"ok",text:`Selected the "${A.name??A.id}" workspace${W>0?" (skipped the API-documentation workspace)":""}.`}),ui(p.profile,p.projectId,A);return}h({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${m.length} available).`}),oe("/workspace")},[e,h,ui,oe]),pi=te((u,p)=>{mi(e,u,p.id,p.name),h({kind:"note",tone:"ok",text:`Project set to "${p.name??p.id}" (agent restarted).`}),Ze(),di(u)},[e,h,Ze,di]),dh=te(async u=>{let p;try{p=mt(e,u)}catch{return}if(!p.project.workspaceId){if(p.project.projectId){if(!p.project.projectName)try{let{projects:c}=await sn(e,p.name),m=c.find(A=>A.id===p.project.projectId);m?.name&&yD(e,p.name,{projectName:m.name})}catch{}await di(p.name);return}try{let{projects:c}=await sn(e,p.name);if(c.length===1){let m=c[0];h({kind:"note",tone:"ok",text:`Using your Document360 project "${m.name??m.id}".`}),pi(p.name,{id:m.id,name:m.name});return}if(c.length>1){let m=c.map(A=>({id:A.id,name:A.name??A.id,sub:A.sub_domain}));h({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),Gn({cursor:0,current:-1,rows:m,profile:p.name,environment:p.connection.name});return}}catch{}h({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),oe("/project")}},[e,h,di,pi,oe]),Bo=te(()=>{let u=Ee.current[0];if(!u)return;if(_t(),u.mode==="local-only"){h({kind:"note",tone:"info",text:`\u25CF ${u.title??u.path} (${u.path})`});for(let W of ia())h({kind:"note",tone:"warn",text:`\u26A0 ${W}`});h({kind:"note",tone:"info",text:aa()}),h({kind:"note",tone:"info",text:Fm()});return}let{plan:p,mode:c}=u;h({kind:"note",tone:"info",text:`\u25CF ${p.title} (${p.path})`});for(let W of p.notes)h({kind:"note",tone:"warn",text:`\u26A0 ${W}`});p.overwritesLocalChanges&&c==="pull"&&h({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let m=Rt(p.oldContent,p.newContent,Ge(),ir);h(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."});let A=Ee.current.length;c==="conflict"?(h({kind:"note",tone:"warn",text:"Conflict \u2014 edited both here and on the portal (diff shows local \u2192 portal)."}),h({kind:"note",tone:"info",text:"Keep local (publish, overwrites portal) \xB7 take Portal (overwrites local) \xB7 Skip?"}),h({kind:"note",tone:"info",text:A>1?`(l/p/s \xB7 la/pa/sa for all ${A} \u2014 anything else stops, keeping your answers so far)`:"(l/p/s \u2014 anything else stops, keeping your answers so far)"})):h({kind:"note",tone:"info",text:A>1?`Write ${p.path}? (y/n \xB7 ya/na for all ${A} \u2014 anything else cancels)`:`Write ${p.path}? (y/n \u2014 anything else cancels)`})},[h,Ge,_t]),to=te(()=>{if(Ee.current.length>0){Bo();return}let u=Dt.current;Dt.current=[];let p=Zt.current;Zt.current=[];for(let c of la(p))h({kind:"note",tone:"warn",text:`\u26A0 ${c}`});u.length>0?(h({kind:"note",tone:"info",text:`Saving ${u.length} kept-local article${u.length===1?"":"s"} over the portal\u2026`}),ct(u,0,{allowUnpullable:!0})):p.length>0||oe("/pull")},[Bo,h,ct,oe]),Fl=te(u=>{let p=ol(u);if(!p)return!1;let c=Ee.current.splice(0),m=c.length;if(p==="local"){for(let A of c)Dt.current.push(OD(A));h({kind:"note",tone:"info",text:`Keeping local for all ${m} \u2014 will publish ${m===1?"it":"them"} over the portal.`})}else if(p==="portal"){let A=0;for(let W of c){if(W.mode==="local-only"){h({kind:"note",tone:"warn",text:`\u26A0 ${Qc(W.path)}`}),Zt.current.push(W.path);continue}try{fl({cwd:e,profileName:s},W.plan),A++}catch(G){h({kind:"note",tone:"error",text:`Take-portal failed for ${W.plan.path}: ${G.message}`})}}h({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${A} article${A===1?"":"s"} (local overwritten, sync base advanced).`})}else{for(let A of c)A.mode==="local-only"&&Zt.current.push(A.path);h({kind:"note",tone:"info",text:`Skipped all ${m} \u2014 still conflict${m===1?"":"s"}.`})}return to(),!0},[e,s,to,h]),ph=te(u=>{if(Ee.current.length===0)return!1;let p=u.trim(),c=p.toLowerCase(),m=Ee.current[0];if(m.mode==="local-only"){if(ol(p))return Fl(p);if(c==="l"||c==="local"||c==="publish")Ee.current.shift(),Dt.current.push(m.path),h({kind:"note",tone:"info",text:`Publishing your copy of ${m.path} over the portal.`});else if(c==="s"||c==="skip")Ee.current.shift(),Zt.current.push(m.path),h({kind:"note",tone:"info",text:`Skipped ${m.path} \u2014 still a conflict.`});else{let W=Ee.current.splice(0),G=Dt.current;return Dt.current=[],Zt.current=[],h({kind:"note",tone:"info",text:`Resolve cancelled. ${W.length} conflict${W.length===1?"":"s"} left untouched.`+(G.length>0?` Saving the ${G.length} article${G.length===1?"":"s"} you already chose to keep - an answer you gave is not undone by stopping.`:"")}),G.length>0&&ct(G,0,{allowUnpullable:!0}),!0}return to(),!0}if(m.mode==="conflict"){if(ol(p))return Fl(p);if(c==="l"||c==="local")Ee.current.shift(),Dt.current.push(m.plan.path),h({kind:"note",tone:"info",text:`Keeping local ${m.plan.path} \u2014 will publish over the portal.`});else if(c==="p"||c==="portal"){Ee.current.shift();try{fl({cwd:e,profileName:s},m.plan),h({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${m.plan.path} (local overwritten, sync base advanced).`})}catch(W){h({kind:"note",tone:"error",text:`Take-portal failed: ${W.message}`})}}else if(c==="s"||c==="skip"||c==="n")Ee.current.shift(),h({kind:"note",tone:"info",text:`Skipped ${m.plan.path} \u2014 still a conflict.`});else{let W=Ee.current.length;Ee.current=[];let G=Dt.current;return Dt.current=[],Zt.current=[],h({kind:"note",tone:"info",text:`Resolve cancelled. ${W} conflict${W===1?"":"s"} left untouched.`+(G.length>0?` Saving the ${G.length} article${G.length===1?"":"s"} you already chose to keep - an answer you gave is not undone by stopping.`:"")}),G.length>0&&ct(G,0,{allowUnpullable:!0}),!0}return to(),!0}let A=ob(p);if(A){let W=Ee.current.splice(0);if(A==="skip")h({kind:"note",tone:"info",text:`Skipped all ${W.length} article${W.length===1?"":"s"}.`});else{let G=0;for(let y of W){if(y.mode==="local-only"){h({kind:"note",tone:"warn",text:`\u26A0 ${Qc(y.path)}`});continue}try{fl({cwd:e,profileName:s},y.plan),G++}catch($){h({kind:"note",tone:"error",text:`Pull failed for ${y.plan.path}: ${$.message}`})}}h({kind:"note",tone:"ok",text:`\u2713 Pulled ${G} article${G===1?"":"s"} (sync base advanced).`})}return to(),!0}if(c==="y"||c==="yes"){let{plan:W}=m;Ee.current.shift();try{fl({cwd:e,profileName:s},W),h({kind:"note",tone:"ok",text:`\u2713 Pulled ${W.path} (sync base advanced).`})}catch(G){h({kind:"note",tone:"error",text:`Pull failed: ${G.message}`})}}else if(c==="n"||c==="no")Ee.current.shift(),h({kind:"note",tone:"info",text:`Skipped ${m.plan.path}.`});else{let W=Ee.current.length;return Ee.current=[],h({kind:"note",tone:"info",text:`Pull cancelled (${W} article(s) left untouched).`}),!0}return to(),!0},[e,s,to,h,Fl]),Ul=te(async u=>{h({kind:"note",tone:"info",text:"Checking Document360 for conflicts\u2026"});try{let p=await ml({cwd:e,profileName:s}),c=u?.replace(/\\/g,"/"),m=p.entries.filter(G=>G.status==="conflict"&&G.path).map(G=>G.path);if(c){if(!m.includes(c)){h({kind:"note",tone:"ok",text:`${c} isn\u2019t in conflict \u2014 nothing to resolve.`});return}m=[c]}if(m.length===0){h({kind:"note",tone:"ok",text:"\u2713 No conflicts \u2014 local and Document360 agree on every tracked article."});return}let A=[];for(let G of m)try{A.push({plan:await qb({cwd:e,profileName:s,relPath:G}),mode:"conflict"})}catch(y){Vb(y)?A.push({mode:"local-only",path:G,title:Yb(e,G)}):h({kind:"note",tone:"error",text:`Could not load ${G} from Document360: ${y.message}`})}if(A.length===0)return;let W=A.some(G=>G.mode!=="local-only");h({kind:"note",tone:"info",text:W?`Resolving ${A.length} conflict${A.length===1?"":"s"} \u2014 for each: keep local, take portal, or skip.`:`Resolving ${A.length} conflict${A.length===1?"":"s"} \u2014 for each: publish your copy over the portal, or skip.`}),Ee.current=A,Dt.current=[],Zt.current=[],Bo()}catch(p){h({kind:"note",tone:"error",text:`Could not compute sync status: ${p.message}`})}},[e,s,h,Bo]),hh=te(u=>{let p=Lr.current;if(!p)return!1;if(Lr.current=null,_t(),u.trim()!==p.repoName)return h({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:c,failed:m}=Dd(e,p.targets);h({kind:"note",tone:m.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${c.length} item${c.length===1?"":"s"}. The repo is back to its original state.`});for(let A of m)h({kind:"note",tone:"error",text:` \u2717 ${A.path}: ${A.error}`});return p.hadDevhints&&(h({kind:"note",tone:"warn",text:Ti().join(`
507
- `)}),on(nc())),h({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
508
- ${rk}`}),oe("/init"),tt(!1),!0},[e,h,on,_t,oe]),Ho=te(async u=>{let p=u.slice(1).trim().split(/\s+/),c=(p[0]??"").toLowerCase(),m=p.slice(1);if(eh.current=u.trim(),tt(!0),$s(m)&&["write","lint","check","review","reorder"].includes(c)){let y=ks(e,s);if(y.length===0){h({kind:"note",tone:"warn",text:"No categories yet \u2014 author some articles first, then scope to one."});return}let $=R=>c==="write"?`/write ${bg(m,R).join(" ")}`.trim():`/${c} ${[R,...m.filter(b=>b!=="--scope")].join(" ")}`.trim();if(y.length===1){Ho($(y[0].token));return}Vn({cursor:0,rows:y,run:R=>{Ho($(R))}});return}if(jn(c,m)){let y=c==="write"&&vs(m).rewrite,$=c==="write"?_u(e,Qb(e),{rewrite:y}):ks(e,s);if($.length>1){let R=m.filter(U=>U.startsWith("--")).join(" "),b=U=>U==="--blocked"?`/${c} --blocked${R?` ${R}`:""}`.trim():`/${c}${U?` ${c==="write"?`--scope ${U}`:U}`:""}${R?` ${R}`:""} ${U?"":"--all"}`.replace(/\s+/g," ").trim(),x=$.reduce((U,ie)=>U+ie.count,0),P={token:"",label:c==="review"?`Everything \u2014 all ${x} articles + structure (IA) review`:c==="reorder"?`Everything \u2014 reorder all ${$.length} categories`:y?`Everything \u2014 rewrite all ${x} planned articles`:`Everything \u2014 write all ${x} pending article${x===1?"":"s"}`,count:x},j=c==="review"?Hd(e):[],N=j.length>0&&j.length<x?[{token:"--blocked",label:`Only what needs review \u2014 ${j.length} article${j.length===1?"":"s"} publishing is blocked on`,count:j.length}]:[],E=c==="review"?Gd(e):[],K=E.length>j.length&&E.length<x?[{token:"--stale",label:`Everything the current editor hasn\u2019t read \u2014 ${E.length} article${E.length===1?"":"s"}`,count:E.length}]:[],_=c==="write"?`Write which articles? (counts = ${y?"articles to regenerate":"still to write"})`:c==="review"?"Review what? (counts = articles)":"Reorder what?";Vn({cursor:0,rows:(U=>c==="review"||c==="write"?U.map(ie=>{let ne=(()=>{try{return Kw(e,b(ie.token))}catch{return null}})();return ne?{...ie,label:`${ie.label} \xB7 ${ne}`}:ie}):U)([...N,...K,P,...$]),run:U=>{Ho(b(U))},title:_});return}}let A=async y=>{let $=Qu(y);if(!ho(e)){await Se(rd(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if($.mode==="single"){await zr([$.id],{runLine:[`/screenshot capture ${$.id}`,`/capture ${$.id}`]});return}if($.mode==="failed"){let b=Ju(e,As(e).rows);if(b.length===0){h({kind:"note",tone:"info",text:"No broken specs to re-run \u2014 /screenshot list shows where things stand."}),oe("/screenshot list");return}await zr(b);return}if($.mode==="blocked"){let{blocked:b,rows:x}=As(e);if(b.length===0){h({kind:"note",tone:"info",text:"No shots are waiting on app data \u2014 /screenshot list shows where things stand."}),oe("/screenshot list");return}let P=ls(x.filter(j=>j.state==="blocked")).length;h({kind:"note",tone:"info",text:`Re-running ${b.length} shot${b.length===1?"":"s"} that skipped on missing data last run.`+(P>0?` If you haven't staged ${P===1?"it":"those "+P+" things"} yet, ${b.length===1?"it":"they"} will skip again \u2014 /screenshot list has the worklist.`:"")}),await zr(b,{runLine:["/screenshot capture --blocked","/screenshot capture --all --retry-blocked"]});return}if($.mode==="all"||$.mode==="scope"){let b=$.mode==="scope"?$.scope:void 0,{ready:x,captured:P,blocked:j,rows:N}=As(e,b),E=[...x,...P,...$.retryBlocked?j:[]];if(E.length===0&&j.length>0&&!$.retryBlocked){let _=b?`/screenshot capture ${b} --retry-blocked`:"/screenshot capture --blocked";Ne(`All ${j.length} shot${j.length===1?"":"s"} in scope ${j.length===1?"is":"are"} blocked on data that wasn't staged last run \u2014 /screenshot list shows what to stage, then ${_}.`,{kind:"cmd",cmd:"/screenshot list",reason:""},"warn");return}if(E.length===0){h({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),oe("/screenshot");return}if(!$.retryBlocked){let _=b?`/screenshot capture ${b} --retry-blocked`:"/screenshot capture --blocked",F=Zu(N.filter(U=>U.state==="blocked"),_);F&&h({kind:"note",tone:"info",text:F})}let K=$.mode==="scope"?[`/screenshot capture ${$.scope}`,`/capture ${$.scope}`]:["/screenshot capture --all","/capture --all"];await zr(E,{runLine:K,...$.retryBlocked?{}:{heldBackBlocked:N.filter(_=>_.state==="blocked")}});return}let R=Zg(_e(e));if(R.length===0){h({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),oe("/screenshot");return}qn({cursor:0,rows:R,title:"Capture screenshots \u2014 pick what to shoot:"})},W=async y=>{let $=id(y);if(!ho(e)){h({kind:"note",tone:"info",text:"Screenshot capture is not set up in this repo yet. Run /screenshot capture and it will walk you through it."}),oe("/screenshot capture");return}let R=dt();if(!Ca(R)){h({kind:"note",tone:"info",text:ld(R)}),oe("/update");return}let b=$.mode==="scope"?$.scope:void 0,{pending:x,done:P,rows:j}=ad(e,b),N=$.mode==="all"||$.mode==="scope"?$.force:!1,E=$.mode==="single"?[$.id]:N?[...x,...P]:x;if(E.length===0){h({kind:"note",tone:"info",text:P.length>0?`Every shot${b?` under ${b}`:""} is already drawn on. To re-draw them anyway (after a wording or style change): /screenshot annotate --all --force`:"No shots have been taken yet \u2014 /screenshot capture takes them first."}),oe(P.length>0?"/screenshot annotate --all --force":"/screenshot capture");return}await ci(E,{force:N,scope:b,verifiedBefore:new Set(j.filter(K=>K.state==="verified").map(K=>K.id))})},G=async()=>{let y=await gr(m,{cwd:e,profileName:s});y.kind==="forward-to-agent"&&y.prompt&&await Se(y.prompt,{display:y.display,quietUser:!0}),Sl()};switch(c){case"help":Xn({tab:0,scroll:0});return;case"exit":case"quit":Nt.current?.close(),r();return;case"clear":Ze(),Po.current=[],rt.current={printed:[],armed:[],printedAt:_o.current},tt(!1),_t(),console.log("\x1B[?2026h\x1B[H\x1B[2J\x1B[3J\x1B[?2026l"),h({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let y;try{y=mt(e,s)}catch($){h({kind:"note",tone:"error",text:$.message});return}h({kind:"note",tone:"info",text:`Profile "${y.name}" \u2192 ${y.connection.name} (${y.connection.apiUrl})${y.production?" \u26A0 PRODUCTION":""}`}),L(!0);try{let $=await jN(y.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},x=>h({kind:"note",tone:"info",text:x})),R=IN(y.name,$);LN(R),await Vl(R,y.name,x=>h({kind:"note",tone:"info",text:x}));let b=Fb(R);if(b){let x=mt(e,s).project;await ql(y.name,b,x.projectId===b?x.projectName:void 0)}if(h({kind:"note",tone:"ok",text:`\u2713 Logged in to "${y.name}" as ${wi(Un(y.name,b??void 0)??R)}`}),await dh(s),!Oo.current){let x=qe(e,s);x.ok||(h({kind:"note",tone:"warn",text:x.reason}),oe("/login"))}if(Oo.current){let x=Oo.current;Oo.current=null;let P=qe(e,s);P.ok?(h({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 tab to run ${x}.`}),oe(x)):(h({kind:"note",tone:"warn",text:`${P.reason} (then ${x}.)`}),oe("/login"),Oo.current=x)}else Fr.current&&(Je(Fr.current,"\u21E5 tab to re-send your last prompt\u2026"),Fr.current=null)}catch($){h({kind:"note",tone:"error",text:`Login failed: ${$.message}`})}finally{L(!1),M($=>$+1)}return}case"allow-prod":{let y=!1;try{y=mt(e,s).production}catch{}if(!y){h({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}gn.current=!0,Ze(),h({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let y=qu(m.join(" ")),$=Jt.current.uuid;if(!$){if(!y){h({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}bl.current=y,Bn(y),xr(`${al} ${y}`),h({kind:"note",tone:"ok",text:`Session will be named "${y}" once it starts.`});return}if(!y){h({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let R=Jt.current.firstPrompt??"";Ub(R,e).then(b=>{b?(Je(`/rename ${b}`),h({kind:"note",tone:"info",text:`Suggestion: "${b}" \u2014 press tab to accept, or type /rename <your name>.`})):h({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>h({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}KN($,y),Bn(y),xr(`${al} ${y}`),h({kind:"note",tone:"ok",text:`Session renamed to "${y}".`});return}case"profile":{let y=m[0],$=Re(e);if(!y){let R=Object.entries($?.profiles??{});if(R.length===0){h({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let b=R.map(([j,N])=>({name:j,env:N.connection?.environment??"custom",prod:N.production===!0,who:_l(j)})),x=s??$?.defaultProfile,P=Math.max(0,b.findIndex(j=>j.name===x));To({cursor:P,current:P,rows:b});return}if(y==="add"){let R=Vu(e,m[1],m[2]);if(R){h({kind:"note",tone:"error",text:R});return}h({kind:"note",tone:"ok",text:`\u2713 Profile "${m[1]}" created (environment: ${m[2]??m[1]}).`}),Ml(m[1],!0);return}if(!$?.profiles?.[y]){h({kind:"note",tone:"error",text:`Unknown profile "${y}". Create it: /profile add ${y} <environment>`});return}Ml(y,!0);return}case"doctor":await Rs(m,{cwd:e,version:o});return;case"logs":{let y=Yl();h({kind:"note",tone:"info",text:y.lines.join(`
509
- `)}),y.copyText&&on(y.copyText,{hint:y.notable?"\u2328 Press c to copy this problem report \u2014 then send it to the team (Teams / Slack / email).":"\u2328 Press c to copy this entry, if you want to send it to the team."});return}case"style-guide":{let y=Ud(e),$=await Ua(m,{cwd:e,profileName:s});if(y&&Fa(m).sub==="show"&&Ne(null,{kind:"cmd",cmd:"/style-guide keep",reason:""}),$.kind==="clear")Ze(),h({kind:"note",tone:"ok",text:"\u2713 Agent restarted \u2014 it now writes to the new rules."});else if($.kind==="forward-to-agent"){let R=Fa(m).sub==="learn";(await Se($.prompt,{display:$.display,quietUser:!0})).producedNothing||(h({kind:"note",tone:"info",text:(R?Hw():Gw()).join(`
510
- `)}),R&&(Ze(),h({kind:"note",tone:"ok",text:"\u2713 Agent restarted \u2014 it now writes to your house rules."})))}M(R=>R+1);return}case"genre":{let y=Re(e)?.appType??null;(await Ha(m,{cwd:e})).kind==="clear"&&(Re(e)?.appType??null)!==y&&(Ze(),h({kind:"note",tone:"ok",text:"\u2713 Agent restarted \u2014 the doc-craft playbook for this genre is now loaded."}));try{Ye.current=!(Re(e)?.appType??Hb(e))}catch{}M(R=>R+1);return}case"roadmap":{if(m[0]?.toLowerCase()==="done"){let y=or(e,m.slice(1).join(" ").trim());h({kind:"note",tone:y.ok?"ok":"warn",text:y.line}),M($=>$+1);return}h({kind:"block",text:Ic(e,{width:Ge(),all:m.some(y=>y.toLowerCase()==="--all")}).join(`
511
- `)});return}case"mcp":await Ni(m);return;case"init":{if(Re(e)){let $=kn(e,s);h({kind:"note",tone:"info",text:["This repo is already set up \u2014 /init won\u2019t overwrite it.",` Change environment: /profile add <${Kb().join("|")}> then /profile <name> (the environment lives on the profile, not the login).`," Anything else: edit .d360-writer/config.json, or run d360-writer init for the CLI wizard."].join(`
512
- `)}),$&&h({kind:"note",tone:"warn",text:`\u26A0 ${$.why} \u2014 ${$.cmd} moves this repo.`});return}let y=[...Kb(),...iD().filter($=>zb($))].map($=>({name:$,apiUrl:aD($).apiUrl,note:zb($)?"being retired":null}));Ao({cursor:0,rows:y});return}case"resume":{let y=m.join(" ").trim(),$=YN(e).filter(x=>x.uuid!==Jt.current.uuid);if(!y){if(!$.length){h({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}zn({query:"",cursor:0,sessions:$});return}let R=VN(e,y);if(!R){h({kind:"note",tone:"error",text:`No session matches "${y}".`});return}Ze(R.uuid),Jt.current={uuid:R.uuid,firstPrompt:R.firstPrompt,titleFired:!0},Bn(R.name),Rp(R.uuid),Po.current=[],rt.current={printed:[],armed:[],printedAt:_o.current};let b=mp(e,R.uuid);for(let x of b)h(x);h({kind:"note",tone:"ok",text:b.length?`Resumed "${R.name}" \u2014 restored ${b.length} message(s); continue where you left off.`:`Resumed "${R.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let y=m.join(" ").trim(),$;try{$=await es(e,s)}catch(b){h({kind:"note",tone:"error",text:`Could not list workspaces: ${b.message}`});return}if(!y){let b=$.workspaces.map(P=>({id:P.id,name:P.name??P.id,type:P.workspace_type}));if(b.length===0){h({kind:"note",tone:"info",text:"No workspaces in this project."});return}let x=Math.max(0,b.findIndex(P=>P.id===$.current));Eo({cursor:x,current:x,rows:b,profile:$.profile,projectId:$.projectId,projectName:$.projectName,environment:$.environment});return}let R=Bl($.workspaces,y);if(!R){h({kind:"note",tone:"error",text:`No workspace matches "${y}".`});return}ui($.profile,$.projectId,R);return}case"project":{let y=m.join(" ").trim(),$;try{$=await sn(e,s)}catch(b){h({kind:"note",tone:"error",text:`Could not list projects: ${b.message} (signed in? try /login)`});return}if(!y){let b=$.projects.map(P=>({id:P.id,name:P.name??P.id,sub:P.sub_domain}));if(b.length===0){h({kind:"note",tone:"info",text:"No projects found for this identity."});return}let x=b.findIndex(P=>P.id===$.current);Gn({cursor:Math.max(0,x),current:x,rows:b,profile:$.profile,environment:$.environment});return}let R=Hl($.projects,y);if(!R){h({kind:"note",tone:"error",text:`No project matches "${y}". Available: ${$.projects.map(b=>b.name??b.id).join(", ")}`});return}pi($.profile,R);return}case"logout":{let y,$,R;try{let N=mt(e,s);y=N.name,$=N.project.projectId,R=N.project.projectName}catch(N){h({kind:"note",tone:"error",text:N.message});return}let b=m.includes("--all-projects"),x=WN(y).filter(N=>{let E=Fb(N);return!!E&&E!==$}).length,P=FN(y,b?void 0:$);BN(e,y),Ze(),M(N=>N+1);let j=b||x===0?"":` Your sign-in for ${x} other project${x===1?"":"s"} is untouched (/logout --all-projects clears those too).`;h({kind:"note",tone:P?"ok":"info",text:P?b?`\u2713 Signed out of every Document360 project for "${y}" and cleared this repo's project/workspace selection.`:`\u2713 Signed out of ${R?`"${R}"`:`"${y}"`} and cleared its project/workspace selection.${j}`:`Profile "${y}" was not signed in. Cleared any project/workspace selection.${j}`}),h({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),oe("/login");return}case"publish":{if(Hc(m)){let P=cn("publish");P&&h({kind:"note",tone:"info",text:P}),await Ho(`/push ${m.join(" ")}`.trim());return}if(!Zn(u.trim()))return;let y=cn("publish");y&&h({kind:"note",tone:"info",text:y});let $=m.find(P=>!P.startsWith("--")),R={skipReview:m.includes(xt),skipStyle:m.includes(ok)};We("Checking what is waiting to go live\u2026");let b;try{b=await Gc(e,s,$)}catch(P){h({kind:"note",tone:"error",text:`Could not check Document360: ${P.message}`});return}finally{We(null)}if(b.length===0){let P=qc(e,s,$);for(let j of P.lines)h({kind:"note",tone:j.startsWith("\u2713")?"ok":"info",text:j});P.ahead>0&&oe(Pe("/push","",$));return}let x=Ap(e,b.map(P=>P.path),{allowUnreviewed:R.skipReview,allowStyleErrors:R.skipStyle,checkScreenshots:!0,allowPlaceholders:m.includes(xD)});if(!x.clear){for(let P of Ep(x,b.length,{scope:$,act:"publish"}))h({kind:"note",tone:"warn",text:P});oe(Pe("/review","--blocked --fix",$));return}h({kind:"note",tone:"info",text:`${b.length} draft${b.length===1?" is":"s are"} ahead of what readers see. Pick what goes live:`}),Do({cursor:0,rows:b,opts:R});return}case"push":{if(!Zn(u.trim()))return;let y=m.includes(xt),$=m.includes(ok);if(m.includes("--preview")){let P=m.find(j=>!j.startsWith("--"));if(!P){h({kind:"note",tone:"error",text:"Which article? Use /push --preview <path> \u2014 a preview is per article."});return}try{let j=await tD({cwd:e,profileName:s,relPath:P.replace(/\\/g,"/"),preview:!0}),N=j.shots.length>0?` \xB7 ${j.shots.length} screenshot${j.shots.length===1?"":"s"} embedded`:"";h({kind:"note",tone:"info",text:`${j.title}
513
- ${j.path} \xB7 ${j.articleId?`updates article ${j.articleId}`:"would be created as a new article"}${N}`}),j.missingShots.length>0&&h({kind:"note",tone:"warn",text:`\u26A0 ${j.missingShots.length} screenshot${j.missingShots.length===1?"":"s"} not taken yet \u2014 the description publishes instead: ${j.missingShots.join(", ")}`}),h({kind:"note",tone:"info",text:j.body}),h({kind:"note",tone:"info",text:`Nothing was sent. /push ${j.path} saves it as a draft.`}),oe(`/push ${j.path}`)}catch(j){h({kind:"note",tone:"error",text:j.message})}return}if(m.includes("--screenshots")||m.includes("--shots")){let P=m.find(_=>!_.startsWith("--")),j=_e(e),N=Bi(j,P);if(N.length===0){let _=j.filter(F=>F.state==="captured").length;h({kind:"note",tone:"info",text:_>0?`${_} screenshot${_===1?" has":"s have"} been taken but the callouts aren't drawn on yet, so there is nothing to embed \u2014 /screenshot annotate finishes ${_===1?"it":"them"}.`:P?`No captured screenshots in ${P} \u2014 /push --screenshots covers the whole knowledge base.`:"No captured screenshots yet \u2014 /screenshot capture first."}),_>0&&oe("/screenshot annotate");return}let E=Hi(j,P);E&&h({kind:"note",tone:"warn",text:E});let K=Gi(j);K&&h({kind:"note",tone:"warn",text:K}),h({kind:"note",tone:"info",text:`Re-saving ${N.length} article${N.length===1?"":"s"} with captured screenshots so the images embed\u2026`}),await ct(N,0,{skipReview:y,skipStyle:$,scope:Pe("","--screenshots",P).trim()});return}if(m[0]==="--related"&&m[1]){let P=await ta(e,s,m[1].replace(/\\/g,"/"));if(P.length===0){h({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await ct(P,0,{skipReview:y,skipStyle:$,scope:`--related ${m[1]}`});return}let R=m.filter(P=>!P.startsWith("--"));if(R[0]){await Ol(R[0],{skipReview:y,skipStyle:$});return}let b=m.includes("--all"),x=m.includes("--force");h({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let P=await ml({cwd:e,profileName:s}),{clean:j,conflicts:N}=lo(P.entries),E=b&&x&&N.length>0,K=Ji(P.entries);if(K>0&&h({kind:"note",tone:"warn",text:`\u26A0 ${K} article${K===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.`}),N.length>0&&!E&&h({kind:"note",tone:"warn",text:us(N.length)}),j.length===0&&!E){let _=rr(e,s);if(_&&h({kind:"note",tone:"info",text:_}),N.length>0){oe("/resolve");return}h({kind:"note",tone:"ok",text:K>0?"\u2713 Nothing else is ahead of Document360 to save.":"\u2713 Nothing is ahead of Document360 \u2014 nothing to save."});let F=P.counts["unknown-base"]??0;F>0&&h({kind:"note",tone:"info",text:`(${F} article(s) have no sync base yet \u2014 /push <path> saves one anyway if you need it.)`}),We("Reconciling structure on Document360 (order + related articles)\u2026");try{let U=await Pp({cwd:e,profileName:s,onRateLimit:De=>We(`Document360 rate limit \u2014 waiting ${Math.ceil(De.waitMs/1e3)}s\u2026`)}),ie=nk(await tk({cwd:e,profileName:s})),ne=Tp(U);ne?h({kind:"note",tone:ne.startsWith("\u26A0")?"warn":"info",text:ne}):U.skipped&&h({kind:"note",tone:"warn",text:`Order sync skipped: ${U.skipped}`}),ie&&h({kind:"note",tone:"info",text:ie}),U.failures?.length?oe("/structure"):(h({kind:"note",tone:"ok",text:ne||ie?"\u2713 Structure synced to Document360 \u2014 /structure shows the new category + article order.":"\u2713 Already in order \u2014 nothing to change."}),(ne||ie)&&oe("/structure"))}catch(U){h({kind:"note",tone:"warn",text:`Structure sync failed: ${U.message}`})}finally{We(null)}return}if(b){let _=(E?[...j,...N]:j).map(F=>F.path);await ct(_,E?0:N.length,{skipReview:y,skipStyle:$,allowUnpullable:E});return}No({cursor:0,rows:Pm(j,N),conflicts:N.length})}catch(P){h({kind:"note",tone:"error",text:`Could not compute sync status: ${P.message}`}),h({kind:"note",tone:"info",text:"Save one article on its own: /push <article-path>"})}return}case"resolve":{if(!Zn(u.trim()))return;await Ul(m.find(y=>!y.startsWith("--")));return}case"preview":{let y=m.join(" ").trim();if(!y){let R=[];try{R=Object.keys(Gb(e,mt(e,s).name)?.articles??{})}catch{}if(R.length===0){h({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}Yn({query:"",cursor:0,paths:R});return}let $=NN(y)?y:xp(e,y);if(Cr($)){try{h({kind:"preview",name:Ys($),text:lk(hl($,"utf8"))})}catch(R){h({kind:"note",tone:"error",text:`Could not read ${$}: ${R.message}`})}return}if(UD.test(y)){try{let R=mt(e,s),b={profile:R.name,connection:R.connection},x=R.project.projectId??_N(b),P=await MN(b,x,y);h({kind:"preview",name:P.title??y,text:P.content??"*(article has no content)*"})}catch(R){h({kind:"note",tone:"error",text:`Could not fetch article: ${R.message}`})}return}h({kind:"note",tone:"error",text:`"${y}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let y=m[0]?.trim();if(!y){let x=$a(Dp(e));Hn({cursor:x,current:x});return}let{lines:$,changed:R,effective:b}=xs(e,y);for(let x of $)h({kind:"note",tone:x.startsWith("\u26A0")?"warn":x.startsWith("\u2713")?"ok":"info",text:x});R&&(zp(x=>x+1),Nt.current?.setModel(b));return}case"verbose":{let y=m[0]?.trim().toLowerCase(),$=y==="on"?!0:y==="off"?!1:!Qs.current;Qs.current=$;try{XN({...Bb(),verboseTranscript:$})}catch{h({kind:"note",tone:"warn",text:"\u26A0 Applied for this session, but the setting could not be saved."})}h({kind:"note",tone:"ok",text:$?"\u2713 Verbose transcript ON \u2014 every tool call with its file path and full result.":"\u2713 Verbose transcript OFF \u2014 doc work shown by article; my bookkeeping collapsed to one line."});return}case"convert":{if(!Re(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:y,run:$}=du(m),R=uD(e,s);if(R.length===0){h({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Save some to Document360 first (/push), then /convert."});return}let b=pu(R,y);if(b.length===0){h({kind:"note",tone:"error",text:`No tracked articles under "${y}". (${R.length} are tracked overall.)`});return}let x=Cp(b),P=3,j=`/convert${y?` --scope ${y}`:""} --run`,N=zs(e,"light");if(!$){let _=Xb({files:hu(e,b),op:"convert",model:N.model}),F=y?`Scope: ${y} (${b.length} of ${R.length} tracked)
514
- `:"",U=`
515
- Model: ${N.model}${N.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;h({kind:"note",tone:"info",text:F+mu(x,_,P).join(`
516
- `)+U}),oe(j);return}Et.current=Date.now(),Ue(0),T(!0);let E=new AbortController;Le.current=E;let K=Date.now();he({verb:"Converting",total:x.length,done:0,active:[],rows:bo(x),tools:0,chars:0,lastAt:Date.now(),startedAt:K}),h({kind:"note",tone:"info",text:`Converting ${b.length} articles in ${x.length} batches (\u2264${P} agents at once) on ${N.model}\u2026 (esc to stop)`});try{for await(let _ of Ks({cwd:e,partitions:x,promptFor:fu,concurrency:P,profileName:s,allowProdWrites:gn.current,model:N.model,signal:E.signal}))if(_.type==="partition_status")_.status==="running"?he(F=>F&&{...F,active:[...F.active,_.label],rows:Ve(F.rows,_.label,"active"),lastAt:Date.now()}):he(F=>F&&{...F,active:F.active.filter(U=>U!==_.label),done:F.done+1,rows:Ve(F.rows,_.label,_.status==="done"?"done":"failed"),lastAt:Date.now()});else if(_.type==="partition_stalled"){let F=vr(_);he(U=>U&&F?{...U,stalledNote:F}:U)}else if(_.type==="partition_event")he(F=>{if(!F)return F;let U={...F,lastAt:Date.now()};return _.event.type==="tool"?U.tools=F.tools+1:_.event.type==="text"&&(U.chars=F.chars+_.event.delta.length),U});else if(_.type==="run_done"){Jn(ne=>ne+_.totalCostUsd),Qn(ne=>ne+_.results.reduce((De,pe)=>De+pe.outputTokens,0));let F=_.aborted?"Stopped. ":"",U=t.kind==="api"?"api":"subscription",ie=Tn(_,"The conversion");h({kind:"note",tone:ie||_.aborted?"warn":_.ok?"ok":"warn",text:ie?ie.join(`
517
- `):F+gu(_.results,x,U).join(`
518
- `)}),Wo(K,_.results,_.totalCostUsd,!ie&&!_.aborted&&_.ok),ie&&oe("/doctor")}}catch(_){h({kind:"note",tone:"error",text:`Convert run failed: ${_.message}`})}finally{Le.current=null,he(null),T(!1),M(_=>_+1)}return}case"write":{if(!Re(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let y=Qb(e);if(y.length===0){h({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:$,path:R,preview:b,concurrency:x,rewrite:P}=vs(m);if(!R&&!b&&!(Re(e)?.appType??Hb(e))){h({kind:"note",tone:"warn",text:`\u26A0 No doc genre is set, so no doc-craft playbook would load \u2014 all ${y.length} articles would be written generically.
500
+ ${b.length===1?"It has":"They have"} no publishable picture yet. Re-take the shot: /screenshot capture`})}if(p.chainVerify===!1||W.length===0)return{drawn:W,undrawn:b,cliMissing:!1};let k=W.filter(v=>p.verifiedBefore.has(v)).length;if(k>Pa){let v=gw({results:g,voidedVerdicts:k,...p.scope?{scope:p.scope}:{}});return v&&Ee(`${v.glyph} ${v.cmd} ${v.why}`,{kind:"cmd",cmd:v.cmd,reason:""},"warn"),{drawn:W,undrawn:b,cliMissing:!1}}let x=W.filter(v=>!p.verifiedBefore.has(v)||k>0);if(x.length===0)return{drawn:W,undrawn:b,cliMissing:!1};h({kind:"note",tone:"info",text:In(x.length)}),await Te(Qt(e,x),{display:"/screenshot verify",quietUser:!0});let y=mr(e,x);return y.length>0&&h({kind:"note",tone:"info",text:y.join(`
501
+ `)}),{drawn:W,undrawn:b,cliMissing:!1}},[e,h,Ee,Te]),Xr=ne(async(u,p)=>{if(!fo(e)){await Te(cd(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(!iw(e)){h({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)"}),A(!0),We("Waiting for you to finish logging in (browser window)\u2026");let F=new AbortController;Oe.current=F;let G;try{G=await aw({cwd:e,signal:F.signal})}catch(ee){h({kind:"note",tone:"error",text:`Could not launch the login: ${ee.message}`});return}finally{Oe.current=null,We(null),A(!1)}if(G.exitCode!==0){ld(G.exitCode,G.output)?h({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(G.output)?h({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."}):h({kind:"note",tone:F.signal.aborted?"warn":"error",text:F.signal.aborted?"Login cancelled \u2014 nothing saved.":`Login did not complete:
502
+ ${id(G.output)}`});return}h({kind:"note",tone:"ok",text:"\u2713 Login saved \u2014 continuing with the capture."})}let c=new Map(u.map(F=>[F,Jf(e,F)])),g=0;if(u.length>1){let F=u.filter(G=>c.get(G).mutates);if(F.length>0&&(g=F.length,u=u.filter(G=>!c.get(G).mutates),u.length===0)){h({kind:"note",tone:"warn",text:`\u26A0 All ${F.length} spec${F.length===1?"":"s"} in scope write real data, so a bulk run has nothing to do. Run one deliberately: /screenshot capture ${F[0]}`});return}}else if(u.length===1&&c.get(u[0]).mutates){let F=c.get(u[0]),G=lw(e);h({kind:"note",tone:"warn",text:`\u26A0 This capture performs a REAL write in your app${F.what?`: ${Qf(F.what)}`:F.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. `+(G.production?`This profile is PRODUCTION \u2014 the write lands in the LIVE tenant${G.url?` (${G.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.")})}A(!0);let T=new AbortController;Oe.current=T;let W=u.map(F=>({label:F,items:1,status:"pending"}));pe({verb:"Capturing",unit:"screenshot",total:u.length,done:0,active:[],rows:W,tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()});let B=ln(e),b=Object.keys(B.shots).length>0,k=cw(p?.heldBackBlocked??[],g);h({kind:"note",tone:"info",text:`Capturing ${u.length} screenshot${u.length===1?"":"s"} with d360-capture (a real browser drives your app)\u2026 (esc to stop)`+(k?`
503
+ ${k}`:"")});let x=Date.now(),y=[];try{for(let F of u){if(T.signal.aborted)break;pe(me=>me&&{...me,active:[F],rows:Ve(me.rows,F,"active"),lastAt:Date.now()});let{exitCode:G,output:ee}=await ad({cwd:e,id:F,signal:T.signal,stdio:"pipe"});if(ld(G,ee)){h({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 ce=T.signal.aborted&&G!==0?"failed":sd(e,F,G,x),he=ce==="captured"?void 0:ce==="skipped"?rw(ee)??"a data prerequisite isn't met \u2014 the spec's skip reason names what to stage":sw(ee);y.push({id:F,outcome:ce,detail:he}),pe(me=>me&&{...me,active:[],done:me.done+1,rows:Ve(me.rows,F,ce==="captured"?"done":"failed"),lastAt:Date.now()})}}catch(F){h({kind:"note",tone:"error",text:`Capture run failed: ${F.message}`})}finally{Oe.current=null,pe(null),A(!1),O(F=>F+1)}if(y.length===0)return;let v=y.filter(F=>F.outcome==="captured"),P=y.filter(F=>F.outcome==="skipped"),j=y.filter(F=>F.outcome==="failed"),I=u.length-y.length;h({kind:"note",tone:j.length?"warn":v.length?"ok":"info",text:[`\u2713 ${v.length} captured`,P.length?`\u2298 ${P.length} blocked`:"",j.length?`\u2717 ${j.length} broken`:"",I?`${I} not run (stopped)`:""].filter(Boolean).join(" ")+` ${y.length} run${g>0?` \xB7 ${g} held back`:""}`+pw(uw(B,y),b).map(F=>`
504
+ ${F}`).join("")});let E=dw(P);if(E.length>0&&h({kind:"note",tone:"info",text:E.join(`
505
+ `)}),j.length>0){let F=Math.max(...j.map(G=>G.id.length));h({kind:"note",tone:"error",text:j.map(G=>`\u2717 ${G.id.padEnd(F)} ${As(G.detail)}`).join(`
506
+ `)})}Oi(e,y.map(F=>({id:F.id,outcome:F.outcome,reason:F.detail,specSource:ao(e,F.id)})),new Date().toISOString()),y.length===u.length&&j.length===0&&P.length===0&&yn(p?.runLine);let Y=[];if(v.length>0&&Sa()){let F=await ci(v.map(G=>G.id),{verifiedBefore:new Set});if(F.cliMissing||(Y=F.undrawn,F.drawn.length>0))return}else if(v.length>0){h({kind:"note",tone:"info",text:In(v.length)}),await Te(Qt(e,v.map(G=>G.id)),{display:"/screenshot verify",quietUser:!0});let F=mr(e,v.map(G=>G.id));F.length>0&&h({kind:"note",tone:"info",text:F.join(`
507
+ `)});return}let M=hw({results:y,ids:u,articles:fw(e,v.map(F=>F.id)),...Y.length>0?{unannotated:Y}:{}});M&&Ee(M.note,{kind:"cmd",cmd:M.cmd,reason:""},M.tone)},[e,h,Ee,Te,yn,ci]),Fl=ne(u=>{let p=Un(u);if(!p||vo(p)&&!p.refreshToken)return null;let c={...Nr(p.idToken)??{},...Nr(p.accessToken)??{}};return c.email??c.preferred_username??"signed in"},[]),Ul=ne((u,p)=>{if(p){let c=Se(e);c&&(c.defaultProfile=u,Yb(c,e))}i(u),Ze(void 0,u),h({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${u}"${p?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),Fl(u)||(h({kind:"note",tone:"warn",text:`Profile "${u}" is not signed in \u2014 sign in with /login.`}),oe("/login")),O(c=>c+1)},[e,h,Ze,Fl,oe]),ui=ne((u,p,c)=>{fi(e,u,p,c.id,c.name),h({kind:"note",tone:"ok",text:`Switched to workspace "${c.name??c.id}" (agent restarted).`}),Ze(),Xb(e,u)||(h({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),h({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:"}),h({kind:"note",tone:"info",text:Jo(Qo(e)).join(`
508
+ `)}),on(so()),Kr.current=Ut(e).status==="current",Uo.current=an(e),h({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,h,Ze,on]),di=ne(async u=>{let p;try{p=await ts(e,u)}catch{h({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),oe("/workspace");return}if(p.workspaces.length===0){h({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let c=p.workspaces.filter(T=>(T.workspace_type??"").toLowerCase()!=="apidocumentation"),g=c.length>0?c:p.workspaces;if(g.length===1){let T=g[0],W=p.workspaces.length-g.length;h({kind:"note",tone:"ok",text:`Selected the "${T.name??T.id}" workspace${W>0?" (skipped the API-documentation workspace)":""}.`}),ui(p.profile,p.projectId,T);return}h({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${g.length} available).`}),oe("/workspace")},[e,h,ui,oe]),pi=ne((u,p)=>{mi(e,u,p.id,p.name),h({kind:"note",tone:"ok",text:`Project set to "${p.name??p.id}" (agent restarted).`}),Ze(),di(u)},[e,h,Ze,di]),gh=ne(async u=>{let p;try{p=mt(e,u)}catch{return}if(!p.project.workspaceId){if(p.project.projectId){if(!p.project.projectName)try{let{projects:c}=await sn(e,p.name),g=c.find(T=>T.id===p.project.projectId);g?.name&&AD(e,p.name,{projectName:g.name})}catch{}await di(p.name);return}try{let{projects:c}=await sn(e,p.name);if(c.length===1){let g=c[0];h({kind:"note",tone:"ok",text:`Using your Document360 project "${g.name??g.id}".`}),pi(p.name,{id:g.id,name:g.name});return}if(c.length>1){let g=c.map(T=>({id:T.id,name:T.name??T.id,sub:T.sub_domain}));h({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),Gn({cursor:0,current:-1,rows:g,profile:p.name,environment:p.connection.name});return}}catch{}h({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),oe("/project")}},[e,h,di,pi,oe]),Ho=ne(()=>{let u=De.current[0];if(!u)return;if(_t(),u.mode==="local-only"){h({kind:"note",tone:"info",text:`\u25CF ${u.title??u.path} (${u.path})`});for(let W of aa())h({kind:"note",tone:"warn",text:`\u26A0 ${W}`});h({kind:"note",tone:"info",text:la()}),h({kind:"note",tone:"info",text:Hm()});return}let{plan:p,mode:c}=u;h({kind:"note",tone:"info",text:`\u25CF ${p.title} (${p.path})`});for(let W of p.notes)h({kind:"note",tone:"warn",text:`\u26A0 ${W}`});p.overwritesLocalChanges&&c==="pull"&&h({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let g=Rt(p.oldContent,p.newContent,qe(),ar);h(g?{kind:"diff",added:g.added,removed:g.removed,lines:g.lines,hidden:g.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."});let T=De.current.length;c==="conflict"?(h({kind:"note",tone:"warn",text:"Conflict \u2014 edited both here and on the portal (diff shows local \u2192 portal)."}),h({kind:"note",tone:"info",text:"Keep local (publish, overwrites portal) \xB7 take Portal (overwrites local) \xB7 Skip?"}),h({kind:"note",tone:"info",text:T>1?`(l/p/s \xB7 la/pa/sa for all ${T} \u2014 anything else stops, keeping your answers so far)`:"(l/p/s \u2014 anything else stops, keeping your answers so far)"})):h({kind:"note",tone:"info",text:T>1?`Write ${p.path}? (y/n \xB7 ya/na for all ${T} \u2014 anything else cancels)`:`Write ${p.path}? (y/n \u2014 anything else cancels)`})},[h,qe,_t]),no=ne(()=>{if(De.current.length>0){Ho();return}let u=Dt.current;Dt.current=[];let p=Zt.current;Zt.current=[];for(let c of ca(p))h({kind:"note",tone:"warn",text:`\u26A0 ${c}`});u.length>0?(h({kind:"note",tone:"info",text:`Saving ${u.length} kept-local article${u.length===1?"":"s"} over the portal\u2026`}),ct(u,0,{allowUnpullable:!0})):p.length>0||oe("/pull")},[Ho,h,ct,oe]),Wl=ne(u=>{let p=rl(u);if(!p)return!1;let c=De.current.splice(0),g=c.length;if(p==="local"){for(let T of c)Dt.current.push(YD(T));h({kind:"note",tone:"info",text:`Keeping local for all ${g} \u2014 will publish ${g===1?"it":"them"} over the portal.`})}else if(p==="portal"){let T=0;for(let W of c){if(W.mode==="local-only"){h({kind:"note",tone:"warn",text:`\u26A0 ${nu(W.path)}`}),Zt.current.push(W.path);continue}try{ml({cwd:e,profileName:s},W.plan),T++}catch(B){h({kind:"note",tone:"error",text:`Take-portal failed for ${W.plan.path}: ${B.message}`})}}h({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${T} article${T===1?"":"s"} (local overwritten, sync base advanced).`})}else{for(let T of c)T.mode==="local-only"&&Zt.current.push(T.path);h({kind:"note",tone:"info",text:`Skipped all ${g} \u2014 still conflict${g===1?"":"s"}.`})}return no(),!0},[e,s,no,h]),wh=ne(u=>{if(De.current.length===0)return!1;let p=u.trim(),c=p.toLowerCase(),g=De.current[0];if(g.mode==="local-only"){if(rl(p))return Wl(p);if(c==="l"||c==="local"||c==="publish")De.current.shift(),Dt.current.push(g.path),h({kind:"note",tone:"info",text:`Publishing your copy of ${g.path} over the portal.`});else if(c==="s"||c==="skip")De.current.shift(),Zt.current.push(g.path),h({kind:"note",tone:"info",text:`Skipped ${g.path} \u2014 still a conflict.`});else{let W=De.current.splice(0),B=Dt.current;return Dt.current=[],Zt.current=[],h({kind:"note",tone:"info",text:`Resolve cancelled. ${W.length} conflict${W.length===1?"":"s"} left untouched.`+(B.length>0?` Saving the ${B.length} article${B.length===1?"":"s"} you already chose to keep - an answer you gave is not undone by stopping.`:"")}),B.length>0&&ct(B,0,{allowUnpullable:!0}),!0}return no(),!0}if(g.mode==="conflict"){if(rl(p))return Wl(p);if(c==="l"||c==="local")De.current.shift(),Dt.current.push(g.plan.path),h({kind:"note",tone:"info",text:`Keeping local ${g.plan.path} \u2014 will publish over the portal.`});else if(c==="p"||c==="portal"){De.current.shift();try{ml({cwd:e,profileName:s},g.plan),h({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${g.plan.path} (local overwritten, sync base advanced).`})}catch(W){h({kind:"note",tone:"error",text:`Take-portal failed: ${W.message}`})}}else if(c==="s"||c==="skip"||c==="n")De.current.shift(),h({kind:"note",tone:"info",text:`Skipped ${g.plan.path} \u2014 still a conflict.`});else{let W=De.current.length;De.current=[];let B=Dt.current;return Dt.current=[],Zt.current=[],h({kind:"note",tone:"info",text:`Resolve cancelled. ${W} conflict${W===1?"":"s"} left untouched.`+(B.length>0?` Saving the ${B.length} article${B.length===1?"":"s"} you already chose to keep - an answer you gave is not undone by stopping.`:"")}),B.length>0&&ct(B,0,{allowUnpullable:!0}),!0}return no(),!0}let T=cb(p);if(T){let W=De.current.splice(0);if(T==="skip")h({kind:"note",tone:"info",text:`Skipped all ${W.length} article${W.length===1?"":"s"}.`});else{let B=0;for(let b of W){if(b.mode==="local-only"){h({kind:"note",tone:"warn",text:`\u26A0 ${nu(b.path)}`});continue}try{ml({cwd:e,profileName:s},b.plan),B++}catch(k){h({kind:"note",tone:"error",text:`Pull failed for ${b.plan.path}: ${k.message}`})}}h({kind:"note",tone:"ok",text:`\u2713 Pulled ${B} article${B===1?"":"s"} (sync base advanced).`})}return no(),!0}if(c==="y"||c==="yes"){let{plan:W}=g;De.current.shift();try{ml({cwd:e,profileName:s},W),h({kind:"note",tone:"ok",text:`\u2713 Pulled ${W.path} (sync base advanced).`})}catch(B){h({kind:"note",tone:"error",text:`Pull failed: ${B.message}`})}}else if(c==="n"||c==="no")De.current.shift(),h({kind:"note",tone:"info",text:`Skipped ${g.plan.path}.`});else{let W=De.current.length;return De.current=[],h({kind:"note",tone:"info",text:`Pull cancelled (${W} article(s) left untouched).`}),!0}return no(),!0},[e,s,no,h,Wl]),Bl=ne(async u=>{h({kind:"note",tone:"info",text:"Checking Document360 for conflicts\u2026"});try{let p=await gl({cwd:e,profileName:s}),c=u?.replace(/\\/g,"/"),g=p.entries.filter(B=>B.status==="conflict"&&B.path).map(B=>B.path);if(c){if(!g.includes(c)){h({kind:"note",tone:"ok",text:`${c} isn\u2019t in conflict \u2014 nothing to resolve.`});return}g=[c]}if(g.length===0){h({kind:"note",tone:"ok",text:"\u2713 No conflicts \u2014 local and Document360 agree on every tracked article."});return}let T=[];for(let B of g)try{T.push({plan:await Qb({cwd:e,profileName:s,relPath:B}),mode:"conflict"})}catch(b){Jb(b)?T.push({mode:"local-only",path:B,title:Zb(e,B)}):h({kind:"note",tone:"error",text:`Could not load ${B} from Document360: ${b.message}`})}if(T.length===0)return;let W=T.some(B=>B.mode!=="local-only");h({kind:"note",tone:"info",text:W?`Resolving ${T.length} conflict${T.length===1?"":"s"} \u2014 for each: keep local, take portal, or skip.`:`Resolving ${T.length} conflict${T.length===1?"":"s"} \u2014 for each: publish your copy over the portal, or skip.`}),De.current=T,Dt.current=[],Zt.current=[],Ho()}catch(p){h({kind:"note",tone:"error",text:`Could not compute sync status: ${p.message}`})}},[e,s,h,Ho]),yh=ne(u=>{let p=Or.current;if(!p)return!1;if(Or.current=null,_t(),u.trim()!==p.repoName)return h({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:c,failed:g}=_d(e,p.targets);h({kind:"note",tone:g.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${c.length} item${c.length===1?"":"s"}. The repo is back to its original state.`});for(let T of g)h({kind:"note",tone:"error",text:` \u2717 ${T.path}: ${T.error}`});return p.hadDevhints&&(h({kind:"note",tone:"warn",text:Ti().join(`
509
+ `)}),on(sc())),h({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
510
+ ${uk}`}),oe("/init"),tt(!1),!0},[e,h,on,_t,oe]),Go=ne(async u=>{let p=u.slice(1).trim().split(/\s+/),c=(p[0]??"").toLowerCase(),g=p.slice(1);if(sh.current=u.trim(),tt(!0),vs(g)&&["write","lint","check","review","reorder"].includes(c)){let b=$s(e,s);if(b.length===0){h({kind:"note",tone:"warn",text:"No categories yet \u2014 author some articles first, then scope to one."});return}let k=x=>c==="write"?`/write ${xg(g,x).join(" ")}`.trim():`/${c} ${[x,...g.filter(y=>y!=="--scope")].join(" ")}`.trim();if(b.length===1){Go(k(b[0].token));return}Vn({cursor:0,rows:b,run:x=>{Go(k(x))}});return}if(jn(c,g)){let b=c==="write"&&xs(g).rewrite,k=c==="write"?Bu(e,ok(e),{rewrite:b}):$s(e,s);if(k.length>1){let x=g.filter(G=>G.startsWith("--")).join(" "),y=G=>G==="--blocked"?`/${c} --blocked${x?` ${x}`:""}`.trim():`/${c}${G?` ${c==="write"?`--scope ${G}`:G}`:""}${x?` ${x}`:""} ${G?"":"--all"}`.replace(/\s+/g," ").trim(),v=k.reduce((G,ee)=>G+ee.count,0),P={token:"",label:c==="review"?`Everything \u2014 all ${v} articles + structure (IA) review`:c==="reorder"?`Everything \u2014 reorder all ${k.length} categories`:b?`Everything \u2014 rewrite all ${v} planned articles`:`Everything \u2014 write all ${v} pending article${v===1?"":"s"}`,count:v},j=c==="review"?Kd(e):[],I=j.length>0&&j.length<v?[{token:"--blocked",label:`Only what needs review \u2014 ${j.length} article${j.length===1?"":"s"} publishing is blocked on`,count:j.length}]:[],E=c==="review"?zd(e):[],Y=E.length>j.length&&E.length<v?[{token:"--stale",label:`Everything the current editor hasn\u2019t read \u2014 ${E.length} article${E.length===1?"":"s"}`,count:E.length}]:[],M=c==="write"?`Write which articles? (counts = ${b?"articles to regenerate":"still to write"})`:c==="review"?"Review what? (counts = articles)":"Reorder what?";Vn({cursor:0,rows:(G=>c==="review"||c==="write"?G.map(ee=>{let ce=(()=>{try{return Jw(e,y(ee.token))}catch{return null}})();return ce?{...ee,label:`${ee.label} \xB7 ${ce}`}:ee}):G)([...I,...Y,P,...k]),run:G=>{Go(y(G))},title:M});return}}let T=async b=>{let k=nd(b);if(!fo(e)){await Te(cd(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(k.mode==="single"){await Xr([k.id],{runLine:[`/screenshot capture ${k.id}`,`/capture ${k.id}`]});return}if(k.mode==="failed"){let y=od(e,Es(e).rows);if(y.length===0){h({kind:"note",tone:"info",text:"No broken specs to re-run \u2014 /screenshot list shows where things stand."}),oe("/screenshot list");return}await Xr(y);return}if(k.mode==="blocked"){let{blocked:y,rows:v}=Es(e);if(y.length===0){h({kind:"note",tone:"info",text:"No shots are waiting on app data \u2014 /screenshot list shows where things stand."}),oe("/screenshot list");return}let P=cs(v.filter(j=>j.state==="blocked")).length;h({kind:"note",tone:"info",text:`Re-running ${y.length} shot${y.length===1?"":"s"} that skipped on missing data last run.`+(P>0?` If you haven't staged ${P===1?"it":"those "+P+" things"} yet, ${y.length===1?"it":"they"} will skip again \u2014 /screenshot list has the worklist.`:"")}),await Xr(y,{runLine:["/screenshot capture --blocked","/screenshot capture --all --retry-blocked"]});return}if(k.mode==="all"||k.mode==="scope"){let y=k.mode==="scope"?k.scope:void 0,{ready:v,captured:P,blocked:j,rows:I}=Es(e,y),E=[...v,...P,...k.retryBlocked?j:[]];if(E.length===0&&j.length>0&&!k.retryBlocked){let M=y?`/screenshot capture ${y} --retry-blocked`:"/screenshot capture --blocked";Ee(`All ${j.length} shot${j.length===1?"":"s"} in scope ${j.length===1?"is":"are"} blocked on data that wasn't staged last run \u2014 /screenshot list shows what to stage, then ${M}.`,{kind:"cmd",cmd:"/screenshot list",reason:""},"warn");return}if(E.length===0){h({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),oe("/screenshot");return}if(!k.retryBlocked){let M=y?`/screenshot capture ${y} --retry-blocked`:"/screenshot capture --blocked",F=rd(I.filter(G=>G.state==="blocked"),M);F&&h({kind:"note",tone:"info",text:F})}let Y=k.mode==="scope"?[`/screenshot capture ${k.scope}`,`/capture ${k.scope}`]:["/screenshot capture --all","/capture --all"];await Xr(E,{runLine:Y,...k.retryBlocked?{}:{heldBackBlocked:I.filter(M=>M.state==="blocked")}});return}let x=ow(_e(e));if(x.length===0){h({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),oe("/screenshot");return}qn({cursor:0,rows:x,title:"Capture screenshots \u2014 pick what to shoot:"})},W=async b=>{let k=dd(b);if(!fo(e)){h({kind:"note",tone:"info",text:"Screenshot capture is not set up in this repo yet. Run /screenshot capture and it will walk you through it."}),oe("/screenshot capture");return}let x=dt();if(!Sa(x)){h({kind:"note",tone:"info",text:hd(x)}),oe("/update");return}let y=k.mode==="scope"?k.scope:void 0,{pending:v,done:P,rows:j}=pd(e,y),I=k.mode==="all"||k.mode==="scope"?k.force:!1,E=k.mode==="single"?[k.id]:I?[...v,...P]:v;if(E.length===0){h({kind:"note",tone:"info",text:P.length>0?`Every shot${y?` under ${y}`:""} is already drawn on. To re-draw them anyway (after a wording or style change): /screenshot annotate --all --force`:"No shots have been taken yet \u2014 /screenshot capture takes them first."}),oe(P.length>0?"/screenshot annotate --all --force":"/screenshot capture");return}await ci(E,{force:I,scope:y,verifiedBefore:new Set(j.filter(Y=>Y.state==="verified").map(Y=>Y.id))})},B=async()=>{let b=await wr(g,{cwd:e,profileName:s});b.kind==="forward-to-agent"&&b.prompt&&await Te(b.prompt,{display:b.display,quietUser:!0}),Tl()};switch(c){case"help":Qn({tab:0,scroll:0});return;case"exit":case"quit":Nt.current?.close(),r();return;case"clear":Ze(),Ao.current=[],rt.current={printed:[],armed:[],printedAt:Mo.current},tt(!1),_t(),console.log("\x1B[?2026h\x1B[H\x1B[2J\x1B[3J\x1B[?2026l"),h({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let b;try{b=mt(e,s)}catch(k){h({kind:"note",tone:"error",text:k.message});return}h({kind:"note",tone:"info",text:`Profile "${b.name}" \u2192 ${b.connection.name} (${b.connection.apiUrl})${b.production?" \u26A0 PRODUCTION":""}`}),N(!0);try{let k=await BN(b.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},v=>h({kind:"note",tone:"info",text:v})),x=HN(b.name,k);GN(x),await zl(x,b.name,v=>h({kind:"note",tone:"info",text:v}));let y=qb(x);if(y){let v=mt(e,s).project;await Kl(b.name,y,v.projectId===y?v.projectName:void 0)}if(h({kind:"note",tone:"ok",text:`\u2713 Logged in to "${b.name}" as ${wi(Un(b.name,y??void 0)??x)}`}),await gh(s),!zn.current){let v=He(e,s);v.ok||(h({kind:"note",tone:"warn",text:v.reason}),oe("/login"))}if(zn.current){let v=zn.current;zn.current=null;let P=He(e,s);P.ok?(h({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 tab to run ${v}.`}),oe(v)):(h({kind:"note",tone:"warn",text:`${P.reason} (then ${v}.)`}),oe("/login"),zn.current=v)}else Ur.current&&(Je(Ur.current,"\u21E5 tab to re-send your last prompt\u2026"),Ur.current=null)}catch(k){if(h({kind:"note",tone:"error",text:`Login failed: ${k.message}`}),!Ii(e,s)){let x=zn.current;h({kind:"note",tone:"warn",text:`Your Document360 session still isn't working, so nothing here can reach your portal${x?` \u2014 ${x} is still waiting`:""}. Run /login to try again.`}),oe("/login")}}finally{N(!1),O(k=>k+1)}return}case"allow-prod":{let b=!1;try{b=mt(e,s).production}catch{}if(!b){h({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}gn.current=!0,Ze(),h({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let b=Xu(g.join(" ")),k=Jt.current.uuid;if(!k){if(!b){h({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}$l.current=b,Bn(b),Rr(`${ll} ${b}`),h({kind:"note",tone:"ok",text:`Session will be named "${b}" once it starts.`});return}if(!b){h({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let x=Jt.current.firstPrompt??"";Vb(x,e).then(y=>{y?(Je(`/rename ${y}`),h({kind:"note",tone:"info",text:`Suggestion: "${y}" \u2014 press tab to accept, or type /rename <your name>.`})):h({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>h({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}rD(k,b),Bn(b),Rr(`${ll} ${b}`),h({kind:"note",tone:"ok",text:`Session renamed to "${b}".`});return}case"profile":{let b=g[0],k=Se(e);if(!b){let x=Object.entries(k?.profiles??{});if(x.length===0){h({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let y=x.map(([j,I])=>({name:j,env:I.connection?.environment??"custom",prod:I.production===!0,who:Fl(j)})),v=s??k?.defaultProfile,P=Math.max(0,y.findIndex(j=>j.name===v));Eo({cursor:P,current:P,rows:y});return}if(b==="add"){let x=Qu(e,g[1],g[2]);if(x){h({kind:"note",tone:"error",text:x});return}h({kind:"note",tone:"ok",text:`\u2713 Profile "${g[1]}" created (environment: ${g[2]??g[1]}).`}),Ul(g[1],!0);return}if(!k?.profiles?.[b]){h({kind:"note",tone:"error",text:`Unknown profile "${b}". Create it: /profile add ${b} <environment>`});return}Ul(b,!0);return}case"doctor":await Cs(g,{cwd:e,version:o});return;case"logs":{let b=Xl();h({kind:"note",tone:"info",text:b.lines.join(`
511
+ `)}),b.copyText&&on(b.copyText,{hint:b.notable?"\u2328 Press c to copy this problem report \u2014 then send it to the team (Teams / Slack / email).":"\u2328 Press c to copy this entry, if you want to send it to the team."});return}case"style-guide":{let b=qd(e),k=await Wa(g,{cwd:e,profileName:s});if(b&&Ua(g).sub==="show"&&Ee(null,{kind:"cmd",cmd:"/style-guide keep",reason:""}),k.kind==="clear")Ze(),h({kind:"note",tone:"ok",text:"\u2713 Agent restarted \u2014 it now writes to the new rules."});else if(k.kind==="forward-to-agent"){let x=Ua(g).sub==="learn";(await Te(k.prompt,{display:k.display,quietUser:!0})).producedNothing||(h({kind:"note",tone:"info",text:(x?Yw():Kw()).join(`
512
+ `)}),x&&(Ze(),h({kind:"note",tone:"ok",text:"\u2713 Agent restarted \u2014 it now writes to your house rules."})))}O(x=>x+1);return}case"genre":{let b=Se(e)?.appType??null;(await Ga(g,{cwd:e})).kind==="clear"&&(Se(e)?.appType??null)!==b&&(Ze(),h({kind:"note",tone:"ok",text:"\u2713 Agent restarted \u2014 the doc-craft playbook for this genre is now loaded."}));try{Ye.current=!(Se(e)?.appType??zb(e))}catch{}O(x=>x+1);return}case"roadmap":{if(g[0]?.toLowerCase()==="done"){let b=rr(e,g.slice(1).join(" ").trim());h({kind:"note",tone:b.ok?"ok":"warn",text:b.line}),O(k=>k+1);return}h({kind:"block",text:Mc(e,{width:qe(),all:g.some(b=>b.toLowerCase()==="--all")}).join(`
513
+ `)});return}case"mcp":await Ni(g);return;case"init":{if(Se(e)){let k=kn(e,s);h({kind:"note",tone:"info",text:["This repo is already set up \u2014 /init won\u2019t overwrite it.",` Change environment: /profile add <${ek().join("|")}> then /profile <name> (the environment lives on the profile, not the login).`," Anything else: edit .d360-writer/config.json, or run d360-writer init for the CLI wizard."].join(`
514
+ `)}),k&&h({kind:"note",tone:"warn",text:`\u26A0 ${k.why} \u2014 ${k.cmd} moves this repo.`});return}let b=[...ek(),...gD().filter(k=>tk(k))].map(k=>({name:k,apiUrl:wD(k).apiUrl,note:tk(k)?"being retired":null}));No({cursor:0,rows:b});return}case"resume":{let b=g.join(" ").trim(),k=oD(e).filter(v=>v.uuid!==Jt.current.uuid);if(!b){if(!k.length){h({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}Xn({query:"",cursor:0,sessions:k});return}let x=nD(e,b);if(!x){h({kind:"note",tone:"error",text:`No session matches "${b}".`});return}Ze(x.uuid),Jt.current={uuid:x.uuid,firstPrompt:x.firstPrompt,titleFired:!0},Bn(x.name),Ap(x.uuid),Ao.current=[],rt.current={printed:[],armed:[],printedAt:Mo.current};let y=kp(e,x.uuid);for(let v of y)h(v);h({kind:"note",tone:"ok",text:y.length?`Resumed "${x.name}" \u2014 restored ${y.length} message(s); continue where you left off.`:`Resumed "${x.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let b=g.join(" ").trim(),k;try{k=await ts(e,s)}catch(y){h({kind:"note",tone:"error",text:`Could not list workspaces: ${y.message}`});return}if(!b){let y=k.workspaces.map(P=>({id:P.id,name:P.name??P.id,type:P.workspace_type}));if(y.length===0){h({kind:"note",tone:"info",text:"No workspaces in this project."});return}let v=Math.max(0,y.findIndex(P=>P.id===k.current));Do({cursor:v,current:v,rows:y,profile:k.profile,projectId:k.projectId,projectName:k.projectName,environment:k.environment});return}let x=Gl(k.workspaces,b);if(!x){h({kind:"note",tone:"error",text:`No workspace matches "${b}".`});return}ui(k.profile,k.projectId,x);return}case"project":{let b=g.join(" ").trim(),k;try{k=await sn(e,s)}catch(y){h({kind:"note",tone:"error",text:`Could not list projects: ${y.message} (signed in? try /login)`});return}if(!b){let y=k.projects.map(P=>({id:P.id,name:P.name??P.id,sub:P.sub_domain}));if(y.length===0){h({kind:"note",tone:"info",text:"No projects found for this identity."});return}let v=y.findIndex(P=>P.id===k.current);Gn({cursor:Math.max(0,v),current:v,rows:y,profile:k.profile,environment:k.environment});return}let x=ql(k.projects,b);if(!x){h({kind:"note",tone:"error",text:`No project matches "${b}". Available: ${k.projects.map(y=>y.name??y.id).join(", ")}`});return}pi(k.profile,x);return}case"logout":{let b,k,x;try{let I=mt(e,s);b=I.name,k=I.project.projectId,x=I.project.projectName}catch(I){h({kind:"note",tone:"error",text:I.message});return}let y=g.includes("--all-projects"),v=QN(b).filter(I=>{let E=qb(I);return!!E&&E!==k}).length,P=zN(b,y?void 0:k);JN(e,b),Ze(),O(I=>I+1);let j=y||v===0?"":` Your sign-in for ${v} other project${v===1?"":"s"} is untouched (/logout --all-projects clears those too).`;h({kind:"note",tone:P?"ok":"info",text:P?y?`\u2713 Signed out of every Document360 project for "${b}" and cleared this repo's project/workspace selection.`:`\u2713 Signed out of ${x?`"${x}"`:`"${b}"`} and cleared its project/workspace selection.${j}`:`Profile "${b}" was not signed in. Cleared any project/workspace selection.${j}`}),h({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),oe("/login");return}case"publish":{if(Kc(g)){let P=cn("publish");P&&h({kind:"note",tone:"info",text:P}),await Go(`/push ${g.join(" ")}`.trim());return}if(!eo(u.trim()))return;let b=cn("publish");b&&h({kind:"note",tone:"info",text:b});let k=g.find(P=>!P.startsWith("--")),x={skipReview:g.includes(xt),skipStyle:g.includes(ck)};We("Checking what is waiting to go live\u2026");let y;try{y=await zc(e,s,k)}catch(P){h({kind:"note",tone:"error",text:`Could not check Document360: ${P.message}`});return}finally{We(null)}if(y.length===0){let P=Xc(e,s,k);for(let j of P.lines)h({kind:"note",tone:j.startsWith("\u2713")?"ok":"info",text:j});P.ahead>0&&oe(Ce("/push","",k));return}let v=Ip(e,y.map(P=>P.path),{allowUnreviewed:x.skipReview,allowStyleErrors:x.skipStyle,checkScreenshots:!0,allowPlaceholders:g.includes(ID)});if(!v.clear){for(let P of Lp(v,y.length,{scope:k,act:"publish"}))h({kind:"note",tone:"warn",text:P});oe(Ce("/review","--blocked --fix",k));return}h({kind:"note",tone:"info",text:`${y.length} draft${y.length===1?" is":"s are"} ahead of what readers see. Pick what goes live:`}),Io({cursor:0,rows:y,opts:x});return}case"push":{if(!eo(u.trim()))return;let b=g.includes(xt),k=g.includes(ck);if(g.includes("--preview")){let P=g.find(j=>!j.startsWith("--"));if(!P){h({kind:"note",tone:"error",text:"Which article? Use /push --preview <path> \u2014 a preview is per article."});return}try{let j=await dD({cwd:e,profileName:s,relPath:P.replace(/\\/g,"/"),preview:!0}),I=j.shots.length>0?` \xB7 ${j.shots.length} screenshot${j.shots.length===1?"":"s"} embedded`:"";h({kind:"note",tone:"info",text:`${j.title}
515
+ ${j.path} \xB7 ${j.articleId?`updates article ${j.articleId}`:"would be created as a new article"}${I}`}),j.missingShots.length>0&&h({kind:"note",tone:"warn",text:`\u26A0 ${j.missingShots.length} screenshot${j.missingShots.length===1?"":"s"} not taken yet \u2014 the description publishes instead: ${j.missingShots.join(", ")}`}),h({kind:"note",tone:"info",text:j.body}),h({kind:"note",tone:"info",text:`Nothing was sent. /push ${j.path} saves it as a draft.`}),oe(`/push ${j.path}`)}catch(j){h({kind:"note",tone:"error",text:j.message})}return}if(g.includes("--screenshots")||g.includes("--shots")){let P=g.find(M=>!M.startsWith("--")),j=_e(e),I=Hi(j,P);if(I.length===0){let M=j.filter(F=>F.state==="captured").length;h({kind:"note",tone:"info",text:M>0?`${M} screenshot${M===1?" has":"s have"} been taken but the callouts aren't drawn on yet, so there is nothing to embed \u2014 /screenshot annotate finishes ${M===1?"it":"them"}.`:P?`No captured screenshots in ${P} \u2014 /push --screenshots covers the whole knowledge base.`:"No captured screenshots yet \u2014 /screenshot capture first."}),M>0&&oe("/screenshot annotate");return}let E=Gi(j,P);E&&h({kind:"note",tone:"warn",text:E});let Y=qi(j);Y&&h({kind:"note",tone:"warn",text:Y}),h({kind:"note",tone:"info",text:`Re-saving ${I.length} article${I.length===1?"":"s"} with captured screenshots so the images embed\u2026`}),await ct(I,0,{skipReview:b,skipStyle:k,scope:Ce("","--screenshots",P).trim()});return}if(g[0]==="--related"&&g[1]){let P=await na(e,s,g[1].replace(/\\/g,"/"));if(P.length===0){h({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await ct(P,0,{skipReview:b,skipStyle:k,scope:`--related ${g[1]}`});return}let x=g.filter(P=>!P.startsWith("--"));if(x[0]){await Ml(x[0],{skipReview:b,skipStyle:k});return}let y=g.includes("--all"),v=g.includes("--force");h({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let P=await gl({cwd:e,profileName:s}),{clean:j,conflicts:I}=co(P.entries),E=y&&v&&I.length>0,Y=Zi(P.entries);if(Y>0&&h({kind:"note",tone:"warn",text:`\u26A0 ${Y} article${Y===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.`}),I.length>0&&!E&&h({kind:"note",tone:"warn",text:ds(I.length)}),j.length===0&&!E){let M=sr(e,s);if(M&&h({kind:"note",tone:"info",text:M}),I.length>0){oe("/resolve");return}h({kind:"note",tone:"ok",text:Y>0?"\u2713 Nothing else is ahead of Document360 to save.":"\u2713 Nothing is ahead of Document360 \u2014 nothing to save."});let F=P.counts["unknown-base"]??0;F>0&&h({kind:"note",tone:"info",text:`(${F} article(s) have no sync base yet \u2014 /push <path> saves one anyway if you need it.)`}),We("Reconciling structure on Document360 (order + related articles)\u2026");try{let G=await Dp({cwd:e,profileName:s,onRateLimit:he=>We(`Document360 rate limit \u2014 waiting ${Math.ceil(he.waitMs/1e3)}s\u2026`)}),ee=lk(await ak({cwd:e,profileName:s})),ce=jp(G);ce?h({kind:"note",tone:ce.startsWith("\u26A0")?"warn":"info",text:ce}):G.skipped&&h({kind:"note",tone:"warn",text:`Order sync skipped: ${G.skipped}`}),ee&&h({kind:"note",tone:"info",text:ee}),G.failures?.length?oe("/structure"):(h({kind:"note",tone:"ok",text:ce||ee?"\u2713 Structure synced to Document360 \u2014 /structure shows the new category + article order.":"\u2713 Already in order \u2014 nothing to change."}),(ce||ee)&&oe("/structure"))}catch(G){h({kind:"note",tone:"warn",text:`Structure sync failed: ${G.message}`})}finally{We(null)}return}if(y){let M=(E?[...j,...I]:j).map(F=>F.path);await ct(M,E?0:I.length,{skipReview:b,skipStyle:k,allowUnpullable:E});return}jo({cursor:0,rows:Nm(j,I),conflicts:I.length})}catch(P){h({kind:"note",tone:"error",text:`Could not compute sync status: ${P.message}`}),h({kind:"note",tone:"info",text:"Save one article on its own: /push <article-path>"})}return}case"resolve":{if(!eo(u.trim()))return;await Bl(g.find(b=>!b.startsWith("--")));return}case"preview":{let b=g.join(" ").trim();if(!b){let x=[];try{x=Object.keys(Xb(e,mt(e,s).name)?.articles??{})}catch{}if(x.length===0){h({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}Yn({query:"",cursor:0,paths:x});return}let k=UN(b)?b:Tp(e,b);if(Sr(k)){try{h({kind:"preview",name:Ys(k),text:fk(fl(k,"utf8"))})}catch(x){h({kind:"note",tone:"error",text:`Could not read ${k}: ${x.message}`})}return}if(QD.test(b)){try{let x=mt(e,s),y={profile:x.name,connection:x.connection},v=x.project.projectId??YN(y),P=await KN(y,v,b);h({kind:"preview",name:P.title??b,text:P.content??"*(article has no content)*"})}catch(x){h({kind:"note",tone:"error",text:`Could not fetch article: ${x.message}`})}return}h({kind:"note",tone:"error",text:`"${b}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let b=g[0]?.trim();if(!b){let v=va(_p(e));Hn({cursor:v,current:v});return}let{lines:k,changed:x,effective:y}=Rs(e,b);for(let v of k)h({kind:"note",tone:v.startsWith("\u26A0")?"warn":v.startsWith("\u2713")?"ok":"info",text:v});x&&(eh(v=>v+1),Nt.current?.setModel(y));return}case"verbose":{let b=g[0]?.trim().toLowerCase(),k=b==="on"?!0:b==="off"?!1:!Qs.current;Qs.current=k;try{iD({...Kb(),verboseTranscript:k})}catch{h({kind:"note",tone:"warn",text:"\u26A0 Applied for this session, but the setting could not be saved."})}h({kind:"note",tone:"ok",text:k?"\u2713 Verbose transcript ON \u2014 every tool call with its file path and full result.":"\u2713 Verbose transcript OFF \u2014 doc work shown by article; my bookkeeping collapsed to one line."});return}case"convert":{if(!Se(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:b,run:k}=gu(g),x=kD(e,s);if(x.length===0){h({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Save some to Document360 first (/push), then /convert."});return}let y=wu(x,b);if(y.length===0){h({kind:"note",tone:"error",text:`No tracked articles under "${b}". (${x.length} are tracked overall.)`});return}let v=Ep(y),P=3,j=`/convert${b?` --scope ${b}`:""} --run`,I=zs(e,"light");if(!k){let M=nk({files:yu(e,y),op:"convert",model:I.model}),F=b?`Scope: ${b} (${y.length} of ${x.length} tracked)
516
+ `:"",G=`
517
+ Model: ${I.model}${I.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;h({kind:"note",tone:"info",text:F+ku(v,M,P).join(`
518
+ `)+G}),oe(j);return}Et.current=Date.now(),Ue(0),A(!0);let E=new AbortController;Oe.current=E;let Y=Date.now();pe({verb:"Converting",total:v.length,done:0,active:[],rows:$o(v),tools:0,chars:0,lastAt:Date.now(),startedAt:Y}),h({kind:"note",tone:"info",text:`Converting ${y.length} articles in ${v.length} batches (\u2264${P} agents at once) on ${I.model}\u2026 (esc to stop)`});try{for await(let M of Ks({cwd:e,partitions:v,promptFor:bu,concurrency:P,profileName:s,allowProdWrites:gn.current,model:I.model,signal:E.signal}))if(M.type==="partition_status")M.status==="running"?pe(F=>F&&{...F,active:[...F.active,M.label],rows:Ve(F.rows,M.label,"active"),lastAt:Date.now()}):pe(F=>F&&{...F,active:F.active.filter(G=>G!==M.label),done:F.done+1,rows:Ve(F.rows,M.label,M.status==="done"?"done":"failed"),lastAt:Date.now()});else if(M.type==="partition_stalled"){let F=xr(M);pe(G=>G&&F?{...G,stalledNote:F}:G)}else if(M.type==="partition_event")pe(F=>{if(!F)return F;let G={...F,lastAt:Date.now()};return M.event.type==="tool"?G.tools=F.tools+1:M.event.type==="text"&&(G.chars=F.chars+M.event.delta.length),G});else if(M.type==="run_done"){Zn(ce=>ce+M.totalCostUsd),Jn(ce=>ce+M.results.reduce((he,me)=>he+me.outputTokens,0));let F=M.aborted?"Stopped. ":"",G=t.kind==="api"?"api":"subscription",ee=Tn(M,"The conversion");h({kind:"note",tone:ee||M.aborted?"warn":M.ok?"ok":"warn",text:ee?ee.join(`
519
+ `):F+$u(M.results,v,G).join(`
520
+ `)}),Bo(Y,M.results,M.totalCostUsd,!ee&&!M.aborted&&M.ok),ee&&oe("/doctor")}}catch(M){h({kind:"note",tone:"error",text:`Convert run failed: ${M.message}`})}finally{Oe.current=null,pe(null),A(!1),O(M=>M+1)}return}case"write":{if(!Se(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let b=ok(e);if(b.length===0){h({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:k,path:x,preview:y,concurrency:v,rewrite:P}=xs(g);if(!x&&!y&&!(Se(e)?.appType??zb(e))){h({kind:"note",tone:"warn",text:`\u26A0 No doc genre is set, so no doc-craft playbook would load \u2014 all ${b.length} articles would be written generically.
519
521
  Pick the genre below (one keypress), then run /write again \u2014 it changes structure, titles and depth for every article.
520
- Not blocked: /write <path> still authors a single article, and /write --preview costs nothing.`}),se(qa.options.map(Q=>({cmd:Q.cmd,desc:Q.desc}))),jo(qa.title);return}let{docsDir:j,targets:N,reason:E,rewriting:K}=ba(e,y,{scope:$,path:R,rewrite:P});if(N.length===0){h({kind:"note",tone:"warn",text:E??"Nothing to write."});return}K&&h({kind:"note",tone:"warn",text:`--rewrite: regenerating ${N.length} already-written article${N.length===1?"":"s"} (overwrites them; git has your baseline).`});let _=Cp(N),F=Au(x),U=zs(e,"standard"),ie=!!R;if(b&&!ie){let Q=Xb({files:Eu(e,y,N),op:"write",model:U.model}),xe=$?`Scope: ${$} (${N.length} pending)
521
- `:"",Oe=`
522
- Model: ${U.model}${U.forced?" (forced)":" \u2014 authoring; /model to override"}`;h({kind:"note",tone:"info",text:xe+Du(_,Q,F).join(`
523
- `)+Oe}),oe(`/write${$?` --scope ${$}`:""}`);return}Et.current=Date.now(),Ue(0),T(!0);let ne=new AbortController;Le.current=ne;let De=Date.now();he({verb:"Writing",total:_.length,done:0,active:[],rows:bo(_),tools:0,chars:0,lastAt:Date.now(),startedAt:De}),h({kind:"note",tone:"info",text:`Writing ${N.length} article${N.length===1?"":"s"} in ${_.length} batch${_.length===1?"":"es"} (\u2264${F} agents at once) on ${U.model}${U.forced?" (forced)":""}\u2026 (esc to stop)`});let pe=new Set;try{for await(let Q of Ks({cwd:e,partitions:_,promptFor:xe=>Nu(xe,j,{rewrite:K||ie}),concurrency:F,profileName:s,allowProdWrites:gn.current,model:U.model,signal:ne.signal}))if(Q.type==="partition_status")Q.status==="running"?he(xe=>xe&&{...xe,active:[...xe.active,Q.label],rows:Ve(xe.rows,Q.label,"active"),lastAt:Date.now()}):he(xe=>xe&&{...xe,active:xe.active.filter(Oe=>Oe!==Q.label),done:xe.done+1,rows:Ve(xe.rows,Q.label,Q.status==="done"?"done":"failed"),lastAt:Date.now()});else if(Q.type==="partition_stalled"){let xe=vr(Q);he(Oe=>Oe&&xe?{...Oe,stalledNote:xe}:Oe)}else if(Q.type==="partition_event"){let xe=null;if(Q.event.type==="tool"){let Oe=bp(Q.event.name,Q.event.input,_[Q.index]?.paths??[]);Oe&&!pe.has(Oe)&&(pe.add(Oe),xe=Q.label)}he(Oe=>{if(!Oe)return Oe;let Ft={...Oe,lastAt:Date.now()};return Q.event.type==="tool"?Ft.tools=Oe.tools+1:Q.event.type==="text"&&(Ft.chars=Oe.chars+Q.event.delta.length),xe&&(Ft.rows=cl(Ft.rows,xe)),Ft})}else if(Q.type==="run_done"){Jn(et=>et+Q.totalCostUsd),Qn(et=>et+Q.results.reduce(($t,oo)=>$t+oo.outputTokens,0));let xe=Q.aborted?"Stopped. ":"",Oe=t.kind==="api"?"api":"subscription",Ft=Tn(Q,"The write");if(h({kind:"note",tone:Ft||Q.aborted?"warn":Q.ok?"ok":"warn",text:Ft?Ft.join(`
524
- `):xe+ju(Q.results,_,Oe,$??R).join(`
525
- `)}),Wo(De,Q.results,Q.totalCostUsd,!Ft&&!Q.aborted&&Q.ok),Ft){oe("/doctor");continue}let yh=Km(Q);if(yh&&h({kind:"note",tone:"warn",text:yh}),!Q.aborted&&Q.ok)try{let et=(pe.size>0?[...pe]:N).map($t=>`${j}/${$t}`);Pr(e,et,{writtenCap:wD,reviewedCap:0,checkedCap:0})}catch{}let no=Q.aborted?[]:hr(e,j,N),bh=Iu(no);bh&&h({kind:"note",tone:"warn",text:bh});let qo=Q.aborted||m.includes("--skip-style")?null:Lu(no);if(qo){let et=qo.errors.length,$t=await li({partitions:qo.partitions,promptFor:qo.promptFor,concurrency:ur,verb:"Fixing",doneNoun:"fixed",headline:`${et} style error${et===1?"":"s"} in ${qo.articles} of the new article${qo.articles===1?"":"s"} \u2014 fixing now, one pass`});if($t.covered.length>0)try{Pr(e,$t.covered,it("lint"))}catch{}no=hr(e,j,N);let oo=Ou(et,no);h({kind:"note",tone:oo[0].startsWith("\u2713")?"ok":"warn",text:oo.join(`
526
- `)})}if(!Q.aborted&&Q.ok){let et=$??R??"",$t=et?` ${et}`:"",oo=no.some(Vo=>Vo.severity==="error");{let Vo=Sp(_,Q.results);yn(`/write${$?` --scope ${$}`:""}${m.includes("--rewrite")?" --rewrite":""}`,{aborted:Q.aborted,partitions:_.length,failed:Vo.failed.length,notRun:Vo.notRun.length,leftBehind:no.filter(Tk=>Tk.severity==="error").length,...Q.blocked?{blocked:Q.blocked}:{},...Q.allEmpty?{allEmpty:!0}:{},...Q.bailedEmpty?{bailedEmpty:!0}:{}})}let kh=et?"/push":"/push --all",Pk=et?`/screenshot author ${et}`:"/screenshot author --all";Ne(oo?`Written, but ${no.filter(Vo=>Vo.severity==="error").length} style error(s) are still unfixed. /lint${$t} --blocked --fix retries them, then /review${$t} --fix for editorial quality, then ${kh}.`:`Written. I\u2019d run /review${$t} --fix next \u2014 editorial review that applies its fixes \u2014 then ${kh} saves them to Document360 as drafts (add ${Pk} first if you want images).`,{kind:"cmd",cmd:oo?`/lint${$t} --blocked --fix`:`/review${$t} --fix`,reason:""})}}}catch(Q){h({kind:"note",tone:"error",text:`Write run failed: ${Q.message}`})}finally{Le.current=null,he(null),T(!1),M(Q=>Q+1)}return}case"draft":{if(!Re(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:y,looseDocs:$}=Mu(e);if(y.length===0&&$===0){h({kind:"note",tone:"info",text:Uu});return}let R=m.join(" ").trim();if(!R&&y.length>1){h({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
527
- ${y.map(P=>` \u2022 ${P.name} (${P.docCount} doc${P.docCount===1?"":"s"})`).join(`
528
- `)}`}),se(y.map(P=>`/draft ${P.name}`));return}let b="",x;if(R){let P=Fu(y,R);P?b=P:x=R}else b=y[0]?.name??"";await Se(ka(b,x),{display:R?`/draft ${R}`:"/draft",quietUser:!0});return}case"pull":{if(!Zn(u.trim()))return;let y=m.find($=>$.startsWith("--"));try{if(y==="--status"){h({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let b=Date.now(),x=await ml({cwd:e,profileName:s});h({kind:"note",tone:"info",text:sa(x,Date.now()-b).join(`
529
- `)});return}if(y==="--baseline"){let b=m.find(N=>!N.startsWith("--")),x=b?b.replace(/\\/g,"/"):void 0;h({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 P=await oD({cwd:e,profileName:s,relPaths:x?[x]:void 0}),j=x?{rebaselined:[],skipped:[]}:await rD({cwd:e,profileName:s});if(P.baselined.length===0&&P.skipped.length===0&&j.rebaselined.length===0){h({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}P.baselined.length>0&&h({kind:"note",tone:"ok",text:`\u2713 Recorded ${P.baselined.length} article${P.baselined.length===1?"":"s"} as matching Document360 \u2014 they read in-sync until either side changes.`}),j.rebaselined.length>0&&h({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${j.rebaselined.length} article${j.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),P.skipped.length>0&&h({kind:"note",tone:"warn",text:`${P.skipped.length} skipped:
530
- ${P.skipped.map(N=>` - ${N.path} (${N.reason})`).join(`
531
- `)}`}),M(N=>N+1);return}if(y==="--compare"){h({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let b=await JN({cwd:e,profileName:s}),x=b.onlyInLegacy.length===0&&b.onlyInManifest.length===0&&b.mappedMissingFromManifest.length===0,P=[`Legacy listing: ${b.legacyCount} \xB7 Manifest: ${b.manifestCount} \xB7 in both: ${b.inBoth}`];x?P.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(b.mappedMissingFromManifest.length&&P.push(`\u2717 ${b.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${b.mappedMissingFromManifest.slice(0,5).join(", ")}`),b.onlyInLegacy.length&&P.push(`\u26A0 ${b.onlyInLegacy.length} only in the legacy listing: ${b.onlyInLegacy.slice(0,5).join(", ")}`),b.onlyInManifest.length&&P.push(`\u26A0 ${b.onlyInManifest.length} only in the manifest: ${b.onlyInManifest.slice(0,5).join(", ")}`),P.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),h({kind:"note",tone:x?"ok":"warn",text:P.join(`
532
- `)});return}if(y){h({kind:"note",tone:"error",text:`Unknown option: ${y} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let $=m[0];if($){let b=$.replace(/\\/g,"/"),x;try{let P=await qb({cwd:e,profileName:s,relPath:b});x={plan:P,mode:P.overwritesLocalChanges?"conflict":"pull"}}catch(P){if(!Vb(P))throw P;x={mode:"local-only",path:b,title:Yb(e,b)}}Ee.current=[x],Dt.current=[],Zt.current=[],Bo();return}h({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let R=await eu({cwd:e,profileName:s});for(let b of tu(R))h({kind:"note",tone:b.tone,text:b.text});M(b=>b+1)}catch($){h({kind:"note",tone:"error",text:`Pull failed: ${$.message}`})}return}case"scope":{if(!Re(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let y=sD(e);if(y.length===0){h({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.'});return}Io({cursor:0,rows:y.map($=>({...$,checked:$.recommended}))});return}case"audit":{if(m[0]==="--auto"){let $=Re(e);if(!$){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let R=m[1]!=="off";Wb({...$,autoAudit:R},e),h({kind:"note",tone:"ok",text:R?"\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}if(!Zn(u.trim()))return;let y=await hs({cwd:e,profileName:s});if(y.kind==="audit-blocked"){Ne(y.note,{kind:"cmd",cmd:y.lead.cmd,reason:y.lead.reason},"warn");return}if(y.kind==="forward-to-agent"&&y.prompt){let $=await Se(y.prompt,{display:y.display,quietUser:!0}),R=oa(e,s);if(R){Ne(R.note,{kind:"cmd",cmd:sr.cmd,reason:sr.reason},"warn"),M(b=>b+1);return}$.producedNothing||(Fs(e,s),M(b=>b+1))}return}case"lint":case"check":{let y=cn(c);y&&h({kind:"note",tone:"info",text:`\u2192 ${y}`});let $=m.find(P=>!P.startsWith("--")),R=$?` ${$}`:"",b=Sr({cwd:e,scope:$}),x=dn(b,m);if(m.includes("--fix")){let P=dr(e,m,b);P.lines.length>0&&h({kind:"note",tone:"ok",text:P.lines.join(`
533
- `)});let j=P.fixed>0?Sr({cwd:e,scope:$}):b,N=xu(e,m,j);if(!N){let Q=Ru(e,m,j);h({kind:"note",tone:"ok",text:Q.lines.join(`
534
- `)});for(let xe of Q.closed)h({kind:"note",tone:"ok",text:xe});return}let E={aborted:!1,partitions:0,failed:0,notRun:0};if(N.kind==="partitioned"){let Q=await li({partitions:N.partitions,promptFor:N.promptFor,concurrency:ur,verb:"Fixing",doneNoun:"fixed",headline:`Fixing ${N.findings} issue${N.findings===1?"":"s"} across ${N.articles} article${N.articles===1?"":"s"} in ${N.partitions.length} batches (\u2264${ur} at once)`,calibrateAs:"/lint"});if(E=Q.outcome,Q.covered.length>0)try{Pr(e,Q.covered,it("lint"))}catch{}if(Q.aborted){let xe=ws({cwd:e,after:dn(Sr({cwd:e,scope:$}).filter(Oe=>!Oe.baselined),m),scope:$,aborted:!0,blocked:un(m)});Ne(xe.text,{kind:"cmd",cmd:xe.cmd,reason:""},"warn");return}}else{h({kind:"note",tone:"info",text:`Fixing ${N.findings} doc issue${N.findings===1?"":"s"}\u2026`});let Q=gD(e,$);await Se(N.prompt,{display:N.display,quietUser:!0});try{Pr(e,Q,it("lint"))}catch{}}let K=dn(Sr({cwd:e,scope:$}).filter(Q=>!Q.baselined),m),_=dn(j.filter(Q=>!Q.baselined),m),F=new Set(K.map(Q=>Q.fp)),U=new Set(_.map(Q=>Q.fp)),ie=_.filter(Q=>!F.has(Q.fp)).length,ne=K.filter(Q=>!U.has(Q.fp)).length,De=ne>0?`
535
- \u26A0 ${ne} new ${ne===1?"issue":"issues"} appeared in the rewrites \u2014 recasting a sentence is where these come from.`:"";h({kind:"note",tone:K.some(Q=>Q.severity==="error")?"warn":"ok",text:K.length===0?`\u2713 Lint: all ${_.length} issue${_.length===1?"":"s"} resolved.`:[`\u2713 Lint: fixed ${ie} of ${_.length}.${De}`,"",...bs(K)].join(`
536
- `)}),yn(ys(m,$),N.kind==="partitioned"?E:{aborted:!1,partitions:0,failed:0,notRun:0,verifiedComplete:K.length===0});let pe=ws({cwd:e,after:K,before:N.findings,scope:$,blocked:un(m)});Ne(pe.text,{kind:"cmd",cmd:pe.cmd,reason:""});return}if(h({kind:"note",tone:x.length===0?"ok":"warn",text:bs(x,{full:m.includes("--full"),baselined:m.includes("--baselined")}).join(`
537
- `)}),x.length>0){let P=Zi(e,$)===0&&ea(e,$)===0?"; /push --all saves them to Document360 as-is":"",j=`/lint${R}${un(m)?" --blocked":""} --fix`,N=On(e,j);Ne(`Found ${x.length} doc issue${x.length===1?"":"s"} above. ${j} has the agent fix them in place${N?` (${N})`:""} \u2014 or /review${R} --fix for the full editorial pass${P}.`,{kind:"cmd",cmd:j,reason:""})}return}case"structure":{let y=_s(e,s);if(y.length===0){h({kind:"note",tone:"info",text:"No documentation structure yet \u2014 run /init and author some articles first."});return}h({kind:"note",tone:"info",text:["Documentation order (categories \u2192 articles):","",...y].join(`
538
- `)});return}case"status":{let y=m.some($=>$==="--all"||$==="--full");h({kind:"block",text:Xd(e,{profileName:s,all:y,width:Ge()}).join(`
539
- `)}),ee.current=!0;return}case"retire":{let y=m.find(R=>!R.startsWith("-"));if(!y){h({kind:"block",text:Qd(e,s).join(`
540
- `)}),ee.current=!0;return}let $=PD(e,y)||y;if(!m.includes("--yes")&&!m.includes("-y")){h({kind:"note",tone:"warn",text:[`\u26A0 This takes "${$}" off your readers on Document360.`," The article, its history and every reviewer comment stay \u2014 nothing is deleted."," /push puts it back later if you change your mind."].join(`
541
- `)}),Je(`/retire ${$} --yes`,"tab to take it off your readers \xB7 or keep typing");return}T(!0);try{let R=await SD({cwd:e,path:$,profileName:s,now:new Date().toISOString()});h(R.ok?{kind:"note",tone:"ok",text:R.alreadyHidden?`\u2713 "${$}" was already invisible to readers. Recorded as retired, so nothing will offer to publish it again.
542
- It stays on Document360 with its history and comments intact. /push puts it back.`:`\u2713 "${$}" is no longer visible to your readers.
543
- It stays on Document360 with its history and comments intact. /push puts it back.`}:{kind:"note",tone:"error",text:`\u2717 Could not retire "${$}" \u2014 ${R.error.message}`})}finally{T(!1)}return}case"terms":{let y=m.findIndex($=>$==="--approve");if(y!==-1){let $=m[y+1];h($?{kind:"block",text:ep(e,$.replace(/^["']|["']$/g,"")).lines.join(`
544
- `)}:{kind:"note",tone:"warn",text:'\u2717 Name the spelling to approve, e.g. /terms --approve "drop-down".'}),ee.current=!0;return}h({kind:"block",text:Zd(e,{...m.find($=>!$.startsWith("--"))?{scope:m.find($=>!$.startsWith("--"))}:{},all:m.includes("--all")}).join(`
545
- `)}),ee.current=!0;return}case"reorder":{let y=Kd(e,m);if(!y){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let $=await Se(y.prompt,{display:y.display,quietUser:!0}),R=Bt(e,{text:"Reordered locally \u2014 /push --all syncs the new order to Document360.",cmd:"/push --all"},"Reordered locally. ");Mo($,R.text,{kind:"cmd",cmd:R.cmd,reason:""});return}case"review":{let y=Vd(e,m);if(y){h({kind:"note",tone:"ok",text:y.lines[0]});for(let N of y.closed)h({kind:"note",tone:"ok",text:N});Ne(y.cta.text,{kind:"cmd",cmd:y.cta.cmd,reason:""});return}let $=qd(e,m);if(!$){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let R=m.includes("--fix"),b=m.find(N=>!N.startsWith("--")),x=R?yo(e,m,b):[],P={aborted:!1,partitions:0,failed:0,notRun:0},j;if($.kind==="partitioned"){let N=await xk($,R);P=N.outcome,j=N}else j=await Se($.prompt,{display:$.display,quietUser:!0}),P={...P,producedNothing:j.producedNothing};if("aborted"in j&&j.aborted){let N=m.includes("--blocked")?"--blocked --fix":m.includes("--stale")?"--stale --fix":"--fix",E=Pe("/review",N,b);Ne(`Stopped \u2014 the batches that finished are saved. ${E} picks up the rest${b||Ms(m)?"":", or narrow it with /review <category> --fix"}.`,{kind:"cmd",cmd:E,reason:""},"warn");return}if($.kind!=="partitioned"&&R&&!j.producedNothing)try{Pr(e,x,it("review"))}catch{}if(R&&yn(`/review${b?` ${b}`:""}${m.includes("--all")?" --all":""}${m.includes("--blocked")?" --blocked":m.includes("--stale")?" --stale":""} --fix`,P),R){if(R&&!j.producedNothing){let K=dr(e,["--fix"],Sr({cwd:e,scope:b}));K.lines.length>0&&h({kind:"note",tone:"ok",text:K.lines.join(`
546
- `)})}let N=R&&!j.producedNothing?Sr({cwd:e,scope:b}).filter(K=>!K.baselined&&K.severity==="error"):[];if(N.length>0){let K=new Set(N.map(U=>U.path)).size,_=`/lint${b?` ${b}`:""} --blocked --fix`,F=On(e,_);h({kind:"note",tone:"warn",text:`\u26A0 The editor's rewrites left ${N.length} style error${N.length===1?"":"s"} in ${K} article${K===1?"":"s"} \u2014 recasting a sentence is where these appear.`}),Mo(j,`Editor applied its fixes, but ${N.length} style error${N.length===1?"":"s"} remain. ${_} clears ${N.length===1?"it":"just those"} \u2014 it costs nothing to find them and one pass to correct${F?` (${F})`:""}. It is the last paid pass before publishing: anything still standing after a second attempt is reported for a person rather than run again.`,{kind:"cmd",cmd:_,reason:""});return}let E=Bt(e,{text:`\u2713 Editor applied its fixes \u2014 your docs are corrected. /push${b?"":" --all"} saves them to Document360 as drafts (or /lint${b?` ${b}`:""} for an instant no-token re-scan first).`,cmd:b?"/push":"/push --all"},"\u2713 Editor applied its fixes to this scope. ",b);Mo(j,E.text,{kind:"cmd",cmd:E.cmd,reason:""})}else{let N=b?` ${b}`:"",E=Zi(e,b)===0&&ea(e,b)===0?`; /push${b?"":" --all"} saves them to Document360 as-is`:"";Mo(j,`The review listed issues above. /review${N} --fix lets the editor apply them all (or /lint${N} --fix for just the deterministic ones${E}).`,{kind:"cmd",cmd:`/review${N} --fix`,reason:""})}return}case"capture-setup":{await G();return}case"devhints":{if(!Re(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}h({kind:"note",tone:"info",text:Qo(Xo(e)).join(`
547
- `)}),on(ro()),Yr.current=Ut(e).status==="current",Fo.current=an(e);return}case"discover":{if(!Re(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await Se(Kc(),{display:"/discover",quietUser:!0});return}case"ask":{if(!Re(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let y=m.join(" ").trim();if(y===""){h({kind:"block",text:fd(CD(e)).join(`
548
- `)});return}try{let $=RD(e,{question:y});h({kind:"note",tone:"ok",text:hd($.file,Es(e)).join(`
549
- `)})}catch($){h({kind:"note",tone:"warn",text:`Could not file the question: ${$.message}`})}return}case"inbox":{if(!Re(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(dd(e)===0){h({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 Se(pd(),{display:"/inbox",quietUser:!0});return}case"share":{let y=Re(e);if(!y){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let $=m[0]?.trim().toLowerCase();if($==="status"){for(let b of Pa(e,y))h({kind:"note",tone:b.tone,text:b.text});return}if($==="on"||$==="off"){for(let b of md(e,y,$==="on"))h({kind:"note",tone:b.tone,text:b.text});M(b=>b+1);return}if($){h({kind:"note",tone:"error",text:`Unknown option: ${$} \u2014 use /share, /share status, /share on, or /share off.`});return}h({kind:"note",tone:"info",text:"Exchanging work with your team\u2026"});let R=await Ta(e,y);for(let b of R.lines)h({kind:"note",tone:b.tone,text:b.text});R.changed&&M(b=>b+1);return}case"feedback":{let y=Zb(e),$="";try{$=Cr(y)?hl(y,"utf8"):""}catch{$=""}if(!/^## /m.test($)){h({kind:"note",tone:"info",text:"No open d360-writer feedback to copy \u2014 nothing logged in .d360-writer/tool-feedback.md yet."});return}let R=await dp($.trim());h({kind:"note",tone:R?"ok":"warn",text:R?"\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 ${y} and copy it manually.`}),R&&El(null);return}case"document":{if(!Re(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{push:y,skipReview:$,what:R}=Bu(m);if(!R&&Wu(e)===0){h({kind:"note",tone:"info",text:Gu});return}let b=`/document${R?` ${R}`:""}${y?" --push":""}`,x=await Se(Hu(R),{display:b,quietUser:!0});y&&!x.producedNothing&&await lh({skipReview:$});return}case"catch-up":{if(!Re(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!Zn(u.trim()))return;let{push:y,skipReview:$}=bd(m);for(let E of await wd(e))h({kind:"note",tone:E.tone,text:E.text});h({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let R=await vd({cwd:e,profileName:s});for(let E of xd(R))h({kind:"note",tone:E.startsWith("\u2713")?"ok":E.startsWith("\u2139")?"info":"warn",text:E});let b=Ds(e);for(let E of kd(b))h({kind:"note",tone:E.tone,text:E.text});let x=pn(e);h({kind:"note",tone:"info",text:yd(x)});let P=ek(e),j=await Se($d(b),{display:`/catch-up${y?" --push":""}`,quietUser:!0}),N=fo(e,P,"","/catch-up");if(y&&!j.producedNothing)await lh({skipReview:$});else if(N.cta)Mo(j,N.cta.text,{kind:"cmd",cmd:N.cta.cmd,reason:""});else{let E=Ea({queued:x,hold:b.hold});Mo(j,E.note,E.lead?{kind:"cmd",cmd:E.lead.cmd,reason:E.lead.reason}:null,E.tone)}return}case"comments":{if(!Re(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!Zn(u.trim()))return;let y=Td(m);We("Checking Document360 for reviewer comments\u2026"),T(!0);let $=null;try{$=await Na(e,s,{...y.scope,onProgress:(b,x)=>We(`Checking Document360 for reviewer comments\u2026 ${b}/${x}`)})}catch(b){h({kind:"note",tone:"error",text:`Couldn\u2019t read comments from Document360: ${b.message}`})}finally{T(!1),We(null)}if(!$)return;M(b=>b+1);let R=mo($.threads,$.labels);if($.threads.length===0){h({kind:"note",tone:"ok",text:Is($,{showAnswered:y.showAnswered,width:Ge()}).join(`
550
- `)});return}if(y.answer&&(y.all||y.scope.path||y.scope.scope||R.length===1)){Uo(Sd($,{full:!0,showAnswered:y.showAnswered,width:Ge()})),await Ll(R,{resolve:y.resolve});return}if(R.length===1){Uo(Da(R[0],{width:Ge()})),Or({group:R[0],cursor:0,fromList:!1,resolve:y.resolve,rest:[]});return}Uo(Is($,{showAnswered:y.showAnswered,width:Ge()})),en({cursor:0,rows:ja(R),groups:R,resolve:y.resolve,report:$});return}case"update":{Pl.current=!0,h({kind:"note",tone:"info",text:"Updating the d360-writer toolchain\u2026 (don\u2019t close this window)"}),Wn(!0);let y=await Oa().finally(()=>Wn(!1));y.ok?(h({kind:"note",tone:"ok",text:`\u2713 Updated ${y.packages.join(" + ")} \u2014 run /exit, then relaunch to apply.`}),oe("/exit"),xo("")):(h({kind:"note",tone:"warn",text:`Update failed. ${La(y.output)}`}),y.output&&h({kind:"note",tone:"info",text:`${y.output}
551
-
552
- Full output: ${Ia()}`}));return}case"screenshot":{let y=is(m),$=so(e);if($&&y.mode!=="list"&&h({kind:"note",tone:"info",text:$}),y.mode==="capture"){await A(y.rest);return}if(y.mode==="annotate"){await W(y.rest);return}if(y.mode==="checklist"){await G();return}if(y.mode==="verify"){let x=_e(e),P=y.rest.find(E=>!E.startsWith("-")),j=P?[P]:Cs(x);if(P&&!x.some(E=>E.id===P)){h({kind:"note",tone:"error",text:`No screenshot placeholder called "${P}". /screenshot list shows them all.`});return}if(j.length===0){let E=x.filter(_=>_.state==="rejected").length,K=x.filter(_=>_.state==="verified").length;h({kind:"note",tone:"info",text:E>0?`Nothing left to verify. ${E} shot${E===1?"":"s"} failed verification \u2014 re-capture with /screenshot capture --failed.`:K>0?`All ${K} captured shot${K===1?" is":"s are"} already verified.`:"No captured screenshots to verify yet \u2014 /screenshot capture takes the shots first."});return}h({kind:"note",tone:"info",text:In(j.length)}),await Se(Qt(e,j),{display:P?`/screenshot verify ${P}`:"/screenshot verify",quietUser:!0});let N=fr(e,j);N.length>0&&h({kind:"note",tone:"info",text:N.join(`
553
- `)});return}if(y.mode==="list"){if(!Re(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let x=Re(e)?.docsDir??jp,P=Tc(e,y.scope),j=_e(e,P);if(y.picker){if(j.length===0){h({kind:"note",tone:"info",text:"No screenshot placeholders found in the docs."});return}let E=om(j);if(E.length===0){h({kind:"note",tone:"info",text:Vi(j,{docsDir:x}).join(`
554
- `)});let K=Pe("/push","--screenshots",P),_=Bt(e,{text:`\u2713 All ${j.length} screenshots are captured. ${K} saves them into the articles on Document360; /screenshot capture${P?` ${P}`:""} re-captures.`,cmd:K},`\u2713 All ${j.length} screenshots are captured. `,P);Ne(_.text,{kind:"cmd",cmd:_.cmd,reason:""});return}qn({cursor:0,rows:E,title:"Screenshots \u2014 pick what to author or capture:"});return}h({kind:"note",tone:"info",text:Vi(j,{scope:P,detail:y.detail,docsDir:x}).join(`
555
- `)}),$&&h({kind:"note",tone:"info",text:$});let N=Pc(j,P);N.key!=="done"&&oe(N.cmd);return}if(y.mode==="single"){await uh(y.id);return}if(!Re(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let R=y.mode==="scope"?y.scope:void 0,b=cD(e,{scope:R}).map(x=>x.id);if(b.length===0){h({kind:"note",tone:"info",text:R?`No screenshot placeholders under ${R}.`:"No screenshot placeholders found in the docs."});return}await ch(b,{setup:y.setup,scope:y.mode==="scope"?y.scope:void 0,runLine:y.mode==="scope"?[`/screenshot author ${y.scope}`,`/screenshot ${y.scope}`]:["/screenshot author --all","/screenshot --all"]});return}case"capture":{await A(m);return}case"reset":{let y=Nd(e);if(y.length===0){h({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}Lr.current={repoName:Ys(e),targets:y,hadDevhints:Cr(Jb(e))},h({kind:"note",tone:"warn",text:jd(e,y).join(`
556
- `)}),Je(Ys(e));return}default:h({kind:"note",tone:"error",text:`Unknown command: /${c} \u2014 type /help.`})}},[e,r,s,Bo,Ul,h,Ze,Se,ct,Ol,dh]),Xr=te(u=>{let p=(u??w).trim();if(k(""),Xs(null),Ro(0),p.startsWith("/")){ee.current=!1,ge.current=!1,ke.current=null,_t(),jo(null);let m=Rl.current.includes(p);m&&(Rl.current=[]),se(A=>m?[]:xb(A,p))}if(!p||(mn(!1),At.current=!1,(Lr.current||Ee.current.length>0)&&h({kind:"user",text:p}),hh(p))||ph(p))return;yl.current.push(p);let c=Pb(p,Mp.current);if(p.startsWith("/"))h({kind:"user",text:p}),z(!0),Ho(c).finally(()=>z(!1));else if(TD(c)){h({kind:"user",text:p});let m=AD(c);if(!m)Se(c,{display:p,quietUser:!0});else{try{ED(e,{title:m,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}Se(`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:p,quietUser:!0})}}else{let m=gm(e,c);Se(m??c,{display:p})}},[w,hh,ph,Ho,Se]),fh=te(u=>{if(u.length>1){if(u.includes("\x1B"))return;let p=Rb(u);if(Cb(p)){let c=Sb(++gk.current,p);Mp.current.set(c,p),S(c)}else S(p);return}S(u)},[S]),Go=Math.max(10,st-6),mh=vp(()=>dl(d.text,Go),[d.text,Go]),Wl=te(u=>g(p=>({...p,pos:Math.max(0,Math.min(p.text.length,p.pos+u))})),[]),hi=te(u=>g(p=>({...p,pos:Ab(dl(p.text,Go),p.pos,u)})),[Go]),Qr=te(u=>g(p=>({...p,pos:Eb(dl(p.text,Go),p.pos,u)})),[Go]),Ck=["\x1B[H","\x1B[1~","\x1BOH"],Sk=["\x1B[F","\x1B[4~","\x1BOF"],gh=te((u,p)=>p.leftArrow?(Wl(-1),!0):p.rightArrow?(Wl(1),!0):u&&Ck.includes(u)?(Qr("start"),!0):u&&Sk.includes(u)?(Qr("end"),!0):p.ctrl&&u==="a"?(Qr("start"),!0):p.ctrl&&u==="e"?(Qr("end"),!0):!1,[Wl,Qr]),wh=te(()=>{if(Le.current){if(!Le.current.signal.aborted){let u=(Lo?.verb??"work").toLowerCase(),p=Lo?.unit??"article";h({kind:"note",tone:"warn",text:`\u238B Stopping the ${u} run (finishing in-flight ${p}s)\u2026`}),Le.current.abort()}return!0}return _r.current?!1:(_r.current=!0,h({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),Nt.current?.interrupt(),!0)},[Lo]);return SN((u,p)=>{if(p.ctrl&&u==="c"){if(Mr.current!==null&&Date.now()-Mr.current<ik){Mr.current=null,Nt.current?.close(),r();return}Mr.current=Date.now(),qp(!0),$l.current&&clearTimeout($l.current),$l.current=setTimeout(()=>{Mr.current=null,qp(!1)},ik),C?wh():w&&k("");return}if(Vr.current.awaySince!==null)try{let c=mb(Vr.current,Date.now(),pn(e));if(Vr.current=c.memory,oh(null),c.kind==="delta"){h({kind:"note",tone:"info",text:wb(c.delta,c.awayMs)});let m=Mt(!1);m.kind==="recommend"&&nn(m.rec,{silent:!0})}else if(c.kind==="briefing"){h({kind:"note",tone:"info",text:`\u{1F4E5} ${qs(c.delta)} arrived while you were away (${yp(c.awayMs)}).`});let m=Mt(!1);m.kind==="recommend"&&nn(m.rec)}}catch{}if(Nl.current=Date.now(),!D){if(C){if(p.escape){wh();return}if(p.return){let c=w.trim();if(!c)return;Kn.current.push(c),kl([...Kn.current]),k("");return}if(gh(u,p))return;if(p.upArrow){hi(-1);return}if(p.downArrow){hi(1);return}if(p.backspace||p.delete){v();return}u&&!p.ctrl&&!p.meta&&fh(u);return}if(wn){if(p.upArrow){Hn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Hn(c=>c&&{...c,cursor:Math.min(Pt.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=tn(u,Pt.length);c!==null&&Hn(m=>m&&{...m,cursor:c});return}if(p.return){let c=Pt[wn.cursor];Hn(null);let{lines:m,changed:A,effective:W}=xs(e,c.value??"default");for(let G of m)h({kind:"note",tone:G.startsWith("\u26A0")?"warn":G.startsWith("\u2713")?"ok":"info",text:G});A&&(zp(G=>G+1),Nt.current?.setModel(W));return}if(u==="s"){let c=Pt[wn.cursor];Hn(null),Nt.current?.setModel(c.value??void 0),h({kind:"note",tone:"ok",text:`\u2713 Using ${c.label} for this session only (your saved default is unchanged).`});return}if(p.escape){Hn(null);return}return}if(jt){if(p.upArrow){To(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){To(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=tn(u,jt.rows.length);c!==null&&To(m=>m&&{...m,cursor:c});return}if(p.return||u==="s"){let c=jt.rows[jt.cursor];To(null),Ml(c.name,p.return===!0);return}if(p.escape){To(null);return}return}if(Ur){if(p.escape){Xn(null);return}if(p.leftArrow||p.tab&&p.shift){Xn(c=>c&&{tab:(c.tab-1+ut.length)%ut.length,scroll:0});return}if(p.rightArrow||p.tab){Xn(c=>c&&{tab:(c.tab+1)%ut.length,scroll:0});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=ut.length){Xn({tab:Number(u)-1,scroll:0});return}if(p.upArrow){Xn(c=>c&&{...c,scroll:Math.max(0,c.scroll-1)});return}if(p.downArrow){Xn(c=>{if(!c)return c;let m=(ut[c.tab]??ut[0]).rows.length;return{...c,scroll:Math.min(Math.max(0,m-1),c.scroll+1)}});return}return}if(It){if(p.upArrow){Ao(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Ao(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=tn(u,It.rows.length);c!==null&&Ao(m=>m&&{...m,cursor:c});return}if(p.return){let c=It.rows[It.cursor].name;if(Ao(null),!oc(e,c).created){h({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}h({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${c}").`});let A=!1;try{let W=Un(c);A=!!W&&!(ko(W)&&!W.refreshToken)}catch{A=!1}h({kind:"note",tone:"info",text:A?`Next: sign in to ${c} and pick your project \u2014 you're already signed in here, so it'll be quick.`:`Next: sign in to Document360 (${c}) and pick your project.`}),oe("/login"),M(W=>W+1);return}if(p.escape){Ao(null);return}return}if(Ke){if(p.upArrow){Eo(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Eo(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=tn(u,Ke.rows.length);c!==null&&Eo(m=>m&&{...m,cursor:c});return}if(p.return){let c=Ke.rows[Ke.cursor],{profile:m,projectId:A}=Ke;Eo(null),ui(m,A,c);return}if(p.escape){Eo(null);return}return}if(nt){if(p.upArrow){Gn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Gn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=tn(u,nt.rows.length);c!==null&&Gn(m=>m&&{...m,cursor:c});return}if(p.return){let c=nt.rows[nt.cursor],{profile:m}=nt;Gn(null),pi(m,c);return}if(p.escape){Gn(null);return}return}if(ot){if(p.upArrow){Io(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Io(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u===" "){Io(c=>c&&{...c,rows:c.rows.map((m,A)=>A===c.cursor?{...m,checked:!m.checked}:m)});return}if(p.return){let c=ot.rows.filter(m=>m.checked).map(m=>m.path);if(Io(null),c.length===0){h({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}zc(e,c),h({kind:"note",tone:"ok",text:`\u2713 Scoped to ${c.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let m of c)h({kind:"note",tone:"info",text:` ${m}`});h({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(p.escape){Io(null);return}return}if(lt){if(p.upArrow){Vn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Vn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=tn(u,lt.rows.length);c!==null&&Vn(m=>m&&{...m,cursor:c});return}if(p.return){let c=lt.rows[lt.cursor],m=lt.run;Vn(null),m(c.token);return}if(p.escape){Vn(null);return}return}if(wt){if(p.upArrow){No(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){No(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=tn(u,wt.rows.length);c!==null&&No(m=>m&&{...m,cursor:c});return}if(p.return){let c=wt.rows[wt.cursor],m=wt.conflicts;No(null),c.conflict?Ul(c.paths[0]):c.kind==="article"?Ol(c.paths[0]):ct(c.paths,c.kind==="all"?m:0);return}if(p.escape){No(null);return}return}if(Lt){if(p.upArrow){Do(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Do(c=>c&&{...c,cursor:Math.min(c.rows.length,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=tn(u,Lt.rows.length+1);c!==null&&Do(m=>m&&{...m,cursor:c});return}if(p.return){let{cursor:c,rows:m,opts:A}=Lt;Do(null);let W=c===0?m:[m[c-1]];Rk(W,A);return}if(p.escape){Do(null),h({kind:"note",tone:"info",text:"Left as drafts \u2014 nothing changed. /publish when they have been signed off."});return}return}if(yt){let{rows:c}=yt;if(p.upArrow){en(m=>m&&{...m,cursor:Math.max(0,m.cursor-1)});return}if(p.downArrow){en(m=>m&&{...m,cursor:Math.min(c.length-1,m.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let m=fp(Wp.current,Number(u),c.length-1);Wp.current=m.memory,m.index!==null&&en(A=>A&&{...A,cursor:m.index+1});return}if(u==="a"||u==="A"){en(m=>m&&{...m,cursor:0});return}if(p.return){let m=c[yt.cursor],{groups:A,resolve:W,report:G}=yt;if(en(null),m.kind==="all"){Ll(A,{resolve:W,report:G});return}Uo(Da(m.group,{width:Ge()})),Or({group:m.group,cursor:0,fromList:!0,resolve:W,rest:A.filter(y=>y.articleId!==m.group.articleId),report:G});return}if(p.escape){en(null),oe("/comments");return}return}if(Qe){let c=()=>{let{rest:m,group:A,fromList:W,resolve:G,report:y}=Qe;if(Or(null),!W||!y){oe("/comments");return}let $=[A,...m].sort((R,b)=>R.category.localeCompare(b.category)||R.title.localeCompare(b.title));en({cursor:0,rows:ja($),groups:$,resolve:G,report:y})};if(p.upArrow||p.downArrow){Or(m=>m&&{...m,cursor:m.cursor===0?1:0});return}if(u==="y"||u==="Y"||p.return&&Qe.cursor===0){let{group:m,resolve:A,rest:W,report:G}=Qe;Or(null),Ll([m],{resolve:A,rest:W,...G?{report:G}:{}});return}if(u==="b"||u==="B"||p.escape||p.return){c();return}return}if(Ot){if(p.upArrow){qn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){qn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=tn(u,Ot.rows.length);c!==null&&qn(m=>m&&{...m,cursor:c});return}if(p.return){let c=Ot.rows[Ot.cursor];qn(null),c.action==="capture"?zr(c.ids,{runLine:c.kind==="all"?["/screenshot capture --all","/capture --all"]:void 0}):c.action==="annotate"?ci(c.ids,{verifiedBefore:new Set(_e(e).filter(m=>m.state==="verified").map(m=>m.id))}):c.kind==="shot"?uh(c.ids[0]):ch(c.ids,{setup:!0,runLine:c.kind==="all"?["/screenshot author --all","/screenshot --all"]:void 0});return}if(p.escape){qn(null);return}return}if(bt){if(p.escape){Yn(null);return}if(p.upArrow){Yn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Yn(c=>c&&{...c,cursor:Math.min(Math.max(0,si.length-1),c.cursor+1)});return}if(p.return){let c=si[bt.cursor];if(c){Yn(null);try{h({kind:"preview",name:Ys(c),text:lk(hl(xp(e,c),"utf8"))})}catch(m){h({kind:"note",tone:"error",text:`Could not read ${c}: ${m.message}`})}}return}if(p.backspace||p.delete){Yn(c=>c&&{...c,query:c.query.slice(0,-1),cursor:0});return}if(u&&!p.ctrl&&!p.meta&&u.length===1){Yn(c=>c&&{...c,query:c.query+u,cursor:0});return}return}if(kt){if(p.escape){zn(null);return}if(p.upArrow){zn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){zn(c=>c&&{...c,cursor:Math.min(Math.max(0,ii.length-1),c.cursor+1)});return}if(p.return){let c=ii[kt.cursor];if(c){zn(null),Ze(c.uuid),Jt.current={uuid:c.uuid,firstPrompt:c.firstPrompt,titleFired:!0},Bn(c.name),Rp(c.uuid),Po.current=[],rt.current={printed:[],armed:[],printedAt:_o.current};let m=mp(e,c.uuid);for(let A of m)h(A);h({kind:"note",tone:"ok",text:m.length?`Resumed "${c.name}" \u2014 restored ${m.length} message(s); continue where you left off.`:`Resumed "${c.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(p.backspace||p.delete){zn(c=>c&&{...c,query:c.query.slice(0,-1),cursor:0});return}if(u&&!p.ctrl&&!p.meta&&u.length===1){zn(c=>c&&{...c,query:c.query+u,cursor:0});return}return}if(p.tab&&!w&&de){k(de),_t();return}if(!w&&fe.length>0&&!At.current&&u&&/^[1-9]$/.test(u)){let c=fe[Number(u)-1];if(c){k(Fn(c));return}}if(!w&&fe.length===0&&!At.current&&rt.current.armed.length>0&&u&&/^[1-9]$/.test(u)){let c=rt.current.armed[Number(u)-1];if(c){k(c);return}}if(!w&&(ni||Gr)&&u==="c"&&!p.ctrl&&!p.meta&&!p.return&&!p.tab){let c=ni!=null;dp(ni??Gr).then(A=>{h({kind:"note",tone:A?"ok":"warn",text:A?c?"\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.":c?"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."}),A&&c&&El(null),A&&!c&&Qp(!0)});return}if(!gh(u,p)){if(sh){if(p.upArrow){Ro(c=>Math.max(0,c-1));return}if(p.downArrow){Ro(c=>Math.min(rn.length-1,c+1));return}if(p.tab){k("/"+(rn[wl]?.name??"")+" "),Ro(0);return}if(p.return){let c=rn[wl];if(c){let m=w.trim().slice(1).split(/\s+/).slice(1).join(" ");if(Zm(c.usage)&&!m){k("/"+c.name+" "),Ro(0);return}Xr("/"+c.name+(m?" "+m:""));return}}}else{if(!w&&fe.length>0&&!At.current&&(p.upArrow||p.downArrow)){if(p.downArrow){jr(c=>c===null?0:Math.min(fe.length-1,c+1));return}if(So!==null){jr(c=>c===null||c===0?null:c-1);return}}if(p.upArrow){if(w!==""&&Co===null){hi(-1);return}let c=yl.current;if(!c.length)return;let m=Co===null?c.length-1:Math.max(0,Co-1);Xs(m),k(c[m]??"");return}if(p.downArrow){if(w!==""&&Co===null){hi(1);return}let c=yl.current;if(Co===null)return;let m=Co+1;m>=c.length?(Xs(null),k("")):(Xs(m),k(c[m]??""));return}}if(p.return){if(So!==null&&!w&&fe[So]){let c=Fn(fe[So]);jr(null),Xr(c);return}Xr();return}if(p.backspace||p.delete){v();return}if(p.escape){k(""),Ro(0),_t(),se([]),jo(null),jr(null),ee.current=!0;return}u&&!p.ctrl&&!p.meta&&fh(u)}}}),at(()=>{if(C||D)return;let u=Kn.current.shift();u!==void 0&&(kl([...Kn.current]),Xr(u))},[C,D,Xr]),ue(je,{flexDirection:"column",width:st,children:[Il!==null&&ue(je,{marginTop:1,flexDirection:"column",children:[Il.truncated&&V(Y,{dimColor:!0,children:"\u2026"}),V(Y,{children:Il.text})]}),C&&Lo?V(GD,{p:Lo}):null,Vp?V(BD,{text:Vp}):C&&!Lo?V(WD,{startTime:Et.current,chars:Ae}):null,V(je,{borderStyle:"round",borderColor:rh.prod?"yellow":ae,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:w?mh.map((u,p)=>{let c=d.text.slice(u.start,u.end),m=p===pl(mh,d.pos),A=Math.min(d.pos,u.end)-u.start;return ue(Y,{children:[V(Y,{color:ae,children:p===0?"> ":" "}),m?ue(Ar,{children:[c.slice(0,A),V(Tr,{ch:c[A]??" "}),c.slice(A+1)]}):c||" "]},`${p}-${u.start}`)}):ue(Y,{children:[V(Y,{color:ae,children:"> "}),Wr?V(Tr,{ch:" "}):$e&&!C?ue(Ar,{children:[V(Tr,{ch:$e[0],dim:!0}),V(Y,{color:"gray",children:$e.slice(1)})]}):de&&!C?ue(Ar,{children:[V(Tr,{ch:de[0],dim:!0}),V(Y,{color:"gray",children:de.slice(1)}),V(Y,{dimColor:!0,children:" (tab)"})]}):(Dl.isSetup||!Dr)&&!C?ue(Ar,{children:[V(Tr,{ch:Dl.text[0],dim:!0}),V(Y,{color:"gray",children:Dl.text.slice(1)})]}):V(Tr,{ch:" "})]})}),Gp.length>0&&V(je,{flexDirection:"column",paddingX:1,children:Gp.map((u,p)=>V(Y,{color:"gray",children:`\u29D7 queued: ${u}`},`${p}-${u.slice(0,24)}`))}),Ur?V(bb,{tab:Ur.tab,scroll:Ur.scroll,rows:vk,width:st,version:o,engineVersion:ck}):wn?ue(je,{flexDirection:"column",paddingX:1,children:[V(Y,{color:ae,bold:!0,children:"Select model"}),V(Y,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),Pt.map((u,p)=>ue(Y,{color:p===wn.cursor?ae:void 0,children:[p===wn.cursor?"\u276F ":" ",`${p+1}. ${u.label}${p===wn.current?" \u2714":""}`.padEnd(16),V(Y,{color:"gray",children:` ${u.desc}`})]},u.label)),V(Y,{dimColor:!0,children:ft({verb:"set as default",rows:Pt.length,extra:["s this session only"]})})]}):jt?ue(je,{flexDirection:"column",paddingX:1,children:[V(Y,{color:ae,bold:!0,children:"Switch connection profile"}),V(hn,{rows:jt.rows,cursor:jt.cursor,cap:qt,render:(u,p,c)=>ue(Y,{color:c?ae:void 0,children:[c?"\u276F ":" ",`${p+1}. ${u.name}${p===jt.current?" \u2714":""}`.padEnd(20),V(Y,{color:"gray",children:` ${u.env} \xB7 ${u.who??"not signed in"}`}),u.prod?V(Y,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},u.name)}),V(Y,{dimColor:!0,children:ft({verb:"switch (saved as default)",rows:jt.rows.length,extra:["s this session only"]})})]}):It?ue(je,{flexDirection:"column",paddingX:1,children:[V(Y,{color:ae,bold:!0,children:"Pick your Document360 environment"}),V(hn,{rows:It.rows,cursor:It.cursor,cap:qt,render:(u,p,c)=>ue(Y,{color:c?ae:void 0,children:[c?"\u276F ":" ",`${p+1}. ${u.name}`.padEnd(16),V(Y,{color:"gray",children:` ${u.apiUrl}`}),u.note?V(Y,{color:"yellow",children:` \u26A0 ${u.note}`}):null]},u.name)}),V(Y,{dimColor:!0,children:ft({verb:"use it",rows:It.rows.length})})]}):Ke?ue(je,{flexDirection:"column",paddingX:1,children:[V(Y,{color:ae,bold:!0,children:"Switch workspace"}),V(Y,{dimColor:!0,children:`environment ${Ke.environment} \xB7 project ${Ke.projectName??`${Ke.projectId.slice(0,8)}\u2026`}`}),V(hn,{rows:Ke.rows,cursor:Ke.cursor,cap:qt,render:(u,p,c)=>ue(Y,{color:c?ae:void 0,children:[c?"\u276F ":" ",`${p+1}. ${u.name}${p===Ke.current?" \u2714":""}`.padEnd(30),V(Y,{color:"gray",children:u.type?` ${u.type}`:""})]},u.id)}),V(Y,{dimColor:!0,children:ft({verb:"switch",rows:Ke.rows.length})})]}):nt?ue(je,{flexDirection:"column",paddingX:1,children:[V(Y,{color:ae,bold:!0,children:"Choose project"}),V(Y,{dimColor:!0,children:`environment ${nt.environment}`}),V(hn,{rows:nt.rows,cursor:nt.cursor,cap:qt,render:(u,p,c)=>ue(Y,{color:c?ae:void 0,children:[c?"\u276F ":" ",`${p+1}. ${u.name}${p===nt.current?" \u2714":""}`.padEnd(30),V(Y,{color:"gray",children:u.sub?` ${u.sub}`:""})]},u.id)}),V(Y,{dimColor:!0,children:ft({verb:"switch",rows:nt.rows.length})})]}):ot?(()=>{let p=Math.min(Math.max(0,ot.cursor-Math.floor(7)),Math.max(0,ot.rows.length-14)),c=ot.rows.slice(p,p+14),m=ot.rows.filter(A=>A.checked).length;return ue(je,{flexDirection:"column",paddingX:1,children:[V(Y,{color:ae,bold:!0,children:`Which folders back the user docs? (${m} selected of ${ot.rows.length})`}),p>0?V(Y,{dimColor:!0,children:` \u2191 ${p} more`}):null,c.map((A,W)=>{let G=p+W;return ue(Y,{color:G===ot.cursor?ae:void 0,children:[G===ot.cursor?"\u276F ":" ",A.checked?"\u25C9 ":"\u25CB ",A.path.padEnd(Math.min(48,st-34)),V(Y,{color:"gray",children:ra(A)})]},A.path)}),p+14<ot.rows.length?V(Y,{dimColor:!0,children:` \u2193 ${ot.rows.length-p-14} more`}):null,V(Y,{dimColor:!0,children:ft({verb:"save",multi:!0})})]})})():lt?ue(je,{flexDirection:"column",paddingX:1,children:[V(Y,{color:ae,bold:!0,children:lt.title??"Which category? (pick one to scope to)"}),V(hn,{rows:lt.rows,cursor:lt.cursor,cap:qt,render:(u,p,c)=>ue(Y,{color:c?ae:void 0,children:[c?"\u276F ":" ",`${`${p+1}.`.padEnd(3)} ${u.label} (${u.count})`.padEnd(Math.min(44,Math.max(20,st-24))),V(Y,{color:"gray",children:` ${u.token}`})]},u.token)}),V(Y,{dimColor:!0,children:ft({verb:"choose it",rows:lt.rows.length})})]}):wt?ue(je,{flexDirection:"column",paddingX:1,children:[V(Y,{color:ae,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),V(hn,{rows:wt.rows,cursor:wt.cursor,cap:qt,render:(u,p,c)=>ue(Y,{color:c?ae:void 0,bold:u.kind==="category"&&!c,children:[c?"\u276F ":" ",`${u.indent?" ":" "}${`${p+1}.`.padEnd(3)} ${u.label}`.padEnd(Math.min(56,st-24)),u.note?V(Y,{color:"gray",children:` ${u.note}`}):null]},`${u.kind}:${u.paths.join(",")}`)}),V(Y,{dimColor:!0,children:ft({verb:"push as drafts",rows:wt.rows.length})})]}):Lt?ue(je,{flexDirection:"column",paddingX:1,children:[V(Y,{color:ae,bold:!0,children:"Publish live to your readers \u2014 this is what they will see:"}),V(hn,{rows:[{path:"",articleId:"",label:`Publish all ${Lt.rows.length} live`,version:void 0},...Lt.rows],cursor:Lt.cursor,cap:qt,render:(u,p,c)=>ue(Y,{color:c?ae:void 0,bold:p===0&&!c,children:[c?"\u276F ":" ",` ${`${p+1}.`.padEnd(3)} ${u.label}`.padEnd(Math.min(56,st-24)),p>0?V(Y,{color:"gray",children:` ${u.version?`draft v${u.version} \u2192 live`:"draft \u2192 live"}`}):null]},`${p}:${u.path||"all"}`)}),V(Y,{dimColor:!0,children:ft({verb:"publish live",cancel:"leave as drafts",rows:Lt.rows.length+1})})]}):yt?ue(je,{flexDirection:"column",paddingX:1,children:[V(Y,{color:ae,bold:!0,children:"Which comments do you want to look at?"}),V(hn,{rows:yt.rows,cursor:yt.cursor,cap:qt,render:(u,p,c)=>ue(Y,{color:c?ae:void 0,bold:u.kind==="all"&&!c,children:[c?"\u276F ":" ",`${(u.kind==="all"?"":`${u.n}.`).padEnd(4)}${u.label}`.padEnd(Math.min(56,Math.max(20,st-24))),u.kind==="article"?V(Y,{color:"gray",children:u.note}):null]},u.kind==="all"?"all":u.group.articleId)}),V(Y,{dimColor:!0,children:ft({verb:"open it",cancel:"close",rows:yt.rows.length-1})}),yt.resolve?V(Y,{dimColor:!0,children:"--resolve is on: threads you answer will be closed as well as replied to"}):null]}):Qe?ue(je,{flexDirection:"column",paddingX:1,children:[V(Y,{color:ae,bold:!0,children:`${Qe.group.title} \u2014 ${Qe.group.threads.length} comment${Qe.group.threads.length===1?"":"s"}`}),ue(Y,{color:Qe.cursor===0?ae:void 0,children:[Qe.cursor===0?"\u276F ":" ",Qe.resolve?"Yes \u2014 fix them, push the draft, reply and resolve":"Yes \u2014 fix them, push the draft to Document360, then reply"]}),ue(Y,{color:Qe.cursor===1?ae:void 0,children:[Qe.cursor===1?"\u276F ":" ",Qe.fromList?"No \u2014 back to the list":"No \u2014 leave them for now"]}),V(Y,{dimColor:!0,children:ft({verb:"open it",cancel:"go back",extra:["y answer"]})})]}):Ot?ue(je,{flexDirection:"column",paddingX:1,children:[V(Y,{color:ae,bold:!0,children:Ot.title}),(()=>{let{rows:u,cursor:p}=Ot,c=rl(u.length,p,qt),m=c.start,A=u.slice(c.start,c.end),W=`${u.length}.`.length+1,G=nm(u,Math.max(20,st-4-W));return ue(Ar,{children:[m>0?V(Y,{color:"gray",children:` \u2026 ${m} more above`}):null,A.map((y,$)=>{let R=m+$,b=R===p,x=G[R];return ue(Y,{color:b?ae:void 0,bold:(y.kind==="all"||y.kind==="category")&&!b,children:[b?"\u276F ":" ",`${R+1}.`.padEnd(W),x.head,x.note?V(Y,{color:"gray",children:x.note}):null]},`${y.action}:${y.kind}:${y.ids.join(",")}`)}),c.below>0?V(Y,{color:"gray",children:` \u2026 ${c.below} more below`}):null]})})(),V(Y,{dimColor:!0,children:ft({verb:"run it",rows:Ot.rows.length})})]}):bt?ue(je,{flexDirection:"column",paddingX:1,children:[V(Y,{color:ae,bold:!0,children:`Preview article${bt.query?` \u2014 filter: ${bt.query}`:" (type to filter)"}`}),si.length===0?V(Y,{color:"gray",children:"no articles match"}):si.map((u,p)=>ue(Y,{color:p===bt.cursor?ae:void 0,children:[p===bt.cursor?"\u276F ":" ",u]},u)),V(Y,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):kt?ue(je,{flexDirection:"column",paddingX:1,children:[V(Y,{color:ae,bold:!0,children:`Resume session${kt.query?` \u2014 filter: ${kt.query}`:" (type to filter)"}`}),ii.length===0?V(Y,{color:"gray",children:"no sessions match"}):ii.map((u,p)=>ue(Y,{color:p===kt.cursor?ae:void 0,children:[p===kt.cursor?"\u276F ":" ",u.name.slice(0,28).padEnd(30),V(Y,{color:p===kt.cursor?ae:"gray",children:u.firstPrompt.slice(0,Math.max(10,st-40))})]},u.uuid)),V(Y,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):sh?ue(je,{flexDirection:"column",children:[eo>0?V(Y,{dimColor:!0,children:` \u22EF ${eo} more above`}):null,jl.map((u,p)=>{let c=eo+p,m=u.name==="model"&&vl?`${u.desc} (currently ${vl})`:u.desc,A=Math.max(20,st-4),W=u.usage.length>A?`${u.usage.slice(0,A-1)}\u2026`:u.usage,G=A-Math.max(W.length,22)-1,y=G<=1?"":m.length>G?`${m.slice(0,G-1)}\u2026`:m;return ue(Y,{color:c===ri?ae:void 0,children:[c===ri?"\u276F ":" ",W.padEnd(22)," ",V(Y,{color:c===ri?ae:"gray",children:y})]},u.name)}),eo+jl.length<rn.length?V(Y,{dimColor:!0,children:` \u22EF ${rn.length-eo-jl.length} more below`}):null,V(Y,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!C&&!w&&fe.length>0?ue(je,{flexDirection:"column",paddingX:1,children:[Hp?V(Y,{color:ae,children:Hp}):null,V(hn,{rows:fe,cursor:So??0,cap:qt,render:(u,p)=>{let c=p===So,m=Fn(u),A=m.slice(0,Math.max(20,st-7)),W=st-A.length-9,G=W>=12?(vb(u)??Qm(m)).slice(0,W):"";return ue(Y,{color:c?ae:void 0,children:[c?"\u276F ":" ",V(Y,{color:ae,children:p+1})," ",A,G?V(Y,{color:c?ae:void 0,dimColor:!c,children:` \u2014 ${G}`}):null]},m)}}),V(Y,{dimColor:!0,children:`\u2191\u2193 choose \xB7 enter run \xB7 1-${fe.length} fill \xB7 esc cancel`})]}):V(je,{paddingX:1,children:ue(Y,{color:"gray",children:[rh.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${vl??"model n/a"}${t.kind==="api"?Br>0?` \xB7 session ${St(Br)}`:"":Kp>0?` \xB7 ${cr(Kp)}`:""} \xB7 \u2191 history \xB7 ${wk?"press ctrl+c again to exit":"ctrl+c twice to exit"}`]})})]})}re();import{jsx as KD}from"react/jsx-runtime";async function dk(e=process.cwd(),t="auto",n,o="0.0.0"){let r=YD(t);r.kind==="none"&&(console.error(""),console.error(O("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${Z("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${Z("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=VD(KD(uk,{cwd:e,auth:r,profileName:n,version:o}),{exitOnCtrlC:!1});await s(),process.stdout.write(`
557
- `),process.exit(0)}re();import{writeCrashLog as Ip,isBenignTransportError as zD}from"document360-engine";var pk=!1;function XD(e=process.stdout){return e.destroyed===!0||e.writable===!1}function Lp(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function hk(e){if(pk)return;pk=!0;let t=(n,o)=>{if(zD(o)){Ip({kind:n,level:"transport",message:Lp(o),stack:o instanceof Error?o.stack:void 0,detail:e}),XD()&&(Ip({kind:"terminal-gone",level:"transport",message:"stdout is closed \u2014 the terminal this session was rendering to is gone, so it exited rather than spin.",detail:e}),process.exit(0));return}let r=Ip({kind:n,level:"fatal",message:Lp(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
558
- `+O(`\u2717 d360-writer crashed: ${Lp(o)}`)+`
522
+ Not blocked: /write <path> still authors a single article, and /write --preview costs nothing.`}),se(Va.options.map(X=>({cmd:X.cmd,desc:X.desc}))),Lo(Va.title);return}let{docsDir:j,targets:I,reason:E,rewriting:Y}=ka(e,b,{scope:k,path:x,rewrite:P});if(I.length===0){h({kind:"note",tone:"warn",text:E??"Nothing to write."});return}Y&&h({kind:"note",tone:"warn",text:`--rewrite: regenerating ${I.length} already-written article${I.length===1?"":"s"} (overwrites them; git has your baseline).`});let M=Ep(I),F=Iu(v),G=zs(e,"standard"),ee=!!x;if(y&&!ee){let X=nk({files:Lu(e,b,I),op:"write",model:G.model}),ve=k?`Scope: ${k} (${I.length} pending)
523
+ `:"",Ie=`
524
+ Model: ${G.model}${G.forced?" (forced)":" \u2014 authoring; /model to override"}`;h({kind:"note",tone:"info",text:ve+_u(M,X,F).join(`
525
+ `)+Ie}),oe(`/write${k?` --scope ${k}`:""}`);return}Et.current=Date.now(),Ue(0),A(!0);let ce=new AbortController;Oe.current=ce;let he=Date.now();pe({verb:"Writing",total:M.length,done:0,active:[],rows:$o(M),tools:0,chars:0,lastAt:Date.now(),startedAt:he}),h({kind:"note",tone:"info",text:`Writing ${I.length} article${I.length===1?"":"s"} in ${M.length} batch${M.length===1?"":"es"} (\u2264${F} agents at once) on ${G.model}${G.forced?" (forced)":""}\u2026 (esc to stop)`});let me=new Set;try{for await(let X of Ks({cwd:e,partitions:M,promptFor:ve=>Ou(ve,j,{rewrite:Y||ee}),concurrency:F,profileName:s,allowProdWrites:gn.current,model:G.model,signal:ce.signal}))if(X.type==="partition_status")X.status==="running"?pe(ve=>ve&&{...ve,active:[...ve.active,X.label],rows:Ve(ve.rows,X.label,"active"),lastAt:Date.now()}):pe(ve=>ve&&{...ve,active:ve.active.filter(Ie=>Ie!==X.label),done:ve.done+1,rows:Ve(ve.rows,X.label,X.status==="done"?"done":"failed"),lastAt:Date.now()});else if(X.type==="partition_stalled"){let ve=xr(X);pe(Ie=>Ie&&ve?{...Ie,stalledNote:ve}:Ie)}else if(X.type==="partition_event"){let ve=null;if(X.event.type==="tool"){let Ie=Rp(X.event.name,X.event.input,M[X.index]?.paths??[]);Ie&&!me.has(Ie)&&(me.add(Ie),ve=X.label)}pe(Ie=>{if(!Ie)return Ie;let Ft={...Ie,lastAt:Date.now()};return X.event.type==="tool"?Ft.tools=Ie.tools+1:X.event.type==="text"&&(Ft.chars=Ie.chars+X.event.delta.length),ve&&(Ft.rows=ul(Ft.rows,ve)),Ft})}else if(X.type==="run_done"){Zn(et=>et+X.totalCostUsd),Jn(et=>et+X.results.reduce(($t,ro)=>$t+ro.outputTokens,0));let ve=X.aborted?"Stopped. ":"",Ie=t.kind==="api"?"api":"subscription",Ft=Tn(X,"The write");if(h({kind:"note",tone:Ft||X.aborted?"warn":X.ok?"ok":"warn",text:Ft?Ft.join(`
526
+ `):ve+Mu(X.results,M,Ie,k??x).join(`
527
+ `)}),Bo(he,X.results,X.totalCostUsd,!Ft&&!X.aborted&&X.ok),Ft){oe("/doctor");continue}let xh=Jm(X);if(xh&&h({kind:"note",tone:"warn",text:xh}),!X.aborted&&X.ok)try{let et=(me.size>0?[...me]:I).map($t=>`${j}/${$t}`);Tr(e,et,{writtenCap:PD,reviewedCap:0,checkedCap:0})}catch{}let oo=X.aborted?[]:fr(e,j,I),Rh=Fu(oo);Rh&&h({kind:"note",tone:"warn",text:Rh});let Vo=X.aborted||g.includes("--skip-style")?null:Uu(oo);if(Vo){let et=Vo.errors.length,$t=await li({partitions:Vo.partitions,promptFor:Vo.promptFor,concurrency:dr,verb:"Fixing",doneNoun:"fixed",headline:`${et} style error${et===1?"":"s"} in ${Vo.articles} of the new article${Vo.articles===1?"":"s"} \u2014 fixing now, one pass`});if($t.covered.length>0)try{Tr(e,$t.covered,it("lint"))}catch{}oo=fr(e,j,I);let ro=Wu(et,oo);h({kind:"note",tone:ro[0].startsWith("\u2713")?"ok":"warn",text:ro.join(`
528
+ `)})}if(!X.aborted&&X.ok){let et=k??x??"",$t=et?` ${et}`:"",ro=oo.some(Yo=>Yo.severity==="error");{let Yo=Np(M,X.results);yn(`/write${k?` --scope ${k}`:""}${g.includes("--rewrite")?" --rewrite":""}`,{aborted:X.aborted,partitions:M.length,failed:Yo.failed.length,notRun:Yo.notRun.length,leftBehind:oo.filter(Ik=>Ik.severity==="error").length,...X.blocked?{blocked:X.blocked}:{},...X.allEmpty?{allEmpty:!0}:{},...X.bailedEmpty?{bailedEmpty:!0}:{}})}let Ch=et?"/push":"/push --all",jk=et?`/screenshot author ${et}`:"/screenshot author --all";Ee(ro?`Written, but ${oo.filter(Yo=>Yo.severity==="error").length} style error(s) are still unfixed. /lint${$t} --blocked --fix retries them, then /review${$t} --fix for editorial quality, then ${Ch}.`:`Written. I\u2019d run /review${$t} --fix next \u2014 editorial review that applies its fixes \u2014 then ${Ch} saves them to Document360 as drafts (add ${jk} first if you want images).`,{kind:"cmd",cmd:ro?`/lint${$t} --blocked --fix`:`/review${$t} --fix`,reason:""})}}}catch(X){h({kind:"note",tone:"error",text:`Write run failed: ${X.message}`})}finally{Oe.current=null,pe(null),A(!1),O(X=>X+1)}return}case"draft":{if(!Se(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:b,looseDocs:k}=Hu(e);if(b.length===0&&k===0){h({kind:"note",tone:"info",text:qu});return}let x=g.join(" ").trim();if(!x&&b.length>1){h({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
529
+ ${b.map(P=>` \u2022 ${P.name} (${P.docCount} doc${P.docCount===1?"":"s"})`).join(`
530
+ `)}`}),se(b.map(P=>`/draft ${P.name}`));return}let y="",v;if(x){let P=Gu(b,x);P?y=P:v=x}else y=b[0]?.name??"";await Te($a(y,v),{display:x?`/draft ${x}`:"/draft",quietUser:!0});return}case"pull":{if(!eo(u.trim()))return;let b=g.find(k=>k.startsWith("--"));try{if(b==="--status"){h({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let y=Date.now(),v=await gl({cwd:e,profileName:s});h({kind:"note",tone:"info",text:ia(v,Date.now()-y).join(`
531
+ `)});return}if(b==="--baseline"){let y=g.find(I=>!I.startsWith("--")),v=y?y.replace(/\\/g,"/"):void 0;h({kind:"note",tone:"info",text:v?`Setting the sync baseline for ${v}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let P=await hD({cwd:e,profileName:s,relPaths:v?[v]:void 0}),j=v?{rebaselined:[],skipped:[]}:await fD({cwd:e,profileName:s});if(P.baselined.length===0&&P.skipped.length===0&&j.rebaselined.length===0){h({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}P.baselined.length>0&&h({kind:"note",tone:"ok",text:`\u2713 Recorded ${P.baselined.length} article${P.baselined.length===1?"":"s"} as matching Document360 \u2014 they read in-sync until either side changes.`}),j.rebaselined.length>0&&h({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${j.rebaselined.length} article${j.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),P.skipped.length>0&&h({kind:"note",tone:"warn",text:`${P.skipped.length} skipped:
532
+ ${P.skipped.map(I=>` - ${I.path} (${I.reason})`).join(`
533
+ `)}`}),O(I=>I+1);return}if(b==="--compare"){h({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let y=await lD({cwd:e,profileName:s}),v=y.onlyInLegacy.length===0&&y.onlyInManifest.length===0&&y.mappedMissingFromManifest.length===0,P=[`Legacy listing: ${y.legacyCount} \xB7 Manifest: ${y.manifestCount} \xB7 in both: ${y.inBoth}`];v?P.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(y.mappedMissingFromManifest.length&&P.push(`\u2717 ${y.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${y.mappedMissingFromManifest.slice(0,5).join(", ")}`),y.onlyInLegacy.length&&P.push(`\u26A0 ${y.onlyInLegacy.length} only in the legacy listing: ${y.onlyInLegacy.slice(0,5).join(", ")}`),y.onlyInManifest.length&&P.push(`\u26A0 ${y.onlyInManifest.length} only in the manifest: ${y.onlyInManifest.slice(0,5).join(", ")}`),P.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),h({kind:"note",tone:v?"ok":"warn",text:P.join(`
534
+ `)});return}if(b){h({kind:"note",tone:"error",text:`Unknown option: ${b} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let k=g[0];if(k){let y=k.replace(/\\/g,"/"),v;try{let P=await Qb({cwd:e,profileName:s,relPath:y});v={plan:P,mode:P.overwritesLocalChanges?"conflict":"pull"}}catch(P){if(!Jb(P))throw P;v={mode:"local-only",path:y,title:Zb(e,y)}}De.current=[v],Dt.current=[],Zt.current=[],Ho();return}h({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let x=await su({cwd:e,profileName:s});for(let y of iu(x))h({kind:"note",tone:y.tone,text:y.text});O(y=>y+1)}catch(k){h({kind:"note",tone:"error",text:`Pull failed: ${k.message}`})}return}case"scope":{if(!Se(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let b=mD(e);if(b.length===0){h({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.'});return}Oo({cursor:0,rows:b.map(k=>({...k,checked:k.recommended}))});return}case"audit":{if(g[0]==="--auto"){let k=Se(e);if(!k){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let x=g[1]!=="off";Yb({...k,autoAudit:x},e),h({kind:"note",tone:"ok",text:x?"\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}if(!eo(u.trim()))return;let b=await fs({cwd:e,profileName:s});if(b.kind==="audit-blocked"){Ee(b.note,{kind:"cmd",cmd:b.lead.cmd,reason:b.lead.reason},"warn");return}if(b.kind==="forward-to-agent"&&b.prompt){let k=await Te(b.prompt,{display:b.display,quietUser:!0}),x=ra(e,s);if(x){Ee(x.note,{kind:"cmd",cmd:ir.cmd,reason:ir.reason},"warn"),O(y=>y+1);return}k.producedNothing||(Us(e,s),O(y=>y+1))}return}case"lint":case"check":{let b=cn(c);b&&h({kind:"note",tone:"info",text:`\u2192 ${b}`});let k=g.find(P=>!P.startsWith("--")),x=k?` ${k}`:"",y=Pr({cwd:e,scope:k}),v=dn(y,g);if(g.includes("--fix")){let P=pr(e,g,y);P.lines.length>0&&h({kind:"note",tone:"ok",text:P.lines.join(`
535
+ `)});let j=P.fixed>0?Pr({cwd:e,scope:k}):y,I=Tu(e,g,j);if(!I){let X=Au(e,g,j);h({kind:"note",tone:"ok",text:X.lines.join(`
536
+ `)});for(let ve of X.closed)h({kind:"note",tone:"ok",text:ve});return}let E={aborted:!1,partitions:0,failed:0,notRun:0};if(I.kind==="partitioned"){let X=await li({partitions:I.partitions,promptFor:I.promptFor,concurrency:dr,verb:"Fixing",doneNoun:"fixed",headline:`Fixing ${I.findings} issue${I.findings===1?"":"s"} across ${I.articles} article${I.articles===1?"":"s"} in ${I.partitions.length} batches (\u2264${dr} at once)`,calibrateAs:"/lint"});if(E=X.outcome,X.covered.length>0)try{Tr(e,X.covered,it("lint"))}catch{}if(X.aborted){let ve=ys({cwd:e,after:dn(Pr({cwd:e,scope:k}).filter(Ie=>!Ie.baselined),g),scope:k,aborted:!0,blocked:un(g)});Ee(ve.text,{kind:"cmd",cmd:ve.cmd,reason:""},"warn");return}}else{h({kind:"note",tone:"info",text:`Fixing ${I.findings} doc issue${I.findings===1?"":"s"}\u2026`});let X=SD(e,k);await Te(I.prompt,{display:I.display,quietUser:!0});try{Tr(e,X,it("lint"))}catch{}}let Y=dn(Pr({cwd:e,scope:k}).filter(X=>!X.baselined),g),M=dn(j.filter(X=>!X.baselined),g),F=new Set(Y.map(X=>X.fp)),G=new Set(M.map(X=>X.fp)),ee=M.filter(X=>!F.has(X.fp)).length,ce=Y.filter(X=>!G.has(X.fp)).length,he=ce>0?`
537
+ \u26A0 ${ce} new ${ce===1?"issue":"issues"} appeared in the rewrites \u2014 recasting a sentence is where these come from.`:"";h({kind:"note",tone:Y.some(X=>X.severity==="error")?"warn":"ok",text:Y.length===0?`\u2713 Lint: all ${M.length} issue${M.length===1?"":"s"} resolved.`:[`\u2713 Lint: fixed ${ee} of ${M.length}.${he}`,"",...ks(Y)].join(`
538
+ `)}),yn(bs(g,k),I.kind==="partitioned"?E:{aborted:!1,partitions:0,failed:0,notRun:0,verifiedComplete:Y.length===0});let me=ys({cwd:e,after:Y,before:I.findings,scope:k,blocked:un(g)});Ee(me.text,{kind:"cmd",cmd:me.cmd,reason:""});return}if(h({kind:"note",tone:v.length===0?"ok":"warn",text:ks(v,{full:g.includes("--full"),baselined:g.includes("--baselined")}).join(`
539
+ `)}),v.length>0){let P=ea(e,k)===0&&ta(e,k)===0?"; /push --all saves them to Document360 as-is":"",j=`/lint${x}${un(g)?" --blocked":""} --fix`,I=On(e,j);Ee(`Found ${v.length} doc issue${v.length===1?"":"s"} above. ${j} has the agent fix them in place${I?` (${I})`:""} \u2014 or /review${x} --fix for the full editorial pass${P}.`,{kind:"cmd",cmd:j,reason:""})}return}case"structure":{let b=Ms(e,s);if(b.length===0){h({kind:"note",tone:"info",text:"No documentation structure yet \u2014 run /init and author some articles first."});return}h({kind:"note",tone:"info",text:["Documentation order (categories \u2192 articles):","",...b].join(`
540
+ `)});return}case"status":{let b=g.some(k=>k==="--all"||k==="--full");h({kind:"block",text:tp(e,{profileName:s,all:b,width:qe()}).join(`
541
+ `)}),te.current=!0;return}case"retire":{let b=g.find(x=>!x.startsWith("-"));if(!b){h({kind:"block",text:np(e,s).join(`
542
+ `)}),te.current=!0;return}let k=MD(e,b)||b;if(!g.includes("--yes")&&!g.includes("-y")){h({kind:"note",tone:"warn",text:[`\u26A0 This takes "${k}" off your readers on Document360.`," The article, its history and every reviewer comment stay \u2014 nothing is deleted."," /push puts it back later if you change your mind."].join(`
543
+ `)}),Je(`/retire ${k} --yes`,"tab to take it off your readers \xB7 or keep typing");return}A(!0);try{let x=await _D({cwd:e,path:k,profileName:s,now:new Date().toISOString()});h(x.ok?{kind:"note",tone:"ok",text:x.alreadyHidden?`\u2713 "${k}" was already invisible to readers. Recorded as retired, so nothing will offer to publish it again.
544
+ It stays on Document360 with its history and comments intact. /push puts it back.`:`\u2713 "${k}" is no longer visible to your readers.
545
+ It stays on Document360 with its history and comments intact. /push puts it back.`}:{kind:"note",tone:"error",text:`\u2717 Could not retire "${k}" \u2014 ${x.error.message}`})}finally{A(!1)}return}case"terms":{let b=g.findIndex(k=>k==="--approve");if(b!==-1){let k=g[b+1];h(k?{kind:"block",text:sp(e,k.replace(/^["']|["']$/g,"")).lines.join(`
546
+ `)}:{kind:"note",tone:"warn",text:'\u2717 Name the spelling to approve, e.g. /terms --approve "drop-down".'}),te.current=!0;return}h({kind:"block",text:rp(e,{...g.find(k=>!k.startsWith("--"))?{scope:g.find(k=>!k.startsWith("--"))}:{},all:g.includes("--all")}).join(`
547
+ `)}),te.current=!0;return}case"reorder":{let b=Zd(e,g);if(!b){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let k=await Te(b.prompt,{display:b.display,quietUser:!0}),x=Bt(e,{text:"Reordered locally \u2014 /push --all syncs the new order to Document360.",cmd:"/push --all"},"Reordered locally. ");Fo(k,x.text,{kind:"cmd",cmd:x.cmd,reason:""});return}case"review":{let b=Qd(e,g);if(b){h({kind:"note",tone:"ok",text:b.lines[0]});for(let I of b.closed)h({kind:"note",tone:"ok",text:I});Ee(b.cta.text,{kind:"cmd",cmd:b.cta.cmd,reason:""});return}let k=Xd(e,g);if(!k){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let x=g.includes("--fix"),y=g.find(I=>!I.startsWith("--")),v=x?bo(e,g,y):[],P={aborted:!1,partitions:0,failed:0,notRun:0},j;if(k.kind==="partitioned"){let I=await Ak(k,x);P=I.outcome,j=I}else j=await Te(k.prompt,{display:k.display,quietUser:!0}),P={...P,producedNothing:j.producedNothing};if("aborted"in j&&j.aborted){let I=g.includes("--blocked")?"--blocked --fix":g.includes("--stale")?"--stale --fix":"--fix",E=Ce("/review",I,y);Ee(`Stopped \u2014 the batches that finished are saved. ${E} picks up the rest${y||Fs(g)?"":", or narrow it with /review <category> --fix"}.`,{kind:"cmd",cmd:E,reason:""},"warn");return}if(k.kind!=="partitioned"&&x&&!j.producedNothing)try{Tr(e,v,it("review"))}catch{}if(x&&yn(`/review${y?` ${y}`:""}${g.includes("--all")?" --all":""}${g.includes("--blocked")?" --blocked":g.includes("--stale")?" --stale":""} --fix`,P),x){if(x&&!j.producedNothing){let Y=pr(e,["--fix"],Pr({cwd:e,scope:y}));Y.lines.length>0&&h({kind:"note",tone:"ok",text:Y.lines.join(`
548
+ `)})}let I=x&&!j.producedNothing?Pr({cwd:e,scope:y}).filter(Y=>!Y.baselined&&Y.severity==="error"):[];if(I.length>0){let Y=new Set(I.map(G=>G.path)).size,M=`/lint${y?` ${y}`:""} --blocked --fix`,F=On(e,M);h({kind:"note",tone:"warn",text:`\u26A0 The editor's rewrites left ${I.length} style error${I.length===1?"":"s"} in ${Y} article${Y===1?"":"s"} \u2014 recasting a sentence is where these appear.`}),Fo(j,`Editor applied its fixes, but ${I.length} style error${I.length===1?"":"s"} remain. ${M} clears ${I.length===1?"it":"just those"} \u2014 it costs nothing to find them and one pass to correct${F?` (${F})`:""}. It is the last paid pass before publishing: anything still standing after a second attempt is reported for a person rather than run again.`,{kind:"cmd",cmd:M,reason:""});return}let E=Bt(e,{text:`\u2713 Editor applied its fixes \u2014 your docs are corrected. /push${y?"":" --all"} saves them to Document360 as drafts (or /lint${y?` ${y}`:""} for an instant no-token re-scan first).`,cmd:y?"/push":"/push --all"},"\u2713 Editor applied its fixes to this scope. ",y);Fo(j,E.text,{kind:"cmd",cmd:E.cmd,reason:""})}else{let I=y?` ${y}`:"",E=ea(e,y)===0&&ta(e,y)===0?`; /push${y?"":" --all"} saves them to Document360 as-is`:"";Fo(j,`The review listed issues above. /review${I} --fix lets the editor apply them all (or /lint${I} --fix for just the deterministic ones${E}).`,{kind:"cmd",cmd:`/review${I} --fix`,reason:""})}return}case"capture-setup":{await B();return}case"devhints":{if(!Se(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}h({kind:"note",tone:"info",text:Jo(Qo(e)).join(`
549
+ `)}),on(so()),Kr.current=Ut(e).status==="current",Uo.current=an(e);return}case"discover":{if(!Se(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await Te(Zc(),{display:"/discover",quietUser:!0});return}case"ask":{if(!Se(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let b=g.join(" ").trim();if(b===""){h({kind:"block",text:bd(OD(e)).join(`
550
+ `)});return}try{let k=LD(e,{question:b});h({kind:"note",tone:"ok",text:yd(k.file,Ns(e)).join(`
551
+ `)})}catch(k){h({kind:"note",tone:"warn",text:`Could not file the question: ${k.message}`})}return}case"inbox":{if(!Se(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(gd(e)===0){h({kind:"note",tone:"info",text:"Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)"});return}await Te(wd(),{display:"/inbox",quietUser:!0});return}case"share":{let b=Se(e);if(!b){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let k=g[0]?.trim().toLowerCase();if(k==="status"){for(let y of Ta(e,b))h({kind:"note",tone:y.tone,text:y.text});return}if(k==="on"||k==="off"){for(let y of kd(e,b,k==="on"))h({kind:"note",tone:y.tone,text:y.text});O(y=>y+1);return}if(k){h({kind:"note",tone:"error",text:`Unknown option: ${k} \u2014 use /share, /share status, /share on, or /share off.`});return}h({kind:"note",tone:"info",text:"Exchanging work with your team\u2026"});let x=await Aa(e,b);for(let y of x.lines)h({kind:"note",tone:y.tone,text:y.text});x.changed&&O(y=>y+1);return}case"feedback":{let b=sk(e),k="";try{k=Sr(b)?fl(b,"utf8"):""}catch{k=""}if(!/^## /m.test(k)){h({kind:"note",tone:"info",text:"No open d360-writer feedback to copy \u2014 nothing logged in .d360-writer/tool-feedback.md yet."});return}let x=await gp(k.trim());h({kind:"note",tone:x?"ok":"warn",text:x?"\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 ${b} and copy it manually.`}),x&&Dl(null);return}case"document":{if(!Se(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{push:b,skipReview:k,what:x}=Yu(g);if(!x&&Vu(e)===0){h({kind:"note",tone:"info",text:zu});return}let y=`/document${x?` ${x}`:""}${b?" --push":""}`,v=await Te(Ku(x),{display:y,quietUser:!0});b&&!v.producedNothing&&await hh({skipReview:k});return}case"catch-up":{if(!Se(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!eo(u.trim()))return;let{push:b,skipReview:k}=Rd(g);for(let E of await vd(e))h({kind:"note",tone:E.tone,text:E.text});h({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let x=await Pd({cwd:e,profileName:s});for(let E of Td(x))h({kind:"note",tone:E.startsWith("\u2713")?"ok":E.startsWith("\u2139")?"info":"warn",text:E});let y=js(e);for(let E of Cd(y))h({kind:"note",tone:E.tone,text:E.text});let v=pn(e);h({kind:"note",tone:"info",text:xd(v)});let P=ik(e),j=await Te(Sd(y),{display:`/catch-up${b?" --push":""}`,quietUser:!0}),I=mo(e,P,"","/catch-up");if(b&&!j.producedNothing)await hh({skipReview:k});else if(I.cta)Fo(j,I.cta.text,{kind:"cmd",cmd:I.cta.cmd,reason:""});else{let E=Na({queued:v,hold:y.hold});Fo(j,E.note,E.lead?{kind:"cmd",cmd:E.lead.cmd,reason:E.lead.reason}:null,E.tone)}return}case"comments":{if(!Se(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!eo(u.trim()))return;let b=jd(g);We("Checking Document360 for reviewer comments\u2026"),A(!0);let k=null;try{k=await Da(e,s,{...b.scope,onProgress:(y,v)=>We(`Checking Document360 for reviewer comments\u2026 ${y}/${v}`)})}catch(y){h({kind:"note",tone:"error",text:`Couldn\u2019t read comments from Document360: ${y.message}`})}finally{A(!1),We(null)}if(!k)return;O(y=>y+1);let x=go(k.threads,k.labels);if(k.threads.length===0){h({kind:"note",tone:"ok",text:Ls(k,{showAnswered:b.showAnswered,width:qe()}).join(`
552
+ `)});return}if(b.answer&&(b.all||b.scope.path||b.scope.scope||x.length===1)){Wo(Nd(k,{full:!0,showAnswered:b.showAnswered,width:qe()})),await _l(x,{resolve:b.resolve});return}if(x.length===1){Wo(ja(x[0],{width:qe()})),_r({group:x[0],cursor:0,fromList:!1,resolve:b.resolve,rest:[]});return}Wo(Ls(k,{showAnswered:b.showAnswered,width:qe()})),en({cursor:0,rows:Ia(x),groups:x,resolve:b.resolve,report:k});return}case"update":{Al.current=!0,h({kind:"note",tone:"info",text:"Updating the d360-writer toolchain\u2026 (don\u2019t close this window)"}),Wn(!0);let b=await _a().finally(()=>Wn(!1));b.ok?(h({kind:"note",tone:"ok",text:`\u2713 Updated ${b.packages.join(" + ")} \u2014 run /exit, then relaunch to apply.`}),oe("/exit"),Co("")):(h({kind:"note",tone:"warn",text:`Update failed. ${Oa(b.output)}`}),b.output&&h({kind:"note",tone:"info",text:`${b.output}
553
+
554
+ Full output: ${La()}`}));return}case"screenshot":{let b=as(g),k=io(e);if(k&&b.mode!=="list"&&h({kind:"note",tone:"info",text:k}),b.mode==="capture"){await T(b.rest);return}if(b.mode==="annotate"){await W(b.rest);return}if(b.mode==="checklist"){await B();return}if(b.mode==="verify"){let v=_e(e),P=b.rest.find(E=>!E.startsWith("-")),j=P?[P]:Ss(v);if(P&&!v.some(E=>E.id===P)){h({kind:"note",tone:"error",text:`No screenshot placeholder called "${P}". /screenshot list shows them all.`});return}if(j.length===0){let E=v.filter(M=>M.state==="rejected").length,Y=v.filter(M=>M.state==="verified").length;h({kind:"note",tone:"info",text:E>0?`Nothing left to verify. ${E} shot${E===1?"":"s"} failed verification \u2014 re-capture with /screenshot capture --failed.`:Y>0?`All ${Y} captured shot${Y===1?" is":"s are"} already verified.`:"No captured screenshots to verify yet \u2014 /screenshot capture takes the shots first."});return}h({kind:"note",tone:"info",text:In(j.length)}),await Te(Qt(e,j),{display:P?`/screenshot verify ${P}`:"/screenshot verify",quietUser:!0});let I=mr(e,j);I.length>0&&h({kind:"note",tone:"info",text:I.join(`
555
+ `)});return}if(b.mode==="list"){if(!Se(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let v=Se(e)?.docsDir??Mp,P=Dc(e,b.scope),j=_e(e,P);if(b.picker){if(j.length===0){h({kind:"note",tone:"info",text:"No screenshot placeholders found in the docs."});return}let E=im(j);if(E.length===0){h({kind:"note",tone:"info",text:Yi(j,{docsDir:v}).join(`
556
+ `)});let Y=Ce("/push","--screenshots",P),M=Bt(e,{text:`\u2713 All ${j.length} screenshots are captured. ${Y} saves them into the articles on Document360; /screenshot capture${P?` ${P}`:""} re-captures.`,cmd:Y},`\u2713 All ${j.length} screenshots are captured. `,P);Ee(M.text,{kind:"cmd",cmd:M.cmd,reason:""});return}qn({cursor:0,rows:E,title:"Screenshots \u2014 pick what to author or capture:"});return}h({kind:"note",tone:"info",text:Yi(j,{scope:P,detail:b.detail,docsDir:v}).join(`
557
+ `)}),k&&h({kind:"note",tone:"info",text:k});let I=Nc(j,P);I.key!=="done"&&oe(I.cmd);return}if(b.mode==="single"){await mh(b.id);return}if(!Se(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let x=b.mode==="scope"?b.scope:void 0,y=bD(e,{scope:x}).map(v=>v.id);if(y.length===0){h({kind:"note",tone:"info",text:x?`No screenshot placeholders under ${x}.`:"No screenshot placeholders found in the docs."});return}await fh(y,{setup:b.setup,scope:b.mode==="scope"?b.scope:void 0,runLine:b.mode==="scope"?[`/screenshot author ${b.scope}`,`/screenshot ${b.scope}`]:["/screenshot author --all","/screenshot --all"]});return}case"capture":{await T(g);return}case"reset":{let b=Od(e);if(b.length===0){h({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}Or.current={repoName:Ys(e),targets:b,hadDevhints:Sr(rk(e))},h({kind:"note",tone:"warn",text:Md(e,b).join(`
558
+ `)}),Je(Ys(e));return}default:h({kind:"note",tone:"error",text:`Unknown command: /${c} \u2014 type /help.`})}},[e,r,s,Ho,Bl,h,Ze,Te,ct,Ml,gh]),Qr=ne(u=>{let p=(u??m).trim();if($(""),Xs(null),So(0),p.startsWith("/")){te.current=!1,we.current=!1,$e.current=null,_t(),Lo(null);let g=Sl.current.includes(p);g&&(Sl.current=[]),se(T=>g?[]:Ab(T,p))}if(!p||(mn(!1),At.current=!1,(Or.current||De.current.length>0)&&h({kind:"user",text:p}),yh(p))||wh(p))return;kl.current.push(p);let c=jb(p,Hp.current);if(p.startsWith("/"))h({kind:"user",text:p}),z(!0),Go(c).finally(()=>z(!1));else if(FD(c)){h({kind:"user",text:p});let g=UD(c);if(!g)Te(c,{display:p,quietUser:!0});else{try{WD(e,{title:g,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}Te(`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${g}". 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 "${g}" and the article path(s) you wrote.`,{display:p,quietUser:!0})}}else{let g=bm(e,c);Te(g??c,{display:p})}},[m,yh,wh,Go,Te]),bh=ne(u=>{if(u.length>1){if(u.includes("\x1B"))return;let p=Eb(u);if(Nb(p)){let c=Db(++vk.current,p);Hp.current.set(c,p),S(c)}else S(p);return}S(u)},[S]),qo=Math.max(10,st-6),kh=Pp(()=>pl(d.text,qo),[d.text,qo]),Hl=ne(u=>w(p=>({...p,pos:Math.max(0,Math.min(p.text.length,p.pos+u))})),[]),hi=ne(u=>w(p=>({...p,pos:Lb(pl(p.text,qo),p.pos,u)})),[qo]),Jr=ne(u=>w(p=>({...p,pos:Ob(pl(p.text,qo),p.pos,u)})),[qo]),Nk=["\x1B[H","\x1B[1~","\x1BOH"],Dk=["\x1B[F","\x1B[4~","\x1BOF"],$h=ne((u,p)=>p.leftArrow?(Hl(-1),!0):p.rightArrow?(Hl(1),!0):u&&Nk.includes(u)?(Jr("start"),!0):u&&Dk.includes(u)?(Jr("end"),!0):p.ctrl&&u==="a"?(Jr("start"),!0):p.ctrl&&u==="e"?(Jr("end"),!0):!1,[Hl,Jr]),vh=ne(()=>{if(Oe.current){if(!Oe.current.signal.aborted){let u=(_o?.verb??"work").toLowerCase(),p=_o?.unit??"article";h({kind:"note",tone:"warn",text:`\u238B Stopping the ${u} run (finishing in-flight ${p}s)\u2026`}),Oe.current.abort()}return!0}return Mr.current?!1:(Mr.current=!0,h({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),Nt.current?.interrupt(),!0)},[_o]);return LN((u,p)=>{if(p.ctrl&&u==="c"){if(Fr.current!==null&&Date.now()-Fr.current<pk){Fr.current=null,Nt.current?.close(),r();return}Fr.current=Date.now(),Xp(!0),xl.current&&clearTimeout(xl.current),xl.current=setTimeout(()=>{Fr.current=null,Xp(!1)},pk),C?vh():m&&$("");return}if(Yr.current.awaySince!==null)try{let c=$b(Yr.current,Date.now(),pn(e));if(Yr.current=c.memory,lh(null),c.kind==="delta"){h({kind:"note",tone:"info",text:xb(c.delta,c.awayMs)});let g=Mt(!1);g.kind==="recommend"&&nn(g.rec,{silent:!0})}else if(c.kind==="briefing"){h({kind:"note",tone:"info",text:`\u{1F4E5} ${qs(c.delta)} arrived while you were away (${xp(c.awayMs)}).`});let g=Mt(!1);g.kind==="recommend"&&nn(g.rec)}}catch{}if(jl.current=Date.now(),!D){if(C){if(p.escape){vh();return}if(p.return){let c=m.trim();if(!c)return;Kn.current.push(c),vl([...Kn.current]),$("");return}if($h(u,p))return;if(p.upArrow){hi(-1);return}if(p.downArrow){hi(1);return}if(p.backspace||p.delete){R();return}u&&!p.ctrl&&!p.meta&&bh(u);return}if(wn){if(p.upArrow){Hn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Hn(c=>c&&{...c,cursor:Math.min(Pt.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=tn(u,Pt.length);c!==null&&Hn(g=>g&&{...g,cursor:c});return}if(p.return){let c=Pt[wn.cursor];Hn(null);let{lines:g,changed:T,effective:W}=Rs(e,c.value??"default");for(let B of g)h({kind:"note",tone:B.startsWith("\u26A0")?"warn":B.startsWith("\u2713")?"ok":"info",text:B});T&&(eh(B=>B+1),Nt.current?.setModel(W));return}if(u==="s"){let c=Pt[wn.cursor];Hn(null),Nt.current?.setModel(c.value??void 0),h({kind:"note",tone:"ok",text:`\u2713 Using ${c.label} for this session only (your saved default is unchanged).`});return}if(p.escape){Hn(null);return}return}if(jt){if(p.upArrow){Eo(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Eo(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=tn(u,jt.rows.length);c!==null&&Eo(g=>g&&{...g,cursor:c});return}if(p.return||u==="s"){let c=jt.rows[jt.cursor];Eo(null),Ul(c.name,p.return===!0);return}if(p.escape){Eo(null);return}return}if(Wr){if(p.escape){Qn(null);return}if(p.leftArrow||p.tab&&p.shift){Qn(c=>c&&{tab:(c.tab-1+ut.length)%ut.length,scroll:0});return}if(p.rightArrow||p.tab){Qn(c=>c&&{tab:(c.tab+1)%ut.length,scroll:0});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=ut.length){Qn({tab:Number(u)-1,scroll:0});return}if(p.upArrow){Qn(c=>c&&{...c,scroll:Math.max(0,c.scroll-1)});return}if(p.downArrow){Qn(c=>{if(!c)return c;let g=(ut[c.tab]??ut[0]).rows.length;return{...c,scroll:Math.min(Math.max(0,g-1),c.scroll+1)}});return}return}if(It){if(p.upArrow){No(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){No(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=tn(u,It.rows.length);c!==null&&No(g=>g&&{...g,cursor:c});return}if(p.return){let c=It.rows[It.cursor].name;if(No(null),!ic(e,c).created){h({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}h({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${c}").`});let T=!1;try{let W=Un(c);T=!!W&&!(vo(W)&&!W.refreshToken)}catch{T=!1}h({kind:"note",tone:"info",text:T?`Next: sign in to ${c} and pick your project \u2014 you're already signed in here, so it'll be quick.`:`Next: sign in to Document360 (${c}) and pick your project.`}),oe("/login"),O(W=>W+1);return}if(p.escape){No(null);return}return}if(Ke){if(p.upArrow){Do(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Do(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=tn(u,Ke.rows.length);c!==null&&Do(g=>g&&{...g,cursor:c});return}if(p.return){let c=Ke.rows[Ke.cursor],{profile:g,projectId:T}=Ke;Do(null),ui(g,T,c);return}if(p.escape){Do(null);return}return}if(nt){if(p.upArrow){Gn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Gn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=tn(u,nt.rows.length);c!==null&&Gn(g=>g&&{...g,cursor:c});return}if(p.return){let c=nt.rows[nt.cursor],{profile:g}=nt;Gn(null),pi(g,c);return}if(p.escape){Gn(null);return}return}if(ot){if(p.upArrow){Oo(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Oo(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u===" "){Oo(c=>c&&{...c,rows:c.rows.map((g,T)=>T===c.cursor?{...g,checked:!g.checked}:g)});return}if(p.return){let c=ot.rows.filter(g=>g.checked).map(g=>g.path);if(Oo(null),c.length===0){h({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}eu(e,c),h({kind:"note",tone:"ok",text:`\u2713 Scoped to ${c.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let g of c)h({kind:"note",tone:"info",text:` ${g}`});h({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(p.escape){Oo(null);return}return}if(lt){if(p.upArrow){Vn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Vn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=tn(u,lt.rows.length);c!==null&&Vn(g=>g&&{...g,cursor:c});return}if(p.return){let c=lt.rows[lt.cursor],g=lt.run;Vn(null),g(c.token);return}if(p.escape){Vn(null);return}return}if(wt){if(p.upArrow){jo(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){jo(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=tn(u,wt.rows.length);c!==null&&jo(g=>g&&{...g,cursor:c});return}if(p.return){let c=wt.rows[wt.cursor],g=wt.conflicts;jo(null),c.conflict?Bl(c.paths[0]):c.kind==="article"?Ml(c.paths[0]):ct(c.paths,c.kind==="all"?g:0);return}if(p.escape){jo(null);return}return}if(Lt){if(p.upArrow){Io(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Io(c=>c&&{...c,cursor:Math.min(c.rows.length,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=tn(u,Lt.rows.length+1);c!==null&&Io(g=>g&&{...g,cursor:c});return}if(p.return){let{cursor:c,rows:g,opts:T}=Lt;Io(null);let W=c===0?g:[g[c-1]];Ek(W,T);return}if(p.escape){Io(null),h({kind:"note",tone:"info",text:"Left as drafts \u2014 nothing changed. /publish when they have been signed off."});return}return}if(yt){let{rows:c}=yt;if(p.upArrow){en(g=>g&&{...g,cursor:Math.max(0,g.cursor-1)});return}if(p.downArrow){en(g=>g&&{...g,cursor:Math.min(c.length-1,g.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let g=bp(Vp.current,Number(u),c.length-1);Vp.current=g.memory,g.index!==null&&en(T=>T&&{...T,cursor:g.index+1});return}if(u==="a"||u==="A"){en(g=>g&&{...g,cursor:0});return}if(p.return){let g=c[yt.cursor],{groups:T,resolve:W,report:B}=yt;if(en(null),g.kind==="all"){_l(T,{resolve:W,report:B});return}Wo(ja(g.group,{width:qe()})),_r({group:g.group,cursor:0,fromList:!0,resolve:W,rest:T.filter(b=>b.articleId!==g.group.articleId),report:B});return}if(p.escape){en(null),oe("/comments");return}return}if(Qe){let c=()=>{let{rest:g,group:T,fromList:W,resolve:B,report:b}=Qe;if(_r(null),!W||!b){oe("/comments");return}let k=[T,...g].sort((x,y)=>x.category.localeCompare(y.category)||x.title.localeCompare(y.title));en({cursor:0,rows:Ia(k),groups:k,resolve:B,report:b})};if(p.upArrow||p.downArrow){_r(g=>g&&{...g,cursor:g.cursor===0?1:0});return}if(u==="y"||u==="Y"||p.return&&Qe.cursor===0){let{group:g,resolve:T,rest:W,report:B}=Qe;_r(null),_l([g],{resolve:T,rest:W,...B?{report:B}:{}});return}if(u==="b"||u==="B"||p.escape||p.return){c();return}return}if(Ot){if(p.upArrow){qn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){qn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=tn(u,Ot.rows.length);c!==null&&qn(g=>g&&{...g,cursor:c});return}if(p.return){let c=Ot.rows[Ot.cursor];qn(null),c.action==="capture"?Xr(c.ids,{runLine:c.kind==="all"?["/screenshot capture --all","/capture --all"]:void 0}):c.action==="annotate"?ci(c.ids,{verifiedBefore:new Set(_e(e).filter(g=>g.state==="verified").map(g=>g.id))}):c.kind==="shot"?mh(c.ids[0]):fh(c.ids,{setup:!0,runLine:c.kind==="all"?["/screenshot author --all","/screenshot --all"]:void 0});return}if(p.escape){qn(null);return}return}if(bt){if(p.escape){Yn(null);return}if(p.upArrow){Yn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Yn(c=>c&&{...c,cursor:Math.min(Math.max(0,si.length-1),c.cursor+1)});return}if(p.return){let c=si[bt.cursor];if(c){Yn(null);try{h({kind:"preview",name:Ys(c),text:fk(fl(Tp(e,c),"utf8"))})}catch(g){h({kind:"note",tone:"error",text:`Could not read ${c}: ${g.message}`})}}return}if(p.backspace||p.delete){Yn(c=>c&&{...c,query:c.query.slice(0,-1),cursor:0});return}if(u&&!p.ctrl&&!p.meta&&u.length===1){Yn(c=>c&&{...c,query:c.query+u,cursor:0});return}return}if(kt){if(p.escape){Xn(null);return}if(p.upArrow){Xn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Xn(c=>c&&{...c,cursor:Math.min(Math.max(0,ii.length-1),c.cursor+1)});return}if(p.return){let c=ii[kt.cursor];if(c){Xn(null),Ze(c.uuid),Jt.current={uuid:c.uuid,firstPrompt:c.firstPrompt,titleFired:!0},Bn(c.name),Ap(c.uuid),Ao.current=[],rt.current={printed:[],armed:[],printedAt:Mo.current};let g=kp(e,c.uuid);for(let T of g)h(T);h({kind:"note",tone:"ok",text:g.length?`Resumed "${c.name}" \u2014 restored ${g.length} message(s); continue where you left off.`:`Resumed "${c.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(p.backspace||p.delete){Xn(c=>c&&{...c,query:c.query.slice(0,-1),cursor:0});return}if(u&&!p.ctrl&&!p.meta&&u.length===1){Xn(c=>c&&{...c,query:c.query+u,cursor:0});return}return}if(p.tab&&!m&&de){$(de),_t();return}if(!m&&fe.length>0&&!At.current&&u&&/^[1-9]$/.test(u)){let c=fe[Number(u)-1];if(c){$(Fn(c));return}}if(!m&&fe.length===0&&!At.current&&rt.current.armed.length>0&&u&&/^[1-9]$/.test(u)){let c=rt.current.armed[Number(u)-1];if(c){$(c);return}}if(!m&&(ni||qr)&&u==="c"&&!p.ctrl&&!p.meta&&!p.return&&!p.tab){let c=ni!=null;gp(ni??qr).then(T=>{h({kind:"note",tone:T?"ok":"warn",text:T?c?"\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.":c?"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&&c&&Dl(null),T&&!c&&nh(!0)});return}if(!$h(u,p)){if(uh){if(p.upArrow){So(c=>Math.max(0,c-1));return}if(p.downArrow){So(c=>Math.min(rn.length-1,c+1));return}if(p.tab){$("/"+(rn[yl]?.name??"")+" "),So(0);return}if(p.return){let c=rn[yl];if(c){let g=m.trim().slice(1).split(/\s+/).slice(1).join(" ");if(og(c.usage)&&!g){$("/"+c.name+" "),So(0);return}Qr("/"+c.name+(g?" "+g:""));return}}}else{if(!m&&fe.length>0&&!At.current&&(p.upArrow||p.downArrow)){if(p.downArrow){Ir(c=>c===null?0:Math.min(fe.length-1,c+1));return}if(To!==null){Ir(c=>c===null||c===0?null:c-1);return}}if(p.upArrow){if(m!==""&&Po===null){hi(-1);return}let c=kl.current;if(!c.length)return;let g=Po===null?c.length-1:Math.max(0,Po-1);Xs(g),$(c[g]??"");return}if(p.downArrow){if(m!==""&&Po===null){hi(1);return}let c=kl.current;if(Po===null)return;let g=Po+1;g>=c.length?(Xs(null),$("")):(Xs(g),$(c[g]??""));return}}if(p.return){if(To!==null&&!m&&fe[To]){let c=Fn(fe[To]);Ir(null),Qr(c);return}Qr();return}if(p.backspace||p.delete){R();return}if(p.escape){$(""),So(0),_t(),se([]),Lo(null),Ir(null),te.current=!0;return}u&&!p.ctrl&&!p.meta&&bh(u)}}}),at(()=>{if(C||D)return;let u=Kn.current.shift();u!==void 0&&(vl([...Kn.current]),Qr(u))},[C,D,Qr]),ue(je,{flexDirection:"column",width:st,children:[Ol!==null&&ue(je,{marginTop:1,flexDirection:"column",children:[Ol.truncated&&V(K,{dimColor:!0,children:"\u2026"}),V(K,{children:Ol.text})]}),C&&_o?V(t1,{p:_o}):null,Qp?V(ZD,{text:Qp}):C&&!_o?V(JD,{startTime:Et.current,chars:Ne}):null,V(je,{borderStyle:"round",borderColor:ch.prod?"yellow":ae,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:m?kh.map((u,p)=>{let c=d.text.slice(u.start,u.end),g=p===hl(kh,d.pos),T=Math.min(d.pos,u.end)-u.start;return ue(K,{children:[V(K,{color:ae,children:p===0?"> ":" "}),g?ue(Er,{children:[c.slice(0,T),V(Ar,{ch:c[T]??" "}),c.slice(T+1)]}):c||" "]},`${p}-${u.start}`)}):ue(K,{children:[V(K,{color:ae,children:"> "}),Br?V(Ar,{ch:" "}):xe&&!C?ue(Er,{children:[V(Ar,{ch:xe[0],dim:!0}),V(K,{color:"gray",children:xe.slice(1)})]}):de&&!C?ue(Er,{children:[V(Ar,{ch:de[0],dim:!0}),V(K,{color:"gray",children:de.slice(1)}),V(K,{dimColor:!0,children:" (tab)"})]}):(Il.isSetup||!jr)&&!C?ue(Er,{children:[V(Ar,{ch:Il.text[0],dim:!0}),V(K,{color:"gray",children:Il.text.slice(1)})]}):V(Ar,{ch:" "})]})}),zp.length>0&&V(je,{flexDirection:"column",paddingX:1,children:zp.map((u,p)=>V(K,{color:"gray",children:`\u29D7 queued: ${u}`},`${p}-${u.slice(0,24)}`))}),Wr?V(Cb,{tab:Wr.tab,scroll:Wr.scroll,rows:Tk,width:st,version:o,engineVersion:mk}):wn?ue(je,{flexDirection:"column",paddingX:1,children:[V(K,{color:ae,bold:!0,children:"Select model"}),V(K,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),Pt.map((u,p)=>ue(K,{color:p===wn.cursor?ae:void 0,children:[p===wn.cursor?"\u276F ":" ",`${p+1}. ${u.label}${p===wn.current?" \u2714":""}`.padEnd(16),V(K,{color:"gray",children:` ${u.desc}`})]},u.label)),V(K,{dimColor:!0,children:ft({verb:"set as default",rows:Pt.length,extra:["s this session only"]})})]}):jt?ue(je,{flexDirection:"column",paddingX:1,children:[V(K,{color:ae,bold:!0,children:"Switch connection profile"}),V(hn,{rows:jt.rows,cursor:jt.cursor,cap:qt,render:(u,p,c)=>ue(K,{color:c?ae:void 0,children:[c?"\u276F ":" ",`${p+1}. ${u.name}${p===jt.current?" \u2714":""}`.padEnd(20),V(K,{color:"gray",children:` ${u.env} \xB7 ${u.who??"not signed in"}`}),u.prod?V(K,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},u.name)}),V(K,{dimColor:!0,children:ft({verb:"switch (saved as default)",rows:jt.rows.length,extra:["s this session only"]})})]}):It?ue(je,{flexDirection:"column",paddingX:1,children:[V(K,{color:ae,bold:!0,children:"Pick your Document360 environment"}),V(hn,{rows:It.rows,cursor:It.cursor,cap:qt,render:(u,p,c)=>ue(K,{color:c?ae:void 0,children:[c?"\u276F ":" ",`${p+1}. ${u.name}`.padEnd(16),V(K,{color:"gray",children:` ${u.apiUrl}`}),u.note?V(K,{color:"yellow",children:` \u26A0 ${u.note}`}):null]},u.name)}),V(K,{dimColor:!0,children:ft({verb:"use it",rows:It.rows.length})})]}):Ke?ue(je,{flexDirection:"column",paddingX:1,children:[V(K,{color:ae,bold:!0,children:"Switch workspace"}),V(K,{dimColor:!0,children:`environment ${Ke.environment} \xB7 project ${Ke.projectName??`${Ke.projectId.slice(0,8)}\u2026`}`}),V(hn,{rows:Ke.rows,cursor:Ke.cursor,cap:qt,render:(u,p,c)=>ue(K,{color:c?ae:void 0,children:[c?"\u276F ":" ",`${p+1}. ${u.name}${p===Ke.current?" \u2714":""}`.padEnd(30),V(K,{color:"gray",children:u.type?` ${u.type}`:""})]},u.id)}),V(K,{dimColor:!0,children:ft({verb:"switch",rows:Ke.rows.length})})]}):nt?ue(je,{flexDirection:"column",paddingX:1,children:[V(K,{color:ae,bold:!0,children:"Choose project"}),V(K,{dimColor:!0,children:`environment ${nt.environment}`}),V(hn,{rows:nt.rows,cursor:nt.cursor,cap:qt,render:(u,p,c)=>ue(K,{color:c?ae:void 0,children:[c?"\u276F ":" ",`${p+1}. ${u.name}${p===nt.current?" \u2714":""}`.padEnd(30),V(K,{color:"gray",children:u.sub?` ${u.sub}`:""})]},u.id)}),V(K,{dimColor:!0,children:ft({verb:"switch",rows:nt.rows.length})})]}):ot?(()=>{let p=Math.min(Math.max(0,ot.cursor-Math.floor(7)),Math.max(0,ot.rows.length-14)),c=ot.rows.slice(p,p+14),g=ot.rows.filter(T=>T.checked).length;return ue(je,{flexDirection:"column",paddingX:1,children:[V(K,{color:ae,bold:!0,children:`Which folders back the user docs? (${g} selected of ${ot.rows.length})`}),p>0?V(K,{dimColor:!0,children:` \u2191 ${p} more`}):null,c.map((T,W)=>{let B=p+W;return ue(K,{color:B===ot.cursor?ae:void 0,children:[B===ot.cursor?"\u276F ":" ",T.checked?"\u25C9 ":"\u25CB ",T.path.padEnd(Math.min(48,st-34)),V(K,{color:"gray",children:sa(T)})]},T.path)}),p+14<ot.rows.length?V(K,{dimColor:!0,children:` \u2193 ${ot.rows.length-p-14} more`}):null,V(K,{dimColor:!0,children:ft({verb:"save",multi:!0})})]})})():lt?ue(je,{flexDirection:"column",paddingX:1,children:[V(K,{color:ae,bold:!0,children:lt.title??"Which category? (pick one to scope to)"}),V(hn,{rows:lt.rows,cursor:lt.cursor,cap:qt,render:(u,p,c)=>ue(K,{color:c?ae:void 0,children:[c?"\u276F ":" ",`${`${p+1}.`.padEnd(3)} ${u.label} (${u.count})`.padEnd(Math.min(44,Math.max(20,st-24))),V(K,{color:"gray",children:` ${u.token}`})]},u.token)}),V(K,{dimColor:!0,children:ft({verb:"choose it",rows:lt.rows.length})})]}):wt?ue(je,{flexDirection:"column",paddingX:1,children:[V(K,{color:ae,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),V(hn,{rows:wt.rows,cursor:wt.cursor,cap:qt,render:(u,p,c)=>ue(K,{color:c?ae:void 0,bold:u.kind==="category"&&!c,children:[c?"\u276F ":" ",`${u.indent?" ":" "}${`${p+1}.`.padEnd(3)} ${u.label}`.padEnd(Math.min(56,st-24)),u.note?V(K,{color:"gray",children:` ${u.note}`}):null]},`${u.kind}:${u.paths.join(",")}`)}),V(K,{dimColor:!0,children:ft({verb:"push as drafts",rows:wt.rows.length})})]}):Lt?ue(je,{flexDirection:"column",paddingX:1,children:[V(K,{color:ae,bold:!0,children:"Publish live to your readers \u2014 this is what they will see:"}),V(hn,{rows:[{path:"",articleId:"",label:`Publish all ${Lt.rows.length} live`,version:void 0},...Lt.rows],cursor:Lt.cursor,cap:qt,render:(u,p,c)=>ue(K,{color:c?ae:void 0,bold:p===0&&!c,children:[c?"\u276F ":" ",` ${`${p+1}.`.padEnd(3)} ${u.label}`.padEnd(Math.min(56,st-24)),p>0?V(K,{color:"gray",children:` ${u.version?`draft v${u.version} \u2192 live`:"draft \u2192 live"}`}):null]},`${p}:${u.path||"all"}`)}),V(K,{dimColor:!0,children:ft({verb:"publish live",cancel:"leave as drafts",rows:Lt.rows.length+1})})]}):yt?ue(je,{flexDirection:"column",paddingX:1,children:[V(K,{color:ae,bold:!0,children:"Which comments do you want to look at?"}),V(hn,{rows:yt.rows,cursor:yt.cursor,cap:qt,render:(u,p,c)=>ue(K,{color:c?ae:void 0,bold:u.kind==="all"&&!c,children:[c?"\u276F ":" ",`${(u.kind==="all"?"":`${u.n}.`).padEnd(4)}${u.label}`.padEnd(Math.min(56,Math.max(20,st-24))),u.kind==="article"?V(K,{color:"gray",children:u.note}):null]},u.kind==="all"?"all":u.group.articleId)}),V(K,{dimColor:!0,children:ft({verb:"open it",cancel:"close",rows:yt.rows.length-1})}),yt.resolve?V(K,{dimColor:!0,children:"--resolve is on: threads you answer will be closed as well as replied to"}):null]}):Qe?ue(je,{flexDirection:"column",paddingX:1,children:[V(K,{color:ae,bold:!0,children:`${Qe.group.title} \u2014 ${Qe.group.threads.length} comment${Qe.group.threads.length===1?"":"s"}`}),ue(K,{color:Qe.cursor===0?ae:void 0,children:[Qe.cursor===0?"\u276F ":" ",Qe.resolve?"Yes \u2014 fix them, push the draft, reply and resolve":"Yes \u2014 fix them, push the draft to Document360, then reply"]}),ue(K,{color:Qe.cursor===1?ae:void 0,children:[Qe.cursor===1?"\u276F ":" ",Qe.fromList?"No \u2014 back to the list":"No \u2014 leave them for now"]}),V(K,{dimColor:!0,children:ft({verb:"open it",cancel:"go back",extra:["y answer"]})})]}):Ot?ue(je,{flexDirection:"column",paddingX:1,children:[V(K,{color:ae,bold:!0,children:Ot.title}),(()=>{let{rows:u,cursor:p}=Ot,c=sl(u.length,p,qt),g=c.start,T=u.slice(c.start,c.end),W=`${u.length}.`.length+1,B=sm(u,Math.max(20,st-4-W));return ue(Er,{children:[g>0?V(K,{color:"gray",children:` \u2026 ${g} more above`}):null,T.map((b,k)=>{let x=g+k,y=x===p,v=B[x];return ue(K,{color:y?ae:void 0,bold:(b.kind==="all"||b.kind==="category")&&!y,children:[y?"\u276F ":" ",`${x+1}.`.padEnd(W),v.head,v.note?V(K,{color:"gray",children:v.note}):null]},`${b.action}:${b.kind}:${b.ids.join(",")}`)}),c.below>0?V(K,{color:"gray",children:` \u2026 ${c.below} more below`}):null]})})(),V(K,{dimColor:!0,children:ft({verb:"run it",rows:Ot.rows.length})})]}):bt?ue(je,{flexDirection:"column",paddingX:1,children:[V(K,{color:ae,bold:!0,children:`Preview article${bt.query?` \u2014 filter: ${bt.query}`:" (type to filter)"}`}),si.length===0?V(K,{color:"gray",children:"no articles match"}):si.map((u,p)=>ue(K,{color:p===bt.cursor?ae:void 0,children:[p===bt.cursor?"\u276F ":" ",u]},u)),V(K,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):kt?ue(je,{flexDirection:"column",paddingX:1,children:[V(K,{color:ae,bold:!0,children:`Resume session${kt.query?` \u2014 filter: ${kt.query}`:" (type to filter)"}`}),ii.length===0?V(K,{color:"gray",children:"no sessions match"}):ii.map((u,p)=>ue(K,{color:p===kt.cursor?ae:void 0,children:[p===kt.cursor?"\u276F ":" ",u.name.slice(0,28).padEnd(30),V(K,{color:p===kt.cursor?ae:"gray",children:u.firstPrompt.slice(0,Math.max(10,st-40))})]},u.uuid)),V(K,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):uh?ue(je,{flexDirection:"column",children:[to>0?V(K,{dimColor:!0,children:` \u22EF ${to} more above`}):null,Ll.map((u,p)=>{let c=to+p,g=u.name==="model"&&Rl?`${u.desc} (currently ${Rl})`:u.desc,T=Math.max(20,st-4),W=u.usage.length>T?`${u.usage.slice(0,T-1)}\u2026`:u.usage,B=T-Math.max(W.length,22)-1,b=B<=1?"":g.length>B?`${g.slice(0,B-1)}\u2026`:g;return ue(K,{color:c===ri?ae:void 0,children:[c===ri?"\u276F ":" ",W.padEnd(22)," ",V(K,{color:c===ri?ae:"gray",children:b})]},u.name)}),to+Ll.length<rn.length?V(K,{dimColor:!0,children:` \u22EF ${rn.length-to-Ll.length} more below`}):null,V(K,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!C&&!m&&fe.length>0?ue(je,{flexDirection:"column",paddingX:1,children:[Kp?V(K,{color:ae,children:Kp}):null,V(hn,{rows:fe,cursor:To??0,cap:qt,render:(u,p)=>{let c=p===To,g=Fn(u),T=g.slice(0,Math.max(20,st-7)),W=st-T.length-9,B=W>=12?(Tb(u)??tg(g)).slice(0,W):"";return ue(K,{color:c?ae:void 0,children:[c?"\u276F ":" ",V(K,{color:ae,children:p+1})," ",T,B?V(K,{color:c?ae:void 0,dimColor:!c,children:` \u2014 ${B}`}):null]},g)}}),V(K,{dimColor:!0,children:`\u2191\u2193 choose \xB7 enter run \xB7 1-${fe.length} fill \xB7 esc cancel`})]}):V(je,{paddingX:1,children:ue(K,{color:"gray",children:[ch.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${Rl??"model n/a"}${t.kind==="api"?Hr>0?` \xB7 session ${St(Hr)}`:"":Zp>0?` \xB7 ${ur(Zp)}`:""} \xB7 \u2191 history \xB7 ${xk?"press ctrl+c again to exit":"ctrl+c twice to exit"}`]})})]})}re();import{jsx as s1}from"react/jsx-runtime";async function wk(e=process.cwd(),t="auto",n,o="0.0.0"){let r=r1(t);r.kind==="none"&&(console.error(""),console.error(_("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${Z("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${Z("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=o1(s1(gk,{cwd:e,auth:r,profileName:n,version:o}),{exitOnCtrlC:!1});await s(),process.stdout.write(`
559
+ `),process.exit(0)}re();import{writeCrashLog as Fp,isBenignTransportError as i1}from"document360-engine";var yk=!1;function a1(e=process.stdout){return e.destroyed===!0||e.writable===!1}function Up(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function bk(e){if(yk)return;yk=!0;let t=(n,o)=>{if(i1(o)){Fp({kind:n,level:"transport",message:Up(o),stack:o instanceof Error?o.stack:void 0,detail:e}),a1()&&(Fp({kind:"terminal-gone",level:"transport",message:"stdout is closed \u2014 the terminal this session was rendering to is gone, so it exited rather than spin.",detail:e}),process.exit(0));return}let r=Fp({kind:n,level:"fatal",message:Up(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
560
+ `+_(`\u2717 d360-writer crashed: ${Up(o)}`)+`
559
561
  `),r&&process.stderr.write(f(` Crash details: ${r}`)+`
560
562
  `+f(" Run: d360-writer logs")+`
561
- `),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var e1=JD(import.meta.url),gl=e1("../package.json");hk("d360-writer");var Gt=new QD;function Op(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}Gt.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=>{Op(e),await yi({profile:e.profile,manual:e.manual})});Gt.command("logout").description("Remove the stored Document360 session for this repo's project").option("--profile <name>","Connection profile").option("--all-projects","Sign out of every Document360 project on this machine, not just this repo's").option("--env <name>",!1).action(async e=>{Op(e),await Lh({profile:e.profile,allProjects:e.allProjects})});Gt.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Op(e),await Ih({profile:e.profile})});var _p=Gt.command("profile").description("Manage connection profiles for the current repo");_p.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>bi(process.cwd()));_p.command("use <name>").description("Set the default profile for this repo").action(e=>ki(process.cwd(),e));_p.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>$i(process.cwd(),e));var fk=Gt.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");fk.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>Yo(process.cwd(),e.profile));fk.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await Rh(process.cwd(),e,t.profile)});var mk=Gt.command("project").description("Choose the Document360 project for this repo (active profile's identity)");mk.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>gi(process.cwd(),e.profile));mk.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await Sh(process.cwd(),e,t.profile)});Gt.command("init").description("Scaffold .d360-writer/config.json for this repo (interactive)").action(async()=>{let{initCommand:e}=await Promise.resolve().then(()=>(Ei(),wf));await e()});Gt.command("logs").description("Show the last thing that went wrong, and where the logs are kept (/logs does the same inside the app, and offers to copy it)").action(()=>Kl());Gt.command("doctor").description("Health-check: node, Claude auth, Document360 login, profile/workspace, category map, API reachability, and a real agent turn").action(async()=>{let{renderDoctorChecks:e,runDoctorChecks:t}=await Promise.resolve().then(()=>(Ra(),Gg)),n=await t(process.cwd(),gl.version);for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});Gt.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(gl.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(ZD.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 Bh(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 Xy(e.cwd,e.auth,e.profile,gl.version):await dk(e.cwd,e.auth,e.profile,gl.version)});Gt.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
563
+ `),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var d1=c1(import.meta.url),wl=d1("../package.json");bk("d360-writer");var Gt=new l1;function Wp(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}Gt.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=>{Wp(e),await yi({profile:e.profile,manual:e.manual})});Gt.command("logout").description("Remove the stored Document360 session for this repo's project").option("--profile <name>","Connection profile").option("--all-projects","Sign out of every Document360 project on this machine, not just this repo's").option("--env <name>",!1).action(async e=>{Wp(e),await _h({profile:e.profile,allProjects:e.allProjects})});Gt.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Wp(e),await Oh({profile:e.profile})});var Bp=Gt.command("profile").description("Manage connection profiles for the current repo");Bp.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>bi(process.cwd()));Bp.command("use <name>").description("Set the default profile for this repo").action(e=>ki(process.cwd(),e));Bp.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>$i(process.cwd(),e));var kk=Gt.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");kk.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>Ko(process.cwd(),e.profile));kk.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await Ah(process.cwd(),e,t.profile)});var $k=Gt.command("project").description("Choose the Document360 project for this repo (active profile's identity)");$k.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>gi(process.cwd(),e.profile));$k.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await Nh(process.cwd(),e,t.profile)});Gt.command("init").description("Scaffold .d360-writer/config.json for this repo (interactive)").action(async()=>{let{initCommand:e}=await Promise.resolve().then(()=>(Ei(),bf));await e()});Gt.command("logs").description("Show the last thing that went wrong, and where the logs are kept (/logs does the same inside the app, and offers to copy it)").action(()=>Ql());Gt.command("doctor").description("Health-check: node, Claude auth, Document360 login, profile/workspace, category map, API reachability, and a real agent turn").action(async()=>{let{renderDoctorChecks:e,runDoctorChecks:t}=await Promise.resolve().then(()=>(Ca(),Kg)),n=await t(process.cwd(),wl.version);for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});Gt.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(wl.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(u1.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 Gh(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 nb(e.cwd,e.auth,e.profile,wl.version):await wk(e.cwd,e.auth,e.profile,wl.version)});Gt.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});