document360-writer 0.5.303 → 0.5.305

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 +246 -244
  2. package/package.json +2 -2
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- var zv=Object.defineProperty;var Ps=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var rm=(e,t)=>{for(var n in t)zv(e,n,{get:t[n],enumerable:!0})};import Fn from"picocolors";var le,Xv,Qv,Jv,sm,Ts,d,L,K,X,ee,Te,Qe,ne,oe=Ps(()=>{"use strict";le="#7f56d9",[Xv,Qv,Jv]=[127,86,217],sm=e=>Fn.isColorSupported?`\x1B[38;2;${Xv};${Qv};${Jv}m${e}\x1B[39m`:e,Ts=e=>Fn.bold(sm(e)),d=e=>Fn.dim(e),L=e=>Fn.red(e),K=e=>Fn.yellow(e),X=e=>Fn.green(e),ee=sm,Te=e=>Fn.gray(e),Qe=e=>Fn.bold(e),ne=(e,t)=>`${e} ${t}`});import{existsSync as $r,writeFileSync as Bn,readFileSync as Jx,readdirSync as Zx}from"node:fs";import{join as Am}from"node:path";import{devHintsGuidePath as ca,hintsDir as Em,hooksDir as Nm,architectureDir as Lm,messagesDir as au,creatorNotesPath as Dm,devhintsStatePath as Om,directivesPath as jm,DIRECTIVES_HEADER as e0,roadmapPath as Im,ROADMAP_HEADER as t0,ensureDir as Ds,writeMessage as n0,listOpenForDev as o0,stampDone as r0,seedBriefConsumed as s0}from"document360-engine";function _m(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
2
+ var s0=Object.defineProperty;var As=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var dm=(e,t)=>{for(var n in t)s0(e,n,{get:t[n],enumerable:!0})};import Un from"picocolors";var ae,i0,a0,l0,pm,Es,d,L,q,Q,ee,Te,Qe,ne,oe=As(()=>{"use strict";ae="#7f56d9",[i0,a0,l0]=[127,86,217],pm=e=>Un.isColorSupported?`\x1B[38;2;${i0};${a0};${l0}m${e}\x1B[39m`:e,Es=e=>Un.bold(pm(e)),d=e=>Un.dim(e),L=e=>Un.red(e),q=e=>Un.yellow(e),Q=e=>Un.green(e),ee=pm,Te=e=>Un.gray(e),Qe=e=>Un.bold(e),ne=(e,t)=>`${e} ${t}`});import{existsSync as kr,writeFileSync as Hn,readFileSync as lx,readdirSync as cx}from"node:fs";import{join as Om}from"node:path";import{devHintsGuidePath as fa,hintsDir as _m,hooksDir as Mm,architectureDir as Bm,messagesDir as pu,creatorNotesPath as Fm,devhintsStatePath as Hm,directivesPath as Um,DIRECTIVES_HEADER as ux,roadmapPath as Wm,ROADMAP_HEADER as dx,ensureDir as Is,writeMessage as px,listOpenForDev as hx,stampDone as fx,seedBriefConsumed as mx}from"document360-engine";function Gm(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
3
3
 
4
4
  <!-- devhints script v${Me} \xB7 maintained by document360-writer (/devhints). -->
5
5
 
@@ -242,7 +242,7 @@ do it**:
242
242
  **Do NOT write or action the documentation yourself** \u2014 same boundary as Part 2. Writing the article is the
243
243
  docs agent's job; it actions open directives on its next \`/catch-up\` (as drafts) and flips each to \`[done]\`
244
244
  with the article it wrote. You are only the relay so the ask is captured durably and travels via git.
245
- `}function a0(){return`# Creator notes (optional \u2014 for the docs agent and the builder)
245
+ `}function yx(){return`# Creator notes (optional \u2014 for the docs agent and the builder)
246
246
 
247
247
  <!-- The ORIGINAL CREATOR's context. Most repos leave this empty \u2014 that's fine.
248
248
  The builder agent reads this FIRST and treats it as authoritative when writing the architecture
@@ -256,12 +256,12 @@ Anything only a human knows that would help document this product. For example:
256
256
  - Gotchas or non-obvious behavior.
257
257
 
258
258
  (Replace these examples with your notes, or leave the file as-is to skip \u2014 it's optional.)
259
- `}function xr(e){Ds(Em(e)),Ds(Lm(e)),Ds(au(e));for(let n of[Em(e),au(e)]){let o=Am(n,".gitkeep");$r(o)||Bn(o,`# Keeps this document360-writer inbox tracked in git even when empty.
260
- `)}$r(Dm(e))||Bn(Dm(e),a0()),$r(jm(e))||Bn(jm(e),e0),$r(Im(e))||Bn(Im(e),t0),Bn(ca(e),_m()),Ds(Nm(e)),Bn(Am(Nm(e),"open-questions.mjs"),i0);let t=zt(e);return Fm(e,new Date().toISOString()),t}async function Mm(e,t){for(let n of Rr(xr(t.cwd)))console.log(n);return{kind:"continue"}}function jo(){return[`This is document360-writer's dev hand-off setup (v${Me}).`,'Connect this repository to document360-writer (its "docs agent" \u2014 a separate tool that writes this',"product's user documentation from your code, but needs your intent). This prompt is SAFE TO RUN MORE","THAN ONCE \u2014 paste it again whenever the product changes. At each step: create what is missing, reconcile","what already exists, and never duplicate, clobber a refined file, or delete human-written notes. In order:","","1. Read `.d360-writer/DEV-HINTS-GUIDE.md` \u2014 the full dev\u2192docs hand-off protocol (Parts 1\u20136). Follow it.","2. Architecture brief in `.d360-writer/architecture/` (per the guide). First read"," `.d360-writer/architecture/CREATOR-NOTES.md` and treat it as authoritative (it may be empty; never"," modify it). Then:"," \u2022 If no brief exists yet, write it now \u2014 a USER-DOC-enabling brief: product intent, user-facing"," surfaces, features and why a user reaches for each, roles/permission gating, core workflows,"," terminology \u2014 every claim citing the source file(s) that prove it. Skip internals (services, data"," access, infra, build/CI, tests)."," \u2022 If a brief already exists, UPDATE it to match the current code: add new surfaces/features, correct"," what changed, remove what was deleted \u2014 but preserve accurate existing content and any human edits."," Do NOT rewrite it from scratch. If nothing changed, leave it as is.","3. Persist the ongoing rule so teammates' agents inherit it: this repo's agent-memory file (CLAUDE.md,"," or AGENTS.md \u2014 whichever this repo already uses; create CLAUDE.md if neither exists) should contain a",' short "Documentation hand-off" section saying: on every user-facing change, drop a hint file in'," `.d360-writer/hints/` and keep `.d360-writer/architecture/` current \u2014 and SURFACE each hint drop in"," your reply (name the file + the one-line surface), never silently; NEVER write or publish the"," user-facing articles yourself (that is the docs agent's job \u2014 you only hand off); each session,"," check `.d360-writer/messages/` for open questions from the docs agent and answer them promptly and"," in full \u2014 an open docs question BLOCKS the documentation, and `[discovery]` questions define the"," whole product brief, so answer those in depth; `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": ${Me},`,' "completedAt": "<UTC now>", "completedCommit": "<current HEAD short sha>"} (preserve any other keys'," already in the file, e.g. emittedAt). Include this file in the commit from step 3.","8. 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(`
261
- `)}function cu(e){try{let t=Jx(Om(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function Fm(e,t){let o={...cu(e)??{},emittedVersion:Me,emittedAt:t};Bn(Om(e),`${JSON.stringify(o,null,2)}
262
- `)}function Sn(e){try{return Zx(Lm(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function zt(e){let n=cu(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<Me?"stale":"current",completedVersion:n}}function l0(e){let t=new RegExp(`${lu.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(\\d+)\\)`).exec(e);return t?Number(t[1]):null}function ua(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,supersededRequests:[],toVersion:Me};try{if(!$r(ca(e)))return n;s0(e);let o=cu(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;if(Me>r&&(Ds(au(e)),Bn(ca(e),_m()),Fm(e,t),n.guideRefreshed=!0),Me>s){let i=o0(e).filter(c=>c.kind==="request"&&c.subject.startsWith(lu)),a=i.filter(c=>(l0(c.subject)??Me)>=Me);for(let c of i.filter(l=>!a.includes(l)))r0(e,c.file,{doneAt:t,answeredBy:"docs"}),n.supersededRequests.push(c.subject);a.length===0&&(n0(e,{id:`onb${Me}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${lu}${Me})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${Me}${s?` (you last completed v${s})`:""}.`,"Re-run the hand-off so the docs agent and this repo stay in step \u2014 run this prompt here:","",jo()].join(`
263
- `)}),n.notifiedBuilder=!0)}}catch{}return n}function da(e){if(!$r(ca(e)))return[];let t=zt(e);return t.status==="current"?[]:[`\u{1F514} Your builder agent ${t.completedVersion?`is on v${t.completedVersion}`:"hasn't completed the hand-off yet"} \u2014 d360-writer's dev\u2194docs protocol is now v${Me}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,vr,jo(),vr,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function uu(){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(`
264
- `)}function pa(){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):",vr,uu(),vr]}function Rr(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${Me}.`," Have them run the prompt below again \u2014 it now sets up two-way messages + on-demand docs.",""]:[],"\u2713 Wrote .d360-writer/DEV-HINTS-GUIDE.md + the .d360-writer/architecture/ (brief), .d360-writer/hints/, and .d360-writer/messages/ inboxes.","","\u{1F4CB} Copy this one prompt and run it in your repo's coding agent (Claude Code / Codex / Cursor):",vr,jo(),vr,"","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 vr,Me,i0,lu,Hn=Ps(()=>{"use strict";vr="-".repeat(64),Me=13,i0=`#!/usr/bin/env node
259
+ `}function vr(e){Is(_m(e)),Is(Bm(e)),Is(pu(e));for(let n of[_m(e),pu(e)]){let o=Om(n,".gitkeep");kr(o)||Hn(o,`# Keeps this document360-writer inbox tracked in git even when empty.
260
+ `)}kr(Fm(e))||Hn(Fm(e),yx()),kr(Um(e))||Hn(Um(e),ux),kr(Wm(e))||Hn(Wm(e),dx),Hn(fa(e),Gm()),Is(Mm(e)),Hn(Om(Mm(e),"open-questions.mjs"),gx);let t=Xt(e);return Vm(e,new Date().toISOString()),t}async function qm(e,t){for(let n of xr(vr(t.cwd)))console.log(n);return{kind:"continue"}}function Io(){return[`This is document360-writer's dev hand-off setup (v${Me}).`,'Connect this repository to document360-writer (its "docs agent" \u2014 a separate tool that writes this',"product's user documentation from your code, but needs your intent). This prompt is SAFE TO RUN MORE","THAN ONCE \u2014 paste it again whenever the product changes. At each step: create what is missing, reconcile","what already exists, and never duplicate, clobber a refined file, or delete human-written notes. In order:","","1. Read `.d360-writer/DEV-HINTS-GUIDE.md` \u2014 the full dev\u2192docs hand-off protocol (Parts 1\u20136). Follow it.","2. Architecture brief in `.d360-writer/architecture/` (per the guide). First read"," `.d360-writer/architecture/CREATOR-NOTES.md` and treat it as authoritative (it may be empty; never"," modify it). Then:"," \u2022 If no brief exists yet, write it now \u2014 a USER-DOC-enabling brief: product intent, user-facing"," surfaces, features and why a user reaches for each, roles/permission gating, core workflows,"," terminology \u2014 every claim citing the source file(s) that prove it. Skip internals (services, data"," access, infra, build/CI, tests)."," \u2022 If a brief already exists, UPDATE it to match the current code: add new surfaces/features, correct"," what changed, remove what was deleted \u2014 but preserve accurate existing content and any human edits."," Do NOT rewrite it from scratch. If nothing changed, leave it as is.","3. Persist the ongoing rule so teammates' agents inherit it: this repo's agent-memory file (CLAUDE.md,"," or AGENTS.md \u2014 whichever this repo already uses; create CLAUDE.md if neither exists) should contain a",' short "Documentation hand-off" section saying: on every user-facing change, drop a hint file in'," `.d360-writer/hints/` and keep `.d360-writer/architecture/` current \u2014 and SURFACE each hint drop in"," your reply (name the file + the one-line surface), never silently; NEVER write or publish the"," user-facing articles yourself (that is the docs agent's job \u2014 you only hand off); each session,"," check `.d360-writer/messages/` for open questions from the docs agent and answer them promptly and"," in full \u2014 an open docs question BLOCKS the documentation, and `[discovery]` questions define the"," whole product brief, so answer those in depth; `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": ${Me},`,' "completedAt": "<UTC now>", "completedCommit": "<current HEAD short sha>"} (preserve any other keys'," already in the file, e.g. emittedAt). Include this file in the commit from step 3.","8. 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(`
261
+ `)}function fu(e){try{let t=lx(Hm(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function Vm(e,t){let o={...fu(e)??{},emittedVersion:Me,emittedAt:t};Hn(Hm(e),`${JSON.stringify(o,null,2)}
262
+ `)}function Pn(e){try{return cx(Bm(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function Xt(e){let n=fu(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<Me?"stale":"current",completedVersion:n}}function wx(e){let t=new RegExp(`${hu.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(\\d+)\\)`).exec(e);return t?Number(t[1]):null}function ma(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,supersededRequests:[],toVersion:Me};try{if(!kr(fa(e)))return n;mx(e);let o=fu(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;if(Me>r&&(Is(pu(e)),Hn(fa(e),Gm()),Vm(e,t),n.guideRefreshed=!0),Me>s){let i=hx(e).filter(c=>c.kind==="request"&&c.subject.startsWith(hu)),a=i.filter(c=>(wx(c.subject)??Me)>=Me);for(let c of i.filter(l=>!a.includes(l)))fx(e,c.file,{doneAt:t,answeredBy:"docs"}),n.supersededRequests.push(c.subject);a.length===0&&(px(e,{id:`onb${Me}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${hu}${Me})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${Me}${s?` (you last completed v${s})`:""}.`,"Re-run the hand-off so the docs agent and this repo stay in step \u2014 run this prompt here:","",Io()].join(`
263
+ `)}),n.notifiedBuilder=!0)}}catch{}return n}function ga(e){if(!kr(fa(e)))return[];let t=Xt(e);return t.status==="current"?[]:[`\u{1F514} Your builder agent ${t.completedVersion?`is on v${t.completedVersion}`:"hasn't completed the hand-off yet"} \u2014 d360-writer's dev\u2194docs protocol is now v${Me}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,$r,Io(),$r,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function mu(){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(`
264
+ `)}function ya(){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):",$r,mu(),$r]}function xr(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${Me}.`," Have them run the prompt below again \u2014 it now sets up two-way messages + on-demand docs.",""]:[],"\u2713 Wrote .d360-writer/DEV-HINTS-GUIDE.md + the .d360-writer/architecture/ (brief), .d360-writer/hints/, and .d360-writer/messages/ inboxes.","","\u{1F4CB} Copy this one prompt and run it in your repo's coding agent (Claude Code / Codex / Cursor):",$r,Io(),$r,"","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 $r,Me,gx,hu,Gn=As(()=>{"use strict";$r="-".repeat(64),Me=13,gx=`#!/usr/bin/env node
265
265
  // d360-writer \u2014 session-start nudge for the builder ("John"). Surfaces open questions the docs agent
266
266
  // ("Julie") left in .d360-writer/messages/ so they get answered, not forgotten. Self-contained (no deps);
267
267
  // wired into your coding agent's session-start trigger by /devhints. See .d360-writer/DEV-HINTS-GUIDE.md.
@@ -299,94 +299,94 @@ try {
299
299
  } catch {
300
300
  /* a session-start nudge must never break the session */
301
301
  }
302
- `;lu="Re-run dev\u2194docs onboarding (protocol v"});var Qm={};rm(Qm,{initCommand:()=>hu,scaffoldInit:()=>du,writeWriterGitignore:()=>pu});import{input as js,confirm as c0}from"@inquirer/prompts";import{basename as Bm,join as ha}from"node:path";import{existsSync as Sr,readFileSync as Hm,readdirSync as u0,writeFileSync as Um}from"node:fs";import{writeProjectConfig as Gm,readProjectConfig as d0,projectConfigPath as qm,writerDir as p0,DEFAULT_DOCS_DIR as Vm,DEFAULT_CAPTURE_DIR as Km,DEFAULT_OUTPUT_DIR as Ym}from"document360-engine";function du(e,t="berlin"){let n=qm(e);if(Sr(n))return{created:!1,path:n,profileName:""};let o={projectId:zm(e)??Bm(e),docsDir:Vm,captureDir:Km,outputDir:Ym,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:Xm(e)};return Gm(o,e),pu(e),{created:!0,path:n,profileName:t}}function pu(e){let t=ha(p0(e),".gitignore"),n="# Local/transient \u2014 the config files here ARE meant to be committed.";if(!Sr(t)){Um(t,[n,...Wm,""].join(`
303
- `),"utf8");return}let o;try{o=Hm(t,"utf8")}catch{return}let r=new Set(o.split(/\r?\n/).map(c=>c.trim())),s=Wm.filter(c=>!r.has(c)&&!r.has(c.replace(/\/$/,"")));if(s.length===0)return;let i=/\r\n/.test(o)?`\r
302
+ `;hu="Re-run dev\u2194docs onboarding (protocol v"});var rg={};dm(rg,{initCommand:()=>wu,scaffoldInit:()=>gu,writeWriterGitignore:()=>yu});import{input as Ls,confirm as bx}from"@inquirer/prompts";import{basename as zm,join as wa}from"node:path";import{existsSync as Rr,readFileSync as Xm,readdirSync as kx,writeFileSync as Ym}from"node:fs";import{writeProjectConfig as Qm,readProjectConfig as $x,projectConfigPath as Jm,writerDir as vx,DEFAULT_DOCS_DIR as Zm,DEFAULT_CAPTURE_DIR as eg,DEFAULT_OUTPUT_DIR as tg}from"document360-engine";function gu(e,t="berlin"){let n=Jm(e);if(Rr(n))return{created:!1,path:n,profileName:""};let o={projectId:ng(e)??zm(e),docsDir:Zm,captureDir:eg,outputDir:tg,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:og(e)};return Qm(o,e),yu(e),{created:!0,path:n,profileName:t}}function yu(e){let t=wa(vx(e),".gitignore"),n="# Local/transient \u2014 the config files here ARE meant to be committed.";if(!Rr(t)){Ym(t,[n,...Km,""].join(`
303
+ `),"utf8");return}let o;try{o=Xm(t,"utf8")}catch{return}let r=new Set(o.split(/\r?\n/).map(c=>c.trim())),s=Km.filter(c=>!r.has(c)&&!r.has(c.replace(/\/$/,"")));if(s.length===0)return;let i=/\r\n/.test(o)?`\r
304
304
  `:`
305
305
  `,a=o.endsWith(`
306
- `)?"":i;Um(t,`${o}${a}${s.join(i)}${i}`,"utf8")}async function hu(){let e=process.cwd(),t=qm(e);if(Sr(t)&&!await c0({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(d("init cancelled.")),{kind:"continue"};let n=zm(e)??Bm(e),o=await js({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await js({message:"Capture directory (where document360-capture .spec.ts files live):",default:Km}),s=await js({message:"Screenshot output directory:",default:Ym}),i=await js({message:"Default connection profile name:",default:"berlin"}),a=await js({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),c={projectId:o,docsDir:Vm,captureDir:r,outputDir:s,profiles:{[i]:{connection:{environment:a},production:!1}},defaultProfile:i,authoritativeSourceFiles:Xm(e)},l=d0(e);l?.terminologyGlossary&&(c.terminologyGlossary=l.terminologyGlossary),Gm(c,e),pu(e);let f=xr(e);console.log(""),console.log(X(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${ee(`d360-writer login --profile ${i}`)} ${d("(sign in; project & workspace auto-selected)")}`),console.log("");for(let g of Rr(f))console.log(g);return console.log(""),console.log(`${d("Then ask:")} ${ee('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function zm(e){let t=ha(e,"package.json");if(!Sr(t))return null;try{return JSON.parse(Hm(t,"utf8")).name??null}catch{return null}}function Xm(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Sr(ha(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=ha(e,n);Sr(o)&&!h0(o)&&t.push(n)}return t}function h0(e){try{return u0(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var Wm,fa=Ps(()=>{"use strict";oe();Hn();Wm=[".sessions/","cache/"]});import{createRequire as P0}from"node:module";import{existsSync as T0,readFileSync as A0}from"node:fs";import{dirname as ag,join as lg}from"node:path";function bt(){let e;try{e=E0.resolve("document360-capture/helpers")}catch{return null}let t=ag(e);for(let n=0;n<5&&!T0(lg(t,"package.json"));n++)t=ag(t);try{let n=JSON.parse(A0(lg(t,"package.json"),"utf8"));return n.name==="document360-capture"&&n.version?n.version:null}catch{return null}}var E0,Cr=Ps(()=>{"use strict";E0=P0(import.meta.url)});var Pw={};rm(Pw,{doctorCommand:()=>oi,renderDoctorChecks:()=>Cw,runDoctorChecks:()=>Sw});import{existsSync as IP}from"node:fs";import{d360GetAll as LP,getAccessToken as OP,isExpired as hl,loadProfileMap as _P,loadTokens as MP,listStoredSessions as FP,tokensProjectId as ip,packageSkillsDir as Rw,ENGINE_VERSION as UP,projectConfigPath as WP,readProjectConfig as BP,DEFAULT_DOCS_DIR as HP,fetchManifestSummary as GP,resolveActiveProfile as qP,classifyClaudeAuth as VP,resolveAuthOrigin as KP,authOriginLine as YP,authOriginFix as zP,CLAUDE_CODE_SETUP_HINT as fl,resolveModelSetting as XP,probeModel as QP,probeAgentTurn as JP,stderrHeadline as ZP,detectAppType as eT,playbookSkillName as tT,D360AuthError as nT,applyStructureOrder as oT}from"document360-engine";async function Sw(e,t){let n=[],o=bt();n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${UP}${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=VP();if(s.state==="ready"){let x=KP(),E=zP(x);n.push({level:E?"warn":"ok",label:`Claude auth: ${YP(x).replace(/^Claude: /,"")}`,...E?{fix:E}:{}})}else 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. ${fl}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:fl});let i=XP(e);if(n.push({level:"ok",label:`Model: ${i.model} (${i.source==="auto"?"auto \u2014 right-sized for docs; /model to change":i.source})`}),s.state==="ready"){let x=await QP(e,i.model??void 0);if(x.ok){n.push({level:"ok",label:`Model reachable \u2014 replied in ${(x.latencyMs/1e3).toFixed(1)}s`});let E=await JP(e,i.model??void 0);if(E.ok)n.push({level:"ok",label:`Agent turn works \u2014 ran with your skills and tools in ${(E.latencyMs/1e3).toFixed(1)}s`});else{let I=ZP(E.stderr),W=/auth|sign.?in|login|credential|token|401|expired/i.test(`${E.error??""} ${E.stderr??""}`);if(n.push({level:"fail",label:E.timedOut?"Agent turn never finished \u2014 the model answers, but a real turn with your skills and tools hangs":W?"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 ${E.producedNothing?"ends instantly with no output":`fails: ${E.error}`}`,fix:(I?`Claude Code said: "${I}". `:"")+(W?`Sign in again, then re-run /doctor. ${fl}`:"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.")}),W){let V=n.find(B=>B.label.startsWith("Claude auth:"));V&&(V.level="warn",V.label="Claude auth: a sign-in exists on this machine, but it is no longer valid",V.fix=`Sign in again. ${fl}`)}}}else x.timedOut?n.push({level:"fail",label:"Model unreachable \u2014 no response in 30s (a docs turn will hang, then end with 0 tokens / no output)",fix:`Usually a corporate proxy/firewall or org policy blocking the Claude model API. Check this machine's network access to the Claude endpoint; confirm with: claude -p "say hi"`}):n.push({level:"fail",label:`Model call failed \u2014 ${x.error??"no output"} (a docs turn will end with 0 tokens / no output)`,fix:'Check sign-in, the selected model (/model), and network access to the Claude endpoint; confirm with: claude -p "say hi"'})}let a=BP(e);if(!a)return n.push({level:"fail",label:`No ${WP(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${a.projectId}`});let c=(a.docsDir??HP).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 ${c}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let l=a.authoritativeSourceFiles??[];n.push(l.length>0?{level:"ok",label:`Sources: docs grounded in ${l.length} path(s) (${l.slice(0,3).join(", ")}${l.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 f=a.appType??eT(e);if(f){let x=a.appType?"from config":"auto-detected",E=f==="web"||f==="cli";n.push({level:"ok",label:`Genre: ${f} (${x})${E?` \u2192 ${tT(f)} loaded`:" \u2014 no doc-type playbook for this genre yet (generic skills)"}`})}else n.push({level:"warn",label:"Genre: unclassified \u2014 no doc-type playbook is loading (generic output)",fix:"Run /genre <web|cli|service|library> to pick \u2014 raises docs to that genre's craft bar"});let g;try{g=qP(e),n.push({level:"ok",label:`Profile: ${g.name} (${g.connection.name})${g.production?" \u26A0 PRODUCTION":""}`})}catch(x){return n.push({level:"fail",label:`Profile config: ${x.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let k=MP(g.name,g.project.projectId),T=FP(g.name).filter(x=>{let E=ip(x);return!!E&&E!==g.project.projectId&&!(hl(x)&&!x.refreshToken)}),A=g.project.projectName?`"${g.project.projectName}"`:"this project";k?hl(k)&&!k.refreshToken?n.push({level:"fail",label:k.refreshRejectedAt?`Document360: session ended \u2014 Document360 refused to renew it (${new Date(k.refreshRejectedAt).toLocaleString()})`:"Document360: session expired (no refresh token)",fix:"/login"}):hl(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 ${A} (until ${new Date(k.expiresAt).toLocaleString()})`}):n.push(T.length>0?{level:"fail",label:`Document360: not signed in to ${A} \u2014 signed in to ${T.map(x=>x.projectName?`"${x.projectName}"`:(ip(x)??"").slice(0,8)+"\u2026").join(", ")} instead`,fix:`Run: /login and pick ${A} \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 ${g.name})`}),T.length>0&&n.push({level:"ok",label:`Other Document360 projects signed in on this machine: ${T.map(x=>x.projectName?`"${x.projectName}"`:(ip(x)??"").slice(0,8)+"\u2026").join(", ")} (kept \u2014 each repo uses its own)`}),n.push(g.project.workspaceId?{level:"ok",label:`Workspace: ${g.project.workspaceName??g.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let S=_P(e,g.name);S?S.projectId&&g.project.projectId&&S.projectId!==g.project.projectId?n.push({level:"fail",label:`Category map projectId (${S.projectId}) \u2260 profile projectId (${g.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):n.push({level:"ok",label:`Category map: ${Object.keys(S.articles).length} articles, ${Object.keys(S.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${g.name}" (created on first /push)`}),n.push(IP(Rw())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${Rw()}`,fix:"Reinstall document360-writer (broken install)"});let C=zt(e);if(C.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${Me})`}):C.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${C.completedVersion}, current is v${Me}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),k&&(!hl(k)||k.refreshToken)){let x={profile:g.name,connection:g.connection,projectId:g.project.projectId,projectName:g.project.projectName};try{await OP(x);let I=await LP(x,"/v3/projects");n.push({level:"ok",label:`API reachable (${g.connection.apiUrl}) \u2014 ${I.length} project(s) visible`})}catch(I){n.push({level:"fail",label:`API call failed: ${I.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let E=S?.projectId??g.project.projectId;if(E&&g.project.workspaceId){try{let I=await GP(x,E,g.project.workspaceId);if(I){let W=(I.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Your Document360 project: reachable on ${g.connection.name} (${I.languages?.length??0} language${(I.languages?.length??0)===1?"":"s"}) \xB7 version ${W||"(none)"}`})}else n.push({level:"ok",label:`Workspace sync manifest: not live on ${g.connection.name} yet \u2014 sync uses the per-article path (nothing to do)`})}catch(I){I instanceof nT||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(I.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${g.project.projectName??E})`,fix:"Run /login and pick this repo's project \u2014 your token is scoped to another project"}):n.push({level:"warn",label:`Workspace sync manifest: probe failed (${I.message.slice(0,80)})`})}try{let I=await oT({cwd:e,profileName:g.name,dryRun:!0}),W=I.categoriesReordered+I.articlesReordered;if(I.skipped==="no category map")n.push({level:"ok",label:"Reading order: nothing to check yet (no articles published)"});else if(I.skipped)n.push({level:"warn",label:`Reading order: can't be checked (${I.skipped})`,fix:"Your article order on Document360 may not match your structure \u2014 /push syncs it once this resolves"});else if(I.unverified)n.push({level:"warn",label:`Reading order: ${I.unverified} of your articles aren't listed by Document360, so their order can't be set`,fix:"Usually means those articles are not live yet (the listing returns published articles). /publish takes them live, then /push re-syncs the order"});else if(W>0){let V=[I.categoriesReordered>0?`${I.categoriesReordered} categor${I.categoriesReordered===1?"y":"ies"}`:"",I.articlesReordered>0?`${I.articlesReordered} article${I.articlesReordered===1?"":"s"}`:""].filter(Boolean);n.push({level:"warn",label:`Reading order: ${V.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(I.orphans?.length){let V=I.orphans;n.push({level:"warn",label:`${V.length} article${V.length===1?"":"s"} on Document360 ${V.length===1?"is":"are"} not in your docs folder: ${V.slice(0,3).map(B=>B.path).join(", ")}${V.length>3?`, +${V.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(I){n.push({level:"warn",label:`Reading order: check failed (${I.message.slice(0,80)})`})}}}return n}function Cw(e){let t=[""];for(let r of e){let s=r.level==="ok"?X("\u2713"):r.level==="warn"?K("\u26A0"):L("\u2717");t.push(` ${s} ${r.label}${r.detail?d(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${d("fix:")} ${ee(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?X(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):L(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function oi(e,t){console.log(d("Running checks\u2026"));for(let n of Cw(await Sw(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var ml=Ps(()=>{"use strict";Hn();oe();Cr()});import{Command as pO}from"commander";import{createRequire as hO}from"node:module";import{AUTH_MODES as fO}from"document360-engine";import{input as mx}from"@inquirer/prompts";import{loginPkce as gx,getAccessToken as yx,toStoredTokens as wx,clearTokens as bx,decodeJwtClaims as dm,isExpired as kx,loadTokens as Qc,saveTokens as $x,listStoredSessions as Jc,tokensProjectId as Wn,rememberSessionProject as pm,resolveActiveProfile as Ns,setProfileProject as vx,readProjectConfig as xx}from"document360-engine";oe();import{select as Zv}from"@inquirer/prompts";import{resolveActiveProfile as ex,setProfileProject as tx,resolveProjectId as nx,listWorkspaces as ox}from"document360-engine";async function As(e,t){let n=ex(e,t),o={profile:n.name,connection:n.connection,projectId:n.project.projectId,projectName:n.project.projectName},r=n.project.projectId??nx(o);return{workspaces:await ox(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var im=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function zc(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 Ji(e,t,n,o,r){tx(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function am(e,t,n){let o;try{o=await As(e,n)}catch(s){return console.log(L(`Could not list workspaces: ${s.message}`)),1}let r=zc(o.workspaces,t);return r?(Ji(e,o.profile,o.projectId,r.id,r.name),console.log(X(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(L(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function kr(e,t){let n;try{n=await As(e,t)}catch(l){console.log(L(`Could not list workspaces: ${l.message}`));return}let{workspaces:o,projectId:r,profile:s,current:i}=n;if(o.length===0){console.log(d("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let l of o)console.log(` ${l.id===i?ee("\u25CF"):" "} ${im(l)} ${d(l.id)}`);console.log(d("Run: d360-writer workspace use <name>"));return}let a=await Zv({message:"Select the Document360 workspace for this repo:",choices:o.map(l=>({name:`${im(l)}${l.id===i?" (current)":""}`,value:l.id}))}),c=o.find(l=>l.id===a);Ji(e,s,r,a,c?.name),console.log(X(`\u2713 Workspace set to "${c?.name??a}" for profile "${s}".`))}oe();import{select as rx}from"@inquirer/prompts";import{resolveActiveProfile as sx,setProfileProject as ix,listProjects as ax}from"document360-engine";async function Rn(e,t){let n=sx(e,t),o={profile:n.name,connection:n.connection};return{projects:await ax(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var lm=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Xc(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 Zi(e,t,n,o){ix(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function cm(e,t,n){let o;try{o=await Rn(e,n)}catch(s){return console.log(L(`Could not list projects: ${s.message}`)),1}let r=Xc(o.projects,t);return r?(Zi(e,o.profile,r.id,r.name),console.log(X(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log(L(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function ea(e,t){let n;try{n=await Rn(e,t)}catch(c){console.log(L(`Could not list projects: ${c.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(d("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let c of o)console.log(` ${c.id===s?ee("\u25CF"):" "} ${lm(c)} ${d(c.id)}`);console.log(d("Run: d360-writer project use <name>"));return}let i=await rx({message:"Select the Document360 project for this repo:",choices:o.map(c=>({name:`${lm(c)}${c.id===s?" (current)":""}`,value:c.id}))}),a=o.find(c=>c.id===i);Zi(e,r,i,a?.name),console.log(X(`\u2713 Project set to "${a?.name??i}" for profile "${r}". Next: pick a workspace.`))}oe();import lx from"picocolors";function cx(e=process.env){return e.FORCE_HYPERLINK==="0"||!lx.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 ux(e,t=e,n){return cx(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var dx=/https?:\/\/[^\s\x1b]+/g;function Es(e,t){return e.replace(dx,n=>ux(n,n,t))}import{readProjectConfig as um,sunsetEnvironment as px,resolveActiveProfile as hx}from"document360-engine";function fx(e,t){let n=um(e);return Object.entries(n?.profiles??{}).find(([,o])=>(o.connection?.environment??"berlin")===t)?.[0]??null}function Un(e,t){try{if(!um(e))return null;let n=hx(e,t),o=px(n.connection.name);if(!o)return null;let r=fx(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 hm(e){return{...dm(e.idToken)??{},...dm(e.accessToken)??{}}}function ta(e){let t=hm(e),n=t.email??t.preferred_username??t.sub??"unknown",o=Wn(e),r=e.projectName?` \xB7 project "${e.projectName}"`:o?` \xB7 project ${o}`:"";return`${n}${r}`}async function Zc(e,t,n){n&&pm(e,t,n);try{let{projects:o}=await Rn(process.cwd(),e);for(let r of Jc(e)){let s=Wn(r);s&&pm(e,s,o.find(i=>i.id===s)?.name)}}catch{}}function Rx(e,t,n){let o=Wn(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 na(e){let t=Ns(process.cwd(),e.profile),n=t.connection;console.log(d(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=Un(process.cwd(),e.profile);o&&(console.log(K(`\u26A0 ${o.why} \u2014 and signing in does NOT change it (the environment comes from the profile, not the login).`)),console.log(K(` To move: ${o.cmd}${o.replacementProfile?"":", then /login"}`)));let r=await gx(n,{manual:e.manual,promptForRedirect:f=>mx({message:f})},f=>console.log(Es(f))),s=wx(t.name,r);$x(s),await eu(s,t.name,f=>console.log(d(f)));let i=Wn(s),a=Ns(process.cwd(),e.profile).project;i&&await Zc(t.name,i,a.projectId===i?a.projectName:void 0);let c=Qc(t.name,i??void 0)??s;console.log(""),console.log(X(`\u2713 Logged in to "${t.name}" as ${ta(c)}`));let l=Rx(c,a.projectId,a.projectName);if(l&&console.log(K(l)),console.log(d(` access token expires: ${s.expiresAt}`)),console.log(d(` refresh token: ${s.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{xx(process.cwd())?.profiles?.[t.name]&&(console.log(""),await kr(process.cwd(),t.name))}catch{}}async function eu(e,t,n){let r=hm(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 Rn(process.cwd(),t);i=a.find(c=>c.id===r)?.name}catch{}vx(process.cwd(),t,{projectId:r,projectName:i}),n(` Project "${i??r}" written to profile "${t}".`)}catch{}}async function fm(e){let t=Ns(process.cwd(),e.profile),n=t.connection,o=Qc(t.name,t.project.projectId);if(!o){console.log(L(`Not logged in to Document360 (profile "${t.name}").`));let r=Jc(t.name).filter(s=>Wn(s)&&Wn(s)!==t.project.projectId);r.length>0&&console.log(d(`This repo's project needs its own sign-in. Signed in on this machine: ${r.map(s=>s.projectName??Wn(s)).join(", ")}`)),console.log(d(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${ee(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${ta(o)}`),kx(o))if(o.refreshToken)try{await yx({profile:t.name,connection:n,projectId:t.project.projectId,projectName:t.project.projectName});let r=Qc(t.name,t.project.projectId);console.log(X(`\u2713 Session refreshed${r?` \u2014 expires ${r.expiresAt}`:""}`))}catch(r){console.log(K(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(d(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(K("Session expired (no refresh token).")),console.log(d(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(d(` expires: ${o.expiresAt}`))}async function mm(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(bx(t.name,n)){console.log(X(e.allProjects?`\u2713 Logged out of every Document360 project for profile "${t.name}".`:`\u2713 Logged out of ${o}.`));let r=Jc(t.name).filter(s=>Wn(s)).length;r>0&&console.log(d(`Still signed in to ${r} other project${r===1?"":"s"} on this machine.`))}else console.log(d(`No Document360 session for ${o} \u2014 nothing to do.`))}oe();import{readProjectConfig as gm,writeProjectConfig as Sx,resolveActiveProfile as Cx,loadTokens as Px,isExpired as Tx}from"document360-engine";function oa(e){let t=gm(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(L("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?ee("\u25CF "):" ",s=o.production?K(" \u26A0 PRODUCTION"):"",i=o.connection.environment??"(inline)",a=Px(n,o.project?.projectId),c=a?Tx(a)&&!a.refreshToken?K("expired"):d("logged in"):d("not logged in");console.log(`${r}${ee(n)} \u2192 ${i}${s} [${c}]`)}console.log(""),console.log(d("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function ra(e,t){let n=gm(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(L(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,Sx(n,e);let o=n.profiles[t].production?K(" \u26A0 PRODUCTION"):"";console.log(X(`\u2713 Default profile is now "${t}"${o}`))}function sa(e,t){try{let n=Cx(e,t);console.log(""),console.log(`Profile ${ee(n.name)}${n.production?K(" \u26A0 PRODUCTION"):""}`),console.log(d(` api: ${n.connection.apiUrl}`)),console.log(d(` identity: ${n.connection.authorizationUrl}`)),console.log(d(` clientId: ${n.connection.clientId}`)),console.log(d(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(d(` project: ${n.project.projectId??"(set at login)"}`)),console.log(d(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(L(n.message)),process.exitCode=1}}oe();import{existsSync as bm,readdirSync as Ax,readFileSync as Ex,statSync as Nx}from"node:fs";import{join as km}from"node:path";import{apiLogDir as Dx}from"document360-engine";var jx=30,Ix=12e3;function Lx(e){if(!bm(e))return{api:[],crash:[]};try{let t=Ax(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 Ox=/·\s*(empty-turn|agent-subprocess|uncaught|unhandled)\s*===/i,_x=/·\s*FATAL\s*·/i,Mx=e=>_x.test(e)||Ox.test(e);function Fx(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(Mx),r=o??n[n.length-1];return{text:r,when:/^=== (\S+)/.exec(r)?.[1]??"",count:n.length,notable:!!o}}function Ux(e,t){let n=t[0];if(!n)return null;try{return Fx(Ex(km(e,n),"utf8"))}catch{return null}}function ym(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}var wm=(e,t)=>{try{return`${(Nx(km(e,t)).size/1024).toFixed(1)} KB`}catch{return""}};function tu(){let e=Dx(),{api:t,crash:n}=Lx(e),o=Ux(e,n),r=[];if(o){let s=o.text.split(/\r?\n/),i=s.slice(0,jx);r.push(o.notable?ne("\u2717",`The last thing that went wrong \u2014 ${ym(o.when)}:`):ne("\u2139",`Nothing has failed. The most recent note d360-writer recorded \u2014 ${ym(o.when)}:`)),r.push("");for(let a of i)r.push(` ${a}`);s.length>i.length&&r.push(d(` \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(d(` ${o.count} entries recorded today; this is the one worth reading.`)),o.notable&&r.push(d(" 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(ne("\u2713","Nothing has failed \u2014 d360-writer has recorded no problems.")),r.push(""));if(r.push(`Logs live in ${ee(e)}`),!bm(e)||t.length===0&&n.length===0)return r.push(d(" 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 ${d("(send these if something crashed or a run did nothing)")}:`);for(let s of n.slice(0,14))r.push(` ${L(s)} ${d(wm(e,s))}`)}if(t.length>0){r.push(""),r.push("Document360 call logs:");for(let s of t.slice(0,14))r.push(` ${s} ${d(wm(e,s))}`)}return r.push(""),r.push(d("Failed calls include what was sent and returned (sign-in details removed, 4 KB cap).")),r.push(d("Set D360_LOG_BODIES=1 to record successful calls too.")),{lines:r,copyText:o?o.text.slice(0,Ix):null,notable:!!o?.notable}}async function $m(){return nu(),{kind:"continue"}}function nu(){let{lines:e,copyText:t}=tu();console.log("");for(let n of e)console.log(n);t&&console.log(d("Inside d360-writer, /logs offers to copy this for you.")),console.log("")}oe();import{createSession as Wx,resolveAuth as Bx,findByName as Hx,slugify as Gx,touchSession as qx,upsertSession as Vx,resolveActiveProfile as Kx}from"document360-engine";async function vm(e,t,n,o,r,s){let i=Bx(n);i.kind==="none"&&(console.error(""),console.error(L("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${ee("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${ee("d360-writer --auth subscription")}`),process.exit(2)),i.kind==="subscription"&&console.error(d("Using your Claude subscription (no API key set)."));let a=null;try{a=Kx(e,r)}catch(k){console.error(L(`Document360 profile error: ${k.message}`)),process.exit(2)}a.production&&(console.error(K(`\u26A0 Profile "${a.name}" is PRODUCTION.`)),s||(console.error(L("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(d(" --yes given \u2014 proceeding against production.")));let c;if(o){let k=Hx(e,o);k||(console.error(L(`No saved session matches "${o}" in this repo.`)),console.error(d("List sessions inside the REPL with /resume.")),process.exit(2)),c=k.uuid,console.error(d(`Resuming "${k.name}"`))}let l=Wx({cwd:e,resume:c,profileName:r,allowProdWrites:s===!0}),f=c??null,g=1;for await(let k of l.send(t))switch(k.type){case"session":if(!f){f=k.sessionId;let T=new Date().toISOString();Vx({uuid:f,name:Gx(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:T,updatedAt:T})}break;case"text":process.stdout.write(k.delta);break;case"tool":console.error(Te(` \u2699 ${k.name}`));break;case"result":g=k.ok?0:1,console.error(d(`(${k.inputTokens}\u2192${k.outputTokens} tokens`+(k.costUsd>0?`, $${k.costUsd<.01?k.costUsd.toFixed(4):k.costUsd.toFixed(2)}`:"")+")")),k.ok||console.error(L("agent finished with an error result"));break;case"error":console.error(""),console.error(L(`agent error: ${k.message}`)),process.exit(1)}f&&qx(f),process.stdout.write(`
307
- `),process.exit(g)}import{createInterface as mj}from"node:readline/promises";import{createSession as Kh,resolveAuth as gj,resolveAuthOrigin as yj,authOriginLine as zk,authOriginFix as wj,getSession as bj,setTitle as kj,slugify as $j,touchSession as e$,upsertSession as vj,generateTitle as xj,resolveActiveProfile as t$,resolveModelSetting as Rj,readProjectConfig as Sj,readUserConfig as Cj,resolveAndPersistAppType as Pj,decodeJwtClaims as Xk,isExpired as Tj,loadTokens as Aj,isDirectiveMention as Ej,stripDirectiveMention as Nj,appendDirective as Dj,reconcileUpgradeActions as jj,stampArticles as Ij,snapshotArticles as Qk,listArticleFiles as Lj,applyStructureOrder as Oj,orderSyncLine as _j,computeSyncStatus as Mj,recordBriefConsumed as Fj}from"document360-engine";import{ENGINE_VERSION as Xx}from"document360-engine";function sn(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 ia(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 sn(`${i+1}. ${s.feature}`,76))o.push(n(a));o.push(n());for(let a of sn(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 aa(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(`
308
- `)}var wt=[{key:"start",label:"Getting Started",rows:[{t:"text",s:"D360-Writer reads your codebase and writes your user documentation."},{t:"gap"},{t:"text",s:"It publishes to Document360 when you are ready."},{t:"gap"},{t:"text",s:"It needs Claude access \u2014 a subscription, or an ANTHROPIC_API_KEY."},{t:"gap"},{t:"sub",s:"Quick start"},{t:"step",n:1,s:"Run /init. Pick your environment, sign in, choose your project."},{t:"step",n:2,s:"Paste the prompt it prints into your coding agent, and let it finish."},{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".'},{t:"gap"},{t:"dim",s:"Claude Code, Codex and Cursor all work. /devhints re-shows that prompt."},{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. Anything not starting with / goes to the agent."},{t:"gap"},{t:"dim",s:"/ browse commands \xB7 \u2191 recall history \xB7 tab run the suggestion"},{t:"dim",s:"1-9 pick from a list \xB7 c copy whatever was offered"},{t:"dim",s:"esc interrupt a run \xB7 ctrl+c twice exit"},{t:"dim",s:"shift+tab switch auto / manual \u2014 see /auto"}]},{key:"agentic",label:"Agentic",rows:[{t:"text",s:"Agentic mode is for products built with an AI coding agent."},{t:"gap"},{t:"text",s:"Your coding agent ships features and leaves notes."},{t:"text",s:"D360-Writer turns those notes into user documentation."},{t:"gap"},{t:"dim",s:"Think of it as a Technical Writer dedicated to your project."},{t:"gap"},{t:"sub",s:"Auto or manual"},{t:"gap"},{t:"text",s:"In MANUAL mode I work out the next step and offer it. You press tab."},{t:"gap"},{t:"text",s:"In AUTO mode I run that step myself, then the one after it."},{t:"gap"},{t:"dim",s:" write \u2192 review \u2192 check the style \u2192 save \u2192 go live"},{t:"gap"},{t:"text",s:"Start a build, come back to a finished knowledge base."},{t:"gap"},{t:"cmd",name:"/auto on",s:"Let me run my own next step."},{t:"cmd",name:"/auto --budget",s:"Cap what one run may spend. The standard cap is $200."},{t:"gap"},{t:"dim",s:" shift+tab switches mode \xB7 esc stops a run"},{t:"dim",s:" Nothing already written, saved or published is undone."},{t:"gap"},{t:"text",s:"Auto changes who presses the key. It does not change what is checked."},{t:"gap"},{t:"text",s:"Every gate still runs."},{t:"text",s:"An article that fails one stays a draft, and the report names it."},{t:"gap"},{t:"text",s:"Screenshots are never automatic \u2014 they need your app on screen."},{t:"gap"},{t:"sub",s:"Every few days"},{t:"cmd",name:"/catch-up",s:"Write up everything pending. It all lands as a draft."},{t:"dim",s:" A note whose code your builder has not committed waits, and they get asked."},{t:"dim",s:" --include-unfinished write those pages anyway"},{t:"cmd",name:"/review --fix",s:"A senior editor reads every article and fixes it."},{t:"cmd",name:"/push --all",s:"Save the reviewed articles to Document360, as drafts."},{t:"cmd",name:"/publish --all",s:"Take those drafts live. It lists them and asks first."},{t:"gap"},{t:"dim",s:" An editorial read is required before anything goes live."},{t:"dim",s:" /review --blocked only the articles publishing is stuck on"},{t:"dim",s:" /review --stale only the ones this editor has not read yet"},{t:"gap"},{t:"sub",s:"Whenever you need"},{t:"cmd",name:"/discover",s:"Interview your builder. Pins a product brief for the docs."},{t:"cmd",name:"/audit",s:"What changed in the code, what is missing from the docs."},{t:"cmd",name:"/pull",s:"Bring down portal edits and any new portal articles."},{t:"cmd",name:"/resolve",s:"Settle a conflict: keep yours, take the portal, or skip."},{t:"cmd",name:"/comments",s:"Reviewer comments on your articles. Read one, answer it."},{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:"dim",s:" An answer fixes the article, saves the draft and replies in the thread."}]},{key:"assistant",label:"Assistant",rows:[{t:"text",s:"D360-Writer is your writing assistant."},{t:"gap"},{t:"text",s:"It does the writing. You decide what gets written, and when."},{t:"gap"},{t:"text",s:"Best for large monorepos: point it at one feature or one set of folders."},{t:"gap"},{t:"sub",s:"Just ask"},{t:"good",s:'"Write the docs for the Multiple JWT feature we shipped last release."'},{t:"gap"},{t:"sub",s:"Or drive it yourself"},{t:"cmd",name:"/scope",s:"Focus on specific source folders."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from its PRDs and the code."},{t:"cmd",name:"/write",s:"Write the planned articles."},{t:"cmd",name:"/push",s:"Save them to Document360 as drafts."},{t:"cmd",name:"/publish",s:"Take the drafts live to your readers."},{t:"cmd",name:"/status",s:"What stands between your work and your readers. Free."},{t:"gap"},{t:"dim",s:" /write --preview shows the plan and the cost first."},{t:"dim",s:" /push --preview <path> shows exactly what Document360 would receive."},{t:"gap"},{t:"sub",s:"One place for what repeats"},{t:"gap"},{t:"text",s:"A variable holds a value \u2014 your product name, a URL \u2014 in one place."},{t:"text",s:"Change it there and every article changes."},{t:"gap"},{t:"text",s:"A snippet does the same for a whole block, like who to contact."},{t:"gap"},{t:"text",s:"A term is defined once, and every article is checked for explaining it."},{t:"gap"},{t:"cmd",name:"/reuse",s:"What your project already keeps on Document360."},{t:"cmd",name:"/reuse pull",s:"Refresh that list from Document360."},{t:"cmd",name:"/reuse add",s:'Create one there: /reuse add variable <name> "<value>".'},{t:"cmd",name:"/reuse audit",s:"Read every article and find what belongs in one place."},{t:"cmd",name:"/terms",s:"Is the same thing called the same name everywhere?"},{t:"cmd",name:"/eval",s:"How does the whole knowledge base score? Free."},{t:"gap"},{t:"dim",s:" Reading is free. Nothing is created until you pick it."},{t:"gap"},{t:"sub",s:"Taking a page back"},{t:"cmd",name:"/retire <path>",s:"Stop showing an article to readers. /push puts it back."},{t:"cmd",name:"/untrack <path>",s:"Disown an imported page that is not one of your docs."},{t:"gap"},{t:"dim",s:" Neither deletes anything. History and reviewer comments stay."}]},{key:"shots",label:"Screenshots",rows:[{t:"text",s:"Documenting a web app? D360-Writer marks where an image helps."},{t:"gap"},{t:"text",s:"The companion CLI d360-capture turns those marks into real,"},{t:"text",s:"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. Placeholders go in where visuals help."},{t:"step",n:2,s:"Run /screenshot author --all to write the capture specs."},{t:"step",n:3,s:"Stage what the checklist asks for, then /screenshot capture."},{t:"step",n:4,s:"The callouts are drawn on straight after. No browser needed."},{t:"step",n:5,s:"Each finished picture is checked, then marked \u2714 verified."},{t:"step",n:6,s:"Run /push --screenshots so the images embed on Document360."},{t:"gap"},{t:"sub",s:"One command family"},{t:"cmd",name:"/screenshot",s:"Pick what to do next."},{t:"cmd",name:"/screenshot author",s:"Write the capture specs."},{t:"cmd",name:"/screenshot capture",s:"Take the shots."},{t:"cmd",name:"/screenshot annotate",s:"Draw the callouts on shots already taken."},{t:"cmd",name:"/screenshot verify",s:"Judge the finished pictures and mark them verified."},{t:"cmd",name:"/screenshot checklist",s:"What to stage, and the test-ids to ask your dev for."},{t:"cmd",name:"/screenshot list",s:"Progress by chapter, and the worklist."},{t:"gap"},{t:"dim",s:" Each takes an <id>, a path, or --all."},{t:"dim",s:" capture --failed re-runs what did not work \xB7 --blocked what waited on data"},{t:"dim",s:" annotate --force re-draws after a wording or style change"},{t:"gap"},{t:"sub",s:"What each state means"},{t:"text",s:"\u2714 verified finished \u2014 this is the finish line"},{t:"text",s:"\u25C8 to verify the picture is done, waiting to be looked at"},{t:"text",s:"\u25CF to annotate shot taken, callouts not drawn on yet"},{t:"text",s:"\u25D0 ready the spec is written, the shot not taken"},{t:"text",s:"\u2691 rejected the shot ran but the picture is wrong"},{t:"text",s:"\u2298 blocked your app lacked the data the shot needs"},{t:"text",s:"\u2717 broken the spec itself is out of date"},{t:"text",s:"\u25CB to-spec no spec written yet"},{t:"gap"},{t:"dim",s:" rejected \u2014 the spec is usually fixed for you, then capture --failed re-shoots"},{t:"dim",s:" blocked \u2014 /screenshot list groups every blocker into a few things to stage"},{t:"dim",s:" broken \u2014 re-author with /screenshot <id>; a re-capture would fail the same way"},{t:"gap"},{t:"dim",s:"One-time setup in your app repo:"},{t:"dim",s:" npm i -g document360-capture \xB7 d360-capture init \xB7 d360-capture auth"}]},{key:"cmds",label:"Commands",rows:[{t:"dim",s:"Every command, one line each \u2014 type / for the full usage."},{t:"dim",s:"The tabs above teach the ones worth more than a line."},{t:"gap"},{t:"sub",s:"Getting started"},{t:"cmd",name:"/init",s:"Set up Document360 and the coding-agent hand-off."},{t:"cmd",name:"/login",s:"Sign in \u2014 one sign-in per project, all kept."},{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."},{t:"cmd",name:"/genre",s:"What kind of product this is \u2014 picks the writing guide."},{t:"cmd",name:"/devhints",s:"Re-show the prompt to paste into your coding agent."},{t:"cmd",name:"/mcp",s:"Connect MCP servers (Notion, Linear, \u2026)."},{t:"gap"},{t:"sub",s:"Agentic \u2014 keep docs in sync"},{t:"cmd",name:"/roadmap",s:"The docs campaign: progress and the next step."},{t:"cmd",name:"/catch-up",s:"Do all pending work \u2192 drafts. --push also saves them."},{t:"cmd",name:"/auto",s:"Run the next step myself instead of waiting for you."},{t:"cmd",name:"/audit",s:"What changed in the code, what's missing from the docs."},{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:"cmd",name:"/share",s:"Get your builder's latest, send yours (automatic)."},{t:"gap"},{t:"sub",s:"Assistant \u2014 directed writing"},{t:"cmd",name:"/discover",s:"Interview your builder \u2192 a product brief for the docs."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from its PRDs and the code."},{t:"cmd",name:"/write",s:"Write the planned articles. --preview costs first."},{t:"cmd",name:"/preview",s:"Render an article locally."},{t:"cmd",name:"/reorder",s:"Put a category's articles in the best reading order."},{t:"cmd",name:"/restructure",s:"Move an article to another category, split one, merge two, rename one."},{t:"cmd",name:"/structure",s:"The reading order, as it will appear on Document360."},{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."},{t:"cmd",name:"/lint",s:"The machine pass over those rules. Free. --fix corrects."},{t:"cmd",name:"/review",s:"The editor pass. Required before anything goes live."},{t:"cmd",name:"/terms",s:"Is the same thing called the same name everywhere? Free."},{t:"cmd",name:"/eval",s:"Score the whole set: links, shape, naming. Free."},{t:"cmd",name:"/reuse",s:"The terms, values and blocks kept on Document360."},{t:"gap"},{t:"sub",s:"Publish & sync"},{t:"cmd",name:"/status",s:"What stands between your work and your readers. Free."},{t:"cmd",name:"/push",s:"Save your articles to Document360 as drafts."},{t:"cmd",name:"/publish",s:"Take the drafts live to your readers. Asks first."},{t:"cmd",name:"/pull",s:"Portal edits + new portal articles. --status: report only."},{t:"cmd",name:"/resolve",s:"Settle a local\u2194portal conflict: keep, take, or skip."},{t:"cmd",name:"/comments",s:"Reviewer comments on your articles \u2014 read and answer."},{t:"cmd",name:"/retire",s:"Take an article off your readers. Nothing is deleted."},{t:"cmd",name:"/untrack",s:"Disown an imported page that is not one of your docs."},{t:"gap"},{t:"sub",s:"Screenshots"},{t:"cmd",name:"/screenshot",s:"The screenshot pipeline. Bare: pick what to do next."},{t:"dim",s:" author \xB7 capture \xB7 annotate \xB7 verify \xB7 checklist \xB7 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 result."},{t:"cmd",name:"/profile",s:"Switch or create a Document360 connection."},{t:"cmd",name:"/allow-prod",s:"Authorize writes to a production profile."},{t:"cmd",name:"/doctor",s:"Health check \u2014 including a real agent turn."},{t:"cmd",name:"/logs",s:"The last problem, in full. Press `c` to copy it."},{t:"cmd",name:"/update",s:"Update D360-Writer, and d360-capture if installed."},{t:"cmd",name:"/feedback",s:"Copy this repo's open feedback, to relay to the team."},{t:"cmd",name:"/logout",s:"Sign out of this project. --all-projects: all of them."},{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."},{t:"cmd",name:"/help",s:"Show this help."},{t:"cmd",name:"/exit",s:"Quit."}]}],xm=24;function ou(e){let t=e.filter(n=>n.t==="cmd").map(n=>n.name.length);return t.length===0?xm:Math.min(xm,Math.max(...t))}var Rm=2;function la(e,t,n,o){let r=" ".repeat(2+n+Rm),s=Math.max(24,o-r.length-2),i=sn(t,s);return e.length>n?{nameCell:e,descLines:i,indent:r,nameOwnLine:!0}:{nameCell:e.padEnd(n+Rm-1),descLines:i,indent:r,nameOwnLine:!1}}function Yx(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=la(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(`
309
- `)}case"gap":return""}}function Sm(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 wt){n.push(`\u2500\u2500 ${o.label} \u2500\u2500`,"");let r=ou(o.rows);for(let s of o.rows)n.push(Yx(s,r,100));n.push("")}return n.push("Tip: anything not starting with / goes to the agent."),n}function ru(e,t){return sn(e,Math.max(10,Math.max(20,t)-2))}function zx(e,t,n){let o=Math.max(20,n),r=s=>Math.max(1,ru(s,o).length);switch(e.t){case"gap":return 1;case"cmd":{let s=la(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 Cm(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=zx(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 Pm(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 su(e=[],t){console.log("");let n=t?.version?{version:t.version,engineVersion:Xx}:void 0;for(let o of Sm(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"}}oe();import{getSession as Qx}from"document360-engine";async function Tm(e,t){let n=t.currentUuid(),o=n?Qx(n):void 0;return console.log(o?d(`
306
+ `)?"":i;Ym(t,`${o}${a}${s.join(i)}${i}`,"utf8")}async function wu(){let e=process.cwd(),t=Jm(e);if(Rr(t)&&!await bx({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(d("init cancelled.")),{kind:"continue"};let n=ng(e)??zm(e),o=await Ls({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await Ls({message:"Capture directory (where document360-capture .spec.ts files live):",default:eg}),s=await Ls({message:"Screenshot output directory:",default:tg}),i=await Ls({message:"Default connection profile name:",default:"berlin"}),a=await Ls({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),c={projectId:o,docsDir:Zm,captureDir:r,outputDir:s,profiles:{[i]:{connection:{environment:a},production:!1}},defaultProfile:i,authoritativeSourceFiles:og(e)},l=$x(e);l?.terminologyGlossary&&(c.terminologyGlossary=l.terminologyGlossary),Qm(c,e),yu(e);let f=vr(e);console.log(""),console.log(Q(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${ee(`d360-writer login --profile ${i}`)} ${d("(sign in; project & workspace auto-selected)")}`),console.log("");for(let g of xr(f))console.log(g);return console.log(""),console.log(`${d("Then ask:")} ${ee('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function ng(e){let t=wa(e,"package.json");if(!Rr(t))return null;try{return JSON.parse(Xm(t,"utf8")).name??null}catch{return null}}function og(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Rr(wa(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=wa(e,n);Rr(o)&&!xx(o)&&t.push(n)}return t}function xx(e){try{return kx(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var Km,ba=As(()=>{"use strict";oe();Gn();Km=[".sessions/","cache/"]});import{createRequire as _x}from"node:module";import{existsSync as Mx,readFileSync as Fx}from"node:fs";import{dirname as fg,join as mg}from"node:path";function kt(){let e;try{e=Ux.resolve("document360-capture/helpers")}catch{return null}let t=fg(e);for(let n=0;n<5&&!Mx(mg(t,"package.json"));n++)t=fg(t);try{let n=JSON.parse(Fx(mg(t,"package.json"),"utf8"));return n.name==="document360-capture"&&n.version?n.version:null}catch{return null}}var Ux,Sr=As(()=>{"use strict";Ux=_x(import.meta.url)});var Iw={};dm(Iw,{doctorCommand:()=>si,renderDoctorChecks:()=>jw,runDoctorChecks:()=>Dw});import{existsSync as GP}from"node:fs";import{d360GetAll as qP,getAccessToken as VP,isExpired as wl,loadProfileMap as YP,loadCoverage as KP,loadTokens as zP,listStoredSessions as XP,tokensProjectId as dp,packageSkillsDir as Nw,ENGINE_VERSION as QP,projectConfigPath as JP,readProjectConfig as ZP,DEFAULT_DOCS_DIR as eT,fetchManifestSummary as tT,resolveActiveProfile as nT,classifyClaudeAuth as oT,resolveAuthOrigin as rT,authOriginLine as sT,authOriginFix as iT,CLAUDE_CODE_SETUP_HINT as bl,resolveModelSetting as aT,probeModel as lT,probeAgentTurn as cT,stderrHeadline as uT,detectAppType as dT,playbookSkillName as pT,D360AuthError as hT,applyStructureOrder as fT}from"document360-engine";async function Dw(e,t){let n=[],o=kt();n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${QP}${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=oT();if(s.state==="ready"){let x=rT(),E=iT(x);n.push({level:E?"warn":"ok",label:`Claude auth: ${sT(x).replace(/^Claude: /,"")}`,...E?{fix:E}:{}})}else 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. ${bl}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:bl});let i=aT(e);if(n.push({level:"ok",label:`Model: ${i.model} (${i.source==="auto"?"auto \u2014 right-sized for docs; /model to change":i.source})`}),s.state==="ready"){let x=await lT(e,i.model??void 0);if(x.ok){n.push({level:"ok",label:`Model reachable \u2014 replied in ${(x.latencyMs/1e3).toFixed(1)}s`});let E=await cT(e,i.model??void 0);if(E.ok)n.push({level:"ok",label:`Agent turn works \u2014 ran with your skills and tools in ${(E.latencyMs/1e3).toFixed(1)}s`});else{let j=uT(E.stderr),W=/auth|sign.?in|login|credential|token|401|expired/i.test(`${E.error??""} ${E.stderr??""}`);if(n.push({level:"fail",label:E.timedOut?"Agent turn never finished \u2014 the model answers, but a real turn with your skills and tools hangs":W?"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 ${E.producedNothing?"ends instantly with no output":`fails: ${E.error}`}`,fix:(j?`Claude Code said: "${j}". `:"")+(W?`Sign in again, then re-run /doctor. ${bl}`:"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.")}),W){let Y=n.find(B=>B.label.startsWith("Claude auth:"));Y&&(Y.level="warn",Y.label="Claude auth: a sign-in exists on this machine, but it is no longer valid",Y.fix=`Sign in again. ${bl}`)}}}else x.timedOut?n.push({level:"fail",label:"Model unreachable \u2014 no response in 30s (a docs turn will hang, then end with 0 tokens / no output)",fix:`Usually a corporate proxy/firewall or org policy blocking the Claude model API. Check this machine's network access to the Claude endpoint; confirm with: claude -p "say hi"`}):n.push({level:"fail",label:`Model call failed \u2014 ${x.error??"no output"} (a docs turn will end with 0 tokens / no output)`,fix:'Check sign-in, the selected model (/model), and network access to the Claude endpoint; confirm with: claude -p "say hi"'})}let a=ZP(e);if(!a)return n.push({level:"fail",label:`No ${JP(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${a.projectId}`});let c=(a.docsDir??eT).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 ${c}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let l=a.authoritativeSourceFiles??[];n.push(l.length>0?{level:"ok",label:`Sources: docs grounded in ${l.length} path(s) (${l.slice(0,3).join(", ")}${l.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 f=a.appType??dT(e);if(f){let x=a.appType?"from config":"auto-detected",E=f==="web"||f==="cli";n.push({level:"ok",label:`Genre: ${f} (${x})${E?` \u2192 ${pT(f)} loaded`:" \u2014 no doc-type playbook for this genre yet (generic skills)"}`})}else n.push({level:"warn",label:"Genre: unclassified \u2014 no doc-type playbook is loading (generic output)",fix:"Run /genre <web|cli|service|library> to pick \u2014 raises docs to that genre's craft bar"});let g;try{g=nT(e),n.push({level:"ok",label:`Profile: ${g.name} (${g.connection.name})${g.production?" \u26A0 PRODUCTION":""}`})}catch(x){return n.push({level:"fail",label:`Profile config: ${x.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let $=zP(g.name,g.project.projectId),T=XP(g.name).filter(x=>{let E=dp(x);return!!E&&E!==g.project.projectId&&!(wl(x)&&!x.refreshToken)}),A=g.project.projectName?`"${g.project.projectName}"`:"this project";$?wl($)&&!$.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"}):wl($)?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 ${A} (until ${new Date($.expiresAt).toLocaleString()})`}):n.push(T.length>0?{level:"fail",label:`Document360: not signed in to ${A} \u2014 signed in to ${T.map(x=>x.projectName?`"${x.projectName}"`:(dp(x)??"").slice(0,8)+"\u2026").join(", ")} instead`,fix:`Run: /login and pick ${A} \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 ${g.name})`}),T.length>0&&n.push({level:"ok",label:`Other Document360 projects signed in on this machine: ${T.map(x=>x.projectName?`"${x.projectName}"`:(dp(x)??"").slice(0,8)+"\u2026").join(", ")} (kept \u2014 each repo uses its own)`}),n.push(g.project.workspaceId?{level:"ok",label:`Workspace: ${g.project.workspaceName??g.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let S=YP(e,g.name);if(!S)n.push({level:"ok",label:`Category map: none yet for "${g.name}" (created on first /push)`});else if(S.projectId&&g.project.projectId&&S.projectId!==g.project.projectId)n.push({level:"fail",label:`Category map projectId (${S.projectId}) \u2260 profile projectId (${g.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"});else{let x=KP(e,g.name),E=`${Object.keys(S.articles).length} articles, ${Object.keys(S.categories).length} categories`;x?x.unmapped>0?n.push({level:"warn",label:`Category map covers ${x.mappedArticles} of ${x.portalArticles} Document360 articles and ${x.mappedCategories} of ${x.portalCategories} categories`+(x.declined>0?` (${x.declined} declined)`:""),fix:`/pull imports the ${x.unmapped} ${x.unmapped===1?"article":"articles"} this repo has no folder for`}):n.push({level:"ok",label:`Category map: ${E} \u2014 every Document360 article is tracked here`}):n.push({level:"ok",label:`Category map: ${E} (not yet compared with Document360)`,fix:"/pull --status compares this repo with Document360"});for(let j of x?.duplicateCategories??[])n.push({level:"warn",label:`Two Document360 categories named "${j.name}" in the same place (${j.ids.join(", ")})`,fix:"Merging or hiding one is your decision \u2014 /restructure moves articles; nothing here deletes"});for(let j of x?.sameNameCategories??[])(x?.duplicateCategories??[]).some(W=>W.name.toLowerCase()===j.name.toLowerCase())||n.push({level:"warn",label:`"${j.name}" is a Document360 category in ${j.entries.length} different places (${j.entries.map(W=>W.id).join(", ")})`,fix:"Readers see them all. Choose which one they keep: /restructure moves articles, /retire hides a page this repo owns, /untrack disowns one that was never ours"})}n.push(GP(Nw())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${Nw()}`,fix:"Reinstall document360-writer (broken install)"});let C=Xt(e);if(C.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${Me})`}):C.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${C.completedVersion}, current is v${Me}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),$&&(!wl($)||$.refreshToken)){let x={profile:g.name,connection:g.connection,projectId:g.project.projectId,projectName:g.project.projectName};try{await VP(x);let j=await qP(x,"/v3/projects");n.push({level:"ok",label:`API reachable (${g.connection.apiUrl}) \u2014 ${j.length} project(s) visible`})}catch(j){n.push({level:"fail",label:`API call failed: ${j.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let E=S?.projectId??g.project.projectId;if(E&&g.project.workspaceId){try{let j=await tT(x,E,g.project.workspaceId);if(j){let W=(j.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Your Document360 project: reachable on ${g.connection.name} (${j.languages?.length??0} language${(j.languages?.length??0)===1?"":"s"}) \xB7 version ${W||"(none)"}`})}else n.push({level:"ok",label:`Workspace sync manifest: not live on ${g.connection.name} yet \u2014 sync uses the per-article path (nothing to do)`})}catch(j){j instanceof hT||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(j.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${g.project.projectName??E})`,fix:"Run /login and pick this repo's project \u2014 your token is scoped to another project"}):n.push({level:"warn",label:`Workspace sync manifest: probe failed (${j.message.slice(0,80)})`})}try{let j=await fT({cwd:e,profileName:g.name,dryRun:!0}),W=j.categoriesReordered+j.articlesReordered;if(j.skipped==="no category map")n.push({level:"ok",label:"Reading order: nothing to check yet (no articles published)"});else if(j.skipped)n.push({level:"warn",label:`Reading order: can't be checked (${j.skipped})`,fix:"Your article order on Document360 may not match your structure \u2014 /push syncs it once this resolves"});else if(j.unverified)n.push({level:"warn",label:`Reading order: ${j.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(W>0){let Y=[j.categoriesReordered>0?`${j.categoriesReordered} categor${j.categoriesReordered===1?"y":"ies"}`:"",j.articlesReordered>0?`${j.articlesReordered} article${j.articlesReordered===1?"":"s"}`:""].filter(Boolean);n.push({level:"warn",label:`Reading order: ${Y.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(j.orphans?.length){let Y=j.orphans;n.push({level:"warn",label:`${Y.length} article${Y.length===1?"":"s"} on Document360 ${Y.length===1?"is":"are"} not in your docs folder: ${Y.slice(0,3).map(B=>B.path).join(", ")}${Y.length>3?`, +${Y.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(j){n.push({level:"warn",label:`Reading order: check failed (${j.message.slice(0,80)})`})}}}return n}function jw(e){let t=[""];for(let r of e){let s=r.level==="ok"?Q("\u2713"):r.level==="warn"?q("\u26A0"):L("\u2717");t.push(` ${s} ${r.label}${r.detail?d(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${d("fix:")} ${ee(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"})`}`):L(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function si(e,t){console.log(d("Running checks\u2026"));for(let n of jw(await Dw(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var kl=As(()=>{"use strict";Gn();oe();Sr()});import{Command as EO}from"commander";import{createRequire as NO}from"node:module";import{AUTH_MODES as DO}from"document360-engine";import{input as S0}from"@inquirer/prompts";import{loginPkce as C0,getAccessToken as P0,toStoredTokens as T0,clearTokens as A0,decodeJwtClaims as wm,isExpired as E0,loadTokens as nu,saveTokens as N0,listStoredSessions as ou,tokensProjectId as Bn,rememberSessionProject as bm,resolveActiveProfile as js,setProfileProject as D0,readProjectConfig as j0}from"document360-engine";oe();import{select as c0}from"@inquirer/prompts";import{resolveActiveProfile as u0,setProfileProject as d0,resolveProjectId as p0,listWorkspaces as h0}from"document360-engine";async function Ns(e,t){let n=u0(e,t),o={profile:n.name,connection:n.connection,projectId:n.project.projectId,projectName:n.project.projectName},r=n.project.projectId??p0(o);return{workspaces:await h0(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var hm=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function eu(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 oa(e,t,n,o,r){d0(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function fm(e,t,n){let o;try{o=await Ns(e,n)}catch(s){return console.log(L(`Could not list workspaces: ${s.message}`)),1}let r=eu(o.workspaces,t);return r?(oa(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(L(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function br(e,t){let n;try{n=await Ns(e,t)}catch(l){console.log(L(`Could not list workspaces: ${l.message}`));return}let{workspaces:o,projectId:r,profile:s,current:i}=n;if(o.length===0){console.log(d("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let l of o)console.log(` ${l.id===i?ee("\u25CF"):" "} ${hm(l)} ${d(l.id)}`);console.log(d("Run: d360-writer workspace use <name>"));return}let a=await c0({message:"Select the Document360 workspace for this repo:",choices:o.map(l=>({name:`${hm(l)}${l.id===i?" (current)":""}`,value:l.id}))}),c=o.find(l=>l.id===a);oa(e,s,r,a,c?.name),console.log(Q(`\u2713 Workspace set to "${c?.name??a}" for profile "${s}".`))}oe();import{select as f0}from"@inquirer/prompts";import{resolveActiveProfile as m0,setProfileProject as g0,listProjects as y0}from"document360-engine";async function Cn(e,t){let n=m0(e,t),o={profile:n.name,connection:n.connection};return{projects:await y0(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var mm=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function tu(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 ra(e,t,n,o){g0(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function gm(e,t,n){let o;try{o=await Cn(e,n)}catch(s){return console.log(L(`Could not list projects: ${s.message}`)),1}let r=tu(o.projects,t);return r?(ra(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(L(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function sa(e,t){let n;try{n=await Cn(e,t)}catch(c){console.log(L(`Could not list projects: ${c.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(d("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let c of o)console.log(` ${c.id===s?ee("\u25CF"):" "} ${mm(c)} ${d(c.id)}`);console.log(d("Run: d360-writer project use <name>"));return}let i=await f0({message:"Select the Document360 project for this repo:",choices:o.map(c=>({name:`${mm(c)}${c.id===s?" (current)":""}`,value:c.id}))}),a=o.find(c=>c.id===i);ra(e,r,i,a?.name),console.log(Q(`\u2713 Project set to "${a?.name??i}" for profile "${r}". Next: pick a workspace.`))}oe();import w0 from"picocolors";function b0(e=process.env){return e.FORCE_HYPERLINK==="0"||!w0.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 k0(e,t=e,n){return b0(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var $0=/https?:\/\/[^\s\x1b]+/g;function Ds(e,t){return e.replace($0,n=>k0(n,n,t))}import{readProjectConfig as ym,sunsetEnvironment as v0,resolveActiveProfile as x0}from"document360-engine";function R0(e,t){let n=ym(e);return Object.entries(n?.profiles??{}).find(([,o])=>(o.connection?.environment??"berlin")===t)?.[0]??null}function Wn(e,t){try{if(!ym(e))return null;let n=x0(e,t),o=v0(n.connection.name);if(!o)return null;let r=R0(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 km(e){return{...wm(e.idToken)??{},...wm(e.accessToken)??{}}}function ia(e){let t=km(e),n=t.email??t.preferred_username??t.sub??"unknown",o=Bn(e),r=e.projectName?` \xB7 project "${e.projectName}"`:o?` \xB7 project ${o}`:"";return`${n}${r}`}async function ru(e,t,n){n&&bm(e,t,n);try{let{projects:o}=await Cn(process.cwd(),e);for(let r of ou(e)){let s=Bn(r);s&&bm(e,s,o.find(i=>i.id===s)?.name)}}catch{}}function I0(e,t,n){let o=Bn(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 aa(e){let t=js(process.cwd(),e.profile),n=t.connection;console.log(d(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=Wn(process.cwd(),e.profile);o&&(console.log(q(`\u26A0 ${o.why} \u2014 and signing in does NOT change it (the environment comes from the profile, not the login).`)),console.log(q(` To move: ${o.cmd}${o.replacementProfile?"":", then /login"}`)));let r=await C0(n,{manual:e.manual,promptForRedirect:f=>S0({message:f})},f=>console.log(Ds(f))),s=T0(t.name,r);N0(s),await su(s,t.name,f=>console.log(d(f)));let i=Bn(s),a=js(process.cwd(),e.profile).project;i&&await ru(t.name,i,a.projectId===i?a.projectName:void 0);let c=nu(t.name,i??void 0)??s;console.log(""),console.log(Q(`\u2713 Logged in to "${t.name}" as ${ia(c)}`));let l=I0(c,a.projectId,a.projectName);if(l&&console.log(q(l)),console.log(d(` access token expires: ${s.expiresAt}`)),console.log(d(` refresh token: ${s.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{j0(process.cwd())?.profiles?.[t.name]&&(console.log(""),await br(process.cwd(),t.name))}catch{}}async function su(e,t,n){let r=km(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(js(process.cwd(),t).project.projectId)return;let i;try{let{projects:a}=await Cn(process.cwd(),t);i=a.find(c=>c.id===r)?.name}catch{}D0(process.cwd(),t,{projectId:r,projectName:i}),n(` Project "${i??r}" written to profile "${t}".`)}catch{}}async function $m(e){let t=js(process.cwd(),e.profile),n=t.connection,o=nu(t.name,t.project.projectId);if(!o){console.log(L(`Not logged in to Document360 (profile "${t.name}").`));let r=ou(t.name).filter(s=>Bn(s)&&Bn(s)!==t.project.projectId);r.length>0&&console.log(d(`This repo's project needs its own sign-in. Signed in on this machine: ${r.map(s=>s.projectName??Bn(s)).join(", ")}`)),console.log(d(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${ee(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${ia(o)}`),E0(o))if(o.refreshToken)try{await P0({profile:t.name,connection:n,projectId:t.project.projectId,projectName:t.project.projectName});let r=nu(t.name,t.project.projectId);console.log(Q(`\u2713 Session refreshed${r?` \u2014 expires ${r.expiresAt}`:""}`))}catch(r){console.log(q(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(d(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(q("Session expired (no refresh token).")),console.log(d(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(d(` expires: ${o.expiresAt}`))}async function vm(e){let t=js(process.cwd(),e.profile),n=e.allProjects?void 0:t.project.projectId,o=t.project.projectName?`"${t.project.projectName}"`:`profile "${t.name}"`;if(A0(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=ou(t.name).filter(s=>Bn(s)).length;r>0&&console.log(d(`Still signed in to ${r} other project${r===1?"":"s"} on this machine.`))}else console.log(d(`No Document360 session for ${o} \u2014 nothing to do.`))}oe();import{readProjectConfig as xm,writeProjectConfig as L0,resolveActiveProfile as O0,loadTokens as _0,isExpired as M0}from"document360-engine";function la(e){let t=xm(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(L("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?ee("\u25CF "):" ",s=o.production?q(" \u26A0 PRODUCTION"):"",i=o.connection.environment??"(inline)",a=_0(n,o.project?.projectId),c=a?M0(a)&&!a.refreshToken?q("expired"):d("logged in"):d("not logged in");console.log(`${r}${ee(n)} \u2192 ${i}${s} [${c}]`)}console.log(""),console.log(d("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function ca(e,t){let n=xm(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(L(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,L0(n,e);let o=n.profiles[t].production?q(" \u26A0 PRODUCTION"):"";console.log(Q(`\u2713 Default profile is now "${t}"${o}`))}function ua(e,t){try{let n=O0(e,t);console.log(""),console.log(`Profile ${ee(n.name)}${n.production?q(" \u26A0 PRODUCTION"):""}`),console.log(d(` api: ${n.connection.apiUrl}`)),console.log(d(` identity: ${n.connection.authorizationUrl}`)),console.log(d(` clientId: ${n.connection.clientId}`)),console.log(d(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(d(` project: ${n.project.projectId??"(set at login)"}`)),console.log(d(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(L(n.message)),process.exitCode=1}}oe();import{existsSync as Cm,readdirSync as F0,readFileSync as U0,statSync as W0}from"node:fs";import{join as Pm}from"node:path";import{apiLogDir as B0}from"document360-engine";var H0=30,G0=12e3;function q0(e){if(!Cm(e))return{api:[],crash:[]};try{let t=F0(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 V0=/·\s*(empty-turn|agent-subprocess|uncaught|unhandled)\s*===/i,Y0=/·\s*FATAL\s*·/i,K0=e=>Y0.test(e)||V0.test(e);function z0(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(K0),r=o??n[n.length-1];return{text:r,when:/^=== (\S+)/.exec(r)?.[1]??"",count:n.length,notable:!!o}}function X0(e,t){let n=t[0];if(!n)return null;try{return z0(U0(Pm(e,n),"utf8"))}catch{return null}}function Rm(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}var Sm=(e,t)=>{try{return`${(W0(Pm(e,t)).size/1024).toFixed(1)} KB`}catch{return""}};function iu(){let e=B0(),{api:t,crash:n}=q0(e),o=X0(e,n),r=[];if(o){let s=o.text.split(/\r?\n/),i=s.slice(0,H0);r.push(o.notable?ne("\u2717",`The last thing that went wrong \u2014 ${Rm(o.when)}:`):ne("\u2139",`Nothing has failed. The most recent note d360-writer recorded \u2014 ${Rm(o.when)}:`)),r.push("");for(let a of i)r.push(` ${a}`);s.length>i.length&&r.push(d(` \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(d(` ${o.count} entries recorded today; this is the one worth reading.`)),o.notable&&r.push(d(" 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(ne("\u2713","Nothing has failed \u2014 d360-writer has recorded no problems.")),r.push(""));if(r.push(`Logs live in ${ee(e)}`),!Cm(e)||t.length===0&&n.length===0)return r.push(d(" 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 ${d("(send these if something crashed or a run did nothing)")}:`);for(let s of n.slice(0,14))r.push(` ${L(s)} ${d(Sm(e,s))}`)}if(t.length>0){r.push(""),r.push("Document360 call logs:");for(let s of t.slice(0,14))r.push(` ${s} ${d(Sm(e,s))}`)}return r.push(""),r.push(d("Failed calls include what was sent and returned (sign-in details removed, 4 KB cap).")),r.push(d("Set D360_LOG_BODIES=1 to record successful calls too.")),{lines:r,copyText:o?o.text.slice(0,G0):null,notable:!!o?.notable}}async function Tm(){return au(),{kind:"continue"}}function au(){let{lines:e,copyText:t}=iu();console.log("");for(let n of e)console.log(n);t&&console.log(d("Inside d360-writer, /logs offers to copy this for you.")),console.log("")}oe();import{createSession as Q0,resolveAuth as J0,findByName as Z0,slugify as ex,touchSession as tx,upsertSession as nx,resolveActiveProfile as ox}from"document360-engine";async function Am(e,t,n,o,r,s){let i=J0(n);i.kind==="none"&&(console.error(""),console.error(L("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${ee("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${ee("d360-writer --auth subscription")}`),process.exit(2)),i.kind==="subscription"&&console.error(d("Using your Claude subscription (no API key set)."));let a=null;try{a=ox(e,r)}catch($){console.error(L(`Document360 profile error: ${$.message}`)),process.exit(2)}a.production&&(console.error(q(`\u26A0 Profile "${a.name}" is PRODUCTION.`)),s||(console.error(L("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(d(" --yes given \u2014 proceeding against production.")));let c;if(o){let $=Z0(e,o);$||(console.error(L(`No saved session matches "${o}" in this repo.`)),console.error(d("List sessions inside the REPL with /resume.")),process.exit(2)),c=$.uuid,console.error(d(`Resuming "${$.name}"`))}let l=Q0({cwd:e,resume:c,profileName:r,allowProdWrites:s===!0}),f=c??null,g=1;for await(let $ of l.send(t))switch($.type){case"session":if(!f){f=$.sessionId;let T=new Date().toISOString();nx({uuid:f,name:ex(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:T,updatedAt:T})}break;case"text":process.stdout.write($.delta);break;case"tool":console.error(Te(` \u2699 ${$.name}`));break;case"result":g=$.ok?0:1,console.error(d(`(${$.inputTokens}\u2192${$.outputTokens} tokens`+($.costUsd>0?`, $${$.costUsd<.01?$.costUsd.toFixed(4):$.costUsd.toFixed(2)}`:"")+")")),$.ok||console.error(L("agent finished with an error result"));break;case"error":console.error(""),console.error(L(`agent error: ${$.message}`)),process.exit(1)}f&&tx(f),process.stdout.write(`
307
+ `),process.exit(g)}import{createInterface as Ij}from"node:readline/promises";import{createSession as Zh,resolveAuth as Lj,resolveAuthOrigin as Oj,authOriginLine as r$,authOriginFix as _j,getSession as Mj,setTitle as Fj,slugify as Uj,touchSession as c$,upsertSession as Wj,generateTitle as Bj,resolveActiveProfile as u$,resolveModelSetting as Hj,readProjectConfig as Gj,readUserConfig as qj,resolveAndPersistAppType as Vj,decodeJwtClaims as s$,isExpired as Yj,loadTokens as Kj,isDirectiveMention as zj,stripDirectiveMention as Xj,appendDirective as Qj,reconcileUpgradeActions as Jj,stampArticles as Zj,snapshotArticles as i$,listArticleFiles as eI,applyStructureOrder as tI,orderSyncLine as nI,computeSyncStatus as oI,recordBriefConsumed as rI}from"document360-engine";import{ENGINE_VERSION as ix}from"document360-engine";function an(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 da(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 an(`${i+1}. ${s.feature}`,76))o.push(n(a));o.push(n());for(let a of an(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 pa(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(`
308
+ `)}var bt=[{key:"start",label:"Getting Started",rows:[{t:"text",s:"D360-Writer reads your codebase and writes your user documentation."},{t:"gap"},{t:"text",s:"It publishes to Document360 when you are ready."},{t:"gap"},{t:"text",s:"It needs Claude access \u2014 a subscription, or an ANTHROPIC_API_KEY."},{t:"gap"},{t:"sub",s:"Quick start"},{t:"step",n:1,s:"Run /init. Pick your environment, sign in, choose your project."},{t:"step",n:2,s:"Paste the prompt it prints into your coding agent, and let it finish."},{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".'},{t:"gap"},{t:"dim",s:"Claude Code, Codex and Cursor all work. /devhints re-shows that prompt."},{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. Anything not starting with / goes to the agent."},{t:"gap"},{t:"dim",s:"/ browse commands \xB7 \u2191 recall history \xB7 tab run the suggestion"},{t:"dim",s:"1-9 pick from a list \xB7 c copy whatever was offered"},{t:"dim",s:"esc interrupt a run \xB7 ctrl+c twice exit"},{t:"dim",s:"shift+tab switch auto / manual \u2014 see /auto"}]},{key:"agentic",label:"Agentic",rows:[{t:"text",s:"Agentic mode is for products built with an AI coding agent."},{t:"gap"},{t:"text",s:"Your coding agent ships features and leaves notes."},{t:"text",s:"D360-Writer turns those notes into user documentation."},{t:"gap"},{t:"dim",s:"Think of it as a Technical Writer dedicated to your project."},{t:"gap"},{t:"sub",s:"Auto or manual"},{t:"gap"},{t:"text",s:"In MANUAL mode I work out the next step and offer it. You press tab."},{t:"gap"},{t:"text",s:"In AUTO mode I run that step myself, then the one after it."},{t:"gap"},{t:"dim",s:" write \u2192 review \u2192 check the style \u2192 save \u2192 go live"},{t:"gap"},{t:"text",s:"Start a build, come back to a finished knowledge base."},{t:"gap"},{t:"cmd",name:"/auto on",s:"Let me run my own next step."},{t:"cmd",name:"/auto --budget",s:"Cap what one run may spend. The standard cap is $200."},{t:"gap"},{t:"dim",s:" shift+tab switches mode \xB7 esc stops a run"},{t:"dim",s:" Nothing already written, saved or published is undone."},{t:"gap"},{t:"text",s:"Auto changes who presses the key. It does not change what is checked."},{t:"gap"},{t:"text",s:"Every gate still runs."},{t:"text",s:"An article that fails one stays a draft, and the report names it."},{t:"gap"},{t:"text",s:"Screenshots are never automatic \u2014 they need your app on screen."},{t:"gap"},{t:"sub",s:"Every few days"},{t:"cmd",name:"/catch-up",s:"Write up everything pending. It all lands as a draft."},{t:"dim",s:" A note whose code your builder has not committed waits, and they get asked."},{t:"dim",s:" --include-unfinished write those pages anyway"},{t:"cmd",name:"/review --fix",s:"A senior editor reads every article and fixes it."},{t:"cmd",name:"/push --all",s:"Save the reviewed articles to Document360, as drafts."},{t:"cmd",name:"/publish --all",s:"Take those drafts live. It lists them and asks first."},{t:"gap"},{t:"dim",s:" An editorial read is required before anything goes live."},{t:"dim",s:" /review --blocked only the articles publishing is stuck on"},{t:"dim",s:" /review --stale only the ones this editor has not read yet"},{t:"gap"},{t:"sub",s:"Whenever you need"},{t:"cmd",name:"/discover",s:"Interview your builder. Pins a product brief for the docs."},{t:"cmd",name:"/audit",s:"What changed in the code, what is missing from the docs."},{t:"cmd",name:"/pull",s:"Bring down portal edits and any new portal articles."},{t:"cmd",name:"/resolve",s:"Settle a conflict: keep yours, take the portal, or skip."},{t:"cmd",name:"/comments",s:"Reviewer comments on your articles. Read one, answer it."},{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:"dim",s:" An answer fixes the article, saves the draft and replies in the thread."}]},{key:"assistant",label:"Assistant",rows:[{t:"text",s:"D360-Writer is your writing assistant."},{t:"gap"},{t:"text",s:"It does the writing. You decide what gets written, and when."},{t:"gap"},{t:"text",s:"Best for large monorepos: point it at one feature or one set of folders."},{t:"gap"},{t:"sub",s:"Just ask"},{t:"good",s:'"Write the docs for the Multiple JWT feature we shipped last release."'},{t:"gap"},{t:"sub",s:"Or drive it yourself"},{t:"cmd",name:"/scope",s:"Focus on specific source folders."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from its PRDs and the code."},{t:"cmd",name:"/write",s:"Write the planned articles."},{t:"cmd",name:"/push",s:"Save them to Document360 as drafts."},{t:"cmd",name:"/publish",s:"Take the drafts live to your readers."},{t:"cmd",name:"/status",s:"What stands between your work and your readers. Free."},{t:"gap"},{t:"dim",s:" /write --preview shows the plan and the cost first."},{t:"dim",s:" /push --preview <path> shows exactly what Document360 would receive."},{t:"gap"},{t:"sub",s:"One place for what repeats"},{t:"gap"},{t:"text",s:"A variable holds a value \u2014 your product name, a URL \u2014 in one place."},{t:"text",s:"Change it there and every article changes."},{t:"gap"},{t:"text",s:"A snippet does the same for a whole block, like who to contact."},{t:"gap"},{t:"text",s:"A term is defined once, and every article is checked for explaining it."},{t:"gap"},{t:"cmd",name:"/reuse",s:"What your project already keeps on Document360."},{t:"cmd",name:"/reuse pull",s:"Refresh that list from Document360."},{t:"cmd",name:"/reuse add",s:'Create one there: /reuse add variable <name> "<value>".'},{t:"cmd",name:"/reuse audit",s:"Read every article and find what belongs in one place."},{t:"cmd",name:"/terms",s:"Is the same thing called the same name everywhere?"},{t:"cmd",name:"/eval",s:"How does the whole knowledge base score? Free."},{t:"gap"},{t:"dim",s:" Reading is free. Nothing is created until you pick it."},{t:"gap"},{t:"sub",s:"Taking a page back"},{t:"cmd",name:"/retire <path>",s:"Stop showing an article to readers. /push puts it back."},{t:"cmd",name:"/untrack <path>",s:"Disown an imported page that is not one of your docs."},{t:"gap"},{t:"dim",s:" Neither deletes anything. History and reviewer comments stay."}]},{key:"shots",label:"Screenshots",rows:[{t:"text",s:"Documenting a web app? D360-Writer marks where an image helps."},{t:"gap"},{t:"text",s:"The companion CLI d360-capture turns those marks into real,"},{t:"text",s:"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. Placeholders go in where visuals help."},{t:"step",n:2,s:"Run /screenshot author --all to write the capture specs."},{t:"step",n:3,s:"Stage what the checklist asks for, then /screenshot capture."},{t:"step",n:4,s:"The callouts are drawn on straight after. No browser needed."},{t:"step",n:5,s:"Each finished picture is checked, then marked \u2714 verified."},{t:"step",n:6,s:"Run /push --screenshots so the images embed on Document360."},{t:"gap"},{t:"sub",s:"One command family"},{t:"cmd",name:"/screenshot",s:"Pick what to do next."},{t:"cmd",name:"/screenshot author",s:"Write the capture specs."},{t:"cmd",name:"/screenshot capture",s:"Take the shots."},{t:"cmd",name:"/screenshot annotate",s:"Draw the callouts on shots already taken."},{t:"cmd",name:"/screenshot verify",s:"Judge the finished pictures and mark them verified."},{t:"cmd",name:"/screenshot checklist",s:"What to stage, and the test-ids to ask your dev for."},{t:"cmd",name:"/screenshot list",s:"Progress by chapter, and the worklist."},{t:"gap"},{t:"dim",s:" Each takes an <id>, a path, or --all."},{t:"dim",s:" capture --failed re-runs what did not work \xB7 --blocked what waited on data"},{t:"dim",s:" annotate --force re-draws after a wording or style change"},{t:"gap"},{t:"sub",s:"What each state means"},{t:"text",s:"\u2714 verified finished \u2014 this is the finish line"},{t:"text",s:"\u25C8 to verify the picture is done, waiting to be looked at"},{t:"text",s:"\u25CF to annotate shot taken, callouts not drawn on yet"},{t:"text",s:"\u25D0 ready the spec is written, the shot not taken"},{t:"text",s:"\u2691 rejected the shot ran but the picture is wrong"},{t:"text",s:"\u2298 blocked your app lacked the data the shot needs"},{t:"text",s:"\u2717 broken the spec itself is out of date"},{t:"text",s:"\u25CB to-spec no spec written yet"},{t:"gap"},{t:"dim",s:" rejected \u2014 the spec is usually fixed for you, then capture --failed re-shoots"},{t:"dim",s:" blocked \u2014 /screenshot list groups every blocker into a few things to stage"},{t:"dim",s:" broken \u2014 re-author with /screenshot <id>; a re-capture would fail the same way"},{t:"gap"},{t:"dim",s:"One-time setup in your app repo:"},{t:"dim",s:" npm i -g document360-capture \xB7 d360-capture init \xB7 d360-capture auth"}]},{key:"cmds",label:"Commands",rows:[{t:"dim",s:"Every command, one line each \u2014 type / for the full usage."},{t:"dim",s:"The tabs above teach the ones worth more than a line."},{t:"gap"},{t:"sub",s:"Getting started"},{t:"cmd",name:"/init",s:"Set up Document360 and the coding-agent hand-off."},{t:"cmd",name:"/login",s:"Sign in \u2014 one sign-in per project, all kept."},{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."},{t:"cmd",name:"/genre",s:"What kind of product this is \u2014 picks the writing guide."},{t:"cmd",name:"/devhints",s:"Re-show the prompt to paste into your coding agent."},{t:"cmd",name:"/mcp",s:"Connect MCP servers (Notion, Linear, \u2026)."},{t:"gap"},{t:"sub",s:"Agentic \u2014 keep docs in sync"},{t:"cmd",name:"/roadmap",s:"The docs campaign: progress and the next step."},{t:"cmd",name:"/catch-up",s:"Do all pending work \u2192 drafts. --push also saves them."},{t:"cmd",name:"/auto",s:"Run the next step myself instead of waiting for you."},{t:"cmd",name:"/audit",s:"What changed in the code, what's missing from the docs."},{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:"cmd",name:"/share",s:"Get your builder's latest, send yours (automatic)."},{t:"gap"},{t:"sub",s:"Assistant \u2014 directed writing"},{t:"cmd",name:"/discover",s:"Interview your builder \u2192 a product brief for the docs."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from its PRDs and the code."},{t:"cmd",name:"/write",s:"Write the planned articles. --preview costs first."},{t:"cmd",name:"/preview",s:"Render an article locally."},{t:"cmd",name:"/reorder",s:"Put a category's articles in the best reading order."},{t:"cmd",name:"/restructure",s:"Move an article to another category, split one, merge two, rename one."},{t:"cmd",name:"/structure",s:"The reading order, as it will appear on Document360."},{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."},{t:"cmd",name:"/lint",s:"The machine pass over those rules. Free. --fix corrects."},{t:"cmd",name:"/review",s:"The editor pass. Required before anything goes live."},{t:"cmd",name:"/terms",s:"Is the same thing called the same name everywhere? Free."},{t:"cmd",name:"/eval",s:"Score the whole set: links, shape, naming. Free."},{t:"cmd",name:"/reuse",s:"The terms, values and blocks kept on Document360."},{t:"gap"},{t:"sub",s:"Publish & sync"},{t:"cmd",name:"/status",s:"What stands between your work and your readers. Free."},{t:"cmd",name:"/push",s:"Save your articles to Document360 as drafts."},{t:"cmd",name:"/publish",s:"Take the drafts live to your readers. Asks first."},{t:"cmd",name:"/pull",s:"Portal edits + new portal articles. --status: report only."},{t:"cmd",name:"/resolve",s:"Settle a local\u2194portal conflict: keep, take, or skip."},{t:"cmd",name:"/comments",s:"Reviewer comments on your articles \u2014 read and answer."},{t:"cmd",name:"/retire",s:"Take an article off your readers. Nothing is deleted."},{t:"cmd",name:"/untrack",s:"Disown an imported page that is not one of your docs."},{t:"gap"},{t:"sub",s:"Screenshots"},{t:"cmd",name:"/screenshot",s:"The screenshot pipeline. Bare: pick what to do next."},{t:"dim",s:" author \xB7 capture \xB7 annotate \xB7 verify \xB7 checklist \xB7 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 result."},{t:"cmd",name:"/profile",s:"Switch or create a Document360 connection."},{t:"cmd",name:"/allow-prod",s:"Authorize writes to a production profile."},{t:"cmd",name:"/doctor",s:"Health check \u2014 including a real agent turn."},{t:"cmd",name:"/logs",s:"The last problem, in full. Press `c` to copy it."},{t:"cmd",name:"/update",s:"Update D360-Writer, and d360-capture if installed."},{t:"cmd",name:"/feedback",s:"Copy this repo's open feedback, to relay to the team."},{t:"cmd",name:"/logout",s:"Sign out of this project. --all-projects: all of them."},{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."},{t:"cmd",name:"/help",s:"Show this help."},{t:"cmd",name:"/exit",s:"Quit."}]}],Em=24;function lu(e){let t=e.filter(n=>n.t==="cmd").map(n=>n.name.length);return t.length===0?Em:Math.min(Em,Math.max(...t))}var Nm=2;function ha(e,t,n,o){let r=" ".repeat(2+n+Nm),s=Math.max(24,o-r.length-2),i=an(t,s);return e.length>n?{nameCell:e,descLines:i,indent:r,nameOwnLine:!0}:{nameCell:e.padEnd(n+Nm-1),descLines:i,indent:r,nameOwnLine:!1}}function rx(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=ha(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(`
309
+ `)}case"gap":return""}}function Dm(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 bt){n.push(`\u2500\u2500 ${o.label} \u2500\u2500`,"");let r=lu(o.rows);for(let s of o.rows)n.push(rx(s,r,100));n.push("")}return n.push("Tip: anything not starting with / goes to the agent."),n}function cu(e,t){return an(e,Math.max(10,Math.max(20,t)-2))}function sx(e,t,n){let o=Math.max(20,n),r=s=>Math.max(1,cu(s,o).length);switch(e.t){case"gap":return 1;case"cmd":{let s=ha(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 jm(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=sx(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 Im(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 uu(e=[],t){console.log("");let n=t?.version?{version:t.version,engineVersion:ix}:void 0;for(let o of Dm(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"}}oe();import{getSession as ax}from"document360-engine";async function Lm(e,t){let n=t.currentUuid(),o=n?ax(n):void 0;return console.log(o?d(`
310
310
  (conversation reset \u2014 "${o.name}" is still available via /resume)
311
311
  `):d(`
312
312
  (conversation reset \u2014 agent will start fresh on the next prompt)
313
- `)),{kind:"clear"}}async function iu(){return{kind:"exit"}}fa();oe();import{readMcpConfig as fu,writeMcpConfig as Jm}from"document360-engine";async function ma(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(f0(),{kind:"continue"}):t==="add"?(m0(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(g0(e.slice(1)),{kind:"continue"}):(console.log(L(`Unknown /mcp subcommand: ${t}`)),console.log(d("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function f0(){let e=fu(),t=Object.keys(e.servers);if(t.length===0){console.log(d(`
313
+ `)),{kind:"clear"}}async function du(){return{kind:"exit"}}ba();oe();import{readMcpConfig as bu,writeMcpConfig as sg}from"document360-engine";async function ka(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(Rx(),{kind:"continue"}):t==="add"?(Sx(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(Cx(e.slice(1)),{kind:"continue"}):(console.log(L(`Unknown /mcp subcommand: ${t}`)),console.log(d("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function Rx(){let e=bu(),t=Object.keys(e.servers);if(t.length===0){console.log(d(`
314
314
  No MCP servers registered. Add one with /mcp add <name> <type> <ref>
315
- `));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(` ${ee(n)} ${d("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?d(` [headers: ${r.join(", ")}]`):"";console.log(` ${ee(n)} ${d(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function m0(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(L("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(L(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=fu(),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 c=o[++a],l=c?.match(/^([^:=]+)[:=](.+)$/);if(!l){console.log(L(`-H expects key:value (no spaces). Got: ${c??"(nothing)"}`));return}i[l[1].trim()]=l[2].trim()}else{console.log(L(`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,Jm(r),console.log(""),console.log(X(`\u2713 Registered "${t}" (${n})`)),console.log(K(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(d(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function g0(e){let t=e[0];if(!t){console.log(L("Usage: /mcp remove <name>"));return}let n=fu();if(!n.servers[t]){console.log(L(`No server named "${t}".`));return}delete n.servers[t],Jm(n),console.log(X(`\u2713 Removed "${t}".`)),console.log(d(" Run /clear to drop it from the current session immediately."))}oe();import{readFileSync as YR}from"node:fs";import{join as zR}from"node:path";import{select as XR}from"@inquirer/prompts";import{computeSyncStatus as Oa,planPartitions as QR,relatedArticlePaths as JR,loadProfileMap as ey,draftPendingPaths as ty,placeholderFindings as ZR,resolveActiveProfile as Ma,listUnpullable as eS,unreviewedPaths as tS,styleErrorPaths as ny,publishGateVerdict as nS,publishGateLines as oS,pushArticles as rS,pushArticle as sS,PUSH_POOL_SIZE as iS,SKIP_STYLE_FLAG as aS,listArticleFiles as oy,docsRootOf as lS,ensureFeedbackChannel as cS,FEEDBACK_CATEGORY_NAME as Jg,resolveCrossLinks as uS,applyStructureOrder as ry,orderSyncLine as sy,applyRelatedArticles as iy,relatedSyncLine as ay}from"document360-engine";import{readFileSync as y0}from"node:fs";import{resolve as w0}from"node:path";import{prettyFolderName as Zm}from"document360-engine";var Gn=Zm;function ga(e){return e.replace(/\\/g,"/").split("/").slice(0,-1).join("/")}function Is(e){let t=e.replace(/\\/g,"/").split("/").pop()??e;return Zm(t.replace(/\.md$/i,""))}function ya(e,t){try{return/^#\s+(.+)$/m.exec(y0(w0(e,t),"utf8"))?.[1]?.trim()??null}catch{return null}}import{resolveActiveProfile as eg,loadTokens as tg,isExpired as yu,listStoredSessions as b0,tokensProjectId as gu}from"document360-engine";function wa(e,t){try{let n=eg(e,t),o=tg(n.name,n.project.projectId);return!o||yu(o)?!1:Je(e,t).ok}catch{return!1}}function k0(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function mu(e,t){return t?`"${t}"`:e?k0(e):"this project"}function $0(e,t){return t?b0(e).filter(n=>{let o=gu(n);return!!o&&o!==t&&!(yu(n)&&!n.refreshToken)}):[]}function Je(e,t){try{let n=eg(e,t),o=n.project.projectId,r=mu(o,n.project.projectName),s=tg(n.name,o);if(!s){let a=$0(n.name,o);return a.length>0?{ok:!1,reason:`You're signed in to Document360 project ${a.map(l=>mu(gu(l)??void 0,l.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(yu(s)&&!s.refreshToken)return{ok:!1,reason:`Your Document360 session for ${r} expired. Run /login.`};let i=gu(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 ${mu(i,s.projectName)}). Run /login and pick ${r}.`}:{ok:!0}}catch{return{ok:!0}}}import{existsSync as kg,readFileSync as Nu}from"node:fs";import{isAbsolute as xa,join as Ra,resolve as Sa}from"node:path";import O from"picocolors";import $a from"string-width";import{readProjectConfig as Vn,screenshotPlaceholderIds as $g,screenshotMarkerProblemsInDocs as q0,DEFAULT_CAPTURE_DIR as Ca,DEFAULT_OUTPUT_DIR as Du,DEFAULT_DOCS_DIR as ju,resolveOutputDir as vg,migrateShotLayout as V0,reviewIsCurrent as K0,anchorPresent as Y0,annotationCurrent as z0,captureLanded as X0,shotArtifacts as Q0,RAW_SUBDIR as J0,ANNOTATED_SUBDIR as Z0}from"document360-engine";import{createHash as wu}from"node:crypto";import{readFileSync as og,writeFileSync as v0}from"node:fs";import{join as x0}from"node:path";import{captureStatePath as rg}from"document360-engine";var ng={version:1,shots:{}};function R0(e){return e.replace(/^/,"").replace(/\r\n?/g,`
315
+ `));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(` ${ee(n)} ${d("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?d(` [headers: ${r.join(", ")}]`):"";console.log(` ${ee(n)} ${d(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function Sx(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(L("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(L(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=bu(),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 c=o[++a],l=c?.match(/^([^:=]+)[:=](.+)$/);if(!l){console.log(L(`-H expects key:value (no spaces). Got: ${c??"(nothing)"}`));return}i[l[1].trim()]=l[2].trim()}else{console.log(L(`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,sg(r),console.log(""),console.log(Q(`\u2713 Registered "${t}" (${n})`)),console.log(q(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(d(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function Cx(e){let t=e[0];if(!t){console.log(L("Usage: /mcp remove <name>"));return}let n=bu();if(!n.servers[t]){console.log(L(`No server named "${t}".`));return}delete n.servers[t],sg(n),console.log(Q(`\u2713 Removed "${t}".`)),console.log(d(" Run /clear to drop it from the current session immediately."))}oe();import{readFileSync as rS}from"node:fs";import{join as sS}from"node:path";import{select as iS}from"@inquirer/prompts";import{computeSyncStatus as Wa,planPartitions as aS,relatedArticlePaths as lS,loadProfileMap as ay,draftPendingPaths as ly,placeholderFindings as cS,resolveActiveProfile as Ha,listUnpullable as uS,unreviewedPaths as dS,styleErrorPaths as cy,publishGateVerdict as pS,publishGateLines as hS,pushArticles as fS,pushArticle as mS,PUSH_POOL_SIZE as gS,SKIP_STYLE_FLAG as yS,listArticleFiles as uy,docsRootOf as wS,ensureFeedbackChannel as bS,FEEDBACK_CATEGORY_NAME as sy,resolveCrossLinks as kS,applyStructureOrder as dy,orderSyncLine as py,applyRelatedArticles as hy,relatedSyncLine as fy}from"document360-engine";import{readFileSync as Px}from"node:fs";import{resolve as Tx}from"node:path";import{prettyFolderName as ig}from"document360-engine";var qn=ig;function $a(e){return e.replace(/\\/g,"/").split("/").slice(0,-1).join("/")}function Os(e){let t=e.replace(/\\/g,"/").split("/").pop()??e;return ig(t.replace(/\.md$/i,""))}function va(e,t){try{return/^#\s+(.+)$/m.exec(Px(Tx(e,t),"utf8"))?.[1]?.trim()??null}catch{return null}}import{resolveActiveProfile as ag,loadTokens as lg,isExpired as vu,listStoredSessions as Ax,tokensProjectId as $u}from"document360-engine";function xa(e,t){try{let n=ag(e,t),o=lg(n.name,n.project.projectId);return!o||vu(o)?!1:Je(e,t).ok}catch{return!1}}function Ex(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function ku(e,t){return t?`"${t}"`:e?Ex(e):"this project"}function Nx(e,t){return t?Ax(e).filter(n=>{let o=$u(n);return!!o&&o!==t&&!(vu(n)&&!n.refreshToken)}):[]}function Je(e,t){try{let n=ag(e,t),o=n.project.projectId,r=ku(o,n.project.projectName),s=lg(n.name,o);if(!s){let a=Nx(n.name,o);return a.length>0?{ok:!1,reason:`You're signed in to Document360 project ${a.map(l=>ku($u(l)??void 0,l.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(vu(s)&&!s.refreshToken)return{ok:!1,reason:`Your Document360 session for ${r} expired. Run /login.`};let i=$u(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 ${ku(i,s.projectName)}). Run /login and pick ${r}.`}:{ok:!0}}catch{return{ok:!0}}}import{existsSync as Pg,readFileSync as Ou}from"node:fs";import{isAbsolute as Ta,join as Aa,resolve as Ea}from"node:path";import O from"picocolors";import Ca from"string-width";import{readProjectConfig as Yn,screenshotPlaceholderIds as Tg,screenshotMarkerProblemsInDocs as tR,DEFAULT_CAPTURE_DIR as Na,DEFAULT_OUTPUT_DIR as _u,DEFAULT_DOCS_DIR as Mu,resolveOutputDir as Ag,migrateShotLayout as nR,reviewIsCurrent as oR,anchorPresent as rR,annotationCurrent as sR,captureLanded as iR,shotArtifacts as aR,RAW_SUBDIR as lR,ANNOTATED_SUBDIR as cR}from"document360-engine";import{createHash as xu}from"node:crypto";import{readFileSync as ug,writeFileSync as Dx}from"node:fs";import{join as jx}from"node:path";import{captureStatePath as dg}from"document360-engine";var cg={version:1,shots:{}};function Ix(e){return e.replace(/^/,"").replace(/\r\n?/g,`
316
316
  `).replace(/\n+$/,`
317
- `)}function sg(e){return wu("sha1").update(R0(e)).digest("hex").slice(0,12)}function S0(e){return wu("sha1").update(e).digest("hex").slice(0,12)}function ba(e){try{let t=JSON.parse(og(x0(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 wu("sha1").update(`${o}|${r?.connection?.startUrl??""}|${i}`).digest("hex").slice(0,12)}catch{return null}}function Cn(e){try{let t=JSON.parse(og(rg(e),"utf8").replace(/^/,""));return!t||typeof t!="object"||t.version!==1||!t.shots?{...ng,shots:{}}:{version:1,shots:t.shots}}catch{return{...ng,shots:{}}}}function C0(e,t){v0(rg(e),`${JSON.stringify(t,null,2)}
318
- `,"utf8")}function bu(e){return e&&/data-testid|\btest-?id\b|has(?:n't| not) landed/i.test(e)?"testid":"data"}function ka(e,t,n){if(t.length===0)return;let o=Cn(e),r=ba(e);for(let s of t){let i=s.specSource?sg(s.specSource):void 0;o.shots[s.id]={outcome:s.outcome,at:n,...s.reason?{reason:s.reason}:{},...s.outcome==="skipped"?{blockedBy:bu(s.reason)}:{},...i?{specHash:i}:{},...r?{envHash:r}:{}}}C0(e,o)}function ku(e,t,n,o){let r=e.shots[t];return!r||n===null||!r.specHash||r.specHash!==sg(n)&&r.specHash!==S0(n)||o&&r.envHash&&r.envHash!==o?null:r}function ig(e){let t=Cn(e).shots;return Object.keys(t).filter(n=>t[n].outcome==="failed").sort()}function $u(e,t,n){let o=ku(Cn(e),t,n,ba(e));return!o||o.outcome==="captured"||!o.reason?null:{outcome:o.outcome,reason:o.reason}}Cr();import{existsSync as N0,readFileSync as ug,readdirSync as dg,writeFileSync as D0}from"node:fs";import{isAbsolute as j0,join as pg,resolve as I0}from"node:path";import{readProjectConfig as L0,DEFAULT_CAPTURE_DIR as O0}from"document360-engine";var cg="0.2.25";function Pr(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 _0=/^([ \t]*)await\s+([^\n;]+?)\.screenshot\(\{\s*path:\s*PLACEHOLDER\.saveTo\s*(?:,\s*fullPage:\s*(?:true|false)\s*)?,?\s*\}\)\s*;?[ \t]*$/m,M0=/^[ \t]*await\s+dumpAnnotations\(\s*page\s*,\s*PLACEHOLDER\s*\)\s*;?[ \t]*\r?\n?/m,hg="(?:'([^']+)'|\"([^\"]+)\"|`([^`]+)`)",F0=new RegExp(`^page\\s*\\.\\s*locator\\(\\s*${hg}\\s*\\)$`),fg=e=>e[1]??e[2]??e[3]??null,U0=/^[A-Za-z_$][\w$]*$/;function W0(e,t){let o=new RegExp(`\\bconst\\s+${t}\\s*=\\s*page\\s*\\.\\s*locator\\(\\s*${hg}\\s*\\)\\s*;`).exec(e);return o?fg(o):null}function B0(e,t){let n=t.trim();if(n==="page")return null;let o=F0.exec(n);if(o){let r=fg(o);return r?{selector:r}:{unresolved:!0}}if(U0.test(n)){let r=W0(e,n);return r?{selector:r}:{unresolved:!0}}return{unresolved:!0}}function mg(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=_0.exec(e);if(!n)return null;let[o,r="",s=""]=n,i=B0(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 c=i.selector.includes("'")?'"':"'",l=e.replace(a[0],`${a[0]}
319
- ${a[1]??" "}clipTo: ${c}${i.selector}${c},`);return l=l.replace(o,`${r}await captureShot(page, PLACEHOLDER);`),l=l.replace(M0,""),l=l.replace(/\bdumpAnnotations\b(?=[^\n]*from 'document360-capture\/helpers')/,"captureShot"),/from 'document360-capture\/helpers'/.test(l)&&!/\bcaptureShot\b[^\n]*from 'document360-capture\/helpers'/.test(l)&&(l=l.replace(/import \{([^}]*)\} from 'document360-capture\/helpers'/,(f,g)=>`import {${g.replace(/\s*$/,"")}, captureShot } from 'document360-capture/helpers'`)),{next:l,selector:i.selector}}function H0(e){try{return dg(e).filter(t=>t.endsWith(".spec.ts")).some(t=>{try{let n=mg(ug(pg(e,t),"utf8"));return n!==null&&!("unresolved"in n)}catch{return!1}})}catch{return!1}}function G0(e){let t=L0(e)?.captureDir??O0;return j0(t)?t:I0(e,t)}function gg(e,t){let n={migrated:[],skipped:[]},o=G0(e);if(!N0(o))return n;let r=t?.captureVersion===void 0?bt():t.captureVersion;if(!Pr(r,cg))return H0(o)?{...n,heldBackForCapture:{installed:r,required:cg}}:n;let s;try{s=dg(o).filter(i=>i.endsWith(".spec.ts"))}catch{return n}for(let i of s.sort()){let a=i.slice(0,-8),c=pg(o,i);try{let l=ug(c,"utf8"),f=mg(l);if(f===null)continue;if("unresolved"in f){n.skipped.push({id:a,receiver:f.unresolved});continue}D0(c,f.next,"utf8"),n.migrated.push(a)}catch{}}return n}function yg(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.
317
+ `)}function pg(e){return xu("sha1").update(Ix(e)).digest("hex").slice(0,12)}function Lx(e){return xu("sha1").update(e).digest("hex").slice(0,12)}function Ra(e){try{let t=JSON.parse(ug(jx(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 xu("sha1").update(`${o}|${r?.connection?.startUrl??""}|${i}`).digest("hex").slice(0,12)}catch{return null}}function Tn(e){try{let t=JSON.parse(ug(dg(e),"utf8").replace(/^/,""));return!t||typeof t!="object"||t.version!==1||!t.shots?{...cg,shots:{}}:{version:1,shots:t.shots}}catch{return{...cg,shots:{}}}}function Ox(e,t){Dx(dg(e),`${JSON.stringify(t,null,2)}
318
+ `,"utf8")}function Ru(e){return e&&/data-testid|\btest-?id\b|has(?:n't| not) landed/i.test(e)?"testid":"data"}function Sa(e,t,n){if(t.length===0)return;let o=Tn(e),r=Ra(e);for(let s of t){let i=s.specSource?pg(s.specSource):void 0;o.shots[s.id]={outcome:s.outcome,at:n,...s.reason?{reason:s.reason}:{},...s.outcome==="skipped"?{blockedBy:Ru(s.reason)}:{},...i?{specHash:i}:{},...r?{envHash:r}:{}}}Ox(e,o)}function Su(e,t,n,o){let r=e.shots[t];return!r||n===null||!r.specHash||r.specHash!==pg(n)&&r.specHash!==Lx(n)||o&&r.envHash&&r.envHash!==o?null:r}function hg(e){let t=Tn(e).shots;return Object.keys(t).filter(n=>t[n].outcome==="failed").sort()}function Cu(e,t,n){let o=Su(Tn(e),t,n,Ra(e));return!o||o.outcome==="captured"||!o.reason?null:{outcome:o.outcome,reason:o.reason}}Sr();import{existsSync as Wx,readFileSync as yg,readdirSync as wg,writeFileSync as Bx}from"node:fs";import{isAbsolute as Hx,join as bg,resolve as Gx}from"node:path";import{readProjectConfig as qx,DEFAULT_CAPTURE_DIR as Vx}from"document360-engine";var gg="0.2.25";function Cr(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 Yx=/^([ \t]*)await\s+([^\n;]+?)\.screenshot\(\{\s*path:\s*PLACEHOLDER\.saveTo\s*(?:,\s*fullPage:\s*(?:true|false)\s*)?,?\s*\}\)\s*;?[ \t]*$/m,Kx=/^[ \t]*await\s+dumpAnnotations\(\s*page\s*,\s*PLACEHOLDER\s*\)\s*;?[ \t]*\r?\n?/m,kg="(?:'([^']+)'|\"([^\"]+)\"|`([^`]+)`)",zx=new RegExp(`^page\\s*\\.\\s*locator\\(\\s*${kg}\\s*\\)$`),$g=e=>e[1]??e[2]??e[3]??null,Xx=/^[A-Za-z_$][\w$]*$/;function Qx(e,t){let o=new RegExp(`\\bconst\\s+${t}\\s*=\\s*page\\s*\\.\\s*locator\\(\\s*${kg}\\s*\\)\\s*;`).exec(e);return o?$g(o):null}function Jx(e,t){let n=t.trim();if(n==="page")return null;let o=zx.exec(n);if(o){let r=$g(o);return r?{selector:r}:{unresolved:!0}}if(Xx.test(n)){let r=Qx(e,n);return r?{selector:r}:{unresolved:!0}}return{unresolved:!0}}function vg(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=Yx.exec(e);if(!n)return null;let[o,r="",s=""]=n,i=Jx(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 c=i.selector.includes("'")?'"':"'",l=e.replace(a[0],`${a[0]}
319
+ ${a[1]??" "}clipTo: ${c}${i.selector}${c},`);return l=l.replace(o,`${r}await captureShot(page, PLACEHOLDER);`),l=l.replace(Kx,""),l=l.replace(/\bdumpAnnotations\b(?=[^\n]*from 'document360-capture\/helpers')/,"captureShot"),/from 'document360-capture\/helpers'/.test(l)&&!/\bcaptureShot\b[^\n]*from 'document360-capture\/helpers'/.test(l)&&(l=l.replace(/import \{([^}]*)\} from 'document360-capture\/helpers'/,(f,g)=>`import {${g.replace(/\s*$/,"")}, captureShot } from 'document360-capture/helpers'`)),{next:l,selector:i.selector}}function Zx(e){try{return wg(e).filter(t=>t.endsWith(".spec.ts")).some(t=>{try{let n=vg(yg(bg(e,t),"utf8"));return n!==null&&!("unresolved"in n)}catch{return!1}})}catch{return!1}}function eR(e){let t=qx(e)?.captureDir??Vx;return Hx(t)?t:Gx(e,t)}function xg(e,t){let n={migrated:[],skipped:[]},o=eR(e);if(!Wx(o))return n;let r=t?.captureVersion===void 0?kt():t.captureVersion;if(!Cr(r,gg))return Zx(o)?{...n,heldBackForCapture:{installed:r,required:gg}}:n;let s;try{s=wg(o).filter(i=>i.endsWith(".spec.ts"))}catch{return n}for(let i of s.sort()){let a=i.slice(0,-8),c=bg(o,i);try{let l=yg(c,"utf8"),f=vg(l);if(f===null)continue;if("unresolved"in f){n.skipped.push({id:a,receiver:f.unresolved});continue}Bx(c,f.next,"utf8"),n.migrated.push(a)}catch{}}return n}function Rg(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.
320
320
  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(`
321
- `)}function Se(e,t,n){return`${e}${n?` ${n}`:""}${t?` ${t}`:""}`}function Dt(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}Cr();var xg=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function wg(e){let t=e.includes("--detail")||e.includes("-d"),n=e.find(o=>o!=="--detail"&&o!=="-d");return{mode:"list",scope:n?xg(n):void 0,...t?{detail:!0}:{}}}function Ls(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 wg(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 wg(o.slice(1));let r=o[0];return r?r==="--all"?{mode:"all",setup:n}:/[\\/]/.test(r)||r.endsWith(".md")?{mode:"scope",scope:xg(r),setup:n}:{mode:"single",id:r}:{mode:"list",picker:!0}}function Ue(e,t,n){let o=Vn(e),r=o?.captureDir??Ca,s=o?.outputDir??Du,i=(g,k)=>xa(g)?Ra(g,k):Sa(e,g,k),a=Cn(e),c=n?.captureVersion===void 0?bt():n.captureVersion,l=Pr(c,Pg),f=ba(e);return $g(e,{scope:t}).map(({id:g,file:k})=>{let T=i(r,`${g}.spec.ts`),A=null;if(kg(T))try{A=Nu(T,"utf8")}catch{}let S=vg(e,s),C=Q0(S,g),x=z0(C),E=X0(C),I=A===null?null:ku(a,g,A,f),W=a.shots[g]?.review,V=x&&K0(W,C.annotatedMtimeMs)?W:void 0,B=A!==null&&nR(A),ae=x&&V?.verdict==="ok"?"verified":x&&V?.verdict==="rejected"?"rejected":x?"annotated":E?"captured":A===null?"placeholder":B||I?.outcome==="skipped"?"blocked":I?.outcome==="failed"?"broken":"spec",me=A===null?void 0:Sg(A),Re=B?rR(A):I?.reason,Ie=B?"testid":I?.outcome==="skipped"?bu(I.reason):void 0,ge=A===null?[]:oR(e,A);return{id:g,file:k,state:ae,...me?{mutates:me.mutates,...me.declared?{}:{undeclared:!0}}:{},...A!==null&&Ru(A).length>0?{unguardedWaits:Ru(A)}:{},...A!==null&&xu(A).length>0?{unverifiedForce:xu(A)}:{},...A!==null&&Su(A).length>0?{handRolled:Su(A)}:{},...A!==null&&Pu(A).length>0?{stalePause:Pu(A)}:{},...A!==null&&l&&Cu(A).length>0?{bareGoto:Cu(A)}:{},...ge.length>0?{staleAnchor:ge}:{},...ae==="blocked"||ae==="broken"?{...Re?{reason:Re}:{},...Ie?{blockedBy:Ie}:{}}:{},...ae==="rejected"?{...V?.reason?{reason:V.reason}:{},...V?.repaired?{repaired:!0}:{}}:{}}})}function eR(e){let t=Vn(e)?.outputDir??Du;return V0(vg(e,t))}function Io(e){let t=eR(e),n=Vn(e)?.outputDir??Du,o=[];t>0&&o.push(`\u2195 Tidied ${t} screenshot file${t===1?"":"s"} into ${n}/{${J0},${Z0}} \u2014 annotated/ is what publishes, raw/ is the pre-annotation intermediate.`);let r=yg(gg(e));return r&&o.push(r),o.length>0?o.join(`
322
- `):null}function Lo(e,t){let n=Vn(e)?.captureDir??Ca,o=xa(n)?Ra(n,`${t}.spec.ts`):Sa(e,n,`${t}.spec.ts`);try{return Nu(o,"utf8")}catch{return null}}function Rg(e,t){let n=Vn(e)?.captureDir??Ca;return kg(xa(n)?Ra(n,`${t}.spec.ts`):Sa(e,n,`${t}.spec.ts`))}function tR(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 Sg(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=tR(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 nR(e){return/(^|\n)\s*test\.skip\s*\(\s*['"`]/.test(e)}function Cg(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 oR(e,t){let n=[];for(let o of Cg(t))Y0(e,o.file,o.anchor)===!1&&n.push(o.testid??o.file??"unnamed request");return[...new Set(n)]}function rR(e){let{testid:t,file:n}=Cg(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 Os(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 xu(e,t=10){let n=Os(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(`
323
- `))||o.push(r+1));return o}function Ru(e){let t=[],n=Os(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 Su(e){let t=[];for(let[n,o]of Os(e).entries())(/\.screenshot\s*\(/.test(o)||/\bdumpAnnotations\s*\(/.test(o))&&t.push(n+1);return t}var Pg="0.2.28";function Cu(e){let t=[];for(let[n,o]of Os(e).entries())/\.goto\s*\(/.test(o)&&t.push(n+1);return t}function Pu(e,t=6){let n=Os(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(`
321
+ `)}function Se(e,t,n){return`${e}${n?` ${n}`:""}${t?` ${t}`:""}`}function Lt(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}Sr();var Eg=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Sg(e){let t=e.includes("--detail")||e.includes("-d"),n=e.find(o=>o!=="--detail"&&o!=="-d");return{mode:"list",scope:n?Eg(n):void 0,...t?{detail:!0}:{}}}function _s(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 Sg(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 Sg(o.slice(1));let r=o[0];return r?r==="--all"?{mode:"all",setup:n}:/[\\/]/.test(r)||r.endsWith(".md")?{mode:"scope",scope:Eg(r),setup:n}:{mode:"single",id:r}:{mode:"list",picker:!0}}function Ue(e,t,n){let o=Yn(e),r=o?.captureDir??Na,s=o?.outputDir??_u,i=(g,$)=>Ta(g)?Aa(g,$):Ea(e,g,$),a=Tn(e),c=n?.captureVersion===void 0?kt():n.captureVersion,l=Cr(c,Ig),f=Ra(e);return Tg(e,{scope:t}).map(({id:g,file:$})=>{let T=i(r,`${g}.spec.ts`),A=null;if(Pg(T))try{A=Ou(T,"utf8")}catch{}let S=Ag(e,s),C=aR(S,g),x=sR(C),E=iR(C),j=A===null?null:Su(a,g,A,f),W=a.shots[g]?.review,Y=x&&oR(W,C.annotatedMtimeMs)?W:void 0,B=A!==null&&pR(A),ue=x&&Y?.verdict==="ok"?"verified":x&&Y?.verdict==="rejected"?"rejected":x?"annotated":E?"captured":A===null?"placeholder":B||j?.outcome==="skipped"?"blocked":j?.outcome==="failed"?"broken":"spec",fe=A===null?void 0:Dg(A),Re=B?fR(A):j?.reason,Ie=B?"testid":j?.outcome==="skipped"?Ru(j.reason):void 0,ge=A===null?[]:hR(e,A);return{id:g,file:$,state:ue,...fe?{mutates:fe.mutates,...fe.declared?{}:{undeclared:!0}}:{},...A!==null&&Au(A).length>0?{unguardedWaits:Au(A)}:{},...A!==null&&Tu(A).length>0?{unverifiedForce:Tu(A)}:{},...A!==null&&Eu(A).length>0?{handRolled:Eu(A)}:{},...A!==null&&Du(A).length>0?{stalePause:Du(A)}:{},...A!==null&&l&&Nu(A).length>0?{bareGoto:Nu(A)}:{},...ge.length>0?{staleAnchor:ge}:{},...ue==="blocked"||ue==="broken"?{...Re?{reason:Re}:{},...Ie?{blockedBy:Ie}:{}}:{},...ue==="rejected"?{...Y?.reason?{reason:Y.reason}:{},...Y?.repaired?{repaired:!0}:{}}:{}}})}function uR(e){let t=Yn(e)?.outputDir??_u;return nR(Ag(e,t))}function Lo(e){let t=uR(e),n=Yn(e)?.outputDir??_u,o=[];t>0&&o.push(`\u2195 Tidied ${t} screenshot file${t===1?"":"s"} into ${n}/{${lR},${cR}} \u2014 annotated/ is what publishes, raw/ is the pre-annotation intermediate.`);let r=Rg(xg(e));return r&&o.push(r),o.length>0?o.join(`
322
+ `):null}function Oo(e,t){let n=Yn(e)?.captureDir??Na,o=Ta(n)?Aa(n,`${t}.spec.ts`):Ea(e,n,`${t}.spec.ts`);try{return Ou(o,"utf8")}catch{return null}}function Ng(e,t){let n=Yn(e)?.captureDir??Na;return Pg(Ta(n)?Aa(n,`${t}.spec.ts`):Ea(e,n,`${t}.spec.ts`))}function dR(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 Dg(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=dR(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 pR(e){return/(^|\n)\s*test\.skip\s*\(\s*['"`]/.test(e)}function jg(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 hR(e,t){let n=[];for(let o of jg(t))rR(e,o.file,o.anchor)===!1&&n.push(o.testid??o.file??"unnamed request");return[...new Set(n)]}function fR(e){let{testid:t,file:n}=jg(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 Ms(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 Tu(e,t=10){let n=Ms(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(`
323
+ `))||o.push(r+1));return o}function Au(e){let t=[],n=Ms(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 Eu(e){let t=[];for(let[n,o]of Ms(e).entries())(/\.screenshot\s*\(/.test(o)||/\bdumpAnnotations\s*\(/.test(o))&&t.push(n+1);return t}var Ig="0.2.28";function Nu(e){let t=[];for(let[n,o]of Ms(e).entries())/\.goto\s*\(/.test(o)&&t.push(n+1);return t}function Du(e,t=6){let n=Ms(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(`
324
324
  `);if(!/test\.skip\s*\(/.test(i)||!/\.count\s*\(\s*\)/.test(i))continue;let a=n.slice(Math.max(0,r-t),r+1).join(`
325
- `);/\.waitFor\s*\(|Promise\.race\s*\(|waitForFunction\s*\(|waitForSelector\s*\(/.test(a)||o.push(r+1)}return o}function Iu(e,t){let n=f=>`line${f.length===1?"":"s"} ${f.join(", ")}`,o=[],r=t?.captureVersion===void 0?bt():t.captureVersion,s=Pr(r,Pg)?Cu(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=Ru(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=Su(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 c=Pu(e);c.length>0&&o.push(`- ${n(c)}: 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 l=xu(e);return l.length>0&&o.push(`- ${n(l)}: 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 Tg(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 Ag(e){return(e??"").trim().replace(/[.\s]+$/,"")}function Eg(e,t){let n=Vn(e)?.captureDir??Ca,o=xa(n)?Ra(n,`${t}.spec.ts`):Sa(e,n,`${t}.spec.ts`);try{return Sg(Nu(o,"utf8"))}catch{return{mutates:!1,declared:!1}}}var sR=["annotated","verified","rejected"],iR=e=>sR.includes(e);function aR(e){return[...new Set(e.filter(t=>iR(t.state)).map(t=>t.file))].sort()}function Pa(e,t){let n=aR(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 Ta(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[`${z("\u26A0",O.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=>` ${O.yellow(s.id.padEnd(o))}`),` Publishing without ${r?"it":"them"}. Finish ${r?"it":"them"} first: ${O.bold(Se("/screenshot annotate","",t))}`].join(`
326
- `)}function Aa(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[`${z("\u26A0",O.yellow)}${t.length} screenshot${t.length===1?"":"s"} failed verification:`,...t.map(o=>` ${O.magenta(o.id.padEnd(n))} ${O.gray(Ar(o.reason??"no reason recorded"))}`),` Publishing anyway. Fix + re-capture: ${O.bold("/screenshot capture --failed")}`].join(`
327
- `)}var lR={placeholder:"\u25CB",spec:"\u25D0",blocked:"\u2298",broken:"\u2717",captured:"\u25CF",annotated:"\u25C8",verified:"\u2714",rejected:"\u2691"},cR={placeholder:O.gray,spec:O.yellow,blocked:O.cyan,broken:O.red,captured:O.yellow,annotated:O.blue,verified:O.green,rejected:O.magenta},uR=` ${O.green("\u2714 verified")} ${O.blue("\u25C8 to verify")} ${O.yellow("\u25CF to annotate")} ${O.yellow("\u25D0 ready")} ${O.magenta("\u2691 rejected")} ${O.cyan("\u2298 blocked")} ${O.red("\u2717 broken")} ${O.gray("\u25CB to spec")}`;function z(e,t=n=>n){return`${t(e)} `}function Ar(e){return e.replace(/\s+/g," ").trim().replace(/^Prerequisites? not met[:—-]?\s*/i,"")}function Ea(e){let t=Ar(e),n=/^(.*?[a-z0-9)"'”’])\.(?:\s|$)/i.exec(t);return(n?n[1]:t).trim()}function _s(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=Ea(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 Ng(e){let t=_s(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,c)=>a+c.ids.length,0);r.push(` ${O.bold("Stage this data")} ${O.gray(`\u2014 unblocks ${s} shot${s===1?"":"s"} in ${n.length} action${n.length===1?"":"s"}`)}`);let i=8;for(let a of n.slice(0,i)){let c=sn(a.reason,86);r.push(` ${O.cyan(qn(`${a.ids.length}\xD7`,4))} ${c[0]??""}`);for(let f of c.slice(1))r.push(` ${f}`);let l=a.ids.slice(0,4).join(" \xB7 ");r.push(O.gray(` ${l}${a.ids.length>4?` \xB7 +${a.ids.length-4} more`:""}`))}n.length>i&&r.push(O.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(` ${z("\u2298",O.cyan)}${s} shot${s===1?"":"s"} need${s===1?"s":""} a data-testid from your developers \u2014 ${O.bold("/screenshot checklist")} builds the hand-off.`)}return r}function Lu(e){if(e.length===0)return[];let t=e.slice(0,6),n=e.length;return["",` ${z("\u26A0",O.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`+O.gray(`, so ${n===1?"that picture":"those pictures"} would never be taken`),...t.map(o=>O.gray(` ${o.file}:${o.line} \u2014 ${o.reason}`)),...n>t.length?[O.gray(` \u2026and ${n-t.length} more`)]:[],O.gray(" Usually a reviewer comment wrapped around it. A marker must start its own line and carry an id:.")]}function Dg(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=["",` ${z("\u26A0",O.yellow)}${r} selector request${r===1?"":"s"} quote${r===1?"s":""} source code that has since changed`+O.gray(" \u2014 your developers would go looking for something that isn't there any more"),O.gray(` Refresh the hand-off before sending it: ${O.bold("/screenshot checklist")}`)];return t&&s.push(O.gray(` ${o.slice(0,8).join(" \xB7 ")}${r>8?` \xB7 +${r-8} more`:""}`)),s}function jg(e,t,n){let o=e.filter(f=>(f.unguardedWaits?.length??0)>0),r=e.filter(f=>f.undeclared),s=e.filter(f=>(f.handRolled?.length??0)>0),i=e.filter(f=>(f.stalePause?.length??0)>0),a=e.filter(f=>(f.bareGoto?.length??0)>0);if(o.length===0&&r.length===0&&s.length===0&&i.length===0&&a.length===0)return[];let c=["",` ${z("\u26A0",O.yellow)}Some specs were written before later reliability fixes:`],l=(f,g)=>` ${f.slice(0,8).map(g).join(" \xB7 ")}${f.length>8?` \xB7 +${f.length-8} more`:""}`;if(o.length>0){let f=o.length;c.push(O.gray(` ${f} crash${f===1?"es":""} instead of telling you what to stage when the data ${f===1?"it needs":"they need"} is missing`)),t&&c.push(O.gray(l(o,g=>`${g.id}:${g.unguardedWaits.join(",")}`)))}if(a.length>0){let f=a.length;c.push(O.gray(` ${f} open${f===1?"s":""} pages the slow way, so ${f===1?"it stalls":"they stall"} for a minute and give up when several shots run at once`)),t&&c.push(O.gray(l(a,g=>`${g.id}:${g.bareGoto.join(",")}`)))}if(i.length>0){let f=i.length;c.push(O.gray(` ${f} decide${f===1?"s":""} "the data is missing" from a fixed pause, so data you HAVE staged can read as absent`)),t&&c.push(O.gray(l(i,g=>`${g.id}:${g.stalePause.join(",")}`)))}if(s.length>0){let f=s.length;c.push(O.gray(` ${f} take${f===1?"s":""} ${f===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&&c.push(O.gray(l(s,g=>`${g.id}:${g.handRolled.join(",")}`)))}if(r.length>0){let f=r.length,g=r.filter(k=>k.mutates).length;c.push(O.gray(` ${f} do${f===1?"es":""} not say whether ${f===1?"it changes":"they change"} data in your app`+(g>0?`, so ${g===1?"one is":`${g} are`} left out of bulk runs to be safe`:""))),t&&c.push(O.gray(l(r,k=>k.id)))}return n?.commandInLead||c.push(O.gray(` Re-write them all with the current rules: ${O.bold("/screenshot author --all")}`)),c}function Ig(e){let t=e.filter(n=>(n.unverifiedForce?.length??0)>0);return t.length===0?[]:["",` ${z("\u26A0",O.red)}${t.length} spec${t.length===1?"":"s"} force-click past Playwright's safety checks without asserting the result`+O.gray(" \u2014 if the click lands on nothing, the shot photographs the unchanged screen"),O.gray(` ${t.slice(0,6).map(n=>`${n.id}:${n.unverifiedForce.join(",")}`).join(" \xB7 ")}${t.length>6?` \xB7 +${t.length-6} more`:""}`),O.gray(` Re-author to check what the click did: ${O.bold("/screenshot author <id>")}`)]}var va=(e,t)=>e.length>=t?e:e+" ".repeat(t-e.length),qn=(e,t)=>e.length>=t?e:" ".repeat(t-e.length)+e;function Lg(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 dR=new Set(["and","or","of","the","to","a","an","in","on","for","with","vs"]),pR=new Set(["ai","api","cli","ui","ux","url","id","http","https","json","xml","sdk","csv","pdf","oauth","sso","mfa","io","faq"]);function hR(e){return e.replace(/[-_]+/g," ").trim().split(/\s+/).filter(Boolean).map((n,o)=>{let r=n.toLowerCase();return pR.has(r)?r.toUpperCase():o>0&&dR.has(r)?r:r.charAt(0).toUpperCase()+r.slice(1)}).join(" ")}function Tu(e){if(!e)return{num:"",name:"(docs root)"};let t=/^(\d+)[-_](.+)$/.exec(e);return{num:t?t[1]:"",name:hR(t?t[2]:e)}}function fR(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).pop()??e}function bg(e,t,n){let o=t>0?Math.round(e/t*n):0;return O.green("\u2588".repeat(o))+O.gray("\u2591".repeat(Math.max(0,n-o)))}function mR(e,t){let n=t>0?Math.round(e/t*100):0,o=qn(`${n}%`,4);return n===100?O.green(o):n>0?O.yellow(o):O.gray(o)}function Og(e,t){let n=new Map;for(let o of e){let r=Lg(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 Ou(e,t){let n=C=>e.filter(x=>x.state===C).length,o=n("captured"),r=n("placeholder"),s=n("spec"),i=n("annotated"),a=n("blocked"),c=n("broken"),l=n("rejected"),f=e.filter(C=>C.state==="spec"&&C.mutates).length,g=s>f,k=e.filter(C=>(C.unguardedWaits?.length??0)>0||(C.bareGoto?.length??0)>0).length,T=e.filter(C=>(C.stalePause?.length??0)>0||(C.handRolled?.length??0)>0).length,A=s>0||a>0||c>0,S=(C,x="")=>Se(C,x,t);return o>0?{key:"annotate",cmd:S("/screenshot annotate")}:r>0?{key:"toSpec",cmd:t?`/screenshot author ${t}`:"/screenshot author --all"}:k>0&&A?{key:"crashy",cmd:t?`/screenshot author ${t}`:"/screenshot author --all"}:T>0&&A?{key:"wrongOutput",cmd:t?`/screenshot author ${t}`:"/screenshot author --all"}:s>0&&(g||i===0)?{key:"ready",cmd:S("/screenshot capture")}:i>0&&s>0?{key:"verify",cmd:S("/screenshot verify")}:a>0?{key:"blocked",cmd:S("/screenshot capture","--blocked")}:c>0?{key:"broken",cmd:`/screenshot ${e.find(C=>C.state==="broken").id}`}:i>0?{key:"verify",cmd:S("/screenshot verify")}:l>0?{key:"rejected",cmd:S("/screenshot capture","--failed")}:{key:"done",cmd:t?`/push ${t}`:"/push"}}function gR(e,t,n=[]){let o=(Z,Ee)=>Z.filter(_e=>_e.state===Ee).length,r=e.length,s=o(e,"verified"),i=o(e,"annotated"),a=o(e,"captured"),c=o(e,"rejected"),l=o(e,"spec"),f=o(e,"blocked"),g=o(e,"broken"),k=o(e,"placeholder"),T=new Set(e.map(Z=>Z.file)).size,A=Og(e,t),S=[];S.push(` ${O.bold("Screenshots")} ${O.green(`${s}/${r} verified`)} ${O.gray("\xB7")} ${i>0?O.blue(`${i} to verify`):O.gray("0 to verify")}`+(a>0?` ${O.gray("\xB7")} ${O.yellow(`${a} to annotate`)}`:"")+(c>0?` ${O.gray("\xB7")} ${O.magenta(`${c} rejected`)}`:"")+` ${O.gray("\xB7")} ${l>0?O.yellow(`${l} ready`):O.gray("0 ready")}`+(f>0?` ${O.gray("\xB7")} ${O.cyan(`${f} blocked`)}`:"")+(g>0?` ${O.gray("\xB7")} ${O.red(`${g} broken`)}`:"")+` ${O.gray("\xB7")} ${k>0?O.red(`${k} to spec`):O.gray("0 to spec")} `+O.gray(`across ${T} article${T===1?"":"s"}`));let C=r>0?Math.round(s/r*100):0;S.push(` [${bg(s,r,32)}] ${O.bold(`${C}%`)}`),S.push("");let x=A.map(([Z])=>Tu(Z)),E=Math.min(32,Math.max(7,...x.map(Z=>Z.name.length))),I=Z=>Z.length>E?`${Z.slice(0,E-1)}\u2026`:va(Z,E),W=[...a>0?[{head:"To annotate",w:11,state:"captured",color:O.yellow}]:[],...i>0?[{head:"To verify",w:9,state:"annotated",color:O.blue}]:[],...c>0?[{head:"Rejected",w:8,state:"rejected",color:O.magenta}]:[],{head:"Ready",w:5,state:"spec",color:O.yellow},...f>0?[{head:"Blocked",w:7,state:"blocked",color:O.cyan}]:[],...g>0?[{head:"Broken",w:6,state:"broken",color:O.red}]:[],{head:"To spec",w:7,state:"placeholder",color:O.red}];S.push(O.gray(` ${va("#",2)} ${va("Chapter",E)} ${qn("Verified",8)} ${W.map(Z=>qn(Z.head,Z.w)).join(" ")} Progress`));for(let[Z,[,Ee]]of A.entries()){let _e=o(Ee,"verified"),Ge=Ee.length,{num:In,name:Ce}=x[Z],Ae=_e===Ge,Ze=I(Ce),nn=W.map(St=>{let co=o(Ee,St.state);return co>0?St.color(qn(String(co),St.w)):O.gray(qn("\u2014",St.w))}).join(" ");S.push(` ${O.cyan(va(In,2))} ${Ae?O.green(Ze):_e>0?Ze:O.gray(Ze)} ${Ae?O.green(qn(`${_e}/${Ge}`,8)):qn(`${_e}/${Ge}`,8)} ${nn} ${bg(_e,Ge,10)} ${mR(_e,Ge)}`)}S.push("");let V=g>0?` ${O.gray("\xB7")} ${g} spec${g===1?"":"s"} broken \u2014 ${O.bold(`/screenshot ${e.find(Z=>Z.state==="broken").id}`)} re-authors ${g===1?"it":"the first"}`:"",B=e.filter(Z=>Z.state==="spec"&&Z.mutates).length,ae=l>B,me=e.filter(Z=>(Z.unguardedWaits?.length??0)>0||(Z.bareGoto?.length??0)>0).length,Re=e.filter(Z=>(Z.stalePause?.length??0)>0||(Z.handRolled?.length??0)>0).length,Ie=l>0||f>0||g>0,ge=!1,we=Ou(e).key;if(we==="annotate")S.push(` ${z("\u25C8",O.blue)}${a} shot${a===1?"":"s"} taken but not drawn on \u2014 run ${O.bold("/screenshot annotate")}`+O.gray(` \u2014 no browser, seconds; the callouts are what make ${a===1?"it":"them"} publishable`)+V);else if(we==="toSpec")S.push(` ${z("\u2192",O.yellow)}${k} placeholder${k===1?"":"s"} still need a spec \u2014 run ${O.bold("/screenshot author --all")}${V}`);else if(we==="crashy")ge=!0,S.push(` ${z("\u2192",O.yellow)}${me} spec${me===1?"":"s"} would crash mid-run \u2014 re-write ${me===1?"it":"them"} first: ${O.bold("/screenshot author --all")}`+O.gray(` \xB7 then ${O.bold("/screenshot capture")} (no browser time wasted on ${me===1?"a shot":"shots"} that can't finish)`)+V);else if(we==="wrongOutput")ge=!0,S.push(` ${z("\u2192",O.yellow)}${Re} spec${Re===1?"":"s"} would shoot the wrong thing \u2014 re-write ${Re===1?"it":"them"} first: ${O.bold("/screenshot author --all")}`+O.gray(` \xB7 then ${O.bold("/screenshot capture")} (a false skip or a misplaced callout costs the same browser time as a good shot)`)+V);else if(we==="ready"){let Z=B>0?O.gray(` \u2014 ${l-B} in one go; ${B} write${B===1?"s":""} real data and run${B===1?"s":""} one at a time`):"";S.push(` ${z("\u2192",O.yellow)}${l} spec${l===1?"":"s"} ready to capture \u2014 run ${O.bold("/screenshot capture")}${Z}${V}`)}else if(we==="verify"&&l>0)S.push(` ${z("\u2192",O.blue)}${i} shot${i===1?"":"s"} awaiting verification \u2014 run ${O.bold("/screenshot verify")}`+O.gray(" \u2014 no browser needed")+O.gray(` \xB7 ${l} ready spec${l===1?"":"s"} write real data, so ${l===1?"it runs":"each runs"} only when named: /screenshot capture <id>`)+V);else if(we==="blocked")S.push(` ${z("\u2192",O.cyan)}${f} shot${f===1?"":"s"} blocked \u2014 stage the data below, then ${O.bold("/screenshot capture --blocked")}${V}`);else if(we==="broken")S.push(` ${z("\u2192",O.red)}${g} spec${g===1?"":"s"} broken \u2014 ${O.bold(`/screenshot ${e.find(Z=>Z.state==="broken").id}`)} re-authors ${g===1?"it":"the first"} (re-capturing fails the same way)`);else if(we==="verify")S.push(` ${z("\u2192",O.blue)}${i} shot${i===1?"":"s"} awaiting verification \u2014 run ${O.bold("/screenshot verify")}`+O.gray(" \u2014 it checks each picture against what its article needs (no browser, no re-capture)"));else if(we==="rejected"){let Z=e.filter(Ee=>Ee.state==="rejected"&&Ee.repaired).length;S.push(` ${z("\u2691",O.magenta)}${c} shot${c===1?"":"s"} failed review \u2014 `+(Z>0?`${Z} spec${Z===1?"":"s"} already repaired; re-capture with ${O.bold("/screenshot capture --failed")}`:`see the reasons below, then ${O.bold("/screenshot capture --failed")}`))}else S.push(` ${z("\u2713",O.green)}all ${r} verified \u2014 ${O.bold("/push")} embeds them in the articles`);if(s>0&&s<r){let Z=A.filter(([,Ee])=>Ee.every(_e=>_e.state!=="verified")).map(([Ee])=>{let{num:_e,name:Ge}=Tu(Ee);return _e?`${_e} ${Ge}`:Ge});Z.length>0&&S.push(O.gray(` Furthest behind: ${Z.slice(0,5).join(" \xB7 ")}${Z.length>5?" \u2026":""} (0% verified)`))}return S.push(...Ng(e),...Ig(e),...jg(e,!1,{commandInLead:ge}),...Dg(e,!1),...Lu(n)),S.push(""),S.push(O.gray(" Drill in: /screenshot list <chapter#> \xB7 /screenshot list --detail (all)")),S}function yR(e,t,n,o=[]){let r=new Set(e.map(l=>l.file)),s=e.filter(l=>l.state==="verified").length,i=e.filter(l=>l.state==="annotated").length,a=e.filter(l=>l.state==="captured").length,c=[` ${O.bold("Screenshots")}: ${e.length} placeholder${e.length===1?"":"s"} across ${r.size} article${r.size===1?"":"s"} \xB7 ${O.green(`${s} verified`)}${i>0?O.blue(` \xB7 ${i} to verify`):""}${a>0?O.yellow(` \xB7 ${a} to annotate`):""}${n?O.gray(` \xB7 scope ${n}`):""}`,""];for(let[l,f]of Og(e,t)){let g=f.filter(C=>C.state==="verified").length,{num:k,name:T}=Tu(l),A=k?`${k} \xB7 ${T}`:T;c.push(` ${O.bold(A)} ${O.gray(`(${g}/${f.length})`)}`);let S=new Map;for(let C of f){let x=fR(C.file),E=S.get(x)??[];S.has(x)||S.set(x,E),E.push(C)}for(let C of[...S.keys()].sort()){c.push(O.gray(` ${C}`));for(let x of S.get(C)){let E=cR[x.state];if(c.push(` ${z(lR[x.state],E)}${E(x.id)}`),(x.state==="blocked"||x.state==="broken"||x.state==="rejected")&&x.reason){for(let I of sn(Ar(x.reason),84))c.push(O.gray(` ${I}`));x.state==="rejected"&&c.push(O.gray(` ${x.repaired?"spec repaired \u2014 re-capture to confirm":"spec not yet repaired"}`))}}}}return c.push(...Ng(e),...Ig(e),...jg(e,!0),...Dg(e,!0),...Lu(o)),c.push("",uR),c}function Na(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.",...Lu(o)];let r=t?.docsDir??ju;return t?.detail||n?yR(e,r,n,o):gR(e,r,o)}function _u(e,t){if(!t||!/^\d+$/.test(t))return t;let n=Vn(e)?.docsDir??ju,o=String(Number(t));for(let{file:r}of $g(e)){let s=Lg(r,n),i=/^(\d+)/.exec(s);if(i&&String(Number(i[1]))===o)return s}return t}function _g(e,t){let r=e.map(a=>" ".repeat(a.depth)+a.label),s=Math.max(0,...e.map((a,c)=>a.note?$a(r[c]):0)),i=Math.min(s,Math.max(0,t-2-24));return e.map((a,c)=>{let l=r[c];if(!a.note)return{head:l,note:""};let f=Math.max(2,i+2-$a(l)),g=a.note.trim(),k=t-$a(l)-f;return{head:l+" ".repeat(f),note:k>1&&$a(g)>k?`${g.slice(0,k-1)}\u2026`:g}})}function wR(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}=wR(s.file),c=o.get(i)??new Map;o.set(i,c);let l=c.get(a)??[];c.set(a,l),l.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(l=>l.id),c=a.length>0;c&&e.push({kind:"category",action:n,label:`${s} (${a.length})`,ids:a,depth:1});for(let l of[...i.keys()].sort()){let f=i.get(l),g=f.filter(r).map(A=>A.id),k=g.length>0;k&&e.push({kind:"article",action:n,label:`${l} (${g.length})`,ids:g,depth:c?2:1});let T=(c?1:0)+(k?1:0)+1;for(let A of f){let S=n==="capture"&&A.mutates?" \u26A0 creates real data \u2014 runs only alone":void 0;e.push({kind:"shot",action:n,label:A.id,ids:[A.id],depth:T,...S?{note:S}:{}})}}}}function vu(e){return e?Ar(e):""}function Mu(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,c)=>a.id.localeCompare(c.id)))e.push({kind:"shot",action:"capture",label:i.id,ids:[i.id],depth:1,note:` \u2298 ${vu(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,c)=>a.id.localeCompare(c.id)))e.push({kind:"shot",action:"author",label:i.id,ids:[i.id],depth:1,note:` \u2717 re-authors \u2014 ${vu(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,c)=>a.id.localeCompare(c.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 ${vu(i.reason)}`})}}function Mg(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"),Mu(o,e.filter(i=>i.state==="blocked"),e.filter(i=>i.state==="broken"),e.filter(i=>i.state==="rejected")),o}var Au=["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(`
328
- `);function bR(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 Eu="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 Fg(e,t,n){let o=e.paths,r=o.filter(c=>t?.get(c)?.outcome==="failed"),s=o.filter(c=>t?.get(c)?.outcome==="skipped"),i=c=>`- ${c}: ${t.get(c).reason.replace(/\s+/g," ").trim()}`,a=o.filter(c=>(n?.get(c)?.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(c=>`- ${c}`).join(`
329
- `),"",...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(c=>Tg(n.get(c),`RULE VIOLATIONS already in ${c}'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.",Au,Eu].join(`
330
- `)}async function Da(e,t,n){let o=Ls(e),r=Io(t?.cwd??process.cwd());if(r&&console.log(O.gray(r)),o.mode==="list"){let c=t?.cwd??process.cwd(),l=_u(c,o.scope),f=Vn(c)?.docsDir??ju,g=Ue(c,l),k=q0(c,l?{scope:l}:{});for(let T of Na(g,{scope:l,detail:o.detail,docsDir:f,markerProblems:k}))console.log(T);return{kind:"continue"}}if(o.mode==="single"){let c=Lo(t?.cwd??process.cwd(),o.id),l=c===null?[]:Iu(c);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.",Au,Eu,...n?.prior?["",...bR(n.prior)]:[],...l.length>0?["",...Tg(l,"RULE VIOLATIONS already in the existing spec \u2014 fix every one:")]:[]].join(`
331
- `),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.`,Au,Eu].join(`
332
- `),a=o.mode==="scope"?`/screenshot ${o.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:i,display:a}}import{readDocsPlan as vR,readProjectConfig as xR,listOpenHints as RR,partitionOpenHints as SR,listOpenForDocs as CR,listOpenDirectives as PR,loadOpenCommentCount as TR,resolveActiveProfile as AR,briefMoved as ER,DEFAULT_DOCS_DIR as NR}from"document360-engine";import{statSync as kR}from"node:fs";import{resolve as $R}from"node:path";function Kn(e,t,n){return n.filter(o=>{try{return kR($R(e,t,o)).size===0}catch{return!0}})}var Oo=e=>e===1?"":"s";function DR(e){try{let t=(xR(e)?.docsDir??NR).replace(/\/+$/,""),n=vR(e,t);return n.length===0?0:Kn(e,t,n.map(o=>o.path)).length}catch{return 0}}function jR(e){try{return TR(e,AR(e).name)}catch{return 0}}function IR(e){let t=i=>{try{return i().length}catch{return 0}},n=t(()=>SR(e,RR(e)).actionable),o=t(()=>CR(e)),r=t(()=>PR(e)),s=!1;try{s=ER(e)}catch{}return{hints:n,messages:o,directives:r,brief:s,total:n+o+r+(s?1:0)}}function Ug(e,t){let n=t?.just,o=IR(e);if(o.total>0&&n!=="/catch-up"){let i=[];return o.hints>0&&i.push(`${o.hints} hint${Oo(o.hints)}`),o.messages>0&&i.push(`${o.messages} message${Oo(o.messages)}`),o.directives>0&&i.push(`${o.directives} request${Oo(o.directives)}`),o.brief&&i.push("an updated product brief"),{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=jR(e);if(r>0&&n!=="/comments")return{cmd:"/comments",short:`${r} reviewer comment${Oo(r)} ${r===1?"is":"are"} waiting on your articles`,text:`${r} reviewer comment${Oo(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=DR(e);return s>0&&n!=="/write"?{cmd:"/write",short:`${s} planned article${Oo(s)} ${s===1?"is":"are"} still unwritten`,text:`${s} planned article${Oo(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 LR}from"document360-engine";var OR=new Set(["--scope","--concurrency","--model"]),_R=new Set(["/screenshot","/style-guide","/reuse"]),MR=e=>e.trim().replace(/\s+/g," ").toLowerCase();function an(e){let t=MR(LR(e));if(!t.startsWith("/"))return null;let n=t.split(" ").filter(Boolean),o=n[0],r=1,s;_R.has(o)&&n[1]&&!n[1].startsWith("-")&&(s=n[1],r=2);let i=new Set,a;for(;r<n.length;r++){let c=n[r];if(c.startsWith("--")){let l=c.indexOf("=");if(l!==-1){let f=c.slice(0,l);i.add(f),f==="--scope"&&(a=c.slice(l+1)||void 0);continue}if(i.add(c),OR.has(c)){let f=n[r+1];f!==void 0&&!f.startsWith("-")&&(c==="--scope"&&(a=f),r++)}continue}if(c.startsWith("-")){i.add(c);continue}a??=c}return{cmd:o,...s?{sub:s}:{},flags:i,...a?{scope:a.replace(/\/+$/,"")}:{}}}function Er(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"/reuse":return e.sub==="pull"||e.sub==="add"||e.sub==="audit";case"/restructure":return e.scope!==void 0;case"/push":case"/publish":case"/convert":case"/catch-up":case"/discover":case"/document":case"/pull":case"/reorder":return!0;default:return!1}}var FR=new Set(["--all"]),UR=new Set(["--concurrency","--model","--verbose","--quiet"]),WR=new Set(["--scope"]);function Wg(e){return[...e.flags].filter(t=>!FR.has(t)&&!UR.has(t)&&!WR.has(t)).sort().join(" ")}function Bg(e,t){if(!t)return!1;let n=an(e),o=an(t);return!n||!o||n.cmd!==o.cmd||n.sub!==o.sub||!Er(n)||Wg(n)!==Wg(o)?!1:n.scope===void 0||n.scope===o.scope}function Xt(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 Ms,roadmapProgress as Yg,stampRoadmapDone as KR}from"document360-engine";oe();oe();import{ROADMAP_STAGES as Hg}from"document360-engine";var Gg=[...Hg,"other"],BR=[[/^\/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 Fu(e){let t=(e.stage??"").trim().toLowerCase();if(Hg.includes(t))return t;let n=(e.run??"").trim().toLowerCase();if(n.startsWith("/")){for(let[o,r]of BR)if(o.test(n))return r}return"other"}function ja(e){return Fu(e)==="capture"}var HR={decide:"Decide",plan:"Plan",capture:"Screenshots",write:"Write",edit:"Edit",lint:"Style rules",save:"Save to Document360",golive:"Go live",other:"Other steps"};function qg(e){return e.status==="done"&&!!e.replacedBy}var Wu=e=>(e.run??"").trim().replace(/\s+/g," ").toLowerCase();function GR(e){let t=[];for(let o of e){let r=Wu(o);r&&!t.includes(r)&&t.push(r)}let n=o=>{let r=Wu(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 qR(e){let t=new Map;for(let o of e){let r=Fu(o),s=t.get(r);s?s.push(o):t.set(r,[o])}let n=[];for(let o of Gg){let r=t.get(o);!r||r.length===0||n.push({key:o,label:HR[o],steps:GR(r),done:r.filter(s=>s.status==="done").length})}return n}var Uu=" ",Vg=e=>e.trim().toLowerCase();function VR(e,t){let n=Math.max(20,t.width-Uu.length),o=e.status==="done"?X("\u2713"):Te("\u25CB"),r=e.status==="done"?d:t.isNext?ee:f=>f,s=sn(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(f=>` \xB7 ${f}`).join(""),c=s.map((f,g)=>g===0?` ${o} ${r(f)}`:`${Uu}${r(f)}`);if(!a)return c;if((s[s.length-1]??"").length+a.length<=n)return c[c.length-1]+=Te(a),c;for(let f of i)c.push(`${Uu}${Te(`\xB7 ${f}`)}`);return c}function Kg(e,t={}){let n=Math.max(40,t.width??80),o=t.all?e:e.filter(a=>!qg(a)),r=e.length-o.length,s=e.filter(a=>a.status==="done").length,i=[ee(`Docs roadmap \u2014 ${s} of ${e.length} step${e.length===1?"":"s"} done`)];for(let a of qR(o)){i.push(""),i.push(` ${Qe(a.label)}${Te(` \xB7 ${a.done} of ${a.steps.length}`)}`);let c="";for(let l of a.steps){let f=Wu(l);i.push(...VR(l,{width:n,showRun:!!f&&f!==c,isNext:!!t.next&&Vg(l.title)===Vg(t.next.title),showReplaced:!!t.all&&qg(l)})),c=f}}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(d(`(+${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 Bu(e,t={}){let n=Ms(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=Yg(e),r=Kg(n,{width:t.width,all:t.all,next:o.next});return r.push(d("(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(d('(d360-writer keeps the wording of its own steps current \u2014 add a "keep:" line to one to leave your version alone.)')),r}function Nr(e,t){let n=Ms(e).filter(l=>l.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=l=>l.trim().toLowerCase(),s=n.find(l=>r(l.title)===r(o)),i=o?s?[s]:n.filter(l=>r(l.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:
325
+ `);/\.waitFor\s*\(|Promise\.race\s*\(|waitForFunction\s*\(|waitForSelector\s*\(/.test(a)||o.push(r+1)}return o}function Fu(e,t){let n=f=>`line${f.length===1?"":"s"} ${f.join(", ")}`,o=[],r=t?.captureVersion===void 0?kt():t.captureVersion,s=Cr(r,Ig)?Nu(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=Au(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=Eu(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 c=Du(e);c.length>0&&o.push(`- ${n(c)}: 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 l=Tu(e);return l.length>0&&o.push(`- ${n(l)}: 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 Lg(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 Og(e){return(e??"").trim().replace(/[.\s]+$/,"")}function _g(e,t){let n=Yn(e)?.captureDir??Na,o=Ta(n)?Aa(n,`${t}.spec.ts`):Ea(e,n,`${t}.spec.ts`);try{return Dg(Ou(o,"utf8"))}catch{return{mutates:!1,declared:!1}}}var mR=["annotated","verified","rejected"],gR=e=>mR.includes(e);function yR(e){return[...new Set(e.filter(t=>gR(t.state)).map(t=>t.file))].sort()}function Da(e,t){let n=yR(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 ja(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[`${K("\u26A0",O.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=>` ${O.yellow(s.id.padEnd(o))}`),` Publishing without ${r?"it":"them"}. Finish ${r?"it":"them"} first: ${O.bold(Se("/screenshot annotate","",t))}`].join(`
326
+ `)}function Ia(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[`${K("\u26A0",O.yellow)}${t.length} screenshot${t.length===1?"":"s"} failed verification:`,...t.map(o=>` ${O.magenta(o.id.padEnd(n))} ${O.gray(Tr(o.reason??"no reason recorded"))}`),` Publishing anyway. Fix + re-capture: ${O.bold("/screenshot capture --failed")}`].join(`
327
+ `)}var wR={placeholder:"\u25CB",spec:"\u25D0",blocked:"\u2298",broken:"\u2717",captured:"\u25CF",annotated:"\u25C8",verified:"\u2714",rejected:"\u2691"},bR={placeholder:O.gray,spec:O.yellow,blocked:O.cyan,broken:O.red,captured:O.yellow,annotated:O.blue,verified:O.green,rejected:O.magenta},kR=` ${O.green("\u2714 verified")} ${O.blue("\u25C8 to verify")} ${O.yellow("\u25CF to annotate")} ${O.yellow("\u25D0 ready")} ${O.magenta("\u2691 rejected")} ${O.cyan("\u2298 blocked")} ${O.red("\u2717 broken")} ${O.gray("\u25CB to spec")}`;function K(e,t=n=>n){return`${t(e)} `}function Tr(e){return e.replace(/\s+/g," ").trim().replace(/^Prerequisites? not met[:—-]?\s*/i,"")}function La(e){let t=Tr(e),n=/^(.*?[a-z0-9)"'”’])\.(?:\s|$)/i.exec(t);return(n?n[1]:t).trim()}function Fs(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=La(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 Mg(e){let t=Fs(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,c)=>a+c.ids.length,0);r.push(` ${O.bold("Stage this data")} ${O.gray(`\u2014 unblocks ${s} shot${s===1?"":"s"} in ${n.length} action${n.length===1?"":"s"}`)}`);let i=8;for(let a of n.slice(0,i)){let c=an(a.reason,86);r.push(` ${O.cyan(Vn(`${a.ids.length}\xD7`,4))} ${c[0]??""}`);for(let f of c.slice(1))r.push(` ${f}`);let l=a.ids.slice(0,4).join(" \xB7 ");r.push(O.gray(` ${l}${a.ids.length>4?` \xB7 +${a.ids.length-4} more`:""}`))}n.length>i&&r.push(O.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(` ${K("\u2298",O.cyan)}${s} shot${s===1?"":"s"} need${s===1?"s":""} a data-testid from your developers \u2014 ${O.bold("/screenshot checklist")} builds the hand-off.`)}return r}function Uu(e){if(e.length===0)return[];let t=e.slice(0,6),n=e.length;return["",` ${K("\u26A0",O.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`+O.gray(`, so ${n===1?"that picture":"those pictures"} would never be taken`),...t.map(o=>O.gray(` ${o.file}:${o.line} \u2014 ${o.reason}`)),...n>t.length?[O.gray(` \u2026and ${n-t.length} more`)]:[],O.gray(" Usually a reviewer comment wrapped around it. A marker must start its own line and carry an id:.")]}function Fg(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=["",` ${K("\u26A0",O.yellow)}${r} selector request${r===1?"":"s"} quote${r===1?"s":""} source code that has since changed`+O.gray(" \u2014 your developers would go looking for something that isn't there any more"),O.gray(` Refresh the hand-off before sending it: ${O.bold("/screenshot checklist")}`)];return t&&s.push(O.gray(` ${o.slice(0,8).join(" \xB7 ")}${r>8?` \xB7 +${r-8} more`:""}`)),s}function Ug(e,t,n){let o=e.filter(f=>(f.unguardedWaits?.length??0)>0),r=e.filter(f=>f.undeclared),s=e.filter(f=>(f.handRolled?.length??0)>0),i=e.filter(f=>(f.stalePause?.length??0)>0),a=e.filter(f=>(f.bareGoto?.length??0)>0);if(o.length===0&&r.length===0&&s.length===0&&i.length===0&&a.length===0)return[];let c=["",` ${K("\u26A0",O.yellow)}Some specs were written before later reliability fixes:`],l=(f,g)=>` ${f.slice(0,8).map(g).join(" \xB7 ")}${f.length>8?` \xB7 +${f.length-8} more`:""}`;if(o.length>0){let f=o.length;c.push(O.gray(` ${f} crash${f===1?"es":""} instead of telling you what to stage when the data ${f===1?"it needs":"they need"} is missing`)),t&&c.push(O.gray(l(o,g=>`${g.id}:${g.unguardedWaits.join(",")}`)))}if(a.length>0){let f=a.length;c.push(O.gray(` ${f} open${f===1?"s":""} pages the slow way, so ${f===1?"it stalls":"they stall"} for a minute and give up when several shots run at once`)),t&&c.push(O.gray(l(a,g=>`${g.id}:${g.bareGoto.join(",")}`)))}if(i.length>0){let f=i.length;c.push(O.gray(` ${f} decide${f===1?"s":""} "the data is missing" from a fixed pause, so data you HAVE staged can read as absent`)),t&&c.push(O.gray(l(i,g=>`${g.id}:${g.stalePause.join(",")}`)))}if(s.length>0){let f=s.length;c.push(O.gray(` ${f} take${f===1?"s":""} ${f===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&&c.push(O.gray(l(s,g=>`${g.id}:${g.handRolled.join(",")}`)))}if(r.length>0){let f=r.length,g=r.filter($=>$.mutates).length;c.push(O.gray(` ${f} do${f===1?"es":""} not say whether ${f===1?"it changes":"they change"} data in your app`+(g>0?`, so ${g===1?"one is":`${g} are`} left out of bulk runs to be safe`:""))),t&&c.push(O.gray(l(r,$=>$.id)))}return n?.commandInLead||c.push(O.gray(` Re-write them all with the current rules: ${O.bold("/screenshot author --all")}`)),c}function Wg(e){let t=e.filter(n=>(n.unverifiedForce?.length??0)>0);return t.length===0?[]:["",` ${K("\u26A0",O.red)}${t.length} spec${t.length===1?"":"s"} force-click past Playwright's safety checks without asserting the result`+O.gray(" \u2014 if the click lands on nothing, the shot photographs the unchanged screen"),O.gray(` ${t.slice(0,6).map(n=>`${n.id}:${n.unverifiedForce.join(",")}`).join(" \xB7 ")}${t.length>6?` \xB7 +${t.length-6} more`:""}`),O.gray(` Re-author to check what the click did: ${O.bold("/screenshot author <id>")}`)]}var Pa=(e,t)=>e.length>=t?e:e+" ".repeat(t-e.length),Vn=(e,t)=>e.length>=t?e:" ".repeat(t-e.length)+e;function Bg(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 $R=new Set(["and","or","of","the","to","a","an","in","on","for","with","vs"]),vR=new Set(["ai","api","cli","ui","ux","url","id","http","https","json","xml","sdk","csv","pdf","oauth","sso","mfa","io","faq"]);function xR(e){return e.replace(/[-_]+/g," ").trim().split(/\s+/).filter(Boolean).map((n,o)=>{let r=n.toLowerCase();return vR.has(r)?r.toUpperCase():o>0&&$R.has(r)?r:r.charAt(0).toUpperCase()+r.slice(1)}).join(" ")}function ju(e){if(!e)return{num:"",name:"(docs root)"};let t=/^(\d+)[-_](.+)$/.exec(e);return{num:t?t[1]:"",name:xR(t?t[2]:e)}}function RR(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).pop()??e}function Cg(e,t,n){let o=t>0?Math.round(e/t*n):0;return O.green("\u2588".repeat(o))+O.gray("\u2591".repeat(Math.max(0,n-o)))}function SR(e,t){let n=t>0?Math.round(e/t*100):0,o=Vn(`${n}%`,4);return n===100?O.green(o):n>0?O.yellow(o):O.gray(o)}function Hg(e,t){let n=new Map;for(let o of e){let r=Bg(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 Wu(e,t){let n=C=>e.filter(x=>x.state===C).length,o=n("captured"),r=n("placeholder"),s=n("spec"),i=n("annotated"),a=n("blocked"),c=n("broken"),l=n("rejected"),f=e.filter(C=>C.state==="spec"&&C.mutates).length,g=s>f,$=e.filter(C=>(C.unguardedWaits?.length??0)>0||(C.bareGoto?.length??0)>0).length,T=e.filter(C=>(C.stalePause?.length??0)>0||(C.handRolled?.length??0)>0).length,A=s>0||a>0||c>0,S=(C,x="")=>Se(C,x,t);return o>0?{key:"annotate",cmd:S("/screenshot annotate")}:r>0?{key:"toSpec",cmd:t?`/screenshot author ${t}`:"/screenshot author --all"}:$>0&&A?{key:"crashy",cmd:t?`/screenshot author ${t}`:"/screenshot author --all"}:T>0&&A?{key:"wrongOutput",cmd:t?`/screenshot author ${t}`:"/screenshot author --all"}:s>0&&(g||i===0)?{key:"ready",cmd:S("/screenshot capture")}:i>0&&s>0?{key:"verify",cmd:S("/screenshot verify")}:a>0?{key:"blocked",cmd:S("/screenshot capture","--blocked")}:c>0?{key:"broken",cmd:`/screenshot ${e.find(C=>C.state==="broken").id}`}:i>0?{key:"verify",cmd:S("/screenshot verify")}:l>0?{key:"rejected",cmd:S("/screenshot capture","--failed")}:{key:"done",cmd:t?`/push ${t}`:"/push"}}function CR(e,t,n=[]){let o=(Z,Ae)=>Z.filter(_e=>_e.state===Ae).length,r=e.length,s=o(e,"verified"),i=o(e,"annotated"),a=o(e,"captured"),c=o(e,"rejected"),l=o(e,"spec"),f=o(e,"blocked"),g=o(e,"broken"),$=o(e,"placeholder"),T=new Set(e.map(Z=>Z.file)).size,A=Hg(e,t),S=[];S.push(` ${O.bold("Screenshots")} ${O.green(`${s}/${r} verified`)} ${O.gray("\xB7")} ${i>0?O.blue(`${i} to verify`):O.gray("0 to verify")}`+(a>0?` ${O.gray("\xB7")} ${O.yellow(`${a} to annotate`)}`:"")+(c>0?` ${O.gray("\xB7")} ${O.magenta(`${c} rejected`)}`:"")+` ${O.gray("\xB7")} ${l>0?O.yellow(`${l} ready`):O.gray("0 ready")}`+(f>0?` ${O.gray("\xB7")} ${O.cyan(`${f} blocked`)}`:"")+(g>0?` ${O.gray("\xB7")} ${O.red(`${g} broken`)}`:"")+` ${O.gray("\xB7")} ${$>0?O.red(`${$} to spec`):O.gray("0 to spec")} `+O.gray(`across ${T} article${T===1?"":"s"}`));let C=r>0?Math.round(s/r*100):0;S.push(` [${Cg(s,r,32)}] ${O.bold(`${C}%`)}`),S.push("");let x=A.map(([Z])=>ju(Z)),E=Math.min(32,Math.max(7,...x.map(Z=>Z.name.length))),j=Z=>Z.length>E?`${Z.slice(0,E-1)}\u2026`:Pa(Z,E),W=[...a>0?[{head:"To annotate",w:11,state:"captured",color:O.yellow}]:[],...i>0?[{head:"To verify",w:9,state:"annotated",color:O.blue}]:[],...c>0?[{head:"Rejected",w:8,state:"rejected",color:O.magenta}]:[],{head:"Ready",w:5,state:"spec",color:O.yellow},...f>0?[{head:"Blocked",w:7,state:"blocked",color:O.cyan}]:[],...g>0?[{head:"Broken",w:6,state:"broken",color:O.red}]:[],{head:"To spec",w:7,state:"placeholder",color:O.red}];S.push(O.gray(` ${Pa("#",2)} ${Pa("Chapter",E)} ${Vn("Verified",8)} ${W.map(Z=>Vn(Z.head,Z.w)).join(" ")} Progress`));for(let[Z,[,Ae]]of A.entries()){let _e=o(Ae,"verified"),ze=Ae.length,{num:On,name:Ce}=x[Z],Ee=_e===ze,Ze=j(Ce),on=W.map(Ct=>{let co=o(Ae,Ct.state);return co>0?Ct.color(Vn(String(co),Ct.w)):O.gray(Vn("\u2014",Ct.w))}).join(" ");S.push(` ${O.cyan(Pa(On,2))} ${Ee?O.green(Ze):_e>0?Ze:O.gray(Ze)} ${Ee?O.green(Vn(`${_e}/${ze}`,8)):Vn(`${_e}/${ze}`,8)} ${on} ${Cg(_e,ze,10)} ${SR(_e,ze)}`)}S.push("");let Y=g>0?` ${O.gray("\xB7")} ${g} spec${g===1?"":"s"} broken \u2014 ${O.bold(`/screenshot ${e.find(Z=>Z.state==="broken").id}`)} re-authors ${g===1?"it":"the first"}`:"",B=e.filter(Z=>Z.state==="spec"&&Z.mutates).length,ue=l>B,fe=e.filter(Z=>(Z.unguardedWaits?.length??0)>0||(Z.bareGoto?.length??0)>0).length,Re=e.filter(Z=>(Z.stalePause?.length??0)>0||(Z.handRolled?.length??0)>0).length,Ie=l>0||f>0||g>0,ge=!1,we=Wu(e).key;if(we==="annotate")S.push(` ${K("\u25C8",O.blue)}${a} shot${a===1?"":"s"} taken but not drawn on \u2014 run ${O.bold("/screenshot annotate")}`+O.gray(` \u2014 no browser, seconds; the callouts are what make ${a===1?"it":"them"} publishable`)+Y);else if(we==="toSpec")S.push(` ${K("\u2192",O.yellow)}${$} placeholder${$===1?"":"s"} still need a spec \u2014 run ${O.bold("/screenshot author --all")}${Y}`);else if(we==="crashy")ge=!0,S.push(` ${K("\u2192",O.yellow)}${fe} spec${fe===1?"":"s"} would crash mid-run \u2014 re-write ${fe===1?"it":"them"} first: ${O.bold("/screenshot author --all")}`+O.gray(` \xB7 then ${O.bold("/screenshot capture")} (no browser time wasted on ${fe===1?"a shot":"shots"} that can't finish)`)+Y);else if(we==="wrongOutput")ge=!0,S.push(` ${K("\u2192",O.yellow)}${Re} spec${Re===1?"":"s"} would shoot the wrong thing \u2014 re-write ${Re===1?"it":"them"} first: ${O.bold("/screenshot author --all")}`+O.gray(` \xB7 then ${O.bold("/screenshot capture")} (a false skip or a misplaced callout costs the same browser time as a good shot)`)+Y);else if(we==="ready"){let Z=B>0?O.gray(` \u2014 ${l-B} in one go; ${B} write${B===1?"s":""} real data and run${B===1?"s":""} one at a time`):"";S.push(` ${K("\u2192",O.yellow)}${l} spec${l===1?"":"s"} ready to capture \u2014 run ${O.bold("/screenshot capture")}${Z}${Y}`)}else if(we==="verify"&&l>0)S.push(` ${K("\u2192",O.blue)}${i} shot${i===1?"":"s"} awaiting verification \u2014 run ${O.bold("/screenshot verify")}`+O.gray(" \u2014 no browser needed")+O.gray(` \xB7 ${l} ready spec${l===1?"":"s"} write real data, so ${l===1?"it runs":"each runs"} only when named: /screenshot capture <id>`)+Y);else if(we==="blocked")S.push(` ${K("\u2192",O.cyan)}${f} shot${f===1?"":"s"} blocked \u2014 stage the data below, then ${O.bold("/screenshot capture --blocked")}${Y}`);else if(we==="broken")S.push(` ${K("\u2192",O.red)}${g} spec${g===1?"":"s"} broken \u2014 ${O.bold(`/screenshot ${e.find(Z=>Z.state==="broken").id}`)} re-authors ${g===1?"it":"the first"} (re-capturing fails the same way)`);else if(we==="verify")S.push(` ${K("\u2192",O.blue)}${i} shot${i===1?"":"s"} awaiting verification \u2014 run ${O.bold("/screenshot verify")}`+O.gray(" \u2014 it checks each picture against what its article needs (no browser, no re-capture)"));else if(we==="rejected"){let Z=e.filter(Ae=>Ae.state==="rejected"&&Ae.repaired).length;S.push(` ${K("\u2691",O.magenta)}${c} shot${c===1?"":"s"} failed review \u2014 `+(Z>0?`${Z} spec${Z===1?"":"s"} already repaired; re-capture with ${O.bold("/screenshot capture --failed")}`:`see the reasons below, then ${O.bold("/screenshot capture --failed")}`))}else S.push(` ${K("\u2713",O.green)}all ${r} verified \u2014 ${O.bold("/push")} embeds them in the articles`);if(s>0&&s<r){let Z=A.filter(([,Ae])=>Ae.every(_e=>_e.state!=="verified")).map(([Ae])=>{let{num:_e,name:ze}=ju(Ae);return _e?`${_e} ${ze}`:ze});Z.length>0&&S.push(O.gray(` Furthest behind: ${Z.slice(0,5).join(" \xB7 ")}${Z.length>5?" \u2026":""} (0% verified)`))}return S.push(...Mg(e),...Wg(e),...Ug(e,!1,{commandInLead:ge}),...Fg(e,!1),...Uu(n)),S.push(""),S.push(O.gray(" Drill in: /screenshot list <chapter#> \xB7 /screenshot list --detail (all)")),S}function PR(e,t,n,o=[]){let r=new Set(e.map(l=>l.file)),s=e.filter(l=>l.state==="verified").length,i=e.filter(l=>l.state==="annotated").length,a=e.filter(l=>l.state==="captured").length,c=[` ${O.bold("Screenshots")}: ${e.length} placeholder${e.length===1?"":"s"} across ${r.size} article${r.size===1?"":"s"} \xB7 ${O.green(`${s} verified`)}${i>0?O.blue(` \xB7 ${i} to verify`):""}${a>0?O.yellow(` \xB7 ${a} to annotate`):""}${n?O.gray(` \xB7 scope ${n}`):""}`,""];for(let[l,f]of Hg(e,t)){let g=f.filter(C=>C.state==="verified").length,{num:$,name:T}=ju(l),A=$?`${$} \xB7 ${T}`:T;c.push(` ${O.bold(A)} ${O.gray(`(${g}/${f.length})`)}`);let S=new Map;for(let C of f){let x=RR(C.file),E=S.get(x)??[];S.has(x)||S.set(x,E),E.push(C)}for(let C of[...S.keys()].sort()){c.push(O.gray(` ${C}`));for(let x of S.get(C)){let E=bR[x.state];if(c.push(` ${K(wR[x.state],E)}${E(x.id)}`),(x.state==="blocked"||x.state==="broken"||x.state==="rejected")&&x.reason){for(let j of an(Tr(x.reason),84))c.push(O.gray(` ${j}`));x.state==="rejected"&&c.push(O.gray(` ${x.repaired?"spec repaired \u2014 re-capture to confirm":"spec not yet repaired"}`))}}}}return c.push(...Mg(e),...Wg(e),...Ug(e,!0),...Fg(e,!0),...Uu(o)),c.push("",kR),c}function Oa(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.",...Uu(o)];let r=t?.docsDir??Mu;return t?.detail||n?PR(e,r,n,o):CR(e,r,o)}function Bu(e,t){if(!t||!/^\d+$/.test(t))return t;let n=Yn(e)?.docsDir??Mu,o=String(Number(t));for(let{file:r}of Tg(e)){let s=Bg(r,n),i=/^(\d+)/.exec(s);if(i&&String(Number(i[1]))===o)return s}return t}function Gg(e,t){let r=e.map(a=>" ".repeat(a.depth)+a.label),s=Math.max(0,...e.map((a,c)=>a.note?Ca(r[c]):0)),i=Math.min(s,Math.max(0,t-2-24));return e.map((a,c)=>{let l=r[c];if(!a.note)return{head:l,note:""};let f=Math.max(2,i+2-Ca(l)),g=a.note.trim(),$=t-Ca(l)-f;return{head:l+" ".repeat(f),note:$>1&&Ca(g)>$?`${g.slice(0,$-1)}\u2026`:g}})}function TR(e){let t=e.replace(/\\/g,"/").split("/").filter(Boolean),n=t.pop()??e;return{category:t.pop()??"(docs root)",article:n}}function Pr(e,t,n){let o=new Map;for(let s of t){let{category:i,article:a}=TR(s.file),c=o.get(i)??new Map;o.set(i,c);let l=c.get(a)??[];c.set(a,l),l.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(l=>l.id),c=a.length>0;c&&e.push({kind:"category",action:n,label:`${s} (${a.length})`,ids:a,depth:1});for(let l of[...i.keys()].sort()){let f=i.get(l),g=f.filter(r).map(A=>A.id),$=g.length>0;$&&e.push({kind:"article",action:n,label:`${l} (${g.length})`,ids:g,depth:c?2:1});let T=(c?1:0)+($?1:0)+1;for(let A of f){let S=n==="capture"&&A.mutates?" \u26A0 creates real data \u2014 runs only alone":void 0;e.push({kind:"shot",action:n,label:A.id,ids:[A.id],depth:T,...S?{note:S}:{}})}}}}function Pu(e){return e?Tr(e):""}function Hu(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,c)=>a.id.localeCompare(c.id)))e.push({kind:"shot",action:"capture",label:i.id,ids:[i.id],depth:1,note:` \u2298 ${Pu(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,c)=>a.id.localeCompare(c.id)))e.push({kind:"shot",action:"author",label:i.id,ids:[i.id],depth:1,note:` \u2717 re-authors \u2014 ${Pu(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,c)=>a.id.localeCompare(c.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 ${Pu(i.reason)}`})}}function qg(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}),Pr(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}),Pr(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}),Pr(o,s,"annotate"),Hu(o,e.filter(i=>i.state==="blocked"),e.filter(i=>i.state==="broken"),e.filter(i=>i.state==="rejected")),o}var Iu=["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(`
328
+ `);function AR(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 Lu="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 Vg(e,t,n){let o=e.paths,r=o.filter(c=>t?.get(c)?.outcome==="failed"),s=o.filter(c=>t?.get(c)?.outcome==="skipped"),i=c=>`- ${c}: ${t.get(c).reason.replace(/\s+/g," ").trim()}`,a=o.filter(c=>(n?.get(c)?.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(c=>`- ${c}`).join(`
329
+ `),"",...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(c=>Lg(n.get(c),`RULE VIOLATIONS already in ${c}'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.",Iu,Lu].join(`
330
+ `)}async function _a(e,t,n){let o=_s(e),r=Lo(t?.cwd??process.cwd());if(r&&console.log(O.gray(r)),o.mode==="list"){let c=t?.cwd??process.cwd(),l=Bu(c,o.scope),f=Yn(c)?.docsDir??Mu,g=Ue(c,l),$=tR(c,l?{scope:l}:{});for(let T of Oa(g,{scope:l,detail:o.detail,docsDir:f,markerProblems:$}))console.log(T);return{kind:"continue"}}if(o.mode==="single"){let c=Oo(t?.cwd??process.cwd(),o.id),l=c===null?[]:Fu(c);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.",Iu,Lu,...n?.prior?["",...AR(n.prior)]:[],...l.length>0?["",...Lg(l,"RULE VIOLATIONS already in the existing spec \u2014 fix every one:")]:[]].join(`
331
+ `),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.`,Iu,Lu].join(`
332
+ `),a=o.mode==="scope"?`/screenshot ${o.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:i,display:a}}import{readDocsPlan as DR,readProjectConfig as jR,listOpenHints as IR,partitionOpenHints as LR,listOpenForDocs as OR,listOpenDirectives as _R,loadOpenCommentCount as MR,resolveActiveProfile as FR,briefMoved as UR,DEFAULT_DOCS_DIR as WR}from"document360-engine";import{statSync as ER}from"node:fs";import{resolve as NR}from"node:path";function Kn(e,t,n){return n.filter(o=>{try{return ER(NR(e,t,o)).size===0}catch{return!0}})}var _o=e=>e===1?"":"s";function BR(e){try{let t=(jR(e)?.docsDir??WR).replace(/\/+$/,""),n=DR(e,t);return n.length===0?0:Kn(e,t,n.map(o=>o.path)).length}catch{return 0}}function HR(e){try{return MR(e,FR(e).name)}catch{return 0}}function GR(e){let t=i=>{try{return i().length}catch{return 0}},n=t(()=>LR(e,IR(e)).actionable),o=t(()=>OR(e)),r=t(()=>_R(e)),s=!1;try{s=UR(e)}catch{}return{hints:n,messages:o,directives:r,brief:s,total:n+o+r+(s?1:0)}}function Yg(e,t){let n=t?.just,o=GR(e);if(o.total>0&&n!=="/catch-up"){let i=[];return o.hints>0&&i.push(`${o.hints} hint${_o(o.hints)}`),o.messages>0&&i.push(`${o.messages} message${_o(o.messages)}`),o.directives>0&&i.push(`${o.directives} request${_o(o.directives)}`),o.brief&&i.push("an updated product brief"),{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=HR(e);if(r>0&&n!=="/comments")return{cmd:"/comments",short:`${r} reviewer comment${_o(r)} ${r===1?"is":"are"} waiting on your articles`,text:`${r} reviewer comment${_o(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=BR(e);return s>0&&n!=="/write"?{cmd:"/write",short:`${s} planned article${_o(s)} ${s===1?"is":"are"} still unwritten`,text:`${s} planned article${_o(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 qR}from"document360-engine";var VR=new Set(["--scope","--concurrency","--model"]),YR=new Set(["/screenshot","/style-guide","/reuse"]),KR=e=>e.trim().replace(/\s+/g," ").toLowerCase();function ln(e){let t=KR(qR(e));if(!t.startsWith("/"))return null;let n=t.split(" ").filter(Boolean),o=n[0],r=1,s;YR.has(o)&&n[1]&&!n[1].startsWith("-")&&(s=n[1],r=2);let i=new Set,a;for(;r<n.length;r++){let c=n[r];if(c.startsWith("--")){let l=c.indexOf("=");if(l!==-1){let f=c.slice(0,l);i.add(f),f==="--scope"&&(a=c.slice(l+1)||void 0);continue}if(i.add(c),VR.has(c)){let f=n[r+1];f!==void 0&&!f.startsWith("-")&&(c==="--scope"&&(a=f),r++)}continue}if(c.startsWith("-")){i.add(c);continue}a??=c}return{cmd:o,...s?{sub:s}:{},flags:i,...a?{scope:a.replace(/\/+$/,"")}:{}}}function Ar(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"/reuse":return e.sub==="pull"||e.sub==="add"||e.sub==="audit";case"/restructure":return e.scope!==void 0;case"/push":case"/publish":case"/convert":case"/catch-up":case"/discover":case"/document":case"/pull":case"/reorder":return!0;default:return!1}}var zR=new Set(["--all"]),XR=new Set(["--concurrency","--model","--verbose","--quiet"]),QR=new Set(["--scope"]);function Kg(e){return[...e.flags].filter(t=>!zR.has(t)&&!XR.has(t)&&!QR.has(t)).sort().join(" ")}function zg(e,t){if(!t)return!1;let n=ln(e),o=ln(t);return!n||!o||n.cmd!==o.cmd||n.sub!==o.sub||!Ar(n)||Kg(n)!==Kg(o)?!1:n.scope===void 0||n.scope===o.scope}function Qt(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 ty,stampRoadmapDone as oS}from"document360-engine";oe();oe();import{ROADMAP_STAGES as Xg}from"document360-engine";var Qg=[...Xg,"other"],JR=[[/^\/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 Gu(e){let t=(e.stage??"").trim().toLowerCase();if(Xg.includes(t))return t;let n=(e.run??"").trim().toLowerCase();if(n.startsWith("/")){for(let[o,r]of JR)if(o.test(n))return r}return"other"}function Ma(e){return Gu(e)==="capture"}var ZR={decide:"Decide",plan:"Plan",capture:"Screenshots",write:"Write",edit:"Edit",lint:"Style rules",save:"Save to Document360",golive:"Go live",other:"Other steps"};function Jg(e){return e.status==="done"&&!!e.replacedBy}var Vu=e=>(e.run??"").trim().replace(/\s+/g," ").toLowerCase();function eS(e){let t=[];for(let o of e){let r=Vu(o);r&&!t.includes(r)&&t.push(r)}let n=o=>{let r=Vu(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 tS(e){let t=new Map;for(let o of e){let r=Gu(o),s=t.get(r);s?s.push(o):t.set(r,[o])}let n=[];for(let o of Qg){let r=t.get(o);!r||r.length===0||n.push({key:o,label:ZR[o],steps:eS(r),done:r.filter(s=>s.status==="done").length})}return n}var qu=" ",Zg=e=>e.trim().toLowerCase();function nS(e,t){let n=Math.max(20,t.width-qu.length),o=e.status==="done"?Q("\u2713"):Te("\u25CB"),r=e.status==="done"?d:t.isNext?ee:f=>f,s=an(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(f=>` \xB7 ${f}`).join(""),c=s.map((f,g)=>g===0?` ${o} ${r(f)}`:`${qu}${r(f)}`);if(!a)return c;if((s[s.length-1]??"").length+a.length<=n)return c[c.length-1]+=Te(a),c;for(let f of i)c.push(`${qu}${Te(`\xB7 ${f}`)}`);return c}function ey(e,t={}){let n=Math.max(40,t.width??80),o=t.all?e:e.filter(a=>!Jg(a)),r=e.length-o.length,s=e.filter(a=>a.status==="done").length,i=[ee(`Docs roadmap \u2014 ${s} of ${e.length} step${e.length===1?"":"s"} done`)];for(let a of tS(o)){i.push(""),i.push(` ${Qe(a.label)}${Te(` \xB7 ${a.done} of ${a.steps.length}`)}`);let c="";for(let l of a.steps){let f=Vu(l);i.push(...nS(l,{width:n,showRun:!!f&&f!==c,isNext:!!t.next&&Zg(l.title)===Zg(t.next.title),showReplaced:!!t.all&&Jg(l)})),c=f}}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(d(`(+${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 Yu(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=ty(e),r=ey(n,{width:t.width,all:t.all,next:o.next});return r.push(d("(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(d('(d360-writer keeps the wording of its own steps current \u2014 add a "keep:" line to one to leave your version alone.)')),r}function Er(e,t){let n=Us(e).filter(l=>l.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=l=>l.trim().toLowerCase(),s=n.find(l=>r(l.title)===r(o)),i=o?s?[s]:n.filter(l=>r(l.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:
333
333
  ${i.map(l=>` \u25CB ${l.title}`).join(`
334
334
  `)}`};if(i.length===0)return{ok:!1,line:`No open step matches "${o}". Open steps:
335
335
  ${n.map(l=>` \u25CB ${l.title}`).join(`
336
- `)}`};let a=i[0].title;KR(e,a,{doneAt:new Date().toISOString()});let c=Yg(e)?.next;return{ok:!0,line:`\u2713 Marked done: ${a}${c?` \u2014 next up: ${c.title}${c.run?` (${c.run})`:""}`:" \u2014 that was the last step: campaign complete."}`}}function zg(e,t){let n=r=>r.trim().replace(/\s+/g," ").toLowerCase(),o=n(t);return o.startsWith("/")?Ms(e).find(r=>r.status==="open"&&!!r.run&&n(r.run)===o)??null:null}function Ia(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 Ms(e))s.status==="open"&&n.some(i=>Bg(i,s.run))&&(o.has(s.title)||(o.add(s.title),r.push(s.title)));return r}function Ke(e,t){if(!t)return[];try{let n=Ia(e,t).filter(o=>Nr(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 La(e,t){let n=Ia(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(`
337
- `)}function Xg(e,t){let n=t.trim().toLowerCase();if(!n)return null;let o=Ms(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:
336
+ `)}`};let a=i[0].title;oS(e,a,{doneAt:new Date().toISOString()});let c=ty(e)?.next;return{ok:!0,line:`\u2713 Marked done: ${a}${c?` \u2014 next up: ${c.title}${c.run?` (${c.run})`:""}`:" \u2014 that was the last step: campaign complete."}`}}function ny(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 Fa(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=>zg(i,s.run))&&(o.has(s.title)||(o.add(s.title),r.push(s.title)));return r}function Ye(e,t){if(!t)return[];try{let n=Fa(e,t).filter(o=>Er(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 Ua(e,t){let n=Fa(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(`
337
+ `)}function oy(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:
338
338
  ${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(`
339
- `):null}async function Qg(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let o=Nr(n,e.slice(1).join(" ").trim());return console.log(o.ok?X(o.line):K(o.line)),{kind:"continue"}}for(let o of Bu(n,{all:e.some(r=>r.toLowerCase()==="--all")}))console.log(o);return{kind:"continue"}}var Gu={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 pushing overwrites the portal edit"},dS="\u26A0 held on Document360 in another editor \u2014 /resolve settles it";function Fo(e){return e.filter(t=>t.path!==null&&t.status in Gu&&!t.link).map(t=>({path:t.path,label:Gu[t.status]}))}function _o(e,t=[]){let n=Fo(e),o=new Set(t),r=new Set([...e.filter(s=>s.status==="conflict"&&s.path).map(s=>s.path),...o]);return{clean:n.filter(s=>!r.has(s.path)),conflicts:n.filter(s=>r.has(s.path)).map(s=>o.has(s.path)&&s.label!==Gu.conflict?{...s,label:dS}:s)}}function Mo(e,t){try{return eS(e,Ma(e,t).name).map(n=>n.path)}catch{return[]}}function Fs(e,t=0){let n=e!==1;if(t>=e)return`\u26A0 ${e} article${n?"s":""} NOT pushed (nothing on the portal overwritten) \u2014 Document360 holds ${n?"their bodies":"its body"} in another editor, so ${n?"they cannot be":"it cannot be"} read back. Settle ${n?"them":"it"}: /resolve (or ask your Document360 admin to move ${n?"them":"it"} to the Markdown editor).`;let o=t>0?` (${t} of ${n?"them are":"these is"} held in another editor and cannot be read back)`:"";return`\u26A0 ${e} conflict${n?"s":""} NOT pushed (portal edit${n?"s":""} kept safe) \u2014 ${n?"these were":"it was"} edited both here and on the portal, so ${n?"they are":"it is"} left untouched.${o} Settle ${n?"them":"it"}: /resolve (or /push <path> to keep yours, /pull <path> to take the portal's).`}function qu(e,t){let n=t.scope?.replace(/\\/g,"/").replace(/\/+$/,"");return!n||!n.endsWith(".md")||!ty(e,t.profileName).map(r=>r.replace(/\\/g,"/")).some(r=>r===n||r.endsWith(`/${n}`)||n.endsWith(`/${r}`))?null:{cmd:Se("/publish","",n),reason:"it takes this draft live \u2014 until it does, your readers still see the previous version"}}function Dr(e,t){let n=ty(e,t),o=n.length;if(o===0)return null;let r=o===1?"":"s",s=0;try{s=ZR(e,n).length}catch{}if(s>0){let i=o-s,a=`${s===o?o===1?"It is":"All of them are":`${s} of them ${s===1?"is":"are"}`} waiting on a missing picture`;return`\u2139 ${o} article${r} ${o===1?"is":"are"} saved on Document360 as a draft and not live yet \u2014 readers still see the previous version. ${a}, so /publish holds ${s===1?"it":"them"} back${i>0?` and takes the other ${i} live once ${i===1?"it has":"they have"} been signed off.`:"."}`}return`\u2139 ${o} article${r} ${o===1?"is":"are"} saved on Document360 as a draft and not live yet \u2014 readers still see the previous version. /publish takes ${o===1?"it":"them"} live once ${o===1?"it has":"they have"} been signed off.`}function _a(e){return e.filter(t=>t.link).length}function Vu(e,t){try{let n=ey(e,Ma(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=uS(YR(zR(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 ly(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:`${Gn(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 Us(e,t){try{let n=Ma(e,t),o=n.project.projectId,r=n.project.workspaceId;if(!o||!r)return null;let s=await cS({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 "${Jg}" 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 "${Jg}" 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 jt="--skip-review";function Ws(e,t){return tS(e,t)}function Fa(e,t){try{return Ws(e,oy(e,t)).length}catch{return 0}}function It(e,t,n="",o,r){let s=Fa(e,o),i=Ua(e,o),a=o?` ${o}`:"",c=o?"/push":"/push --all",l=Ug(e,{just:r}),f=!!o&&o.endsWith(".md"),g=l&&f?` (${l.short} \u2014 ${l.cmd} once this page is delivered.)`:"";if(l&&!f){let A=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}${l.text}${A}`,cmd:l.cmd}}if(s===0&&i===0)return g?{...t,text:`${t.text}${g}`}:t;let k=o&&!o.endsWith(".md")?` in ${o}`:"";if(s>0){let A=s===1?"":"s",S=i>0?` ${i} also break house style rules \u2014 /lint${a} --blocked --fix clears those afterwards.`:"",C=`/review${a} --blocked --fix`;return{text:`${n}${s} article${A}${k} ${s===1?"carries":"carry"} text no editor has read, so pushing ${s===1?"it is":"them is"} blocked. ${C} reads ${s===1?"it":"just those"} and applies its fixes.${S} Then ${c}.${g}`,cmd:C}}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 ${c}.${g}`,cmd:`/lint${a} --blocked --fix`}}function Ua(e,t){try{return ny(e,oy(e,t)).length}catch{return 0}}function cy(e,t){return ny(e,t)}function Ku(e,t,n){try{let o=ey(e,Ma(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 Yu(e,t){let n=`/push${t.scope?` ${t.scope}`:" --all"}`,o=c=>`${c} article${c===1?"":"s"}`,r=[],s=e.pushed.length,i=t.elapsedMs!==void 0?` \xB7 ${fS(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 c=e.failed.filter(g=>g.refused),l=hS(e.failed,t.docsRoot),f=e.failed.length;if(l.length===1&&f>1)r.push(`${o(f)} could not be pushed \u2014 all with the same error: ${l[0].error}`),r.push(...Zg(l[0].paths," \u2717 "));else{r.push(`${o(f)} could not be pushed:`);for(let g of l)g.paths.length===1?r.push(` \u2717 ${g.paths[0]} \u2014 ${g.error}`):(r.push(` \u2717 ${o(g.paths.length)} \u2014 ${g.error}`),r.push(...Zg(g.paths," ")))}c.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): ${pS(e.notRun)}`),e.missingShots.length>0){let c=e.missingShots.flatMap(l=>l.ids);r.push(`\u26A0 ${c.length} screenshot${c.length===1?"":"s"} in ${o(e.missingShots.length)} ${c.length===1?"has":"have"} not been taken, so the description was published instead: /screenshot capture`)}return t.conflictsSkipped&&t.conflictsSkipped>0&&r.push(Fs(t.conflictsSkipped,t.unreadableSkipped??0)),r}var pS=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Hu=5;function Zg(e,t){let n=e.slice(0,Hu).map(o=>`${t}${o}`);return e.length>Hu&&n.push(`${" ".repeat(t.length)}\u2026 +${e.length-Hu} more`),n}function hS(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 fS(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 Qt(e,t,n=0,o){let r=nS(e.cwd,t,{allowUnreviewed:o?.skipReview===!0,allowStyleErrors:o?.skipStyle===!0});if(!r.clear){for(let l of oS(r,t.length,{act:"push"}))console.log(K(l));return{kind:"continue"}}let s={aborted:!1,partitions:0,failed:0,notRun:0,producedNothing:!0},i={retryable:0,stopped:!1,paths:[]},a=async(l,f)=>{let g=Date.now();console.log(d(f?`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 (${iS} at a time)\u2026`));let k=await rS({cwd:e.cwd,...e.profileName?{profileName:e.profileName}:{},paths:l,allowProdWrites:e.allowProdWrites?.()===!0,...o?.allowUnpullable===!0?{allowUnpullable:!0}:{},onEvent:I=>{I.type==="article_done"?console.log(X(` \u2713 ${I.result.path}${I.result.action==="created"?" (new)":""}`)):I.type==="article_failed"&&console.log(L(` \u2717 ${I.failure.path}`))}});console.log("");let T=Ku(e.cwd,l,e.profileName);f||(i={retryable:k.failed.filter(I=>!I.refused).length,stopped:!!k.stopped,paths:k.failed.map(I=>I.path)},s={aborted:k.aborted||!!k.stopped,partitions:QR(l).length,failed:k.failed.length,notRun:k.notRun.length,producedNothing:k.pushed.length===0,verifiedComplete:T>=l.length,leftBehind:n});let A=k.pushed.length>0;for(let I of Yu(k,{recorded:T,elapsedMs:Date.now()-g,docsRoot:lS(e.cwd),...f?{}:{conflictsSkipped:n,unreadableSkipped:o?.unreadableSkipped??0},...o?.scope?{scope:o.scope}:{}}))console.log(A&&k.failed.length===0?X(I):K(I));let S=k.aborted||!!k.stopped;if(!A)return S;let C=Vu(e.cwd,e.profileName);C&&console.log(d(C));let x=Dr(e.cwd,e.profileName);if(x&&console.log(d(x)),S)return S;try{let I=sy(await ry({cwd:e.cwd,profileName:e.profileName,onRateLimit:W=>console.log(d(` Document360 rate limit \u2014 waiting ${Math.ceil(W.waitMs/1e3)}s\u2026`))}));I&&console.log(I.startsWith("\u26A0")?K(I):d(I))}catch{}try{let I=ay(await iy({cwd:e.cwd,profileName:e.profileName}));I&&console.log(d(I))}catch{}let E=await Us(e.cwd,e.profileName);return E&&console.log(d(E)),S};try{if(!await a(t,!1)){let f=await zu(e.cwd,e.profileName,t,i.paths);if(f.length>0&&await a(f,!0),Xt(s))for(let g of Ke(e.cwd,o?.scope?`/push ${o.scope}`:"/push --all"))console.log(X(g))}}catch(l){console.log(L(`Push run failed: ${l.message}`))}if(console.log(""),i.retryable>0){let l=Se("/push",o?.scope?"":"--all",o?.scope);return console.log(d(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}}let c=qu(e.cwd,{scope:o?.scope,profileName:e.profileName});return c?(console.log(d(`Next: ${c.cmd} \u2014 ${c.reason}.`)),{kind:"continue",ownNext:!0}):{kind:"continue"}}async function Wa(e,t,n){let o=JR(e,n);if(o.length===0)return[];let r=new Set(Fo((await Oa({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function zu(e,t,n,o=[]){try{let r=new Set(n),s=new Set(o),i=await Oa({cwd:e,profileName:t});return Fo(i.entries).map(a=>a.path).filter(a=>r.has(a)&&!s.has(a))}catch{return[]}}async function mS(e,t,n){try{let o=await sS({cwd:e,...t?{profileName:t}:{},relPath:n.replace(/\\/g,"/"),preview:!0});console.log(""),console.log(X(`${o.title}`)),console.log(d(`${o.path} \xB7 ${o.articleId?`updates article ${o.articleId}`:"would be created as a new article"}`)),o.shots.length>0&&console.log(d(`${o.shots.length} screenshot${o.shots.length===1?"":"s"} embedded: ${o.shots.map(r=>r.id).join(", ")}`)),o.missingShots.length>0&&console.log(K(`\u26A0 ${o.missingShots.length} screenshot${o.missingShots.length===1?"":"s"} not taken yet \u2014 the description publishes instead: ${o.missingShots.join(", ")}`)),console.log(d("\u2500".repeat(Math.min(80,Math.max(20,(process.stdout.columns??80)-1))))),console.log(o.body),console.log(d("\u2500".repeat(Math.min(80,Math.max(20,(process.stdout.columns??80)-1))))),console.log(d(`Nothing was sent. Run /push ${o.path} to save it as a draft.`))}catch(o){console.log(L(o.message))}return{kind:"continue"}}async function Ba(e,t){let n=Je(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(L(n.reason)),{kind:"continue"};let o=e.includes(jt),r=e.includes(aS);if(e.includes("--preview")){let i=e.find(a=>!a.startsWith("--"));return i?await mS(t?.cwd??process.cwd(),t?.profileName,i):(console.log(L("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(T=>!T.startsWith("--")),c=Ue(i),l=Pa(c,a);if(l.length===0){let T=c.filter(A=>A.state==="captured").length;return console.log(d(T>0?`${T} screenshot${T===1?" has":"s have"} been taken but the callouts aren't drawn on yet, so there is nothing to embed \u2014 /screenshot annotate finishes ${T===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 f=Ta(c,a);f&&console.log(f);let g=Aa(c);g&&console.log(g);let k=Se("","--screenshots",a).trim();return await Qt(t??{cwd:process.cwd()},l,0,{skipReview:o,skipStyle:r,scope:k})}if(s==="--related"&&e[1]){if(!t)return{kind:"continue"};let i=await Wa(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return i.length===0?(console.log(X("\u2713 All related articles are already on Document360.")),{kind:"continue"}):await Qt(t,i,0,{skipReview:o,skipStyle:r,scope:`--related ${e[1]}`})}if(s==="--all"){console.log(d("Checking what needs pushing\u2026"));try{let i=await Oa({cwd:t?.cwd??process.cwd()}),a=new Set(Mo(t?.cwd??process.cwd(),t?.profileName)),{clean:c,conflicts:l}=_o(i.entries,a),f=l.filter(S=>a.has(S.path)).length,g=_a(i.entries),k=e.includes("--force"),T=k&&l.length>0;g>0&&console.log(K(`\u26A0 ${g} 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&&!T&&console.log(K(Fs(l.length,f)));let A=T?[...c,...l]:c;if(A.length===0){if(l.length>0){let C=Dr(t?.cwd??process.cwd(),t?.profileName);return C&&console.log(d(C)),console.log(d("Resolve the conflicts: /resolve")),{kind:"continue"}}console.log(X(g>0?"\u2713 Nothing else is ahead of Document360 to push.":"\u2713 Nothing is ahead of Document360 \u2014 nothing to push."));let S=Dr(t?.cwd??process.cwd(),t?.profileName);if(S&&console.log(d(S)),t)try{let C=sy(await ry({cwd:t.cwd,profileName:t.profileName,onRateLimit:E=>console.log(d(` Document360 rate limit \u2014 waiting ${Math.ceil(E.waitMs/1e3)}s\u2026`))}));C&&console.log(C.startsWith("\u26A0")?K(C):d(C));let x=ay(await iy({cwd:t.cwd,profileName:t.profileName}));x&&console.log(d(x))}catch{}return{kind:"continue"}}return await Qt(t??{cwd:process.cwd()},A.map(S=>S.path),T?0:l.length,{skipReview:o,skipStyle:r,allowUnpullable:k,unreadableSkipped:T?0:f})}catch(i){return console.log(L(`Could not compute sync status: ${i.message}`)),{kind:"continue"}}}if(s&&s.startsWith("--")&&(s=e.find(i=>!i.startsWith("--"))??""),!s){console.log(d("Checking what needs pushing\u2026"));let i,a=0,c=0;try{let l=await Oa({cwd:t?.cwd??process.cwd()}),f=new Set(Mo(t?.cwd??process.cwd(),t?.profileName)),{clean:g,conflicts:k}=_o(l.entries,f);c=k.filter(A=>f.has(A.path)).length,i=g,a=k.length;let T=_a(l.entries);if(T>0&&console.log(K(`\u26A0 ${T} 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.`)),k.length>0&&console.log(K(Fs(k.length,c))),i.length===0&&k.length>0)return console.log(d("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(l){return console.log(L(`Could not compute sync status: ${l.message}`)),console.log(d("Push a specific article: /push <article-path>")),{kind:"continue"}}if(i.length===0)return console.log(X("\u2713 Nothing is ahead of Document360 \u2014 nothing to push.")),console.log(d(" (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} ${d(`(${l.label})`)}`);return console.log(d("Run: /push <article-path>")),{kind:"continue"}}try{s=await t.withPausedInput(()=>XR({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(d("Cancelled.")),{kind:"continue"}}if(s==="--all")return await Qt(t,i.map(l=>l.path),a,{skipReview:o,skipStyle:r,unreadableSkipped:c})}return await Qt(t??{cwd:process.cwd()},[s],0,{skipReview:o,skipStyle:r,scope:s})}oe();import{select as bS}from"@inquirer/prompts";import{computeSyncStatus as kS,localAheadPaths as $S,pendingDrafts as vS,publishArticleLive as xS,publishGateVerdict as RS,publishGateLines as SS,blockedPaths as CS,placeholderRemedy as PS,resolveActiveProfile as _6,SKIP_STYLE_FLAG as TS,SKIP_SHOTS_FLAG as AS}from"document360-engine";import{gateFixTarget as gS}from"document360-engine";var Qu=e=>"ruleId"in e,Ha=e=>Qu(e)?e.severity:"warning",Yn=e=>e===1?"":"s";function Bs(e,t){let n=t??gS(e),o=n?` ${n}`:"";return e.unreviewed.length>0?`/review${o} --blocked --fix`:`/lint${o} --blocked --fix`}var Xu=new Map;var yS=e=>Qu(e)?e.fp||`${e.ruleId}:${e.path}:${e.line}:${e.term}`:`${e.kind}:${e.path}:${e.line}`;function Hs(e){let{cwd:t,after:n,scope:o,aborted:r,blocked:s}=e,i=n.filter(T=>Ha(T)==="error").length,a=n.filter(T=>Ha(T)==="warning").length,c=n.filter(T=>Ha(T)==="suggestion").length,l=Se("/lint","--blocked --fix",o);if(r){let T=Se("/lint",s?"--blocked --fix":"--fix",o);return{text:`Stopped. Nothing else changed \u2014 ${T} picks up where this left off.`,cmd:T}}if(i>0){let T=n.filter(E=>Ha(E)==="error"),A=new Set(T.map(E=>E.path)).size,S=`${t}::${o??""}`,C=T.map(yS).sort().join("|"),x=Xu.get(S)===C;if(Xu.set(S,C),x){let E=Se("/lint","--blocked --full",o),I=[...new Set(T.filter(Qu).map(W=>W.ruleId))];return{text:`The same ${i} error${Yn(i)} in ${A} article${Yn(A)} survived two ${l} passes, so a third would change nothing \u2014 ${i===1?"it needs":"they need"} a person. ${E} shows ${i===1?"it":"them"} in place. If ${I.length===1?`${I[0]} is`:"a rule is"} wrong for your product, switch it off in .d360-writer/config.json under "styleGuide": { "rules": { "<rule>": "off" } }.`,cmd:E}}return{text:`${i} error${Yn(i)} in ${A} article${Yn(A)} still block${i===1?"s":""} publishing. ${l} has another go at ${i===1?"it":"just those"} \u2014 if a second pass leaves the same ones, they need a human eye.`,cmd:l}}Xu.delete(`${t}::${o??""}`);let f=a>0&&c>0?`${a} warning${Yn(a)} and ${c} suggestion${Yn(c)} remain (neither blocks publishing). `:a>0?`${a} warning${Yn(a)} remain${a===1?"s":""}, which ${a===1?"does":"do"} not block publishing. `:c>0?`${c} suggestion${Yn(c)} remain${c===1?"s":""} \u2014 ${c===1?"it is":"they are"} judgment calls and ${c===1?"does":"do"} not block publishing. `:"",g=f===""?"\u2713 Nothing left to fix. ":`\u2713 ${f}`,k=o?"/push":"/push --all";return It(t,{text:`${g}Nothing is blocking${o?` in ${o}`:""} \u2014 ${k} saves the articles to Document360 as drafts.`,cmd:k},g,o)}var wS={check:"/check is now /lint (same command)."};function Ga(){return"That saves drafts rather than taking anything live, so running /push. (/publish takes saved drafts live.)"}var uy=new Set;function Gs(e){let t=wS[e.replace(/^\//,"")];return!t||uy.has(e)?null:(uy.add(e),t)}var ES=150,NS=e=>e>0?new Promise(t=>setTimeout(t,e)):Promise.resolve(),Zu=e=>e===1?"":"s",Ju=e=>e.replace(/\\/g,"/").split("/").pop()??e;function ed(e){return e.includes("--screenshots")||e.includes("--shots")||e[0]==="--related"}async function td(e,t,n){await kS({cwd:e,profileName:t});let o=n?n.replace(/\\/g,"/").replace(/\/+$/,""):null;return vS(e,t).filter(r=>!o||r.path===o||r.path.startsWith(`${o}/`)).map(r=>({...r,label:DS(e,r.path)}))}function DS(e,t){let n=ya(e,t)??Is(t),o=ga(t),r=o?Gn(o):"";return r?`${r} \u203A ${n}`:n}function jS(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 nd(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=$S(e,t).filter(a=>!s||a===s||a.startsWith(`${s}/`)).length;return i>0&&r.push(`${i} article${Zu(i)} ${i===1?"has":"have"} local edits that aren't on Document360 yet \u2014 that's /push${n?` ${n}`:""}.`),{lines:r,ahead:i}}function qa(e,t,n){let o=null;try{o=PS(e,t.placeholders)?.cmd??null}catch{}return{cmd:t.unreviewed.length>0||t.styleErrors.length>0?Bs(t,n):o,shotFix:o}}async function od(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 xS({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 NS(ES)}return r}function rd(e){let{published:t,blocked:n,failed:o}=e,r=[];if(t.length>0){r.push(`\u2713 ${t.length} article${Zu(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 ${Ju(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 ${Ju(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 dy(e,t){let n=t?.cwd??process.cwd();if(ed(e))return console.log(d(`\u2192 ${Ga()}`)),Ba(e,t);let o=Je(n,t?.profileName);if(!o.ok)return console.log(L(o.reason)),{kind:"continue"};let r=e.includes(jt),s=e.includes(TS),i=e.includes(AS),a=e.includes("--all"),c=e.find(C=>!C.startsWith("--"));console.log(d("Checking what is waiting to go live\u2026"));let l;try{l=await td(n,t?.profileName,c)}catch(C){return console.log(L(`Could not check Document360: ${C.message}`)),{kind:"continue"}}if(l.length===0){for(let C of nd(n,t?.profileName,c).lines)console.log(C.startsWith("\u2713")?X(C):d(C));return{kind:"continue"}}let f=RS(n,l.map(C=>C.path),{allowUnreviewed:r,allowStyleErrors:s,checkScreenshots:!0,allowPlaceholders:i}),g=new Set(CS(f)),k=l.filter(C=>!g.has(C.path)),T=qa(n,f,c);if(g.size>0)for(let C of SS(f,l.length,{scope:c,act:"publish",going:k.length,shotFix:T.shotFix}))console.log(K(C));if(k.length===0)return T.cmd&&console.log(d(`Run: ${T.cmd}`)),{kind:"continue"};l=k,console.log(""),console.log(`${l.length} draft${Zu(l.length)} ${l.length===1?"is":"are"} ahead of what readers see:`);for(let C of jS(l.slice(0,12)))console.log(d(C));l.length>12&&console.log(d(` \u2026and ${l.length-12} more`)),console.log("");let A=l;if(!a){let C=await bS({message:"Publish live to your readers?",choices:[{name:`Yes \u2014 publish all ${l.length} live`,value:"all"},...l.slice(0,8).map(x=>({name:`Just ${x.label}`,value:x.path})),{name:"No \u2014 leave them as drafts",value:"none"}]});if(C==="none")return console.log(d("Left as drafts. Nothing changed.")),{kind:"continue"};C!=="all"&&(A=l.filter(x=>x.path===C))}let S=await od(n,t?.profileName,A,{skipReview:r,skipStyle:s,onProgress:(C,x,E)=>console.log(d(` \u25B8 ${C+1}/${x} ${Ju(E)}\u2026`))});console.log("");for(let C of rd(S))console.log(C.startsWith("\u2713")?X(C):C.startsWith("\u2717")?K(C):d(C));return{kind:"continue"}}import{loadKnownConflicts as IS,localArticleTitle as LS,resolveActiveProfile as OS}from"document360-engine";function _S(e,t){let n=LS(e,t);return n||(t.split(/[\\/]/).pop()??t).replace(/\.md$/,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ")}function Va(e,t){let n=[];try{n=IS(e,OS(e,t).name)}catch{return null}if(n.length===0)return null;let o=n.length,r=n.slice(0,3).map(i=>_S(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 jr={cmd:"/resolve",reason:"it walks each one with you \u2014 keep yours, take the portal's, or skip"};async function qs(e){if(e?.cwd){let n=Va(e.cwd,e.profileName);if(n)return{kind:"audit-blocked",note:n.note,lead:jr}}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 against the CURRENT code (its `sources` exist, and the code as it stands shows the surface it claims) before trusting it; never judge it by its `branch` or `commit`. Fold verified ones into the table, flag the rest.","2.6. Anything d360_pending_hints returns under `held` is NOT a proposal. Its cited code has uncommitted changes, so the builder is still writing that surface and has already been asked whether it is done. List each held item at the END of the table as a `waiting` row (Reason: the code behind it is not finished), do NOT propose create/update/retire for it, and do NOT stamp it consumed.","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(`
340
- `),display:"/audit"}}oe();import{readProjectConfig as MS,writeProjectConfig as py,autoBudgetUsd as FS,autoModeEnabled as US,DEFAULT_AUTO_BUDGET_USD as WS}from"document360-engine";function Ye(e){return`$${e%1===0?e.toFixed(0):e.toFixed(2)}`}function Vs(e){return e?"I run the next step myself instead of waiting for you \u2014 writing, reviewing, checking style, saving and going live.":"I suggest the next step and wait for you to run it."}function Ks(e){let t=US(e),n=FS(e),o=e.auto?.budgetUsd===void 0?" (the standard limit \u2014 nothing set for this repo)":"",r=[{tone:"info",text:`Mode: ${t?"auto":"manual"} \u2014 ${Vs(t)}`}];return t?(r.push({tone:"info",text:`Spending limit: ${Ye(n)} a run${o}. I stop and report when it is reached.`}),r.push({tone:"info",text:"Screenshots are never part of an automatic run \u2014 they need your product running."}),r.push({tone:"info",text:"Stop a run at any time: esc. Switch back to manual: shift+tab, or /auto off."})):r.push({tone:"info",text:`Turn it on: /auto on \xB7 or shift+tab. Spending limit if you do: ${Ye(n)} a run.`}),r}function Ka(e,t,n,o=new Date){let r={...t,auto:{...t.auto,enabled:n,decidedAt:o.toISOString()}};return py(r,e),[n?{tone:"ok",text:z("\u2713")+"Auto mode ON \u2014 "+Vs(!0)}:{tone:"ok",text:z("\u2713")+"Manual mode \u2014 "+Vs(!1)},...Ks(r)]}function id(e,t,n){if(!Number.isFinite(n)||n<=0)return null;let o={...t,auto:{...t.auto,enabled:t.auto?.enabled===!0,budgetUsd:n}};return py(o,e),[{tone:"ok",text:z("\u2713")+`Spending limit set to ${Ye(n)} a run.`},...Ks(o)]}function ad(e){let t=e.findIndex(r=>r==="--budget"||r.startsWith("--budget="));if(t===-1)return{malformed:!1};let n=e[t].includes("=")?e[t].split("=").slice(1).join("="):e[t+1];if(n===void 0)return{malformed:!0};let o=Number(String(n).replace(/^\$/,"").replace(/,/g,""));return!Number.isFinite(o)||o<=0?{malformed:!0}:{usd:o,malformed:!1}}function ld(e,t){let n=e.findIndex(o=>o==="--budget");return e.filter((o,r)=>!o.startsWith("--")&&!(n!==-1&&r===n+1)&&o!==String(t)).map(o=>o.trim().toLowerCase()).find(o=>o.length>0)}var sd=e=>{for(let t of e)console.log(t.tone==="ok"?X(t.text):t.tone==="warn"?K(t.text):t.tone==="error"?L(t.text):d(t.text))};async function hy(e,t){let n=t.cwd,o=MS(n);if(!o)return console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=ad(e);if(r.malformed)return console.log(L(`I could not read that spending limit. Give it as an amount, like: /auto --budget 150 (the standard limit is ${Ye(WS)}).`)),{kind:"continue"};let s=ld(e,r.usd);if(r.usd!==void 0&&!s){let i=id(n,o,r.usd);return i&&sd(i),{kind:"continue"}}if(!s||s==="status")return sd(Ks(o)),{kind:"continue"};if(s==="on"||s==="off"){let i=r.usd!==void 0?{...o,auto:{...o.auto,enabled:o.auto?.enabled===!0,budgetUsd:r.usd}}:o;return sd(Ka(n,i,s==="on")),{kind:"continue"}}return console.log(L(`I don't know "${s}". Use: /auto on \xB7 /auto off \xB7 /auto status \xB7 /auto --budget <amount>`)),{kind:"continue"}}oe();import{readProjectConfig as BS}from"document360-engine";function cd(){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(`
341
- `)}async function fy(e,t){let n=t?.cwd??process.cwd();return BS(n)?{kind:"forward-to-agent",prompt:cd(),display:"/discover"}:(console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"})}oe();import{checkbox as HS}from"@inquirer/prompts";import{inventoryRepo as GS,readProjectConfig as my,writeProjectConfig as qS}from"document360-engine";function ud(e,t){let n=my(e);n&&(n.authoritativeSourceFiles=t,qS(n,e))}function Ya(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 gy(e,t){let n=t?.cwd??process.cwd();if(!my(n))return console.log(L("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=GS(n);if(o.length===0)return console.log(d('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(ee("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${d(Ya(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>HS({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${Ya(s)})`,value:s.path,checked:s.recommended})),pageSize:20}))}catch{return console.log(d("Cancelled.")),{kind:"continue"}}if(r.length===0)return console.log(d("Nothing selected \u2014 scope unchanged.")),{kind:"continue"};ud(n,r),console.log(X(`\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"}}oe();import{confirm as oC}from"@inquirer/prompts";import{applyPull as fd,computeSyncStatus as Ty,compareRemoteSources as rC,planPull as Ay,planImport as sC,applyImport as iC,establishBaselines as aC,rebaselineServerMeta as lC,D360AuthError as cC}from"document360-engine";oe();var yy=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /push <path>):",paint:L,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /push <path>:",paint:K,mark:"M"},{status:"remote-ahead",header:"Changed on Document360 \u2014 pull with /pull <path> (or just /pull):",paint:ee,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:L,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:L,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint:Te,mark:"X"},{status:"untracked-local",header:"New here \u2014 not on Document360 yet (publish to add them):",paint:d,mark:"?"},{status:"untracked-remote",header:"On Document360 \u2014 not in your local docs yet (run /pull to import them):",paint:d,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:Te,mark:"\xB7"}];function VS(e){return e.path?e.path:`${e.title??"(untitled)"} ${Te(`[${e.articleId}]`)}`}function KS(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 za(e,t){let n=[],o=e.entries.filter(f=>f.link);if(o.length>0){n.push(""),n.push(Qe("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let f of o)n.push(` ${K("~")} ${K(f.path??"")} ${Te(`\u2192 "${f.link.title}"`)}`)}for(let f of yy){let g=e.entries.filter(k=>k.status===f.status&&!(f.status==="untracked-local"&&k.link));if(g.length!==0){n.push(""),n.push(Qe(f.header));for(let k of g)n.push(` ${f.paint(f.mark)} ${f.paint(VS(k))}${k.detail?Te(` (${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,c=s===r?X("\u2713 everything up to date"):[r>0?X(`\u2713 ${r} up to date`):null,a>0?`${a} to link`:null,...yy.map(f=>{let g=(e.counts[f.status]??0)-(f.status==="untracked-local"?a:0);return g>0?`${g} ${i[f.status]}`:null})].filter(Boolean).join(Te(" \xB7 ")),l=t!==void 0?` \xB7 synced in ${KS(t)}`:"";return n.push(c+Te(` \xB7 ${s} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${l}`)),n}import{structuredPatch as YS}from"diff";import wy from"picocolors";var zS=80,Ir=400,XS="\x1B[48;2;74;28;28m",QS="\x1B[48;2;24;66;24m",by="\x1B[49m",dd=e=>String(e).padStart(5);function ky(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}function $y(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 Lt(e,t,n,o=zS){let r=A=>{let S=A.replace(/\r\n/g,`
339
+ `):null}async function ry(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let o=Er(n,e.slice(1).join(" ").trim());return console.log(o.ok?Q(o.line):q(o.line)),{kind:"continue"}}for(let o of Yu(n,{all:e.some(r=>r.toLowerCase()==="--all")}))console.log(o);return{kind:"continue"}}var zu={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 pushing overwrites the portal edit"},$S="\u26A0 held on Document360 in another editor \u2014 /resolve settles it";function Uo(e){return e.filter(t=>t.path!==null&&t.status in zu&&!t.link).map(t=>({path:t.path,label:zu[t.status]}))}function Mo(e,t=[]){let n=Uo(e),o=new Set(t),r=new Set([...e.filter(s=>s.status==="conflict"&&s.path).map(s=>s.path),...o]);return{clean:n.filter(s=>!r.has(s.path)),conflicts:n.filter(s=>r.has(s.path)).map(s=>o.has(s.path)&&s.label!==zu.conflict?{...s,label:$S}:s)}}function Fo(e,t){try{return uS(e,Ha(e,t).name).map(n=>n.path)}catch{return[]}}function Ws(e,t=0){let n=e!==1;if(t>=e)return`\u26A0 ${e} article${n?"s":""} NOT pushed (nothing on the portal overwritten) \u2014 Document360 holds ${n?"their bodies":"its body"} in another editor, so ${n?"they cannot be":"it cannot be"} read back. Settle ${n?"them":"it"}: /resolve (or ask your Document360 admin to move ${n?"them":"it"} to the Markdown editor).`;let o=t>0?` (${t} of ${n?"them are":"these is"} held in another editor and cannot be read back)`:"";return`\u26A0 ${e} conflict${n?"s":""} NOT pushed (portal edit${n?"s":""} kept safe) \u2014 ${n?"these were":"it was"} edited both here and on the portal, so ${n?"they are":"it is"} left untouched.${o} Settle ${n?"them":"it"}: /resolve (or /push <path> to keep yours, /pull <path> to take the portal's).`}function Xu(e,t){let n=t.scope?.replace(/\\/g,"/").replace(/\/+$/,"");return!n||!n.endsWith(".md")||!ly(e,t.profileName).map(r=>r.replace(/\\/g,"/")).some(r=>r===n||r.endsWith(`/${n}`)||n.endsWith(`/${r}`))?null:{cmd:Se("/publish","",n),reason:"it takes this draft live \u2014 until it does, your readers still see the previous version"}}function Nr(e,t){let n=ly(e,t),o=n.length;if(o===0)return null;let r=o===1?"":"s",s=0;try{s=cS(e,n).length}catch{}if(s>0){let i=o-s,a=`${s===o?o===1?"It is":"All of them are":`${s} of them ${s===1?"is":"are"}`} waiting on a missing picture`;return`\u2139 ${o} article${r} ${o===1?"is":"are"} saved on Document360 as a draft and not live yet \u2014 readers still see the previous version. ${a}, so /publish holds ${s===1?"it":"them"} back${i>0?` and takes the other ${i} live once ${i===1?"it has":"they have"} been signed off.`:"."}`}return`\u2139 ${o} article${r} ${o===1?"is":"are"} saved on Document360 as a draft and not live yet \u2014 readers still see the previous version. /publish takes ${o===1?"it":"them"} live once ${o===1?"it has":"they have"} been signed off.`}function Ba(e){return e.filter(t=>t.link).length}function Qu(e,t){try{let n=ay(e,Ha(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=kS(rS(sS(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 my(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:`${qn(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 Bs(e,t){try{let n=Ha(e,t),o=n.project.projectId,r=n.project.workspaceId;if(!o||!r)return null;let s=await bS({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 "${sy}" 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 "${sy}" 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 Ot="--skip-review";function Hs(e,t){return dS(e,t)}function Ga(e,t){try{return Hs(e,uy(e,t)).length}catch{return 0}}function _t(e,t,n="",o,r){let s=Ga(e,o),i=qa(e,o),a=o?` ${o}`:"",c=o?"/push":"/push --all",l=Yg(e,{just:r}),f=!!o&&o.endsWith(".md"),g=l&&f?` (${l.short} \u2014 ${l.cmd} once this page is delivered.)`:"";if(l&&!f){let A=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}${l.text}${A}`,cmd:l.cmd}}if(s===0&&i===0)return g?{...t,text:`${t.text}${g}`}:t;let $=o&&!o.endsWith(".md")?` in ${o}`:"";if(s>0){let A=s===1?"":"s",S=i>0?` ${i} also break house style rules \u2014 /lint${a} --blocked --fix clears those afterwards.`:"",C=`/review${a} --blocked --fix`;return{text:`${n}${s} article${A}${$} ${s===1?"carries":"carry"} text no editor has read, so pushing ${s===1?"it is":"them is"} blocked. ${C} reads ${s===1?"it":"just those"} and applies its fixes.${S} Then ${c}.${g}`,cmd:C}}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 ${c}.${g}`,cmd:`/lint${a} --blocked --fix`}}function qa(e,t){try{return cy(e,uy(e,t)).length}catch{return 0}}function gy(e,t){return cy(e,t)}function Ju(e,t,n){try{let o=ay(e,Ha(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 Zu(e,t){let n=`/push${t.scope?` ${t.scope}`:" --all"}`,o=c=>`${c} article${c===1?"":"s"}`,r=[],s=e.pushed.length,i=t.elapsedMs!==void 0?` \xB7 ${RS(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 c=e.failed.filter(g=>g.refused),l=xS(e.failed,t.docsRoot),f=e.failed.length;if(l.length===1&&f>1)r.push(`${o(f)} could not be pushed \u2014 all with the same error: ${l[0].error}`),r.push(...iy(l[0].paths," \u2717 "));else{r.push(`${o(f)} could not be pushed:`);for(let g of l)g.paths.length===1?r.push(` \u2717 ${g.paths[0]} \u2014 ${g.error}`):(r.push(` \u2717 ${o(g.paths.length)} \u2014 ${g.error}`),r.push(...iy(g.paths," ")))}c.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): ${vS(e.notRun)}`),e.missingShots.length>0){let c=e.missingShots.flatMap(l=>l.ids);r.push(`\u26A0 ${c.length} screenshot${c.length===1?"":"s"} in ${o(e.missingShots.length)} ${c.length===1?"has":"have"} not been taken, so the description was published instead: /screenshot capture`)}if(e.categoryLookupFailed.length>0){let c=e.categoryLookupFailed.length;r.push(`\u26A0 Could not check Document360 for existing categories, so ${c===1?"a new one was":`${c} new ones were`} created. There may now be two with the same name: /doctor lists them.`),r.push(` Reason: ${e.categoryLookupFailed[0].reason}`)}return t.conflictsSkipped&&t.conflictsSkipped>0&&r.push(Ws(t.conflictsSkipped,t.unreadableSkipped??0)),r}var vS=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Ku=5;function iy(e,t){let n=e.slice(0,Ku).map(o=>`${t}${o}`);return e.length>Ku&&n.push(`${" ".repeat(t.length)}\u2026 +${e.length-Ku} more`),n}function xS(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 RS(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 Jt(e,t,n=0,o){let r=pS(e.cwd,t,{allowUnreviewed:o?.skipReview===!0,allowStyleErrors:o?.skipStyle===!0});if(!r.clear){for(let l of hS(r,t.length,{act:"push"}))console.log(q(l));return{kind:"continue"}}let s={aborted:!1,partitions:0,failed:0,notRun:0,producedNothing:!0},i={retryable:0,stopped:!1,paths:[]},a=async(l,f)=>{let g=Date.now();console.log(d(f?`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 (${gS} at a time)\u2026`));let $=await fS({cwd:e.cwd,...e.profileName?{profileName:e.profileName}:{},paths:l,allowProdWrites:e.allowProdWrites?.()===!0,...o?.allowUnpullable===!0?{allowUnpullable:!0}:{},onEvent:j=>{j.type==="article_done"?console.log(Q(` \u2713 ${j.result.path}${j.result.action==="created"?" (new)":""}`)):j.type==="article_failed"&&console.log(L(` \u2717 ${j.failure.path}`))}});console.log("");let T=Ju(e.cwd,l,e.profileName);f||(i={retryable:$.failed.filter(j=>!j.refused).length,stopped:!!$.stopped,paths:$.failed.map(j=>j.path)},s={aborted:$.aborted||!!$.stopped,partitions:aS(l).length,failed:$.failed.length,notRun:$.notRun.length,producedNothing:$.pushed.length===0,verifiedComplete:T>=l.length,leftBehind:n});let A=$.pushed.length>0;for(let j of Zu($,{recorded:T,elapsedMs:Date.now()-g,docsRoot:wS(e.cwd),...f?{}:{conflictsSkipped:n,unreadableSkipped:o?.unreadableSkipped??0},...o?.scope?{scope:o.scope}:{}}))console.log(A&&$.failed.length===0?Q(j):q(j));let S=$.aborted||!!$.stopped;if(!A)return S;let C=Qu(e.cwd,e.profileName);C&&console.log(d(C));let x=Nr(e.cwd,e.profileName);if(x&&console.log(d(x)),S)return S;try{let j=py(await dy({cwd:e.cwd,profileName:e.profileName,onRateLimit:W=>console.log(d(` Document360 rate limit \u2014 waiting ${Math.ceil(W.waitMs/1e3)}s\u2026`))}));j&&console.log(j.startsWith("\u26A0")?q(j):d(j))}catch{}try{let j=fy(await hy({cwd:e.cwd,profileName:e.profileName}));j&&console.log(d(j))}catch{}let E=await Bs(e.cwd,e.profileName);return E&&console.log(d(E)),S};try{if(!await a(t,!1)){let f=await ed(e.cwd,e.profileName,t,i.paths);if(f.length>0&&await a(f,!0),Qt(s))for(let g of Ye(e.cwd,o?.scope?`/push ${o.scope}`:"/push --all"))console.log(Q(g))}}catch(l){console.log(L(`Push run failed: ${l.message}`))}if(console.log(""),i.retryable>0){let l=Se("/push",o?.scope?"":"--all",o?.scope);return console.log(d(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}}let c=Xu(e.cwd,{scope:o?.scope,profileName:e.profileName});return c?(console.log(d(`Next: ${c.cmd} \u2014 ${c.reason}.`)),{kind:"continue",ownNext:!0}):{kind:"continue"}}async function Va(e,t,n){let o=lS(e,n);if(o.length===0)return[];let r=new Set(Uo((await Wa({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function ed(e,t,n,o=[]){try{let r=new Set(n),s=new Set(o),i=await Wa({cwd:e,profileName:t});return Uo(i.entries).map(a=>a.path).filter(a=>r.has(a)&&!s.has(a))}catch{return[]}}async function SS(e,t,n){try{let o=await mS({cwd:e,...t?{profileName:t}:{},relPath:n.replace(/\\/g,"/"),preview:!0});console.log(""),console.log(Q(`${o.title}`)),console.log(d(`${o.path} \xB7 ${o.articleId?`updates article ${o.articleId}`:"would be created as a new article"}`)),o.shots.length>0&&console.log(d(`${o.shots.length} screenshot${o.shots.length===1?"":"s"} embedded: ${o.shots.map(r=>r.id).join(", ")}`)),o.missingShots.length>0&&console.log(q(`\u26A0 ${o.missingShots.length} screenshot${o.missingShots.length===1?"":"s"} not taken yet \u2014 the description publishes instead: ${o.missingShots.join(", ")}`)),console.log(d("\u2500".repeat(Math.min(80,Math.max(20,(process.stdout.columns??80)-1))))),console.log(o.body),console.log(d("\u2500".repeat(Math.min(80,Math.max(20,(process.stdout.columns??80)-1))))),console.log(d(`Nothing was sent. Run /push ${o.path} to save it as a draft.`))}catch(o){console.log(L(o.message))}return{kind:"continue"}}async function Ya(e,t){let n=Je(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(L(n.reason)),{kind:"continue"};let o=e.includes(Ot),r=e.includes(yS);if(e.includes("--preview")){let i=e.find(a=>!a.startsWith("--"));return i?await SS(t?.cwd??process.cwd(),t?.profileName,i):(console.log(L("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(T=>!T.startsWith("--")),c=Ue(i),l=Da(c,a);if(l.length===0){let T=c.filter(A=>A.state==="captured").length;return console.log(d(T>0?`${T} screenshot${T===1?" has":"s have"} been taken but the callouts aren't drawn on yet, so there is nothing to embed \u2014 /screenshot annotate finishes ${T===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 f=ja(c,a);f&&console.log(f);let g=Ia(c);g&&console.log(g);let $=Se("","--screenshots",a).trim();return await Jt(t??{cwd:process.cwd()},l,0,{skipReview:o,skipStyle:r,scope:$})}if(s==="--related"&&e[1]){if(!t)return{kind:"continue"};let i=await Va(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 Jt(t,i,0,{skipReview:o,skipStyle:r,scope:`--related ${e[1]}`})}if(s==="--all"){console.log(d("Checking what needs pushing\u2026"));try{let i=await Wa({cwd:t?.cwd??process.cwd()}),a=new Set(Fo(t?.cwd??process.cwd(),t?.profileName)),{clean:c,conflicts:l}=Mo(i.entries,a),f=l.filter(S=>a.has(S.path)).length,g=Ba(i.entries),$=e.includes("--force"),T=$&&l.length>0;g>0&&console.log(q(`\u26A0 ${g} 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&&!T&&console.log(q(Ws(l.length,f)));let A=T?[...c,...l]:c;if(A.length===0){if(l.length>0){let C=Nr(t?.cwd??process.cwd(),t?.profileName);return C&&console.log(d(C)),console.log(d("Resolve the conflicts: /resolve")),{kind:"continue"}}console.log(Q(g>0?"\u2713 Nothing else is ahead of Document360 to push.":"\u2713 Nothing is ahead of Document360 \u2014 nothing to push."));let S=Nr(t?.cwd??process.cwd(),t?.profileName);if(S&&console.log(d(S)),t)try{let C=py(await dy({cwd:t.cwd,profileName:t.profileName,onRateLimit:E=>console.log(d(` Document360 rate limit \u2014 waiting ${Math.ceil(E.waitMs/1e3)}s\u2026`))}));C&&console.log(C.startsWith("\u26A0")?q(C):d(C));let x=fy(await hy({cwd:t.cwd,profileName:t.profileName}));x&&console.log(d(x))}catch{}return{kind:"continue"}}return await Jt(t??{cwd:process.cwd()},A.map(S=>S.path),T?0:l.length,{skipReview:o,skipStyle:r,allowUnpullable:$,unreadableSkipped:T?0:f})}catch(i){return console.log(L(`Could not compute sync status: ${i.message}`)),{kind:"continue"}}}if(s&&s.startsWith("--")&&(s=e.find(i=>!i.startsWith("--"))??""),!s){console.log(d("Checking what needs pushing\u2026"));let i,a=0,c=0;try{let l=await Wa({cwd:t?.cwd??process.cwd()}),f=new Set(Fo(t?.cwd??process.cwd(),t?.profileName)),{clean:g,conflicts:$}=Mo(l.entries,f);c=$.filter(A=>f.has(A.path)).length,i=g,a=$.length;let T=Ba(l.entries);if(T>0&&console.log(q(`\u26A0 ${T} 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.`)),$.length>0&&console.log(q(Ws($.length,c))),i.length===0&&$.length>0)return console.log(d("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(l){return console.log(L(`Could not compute sync status: ${l.message}`)),console.log(d("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(d(" (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} ${d(`(${l.label})`)}`);return console.log(d("Run: /push <article-path>")),{kind:"continue"}}try{s=await t.withPausedInput(()=>iS({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(d("Cancelled.")),{kind:"continue"}}if(s==="--all")return await Jt(t,i.map(l=>l.path),a,{skipReview:o,skipStyle:r,unreadableSkipped:c})}return await Jt(t??{cwd:process.cwd()},[s],0,{skipReview:o,skipStyle:r,scope:s})}oe();import{select as AS}from"@inquirer/prompts";import{computeSyncStatus as ES,localAheadPaths as NS,pendingDrafts as DS,publishArticleLive as jS,publishGateVerdict as IS,publishGateLines as LS,blockedPaths as OS,placeholderRemedy as _S,resolveActiveProfile as t_,SKIP_STYLE_FLAG as MS,SKIP_SHOTS_FLAG as FS}from"document360-engine";import{gateFixTarget as CS}from"document360-engine";var nd=e=>"ruleId"in e,Ka=e=>nd(e)?e.severity:"warning",zn=e=>e===1?"":"s";function Gs(e,t){let n=t??CS(e),o=n?` ${n}`:"";return e.unreviewed.length>0?`/review${o} --blocked --fix`:`/lint${o} --blocked --fix`}var td=new Map;var PS=e=>nd(e)?e.fp||`${e.ruleId}:${e.path}:${e.line}:${e.term}`:`${e.kind}:${e.path}:${e.line}`;function qs(e){let{cwd:t,after:n,scope:o,aborted:r,blocked:s}=e,i=n.filter(T=>Ka(T)==="error").length,a=n.filter(T=>Ka(T)==="warning").length,c=n.filter(T=>Ka(T)==="suggestion").length,l=Se("/lint","--blocked --fix",o);if(r){let T=Se("/lint",s?"--blocked --fix":"--fix",o);return{text:`Stopped. Nothing else changed \u2014 ${T} picks up where this left off.`,cmd:T}}if(i>0){let T=n.filter(E=>Ka(E)==="error"),A=new Set(T.map(E=>E.path)).size,S=`${t}::${o??""}`,C=T.map(PS).sort().join("|"),x=td.get(S)===C;if(td.set(S,C),x){let E=Se("/lint","--blocked --full",o),j=[...new Set(T.filter(nd).map(W=>W.ruleId))];return{text:`The same ${i} error${zn(i)} in ${A} article${zn(A)} survived two ${l} passes, so a third would change nothing \u2014 ${i===1?"it needs":"they need"} a person. ${E} shows ${i===1?"it":"them"} in place. If ${j.length===1?`${j[0]} is`:"a rule is"} wrong for your product, switch it off in .d360-writer/config.json under "styleGuide": { "rules": { "<rule>": "off" } }.`,cmd:E}}return{text:`${i} error${zn(i)} in ${A} article${zn(A)} still block${i===1?"s":""} publishing. ${l} has another go at ${i===1?"it":"just those"} \u2014 if a second pass leaves the same ones, they need a human eye.`,cmd:l}}td.delete(`${t}::${o??""}`);let f=a>0&&c>0?`${a} warning${zn(a)} and ${c} suggestion${zn(c)} remain (neither blocks publishing). `:a>0?`${a} warning${zn(a)} remain${a===1?"s":""}, which ${a===1?"does":"do"} not block publishing. `:c>0?`${c} suggestion${zn(c)} remain${c===1?"s":""} \u2014 ${c===1?"it is":"they are"} judgment calls and ${c===1?"does":"do"} not block publishing. `:"",g=f===""?"\u2713 Nothing left to fix. ":`\u2713 ${f}`,$=o?"/push":"/push --all";return _t(t,{text:`${g}Nothing is blocking${o?` in ${o}`:""} \u2014 ${$} saves the articles to Document360 as drafts.`,cmd:$},g,o)}var TS={check:"/check is now /lint (same command)."};function za(){return"That saves drafts rather than taking anything live, so running /push. (/publish takes saved drafts live.)"}var yy=new Set;function Vs(e){let t=TS[e.replace(/^\//,"")];return!t||yy.has(e)?null:(yy.add(e),t)}var US=150,WS=e=>e>0?new Promise(t=>setTimeout(t,e)):Promise.resolve(),rd=e=>e===1?"":"s",od=e=>e.replace(/\\/g,"/").split("/").pop()??e;function sd(e){return e.includes("--screenshots")||e.includes("--shots")||e[0]==="--related"}async function id(e,t,n){await ES({cwd:e,profileName:t});let o=n?n.replace(/\\/g,"/").replace(/\/+$/,""):null;return DS(e,t).filter(r=>!o||r.path===o||r.path.startsWith(`${o}/`)).map(r=>({...r,label:BS(e,r.path)}))}function BS(e,t){let n=va(e,t)??Os(t),o=$a(t),r=o?qn(o):"";return r?`${r} \u203A ${n}`:n}function HS(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 ad(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=NS(e,t).filter(a=>!s||a===s||a.startsWith(`${s}/`)).length;return i>0&&r.push(`${i} article${rd(i)} ${i===1?"has":"have"} local edits that aren't on Document360 yet \u2014 that's /push${n?` ${n}`:""}.`),{lines:r,ahead:i}}function Xa(e,t,n){let o=null;try{o=_S(e,t.placeholders)?.cmd??null}catch{}return{cmd:t.unreviewed.length>0||t.styleErrors.length>0?Gs(t,n):o,shotFix:o}}async function ld(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 jS({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 WS(US)}return r}function cd(e){let{published:t,blocked:n,failed:o}=e,r=[];if(t.length>0){r.push(`\u2713 ${t.length} article${rd(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 ${od(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 ${od(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 wy(e,t){let n=t?.cwd??process.cwd();if(sd(e))return console.log(d(`\u2192 ${za()}`)),Ya(e,t);let o=Je(n,t?.profileName);if(!o.ok)return console.log(L(o.reason)),{kind:"continue"};let r=e.includes(Ot),s=e.includes(MS),i=e.includes(FS),a=e.includes("--all"),c=e.find(C=>!C.startsWith("--"));console.log(d("Checking what is waiting to go live\u2026"));let l;try{l=await id(n,t?.profileName,c)}catch(C){return console.log(L(`Could not check Document360: ${C.message}`)),{kind:"continue"}}if(l.length===0){for(let C of ad(n,t?.profileName,c).lines)console.log(C.startsWith("\u2713")?Q(C):d(C));return{kind:"continue"}}let f=IS(n,l.map(C=>C.path),{allowUnreviewed:r,allowStyleErrors:s,checkScreenshots:!0,allowPlaceholders:i}),g=new Set(OS(f)),$=l.filter(C=>!g.has(C.path)),T=Xa(n,f,c);if(g.size>0)for(let C of LS(f,l.length,{scope:c,act:"publish",going:$.length,shotFix:T.shotFix}))console.log(q(C));if($.length===0)return T.cmd&&console.log(d(`Run: ${T.cmd}`)),{kind:"continue"};l=$,console.log(""),console.log(`${l.length} draft${rd(l.length)} ${l.length===1?"is":"are"} ahead of what readers see:`);for(let C of HS(l.slice(0,12)))console.log(d(C));l.length>12&&console.log(d(` \u2026and ${l.length-12} more`)),console.log("");let A=l;if(!a){let C=await AS({message:"Publish live to your readers?",choices:[{name:`Yes \u2014 publish all ${l.length} live`,value:"all"},...l.slice(0,8).map(x=>({name:`Just ${x.label}`,value:x.path})),{name:"No \u2014 leave them as drafts",value:"none"}]});if(C==="none")return console.log(d("Left as drafts. Nothing changed.")),{kind:"continue"};C!=="all"&&(A=l.filter(x=>x.path===C))}let S=await ld(n,t?.profileName,A,{skipReview:r,skipStyle:s,onProgress:(C,x,E)=>console.log(d(` \u25B8 ${C+1}/${x} ${od(E)}\u2026`))});console.log("");for(let C of cd(S))console.log(C.startsWith("\u2713")?Q(C):C.startsWith("\u2717")?q(C):d(C));return{kind:"continue"}}import{loadKnownConflicts as GS,localArticleTitle as qS,resolveActiveProfile as VS}from"document360-engine";function YS(e,t){let n=qS(e,t);return n||(t.split(/[\\/]/).pop()??t).replace(/\.md$/,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ")}function Qa(e,t){let n=[];try{n=GS(e,VS(e,t).name)}catch{return null}if(n.length===0)return null;let o=n.length,r=n.slice(0,3).map(i=>YS(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 Dr={cmd:"/resolve",reason:"it walks each one with you \u2014 keep yours, take the portal's, or skip"};async function Ys(e){if(e?.cwd){let n=Qa(e.cwd,e.profileName);if(n)return{kind:"audit-blocked",note:n.note,lead:Dr}}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 against the CURRENT code (its `sources` exist, and the code as it stands shows the surface it claims) before trusting it; never judge it by its `branch` or `commit`. Fold verified ones into the table, flag the rest.","2.6. Anything d360_pending_hints returns under `held` is NOT a proposal. Its cited code has uncommitted changes, so the builder is still writing that surface and has already been asked whether it is done. List each held item at the END of the table as a `waiting` row (Reason: the code behind it is not finished), do NOT propose create/update/retire for it, and do NOT stamp it consumed.","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 |. Leave every hint OPEN \u2014 this run proposes, it does not write articles, so nothing has been acted on yet.","","Do not start writing or updating any article yet; the proposal table is the deliverable."].join(`
340
+ `),display:"/audit"}}oe();import{readProjectConfig as KS,writeProjectConfig as by,autoBudgetUsd as zS,autoModeEnabled as XS,DEFAULT_AUTO_BUDGET_USD as QS}from"document360-engine";function Ke(e){return`$${e%1===0?e.toFixed(0):e.toFixed(2)}`}function Ks(e){return e?"I run the next step myself instead of waiting for you \u2014 writing, reviewing, checking style, saving and going live.":"I suggest the next step and wait for you to run it."}function zs(e){let t=XS(e),n=zS(e),o=e.auto?.budgetUsd===void 0?" (the standard limit \u2014 nothing set for this repo)":"",r=[{tone:"info",text:`Mode: ${t?"auto":"manual"} \u2014 ${Ks(t)}`}];return t?(r.push({tone:"info",text:`Spending limit: ${Ke(n)} a run${o}. I stop and report when it is reached.`}),r.push({tone:"info",text:"Screenshots are never part of an automatic run \u2014 they need your product running."}),r.push({tone:"info",text:"Stop a run at any time: esc. Switch back to manual: shift+tab, or /auto off."})):r.push({tone:"info",text:`Turn it on: /auto on \xB7 or shift+tab. Spending limit if you do: ${Ke(n)} a run.`}),r}function Ja(e,t,n,o=new Date){let r={...t,auto:{...t.auto,enabled:n,decidedAt:o.toISOString()}};return by(r,e),[n?{tone:"ok",text:K("\u2713")+"Auto mode ON \u2014 "+Ks(!0)}:{tone:"ok",text:K("\u2713")+"Manual mode \u2014 "+Ks(!1)},...zs(r)]}function dd(e,t,n){if(!Number.isFinite(n)||n<=0)return null;let o={...t,auto:{...t.auto,enabled:t.auto?.enabled===!0,budgetUsd:n}};return by(o,e),[{tone:"ok",text:K("\u2713")+`Spending limit set to ${Ke(n)} a run.`},...zs(o)]}function pd(e){let t=e.findIndex(r=>r==="--budget"||r.startsWith("--budget="));if(t===-1)return{malformed:!1};let n=e[t].includes("=")?e[t].split("=").slice(1).join("="):e[t+1];if(n===void 0)return{malformed:!0};let o=Number(String(n).replace(/^\$/,"").replace(/,/g,""));return!Number.isFinite(o)||o<=0?{malformed:!0}:{usd:o,malformed:!1}}function hd(e,t){let n=e.findIndex(o=>o==="--budget");return e.filter((o,r)=>!o.startsWith("--")&&!(n!==-1&&r===n+1)&&o!==String(t)).map(o=>o.trim().toLowerCase()).find(o=>o.length>0)}var ud=e=>{for(let t of e)console.log(t.tone==="ok"?Q(t.text):t.tone==="warn"?q(t.text):t.tone==="error"?L(t.text):d(t.text))};async function ky(e,t){let n=t.cwd,o=KS(n);if(!o)return console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=pd(e);if(r.malformed)return console.log(L(`I could not read that spending limit. Give it as an amount, like: /auto --budget 150 (the standard limit is ${Ke(QS)}).`)),{kind:"continue"};let s=hd(e,r.usd);if(r.usd!==void 0&&!s){let i=dd(n,o,r.usd);return i&&ud(i),{kind:"continue"}}if(!s||s==="status")return ud(zs(o)),{kind:"continue"};if(s==="on"||s==="off"){let i=r.usd!==void 0?{...o,auto:{...o.auto,enabled:o.auto?.enabled===!0,budgetUsd:r.usd}}:o;return ud(Ja(n,i,s==="on")),{kind:"continue"}}return console.log(L(`I don't know "${s}". Use: /auto on \xB7 /auto off \xB7 /auto status \xB7 /auto --budget <amount>`)),{kind:"continue"}}oe();import{readProjectConfig as JS}from"document360-engine";function fd(){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(`
341
+ `)}async function $y(e,t){let n=t?.cwd??process.cwd();return JS(n)?{kind:"forward-to-agent",prompt:fd(),display:"/discover"}:(console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"})}oe();import{checkbox as ZS}from"@inquirer/prompts";import{inventoryRepo as eC,readProjectConfig as vy,writeProjectConfig as tC}from"document360-engine";function md(e,t){let n=vy(e);n&&(n.authoritativeSourceFiles=t,tC(n,e))}function Za(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 xy(e,t){let n=t?.cwd??process.cwd();if(!vy(n))return console.log(L("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=eC(n);if(o.length===0)return console.log(d('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(ee("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${d(Za(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>ZS({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${Za(s)})`,value:s.path,checked:s.recommended})),pageSize:20}))}catch{return console.log(d("Cancelled.")),{kind:"continue"}}if(r.length===0)return console.log(d("Nothing selected \u2014 scope unchanged.")),{kind:"continue"};md(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"}}oe();import{confirm as hC}from"@inquirer/prompts";import{applyPull as bd,computeSyncStatus as Ly,compareRemoteSources as fC,planPull as Oy,planImport as mC,applyImport as gC,establishBaselines as yC,rebaselineServerMeta as wC,D360AuthError as bC}from"document360-engine";oe();var Ry=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /push <path>):",paint:L,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /push <path>:",paint:q,mark:"M"},{status:"remote-ahead",header:"Changed on Document360 \u2014 pull with /pull <path> (or just /pull):",paint:ee,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:L,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:L,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint:Te,mark:"X"},{status:"untracked-local",header:"New here \u2014 not on Document360 yet (publish to add them):",paint:d,mark:"?"},{status:"untracked-remote",header:"On Document360 \u2014 not in your local docs yet (run /pull to import them):",paint:d,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:Te,mark:"\xB7"}];function nC(e){return e.path?e.path:`${e.title??"(untitled)"} ${Te(`[${e.articleId}]`)}`}function oC(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 el(e,t){let n=[],o=e.entries.filter(f=>f.link);if(o.length>0){n.push(""),n.push(Qe("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let f of o)n.push(` ${q("~")} ${q(f.path??"")} ${Te(`\u2192 "${f.link.title}"`)}`)}for(let f of Ry){let g=e.entries.filter($=>$.status===f.status&&!(f.status==="untracked-local"&&$.link));if(g.length!==0){n.push(""),n.push(Qe(f.header));for(let $ of g)n.push(` ${f.paint(f.mark)} ${f.paint(nC($))}${$.detail?Te(` (${$.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,c=s===r?Q("\u2713 everything up to date"):[r>0?Q(`\u2713 ${r} up to date`):null,a>0?`${a} to link`:null,...Ry.map(f=>{let g=(e.counts[f.status]??0)-(f.status==="untracked-local"?a:0);return g>0?`${g} ${i[f.status]}`:null})].filter(Boolean).join(Te(" \xB7 ")),l=t!==void 0?` \xB7 synced in ${oC(t)}`:"";return n.push(c+Te(` \xB7 ${s} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${l}`)),n}import{structuredPatch as rC}from"diff";import Sy from"picocolors";var sC=80,jr=400,iC="\x1B[48;2;74;28;28m",aC="\x1B[48;2;24;66;24m",Cy="\x1B[49m",gd=e=>String(e).padStart(5);function Py(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}function Ty(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 Mt(e,t,n,o=sC){let r=A=>{let S=A.replace(/\r\n/g,`
342
342
  `);return S.endsWith(`
343
343
  `)||S===""?S:S+`
344
- `},s=r(e),i=r(t);if(s===i)return null;let a=Math.max(20,n-10),c=YS("a","b",s,i,"","",{context:3}),l=0,f=0,g=[];c.hunks.forEach((A,S)=>{S>0&&g.push(wy.gray(" \u2026"));let C=A.oldStart,x=A.newStart,E=[],I=[],W=()=>{for(let V=0;V<E.length;V++){let B=V<I.length?ky(E[V],I[V]):void 0;f++,g.push(`${XS}${dd(C++)} - ${$y(E[V],a,B)}${by}`)}for(let V=0;V<I.length;V++){let B=V<E.length?ky(E[V],I[V]):void 0;l++,g.push(`${QS}${dd(x++)} + ${$y(I[V],a,B)}${by}`)}E=[],I=[]};for(let V of A.lines){let B=V[0],ae=V.slice(1);B==="-"?E.push(ae):B==="+"?I.push(ae):(W(),g.push(wy.gray(dd(x))+" "+ae.slice(0,a)),C++,x++)}W()});let k=Math.max(1,o),T=g.slice(0,k);return{added:l,removed:f,lines:T,hidden:Math.max(0,g.length-k)}}import{select as Sy}from"@inquirer/prompts";import{applyPull as Cy,computeSyncStatus as eC,isPullWouldBlankError as xy,localArticleTitle as tC,planPull as Ry}from"document360-engine";import{listUnpullable as JS,resolveActiveProfile as ZS}from"document360-engine";function Xa(e,t,n,o){let r=n.filter(a=>a.status==="conflict"&&a.path).map(a=>a.path),s=new Set(o),i=[];try{i=JS(e,ZS(e,t).name).map(a=>a.path).filter(a=>s.has(a))}catch{}return[...new Set([...r,...i])].sort()}function Qa(){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 Ja(){return"Publish your copy over the portal (settles it) \xB7 Skip?"}function vy(){return"(l publish yours \xB7 s skip \u2014 anything else stops, keeping your answers so far)"}function Za(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 pd(e){return`Cannot take the portal copy of ${e} \u2014 Document360 will not return it as markdown. Left as it was.`}oe();var el=e=>e===1?"":"s";async function hd(e,t,n=1){console.log(""),console.log(`${ee("\u25CF")} ${Qe(t.title)} ${Te(`(${t.path})`)}`);for(let i of t.notes)console.log(K(` \u26A0 ${i}`));let o=Lt(t.oldContent,t.newContent,Math.max(40,(process.stdout.columns??80)-1),Ir);if(o){console.log(Te(` \u23BF local \u2192 portal: +${o.added} / -${o.removed} line${el(o.added+o.removed)}`));for(let i of o.lines)console.log(i);o.hidden>0&&console.log(d(` \u2026 +${o.hidden} more diff lines`))}else console.log(d(" Local already matches the portal content \u2014 resolving just advances the sync base."));let r=n>1,s=await e.withPausedInput(()=>Sy({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"?(Cy({cwd:e.cwd,profileName:e.profileName},t),console.log(X(" \u2713 Took the portal copy (local overwritten, sync base advanced).")),"took-portal"):s==="local"?"keep-local":s==="skip"?(console.log(d(" Skipped \u2014 still a conflict.")),"skipped"):s==="local-all"?"keep-local-all":s==="portal-all"?"took-portal-all":"skipped-all"}async function nC(e,t){console.log(""),console.log(`${ee("\u25CF")} ${Qe(tC(e.cwd,t)??t)} ${Te(`(${t})`)}`);for(let o of Qa())console.log(K(` \u26A0 ${o}`));return await e.withPausedInput(()=>Sy({message:Ja(),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(d(" Skipped \u2014 still a conflict.")),"skipped")}async function Py(e,t){let n=Je(t.cwd,t.profileName);if(!n.ok)return console.log(L(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let r=await eC({cwd:t.cwd,profileName:t.profileName}),s=Xa(t.cwd,t.profileName,r.entries,Fo(r.entries).map(c=>c.path));if(o){if(!s.includes(o))return console.log(X(`${o} isn't waiting on a decision \u2014 nothing to resolve.`)),{kind:"continue"};s=[o]}if(s.length===0)return console.log(X("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let i=[],a=[];for(let[c,l]of s.entries()){let f;try{f=await Ry({cwd:t.cwd,profileName:t.profileName,relPath:l})}catch(T){if(!xy(T))throw T;await nC(t,l)==="keep-local"?i.push(l):a.push(l);continue}let g=await hd(t,f,s.length-c);if(g==="keep-local"&&i.push(l),!g.endsWith("-all"))continue;let k=s.slice(c);if(g==="keep-local-all")i.push(...k),console.log(d(` Keeping local for all ${k.length} \u2014 publishing them over the portal.`));else if(g==="took-portal-all"){let T=0;for(let A of k)try{Cy({cwd:t.cwd,profileName:t.profileName},await Ry({cwd:t.cwd,profileName:t.profileName,relPath:A})),T++}catch(S){console.log(L(` \u2717 ${A}: ${S.message}`)),xy(S)&&a.push(A)}console.log(X(` \u2713 Took the portal copy of ${T} article${el(T)} (local overwritten, sync base advanced).`))}else console.log(d(` Skipped all ${k.length} \u2014 still conflict${el(k.length)}.`));break}for(let c of Za(a))console.log(K(`\u26A0 ${c}`));if(i.length>0)return console.log(d(`Publishing ${i.length} kept-local article${el(i.length)} over the portal\u2026`)),await Qt(t,i,0,{allowUnpullable:!0})}catch(r){console.log(L(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function Ey(e,t){let n=Je(t.cwd,t.profileName);if(!n.ok)return console.log(L(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await uC(t),{kind:"continue"};if(o==="--baseline")return await dC(t,e.filter(i=>i!=="--baseline")),{kind:"continue"};if(o==="--compare")return await pC(t),{kind:"continue"};if(o)return console.log(L(`Unknown option: ${o}`)),console.log(d("Usage: /pull pull portal edits + import new portal articles")),console.log(d(" /pull <path> pull one article (or resolve a conflict)")),console.log(d(" /pull --status drift report only (no writes)")),console.log(d(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await hC(t,r),{kind:"continue"};console.log(d("Pulling changes from Document360\u2026"));let s=await md({cwd:t.cwd,profileName:t.profileName});for(let i of gd(s))console.log(i.tone==="ok"?X(i.text):i.tone==="warn"?K(i.text):d(i.text));console.log("")}catch(r){r instanceof cC?console.log(L(r.message)):console.log(L(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function md(e){let t=await Ty({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 Ay({cwd:e.cwd,profileName:e.profileName,relPath:o.path});fd({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 sC({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});iC({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 tl=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Uo=e=>e===1?"":"s";function gd(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: ${tl(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${Uo(e.imported.length)}: ${tl(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). (${tl(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${Uo(e.failed.length)} failed: ${tl(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 uC(e){console.log(d("Checking Document360 for drift\u2026"));let t=Date.now(),n=await Ty({cwd:e.cwd,profileName:e.profileName});for(let o of za(n,Date.now()-t))console.log(o);console.log("")}async function dC(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(d(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await aC({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await lC({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(X("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(X(`\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(X(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(K(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(d(` - ${s.path} (${s.reason})`))}}async function pC(e){console.log(d("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await rC({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${Qe(String(t.legacyCount))} \xB7 Manifest: ${Qe(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(X("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(L(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(K(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(K(` ${t.onlyInManifest.length} only in the manifest: ${t.onlyInManifest.slice(0,5).join(", ")}`)),console.log(d(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function hC(e,t){let n=t.replace(/\\/g,"/"),o=await Ay({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await hd(e,o)==="keep-local"&&(console.log(d(`Publishing ${o.path} over the portal\u2026`)),await Qt(e,[o.path]));return}console.log(""),console.log(`${ee("\u25CF")} ${Qe(o.title)} ${Te(`(${o.path})`)}`);for(let i of o.notes)console.log(K(` \u26A0 ${i}`));let r=Lt(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1),Ir);if(!r){console.log(d(" Local file already matches the remote content \u2014 advancing the sync base only.")),fd({cwd:e.cwd,profileName:e.profileName},o);return}console.log(Te(` \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(d(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>oC({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(d(" Skipped."));return}fd({cwd:e.cwd,profileName:e.profileName},o),console.log(X(` \u2713 Pulled ${o.path} (sync base advanced).`))}oe();import{statSync as RC}from"node:fs";import{resolve as SC}from"node:path";import{estimateBulkCost as CC,planPartitions as PC,readProjectConfig as TC,resolveModelForOperation as AC,runPartitioned as EC,trackedArticlePaths as NC}from"document360-engine";function zn(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 Ny(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 nl(e,t){let n=t-e;return n>=300&&n>=t*.2}function Ot(e,t,n,o=Date.now(),r){let s=t.reduce((a,c)=>a+(c.inputTokens??0),0),i=t.reduce((a,c)=>a+(c.cacheReadTokens??0),0);return{seconds:Math.max(0,Math.round((o-e)/1e3)),outputTokens:t.reduce((a,c)=>a+c.outputTokens,0),inputTokens:s,...s>0?{cachedPct:Math.round(i/s*100)}:{},...r!==void 0?{activeSeconds:r}:{},costUsd:n}}function ol(e){return e.activeSeconds!==void 0&&nl(e.activeSeconds,e.seconds)?`${yd(e.seconds)} elapsed \xB7 ${yd(e.activeSeconds)} working`:yd(e.seconds)}var Dy=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:`${e}`,yd=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 ln(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 ${ol(e)}, ${Dy(e.inputTokens)}\u2192${Dy(e.outputTokens)} tokens${t}${n})`}import xe from"picocolors";import $d from"wrap-ansi";import vd from"string-width";oe();import Xn from"picocolors";import sl from"wrap-ansi";import rl from"string-width";var Wo=[{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|--related <path>|[<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; --related <path>: also save that article's related articles that were never saved; --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 | sweep [skip] | 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, hold every article to them and apply the free text swaps (bare: pick from a list); keep: settle on the rules you have today; sweep: how much of your knowledge base still needs reading against a guide you switched to (skip stops me raising it); 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] [--baselined]",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; --baselined shows the issues that were already in your articles when you chose this style guide, which never block publishing",group:"docs"},{name:"review",usage:"/review [<category|path> | --all | --blocked | --stale] [--fix]",desc:"Independent senior-editor review: style guide, terminology/voice, grammar/clarity, page structure, improvement suggestions. A whole-knowledge-base run also gets one editor on the SHAPE of the docs \u2014 reading order, categories that have grown too big, articles filed in the wrong place, names that no longer fit. 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:"restructure",usage:"/restructure [<what to change>]",desc:"Reshape the knowledge base: move an article to a different category, split one that has grown too big, merge two, rename one, or nest one inside another. A category left empty by a merge is hidden from readers, never deleted. Bare: reviews how the docs are organised and reports what should change, without touching anything; the changes reach Document360 on the 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>] [--yes]",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:"untrack",usage:"/untrack [<path>] [--undo] [--list] [--yes]",desc:"Disown a page that was imported from Document360 but is not one of your docs. /catch-up and /pull import every article they find in your categories; this records the ones you do not want, so they are never imported again \u2014 and the decision travels with the repo, so a teammate\u2019s clone inherits it. Nothing on Document360 changes and nothing is deleted: the markdown moves to .d360-writer/declined/. Bare: lists what this repo has declined. --undo puts one back",group:"publish"},{name:"reuse",usage:'/reuse [pull | add <variable|snippet> <name> "<value>" | audit [<category>] [--create <n\u2026>]]',desc:"The terms, values and blocks your project already maintains on Document360, so your articles reference them instead of repeating them. A variable holds a value like your product name in one place \u2014 change it there and every article changes; type it out by hand and /lint flags it. A snippet does the same for a whole block, and the writer references yours by name instead of writing its own version. A term is defined once and every article is checked for explaining it the first time it appears. Reading is free; pull refreshes from Document360, add creates a new one there, and audit reads every article to work out what belongs in one place",group:"docs"},{name:"eval",usage:"/eval [<category>] [--all]",desc:"How does your whole knowledge base score? Reads every article and reports what no single-article check can see: internal links written as portal URLs, links pointing at headings that no longer exist, link text that names a different article, the command summary line appearing in several shapes, two names for the same section, and how many style findings were accepted as exempt when you chose your style guide. Costs nothing and calls nothing",group:"docs"},{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] [--include-unfinished]",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. A note whose code your builder has not committed is left for later, and they are asked whether it is done; --include-unfinished writes those pages anyway. 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:"auto",usage:"/auto [on|off|status] [--budget <amount>]",desc:"Auto or manual: in auto I run the next step myself \u2014 write, review, check style, save, go live \u2014 instead of waiting for you (shift+tab cycles it; esc stops a run)",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"}],jy={"/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","/auto":"choose whether I run the next step myself or wait for you","/style-guide":"choose the writing rules your docs are held to","/lint":"check the docs against those rules (costs nothing)"};function Iy(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(jy[n])return jy[n];let o=Wo.find(r=>r.name===t);return o?o.desc:""}function Ly(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return Wo.filter(n=>n.name.startsWith(t))}function Oy(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 fC=new RegExp(`^\\s*/(?:${Wo.map(e=>e.name).join("|")})(?:\\s|$)`),_y=e=>fC.test(e),My=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Fy=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),Uy=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function mC(e){let t=e.replace(/\r/g,"").split(`
345
- `),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(My(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&Fy(t[o+1])){let a=Uy(r);o+=2;let c=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)c.push(Uy(t[o++]));n.push({kind:"table",header:a,rows:c});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 c=t[o++];a.push({ordered:/^\s*\d+\.\s+/.test(c),text:c.replace(/^\s*([-*]|\d+\.)\s+/,"")})}n.push({kind:"list",items:a});continue}if(r.trim()===""){o++;continue}if(_y(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])&&!_y(t[o])&&!My(t[o])&&!(t[o].includes("|")&&o+1<t.length&&Fy(t[o+1]));)i.push(t[o++]);n.push({kind:"para",text:i.join(" ")})}return n}function wd(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?Xn.bold(t.slice(2,-2)):t.startsWith("`")?ee(t.slice(1,-1)):Xn.italic(t.slice(1,-1)))}var gC=(e,t)=>e+" ".repeat(Math.max(0,t-rl(e)));function Ys(e,t,n,o={}){return Wy(e,t,n,o)}function Wy(e,t,n,o={}){let r=e.length,s=C=>Math.max(0,...C.split(`
346
- `).map(x=>rl(x))),i=e.map((C,x)=>Math.max(rl(C),...t.map(E=>s(E[x]??"")))),a=Math.max(24,n),c=3*r+1,l=[...i],f=()=>l.reduce((C,x)=>C+x,0)+c,g=0;for(;f()>a&&g++<1e4;){let C=-1,x=6;for(let E=0;E<r;E++)l[E]>x&&(x=l[E],C=E);if(C===-1)break;l[C]-=1}let k=(C,x,E)=>Xn.gray(C+l.map(I=>"\u2500".repeat(I+2)).join(x)+E),T=Xn.gray("\u2502"),A=(C,x)=>{let E=l.map((B,ae)=>{let me=C[ae]??"",Re=x?Xn.bold(me):o.plain?me:wd(me);return me.includes(`
344
+ `},s=r(e),i=r(t);if(s===i)return null;let a=Math.max(20,n-10),c=rC("a","b",s,i,"","",{context:3}),l=0,f=0,g=[];c.hunks.forEach((A,S)=>{S>0&&g.push(Sy.gray(" \u2026"));let C=A.oldStart,x=A.newStart,E=[],j=[],W=()=>{for(let Y=0;Y<E.length;Y++){let B=Y<j.length?Py(E[Y],j[Y]):void 0;f++,g.push(`${iC}${gd(C++)} - ${Ty(E[Y],a,B)}${Cy}`)}for(let Y=0;Y<j.length;Y++){let B=Y<E.length?Py(E[Y],j[Y]):void 0;l++,g.push(`${aC}${gd(x++)} + ${Ty(j[Y],a,B)}${Cy}`)}E=[],j=[]};for(let Y of A.lines){let B=Y[0],ue=Y.slice(1);B==="-"?E.push(ue):B==="+"?j.push(ue):(W(),g.push(Sy.gray(gd(x))+" "+ue.slice(0,a)),C++,x++)}W()});let $=Math.max(1,o),T=g.slice(0,$);return{added:l,removed:f,lines:T,hidden:Math.max(0,g.length-$)}}import{select as Dy}from"@inquirer/prompts";import{applyPull as jy,computeSyncStatus as uC,isPullWouldBlankError as Ey,localArticleTitle as dC,planPull as Ny}from"document360-engine";import{listUnpullable as lC,resolveActiveProfile as cC}from"document360-engine";function tl(e,t,n,o){let r=n.filter(a=>a.status==="conflict"&&a.path).map(a=>a.path),s=new Set(o),i=[];try{i=lC(e,cC(e,t).name).map(a=>a.path).filter(a=>s.has(a))}catch{}return[...new Set([...r,...i])].sort()}function nl(){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 ol(){return"Publish your copy over the portal (settles it) \xB7 Skip?"}function Ay(){return"(l publish yours \xB7 s skip \u2014 anything else stops, keeping your answers so far)"}function rl(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 yd(e){return`Cannot take the portal copy of ${e} \u2014 Document360 will not return it as markdown. Left as it was.`}oe();var sl=e=>e===1?"":"s";async function wd(e,t,n=1){console.log(""),console.log(`${ee("\u25CF")} ${Qe(t.title)} ${Te(`(${t.path})`)}`);for(let i of t.notes)console.log(q(` \u26A0 ${i}`));let o=Mt(t.oldContent,t.newContent,Math.max(40,(process.stdout.columns??80)-1),jr);if(o){console.log(Te(` \u23BF local \u2192 portal: +${o.added} / -${o.removed} line${sl(o.added+o.removed)}`));for(let i of o.lines)console.log(i);o.hidden>0&&console.log(d(` \u2026 +${o.hidden} more diff lines`))}else console.log(d(" Local already matches the portal content \u2014 resolving just advances the sync base."));let r=n>1,s=await e.withPausedInput(()=>Dy({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"?(jy({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(d(" Skipped \u2014 still a conflict.")),"skipped"):s==="local-all"?"keep-local-all":s==="portal-all"?"took-portal-all":"skipped-all"}async function pC(e,t){console.log(""),console.log(`${ee("\u25CF")} ${Qe(dC(e.cwd,t)??t)} ${Te(`(${t})`)}`);for(let o of nl())console.log(q(` \u26A0 ${o}`));return await e.withPausedInput(()=>Dy({message:ol(),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(d(" Skipped \u2014 still a conflict.")),"skipped")}async function Iy(e,t){let n=Je(t.cwd,t.profileName);if(!n.ok)return console.log(L(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let r=await uC({cwd:t.cwd,profileName:t.profileName}),s=tl(t.cwd,t.profileName,r.entries,Uo(r.entries).map(c=>c.path));if(o){if(!s.includes(o))return console.log(Q(`${o} isn't waiting on a decision \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[c,l]of s.entries()){let f;try{f=await Ny({cwd:t.cwd,profileName:t.profileName,relPath:l})}catch(T){if(!Ey(T))throw T;await pC(t,l)==="keep-local"?i.push(l):a.push(l);continue}let g=await wd(t,f,s.length-c);if(g==="keep-local"&&i.push(l),!g.endsWith("-all"))continue;let $=s.slice(c);if(g==="keep-local-all")i.push(...$),console.log(d(` Keeping local for all ${$.length} \u2014 publishing them over the portal.`));else if(g==="took-portal-all"){let T=0;for(let A of $)try{jy({cwd:t.cwd,profileName:t.profileName},await Ny({cwd:t.cwd,profileName:t.profileName,relPath:A})),T++}catch(S){console.log(L(` \u2717 ${A}: ${S.message}`)),Ey(S)&&a.push(A)}console.log(Q(` \u2713 Took the portal copy of ${T} article${sl(T)} (local overwritten, sync base advanced).`))}else console.log(d(` Skipped all ${$.length} \u2014 still conflict${sl($.length)}.`));break}for(let c of rl(a))console.log(q(`\u26A0 ${c}`));if(i.length>0)return console.log(d(`Publishing ${i.length} kept-local article${sl(i.length)} over the portal\u2026`)),await Jt(t,i,0,{allowUnpullable:!0})}catch(r){console.log(L(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function _y(e,t){let n=Je(t.cwd,t.profileName);if(!n.ok)return console.log(L(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await kC(t),{kind:"continue"};if(o==="--baseline")return await $C(t,e.filter(i=>i!=="--baseline")),{kind:"continue"};if(o==="--compare")return await vC(t),{kind:"continue"};if(o)return console.log(L(`Unknown option: ${o}`)),console.log(d("Usage: /pull pull portal edits + import new portal articles")),console.log(d(" /pull <path> pull one article (or resolve a conflict)")),console.log(d(" /pull --status drift report only (no writes)")),console.log(d(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await xC(t,r),{kind:"continue"};console.log(d("Pulling changes from Document360\u2026"));let s=await kd({cwd:t.cwd,profileName:t.profileName});for(let i of $d(s))console.log(i.tone==="ok"?Q(i.text):i.tone==="warn"?q(i.text):d(i.text));console.log("")}catch(r){r instanceof bC?console.log(L(r.message)):console.log(L(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function kd(e){let t=await Ly({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 Oy({cwd:e.cwd,profileName:e.profileName,relPath:o.path});bd({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 mC({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId,...o.remoteCategory?{categoryPath:o.remoteCategory.path}:{}});gC({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 il=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Wo=e=>e===1?"":"s";function $d(e){let t=[];if(e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${Wo(e.pulled.length)} into local: ${il(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${Wo(e.imported.length)}: ${il(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${Wo(e.toPublish)} changed locally \u2014 /push saves them to Document360.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${Wo(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). (${il(e.conflicts)})`}),e.failed.length){t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${Wo(e.failed.length)} could not be imported.`});let n=new Map;for(let o of e.failed){let r=o.error.replace(/^"[^"]*" could not be imported: /,"");n.set(r,[...n.get(r)??[],o.ref])}for(let[o,r]of n)t.push({tone:"warn",text:` ${o}`}),t.push({tone:"warn",text:` ${il(r)}`})}return t.length===0&&t.push({tone:"ok",text:"\u2713 Already in sync with Document360 \u2014 nothing to pull."}),t}async function kC(e){console.log(d("Checking Document360 for drift\u2026"));let t=Date.now(),n=await Ly({cwd:e.cwd,profileName:e.profileName});for(let o of el(n,Date.now()-t))console.log(o);console.log("")}async function $C(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(d(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await yC({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await wC({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(q(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(d(` - ${s.path} (${s.reason})`))}}async function vC(e){console.log(d("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await fC({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${Qe(String(t.legacyCount))} \xB7 Manifest: ${Qe(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(L(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(q(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(q(` ${t.onlyInManifest.length} only in the manifest: ${t.onlyInManifest.slice(0,5).join(", ")}`)),console.log(d(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function xC(e,t){let n=t.replace(/\\/g,"/"),o=await Oy({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await wd(e,o)==="keep-local"&&(console.log(d(`Publishing ${o.path} over the portal\u2026`)),await Jt(e,[o.path]));return}console.log(""),console.log(`${ee("\u25CF")} ${Qe(o.title)} ${Te(`(${o.path})`)}`);for(let i of o.notes)console.log(q(` \u26A0 ${i}`));let r=Mt(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1),jr);if(!r){console.log(d(" Local file already matches the remote content \u2014 advancing the sync base only.")),bd({cwd:e.cwd,profileName:e.profileName},o);return}console.log(Te(` \u23BF Added ${r.added} line${Wo(r.added)}, removed ${r.removed} line${Wo(r.removed)}`));for(let i of r.lines)console.log(i);if(r.hidden>0&&console.log(d(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>hC({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(d(" Skipped."));return}bd({cwd:e.cwd,profileName:e.profileName},o),console.log(Q(` \u2713 Pulled ${o.path} (sync base advanced).`))}oe();import{statSync as IC}from"node:fs";import{resolve as LC}from"node:path";import{estimateBulkCost as OC,planPartitions as _C,readProjectConfig as MC,resolveModelForOperation as FC,runPartitioned as UC,trackedArticlePaths as WC}from"document360-engine";function Xn(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 My(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 Ir=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 al(e,t){let n=t-e;return n>=300&&n>=t*.2}function Ft(e,t,n,o=Date.now(),r){let s=t.reduce((a,c)=>a+(c.inputTokens??0),0),i=t.reduce((a,c)=>a+(c.cacheReadTokens??0),0);return{seconds:Math.max(0,Math.round((o-e)/1e3)),outputTokens:t.reduce((a,c)=>a+c.outputTokens,0),inputTokens:s,...s>0?{cachedPct:Math.round(i/s*100)}:{},...r!==void 0?{activeSeconds:r}:{},costUsd:n}}function ll(e){return e.activeSeconds!==void 0&&al(e.activeSeconds,e.seconds)?`${vd(e.seconds)} elapsed \xB7 ${vd(e.activeSeconds)} working`:vd(e.seconds)}var Fy=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:`${e}`,vd=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 cn(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 ${ll(e)}, ${Fy(e.inputTokens)}\u2192${Fy(e.outputTokens)} tokens${t}${n})`}import xe from"picocolors";import Cd from"wrap-ansi";import Pd from"string-width";oe();import Qn from"picocolors";import ul from"wrap-ansi";import cl from"string-width";var Bo=[{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|--related <path>|[<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; --related <path>: also save that article's related articles that were never saved; --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 | sweep [skip] | 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, hold every article to them and apply the free text swaps (bare: pick from a list); keep: settle on the rules you have today; sweep: how much of your knowledge base still needs reading against a guide you switched to (skip stops me raising it); 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] [--baselined]",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; --baselined shows the issues that were already in your articles when you chose this style guide, which never block publishing",group:"docs"},{name:"review",usage:"/review [<category|path> | --all | --blocked | --stale] [--fix]",desc:"Independent senior-editor review: style guide, terminology/voice, grammar/clarity, page structure, improvement suggestions. A whole-knowledge-base run also gets one editor on the SHAPE of the docs \u2014 reading order, categories that have grown too big, articles filed in the wrong place, names that no longer fit. 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:"restructure",usage:"/restructure [<what to change>]",desc:"Reshape the knowledge base: move an article to a different category, split one that has grown too big, merge two, rename one, or nest one inside another. A category left empty by a merge is hidden from readers, never deleted. Bare: reviews how the docs are organised and reports what should change, without touching anything; the changes reach Document360 on the 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>] [--yes]",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:"untrack",usage:"/untrack [<path>] [--undo] [--list] [--yes]",desc:"Disown a page that was imported from Document360 but is not one of your docs. /catch-up and /pull import every article they find in your categories; this records the ones you do not want, so they are never imported again \u2014 and the decision travels with the repo, so a teammate\u2019s clone inherits it. Nothing on Document360 changes and nothing is deleted: the markdown moves to .d360-writer/declined/. Bare: lists what this repo has declined. --undo puts one back",group:"publish"},{name:"reuse",usage:'/reuse [pull | add <variable|snippet> <name> "<value>" | audit [<category>] [--create <n\u2026>]]',desc:"The terms, values and blocks your project already maintains on Document360, so your articles reference them instead of repeating them. A variable holds a value like your product name in one place \u2014 change it there and every article changes; type it out by hand and /lint flags it. A snippet does the same for a whole block, and the writer references yours by name instead of writing its own version. A term is defined once and every article is checked for explaining it the first time it appears. Reading is free; pull refreshes from Document360, add creates a new one there, and audit reads every article to work out what belongs in one place",group:"docs"},{name:"eval",usage:"/eval [<category>] [--all]",desc:"How does your whole knowledge base score? Reads every article and reports what no single-article check can see: internal links written as portal URLs, links pointing at headings that no longer exist, link text that names a different article, the command summary line appearing in several shapes, two names for the same section, and how many style findings were accepted as exempt when you chose your style guide. Costs nothing and calls nothing",group:"docs"},{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] [--include-unfinished]",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. A note whose code your builder has not committed is left for later, and they are asked whether it is done; --include-unfinished writes those pages anyway. 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:"auto",usage:"/auto [on|off|status] [--budget <amount>]",desc:"Auto or manual: in auto I run the next step myself \u2014 write, review, check style, save, go live \u2014 instead of waiting for you (shift+tab cycles it; esc stops a run)",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",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"}],Uy={"/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","/auto":"choose whether I run the next step myself or wait for you","/style-guide":"choose the writing rules your docs are held to","/lint":"check the docs against those rules (costs nothing)"};function Wy(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(Uy[n])return Uy[n];let o=Bo.find(r=>r.name===t);return o?o.desc:""}function By(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return Bo.filter(n=>n.name.startsWith(t))}function Hy(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 RC=new RegExp(`^\\s*/(?:${Bo.map(e=>e.name).join("|")})(?:\\s|$)`),Gy=e=>RC.test(e),qy=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Vy=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),Yy=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function SC(e){let t=e.replace(/\r/g,"").split(`
345
+ `),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(qy(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&Vy(t[o+1])){let a=Yy(r);o+=2;let c=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)c.push(Yy(t[o++]));n.push({kind:"table",header:a,rows:c});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 c=t[o++];a.push({ordered:/^\s*\d+\.\s+/.test(c),text:c.replace(/^\s*([-*]|\d+\.)\s+/,"")})}n.push({kind:"list",items:a});continue}if(r.trim()===""){o++;continue}if(Gy(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])&&!Gy(t[o])&&!qy(t[o])&&!(t[o].includes("|")&&o+1<t.length&&Vy(t[o+1]));)i.push(t[o++]);n.push({kind:"para",text:i.join(" ")})}return n}function xd(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?Qn.bold(t.slice(2,-2)):t.startsWith("`")?ee(t.slice(1,-1)):Qn.italic(t.slice(1,-1)))}var CC=(e,t)=>e+" ".repeat(Math.max(0,t-cl(e)));function Xs(e,t,n,o={}){return Ky(e,t,n,o)}function Ky(e,t,n,o={}){let r=e.length,s=C=>Math.max(0,...C.split(`
346
+ `).map(x=>cl(x))),i=e.map((C,x)=>Math.max(cl(C),...t.map(E=>s(E[x]??"")))),a=Math.max(24,n),c=3*r+1,l=[...i],f=()=>l.reduce((C,x)=>C+x,0)+c,g=0;for(;f()>a&&g++<1e4;){let C=-1,x=6;for(let E=0;E<r;E++)l[E]>x&&(x=l[E],C=E);if(C===-1)break;l[C]-=1}let $=(C,x,E)=>Qn.gray(C+l.map(j=>"\u2500".repeat(j+2)).join(x)+E),T=Qn.gray("\u2502"),A=(C,x)=>{let E=l.map((B,ue)=>{let fe=C[ue]??"",Re=x?Qn.bold(fe):o.plain?fe:xd(fe);return fe.includes(`
347
347
  `)?Re.split(`
348
- `).flatMap(Ie=>sl(Ie,B,{hard:!0}).split(`
349
- `)):sl(Re,B,{hard:!0}).split(`
350
- `)}),I=Math.max(...E.map(B=>B.length)),W=[],V=(B,ae,me)=>o.align?.[me]==="right"?" ".repeat(Math.max(0,ae-rl(B)))+B:gC(B,ae);for(let B=0;B<I;B++)W.push(l.map((ae,me)=>`${T} ${V(E[me][B]??"",ae,me)} `).join("")+T);return W.join(`
351
- `)},S=[k("\u250C","\u252C","\u2510"),A(e,!0)];return S.push(t.length===0?k("\u2514","\u2534","\u2518"):k("\u251C","\u253C","\u2524")),t.forEach((C,x)=>{S.push(A(C,!1)),S.push(x===t.length-1?k("\u2514","\u2534","\u2518"):k("\u251C","\u253C","\u2524"))}),S.join(`
352
- `)}function yC(e,t){switch(e.kind){case"heading":return Xn.bold(e.text);case"hr":return Xn.gray("\u2500".repeat(t));case"para":return sl(wd(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]=sl(wd(o.text),Math.max(10,t-s.length)).split(`
348
+ `).flatMap(Ie=>ul(Ie,B,{hard:!0}).split(`
349
+ `)):ul(Re,B,{hard:!0}).split(`
350
+ `)}),j=Math.max(...E.map(B=>B.length)),W=[],Y=(B,ue,fe)=>o.align?.[fe]==="right"?" ".repeat(Math.max(0,ue-cl(B)))+B:CC(B,ue);for(let B=0;B<j;B++)W.push(l.map((ue,fe)=>`${T} ${Y(E[fe][B]??"",ue,fe)} `).join("")+T);return W.join(`
351
+ `)},S=[$("\u250C","\u252C","\u2510"),A(e,!0)];return S.push(t.length===0?$("\u2514","\u2534","\u2518"):$("\u251C","\u253C","\u2524")),t.forEach((C,x)=>{S.push(A(C,!1)),S.push(x===t.length-1?$("\u2514","\u2534","\u2518"):$("\u251C","\u253C","\u2524"))}),S.join(`
352
+ `)}function PC(e,t){switch(e.kind){case"heading":return Qn.bold(e.text);case"hr":return Qn.gray("\u2500".repeat(t));case"para":return ul(xd(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]=ul(xd(o.text),Math.max(10,t-s.length)).split(`
353
353
  `);return` ${r} ${i}`+a.map(c=>`
354
354
  ${s}${c}`).join("")}).join(`
355
- `)}case"code":return e.lines.map(n=>Xn.gray(" "+n)).join(`
356
- `);case"table":return Wy(e.header,e.rows,t)}}function bd(e,t){let n=Math.max(20,t);return mC(e).map(o=>yC(o,n)).join(`
355
+ `)}case"code":return e.lines.map(n=>Qn.gray(" "+n)).join(`
356
+ `);case"table":return Ky(e.header,e.rows,t)}}function Rd(e,t){let n=Math.max(20,t);return SC(e).map(o=>PC(o,n)).join(`
357
357
 
358
- `)}oe();import wC from"picocolors";var bC=[127,86,217],kC=[22,38,43],By={T:bC,E:kC},zs=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],kd=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,$C=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function Hy(){if(!wC.isColorSupported)return[];let e=zs[0].length,t=[];for(let n=0;n<zs.length;n+=2){let o="";for(let r=0;r<e;r++){let s=By[zs[n][r]],i=n+1<zs.length?By[zs[n+1][r]]:void 0;s&&i?o+=`${kd(s)}${$C(i)}\u2580\x1B[49m\x1B[39m`:s?o+=`${kd(s)}\u2580\x1B[39m`:i?o+=`${kd(i)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function Xs(e){let t=n=>n.toFixed(1).endsWith(".0")?n.toFixed(0):n.toFixed(1);return e<1e3?String(e):e<1e6?`${t(e/1e3)}k`:`${t(e/1e6)}M`}function Pn(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function qy(e,t,n){let o=e>0&&e<=n?e:t;return Math.max(0,Math.floor((n-o)/1e3))}function kt(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function _r(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var Or=(e,t)=>` ${e.padEnd(13)}${t}`;function vC(e,t){let n=[Ts("\u270E document360-writer")+xe.gray(` v${e.version} \xB7 engine v${e.engineVersion}${e.captureVersion?` \xB7 capture v${e.captureVersion}`:""}`),xe.gray(" Reads your code, writes your docs."),"",Or("Claude:",`${e.claude}${xe.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),Or("Document360:",e.configured?e.loggedOut?xe.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?xe.gray(` (${e.sessionHint})`):""}`:xe.yellow("not set up \u2014 run /init")),Or("Profile:",e.configured?`${e.profile}${xe.gray(` (${e.apiUrl})`)}${e.prod?xe.bold(xe.yellow(" \u26A0 PRODUCTION")):""}`:xe.gray("\u2014 (run /init)")),Or("Project:",e.project),Or("Mode:",xe.gray(e.mode)),Or("cwd:",xe.gray(e.cwd))],o=Hy();if(o.length===0)return n.join(`
359
- `);let r=2,s=3,i=vd(o[0]);if(!(t>=r+i+s+Math.max(...n.map(f=>vd(f)))))return[...o.map(f=>" "+f),...n].join(`
358
+ `)}oe();import TC from"picocolors";var AC=[127,86,217],EC=[22,38,43],zy={T:AC,E:EC},Qs=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],Sd=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,NC=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function Xy(){if(!TC.isColorSupported)return[];let e=Qs[0].length,t=[];for(let n=0;n<Qs.length;n+=2){let o="";for(let r=0;r<e;r++){let s=zy[Qs[n][r]],i=n+1<Qs.length?zy[Qs[n+1][r]]:void 0;s&&i?o+=`${Sd(s)}${NC(i)}\u2580\x1B[49m\x1B[39m`:s?o+=`${Sd(s)}\u2580\x1B[39m`:i?o+=`${Sd(i)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function Js(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 An(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function Jy(e,t,n){let o=e>0&&e<=n?e:t;return Math.max(0,Math.floor((n-o)/1e3))}function $t(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function Or(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 DC(e,t){let n=[Es("\u270E document360-writer")+xe.gray(` v${e.version} \xB7 engine v${e.engineVersion}${e.captureVersion?` \xB7 capture v${e.captureVersion}`:""}`),xe.gray(" Reads your code, writes your docs."),"",Lr("Claude:",`${e.claude}${xe.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),Lr("Document360:",e.configured?e.loggedOut?xe.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?xe.gray(` (${e.sessionHint})`):""}`:xe.yellow("not set up \u2014 run /init")),Lr("Profile:",e.configured?`${e.profile}${xe.gray(` (${e.apiUrl})`)}${e.prod?xe.bold(xe.yellow(" \u26A0 PRODUCTION")):""}`:xe.gray("\u2014 (run /init)")),Lr("Project:",e.project),Lr("Mode:",xe.gray(e.mode)),Lr("cwd:",xe.gray(e.cwd))],o=Xy();if(o.length===0)return n.join(`
359
+ `);let r=2,s=3,i=Pd(o[0]);if(!(t>=r+i+s+Math.max(...n.map(f=>Pd(f)))))return[...o.map(f=>" "+f),...n].join(`
360
360
  `);let c=Math.max(0,Math.floor((n.length-o.length)/2)),l=[];for(let f=0;f<Math.max(o.length+c,n.length);f++){let g=o[f-c]??" ".repeat(i);l.push((" ".repeat(r)+g+" ".repeat(s)+(n[f]??"")).trimEnd())}return l.join(`
361
- `)}var xC={error:xe.red,warn:xe.yellow,ok:xe.green,info:xe.gray},Gy=9;function xd(e){return e.length>=Gy?`${e} `:e.padEnd(Gy)}function il(e){return e.replace(/^(\s*• |)([^\x00-\x7F][\u{1F000}-\u{1FAFF}‍️]*) (?=\S)/gmu,"$1$2 ")}function Rd(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return vC(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(`
362
- `).flatMap(l=>$d(l,s,{hard:!0}).split(`
361
+ `)}var jC={error:xe.red,warn:xe.yellow,ok:xe.green,info:xe.gray},Qy=9;function Td(e){return e.length>=Qy?`${e} `:e.padEnd(Qy)}function dl(e){return e.replace(/^(\s*• |)([^\x00-\x7F][\u{1F000}-\u{1FAFF}‍️]*) (?=\S)/gmu,"$1$2 ")}function Ad(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return DC(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(`
362
+ `).flatMap(l=>Cd(l,s,{hard:!0}).split(`
363
363
  `)),c=Math.max(0,a.length-i);return c>0&&(a=[...a.slice(0,i),xe.dim(`\u2026 +${c} more lines`)]),`
364
- `+a.map((l,f)=>o+(f===0?ee(" \u276F "):" ")+l+" ".repeat(Math.max(0,s-vd(l))+1)+r).join(`
364
+ `+a.map((l,f)=>o+(f===0?ee(" \u276F "):" ")+l+" ".repeat(Math.max(0,s-Pd(l))+1)+r).join(`
365
365
  `)}case"assistant":return`
366
- `+bd(e.text,n);case"tool":{let o=e.arg!==null?xe.gray(`${e.sep}(${e.arg})`):"";return`
367
- `+$d(xe.gray("\u25CF ")+e.title+o,n)}case"doc":{let o=[e.category,e.note].filter(s=>!!s).map(s=>xe.gray(` \xB7 ${s}`)),r=e.loud?xe.gray(" \xB7 ")+xe.bold(xe.yellow(e.loud)):"";return`
368
- `+$d(xe.green("\u25CF ")+ee(xe.bold(xd(e.verb)))+xe.bold(e.title)+o.join("")+r,n)}case"tool-result":{let o=e.isError?xe.red:xe.gray,r=e.lines.map((s,i)=>o((i===0?" \u23BF ":" ")+s));return e.hidden>0&&r.push(xe.dim(` \u2026 +${e.hidden} lines`)),r.join(`
366
+ `+Rd(e.text,n);case"tool":{let o=e.arg!==null?xe.gray(`${e.sep}(${e.arg})`):"";return`
367
+ `+Cd(xe.gray("\u25CF ")+e.title+o,n)}case"doc":{let o=[e.category,e.note].filter(s=>!!s).map(s=>xe.gray(` \xB7 ${s}`)),r=e.loud?xe.gray(" \xB7 ")+xe.bold(xe.yellow(e.loud)):"";return`
368
+ `+Cd(xe.green("\u25CF ")+ee(xe.bold(Td(e.verb)))+xe.bold(e.title)+o.join("")+r,n)}case"tool-result":{let o=e.isError?xe.red:xe.gray,r=e.lines.map((s,i)=>o((i===0?" \u23BF ":" ")+s));return e.hidden>0&&r.push(xe.dim(` \u2026 +${e.hidden} lines`)),r.join(`
369
369
  `)}case"diff":{let o=i=>i===1?"":"s",s=[xe.gray(` \u23BF Added ${e.added} line${o(e.added)}, removed ${e.removed} line${o(e.removed)}`),...e.lines];return e.hidden>0&&s.push(xe.dim(` \u2026 +${e.hidden} more diff lines`)),s.join(`
370
- `)}case"link":return e.lines.map(o=>ee(Es(` \u2B95 ${o}`))).join(`
370
+ `)}case"link":return e.lines.map(o=>ee(Ds(` \u2B95 ${o}`))).join(`
371
371
  `);case"preview":return`
372
- `+Ts(`\u25A3 Preview \u2014 ${e.name}`)+`
372
+ `+Es(`\u25A3 Preview \u2014 ${e.name}`)+`
373
373
 
374
- `+bd(e.text,n);case"note":return`
375
- `+xC[e.tone](Es(il(e.text)));case"block":return`
376
- `+e.text;case"done":{let o=e.inTokens&&e.inTokens>0?` \xB7 ${Xs(e.inTokens)} in${e.cachedPct!=null?` (${e.cachedPct}% cached)`:""}`:"",r=e.activeSeconds!==void 0&&nl(e.activeSeconds,e.seconds)?`${Pn(e.seconds)} elapsed \xB7 ${Pn(e.activeSeconds)} working`:Pn(e.seconds),s=e.costUsd>0?` \xB7 this turn ${kt(e.costUsd)}`+(e.sessionCostUsd!==void 0&&e.sessionCostUsd>e.costUsd?` \xB7 session ${kt(e.sessionCostUsd)}`:""):"";return`
377
- `+(e.ok?xe.magenta("\u2736 "):xe.red("\u2736 "))+xe.gray(`Cooked for ${r} \xB7 ${Xs(e.tokens)} tokens out${o}${s}`)}}}function Vy(e,t,n){let o=e.map(i=>Rd(i,t));if(n===void 0||n<=0)return o.join(`
374
+ `+Rd(e.text,n);case"note":return`
375
+ `+jC[e.tone](Ds(dl(e.text)));case"block":return`
376
+ `+e.text;case"done":{let o=e.inTokens&&e.inTokens>0?` \xB7 ${Js(e.inTokens)} in${e.cachedPct!=null?` (${e.cachedPct}% cached)`:""}`:"",r=e.activeSeconds!==void 0&&al(e.activeSeconds,e.seconds)?`${An(e.seconds)} elapsed \xB7 ${An(e.activeSeconds)} working`:An(e.seconds),s=e.costUsd>0?` \xB7 this turn ${$t(e.costUsd)}`+(e.sessionCostUsd!==void 0&&e.sessionCostUsd>e.costUsd?` \xB7 session ${$t(e.sessionCostUsd)}`:""):"";return`
377
+ `+(e.ok?xe.magenta("\u2736 "):xe.red("\u2736 "))+xe.gray(`Cooked for ${r} \xB7 ${Js(e.tokens)} tokens out${o}${s}`)}}}function Zy(e,t,n){let o=e.map(i=>Ad(i,t));if(n===void 0||n<=0)return o.join(`
378
378
  `);let r=[],s=0;for(let i=o.length-1;i>=0;i--){let a=o[i].split(`
379
379
  `).length;if(r.length>0&&s+a>n)break;r.unshift(o[i]),s+=a}return r.join(`
380
- `)}var Sd=3;function Cd(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 Pd(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Td(e,t){return t.map(n=>{let o=0;try{o=RC(SC(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function Ad(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:
380
+ `)}var Ed=3;function Nd(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 Dd(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function jd(e,t){return t.map(n=>{let o=0;try{o=IC(LC(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function Id(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:
381
381
  - 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.
382
382
  - 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.
383
383
  - 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.
384
384
  - Work only on these files:
385
385
  `+e.paths.map(t=>`- ${t}`).join(`
386
- `)}function Ed(e,t,n){let o=e.reduce((a,c)=>a+c.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: ${kt(r)}\u2013${kt(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function Nd(e,t,n){let o=A=>t[A.index]?.paths.length??0,r=e.filter(A=>A.ok),s=e.filter(A=>!A.ok),i=e.reduce((A,S)=>A+o(S),0),a=r.reduce((A,S)=>A+o(S),0),c=e.reduce((A,S)=>A+S.costUsd,0),l=e.reduce((A,S)=>A+S.outputTokens,0),f=n==="api"?`${kt(c)} total`:_r(l),g=`${r.length}/${e.length} batch${e.length===1?"":"es"} completed`,k=A=>`${A} article${A===1?"":"s"}`,T=[];if(s.length===0)T.push(`Converted ${k(i)} (${g}) successfully \xB7 ${f}.`);else{T.push(`Converted ${a}/${k(i)} (${g}) \xB7 ${f}.`),T.push(`${s.length} batch${s.length===1?"":"es"} failed \u2014 re-run /convert to retry:`);for(let A of s)T.push(` \u2717 ${A.label}${A.error?` \u2014 ${A.error}`:""}`)}return T}async function Ky(e,t){if(!TC(t.cwd))return console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=Cd(e),r=NC(t.cwd,t.profileName);if(r.length===0)return console.log(L("No tracked articles in d360-category-map.json. Save some to Document360 first (/push), then /convert.")),{kind:"continue"};let s=Pd(r,n);if(s.length===0)return console.log(L(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let i=PC(s),a=`/convert${n?` --scope ${n}`:""} --run`,{model:c,forced:l}=AC(t.cwd,"light");if(!o){let g=CC({files:Td(t.cwd,s),op:"convert",model:c});n&&console.log(d(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let k of Ed(i,g,Sd))console.log(k);return console.log(d(`Model: ${c}${l?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(d(`Run ${a} to start.`)),console.log(""),{kind:"continue"}}console.log(d(`Converting ${s.length} articles in ${i.length} batches (\u2264${Sd} agents at once) on ${c}\u2026`)),console.log(d(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let f=Date.now();try{for await(let g of EC({cwd:t.cwd,partitions:i,promptFor:Ad,concurrency:Sd,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:c}))if(g.type==="partition_status")g.status==="running"?console.log(d(` \u25B8 ${g.label} \u2014 converting\u2026`)):g.status==="done"?console.log(X(` \u2713 ${g.label}`)):console.log(L(` \u2717 ${g.label}`));else if(g.type==="run_done"){console.log("");let k=process.env.ANTHROPIC_API_KEY?"api":"subscription",T=zn(g,"The conversion");for(let A of T??Nd(g.results,i,k))console.log(T||!g.ok?K(A):X(A));console.log(d(ln(Ot(f,g.results,g.totalCostUsd))))}}catch(g){console.log(L(`Convert run failed: ${g.message}`))}return console.log(""),{kind:"continue"}}import{statSync as eP}from"node:fs";import{resolve as tP}from"node:path";import{CLAUDE_ACCOUNT_MISMATCH_HINT as nP,estimateBulkCost as oP,lintDocs as rP,planFindingPartitions as sP,planPartitions as iP,readDocsPlan as aP,readProjectConfig as Ud,DEFAULT_DOCS_DIR as aw,resolveModelForOperation as ow,runPartitioned as rw,partitionCoverage as sw,stampArticles as iw,readReviewerNotes as lP,renderNotesForPrompt as cP,readReaderContract as uP,renderGapsForPrompt as dP,notesForPath as pP,CONTENT_CAP_VERSION as hP}from"document360-engine";oe();import{lintDocs as jd,guidanceForRules as DC,planFindingPartitions as jC,runPartitioned as IC,partitionCoverage as LC,resolveModelForOperation as OC,stampArticles as _C,applyDeterministicFixes as MC,isMechanical as FC}from"document360-engine";import{CONTENT_CAP_VERSION as Yy}from"document360-engine";function zy(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 Xy(e){return e.trim().split(/\s+/).slice(1).find(t=>!t.startsWith("--"))}function ft(e){return e==="review"?{reviewedCap:Yy}:{checkedCap:Yy}}var ll={error:0,warning:1,suggestion:2},UC={error:"\u2717",warning:"\u26A0",suggestion:"\xB7"},WC=10,BC=8,HC=96,Qy=34,cn=e=>"ruleId"in e,Qn=e=>cn(e)?e.severity:"warning",Id=e=>cn(e)?e.ruleId:e.kind,Bo=e=>e.fileLine??e.line;function Tn(e){return e.includes("--blocked")}function An(e,t){return Tn(t)?e.filter(n=>Qn(n)==="error"):e}function Qs(e,t){return`/lint${t?` ${t}`:""}${Tn(e)?" --blocked":""} --fix`}function Dd(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function al(e){let t={error:0,warning:0,suggestion:0};for(let n of e)t[Qn(n)]++;return t}function Jy(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 Js(e,t={}){let n=t.baselined?[]:e.filter(g=>cn(g)&&g.baselined),o=t.baselined?e:e.filter(g=>!(cn(g)&&g.baselined)),r=n.length>0?[ne("\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[ne("\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 g of o){let k=s.get(g.path)??[];k.push(g),s.set(g.path,k)}let i=al(o),a=[ne("\u26A0",`${o.length} issue${o.length===1?"":"s"} in ${s.size} article${s.size===1?"":"s"} \u2014 ${Jy(i)}.`),""],c=[...s.entries()].sort((g,k)=>{let T=al(g[1]);return al(k[1]).error-T.error||k[1].length-g[1].length||g[0].localeCompare(k[0])}),l=t.full?c:c.slice(0,WC);for(let[g,k]of l){a.push(` ${g} ${d(Jy(al(k)))}`);let T=new Map;for(let x of k){let E=Id(x),I=T.get(E)??[];I.push(x),T.set(E,I)}let A=[...T.entries()].sort((x,E)=>ll[Qn(x[1][0])]-ll[Qn(E[1][0])]||E[1].length-x[1].length||x[0].localeCompare(E[0])),S=t.full?A:A.slice(0,BC);for(let[x,E]of S){let I=[...E].sort((we,Z)=>Bo(we)-Bo(Z)),W=UC[Qn(I[0])],B=new Set(I.map(we=>we.term)).size===1?` ${Dd(`"${I[0].term}"`,Qy)}`:"",ae=I.length>1?d(` \xD7${I.length}`):"",me=t.full?I[0].message:Dd(I[0].message,HC);a.push(` ${W} ${x}${ae}${B}`),a.push(` ${d(me)}`);let Re=I.map(we=>B?`L${Bo(we)}`:`L${Bo(we)} ${Dd(`"${we.term}"`,Qy)}`),Ie=t.full?Re:Re.slice(0,12),ge=Re.length-Ie.length;a.push(` ${d(Ie.join(", ")+(ge>0?` \u2026+${ge}`:""))}`)}let C=A.length-S.length;C>0&&a.push(d(` \u2026${C} more rule${C===1?"":"s"} fired here (/lint ${g} --full)`)),a.push("")}let f=c.length-l.length;return f>0&&(a.push(d(` \u2026and ${f} more article${f===1?"":"s"} (/lint <category> narrows \xB7 /lint --full lists every one)`)),a.push("")),a.push(...r),a}var GC=200;function cl(e){let n=[...e.filter(c=>!(cn(c)&&c.baselined))].sort((c,l)=>ll[Qn(c)]-ll[Qn(l)]||c.path.localeCompare(l.path)||Bo(c)-Bo(l)),o=n.slice(0,GC),r=n.length-o.length,s=new Map;for(let c of o){let l=s.get(c.path)??[];l.push(c),s.set(c.path,l)}let i=[...s.entries()].map(([c,l])=>[c,...l.map(f=>` - L${Bo(f)} [${Id(f)}] (${Qn(f)}): "${f.term}": ${f.message}`)].join(`
386
+ `)}function Ld(e,t,n){let o=e.reduce((a,c)=>a+c.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: ${$t(r)}\u2013${$t(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function Od(e,t,n){let o=A=>t[A.index]?.paths.length??0,r=e.filter(A=>A.ok),s=e.filter(A=>!A.ok),i=e.reduce((A,S)=>A+o(S),0),a=r.reduce((A,S)=>A+o(S),0),c=e.reduce((A,S)=>A+S.costUsd,0),l=e.reduce((A,S)=>A+S.outputTokens,0),f=n==="api"?`${$t(c)} total`:Or(l),g=`${r.length}/${e.length} batch${e.length===1?"":"es"} completed`,$=A=>`${A} article${A===1?"":"s"}`,T=[];if(s.length===0)T.push(`Converted ${$(i)} (${g}) successfully \xB7 ${f}.`);else{T.push(`Converted ${a}/${$(i)} (${g}) \xB7 ${f}.`),T.push(`${s.length} batch${s.length===1?"":"es"} failed \u2014 re-run /convert to retry:`);for(let A of s)T.push(` \u2717 ${A.label}${A.error?` \u2014 ${A.error}`:""}`)}return T}async function ew(e,t){if(!MC(t.cwd))return console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=Nd(e),r=WC(t.cwd,t.profileName);if(r.length===0)return console.log(L("No tracked articles in d360-category-map.json. Save some to Document360 first (/push), then /convert.")),{kind:"continue"};let s=Dd(r,n);if(s.length===0)return console.log(L(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let i=_C(s),a=`/convert${n?` --scope ${n}`:""} --run`,{model:c,forced:l}=FC(t.cwd,"light");if(!o){let g=OC({files:jd(t.cwd,s),op:"convert",model:c});n&&console.log(d(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let $ of Ld(i,g,Ed))console.log($);return console.log(d(`Model: ${c}${l?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(d(`Run ${a} to start.`)),console.log(""),{kind:"continue"}}console.log(d(`Converting ${s.length} articles in ${i.length} batches (\u2264${Ed} agents at once) on ${c}\u2026`)),console.log(d(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let f=Date.now();try{for await(let g of UC({cwd:t.cwd,partitions:i,promptFor:Id,concurrency:Ed,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:c}))if(g.type==="partition_status")g.status==="running"?console.log(d(` \u25B8 ${g.label} \u2014 converting\u2026`)):g.status==="done"?console.log(Q(` \u2713 ${g.label}`)):console.log(L(` \u2717 ${g.label}`));else if(g.type==="run_done"){console.log("");let $=process.env.ANTHROPIC_API_KEY?"api":"subscription",T=Xn(g,"The conversion");for(let A of T??Od(g.results,i,$))console.log(T||!g.ok?q(A):Q(A));console.log(d(cn(Ft(f,g.results,g.totalCostUsd))))}}catch(g){console.log(L(`Convert run failed: ${g.message}`))}return console.log(""),{kind:"continue"}}import{statSync as uP}from"node:fs";import{resolve as dP}from"node:path";import{CLAUDE_ACCOUNT_MISMATCH_HINT as pP,estimateBulkCost as hP,lintDocs as fP,planFindingPartitions as mP,planPartitions as gP,readDocsPlan as yP,readProjectConfig as qd,DEFAULT_DOCS_DIR as fw,resolveModelForOperation as uw,runPartitioned as dw,partitionCoverage as pw,stampArticles as hw,readReviewerNotes as wP,renderNotesForPrompt as bP,readReaderContract as kP,renderGapsForPrompt as $P,notesForPath as vP,CONTENT_CAP_VERSION as xP}from"document360-engine";oe();import{lintDocs as Md,guidanceForRules as BC,planFindingPartitions as HC,runPartitioned as GC,partitionCoverage as qC,resolveModelForOperation as VC,stampArticles as YC,applyDeterministicFixes as KC,isMechanical as zC}from"document360-engine";import{CONTENT_CAP_VERSION as tw}from"document360-engine";function nw(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 ow(e){return e.trim().split(/\s+/).slice(1).find(t=>!t.startsWith("--"))}function mt(e){return e==="review"?{reviewedCap:tw}:{checkedCap:tw}}var hl={error:0,warning:1,suggestion:2},XC={error:"\u2717",warning:"\u26A0",suggestion:"\xB7"},QC=10,JC=8,ZC=96,rw=34,un=e=>"ruleId"in e,Jn=e=>un(e)?e.severity:"warning",Fd=e=>un(e)?e.ruleId:e.kind,Ho=e=>e.fileLine??e.line;function En(e){return e.includes("--blocked")}function Nn(e,t){return En(t)?e.filter(n=>Jn(n)==="error"):e}function Zs(e,t){return`/lint${t?` ${t}`:""}${En(e)?" --blocked":""} --fix`}function _d(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function pl(e){let t={error:0,warning:0,suggestion:0};for(let n of e)t[Jn(n)]++;return t}function sw(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 ei(e,t={}){let n=t.baselined?[]:e.filter(g=>un(g)&&g.baselined),o=t.baselined?e:e.filter(g=>!(un(g)&&g.baselined)),r=n.length>0?[ne("\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[ne("\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 g of o){let $=s.get(g.path)??[];$.push(g),s.set(g.path,$)}let i=pl(o),a=[ne("\u26A0",`${o.length} issue${o.length===1?"":"s"} in ${s.size} article${s.size===1?"":"s"} \u2014 ${sw(i)}.`),""],c=[...s.entries()].sort((g,$)=>{let T=pl(g[1]);return pl($[1]).error-T.error||$[1].length-g[1].length||g[0].localeCompare($[0])}),l=t.full?c:c.slice(0,QC);for(let[g,$]of l){a.push(` ${g} ${d(sw(pl($)))}`);let T=new Map;for(let x of $){let E=Fd(x),j=T.get(E)??[];j.push(x),T.set(E,j)}let A=[...T.entries()].sort((x,E)=>hl[Jn(x[1][0])]-hl[Jn(E[1][0])]||E[1].length-x[1].length||x[0].localeCompare(E[0])),S=t.full?A:A.slice(0,JC);for(let[x,E]of S){let j=[...E].sort((we,Z)=>Ho(we)-Ho(Z)),W=XC[Jn(j[0])],B=new Set(j.map(we=>we.term)).size===1?` ${_d(`"${j[0].term}"`,rw)}`:"",ue=j.length>1?d(` \xD7${j.length}`):"",fe=t.full?j[0].message:_d(j[0].message,ZC);a.push(` ${W} ${x}${ue}${B}`),a.push(` ${d(fe)}`);let Re=j.map(we=>B?`L${Ho(we)}`:`L${Ho(we)} ${_d(`"${we.term}"`,rw)}`),Ie=t.full?Re:Re.slice(0,12),ge=Re.length-Ie.length;a.push(` ${d(Ie.join(", ")+(ge>0?` \u2026+${ge}`:""))}`)}let C=A.length-S.length;C>0&&a.push(d(` \u2026${C} more rule${C===1?"":"s"} fired here (/lint ${g} --full)`)),a.push("")}let f=c.length-l.length;return f>0&&(a.push(d(` \u2026and ${f} more article${f===1?"":"s"} (/lint <category> narrows \xB7 /lint --full lists every one)`)),a.push("")),a.push(...r),a}var eP=200;function fl(e){let n=[...e.filter(c=>!(un(c)&&c.baselined))].sort((c,l)=>hl[Jn(c)]-hl[Jn(l)]||c.path.localeCompare(l.path)||Ho(c)-Ho(l)),o=n.slice(0,eP),r=n.length-o.length,s=new Map;for(let c of o){let l=s.get(c.path)??[];l.push(c),s.set(c.path,l)}let i=[...s.entries()].map(([c,l])=>[c,...l.map(f=>` - L${Ho(f)} [${Fd(f)}] (${Jn(f)}): "${f.term}": ${f.message}`)].join(`
387
387
  `)).join(`
388
- `),a=DC(o.map(c=>({id:Id(c),message:c.message,link:cn(c)?c.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(`
389
- `)}var Mr=3;function Jn(e,t,n){let o=n.filter(a=>!(cn(a)&&a.baselined)),r=An(o,t).filter(a=>cn(a)&&FC(a));if(r.length===0)return{fixed:0,skipped:0,lines:[],paths:[]};let s=MC(e,r),i=[];if(s.fixed.length>0){let a=new Set(s.fixed.map(c=>c.path)).size;i.push(X(ne("\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(d(` ${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 Ld(e,t,n){let o=An(n.filter(a=>!(cn(a)&&a.baselined)),t);if(o.length===0)return null;let r=t.find(a=>!a.startsWith("--")),s=Qs(t,r),i=jC(o);return i.length<=1?{kind:"single",prompt:cl(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 c=new Set(a.paths);return cl(o.filter(l=>c.has(l.path)))}}}function Od(e,t,n){let o=t.find(c=>!c.startsWith("--")),r=o?` in ${o}`:"",s=n.filter(c=>!(cn(c)&&c.baselined)),i=new Set(s.map(c=>c.path)).size;return{lines:Tn(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:Ke(e,Qs(t,o))}}async function qC(e,t,n,o=[]){let{model:r}=OC(e.cwd,"standard");console.log(d(`Fixing ${t.findings} issue${t.findings===1?"":"s"} across ${t.articles} article${t.articles===1?"":"s"} in ${t.partitions.length} batches (\u2264${Mr} 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 g of IC({cwd:e.cwd,partitions:t.partitions,promptFor:t.promptFor,concurrency:Mr,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:r}))if(g.type==="partition_status")g.status==="running"?console.log(d(` \u25B8 ${g.label} \u2014 fixing\u2026`)):g.status==="done"?console.log(X(` \u2713 ${g.label}`)):console.log(L(` \u2717 ${g.label}`));else if(g.type==="run_done"){let k=LC(t.partitions,g.results);a={aborted:!!g.aborted,partitions:t.partitions.length,failed:k.failed.length,notRun:k.notRun.length,...g.blocked?{blocked:g.blocked}:{},...g.allEmpty?{allEmpty:!0}:{},...g.bailedEmpty?{bailedEmpty:!0}:{}},console.log(d(ln(Ot(i,g.results,g.totalCostUsd)))),k.failed.length&&console.log(K(`\u26A0 ${k.failed.length} batch${k.failed.length===1?"":"es"} not fixed: ${k.failed.map(T=>T.label).join(", ")}`)),k.notRun.length&&console.log(K(`\u26A0 ${k.notRun.length} batch${k.notRun.length===1?"":"es"} never started \u2014 their articles are untouched.`)),g.blocked&&console.log(K(`\u26A0 ${g.blocked}`)),g.allEmpty&&console.log(K("\u26A0 No turn produced any work this run \u2014 nothing was changed.")),!g.allEmpty&&!g.blocked&&s.push(...k.covered)}}catch(g){return console.log(L(`Fix run failed: ${g.message}`)),{kind:"continue"}}if(s.length>0)try{_C(e.cwd,s,ft("lint"))}catch{}let c=jd({cwd:e.cwd,scope:n}).filter(g=>!g.baselined),l=An(c,o);console.log("");for(let g of Js(l))console.log(l.length===0?X(g):K(g));if(Xt(a))for(let g of Ke(e.cwd,Qs(o,n)))console.log(X(g));let f=Hs({cwd:e.cwd,after:l,before:t.findings,scope:n,blocked:Tn(o)});return console.log(""),console.log(d(f.text)),{kind:"continue",ownNext:!0}}async function _d(e,t){let n=e.includes("--fix"),o=e.find(a=>!a.startsWith("--")),r=o?` ${o}`:"",s=jd({cwd:t.cwd,scope:o});if(n){let a=Jn(t.cwd,e,s);for(let f of a.lines)console.log(f);let c=a.fixed>0?jd({cwd:t.cwd,scope:o}):s,l=Ld(t.cwd,e,c);if(!l){let f=Od(t.cwd,e,c);console.log(X(f.lines[0]));for(let g of f.lines.slice(1))console.log(d(g));for(let g of f.closed)console.log(X(g));return{kind:"continue",ownNext:!0}}return l.kind==="partitioned"?qC(t,l,o,e):(console.log(d(`Fixing ${l.findings} doc issue${l.findings===1?"":"s"} (run /lint again after to confirm)\u2026`)),{kind:"forward-to-agent",prompt:l.prompt,display:l.display})}let i=An(s,e);console.log(d("Linting the docs (engine internals, unknown commands, stale facts, AI-tells, em dashes, callout shape)\u2026"));for(let a of Js(i,{full:e.includes("--full"),baselined:e.includes("--baselined")}))console.log(i.length===0?X(a):K(a));return i.length>0&&console.log(d(`Run /lint${r}${Tn(e)?" --blocked":""} --fix to have the agent correct these.`)),console.log(""),{kind:"continue",ownNext:i.length>0}}var Zy=async(e,t)=>{let n=Gs("check");return n&&console.log(d(`\u2192 ${n}`)),_d(e,t)};oe();import{readProjectConfig as VC,loadProfileMap as KC,resolveActiveProfile as YC,desiredCategoryOrder as zC,desiredArticleOrder as XC,DEFAULT_DOCS_DIR as QC}from"document360-engine";var Md=e=>e.replace(/\\/g,"/"),ew=e=>Md(e).split("/").pop()??e;function Fd(e){let t=ew(e),n=t.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return n?n.charAt(0).toUpperCase()+n.slice(1):t}var JC=Fd;function Zs(e,t){try{let n=VC(e);if(!n)return[];let o=YC(e,t),r=KC(e,o.name);if(!r)return[];let s=Md(n.docsDir??QC).replace(/\/+$/,""),i=new Map;for(let c of XC(r))i.set(c.categoryPath,(i.get(c.categoryPath)??0)+1);let a=[];for(let c of zC(r)){let l=Md(c.path),f=l.startsWith(`${s}/`)?l.slice(s.length+1):l===s?"":l;f&&a.push({token:f,label:JC(ew(l)),count:i.get(c.path)??0})}return a}catch{return[]}}function tw(e,t){let n=Zs(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 Zn(e,t){if(t.includes("--all")||t.includes("--blocked")||t.includes("--stale")||t.some(n=>n.startsWith("--scope="))||t.includes("--scope")&&!ei(t))return!1;for(let n=0;n<t.length;n++){let o=t[n];if(o.startsWith("--")){ZC.has(o)&&n++;continue}return!1}return e==="write"?!t.includes("--preview")&&!t.includes("--dry-run"):e==="review"||e==="reorder"}var ZC=new Set(["--scope","--concurrency"]);function Fr(e,t,n,o,r){if(r=r??Zs(e,o),r.length<=1)return[];let s=n.filter(l=>l.startsWith("--")).join(" "),i=s?` ${s}`:"",a=`/${t}${i} --all`.replace(/\s+/g," "),c=l=>t==="write"?`/write --scope ${l}${i}`:`/${t} ${l}${i}`;return[`Bare /${t} covers the WHOLE knowledge base (${r.reduce((l,f)=>l+f.count,0)} articles). Pick a target:`,` ${a} (everything)`,...r.map(l=>` ${c(l.token)} (${l.label} \xB7 ${l.count} article${l.count===1?"":"s"})`)]}function ei(e){let t=e.indexOf("--scope");if(t===-1)return!1;let n=e[t+1];return n===void 0||n.startsWith("-")}function nw(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 fP=3,mP=8;function Wd(e){return e===void 0||!Number.isFinite(e)?fP:Math.max(1,Math.min(Math.floor(e),mP))}function ti(e){let t,n,o=!1,r=!1,s,i=c=>{let l=Number(c);return c!==void 0&&Number.isFinite(l)?l:void 0};for(let c=0;c<e.length;c++){let l=e[c];if(l==="--preview"||l==="--dry-run")o=!0;else if(l==="--rewrite"||l==="--force")r=!0;else{if(l==="--run"||l==="--yes"||l==="--all")continue;l==="--scope"?t=e[++c]:l?.startsWith("--scope=")?t=l.slice(8):l==="--concurrency"?s=i(e[++c]):l?.startsWith("--concurrency=")?s=i(l.slice(14)):l&&!l.startsWith("--")&&(n=l)}}let a=c=>c?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:a(t),path:a(n),preview:o,concurrency:s,rewrite:r}}function gP(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function yP(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Bd(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+=eP(tP(e,i)).size}catch{}return{path:r,bytes:s}})}function Hd(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()?`
388
+ `),a=BC(o.map(c=>({id:Fd(c),message:c.message,link:un(c)?c.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(`
389
+ `)}var _r=3;function Zn(e,t,n){let o=n.filter(a=>!(un(a)&&a.baselined)),r=Nn(o,t).filter(a=>un(a)&&zC(a));if(r.length===0)return{fixed:0,skipped:0,lines:[],paths:[]};let s=KC(e,r),i=[];if(s.fixed.length>0){let a=new Set(s.fixed.map(c=>c.path)).size;i.push(Q(ne("\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(d(` ${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 Ud(e,t,n){let o=Nn(n.filter(a=>!(un(a)&&a.baselined)),t);if(o.length===0)return null;let r=t.find(a=>!a.startsWith("--")),s=Zs(t,r),i=HC(o);return i.length<=1?{kind:"single",prompt:fl(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 c=new Set(a.paths);return fl(o.filter(l=>c.has(l.path)))}}}function Wd(e,t,n){let o=t.find(c=>!c.startsWith("--")),r=o?` in ${o}`:"",s=n.filter(c=>!(un(c)&&c.baselined)),i=new Set(s.map(c=>c.path)).size;return{lines:En(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:Ye(e,Zs(t,o))}}async function tP(e,t,n,o=[]){let{model:r}=VC(e.cwd,"standard");console.log(d(`Fixing ${t.findings} issue${t.findings===1?"":"s"} across ${t.articles} article${t.articles===1?"":"s"} in ${t.partitions.length} batches (\u2264${_r} 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 g of GC({cwd:e.cwd,partitions:t.partitions,promptFor:t.promptFor,concurrency:_r,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:r}))if(g.type==="partition_status")g.status==="running"?console.log(d(` \u25B8 ${g.label} \u2014 fixing\u2026`)):g.status==="done"?console.log(Q(` \u2713 ${g.label}`)):console.log(L(` \u2717 ${g.label}`));else if(g.type==="run_done"){let $=qC(t.partitions,g.results);a={aborted:!!g.aborted,partitions:t.partitions.length,failed:$.failed.length,notRun:$.notRun.length,...g.blocked?{blocked:g.blocked}:{},...g.allEmpty?{allEmpty:!0}:{},...g.bailedEmpty?{bailedEmpty:!0}:{}},console.log(d(cn(Ft(i,g.results,g.totalCostUsd)))),$.failed.length&&console.log(q(`\u26A0 ${$.failed.length} batch${$.failed.length===1?"":"es"} not fixed: ${$.failed.map(T=>T.label).join(", ")}`)),$.notRun.length&&console.log(q(`\u26A0 ${$.notRun.length} batch${$.notRun.length===1?"":"es"} never started \u2014 their articles are untouched.`)),g.blocked&&console.log(q(`\u26A0 ${g.blocked}`)),g.allEmpty&&console.log(q("\u26A0 No turn produced any work this run \u2014 nothing was changed.")),!g.allEmpty&&!g.blocked&&s.push(...$.covered)}}catch(g){return console.log(L(`Fix run failed: ${g.message}`)),{kind:"continue"}}if(s.length>0)try{YC(e.cwd,s,mt("lint"))}catch{}let c=Md({cwd:e.cwd,scope:n}).filter(g=>!g.baselined),l=Nn(c,o);console.log("");for(let g of ei(l))console.log(l.length===0?Q(g):q(g));if(Qt(a))for(let g of Ye(e.cwd,Zs(o,n)))console.log(Q(g));let f=qs({cwd:e.cwd,after:l,before:t.findings,scope:n,blocked:En(o)});return console.log(""),console.log(d(f.text)),{kind:"continue",ownNext:!0}}async function Bd(e,t){let n=e.includes("--fix"),o=e.find(a=>!a.startsWith("--")),r=o?` ${o}`:"",s=Md({cwd:t.cwd,scope:o});if(n){let a=Zn(t.cwd,e,s);for(let f of a.lines)console.log(f);let c=a.fixed>0?Md({cwd:t.cwd,scope:o}):s,l=Ud(t.cwd,e,c);if(!l){let f=Wd(t.cwd,e,c);console.log(Q(f.lines[0]));for(let g of f.lines.slice(1))console.log(d(g));for(let g of f.closed)console.log(Q(g));return{kind:"continue",ownNext:!0}}return l.kind==="partitioned"?tP(t,l,o,e):(console.log(d(`Fixing ${l.findings} doc issue${l.findings===1?"":"s"} (run /lint again after to confirm)\u2026`)),{kind:"forward-to-agent",prompt:l.prompt,display:l.display})}let i=Nn(s,e);console.log(d("Linting the docs (engine internals, unknown commands, stale facts, AI-tells, em dashes, callout shape)\u2026"));for(let a of ei(i,{full:e.includes("--full"),baselined:e.includes("--baselined")}))console.log(i.length===0?Q(a):q(a));return i.length>0&&console.log(d(`Run /lint${r}${En(e)?" --blocked":""} --fix to have the agent correct these.`)),console.log(""),{kind:"continue",ownNext:i.length>0}}var iw=async(e,t)=>{let n=Vs("check");return n&&console.log(d(`\u2192 ${n}`)),Bd(e,t)};oe();import{readProjectConfig as nP,loadProfileMap as oP,resolveActiveProfile as rP,desiredCategoryOrder as sP,desiredArticleOrder as iP,DEFAULT_DOCS_DIR as aP}from"document360-engine";var Hd=e=>e.replace(/\\/g,"/"),aw=e=>Hd(e).split("/").pop()??e;function Gd(e){let t=aw(e),n=t.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return n?n.charAt(0).toUpperCase()+n.slice(1):t}var lP=Gd;function ti(e,t){try{let n=nP(e);if(!n)return[];let o=rP(e,t),r=oP(e,o.name);if(!r)return[];let s=Hd(n.docsDir??aP).replace(/\/+$/,""),i=new Map;for(let c of iP(r))i.set(c.categoryPath,(i.get(c.categoryPath)??0)+1);let a=[];for(let c of sP(r)){let l=Hd(c.path),f=l.startsWith(`${s}/`)?l.slice(s.length+1):l===s?"":l;f&&a.push({token:f,label:lP(aw(l)),count:i.get(c.path)??0})}return a}catch{return[]}}function lw(e,t){let n=ti(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 eo(e,t){if(t.includes("--all")||t.includes("--blocked")||t.includes("--stale")||t.some(n=>n.startsWith("--scope="))||t.includes("--scope")&&!ni(t))return!1;for(let n=0;n<t.length;n++){let o=t[n];if(o.startsWith("--")){cP.has(o)&&n++;continue}return!1}return e==="write"?!t.includes("--preview")&&!t.includes("--dry-run"):e==="review"||e==="reorder"}var cP=new Set(["--scope","--concurrency"]);function Mr(e,t,n,o,r){if(r=r??ti(e,o),r.length<=1)return[];let s=n.filter(l=>l.startsWith("--")).join(" "),i=s?` ${s}`:"",a=`/${t}${i} --all`.replace(/\s+/g," "),c=l=>t==="write"?`/write --scope ${l}${i}`:`/${t} ${l}${i}`;return[`Bare /${t} covers the WHOLE knowledge base (${r.reduce((l,f)=>l+f.count,0)} articles). Pick a target:`,` ${a} (everything)`,...r.map(l=>` ${c(l.token)} (${l.label} \xB7 ${l.count} article${l.count===1?"":"s"})`)]}function ni(e){let t=e.indexOf("--scope");if(t===-1)return!1;let n=e[t+1];return n===void 0||n.startsWith("-")}function cw(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 RP=3,SP=8;function Vd(e){return e===void 0||!Number.isFinite(e)?RP:Math.max(1,Math.min(Math.floor(e),SP))}function oi(e){let t,n,o=!1,r=!1,s,i=c=>{let l=Number(c);return c!==void 0&&Number.isFinite(l)?l:void 0};for(let c=0;c<e.length;c++){let l=e[c];if(l==="--preview"||l==="--dry-run")o=!0;else if(l==="--rewrite"||l==="--force")r=!0;else{if(l==="--run"||l==="--yes"||l==="--all")continue;l==="--scope"?t=e[++c]:l?.startsWith("--scope=")?t=l.slice(8):l==="--concurrency"?s=i(e[++c]):l?.startsWith("--concurrency=")?s=i(l.slice(14)):l&&!l.startsWith("--")&&(n=l)}}let a=c=>c?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:a(t),path:a(n),preview:o,concurrency:s,rewrite:r}}function CP(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function PP(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Yd(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+=uP(dP(e,i)).size}catch{}return{path:r,bytes:s}})}function Kd(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()?`
390
390
  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:
391
391
  `+n.reviewerNotes.trim()+`
392
392
  `:"",s=n.openGaps?.trim()?`
@@ -404,198 +404,200 @@ QUESTIONS ALREADY RAISED ABOUT THESE ARTICLES (waiting on a person). Someone has
404
404
  - 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.
405
405
  Articles:
406
406
  `+e.paths.map(a=>`- ${a}`).join(`
407
- `)+r+s}function Gd(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: ${kt(r)}\u2013${kt(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function qd(e,t,n,o){let r=S=>t[S.index]?.paths.length??0,s=e.filter(S=>S.ok),i=e.filter(S=>!S.ok),a=e.reduce((S,C)=>S+r(C),0),c=s.reduce((S,C)=>S+r(C),0),l=e.reduce((S,C)=>S+C.costUsd,0),f=e.reduce((S,C)=>S+C.outputTokens,0),g=n==="api"?`${kt(l)} total`:_r(f),k=`${s.length}/${e.length} batch${e.length===1?"":"es"} completed`,T=S=>`${S} article${S===1?"":"s"}`,A=[];if(i.length===0){A.push(`Wrote ${T(a)} (${k}) successfully \xB7 ${g}.`);let S=o?` ${o}`:"",C=o?"/push":"/push --all",x=o?`/screenshot author ${o}`:"/screenshot author --all";A.push("Next \u2014 an editorial review, because these were written by an AI:"),A.push(`/review${S} --fix`),A.push(`It reads every article and applies its fixes; ${C} then pushes them up (add screenshots first with ${x} if you want them).`)}else{A.push(`Wrote ${c}/${T(a)} (${k}) \xB7 ${g}.`),A.push(`${i.length} batch${i.length===1?"":"es"} failed \u2014 re-run /write${o?` --scope ${o}`:""} to retry the rest:`);for(let S of i)A.push(` \u2717 ${S.label}${S.error?` \u2014 ${S.error}`:""}`);i.some(S=>/rate-limited/i.test(S.error??""))&&(A.push("Claude rate-limited this run, not your usage allowance. Retry one batch at a time:"),A.push(`/write${o?` --scope ${o}`:""} --concurrency 1`)),i.some(S=>/usage limit has been reached/i.test(S.error??""))&&A.push(nP)}return A}function Ur(e,t,n){try{return rP({cwd:e,paths:n.map(o=>`${t}/${o}`)}).filter(o=>!o.baselined)}catch{return[]}}function Vd(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 Kd(e){let t=e.filter(o=>o.severity==="error");if(t.length===0)return null;let n=sP(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 cl(t.filter(s=>r.has(s.path)))}}}function Yd(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 ul(e,t,n){let o=(Ud(e)?.docsDir??aw).replace(/\/+$/,""),r=t.map(a=>a.path);if(n.path){let a=gP(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=yP(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=Kn(e,o,s);if(i.length===0){let a=n.scope?` under "${n.scope}"`:"",c=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${c} --rewrite to regenerate them all.`}}return{docsDir:o,targets:i,planCount:r.length}}function zd(e,t,n){let{targets:o}=ul(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:Fd(s),count:i}))}async function lw(e,t){if(!Ud(t.cwd))return console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"};if(ei(e)){for(let V of tw(t.cwd,t.profileName))console.log(d(V));return{kind:"continue"}}let n=aP(t.cwd,(Ud(t.cwd)?.docsDir??aw).replace(/\/+$/,""));if(n.length===0)return console.log(L("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};if(Zn("write",e)){let V=zd(t.cwd,n,{rewrite:ti(e).rewrite}),B=Fr(t.cwd,"write",e,t.profileName,V);if(B.length>0){for(let ae of B)console.log(d(ae));return{kind:"continue"}}}let{scope:o,path:r,preview:s,concurrency:i,rewrite:a}=ti(e),{docsDir:c,targets:l,reason:f,rewriting:g}=ul(t.cwd,n,{scope:o,path:r,rewrite:a});if(l.length===0)return console.log(f?K(f):K("Nothing to write.")),{kind:"continue"};g&&console.log(K(`--rewrite: regenerating ${l.length} already-written article${l.length===1?"":"s"} (overwrites them; git has your baseline).`));let k=iP(l),T=Wd(i),{model:A,forced:S}=ow(t.cwd,"standard"),C=!!r;if(s&&!C){let V=oP({files:Bd(t.cwd,n,l),op:"write",model:A});o&&console.log(d(`Scope: ${o} (${l.length} pending).`));for(let B of Gd(k,V,T))console.log(B);return console.log(d(`Model: ${A}${S?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(d(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}let x=lP(t.cwd),E=uP(t.cwd),I=l.filter(V=>pP(x,V).length>0).length;I>0&&console.log(d(` ${I} of these ${I===1?"has":"have"} reviewer comments \u2014 the writer gets them.`)),console.log(d(`Writing ${l.length} article${l.length===1?"":"s"} in ${k.length} batch${k.length===1?"":"es"} (\u2264${T} agents at once) on ${A}\u2026`)),console.log(d(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let W=Date.now();try{for await(let V of rw({cwd:t.cwd,partitions:k,promptFor:B=>Hd(B,c,{rewrite:g||C,reviewerNotes:cP(x,B.paths),openGaps:dP(t.cwd,B.paths),readerContract:E}),concurrency:T,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:A}))if(V.type==="partition_status")V.status==="running"?console.log(d(` \u25B8 ${V.label} \u2014 writing\u2026`)):V.status==="done"?console.log(X(` \u2713 ${V.label}`)):console.log(L(` \u2717 ${V.label}`));else if(V.type==="run_done"){console.log("");let B=process.env.ANTHROPIC_API_KEY?"api":"subscription",ae=zn(V,"The write");if(ae){for(let ge of ae)console.log(K(ge));continue}for(let ge of qd(V.results,k,B,o??r))console.log(V.ok?X(ge):K(ge));if(console.log(d(ln(Ot(W,V.results,V.totalCostUsd)))),V.ok)try{iw(t.cwd,l.map(ge=>`${c}/${ge}`),{writtenCap:hP,reviewedCap:0,checkedCap:0})}catch{}let me=Ur(t.cwd,c,l),Re=Vd(me);Re&&console.log(K(Re));let Ie=e.includes("--skip-style")?null:Kd(me);if(Ie){console.log(d(`Fixing ${Ie.errors.length} style error(s) in ${Ie.articles} article(s) \u2014 one pass\u2026`));let{model:ge}=ow(t.cwd,"standard"),we=[];try{for await(let Z of rw({cwd:t.cwd,partitions:Ie.partitions,promptFor:Ie.promptFor,concurrency:3,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:ge}))if(Z.type==="partition_status"&&Z.status!=="running")console.log(Z.status==="done"?X(` \u2713 ${Z.label}`):L(` \u2717 ${Z.label}`));else if(Z.type==="run_done"&&!Z.allEmpty&&!Z.blocked){let Ee=sw(Ie.partitions,Z.results);Ee.notRun.length&&console.log(K(`\u26A0 ${Ee.notRun.length} style-fix batch${Ee.notRun.length===1?"":"es"} never started \u2014 their articles are untouched.`)),we.push(...Ee.covered)}}catch(Z){console.log(K(`Style fix pass failed: ${Z.message}`))}if(we.length>0)try{iw(t.cwd,we,ft("lint"))}catch{}for(let Z of Yd(Ie.errors.length,Ur(t.cwd,c,l)))console.log(Z.startsWith("\u2713")?X(Z):K(Z))}{let ge=sw(k,V.results),we={aborted:!!V.aborted,partitions:k.length,failed:ge.failed.length,notRun:ge.notRun.length,leftBehind:Ur(t.cwd,c,l).filter(Z=>Z.severity==="error").length,...V.blocked?{blocked:V.blocked}:{},...V.allEmpty?{allEmpty:!0}:{},...V.bailedEmpty?{bailedEmpty:!0}:{}};if(Xt(we)){let Z=`/write${o?` --scope ${o}`:""}${e.includes("--rewrite")?" --rewrite":""}`;for(let Ee of Ke(t.cwd,Z))console.log(X(Ee))}}}}catch(V){console.log(L(`Write run failed: ${V.message}`))}return console.log(""),{kind:"continue"}}oe();import{existsSync as wP,readdirSync as cw,statSync as uw}from"node:fs";import{join as dw}from"node:path";import{inputDir as bP,readProjectConfig as kP}from"document360-engine";var pw=/\.(md|markdown|pdf|txt)$/i;function Xd(e){let t=bP(e);if(!wP(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of cw(t)){let s=dw(t,r),i=!1;try{i=uw(s).isDirectory()}catch{continue}if(i){if(r.startsWith("."))continue;let a=$P(s);a>0&&n.push({name:r,docCount:a})}else pw.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function $P(e){let t=0;for(let n of cw(e))try{uw(dw(e,n)).isFile()&&pw.test(n)&&t++}catch{}return t}function Qd(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 dl(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(`
408
- `)}var Jd="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function hw(e,t){let n=t?.cwd??process.cwd();if(!kP(n))return console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=Xd(n);if(o.length===0&&r===0)return console.log(d(Jd)),{kind:"continue"};let s=e.join(" ").trim();if(!s){if(o.length>1){console.log(d("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let c of o)console.log(` ${c.name} ${d(`(${c.docCount} doc${c.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let a=o[0]?.name??"";return{kind:"forward-to-agent",prompt:dl(a),display:a?`/draft ${a}`:"/draft"}}let i=Qd(o,s);return{kind:"forward-to-agent",prompt:dl(i??"",i?void 0:s),display:`/draft ${s}`}}oe();import{listOpenForDocs as vP,readProjectConfig as xP}from"document360-engine";function Zd(e){try{return vP(e).filter(t=>t.kind==="request").length}catch{return 0}}function ep(e){let t=e.includes("--push")||e.includes("--publish"),n=e.includes(jt),o=e.filter(r=>!r.startsWith("--")).join(" ").trim();return{push:t,skipReview:n,what:o}}function tp(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(`
409
- `)}var np="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 fw(e,t){let n=t?.cwd??process.cwd();if(!xP(n))return console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"};let{push:o,what:r}=ep(e);if(!r&&Zd(n)===0)return console.log(d(np)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --push":""}`;return{kind:"forward-to-agent",prompt:tp(r),display:s}}oe();import{search as RP}from"@inquirer/prompts";import{findByName as SP,getSession as CP,listSessions as PP,relativeTime as gw}from"document360-engine";async function yw(e,t){let n=PP(t.cwd).filter(o=>o.uuid!==t.currentUuid());if(n.length===0)return console.log(d("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=SP(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(L(`No session matches "${o}".`)),mw(n),{kind:"continue"})}if(!process.stdin.isTTY)return mw(n),console.log(d("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>RP({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} ${gw(a.updatedAt)}`,value:a.uuid,description:a.firstPrompt.slice(0,100)}))}})),r=CP(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function mw(e){console.log("");for(let t of e.slice(0,15))console.log(` ${ee(t.name)} ${d(gw(t.updatedAt))}`),console.log(` ${d(t.firstPrompt.slice(0,80))}`);console.log("")}oe();import{renameSession as TP}from"document360-engine";function op(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 ww(e,t){let n=op(e.join(" "));if(!n)return console.log(L("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(TP(o,n)?console.log(X(`\u2713 Session renamed to "${n}"`)):console.log(L("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(X(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as bw,readProjectConfig as AP,writeProjectConfig as EP}from"document360-engine";oe();function rp(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=AP(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 bw().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},EP(o,e),null):`Unknown environment "${r}". Known: ${bw().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function kw(e,t){let n=e[0];if(!n)return oa(t.cwd),{kind:"continue"};if(n==="add"){let o=rp(t.cwd,e[1],e[2]);return o?(console.log(L(o)),{kind:"continue"}):(console.log(X(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${ee(`/profile ${e[1]}`)} then ${ee("/login")}`),console.log(d(" Until you switch, this repo keeps using the current profile\u2019s environment.")),{kind:"continue"})}return ra(t.cwd,n),sa(t.cwd,n),console.log(d(" Restarting agent for the new profile\u2026")),{kind:"clear"}}oe();import{select as NP}from"@inquirer/prompts";import{readProjectConfig as DP,readUserConfig as $w,resolveModelSetting as sp,writeUserConfig as vw}from"document360-engine";var _t=[{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 pl(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=_t.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function jP(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 ni(e,t){let n=()=>sp(e).model;if(t==="default"){let s=$w();return s.defaultModel?(delete s.defaultModel,vw(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${sp(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}}vw({...$w(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=DP(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 xw(e,t){let n=e[0]?.trim();if(!n){let i=sp(t.cwd);if(!process.stdin.isTTY)return console.log(`${Qe("Model:")} ${ee(i.model)}${i.source==="auto"?d(" (auto)"):""}`),console.log(d(` source: ${jP(i)}`)),console.log(d(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let a=pl(i),c;try{c=await t.withPausedInput(()=>NP({message:`Select model (current: ${i.model}${i.source==="auto"?" \xB7 auto":""})`,default:_t[a].value,choices:_t.map((k,T)=>({name:`${k.label}${T===a?" \u2714":""}`,value:k.value,description:k.desc}))}))}catch{return console.log(d("Cancelled.")),{kind:"continue"}}let{lines:l,changed:f,effective:g}=ni(t.cwd,c??"default");for(let k of l)console.log(k.startsWith("\u26A0")?K(k):k.startsWith("\u2713")?X(k):d(k));return f&&await t.setModel(g),{kind:"continue"}}let{lines:o,changed:r,effective:s}=ni(t.cwd,n);for(let i of o)console.log(i.startsWith("\u26A0")?K(i):i.startsWith("\u2713")?X(i):d(i));return r&&await t.setModel(s),{kind:"continue"}}ml();async function Tw(e,t){return await t.withPausedInput(()=>kr(t.cwd)),{kind:"clear"}}async function Aw(e,t){return await t.withPausedInput(()=>ea(t.cwd,t.profileName)),{kind:"clear"}}oe();import{resolveActiveProfile as rT}from"document360-engine";async function Ew(e,t){let n=!1;try{n=rT(t.cwd).production}catch{}return n?(console.log(K("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(d("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}oe();var Nw=async(e,t)=>{try{await t.withPausedInput(()=>na({}))}catch(n){if(console.log(L(`Login failed: ${n.message}`)),!wa(t.cwd,t.profileName))return console.log(d("Your Document360 session still isn't working \u2014 run /login to try again.")),{kind:"continue",ownNext:!0}}return{kind:"continue"}};import{resolveActiveProfile as sT,clearTokens as iT,clearProfileProject as aT,listStoredSessions as lT,tokensProjectId as cT}from"document360-engine";oe();async function Dw(e,t){let n,o,r,s;try{let g=sT(t.cwd,t.profileName);n=g.name,o=g.connection.name,r=g.project.projectId,s=g.project.projectName}catch(g){return console.log(L(g.message)),{kind:"continue"}}let i=e.includes("--all-projects"),a=lT(n).filter(g=>{let k=cT(g);return!!k&&k!==r}).length,c=iT(n,i?void 0:r);aT(t.cwd,n);let l=i||a===0?"":` Your sign-in for ${a} other project${a===1?"":"s"} is untouched (/logout --all-projects clears those too).`;console.log(c?i?X(`\u2713 Signed out of every Document360 project for "${n}" and cleared this repo's project/workspace selection.`):X(`\u2713 Signed out of ${s?`"${s}"`:`"${n}"`} and cleared its project/workspace selection.${l}`):d(`Profile "${n}" was not signed in. Cleared any project/workspace selection.${l}`)),console.log(d(`Run /login to sign back in to "${n}" (the ${o} environment) and pick a project.`));let f=Un(t.cwd,t.profileName);return console.log(f?K(`\u26A0 ${f.why}. Signing out doesn\u2019t change the environment \u2014 ${f.cmd} does.`):d(" Different environment? That comes from the profile, not the login \u2014 /profile add <environment>.")),{kind:"continue"}}import{existsSync as Lw,readFileSync as lp}from"node:fs";import{homedir as wT}from"node:os";import{basename as bT,join as ii}from"node:path";import{readProjectConfig as kT,DEFAULT_OUTPUT_DIR as $T,existingAnnotatedShotPath as FF,resolveOutputDir as vT,shotArtifacts as xT}from"document360-engine";import $t from"picocolors";import{annotationsPath as uT,resolveOutputDir as dT,readProjectConfig as pT,DEFAULT_OUTPUT_DIR as hT,existingAnnotatedShotPath as fT}from"document360-engine";function mT(e){let n=e.filter(o=>o!=="--all"&&o!=="-a").find(o=>!o.startsWith("-"));return n?{mode:"single",id:n}:{mode:"all"}}function ri(e){return e.filter(t=>t.state==="annotated").map(t=>t.id)}function un(e,t){let n=dT(e,pT(e)?.outputDir??hT),o=new Map(Ue(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(fT(n,i))}`,` facts: ${r(uT(n,i))}`,` article: ${a}`].join(`
407
+ `)+r+s}function zd(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: ${$t(r)}\u2013${$t(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function Xd(e,t,n,o){let r=S=>t[S.index]?.paths.length??0,s=e.filter(S=>S.ok),i=e.filter(S=>!S.ok),a=e.reduce((S,C)=>S+r(C),0),c=s.reduce((S,C)=>S+r(C),0),l=e.reduce((S,C)=>S+C.costUsd,0),f=e.reduce((S,C)=>S+C.outputTokens,0),g=n==="api"?`${$t(l)} total`:Or(f),$=`${s.length}/${e.length} batch${e.length===1?"":"es"} completed`,T=S=>`${S} article${S===1?"":"s"}`,A=[];if(i.length===0){A.push(`Wrote ${T(a)} (${$}) successfully \xB7 ${g}.`);let S=o?` ${o}`:"",C=o?"/push":"/push --all",x=o?`/screenshot author ${o}`:"/screenshot author --all";A.push("Next \u2014 an editorial review, because these were written by an AI:"),A.push(`/review${S} --fix`),A.push(`It reads every article and applies its fixes; ${C} then pushes them up (add screenshots first with ${x} if you want them).`)}else{A.push(`Wrote ${c}/${T(a)} (${$}) \xB7 ${g}.`),A.push(`${i.length} batch${i.length===1?"":"es"} failed \u2014 re-run /write${o?` --scope ${o}`:""} to retry the rest:`);for(let S of i)A.push(` \u2717 ${S.label}${S.error?` \u2014 ${S.error}`:""}`);i.some(S=>/rate-limited/i.test(S.error??""))&&(A.push("Claude rate-limited this run, not your usage allowance. Retry one batch at a time:"),A.push(`/write${o?` --scope ${o}`:""} --concurrency 1`)),i.some(S=>/usage limit has been reached/i.test(S.error??""))&&A.push(pP)}return A}function Fr(e,t,n){try{return fP({cwd:e,paths:n.map(o=>`${t}/${o}`)}).filter(o=>!o.baselined)}catch{return[]}}function Qd(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 Jd(e){let t=e.filter(o=>o.severity==="error");if(t.length===0)return null;let n=mP(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 fl(t.filter(s=>r.has(s.path)))}}}function Zd(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 ml(e,t,n){let o=(qd(e)?.docsDir??fw).replace(/\/+$/,""),r=t.map(a=>a.path);if(n.path){let a=CP(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=PP(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=Kn(e,o,s);if(i.length===0){let a=n.scope?` under "${n.scope}"`:"",c=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${c} --rewrite to regenerate them all.`}}return{docsDir:o,targets:i,planCount:r.length}}function ep(e,t,n){let{targets:o}=ml(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:Gd(s),count:i}))}async function mw(e,t){if(!qd(t.cwd))return console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"};if(ni(e)){for(let Y of lw(t.cwd,t.profileName))console.log(d(Y));return{kind:"continue"}}let n=yP(t.cwd,(qd(t.cwd)?.docsDir??fw).replace(/\/+$/,""));if(n.length===0)return console.log(L("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};if(eo("write",e)){let Y=ep(t.cwd,n,{rewrite:oi(e).rewrite}),B=Mr(t.cwd,"write",e,t.profileName,Y);if(B.length>0){for(let ue of B)console.log(d(ue));return{kind:"continue"}}}let{scope:o,path:r,preview:s,concurrency:i,rewrite:a}=oi(e),{docsDir:c,targets:l,reason:f,rewriting:g}=ml(t.cwd,n,{scope:o,path:r,rewrite:a});if(l.length===0)return console.log(f?q(f):q("Nothing to write.")),{kind:"continue"};g&&console.log(q(`--rewrite: regenerating ${l.length} already-written article${l.length===1?"":"s"} (overwrites them; git has your baseline).`));let $=gP(l),T=Vd(i),{model:A,forced:S}=uw(t.cwd,"standard"),C=!!r;if(s&&!C){let Y=hP({files:Yd(t.cwd,n,l),op:"write",model:A});o&&console.log(d(`Scope: ${o} (${l.length} pending).`));for(let B of zd($,Y,T))console.log(B);return console.log(d(`Model: ${A}${S?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(d(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}let x=wP(t.cwd),E=kP(t.cwd),j=l.filter(Y=>vP(x,Y).length>0).length;j>0&&console.log(d(` ${j} of these ${j===1?"has":"have"} reviewer comments \u2014 the writer gets them.`)),console.log(d(`Writing ${l.length} article${l.length===1?"":"s"} in ${$.length} batch${$.length===1?"":"es"} (\u2264${T} agents at once) on ${A}\u2026`)),console.log(d(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let W=Date.now();try{for await(let Y of dw({cwd:t.cwd,partitions:$,promptFor:B=>Kd(B,c,{rewrite:g||C,reviewerNotes:bP(x,B.paths),openGaps:$P(t.cwd,B.paths),readerContract:E}),concurrency:T,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:A}))if(Y.type==="partition_status")Y.status==="running"?console.log(d(` \u25B8 ${Y.label} \u2014 writing\u2026`)):Y.status==="done"?console.log(Q(` \u2713 ${Y.label}`)):console.log(L(` \u2717 ${Y.label}`));else if(Y.type==="run_done"){console.log("");let B=process.env.ANTHROPIC_API_KEY?"api":"subscription",ue=Xn(Y,"The write");if(ue){for(let ge of ue)console.log(q(ge));continue}for(let ge of Xd(Y.results,$,B,o??r))console.log(Y.ok?Q(ge):q(ge));if(console.log(d(cn(Ft(W,Y.results,Y.totalCostUsd)))),Y.ok)try{hw(t.cwd,l.map(ge=>`${c}/${ge}`),{writtenCap:xP,reviewedCap:0,checkedCap:0})}catch{}let fe=Fr(t.cwd,c,l),Re=Qd(fe);Re&&console.log(q(Re));let Ie=e.includes("--skip-style")?null:Jd(fe);if(Ie){console.log(d(`Fixing ${Ie.errors.length} style error(s) in ${Ie.articles} article(s) \u2014 one pass\u2026`));let{model:ge}=uw(t.cwd,"standard"),we=[];try{for await(let Z of dw({cwd:t.cwd,partitions:Ie.partitions,promptFor:Ie.promptFor,concurrency:3,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:ge}))if(Z.type==="partition_status"&&Z.status!=="running")console.log(Z.status==="done"?Q(` \u2713 ${Z.label}`):L(` \u2717 ${Z.label}`));else if(Z.type==="run_done"&&!Z.allEmpty&&!Z.blocked){let Ae=pw(Ie.partitions,Z.results);Ae.notRun.length&&console.log(q(`\u26A0 ${Ae.notRun.length} style-fix batch${Ae.notRun.length===1?"":"es"} never started \u2014 their articles are untouched.`)),we.push(...Ae.covered)}}catch(Z){console.log(q(`Style fix pass failed: ${Z.message}`))}if(we.length>0)try{hw(t.cwd,we,mt("lint"))}catch{}for(let Z of Zd(Ie.errors.length,Fr(t.cwd,c,l)))console.log(Z.startsWith("\u2713")?Q(Z):q(Z))}{let ge=pw($,Y.results),we={aborted:!!Y.aborted,partitions:$.length,failed:ge.failed.length,notRun:ge.notRun.length,leftBehind:Fr(t.cwd,c,l).filter(Z=>Z.severity==="error").length,...Y.blocked?{blocked:Y.blocked}:{},...Y.allEmpty?{allEmpty:!0}:{},...Y.bailedEmpty?{bailedEmpty:!0}:{}};if(Qt(we)){let Z=`/write${o?` --scope ${o}`:""}${e.includes("--rewrite")?" --rewrite":""}`;for(let Ae of Ye(t.cwd,Z))console.log(Q(Ae))}}}}catch(Y){console.log(L(`Write run failed: ${Y.message}`))}return console.log(""),{kind:"continue"}}oe();import{existsSync as TP,readdirSync as gw,statSync as yw}from"node:fs";import{join as ww}from"node:path";import{inputDir as AP,readProjectConfig as EP}from"document360-engine";var bw=/\.(md|markdown|pdf|txt)$/i;function tp(e){let t=AP(e);if(!TP(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of gw(t)){let s=ww(t,r),i=!1;try{i=yw(s).isDirectory()}catch{continue}if(i){if(r.startsWith("."))continue;let a=NP(s);a>0&&n.push({name:r,docCount:a})}else bw.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function NP(e){let t=0;for(let n of gw(e))try{yw(ww(e,n)).isFile()&&bw.test(n)&&t++}catch{}return t}function np(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 gl(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(`
408
+ `)}var op="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function kw(e,t){let n=t?.cwd??process.cwd();if(!EP(n))return console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=tp(n);if(o.length===0&&r===0)return console.log(d(op)),{kind:"continue"};let s=e.join(" ").trim();if(!s){if(o.length>1){console.log(d("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let c of o)console.log(` ${c.name} ${d(`(${c.docCount} doc${c.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let a=o[0]?.name??"";return{kind:"forward-to-agent",prompt:gl(a),display:a?`/draft ${a}`:"/draft"}}let i=np(o,s);return{kind:"forward-to-agent",prompt:gl(i??"",i?void 0:s),display:`/draft ${s}`}}oe();import{listOpenForDocs as DP,readProjectConfig as jP}from"document360-engine";function rp(e){try{return DP(e).filter(t=>t.kind==="request").length}catch{return 0}}function sp(e){let t=e.includes("--push")||e.includes("--publish"),n=e.includes(Ot),o=e.filter(r=>!r.startsWith("--")).join(" ").trim();return{push:t,skipReview:n,what:o}}function ip(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(`
409
+ `)}var ap="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 $w(e,t){let n=t?.cwd??process.cwd();if(!jP(n))return console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"};let{push:o,what:r}=sp(e);if(!r&&rp(n)===0)return console.log(d(ap)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --push":""}`;return{kind:"forward-to-agent",prompt:ip(r),display:s}}oe();import{search as IP}from"@inquirer/prompts";import{findByName as LP,getSession as OP,listSessions as _P,relativeTime as xw}from"document360-engine";async function Rw(e,t){let n=_P(t.cwd).filter(o=>o.uuid!==t.currentUuid());if(n.length===0)return console.log(d("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=LP(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(L(`No session matches "${o}".`)),vw(n),{kind:"continue"})}if(!process.stdin.isTTY)return vw(n),console.log(d("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>IP({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} ${xw(a.updatedAt)}`,value:a.uuid,description:a.firstPrompt.slice(0,100)}))}})),r=OP(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function vw(e){console.log("");for(let t of e.slice(0,15))console.log(` ${ee(t.name)} ${d(xw(t.updatedAt))}`),console.log(` ${d(t.firstPrompt.slice(0,80))}`);console.log("")}oe();import{renameSession as MP}from"document360-engine";function lp(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 Sw(e,t){let n=lp(e.join(" "));if(!n)return console.log(L("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(MP(o,n)?console.log(Q(`\u2713 Session renamed to "${n}"`)):console.log(L("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 Cw,readProjectConfig as FP,writeProjectConfig as UP}from"document360-engine";oe();function cp(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=FP(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 Cw().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},UP(o,e),null):`Unknown environment "${r}". Known: ${Cw().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function Pw(e,t){let n=e[0];if(!n)return la(t.cwd),{kind:"continue"};if(n==="add"){let o=cp(t.cwd,e[1],e[2]);return o?(console.log(L(o)),{kind:"continue"}):(console.log(Q(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${ee(`/profile ${e[1]}`)} then ${ee("/login")}`),console.log(d(" Until you switch, this repo keeps using the current profile\u2019s environment.")),{kind:"continue"})}return ca(t.cwd,n),ua(t.cwd,n),console.log(d(" Restarting agent for the new profile\u2026")),{kind:"clear"}}oe();import{select as WP}from"@inquirer/prompts";import{readProjectConfig as BP,readUserConfig as Tw,resolveModelSetting as up,writeUserConfig as Aw}from"document360-engine";var Ut=[{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 yl(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=Ut.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function HP(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 ri(e,t){let n=()=>up(e).model;if(t==="default"){let s=Tw();return s.defaultModel?(delete s.defaultModel,Aw(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${up(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}}Aw({...Tw(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=BP(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 Ew(e,t){let n=e[0]?.trim();if(!n){let i=up(t.cwd);if(!process.stdin.isTTY)return console.log(`${Qe("Model:")} ${ee(i.model)}${i.source==="auto"?d(" (auto)"):""}`),console.log(d(` source: ${HP(i)}`)),console.log(d(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let a=yl(i),c;try{c=await t.withPausedInput(()=>WP({message:`Select model (current: ${i.model}${i.source==="auto"?" \xB7 auto":""})`,default:Ut[a].value,choices:Ut.map(($,T)=>({name:`${$.label}${T===a?" \u2714":""}`,value:$.value,description:$.desc}))}))}catch{return console.log(d("Cancelled.")),{kind:"continue"}}let{lines:l,changed:f,effective:g}=ri(t.cwd,c??"default");for(let $ of l)console.log($.startsWith("\u26A0")?q($):$.startsWith("\u2713")?Q($):d($));return f&&await t.setModel(g),{kind:"continue"}}let{lines:o,changed:r,effective:s}=ri(t.cwd,n);for(let i of o)console.log(i.startsWith("\u26A0")?q(i):i.startsWith("\u2713")?Q(i):d(i));return r&&await t.setModel(s),{kind:"continue"}}kl();async function Lw(e,t){return await t.withPausedInput(()=>br(t.cwd)),{kind:"clear"}}async function Ow(e,t){return await t.withPausedInput(()=>sa(t.cwd,t.profileName)),{kind:"clear"}}oe();import{resolveActiveProfile as mT}from"document360-engine";async function _w(e,t){let n=!1;try{n=mT(t.cwd).production}catch{}return n?(console.log(q("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(d("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}oe();var Mw=async(e,t)=>{try{await t.withPausedInput(()=>aa({}))}catch(n){if(console.log(L(`Login failed: ${n.message}`)),!xa(t.cwd,t.profileName))return console.log(d("Your Document360 session still isn't working \u2014 run /login to try again.")),{kind:"continue",ownNext:!0}}return{kind:"continue"}};import{resolveActiveProfile as gT,clearTokens as yT,clearProfileProject as wT,listStoredSessions as bT,tokensProjectId as kT}from"document360-engine";oe();async function Fw(e,t){let n,o,r,s;try{let g=gT(t.cwd,t.profileName);n=g.name,o=g.connection.name,r=g.project.projectId,s=g.project.projectName}catch(g){return console.log(L(g.message)),{kind:"continue"}}let i=e.includes("--all-projects"),a=bT(n).filter(g=>{let $=kT(g);return!!$&&$!==r}).length,c=yT(n,i?void 0:r);wT(t.cwd,n);let l=i||a===0?"":` Your sign-in for ${a} other project${a===1?"":"s"} is untouched (/logout --all-projects clears those too).`;console.log(c?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.${l}`):d(`Profile "${n}" was not signed in. Cleared any project/workspace selection.${l}`)),console.log(d(`Run /login to sign back in to "${n}" (the ${o} environment) and pick a project.`));let f=Wn(t.cwd,t.profileName);return console.log(f?q(`\u26A0 ${f.why}. Signing out doesn\u2019t change the environment \u2014 ${f.cmd} does.`):d(" Different environment? That comes from the profile, not the login \u2014 /profile add <environment>.")),{kind:"continue"}}import{existsSync as Bw,readFileSync as hp}from"node:fs";import{homedir as AT}from"node:os";import{basename as ET,join as li}from"node:path";import{readProjectConfig as NT,DEFAULT_OUTPUT_DIR as DT,existingAnnotatedShotPath as oU,resolveOutputDir as jT,shotArtifacts as IT}from"document360-engine";import vt from"picocolors";import{annotationsPath as $T,resolveOutputDir as vT,readProjectConfig as xT,DEFAULT_OUTPUT_DIR as RT,existingAnnotatedShotPath as ST}from"document360-engine";function CT(e){let n=e.filter(o=>o!=="--all"&&o!=="-a").find(o=>!o.startsWith("-"));return n?{mode:"single",id:n}:{mode:"all"}}function ii(e){return e.filter(t=>t.state==="annotated").map(t=>t.id)}function dn(e,t){let n=vT(e,xT(e)?.outputDir??RT),o=new Map(Ue(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(ST(n,i))}`,` facts: ${r($T(n,i))}`,` article: ${a}`].join(`
410
410
  `)}).join(`
411
411
  `);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(`
412
- `)}function eo(e){return`${z("\u2192",$t.blue)}Verifying ${e} new screenshot${e===1?"":"s"} (reading each image)\u2026`}var gT=(e,t=88)=>{let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n};function Wr(e,t){if(t.length===0)return[];let n=Cn(e).shots,o=[],r=[],s=[];for(let a of t){let c=n[a]?.review;c?c.verdict==="ok"?o.push(a):r.push({id:a,reason:c.reason??"no reason recorded",repaired:!!c.repaired}):s.push(a)}let i=[""];if(i.push(`${z("\u2714",$t.green)}${$t.green(`${o.length} verified`)}`+(r.length>0?` ${$t.magenta(`\u2691 ${r.length} flagged`)}`:"")+(s.length>0?` ${$t.yellow(`? ${s.length} not verified`)}`:"")+$t.gray(` ${t.length} shot${t.length===1?"":"s"} in this pass`)),r.length>0){let a=Math.max(...r.map(l=>l.id.length));for(let l of r)i.push(` ${$t.magenta(l.id.padEnd(a))} ${$t.gray(gT(l.reason))}`);let c=r.filter(l=>l.repaired).length;i.push(`${z("\u2192",$t.magenta)}Re-capture the ${r.length} flagged: ${$t.bold("/screenshot capture --failed")}`+(c<r.length?$t.gray(` (${r.length-c} still need${r.length-c===1?"s":""} a spec fix first)`):""))}return s.length>0&&i.push(`${z("\u26A0",$t.yellow)}No verdict recorded for ${s.slice(0,3).join(", ")}${s.length>3?`, +${s.length-3}`:""} \u2014 still awaiting verification. Run ${$t.bold("/screenshot verify")} again.`),i}async function jw(e,t){let n=t?.cwd??process.cwd(),o=Io(n);o&&console.log(o);let r=Ue(n),s=mT(e);if(s.mode==="single"){let a=r.find(c=>c.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:un(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=ri(r);if(i.length===0){let a=r.filter(f=>f.state==="verified").length,c=r.filter(f=>f.state==="rejected").length,l=r.filter(f=>f.state==="captured").length;return console.log(l>0?`${l} shot${l===1?" is":"s are"} taken but not drawn on yet \u2014 /screenshot annotate finishes ${l===1?"it":"them"}, then there'll be something to verify.`:c>0?`Nothing left to verify. ${c} shot${c===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:un(n,i),display:"/screenshot verify"}}import{spawn as Iw}from"node:child_process";var ap="d360-capture";function yT(e,t){if(t&&typeof e.pid=="number")try{process.kill(-e.pid,"SIGTERM");return}catch{}try{e.kill()}catch{}}function si(e){let t=process.platform==="win32",n=!t&&e.stdio==="pipe";return new Promise((o,r)=>{let s=t?Iw(`${ap} ${e.args.join(" ")}`,{cwd:e.cwd,shell:!0,stdio:e.stdio==="inherit"?"inherit":["ignore","pipe","pipe"],env:{...process.env,NO_UPDATE_NOTIFIER:"1"}}):Iw(ap,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",c=>{i+=c.toString()}),s.stderr?.on("data",c=>{i+=c.toString()}));let a=()=>yT(s,n);e.signal?.addEventListener("abort",a,{once:!0}),s.on("error",c=>{if(e.signal?.removeEventListener("abort",a),c.code==="ENOENT"){o({exitCode:127,output:`${i}
413
- ${ap}: command not found`.trim()});return}r(c)}),s.on("close",c=>{e.signal?.removeEventListener("abort",a),o({exitCode:c??1,output:i})})})}var RT=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function cp(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:RT(t),retryBlocked:n}:{mode:"single",id:t}:{mode:"picker"}}function li(e,t){let n=Ue(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}),Tr(o,t,"capture"),Mu(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 up(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([...ig(e).filter(r=>n.has(r)),...o])].sort()}function dp(e,t){let n=e.length;if(n===0)return null;let o=_s(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(`
414
- `)}function ST(e,t){let n=kT(e)?.outputDir??$T;return xT(vT(e,n),t)}function pp(e,t,n,o){let r=ST(e,t);return(r.annotationsMtimeMs??0)>=o&&r.rawMtimeMs!==void 0?"captured":n===0?"skipped":"failed"}function _w(e){let t=/⊘[^\n—]*—\s*(.+)/.exec(e);return t?t[1].trim():null}var CT=/element is not (?:enabled|visible|stable|editable)|intercepts pointer events|outside of the viewport|element is not attached/i;function Mw(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=>CT.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(`
415
- `):hp(e)}function hp(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(`
416
- `)}var PT=/^[A-Za-z0-9._-]+$/;function fp(e){return PT.test(e.id)?si({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 Fw(e,t=wT()){try{let n=JSON.parse(lp(ii(e,".d360-writer","capture.json"),"utf8").replace(/^/,"")),o=n.projectId;if(!o)try{o=JSON.parse(lp(ii(e,"package.json"),"utf8")).name}catch{}o||=bT(e);let r=Object.keys(n.profiles??{}),s=n.defaultProfile??(r.length===1?r[0]:r.includes("staging")?"staging":r[0]);return s?Lw(ii(t,".document360-capture","auth-states",o,`${s}.json`)):!0}catch{return!0}}function Uw(e){return si({args:["auth","--auto"],cwd:e.cwd,stdio:"pipe",signal:e.signal})}function mp(e,t){return e===127||/is not recognized as an internal or external command|command not found/i.test(t)}function Ww(e){try{let t=JSON.parse(lp(ii(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 Lw(ii(e,".d360-writer","capture.json"))}function gp(){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(`
417
- `)}function Bw(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(", ")}
418
- /screenshot list --detail shows what each one needs`}function Hw(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):ai(r?.reason)!==ai(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):Ea(r?.reason??"")!==Ea(o.detail??"")?n.blockedNewReason.push(o.id):n.blockedAsBefore.push(o.id))}return n}function ai(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 Gw(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?Ar(o.detail):"no reason recorded"}`)}function Br(e,t=2){return e.length<=t?e.join(" \xB7 "):`${e.slice(0,t).join(" \xB7 ")} \xB7 +${e.length-t}`}function qw(e,t){if(!t)return[];let n=[],o=(i,a,c,l)=>{a>0&&n.push({glyph:i,label:`${a} ${c}`,tail:l})};if(o("\u2713",e.newlyCaptured.length,"newly captured",Br(e.newlyCaptured)),o("\u2717",e.newlyBroken.length,"newly broken",Br(e.newlyBroken)),o("\u2192",e.repairedNowBlocked.length,"repaired",`no longer broken \u2014 only data stands in the way \xB7 ${Br(e.repairedNowBlocked)}`),o("\u2298",e.newlyBlocked.length,"newly blocked",Br(e.newlyBlocked)),o("\u2192",e.blockedNewReason.length,"blocked on something new",`an earlier step now passes \xB7 ${Br(e.blockedNewReason)}`),o("\u2192",e.brokeDifferently.length,"broken differently",`the previous cause is fixed \xB7 ${Br(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 Vw(e){let t=e.results.filter(T=>T.outcome==="captured"),n=e.results.filter(T=>T.outcome==="skipped"),o=e.results.filter(T=>T.outcome==="failed"),r=e.unannotated??[],s=T=>T===1?"":"s";if(t.length+n.length+o.length===0)return null;let i=e.articles.length===1?`/push ${e.articles[0]}`:Se("/push","--screenshots",Dt(e.articles)),a=e.ids.length===1?`/screenshot capture ${e.ids[0]}`:"/screenshot capture",c=o[0]?.id,l=[];o.length>0&&l.push({glyph:"\u2717",cmd:`/screenshot ${c}`,why:`re-author the ${o.length===1?"broken spec":`first of ${o.length} broken specs`} \u2014 re-running fails the same way`});let f=Se("/screenshot annotate","",r.length===1?r[0]:void 0);r.length>0&&l.push({glyph:"\u25C8",cmd:f,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&&l.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&&l.push({glyph:"\u2713",cmd:i,why:`embed the ${t.length-r.length} new PNG${s(t.length-r.length)}`});let g=Math.max(...l.map(T=>T.cmd.length));return{note:l.map(T=>`${T.glyph} ${T.cmd.padEnd(g)} ${T.why}`).join(`
419
- `),cmd:o.length>0?`/screenshot ${c}`:r.length>0?f:t.length>0?i:a,tone:o.length>0||r.length>0?"warn":"info"}}function Kw(e,t){let n=new Map(Ue(e).map(o=>[o.id,o.file]));return[...new Set(t.map(o=>n.get(o)).filter(o=>!!o))].sort()}async function yp(e,t){let n=t?.cwd??process.cwd(),o=cp(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}=li(n,o.mode==="scope"?o.scope:void 0),c=up(n,a),l=(o.mode==="all"||o.mode==="scope")&&o.retryBlocked,f=o.mode==="single"?[o.id]:o.mode==="failed"?c:o.mode==="blocked"?i:o.mode==="picker"?r:[...r,...s,...l?i:[]];if(f.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(!l&&o.mode!=="single"&&o.mode!=="failed"&&o.mode!=="blocked"){let S=dp(a.filter(C=>C.state==="blocked"),"/screenshot capture --blocked");S&&console.log(S)}let g=Date.now(),k=[];for(let S of f){console.log(`\u25B6 ${S}`);try{let{exitCode:C}=await fp({cwd:n,id:S,stdio:"inherit"});k.push({id:S,outcome:pp(n,S,C,g)})}catch(C){if(C.code==="ENOENT")return console.log("d360-capture is not installed. Run: npm i -g document360-capture"),{kind:"continue"};k.push({id:S,outcome:"failed",detail:C.message})}}let T=S=>k.filter(C=>C.outcome===S).length;console.log(`\u2713 ${T("captured")} captured \xB7 \u2298 ${T("skipped")} skipped \xB7 \u2717 ${T("failed")} failed`);let A=k.filter(S=>S.outcome==="captured");return ka(n,k.map(S=>({id:S.id,outcome:S.outcome,reason:S.detail,specSource:Lo(n,S.id)})),new Date().toISOString()),A.length>0?(console.log(eo(A.length)),{kind:"forward-to-agent",prompt:un(n,A.map(S=>S.id)),display:"/screenshot verify"}):{kind:"continue"}}import{readProjectConfig as TT,DEFAULT_OUTPUT_DIR as AT,resolveOutputDir as ET,shotArtifacts as NT,annotationCurrent as DT}from"document360-engine";Cr();var Yw="0.2.29";function gl(e=bt()){return Pr(e,Yw)}function wp(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 bp(e,t){let n=Ue(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 jT=/^[A-Za-z0-9._-]+$/;function IT(e){if(!jT.test(e.id))return Promise.reject(new Error(`Not a valid spec id: "${e.id}"`));let t=["annotate",e.id,...e.force?["--force"]:[]];return si({args:t,cwd:e.cwd,stdio:e.stdio,signal:e.signal})}function LT(e,t,n,o){let r=ET(e,TT(e)?.outputDir??AT),s=NT(r,t);return(s.annotatedMtimeMs??0)>=o?"annotated":n===0&&DT(s)?"skipped":"failed"}function kp(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 ${Yw} or later, then /screenshot annotate becomes available.`}var yl=8;function zw(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:Se("/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>yl?{glyph:"\u25C8",cmd:Se("/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:Se("/screenshot verify","",e.scope),why:`${n.length} picture${n.length===1?"":"s"} ready to check \u2014 no browser needed`}}async function $p(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 IT({cwd:e.cwd,id:o,...e.force?{force:!0}:{},...e.signal?{signal:e.signal}:{},stdio:"pipe"}),i=LT(e.cwd,o,r,t);n.push({id:o,outcome:i,...i==="failed"?{detail:OT(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 vp(e,t){let n=t?.cwd??process.cwd(),o=wp(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=bt();if(!gl(r))return console.log(kp(r)),{kind:"continue"};let s=Io(n);s&&console.log(s);let i=o.mode==="scope"?o.scope:void 0,{pending:a,done:c,rows:l}=bp(n,i),f=o.mode==="all"||o.mode==="scope"?o.force:!1,g=o.mode==="single"?[o.id]:f?[...a,...c]:a;if(g.length===0){let I=c.length>0;return console.log(I?`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(l.filter(I=>I.state==="verified").map(I=>I.id)),{results:T,cliMissing:A}=await $p({cwd:n,ids:g,force:f});if(A)return console.log("d360-capture is not installed. Run: npm i -g document360-capture"),{kind:"continue"};let S=I=>T.filter(W=>W.outcome===I).length;console.log(`\u2713 ${S("annotated")} annotated`+(S("skipped")?` \xB7 ${S("skipped")} already current`:"")+(S("failed")?` \xB7 \u2717 ${S("failed")} failed`:""));for(let I of T.filter(W=>W.outcome==="failed"))console.log(` \u2717 ${I.id}${I.detail?` \u2014 ${I.detail}`:""}`);let C=T.filter(I=>I.outcome==="annotated").map(I=>I.id);if(C.length===0)return{kind:"continue"};let x=C.filter(I=>k.has(I)).length;if(x>yl)return console.log(`\u26A0 ${x} verified shots were re-drawn, so their verdicts no longer describe the picture on disk.
420
- Check them when you're ready: ${Se("/screenshot verify","",i)}`),{kind:"continue"};let E=C.filter(I=>!k.has(I)||x>0);return E.length===0?{kind:"continue"}:(console.log(eo(E.length)),{kind:"forward-to-agent",prompt:un(n,E),display:"/screenshot verify"})}function OT(e){return e.split(/\r?\n/).map(n=>n.trim()).filter(n=>n.length>0&&!/^[▶✓↕]/.test(n)).at(-1)}oe();import{existsSync as _T}from"node:fs";import{join as MT}from"node:path";import{builderChannelWired as FT,driftedAnchors as UT,readTestidRequests as WT,testidHandoffPrompt as BT,testidRequestPaths as HT,writerDir as GT}from"document360-engine";async function Hr(e,t){let n=t?.cwd;if(n){let r=qT(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(`
421
- `),display:"/screenshot checklist"}}function qT(e){let t;try{t=Ue(e)}catch{return null}let n=_T(MT(GT(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?[`${z("\u25CB",d)}No screenshots are planned yet, so there is nothing to stage.`,d(" A screenshot is planned by the article that needs it. /write adds the placeholders as it writes.")]:[`${z("\u25CB",d)}${r} screenshot${r===1?"":"s"} planned across ${s} article${s===1?"":"s"} \u2014 none captured, none with a spec, and no capture setup yet.`,d(" There is nothing to stage from yet: a checklist is built from what each spec needs, and no specs exist."),d(" /screenshot author writes the specs. Come back to /screenshot checklist once they exist and it will"),d(" tell you what data to stage and which test ids your developers still owe you."),"",d(" Free \u2014 this read your files and called nothing.")]}var Xw="-".repeat(64);function Qw(e){let t=WT(e);if(t.length===0)return null;let{mdRel:n}=HT(e),o=t.length,r=new Set(t.map(f=>f.file).filter(Boolean)).size,s=`${o} data-testid attribute${o===1?"":"s"}`,i=`${r} source file${r===1?"":"s"}`,a=BT(e,o),c=UT(t).length,l=c>0?[` \u26A0 ${c} of ${c===1?"them quotes":"them quote"} code that has changed since \u2014 still likely right,`,` but ${c===1?"it says":"they say"} so, and ${c===1?"asks":"ask"} to be found by description instead.`]:[];return FT(e)?{prompt:a,lines:[`\u{1F4CB} Developer hand-off \u2014 ${s} requested across ${i}.`,...l," 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}.`,...l,"\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.)","",Xw,a,Xw]}}Hn();oe();import{listOpenForDocs as VT,readProjectConfig as KT}from"document360-engine";function xp(e){try{return VT(e).length}catch{return 0}}function Rp(){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(`
422
- `)}async function Jw(e,t){let n=t?.cwd??process.cwd();return KT(n)?xp(n)===0?(console.log(d("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:Rp(),display:"/inbox"}:(console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"})}oe();import{askBuilder as YT,openGapQuestions as Zw,readProjectConfig as zT}from"document360-engine";function ci(e){try{return Zw(e).length}catch{return 0}}function Sp(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 Cp(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 eb(e,t,n){let o=t?.cwd??process.cwd();if(!zT(o))return console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e.join(" ").trim();if(r===""){for(let s of Cp(Zw(o)))console.log(s.startsWith(" \xB7")?d(s):s);return{kind:"continue",ownNext:!0}}try{let s=YT(o,{question:r,...n?{article:n}:{}}),i=ci(o);for(let a of Sp(s.file,i))console.log(a.startsWith("\u2713")?X(a):d(a))}catch(s){console.log(K(`Could not file the question: ${s.message}`))}return{kind:"continue",ownNext:!0}}oe();import{listOpenHints as rb,listOpenForDocs as nA,listOpenDirectives as oA,readProjectConfig as sb,computeSyncStatus as rA,planPull as sA,applyPull as iA,planImport as aA,applyImport as lA,pullDocsUpdates as cA,handoffAvailable as uA,readProductBriefState as dA,readDiscoveryQueue as pA,partitionOpenHints as ib,askAboutUnfinishedHint as hA,briefMoved as fA}from"document360-engine";oe();import{readProjectConfig as XT,writeProjectConfig as tb,reconcileDocsGit as QT,pullDocsUpdates as JT,probeGitState as ZT,resolveGitHandoff as nb,handoffAvailable as eA}from"document360-engine";var ui=e=>e===1?"":"s";function to(e,t){let n=o=>{let r=(o??"").split(`
423
- `).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 wl(e,t){let n=nb(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=ZT(e);if(!o)return[{tone:"info",text:"Sharing: unavailable \u2014 this folder is not a git repository."}];if(!o.upstream)return[{tone:"warn",text:z("\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:z("\u26A0")+`${o.ahead} change${ui(o.ahead)} not shared yet \u2014 run /share`}):s.push({tone:"ok",text:z("\u2713")+"Everything is shared with your team."}),s}function Pp(e,t,n){tb({...t,gitHandoff:{commit:n,push:n}},e);let o=n?{tone:"ok",text:z("\u2713")+"Sharing on \u2014 d360-writer will save and send its own work from now on."}:{tone:"ok",text:z("\u2713")+"Sharing off \u2014 d360-writer will leave its work for your coding agent to commit."};return n?[o,...wl(e,{...t,gitHandoff:{commit:!0,push:!0}})]:[o]}async function bl(e,t){let n=[],o=nb(t);if(!o.commit)return{lines:[{tone:"info",text:to("disabled")}],changed:!1};let r=t;o.push==="unconfirmed"&&eA(e,t)&&(r={...t,gitHandoff:{commit:!0,push:!0}},tb(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 JT(e);if(s.ok&&s.pulled>0){let l=[s.newHints>0?`${s.newHints} new hint${ui(s.newHints)}`:null,s.newMessages>0?`${s.newMessages} new message${ui(s.newMessages)}`:null].filter(Boolean);n.push({tone:"ok",text:z("\u2B07")+`Got your builder's latest${l.length?` \u2014 ${l.join(", ")}`:""}.`})}else!s.ok&&s.reason!=="no-upstream"&&s.reason!=="no-git"&&n.push({tone:"warn",text:z("\u26A0")+to(s.reason,s.detail)});let i=await QT(e,r);if(i.commit&&!i.commit.ok)return n.push({tone:"warn",text:z("\u26A0")+to(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:z("\u2713")+`Saved ${a} change${ui(a)} to the docs folder.`}),i.push&&!i.push.ok)return n.push({tone:"warn",text:z("\u26A0")+to(i.push.reason,i.push.detail)}),{lines:n,changed:a>0};let c=i.push?.ok?i.push.pushed:0;return c>0?n.push({tone:"ok",text:z("\u2B06")+`Shared ${c} change set${ui(c)} with your team.`}):a===0&&(s.ok&&s.pulled===0)?n.push({tone:"ok",text:z("\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||c>0||s.ok&&s.pulled>0}}var tA={ok:X,info:Te,warn:K,error:L};async function ob(e,t){let n=t.cwd,o=XT(n);if(!o)return console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase(),s=a=>{for(let c of a)console.log(tA[c.tone](c.text))};if(r==="status")return s(wl(n,o)),{kind:"continue"};if(r==="on"||r==="off")return s(Pp(n,o,r==="on")),{kind:"continue"};if(r)return console.log(L(`Unknown option "${r}". Use /share, /share status, /share on, or /share off.`)),{kind:"continue"};console.log(d("Exchanging work with your team\u2026"));let{lines:i}=await bl(n,o);return s(i),{kind:"continue"}}function Jt(e){let t=0,n=0,o=0,r=0,s=0,i=0;try{let c=ib(e,rb(e));t=c.actionable.length,n=c.held.length,o=c.held.filter(l=>l.asked).length}catch{}try{let c=nA(e);r=c.filter(l=>l.kind==="request").length,s=c.filter(l=>l.kind==="answer").length}catch{}try{i=oA(e).length}catch{}let a=!1;try{a=fA(e)}catch{}return{hints:t,requests:r,answers:s,directives:i,held:n,heldAsked:o,briefMoved:a}}async function Ep(e){let t=sb(e);if(!t)return[];if(!uA(e,t))return[];let n=await cA(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 ${to(n.reason,n.detail)}`}]}function Gr(e){let t=[];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"}`);let n=t.join(", ");return e.briefMoved?n?`${n} and an updated product brief`:"an updated product brief":n||null}function Np(e){let t=Gr(e);return t?`Catching up on ${t}\u2026`:"Nothing queued from your builder \u2014 checking Document360 for reviewer comments and feedback\u2026"}function kl(e){let t={...e.queued,briefMoved:!1},n=Gr(t);if(n)return{tone:"warn",note:`${z("\u26A0")}That run finished without writing anything, and ${n} ${t.hints+t.requests+t.answers+t.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"}};if(e.queued.held>0){let o=e.queued.held;return{tone:"info",note:`${z("\u2139")}Nothing to write yet \u2014 your builder's ${o} note${En(o)} ${o===1?"is":"are"} waiting on code that isn't finished. ${o===1?"It stays":"They stay"} queued.`,lead:null}}return e.hold?{tone:"info",note:`${z("\u2139")}No articles changed \u2014 product discovery is still open, so new overview and concept pages are on hold.`,lead:null}:{tone:"info",note:`${z("\u2713")}Nothing needed writing \u2014 no articles changed.`,lead:null}}function Dp(e){return{push:e.includes("--push")||e.includes("--publish"),skipReview:e.includes(jt),includeUnfinished:e.includes($l)}}var $l="--include-unfinished";function di(e){let t={hold:!1,openQuestions:0,answersPending:0};try{let n=dA(e);return!n||n.status==="confident"?t:{hold:!0,...pA(e)}}catch{return t}}function jp(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:`${z("\u2139")}Product discovery is still open \u2014 ${n} answer${En(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:`${z("\u26A0")}Product discovery isn't finished \u2014 ${n} question${En(n)} still with your builder.`},{tone:"warn",text:` ${t} until the brief is settled.`}]}return[{tone:"warn",text:`${z("\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 Ip(e){try{return ib(e,rb(e)).held}catch{return[]}}function Lp(e,t){let n=0;for(let o of t)try{hA(e,{hintFile:o.file,surface:o.surface,sources:o.unfinished})&&(n+=1)}catch{}return n}var Tp=3;function Op(e,t){if(e.length===0)return[];let n=e.length,o=[];if(e.every(r=>r.unfinished.length===0))return o.push({tone:"warn",text:`${z("\u26A0")}Your repository is in the middle of a merge, so the code isn't settled yet.`}),o.push({tone:"warn",text:` I've left your builder's ${n} note${En(n)} for now. Finish the merge and I'll pick ${n===1?"it":"them"} up.`}),o;o.push({tone:"warn",text:`${z("\u26A0")}${n} of your builder's note${En(n)} describe${n===1?"s":""} code that isn't finished, so I've left ${n===1?"its page":"those pages"} for now:`});for(let r of e.slice(0,Tp))o.push({tone:"warn",text:` \xB7 ${r.surface||r.file}`});return n>Tp&&o.push({tone:"warn",text:` \xB7 and ${n-Tp} more`}),o.push({tone:"info",text:t>0?` I've asked your builder whether ${t===1?"it is":"they're"} done. Everything else is written as normal.`:` Your builder already has my question about ${n===1?"it":"those"}. Everything else is written as normal.`}),o}function _p(e={hold:!1,openQuestions:0,answersPending:0},t={held:0,includeUnfinished:!1},n=!1){let o=["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(t.held>0&&o.push(t.includeUnfinished?"2b. THE USER ASKED FOR THE UNFINISHED WORK TOO. Some hints came back under `held` rather than in the main list: the files they cite have uncommitted changes, so the surface they describe is still being edited and what you read may change before it ships. Document them anyway this run, as drafts, grounded strictly in the code as it stands \u2014 never in what you expect it to become. Treat them as normal hints otherwise (resolve the article the same way, stamp them consumed). In your closing summary name each one and say plainly that the code behind it was still being edited, so those pages want a re-read once it lands.":"2b. SOME HINTS ARE HELD, and they are not yours to act on this run. They came back under `held` rather than in the main list because the files they cite have uncommitted changes: the builder is still typing that surface, so anything you documented from it would describe something readers will not recognise. Do NOT document a held hint, do NOT go reading its code to judge it for yourself, and do NOT stamp it consumed \u2014 it stays queued and returns on its own once the code lands. The builder has ALREADY been asked whether each one is finished, so do not file another question about them. In your closing summary, name what is waiting in plain words and say that nothing else is blocked. Then write everything else normally."),n&&o.push("2c. THE BUILDER HAS REWRITTEN THEIR ARCHITECTURE BRIEF since the docs last caught up. Read every `.md` in `.d360-writer/architecture/` (except CREATOR-NOTES.md, which is the human owner's and is covered elsewhere) and work out what is NEW or CHANGED in it versus what the existing articles say. A brief refresh is a hand-off like any other, and it is the one that arrives without a hint file: the builder may have described a surface nobody has documented, corrected how an existing one actually works, or changed the product's own vocabulary. Treat what you find as proposals for step 4 \u2014 a new article, an update to an existing one, or nothing at all when the change was internal or editorial. Do NOT rewrite the brief, and do NOT treat it as a directive: it is grounding, and what the docs owe it is your judgment."),e.hold){let r=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${En(e.openQuestions)}`:"continue product discovery to settle the brief";o.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: ${r}.`)}return o.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)."),o.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.'),o.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."),o.join(`
424
- `)}var mA={status:rA,plan:sA,apply:iA,planImport:aA,applyImport:lA};async function Mp(e,t=mA){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 Ap=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,En=e=>e===1?"":"s";function Fp(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${En(e.pulled.length)} into local: ${Ap(e.pulled)}`),e.imported.length&&t.push(`\u2713 Imported ${e.imported.length} new portal article${En(e.imported.length)} into local drafts: ${Ap(e.imported)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${En(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${Ap(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 ab(e,t){let n=t?.cwd??process.cwd();if(!sb(n))return console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Je(n,t?.profileName);if(!o.ok)return console.log(L(o.reason)),{kind:"continue"};let{push:r,includeUnfinished:s}=Dp(e);for(let k of await Ep(n))console.log(k.tone==="ok"?X(k.text):K(k.text));console.log(d("Reconciling with Document360 (pulling any portal changes)\u2026"));let i=await Mp({cwd:n,profileName:t?.profileName});for(let k of Fp(i))console.log(k.startsWith("\u2713")?X(k):k.startsWith("\u2139")?d(k):K(k));let a=di(n);for(let k of jp(a))console.log(k.tone==="warn"?K(k.text):d(k.text));let c=Ip(n),l=s?[]:c,f=Lp(n,l);for(let k of Op(l,f))console.log(k.tone==="warn"?K(k.text):d(k.text));let g=Jt(n);return console.log(d(Np(g))),{kind:"forward-to-agent",prompt:_p(a,{held:c.length,includeUnfinished:s},g.briefMoved),display:`/catch-up${r?" --push":""}${s?` ${$l}`:""}`}}oe();import{resolveActiveProfile as kA,resolveProjectId as $A,loadProfileMap as vA,readCommentLedger as xA,isCommentOpen as RA,saveOpenCommentCount as SA,loadCommentSweepMemory as CA,recordCommentSweep as PA,planCommentSweep as TA,sweepOpenComments as AA,loadUserNames as EA,writeReviewerNotes as NA,sweptFromResult as DA,needsFullArchivePass as jA,reviewerNotesPath as IA,commentHtmlToText as lb,annotatedText as LA,readProjectConfig as OA,loadPortalLabels as _A,portalBreadcrumb as Wp,portalCategoryPath as MA,resolveModelForOperation as FA,runPartitioned as UA,snapshotArticles as WA,EMPTY_PORTAL_LABELS as BA}from"document360-engine";import Ne from"picocolors";import{CONTENT_CAP_VERSION as gA,stampArticles as yA,articlesChangedSince as wA,docsRootOf as bA}from"document360-engine";function Go(e,t,n="",o){let r=[];try{r=wA(e,t)}catch{return{changed:[],cta:null}}if(r.length===0)return{changed:[],cta:null};try{yA(e,r,{writtenCap:gA,reviewedCap:0,checkedCap:0})}catch{}let s=bA(e),i=f=>{let g=f.replace(/\\/g,"/");return g.startsWith(`${s}/`)?g.slice(s.length+1):g},a=Dt(r.map(i)),c=r.length,l=a?"/push":"/push --all";try{return{changed:r,cta:It(e,{text:`${n}${c} article${c===1?"":"s"} updated \u2014 ${l} saves ${c===1?"it":"them"} to Document360 as ${c===1?"a draft":"drafts"}.`,cmd:l},n,a,o)}}catch{return{changed:r,cta:null}}}var ub=300,pi=3;function HA(e,t){let n=ga(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||Gn(n).toLowerCase()===o}async function vl(e,t,n={}){let o=kA(e,t),r={profile:o.name,connection:o.connection,projectId:o.project.projectId,projectName:o.project.projectName},s=$A(r,o.project.projectId),i=vA(e,o.name);if(!i)return{threads:[],answered:[],labels:BA,scanned:0,failed:[],truncated:0,skipped:0,archived:!1};let a=xA(e,o.name),c=new Set(Object.values(a).map(B=>B.articlePath).filter(B=>!!B)),l=Object.keys(a).length===0||c.size>0,f=n.articleIds?.length?new Set(n.articleIds):null,g=!!(f||n.path||n.scope),k=Object.entries(i.articles).filter(([,B])=>!!B.id).filter(([B,ae])=>f?f.has(ae.id):n.path?B.replace(/\\/g,"/")===n.path.replace(/\\/g,"/"):n.scope?HA(B,n.scope):!0).map(([B,ae])=>({articleId:ae.id,path:B,title:ya(e,B),answered:g||(l?c.has(B):!0)})),T=k.slice(0,ub),A=await _A(r,s,o.project.workspaceId,{cwd:e,profile:o.name}),S=g||n.full?{read:T,skipped:[]}:TA(T,{live:A.live,stateOf:B=>A.articles.get(B),memory:CA(e,o.name),alwaysRead:new Set(k.filter(B=>c.has(B.path)).map(B=>B.articleId))}),C=o.project.languageCode,x=jA(e)||!!n.full,E=await AA(r,s,S.read,{isOpen:(B,ae)=>RA(a,B.id??"",ae,B),...C?{langCode:C}:{},...n.onProgress?{onProgress:n.onProgress}:{},...x?{includeResolved:x}:{}}),I=E.threads.length>0||E.answered.length>0?await EA(r,s):new Map,W=NA(e,DA(E.threads,E.answered,B=>Wp(A,B)),{userNames:I,ourReplyIds:Object.values(a).flatMap(B=>B.replyIds??[]),...x?{completeFor:S.read.filter(B=>!E.failed.some(ae=>ae.articleId===B.articleId)).map(B=>B.articleId)}:{}});g||SA(e,o.name,E.threads.length);let V=new Map;for(let B of[...E.threads,...E.answered])V.set(B.articleId,(V.get(B.articleId)??0)+1);return PA(e,o.name,{live:A.live,read:S.read.map(B=>B.articleId),failedIds:E.failed.map(B=>B.articleId),threadCounts:V,latestVersionOf:B=>A.articles.get(B)?.latestVersion}),{threads:E.threads,answered:E.answered,labels:A,scanned:E.scanned,failed:E.failed,truncated:Math.max(0,k.length-T.length),skipped:S.skipped.length,archived:W}}function GA(e,t=96){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n}var cb=500;function qA(e){let t=LA(e.comment);if(!t)return"a passage";let n=t.replace(/\s+/g," ").trim();if(n.length<=cb)return e.comment.commented_text_truncated?`\u201C${n}\u2026\u201D
425
- (Document360 sends the first 500 characters of a highlight)`:`\u201C${n}\u201D`;let o=n.slice(0,cb).trimEnd(),r=n.length-o.length;return`\u201C${o}\u2026\u201D
426
- (+${r} more character${r===1?"":"s"}${e.comment.commented_text_truncated?", and Document360 caps a highlight at 500":""})`}function VA(e,t){let n=MA(t,e.articleId);return n.length>0?n.join(" \u203A "):e.path?Gn(e.path):""}function KA(e,t){return t.articles.get(e.articleId)?.title?.trim()||e.title||(e.path?Is(e.path):e.articleId)}function YA(e,t){return Wp(t,e.articleId,{category:e.path?Gn(e.path):null,title:e.title??(e.path?Is(e.path):null)})??e.path??e.articleId}function qo(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:VA(o,t),title:KA(o,t),label:YA(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 zA=100,XA=120,db=(e,t)=>Math.max(40,Math.min(e??96,t));function pb(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`),`${Ne.bold("Reviewer comments")} ${r.join(` ${Ne.gray("\xB7")} `)}`}function Up(e){let t=[],n=o=>o===1?"":"s";if(e.skipped>0&&t.push(Ne.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(`${z("\u26A0",Ne.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=Wp(e.labels,o.articleId,{title:o.title})??o.title??o.articleId;t.push(` ${Ne.gray(`${r} \u2014 ${GA(o.error,60)}`)}`)}e.failed.length>5&&t.push(` ${Ne.gray(`+${e.failed.length-5} more`)}`),t.push(Ne.gray(" Run /comments again to retry them."))}return e.truncated&&t.push(`${z("\u26A0",Ne.yellow)}Checked the first ${ub} articles; ${e.truncated} not checked this run.`),e.archived&&(e.threads.length>0||e.answered.length>0)?t.push(Ne.gray(` Everything reviewers have written is kept in ${IA(".").replace(/\\/g,"/").replace(/^\.\//,"")} \u2014 it outlives a rewrite.`)):!e.archived&&(e.threads.length>0||e.answered.length>0)&&t.push(`${z("\u26A0",Ne.yellow)}Couldn\u2019t write the reviewer-notes file, so Document360 is still the only copy of these notes.`),t}function hi(e,t={}){let n=[],o=a=>a===1?"":"s",r=e.answered.length,s=()=>{if(!(!t.showAnswered||r===0)){n.push(` ${Ne.gray(`Answered, waiting on the reviewer (${r})`)}`);for(let a of qo(e.answered,e.labels))n.push(` ${Ne.gray(`${a.label} \u2014 ${a.threads.length} thread${o(a.threads.length)}`)}`);n.push("")}};if(e.threads.length===0){let a=r>0?` ${Ne.gray("\xB7")} ${r} answered, awaiting reviewer`:"",c=e.scanned+e.skipped;return n.push(e.skipped>0?`${z("\u2713",Ne.green)}No open reviewer comments in the ${e.scanned} article${o(e.scanned)} checked ${Ne.gray("\xB7")} ${e.skipped} of ${c} not checked${a}`:`${z("\u2713",Ne.green)}No open reviewer comments across ${e.scanned} article${o(e.scanned)}.${a}`),r>0?(n.push(Ne.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(Ne.gray(" /comments --answered lists them."))):n.push(Ne.gray(" Reviewers leave these by highlighting text in a draft in the Document360 portal and commenting on it.")),n.push(""),s(),n.push(...Up(e)),n}let i=qo(e.threads,e.labels);return n.push(pb(e)),n.push(""),n.push(Ys(["#","Category","Article","Comments"],i.map((a,c)=>[`${c+1}`,a.category||"(root)",a.title,`${a.threads.length}`]),db(t.width,zA),{plain:!0,align:["left","left","left","right"]})),n.push(""),s(),n.push(...Up(e)),n}function xl(e,t={}){let n=s=>s===1?"":"s",o=[`${Ne.gray("Category:")} ${e.category||"(root)"}`,`${Ne.gray("Article: ")} ${Ne.bold(e.title)}`,Ne.gray(`${e.threads.length} comment${n(e.threads.length)} from your reviewers`),""],r=e.threads.map(s=>{let i=[lb(s.comment.comment)||"(empty comment)"];for(let a of s.comment.replies??[])i.push(`\u21B3 ${lb(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)"),[qA(s),i.join(`
427
- `)]});return o.push(Ys(["Annotated text","Comment"],r,db(t.width,XA),{plain:!0})),o.push(""),o}function Rl(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 Bp(e,t={}){let n=qo(e.threads,e.labels);if(t.full&&n.length===1){let o=n[0];return[pb(e),"",...xl(o,t),...Up(e)]}return hi(e,t)}function QA(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 Hp(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.`,"",...QA({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(`
428
- `)}function Gp(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 JA(e,t,n){if(t.length===0)return{kind:"continue"};let o=t.reduce((g,k)=>g+k.threads.length,0),{model:r}=FA(e.cwd,"standard"),s=new Map(t.map(g=>[g.label,g])),i=t.map(g=>({label:g.label,paths:g.path?[g.path]:[]}));console.log(d(`Answering ${o} comment${o===1?"":"s"} across ${i.length} article${i.length===1?"":"s"} (\u2264${pi} 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(),c=WA(e.cwd);try{for await(let g of UA({cwd:e.cwd,partitions:i,promptFor:k=>{let T=s.get(k.label);return Hp({articleId:T.articleId,label:T.label,path:T.path,count:T.threads.length,resolve:n.resolve})},concurrency:pi,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),allowCommentResolve:n.resolve,model:r}))if(g.type==="partition_status")g.status==="running"?console.log(d(` \u25B8 ${g.label} \u2014 answering\u2026`)):g.status==="done"?console.log(X(` \u2713 ${g.label}`)):console.log(L(` \u2717 ${g.label}`));else if(g.type==="run_done"){let k=g.results.filter(T=>!T.ok);console.log(""),console.log(`${g.results.length-k.length}/${i.length} article${i.length===1?"":"s"} answered.`),k.length&&console.log(K(`\u26A0 ${k.length} left untouched (their comments are still open, so nothing was promised to those reviewers): ${k.map(T=>T.label).join(", ")}`)),g.blocked&&console.log(K(`\u26A0 ${g.blocked}`)),g.allEmpty&&console.log(K("\u26A0 No agent produced any work this run \u2014 nothing was changed or answered.")),console.log(d(ln(Ot(a,g.results,g.totalCostUsd))))}}catch(g){console.log(L(`Answering comments failed: ${g.message}`))}let f=Go(e.cwd,c,"","/comments").changed.length;return f>0&&console.log(`${f} article${f===1?"":"s"} changed, and that new text has not been read by an editor \u2014 ${f===1?"it":"they"} can go live once /review has been over ${f===1?"it":"them"}.`),{kind:"continue"}}async function hb(e,t){let n=t?.cwd??process.cwd();if(!OA(n))return console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Je(n,t?.profileName);if(!o.ok)return console.log(L(o.reason)),{kind:"continue"};let r=Gp(e);console.log(d("Checking Document360 for reviewer comments\u2026"));let s;try{s=await vl(n,t?.profileName,r.scope)}catch(a){return console.log(L(`Couldn\u2019t read comments from Document360: ${a.message}`)),{kind:"continue"}}for(let a of Bp(s,{full:!!r.scope.path,showAnswered:r.showAnswered}))console.log(a);if(s.threads.length===0)return{kind:"continue"};if(r.answer&&t)return JA(t,qo(s.threads,s.labels),{resolve:r.resolve});let i=qo(s.threads,s.labels)[0];return console.log(`${z("\u2192",Ne.yellow)}${Ne.bold("/comments <article>")} shows one article\u2019s comments in full `+Ne.gray(i?.path?`(e.g. /comments ${i.path})`:"(by its local path)")),console.log(`${z("\u2192",Ne.yellow)}${Ne.bold("/comments --answer")} fixes each one, updates the draft in Document360, then replies in the thread `+Ne.gray("(one article at a time: /comments --answer <article>, or --scope <category>)")),{kind:"continue"}}oe();import{spawn as fb}from"node:child_process";import{mkdirSync as ZA,openSync as eE,readFileSync as tE}from"node:fs";import{dirname as nE,join as oE}from"node:path";import{logsDir as rE}from"document360-engine";var qr="document360-writer",fi=`npm i -g ${qr}@latest`,sE="document360-capture";function iE(){return new Promise(e=>{try{let t=fb("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 Sl(){return oE(rE(),"self-update.log")}function Cl(e){return/\bEACCES\b|permission denied|EPERM|operation not permitted/i.test(e)?process.platform==="win32"?`Permission denied. Run ${fi} from an Administrator terminal.`:`Permission denied \u2014 your global npm folder isn't writable. Either run sudo ${fi} , 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: ${fi}`:/EBADENGINE|Unsupported engine/i.test(e)?`Your Node version is too old for this release. Install Node 20 or later, then run: ${fi}`:`Run manually: ${fi}`}function aE(e,t=6){return e.split(/\r?\n/).map(n=>n.trimEnd()).filter(Boolean).slice(-t).join(`
429
- `)}async function Pl(){let e=process.platform==="win32",n=await iE()?[qr,sE]:[qr],o=Sl(),r=null;try{ZA(nE(o),{recursive:!0}),r=eE(o,"w")}catch{r=null}let s=()=>{try{return aE(tE(o,"utf8"))}catch{return""}};return new Promise(i=>{try{let a=fb(`npm i -g ${n.map(c=>`${c}@latest`).join(" ")}`,{stdio:r===null?"ignore":["ignore",r,r],shell:!0,detached:!e,windowsHide:!0});a.on("error",c=>i({ok:!1,output:`${String(c)}
430
- ${s()}`.trim(),packages:n})),a.on("close",c=>i({ok:c===0,output:c===0?"":s(),packages:n})),e||a.unref()}catch(a){i({ok:!1,output:String(a),packages:n})}})}async function mb(){console.log(d("Updating the d360-writer toolchain\u2026"));let e=await Pl();return e.ok?(console.log(X(`\u2713 Updated ${e.packages.join(" + ")}. Exit (/exit) and relaunch d360-writer to apply.`)),{kind:"continue"}):(console.log(L(`Update failed. ${Cl(e.output)}`)),e.output&&console.log(d(e.output)),console.log(d(`Full output: ${Sl()}`)),{kind:"continue"})}oe();Hn();import{existsSync as qp,rmSync as lE}from"node:fs";import{basename as gb,resolve as Vp}from"node:path";import{execFileSync as cE}from"node:child_process";import{input as uE}from"@inquirer/prompts";import{readProjectConfig as dE,devHintsGuidePath as pE}from"document360-engine";var hE=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],fE=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),Tl=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),yb=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function wb(e){let t=Tl(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:yb(t)?!0:fE.has(t)}function Kp(e){let t=null;try{t=dE(e)}catch{t=null}let n=new Set(hE);for(let o of[Tl(t?.docsDir),Tl(t?.captureDir),Tl(t?.outputDir)])o&&yb(o)&&n.add(o);return[...n].filter(o=>wb(o)&&qp(Vp(e,o)))}function Yp(e,t){let n=[],o=[];for(let r of t){if(!wb(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{lE(Vp(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function bb(e,t){try{return cE("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
431
- `).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function mE(e){return bb(e,".d360-writer/hints")}function gE(e){return bb(e,".d360-writer/messages")}function zp(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=mE(e),o=gE(e),r=qp(Vp(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: ${gb(e)}`]}async function kb(e,t){let n=Kp(t.cwd);for(let c of zp(t.cwd,n))console.log(n.length===0?d(c):c);if(n.length===0)return{kind:"continue"};let o=gb(t.cwd);if((await t.withPausedInput(()=>uE({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(K("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=qp(pE(t.cwd)),{removed:i,failed:a}=Yp(t.cwd,n);console.log(X(`\u2713 Reset complete \u2014 removed ${i.length} item${i.length===1?"":"s"}. The repo is back to its original state.`));for(let c of a)console.log(L(` \u2717 ${c.path}: ${c.error}`));if(s){for(let c of pa())console.log(c);console.log(d("(Select and copy the prompt above to paste into your coding agent.)"))}return console.log(d("Set up d360-writer again with /init (then /login, /workspace).")),{kind:"continue"}}oe();import{buildRegistry as Zp,clearRegistryCache as yE,lintArticles as Al,listAvailablePacks as Xp,readProjectConfig as Nn,readStyleBaseline as wE,clearStyleBaseline as bE,styleBaselinePath as kE,recordStyleSwitch as $E,declineStyleSweep as vE,styleSweepOutstanding as xE,resolveActivePacks as eh,styleGuidePath as vb,writeProjectConfig as th,buildStyleCompilePrompt as RE,loadStyleGuide as SE,loadHouseRules as CE,buildStyleLearnPrompt as PE,reviewerNotesPath as TE,listStyleGuides as AE,getStyleGuide as EE,resolveActiveProfile as NE,resolveProjectId as DE,styleGuideSettled as jE,styleGuideUpgradeOffered as xb,DEFAULT_PACK as nh,STYLE_GUIDE_MAX_CHARS as $b,BUILTIN_RULES as El,ALWAYS_ON_PACK as no}from"document360-engine";import{existsSync as oh,mkdirSync as IE,readFileSync as Rb,writeFileSync as Qp}from"node:fs";import{dirname as LE}from"node:path";import{createHash as OE}from"node:crypto";function Vr(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==="sweep"?{sub:"sweep",value:t[1]}: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 _E(e){try{return zg(e,"/style-guide")?.title??null}catch{return null}}function rh(e){try{return!jE(Nn(e)?.styleGuide)}catch{return!1}}function Sb(e,t){let n=[],o=new Set,r=s=>{if(o.has(s))return;o.add(s),Nr(e,s).ok&&n.push(ne("\u2713",`That settles a docs-campaign step \u2014 marked done: ${s}`))};try{let s=_E(e);if(s&&r(s),t)for(let i of Ia(e,t))r(i)}catch{}return n}function ME(e){let t=Nn(e)??{projectId:""},n=eh(t.styleGuide).filter(s=>s!==no),o=xb(t.styleGuide);th({...t,styleGuide:{...t.styleGuide,decidedAt:new Date().toISOString(),...o?{declinedUpgrade:nh}:{}}},e);let r=[ne("\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."),d(" Change your mind any time: /style-guide use \xB7 see the options: /style-guide list")];return r.push(...Sb(e)),r}var mi="House";async function FE(e,t,n){let o,r;try{let S=NE(e,n);o={profile:S.name,connection:S.connection,projectId:S.project.projectId,projectName:S.project.projectName},r=await DE(o,S.project?.projectId)}catch(S){return{lines:[ne("\u2717",`Not signed in to Document360: ${S instanceof Error?S.message:String(S)}`),d(" Run /login first.")],restart:!1}}let s=await AE(o,r);if(s.kind!=="ok")return{lines:[ne("\u26A0",`Document360 didn't return your style guides \u2014 ${s.reason}.`),d(" Nothing is blocked. Your house style guide lives at .d360-writer/style-guide.md \u2014 write or paste"),d(" it there directly, and /review and the writer both read it. /style-guide compile then turns its"),d(" mechanical parts into checks.")],restart:!1};if(s.guides.length===0)return{lines:[ne("\u2139","This Document360 project has no style guides yet."),d(" 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((C,x)=>{let E=[C.language_code,C.created_by_name,C.created_at?.slice(0,10)].filter(Boolean).join(" \xB7 ");return` ${x+1} ${C.name??C.id}${C.is_default?d(" (default)"):""}${E?d(` ${E}`):""}`}),"",d(" 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(S=>S.id===t);if(!a)return{lines:[ne("\u2717",`No style guide numbered or identified by "${t}". Run /style-guide pull to list them.`)],restart:!1};let c=await EE(o,r,a.id,{langCode:a.language_code});if(c.kind!=="ok"){let S=c.kind==="notFound"?"Document360 could not find it (style guides are per language)":c.reason;return{lines:[ne("\u2717",`Could not read "${a.name??a.id}" \u2014 ${S}.`)],restart:!1}}let l=(c.guide.content??"").trim();if(!l)return{lines:[ne("\u26A0",`"${a.name??a.id}" has no content yet \u2014 nothing to pull.`)],restart:!1};let f=vb(e),g=[];if(oh(f))try{Qp(`${f}.bak`,Rb(f,"utf8"),"utf8"),g.push(d(" Your previous guide is at .d360-writer/style-guide.md.bak"))}catch{}let k=l.length>$b?l.slice(0,$b):l,T=`<!-- Pulled from Document360: "${a.name??a.id}" (${new Date().toISOString().slice(0,10)}). Edit freely \u2014 /style-guide pull overwrites this file. -->
432
-
433
- `;IE(LE(f),{recursive:!0}),Qp(f,`${T}${k}
434
- `,"utf8");let A=Nn(e)??{projectId:""};return th({...A,styleGuide:{...A.styleGuide,pulledFrom:{styleGuideId:a.id,name:a.name??a.id,pulledAt:new Date().toISOString(),contentHash:OE("sha1").update(k).digest("hex").slice(0,16)}}},e),{lines:[ne("\u2713",`Pulled "${a.name??a.id}" into .d360-writer/style-guide.md (${k.length.toLocaleString()} characters).`),...g,d(" This is PROSE, not rules \u2014 /review judges against it, and the writer now writes to it."),d(" Turn its mechanical parts into checks: /style-guide compile"),d(" Restarting the agent so it writes to the new guide\u2026")],restart:!0}}function UE(e){let t=Zp(e).rules.filter(n=>n.pack.toLowerCase()===mi.toLowerCase()).map(n=>n.id);return{prompt:RE({guide:SE(e),packName:mi,existingRuleIds:t}),display:"/style-guide compile"}}function WE(e){let t=TE(e),n=oh(t)?Rb(t,"utf8").trim():"";return!n||!/^## /m.test(n)?{kind:"nothing",lines:[ne("\u2139","No reviewer comments have been read yet, so there is nothing to learn from."),d(" Reviewers comment on your drafts in Document360; /comments reads them, and every read"),d(" keeps a copy in .d360-writer/reviewer-notes.md. Run /comments first.")]}:{kind:"run",prompt:PE({notes:n,existingRules:CE(e),houseRulesFile:".d360-writer/house-rules.md"}),display:"/style-guide learn"}}function Cb(){return[d(" Read what it wrote: git diff .d360-writer/house-rules.md"),d(" These rules apply from now on \u2014 the writer follows them and /review judges against them."),d(" Disagree with one? Delete the line. It is your file, and nothing regenerates it."),d(" Restarting the agent so it writes to the new rules\u2026")]}function Pb(){return[d(` Review what it wrote: git diff .d360-writer/styles/${mi}/`),d(` Anything it could not check mechanically is listed in .d360-writer/styles/${mi}/UNCHECKABLE.md \u2014 /review judges those.`),d(` Turn them on when you are happy: /style-guide use ${mi.toLowerCase()} (they start as warnings, never blocking)`)]}var tt=(e,t)=>`${e} ${t}${e===1?"":"s"}`,Jp=e=>/^v\d/i.test(e)?e:`v${e}`;function BE(e){let t=(e.description??`${e.name} style guide`).trim().replace(/\s+/g," "),n=/^(.{0,72})(?:[.,:;—]|$)/.exec(t)?.[1]?.replace(/[.,:;—\s]+$/,"").trim();if(n&&n.length>0)return n;let o=t.slice(0,72),r=o.lastIndexOf(" ");return`${r>20?o.slice(0,r):o}\u2026`}function Tb(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 HE(e){let n=Nn(e)?.styleGuide?.pulledFrom;return n?`.d360-writer/style-guide.md \u2014 pulled ${n.pulledAt.slice(0,10)} from "${n.name}"`:oh(vb(e))?".d360-writer/style-guide.md (yours)":"the built-in default"}function GE(e){let t=Nn(e),n=Zp(e),o=(t?.styleGuide?.packs??[]).filter(Boolean),r=n.packs.filter(l=>l.name.toLowerCase()===no),s=n.packs.filter(l=>{let f=l.name.toLowerCase();return f!==no&&f!=="d360"}),i=t?.styleGuide?.packs===void 0&&s.length>0,a=[`Style guide: ${HE(e)}`,`Rule packs: ${s.length>0?s.map(l=>`${l.name.toLowerCase()} ${Jp(l.version)}`).join(", ")+(i?d(" (the default \u2014 nobody has chosen yet)"):""):d("none chosen")}`,`Always on: ${d(`d360 (correctness, built in \u2014 ${tt(El.length,"rule")})`)}`];for(let l of r)a.push(` ${d(`${l.name.toLowerCase()} ${Jp(l.version)} (anti-slop \u2014 ${tt(l.ruleCount,"rule")})`)}`);r.length>0&&(a.push(d(" Every article here is machine-written, so these cannot be switched off by")),a.push(d(" choosing another pack. styleGuide.humanise: false turns them off deliberately.")));let c=[...El.map(l=>({severity:l.severity})),...n.rules.map(l=>({severity:l.severity}))];a.push("",`${tt(c.length,"rule")} active \xB7 ${Tb(c)}`);try{let l=Al({cwd:e}),f=l.findings.filter(k=>!k.baselined),g=f.filter(k=>k.severity==="error").length;a.push(""),a.push(g===0?ne("\u2713",`No style errors across the docs${f.length>0?`, though ${tt(f.length,"other issue")} ${f.length===1?"is":"are"} reported`:""}.`):ne("\u2717",`${tt(g,"style error")} \u2014 /lint --blocked shows them, /lint --blocked --fix corrects them.`)),l.baselinedCount>0&&a.push(ne("\u2139",`${tt(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&&a.push(ne("\u26A0",`${tt(l.ruleErrors.length,"rule")} could not be loaded: ${l.ruleErrors.slice(0,2).map(k=>`${k.ruleId} (${k.reason})`).join("; ")}`))}catch{}return a.push(""),a.push(d(" See them all: /style-guide list \xB7 change: /style-guide use \xB7 one rule: /style-guide explain <rule>")),xb(Nn(e)?.styleGuide)&&(a.push(""),a.push("A guide built for software documentation is installed, and these docs are not on it:"),a.push(` Move to it /style-guide use ${nh}`),a.push(" Stay as you are /style-guide keep"),a.push(d(" Several rules in a general-prose guide are wrong for software documentation. This one was")),a.push(d(" measured on real knowledge bases, rule by rule, and nothing in it can block a publish."))),rh(e)&&(a.push(""),a.push("Nobody has settled this yet, and it is a decision \u2014 nothing above changed anything:"),a.push(" Happy with these rules? /style-guide keep"),a.push(" Want a stricter standard? /style-guide use microsoft (or google)"),a.push(d(" Worth settling now rather than later: it shapes every article written from here, and")),a.push(d(" changing it once a knowledge base exists means going back over what is already written."))),a}function Ab(e){let t=Nn(e),n=new Set(eh(t?.styleGuide)),o=Xp(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(),c=n.has(a),l=a===no,f=c?"\u2713":"\xB7",g=l?d("(always on)"):c?d("(active)"):"",k=i.local?d(" [yours]"):"";r.push(` ${f} ${a.padEnd(s)}${k} ${i.description??""}`),r.push(` ${d(`${tt(i.rules.length,"rule")} \xB7 ${Tb(i.rules)} \xB7 ${Jp(i.version)}`)} ${g}`),i.errors.length>0&&r.push(ne("\u26A0",`${tt(i.errors.length,"rule")} in this pack could not be loaded \u2014 /style-guide explain names them.`))}return o.every(i=>i.name.toLowerCase()===no)&&(r.push(""),r.push(d(" The Microsoft and Google style guides are not installed in this build yet."))),r.push(""),r.push(d(" Turn one on: /style-guide use <name> (this replaces the chosen set, it does not add to it)")),r.push(d(" Several: /style-guide use microsoft,google")),r.push(d(" Back to none: /style-guide use none")),r}function qE(e,t){if(!t)return[ne("\u26A0","Name a rule: /style-guide explain Humanise.EmDash")];let n=Zp(e),o=El.find(l=>l.id.toLowerCase()===t.toLowerCase()),r=n.rules.find(l=>l.id.toLowerCase()===t.toLowerCase());if(!o&&!r){let l=[...El.map(f=>f.id),...n.rules.map(f=>f.id)].filter(f=>f.toLowerCase().includes(t.toLowerCase())).slice(0,5);return[ne("\u26A0",`No active rule called "${t}".`),...l.length>0?[d(` Did you mean: ${l.join(", ")}`)]:[d(" /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()}`,c=[`${s} ${i} \xB7 ${a}`,""];c.push(` ${o?.summary??r.message}`),r?.link&&c.push(d(` ${r.link}`)),r?.degraded&&(c.push(""),c.push(ne("\u26A0",`This rule is translated approximately: ${r.degraded}. It may match slightly more than the original does.`)));try{let l=Al({cwd:e}).findings.filter(g=>g.ruleId===s),f=l.filter(g=>!g.baselined);c.push(""),c.push(l.length===0?" Currently: no findings.":` Currently: ${tt(f.length,"finding")}${l.length!==f.length?`, plus ${l.length-f.length} baselined and hidden`:""}.`)}catch{}return c.push(""),o?(c.push(d(" Built-in checks are grounded in your product's own source and cannot be switched off \u2014 they")),c.push(d(" catch defects of fact, not matters of taste."))):(c.push(i==="error"?d(' This one BLOCKS publishing \u2014 your config sets it to "error" deliberately.'):d(" Style rules never block publishing. Fix it when you want to; it will not hold a page back.")),c.push(d(` Silence it everywhere: add "${s}": "off" to styleGuide.rules in .d360-writer/config.json`)),i!=="error"&&c.push(d(" Silence one passage: <!-- vale "+s+" = NO --> \u2026 <!-- vale "+s+" = YES -->"))),c}function sh(e,t){let n=(t??"").trim();if(!n){let T=Xp(e).filter(x=>x.name.toLowerCase()!==no),A=new Set(eh(Nn(e)?.styleGuide).map(x=>x.toLowerCase())),S=x=>x.toLowerCase()===nh?0:1,C=T.sort((x,E)=>S(x.name)-S(E.name)||x.name.localeCompare(E.name)).map(x=>({cmd:`/style-guide use ${x.name.toLowerCase()}`,desc:`${BE(x)} \u2014 ${x.rules.length} rules${A.has(x.name.toLowerCase())?" (active now)":""}`}));return{lines:[],restart:!1,pick:{title:"Which writing rules should these docs follow?",lead:"Pick below. Whichever you choose, every article here is held to it \u2014 nothing stays exempt.",options:[...C,{cmd:"/style-guide use none",desc:"the built-in checks only \u2014 correctness and anti-slop"}]}}}let o=n.toLowerCase()==="none"?[]:n.split(/[,\s]+/).map(T=>T.trim().toLowerCase()).filter(Boolean),r=new Map(Xp(e).map(T=>[T.name.toLowerCase(),T])),s=o.filter(T=>!r.has(T));if(s.length>0)return{lines:[ne("\u2717",`No rule pack named ${s.map(T=>`"${T}"`).join(", ")}.`),"",...Ab(e)],restart:!1};let i=Nn(e)??{projectId:""},{declinedUpgrade:a,...c}=i.styleGuide??{},l=(i.styleGuide?.packs??[]).map(T=>T.trim().toLowerCase()).filter(Boolean);th({...i,styleGuide:{...c,packs:o,decidedAt:new Date().toISOString()}},e),yE();let f=[ne("\u2192",`Switching to: ${o.length>0?o.join(", "):"the built-in checks only"}${o.includes(no)?"":` (+ ${no}, always on)`}\u2026`)],g,k=[];try{let T=wE(e),A=T?Object.values(T.entries).reduce((x,E)=>x+E.count,0):0;if(T){try{Qp(`${kE(e)}.bak`,JSON.stringify(T,null,2),"utf8")}catch{}bE(e)}let S=Al({cwd:e}),C=new Set(S.findings.map(x=>x.path)).size;if(S.findings.length===0)f.push(ne("\u2713",C===0?"No articles yet \u2014 everything you write from here is held to the full set.":"Your articles are already clean against these rules."));else{f.push(ne("\u26A0","Every article is held to the new rules. Nothing stays exempt."),"",d(` ${tt(S.findings.length,"finding")} across ${tt(C,"article")} ${S.findings.length===1?"is":"are"} now live.`)),A>0&&(f.push(d(` ${tt(A,"finding")} accepted under your previous guide ${A===1?"is":"are"} not carried over.`)),f.push(d(" Your previous record is at .d360-writer/style-baseline.json.bak"))),f.push(""),f.push(ne("\u2713","Nothing blocks publishing \u2014 no style-pack rule can."));let x=Jn(e,["--fix"],S.findings);x.lines.length>0&&f.push("",...x.lines);let E=x.fixed>0?Al({cwd:e}):S,I=E.findings.length,W=new Set(E.findings.map(V=>V.path)).size;I===0?f.push(ne("\u2713","That was all of them \u2014 your articles now match the new guide.")):g={findings:I,articles:W,cmd:"/review --all --fix",...x.fixed>0?{outOf:S.findings.length}:{}},k=[...new Set(E.findings.map(V=>V.path))]}$E(e,{packs:o,from:l,articlesWithFindings:k})}catch(T){f.push(ne("\u26A0",`The packs are active, but reading your articles failed: ${T instanceof Error?T.message:String(T)}`)),f.push(d(" Run /lint to see the current state before publishing."))}return f.push(...Sb(e,`/style-guide use ${n}`)),f.push(d(" Restarting the agent so it writes to the new rules\u2026")),{lines:f,restart:!0,...g?{editorial:g}:{}}}function VE(e){return[e.title,d(` ${e.lead}`),"",...e.options.map(t=>` ${t.cmd}`.padEnd(38)+d(t.desc))]}function ih(e){let t=e.outOf?`${e.findings} of the ${e.outOf} findings`:tt(e.findings,"finding");return[ne("\u2192",`${t} across ${tt(e.articles,"article")} ${e.findings===1?"needs":"need"} a read, not a swap.`),d(` ${e.cmd} reads each one and rewrites it. Nothing is blocking your publishing in the meantime.`)]}function KE(e,t){let n=(t??"").trim().toLowerCase()==="skip",o=xE(e);if(!o)return[ne("\u2713","No sweep is owed \u2014 your articles have been read against the guide they follow.")];let r=o.packs.length>0?o.packs.join(", "):"the built-in checks";if(n)return vE(e),[ne("\u2713",`Fine \u2014 I won't raise the ${r} sweep again.`),"",d(` ${tt(o.pending,"article")} still ${o.pending===1?"has":"have"} not been read against it.`),d(" /review --all --fix does the sweep whenever you want it.")];let s=o.total-o.pending;return[ne("\u2192",`${o.pending} of your ${tt(o.total,"article")} still ${o.pending===1?"needs":"need"} a read against ${r}.`),"",...s>0?[d(` ${s} read so far.`)]:[],d(" /review --all --fix reads the rest and rewrites them."),d(" /style-guide sweep skip stops me raising it.")]}async function Nl(e,t){let{sub:n,value:o}=Vr(e),r=s=>{for(let i of s)console.log(i);console.log("")};switch(n){case"list":return r(Ab(t.cwd)),{kind:"continue"};case"explain":return r(qE(t.cwd,o)),{kind:"continue"};case"use":{let s=sh(t.cwd,o);return r(s.pick?VE(s.pick):s.lines),s.editorial&&r(ih(s.editorial)),s.restart?{kind:"clear"}:{kind:"continue"}}case"keep":return r(ME(t.cwd)),{kind:"continue"};case"sweep":return r(KE(t.cwd,o)),{kind:"continue"};case"pull":{let s=await FE(t.cwd,o,t.profileName);return r(s.lines),s.restart?{kind:"clear"}:{kind:"continue"}}case"compile":{let s=UE(t.cwd);return{kind:"forward-to-agent",prompt:s.prompt,display:s.display}}case"learn":{let s=WE(t.cwd);return s.kind==="nothing"?(r(s.lines),{kind:"continue"}):{kind:"forward-to-agent",prompt:s.prompt,display:s.display}}default:return r(GE(t.cwd)),{kind:"continue"}}}oe();import{lintDocs as jl,loadStyleGuide as Fb,buildReviewPrompt as Ub,buildStructureReviewPrompt as pN,structureReviewDue as hN,structureFingerprint as fN,recordStructureReview as mN,hasCaptureArtifacts as Wb,readProjectConfig as hh,DEFAULT_DOCS_DIR as fh,listArticleFiles as Yo,normalizeScope as gN,planPartitions as yN,runPartitioned as Bb,partitionCoverage as wN,resolveModelForOperation as Hb,stampArticles as bN,snapshotArticles as kN,reviewStalePaths as $N,readReviewerNotes as Gb,renderNotesForPrompt as qb,readDocsPlan as vN,CONTENT_CAP_VERSION as ph}from"document360-engine";import{articlesChangedSince as YE,isUnadoptedArticle as zE,docsRootOf as XE}from"document360-engine";function Vo(e,t,n,o){let r=t.map(l=>l.replace(/\\/g,"/"));if(!n)return{changed:[],earned:r,unadopted:[]};let s=[];try{s=YE(e,n).map(l=>l.replace(/\\/g,"/"))}catch{return{changed:[],earned:r,unadopted:[]}}let i=new Set(s),a=r.filter(l=>!i.has(l)&&zE(e,l,o)),c=new Set(a);return{changed:s.filter(l=>r.includes(l)),earned:r.filter(l=>!c.has(l)),unadopted:a}}function QE(e,t){let n=t.replace(/\\/g,"/");try{let o=XE(e).replace(/\\/g,"/").replace(/\/+$/,"");return o&&n.startsWith(`${o}/`)?n.slice(o.length+1):n}catch{return n}}function Kr(e,t,n){if(t.length===0)return null;let o=t.length===1,r=[];r.push(o?`\u26A0 The editor changed nothing in ${QE(e,t[0])}, so it is not recorded as reviewed.`:`\u26A0 The editor changed nothing in ${t.length} pages, so they are not recorded as reviewed.`),r.push(o?" Nothing here has adopted this page: it came from Document360, it is not in your docs plan, and":" Nothing here has adopted them: they came from Document360, they are not in your docs plan, and"),r.push(o?" nothing records what it was written from. There was nothing for an editor to check it against.":" nothing records what they were written from. There was nothing for an editor to check them against.");for(let i of t)r.push(`/untrack ${i}`);r.push(o?" That disowns it \u2014 the page, its history and its comments stay on Document360, readers see no":" That disowns one \u2014 the page, its history and its comments stay on Document360, readers see no"),r.push(" change, and the markdown is kept. Nothing is deleted.");let s=n.lead&&o?{text:r.join(`
435
- `),cmd:`/untrack ${t[0]}`}:null;return{lines:r,cta:s}}function gi(e){return e===0?"The editor found nothing to change":"Editor applied its fixes"}import{listArticleFiles as Eb,lintDocs as JE,planFindingPartitions as ZE,planPartitions as eN,readDocsPlan as tN,readProjectConfig as nN,runRate as lh,DEFAULT_DOCS_DIR as oN}from"document360-engine";function ch(e){switch(e.cmd){case"/review":return{concurrency:ro,maxPerPartition:dh,minutesPerBatch:5};case"/write":return{concurrency:3,minutesPerBatch:4};case"/lint":return{concurrency:3,minutesPerBatch:2};default:return{concurrency:3,minutesPerBatch:2}}}function rN(e,t){let n=JE({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:ZE(o).length}}var sN=new Set(["/push","/publish","/pull"]);function Nb(e,t){if(t.cmd==="/lint"){let r=oo(()=>rN(e,t));return r?{lead:r.lead,billable:r.articles,batches:r.batches}:null}if(t.cmd==="/catch-up"){let r=oo(()=>Jt(e));if(!r)return null;let s=r.hints+r.requests+r.answers+r.directives;if(s===0)return null;let i=oo(()=>Gr(r));return i?{lead:i,billable:0,batches:null}:{lead:`${s} queued item${s===1?"":"s"}`,billable:0,batches:null}}if(t.cmd==="/reuse"){if(t.sub!=="audit")return null;let r=oo(()=>Eb(e,t.scope))?.length??0;return r<4?null:{lead:`${r} article${r===1?"":"s"} read \xB7 one editorial turn`,billable:0,batches:null}}if(sN.has(t.cmd)){let r=oo(()=>Eb(e,t.scope))?.length??0;return r<4?null:{lead:`${r} article${r===1?"":"s"}`,billable:0,batches:null}}let n=iN(e,t);if(!n||n.length<4)return null;let o=ch(t);return{lead:`${n.length} article${n.length===1?"":"s"}`,billable:n.length,batches:eN(n,o.maxPerPartition?{maxPerPartition:o.maxPerPartition}:void 0).length}}function iN(e,t){try{if(t.cmd==="/write"){let n=(nN(e)?.docsDir??oN).replace(/\/+$/,""),o=tN(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:Kn(e,n,r)}return t.cmd==="/review"?Ko(e,[...t.flags],t.scope):null}catch{return null}}function Db(e,t){let n=Zt(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 Zt(e,t){let n=an(t);if(!n||!Er(n))return null;let o=Nb(e,n);if(!o)return null;let r=oo(()=>lh(e,n.cmd));if(o.batches===null){let l=r?.minutesPerWave!==void 0?` \xB7 ~${ah(r.minutesPerWave)}`:"";return`${o.lead}${l}`}let s=ch(n),a=Math.ceil(o.batches/s.concurrency)*(r?.minutesPerWave??s.minutesPerBatch),c=r?.usdPerArticle!==void 0&&o.billable>0?` \xB7 ~${Lb(o.billable*r.usdPerArticle)}`:"";return`${o.lead} \xB7 ${o.batches} batch${o.batches===1?"":"es"} \xB7 ~${ah(a)}${c}`}function jb(e,t){let n=an(t);if(!n||!Er(n))return null;let o=oo(()=>lh(e,n.cmd));if(o?.usdPerArticle===void 0)return null;let r=Nb(e,n);return!r||r.billable===0?null:r.billable*o.usdPerArticle*uh}var Ib=.7,uh=1.4;function ah(e){let t=Math.max(1,Math.round(e*Ib)),n=Math.max(t,Math.round(e*uh));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 Lb(e){let t=e*Ib,n=e*uh;return n>=10?`$${Math.round(t)}\u2013${Math.round(n)}`:`$${t.toFixed(2)}\u2013${n.toFixed(2)}`}function oo(e){try{return e()}catch{return null}}function Dl(e,t,n,o){if(n<4||o<1)return null;let r=ch({cmd:t,scope:void 0,flags:new Set,args:[]}),s=Math.ceil(o/r.concurrency),i=oo(()=>lh(e,t)),a=s*(i?.minutesPerWave??r.minutesPerBatch),c=i?.usdPerArticle!==void 0?` \xB7 ~${Lb(n*i.usdPerArticle)}`:"";return`~${ah(a)}${c}`}import{loadProfileMap as xN,resolveActiveProfile as RN}from"document360-engine";import{renderGapsForPrompt as Vb,readReaderContract as mh,renderCorpusTermsForPrompt as Kb,scanTerminology as Yb,renderReuseForPrompt as zb,scanReuse as Xb}from"document360-engine";import{recordRunSample as SN}from"document360-engine";oe();import{readProjectConfig as aN,loadProfileMap as lN,resolveActiveProfile as cN,desiredCategoryOrder as uN,desiredArticleOrder as dN}from"document360-engine";function Ob(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}var _b=e=>e.replace(/\\/g,"/").split("/").pop()??e;function Yr(e,t){try{if(!aN(e))return[];let n=cN(e,t),o=lN(e,n.name);if(!o)return[];let r=new Map;for(let g of dN(o)){let k=r.get(g.categoryPath);k?k.push(g):r.set(g.categoryPath,[g])}let s=uN(o),i=Math.min(...s.map(g=>g.path.split("/").length),Number.MAX_SAFE_INTEGER),a=new Map;for(let g of s){let k=g.path.split("/").slice(0,-1).join("/"),T=a.get(k);T?T.push(g):a.set(k,[g])}let c=[],l=(g,k)=>{for(let T of(a.get(g)??[]).sort((A,S)=>A.order-S.order)){let A=" ".repeat(k);c.push(`${A}${Ob(_b(T.path))}`);for(let S of(r.get(T.path)??[]).sort((C,x)=>C.order-x.order))c.push(`${A} ${Ob(_b(S.path))}`);l(T.path,k+1)}},f=s.find(g=>g.path.split("/").length===i);return l(f?f.path.split("/").slice(0,-1).join("/"):"",0),c}catch{return[]}}async function Mb(e,t){let n=Yr(t.cwd,t.profileName);if(n.length===0)return console.log(d("No documentation structure yet \u2014 run /init and author some articles first.")),{kind:"continue"};console.log(ee("Documentation order (categories \u2192 articles):"));for(let o of n)console.log(o);return console.log(""),{kind:"continue"}}function gh(e,t){return Ws(e,Yo(e,t))}function yh(e,t){return $N(e,Yo(e,t),ph)}function zr(e){return e.includes("--blocked")||e.includes("--stale")}function Ko(e,t,n){return t.includes("--blocked")?gh(e,n):t.includes("--stale")?yh(e,n):Yo(e,n)}function wh(e,t,n){let o;try{o=vN(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}/`,""),c=r.get(a);c&&s.push({path:i,type:c.type,...c.purpose?{purpose:c.purpose}:{}})}return s}function Qb(e,t){let n=hh(e);if(!n)return null;let o=(n.docsDir??fh).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),s=zr(t),i=t.find(C=>!C.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),a=jl({cwd:e}),c=i?gN(o,i):"",l=c?a.filter(C=>C.path===`${o}/${c}`||C.path.startsWith(`${o}/${c}/`)):a,f=s?Ko(e,t,i):void 0,g=f?l.filter(C=>f.includes(C.path)):l,k=i||s?"":Yr(e).join(`
436
- `),T=Wb(e,n),A=Ub({docsRoot:o,scope:i,styleGuide:Fb(e),deterministicFindings:g,fix:r,structure:k||void 0,screenshots:T,...f?{paths:f}:{},reviewerNotes:qb(Gb(e),f??Yo(e,i)),openGaps:Vb(e,f??Yo(e,i)),readerContract:mh(e),corpusTerms:Kb(Yb(e)),corpusReuse:zb(Xb(e)),planRows:wh(e,o,f??Yo(e,i))}),S=t.includes("--blocked")?" --blocked":t.includes("--stale")?" --stale":"";return{prompt:A,display:`/review${i?` ${i}`:""}${S}${r?" --fix":""}`}}var CN=e=>"ruleId"in e,ro=3,dh=3;function bh(e,t){let n=Qb(e,t);if(!n)return null;let o=t.find(C=>!C.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),r=Ko(e,t,o),s=yN(r,{maxPerPartition:dh});if(s.length<=1)return{kind:"single",...n};let i=hh(e),a=(i?.docsDir??fh).replace(/\\/g,"/").replace(/\/+$/,""),c=t.includes("--fix"),l=Fb(e),f=jl({cwd:e}),g=Gb(e),k=Wb(e,i),T=mh(e),A=Kb(Yb(e)),S=zb(Xb(e));return{kind:"partitioned",partitions:s,articles:r.length,wholeKb:!o&&!zr(t),display:n.display,promptFor:C=>{let x=new Set(C.paths);return Ub({docsRoot:a,styleGuide:l,deterministicFindings:f.filter(E=>x.has(E.path)),fix:c,screenshots:k,paths:C.paths,reviewerNotes:qb(g,C.paths),openGaps:Vb(e,C.paths),readerContract:T,corpusTerms:A,corpusReuse:S,planRows:wh(e,a,C.paths)})}}}function yi(e,t,n){let o=hh(e);if(!o||t.find(c=>!c.startsWith("--"))||n?.kind==="single"&&!zr(t))return null;let s=(o.docsDir??fh).replace(/\\/g,"/").replace(/\/+$/,""),i=Yr(e);if(Object.keys(xN(e,RN(e).name)?.categories??{}).length<2)return null;let a=i.join(`
437
- `);return hN(e,a,ph)?{prompt:pN({docsRoot:s,structure:a,planRows:wh(e,s,Yo(e)).map(c=>`${c.path} ${c.type}`).join(`
438
- `),readerContract:mh(e)}),display:"/review \u2014 the shape of your knowledge base",fingerprint:fN(a,ph)}:null}function kh(e,t){if(!zr(t))return null;let n=t.find(g=>!g.startsWith("--"));if(Ko(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.`,c=`/push${n?` ${n}`:" --all"}`,l=It(e,{text:`${c} saves ${r?"it":"what has changed"} to Document360 as ${r?"a draft":"drafts"}.`,cmd:c},"",n,"/review"),f=Ke(e,Qb(e,t)?.display??"");return{lines:[a,` ${l.text}`],closed:f,cta:l}}async function Jb(e,t){let n=kh(t.cwd,e);if(n){console.log(X(n.lines[0]));for(let s of n.lines.slice(1))console.log(d(s));for(let s of n.closed)console.log(X(s));let r=yi(t.cwd,e,null);return r&&(console.log(d("One thing left: no editor has looked at how your docs are organised since it last changed.")),await Zb(t,r)),{kind:"continue",ownNext:!0}}if(Zn("review",e)){let r=Fr(t.cwd,"review",e,t.profileName);if(r.length>0){for(let s of r)console.log(d(s));return{kind:"continue"}}}let o=bh(t.cwd,e);return o?o.kind==="single"?{kind:"forward-to-agent",prompt:o.prompt,display:o.display}:await PN(t,o,e.includes("--fix"),e.find(r=>!r.startsWith("--")),e):(console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"})}async function Zb(e,t){console.log(""),console.log(d(`Reviewing ${t.display.replace(/^\/review — /,"")}\u2026`));let n=!1;try{for await(let o of Bb({cwd:e.cwd,partitions:[{label:"the shape of your knowledge base",paths:[]}],promptFor:()=>t.prompt,concurrency:1,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:Hb(e.cwd,"standard").model,scope:"review"}))o.type==="run_done"&&(n=o.results.some(r=>r.ok))}catch{return}n&&mN(e.cwd,t.fingerprint)}async function PN(e,t,n,o,r=[]){let{model:s}=Hb(e.cwd,"standard"),i=yi(e.cwd,r,t),a=Dl(e.cwd,"/review",t.articles,t.partitions.length);console.log(d(`Reviewing ${t.articles} article${t.articles===1?"":"s"} in ${t.partitions.length} batches (\u2264${ro} editors at once) on ${s}${n?", applying fixes":", report only"}${a?` \xB7 ${a}`:""}\u2026`));let c=Date.now(),l=n?kN(e.cwd):null,f=[],g=0,k=new Lr;k.start();let T={aborted:!1,partitions:0,failed:0,notRun:0,producedNothing:!0};try{for await(let x of Bb({cwd:e.cwd,partitions:t.partitions,promptFor:t.promptFor,concurrency:ro,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:s,scope:"review"}))if(x.type==="partition_status")x.status==="running"?console.log(d(` \u25B8 ${x.label} \u2014 reviewing\u2026`)):x.status==="done"?console.log(X(` \u2713 ${x.label}`)):console.log(L(` \u2717 ${x.label}`));else if(x.type==="run_done"){let E=wN(t.partitions,x.results);T={aborted:!!x.aborted,partitions:t.partitions.length,failed:E.failed.length,notRun:E.notRun.length,...x.blocked?{blocked:x.blocked}:{},...x.allEmpty?{allEmpty:!0}:{},...x.bailedEmpty?{bailedEmpty:!0}:{}},console.log(""),console.log(`${x.results.length-E.failed.length}/${t.partitions.length} batches reviewed.`),E.failed.length&&console.log(K(`\u26A0 ${E.failed.length} not reviewed: ${E.failed.map(W=>W.label).join(", ")}`)),E.notRun.length&&console.log(K(`\u26A0 ${E.notRun.length} batch${E.notRun.length===1?"":"es"} never started \u2014 their articles are untouched.`)),x.blocked&&console.log(K(`\u26A0 ${x.blocked}`)),x.allEmpty&&console.log(K("\u26A0 No editor produced any work this run \u2014 nothing was reviewed or changed."));for(let W of $h(t,!!i))console.log(d(W));if(n&&!x.allEmpty&&!x.blocked){let W=Vo(e.cwd,E.covered,l,e.profileName);if(f.push(...W.unadopted),g=W.changed.length,W.earned.length>0)try{bN(e.cwd,W.earned,ft("review"))}catch{}}let I=k.stop();if(console.log(d(ln(Ot(c,x.results,x.totalCostUsd,Date.now(),I.activeSeconds)))),!x.allEmpty&&!x.blocked){let W=x.results.filter(V=>V.ok).length;SN(e.cwd,"review",{articles:E.covered.length,waves:Math.ceil(W/Math.max(1,ro)),seconds:I.activeSeconds,costUsd:x.totalCostUsd})}}}catch(x){return k.stop(),console.log(L(`Review failed: ${x.message}`)),{kind:"continue"}}if(k.stop(),i&&!T.aborted&&await Zb(e,i),n&&Xt(T))for(let x of Ke(e.cwd,t.display))console.log(X(x));if(!n)return{kind:"continue"};let A=Jn(e.cwd,["--fix"],jl({cwd:e.cwd,scope:o}));for(let x of A.lines)console.log(x);let C=jl({cwd:e.cwd,scope:o}).filter(x=>!x.baselined).filter(x=>CN(x)&&x.severity==="error");if(console.log(""),C.length>0){let x=Se("/lint","--blocked --fix",o);console.log(d(`${gi(g)}, but ${C.length} style error${C.length===1?"":"s"} remain \u2014 ${x} 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{let x=Kr(e.cwd,f,{lead:g===0});if(x)for(let E of x.lines)console.log(K(E));if(x?.cta)return{kind:"continue",ownNext:!0};console.log(d(It(e.cwd,{text:`\u2713 ${g===0?"Reviewed \u2014 nothing needed changing":"Reviewed and fixed"}. /push --all saves the articles to Document360 as drafts.`,cmd:"/push --all"},"",o).text))}return{kind:"continue",ownNext:!0}}function $h(e,t=!1){return e.partitions.length<2?[]:t?["Each editor saw one slice of the docs, so no one of them judged the set as a whole.","They did all see how the whole set spells its terms; two different WORDS for one thing still need a person."]:[`Each editor saw one slice of the docs, so reading order ${e.wholeKb?"ACROSS categories":"ACROSS the rest of the knowledge base"} was not judged.`,"They did all see how the whole set spells its terms; two different WORDS for one thing still need a person.","/structure shows the reading order if you want to check it yourself."]}oe();import{readProjectConfig as TN}from"document360-engine";function vh(e,t){if(!TN(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(`
439
- `),display:`/reorder${n?` ${n}`:""}`}}async function ek(e,t){if(Zn("reorder",e)){let o=Fr(t.cwd,"reorder",e,t.profileName);if(o.length>0){for(let r of o)console.log(d(r));return{kind:"continue"}}}let n=vh(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"})}oe();import{readProjectConfig as AN}from"document360-engine";function xh(e,t){if(!AN(e))return null;let n=t.filter(r=>!r.startsWith("--")).join(" ").trim();return{prompt:[n?`Restructure the docs: ${n}`:"Review how the docs are organised and tell me what should change.","","Follow the manage-structure skill.",n?"Apply the change with the right tool: d360_move_articles to refile, split or merge; d360_rename_category to rename; d360_nest_category to put a category inside another or lift one back out; d360_reorder_articles or d360_reorder_categories if only the order is wrong.":["Read the current structure first, then judge it as a senior technical writer would: is every article","filed where a reader would look for it, has any category grown past one topic and want splitting, are","two categories really the same one, does any name still describe what is in it, and does any nesting","earn the click it costs the reader?","","Report what you would change and why, as a short numbered list, and STOP THERE. Do not apply anything","yet: reshaping a knowledge base is my call, not yours. If nothing needs changing, say so plainly."].join(`
412
+ `)}function to(e){return`${K("\u2192",vt.blue)}Verifying ${e} new screenshot${e===1?"":"s"} (reading each image)\u2026`}var PT=(e,t=88)=>{let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n};function Ur(e,t){if(t.length===0)return[];let n=Tn(e).shots,o=[],r=[],s=[];for(let a of t){let c=n[a]?.review;c?c.verdict==="ok"?o.push(a):r.push({id:a,reason:c.reason??"no reason recorded",repaired:!!c.repaired}):s.push(a)}let i=[""];if(i.push(`${K("\u2714",vt.green)}${vt.green(`${o.length} verified`)}`+(r.length>0?` ${vt.magenta(`\u2691 ${r.length} flagged`)}`:"")+(s.length>0?` ${vt.yellow(`? ${s.length} not verified`)}`:"")+vt.gray(` ${t.length} shot${t.length===1?"":"s"} in this pass`)),r.length>0){let a=Math.max(...r.map(l=>l.id.length));for(let l of r)i.push(` ${vt.magenta(l.id.padEnd(a))} ${vt.gray(PT(l.reason))}`);let c=r.filter(l=>l.repaired).length;i.push(`${K("\u2192",vt.magenta)}Re-capture the ${r.length} flagged: ${vt.bold("/screenshot capture --failed")}`+(c<r.length?vt.gray(` (${r.length-c} still need${r.length-c===1?"s":""} a spec fix first)`):""))}return s.length>0&&i.push(`${K("\u26A0",vt.yellow)}No verdict recorded for ${s.slice(0,3).join(", ")}${s.length>3?`, +${s.length-3}`:""} \u2014 still awaiting verification. Run ${vt.bold("/screenshot verify")} again.`),i}async function Uw(e,t){let n=t?.cwd??process.cwd(),o=Lo(n);o&&console.log(o);let r=Ue(n),s=CT(e);if(s.mode==="single"){let a=r.find(c=>c.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:dn(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=ii(r);if(i.length===0){let a=r.filter(f=>f.state==="verified").length,c=r.filter(f=>f.state==="rejected").length,l=r.filter(f=>f.state==="captured").length;return console.log(l>0?`${l} shot${l===1?" is":"s are"} taken but not drawn on yet \u2014 /screenshot annotate finishes ${l===1?"it":"them"}, then there'll be something to verify.`:c>0?`Nothing left to verify. ${c} shot${c===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:dn(n,i),display:"/screenshot verify"}}import{spawn as Ww}from"node:child_process";var pp="d360-capture";function TT(e,t){if(t&&typeof e.pid=="number")try{process.kill(-e.pid,"SIGTERM");return}catch{}try{e.kill()}catch{}}function ai(e){let t=process.platform==="win32",n=!t&&e.stdio==="pipe";return new Promise((o,r)=>{let s=t?Ww(`${pp} ${e.args.join(" ")}`,{cwd:e.cwd,shell:!0,stdio:e.stdio==="inherit"?"inherit":["ignore","pipe","pipe"],env:{...process.env,NO_UPDATE_NOTIFIER:"1"}}):Ww(pp,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",c=>{i+=c.toString()}),s.stderr?.on("data",c=>{i+=c.toString()}));let a=()=>TT(s,n);e.signal?.addEventListener("abort",a,{once:!0}),s.on("error",c=>{if(e.signal?.removeEventListener("abort",a),c.code==="ENOENT"){o({exitCode:127,output:`${i}
413
+ ${pp}: command not found`.trim()});return}r(c)}),s.on("close",c=>{e.signal?.removeEventListener("abort",a),o({exitCode:c??1,output:i})})})}var LT=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function fp(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:LT(t),retryBlocked:n}:{mode:"single",id:t}:{mode:"picker"}}function ui(e,t){let n=Ue(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 Hw(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}),Pr(o,t,"capture"),Hu(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 mp(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([...hg(e).filter(r=>n.has(r)),...o])].sort()}function gp(e,t){let n=e.length;if(n===0)return null;let o=Fs(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(`
414
+ `)}function OT(e,t){let n=NT(e)?.outputDir??DT;return IT(jT(e,n),t)}function yp(e,t,n,o){let r=OT(e,t);return(r.annotationsMtimeMs??0)>=o&&r.rawMtimeMs!==void 0?"captured":n===0?"skipped":"failed"}function Gw(e){let t=/⊘[^\n—]*—\s*(.+)/.exec(e);return t?t[1].trim():null}var _T=/element is not (?:enabled|visible|stable|editable)|intercepts pointer events|outside of the viewport|element is not attached/i;function qw(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=>_T.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(`
415
+ `):wp(e)}function wp(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(`
416
+ `)}var MT=/^[A-Za-z0-9._-]+$/;function bp(e){return MT.test(e.id)?ai({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 Vw(e,t=AT()){try{let n=JSON.parse(hp(li(e,".d360-writer","capture.json"),"utf8").replace(/^/,"")),o=n.projectId;if(!o)try{o=JSON.parse(hp(li(e,"package.json"),"utf8")).name}catch{}o||=ET(e);let r=Object.keys(n.profiles??{}),s=n.defaultProfile??(r.length===1?r[0]:r.includes("staging")?"staging":r[0]);return s?Bw(li(t,".document360-capture","auth-states",o,`${s}.json`)):!0}catch{return!0}}function Yw(e){return ai({args:["auth","--auto"],cwd:e.cwd,stdio:"pipe",signal:e.signal})}function kp(e,t){return e===127||/is not recognized as an internal or external command|command not found/i.test(t)}function Kw(e){try{let t=JSON.parse(hp(li(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 Go(e){return Bw(li(e,".d360-writer","capture.json"))}function $p(){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(`
417
+ `)}function zw(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(", ")}
418
+ /screenshot list --detail shows what each one needs`}function Xw(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):ci(r?.reason)!==ci(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):La(r?.reason??"")!==La(o.detail??"")?n.blockedNewReason.push(o.id):n.blockedAsBefore.push(o.id))}return n}function ci(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 Qw(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?Tr(o.detail):"no reason recorded"}`)}function Wr(e,t=2){return e.length<=t?e.join(" \xB7 "):`${e.slice(0,t).join(" \xB7 ")} \xB7 +${e.length-t}`}function Jw(e,t){if(!t)return[];let n=[],o=(i,a,c,l)=>{a>0&&n.push({glyph:i,label:`${a} ${c}`,tail:l})};if(o("\u2713",e.newlyCaptured.length,"newly captured",Wr(e.newlyCaptured)),o("\u2717",e.newlyBroken.length,"newly broken",Wr(e.newlyBroken)),o("\u2192",e.repairedNowBlocked.length,"repaired",`no longer broken \u2014 only data stands in the way \xB7 ${Wr(e.repairedNowBlocked)}`),o("\u2298",e.newlyBlocked.length,"newly blocked",Wr(e.newlyBlocked)),o("\u2192",e.blockedNewReason.length,"blocked on something new",`an earlier step now passes \xB7 ${Wr(e.blockedNewReason)}`),o("\u2192",e.brokeDifferently.length,"broken differently",`the previous cause is fixed \xB7 ${Wr(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 Zw(e){let t=e.results.filter(T=>T.outcome==="captured"),n=e.results.filter(T=>T.outcome==="skipped"),o=e.results.filter(T=>T.outcome==="failed"),r=e.unannotated??[],s=T=>T===1?"":"s";if(t.length+n.length+o.length===0)return null;let i=e.articles.length===1?`/push ${e.articles[0]}`:Se("/push","--screenshots",Lt(e.articles)),a=e.ids.length===1?`/screenshot capture ${e.ids[0]}`:"/screenshot capture",c=o[0]?.id,l=[];o.length>0&&l.push({glyph:"\u2717",cmd:`/screenshot ${c}`,why:`re-author the ${o.length===1?"broken spec":`first of ${o.length} broken specs`} \u2014 re-running fails the same way`});let f=Se("/screenshot annotate","",r.length===1?r[0]:void 0);r.length>0&&l.push({glyph:"\u25C8",cmd:f,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&&l.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&&l.push({glyph:"\u2713",cmd:i,why:`embed the ${t.length-r.length} new PNG${s(t.length-r.length)}`});let g=Math.max(...l.map(T=>T.cmd.length));return{note:l.map(T=>`${T.glyph} ${T.cmd.padEnd(g)} ${T.why}`).join(`
419
+ `),cmd:o.length>0?`/screenshot ${c}`:r.length>0?f:t.length>0?i:a,tone:o.length>0||r.length>0?"warn":"info"}}function eb(e,t){let n=new Map(Ue(e).map(o=>[o.id,o.file]));return[...new Set(t.map(o=>n.get(o)).filter(o=>!!o))].sort()}async function vp(e,t){let n=t?.cwd??process.cwd(),o=fp(e);if(!Go(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}=ui(n,o.mode==="scope"?o.scope:void 0),c=mp(n,a),l=(o.mode==="all"||o.mode==="scope")&&o.retryBlocked,f=o.mode==="single"?[o.id]:o.mode==="failed"?c:o.mode==="blocked"?i:o.mode==="picker"?r:[...r,...s,...l?i:[]];if(f.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(!l&&o.mode!=="single"&&o.mode!=="failed"&&o.mode!=="blocked"){let S=gp(a.filter(C=>C.state==="blocked"),"/screenshot capture --blocked");S&&console.log(S)}let g=Date.now(),$=[];for(let S of f){console.log(`\u25B6 ${S}`);try{let{exitCode:C}=await bp({cwd:n,id:S,stdio:"inherit"});$.push({id:S,outcome:yp(n,S,C,g)})}catch(C){if(C.code==="ENOENT")return console.log("d360-capture is not installed. Run: npm i -g document360-capture"),{kind:"continue"};$.push({id:S,outcome:"failed",detail:C.message})}}let T=S=>$.filter(C=>C.outcome===S).length;console.log(`\u2713 ${T("captured")} captured \xB7 \u2298 ${T("skipped")} skipped \xB7 \u2717 ${T("failed")} failed`);let A=$.filter(S=>S.outcome==="captured");return Sa(n,$.map(S=>({id:S.id,outcome:S.outcome,reason:S.detail,specSource:Oo(n,S.id)})),new Date().toISOString()),A.length>0?(console.log(to(A.length)),{kind:"forward-to-agent",prompt:dn(n,A.map(S=>S.id)),display:"/screenshot verify"}):{kind:"continue"}}import{readProjectConfig as FT,DEFAULT_OUTPUT_DIR as UT,resolveOutputDir as WT,shotArtifacts as BT,annotationCurrent as HT}from"document360-engine";Sr();var tb="0.2.29";function $l(e=kt()){return Cr(e,tb)}function xp(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 Rp(e,t){let n=Ue(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 GT=/^[A-Za-z0-9._-]+$/;function qT(e){if(!GT.test(e.id))return Promise.reject(new Error(`Not a valid spec id: "${e.id}"`));let t=["annotate",e.id,...e.force?["--force"]:[]];return ai({args:t,cwd:e.cwd,stdio:e.stdio,signal:e.signal})}function VT(e,t,n,o){let r=WT(e,FT(e)?.outputDir??UT),s=BT(r,t);return(s.annotatedMtimeMs??0)>=o?"annotated":n===0&&HT(s)?"skipped":"failed"}function Sp(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 ${tb} or later, then /screenshot annotate becomes available.`}var vl=8;function nb(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:Se("/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>vl?{glyph:"\u25C8",cmd:Se("/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:Se("/screenshot verify","",e.scope),why:`${n.length} picture${n.length===1?"":"s"} ready to check \u2014 no browser needed`}}async function Cp(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 qT({cwd:e.cwd,id:o,...e.force?{force:!0}:{},...e.signal?{signal:e.signal}:{},stdio:"pipe"}),i=VT(e.cwd,o,r,t);n.push({id:o,outcome:i,...i==="failed"?{detail:YT(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 Pp(e,t){let n=t?.cwd??process.cwd(),o=xp(e);if(!Go(n))return console.log("Screenshot capture is not set up in this repo yet. Run: d360-capture init"),{kind:"continue"};let r=kt();if(!$l(r))return console.log(Sp(r)),{kind:"continue"};let s=Lo(n);s&&console.log(s);let i=o.mode==="scope"?o.scope:void 0,{pending:a,done:c,rows:l}=Rp(n,i),f=o.mode==="all"||o.mode==="scope"?o.force:!1,g=o.mode==="single"?[o.id]:f?[...a,...c]:a;if(g.length===0){let j=c.length>0;return console.log(j?`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(l.filter(j=>j.state==="verified").map(j=>j.id)),{results:T,cliMissing:A}=await Cp({cwd:n,ids:g,force:f});if(A)return console.log("d360-capture is not installed. Run: npm i -g document360-capture"),{kind:"continue"};let S=j=>T.filter(W=>W.outcome===j).length;console.log(`\u2713 ${S("annotated")} annotated`+(S("skipped")?` \xB7 ${S("skipped")} already current`:"")+(S("failed")?` \xB7 \u2717 ${S("failed")} failed`:""));for(let j of T.filter(W=>W.outcome==="failed"))console.log(` \u2717 ${j.id}${j.detail?` \u2014 ${j.detail}`:""}`);let C=T.filter(j=>j.outcome==="annotated").map(j=>j.id);if(C.length===0)return{kind:"continue"};let x=C.filter(j=>$.has(j)).length;if(x>vl)return console.log(`\u26A0 ${x} verified shots were re-drawn, so their verdicts no longer describe the picture on disk.
420
+ Check them when you're ready: ${Se("/screenshot verify","",i)}`),{kind:"continue"};let E=C.filter(j=>!$.has(j)||x>0);return E.length===0?{kind:"continue"}:(console.log(to(E.length)),{kind:"forward-to-agent",prompt:dn(n,E),display:"/screenshot verify"})}function YT(e){return e.split(/\r?\n/).map(n=>n.trim()).filter(n=>n.length>0&&!/^[▶✓↕]/.test(n)).at(-1)}oe();import{existsSync as KT}from"node:fs";import{join as zT}from"node:path";import{builderChannelWired as XT,driftedAnchors as QT,readTestidRequests as JT,testidHandoffPrompt as ZT,testidRequestPaths as eA,writerDir as tA}from"document360-engine";async function Br(e,t){let n=t?.cwd;if(n){let r=nA(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(`
421
+ `),display:"/screenshot checklist"}}function nA(e){let t;try{t=Ue(e)}catch{return null}let n=KT(zT(tA(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?[`${K("\u25CB",d)}No screenshots are planned yet, so there is nothing to stage.`,d(" A screenshot is planned by the article that needs it. /write adds the placeholders as it writes.")]:[`${K("\u25CB",d)}${r} screenshot${r===1?"":"s"} planned across ${s} article${s===1?"":"s"} \u2014 none captured, none with a spec, and no capture setup yet.`,d(" There is nothing to stage from yet: a checklist is built from what each spec needs, and no specs exist."),d(" /screenshot author writes the specs. Come back to /screenshot checklist once they exist and it will"),d(" tell you what data to stage and which test ids your developers still owe you."),"",d(" Free \u2014 this read your files and called nothing.")]}var ob="-".repeat(64);function rb(e){let t=JT(e);if(t.length===0)return null;let{mdRel:n}=eA(e),o=t.length,r=new Set(t.map(f=>f.file).filter(Boolean)).size,s=`${o} data-testid attribute${o===1?"":"s"}`,i=`${r} source file${r===1?"":"s"}`,a=ZT(e,o),c=QT(t).length,l=c>0?[` \u26A0 ${c} of ${c===1?"them quotes":"them quote"} code that has changed since \u2014 still likely right,`,` but ${c===1?"it says":"they say"} so, and ${c===1?"asks":"ask"} to be found by description instead.`]:[];return XT(e)?{prompt:a,lines:[`\u{1F4CB} Developer hand-off \u2014 ${s} requested across ${i}.`,...l," 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}.`,...l,"\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.)","",ob,a,ob]}}Gn();oe();import{listOpenForDocs as oA,readProjectConfig as rA}from"document360-engine";function Tp(e){try{return oA(e).length}catch{return 0}}function Ap(){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(`
422
+ `)}async function sb(e,t){let n=t?.cwd??process.cwd();return rA(n)?Tp(n)===0?(console.log(d("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:Ap(),display:"/inbox"}:(console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"})}oe();import{askBuilder as sA,openGapQuestions as ib,readProjectConfig as iA}from"document360-engine";function di(e){try{return ib(e).length}catch{return 0}}function Ep(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 Np(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 ab(e,t,n){let o=t?.cwd??process.cwd();if(!iA(o))return console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e.join(" ").trim();if(r===""){for(let s of Np(ib(o)))console.log(s.startsWith(" \xB7")?d(s):s);return{kind:"continue",ownNext:!0}}try{let s=sA(o,{question:r,...n?{article:n}:{}}),i=di(o);for(let a of Ep(s.file,i))console.log(a.startsWith("\u2713")?Q(a):d(a))}catch(s){console.log(q(`Could not file the question: ${s.message}`))}return{kind:"continue",ownNext:!0}}oe();import{listOpenHints as db,listOpenForDocs as hA,listOpenDirectives as fA,readProjectConfig as pb,computeSyncStatus as mA,planPull as gA,applyPull as yA,planImport as wA,applyImport as bA,pullDocsUpdates as kA,handoffAvailable as $A,readProductBriefState as vA,readDiscoveryQueue as xA,partitionOpenHints as hb,askAboutUnfinishedHint as RA,briefMoved as SA}from"document360-engine";oe();import{readProjectConfig as aA,writeProjectConfig as lb,reconcileDocsGit as lA,pullDocsUpdates as cA,probeGitState as uA,resolveGitHandoff as cb,handoffAvailable as dA}from"document360-engine";var pi=e=>e===1?"":"s";function no(e,t){let n=o=>{let r=(o??"").split(`
423
+ `).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 xl(e,t){let n=cb(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=uA(e);if(!o)return[{tone:"info",text:"Sharing: unavailable \u2014 this folder is not a git repository."}];if(!o.upstream)return[{tone:"warn",text:K("\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:K("\u26A0")+`${o.ahead} change${pi(o.ahead)} not shared yet \u2014 run /share`}):s.push({tone:"ok",text:K("\u2713")+"Everything is shared with your team."}),s}function Dp(e,t,n){lb({...t,gitHandoff:{commit:n,push:n}},e);let o=n?{tone:"ok",text:K("\u2713")+"Sharing on \u2014 d360-writer will save and send its own work from now on."}:{tone:"ok",text:K("\u2713")+"Sharing off \u2014 d360-writer will leave its work for your coding agent to commit."};return n?[o,...xl(e,{...t,gitHandoff:{commit:!0,push:!0}})]:[o]}async function Rl(e,t){let n=[],o=cb(t);if(!o.commit)return{lines:[{tone:"info",text:no("disabled")}],changed:!1};let r=t;o.push==="unconfirmed"&&dA(e,t)&&(r={...t,gitHandoff:{commit:!0,push:!0}},lb(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 cA(e);if(s.ok&&s.pulled>0){let l=[s.newHints>0?`${s.newHints} new hint${pi(s.newHints)}`:null,s.newMessages>0?`${s.newMessages} new message${pi(s.newMessages)}`:null].filter(Boolean);n.push({tone:"ok",text:K("\u2B07")+`Got your builder's latest${l.length?` \u2014 ${l.join(", ")}`:""}.`})}else!s.ok&&s.reason!=="no-upstream"&&s.reason!=="no-git"&&n.push({tone:"warn",text:K("\u26A0")+no(s.reason,s.detail)});let i=await lA(e,r);if(i.commit&&!i.commit.ok)return n.push({tone:"warn",text:K("\u26A0")+no(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:K("\u2713")+`Saved ${a} change${pi(a)} to the docs folder.`}),i.push&&!i.push.ok)return n.push({tone:"warn",text:K("\u26A0")+no(i.push.reason,i.push.detail)}),{lines:n,changed:a>0};let c=i.push?.ok?i.push.pushed:0;return c>0?n.push({tone:"ok",text:K("\u2B06")+`Shared ${c} change set${pi(c)} with your team.`}):a===0&&(s.ok&&s.pulled===0)?n.push({tone:"ok",text:K("\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||c>0||s.ok&&s.pulled>0}}var pA={ok:Q,info:Te,warn:q,error:L};async function ub(e,t){let n=t.cwd,o=aA(n);if(!o)return console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase(),s=a=>{for(let c of a)console.log(pA[c.tone](c.text))};if(r==="status")return s(xl(n,o)),{kind:"continue"};if(r==="on"||r==="off")return s(Dp(n,o,r==="on")),{kind:"continue"};if(r)return console.log(L(`Unknown option "${r}". Use /share, /share status, /share on, or /share off.`)),{kind:"continue"};console.log(d("Exchanging work with your team\u2026"));let{lines:i}=await Rl(n,o);return s(i),{kind:"continue"}}function Zt(e){let t=0,n=0,o=0,r=0,s=0,i=0;try{let c=hb(e,db(e));t=c.actionable.length,n=c.held.length,o=c.held.filter(l=>l.asked).length}catch{}try{let c=hA(e);r=c.filter(l=>l.kind==="request").length,s=c.filter(l=>l.kind==="answer").length}catch{}try{i=fA(e).length}catch{}let a=!1;try{a=SA(e)}catch{}return{hints:t,requests:r,answers:s,directives:i,held:n,heldAsked:o,briefMoved:a}}async function Ip(e){let t=pb(e);if(!t)return[];if(!$A(e,t))return[];let n=await kA(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 ${no(n.reason,n.detail)}`}]}function Hr(e){let t=[];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"}`);let n=t.join(", ");return e.briefMoved?n?`${n} and an updated product brief`:"an updated product brief":n||null}function Lp(e){let t=Hr(e);return t?`Catching up on ${t}\u2026`:"Nothing queued from your builder \u2014 checking Document360 for reviewer comments and feedback\u2026"}function Cl(e){let t={...e.queued,briefMoved:!1},n=Hr(t);if(n)return{tone:"warn",note:`${K("\u26A0")}That run finished without writing anything, and ${n} ${t.hints+t.requests+t.answers+t.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"}};if(e.queued.held>0){let o=e.queued.held;return{tone:"info",note:`${K("\u2139")}Nothing to write yet \u2014 your builder's ${o} note${pn(o)} ${o===1?"is":"are"} waiting on code that isn't finished. ${o===1?"It stays":"They stay"} queued.`,lead:null}}return e.hold?{tone:"info",note:`${K("\u2139")}No articles changed \u2014 product discovery is still open, so new overview and concept pages are on hold.`,lead:null}:{tone:"info",note:`${K("\u2713")}Nothing needed writing \u2014 no articles changed.`,lead:null}}function Op(e){return{push:e.includes("--push")||e.includes("--publish"),skipReview:e.includes(Ot),includeUnfinished:e.includes(Pl)}}var Pl="--include-unfinished";function hi(e){let t={hold:!1,openQuestions:0,answersPending:0};try{let n=vA(e);return!n||n.status==="confident"?t:{hold:!0,...xA(e)}}catch{return t}}function _p(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:`${K("\u2139")}Product discovery is still open \u2014 ${n} answer${pn(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:`${K("\u26A0")}Product discovery isn't finished \u2014 ${n} question${pn(n)} still with your builder.`},{tone:"warn",text:` ${t} until the brief is settled.`}]}return[{tone:"warn",text:`${K("\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 Mp(e){try{return hb(e,db(e)).held}catch{return[]}}function Fp(e,t){let n=0;for(let o of t)try{RA(e,{hintFile:o.file,surface:o.surface,sources:o.unfinished})&&(n+=1)}catch{}return n}var jp=3;function Up(e,t){if(e.length===0)return[];let n=e.length,o=[];if(e.every(r=>r.unfinished.length===0))return o.push({tone:"warn",text:`${K("\u26A0")}Your repository is in the middle of a merge, so the code isn't settled yet.`}),o.push({tone:"warn",text:` I've left your builder's ${n} note${pn(n)} for now. Finish the merge and I'll pick ${n===1?"it":"them"} up.`}),o;o.push({tone:"warn",text:`${K("\u26A0")}${n} of your builder's note${pn(n)} describe${n===1?"s":""} code that isn't finished, so I've left ${n===1?"its page":"those pages"} for now:`});for(let r of e.slice(0,jp))o.push({tone:"warn",text:` \xB7 ${r.surface||r.file}`});return n>jp&&o.push({tone:"warn",text:` \xB7 and ${n-jp} more`}),o.push({tone:"info",text:t>0?` I've asked your builder whether ${t===1?"it is":"they're"} done. Everything else is written as normal.`:` Your builder already has my question about ${n===1?"it":"those"}. Everything else is written as normal.`}),o}function Wp(e={hold:!1,openQuestions:0,answersPending:0},t={held:0,includeUnfinished:!1},n=!1){let o=["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(t.held>0&&o.push(t.includeUnfinished?"2b. THE USER ASKED FOR THE UNFINISHED WORK TOO. Some hints came back under `held` rather than in the main list: the files they cite have uncommitted changes, so the surface they describe is still being edited and what you read may change before it ships. Document them anyway this run, as drafts, grounded strictly in the code as it stands \u2014 never in what you expect it to become. Treat them as normal hints otherwise (resolve the article the same way, stamp them consumed). In your closing summary name each one and say plainly that the code behind it was still being edited, so those pages want a re-read once it lands.":"2b. SOME HINTS ARE HELD, and they are not yours to act on this run. They came back under `held` rather than in the main list because the files they cite have uncommitted changes: the builder is still typing that surface, so anything you documented from it would describe something readers will not recognise. Do NOT document a held hint, do NOT go reading its code to judge it for yourself, and do NOT stamp it consumed \u2014 it stays queued and returns on its own once the code lands. The builder has ALREADY been asked whether each one is finished, so do not file another question about them. In your closing summary, name what is waiting in plain words and say that nothing else is blocked. Then write everything else normally."),n&&o.push("2c. THE BUILDER HAS REWRITTEN THEIR ARCHITECTURE BRIEF since the docs last caught up. Read every `.md` in `.d360-writer/architecture/` (except CREATOR-NOTES.md, which is the human owner's and is covered elsewhere) and work out what is NEW or CHANGED in it versus what the existing articles say. A brief refresh is a hand-off like any other, and it is the one that arrives without a hint file: the builder may have described a surface nobody has documented, corrected how an existing one actually works, or changed the product's own vocabulary. Treat what you find as proposals for step 4 \u2014 a new article, an update to an existing one, or nothing at all when the change was internal or editorial. Do NOT rewrite the brief, and do NOT treat it as a directive: it is grounding, and what the docs owe it is your judgment."),e.hold){let r=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${pn(e.openQuestions)}`:"continue product discovery to settle the brief";o.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: ${r}.`)}return o.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 close each hint with d360_hint_done \u2014 the ONLY way to close one; never edit a hint file yourself. Pass outcome: documented plus the article path(s) you changed this run; use already-covered, retired or no-doc-change WITH a short note when no article needed writing. 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)."),o.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.'),o.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."),o.join(`
424
+ `)}var CA={status:mA,plan:gA,apply:yA,planImport:wA,applyImport:bA};async function Bp(e,t=CA){let n={pulled:[],imported:[],conflicts:[],failed:[],needFolders:[]},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){if(r.remoteCategory&&!r.remoteCategory.hasLocalFolder){n.needFolders.push(r.title??r.articleId);continue}try{let s=await t.planImport({cwd:e.cwd,profileName:e.profileName,articleId:r.articleId,...r.remoteCategory?{categoryPath:r.remoteCategory.path}:{}});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 Sl=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,pn=e=>e===1?"":"s";function Hp(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${pn(e.pulled.length)} into local: ${Sl(e.pulled)}`),e.imported.length&&t.push(`\u2713 Imported ${e.imported.length} new portal article${pn(e.imported.length)} into local drafts: ${Sl(e.imported)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${pn(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${Sl(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.`),e.needFolders.length&&t.push(`\u2139 ${e.needFolders.length} portal article${pn(e.needFolders.length)} ${e.needFolders.length===1?"is":"are"} in a category with no folder here \u2014 /pull creates ${e.needFolders.length===1?"it":"them"} and imports ${e.needFolders.length===1?"the article":"the articles"}: ${Sl(e.needFolders)}`),t}async function fb(e,t){let n=t?.cwd??process.cwd();if(!pb(n))return console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Je(n,t?.profileName);if(!o.ok)return console.log(L(o.reason)),{kind:"continue"};let{push:r,includeUnfinished:s}=Op(e);for(let $ of await Ip(n))console.log($.tone==="ok"?Q($.text):q($.text));console.log(d("Reconciling with Document360 (pulling any portal changes)\u2026"));let i=await Bp({cwd:n,profileName:t?.profileName});for(let $ of Hp(i))console.log($.startsWith("\u2713")?Q($):$.startsWith("\u2139")?d($):q($));let a=hi(n);for(let $ of _p(a))console.log($.tone==="warn"?q($.text):d($.text));let c=Mp(n),l=s?[]:c,f=Fp(n,l);for(let $ of Up(l,f))console.log($.tone==="warn"?q($.text):d($.text));let g=Zt(n);return console.log(d(Lp(g))),{kind:"forward-to-agent",prompt:Wp(a,{held:c.length,includeUnfinished:s},g.briefMoved),display:`/catch-up${r?" --push":""}${s?` ${Pl}`:""}`}}oe();import{resolveActiveProfile as NA,resolveProjectId as DA,loadProfileMap as jA,readCommentLedger as IA,isCommentOpen as LA,saveOpenCommentCount as OA,loadCommentSweepMemory as _A,recordCommentSweep as MA,planCommentSweep as FA,sweepOpenComments as UA,loadUserNames as WA,writeReviewerNotes as BA,sweptFromResult as HA,needsFullArchivePass as GA,reviewerNotesPath as qA,commentHtmlToText as mb,annotatedText as VA,readProjectConfig as YA,loadPortalLabels as KA,portalBreadcrumb as qp,portalCategoryPath as zA,resolveModelForOperation as XA,runPartitioned as QA,snapshotArticles as JA,EMPTY_PORTAL_LABELS as ZA}from"document360-engine";import Ne from"picocolors";import{CONTENT_CAP_VERSION as PA,stampArticles as TA,articlesChangedSince as AA,docsRootOf as EA}from"document360-engine";function qo(e,t,n="",o){let r=[];try{r=AA(e,t)}catch{return{changed:[],cta:null}}if(r.length===0)return{changed:[],cta:null};try{TA(e,r,{writtenCap:PA,reviewedCap:0,checkedCap:0})}catch{}let s=EA(e),i=f=>{let g=f.replace(/\\/g,"/");return g.startsWith(`${s}/`)?g.slice(s.length+1):g},a=Lt(r.map(i)),c=r.length,l=a?"/push":"/push --all";try{return{changed:r,cta:_t(e,{text:`${n}${c} article${c===1?"":"s"} updated \u2014 ${l} saves ${c===1?"it":"them"} to Document360 as ${c===1?"a draft":"drafts"}.`,cmd:l},n,a,o)}}catch{return{changed:r,cta:null}}}var yb=300,fi=3;function eE(e,t){let n=$a(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||qn(n).toLowerCase()===o}async function Tl(e,t,n={}){let o=NA(e,t),r={profile:o.name,connection:o.connection,projectId:o.project.projectId,projectName:o.project.projectName},s=DA(r,o.project.projectId),i=jA(e,o.name);if(!i)return{threads:[],answered:[],labels:ZA,scanned:0,failed:[],truncated:0,skipped:0,archived:!1};let a=IA(e,o.name),c=new Set(Object.values(a).map(B=>B.articlePath).filter(B=>!!B)),l=Object.keys(a).length===0||c.size>0,f=n.articleIds?.length?new Set(n.articleIds):null,g=!!(f||n.path||n.scope),$=Object.entries(i.articles).filter(([,B])=>!!B.id).filter(([B,ue])=>f?f.has(ue.id):n.path?B.replace(/\\/g,"/")===n.path.replace(/\\/g,"/"):n.scope?eE(B,n.scope):!0).map(([B,ue])=>({articleId:ue.id,path:B,title:va(e,B),answered:g||(l?c.has(B):!0)})),T=$.slice(0,yb),A=await KA(r,s,o.project.workspaceId,{cwd:e,profile:o.name}),S=g||n.full?{read:T,skipped:[]}:FA(T,{live:A.live,stateOf:B=>A.articles.get(B),memory:_A(e,o.name),alwaysRead:new Set($.filter(B=>c.has(B.path)).map(B=>B.articleId))}),C=o.project.languageCode,x=GA(e)||!!n.full,E=await UA(r,s,S.read,{isOpen:(B,ue)=>LA(a,B.id??"",ue,B),...C?{langCode:C}:{},...n.onProgress?{onProgress:n.onProgress}:{},...x?{includeResolved:x}:{}}),j=E.threads.length>0||E.answered.length>0?await WA(r,s):new Map,W=BA(e,HA(E.threads,E.answered,B=>qp(A,B)),{userNames:j,ourReplyIds:Object.values(a).flatMap(B=>B.replyIds??[]),...x?{completeFor:S.read.filter(B=>!E.failed.some(ue=>ue.articleId===B.articleId)).map(B=>B.articleId)}:{}});g||OA(e,o.name,E.threads.length);let Y=new Map;for(let B of[...E.threads,...E.answered])Y.set(B.articleId,(Y.get(B.articleId)??0)+1);return MA(e,o.name,{live:A.live,read:S.read.map(B=>B.articleId),failedIds:E.failed.map(B=>B.articleId),threadCounts:Y,latestVersionOf:B=>A.articles.get(B)?.latestVersion}),{threads:E.threads,answered:E.answered,labels:A,scanned:E.scanned,failed:E.failed,truncated:Math.max(0,$.length-T.length),skipped:S.skipped.length,archived:W}}function tE(e,t=96){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n}var gb=500;function nE(e){let t=VA(e.comment);if(!t)return"a passage";let n=t.replace(/\s+/g," ").trim();if(n.length<=gb)return e.comment.commented_text_truncated?`\u201C${n}\u2026\u201D
425
+ (Document360 sends the first 500 characters of a highlight)`:`\u201C${n}\u201D`;let o=n.slice(0,gb).trimEnd(),r=n.length-o.length;return`\u201C${o}\u2026\u201D
426
+ (+${r} more character${r===1?"":"s"}${e.comment.commented_text_truncated?", and Document360 caps a highlight at 500":""})`}function oE(e,t){let n=zA(t,e.articleId);return n.length>0?n.join(" \u203A "):e.path?qn(e.path):""}function rE(e,t){return t.articles.get(e.articleId)?.title?.trim()||e.title||(e.path?Os(e.path):e.articleId)}function sE(e,t){return qp(t,e.articleId,{category:e.path?qn(e.path):null,title:e.title??(e.path?Os(e.path):null)})??e.path??e.articleId}function Vo(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:oE(o,t),title:rE(o,t),label:sE(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 iE=100,aE=120,wb=(e,t)=>Math.max(40,Math.min(e??96,t));function bb(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`),`${Ne.bold("Reviewer comments")} ${r.join(` ${Ne.gray("\xB7")} `)}`}function Gp(e){let t=[],n=o=>o===1?"":"s";if(e.skipped>0&&t.push(Ne.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(`${K("\u26A0",Ne.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=qp(e.labels,o.articleId,{title:o.title})??o.title??o.articleId;t.push(` ${Ne.gray(`${r} \u2014 ${tE(o.error,60)}`)}`)}e.failed.length>5&&t.push(` ${Ne.gray(`+${e.failed.length-5} more`)}`),t.push(Ne.gray(" Run /comments again to retry them."))}return e.truncated&&t.push(`${K("\u26A0",Ne.yellow)}Checked the first ${yb} articles; ${e.truncated} not checked this run.`),e.archived&&(e.threads.length>0||e.answered.length>0)?t.push(Ne.gray(` Everything reviewers have written is kept in ${qA(".").replace(/\\/g,"/").replace(/^\.\//,"")} \u2014 it outlives a rewrite.`)):!e.archived&&(e.threads.length>0||e.answered.length>0)&&t.push(`${K("\u26A0",Ne.yellow)}Couldn\u2019t write the reviewer-notes file, so Document360 is still the only copy of these notes.`),t}function mi(e,t={}){let n=[],o=a=>a===1?"":"s",r=e.answered.length,s=()=>{if(!(!t.showAnswered||r===0)){n.push(` ${Ne.gray(`Answered, waiting on the reviewer (${r})`)}`);for(let a of Vo(e.answered,e.labels))n.push(` ${Ne.gray(`${a.label} \u2014 ${a.threads.length} thread${o(a.threads.length)}`)}`);n.push("")}};if(e.threads.length===0){let a=r>0?` ${Ne.gray("\xB7")} ${r} answered, awaiting reviewer`:"",c=e.scanned+e.skipped;return n.push(e.skipped>0?`${K("\u2713",Ne.green)}No open reviewer comments in the ${e.scanned} article${o(e.scanned)} checked ${Ne.gray("\xB7")} ${e.skipped} of ${c} not checked${a}`:`${K("\u2713",Ne.green)}No open reviewer comments across ${e.scanned} article${o(e.scanned)}.${a}`),r>0?(n.push(Ne.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(Ne.gray(" /comments --answered lists them."))):n.push(Ne.gray(" Reviewers leave these by highlighting text in a draft in the Document360 portal and commenting on it.")),n.push(""),s(),n.push(...Gp(e)),n}let i=Vo(e.threads,e.labels);return n.push(bb(e)),n.push(""),n.push(Xs(["#","Category","Article","Comments"],i.map((a,c)=>[`${c+1}`,a.category||"(root)",a.title,`${a.threads.length}`]),wb(t.width,iE),{plain:!0,align:["left","left","left","right"]})),n.push(""),s(),n.push(...Gp(e)),n}function Al(e,t={}){let n=s=>s===1?"":"s",o=[`${Ne.gray("Category:")} ${e.category||"(root)"}`,`${Ne.gray("Article: ")} ${Ne.bold(e.title)}`,Ne.gray(`${e.threads.length} comment${n(e.threads.length)} from your reviewers`),""],r=e.threads.map(s=>{let i=[mb(s.comment.comment)||"(empty comment)"];for(let a of s.comment.replies??[])i.push(`\u21B3 ${mb(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)"),[nE(s),i.join(`
427
+ `)]});return o.push(Xs(["Annotated text","Comment"],r,wb(t.width,aE),{plain:!0})),o.push(""),o}function El(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 Vp(e,t={}){let n=Vo(e.threads,e.labels);if(t.full&&n.length===1){let o=n[0];return[bb(e),"",...Al(o,t),...Gp(e)]}return mi(e,t)}function lE(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 Yp(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.`,"",...lE({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(`
428
+ `)}function Kp(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 cE(e,t,n){if(t.length===0)return{kind:"continue"};let o=t.reduce((g,$)=>g+$.threads.length,0),{model:r}=XA(e.cwd,"standard"),s=new Map(t.map(g=>[g.label,g])),i=t.map(g=>({label:g.label,paths:g.path?[g.path]:[]}));console.log(d(`Answering ${o} comment${o===1?"":"s"} across ${i.length} article${i.length===1?"":"s"} (\u2264${fi} 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(),c=JA(e.cwd);try{for await(let g of QA({cwd:e.cwd,partitions:i,promptFor:$=>{let T=s.get($.label);return Yp({articleId:T.articleId,label:T.label,path:T.path,count:T.threads.length,resolve:n.resolve})},concurrency:fi,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),allowCommentResolve:n.resolve,model:r}))if(g.type==="partition_status")g.status==="running"?console.log(d(` \u25B8 ${g.label} \u2014 answering\u2026`)):g.status==="done"?console.log(Q(` \u2713 ${g.label}`)):console.log(L(` \u2717 ${g.label}`));else if(g.type==="run_done"){let $=g.results.filter(T=>!T.ok);console.log(""),console.log(`${g.results.length-$.length}/${i.length} article${i.length===1?"":"s"} answered.`),$.length&&console.log(q(`\u26A0 ${$.length} left untouched (their comments are still open, so nothing was promised to those reviewers): ${$.map(T=>T.label).join(", ")}`)),g.blocked&&console.log(q(`\u26A0 ${g.blocked}`)),g.allEmpty&&console.log(q("\u26A0 No agent produced any work this run \u2014 nothing was changed or answered.")),console.log(d(cn(Ft(a,g.results,g.totalCostUsd))))}}catch(g){console.log(L(`Answering comments failed: ${g.message}`))}let f=qo(e.cwd,c,"","/comments").changed.length;return f>0&&console.log(`${f} article${f===1?"":"s"} changed, and that new text has not been read by an editor \u2014 ${f===1?"it":"they"} can go live once /review has been over ${f===1?"it":"them"}.`),{kind:"continue"}}async function kb(e,t){let n=t?.cwd??process.cwd();if(!YA(n))return console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Je(n,t?.profileName);if(!o.ok)return console.log(L(o.reason)),{kind:"continue"};let r=Kp(e);console.log(d("Checking Document360 for reviewer comments\u2026"));let s;try{s=await Tl(n,t?.profileName,r.scope)}catch(a){return console.log(L(`Couldn\u2019t read comments from Document360: ${a.message}`)),{kind:"continue"}}for(let a of Vp(s,{full:!!r.scope.path,showAnswered:r.showAnswered}))console.log(a);if(s.threads.length===0)return{kind:"continue"};if(r.answer&&t)return cE(t,Vo(s.threads,s.labels),{resolve:r.resolve});let i=Vo(s.threads,s.labels)[0];return console.log(`${K("\u2192",Ne.yellow)}${Ne.bold("/comments <article>")} shows one article\u2019s comments in full `+Ne.gray(i?.path?`(e.g. /comments ${i.path})`:"(by its local path)")),console.log(`${K("\u2192",Ne.yellow)}${Ne.bold("/comments --answer")} fixes each one, updates the draft in Document360, then replies in the thread `+Ne.gray("(one article at a time: /comments --answer <article>, or --scope <category>)")),{kind:"continue"}}oe();import{spawn as vb}from"node:child_process";import{mkdirSync as uE,openSync as dE,readFileSync as pE}from"node:fs";import{dirname as hE,join as fE}from"node:path";import{logsDir as mE}from"document360-engine";var Yo="document360-writer",Gr=`npm i -g ${Yo}@latest`,gE="document360-capture";function yE(){return new Promise(e=>{try{let t=vb("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 gi(){return fE(mE(),"self-update.log")}function zp(e){return/\bEBUSY\b|\bETXTBSY\b|resource busy or locked|text file busy/i.test(e)}function Nl(){return process.platform==="win32"}var Xp=null;function Dl(e){Xp=e}function yi(e){return zp(e)?`Another d360-writer is still running and holding its files open. Close every d360-writer window, then run: ${Gr}`:/\bEACCES\b|permission denied|EPERM|operation not permitted/i.test(e)?process.platform==="win32"?`Permission denied. Run ${Gr} from an Administrator terminal.`:`Permission denied \u2014 your global npm folder isn't writable. Either run sudo ${Gr} , 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: ${Gr}`:/EBADENGINE|Unsupported engine/i.test(e)?`Your Node version is too old for this release. Install Node 20 or later, then run: ${Gr}`:`Run manually: ${Gr}`}function wE(e,t=6){return e.split(/\r?\n/).map(n=>n.trimEnd()).filter(Boolean).slice(-t).join(`
429
+ `)}async function wi(){let e=process.platform==="win32",n=await yE()?[Yo,gE]:[Yo],o=gi(),r=null;try{uE(hE(o),{recursive:!0}),r=dE(o,"w")}catch{r=null}let s=()=>{try{return wE(pE(o,"utf8"))}catch{return""}};return new Promise(i=>{try{let a=vb(`npm i -g ${n.map(c=>`${c}@latest`).join(" ")}`,{stdio:r===null?"ignore":["ignore",r,r],shell:!0,detached:!e,windowsHide:!0});a.on("error",c=>i({ok:!1,output:`${String(c)}
430
+ ${s()}`.trim(),packages:n})),a.on("close",c=>i({ok:c===0,output:c===0?"":s(),packages:n})),e||a.unref()}catch(a){i({ok:!1,output:String(a),packages:n})}})}var $b=[1500,2e3,2500],bE=e=>new Promise(t=>setTimeout(t,e));async function jl(e={}){let t=Xp;if(t===null)return"none";Xp=null;let n=e.run??wi,o=e.wait??bE,r=e.write??(a=>console.log(a)),s=t?`v${t}`:"the update";r(""),r(d(ne("\u2B06",`Installing ${s}\u2026 (don\u2019t close this window)`)));let i=e.spinner===!1?null:kE();try{let a={ok:!1,output:"",packages:[]};for(let c=0;a=await n(),!(a.ok||!zp(a.output)||c>=$b.length);c++)await o($b[c]);return i?.(),a.ok?(r(Q(ne("\u2713",`Updated to ${s} \u2014 it\u2019s live next time you start d360-writer.`))),"installed"):zp(a.output)?(r(q(ne("\u26A0",`Couldn\u2019t install ${s} \u2014 another d360-writer window is still open.`))),r(d(" It installs when the last one closes.")),"busy"):(r(q(ne("\u26A0",`Couldn\u2019t install ${s}. ${yi(a.output)}`))),r(d(` Full output: ${gi()}`)),"failed")}catch{return i?.(),"failed"}}function kE(){if(!process.stdout.isTTY)return null;let e=0,t=setInterval(()=>{e=e%3+1,process.stdout.write(`\r ${".".repeat(e)}${" ".repeat(3-e)}`)},1e3);return()=>{clearInterval(t),process.stdout.write("\r \r")}}async function xb(){if(Nl())return Dl(""),console.log(d("\u2B06 Windows can\u2019t replace the files while d360-writer is running.")),console.log(d(" I\u2019ll install the update the moment you /exit.")),{kind:"continue"};console.log(d("Updating the d360-writer toolchain\u2026"));let e=await wi();return e.ok?(console.log(Q(`\u2713 Updated ${e.packages.join(" + ")}. Exit (/exit) and relaunch d360-writer to apply.`)),{kind:"continue"}):(console.log(L(`Update failed. ${yi(e.output)}`)),e.output&&console.log(d(e.output)),console.log(d(`Full output: ${gi()}`)),{kind:"continue"})}oe();Gn();import{existsSync as Qp,rmSync as $E}from"node:fs";import{basename as Rb,resolve as Jp}from"node:path";import{execFileSync as vE}from"node:child_process";import{input as xE}from"@inquirer/prompts";import{readProjectConfig as RE,devHintsGuidePath as SE}from"document360-engine";var CE=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],PE=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),Il=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),Sb=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function Cb(e){let t=Il(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:Sb(t)?!0:PE.has(t)}function Zp(e){let t=null;try{t=RE(e)}catch{t=null}let n=new Set(CE);for(let o of[Il(t?.docsDir),Il(t?.captureDir),Il(t?.outputDir)])o&&Sb(o)&&n.add(o);return[...n].filter(o=>Cb(o)&&Qp(Jp(e,o)))}function eh(e,t){let n=[],o=[];for(let r of t){if(!Cb(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{$E(Jp(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function Pb(e,t){try{return vE("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
431
+ `).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function TE(e){return Pb(e,".d360-writer/hints")}function AE(e){return Pb(e,".d360-writer/messages")}function th(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=TE(e),o=AE(e),r=Qp(Jp(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: ${Rb(e)}`]}async function Tb(e,t){let n=Zp(t.cwd);for(let c of th(t.cwd,n))console.log(n.length===0?d(c):c);if(n.length===0)return{kind:"continue"};let o=Rb(t.cwd);if((await t.withPausedInput(()=>xE({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(q("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=Qp(SE(t.cwd)),{removed:i,failed:a}=eh(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 c of a)console.log(L(` \u2717 ${c.path}: ${c.error}`));if(s){for(let c of ya())console.log(c);console.log(d("(Select and copy the prompt above to paste into your coding agent.)"))}return console.log(d("Set up d360-writer again with /init (then /login, /workspace).")),{kind:"continue"}}oe();import{buildRegistry as sh,clearRegistryCache as EE,lintArticles as Ll,listAvailablePacks as nh,readProjectConfig as Dn,readStyleBaseline as NE,clearStyleBaseline as DE,styleBaselinePath as jE,recordStyleSwitch as IE,declineStyleSweep as LE,styleSweepOutstanding as OE,resolveActivePacks as ih,styleGuidePath as Eb,writeProjectConfig as ah,buildStyleCompilePrompt as _E,loadStyleGuide as ME,loadHouseRules as FE,buildStyleLearnPrompt as UE,reviewerNotesPath as WE,listStyleGuides as BE,getStyleGuide as HE,resolveActiveProfile as GE,resolveProjectId as qE,styleGuideSettled as VE,styleGuideUpgradeOffered as Nb,DEFAULT_PACK as lh,STYLE_GUIDE_MAX_CHARS as Ab,BUILTIN_RULES as Ol,ALWAYS_ON_PACK as oo}from"document360-engine";import{existsSync as ch,mkdirSync as YE,readFileSync as Db,writeFileSync as oh}from"node:fs";import{dirname as KE}from"node:path";import{createHash as zE}from"node:crypto";function qr(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==="sweep"?{sub:"sweep",value:t[1]}: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 XE(e){try{return ny(e,"/style-guide")?.title??null}catch{return null}}function uh(e){try{return!VE(Dn(e)?.styleGuide)}catch{return!1}}function jb(e,t){let n=[],o=new Set,r=s=>{if(o.has(s))return;o.add(s),Er(e,s).ok&&n.push(ne("\u2713",`That settles a docs-campaign step \u2014 marked done: ${s}`))};try{let s=XE(e);if(s&&r(s),t)for(let i of Fa(e,t))r(i)}catch{}return n}function QE(e){let t=Dn(e)??{projectId:""},n=ih(t.styleGuide).filter(s=>s!==oo),o=Nb(t.styleGuide);ah({...t,styleGuide:{...t.styleGuide,decidedAt:new Date().toISOString(),...o?{declinedUpgrade:lh}:{}}},e);let r=[ne("\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."),d(" Change your mind any time: /style-guide use \xB7 see the options: /style-guide list")];return r.push(...jb(e)),r}var bi="House";async function JE(e,t,n){let o,r;try{let S=GE(e,n);o={profile:S.name,connection:S.connection,projectId:S.project.projectId,projectName:S.project.projectName},r=await qE(o,S.project?.projectId)}catch(S){return{lines:[ne("\u2717",`Not signed in to Document360: ${S instanceof Error?S.message:String(S)}`),d(" Run /login first.")],restart:!1}}let s=await BE(o,r);if(s.kind!=="ok")return{lines:[ne("\u26A0",`Document360 didn't return your style guides \u2014 ${s.reason}.`),d(" Nothing is blocked. Your house style guide lives at .d360-writer/style-guide.md \u2014 write or paste"),d(" it there directly, and /review and the writer both read it. /style-guide compile then turns its"),d(" mechanical parts into checks.")],restart:!1};if(s.guides.length===0)return{lines:[ne("\u2139","This Document360 project has no style guides yet."),d(" 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((C,x)=>{let E=[C.language_code,C.created_by_name,C.created_at?.slice(0,10)].filter(Boolean).join(" \xB7 ");return` ${x+1} ${C.name??C.id}${C.is_default?d(" (default)"):""}${E?d(` ${E}`):""}`}),"",d(" 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(S=>S.id===t);if(!a)return{lines:[ne("\u2717",`No style guide numbered or identified by "${t}". Run /style-guide pull to list them.`)],restart:!1};let c=await HE(o,r,a.id,{langCode:a.language_code});if(c.kind!=="ok"){let S=c.kind==="notFound"?"Document360 could not find it (style guides are per language)":c.reason;return{lines:[ne("\u2717",`Could not read "${a.name??a.id}" \u2014 ${S}.`)],restart:!1}}let l=(c.guide.content??"").trim();if(!l)return{lines:[ne("\u26A0",`"${a.name??a.id}" has no content yet \u2014 nothing to pull.`)],restart:!1};let f=Eb(e),g=[];if(ch(f))try{oh(`${f}.bak`,Db(f,"utf8"),"utf8"),g.push(d(" Your previous guide is at .d360-writer/style-guide.md.bak"))}catch{}let $=l.length>Ab?l.slice(0,Ab):l,T=`<!-- Pulled from Document360: "${a.name??a.id}" (${new Date().toISOString().slice(0,10)}). Edit freely \u2014 /style-guide pull overwrites this file. -->
432
+
433
+ `;YE(KE(f),{recursive:!0}),oh(f,`${T}${$}
434
+ `,"utf8");let A=Dn(e)??{projectId:""};return ah({...A,styleGuide:{...A.styleGuide,pulledFrom:{styleGuideId:a.id,name:a.name??a.id,pulledAt:new Date().toISOString(),contentHash:zE("sha1").update($).digest("hex").slice(0,16)}}},e),{lines:[ne("\u2713",`Pulled "${a.name??a.id}" into .d360-writer/style-guide.md (${$.length.toLocaleString()} characters).`),...g,d(" This is PROSE, not rules \u2014 /review judges against it, and the writer now writes to it."),d(" Turn its mechanical parts into checks: /style-guide compile"),d(" Restarting the agent so it writes to the new guide\u2026")],restart:!0}}function ZE(e){let t=sh(e).rules.filter(n=>n.pack.toLowerCase()===bi.toLowerCase()).map(n=>n.id);return{prompt:_E({guide:ME(e),packName:bi,existingRuleIds:t}),display:"/style-guide compile"}}function eN(e){let t=WE(e),n=ch(t)?Db(t,"utf8").trim():"";return!n||!/^## /m.test(n)?{kind:"nothing",lines:[ne("\u2139","No reviewer comments have been read yet, so there is nothing to learn from."),d(" Reviewers comment on your drafts in Document360; /comments reads them, and every read"),d(" keeps a copy in .d360-writer/reviewer-notes.md. Run /comments first.")]}:{kind:"run",prompt:UE({notes:n,existingRules:FE(e),houseRulesFile:".d360-writer/house-rules.md"}),display:"/style-guide learn"}}function Ib(){return[d(" Read what it wrote: git diff .d360-writer/house-rules.md"),d(" These rules apply from now on \u2014 the writer follows them and /review judges against them."),d(" Disagree with one? Delete the line. It is your file, and nothing regenerates it."),d(" Restarting the agent so it writes to the new rules\u2026")]}function Lb(){return[d(` Review what it wrote: git diff .d360-writer/styles/${bi}/`),d(` Anything it could not check mechanically is listed in .d360-writer/styles/${bi}/UNCHECKABLE.md \u2014 /review judges those.`),d(` Turn them on when you are happy: /style-guide use ${bi.toLowerCase()} (they start as warnings, never blocking)`)]}var ot=(e,t)=>`${e} ${t}${e===1?"":"s"}`,rh=e=>/^v\d/i.test(e)?e:`v${e}`;function tN(e){let t=(e.description??`${e.name} style guide`).trim().replace(/\s+/g," "),n=/^(.{0,72})(?:[.,:;—]|$)/.exec(t)?.[1]?.replace(/[.,:;—\s]+$/,"").trim();if(n&&n.length>0)return n;let o=t.slice(0,72),r=o.lastIndexOf(" ");return`${r>20?o.slice(0,r):o}\u2026`}function Ob(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 nN(e){let n=Dn(e)?.styleGuide?.pulledFrom;return n?`.d360-writer/style-guide.md \u2014 pulled ${n.pulledAt.slice(0,10)} from "${n.name}"`:ch(Eb(e))?".d360-writer/style-guide.md (yours)":"the built-in default"}function oN(e){let t=Dn(e),n=sh(e),o=(t?.styleGuide?.packs??[]).filter(Boolean),r=n.packs.filter(l=>l.name.toLowerCase()===oo),s=n.packs.filter(l=>{let f=l.name.toLowerCase();return f!==oo&&f!=="d360"}),i=t?.styleGuide?.packs===void 0&&s.length>0,a=[`Style guide: ${nN(e)}`,`Rule packs: ${s.length>0?s.map(l=>`${l.name.toLowerCase()} ${rh(l.version)}`).join(", ")+(i?d(" (the default \u2014 nobody has chosen yet)"):""):d("none chosen")}`,`Always on: ${d(`d360 (correctness, built in \u2014 ${ot(Ol.length,"rule")})`)}`];for(let l of r)a.push(` ${d(`${l.name.toLowerCase()} ${rh(l.version)} (anti-slop \u2014 ${ot(l.ruleCount,"rule")})`)}`);r.length>0&&(a.push(d(" Every article here is machine-written, so these cannot be switched off by")),a.push(d(" choosing another pack. styleGuide.humanise: false turns them off deliberately.")));let c=[...Ol.map(l=>({severity:l.severity})),...n.rules.map(l=>({severity:l.severity}))];a.push("",`${ot(c.length,"rule")} active \xB7 ${Ob(c)}`);try{let l=Ll({cwd:e}),f=l.findings.filter($=>!$.baselined),g=f.filter($=>$.severity==="error").length;a.push(""),a.push(g===0?ne("\u2713",`No style errors across the docs${f.length>0?`, though ${ot(f.length,"other issue")} ${f.length===1?"is":"are"} reported`:""}.`):ne("\u2717",`${ot(g,"style error")} \u2014 /lint --blocked shows them, /lint --blocked --fix corrects them.`)),l.baselinedCount>0&&a.push(ne("\u2139",`${ot(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&&a.push(ne("\u26A0",`${ot(l.ruleErrors.length,"rule")} could not be loaded: ${l.ruleErrors.slice(0,2).map($=>`${$.ruleId} (${$.reason})`).join("; ")}`))}catch{}return a.push(""),a.push(d(" See them all: /style-guide list \xB7 change: /style-guide use \xB7 one rule: /style-guide explain <rule>")),Nb(Dn(e)?.styleGuide)&&(a.push(""),a.push("A guide built for software documentation is installed, and these docs are not on it:"),a.push(` Move to it /style-guide use ${lh}`),a.push(" Stay as you are /style-guide keep"),a.push(d(" Several rules in a general-prose guide are wrong for software documentation. This one was")),a.push(d(" measured on real knowledge bases, rule by rule, and nothing in it can block a publish."))),uh(e)&&(a.push(""),a.push("Nobody has settled this yet, and it is a decision \u2014 nothing above changed anything:"),a.push(" Happy with these rules? /style-guide keep"),a.push(" Want a stricter standard? /style-guide use microsoft (or google)"),a.push(d(" Worth settling now rather than later: it shapes every article written from here, and")),a.push(d(" changing it once a knowledge base exists means going back over what is already written."))),a}function _b(e){let t=Dn(e),n=new Set(ih(t?.styleGuide)),o=nh(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(),c=n.has(a),l=a===oo,f=c?"\u2713":"\xB7",g=l?d("(always on)"):c?d("(active)"):"",$=i.local?d(" [yours]"):"";r.push(` ${f} ${a.padEnd(s)}${$} ${i.description??""}`),r.push(` ${d(`${ot(i.rules.length,"rule")} \xB7 ${Ob(i.rules)} \xB7 ${rh(i.version)}`)} ${g}`),i.errors.length>0&&r.push(ne("\u26A0",`${ot(i.errors.length,"rule")} in this pack could not be loaded \u2014 /style-guide explain names them.`))}return o.every(i=>i.name.toLowerCase()===oo)&&(r.push(""),r.push(d(" The Microsoft and Google style guides are not installed in this build yet."))),r.push(""),r.push(d(" Turn one on: /style-guide use <name> (this replaces the chosen set, it does not add to it)")),r.push(d(" Several: /style-guide use microsoft,google")),r.push(d(" Back to none: /style-guide use none")),r}function rN(e,t){if(!t)return[ne("\u26A0","Name a rule: /style-guide explain Humanise.EmDash")];let n=sh(e),o=Ol.find(l=>l.id.toLowerCase()===t.toLowerCase()),r=n.rules.find(l=>l.id.toLowerCase()===t.toLowerCase());if(!o&&!r){let l=[...Ol.map(f=>f.id),...n.rules.map(f=>f.id)].filter(f=>f.toLowerCase().includes(t.toLowerCase())).slice(0,5);return[ne("\u26A0",`No active rule called "${t}".`),...l.length>0?[d(` Did you mean: ${l.join(", ")}`)]:[d(" /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()}`,c=[`${s} ${i} \xB7 ${a}`,""];c.push(` ${o?.summary??r.message}`),r?.link&&c.push(d(` ${r.link}`)),r?.degraded&&(c.push(""),c.push(ne("\u26A0",`This rule is translated approximately: ${r.degraded}. It may match slightly more than the original does.`)));try{let l=Ll({cwd:e}).findings.filter(g=>g.ruleId===s),f=l.filter(g=>!g.baselined);c.push(""),c.push(l.length===0?" Currently: no findings.":` Currently: ${ot(f.length,"finding")}${l.length!==f.length?`, plus ${l.length-f.length} baselined and hidden`:""}.`)}catch{}return c.push(""),o?(c.push(d(" Built-in checks are grounded in your product's own source and cannot be switched off \u2014 they")),c.push(d(" catch defects of fact, not matters of taste."))):(c.push(i==="error"?d(' This one BLOCKS publishing \u2014 your config sets it to "error" deliberately.'):d(" Style rules never block publishing. Fix it when you want to; it will not hold a page back.")),c.push(d(` Silence it everywhere: add "${s}": "off" to styleGuide.rules in .d360-writer/config.json`)),i!=="error"&&c.push(d(" Silence one passage: <!-- vale "+s+" = NO --> \u2026 <!-- vale "+s+" = YES -->"))),c}function dh(e,t){let n=(t??"").trim();if(!n){let T=nh(e).filter(x=>x.name.toLowerCase()!==oo),A=new Set(ih(Dn(e)?.styleGuide).map(x=>x.toLowerCase())),S=x=>x.toLowerCase()===lh?0:1,C=T.sort((x,E)=>S(x.name)-S(E.name)||x.name.localeCompare(E.name)).map(x=>({cmd:`/style-guide use ${x.name.toLowerCase()}`,desc:`${tN(x)} \u2014 ${x.rules.length} rules${A.has(x.name.toLowerCase())?" (active now)":""}`}));return{lines:[],restart:!1,pick:{title:"Which writing rules should these docs follow?",lead:"Pick below. Whichever you choose, every article here is held to it \u2014 nothing stays exempt.",options:[...C,{cmd:"/style-guide use none",desc:"the built-in checks only \u2014 correctness and anti-slop"}]}}}let o=n.toLowerCase()==="none"?[]:n.split(/[,\s]+/).map(T=>T.trim().toLowerCase()).filter(Boolean),r=new Map(nh(e).map(T=>[T.name.toLowerCase(),T])),s=o.filter(T=>!r.has(T));if(s.length>0)return{lines:[ne("\u2717",`No rule pack named ${s.map(T=>`"${T}"`).join(", ")}.`),"",..._b(e)],restart:!1};let i=Dn(e)??{projectId:""},{declinedUpgrade:a,...c}=i.styleGuide??{},l=(i.styleGuide?.packs??[]).map(T=>T.trim().toLowerCase()).filter(Boolean);ah({...i,styleGuide:{...c,packs:o,decidedAt:new Date().toISOString()}},e),EE();let f=[ne("\u2192",`Switching to: ${o.length>0?o.join(", "):"the built-in checks only"}${o.includes(oo)?"":` (+ ${oo}, always on)`}\u2026`)],g,$=[];try{let T=NE(e),A=T?Object.values(T.entries).reduce((x,E)=>x+E.count,0):0;if(T){try{oh(`${jE(e)}.bak`,JSON.stringify(T,null,2),"utf8")}catch{}DE(e)}let S=Ll({cwd:e}),C=new Set(S.findings.map(x=>x.path)).size;if(S.findings.length===0)f.push(ne("\u2713",C===0?"No articles yet \u2014 everything you write from here is held to the full set.":"Your articles are already clean against these rules."));else{f.push(ne("\u26A0","Every article is held to the new rules. Nothing stays exempt."),"",d(` ${ot(S.findings.length,"finding")} across ${ot(C,"article")} ${S.findings.length===1?"is":"are"} now live.`)),A>0&&(f.push(d(` ${ot(A,"finding")} accepted under your previous guide ${A===1?"is":"are"} not carried over.`)),f.push(d(" Your previous record is at .d360-writer/style-baseline.json.bak"))),f.push(""),f.push(ne("\u2713","Nothing blocks publishing \u2014 no style-pack rule can."));let x=Zn(e,["--fix"],S.findings);x.lines.length>0&&f.push("",...x.lines);let E=x.fixed>0?Ll({cwd:e}):S,j=E.findings.length,W=new Set(E.findings.map(Y=>Y.path)).size;j===0?f.push(ne("\u2713","That was all of them \u2014 your articles now match the new guide.")):g={findings:j,articles:W,cmd:"/review --all --fix",...x.fixed>0?{outOf:S.findings.length}:{}},$=[...new Set(E.findings.map(Y=>Y.path))]}IE(e,{packs:o,from:l,articlesWithFindings:$})}catch(T){f.push(ne("\u26A0",`The packs are active, but reading your articles failed: ${T instanceof Error?T.message:String(T)}`)),f.push(d(" Run /lint to see the current state before publishing."))}return f.push(...jb(e,`/style-guide use ${n}`)),f.push(d(" Restarting the agent so it writes to the new rules\u2026")),{lines:f,restart:!0,...g?{editorial:g}:{}}}function sN(e){return[e.title,d(` ${e.lead}`),"",...e.options.map(t=>` ${t.cmd}`.padEnd(38)+d(t.desc))]}function ph(e){let t=e.outOf?`${e.findings} of the ${e.outOf} findings`:ot(e.findings,"finding");return[ne("\u2192",`${t} across ${ot(e.articles,"article")} ${e.findings===1?"needs":"need"} a read, not a swap.`),d(` ${e.cmd} reads each one and rewrites it. Nothing is blocking your publishing in the meantime.`)]}function iN(e,t){let n=(t??"").trim().toLowerCase()==="skip",o=OE(e);if(!o)return[ne("\u2713","No sweep is owed \u2014 your articles have been read against the guide they follow.")];let r=o.packs.length>0?o.packs.join(", "):"the built-in checks";if(n)return LE(e),[ne("\u2713",`Fine \u2014 I won't raise the ${r} sweep again.`),"",d(` ${ot(o.pending,"article")} still ${o.pending===1?"has":"have"} not been read against it.`),d(" /review --all --fix does the sweep whenever you want it.")];let s=o.total-o.pending;return[ne("\u2192",`${o.pending} of your ${ot(o.total,"article")} still ${o.pending===1?"needs":"need"} a read against ${r}.`),"",...s>0?[d(` ${s} read so far.`)]:[],d(" /review --all --fix reads the rest and rewrites them."),d(" /style-guide sweep skip stops me raising it.")]}async function _l(e,t){let{sub:n,value:o}=qr(e),r=s=>{for(let i of s)console.log(i);console.log("")};switch(n){case"list":return r(_b(t.cwd)),{kind:"continue"};case"explain":return r(rN(t.cwd,o)),{kind:"continue"};case"use":{let s=dh(t.cwd,o);return r(s.pick?sN(s.pick):s.lines),s.editorial&&r(ph(s.editorial)),s.restart?{kind:"clear"}:{kind:"continue"}}case"keep":return r(QE(t.cwd)),{kind:"continue"};case"sweep":return r(iN(t.cwd,o)),{kind:"continue"};case"pull":{let s=await JE(t.cwd,o,t.profileName);return r(s.lines),s.restart?{kind:"clear"}:{kind:"continue"}}case"compile":{let s=ZE(t.cwd);return{kind:"forward-to-agent",prompt:s.prompt,display:s.display}}case"learn":{let s=eN(t.cwd);return s.kind==="nothing"?(r(s.lines),{kind:"continue"}):{kind:"forward-to-agent",prompt:s.prompt,display:s.display}}default:return r(oN(t.cwd)),{kind:"continue"}}}oe();import{lintDocs as Fl,loadStyleGuide as Yb,buildReviewPrompt as Kb,buildStructureReviewPrompt as TN,structureReviewDue as AN,structureFingerprint as EN,recordStructureReview as NN,hasCaptureArtifacts as zb,readProjectConfig as bh,DEFAULT_DOCS_DIR as kh,listArticleFiles as Xo,normalizeScope as DN,planPartitions as jN,runPartitioned as Xb,partitionCoverage as IN,resolveModelForOperation as Qb,stampArticles as LN,snapshotArticles as ON,reviewStalePaths as _N,readReviewerNotes as Jb,renderNotesForPrompt as Zb,readDocsPlan as MN,CONTENT_CAP_VERSION as wh}from"document360-engine";import{articlesChangedSince as aN,isUnadoptedArticle as lN,docsRootOf as cN}from"document360-engine";function Ko(e,t,n,o){let r=t.map(l=>l.replace(/\\/g,"/"));if(!n)return{changed:[],earned:r,unadopted:[]};let s=[];try{s=aN(e,n).map(l=>l.replace(/\\/g,"/"))}catch{return{changed:[],earned:r,unadopted:[]}}let i=new Set(s),a=r.filter(l=>!i.has(l)&&lN(e,l,o)),c=new Set(a);return{changed:s.filter(l=>r.includes(l)),earned:r.filter(l=>!c.has(l)),unadopted:a}}function uN(e,t){let n=t.replace(/\\/g,"/");try{let o=cN(e).replace(/\\/g,"/").replace(/\/+$/,"");return o&&n.startsWith(`${o}/`)?n.slice(o.length+1):n}catch{return n}}function Vr(e,t,n){if(t.length===0)return null;let o=t.length===1,r=[];r.push(o?`\u26A0 The editor changed nothing in ${uN(e,t[0])}, so it is not recorded as reviewed.`:`\u26A0 The editor changed nothing in ${t.length} pages, so they are not recorded as reviewed.`),r.push(o?" Nothing here has adopted this page: it came from Document360, it is not in your docs plan, and":" Nothing here has adopted them: they came from Document360, they are not in your docs plan, and"),r.push(o?" nothing records what it was written from. There was nothing for an editor to check it against.":" nothing records what they were written from. There was nothing for an editor to check them against.");for(let i of t)r.push(`/untrack ${i}`);r.push(o?" That disowns it \u2014 the page, its history and its comments stay on Document360, readers see no":" That disowns one \u2014 the page, its history and its comments stay on Document360, readers see no"),r.push(" change, and the markdown is kept. Nothing is deleted.");let s=n.lead&&o?{text:r.join(`
435
+ `),cmd:`/untrack ${t[0]}`}:null;return{lines:r,cta:s}}function ki(e){return e===0?"The editor found nothing to change":"Editor applied its fixes"}import{listArticleFiles as Mb,lintDocs as dN,planFindingPartitions as pN,planPartitions as hN,readDocsPlan as fN,readProjectConfig as mN,runRate as fh,loadCoverage as gN,coverageGap as yN,resolveActiveProfile as wN,DEFAULT_DOCS_DIR as bN}from"document360-engine";function mh(e){switch(e.cmd){case"/review":return{concurrency:ro,maxPerPartition:yh,minutesPerBatch:5};case"/write":return{concurrency:3,minutesPerBatch:4};case"/lint":return{concurrency:3,minutesPerBatch:2};default:return{concurrency:3,minutesPerBatch:2}}}function kN(e,t){let n=dN({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:pN(o).length}}var $N=new Set(["/push","/publish"]);function Fb(e,t){if(t.cmd==="/lint"){let r=jn(()=>kN(e,t));return r?{lead:r.lead,billable:r.articles,batches:r.batches}:null}if(t.cmd==="/catch-up"){let r=jn(()=>Zt(e));if(!r)return null;let s=r.hints+r.requests+r.answers+r.directives;if(s===0)return null;let i=jn(()=>Hr(r));return i?{lead:i,billable:0,batches:null}:{lead:`${s} queued item${s===1?"":"s"}`,billable:0,batches:null}}if(t.cmd==="/reuse"){if(t.sub!=="audit")return null;let r=jn(()=>Mb(e,t.scope))?.length??0;return r<4?null:{lead:`${r} article${r===1?"":"s"} read \xB7 one editorial turn`,billable:0,batches:null}}if(t.cmd==="/pull"){let r=jn(()=>yN(gN(e,wN(e).name)))??0;return r<4?null:{lead:`${r} article${r===1?"":"s"} to import`,billable:0,batches:null}}if($N.has(t.cmd)){let r=jn(()=>Mb(e,t.scope))?.length??0;return r<4?null:{lead:`${r} article${r===1?"":"s"}`,billable:0,batches:null}}let n=vN(e,t);if(!n||n.length<4)return null;let o=mh(t);return{lead:`${n.length} article${n.length===1?"":"s"}`,billable:n.length,batches:hN(n,o.maxPerPartition?{maxPerPartition:o.maxPerPartition}:void 0).length}}function vN(e,t){try{if(t.cmd==="/write"){let n=(mN(e)?.docsDir??bN).replace(/\/+$/,""),o=fN(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:Kn(e,n,r)}return t.cmd==="/review"?zo(e,[...t.flags],t.scope):null}catch{return null}}function Ub(e,t){let n=en(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 en(e,t){let n=ln(t);if(!n||!Ar(n))return null;let o=Fb(e,n);if(!o)return null;let r=jn(()=>fh(e,n.cmd));if(o.batches===null){let l=r?.minutesPerWave!==void 0?` \xB7 ~${hh(r.minutesPerWave)}`:"";return`${o.lead}${l}`}let s=mh(n),a=Math.ceil(o.batches/s.concurrency)*(r?.minutesPerWave??s.minutesPerBatch),c=r?.usdPerArticle!==void 0&&o.billable>0?` \xB7 ~${Hb(o.billable*r.usdPerArticle)}`:"";return`${o.lead} \xB7 ${o.batches} batch${o.batches===1?"":"es"} \xB7 ~${hh(a)}${c}`}function Wb(e,t){let n=ln(t);if(!n||!Ar(n))return null;let o=jn(()=>fh(e,n.cmd));if(o?.usdPerArticle===void 0)return null;let r=Fb(e,n);return!r||r.billable===0?null:r.billable*o.usdPerArticle*gh}var Bb=.7,gh=1.4;function hh(e){let t=Math.max(1,Math.round(e*Bb)),n=Math.max(t,Math.round(e*gh));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 Hb(e){let t=e*Bb,n=e*gh;return n>=10?`$${Math.round(t)}\u2013${Math.round(n)}`:`$${t.toFixed(2)}\u2013${n.toFixed(2)}`}function jn(e){try{return e()}catch{return null}}function Ml(e,t,n,o){if(n<4||o<1)return null;let r=mh({cmd:t,scope:void 0,flags:new Set,args:[]}),s=Math.ceil(o/r.concurrency),i=jn(()=>fh(e,t)),a=s*(i?.minutesPerWave??r.minutesPerBatch),c=i?.usdPerArticle!==void 0?` \xB7 ~${Hb(n*i.usdPerArticle)}`:"";return`~${hh(a)}${c}`}import{loadProfileMap as FN,resolveActiveProfile as UN}from"document360-engine";import{renderGapsForPrompt as ek,readReaderContract as $h,renderCorpusTermsForPrompt as tk,scanTerminology as nk,renderReuseForPrompt as ok,scanReuse as rk}from"document360-engine";import{recordRunSample as WN}from"document360-engine";oe();import{readProjectConfig as xN,loadProfileMap as RN,resolveActiveProfile as SN,desiredCategoryOrder as CN,desiredArticleOrder as PN}from"document360-engine";function Gb(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}var qb=e=>e.replace(/\\/g,"/").split("/").pop()??e;function Yr(e,t){try{if(!xN(e))return[];let n=SN(e,t),o=RN(e,n.name);if(!o)return[];let r=new Map;for(let g of PN(o)){let $=r.get(g.categoryPath);$?$.push(g):r.set(g.categoryPath,[g])}let s=CN(o),i=Math.min(...s.map(g=>g.path.split("/").length),Number.MAX_SAFE_INTEGER),a=new Map;for(let g of s){let $=g.path.split("/").slice(0,-1).join("/"),T=a.get($);T?T.push(g):a.set($,[g])}let c=[],l=(g,$)=>{for(let T of(a.get(g)??[]).sort((A,S)=>A.order-S.order)){let A=" ".repeat($);c.push(`${A}${Gb(qb(T.path))}`);for(let S of(r.get(T.path)??[]).sort((C,x)=>C.order-x.order))c.push(`${A} ${Gb(qb(S.path))}`);l(T.path,$+1)}},f=s.find(g=>g.path.split("/").length===i);return l(f?f.path.split("/").slice(0,-1).join("/"):"",0),c}catch{return[]}}async function Vb(e,t){let n=Yr(t.cwd,t.profileName);if(n.length===0)return console.log(d("No documentation structure yet \u2014 run /init and author some articles first.")),{kind:"continue"};console.log(ee("Documentation order (categories \u2192 articles):"));for(let o of n)console.log(o);return console.log(""),{kind:"continue"}}function vh(e,t){return Hs(e,Xo(e,t))}function xh(e,t){return _N(e,Xo(e,t),wh)}function Kr(e){return e.includes("--blocked")||e.includes("--stale")}function zo(e,t,n){return t.includes("--blocked")?vh(e,n):t.includes("--stale")?xh(e,n):Xo(e,n)}function Rh(e,t,n){let o;try{o=MN(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}/`,""),c=r.get(a);c&&s.push({path:i,type:c.type,...c.purpose?{purpose:c.purpose}:{}})}return s}function sk(e,t){let n=bh(e);if(!n)return null;let o=(n.docsDir??kh).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),s=Kr(t),i=t.find(C=>!C.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),a=Fl({cwd:e}),c=i?DN(o,i):"",l=c?a.filter(C=>C.path===`${o}/${c}`||C.path.startsWith(`${o}/${c}/`)):a,f=s?zo(e,t,i):void 0,g=f?l.filter(C=>f.includes(C.path)):l,$=i||s?"":Yr(e).join(`
436
+ `),T=zb(e,n),A=Kb({docsRoot:o,scope:i,styleGuide:Yb(e),deterministicFindings:g,fix:r,structure:$||void 0,screenshots:T,...f?{paths:f}:{},reviewerNotes:Zb(Jb(e),f??Xo(e,i)),openGaps:ek(e,f??Xo(e,i)),readerContract:$h(e),corpusTerms:tk(nk(e)),corpusReuse:ok(rk(e)),planRows:Rh(e,o,f??Xo(e,i))}),S=t.includes("--blocked")?" --blocked":t.includes("--stale")?" --stale":"";return{prompt:A,display:`/review${i?` ${i}`:""}${S}${r?" --fix":""}`}}var BN=e=>"ruleId"in e,ro=3,yh=3;function Sh(e,t){let n=sk(e,t);if(!n)return null;let o=t.find(C=>!C.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),r=zo(e,t,o),s=jN(r,{maxPerPartition:yh});if(s.length<=1)return{kind:"single",...n};let i=bh(e),a=(i?.docsDir??kh).replace(/\\/g,"/").replace(/\/+$/,""),c=t.includes("--fix"),l=Yb(e),f=Fl({cwd:e}),g=Jb(e),$=zb(e,i),T=$h(e),A=tk(nk(e)),S=ok(rk(e));return{kind:"partitioned",partitions:s,articles:r.length,wholeKb:!o&&!Kr(t),display:n.display,promptFor:C=>{let x=new Set(C.paths);return Kb({docsRoot:a,styleGuide:l,deterministicFindings:f.filter(E=>x.has(E.path)),fix:c,screenshots:$,paths:C.paths,reviewerNotes:Zb(g,C.paths),openGaps:ek(e,C.paths),readerContract:T,corpusTerms:A,corpusReuse:S,planRows:Rh(e,a,C.paths)})}}}function $i(e,t,n){let o=bh(e);if(!o||t.find(c=>!c.startsWith("--"))||n?.kind==="single"&&!Kr(t))return null;let s=(o.docsDir??kh).replace(/\\/g,"/").replace(/\/+$/,""),i=Yr(e);if(Object.keys(FN(e,UN(e).name)?.categories??{}).length<2)return null;let a=i.join(`
437
+ `);return AN(e,a,wh)?{prompt:TN({docsRoot:s,structure:a,planRows:Rh(e,s,Xo(e)).map(c=>`${c.path} ${c.type}`).join(`
438
+ `),readerContract:$h(e)}),display:"/review \u2014 the shape of your knowledge base",fingerprint:EN(a,wh)}:null}function Ch(e,t){if(!Kr(t))return null;let n=t.find(g=>!g.startsWith("--"));if(zo(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.`,c=`/push${n?` ${n}`:" --all"}`,l=_t(e,{text:`${c} saves ${r?"it":"what has changed"} to Document360 as ${r?"a draft":"drafts"}.`,cmd:c},"",n,"/review"),f=Ye(e,sk(e,t)?.display??"");return{lines:[a,` ${l.text}`],closed:f,cta:l}}async function ik(e,t){let n=Ch(t.cwd,e);if(n){console.log(Q(n.lines[0]));for(let s of n.lines.slice(1))console.log(d(s));for(let s of n.closed)console.log(Q(s));let r=$i(t.cwd,e,null);return r&&(console.log(d("One thing left: no editor has looked at how your docs are organised since it last changed.")),await ak(t,r)),{kind:"continue",ownNext:!0}}if(eo("review",e)){let r=Mr(t.cwd,"review",e,t.profileName);if(r.length>0){for(let s of r)console.log(d(s));return{kind:"continue"}}}let o=Sh(t.cwd,e);return o?o.kind==="single"?{kind:"forward-to-agent",prompt:o.prompt,display:o.display}:await HN(t,o,e.includes("--fix"),e.find(r=>!r.startsWith("--")),e):(console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"})}async function ak(e,t){console.log(""),console.log(d(`Reviewing ${t.display.replace(/^\/review — /,"")}\u2026`));let n=!1;try{for await(let o of Xb({cwd:e.cwd,partitions:[{label:"the shape of your knowledge base",paths:[]}],promptFor:()=>t.prompt,concurrency:1,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:Qb(e.cwd,"standard").model,scope:"review"}))o.type==="run_done"&&(n=o.results.some(r=>r.ok))}catch{return}n&&NN(e.cwd,t.fingerprint)}async function HN(e,t,n,o,r=[]){let{model:s}=Qb(e.cwd,"standard"),i=$i(e.cwd,r,t),a=Ml(e.cwd,"/review",t.articles,t.partitions.length);console.log(d(`Reviewing ${t.articles} article${t.articles===1?"":"s"} in ${t.partitions.length} batches (\u2264${ro} editors at once) on ${s}${n?", applying fixes":", report only"}${a?` \xB7 ${a}`:""}\u2026`));let c=Date.now(),l=n?ON(e.cwd):null,f=[],g=0,$=new Ir;$.start();let T={aborted:!1,partitions:0,failed:0,notRun:0,producedNothing:!0};try{for await(let x of Xb({cwd:e.cwd,partitions:t.partitions,promptFor:t.promptFor,concurrency:ro,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:s,scope:"review"}))if(x.type==="partition_status")x.status==="running"?console.log(d(` \u25B8 ${x.label} \u2014 reviewing\u2026`)):x.status==="done"?console.log(Q(` \u2713 ${x.label}`)):console.log(L(` \u2717 ${x.label}`));else if(x.type==="run_done"){let E=IN(t.partitions,x.results);T={aborted:!!x.aborted,partitions:t.partitions.length,failed:E.failed.length,notRun:E.notRun.length,...x.blocked?{blocked:x.blocked}:{},...x.allEmpty?{allEmpty:!0}:{},...x.bailedEmpty?{bailedEmpty:!0}:{}},console.log(""),console.log(`${x.results.length-E.failed.length}/${t.partitions.length} batches reviewed.`),E.failed.length&&console.log(q(`\u26A0 ${E.failed.length} not reviewed: ${E.failed.map(W=>W.label).join(", ")}`)),E.notRun.length&&console.log(q(`\u26A0 ${E.notRun.length} batch${E.notRun.length===1?"":"es"} never started \u2014 their articles are untouched.`)),x.blocked&&console.log(q(`\u26A0 ${x.blocked}`)),x.allEmpty&&console.log(q("\u26A0 No editor produced any work this run \u2014 nothing was reviewed or changed."));for(let W of Ph(t,!!i))console.log(d(W));if(n&&!x.allEmpty&&!x.blocked){let W=Ko(e.cwd,E.covered,l,e.profileName);if(f.push(...W.unadopted),g=W.changed.length,W.earned.length>0)try{LN(e.cwd,W.earned,mt("review"))}catch{}}let j=$.stop();if(console.log(d(cn(Ft(c,x.results,x.totalCostUsd,Date.now(),j.activeSeconds)))),!x.allEmpty&&!x.blocked){let W=x.results.filter(Y=>Y.ok).length;WN(e.cwd,"review",{articles:E.covered.length,waves:Math.ceil(W/Math.max(1,ro)),seconds:j.activeSeconds,costUsd:x.totalCostUsd})}}}catch(x){return $.stop(),console.log(L(`Review failed: ${x.message}`)),{kind:"continue"}}if($.stop(),i&&!T.aborted&&await ak(e,i),n&&Qt(T))for(let x of Ye(e.cwd,t.display))console.log(Q(x));if(!n)return{kind:"continue"};let A=Zn(e.cwd,["--fix"],Fl({cwd:e.cwd,scope:o}));for(let x of A.lines)console.log(x);let C=Fl({cwd:e.cwd,scope:o}).filter(x=>!x.baselined).filter(x=>BN(x)&&x.severity==="error");if(console.log(""),C.length>0){let x=Se("/lint","--blocked --fix",o);console.log(d(`${ki(g)}, but ${C.length} style error${C.length===1?"":"s"} remain \u2014 ${x} 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{let x=Vr(e.cwd,f,{lead:g===0});if(x)for(let E of x.lines)console.log(q(E));if(x?.cta)return{kind:"continue",ownNext:!0};console.log(d(_t(e.cwd,{text:`\u2713 ${g===0?"Reviewed \u2014 nothing needed changing":"Reviewed and fixed"}. /push --all saves the articles to Document360 as drafts.`,cmd:"/push --all"},"",o).text))}return{kind:"continue",ownNext:!0}}function Ph(e,t=!1){return e.partitions.length<2?[]:t?["Each editor saw one slice of the docs, so no one of them judged the set as a whole.","They did all see how the whole set spells its terms; two different WORDS for one thing still need a person."]:[`Each editor saw one slice of the docs, so reading order ${e.wholeKb?"ACROSS categories":"ACROSS the rest of the knowledge base"} was not judged.`,"They did all see how the whole set spells its terms; two different WORDS for one thing still need a person.","/structure shows the reading order if you want to check it yourself."]}oe();import{readProjectConfig as GN}from"document360-engine";function Th(e,t){if(!GN(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(`
439
+ `),display:`/reorder${n?` ${n}`:""}`}}async function lk(e,t){if(eo("reorder",e)){let o=Mr(t.cwd,"reorder",e,t.profileName);if(o.length>0){for(let r of o)console.log(d(r));return{kind:"continue"}}}let n=Th(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"})}oe();import{readProjectConfig as qN}from"document360-engine";function Ah(e,t){if(!qN(e))return null;let n=t.filter(r=>!r.startsWith("--")).join(" ").trim();return{prompt:[n?`Restructure the docs: ${n}`:"Review how the docs are organised and tell me what should change.","","Follow the manage-structure skill.",n?"Apply the change with the right tool: d360_move_articles to refile, split or merge; d360_rename_category to rename; d360_nest_category to put a category inside another or lift one back out; d360_reorder_articles or d360_reorder_categories if only the order is wrong.":["Read the current structure first, then judge it as a senior technical writer would: is every article","filed where a reader would look for it, has any category grown past one topic and want splitting, are","two categories really the same one, does any name still describe what is in it, and does any nesting","earn the click it costs the reader?","","Report what you would change and why, as a short numbered list, and STOP THERE. Do not apply anything","yet: reshaping a knowledge base is my call, not yours. If nothing needs changing, say so plainly."].join(`
440
440
  `),"","Do not rename files or folders or edit the map by hand; the tools handle the whole refactor.","Moving an article does not change its public URL, so say so rather than warning me about broken links.","A category a merge leaves empty is handled for me: it goes locally and is hidden from readers on the","next push, never deleted. Say that in those words rather than telling me to tidy it up myself.","When you have applied something, remind me it reaches Document360 on the next /push."].filter(Boolean).join(`
441
- `),display:`/restructure${n?` ${n}`:""}`}}async function tk(e,t){let n=xh(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"})}oe();import{computeReadiness as EN,readinessPlaceholderPlaces as NN}from"document360-engine";import ze from"picocolors";var Xr=5;function Oe(e,t=58){let n=e.replace(/\\/g,"/");return n.length<=t?n:`\u2026${n.slice(n.length-t+1)}`}function DN(e){let t=[],n=e.verdict;if(e.conflicts.length>0&&t.push({glyph:"\u2717",paint:ze.red,title:`Changed here and on Document360 (${e.conflicts.length})`,fix:"/resolve",items:e.conflicts.map(o=>Oe(o))}),n.unreviewed.length>0&&t.push({glyph:"\u2717",paint:ze.red,title:`Never read by an editor (${n.unreviewed.length})`,fix:"/review --blocked --fix",items:n.unreviewed.map(o=>Oe(o))}),n.styleErrors.length>0){let o=n.styleErrors.reduce((r,s)=>r+s.errors,0);t.push({glyph:"\u2717",paint:ze.red,title:`Break house style rules your config makes blocking (${o} error${o===1?"":"s"})`,fix:"/lint --blocked --fix",items:n.styleErrors.map(r=>`${Oe(r.path)} (${r.errors})`)})}if(n.placeholders.length>0){let o=NN(e);t.push({glyph:"\u2717",paint:ze.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=>`${Oe(r.path)} (${r.missingShots.length+r.orphans})`)})}return t}function jN(e){let t=e.verdict,n=[];return e.conflicts.length===0&&n.push(`${z("\u2713",ze.green)}Nothing is in conflict with Document360`),t.unreviewed.length===0&&n.push(`${z("\u2713",ze.green)}Every article has been read by an editor`),t.styleErrors.length===0&&n.push(`${z("\u2713",ze.green)}House style: nothing blocking`),t.placeholders.length===0&&n.push(`${z("\u2713",ze.green)}No placeholder text would reach a reader`),n}function IN(e,t){if(e.rows.length===0)return[];let n=r=>r?ze.green("\u2713"):ze.red("\u2717"),o=e.rows.map((r,s)=>[String(s+1),Oe(r.path,46),n(r.reviewed),r.styleErrors===0?ze.green("\u2713"):ze.red(`\u2717 ${r.styleErrors}`),r.placeholders===0?ze.green("\u2713"):ze.red(`\u2717 ${r.placeholders}`),r.conflict?ze.red("conflict"):r.draftPending?ze.yellow("draft"):r.localAhead?d("not saved"):d("\u2014")]);return Ys(["#","Article","Read","Style","Pictures","Document360"],o,t).split(`
442
- `)}function Rh(e,t={}){let n=EN(e,t.profileName),o=[];if(n.rows.length===0)return o.push(ee("Publish readiness")),o.push(""),o.push(n.tracked===0?`${z("\u25CB",ze.gray)}No articles are tracked yet. /write authors them, /push saves them to Document360.`:`${z("\u2713",ze.green)}All ${n.tracked} articles are live and unchanged \u2014 nothing is waiting on you.`),n.orphans.length>0&&o.push(...ok(n)),n.unadopted.length>0&&(o.push(""),o.push(...nk(n))),o.push(""),o.push(d(" 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(ee("Publish readiness")+d(` ${r} article${r===1?"":"s"} not yet settled with readers \xB7 ${s===0?"nothing blocked":`${s} blocked`}`)),o.push(""),t.all&&(o.push(...IN(n,t.width??100)),o.push(""));for(let l of DN(n)){o.push(` ${z(l.glyph,l.paint)}${l.title}${l.fix?d(` ${l.fix}`):""}`);for(let f of l.items.slice(0,Xr))o.push(d(` ${f}`));l.items.length>Xr&&o.push(d(` \u2026and ${l.items.length-Xr} more`)),o.push("")}let i=nk(n);i.length>0&&(o.push(...i),o.push(""));let a=jN(n);if(a.length>0){for(let l of a)o.push(` ${l}`);o.push("")}let c=n.rows.filter(l=>l.localAhead).length;return c>0&&o.push(d(` ${c} changed here \u2014 /push saves ${c===1?"it":"them"} to Document360 as ${c===1?"a draft":"drafts"}. Readers see nothing until then.`)),n.draftPending.length>0&&o.push(d(` ${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(...ok(n)),!t.all&&n.rows.length>0&&o.push(d(" /status --all shows every article, gate by gate.")),o.push(""),o.push(d(" Free \u2014 /status reads your local files and the last sync. It calls nothing.")),o}function nk(e){let t=e.unadopted.length;if(t===0)return[];let n=[` ${z("\u25CB",ze.gray)}${t===1?"One page here came from Document360 and nothing has adopted it":`${t} pages here came from Document360 and nothing has adopted them`}`,d(` Not in your docs plan, not written by d360-writer, and nothing records what ${t===1?"it says":"they say"}.`),d(` So no editor can check ${t===1?"it":"them"}: a review pass over ${t===1?"it":"them"} comes back having changed nothing.`)];for(let o of e.unadopted.slice(0,Xr))n.push(` /untrack ${o.path}`);return t>Xr&&n.push(d(` \u2026and ${t-Xr} more`)),n.push(d(" Disowning one leaves Document360 untouched \u2014 the page, its history and its comments all stay.")),n}function ok(e){let t=e.orphans.length;return[d(` ${t} article${t===1?"":"s"} on Document360 ${t===1?"is":"are"} not in your docs folder (${Oe(e.orphans[0].path,40)}${t>1?`, +${t-1} more`:""}) \u2014 /doctor lists ${t===1?"it":"them"}.`)]}async function rk(e,t){let n=e.some(o=>o==="--all"||o==="--full");for(let o of Rh(t.cwd,{profileName:t.profileName,all:n}))console.log(o);return{kind:"continue",ownNext:!0}}oe();import{computeReadiness as LN,retireArticle as ON,retiredPaths as _N,normalizeScope as MN}from"document360-engine";import{select as FN}from"@inquirer/prompts";function Sh(e,t){let n=LN(e,t),o=_N(e,t),r=[ee("Take an article off your readers"),""];if(n.orphans.length>0){r.push(` ${z("\u25CB",d)}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(d(` ${Oe(s.path)}`));n.orphans.length>8&&r.push(d(` \u2026and ${n.orphans.length-8} more`)),r.push("")}if(o.length>0){r.push(` ${z("\u2713",d)}Already retired \u2014 readers do not see ${o.length===1?"it":"these"}:`);for(let s of o.slice(0,5))r.push(d(` ${Oe(s)}`));o.length>5&&r.push(d(` \u2026and ${o.length-5} more`)),r.push("")}return n.orphans.length===0&&o.length===0&&(r.push(d(" Nothing obvious to retire \u2014 every tracked article is still in your docs folder.")),r.push("")),r.push(d(" /retire <path> takes one off your readers. Any tracked article can be named, not just these.")),r.push(d(" Nothing is deleted: the article, its history and every reviewer comment stay on Document360.")),r.push(d(" /push puts one back \u2014 reviving is a publish like any other, with the same review.")),r}async function sk(e,t){let n=t.cwd,o=e.find(a=>!a.startsWith("-"));if(!o){for(let a of Sh(n,t.profileName))console.log(a);return{kind:"continue",ownNext:!0}}let r=MN(n,o)||o;if(!(e.includes("--yes")||e.includes("-y"))&&(console.log(""),console.log(K(`This takes "${Oe(r)}" off your readers on Document360.`)),console.log(d(" The article, its history and every reviewer comment stay \u2014 nothing is deleted.")),console.log(d(" /push puts it back later if you change your mind.")),console.log(""),await FN({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(d("Nothing changed.")),{kind:"continue",ownNext:!0};let i=await ON({cwd:n,path:r,profileName:t.profileName,now:new Date().toISOString()});return i.ok?(console.log(i.alreadyHidden?`${z("\u2713")}"${Oe(r)}" was already invisible to readers. Recorded as retired, so nothing will offer to publish it again.`:`${z("\u2713")}"${Oe(r)}" is no longer visible to your readers.`),console.log(d(" It is still on Document360 with its history and comments intact. /push puts it back.")),{kind:"continue",ownNext:!0}):(console.log(L(`${z("\u2717")}Could not retire "${Oe(r)}" \u2014 ${i.error.message}`)),{kind:"continue",ownNext:!0})}oe();import{declineImport as UN,loadDeclinedImports as WN,undoDecline as BN,normalizeScope as HN,resolveActiveProfile as GN}from"document360-engine";import{select as qN}from"@inquirer/prompts";function Ch(e,t){let n={};try{n=WN(e,GN(e,t).name)}catch{}let o=Object.keys(n),r=[ee("Pages on Document360 that are not part of these docs"),""];if(o.length===0)r.push(d(" Nothing is declined. Every article on Document360 in one of your categories is")),r.push(d(" imported into your docs folder when you run /catch-up or /pull."));else{for(let s of o.slice(0,10)){let i=n[s];r.push(` ${z("\u25CB",d)}${i.title??i.path??s}`),i.path&&r.push(d(` was ${Oe(i.path)}`)),i.keptAt&&r.push(d(` kept at ${i.keptAt}`))}o.length>10&&r.push(d(` \u2026and ${o.length-10} more`))}return r.push(""),r.push(d(" /untrack <path> disowns an imported page \u2014 nothing on Document360 changes.")),r.push(d(" /untrack --undo <path> puts it back and lets the next /catch-up import it again.")),r}async function ik(e,t){let n=t.cwd,o=e.find(l=>!l.startsWith("-")),r=e.includes("--list")||e.includes("-l"),s=e.includes("--undo");if(r||!o&&!s){for(let l of Ch(n,t.profileName))console.log(l);return{kind:"continue",ownNext:!0}}if(!o)return console.log(L(`${z("\u2717")}Name what to put back: /untrack --undo <path>`)),{kind:"continue",ownNext:!0};let i=HN(n,o)||o;if(s){let l=BN(n,t.profileName,i);return l.ok?(console.log(l.restoredTo?`${z("\u2713")}Put "${Oe(l.restoredTo)}" back in your docs folder.`:`${z("\u2713")}No longer declined. /catch-up imports it again on the next run.`),{kind:"continue",ownNext:!0}):(console.log(L(`${z("\u2717")}${l.error.message}`)),{kind:"continue",ownNext:!0})}if(!(e.includes("--yes")||e.includes("-y"))&&(console.log(""),console.log(K(`This stops tracking "${Oe(i)}" as one of your docs.`)),console.log(d(" Nothing on Document360 changes \u2014 the page, its history and its comments all stay,")),console.log(d(" and your readers see no difference.")),console.log(d(" The markdown moves to .d360-writer/declined/, so nothing is deleted.")),console.log(d(" /untrack --undo puts it back if you change your mind.")),console.log(""),await qN({message:"Stop tracking it?",choices:[{name:"No \u2014 leave it as it is",value:"no"},{name:"Yes \u2014 it is not one of my docs",value:"yes"}]})!=="yes"))return console.log(d("Nothing changed.")),{kind:"continue",ownNext:!0};let c=UN({cwd:n,path:i,profileName:t.profileName,now:new Date().toISOString()});return c.ok?(console.log(`${z("\u2713")}"${c.title??Oe(c.path)}" is no longer one of your docs.`),c.keptAt&&console.log(d(` The markdown is kept at ${c.keptAt} \u2014 nothing was deleted.`)),console.log(d(" It is untouched on Document360. /catch-up will not import it again.")),{kind:"continue",ownNext:!0}):(console.log(L(`${z("\u2717")}Could not untrack "${Oe(i)}" \u2014 ${c.error.message}`)),{kind:"continue",ownNext:!0})}oe();import{scanTerminology as ak,approvalBlockedReason as lk,readProjectConfig as VN,writeProjectConfig as KN,termKey as Ph,HEAD_NOUN_CAP as YN}from"document360-engine";import en from"picocolors";var zN=3,XN=e=>e.uses.map(t=>`${en.bold(t.form)} ${d(`${t.files.length} article${t.files.length===1?"":"s"}`)}`).join(d(" \xB7 "));function Th(e,t={}){let n=ak(e,t.scope?{scope:t.scope}:{}),o=[];if(n.scanned===0)return[ee("Terminology"),"",`${z("\u25CB",d)}No articles to read yet.`,""];let r=n.variance.length+n.headings.length;if(o.push(ee("Terminology")+d(` ${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(` ${z("\u2717",en.red)}The same term, spelled more than one way`);for(let s of n.variance){o.push(` ${XN(s)}`);let i=s.uses[s.uses.length-1],a=i.files.slice(0,zN);o.push(d(` "${i.form}" is in ${a.map(l=>Oe(l,40)).join(", ")}${i.files.length>a.length?`, +${i.files.length-a.length} more`:""}`));let c=lk(s);c?o.push(d(` ${c}`)):o.push(d(` /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,YN);o.push(` ${z("\u25CB",d)}Possibly the same thing under a short name \u2014 ${en.italic("your call")}`);for(let i of s)o.push(d(` ${i.uses.map(a=>a.form).join(" \xB7 ")}`));n.headNouns.length>s.length&&o.push(d(` \u2026and ${n.headNouns.length-s.length} more \u2014 /terms --all lists them`)),o.push(d(' A shared word is not proof of a shared meaning: "billing history" and "history" are')),o.push(d(" different things. Nothing is flagged as wrong here.")),o.push("")}if(n.headings.length>0){o.push(` ${z("\u26A0",en.yellow)}Titles out of step with the rest of their kind`);for(let s of n.headings)o.push(` ${en.bold(s.title)} ${d(`\u2014 ${Oe(s.path,40)}`)}`),o.push(d(` the other ${s.peers} ${s.type} article${s.peers===1?"":"s"} look like "${s.example}"; this one starts ${QN(s.shape)}`));o.push("")}return r===0&&n.headNouns.length===0&&(o.push(` ${z("\u2713",en.green)}Every term is spelled one way, and every title matches its kind.`),o.push("")),o.push(d(' This compares spellings, not meanings: two different words for one thing (say "nav" and')),o.push(d(' "rail") look unrelated to it. Add the pair to your approved terms and every run enforces it.')),o.push(d(" Free \u2014 this read your articles and called nothing.")),o}function QN(e){return e==="gerund"?"with an -ing word":e==="how-to"?'with "How to"':"differently"}function Ah(e,t,n){let o=n??ak(e),r=Ph(t),s=o.variance.find(g=>g.uses.some(k=>Ph(k.form)===r));if(!s)return{wrote:!1,lines:[`${z("\u2717",en.red)}"${t}" is not one of the terms with competing spellings. /terms lists them.`]};let i=lk(s);if(i)return{wrote:!1,lines:[`${z("\u2717",en.red)}That one cannot be recorded: ${i}.`,d(` The spellings in play are ${s.uses.map(g=>`"${g.form}"`).join(" and ")}.`)]};let a=s.uses.find(g=>Ph(g.form)===r).form,c=s.uses.filter(g=>g.form!==a).map(g=>g.form),l=VN(e);if(!l)return{wrote:!1,lines:[`${z("\u2717",en.red)}No project configuration here \u2014 run /init first.`]};let f={...l.terminologyGlossary??{}};for(let g of c)f[g]=a;return KN({...l,terminologyGlossary:f},e),{wrote:!0,lines:[`${z("\u2713",en.green)}"${a}" is now the approved spelling.`,d(` Added to your approved terms: ${c.map(g=>`"${g}" \u2192 "${a}"`).join(", ")}`),d(" Every run enforces it from now on, and /lint --fix corrects the others for free.")]}}async function ck(e,t){let n=e.findIndex(s=>s==="--approve");if(n!==-1){let s=e[n+1];if(!s)return console.log(`${z("\u2717",en.red)}Name the spelling to approve, e.g. /terms --approve "drop-down".`),{kind:"continue",ownNext:!0};for(let i of Ah(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 Th(t.cwd,{...r?{scope:r}:{},all:o}))console.log(s);return{kind:"continue",ownNext:!0}}oe();import{evaluateCorpus as JN,buildRegistry as ZN,lintArticles as eD,scanTerminology as tD,BUILTIN_RULES as nD}from"document360-engine";import dn from"picocolors";var so=3,vt=(e,t)=>`${e} ${t}${e===1?"":"s"}`,pk=e=>`${Oe(e.path)}:${e.line}`,uk=e=>e.split("/").pop()?.split("\\").pop()??e;function dk(e,t,n,o,r,s,i){if(r.length===0)return;e.push(` ${z(t,n)}${o}`);let a=i?r:r.slice(0,so);for(let c of a)e.push(d(` ${pk(c)} ${c.detail}`));r.length>a.length&&e.push(d(` \u2026and ${r.length-a.length} more \u2014 /eval --all`)),e.push(d(` ${s}`)),e.push("")}function Eh(e,t={}){let n=ZN(e),o=new Set([...nD.map(c=>c.id),...n.rules.map(c=>c.id)]),r=JN(e,o,{...t.scope?{scope:t.scope}:{},...t.profile?{profile:t.profile}:{}}),s=t.all===!0,i=[];if(r.articles===0)return[ee("Knowledge-base score"),"",`${z("\u25CB",d)}No articles to read yet.`,""];let a=r.links.absolute.length+r.links.deadAnchors.length+r.links.staleLabels.length+r.shapes.typeTemplates.filter(c=>c.deviations.length>0).length+(r.shapes.synopsisForms.length>1?1:0);if(i.push(ee("Knowledge-base score")+d(` ${vt(r.articles,"article")} read \xB7 ${a===0?"nothing to look at":`${a} to look at`}`)),i.push(""),dk(i,"\u2717",dn.red,"Internal links written as portal URLs",r.links.absolute,"These break the day the site moves. Write them as relative .md links instead.",s),dk(i,"\u2717",dn.red,"Links pointing at headings that do not exist",r.links.deadAnchors,"The heading was renamed after the link was written. Point it at the current heading.",s),r.links.staleLabels.length>0){let c=r.links.staleLabels.reduce((l,f)=>l+f.sites.length,0);i.push(` ${z("\u26A0",dn.yellow)}${vt(r.links.staleLabels.length,"link label")} name an article something it is not called${c>r.links.staleLabels.length?d(`, in ${vt(c,"place")}`):""}`);for(let l of s?r.links.staleLabels:r.links.staleLabels.slice(0,so))if(i.push(d(` "${l.label}" \u2192 the article is titled "${l.title}"${l.sites.length>1?` (${l.sites.length}\xD7)`:""}`)),s)for(let f of l.sites)i.push(d(` ${pk(f)}`));!s&&r.links.staleLabels.length>so&&i.push(d(` \u2026and ${r.links.staleLabels.length-so} more \u2014 /eval --all`)),i.push(d(" A reader clicks expecting one page and lands on another name.")),i.push("")}if(s&&r.links.shortenedLabels.length>0){i.push(` ${z("\u25CB",d)}${vt(r.links.shortenedLabels.length,"link label")} shorten the title they point at`);for(let c of r.links.shortenedLabels.slice(0,10))i.push(d(` "${c.label}" \u2192 "${c.title}"`));i.push(d(" Usually fine. Listed separately because it is a judgment call, not a defect.")),i.push("")}if(r.shapes.synopsisForms.length>1){i.push(` ${z("\u26A0",dn.yellow)}The command summary line appears in ${vt(r.shapes.synopsisForms.length,"shape")}`);for(let c of r.shapes.synopsisForms)i.push(d(` ${String(c.count).padStart(3)} ${c.form.padEnd(14)} ${c.examples.map(uk).join(", ")}`));r.shapes.noSynopsis.length>0&&i.push(d(` ${vt(r.shapes.noSynopsis.length,"article")} carry none at all`)),i.push(d(" Same information, different labels. Pick one and use it everywhere.")),i.push("")}for(let c of r.shapes.typeTemplates)if(c.deviations.length!==0){i.push(` ${z("\u26A0",dn.yellow)}${c.deviations.length} of ${vt(c.articles,`${c.type} article`)} skip a section the rest of them carry`),i.push(d(` Most ${c.type} articles have: ${c.expected.map(l=>`## ${l.heading} (${l.count})`).join(" \xB7 ")}`));for(let l of s?c.deviations:c.deviations.slice(0,so))i.push(d(` ${uk(l.path)} \u2014 missing ${l.missing.map(f=>`## ${f}`).join(", ")}`));!s&&c.deviations.length>so&&i.push(d(` \u2026and ${c.deviations.length-so} more \u2014 /eval --all`)),i.push(d(" A deviation may be deliberate. This counts them; it does not say the template is right.")),i.push("")}try{let c=tD(e,t.scope?{scope:t.scope}:{});if(c.variance.length>0){i.push(` ${z("\u26A0",dn.yellow)}${vt(c.variance.length,"term")} spelled more than one way across the set`);for(let l of c.variance.slice(0,s?99:so))i.push(d(` ${l.uses.map(f=>`"${f.form}" \xD7${f.count}`).join(" \xB7 ")}`));c.headNouns.length>0&&i.push(d(` ${vt(c.headNouns.length,"short name")} may be a longer one abbreviated \u2014 /terms lists them`)),i.push(d(' Settle one and every later run enforces it: /terms --approve "<term>"')),i.push("")}}catch{}try{let l=eD({cwd:e,...t.scope?{scope:t.scope}:{}}).findings.filter(g=>!g.baselined),f=l.filter(g=>g.severity==="error").length;if(i.push(` ${z(f>0?"\u2717":l.length>0?"\u26A0":"\u2713",f>0?dn.red:l.length>0?dn.yellow:dn.green)}`+(l.length===0?"Style rules: nothing reported":`Style rules: ${vt(l.length,"finding")}${f>0?`, ${f} blocking publish`:", none blocking publish"}`)),l.length>0){let g=new Map;for(let k of l)g.set(k.ruleId,(g.get(k.ruleId)??0)+1);for(let[k,T]of[...g.entries()].sort((A,S)=>S[1]-A[1]).slice(0,s?99:5))i.push(d(` ${String(T).padStart(4)} ${k}`));i.push(d(" Fix what can be fixed mechanically: /lint --fix"))}i.push("")}catch{}if(r.debt&&r.debt.total>0){let c=r.debt.liveRules.reduce((g,k)=>g+k.count,0),l=r.debt.inertRules.reduce((g,k)=>g+k.count,0),f=r.debt.createdAt.slice(0,10);if(c>0){i.push(` ${z("\u2139",d)}${vt(c,"style finding")} accepted as exempt on ${f}, from rules that are still on`);for(let g of r.debt.liveRules.slice(0,s?99:4))i.push(d(` ${String(g.count).padStart(4)} ${g.rule}`));i.push(d(" Nothing reports these, so the articles read as compliant. They are exempt, not compliant.")),i.push(d(" Work them down with /review --all --fix, then /lint --all --fix."))}else l>0&&(i.push(` ${z("\u25CB",d)}${vt(l,"finding")} accepted on ${f} under a style guide no longer in use`),i.push(d(" They match no active rule, so they suppress nothing. Only weight in the file.")));i.push("")}return a===0&&(r.debt?.total??0)===0&&(i.push(` ${z("\u2713",dn.green)}Links resolve, one template shape, one name per thing.`),i.push("")),i.push(d(` Free \u2014 this read your ${vt(r.articles,"article")} and called nothing.`)),i}async function hk(e,t){let n=e.includes("--all"),o=e.find(r=>!r.startsWith("--"));for(let r of Eh(t.cwd,{...o?{scope:o}:{},...t.profileName?{profile:t.profileName}:{},all:n}))console.log(r);return{kind:"continue",ownNext:!0}}import{fetchPortalReuse as kD,readReuseCache as $D,writeReuseCache as vD,resolveActiveProfile as jh,resolveProjectId as Ih,createVariable as wk,createSnippet as bk,reuseNameProblem as xD,variableRule as RD,VARIABLE_MAX_CHARS as gk}from"document360-engine";oe();import{scanReuse as fk,scanValueCandidates as mk,buildReuseAuditPrompt as oD,reuseAuditProposalPath as rD,readReuseProposal as sD,readReuseCache as iD,listArticleFiles as aD,normalizeScope as lD,docsRootOf as cD,variableRule as uD}from"document360-engine";import{rmSync as dD}from"node:fs";import pD from"picocolors";var Il=6,hD=20;function fD(e,t){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}\u2026`:n}function mD(e,t=52){let n=e.replace(/\s+/g," ").trim(),o=[],r="";for(let s of n.split(" "))r===""?r=s:`${r} ${s}`.length<=t?r+=` ${s}`:(o.push(r),r=s);return r!==""&&o.push(r),o}function Ll(e,t,n,o){let r=[ee("Content reuse audit"),""];return r.push(`${e} article${e===1?"":"s"} read${d(" \xB7 free to look")}`,""),r.push(` ${String(n).padStart(3)} value${n===1?"":"s"} written out by hand in more than one article`),r.push(` ${String(t).padStart(3)} block${t===1?"":"s"} written more than once, in different words`),o>0&&r.push(d(` ${o} more families were left out of this pass \u2014 the longest ones are shown first.`)),r}function Ol(e,t){let n=cD(e),o=t.filter(k=>k!=="audit"&&!k.startsWith("--")).find(k=>k!==void 0),r=o?lD(n,o.replace(/\\/g,"/").replace(/\/+$/,"")):void 0,s=aD(e,r).length;if(s===0)return{lines:[ne("\u25CB",r?`No articles under ${r} to audit.`:"No articles to audit yet."),d(" Reuse is about text that repeats, so there has to be some text first.")]};let i=fk(e,{...r?{scope:r}:{},groups:!0}),a=mk(e,r?{scope:r}:void 0),c=i.groups??[],l=a.candidates;if(c.length===0&&l.length===0)return{lines:[ne("\u2713",`Nothing repeats across ${s} article${s===1?"":"s"} \u2014 there is nothing to keep in one place.`),d(" That is a good answer, not an empty one. Run this again after a few more articles.")]};let f=iD(e),g=rD(e);try{dD(g,{force:!0})}catch{}return{prompt:oD({cwd:e,families:c,values:l,snippets:f?.snippets??[],variables:f?.variables??[],terms:f?.terms??[],proposalPath:g,articles:s}),display:r?`/reuse audit ${r}`:"/reuse audit",articles:s,families:c.length,values:l.length}}function gD(e,t){let n=[],o=` ${String(t).padStart(2)} ${e.kind.padEnd(9)}${pD.bold(e.name.padEnd(hD))}`,r=e.kind==="variable"?[`"${fD(e.value,52)}"`]:mD(`"${e.value}"`);n.push(`${o}${r[0]??""}`);for(let a of r.slice(1))n.push(`${" ".repeat(o.length-10)}${a}`);let s=e.uses>0?`${e.uses} use${e.uses===1?"":"s"} across ${e.files} article${e.files===1?"":"s"}`:"",i=e.why?s?` \u2014 ${e.why}`:e.why:"";return(s||i)&&n.push(d(` ${s}${i}`)),n}function yD(e,t,n){let o=[],r=e.proposals.length;if(o.push(r===0?ne("\u2713",`An editor read ${t} famil${t===1?"y":"ies"} and ${n} value${n===1?"":"s"}. None of it has to stay identical everywhere.`):ne("\u2713",`An editor read ${t} famil${t===1?"y":"ies"} and ${n} value${n===1?"":"s"}. ${r} ${r===1?"is":"are"} worth keeping in one place.`),""),e.proposals.forEach((s,i)=>{o.push(...gD(s,i+1),"")}),e.rejected.length>0){o.push(" Not proposed, and why:");for(let s of e.rejected.slice(0,Il))o.push(d(` \xB7 ${s.what} \u2014 ${s.why}`));e.rejected.length>Il&&o.push(d(` \xB7 \u2026and ${e.rejected.length-Il} more.`)),o.push("")}if(e.dropped.length>0){o.push(ne("\u26A0",`${e.dropped.length} proposal${e.dropped.length===1?"":"s"} could not be used:`));for(let s of e.dropped.slice(0,Il))o.push(d(` \xB7 ${s}`));o.push("")}return o}function wD(){return[d(" Nothing to create. The knowledge base repeats itself, but not in ways that have to stay"),d(" identical everywhere \u2014 which is the answer an editor is for."),""]}function _l(e,t){let n=[],o=t.created.map(a=>a.name);o.length>0&&(n.push(ne("\u2713",`Created ${o.length} on Document360: ${o.join(", ")}.`)),n.push(d(" Your local copy is in step and the agent has been restarted, so it writes with them from now on.")));for(let a of t.failed)n.push(ne("\u2717",`Document360 refused "${a.name}" \u2014 ${a.why}`));t.failed.length>0&&n.push(d(" Nothing else was changed. A name already in use is the usual cause; /reuse lists what exists."));let r=t.created.some(a=>a.kind==="variable"),s=t.created.filter(a=>a.kind==="snippet"),i=null;if(r){let a=uD(e).rule!==null;n.push(""),n.push(a?ne("\u2139","Those values are still typed out by hand across your articles."):ne("\u2139","Those values are created, but nothing checks them yet.")),a&&(n.push(d(" /lint --all --fix swaps every one of them \u2014 it costs no agent time, and nothing else in")),n.push(d(" your articles changes.")),i="/lint --all --fix")}return s.length>0&&(n.push(""),n.push(ne("\u2139",`${s.length===1?"The snippet exists":`The ${s.length} snippets exist`} on Document360, but no article references ${s.length===1?"it":"them"} yet.`)),n.push(d(` Ask me to use ${s.length===1?"it":"them"} in an article, or run /review --all --fix and the editor will replace the`)),n.push(d(" passages it finds. Replacing a passage changes the words a reader sees, so it goes through")),n.push(d(" an editorial read rather than a mechanical swap.")),i||(i="/review --all --fix")),i&&n.push("",i,""),{lines:n,cta:i}}function Ml(e,t){let n=e.indexOf("--create");if(n===-1)return{picks:[],bad:[]};let o=e.slice(n+1).filter(i=>!i.startsWith("--"));if(o.length===1&&(o[0]==="a"||o[0]==="all"))return{picks:Array.from({length:t},(i,a)=>a),bad:[]};let r=[],s=[];for(let i of o){let a=Number(i);if(!Number.isInteger(a)||a<1||a>t){s.push(i);continue}r.includes(a-1)||r.push(a-1)}return{picks:r,bad:s}}function bD(e){if(e===0)return[];let t=Array.from({length:e},(n,o)=>o+1).join(" ");return[d(` Pick what to create. Run the line below for all ${e}, or edit the numbers to take some.`),"",`/reuse audit --create ${t}`,""]}function Fl(){return[ne("\u2717","There is no reuse proposal to create from."),d(" Run /reuse audit first \u2014 it reads your articles and works out what belongs in one place."),"","/reuse audit",""]}function Ul(e,t){let n=sD(e);if(!n)return[ne("\u26A0","The editor did not leave a proposal, so there is nothing to create."),d(" Nothing was changed. This is usually a turn that stopped early \u2014 running it again is safe,"),d(" and the scan it starts from costs nothing."),"",t?`/reuse audit ${t}`:"/reuse audit",""];let o=fk(e,{...t?{scope:t}:{},groups:!0}),r=mk(e,t?{scope:t}:void 0),s=yD(n,(o.groups??[]).length,r.candidates.length);return s.push(...n.proposals.length===0?wD():bD(n.proposals.length)),s}oe();import{readReuseProposal as SD}from"document360-engine";import Qr from"picocolors";var Nh=8,Dn=6,Dh=14,CD=52;function PD(e){if(!e)return"";let t=new Date(e);return Number.isNaN(t.getTime())?"":t.toLocaleDateString(void 0,{day:"numeric",month:"short"})}function yk(e,t=CD){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}\u2026`:n}function Lh(e){let t=$D(e),n=[ee("Reusable content"),""];if(!t||t.terms.length===0&&t.snippets.length===0&&t.variables.length===0)return n.push(`${z("\u25CB",d)}Nothing pulled from Document360 yet.`,"",d(" A variable holds a value like your product name in one place, so changing it changes every"),d(" article at once. A snippet does the same for a whole block, like who to contact when"),d(" something goes wrong. A term is defined once and explained everywhere it first appears."),"","/reuse pull",""),n;let o=PD(t.pulledAt);if(t.terms.length===0)n.push(`${z("\u25CB",d)}No glossary terms in this Document360 project${o?d(` (checked ${o})`):""}.`);else{n.push(`${t.terms.length} term${t.terms.length===1?"":"s"} from Document360${o?d(`, pulled ${o}`):""}.`,"");for(let r of t.terms.slice(0,Nh)){let s=" ".repeat(Math.max(1,Dh-r.term.length));n.push(` ${Qr.bold(r.term)}${s}${d(r.definition||"(no definition)")}`)}t.terms.length>Nh&&n.push(d(` \u2026and ${t.terms.length-Nh} more.`))}if(t.variables.length>0){n.push("",`${t.variables.length} value${t.variables.length===1?"":"s"} kept in one place.`,"");for(let s of t.variables.slice(0,Dn)){let i=" ".repeat(Math.max(1,Dh-s.name.length));n.push(` ${Qr.bold(s.name)}${i}${d(s.value?`"${yk(s.value)}"`:"(no value recorded)")}`)}t.variables.length>Dn&&n.push(d(` \u2026and ${t.variables.length-Dn} more.`));let{skipped:r}=RD(e);if(r.length>0){let s=t.variables.length-r.length;n.push("",d(` ${s} of ${t.variables.length} are checked in your articles. ${r.length===1?"This one is":"These are"} not:`));for(let i of r.slice(0,Dn))n.push(d(` ${i.name} \u2014 ${i.why}.`));r.length>Dn&&n.push(d(` \u2026and ${r.length-Dn} more.`))}}if(t.snippets.length>0){n.push("",`${t.snippets.length} maintained block${t.snippets.length===1?"":"s"}.`,"");for(let r of t.snippets.slice(0,Dn)){let s=" ".repeat(Math.max(1,Dh-r.name.length)),i=r.usedBy>0?d(` (in ${r.usedBy} article${r.usedBy===1?"":"s"})`):"";n.push(` ${Qr.bold(r.name)}${s}${d(r.description||yk(r.value??"")||"(no content recorded)")}${i}`)}t.snippets.length>Dn&&n.push(d(` \u2026and ${t.snippets.length-Dn} more.`))}return n.push("",d(" Terms are checked at first use in every article, a value you typed out by hand is flagged,"),d(" and the writer reuses your blocks by name instead of writing its own version of them."),"","/reuse pull","/lint --all",""),n}async function wi(e,t){let n,o;try{let l=jh(e,t);n={profile:l.name,connection:l.connection,projectId:l.project.projectId,projectName:l.project.projectName},o=await Ih(n,l.project?.projectId)}catch(l){return{lines:[ne("\u2717",`Not signed in to Document360: ${l instanceof Error?l.message:String(l)}`),d(" Run /login first.")],restart:!1}}let r;try{r=await kD(n,o)}catch(l){return{lines:[ne("\u26A0",`Document360 didn't return your reusable content \u2014 ${l instanceof Error?l.message:String(l)}.`),d(" Nothing is blocked. Everything else works exactly as it did; you just do not get the"),d(" first-use check on your terms, or the reuse checks, until this succeeds.")],restart:!1}}let s={pulledAt:new Date().toISOString(),profile:n.profile,projectId:o,terms:r.terms,snippets:r.snippets,variables:r.variables};if(vD(e,s),s.terms.length+s.snippets.length+s.variables.length===0)return{lines:[ne("\u2139","This Document360 project has no terms, snippets or variables yet."),d(" Someone with portal access adds them under Content tools. A good first one is your product"),d(" name as a variable: it is the string most likely to change, and the hardest to change late.")],restart:!1};let a=[`${s.terms.length} term${s.terms.length===1?"":"s"}`,`${s.snippets.length} snippet${s.snippets.length===1?"":"s"}`,`${s.variables.length} variable${s.variables.length===1?"":"s"}`],c=[ne("\u2713",`Pulled ${a.join(" \xB7 ")} from Document360.`)];return r.droppedTerms.length>0&&c.push(d(` ${r.droppedTerms.length} term${r.droppedTerms.length===1?" has":"s have"} no wording recorded in Document360, so ${r.droppedTerms.length===1?"it is":"they are"} not checked:`),d(` ${r.droppedTerms.slice(0,6).join(", ")}${r.droppedTerms.length>6?`, and ${r.droppedTerms.length-6} more`:""}.`)),r.contentlessBlocks.length>0&&c.push(d(` ${r.contentlessBlocks.length} block${r.contentlessBlocks.length===1?"":"s"} came back without content, so ${r.contentlessBlocks.length===1?"it is":"they are"} not matched against your articles:`),d(` ${r.contentlessBlocks.slice(0,6).join(", ")}${r.contentlessBlocks.length>6?`, and ${r.contentlessBlocks.length-6} more`:""}.`)),c.push("",d(" Your terms are now checked at first use in every article, a value you typed out by hand is"),d(" flagged, and the writer reuses your blocks by name instead of writing its own version."),"","/lint --all",""),{lines:c,restart:!0}}async function Oh(e,t,n,o,r){let s=xD(n);if(s)return{lines:[ne("\u2717",`That name will not work: ${s}.`),d(' Try something like "product-name".')],restart:!1};if(o.trim()==="")return{lines:[ne("\u2717","A value is required \u2014 that is the text this will stand for in your articles.")],restart:!1};if(t==="variable"&&o.length>gk)return{lines:[ne("\u2717",`A variable holds at most ${gk} characters and this is ${o.length}.`),d(' Longer text belongs in a snippet: /reuse add snippet <name> "<text>"')],restart:!1};let i,a;try{let c=jh(e);i={profile:c.name,connection:c.connection,projectId:c.project.projectId,projectName:c.project.projectName},a=await Ih(i,c.project?.projectId)}catch(c){return{lines:[ne("\u2717",`Not signed in to Document360: ${c instanceof Error?c.message:String(c)}`),d(" Run /login first.")],restart:!1}}try{let c=t==="variable"?await wk(i,a,{name:n,value:o}):await bk(i,a,{name:n,value:o,...r?{description:r}:{}}),l=await wi(e);return{lines:[ne("\u2713",`Created the ${t} "${c.name}" on Document360.`),d(` Write ${t==="variable"?`:variable[]{name="${c.name}"}`:`::snippet{name="${c.name}"}`} and Document360 puts your text there.`),"",...l.lines],restart:!0}}catch(c){let l=c instanceof Error?c.message:String(c);return{lines:[ne("\u2717",`Document360 refused to create that ${t} \u2014 ${l}`),d(" Nothing was changed. A name already in use is the usual cause; /reuse lists what exists.")],restart:!1}}}function kk(e){let t=e.trim();return t.length>=2&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))?t.slice(1,-1):t}function TD(e){let t=e.indexOf("--desc");if(t===-1)return{rest:e};let n=kk(e.slice(t+1).join(" "));return{rest:e.slice(0,t),...n?{description:n}:{}}}function _h(e){let{rest:t,description:n}=TD(e),o=t.filter(c=>!c.startsWith("--")),[,r,s,...i]=o;if(r!=="variable"&&r!=="snippet")return{error:'Say which one: /reuse add variable <name> "<value>", or /reuse add snippet <name> "<text>".'};if(!s)return{error:`Give it a name: /reuse add ${r} <name> "<value>".`};if(r==="variable"&&n)return{error:"Only a snippet takes --desc; a variable is just its value. Drop the flag, or add it as a snippet."};let a=kk(i.join(" "));return a===""?{error:`Give it a value: /reuse add ${r} ${s} "<the text it stands for>".`}:{kind:r,name:s,value:a,...n?{description:n}:{}}}async function $k(e,t){let n=e.find(o=>!o.startsWith("--"));if(n==="add"){let o=_h(e);if("error"in o)return console.log(`${z("\u2717",Qr.red)}${o.error}`),{kind:"continue",ownNext:!0};let r=await Oh(t.cwd,o.kind,o.name,o.value,o.description);for(let s of r.lines)console.log(s);return r.restart?{kind:"clear"}:{kind:"continue",ownNext:!0}}if(n==="pull"){let o=await wi(t.cwd);for(let r of o.lines)console.log(r);for(let r of Ke(t.cwd,"/reuse pull"))console.log(r);return o.restart?{kind:"clear"}:{kind:"continue",ownNext:!0}}if(n==="audit"){if(e.includes("--create")){let r=SD(t.cwd);if(!r||r.proposals.length===0){for(let f of Fl())console.log(f);return{kind:"continue",ownNext:!0}}let{picks:s,bad:i}=Ml(e,r.proposals.length);for(let f of i)console.log(`${z("\u26A0",Qr.yellow)}There is no proposal ${f} \u2014 the list has ${r.proposals.length}.`);if(s.length===0)return console.log(`${z("\u25CB",d)}Nothing picked, so nothing was created.`),{kind:"continue",ownNext:!0};let{outcome:a,pullLines:c}=await Mh(t.cwd,s.map(f=>r.proposals[f]));for(let f of c)console.log(f);let{lines:l}=_l(t.cwd,a);for(let f of l)console.log(f);for(let f of Ke(t.cwd,"/reuse audit"))console.log(f);return a.created.length>0?{kind:"clear"}:{kind:"continue",ownNext:!0}}let o=Ol(t.cwd,e);if("lines"in o){for(let r of o.lines)console.log(r);for(let r of Ke(t.cwd,"/reuse audit"))console.log(r);return{kind:"continue",ownNext:!0}}for(let r of Ll(o.articles,o.families,o.values,0))console.log(r);return{kind:"forward-to-agent",prompt:o.prompt,display:o.display}}if(n&&n!=="show")return console.log(`${z("\u2717",Qr.red)}I don't know "/reuse ${n}". Use /reuse to see what this project maintains, /reuse pull to refresh it, /reuse audit to find what belongs in one place, or /reuse add variable <name> "<value>".`),{kind:"continue",ownNext:!0};for(let o of Lh(t.cwd))console.log(o);return{kind:"continue",ownNext:!0}}async function Mh(e,t){let n=[],o=[],r,s;try{let a=jh(e);r={profile:a.name,connection:a.connection,projectId:a.project.projectId,projectName:a.project.projectName},s=await Ih(r,a.project?.projectId)}catch(a){return{outcome:{created:[],failed:t.map(c=>({name:c.name,why:`not signed in to Document360: ${a instanceof Error?a.message:String(a)}`}))},pullLines:[d(" Run /login first.")]}}for(let a of t)try{a.kind==="variable"?await wk(r,s,{name:a.name,value:a.value}):await bk(r,s,{name:a.name,value:a.value,...a.description?{description:a.description}:{}}),n.push(a)}catch(c){o.push({name:a.name,why:c instanceof Error?c.message:String(c)})}if(n.length===0)return{outcome:{created:n,failed:o},pullLines:[]};let i=await wi(e);return{outcome:{created:n,failed:o},pullLines:i.restart?[]:i.lines}}oe();import{readProjectConfig as AD,writeProjectConfig as vk,isAppType as ED,playbookSkillName as ND,detectAppType as xk}from"document360-engine";var Rk=["web","cli","service","library"],DD=new Set(["web","cli"]);function Fh(e){return DD.has(e)?`${ND(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function Wl(e,t){let n=t.cwd,o=AD(n);if(!o)return console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let s=o.appType??xk(n);if(s){let i=o.appType?"set in config":"auto-detected";console.log(`${ee("Genre:")} ${s} (${i}) \u2014 ${Fh(s)}`)}else console.log(K("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(d(`Set it: /genre <${Rk.join("|")}> \xB7 revert to auto-detect: /genre auto`)),{kind:"continue"}}if(r==="auto"||r==="clear"){if(!o.appType)return console.log(d("Already on auto-detect (no genre set in config).")),{kind:"continue"};let{appType:s,...i}=o;vk(i,n);let a=xk(n);return console.log(X(`\u2713 Genre reset to auto-detect \u2014 now: ${a?`${a} (${Fh(a)})`:"unclassified (no playbook)"}.`)),console.log(d(" Restarting the agent so the loaded playbook matches\u2026")),{kind:"clear"}}return ED(r)?(vk({...o,appType:r},n),console.log(X(`\u2713 Genre set to ${r} \u2014 ${Fh(r)}.`)),console.log(d(" Restarting the agent so the playbook loads\u2026")),{kind:"clear"}):(console.log(L(`Unknown genre "${r}". Choose one of: ${Rk.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}var Sk={help:su,"?":su,clear:Tm,exit:iu,quit:iu,init:hu,mcp:ma,push:Ba,publish:dy,audit:(e,t)=>qs({cwd:t.cwd,profileName:t.profileName}),discover:fy,scope:gy,pull:Ey,resolve:Py,convert:Ky,write:lw,draft:hw,document:fw,resume:yw,rename:ww,profile:kw,model:xw,doctor:oi,logs:$m,workspace:Tw,project:Aw,"allow-prod":Ew,login:Nw,logout:Dw,screenshot:async(e,t)=>{let n=Ls(e);return n.mode==="capture"?yp(n.rest,t):n.mode==="annotate"?vp(n.rest,t):n.mode==="verify"?jw(n.rest,t):n.mode==="checklist"?Hr(e,t):Da(e,t)},capture:yp,annotate:vp,"capture-setup":Hr,devhints:Mm,inbox:Jw,ask:eb,"catch-up":ab,comments:hb,update:mb,reset:kb,lint:_d,check:Zy,"style-guide":Nl,review:Jb,reorder:ek,restructure:tk,structure:Mb,status:rk,retire:sk,untrack:ik,terms:ck,eval:hk,reuse:$k,genre:Wl,roadmap:Qg,share:ob,auto:hy};function Ck(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 jD}from"node:child_process";import{recordAnalyzedCommit as ID,resolveActiveProfile as LD}from"document360-engine";function OD(e){try{let t=jD("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 bi(e,t){try{let n=OD(e);if(!n)return null;let o=LD(e,t);return ID(e,o.name,n)?n:null}catch{return null}}Hn();var Pk="Or just tell me what to write or update.";function Ak(e,t=0){if(!(e>0))return null;let n=e===1?"the page":"those pages",o=`${e} note${de(e)} from your builder ${e===1?"is":"are"} waiting on code they haven't finished.`,r=t>=e?`I've asked whether ${e===1?"it's":"they're"} done, and I'll write ${n} once the code lands.`:`I'll write ${n} once the code lands, and /catch-up asks your builder whether ${e===1?"it's":"they're"} done.`;return`${o} ${r} Nothing else is blocked.`}function _D(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}
443
-
444
- Optional from here: ${e} of your ${t} docs campaign step${de(t)} ${e===1?"is":"are"} still open (/roadmap shows them).`}function MD(e){let{heldDrafts:t,behind:n}=e,o=t>0?"every draft that was ready is live, and readers have it":"everything you have written is live, and readers are seeing it",r=[];return t>0&&r.push(`${t} article${de(t)} ${t===1?"is":"are"} still saved as a draft, waiting on a picture.`),n>0&&r.push(`${n} code change${de(n)} ${n===1?"has":"have"} landed since your last docs check.`),[`\u2713 That\u2019s this round done \u2014 ${o}.`,...r].join(" ")}var FD="Still open, whenever you want it:";function UD(e,t){let n=t?`Press 1\u2013${e} when you want one \u2014 nothing runs on its own.`:"Run one of the commands above when you want to.";return`Nothing is armed. ${e>0?`${n} `:""}Whatever you leave, I\u2019ll raise again next time you\u2019re in.`}var WD="Screenshots are the only thing still open \u2014 a separate job, and none of it changes your text:",BD="Optional depth, when you want it:",HD="Writing",GD="Screenshots \u2014 a separate job from the writing";function qD(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 VD='\u{1F4ED} No docs yet for this repo. Tell me "write the docs for this repo" and I\u2019ll read the code and draft a structure \u2014 or /audit to see what the docs should cover.';function de(e){return e===1?"":"s"}function KD(e,t){let n=`${t} missing picture${de(t)}`;switch(e){case"spec":return`it writes the capture instructions for the ${n} \u2014 reading your code for the exact screens and buttons`;case"capture":return`it takes the ${n} in a browser and draws the callouts on straight after \u2014 your app needs to be running`;default:return`it draws the callouts on the ${n} already taken \u2014 no browser, about a second each`}}function YD(e,t){if(!e||!t)return!1;let n=o=>o.trim().replace(/\s+/g," ").toLowerCase();return n(e)===n(t)}function Jr(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 Ek(e,t){return e.length===t.length&&e.every((n,o)=>n===t[o])}function Tk(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 c=0;c<n;c++){let l=r.exec(o);if(!l)break;s=o.slice(0,l.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 Zr(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 zo="write the docs for this repo",Bl={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 zD(e,t){let n=[];if(e.sunsetEnv){let l=e.sunsetEnv,f=l.replacementProfile?`/profile ${l.replacementProfile}`:`/profile add ${l.replacement}`;n.push({key:"environment",bullet:`this repo publishes to the ${l.name} environment, which is being retired (${l.replacement} is the current one)`,lead:{kind:"cmd",cmd:f,reason:l.replacementProfile?`it switches to your ${l.replacement} profile (then /login if it asks)`:`it creates a ${l.replacement} profile and switches to it (then /login picks the project)`},picker:null,follow:null,tone:"warn"})}if(e.devhints!=="current"&&e.builderStarted){let l=e.devhintsToVersion?`v${e.devhintsToVersion}`:"a newer version",f=e.devhints==="stale"&&e.devhintsCompletedVersion?` (your builder is on v${e.devhintsCompletedVersion})`:"";n.push({key:"devhints",bullet:`dev\u2194docs protocol moved to ${l}${f} \u2014 your docs aren\u2019t blocked`,lead:{kind:"cmd",cmd:"/devhints",reason:`one paste updates your builder to ${l}`},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:Bl,follow:"Then pick the doc genre below (it sets the playbook I write with)."}),e.styleRules){let l=e.styleRules.articles;n.push({key:"styleRules",bullet:l>0?`the writing rules for these docs were never settled \u2014 and ${l} article${de(l)} ${l===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:l>0?`Which writing rules should these docs follow? (${l} article${de(l)} already written \u2014 changing this later means rewriting them)`:"Which writing rules should these docs follow? (this shapes every article I write)",lead:l>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.styleUpgrade){let l=e.styleUpgrade,f=l.articles,g=l.from.length>0?l.from.join(", "):"the built-in checks only";n.push({key:"styleUpgrade",bullet:`you\u2019re on ${g} \u2014 several of its rules are wrong for software documentation, and the guide measured on real knowledge bases is ready`,lead:null,picker:{title:`Move these docs to the Document360 style guide? (you\u2019re on ${g})`,lead:f>0?`Pick below \u2014 one keypress. Switching is instant; I then run the free text swaps over your ${f} article${de(f)} and stop before the editorial pass.`:"Pick below \u2014 one keypress, before I write anything to it.",exclusive:!0,options:[{cmd:`/style-guide use ${l.to}`,desc:f>0?`switch, then bring your ${f} article${de(f)} up to it \u2014 ${l.rules} rules, none of which can block a publish`:`Microsoft style corrected for software docs \u2014 ${l.rules} rules, none of which can block a publish`},{cmd:"/style-guide keep",desc:`stay on ${g} \u2014 I won\u2019t ask again`}]},follow:"Then decide whether these docs move to the Document360 style guide \u2014 it gets dearer to change the longer it waits."})}if(e.autoChoice){let l=e.autoChoice.articles;n.push({key:"autoMode",bullet:l>0?`you haven\u2019t said whether I should run each step myself or wait for you \u2014 with ${l} article${de(l)} here, that is the difference between a night\u2019s work and an afternoon of key presses`:"you haven\u2019t said whether I should run each step myself or wait for you to press the key each time",lead:null,picker:{title:"Should I run each step myself, or wait for you?",lead:"Pick how I should work below \u2014 one keypress, and shift+tab changes it again whenever you like.",exclusive:!0,options:e.autoChoice.presets},follow:"Then say whether I should run each step myself or wait for you \u2014 shift+tab changes it later."})}if(e.discovery&&e.discovery.status!=="confident"){let l=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)."}):l>0?n.push({key:"discovery",bullet:`product discovery is waiting on ${l} answer${de(l)} 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 l=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",f=[];e.directives>0&&f.push(`${e.directives} owner directive${de(e.directives)} waiting`);let g=e.discovery&&e.discovery.status!=="confident"?e.discovery.answersPending:0,k=g>0?` (${g} settle${g===1?"s":""} the product brief)`:"";e.pendingText&&f.push(`your builder left ${e.pendingText}${k}`),n.push({key:"catchup",bullet:f.join(`
445
- \u2022 `),lead:{kind:"cmd",cmd:"/catch-up",reason:l},picker:null,follow:"Then /catch-up clears what\u2019s queued for the docs.",dependsOn:["discovery"]})}if(e.openComments>0){let l=e.openComments;n.push({key:"comments",bullet:`${l} reviewer comment${de(l)} 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 ${l} reviewer comment${de(l)} waiting on your articles.`})}if(e.conflicts>0){let l=e.conflicts,f=l===1?"it":"these",g=e.unreadable===l,k=g?`${l} article${de(l)} ${l===1?"is":"are"} held on Document360 in a form I can't read back`:e.unreadable>0?`${l} article${de(l)} ${l===1?"is":"are"} waiting on your decision \u2014 changed both here and on Document360, or held there in a form I can't read back`:`${l} article${de(l)} changed both here and on Document360`;n.push({key:"resolve",bullet:`${k} \u2014 /push skips ${f}, and an audit can't trust your local copy until ${l===1?"it is":"they are"} settled`,lead:{kind:"cmd",cmd:"/resolve",reason:g?"it walks each one with you \u2014 publish your copy over the portal, or skip":"it walks each one with you \u2014 keep yours, take the portal's, or skip"},picker:null,follow:g?`Then /resolve settles the ${l} article${de(l)} Document360 won't hand back (publish yours over the portal / skip).`:`Then /resolve settles the ${l} article${de(l)} waiting on your decision (keep yours / take the portal's / skip).`})}let o=e.draftAhead,r=o>0?{key:"golive",bullet:`${o} article${de(o)} ${o===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 ${o} draft${de(o)} live to your readers \u2014 it lists them and asks first`},picker:null,follow:`Then /publish takes the ${o} draft${de(o)} live \u2014 until it does, readers see the previous version.`,dependsOn:["comments"],blockedBy:["review","styleguide"]}:null,s=r!==null&&e.localAhead===0&&e.unreviewed===0&&e.styleErrors===0;if(r&&s&&n.push(r),e.behind>0){let l=e.behind;n.push({key:"audit",bullet:`${l} code change${de(l)} 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 ${l} newer commit${de(l)}.`,blockedBy:["resolve"],opensRound:!0})}if(e.hasDocs&&e.pendingWrites>0){let l=e.pendingWrites;n.push({key:"write",bullet:`${l} planned article${de(l)} still unwritten`,lead:{kind:"cmd",cmd:"/write",reason:"it finishes the articles already planned"},picker:null,follow:`Then /write finishes the ${l} planned article${de(l)}.`,dependsOn:["genre","discovery","catchup","audit"]})}if(e.styleSweep){let l=e.styleSweep.pending,f=e.styleSweep.packs.length>0?e.styleSweep.packs.join(", "):"the built-in checks",g=e.styleSweep.scope?Se("/review","--fix",e.styleSweep.scope):"/review --all --fix";n.push({key:"styleSweep",bullet:`your writing rules changed to ${f} \u2014 ${l<e.styleSweep.total?`${l} of ${e.styleSweep.total}`:`${l}`} article${de(l)} ${l===1?"has":"have"} not been read against them yet`,lead:{kind:"cmd",cmd:g,reason:"it reads each one against the new rules and rewrites it",detail:[t?.scaleFor?.(g),"/style-guide sweep skip stops me raising it."].filter(Boolean).map(k=>k.replace(/([^.!?…])$/,"$1.")).join(" ")},picker:null,follow:`Then ${g} reads the ${l} article${de(l)} the new rules have never been applied to.`,dependsOn:["catchup","comments","audit"]})}if(e.unreviewed>0){let l=e.unreviewed,f=Se("/review","--blocked --fix",e.unreviewedScope);n.push({key:"review",bullet:`${l} article${de(l)} not yet live ${l===1?"carries":"carry"} text no editor has read`,lead:{kind:"cmd",cmd:f,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 ${f} reviews the ${l} unreviewed article${de(l)} \u2014 nothing reaches your readers until it has.`,dependsOn:["catchup","comments"]})}if(e.styleErrors>0){let l=e.styleErrors,f=Se("/lint","--blocked --fix",e.styleErrorScope);n.push({key:"styleguide",bullet:`${l} article${de(l)} not yet live break${l===1?"s":""} house style rules that block publishing`,lead:{kind:"cmd",cmd:f,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 ${f} clears the style errors on ${l} article${de(l)} \u2014 nothing reaches your readers until it has.`,dependsOn:["catchup","comments","review"]})}let i=e.draftBlockedShots??null,a=i&&i.articles>0?{key:"annotate",bullet:`${i.articles} article${de(i.articles)} ${i.articles===1?"is":"are"} saved on Document360 and cannot go live \u2014 ${i.places} picture${de(i.places)} ${i.places===1?"is":"are"} missing, so your readers would see "[Screenshot: \u2026]" on the page`,lead:i.cmd?{kind:"cmd",cmd:i.cmd,reason:KD(i.stage,i.places)}:{kind:"prompt",text:`fix the ${i.places} bare "[Screenshot: \u2026]" line${de(i.places)} \u2014 either give each one a proper screenshot block or take the line out`,reason:"these lines belong to no screenshot, so no command can finish them"},picker:null,follow:i.cmd?`Then ${i.cmd} deals with the ${i.places} missing picture${de(i.places)}, and /push and /publish take the ${i.articles} article${de(i.articles)} live.`:`Then the ${i.places} bare "[Screenshot: \u2026]" line${de(i.places)} can be sorted out, and /push and /publish take the ${i.articles} article${de(i.articles)} live.`,...i.stage==="spec"||i.stage==="capture"?{opensRound:!0}:{}}:e.shotsToAnnotate>0?{key:"annotate",bullet:`${e.shotsToAnnotate} screenshot${de(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${de(e.shotsToAnnotate)} already taken.`}:e.shotsToRecapture>0?{key:"annotate",bullet:`${e.shotsToRecapture} screenshot${de(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${de(e.shotsToRecapture)}.`,opensRound:!0}:null,c=a!==null&&i!==null&&i.articles>0;if(a&&!c&&e.localAhead>0&&n.push(a),e.localAhead>0){let l=e.localAhead;n.push({key:"publish",bullet:`${l} article${de(l)} changed locally \u2014 ready to send to Document360`,lead:{kind:"cmd",cmd:"/push",reason:`it saves your ${l} local edit${de(l)} to Document360 as drafts`},picker:null,follow:`Then /push saves your ${l} local edit${de(l)} to Document360.`,dependsOn:["discovery","comments","audit","annotate"],blockedBy:["review","styleguide"]})}if(r&&!s&&n.push(r),a&&(c||e.localAhead===0)&&n.push(a),e.hasDocs&&e.roadmap?.next){let l=e.roadmap,f=l.next,g=f.run?t?.scaleFor?.(f.run)??null:null,k=f.run?g:Tk(f.body),T=f.run?g??void 0:Tk(f.body,340,2)??void 0,A=`docs campaign: ${l.done} of ${l.total} step${de(l.total)} done`,S=!!f.run&&YD(f.run,e.lastCommand);n.push(S?{key:"roadmap",bullet:`${A} \u2014 \u201C${f.title}\u201D is waiting on you
446
- \u2022 You just ran ${f.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:`${A} \u2014 next: ${f.title}${k?`
447
- \u2022 ${k}`:""}`,lead:f.run?{kind:"cmd",cmd:f.run,reason:"it\u2019s the next step of your docs campaign",...T?{detail:T}:{}}:{kind:"prompt",text:f.title,reason:"it\u2019s the next step of your docs campaign",...T?{detail:T}:{}},picker:null,follow:`Then the campaign continues: ${f.title} (/roadmap shows all ${l.total} steps).`,dependsOn:["genre","discovery","audit"],rowBullet:`${A} \u2014 this is next${k?`
448
- \u2022 ${k}`:""}`,opensRound:!0})}if(e.handoff){let l=Math.max(e.handoff.unpushed,e.handoff.uncommitted>0?1:0),f=e.handoff.unpushed;l>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(`
449
- `),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}):f>0&&n.push({key:"share",bullet:`\u26A0 ${f} docs change set${de(f)} 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 l=e.uncommittedDocs;n.push({key:"commit",bullet:`\u26A0 ${l} uncommitted change${de(l)} under .d360-writer/ \u2014 tell your coding agent: "commit d360-writer's work"`,lead:null,picker:null,follow:null})}return n}function Nk(e){return e.find(t=>t.lead||t.picker)??null}function XD(e){return e.kind==="cmd"?e.cmd:e.kind==="prompt"?`\u201C${e.text}\u201D`:""}function es(e){return e.kind==="cmd"?e.cmd:e.kind==="prompt"?e.text:null}function QD(e){return es(e)??""}function JD(e,t,n){let o=a=>(a??[]).map(c=>t.get(c)).filter(c=>c!==void 0&&c<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 ki(e,t,n,o=null,r,s=0,i=0,a=0,c=!1){if(r&&r.length>0){let E=r.filter(ja),I=r.filter(me=>!ja(me)),W=[...I,...E],V=(me,Re)=>` ${Re+1}. ${me.title}${me.run?` \xB7 ${me.run}`:""}`,B;return E.length===0||I.length===0?B=[e,...W.map(V)].join(`
450
- `):B=[e,"",` ${HD}`,...I.map((me,Re)=>V(me,Re)),"",` ${GD}`,...E.map((me,Re)=>V(me,I.length+Re))].join(`
451
- `),{note:[...o?[o]:[],B,qD(W.length,n),Pk].join(`
452
-
453
- `),menu:W.map(me=>me.run??me.title)}}let l=c?null:Nk(t),f=l?.picker?[]:t.filter(E=>E.lead),g=c||f.length>=2?f:[],k=new Map(g.map((E,I)=>[E.key,I+1])),T=[];l?.lead?T.push(Zr(l.lead)):l?.picker&&T.push(l.picker.lead);for(let E of t.filter(I=>I!==l&&!I.lead).slice(0,2))E.follow&&T.push(E.follow);c?T.push(UD(g.length,n)):g.length>=2&&n&&T.push(`Press 1\u2013${g.length} to pick a different one \u2014 the number fills the box, enter runs it.`);let A=T.join(" "),S=t.filter(E=>E.bullet).map(E=>{let I=k.get(E.key),[W="",...V]=(I&&E.lead?.kind==="prompt"&&E.rowBullet?E.rowBullet:E.bullet).split(`
454
- \u2022 `),B=E===l&&E.lead?.kind!=="answer"&&E.lead?.detail?[]:V;if(I&&E.lead){let Re=W.replace(/^→\s+/,"");return[` ${I}. ${XD(E.lead)} \u2014 ${Re}${JD(E,k,I)}`,...B.map(ge=>` ${ge}`)].join(`
455
- `)}let ae=E.lead?.kind==="cmd"?E.lead.cmd:null;return` \u2022 ${[W,...B].join(`
456
- \u2022 `)}${ae&&!A.includes(ae)?` \u2014 ${ae}`:""}`}),C=o?[o,[e,...S].join(`
441
+ `),display:`/restructure${n?` ${n}`:""}`}}async function ck(e,t){let n=Ah(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"})}oe();import{computeReadiness as VN,readinessPlaceholderPlaces as YN,coverageGap as KN}from"document360-engine";import We from"picocolors";var zr=5;function Oe(e,t=58){let n=e.replace(/\\/g,"/");return n.length<=t?n:`\u2026${n.slice(n.length-t+1)}`}function zN(e){let t=[],n=e.verdict;if(e.conflicts.length>0&&t.push({glyph:"\u2717",paint:We.red,title:`Changed here and on Document360 (${e.conflicts.length})`,fix:"/resolve",items:e.conflicts.map(o=>Oe(o))}),n.unreviewed.length>0&&t.push({glyph:"\u2717",paint:We.red,title:`Never read by an editor (${n.unreviewed.length})`,fix:"/review --blocked --fix",items:n.unreviewed.map(o=>Oe(o))}),n.styleErrors.length>0){let o=n.styleErrors.reduce((r,s)=>r+s.errors,0);t.push({glyph:"\u2717",paint:We.red,title:`Break house style rules your config makes blocking (${o} error${o===1?"":"s"})`,fix:"/lint --blocked --fix",items:n.styleErrors.map(r=>`${Oe(r.path)} (${r.errors})`)})}if(n.placeholders.length>0){let o=YN(e);t.push({glyph:"\u2717",paint:We.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=>`${Oe(r.path)} (${r.missingShots.length+r.orphans})`)})}return t}function XN(e){let t=e.verdict,n=[];return e.conflicts.length===0&&n.push(`${K("\u2713",We.green)}Nothing is in conflict with Document360`),t.unreviewed.length===0&&n.push(`${K("\u2713",We.green)}Every article has been read by an editor`),t.styleErrors.length===0&&n.push(`${K("\u2713",We.green)}House style: nothing blocking`),t.placeholders.length===0&&n.push(`${K("\u2713",We.green)}No placeholder text would reach a reader`),n}function QN(e,t){if(e.rows.length===0)return[];let n=r=>r?We.green("\u2713"):We.red("\u2717"),o=e.rows.map((r,s)=>[String(s+1),Oe(r.path,46),n(r.reviewed),r.styleErrors===0?We.green("\u2713"):We.red(`\u2717 ${r.styleErrors}`),r.placeholders===0?We.green("\u2713"):We.red(`\u2717 ${r.placeholders}`),r.conflict?We.red("conflict"):r.draftPending?We.yellow("draft"):r.localAhead?d("not saved"):d("\u2014")]);return Xs(["#","Article","Read","Style","Pictures","Document360 (last sync)"],o,t).split(`
442
+ `)}function Eh(e,t={}){let n=VN(e,t.profileName),o=[];if(n.rows.length===0){o.push(ee("Publish readiness")),o.push("");let l=KN(n.coverage);return o.push(n.tracked===0?`${K("\u25CB",We.gray)}No articles are tracked yet. /write authors them, /push saves them to Document360.`:l>0?`${K("\u2713",We.green)}All ${n.tracked} tracked articles are live and unchanged.`:`${K("\u2713",We.green)}All ${n.tracked} articles are live and unchanged \u2014 nothing is waiting on you.`),o.push(...JN(n)),n.orphans.length>0&&o.push(...dk(n)),n.unadopted.length>0&&(o.push(""),o.push(...uk(n))),o.push(""),o.push(d(" 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(ee("Publish readiness")+d(` ${r} article${r===1?"":"s"} not yet settled with readers \xB7 ${s===0?"nothing blocked":`${s} blocked`}`)),o.push(""),t.all&&(o.push(...QN(n,t.width??100)),o.push(""));for(let l of zN(n)){o.push(` ${K(l.glyph,l.paint)}${l.title}${l.fix?d(` ${l.fix}`):""}`);for(let f of l.items.slice(0,zr))o.push(d(` ${f}`));l.items.length>zr&&o.push(d(` \u2026and ${l.items.length-zr} more`)),o.push("")}let i=uk(n);i.length>0&&(o.push(...i),o.push(""));let a=XN(n);if(a.length>0){for(let l of a)o.push(` ${l}`);o.push("")}let c=n.rows.filter(l=>l.localAhead).length;return c>0&&o.push(d(` ${c} changed here \u2014 /push saves ${c===1?"it":"them"} to Document360 as ${c===1?"a draft":"drafts"}. Readers see nothing until then.`)),n.draftPending.length>0&&(o.push(d(` ${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.`)),o.push(d(" That is from your last sync. /pull re-checks what is live."))),n.orphans.length>0&&o.push(...dk(n)),!t.all&&n.rows.length>0&&o.push(d(" /status --all shows every article, gate by gate.")),o.push(""),o.push(d(" Free \u2014 /status reads your local files and the last sync. It calls nothing.")),o}function uk(e){let t=e.unadopted.length;if(t===0)return[];let n=[` ${K("\u25CB",We.gray)}${t===1?"One page here came from Document360 and nothing has adopted it":`${t} pages here came from Document360 and nothing has adopted them`}`,d(` Not in your docs plan, not written by d360-writer, and nothing records what ${t===1?"it says":"they say"}.`),d(` So no editor can check ${t===1?"it":"them"}: a review pass over ${t===1?"it":"them"} comes back having changed nothing.`)];for(let o of e.unadopted.slice(0,zr))n.push(` /untrack ${o.path}`);return t>zr&&n.push(d(` \u2026and ${t-zr} more`)),n.push(d(" Disowning one leaves Document360 untouched \u2014 the page, its history and its comments all stay.")),n}function dk(e){let t=e.orphans.length;return[d(` ${t} article${t===1?"":"s"} on Document360 ${t===1?"is":"are"} not in your docs folder (${Oe(e.orphans[0].path,40)}${t>1?`, +${t-1} more`:""}) \u2014 /doctor lists ${t===1?"it":"them"}.`)]}function pk(e){let t=Date.now()-Date.parse(e);if(!Number.isFinite(t)||t<0)return"just now";let n=Math.floor(t/6e4);if(n<2)return"just now";if(n<60)return`${n} minutes ago`;let o=Math.floor(n/60);if(o<24)return`${o} hour${o===1?"":"s"} ago`;let r=Math.floor(o/24);return`${r} day${r===1?"":"s"} ago`}function JN(e){let t=e.coverage;if(!t)return e.tracked===0?[]:["",d(" Nothing has compared this repo with Document360 yet."),"",d(" /pull --status counts what is there.")];if(t.unmapped===0)return[d(` Every Document360 article is tracked here (${t.mappedArticles} of ${t.portalArticles}, checked ${pk(t.at)}).`)];let n=t.portalOnlyCategories.filter(r=>r.articles>0).length,o=["",q(` ${K("\u26A0",We.yellow)}Document360 holds ${t.portalArticles} articles in ${t.portalCategories} categories.`),"",d(` This repo tracks ${t.mappedArticles} of them.`)];return n>0&&(o.push(""),o.push(d(` ${t.unmapped} articles sit in ${n} ${n===1?"category":"categories"} with no folder here.`))),t.declined>0&&(o.push(""),o.push(d(` ${t.declined} more ${t.declined===1?"is one you":"are ones you"} declined with /untrack.`))),o.push(""),o.push(d(` /pull imports them. Checked ${pk(t.at)}.`)),o}async function hk(e,t){let n=e.some(o=>o==="--all"||o==="--full");for(let o of Eh(t.cwd,{profileName:t.profileName,all:n}))console.log(o);return{kind:"continue",ownNext:!0}}oe();import{computeReadiness as ZN,retireArticle as eD,retiredPaths as tD,normalizeScope as nD}from"document360-engine";import{select as oD}from"@inquirer/prompts";function Nh(e,t){let n=ZN(e,t),o=tD(e,t),r=[ee("Take an article off your readers"),""];if(n.orphans.length>0){r.push(` ${K("\u25CB",d)}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(d(` ${Oe(s.path)}`));n.orphans.length>8&&r.push(d(` \u2026and ${n.orphans.length-8} more`)),r.push("")}if(o.length>0){r.push(` ${K("\u2713",d)}Already retired \u2014 readers do not see ${o.length===1?"it":"these"}:`);for(let s of o.slice(0,5))r.push(d(` ${Oe(s)}`));o.length>5&&r.push(d(` \u2026and ${o.length-5} more`)),r.push("")}return n.orphans.length===0&&o.length===0&&(r.push(d(" Nothing obvious to retire \u2014 every tracked article is still in your docs folder.")),r.push("")),r.push(d(" /retire <path> takes one off your readers. Any tracked article can be named, not just these.")),r.push(d(" Nothing is deleted: the article, its history and every reviewer comment stay on Document360.")),r.push(d(" /push puts one back \u2014 reviving is a publish like any other, with the same review.")),r}async function fk(e,t){let n=t.cwd,o=e.find(a=>!a.startsWith("-"));if(!o){for(let a of Nh(n,t.profileName))console.log(a);return{kind:"continue",ownNext:!0}}let r=nD(n,o)||o;if(!(e.includes("--yes")||e.includes("-y"))&&(console.log(""),console.log(q(`This takes "${Oe(r)}" off your readers on Document360.`)),console.log(d(" The article, its history and every reviewer comment stay \u2014 nothing is deleted.")),console.log(d(" /push puts it back later if you change your mind.")),console.log(""),await oD({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(d("Nothing changed.")),{kind:"continue",ownNext:!0};let i=await eD({cwd:n,path:r,profileName:t.profileName,now:new Date().toISOString()});return i.ok?(console.log(i.alreadyHidden?`${K("\u2713")}"${Oe(r)}" was already invisible to readers. Recorded as retired, so nothing will offer to publish it again.`:`${K("\u2713")}"${Oe(r)}" is no longer visible to your readers.`),console.log(d(" It is still on Document360 with its history and comments intact. /push puts it back.")),{kind:"continue",ownNext:!0}):(console.log(L(`${K("\u2717")}Could not retire "${Oe(r)}" \u2014 ${i.error.message}`)),{kind:"continue",ownNext:!0})}oe();import{declineImport as rD,loadDeclinedImports as sD,undoDecline as iD,normalizeScope as aD,resolveActiveProfile as lD}from"document360-engine";import{select as cD}from"@inquirer/prompts";function Dh(e,t){let n={};try{n=sD(e,lD(e,t).name)}catch{}let o=Object.keys(n),r=[ee("Pages on Document360 that are not part of these docs"),""];if(o.length===0)r.push(d(" Nothing is declined. Every article on Document360 in one of your categories is")),r.push(d(" imported into your docs folder when you run /catch-up or /pull."));else{for(let s of o.slice(0,10)){let i=n[s];r.push(` ${K("\u25CB",d)}${i.title??i.path??s}`),i.path&&r.push(d(` was ${Oe(i.path)}`)),i.keptAt&&r.push(d(` kept at ${i.keptAt}`))}o.length>10&&r.push(d(` \u2026and ${o.length-10} more`))}return r.push(""),r.push(d(" /untrack <path> disowns an imported page \u2014 nothing on Document360 changes.")),r.push(d(" /untrack --undo <path> puts it back and lets the next /catch-up import it again.")),r}async function mk(e,t){let n=t.cwd,o=e.find(l=>!l.startsWith("-")),r=e.includes("--list")||e.includes("-l"),s=e.includes("--undo");if(r||!o&&!s){for(let l of Dh(n,t.profileName))console.log(l);return{kind:"continue",ownNext:!0}}if(!o)return console.log(L(`${K("\u2717")}Name what to put back: /untrack --undo <path>`)),{kind:"continue",ownNext:!0};let i=aD(n,o)||o;if(s){let l=iD(n,t.profileName,i);return l.ok?(console.log(l.restoredTo?`${K("\u2713")}Put "${Oe(l.restoredTo)}" back in your docs folder.`:`${K("\u2713")}No longer declined. /catch-up imports it again on the next run.`),{kind:"continue",ownNext:!0}):(console.log(L(`${K("\u2717")}${l.error.message}`)),{kind:"continue",ownNext:!0})}if(!(e.includes("--yes")||e.includes("-y"))&&(console.log(""),console.log(q(`This stops tracking "${Oe(i)}" as one of your docs.`)),console.log(d(" Nothing on Document360 changes \u2014 the page, its history and its comments all stay,")),console.log(d(" and your readers see no difference.")),console.log(d(" The markdown moves to .d360-writer/declined/, so nothing is deleted.")),console.log(d(" /untrack --undo puts it back if you change your mind.")),console.log(""),await cD({message:"Stop tracking it?",choices:[{name:"No \u2014 leave it as it is",value:"no"},{name:"Yes \u2014 it is not one of my docs",value:"yes"}]})!=="yes"))return console.log(d("Nothing changed.")),{kind:"continue",ownNext:!0};let c=rD({cwd:n,path:i,profileName:t.profileName,now:new Date().toISOString()});return c.ok?(console.log(`${K("\u2713")}"${c.title??Oe(c.path)}" is no longer one of your docs.`),c.keptAt&&console.log(d(` The markdown is kept at ${c.keptAt} \u2014 nothing was deleted.`)),console.log(d(" It is untouched on Document360. /catch-up will not import it again.")),{kind:"continue",ownNext:!0}):(console.log(L(`${K("\u2717")}Could not untrack "${Oe(i)}" \u2014 ${c.error.message}`)),{kind:"continue",ownNext:!0})}oe();import{scanTerminology as gk,approvalBlockedReason as yk,readProjectConfig as uD,writeProjectConfig as dD,termKey as jh,HEAD_NOUN_CAP as pD}from"document360-engine";import tn from"picocolors";var hD=3,fD=e=>e.uses.map(t=>`${tn.bold(t.form)} ${d(`${t.files.length} article${t.files.length===1?"":"s"}`)}`).join(d(" \xB7 "));function Ih(e,t={}){let n=gk(e,t.scope?{scope:t.scope}:{}),o=[];if(n.scanned===0)return[ee("Terminology"),"",`${K("\u25CB",d)}No articles to read yet.`,""];let r=n.variance.length+n.headings.length;if(o.push(ee("Terminology")+d(` ${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(` ${K("\u2717",tn.red)}The same term, spelled more than one way`);for(let s of n.variance){o.push(` ${fD(s)}`);let i=s.uses[s.uses.length-1],a=i.files.slice(0,hD);o.push(d(` "${i.form}" is in ${a.map(l=>Oe(l,40)).join(", ")}${i.files.length>a.length?`, +${i.files.length-a.length} more`:""}`));let c=yk(s);c?o.push(d(` ${c}`)):o.push(d(` /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,pD);o.push(` ${K("\u25CB",d)}Possibly the same thing under a short name \u2014 ${tn.italic("your call")}`);for(let i of s)o.push(d(` ${i.uses.map(a=>a.form).join(" \xB7 ")}`));n.headNouns.length>s.length&&o.push(d(` \u2026and ${n.headNouns.length-s.length} more \u2014 /terms --all lists them`)),o.push(d(' A shared word is not proof of a shared meaning: "billing history" and "history" are')),o.push(d(" different things. Nothing is flagged as wrong here.")),o.push("")}if(n.headings.length>0){o.push(` ${K("\u26A0",tn.yellow)}Titles out of step with the rest of their kind`);for(let s of n.headings)o.push(` ${tn.bold(s.title)} ${d(`\u2014 ${Oe(s.path,40)}`)}`),o.push(d(` the other ${s.peers} ${s.type} article${s.peers===1?"":"s"} look like "${s.example}"; this one starts ${mD(s.shape)}`));o.push("")}return r===0&&n.headNouns.length===0&&(o.push(` ${K("\u2713",tn.green)}Every term is spelled one way, and every title matches its kind.`),o.push("")),o.push(d(' This compares spellings, not meanings: two different words for one thing (say "nav" and')),o.push(d(' "rail") look unrelated to it. Add the pair to your approved terms and every run enforces it.')),o.push(d(" Free \u2014 this read your articles and called nothing.")),o}function mD(e){return e==="gerund"?"with an -ing word":e==="how-to"?'with "How to"':"differently"}function Lh(e,t,n){let o=n??gk(e),r=jh(t),s=o.variance.find(g=>g.uses.some($=>jh($.form)===r));if(!s)return{wrote:!1,lines:[`${K("\u2717",tn.red)}"${t}" is not one of the terms with competing spellings. /terms lists them.`]};let i=yk(s);if(i)return{wrote:!1,lines:[`${K("\u2717",tn.red)}That one cannot be recorded: ${i}.`,d(` The spellings in play are ${s.uses.map(g=>`"${g.form}"`).join(" and ")}.`)]};let a=s.uses.find(g=>jh(g.form)===r).form,c=s.uses.filter(g=>g.form!==a).map(g=>g.form),l=uD(e);if(!l)return{wrote:!1,lines:[`${K("\u2717",tn.red)}No project configuration here \u2014 run /init first.`]};let f={...l.terminologyGlossary??{}};for(let g of c)f[g]=a;return dD({...l,terminologyGlossary:f},e),{wrote:!0,lines:[`${K("\u2713",tn.green)}"${a}" is now the approved spelling.`,d(` Added to your approved terms: ${c.map(g=>`"${g}" \u2192 "${a}"`).join(", ")}`),d(" Every run enforces it from now on, and /lint --fix corrects the others for free.")]}}async function wk(e,t){let n=e.findIndex(s=>s==="--approve");if(n!==-1){let s=e[n+1];if(!s)return console.log(`${K("\u2717",tn.red)}Name the spelling to approve, e.g. /terms --approve "drop-down".`),{kind:"continue",ownNext:!0};for(let i of Lh(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 Ih(t.cwd,{...r?{scope:r}:{},all:o}))console.log(s);return{kind:"continue",ownNext:!0}}oe();import{evaluateCorpus as gD,buildRegistry as yD,lintArticles as wD,scanTerminology as bD,BUILTIN_RULES as kD}from"document360-engine";import hn from"picocolors";var so=3,xt=(e,t)=>`${e} ${t}${e===1?"":"s"}`,$k=e=>`${Oe(e.path)}:${e.line}`,bk=e=>e.split("/").pop()?.split("\\").pop()??e;function kk(e,t,n,o,r,s,i){if(r.length===0)return;e.push(` ${K(t,n)}${o}`);let a=i?r:r.slice(0,so);for(let c of a)e.push(d(` ${$k(c)} ${c.detail}`));r.length>a.length&&e.push(d(` \u2026and ${r.length-a.length} more \u2014 /eval --all`)),e.push(d(` ${s}`)),e.push("")}function Oh(e,t={}){let n=yD(e),o=new Set([...kD.map(c=>c.id),...n.rules.map(c=>c.id)]),r=gD(e,o,{...t.scope?{scope:t.scope}:{},...t.profile?{profile:t.profile}:{}}),s=t.all===!0,i=[];if(r.articles===0)return[ee("Knowledge-base score"),"",`${K("\u25CB",d)}No articles to read yet.`,""];let a=r.links.absolute.length+r.links.deadAnchors.length+r.links.staleLabels.length+r.shapes.typeTemplates.filter(c=>c.deviations.length>0).length+(r.shapes.synopsisForms.length>1?1:0);if(i.push(ee("Knowledge-base score")+d(` ${xt(r.articles,"article")} read \xB7 ${a===0?"nothing to look at":`${a} to look at`}`)),i.push(""),kk(i,"\u2717",hn.red,"Internal links written as portal URLs",r.links.absolute,"These break the day the site moves. Write them as relative .md links instead.",s),kk(i,"\u2717",hn.red,"Links pointing at headings that do not exist",r.links.deadAnchors,"The heading was renamed after the link was written. Point it at the current heading.",s),r.links.staleLabels.length>0){let c=r.links.staleLabels.reduce((l,f)=>l+f.sites.length,0);i.push(` ${K("\u26A0",hn.yellow)}${xt(r.links.staleLabels.length,"link label")} name an article something it is not called${c>r.links.staleLabels.length?d(`, in ${xt(c,"place")}`):""}`);for(let l of s?r.links.staleLabels:r.links.staleLabels.slice(0,so))if(i.push(d(` "${l.label}" \u2192 the article is titled "${l.title}"${l.sites.length>1?` (${l.sites.length}\xD7)`:""}`)),s)for(let f of l.sites)i.push(d(` ${$k(f)}`));!s&&r.links.staleLabels.length>so&&i.push(d(` \u2026and ${r.links.staleLabels.length-so} more \u2014 /eval --all`)),i.push(d(" A reader clicks expecting one page and lands on another name.")),i.push("")}if(s&&r.links.shortenedLabels.length>0){i.push(` ${K("\u25CB",d)}${xt(r.links.shortenedLabels.length,"link label")} shorten the title they point at`);for(let c of r.links.shortenedLabels.slice(0,10))i.push(d(` "${c.label}" \u2192 "${c.title}"`));i.push(d(" Usually fine. Listed separately because it is a judgment call, not a defect.")),i.push("")}if(r.shapes.synopsisForms.length>1){i.push(` ${K("\u26A0",hn.yellow)}The command summary line appears in ${xt(r.shapes.synopsisForms.length,"shape")}`);for(let c of r.shapes.synopsisForms)i.push(d(` ${String(c.count).padStart(3)} ${c.form.padEnd(14)} ${c.examples.map(bk).join(", ")}`));r.shapes.noSynopsis.length>0&&i.push(d(` ${xt(r.shapes.noSynopsis.length,"article")} carry none at all`)),i.push(d(" Same information, different labels. Pick one and use it everywhere.")),i.push("")}for(let c of r.shapes.typeTemplates)if(c.deviations.length!==0){i.push(` ${K("\u26A0",hn.yellow)}${c.deviations.length} of ${xt(c.articles,`${c.type} article`)} skip a section the rest of them carry`),i.push(d(` Most ${c.type} articles have: ${c.expected.map(l=>`## ${l.heading} (${l.count})`).join(" \xB7 ")}`));for(let l of s?c.deviations:c.deviations.slice(0,so))i.push(d(` ${bk(l.path)} \u2014 missing ${l.missing.map(f=>`## ${f}`).join(", ")}`));!s&&c.deviations.length>so&&i.push(d(` \u2026and ${c.deviations.length-so} more \u2014 /eval --all`)),i.push(d(" A deviation may be deliberate. This counts them; it does not say the template is right.")),i.push("")}try{let c=bD(e,t.scope?{scope:t.scope}:{});if(c.variance.length>0){i.push(` ${K("\u26A0",hn.yellow)}${xt(c.variance.length,"term")} spelled more than one way across the set`);for(let l of c.variance.slice(0,s?99:so))i.push(d(` ${l.uses.map(f=>`"${f.form}" \xD7${f.count}`).join(" \xB7 ")}`));c.headNouns.length>0&&i.push(d(` ${xt(c.headNouns.length,"short name")} may be a longer one abbreviated \u2014 /terms lists them`)),i.push(d(' Settle one and every later run enforces it: /terms --approve "<term>"')),i.push("")}}catch{}try{let l=wD({cwd:e,...t.scope?{scope:t.scope}:{}}).findings.filter(g=>!g.baselined),f=l.filter(g=>g.severity==="error").length;if(i.push(` ${K(f>0?"\u2717":l.length>0?"\u26A0":"\u2713",f>0?hn.red:l.length>0?hn.yellow:hn.green)}`+(l.length===0?"Style rules: nothing reported":`Style rules: ${xt(l.length,"finding")}${f>0?`, ${f} blocking publish`:", none blocking publish"}`)),l.length>0){let g=new Map;for(let $ of l)g.set($.ruleId,(g.get($.ruleId)??0)+1);for(let[$,T]of[...g.entries()].sort((A,S)=>S[1]-A[1]).slice(0,s?99:5))i.push(d(` ${String(T).padStart(4)} ${$}`));i.push(d(" Fix what can be fixed mechanically: /lint --fix"))}i.push("")}catch{}if(r.debt&&r.debt.total>0){let c=r.debt.liveRules.reduce((g,$)=>g+$.count,0),l=r.debt.inertRules.reduce((g,$)=>g+$.count,0),f=r.debt.createdAt.slice(0,10);if(c>0){i.push(` ${K("\u2139",d)}${xt(c,"style finding")} accepted as exempt on ${f}, from rules that are still on`);for(let g of r.debt.liveRules.slice(0,s?99:4))i.push(d(` ${String(g.count).padStart(4)} ${g.rule}`));i.push(d(" Nothing reports these, so the articles read as compliant. They are exempt, not compliant.")),i.push(d(" Work them down with /review --all --fix, then /lint --all --fix."))}else l>0&&(i.push(` ${K("\u25CB",d)}${xt(l,"finding")} accepted on ${f} under a style guide no longer in use`),i.push(d(" They match no active rule, so they suppress nothing. Only weight in the file.")));i.push("")}return a===0&&(r.debt?.total??0)===0&&(i.push(` ${K("\u2713",hn.green)}Links resolve, one template shape, one name per thing.`),i.push("")),i.push(d(` Free \u2014 this read your ${xt(r.articles,"article")} and called nothing.`)),i}async function vk(e,t){let n=e.includes("--all"),o=e.find(r=>!r.startsWith("--"));for(let r of Oh(t.cwd,{...o?{scope:o}:{},...t.profileName?{profile:t.profileName}:{},all:n}))console.log(r);return{kind:"continue",ownNext:!0}}import{fetchPortalReuse as MD,readReuseCache as FD,writeReuseCache as UD,resolveActiveProfile as Fh,resolveProjectId as Uh,createVariable as Pk,createSnippet as Tk,reuseNameProblem as WD,variableRule as BD,VARIABLE_MAX_CHARS as Sk}from"document360-engine";oe();import{scanReuse as xk,scanValueCandidates as Rk,buildReuseAuditPrompt as $D,reuseAuditProposalPath as vD,readReuseProposal as xD,readReuseCache as RD,listArticleFiles as SD,normalizeScope as CD,docsRootOf as PD,variableRule as TD}from"document360-engine";import{rmSync as AD}from"node:fs";import ED from"picocolors";var Ul=6,ND=20;function DD(e,t){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}\u2026`:n}function jD(e,t=52){let n=e.replace(/\s+/g," ").trim(),o=[],r="";for(let s of n.split(" "))r===""?r=s:`${r} ${s}`.length<=t?r+=` ${s}`:(o.push(r),r=s);return r!==""&&o.push(r),o}function Wl(e,t,n,o){let r=[ee("Content reuse audit"),""];return r.push(`${e} article${e===1?"":"s"} read${d(" \xB7 free to look")}`,""),r.push(` ${String(n).padStart(3)} value${n===1?"":"s"} written out by hand in more than one article`),r.push(` ${String(t).padStart(3)} block${t===1?"":"s"} written more than once, in different words`),o>0&&r.push(d(` ${o} more families were left out of this pass \u2014 the longest ones are shown first.`)),r}function Bl(e,t){let n=PD(e),o=t.filter($=>$!=="audit"&&!$.startsWith("--")).find($=>$!==void 0),r=o?CD(n,o.replace(/\\/g,"/").replace(/\/+$/,"")):void 0,s=SD(e,r).length;if(s===0)return{lines:[ne("\u25CB",r?`No articles under ${r} to audit.`:"No articles to audit yet."),d(" Reuse is about text that repeats, so there has to be some text first.")]};let i=xk(e,{...r?{scope:r}:{},groups:!0}),a=Rk(e,r?{scope:r}:void 0),c=i.groups??[],l=a.candidates;if(c.length===0&&l.length===0)return{lines:[ne("\u2713",`Nothing repeats across ${s} article${s===1?"":"s"} \u2014 there is nothing to keep in one place.`),d(" That is a good answer, not an empty one. Run this again after a few more articles.")]};let f=RD(e),g=vD(e);try{AD(g,{force:!0})}catch{}return{prompt:$D({cwd:e,families:c,values:l,snippets:f?.snippets??[],variables:f?.variables??[],terms:f?.terms??[],proposalPath:g,articles:s}),display:r?`/reuse audit ${r}`:"/reuse audit",articles:s,families:c.length,values:l.length}}function ID(e,t){let n=[],o=` ${String(t).padStart(2)} ${e.kind.padEnd(9)}${ED.bold(e.name.padEnd(ND))}`,r=e.kind==="variable"?[`"${DD(e.value,52)}"`]:jD(`"${e.value}"`);n.push(`${o}${r[0]??""}`);for(let a of r.slice(1))n.push(`${" ".repeat(o.length-10)}${a}`);let s=e.uses>0?`${e.uses} use${e.uses===1?"":"s"} across ${e.files} article${e.files===1?"":"s"}`:"",i=e.why?s?` \u2014 ${e.why}`:e.why:"";return(s||i)&&n.push(d(` ${s}${i}`)),n}function LD(e,t,n){let o=[],r=e.proposals.length;if(o.push(r===0?ne("\u2713",`An editor read ${t} famil${t===1?"y":"ies"} and ${n} value${n===1?"":"s"}. None of it has to stay identical everywhere.`):ne("\u2713",`An editor read ${t} famil${t===1?"y":"ies"} and ${n} value${n===1?"":"s"}. ${r} ${r===1?"is":"are"} worth keeping in one place.`),""),e.proposals.forEach((s,i)=>{o.push(...ID(s,i+1),"")}),e.rejected.length>0){o.push(" Not proposed, and why:");for(let s of e.rejected.slice(0,Ul))o.push(d(` \xB7 ${s.what} \u2014 ${s.why}`));e.rejected.length>Ul&&o.push(d(` \xB7 \u2026and ${e.rejected.length-Ul} more.`)),o.push("")}if(e.dropped.length>0){o.push(ne("\u26A0",`${e.dropped.length} proposal${e.dropped.length===1?"":"s"} could not be used:`));for(let s of e.dropped.slice(0,Ul))o.push(d(` \xB7 ${s}`));o.push("")}return o}function OD(){return[d(" Nothing to create. The knowledge base repeats itself, but not in ways that have to stay"),d(" identical everywhere \u2014 which is the answer an editor is for."),""]}function Hl(e,t){let n=[],o=t.created.map(a=>a.name);o.length>0&&(n.push(ne("\u2713",`Created ${o.length} on Document360: ${o.join(", ")}.`)),n.push(d(" Your local copy is in step and the agent has been restarted, so it writes with them from now on.")));for(let a of t.failed)n.push(ne("\u2717",`Document360 refused "${a.name}" \u2014 ${a.why}`));t.failed.length>0&&n.push(d(" Nothing else was changed. A name already in use is the usual cause; /reuse lists what exists."));let r=t.created.some(a=>a.kind==="variable"),s=t.created.filter(a=>a.kind==="snippet"),i=null;if(r){let a=TD(e).rule!==null;n.push(""),n.push(a?ne("\u2139","Those values are still typed out by hand across your articles."):ne("\u2139","Those values are created, but nothing checks them yet.")),a&&(n.push(d(" /lint --all --fix swaps every one of them \u2014 it costs no agent time, and nothing else in")),n.push(d(" your articles changes.")),i="/lint --all --fix")}return s.length>0&&(n.push(""),n.push(ne("\u2139",`${s.length===1?"The snippet exists":`The ${s.length} snippets exist`} on Document360, but no article references ${s.length===1?"it":"them"} yet.`)),n.push(d(` Ask me to use ${s.length===1?"it":"them"} in an article, or run /review --all --fix and the editor will replace the`)),n.push(d(" passages it finds. Replacing a passage changes the words a reader sees, so it goes through")),n.push(d(" an editorial read rather than a mechanical swap.")),i||(i="/review --all --fix")),i&&n.push("",i,""),{lines:n,cta:i}}function Gl(e,t){let n=e.indexOf("--create");if(n===-1)return{picks:[],bad:[]};let o=e.slice(n+1).filter(i=>!i.startsWith("--"));if(o.length===1&&(o[0]==="a"||o[0]==="all"))return{picks:Array.from({length:t},(i,a)=>a),bad:[]};let r=[],s=[];for(let i of o){let a=Number(i);if(!Number.isInteger(a)||a<1||a>t){s.push(i);continue}r.includes(a-1)||r.push(a-1)}return{picks:r,bad:s}}function _D(e){if(e===0)return[];let t=Array.from({length:e},(n,o)=>o+1).join(" ");return[d(` Pick what to create. Run the line below for all ${e}, or edit the numbers to take some.`),"",`/reuse audit --create ${t}`,""]}function ql(){return[ne("\u2717","There is no reuse proposal to create from."),d(" Run /reuse audit first \u2014 it reads your articles and works out what belongs in one place."),"","/reuse audit",""]}function Vl(e,t){let n=xD(e);if(!n)return[ne("\u26A0","The editor did not leave a proposal, so there is nothing to create."),d(" Nothing was changed. This is usually a turn that stopped early \u2014 running it again is safe,"),d(" and the scan it starts from costs nothing."),"",t?`/reuse audit ${t}`:"/reuse audit",""];let o=xk(e,{...t?{scope:t}:{},groups:!0}),r=Rk(e,t?{scope:t}:void 0),s=LD(n,(o.groups??[]).length,r.candidates.length);return s.push(...n.proposals.length===0?OD():_D(n.proposals.length)),s}oe();import{readReuseProposal as HD}from"document360-engine";import Xr from"picocolors";var _h=8,In=6,Mh=14,GD=52;function qD(e){if(!e)return"";let t=new Date(e);return Number.isNaN(t.getTime())?"":t.toLocaleDateString(void 0,{day:"numeric",month:"short"})}function Ck(e,t=GD){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}\u2026`:n}function Wh(e){let t=FD(e),n=[ee("Reusable content"),""];if(!t||t.terms.length===0&&t.snippets.length===0&&t.variables.length===0)return n.push(`${K("\u25CB",d)}Nothing pulled from Document360 yet.`,"",d(" A variable holds a value like your product name in one place, so changing it changes every"),d(" article at once. A snippet does the same for a whole block, like who to contact when"),d(" something goes wrong. A term is defined once and explained everywhere it first appears."),"","/reuse pull",""),n;let o=qD(t.pulledAt);if(t.terms.length===0)n.push(`${K("\u25CB",d)}No glossary terms in this Document360 project${o?d(` (checked ${o})`):""}.`);else{n.push(`${t.terms.length} term${t.terms.length===1?"":"s"} from Document360${o?d(`, pulled ${o}`):""}.`,"");for(let r of t.terms.slice(0,_h)){let s=" ".repeat(Math.max(1,Mh-r.term.length));n.push(` ${Xr.bold(r.term)}${s}${d(r.definition||"(no definition)")}`)}t.terms.length>_h&&n.push(d(` \u2026and ${t.terms.length-_h} more.`))}if(t.variables.length>0){n.push("",`${t.variables.length} value${t.variables.length===1?"":"s"} kept in one place.`,"");for(let s of t.variables.slice(0,In)){let i=" ".repeat(Math.max(1,Mh-s.name.length));n.push(` ${Xr.bold(s.name)}${i}${d(s.value?`"${Ck(s.value)}"`:"(no value recorded)")}`)}t.variables.length>In&&n.push(d(` \u2026and ${t.variables.length-In} more.`));let{skipped:r}=BD(e);if(r.length>0){let s=t.variables.length-r.length;n.push("",d(` ${s} of ${t.variables.length} are checked in your articles. ${r.length===1?"This one is":"These are"} not:`));for(let i of r.slice(0,In))n.push(d(` ${i.name} \u2014 ${i.why}.`));r.length>In&&n.push(d(` \u2026and ${r.length-In} more.`))}}if(t.snippets.length>0){n.push("",`${t.snippets.length} maintained block${t.snippets.length===1?"":"s"}.`,"");for(let r of t.snippets.slice(0,In)){let s=" ".repeat(Math.max(1,Mh-r.name.length)),i=r.usedBy>0?d(` (in ${r.usedBy} article${r.usedBy===1?"":"s"})`):"";n.push(` ${Xr.bold(r.name)}${s}${d(r.description||Ck(r.value??"")||"(no content recorded)")}${i}`)}t.snippets.length>In&&n.push(d(` \u2026and ${t.snippets.length-In} more.`))}return n.push("",d(" Terms are checked at first use in every article, a value you typed out by hand is flagged,"),d(" and the writer reuses your blocks by name instead of writing its own version of them."),"","/reuse pull","/lint --all",""),n}async function vi(e,t){let n,o;try{let l=Fh(e,t);n={profile:l.name,connection:l.connection,projectId:l.project.projectId,projectName:l.project.projectName},o=await Uh(n,l.project?.projectId)}catch(l){return{lines:[ne("\u2717",`Not signed in to Document360: ${l instanceof Error?l.message:String(l)}`),d(" Run /login first.")],restart:!1}}let r;try{r=await MD(n,o)}catch(l){return{lines:[ne("\u26A0",`Document360 didn't return your reusable content \u2014 ${l instanceof Error?l.message:String(l)}.`),d(" Nothing is blocked. Everything else works exactly as it did; you just do not get the"),d(" first-use check on your terms, or the reuse checks, until this succeeds.")],restart:!1}}let s={pulledAt:new Date().toISOString(),profile:n.profile,projectId:o,terms:r.terms,snippets:r.snippets,variables:r.variables};if(UD(e,s),s.terms.length+s.snippets.length+s.variables.length===0)return{lines:[ne("\u2139","This Document360 project has no terms, snippets or variables yet."),d(" Someone with portal access adds them under Content tools. A good first one is your product"),d(" name as a variable: it is the string most likely to change, and the hardest to change late.")],restart:!1};let a=[`${s.terms.length} term${s.terms.length===1?"":"s"}`,`${s.snippets.length} snippet${s.snippets.length===1?"":"s"}`,`${s.variables.length} variable${s.variables.length===1?"":"s"}`],c=[ne("\u2713",`Pulled ${a.join(" \xB7 ")} from Document360.`)];return r.droppedTerms.length>0&&c.push(d(` ${r.droppedTerms.length} term${r.droppedTerms.length===1?" has":"s have"} no wording recorded in Document360, so ${r.droppedTerms.length===1?"it is":"they are"} not checked:`),d(` ${r.droppedTerms.slice(0,6).join(", ")}${r.droppedTerms.length>6?`, and ${r.droppedTerms.length-6} more`:""}.`)),r.contentlessBlocks.length>0&&c.push(d(` ${r.contentlessBlocks.length} block${r.contentlessBlocks.length===1?"":"s"} came back without content, so ${r.contentlessBlocks.length===1?"it is":"they are"} not matched against your articles:`),d(` ${r.contentlessBlocks.slice(0,6).join(", ")}${r.contentlessBlocks.length>6?`, and ${r.contentlessBlocks.length-6} more`:""}.`)),c.push("",d(" Your terms are now checked at first use in every article, a value you typed out by hand is"),d(" flagged, and the writer reuses your blocks by name instead of writing its own version."),"","/lint --all",""),{lines:c,restart:!0}}async function Bh(e,t,n,o,r){let s=WD(n);if(s)return{lines:[ne("\u2717",`That name will not work: ${s}.`),d(' Try something like "product-name".')],restart:!1};if(o.trim()==="")return{lines:[ne("\u2717","A value is required \u2014 that is the text this will stand for in your articles.")],restart:!1};if(t==="variable"&&o.length>Sk)return{lines:[ne("\u2717",`A variable holds at most ${Sk} characters and this is ${o.length}.`),d(' Longer text belongs in a snippet: /reuse add snippet <name> "<text>"')],restart:!1};let i,a;try{let c=Fh(e);i={profile:c.name,connection:c.connection,projectId:c.project.projectId,projectName:c.project.projectName},a=await Uh(i,c.project?.projectId)}catch(c){return{lines:[ne("\u2717",`Not signed in to Document360: ${c instanceof Error?c.message:String(c)}`),d(" Run /login first.")],restart:!1}}try{let c=t==="variable"?await Pk(i,a,{name:n,value:o}):await Tk(i,a,{name:n,value:o,...r?{description:r}:{}}),l=await vi(e);return{lines:[ne("\u2713",`Created the ${t} "${c.name}" on Document360.`),d(` Write ${t==="variable"?`:variable[]{name="${c.name}"}`:`::snippet{name="${c.name}"}`} and Document360 puts your text there.`),"",...l.lines],restart:!0}}catch(c){let l=c instanceof Error?c.message:String(c);return{lines:[ne("\u2717",`Document360 refused to create that ${t} \u2014 ${l}`),d(" Nothing was changed. A name already in use is the usual cause; /reuse lists what exists.")],restart:!1}}}function Ak(e){let t=e.trim();return t.length>=2&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))?t.slice(1,-1):t}function VD(e){let t=e.indexOf("--desc");if(t===-1)return{rest:e};let n=Ak(e.slice(t+1).join(" "));return{rest:e.slice(0,t),...n?{description:n}:{}}}function Hh(e){let{rest:t,description:n}=VD(e),o=t.filter(c=>!c.startsWith("--")),[,r,s,...i]=o;if(r!=="variable"&&r!=="snippet")return{error:'Say which one: /reuse add variable <name> "<value>", or /reuse add snippet <name> "<text>".'};if(!s)return{error:`Give it a name: /reuse add ${r} <name> "<value>".`};if(r==="variable"&&n)return{error:"Only a snippet takes --desc; a variable is just its value. Drop the flag, or add it as a snippet."};let a=Ak(i.join(" "));return a===""?{error:`Give it a value: /reuse add ${r} ${s} "<the text it stands for>".`}:{kind:r,name:s,value:a,...n?{description:n}:{}}}async function Ek(e,t){let n=e.find(o=>!o.startsWith("--"));if(n==="add"){let o=Hh(e);if("error"in o)return console.log(`${K("\u2717",Xr.red)}${o.error}`),{kind:"continue",ownNext:!0};let r=await Bh(t.cwd,o.kind,o.name,o.value,o.description);for(let s of r.lines)console.log(s);return r.restart?{kind:"clear"}:{kind:"continue",ownNext:!0}}if(n==="pull"){let o=await vi(t.cwd);for(let r of o.lines)console.log(r);for(let r of Ye(t.cwd,"/reuse pull"))console.log(r);return o.restart?{kind:"clear"}:{kind:"continue",ownNext:!0}}if(n==="audit"){if(e.includes("--create")){let r=HD(t.cwd);if(!r||r.proposals.length===0){for(let f of ql())console.log(f);return{kind:"continue",ownNext:!0}}let{picks:s,bad:i}=Gl(e,r.proposals.length);for(let f of i)console.log(`${K("\u26A0",Xr.yellow)}There is no proposal ${f} \u2014 the list has ${r.proposals.length}.`);if(s.length===0)return console.log(`${K("\u25CB",d)}Nothing picked, so nothing was created.`),{kind:"continue",ownNext:!0};let{outcome:a,pullLines:c}=await Gh(t.cwd,s.map(f=>r.proposals[f]));for(let f of c)console.log(f);let{lines:l}=Hl(t.cwd,a);for(let f of l)console.log(f);for(let f of Ye(t.cwd,"/reuse audit"))console.log(f);return a.created.length>0?{kind:"clear"}:{kind:"continue",ownNext:!0}}let o=Bl(t.cwd,e);if("lines"in o){for(let r of o.lines)console.log(r);for(let r of Ye(t.cwd,"/reuse audit"))console.log(r);return{kind:"continue",ownNext:!0}}for(let r of Wl(o.articles,o.families,o.values,0))console.log(r);return{kind:"forward-to-agent",prompt:o.prompt,display:o.display}}if(n&&n!=="show")return console.log(`${K("\u2717",Xr.red)}I don't know "/reuse ${n}". Use /reuse to see what this project maintains, /reuse pull to refresh it, /reuse audit to find what belongs in one place, or /reuse add variable <name> "<value>".`),{kind:"continue",ownNext:!0};for(let o of Wh(t.cwd))console.log(o);return{kind:"continue",ownNext:!0}}async function Gh(e,t){let n=[],o=[],r,s;try{let a=Fh(e);r={profile:a.name,connection:a.connection,projectId:a.project.projectId,projectName:a.project.projectName},s=await Uh(r,a.project?.projectId)}catch(a){return{outcome:{created:[],failed:t.map(c=>({name:c.name,why:`not signed in to Document360: ${a instanceof Error?a.message:String(a)}`}))},pullLines:[d(" Run /login first.")]}}for(let a of t)try{a.kind==="variable"?await Pk(r,s,{name:a.name,value:a.value}):await Tk(r,s,{name:a.name,value:a.value,...a.description?{description:a.description}:{}}),n.push(a)}catch(c){o.push({name:a.name,why:c instanceof Error?c.message:String(c)})}if(n.length===0)return{outcome:{created:n,failed:o},pullLines:[]};let i=await vi(e);return{outcome:{created:n,failed:o},pullLines:i.restart?[]:i.lines}}oe();import{readProjectConfig as YD,writeProjectConfig as Nk,isAppType as KD,playbookSkillName as zD,detectAppType as Dk}from"document360-engine";var jk=["web","cli","service","library"],XD=new Set(["web","cli"]);function qh(e){return XD.has(e)?`${zD(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function Yl(e,t){let n=t.cwd,o=YD(n);if(!o)return console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let s=o.appType??Dk(n);if(s){let i=o.appType?"set in config":"auto-detected";console.log(`${ee("Genre:")} ${s} (${i}) \u2014 ${qh(s)}`)}else console.log(q("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(d(`Set it: /genre <${jk.join("|")}> \xB7 revert to auto-detect: /genre auto`)),{kind:"continue"}}if(r==="auto"||r==="clear"){if(!o.appType)return console.log(d("Already on auto-detect (no genre set in config).")),{kind:"continue"};let{appType:s,...i}=o;Nk(i,n);let a=Dk(n);return console.log(Q(`\u2713 Genre reset to auto-detect \u2014 now: ${a?`${a} (${qh(a)})`:"unclassified (no playbook)"}.`)),console.log(d(" Restarting the agent so the loaded playbook matches\u2026")),{kind:"clear"}}return KD(r)?(Nk({...o,appType:r},n),console.log(Q(`\u2713 Genre set to ${r} \u2014 ${qh(r)}.`)),console.log(d(" Restarting the agent so the playbook loads\u2026")),{kind:"clear"}):(console.log(L(`Unknown genre "${r}". Choose one of: ${jk.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}var Ik={help:uu,"?":uu,clear:Lm,exit:du,quit:du,init:wu,mcp:ka,push:Ya,publish:wy,audit:(e,t)=>Ys({cwd:t.cwd,profileName:t.profileName}),discover:$y,scope:xy,pull:_y,resolve:Iy,convert:ew,write:mw,draft:kw,document:$w,resume:Rw,rename:Sw,profile:Pw,model:Ew,doctor:si,logs:Tm,workspace:Lw,project:Ow,"allow-prod":_w,login:Mw,logout:Fw,screenshot:async(e,t)=>{let n=_s(e);return n.mode==="capture"?vp(n.rest,t):n.mode==="annotate"?Pp(n.rest,t):n.mode==="verify"?Uw(n.rest,t):n.mode==="checklist"?Br(e,t):_a(e,t)},capture:vp,annotate:Pp,"capture-setup":Br,devhints:qm,inbox:sb,ask:ab,"catch-up":fb,comments:kb,update:xb,reset:Tb,lint:Bd,check:iw,"style-guide":_l,review:ik,reorder:lk,restructure:ck,structure:Vb,status:hk,retire:fk,untrack:mk,terms:wk,eval:vk,reuse:Ek,genre:Yl,roadmap:ry,share:ub,auto:ky};function Lk(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 QD}from"node:child_process";import{recordAnalyzedCommit as JD,resolveActiveProfile as ZD}from"document360-engine";function e1(e){try{let t=QD("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 xi(e,t){try{let n=e1(e);if(!n)return null;let o=ZD(e,t);return JD(e,o.name,n)?n:null}catch{return null}}Gn();var Ok="Or just tell me what to write or update.";function Mk(e,t=0){if(!(e>0))return null;let n=e===1?"the page":"those pages",o=`${e} note${le(e)} from your builder ${e===1?"is":"are"} waiting on code they haven't finished.`,r=t>=e?`I've asked whether ${e===1?"it's":"they're"} done, and I'll write ${n} once the code lands.`:`I'll write ${n} once the code lands, and /catch-up asks your builder whether ${e===1?"it's":"they're"} done.`;return`${o} ${r} Nothing else is blocked.`}function t1(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}
443
+
444
+ Optional from here: ${e} of your ${t} docs campaign step${le(t)} ${e===1?"is":"are"} still open (/roadmap shows them).`}function n1(e){let{heldDrafts:t,behind:n}=e,o=t>0?"every draft that was ready is live, and readers have it":"everything you have written is live, and readers are seeing it",r=[];return t>0&&r.push(`${t} article${le(t)} ${t===1?"is":"are"} still saved as a draft, waiting on a picture.`),n>0&&r.push(`${n} code change${le(n)} ${n===1?"has":"have"} landed since your last docs check.`),[`\u2713 That\u2019s this round done \u2014 ${o}.`,...r].join(" ")}var o1="Still open, whenever you want it:";function r1(e,t){let n=t?`Press 1\u2013${e} when you want one \u2014 nothing runs on its own.`:"Run one of the commands above when you want to.";return`Nothing is armed. ${e>0?`${n} `:""}Whatever you leave, I\u2019ll raise again next time you\u2019re in.`}var s1="Screenshots are the only thing still open \u2014 a separate job, and none of it changes your text:",i1="Optional depth, when you want it:",a1="Writing",l1="Screenshots \u2014 a separate job from the writing";function c1(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 u1='\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 le(e){return e===1?"":"s"}function d1(e,t){let n=`${t} missing picture${le(t)}`;switch(e){case"spec":return`it writes the capture instructions for the ${n} \u2014 reading your code for the exact screens and buttons`;case"capture":return`it takes the ${n} in a browser and draws the callouts on straight after \u2014 your app needs to be running`;default:return`it draws the callouts on the ${n} already taken \u2014 no browser, about a second each`}}function p1(e,t){if(!e||!t)return!1;let n=o=>o.trim().replace(/\s+/g," ").toLowerCase();return n(e)===n(t)}function Qr(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 Fk(e,t){return e.length===t.length&&e.every((n,o)=>n===t[o])}function _k(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 c=0;c<n;c++){let l=r.exec(o);if(!l)break;s=o.slice(0,l.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 Jr(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 Qo="write the docs for this repo",Kl={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 h1(e,t){let n=[];if(e.sunsetEnv){let l=e.sunsetEnv,f=l.replacementProfile?`/profile ${l.replacementProfile}`:`/profile add ${l.replacement}`;n.push({key:"environment",bullet:`this repo publishes to the ${l.name} environment, which is being retired (${l.replacement} is the current one)`,lead:{kind:"cmd",cmd:f,reason:l.replacementProfile?`it switches to your ${l.replacement} profile (then /login if it asks)`:`it creates a ${l.replacement} profile and switches to it (then /login picks the project)`},picker:null,follow:null,tone:"warn"})}if(e.devhints!=="current"&&e.builderStarted){let l=e.devhintsToVersion?`v${e.devhintsToVersion}`:"a newer version",f=e.devhints==="stale"&&e.devhintsCompletedVersion?` (your builder is on v${e.devhintsCompletedVersion})`:"";n.push({key:"devhints",bullet:`dev\u2194docs protocol moved to ${l}${f} \u2014 your docs aren\u2019t blocked`,lead:{kind:"cmd",cmd:"/devhints",reason:`one paste updates your builder to ${l}`},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:Kl,follow:"Then pick the doc genre below (it sets the playbook I write with)."}),e.styleRules){let l=e.styleRules.articles;n.push({key:"styleRules",bullet:l>0?`the writing rules for these docs were never settled \u2014 and ${l} article${le(l)} ${l===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:l>0?`Which writing rules should these docs follow? (${l} article${le(l)} already written \u2014 changing this later means rewriting them)`:"Which writing rules should these docs follow? (this shapes every article I write)",lead:l>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.styleUpgrade){let l=e.styleUpgrade,f=l.articles,g=l.from.length>0?l.from.join(", "):"the built-in checks only";n.push({key:"styleUpgrade",bullet:`you\u2019re on ${g} \u2014 several of its rules are wrong for software documentation, and the guide measured on real knowledge bases is ready`,lead:null,picker:{title:`Move these docs to the Document360 style guide? (you\u2019re on ${g})`,lead:f>0?`Pick below \u2014 one keypress. Switching is instant; I then run the free text swaps over your ${f} article${le(f)} and stop before the editorial pass.`:"Pick below \u2014 one keypress, before I write anything to it.",exclusive:!0,options:[{cmd:`/style-guide use ${l.to}`,desc:f>0?`switch, then bring your ${f} article${le(f)} up to it \u2014 ${l.rules} rules, none of which can block a publish`:`Microsoft style corrected for software docs \u2014 ${l.rules} rules, none of which can block a publish`},{cmd:"/style-guide keep",desc:`stay on ${g} \u2014 I won\u2019t ask again`}]},follow:"Then decide whether these docs move to the Document360 style guide \u2014 it gets dearer to change the longer it waits."})}if(e.autoChoice){let l=e.autoChoice.articles;n.push({key:"autoMode",bullet:l>0?`you haven\u2019t said whether I should run each step myself or wait for you \u2014 with ${l} article${le(l)} here, that is the difference between a night\u2019s work and an afternoon of key presses`:"you haven\u2019t said whether I should run each step myself or wait for you to press the key each time",lead:null,picker:{title:"Should I run each step myself, or wait for you?",lead:"Pick how I should work below \u2014 one keypress, and shift+tab changes it again whenever you like.",exclusive:!0,options:e.autoChoice.presets},follow:"Then say whether I should run each step myself or wait for you \u2014 shift+tab changes it later."})}if(e.discovery&&e.discovery.status!=="confident"){let l=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)."}):l>0?n.push({key:"discovery",bullet:`product discovery is waiting on ${l} answer${le(l)} 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 l=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",f=[];e.directives>0&&f.push(`${e.directives} owner directive${le(e.directives)} waiting`);let g=e.discovery&&e.discovery.status!=="confident"?e.discovery.answersPending:0,$=g>0?` (${g} settle${g===1?"s":""} the product brief)`:"";e.pendingText&&f.push(`your builder left ${e.pendingText}${$}`),n.push({key:"catchup",bullet:f.join(`
445
+ \u2022 `),lead:{kind:"cmd",cmd:"/catch-up",reason:l},picker:null,follow:"Then /catch-up clears what\u2019s queued for the docs.",dependsOn:["discovery"]})}if(e.openComments>0){let l=e.openComments;n.push({key:"comments",bullet:`${l} reviewer comment${le(l)} 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 ${l} reviewer comment${le(l)} waiting on your articles.`})}if(e.conflicts>0){let l=e.conflicts,f=l===1?"it":"these",g=e.unreadable===l,$=g?`${l} article${le(l)} ${l===1?"is":"are"} held on Document360 in a form I can't read back`:e.unreadable>0?`${l} article${le(l)} ${l===1?"is":"are"} waiting on your decision \u2014 changed both here and on Document360, or held there in a form I can't read back`:`${l} article${le(l)} changed both here and on Document360`;n.push({key:"resolve",bullet:`${$} \u2014 /push skips ${f}, and an audit can't trust your local copy until ${l===1?"it is":"they are"} settled`,lead:{kind:"cmd",cmd:"/resolve",reason:g?"it walks each one with you \u2014 publish your copy over the portal, or skip":"it walks each one with you \u2014 keep yours, take the portal's, or skip"},picker:null,follow:g?`Then /resolve settles the ${l} article${le(l)} Document360 won't hand back (publish yours over the portal / skip).`:`Then /resolve settles the ${l} article${le(l)} waiting on your decision (keep yours / take the portal's / skip).`})}let o=e.draftAhead,r=o>0?{key:"golive",bullet:`${o} article${le(o)} ${o===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 ${o} draft${le(o)} live to your readers \u2014 it lists them and asks first`},picker:null,follow:`Then /publish takes the ${o} draft${le(o)} live \u2014 until it does, readers see the previous version.`,dependsOn:["comments"],blockedBy:["review","styleguide"]}:null,s=r!==null&&e.localAhead===0&&e.unreviewed===0&&e.styleErrors===0;if(r&&s&&n.push(r),e.portalUntracked>0){let l=e.portalUntracked,f=e.portalOnlyCategories;n.push({key:"coverage",bullet:`${l} article${le(l)} on Document360 ${l===1?"is":"are"} not in your docs folder \u2014 a plan or an audit built now would miss ${l===1?"it":"them"}`,lead:{kind:"cmd",cmd:"/pull",reason:f>0?`it imports ${l===1?"it":"them"} and creates the ${f} ${f===1?"folder":"folders"} they need`:`it imports ${l===1?"it":"them"} into your docs folder`},picker:null,follow:`Then /pull brings the ${l} Document360 article${le(l)} this repo is not tracking.`})}if(e.behind>0){let l=e.behind;n.push({key:"audit",bullet:`${l} code change${le(l)} 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 ${l} newer commit${le(l)}.`,blockedBy:["resolve"],dependsOn:["coverage"],opensRound:!0})}if(e.hasDocs&&e.pendingWrites>0){let l=e.pendingWrites;n.push({key:"write",bullet:`${l} planned article${le(l)} still unwritten`,lead:{kind:"cmd",cmd:"/write",reason:"it finishes the articles already planned"},picker:null,follow:`Then /write finishes the ${l} planned article${le(l)}.`,dependsOn:["genre","discovery","catchup","audit","coverage"]})}if(e.styleSweep){let l=e.styleSweep.pending,f=e.styleSweep.packs.length>0?e.styleSweep.packs.join(", "):"the built-in checks",g=e.styleSweep.scope?Se("/review","--fix",e.styleSweep.scope):"/review --all --fix";n.push({key:"styleSweep",bullet:`your writing rules changed to ${f} \u2014 ${l<e.styleSweep.total?`${l} of ${e.styleSweep.total}`:`${l}`} article${le(l)} ${l===1?"has":"have"} not been read against them yet`,lead:{kind:"cmd",cmd:g,reason:"it reads each one against the new rules and rewrites it",detail:[t?.scaleFor?.(g),"/style-guide sweep skip stops me raising it."].filter(Boolean).map($=>$.replace(/([^.!?…])$/,"$1.")).join(" ")},picker:null,follow:`Then ${g} reads the ${l} article${le(l)} the new rules have never been applied to.`,dependsOn:["catchup","comments","audit"]})}if(e.unreviewed>0){let l=e.unreviewed,f=Se("/review","--blocked --fix",e.unreviewedScope);n.push({key:"review",bullet:`${l} article${le(l)} not yet live ${l===1?"carries":"carry"} text no editor has read`,lead:{kind:"cmd",cmd:f,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 ${f} reviews the ${l} unreviewed article${le(l)} \u2014 nothing reaches your readers until it has.`,dependsOn:["catchup","comments"]})}if(e.styleErrors>0){let l=e.styleErrors,f=Se("/lint","--blocked --fix",e.styleErrorScope);n.push({key:"styleguide",bullet:`${l} article${le(l)} not yet live break${l===1?"s":""} house style rules that block publishing`,lead:{kind:"cmd",cmd:f,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 ${f} clears the style errors on ${l} article${le(l)} \u2014 nothing reaches your readers until it has.`,dependsOn:["catchup","comments","review"]})}let i=e.draftBlockedShots??null,a=i&&i.articles>0?{key:"annotate",bullet:`${i.articles} article${le(i.articles)} ${i.articles===1?"is":"are"} saved on Document360 and cannot go live \u2014 ${i.places} picture${le(i.places)} ${i.places===1?"is":"are"} missing, so your readers would see "[Screenshot: \u2026]" on the page`,lead:i.cmd?{kind:"cmd",cmd:i.cmd,reason:d1(i.stage,i.places)}:{kind:"prompt",text:`fix the ${i.places} bare "[Screenshot: \u2026]" line${le(i.places)} \u2014 either give each one a proper screenshot block or take the line out`,reason:"these lines belong to no screenshot, so no command can finish them"},picker:null,follow:i.cmd?`Then ${i.cmd} deals with the ${i.places} missing picture${le(i.places)}, and /push and /publish take the ${i.articles} article${le(i.articles)} live.`:`Then the ${i.places} bare "[Screenshot: \u2026]" line${le(i.places)} can be sorted out, and /push and /publish take the ${i.articles} article${le(i.articles)} live.`,...i.stage==="spec"||i.stage==="capture"?{opensRound:!0}:{}}:e.shotsToAnnotate>0?{key:"annotate",bullet:`${e.shotsToAnnotate} screenshot${le(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${le(e.shotsToAnnotate)} already taken.`}:e.shotsToRecapture>0?{key:"annotate",bullet:`${e.shotsToRecapture} screenshot${le(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${le(e.shotsToRecapture)}.`,opensRound:!0}:null,c=a!==null&&i!==null&&i.articles>0;if(a&&!c&&e.localAhead>0&&n.push(a),e.localAhead>0){let l=e.localAhead;n.push({key:"publish",bullet:`${l} article${le(l)} changed locally \u2014 ready to send to Document360`,lead:{kind:"cmd",cmd:"/push",reason:`it saves your ${l} local edit${le(l)} to Document360 as drafts`},picker:null,follow:`Then /push saves your ${l} local edit${le(l)} to Document360.`,dependsOn:["discovery","comments","audit","annotate"],blockedBy:["review","styleguide"]})}if(r&&!s&&n.push(r),a&&(c||e.localAhead===0)&&n.push(a),e.hasDocs&&e.roadmap?.next){let l=e.roadmap,f=l.next,g=f.run?t?.scaleFor?.(f.run)??null:null,$=f.run?g:_k(f.body),T=f.run?g??void 0:_k(f.body,340,2)??void 0,A=`docs campaign: ${l.done} of ${l.total} step${le(l.total)} done`,S=!!f.run&&p1(f.run,e.lastCommand);n.push(S?{key:"roadmap",bullet:`${A} \u2014 \u201C${f.title}\u201D is waiting on you
446
+ \u2022 You just ran ${f.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:`${A} \u2014 next: ${f.title}${$?`
447
+ \u2022 ${$}`:""}`,lead:f.run?{kind:"cmd",cmd:f.run,reason:"it\u2019s the next step of your docs campaign",...T?{detail:T}:{}}:{kind:"prompt",text:f.title,reason:"it\u2019s the next step of your docs campaign",...T?{detail:T}:{}},picker:null,follow:`Then the campaign continues: ${f.title} (/roadmap shows all ${l.total} steps).`,dependsOn:["genre","discovery","audit"],rowBullet:`${A} \u2014 this is next${$?`
448
+ \u2022 ${$}`:""}`,opensRound:!0})}if(e.handoff){let l=Math.max(e.handoff.unpushed,e.handoff.uncommitted>0?1:0),f=e.handoff.unpushed;l>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(`
449
+ `),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}):f>0&&n.push({key:"share",bullet:`\u26A0 ${f} docs change set${le(f)} 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 l=e.uncommittedDocs;n.push({key:"commit",bullet:`\u26A0 ${l} uncommitted change${le(l)} under .d360-writer/ \u2014 tell your coding agent: "commit d360-writer's work"`,lead:null,picker:null,follow:null})}return n}function Uk(e){return e.find(t=>t.lead||t.picker)??null}function f1(e){return e.kind==="cmd"?e.cmd:e.kind==="prompt"?`\u201C${e.text}\u201D`:""}function Zr(e){return e.kind==="cmd"?e.cmd:e.kind==="prompt"?e.text:null}function m1(e){return Zr(e)??""}function g1(e,t,n){let o=a=>(a??[]).map(c=>t.get(c)).filter(c=>c!==void 0&&c<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 Ri(e,t,n,o=null,r,s=0,i=0,a=0,c=!1){if(r&&r.length>0){let E=r.filter(Ma),j=r.filter(fe=>!Ma(fe)),W=[...j,...E],Y=(fe,Re)=>` ${Re+1}. ${fe.title}${fe.run?` \xB7 ${fe.run}`:""}`,B;return E.length===0||j.length===0?B=[e,...W.map(Y)].join(`
450
+ `):B=[e,"",` ${a1}`,...j.map((fe,Re)=>Y(fe,Re)),"",` ${l1}`,...E.map((fe,Re)=>Y(fe,j.length+Re))].join(`
451
+ `),{note:[...o?[o]:[],B,c1(W.length,n),Ok].join(`
452
+
453
+ `),menu:W.map(fe=>fe.run??fe.title)}}let l=c?null:Uk(t),f=l?.picker?[]:t.filter(E=>E.lead),g=c||f.length>=2?f:[],$=new Map(g.map((E,j)=>[E.key,j+1])),T=[];l?.lead?T.push(Jr(l.lead)):l?.picker&&T.push(l.picker.lead);for(let E of t.filter(j=>j!==l&&!j.lead).slice(0,2))E.follow&&T.push(E.follow);c?T.push(r1(g.length,n)):g.length>=2&&n&&T.push(`Press 1\u2013${g.length} to pick a different one \u2014 the number fills the box, enter runs it.`);let A=T.join(" "),S=t.filter(E=>E.bullet).map(E=>{let j=$.get(E.key),[W="",...Y]=(j&&E.lead?.kind==="prompt"&&E.rowBullet?E.rowBullet:E.bullet).split(`
454
+ \u2022 `),B=E===l&&E.lead?.kind!=="answer"&&E.lead?.detail?[]:Y;if(j&&E.lead){let Re=W.replace(/^→\s+/,"");return[` ${j}. ${f1(E.lead)} \u2014 ${Re}${g1(E,$,j)}`,...B.map(ge=>` ${ge}`)].join(`
455
+ `)}let ue=E.lead?.kind==="cmd"?E.lead.cmd:null;return` \u2022 ${[W,...B].join(`
456
+ \u2022 `)}${ue&&!A.includes(ue)?` \u2014 ${ue}`:""}`}),C=o?[o,[e,...S].join(`
457
457
  `)]:[[e,...S].join(`
458
- `)];if(T.length&&C.push(T.join(" ")),s>0){let E=s;C.push(`${E} question${de(E)} you asked your developers ${E===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.`)}let x=Ak(i,a);return x&&C.push(x),C.push(Pk),{note:C.join(`
459
-
460
- `),menu:g.map(E=>QD(E.lead))}}function $i(e,t){let n=t?.pickable===!0,o=x=>t?.header?`${t.header}
461
-
462
- ${x}`:x;if(!e.ready)return{kind:"idle"};if(e.pendingAnswer)return{kind:"recommend",rec:{note:null,settled:null,restKind: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:[],heldHints:e.heldHints}};let r=zD(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(ja)&&e.roadmap.total-e.roadmap.done===i.length,c=s?_D(e.roadmap.total-e.roadmap.done,e.roadmap.total,{listed:i.length>0,onlyScreenshots:a}):null,l=r.filter(x=>x.lead||x.picker),f=!s&&l.length>0&&l.every(x=>x.opensRound===!0),g=f?MD({heldDrafts:e.draftBlockedShots?.articles??0,behind:e.behind}):c,k=s?"complete":f?"delivered":null;if(!e.hasDocs){let x=Nk(r);if(x&&(x.lead?.kind==="cmd"||x.picker)){let E=ki(t?.header??"\u{1F4ED} No docs yet for this repo \u2014 here\u2019s where things stand:",r,n,null,void 0,e.outboundQuestions,e.heldHints,e.heldHintsAsked);return{kind:"recommend",rec:{note:E.note,settled:null,restKind:null,tone:x.tone??"info",lead:x.lead,picker:x.picker,menu:E.menu,heldHints:e.heldHints}}}return{kind:"recommend",rec:{note:o(VD),settled:null,restKind:null,tone:"info",lead:{kind:"prompt",text:zo,reason:"I\u2019ll read the code and draft a structure"},picker:null,menu:[],heldHints:e.heldHints}}}if(r.length===0){let x=e.roadmap&&!e.roadmap.next?` Docs campaign complete \u2014 all ${e.roadmap.total} step${de(e.roadmap.total)} done (/roadmap).`:"",E=Ak(e.heldHints,e.heldHintsAsked);return{kind:"recommend",rec:{note:o(`Welcome back. Your ${e.tracked} tracked article${de(e.tracked)} for \u201C${e.profileName}\u201D are all in sync \u2014 /audit re-checks the code, /pull brings down portal edits.${x}`+(E?`
463
-
464
- ${E}`:"")),settled:null,restKind:null,tone:"info",lead:null,picker:null,menu:[],heldHints:e.heldHints}}}let T=l,A=T[0]??null;if(!A){let x=ki(t?.header??"Welcome back \u2014 where your docs stand:",r,n,null,void 0,e.outboundQuestions,e.heldHints,e.heldHintsAsked);return{kind:"recommend",rec:{note:x.note,settled:null,restKind:null,tone:"info",lead:null,picker:null,menu:x.menu,heldHints:e.heldHints}}}if((A.key==="audit"||T[1]?.key==="audit")&&e.behind>0&&e.autoAudit&&e.allowAutoAudit)return{kind:"autoAudit",note:o(`\u{1F4CB} ${e.behind} code change${de(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`)};if(s){let x=ki(a?WD:BD,r,n,g,i,e.outboundQuestions,e.heldHints,e.heldHintsAsked);return{kind:"recommend",rec:{note:x.note,settled:g,restKind:k,tone:"info",lead:null,picker:null,menu:x.menu,heldHints:e.heldHints}}}if(f){let x=ki(FD,r,n,g,void 0,e.outboundQuestions,e.heldHints,e.heldHintsAsked,!0);return{kind:"recommend",rec:{note:x.note,settled:g,restKind:k,tone:"info",lead:null,picker:null,menu:x.menu,heldHints:e.heldHints}}}let C=ki(t?.header??"Welcome back \u2014 where your docs stand:",r,n,g,void 0,e.outboundQuestions,e.heldHints,e.heldHintsAsked);return{kind:"recommend",rec:{note:C.note,settled:g,restKind:k,tone:A.tone??"info",lead:A.lead,picker:A.picker,menu:C.menu,heldHints:e.heldHints}}}import{existsSync as Hl,readdirSync as Hh}from"node:fs";import{spawnSync as ZD}from"node:child_process";import{join as Gl}from"node:path";import{readProjectConfig as Bh,resolveActiveProfile as Ok,loadTokens as e1,isExpired as t1,loadProfileMap as _k,localAheadPaths as n1,loadKnownConflicts as o1,listUnpullable as r1,draftPendingPaths as s1,loadOpenCommentCount as i1,readDocsPlan as a1,devHintsGuidePath as l1,DEFAULT_DOCS_DIR as ql,roadmapProgress as c1,listRoadmap as Dk,readProductBriefState as u1,readDiscoveryQueue as d1,reconcileCommitRequest as p1,reconcileTestidRequest as h1,snapshotHandoff as f1,shareExplainedPath as m1,unannotatedShotIds as g1,shotsNeedingRecapture as y1,resolveOutputDir as w1,DEFAULT_OUTPUT_DIR as b1,WRITER_DIRNAME as Uh,styleGuideSettled as k1,styleGuideUpgradeOffered as $1,styleSweepOutstanding as v1,styleSweepSeedNeeded as x1,recordStyleSwitch as R1,lintArticles as S1,DEFAULT_PACK as C1,autoModeSettled as P1,autoBudgetUsd as T1,listAvailablePacks as jk,listArticleFiles as Wh,placeholderFindings as A1,placeholderRemedy as E1}from"document360-engine";Hn();var Ik=new Set,N1=5;function Lk(e){try{return Hh(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function Gh(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>Lk(Gl(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&Lk(Gl(e,o)))}function qh(e,t){try{let n=Bh(e);if(!n)return!1;let o=Ok(e,t),r=_k(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=Gl(e,(n.docsDir??ql).replace(/\/+$/,""));return!!(Hl(s)&&Hh(s).length>0||Hl(l1(e)))}catch{return!1}}function D1(e){let t=[`:(exclude)${Uh}`],n=(e.docsDir??ql).replace(/\\/g,"/").replace(/\/+$/,"");return n&&!n.startsWith(`${Uh}/`)&&n!==Uh&&t.push(`:(exclude)${n}`),t}function j1(e,t,n){try{let o=ZD("git",["rev-list","--count",`${t}..HEAD`,"--",".",...D1(n)],{cwd:e,encoding:"utf8",timeout:1200});return o.status===0&&parseInt((o.stdout||"").trim(),10)||0}catch{return 0}}function vi(e,t,n){try{let o=Bh(e);if(!o)return null;let r=Ok(e,t),s=e1(r.name,r.project.projectId),i=!!s&&(!t1(s)||!!s.refreshToken),a=qh(e,t)||!Gh(e,o.authoritativeSourceFiles),c=_k(e,r.name),l=c?Object.keys(c.articles).length:0,f=Gl(e,(o.docsDir??ql).replace(/\/+$/,"")),g=!1;try{g=Hl(f)&&Hh(f).length>0}catch{}let k=c?.lastAnalyzedCommit?j1(e,c.lastAnalyzedCommit,o):0,T=0;try{let fe=(o.docsDir??ql).replace(/\/+$/,""),He=a1(e,fe);He.length>0&&(T=Kn(e,fe,He.map(hn=>hn.path)).length)}catch{}let A=Jt(e),S=Gr({...A,directives:0}),C=n1(e,t),x=new Set(o1(e,r.name)),E=new Set(r1(e,r.name).map(fe=>fe.path)),I=C.filter(fe=>x.has(fe)||E.has(fe)),W=I.length,V=C.length-W,B=new Set(C),ae=s1(e,t).filter(fe=>!B.has(fe)),me=A1(e,ae),Re=new Set(me.map(fe=>fe.path)),Ie=ae.filter(fe=>!Re.has(fe)).length,ge=null;try{ge=E1(e,me)}catch{}let we=[...C.filter(fe=>!x.has(fe)),...ae],Z=Ws(e,we),Ee=Z.length,_e=Dt(Z),Ge=null;try{if(!k1(o.styleGuide)){let fe=jk(e).filter(He=>He.name.toLowerCase()!=="humanise");Ge={articles:Wh(e).length,presets:[{cmd:"/style-guide keep",desc:"the built-in rules only \u2014 correctness and anti-slop checks (nothing changes)"},...fe.map(He=>({cmd:`/style-guide use ${He.name.toLowerCase()}`,desc:`${He.name} style guide \u2014 ${He.rules.length} more rules`}))]}}}catch{}let In=null;try{if($1(o.styleGuide)){let He=jk(e).find(hn=>hn.name.toLowerCase()===C1);He&&(In={to:He.name.toLowerCase(),rules:He.rules.length,from:(o.styleGuide?.packs??[]).map(hn=>hn.trim().toLowerCase()).filter(Boolean),articles:Wh(e).length})}}catch{}let Ce=null;try{if(x1(e,o?.styleGuide?.packs,o?.styleGuide?.decidedAt)&&!Ik.has(e)){Ik.add(e);let He=S1({cwd:e}).findings;R1(e,{packs:o?.styleGuide?.packs??[],from:[],articlesWithFindings:[...new Set(He.map(hn=>hn.path))]})}let fe=v1(e);fe&&(Ce={pending:fe.pending,total:fe.total,packs:fe.packs,...Dt(fe.paths)?{scope:Dt(fe.paths)}:{}})}catch{}let Ae=null;try{P1(o)||(Ae={articles:Wh(e).length,presets:[{cmd:"/auto off",desc:"manual \u2014 I suggest the next step and wait for you to run it"},{cmd:"/auto on",desc:`auto \u2014 I run the next step myself, all the way to live (up to ${Ye(T1(o))} a run)`}]})}catch{}let Ze=0,nn;try{let fe=cy(e,we);Ze=fe.length,nn=Dt(fe)}catch{}let St=0,co=0;try{let fe=w1(e,Bh(e)?.outputDir??b1);St=g1(fe).length,co=y1(fe).length}catch{}let er=i1(e,r.name),tr=zt(e),us=c1(e),kc=us?{...us,open:Dk(e).filter(fe=>fe.status==="open").slice(0,N1).map(fe=>({title:fe.title,...fe.run?{run:fe.run}:{},...fe.stage?{stage:fe.stage}:{}}))}:null,Ft=f1(e,o),Ut=p1(e,new Date().toISOString(),{supersededByHandoff:Ft!==null});h1(e,new Date().toISOString());let Ln=Un(e,t),On=Ln?{name:Ln.name,replacement:Ln.replacement,replacementProfile:Ln.replacementProfile}:null,pn=u1(e),uo=d1(e),on=pn?{status:pn.status,openQuestions:uo.openQuestions,answersPending:uo.answersPending}:null;return!on&&g&&Dk(e).some(He=>He.status==="open"&&(He.run??"").trim()==="/discover")&&(on={status:"pending",openQuestions:0,answersPending:0}),{ready:i&&a&&!n.claudeMissing,hasDocs:g,tracked:l,pendingText:S,directives:A.directives,behind:k,pendingWrites:T,localAhead:V,unreviewed:Ee,unreviewedScope:_e,styleErrors:Ze,shotsToAnnotate:St,shotsToRecapture:co,styleErrorScope:nn,draftAhead:Ie,draftBlockedShots:ge,conflicts:W,unreadable:I.filter(fe=>E.has(fe)).length,openComments:er,outboundQuestions:ci(e),heldHints:A.held,heldHintsAsked:A.heldAsked,autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:tr.status,devhintsCompletedVersion:tr.completedVersion,devhintsToVersion:Me,builderStarted:Sn(e),genreUnknown:n.genreUnknown,pendingAnswer:n.pendingAnswer??null,lastCommand:n.lastCommand??null,styleRules:Ge,styleUpgrade:In,styleSweep:Ce,autoChoice:Ae,roadmap:kc,discovery:on,uncommittedDocs:Ut.dirty.length,handoff:Ft,shareExplained:Hl(m1(e)),sunsetEnv:On}}catch{return null}}oe();import{existsSync as O1,readFileSync as _1}from"node:fs";import{isAbsolute as M1,join as F1}from"node:path";import{DEFAULT_DOCS_DIR as U1,findPathByArticleId as W1,isArticleDocPath as B1,loadProfileMap as H1,readProjectConfig as G1,resolveActiveProfile as q1}from"document360-engine";function I1(){return process.platform==="win32"||process.platform==="darwin"}var L1=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Vl(e,t){let n=e.replace(/\\/g,"/"),o=`${L1(t)}/`,[r,s]=I1()?[n.toLowerCase(),o.toLowerCase()]:[n,o];return r.startsWith(s)?n.slice(o.length):null}var Fk=70;function V1(e,t){return{docsRoot:()=>(G1(e)?.docsDir??U1).replace(/\\/g,"/").replace(/\/+$/,""),read:n=>{try{let o=M1(n)?n:F1(e,n);return O1(o)?_1(o,"utf8"):null}catch{return null}},pathForArticleId:n=>{try{let o=H1(e,q1(e,t).name);return o?W1(o,n):null}catch{return null}}}}var Xo=(e,t=Fk)=>{let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"};function xi(e){if(!e)return null;let t=!1;for(let n of e.split(`
465
- `)){let o=n.trimEnd();if(/^\s*(```|~~~)/.test(o)){t=!t;continue}if(t)continue;let r=/^#\s+(\S.*)$/.exec(o);if(r)return Xo(r[1])}return null}var K1=new Set(["a","an","and","as","at","but","by","for","in","of","on","or","the","to","vs","with"]),Y1=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 Uk(e,t,n){let o=e.toLowerCase();return Y1.has(o)?e.toUpperCase():!t&&K1.has(o)?o:!t&&!n?e:e.charAt(0).toUpperCase()+e.slice(1)}var Wk=e=>e.replace(/^\d+[-_.]/,"").split(/[-_]/).filter(Boolean);function z1(e){let t=Wk(e);return t.length===0?e:t.map((n,o)=>Uk(n,o===0,!0)).join(" ")}function Bk(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:z1(n[n.length-2])}function Hk(e){let t=e.replace(/\\/g,"/").split("/").pop()??e,n=Wk(t.replace(/\.(md|markdown)$/i,""));return n.length===0?t:n.map((o,r)=>Uk(o,r===0,!1)).join(" ")}var X1=46;function Q1(e,t){let n=0,o=!1,r=null;for(let s of e.split(`
466
- `)){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=Xo(a[2],Fk))}n+=s.length+1}return r}function Mk(e){for(let t of e.split(`
467
- `)){let n=t.replace(/^\s*(#{1,6}\s+|[-*+]\s+|>\s+|\d+[.)]\s+)/,"").replace(/^\s*\|/,"").trim();if(n)return Xo(n,X1)}return null}var Mt=e=>typeof e=="string"&&e?e:null,J1=e=>typeof e=="string"&&e.length>=8?`id ${e.slice(0,8)}\u2026`:null;function Z1(e,t){return Vl(e,t)??e.replace(/\\/g,"/")}function ej(e,t){let n=Lt(e,t,200);return n?`+${n.added} \u2212${n.removed}`:"no change"}var tj=new Set(["Edit","MultiEdit","Write"]);function nj(e,t,n,o){if(!tj.has(e))return null;let r=Mt(t.file_path);if(!r)return null;let s=Z1(r,n),i=o.docsRoot();if(!(s===i||s.startsWith(`${i}/`)))return null;let a=s.slice(i.length+1);if(!a||!B1(a))return null;let c=Bk(a),l=o.read(s),f=W=>xi(W)??xi(l)??Hk(a);if(e==="Write"){let W=Mt(t.content)??"",V=f(W);if(l===null){let B=W.replace(/\n$/,"").split(`
468
- `).length;return{verb:"Draft",title:V,category:c,note:`new, ${B} lines`,articleKey:s}}return{verb:"Rewrite",title:V,category:c,note:ej(l,W),articleKey:s}}let g=Array.isArray(t.edits)?t.edits.map(W=>({from:Mt(W.old_string)??"",to:Mt(W.new_string)??""})):[{from:Mt(t.old_string)??"",to:Mt(t.new_string)??""}],k=g.reduce((W,V)=>{let B=Lt(V.from,V.to,200);return B?{added:W.added+B.added,removed:W.removed+B.removed}:W},{added:0,removed:0}),T=k.added===0&&k.removed===0?"no change":`+${k.added} \u2212${k.removed}`,A=g[0],S=A&&l?Q1(l,l.indexOf(A.from)):null,C=A?Mk(A.to)??Mk(A.from):null,x=g.length>1?` +${g.length-1} more`:"",E=C?`\u201C${C}\u201D${x}`:x.trim()||null,I=S?{title:`\u21B3 ${S}`,category:E,note:T}:E?{title:`\u21B3 ${E}`,category:null,note:T}:null;return{verb:"Update",title:f(g.map(W=>W.to).join(`
469
- `)),category:c,note:T,articleKey:s,...I?{repeat:I}:{}}}function oj(e,t,n){let o=()=>{let r=Mt(t.article_id),s=r?n.pathForArticleId(r):null;return(s?xi(n.read(s)):null)??(s?Hk(s):J1(r)??"article")};switch(e){case"d360_create_article":{let r=Mt(t.title);return r?{verb:"Create",title:Xo(r),category:Bk(t.local_path),note:"Document360 draft"}:null}case"d360_update_article":return{verb:"Update",title:Mt(t.title)?Xo(Mt(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=Mt(t.name);return r?{verb:"Create",title:Xo(r),category:null,note:"Document360 category"}:null}case"d360_upload_drive_file":{let r=Mt(t.file_path);if(!r)return null;let s=r.replace(/\\/g,"/").split("/").pop()??r;return{verb:"Upload",title:Xo(s),category:null,note:"Document360 Drive",keepResult:!0}}default:return null}}function Kl(e,t,n,o,r=V1(n,o)){try{let s="mcp__document360__";return e.startsWith(s)?oj(e.slice(s.length),t,r):nj(e,t,n,r)}catch{return null}}var rj={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"},qk=160,Vh=200,Vk=40;function io(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:sj(n)?"\u2026"+n.slice(n.length-(t-1)):n.slice(0,t-1)+"\u2026"}function sj(e){return!e.includes(" ")&&/[/\\]/.test(e)}function Gk(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}: ${io(typeof r=="string"?r:JSON.stringify(r),Vk)}`);return t.length>4&&n.push("\u2026"),io(n.join(", "),qk)}var ij=new Set(["file_path","notebook_path"]);function aj(e,t){return t?Vl(e.replace(/\\/g,"/").replace(/\/+$/,""),t)??e:e}var Yl=e=>typeof e=="string"&&e?e:null;function lj(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});return e==="d360_sync_status"?n("Check sync status",null):null}function zl(e,t,n){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,s="",...i]=e.split("__"),a=i.join("__");if(s==="document360"){let f=lj(a,t);if(f)return f}let c=a.replace(/^d360_/,"").replace(/_/g," ");return{title:`${s==="document360"?"Document360":s.charAt(0).toUpperCase()+s.slice(1)}: ${c}`,sep:" ",arg:Gk(t)}}let o=rj[e],r=o?t[o]:void 0;if(typeof r=="string"&&r){let s=o&&ij.has(o)?aj(r,n):r;return{title:e,sep:"",arg:io(s,qk)}}return{title:e,sep:"",arg:Gk(t)}}function cj(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 uj(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(cj).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>io(r,Vh))]}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}: ${io(String(r),Vk)}`);return n.length>0?[io(n.join(" \xB7 "),Vh)]:null}return null}function dj(e){let t=Yl(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function pj(e,t,n){switch(e){case"d360_create_article":{let o=dj(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=Yl(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 ${io(o[0],120)}`:""}`]}case"d360_create_variable":{let o=Yl(t?.name);return[`\u2713 variable created${o?` \xB7 :variable[]{name="${o}"}`:""}`]}case"d360_create_snippet":{let o=Yl(t?.name);return[`\u2713 snippet created${o?` \xB7 ::snippet{name="${o}"}`:""}`]}default:return null}}var Kk=new Set(["Edit","Write","MultiEdit","NotebookEdit"]);function hj(e){return e.replace(/^\s*\d+\t/,"")}function fj(e,t){if(Kk.has(e))return[];let n=t.split(`
470
- `);if(e==="Read"){let o=n.length,r=xi(n.map(hj).join(`
471
- `));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 Xl(e,t=4,n,o){let r=e.replace(/\r\n/g,`
472
- `).trimEnd();if(n&&Kk.has(n))return{lines:[],hidden:0};if(!r)return{lines:["(no output)"],hidden:0};if(n&&!n.startsWith("mcp__")){let i=fj(n,r);if(i)return{lines:i,hidden:0}}if(n?.startsWith("mcp__document360__")){let i=pj(n.slice(18),o,r);if(i)return{lines:i,hidden:0}}let s=uj(r)??r.split(`
473
- `);return{lines:s.slice(0,t).map(i=>io(i,Vh)),hidden:Math.max(0,s.length-t)}}function Ql(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function Jl(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 Yk(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 Zl(e){return Yk(e,"url")}function ec(e){return Yk(e,"preview_url")}function tc(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 n$=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/,Yh=null;function Jk(){return Yh===null&&(Yh=Cj().verboseTranscript===!0),Yh}function Uj(e,t,n,o){if(n$.test(e))try{let r=t$(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,i=Jl(t,n),a=tc(t,n),c=a?`${a} \u2014 `:"",l=Zl(n);e.endsWith("publish_article")&&l&&console.log(ee(` \u2B95 ${c}Live: ${l}`));let f=ec(n);f?console.log(ee(` \u2B95 ${c}Preview: ${f}`)):i&&s&&console.log(ee(` \u2B95 ${c}Preview: ${Ql(r.connection.portalUrl,s,i,r.project.languageCode??"en")}`))}catch{}}async function o$(e=process.cwd(),t="auto",n,o){let r=gj(t);r.kind==="none"&&(console.error(""),console.error(L("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${ee("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${ee('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${ee("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${ee("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),Wj(e,n);let s=yj(t),i=wj(s);console.log(i?K(` ${zk(s)}`):d(` ${zk(s)}`)),i?console.log(d(` ${i}`)):r.kind==="subscription"&&!r.stored&&console.log(d(" No sign-in found on this machine \u2014 trying your Claude session anyway.")),console.log("");let a=!1,c=Kh({cwd:e,profileName:n,allowProdWrites:a}),l={uuid:null,firstPrompt:null,titleFired:!1},f=mj({input:process.stdin,output:process.stdout}),g=[],k=null,T=!1;f.on("line",C=>{if(k){let x=k;k=null,x(C)}else g.push(C)}),f.on("close",()=>{if(T=!0,k){let C=k;k=null,C(null)}});function A(){return g.length>0?Promise.resolve(g.shift()):T?Promise.resolve(null):(process.stdout.write(ee("> ")),new Promise(C=>{k=C}))}let S={cwd:e,version:o,profileName:n,allowProdWrites:()=>a,restartAgent:()=>{c.close(),c=Kh({cwd:e,profileName:n,allowProdWrites:a}),l={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>l.uuid,setPendingName:C=>{l.pendingName=C},setModel:async C=>c.setModel(C),withPausedInput:async C=>{f.pause();try{return await C()}finally{f.resume()}}};try{for(;;){let C=await A();if(C===null)break;let x=C.trim();if(x){if(x.startsWith("/")){let E=Ck(x);if(!E)continue;let I=Sk[E.name];if(!I){console.log(L(`Unknown command: /${E.name}`)),console.log(d("Type /help for the list."));continue}let W=await I(E.args,S);if(W.kind==="exit")break;if(W.kind==="clear"){S.restartAgent();continue}if(W.kind==="allow-prod"){a=!0,S.restartAgent(),console.log(X("\u2713 Production writes authorized for this session.")),console.log("");continue}if(W.kind==="resume"){c.close(),c=Kh({cwd:e,resume:W.uuid,profileName:n,allowProdWrites:a});let V=bj(W.uuid);l={uuid:W.uuid,firstPrompt:V?.firstPrompt??null,titleFired:!0},e$(W.uuid),console.log(X(`\u2713 Resumed "${W.name}"`)),console.log("");continue}if(W.kind==="audit-blocked"){console.log(K(W.note)),console.log(d(` Run: ${W.lead.cmd} \u2014 ${W.lead.reason}.`)),console.log("");continue}if(W.kind==="forward-to-agent"){l.firstPrompt||(l.firstPrompt=W.display??W.prompt);let V=W.display??"",B=V.trim().split(/\s+/),ae=zy(V),me=ae?Lj(e,Xy(V)):[],Re=ae==="review"?Qk(e):null,Ie=B[0]==="/screenshot"&&(B[1]==="verify"||B[1]==="review"),ge=Ie?B[2]&&!B[2].startsWith("--")?[B[2]]:ri(Ue(e)):[],we=B[0]==="/catch-up"&&!ae,Z=we?Qk(e):null,Ee=we?Jt(e):null,_e=we?di(e).hold:!1,Ge=W.prompt;if(V.startsWith("/"))try{let Ce=La(e,V);Ce&&(Ge=`${Ge}
474
-
475
- ${Ce}`)}catch{}let In=await zh(c,Ge,r,l,e,n);if(ae){let Ce=ae==="review"?Vo(e,me,Re,n):null,Ae=Ce?Ce.earned:me;if(Ae.length>0)try{Ij(e,Ae,ft(ae))}catch{}let Ze=Ce?Kr(e,Ce.unadopted,{lead:Ce.changed.length===0}):null;if(Ze)for(let nn of Ze.lines)console.log(d(nn))}if(Z){In.produced&&Fj(e);let Ce=Go(e,Z,"",B[0]);if(Ce.cta)console.log(d(Ce.cta.text));else if(Ee){let Ae=kl({queued:Ee,hold:_e});Ae.note&&console.log(Ae.tone==="warn"?K(Ae.note):d(Ae.note)),Ae.lead&&console.log(d(` Run ${Ae.lead.cmd} \u2014 ${Ae.lead.reason}.`))}}if(B[0]==="/reuse"&&B[1]==="audit"){let Ce=B.slice(2).find(Ae=>!Ae.startsWith("--"));for(let Ae of Ul(e,Ce))console.log(Ae)}if(B[0]==="/audit"&&!B.includes("--auto")&&bi(e,n),Ie&&ge.length>0)try{for(let Ce of Wr(e,ge))console.log(Ce)}catch{}if(B[0]==="/push"){let Ce=await Us(e,n);Ce&&console.log(d(Ce))}if((B[0]==="/catch-up"||B[0]==="/document")&&(B.includes("--push")||B.includes("--publish")))try{let Ce=await Mj({cwd:e,profileName:n}),{clean:Ae,conflicts:Ze}=_o(Ce.entries,Mo(e,n));Ae.length===0?console.log(d("Nothing new to push \u2014 everything is already up to date on Document360.")):await Qt(S,Ae.map(nn=>nn.path),Ze.length,{skipReview:B.includes(jt)})}catch(Ce){console.log(K(`Couldn't check what to push (${Ce.message}) \u2014 your drafts are saved; run /push when ready.`))}}else W.kind==="continue"&&W.ownNext||Bj(e,n);continue}if(Ej(x)){let E=Nj(x);if(E){try{Dj(e,{title:E,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}l.firstPrompt||(l.firstPrompt=x),await zh(c,`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${E}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${E}" and the article path(s) you wrote.`,r,l,e,n);continue}}l.firstPrompt||(l.firstPrompt=x),await zh(c,x,r,l,e,n)}}}finally{c.close(),f.close()}}function Wj(e,t){console.log(""),console.log(Ts("document360-writer")),console.log(d(` cwd: ${e}`));let n=Rj(e);if(console.log(d(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(Hj(e,t)),!Sj(e))console.log(K(" 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(ua(e),!Sn(e))for(let r of da(e))console.log(K(` ${r}`))}catch{}try{let r=Pj(e);r.persisted&&r.appType?console.log(d(` \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=jj(e);for(let s of ia(r.applied))console.log(K(` ${s}`));if(r.reopenedForRedaction)for(let s of aa(r.reopenedForRedaction).split(/\r?\n/))console.log(K(` ${s}`))}catch{}try{let r=vi(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:o}),s=r?$i(r,{pickable:!1,scaleFor:i=>Zt(e,i)}):null;if(s?.kind==="recommend"&&s.rec.note){let i=s.rec.tone==="warn"?K:d;for(let a of il(s.rec.note).split(`
476
- `))console.log(i(` ${a}`));s.rec.picker&&console.log(ee(` Pick one: ${s.rec.picker.options.map(a=>a.cmd).join(" \xB7 ")}`))}}catch{}}console.log(d(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}var Zk=!1;function Bj(e,t){try{let n=vi(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:!1}),o=n?$i(n,{scaleFor:r=>Zt(e,r)}):null;if(o?.kind!=="recommend")return;if(o.rec.settled&&!Zk){Zk=!0;for(let r of il(o.rec.settled).split(`
477
- `))console.log(X(` ${r}`))}else o.rec.settled&&!o.rec.lead&&console.log(d(" Nothing is waiting. /roadmap lists the optional campaign steps."));o.rec.lead&&console.log(d(` Next: ${Zr(o.rec.lead)}`))}catch{}}function Hj(e,t){try{let n=t$(e,t),o=n.production?K(" \u26A0 PRODUCTION"):"",r=Aj(n.name,n.project.projectId);if(!r)return d(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...Xk(r.idToken)??{},...Xk(r.accessToken)??{}},i=s.email??s.preferred_username??"signed in";return Tj(r)&&!r.refreshToken?K(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):d(` Document360: ${i} \xB7 profile "${n.name}"${o}`)}catch(n){return d(` Document360: ${n.message.split(".")[0]}`)}}function Gj(){console.error(""),console.error(`Sign in with your Claude subscription: run ${ee("claude")} once, then retry.`),console.error(` (No Claude Code? ${ee("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${ee("https://console.anthropic.com/settings/keys")}`)}function qj(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;vj({uuid:t,name:r??$j(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function Vj(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||xj(o,t).then(r=>{r&&kj(n,r)}).catch(()=>{})}async function zh(e,t,n,o,r,s){let i=new Map,a=!1,c=!1;for await(let l of e.send(t))l.type==="tool"&&(c=!0),l.type==="text"&&l.delta.trim()&&(c=!0),l.type==="tool"&&n$.test(l.name)&&(a=!0),Kj(l,o,r,n,i,s);if(a)try{let l=_j(await Oj({cwd:r,profileName:s}));l&&console.log(l.startsWith("\u26A0")?K(l):l)}catch{}return{produced:c}}function Kj(e,t,n,o,r,s){switch(e.type){case"session":t.uuid||qj(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let i=Jk()?null:Kl(e.name,e.input,n,s);if(i){process.stdout.write(`
478
-
479
- `);let c=[i.category,i.note].filter(f=>!!f).map(f=>Te(` \xB7 ${f}`)),l=i.loud?Te(" \xB7 ")+Qe(K(i.loud)):"";console.log(`${X("\u25CF")} ${ee(Qe(xd(i.verb)))}${Qe(i.title)}${c.join("")}${l}`),r.set(e.id,{name:e.name,input:e.input,doc:!0,keepResult:i.keepResult});break}let a=zl(e.name,e.input,process.cwd());a&&(process.stdout.write(`
480
-
481
- `),console.log(`${Te("\u25CF")} ${a.title}${a.arg!==null?Te(`${a.sep}(${a.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let i=Lt(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!i)break;let a=c=>c===1?"":"s";console.log(Te(` \u23BF Added ${i.added} line${a(i.added)}, removed ${i.removed} line${a(i.removed)}`));for(let c of i.lines)console.log(c);i.hidden>0&&console.log(d(` \u2026 +${i.hidden} more diff lines`));break}case"tool_result":{let i=r.get(e.id);if(!i)break;r.delete(e.id);let c=i.doc&&!i.keepResult&&!e.isError?{lines:[],hidden:0}:Xl(e.output,4,e.isError||Jk()?void 0:i.name,i.input),l=e.isError?L:Te;c.lines.forEach((f,g)=>console.log(l((g===0?" \u23BF ":" ")+f))),c.hidden>0&&console.log(d(` \u2026 +${c.hidden} lines`)),e.isError||Uj(i.name,i.input,e.output,n);break}case"result":{process.stdout.write(`
482
- `);let i=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(d(` (${Xs(i)}\u2192${Xs(e.outputTokens)} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(e$(t.uuid),t.titleFired||Vj(t,n));break}case"error":console.error(""),e.kind==="limit"?console.log(K(`\u23F3 ${e.message}`)):console.error(L(`agent error: ${e.message}`)),e.note&&console.log(d(` ${e.note}`)),o.kind==="subscription"&&e.kind==="auth"&&Gj();break}}import{render as aO}from"ink";import{resolveAuth as lO}from"document360-engine";import{useCallback as re,useEffect as it,useMemo as hc,useRef as ie,useState as ce}from"react";import{Box as je,Text as Y,useApp as NI,useInput as DI,useStdout as jI}from"ink";import{existsSync as rs,readFileSync as fc,readdirSync as II,writeFileSync as ov,mkdirSync as LI}from"node:fs";import{basename as Ci,dirname as OI,isAbsolute as _I,join as Pi}from"node:path";import{createSession as rv,classifyClaudeAuth as mf,CLAUDE_CODE_SETUP_HINT as MI,loginPkce as FI,toStoredTokens as UI,saveTokens as WI,getAccessToken as BI,D360AuthError as HI,resolveActiveProfile as Rt,resolveProjectId as GI,getArticle as qI,decodeJwtClaims as ls,isExpired as Zo,loadTokens as lo,clearTokens as VI,rememberSessionProject as KI,listStoredSessions as YI,tokensProjectId as sv,clearProfileProject as zI,setTitle as XI,slugify as QI,touchSession as lf,upsertSession as JI,generateTitle as iv,findByName as ZI,listSessions as eL,renameSession as tL,suggestNextAction as nL,readProjectConfig as ke,writeProjectConfig as av,autoModeEnabled as lv,autoBudgetUsd as mc,DEFAULT_AUTO_BUDGET_USD as oL,WRITER_DIRNAME as rL,readUserConfig as cv,writeUserConfig as sL,resolveAndPersistAppType as iL,detectAppType as uv,resolveModelSetting as gf,loadProfileMap as dv,applyPull as gc,computeSyncStatus as yc,lintDocs as ss,compareRemoteSources as aL,planPull as pv,recordRunSample as lL,pushArticles as cL,pushArticle as uL,PUSH_POOL_SIZE as dL,isPullWouldBlankError as hv,localArticleTitle as fv,establishBaselines as pL,rebaselineServerMeta as hL,inventoryRepo as fL,knownEnvironments as mL,currentEnvironments as mv,sunsetEnvironment as gv,resolveEnvironment as gL,planPartitions as cf,partitionEvenly as yL,screenshotPlaceholderIds as wL,trackedArticlePaths as bL,runPartitioned as Ti,partitionCoverage as uf,estimateBulkCost as yv,resolveModelForOperation as Ai,readDocsPlan as wv,checkForUpdate as kL,detectInstallKind as $L,isSelfUpdatable as vL,devHintsGuidePath as bv,toolFeedbackPath as kv,reconcileToolFeedback as xL,reconcileUpgradeActions as RL,stampArticles as is,snapshotArticles as df,listArticleFiles as SL,CONTENT_CAP_VERSION as CL,ENGINE_VERSION as Nv,DEFAULT_DOCS_DIR as yf,docsRootOf as PL,setProfileProject as TL,writeCrashLog as AL,applyStructureOrder as pf,orderSyncLine as hf,applyRelatedArticles as $v,relatedSyncLine as vv,reconcileDocsGit as EL,shareExplainedPath as NL,ensureDir as DL}from"document360-engine";Cr();Hn();import{spawn as r$}from"node:child_process";function Yj(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function zj(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?r$([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):r$(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 Xh(e){for(let[t,n]of Yj())if(await zj(t,n,e))return!0;return!1}var s$=/\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 i$(e){let t=e.replace(/\s+$/,"").split(`
483
- `),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 Xj=/\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 a$(e){let t=e.trimEnd();if(!t)return null;let n=i$(t);return n>=2?{options:n}:/\?[\s*_"')\]]*$/.test(t)||s$.test(t)||Xj.test(t)?{options:0}:null}function Qh(e,t){if(t.closed)return e;let n=e.split(`
484
- `),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){s$.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(`
485
- `)}var Qj=/^(?:(?:run|use|try|execute)\s+)?['"`*]?(\/[a-z][a-z-]*)['"`*]?((?:\s+(?:--?[a-z][\w-]*|\S*[/\\]\S*|\d{1,3}[-_][\w.-]*|[\w.-]+\.(?:md|markdown)))*)/i;function Jj(e,t){let n=i$(e);return n<2?[]:e.replace(/\s+$/,"").split(`
486
- `).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=Qj.exec(i);if(!a)return null;let c=a[1].slice(1).toLowerCase();return t.has(c)?`${a[1]}${(a[2]??"").replace(/\s+/g," ").trimEnd()}`:null})}function l$(e,t){let n=Jj(e,t);return n.length<2||n.some(o=>o===null)?null:n}function Zj(e){let t=e.split(`
487
- `).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 ts(e){if(e.usageLimit)return`${e.label}: ${e.usageLimit}`;let t=e.stderrTail?Zj(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 eI={la:"local","l all":"local","local all":"local",pa:"portal","p all":"portal","portal all":"portal",sa:"skip","s all":"skip","skip all":"skip"},tI={L:"local",P:"portal",S:"skip"},nI={ya:"write","y all":"write","yes all":"write",na:"skip","n all":"skip","no all":"skip"},oI={Y:"write",N:"skip"};function c$(e,t,n){let o=e.trim(),r=o.toLowerCase().replace(/\s+/g," ");return t[r]??(o.length===1?n[o]??null:null)}function nc(e){return c$(e,eI,tI)}function u$(e){return c$(e,nI,oI)}function Jh(e,t){let n=t?.max??12,o=t?.chrome??8;return Math.max(3,Math.min(n,(e??24)-o))}function oc(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 Zh(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 d$(e){return e<2?null:`1-${e}`}function xt(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:d$(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 p$(e){if(e.multi)return"pick with space, then enter to save \xB7 esc to cancel\u2026";let t=e.rows===void 0?null:d$(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 rI=[/\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],sI=[/\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/],iI=/^(read|glob|grep|ls|search|notebookread)$/i;function h$(e,t){return!e||!iI.test(e.trim())||sI.some(n=>n.test(t))?!1:rI.some(n=>n.test(t))}import{existsSync as aI,mkdirSync as lI,readFileSync as cI,writeFileSync as uI}from"node:fs";import{join as f$}from"node:path";import{writerDir as dI}from"document360-engine";function m$(e){return f$(dI(e),".sessions")}function g$(e,t){return f$(m$(e),`${t}.json`)}function y$(e,t,n){try{lI(m$(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");uI(g$(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function ef(e,t){try{let n=g$(e,t);if(!aI(n))return[];let o=JSON.parse(cI(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var pI=e=>`\x1B]0;${e}\x07`,hI=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function w$(e){process.stdout.isTTY&&process.stdout.write(e)}function ns(e){w$(pI(e))}function rc(e){w$(hI(e))}var sc=["\xB7 "," \xB7"],ic="\u{1F7E3}";ml();var b$=e=>e===1?"":"s";function k$(e){let t=e.ran.length,n=t===0?"nothing to do":`${t} step${b$(t)} done`;switch(e.reason.kind){case"settled":return{tone:"ok",text:`Auto mode finished \u2014 that is the full round trip. ${n}.`};case"delivered":return{tone:"ok",text:`Auto mode finished \u2014 this round is delivered and your readers have it. ${n}.`};case"nothingToDo":return t===0?e.parked.length>0?{tone:"ok",text:"Auto mode had nothing it could run on its own \u2014 everything else is already written, saved and live."}:{tone:"ok",text:"Auto mode had nothing to do \u2014 everything is already written, saved and live."}:e.parked.length>0?{tone:"ok",text:`Auto mode finished what it could. ${n}.`}:{tone:"ok",text:`Auto mode finished \u2014 nothing left waiting. ${n}.`};case"onlyBlocked":return t===0?{tone:"warn",text:"Auto mode did not start anything \u2014 everything waiting needs a decision from you."}:{tone:"warn",text:`Auto mode went as far as it could on its own. ${n}, and the rest needs you.`};case"budget":return{tone:"warn",text:`Auto mode stopped at its spending limit \u2014 ${Ye(e.reason.spentUsd)} of ${Ye(e.reason.limitUsd)}. ${n}.`};case"stopped":return{tone:"warn",text:`Auto mode stopped \u2014 you asked it to. ${n}.`};case"repeat":case"noProgress":return{tone:"warn",text:`Auto mode stopped \u2014 ${e.reason.cmd} came back unfinished, and running it again would not have changed that. ${n}.`};case"maxSteps":return{tone:"warn",text:`Auto mode stopped after ${e.reason.steps} steps without reaching a finished state. ${n}.`}}}function $$(e){switch(e.reason.kind){case"settled":case"nothingToDo":return e.parked.length>0?{tone:"info",text:"What is left is with someone else. I am still in auto mode, so I will pick it up as soon as it lands."}:{tone:"info",text:"Nothing is waiting. I am still in auto mode, so the next time there is work I will pick it up."};case"delivered":return{tone:"info",text:"What is left needs you or a browser \u2014 /status lists it, and it costs nothing. I am still in auto mode for the next round."};case"budget":return{tone:"info",text:`/auto --budget <amount> raises the limit, then ${e.reason.next} is where it picks up.`};case"stopped":return{tone:"info",text:"/auto on picks the round trip back up from here. Nothing was undone."};case"onlyBlocked":return{tone:"info",text:"Clear the items above and I will carry on \u2014 /auto on starts me again."};case"repeat":case"noProgress":case"maxSteps":return{tone:"info",text:"This one needs a person. /status shows what stands between your work and your readers, and it costs nothing."}}}function v$(e){let t=[k$(e)],n=e.spentUsd>0?` \xB7 ${Ye(e.spentUsd)} of ${Ye(e.budgetUsd)}`:"";if(t.push({tone:"info",text:` ${ol({seconds:e.seconds,...e.activeSeconds!==void 0?{activeSeconds:e.activeSeconds}:{}})}${n}`}),e.ran.length>0){t.push({tone:"info",text:""}),t.push({tone:"info",text:" What I ran:"});for(let o of e.ran)t.push({tone:"info",text:` \xB7 ${o}`})}if(e.parked.length>0){t.push({tone:"info",text:""}),t.push({tone:"warn",text:` ${e.parked.length} thing${b$(e.parked.length)} need${e.parked.length===1?"s":""} you:`});for(let o of e.parked)t.push({tone:"warn",text:` \xB7 ${o.what}${o.cmd?` \u2192 ${o.cmd}`:""}`})}return e.reason.kind!=="settled"&&e.reason.kind!=="nothingToDo"&&e.reason.kind!=="delivered"&&e.ran.length>0&&(t.push({tone:"info",text:""}),t.push({tone:"info",text:" Everything already written, saved and published is kept \u2014 stopping never undoes work."})),t.push({tone:"info",text:""}),t.push($$(e)),t}function x$(e,t){let n=k$(e).text,o=[`# Automatic run \u2014 ${t}`,"",n,""];if(o.push(`- Time: ${ol({seconds:e.seconds,...e.activeSeconds!==void 0?{activeSeconds:e.activeSeconds}:{}})}`),o.push(`- Spent: ${Ye(e.spentUsd)} of a ${Ye(e.budgetUsd)} limit`),o.push(""),o.push("## What ran"),o.push(""),e.ran.length===0)o.push("Nothing \u2014 see above for why.");else for(let r of e.ran)o.push(`- \`${r}\``);if(o.push(""),o.push("## What needs you"),o.push(""),e.parked.length===0)o.push("Nothing.");else for(let r of e.parked)o.push(`- ${r.what}${r.cmd?` Run \`${r.cmd}\`.`:""}`);return o.push(""),o.push($$(e).text),o.push(""),o.join(`
488
- `)}var R$=new Set(["/resolve","/pull","/screenshot","/login","/logout","/init","/reset","/discover","/genre","/style-guide","/scope","/profile","/project","/workspace","/model","/mcp","/share","/auto","/allow-prod"]),fI=new Set(["--skip-review","--skip-style","--skip-screenshots","--force"]),mI=40,gI=2,yI=(e,t)=>e.what===t.what&&e.cmd===t.cmd;function ac(e,t){return e.some(n=>yI(n,t))?e:[...e,t]}function S$(e){let t=an(e);if(!t||R$.has(t.cmd)||!Er(t))return!1;for(let n of t.flags)if(fI.has(n))return!1;return!wI(t)}function wI(e){return e.cmd!=="/review"&&e.cmd!=="/write"&&e.cmd!=="/reorder"||e.flags.has("--all")||e.flags.has("--blocked")||e.flags.has("--stale")?!1:e.scope===void 0}function C$(e){let t=an(e);return!t||t.cmd!=="/push"||t.scope!==void 0||t.flags.has("--all")||t.flags.size>0?e:"/push --all"}function P$(e){return!e||e.kind!=="cmd"?null:e.cmd}function bI(e){return e.kind==="answer"?{what:"I asked you a question and stopped to wait for the answer.",cmd:null}:e.kind==="prompt"?{what:`A step needs you to tell me what you want: \u201C${e.text}\u201D.`,cmd:null}:T$(e.cmd)}function T$(e){switch(an(e)?.cmd??e.split(/\s+/)[0]??e){case"/resolve":return{what:"Some articles were changed both here and in Document360, and only you can say which copy survives.",cmd:"/resolve"};case"/pull":return{what:"There are edits in Document360 to bring down, and each one needs your yes or no.",cmd:"/pull"};case"/screenshot":return{what:"Some screenshots are still to be taken \u2014 that needs your product running, so I never do it automatically.",cmd:"/screenshot"};case"/login":return{what:"The Document360 session needs signing in again, which happens in your browser.",cmd:"/login"};case"/discover":return{what:"The product questions are still out with your builder, so there is nothing I can answer tonight.",cmd:"/discover"};default:return{what:`${e} is a step I leave to you.`,cmd:e}}}var kI=(e,t)=>e.ran.filter(n=>n===t).length;function A$(e,t,n){let o=t.parked,r=n.maxSteps??mI;if(t.ran.length>=r)return{kind:"stop",reason:{kind:"maxSteps",steps:t.ran.length},parked:o};if(e.heldHints>0){let a=e.heldHints;o=ac(o,{what:`${a} note${a===1?"":"s"} from your builder ${a===1?"is":"are"} waiting on code they haven't finished \u2014 I've asked whether ${a===1?"it's":"they're"} done.`,cmd:null})}if(e.restKind==="complete")return{kind:"stop",reason:{kind:"settled"},parked:o};if(e.restKind==="delivered"&&t.ran.length>0)return{kind:"stop",reason:{kind:"delivered"},parked:o};if(!e.lead&&!e.picker&&e.menu.length===0)return{kind:"stop",reason:{kind:"nothingToDo"},parked:o};e.picker&&(o=ac(o,{what:`${e.picker.title} \u2014 that one is yours to answer.`,cmd:null}));let s=[{cmd:P$(e.lead),lead:e.lead},...e.menu.map(a=>({cmd:a.startsWith("/")?a:null,lead:null}))],i=new Set;for(let a of s){if(!a.cmd){if(a.lead?.kind==="prompt"&&a.lead.text===zo)return t.ran.includes(zo)?{kind:"stop",reason:{kind:"noProgress",cmd:zo},parked:o}:t.spentUsd>=n.budgetUsd?{kind:"stop",reason:{kind:"budget",spentUsd:t.spentUsd,limitUsd:n.budgetUsd,next:zo},parked:o}:{kind:"prompt",text:zo,parked:o};a.lead&&(o=ac(o,bI(a.lead)));continue}let c=C$(a.cmd);if(i.has(c))continue;if(i.add(c),!S$(a.cmd)){let f=an(a.cmd);f&&R$.has(f.cmd)&&(o=ac(o,T$(a.cmd)));continue}if(t.ran[t.ran.length-1]===c)return{kind:"stop",reason:{kind:"repeat",cmd:c},parked:o};if(kI(t,c)>=gI)return{kind:"stop",reason:{kind:"repeat",cmd:c},parked:o};if(t.lastClosedItsTarget===!1&&t.lastLeadKey&&t.lastLeadKey===c)return{kind:"stop",reason:{kind:"noProgress",cmd:c},parked:o};let l=t.spentUsd+(n.nextCostUsd??0);return t.spentUsd>=n.budgetUsd||l>n.budgetUsd?{kind:"stop",reason:{kind:"budget",spentUsd:t.spentUsd,limitUsd:n.budgetUsd,next:c},parked:o}:{kind:"run",cmd:c,parked:o}}return{kind:"stop",reason:{kind:"onlyBlocked"},parked:o}}function E$(e,t,n){let o=[],r=new Set([t]),s=[P$(e.lead),...e.menu.map(i=>i.startsWith("/")?i:null)];for(let i of s){if(!i||!S$(i))continue;let a=C$(i);if(r.has(a))continue;r.add(a);let c=null;try{c=n(a)}catch{c=null}o.push({cmd:a,scale:c})}return o}var N$=()=>({fingerprint:null,counts:null,settled:0,spokenBaseline:null,lastSpokeAt:null,awaySince:null}),$I={hints:0,requests:0,answers:0,directives:0,held:0,heldAsked:0,briefMoved:!1};function tf(e,t){let n=e??$I;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),held:Math.max(0,t.held-n.held),heldAsked:Math.max(0,t.heldAsked-n.heldAsked),briefMoved:t.briefMoved&&!n.briefMoved}}var lc=e=>e.hints===0&&e.requests===0&&e.answers===0&&e.directives===0&&!e.briefMoved,D$=e=>e.hints+e.requests+e.answers+e.directives+(e.briefMoved?1:0),nf=(e,t)=>e-t>=6e5;function j$(e){let{now:t,lastInputAt:n,fingerprint:o,counts:r,occupied:s,prev:i}=e,a=nf(t,n),l=i.fingerprint!==null&&i.fingerprint!==o?0:i.settled+1,f={...i,fingerprint:o,counts:r,settled:l,awaySince:a?i.awaySince??t:null,spokenBaseline:i.spokenBaseline??r};if(a){let k=tf(f.spokenBaseline,r);return{memory:f,speak:null,waiting:lc(k)?null:k}}if(s)return{memory:f,speak:null,waiting:null};if(l<2)return{memory:f,speak:null,waiting:null};let g=tf(i.spokenBaseline,r);return lc(g)?{memory:f,speak:null,waiting:null}:i.lastSpokeAt!==null&&t-i.lastSpokeAt<6e5?{memory:f,speak:null,waiting:null}:{memory:{...f,spokenBaseline:r,lastSpokeAt:t,settled:l},speak:g,waiting:null}}function I$(e,t,n){if(e.awaySince===null)return{kind:"none",memory:e};let o=t-e.awaySince,r=tf(e.spokenBaseline,n),s={...e,awaySince:null,counts:n,spokenBaseline:n,lastSpokeAt:lc(r)?e.lastSpokeAt:t};return lc(r)?{kind:"none",memory:s}:{kind:o>=36e5?"briefing":"delta",memory:s,delta:r,awayMs:o}}function Ri(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"}`),e.briefMoved&&t.push("an updated product brief"),t.length===0?"":t.length===1?t[0]:`${t.slice(0,-1).join(", ")} and ${t.at(-1)}`}function of(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 L$(e){return`\u{1F4E5} ${Ri(e)} just arrived from your builder \u2014 /catch-up folds ${D$(e)===1?"it":"them"} into the docs.`}function O$(e,t){return`\u{1F4E5} While you were away (${of(t)}): ${Ri(e)} from your builder \u2014 /catch-up folds ${D$(e)===1?"it":"them"} into the docs.`}function _$(e){return`\u{1F4E5} ${Ri(e)} waiting from your builder \xB7 tab to run /catch-up\u2026`}fa();import{publishGateVerdict as wc,publishGateLines as ff,blockedPaths as jL,SKIP_STYLE_FLAG as xv,SKIP_SHOTS_FLAG as IL}from"document360-engine";import{askBuilder as LL,openGapQuestions as OL}from"document360-engine";import{recordStructureReview as Rv}from"document360-engine";import{recordBriefConsumed as _L}from"document360-engine";import{retireArticle as ML,normalizeScope as Sv,declineImport as FL,undoDecline as UL}from"document360-engine";import{readReuseProposal as WL}from"document360-engine";oe();import{Box as Si,Text as We}from"ink";import{jsx as Be,jsxs as os}from"react/jsx-runtime";function vI({row:e,nameW:t,width:n}){let o=s=>ru(s,n),r=(s,i)=>Be(Si,{flexDirection:"column",children:s.map(i)});switch(e.t){case"head":return r(o(e.s),(s,i)=>Be(We,{color:le,bold:!0,children:s},i));case"text":return r(o(e.s),(s,i)=>Be(We,{children:s},i));case"dim":return r(o(e.s),(s,i)=>Be(We,{dimColor:!0,children:s},i));case"sub":return r(o(e.s),(s,i)=>Be(We,{bold:!0,dimColor:!0,children:s},i));case"good":return r(o(e.s),(s,i)=>Be(We,{color:"green",children:s},i));case"step":{let s=o(`${e.n}. ${e.s}`);return Be(Si,{flexDirection:"column",children:s.map((i,a)=>a===0?os(We,{children:[Be(We,{color:le,children:`${e.n}. `}),i.slice(`${e.n}. `.length)]},a):Be(We,{children:i},a))})}case"cmd":{let s=la(e.name,e.s,t,n),i=s.descLines.slice(s.nameOwnLine?0:1);return os(Si,{flexDirection:"column",children:[os(We,{children:[" ",Be(We,{color:le,children:s.nameCell}),!s.nameOwnLine&&Be(We,{dimColor:!0,children:` ${s.descLines[0]??""}`})]}),i.map((a,c)=>Be(We,{dimColor:!0,children:`${s.indent}${a}`},c))]})}case"gap":return Be(We,{children:" "})}}function M$({tab:e,scroll:t,rows:n,width:o,version:r,engineVersion:s}){let i=wt[e]??wt[0],a=ou(i.rows),c=Math.max(20,o-2),l=6+wt.reduce((C,x)=>C+x.label.length+4,0),f="\u2500".repeat(Math.min(l,c)),g=`\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=Pm({rows:n,inner:c,barWidth:l,footerWidth:g.length}),{visible:T,above:A,below:S}=Cm(i.rows,{width:o,budget:k,scroll:t,nameW:a});return os(Si,{flexDirection:"column",paddingX:1,children:[os(We,{children:[Be(We,{color:le,bold:!0,children:"Help "}),wt.map((C,x)=>x===e?Be(We,{color:"white",backgroundColor:le,bold:!0,children:` ${C.label} `},C.key):Be(We,{children:` ${C.label} `},C.key))]}),Be(We,{color:le,children:f}),os(Si,{flexDirection:"column",marginTop:1,children:[A>0?Be(We,{dimColor:!0,children:`\u22EF ${A} more above`}):null,T.map((C,x)=>Be(vI,{row:C,nameW:a,width:o},A+x)),S>0?Be(We,{dimColor:!0,children:`\u22EF ${S} more below`}):null]}),Be(We,{dimColor:!0,children:`
489
- \u2190/\u2192 or tab switch \xB7 1-5 jump${A+S>0?" \xB7 \u2191\u2193 scroll":""} \xB7 esc close \xB7 d360-writer v${r} \xB7 engine v${s}`})]})}var xI=/^(?:\d+[.)]|[-*•])\s+/;function F$(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
490
- `)){let i=s.trim().replace(xI,""),a=i.match(/^`([^`]+)`$/);a&&(i=a[1].trim());let c=i.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!c||!o.has(c[1].toLowerCase()))continue;let l=`/${c[1].toLowerCase()}${c[2]?` ${c[2]}`:""}`;if(r.includes(l)||r.push(l),r.length>=n)break}return r}oe();function Qo(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function nt(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function cc(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var RI=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function rf(e,t,n){if(!RI.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 sf(e){return e.replace(/^[\w.-]+\//,"")}var uc=16,U$={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function ao(e){return typeof e=="string"?e:e.cmd}function W$(e){return typeof e=="string"?void 0:e.desc}function af(e){return e.trim().split(/\s+/).slice(1).join(" ")}function B$(e,t){let n=af(t);return e.some(r=>ao(r).trim()===t.trim()||!!n&&af(ao(r))===n)?e.filter(r=>ao(r).trim()!==t.trim()&&!(n&&af(ao(r))===n)):[]}import{isDirectiveMention as BL,stripDirectiveMention as HL,appendDirective as GL,reconcileTestidRequest as qL,builderChannelWired as VL,pendingFingerprint as KL}from"document360-engine";var SI=/\[Pasted text #\d+ \+\d+ lines?\]/g;function H$(e){return e.replace(/\r\n?/g,`
491
- `)}function G$(e){return e.includes(`
492
- `)||e.length>200}function q$(e,t){let n=t.split(`
493
- `).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function V$(e,t){return e.replace(SI,n=>t.get(n)??n)}function K$(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function dc(e,t){let n=Math.max(1,t),o=[],r=0;for(let s of e.split(`
494
- `)){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 pc(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function Y$(e,t,n){let o=pc(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 z$(e,t,n){let o=e[pc(e,t)];return n==="start"?o.start:o.end}var CI=new Set(["Edit","Write","MultiEdit","NotebookEdit"]),X$={hint:"hint",message:"message",state:"state file",roadmap:"roadmap",directive:"directives",feedback:"tool-feedback"},PI=new Set(["hint","message","state"]),TI=["hint","message","roadmap","directive","feedback","state"];function AI(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 Q$(e,t){let n=e==="Read"?"read":CI.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=AI(r.slice(i+s.length));return a?{category:a,verb:n,path:r}:null}function J$(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 TI)for(let s of["updated","read"]){let i=t.get(`${r}:${s}`)?.size??0;i!==0&&o.push(PI.has(r)?`${i} ${X$[r]}${i===1?"":"s"} ${s}`:`${X$[r]} ${s}`)}return o.length>0?o.join(" \xB7 "):null}function Z$(e,t,n){let o=Math.max(1,n),r=e.split(`
458
+ `)];if(T.length&&C.push(T.join(" ")),s>0){let E=s;C.push(`${E} question${le(E)} you asked your developers ${E===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.`)}let x=Mk(i,a);return x&&C.push(x),C.push(Ok),{note:C.join(`
459
+
460
+ `),menu:g.map(E=>m1(E.lead))}}function Si(e,t){let n=t?.pickable===!0,o=x=>t?.header?`${t.header}
461
+
462
+ ${x}`:x;if(!e.ready)return{kind:"idle"};if(e.pendingAnswer)return{kind:"recommend",rec:{note:null,settled:null,restKind: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:[],heldHints:e.heldHints}};let r=h1(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(Ma)&&e.roadmap.total-e.roadmap.done===i.length,c=s?t1(e.roadmap.total-e.roadmap.done,e.roadmap.total,{listed:i.length>0,onlyScreenshots:a}):null,l=r.filter(x=>x.lead||x.picker),f=!s&&l.length>0&&l.every(x=>x.opensRound===!0),g=f?n1({heldDrafts:e.draftBlockedShots?.articles??0,behind:e.behind}):c,$=s?"complete":f?"delivered":null;if(!e.hasDocs){let x=Uk(r);if(x&&(x.lead?.kind==="cmd"||x.picker)){let E=Ri(t?.header??"\u{1F4ED} No docs yet for this repo \u2014 here\u2019s where things stand:",r,n,null,void 0,e.outboundQuestions,e.heldHints,e.heldHintsAsked);return{kind:"recommend",rec:{note:E.note,settled:null,restKind:null,tone:x.tone??"info",lead:x.lead,picker:x.picker,menu:E.menu,heldHints:e.heldHints}}}return{kind:"recommend",rec:{note:o(u1),settled:null,restKind:null,tone:"info",lead:{kind:"prompt",text:Qo,reason:"I\u2019ll read the code and draft a structure"},picker:null,menu:[],heldHints:e.heldHints}}}if(r.length===0){let x=e.roadmap&&!e.roadmap.next?` Docs campaign complete \u2014 all ${e.roadmap.total} step${le(e.roadmap.total)} done (/roadmap).`:"",E=Mk(e.heldHints,e.heldHintsAsked);return{kind:"recommend",rec:{note:o(`Welcome back. Your ${e.tracked} tracked article${le(e.tracked)} for \u201C${e.profileName}\u201D are all in sync \u2014 /audit re-checks the code, /pull brings down portal edits.${x}`+(E?`
463
+
464
+ ${E}`:"")),settled:null,restKind:null,tone:"info",lead:null,picker:null,menu:[],heldHints:e.heldHints}}}let T=l,A=T[0]??null;if(!A){let x=Ri(t?.header??"Welcome back \u2014 where your docs stand:",r,n,null,void 0,e.outboundQuestions,e.heldHints,e.heldHintsAsked);return{kind:"recommend",rec:{note:x.note,settled:null,restKind:null,tone:"info",lead:null,picker:null,menu:x.menu,heldHints:e.heldHints}}}if((A.key==="audit"||T[1]?.key==="audit")&&e.behind>0&&e.autoAudit&&e.allowAutoAudit)return{kind:"autoAudit",note:o(`\u{1F4CB} ${e.behind} code change${le(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`)};if(s){let x=Ri(a?s1:i1,r,n,g,i,e.outboundQuestions,e.heldHints,e.heldHintsAsked);return{kind:"recommend",rec:{note:x.note,settled:g,restKind:$,tone:"info",lead:null,picker:null,menu:x.menu,heldHints:e.heldHints}}}if(f){let x=Ri(o1,r,n,g,void 0,e.outboundQuestions,e.heldHints,e.heldHintsAsked,!0);return{kind:"recommend",rec:{note:x.note,settled:g,restKind:$,tone:"info",lead:null,picker:null,menu:x.menu,heldHints:e.heldHints}}}let C=Ri(t?.header??"Welcome back \u2014 where your docs stand:",r,n,g,void 0,e.outboundQuestions,e.heldHints,e.heldHintsAsked);return{kind:"recommend",rec:{note:C.note,settled:g,restKind:$,tone:A.tone??"info",lead:A.lead,picker:A.picker,menu:C.menu,heldHints:e.heldHints}}}import{existsSync as zl,readdirSync as zh}from"node:fs";import{spawnSync as y1}from"node:child_process";import{join as Xl}from"node:path";import{readProjectConfig as Kh,resolveActiveProfile as qk,loadTokens as w1,isExpired as b1,loadProfileMap as Vk,localAheadPaths as k1,loadKnownConflicts as $1,loadCoverage as v1,listUnpullable as x1,draftPendingPaths as R1,loadOpenCommentCount as S1,readDocsPlan as C1,devHintsGuidePath as P1,DEFAULT_DOCS_DIR as Ql,roadmapProgress as T1,listRoadmap as Wk,readProductBriefState as A1,readDiscoveryQueue as E1,reconcileCommitRequest as N1,reconcileTestidRequest as D1,snapshotHandoff as j1,shareExplainedPath as I1,unannotatedShotIds as L1,shotsNeedingRecapture as O1,resolveOutputDir as _1,DEFAULT_OUTPUT_DIR as M1,WRITER_DIRNAME as Vh,styleGuideSettled as F1,styleGuideUpgradeOffered as U1,styleSweepOutstanding as W1,styleSweepSeedNeeded as B1,recordStyleSwitch as H1,lintArticles as G1,DEFAULT_PACK as q1,autoModeSettled as V1,autoBudgetUsd as Y1,listAvailablePacks as Bk,listArticleFiles as Yh,placeholderFindings as K1,placeholderRemedy as z1}from"document360-engine";Gn();var Hk=new Set,X1=5;function Gk(e){try{return zh(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function Xh(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>Gk(Xl(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&Gk(Xl(e,o)))}function Qh(e,t){try{let n=Kh(e);if(!n)return!1;let o=qk(e,t),r=Vk(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=Xl(e,(n.docsDir??Ql).replace(/\/+$/,""));return!!(zl(s)&&zh(s).length>0||zl(P1(e)))}catch{return!1}}function Q1(e){let t=[`:(exclude)${Vh}`],n=(e.docsDir??Ql).replace(/\\/g,"/").replace(/\/+$/,"");return n&&!n.startsWith(`${Vh}/`)&&n!==Vh&&t.push(`:(exclude)${n}`),t}function J1(e,t,n){try{let o=y1("git",["rev-list","--count",`${t}..HEAD`,"--",".",...Q1(n)],{cwd:e,encoding:"utf8",timeout:1200});return o.status===0&&parseInt((o.stdout||"").trim(),10)||0}catch{return 0}}function Ci(e,t,n){try{let o=Kh(e);if(!o)return null;let r=qk(e,t),s=w1(r.name,r.project.projectId),i=!!s&&(!b1(s)||!!s.refreshToken),a=Qh(e,t)||!Xh(e,o.authoritativeSourceFiles),c=Vk(e,r.name),l=c?Object.keys(c.articles).length:0,f=Xl(e,(o.docsDir??Ql).replace(/\/+$/,"")),g=!1;try{g=zl(f)&&zh(f).length>0}catch{}let $=c?.lastAnalyzedCommit?J1(e,c.lastAnalyzedCommit,o):0,T=0;try{let me=(o.docsDir??Ql).replace(/\/+$/,""),Ge=C1(e,me);Ge.length>0&&(T=Kn(e,me,Ge.map(ct=>ct.path)).length)}catch{}let A=Zt(e),S=Hr({...A,directives:0}),C=k1(e,t),x=new Set($1(e,r.name)),E=new Set(x1(e,r.name).map(me=>me.path)),j=v1(e,r.name),W=C.filter(me=>x.has(me)||E.has(me)),Y=W.length,B=C.length-Y,ue=new Set(C),fe=R1(e,t).filter(me=>!ue.has(me)),Re=K1(e,fe),Ie=new Set(Re.map(me=>me.path)),ge=fe.filter(me=>!Ie.has(me)).length,we=null;try{we=z1(e,Re)}catch{}let Z=[...C.filter(me=>!x.has(me)),...fe],Ae=Hs(e,Z),_e=Ae.length,ze=Lt(Ae),On=null;try{if(!F1(o.styleGuide)){let me=Bk(e).filter(Ge=>Ge.name.toLowerCase()!=="humanise");On={articles:Yh(e).length,presets:[{cmd:"/style-guide keep",desc:"the built-in rules only \u2014 correctness and anti-slop checks (nothing changes)"},...me.map(Ge=>({cmd:`/style-guide use ${Ge.name.toLowerCase()}`,desc:`${Ge.name} style guide \u2014 ${Ge.rules.length} more rules`}))]}}}catch{}let Ce=null;try{if(U1(o.styleGuide)){let Ge=Bk(e).find(ct=>ct.name.toLowerCase()===q1);Ge&&(Ce={to:Ge.name.toLowerCase(),rules:Ge.rules.length,from:(o.styleGuide?.packs??[]).map(ct=>ct.trim().toLowerCase()).filter(Boolean),articles:Yh(e).length})}}catch{}let Ee=null;try{if(B1(e,o?.styleGuide?.packs,o?.styleGuide?.decidedAt)&&!Hk.has(e)){Hk.add(e);let Ge=G1({cwd:e}).findings;H1(e,{packs:o?.styleGuide?.packs??[],from:[],articlesWithFindings:[...new Set(Ge.map(ct=>ct.path))]})}let me=W1(e);me&&(Ee={pending:me.pending,total:me.total,packs:me.packs,...Lt(me.paths)?{scope:Lt(me.paths)}:{}})}catch{}let Ze=null;try{V1(o)||(Ze={articles:Yh(e).length,presets:[{cmd:"/auto off",desc:"manual \u2014 I suggest the next step and wait for you to run it"},{cmd:"/auto on",desc:`auto \u2014 I run the next step myself, all the way to live (up to ${Ke(Y1(o))} a run)`}]})}catch{}let on=0,Ct;try{let me=gy(e,Z);on=me.length,Ct=Lt(me)}catch{}let co=0,uo=0;try{let me=_1(e,Kh(e)?.outputDir??M1);co=L1(me).length,uo=O1(me).length}catch{}let cs=S1(e,r.name),us=Xt(e),Ii=T1(e),rn=Ii?{...Ii,open:Wk(e).filter(me=>me.status==="open").slice(0,X1).map(me=>({title:me.title,...me.run?{run:me.run}:{},...me.stage?{stage:me.stage}:{}}))}:null,Pt=j1(e,o),ds=N1(e,new Date().toISOString(),{supersededByHandoff:Pt!==null});D1(e,new Date().toISOString());let Bt=Wn(e,t),_n=Bt?{name:Bt.name,replacement:Bt.replacement,replacementProfile:Bt.replacementProfile}:null,po=A1(e),fn=E1(e),mn=po?{status:po.status,openQuestions:fn.openQuestions,answersPending:fn.answersPending}:null;return!mn&&g&&Wk(e).some(Ge=>Ge.status==="open"&&(Ge.run??"").trim()==="/discover")&&(mn={status:"pending",openQuestions:0,answersPending:0}),{ready:i&&a&&!n.claudeMissing,hasDocs:g,tracked:l,pendingText:S,directives:A.directives,behind:$,pendingWrites:T,localAhead:B,unreviewed:_e,unreviewedScope:ze,styleErrors:on,shotsToAnnotate:co,shotsToRecapture:uo,styleErrorScope:Ct,draftAhead:ge,draftBlockedShots:we,conflicts:Y,unreadable:W.filter(me=>E.has(me)).length,portalUntracked:j?.unmapped??0,portalOnlyCategories:j?.portalOnlyCategories.filter(me=>me.articles>0).length??0,openComments:cs,outboundQuestions:di(e),heldHints:A.held,heldHintsAsked:A.heldAsked,autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:us.status,devhintsCompletedVersion:us.completedVersion,devhintsToVersion:Me,builderStarted:Pn(e),genreUnknown:n.genreUnknown,pendingAnswer:n.pendingAnswer??null,lastCommand:n.lastCommand??null,styleRules:On,styleUpgrade:Ce,styleSweep:Ee,autoChoice:Ze,roadmap:rn,discovery:mn,uncommittedDocs:ds.dirty.length,handoff:Pt,shareExplained:zl(I1(e)),sunsetEnv:_n}}catch{return null}}oe();import{existsSync as tj,readFileSync as nj}from"node:fs";import{isAbsolute as oj,join as rj}from"node:path";import{DEFAULT_DOCS_DIR as sj,findPathByArticleId as ij,isArticleDocPath as aj,loadProfileMap as lj,readProjectConfig as cj,resolveActiveProfile as uj}from"document360-engine";function Z1(){return process.platform==="win32"||process.platform==="darwin"}var ej=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Jl(e,t){let n=e.replace(/\\/g,"/"),o=`${ej(t)}/`,[r,s]=Z1()?[n.toLowerCase(),o.toLowerCase()]:[n,o];return r.startsWith(s)?n.slice(o.length):null}var Kk=70;function dj(e,t){return{docsRoot:()=>(cj(e)?.docsDir??sj).replace(/\\/g,"/").replace(/\/+$/,""),read:n=>{try{let o=oj(n)?n:rj(e,n);return tj(o)?nj(o,"utf8"):null}catch{return null}},pathForArticleId:n=>{try{let o=lj(e,uj(e,t).name);return o?ij(o,n):null}catch{return null}}}}var Jo=(e,t=Kk)=>{let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"};function Pi(e){if(!e)return null;let t=!1;for(let n of e.split(`
465
+ `)){let o=n.trimEnd();if(/^\s*(```|~~~)/.test(o)){t=!t;continue}if(t)continue;let r=/^#\s+(\S.*)$/.exec(o);if(r)return Jo(r[1])}return null}var pj=new Set(["a","an","and","as","at","but","by","for","in","of","on","or","the","to","vs","with"]),hj=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 zk(e,t,n){let o=e.toLowerCase();return hj.has(o)?e.toUpperCase():!t&&pj.has(o)?o:!t&&!n?e:e.charAt(0).toUpperCase()+e.slice(1)}var Xk=e=>e.replace(/^\d+[-_.]/,"").split(/[-_]/).filter(Boolean);function fj(e){let t=Xk(e);return t.length===0?e:t.map((n,o)=>zk(n,o===0,!0)).join(" ")}function Qk(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:fj(n[n.length-2])}function Jk(e){let t=e.replace(/\\/g,"/").split("/").pop()??e,n=Xk(t.replace(/\.(md|markdown)$/i,""));return n.length===0?t:n.map((o,r)=>zk(o,r===0,!1)).join(" ")}var mj=46;function gj(e,t){let n=0,o=!1,r=null;for(let s of e.split(`
466
+ `)){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=Jo(a[2],Kk))}n+=s.length+1}return r}function Yk(e){for(let t of e.split(`
467
+ `)){let n=t.replace(/^\s*(#{1,6}\s+|[-*+]\s+|>\s+|\d+[.)]\s+)/,"").replace(/^\s*\|/,"").trim();if(n)return Jo(n,mj)}return null}var Wt=e=>typeof e=="string"&&e?e:null,yj=e=>typeof e=="string"&&e.length>=8?`id ${e.slice(0,8)}\u2026`:null;function wj(e,t){return Jl(e,t)??e.replace(/\\/g,"/")}function bj(e,t){let n=Mt(e,t,200);return n?`+${n.added} \u2212${n.removed}`:"no change"}var kj=new Set(["Edit","MultiEdit","Write"]);function $j(e,t,n,o){if(!kj.has(e))return null;let r=Wt(t.file_path);if(!r)return null;let s=wj(r,n),i=o.docsRoot();if(!(s===i||s.startsWith(`${i}/`)))return null;let a=s.slice(i.length+1);if(!a||!aj(a))return null;let c=Qk(a),l=o.read(s),f=W=>Pi(W)??Pi(l)??Jk(a);if(e==="Write"){let W=Wt(t.content)??"",Y=f(W);if(l===null){let B=W.replace(/\n$/,"").split(`
468
+ `).length;return{verb:"Draft",title:Y,category:c,note:`new, ${B} lines`,articleKey:s}}return{verb:"Rewrite",title:Y,category:c,note:bj(l,W),articleKey:s}}let g=Array.isArray(t.edits)?t.edits.map(W=>({from:Wt(W.old_string)??"",to:Wt(W.new_string)??""})):[{from:Wt(t.old_string)??"",to:Wt(t.new_string)??""}],$=g.reduce((W,Y)=>{let B=Mt(Y.from,Y.to,200);return B?{added:W.added+B.added,removed:W.removed+B.removed}:W},{added:0,removed:0}),T=$.added===0&&$.removed===0?"no change":`+${$.added} \u2212${$.removed}`,A=g[0],S=A&&l?gj(l,l.indexOf(A.from)):null,C=A?Yk(A.to)??Yk(A.from):null,x=g.length>1?` +${g.length-1} more`:"",E=C?`\u201C${C}\u201D${x}`:x.trim()||null,j=S?{title:`\u21B3 ${S}`,category:E,note:T}:E?{title:`\u21B3 ${E}`,category:null,note:T}:null;return{verb:"Update",title:f(g.map(W=>W.to).join(`
469
+ `)),category:c,note:T,articleKey:s,...j?{repeat:j}:{}}}function vj(e,t,n){let o=()=>{let r=Wt(t.article_id),s=r?n.pathForArticleId(r):null;return(s?Pi(n.read(s)):null)??(s?Jk(s):yj(r)??"article")};switch(e){case"d360_create_article":{let r=Wt(t.title);return r?{verb:"Create",title:Jo(r),category:Qk(t.local_path),note:"Document360 draft"}:null}case"d360_update_article":return{verb:"Update",title:Wt(t.title)?Jo(Wt(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=Wt(t.name);return r?{verb:"Create",title:Jo(r),category:null,note:"Document360 category"}:null}case"d360_upload_drive_file":{let r=Wt(t.file_path);if(!r)return null;let s=r.replace(/\\/g,"/").split("/").pop()??r;return{verb:"Upload",title:Jo(s),category:null,note:"Document360 Drive",keepResult:!0}}default:return null}}function Zl(e,t,n,o,r=dj(n,o)){try{let s="mcp__document360__";return e.startsWith(s)?vj(e.slice(s.length),t,r):$j(e,t,n,r)}catch{return null}}var xj={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"},e$=160,Jh=200,t$=40;function io(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:Rj(n)?"\u2026"+n.slice(n.length-(t-1)):n.slice(0,t-1)+"\u2026"}function Rj(e){return!e.includes(" ")&&/[/\\]/.test(e)}function Zk(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}: ${io(typeof r=="string"?r:JSON.stringify(r),t$)}`);return t.length>4&&n.push("\u2026"),io(n.join(", "),e$)}var Sj=new Set(["file_path","notebook_path"]);function Cj(e,t){return t?Jl(e.replace(/\\/g,"/").replace(/\/+$/,""),t)??e:e}var ec=e=>typeof e=="string"&&e?e:null;function Pj(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});return e==="d360_sync_status"?n("Check sync status",null):null}function tc(e,t,n){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,s="",...i]=e.split("__"),a=i.join("__");if(s==="document360"){let f=Pj(a,t);if(f)return f}let c=a.replace(/^d360_/,"").replace(/_/g," ");return{title:`${s==="document360"?"Document360":s.charAt(0).toUpperCase()+s.slice(1)}: ${c}`,sep:" ",arg:Zk(t)}}let o=xj[e],r=o?t[o]:void 0;if(typeof r=="string"&&r){let s=o&&Sj.has(o)?Cj(r,n):r;return{title:e,sep:"",arg:io(s,e$)}}return{title:e,sep:"",arg:Zk(t)}}function Tj(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 Aj(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(Tj).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>io(r,Jh))]}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}: ${io(String(r),t$)}`);return n.length>0?[io(n.join(" \xB7 "),Jh)]:null}return null}function Ej(e){let t=ec(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function Nj(e,t,n){switch(e){case"d360_create_article":{let o=Ej(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=ec(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 ${io(o[0],120)}`:""}`]}case"d360_create_variable":{let o=ec(t?.name);return[`\u2713 variable created${o?` \xB7 :variable[]{name="${o}"}`:""}`]}case"d360_create_snippet":{let o=ec(t?.name);return[`\u2713 snippet created${o?` \xB7 ::snippet{name="${o}"}`:""}`]}default:return null}}var n$=new Set(["Edit","Write","MultiEdit","NotebookEdit"]);function Dj(e){return e.replace(/^\s*\d+\t/,"")}function jj(e,t){if(n$.has(e))return[];let n=t.split(`
470
+ `);if(e==="Read"){let o=n.length,r=Pi(n.map(Dj).join(`
471
+ `));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 nc(e,t=4,n,o){let r=e.replace(/\r\n/g,`
472
+ `).trimEnd();if(n&&n$.has(n))return{lines:[],hidden:0};if(!r)return{lines:["(no output)"],hidden:0};if(n&&!n.startsWith("mcp__")){let i=jj(n,r);if(i)return{lines:i,hidden:0}}if(n?.startsWith("mcp__document360__")){let i=Nj(n.slice(18),o,r);if(i)return{lines:i,hidden:0}}let s=Aj(r)??r.split(`
473
+ `);return{lines:s.slice(0,t).map(i=>io(i,Jh)),hidden:Math.max(0,s.length-t)}}function oc(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function rc(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 o$(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 sc(e){return o$(e,"url")}function ic(e){return o$(e,"preview_url")}function ac(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 d$=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/,ef=null;function a$(){return ef===null&&(ef=qj().verboseTranscript===!0),ef}function sI(e,t,n,o){if(d$.test(e))try{let r=u$(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,i=rc(t,n),a=ac(t,n),c=a?`${a} \u2014 `:"",l=sc(n);e.endsWith("publish_article")&&l&&console.log(ee(` \u2B95 ${c}Live: ${l}`));let f=ic(n);f?console.log(ee(` \u2B95 ${c}Preview: ${f}`)):i&&s&&console.log(ee(` \u2B95 ${c}Preview: ${oc(r.connection.portalUrl,s,i,r.project.languageCode??"en")}`))}catch{}}async function p$(e=process.cwd(),t="auto",n,o){let r=Lj(t);r.kind==="none"&&(console.error(""),console.error(L("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${ee("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${ee('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${ee("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${ee("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),iI(e,n);let s=Oj(t),i=_j(s);console.log(i?q(` ${r$(s)}`):d(` ${r$(s)}`)),i?console.log(d(` ${i}`)):r.kind==="subscription"&&!r.stored&&console.log(d(" No sign-in found on this machine \u2014 trying your Claude session anyway.")),console.log("");let a=!1,c=Zh({cwd:e,profileName:n,allowProdWrites:a}),l={uuid:null,firstPrompt:null,titleFired:!1},f=Ij({input:process.stdin,output:process.stdout}),g=[],$=null,T=!1;f.on("line",C=>{if($){let x=$;$=null,x(C)}else g.push(C)}),f.on("close",()=>{if(T=!0,$){let C=$;$=null,C(null)}});function A(){return g.length>0?Promise.resolve(g.shift()):T?Promise.resolve(null):(process.stdout.write(ee("> ")),new Promise(C=>{$=C}))}let S={cwd:e,version:o,profileName:n,allowProdWrites:()=>a,restartAgent:()=>{c.close(),c=Zh({cwd:e,profileName:n,allowProdWrites:a}),l={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>l.uuid,setPendingName:C=>{l.pendingName=C},setModel:async C=>c.setModel(C),withPausedInput:async C=>{f.pause();try{return await C()}finally{f.resume()}}};try{for(;;){let C=await A();if(C===null)break;let x=C.trim();if(x){if(x.startsWith("/")){let E=Lk(x);if(!E)continue;let j=Ik[E.name];if(!j){console.log(L(`Unknown command: /${E.name}`)),console.log(d("Type /help for the list."));continue}let W=await j(E.args,S);if(W.kind==="exit")break;if(W.kind==="clear"){S.restartAgent();continue}if(W.kind==="allow-prod"){a=!0,S.restartAgent(),console.log(Q("\u2713 Production writes authorized for this session.")),console.log("");continue}if(W.kind==="resume"){c.close(),c=Zh({cwd:e,resume:W.uuid,profileName:n,allowProdWrites:a});let Y=Mj(W.uuid);l={uuid:W.uuid,firstPrompt:Y?.firstPrompt??null,titleFired:!0},c$(W.uuid),console.log(Q(`\u2713 Resumed "${W.name}"`)),console.log("");continue}if(W.kind==="audit-blocked"){console.log(q(W.note)),console.log(d(` Run: ${W.lead.cmd} \u2014 ${W.lead.reason}.`)),console.log("");continue}if(W.kind==="forward-to-agent"){l.firstPrompt||(l.firstPrompt=W.display??W.prompt);let Y=W.display??"",B=Y.trim().split(/\s+/),ue=nw(Y),fe=ue?eI(e,ow(Y)):[],Re=ue==="review"?i$(e):null,Ie=B[0]==="/screenshot"&&(B[1]==="verify"||B[1]==="review"),ge=Ie?B[2]&&!B[2].startsWith("--")?[B[2]]:ii(Ue(e)):[],we=B[0]==="/catch-up"&&!ue,Z=we?i$(e):null;c.beginTurn({baseline:Z,allowUnfinishedHints:B.includes("--include-unfinished")});let Ae=we?Zt(e):null,_e=we?hi(e).hold:!1,ze=W.prompt;if(Y.startsWith("/"))try{let Ce=Ua(e,Y);Ce&&(ze=`${ze}
474
+
475
+ ${Ce}`)}catch{}let On=await tf(c,ze,r,l,e,n);if(ue){let Ce=ue==="review"?Ko(e,fe,Re,n):null,Ee=Ce?Ce.earned:fe;if(Ee.length>0)try{Zj(e,Ee,mt(ue))}catch{}let Ze=Ce?Vr(e,Ce.unadopted,{lead:Ce.changed.length===0}):null;if(Ze)for(let on of Ze.lines)console.log(d(on))}if(Z){On.produced&&rI(e);let Ce=qo(e,Z,"",B[0]);if(Ce.cta)console.log(d(Ce.cta.text));else if(Ae){let Ee=Cl({queued:Ae,hold:_e});Ee.note&&console.log(Ee.tone==="warn"?q(Ee.note):d(Ee.note)),Ee.lead&&console.log(d(` Run ${Ee.lead.cmd} \u2014 ${Ee.lead.reason}.`))}}if(B[0]==="/reuse"&&B[1]==="audit"){let Ce=B.slice(2).find(Ee=>!Ee.startsWith("--"));for(let Ee of Vl(e,Ce))console.log(Ee)}if(B[0]==="/audit"&&!B.includes("--auto")&&xi(e,n),Ie&&ge.length>0)try{for(let Ce of Ur(e,ge))console.log(Ce)}catch{}if(B[0]==="/push"){let Ce=await Bs(e,n);Ce&&console.log(d(Ce))}if((B[0]==="/catch-up"||B[0]==="/document")&&(B.includes("--push")||B.includes("--publish")))try{let Ce=await oI({cwd:e,profileName:n}),{clean:Ee,conflicts:Ze}=Mo(Ce.entries,Fo(e,n));Ee.length===0?console.log(d("Nothing new to push \u2014 everything is already up to date on Document360.")):await Jt(S,Ee.map(on=>on.path),Ze.length,{skipReview:B.includes(Ot)})}catch(Ce){console.log(q(`Couldn't check what to push (${Ce.message}) \u2014 your drafts are saved; run /push when ready.`))}}else W.kind==="continue"&&W.ownNext||aI(e,n);continue}if(zj(x)){let E=Xj(x);if(E){try{Qj(e,{title:E,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}l.firstPrompt||(l.firstPrompt=x),await tf(c,`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${E}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${E}" and the article path(s) you wrote.`,r,l,e,n);continue}}l.firstPrompt||(l.firstPrompt=x),await tf(c,x,r,l,e,n)}}}finally{c.close(),f.close(),await jl()}}function iI(e,t){console.log(""),console.log(Es("document360-writer")),console.log(d(` cwd: ${e}`));let n=Hj(e);if(console.log(d(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(lI(e,t)),!Gj(e))console.log(q(" 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(ma(e),!Pn(e))for(let r of ga(e))console.log(q(` ${r}`))}catch{}try{let r=Vj(e);r.persisted&&r.appType?console.log(d(` \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=Jj(e);for(let s of da(r.applied))console.log(q(` ${s}`));if(r.reopenedForRedaction)for(let s of pa(r.reopenedForRedaction).split(/\r?\n/))console.log(q(` ${s}`))}catch{}try{let r=Ci(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:o}),s=r?Si(r,{pickable:!1,scaleFor:i=>en(e,i)}):null;if(s?.kind==="recommend"&&s.rec.note){let i=s.rec.tone==="warn"?q:d;for(let a of dl(s.rec.note).split(`
476
+ `))console.log(i(` ${a}`));s.rec.picker&&console.log(ee(` Pick one: ${s.rec.picker.options.map(a=>a.cmd).join(" \xB7 ")}`))}}catch{}}console.log(d(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}var l$=!1;function aI(e,t){try{let n=Ci(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:!1}),o=n?Si(n,{scaleFor:r=>en(e,r)}):null;if(o?.kind!=="recommend")return;if(o.rec.settled&&!l$){l$=!0;for(let r of dl(o.rec.settled).split(`
477
+ `))console.log(Q(` ${r}`))}else o.rec.settled&&!o.rec.lead&&console.log(d(" Nothing is waiting. /roadmap lists the optional campaign steps."));o.rec.lead&&console.log(d(` Next: ${Jr(o.rec.lead)}`))}catch{}}function lI(e,t){try{let n=u$(e,t),o=n.production?q(" \u26A0 PRODUCTION"):"",r=Kj(n.name,n.project.projectId);if(!r)return d(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...s$(r.idToken)??{},...s$(r.accessToken)??{}},i=s.email??s.preferred_username??"signed in";return Yj(r)&&!r.refreshToken?q(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):d(` Document360: ${i} \xB7 profile "${n.name}"${o}`)}catch(n){return d(` Document360: ${n.message.split(".")[0]}`)}}function cI(){console.error(""),console.error(`Sign in with your Claude subscription: run ${ee("claude")} once, then retry.`),console.error(` (No Claude Code? ${ee("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${ee("https://console.anthropic.com/settings/keys")}`)}function uI(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;Wj({uuid:t,name:r??Uj(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function dI(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||Bj(o,t).then(r=>{r&&Fj(n,r)}).catch(()=>{})}async function tf(e,t,n,o,r,s){let i=new Map,a=!1,c=!1;for await(let l of e.send(t))l.type==="tool"&&(c=!0),l.type==="text"&&l.delta.trim()&&(c=!0),l.type==="tool"&&d$.test(l.name)&&(a=!0),pI(l,o,r,n,i,s);if(a)try{let l=nI(await tI({cwd:r,profileName:s}));l&&console.log(l.startsWith("\u26A0")?q(l):l)}catch{}return{produced:c}}function pI(e,t,n,o,r,s){switch(e.type){case"session":t.uuid||uI(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let i=a$()?null:Zl(e.name,e.input,n,s);if(i){process.stdout.write(`
478
+
479
+ `);let c=[i.category,i.note].filter(f=>!!f).map(f=>Te(` \xB7 ${f}`)),l=i.loud?Te(" \xB7 ")+Qe(q(i.loud)):"";console.log(`${Q("\u25CF")} ${ee(Qe(Td(i.verb)))}${Qe(i.title)}${c.join("")}${l}`),r.set(e.id,{name:e.name,input:e.input,doc:!0,keepResult:i.keepResult});break}let a=tc(e.name,e.input,process.cwd());a&&(process.stdout.write(`
480
+
481
+ `),console.log(`${Te("\u25CF")} ${a.title}${a.arg!==null?Te(`${a.sep}(${a.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let i=Mt(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!i)break;let a=c=>c===1?"":"s";console.log(Te(` \u23BF Added ${i.added} line${a(i.added)}, removed ${i.removed} line${a(i.removed)}`));for(let c of i.lines)console.log(c);i.hidden>0&&console.log(d(` \u2026 +${i.hidden} more diff lines`));break}case"tool_result":{let i=r.get(e.id);if(!i)break;r.delete(e.id);let c=i.doc&&!i.keepResult&&!e.isError?{lines:[],hidden:0}:nc(e.output,4,e.isError||a$()?void 0:i.name,i.input),l=e.isError?L:Te;c.lines.forEach((f,g)=>console.log(l((g===0?" \u23BF ":" ")+f))),c.hidden>0&&console.log(d(` \u2026 +${c.hidden} lines`)),e.isError||sI(i.name,i.input,e.output,n);break}case"result":{process.stdout.write(`
482
+ `);let i=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(d(` (${Js(i)}\u2192${Js(e.outputTokens)} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(c$(t.uuid),t.titleFired||dI(t,n));break}case"error":console.error(""),e.kind==="limit"?console.log(q(`\u23F3 ${e.message}`)):console.error(L(`agent error: ${e.message}`)),e.note&&console.log(d(` ${e.note}`)),o.kind==="subscription"&&e.kind==="auth"&&cI();break}}import{render as SO}from"ink";import{resolveAuth as CO}from"document360-engine";import{useCallback as re,useEffect as it,useMemo as bc,useRef as ie,useState as ce}from"react";import{Box as je,Text as z,useApp as XI,useInput as QI,useStdout as JI}from"ink";import{existsSync as os,readFileSync as kc,readdirSync as ZI,writeFileSync as pv,mkdirSync as eL}from"node:fs";import{basename as Ei,dirname as tL,isAbsolute as nL,join as Ni}from"node:path";import{createSession as hv,classifyClaudeAuth as $f,CLAUDE_CODE_SETUP_HINT as oL,loginPkce as rL,toStoredTokens as sL,saveTokens as iL,getAccessToken as aL,D360AuthError as lL,resolveActiveProfile as St,resolveProjectId as cL,getArticle as uL,decodeJwtClaims as as,isExpired as tr,loadTokens as lo,clearTokens as dL,rememberSessionProject as pL,listStoredSessions as hL,tokensProjectId as fv,clearProfileProject as fL,setTitle as mL,slugify as gL,touchSession as ff,upsertSession as yL,generateTitle as mv,findByName as wL,listSessions as bL,renameSession as kL,suggestNextAction as $L,readProjectConfig as ke,writeProjectConfig as gv,autoModeEnabled as yv,autoBudgetUsd as $c,DEFAULT_AUTO_BUDGET_USD as vL,WRITER_DIRNAME as xL,readUserConfig as wv,writeUserConfig as RL,resolveAndPersistAppType as SL,detectAppType as bv,resolveModelSetting as vf,loadProfileMap as kv,applyPull as vc,computeSyncStatus as xc,lintDocs as rs,compareRemoteSources as CL,planPull as $v,recordRunSample as PL,pushArticles as TL,pushArticle as AL,PUSH_POOL_SIZE as EL,isPullWouldBlankError as vv,localArticleTitle as xv,establishBaselines as NL,rebaselineServerMeta as DL,inventoryRepo as jL,knownEnvironments as IL,currentEnvironments as Rv,sunsetEnvironment as Sv,resolveEnvironment as LL,planPartitions as mf,partitionEvenly as OL,screenshotPlaceholderIds as _L,trackedArticlePaths as ML,runPartitioned as Di,partitionCoverage as gf,estimateBulkCost as Cv,resolveModelForOperation as ji,readDocsPlan as Pv,checkForUpdate as Tv,detectInstallKind as FL,isSelfUpdatable as UL,devHintsGuidePath as Av,toolFeedbackPath as Ev,reconcileToolFeedback as WL,reconcileUpgradeActions as BL,stampArticles as ss,snapshotArticles as yf,listArticleFiles as HL,CONTENT_CAP_VERSION as GL,ENGINE_VERSION as Wv,DEFAULT_DOCS_DIR as xf,docsRootOf as qL,setProfileProject as VL,writeCrashLog as YL,applyStructureOrder as wf,orderSyncLine as bf,applyRelatedArticles as Nv,relatedSyncLine as Dv,reconcileDocsGit as KL,shareExplainedPath as zL,ensureDir as XL}from"document360-engine";Sr();Gn();import{spawn as h$}from"node:child_process";function hI(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function fI(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?h$([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):h$(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 nf(e){for(let[t,n]of hI())if(await fI(t,n,e))return!0;return!1}var f$=/\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 m$(e){let t=e.replace(/\s+$/,"").split(`
483
+ `),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 mI=/\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 g$(e){let t=e.trimEnd();if(!t)return null;let n=m$(t);return n>=2?{options:n}:/\?[\s*_"')\]]*$/.test(t)||f$.test(t)||mI.test(t)?{options:0}:null}function of(e,t){if(t.closed)return e;let n=e.split(`
484
+ `),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){f$.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(`
485
+ `)}var gI=/^(?:(?:run|use|try|execute)\s+)?['"`*]?(\/[a-z][a-z-]*)['"`*]?((?:\s+(?:--?[a-z][\w-]*|\S*[/\\]\S*|\d{1,3}[-_][\w.-]*|[\w.-]+\.(?:md|markdown)))*)/i;function yI(e,t){let n=m$(e);return n<2?[]:e.replace(/\s+$/,"").split(`
486
+ `).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=gI.exec(i);if(!a)return null;let c=a[1].slice(1).toLowerCase();return t.has(c)?`${a[1]}${(a[2]??"").replace(/\s+/g," ").trimEnd()}`:null})}function y$(e,t){let n=yI(e,t);return n.length<2||n.some(o=>o===null)?null:n}function wI(e){let t=e.split(`
487
+ `).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 es(e){if(e.usageLimit)return`${e.label}: ${e.usageLimit}`;let t=e.stderrTail?wI(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 bI={la:"local","l all":"local","local all":"local",pa:"portal","p all":"portal","portal all":"portal",sa:"skip","s all":"skip","skip all":"skip"},kI={L:"local",P:"portal",S:"skip"},$I={ya:"write","y all":"write","yes all":"write",na:"skip","n all":"skip","no all":"skip"},vI={Y:"write",N:"skip"};function w$(e,t,n){let o=e.trim(),r=o.toLowerCase().replace(/\s+/g," ");return t[r]??(o.length===1?n[o]??null:null)}function lc(e){return w$(e,bI,kI)}function b$(e){return w$(e,$I,vI)}function rf(e,t){let n=t?.max??12,o=t?.chrome??8;return Math.max(3,Math.min(n,(e??24)-o))}function cc(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 sf(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 k$(e){return e<2?null:`1-${e}`}function Rt(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:k$(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 $$(e){if(e.multi)return"pick with space, then enter to save \xB7 esc to cancel\u2026";let t=e.rows===void 0?null:k$(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 xI=[/\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],RI=[/\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/],SI=/^(read|glob|grep|ls|search|notebookread)$/i;function v$(e,t){return!e||!SI.test(e.trim())||RI.some(n=>n.test(t))?!1:xI.some(n=>n.test(t))}import{existsSync as CI,mkdirSync as PI,readFileSync as TI,writeFileSync as AI}from"node:fs";import{join as x$}from"node:path";import{writerDir as EI}from"document360-engine";function R$(e){return x$(EI(e),".sessions")}function S$(e,t){return x$(R$(e),`${t}.json`)}function C$(e,t,n){try{PI(R$(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");AI(S$(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function af(e,t){try{let n=S$(e,t);if(!CI(n))return[];let o=JSON.parse(TI(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var NI=e=>`\x1B]0;${e}\x07`,DI=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function P$(e){process.stdout.isTTY&&process.stdout.write(e)}function ts(e){P$(NI(e))}function uc(e){P$(DI(e))}var dc=["\xB7 "," \xB7"],pc="\u{1F7E3}";kl();var T$=e=>e===1?"":"s";function A$(e){let t=e.ran.length,n=t===0?"nothing to do":`${t} step${T$(t)} done`;switch(e.reason.kind){case"settled":return{tone:"ok",text:`Auto mode finished \u2014 that is the full round trip. ${n}.`};case"delivered":return{tone:"ok",text:`Auto mode finished \u2014 this round is delivered and your readers have it. ${n}.`};case"nothingToDo":return t===0?e.parked.length>0?{tone:"ok",text:"Auto mode had nothing it could run on its own \u2014 everything else is already written, saved and live."}:{tone:"ok",text:"Auto mode had nothing to do \u2014 everything is already written, saved and live."}:e.parked.length>0?{tone:"ok",text:`Auto mode finished what it could. ${n}.`}:{tone:"ok",text:`Auto mode finished \u2014 nothing left waiting. ${n}.`};case"onlyBlocked":return t===0?{tone:"warn",text:"Auto mode did not start anything \u2014 everything waiting needs a decision from you."}:{tone:"warn",text:`Auto mode went as far as it could on its own. ${n}, and the rest needs you.`};case"budget":return{tone:"warn",text:`Auto mode stopped at its spending limit \u2014 ${Ke(e.reason.spentUsd)} of ${Ke(e.reason.limitUsd)}. ${n}.`};case"stopped":return{tone:"warn",text:`Auto mode stopped \u2014 you asked it to. ${n}.`};case"repeat":case"noProgress":return{tone:"warn",text:`Auto mode stopped \u2014 ${e.reason.cmd} came back unfinished, and running it again would not have changed that. ${n}.`};case"maxSteps":return{tone:"warn",text:`Auto mode stopped after ${e.reason.steps} steps without reaching a finished state. ${n}.`}}}function E$(e){switch(e.reason.kind){case"settled":case"nothingToDo":return e.parked.length>0?{tone:"info",text:"What is left is with someone else. I am still in auto mode, so I will pick it up as soon as it lands."}:{tone:"info",text:"Nothing is waiting. I am still in auto mode, so the next time there is work I will pick it up."};case"delivered":return{tone:"info",text:"What is left needs you or a browser \u2014 /status lists it, and it costs nothing. I am still in auto mode for the next round."};case"budget":return{tone:"info",text:`/auto --budget <amount> raises the limit, then ${e.reason.next} is where it picks up.`};case"stopped":return{tone:"info",text:"/auto on picks the round trip back up from here. Nothing was undone."};case"onlyBlocked":return{tone:"info",text:"Clear the items above and I will carry on \u2014 /auto on starts me again."};case"repeat":case"noProgress":case"maxSteps":return{tone:"info",text:"This one needs a person. /status shows what stands between your work and your readers, and it costs nothing."}}}function N$(e){let t=[A$(e)],n=e.spentUsd>0?` \xB7 ${Ke(e.spentUsd)} of ${Ke(e.budgetUsd)}`:"";if(t.push({tone:"info",text:` ${ll({seconds:e.seconds,...e.activeSeconds!==void 0?{activeSeconds:e.activeSeconds}:{}})}${n}`}),e.ran.length>0){t.push({tone:"info",text:""}),t.push({tone:"info",text:" What I ran:"});for(let o of e.ran)t.push({tone:"info",text:` \xB7 ${o}`})}if(e.parked.length>0){t.push({tone:"info",text:""}),t.push({tone:"warn",text:` ${e.parked.length} thing${T$(e.parked.length)} need${e.parked.length===1?"s":""} you:`});for(let o of e.parked)t.push({tone:"warn",text:` \xB7 ${o.what}${o.cmd?` \u2192 ${o.cmd}`:""}`})}return e.reason.kind!=="settled"&&e.reason.kind!=="nothingToDo"&&e.reason.kind!=="delivered"&&e.ran.length>0&&(t.push({tone:"info",text:""}),t.push({tone:"info",text:" Everything already written, saved and published is kept \u2014 stopping never undoes work."})),t.push({tone:"info",text:""}),t.push(E$(e)),t}function D$(e,t){let n=A$(e).text,o=[`# Automatic run \u2014 ${t}`,"",n,""];if(o.push(`- Time: ${ll({seconds:e.seconds,...e.activeSeconds!==void 0?{activeSeconds:e.activeSeconds}:{}})}`),o.push(`- Spent: ${Ke(e.spentUsd)} of a ${Ke(e.budgetUsd)} limit`),o.push(""),o.push("## What ran"),o.push(""),e.ran.length===0)o.push("Nothing \u2014 see above for why.");else for(let r of e.ran)o.push(`- \`${r}\``);if(o.push(""),o.push("## What needs you"),o.push(""),e.parked.length===0)o.push("Nothing.");else for(let r of e.parked)o.push(`- ${r.what}${r.cmd?` Run \`${r.cmd}\`.`:""}`);return o.push(""),o.push(E$(e).text),o.push(""),o.join(`
488
+ `)}var j$=new Set(["/resolve","/pull","/screenshot","/login","/logout","/init","/reset","/discover","/genre","/style-guide","/scope","/profile","/project","/workspace","/model","/mcp","/share","/auto","/allow-prod"]),jI=new Set(["--skip-review","--skip-style","--skip-screenshots","--force"]),II=40,LI=2,OI=(e,t)=>e.what===t.what&&e.cmd===t.cmd;function hc(e,t){return e.some(n=>OI(n,t))?e:[...e,t]}function I$(e){let t=ln(e);if(!t||j$.has(t.cmd)||!Ar(t))return!1;for(let n of t.flags)if(jI.has(n))return!1;return!_I(t)}function _I(e){return e.cmd!=="/review"&&e.cmd!=="/write"&&e.cmd!=="/reorder"||e.flags.has("--all")||e.flags.has("--blocked")||e.flags.has("--stale")?!1:e.scope===void 0}function L$(e){let t=ln(e);return!t||t.cmd!=="/push"||t.scope!==void 0||t.flags.has("--all")||t.flags.size>0?e:"/push --all"}function O$(e){return!e||e.kind!=="cmd"?null:e.cmd}function MI(e){return e.kind==="answer"?{what:"I asked you a question and stopped to wait for the answer.",cmd:null}:e.kind==="prompt"?{what:`A step needs you to tell me what you want: \u201C${e.text}\u201D.`,cmd:null}:_$(e.cmd)}function _$(e){switch(ln(e)?.cmd??e.split(/\s+/)[0]??e){case"/resolve":return{what:"Some articles were changed both here and in Document360, and only you can say which copy survives.",cmd:"/resolve"};case"/pull":return{what:"Document360 has articles this repo has no folder for, and importing them changes your docs tree.",cmd:"/pull"};case"/screenshot":return{what:"Some screenshots are still to be taken \u2014 that needs your product running, so I never do it automatically.",cmd:"/screenshot"};case"/login":return{what:"The Document360 session needs signing in again, which happens in your browser.",cmd:"/login"};case"/discover":return{what:"The product questions are still out with your builder, so there is nothing I can answer tonight.",cmd:"/discover"};default:return{what:`${e} is a step I leave to you.`,cmd:e}}}var FI=(e,t)=>e.ran.filter(n=>n===t).length;function M$(e,t,n){let o=t.parked,r=n.maxSteps??II;if(t.ran.length>=r)return{kind:"stop",reason:{kind:"maxSteps",steps:t.ran.length},parked:o};if(e.heldHints>0){let a=e.heldHints;o=hc(o,{what:`${a} note${a===1?"":"s"} from your builder ${a===1?"is":"are"} waiting on code they haven't finished \u2014 I've asked whether ${a===1?"it's":"they're"} done.`,cmd:null})}if(e.restKind==="complete")return{kind:"stop",reason:{kind:"settled"},parked:o};if(e.restKind==="delivered"&&t.ran.length>0)return{kind:"stop",reason:{kind:"delivered"},parked:o};if(!e.lead&&!e.picker&&e.menu.length===0)return{kind:"stop",reason:{kind:"nothingToDo"},parked:o};e.picker&&(o=hc(o,{what:`${e.picker.title} \u2014 that one is yours to answer.`,cmd:null}));let s=[{cmd:O$(e.lead),lead:e.lead},...e.menu.map(a=>({cmd:a.startsWith("/")?a:null,lead:null}))],i=new Set;for(let a of s){if(!a.cmd){if(a.lead?.kind==="prompt"&&a.lead.text===Qo)return t.ran.includes(Qo)?{kind:"stop",reason:{kind:"noProgress",cmd:Qo},parked:o}:t.spentUsd>=n.budgetUsd?{kind:"stop",reason:{kind:"budget",spentUsd:t.spentUsd,limitUsd:n.budgetUsd,next:Qo},parked:o}:{kind:"prompt",text:Qo,parked:o};a.lead&&(o=hc(o,MI(a.lead)));continue}let c=L$(a.cmd);if(i.has(c))continue;if(i.add(c),!I$(a.cmd)){let f=ln(a.cmd);f&&j$.has(f.cmd)&&(o=hc(o,_$(a.cmd)));continue}if(t.ran[t.ran.length-1]===c)return{kind:"stop",reason:{kind:"repeat",cmd:c},parked:o};if(FI(t,c)>=LI)return{kind:"stop",reason:{kind:"repeat",cmd:c},parked:o};if(t.lastClosedItsTarget===!1&&t.lastLeadKey&&t.lastLeadKey===c)return{kind:"stop",reason:{kind:"noProgress",cmd:c},parked:o};let l=t.spentUsd+(n.nextCostUsd??0);return t.spentUsd>=n.budgetUsd||l>n.budgetUsd?{kind:"stop",reason:{kind:"budget",spentUsd:t.spentUsd,limitUsd:n.budgetUsd,next:c},parked:o}:{kind:"run",cmd:c,parked:o}}return{kind:"stop",reason:{kind:"onlyBlocked"},parked:o}}function F$(e,t,n){let o=[],r=new Set([t]),s=[O$(e.lead),...e.menu.map(i=>i.startsWith("/")?i:null)];for(let i of s){if(!i||!I$(i))continue;let a=L$(i);if(r.has(a))continue;r.add(a);let c=null;try{c=n(a)}catch{c=null}o.push({cmd:a,scale:c})}return o}var U$=()=>({fingerprint:null,counts:null,settled:0,spokenBaseline:null,lastSpokeAt:null,awaySince:null}),UI={hints:0,requests:0,answers:0,directives:0,held:0,heldAsked:0,briefMoved:!1};function lf(e,t){let n=e??UI;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),held:Math.max(0,t.held-n.held),heldAsked:Math.max(0,t.heldAsked-n.heldAsked),briefMoved:t.briefMoved&&!n.briefMoved}}var fc=e=>e.hints===0&&e.requests===0&&e.answers===0&&e.directives===0&&!e.briefMoved,W$=e=>e.hints+e.requests+e.answers+e.directives+(e.briefMoved?1:0),cf=(e,t)=>e-t>=6e5;function B$(e){let{now:t,lastInputAt:n,fingerprint:o,counts:r,occupied:s,prev:i}=e,a=cf(t,n),l=i.fingerprint!==null&&i.fingerprint!==o?0:i.settled+1,f={...i,fingerprint:o,counts:r,settled:l,awaySince:a?i.awaySince??t:null,spokenBaseline:i.spokenBaseline??r};if(a){let $=lf(f.spokenBaseline,r);return{memory:f,speak:null,waiting:fc($)?null:$}}if(s)return{memory:f,speak:null,waiting:null};if(l<2)return{memory:f,speak:null,waiting:null};let g=lf(i.spokenBaseline,r);return fc(g)?{memory:f,speak:null,waiting:null}:i.lastSpokeAt!==null&&t-i.lastSpokeAt<6e5?{memory:f,speak:null,waiting:null}:{memory:{...f,spokenBaseline:r,lastSpokeAt:t,settled:l},speak:g,waiting:null}}function H$(e,t,n){if(e.awaySince===null)return{kind:"none",memory:e};let o=t-e.awaySince,r=lf(e.spokenBaseline,n),s={...e,awaySince:null,counts:n,spokenBaseline:n,lastSpokeAt:fc(r)?e.lastSpokeAt:t};return fc(r)?{kind:"none",memory:s}:{kind:o>=36e5?"briefing":"delta",memory:s,delta:r,awayMs:o}}function Ti(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"}`),e.briefMoved&&t.push("an updated product brief"),t.length===0?"":t.length===1?t[0]:`${t.slice(0,-1).join(", ")} and ${t.at(-1)}`}function uf(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 G$(e){return`\u{1F4E5} ${Ti(e)} just arrived from your builder \u2014 /catch-up folds ${W$(e)===1?"it":"them"} into the docs.`}function q$(e,t){return`\u{1F4E5} While you were away (${uf(t)}): ${Ti(e)} from your builder \u2014 /catch-up folds ${W$(e)===1?"it":"them"} into the docs.`}function V$(e){return`\u{1F4E5} ${Ti(e)} waiting from your builder \xB7 tab to run /catch-up\u2026`}ba();import{publishGateVerdict as Rc,publishGateLines as kf,blockedPaths as QL,SKIP_STYLE_FLAG as jv,SKIP_SHOTS_FLAG as JL}from"document360-engine";import{askBuilder as ZL,openGapQuestions as eO}from"document360-engine";import{recordStructureReview as Iv}from"document360-engine";import{recordBriefConsumed as tO}from"document360-engine";import{retireArticle as nO,normalizeScope as Lv,declineImport as oO,undoDecline as rO}from"document360-engine";import{readReuseProposal as sO}from"document360-engine";oe();import{Box as Ai,Text as Be}from"ink";import{jsx as He,jsxs as ns}from"react/jsx-runtime";function WI({row:e,nameW:t,width:n}){let o=s=>cu(s,n),r=(s,i)=>He(Ai,{flexDirection:"column",children:s.map(i)});switch(e.t){case"head":return r(o(e.s),(s,i)=>He(Be,{color:ae,bold:!0,children:s},i));case"text":return r(o(e.s),(s,i)=>He(Be,{children:s},i));case"dim":return r(o(e.s),(s,i)=>He(Be,{dimColor:!0,children:s},i));case"sub":return r(o(e.s),(s,i)=>He(Be,{bold:!0,dimColor:!0,children:s},i));case"good":return r(o(e.s),(s,i)=>He(Be,{color:"green",children:s},i));case"step":{let s=o(`${e.n}. ${e.s}`);return He(Ai,{flexDirection:"column",children:s.map((i,a)=>a===0?ns(Be,{children:[He(Be,{color:ae,children:`${e.n}. `}),i.slice(`${e.n}. `.length)]},a):He(Be,{children:i},a))})}case"cmd":{let s=ha(e.name,e.s,t,n),i=s.descLines.slice(s.nameOwnLine?0:1);return ns(Ai,{flexDirection:"column",children:[ns(Be,{children:[" ",He(Be,{color:ae,children:s.nameCell}),!s.nameOwnLine&&He(Be,{dimColor:!0,children:` ${s.descLines[0]??""}`})]}),i.map((a,c)=>He(Be,{dimColor:!0,children:`${s.indent}${a}`},c))]})}case"gap":return He(Be,{children:" "})}}function Y$({tab:e,scroll:t,rows:n,width:o,version:r,engineVersion:s}){let i=bt[e]??bt[0],a=lu(i.rows),c=Math.max(20,o-2),l=6+bt.reduce((C,x)=>C+x.label.length+4,0),f="\u2500".repeat(Math.min(l,c)),g=`\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}`,$=Im({rows:n,inner:c,barWidth:l,footerWidth:g.length}),{visible:T,above:A,below:S}=jm(i.rows,{width:o,budget:$,scroll:t,nameW:a});return ns(Ai,{flexDirection:"column",paddingX:1,children:[ns(Be,{children:[He(Be,{color:ae,bold:!0,children:"Help "}),bt.map((C,x)=>x===e?He(Be,{color:"white",backgroundColor:ae,bold:!0,children:` ${C.label} `},C.key):He(Be,{children:` ${C.label} `},C.key))]}),He(Be,{color:ae,children:f}),ns(Ai,{flexDirection:"column",marginTop:1,children:[A>0?He(Be,{dimColor:!0,children:`\u22EF ${A} more above`}):null,T.map((C,x)=>He(WI,{row:C,nameW:a,width:o},A+x)),S>0?He(Be,{dimColor:!0,children:`\u22EF ${S} more below`}):null]}),He(Be,{dimColor:!0,children:`
489
+ \u2190/\u2192 or tab switch \xB7 1-5 jump${A+S>0?" \xB7 \u2191\u2193 scroll":""} \xB7 esc close \xB7 d360-writer v${r} \xB7 engine v${s}`})]})}var BI=/^(?:\d+[.)]|[-*•])\s+/;function K$(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
490
+ `)){let i=s.trim().replace(BI,""),a=i.match(/^`([^`]+)`$/);a&&(i=a[1].trim());let c=i.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!c||!o.has(c[1].toLowerCase()))continue;let l=`/${c[1].toLowerCase()}${c[2]?` ${c[2]}`:""}`;if(r.includes(l)||r.push(l),r.length>=n)break}return r}oe();function Zo(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function rt(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function mc(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var HI=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function df(e,t,n){if(!HI.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 pf(e){return e.replace(/^[\w.-]+\//,"")}var gc=16,z$={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function ao(e){return typeof e=="string"?e:e.cmd}function X$(e){return typeof e=="string"?void 0:e.desc}function hf(e){return e.trim().split(/\s+/).slice(1).join(" ")}function Q$(e,t){let n=hf(t);return e.some(r=>ao(r).trim()===t.trim()||!!n&&hf(ao(r))===n)?e.filter(r=>ao(r).trim()!==t.trim()&&!(n&&hf(ao(r))===n)):[]}import{isDirectiveMention as iO,stripDirectiveMention as aO,appendDirective as lO,reconcileTestidRequest as cO,builderChannelWired as uO,pendingFingerprint as dO}from"document360-engine";var GI=/\[Pasted text #\d+ \+\d+ lines?\]/g;function J$(e){return e.replace(/\r\n?/g,`
491
+ `)}function Z$(e){return e.includes(`
492
+ `)||e.length>200}function ev(e,t){let n=t.split(`
493
+ `).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function tv(e,t){return e.replace(GI,n=>t.get(n)??n)}function nv(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function yc(e,t){let n=Math.max(1,t),o=[],r=0;for(let s of e.split(`
494
+ `)){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 wc(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function ov(e,t,n){let o=wc(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 rv(e,t,n){let o=e[wc(e,t)];return n==="start"?o.start:o.end}var qI=new Set(["Edit","Write","MultiEdit","NotebookEdit"]),sv={hint:"hint",message:"message",state:"state file",roadmap:"roadmap",directive:"directives",feedback:"tool-feedback"},VI=new Set(["hint","message","state"]),YI=["hint","message","roadmap","directive","feedback","state"];function KI(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 iv(e,t){let n=e==="Read"?"read":qI.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=KI(r.slice(i+s.length));return a?{category:a,verb:n,path:r}:null}function av(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 YI)for(let s of["updated","read"]){let i=t.get(`${r}:${s}`)?.size??0;i!==0&&o.push(VI.has(r)?`${i} ${sv[r]}${i===1?"":"s"} ${s}`:`${sv[r]} ${s}`)}return o.length>0?o.join(" \xB7 "):null}function lv(e,t,n){let o=Math.max(1,n),r=e.split(`
495
495
  `),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 c=s-t;return{text:[c>0?a.slice(c*o):a,...r.slice(i+1)].join(`
496
- `),truncated:i>0||c>0}}}return{text:e,truncated:!1}}function ev(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 tv(e){let t=!1,n=0,o=0;for(let r of e.split(`
497
- `)){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 Jo,jsx as q,jsxs as he}from"react/jsx-runtime";var YL={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL",auto:"auto \u2014 right-sized for docs \xB7 /model to change"},Cv=` 1. /init \u2014 pick your Document360 environment & scaffold config
496
+ `),truncated:i>0||c>0}}}return{text:e,truncated:!1}}function cv(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 uv(e){let t=!1,n=0,o=0;for(let r of e.split(`
497
+ `)){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 he}from"react/jsx-runtime";var pO={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL",auto:"auto \u2014 right-sized for docs \xB7 /model to change"},Ov=` 1. /init \u2014 pick your Document360 environment & scaffold config
498
498
  2. /login \u2014 sign in & pick your Document360 project (workspace auto-selected)
499
- 3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function zL(e,t,n,o){let r=mf(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=gf(e),a=ke(e),c=(a?.docsDir??yf).replace(/\/+$/,""),l=a?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${c}/ + config`,f={version:t,engineVersion:Nv,captureVersion:bt(),claude:s,model:i.model,modelSource:YL[i.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:a!==null,mode:l};if(a===null)return f;try{let g=Rt(e,o);f.profile=g.name,f.apiUrl=g.connection.apiUrl,f.prod=g.production,f.project=g.project.projectName??g.project.projectId??"(chosen at login)";let k=lo(g.name,g.project.projectId);if(k){let T={...ls(k.idToken)??{},...ls(k.accessToken)??{}},A=T.email??T.preferred_username??"signed in";Zo(k)?k.refreshToken&&(f.who=A,f.loggedOut=!1,f.sessionHint="session expired \u2014 refreshing\u2026"):(f.who=A,f.loggedOut=!1,f.sessionHint=`session valid until ${new Date(k.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return f}var XL=e=>e.mode==="local-only"?e.path:e.plan.path;function QL(e,t){try{let n=Rt(e,t),o=lo(n.name,n.project.projectId);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...ls(o.idToken)??{},...ls(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return Zo(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 Pv=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],cs=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],JL="Ask me to write or update an article\u2026",Tv=2e3,ZL=new Set(Wo.map(e=>e.name));function as({ch:e,dim:t}){let[n,o]=ce(!0);return it(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),q(Y,{inverse:n,color:t&&!n?"gray":void 0,children:e})}function jn({rows:e,cursor:t,cap:n,render:o}){let r=oc(e.length,t,n);return he(Jo,{children:[r.above>0?q(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?q(Y,{color:"gray",children:` \u22EF ${r.below} more below`}):null]})}var Av=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Ev(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var eO=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function tO({startTime:e,chars:t}){let[n,o]=ce(0),r=ie(Date.now());it(()=>{let l=setInterval(()=>o(f=>f+1),120);return()=>clearInterval(l)},[]);let s=cs[n%cs.length],i=Pv[Math.floor(n/16)%Pv.length],a=qy(e,r.current,Date.now()),c=Math.round(t/4);return he(je,{children:[q(Y,{color:le,children:` ${s} ${i}\u2026 `}),q(Y,{color:"gray",children:`(${Pn(a)} \xB7 ~${c} tokens \xB7 esc to interrupt)`})]})}function nO({step:e,cmd:t,startedAt:n,spentUsd:o,budgetUsd:r}){let[,s]=ce(0);it(()=>{let c=setInterval(()=>s(l=>l+1),1e3);return()=>clearInterval(c)},[]);let i=Math.max(0,Math.round((Date.now()-n)/1e3)),a=o>0?` \xB7 ${kt(o)} of ${Ye(r)}`:` \xB7 limit ${Ye(r)}`;return he(je,{flexDirection:"column",children:[he(je,{children:[q(Y,{color:le,children:` \u23F5\u23F5 auto \xB7 step ${e} \xB7 `}),q(Y,{color:le,bold:!0,children:t})]}),q(Y,{color:"gray",children:` ${Pn(i)}${a} \xB7 esc stops`})]})}function oO({text:e}){let[t,n]=ce(0);return it(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),q(je,{paddingX:1,children:q(Y,{color:le,children:`${cs[t%cs.length]} ${e}`})})}var rO=12e4;function sO({p:e}){let[t,n]=ce(0);it(()=>{let x=setInterval(()=>n(E=>E+1),150);return()=>clearInterval(x)},[]);let o=cs[t%cs.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>=rO,c=e.verb??"Converting",l=e.unit??"article",f=e.rows.reduce((x,E)=>x+E.items,0),g=e.rows.reduce((x,E)=>x+(E.status==="done"?E.items:E.itemsDone??0),0),k=c.toLowerCase(),T=e.rows,A=0;if(T.length>uc){let x=T.findIndex(I=>I.status==="active"||I.status==="pending"),E=Math.max(0,Math.min(x-2,T.length-uc));A=T.slice(0,E).filter(I=>I.status==="done").length,T=T.slice(E,E+uc)}let S=Math.min(40,Math.max(...T.map(x=>sf(x.label).length),0)),C=x=>x==="failed"?"red":x==="active"?le:void 0;return he(je,{flexDirection:"column",children:[he(je,{children:[q(Y,{color:le,children:` ${o} ${c} ${f} ${l}${f===1?"":"s"} `}),q(Y,{color:"gray",children:e.agentless?`\xB7 ${g}/${f} ${l}${f===1?"":"s"} \xB7 ${Pn(r)} \xB7 esc to stop`:`\xB7 ${g}/${f} ${l}${f===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 ${Pn(r)} \xB7 esc to stop`})]}),A>0&&q(Y,{dimColor:!0,children:` \u2714 +${A} done`}),T.map(x=>he(Y,{color:C(x.status),dimColor:x.status==="done"||x.status==="pending",children:[` ${U$[x.status]} ${sf(x.label).padEnd(S)}`,x.status==="active"&&x.itemsDone!==void 0?` (${x.itemsDone}/${x.items} ${l}${x.items===1?"":"s"})`:x.status!=="pending"?` (${x.items} ${l}${x.items===1?"":"s"})`:"",x.status==="active"?` \u2190 ${k}\u2026`:""]},x.label)),a&&q(Y,{color:"yellow",children:` \u26A0 no activity for ${Pn(s)} \u2014 press esc to stop if it's wedged`}),a&&e.stalledNote?q(Y,{color:"yellow",children:` ${e.stalledNote}`}):null]})}var iO=10800*1e3;function Dv({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=NI(),[s,i]=ce(n),[a,c]=ce(null),[l,f]=ce({text:"",pos:0}),g=l.text,k=re(p=>{f(m=>{let u=typeof p=="function"?p(m.text):p;return{text:u,pos:u.length}})},[]),T=re(p=>{f(m=>({text:m.text.slice(0,m.pos)+p+m.text.slice(m.pos),pos:m.pos+p.length}))},[]),A=re(()=>{f(p=>{if(p.pos===0)return p;let m=p.text.slice(0,p.pos),u=K$(m)??m.slice(0,-1);return{text:u+p.text.slice(p.pos),pos:u.length}})},[]),[S,C]=ce(!1),[x,E]=ce(!1),[I,W]=ce(0),[V,B]=ce(!1),[ae,me]=ce(null),[Re,Ie]=ce(null),[ge,we]=ce([]),Z=ie(!1),Ee=ie(!1),_e=ie(null),Ge=ie(!1),[In,Ce]=ce(!1),Ae=ie(!1),Ze=ie(0),[nn,St]=ce(!1),[co,er]=ce(!1),[tr,us]=ce(null),[kc,Ft]=ce(0),Ut=ie(0),[Ln,On]=ce(0),[pn,uo]=ce(null),[on,fe]=ce(null),He=ie(new Map),hn=ie(0),nr=ie([]),Wt=ie(null);Wt.current===null&&(Wt.current=rv({cwd:e,profileName:s,allowProdWrites:!1}));let fn=ie({uuid:null,firstPrompt:null,titleFired:!1}),ds=ie(new Map),vf=ie(null),$c=ie(null),Ei=ie(cv().verboseTranscript===!0),_n=ie(!1),vc=ie([]),De=ie([]),mn=ie([]),Bt=ie([]),or=ie(null),[xf,po]=ce(null),xc=ie(null),[gn,ho]=ce(null),[Ht,rr]=ce(null),[Gt,sr]=ce(null),[ot,ir]=ce(null),[ct,fo]=ce(null),[Ct,ar]=ce(null),[qt,lr]=ce(null),[Vt,mo]=ce(null),[Pt,yn]=ce(null),[at,ps]=ce(null),Rf=ie({value:0,at:0}),Sf=ie({value:0,at:0}),wn=re((p,m)=>{let{index:u,memory:y}=Zh(Sf.current,Number(p),m);return Sf.current=y,u},[]),[mt,go]=ce(null),[Cf,yo]=ce(null);it(()=>fe(null),[ge]);let[Tt,wo]=ce(null),[ut,cr]=ce(null),[Pf,Rc]=ce([]),bo=ie([]),hs=ie(!1),fs=ie(null),Sc=ie(null),[Mv,Tf]=ce(!1),Xe=ie(null),[dt,Ni]=ce(null),Di=ie(!1),ko=ie(!1),ji=ie(!1),Cc=ie(null),[ur,Af]=ce(null),Pc=ie(null),Fe=ie(null),[dr,be]=ce(null),[Ef,qe]=ce(null),Ii=ie(!1),ms=ie(null),$o=ie(null),[At,vo]=ce(null),[gs,xo]=ce(null),Mn=!!(dt||Gt||ot||ct||Ct||qt||Vt||Pt||at||mt||Tt||ut||At||gs),ys=hc(()=>{try{return lv(ke(e))}catch{return!1}},[e,I]),Nf=qt?{verb:"publish live",cancel:"leave as drafts",rows:qt.rows.length+1}:Ct?{verb:"push as drafts",rows:Ct.rows.length}:mt?{verb:"choose it",rows:mt.rows.length}:Vt?{verb:"run it",rows:Vt.rows.length}:Pt?{verb:"open it",cancel:"close",rows:Pt.rows.length-1}:ot?{verb:"switch",rows:ot.rows.length}:ct?{verb:"switch",rows:ct.rows.length}:Gt?{verb:"use it",rows:Gt.rows.length}:Ht?{verb:"switch",rows:Ht.rows.length,extra:["s this session only"]}:gn?{verb:"use it",rows:_t.length}:ut?{verb:"save",multi:!0}:null,[Df,Ro]=ce(0),[Et,So]=ce(0),[Fv,jf]=ce(0),Tc=hc(()=>{try{let p=gf(e);return p.source==="auto"?`${p.model} (auto)`:p.model}catch{return null}},[e,Fv]),{stdout:rt}=jI(),[,Uv]=ce(0),If=ie(`${rt.columns??80}x${rt.rows??24}`),et=re(()=>Math.max(20,(rt.columns??80)-1),[rt]),Li=re(p=>{nr.current.push(p);let m=Rd(p,et());pr.current+=m.split(`
500
- `).length+1,console.log(m)},[et]),Ac=ie([]),Oi=re(()=>{let p=Ac.current;if(p.length===0)return;Ac.current=[];let m=J$(p);m&&Li({kind:"note",tone:"info",text:`\u25CF Housekeeping ${m}`})},[Li]),h=re(p=>{Oi(),Li(p)},[Li,Oi]),pt=ie({printed:[],armed:[],printedAt:0}),_i=ie(null),Mi=ie([]),pr=ie(0),Fi=re(()=>Xe.current!==null,[]),st=re((p,m)=>{Fi()||(Ze.current++,pt.current.armed=[],me(p),Ie(m??null))},[Fi]),Kt=re(()=>{Ze.current++,pt.current.armed=[],me(null),Ie(null)},[]),ws=re(p=>{Fi()||(Ze.current++,pt.current.armed=[],me(null),Ie(p))},[Fi]),se=re(p=>st(p,Jr({kind:"cmd",cmd:p,reason:""})),[st]),bn=re((p,m)=>{if(!m?.silent&&p.note&&h({kind:"note",tone:m?.tone??p.tone,text:p.note}),!m?.silent&&p.note?.includes(".d360-writer/ \u2014 your articles"))try{let P=NL(e);DL(OI(P)),ov(P,`${new Date().toISOString()}
501
- `)}catch{}p.picker&&(we(p.picker.options.map(P=>({cmd:P.cmd,desc:P.desc}))),yo(p.picker.title),Mi.current=p.picker.exclusive?p.picker.options.map(P=>P.cmd.trim()):[]),!m?.silent&&p.note&&(pt.current.printed=p.menu,pt.current.printedAt=pr.current);let y=pr.current-pt.current.printedAt<Math.max(8,(rt.rows??24)-4)&&Ek(pt.current.printed,p.menu)?p.menu:[];p.lead?(p.lead.kind==="answer"?ws(Jr(p.lead,y.length)):st(p.lead.kind==="cmd"?p.lead.cmd:p.lead.text,Jr(p.lead,y.length)),!m?.silent&&p.note&&(_i.current=es(p.lead))):!p.picker&&(!m?.silent||p.restKind!==null)&&(Kt(),y.length>0&&ws(p.restKind==="delivered"?`1\u2013${y.length} when you want one \xB7 nothing is owed \xB7 or just ask me anything\u2026`:`1\u2013${y.length} to pick a campaign step \xB7 nothing is waiting \xB7 or just ask me anything\u2026`)),pt.current.armed=y},[h,st,ws,e,rt]),Pe=re((p,m,u="info")=>{pt.current.armed=[],p&&h({kind:"note",tone:u,text:p}),m&&(m.kind==="answer"?ws(Jr(m)):st(m.kind==="cmd"?m.cmd:m.text,Jr(m)),_i.current=p?es(m):null)},[h,st,ws]),kn=re((p,m,u,y="info")=>{if(p.producedNothing){Pe("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}p.handedBack||Pe(m,u,y)},[Pe]),[Co,Ec]=ce(null),[Wv,Lf]=ce(!1),$n=re((p,m)=>{Ec(p),Lf(!1),h({kind:"note",tone:"info",text:m?.hint??"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[h]),Nc=re(()=>{qL(e,new Date().toISOString());let p=Qw(e);p&&(h({kind:"note",tone:"info",text:p.lines.join(`
502
- `)}),$n(p.prompt,VL(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,$n]),Dc=ie(!1),jc=re(async()=>{try{if(Dc.current||!vL($L())||ke(e)?.mode==="engineer")return;let p=await kL({pkg:qr,currentVersion:o,force:!0});if(!p.updateAvailable||!p.latest)return;Dc.current=!0,h({kind:"note",tone:"info",text:`\u2B06 Updating ${qr} ${p.current} \u2192 ${p.latest}\u2026 (wait for the \u2713 before you /exit)`}),er(!0);let m=await Pl().finally(()=>er(!1));m.ok?(h({kind:"note",tone:"ok",text:`\u2713 Updated to v${p.latest} \u2014 run /exit, then relaunch to apply.`}),se("/exit"),us(p.latest)):h({kind:"note",tone:"warn",text:`Update available (v${p.latest}) but auto-update failed. ${Cl(m.output)}`})}catch{}},[e,o,h,se]),bs=ie(!1),Ic=ie(null),Of=re(async p=>{if(!bs.current)try{let m=ke(e);if(!m)return;let u=_f.current;if(!u)return;if(u.pushConsent!=="on"){if(u.uncommitted===0)return;bs.current=!0;try{let P=await EL(e,m);if(P.commit?.ok)Ic.current=null;else if(P.commit&&!P.commit.ok){let F=`${P.commit.reason}:${P.commit.detail??""}`;Ic.current!==F&&(Ic.current=F,h({kind:"note",tone:"warn",text:`\u26A0 Couldn't save your docs work to git \u2014 ${to(P.commit.reason,P.commit.detail)}`}))}}finally{bs.current=!1}return}if(u.uncommitted===0&&u.unpushed===0&&!p.pull)return;bs.current=!0;try{let{lines:P,changed:F}=await bl(e,m);for(let G of P)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});F&&W(G=>G+1)}finally{bs.current=!1}}catch{}},[e,h]),Po=re(p=>{let m=Je(e,s);return m.ok?!0:(h({kind:"note",tone:"warn",text:m.reason}),$o.current=p,se("/login"),!1)},[e,s,h,se]),[Ui,Lc]=ce(null),_f=ie(null),Mf=ie(null),gt=re((p,m)=>{let u=vi(e,s,{claudeMissing:mf(t).state==="missing",allowAutoAudit:p,genreUnknown:Ge.current,pendingAnswer:_e.current,lastCommand:Mf.current});return _f.current=u?.handoff??null,u?$i(u,{header:m,pickable:!0,scaleFor:y=>Zt(e,y)}):{kind:"idle"}},[e,s,t]),Oc=ie(Date.now()),ks=ie(N$()),Ff=ie(0),[Uf,Wf]=ce(null),$s=ie(!0),hr=ie(!1),Wi=ie(0),vs=ie(0);it(()=>{let p=setInterval(()=>{if($s.current){Wi.current=0,vs.current=0;return}if(!S)try{if(!rs(bv(e)))return;if(zt(e).status==="current"){$s.current=!0,Wi.current=0,vs.current=0;let u=hr.current?`\u2713 Your builder finished the protocol update (v${Me}) \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:",y=gt(!1,u),P=y.kind==="recommend"?y.rec:null;Ec(null),P?.note?bn(P,{tone:"ok"}):(h({kind:"note",tone:"ok",text:`${u}${P?.lead?` ${Zr(P.lead)}`:""}`}),P?.lead||P?.picker?bn(P,{silent:!0}):hr.current||st("write the docs for this repo")),W(F=>F+1);return}if(hr.current)return;Wi.current+=1;let m=Wi.current;if((m===4||m%15===0)&&vs.current<3){vs.current+=1;let u=vs.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";h({kind:"note",tone:"info",text:Sn(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${u}`:`\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.${u}`})}}catch{}},4e3);return()=>clearInterval(p)},[e,S,h,gt,bn,st]),it(()=>{let p=xf??Ci(e);if(!S){rc(0),ns(`${ic} ${p}`);return}rc(3);let m=0;ns(`${sc[0]} ${p}`);let u=setInterval(()=>{m=(m+1)%sc.length,ns(`${sc[m]} ${p}`)},400);return()=>clearInterval(u)},[S,e,xf]),it(()=>()=>rc(0),[]),it(()=>{let p=performance.now(),m=[],u=(w,$)=>{let v=performance.now();try{return $()}finally{let b=Math.round(performance.now()-v);b>=80&&m.push(`${w}: ${b}ms`)}};h({kind:"banner",info:u("banner",()=>zL(e,o,t,s))});let y=mf(t).state==="missing";if(y&&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.
503
- ${MI}
499
+ 3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function hO(e,t,n,o){let r=$f(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=vf(e),a=ke(e),c=(a?.docsDir??xf).replace(/\/+$/,""),l=a?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${c}/ + config`,f={version:t,engineVersion:Wv,captureVersion:kt(),claude:s,model:i.model,modelSource:pO[i.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:a!==null,mode:l};if(a===null)return f;try{let g=St(e,o);f.profile=g.name,f.apiUrl=g.connection.apiUrl,f.prod=g.production,f.project=g.project.projectName??g.project.projectId??"(chosen at login)";let $=lo(g.name,g.project.projectId);if($){let T={...as($.idToken)??{},...as($.accessToken)??{}},A=T.email??T.preferred_username??"signed in";tr($)?$.refreshToken&&(f.who=A,f.loggedOut=!1,f.sessionHint="session expired \u2014 refreshing\u2026"):(f.who=A,f.loggedOut=!1,f.sessionHint=`session valid until ${new Date($.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return f}var fO=e=>e.mode==="local-only"?e.path:e.plan.path;function mO(e,t){try{let n=St(e,t),o=lo(n.name,n.project.projectId);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...as(o.idToken)??{},...as(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return tr(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 _v=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],ls=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],gO="Ask me to write or update an article\u2026",Mv=2e3,yO=new Set(Bo.map(e=>e.name));function is({ch:e,dim:t}){let[n,o]=ce(!0);return it(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),V(z,{inverse:n,color:t&&!n?"gray":void 0,children:e})}function Ln({rows:e,cursor:t,cap:n,render:o}){let r=cc(e.length,t,n);return he(er,{children:[r.above>0?V(z,{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(z,{color:"gray",children:` \u22EF ${r.below} more below`}):null]})}var Fv=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Uv(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var wO=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function bO({startTime:e,chars:t}){let[n,o]=ce(0),r=ie(Date.now());it(()=>{let l=setInterval(()=>o(f=>f+1),120);return()=>clearInterval(l)},[]);let s=ls[n%ls.length],i=_v[Math.floor(n/16)%_v.length],a=Jy(e,r.current,Date.now()),c=Math.round(t/4);return he(je,{children:[V(z,{color:ae,children:` ${s} ${i}\u2026 `}),V(z,{color:"gray",children:`(${An(a)} \xB7 ~${c} tokens \xB7 esc to interrupt)`})]})}function kO({step:e,cmd:t,startedAt:n,spentUsd:o,budgetUsd:r}){let[,s]=ce(0);it(()=>{let c=setInterval(()=>s(l=>l+1),1e3);return()=>clearInterval(c)},[]);let i=Math.max(0,Math.round((Date.now()-n)/1e3)),a=o>0?` \xB7 ${$t(o)} of ${Ke(r)}`:` \xB7 limit ${Ke(r)}`;return he(je,{flexDirection:"column",children:[he(je,{children:[V(z,{color:ae,children:` \u23F5\u23F5 auto \xB7 step ${e} \xB7 `}),V(z,{color:ae,bold:!0,children:t})]}),V(z,{color:"gray",children:` ${An(i)}${a} \xB7 esc stops`})]})}function $O({text:e}){let[t,n]=ce(0);return it(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),V(je,{paddingX:1,children:V(z,{color:ae,children:`${ls[t%ls.length]} ${e}`})})}var vO=12e4;function xO({p:e}){let[t,n]=ce(0);it(()=>{let x=setInterval(()=>n(E=>E+1),150);return()=>clearInterval(x)},[]);let o=ls[t%ls.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>=vO,c=e.verb??"Converting",l=e.unit??"article",f=e.rows.reduce((x,E)=>x+E.items,0),g=e.rows.reduce((x,E)=>x+(E.status==="done"?E.items:E.itemsDone??0),0),$=c.toLowerCase(),T=e.rows,A=0;if(T.length>gc){let x=T.findIndex(j=>j.status==="active"||j.status==="pending"),E=Math.max(0,Math.min(x-2,T.length-gc));A=T.slice(0,E).filter(j=>j.status==="done").length,T=T.slice(E,E+gc)}let S=Math.min(40,Math.max(...T.map(x=>pf(x.label).length),0)),C=x=>x==="failed"?"red":x==="active"?ae:void 0;return he(je,{flexDirection:"column",children:[he(je,{children:[V(z,{color:ae,children:` ${o} ${c} ${f} ${l}${f===1?"":"s"} `}),V(z,{color:"gray",children:e.agentless?`\xB7 ${g}/${f} ${l}${f===1?"":"s"} \xB7 ${An(r)} \xB7 esc to stop`:`\xB7 ${g}/${f} ${l}${f===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 ${An(r)} \xB7 esc to stop`})]}),A>0&&V(z,{dimColor:!0,children:` \u2714 +${A} done`}),T.map(x=>he(z,{color:C(x.status),dimColor:x.status==="done"||x.status==="pending",children:[` ${z$[x.status]} ${pf(x.label).padEnd(S)}`,x.status==="active"&&x.itemsDone!==void 0?` (${x.itemsDone}/${x.items} ${l}${x.items===1?"":"s"})`:x.status!=="pending"?` (${x.items} ${l}${x.items===1?"":"s"})`:"",x.status==="active"?` \u2190 ${$}\u2026`:""]},x.label)),a&&V(z,{color:"yellow",children:` \u26A0 no activity for ${An(s)} \u2014 press esc to stop if it's wedged`}),a&&e.stalledNote?V(z,{color:"yellow",children:` ${e.stalledNote}`}):null]})}var RO=10800*1e3;function Bv({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=XI(),[s,i]=ce(n),[a,c]=ce(null),[l,f]=ce({text:"",pos:0}),g=l.text,$=re(p=>{f(m=>{let u=typeof p=="function"?p(m.text):p;return{text:u,pos:u.length}})},[]),T=re(p=>{f(m=>({text:m.text.slice(0,m.pos)+p+m.text.slice(m.pos),pos:m.pos+p.length}))},[]),A=re(()=>{f(p=>{if(p.pos===0)return p;let m=p.text.slice(0,p.pos),u=nv(m)??m.slice(0,-1);return{text:u+p.text.slice(p.pos),pos:u.length}})},[]),[S,C]=ce(!1),[x,E]=ce(!1),[j,W]=ce(0),[Y,B]=ce(!1),[ue,fe]=ce(null),[Re,Ie]=ce(null),[ge,we]=ce([]),Z=ie(!1),Ae=ie(!1),_e=ie(null),ze=ie(!1),[On,Ce]=ce(!1),Ee=ie(!1),Ze=ie(0),[on,Ct]=ce(!1),[co,uo]=ce(!1),[cs,us]=ce(null),[Ii,rn]=ce(0),Pt=ie(0),[ds,Bt]=ce(0),[_n,po]=ce(null),[fn,mn]=ce(null),me=ie(new Map),Ge=ie(0),ct=ie([]),Tt=ie(null);Tt.current===null&&(Tt.current=hv({cwd:e,profileName:s,allowProdWrites:!1}));let gn=ie({uuid:null,firstPrompt:null,titleFired:!1}),ps=ie(new Map),Tf=ie(null),Cc=ie(null),Li=ie(wv().verboseTranscript===!0),Mn=ie(!1),Pc=ie([]),De=ie([]),yn=ie([]),Ht=ie([]),nr=ie(null),[Af,ho]=ce(null),Tc=ie(null),[wn,fo]=ce(null),[Gt,or]=ce(null),[qt,rr]=ce(null),[st,sr]=ce(null),[ut,mo]=ce(null),[At,ir]=ce(null),[Vt,ar]=ce(null),[Yt,go]=ce(null),[Et,bn]=ce(null),[at,hs]=ce(null),Ef=ie({value:0,at:0}),Nf=ie({value:0,at:0}),kn=re((p,m)=>{let{index:u,memory:y}=sf(Nf.current,Number(p),m);return Nf.current=y,u},[]),[gt,yo]=ce(null),[Df,wo]=ce(null);it(()=>mn(null),[ge]);let[Nt,bo]=ce(null),[dt,lr]=ce(null),[jf,Ac]=ce([]),ko=ie([]),fs=ie(!1),ms=ie(null),Ec=ie(null),[Kv,If]=ce(!1),Xe=ie(null),[pt,Oi]=ce(null),_i=ie(!1),$o=ie(!1),Mi=ie(!1),Nc=ie(null),[cr,Lf]=ce(null),Dc=ie(null),Fe=ie(null),[ur,be]=ce(null),[Of,qe]=ce(null),gs=ie(!1),ys=ie(null),jc=ie(null),vo=ie(null),[Dt,xo]=ce(null),[ws,Ro]=ce(null),Fn=!!(pt||qt||st||ut||At||Vt||Yt||Et||at||gt||Nt||dt||Dt||ws),bs=bc(()=>{try{return yv(ke(e))}catch{return!1}},[e,j]),_f=Vt?{verb:"publish live",cancel:"leave as drafts",rows:Vt.rows.length+1}:At?{verb:"push as drafts",rows:At.rows.length}:gt?{verb:"choose it",rows:gt.rows.length}:Yt?{verb:"run it",rows:Yt.rows.length}:Et?{verb:"open it",cancel:"close",rows:Et.rows.length-1}:st?{verb:"switch",rows:st.rows.length}:ut?{verb:"switch",rows:ut.rows.length}:qt?{verb:"use it",rows:qt.rows.length}:Gt?{verb:"switch",rows:Gt.rows.length,extra:["s this session only"]}:wn?{verb:"use it",rows:Ut.length}:dt?{verb:"save",multi:!0}:null,[Mf,So]=ce(0),[jt,Co]=ce(0),[zv,Ff]=ce(0),Ic=bc(()=>{try{let p=vf(e);return p.source==="auto"?`${p.model} (auto)`:p.model}catch{return null}},[e,zv]),{stdout:et}=JI(),[,Xv]=ce(0),Uf=ie(`${et.columns??80}x${et.rows??24}`),Wf=ie(et.columns??80),tt=re(()=>Math.max(20,(et.columns??80)-1),[et]),Fi=re(p=>{ct.current.push(p);let m=Ad(p,tt());dr.current+=m.split(`
500
+ `).length+1,console.log(m)},[tt]),Lc=ie([]),Ui=re(()=>{let p=Lc.current;if(p.length===0)return;Lc.current=[];let m=av(p);m&&Fi({kind:"note",tone:"info",text:`\u25CF Housekeeping ${m}`})},[Fi]),h=re(p=>{Ui(),Fi(p)},[Fi,Ui]),ht=ie({printed:[],armed:[],printedAt:0}),Wi=ie(null),Bi=ie([]),dr=ie(0),Hi=re(()=>Xe.current!==null,[]),nt=re((p,m)=>{Hi()||(Ze.current++,ht.current.armed=[],fe(p),Ie(m??null))},[Hi]),Kt=re(()=>{Ze.current++,ht.current.armed=[],fe(null),Ie(null)},[]),ks=re(p=>{Hi()||(Ze.current++,ht.current.armed=[],fe(null),Ie(p))},[Hi]),se=re(p=>nt(p,Qr({kind:"cmd",cmd:p,reason:""})),[nt]),$n=re((p,m)=>{if(!m?.silent&&p.note&&h({kind:"note",tone:m?.tone??p.tone,text:p.note}),!m?.silent&&p.note?.includes(".d360-writer/ \u2014 your articles"))try{let P=zL(e);XL(tL(P)),pv(P,`${new Date().toISOString()}
501
+ `)}catch{}p.picker&&(we(p.picker.options.map(P=>({cmd:P.cmd,desc:P.desc}))),wo(p.picker.title),Bi.current=p.picker.exclusive?p.picker.options.map(P=>P.cmd.trim()):[]),!m?.silent&&p.note&&(ht.current.printed=p.menu,ht.current.printedAt=dr.current);let y=dr.current-ht.current.printedAt<Math.max(8,(et.rows??24)-4)&&Fk(ht.current.printed,p.menu)?p.menu:[];p.lead?(p.lead.kind==="answer"?ks(Qr(p.lead,y.length)):nt(p.lead.kind==="cmd"?p.lead.cmd:p.lead.text,Qr(p.lead,y.length)),!m?.silent&&p.note&&(Wi.current=Zr(p.lead))):!p.picker&&(!m?.silent||p.restKind!==null)&&(Kt(),y.length>0&&ks(p.restKind==="delivered"?`1\u2013${y.length} when you want one \xB7 nothing is owed \xB7 or just ask me anything\u2026`:`1\u2013${y.length} to pick a campaign step \xB7 nothing is waiting \xB7 or just ask me anything\u2026`)),ht.current.armed=y},[h,nt,ks,e,et]),Pe=re((p,m,u="info")=>{ht.current.armed=[],p&&h({kind:"note",tone:u,text:p}),m&&(m.kind==="answer"?ks(Qr(m)):nt(m.kind==="cmd"?m.cmd:m.text,Qr(m)),Wi.current=p?Zr(m):null)},[h,nt,ks]),vn=re((p,m,u,y="info")=>{if(p.producedNothing){Pe("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}p.handedBack||Pe(m,u,y)},[Pe]),[Po,Oc]=ce(null),[Qv,Bf]=ce(!1),xn=re((p,m)=>{Oc(p),Bf(!1),h({kind:"note",tone:"info",text:m?.hint??"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[h]),_c=re(()=>{cO(e,new Date().toISOString());let p=rb(e);p&&(h({kind:"note",tone:"info",text:p.lines.join(`
502
+ `)}),xn(p.prompt,uO(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,xn]),Gi=ie(!1),Mc=re(async()=>{try{if(Gi.current||!UL(FL())||ke(e)?.mode==="engineer")return;let p=await Tv({pkg:Yo,currentVersion:o,force:!0});if(!p.updateAvailable||!p.latest)return;if(Gi.current=!0,Nl()){Dl(p.latest),h({kind:"note",tone:"info",text:`\u2B06 Update v${p.latest} is ready to install.
503
+ I'll install it when you /exit \u2014 your next launch runs it.`});return}h({kind:"note",tone:"info",text:`\u2B06 Updating ${Yo} ${p.current} \u2192 ${p.latest}\u2026 (wait for the \u2713 before you /exit)`}),uo(!0);let m=await wi().finally(()=>uo(!1));m.ok?(h({kind:"note",tone:"ok",text:`\u2713 Updated to v${p.latest} \u2014 run /exit, then relaunch to apply.`}),se("/exit"),us(p.latest)):h({kind:"note",tone:"warn",text:`Update available (v${p.latest}) but auto-update failed. ${yi(m.output)}`})}catch{}},[e,o,h,se]),$s=ie(!1),Fc=ie(null),Hf=re(async p=>{if(!$s.current)try{let m=ke(e);if(!m)return;let u=Gf.current;if(!u)return;if(u.pushConsent!=="on"){if(u.uncommitted===0)return;$s.current=!0;try{let P=await KL(e,m);if(P.commit?.ok)Fc.current=null;else if(P.commit&&!P.commit.ok){let _=`${P.commit.reason}:${P.commit.detail??""}`;Fc.current!==_&&(Fc.current=_,h({kind:"note",tone:"warn",text:`\u26A0 Couldn't save your docs work to git \u2014 ${no(P.commit.reason,P.commit.detail)}`}))}}finally{$s.current=!1}return}if(u.uncommitted===0&&u.unpushed===0&&!p.pull)return;$s.current=!0;try{let{lines:P,changed:_}=await Rl(e,m);for(let H of P)H.tone==="warn"||H.tone==="error"?h({kind:"note",tone:H.tone,text:H.text}):H.text.includes("\u2B07")&&h({kind:"note",tone:H.tone,text:H.text});_&&W(H=>H+1)}finally{$s.current=!1}}catch{}},[e,h]),To=re(p=>{let m=Je(e,s);return m.ok?!0:(h({kind:"note",tone:"warn",text:m.reason}),vo.current=p,se("/login"),!1)},[e,s,h,se]),[qi,Uc]=ce(null),Gf=ie(null),qf=ie(null),yt=re((p,m)=>{let u=Ci(e,s,{claudeMissing:$f(t).state==="missing",allowAutoAudit:p,genreUnknown:ze.current,pendingAnswer:_e.current,lastCommand:qf.current});return Gf.current=u?.handoff??null,u?Si(u,{header:m,pickable:!0,scaleFor:y=>en(e,y)}):{kind:"idle"}},[e,s,t]),Wc=ie(Date.now()),vs=ie(U$()),Vf=ie(0),[Yf,Kf]=ce(null),xs=ie(!0),pr=ie(!1),Vi=ie(0),Rs=ie(0);it(()=>{let p=setInterval(()=>{if(xs.current){Vi.current=0,Rs.current=0;return}if(!S)try{if(!os(Av(e)))return;if(Xt(e).status==="current"){xs.current=!0,Vi.current=0,Rs.current=0;let u=pr.current?`\u2713 Your builder finished the protocol update (v${Me}) \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:",y=yt(!1,u),P=y.kind==="recommend"?y.rec:null;Oc(null),P?.note?$n(P,{tone:"ok"}):(h({kind:"note",tone:"ok",text:`${u}${P?.lead?` ${Jr(P.lead)}`:""}`}),P?.lead||P?.picker?$n(P,{silent:!0}):pr.current||nt("write the docs for this repo")),W(_=>_+1);return}if(pr.current)return;Vi.current+=1;let m=Vi.current;if((m===4||m%15===0)&&Rs.current<3){Rs.current+=1;let u=Rs.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";h({kind:"note",tone:"info",text:Pn(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${u}`:`\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.${u}`})}}catch{}},4e3);return()=>clearInterval(p)},[e,S,h,yt,$n,nt]),it(()=>{let p=Af??Ei(e);if(!S){uc(0),ts(`${pc} ${p}`);return}uc(3);let m=0;ts(`${dc[0]} ${p}`);let u=setInterval(()=>{m=(m+1)%dc.length,ts(`${dc[m]} ${p}`)},400);return()=>clearInterval(u)},[S,e,Af]),it(()=>()=>uc(0),[]),it(()=>{let p=performance.now(),m=[],u=(w,k)=>{let v=performance.now();try{return k()}finally{let b=Math.round(performance.now()-v);b>=80&&m.push(`${w}: ${b}ms`)}};h({kind:"banner",info:u("banner",()=>hO(e,o,t,s))});let y=$f(t).state==="missing";if(y&&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.
504
+ ${oL}
504
505
  Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!ke(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:
505
- ${Cv}`}),se(y?"/doctor":"/init");return}y&&se("/doctor");try{let w=Rt(e,s);w.project.projectId&&KI(w.name,w.project.projectId,w.project.projectName);let $=lo(w.name,w.project.projectId),v=Je(e,s);$&&Zo($)&&$.refreshToken?BI({profile:w.name,connection:w.connection,projectId:w.project.projectId,projectName:w.project.projectName}).then(()=>{h({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),W(b=>b+1)}).catch(b=>{if(b instanceof HI&&b.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."}),se("/login"),W(R=>R+1)}):v.ok||(h({kind:"note",tone:"warn",text:v.reason}),se("/login"))}catch{}try{let w=ke(e),$=Rt(e,s),v=lo($.name,$.project.projectId);w&&v&&!Zo(v)&&Gh(e,w.authoritativeSourceFiles)&&!qh(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."}),se("/scope"))}catch{}try{let w=u("resolve-genre",()=>iL(e));w.persisted&&w.appType?h({kind:"note",tone:"ok",text:`\u2713 Detected a ${w.appType} app \u2014 enabled the ${w.appType}-doc-playbook (change with /genre, or edit .d360-writer/config.json).`}):w.source==="unknown"&&ke(e)&&(Ge.current=!0)}catch{}let P=zt(e);try{if(u("reconcile-devhints",()=>ua(e)),P.status!=="current"&&!Sn(e)){let w=da(e);w.length&&(h({kind:"note",tone:"warn",text:w.join(`
506
- `)}),$n(jo()),$s.current=!1,hr.current=!1)}}catch{}try{let w=u("reconcile-feedback",()=>xL(e));w.archived>0&&h({kind:"note",tone:"ok",text:`\u2713 Tidied ${w.archived} resolved item${w.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${w.open>0?`; ${w.open} still open`:""}.`})}catch{}try{let w=u("upgrade-actions",()=>RL(e));w.applied.length>0&&h({kind:"note",tone:"warn",text:ia(w.applied).join(`
507
- `)}),w.reopenedForRedaction&&h({kind:"note",tone:"warn",text:aa(w.reopenedForRedaction)})}catch{}let F=u("ready-decision",()=>gt(!0));F.kind==="autoAudit"?(h({kind:"note",tone:"info",text:F.note}),qs({cwd:e,profileName:s}).then(w=>{if(w.kind==="audit-blocked"){Pe(w.note,{kind:"cmd",cmd:w.lead.cmd,reason:w.lead.reason},"warn");return}w.kind!=="forward-to-agent"||!w.prompt||ve(w.prompt,{display:w.display,quietUser:!0}).then($=>{if($.producedNothing)return;let v=Va(e,s);if(v){Pe(v.note,{kind:"cmd",cmd:jr.cmd,reason:jr.reason},"warn"),W(b=>b+1);return}bi(e,s),W(b=>b+1)})})):F.kind==="recommend"&&bn(F.rec);let G=Math.round(performance.now()-p);G>=800&&AL({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${G}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${m.length?m.join(`
506
+ ${Ov}`}),se(y?"/doctor":"/init");return}y&&se("/doctor");try{let w=St(e,s);w.project.projectId&&pL(w.name,w.project.projectId,w.project.projectName);let k=lo(w.name,w.project.projectId),v=Je(e,s);k&&tr(k)&&k.refreshToken?aL({profile:w.name,connection:w.connection,projectId:w.project.projectId,projectName:w.project.projectName}).then(()=>{h({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),W(b=>b+1)}).catch(b=>{if(b instanceof lL&&b.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."}),se("/login"),W(R=>R+1)}):v.ok||(h({kind:"note",tone:"warn",text:v.reason}),se("/login"))}catch{}try{let w=ke(e),k=St(e,s),v=lo(k.name,k.project.projectId);w&&v&&!tr(v)&&Xh(e,w.authoritativeSourceFiles)&&!Qh(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."}),se("/scope"))}catch{}try{let w=u("resolve-genre",()=>SL(e));w.persisted&&w.appType?h({kind:"note",tone:"ok",text:`\u2713 Detected a ${w.appType} app \u2014 enabled the ${w.appType}-doc-playbook (change with /genre, or edit .d360-writer/config.json).`}):w.source==="unknown"&&ke(e)&&(ze.current=!0)}catch{}let P=Xt(e);try{if(u("reconcile-devhints",()=>ma(e)),P.status!=="current"&&!Pn(e)){let w=ga(e);w.length&&(h({kind:"note",tone:"warn",text:w.join(`
507
+ `)}),xn(Io()),xs.current=!1,pr.current=!1)}}catch{}try{let w=u("reconcile-feedback",()=>WL(e));w.archived>0&&h({kind:"note",tone:"ok",text:`\u2713 Tidied ${w.archived} resolved item${w.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${w.open>0?`; ${w.open} still open`:""}.`})}catch{}try{let w=u("upgrade-actions",()=>BL(e));w.applied.length>0&&h({kind:"note",tone:"warn",text:da(w.applied).join(`
508
+ `)}),w.reopenedForRedaction&&h({kind:"note",tone:"warn",text:pa(w.reopenedForRedaction)})}catch{}let _=u("ready-decision",()=>yt(!0));_.kind==="autoAudit"?(h({kind:"note",tone:"info",text:_.note}),Ys({cwd:e,profileName:s}).then(w=>{if(w.kind==="audit-blocked"){Pe(w.note,{kind:"cmd",cmd:w.lead.cmd,reason:w.lead.reason},"warn");return}w.kind!=="forward-to-agent"||!w.prompt||ve(w.prompt,{display:w.display,quietUser:!0}).then(k=>{if(k.producedNothing)return;let v=Qa(e,s);if(v){Pe(v.note,{kind:"cmd",cmd:Dr.cmd,reason:Dr.reason},"warn"),W(b=>b+1);return}xi(e,s),W(b=>b+1)})})):_.kind==="recommend"&&$n(_.rec);let H=Math.round(performance.now()-p);H>=800&&YL({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${H}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${m.length?m.join(`
508
509
  `):"no single phase \u226580ms"}
509
- cwd: ${e}`}),jc(),Of({pull:!0})},[]),it(()=>{let p=setInterval(()=>{jc()},iO);return()=>clearInterval(p)},[jc]),it(()=>{let p=setInterval(()=>{try{let m=Date.now(),u=nf(m,Oc.current);if(Ff.current+=1,u&&Ff.current%Math.round(3e5/6e4)!==0)return;let y=KL(e),P=ks.current,F=y===P.fingerprint&&P.counts?P.counts:Jt(e),G=j$({now:m,lastInputAt:Oc.current,fingerprint:y,counts:F,occupied:S||V||ge.length>0||g!==""||Mn||De.current.length>0,prev:P});if(ks.current=G.memory,Wf(G.waiting),G.speak&&Xe.current===null){h({kind:"note",tone:"info",text:L$(G.speak)});let w=gt(!1);w.kind==="recommend"&&bn(w.rec,{silent:!0})}}catch{}},6e4);return()=>clearInterval(p)},[e,S,V,ge.length,g,Mn,h,gt,bn]),it(()=>{if(S||V||Z.current||ys&&!ko.current||ae!==null||ge.length>0||g!==""||Co!==null||De.current.length>0||or.current||Mn)return;let p=gt(!1);if(p.kind==="recommend"&&(p.rec.lead||p.rec.picker||p.rec.menu.length>0)){bn(p.rec,{silent:!0});let m=p.rec.lead,u=m?es(m):p.rec.restKind?`rest:${p.rec.restKind}`:null;u&&u!==_i.current&&(_i.current=u,p.rec.settled&&h({kind:"note",tone:"ok",text:p.rec.settled}),m&&h({kind:"note",tone:"info",text:Zr(m)}))}Of({pull:!1})},[S,V,ae,ge,g,Co,Mn,I,gt,In]);let xs=re((p,m)=>{let u=Xe.current;if(Xe.current=null,Di.current=!1,ji.current=!1,!u)return;let y=Math.max(0,Math.round((Date.now()-u.startedAt)/1e3)),P={ran:u.ran,parked:m,spentUsd:Math.max(0,Et-u.stepStartedSpend),budgetUsd:mc(ke(e)),seconds:y,reason:p};for(let G of v$(P))h({kind:"note",tone:G.tone,text:G.text});try{let G=new Date().toISOString().replace(/[:.]/g,"-"),w=Pi(e,rL,"auto-runs");LI(w,{recursive:!0}),ov(Pi(w,`${G}.md`),x$(P,new Date().toISOString()),"utf8")}catch{}let F=m.find(G=>G.cmd)?.cmd;F&&se(F),Af(null),W(G=>G+1)},[e,h,Et,se]);it(()=>{if(!ys||ko.current||ji.current||S||V||ge.length>0||g!==""||Co!==null||De.current.length>0||or.current||Mn)return;let p=Xe.current;if(p?.stopping){xs({kind:"stopped",how:"manual"},p.parked);return}let m=gt(!1);if(m.kind!=="recommend")return;let u=p??{ran:[],parked:[],spentUsd:0,startedAt:Date.now(),stopping:!1,stepStartedSpend:Et},y=Pc.current,P=A$(m.rec,{ran:u.ran,parked:u.parked,spentUsd:Math.max(0,Et-u.stepStartedSpend),...u.ran.length>0?{lastLeadKey:u.ran[u.ran.length-1]??null}:{},...y?{lastClosedItsTarget:Xt(y)}:{}},{budgetUsd:mc(ke(e))});if(P.kind==="stop"){if(!p&&P.reason.kind!=="onlyBlocked")return;if(!p){let w=m.rec.lead?es(m.rec.lead):"blocked";if(Cc.current===w)return;Cc.current=w}Xe.current=u,xs(P.reason,P.parked);return}if(!Di.current){let w=mc(ke(e)),$=N=>{try{return N()}catch{return null}},v=P.kind==="run"?P.cmd:`\u201C${P.text}\u201D`,b=P.kind==="run"?$(()=>jb(e,P.cmd)):null,R=P.kind==="run"?$(()=>E$(m.rec,P.cmd,N=>Zt(e,N)))??[]:[];Ni({firstCmd:v,scale:P.kind==="run"?$(()=>Zt(e,P.cmd)):null,upcoming:R,budgetUsd:w,overBudget:b!==null&&b>w});return}let F=P.kind==="run"?P.cmd:P.text;u.parked=P.parked,u.ran=[...u.ran,F],Xe.current=u,Pc.current=null,h({kind:"block",text:ee(ne("\u25B6",`Auto mode, step ${u.ran.length}: ${F}`))}),Af({step:u.ran.length,cmd:F,startedAt:u.startedAt,spentUsd:Math.max(0,Et-u.stepStartedSpend),budgetUsd:mc(ke(e))}),Cc.current=null,ji.current=!0,B(!0),(P.kind==="run"?Eo(P.cmd):ve(P.text,{display:P.text,quietUser:!0}).then(()=>{})).finally(()=>{ji.current=!1,B(!1)})},[ys,S,V,ge,g,Co,Mn,I,gt,xs]),it(()=>{let p=null,m=null,u=()=>{p&&clearTimeout(p),p=setTimeout(()=>{p=null;let y=`${rt.columns??80}x${rt.rows??24}`;y!==If.current&&(If.current=y,Uv(P=>P+1),m&&clearTimeout(m),m=setTimeout(()=>{m=null;let P=Math.max(8,(rt.rows??24)-2);console.log("\x1B[?2026h\x1B[H\x1B[2J"+Vy(nr.current,et(),P)+"\x1B[?2026l")},80))},400)};return rt.on("resize",u),()=>{p&&clearTimeout(p),m&&clearTimeout(m),rt.off("resize",u)}},[rt,et]);let ht=Math.max(20,(rt.columns??80)-1),Bf=hc(()=>QL(e,s),[e,s,I]),_c=(()=>{if(co)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(tr!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${tr?` v${tr}`:""}\u2026`,isSetup:!0};if(Nf)return{text:p$(Nf),isSetup:!0};if(Ui)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(Co)return Wv?{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(Uf)return{text:_$(Uf),isSetup:!0};if(De.current.length>0){let y=De.current.length,P=De.current[0].mode;return P==="local-only"?{text:"l publish yours over the portal \xB7 s skip \xB7 anything else cancels\u2026",isSetup:!0}:P==="conflict"?{text:y>1?`l keep local \xB7 p take portal \xB7 s skip \xB7 la/pa/sa for all ${y}\u2026`:"l keep local \xB7 p take portal \xB7 s skip \xB7 anything else cancels\u2026",isSetup:!0}:{text:y>1?`y to write \xB7 n to skip \xB7 ya/na for all ${y}\u2026`:"y to write \xB7 n to skip \xB7 anything else cancels\u2026",isSetup:!0}}let p=ke(e);if(!p)return{text:"Run /init to set up this repo (or /help)\u2026",isSetup:!0};let m=Pi(e,(p.docsDir??yf).replace(/\/+$/,"")),u=(()=>{try{return rs(m)&&II(m).length>0}catch{return!1}})();try{let y=Rt(e,s),P=lo(y.name,y.project.projectId);if(!(!!P&&!(Zo(P)&&!P.refreshToken)))return{text:`Sign in with /login (profile "${y.name}")\u2026`,isSetup:!0};if(!y.project.projectId)return{text:"Sign in to Document360 to pick your project\u2026",isSetup:!0};if(!y.project.workspaceId&&!u)return{text:"Pick a workspace with /workspace\u2026",isSetup:!0}}catch{}return u?{text:JL,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),vn=Ly(g),Mc=vn.length>0&&!S,Bv=12,rn=Jh(rt.rows),Hv=rt.rows??24,Hf=Jh(rt.rows,{max:Bv}),Bi=Math.min(Ln,Math.max(0,vn.length-1)),To=oc(vn.length,Bi,Hf).start,Fc=vn.slice(To,To+Hf),Uc=a!==null?Z$(a,8,ht):null,Hi=Tt?Tt.paths.filter(p=>!Tt.query||p.toLowerCase().includes(Tt.query.toLowerCase())).slice(0,8):[],Gi=At?At.sessions.filter(p=>{let m=At.query.toLowerCase();return!m||p.name.toLowerCase().includes(m)||p.firstPrompt.toLowerCase().includes(m)}).slice(0,8):[],Ve=re((p,m)=>{Wt.current?.close(),Wt.current=rv({cwd:e,resume:p,profileName:m??s,allowProdWrites:_n.current}),p||(fn.current={uuid:null,firstPrompt:null,titleFired:!1},po(null)),Ro(0),So(0)},[e,s]),Gf=re((p,m,u)=>{if(Av.test(p))try{let y=Rt(e,s),P=typeof m.project_id=="string"&&m.project_id||y.project.projectId,F=Jl(m,u),G=[],w=tc(m,u),$=w?`${w} \u2014 `:"",v=Zl(u);p.endsWith("publish_article")&&v&&G.push(`${$}Live: ${v}`);let b=ec(u);b?G.push(`${$}Preview: ${b}`):F&&P&&G.push(`${$}Preview: ${Ql(y.connection.portalUrl,P,F,y.project.languageCode??"en")}`),G.length>0&&h({kind:"link",lines:G})}catch{}},[e,s,h]),ve=re(async(p,m)=>{St(!0),Z.current=!1,Ee.current=!1,_e.current=null,Kt(),we([]),yo(null),Ec(null);let u=Ze.current;if(m?.display?.startsWith("/"))try{let D=La(e,m.display);D&&(p=`${p}
510
-
511
- ${D}`)}catch{}m?.quietUser||h({kind:"user",text:m?.echoDisplay&&m.display?m.display:p});let y=fn.current;y.firstPrompt||(y.firstPrompt=m?.display??p),Ut.current=Date.now(),Ft(0),C(!0),ds.current.clear(),$c.current=null;let P="",F=!1,G=!1,w=!1,$=!1,v="",b={num:0,closed:!1,cueSeen:!1},R=null,N=()=>{R||(R=setTimeout(()=>{R=null,c(v.length>0?v:null)},60))},_=()=>{R&&clearTimeout(R),R=null,c(null)},M=(D=!1)=>{let{head:Q,keep:j}=ev(v,D);Q.trim()&&h({kind:"assistant",text:Qh(Q.trimEnd(),b)}),v=j,_()};try{for await(let D of Wt.current.send(p))if(D.type==="session"){if(!y.uuid){y.uuid=D.sessionId;let Q=new Date().toISOString(),j=xc.current,U=j??QI(y.firstPrompt??"session");JI({uuid:D.sessionId,name:U,renamed:!!j,titled:!1,cwd:e,firstPrompt:y.firstPrompt??"",createdAt:Q,updatedAt:Q}),po(U),xc.current=null}}else if(D.type==="text"){v+=D.delta,P+=D.delta;let Q=tv(v);if(Q>0){let j=v.slice(0,Q).trimEnd();j&&h({kind:"assistant",text:Qh(j,b)}),v=v.slice(Q)}N(),Ft(j=>j+D.delta.length)}else if(D.type==="tool"){F=!0,Av.test(D.name)&&(G=!0);let j=(ye=>typeof ye=="string"&&ye?ye.replace(/\\/g,"/").toLowerCase():null)(D.input.file_path??D.input.notebook_path),U=["Edit","Write","MultiEdit","NotebookEdit"].includes(D.name),H=D.name==="Read"&&j!==null&&j===vf.current;vf.current=U?j:null;let te=Ei.current,ue=te?null:Q$(D.name,D.input),pe=te?null:Kl(D.name,D.input,e,s);if(ue)Ac.current.push(ue);else if(pe){M();let ye=pe.repeat&&pe.articleKey&&pe.articleKey===$c.current?pe.repeat:pe;$c.current=pe.articleKey??null,h({kind:"doc",verb:pe.verb,title:ye.title,category:ye.category,note:ye.note,...pe.loud?{loud:pe.loud}:{}}),ds.current.set(D.id,{name:D.name,input:D.input,doc:!0,keepResult:pe.keepResult})}else if(H)M(),h({kind:"tool",title:"Read",sep:"",arg:"re-checking the file it just edited"});else{let ye=zl(D.name,D.input,e);ye&&(M(),h({kind:"tool",title:ye.title,sep:ye.sep,arg:ye.arg}),ds.current.set(D.id,{name:D.name,input:D.input}))}}else if(D.type==="article_diff"){let Q=Lt(D.oldContent,D.newContent,et());Q&&(M(),h({kind:"diff",added:Q.added,removed:Q.removed,lines:Q.lines,hidden:Q.hidden}))}else if(D.type==="tool_result"){D.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(D.output)&&(Ii.current=!0);let Q=ds.current.get(D.id);if(Q){ds.current.delete(D.id),M();let U=Q.doc&&!Q.keepResult&&!D.isError?{lines:[],hidden:0}:Xl(D.output,4,D.isError||Ei.current?void 0:Q.name,Q.input),H=D.isError&&h$(Q.name,D.output);U.lines.length>0&&h({kind:"tool-result",lines:U.lines,hidden:U.hidden,isError:D.isError&&!H}),D.isError||Gf(Q.name,Q.input,D.output)}}else if(D.type==="result"){M(!0),Ro(H=>H+D.outputTokens),So(H=>Math.max(H,D.sessionCostUsd));let Q=D.inputTokens+D.cacheReadTokens+D.cacheCreationTokens;if(h({kind:"done",seconds:Math.round((Date.now()-Ut.current)/1e3),tokens:D.outputTokens,costUsd:D.costUsd,sessionCostUsd:Math.max(Et,D.sessionCostUsd),ok:D.ok,...Q>0?{inTokens:Q,cachedPct:Math.round(D.cacheReadTokens/Q*100)}:{}}),!w&&!F&&!P.trim()&&!hs.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."})),D.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(P))try{let H=kv(e);if(rs(H)){let te=fc(H,"utf8").trim();te&&(Lc(te),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 j=D.ok?a$(P):null;Ee.current=j!==null,_e.current=j;let U=D.ok?l$(P,ZL):null;if(U)Ce(!1),Ae.current=!1,we(U);else if(D.ok&&(b.cueSeen||(j?.options??0)>=2))Ce(!0),Ae.current=!0,we([]);else if(j)we([]);else{let H=D.ok?F$(P,Wo.map(te=>te.name)):[];if(H.length>0)se(H[0]);else if(D.ok&&P.trim()&&!Ee.current){let te=gt(!1);te.kind==="recommend"&&(te.rec.lead||te.rec.picker)||nL(p,P,e).then(ue=>{ue&&Ze.current===u&&st(ue)}).catch(()=>{})}}if(y.uuid&&(lf(y.uuid),!y.titleFired)){y.titleFired=!0;let H=y.uuid,te=y.firstPrompt;te&&iv(te,e).then(ue=>{ue&&(XI(H,ue),po(ue))}).catch(()=>{})}}else D.type==="error"&&(M(!0),w=!0,D.kind==="auth"&&(Ii.current=!0),h(D.kind==="limit"?{kind:"note",text:`\u23F3 ${D.message}`,tone:"warn"}:{kind:"note",text:`agent error: ${D.message}`,tone:"error"}),D.note&&h({kind:"note",text:D.note,tone:"info"}))}finally{if(C(!1),_(),Oi(),G)try{let D=hf(await pf({cwd:e,profileName:s,onRateLimit:Q=>qe(`Document360 rate limit \u2014 waiting ${Math.ceil(Q.waitMs/1e3)}s\u2026`)}));D&&h({kind:"note",tone:D.startsWith("\u26A0")?"warn":"info",text:D})}catch{}finally{qe(null)}W(D=>D+1),fn.current.uuid&&y$(e,fn.current.uuid,nr.current),Ii.current?(Ii.current=!1,ms.current=m?.display??p,st("/login","\u21E5 tab to run /login \u2014 then I\u2019ll re-send your last prompt\u2026")):ms.current=null,hs.current&&(hs.current=!1,bo.current.length>0&&(h({kind:"note",tone:"info",text:`(${bo.current.length} queued message(s) discarded)`}),bo.current=[],Rc([])),h({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}return{producedNothing:$,handedBack:_e.current!==null}},[e,h,Gf,et,st,se,Kt,gt,Oi]),qi=re(async()=>{try{qe("Checking Document360 for new reviewer comments\u2026"),await vl(e,s,{onProgress:(p,m)=>qe(`Checking Document360 for new reviewer comments\u2026 ${p}/${m}`)})}catch{}finally{qe(null)}},[e,s]),yt=re(async(p,m=0,u)=>{let y=wc(e,p,{allowUnreviewed:u?.skipReview===!0,allowStyleErrors:u?.skipStyle===!0});if(!y.clear){h({kind:"note",tone:"warn",text:ff(y,p.length,{act:"push"}).join(`
512
- `)}),se(Bs(y));return}Ut.current=Date.now(),Ft(0),C(!0);let P=new AbortController;Fe.current=P;let F={aborted:!1,partitions:0,failed:0,notRun:0,producedNothing:!0},G={retryable:0,stopped:!1,paths:[]},w=async($,v)=>{let b=cf($),R=new Map;for(let te of b)for(let ue of te.paths)R.set(ue,te.label);let N=new Map(b.map(te=>[te.label,te.paths.length])),_=new Set,M=Date.now();be({verb:"Pushing",unit:"article",total:$.length,done:0,active:[],rows:Qo(b),tools:0,chars:0,lastAt:Date.now(),startedAt:M,agentless:!0}),h({kind:"note",tone:"info",text:v?`Resolving cross-links in ${$.length} article${$.length===1?"":"s"} whose targets were saved this run (second pass)\u2026 (esc to stop)`:`Pushing ${$.length} article${$.length===1?"":"s"} to Document360 (${dL} at a time)\u2026 (esc to stop)`});let D=await cL({cwd:e,profileName:s,paths:$,allowProdWrites:_n.current,...u?.allowUnpullable===!0?{allowUnpullable:!0}:{},signal:P.signal,onEvent:te=>{let ue=te.type==="article_done"?te.result.path:te.type==="article_failed"?te.failure.path:te.path,pe=R.get(ue);if(!pe)return;if(te.type==="article_start"){be(J=>J&&!J.active.includes(pe)?{...J,active:[...J.active,pe],rows:nt(J.rows,pe,"active"),lastAt:Date.now()}:J&&{...J,lastAt:Date.now()});return}te.type==="article_failed"&&_.add(pe);let ye=(N.get(pe)??1)-1;N.set(pe,ye),be(J=>{if(!J)return J;let $e={...J,done:J.done+1,rows:cc(J.rows,pe),lastAt:Date.now()};return ye>0?$e:{...$e,active:$e.active.filter(Le=>Le!==pe),rows:nt($e.rows,pe,_.has(pe)?"failed":"done")}})}}),Q=D.aborted||!!D.stopped,j=Ku(e,$,s);v||(F={aborted:Q,partitions:b.length,failed:D.failed.length,notRun:D.notRun.length,producedNothing:D.pushed.length===0,verifiedComplete:j>=$.length,leftBehind:m});let U=D.pushed.length>0;h({kind:"note",tone:Q||D.failed.length>0||!U?"warn":"ok",text:(Q?"Stopped. ":"")+Yu(D,{recorded:j,elapsedMs:Date.now()-M,docsRoot:PL(e),...v?{}:{conflictsSkipped:m,unreadableSkipped:u?.unreadableSkipped??0},...u?.scope?{scope:u.scope}:{}}).join(`
513
- `)}),v||(G={retryable:D.failed.filter(te=>!te.refused).length,stopped:!!D.stopped,paths:D.failed.map(te=>te.path)});let H=Vu(e,s);if(H&&h({kind:"note",tone:"info",text:H}),U){let te=Dr(e,s);te&&h({kind:"note",tone:"info",text:te})}if(!Q&&U){try{let ue=await pf({cwd:e,profileName:s,onRateLimit:ye=>qe(`Document360 rate limit \u2014 waiting ${Math.ceil(ye.waitMs/1e3)}s\u2026`)}),pe=hf(ue);pe?h({kind:"note",tone:pe.startsWith("\u26A0")?"warn":"info",text:pe}):ue.skipped&&h({kind:"note",tone:"warn",text:`Order sync skipped: ${ue.skipped}`})}catch(ue){h({kind:"note",tone:"warn",text:`Order sync failed: ${ue.message}`})}finally{qe(null)}try{let ue=vv(await $v({cwd:e,profileName:s}));ue&&h({kind:"note",tone:"info",text:ue})}catch(ue){h({kind:"note",tone:"warn",text:`Related-articles sync failed: ${ue.message}`})}let te=await Us(e,s);te&&h({kind:"note",tone:"info",text:te})}return Q};try{let $=await w(p,!1);if(!$){let b=await zu(e,s,p,G.paths);b.length>0&&await w(b,!0),xn(u?.scope?`/push ${u.scope}`:"/push --all",F)}let v=Se("/push",u?.scope?"":"--all",u?.scope);if(G.retryable>0)Pe(null,{kind:"cmd",cmd:v,reason:G.stopped?"Document360 stopped answering \u2014 your articles are unchanged, so this picks up where the run left off":`${G.retryable} article${G.retryable===1?"":"s"} could not be saved \u2014 this retries them`},"warn");else if(!$&&m>0)Pe(null,{kind:"cmd",cmd:"/resolve",reason:`${m} conflict${m===1?"":"s"} still need settling \u2014 they were left untouched`},"warn");else if(!$){let b=qu(e,{scope:u?.scope,profileName:s});b&&Pe(null,{kind:"cmd",...b})}}catch($){h({kind:"note",tone:"error",text:`Publish run failed: ${$.message}`})}finally{Fe.current=null,be(null),await qi(),C(!1),W($=>$+1)}},[e,s,h,t,Pe,qi]),fr=re(p=>h({kind:"block",text:p.join(`
514
- `)}),[h]),mr=re((p,m,u,y,P)=>{let F=Ot(p,m,u,Date.now(),P);h({kind:"done",seconds:F.seconds,tokens:F.outputTokens,costUsd:F.costUsd,ok:y,...F.activeSeconds!==void 0?{activeSeconds:F.activeSeconds}:{},sessionCostUsd:Et+u,...F.inputTokens>0?{inTokens:F.inputTokens,...F.cachedPct!==void 0?{cachedPct:F.cachedPct}:{}}:{}})},[h,Et]),Vi=re(async p=>{let m=Ai(e,"standard");Ut.current=Date.now(),Ft(0),C(!0);let u=new AbortController;Fe.current=u;let y=Date.now(),P=new Lr;P.start(),be({verb:p.verb,unit:"article",total:p.partitions.length,done:0,active:[],rows:Qo(p.partitions),tools:0,chars:0,lastAt:Date.now(),startedAt:y}),h({kind:"note",tone:"info",text:`${p.headline} on ${m.model}\u2026 (esc to stop)`});let F=!0,G=[],w=!1,$={aborted:!1,partitions:0,failed:0,notRun:0,producedNothing:!0},v=new Set;try{for await(let b of Ti({cwd:e,partitions:p.partitions,promptFor:p.promptFor,concurrency:p.concurrency,profileName:s,allowProdWrites:_n.current,model:m.model,signal:u.signal,scope:p.scope}))if(b.type==="partition_status")b.status==="running"?be(R=>R&&{...R,active:[...R.active,b.label],rows:nt(R.rows,b.label,"active"),lastAt:Date.now()}):be(R=>R&&{...R,active:R.active.filter(N=>N!==b.label),done:R.done+1,rows:nt(R.rows,b.label,b.status==="done"?"done":"failed"),lastAt:Date.now()});else if(b.type==="partition_stalled"){let R=ts(b);be(N=>N&&R?{...N,stalledNote:R}:N)}else if(b.type==="partition_event"){let R=null;if(b.event.type==="tool"){let N=rf(b.event.name,b.event.input,p.partitions[b.index]?.paths??[]);N&&!v.has(N)&&(v.add(N),R=b.label)}be(N=>{if(!N)return N;let _={...N,lastAt:Date.now()};return b.event.type==="tool"?_.tools=N.tools+1:b.event.type==="text"&&(_.chars=N.chars+b.event.delta.length),R&&(_.rows=cc(_.rows,R)),_})}else if(b.type==="run_done"){So(M=>M+b.totalCostUsd),Ro(M=>M+b.results.reduce((D,Q)=>D+Q.outputTokens,0));let R=uf(p.partitions,b.results);F=!!b.allEmpty||!!b.blocked,w=!!b.aborted,$={aborted:!!b.aborted,partitions:p.partitions.length,failed:R.failed.length,notRun:R.notRun.length,...b.blocked?{blocked:b.blocked}:{},...b.allEmpty?{allEmpty:!0}:{},...b.bailedEmpty?{bailedEmpty:!0}:{}};let N=[`${b.aborted?"Stopped. ":""}${b.results.length-R.failed.length}/${p.partitions.length} batches ${p.doneNoun}.`,...R.failed.length?[`\u26A0 ${R.failed.length} not ${p.doneNoun} \u2014 their articles are unchanged: ${R.failed.map(M=>M.label).join(", ")}`]:[],...R.notRun.length?[`\u26A0 ${R.notRun.length} batch${R.notRun.length===1?"":"es"} never started \u2014 their articles are untouched.`]:[],...b.blocked?[`\u26A0 ${b.blocked}`]:[],...b.allEmpty?[p.emptyNote??"\u26A0 No turn produced any work this run \u2014 nothing was changed."]:[],...p.caveatLines??[]];h({kind:"note",tone:b.aborted||R.failed.length||R.notRun.length||b.blocked||b.allEmpty?"warn":"ok",text:N.join(`
515
- `)});let _=P.stop();if(mr(y,b.results,b.totalCostUsd,!w&&!F&&!R.failed.length,_.activeSeconds),p.calibrateAs){let M=b.results.filter(D=>D.ok).length;lL(e,p.calibrateAs,{articles:R.covered.length,waves:Math.ceil(M/Math.max(1,p.concurrency)),seconds:_.activeSeconds,costUsd:b.totalCostUsd})}F||(G=R.covered)}}catch(b){h({kind:"note",tone:"error",text:`${p.verb} failed: ${b.message}`})}finally{P.stop(),Fe.current=null,be(null),C(!1),W(b=>b+1)}return{producedNothing:F,covered:G,aborted:w,outcome:$}},[e,s,h,mr]),Gv=re(async(p,m,u,y=!1)=>{let P=await Vi({partitions:p.partitions,promptFor:p.promptFor,concurrency:ro,verb:"Reviewing",doneNoun:"reviewed",headline:`Reviewing ${p.articles} article${p.articles===1?"":"s"} in ${p.partitions.length} batches (\u2264${ro} editors at once)${m?", applying fixes as they go":", report only"}`+(()=>{let G=Dl(e,"/review",p.articles,p.partitions.length);return G?` \xB7 ${G}`:""})(),caveatLines:$h(p,y),emptyNote:"\u26A0 No editor produced any work this run \u2014 nothing was reviewed or changed.",calibrateAs:"/review",scope:"review"}),F=null;if(m&&P.covered.length>0&&(F=Vo(e,P.covered,u,s),F.earned.length>0))try{is(e,F.earned,ft("review"))}catch{}return{producedNothing:P.producedNothing,aborted:P.aborted,outcome:P.outcome,evidence:F}},[e,Vi]),Wc=re(async(p,m)=>{if(p.length===0)return;let u=p.reduce((v,b)=>v+b.threads.length,0),y=new Map,P=p.map(v=>(y.set(v.label,v),{label:v.label,paths:v.path?[v.path]:[]})),F=Ai(e,"standard");Ut.current=Date.now(),Ft(0),C(!0);let G=new AbortController;Fe.current=G;let w=Date.now(),$=df(e);be({verb:"Answering",unit:"article",total:P.length,done:0,active:[],rows:Qo(P),tools:0,chars:0,lastAt:Date.now(),startedAt:w}),h({kind:"note",tone:"info",text:`Answering ${u} comment${u===1?"":"s"} across ${P.length} article${P.length===1?"":"s"} (\u2264${pi} agents at once) on ${F.model}. Each article is fixed, pushed to Document360 as a draft, then answered in the thread${m.resolve?" and resolved":" \u2014 the threads stay open for your reviewers to close"}\u2026 (esc to stop)`});try{for await(let v of Ti({cwd:e,partitions:P,promptFor:b=>{let R=y.get(b.label);return Hp({articleId:R.articleId,label:R.label,path:R.path,count:R.threads.length,resolve:m.resolve})},concurrency:pi,profileName:s,allowProdWrites:_n.current,allowCommentResolve:m.resolve,model:F.model,signal:G.signal}))if(v.type==="partition_status")v.status==="running"?be(b=>b&&{...b,active:[...b.active,v.label],rows:nt(b.rows,v.label,"active"),lastAt:Date.now()}):be(b=>b&&{...b,active:b.active.filter(R=>R!==v.label),done:b.done+1,rows:nt(b.rows,v.label,v.status==="done"?"done":"failed"),lastAt:Date.now()});else if(v.type==="partition_stalled"){let b=ts(v);be(R=>R&&b?{...R,stalledNote:b}:R)}else if(v.type==="partition_event")be(b=>{if(!b)return b;let R={...b,lastAt:Date.now()};return v.event.type==="tool"?R.tools=b.tools+1:v.event.type==="text"&&(R.chars=b.chars+v.event.delta.length),R});else if(v.type==="run_done"){So(j=>j+v.totalCostUsd),Ro(j=>j+v.results.reduce((U,H)=>U+H.outputTokens,0));let b=uf(P,v.results),R=v.results.length-b.failed.length,N=v.aborted?"Stopped. ":"",_=[...b.failed.map(j=>j.label),...b.notRun.map(j=>j.label)],M=[`${N}${R}/${P.length} article${P.length===1?"":"s"} answered.`,..._.length?[`\u26A0 ${_.length} left untouched (their threads are still open, which is correct \u2014 nothing was promised to those reviewers): ${_.join(", ")}`]:[],...v.blocked?[`\u26A0 ${v.blocked}`]:[],...v.allEmpty?["\u26A0 No agent produced any work this run \u2014 nothing was changed or answered."]:[]];h({kind:"note",tone:v.aborted||_.length||v.blocked||v.allEmpty?"warn":"ok",text:M.join(`
516
- `)}),mr(w,v.results,v.totalCostUsd,!v.aborted&&!_.length&&!v.blocked&&!v.allEmpty);let D=new Set(_),Q=[...m.rest??[],...p.filter(j=>D.has(j.label))];if(Q.length>0&&!v.aborted&&m.report){let j=Q.reduce((H,te)=>H+te.threads.length,0);h({kind:"note",tone:"info",text:`${j} comment${j===1?"":"s"} on ${Q.length} other article${Q.length===1?"":"s"} still open \u2014 pick the next one, or esc to stop here.`});let U={...m.report,threads:Q.flatMap(H=>H.threads)};fr(hi(U,{width:et()})),yn({cursor:0,rows:Rl(Q),groups:Q,resolve:m.resolve,report:U})}else if(Q.length>0&&!v.aborted){let j=Q.map(H=>H.path).filter(H=>!!H),U=j.length===Q.length?Dt(j):void 0;se(U?j.length===1?`/comments ${U}`:`/comments --scope ${U}`:"/comments")}xn("/comments --answer",{aborted:v.aborted,partitions:P.length,failed:b.failed.length,notRun:b.notRun.length,...v.blocked?{blocked:v.blocked}:{},...v.allEmpty?{allEmpty:!0}:{},leftBehind:(m.rest??[]).length})}}catch(v){h({kind:"note",tone:"error",text:`Answering comments failed: ${v.message}`})}finally{let b=Go(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"}.`}),Fe.current=null,be(null),C(!1),W(R=>R+1)}},[e,s,h,Pe,se,fr,et]),Bc=re(async(p,m)=>{if(!(m?.skipReview===!0||m?.skipStyle===!0)){let y=wc(e,[p],{});if(!y.clear){h({kind:"note",tone:"warn",text:ff(y,1,{act:"push"}).join(`
517
- `)}),se(Bs(y,p));return}}await yt([p],0,{skipReview:m?.skipReview,skipStyle:m?.skipStyle,scope:p});try{let y=await Wa(e,s,p.replace(/\\/g,"/"));y.length>0&&(yo(`Related articles not yet saved to Document360 (${y.length}):`),we([`/push --related ${p}`,...y.map(P=>`/push ${P}`)]))}catch{}},[e,s,ve,yt]),qf=re(async(p,m)=>{C(!0);try{let u=await od(e,s,p,{skipReview:m.skipReview,skipStyle:m.skipStyle,onProgress:(P,F,G)=>qe(`Publishing ${P+1}/${F} \u2014 ${G}\u2026`)}),y=u.blocked.length+u.failed.length;if(h({kind:"note",tone:y>0?"warn":"ok",text:rd(u).join(`
518
- `)}),u.blocked.length>0){let P=wc(e,u.blocked.map(G=>G.path),{allowUnreviewed:m.skipReview,allowStyleErrors:m.skipStyle,checkScreenshots:!0}),F=qa(e,P,m.scope);F.cmd?se(F.cmd):Pe(null,null)}else Pe(null,null)}catch(u){h({kind:"note",tone:"error",text:`Publishing failed: ${u.message}`})}finally{qe(null),await qi(),C(!1),W(u=>u+1)}},[e,s,h,se,Pe,qi]),Vf=re(async p=>{try{let m=await yc({cwd:e,profileName:s}),u=new Set(Mo(e,s)),{clean:y,conflicts:P}=_o(m.entries,u);if(y.length===0){h({kind:"note",tone:"info",text:"Nothing new to save \u2014 everything is already up to date on Document360."});return}await yt(y.map(F=>F.path),P.length,{skipReview:p?.skipReview,skipStyle:p?.skipStyle,unreadableSkipped:P.filter(F=>u.has(F.path)).length})}catch(m){h({kind:"note",tone:"warn",text:`Couldn\u2019t check what to save (${m.message}) \u2014 your articles are written; run /push when ready.`})}},[e,s,yt]),xn=re((p,m)=>{if(m&&(Pc.current=m),!(m&&!Xt(m)))for(let u of Ke(e,p))h({kind:"note",tone:"ok",text:u})},[e,h]),Kf=re(async(p,m)=>{let y=yL(p,3),P=Ai(e,"standard"),F=new Map,G=new Map;for(let b of p){let R=Lo(e,b),N=$u(e,b,R);if(N&&F.set(b,N),R!==null){let _=Iu(R);_.length>0&&G.set(b,_)}}Ut.current=Date.now(),Ft(0),C(!0);let w=new AbortController;Fe.current=w;let $=Date.now();be({verb:"Authoring",unit:"spec",total:y.length,done:0,active:[],rows:Qo(y),tools:0,chars:0,lastAt:Date.now(),startedAt:$}),h({kind:"note",tone:"info",text:`Authoring ${p.length} screenshot spec${p.length===1?"":"s"} in ${y.length} batch${y.length===1?"":"es"} (\u22646 agents at once) on ${P.model}${P.forced?" (forced)":""}\u2026 (esc to stop)`});let v=!1;try{for await(let b of Ti({cwd:e,partitions:y,promptFor:R=>Fg(R,F,G),concurrency:6,profileName:s,allowProdWrites:_n.current,model:P.model,signal:w.signal}))if(b.type==="partition_status")b.status==="running"?be(R=>R&&{...R,active:[...R.active,b.label],rows:nt(R.rows,b.label,"active"),lastAt:Date.now()}):be(R=>R&&{...R,active:R.active.filter(N=>N!==b.label),done:R.done+1,rows:nt(R.rows,b.label,b.status==="done"?"done":"failed"),lastAt:Date.now()});else if(b.type==="partition_stalled"){let R=ts(b);be(N=>N&&R?{...N,stalledNote:R}:N)}else if(b.type==="partition_event")be(R=>{if(!R)return R;let N={...R,lastAt:Date.now()};return b.event.type==="tool"?N.tools=R.tools+1:b.event.type==="text"&&(N.chars=R.chars+b.event.delta.length),N});else if(b.type==="run_done"){So(D=>D+b.totalCostUsd),Ro(D=>D+b.results.reduce((Q,j)=>Q+j.outputTokens,0));let R=b.results.filter(D=>D.ok).length,N=b.aborted?"Stopped. ":"";v=!b.aborted&&m.setup;let _=b.aborted?"":v?" Refreshing the staging checklist\u2026":` Next: /screenshot capture${m.scope?` ${m.scope}`:" --all"} (or /screenshot checklist first for the staging checklist).`,M=zn(b,"Spec authoring");h({kind:"note",tone:M||b.aborted?"warn":b.ok?"ok":"warn",text:M?M.join(`
519
- `):`${N}Authored specs \u2014 ${R}/${b.results.length} batches ok.${_}`}),mr($,b.results,b.totalCostUsd,!M&&!b.aborted&&b.ok),M&&(se("/doctor"),v=!1),!b.aborted&&b.ok&&!M&&xn(m.runLine)}}catch(b){h({kind:"note",tone:"error",text:`Spec authoring failed: ${b.message}`})}finally{Fe.current=null,be(null),C(!1),W(b=>b+1)}if(v){let b=await Hr();b.kind==="forward-to-agent"&&b.prompt&&await ve(b.prompt,{display:b.display,quietUser:!0}),Nc()}},[e,s,h,ve,xn,Nc]),Yf=re(async p=>{let m=$u(e,p,Lo(e,p))??void 0,u=await Da([p],void 0,{prior:m});u.kind==="forward-to-agent"&&u.prompt&&await ve(u.prompt,{display:u.display,quietUser:!0}),Rg(e,p)&&Pe(`Spec ready \u2014 /screenshot capture ${p} takes the screenshot; bare /screenshot picks the next shot.`,{kind:"cmd",cmd:`/screenshot capture ${p}`,reason:""})},[e,ve,Pe]),Ki=re(async(p,m)=>{if(p.length===0)return{drawn:[],undrawn:[],cliMissing:!1};C(!0);let u=new AbortController;Fe.current=u,be({verb:"Drawing callouts",unit:"screenshot",total:p.length,done:0,active:[],rows:p.map(R=>({label:R,items:1,status:"pending"})),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()});let y=[],P=!1;try{let R=await $p({cwd:e,ids:p,...m.force?{force:!0}:{},signal:u.signal,onStart:N=>be(_=>_&&{..._,active:[N],rows:nt(_.rows,N,"active"),lastAt:Date.now()}),onDone:(N,_)=>be(M=>M&&{...M,active:[],done:M.done+1,rows:nt(M.rows,N,_==="failed"?"failed":"done"),lastAt:Date.now()})});y=R.results,P=R.cliMissing??!1}catch(R){h({kind:"note",tone:"error",text:`Drawing the callouts failed: ${R.message}`})}finally{Fe.current=null,be(null),C(!1),W(R=>R+1)}if(P)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:p,cliMissing:!0};let F=y.filter(R=>R.outcome==="annotated").map(R=>R.id),G=y.filter(R=>R.outcome==="skipped").map(R=>R.id),w=p.filter(R=>!F.includes(R)&&!G.includes(R));if(h({kind:"note",tone:w.length?"warn":"ok",text:[`\u25C8 ${F.length} drawn`,G.length?`${G.length} already current`:"",w.length?`\u2717 ${w.length} not drawn`:""].filter(Boolean).join(" ")}),w.length>0){let R=Math.max(...w.map(N=>N.length));h({kind:"note",tone:"warn",text:w.map(N=>`\u2717 ${N.padEnd(R)} ${ai(y.find(_=>_.id===N)?.detail)||"no picture was produced"}`).join(`
510
+ cwd: ${e}`}),Mc(),Hf({pull:!0})},[]),it(()=>{let p=setInterval(()=>{Mc()},RO);return()=>clearInterval(p)},[Mc]),it(()=>{let p=setInterval(()=>{try{let m=Date.now(),u=cf(m,Wc.current);if(Vf.current+=1,u&&Vf.current%Math.round(3e5/6e4)!==0)return;let y=dO(e),P=vs.current,_=y===P.fingerprint&&P.counts?P.counts:Zt(e),H=B$({now:m,lastInputAt:Wc.current,fingerprint:y,counts:_,occupied:S||Y||ge.length>0||g!==""||Fn||De.current.length>0,prev:P});if(vs.current=H.memory,Kf(H.waiting),H.speak&&Xe.current===null){h({kind:"note",tone:"info",text:G$(H.speak)});let w=yt(!1);w.kind==="recommend"&&$n(w.rec,{silent:!0})}}catch{}},6e4);return()=>clearInterval(p)},[e,S,Y,ge.length,g,Fn,h,yt,$n]),it(()=>{if(S||Y||Z.current||bs&&!$o.current||ue!==null||ge.length>0||g!==""||Po!==null||De.current.length>0||nr.current||Fn)return;let p=yt(!1);if(p.kind==="recommend"&&(p.rec.lead||p.rec.picker||p.rec.menu.length>0)){$n(p.rec,{silent:!0});let m=p.rec.lead,u=m?Zr(m):p.rec.restKind?`rest:${p.rec.restKind}`:null;u&&u!==Wi.current&&(Wi.current=u,p.rec.settled&&h({kind:"note",tone:"ok",text:p.rec.settled}),m&&h({kind:"note",tone:"info",text:Jr(m)}))}Hf({pull:!1})},[S,Y,ue,ge,g,Po,Fn,j,yt,On]);let Ss=re((p,m)=>{let u=Xe.current;if(Xe.current=null,_i.current=!1,Mi.current=!1,!u)return;let y=Math.max(0,Math.round((Date.now()-u.startedAt)/1e3)),P={ran:u.ran,parked:m,spentUsd:Math.max(0,jt-u.stepStartedSpend),budgetUsd:$c(ke(e)),seconds:y,reason:p};for(let H of N$(P))h({kind:"note",tone:H.tone,text:H.text});try{let H=new Date().toISOString().replace(/[:.]/g,"-"),w=Ni(e,xL,"auto-runs");eL(w,{recursive:!0}),pv(Ni(w,`${H}.md`),D$(P,new Date().toISOString()),"utf8")}catch{}let _=m.find(H=>H.cmd)?.cmd;_&&se(_),Lf(null),W(H=>H+1)},[e,h,jt,se]);it(()=>{if(!bs||$o.current||Mi.current||S||Y||ge.length>0||g!==""||Po!==null||De.current.length>0||nr.current||Fn)return;let p=Xe.current;if(p?.stopping){Ss({kind:"stopped",how:"manual"},p.parked);return}let m=yt(!1);if(m.kind!=="recommend")return;let u=p??{ran:[],parked:[],spentUsd:0,startedAt:Date.now(),stopping:!1,stepStartedSpend:jt},y=Dc.current,P=M$(m.rec,{ran:u.ran,parked:u.parked,spentUsd:Math.max(0,jt-u.stepStartedSpend),...u.ran.length>0?{lastLeadKey:u.ran[u.ran.length-1]??null}:{},...y?{lastClosedItsTarget:Qt(y)}:{}},{budgetUsd:$c(ke(e))});if(P.kind==="stop"){if(!p&&P.reason.kind!=="onlyBlocked")return;if(!p){let w=m.rec.lead?Zr(m.rec.lead):"blocked";if(Nc.current===w)return;Nc.current=w}Xe.current=u,Ss(P.reason,P.parked);return}if(!_i.current){let w=$c(ke(e)),k=N=>{try{return N()}catch{return null}},v=P.kind==="run"?P.cmd:`\u201C${P.text}\u201D`,b=P.kind==="run"?k(()=>Wb(e,P.cmd)):null,R=P.kind==="run"?k(()=>F$(m.rec,P.cmd,N=>en(e,N)))??[]:[];Oi({firstCmd:v,scale:P.kind==="run"?k(()=>en(e,P.cmd)):null,upcoming:R,budgetUsd:w,overBudget:b!==null&&b>w});return}let _=P.kind==="run"?P.cmd:P.text;u.parked=P.parked,u.ran=[...u.ran,_],Xe.current=u,Dc.current=null,h({kind:"block",text:ee(ne("\u25B6",`Auto mode, step ${u.ran.length}: ${_}`))}),Lf({step:u.ran.length,cmd:_,startedAt:u.startedAt,spentUsd:Math.max(0,jt-u.stepStartedSpend),budgetUsd:$c(ke(e))}),Nc.current=null,Mi.current=!0,B(!0),(P.kind==="run"?No(P.cmd):ve(P.text,{display:P.text,quietUser:!0}).then(()=>{})).finally(()=>{Mi.current=!1,B(!1)})},[bs,S,Y,ge,g,Po,Fn,j,yt,Ss]),it(()=>{let p=null,m=null,u=()=>{p&&clearTimeout(p),p=setTimeout(()=>{p=null;let y=et.columns??80,P=`${y}x${et.rows??24}`;if(P===Uf.current)return;let _=y<(Wf.current??y);Uf.current=P,Wf.current=y,Xv(H=>H+1),_&&(m&&clearTimeout(m),m=setTimeout(()=>{m=null;let H=Math.max(8,(et.rows??24)-2);console.log("\x1B[?2026h\x1B[H\x1B[2J"+Zy(ct.current,tt(),H)+"\x1B[?2026l")},80))},400)};return et.on("resize",u),()=>{p&&clearTimeout(p),m&&clearTimeout(m),et.off("resize",u)}},[et,tt]);let ft=Math.max(20,(et.columns??80)-1),zf=bc(()=>mO(e,s),[e,s,j]),Bc=(()=>{if(co)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(cs!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${cs?` v${cs}`:""}\u2026`,isSetup:!0};if(_f)return{text:$$(_f),isSetup:!0};if(qi)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(Po)return Qv?{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(Yf)return{text:V$(Yf),isSetup:!0};if(De.current.length>0){let y=De.current.length,P=De.current[0].mode;return P==="local-only"?{text:"l publish yours over the portal \xB7 s skip \xB7 anything else cancels\u2026",isSetup:!0}:P==="conflict"?{text:y>1?`l keep local \xB7 p take portal \xB7 s skip \xB7 la/pa/sa for all ${y}\u2026`:"l keep local \xB7 p take portal \xB7 s skip \xB7 anything else cancels\u2026",isSetup:!0}:{text:y>1?`y to write \xB7 n to skip \xB7 ya/na for all ${y}\u2026`:"y to write \xB7 n to skip \xB7 anything else cancels\u2026",isSetup:!0}}let p=ke(e);if(!p)return{text:"Run /init to set up this repo (or /help)\u2026",isSetup:!0};let m=Ni(e,(p.docsDir??xf).replace(/\/+$/,"")),u=(()=>{try{return os(m)&&ZI(m).length>0}catch{return!1}})();try{let y=St(e,s),P=lo(y.name,y.project.projectId);if(!(!!P&&!(tr(P)&&!P.refreshToken)))return{text:`Sign in with /login (profile "${y.name}")\u2026`,isSetup:!0};if(!y.project.projectId)return{text:"Sign in to Document360 to pick your project\u2026",isSetup:!0};if(!y.project.workspaceId&&!u)return{text:"Pick a workspace with /workspace\u2026",isSetup:!0}}catch{}return u?{text:gO,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),Rn=By(g),Hc=Rn.length>0&&!S,Jv=12,sn=rf(et.rows),Zv=et.rows??24,Xf=rf(et.rows,{max:Jv}),Yi=Math.min(ds,Math.max(0,Rn.length-1)),Ao=cc(Rn.length,Yi,Xf).start,Gc=Rn.slice(Ao,Ao+Xf),qc=a!==null?lv(a,8,ft):null,Ki=Nt?Nt.paths.filter(p=>!Nt.query||p.toLowerCase().includes(Nt.query.toLowerCase())).slice(0,8):[],zi=Dt?Dt.sessions.filter(p=>{let m=Dt.query.toLowerCase();return!m||p.name.toLowerCase().includes(m)||p.firstPrompt.toLowerCase().includes(m)}).slice(0,8):[],Ve=re((p,m)=>{Tt.current?.close(),Tt.current=hv({cwd:e,resume:p,profileName:m??s,allowProdWrites:Mn.current}),p||(gn.current={uuid:null,firstPrompt:null,titleFired:!1},ho(null)),So(0),Co(0)},[e,s]),Qf=re((p,m,u)=>{if(Fv.test(p))try{let y=St(e,s),P=typeof m.project_id=="string"&&m.project_id||y.project.projectId,_=rc(m,u),H=[],w=ac(m,u),k=w?`${w} \u2014 `:"",v=sc(u);p.endsWith("publish_article")&&v&&H.push(`${k}Live: ${v}`);let b=ic(u);b?H.push(`${k}Preview: ${b}`):_&&P&&H.push(`${k}Preview: ${oc(y.connection.portalUrl,P,_,y.project.languageCode??"en")}`),H.length>0&&h({kind:"link",lines:H})}catch{}},[e,s,h]),ve=re(async(p,m)=>{Ct(!0),Z.current=!1,Ae.current=!1,_e.current=null,Kt(),we([]),wo(null),Oc(null);let u=Ze.current;if(m?.display?.startsWith("/"))try{let D=Ua(e,m.display);D&&(p=`${p}
511
+
512
+ ${D}`)}catch{}m?.quietUser||h({kind:"user",text:m?.echoDisplay&&m.display?m.display:p});let y=gn.current;y.firstPrompt||(y.firstPrompt=m?.display??p),Pt.current=Date.now(),rn(0),C(!0),ps.current.clear(),Cc.current=null;let P="",_=!1,H=!1,w=!1,k=!1,v="",b={num:0,closed:!1,cueSeen:!1},R=null,N=()=>{R||(R=setTimeout(()=>{R=null,c(v.length>0?v:null)},60))},M=()=>{R&&clearTimeout(R),R=null,c(null)},F=(D=!1)=>{let{head:X,keep:I}=cv(v,D);X.trim()&&h({kind:"assistant",text:of(X.trimEnd(),b)}),v=I,M()};try{for await(let D of Tt.current.send(p))if(D.type==="session"){if(!y.uuid){y.uuid=D.sessionId;let X=new Date().toISOString(),I=Tc.current,U=I??gL(y.firstPrompt??"session");yL({uuid:D.sessionId,name:U,renamed:!!I,titled:!1,cwd:e,firstPrompt:y.firstPrompt??"",createdAt:X,updatedAt:X}),ho(U),Tc.current=null}}else if(D.type==="text"){v+=D.delta,P+=D.delta;let X=uv(v);if(X>0){let I=v.slice(0,X).trimEnd();I&&h({kind:"assistant",text:of(I,b)}),v=v.slice(X)}N(),rn(I=>I+D.delta.length)}else if(D.type==="tool"){_=!0,Fv.test(D.name)&&(H=!0);let I=(ye=>typeof ye=="string"&&ye?ye.replace(/\\/g,"/").toLowerCase():null)(D.input.file_path??D.input.notebook_path),U=["Edit","Write","MultiEdit","NotebookEdit"].includes(D.name),G=D.name==="Read"&&I!==null&&I===Tf.current;Tf.current=U?I:null;let te=Li.current,de=te?null:iv(D.name,D.input),pe=te?null:Zl(D.name,D.input,e,s);if(de)Lc.current.push(de);else if(pe){F();let ye=pe.repeat&&pe.articleKey&&pe.articleKey===Cc.current?pe.repeat:pe;Cc.current=pe.articleKey??null,h({kind:"doc",verb:pe.verb,title:ye.title,category:ye.category,note:ye.note,...pe.loud?{loud:pe.loud}:{}}),ps.current.set(D.id,{name:D.name,input:D.input,doc:!0,keepResult:pe.keepResult})}else if(G)F(),h({kind:"tool",title:"Read",sep:"",arg:"re-checking the file it just edited"});else{let ye=tc(D.name,D.input,e);ye&&(F(),h({kind:"tool",title:ye.title,sep:ye.sep,arg:ye.arg}),ps.current.set(D.id,{name:D.name,input:D.input}))}}else if(D.type==="article_diff"){let X=Mt(D.oldContent,D.newContent,tt());X&&(F(),h({kind:"diff",added:X.added,removed:X.removed,lines:X.lines,hidden:X.hidden}))}else if(D.type==="gate_blocked")jc.current={path:D.path,commands:D.commands};else if(D.type==="tool_result"){D.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(D.output)&&(gs.current=!0);let X=ps.current.get(D.id);if(X){ps.current.delete(D.id),F();let U=X.doc&&!X.keepResult&&!D.isError?{lines:[],hidden:0}:nc(D.output,4,D.isError||Li.current?void 0:X.name,X.input),G=D.isError&&v$(X.name,D.output);U.lines.length>0&&h({kind:"tool-result",lines:U.lines,hidden:U.hidden,isError:D.isError&&!G}),D.isError||Qf(X.name,X.input,D.output)}}else if(D.type==="result"){F(!0),So(G=>G+D.outputTokens),Co(G=>Math.max(G,D.sessionCostUsd));let X=D.inputTokens+D.cacheReadTokens+D.cacheCreationTokens;if(h({kind:"done",seconds:Math.round((Date.now()-Pt.current)/1e3),tokens:D.outputTokens,costUsd:D.costUsd,sessionCostUsd:Math.max(jt,D.sessionCostUsd),ok:D.ok,...X>0?{inTokens:X,cachedPct:Math.round(D.cacheReadTokens/X*100)}:{}}),!w&&!_&&!P.trim()&&!fs.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."})),D.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(P))try{let G=Ev(e);if(os(G)){let te=kc(G,"utf8").trim();te&&(Uc(te),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 I=D.ok?g$(P):null;Ae.current=I!==null,_e.current=I;let U=D.ok?y$(P,yO):null;if(U)Ce(!1),Ee.current=!1,we(U);else if(D.ok&&(b.cueSeen||(I?.options??0)>=2))Ce(!0),Ee.current=!0,we([]);else if(I)we([]);else{let G=D.ok?K$(P,Bo.map(te=>te.name)):[];if(G.length>0)se(G[0]);else if(D.ok&&P.trim()&&!Ae.current){let te=yt(!1);te.kind==="recommend"&&(te.rec.lead||te.rec.picker)||$L(p,P,e).then(de=>{de&&Ze.current===u&&nt(de)}).catch(()=>{})}}if(y.uuid&&(ff(y.uuid),!y.titleFired)){y.titleFired=!0;let G=y.uuid,te=y.firstPrompt;te&&mv(te,e).then(de=>{de&&(mL(G,de),ho(de))}).catch(()=>{})}}else D.type==="error"&&(F(!0),w=!0,D.kind==="auth"&&(gs.current=!0),h(D.kind==="limit"?{kind:"note",text:`\u23F3 ${D.message}`,tone:"warn"}:{kind:"note",text:`agent error: ${D.message}`,tone:"error"}),D.note&&h({kind:"note",text:D.note,tone:"info"}))}finally{if(C(!1),M(),Ui(),H)try{let X=bf(await wf({cwd:e,profileName:s,onRateLimit:I=>qe(`Document360 rate limit \u2014 waiting ${Math.ceil(I.waitMs/1e3)}s\u2026`)}));X&&h({kind:"note",tone:X.startsWith("\u26A0")?"warn":"info",text:X})}catch{}finally{qe(null)}W(X=>X+1),gn.current.uuid&&C$(e,gn.current.uuid,ct.current),gs.current?(gs.current=!1,ys.current=m?.display??p,nt("/login","\u21E5 tab to run /login \u2014 then I\u2019ll re-send your last prompt\u2026")):ys.current=null;let D=jc.current;if(jc.current=null,D&&!gs.current&&D.commands.length>0){let X=D.commands[0],I=D.commands.length>1?` \u2014 then ${D.commands[1].split(" ")[0]} for the style errors`:"";nt(X,`\u21E5 tab to run ${X.split(" ")[0]}${I}`)}fs.current&&(fs.current=!1,ko.current.length>0&&(h({kind:"note",tone:"info",text:`(${ko.current.length} queued message(s) discarded)`}),ko.current=[],Ac([])),h({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}return{producedNothing:k,handedBack:_e.current!==null}},[e,h,Qf,tt,nt,se,Kt,yt,Ui]),Xi=re(async()=>{try{qe("Checking Document360 for new reviewer comments\u2026"),await Tl(e,s,{onProgress:(p,m)=>qe(`Checking Document360 for new reviewer comments\u2026 ${p}/${m}`)})}catch{}finally{qe(null)}},[e,s]),wt=re(async(p,m=0,u)=>{let y=Rc(e,p,{allowUnreviewed:u?.skipReview===!0,allowStyleErrors:u?.skipStyle===!0});if(!y.clear){h({kind:"note",tone:"warn",text:kf(y,p.length,{act:"push"}).join(`
513
+ `)}),se(Gs(y));return}Pt.current=Date.now(),rn(0),C(!0);let P=new AbortController;Fe.current=P;let _={aborted:!1,partitions:0,failed:0,notRun:0,producedNothing:!0},H={retryable:0,stopped:!1,paths:[]},w=async(k,v)=>{let b=mf(k),R=new Map;for(let te of b)for(let de of te.paths)R.set(de,te.label);let N=new Map(b.map(te=>[te.label,te.paths.length])),M=new Set,F=Date.now();be({verb:"Pushing",unit:"article",total:k.length,done:0,active:[],rows:Zo(b),tools:0,chars:0,lastAt:Date.now(),startedAt:F,agentless:!0}),h({kind:"note",tone:"info",text:v?`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 (${EL} at a time)\u2026 (esc to stop)`});let D=await TL({cwd:e,profileName:s,paths:k,allowProdWrites:Mn.current,...u?.allowUnpullable===!0?{allowUnpullable:!0}:{},signal:P.signal,onEvent:te=>{let de=te.type==="article_done"?te.result.path:te.type==="article_failed"?te.failure.path:te.path,pe=R.get(de);if(!pe)return;if(te.type==="article_start"){be(J=>J&&!J.active.includes(pe)?{...J,active:[...J.active,pe],rows:rt(J.rows,pe,"active"),lastAt:Date.now()}:J&&{...J,lastAt:Date.now()});return}te.type==="article_failed"&&M.add(pe);let ye=(N.get(pe)??1)-1;N.set(pe,ye),be(J=>{if(!J)return J;let $e={...J,done:J.done+1,rows:mc(J.rows,pe),lastAt:Date.now()};return ye>0?$e:{...$e,active:$e.active.filter(Le=>Le!==pe),rows:rt($e.rows,pe,M.has(pe)?"failed":"done")}})}}),X=D.aborted||!!D.stopped,I=Ju(e,k,s);v||(_={aborted:X,partitions:b.length,failed:D.failed.length,notRun:D.notRun.length,producedNothing:D.pushed.length===0,verifiedComplete:I>=k.length,leftBehind:m});let U=D.pushed.length>0;h({kind:"note",tone:X||D.failed.length>0||!U?"warn":"ok",text:(X?"Stopped. ":"")+Zu(D,{recorded:I,elapsedMs:Date.now()-F,docsRoot:qL(e),...v?{}:{conflictsSkipped:m,unreadableSkipped:u?.unreadableSkipped??0},...u?.scope?{scope:u.scope}:{}}).join(`
514
+ `)}),v||(H={retryable:D.failed.filter(te=>!te.refused).length,stopped:!!D.stopped,paths:D.failed.map(te=>te.path)});let G=Qu(e,s);if(G&&h({kind:"note",tone:"info",text:G}),U){let te=Nr(e,s);te&&h({kind:"note",tone:"info",text:te})}if(!X&&U){try{let de=await wf({cwd:e,profileName:s,onRateLimit:ye=>qe(`Document360 rate limit \u2014 waiting ${Math.ceil(ye.waitMs/1e3)}s\u2026`)}),pe=bf(de);pe?h({kind:"note",tone:pe.startsWith("\u26A0")?"warn":"info",text:pe}):de.skipped&&h({kind:"note",tone:"warn",text:`Order sync skipped: ${de.skipped}`})}catch(de){h({kind:"note",tone:"warn",text:`Order sync failed: ${de.message}`})}finally{qe(null)}try{let de=Dv(await Nv({cwd:e,profileName:s}));de&&h({kind:"note",tone:"info",text:de})}catch(de){h({kind:"note",tone:"warn",text:`Related-articles sync failed: ${de.message}`})}let te=await Bs(e,s);te&&h({kind:"note",tone:"info",text:te})}return X};try{let k=await w(p,!1);if(!k){let b=await ed(e,s,p,H.paths);b.length>0&&await w(b,!0),Sn(u?.scope?`/push ${u.scope}`:"/push --all",_)}let v=Se("/push",u?.scope?"":"--all",u?.scope);if(H.retryable>0)Pe(null,{kind:"cmd",cmd:v,reason:H.stopped?"Document360 stopped answering \u2014 your articles are unchanged, so this picks up where the run left off":`${H.retryable} article${H.retryable===1?"":"s"} could not be saved \u2014 this retries them`},"warn");else if(!k&&m>0)Pe(null,{kind:"cmd",cmd:"/resolve",reason:`${m} conflict${m===1?"":"s"} still need settling \u2014 they were left untouched`},"warn");else if(!k){let b=Xu(e,{scope:u?.scope,profileName:s});b&&Pe(null,{kind:"cmd",...b})}}catch(k){h({kind:"note",tone:"error",text:`Publish run failed: ${k.message}`})}finally{Fe.current=null,be(null),await Xi(),C(!1),W(k=>k+1)}},[e,s,h,t,Pe,Xi]),hr=re(p=>h({kind:"block",text:p.join(`
515
+ `)}),[h]),fr=re((p,m,u,y,P)=>{let _=Ft(p,m,u,Date.now(),P);h({kind:"done",seconds:_.seconds,tokens:_.outputTokens,costUsd:_.costUsd,ok:y,..._.activeSeconds!==void 0?{activeSeconds:_.activeSeconds}:{},sessionCostUsd:jt+u,..._.inputTokens>0?{inTokens:_.inputTokens,..._.cachedPct!==void 0?{cachedPct:_.cachedPct}:{}}:{}})},[h,jt]),Qi=re(async p=>{let m=ji(e,"standard");Pt.current=Date.now(),rn(0),C(!0);let u=new AbortController;Fe.current=u;let y=Date.now(),P=new Ir;P.start(),be({verb:p.verb,unit:"article",total:p.partitions.length,done:0,active:[],rows:Zo(p.partitions),tools:0,chars:0,lastAt:Date.now(),startedAt:y}),h({kind:"note",tone:"info",text:`${p.headline} on ${m.model}\u2026 (esc to stop)`});let _=!0,H=[],w=!1,k={aborted:!1,partitions:0,failed:0,notRun:0,producedNothing:!0},v=new Set;try{for await(let b of Di({cwd:e,partitions:p.partitions,promptFor:p.promptFor,concurrency:p.concurrency,profileName:s,allowProdWrites:Mn.current,model:m.model,signal:u.signal,scope:p.scope}))if(b.type==="partition_status")b.status==="running"?be(R=>R&&{...R,active:[...R.active,b.label],rows:rt(R.rows,b.label,"active"),lastAt:Date.now()}):be(R=>R&&{...R,active:R.active.filter(N=>N!==b.label),done:R.done+1,rows:rt(R.rows,b.label,b.status==="done"?"done":"failed"),lastAt:Date.now()});else if(b.type==="partition_stalled"){let R=es(b);be(N=>N&&R?{...N,stalledNote:R}:N)}else if(b.type==="partition_event"){let R=null;if(b.event.type==="tool"){let N=df(b.event.name,b.event.input,p.partitions[b.index]?.paths??[]);N&&!v.has(N)&&(v.add(N),R=b.label)}be(N=>{if(!N)return N;let M={...N,lastAt:Date.now()};return b.event.type==="tool"?M.tools=N.tools+1:b.event.type==="text"&&(M.chars=N.chars+b.event.delta.length),R&&(M.rows=mc(M.rows,R)),M})}else if(b.type==="run_done"){Co(F=>F+b.totalCostUsd),So(F=>F+b.results.reduce((D,X)=>D+X.outputTokens,0));let R=gf(p.partitions,b.results);_=!!b.allEmpty||!!b.blocked,w=!!b.aborted,k={aborted:!!b.aborted,partitions:p.partitions.length,failed:R.failed.length,notRun:R.notRun.length,...b.blocked?{blocked:b.blocked}:{},...b.allEmpty?{allEmpty:!0}:{},...b.bailedEmpty?{bailedEmpty:!0}:{}};let N=[`${b.aborted?"Stopped. ":""}${b.results.length-R.failed.length}/${p.partitions.length} batches ${p.doneNoun}.`,...R.failed.length?[`\u26A0 ${R.failed.length} not ${p.doneNoun} \u2014 their articles are unchanged: ${R.failed.map(F=>F.label).join(", ")}`]:[],...R.notRun.length?[`\u26A0 ${R.notRun.length} batch${R.notRun.length===1?"":"es"} never started \u2014 their articles are untouched.`]:[],...b.blocked?[`\u26A0 ${b.blocked}`]:[],...b.allEmpty?[p.emptyNote??"\u26A0 No turn produced any work this run \u2014 nothing was changed."]:[],...p.caveatLines??[]];h({kind:"note",tone:b.aborted||R.failed.length||R.notRun.length||b.blocked||b.allEmpty?"warn":"ok",text:N.join(`
516
+ `)});let M=P.stop();if(fr(y,b.results,b.totalCostUsd,!w&&!_&&!R.failed.length,M.activeSeconds),p.calibrateAs){let F=b.results.filter(D=>D.ok).length;PL(e,p.calibrateAs,{articles:R.covered.length,waves:Math.ceil(F/Math.max(1,p.concurrency)),seconds:M.activeSeconds,costUsd:b.totalCostUsd})}_||(H=R.covered)}}catch(b){h({kind:"note",tone:"error",text:`${p.verb} failed: ${b.message}`})}finally{P.stop(),Fe.current=null,be(null),C(!1),W(b=>b+1)}return{producedNothing:_,covered:H,aborted:w,outcome:k}},[e,s,h,fr]),e0=re(async(p,m,u,y=!1)=>{let P=await Qi({partitions:p.partitions,promptFor:p.promptFor,concurrency:ro,verb:"Reviewing",doneNoun:"reviewed",headline:`Reviewing ${p.articles} article${p.articles===1?"":"s"} in ${p.partitions.length} batches (\u2264${ro} editors at once)${m?", applying fixes as they go":", report only"}`+(()=>{let H=Ml(e,"/review",p.articles,p.partitions.length);return H?` \xB7 ${H}`:""})(),caveatLines:Ph(p,y),emptyNote:"\u26A0 No editor produced any work this run \u2014 nothing was reviewed or changed.",calibrateAs:"/review",scope:"review"}),_=null;if(m&&P.covered.length>0&&(_=Ko(e,P.covered,u,s),_.earned.length>0))try{ss(e,_.earned,mt("review"))}catch{}return{producedNothing:P.producedNothing,aborted:P.aborted,outcome:P.outcome,evidence:_}},[e,Qi]),Vc=re(async(p,m)=>{if(p.length===0)return;let u=p.reduce((v,b)=>v+b.threads.length,0),y=new Map,P=p.map(v=>(y.set(v.label,v),{label:v.label,paths:v.path?[v.path]:[]})),_=ji(e,"standard");Pt.current=Date.now(),rn(0),C(!0);let H=new AbortController;Fe.current=H;let w=Date.now(),k=yf(e);be({verb:"Answering",unit:"article",total:P.length,done:0,active:[],rows:Zo(P),tools:0,chars:0,lastAt:Date.now(),startedAt:w}),h({kind:"note",tone:"info",text:`Answering ${u} comment${u===1?"":"s"} across ${P.length} article${P.length===1?"":"s"} (\u2264${fi} agents at once) on ${_.model}. Each article is fixed, pushed to Document360 as a draft, then answered in the thread${m.resolve?" and resolved":" \u2014 the threads stay open for your reviewers to close"}\u2026 (esc to stop)`});try{for await(let v of Di({cwd:e,partitions:P,promptFor:b=>{let R=y.get(b.label);return Yp({articleId:R.articleId,label:R.label,path:R.path,count:R.threads.length,resolve:m.resolve})},concurrency:fi,profileName:s,allowProdWrites:Mn.current,allowCommentResolve:m.resolve,model:_.model,signal:H.signal}))if(v.type==="partition_status")v.status==="running"?be(b=>b&&{...b,active:[...b.active,v.label],rows:rt(b.rows,v.label,"active"),lastAt:Date.now()}):be(b=>b&&{...b,active:b.active.filter(R=>R!==v.label),done:b.done+1,rows:rt(b.rows,v.label,v.status==="done"?"done":"failed"),lastAt:Date.now()});else if(v.type==="partition_stalled"){let b=es(v);be(R=>R&&b?{...R,stalledNote:b}:R)}else if(v.type==="partition_event")be(b=>{if(!b)return b;let R={...b,lastAt:Date.now()};return v.event.type==="tool"?R.tools=b.tools+1:v.event.type==="text"&&(R.chars=b.chars+v.event.delta.length),R});else if(v.type==="run_done"){Co(I=>I+v.totalCostUsd),So(I=>I+v.results.reduce((U,G)=>U+G.outputTokens,0));let b=gf(P,v.results),R=v.results.length-b.failed.length,N=v.aborted?"Stopped. ":"",M=[...b.failed.map(I=>I.label),...b.notRun.map(I=>I.label)],F=[`${N}${R}/${P.length} article${P.length===1?"":"s"} answered.`,...M.length?[`\u26A0 ${M.length} left untouched (their threads are still open, which is correct \u2014 nothing was promised to those reviewers): ${M.join(", ")}`]:[],...v.blocked?[`\u26A0 ${v.blocked}`]:[],...v.allEmpty?["\u26A0 No agent produced any work this run \u2014 nothing was changed or answered."]:[]];h({kind:"note",tone:v.aborted||M.length||v.blocked||v.allEmpty?"warn":"ok",text:F.join(`
517
+ `)}),fr(w,v.results,v.totalCostUsd,!v.aborted&&!M.length&&!v.blocked&&!v.allEmpty);let D=new Set(M),X=[...m.rest??[],...p.filter(I=>D.has(I.label))];if(X.length>0&&!v.aborted&&m.report){let I=X.reduce((G,te)=>G+te.threads.length,0);h({kind:"note",tone:"info",text:`${I} comment${I===1?"":"s"} on ${X.length} other article${X.length===1?"":"s"} still open \u2014 pick the next one, or esc to stop here.`});let U={...m.report,threads:X.flatMap(G=>G.threads)};hr(mi(U,{width:tt()})),bn({cursor:0,rows:El(X),groups:X,resolve:m.resolve,report:U})}else if(X.length>0&&!v.aborted){let I=X.map(G=>G.path).filter(G=>!!G),U=I.length===X.length?Lt(I):void 0;se(U?I.length===1?`/comments ${U}`:`/comments --scope ${U}`:"/comments")}Sn("/comments --answer",{aborted:v.aborted,partitions:P.length,failed:b.failed.length,notRun:b.notRun.length,...v.blocked?{blocked:v.blocked}:{},...v.allEmpty?{allEmpty:!0}:{},leftBehind:(m.rest??[]).length})}}catch(v){h({kind:"note",tone:"error",text:`Answering comments failed: ${v.message}`})}finally{let b=qo(e,k,"","/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"}.`}),Fe.current=null,be(null),C(!1),W(R=>R+1)}},[e,s,h,Pe,se,hr,tt]),Yc=re(async(p,m)=>{if(!(m?.skipReview===!0||m?.skipStyle===!0)){let y=Rc(e,[p],{});if(!y.clear){h({kind:"note",tone:"warn",text:kf(y,1,{act:"push"}).join(`
518
+ `)}),se(Gs(y,p));return}}await wt([p],0,{skipReview:m?.skipReview,skipStyle:m?.skipStyle,scope:p});try{let y=await Va(e,s,p.replace(/\\/g,"/"));y.length>0&&(wo(`Related articles not yet saved to Document360 (${y.length}):`),we([`/push --related ${p}`,...y.map(P=>`/push ${P}`)]))}catch{}},[e,s,ve,wt]),Jf=re(async(p,m)=>{C(!0);try{let u=await ld(e,s,p,{skipReview:m.skipReview,skipStyle:m.skipStyle,onProgress:(P,_,H)=>qe(`Publishing ${P+1}/${_} \u2014 ${H}\u2026`)}),y=u.blocked.length+u.failed.length;if(h({kind:"note",tone:y>0?"warn":"ok",text:cd(u).join(`
519
+ `)}),u.blocked.length>0){let P=Rc(e,u.blocked.map(H=>H.path),{allowUnreviewed:m.skipReview,allowStyleErrors:m.skipStyle,checkScreenshots:!0}),_=Xa(e,P,m.scope);_.cmd?se(_.cmd):Pe(null,null)}else Pe(null,null)}catch(u){h({kind:"note",tone:"error",text:`Publishing failed: ${u.message}`})}finally{qe(null),await Xi(),C(!1),W(u=>u+1)}},[e,s,h,se,Pe,Xi]),Zf=re(async p=>{try{let m=await xc({cwd:e,profileName:s}),u=new Set(Fo(e,s)),{clean:y,conflicts:P}=Mo(m.entries,u);if(y.length===0){h({kind:"note",tone:"info",text:"Nothing new to save \u2014 everything is already up to date on Document360."});return}await wt(y.map(_=>_.path),P.length,{skipReview:p?.skipReview,skipStyle:p?.skipStyle,unreadableSkipped:P.filter(_=>u.has(_.path)).length})}catch(m){h({kind:"note",tone:"warn",text:`Couldn\u2019t check what to save (${m.message}) \u2014 your articles are written; run /push when ready.`})}},[e,s,wt]),Sn=re((p,m)=>{if(m&&(Dc.current=m),!(m&&!Qt(m)))for(let u of Ye(e,p))h({kind:"note",tone:"ok",text:u})},[e,h]),em=re(async(p,m)=>{let y=OL(p,3),P=ji(e,"standard"),_=new Map,H=new Map;for(let b of p){let R=Oo(e,b),N=Cu(e,b,R);if(N&&_.set(b,N),R!==null){let M=Fu(R);M.length>0&&H.set(b,M)}}Pt.current=Date.now(),rn(0),C(!0);let w=new AbortController;Fe.current=w;let k=Date.now();be({verb:"Authoring",unit:"spec",total:y.length,done:0,active:[],rows:Zo(y),tools:0,chars:0,lastAt:Date.now(),startedAt:k}),h({kind:"note",tone:"info",text:`Authoring ${p.length} screenshot spec${p.length===1?"":"s"} in ${y.length} batch${y.length===1?"":"es"} (\u22646 agents at once) on ${P.model}${P.forced?" (forced)":""}\u2026 (esc to stop)`});let v=!1;try{for await(let b of Di({cwd:e,partitions:y,promptFor:R=>Vg(R,_,H),concurrency:6,profileName:s,allowProdWrites:Mn.current,model:P.model,signal:w.signal}))if(b.type==="partition_status")b.status==="running"?be(R=>R&&{...R,active:[...R.active,b.label],rows:rt(R.rows,b.label,"active"),lastAt:Date.now()}):be(R=>R&&{...R,active:R.active.filter(N=>N!==b.label),done:R.done+1,rows:rt(R.rows,b.label,b.status==="done"?"done":"failed"),lastAt:Date.now()});else if(b.type==="partition_stalled"){let R=es(b);be(N=>N&&R?{...N,stalledNote:R}:N)}else if(b.type==="partition_event")be(R=>{if(!R)return R;let N={...R,lastAt:Date.now()};return b.event.type==="tool"?N.tools=R.tools+1:b.event.type==="text"&&(N.chars=R.chars+b.event.delta.length),N});else if(b.type==="run_done"){Co(D=>D+b.totalCostUsd),So(D=>D+b.results.reduce((X,I)=>X+I.outputTokens,0));let R=b.results.filter(D=>D.ok).length,N=b.aborted?"Stopped. ":"";v=!b.aborted&&m.setup;let M=b.aborted?"":v?" Refreshing the staging checklist\u2026":` Next: /screenshot capture${m.scope?` ${m.scope}`:" --all"} (or /screenshot checklist first for the staging checklist).`,F=Xn(b,"Spec authoring");h({kind:"note",tone:F||b.aborted?"warn":b.ok?"ok":"warn",text:F?F.join(`
520
+ `):`${N}Authored specs \u2014 ${R}/${b.results.length} batches ok.${M}`}),fr(k,b.results,b.totalCostUsd,!F&&!b.aborted&&b.ok),F&&(se("/doctor"),v=!1),!b.aborted&&b.ok&&!F&&Sn(m.runLine)}}catch(b){h({kind:"note",tone:"error",text:`Spec authoring failed: ${b.message}`})}finally{Fe.current=null,be(null),C(!1),W(b=>b+1)}if(v){let b=await Br();b.kind==="forward-to-agent"&&b.prompt&&await ve(b.prompt,{display:b.display,quietUser:!0}),_c()}},[e,s,h,ve,Sn,_c]),tm=re(async p=>{let m=Cu(e,p,Oo(e,p))??void 0,u=await _a([p],void 0,{prior:m});u.kind==="forward-to-agent"&&u.prompt&&await ve(u.prompt,{display:u.display,quietUser:!0}),Ng(e,p)&&Pe(`Spec ready \u2014 /screenshot capture ${p} takes the screenshot; bare /screenshot picks the next shot.`,{kind:"cmd",cmd:`/screenshot capture ${p}`,reason:""})},[e,ve,Pe]),Ji=re(async(p,m)=>{if(p.length===0)return{drawn:[],undrawn:[],cliMissing:!1};C(!0);let u=new AbortController;Fe.current=u,be({verb:"Drawing callouts",unit:"screenshot",total:p.length,done:0,active:[],rows:p.map(R=>({label:R,items:1,status:"pending"})),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()});let y=[],P=!1;try{let R=await Cp({cwd:e,ids:p,...m.force?{force:!0}:{},signal:u.signal,onStart:N=>be(M=>M&&{...M,active:[N],rows:rt(M.rows,N,"active"),lastAt:Date.now()}),onDone:(N,M)=>be(F=>F&&{...F,active:[],done:F.done+1,rows:rt(F.rows,N,M==="failed"?"failed":"done"),lastAt:Date.now()})});y=R.results,P=R.cliMissing??!1}catch(R){h({kind:"note",tone:"error",text:`Drawing the callouts failed: ${R.message}`})}finally{Fe.current=null,be(null),C(!1),W(R=>R+1)}if(P)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:p,cliMissing:!0};let _=y.filter(R=>R.outcome==="annotated").map(R=>R.id),H=y.filter(R=>R.outcome==="skipped").map(R=>R.id),w=p.filter(R=>!_.includes(R)&&!H.includes(R));if(h({kind:"note",tone:w.length?"warn":"ok",text:[`\u25C8 ${_.length} drawn`,H.length?`${H.length} already current`:"",w.length?`\u2717 ${w.length} not drawn`:""].filter(Boolean).join(" ")}),w.length>0){let R=Math.max(...w.map(N=>N.length));h({kind:"note",tone:"warn",text:w.map(N=>`\u2717 ${N.padEnd(R)} ${ci(y.find(M=>M.id===N)?.detail)||"no picture was produced"}`).join(`
520
521
  `)+`
521
- ${w.length===1?"It has":"They have"} no publishable picture yet. Re-take the shot: /screenshot capture`})}if(m.chainVerify===!1||F.length===0)return{drawn:F,undrawn:w,cliMissing:!1};let $=F.filter(R=>m.verifiedBefore.has(R)).length;if($>yl){let R=zw({results:y,voidedVerdicts:$,...m.scope?{scope:m.scope}:{}});return R&&Pe(`${R.glyph} ${R.cmd} ${R.why}`,{kind:"cmd",cmd:R.cmd,reason:""},"warn"),{drawn:F,undrawn:w,cliMissing:!1}}let v=F.filter(R=>!m.verifiedBefore.has(R)||$>0);if(v.length===0)return{drawn:F,undrawn:w,cliMissing:!1};h({kind:"note",tone:"info",text:eo(v.length)}),await ve(un(e,v),{display:"/screenshot verify",quietUser:!0});let b=Wr(e,v);return b.length>0&&h({kind:"note",tone:"info",text:b.join(`
522
- `)}),{drawn:F,undrawn:w,cliMissing:!1}},[e,h,Pe,ve]),Rs=re(async(p,m)=>{if(!Ho(e)){await ve(gp(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(!Fw(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)"}),C(!0),qe("Waiting for you to finish logging in (browser window)\u2026");let U=new AbortController;Fe.current=U;let H;try{H=await Uw({cwd:e,signal:U.signal})}catch(te){h({kind:"note",tone:"error",text:`Could not launch the login: ${te.message}`});return}finally{Fe.current=null,qe(null),C(!1)}if(H.exitCode!==0){mp(H.exitCode,H.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(H.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:U.signal.aborted?"warn":"error",text:U.signal.aborted?"Login cancelled \u2014 nothing saved.":`Login did not complete:
523
- ${hp(H.output)}`});return}h({kind:"note",tone:"ok",text:"\u2713 Login saved \u2014 continuing with the capture."})}let u=new Map(p.map(U=>[U,Eg(e,U)])),y=0;if(p.length>1){let U=p.filter(H=>u.get(H).mutates);if(U.length>0&&(y=U.length,p=p.filter(H=>!u.get(H).mutates),p.length===0)){h({kind:"note",tone:"warn",text:`\u26A0 All ${U.length} spec${U.length===1?"":"s"} in scope write real data, so a bulk run has nothing to do. Run one deliberately: /screenshot capture ${U[0]}`});return}}else if(p.length===1&&u.get(p[0]).mutates){let U=u.get(p[0]),H=Ww(e);h({kind:"note",tone:"warn",text:`\u26A0 This capture performs a REAL write in your app${U.what?`: ${Ag(U.what)}`:U.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. `+(H.production?`This profile is PRODUCTION \u2014 the write lands in the LIVE tenant${H.url?` (${H.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.")})}C(!0);let P=new AbortController;Fe.current=P;let F=p.map(U=>({label:U,items:1,status:"pending"}));be({verb:"Capturing",unit:"screenshot",total:p.length,done:0,active:[],rows:F,tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()});let G=Cn(e),w=Object.keys(G.shots).length>0,$=Bw(m?.heldBackBlocked??[],y);h({kind:"note",tone:"info",text:`Capturing ${p.length} screenshot${p.length===1?"":"s"} with d360-capture (a real browser drives your app)\u2026 (esc to stop)`+($?`
524
- ${$}`:"")});let v=Date.now(),b=[];try{for(let U of p){if(P.signal.aborted)break;be(ye=>ye&&{...ye,active:[U],rows:nt(ye.rows,U,"active"),lastAt:Date.now()});let{exitCode:H,output:te}=await fp({cwd:e,id:U,signal:P.signal,stdio:"pipe"});if(mp(H,te)){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 ue=P.signal.aborted&&H!==0?"failed":pp(e,U,H,v),pe=ue==="captured"?void 0:ue==="skipped"?_w(te)??"a data prerequisite isn't met \u2014 the spec's skip reason names what to stage":Mw(te);b.push({id:U,outcome:ue,detail:pe}),be(ye=>ye&&{...ye,active:[],done:ye.done+1,rows:nt(ye.rows,U,ue==="captured"?"done":"failed"),lastAt:Date.now()})}}catch(U){h({kind:"note",tone:"error",text:`Capture run failed: ${U.message}`})}finally{Fe.current=null,be(null),C(!1),W(U=>U+1)}if(b.length===0)return;let R=b.filter(U=>U.outcome==="captured"),N=b.filter(U=>U.outcome==="skipped"),_=b.filter(U=>U.outcome==="failed"),M=p.length-b.length;h({kind:"note",tone:_.length?"warn":R.length?"ok":"info",text:[`\u2713 ${R.length} captured`,N.length?`\u2298 ${N.length} blocked`:"",_.length?`\u2717 ${_.length} broken`:"",M?`${M} not run (stopped)`:""].filter(Boolean).join(" ")+` ${b.length} run${y>0?` \xB7 ${y} held back`:""}`+qw(Hw(G,b),w).map(U=>`
525
- ${U}`).join("")});let D=Gw(N);if(D.length>0&&h({kind:"note",tone:"info",text:D.join(`
526
- `)}),_.length>0){let U=Math.max(..._.map(H=>H.id.length));h({kind:"note",tone:"error",text:_.map(H=>`\u2717 ${H.id.padEnd(U)} ${ai(H.detail)}`).join(`
527
- `)})}ka(e,b.map(U=>({id:U.id,outcome:U.outcome,reason:U.detail,specSource:Lo(e,U.id)})),new Date().toISOString()),b.length===p.length&&_.length===0&&N.length===0&&xn(m?.runLine);let Q=[];if(R.length>0&&gl()){let U=await Ki(R.map(H=>H.id),{verifiedBefore:new Set});if(U.cliMissing||(Q=U.undrawn,U.drawn.length>0))return}else if(R.length>0){h({kind:"note",tone:"info",text:eo(R.length)}),await ve(un(e,R.map(H=>H.id)),{display:"/screenshot verify",quietUser:!0});let U=Wr(e,R.map(H=>H.id));U.length>0&&h({kind:"note",tone:"info",text:U.join(`
528
- `)});return}let j=Vw({results:b,ids:p,articles:Kw(e,R.map(U=>U.id)),...Q.length>0?{unannotated:Q}:{}});j&&Pe(j.note,{kind:"cmd",cmd:j.cmd,reason:""},j.tone)},[e,h,Pe,ve,xn,Ki]),Hc=re(p=>{let m=lo(p);if(!m||Zo(m)&&!m.refreshToken)return null;let u={...ls(m.idToken)??{},...ls(m.accessToken)??{}};return u.email??u.preferred_username??"signed in"},[]),Gc=re((p,m)=>{if(m){let u=ke(e);u&&(u.defaultProfile=p,av(u,e))}i(p),Ve(void 0,p),h({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${p}"${m?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),Hc(p)||(h({kind:"note",tone:"warn",text:`Profile "${p}" is not signed in \u2014 sign in with /login.`}),se("/login")),W(u=>u+1)},[e,h,Ve,Hc,se]),Yi=re((p,m,u)=>{Ji(e,p,m,u.id,u.name),h({kind:"note",tone:"ok",text:`Switched to workspace "${u.name??u.id}" (agent restarted).`}),Ve(),dv(e,p)||(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:Rr(xr(e)).join(`
529
- `)}),$n(jo()),$s.current=zt(e).status==="current",hr.current=Sn(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,Ve,$n]),zi=re(async p=>{let m;try{m=await As(e,p)}catch{h({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),se("/workspace");return}if(m.workspaces.length===0){h({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let u=m.workspaces.filter(P=>(P.workspace_type??"").toLowerCase()!=="apidocumentation"),y=u.length>0?u:m.workspaces;if(y.length===1){let P=y[0],F=m.workspaces.length-y.length;h({kind:"note",tone:"ok",text:`Selected the "${P.name??P.id}" workspace${F>0?" (skipped the API-documentation workspace)":""}.`}),Yi(m.profile,m.projectId,P);return}h({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${y.length} available).`}),se("/workspace")},[e,h,Yi,se]),Xi=re((p,m)=>{Zi(e,p,m.id,m.name),h({kind:"note",tone:"ok",text:`Project set to "${m.name??m.id}" (agent restarted).`}),Ve(),zi(p)},[e,h,Ve,zi]),zf=re(async p=>{let m;try{m=Rt(e,p)}catch{return}if(!m.project.workspaceId){if(m.project.projectId){if(!m.project.projectName)try{let{projects:u}=await Rn(e,m.name),y=u.find(P=>P.id===m.project.projectId);y?.name&&TL(e,m.name,{projectName:y.name})}catch{}await zi(m.name);return}try{let{projects:u}=await Rn(e,m.name);if(u.length===1){let y=u[0];h({kind:"note",tone:"ok",text:`Using your Document360 project "${y.name??y.id}".`}),Xi(m.name,{id:y.id,name:y.name});return}if(u.length>1){let y=u.map(P=>({id:P.id,name:P.name??P.id,sub:P.sub_domain}));h({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),fo({cursor:0,current:-1,rows:y,profile:m.name,environment:m.connection.name});return}}catch{}h({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),se("/project")}},[e,h,zi,Xi,se]),gr=re(()=>{let p=De.current[0];if(!p)return;if(Kt(),p.mode==="local-only"){h({kind:"note",tone:"info",text:`\u25CF ${p.title??p.path} (${p.path})`});for(let F of Qa())h({kind:"note",tone:"warn",text:`\u26A0 ${F}`});h({kind:"note",tone:"info",text:Ja()}),h({kind:"note",tone:"info",text:vy()});return}let{plan:m,mode:u}=p;h({kind:"note",tone:"info",text:`\u25CF ${m.title} (${m.path})`});for(let F of m.notes)h({kind:"note",tone:"warn",text:`\u26A0 ${F}`});m.overwritesLocalChanges&&u==="pull"&&h({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let y=Lt(m.oldContent,m.newContent,et(),Ir);h(y?{kind:"diff",added:y.added,removed:y.removed,lines:y.lines,hidden:y.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."});let P=De.current.length;u==="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:P>1?`(l/p/s \xB7 la/pa/sa for all ${P} \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:P>1?`Write ${m.path}? (y/n \xB7 ya/na for all ${P} \u2014 anything else cancels)`:`Write ${m.path}? (y/n \u2014 anything else cancels)`})},[h,et,Kt]),Ao=re(()=>{if(De.current.length>0){gr();return}let p=Bt.current;Bt.current=[];let m=mn.current;mn.current=[];for(let u of Za(m))h({kind:"note",tone:"warn",text:`\u26A0 ${u}`});p.length>0?(h({kind:"note",tone:"info",text:`Saving ${p.length} kept-local article${p.length===1?"":"s"} over the portal\u2026`}),yt(p,0,{allowUnpullable:!0})):m.length>0||se("/pull")},[gr,h,yt,se]),qc=re(p=>{let m=nc(p);if(!m)return!1;let u=De.current.splice(0),y=u.length;if(m==="local"){for(let P of u)Bt.current.push(XL(P));h({kind:"note",tone:"info",text:`Keeping local for all ${y} \u2014 will publish ${y===1?"it":"them"} over the portal.`})}else if(m==="portal"){let P=0;for(let F of u){if(F.mode==="local-only"){h({kind:"note",tone:"warn",text:`\u26A0 ${pd(F.path)}`}),mn.current.push(F.path);continue}try{gc({cwd:e,profileName:s},F.plan),P++}catch(G){h({kind:"note",tone:"error",text:`Take-portal failed for ${F.plan.path}: ${G.message}`})}}h({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${P} article${P===1?"":"s"} (local overwritten, sync base advanced).`})}else{for(let P of u)P.mode==="local-only"&&mn.current.push(P.path);h({kind:"note",tone:"info",text:`Skipped all ${y} \u2014 still conflict${y===1?"":"s"}.`})}return Ao(),!0},[e,s,Ao,h]),Xf=re(p=>{if(De.current.length===0)return!1;let m=p.trim(),u=m.toLowerCase(),y=De.current[0];if(y.mode==="local-only"){if(nc(m))return qc(m);if(u==="l"||u==="local"||u==="publish")De.current.shift(),Bt.current.push(y.path),h({kind:"note",tone:"info",text:`Publishing your copy of ${y.path} over the portal.`});else if(u==="s"||u==="skip")De.current.shift(),mn.current.push(y.path),h({kind:"note",tone:"info",text:`Skipped ${y.path} \u2014 still a conflict.`});else{let F=De.current.splice(0),G=Bt.current;return Bt.current=[],mn.current=[],h({kind:"note",tone:"info",text:`Resolve cancelled. ${F.length} conflict${F.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&&yt(G,0,{allowUnpullable:!0}),!0}return Ao(),!0}if(y.mode==="conflict"){if(nc(m))return qc(m);if(u==="l"||u==="local")De.current.shift(),Bt.current.push(y.plan.path),h({kind:"note",tone:"info",text:`Keeping local ${y.plan.path} \u2014 will publish over the portal.`});else if(u==="p"||u==="portal"){De.current.shift();try{gc({cwd:e,profileName:s},y.plan),h({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${y.plan.path} (local overwritten, sync base advanced).`})}catch(F){h({kind:"note",tone:"error",text:`Take-portal failed: ${F.message}`})}}else if(u==="s"||u==="skip"||u==="n")De.current.shift(),h({kind:"note",tone:"info",text:`Skipped ${y.plan.path} \u2014 still a conflict.`});else{let F=De.current.length;De.current=[];let G=Bt.current;return Bt.current=[],mn.current=[],h({kind:"note",tone:"info",text:`Resolve cancelled. ${F} conflict${F===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&&yt(G,0,{allowUnpullable:!0}),!0}return Ao(),!0}let P=u$(m);if(P){let F=De.current.splice(0);if(P==="skip")h({kind:"note",tone:"info",text:`Skipped all ${F.length} article${F.length===1?"":"s"}.`});else{let G=0;for(let w of F){if(w.mode==="local-only"){h({kind:"note",tone:"warn",text:`\u26A0 ${pd(w.path)}`});continue}try{gc({cwd:e,profileName:s},w.plan),G++}catch($){h({kind:"note",tone:"error",text:`Pull failed for ${w.plan.path}: ${$.message}`})}}h({kind:"note",tone:"ok",text:`\u2713 Pulled ${G} article${G===1?"":"s"} (sync base advanced).`})}return Ao(),!0}if(u==="y"||u==="yes"){let{plan:F}=y;De.current.shift();try{gc({cwd:e,profileName:s},F),h({kind:"note",tone:"ok",text:`\u2713 Pulled ${F.path} (sync base advanced).`})}catch(G){h({kind:"note",tone:"error",text:`Pull failed: ${G.message}`})}}else if(u==="n"||u==="no")De.current.shift(),h({kind:"note",tone:"info",text:`Skipped ${y.plan.path}.`});else{let F=De.current.length;return De.current=[],h({kind:"note",tone:"info",text:`Pull cancelled (${F} article(s) left untouched).`}),!0}return Ao(),!0},[e,s,Ao,h,qc]),Vc=re(async p=>{h({kind:"note",tone:"info",text:"Checking Document360 for conflicts\u2026"});try{let m=await yc({cwd:e,profileName:s}),u=p?.replace(/\\/g,"/"),y=Xa(e,s,m.entries,Fo(m.entries).map(G=>G.path));if(u){if(!y.includes(u)){h({kind:"note",tone:"ok",text:`${u} isn\u2019t waiting on a decision \u2014 nothing to resolve.`});return}y=[u]}if(y.length===0){h({kind:"note",tone:"ok",text:"\u2713 No conflicts \u2014 local and Document360 agree on every tracked article."});return}let P=[];for(let G of y)try{P.push({plan:await pv({cwd:e,profileName:s,relPath:G}),mode:"conflict"})}catch(w){hv(w)?P.push({mode:"local-only",path:G,title:fv(e,G)}):h({kind:"note",tone:"error",text:`Could not load ${G} from Document360: ${w.message}`})}if(P.length===0)return;let F=P.some(G=>G.mode!=="local-only");h({kind:"note",tone:"info",text:F?`Resolving ${P.length} conflict${P.length===1?"":"s"} \u2014 for each: keep local, take portal, or skip.`:`Resolving ${P.length} conflict${P.length===1?"":"s"} \u2014 for each: publish your copy over the portal, or skip.`}),De.current=P,Bt.current=[],mn.current=[],gr()}catch(m){h({kind:"note",tone:"error",text:`Could not compute sync status: ${m.message}`})}},[e,s,h,gr]),Qf=re(p=>{let m=or.current;if(!m)return!1;if(or.current=null,Kt(),p.trim()!==m.repoName)return h({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:u,failed:y}=Yp(e,m.targets);h({kind:"note",tone:y.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${u.length} item${u.length===1?"":"s"}. The repo is back to its original state.`});for(let P of y)h({kind:"note",tone:"error",text:` \u2717 ${P.path}: ${P.error}`});return m.hadDevhints&&(h({kind:"note",tone:"warn",text:pa().join(`
530
- `)}),$n(uu())),h({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
531
- ${Cv}`}),se("/init"),St(!1),!0},[e,h,$n,Kt,se]),Eo=re(async p=>{let m=p.slice(1).trim().split(/\s+/),u=(m[0]??"").toLowerCase(),y=m.slice(1);if(Mf.current=p.trim(),St(!0),ei(y)&&["write","lint","check","review","reorder"].includes(u)){let w=Zs(e,s);if(w.length===0){h({kind:"note",tone:"warn",text:"No categories yet \u2014 author some articles first, then scope to one."});return}let $=v=>u==="write"?`/write ${nw(y,v).join(" ")}`.trim():`/${u} ${[v,...y.filter(b=>b!=="--scope")].join(" ")}`.trim();if(w.length===1){Eo($(w[0].token));return}go({cursor:0,rows:w,run:v=>{Eo($(v))}});return}if(Zn(u,y)){let w=u==="write"&&ti(y).rewrite,$=u==="write"?zd(e,wv(e),{rewrite:w}):Zs(e,s);if($.length>1){let v=y.filter(H=>H.startsWith("--")).join(" "),b=H=>H==="--blocked"?`/${u} --blocked${v?` ${v}`:""}`.trim():`/${u}${H?` ${u==="write"?`--scope ${H}`:H}`:""}${v?` ${v}`:""} ${H?"":"--all"}`.replace(/\s+/g," ").trim(),R=$.reduce((H,te)=>H+te.count,0),N={token:"",label:u==="review"?`Everything \u2014 all ${R} articles + structure (IA) review`:u==="reorder"?`Everything \u2014 reorder all ${$.length} categories`:w?`Everything \u2014 rewrite all ${R} planned articles`:`Everything \u2014 write all ${R} pending article${R===1?"":"s"}`,count:R},_=u==="review"?gh(e):[],M=_.length>0&&_.length<R?[{token:"--blocked",label:`Only what needs review \u2014 ${_.length} article${_.length===1?"":"s"} publishing is blocked on`,count:_.length}]:[],D=u==="review"?yh(e):[],Q=D.length>_.length&&D.length<R?[{token:"--stale",label:`Everything the current editor hasn\u2019t read \u2014 ${D.length} article${D.length===1?"":"s"}`,count:D.length}]:[],j=u==="write"?`Write which articles? (counts = ${w?"articles to regenerate":"still to write"})`:u==="review"?"Review what? (counts = articles)":"Reorder what?";go({cursor:0,rows:(H=>u==="review"||u==="write"?H.map(te=>{let ue=(()=>{try{return Db(e,b(te.token))}catch{return null}})();return ue?{...te,label:`${te.label} \xB7 ${ue}`}:te}):H)([...M,...Q,N,...$]),run:H=>{Eo(b(H))},title:j});return}}let P=async w=>{let $=cp(w);if(!Ho(e)){await ve(gp(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if($.mode==="single"){await Rs([$.id],{runLine:[`/screenshot capture ${$.id}`,`/capture ${$.id}`]});return}if($.mode==="failed"){let b=up(e,li(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."}),se("/screenshot list");return}await Rs(b);return}if($.mode==="blocked"){let{blocked:b,rows:R}=li(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."}),se("/screenshot list");return}let N=_s(R.filter(_=>_.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.`+(N>0?` If you haven't staged ${N===1?"it":"those "+N+" things"} yet, ${b.length===1?"it":"they"} will skip again \u2014 /screenshot list has the worklist.`:"")}),await Rs(b,{runLine:["/screenshot capture --blocked","/screenshot capture --all --retry-blocked"]});return}if($.mode==="all"||$.mode==="scope"){let b=$.mode==="scope"?$.scope:void 0,{ready:R,captured:N,blocked:_,rows:M}=li(e,b),D=[...R,...N,...$.retryBlocked?_:[]];if(D.length===0&&_.length>0&&!$.retryBlocked){let j=b?`/screenshot capture ${b} --retry-blocked`:"/screenshot capture --blocked";Pe(`All ${_.length} shot${_.length===1?"":"s"} in scope ${_.length===1?"is":"are"} blocked on data that wasn't staged last run \u2014 /screenshot list shows what to stage, then ${j}.`,{kind:"cmd",cmd:"/screenshot list",reason:""},"warn");return}if(D.length===0){h({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),se("/screenshot");return}if(!$.retryBlocked){let j=b?`/screenshot capture ${b} --retry-blocked`:"/screenshot capture --blocked",U=dp(M.filter(H=>H.state==="blocked"),j);U&&h({kind:"note",tone:"info",text:U})}let Q=$.mode==="scope"?[`/screenshot capture ${$.scope}`,`/capture ${$.scope}`]:["/screenshot capture --all","/capture --all"];await Rs(D,{runLine:Q,...$.retryBlocked?{}:{heldBackBlocked:M.filter(j=>j.state==="blocked")}});return}let v=Ow(Ue(e));if(v.length===0){h({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),se("/screenshot");return}mo({cursor:0,rows:v,title:"Capture screenshots \u2014 pick what to shoot:"})},F=async w=>{let $=wp(w);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."}),se("/screenshot capture");return}let v=bt();if(!gl(v)){h({kind:"note",tone:"info",text:kp(v)}),se("/update");return}let b=$.mode==="scope"?$.scope:void 0,{pending:R,done:N,rows:_}=bp(e,b),M=$.mode==="all"||$.mode==="scope"?$.force:!1,D=$.mode==="single"?[$.id]:M?[...R,...N]:R;if(D.length===0){h({kind:"note",tone:"info",text:N.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."}),se(N.length>0?"/screenshot annotate --all --force":"/screenshot capture");return}await Ki(D,{force:M,scope:b,verifiedBefore:new Set(_.filter(Q=>Q.state==="verified").map(Q=>Q.id))})},G=async()=>{let w=await Hr(y,{cwd:e,profileName:s});w.kind==="forward-to-agent"&&w.prompt&&await ve(w.prompt,{display:w.display,quietUser:!0}),Nc()};switch(u){case"help":xo({tab:0,scroll:0});return;case"exit":case"quit":Wt.current?.close(),r();return;case"clear":Ve(),nr.current=[],pt.current={printed:[],armed:[],printedAt:pr.current},St(!1),Kt(),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 w;try{w=Rt(e,s)}catch($){h({kind:"note",tone:"error",text:$.message});return}h({kind:"note",tone:"info",text:`Profile "${w.name}" \u2192 ${w.connection.name} (${w.connection.apiUrl})${w.production?" \u26A0 PRODUCTION":""}`}),E(!0);try{let $=await FI(w.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},R=>h({kind:"note",tone:"info",text:R})),v=UI(w.name,$);WI(v),await eu(v,w.name,R=>h({kind:"note",tone:"info",text:R}));let b=sv(v);if(b){let R=Rt(e,s).project;await Zc(w.name,b,R.projectId===b?R.projectName:void 0)}if(h({kind:"note",tone:"ok",text:`\u2713 Logged in to "${w.name}" as ${ta(lo(w.name,b??void 0)??v)}`}),await zf(s),!$o.current){let R=Je(e,s);R.ok||(h({kind:"note",tone:"warn",text:R.reason}),se("/login"))}if($o.current){let R=$o.current;$o.current=null;let N=Je(e,s);N.ok?(h({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 tab to run ${R}.`}),se(R)):(h({kind:"note",tone:"warn",text:`${N.reason} (then ${R}.)`}),se("/login"),$o.current=R)}else ms.current&&(st(ms.current,"\u21E5 tab to re-send your last prompt\u2026"),ms.current=null)}catch($){if(h({kind:"note",tone:"error",text:`Login failed: ${$.message}`}),!wa(e,s)){let v=$o.current;h({kind:"note",tone:"warn",text:`Your Document360 session still isn't working, so nothing here can reach your portal${v?` \u2014 ${v} is still waiting`:""}. Run /login to try again.`}),se("/login")}}finally{E(!1),W($=>$+1)}return}case"allow-prod":{let w=!1;try{w=Rt(e,s).production}catch{}if(!w){h({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}_n.current=!0,Ve(),h({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let w=op(y.join(" ")),$=fn.current.uuid;if(!$){if(!w){h({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}xc.current=w,po(w),ns(`${ic} ${w}`),h({kind:"note",tone:"ok",text:`Session will be named "${w}" once it starts.`});return}if(!w){h({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let v=fn.current.firstPrompt??"";iv(v,e).then(b=>{b?(st(`/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}tL($,w),po(w),ns(`${ic} ${w}`),h({kind:"note",tone:"ok",text:`Session renamed to "${w}".`});return}case"profile":{let w=y[0],$=ke(e);if(!w){let v=Object.entries($?.profiles??{});if(v.length===0){h({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let b=v.map(([_,M])=>({name:_,env:M.connection?.environment??"custom",prod:M.production===!0,who:Hc(_)})),R=s??$?.defaultProfile,N=Math.max(0,b.findIndex(_=>_.name===R));rr({cursor:N,current:N,rows:b});return}if(w==="add"){let v=rp(e,y[1],y[2]);if(v){h({kind:"note",tone:"error",text:v});return}h({kind:"note",tone:"ok",text:`\u2713 Profile "${y[1]}" created (environment: ${y[2]??y[1]}).`}),Gc(y[1],!0);return}if(!$?.profiles?.[w]){h({kind:"note",tone:"error",text:`Unknown profile "${w}". Create it: /profile add ${w} <environment>`});return}Gc(w,!0);return}case"doctor":await oi(y,{cwd:e,version:o});return;case"logs":{let w=tu();h({kind:"note",tone:"info",text:w.lines.join(`
532
- `)}),w.copyText&&$n(w.copyText,{hint:w.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 w=rh(e);if(Vr(y).sub==="use"){let v=sh(e,Vr(y).value);if(v.pick){h({kind:"note",tone:"info",text:`${v.pick.title}
533
- ${v.pick.lead}`}),we(v.pick.options.map(b=>({cmd:b.cmd,desc:b.desc}))),yo(v.pick.title),Mi.current=v.pick.options.map(b=>b.cmd.trim()),W(b=>b+1);return}if(v.lines.length>0&&h({kind:"note",tone:"info",text:v.lines.join(`
534
- `)}),v.restart&&(Ve(),h({kind:"note",tone:"ok",text:"\u2713 Agent restarted \u2014 it now writes to the new rules."})),v.editorial){let b=Zt(e,v.editorial.cmd);Pe(ih(v.editorial).join(`
535
- `),{kind:"cmd",cmd:v.editorial.cmd,reason:"it reads every article the new guide flagged and rewrites it",...b?{detail:b}:{}})}W(b=>b+1);return}let $=await Nl(y,{cwd:e,profileName:s});if(w&&Vr(y).sub==="show"&&Pe(null,{kind:"cmd",cmd:"/style-guide keep",reason:""}),$.kind==="clear")Ve(),h({kind:"note",tone:"ok",text:"\u2713 Agent restarted \u2014 it now writes to the new rules."});else if($.kind==="forward-to-agent"){let v=Vr(y).sub==="learn";(await ve($.prompt,{display:$.display,quietUser:!0})).producedNothing||(h({kind:"note",tone:"info",text:(v?Cb():Pb()).join(`
536
- `)}),v&&(Ve(),h({kind:"note",tone:"ok",text:"\u2713 Agent restarted \u2014 it now writes to your house rules."})))}W(v=>v+1);return}case"genre":{let w=ke(e)?.appType??null;(await Wl(y,{cwd:e})).kind==="clear"&&(ke(e)?.appType??null)!==w&&(Ve(),h({kind:"note",tone:"ok",text:"\u2713 Agent restarted \u2014 the doc-craft playbook for this genre is now loaded."}));try{Ge.current=!(ke(e)?.appType??uv(e))}catch{}W(v=>v+1);return}case"roadmap":{if(y[0]?.toLowerCase()==="done"){let w=Nr(e,y.slice(1).join(" ").trim());h({kind:"note",tone:w.ok?"ok":"warn",text:w.line}),W($=>$+1);return}h({kind:"block",text:Bu(e,{width:et(),all:y.some(w=>w.toLowerCase()==="--all")}).join(`
537
- `)});return}case"mcp":await ma(y);return;case"init":{if(ke(e)){let $=Un(e,s);h({kind:"note",tone:"info",text:["This repo is already set up \u2014 /init won\u2019t overwrite it.",` Change environment: /profile add <${mv().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(`
538
- `)}),$&&h({kind:"note",tone:"warn",text:`\u26A0 ${$.why} \u2014 ${$.cmd} moves this repo.`});return}let w=[...mv(),...mL().filter($=>gv($))].map($=>({name:$,apiUrl:gL($).apiUrl,note:gv($)?"being retired":null}));sr({cursor:0,rows:w});return}case"resume":{let w=y.join(" ").trim(),$=eL(e).filter(R=>R.uuid!==fn.current.uuid);if(!w){if(!$.length){h({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}vo({query:"",cursor:0,sessions:$});return}let v=ZI(e,w);if(!v){h({kind:"note",tone:"error",text:`No session matches "${w}".`});return}Ve(v.uuid),fn.current={uuid:v.uuid,firstPrompt:v.firstPrompt,titleFired:!0},po(v.name),lf(v.uuid),nr.current=[],pt.current={printed:[],armed:[],printedAt:pr.current};let b=ef(e,v.uuid);for(let R of b)h(R);h({kind:"note",tone:"ok",text:b.length?`Resumed "${v.name}" \u2014 restored ${b.length} message(s); continue where you left off.`:`Resumed "${v.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let w=y.join(" ").trim(),$;try{$=await As(e,s)}catch(b){h({kind:"note",tone:"error",text:`Could not list workspaces: ${b.message}`});return}if(!w){let b=$.workspaces.map(N=>({id:N.id,name:N.name??N.id,type:N.workspace_type}));if(b.length===0){h({kind:"note",tone:"info",text:"No workspaces in this project."});return}let R=Math.max(0,b.findIndex(N=>N.id===$.current));ir({cursor:R,current:R,rows:b,profile:$.profile,projectId:$.projectId,projectName:$.projectName,environment:$.environment});return}let v=zc($.workspaces,w);if(!v){h({kind:"note",tone:"error",text:`No workspace matches "${w}".`});return}Yi($.profile,$.projectId,v);return}case"project":{let w=y.join(" ").trim(),$;try{$=await Rn(e,s)}catch(b){h({kind:"note",tone:"error",text:`Could not list projects: ${b.message} (signed in? try /login)`});return}if(!w){let b=$.projects.map(N=>({id:N.id,name:N.name??N.id,sub:N.sub_domain}));if(b.length===0){h({kind:"note",tone:"info",text:"No projects found for this identity."});return}let R=b.findIndex(N=>N.id===$.current);fo({cursor:Math.max(0,R),current:R,rows:b,profile:$.profile,environment:$.environment});return}let v=Xc($.projects,w);if(!v){h({kind:"note",tone:"error",text:`No project matches "${w}". Available: ${$.projects.map(b=>b.name??b.id).join(", ")}`});return}Xi($.profile,v);return}case"logout":{let w,$,v;try{let M=Rt(e,s);w=M.name,$=M.project.projectId,v=M.project.projectName}catch(M){h({kind:"note",tone:"error",text:M.message});return}let b=y.includes("--all-projects"),R=YI(w).filter(M=>{let D=sv(M);return!!D&&D!==$}).length,N=VI(w,b?void 0:$);zI(e,w),Ve(),W(M=>M+1);let _=b||R===0?"":` Your sign-in for ${R} other project${R===1?"":"s"} is untouched (/logout --all-projects clears those too).`;h({kind:"note",tone:N?"ok":"info",text:N?b?`\u2713 Signed out of every Document360 project for "${w}" and cleared this repo's project/workspace selection.`:`\u2713 Signed out of ${v?`"${v}"`:`"${w}"`} and cleared its project/workspace selection.${_}`:`Profile "${w}" was not signed in. Cleared any project/workspace selection.${_}`}),h({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),se("/login");return}case"publish":{if(ed(y)){h({kind:"note",tone:"info",text:Ga()}),await Eo(`/push ${y.join(" ")}`.trim());return}if(!Po(p.trim()))return;let w=y.find(D=>!D.startsWith("--")),$={skipReview:y.includes(jt),skipStyle:y.includes(xv),...w?{scope:w}:{}};qe("Checking what is waiting to go live\u2026");let v;try{v=await td(e,s,w)}catch(D){h({kind:"note",tone:"error",text:`Could not check Document360: ${D.message}`});return}finally{qe(null)}if(v.length===0){let D=nd(e,s,w);for(let Q of D.lines)h({kind:"note",tone:Q.startsWith("\u2713")?"ok":"info",text:Q});D.ahead>0&&se(Se("/push","",w));return}let b=wc(e,v.map(D=>D.path),{allowUnreviewed:$.skipReview,allowStyleErrors:$.skipStyle,checkScreenshots:!0,allowPlaceholders:y.includes(IL)}),R=jL(b),N=v.filter(D=>R.has(D.path)),_=v.filter(D=>!R.has(D.path)),M=qa(e,b,w);if(N.length>0)for(let D of ff(b,v.length,{scope:w,act:"publish",going:_.length,shotFix:M.shotFix}))h({kind:"note",tone:"warn",text:D});if(_.length===0){M.cmd&&se(M.cmd);return}if(v=_,Xe.current&&Di.current){h({kind:"note",tone:"info",text:`Taking ${v.length} draft${v.length===1?"":"s"} live \u2014 you approved this run when it started.`}),await qf(v,$);return}h({kind:"note",tone:"info",text:`${v.length} draft${v.length===1?" is":"s are"} ahead of what readers see. Pick what goes live:`}),lr({cursor:0,rows:v,opts:$});return}case"push":{if(!Po(p.trim()))return;let w=y.includes(jt),$=y.includes(xv);if(y.includes("--preview")){let N=y.find(_=>!_.startsWith("--"));if(!N){h({kind:"note",tone:"error",text:"Which article? Use /push --preview <path> \u2014 a preview is per article."});return}try{let _=await uL({cwd:e,profileName:s,relPath:N.replace(/\\/g,"/"),preview:!0}),M=_.shots.length>0?` \xB7 ${_.shots.length} screenshot${_.shots.length===1?"":"s"} embedded`:"";h({kind:"note",tone:"info",text:`${_.title}
539
- ${_.path} \xB7 ${_.articleId?`updates article ${_.articleId}`:"would be created as a new article"}${M}`}),_.missingShots.length>0&&h({kind:"note",tone:"warn",text:`\u26A0 ${_.missingShots.length} screenshot${_.missingShots.length===1?"":"s"} not taken yet \u2014 the description publishes instead: ${_.missingShots.join(", ")}`}),h({kind:"note",tone:"info",text:_.body}),h({kind:"note",tone:"info",text:`Nothing was sent. /push ${_.path} saves it as a draft.`}),se(`/push ${_.path}`)}catch(_){h({kind:"note",tone:"error",text:_.message})}return}if(y.includes("--screenshots")||y.includes("--shots")){let N=y.find(j=>!j.startsWith("--")),_=Ue(e),M=Pa(_,N);if(M.length===0){let j=_.filter(U=>U.state==="captured").length;h({kind:"note",tone:"info",text:j>0?`${j} screenshot${j===1?" has":"s have"} been taken but the callouts aren't drawn on yet, so there is nothing to embed \u2014 /screenshot annotate finishes ${j===1?"it":"them"}.`:N?`No captured screenshots in ${N} \u2014 /push --screenshots covers the whole knowledge base.`:"No captured screenshots yet \u2014 /screenshot capture first."}),j>0&&se("/screenshot annotate");return}let D=Ta(_,N);D&&h({kind:"note",tone:"warn",text:D});let Q=Aa(_);Q&&h({kind:"note",tone:"warn",text:Q}),h({kind:"note",tone:"info",text:`Re-saving ${M.length} article${M.length===1?"":"s"} with captured screenshots so the images embed\u2026`}),await yt(M,0,{skipReview:w,skipStyle:$,scope:Se("","--screenshots",N).trim()});return}if(y[0]==="--related"&&y[1]){let N=await Wa(e,s,y[1].replace(/\\/g,"/"));if(N.length===0){h({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await yt(N,0,{skipReview:w,skipStyle:$,scope:`--related ${y[1]}`});return}let v=y.filter(N=>!N.startsWith("--"));if(v[0]){await Bc(v[0],{skipReview:w,skipStyle:$});return}let b=y.includes("--all"),R=y.includes("--force");h({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let N=await yc({cwd:e,profileName:s}),_=new Set(Mo(e,s)),{clean:M,conflicts:D}=_o(N.entries,_),Q=D.filter(H=>_.has(H.path)).length,j=b&&R&&D.length>0,U=_a(N.entries);if(U>0&&h({kind:"note",tone:"warn",text:`\u26A0 ${U} article${U===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.`}),D.length>0&&!j&&h({kind:"note",tone:"warn",text:Fs(D.length,Q)}),M.length===0&&!j){let H=Dr(e,s);if(H&&h({kind:"note",tone:"info",text:H}),D.length>0){se("/resolve");return}h({kind:"note",tone:"ok",text:U>0?"\u2713 Nothing else is ahead of Document360 to save.":"\u2713 Nothing is ahead of Document360 \u2014 nothing to save."});let te=N.counts["unknown-base"]??0;te>0&&h({kind:"note",tone:"info",text:`(${te} article(s) have no sync base yet \u2014 /push <path> saves one anyway if you need it.)`}),qe("Reconciling structure on Document360 (order + related articles)\u2026");try{let ue=await pf({cwd:e,profileName:s,onRateLimit:J=>qe(`Document360 rate limit \u2014 waiting ${Math.ceil(J.waitMs/1e3)}s\u2026`)}),pe=vv(await $v({cwd:e,profileName:s})),ye=hf(ue);ye?h({kind:"note",tone:ye.startsWith("\u26A0")?"warn":"info",text:ye}):ue.skipped&&h({kind:"note",tone:"warn",text:`Order sync skipped: ${ue.skipped}`}),pe&&h({kind:"note",tone:"info",text:pe}),ue.failures?.length?se("/structure"):(h({kind:"note",tone:"ok",text:ye||pe?"\u2713 Structure synced to Document360 \u2014 /structure shows the new category + article order.":"\u2713 Already in order \u2014 nothing to change."}),(ye||pe)&&se("/structure"))}catch(ue){h({kind:"note",tone:"warn",text:`Structure sync failed: ${ue.message}`})}finally{qe(null)}return}if(b){let H=(j?[...M,...D]:M).map(te=>te.path);await yt(H,j?0:D.length,{skipReview:w,skipStyle:$,allowUnpullable:R,unreadableSkipped:j?0:Q});return}ar({cursor:0,rows:ly(M,D),conflicts:D.length})}catch(N){h({kind:"note",tone:"error",text:`Could not compute sync status: ${N.message}`}),h({kind:"note",tone:"info",text:"Save one article on its own: /push <article-path>"})}return}case"resolve":{if(!Po(p.trim()))return;await Vc(y.find(w=>!w.startsWith("--")));return}case"preview":{let w=y.join(" ").trim();if(!w){let v=[];try{v=Object.keys(dv(e,Rt(e,s).name)?.articles??{})}catch{}if(v.length===0){h({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}wo({query:"",cursor:0,paths:v});return}let $=_I(w)?w:Pi(e,w);if(rs($)){try{h({kind:"preview",name:Ci($),text:Ev(fc($,"utf8"))})}catch(v){h({kind:"note",tone:"error",text:`Could not read ${$}: ${v.message}`})}return}if(eO.test(w)){try{let v=Rt(e,s),b={profile:v.name,connection:v.connection},R=v.project.projectId??GI(b),N=await qI(b,R,w);h({kind:"preview",name:N.title??w,text:N.content??"*(article has no content)*"})}catch(v){h({kind:"note",tone:"error",text:`Could not fetch article: ${v.message}`})}return}h({kind:"note",tone:"error",text:`"${w}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let w=y[0]?.trim();if(!w){let R=pl(gf(e));ho({cursor:R,current:R});return}let{lines:$,changed:v,effective:b}=ni(e,w);for(let R of $)h({kind:"note",tone:R.startsWith("\u26A0")?"warn":R.startsWith("\u2713")?"ok":"info",text:R});v&&(jf(R=>R+1),Wt.current?.setModel(b));return}case"verbose":{let w=y[0]?.trim().toLowerCase(),$=w==="on"?!0:w==="off"?!1:!Ei.current;Ei.current=$;try{sL({...cv(),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(!ke(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:w,run:$}=Cd(y),v=bL(e,s);if(v.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=Pd(v,w);if(b.length===0){h({kind:"note",tone:"error",text:`No tracked articles under "${w}". (${v.length} are tracked overall.)`});return}let R=cf(b),N=3,_=`/convert${w?` --scope ${w}`:""} --run`,M=Ai(e,"light");if(!$){let j=yv({files:Td(e,b),op:"convert",model:M.model}),U=w?`Scope: ${w} (${b.length} of ${v.length} tracked)
540
- `:"",H=`
541
- Model: ${M.model}${M.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;h({kind:"note",tone:"info",text:U+Ed(R,j,N).join(`
542
- `)+H}),se(_);return}Ut.current=Date.now(),Ft(0),C(!0);let D=new AbortController;Fe.current=D;let Q=Date.now();be({verb:"Converting",total:R.length,done:0,active:[],rows:Qo(R),tools:0,chars:0,lastAt:Date.now(),startedAt:Q}),h({kind:"note",tone:"info",text:`Converting ${b.length} articles in ${R.length} batches (\u2264${N} agents at once) on ${M.model}\u2026 (esc to stop)`});try{for await(let j of Ti({cwd:e,partitions:R,promptFor:Ad,concurrency:N,profileName:s,allowProdWrites:_n.current,model:M.model,signal:D.signal}))if(j.type==="partition_status")j.status==="running"?be(U=>U&&{...U,active:[...U.active,j.label],rows:nt(U.rows,j.label,"active"),lastAt:Date.now()}):be(U=>U&&{...U,active:U.active.filter(H=>H!==j.label),done:U.done+1,rows:nt(U.rows,j.label,j.status==="done"?"done":"failed"),lastAt:Date.now()});else if(j.type==="partition_stalled"){let U=ts(j);be(H=>H&&U?{...H,stalledNote:U}:H)}else if(j.type==="partition_event")be(U=>{if(!U)return U;let H={...U,lastAt:Date.now()};return j.event.type==="tool"?H.tools=U.tools+1:j.event.type==="text"&&(H.chars=U.chars+j.event.delta.length),H});else if(j.type==="run_done"){So(ue=>ue+j.totalCostUsd),Ro(ue=>ue+j.results.reduce((pe,ye)=>pe+ye.outputTokens,0));let U=j.aborted?"Stopped. ":"",H=t.kind==="api"?"api":"subscription",te=zn(j,"The conversion");h({kind:"note",tone:te||j.aborted?"warn":j.ok?"ok":"warn",text:te?te.join(`
543
- `):U+Nd(j.results,R,H).join(`
544
- `)}),mr(Q,j.results,j.totalCostUsd,!te&&!j.aborted&&j.ok),te&&se("/doctor")}}catch(j){h({kind:"note",tone:"error",text:`Convert run failed: ${j.message}`})}finally{Fe.current=null,be(null),C(!1),W(j=>j+1)}return}case"write":{if(!ke(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let w=wv(e);if(w.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:v,preview:b,concurrency:R,rewrite:N}=ti(y);if(!v&&!b&&!(ke(e)?.appType??uv(e))){h({kind:"note",tone:"warn",text:`\u26A0 No doc genre is set, so no doc-craft playbook would load \u2014 all ${w.length} articles would be written generically.
522
+ ${w.length===1?"It has":"They have"} no publishable picture yet. Re-take the shot: /screenshot capture`})}if(m.chainVerify===!1||_.length===0)return{drawn:_,undrawn:w,cliMissing:!1};let k=_.filter(R=>m.verifiedBefore.has(R)).length;if(k>vl){let R=nb({results:y,voidedVerdicts:k,...m.scope?{scope:m.scope}:{}});return R&&Pe(`${R.glyph} ${R.cmd} ${R.why}`,{kind:"cmd",cmd:R.cmd,reason:""},"warn"),{drawn:_,undrawn:w,cliMissing:!1}}let v=_.filter(R=>!m.verifiedBefore.has(R)||k>0);if(v.length===0)return{drawn:_,undrawn:w,cliMissing:!1};h({kind:"note",tone:"info",text:to(v.length)}),await ve(dn(e,v),{display:"/screenshot verify",quietUser:!0});let b=Ur(e,v);return b.length>0&&h({kind:"note",tone:"info",text:b.join(`
523
+ `)}),{drawn:_,undrawn:w,cliMissing:!1}},[e,h,Pe,ve]),Cs=re(async(p,m)=>{if(!Go(e)){await ve($p(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(!Vw(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)"}),C(!0),qe("Waiting for you to finish logging in (browser window)\u2026");let U=new AbortController;Fe.current=U;let G;try{G=await Yw({cwd:e,signal:U.signal})}catch(te){h({kind:"note",tone:"error",text:`Could not launch the login: ${te.message}`});return}finally{Fe.current=null,qe(null),C(!1)}if(G.exitCode!==0){kp(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:U.signal.aborted?"warn":"error",text:U.signal.aborted?"Login cancelled \u2014 nothing saved.":`Login did not complete:
524
+ ${wp(G.output)}`});return}h({kind:"note",tone:"ok",text:"\u2713 Login saved \u2014 continuing with the capture."})}let u=new Map(p.map(U=>[U,_g(e,U)])),y=0;if(p.length>1){let U=p.filter(G=>u.get(G).mutates);if(U.length>0&&(y=U.length,p=p.filter(G=>!u.get(G).mutates),p.length===0)){h({kind:"note",tone:"warn",text:`\u26A0 All ${U.length} spec${U.length===1?"":"s"} in scope write real data, so a bulk run has nothing to do. Run one deliberately: /screenshot capture ${U[0]}`});return}}else if(p.length===1&&u.get(p[0]).mutates){let U=u.get(p[0]),G=Kw(e);h({kind:"note",tone:"warn",text:`\u26A0 This capture performs a REAL write in your app${U.what?`: ${Og(U.what)}`:U.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.")})}C(!0);let P=new AbortController;Fe.current=P;let _=p.map(U=>({label:U,items:1,status:"pending"}));be({verb:"Capturing",unit:"screenshot",total:p.length,done:0,active:[],rows:_,tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()});let H=Tn(e),w=Object.keys(H.shots).length>0,k=zw(m?.heldBackBlocked??[],y);h({kind:"note",tone:"info",text:`Capturing ${p.length} screenshot${p.length===1?"":"s"} with d360-capture (a real browser drives your app)\u2026 (esc to stop)`+(k?`
525
+ ${k}`:"")});let v=Date.now(),b=[];try{for(let U of p){if(P.signal.aborted)break;be(ye=>ye&&{...ye,active:[U],rows:rt(ye.rows,U,"active"),lastAt:Date.now()});let{exitCode:G,output:te}=await bp({cwd:e,id:U,signal:P.signal,stdio:"pipe"});if(kp(G,te)){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 de=P.signal.aborted&&G!==0?"failed":yp(e,U,G,v),pe=de==="captured"?void 0:de==="skipped"?Gw(te)??"a data prerequisite isn't met \u2014 the spec's skip reason names what to stage":qw(te);b.push({id:U,outcome:de,detail:pe}),be(ye=>ye&&{...ye,active:[],done:ye.done+1,rows:rt(ye.rows,U,de==="captured"?"done":"failed"),lastAt:Date.now()})}}catch(U){h({kind:"note",tone:"error",text:`Capture run failed: ${U.message}`})}finally{Fe.current=null,be(null),C(!1),W(U=>U+1)}if(b.length===0)return;let R=b.filter(U=>U.outcome==="captured"),N=b.filter(U=>U.outcome==="skipped"),M=b.filter(U=>U.outcome==="failed"),F=p.length-b.length;h({kind:"note",tone:M.length?"warn":R.length?"ok":"info",text:[`\u2713 ${R.length} captured`,N.length?`\u2298 ${N.length} blocked`:"",M.length?`\u2717 ${M.length} broken`:"",F?`${F} not run (stopped)`:""].filter(Boolean).join(" ")+` ${b.length} run${y>0?` \xB7 ${y} held back`:""}`+Jw(Xw(H,b),w).map(U=>`
526
+ ${U}`).join("")});let D=Qw(N);if(D.length>0&&h({kind:"note",tone:"info",text:D.join(`
527
+ `)}),M.length>0){let U=Math.max(...M.map(G=>G.id.length));h({kind:"note",tone:"error",text:M.map(G=>`\u2717 ${G.id.padEnd(U)} ${ci(G.detail)}`).join(`
528
+ `)})}Sa(e,b.map(U=>({id:U.id,outcome:U.outcome,reason:U.detail,specSource:Oo(e,U.id)})),new Date().toISOString()),b.length===p.length&&M.length===0&&N.length===0&&Sn(m?.runLine);let X=[];if(R.length>0&&$l()){let U=await Ji(R.map(G=>G.id),{verifiedBefore:new Set});if(U.cliMissing||(X=U.undrawn,U.drawn.length>0))return}else if(R.length>0){h({kind:"note",tone:"info",text:to(R.length)}),await ve(dn(e,R.map(G=>G.id)),{display:"/screenshot verify",quietUser:!0});let U=Ur(e,R.map(G=>G.id));U.length>0&&h({kind:"note",tone:"info",text:U.join(`
529
+ `)});return}let I=Zw({results:b,ids:p,articles:eb(e,R.map(U=>U.id)),...X.length>0?{unannotated:X}:{}});I&&Pe(I.note,{kind:"cmd",cmd:I.cmd,reason:""},I.tone)},[e,h,Pe,ve,Sn,Ji]),Kc=re(p=>{let m=lo(p);if(!m||tr(m)&&!m.refreshToken)return null;let u={...as(m.idToken)??{},...as(m.accessToken)??{}};return u.email??u.preferred_username??"signed in"},[]),zc=re((p,m)=>{if(m){let u=ke(e);u&&(u.defaultProfile=p,gv(u,e))}i(p),Ve(void 0,p),h({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${p}"${m?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),Kc(p)||(h({kind:"note",tone:"warn",text:`Profile "${p}" is not signed in \u2014 sign in with /login.`}),se("/login")),W(u=>u+1)},[e,h,Ve,Kc,se]),Zi=re((p,m,u)=>{oa(e,p,m,u.id,u.name),h({kind:"note",tone:"ok",text:`Switched to workspace "${u.name??u.id}" (agent restarted).`}),Ve(),kv(e,p)||(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:xr(vr(e)).join(`
530
+ `)}),xn(Io()),xs.current=Xt(e).status==="current",pr.current=Pn(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,Ve,xn]),ea=re(async p=>{let m;try{m=await Ns(e,p)}catch{h({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),se("/workspace");return}if(m.workspaces.length===0){h({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let u=m.workspaces.filter(P=>(P.workspace_type??"").toLowerCase()!=="apidocumentation"),y=u.length>0?u:m.workspaces;if(y.length===1){let P=y[0],_=m.workspaces.length-y.length;h({kind:"note",tone:"ok",text:`Selected the "${P.name??P.id}" workspace${_>0?" (skipped the API-documentation workspace)":""}.`}),Zi(m.profile,m.projectId,P);return}h({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${y.length} available).`}),se("/workspace")},[e,h,Zi,se]),ta=re((p,m)=>{ra(e,p,m.id,m.name),h({kind:"note",tone:"ok",text:`Project set to "${m.name??m.id}" (agent restarted).`}),Ve(),ea(p)},[e,h,Ve,ea]),nm=re(async p=>{let m;try{m=St(e,p)}catch{return}if(!m.project.workspaceId){if(m.project.projectId){if(!m.project.projectName)try{let{projects:u}=await Cn(e,m.name),y=u.find(P=>P.id===m.project.projectId);y?.name&&VL(e,m.name,{projectName:y.name})}catch{}await ea(m.name);return}try{let{projects:u}=await Cn(e,m.name);if(u.length===1){let y=u[0];h({kind:"note",tone:"ok",text:`Using your Document360 project "${y.name??y.id}".`}),ta(m.name,{id:y.id,name:y.name});return}if(u.length>1){let y=u.map(P=>({id:P.id,name:P.name??P.id,sub:P.sub_domain}));h({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),mo({cursor:0,current:-1,rows:y,profile:m.name,environment:m.connection.name});return}}catch{}h({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),se("/project")}},[e,h,ea,ta,se]),mr=re(()=>{let p=De.current[0];if(!p)return;if(Kt(),p.mode==="local-only"){h({kind:"note",tone:"info",text:`\u25CF ${p.title??p.path} (${p.path})`});for(let _ of nl())h({kind:"note",tone:"warn",text:`\u26A0 ${_}`});h({kind:"note",tone:"info",text:ol()}),h({kind:"note",tone:"info",text:Ay()});return}let{plan:m,mode:u}=p;h({kind:"note",tone:"info",text:`\u25CF ${m.title} (${m.path})`});for(let _ of m.notes)h({kind:"note",tone:"warn",text:`\u26A0 ${_}`});m.overwritesLocalChanges&&u==="pull"&&h({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let y=Mt(m.oldContent,m.newContent,tt(),jr);h(y?{kind:"diff",added:y.added,removed:y.removed,lines:y.lines,hidden:y.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."});let P=De.current.length;u==="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:P>1?`(l/p/s \xB7 la/pa/sa for all ${P} \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:P>1?`Write ${m.path}? (y/n \xB7 ya/na for all ${P} \u2014 anything else cancels)`:`Write ${m.path}? (y/n \u2014 anything else cancels)`})},[h,tt,Kt]),Eo=re(()=>{if(De.current.length>0){mr();return}let p=Ht.current;Ht.current=[];let m=yn.current;yn.current=[];for(let u of rl(m))h({kind:"note",tone:"warn",text:`\u26A0 ${u}`});p.length>0?(h({kind:"note",tone:"info",text:`Saving ${p.length} kept-local article${p.length===1?"":"s"} over the portal\u2026`}),wt(p,0,{allowUnpullable:!0})):m.length>0||se("/pull")},[mr,h,wt,se]),Xc=re(p=>{let m=lc(p);if(!m)return!1;let u=De.current.splice(0),y=u.length;if(m==="local"){for(let P of u)Ht.current.push(fO(P));h({kind:"note",tone:"info",text:`Keeping local for all ${y} \u2014 will publish ${y===1?"it":"them"} over the portal.`})}else if(m==="portal"){let P=0;for(let _ of u){if(_.mode==="local-only"){h({kind:"note",tone:"warn",text:`\u26A0 ${yd(_.path)}`}),yn.current.push(_.path);continue}try{vc({cwd:e,profileName:s},_.plan),P++}catch(H){h({kind:"note",tone:"error",text:`Take-portal failed for ${_.plan.path}: ${H.message}`})}}h({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${P} article${P===1?"":"s"} (local overwritten, sync base advanced).`})}else{for(let P of u)P.mode==="local-only"&&yn.current.push(P.path);h({kind:"note",tone:"info",text:`Skipped all ${y} \u2014 still conflict${y===1?"":"s"}.`})}return Eo(),!0},[e,s,Eo,h]),om=re(p=>{if(De.current.length===0)return!1;let m=p.trim(),u=m.toLowerCase(),y=De.current[0];if(y.mode==="local-only"){if(lc(m))return Xc(m);if(u==="l"||u==="local"||u==="publish")De.current.shift(),Ht.current.push(y.path),h({kind:"note",tone:"info",text:`Publishing your copy of ${y.path} over the portal.`});else if(u==="s"||u==="skip")De.current.shift(),yn.current.push(y.path),h({kind:"note",tone:"info",text:`Skipped ${y.path} \u2014 still a conflict.`});else{let _=De.current.splice(0),H=Ht.current;return Ht.current=[],yn.current=[],h({kind:"note",tone:"info",text:`Resolve cancelled. ${_.length} conflict${_.length===1?"":"s"} left untouched.`+(H.length>0?` Saving the ${H.length} article${H.length===1?"":"s"} you already chose to keep - an answer you gave is not undone by stopping.`:"")}),H.length>0&&wt(H,0,{allowUnpullable:!0}),!0}return Eo(),!0}if(y.mode==="conflict"){if(lc(m))return Xc(m);if(u==="l"||u==="local")De.current.shift(),Ht.current.push(y.plan.path),h({kind:"note",tone:"info",text:`Keeping local ${y.plan.path} \u2014 will publish over the portal.`});else if(u==="p"||u==="portal"){De.current.shift();try{vc({cwd:e,profileName:s},y.plan),h({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${y.plan.path} (local overwritten, sync base advanced).`})}catch(_){h({kind:"note",tone:"error",text:`Take-portal failed: ${_.message}`})}}else if(u==="s"||u==="skip"||u==="n")De.current.shift(),h({kind:"note",tone:"info",text:`Skipped ${y.plan.path} \u2014 still a conflict.`});else{let _=De.current.length;De.current=[];let H=Ht.current;return Ht.current=[],yn.current=[],h({kind:"note",tone:"info",text:`Resolve cancelled. ${_} conflict${_===1?"":"s"} left untouched.`+(H.length>0?` Saving the ${H.length} article${H.length===1?"":"s"} you already chose to keep - an answer you gave is not undone by stopping.`:"")}),H.length>0&&wt(H,0,{allowUnpullable:!0}),!0}return Eo(),!0}let P=b$(m);if(P){let _=De.current.splice(0);if(P==="skip")h({kind:"note",tone:"info",text:`Skipped all ${_.length} article${_.length===1?"":"s"}.`});else{let H=0;for(let w of _){if(w.mode==="local-only"){h({kind:"note",tone:"warn",text:`\u26A0 ${yd(w.path)}`});continue}try{vc({cwd:e,profileName:s},w.plan),H++}catch(k){h({kind:"note",tone:"error",text:`Pull failed for ${w.plan.path}: ${k.message}`})}}h({kind:"note",tone:"ok",text:`\u2713 Pulled ${H} article${H===1?"":"s"} (sync base advanced).`})}return Eo(),!0}if(u==="y"||u==="yes"){let{plan:_}=y;De.current.shift();try{vc({cwd:e,profileName:s},_),h({kind:"note",tone:"ok",text:`\u2713 Pulled ${_.path} (sync base advanced).`})}catch(H){h({kind:"note",tone:"error",text:`Pull failed: ${H.message}`})}}else if(u==="n"||u==="no")De.current.shift(),h({kind:"note",tone:"info",text:`Skipped ${y.plan.path}.`});else{let _=De.current.length;return De.current=[],h({kind:"note",tone:"info",text:`Pull cancelled (${_} article(s) left untouched).`}),!0}return Eo(),!0},[e,s,Eo,h,Xc]),Qc=re(async p=>{h({kind:"note",tone:"info",text:"Checking Document360 for conflicts\u2026"});try{let m=await xc({cwd:e,profileName:s}),u=p?.replace(/\\/g,"/"),y=tl(e,s,m.entries,Uo(m.entries).map(H=>H.path));if(u){if(!y.includes(u)){h({kind:"note",tone:"ok",text:`${u} isn\u2019t waiting on a decision \u2014 nothing to resolve.`});return}y=[u]}if(y.length===0){h({kind:"note",tone:"ok",text:"\u2713 No conflicts \u2014 local and Document360 agree on every tracked article."});return}let P=[];for(let H of y)try{P.push({plan:await $v({cwd:e,profileName:s,relPath:H}),mode:"conflict"})}catch(w){vv(w)?P.push({mode:"local-only",path:H,title:xv(e,H)}):h({kind:"note",tone:"error",text:`Could not load ${H} from Document360: ${w.message}`})}if(P.length===0)return;let _=P.some(H=>H.mode!=="local-only");h({kind:"note",tone:"info",text:_?`Resolving ${P.length} conflict${P.length===1?"":"s"} \u2014 for each: keep local, take portal, or skip.`:`Resolving ${P.length} conflict${P.length===1?"":"s"} \u2014 for each: publish your copy over the portal, or skip.`}),De.current=P,Ht.current=[],yn.current=[],mr()}catch(m){h({kind:"note",tone:"error",text:`Could not compute sync status: ${m.message}`})}},[e,s,h,mr]),rm=re(p=>{let m=nr.current;if(!m)return!1;if(nr.current=null,Kt(),p.trim()!==m.repoName)return h({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:u,failed:y}=eh(e,m.targets);h({kind:"note",tone:y.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${u.length} item${u.length===1?"":"s"}. The repo is back to its original state.`});for(let P of y)h({kind:"note",tone:"error",text:` \u2717 ${P.path}: ${P.error}`});return m.hadDevhints&&(h({kind:"note",tone:"warn",text:ya().join(`
531
+ `)}),xn(mu())),h({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
532
+ ${Ov}`}),se("/init"),Ct(!1),!0},[e,h,xn,Kt,se]),No=re(async p=>{let m=p.slice(1).trim().split(/\s+/),u=(m[0]??"").toLowerCase(),y=m.slice(1);if(qf.current=p.trim(),Ct(!0),ni(y)&&["write","lint","check","review","reorder"].includes(u)){let w=ti(e,s);if(w.length===0){h({kind:"note",tone:"warn",text:"No categories yet \u2014 author some articles first, then scope to one."});return}let k=v=>u==="write"?`/write ${cw(y,v).join(" ")}`.trim():`/${u} ${[v,...y.filter(b=>b!=="--scope")].join(" ")}`.trim();if(w.length===1){No(k(w[0].token));return}yo({cursor:0,rows:w,run:v=>{No(k(v))}});return}if(eo(u,y)){let w=u==="write"&&oi(y).rewrite,k=u==="write"?ep(e,Pv(e),{rewrite:w}):ti(e,s);if(k.length>1){let v=y.filter(G=>G.startsWith("--")).join(" "),b=G=>G==="--blocked"?`/${u} --blocked${v?` ${v}`:""}`.trim():`/${u}${G?` ${u==="write"?`--scope ${G}`:G}`:""}${v?` ${v}`:""} ${G?"":"--all"}`.replace(/\s+/g," ").trim(),R=k.reduce((G,te)=>G+te.count,0),N={token:"",label:u==="review"?`Everything \u2014 all ${R} articles + structure (IA) review`:u==="reorder"?`Everything \u2014 reorder all ${k.length} categories`:w?`Everything \u2014 rewrite all ${R} planned articles`:`Everything \u2014 write all ${R} pending article${R===1?"":"s"}`,count:R},M=u==="review"?vh(e):[],F=M.length>0&&M.length<R?[{token:"--blocked",label:`Only what needs review \u2014 ${M.length} article${M.length===1?"":"s"} publishing is blocked on`,count:M.length}]:[],D=u==="review"?xh(e):[],X=D.length>M.length&&D.length<R?[{token:"--stale",label:`Everything the current editor hasn\u2019t read \u2014 ${D.length} article${D.length===1?"":"s"}`,count:D.length}]:[],I=u==="write"?`Write which articles? (counts = ${w?"articles to regenerate":"still to write"})`:u==="review"?"Review what? (counts = articles)":"Reorder what?";yo({cursor:0,rows:(G=>u==="review"||u==="write"?G.map(te=>{let de=(()=>{try{return Ub(e,b(te.token))}catch{return null}})();return de?{...te,label:`${te.label} \xB7 ${de}`}:te}):G)([...F,...X,N,...k]),run:G=>{No(b(G))},title:I});return}}let P=async w=>{let k=fp(w);if(!Go(e)){await ve($p(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(k.mode==="single"){await Cs([k.id],{runLine:[`/screenshot capture ${k.id}`,`/capture ${k.id}`]});return}if(k.mode==="failed"){let b=mp(e,ui(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."}),se("/screenshot list");return}await Cs(b);return}if(k.mode==="blocked"){let{blocked:b,rows:R}=ui(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."}),se("/screenshot list");return}let N=Fs(R.filter(M=>M.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.`+(N>0?` If you haven't staged ${N===1?"it":"those "+N+" things"} yet, ${b.length===1?"it":"they"} will skip again \u2014 /screenshot list has the worklist.`:"")}),await Cs(b,{runLine:["/screenshot capture --blocked","/screenshot capture --all --retry-blocked"]});return}if(k.mode==="all"||k.mode==="scope"){let b=k.mode==="scope"?k.scope:void 0,{ready:R,captured:N,blocked:M,rows:F}=ui(e,b),D=[...R,...N,...k.retryBlocked?M:[]];if(D.length===0&&M.length>0&&!k.retryBlocked){let I=b?`/screenshot capture ${b} --retry-blocked`:"/screenshot capture --blocked";Pe(`All ${M.length} shot${M.length===1?"":"s"} in scope ${M.length===1?"is":"are"} blocked on data that wasn't staged last run \u2014 /screenshot list shows what to stage, then ${I}.`,{kind:"cmd",cmd:"/screenshot list",reason:""},"warn");return}if(D.length===0){h({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),se("/screenshot");return}if(!k.retryBlocked){let I=b?`/screenshot capture ${b} --retry-blocked`:"/screenshot capture --blocked",U=gp(F.filter(G=>G.state==="blocked"),I);U&&h({kind:"note",tone:"info",text:U})}let X=k.mode==="scope"?[`/screenshot capture ${k.scope}`,`/capture ${k.scope}`]:["/screenshot capture --all","/capture --all"];await Cs(D,{runLine:X,...k.retryBlocked?{}:{heldBackBlocked:F.filter(I=>I.state==="blocked")}});return}let v=Hw(Ue(e));if(v.length===0){h({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),se("/screenshot");return}go({cursor:0,rows:v,title:"Capture screenshots \u2014 pick what to shoot:"})},_=async w=>{let k=xp(w);if(!Go(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."}),se("/screenshot capture");return}let v=kt();if(!$l(v)){h({kind:"note",tone:"info",text:Sp(v)}),se("/update");return}let b=k.mode==="scope"?k.scope:void 0,{pending:R,done:N,rows:M}=Rp(e,b),F=k.mode==="all"||k.mode==="scope"?k.force:!1,D=k.mode==="single"?[k.id]:F?[...R,...N]:R;if(D.length===0){h({kind:"note",tone:"info",text:N.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."}),se(N.length>0?"/screenshot annotate --all --force":"/screenshot capture");return}await Ji(D,{force:F,scope:b,verifiedBefore:new Set(M.filter(X=>X.state==="verified").map(X=>X.id))})},H=async()=>{let w=await Br(y,{cwd:e,profileName:s});w.kind==="forward-to-agent"&&w.prompt&&await ve(w.prompt,{display:w.display,quietUser:!0}),_c()};switch(u){case"help":Ro({tab:0,scroll:0});return;case"exit":case"quit":Tt.current?.close(),r();return;case"clear":Ve(),ct.current=[],ht.current={printed:[],armed:[],printedAt:dr.current},Ct(!1),Kt(),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 w;try{w=St(e,s)}catch(k){h({kind:"note",tone:"error",text:k.message});return}h({kind:"note",tone:"info",text:`Profile "${w.name}" \u2192 ${w.connection.name} (${w.connection.apiUrl})${w.production?" \u26A0 PRODUCTION":""}`}),E(!0);try{let k=await rL(w.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},R=>h({kind:"note",tone:"info",text:R})),v=sL(w.name,k);iL(v),await su(v,w.name,R=>h({kind:"note",tone:"info",text:R}));let b=fv(v);if(b){let R=St(e,s).project;await ru(w.name,b,R.projectId===b?R.projectName:void 0)}if(h({kind:"note",tone:"ok",text:`\u2713 Logged in to "${w.name}" as ${ia(lo(w.name,b??void 0)??v)}`}),await nm(s),!vo.current){let R=Je(e,s);R.ok||(h({kind:"note",tone:"warn",text:R.reason}),se("/login"))}if(vo.current){let R=vo.current;vo.current=null;let N=Je(e,s);N.ok?(h({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 tab to run ${R}.`}),se(R)):(h({kind:"note",tone:"warn",text:`${N.reason} (then ${R}.)`}),se("/login"),vo.current=R)}else ys.current&&(nt(ys.current,"\u21E5 tab to re-send your last prompt\u2026"),ys.current=null)}catch(k){if(h({kind:"note",tone:"error",text:`Login failed: ${k.message}`}),!xa(e,s)){let v=vo.current;h({kind:"note",tone:"warn",text:`Your Document360 session still isn't working, so nothing here can reach your portal${v?` \u2014 ${v} is still waiting`:""}. Run /login to try again.`}),se("/login")}}finally{E(!1),W(k=>k+1)}return}case"allow-prod":{let w=!1;try{w=St(e,s).production}catch{}if(!w){h({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}Mn.current=!0,Ve(),h({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let w=lp(y.join(" ")),k=gn.current.uuid;if(!k){if(!w){h({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}Tc.current=w,ho(w),ts(`${pc} ${w}`),h({kind:"note",tone:"ok",text:`Session will be named "${w}" once it starts.`});return}if(!w){h({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let v=gn.current.firstPrompt??"";mv(v,e).then(b=>{b?(nt(`/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}kL(k,w),ho(w),ts(`${pc} ${w}`),h({kind:"note",tone:"ok",text:`Session renamed to "${w}".`});return}case"profile":{let w=y[0],k=ke(e);if(!w){let v=Object.entries(k?.profiles??{});if(v.length===0){h({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let b=v.map(([M,F])=>({name:M,env:F.connection?.environment??"custom",prod:F.production===!0,who:Kc(M)})),R=s??k?.defaultProfile,N=Math.max(0,b.findIndex(M=>M.name===R));or({cursor:N,current:N,rows:b});return}if(w==="add"){let v=cp(e,y[1],y[2]);if(v){h({kind:"note",tone:"error",text:v});return}h({kind:"note",tone:"ok",text:`\u2713 Profile "${y[1]}" created (environment: ${y[2]??y[1]}).`}),zc(y[1],!0);return}if(!k?.profiles?.[w]){h({kind:"note",tone:"error",text:`Unknown profile "${w}". Create it: /profile add ${w} <environment>`});return}zc(w,!0);return}case"doctor":await si(y,{cwd:e,version:o});return;case"logs":{let w=iu();h({kind:"note",tone:"info",text:w.lines.join(`
533
+ `)}),w.copyText&&xn(w.copyText,{hint:w.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 w=uh(e);if(qr(y).sub==="use"){let v=dh(e,qr(y).value);if(v.pick){h({kind:"note",tone:"info",text:`${v.pick.title}
534
+ ${v.pick.lead}`}),we(v.pick.options.map(b=>({cmd:b.cmd,desc:b.desc}))),wo(v.pick.title),Bi.current=v.pick.options.map(b=>b.cmd.trim()),W(b=>b+1);return}if(v.lines.length>0&&h({kind:"note",tone:"info",text:v.lines.join(`
535
+ `)}),v.restart&&(Ve(),h({kind:"note",tone:"ok",text:"\u2713 Agent restarted \u2014 it now writes to the new rules."})),v.editorial){let b=en(e,v.editorial.cmd);Pe(ph(v.editorial).join(`
536
+ `),{kind:"cmd",cmd:v.editorial.cmd,reason:"it reads every article the new guide flagged and rewrites it",...b?{detail:b}:{}})}W(b=>b+1);return}let k=await _l(y,{cwd:e,profileName:s});if(w&&qr(y).sub==="show"&&Pe(null,{kind:"cmd",cmd:"/style-guide keep",reason:""}),k.kind==="clear")Ve(),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 v=qr(y).sub==="learn";(await ve(k.prompt,{display:k.display,quietUser:!0})).producedNothing||(h({kind:"note",tone:"info",text:(v?Ib():Lb()).join(`
537
+ `)}),v&&(Ve(),h({kind:"note",tone:"ok",text:"\u2713 Agent restarted \u2014 it now writes to your house rules."})))}W(v=>v+1);return}case"genre":{let w=ke(e)?.appType??null;(await Yl(y,{cwd:e})).kind==="clear"&&(ke(e)?.appType??null)!==w&&(Ve(),h({kind:"note",tone:"ok",text:"\u2713 Agent restarted \u2014 the doc-craft playbook for this genre is now loaded."}));try{ze.current=!(ke(e)?.appType??bv(e))}catch{}W(v=>v+1);return}case"roadmap":{if(y[0]?.toLowerCase()==="done"){let w=Er(e,y.slice(1).join(" ").trim());h({kind:"note",tone:w.ok?"ok":"warn",text:w.line}),W(k=>k+1);return}h({kind:"block",text:Yu(e,{width:tt(),all:y.some(w=>w.toLowerCase()==="--all")}).join(`
538
+ `)});return}case"mcp":await ka(y);return;case"init":{if(ke(e)){let k=Wn(e,s);h({kind:"note",tone:"info",text:["This repo is already set up \u2014 /init won\u2019t overwrite it.",` Change environment: /profile add <${Rv().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(`
539
+ `)}),k&&h({kind:"note",tone:"warn",text:`\u26A0 ${k.why} \u2014 ${k.cmd} moves this repo.`});return}let w=[...Rv(),...IL().filter(k=>Sv(k))].map(k=>({name:k,apiUrl:LL(k).apiUrl,note:Sv(k)?"being retired":null}));rr({cursor:0,rows:w});return}case"resume":{let w=y.join(" ").trim(),k=bL(e).filter(R=>R.uuid!==gn.current.uuid);if(!w){if(!k.length){h({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}xo({query:"",cursor:0,sessions:k});return}let v=wL(e,w);if(!v){h({kind:"note",tone:"error",text:`No session matches "${w}".`});return}Ve(v.uuid),gn.current={uuid:v.uuid,firstPrompt:v.firstPrompt,titleFired:!0},ho(v.name),ff(v.uuid),ct.current=[],ht.current={printed:[],armed:[],printedAt:dr.current};let b=af(e,v.uuid);for(let R of b)h(R);h({kind:"note",tone:"ok",text:b.length?`Resumed "${v.name}" \u2014 restored ${b.length} message(s); continue where you left off.`:`Resumed "${v.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let w=y.join(" ").trim(),k;try{k=await Ns(e,s)}catch(b){h({kind:"note",tone:"error",text:`Could not list workspaces: ${b.message}`});return}if(!w){let b=k.workspaces.map(N=>({id:N.id,name:N.name??N.id,type:N.workspace_type}));if(b.length===0){h({kind:"note",tone:"info",text:"No workspaces in this project."});return}let R=Math.max(0,b.findIndex(N=>N.id===k.current));sr({cursor:R,current:R,rows:b,profile:k.profile,projectId:k.projectId,projectName:k.projectName,environment:k.environment});return}let v=eu(k.workspaces,w);if(!v){h({kind:"note",tone:"error",text:`No workspace matches "${w}".`});return}Zi(k.profile,k.projectId,v);return}case"project":{let w=y.join(" ").trim(),k;try{k=await Cn(e,s)}catch(b){h({kind:"note",tone:"error",text:`Could not list projects: ${b.message} (signed in? try /login)`});return}if(!w){let b=k.projects.map(N=>({id:N.id,name:N.name??N.id,sub:N.sub_domain}));if(b.length===0){h({kind:"note",tone:"info",text:"No projects found for this identity."});return}let R=b.findIndex(N=>N.id===k.current);mo({cursor:Math.max(0,R),current:R,rows:b,profile:k.profile,environment:k.environment});return}let v=tu(k.projects,w);if(!v){h({kind:"note",tone:"error",text:`No project matches "${w}". Available: ${k.projects.map(b=>b.name??b.id).join(", ")}`});return}ta(k.profile,v);return}case"logout":{let w,k,v;try{let F=St(e,s);w=F.name,k=F.project.projectId,v=F.project.projectName}catch(F){h({kind:"note",tone:"error",text:F.message});return}let b=y.includes("--all-projects"),R=hL(w).filter(F=>{let D=fv(F);return!!D&&D!==k}).length,N=dL(w,b?void 0:k);fL(e,w),Ve(),W(F=>F+1);let M=b||R===0?"":` Your sign-in for ${R} other project${R===1?"":"s"} is untouched (/logout --all-projects clears those too).`;h({kind:"note",tone:N?"ok":"info",text:N?b?`\u2713 Signed out of every Document360 project for "${w}" and cleared this repo's project/workspace selection.`:`\u2713 Signed out of ${v?`"${v}"`:`"${w}"`} and cleared its project/workspace selection.${M}`:`Profile "${w}" was not signed in. Cleared any project/workspace selection.${M}`}),h({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),se("/login");return}case"publish":{if(sd(y)){h({kind:"note",tone:"info",text:za()}),await No(`/push ${y.join(" ")}`.trim());return}if(!To(p.trim()))return;let w=y.find(D=>!D.startsWith("--")),k={skipReview:y.includes(Ot),skipStyle:y.includes(jv),...w?{scope:w}:{}};qe("Checking what is waiting to go live\u2026");let v;try{v=await id(e,s,w)}catch(D){h({kind:"note",tone:"error",text:`Could not check Document360: ${D.message}`});return}finally{qe(null)}if(v.length===0){let D=ad(e,s,w);for(let X of D.lines)h({kind:"note",tone:X.startsWith("\u2713")?"ok":"info",text:X});D.ahead>0&&se(Se("/push","",w));return}let b=Rc(e,v.map(D=>D.path),{allowUnreviewed:k.skipReview,allowStyleErrors:k.skipStyle,checkScreenshots:!0,allowPlaceholders:y.includes(JL)}),R=QL(b),N=v.filter(D=>R.has(D.path)),M=v.filter(D=>!R.has(D.path)),F=Xa(e,b,w);if(N.length>0)for(let D of kf(b,v.length,{scope:w,act:"publish",going:M.length,shotFix:F.shotFix}))h({kind:"note",tone:"warn",text:D});if(M.length===0){F.cmd&&se(F.cmd);return}if(v=M,Xe.current&&_i.current){h({kind:"note",tone:"info",text:`Taking ${v.length} draft${v.length===1?"":"s"} live \u2014 you approved this run when it started.`}),await Jf(v,k);return}h({kind:"note",tone:"info",text:`${v.length} draft${v.length===1?" is":"s are"} ahead of what readers see. Pick what goes live:`}),ar({cursor:0,rows:v,opts:k});return}case"push":{if(!To(p.trim()))return;let w=y.includes(Ot),k=y.includes(jv);if(y.includes("--preview")){let N=y.find(M=>!M.startsWith("--"));if(!N){h({kind:"note",tone:"error",text:"Which article? Use /push --preview <path> \u2014 a preview is per article."});return}try{let M=await AL({cwd:e,profileName:s,relPath:N.replace(/\\/g,"/"),preview:!0}),F=M.shots.length>0?` \xB7 ${M.shots.length} screenshot${M.shots.length===1?"":"s"} embedded`:"";h({kind:"note",tone:"info",text:`${M.title}
540
+ ${M.path} \xB7 ${M.articleId?`updates article ${M.articleId}`:"would be created as a new article"}${F}`}),M.missingShots.length>0&&h({kind:"note",tone:"warn",text:`\u26A0 ${M.missingShots.length} screenshot${M.missingShots.length===1?"":"s"} not taken yet \u2014 the description publishes instead: ${M.missingShots.join(", ")}`}),h({kind:"note",tone:"info",text:M.body}),h({kind:"note",tone:"info",text:`Nothing was sent. /push ${M.path} saves it as a draft.`}),se(`/push ${M.path}`)}catch(M){h({kind:"note",tone:"error",text:M.message})}return}if(y.includes("--screenshots")||y.includes("--shots")){let N=y.find(I=>!I.startsWith("--")),M=Ue(e),F=Da(M,N);if(F.length===0){let I=M.filter(U=>U.state==="captured").length;h({kind:"note",tone:"info",text:I>0?`${I} screenshot${I===1?" has":"s have"} been taken but the callouts aren't drawn on yet, so there is nothing to embed \u2014 /screenshot annotate finishes ${I===1?"it":"them"}.`:N?`No captured screenshots in ${N} \u2014 /push --screenshots covers the whole knowledge base.`:"No captured screenshots yet \u2014 /screenshot capture first."}),I>0&&se("/screenshot annotate");return}let D=ja(M,N);D&&h({kind:"note",tone:"warn",text:D});let X=Ia(M);X&&h({kind:"note",tone:"warn",text:X}),h({kind:"note",tone:"info",text:`Re-saving ${F.length} article${F.length===1?"":"s"} with captured screenshots so the images embed\u2026`}),await wt(F,0,{skipReview:w,skipStyle:k,scope:Se("","--screenshots",N).trim()});return}if(y[0]==="--related"&&y[1]){let N=await Va(e,s,y[1].replace(/\\/g,"/"));if(N.length===0){h({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await wt(N,0,{skipReview:w,skipStyle:k,scope:`--related ${y[1]}`});return}let v=y.filter(N=>!N.startsWith("--"));if(v[0]){await Yc(v[0],{skipReview:w,skipStyle:k});return}let b=y.includes("--all"),R=y.includes("--force");h({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let N=await xc({cwd:e,profileName:s}),M=new Set(Fo(e,s)),{clean:F,conflicts:D}=Mo(N.entries,M),X=D.filter(G=>M.has(G.path)).length,I=b&&R&&D.length>0,U=Ba(N.entries);if(U>0&&h({kind:"note",tone:"warn",text:`\u26A0 ${U} article${U===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.`}),D.length>0&&!I&&h({kind:"note",tone:"warn",text:Ws(D.length,X)}),F.length===0&&!I){let G=Nr(e,s);if(G&&h({kind:"note",tone:"info",text:G}),D.length>0){se("/resolve");return}h({kind:"note",tone:"ok",text:U>0?"\u2713 Nothing else is ahead of Document360 to save.":"\u2713 Nothing is ahead of Document360 \u2014 nothing to save."});let te=N.counts["unknown-base"]??0;te>0&&h({kind:"note",tone:"info",text:`(${te} article(s) have no sync base yet \u2014 /push <path> saves one anyway if you need it.)`}),qe("Reconciling structure on Document360 (order + related articles)\u2026");try{let de=await wf({cwd:e,profileName:s,onRateLimit:J=>qe(`Document360 rate limit \u2014 waiting ${Math.ceil(J.waitMs/1e3)}s\u2026`)}),pe=Dv(await Nv({cwd:e,profileName:s})),ye=bf(de);ye?h({kind:"note",tone:ye.startsWith("\u26A0")?"warn":"info",text:ye}):de.skipped&&h({kind:"note",tone:"warn",text:`Order sync skipped: ${de.skipped}`}),pe&&h({kind:"note",tone:"info",text:pe}),de.failures?.length?se("/structure"):(h({kind:"note",tone:"ok",text:ye||pe?"\u2713 Structure synced to Document360 \u2014 /structure shows the new category + article order.":"\u2713 Already in order \u2014 nothing to change."}),(ye||pe)&&se("/structure"))}catch(de){h({kind:"note",tone:"warn",text:`Structure sync failed: ${de.message}`})}finally{qe(null)}return}if(b){let G=(I?[...F,...D]:F).map(te=>te.path);await wt(G,I?0:D.length,{skipReview:w,skipStyle:k,allowUnpullable:R,unreadableSkipped:I?0:X});return}ir({cursor:0,rows:my(F,D),conflicts:D.length})}catch(N){h({kind:"note",tone:"error",text:`Could not compute sync status: ${N.message}`}),h({kind:"note",tone:"info",text:"Save one article on its own: /push <article-path>"})}return}case"resolve":{if(!To(p.trim()))return;await Qc(y.find(w=>!w.startsWith("--")));return}case"preview":{let w=y.join(" ").trim();if(!w){let v=[];try{v=Object.keys(kv(e,St(e,s).name)?.articles??{})}catch{}if(v.length===0){h({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}bo({query:"",cursor:0,paths:v});return}let k=nL(w)?w:Ni(e,w);if(os(k)){try{h({kind:"preview",name:Ei(k),text:Uv(kc(k,"utf8"))})}catch(v){h({kind:"note",tone:"error",text:`Could not read ${k}: ${v.message}`})}return}if(wO.test(w)){try{let v=St(e,s),b={profile:v.name,connection:v.connection},R=v.project.projectId??cL(b),N=await uL(b,R,w);h({kind:"preview",name:N.title??w,text:N.content??"*(article has no content)*"})}catch(v){h({kind:"note",tone:"error",text:`Could not fetch article: ${v.message}`})}return}h({kind:"note",tone:"error",text:`"${w}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let w=y[0]?.trim();if(!w){let R=yl(vf(e));fo({cursor:R,current:R});return}let{lines:k,changed:v,effective:b}=ri(e,w);for(let R of k)h({kind:"note",tone:R.startsWith("\u26A0")?"warn":R.startsWith("\u2713")?"ok":"info",text:R});v&&(Ff(R=>R+1),Tt.current?.setModel(b));return}case"verbose":{let w=y[0]?.trim().toLowerCase(),k=w==="on"?!0:w==="off"?!1:!Li.current;Li.current=k;try{RL({...wv(),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(!ke(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:w,run:k}=Nd(y),v=ML(e,s);if(v.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=Dd(v,w);if(b.length===0){h({kind:"note",tone:"error",text:`No tracked articles under "${w}". (${v.length} are tracked overall.)`});return}let R=mf(b),N=3,M=`/convert${w?` --scope ${w}`:""} --run`,F=ji(e,"light");if(!k){let I=Cv({files:jd(e,b),op:"convert",model:F.model}),U=w?`Scope: ${w} (${b.length} of ${v.length} tracked)
541
+ `:"",G=`
542
+ Model: ${F.model}${F.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;h({kind:"note",tone:"info",text:U+Ld(R,I,N).join(`
543
+ `)+G}),se(M);return}Pt.current=Date.now(),rn(0),C(!0);let D=new AbortController;Fe.current=D;let X=Date.now();be({verb:"Converting",total:R.length,done:0,active:[],rows:Zo(R),tools:0,chars:0,lastAt:Date.now(),startedAt:X}),h({kind:"note",tone:"info",text:`Converting ${b.length} articles in ${R.length} batches (\u2264${N} agents at once) on ${F.model}\u2026 (esc to stop)`});try{for await(let I of Di({cwd:e,partitions:R,promptFor:Id,concurrency:N,profileName:s,allowProdWrites:Mn.current,model:F.model,signal:D.signal}))if(I.type==="partition_status")I.status==="running"?be(U=>U&&{...U,active:[...U.active,I.label],rows:rt(U.rows,I.label,"active"),lastAt:Date.now()}):be(U=>U&&{...U,active:U.active.filter(G=>G!==I.label),done:U.done+1,rows:rt(U.rows,I.label,I.status==="done"?"done":"failed"),lastAt:Date.now()});else if(I.type==="partition_stalled"){let U=es(I);be(G=>G&&U?{...G,stalledNote:U}:G)}else if(I.type==="partition_event")be(U=>{if(!U)return U;let G={...U,lastAt:Date.now()};return I.event.type==="tool"?G.tools=U.tools+1:I.event.type==="text"&&(G.chars=U.chars+I.event.delta.length),G});else if(I.type==="run_done"){Co(de=>de+I.totalCostUsd),So(de=>de+I.results.reduce((pe,ye)=>pe+ye.outputTokens,0));let U=I.aborted?"Stopped. ":"",G=t.kind==="api"?"api":"subscription",te=Xn(I,"The conversion");h({kind:"note",tone:te||I.aborted?"warn":I.ok?"ok":"warn",text:te?te.join(`
544
+ `):U+Od(I.results,R,G).join(`
545
+ `)}),fr(X,I.results,I.totalCostUsd,!te&&!I.aborted&&I.ok),te&&se("/doctor")}}catch(I){h({kind:"note",tone:"error",text:`Convert run failed: ${I.message}`})}finally{Fe.current=null,be(null),C(!1),W(I=>I+1)}return}case"write":{if(!ke(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let w=Pv(e);if(w.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:v,preview:b,concurrency:R,rewrite:N}=oi(y);if(!v&&!b&&!(ke(e)?.appType??bv(e))){h({kind:"note",tone:"warn",text:`\u26A0 No doc genre is set, so no doc-craft playbook would load \u2014 all ${w.length} articles would be written generically.
545
546
  Pick the genre below (one keypress), then run /write again \u2014 it changes structure, titles and depth for every article.
546
- Not blocked: /write <path> still authors a single article, and /write --preview costs nothing.`}),we(Bl.options.map(J=>({cmd:J.cmd,desc:J.desc}))),yo(Bl.title);return}let{docsDir:_,targets:M,reason:D,rewriting:Q}=ul(e,w,{scope:$,path:v,rewrite:N});if(M.length===0){h({kind:"note",tone:"warn",text:D??"Nothing to write."});return}Q&&h({kind:"note",tone:"warn",text:`--rewrite: regenerating ${M.length} already-written article${M.length===1?"":"s"} (overwrites them; git has your baseline).`});let j=cf(M),U=Wd(R),H=Ai(e,"standard"),te=!!v;if(b&&!te){let J=yv({files:Bd(e,w,M),op:"write",model:H.model}),$e=$?`Scope: ${$} (${M.length} pending)
547
+ Not blocked: /write <path> still authors a single article, and /write --preview costs nothing.`}),we(Kl.options.map(J=>({cmd:J.cmd,desc:J.desc}))),wo(Kl.title);return}let{docsDir:M,targets:F,reason:D,rewriting:X}=ml(e,w,{scope:k,path:v,rewrite:N});if(F.length===0){h({kind:"note",tone:"warn",text:D??"Nothing to write."});return}X&&h({kind:"note",tone:"warn",text:`--rewrite: regenerating ${F.length} already-written article${F.length===1?"":"s"} (overwrites them; git has your baseline).`});let I=mf(F),U=Vd(R),G=ji(e,"standard"),te=!!v;if(b&&!te){let J=Cv({files:Yd(e,w,F),op:"write",model:G.model}),$e=k?`Scope: ${k} (${F.length} pending)
547
548
  `:"",Le=`
548
- Model: ${H.model}${H.forced?" (forced)":" \u2014 authoring; /model to override"}`;h({kind:"note",tone:"info",text:$e+Gd(j,J,U).join(`
549
- `)+Le}),se(`/write${$?` --scope ${$}`:""}`);return}Ut.current=Date.now(),Ft(0),C(!0);let ue=new AbortController;Fe.current=ue;let pe=Date.now();be({verb:"Writing",total:j.length,done:0,active:[],rows:Qo(j),tools:0,chars:0,lastAt:Date.now(),startedAt:pe}),h({kind:"note",tone:"info",text:`Writing ${M.length} article${M.length===1?"":"s"} in ${j.length} batch${j.length===1?"":"es"} (\u2264${U} agents at once) on ${H.model}${H.forced?" (forced)":""}\u2026 (esc to stop)`});let ye=new Set;try{for await(let J of Ti({cwd:e,partitions:j,promptFor:$e=>Hd($e,_,{rewrite:Q||te}),concurrency:U,profileName:s,allowProdWrites:_n.current,model:H.model,signal:ue.signal}))if(J.type==="partition_status")J.status==="running"?be($e=>$e&&{...$e,active:[...$e.active,J.label],rows:nt($e.rows,J.label,"active"),lastAt:Date.now()}):be($e=>$e&&{...$e,active:$e.active.filter(Le=>Le!==J.label),done:$e.done+1,rows:nt($e.rows,J.label,J.status==="done"?"done":"failed"),lastAt:Date.now()});else if(J.type==="partition_stalled"){let $e=ts(J);be(Le=>Le&&$e?{...Le,stalledNote:$e}:Le)}else if(J.type==="partition_event"){let $e=null;if(J.event.type==="tool"){let Le=rf(J.event.name,J.event.input,j[J.index]?.paths??[]);Le&&!ye.has(Le)&&(ye.add(Le),$e=J.label)}be(Le=>{if(!Le)return Le;let Yt={...Le,lastAt:Date.now()};return J.event.type==="tool"?Yt.tools=Le.tools+1:J.event.type==="text"&&(Yt.chars=Le.chars+J.event.delta.length),$e&&(Yt.rows=cc(Yt.rows,$e)),Yt})}else if(J.type==="run_done"){So(lt=>lt+J.totalCostUsd),Ro(lt=>lt+J.results.reduce((Nt,Do)=>Nt+Do.outputTokens,0));let $e=J.aborted?"Stopped. ":"",Le=t.kind==="api"?"api":"subscription",Yt=zn(J,"The write");if(h({kind:"note",tone:Yt||J.aborted?"warn":J.ok?"ok":"warn",text:Yt?Yt.join(`
550
- `):$e+qd(J.results,j,Le,$??v).join(`
551
- `)}),mr(pe,J.results,J.totalCostUsd,!Yt&&!J.aborted&&J.ok),Yt){se("/doctor");continue}let tm=Ny(J);if(tm&&h({kind:"note",tone:"warn",text:tm}),!J.aborted&&J.ok)try{let lt=(ye.size>0?[...ye]:M).map(Nt=>`${_}/${Nt}`);is(e,lt,{writtenCap:CL,reviewedCap:0,checkedCap:0})}catch{}let No=J.aborted?[]:Ur(e,_,M),nm=Vd(No);nm&&h({kind:"note",tone:"warn",text:nm});let wr=J.aborted||y.includes("--skip-style")?null:Kd(No);if(wr){let lt=wr.errors.length,Nt=await Vi({partitions:wr.partitions,promptFor:wr.promptFor,concurrency:Mr,verb:"Fixing",doneNoun:"fixed",headline:`${lt} style error${lt===1?"":"s"} in ${wr.articles} of the new article${wr.articles===1?"":"s"} \u2014 fixing now, one pass`});if(Nt.covered.length>0)try{is(e,Nt.covered,ft("lint"))}catch{}No=Ur(e,_,M);let Do=Yd(lt,No);h({kind:"note",tone:Do[0].startsWith("\u2713")?"ok":"warn",text:Do.join(`
552
- `)})}if(!J.aborted&&J.ok){let lt=$??v??"",Nt=lt?` ${lt}`:"",Do=No.some(br=>br.severity==="error");{let br=uf(j,J.results);xn(`/write${$?` --scope ${$}`:""}${y.includes("--rewrite")?" --rewrite":""}`,{aborted:J.aborted,partitions:j.length,failed:br.failed.length,notRun:br.notRun.length,leftBehind:No.filter(Yv=>Yv.severity==="error").length,...J.blocked?{blocked:J.blocked}:{},...J.allEmpty?{allEmpty:!0}:{},...J.bailedEmpty?{bailedEmpty:!0}:{}})}let om=lt?"/push":"/push --all",Kv=lt?`/screenshot author ${lt}`:"/screenshot author --all";Pe(Do?`Written, but ${No.filter(br=>br.severity==="error").length} style error(s) are still unfixed. /lint${Nt} --blocked --fix retries them, then /review${Nt} --fix for editorial quality, then ${om}.`:`Written. I\u2019d run /review${Nt} --fix next \u2014 editorial review that applies its fixes \u2014 then ${om} saves them to Document360 as drafts (add ${Kv} first if you want images).`,{kind:"cmd",cmd:Do?`/lint${Nt} --blocked --fix`:`/review${Nt} --fix`,reason:""})}}}catch(J){h({kind:"note",tone:"error",text:`Write run failed: ${J.message}`})}finally{Fe.current=null,be(null),C(!1),W(J=>J+1)}return}case"draft":{if(!ke(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:w,looseDocs:$}=Xd(e);if(w.length===0&&$===0){h({kind:"note",tone:"info",text:Jd});return}let v=y.join(" ").trim();if(!v&&w.length>1){h({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
549
+ Model: ${G.model}${G.forced?" (forced)":" \u2014 authoring; /model to override"}`;h({kind:"note",tone:"info",text:$e+zd(I,J,U).join(`
550
+ `)+Le}),se(`/write${k?` --scope ${k}`:""}`);return}Pt.current=Date.now(),rn(0),C(!0);let de=new AbortController;Fe.current=de;let pe=Date.now();be({verb:"Writing",total:I.length,done:0,active:[],rows:Zo(I),tools:0,chars:0,lastAt:Date.now(),startedAt:pe}),h({kind:"note",tone:"info",text:`Writing ${F.length} article${F.length===1?"":"s"} in ${I.length} batch${I.length===1?"":"es"} (\u2264${U} agents at once) on ${G.model}${G.forced?" (forced)":""}\u2026 (esc to stop)`});let ye=new Set;try{for await(let J of Di({cwd:e,partitions:I,promptFor:$e=>Kd($e,M,{rewrite:X||te}),concurrency:U,profileName:s,allowProdWrites:Mn.current,model:G.model,signal:de.signal}))if(J.type==="partition_status")J.status==="running"?be($e=>$e&&{...$e,active:[...$e.active,J.label],rows:rt($e.rows,J.label,"active"),lastAt:Date.now()}):be($e=>$e&&{...$e,active:$e.active.filter(Le=>Le!==J.label),done:$e.done+1,rows:rt($e.rows,J.label,J.status==="done"?"done":"failed"),lastAt:Date.now()});else if(J.type==="partition_stalled"){let $e=es(J);be(Le=>Le&&$e?{...Le,stalledNote:$e}:Le)}else if(J.type==="partition_event"){let $e=null;if(J.event.type==="tool"){let Le=df(J.event.name,J.event.input,I[J.index]?.paths??[]);Le&&!ye.has(Le)&&(ye.add(Le),$e=J.label)}be(Le=>{if(!Le)return Le;let zt={...Le,lastAt:Date.now()};return J.event.type==="tool"?zt.tools=Le.tools+1:J.event.type==="text"&&(zt.chars=Le.chars+J.event.delta.length),$e&&(zt.rows=mc(zt.rows,$e)),zt})}else if(J.type==="run_done"){Co(lt=>lt+J.totalCostUsd),So(lt=>lt+J.results.reduce((It,jo)=>It+jo.outputTokens,0));let $e=J.aborted?"Stopped. ":"",Le=t.kind==="api"?"api":"subscription",zt=Xn(J,"The write");if(h({kind:"note",tone:zt||J.aborted?"warn":J.ok?"ok":"warn",text:zt?zt.join(`
551
+ `):$e+Xd(J.results,I,Le,k??v).join(`
552
+ `)}),fr(pe,J.results,J.totalCostUsd,!zt&&!J.aborted&&J.ok),zt){se("/doctor");continue}let lm=My(J);if(lm&&h({kind:"note",tone:"warn",text:lm}),!J.aborted&&J.ok)try{let lt=(ye.size>0?[...ye]:F).map(It=>`${M}/${It}`);ss(e,lt,{writtenCap:GL,reviewedCap:0,checkedCap:0})}catch{}let Do=J.aborted?[]:Fr(e,M,F),cm=Qd(Do);cm&&h({kind:"note",tone:"warn",text:cm});let yr=J.aborted||y.includes("--skip-style")?null:Jd(Do);if(yr){let lt=yr.errors.length,It=await Qi({partitions:yr.partitions,promptFor:yr.promptFor,concurrency:_r,verb:"Fixing",doneNoun:"fixed",headline:`${lt} style error${lt===1?"":"s"} in ${yr.articles} of the new article${yr.articles===1?"":"s"} \u2014 fixing now, one pass`});if(It.covered.length>0)try{ss(e,It.covered,mt("lint"))}catch{}Do=Fr(e,M,F);let jo=Zd(lt,Do);h({kind:"note",tone:jo[0].startsWith("\u2713")?"ok":"warn",text:jo.join(`
553
+ `)})}if(!J.aborted&&J.ok){let lt=k??v??"",It=lt?` ${lt}`:"",jo=Do.some(wr=>wr.severity==="error");{let wr=gf(I,J.results);Sn(`/write${k?` --scope ${k}`:""}${y.includes("--rewrite")?" --rewrite":""}`,{aborted:J.aborted,partitions:I.length,failed:wr.failed.length,notRun:wr.notRun.length,leftBehind:Do.filter(r0=>r0.severity==="error").length,...J.blocked?{blocked:J.blocked}:{},...J.allEmpty?{allEmpty:!0}:{},...J.bailedEmpty?{bailedEmpty:!0}:{}})}let um=lt?"/push":"/push --all",o0=lt?`/screenshot author ${lt}`:"/screenshot author --all";Pe(jo?`Written, but ${Do.filter(wr=>wr.severity==="error").length} style error(s) are still unfixed. /lint${It} --blocked --fix retries them, then /review${It} --fix for editorial quality, then ${um}.`:`Written. I\u2019d run /review${It} --fix next \u2014 editorial review that applies its fixes \u2014 then ${um} saves them to Document360 as drafts (add ${o0} first if you want images).`,{kind:"cmd",cmd:jo?`/lint${It} --blocked --fix`:`/review${It} --fix`,reason:""})}}}catch(J){h({kind:"note",tone:"error",text:`Write run failed: ${J.message}`})}finally{Fe.current=null,be(null),C(!1),W(J=>J+1)}return}case"draft":{if(!ke(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:w,looseDocs:k}=tp(e);if(w.length===0&&k===0){h({kind:"note",tone:"info",text:op});return}let v=y.join(" ").trim();if(!v&&w.length>1){h({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
553
554
  ${w.map(N=>` \u2022 ${N.name} (${N.docCount} doc${N.docCount===1?"":"s"})`).join(`
554
- `)}`}),we(w.map(N=>`/draft ${N.name}`));return}let b="",R;if(v){let N=Qd(w,v);N?b=N:R=v}else b=w[0]?.name??"";await ve(dl(b,R),{display:v?`/draft ${v}`:"/draft",quietUser:!0});return}case"pull":{if(!Po(p.trim()))return;let w=y.find($=>$.startsWith("--"));try{if(w==="--status"){h({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let b=Date.now(),R=await yc({cwd:e,profileName:s});h({kind:"note",tone:"info",text:za(R,Date.now()-b).join(`
555
- `)});return}if(w==="--baseline"){let b=y.find(M=>!M.startsWith("--")),R=b?b.replace(/\\/g,"/"):void 0;h({kind:"note",tone:"info",text:R?`Setting the sync baseline for ${R}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let N=await pL({cwd:e,profileName:s,relPaths:R?[R]:void 0}),_=R?{rebaselined:[],skipped:[]}:await hL({cwd:e,profileName:s});if(N.baselined.length===0&&N.skipped.length===0&&_.rebaselined.length===0){h({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}N.baselined.length>0&&h({kind:"note",tone:"ok",text:`\u2713 Recorded ${N.baselined.length} article${N.baselined.length===1?"":"s"} as matching Document360 \u2014 they read in-sync until either side changes.`}),_.rebaselined.length>0&&h({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${_.rebaselined.length} article${_.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),N.skipped.length>0&&h({kind:"note",tone:"warn",text:`${N.skipped.length} skipped:
556
- ${N.skipped.map(M=>` - ${M.path} (${M.reason})`).join(`
557
- `)}`}),W(M=>M+1);return}if(w==="--compare"){h({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let b=await aL({cwd:e,profileName:s}),R=b.onlyInLegacy.length===0&&b.onlyInManifest.length===0&&b.mappedMissingFromManifest.length===0,N=[`Legacy listing: ${b.legacyCount} \xB7 Manifest: ${b.manifestCount} \xB7 in both: ${b.inBoth}`];R?N.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(b.mappedMissingFromManifest.length&&N.push(`\u2717 ${b.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${b.mappedMissingFromManifest.slice(0,5).join(", ")}`),b.onlyInLegacy.length&&N.push(`\u26A0 ${b.onlyInLegacy.length} only in the legacy listing: ${b.onlyInLegacy.slice(0,5).join(", ")}`),b.onlyInManifest.length&&N.push(`\u26A0 ${b.onlyInManifest.length} only in the manifest: ${b.onlyInManifest.slice(0,5).join(", ")}`),N.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),h({kind:"note",tone:R?"ok":"warn",text:N.join(`
558
- `)});return}if(w){h({kind:"note",tone:"error",text:`Unknown option: ${w} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let $=y[0];if($){let b=$.replace(/\\/g,"/"),R;try{let N=await pv({cwd:e,profileName:s,relPath:b});R={plan:N,mode:N.overwritesLocalChanges?"conflict":"pull"}}catch(N){if(!hv(N))throw N;R={mode:"local-only",path:b,title:fv(e,b)}}De.current=[R],Bt.current=[],mn.current=[],gr();return}h({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let v=await md({cwd:e,profileName:s});for(let b of gd(v))h({kind:"note",tone:b.tone,text:b.text});W(b=>b+1)}catch($){h({kind:"note",tone:"error",text:`Pull failed: ${$.message}`})}return}case"scope":{if(!ke(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let w=fL(e);if(w.length===0){h({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.'});return}cr({cursor:0,rows:w.map($=>({...$,checked:$.recommended}))});return}case"audit":{if(y[0]==="--auto"){let $=ke(e);if(!$){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let v=y[1]!=="off";av({...$,autoAudit:v},e),h({kind:"note",tone:"ok",text:v?"\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(!Po(p.trim()))return;let w=await qs({cwd:e,profileName:s});if(w.kind==="audit-blocked"){Pe(w.note,{kind:"cmd",cmd:w.lead.cmd,reason:w.lead.reason},"warn");return}if(w.kind==="forward-to-agent"&&w.prompt){let $=await ve(w.prompt,{display:w.display,quietUser:!0}),v=Va(e,s);if(v){Pe(v.note,{kind:"cmd",cmd:jr.cmd,reason:jr.reason},"warn"),W(b=>b+1);return}$.producedNothing||(bi(e,s),W(b=>b+1))}return}case"lint":case"check":{let w=Gs(u);w&&h({kind:"note",tone:"info",text:`\u2192 ${w}`});let $=y.find(N=>!N.startsWith("--")),v=$?` ${$}`:"",b=ss({cwd:e,scope:$}),R=An(b,y);if(y.includes("--fix")){let N=Jn(e,y,b);N.lines.length>0&&h({kind:"note",tone:"ok",text:N.lines.join(`
559
- `)});let _=N.fixed>0?ss({cwd:e,scope:$}):b,M=Ld(e,y,_);if(!M){let J=Od(e,y,_);h({kind:"note",tone:"ok",text:J.lines.join(`
560
- `)});for(let $e of J.closed)h({kind:"note",tone:"ok",text:$e});return}let D={aborted:!1,partitions:0,failed:0,notRun:0};if(M.kind==="partitioned"){let J=await Vi({partitions:M.partitions,promptFor:M.promptFor,concurrency:Mr,verb:"Fixing",doneNoun:"fixed",headline:`Fixing ${M.findings} issue${M.findings===1?"":"s"} across ${M.articles} article${M.articles===1?"":"s"} in ${M.partitions.length} batches (\u2264${Mr} at once)`,calibrateAs:"/lint"});if(D=J.outcome,J.covered.length>0)try{is(e,J.covered,ft("lint"))}catch{}if(J.aborted){let $e=Hs({cwd:e,after:An(ss({cwd:e,scope:$}).filter(Le=>!Le.baselined),y),scope:$,aborted:!0,blocked:Tn(y)});Pe($e.text,{kind:"cmd",cmd:$e.cmd,reason:""},"warn");return}}else{h({kind:"note",tone:"info",text:`Fixing ${M.findings} doc issue${M.findings===1?"":"s"}\u2026`});let J=SL(e,$);await ve(M.prompt,{display:M.display,quietUser:!0});try{is(e,J,ft("lint"))}catch{}}let Q=An(ss({cwd:e,scope:$}).filter(J=>!J.baselined),y),j=An(_.filter(J=>!J.baselined),y),U=new Set(Q.map(J=>J.fp)),H=new Set(j.map(J=>J.fp)),te=j.filter(J=>!U.has(J.fp)).length,ue=Q.filter(J=>!H.has(J.fp)).length,pe=ue>0?`
561
- \u26A0 ${ue} new ${ue===1?"issue":"issues"} appeared in the rewrites \u2014 recasting a sentence is where these come from.`:"";h({kind:"note",tone:Q.some(J=>J.severity==="error")?"warn":"ok",text:Q.length===0?`\u2713 Lint: all ${j.length} issue${j.length===1?"":"s"} resolved.`:[`\u2713 Lint: fixed ${te} of ${j.length}.${pe}`,"",...Js(Q)].join(`
562
- `)}),xn(Qs(y,$),M.kind==="partitioned"?D:{aborted:!1,partitions:0,failed:0,notRun:0,verifiedComplete:Q.length===0});let ye=Hs({cwd:e,after:Q,before:M.findings,scope:$,blocked:Tn(y)});Pe(ye.text,{kind:"cmd",cmd:ye.cmd,reason:""});return}if(h({kind:"note",tone:R.length===0?"ok":"warn",text:Js(R,{full:y.includes("--full"),baselined:y.includes("--baselined")}).join(`
563
- `)}),R.length>0){let N=Fa(e,$)===0&&Ua(e,$)===0?"; /push --all saves them to Document360 as-is":"",_=`/lint${v}${Tn(y)?" --blocked":""} --fix`,M=Zt(e,_);Pe(`Found ${R.length} doc issue${R.length===1?"":"s"} above. ${_} has the agent fix them in place${M?` (${M})`:""} \u2014 or /review${v} --fix for the full editorial pass${N}.`,{kind:"cmd",cmd:_,reason:""})}return}case"structure":{let w=Yr(e,s);if(w.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):","",...w].join(`
564
- `)});return}case"status":{let w=y.some($=>$==="--all"||$==="--full");h({kind:"block",text:Rh(e,{profileName:s,all:w,width:et()}).join(`
565
- `)}),Z.current=!0;return}case"retire":{let w=y.find(v=>!v.startsWith("-"));if(!w){h({kind:"block",text:Sh(e,s).join(`
566
- `)}),Z.current=!0;return}let $=Sv(e,w)||w;if(!y.includes("--yes")&&!y.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(`
567
- `)}),st(`/retire ${$} --yes`,"tab to take it off your readers \xB7 or keep typing");return}C(!0);try{let v=await ML({cwd:e,path:$,profileName:s,now:new Date().toISOString()});h(v.ok?{kind:"note",tone:"ok",text:v.alreadyHidden?`\u2713 "${$}" was already invisible to readers. Recorded as retired, so nothing will offer to publish it again.
568
- It stays on Document360 with its history and comments intact. /push puts it back.`:`\u2713 "${$}" is no longer visible to your readers.
569
- It stays on Document360 with its history and comments intact. /push puts it back.`}:{kind:"note",tone:"error",text:`\u2717 Could not retire "${$}" \u2014 ${v.error.message}`})}finally{C(!1)}return}case"untrack":{let w=y.find(b=>!b.startsWith("-"));if(y.includes("--list")||!w&&!y.includes("--undo")){h({kind:"block",text:Ch(e,s).join(`
570
- `)}),Z.current=!0;return}if(!w){h({kind:"note",tone:"warn",text:"\u2717 Name what to put back: /untrack --undo <path>"});return}let $=Sv(e,w)||w;if(y.includes("--undo")){let b=UL(e,s,$);h(b.ok?{kind:"note",tone:"ok",text:b.restoredTo?`\u2713 Put "${b.restoredTo}" back in your docs folder.`:"\u2713 No longer declined. /catch-up imports it again on the next run."}:{kind:"note",tone:"error",text:`\u2717 ${b.error.message}`});return}if(!y.includes("--yes")&&!y.includes("-y")){h({kind:"note",tone:"warn",text:[`\u26A0 This stops tracking "${$}" as one of your docs.`," Nothing on Document360 changes \u2014 the page, its history and its comments all stay,"," and your readers see no difference."," The markdown moves to .d360-writer/declined/, so nothing is deleted."," /untrack --undo puts it back if you change your mind."].join(`
571
- `)}),st(`/untrack ${$} --yes`,"tab to stop tracking it \xB7 or keep typing");return}let v=FL({cwd:e,path:$,profileName:s,now:new Date().toISOString()});h(v.ok?{kind:"note",tone:"ok",text:[`\u2713 "${v.title??v.path}" is no longer one of your docs.`,...v.keptAt?[` The markdown is kept at ${v.keptAt} \u2014 nothing was deleted.`]:[]," It is untouched on Document360. /catch-up will not import it again."].join(`
572
- `)}:{kind:"note",tone:"error",text:`\u2717 Could not untrack "${$}" \u2014 ${v.error.message}`});return}case"eval":{h({kind:"block",text:Eh(e,{...y.find(w=>!w.startsWith("--"))?{scope:y.find(w=>!w.startsWith("--"))}:{},...s?{profile:s}:{},all:y.includes("--all")}).join(`
573
- `)}),Z.current=!0;return}case"terms":{let w=y.findIndex($=>$==="--approve");if(w!==-1){let $=y[w+1];h($?{kind:"block",text:Ah(e,$.replace(/^["']|["']$/g,"")).lines.join(`
574
- `)}:{kind:"note",tone:"warn",text:'\u2717 Name the spelling to approve, e.g. /terms --approve "drop-down".'}),Z.current=!0;return}h({kind:"block",text:Th(e,{...y.find($=>!$.startsWith("--"))?{scope:y.find($=>!$.startsWith("--"))}:{},all:y.includes("--all")}).join(`
575
- `)}),Z.current=!0;return}case"reuse":{let w=y.find($=>!$.startsWith("--"));if(w==="pull"){(async()=>{let $=await wi(e);h({kind:"block",text:$.lines.join(`
576
- `)});for(let v of Ke(e,"/reuse pull"))h({kind:"note",tone:"ok",text:v});$.restart&&Ve()})(),Z.current=!0;return}if(w==="audit"){if(y.includes("--create")){let v=WL(e);if(!v||v.proposals.length===0){h({kind:"block",text:Fl().join(`
577
- `)}),Z.current=!0;return}let{picks:b,bad:R}=Ml(y,v.proposals.length);for(let N of R)h({kind:"note",tone:"warn",text:`\u26A0 There is no proposal ${N} \u2014 the list has ${v.proposals.length}.`});if(b.length===0){h({kind:"note",tone:"info",text:"\u25CB Nothing picked, so nothing was created."}),Z.current=!0;return}(async()=>{let{outcome:N,pullLines:_}=await Mh(e,b.map(M=>v.proposals[M]));_.length>0&&h({kind:"block",text:_.join(`
578
- `)}),h({kind:"block",text:_l(e,N).lines.join(`
579
- `)});for(let M of Ke(e,"/reuse audit"))h({kind:"note",tone:"ok",text:M});N.created.length>0&&Ve()})(),Z.current=!0;return}let $=Ol(e,y);if("lines"in $){h({kind:"block",text:$.lines.join(`
580
- `)});for(let v of Ke(e,"/reuse audit"))h({kind:"note",tone:"ok",text:v});Z.current=!0;return}h({kind:"block",text:Ll($.articles,$.families,$.values,0).join(`
581
- `)}),(async()=>(await ve($.prompt,{display:$.display,quietUser:!0}),h({kind:"block",text:Ul(e,$.display.split(/\s+/)[2]).join(`
582
- `)})))(),Z.current=!0;return}if(w==="add"){let $=_h(y);if("error"in $){h({kind:"note",tone:"warn",text:`\u2717 ${$.error}`}),Z.current=!0;return}(async()=>{let v=await Oh(e,$.kind,$.name,$.value,$.description);h({kind:"block",text:v.lines.join(`
583
- `)}),v.restart&&Ve()})(),Z.current=!0;return}if(w&&w!=="show"){h({kind:"note",tone:"warn",text:`\u2717 I don't know "/reuse ${w}". Use /reuse to see what this project maintains, /reuse pull to refresh it, or /reuse add variable <name> "<value>".`}),Z.current=!0;return}h({kind:"block",text:Lh(e).join(`
584
- `)}),Z.current=!0;return}case"reorder":{let w=vh(e,y);if(!w){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let $=await ve(w.prompt,{display:w.display,quietUser:!0}),v=It(e,{text:"Reordered locally \u2014 /push --all syncs the new order to Document360.",cmd:"/push --all"},"Reordered locally. ");kn($,v.text,{kind:"cmd",cmd:v.cmd,reason:""});return}case"restructure":{let w=xh(e,y);if(!w){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let $=await ve(w.prompt,{display:w.display,quietUser:!0});if(y.filter(b=>!b.startsWith("--")).length===0){kn($,null,null);return}let v=It(e,{text:"Restructured locally \u2014 /push --all moves it on Document360.",cmd:"/push --all"},"Restructured locally. ");kn($,v.text,{kind:"cmd",cmd:v.cmd,reason:""});return}case"review":{let w=kh(e,y);if(w){h({kind:"note",tone:"ok",text:w.lines[0]});for(let U of w.closed)h({kind:"note",tone:"ok",text:U});let j=yi(e,y,null);j&&(h({kind:"note",tone:"info",text:"One thing left: no editor has looked at how your docs are organised since it last changed. Checking that now \u2014 it reads the shape, not the articles, so it is one quick pass."}),(await ve(j.prompt,{display:j.display,quietUser:!0})).producedNothing||Rv(e,j.fingerprint)),Pe(w.cta.text,{kind:"cmd",cmd:w.cta.cmd,reason:""});return}let $=bh(e,y);if(!$){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let v=y.includes("--fix"),b=y.find(j=>!j.startsWith("--")),R=v?Ko(e,y,b):[],N=v?df(e):null,_={aborted:!1,partitions:0,failed:0,notRun:0},M,D=null,Q=yi(e,y,$);if($.kind==="partitioned"){let j=await Gv($,v,N,!!Q);_=j.outcome,M=j,D=j.evidence}else M=await ve($.prompt,{display:$.display,quietUser:!0}),_={..._,producedNothing:M.producedNothing};if("aborted"in M&&M.aborted){let j=y.includes("--blocked")?"--blocked --fix":y.includes("--stale")?"--stale --fix":"--fix",U=Se("/review",j,b);Pe(`Stopped \u2014 the batches that finished are saved. ${U} picks up the rest${b||zr(y)?"":", or narrow it with /review <category> --fix"}.`,{kind:"cmd",cmd:U,reason:""},"warn");return}if(Q&&((await ve(Q.prompt,{display:Q.display,quietUser:!0})).producedNothing||Rv(e,Q.fingerprint)),$.kind!=="partitioned"&&v&&!M.producedNothing&&(D=Vo(e,R,N,s),D.earned.length>0))try{is(e,D.earned,ft("review"))}catch{}if(v&&xn(`/review${b?` ${b}`:""}${y.includes("--all")?" --all":""}${y.includes("--blocked")?" --blocked":y.includes("--stale")?" --stale":""} --fix`,_),v){if(v&&!M.producedNothing){let pe=Jn(e,["--fix"],ss({cwd:e,scope:b}));pe.lines.length>0&&h({kind:"note",tone:"ok",text:pe.lines.join(`
585
- `)})}let j=v&&!M.producedNothing?ss({cwd:e,scope:b}).filter(pe=>!pe.baselined&&pe.severity==="error"):[],U=D?D.changed.length:-1,H=U<0?"Editor applied its fixes":gi(U),te=Kr(e,D?.unadopted??[],{lead:U===0&&j.length===0});if(te&&h({kind:"note",tone:"warn",text:te.lines.join(`
586
- `)}),j.length>0){let pe=new Set(j.map(Le=>Le.path)).size,ye=`/lint${b?` ${b}`:""} --blocked --fix`,J=Zt(e,ye),$e=!D||D.changed.length>0;h({kind:"note",tone:"warn",text:$e?`\u26A0 The editor's rewrites left ${j.length} style error${j.length===1?"":"s"} in ${pe} article${pe===1?"":"s"} \u2014 recasting a sentence is where these appear.`:`\u26A0 ${j.length} style error${j.length===1?"":"s"} in ${pe} article${pe===1?"":"s"} still block${j.length===1?"s":""} publishing \u2014 the editor changed nothing, so these were already there.`}),kn(M,`${D?gi(D.changed.length):"Editor applied its fixes"}, but ${j.length} style error${j.length===1?"":"s"} remain. ${ye} clears ${j.length===1?"it":"just those"} \u2014 it costs nothing to find them and one pass to correct${J?` (${J})`:""}. 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:ye,reason:""});return}if(te?.cta){kn(M,te.cta.text,{kind:"cmd",cmd:te.cta.cmd,reason:""});return}let ue=It(e,{text:`\u2713 ${H} \u2014 your docs are ready. /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 ${H} in this scope. `,b);kn(M,ue.text,{kind:"cmd",cmd:ue.cmd,reason:""})}else{let j=b?` ${b}`:"",U=Fa(e,b)===0&&Ua(e,b)===0?`; /push${b?"":" --all"} saves them to Document360 as-is`:"";kn(M,`The review listed issues above. /review${j} --fix lets the editor apply them all (or /lint${j} --fix for just the deterministic ones${U}).`,{kind:"cmd",cmd:`/review${j} --fix`,reason:""})}return}case"capture-setup":{await G();return}case"devhints":{if(!ke(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}h({kind:"note",tone:"info",text:Rr(xr(e)).join(`
587
- `)}),$n(jo()),$s.current=zt(e).status==="current",hr.current=Sn(e);return}case"discover":{if(!ke(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await ve(cd(),{display:"/discover",quietUser:!0});return}case"ask":{if(!ke(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let w=y.join(" ").trim();if(w===""){h({kind:"block",text:Cp(OL(e)).join(`
588
- `)});return}try{let $=LL(e,{question:w});h({kind:"note",tone:"ok",text:Sp($.file,ci(e)).join(`
589
- `)})}catch($){h({kind:"note",tone:"warn",text:`Could not file the question: ${$.message}`})}return}case"inbox":{if(!ke(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(xp(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 ve(Rp(),{display:"/inbox",quietUser:!0});return}case"auto":{let w=ke(e);if(!w){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let $=ad(y);if($.malformed){h({kind:"note",tone:"error",text:`I could not read that spending limit. Give it as an amount, like: /auto --budget 150 (the standard limit is ${Ye(oL)}).`});return}let v=ld(y,$.usd),b=R=>{for(let N of R)h({kind:"note",tone:N.tone,text:N.text});W(N=>N+1)};if($.usd!==void 0&&!v){let R=id(e,w,$.usd);R&&b(R);return}if(!v||v==="status"){for(let R of Ks(w))h({kind:"note",tone:R.tone,text:R.text});return}if(v==="on"||v==="off"){v==="on"&&(ko.current=!1);let R=$.usd!==void 0?{...w,auto:{...w.auto,enabled:w.auto?.enabled===!0,budgetUsd:$.usd}}:w;b(Ka(e,R,v==="on"));return}h({kind:"note",tone:"error",text:`I don't know "${v}". Use: /auto on \xB7 /auto off \xB7 /auto status \xB7 /auto --budget <amount>`});return}case"share":{let w=ke(e);if(!w){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let $=y[0]?.trim().toLowerCase();if($==="status"){for(let b of wl(e,w))h({kind:"note",tone:b.tone,text:b.text});return}if($==="on"||$==="off"){for(let b of Pp(e,w,$==="on"))h({kind:"note",tone:b.tone,text:b.text});W(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 v=await bl(e,w);for(let b of v.lines)h({kind:"note",tone:b.tone,text:b.text});v.changed&&W(b=>b+1);return}case"feedback":{let w=kv(e),$="";try{$=rs(w)?fc(w,"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 v=await Xh($.trim());h({kind:"note",tone:v?"ok":"warn",text:v?"\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 ${w} and copy it manually.`}),v&&Lc(null);return}case"document":{if(!ke(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{push:w,skipReview:$,what:v}=ep(y);if(!v&&Zd(e)===0){h({kind:"note",tone:"info",text:np});return}let b=`/document${v?` ${v}`:""}${w?" --push":""}`,R=await ve(tp(v),{display:b,quietUser:!0});w&&!R.producedNothing&&await Vf({skipReview:$});return}case"catch-up":{if(!ke(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!Po(p.trim()))return;let{push:w,skipReview:$,includeUnfinished:v}=Dp(y);for(let H of await Ep(e))h({kind:"note",tone:H.tone,text:H.text});h({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let b=await Mp({cwd:e,profileName:s});for(let H of Fp(b))h({kind:"note",tone:H.startsWith("\u2713")?"ok":H.startsWith("\u2139")?"info":"warn",text:H});let R=di(e);for(let H of jp(R))h({kind:"note",tone:H.tone,text:H.text});let N=Ip(e),_=v?[]:N,M=Lp(e,_);for(let H of Op(_,M))h({kind:"note",tone:H.tone,text:H.text});let D=Jt(e);h({kind:"note",tone:"info",text:Np(D)});let Q=df(e),j=await ve(_p(R,{held:N.length,includeUnfinished:v},D.briefMoved),{display:`/catch-up${w?" --push":""}${v?` ${$l}`:""}`,quietUser:!0});j.producedNothing||_L(e);let U=Go(e,Q,"","/catch-up");if(w&&!j.producedNothing)await Vf({skipReview:$});else if(U.cta)kn(j,U.cta.text,{kind:"cmd",cmd:U.cta.cmd,reason:""});else{let H=kl({queued:D,hold:R.hold});kn(j,H.note,H.lead?{kind:"cmd",cmd:H.lead.cmd,reason:H.lead.reason}:null,H.tone)}return}case"comments":{if(!ke(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!Po(p.trim()))return;let w=Gp(y);qe("Checking Document360 for reviewer comments\u2026"),C(!0);let $=null;try{$=await vl(e,s,{...w.scope,onProgress:(b,R)=>qe(`Checking Document360 for reviewer comments\u2026 ${b}/${R}`)})}catch(b){h({kind:"note",tone:"error",text:`Couldn\u2019t read comments from Document360: ${b.message}`})}finally{C(!1),qe(null)}if(!$)return;W(b=>b+1);let v=qo($.threads,$.labels);if($.threads.length===0){h({kind:"note",tone:"ok",text:hi($,{showAnswered:w.showAnswered,width:et()}).join(`
590
- `)});return}if(w.answer&&(w.all||w.scope.path||w.scope.scope||v.length===1)){fr(Bp($,{full:!0,showAnswered:w.showAnswered,width:et()})),await Wc(v,{resolve:w.resolve});return}if(v.length===1){fr(xl(v[0],{width:et()})),ps({group:v[0],cursor:0,fromList:!1,resolve:w.resolve,rest:[]});return}fr(hi($,{showAnswered:w.showAnswered,width:et()})),yn({cursor:0,rows:Rl(v),groups:v,resolve:w.resolve,report:$});return}case"update":{Dc.current=!0,h({kind:"note",tone:"info",text:"Updating the d360-writer toolchain\u2026 (don\u2019t close this window)"}),er(!0);let w=await Pl().finally(()=>er(!1));w.ok?(h({kind:"note",tone:"ok",text:`\u2713 Updated ${w.packages.join(" + ")} \u2014 run /exit, then relaunch to apply.`}),se("/exit"),us("")):(h({kind:"note",tone:"warn",text:`Update failed. ${Cl(w.output)}`}),w.output&&h({kind:"note",tone:"info",text:`${w.output}
591
-
592
- Full output: ${Sl()}`}));return}case"screenshot":{let w=Ls(y),$=Io(e);if($&&w.mode!=="list"&&h({kind:"note",tone:"info",text:$}),w.mode==="capture"){await P(w.rest);return}if(w.mode==="annotate"){await F(w.rest);return}if(w.mode==="checklist"){await G();return}if(w.mode==="verify"){let R=Ue(e),N=w.rest.find(D=>!D.startsWith("-")),_=N?[N]:ri(R);if(N&&!R.some(D=>D.id===N)){h({kind:"note",tone:"error",text:`No screenshot placeholder called "${N}". /screenshot list shows them all.`});return}if(_.length===0){let D=R.filter(j=>j.state==="rejected").length,Q=R.filter(j=>j.state==="verified").length;h({kind:"note",tone:"info",text:D>0?`Nothing left to verify. ${D} shot${D===1?"":"s"} failed verification \u2014 re-capture with /screenshot capture --failed.`:Q>0?`All ${Q} captured shot${Q===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:eo(_.length)}),await ve(un(e,_),{display:N?`/screenshot verify ${N}`:"/screenshot verify",quietUser:!0});let M=Wr(e,_);M.length>0&&h({kind:"note",tone:"info",text:M.join(`
593
- `)});return}if(w.mode==="list"){if(!ke(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let R=ke(e)?.docsDir??yf,N=_u(e,w.scope),_=Ue(e,N);if(w.picker){if(_.length===0){h({kind:"note",tone:"info",text:"No screenshot placeholders found in the docs."});return}let D=Mg(_);if(D.length===0){h({kind:"note",tone:"info",text:Na(_,{docsDir:R}).join(`
594
- `)});let Q=Se("/push","--screenshots",N),j=It(e,{text:`\u2713 All ${_.length} screenshots are captured. ${Q} saves them into the articles on Document360; /screenshot capture${N?` ${N}`:""} re-captures.`,cmd:Q},`\u2713 All ${_.length} screenshots are captured. `,N);Pe(j.text,{kind:"cmd",cmd:j.cmd,reason:""});return}mo({cursor:0,rows:D,title:"Screenshots \u2014 pick what to author or capture:"});return}h({kind:"note",tone:"info",text:Na(_,{scope:N,detail:w.detail,docsDir:R}).join(`
595
- `)}),$&&h({kind:"note",tone:"info",text:$});let M=Ou(_,N);M.key!=="done"&&se(M.cmd);return}if(w.mode==="single"){await Yf(w.id);return}if(!ke(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let v=w.mode==="scope"?w.scope:void 0,b=wL(e,{scope:v}).map(R=>R.id);if(b.length===0){h({kind:"note",tone:"info",text:v?`No screenshot placeholders under ${v}.`:"No screenshot placeholders found in the docs."});return}await Kf(b,{setup:w.setup,scope:w.mode==="scope"?w.scope:void 0,runLine:w.mode==="scope"?[`/screenshot author ${w.scope}`,`/screenshot ${w.scope}`]:["/screenshot author --all","/screenshot --all"]});return}case"capture":{await P(y);return}case"reset":{let w=Kp(e);if(w.length===0){h({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}or.current={repoName:Ci(e),targets:w,hadDevhints:rs(bv(e))},h({kind:"note",tone:"warn",text:zp(e,w).join(`
596
- `)}),st(Ci(e));return}default:h({kind:"note",tone:"error",text:`Unknown command: /${u} \u2014 type /help.`})}},[e,r,s,gr,Vc,h,Ve,ve,yt,Bc,zf]),Ss=re(p=>{let m=(p??g).trim();if(k(""),uo(null),On(0),m.startsWith("/")){Z.current=!1,Ee.current=!1,_e.current=null,Kt(),yo(null);let y=Mi.current.includes(m);y&&(Mi.current=[]),we(P=>y?[]:B$(P,m))}if(!m||(Ce(!1),Ae.current=!1,(or.current||De.current.length>0)&&h({kind:"user",text:m}),Qf(m))||Xf(m))return;vc.current.push(m);let u=V$(m,He.current);if(m.startsWith("/"))h({kind:"user",text:m}),B(!0),Eo(u).finally(()=>B(!1));else if(BL(u)){h({kind:"user",text:m});let y=HL(u);if(!y)ve(u,{display:m,quietUser:!0});else{try{GL(e,{title:y,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}ve(`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${y}". 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 "${y}" and the article path(s) you wrote.`,{display:m,quietUser:!0})}}else{let y=Xg(e,u);ve(y??u,{display:m})}},[g,Qf,Xf,Eo,ve]),Jf=re(p=>{if(p.length>1){if(p.includes("\x1B"))return;let m=H$(p);if(G$(m)){let u=q$(++hn.current,m);He.current.set(u,m),T(u)}else T(m);return}T(p)},[T]),yr=Math.max(10,ht-6),Zf=hc(()=>dc(l.text,yr),[l.text,yr]),Kc=re(p=>f(m=>({...m,pos:Math.max(0,Math.min(m.text.length,m.pos+p))})),[]),Qi=re(p=>f(m=>({...m,pos:Y$(dc(m.text,yr),m.pos,p)})),[yr]),Cs=re(p=>f(m=>({...m,pos:z$(dc(m.text,yr),m.pos,p)})),[yr]),qv=["\x1B[H","\x1B[1~","\x1BOH"],Vv=["\x1B[F","\x1B[4~","\x1BOF"],em=re((p,m)=>m.leftArrow?(Kc(-1),!0):m.rightArrow?(Kc(1),!0):p&&qv.includes(p)?(Cs("start"),!0):p&&Vv.includes(p)?(Cs("end"),!0):m.ctrl&&p==="a"?(Cs("start"),!0):m.ctrl&&p==="e"?(Cs("end"),!0):!1,[Kc,Cs]),Yc=re(()=>{if(Fe.current){if(!Fe.current.signal.aborted){let p=(dr?.verb??"work").toLowerCase(),m=dr?.unit??"article";h({kind:"note",tone:"warn",text:`\u238B Stopping the ${p} run (finishing in-flight ${m}s)\u2026`}),Fe.current.abort()}return!0}return hs.current?!1:(hs.current=!0,h({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),Wt.current?.interrupt(),!0)},[dr]);return DI((p,m)=>{if(m.ctrl&&p==="c"){if(fs.current!==null&&Date.now()-fs.current<Tv){fs.current=null,Wt.current?.close(),r();return}fs.current=Date.now(),Tf(!0),Sc.current&&clearTimeout(Sc.current),Sc.current=setTimeout(()=>{fs.current=null,Tf(!1)},Tv),S?Yc():g&&k("");return}if(ks.current.awaySince!==null&&Xe.current===null)try{let u=I$(ks.current,Date.now(),Jt(e));if(ks.current=u.memory,Wf(null),u.kind==="delta"){h({kind:"note",tone:"info",text:O$(u.delta,u.awayMs)});let y=gt(!1);y.kind==="recommend"&&bn(y.rec,{silent:!0})}else if(u.kind==="briefing"){h({kind:"note",tone:"info",text:`\u{1F4E5} ${Ri(u.delta)} arrived while you were away (${of(u.awayMs)}).`});let y=gt(!1);y.kind==="recommend"&&bn(y.rec)}}catch{}if(Oc.current=Date.now(),!x){if(dt){if(m.return){Ni(null),Di.current=!0,W(u=>u+1),h({kind:"note",tone:"info",text:"\u25B6 Auto mode starting \u2014 esc stops it at any point, and nothing already done is undone."});return}if(p==="b"||p==="B"){Ni(null),k("/auto --budget ");return}if(m.escape){Ni(null),ko.current=!0,Xe.current=null,h({kind:"note",tone:"info",text:"Left in manual for now \u2014 nothing started. Auto mode is still on: /auto on begins the round trip when you are ready, or /auto off switches it off."}),W(u=>u+1);return}return}if(m.tab&&m.shift&&!Mn&&!gn&&!Mc){let u=ke(e);if(!u){h({kind:"note",tone:"info",text:"Set this repo up first with /init \u2014 then shift+tab switches between auto and manual."});return}let y=!lv(u);Ka(e,u,y),y&&(ko.current=!1);let P=!y&&Xe.current!==null;P&&(Xe.current={...Xe.current,stopping:!0}),h({kind:"note",tone:"ok",text:P?"Manual mode \u2014 I'll finish what is running and stop there, then hand back. (shift+tab to change it back.)":`${y?"Auto mode ON":"Manual mode"} \u2014 ${Vs(y)} (shift+tab to change it back.)`}),W(F=>F+1);return}if(S){if(m.escape){if(Xe.current){ko.current=!0;let u=Xe.current;Yc(),xs({kind:"stopped",how:"esc"},u.parked);return}Yc();return}if(m.return){let u=g.trim();if(!u)return;bo.current.push(u),Rc([...bo.current]),k("");return}if(em(p,m))return;if(m.upArrow){Qi(-1);return}if(m.downArrow){Qi(1);return}if(m.backspace||m.delete){A();return}p&&!m.ctrl&&!m.meta&&Jf(p);return}if(gn){if(m.upArrow){ho(u=>u&&{...u,cursor:Math.max(0,u.cursor-1)});return}if(m.downArrow){ho(u=>u&&{...u,cursor:Math.min(_t.length-1,u.cursor+1)});return}if(p&&/^[0-9]$/.test(p)){let u=wn(p,_t.length);u!==null&&ho(y=>y&&{...y,cursor:u});return}if(m.return){let u=_t[gn.cursor];ho(null);let{lines:y,changed:P,effective:F}=ni(e,u.value??"default");for(let G of y)h({kind:"note",tone:G.startsWith("\u26A0")?"warn":G.startsWith("\u2713")?"ok":"info",text:G});P&&(jf(G=>G+1),Wt.current?.setModel(F));return}if(p==="s"){let u=_t[gn.cursor];ho(null),Wt.current?.setModel(u.value??void 0),h({kind:"note",tone:"ok",text:`\u2713 Using ${u.label} for this session only (your saved default is unchanged).`});return}if(m.escape){ho(null);return}return}if(Ht){if(m.upArrow){rr(u=>u&&{...u,cursor:Math.max(0,u.cursor-1)});return}if(m.downArrow){rr(u=>u&&{...u,cursor:Math.min(u.rows.length-1,u.cursor+1)});return}if(p&&/^[0-9]$/.test(p)){let u=wn(p,Ht.rows.length);u!==null&&rr(y=>y&&{...y,cursor:u});return}if(m.return||p==="s"){let u=Ht.rows[Ht.cursor];rr(null),Gc(u.name,m.return===!0);return}if(m.escape){rr(null);return}return}if(gs){if(m.escape){xo(null);return}if(m.leftArrow||m.tab&&m.shift){xo(u=>u&&{tab:(u.tab-1+wt.length)%wt.length,scroll:0});return}if(m.rightArrow||m.tab){xo(u=>u&&{tab:(u.tab+1)%wt.length,scroll:0});return}if(p&&/^[1-9]$/.test(p)&&Number(p)<=wt.length){xo({tab:Number(p)-1,scroll:0});return}if(m.upArrow){xo(u=>u&&{...u,scroll:Math.max(0,u.scroll-1)});return}if(m.downArrow){xo(u=>{if(!u)return u;let y=(wt[u.tab]??wt[0]).rows.length;return{...u,scroll:Math.min(Math.max(0,y-1),u.scroll+1)}});return}return}if(Gt){if(m.upArrow){sr(u=>u&&{...u,cursor:Math.max(0,u.cursor-1)});return}if(m.downArrow){sr(u=>u&&{...u,cursor:Math.min(u.rows.length-1,u.cursor+1)});return}if(p&&/^[0-9]$/.test(p)){let u=wn(p,Gt.rows.length);u!==null&&sr(y=>y&&{...y,cursor:u});return}if(m.return){let u=Gt.rows[Gt.cursor].name;if(sr(null),!du(e,u).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 "${u}").`});let P=!1;try{let F=lo(u);P=!!F&&!(Zo(F)&&!F.refreshToken)}catch{P=!1}h({kind:"note",tone:"info",text:P?`Next: sign in to ${u} and pick your project \u2014 you're already signed in here, so it'll be quick.`:`Next: sign in to Document360 (${u}) and pick your project.`}),se("/login"),W(F=>F+1);return}if(m.escape){sr(null);return}return}if(ot){if(m.upArrow){ir(u=>u&&{...u,cursor:Math.max(0,u.cursor-1)});return}if(m.downArrow){ir(u=>u&&{...u,cursor:Math.min(u.rows.length-1,u.cursor+1)});return}if(p&&/^[0-9]$/.test(p)){let u=wn(p,ot.rows.length);u!==null&&ir(y=>y&&{...y,cursor:u});return}if(m.return){let u=ot.rows[ot.cursor],{profile:y,projectId:P}=ot;ir(null),Yi(y,P,u);return}if(m.escape){ir(null);return}return}if(ct){if(m.upArrow){fo(u=>u&&{...u,cursor:Math.max(0,u.cursor-1)});return}if(m.downArrow){fo(u=>u&&{...u,cursor:Math.min(u.rows.length-1,u.cursor+1)});return}if(p&&/^[0-9]$/.test(p)){let u=wn(p,ct.rows.length);u!==null&&fo(y=>y&&{...y,cursor:u});return}if(m.return){let u=ct.rows[ct.cursor],{profile:y}=ct;fo(null),Xi(y,u);return}if(m.escape){fo(null);return}return}if(ut){if(m.upArrow){cr(u=>u&&{...u,cursor:Math.max(0,u.cursor-1)});return}if(m.downArrow){cr(u=>u&&{...u,cursor:Math.min(u.rows.length-1,u.cursor+1)});return}if(p===" "){cr(u=>u&&{...u,rows:u.rows.map((y,P)=>P===u.cursor?{...y,checked:!y.checked}:y)});return}if(m.return){let u=ut.rows.filter(y=>y.checked).map(y=>y.path);if(cr(null),u.length===0){h({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}ud(e,u),h({kind:"note",tone:"ok",text:`\u2713 Scoped to ${u.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let y of u)h({kind:"note",tone:"info",text:` ${y}`});h({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(m.escape){cr(null);return}return}if(mt){if(m.upArrow){go(u=>u&&{...u,cursor:Math.max(0,u.cursor-1)});return}if(m.downArrow){go(u=>u&&{...u,cursor:Math.min(u.rows.length-1,u.cursor+1)});return}if(p&&/^[0-9]$/.test(p)){let u=wn(p,mt.rows.length);u!==null&&go(y=>y&&{...y,cursor:u});return}if(m.return){let u=mt.rows[mt.cursor],y=mt.run;go(null),y(u.token);return}if(m.escape){go(null);return}return}if(Ct){if(m.upArrow){ar(u=>u&&{...u,cursor:Math.max(0,u.cursor-1)});return}if(m.downArrow){ar(u=>u&&{...u,cursor:Math.min(u.rows.length-1,u.cursor+1)});return}if(p&&/^[0-9]$/.test(p)){let u=wn(p,Ct.rows.length);u!==null&&ar(y=>y&&{...y,cursor:u});return}if(m.return){let u=Ct.rows[Ct.cursor],y=Ct.conflicts;ar(null),u.conflict?Vc(u.paths[0]):u.kind==="article"?Bc(u.paths[0]):yt(u.paths,u.kind==="all"?y:0);return}if(m.escape){ar(null);return}return}if(qt){if(m.upArrow){lr(u=>u&&{...u,cursor:Math.max(0,u.cursor-1)});return}if(m.downArrow){lr(u=>u&&{...u,cursor:Math.min(u.rows.length,u.cursor+1)});return}if(p&&/^[0-9]$/.test(p)){let u=wn(p,qt.rows.length+1);u!==null&&lr(y=>y&&{...y,cursor:u});return}if(m.return){let{cursor:u,rows:y,opts:P}=qt;lr(null);let F=u===0?y:[y[u-1]];qf(F,P);return}if(m.escape){lr(null),h({kind:"note",tone:"info",text:"Left as drafts \u2014 nothing changed. /publish when they have been signed off."});return}return}if(Pt){let{rows:u}=Pt;if(m.upArrow){yn(y=>y&&{...y,cursor:Math.max(0,y.cursor-1)});return}if(m.downArrow){yn(y=>y&&{...y,cursor:Math.min(u.length-1,y.cursor+1)});return}if(p&&/^[0-9]$/.test(p)){let y=Zh(Rf.current,Number(p),u.length-1);Rf.current=y.memory,y.index!==null&&yn(P=>P&&{...P,cursor:y.index+1});return}if(p==="a"||p==="A"){yn(y=>y&&{...y,cursor:0});return}if(m.return){let y=u[Pt.cursor],{groups:P,resolve:F,report:G}=Pt;if(yn(null),y.kind==="all"){Wc(P,{resolve:F,report:G});return}fr(xl(y.group,{width:et()})),ps({group:y.group,cursor:0,fromList:!0,resolve:F,rest:P.filter(w=>w.articleId!==y.group.articleId),report:G});return}if(m.escape){yn(null),se("/comments");return}return}if(at){let u=()=>{let{rest:y,group:P,fromList:F,resolve:G,report:w}=at;if(ps(null),!F||!w){se("/comments");return}let $=[P,...y].sort((v,b)=>v.category.localeCompare(b.category)||v.title.localeCompare(b.title));yn({cursor:0,rows:Rl($),groups:$,resolve:G,report:w})};if(m.upArrow||m.downArrow){ps(y=>y&&{...y,cursor:y.cursor===0?1:0});return}if(p==="y"||p==="Y"||m.return&&at.cursor===0){let{group:y,resolve:P,rest:F,report:G}=at;ps(null),Wc([y],{resolve:P,rest:F,...G?{report:G}:{}});return}if(p==="b"||p==="B"||m.escape||m.return){u();return}return}if(Vt){if(m.upArrow){mo(u=>u&&{...u,cursor:Math.max(0,u.cursor-1)});return}if(m.downArrow){mo(u=>u&&{...u,cursor:Math.min(u.rows.length-1,u.cursor+1)});return}if(p&&/^[0-9]$/.test(p)){let u=wn(p,Vt.rows.length);u!==null&&mo(y=>y&&{...y,cursor:u});return}if(m.return){let u=Vt.rows[Vt.cursor];mo(null),u.action==="capture"?Rs(u.ids,{runLine:u.kind==="all"?["/screenshot capture --all","/capture --all"]:void 0}):u.action==="annotate"?Ki(u.ids,{verifiedBefore:new Set(Ue(e).filter(y=>y.state==="verified").map(y=>y.id))}):u.kind==="shot"?Yf(u.ids[0]):Kf(u.ids,{setup:!0,runLine:u.kind==="all"?["/screenshot author --all","/screenshot --all"]:void 0});return}if(m.escape){mo(null);return}return}if(Tt){if(m.escape){wo(null);return}if(m.upArrow){wo(u=>u&&{...u,cursor:Math.max(0,u.cursor-1)});return}if(m.downArrow){wo(u=>u&&{...u,cursor:Math.min(Math.max(0,Hi.length-1),u.cursor+1)});return}if(m.return){let u=Hi[Tt.cursor];if(u){wo(null);try{h({kind:"preview",name:Ci(u),text:Ev(fc(Pi(e,u),"utf8"))})}catch(y){h({kind:"note",tone:"error",text:`Could not read ${u}: ${y.message}`})}}return}if(m.backspace||m.delete){wo(u=>u&&{...u,query:u.query.slice(0,-1),cursor:0});return}if(p&&!m.ctrl&&!m.meta&&p.length===1){wo(u=>u&&{...u,query:u.query+p,cursor:0});return}return}if(At){if(m.escape){vo(null);return}if(m.upArrow){vo(u=>u&&{...u,cursor:Math.max(0,u.cursor-1)});return}if(m.downArrow){vo(u=>u&&{...u,cursor:Math.min(Math.max(0,Gi.length-1),u.cursor+1)});return}if(m.return){let u=Gi[At.cursor];if(u){vo(null),Ve(u.uuid),fn.current={uuid:u.uuid,firstPrompt:u.firstPrompt,titleFired:!0},po(u.name),lf(u.uuid),nr.current=[],pt.current={printed:[],armed:[],printedAt:pr.current};let y=ef(e,u.uuid);for(let P of y)h(P);h({kind:"note",tone:"ok",text:y.length?`Resumed "${u.name}" \u2014 restored ${y.length} message(s); continue where you left off.`:`Resumed "${u.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(m.backspace||m.delete){vo(u=>u&&{...u,query:u.query.slice(0,-1),cursor:0});return}if(p&&!m.ctrl&&!m.meta&&p.length===1){vo(u=>u&&{...u,query:u.query+p,cursor:0});return}return}if(m.tab&&!g&&ae){k(ae),Kt();return}if(!g&&ge.length>0&&!Ae.current&&p&&/^[1-9]$/.test(p)){let u=ge[Number(p)-1];if(u){k(ao(u));return}}if(!g&&ge.length===0&&!Ae.current&&pt.current.armed.length>0&&p&&/^[1-9]$/.test(p)){let u=pt.current.armed[Number(p)-1];if(u){k(u);return}}if(!g&&(Ui||Co)&&p==="c"&&!m.ctrl&&!m.meta&&!m.return&&!m.tab){let u=Ui!=null;Xh(Ui??Co).then(P=>{h({kind:"note",tone:P?"ok":"warn",text:P?u?"\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.":u?"Couldn't reach your clipboard \u2014 select the feedback above and copy it manually.":"Couldn't reach your clipboard \u2014 select the prompt above and copy it manually."}),P&&u&&Lc(null),P&&!u&&Lf(!0)});return}if(!em(p,m)){if(Mc){if(m.upArrow){On(u=>Math.max(0,u-1));return}if(m.downArrow){On(u=>Math.min(vn.length-1,u+1));return}if(m.tab){k("/"+(vn[Ln]?.name??"")+" "),On(0);return}if(m.return){let u=vn[Ln];if(u){let y=g.trim().slice(1).split(/\s+/).slice(1).join(" ");if(Oy(u.usage)&&!y){k("/"+u.name+" "),On(0);return}Ss("/"+u.name+(y?" "+y:""));return}}}else{if(!g&&ge.length>0&&!Ae.current&&(m.upArrow||m.downArrow)){if(m.downArrow){fe(u=>u===null?0:Math.min(ge.length-1,u+1));return}if(on!==null){fe(u=>u===null||u===0?null:u-1);return}}if(m.upArrow){if(g!==""&&pn===null){Qi(-1);return}let u=vc.current;if(!u.length)return;let y=pn===null?u.length-1:Math.max(0,pn-1);uo(y),k(u[y]??"");return}if(m.downArrow){if(g!==""&&pn===null){Qi(1);return}let u=vc.current;if(pn===null)return;let y=pn+1;y>=u.length?(uo(null),k("")):(uo(y),k(u[y]??""));return}}if(m.return){if(on!==null&&!g&&ge[on]){let u=ao(ge[on]);fe(null),Ss(u);return}Ss();return}if(m.backspace||m.delete){A();return}if(m.escape){Xe.current&&(ko.current=!0,xs({kind:"stopped",how:"esc"},Xe.current.parked)),k(""),On(0),Kt(),we([]),yo(null),fe(null),Z.current=!0;return}p&&!m.ctrl&&!m.meta&&Jf(p)}}}),it(()=>{if(S||x)return;let p=bo.current.shift();p!==void 0&&(Rc([...bo.current]),Ss(p))},[S,x,Ss]),he(je,{flexDirection:"column",width:ht,children:[Uc!==null&&he(je,{marginTop:1,flexDirection:"column",children:[Uc.truncated&&q(Y,{dimColor:!0,children:"\u2026"}),q(Y,{children:Uc.text})]}),ur?q(nO,{step:ur.step,cmd:ur.cmd,startedAt:ur.startedAt,spentUsd:Math.max(ur.spentUsd,Et-(Xe.current?.stepStartedSpend??Et)),budgetUsd:ur.budgetUsd}):null,S&&dr?q(sO,{p:dr}):null,Ef?q(oO,{text:Ef}):S&&!dr?q(tO,{startTime:Ut.current,chars:kc}):null,q(je,{borderStyle:"round",borderColor:Bf.prod?"yellow":le,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:g?Zf.map((p,m)=>{let u=l.text.slice(p.start,p.end),y=m===pc(Zf,l.pos),P=Math.min(l.pos,p.end)-p.start;return he(Y,{children:[q(Y,{color:le,children:m===0?"> ":" "}),y?he(Jo,{children:[u.slice(0,P),q(as,{ch:u[P]??" "}),u.slice(P+1)]}):u||" "]},`${m}-${p.start}`)}):he(Y,{children:[q(Y,{color:le,children:"> "}),Mn?q(as,{ch:" "}):Re&&!S?he(Jo,{children:[q(as,{ch:Re[0],dim:!0}),q(Y,{color:"gray",children:Re.slice(1)})]}):ae&&!S?he(Jo,{children:[q(as,{ch:ae[0],dim:!0}),q(Y,{color:"gray",children:ae.slice(1)}),q(Y,{dimColor:!0,children:" (tab)"})]}):(_c.isSetup||!nn)&&!S?he(Jo,{children:[q(as,{ch:_c.text[0],dim:!0}),q(Y,{color:"gray",children:_c.text.slice(1)})]}):q(as,{ch:" "})]})}),Pf.length>0&&q(je,{flexDirection:"column",paddingX:1,children:Pf.map((p,m)=>q(Y,{color:"gray",children:`\u29D7 queued: ${p}`},`${m}-${p.slice(0,24)}`))}),dt?he(je,{flexDirection:"column",paddingX:1,children:[q(Y,{color:le,bold:!0,children:"Auto mode \u2014 I run each step myself"}),q(Y,{color:"gray",children:` first step ${dt.firstCmd}${dt.scale?` \u2014 ${dt.scale}`:""}`}),dt.upcoming.length>0?he(Jo,{children:[q(Y,{color:"gray",children:" as things stand, after that:"}),dt.upcoming.map(p=>q(Y,{color:"gray",children:` ${p.cmd}${p.scale?` ${p.scale}`:""}`},p.cmd)),q(Y,{color:"gray",children:" each step changes what the next one finds, so this is not a total"})]}):q(Y,{color:"gray",children:" I work down the ladder from there \u2014 reviewing, checking style, saving and going live"}),[dt.scale,...dt.upcoming.map(p=>p.scale)].every(p=>!p?.includes("$"))?q(Y,{color:"gray",children:" no cost estimate yet \u2014 this repo has not finished a run for me to measure"}):null,q(Y,{color:"gray",children:` spending limit ${Ye(dt.budgetUsd)} \xB7 I stop and report if it is reached`}),q(Y,{color:"gray",children:" screenshots are not part of an automatic run"}),dt.overBudget?q(Y,{color:"yellow",children:`\u26A0 That is more than your ${Ye(dt.budgetUsd)} limit. I will stop partway and report what is left.`}):null,q(Y,{dimColor:!0,children:dt.overBudget?"b raise the limit \xB7 enter start anyway \xB7 esc stay in manual for now":"enter start \xB7 b change the limit \xB7 esc stay in manual for now"})]}):gs?q(M$,{tab:gs.tab,scroll:gs.scroll,rows:Hv,width:ht,version:o,engineVersion:Nv}):gn?he(je,{flexDirection:"column",paddingX:1,children:[q(Y,{color:le,bold:!0,children:"Select model"}),q(Y,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),_t.map((p,m)=>he(Y,{color:m===gn.cursor?le:void 0,children:[m===gn.cursor?"\u276F ":" ",`${m+1}. ${p.label}${m===gn.current?" \u2714":""}`.padEnd(16),q(Y,{color:"gray",children:` ${p.desc}`})]},p.label)),q(Y,{dimColor:!0,children:xt({verb:"set as default",rows:_t.length,extra:["s this session only"]})})]}):Ht?he(je,{flexDirection:"column",paddingX:1,children:[q(Y,{color:le,bold:!0,children:"Switch connection profile"}),q(jn,{rows:Ht.rows,cursor:Ht.cursor,cap:rn,render:(p,m,u)=>he(Y,{color:u?le:void 0,children:[u?"\u276F ":" ",`${m+1}. ${p.name}${m===Ht.current?" \u2714":""}`.padEnd(20),q(Y,{color:"gray",children:` ${p.env} \xB7 ${p.who??"not signed in"}`}),p.prod?q(Y,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},p.name)}),q(Y,{dimColor:!0,children:xt({verb:"switch (saved as default)",rows:Ht.rows.length,extra:["s this session only"]})})]}):Gt?he(je,{flexDirection:"column",paddingX:1,children:[q(Y,{color:le,bold:!0,children:"Pick your Document360 environment"}),q(jn,{rows:Gt.rows,cursor:Gt.cursor,cap:rn,render:(p,m,u)=>he(Y,{color:u?le:void 0,children:[u?"\u276F ":" ",`${m+1}. ${p.name}`.padEnd(16),q(Y,{color:"gray",children:` ${p.apiUrl}`}),p.note?q(Y,{color:"yellow",children:` \u26A0 ${p.note}`}):null]},p.name)}),q(Y,{dimColor:!0,children:xt({verb:"use it",rows:Gt.rows.length})})]}):ot?he(je,{flexDirection:"column",paddingX:1,children:[q(Y,{color:le,bold:!0,children:"Switch workspace"}),q(Y,{dimColor:!0,children:`environment ${ot.environment} \xB7 project ${ot.projectName??`${ot.projectId.slice(0,8)}\u2026`}`}),q(jn,{rows:ot.rows,cursor:ot.cursor,cap:rn,render:(p,m,u)=>he(Y,{color:u?le:void 0,children:[u?"\u276F ":" ",`${m+1}. ${p.name}${m===ot.current?" \u2714":""}`.padEnd(30),q(Y,{color:"gray",children:p.type?` ${p.type}`:""})]},p.id)}),q(Y,{dimColor:!0,children:xt({verb:"switch",rows:ot.rows.length})})]}):ct?he(je,{flexDirection:"column",paddingX:1,children:[q(Y,{color:le,bold:!0,children:"Choose project"}),q(Y,{dimColor:!0,children:`environment ${ct.environment}`}),q(jn,{rows:ct.rows,cursor:ct.cursor,cap:rn,render:(p,m,u)=>he(Y,{color:u?le:void 0,children:[u?"\u276F ":" ",`${m+1}. ${p.name}${m===ct.current?" \u2714":""}`.padEnd(30),q(Y,{color:"gray",children:p.sub?` ${p.sub}`:""})]},p.id)}),q(Y,{dimColor:!0,children:xt({verb:"switch",rows:ct.rows.length})})]}):ut?(()=>{let m=Math.min(Math.max(0,ut.cursor-Math.floor(7)),Math.max(0,ut.rows.length-14)),u=ut.rows.slice(m,m+14),y=ut.rows.filter(P=>P.checked).length;return he(je,{flexDirection:"column",paddingX:1,children:[q(Y,{color:le,bold:!0,children:`Which folders back the user docs? (${y} selected of ${ut.rows.length})`}),m>0?q(Y,{dimColor:!0,children:` \u2191 ${m} more`}):null,u.map((P,F)=>{let G=m+F;return he(Y,{color:G===ut.cursor?le:void 0,children:[G===ut.cursor?"\u276F ":" ",P.checked?"\u25C9 ":"\u25CB ",P.path.padEnd(Math.min(48,ht-34)),q(Y,{color:"gray",children:Ya(P)})]},P.path)}),m+14<ut.rows.length?q(Y,{dimColor:!0,children:` \u2193 ${ut.rows.length-m-14} more`}):null,q(Y,{dimColor:!0,children:xt({verb:"save",multi:!0})})]})})():mt?he(je,{flexDirection:"column",paddingX:1,children:[q(Y,{color:le,bold:!0,children:mt.title??"Which category? (pick one to scope to)"}),q(jn,{rows:mt.rows,cursor:mt.cursor,cap:rn,render:(p,m,u)=>he(Y,{color:u?le:void 0,children:[u?"\u276F ":" ",`${`${m+1}.`.padEnd(3)} ${p.label} (${p.count})`.padEnd(Math.min(44,Math.max(20,ht-24))),q(Y,{color:"gray",children:` ${p.token}`})]},p.token)}),q(Y,{dimColor:!0,children:xt({verb:"choose it",rows:mt.rows.length})})]}):Ct?he(je,{flexDirection:"column",paddingX:1,children:[q(Y,{color:le,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),q(jn,{rows:Ct.rows,cursor:Ct.cursor,cap:rn,render:(p,m,u)=>he(Y,{color:u?le:void 0,bold:p.kind==="category"&&!u,children:[u?"\u276F ":" ",`${p.indent?" ":" "}${`${m+1}.`.padEnd(3)} ${p.label}`.padEnd(Math.min(56,ht-24)),p.note?q(Y,{color:"gray",children:` ${p.note}`}):null]},`${p.kind}:${p.paths.join(",")}`)}),q(Y,{dimColor:!0,children:xt({verb:"push as drafts",rows:Ct.rows.length})})]}):qt?he(je,{flexDirection:"column",paddingX:1,children:[q(Y,{color:le,bold:!0,children:"Publish live to your readers \u2014 this is what they will see:"}),q(jn,{rows:[{path:"",articleId:"",label:`Publish all ${qt.rows.length} live`,version:void 0},...qt.rows],cursor:qt.cursor,cap:rn,render:(p,m,u)=>he(Y,{color:u?le:void 0,bold:m===0&&!u,children:[u?"\u276F ":" ",` ${`${m+1}.`.padEnd(3)} ${p.label}`.padEnd(Math.min(56,ht-24)),m>0?q(Y,{color:"gray",children:` ${p.version?`draft v${p.version} \u2192 live`:"draft \u2192 live"}`}):null]},`${m}:${p.path||"all"}`)}),q(Y,{dimColor:!0,children:xt({verb:"publish live",cancel:"leave as drafts",rows:qt.rows.length+1})})]}):Pt?he(je,{flexDirection:"column",paddingX:1,children:[q(Y,{color:le,bold:!0,children:"Which comments do you want to look at?"}),q(jn,{rows:Pt.rows,cursor:Pt.cursor,cap:rn,render:(p,m,u)=>he(Y,{color:u?le:void 0,bold:p.kind==="all"&&!u,children:[u?"\u276F ":" ",`${(p.kind==="all"?"":`${p.n}.`).padEnd(4)}${p.label}`.padEnd(Math.min(56,Math.max(20,ht-24))),p.kind==="article"?q(Y,{color:"gray",children:p.note}):null]},p.kind==="all"?"all":p.group.articleId)}),q(Y,{dimColor:!0,children:xt({verb:"open it",cancel:"close",rows:Pt.rows.length-1})}),Pt.resolve?q(Y,{dimColor:!0,children:"--resolve is on: threads you answer will be closed as well as replied to"}):null]}):at?he(je,{flexDirection:"column",paddingX:1,children:[q(Y,{color:le,bold:!0,children:`${at.group.title} \u2014 ${at.group.threads.length} comment${at.group.threads.length===1?"":"s"}`}),he(Y,{color:at.cursor===0?le:void 0,children:[at.cursor===0?"\u276F ":" ",at.resolve?"Yes \u2014 fix them, push the draft, reply and resolve":"Yes \u2014 fix them, push the draft to Document360, then reply"]}),he(Y,{color:at.cursor===1?le:void 0,children:[at.cursor===1?"\u276F ":" ",at.fromList?"No \u2014 back to the list":"No \u2014 leave them for now"]}),q(Y,{dimColor:!0,children:xt({verb:"open it",cancel:"go back",extra:["y answer"]})})]}):Vt?he(je,{flexDirection:"column",paddingX:1,children:[q(Y,{color:le,bold:!0,children:Vt.title}),(()=>{let{rows:p,cursor:m}=Vt,u=oc(p.length,m,rn),y=u.start,P=p.slice(u.start,u.end),F=`${p.length}.`.length+1,G=_g(p,Math.max(20,ht-4-F));return he(Jo,{children:[y>0?q(Y,{color:"gray",children:` \u2026 ${y} more above`}):null,P.map((w,$)=>{let v=y+$,b=v===m,R=G[v];return he(Y,{color:b?le:void 0,bold:(w.kind==="all"||w.kind==="category")&&!b,children:[b?"\u276F ":" ",`${v+1}.`.padEnd(F),R.head,R.note?q(Y,{color:"gray",children:R.note}):null]},`${w.action}:${w.kind}:${w.ids.join(",")}`)}),u.below>0?q(Y,{color:"gray",children:` \u2026 ${u.below} more below`}):null]})})(),q(Y,{dimColor:!0,children:xt({verb:"run it",rows:Vt.rows.length})})]}):Tt?he(je,{flexDirection:"column",paddingX:1,children:[q(Y,{color:le,bold:!0,children:`Preview article${Tt.query?` \u2014 filter: ${Tt.query}`:" (type to filter)"}`}),Hi.length===0?q(Y,{color:"gray",children:"no articles match"}):Hi.map((p,m)=>he(Y,{color:m===Tt.cursor?le:void 0,children:[m===Tt.cursor?"\u276F ":" ",p]},p)),q(Y,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):At?he(je,{flexDirection:"column",paddingX:1,children:[q(Y,{color:le,bold:!0,children:`Resume session${At.query?` \u2014 filter: ${At.query}`:" (type to filter)"}`}),Gi.length===0?q(Y,{color:"gray",children:"no sessions match"}):Gi.map((p,m)=>he(Y,{color:m===At.cursor?le:void 0,children:[m===At.cursor?"\u276F ":" ",p.name.slice(0,28).padEnd(30),q(Y,{color:m===At.cursor?le:"gray",children:p.firstPrompt.slice(0,Math.max(10,ht-40))})]},p.uuid)),q(Y,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Mc?he(je,{flexDirection:"column",children:[To>0?q(Y,{dimColor:!0,children:` \u22EF ${To} more above`}):null,Fc.map((p,m)=>{let u=To+m,y=p.name==="model"&&Tc?`${p.desc} (currently ${Tc})`:p.desc,P=Math.max(20,ht-4),F=p.usage.length>P?`${p.usage.slice(0,P-1)}\u2026`:p.usage,G=P-Math.max(F.length,22)-1,w=G<=1?"":y.length>G?`${y.slice(0,G-1)}\u2026`:y;return he(Y,{color:u===Bi?le:void 0,children:[u===Bi?"\u276F ":" ",F.padEnd(22)," ",q(Y,{color:u===Bi?le:"gray",children:w})]},p.name)}),To+Fc.length<vn.length?q(Y,{dimColor:!0,children:` \u22EF ${vn.length-To-Fc.length} more below`}):null,q(Y,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!S&&!g&&ge.length>0?he(je,{flexDirection:"column",paddingX:1,children:[Cf?q(Y,{color:le,children:Cf}):null,q(jn,{rows:ge,cursor:on??0,cap:rn,render:(p,m)=>{let u=m===on,y=ao(p),P=y.slice(0,Math.max(20,ht-7)),F=ht-P.length-9,G=F>=12?(W$(p)??Iy(y)).slice(0,F):"";return he(Y,{color:u?le:void 0,children:[u?"\u276F ":" ",q(Y,{color:le,children:m+1})," ",P,G?q(Y,{color:u?le:void 0,dimColor:!u,children:` \u2014 ${G}`}):null]},y)}}),q(Y,{dimColor:!0,children:`\u2191\u2193 choose \xB7 enter run \xB7 1-${ge.length} fill \xB7 esc cancel`})]}):q(je,{paddingX:1,children:he(Y,{color:"gray",children:[Bf.prod?"\u26A0 PRODUCTION \xB7 ":"",q(Y,{color:ys?le:void 0,children:ys?"\u23F5\u23F5 auto":"\u23F5 manual"}),` \xB7 /help \xB7 ${Tc??"model n/a"}${t.kind==="api"?Et>0?` \xB7 session ${kt(Et)}`:"":Df>0?` \xB7 ${_r(Df)}`:""} \xB7 \u2191 history \xB7 shift+tab mode \xB7 ${Mv?"press ctrl+c again to exit":"ctrl+c twice to exit"}`]})})]})}oe();import{jsx as cO}from"react/jsx-runtime";async function jv(e=process.cwd(),t="auto",n,o="0.0.0"){let r=lO(t);r.kind==="none"&&(console.error(""),console.error(L("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${ee("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${ee("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=aO(cO(Dv,{cwd:e,auth:r,profileName:n,version:o}),{exitOnCtrlC:!1});await s(),process.stdout.write(`
597
- `),process.exit(0)}oe();import{writeCrashLog as wf,isBenignTransportError as uO}from"document360-engine";var Iv=!1;function dO(e=process.stdout){return e.destroyed===!0||e.writable===!1}function bf(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function Lv(e){if(Iv)return;Iv=!0;let t=(n,o)=>{if(uO(o)){wf({kind:n,level:"transport",message:bf(o),stack:o instanceof Error?o.stack:void 0,detail:e}),dO()&&(wf({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=wf({kind:n,level:"fatal",message:bf(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
598
- `+L(`\u2717 d360-writer crashed: ${bf(o)}`)+`
555
+ `)}`}),we(w.map(N=>`/draft ${N.name}`));return}let b="",R;if(v){let N=np(w,v);N?b=N:R=v}else b=w[0]?.name??"";await ve(gl(b,R),{display:v?`/draft ${v}`:"/draft",quietUser:!0});return}case"pull":{if(!To(p.trim()))return;let w=y.find(k=>k.startsWith("--"));try{if(w==="--status"){h({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let b=Date.now(),R=await xc({cwd:e,profileName:s});h({kind:"note",tone:"info",text:el(R,Date.now()-b).join(`
556
+ `)});return}if(w==="--baseline"){let b=y.find(F=>!F.startsWith("--")),R=b?b.replace(/\\/g,"/"):void 0;h({kind:"note",tone:"info",text:R?`Setting the sync baseline for ${R}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let N=await NL({cwd:e,profileName:s,relPaths:R?[R]:void 0}),M=R?{rebaselined:[],skipped:[]}:await DL({cwd:e,profileName:s});if(N.baselined.length===0&&N.skipped.length===0&&M.rebaselined.length===0){h({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}N.baselined.length>0&&h({kind:"note",tone:"ok",text:`\u2713 Recorded ${N.baselined.length} article${N.baselined.length===1?"":"s"} as matching Document360 \u2014 they read in-sync until either side changes.`}),M.rebaselined.length>0&&h({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${M.rebaselined.length} article${M.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),N.skipped.length>0&&h({kind:"note",tone:"warn",text:`${N.skipped.length} skipped:
557
+ ${N.skipped.map(F=>` - ${F.path} (${F.reason})`).join(`
558
+ `)}`}),W(F=>F+1);return}if(w==="--compare"){h({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let b=await CL({cwd:e,profileName:s}),R=b.onlyInLegacy.length===0&&b.onlyInManifest.length===0&&b.mappedMissingFromManifest.length===0,N=[`Legacy listing: ${b.legacyCount} \xB7 Manifest: ${b.manifestCount} \xB7 in both: ${b.inBoth}`];R?N.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(b.mappedMissingFromManifest.length&&N.push(`\u2717 ${b.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${b.mappedMissingFromManifest.slice(0,5).join(", ")}`),b.onlyInLegacy.length&&N.push(`\u26A0 ${b.onlyInLegacy.length} only in the legacy listing: ${b.onlyInLegacy.slice(0,5).join(", ")}`),b.onlyInManifest.length&&N.push(`\u26A0 ${b.onlyInManifest.length} only in the manifest: ${b.onlyInManifest.slice(0,5).join(", ")}`),N.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),h({kind:"note",tone:R?"ok":"warn",text:N.join(`
559
+ `)});return}if(w){h({kind:"note",tone:"error",text:`Unknown option: ${w} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let k=y[0];if(k){let b=k.replace(/\\/g,"/"),R;try{let N=await $v({cwd:e,profileName:s,relPath:b});R={plan:N,mode:N.overwritesLocalChanges?"conflict":"pull"}}catch(N){if(!vv(N))throw N;R={mode:"local-only",path:b,title:xv(e,b)}}De.current=[R],Ht.current=[],yn.current=[],mr();return}h({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let v=await kd({cwd:e,profileName:s});for(let b of $d(v))h({kind:"note",tone:b.tone,text:b.text});W(b=>b+1)}catch(k){h({kind:"note",tone:"error",text:`Pull failed: ${k.message}`})}return}case"scope":{if(!ke(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let w=jL(e);if(w.length===0){h({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.'});return}lr({cursor:0,rows:w.map(k=>({...k,checked:k.recommended}))});return}case"audit":{if(y[0]==="--auto"){let k=ke(e);if(!k){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let v=y[1]!=="off";gv({...k,autoAudit:v},e),h({kind:"note",tone:"ok",text:v?"\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(!To(p.trim()))return;let w=await Ys({cwd:e,profileName:s});if(w.kind==="audit-blocked"){Pe(w.note,{kind:"cmd",cmd:w.lead.cmd,reason:w.lead.reason},"warn");return}if(w.kind==="forward-to-agent"&&w.prompt){let k=await ve(w.prompt,{display:w.display,quietUser:!0}),v=Qa(e,s);if(v){Pe(v.note,{kind:"cmd",cmd:Dr.cmd,reason:Dr.reason},"warn"),W(b=>b+1);return}k.producedNothing||(xi(e,s),W(b=>b+1))}return}case"lint":case"check":{let w=Vs(u);w&&h({kind:"note",tone:"info",text:`\u2192 ${w}`});let k=y.find(N=>!N.startsWith("--")),v=k?` ${k}`:"",b=rs({cwd:e,scope:k}),R=Nn(b,y);if(y.includes("--fix")){let N=Zn(e,y,b);N.lines.length>0&&h({kind:"note",tone:"ok",text:N.lines.join(`
560
+ `)});let M=N.fixed>0?rs({cwd:e,scope:k}):b,F=Ud(e,y,M);if(!F){let J=Wd(e,y,M);h({kind:"note",tone:"ok",text:J.lines.join(`
561
+ `)});for(let $e of J.closed)h({kind:"note",tone:"ok",text:$e});return}let D={aborted:!1,partitions:0,failed:0,notRun:0};if(F.kind==="partitioned"){let J=await Qi({partitions:F.partitions,promptFor:F.promptFor,concurrency:_r,verb:"Fixing",doneNoun:"fixed",headline:`Fixing ${F.findings} issue${F.findings===1?"":"s"} across ${F.articles} article${F.articles===1?"":"s"} in ${F.partitions.length} batches (\u2264${_r} at once)`,calibrateAs:"/lint"});if(D=J.outcome,J.covered.length>0)try{ss(e,J.covered,mt("lint"))}catch{}if(J.aborted){let $e=qs({cwd:e,after:Nn(rs({cwd:e,scope:k}).filter(Le=>!Le.baselined),y),scope:k,aborted:!0,blocked:En(y)});Pe($e.text,{kind:"cmd",cmd:$e.cmd,reason:""},"warn");return}}else{h({kind:"note",tone:"info",text:`Fixing ${F.findings} doc issue${F.findings===1?"":"s"}\u2026`});let J=HL(e,k);await ve(F.prompt,{display:F.display,quietUser:!0});try{ss(e,J,mt("lint"))}catch{}}let X=Nn(rs({cwd:e,scope:k}).filter(J=>!J.baselined),y),I=Nn(M.filter(J=>!J.baselined),y),U=new Set(X.map(J=>J.fp)),G=new Set(I.map(J=>J.fp)),te=I.filter(J=>!U.has(J.fp)).length,de=X.filter(J=>!G.has(J.fp)).length,pe=de>0?`
562
+ \u26A0 ${de} new ${de===1?"issue":"issues"} appeared in the rewrites \u2014 recasting a sentence is where these come from.`:"";h({kind:"note",tone:X.some(J=>J.severity==="error")?"warn":"ok",text:X.length===0?`\u2713 Lint: all ${I.length} issue${I.length===1?"":"s"} resolved.`:[`\u2713 Lint: fixed ${te} of ${I.length}.${pe}`,"",...ei(X)].join(`
563
+ `)}),Sn(Zs(y,k),F.kind==="partitioned"?D:{aborted:!1,partitions:0,failed:0,notRun:0,verifiedComplete:X.length===0});let ye=qs({cwd:e,after:X,before:F.findings,scope:k,blocked:En(y)});Pe(ye.text,{kind:"cmd",cmd:ye.cmd,reason:""});return}if(h({kind:"note",tone:R.length===0?"ok":"warn",text:ei(R,{full:y.includes("--full"),baselined:y.includes("--baselined")}).join(`
564
+ `)}),R.length>0){let N=Ga(e,k)===0&&qa(e,k)===0?"; /push --all saves them to Document360 as-is":"",M=`/lint${v}${En(y)?" --blocked":""} --fix`,F=en(e,M);Pe(`Found ${R.length} doc issue${R.length===1?"":"s"} above. ${M} has the agent fix them in place${F?` (${F})`:""} \u2014 or /review${v} --fix for the full editorial pass${N}.`,{kind:"cmd",cmd:M,reason:""})}return}case"structure":{let w=Yr(e,s);if(w.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):","",...w].join(`
565
+ `)});return}case"status":{let w=y.some(k=>k==="--all"||k==="--full");h({kind:"block",text:Eh(e,{profileName:s,all:w,width:tt()}).join(`
566
+ `)}),Z.current=!0;return}case"retire":{let w=y.find(v=>!v.startsWith("-"));if(!w){h({kind:"block",text:Nh(e,s).join(`
567
+ `)}),Z.current=!0;return}let k=Lv(e,w)||w;if(!y.includes("--yes")&&!y.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(`
568
+ `)}),nt(`/retire ${k} --yes`,"tab to take it off your readers \xB7 or keep typing");return}C(!0);try{let v=await nO({cwd:e,path:k,profileName:s,now:new Date().toISOString()});h(v.ok?{kind:"note",tone:"ok",text:v.alreadyHidden?`\u2713 "${k}" was already invisible to readers. Recorded as retired, so nothing will offer to publish it again.
569
+ It stays on Document360 with its history and comments intact. /push puts it back.`:`\u2713 "${k}" is no longer visible to your readers.
570
+ 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 ${v.error.message}`})}finally{C(!1)}return}case"untrack":{let w=y.find(b=>!b.startsWith("-"));if(y.includes("--list")||!w&&!y.includes("--undo")){h({kind:"block",text:Dh(e,s).join(`
571
+ `)}),Z.current=!0;return}if(!w){h({kind:"note",tone:"warn",text:"\u2717 Name what to put back: /untrack --undo <path>"});return}let k=Lv(e,w)||w;if(y.includes("--undo")){let b=rO(e,s,k);h(b.ok?{kind:"note",tone:"ok",text:b.restoredTo?`\u2713 Put "${b.restoredTo}" back in your docs folder.`:"\u2713 No longer declined. /catch-up imports it again on the next run."}:{kind:"note",tone:"error",text:`\u2717 ${b.error.message}`});return}if(!y.includes("--yes")&&!y.includes("-y")){h({kind:"note",tone:"warn",text:[`\u26A0 This stops tracking "${k}" as one of your docs.`," Nothing on Document360 changes \u2014 the page, its history and its comments all stay,"," and your readers see no difference."," The markdown moves to .d360-writer/declined/, so nothing is deleted."," /untrack --undo puts it back if you change your mind."].join(`
572
+ `)}),nt(`/untrack ${k} --yes`,"tab to stop tracking it \xB7 or keep typing");return}let v=oO({cwd:e,path:k,profileName:s,now:new Date().toISOString()});h(v.ok?{kind:"note",tone:"ok",text:[`\u2713 "${v.title??v.path}" is no longer one of your docs.`,...v.keptAt?[` The markdown is kept at ${v.keptAt} \u2014 nothing was deleted.`]:[]," It is untouched on Document360. /catch-up will not import it again."].join(`
573
+ `)}:{kind:"note",tone:"error",text:`\u2717 Could not untrack "${k}" \u2014 ${v.error.message}`});return}case"eval":{h({kind:"block",text:Oh(e,{...y.find(w=>!w.startsWith("--"))?{scope:y.find(w=>!w.startsWith("--"))}:{},...s?{profile:s}:{},all:y.includes("--all")}).join(`
574
+ `)}),Z.current=!0;return}case"terms":{let w=y.findIndex(k=>k==="--approve");if(w!==-1){let k=y[w+1];h(k?{kind:"block",text:Lh(e,k.replace(/^["']|["']$/g,"")).lines.join(`
575
+ `)}:{kind:"note",tone:"warn",text:'\u2717 Name the spelling to approve, e.g. /terms --approve "drop-down".'}),Z.current=!0;return}h({kind:"block",text:Ih(e,{...y.find(k=>!k.startsWith("--"))?{scope:y.find(k=>!k.startsWith("--"))}:{},all:y.includes("--all")}).join(`
576
+ `)}),Z.current=!0;return}case"reuse":{let w=y.find(k=>!k.startsWith("--"));if(w==="pull"){(async()=>{let k=await vi(e);h({kind:"block",text:k.lines.join(`
577
+ `)});for(let v of Ye(e,"/reuse pull"))h({kind:"note",tone:"ok",text:v});k.restart&&Ve()})(),Z.current=!0;return}if(w==="audit"){if(y.includes("--create")){let v=sO(e);if(!v||v.proposals.length===0){h({kind:"block",text:ql().join(`
578
+ `)}),Z.current=!0;return}let{picks:b,bad:R}=Gl(y,v.proposals.length);for(let N of R)h({kind:"note",tone:"warn",text:`\u26A0 There is no proposal ${N} \u2014 the list has ${v.proposals.length}.`});if(b.length===0){h({kind:"note",tone:"info",text:"\u25CB Nothing picked, so nothing was created."}),Z.current=!0;return}(async()=>{let{outcome:N,pullLines:M}=await Gh(e,b.map(F=>v.proposals[F]));M.length>0&&h({kind:"block",text:M.join(`
579
+ `)}),h({kind:"block",text:Hl(e,N).lines.join(`
580
+ `)});for(let F of Ye(e,"/reuse audit"))h({kind:"note",tone:"ok",text:F});N.created.length>0&&Ve()})(),Z.current=!0;return}let k=Bl(e,y);if("lines"in k){h({kind:"block",text:k.lines.join(`
581
+ `)});for(let v of Ye(e,"/reuse audit"))h({kind:"note",tone:"ok",text:v});Z.current=!0;return}h({kind:"block",text:Wl(k.articles,k.families,k.values,0).join(`
582
+ `)}),(async()=>(await ve(k.prompt,{display:k.display,quietUser:!0}),h({kind:"block",text:Vl(e,k.display.split(/\s+/)[2]).join(`
583
+ `)})))(),Z.current=!0;return}if(w==="add"){let k=Hh(y);if("error"in k){h({kind:"note",tone:"warn",text:`\u2717 ${k.error}`}),Z.current=!0;return}(async()=>{let v=await Bh(e,k.kind,k.name,k.value,k.description);h({kind:"block",text:v.lines.join(`
584
+ `)}),v.restart&&Ve()})(),Z.current=!0;return}if(w&&w!=="show"){h({kind:"note",tone:"warn",text:`\u2717 I don't know "/reuse ${w}". Use /reuse to see what this project maintains, /reuse pull to refresh it, or /reuse add variable <name> "<value>".`}),Z.current=!0;return}h({kind:"block",text:Wh(e).join(`
585
+ `)}),Z.current=!0;return}case"reorder":{let w=Th(e,y);if(!w){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let k=await ve(w.prompt,{display:w.display,quietUser:!0}),v=_t(e,{text:"Reordered locally \u2014 /push --all syncs the new order to Document360.",cmd:"/push --all"},"Reordered locally. ");vn(k,v.text,{kind:"cmd",cmd:v.cmd,reason:""});return}case"restructure":{let w=Ah(e,y);if(!w){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let k=await ve(w.prompt,{display:w.display,quietUser:!0});if(y.filter(b=>!b.startsWith("--")).length===0){vn(k,null,null);return}let v=_t(e,{text:"Restructured locally \u2014 /push --all moves it on Document360.",cmd:"/push --all"},"Restructured locally. ");vn(k,v.text,{kind:"cmd",cmd:v.cmd,reason:""});return}case"review":{let w=Ch(e,y);if(w){h({kind:"note",tone:"ok",text:w.lines[0]});for(let U of w.closed)h({kind:"note",tone:"ok",text:U});let I=$i(e,y,null);I&&(h({kind:"note",tone:"info",text:"One thing left: no editor has looked at how your docs are organised since it last changed. Checking that now \u2014 it reads the shape, not the articles, so it is one quick pass."}),(await ve(I.prompt,{display:I.display,quietUser:!0})).producedNothing||Iv(e,I.fingerprint)),Pe(w.cta.text,{kind:"cmd",cmd:w.cta.cmd,reason:""});return}let k=Sh(e,y);if(!k){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let v=y.includes("--fix"),b=y.find(I=>!I.startsWith("--")),R=v?zo(e,y,b):[],N=v?yf(e):null,M={aborted:!1,partitions:0,failed:0,notRun:0},F,D=null,X=$i(e,y,k);if(k.kind==="partitioned"){let I=await e0(k,v,N,!!X);M=I.outcome,F=I,D=I.evidence}else F=await ve(k.prompt,{display:k.display,quietUser:!0}),M={...M,producedNothing:F.producedNothing};if("aborted"in F&&F.aborted){let I=y.includes("--blocked")?"--blocked --fix":y.includes("--stale")?"--stale --fix":"--fix",U=Se("/review",I,b);Pe(`Stopped \u2014 the batches that finished are saved. ${U} picks up the rest${b||Kr(y)?"":", or narrow it with /review <category> --fix"}.`,{kind:"cmd",cmd:U,reason:""},"warn");return}if(X&&((await ve(X.prompt,{display:X.display,quietUser:!0})).producedNothing||Iv(e,X.fingerprint)),k.kind!=="partitioned"&&v&&!F.producedNothing&&(D=Ko(e,R,N,s),D.earned.length>0))try{ss(e,D.earned,mt("review"))}catch{}if(v&&Sn(`/review${b?` ${b}`:""}${y.includes("--all")?" --all":""}${y.includes("--blocked")?" --blocked":y.includes("--stale")?" --stale":""} --fix`,M),v){if(v&&!F.producedNothing){let pe=Zn(e,["--fix"],rs({cwd:e,scope:b}));pe.lines.length>0&&h({kind:"note",tone:"ok",text:pe.lines.join(`
586
+ `)})}let I=v&&!F.producedNothing?rs({cwd:e,scope:b}).filter(pe=>!pe.baselined&&pe.severity==="error"):[],U=D?D.changed.length:-1,G=U<0?"Editor applied its fixes":ki(U),te=Vr(e,D?.unadopted??[],{lead:U===0&&I.length===0});if(te&&h({kind:"note",tone:"warn",text:te.lines.join(`
587
+ `)}),I.length>0){let pe=new Set(I.map(Le=>Le.path)).size,ye=`/lint${b?` ${b}`:""} --blocked --fix`,J=en(e,ye),$e=!D||D.changed.length>0;h({kind:"note",tone:"warn",text:$e?`\u26A0 The editor's rewrites left ${I.length} style error${I.length===1?"":"s"} in ${pe} article${pe===1?"":"s"} \u2014 recasting a sentence is where these appear.`:`\u26A0 ${I.length} style error${I.length===1?"":"s"} in ${pe} article${pe===1?"":"s"} still block${I.length===1?"s":""} publishing \u2014 the editor changed nothing, so these were already there.`}),vn(F,`${D?ki(D.changed.length):"Editor applied its fixes"}, but ${I.length} style error${I.length===1?"":"s"} remain. ${ye} clears ${I.length===1?"it":"just those"} \u2014 it costs nothing to find them and one pass to correct${J?` (${J})`:""}. 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:ye,reason:""});return}if(te?.cta){vn(F,te.cta.text,{kind:"cmd",cmd:te.cta.cmd,reason:""});return}let de=_t(e,{text:`\u2713 ${G} \u2014 your docs are ready. /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 ${G} in this scope. `,b);vn(F,de.text,{kind:"cmd",cmd:de.cmd,reason:""})}else{let I=b?` ${b}`:"",U=Ga(e,b)===0&&qa(e,b)===0?`; /push${b?"":" --all"} saves them to Document360 as-is`:"";vn(F,`The review listed issues above. /review${I} --fix lets the editor apply them all (or /lint${I} --fix for just the deterministic ones${U}).`,{kind:"cmd",cmd:`/review${I} --fix`,reason:""})}return}case"capture-setup":{await H();return}case"devhints":{if(!ke(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}h({kind:"note",tone:"info",text:xr(vr(e)).join(`
588
+ `)}),xn(Io()),xs.current=Xt(e).status==="current",pr.current=Pn(e);return}case"discover":{if(!ke(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await ve(fd(),{display:"/discover",quietUser:!0});return}case"ask":{if(!ke(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let w=y.join(" ").trim();if(w===""){h({kind:"block",text:Np(eO(e)).join(`
589
+ `)});return}try{let k=ZL(e,{question:w});h({kind:"note",tone:"ok",text:Ep(k.file,di(e)).join(`
590
+ `)})}catch(k){h({kind:"note",tone:"warn",text:`Could not file the question: ${k.message}`})}return}case"inbox":{if(!ke(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(Tp(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 ve(Ap(),{display:"/inbox",quietUser:!0});return}case"auto":{let w=ke(e);if(!w){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let k=pd(y);if(k.malformed){h({kind:"note",tone:"error",text:`I could not read that spending limit. Give it as an amount, like: /auto --budget 150 (the standard limit is ${Ke(vL)}).`});return}let v=hd(y,k.usd),b=R=>{for(let N of R)h({kind:"note",tone:N.tone,text:N.text});W(N=>N+1)};if(k.usd!==void 0&&!v){let R=dd(e,w,k.usd);R&&b(R);return}if(!v||v==="status"){for(let R of zs(w))h({kind:"note",tone:R.tone,text:R.text});return}if(v==="on"||v==="off"){v==="on"&&($o.current=!1);let R=k.usd!==void 0?{...w,auto:{...w.auto,enabled:w.auto?.enabled===!0,budgetUsd:k.usd}}:w;b(Ja(e,R,v==="on"));return}h({kind:"note",tone:"error",text:`I don't know "${v}". Use: /auto on \xB7 /auto off \xB7 /auto status \xB7 /auto --budget <amount>`});return}case"share":{let w=ke(e);if(!w){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let k=y[0]?.trim().toLowerCase();if(k==="status"){for(let b of xl(e,w))h({kind:"note",tone:b.tone,text:b.text});return}if(k==="on"||k==="off"){for(let b of Dp(e,w,k==="on"))h({kind:"note",tone:b.tone,text:b.text});W(b=>b+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 v=await Rl(e,w);for(let b of v.lines)h({kind:"note",tone:b.tone,text:b.text});v.changed&&W(b=>b+1);return}case"feedback":{let w=Ev(e),k="";try{k=os(w)?kc(w,"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 v=await nf(k.trim());h({kind:"note",tone:v?"ok":"warn",text:v?"\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 ${w} and copy it manually.`}),v&&Uc(null);return}case"document":{if(!ke(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{push:w,skipReview:k,what:v}=sp(y);if(!v&&rp(e)===0){h({kind:"note",tone:"info",text:ap});return}let b=`/document${v?` ${v}`:""}${w?" --push":""}`,R=await ve(ip(v),{display:b,quietUser:!0});w&&!R.producedNothing&&await Zf({skipReview:k});return}case"catch-up":{if(!ke(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!To(p.trim()))return;let{push:w,skipReview:k,includeUnfinished:v}=Op(y);for(let G of await Ip(e))h({kind:"note",tone:G.tone,text:G.text});h({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let b=await Bp({cwd:e,profileName:s});for(let G of Hp(b))h({kind:"note",tone:G.startsWith("\u2713")?"ok":G.startsWith("\u2139")?"info":"warn",text:G});let R=hi(e);for(let G of _p(R))h({kind:"note",tone:G.tone,text:G.text});let N=Mp(e),M=v?[]:N,F=Fp(e,M);for(let G of Up(M,F))h({kind:"note",tone:G.tone,text:G.text});let D=Zt(e);h({kind:"note",tone:"info",text:Lp(D)});let X=yf(e);Tt.current?.beginTurn({baseline:X,allowUnfinishedHints:v});let I=await ve(Wp(R,{held:N.length,includeUnfinished:v},D.briefMoved),{display:`/catch-up${w?" --push":""}${v?` ${Pl}`:""}`,quietUser:!0});I.producedNothing||tO(e);let U=qo(e,X,"","/catch-up");if(w&&!I.producedNothing)await Zf({skipReview:k});else if(U.cta)vn(I,U.cta.text,{kind:"cmd",cmd:U.cta.cmd,reason:""});else{let G=Cl({queued:D,hold:R.hold});vn(I,G.note,G.lead?{kind:"cmd",cmd:G.lead.cmd,reason:G.lead.reason}:null,G.tone)}return}case"comments":{if(!ke(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!To(p.trim()))return;let w=Kp(y);qe("Checking Document360 for reviewer comments\u2026"),C(!0);let k=null;try{k=await Tl(e,s,{...w.scope,onProgress:(b,R)=>qe(`Checking Document360 for reviewer comments\u2026 ${b}/${R}`)})}catch(b){h({kind:"note",tone:"error",text:`Couldn\u2019t read comments from Document360: ${b.message}`})}finally{C(!1),qe(null)}if(!k)return;W(b=>b+1);let v=Vo(k.threads,k.labels);if(k.threads.length===0){h({kind:"note",tone:"ok",text:mi(k,{showAnswered:w.showAnswered,width:tt()}).join(`
591
+ `)});return}if(w.answer&&(w.all||w.scope.path||w.scope.scope||v.length===1)){hr(Vp(k,{full:!0,showAnswered:w.showAnswered,width:tt()})),await Vc(v,{resolve:w.resolve});return}if(v.length===1){hr(Al(v[0],{width:tt()})),hs({group:v[0],cursor:0,fromList:!1,resolve:w.resolve,rest:[]});return}hr(mi(k,{showAnswered:w.showAnswered,width:tt()})),bn({cursor:0,rows:El(v),groups:v,resolve:w.resolve,report:k});return}case"update":{if(Nl()){h({kind:"note",tone:"info",text:"Checking for a newer version\u2026"});let k=await Tv({pkg:Yo,currentVersion:o,force:!0}).catch(()=>null);if(!k?.updateAvailable||!k.latest){h({kind:"note",tone:"ok",text:`\u2713 You're on the latest version (v${o}).`});return}Gi.current=!0,Dl(k.latest),h({kind:"note",tone:"info",text:`\u2B06 Update v${k.latest} is ready.
592
+ Windows can't replace the files while d360-writer is running, so I'll install it the moment you /exit.`}),se("/exit");return}Gi.current=!0,h({kind:"note",tone:"info",text:"Updating the d360-writer toolchain\u2026 (don\u2019t close this window)"}),uo(!0);let w=await wi().finally(()=>uo(!1));w.ok?(h({kind:"note",tone:"ok",text:`\u2713 Updated ${w.packages.join(" + ")} \u2014 run /exit, then relaunch to apply.`}),se("/exit"),us("")):(h({kind:"note",tone:"warn",text:`Update failed. ${yi(w.output)}`}),w.output&&h({kind:"note",tone:"info",text:`${w.output}
593
+
594
+ Full output: ${gi()}`}));return}case"screenshot":{let w=_s(y),k=Lo(e);if(k&&w.mode!=="list"&&h({kind:"note",tone:"info",text:k}),w.mode==="capture"){await P(w.rest);return}if(w.mode==="annotate"){await _(w.rest);return}if(w.mode==="checklist"){await H();return}if(w.mode==="verify"){let R=Ue(e),N=w.rest.find(D=>!D.startsWith("-")),M=N?[N]:ii(R);if(N&&!R.some(D=>D.id===N)){h({kind:"note",tone:"error",text:`No screenshot placeholder called "${N}". /screenshot list shows them all.`});return}if(M.length===0){let D=R.filter(I=>I.state==="rejected").length,X=R.filter(I=>I.state==="verified").length;h({kind:"note",tone:"info",text:D>0?`Nothing left to verify. ${D} shot${D===1?"":"s"} failed verification \u2014 re-capture with /screenshot capture --failed.`:X>0?`All ${X} captured shot${X===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:to(M.length)}),await ve(dn(e,M),{display:N?`/screenshot verify ${N}`:"/screenshot verify",quietUser:!0});let F=Ur(e,M);F.length>0&&h({kind:"note",tone:"info",text:F.join(`
595
+ `)});return}if(w.mode==="list"){if(!ke(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let R=ke(e)?.docsDir??xf,N=Bu(e,w.scope),M=Ue(e,N);if(w.picker){if(M.length===0){h({kind:"note",tone:"info",text:"No screenshot placeholders found in the docs."});return}let D=qg(M);if(D.length===0){h({kind:"note",tone:"info",text:Oa(M,{docsDir:R}).join(`
596
+ `)});let X=Se("/push","--screenshots",N),I=_t(e,{text:`\u2713 All ${M.length} screenshots are captured. ${X} saves them into the articles on Document360; /screenshot capture${N?` ${N}`:""} re-captures.`,cmd:X},`\u2713 All ${M.length} screenshots are captured. `,N);Pe(I.text,{kind:"cmd",cmd:I.cmd,reason:""});return}go({cursor:0,rows:D,title:"Screenshots \u2014 pick what to author or capture:"});return}h({kind:"note",tone:"info",text:Oa(M,{scope:N,detail:w.detail,docsDir:R}).join(`
597
+ `)}),k&&h({kind:"note",tone:"info",text:k});let F=Wu(M,N);F.key!=="done"&&se(F.cmd);return}if(w.mode==="single"){await tm(w.id);return}if(!ke(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let v=w.mode==="scope"?w.scope:void 0,b=_L(e,{scope:v}).map(R=>R.id);if(b.length===0){h({kind:"note",tone:"info",text:v?`No screenshot placeholders under ${v}.`:"No screenshot placeholders found in the docs."});return}await em(b,{setup:w.setup,scope:w.mode==="scope"?w.scope:void 0,runLine:w.mode==="scope"?[`/screenshot author ${w.scope}`,`/screenshot ${w.scope}`]:["/screenshot author --all","/screenshot --all"]});return}case"capture":{await P(y);return}case"reset":{let w=Zp(e);if(w.length===0){h({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}nr.current={repoName:Ei(e),targets:w,hadDevhints:os(Av(e))},h({kind:"note",tone:"warn",text:th(e,w).join(`
598
+ `)}),nt(Ei(e));return}default:h({kind:"note",tone:"error",text:`Unknown command: /${u} \u2014 type /help.`})}},[e,r,s,mr,Qc,h,Ve,ve,wt,Yc,nm]),Ps=re(p=>{let m=(p??g).trim();if($(""),po(null),Bt(0),m.startsWith("/")){Z.current=!1,Ae.current=!1,_e.current=null,Kt(),wo(null);let y=Bi.current.includes(m);y&&(Bi.current=[]),we(P=>y?[]:Q$(P,m))}if(!m||(Ce(!1),Ee.current=!1,(nr.current||De.current.length>0)&&h({kind:"user",text:m}),rm(m))||om(m))return;Pc.current.push(m);let u=tv(m,me.current);if(m.startsWith("/"))h({kind:"user",text:m}),B(!0),No(u).finally(()=>B(!1));else if(iO(u)){h({kind:"user",text:m});let y=aO(u);if(!y)ve(u,{display:m,quietUser:!0});else{try{lO(e,{title:y,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}ve(`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${y}". 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 "${y}" and the article path(s) you wrote.`,{display:m,quietUser:!0})}}else{let y=oy(e,u);ve(y??u,{display:m})}},[g,rm,om,No,ve]),sm=re(p=>{if(p.length>1){if(p.includes("\x1B"))return;let m=J$(p);if(Z$(m)){let u=ev(++Ge.current,m);me.current.set(u,m),T(u)}else T(m);return}T(p)},[T]),gr=Math.max(10,ft-6),im=bc(()=>yc(l.text,gr),[l.text,gr]),Jc=re(p=>f(m=>({...m,pos:Math.max(0,Math.min(m.text.length,m.pos+p))})),[]),na=re(p=>f(m=>({...m,pos:ov(yc(m.text,gr),m.pos,p)})),[gr]),Ts=re(p=>f(m=>({...m,pos:rv(yc(m.text,gr),m.pos,p)})),[gr]),t0=["\x1B[H","\x1B[1~","\x1BOH"],n0=["\x1B[F","\x1B[4~","\x1BOF"],am=re((p,m)=>m.leftArrow?(Jc(-1),!0):m.rightArrow?(Jc(1),!0):p&&t0.includes(p)?(Ts("start"),!0):p&&n0.includes(p)?(Ts("end"),!0):m.ctrl&&p==="a"?(Ts("start"),!0):m.ctrl&&p==="e"?(Ts("end"),!0):!1,[Jc,Ts]),Zc=re(()=>{if(Fe.current){if(!Fe.current.signal.aborted){let p=(ur?.verb??"work").toLowerCase(),m=ur?.unit??"article";h({kind:"note",tone:"warn",text:`\u238B Stopping the ${p} run (finishing in-flight ${m}s)\u2026`}),Fe.current.abort()}return!0}return fs.current?!1:(fs.current=!0,h({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),Tt.current?.interrupt(),!0)},[ur]);return QI((p,m)=>{if(m.ctrl&&p==="c"){if(ms.current!==null&&Date.now()-ms.current<Mv){ms.current=null,Tt.current?.close(),r();return}ms.current=Date.now(),If(!0),Ec.current&&clearTimeout(Ec.current),Ec.current=setTimeout(()=>{ms.current=null,If(!1)},Mv),S?Zc():g&&$("");return}if(vs.current.awaySince!==null&&Xe.current===null)try{let u=H$(vs.current,Date.now(),Zt(e));if(vs.current=u.memory,Kf(null),u.kind==="delta"){h({kind:"note",tone:"info",text:q$(u.delta,u.awayMs)});let y=yt(!1);y.kind==="recommend"&&$n(y.rec,{silent:!0})}else if(u.kind==="briefing"){h({kind:"note",tone:"info",text:`\u{1F4E5} ${Ti(u.delta)} arrived while you were away (${uf(u.awayMs)}).`});let y=yt(!1);y.kind==="recommend"&&$n(y.rec)}}catch{}if(Wc.current=Date.now(),!x){if(pt){if(m.return){Oi(null),_i.current=!0,W(u=>u+1),h({kind:"note",tone:"info",text:"\u25B6 Auto mode starting \u2014 esc stops it at any point, and nothing already done is undone."});return}if(p==="b"||p==="B"){Oi(null),$("/auto --budget ");return}if(m.escape){Oi(null),$o.current=!0,Xe.current=null,h({kind:"note",tone:"info",text:"Left in manual for now \u2014 nothing started. Auto mode is still on: /auto on begins the round trip when you are ready, or /auto off switches it off."}),W(u=>u+1);return}return}if(m.tab&&m.shift&&!Fn&&!wn&&!Hc){let u=ke(e);if(!u){h({kind:"note",tone:"info",text:"Set this repo up first with /init \u2014 then shift+tab switches between auto and manual."});return}let y=!yv(u);Ja(e,u,y),y&&($o.current=!1);let P=!y&&Xe.current!==null;P&&(Xe.current={...Xe.current,stopping:!0}),h({kind:"note",tone:"ok",text:P?"Manual mode \u2014 I'll finish what is running and stop there, then hand back. (shift+tab to change it back.)":`${y?"Auto mode ON":"Manual mode"} \u2014 ${Ks(y)} (shift+tab to change it back.)`}),W(_=>_+1);return}if(S){if(m.escape){if(Xe.current){$o.current=!0;let u=Xe.current;Zc(),Ss({kind:"stopped",how:"esc"},u.parked);return}Zc();return}if(m.return){let u=g.trim();if(!u)return;ko.current.push(u),Ac([...ko.current]),$("");return}if(am(p,m))return;if(m.upArrow){na(-1);return}if(m.downArrow){na(1);return}if(m.backspace||m.delete){A();return}p&&!m.ctrl&&!m.meta&&sm(p);return}if(wn){if(m.upArrow){fo(u=>u&&{...u,cursor:Math.max(0,u.cursor-1)});return}if(m.downArrow){fo(u=>u&&{...u,cursor:Math.min(Ut.length-1,u.cursor+1)});return}if(p&&/^[0-9]$/.test(p)){let u=kn(p,Ut.length);u!==null&&fo(y=>y&&{...y,cursor:u});return}if(m.return){let u=Ut[wn.cursor];fo(null);let{lines:y,changed:P,effective:_}=ri(e,u.value??"default");for(let H of y)h({kind:"note",tone:H.startsWith("\u26A0")?"warn":H.startsWith("\u2713")?"ok":"info",text:H});P&&(Ff(H=>H+1),Tt.current?.setModel(_));return}if(p==="s"){let u=Ut[wn.cursor];fo(null),Tt.current?.setModel(u.value??void 0),h({kind:"note",tone:"ok",text:`\u2713 Using ${u.label} for this session only (your saved default is unchanged).`});return}if(m.escape){fo(null);return}return}if(Gt){if(m.upArrow){or(u=>u&&{...u,cursor:Math.max(0,u.cursor-1)});return}if(m.downArrow){or(u=>u&&{...u,cursor:Math.min(u.rows.length-1,u.cursor+1)});return}if(p&&/^[0-9]$/.test(p)){let u=kn(p,Gt.rows.length);u!==null&&or(y=>y&&{...y,cursor:u});return}if(m.return||p==="s"){let u=Gt.rows[Gt.cursor];or(null),zc(u.name,m.return===!0);return}if(m.escape){or(null);return}return}if(ws){if(m.escape){Ro(null);return}if(m.leftArrow||m.tab&&m.shift){Ro(u=>u&&{tab:(u.tab-1+bt.length)%bt.length,scroll:0});return}if(m.rightArrow||m.tab){Ro(u=>u&&{tab:(u.tab+1)%bt.length,scroll:0});return}if(p&&/^[1-9]$/.test(p)&&Number(p)<=bt.length){Ro({tab:Number(p)-1,scroll:0});return}if(m.upArrow){Ro(u=>u&&{...u,scroll:Math.max(0,u.scroll-1)});return}if(m.downArrow){Ro(u=>{if(!u)return u;let y=(bt[u.tab]??bt[0]).rows.length;return{...u,scroll:Math.min(Math.max(0,y-1),u.scroll+1)}});return}return}if(qt){if(m.upArrow){rr(u=>u&&{...u,cursor:Math.max(0,u.cursor-1)});return}if(m.downArrow){rr(u=>u&&{...u,cursor:Math.min(u.rows.length-1,u.cursor+1)});return}if(p&&/^[0-9]$/.test(p)){let u=kn(p,qt.rows.length);u!==null&&rr(y=>y&&{...y,cursor:u});return}if(m.return){let u=qt.rows[qt.cursor].name;if(rr(null),!gu(e,u).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 "${u}").`});let P=!1;try{let _=lo(u);P=!!_&&!(tr(_)&&!_.refreshToken)}catch{P=!1}h({kind:"note",tone:"info",text:P?`Next: sign in to ${u} and pick your project \u2014 you're already signed in here, so it'll be quick.`:`Next: sign in to Document360 (${u}) and pick your project.`}),se("/login"),W(_=>_+1);return}if(m.escape){rr(null);return}return}if(st){if(m.upArrow){sr(u=>u&&{...u,cursor:Math.max(0,u.cursor-1)});return}if(m.downArrow){sr(u=>u&&{...u,cursor:Math.min(u.rows.length-1,u.cursor+1)});return}if(p&&/^[0-9]$/.test(p)){let u=kn(p,st.rows.length);u!==null&&sr(y=>y&&{...y,cursor:u});return}if(m.return){let u=st.rows[st.cursor],{profile:y,projectId:P}=st;sr(null),Zi(y,P,u);return}if(m.escape){sr(null);return}return}if(ut){if(m.upArrow){mo(u=>u&&{...u,cursor:Math.max(0,u.cursor-1)});return}if(m.downArrow){mo(u=>u&&{...u,cursor:Math.min(u.rows.length-1,u.cursor+1)});return}if(p&&/^[0-9]$/.test(p)){let u=kn(p,ut.rows.length);u!==null&&mo(y=>y&&{...y,cursor:u});return}if(m.return){let u=ut.rows[ut.cursor],{profile:y}=ut;mo(null),ta(y,u);return}if(m.escape){mo(null);return}return}if(dt){if(m.upArrow){lr(u=>u&&{...u,cursor:Math.max(0,u.cursor-1)});return}if(m.downArrow){lr(u=>u&&{...u,cursor:Math.min(u.rows.length-1,u.cursor+1)});return}if(p===" "){lr(u=>u&&{...u,rows:u.rows.map((y,P)=>P===u.cursor?{...y,checked:!y.checked}:y)});return}if(m.return){let u=dt.rows.filter(y=>y.checked).map(y=>y.path);if(lr(null),u.length===0){h({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}md(e,u),h({kind:"note",tone:"ok",text:`\u2713 Scoped to ${u.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let y of u)h({kind:"note",tone:"info",text:` ${y}`});h({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(m.escape){lr(null);return}return}if(gt){if(m.upArrow){yo(u=>u&&{...u,cursor:Math.max(0,u.cursor-1)});return}if(m.downArrow){yo(u=>u&&{...u,cursor:Math.min(u.rows.length-1,u.cursor+1)});return}if(p&&/^[0-9]$/.test(p)){let u=kn(p,gt.rows.length);u!==null&&yo(y=>y&&{...y,cursor:u});return}if(m.return){let u=gt.rows[gt.cursor],y=gt.run;yo(null),y(u.token);return}if(m.escape){yo(null);return}return}if(At){if(m.upArrow){ir(u=>u&&{...u,cursor:Math.max(0,u.cursor-1)});return}if(m.downArrow){ir(u=>u&&{...u,cursor:Math.min(u.rows.length-1,u.cursor+1)});return}if(p&&/^[0-9]$/.test(p)){let u=kn(p,At.rows.length);u!==null&&ir(y=>y&&{...y,cursor:u});return}if(m.return){let u=At.rows[At.cursor],y=At.conflicts;ir(null),u.conflict?Qc(u.paths[0]):u.kind==="article"?Yc(u.paths[0]):wt(u.paths,u.kind==="all"?y:0);return}if(m.escape){ir(null);return}return}if(Vt){if(m.upArrow){ar(u=>u&&{...u,cursor:Math.max(0,u.cursor-1)});return}if(m.downArrow){ar(u=>u&&{...u,cursor:Math.min(u.rows.length,u.cursor+1)});return}if(p&&/^[0-9]$/.test(p)){let u=kn(p,Vt.rows.length+1);u!==null&&ar(y=>y&&{...y,cursor:u});return}if(m.return){let{cursor:u,rows:y,opts:P}=Vt;ar(null);let _=u===0?y:[y[u-1]];Jf(_,P);return}if(m.escape){ar(null),h({kind:"note",tone:"info",text:"Left as drafts \u2014 nothing changed. /publish when they have been signed off."});return}return}if(Et){let{rows:u}=Et;if(m.upArrow){bn(y=>y&&{...y,cursor:Math.max(0,y.cursor-1)});return}if(m.downArrow){bn(y=>y&&{...y,cursor:Math.min(u.length-1,y.cursor+1)});return}if(p&&/^[0-9]$/.test(p)){let y=sf(Ef.current,Number(p),u.length-1);Ef.current=y.memory,y.index!==null&&bn(P=>P&&{...P,cursor:y.index+1});return}if(p==="a"||p==="A"){bn(y=>y&&{...y,cursor:0});return}if(m.return){let y=u[Et.cursor],{groups:P,resolve:_,report:H}=Et;if(bn(null),y.kind==="all"){Vc(P,{resolve:_,report:H});return}hr(Al(y.group,{width:tt()})),hs({group:y.group,cursor:0,fromList:!0,resolve:_,rest:P.filter(w=>w.articleId!==y.group.articleId),report:H});return}if(m.escape){bn(null),se("/comments");return}return}if(at){let u=()=>{let{rest:y,group:P,fromList:_,resolve:H,report:w}=at;if(hs(null),!_||!w){se("/comments");return}let k=[P,...y].sort((v,b)=>v.category.localeCompare(b.category)||v.title.localeCompare(b.title));bn({cursor:0,rows:El(k),groups:k,resolve:H,report:w})};if(m.upArrow||m.downArrow){hs(y=>y&&{...y,cursor:y.cursor===0?1:0});return}if(p==="y"||p==="Y"||m.return&&at.cursor===0){let{group:y,resolve:P,rest:_,report:H}=at;hs(null),Vc([y],{resolve:P,rest:_,...H?{report:H}:{}});return}if(p==="b"||p==="B"||m.escape||m.return){u();return}return}if(Yt){if(m.upArrow){go(u=>u&&{...u,cursor:Math.max(0,u.cursor-1)});return}if(m.downArrow){go(u=>u&&{...u,cursor:Math.min(u.rows.length-1,u.cursor+1)});return}if(p&&/^[0-9]$/.test(p)){let u=kn(p,Yt.rows.length);u!==null&&go(y=>y&&{...y,cursor:u});return}if(m.return){let u=Yt.rows[Yt.cursor];go(null),u.action==="capture"?Cs(u.ids,{runLine:u.kind==="all"?["/screenshot capture --all","/capture --all"]:void 0}):u.action==="annotate"?Ji(u.ids,{verifiedBefore:new Set(Ue(e).filter(y=>y.state==="verified").map(y=>y.id))}):u.kind==="shot"?tm(u.ids[0]):em(u.ids,{setup:!0,runLine:u.kind==="all"?["/screenshot author --all","/screenshot --all"]:void 0});return}if(m.escape){go(null);return}return}if(Nt){if(m.escape){bo(null);return}if(m.upArrow){bo(u=>u&&{...u,cursor:Math.max(0,u.cursor-1)});return}if(m.downArrow){bo(u=>u&&{...u,cursor:Math.min(Math.max(0,Ki.length-1),u.cursor+1)});return}if(m.return){let u=Ki[Nt.cursor];if(u){bo(null);try{h({kind:"preview",name:Ei(u),text:Uv(kc(Ni(e,u),"utf8"))})}catch(y){h({kind:"note",tone:"error",text:`Could not read ${u}: ${y.message}`})}}return}if(m.backspace||m.delete){bo(u=>u&&{...u,query:u.query.slice(0,-1),cursor:0});return}if(p&&!m.ctrl&&!m.meta&&p.length===1){bo(u=>u&&{...u,query:u.query+p,cursor:0});return}return}if(Dt){if(m.escape){xo(null);return}if(m.upArrow){xo(u=>u&&{...u,cursor:Math.max(0,u.cursor-1)});return}if(m.downArrow){xo(u=>u&&{...u,cursor:Math.min(Math.max(0,zi.length-1),u.cursor+1)});return}if(m.return){let u=zi[Dt.cursor];if(u){xo(null),Ve(u.uuid),gn.current={uuid:u.uuid,firstPrompt:u.firstPrompt,titleFired:!0},ho(u.name),ff(u.uuid),ct.current=[],ht.current={printed:[],armed:[],printedAt:dr.current};let y=af(e,u.uuid);for(let P of y)h(P);h({kind:"note",tone:"ok",text:y.length?`Resumed "${u.name}" \u2014 restored ${y.length} message(s); continue where you left off.`:`Resumed "${u.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(m.backspace||m.delete){xo(u=>u&&{...u,query:u.query.slice(0,-1),cursor:0});return}if(p&&!m.ctrl&&!m.meta&&p.length===1){xo(u=>u&&{...u,query:u.query+p,cursor:0});return}return}if(m.tab&&!g&&ue){$(ue),Kt();return}if(!g&&ge.length>0&&!Ee.current&&p&&/^[1-9]$/.test(p)){let u=ge[Number(p)-1];if(u){$(ao(u));return}}if(!g&&ge.length===0&&!Ee.current&&ht.current.armed.length>0&&p&&/^[1-9]$/.test(p)){let u=ht.current.armed[Number(p)-1];if(u){$(u);return}}if(!g&&(qi||Po)&&p==="c"&&!m.ctrl&&!m.meta&&!m.return&&!m.tab){let u=qi!=null;nf(qi??Po).then(P=>{h({kind:"note",tone:P?"ok":"warn",text:P?u?"\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.":u?"Couldn't reach your clipboard \u2014 select the feedback above and copy it manually.":"Couldn't reach your clipboard \u2014 select the prompt above and copy it manually."}),P&&u&&Uc(null),P&&!u&&Bf(!0)});return}if(!am(p,m)){if(Hc){if(m.upArrow){Bt(u=>Math.max(0,u-1));return}if(m.downArrow){Bt(u=>Math.min(Rn.length-1,u+1));return}if(m.tab){$("/"+(Rn[ds]?.name??"")+" "),Bt(0);return}if(m.return){let u=Rn[ds];if(u){let y=g.trim().slice(1).split(/\s+/).slice(1).join(" ");if(Hy(u.usage)&&!y){$("/"+u.name+" "),Bt(0);return}Ps("/"+u.name+(y?" "+y:""));return}}}else{if(!g&&ge.length>0&&!Ee.current&&(m.upArrow||m.downArrow)){if(m.downArrow){mn(u=>u===null?0:Math.min(ge.length-1,u+1));return}if(fn!==null){mn(u=>u===null||u===0?null:u-1);return}}if(m.upArrow){if(g!==""&&_n===null){na(-1);return}let u=Pc.current;if(!u.length)return;let y=_n===null?u.length-1:Math.max(0,_n-1);po(y),$(u[y]??"");return}if(m.downArrow){if(g!==""&&_n===null){na(1);return}let u=Pc.current;if(_n===null)return;let y=_n+1;y>=u.length?(po(null),$("")):(po(y),$(u[y]??""));return}}if(m.return){if(fn!==null&&!g&&ge[fn]){let u=ao(ge[fn]);mn(null),Ps(u);return}Ps();return}if(m.backspace||m.delete){A();return}if(m.escape){Xe.current&&($o.current=!0,Ss({kind:"stopped",how:"esc"},Xe.current.parked)),$(""),Bt(0),Kt(),we([]),wo(null),mn(null),Z.current=!0;return}p&&!m.ctrl&&!m.meta&&sm(p)}}}),it(()=>{if(S||x)return;let p=ko.current.shift();p!==void 0&&(Ac([...ko.current]),Ps(p))},[S,x,Ps]),he(je,{flexDirection:"column",width:ft,children:[qc!==null&&he(je,{marginTop:1,flexDirection:"column",children:[qc.truncated&&V(z,{dimColor:!0,children:"\u2026"}),V(z,{children:qc.text})]}),cr?V(kO,{step:cr.step,cmd:cr.cmd,startedAt:cr.startedAt,spentUsd:Math.max(cr.spentUsd,jt-(Xe.current?.stepStartedSpend??jt)),budgetUsd:cr.budgetUsd}):null,S&&ur?V(xO,{p:ur}):null,Of?V($O,{text:Of}):S&&!ur?V(bO,{startTime:Pt.current,chars:Ii}):null,V(je,{borderStyle:"round",borderColor:zf.prod?"yellow":ae,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:g?im.map((p,m)=>{let u=l.text.slice(p.start,p.end),y=m===wc(im,l.pos),P=Math.min(l.pos,p.end)-p.start;return he(z,{children:[V(z,{color:ae,children:m===0?"> ":" "}),y?he(er,{children:[u.slice(0,P),V(is,{ch:u[P]??" "}),u.slice(P+1)]}):u||" "]},`${m}-${p.start}`)}):he(z,{children:[V(z,{color:ae,children:"> "}),Fn?V(is,{ch:" "}):Re&&!S?he(er,{children:[V(is,{ch:Re[0],dim:!0}),V(z,{color:"gray",children:Re.slice(1)})]}):ue&&!S?he(er,{children:[V(is,{ch:ue[0],dim:!0}),V(z,{color:"gray",children:ue.slice(1)}),V(z,{dimColor:!0,children:" (tab)"})]}):(Bc.isSetup||!on)&&!S?he(er,{children:[V(is,{ch:Bc.text[0],dim:!0}),V(z,{color:"gray",children:Bc.text.slice(1)})]}):V(is,{ch:" "})]})}),jf.length>0&&V(je,{flexDirection:"column",paddingX:1,children:jf.map((p,m)=>V(z,{color:"gray",children:`\u29D7 queued: ${p}`},`${m}-${p.slice(0,24)}`))}),pt?he(je,{flexDirection:"column",paddingX:1,children:[V(z,{color:ae,bold:!0,children:"Auto mode \u2014 I run each step myself"}),V(z,{color:"gray",children:` first step ${pt.firstCmd}${pt.scale?` \u2014 ${pt.scale}`:""}`}),pt.upcoming.length>0?he(er,{children:[V(z,{color:"gray",children:" as things stand, after that:"}),pt.upcoming.map(p=>V(z,{color:"gray",children:` ${p.cmd}${p.scale?` ${p.scale}`:""}`},p.cmd)),V(z,{color:"gray",children:" each step changes what the next one finds, so this is not a total"})]}):V(z,{color:"gray",children:" I work down the ladder from there \u2014 reviewing, checking style, saving and going live"}),[pt.scale,...pt.upcoming.map(p=>p.scale)].every(p=>!p?.includes("$"))?V(z,{color:"gray",children:" no cost estimate yet \u2014 this repo has not finished a run for me to measure"}):null,V(z,{color:"gray",children:` spending limit ${Ke(pt.budgetUsd)} \xB7 I stop and report if it is reached`}),V(z,{color:"gray",children:" screenshots are not part of an automatic run"}),pt.overBudget?V(z,{color:"yellow",children:`\u26A0 That is more than your ${Ke(pt.budgetUsd)} limit. I will stop partway and report what is left.`}):null,V(z,{dimColor:!0,children:pt.overBudget?"b raise the limit \xB7 enter start anyway \xB7 esc stay in manual for now":"enter start \xB7 b change the limit \xB7 esc stay in manual for now"})]}):ws?V(Y$,{tab:ws.tab,scroll:ws.scroll,rows:Zv,width:ft,version:o,engineVersion:Wv}):wn?he(je,{flexDirection:"column",paddingX:1,children:[V(z,{color:ae,bold:!0,children:"Select model"}),V(z,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),Ut.map((p,m)=>he(z,{color:m===wn.cursor?ae:void 0,children:[m===wn.cursor?"\u276F ":" ",`${m+1}. ${p.label}${m===wn.current?" \u2714":""}`.padEnd(16),V(z,{color:"gray",children:` ${p.desc}`})]},p.label)),V(z,{dimColor:!0,children:Rt({verb:"set as default",rows:Ut.length,extra:["s this session only"]})})]}):Gt?he(je,{flexDirection:"column",paddingX:1,children:[V(z,{color:ae,bold:!0,children:"Switch connection profile"}),V(Ln,{rows:Gt.rows,cursor:Gt.cursor,cap:sn,render:(p,m,u)=>he(z,{color:u?ae:void 0,children:[u?"\u276F ":" ",`${m+1}. ${p.name}${m===Gt.current?" \u2714":""}`.padEnd(20),V(z,{color:"gray",children:` ${p.env} \xB7 ${p.who??"not signed in"}`}),p.prod?V(z,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},p.name)}),V(z,{dimColor:!0,children:Rt({verb:"switch (saved as default)",rows:Gt.rows.length,extra:["s this session only"]})})]}):qt?he(je,{flexDirection:"column",paddingX:1,children:[V(z,{color:ae,bold:!0,children:"Pick your Document360 environment"}),V(Ln,{rows:qt.rows,cursor:qt.cursor,cap:sn,render:(p,m,u)=>he(z,{color:u?ae:void 0,children:[u?"\u276F ":" ",`${m+1}. ${p.name}`.padEnd(16),V(z,{color:"gray",children:` ${p.apiUrl}`}),p.note?V(z,{color:"yellow",children:` \u26A0 ${p.note}`}):null]},p.name)}),V(z,{dimColor:!0,children:Rt({verb:"use it",rows:qt.rows.length})})]}):st?he(je,{flexDirection:"column",paddingX:1,children:[V(z,{color:ae,bold:!0,children:"Switch workspace"}),V(z,{dimColor:!0,children:`environment ${st.environment} \xB7 project ${st.projectName??`${st.projectId.slice(0,8)}\u2026`}`}),V(Ln,{rows:st.rows,cursor:st.cursor,cap:sn,render:(p,m,u)=>he(z,{color:u?ae:void 0,children:[u?"\u276F ":" ",`${m+1}. ${p.name}${m===st.current?" \u2714":""}`.padEnd(30),V(z,{color:"gray",children:p.type?` ${p.type}`:""})]},p.id)}),V(z,{dimColor:!0,children:Rt({verb:"switch",rows:st.rows.length})})]}):ut?he(je,{flexDirection:"column",paddingX:1,children:[V(z,{color:ae,bold:!0,children:"Choose project"}),V(z,{dimColor:!0,children:`environment ${ut.environment}`}),V(Ln,{rows:ut.rows,cursor:ut.cursor,cap:sn,render:(p,m,u)=>he(z,{color:u?ae:void 0,children:[u?"\u276F ":" ",`${m+1}. ${p.name}${m===ut.current?" \u2714":""}`.padEnd(30),V(z,{color:"gray",children:p.sub?` ${p.sub}`:""})]},p.id)}),V(z,{dimColor:!0,children:Rt({verb:"switch",rows:ut.rows.length})})]}):dt?(()=>{let m=Math.min(Math.max(0,dt.cursor-Math.floor(7)),Math.max(0,dt.rows.length-14)),u=dt.rows.slice(m,m+14),y=dt.rows.filter(P=>P.checked).length;return he(je,{flexDirection:"column",paddingX:1,children:[V(z,{color:ae,bold:!0,children:`Which folders back the user docs? (${y} selected of ${dt.rows.length})`}),m>0?V(z,{dimColor:!0,children:` \u2191 ${m} more`}):null,u.map((P,_)=>{let H=m+_;return he(z,{color:H===dt.cursor?ae:void 0,children:[H===dt.cursor?"\u276F ":" ",P.checked?"\u25C9 ":"\u25CB ",P.path.padEnd(Math.min(48,ft-34)),V(z,{color:"gray",children:Za(P)})]},P.path)}),m+14<dt.rows.length?V(z,{dimColor:!0,children:` \u2193 ${dt.rows.length-m-14} more`}):null,V(z,{dimColor:!0,children:Rt({verb:"save",multi:!0})})]})})():gt?he(je,{flexDirection:"column",paddingX:1,children:[V(z,{color:ae,bold:!0,children:gt.title??"Which category? (pick one to scope to)"}),V(Ln,{rows:gt.rows,cursor:gt.cursor,cap:sn,render:(p,m,u)=>he(z,{color:u?ae:void 0,children:[u?"\u276F ":" ",`${`${m+1}.`.padEnd(3)} ${p.label} (${p.count})`.padEnd(Math.min(44,Math.max(20,ft-24))),V(z,{color:"gray",children:` ${p.token}`})]},p.token)}),V(z,{dimColor:!0,children:Rt({verb:"choose it",rows:gt.rows.length})})]}):At?he(je,{flexDirection:"column",paddingX:1,children:[V(z,{color:ae,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),V(Ln,{rows:At.rows,cursor:At.cursor,cap:sn,render:(p,m,u)=>he(z,{color:u?ae:void 0,bold:p.kind==="category"&&!u,children:[u?"\u276F ":" ",`${p.indent?" ":" "}${`${m+1}.`.padEnd(3)} ${p.label}`.padEnd(Math.min(56,ft-24)),p.note?V(z,{color:"gray",children:` ${p.note}`}):null]},`${p.kind}:${p.paths.join(",")}`)}),V(z,{dimColor:!0,children:Rt({verb:"push as drafts",rows:At.rows.length})})]}):Vt?he(je,{flexDirection:"column",paddingX:1,children:[V(z,{color:ae,bold:!0,children:"Publish live to your readers \u2014 this is what they will see:"}),V(Ln,{rows:[{path:"",articleId:"",label:`Publish all ${Vt.rows.length} live`,version:void 0},...Vt.rows],cursor:Vt.cursor,cap:sn,render:(p,m,u)=>he(z,{color:u?ae:void 0,bold:m===0&&!u,children:[u?"\u276F ":" ",` ${`${m+1}.`.padEnd(3)} ${p.label}`.padEnd(Math.min(56,ft-24)),m>0?V(z,{color:"gray",children:` ${p.version?`draft v${p.version} \u2192 live`:"draft \u2192 live"}`}):null]},`${m}:${p.path||"all"}`)}),V(z,{dimColor:!0,children:Rt({verb:"publish live",cancel:"leave as drafts",rows:Vt.rows.length+1})})]}):Et?he(je,{flexDirection:"column",paddingX:1,children:[V(z,{color:ae,bold:!0,children:"Which comments do you want to look at?"}),V(Ln,{rows:Et.rows,cursor:Et.cursor,cap:sn,render:(p,m,u)=>he(z,{color:u?ae:void 0,bold:p.kind==="all"&&!u,children:[u?"\u276F ":" ",`${(p.kind==="all"?"":`${p.n}.`).padEnd(4)}${p.label}`.padEnd(Math.min(56,Math.max(20,ft-24))),p.kind==="article"?V(z,{color:"gray",children:p.note}):null]},p.kind==="all"?"all":p.group.articleId)}),V(z,{dimColor:!0,children:Rt({verb:"open it",cancel:"close",rows:Et.rows.length-1})}),Et.resolve?V(z,{dimColor:!0,children:"--resolve is on: threads you answer will be closed as well as replied to"}):null]}):at?he(je,{flexDirection:"column",paddingX:1,children:[V(z,{color:ae,bold:!0,children:`${at.group.title} \u2014 ${at.group.threads.length} comment${at.group.threads.length===1?"":"s"}`}),he(z,{color:at.cursor===0?ae:void 0,children:[at.cursor===0?"\u276F ":" ",at.resolve?"Yes \u2014 fix them, push the draft, reply and resolve":"Yes \u2014 fix them, push the draft to Document360, then reply"]}),he(z,{color:at.cursor===1?ae:void 0,children:[at.cursor===1?"\u276F ":" ",at.fromList?"No \u2014 back to the list":"No \u2014 leave them for now"]}),V(z,{dimColor:!0,children:Rt({verb:"open it",cancel:"go back",extra:["y answer"]})})]}):Yt?he(je,{flexDirection:"column",paddingX:1,children:[V(z,{color:ae,bold:!0,children:Yt.title}),(()=>{let{rows:p,cursor:m}=Yt,u=cc(p.length,m,sn),y=u.start,P=p.slice(u.start,u.end),_=`${p.length}.`.length+1,H=Gg(p,Math.max(20,ft-4-_));return he(er,{children:[y>0?V(z,{color:"gray",children:` \u2026 ${y} more above`}):null,P.map((w,k)=>{let v=y+k,b=v===m,R=H[v];return he(z,{color:b?ae:void 0,bold:(w.kind==="all"||w.kind==="category")&&!b,children:[b?"\u276F ":" ",`${v+1}.`.padEnd(_),R.head,R.note?V(z,{color:"gray",children:R.note}):null]},`${w.action}:${w.kind}:${w.ids.join(",")}`)}),u.below>0?V(z,{color:"gray",children:` \u2026 ${u.below} more below`}):null]})})(),V(z,{dimColor:!0,children:Rt({verb:"run it",rows:Yt.rows.length})})]}):Nt?he(je,{flexDirection:"column",paddingX:1,children:[V(z,{color:ae,bold:!0,children:`Preview article${Nt.query?` \u2014 filter: ${Nt.query}`:" (type to filter)"}`}),Ki.length===0?V(z,{color:"gray",children:"no articles match"}):Ki.map((p,m)=>he(z,{color:m===Nt.cursor?ae:void 0,children:[m===Nt.cursor?"\u276F ":" ",p]},p)),V(z,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):Dt?he(je,{flexDirection:"column",paddingX:1,children:[V(z,{color:ae,bold:!0,children:`Resume session${Dt.query?` \u2014 filter: ${Dt.query}`:" (type to filter)"}`}),zi.length===0?V(z,{color:"gray",children:"no sessions match"}):zi.map((p,m)=>he(z,{color:m===Dt.cursor?ae:void 0,children:[m===Dt.cursor?"\u276F ":" ",p.name.slice(0,28).padEnd(30),V(z,{color:m===Dt.cursor?ae:"gray",children:p.firstPrompt.slice(0,Math.max(10,ft-40))})]},p.uuid)),V(z,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Hc?he(je,{flexDirection:"column",children:[Ao>0?V(z,{dimColor:!0,children:` \u22EF ${Ao} more above`}):null,Gc.map((p,m)=>{let u=Ao+m,y=p.name==="model"&&Ic?`${p.desc} (currently ${Ic})`:p.desc,P=Math.max(20,ft-4),_=p.usage.length>P?`${p.usage.slice(0,P-1)}\u2026`:p.usage,H=P-Math.max(_.length,22)-1,w=H<=1?"":y.length>H?`${y.slice(0,H-1)}\u2026`:y;return he(z,{color:u===Yi?ae:void 0,children:[u===Yi?"\u276F ":" ",_.padEnd(22)," ",V(z,{color:u===Yi?ae:"gray",children:w})]},p.name)}),Ao+Gc.length<Rn.length?V(z,{dimColor:!0,children:` \u22EF ${Rn.length-Ao-Gc.length} more below`}):null,V(z,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!S&&!g&&ge.length>0?he(je,{flexDirection:"column",paddingX:1,children:[Df?V(z,{color:ae,children:Df}):null,V(Ln,{rows:ge,cursor:fn??0,cap:sn,render:(p,m)=>{let u=m===fn,y=ao(p),P=y.slice(0,Math.max(20,ft-7)),_=ft-P.length-9,H=_>=12?(X$(p)??Wy(y)).slice(0,_):"";return he(z,{color:u?ae:void 0,children:[u?"\u276F ":" ",V(z,{color:ae,children:m+1})," ",P,H?V(z,{color:u?ae:void 0,dimColor:!u,children:` \u2014 ${H}`}):null]},y)}}),V(z,{dimColor:!0,children:`\u2191\u2193 choose \xB7 enter run \xB7 1-${ge.length} fill \xB7 esc cancel`})]}):V(je,{paddingX:1,children:he(z,{color:"gray",children:[zf.prod?"\u26A0 PRODUCTION \xB7 ":"",V(z,{color:bs?ae:void 0,children:bs?"\u23F5\u23F5 auto":"\u23F5 manual"}),` \xB7 /help \xB7 ${Ic??"model n/a"}${t.kind==="api"?jt>0?` \xB7 session ${$t(jt)}`:"":Mf>0?` \xB7 ${Or(Mf)}`:""} \xB7 \u2191 history \xB7 shift+tab mode \xB7 ${Kv?"press ctrl+c again to exit":"ctrl+c twice to exit"}`]})})]})}oe();import{jsx as PO}from"react/jsx-runtime";async function Hv(e=process.cwd(),t="auto",n,o="0.0.0"){let r=CO(t);r.kind==="none"&&(console.error(""),console.error(L("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${ee("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${ee("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=SO(PO(Bv,{cwd:e,auth:r,profileName:n,version:o}),{exitOnCtrlC:!1});await s(),await jl(),process.stdout.write(`
599
+ `),process.exit(0)}oe();import{writeCrashLog as Rf,isBenignTransportError as TO}from"document360-engine";var Gv=!1;function AO(e=process.stdout){return e.destroyed===!0||e.writable===!1}function Sf(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function qv(e){if(Gv)return;Gv=!0;let t=(n,o)=>{if(TO(o)){Rf({kind:n,level:"transport",message:Sf(o),stack:o instanceof Error?o.stack:void 0,detail:e}),AO()&&(Rf({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=Rf({kind:n,level:"fatal",message:Sf(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
600
+ `+L(`\u2717 d360-writer crashed: ${Sf(o)}`)+`
599
601
  `),r&&process.stderr.write(d(` Crash details: ${r}`)+`
600
602
  `+d(" Run: d360-writer logs")+`
601
- `),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var mO=hO(import.meta.url),bc=mO("../package.json");Lv("d360-writer");var tn=new pO;function kf(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}tn.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=>{kf(e),await na({profile:e.profile,manual:e.manual})});tn.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=>{kf(e),await mm({profile:e.profile,allProjects:e.allProjects})});tn.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{kf(e),await fm({profile:e.profile})});var $f=tn.command("profile").description("Manage connection profiles for the current repo");$f.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>oa(process.cwd()));$f.command("use <name>").description("Set the default profile for this repo").action(e=>ra(process.cwd(),e));$f.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>sa(process.cwd(),e));var Ov=tn.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");Ov.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>kr(process.cwd(),e.profile));Ov.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await am(process.cwd(),e,t.profile)});var _v=tn.command("project").description("Choose the Document360 project for this repo (active profile's identity)");_v.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>ea(process.cwd(),e.profile));_v.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await cm(process.cwd(),e,t.profile)});tn.command("init").description("Scaffold .d360-writer/config.json for this repo (interactive)").action(async()=>{let{initCommand:e}=await Promise.resolve().then(()=>(fa(),Qm));await e()});tn.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(()=>nu());tn.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(()=>(ml(),Pw)),n=await t(process.cwd(),bc.version);for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});tn.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(bc.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(fO.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 vm(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 o$(e.cwd,e.auth,e.profile,bc.version):await jv(e.cwd,e.auth,e.profile,bc.version)});tn.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
603
+ `),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var jO=NO(import.meta.url),Sc=jO("../package.json");qv("d360-writer");var nn=new EO;function Cf(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}nn.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=>{Cf(e),await aa({profile:e.profile,manual:e.manual})});nn.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=>{Cf(e),await vm({profile:e.profile,allProjects:e.allProjects})});nn.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Cf(e),await $m({profile:e.profile})});var Pf=nn.command("profile").description("Manage connection profiles for the current repo");Pf.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>la(process.cwd()));Pf.command("use <name>").description("Set the default profile for this repo").action(e=>ca(process.cwd(),e));Pf.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>ua(process.cwd(),e));var Vv=nn.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");Vv.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>br(process.cwd(),e.profile));Vv.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await fm(process.cwd(),e,t.profile)});var Yv=nn.command("project").description("Choose the Document360 project for this repo (active profile's identity)");Yv.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>sa(process.cwd(),e.profile));Yv.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await gm(process.cwd(),e,t.profile)});nn.command("init").description("Scaffold .d360-writer/config.json for this repo (interactive)").action(async()=>{let{initCommand:e}=await Promise.resolve().then(()=>(ba(),rg));await e()});nn.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(()=>au());nn.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(()=>(kl(),Iw)),n=await t(process.cwd(),Sc.version);for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});nn.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(Sc.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(DO.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 Am(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 p$(e.cwd,e.auth,e.profile,Sc.version):await Hv(e.cwd,e.auth,e.profile,Sc.version)});nn.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});