document360-writer 0.5.276 → 0.5.277
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.
- package/dist/cli.js +215 -215
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var x$=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 ef=(e,t)=>{for(var n in t)x$(e,n,{get:t[n],enumerable:!0})};import Pn from"picocolors";var ae,R$,S$,C$,tf,hs,m,_,V,Y,Z,xe,qe,me,se=ps(()=>{"use strict";ae="#7f56d9",[R$,S$,C$]=[127,86,217],tf=e=>Pn.isColorSupported?`\x1B[38;2;${R$};${S$};${C$}m${e}\x1B[39m`:e,hs=e=>Pn.bold(tf(e)),m=e=>Pn.dim(e),_=e=>Pn.red(e),V=e=>Pn.yellow(e),Y=e=>Pn.green(e),Z=tf,xe=e=>Pn.gray(e),qe=e=>Pn.bold(e),me=(e,t)=>`${e} ${t}`});import{existsSync as sr,writeFileSync as En,readFileSync as Cv,readdirSync as Pv}from"node:fs";import{join as Sf}from"node:path";import{devHintsGuidePath as Gi,hintsDir as Cf,hooksDir as Pf,architectureDir as Df,messagesDir as Pc,creatorNotesPath as Tf,devhintsStatePath as Nf,directivesPath as Af,DIRECTIVES_HEADER as Tv,roadmapPath as Ef,ROADMAP_HEADER as Av,ensureDir as ws,writeMessage as Ev,listOpenForDev as Dv,stampDone as Nv}from"document360-engine";function jf(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
|
|
3
3
|
|
|
4
4
|
<!-- devhints script v${Oe} \xB7 maintained by document360-writer (/devhints). -->
|
|
5
5
|
|
|
@@ -235,7 +235,7 @@ do it**:
|
|
|
235
235
|
**Do NOT write or action the documentation yourself** \u2014 same boundary as Part 2. Writing the article is the
|
|
236
236
|
docs agent's job; it actions open directives on its next \`/catch-up\` (as drafts) and flips each to \`[done]\`
|
|
237
237
|
with the article it wrote. You are only the relay so the ask is captured durably and travels via git.
|
|
238
|
-
`}function
|
|
238
|
+
`}function Iv(){return`# Creator notes (optional \u2014 for the docs agent and the builder)
|
|
239
239
|
|
|
240
240
|
<!-- The ORIGINAL CREATOR's context. Most repos leave this empty \u2014 that's fine.
|
|
241
241
|
The builder agent reads this FIRST and treats it as authoritative when writing the architecture
|
|
@@ -249,12 +249,12 @@ Anything only a human knows that would help document this product. For example:
|
|
|
249
249
|
- Gotchas or non-obvious behavior.
|
|
250
250
|
|
|
251
251
|
(Replace these examples with your notes, or leave the file as-is to skip \u2014 it's optional.)
|
|
252
|
-
`}function
|
|
253
|
-
`)}
|
|
254
|
-
`)}function
|
|
255
|
-
`)}function mn(e){try{return
|
|
256
|
-
`)}),n.notifiedBuilder=!0)}}catch{}return n}function
|
|
257
|
-
`)}function
|
|
252
|
+
`}function ar(e){ws(Cf(e)),ws(Df(e)),ws(Pc(e));for(let n of[Cf(e),Pc(e)]){let o=Sf(n,".gitkeep");sr(o)||En(o,`# Keeps this document360-writer inbox tracked in git even when empty.
|
|
253
|
+
`)}sr(Tf(e))||En(Tf(e),Iv()),sr(Af(e))||En(Af(e),Tv),sr(Ef(e))||En(Ef(e),Av),En(Gi(e),jf()),ws(Pf(e)),En(Sf(Pf(e),"open-questions.mjs"),jv);let t=Gt(e);return Lf(e,new Date().toISOString()),t}async function If(e,t){for(let n of lr(ar(t.cwd)))console.log(n);return{kind:"continue"}}function fo(){return[`This is document360-writer's dev hand-off setup (v${Oe}).`,'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": ${Oe},`,' "completedAt": "<UTC now>", "completedCommit": "<current HEAD short sha>"} (preserve any other keys'," already in the file, e.g. emittedAt). Include this file in the commit from step 3.","8. Finish with a RECEIPT of what this run actually changed, then the right next step. Two parts.",""," (a) The receipt. A heading line, then one short bullet per thing that CHANGED \u2014 omit any bullet"," that did not happen, so a run that changed little stays three lines rather than ten. Report"," OUTCOMES, not the steps you took. Cover, where applicable: the protocol version you moved to; the"," architecture brief (created / N files updated / unchanged); how many docs questions you answered"," (and how many were `[discovery]`); how many hints you dropped \u2014 and when none, add one clause",' saying WHY, so "0 hints" reads as a judgement rather than an omission; whether you added to'," CREATOR-NOTES.md; whether you wired the session-start hook; and the commit you pushed. Shape:"," \u2705 Hand-off refreshed (protocol v11 \u2192 v12)"," \u2022 architecture brief: 2 files updated"," \u2022 answered 3 docs questions (1 [discovery])"," \u2022 dropped 0 hints \u2014 only internal test anchors changed"," \u2022 committed + pushed: <short sha>",' Say "\u2705 Setup complete" instead when this was the first-time setup (no brief existed before).',""," (b) The next step \u2014 chosen by what you are actually HANDING OVER. Do not print a command in every"," case, and never invent one to look helpful:"," \u2022 You answered a question, dropped a hint, or relayed an owner directive \u2192 the docs agent has a"," queue to fold in. Print, fenced on its own line so it copies cleanly:"," ```"," /catch-up"," ```"," \u2022 The docs folder configured in `.d360-writer/config.json` (default `.d360-writer/user-docs/`) is"," absent or empty \u2192 this repo has no docs yet, so it is a cold start:"," ```"," write the docs for this repo"," ```"," \u2022 You handed over NOTHING (no answers, no hints, no directives) and docs already exist \u2192 print NO",' command. Say: "Nothing new to hand over. Switch back to the document360-writer terminal \u2014 it',' will show you where things stand." The docs agent picks its own next action from the whole'," picture (its documentation campaign, coverage gaps, what is still unpublished); a command"," guessed from your side would override one it already knows to be better.",' When you DO print a block, precede it with "Back in the document360-writer terminal, paste this:"',' \u2014 or "Now switch to the document360-writer terminal and paste this:" on first-time setup.'].join(`
|
|
254
|
+
`)}function Ac(e){try{let t=Cv(Nf(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function Lf(e,t){let o={...Ac(e)??{},emittedVersion:Oe,emittedAt:t};En(Nf(e),`${JSON.stringify(o,null,2)}
|
|
255
|
+
`)}function mn(e){try{return Pv(Df(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function Gt(e){let n=Ac(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<Oe?"stale":"current",completedVersion:n}}function Lv(e){let t=new RegExp(`${Tc.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(\\d+)\\)`).exec(e);return t?Number(t[1]):null}function qi(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,supersededRequests:[],toVersion:Oe};try{if(!sr(Gi(e)))return n;let o=Ac(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;if(Oe>r&&(ws(Pc(e)),En(Gi(e),jf()),Lf(e,t),n.guideRefreshed=!0),Oe>s){let i=Dv(e).filter(l=>l.kind==="request"&&l.subject.startsWith(Tc)),a=i.filter(l=>(Lv(l.subject)??Oe)>=Oe);for(let l of i.filter(d=>!a.includes(d)))Nv(e,l.file,{doneAt:t,answeredBy:"docs"}),n.supersededRequests.push(l.subject);a.length===0&&(Ev(e,{id:`onb${Oe}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${Tc}${Oe})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${Oe}${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:","",fo()].join(`
|
|
256
|
+
`)}),n.notifiedBuilder=!0)}}catch{}return n}function Vi(e){if(!sr(Gi(e)))return[];let t=Gt(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${Oe}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,ir,fo(),ir,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function Ec(){return['document360-writer (its "docs agent") has been removed from this repository. Please undo its dev\u2192docs',"hand-off setup and restore this repo to how it was before \u2014 in order:","","1. In this repo's agent-memory file (CLAUDE.md, or AGENTS.md \u2014 whichever it edited), REMOVE the",' "Documentation hand-off" section that was added (the rule about dropping hint files in'," `.d360-writer/hints/`, keeping `.d360-writer/architecture/` current, checking"," `.d360-writer/messages/`, and relaying `@d360-writer` directives to `.d360-writer/directives.md`)."," Leave everything else in that file untouched.","2. The `.d360-writer/` folder is already deleted on disk. If it was committed, remove it from version"," control too \u2014 `git rm -r --cached .d360-writer` (if it still resolves) \u2014 and commit the deletions.","3. Do NOT recreate any of those files or follow the hand-off protocol anymore.","","That's it \u2014 this repo is back to its pre-docs-agent state."].join(`
|
|
257
|
+
`)}function Yi(){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):",ir,Ec(),ir]}function lr(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${Oe}.`," 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):",ir,fo(),ir,"","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 ir,Oe,jv,Tc,Dn=ps(()=>{"use strict";ir="-".repeat(64),Oe=12,jv=`#!/usr/bin/env node
|
|
258
258
|
// d360-writer \u2014 session-start nudge for the builder ("John"). Surfaces open questions the docs agent
|
|
259
259
|
// ("Julie") left in .d360-writer/messages/ so they get answered, not forgotten. Self-contained (no deps);
|
|
260
260
|
// wired into your coding agent's session-start trigger by /devhints. See .d360-writer/DEV-HINTS-GUIDE.md.
|
|
@@ -292,94 +292,94 @@ try {
|
|
|
292
292
|
} catch {
|
|
293
293
|
/* a session-start nudge must never break the session */
|
|
294
294
|
}
|
|
295
|
-
`;
|
|
296
|
-
`),"utf8");return}let o;try{o=
|
|
295
|
+
`;Tc="Re-run dev\u2194docs onboarding (protocol v"});var Yf={};ef(Yf,{initCommand:()=>jc,scaffoldInit:()=>Dc,writeWriterGitignore:()=>Nc});import{input as ys,confirm as Ov}from"@inquirer/prompts";import{basename as Mf,join as Ki}from"node:path";import{existsSync as cr,readFileSync as Ff,readdirSync as _v,writeFileSync as Of}from"node:fs";import{writeProjectConfig as Uf,readProjectConfig as Mv,projectConfigPath as Wf,writerDir as Fv,DEFAULT_DOCS_DIR as Bf,DEFAULT_CAPTURE_DIR as Hf,DEFAULT_OUTPUT_DIR as Gf}from"document360-engine";function Dc(e,t="berlin"){let n=Wf(e);if(cr(n))return{created:!1,path:n,profileName:""};let o={projectId:qf(e)??Mf(e),docsDir:Bf,captureDir:Hf,outputDir:Gf,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:Vf(e)};return Uf(o,e),Nc(e),{created:!0,path:n,profileName:t}}function Nc(e){let t=Ki(Fv(e),".gitignore"),n="# Local/transient \u2014 the config files here ARE meant to be committed.";if(!cr(t)){Of(t,[n,..._f,""].join(`
|
|
296
|
+
`),"utf8");return}let o;try{o=Ff(t,"utf8")}catch{return}let r=new Set(o.split(/\r?\n/).map(l=>l.trim())),s=_f.filter(l=>!r.has(l)&&!r.has(l.replace(/\/$/,"")));if(s.length===0)return;let i=/\r\n/.test(o)?`\r
|
|
297
297
|
`:`
|
|
298
298
|
`,a=o.endsWith(`
|
|
299
|
-
`)?"":i;jf(t,`${o}${a}${s.join(i)}${i}`,"utf8")}async function Ec(){let e=process.cwd(),t=Mf(e);if(lr(t)&&!await jv({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(m("init cancelled.")),{kind:"continue"};let n=Bf(e)??Lf(e),o=await gs({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await gs({message:"Capture directory (where document360-capture .spec.ts files live):",default:Uf}),s=await gs({message:"Screenshot output directory:",default:Wf}),i=await gs({message:"Default connection profile name:",default:"berlin"}),a=await gs({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),l={projectId:o,docsDir:Ff,captureDir:r,outputDir:s,profiles:{[i]:{connection:{environment:a},production:!1}},defaultProfile:i,authoritativeSourceFiles:Hf(e)},d=Lv(e);d?.terminologyGlossary&&(l.terminologyGlossary=d.terminologyGlossary),_f(l,e),Ac(e);let w=ir(e);console.log(""),console.log(Y(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${Z(`d360-writer login --profile ${i}`)} ${m("(sign in; project & workspace auto-selected)")}`),console.log("");for(let g of ar(w))console.log(g);return console.log(""),console.log(`${m("Then ask:")} ${Z('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function Bf(e){let t=Vi(e,"package.json");if(!lr(t))return null;try{return JSON.parse(Of(t,"utf8")).name??null}catch{return null}}function Hf(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])lr(Vi(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Vi(e,n);lr(o)&&!_v(o)&&t.push(n)}return t}function _v(e){try{return Iv(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var If,Yi=us(()=>{"use strict";se();En();If=[".sessions/","cache/"]});import{createRequire as Qv}from"node:module";import{existsSync as Jv,readFileSync as Zv}from"node:fs";import{dirname as em,join as tm}from"node:path";function mt(){let e;try{e=ex.resolve("document360-capture/helpers")}catch{return null}let t=em(e);for(let n=0;n<5&&!Jv(tm(t,"package.json"));n++)t=em(t);try{let n=JSON.parse(Zv(tm(t,"package.json"),"utf8"));return n.name==="document360-capture"&&n.version?n.version:null}catch{return null}}var ex,cr=us(()=>{"use strict";ex=Qv(import.meta.url)});var $w={};Qh($w,{doctorCommand:()=>Ms,renderDoctorChecks:()=>kw,runDoctorChecks:()=>bw});import{existsSync as zS}from"node:fs";import{d360GetAll as XS,getAccessToken as QS,isExpired as Wa,loadProfileMap as JS,loadTokens as ZS,listStoredSessions as eC,tokensProjectId as Rd,packageSkillsDir as yw,ENGINE_VERSION as tC,projectConfigPath as nC,readProjectConfig as oC,DEFAULT_DOCS_DIR as rC,fetchManifestSummary as sC,resolveActiveProfile as iC,classifyClaudeAuth as aC,resolveAuthOrigin as lC,authOriginLine as cC,authOriginFix as uC,CLAUDE_CODE_SETUP_HINT as Ba,resolveModelSetting as dC,probeModel as pC,probeAgentTurn as hC,stderrHeadline as fC,detectAppType as mC,playbookSkillName as gC,D360AuthError as wC,applyStructureOrder as yC}from"document360-engine";async function bw(e,t){let n=[],o=mt();n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${tC}${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=aC();if(s.state==="ready"){let D=lC(),N=uC(D);n.push({level:N?"warn":"ok",label:`Claude auth: ${cC(D).replace(/^Claude: /,"")}`,...N?{fix:N}:{}})}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. ${Ba}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:Ba});let i=dC(e);if(n.push({level:"ok",label:`Model: ${i.model} (${i.source==="auto"?"auto \u2014 right-sized for docs; /model to change":i.source})`}),s.state==="ready"){let D=await pC(e,i.model??void 0);if(D.ok){n.push({level:"ok",label:`Model reachable \u2014 replied in ${(D.latencyMs/1e3).toFixed(1)}s`});let N=await hC(e,i.model??void 0);if(N.ok)n.push({level:"ok",label:`Agent turn works \u2014 ran with your skills and tools in ${(N.latencyMs/1e3).toFixed(1)}s`});else{let W=fC(N.stderr),I=/auth|sign.?in|login|credential|token|401|expired/i.test(`${N.error??""} ${N.stderr??""}`);if(n.push({level:"fail",label:N.timedOut?"Agent turn never finished \u2014 the model answers, but a real turn with your skills and tools hangs":I?"Agent turn failed \u2014 your Claude sign-in has expired, so every /write, /review and /catch-up will do nothing":`Agent turn produced nothing \u2014 the model answers, but a real turn with your skills and tools ${N.producedNothing?"ends instantly with no output":`fails: ${N.error}`}`,fix:(W?`Claude Code said: "${W}". `:"")+(I?`Sign in again, then re-run /doctor. ${Ba}`:"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.")}),I){let X=n.find(H=>H.label.startsWith("Claude auth:"));X&&(X.level="warn",X.label="Claude auth: a sign-in exists on this machine, but it is no longer valid",X.fix=`Sign in again. ${Ba}`)}}}else D.timedOut?n.push({level:"fail",label:"Model unreachable \u2014 no response in 30s (a docs turn will hang, then end with 0 tokens / no output)",fix:`Usually a corporate proxy/firewall or org policy blocking the Claude model API. Check this machine's network access to the Claude endpoint; confirm with: claude -p "say hi"`}):n.push({level:"fail",label:`Model call failed \u2014 ${D.error??"no output"} (a docs turn will end with 0 tokens / no output)`,fix:'Check sign-in, the selected model (/model), and network access to the Claude endpoint; confirm with: claude -p "say hi"'})}let a=oC(e);if(!a)return n.push({level:"fail",label:`No ${nC(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${a.projectId}`});let l=(a.docsDir??rC).replace(/\/+$/,"");n.push(a.mode==="engineer"?{level:"warn",label:"Mode: engineer \u2014 agent may modify any source file (dogfooding)",fix:'Remove "mode" from .d360-writer/config.json for the writer-mode boundary'}:{level:"ok",label:`Mode: writer \u2014 edits limited to ${l}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let d=a.authoritativeSourceFiles??[];n.push(d.length>0?{level:"ok",label:`Sources: docs grounded in ${d.length} path(s) (${d.slice(0,3).join(", ")}${d.length>3?", \u2026":""})`}:{level:"warn",label:"Sources: not set \u2014 docs are grounded in the whole repo",fix:"Run: /scope to choose which files/folders the docs are written from"});let w=a.appType??mC(e);if(w){let D=a.appType?"from config":"auto-detected",N=w==="web"||w==="cli";n.push({level:"ok",label:`Genre: ${w} (${D})${N?` \u2192 ${gC(w)} loaded`:" \u2014 no doc-type playbook for this genre yet (generic skills)"}`})}else n.push({level:"warn",label:"Genre: unclassified \u2014 no doc-type playbook is loading (generic output)",fix:"Run /genre <web|cli|service|library> to pick \u2014 raises docs to that genre's craft bar"});let g;try{g=iC(e),n.push({level:"ok",label:`Profile: ${g.name} (${g.connection.name})${g.production?" \u26A0 PRODUCTION":""}`})}catch(D){return n.push({level:"fail",label:`Profile config: ${D.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let $=ZS(g.name,g.project.projectId),P=eC(g.name).filter(D=>{let N=Rd(D);return!!N&&N!==g.project.projectId&&!(Wa(D)&&!D.refreshToken)}),C=g.project.projectName?`"${g.project.projectName}"`:"this project";$?Wa($)&&!$.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"}):Wa($)?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 ${C} (until ${new Date($.expiresAt).toLocaleString()})`}):n.push(P.length>0?{level:"fail",label:`Document360: not signed in to ${C} \u2014 signed in to ${P.map(D=>D.projectName?`"${D.projectName}"`:(Rd(D)??"").slice(0,8)+"\u2026").join(", ")} instead`,fix:`Run: /login and pick ${C} \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})`}),P.length>0&&n.push({level:"ok",label:`Other Document360 projects signed in on this machine: ${P.map(D=>D.projectName?`"${D.projectName}"`:(Rd(D)??"").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 R=JS(e,g.name);R?R.projectId&&g.project.projectId&&R.projectId!==g.project.projectId?n.push({level:"fail",label:`Category map projectId (${R.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(R.articles).length} articles, ${Object.keys(R.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${g.name}" (created on first /push)`}),n.push(zS(yw())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${yw()}`,fix:"Reinstall document360-writer (broken install)"});let T=Ht(e);if(T.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${Oe})`}):T.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${T.completedVersion}, current is v${Oe}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),$&&(!Wa($)||$.refreshToken)){let D={profile:g.name,connection:g.connection,projectId:g.project.projectId,projectName:g.project.projectName};try{await QS(D);let W=await XS(D,"/v3/projects");n.push({level:"ok",label:`API reachable (${g.connection.apiUrl}) \u2014 ${W.length} project(s) visible`})}catch(W){n.push({level:"fail",label:`API call failed: ${W.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let N=R?.projectId??g.project.projectId;if(N&&g.project.workspaceId){try{let W=await sC(D,N,g.project.workspaceId);if(W){let I=(W.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Your Document360 project: reachable on ${g.connection.name} (${W.languages?.length??0} language${(W.languages?.length??0)===1?"":"s"}) \xB7 version ${I||"(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(W){W instanceof wC||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(W.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${g.project.projectName??N})`,fix:"Run /login and pick this repo's project \u2014 your token is scoped to another project"}):n.push({level:"warn",label:`Workspace sync manifest: probe failed (${W.message.slice(0,80)})`})}try{let W=await yC({cwd:e,profileName:g.name,dryRun:!0}),I=W.categoriesReordered+W.articlesReordered;if(W.skipped==="no category map")n.push({level:"ok",label:"Reading order: nothing to check yet (no articles published)"});else if(W.skipped)n.push({level:"warn",label:`Reading order: can't be checked (${W.skipped})`,fix:"Your article order on Document360 may not match your structure \u2014 /push syncs it once this resolves"});else if(W.unverified)n.push({level:"warn",label:`Reading order: ${W.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(I>0){let X=[W.categoriesReordered>0?`${W.categoriesReordered} categor${W.categoriesReordered===1?"y":"ies"}`:"",W.articlesReordered>0?`${W.articlesReordered} article${W.articlesReordered===1?"":"s"}`:""].filter(Boolean);n.push({level:"warn",label:`Reading order: ${X.join(" + ")} out of order on Document360`,fix:"Run /push \u2014 it re-syncs the order from your NN- folder/file prefixes"})}else n.push({level:"ok",label:"Reading order: Document360 matches your structure"});if(W.orphans?.length){let X=W.orphans;n.push({level:"warn",label:`${X.length} article${X.length===1?"":"s"} on Document360 ${X.length===1?"is":"are"} not in your docs folder: ${X.slice(0,3).map(H=>H.path).join(", ")}${X.length>3?`, +${X.length-3} more`:""}`,fix:"/retire <path> takes one off your readers \xB7 /pull <path> brings one back into your docs folder \u2014 until you choose, it stays live and d360-writer leaves it alone"})}}catch(W){n.push({level:"warn",label:`Reading order: check failed (${W.message.slice(0,80)})`})}}}return n}function kw(e){let t=[""];for(let r of e){let s=r.level==="ok"?Y("\u2713"):r.level==="warn"?G("\u26A0"):_("\u2717");t.push(` ${s} ${r.label}${r.detail?m(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${m("fix:")} ${Z(r.fix)}`)}let n=e.filter(r=>r.level==="fail").length,o=e.filter(r=>r.level==="warn").length;return t.push(""),t.push(n===0?Y(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):_(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function Ms(e,t){console.log(m("Running checks\u2026"));for(let n of kw(await bw(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var Ha=us(()=>{"use strict";En();se();cr()});import{Command as mj}from"commander";import{createRequire as gj}from"node:module";import{AUTH_MODES as wj}from"document360-engine";import{input as U$}from"@inquirer/prompts";import{loginPkce as W$,getAccessToken as B$,toStoredTokens as H$,clearTokens as G$,decodeJwtClaims as rf,isExpired as q$,loadTokens as fc,saveTokens as V$,listStoredSessions as mc,tokensProjectId as Tn,rememberSessionProject as sf,resolveActiveProfile as fs,setProfileProject as Y$,readProjectConfig as K$}from"document360-engine";se();import{select as R$}from"@inquirer/prompts";import{resolveActiveProfile as S$,setProfileProject as C$,resolveProjectId as P$,listWorkspaces as T$}from"document360-engine";async function ps(e,t){let n=S$(e,t),o={profile:n.name,connection:n.connection,projectId:n.project.projectId,projectName:n.project.projectName},r=n.project.projectId??P$(o);return{workspaces:await T$(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var Zh=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function pc(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 Di(e,t,n,o,r){C$(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function ef(e,t,n){let o;try{o=await ps(e,n)}catch(s){return console.log(_(`Could not list workspaces: ${s.message}`)),1}let r=pc(o.workspaces,t);return r?(Di(e,o.profile,o.projectId,r.id,r.name),console.log(Y(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(_(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function or(e,t){let n;try{n=await ps(e,t)}catch(d){console.log(_(`Could not list workspaces: ${d.message}`));return}let{workspaces:o,projectId:r,profile:s,current:i}=n;if(o.length===0){console.log(m("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let d of o)console.log(` ${d.id===i?Z("\u25CF"):" "} ${Zh(d)} ${m(d.id)}`);console.log(m("Run: d360-writer workspace use <name>"));return}let a=await R$({message:"Select the Document360 workspace for this repo:",choices:o.map(d=>({name:`${Zh(d)}${d.id===i?" (current)":""}`,value:d.id}))}),l=o.find(d=>d.id===a);Di(e,s,r,a,l?.name),console.log(Y(`\u2713 Workspace set to "${l?.name??a}" for profile "${s}".`))}se();import{select as A$}from"@inquirer/prompts";import{resolveActiveProfile as E$,setProfileProject as D$,listProjects as N$}from"document360-engine";async function fn(e,t){let n=E$(e,t),o={profile:n.name,connection:n.connection};return{projects:await N$(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var tf=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function hc(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 Ni(e,t,n,o){D$(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function nf(e,t,n){let o;try{o=await fn(e,n)}catch(s){return console.log(_(`Could not list projects: ${s.message}`)),1}let r=hc(o.projects,t);return r?(Ni(e,o.profile,r.id,r.name),console.log(Y(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log(_(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function ji(e,t){let n;try{n=await fn(e,t)}catch(l){console.log(_(`Could not list projects: ${l.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(m("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let l of o)console.log(` ${l.id===s?Z("\u25CF"):" "} ${tf(l)} ${m(l.id)}`);console.log(m("Run: d360-writer project use <name>"));return}let i=await A$({message:"Select the Document360 project for this repo:",choices:o.map(l=>({name:`${tf(l)}${l.id===s?" (current)":""}`,value:l.id}))}),a=o.find(l=>l.id===i);Ni(e,r,i,a?.name),console.log(Y(`\u2713 Project set to "${a?.name??i}" for profile "${r}". Next: pick a workspace.`))}se();import j$ from"picocolors";function I$(e=process.env){return e.FORCE_HYPERLINK==="0"||!j$.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 L$(e,t=e,n){return I$(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var O$=/https?:\/\/[^\s\x1b]+/g;function hs(e,t){return e.replace(O$,n=>L$(n,n,t))}import{readProjectConfig as of,sunsetEnvironment as _$,resolveActiveProfile as M$}from"document360-engine";function F$(e,t){let n=of(e);return Object.entries(n?.profiles??{}).find(([,o])=>(o.connection?.environment??"berlin")===t)?.[0]??null}function Pn(e,t){try{if(!of(e))return null;let n=M$(e,t),o=_$(n.connection.name);if(!o)return null;let r=F$(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 af(e){return{...rf(e.idToken)??{},...rf(e.accessToken)??{}}}function Ii(e){let t=af(e),n=t.email??t.preferred_username??t.sub??"unknown",o=Tn(e),r=e.projectName?` \xB7 project "${e.projectName}"`:o?` \xB7 project ${o}`:"";return`${n}${r}`}async function gc(e,t,n){n&&sf(e,t,n);try{let{projects:o}=await fn(process.cwd(),e);for(let r of mc(e)){let s=Tn(r);s&&sf(e,s,o.find(i=>i.id===s)?.name)}}catch{}}function z$(e,t,n){let o=Tn(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 Li(e){let t=fs(process.cwd(),e.profile),n=t.connection;console.log(m(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=Pn(process.cwd(),e.profile);o&&(console.log(G(`\u26A0 ${o.why} \u2014 and signing in does NOT change it (the environment comes from the profile, not the login).`)),console.log(G(` To move: ${o.cmd}${o.replacementProfile?"":", then /login"}`)));let r=await W$(n,{manual:e.manual,promptForRedirect:w=>U$({message:w})},w=>console.log(hs(w))),s=H$(t.name,r);V$(s),await wc(s,t.name,w=>console.log(m(w)));let i=Tn(s),a=fs(process.cwd(),e.profile).project;i&&await gc(t.name,i,a.projectId===i?a.projectName:void 0);let l=fc(t.name,i??void 0)??s;console.log(""),console.log(Y(`\u2713 Logged in to "${t.name}" as ${Ii(l)}`));let d=z$(l,a.projectId,a.projectName);if(d&&console.log(G(d)),console.log(m(` access token expires: ${s.expiresAt}`)),console.log(m(` refresh token: ${s.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{K$(process.cwd())?.profiles?.[t.name]&&(console.log(""),await or(process.cwd(),t.name))}catch{}}async function wc(e,t,n){let r=af(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(fs(process.cwd(),t).project.projectId)return;let i;try{let{projects:a}=await fn(process.cwd(),t);i=a.find(l=>l.id===r)?.name}catch{}Y$(process.cwd(),t,{projectId:r,projectName:i}),n(` Project "${i??r}" written to profile "${t}".`)}catch{}}async function lf(e){let t=fs(process.cwd(),e.profile),n=t.connection,o=fc(t.name,t.project.projectId);if(!o){console.log(_(`Not logged in to Document360 (profile "${t.name}").`));let r=mc(t.name).filter(s=>Tn(s)&&Tn(s)!==t.project.projectId);r.length>0&&console.log(m(`This repo's project needs its own sign-in. Signed in on this machine: ${r.map(s=>s.projectName??Tn(s)).join(", ")}`)),console.log(m(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${Z(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Ii(o)}`),q$(o))if(o.refreshToken)try{await B$({profile:t.name,connection:n,projectId:t.project.projectId,projectName:t.project.projectName});let r=fc(t.name,t.project.projectId);console.log(Y(`\u2713 Session refreshed${r?` \u2014 expires ${r.expiresAt}`:""}`))}catch(r){console.log(G(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(m(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(G("Session expired (no refresh token).")),console.log(m(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(m(` expires: ${o.expiresAt}`))}async function cf(e){let t=fs(process.cwd(),e.profile),n=e.allProjects?void 0:t.project.projectId,o=t.project.projectName?`"${t.project.projectName}"`:`profile "${t.name}"`;if(G$(t.name,n)){console.log(Y(e.allProjects?`\u2713 Logged out of every Document360 project for profile "${t.name}".`:`\u2713 Logged out of ${o}.`));let r=mc(t.name).filter(s=>Tn(s)).length;r>0&&console.log(m(`Still signed in to ${r} other project${r===1?"":"s"} on this machine.`))}else console.log(m(`No Document360 session for ${o} \u2014 nothing to do.`))}se();import{readProjectConfig as uf,writeProjectConfig as X$,resolveActiveProfile as Q$,loadTokens as J$,isExpired as Z$}from"document360-engine";function Oi(e){let t=uf(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(_("No profiles in .d360-writer/config.json. Run: d360-writer init")),process.exitCode=1;return}console.log("");for(let[n,o]of Object.entries(t.profiles)){let r=n===t.defaultProfile?Z("\u25CF "):" ",s=o.production?G(" \u26A0 PRODUCTION"):"",i=o.connection.environment??"(inline)",a=J$(n,o.project?.projectId),l=a?Z$(a)&&!a.refreshToken?G("expired"):m("logged in"):m("not logged in");console.log(`${r}${Z(n)} \u2192 ${i}${s} [${l}]`)}console.log(""),console.log(m("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function _i(e,t){let n=uf(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(_(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,X$(n,e);let o=n.profiles[t].production?G(" \u26A0 PRODUCTION"):"";console.log(Y(`\u2713 Default profile is now "${t}"${o}`))}function Mi(e,t){try{let n=Q$(e,t);console.log(""),console.log(`Profile ${Z(n.name)}${n.production?G(" \u26A0 PRODUCTION"):""}`),console.log(m(` api: ${n.connection.apiUrl}`)),console.log(m(` identity: ${n.connection.authorizationUrl}`)),console.log(m(` clientId: ${n.connection.clientId}`)),console.log(m(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(m(` project: ${n.project.projectId??"(set at login)"}`)),console.log(m(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(_(n.message)),process.exitCode=1}}se();import{existsSync as hf,readdirSync as ev,readFileSync as tv,statSync as nv}from"node:fs";import{join as ff}from"node:path";import{apiLogDir as ov}from"document360-engine";var rv=30,sv=12e3;function iv(e){if(!hf(e))return{api:[],crash:[]};try{let t=ev(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 av=/·\s*(empty-turn|agent-subprocess|uncaught|unhandled)\s*===/i,lv=/·\s*FATAL\s*·/i,cv=e=>lv.test(e)||av.test(e);function uv(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(cv),r=o??n[n.length-1];return{text:r,when:/^=== (\S+)/.exec(r)?.[1]??"",count:n.length,notable:!!o}}function dv(e,t){let n=t[0];if(!n)return null;try{return uv(tv(ff(e,n),"utf8"))}catch{return null}}function df(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}var pf=(e,t)=>{try{return`${(nv(ff(e,t)).size/1024).toFixed(1)} KB`}catch{return""}};function yc(){let e=ov(),{api:t,crash:n}=iv(e),o=dv(e,n),r=[];if(o){let s=o.text.split(/\r?\n/),i=s.slice(0,rv);r.push(o.notable?ge("\u2717",`The last thing that went wrong \u2014 ${df(o.when)}:`):ge("\u2139",`Nothing has failed. The most recent note d360-writer recorded \u2014 ${df(o.when)}:`)),r.push("");for(let a of i)r.push(` ${a}`);s.length>i.length&&r.push(m(` \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(m(` ${o.count} entries recorded today; this is the one worth reading.`)),o.notable&&r.push(m(" If this is not obviously your own doing, send it to the team \u2014 it names what failed.")),r.push("")}else n.length===0&&(r.push(ge("\u2713","Nothing has failed \u2014 d360-writer has recorded no problems.")),r.push(""));if(r.push(`Logs live in ${Z(e)}`),!hf(e)||t.length===0&&n.length===0)return r.push(m(" 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 ${m("(send these if something crashed or a run did nothing)")}:`);for(let s of n.slice(0,14))r.push(` ${_(s)} ${m(pf(e,s))}`)}if(t.length>0){r.push(""),r.push("Document360 call logs:");for(let s of t.slice(0,14))r.push(` ${s} ${m(pf(e,s))}`)}return r.push(""),r.push(m("Failed calls include what was sent and returned (sign-in details removed, 4 KB cap).")),r.push(m("Set D360_LOG_BODIES=1 to record successful calls too.")),{lines:r,copyText:o?o.text.slice(0,sv):null,notable:!!o?.notable}}async function mf(){return bc(),{kind:"continue"}}function bc(){let{lines:e,copyText:t}=yc();console.log("");for(let n of e)console.log(n);t&&console.log(m("Inside d360-writer, /logs offers to copy this for you.")),console.log("")}se();import{createSession as pv,resolveAuth as hv,findByName as fv,slugify as mv,touchSession as gv,upsertSession as wv,resolveActiveProfile as yv}from"document360-engine";async function gf(e,t,n,o,r,s){let i=hv(n);i.kind==="none"&&(console.error(""),console.error(_("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${Z("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${Z("d360-writer --auth subscription")}`),process.exit(2)),i.kind==="subscription"&&console.error(m("Using your Claude subscription (no API key set)."));let a=null;try{a=yv(e,r)}catch($){console.error(_(`Document360 profile error: ${$.message}`)),process.exit(2)}a.production&&(console.error(G(`\u26A0 Profile "${a.name}" is PRODUCTION.`)),s||(console.error(_("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(m(" --yes given \u2014 proceeding against production.")));let l;if(o){let $=fv(e,o);$||(console.error(_(`No saved session matches "${o}" in this repo.`)),console.error(m("List sessions inside the REPL with /resume.")),process.exit(2)),l=$.uuid,console.error(m(`Resuming "${$.name}"`))}let d=pv({cwd:e,resume:l,profileName:r,allowProdWrites:s===!0}),w=l??null,g=1;for await(let $ of d.send(t))switch($.type){case"session":if(!w){w=$.sessionId;let P=new Date().toISOString();wv({uuid:w,name:mv(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:P,updatedAt:P})}break;case"text":process.stdout.write($.delta);break;case"tool":console.error(xe(` \u2699 ${$.name}`));break;case"result":g=$.ok?0:1,console.error(m(`(${$.inputTokens}\u2192${$.outputTokens} tokens`+($.costUsd>0?`, $${$.costUsd<.01?$.costUsd.toFixed(4):$.costUsd.toFixed(2)}`:"")+")")),$.ok||console.error(_("agent finished with an error result"));break;case"error":console.error(""),console.error(_(`agent error: ${$.message}`)),process.exit(1)}w&&gv(w),process.stdout.write(`
|
|
300
|
-
`),process.exit(g)}import{createInterface as
|
|
301
|
-
`)}var ft=[{key:"start",label:"Getting Started",rows:[{t:"text",s:"D360-Writer reads your codebase, generates end-user documentation, and publishes it to Document360."},{t:"text",s:"It needs Claude access \u2014 a Claude subscription (default) or an ANTHROPIC_API_KEY."},{t:"gap"},{t:"sub",s:"Quick start"},{t:"step",n:1,s:"Run /init \u2014 pick your environment, sign in, choose your project & workspace. It ends by printing a one-paste hand-off prompt."},{t:"step",n:2,s:"Paste that prompt into your repo's coding agent (Claude Code / Codex / Cursor). Let it finish, then follow its closing line. (Re-show it: /devhints)"},{t:"step",n:3,s:"Run /doctor to confirm every check is green."},{t:"step",n:4,s:'Type "write the docs for this repository" and follow the prompts.'},{t:"gap"},{t:"dim",s:"That's it \u2014 D360-Writer drafts your docs without you writing a line."},{t:"gap"},{t:"sub",s:"Tips"},{t:"text",s:"Just talk to it \u2014 anything not starting with / goes to the agent."},{t:"dim",s:"/ browses commands \xB7 \u2191 recalls history \xB7 esc interrupts a run \xB7 ctrl+c twice exits"},{t:"dim",s:"tab runs the suggestion \xB7 1-9 pick from a list \xB7 c copies whatever was offered for copying"},{t:"dim",s:"shift+tab switches between auto and manual \u2014 in auto I run the next step myself (/auto)"}]},{key:"agentic",label:"Agentic",rows:[{t:"text",s:"Agentic Mode is designed for applications built using AI coding agents. D360-Writer works alongside your coding agent to continuously create and maintain your user documentation. Think of it as hiring a Technical Writer dedicated to your project."},{t:"gap"},{t:"text",s:"As your coding agent ships new features, it leaves documentation notes for D360-Writer. All you need to do is run the documentation loop."},{t:"gap"},{t:"sub",s:"Auto or manual"},{t:"text",s:"In MANUAL mode D360-Writer works out the next step, offers it, and waits for you to press tab. In AUTO mode it runs that step itself and keeps going \u2014 write, review, check the style, save, go live \u2014 so you can start a build and come back to a finished knowledge base."},{t:"cmd",name:"/auto on",s:"Let D360-Writer run its own next step. Shift+tab cycles between auto and manual at any time, and the mode is shown at the bottom of the screen."},{t:"cmd",name:"/auto --budget <amount>",s:"How much one automatic run may spend before it stops and reports. Every repo has a limit; the standard one is $200."},{t:"dim",s:" esc stops a running automatic pass. Everything already written, saved or published stays \u2014 stopping never undoes work."},{t:"text",s:"Auto mode changes who presses the key, not what is checked. The editorial pass still reads every article, and an article that fails a check is held back as a draft and named in the report rather than being pushed past it. Screenshots are never taken automatically: they need your product running with the right data on screen."},{t:"gap"},{t:"sub",s:"Every few days"},{t:"cmd",name:"/catch-up",s:"Analyze the latest code changes, read the notes left by your coding agent, and update the documentation. Everything lands as a draft."},{t:"cmd",name:"/review --fix",s:"A senior editor reads every article and applies its fixes. Required before anything goes live \u2014 these were written by an AI."},{t:"cmd",name:"/review --blocked --fix",s:"The same editorial pass over only the articles publishing is blocked on \u2014 after a run that rewrote two of forty, this reads those two."},{t:"cmd",name:"/review --stale --fix",s:"The same pass over every article the current editor has not read yet \u2014 never reviewed, or reviewed before the editor last improved. Run it twice and the second run does nothing, so it is the safe way to catch a knowledge base up."},{t:"cmd",name:"/push --all",s:"Save the reviewed articles to Document360, as drafts."},{t:"cmd",name:"/publish --all",s:"Take those drafts live to your readers \u2014 it lists what will become visible and asks first."},{t:"dim",s:" (/catch-up --push runs the writing and the save back-to-back; going live stays a deliberate step)"},{t:"gap"},{t:"sub",s:"Whenever you need"},{t:"cmd",name:"/discover",s:"Interview your coding agent to understand the product (what it is, who it's for, the core idea, common misconceptions) \u2014 pins a product brief that grounds every article. Runs before writing a repo's docs; loops until confident."},{t:"cmd",name:"/audit",s:"Preview what has changed and identify missing documentation, without writing or publishing anything."},{t:"cmd",name:"/pull",s:"Bring Document360 down \u2014 pull edits made in the portal and import any new portal articles."},{t:"cmd",name:"/resolve",s:"Resolve conflicts when an article was edited both here and in the portal \u2014 review the diff, then keep yours, take the portal's, or skip."},{t:"cmd",name:"/comments",s:"The comments reviewers left on passages of your articles in the Document360 portal. You get a table \u2014 category, article, how many comments \u2014 and pick a number to read that article's comments in full (the highlighted passage beside what they said), then answer them or go back to the list. `a` answers everything. Each article is fixed, pushed to Document360 as an updated draft, and answered in the thread. Threads are left OPEN for the reviewer to close once they've checked the change; add --resolve to close the ones fully handled. --answered lists the ones already waiting on your reviewers; --full re-reads every article instead of only the ones that can have changed."},{t:"cmd",name:"/inbox",s:"Review and act on messages left by your coding agent."},{t:"cmd",name:"/ask <question>",s:"Ask your developers something the code cannot tell you: why a feature exists, when to use it, whether it can be undone. Costs nothing and does not stop your work."}]},{key:"assistant",label:"Assistant",rows:[{t:"text",s:"D360-Writer is your writing assistant \u2014 it does the writing, you decide what gets written and when."},{t:"text",s:"Best for large or complex monorepos: focus it on one feature, component, or set of source folders."},{t:"gap"},{t:"sub",s:"Just ask"},{t:"good",s:'"Write the documentation for the Multiple JWT feature we shipped in the latest release."'},{t:"gap"},{t:"sub",s:"Or use the pipeline"},{t:"cmd",name:"/scope",s:"Focus D360-Writer on specific source folders (monorepos)."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from its PRDs in .d360-writer/input/ + the code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview shows the plan + cost first)."},{t:"cmd",name:"/push",s:"Save the articles to Document360 as drafts. Requires an editorial review first \u2014 /review --fix."},{t:"cmd",name:"/push --preview <path>",s:"Show exactly what Document360 would receive for one article \u2014 details at the top and title removed, screenshots in place, links resolved. Sends nothing."},{t:"cmd",name:"/publish",s:"Take the drafts live to your readers, once they have been signed off."},{t:"cmd",name:"/status",s:"What stands between your work and your readers: which articles no editor has read, which break a blocking style rule, which would show placeholder text, and which are saved as drafts your readers cannot see yet. Each group names the one command that clears it. Costs nothing and calls nothing \u2014 run it before you publish, not after. --all shows every article gate by gate."},{t:"cmd",name:"/retire <path>",s:"Take an article off your readers: it stops being visible on Document360 and nothing offers to publish it again. Nothing is deleted \u2014 the article, its history and every reviewer comment stay, so a retirement is always reversible. Bare /retire lists what is worth retiring. /push puts one back."},{t:"cmd",name:"/terms",s:'Is your knowledge base calling the same thing by the same name? It reads every article and reports terms spelled more than one way, short names that might be an abbreviation of a longer one, and titles out of step with the rest of their kind. This is the consistency an editor reading three articles at a time structurally cannot see. Costs nothing. --approve "<term>" records your choice so every later run enforces it.'}]},{key:"shots",label:"Screenshots",rows:[{t:"text",s:"Documenting a web app? D360-Writer marks where an image helps with a <!-- SCREENSHOT --> placeholder."},{t:"text",s:"The companion CLI d360-capture turns those into real, annotated screenshots by driving your app in a browser."},{t:"gap"},{t:"sub",s:"Flow"},{t:"step",n:1,s:"Write your docs as usual \u2014 placeholders are added where visuals help."},{t:"step",n:2,s:"Run /screenshot author --all to write the capture specs and refresh the capture checklist (data + test-ids the shots need)."},{t:"step",n:3,s:"Stage what the checklist asks for, then /screenshot capture \u2014 the writer drives a real browser that signs in, navigates and takes the shots."},{t:"step",n:4,s:"The callouts are drawn on straight after, no browser needed. /screenshot annotate finishes any that were left, and re-draws after you reword a callout or change the marker style."},{t:"step",n:5,s:"Each finished picture is then checked automatically: D360-Writer looks at it and marks it \u2714 verified, or flags what is wrong and fixes the spec for you."},{t:"step",n:6,s:"Run /push --screenshots \u2014 it re-saves the articles with finished shots so the images embed on Document360. Put a category in front (/push 04-publishing --screenshots) to re-save only that one."},{t:"gap"},{t:"sub",s:"One command family"},{t:"cmd",name:"/screenshot",s:"Bare: pick what to do next (author or capture, per shot)."},{t:"cmd",name:"/screenshot author",s:"Write capture specs (<id>, a path, or --all)."},{t:"cmd",name:"/screenshot capture",s:"Take the screenshots (<id>, a path, or --all; bare = pick ready specs)."},{t:"cmd",name:"/screenshot capture --failed",s:"Re-run just the shots that did not work \u2014 a failed run, or one that failed verification."},{t:"cmd",name:"/screenshot capture --blocked",s:"Re-run the shots waiting on app data, once you have staged it (a bulk run leaves them out by default)."},{t:"cmd",name:"/screenshot annotate",s:"Draw the callouts on shots already taken (<id>, a path, or --all). No browser and no sign-in \u2014 it re-uses the pictures you have, so it takes about a second each. --force re-draws ones that are already finished."},{t:"cmd",name:"/screenshot verify",s:"Look at the finished pictures and mark them verified (<id> for one). Runs automatically after a capture \u2014 run it yourself for shots taken before this existed, or after an interrupted run. No browser needed."},{t:"cmd",name:"/screenshot checklist",s:"What to stage + dev test-id requests (a report; auto-runs after bulk authoring)."},{t:"cmd",name:"/screenshot list",s:'Progress by chapter (\u2714 verified \xB7 \u25C8 to verify \xB7 \u25CF to annotate \xB7 \u25D0 ready \xB7 \u2691 rejected \xB7 \u2298 blocked \xB7 \u2717 broken \xB7 \u25CB to-spec) plus the grouped "stage this data" worklist; list <chapter#> or --detail drills in.'},{t:"gap"},{t:"sub",s:"What done means"},{t:"text",s:"\u2714 verified is the finish line. \u25CF to annotate means the browser has taken the shot but the callouts are not on it yet, so there is nothing to publish; \u25C8 to verify means the picture is finished and waiting to be looked at. It counts as done once it has been judged fit for the article."},{t:"gap"},{t:"sub",s:"When a shot does not produce a usable image"},{t:"text",s:"\u25CF to annotate means the shot was taken but the callouts were never drawn on \u2014 the browser work is already paid for, so /screenshot annotate finishes it in about a second."},{t:"text",s:"\u2298 blocked means your app lacked the data the shot needs \u2014 /screenshot list groups every blocker into the handful of things to go and stage."},{t:"text",s:"\u2717 broken means the spec itself is out of date. Re-author it with /screenshot <id> (which carries the error into the fix); re-running the capture would fail the same way."},{t:"text",s:"\u2691 rejected means the shot ran but the picture is wrong \u2014 an empty placeholder where content should be, a callout on the wrong element, the subject unreadable. The spec is usually fixed for you; /screenshot capture --failed re-shoots. /screenshot list --detail shows each reason."},{t:"gap"},{t:"dim",s:"One-time setup in the app repo: npm i -g document360-capture \xB7 d360-capture init \xB7 d360-capture auth (real login, once per machine)."}]},{key:"cmds",label:"Commands",rows:[{t:"dim",s:"Grouped by job. Type any command, or just talk to the agent."},{t:"gap"},{t:"sub",s:"Getting started"},{t:"cmd",name:"/init",s:"Set up Document360 (environment, sign-in, project, hand-off prompt)."},{t:"cmd",name:"/login",s:"Sign in to Document360. One sign-in per project, all kept \u2014 switching repos never signs you out of the others."},{t:"cmd",name:"/project",s:"Choose the Document360 project."},{t:"cmd",name:"/workspace",s:"Switch the workspace."},{t:"cmd",name:"/scope",s:"Choose which repo folders back the docs (monorepos)."},{t:"cmd",name:"/devhints",s:"Re-show the builder hand-off prompt."},{t:"gap"},{t:"sub",s:"Agentic \u2014 keep docs in sync"},{t:"cmd",name:"/roadmap",s:"The docs campaign, grouped by the part of the job: progress + the next step (`--all` also shows replaced steps, `done` marks the next step finished)."},{t:"cmd",name:"/catch-up",s:"Do all pending work \u2192 drafts (--push then saves them to Document360)."},{t:"cmd",name:"/share",s:"Exchange work with your team: get your builder's latest, send yours (automatic; `off` to stop)."},{t:"cmd",name:"/push",s:"Save to Document360 as drafts (--all or a path). Needs /review --fix first."},{t:"cmd",name:"/publish",s:"Take the drafts live to your readers (--all or a path). Lists them and asks first."},{t:"cmd",name:"/audit",s:"Preview what changed / what's missing."},{t:"cmd",name:"/pull",s:"Pull portal edits + new articles (--status: report only)."},{t:"cmd",name:"/resolve",s:"Resolve local\u2194portal conflicts (diff \u2192 keep local / take portal / skip \u2014 one at a time, or all at once)."},{t:"cmd",name:"/comments",s:"Reviewer comments on your articles \u2014 a table by article; pick one to read it, then answer (--resolve also closes the threads)."},{t:"cmd",name:"/inbox",s:"Act on your coding agent's messages."},{t:"cmd",name:"/ask",s:"Ask your developers what the code cannot answer."},{t:"gap"},{t:"sub",s:"Quality \u2014 before you publish"},{t:"cmd",name:"/style-guide",s:"Choose the writing rules your docs are held to \u2014 the Microsoft or Google style guide, or just the house rules. Adopting one records what your articles already contain, so nothing you have written suddenly breaks. `keep` settles on the rules you already have, so the question stops being asked. `pull` brings your Document360 project's own style guide down so the writer works to it; `learn` reads what your reviewers keep asking for and turns the general parts into standing rules the writer follows from then on; `compile` turns mechanical statements into checks and tells you which parts only an editor can judge."},{t:"cmd",name:"/lint",s:"The machine pass: leaked internals, invented commands, stale facts, AI-tells, em dashes, callout shape. Costs nothing to run; --fix has the agent correct what it found, which is a real pass over every article that has an issue. --blocked narrows both to the errors that block publishing, leaving warnings and suggestions alone."},{t:"cmd",name:"/review",s:"The editor pass: a senior editor reads the articles against the house style guide and judges what no rule can. --fix applies the corrections, --blocked narrows to the articles publishing is blocked on, --stale to the ones the current editor has not read. Required before anything goes live."},{t:"gap"},{t:"sub",s:"Assistant \u2014 directed writing"},{t:"cmd",name:"/discover",s:"Interview your builder \u2192 product brief that grounds the docs."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from PRDs + code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview first)."},{t:"cmd",name:"/preview",s:"Render an article locally."},{t:"gap"},{t:"sub",s:"Screenshots"},{t:"cmd",name:"/screenshot",s:"The screenshot pipeline: bare = pick; author / capture / checklist / list."},{t:"gap"},{t:"sub",s:"Setup & health"},{t:"cmd",name:"/model",s:"Set the Claude model."},{t:"cmd",name:"/verbose",s:"Raw transcript: every tool call, path and full result (bare: toggle)."},{t:"cmd",name:"/profile",s:"Switch/create a Document360 connection."},{t:"cmd",name:"/mcp",s:"Connect MCP servers (Notion, Linear, \u2026)."},{t:"cmd",name:"/allow-prod",s:"Authorize writes to a production profile."},{t:"cmd",name:"/doctor",s:"Health check: auth, profile, workspace, API \u2014 and a real agent turn, so a setup that looks fine but cannot actually write anything is caught here rather than by an empty `/write`."},{t:"cmd",name:"/logs",s:"Shows the most recent problem d360-writer recorded, in full, and where the logs are kept. Run it whenever a command did nothing or something crashed: the reason is in there. Press `c` to copy it and send it to the team."},{t:"cmd",name:"/update",s:"Update D360-Writer."},{t:"cmd",name:"/feedback",s:"Copy logged D360-Writer feedback to your clipboard (relay it to the team)."},{t:"cmd",name:"/reset",s:"Delete all D360-Writer files (confirms first)."},{t:"gap"},{t:"sub",s:"Session"},{t:"cmd",name:"/resume",s:"Resume a saved session."},{t:"cmd",name:"/rename",s:"Name the session."},{t:"cmd",name:"/clear",s:"Clear the screen and reset the conversation (resumable)."},{t:"cmd",name:"/help",s:"Show this help."},{t:"cmd",name:"/exit",s:"Quit."}]}],wf=24;function kc(e){let t=e.filter(n=>n.t==="cmd").map(n=>n.name.length);return t.length===0?wf:Math.min(wf,Math.max(...t))}function Wi(e,t,n,o){let r=" ".repeat(2+n+1),s=Math.max(24,o-r.length-2),i=Qt(t,s);return e.length>n?{nameCell:e,descLines:i,indent:r,nameOwnLine:!0}:{nameCell:e.padEnd(n),descLines:i,indent:r,nameOwnLine:!1}}function bv(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=Wi(e.name,e.s,t,n),r=o.descLines.slice(o.nameOwnLine?0:1).map(i=>`${o.indent}${i}`);return[o.nameOwnLine?` ${o.nameCell}`:` ${o.nameCell} ${o.descLines[0]??""}`,...r].join(`
|
|
302
|
-
`)}case"gap":return""}}function
|
|
299
|
+
`)?"":i;Of(t,`${o}${a}${s.join(i)}${i}`,"utf8")}async function jc(){let e=process.cwd(),t=Wf(e);if(cr(t)&&!await Ov({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(m("init cancelled.")),{kind:"continue"};let n=qf(e)??Mf(e),o=await ys({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await ys({message:"Capture directory (where document360-capture .spec.ts files live):",default:Hf}),s=await ys({message:"Screenshot output directory:",default:Gf}),i=await ys({message:"Default connection profile name:",default:"berlin"}),a=await ys({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),l={projectId:o,docsDir:Bf,captureDir:r,outputDir:s,profiles:{[i]:{connection:{environment:a},production:!1}},defaultProfile:i,authoritativeSourceFiles:Vf(e)},d=Mv(e);d?.terminologyGlossary&&(l.terminologyGlossary=d.terminologyGlossary),Uf(l,e),Nc(e);let w=ar(e);console.log(""),console.log(Y(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${Z(`d360-writer login --profile ${i}`)} ${m("(sign in; project & workspace auto-selected)")}`),console.log("");for(let g of lr(w))console.log(g);return console.log(""),console.log(`${m("Then ask:")} ${Z('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function qf(e){let t=Ki(e,"package.json");if(!cr(t))return null;try{return JSON.parse(Ff(t,"utf8")).name??null}catch{return null}}function Vf(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])cr(Ki(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Ki(e,n);cr(o)&&!Uv(o)&&t.push(n)}return t}function Uv(e){try{return _v(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var _f,zi=ps(()=>{"use strict";se();Dn();_f=[".sessions/","cache/"]});import{createRequire as ex}from"node:module";import{existsSync as tx,readFileSync as nx}from"node:fs";import{dirname as om,join as rm}from"node:path";function mt(){let e;try{e=ox.resolve("document360-capture/helpers")}catch{return null}let t=om(e);for(let n=0;n<5&&!tx(rm(t,"package.json"));n++)t=om(t);try{let n=JSON.parse(nx(rm(t,"package.json"),"utf8"));return n.name==="document360-capture"&&n.version?n.version:null}catch{return null}}var ox,ur=ps(()=>{"use strict";ox=ex(import.meta.url)});var Rw={};ef(Rw,{doctorCommand:()=>Us,renderDoctorChecks:()=>xw,runDoctorChecks:()=>vw});import{existsSync as JS}from"node:fs";import{d360GetAll as ZS,getAccessToken as eC,isExpired as Ha,loadProfileMap as tC,loadTokens as nC,listStoredSessions as oC,tokensProjectId as Pd,packageSkillsDir as $w,ENGINE_VERSION as rC,projectConfigPath as sC,readProjectConfig as iC,DEFAULT_DOCS_DIR as aC,fetchManifestSummary as lC,resolveActiveProfile as cC,classifyClaudeAuth as uC,resolveAuthOrigin as dC,authOriginLine as pC,authOriginFix as hC,CLAUDE_CODE_SETUP_HINT as Ga,resolveModelSetting as fC,probeModel as mC,probeAgentTurn as gC,stderrHeadline as wC,detectAppType as yC,playbookSkillName as bC,D360AuthError as kC,applyStructureOrder as $C}from"document360-engine";async function vw(e,t){let n=[],o=mt();n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${rC}${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=uC();if(s.state==="ready"){let D=dC(),N=hC(D);n.push({level:N?"warn":"ok",label:`Claude auth: ${pC(D).replace(/^Claude: /,"")}`,...N?{fix:N}:{}})}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. ${Ga}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:Ga});let i=fC(e);if(n.push({level:"ok",label:`Model: ${i.model} (${i.source==="auto"?"auto \u2014 right-sized for docs; /model to change":i.source})`}),s.state==="ready"){let D=await mC(e,i.model??void 0);if(D.ok){n.push({level:"ok",label:`Model reachable \u2014 replied in ${(D.latencyMs/1e3).toFixed(1)}s`});let N=await gC(e,i.model??void 0);if(N.ok)n.push({level:"ok",label:`Agent turn works \u2014 ran with your skills and tools in ${(N.latencyMs/1e3).toFixed(1)}s`});else{let B=wC(N.stderr),I=/auth|sign.?in|login|credential|token|401|expired/i.test(`${N.error??""} ${N.stderr??""}`);if(n.push({level:"fail",label:N.timedOut?"Agent turn never finished \u2014 the model answers, but a real turn with your skills and tools hangs":I?"Agent turn failed \u2014 your Claude sign-in has expired, so every /write, /review and /catch-up will do nothing":`Agent turn produced nothing \u2014 the model answers, but a real turn with your skills and tools ${N.producedNothing?"ends instantly with no output":`fails: ${N.error}`}`,fix:(B?`Claude Code said: "${B}". `:"")+(I?`Sign in again, then re-run /doctor. ${Ga}`:"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.")}),I){let X=n.find(q=>q.label.startsWith("Claude auth:"));X&&(X.level="warn",X.label="Claude auth: a sign-in exists on this machine, but it is no longer valid",X.fix=`Sign in again. ${Ga}`)}}}else D.timedOut?n.push({level:"fail",label:"Model unreachable \u2014 no response in 30s (a docs turn will hang, then end with 0 tokens / no output)",fix:`Usually a corporate proxy/firewall or org policy blocking the Claude model API. Check this machine's network access to the Claude endpoint; confirm with: claude -p "say hi"`}):n.push({level:"fail",label:`Model call failed \u2014 ${D.error??"no output"} (a docs turn will end with 0 tokens / no output)`,fix:'Check sign-in, the selected model (/model), and network access to the Claude endpoint; confirm with: claude -p "say hi"'})}let a=iC(e);if(!a)return n.push({level:"fail",label:`No ${sC(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${a.projectId}`});let l=(a.docsDir??aC).replace(/\/+$/,"");n.push(a.mode==="engineer"?{level:"warn",label:"Mode: engineer \u2014 agent may modify any source file (dogfooding)",fix:'Remove "mode" from .d360-writer/config.json for the writer-mode boundary'}:{level:"ok",label:`Mode: writer \u2014 edits limited to ${l}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let d=a.authoritativeSourceFiles??[];n.push(d.length>0?{level:"ok",label:`Sources: docs grounded in ${d.length} path(s) (${d.slice(0,3).join(", ")}${d.length>3?", \u2026":""})`}:{level:"warn",label:"Sources: not set \u2014 docs are grounded in the whole repo",fix:"Run: /scope to choose which files/folders the docs are written from"});let w=a.appType??yC(e);if(w){let D=a.appType?"from config":"auto-detected",N=w==="web"||w==="cli";n.push({level:"ok",label:`Genre: ${w} (${D})${N?` \u2192 ${bC(w)} loaded`:" \u2014 no doc-type playbook for this genre yet (generic skills)"}`})}else n.push({level:"warn",label:"Genre: unclassified \u2014 no doc-type playbook is loading (generic output)",fix:"Run /genre <web|cli|service|library> to pick \u2014 raises docs to that genre's craft bar"});let g;try{g=cC(e),n.push({level:"ok",label:`Profile: ${g.name} (${g.connection.name})${g.production?" \u26A0 PRODUCTION":""}`})}catch(D){return n.push({level:"fail",label:`Profile config: ${D.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let $=nC(g.name,g.project.projectId),P=oC(g.name).filter(D=>{let N=Pd(D);return!!N&&N!==g.project.projectId&&!(Ha(D)&&!D.refreshToken)}),C=g.project.projectName?`"${g.project.projectName}"`:"this project";$?Ha($)&&!$.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"}):Ha($)?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 ${C} (until ${new Date($.expiresAt).toLocaleString()})`}):n.push(P.length>0?{level:"fail",label:`Document360: not signed in to ${C} \u2014 signed in to ${P.map(D=>D.projectName?`"${D.projectName}"`:(Pd(D)??"").slice(0,8)+"\u2026").join(", ")} instead`,fix:`Run: /login and pick ${C} \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})`}),P.length>0&&n.push({level:"ok",label:`Other Document360 projects signed in on this machine: ${P.map(D=>D.projectName?`"${D.projectName}"`:(Pd(D)??"").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 R=tC(e,g.name);R?R.projectId&&g.project.projectId&&R.projectId!==g.project.projectId?n.push({level:"fail",label:`Category map projectId (${R.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(R.articles).length} articles, ${Object.keys(R.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${g.name}" (created on first /push)`}),n.push(JS($w())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${$w()}`,fix:"Reinstall document360-writer (broken install)"});let T=Gt(e);if(T.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${Oe})`}):T.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${T.completedVersion}, current is v${Oe}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),$&&(!Ha($)||$.refreshToken)){let D={profile:g.name,connection:g.connection,projectId:g.project.projectId,projectName:g.project.projectName};try{await eC(D);let B=await ZS(D,"/v3/projects");n.push({level:"ok",label:`API reachable (${g.connection.apiUrl}) \u2014 ${B.length} project(s) visible`})}catch(B){n.push({level:"fail",label:`API call failed: ${B.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let N=R?.projectId??g.project.projectId;if(N&&g.project.workspaceId){try{let B=await lC(D,N,g.project.workspaceId);if(B){let I=(B.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Your Document360 project: reachable on ${g.connection.name} (${B.languages?.length??0} language${(B.languages?.length??0)===1?"":"s"}) \xB7 version ${I||"(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(B){B instanceof kC||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(B.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${g.project.projectName??N})`,fix:"Run /login and pick this repo's project \u2014 your token is scoped to another project"}):n.push({level:"warn",label:`Workspace sync manifest: probe failed (${B.message.slice(0,80)})`})}try{let B=await $C({cwd:e,profileName:g.name,dryRun:!0}),I=B.categoriesReordered+B.articlesReordered;if(B.skipped==="no category map")n.push({level:"ok",label:"Reading order: nothing to check yet (no articles published)"});else if(B.skipped)n.push({level:"warn",label:`Reading order: can't be checked (${B.skipped})`,fix:"Your article order on Document360 may not match your structure \u2014 /push syncs it once this resolves"});else if(B.unverified)n.push({level:"warn",label:`Reading order: ${B.unverified} of your articles aren't listed by Document360, so their order can't be set`,fix:"Usually means those articles are not live yet (the listing returns published articles). /publish takes them live, then /push re-syncs the order"});else if(I>0){let X=[B.categoriesReordered>0?`${B.categoriesReordered} categor${B.categoriesReordered===1?"y":"ies"}`:"",B.articlesReordered>0?`${B.articlesReordered} article${B.articlesReordered===1?"":"s"}`:""].filter(Boolean);n.push({level:"warn",label:`Reading order: ${X.join(" + ")} out of order on Document360`,fix:"Run /push \u2014 it re-syncs the order from your NN- folder/file prefixes"})}else n.push({level:"ok",label:"Reading order: Document360 matches your structure"});if(B.orphans?.length){let X=B.orphans;n.push({level:"warn",label:`${X.length} article${X.length===1?"":"s"} on Document360 ${X.length===1?"is":"are"} not in your docs folder: ${X.slice(0,3).map(q=>q.path).join(", ")}${X.length>3?`, +${X.length-3} more`:""}`,fix:"/retire <path> takes one off your readers \xB7 /pull <path> brings one back into your docs folder \u2014 until you choose, it stays live and d360-writer leaves it alone"})}}catch(B){n.push({level:"warn",label:`Reading order: check failed (${B.message.slice(0,80)})`})}}}return n}function xw(e){let t=[""];for(let r of e){let s=r.level==="ok"?Y("\u2713"):r.level==="warn"?V("\u26A0"):_("\u2717");t.push(` ${s} ${r.label}${r.detail?m(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${m("fix:")} ${Z(r.fix)}`)}let n=e.filter(r=>r.level==="fail").length,o=e.filter(r=>r.level==="warn").length;return t.push(""),t.push(n===0?Y(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):_(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function Us(e,t){console.log(m("Running checks\u2026"));for(let n of xw(await vw(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var qa=ps(()=>{"use strict";Dn();se();ur()});import{Command as bj}from"commander";import{createRequire as kj}from"node:module";import{AUTH_MODES as $j}from"document360-engine";import{input as H$}from"@inquirer/prompts";import{loginPkce as G$,getAccessToken as q$,toStoredTokens as V$,clearTokens as Y$,decodeJwtClaims as lf,isExpired as K$,loadTokens as wc,saveTokens as z$,listStoredSessions as yc,tokensProjectId as An,rememberSessionProject as cf,resolveActiveProfile as gs,setProfileProject as X$,readProjectConfig as Q$}from"document360-engine";se();import{select as P$}from"@inquirer/prompts";import{resolveActiveProfile as T$,setProfileProject as A$,resolveProjectId as E$,listWorkspaces as D$}from"document360-engine";async function fs(e,t){let n=T$(e,t),o={profile:n.name,connection:n.connection,projectId:n.project.projectId,projectName:n.project.projectName},r=n.project.projectId??E$(o);return{workspaces:await D$(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var nf=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function mc(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){A$(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function of(e,t,n){let o;try{o=await fs(e,n)}catch(s){return console.log(_(`Could not list workspaces: ${s.message}`)),1}let r=mc(o.workspaces,t);return r?(ji(e,o.profile,o.projectId,r.id,r.name),console.log(Y(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(_(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function rr(e,t){let n;try{n=await fs(e,t)}catch(d){console.log(_(`Could not list workspaces: ${d.message}`));return}let{workspaces:o,projectId:r,profile:s,current:i}=n;if(o.length===0){console.log(m("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let d of o)console.log(` ${d.id===i?Z("\u25CF"):" "} ${nf(d)} ${m(d.id)}`);console.log(m("Run: d360-writer workspace use <name>"));return}let a=await P$({message:"Select the Document360 workspace for this repo:",choices:o.map(d=>({name:`${nf(d)}${d.id===i?" (current)":""}`,value:d.id}))}),l=o.find(d=>d.id===a);ji(e,s,r,a,l?.name),console.log(Y(`\u2713 Workspace set to "${l?.name??a}" for profile "${s}".`))}se();import{select as N$}from"@inquirer/prompts";import{resolveActiveProfile as j$,setProfileProject as I$,listProjects as L$}from"document360-engine";async function fn(e,t){let n=j$(e,t),o={profile:n.name,connection:n.connection};return{projects:await L$(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var rf=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function gc(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 Ii(e,t,n,o){I$(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function sf(e,t,n){let o;try{o=await fn(e,n)}catch(s){return console.log(_(`Could not list projects: ${s.message}`)),1}let r=gc(o.projects,t);return r?(Ii(e,o.profile,r.id,r.name),console.log(Y(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log(_(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function Li(e,t){let n;try{n=await fn(e,t)}catch(l){console.log(_(`Could not list projects: ${l.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(m("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let l of o)console.log(` ${l.id===s?Z("\u25CF"):" "} ${rf(l)} ${m(l.id)}`);console.log(m("Run: d360-writer project use <name>"));return}let i=await N$({message:"Select the Document360 project for this repo:",choices:o.map(l=>({name:`${rf(l)}${l.id===s?" (current)":""}`,value:l.id}))}),a=o.find(l=>l.id===i);Ii(e,r,i,a?.name),console.log(Y(`\u2713 Project set to "${a?.name??i}" for profile "${r}". Next: pick a workspace.`))}se();import O$ from"picocolors";function _$(e=process.env){return e.FORCE_HYPERLINK==="0"||!O$.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 M$(e,t=e,n){return _$(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var F$=/https?:\/\/[^\s\x1b]+/g;function ms(e,t){return e.replace(F$,n=>M$(n,n,t))}import{readProjectConfig as af,sunsetEnvironment as U$,resolveActiveProfile as W$}from"document360-engine";function B$(e,t){let n=af(e);return Object.entries(n?.profiles??{}).find(([,o])=>(o.connection?.environment??"berlin")===t)?.[0]??null}function Tn(e,t){try{if(!af(e))return null;let n=W$(e,t),o=U$(n.connection.name);if(!o)return null;let r=B$(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 uf(e){return{...lf(e.idToken)??{},...lf(e.accessToken)??{}}}function Oi(e){let t=uf(e),n=t.email??t.preferred_username??t.sub??"unknown",o=An(e),r=e.projectName?` \xB7 project "${e.projectName}"`:o?` \xB7 project ${o}`:"";return`${n}${r}`}async function bc(e,t,n){n&&cf(e,t,n);try{let{projects:o}=await fn(process.cwd(),e);for(let r of yc(e)){let s=An(r);s&&cf(e,s,o.find(i=>i.id===s)?.name)}}catch{}}function J$(e,t,n){let o=An(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 _i(e){let t=gs(process.cwd(),e.profile),n=t.connection;console.log(m(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=Tn(process.cwd(),e.profile);o&&(console.log(V(`\u26A0 ${o.why} \u2014 and signing in does NOT change it (the environment comes from the profile, not the login).`)),console.log(V(` To move: ${o.cmd}${o.replacementProfile?"":", then /login"}`)));let r=await G$(n,{manual:e.manual,promptForRedirect:w=>H$({message:w})},w=>console.log(ms(w))),s=V$(t.name,r);z$(s),await kc(s,t.name,w=>console.log(m(w)));let i=An(s),a=gs(process.cwd(),e.profile).project;i&&await bc(t.name,i,a.projectId===i?a.projectName:void 0);let l=wc(t.name,i??void 0)??s;console.log(""),console.log(Y(`\u2713 Logged in to "${t.name}" as ${Oi(l)}`));let d=J$(l,a.projectId,a.projectName);if(d&&console.log(V(d)),console.log(m(` access token expires: ${s.expiresAt}`)),console.log(m(` refresh token: ${s.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{Q$(process.cwd())?.profiles?.[t.name]&&(console.log(""),await rr(process.cwd(),t.name))}catch{}}async function kc(e,t,n){let r=uf(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(gs(process.cwd(),t).project.projectId)return;let i;try{let{projects:a}=await fn(process.cwd(),t);i=a.find(l=>l.id===r)?.name}catch{}X$(process.cwd(),t,{projectId:r,projectName:i}),n(` Project "${i??r}" written to profile "${t}".`)}catch{}}async function df(e){let t=gs(process.cwd(),e.profile),n=t.connection,o=wc(t.name,t.project.projectId);if(!o){console.log(_(`Not logged in to Document360 (profile "${t.name}").`));let r=yc(t.name).filter(s=>An(s)&&An(s)!==t.project.projectId);r.length>0&&console.log(m(`This repo's project needs its own sign-in. Signed in on this machine: ${r.map(s=>s.projectName??An(s)).join(", ")}`)),console.log(m(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${Z(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Oi(o)}`),K$(o))if(o.refreshToken)try{await q$({profile:t.name,connection:n,projectId:t.project.projectId,projectName:t.project.projectName});let r=wc(t.name,t.project.projectId);console.log(Y(`\u2713 Session refreshed${r?` \u2014 expires ${r.expiresAt}`:""}`))}catch(r){console.log(V(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(m(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(V("Session expired (no refresh token).")),console.log(m(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(m(` expires: ${o.expiresAt}`))}async function pf(e){let t=gs(process.cwd(),e.profile),n=e.allProjects?void 0:t.project.projectId,o=t.project.projectName?`"${t.project.projectName}"`:`profile "${t.name}"`;if(Y$(t.name,n)){console.log(Y(e.allProjects?`\u2713 Logged out of every Document360 project for profile "${t.name}".`:`\u2713 Logged out of ${o}.`));let r=yc(t.name).filter(s=>An(s)).length;r>0&&console.log(m(`Still signed in to ${r} other project${r===1?"":"s"} on this machine.`))}else console.log(m(`No Document360 session for ${o} \u2014 nothing to do.`))}se();import{readProjectConfig as hf,writeProjectConfig as Z$,resolveActiveProfile as ev,loadTokens as tv,isExpired as nv}from"document360-engine";function Mi(e){let t=hf(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(_("No profiles in .d360-writer/config.json. Run: d360-writer init")),process.exitCode=1;return}console.log("");for(let[n,o]of Object.entries(t.profiles)){let r=n===t.defaultProfile?Z("\u25CF "):" ",s=o.production?V(" \u26A0 PRODUCTION"):"",i=o.connection.environment??"(inline)",a=tv(n,o.project?.projectId),l=a?nv(a)&&!a.refreshToken?V("expired"):m("logged in"):m("not logged in");console.log(`${r}${Z(n)} \u2192 ${i}${s} [${l}]`)}console.log(""),console.log(m("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function Fi(e,t){let n=hf(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(_(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,Z$(n,e);let o=n.profiles[t].production?V(" \u26A0 PRODUCTION"):"";console.log(Y(`\u2713 Default profile is now "${t}"${o}`))}function Ui(e,t){try{let n=ev(e,t);console.log(""),console.log(`Profile ${Z(n.name)}${n.production?V(" \u26A0 PRODUCTION"):""}`),console.log(m(` api: ${n.connection.apiUrl}`)),console.log(m(` identity: ${n.connection.authorizationUrl}`)),console.log(m(` clientId: ${n.connection.clientId}`)),console.log(m(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(m(` project: ${n.project.projectId??"(set at login)"}`)),console.log(m(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(_(n.message)),process.exitCode=1}}se();import{existsSync as gf,readdirSync as ov,readFileSync as rv,statSync as sv}from"node:fs";import{join as wf}from"node:path";import{apiLogDir as iv}from"document360-engine";var av=30,lv=12e3;function cv(e){if(!gf(e))return{api:[],crash:[]};try{let t=ov(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 uv=/·\s*(empty-turn|agent-subprocess|uncaught|unhandled)\s*===/i,dv=/·\s*FATAL\s*·/i,pv=e=>dv.test(e)||uv.test(e);function hv(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(pv),r=o??n[n.length-1];return{text:r,when:/^=== (\S+)/.exec(r)?.[1]??"",count:n.length,notable:!!o}}function fv(e,t){let n=t[0];if(!n)return null;try{return hv(rv(wf(e,n),"utf8"))}catch{return null}}function ff(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}var mf=(e,t)=>{try{return`${(sv(wf(e,t)).size/1024).toFixed(1)} KB`}catch{return""}};function $c(){let e=iv(),{api:t,crash:n}=cv(e),o=fv(e,n),r=[];if(o){let s=o.text.split(/\r?\n/),i=s.slice(0,av);r.push(o.notable?me("\u2717",`The last thing that went wrong \u2014 ${ff(o.when)}:`):me("\u2139",`Nothing has failed. The most recent note d360-writer recorded \u2014 ${ff(o.when)}:`)),r.push("");for(let a of i)r.push(` ${a}`);s.length>i.length&&r.push(m(` \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(m(` ${o.count} entries recorded today; this is the one worth reading.`)),o.notable&&r.push(m(" If this is not obviously your own doing, send it to the team \u2014 it names what failed.")),r.push("")}else n.length===0&&(r.push(me("\u2713","Nothing has failed \u2014 d360-writer has recorded no problems.")),r.push(""));if(r.push(`Logs live in ${Z(e)}`),!gf(e)||t.length===0&&n.length===0)return r.push(m(" 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 ${m("(send these if something crashed or a run did nothing)")}:`);for(let s of n.slice(0,14))r.push(` ${_(s)} ${m(mf(e,s))}`)}if(t.length>0){r.push(""),r.push("Document360 call logs:");for(let s of t.slice(0,14))r.push(` ${s} ${m(mf(e,s))}`)}return r.push(""),r.push(m("Failed calls include what was sent and returned (sign-in details removed, 4 KB cap).")),r.push(m("Set D360_LOG_BODIES=1 to record successful calls too.")),{lines:r,copyText:o?o.text.slice(0,lv):null,notable:!!o?.notable}}async function yf(){return vc(),{kind:"continue"}}function vc(){let{lines:e,copyText:t}=$c();console.log("");for(let n of e)console.log(n);t&&console.log(m("Inside d360-writer, /logs offers to copy this for you.")),console.log("")}se();import{createSession as mv,resolveAuth as gv,findByName as wv,slugify as yv,touchSession as bv,upsertSession as kv,resolveActiveProfile as $v}from"document360-engine";async function bf(e,t,n,o,r,s){let i=gv(n);i.kind==="none"&&(console.error(""),console.error(_("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${Z("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${Z("d360-writer --auth subscription")}`),process.exit(2)),i.kind==="subscription"&&console.error(m("Using your Claude subscription (no API key set)."));let a=null;try{a=$v(e,r)}catch($){console.error(_(`Document360 profile error: ${$.message}`)),process.exit(2)}a.production&&(console.error(V(`\u26A0 Profile "${a.name}" is PRODUCTION.`)),s||(console.error(_("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(m(" --yes given \u2014 proceeding against production.")));let l;if(o){let $=wv(e,o);$||(console.error(_(`No saved session matches "${o}" in this repo.`)),console.error(m("List sessions inside the REPL with /resume.")),process.exit(2)),l=$.uuid,console.error(m(`Resuming "${$.name}"`))}let d=mv({cwd:e,resume:l,profileName:r,allowProdWrites:s===!0}),w=l??null,g=1;for await(let $ of d.send(t))switch($.type){case"session":if(!w){w=$.sessionId;let P=new Date().toISOString();kv({uuid:w,name:yv(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:P,updatedAt:P})}break;case"text":process.stdout.write($.delta);break;case"tool":console.error(xe(` \u2699 ${$.name}`));break;case"result":g=$.ok?0:1,console.error(m(`(${$.inputTokens}\u2192${$.outputTokens} tokens`+($.costUsd>0?`, $${$.costUsd<.01?$.costUsd.toFixed(4):$.costUsd.toFixed(2)}`:"")+")")),$.ok||console.error(_("agent finished with an error result"));break;case"error":console.error(""),console.error(_(`agent error: ${$.message}`)),process.exit(1)}w&&bv(w),process.stdout.write(`
|
|
300
|
+
`),process.exit(g)}import{createInterface as vD}from"node:readline/promises";import{createSession as Bp,resolveAuth as xD,resolveAuthOrigin as RD,authOriginLine as Tb,authOriginFix as SD,getSession as CD,setTitle as PD,slugify as TD,touchSession as Nb,upsertSession as AD,generateTitle as ED,resolveActiveProfile as jb,resolveModelSetting as DD,readProjectConfig as ND,readUserConfig as jD,resolveAndPersistAppType as ID,decodeJwtClaims as Ab,isExpired as LD,loadTokens as OD,isDirectiveMention as _D,stripDirectiveMention as MD,appendDirective as FD,reconcileUpgradeActions as UD,stampArticles as WD,snapshotArticles as BD,listArticleFiles as HD,applyStructureOrder as GD,orderSyncLine as qD,computeSyncStatus as VD}from"document360-engine";import{ENGINE_VERSION as Rv}from"document360-engine";function Jt(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 Wi(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 Jt(`${i+1}. ${s.feature}`,76))o.push(n(a));o.push(n());for(let a of Jt(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 Bi(e){return[`\u26A0 ${e} screenshot${e===1?"":"s"} that hide${e===1?"s":""} sensitive areas ${e===1?"is":"are"} back to needing a check.`," A blacked-out area only covered the first matching spot on the screen \u2014 so on a list or a table, the",` rows below it were still readable. Blackouts now cover every match, and ${e===1?"that picture needs":"those pictures need"} a fresh look.`].join(`
|
|
301
|
+
`)}var ft=[{key:"start",label:"Getting Started",rows:[{t:"text",s:"D360-Writer reads your codebase, generates end-user documentation, and publishes it to Document360."},{t:"text",s:"It needs Claude access \u2014 a Claude subscription (default) or an ANTHROPIC_API_KEY."},{t:"gap"},{t:"sub",s:"Quick start"},{t:"step",n:1,s:"Run /init \u2014 pick your environment, sign in, choose your project & workspace. It ends by printing a one-paste hand-off prompt."},{t:"step",n:2,s:"Paste that prompt into your repo's coding agent (Claude Code / Codex / Cursor). Let it finish, then follow its closing line. (Re-show it: /devhints)"},{t:"step",n:3,s:"Run /doctor to confirm every check is green."},{t:"step",n:4,s:'Type "write the docs for this repository" and follow the prompts.'},{t:"gap"},{t:"dim",s:"That's it \u2014 D360-Writer drafts your docs without you writing a line."},{t:"gap"},{t:"sub",s:"Tips"},{t:"text",s:"Just talk to it \u2014 anything not starting with / goes to the agent."},{t:"dim",s:"/ browses commands \xB7 \u2191 recalls history \xB7 esc interrupts a run \xB7 ctrl+c twice exits"},{t:"dim",s:"tab runs the suggestion \xB7 1-9 pick from a list \xB7 c copies whatever was offered for copying"},{t:"dim",s:"shift+tab switches between auto and manual \u2014 in auto I run the next step myself (/auto)"}]},{key:"agentic",label:"Agentic",rows:[{t:"text",s:"Agentic Mode is designed for applications built using AI coding agents. D360-Writer works alongside your coding agent to continuously create and maintain your user documentation. Think of it as hiring a Technical Writer dedicated to your project."},{t:"gap"},{t:"text",s:"As your coding agent ships new features, it leaves documentation notes for D360-Writer. All you need to do is run the documentation loop."},{t:"gap"},{t:"sub",s:"Auto or manual"},{t:"text",s:"In MANUAL mode D360-Writer works out the next step, offers it, and waits for you to press tab. In AUTO mode it runs that step itself and keeps going \u2014 write, review, check the style, save, go live \u2014 so you can start a build and come back to a finished knowledge base."},{t:"cmd",name:"/auto on",s:"Let D360-Writer run its own next step. Shift+tab cycles between auto and manual at any time, and the mode is shown at the bottom of the screen."},{t:"cmd",name:"/auto --budget <amount>",s:"How much one automatic run may spend before it stops and reports. Every repo has a limit; the standard one is $200."},{t:"dim",s:" esc stops a running automatic pass. Everything already written, saved or published stays \u2014 stopping never undoes work."},{t:"text",s:"Auto mode changes who presses the key, not what is checked. The editorial pass still reads every article, and an article that fails a check is held back as a draft and named in the report rather than being pushed past it. Screenshots are never taken automatically: they need your product running with the right data on screen."},{t:"gap"},{t:"sub",s:"Every few days"},{t:"cmd",name:"/catch-up",s:"Analyze the latest code changes, read the notes left by your coding agent, and update the documentation. Everything lands as a draft."},{t:"cmd",name:"/review --fix",s:"A senior editor reads every article and applies its fixes. Required before anything goes live \u2014 these were written by an AI."},{t:"cmd",name:"/review --blocked --fix",s:"The same editorial pass over only the articles publishing is blocked on \u2014 after a run that rewrote two of forty, this reads those two."},{t:"cmd",name:"/review --stale --fix",s:"The same pass over every article the current editor has not read yet \u2014 never reviewed, or reviewed before the editor last improved. Run it twice and the second run does nothing, so it is the safe way to catch a knowledge base up."},{t:"cmd",name:"/push --all",s:"Save the reviewed articles to Document360, as drafts."},{t:"cmd",name:"/publish --all",s:"Take those drafts live to your readers \u2014 it lists what will become visible and asks first."},{t:"dim",s:" (/catch-up --push runs the writing and the save back-to-back; going live stays a deliberate step)"},{t:"gap"},{t:"sub",s:"Whenever you need"},{t:"cmd",name:"/discover",s:"Interview your coding agent to understand the product (what it is, who it's for, the core idea, common misconceptions) \u2014 pins a product brief that grounds every article. Runs before writing a repo's docs; loops until confident."},{t:"cmd",name:"/audit",s:"Preview what has changed and identify missing documentation, without writing or publishing anything."},{t:"cmd",name:"/pull",s:"Bring Document360 down \u2014 pull edits made in the portal and import any new portal articles."},{t:"cmd",name:"/resolve",s:"Resolve conflicts when an article was edited both here and in the portal \u2014 review the diff, then keep yours, take the portal's, or skip."},{t:"cmd",name:"/comments",s:"The comments reviewers left on passages of your articles in the Document360 portal. You get a table \u2014 category, article, how many comments \u2014 and pick a number to read that article's comments in full (the highlighted passage beside what they said), then answer them or go back to the list. `a` answers everything. Each article is fixed, pushed to Document360 as an updated draft, and answered in the thread. Threads are left OPEN for the reviewer to close once they've checked the change; add --resolve to close the ones fully handled. --answered lists the ones already waiting on your reviewers; --full re-reads every article instead of only the ones that can have changed."},{t:"cmd",name:"/inbox",s:"Review and act on messages left by your coding agent."},{t:"cmd",name:"/ask <question>",s:"Ask your developers something the code cannot tell you: why a feature exists, when to use it, whether it can be undone. Costs nothing and does not stop your work."}]},{key:"assistant",label:"Assistant",rows:[{t:"text",s:"D360-Writer is your writing assistant \u2014 it does the writing, you decide what gets written and when."},{t:"text",s:"Best for large or complex monorepos: focus it on one feature, component, or set of source folders."},{t:"gap"},{t:"sub",s:"Just ask"},{t:"good",s:'"Write the documentation for the Multiple JWT feature we shipped in the latest release."'},{t:"gap"},{t:"sub",s:"Or use the pipeline"},{t:"cmd",name:"/scope",s:"Focus D360-Writer on specific source folders (monorepos)."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from its PRDs in .d360-writer/input/ + the code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview shows the plan + cost first)."},{t:"cmd",name:"/push",s:"Save the articles to Document360 as drafts. Requires an editorial review first \u2014 /review --fix."},{t:"cmd",name:"/push --preview <path>",s:"Show exactly what Document360 would receive for one article \u2014 details at the top and title removed, screenshots in place, links resolved. Sends nothing."},{t:"cmd",name:"/publish",s:"Take the drafts live to your readers, once they have been signed off."},{t:"cmd",name:"/status",s:"What stands between your work and your readers: which articles no editor has read, which break a blocking style rule, which would show placeholder text, and which are saved as drafts your readers cannot see yet. Each group names the one command that clears it. Costs nothing and calls nothing \u2014 run it before you publish, not after. --all shows every article gate by gate."},{t:"cmd",name:"/retire <path>",s:"Take an article off your readers: it stops being visible on Document360 and nothing offers to publish it again. Nothing is deleted \u2014 the article, its history and every reviewer comment stay, so a retirement is always reversible. Bare /retire lists what is worth retiring. /push puts one back."},{t:"cmd",name:"/terms",s:'Is your knowledge base calling the same thing by the same name? It reads every article and reports terms spelled more than one way, short names that might be an abbreviation of a longer one, and titles out of step with the rest of their kind. This is the consistency an editor reading three articles at a time structurally cannot see. Costs nothing. --approve "<term>" records your choice so every later run enforces it.'}]},{key:"shots",label:"Screenshots",rows:[{t:"text",s:"Documenting a web app? D360-Writer marks where an image helps with a <!-- SCREENSHOT --> placeholder."},{t:"text",s:"The companion CLI d360-capture turns those into real, annotated screenshots by driving your app in a browser."},{t:"gap"},{t:"sub",s:"Flow"},{t:"step",n:1,s:"Write your docs as usual \u2014 placeholders are added where visuals help."},{t:"step",n:2,s:"Run /screenshot author --all to write the capture specs and refresh the capture checklist (data + test-ids the shots need)."},{t:"step",n:3,s:"Stage what the checklist asks for, then /screenshot capture \u2014 the writer drives a real browser that signs in, navigates and takes the shots."},{t:"step",n:4,s:"The callouts are drawn on straight after, no browser needed. /screenshot annotate finishes any that were left, and re-draws after you reword a callout or change the marker style."},{t:"step",n:5,s:"Each finished picture is then checked automatically: D360-Writer looks at it and marks it \u2714 verified, or flags what is wrong and fixes the spec for you."},{t:"step",n:6,s:"Run /push --screenshots \u2014 it re-saves the articles with finished shots so the images embed on Document360. Put a category in front (/push 04-publishing --screenshots) to re-save only that one."},{t:"gap"},{t:"sub",s:"One command family"},{t:"cmd",name:"/screenshot",s:"Bare: pick what to do next (author or capture, per shot)."},{t:"cmd",name:"/screenshot author",s:"Write capture specs (<id>, a path, or --all)."},{t:"cmd",name:"/screenshot capture",s:"Take the screenshots (<id>, a path, or --all; bare = pick ready specs)."},{t:"cmd",name:"/screenshot capture --failed",s:"Re-run just the shots that did not work \u2014 a failed run, or one that failed verification."},{t:"cmd",name:"/screenshot capture --blocked",s:"Re-run the shots waiting on app data, once you have staged it (a bulk run leaves them out by default)."},{t:"cmd",name:"/screenshot annotate",s:"Draw the callouts on shots already taken (<id>, a path, or --all). No browser and no sign-in \u2014 it re-uses the pictures you have, so it takes about a second each. --force re-draws ones that are already finished."},{t:"cmd",name:"/screenshot verify",s:"Look at the finished pictures and mark them verified (<id> for one). Runs automatically after a capture \u2014 run it yourself for shots taken before this existed, or after an interrupted run. No browser needed."},{t:"cmd",name:"/screenshot checklist",s:"What to stage + dev test-id requests (a report; auto-runs after bulk authoring)."},{t:"cmd",name:"/screenshot list",s:'Progress by chapter (\u2714 verified \xB7 \u25C8 to verify \xB7 \u25CF to annotate \xB7 \u25D0 ready \xB7 \u2691 rejected \xB7 \u2298 blocked \xB7 \u2717 broken \xB7 \u25CB to-spec) plus the grouped "stage this data" worklist; list <chapter#> or --detail drills in.'},{t:"gap"},{t:"sub",s:"What done means"},{t:"text",s:"\u2714 verified is the finish line. \u25CF to annotate means the browser has taken the shot but the callouts are not on it yet, so there is nothing to publish; \u25C8 to verify means the picture is finished and waiting to be looked at. It counts as done once it has been judged fit for the article."},{t:"gap"},{t:"sub",s:"When a shot does not produce a usable image"},{t:"text",s:"\u25CF to annotate means the shot was taken but the callouts were never drawn on \u2014 the browser work is already paid for, so /screenshot annotate finishes it in about a second."},{t:"text",s:"\u2298 blocked means your app lacked the data the shot needs \u2014 /screenshot list groups every blocker into the handful of things to go and stage."},{t:"text",s:"\u2717 broken means the spec itself is out of date. Re-author it with /screenshot <id> (which carries the error into the fix); re-running the capture would fail the same way."},{t:"text",s:"\u2691 rejected means the shot ran but the picture is wrong \u2014 an empty placeholder where content should be, a callout on the wrong element, the subject unreadable. The spec is usually fixed for you; /screenshot capture --failed re-shoots. /screenshot list --detail shows each reason."},{t:"gap"},{t:"dim",s:"One-time setup in the app repo: npm i -g document360-capture \xB7 d360-capture init \xB7 d360-capture auth (real login, once per machine)."}]},{key:"cmds",label:"Commands",rows:[{t:"dim",s:"Grouped by job. Type any command, or just talk to the agent."},{t:"gap"},{t:"sub",s:"Getting started"},{t:"cmd",name:"/init",s:"Set up Document360 (environment, sign-in, project, hand-off prompt)."},{t:"cmd",name:"/login",s:"Sign in to Document360. One sign-in per project, all kept \u2014 switching repos never signs you out of the others."},{t:"cmd",name:"/project",s:"Choose the Document360 project."},{t:"cmd",name:"/workspace",s:"Switch the workspace."},{t:"cmd",name:"/scope",s:"Choose which repo folders back the docs (monorepos)."},{t:"cmd",name:"/devhints",s:"Re-show the builder hand-off prompt."},{t:"gap"},{t:"sub",s:"Agentic \u2014 keep docs in sync"},{t:"cmd",name:"/roadmap",s:"The docs campaign, grouped by the part of the job: progress + the next step (`--all` also shows replaced steps, `done` marks the next step finished)."},{t:"cmd",name:"/catch-up",s:"Do all pending work \u2192 drafts (--push then saves them to Document360)."},{t:"cmd",name:"/share",s:"Exchange work with your team: get your builder's latest, send yours (automatic; `off` to stop)."},{t:"cmd",name:"/push",s:"Save to Document360 as drafts (--all or a path). Needs /review --fix first."},{t:"cmd",name:"/publish",s:"Take the drafts live to your readers (--all or a path). Lists them and asks first."},{t:"cmd",name:"/audit",s:"Preview what changed / what's missing."},{t:"cmd",name:"/pull",s:"Pull portal edits + new articles (--status: report only)."},{t:"cmd",name:"/resolve",s:"Resolve local\u2194portal conflicts (diff \u2192 keep local / take portal / skip \u2014 one at a time, or all at once)."},{t:"cmd",name:"/comments",s:"Reviewer comments on your articles \u2014 a table by article; pick one to read it, then answer (--resolve also closes the threads)."},{t:"cmd",name:"/inbox",s:"Act on your coding agent's messages."},{t:"cmd",name:"/ask",s:"Ask your developers what the code cannot answer."},{t:"gap"},{t:"sub",s:"Quality \u2014 before you publish"},{t:"cmd",name:"/style-guide",s:"Choose the writing rules your docs are held to \u2014 the Microsoft or Google style guide, or just the house rules. Adopting one records what your articles already contain, so nothing you have written suddenly breaks. `keep` settles on the rules you already have, so the question stops being asked. `pull` brings your Document360 project's own style guide down so the writer works to it; `learn` reads what your reviewers keep asking for and turns the general parts into standing rules the writer follows from then on; `compile` turns mechanical statements into checks and tells you which parts only an editor can judge."},{t:"cmd",name:"/lint",s:"The machine pass: leaked internals, invented commands, stale facts, AI-tells, em dashes, callout shape. Costs nothing to run; --fix has the agent correct what it found, which is a real pass over every article that has an issue. --blocked narrows both to the errors that block publishing, leaving warnings and suggestions alone."},{t:"cmd",name:"/review",s:"The editor pass: a senior editor reads the articles against the house style guide and judges what no rule can. --fix applies the corrections, --blocked narrows to the articles publishing is blocked on, --stale to the ones the current editor has not read. Required before anything goes live."},{t:"gap"},{t:"sub",s:"Assistant \u2014 directed writing"},{t:"cmd",name:"/discover",s:"Interview your builder \u2192 product brief that grounds the docs."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from PRDs + code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview first)."},{t:"cmd",name:"/preview",s:"Render an article locally."},{t:"gap"},{t:"sub",s:"Screenshots"},{t:"cmd",name:"/screenshot",s:"The screenshot pipeline: bare = pick; author / capture / checklist / list."},{t:"gap"},{t:"sub",s:"Setup & health"},{t:"cmd",name:"/model",s:"Set the Claude model."},{t:"cmd",name:"/verbose",s:"Raw transcript: every tool call, path and full result (bare: toggle)."},{t:"cmd",name:"/profile",s:"Switch/create a Document360 connection."},{t:"cmd",name:"/mcp",s:"Connect MCP servers (Notion, Linear, \u2026)."},{t:"cmd",name:"/allow-prod",s:"Authorize writes to a production profile."},{t:"cmd",name:"/doctor",s:"Health check: auth, profile, workspace, API \u2014 and a real agent turn, so a setup that looks fine but cannot actually write anything is caught here rather than by an empty `/write`."},{t:"cmd",name:"/logs",s:"Shows the most recent problem d360-writer recorded, in full, and where the logs are kept. Run it whenever a command did nothing or something crashed: the reason is in there. Press `c` to copy it and send it to the team."},{t:"cmd",name:"/update",s:"Update D360-Writer."},{t:"cmd",name:"/feedback",s:"Copy logged D360-Writer feedback to your clipboard (relay it to the team)."},{t:"cmd",name:"/reset",s:"Delete all D360-Writer files (confirms first)."},{t:"gap"},{t:"sub",s:"Session"},{t:"cmd",name:"/resume",s:"Resume a saved session."},{t:"cmd",name:"/rename",s:"Name the session."},{t:"cmd",name:"/clear",s:"Clear the screen and reset the conversation (resumable)."},{t:"cmd",name:"/help",s:"Show this help."},{t:"cmd",name:"/exit",s:"Quit."}]}],kf=24;function xc(e){let t=e.filter(n=>n.t==="cmd").map(n=>n.name.length);return t.length===0?kf:Math.min(kf,Math.max(...t))}function Hi(e,t,n,o){let r=" ".repeat(2+n+1),s=Math.max(24,o-r.length-2),i=Jt(t,s);return e.length>n?{nameCell:e,descLines:i,indent:r,nameOwnLine:!0}:{nameCell:e.padEnd(n),descLines:i,indent:r,nameOwnLine:!1}}function vv(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=Hi(e.name,e.s,t,n),r=o.descLines.slice(o.nameOwnLine?0:1).map(i=>`${o.indent}${i}`);return[o.nameOwnLine?` ${o.nameCell}`:` ${o.nameCell} ${o.descLines[0]??""}`,...r].join(`
|
|
302
|
+
`)}case"gap":return""}}function $f(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 ft){n.push(`\u2500\u2500 ${o.label} \u2500\u2500`,"");let r=xc(o.rows);for(let s of o.rows)n.push(vv(s,r,100));n.push("")}return n.push("Tip: anything not starting with / goes to the agent."),n}function Rc(e,t){return Jt(e,Math.max(10,Math.max(20,t)-2))}function xv(e,t,n){let o=Math.max(20,n),r=s=>Math.max(1,Rc(s,o).length);switch(e.t){case"gap":return 1;case"cmd":{let s=Hi(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 vf(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=xv(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 xf(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 Sc(e=[],t){console.log("");let n=t?.version?{version:t.version,engineVersion:Rv}:void 0;for(let o of $f(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"}}se();import{getSession as Sv}from"document360-engine";async function Rf(e,t){let n=t.currentUuid(),o=n?Sv(n):void 0;return console.log(o?m(`
|
|
303
303
|
(conversation reset \u2014 "${o.name}" is still available via /resume)
|
|
304
304
|
`):m(`
|
|
305
305
|
(conversation reset \u2014 agent will start fresh on the next prompt)
|
|
306
|
-
`)),{kind:"clear"}}async function
|
|
306
|
+
`)),{kind:"clear"}}async function Cc(){return{kind:"exit"}}zi();se();import{readMcpConfig as Ic,writeMcpConfig as Kf}from"document360-engine";async function Xi(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(Wv(),{kind:"continue"}):t==="add"?(Bv(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(Hv(e.slice(1)),{kind:"continue"}):(console.log(_(`Unknown /mcp subcommand: ${t}`)),console.log(m("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function Wv(){let e=Ic(),t=Object.keys(e.servers);if(t.length===0){console.log(m(`
|
|
307
307
|
No MCP servers registered. Add one with /mcp add <name> <type> <ref>
|
|
308
|
-
`));return}console.log(""),console.log("Registered MCP servers (~/.document360-writer/mcp.json):");for(let n of t){let o=e.servers[n];if(o.type==="stdio")console.log(` ${Z(n)} ${m("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?m(` [headers: ${r.join(", ")}]`):"";console.log(` ${Z(n)} ${m(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function
|
|
308
|
+
`));return}console.log(""),console.log("Registered MCP servers (~/.document360-writer/mcp.json):");for(let n of t){let o=e.servers[n];if(o.type==="stdio")console.log(` ${Z(n)} ${m("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?m(` [headers: ${r.join(", ")}]`):"";console.log(` ${Z(n)} ${m(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function Bv(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(_("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(_(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=Ic(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let i={};for(let a=1;a<o.length;a++)if(o[a]==="-H"||o[a]==="--header"){let l=o[++a],d=l?.match(/^([^:=]+)[:=](.+)$/);if(!d){console.log(_(`-H expects key:value (no spaces). Got: ${l??"(nothing)"}`));return}i[d[1].trim()]=d[2].trim()}else{console.log(_(`Unexpected argument: ${o[a]}. After the URL, only -H key:value is allowed.`));return}s={type:n,url:o[0],headers:Object.keys(i).length>0?i:void 0}}r.servers[t]=s,Kf(r),console.log(""),console.log(Y(`\u2713 Registered "${t}" (${n})`)),console.log(V(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(m(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function Hv(e){let t=e[0];if(!t){console.log(_("Usage: /mcp remove <name>"));return}let n=Ic();if(!n.servers[t]){console.log(_(`No server named "${t}".`));return}delete n.servers[t],Kf(n),console.log(Y(`\u2713 Removed "${t}".`)),console.log(m(" Run /clear to drop it from the current session immediately."))}se();import{readFileSync as b0}from"node:fs";import{join as k0}from"node:path";import{select as $0}from"@inquirer/prompts";import{computeSyncStatus as ga,planPartitions as v0,relatedArticlePaths as x0,loadProfileMap as Jm,draftPendingPaths as R0,resolveActiveProfile as uu,unreviewedPaths as S0,styleErrorPaths as Zm,publishGateVerdict as C0,publishGateLines as P0,pushArticles as T0,pushArticle as A0,PUSH_POOL_SIZE as E0,SKIP_STYLE_FLAG as D0,listArticleFiles as eg,docsRootOf as N0,ensureFeedbackChannel as j0,FEEDBACK_CATEGORY_NAME as zm,resolveCrossLinks as I0,applyStructureOrder as tg,orderSyncLine as ng,applyRelatedArticles as og,relatedSyncLine as rg}from"document360-engine";import{readFileSync as Gv}from"node:fs";import{resolve as qv}from"node:path";import{prettyFolderName as zf}from"document360-engine";var Nn=zf;function Qi(e){return e.replace(/\\/g,"/").split("/").slice(0,-1).join("/")}function bs(e){let t=e.replace(/\\/g,"/").split("/").pop()??e;return zf(t.replace(/\.md$/i,""))}function Ji(e,t){try{return/^#\s+(.+)$/m.exec(Gv(qv(e,t),"utf8"))?.[1]?.trim()??null}catch{return null}}import{resolveActiveProfile as Xf,loadTokens as Qf,isExpired as _c,listStoredSessions as Vv,tokensProjectId as Oc}from"document360-engine";function Zi(e,t){try{let n=Xf(e,t),o=Qf(n.name,n.project.projectId);return!o||_c(o)?!1:Ve(e,t).ok}catch{return!1}}function Yv(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function Lc(e,t){return t?`"${t}"`:e?Yv(e):"this project"}function Kv(e,t){return t?Vv(e).filter(n=>{let o=Oc(n);return!!o&&o!==t&&!(_c(n)&&!n.refreshToken)}):[]}function Ve(e,t){try{let n=Xf(e,t),o=n.project.projectId,r=Lc(o,n.project.projectName),s=Qf(n.name,o);if(!s){let a=Kv(n.name,o);return a.length>0?{ok:!1,reason:`You're signed in to Document360 project ${a.map(d=>Lc(Oc(d)??void 0,d.projectName)).join(", ")}, and this repo's docs live in ${r}. A sign-in covers one project, so ${r} needs its own \u2014 run /login and pick it. Both stay signed in after that, so switching between repos won't ask again.`}:{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`}}if(_c(s)&&!s.refreshToken)return{ok:!1,reason:`Your Document360 session for ${r} expired. Run /login.`};let i=Oc(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 ${Lc(i,s.projectName)}). Run /login and pick ${r}.`}:{ok:!0}}catch{return{ok:!0}}}import{existsSync as gm,readFileSync as Qc}from"node:fs";import{isAbsolute as ra,join as sa,resolve as ia}from"node:path";import O from"picocolors";import na from"string-width";import{readProjectConfig as In,screenshotPlaceholderIds as wm,screenshotMarkerProblemsInDocs as yx,DEFAULT_CAPTURE_DIR as aa,DEFAULT_OUTPUT_DIR as Jc,DEFAULT_DOCS_DIR as Zc,resolveOutputDir as ym,migrateShotLayout as bx,reviewIsCurrent as kx,anchorPresent as $x,annotationCurrent as vx,captureLanded as xx,shotArtifacts as Rx,RAW_SUBDIR as Sx,ANNOTATED_SUBDIR as Cx}from"document360-engine";import{createHash as Mc}from"node:crypto";import{readFileSync as Zf,writeFileSync as zv}from"node:fs";import{join as Xv}from"node:path";import{captureStatePath as em}from"document360-engine";var Jf={version:1,shots:{}};function Qv(e){return e.replace(/^/,"").replace(/\r\n?/g,`
|
|
309
309
|
`).replace(/\n+$/,`
|
|
310
|
-
`)}function
|
|
311
|
-
`,"utf8")}function
|
|
312
|
-
${a[1]??" "}clipTo: ${l}${i.selector}${l},`);return d=d.replace(o,`${r}await captureShot(page, PLACEHOLDER);`),d=d.replace(
|
|
310
|
+
`)}function tm(e){return Mc("sha1").update(Qv(e)).digest("hex").slice(0,12)}function Jv(e){return Mc("sha1").update(e).digest("hex").slice(0,12)}function ea(e){try{let t=JSON.parse(Zf(Xv(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 Mc("sha1").update(`${o}|${r?.connection?.startUrl??""}|${i}`).digest("hex").slice(0,12)}catch{return null}}function gn(e){try{let t=JSON.parse(Zf(em(e),"utf8").replace(/^/,""));return!t||typeof t!="object"||t.version!==1||!t.shots?{...Jf,shots:{}}:{version:1,shots:t.shots}}catch{return{...Jf,shots:{}}}}function Zv(e,t){zv(em(e),`${JSON.stringify(t,null,2)}
|
|
311
|
+
`,"utf8")}function Fc(e){return e&&/data-testid|\btest-?id\b|has(?:n't| not) landed/i.test(e)?"testid":"data"}function ta(e,t,n){if(t.length===0)return;let o=gn(e),r=ea(e);for(let s of t){let i=s.specSource?tm(s.specSource):void 0;o.shots[s.id]={outcome:s.outcome,at:n,...s.reason?{reason:s.reason}:{},...s.outcome==="skipped"?{blockedBy:Fc(s.reason)}:{},...i?{specHash:i}:{},...r?{envHash:r}:{}}}Zv(e,o)}function Uc(e,t,n,o){let r=e.shots[t];return!r||n===null||!r.specHash||r.specHash!==tm(n)&&r.specHash!==Jv(n)||o&&r.envHash&&r.envHash!==o?null:r}function nm(e){let t=gn(e).shots;return Object.keys(t).filter(n=>t[n].outcome==="failed").sort()}function Wc(e,t,n){let o=Uc(gn(e),t,n,ea(e));return!o||o.outcome==="captured"||!o.reason?null:{outcome:o.outcome,reason:o.reason}}ur();import{existsSync as rx,readFileSync as im,readdirSync as am,writeFileSync as sx}from"node:fs";import{isAbsolute as ix,join as lm,resolve as ax}from"node:path";import{readProjectConfig as lx,DEFAULT_CAPTURE_DIR as cx}from"document360-engine";var sm="0.2.25";function dr(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 ux=/^([ \t]*)await\s+([^\n;]+?)\.screenshot\(\{\s*path:\s*PLACEHOLDER\.saveTo\s*(?:,\s*fullPage:\s*(?:true|false)\s*)?,?\s*\}\)\s*;?[ \t]*$/m,dx=/^[ \t]*await\s+dumpAnnotations\(\s*page\s*,\s*PLACEHOLDER\s*\)\s*;?[ \t]*\r?\n?/m,cm="(?:'([^']+)'|\"([^\"]+)\"|`([^`]+)`)",px=new RegExp(`^page\\s*\\.\\s*locator\\(\\s*${cm}\\s*\\)$`),um=e=>e[1]??e[2]??e[3]??null,hx=/^[A-Za-z_$][\w$]*$/;function fx(e,t){let o=new RegExp(`\\bconst\\s+${t}\\s*=\\s*page\\s*\\.\\s*locator\\(\\s*${cm}\\s*\\)\\s*;`).exec(e);return o?um(o):null}function mx(e,t){let n=t.trim();if(n==="page")return null;let o=px.exec(n);if(o){let r=um(o);return r?{selector:r}:{unresolved:!0}}if(hx.test(n)){let r=fx(e,n);return r?{selector:r}:{unresolved:!0}}return{unresolved:!0}}function dm(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=ux.exec(e);if(!n)return null;let[o,r="",s=""]=n,i=mx(e,s);if(i===null)return null;if("unresolved"in i)return{unresolved:s.trim()};let a=/^([ \t]*)saveTo:\s*.+,[ \t]*$/m.exec(e);if(!a)return null;let l=i.selector.includes("'")?'"':"'",d=e.replace(a[0],`${a[0]}
|
|
312
|
+
${a[1]??" "}clipTo: ${l}${i.selector}${l},`);return d=d.replace(o,`${r}await captureShot(page, PLACEHOLDER);`),d=d.replace(dx,""),d=d.replace(/\bdumpAnnotations\b(?=[^\n]*from 'document360-capture\/helpers')/,"captureShot"),/from 'document360-capture\/helpers'/.test(d)&&!/\bcaptureShot\b[^\n]*from 'document360-capture\/helpers'/.test(d)&&(d=d.replace(/import \{([^}]*)\} from 'document360-capture\/helpers'/,(w,g)=>`import {${g.replace(/\s*$/,"")}, captureShot } from 'document360-capture/helpers'`)),{next:d,selector:i.selector}}function gx(e){try{return am(e).filter(t=>t.endsWith(".spec.ts")).some(t=>{try{let n=dm(im(lm(e,t),"utf8"));return n!==null&&!("unresolved"in n)}catch{return!1}})}catch{return!1}}function wx(e){let t=lx(e)?.captureDir??cx;return ix(t)?t:ax(e,t)}function pm(e,t){let n={migrated:[],skipped:[]},o=wx(e);if(!rx(o))return n;let r=t?.captureVersion===void 0?mt():t.captureVersion;if(!dr(r,sm))return gx(o)?{...n,heldBackForCapture:{installed:r,required:sm}}:n;let s;try{s=am(o).filter(i=>i.endsWith(".spec.ts"))}catch{return n}for(let i of s.sort()){let a=i.slice(0,-8),l=lm(o,i);try{let d=im(l,"utf8"),w=dm(d);if(w===null)continue;if("unresolved"in w){n.skipped.push({id:a,receiver:w.unresolved});continue}sx(l,w.next,"utf8"),n.migrated.push(a)}catch{}}return n}function hm(e){if(e.heldBackForCapture){let{installed:n,required:o}=e.heldBackForCapture;return`\u26A0 Some capture specs need a fix that requires d360-capture ${o}+ (${n?`you have ${n}`:"not found on this machine"}). Until then their callouts may sit in the wrong place on cropped screenshots.
|
|
313
313
|
Run /update to bring the whole toolchain up, then /screenshot again.`}if(e.migrated.length===0&&e.skipped.length===0)return null;let t=[];return e.migrated.length>0&&t.push(`\u2195 Fixed ${e.migrated.length} capture spec${e.migrated.length===1?"":"s"} that cropped the screenshot without telling the annotator \u2014 their callouts were landing outside the image. Re-capture to pick up the fix.`),e.skipped.length>0&&t.push(`\u26A0 ${e.skipped.length} spec${e.skipped.length===1?"":"s"} crop${e.skipped.length===1?"s":""} to something that needs a human eye (${e.skipped.slice(0,3).map(n=>n.id).join(", ")}${e.skipped.length>3?"\u2026":""}) \u2014 /screenshot verify flags them if their callouts are off.`),t.join(`
|
|
314
|
-
`)}function Re(e,t,n){return`${e}${n?` ${n}`:""}${t?` ${t}`:""}`}function
|
|
315
|
-
`):null}function
|
|
316
|
-
`))||o.push(r+1));return o}function
|
|
314
|
+
`)}function Re(e,t,n){return`${e}${n?` ${n}`:""}${t?` ${t}`:""}`}function Zt(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}ur();var bm=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function fm(e){let t=e.includes("--detail")||e.includes("-d"),n=e.find(o=>o!=="--detail"&&o!=="-d");return{mode:"list",scope:n?bm(n):void 0,...t?{detail:!0}:{}}}function ks(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 fm(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 fm(o.slice(1));let r=o[0];return r?r==="--all"?{mode:"all",setup:n}:/[\\/]/.test(r)||r.endsWith(".md")?{mode:"scope",scope:bm(r),setup:n}:{mode:"single",id:r}:{mode:"list",picker:!0}}function Fe(e,t,n){let o=In(e),r=o?.captureDir??aa,s=o?.outputDir??Jc,i=(g,$)=>ra(g)?sa(g,$):ia(e,g,$),a=gn(e),l=n?.captureVersion===void 0?mt():n.captureVersion,d=dr(l,xm),w=ea(e);return wm(e,{scope:t}).map(({id:g,file:$})=>{let P=i(r,`${g}.spec.ts`),C=null;if(gm(P))try{C=Qc(P,"utf8")}catch{}let R=ym(e,s),T=Rx(R,g),D=vx(T),N=xx(T),B=C===null?null:Uc(a,g,C,w),I=a.shots[g]?.review,X=D&&kx(I,T.annotatedMtimeMs)?I:void 0,q=C!==null&&Ax(C),de=D&&X?.verdict==="ok"?"verified":D&&X?.verdict==="rejected"?"rejected":D?"annotated":N?"captured":C===null?"placeholder":q||B?.outcome==="skipped"?"blocked":B?.outcome==="failed"?"broken":"spec",ve=C===null?void 0:$m(C),Se=q?Dx(C):B?.reason,Te=q?"testid":B?.outcome==="skipped"?Fc(B.reason):void 0,he=C===null?[]:Ex(e,C);return{id:g,file:$,state:de,...ve?{mutates:ve.mutates,...ve.declared?{}:{undeclared:!0}}:{},...C!==null&&Gc(C).length>0?{unguardedWaits:Gc(C)}:{},...C!==null&&Hc(C).length>0?{unverifiedForce:Hc(C)}:{},...C!==null&&qc(C).length>0?{handRolled:qc(C)}:{},...C!==null&&Yc(C).length>0?{stalePause:Yc(C)}:{},...C!==null&&d&&Vc(C).length>0?{bareGoto:Vc(C)}:{},...he.length>0?{staleAnchor:he}:{},...de==="blocked"||de==="broken"?{...Se?{reason:Se}:{},...Te?{blockedBy:Te}:{}}:{},...de==="rejected"?{...X?.reason?{reason:X.reason}:{},...X?.repaired?{repaired:!0}:{}}:{}}})}function Px(e){let t=In(e)?.outputDir??Jc;return bx(ym(e,t))}function mo(e){let t=Px(e),n=In(e)?.outputDir??Jc,o=[];t>0&&o.push(`\u2195 Tidied ${t} screenshot file${t===1?"":"s"} into ${n}/{${Sx},${Cx}} \u2014 annotated/ is what publishes, raw/ is the pre-annotation intermediate.`);let r=hm(pm(e));return r&&o.push(r),o.length>0?o.join(`
|
|
315
|
+
`):null}function go(e,t){let n=In(e)?.captureDir??aa,o=ra(n)?sa(n,`${t}.spec.ts`):ia(e,n,`${t}.spec.ts`);try{return Qc(o,"utf8")}catch{return null}}function km(e,t){let n=In(e)?.captureDir??aa;return gm(ra(n)?sa(n,`${t}.spec.ts`):ia(e,n,`${t}.spec.ts`))}function Tx(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 $m(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=Tx(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 Ax(e){return/(^|\n)\s*test\.skip\s*\(\s*['"`]/.test(e)}function vm(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 Ex(e,t){let n=[];for(let o of vm(t))$x(e,o.file,o.anchor)===!1&&n.push(o.testid??o.file??"unnamed request");return[...new Set(n)]}function Dx(e){let{testid:t,file:n}=vm(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 $s(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 Hc(e,t=10){let n=$s(e),o=[];for(let[r,s]of n.entries())/\.click\s*\([^)]*force\s*:\s*true/.test(s)&&(/test\.skip\s*\(/.test(n.slice(r+1,r+1+t).join(`
|
|
316
|
+
`))||o.push(r+1));return o}function Gc(e){let t=[],n=$s(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 qc(e){let t=[];for(let[n,o]of $s(e).entries())(/\.screenshot\s*\(/.test(o)||/\bdumpAnnotations\s*\(/.test(o))&&t.push(n+1);return t}var xm="0.2.28";function Vc(e){let t=[];for(let[n,o]of $s(e).entries())/\.goto\s*\(/.test(o)&&t.push(n+1);return t}function Yc(e,t=6){let n=$s(e),o=[];for(let[r,s]of n.entries()){if(!/waitForTimeout\s*\(/.test(s))continue;let i=n.slice(r+1,r+1+t).join(`
|
|
317
317
|
`);if(!/test\.skip\s*\(/.test(i)||!/\.count\s*\(\s*\)/.test(i))continue;let a=n.slice(Math.max(0,r-t),r+1).join(`
|
|
318
|
-
`);/\.waitFor\s*\(|Promise\.race\s*\(|waitForFunction\s*\(|waitForSelector\s*\(/.test(a)||o.push(r+1)}return o}function
|
|
319
|
-
`)}function
|
|
320
|
-
`)}var Nx={placeholder:"\u25CB",spec:"\u25D0",blocked:"\u2298",broken:"\u2717",captured:"\u25CF",annotated:"\u25C8",verified:"\u2714",rejected:"\u2691"},jx={placeholder:O.gray,spec:O.yellow,blocked:O.cyan,broken:O.red,captured:O.yellow,annotated:O.blue,verified:O.green,rejected:O.magenta},Ix=` ${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 J(e,t=n=>n){return`${t(e)} `}function pr(e){return e.replace(/\s+/g," ").trim().replace(/^Prerequisites? not met[:—-]?\s*/i,"")}function ca(e){let t=pr(e),n=/^(.*?[a-z0-9)"'”’])\.(?:\s|$)/i.exec(t);return(n?n[1]:t).trim()}function ks(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=ca(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 Rm(e){let t=ks(e);if(t.length===0)return[];let n=t.filter(s=>s.blockedBy==="data"),o=t.filter(s=>s.blockedBy==="testid"),r=[""];if(n.length>0){let s=n.reduce((a,l)=>a+l.ids.length,0);r.push(` ${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 l=Qt(a.reason,86);r.push(` ${O.cyan(Nn(`${a.ids.length}\xD7`,4))} ${l[0]??""}`);for(let w of l.slice(1))r.push(` ${w}`);let d=a.ids.slice(0,4).join(" \xB7 ");r.push(O.gray(` ${d}${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(` ${J("\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 Jc(e){if(e.length===0)return[];let t=e.slice(0,6),n=e.length;return["",` ${J("\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 Sm(e,t){let n=e.filter(i=>(i.staleAnchor?.length??0)>0);if(n.length===0)return[];let o=[...new Set(n.flatMap(i=>i.staleAnchor))],r=o.length,s=["",` ${J("\u26A0",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 Cm(e,t,n){let o=e.filter(w=>(w.unguardedWaits?.length??0)>0),r=e.filter(w=>w.undeclared),s=e.filter(w=>(w.handRolled?.length??0)>0),i=e.filter(w=>(w.stalePause?.length??0)>0),a=e.filter(w=>(w.bareGoto?.length??0)>0);if(o.length===0&&r.length===0&&s.length===0&&i.length===0&&a.length===0)return[];let l=["",` ${J("\u26A0",O.yellow)}Some specs were written before later reliability fixes:`],d=(w,g)=>` ${w.slice(0,8).map(g).join(" \xB7 ")}${w.length>8?` \xB7 +${w.length-8} more`:""}`;if(o.length>0){let w=o.length;l.push(O.gray(` ${w} crash${w===1?"es":""} instead of telling you what to stage when the data ${w===1?"it needs":"they need"} is missing`)),t&&l.push(O.gray(d(o,g=>`${g.id}:${g.unguardedWaits.join(",")}`)))}if(a.length>0){let w=a.length;l.push(O.gray(` ${w} open${w===1?"s":""} pages the slow way, so ${w===1?"it stalls":"they stall"} for a minute and give up when several shots run at once`)),t&&l.push(O.gray(d(a,g=>`${g.id}:${g.bareGoto.join(",")}`)))}if(i.length>0){let w=i.length;l.push(O.gray(` ${w} decide${w===1?"s":""} "the data is missing" from a fixed pause, so data you HAVE staged can read as absent`)),t&&l.push(O.gray(d(i,g=>`${g.id}:${g.stalePause.join(",")}`)))}if(s.length>0){let w=s.length;l.push(O.gray(` ${w} take${w===1?"s":""} ${w===1?"its":"their"} own screenshot instead of the one call that positions the callouts too \u2014 on a cropped shot the numbers land in the wrong places, and nothing reports it`)),t&&l.push(O.gray(d(s,g=>`${g.id}:${g.handRolled.join(",")}`)))}if(r.length>0){let w=r.length,g=r.filter($=>$.mutates).length;l.push(O.gray(` ${w} do${w===1?"es":""} not say whether ${w===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&&l.push(O.gray(d(r,$=>$.id)))}return n?.commandInLead||l.push(O.gray(` Re-write them all with the current rules: ${O.bold("/screenshot author --all")}`)),l}function Pm(e){let t=e.filter(n=>(n.unverifiedForce?.length??0)>0);return t.length===0?[]:["",` ${J("\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 ta=(e,t)=>e.length>=t?e:e+" ".repeat(t-e.length),Nn=(e,t)=>e.length>=t?e:" ".repeat(t-e.length)+e;function Tm(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 Lx=new Set(["and","or","of","the","to","a","an","in","on","for","with","vs"]),Ox=new Set(["ai","api","cli","ui","ux","url","id","http","https","json","xml","sdk","csv","pdf","oauth","sso","mfa","io","faq"]);function _x(e){return e.replace(/[-_]+/g," ").trim().split(/\s+/).filter(Boolean).map((n,o)=>{let r=n.toLowerCase();return Ox.has(r)?r.toUpperCase():o>0&&Lx.has(r)?r:r.charAt(0).toUpperCase()+r.slice(1)}).join(" ")}function qc(e){if(!e)return{num:"",name:"(docs root)"};let t=/^(\d+)[-_](.+)$/.exec(e);return{num:t?t[1]:"",name:_x(t?t[2]:e)}}function Mx(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).pop()??e}function pm(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 Fx(e,t){let n=t>0?Math.round(e/t*100):0,o=Nn(`${n}%`,4);return n===100?O.green(o):n>0?O.yellow(o):O.gray(o)}function Am(e,t){let n=new Map;for(let o of e){let r=Tm(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 Zc(e,t){let n=T=>e.filter(D=>D.state===T).length,o=n("captured"),r=n("placeholder"),s=n("spec"),i=n("annotated"),a=n("blocked"),l=n("broken"),d=n("rejected"),w=e.filter(T=>T.state==="spec"&&T.mutates).length,g=s>w,$=e.filter(T=>(T.unguardedWaits?.length??0)>0||(T.bareGoto?.length??0)>0).length,P=e.filter(T=>(T.stalePause?.length??0)>0||(T.handRolled?.length??0)>0).length,C=s>0||a>0||l>0,R=(T,D="")=>Re(T,D,t);return o>0?{key:"annotate",cmd:R("/screenshot annotate")}:r>0?{key:"toSpec",cmd:t?`/screenshot author ${t}`:"/screenshot author --all"}:$>0&&C?{key:"crashy",cmd:t?`/screenshot author ${t}`:"/screenshot author --all"}:P>0&&C?{key:"wrongOutput",cmd:t?`/screenshot author ${t}`:"/screenshot author --all"}:s>0&&(g||i===0)?{key:"ready",cmd:R("/screenshot capture")}:i>0&&s>0?{key:"verify",cmd:R("/screenshot verify")}:a>0?{key:"blocked",cmd:R("/screenshot capture","--blocked")}:l>0?{key:"broken",cmd:`/screenshot ${e.find(T=>T.state==="broken").id}`}:i>0?{key:"verify",cmd:R("/screenshot verify")}:d>0?{key:"rejected",cmd:R("/screenshot capture","--failed")}:{key:"done",cmd:t?`/push ${t}`:"/push"}}function Ux(e,t,n=[]){let o=(te,Le)=>te.filter(Ne=>Ne.state===Le).length,r=e.length,s=o(e,"verified"),i=o(e,"annotated"),a=o(e,"captured"),l=o(e,"rejected"),d=o(e,"spec"),w=o(e,"blocked"),g=o(e,"broken"),$=o(e,"placeholder"),P=new Set(e.map(te=>te.file)).size,C=Am(e,t),R=[];R.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`)}`:"")+(l>0?` ${O.gray("\xB7")} ${O.magenta(`${l} rejected`)}`:"")+` ${O.gray("\xB7")} ${d>0?O.yellow(`${d} ready`):O.gray("0 ready")}`+(w>0?` ${O.gray("\xB7")} ${O.cyan(`${w} 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 ${P} article${P===1?"":"s"}`));let T=r>0?Math.round(s/r*100):0;R.push(` [${pm(s,r,32)}] ${O.bold(`${T}%`)}`),R.push("");let D=C.map(([te])=>qc(te)),N=Math.min(32,Math.max(7,...D.map(te=>te.name.length))),W=te=>te.length>N?`${te.slice(0,N-1)}\u2026`:ta(te,N),I=[...a>0?[{head:"To annotate",w:11,state:"captured",color:O.yellow}]:[],...i>0?[{head:"To verify",w:9,state:"annotated",color:O.blue}]:[],...l>0?[{head:"Rejected",w:8,state:"rejected",color:O.magenta}]:[],{head:"Ready",w:5,state:"spec",color:O.yellow},...w>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}];R.push(O.gray(` ${ta("#",2)} ${ta("Chapter",N)} ${Nn("Verified",8)} ${I.map(te=>Nn(te.head,te.w)).join(" ")} Progress`));for(let[te,[,Le]]of C.entries()){let Ne=o(Le,"verified"),Ce=Le.length,{num:ze,name:zt}=D[te],rt=Ne===Ce,jt=W(zt),Do=I.map(It=>{let on=o(Le,It.state);return on>0?It.color(Nn(String(on),It.w)):O.gray(Nn("\u2014",It.w))}).join(" ");R.push(` ${O.cyan(ta(ze,2))} ${rt?O.green(jt):Ne>0?jt:O.gray(jt)} ${rt?O.green(Nn(`${Ne}/${Ce}`,8)):Nn(`${Ne}/${Ce}`,8)} ${Do} ${pm(Ne,Ce,10)} ${Fx(Ne,Ce)}`)}R.push("");let X=g>0?` ${O.gray("\xB7")} ${g} spec${g===1?"":"s"} broken \u2014 ${O.bold(`/screenshot ${e.find(te=>te.state==="broken").id}`)} re-authors ${g===1?"it":"the first"}`:"",H=e.filter(te=>te.state==="spec"&&te.mutates).length,de=d>H,ve=e.filter(te=>(te.unguardedWaits?.length??0)>0||(te.bareGoto?.length??0)>0).length,Se=e.filter(te=>(te.stalePause?.length??0)>0||(te.handRolled?.length??0)>0).length,Te=d>0||w>0||g>0,he=!1,ie=Zc(e).key;if(ie==="annotate")R.push(` ${J("\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`)+X);else if(ie==="toSpec")R.push(` ${J("\u2192",O.yellow)}${$} placeholder${$===1?"":"s"} still need a spec \u2014 run ${O.bold("/screenshot author --all")}${X}`);else if(ie==="crashy")he=!0,R.push(` ${J("\u2192",O.yellow)}${ve} spec${ve===1?"":"s"} would crash mid-run \u2014 re-write ${ve===1?"it":"them"} first: ${O.bold("/screenshot author --all")}`+O.gray(` \xB7 then ${O.bold("/screenshot capture")} (no browser time wasted on ${ve===1?"a shot":"shots"} that can't finish)`)+X);else if(ie==="wrongOutput")he=!0,R.push(` ${J("\u2192",O.yellow)}${Se} spec${Se===1?"":"s"} would shoot the wrong thing \u2014 re-write ${Se===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)`)+X);else if(ie==="ready"){let te=H>0?O.gray(` \u2014 ${d-H} in one go; ${H} write${H===1?"s":""} real data and run${H===1?"s":""} one at a time`):"";R.push(` ${J("\u2192",O.yellow)}${d} spec${d===1?"":"s"} ready to capture \u2014 run ${O.bold("/screenshot capture")}${te}${X}`)}else if(ie==="verify"&&d>0)R.push(` ${J("\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 ${d} ready spec${d===1?"":"s"} write real data, so ${d===1?"it runs":"each runs"} only when named: /screenshot capture <id>`)+X);else if(ie==="blocked")R.push(` ${J("\u2192",O.cyan)}${w} shot${w===1?"":"s"} blocked \u2014 stage the data below, then ${O.bold("/screenshot capture --blocked")}${X}`);else if(ie==="broken")R.push(` ${J("\u2192",O.red)}${g} spec${g===1?"":"s"} broken \u2014 ${O.bold(`/screenshot ${e.find(te=>te.state==="broken").id}`)} re-authors ${g===1?"it":"the first"} (re-capturing fails the same way)`);else if(ie==="verify")R.push(` ${J("\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(ie==="rejected"){let te=e.filter(Le=>Le.state==="rejected"&&Le.repaired).length;R.push(` ${J("\u2691",O.magenta)}${l} shot${l===1?"":"s"} failed review \u2014 `+(te>0?`${te} spec${te===1?"":"s"} already repaired; re-capture with ${O.bold("/screenshot capture --failed")}`:`see the reasons below, then ${O.bold("/screenshot capture --failed")}`))}else R.push(` ${J("\u2713",O.green)}all ${r} verified \u2014 ${O.bold("/push")} embeds them in the articles`);if(s>0&&s<r){let te=C.filter(([,Le])=>Le.every(Ne=>Ne.state!=="verified")).map(([Le])=>{let{num:Ne,name:Ce}=qc(Le);return Ne?`${Ne} ${Ce}`:Ce});te.length>0&&R.push(O.gray(` Furthest behind: ${te.slice(0,5).join(" \xB7 ")}${te.length>5?" \u2026":""} (0% verified)`))}return R.push(...Rm(e),...Pm(e),...Cm(e,!1,{commandInLead:he}),...Sm(e,!1),...Jc(n)),R.push(""),R.push(O.gray(" Drill in: /screenshot list <chapter#> \xB7 /screenshot list --detail (all)")),R}function Wx(e,t,n,o=[]){let r=new Set(e.map(d=>d.file)),s=e.filter(d=>d.state==="verified").length,i=e.filter(d=>d.state==="annotated").length,a=e.filter(d=>d.state==="captured").length,l=[` ${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[d,w]of Am(e,t)){let g=w.filter(T=>T.state==="verified").length,{num:$,name:P}=qc(d),C=$?`${$} \xB7 ${P}`:P;l.push(` ${O.bold(C)} ${O.gray(`(${g}/${w.length})`)}`);let R=new Map;for(let T of w){let D=Mx(T.file),N=R.get(D)??[];R.has(D)||R.set(D,N),N.push(T)}for(let T of[...R.keys()].sort()){l.push(O.gray(` ${T}`));for(let D of R.get(T)){let N=jx[D.state];if(l.push(` ${J(Nx[D.state],N)}${N(D.id)}`),(D.state==="blocked"||D.state==="broken"||D.state==="rejected")&&D.reason){for(let W of Qt(pr(D.reason),84))l.push(O.gray(` ${W}`));D.state==="rejected"&&l.push(O.gray(` ${D.repaired?"spec repaired \u2014 re-capture to confirm":"spec not yet repaired"}`))}}}}return l.push(...Rm(e),...Pm(e),...Cm(e,!0),...Sm(e,!0),...Jc(o)),l.push("",Ix),l}function ua(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.",...Jc(o)];let r=t?.docsDir??Xc;return t?.detail||n?Wx(e,r,n,o):Ux(e,r,o)}function eu(e,t){if(!t||!/^\d+$/.test(t))return t;let n=jn(e)?.docsDir??Xc,o=String(Number(t));for(let{file:r}of fm(e)){let s=Tm(r,n),i=/^(\d+)/.exec(s);if(i&&String(Number(i[1]))===o)return s}return t}function Em(e,t){let r=e.map(a=>" ".repeat(a.depth)+a.label),s=Math.max(0,...e.map((a,l)=>a.note?ea(r[l]):0)),i=Math.min(s,Math.max(0,t-2-24));return e.map((a,l)=>{let d=r[l];if(!a.note)return{head:d,note:""};let w=Math.max(2,i+2-ea(d)),g=a.note.trim(),$=t-ea(d)-w;return{head:d+" ".repeat(w),note:$>1&&ea(g)>$?`${g.slice(0,$-1)}\u2026`:g}})}function Bx(e){let t=e.replace(/\\/g,"/").split("/").filter(Boolean),n=t.pop()??e;return{category:t.pop()??"(docs root)",article:n}}function dr(e,t,n){let o=new Map;for(let s of t){let{category:i,article:a}=Bx(s.file),l=o.get(i)??new Map;o.set(i,l);let d=l.get(a)??[];l.set(a,d),d.push(s)}let r=s=>n!=="capture"||!s.mutates;for(let s of[...o.keys()].sort()){let i=o.get(s),a=[...i.values()].flat().filter(r).map(d=>d.id),l=a.length>0;l&&e.push({kind:"category",action:n,label:`${s} (${a.length})`,ids:a,depth:1});for(let d of[...i.keys()].sort()){let w=i.get(d),g=w.filter(r).map(C=>C.id),$=g.length>0;$&&e.push({kind:"article",action:n,label:`${d} (${g.length})`,ids:g,depth:l?2:1});let P=(l?1:0)+($?1:0)+1;for(let C of w){let R=n==="capture"&&C.mutates?" \u26A0 creates real data \u2014 runs only alone":void 0;e.push({kind:"shot",action:n,label:C.id,ids:[C.id],depth:P,...R?{note:R}:{}})}}}}function Fc(e){return e?pr(e):""}function tu(e,t,n,o=[]){let r=t.filter(i=>!i.mutates);r.length>1&&e.push({kind:"all",action:"capture",label:`Retry ${r.length} blocked shots (Prerequisites not met \u2014 Stage the data first)`,ids:r.map(i=>i.id),depth:0});for(let i of[...t].sort((a,l)=>a.id.localeCompare(l.id)))e.push({kind:"shot",action:"capture",label:i.id,ids:[i.id],depth:1,note:` \u2298 ${Fc(i.reason)}`});n.length>1&&e.push({kind:"all",action:"author",label:`Re-author ${n.length} broken specs`,ids:n.map(i=>i.id),depth:0});for(let i of[...n].sort((a,l)=>a.id.localeCompare(l.id)))e.push({kind:"shot",action:"author",label:i.id,ids:[i.id],depth:1,note:` \u2717 re-authors \u2014 ${Fc(i.reason)}`});let s=o.filter(i=>!i.mutates);s.length>1&&e.push({kind:"all",action:"capture",label:`Re-capture ${s.length} shots that failed review`,ids:s.map(i=>i.id),depth:0});for(let i of[...o].sort((a,l)=>a.id.localeCompare(l.id))){let a=i.repaired?"re-captures":"re-captures (spec not yet repaired)";e.push({kind:"shot",action:"capture",label:i.id,ids:[i.id],depth:1,note:` \u2691 ${a} \u2014 ${Fc(i.reason)}`})}}function Dm(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}),dr(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}),dr(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}),dr(o,s,"annotate"),tu(o,e.filter(i=>i.state==="blocked"),e.filter(i=>i.state==="broken"),e.filter(i=>i.state==="rejected")),o}var Vc=["MANDATORY \u2014 a missing prerequisite must SKIP, never time out. Two rules, applied to EVERY locator","in the spec, not just the first one or the one shown in the skill's example:","1. A bare `await x.waitFor(...)` is itself the bug: on a missing element it THROWS and the run"," reports a hard failure with a stack trace instead of a staging instruction. Every wait must be",' `await x.waitFor({ state: "visible", timeout: 10_000 }).catch(() => {});` followed by',' `if ((await x.count()) === 0) test.skip(true, "Prerequisite not met: \u2026")`. That applies to each'," element you wait on or click IN TURN \u2014 tabs, toggles, rows, buttons reached after the first"," guard \u2014 because any of them can be absent for the same reason the data is."," And guard on the SAME predicate the action needs: `.click()` requires visible AND ENABLED, so a",' DISABLED button passes both waitFor({state:"visible"}) and count()>0 and then times out at 15s'," (measured). Add `|| !(await x.isEnabled().catch(() => false))` to the condition, and put the"," control's own title/aria-disabled text in the skip reason \u2014 a disabled control is the product"," telling you the prerequisite is unmet, usually with the reason attached.",' And when a wait DOES time out, diagnose before you guard: a skip asserts "your app lacks this',' data", so if the real cause is a locator matching a node you did not intend (a rollup row, a'," sibling with the same testid), that assertion is a lie and sends the user to stage what they"," already have. Narrow the selector first, THEN guard."," Two corollaries, both of which have cost a wasted repair round:"," (a) An element that is not RENDERED is not absent. A collapsed tree node, an unopened accordion,"," an inactive tab, a virtualised list or page 2 of a table keeps its children out of the DOM."," EXPAND/scroll/switch to reach the target \u2014 that is a step to script, not data to stage."," (b) When you narrow past a decoy, count the UNNARROWED set too and put the number in the reason:",' "Found 6 folder roll-ups but no endpoint-level score \u2014 if one exists it may not be rendered".',' A bare "prerequisite not met" cannot tell absent data from an over-narrow selector. Put that'," evidence in a LATER sentence, never the first: grouping keys on the first sentence, so an",' interpolated count there makes every run its own "action" and the dedup stops working.'," (c) `click({ force: true })` is the ONE pattern that turns a failure into a silent WRONG"," SCREENSHOT rather than a crash or skip: it skips the actionability checks, so a click that"," lands on nothing photographs the unchanged screen and that image ships in the docs. It is"," sometimes right (a button nested inside a button reads as intercepted by its own ancestor)."," Never force blind: ground it in source, scrollIntoViewIfNeeded() first, and ASSERT THE"," CONSEQUENCE immediately after with a guarded wait + test.skip, so a no-op force skips."," Know its limit: force skips the CHECK but still hit-tests real screen coordinates, so the"," element that RECEIVES the event may not be the one your locator names (measured: a forced"," click on a pill nested in its section-header button never ran the pill's own handler).",' For a genuinely nested interactive node use `locator.dispatchEvent("click")`, which goes'," straight to that node with no hit-test \u2014 and still assert the consequence."," (d) Never bind a locator to an attribute your own interaction CHANGES. A locator is re-evaluated",' on every use, so `button[title="Multi-select scenarios"]` matches nothing once the click',' flips it to `title="Exit select mode"` \u2014 a 15s "not found" timeout on an element that is'," right there (measured). Toggling labels are normal (Play/Pause, Expand/Collapse, Select"," all/Deselect all): if the attribute is a ternary on state it is not an identity. Match both"," values in one locator, or use a testid."," (e) Cleanup after the screenshot is BEST-EFFORT and must never throw or test.skip. Anything"," after captureShot() runs with the image already on disk, so a throw there turns a successful"," capture into a reported failure and the shot is thrown away (measured: a valid .raw.png plus"," annotations, reported broken). Guard with isVisible()/isEnabled() and click best-effort \u2014 by"," then there is nothing left to skip."," (f) An element that is RENDERED can still be EMPTY. A component may mount an input/textarea/pane",' with no content and fill it when its fetch resolves, so waitFor({state:"visible"}) proves the'," node exists, not that the data arrived \u2014 reading inputValue()/textContent() right after can"," catch the pre-fetch empty state and false-skip data that IS there. When the decision rests on"," a VALUE rather than on presence, wait for the value: page.waitForFunction(sel => { const el =",' document.querySelector(sel); return !!el && (el.value ?? el.textContent ?? "").trim() !== ""; },',' "<selector>", { timeout: 10_000 }).catch(() => {}) \u2014 THEN read it and skip on empty.'," (g) NEVER take the screenshot yourself. `captureShot(page, PLACEHOLDER)` is the only capture call:"," it shoots AND resolves the callout positions in one pass, so they cannot disagree. A"," page.screenshot()/locator.screenshot() + dumpAnnotations() pair measures coordinates against"," the whole page while a cropped image starts at the crop corner, so every pin and highlight is"," offset \u2014 and nothing errors, so the spec reports success and the picture is wrong."," (h) EVERY navigation goes through `gotoResilient` (from document360-capture/helpers), never a bare",' page.goto(): `await gotoResilient(page)` for the start URL, `gotoResilient(page, "/route")`',` mid-spec. Under a bulk run, sibling specs saturate the network and goto's default "load" wait`," never fires \u2014 four specs died on that identical first line, each patched by hand.","2. Never reason about whether a role/text locator is unique; you cannot verify that by reading"," source, and Playwright fails the whole spec on 2+ matches. Every `getByRole`/`getByText`/"," `:has-text` without a unique data-testid gets `.first()` or a container scope"," (`page.locator('[data-testid=\"\u2026\"]').getByRole(\u2026)`). If you catch yourself writing a comment"," ARGUING a selector is unique, scope it instead \u2014 that argument is what fails.","3. Every skip reason opens with the SHARED staging action, worded identically across every shot",' that needs the same thing, naming where in the product to do it ("Create an API key in Settings',' \u2192 API Keys."); shot-specific detail (counts, which record, which state) goes in LATER sentences.'," The dashboard groups blocked shots by that first sentence, so a near-duplicate wording splits one"," chore into two. Grep sibling specs and reuse their exact opening sentence."," That consistency applies WITHIN one spec too, and a spec with 2+ test.skip calls needs two checks:"," (a) does a LATER branch's reason still HOLD, given what passing the earlier guard already proved?",` A later branch that reuses an earlier one's reason verbatim ("sign in as an owner\u2026") when`," reaching it proves that condition passed does not just read oddly \u2014 it misdiagnoses the cause"," and sends the reader to fix something that is already fine."," (b) do multiple branches for the SAME prerequisite (found 0 vs found fewer than N) open with one"," identical sentence? Divergent openings defeat the grouping even within a single spec.","Before you finish, re-read each spec you wrote and check every rule above line by line."].join(`
|
|
321
|
-
`);function
|
|
322
|
-
`),"",...r.length>0?["REPAIR: these already have a spec, and it FAILED its last capture. Read the existing spec","first and fix the named failure specifically; do not re-emit the same locator and hope. A",'"strict mode violation" means the locator matched 2+ elements (scope it to a stable container',"or take .first()); a click timeout means the element was absent or unreachable (if the data","simply is not staged, the spec must test.skip with a reason naming what to stage, not time out).",...r.map(i),""]:[],...s.length>0?["REPAIR: these already have a spec and it SKIPPED. Treat each reason as SUSPECT, not as proof","the spec is right: a FALSE skip is indistinguishable from a true one from inside the spec, and","you are being asked to re-author rather than to stage. Check TWO things before concluding a","spec needs no change. (1) Is the target RENDERED? A collapsed tree node, unopened accordion,","inactive tab, virtualised list or page 2 of a table keeps children out of the DOM, so the count","is zero for data one click away, so expanding is a step to SCRIPT. (2) Is the selector too narrow?","If you filtered past a decoy, count the unnarrowed set and put the number in the reason. A spec","that satisfies every rule and still cannot reach its target is NOT correct.",...s.map(i),""]:[],...a.flatMap(l
|
|
323
|
-
`)}async function
|
|
324
|
-
`),display:`/screenshot ${o.id}`}}if(o.mode==="capture"||o.mode==="annotate"||o.mode==="verify"||o.mode==="checklist")return{kind:"continue"};let i=[`Run the emit-screenshot-spec skill to (re)generate the document360-capture spec for ${o.mode==="scope"?`every <!-- SCREENSHOT --> placeholder in articles under ${o.scope}`:"every <!-- SCREENSHOT --> placeholder across the docs tree (the configured docsDir)"}.`,"Follow that skill exactly for each: read the SCREENSHOT block; read the product source for EXACT routes","and stable data-testid selectors (never guess); enter the prepared context via captureScope(); guard data",`prerequisites with test.skip(reason); write <captureDir>/<id>.spec.ts.${o.setup?" When done, run capture-setup-checklist to refresh CAPTURE-CHECKLIST.md.":""} Report specs written, TODO data-testids, and data to stage.`,
|
|
325
|
-
`),a=o.mode==="scope"?`/screenshot ${o.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:i,display:a}}import{readDocsPlan as
|
|
318
|
+
`);/\.waitFor\s*\(|Promise\.race\s*\(|waitForFunction\s*\(|waitForSelector\s*\(/.test(a)||o.push(r+1)}return o}function eu(e,t){let n=w=>`line${w.length===1?"":"s"} ${w.join(", ")}`,o=[],r=t?.captureVersion===void 0?mt():t.captureVersion,s=dr(r,xm)?Vc(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=Gc(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=qc(e);a.length>0&&o.push(`- ${n(a)}: takes its own screenshot (or calls dumpAnnotations) instead of captureShot(page, PLACEHOLDER). On a cropped shot that misplaces every callout and nothing errors.`);let l=Yc(e);l.length>0&&o.push(`- ${n(l)}: the "data is missing" decision rests on a fixed waitForTimeout, so staged data can read as absent. Give the element a bounded chance to appear first, then count.`);let d=Hc(e);return d.length>0&&o.push(`- ${n(d)}: click({ force: true }) with no assertion that it worked, so a no-op click photographs the unchanged screen. Assert the expected result immediately after, guarded, and skip if it never arrives.`),/CAPTURE-SAFETY:/.test(e)||o.push("- no CAPTURE-SAFETY marker: add exactly one `// CAPTURE-SAFETY: readonly` or `// CAPTURE-SAFETY: mutates \u2014 <what>; cleanup: <how>` at the top."),o}function Rm(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 Sm(e){return(e??"").trim().replace(/[.\s]+$/,"")}function Cm(e,t){let n=In(e)?.captureDir??aa,o=ra(n)?sa(n,`${t}.spec.ts`):ia(e,n,`${t}.spec.ts`);try{return $m(Qc(o,"utf8"))}catch{return{mutates:!1,declared:!1}}}var Nx=["annotated","verified","rejected"],jx=e=>Nx.includes(e);function Ix(e){return[...new Set(e.filter(t=>jx(t.state)).map(t=>t.file))].sort()}function la(e,t){let n=Ix(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 ca(e,t){let n=e.filter(s=>s.state==="captured");if(n.length===0)return null;let o=Math.max(...n.map(s=>s.id.length)),r=n.length===1;return[`${J("\u26A0",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(Re("/screenshot annotate","",t))}`].join(`
|
|
319
|
+
`)}function ua(e){let t=e.filter(o=>o.state==="rejected");if(t.length===0)return null;let n=Math.max(...t.map(o=>o.id.length));return[`${J("\u26A0",O.yellow)}${t.length} screenshot${t.length===1?"":"s"} failed verification:`,...t.map(o=>` ${O.magenta(o.id.padEnd(n))} ${O.gray(hr(o.reason??"no reason recorded"))}`),` Publishing anyway. Fix + re-capture: ${O.bold("/screenshot capture --failed")}`].join(`
|
|
320
|
+
`)}var Lx={placeholder:"\u25CB",spec:"\u25D0",blocked:"\u2298",broken:"\u2717",captured:"\u25CF",annotated:"\u25C8",verified:"\u2714",rejected:"\u2691"},Ox={placeholder:O.gray,spec:O.yellow,blocked:O.cyan,broken:O.red,captured:O.yellow,annotated:O.blue,verified:O.green,rejected:O.magenta},_x=` ${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 J(e,t=n=>n){return`${t(e)} `}function hr(e){return e.replace(/\s+/g," ").trim().replace(/^Prerequisites? not met[:—-]?\s*/i,"")}function da(e){let t=hr(e),n=/^(.*?[a-z0-9)"'”’])\.(?:\s|$)/i.exec(t);return(n?n[1]:t).trim()}function vs(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=da(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 Pm(e){let t=vs(e);if(t.length===0)return[];let n=t.filter(s=>s.blockedBy==="data"),o=t.filter(s=>s.blockedBy==="testid"),r=[""];if(n.length>0){let s=n.reduce((a,l)=>a+l.ids.length,0);r.push(` ${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 l=Jt(a.reason,86);r.push(` ${O.cyan(jn(`${a.ids.length}\xD7`,4))} ${l[0]??""}`);for(let w of l.slice(1))r.push(` ${w}`);let d=a.ids.slice(0,4).join(" \xB7 ");r.push(O.gray(` ${d}${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(` ${J("\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 tu(e){if(e.length===0)return[];let t=e.slice(0,6),n=e.length;return["",` ${J("\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 Tm(e,t){let n=e.filter(i=>(i.staleAnchor?.length??0)>0);if(n.length===0)return[];let o=[...new Set(n.flatMap(i=>i.staleAnchor))],r=o.length,s=["",` ${J("\u26A0",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 Am(e,t,n){let o=e.filter(w=>(w.unguardedWaits?.length??0)>0),r=e.filter(w=>w.undeclared),s=e.filter(w=>(w.handRolled?.length??0)>0),i=e.filter(w=>(w.stalePause?.length??0)>0),a=e.filter(w=>(w.bareGoto?.length??0)>0);if(o.length===0&&r.length===0&&s.length===0&&i.length===0&&a.length===0)return[];let l=["",` ${J("\u26A0",O.yellow)}Some specs were written before later reliability fixes:`],d=(w,g)=>` ${w.slice(0,8).map(g).join(" \xB7 ")}${w.length>8?` \xB7 +${w.length-8} more`:""}`;if(o.length>0){let w=o.length;l.push(O.gray(` ${w} crash${w===1?"es":""} instead of telling you what to stage when the data ${w===1?"it needs":"they need"} is missing`)),t&&l.push(O.gray(d(o,g=>`${g.id}:${g.unguardedWaits.join(",")}`)))}if(a.length>0){let w=a.length;l.push(O.gray(` ${w} open${w===1?"s":""} pages the slow way, so ${w===1?"it stalls":"they stall"} for a minute and give up when several shots run at once`)),t&&l.push(O.gray(d(a,g=>`${g.id}:${g.bareGoto.join(",")}`)))}if(i.length>0){let w=i.length;l.push(O.gray(` ${w} decide${w===1?"s":""} "the data is missing" from a fixed pause, so data you HAVE staged can read as absent`)),t&&l.push(O.gray(d(i,g=>`${g.id}:${g.stalePause.join(",")}`)))}if(s.length>0){let w=s.length;l.push(O.gray(` ${w} take${w===1?"s":""} ${w===1?"its":"their"} own screenshot instead of the one call that positions the callouts too \u2014 on a cropped shot the numbers land in the wrong places, and nothing reports it`)),t&&l.push(O.gray(d(s,g=>`${g.id}:${g.handRolled.join(",")}`)))}if(r.length>0){let w=r.length,g=r.filter($=>$.mutates).length;l.push(O.gray(` ${w} do${w===1?"es":""} not say whether ${w===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&&l.push(O.gray(d(r,$=>$.id)))}return n?.commandInLead||l.push(O.gray(` Re-write them all with the current rules: ${O.bold("/screenshot author --all")}`)),l}function Em(e){let t=e.filter(n=>(n.unverifiedForce?.length??0)>0);return t.length===0?[]:["",` ${J("\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 oa=(e,t)=>e.length>=t?e:e+" ".repeat(t-e.length),jn=(e,t)=>e.length>=t?e:" ".repeat(t-e.length)+e;function Dm(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 Mx=new Set(["and","or","of","the","to","a","an","in","on","for","with","vs"]),Fx=new Set(["ai","api","cli","ui","ux","url","id","http","https","json","xml","sdk","csv","pdf","oauth","sso","mfa","io","faq"]);function Ux(e){return e.replace(/[-_]+/g," ").trim().split(/\s+/).filter(Boolean).map((n,o)=>{let r=n.toLowerCase();return Fx.has(r)?r.toUpperCase():o>0&&Mx.has(r)?r:r.charAt(0).toUpperCase()+r.slice(1)}).join(" ")}function Kc(e){if(!e)return{num:"",name:"(docs root)"};let t=/^(\d+)[-_](.+)$/.exec(e);return{num:t?t[1]:"",name:Ux(t?t[2]:e)}}function Wx(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).pop()??e}function mm(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 Bx(e,t){let n=t>0?Math.round(e/t*100):0,o=jn(`${n}%`,4);return n===100?O.green(o):n>0?O.yellow(o):O.gray(o)}function Nm(e,t){let n=new Map;for(let o of e){let r=Dm(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 nu(e,t){let n=T=>e.filter(D=>D.state===T).length,o=n("captured"),r=n("placeholder"),s=n("spec"),i=n("annotated"),a=n("blocked"),l=n("broken"),d=n("rejected"),w=e.filter(T=>T.state==="spec"&&T.mutates).length,g=s>w,$=e.filter(T=>(T.unguardedWaits?.length??0)>0||(T.bareGoto?.length??0)>0).length,P=e.filter(T=>(T.stalePause?.length??0)>0||(T.handRolled?.length??0)>0).length,C=s>0||a>0||l>0,R=(T,D="")=>Re(T,D,t);return o>0?{key:"annotate",cmd:R("/screenshot annotate")}:r>0?{key:"toSpec",cmd:t?`/screenshot author ${t}`:"/screenshot author --all"}:$>0&&C?{key:"crashy",cmd:t?`/screenshot author ${t}`:"/screenshot author --all"}:P>0&&C?{key:"wrongOutput",cmd:t?`/screenshot author ${t}`:"/screenshot author --all"}:s>0&&(g||i===0)?{key:"ready",cmd:R("/screenshot capture")}:i>0&&s>0?{key:"verify",cmd:R("/screenshot verify")}:a>0?{key:"blocked",cmd:R("/screenshot capture","--blocked")}:l>0?{key:"broken",cmd:`/screenshot ${e.find(T=>T.state==="broken").id}`}:i>0?{key:"verify",cmd:R("/screenshot verify")}:d>0?{key:"rejected",cmd:R("/screenshot capture","--failed")}:{key:"done",cmd:t?`/push ${t}`:"/push"}}function Hx(e,t,n=[]){let o=(te,Le)=>te.filter(je=>je.state===Le).length,r=e.length,s=o(e,"verified"),i=o(e,"annotated"),a=o(e,"captured"),l=o(e,"rejected"),d=o(e,"spec"),w=o(e,"blocked"),g=o(e,"broken"),$=o(e,"placeholder"),P=new Set(e.map(te=>te.file)).size,C=Nm(e,t),R=[];R.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`)}`:"")+(l>0?` ${O.gray("\xB7")} ${O.magenta(`${l} rejected`)}`:"")+` ${O.gray("\xB7")} ${d>0?O.yellow(`${d} ready`):O.gray("0 ready")}`+(w>0?` ${O.gray("\xB7")} ${O.cyan(`${w} 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 ${P} article${P===1?"":"s"}`));let T=r>0?Math.round(s/r*100):0;R.push(` [${mm(s,r,32)}] ${O.bold(`${T}%`)}`),R.push("");let D=C.map(([te])=>Kc(te)),N=Math.min(32,Math.max(7,...D.map(te=>te.name.length))),B=te=>te.length>N?`${te.slice(0,N-1)}\u2026`:oa(te,N),I=[...a>0?[{head:"To annotate",w:11,state:"captured",color:O.yellow}]:[],...i>0?[{head:"To verify",w:9,state:"annotated",color:O.blue}]:[],...l>0?[{head:"Rejected",w:8,state:"rejected",color:O.magenta}]:[],{head:"Ready",w:5,state:"spec",color:O.yellow},...w>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}];R.push(O.gray(` ${oa("#",2)} ${oa("Chapter",N)} ${jn("Verified",8)} ${I.map(te=>jn(te.head,te.w)).join(" ")} Progress`));for(let[te,[,Le]]of C.entries()){let je=o(Le,"verified"),Ce=Le.length,{num:Xe,name:Xt}=D[te],st=je===Ce,It=B(Xt),No=I.map(Lt=>{let rn=o(Le,Lt.state);return rn>0?Lt.color(jn(String(rn),Lt.w)):O.gray(jn("\u2014",Lt.w))}).join(" ");R.push(` ${O.cyan(oa(Xe,2))} ${st?O.green(It):je>0?It:O.gray(It)} ${st?O.green(jn(`${je}/${Ce}`,8)):jn(`${je}/${Ce}`,8)} ${No} ${mm(je,Ce,10)} ${Bx(je,Ce)}`)}R.push("");let X=g>0?` ${O.gray("\xB7")} ${g} spec${g===1?"":"s"} broken \u2014 ${O.bold(`/screenshot ${e.find(te=>te.state==="broken").id}`)} re-authors ${g===1?"it":"the first"}`:"",q=e.filter(te=>te.state==="spec"&&te.mutates).length,de=d>q,ve=e.filter(te=>(te.unguardedWaits?.length??0)>0||(te.bareGoto?.length??0)>0).length,Se=e.filter(te=>(te.stalePause?.length??0)>0||(te.handRolled?.length??0)>0).length,Te=d>0||w>0||g>0,he=!1,ie=nu(e).key;if(ie==="annotate")R.push(` ${J("\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`)+X);else if(ie==="toSpec")R.push(` ${J("\u2192",O.yellow)}${$} placeholder${$===1?"":"s"} still need a spec \u2014 run ${O.bold("/screenshot author --all")}${X}`);else if(ie==="crashy")he=!0,R.push(` ${J("\u2192",O.yellow)}${ve} spec${ve===1?"":"s"} would crash mid-run \u2014 re-write ${ve===1?"it":"them"} first: ${O.bold("/screenshot author --all")}`+O.gray(` \xB7 then ${O.bold("/screenshot capture")} (no browser time wasted on ${ve===1?"a shot":"shots"} that can't finish)`)+X);else if(ie==="wrongOutput")he=!0,R.push(` ${J("\u2192",O.yellow)}${Se} spec${Se===1?"":"s"} would shoot the wrong thing \u2014 re-write ${Se===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)`)+X);else if(ie==="ready"){let te=q>0?O.gray(` \u2014 ${d-q} in one go; ${q} write${q===1?"s":""} real data and run${q===1?"s":""} one at a time`):"";R.push(` ${J("\u2192",O.yellow)}${d} spec${d===1?"":"s"} ready to capture \u2014 run ${O.bold("/screenshot capture")}${te}${X}`)}else if(ie==="verify"&&d>0)R.push(` ${J("\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 ${d} ready spec${d===1?"":"s"} write real data, so ${d===1?"it runs":"each runs"} only when named: /screenshot capture <id>`)+X);else if(ie==="blocked")R.push(` ${J("\u2192",O.cyan)}${w} shot${w===1?"":"s"} blocked \u2014 stage the data below, then ${O.bold("/screenshot capture --blocked")}${X}`);else if(ie==="broken")R.push(` ${J("\u2192",O.red)}${g} spec${g===1?"":"s"} broken \u2014 ${O.bold(`/screenshot ${e.find(te=>te.state==="broken").id}`)} re-authors ${g===1?"it":"the first"} (re-capturing fails the same way)`);else if(ie==="verify")R.push(` ${J("\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(ie==="rejected"){let te=e.filter(Le=>Le.state==="rejected"&&Le.repaired).length;R.push(` ${J("\u2691",O.magenta)}${l} shot${l===1?"":"s"} failed review \u2014 `+(te>0?`${te} spec${te===1?"":"s"} already repaired; re-capture with ${O.bold("/screenshot capture --failed")}`:`see the reasons below, then ${O.bold("/screenshot capture --failed")}`))}else R.push(` ${J("\u2713",O.green)}all ${r} verified \u2014 ${O.bold("/push")} embeds them in the articles`);if(s>0&&s<r){let te=C.filter(([,Le])=>Le.every(je=>je.state!=="verified")).map(([Le])=>{let{num:je,name:Ce}=Kc(Le);return je?`${je} ${Ce}`:Ce});te.length>0&&R.push(O.gray(` Furthest behind: ${te.slice(0,5).join(" \xB7 ")}${te.length>5?" \u2026":""} (0% verified)`))}return R.push(...Pm(e),...Em(e),...Am(e,!1,{commandInLead:he}),...Tm(e,!1),...tu(n)),R.push(""),R.push(O.gray(" Drill in: /screenshot list <chapter#> \xB7 /screenshot list --detail (all)")),R}function Gx(e,t,n,o=[]){let r=new Set(e.map(d=>d.file)),s=e.filter(d=>d.state==="verified").length,i=e.filter(d=>d.state==="annotated").length,a=e.filter(d=>d.state==="captured").length,l=[` ${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[d,w]of Nm(e,t)){let g=w.filter(T=>T.state==="verified").length,{num:$,name:P}=Kc(d),C=$?`${$} \xB7 ${P}`:P;l.push(` ${O.bold(C)} ${O.gray(`(${g}/${w.length})`)}`);let R=new Map;for(let T of w){let D=Wx(T.file),N=R.get(D)??[];R.has(D)||R.set(D,N),N.push(T)}for(let T of[...R.keys()].sort()){l.push(O.gray(` ${T}`));for(let D of R.get(T)){let N=Ox[D.state];if(l.push(` ${J(Lx[D.state],N)}${N(D.id)}`),(D.state==="blocked"||D.state==="broken"||D.state==="rejected")&&D.reason){for(let B of Jt(hr(D.reason),84))l.push(O.gray(` ${B}`));D.state==="rejected"&&l.push(O.gray(` ${D.repaired?"spec repaired \u2014 re-capture to confirm":"spec not yet repaired"}`))}}}}return l.push(...Pm(e),...Em(e),...Am(e,!0),...Tm(e,!0),...tu(o)),l.push("",_x),l}function pa(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.",...tu(o)];let r=t?.docsDir??Zc;return t?.detail||n?Gx(e,r,n,o):Hx(e,r,o)}function ou(e,t){if(!t||!/^\d+$/.test(t))return t;let n=In(e)?.docsDir??Zc,o=String(Number(t));for(let{file:r}of wm(e)){let s=Dm(r,n),i=/^(\d+)/.exec(s);if(i&&String(Number(i[1]))===o)return s}return t}function jm(e,t){let r=e.map(a=>" ".repeat(a.depth)+a.label),s=Math.max(0,...e.map((a,l)=>a.note?na(r[l]):0)),i=Math.min(s,Math.max(0,t-2-24));return e.map((a,l)=>{let d=r[l];if(!a.note)return{head:d,note:""};let w=Math.max(2,i+2-na(d)),g=a.note.trim(),$=t-na(d)-w;return{head:d+" ".repeat(w),note:$>1&&na(g)>$?`${g.slice(0,$-1)}\u2026`:g}})}function qx(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}=qx(s.file),l=o.get(i)??new Map;o.set(i,l);let d=l.get(a)??[];l.set(a,d),d.push(s)}let r=s=>n!=="capture"||!s.mutates;for(let s of[...o.keys()].sort()){let i=o.get(s),a=[...i.values()].flat().filter(r).map(d=>d.id),l=a.length>0;l&&e.push({kind:"category",action:n,label:`${s} (${a.length})`,ids:a,depth:1});for(let d of[...i.keys()].sort()){let w=i.get(d),g=w.filter(r).map(C=>C.id),$=g.length>0;$&&e.push({kind:"article",action:n,label:`${d} (${g.length})`,ids:g,depth:l?2:1});let P=(l?1:0)+($?1:0)+1;for(let C of w){let R=n==="capture"&&C.mutates?" \u26A0 creates real data \u2014 runs only alone":void 0;e.push({kind:"shot",action:n,label:C.id,ids:[C.id],depth:P,...R?{note:R}:{}})}}}}function Bc(e){return e?hr(e):""}function ru(e,t,n,o=[]){let r=t.filter(i=>!i.mutates);r.length>1&&e.push({kind:"all",action:"capture",label:`Retry ${r.length} blocked shots (Prerequisites not met \u2014 Stage the data first)`,ids:r.map(i=>i.id),depth:0});for(let i of[...t].sort((a,l)=>a.id.localeCompare(l.id)))e.push({kind:"shot",action:"capture",label:i.id,ids:[i.id],depth:1,note:` \u2298 ${Bc(i.reason)}`});n.length>1&&e.push({kind:"all",action:"author",label:`Re-author ${n.length} broken specs`,ids:n.map(i=>i.id),depth:0});for(let i of[...n].sort((a,l)=>a.id.localeCompare(l.id)))e.push({kind:"shot",action:"author",label:i.id,ids:[i.id],depth:1,note:` \u2717 re-authors \u2014 ${Bc(i.reason)}`});let s=o.filter(i=>!i.mutates);s.length>1&&e.push({kind:"all",action:"capture",label:`Re-capture ${s.length} shots that failed review`,ids:s.map(i=>i.id),depth:0});for(let i of[...o].sort((a,l)=>a.id.localeCompare(l.id))){let a=i.repaired?"re-captures":"re-captures (spec not yet repaired)";e.push({kind:"shot",action:"capture",label:i.id,ids:[i.id],depth:1,note:` \u2691 ${a} \u2014 ${Bc(i.reason)}`})}}function Im(e){let t=e.filter(i=>i.state==="placeholder"),n=e.filter(i=>i.state==="spec"),o=[];t.length>1&&o.push({kind:"all",action:"author",label:`Author all ${t.length} remaining specs`,ids:t.map(i=>i.id),depth:0}),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"),ru(o,e.filter(i=>i.state==="blocked"),e.filter(i=>i.state==="broken"),e.filter(i=>i.state==="rejected")),o}var zc=["MANDATORY \u2014 a missing prerequisite must SKIP, never time out. Two rules, applied to EVERY locator","in the spec, not just the first one or the one shown in the skill's example:","1. A bare `await x.waitFor(...)` is itself the bug: on a missing element it THROWS and the run"," reports a hard failure with a stack trace instead of a staging instruction. Every wait must be",' `await x.waitFor({ state: "visible", timeout: 10_000 }).catch(() => {});` followed by',' `if ((await x.count()) === 0) test.skip(true, "Prerequisite not met: \u2026")`. That applies to each'," element you wait on or click IN TURN \u2014 tabs, toggles, rows, buttons reached after the first"," guard \u2014 because any of them can be absent for the same reason the data is."," And guard on the SAME predicate the action needs: `.click()` requires visible AND ENABLED, so a",' DISABLED button passes both waitFor({state:"visible"}) and count()>0 and then times out at 15s'," (measured). Add `|| !(await x.isEnabled().catch(() => false))` to the condition, and put the"," control's own title/aria-disabled text in the skip reason \u2014 a disabled control is the product"," telling you the prerequisite is unmet, usually with the reason attached.",' And when a wait DOES time out, diagnose before you guard: a skip asserts "your app lacks this',' data", so if the real cause is a locator matching a node you did not intend (a rollup row, a'," sibling with the same testid), that assertion is a lie and sends the user to stage what they"," already have. Narrow the selector first, THEN guard."," Two corollaries, both of which have cost a wasted repair round:"," (a) An element that is not RENDERED is not absent. A collapsed tree node, an unopened accordion,"," an inactive tab, a virtualised list or page 2 of a table keeps its children out of the DOM."," EXPAND/scroll/switch to reach the target \u2014 that is a step to script, not data to stage."," (b) When you narrow past a decoy, count the UNNARROWED set too and put the number in the reason:",' "Found 6 folder roll-ups but no endpoint-level score \u2014 if one exists it may not be rendered".',' A bare "prerequisite not met" cannot tell absent data from an over-narrow selector. Put that'," evidence in a LATER sentence, never the first: grouping keys on the first sentence, so an",' interpolated count there makes every run its own "action" and the dedup stops working.'," (c) `click({ force: true })` is the ONE pattern that turns a failure into a silent WRONG"," SCREENSHOT rather than a crash or skip: it skips the actionability checks, so a click that"," lands on nothing photographs the unchanged screen and that image ships in the docs. It is"," sometimes right (a button nested inside a button reads as intercepted by its own ancestor)."," Never force blind: ground it in source, scrollIntoViewIfNeeded() first, and ASSERT THE"," CONSEQUENCE immediately after with a guarded wait + test.skip, so a no-op force skips."," Know its limit: force skips the CHECK but still hit-tests real screen coordinates, so the"," element that RECEIVES the event may not be the one your locator names (measured: a forced"," click on a pill nested in its section-header button never ran the pill's own handler).",' For a genuinely nested interactive node use `locator.dispatchEvent("click")`, which goes'," straight to that node with no hit-test \u2014 and still assert the consequence."," (d) Never bind a locator to an attribute your own interaction CHANGES. A locator is re-evaluated",' on every use, so `button[title="Multi-select scenarios"]` matches nothing once the click',' flips it to `title="Exit select mode"` \u2014 a 15s "not found" timeout on an element that is'," right there (measured). Toggling labels are normal (Play/Pause, Expand/Collapse, Select"," all/Deselect all): if the attribute is a ternary on state it is not an identity. Match both"," values in one locator, or use a testid."," (e) Cleanup after the screenshot is BEST-EFFORT and must never throw or test.skip. Anything"," after captureShot() runs with the image already on disk, so a throw there turns a successful"," capture into a reported failure and the shot is thrown away (measured: a valid .raw.png plus"," annotations, reported broken). Guard with isVisible()/isEnabled() and click best-effort \u2014 by"," then there is nothing left to skip."," (f) An element that is RENDERED can still be EMPTY. A component may mount an input/textarea/pane",' with no content and fill it when its fetch resolves, so waitFor({state:"visible"}) proves the'," node exists, not that the data arrived \u2014 reading inputValue()/textContent() right after can"," catch the pre-fetch empty state and false-skip data that IS there. When the decision rests on"," a VALUE rather than on presence, wait for the value: page.waitForFunction(sel => { const el =",' document.querySelector(sel); return !!el && (el.value ?? el.textContent ?? "").trim() !== ""; },',' "<selector>", { timeout: 10_000 }).catch(() => {}) \u2014 THEN read it and skip on empty.'," (g) NEVER take the screenshot yourself. `captureShot(page, PLACEHOLDER)` is the only capture call:"," it shoots AND resolves the callout positions in one pass, so they cannot disagree. A"," page.screenshot()/locator.screenshot() + dumpAnnotations() pair measures coordinates against"," the whole page while a cropped image starts at the crop corner, so every pin and highlight is"," offset \u2014 and nothing errors, so the spec reports success and the picture is wrong."," (h) EVERY navigation goes through `gotoResilient` (from document360-capture/helpers), never a bare",' page.goto(): `await gotoResilient(page)` for the start URL, `gotoResilient(page, "/route")`',` mid-spec. Under a bulk run, sibling specs saturate the network and goto's default "load" wait`," never fires \u2014 four specs died on that identical first line, each patched by hand.","2. Never reason about whether a role/text locator is unique; you cannot verify that by reading"," source, and Playwright fails the whole spec on 2+ matches. Every `getByRole`/`getByText`/"," `:has-text` without a unique data-testid gets `.first()` or a container scope"," (`page.locator('[data-testid=\"\u2026\"]').getByRole(\u2026)`). If you catch yourself writing a comment"," ARGUING a selector is unique, scope it instead \u2014 that argument is what fails.","3. Every skip reason opens with the SHARED staging action, worded identically across every shot",' that needs the same thing, naming where in the product to do it ("Create an API key in Settings',' \u2192 API Keys."); shot-specific detail (counts, which record, which state) goes in LATER sentences.'," The dashboard groups blocked shots by that first sentence, so a near-duplicate wording splits one"," chore into two. Grep sibling specs and reuse their exact opening sentence."," That consistency applies WITHIN one spec too, and a spec with 2+ test.skip calls needs two checks:"," (a) does a LATER branch's reason still HOLD, given what passing the earlier guard already proved?",` A later branch that reuses an earlier one's reason verbatim ("sign in as an owner\u2026") when`," reaching it proves that condition passed does not just read oddly \u2014 it misdiagnoses the cause"," and sends the reader to fix something that is already fine."," (b) do multiple branches for the SAME prerequisite (found 0 vs found fewer than N) open with one"," identical sentence? Divergent openings defeat the grouping even within a single spec.","Before you finish, re-read each spec you wrote and check every rule above line by line."].join(`
|
|
321
|
+
`);function Vx(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 Xc="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 Lm(e,t,n){let o=e.paths,r=o.filter(l=>t?.get(l)?.outcome==="failed"),s=o.filter(l=>t?.get(l)?.outcome==="skipped"),i=l=>`- ${l}: ${t.get(l).reason.replace(/\s+/g," ").trim()}`,a=o.filter(l=>(n?.get(l)?.length??0)>0);return["Run the emit-screenshot-spec skill to author the document360-capture spec for EACH of these","SCREENSHOT placeholder ids:",e.paths.map(l=>`- ${l}`).join(`
|
|
322
|
+
`),"",...r.length>0?["REPAIR: these already have a spec, and it FAILED its last capture. Read the existing spec","first and fix the named failure specifically; do not re-emit the same locator and hope. A",'"strict mode violation" means the locator matched 2+ elements (scope it to a stable container',"or take .first()); a click timeout means the element was absent or unreachable (if the data","simply is not staged, the spec must test.skip with a reason naming what to stage, not time out).",...r.map(i),""]:[],...s.length>0?["REPAIR: these already have a spec and it SKIPPED. Treat each reason as SUSPECT, not as proof","the spec is right: a FALSE skip is indistinguishable from a true one from inside the spec, and","you are being asked to re-author rather than to stage. Check TWO things before concluding a","spec needs no change. (1) Is the target RENDERED? A collapsed tree node, unopened accordion,","inactive tab, virtualised list or page 2 of a table keeps children out of the DOM, so the count","is zero for data one click away, so expanding is a step to SCRIPT. (2) Is the selector too narrow?","If you filtered past a decoy, count the unnarrowed set and put the number in the reason. A spec","that satisfies every rule and still cannot reach its target is NOT correct.",...s.map(i),""]:[],...a.flatMap(l=>Rm(n.get(l),`RULE VIOLATIONS already in ${l}'s existing spec \u2014 fix every one:`)),"For each: locate its <!-- SCREENSHOT --> block in the docs tree (the configured docsDir); read the product source for","EXACT routes + stable data-testid selectors (never guess); enter the prepared context via","captureScope(); guard data prerequisites with test.skip(reason); write <captureDir>/<id>.spec.ts","(skip-with-TODO if a stable selector is missing). Do NOT run other skills. Report the specs you","wrote and any TODO data-testids.",zc,Xc].join(`
|
|
323
|
+
`)}async function ha(e,t,n){let o=ks(e),r=mo(t?.cwd??process.cwd());if(r&&console.log(O.gray(r)),o.mode==="list"){let l=t?.cwd??process.cwd(),d=ou(l,o.scope),w=In(l)?.docsDir??Zc,g=Fe(l,d),$=yx(l,d?{scope:d}:{});for(let P of pa(g,{scope:d,detail:o.detail,docsDir:w,markerProblems:$}))console.log(P);return{kind:"continue"}}if(o.mode==="single"){let l=go(t?.cwd??process.cwd(),o.id),d=l===null?[]:eu(l);return{kind:"forward-to-agent",prompt:[`Run the emit-screenshot-spec skill for the SCREENSHOT placeholder with id \`${o.id}\`.`,"Locate its <!-- SCREENSHOT --> block in the docs tree (the configured docsDir), then follow that skill exactly: read the","product source for EXACT routes + stable data-testid selectors (never guess); enter the prepared","context via captureScope(); guard data prerequisites with test.skip(reason); write",`<captureDir>/${o.id}.spec.ts. Report per the skill's writer-facing format: spec path, data to`,"stage, dev requests only if any, and the capture command; no grounding narration.",zc,Xc,...n?.prior?["",...Vx(n.prior)]:[],...d.length>0?["",...Rm(d,"RULE VIOLATIONS already in the existing spec \u2014 fix every one:")]:[]].join(`
|
|
324
|
+
`),display:`/screenshot ${o.id}`}}if(o.mode==="capture"||o.mode==="annotate"||o.mode==="verify"||o.mode==="checklist")return{kind:"continue"};let i=[`Run the emit-screenshot-spec skill to (re)generate the document360-capture spec for ${o.mode==="scope"?`every <!-- SCREENSHOT --> placeholder in articles under ${o.scope}`:"every <!-- SCREENSHOT --> placeholder across the docs tree (the configured docsDir)"}.`,"Follow that skill exactly for each: read the SCREENSHOT block; read the product source for EXACT routes","and stable data-testid selectors (never guess); enter the prepared context via captureScope(); guard data",`prerequisites with test.skip(reason); write <captureDir>/<id>.spec.ts.${o.setup?" When done, run capture-setup-checklist to refresh CAPTURE-CHECKLIST.md.":""} Report specs written, TODO data-testids, and data to stage.`,zc,Xc].join(`
|
|
325
|
+
`),a=o.mode==="scope"?`/screenshot ${o.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:i,display:a}}import{readDocsPlan as zx,readProjectConfig as Xx,listOpenHints as Qx,listOpenForDocs as Jx,listOpenDirectives as Zx,loadOpenCommentCount as e0,resolveActiveProfile as t0,DEFAULT_DOCS_DIR as n0}from"document360-engine";import{statSync as Yx}from"node:fs";import{resolve as Kx}from"node:path";function Ln(e,t,n){return n.filter(o=>{try{return Yx(Kx(e,t,o)).size===0}catch{return!0}})}var wo=e=>e===1?"":"s";function o0(e){try{let t=(Xx(e)?.docsDir??n0).replace(/\/+$/,""),n=zx(e,t);return n.length===0?0:Ln(e,t,n.map(o=>o.path)).length}catch{return 0}}function r0(e){try{return e0(e,t0(e).name)}catch{return 0}}function s0(e){let t=s=>{try{return s().length}catch{return 0}},n=t(()=>Qx(e)),o=t(()=>Jx(e)),r=t(()=>Zx(e));return{hints:n,messages:o,directives:r,total:n+o+r}}function Om(e,t){let n=t?.just,o=s0(e);if(o.total>0&&n!=="/catch-up"){let i=[];return o.hints>0&&i.push(`${o.hints} hint${wo(o.hints)}`),o.messages>0&&i.push(`${o.messages} message${wo(o.messages)}`),o.directives>0&&i.push(`${o.directives} request${wo(o.directives)}`),{cmd:"/catch-up",short:`Your builder left ${i.join(" and ")} waiting`,text:`Your builder left ${i.join(" and ")} waiting. /catch-up clears that first \u2014 it rewrites articles, so reviewing or sending anything up before it runs is work you would do twice.`}}let r=r0(e);if(r>0&&n!=="/comments")return{cmd:"/comments",short:`${r} reviewer comment${wo(r)} ${r===1?"is":"are"} waiting on your articles`,text:`${r} reviewer comment${wo(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=o0(e);return s>0&&n!=="/write"?{cmd:"/write",short:`${s} planned article${wo(s)} ${s===1?"is":"are"} still unwritten`,text:`${s} planned article${wo(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 i0}from"document360-engine";var a0=new Set(["--scope","--concurrency","--model"]),l0=new Set(["/screenshot","/style-guide"]),c0=e=>e.trim().replace(/\s+/g," ").toLowerCase();function en(e){let t=c0(i0(e));if(!t.startsWith("/"))return null;let n=t.split(" ").filter(Boolean),o=n[0],r=1,s;l0.has(o)&&n[1]&&!n[1].startsWith("-")&&(s=n[1],r=2);let i=new Set,a;for(;r<n.length;r++){let l=n[r];if(l.startsWith("--")){let d=l.indexOf("=");if(d!==-1){let w=l.slice(0,d);i.add(w),w==="--scope"&&(a=l.slice(d+1)||void 0);continue}if(i.add(l),a0.has(l)){let w=n[r+1];w!==void 0&&!w.startsWith("-")&&(l==="--scope"&&(a=w),r++)}continue}if(l.startsWith("-")){i.add(l);continue}a??=l}return{cmd:o,...s?{sub:s}:{},flags:i,...a?{scope:a.replace(/\/+$/,"")}:{}}}function fr(e){switch(e.cmd){case"/review":case"/lint":return e.flags.has("--fix");case"/write":return!e.flags.has("--preview")&&!e.flags.has("--dry-run");case"/comments":return e.flags.has("--answer");case"/screenshot":return e.sub==="author"||e.sub==="capture"||e.sub==="annotate"||e.sub==="verify";case"/style-guide":return e.sub==="use"||e.sub==="keep"||e.sub==="compile"||e.sub==="learn";case"/push":case"/publish":case"/convert":case"/catch-up":case"/discover":case"/document":case"/pull":case"/reorder":return!0;default:return!1}}var u0=new Set(["--all"]),d0=new Set(["--concurrency","--model","--verbose","--quiet"]),p0=new Set(["--scope"]);function _m(e){return[...e.flags].filter(t=>!u0.has(t)&&!d0.has(t)&&!p0.has(t)).sort().join(" ")}function Mm(e,t){if(!t)return!1;let n=en(e),o=en(t);return!n||!o||n.cmd!==o.cmd||n.sub!==o.sub||!fr(n)||_m(n)!==_m(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 xs,roadmapProgress as Gm,stampRoadmapDone as y0}from"document360-engine";se();se();import{ROADMAP_STAGES as Fm}from"document360-engine";var Um=[...Fm,"other"],h0=[[/^\/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 su(e){let t=(e.stage??"").trim().toLowerCase();if(Fm.includes(t))return t;let n=(e.run??"").trim().toLowerCase();if(n.startsWith("/")){for(let[o,r]of h0)if(o.test(n))return r}return"other"}function fa(e){return su(e)==="capture"}var f0={decide:"Decide",plan:"Plan",capture:"Screenshots",write:"Write",edit:"Edit",lint:"Style rules",save:"Save to Document360",golive:"Go live",other:"Other steps"};function Wm(e){return e.status==="done"&&!!e.replacedBy}var au=e=>(e.run??"").trim().replace(/\s+/g," ").toLowerCase();function m0(e){let t=[];for(let o of e){let r=au(o);r&&!t.includes(r)&&t.push(r)}let n=o=>{let r=au(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 g0(e){let t=new Map;for(let o of e){let r=su(o),s=t.get(r);s?s.push(o):t.set(r,[o])}let n=[];for(let o of Um){let r=t.get(o);!r||r.length===0||n.push({key:o,label:f0[o],steps:m0(r),done:r.filter(s=>s.status==="done").length})}return n}var iu=" ",Bm=e=>e.trim().toLowerCase();function w0(e,t){let n=Math.max(20,t.width-iu.length),o=e.status==="done"?Y("\u2713"):xe("\u25CB"),r=e.status==="done"?m:t.isNext?Z:w=>w,s=Jt(e.title.trim(),n);s.length===0&&s.push("");let i=[];t.showRun&&e.run?.trim()&&i.push(e.run.trim()),t.showReplaced&&e.replacedBy&&i.push(`replaced by \u201C${e.replacedBy}\u201D`);let a=i.map(w=>` \xB7 ${w}`).join(""),l=s.map((w,g)=>g===0?` ${o} ${r(w)}`:`${iu}${r(w)}`);if(!a)return l;if((s[s.length-1]??"").length+a.length<=n)return l[l.length-1]+=xe(a),l;for(let w of i)l.push(`${iu}${xe(`\xB7 ${w}`)}`);return l}function Hm(e,t={}){let n=Math.max(40,t.width??80),o=t.all?e:e.filter(a=>!Wm(a)),r=e.length-o.length,s=e.filter(a=>a.status==="done").length,i=[Z(`Docs roadmap \u2014 ${s} of ${e.length} step${e.length===1?"":"s"} done`)];for(let a of g0(o)){i.push(""),i.push(` ${qe(a.label)}${xe(` \xB7 ${a.done} of ${a.steps.length}`)}`);let l="";for(let d of a.steps){let w=au(d);i.push(...w0(d,{width:n,showRun:!!w&&w!==l,isNext:!!t.next&&Bm(d.title)===Bm(t.next.title),showReplaced:!!t.all&&Wm(d)})),l=w}}return i.push(""),i.push(t.next?`Next: ${t.next.title}${t.next.run?` \u2014 ${t.next.run}`:""}`:"Campaign complete \u2014 the docs agent adds new steps as the app changes."),r>0&&i.push(m(`(+${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 lu(e,t={}){let n=xs(e);if(n.length===0)return["No docs roadmap yet \u2014 the docs agent seeds .d360-writer/roadmap.md when it pins a structure,","and adds steps as the app changes. You can also write steps by hand (## [open] <step>), or ask:",'"propose the docs roadmap for this repo".'];let o=Gm(e),r=Hm(n,{width:t.width,all:t.all,next:o.next});return r.push(m("(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(m('(d360-writer keeps the wording of its own steps current \u2014 add a "keep:" line to one to leave your version alone.)')),r}function mr(e,t){let n=xs(e).filter(d=>d.status==="open"),o=t.trim();if(n.length===0)return{ok:!1,line:"The roadmap has no open steps \u2014 nothing to mark done."};let r=d=>d.trim().toLowerCase(),s=n.find(d=>r(d.title)===r(o)),i=o?s?[s]:n.filter(d=>r(d.title).includes(r(o))):[n[0]];if(i.length>1)return{ok:!1,line:`"${o}" matches ${i.length} open steps \u2014 add a distinguishing word:
|
|
326
326
|
${i.map(d=>` \u25CB ${d.title}`).join(`
|
|
327
327
|
`)}`};if(i.length===0)return{ok:!1,line:`No open step matches "${o}". Open steps:
|
|
328
328
|
${n.map(d=>` \u25CB ${d.title}`).join(`
|
|
329
|
-
`)}`};let a=i[0].title;
|
|
330
|
-
`)}function
|
|
329
|
+
`)}`};let a=i[0].title;y0(e,a,{doneAt:new Date().toISOString()});let l=Gm(e)?.next;return{ok:!0,line:`\u2713 Marked done: ${a}${l?` \u2014 next up: ${l.title}${l.run?` (${l.run})`:""}`:" \u2014 that was the last step: campaign complete."}`}}function qm(e,t){let n=r=>r.trim().replace(/\s+/g," ").toLowerCase(),o=n(t);return o.startsWith("/")?xs(e).find(r=>r.status==="open"&&!!r.run&&n(r.run)===o)??null:null}function Vm(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 xs(e))s.status==="open"&&n.some(i=>Mm(i,s.run))&&(o.has(s.title)||(o.add(s.title),r.push(s.title)));return r}function Tt(e,t){if(!t)return[];try{let n=Vm(e,t).filter(o=>mr(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 ma(e,t){let n=Vm(e,t);if(n.length===0)return null;let o=n.map(r=>`"${r}"`).join(", ");return[n.length===1?`Note: this command executes the open docs-roadmap step ${o}.`:`Note: this command executes ${n.length} open docs-roadmap steps: ${o}.`,`Close the loop IN THE SAME TURN the goal state is reached: call d360_roadmap_done with exactly the title of EACH step it completed (${o}), then tell the user they are marked done \u2014 including when you find the goal already holds ("no action needed" completes the STEP, not just the turn). Leave one open ONLY if its work is genuinely incomplete, and say exactly what remains.`].join(`
|
|
330
|
+
`)}function Ym(e,t){let n=t.trim().toLowerCase();if(!n)return null;let o=xs(e).find(r=>r.status==="open"&&r.title.trim().toLowerCase()===n);return o?[`Execute this open docs-roadmap step: "${o.title}".`,o.run?`Its run command: ${o.run}`:"",o.body?`Step detail:
|
|
331
331
|
${o.body}`:"","",`Close the loop IN THE SAME TURN the step's goal state is reached: call d360_roadmap_done with exactly the title "${o.title}", then tell the user it is marked done. This INCLUDES discovering the goal already holds \u2014 "no action needed" completes the STEP, not just the turn, so stamp it done then too. Leave it open ONLY if the work is genuinely incomplete (blocked, or background results not yet applied) \u2014 then say exactly what remains before it can be closed.`].filter(Boolean).join(`
|
|
332
|
-
`):null}async function qm(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let o=fr(n,e.slice(1).join(" ").trim());return console.log(o.ok?Y(o.line):G(o.line)),{kind:"continue"}}for(let o of su(n,{all:e.some(r=>r.toLowerCase()==="--all")}))console.log(o);return{kind:"continue"}}var Ym={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 pushing overwrites the portal edit"};function lu(e){return e.filter(t=>t.path!==null&&t.status in Ym&&!t.link).map(t=>({path:t.path,label:Ym[t.status]}))}function wo(e){let t=lu(e),n=new Set(e.filter(o=>o.status==="conflict"&&o.path).map(o=>o.path));return{clean:t.filter(o=>!n.has(o.path)),conflicts:t.filter(o=>n.has(o.path))}}function vs(e){let t=e!==1;return`\u26A0 ${e} conflict${t?"s":""} NOT pushed (portal edit${t?"s":""} kept safe) \u2014 ${t?"these were":"it was"} edited both here and on the portal, so ${t?"they are":"it is"} left untouched. Settle ${t?"them":"it"}: /resolve (or /push <path> to keep yours, /pull <path> to take the portal's).`}function mr(e,t){let n=$0(e,t).length;return n===0?null:`\u2139 ${n} article${n===1?"":"s"} ${n===1?"is":"are"} saved on Document360 as a draft and not live yet \u2014 readers still see the previous version. /publish takes ${n===1?"it":"them"} live once ${n===1?"it has":"they have"} been signed off.`}function ma(e){return e.filter(t=>t.link).length}function cu(e,t){try{let n=zm(e,au(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=D0(g0(w0(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 ng(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:`${Dn(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 xs(e,t){try{let n=au(e,t),o=n.project.projectId,r=n.project.workspaceId;if(!o||!r)return null;let s=await E0({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 "${Vm}" 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 "${Vm}" 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 Pt="--skip-review";function Rs(e,t){return v0(e,t)}function ga(e,t){try{return Rs(e,Qm(e,t)).length}catch{return 0}}function Vt(e,t,n="",o,r){let s=ga(e,o),i=wa(e,o),a=o?` ${o}`:"",l=o?"/push":"/push --all",d=jm(e,{just:r}),w=!!o&&o.endsWith(".md"),g=d&&w?` (${d.short} \u2014 ${d.cmd} once this page is delivered.)`:"";if(d&&!w){let C=s>0?` (${s} article${s===1?"":"s"}${o&&!o.endsWith(".md")?` in ${o}`:""} ${s===1?"carries":"carry"} text no editor has read, so ${s===1?"it cannot":"they cannot"} be sent up until /review${a} --blocked --fix runs \u2014 that can wait until the writing is done.)`:i>0?` (${i} article${i===1?"":"s"} break${i===1?"s":""} house style rules that block sending up \u2014 /lint${a} --blocked --fix clears that whenever you want.)`:"";return{text:`${n}${d.text}${C}`,cmd:d.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 C=s===1?"":"s",R=i>0?` ${i} also break house style rules \u2014 /lint${a} --blocked --fix clears those afterwards.`:"",T=`/review${a} --blocked --fix`;return{text:`${n}${s} article${C}${$} ${s===1?"carries":"carry"} text no editor has read, so pushing ${s===1?"it is":"them is"} blocked. ${T} reads ${s===1?"it":"just those"} and applies its fixes.${R} Then ${l}.${g}`,cmd:T}}return{text:`${n}${i} article${i===1?"":"s"}${$} break${i===1?"s":""} house style rules that block publishing. /lint${a} --blocked --fix corrects them in place \u2014 finding them costs nothing \u2014 then ${l}.${g}`,cmd:`/lint${a} --blocked --fix`}}function wa(e,t){try{return Xm(e,Qm(e,t)).length}catch{return 0}}function og(e,t){return Xm(e,t)}function uu(e,t,n){try{let o=zm(e,au(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 du(e,t){let n=`/push${t.scope?` ${t.scope}`:" --all"}`,o=l=>`${l} article${l===1?"":"s"}`,r=[],s=e.pushed.length,i=t.elapsedMs!==void 0?` \xB7 ${I0(t.elapsedMs)}`:"",a=e.screenshotsUploaded>0?` \xB7 ${e.screenshotsUploaded} screenshot${e.screenshotsUploaded===1?"":"s"} uploaded`:"";if(s===0&&e.failed.length===0?r.push("Nothing was pushed \u2014 no articles were sent."):t.recorded<s?(r.push(`Pushed ${t.recorded}/${o(s)}${a}${i}.`),r.push(`${s-t.recorded} article${s-t.recorded===1?"":"s"} reported success but ${s-t.recorded===1?"is":"are"} not recorded in the category map \u2014 re-run ${n}.`)):(r.push(`Pushed ${o(s)}${e.created>0?` (${e.created} new)`:""}${a}${i}.`),r.push(`Saved on Document360 as draft${s===1?"":"s"} \u2014 readers don't see ${s===1?"it":"them"} until /publish takes ${s===1?"it":"them"} live.`)),e.stopped&&r.push(`Stopped: ${e.stopped.streak} articles in a row could not reach Document360${e.notRun.length>0?`, so the remaining ${e.notRun.length} ${e.notRun.length===1?"was":"were"} not attempted`:""}.`),e.failed.length>0){let l=e.failed.filter(g=>g.refused),d=j0(e.failed,t.docsRoot),w=e.failed.length;if(d.length===1&&w>1)r.push(`${o(w)} could not be pushed \u2014 all with the same error: ${d[0].error}`),r.push(...Km(d[0].paths," \u2717 "));else{r.push(`${o(w)} could not be pushed:`);for(let g of d)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(...Km(g.paths," ")))}l.length<e.failed.length&&(e.stopped?r.push(`Nothing was lost \u2014 your articles are unchanged. Re-run ${n} when Document360 is back.`):r.push(`Re-run ${n} to retry the rest \u2014 articles already saved are sent again only if they changed.`))}if(e.notRun.length>0&&!e.stopped&&r.push(`\u26A0 ${o(e.notRun.length)} never started (the run was stopped): ${N0(e.notRun)}`),e.missingShots.length>0){let l=e.missingShots.flatMap(d=>d.ids);r.push(`\u26A0 ${l.length} screenshot${l.length===1?"":"s"} in ${o(e.missingShots.length)} ${l.length===1?"has":"have"} not been taken, so the description was published instead: /screenshot capture`)}return t.conflictsSkipped&&t.conflictsSkipped>0&&r.push(vs(t.conflictsSkipped)),r}var N0=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,iu=5;function Km(e,t){let n=e.slice(0,iu).map(o=>`${t}${o}`);return e.length>iu&&n.push(`${" ".repeat(t.length)}\u2026 +${e.length-iu} more`),n}function j0(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 I0(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=x0(e.cwd,t,{allowUnreviewed:o?.skipReview===!0,allowStyleErrors:o?.skipStyle===!0});if(!r.clear){for(let l of R0(r,t.length,{act:"push"}))console.log(G(l));return{kind:"continue"}}let s={aborted:!1,partitions:0,failed:0,notRun:0,producedNothing:!0},i={retryable:0,stopped:!1},a=async(l,d)=>{let w=Date.now();console.log(m(d?`Resolving cross-links in ${l.length} article${l.length===1?"":"s"} whose targets published this run (second pass)\u2026`:`Pushing ${l.length} article${l.length===1?"":"s"} to Document360 (${P0} at a time)\u2026`));let g=await S0({cwd:e.cwd,...e.profileName?{profileName:e.profileName}:{},paths:l,allowProdWrites:e.allowProdWrites?.()===!0,...o?.allowUnpullable===!0?{allowUnpullable:!0}:{},onEvent:N=>{N.type==="article_done"?console.log(Y(` \u2713 ${N.result.path}${N.result.action==="created"?" (new)":""}`)):N.type==="article_failed"&&console.log(_(` \u2717 ${N.failure.path}`))}});console.log("");let $=uu(e.cwd,l,e.profileName);d||(i={retryable:g.failed.filter(N=>!N.refused).length,stopped:!!g.stopped},s={aborted:g.aborted||!!g.stopped,partitions:b0(l).length,failed:g.failed.length,notRun:g.notRun.length,producedNothing:g.pushed.length===0,verifiedComplete:$>=l.length,leftBehind:n});let P=g.pushed.length>0;for(let N of du(g,{recorded:$,elapsedMs:Date.now()-w,docsRoot:A0(e.cwd),...d?{}:{conflictsSkipped:n},...o?.scope?{scope:o.scope}:{}}))console.log(P&&g.failed.length===0?Y(N):G(N));let C=g.aborted||!!g.stopped;if(!P)return C;let R=cu(e.cwd,e.profileName);R&&console.log(m(R));let T=mr(e.cwd,e.profileName);if(T&&console.log(m(T)),C)return C;try{let N=Zm(await Jm({cwd:e.cwd,profileName:e.profileName,onRateLimit:W=>console.log(m(` Document360 rate limit \u2014 waiting ${Math.ceil(W.waitMs/1e3)}s\u2026`))}));N&&console.log(N.startsWith("\u26A0")?G(N):m(N))}catch{}try{let N=tg(await eg({cwd:e.cwd,profileName:e.profileName}));N&&console.log(m(N))}catch{}let D=await xs(e.cwd,e.profileName);return D&&console.log(m(D)),C};try{if(!await a(t,!1)){let d=await pu(e.cwd,e.profileName,t);if(d.length>0&&await a(d,!0),Gt(s))for(let w of Ct(e.cwd,o?.scope?`/push ${o.scope}`:"/push --all"))console.log(Y(w))}}catch(l){console.log(_(`Push run failed: ${l.message}`))}if(console.log(""),i.retryable>0){let l=Re("/push",o?.scope?"":"--all",o?.scope);return console.log(m(i.stopped?`Next: ${l} \u2014 your articles are unchanged, so it picks up where the run left off.`:`Next: ${l} \u2014 retries the ${i.retryable} article${i.retryable===1?"":"s"} that could not be saved.`)),{kind:"continue",ownNext:!0}}return{kind:"continue"}}async function ya(e,t,n){let o=k0(e,n);if(o.length===0)return[];let r=new Set(lu((await fa({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function pu(e,t,n){try{let o=new Set(n),r=await fa({cwd:e,profileName:t});return lu(r.entries).map(s=>s.path).filter(s=>o.has(s))}catch{return[]}}async function L0(e,t,n){try{let o=await C0({cwd:e,...t?{profileName:t}:{},relPath:n.replace(/\\/g,"/"),preview:!0});console.log(""),console.log(Y(`${o.title}`)),console.log(m(`${o.path} \xB7 ${o.articleId?`updates article ${o.articleId}`:"would be created as a new article"}`)),o.shots.length>0&&console.log(m(`${o.shots.length} screenshot${o.shots.length===1?"":"s"} embedded: ${o.shots.map(r=>r.id).join(", ")}`)),o.missingShots.length>0&&console.log(G(`\u26A0 ${o.missingShots.length} screenshot${o.missingShots.length===1?"":"s"} not taken yet \u2014 the description publishes instead: ${o.missingShots.join(", ")}`)),console.log(m("\u2500".repeat(Math.min(80,Math.max(20,(process.stdout.columns??80)-1))))),console.log(o.body),console.log(m("\u2500".repeat(Math.min(80,Math.max(20,(process.stdout.columns??80)-1))))),console.log(m(`Nothing was sent. Run /push ${o.path} to save it as a draft.`))}catch(o){console.log(_(o.message))}return{kind:"continue"}}async function ba(e,t){let n=Ge(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(_(n.reason)),{kind:"continue"};let o=e.includes(Pt),r=e.includes(T0);if(e.includes("--preview")){let i=e.find(a=>!a.startsWith("--"));return i?await L0(t?.cwd??process.cwd(),t?.profileName,i):(console.log(_("Which article? Use /push --preview <path> \u2014 a preview is per article.")),{kind:"continue"})}let s=e[0];if(e.includes("--screenshots")||e.includes("--shots")){let i=t?.cwd??process.cwd(),a=e.find(P=>!P.startsWith("--")),l=Fe(i),d=ia(l,a);if(d.length===0){let P=l.filter(C=>C.state==="captured").length;return console.log(m(P>0?`${P} screenshot${P===1?" has":"s have"} been taken but the callouts aren't drawn on yet, so there is nothing to embed \u2014 /screenshot annotate finishes ${P===1?"it":"them"}.`:a?`No captured screenshots in ${a} \u2014 /push --screenshots covers the whole knowledge base.`:"No captured screenshots yet \u2014 /screenshot capture first.")),{kind:"continue"}}let w=aa(l,a);w&&console.log(w);let g=la(l);g&&console.log(g);let $=Re("","--screenshots",a).trim();return await qt(t??{cwd:process.cwd()},d,0,{skipReview:o,skipStyle:r,scope:$})}if(s==="--related"&&e[1]){if(!t)return{kind:"continue"};let i=await ya(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return i.length===0?(console.log(Y("\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(m("Checking what needs pushing\u2026"));try{let i=await fa({cwd:t?.cwd??process.cwd()}),{clean:a,conflicts:l}=wo(i.entries),d=ma(i.entries),w=e.includes("--force")&&l.length>0;d>0&&console.log(G(`\u26A0 ${d} article(s) already exist on Document360 but aren't linked \u2014 left out (pushing would duplicate them). Run /catch-up or ask me to link them first.`)),l.length>0&&!w&&console.log(G(vs(l.length)));let g=w?[...a,...l]:a;if(g.length===0){if(l.length>0){let P=mr(t?.cwd??process.cwd(),t?.profileName);return P&&console.log(m(P)),console.log(m("Resolve the conflicts: /resolve")),{kind:"continue"}}console.log(Y(d>0?"\u2713 Nothing else is ahead of Document360 to push.":"\u2713 Nothing is ahead of Document360 \u2014 nothing to push."));let $=mr(t?.cwd??process.cwd(),t?.profileName);if($&&console.log(m($)),t)try{let P=Zm(await Jm({cwd:t.cwd,profileName:t.profileName,onRateLimit:R=>console.log(m(` Document360 rate limit \u2014 waiting ${Math.ceil(R.waitMs/1e3)}s\u2026`))}));P&&console.log(P.startsWith("\u26A0")?G(P):m(P));let C=tg(await eg({cwd:t.cwd,profileName:t.profileName}));C&&console.log(m(C))}catch{}return{kind:"continue"}}return await qt(t??{cwd:process.cwd()},g.map($=>$.path),w?0:l.length,{skipReview:o,skipStyle:r,allowUnpullable:w})}catch(i){return console.log(_(`Could not compute sync status: ${i.message}`)),{kind:"continue"}}}if(s&&s.startsWith("--")&&(s=e.find(i=>!i.startsWith("--"))??""),!s){console.log(m("Checking what needs pushing\u2026"));let i,a=0;try{let l=await fa({cwd:t?.cwd??process.cwd()}),{clean:d,conflicts:w}=wo(l.entries);i=d,a=w.length;let g=ma(l.entries);if(g>0&&console.log(G(`\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.`)),w.length>0&&console.log(G(vs(w.length))),i.length===0&&w.length>0)return console.log(m("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(l){return console.log(_(`Could not compute sync status: ${l.message}`)),console.log(m("Push a specific article: /push <article-path>")),{kind:"continue"}}if(i.length===0)return console.log(Y("\u2713 Nothing is ahead of Document360 \u2014 nothing to push.")),console.log(m(" (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} ${m(`(${l.label})`)}`);return console.log(m("Run: /push <article-path>")),{kind:"continue"}}try{s=await t.withPausedInput(()=>y0({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(m("Cancelled.")),{kind:"continue"}}if(s==="--all")return await qt(t,i.map(l=>l.path),a,{skipReview:o,skipStyle:r})}return await qt(t??{cwd:process.cwd()},[s],0,{skipReview:o,skipStyle:r,scope:s})}se();import{select as _0}from"@inquirer/prompts";import{computeSyncStatus as M0,localAheadPaths as F0,pendingDrafts as U0,publishArticleLive as W0,publishGateVerdict as B0,publishGateLines as H0,blockedPaths as G0,resolveActiveProfile as LL,SKIP_STYLE_FLAG as q0,SKIP_SHOTS_FLAG as V0}from"document360-engine";var O0={check:"/check is now /lint (same command).",publish:"/publish now means taking drafts LIVE to readers \u2014 saving your local edits to Document360 is /push."},rg=new Set;function wn(e){let t=O0[e.replace(/^\//,"")];return!t||rg.has(e)?null:(rg.add(e),t)}var Y0=150,K0=e=>e>0?new Promise(t=>setTimeout(t,e)):Promise.resolve(),fu=e=>e===1?"":"s",hu=e=>e.replace(/\\/g,"/").split("/").pop()??e;function mu(e){return e.includes("--screenshots")||e.includes("--shots")||e[0]==="--related"}async function gu(e,t,n){await M0({cwd:e,profileName:t});let o=n?n.replace(/\\/g,"/").replace(/\/+$/,""):null;return U0(e,t).filter(r=>!o||r.path===o||r.path.startsWith(`${o}/`)).map(r=>({...r,label:z0(e,r.path)}))}function z0(e,t){let n=Xi(e,t)??ws(t),o=zi(t),r=o?Dn(o):"";return r?`${r} \u203A ${n}`:n}function X0(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 wu(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=F0(e,t).filter(a=>!s||a===s||a.startsWith(`${s}/`)).length;return i>0&&r.push(`${i} article${fu(i)} ${i===1?"has":"have"} local edits that aren't on Document360 yet \u2014 that's /push${n?` ${n}`:""}.`),{lines:r,ahead:i}}async function yu(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 W0({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 K0(Y0)}return r}function bu(e){let{published:t,blocked:n,failed:o}=e,r=[];if(t.length>0){r.push(`\u2713 ${t.length} article${fu(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 ${hu(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 ${hu(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 sg(e,t){let n=t?.cwd??process.cwd(),o=wn("publish");if(mu(e))return o&&console.log(m(`\u2192 ${o}`)),console.log(m("Running /push\u2026")),ba(e,t);let r=Ge(n,t?.profileName);if(!r.ok)return console.log(_(r.reason)),{kind:"continue"};o&&console.log(m(`\u2192 ${o}`));let s=e.includes(Pt),i=e.includes(q0),a=e.includes(V0),l=e.includes("--all"),d=e.find(T=>!T.startsWith("--"));console.log(m("Checking what is waiting to go live\u2026"));let w;try{w=await gu(n,t?.profileName,d)}catch(T){return console.log(_(`Could not check Document360: ${T.message}`)),{kind:"continue"}}if(w.length===0){for(let T of wu(n,t?.profileName,d).lines)console.log(T.startsWith("\u2713")?Y(T):m(T));return{kind:"continue"}}let g=B0(n,w.map(T=>T.path),{allowUnreviewed:s,allowStyleErrors:i,checkScreenshots:!0,allowPlaceholders:a}),$=new Set(G0(g)),P=w.filter(T=>!$.has(T.path));if($.size>0)for(let T of H0(g,w.length,{scope:d,act:"publish",going:P.length}))console.log(G(T));if(P.length===0)return{kind:"continue"};w=P,console.log(""),console.log(`${w.length} draft${fu(w.length)} ${w.length===1?"is":"are"} ahead of what readers see:`);for(let T of X0(w.slice(0,12)))console.log(m(T));w.length>12&&console.log(m(` \u2026and ${w.length-12} more`)),console.log("");let C=w;if(!l){let T=await _0({message:"Publish live to your readers?",choices:[{name:`Yes \u2014 publish all ${w.length} live`,value:"all"},...w.slice(0,8).map(D=>({name:`Just ${D.label}`,value:D.path})),{name:"No \u2014 leave them as drafts",value:"none"}]});if(T==="none")return console.log(m("Left as drafts. Nothing changed.")),{kind:"continue"};T!=="all"&&(C=w.filter(D=>D.path===T))}let R=await yu(n,t?.profileName,C,{skipReview:s,skipStyle:i,onProgress:(T,D,N)=>console.log(m(` \u25B8 ${T+1}/${D} ${hu(N)}\u2026`))});console.log("");for(let T of bu(R))console.log(T.startsWith("\u2713")?Y(T):T.startsWith("\u2717")?G(T):m(T));return{kind:"continue"}}import{loadKnownConflicts as Q0,localArticleTitle as J0,resolveActiveProfile as Z0}from"document360-engine";function eR(e,t){let n=J0(e,t);return n||(t.split(/[\\/]/).pop()??t).replace(/\.md$/,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ")}function ka(e,t){let n=[];try{n=Q0(e,Z0(e,t).name)}catch{return null}if(n.length===0)return null;let o=n.length,r=n.slice(0,3).map(i=>eR(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 gr={cmd:"/resolve",reason:"it walks each one with you \u2014 keep yours, take the portal's, or skip"};async function Ss(e){if(e?.cwd){let n=ka(e.cwd,e.profileName);if(n)return{kind:"audit-blocked",note:n.note,lead:gr}}return{kind:"forward-to-agent",prompt:["Run the gap-analysis skill against this repo.","","Follow its stages in order:","1. d360_sync_status first; stop if any article is changed in both places, or changed on Document360 and not yet pulled down (the local copy cannot be trusted until that is resolved). Say which articles, in plain words, never the internal status word \u2014 and tell the user to run /resolve, which walks the affected articles one at a time (keep the local copy, take the portal's, or skip). Do NOT ask them to report back to you: they will run /resolve and then /audit again.","2. git diff since the lastAnalyzedCommit marker in d360-category-map.json (or last 30 days if no marker), filtered to the authoritativeSourceFiles paths.","2.5. d360_pending_hints: the source agent's own notes on what it shipped. Verify each (sources exist, commit is an ancestor of HEAD, source shows the surface) before trusting; fold verified ones into the table, flag the rest.","3. Map changes (diff + hints) to articles via their `sources:` frontmatter; read only implicated articles and changed source files. If articles are missing `sources:`, this is the one-time bootstrap pass, so backfill them.","4. Output the proposal table: | Article (path or proposed title) | Action (create | update | retire | link) | Reason | Evidence | Scope |, then stamp consumed hints.","","Do not start writing or updating any article yet; the proposal table is the deliverable."].join(`
|
|
333
|
-
`),display:"/audit"}}se();import{readProjectConfig as
|
|
334
|
-
`)}async function
|
|
332
|
+
`):null}async function Km(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let o=mr(n,e.slice(1).join(" ").trim());return console.log(o.ok?Y(o.line):V(o.line)),{kind:"continue"}}for(let o of lu(n,{all:e.some(r=>r.toLowerCase()==="--all")}))console.log(o);return{kind:"continue"}}var Xm={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 pushing overwrites the portal edit"};function du(e){return e.filter(t=>t.path!==null&&t.status in Xm&&!t.link).map(t=>({path:t.path,label:Xm[t.status]}))}function yo(e){let t=du(e),n=new Set(e.filter(o=>o.status==="conflict"&&o.path).map(o=>o.path));return{clean:t.filter(o=>!n.has(o.path)),conflicts:t.filter(o=>n.has(o.path))}}function Rs(e){let t=e!==1;return`\u26A0 ${e} conflict${t?"s":""} NOT pushed (portal edit${t?"s":""} kept safe) \u2014 ${t?"these were":"it was"} edited both here and on the portal, so ${t?"they are":"it is"} left untouched. Settle ${t?"them":"it"}: /resolve (or /push <path> to keep yours, /pull <path> to take the portal's).`}function gr(e,t){let n=R0(e,t).length;return n===0?null:`\u2139 ${n} article${n===1?"":"s"} ${n===1?"is":"are"} saved on Document360 as a draft and not live yet \u2014 readers still see the previous version. /publish takes ${n===1?"it":"them"} live once ${n===1?"it has":"they have"} been signed off.`}function wa(e){return e.filter(t=>t.link).length}function pu(e,t){try{let n=Jm(e,uu(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=I0(b0(k0(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 sg(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:`${Nn(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 Ss(e,t){try{let n=uu(e,t),o=n.project.projectId,r=n.project.workspaceId;if(!o||!r)return null;let s=await j0({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 "${zm}" 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 "${zm}" 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 At="--skip-review";function Cs(e,t){return S0(e,t)}function ya(e,t){try{return Cs(e,eg(e,t)).length}catch{return 0}}function Yt(e,t,n="",o,r){let s=ya(e,o),i=ba(e,o),a=o?` ${o}`:"",l=o?"/push":"/push --all",d=Om(e,{just:r}),w=!!o&&o.endsWith(".md"),g=d&&w?` (${d.short} \u2014 ${d.cmd} once this page is delivered.)`:"";if(d&&!w){let C=s>0?` (${s} article${s===1?"":"s"}${o&&!o.endsWith(".md")?` in ${o}`:""} ${s===1?"carries":"carry"} text no editor has read, so ${s===1?"it cannot":"they cannot"} be sent up until /review${a} --blocked --fix runs \u2014 that can wait until the writing is done.)`:i>0?` (${i} article${i===1?"":"s"} break${i===1?"s":""} house style rules that block sending up \u2014 /lint${a} --blocked --fix clears that whenever you want.)`:"";return{text:`${n}${d.text}${C}`,cmd:d.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 C=s===1?"":"s",R=i>0?` ${i} also break house style rules \u2014 /lint${a} --blocked --fix clears those afterwards.`:"",T=`/review${a} --blocked --fix`;return{text:`${n}${s} article${C}${$} ${s===1?"carries":"carry"} text no editor has read, so pushing ${s===1?"it is":"them is"} blocked. ${T} reads ${s===1?"it":"just those"} and applies its fixes.${R} Then ${l}.${g}`,cmd:T}}return{text:`${n}${i} article${i===1?"":"s"}${$} break${i===1?"s":""} house style rules that block publishing. /lint${a} --blocked --fix corrects them in place \u2014 finding them costs nothing \u2014 then ${l}.${g}`,cmd:`/lint${a} --blocked --fix`}}function ba(e,t){try{return Zm(e,eg(e,t)).length}catch{return 0}}function ig(e,t){return Zm(e,t)}function hu(e,t,n){try{let o=Jm(e,uu(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 fu(e,t){let n=`/push${t.scope?` ${t.scope}`:" --all"}`,o=l=>`${l} article${l===1?"":"s"}`,r=[],s=e.pushed.length,i=t.elapsedMs!==void 0?` \xB7 ${_0(t.elapsedMs)}`:"",a=e.screenshotsUploaded>0?` \xB7 ${e.screenshotsUploaded} screenshot${e.screenshotsUploaded===1?"":"s"} uploaded`:"";if(s===0&&e.failed.length===0?r.push("Nothing was pushed \u2014 no articles were sent."):t.recorded<s?(r.push(`Pushed ${t.recorded}/${o(s)}${a}${i}.`),r.push(`${s-t.recorded} article${s-t.recorded===1?"":"s"} reported success but ${s-t.recorded===1?"is":"are"} not recorded in the category map \u2014 re-run ${n}.`)):(r.push(`Pushed ${o(s)}${e.created>0?` (${e.created} new)`:""}${a}${i}.`),r.push(`Saved on Document360 as draft${s===1?"":"s"} \u2014 readers don't see ${s===1?"it":"them"} until /publish takes ${s===1?"it":"them"} live.`)),e.stopped&&r.push(`Stopped: ${e.stopped.streak} articles in a row could not reach Document360${e.notRun.length>0?`, so the remaining ${e.notRun.length} ${e.notRun.length===1?"was":"were"} not attempted`:""}.`),e.failed.length>0){let l=e.failed.filter(g=>g.refused),d=O0(e.failed,t.docsRoot),w=e.failed.length;if(d.length===1&&w>1)r.push(`${o(w)} could not be pushed \u2014 all with the same error: ${d[0].error}`),r.push(...Qm(d[0].paths," \u2717 "));else{r.push(`${o(w)} could not be pushed:`);for(let g of d)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(...Qm(g.paths," ")))}l.length<e.failed.length&&(e.stopped?r.push(`Nothing was lost \u2014 your articles are unchanged. Re-run ${n} when Document360 is back.`):r.push(`Re-run ${n} to retry the rest \u2014 articles already saved are sent again only if they changed.`))}if(e.notRun.length>0&&!e.stopped&&r.push(`\u26A0 ${o(e.notRun.length)} never started (the run was stopped): ${L0(e.notRun)}`),e.missingShots.length>0){let l=e.missingShots.flatMap(d=>d.ids);r.push(`\u26A0 ${l.length} screenshot${l.length===1?"":"s"} in ${o(e.missingShots.length)} ${l.length===1?"has":"have"} not been taken, so the description was published instead: /screenshot capture`)}return t.conflictsSkipped&&t.conflictsSkipped>0&&r.push(Rs(t.conflictsSkipped)),r}var L0=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,cu=5;function Qm(e,t){let n=e.slice(0,cu).map(o=>`${t}${o}`);return e.length>cu&&n.push(`${" ".repeat(t.length)}\u2026 +${e.length-cu} more`),n}function O0(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 _0(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 Vt(e,t,n=0,o){let r=C0(e.cwd,t,{allowUnreviewed:o?.skipReview===!0,allowStyleErrors:o?.skipStyle===!0});if(!r.clear){for(let l of P0(r,t.length,{act:"push"}))console.log(V(l));return{kind:"continue"}}let s={aborted:!1,partitions:0,failed:0,notRun:0,producedNothing:!0},i={retryable:0,stopped:!1},a=async(l,d)=>{let w=Date.now();console.log(m(d?`Resolving cross-links in ${l.length} article${l.length===1?"":"s"} whose targets published this run (second pass)\u2026`:`Pushing ${l.length} article${l.length===1?"":"s"} to Document360 (${E0} at a time)\u2026`));let g=await T0({cwd:e.cwd,...e.profileName?{profileName:e.profileName}:{},paths:l,allowProdWrites:e.allowProdWrites?.()===!0,...o?.allowUnpullable===!0?{allowUnpullable:!0}:{},onEvent:N=>{N.type==="article_done"?console.log(Y(` \u2713 ${N.result.path}${N.result.action==="created"?" (new)":""}`)):N.type==="article_failed"&&console.log(_(` \u2717 ${N.failure.path}`))}});console.log("");let $=hu(e.cwd,l,e.profileName);d||(i={retryable:g.failed.filter(N=>!N.refused).length,stopped:!!g.stopped},s={aborted:g.aborted||!!g.stopped,partitions:v0(l).length,failed:g.failed.length,notRun:g.notRun.length,producedNothing:g.pushed.length===0,verifiedComplete:$>=l.length,leftBehind:n});let P=g.pushed.length>0;for(let N of fu(g,{recorded:$,elapsedMs:Date.now()-w,docsRoot:N0(e.cwd),...d?{}:{conflictsSkipped:n},...o?.scope?{scope:o.scope}:{}}))console.log(P&&g.failed.length===0?Y(N):V(N));let C=g.aborted||!!g.stopped;if(!P)return C;let R=pu(e.cwd,e.profileName);R&&console.log(m(R));let T=gr(e.cwd,e.profileName);if(T&&console.log(m(T)),C)return C;try{let N=ng(await tg({cwd:e.cwd,profileName:e.profileName,onRateLimit:B=>console.log(m(` Document360 rate limit \u2014 waiting ${Math.ceil(B.waitMs/1e3)}s\u2026`))}));N&&console.log(N.startsWith("\u26A0")?V(N):m(N))}catch{}try{let N=rg(await og({cwd:e.cwd,profileName:e.profileName}));N&&console.log(m(N))}catch{}let D=await Ss(e.cwd,e.profileName);return D&&console.log(m(D)),C};try{if(!await a(t,!1)){let d=await mu(e.cwd,e.profileName,t);if(d.length>0&&await a(d,!0),qt(s))for(let w of Tt(e.cwd,o?.scope?`/push ${o.scope}`:"/push --all"))console.log(Y(w))}}catch(l){console.log(_(`Push run failed: ${l.message}`))}if(console.log(""),i.retryable>0){let l=Re("/push",o?.scope?"":"--all",o?.scope);return console.log(m(i.stopped?`Next: ${l} \u2014 your articles are unchanged, so it picks up where the run left off.`:`Next: ${l} \u2014 retries the ${i.retryable} article${i.retryable===1?"":"s"} that could not be saved.`)),{kind:"continue",ownNext:!0}}return{kind:"continue"}}async function ka(e,t,n){let o=x0(e,n);if(o.length===0)return[];let r=new Set(du((await ga({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function mu(e,t,n){try{let o=new Set(n),r=await ga({cwd:e,profileName:t});return du(r.entries).map(s=>s.path).filter(s=>o.has(s))}catch{return[]}}async function M0(e,t,n){try{let o=await A0({cwd:e,...t?{profileName:t}:{},relPath:n.replace(/\\/g,"/"),preview:!0});console.log(""),console.log(Y(`${o.title}`)),console.log(m(`${o.path} \xB7 ${o.articleId?`updates article ${o.articleId}`:"would be created as a new article"}`)),o.shots.length>0&&console.log(m(`${o.shots.length} screenshot${o.shots.length===1?"":"s"} embedded: ${o.shots.map(r=>r.id).join(", ")}`)),o.missingShots.length>0&&console.log(V(`\u26A0 ${o.missingShots.length} screenshot${o.missingShots.length===1?"":"s"} not taken yet \u2014 the description publishes instead: ${o.missingShots.join(", ")}`)),console.log(m("\u2500".repeat(Math.min(80,Math.max(20,(process.stdout.columns??80)-1))))),console.log(o.body),console.log(m("\u2500".repeat(Math.min(80,Math.max(20,(process.stdout.columns??80)-1))))),console.log(m(`Nothing was sent. Run /push ${o.path} to save it as a draft.`))}catch(o){console.log(_(o.message))}return{kind:"continue"}}async function $a(e,t){let n=Ve(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(_(n.reason)),{kind:"continue"};let o=e.includes(At),r=e.includes(D0);if(e.includes("--preview")){let i=e.find(a=>!a.startsWith("--"));return i?await M0(t?.cwd??process.cwd(),t?.profileName,i):(console.log(_("Which article? Use /push --preview <path> \u2014 a preview is per article.")),{kind:"continue"})}let s=e[0];if(e.includes("--screenshots")||e.includes("--shots")){let i=t?.cwd??process.cwd(),a=e.find(P=>!P.startsWith("--")),l=Fe(i),d=la(l,a);if(d.length===0){let P=l.filter(C=>C.state==="captured").length;return console.log(m(P>0?`${P} screenshot${P===1?" has":"s have"} been taken but the callouts aren't drawn on yet, so there is nothing to embed \u2014 /screenshot annotate finishes ${P===1?"it":"them"}.`:a?`No captured screenshots in ${a} \u2014 /push --screenshots covers the whole knowledge base.`:"No captured screenshots yet \u2014 /screenshot capture first.")),{kind:"continue"}}let w=ca(l,a);w&&console.log(w);let g=ua(l);g&&console.log(g);let $=Re("","--screenshots",a).trim();return await Vt(t??{cwd:process.cwd()},d,0,{skipReview:o,skipStyle:r,scope:$})}if(s==="--related"&&e[1]){if(!t)return{kind:"continue"};let i=await ka(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return i.length===0?(console.log(Y("\u2713 All related articles are already on Document360.")),{kind:"continue"}):await Vt(t,i,0,{skipReview:o,skipStyle:r,scope:`--related ${e[1]}`})}if(s==="--all"){console.log(m("Checking what needs pushing\u2026"));try{let i=await ga({cwd:t?.cwd??process.cwd()}),{clean:a,conflicts:l}=yo(i.entries),d=wa(i.entries),w=e.includes("--force")&&l.length>0;d>0&&console.log(V(`\u26A0 ${d} article(s) already exist on Document360 but aren't linked \u2014 left out (pushing would duplicate them). Run /catch-up or ask me to link them first.`)),l.length>0&&!w&&console.log(V(Rs(l.length)));let g=w?[...a,...l]:a;if(g.length===0){if(l.length>0){let P=gr(t?.cwd??process.cwd(),t?.profileName);return P&&console.log(m(P)),console.log(m("Resolve the conflicts: /resolve")),{kind:"continue"}}console.log(Y(d>0?"\u2713 Nothing else is ahead of Document360 to push.":"\u2713 Nothing is ahead of Document360 \u2014 nothing to push."));let $=gr(t?.cwd??process.cwd(),t?.profileName);if($&&console.log(m($)),t)try{let P=ng(await tg({cwd:t.cwd,profileName:t.profileName,onRateLimit:R=>console.log(m(` Document360 rate limit \u2014 waiting ${Math.ceil(R.waitMs/1e3)}s\u2026`))}));P&&console.log(P.startsWith("\u26A0")?V(P):m(P));let C=rg(await og({cwd:t.cwd,profileName:t.profileName}));C&&console.log(m(C))}catch{}return{kind:"continue"}}return await Vt(t??{cwd:process.cwd()},g.map($=>$.path),w?0:l.length,{skipReview:o,skipStyle:r,allowUnpullable:w})}catch(i){return console.log(_(`Could not compute sync status: ${i.message}`)),{kind:"continue"}}}if(s&&s.startsWith("--")&&(s=e.find(i=>!i.startsWith("--"))??""),!s){console.log(m("Checking what needs pushing\u2026"));let i,a=0;try{let l=await ga({cwd:t?.cwd??process.cwd()}),{clean:d,conflicts:w}=yo(l.entries);i=d,a=w.length;let g=wa(l.entries);if(g>0&&console.log(V(`\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.`)),w.length>0&&console.log(V(Rs(w.length))),i.length===0&&w.length>0)return console.log(m("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(l){return console.log(_(`Could not compute sync status: ${l.message}`)),console.log(m("Push a specific article: /push <article-path>")),{kind:"continue"}}if(i.length===0)return console.log(Y("\u2713 Nothing is ahead of Document360 \u2014 nothing to push.")),console.log(m(" (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} ${m(`(${l.label})`)}`);return console.log(m("Run: /push <article-path>")),{kind:"continue"}}try{s=await t.withPausedInput(()=>$0({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(m("Cancelled.")),{kind:"continue"}}if(s==="--all")return await Vt(t,i.map(l=>l.path),a,{skipReview:o,skipStyle:r})}return await Vt(t??{cwd:process.cwd()},[s],0,{skipReview:o,skipStyle:r,scope:s})}se();import{select as U0}from"@inquirer/prompts";import{computeSyncStatus as W0,localAheadPaths as B0,pendingDrafts as H0,publishArticleLive as G0,publishGateVerdict as q0,publishGateLines as V0,blockedPaths as Y0,resolveActiveProfile as FL,SKIP_STYLE_FLAG as K0,SKIP_SHOTS_FLAG as z0}from"document360-engine";var F0={check:"/check is now /lint (same command).",publish:"/publish now means taking drafts LIVE to readers \u2014 saving your local edits to Document360 is /push."},ag=new Set;function wn(e){let t=F0[e.replace(/^\//,"")];return!t||ag.has(e)?null:(ag.add(e),t)}var X0=150,Q0=e=>e>0?new Promise(t=>setTimeout(t,e)):Promise.resolve(),wu=e=>e===1?"":"s",gu=e=>e.replace(/\\/g,"/").split("/").pop()??e;function yu(e){return e.includes("--screenshots")||e.includes("--shots")||e[0]==="--related"}async function bu(e,t,n){await W0({cwd:e,profileName:t});let o=n?n.replace(/\\/g,"/").replace(/\/+$/,""):null;return H0(e,t).filter(r=>!o||r.path===o||r.path.startsWith(`${o}/`)).map(r=>({...r,label:J0(e,r.path)}))}function J0(e,t){let n=Ji(e,t)??bs(t),o=Qi(t),r=o?Nn(o):"";return r?`${r} \u203A ${n}`:n}function Z0(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 ku(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=B0(e,t).filter(a=>!s||a===s||a.startsWith(`${s}/`)).length;return i>0&&r.push(`${i} article${wu(i)} ${i===1?"has":"have"} local edits that aren't on Document360 yet \u2014 that's /push${n?` ${n}`:""}.`),{lines:r,ahead:i}}async function $u(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 G0({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 Q0(X0)}return r}function vu(e){let{published:t,blocked:n,failed:o}=e,r=[];if(t.length>0){r.push(`\u2713 ${t.length} article${wu(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 ${gu(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 ${gu(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 lg(e,t){let n=t?.cwd??process.cwd(),o=wn("publish");if(yu(e))return o&&console.log(m(`\u2192 ${o}`)),console.log(m("Running /push\u2026")),$a(e,t);let r=Ve(n,t?.profileName);if(!r.ok)return console.log(_(r.reason)),{kind:"continue"};o&&console.log(m(`\u2192 ${o}`));let s=e.includes(At),i=e.includes(K0),a=e.includes(z0),l=e.includes("--all"),d=e.find(T=>!T.startsWith("--"));console.log(m("Checking what is waiting to go live\u2026"));let w;try{w=await bu(n,t?.profileName,d)}catch(T){return console.log(_(`Could not check Document360: ${T.message}`)),{kind:"continue"}}if(w.length===0){for(let T of ku(n,t?.profileName,d).lines)console.log(T.startsWith("\u2713")?Y(T):m(T));return{kind:"continue"}}let g=q0(n,w.map(T=>T.path),{allowUnreviewed:s,allowStyleErrors:i,checkScreenshots:!0,allowPlaceholders:a}),$=new Set(Y0(g)),P=w.filter(T=>!$.has(T.path));if($.size>0)for(let T of V0(g,w.length,{scope:d,act:"publish",going:P.length}))console.log(V(T));if(P.length===0)return{kind:"continue"};w=P,console.log(""),console.log(`${w.length} draft${wu(w.length)} ${w.length===1?"is":"are"} ahead of what readers see:`);for(let T of Z0(w.slice(0,12)))console.log(m(T));w.length>12&&console.log(m(` \u2026and ${w.length-12} more`)),console.log("");let C=w;if(!l){let T=await U0({message:"Publish live to your readers?",choices:[{name:`Yes \u2014 publish all ${w.length} live`,value:"all"},...w.slice(0,8).map(D=>({name:`Just ${D.label}`,value:D.path})),{name:"No \u2014 leave them as drafts",value:"none"}]});if(T==="none")return console.log(m("Left as drafts. Nothing changed.")),{kind:"continue"};T!=="all"&&(C=w.filter(D=>D.path===T))}let R=await $u(n,t?.profileName,C,{skipReview:s,skipStyle:i,onProgress:(T,D,N)=>console.log(m(` \u25B8 ${T+1}/${D} ${gu(N)}\u2026`))});console.log("");for(let T of vu(R))console.log(T.startsWith("\u2713")?Y(T):T.startsWith("\u2717")?V(T):m(T));return{kind:"continue"}}import{loadKnownConflicts as eR,localArticleTitle as tR,resolveActiveProfile as nR}from"document360-engine";function oR(e,t){let n=tR(e,t);return n||(t.split(/[\\/]/).pop()??t).replace(/\.md$/,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ")}function va(e,t){let n=[];try{n=eR(e,nR(e,t).name)}catch{return null}if(n.length===0)return null;let o=n.length,r=n.slice(0,3).map(i=>oR(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 wr={cmd:"/resolve",reason:"it walks each one with you \u2014 keep yours, take the portal's, or skip"};async function Ps(e){if(e?.cwd){let n=va(e.cwd,e.profileName);if(n)return{kind:"audit-blocked",note:n.note,lead:wr}}return{kind:"forward-to-agent",prompt:["Run the gap-analysis skill against this repo.","","Follow its stages in order:","1. d360_sync_status first; stop if any article is changed in both places, or changed on Document360 and not yet pulled down (the local copy cannot be trusted until that is resolved). Say which articles, in plain words, never the internal status word \u2014 and tell the user to run /resolve, which walks the affected articles one at a time (keep the local copy, take the portal's, or skip). Do NOT ask them to report back to you: they will run /resolve and then /audit again.","2. git diff since the lastAnalyzedCommit marker in d360-category-map.json (or last 30 days if no marker), filtered to the authoritativeSourceFiles paths.","2.5. d360_pending_hints: the source agent's own notes on what it shipped. Verify each (sources exist, commit is an ancestor of HEAD, source shows the surface) before trusting; fold verified ones into the table, flag the rest.","3. Map changes (diff + hints) to articles via their `sources:` frontmatter; read only implicated articles and changed source files. If articles are missing `sources:`, this is the one-time bootstrap pass, so backfill them.","4. Output the proposal table: | Article (path or proposed title) | Action (create | update | retire | link) | Reason | Evidence | Scope |, then stamp consumed hints.","","Do not start writing or updating any article yet; the proposal table is the deliverable."].join(`
|
|
333
|
+
`),display:"/audit"}}se();import{readProjectConfig as rR,writeProjectConfig as cg,autoBudgetUsd as sR,autoModeEnabled as iR,DEFAULT_AUTO_BUDGET_USD as aR}from"document360-engine";function He(e){return`$${e%1===0?e.toFixed(0):e.toFixed(2)}`}function Ts(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 As(e){let t=iR(e),n=sR(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 ${Ts(t)}`}];return t?(r.push({tone:"info",text:`Spending limit: ${He(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: ${He(n)} a run.`}),r}function xa(e,t,n,o=new Date){let r={...t,auto:{...t.auto,enabled:n,decidedAt:o.toISOString()}};return cg(r,e),[n?{tone:"ok",text:J("\u2713")+"Auto mode ON \u2014 "+Ts(!0)}:{tone:"ok",text:J("\u2713")+"Manual mode \u2014 "+Ts(!1)},...As(r)]}function Ru(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 cg(o,e),[{tone:"ok",text:J("\u2713")+`Spending limit set to ${He(n)} a run.`},...As(o)]}function Su(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 Cu(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 xu=e=>{for(let t of e)console.log(t.tone==="ok"?Y(t.text):t.tone==="warn"?V(t.text):t.tone==="error"?_(t.text):m(t.text))};async function ug(e,t){let n=t.cwd,o=rR(n);if(!o)return console.log(_("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=Su(e);if(r.malformed)return console.log(_(`I could not read that spending limit. Give it as an amount, like: /auto --budget 150 (the standard limit is ${He(aR)}).`)),{kind:"continue"};let s=Cu(e,r.usd);if(r.usd!==void 0&&!s){let i=Ru(n,o,r.usd);return i&&xu(i),{kind:"continue"}}if(!s||s==="status")return xu(As(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 xu(xa(n,i,s==="on")),{kind:"continue"}}return console.log(_(`I don't know "${s}". Use: /auto on \xB7 /auto off \xB7 /auto status \xB7 /auto --budget <amount>`)),{kind:"continue"}}se();import{readProjectConfig as lR}from"document360-engine";function Pu(){return["Run the discover-product skill against this repo.","","Build (or continue refining) the product brief at `.d360-writer/product-brief.md` by interviewing the","source repo's coding agent (the builder):","1. Gather all grounding: the code surface (analyze-codebase pass), `.d360-writer/architecture/`"," (+ CREATOR-NOTES), any specs under `.d360-writer/input/`, existing docs, git log, and the current"," product brief if one exists.","2. Self-assess against the 8-point readiness rubric (identity, audience, core mental model,"," misconceptions, positioning, key concepts & terminology, critical journeys, boundaries/non-goals).","3. Write/update the brief, with every claim cited to its grounding, and keep its frontmatter current"," (status, rounds, open_questions, last_updated).","4. For the dimensions you cannot yet ground confidently, ask the builder a focused batch (\u22646) of pointed",' questions via d360_ask_builder, with the subject prefixed "[discovery] ". Then END the turn;'," builder answers async; /catch-up will ingest the answers and continue the loop.","","Set status: confident and hand off to propose-structure ONLY when every rubric dimension passes. If the","builder stays silent across a few rounds, degrade gracefully per the skill (best-effort brief, flagged","open questions) rather than blocking the docs. Do NOT write or publish any articles in this turn."].join(`
|
|
334
|
+
`)}async function dg(e,t){let n=t?.cwd??process.cwd();return lR(n)?{kind:"forward-to-agent",prompt:Pu(),display:"/discover"}:(console.log(_("No d360-writer config here. Run /init first.")),{kind:"continue"})}se();import{checkbox as cR}from"@inquirer/prompts";import{inventoryRepo as uR,readProjectConfig as pg,writeProjectConfig as dR}from"document360-engine";function Tu(e,t){let n=pg(e);n&&(n.authoritativeSourceFiles=t,dR(n,e))}function Ra(e){let t=[`${e.fileCount}${e.fileCount>=5e3?"+":""} files`];return e.stacks.length&&t.push(e.stacks.join("+")),t.push(e.reason),t.join(" \xB7 ")}async function hg(e,t){let n=t?.cwd??process.cwd();if(!pg(n))return console.log(_("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=uR(n);if(o.length===0)return console.log(m('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(Z("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${m(Ra(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>cR({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${Ra(s)})`,value:s.path,checked:s.recommended})),pageSize:20}))}catch{return console.log(m("Cancelled.")),{kind:"continue"}}if(r.length===0)return console.log(m("Nothing selected \u2014 scope unchanged.")),{kind:"continue"};Tu(n,r),console.log(Y(`\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"}}se();import{confirm as $R}from"@inquirer/prompts";import{applyPull as Nu,computeSyncStatus as Sg,compareRemoteSources as vR,planPull as Cg,planImport as xR,applyImport as RR,establishBaselines as SR,rebaselineServerMeta as CR,D360AuthError as PR}from"document360-engine";se();var fg=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /push <path>):",paint:_,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /push <path>:",paint:V,mark:"M"},{status:"remote-ahead",header:"Changed on Document360 \u2014 pull with /pull <path> (or just /pull):",paint:Z,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:_,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:_,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint:xe,mark:"X"},{status:"untracked-local",header:"New here \u2014 not on Document360 yet (publish to add them):",paint:m,mark:"?"},{status:"untracked-remote",header:"On Document360 \u2014 not in your local docs yet (run /pull to import them):",paint:m,mark:"?"},{status:"unknown-base",header:"Tracked, not yet compared \u2014 run /pull --baseline to set a baseline (or the next publish/pull sets one):",paint:xe,mark:"\xB7"}];function pR(e){return e.path?e.path:`${e.title??"(untitled)"} ${xe(`[${e.articleId}]`)}`}function hR(e){let t=e/1e3;if(t<60)return`${t.toFixed(1)}s`;let n=Math.floor(t/60);return`${n}m ${Math.round(t-n*60)}s`}function Sa(e,t){let n=[],o=e.entries.filter(w=>w.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 w of o)n.push(` ${V("~")} ${V(w.path??"")} ${xe(`\u2192 "${w.link.title}"`)}`)}for(let w of fg){let g=e.entries.filter($=>$.status===w.status&&!(w.status==="untracked-local"&&$.link));if(g.length!==0){n.push(""),n.push(qe(w.header));for(let $ of g)n.push(` ${w.paint(w.mark)} ${w.paint(pR($))}${$.detail?xe(` (${$.detail})`):""}`)}}let r=e.counts["in-sync"]??0,s=e.entries.length;n.push("");let i={"in-sync":"up to date","local-ahead":"changed here","remote-ahead":"changed on Document360",conflict:"changed both places","untracked-local":"new here","untracked-remote":"only on Document360","deleted-local":"removed locally","deleted-remote":"gone from Document360",orphaned:"gone both sides","unknown-base":"not yet compared"},a=o.length,l=s===r?Y("\u2713 everything up to date"):[r>0?Y(`\u2713 ${r} up to date`):null,a>0?`${a} to link`:null,...fg.map(w=>{let g=(e.counts[w.status]??0)-(w.status==="untracked-local"?a:0);return g>0?`${g} ${i[w.status]}`:null})].filter(Boolean).join(xe(" \xB7 ")),d=t!==void 0?` \xB7 synced in ${hR(t)}`:"";return n.push(l+xe(` \xB7 ${s} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${d}`)),n}import{structuredPatch as fR}from"diff";import mg from"picocolors";var mR=80,yr=400,gR="\x1B[48;2;74;28;28m",wR="\x1B[48;2;24;66;24m",gg="\x1B[49m",Au=e=>String(e).padStart(5);function wg(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}function yg(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 Et(e,t,n,o=mR){let r=C=>{let R=C.replace(/\r\n/g,`
|
|
335
335
|
`);return R.endsWith(`
|
|
336
336
|
`)||R===""?R:R+`
|
|
337
|
-
`},s=r(e),i=r(t);if(s===i)return null;let a=Math.max(20,n-10),l=dR("a","b",s,i,"","",{context:3}),d=0,w=0,g=[];l.hunks.forEach((C,R)=>{R>0&&g.push(pg.gray(" \u2026"));let T=C.oldStart,D=C.newStart,N=[],W=[],I=()=>{for(let X=0;X<N.length;X++){let H=X<W.length?fg(N[X],W[X]):void 0;w++,g.push(`${hR}${Cu(T++)} - ${mg(N[X],a,H)}${hg}`)}for(let X=0;X<W.length;X++){let H=X<N.length?fg(N[X],W[X]):void 0;d++,g.push(`${fR}${Cu(D++)} + ${mg(W[X],a,H)}${hg}`)}N=[],W=[]};for(let X of C.lines){let H=X[0],de=X.slice(1);H==="-"?N.push(de):H==="+"?W.push(de):(I(),g.push(pg.gray(Cu(D))+" "+de.slice(0,a)),T++,D++)}I()});let $=Math.max(1,o),P=g.slice(0,$);return{added:d,removed:w,lines:P,hidden:Math.max(0,g.length-$)}}import{select as bg}from"@inquirer/prompts";import{applyPull as kg,computeSyncStatus as mR,isPullWouldBlankError as wg,localArticleTitle as gR,planPull as yg}from"document360-engine";function Ra(){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 Sa(){return"Publish your copy over the portal (settles it) \xB7 Skip?"}function gg(){return"(l publish yours \xB7 s skip \u2014 anything else stops, keeping your answers so far)"}function Ca(e){if(e.length===0)return[];let t=e.length,n=e.slice(0,3).join(", ")+(t>3?`, +${t-3} more`:"");return[`${t} article${t===1?"":"s"} stay${t===1?"s":""} flagged \u2014 Document360 cannot hand ${t===1?"its":"their"} markdown back: ${n}`,"Two ways out: run /resolve and press l to publish your copy over the portal, or ask your Document360 admin to move the article back to the Markdown (Editor 3.0) editor, then run /resolve again."]}function Pu(e){return`Cannot take the portal copy of ${e} \u2014 Document360 will not return it as markdown. Left as it was.`}se();var Pa=e=>e===1?"":"s";async function Tu(e,t,n=1){console.log(""),console.log(`${Z("\u25CF")} ${He(t.title)} ${xe(`(${t.path})`)}`);for(let i of t.notes)console.log(G(` \u26A0 ${i}`));let o=Tt(t.oldContent,t.newContent,Math.max(40,(process.stdout.columns??80)-1),wr);if(o){console.log(xe(` \u23BF local \u2192 portal: +${o.added} / -${o.removed} line${Pa(o.added+o.removed)}`));for(let i of o.lines)console.log(i);o.hidden>0&&console.log(m(` \u2026 +${o.hidden} more diff lines`))}else console.log(m(" Local already matches the portal content \u2014 resolving just advances the sync base."));let r=n>1,s=await e.withPausedInput(()=>bg({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"?(kg({cwd:e.cwd,profileName:e.profileName},t),console.log(Y(" \u2713 Took the portal copy (local overwritten, sync base advanced).")),"took-portal"):s==="local"?"keep-local":s==="skip"?(console.log(m(" Skipped \u2014 still a conflict.")),"skipped"):s==="local-all"?"keep-local-all":s==="portal-all"?"took-portal-all":"skipped-all"}async function wR(e,t){console.log(""),console.log(`${Z("\u25CF")} ${He(gR(e.cwd,t)??t)} ${xe(`(${t})`)}`);for(let o of Ra())console.log(G(` \u26A0 ${o}`));return await e.withPausedInput(()=>bg({message:Sa(),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(m(" Skipped \u2014 still a conflict.")),"skipped")}async function $g(e,t){let n=Ge(t.cwd,t.profileName);if(!n.ok)return console.log(_(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let s=(await mR({cwd:t.cwd,profileName:t.profileName})).entries.filter(l=>l.status==="conflict"&&l.path).map(l=>l.path);if(o){if(!s.includes(o))return console.log(Y(`${o} isn't in conflict \u2014 nothing to resolve.`)),{kind:"continue"};s=[o]}if(s.length===0)return console.log(Y("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let i=[],a=[];for(let[l,d]of s.entries()){let w;try{w=await yg({cwd:t.cwd,profileName:t.profileName,relPath:d})}catch(P){if(!wg(P))throw P;await wR(t,d)==="keep-local"?i.push(d):a.push(d);continue}let g=await Tu(t,w,s.length-l);if(g==="keep-local"&&i.push(d),!g.endsWith("-all"))continue;let $=s.slice(l);if(g==="keep-local-all")i.push(...$),console.log(m(` Keeping local for all ${$.length} \u2014 publishing them over the portal.`));else if(g==="took-portal-all"){let P=0;for(let C of $)try{kg({cwd:t.cwd,profileName:t.profileName},await yg({cwd:t.cwd,profileName:t.profileName,relPath:C})),P++}catch(R){console.log(_(` \u2717 ${C}: ${R.message}`)),wg(R)&&a.push(C)}console.log(Y(` \u2713 Took the portal copy of ${P} article${Pa(P)} (local overwritten, sync base advanced).`))}else console.log(m(` Skipped all ${$.length} \u2014 still conflict${Pa($.length)}.`));break}for(let l of Ca(a))console.log(G(`\u26A0 ${l}`));if(i.length>0)return console.log(m(`Publishing ${i.length} kept-local article${Pa(i.length)} over the portal\u2026`)),await qt(t,i,0,{allowUnpullable:!0})}catch(r){console.log(_(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function Rg(e,t){let n=Ge(t.cwd,t.profileName);if(!n.ok)return console.log(_(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await SR(t),{kind:"continue"};if(o==="--baseline")return await CR(t,e.filter(i=>i!=="--baseline")),{kind:"continue"};if(o==="--compare")return await PR(t),{kind:"continue"};if(o)return console.log(_(`Unknown option: ${o}`)),console.log(m("Usage: /pull pull portal edits + import new portal articles")),console.log(m(" /pull <path> pull one article (or resolve a conflict)")),console.log(m(" /pull --status drift report only (no writes)")),console.log(m(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await TR(t,r),{kind:"continue"};console.log(m("Pulling changes from Document360\u2026"));let s=await Eu({cwd:t.cwd,profileName:t.profileName});for(let i of Du(s))console.log(i.tone==="ok"?Y(i.text):i.tone==="warn"?G(i.text):m(i.text));console.log("")}catch(r){r instanceof RR?console.log(_(r.message)):console.log(_(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function Eu(e){let t=await vg({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 xg({cwd:e.cwd,profileName:e.profileName,relPath:o.path});Au({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 kR({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});$R({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 Ta=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,yo=e=>e===1?"":"s";function Du(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${yo(e.pulled.length)} into local: ${Ta(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${yo(e.imported.length)}: ${Ta(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${yo(e.toPublish)} changed locally \u2014 /push saves them to Document360.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${yo(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). (${Ta(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${yo(e.failed.length)} failed: ${Ta(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 SR(e){console.log(m("Checking Document360 for drift\u2026"));let t=Date.now(),n=await vg({cwd:e.cwd,profileName:e.profileName});for(let o of xa(n,Date.now()-t))console.log(o);console.log("")}async function CR(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(m(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await vR({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await xR({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(Y("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(Y(`\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(Y(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(G(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(m(` - ${s.path} (${s.reason})`))}}async function PR(e){console.log(m("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await bR({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${He(String(t.legacyCount))} \xB7 Manifest: ${He(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(Y("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(_(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(G(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(G(` ${t.onlyInManifest.length} only in the manifest: ${t.onlyInManifest.slice(0,5).join(", ")}`)),console.log(m(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function TR(e,t){let n=t.replace(/\\/g,"/"),o=await xg({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await Tu(e,o)==="keep-local"&&(console.log(m(`Publishing ${o.path} over the portal\u2026`)),await qt(e,[o.path]));return}console.log(""),console.log(`${Z("\u25CF")} ${He(o.title)} ${xe(`(${o.path})`)}`);for(let i of o.notes)console.log(G(` \u26A0 ${i}`));let r=Tt(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1),wr);if(!r){console.log(m(" Local file already matches the remote content \u2014 advancing the sync base only.")),Au({cwd:e.cwd,profileName:e.profileName},o);return}console.log(xe(` \u23BF Added ${r.added} line${yo(r.added)}, removed ${r.removed} line${yo(r.removed)}`));for(let i of r.lines)console.log(i);if(r.hidden>0&&console.log(m(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>yR({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(m(" Skipped."));return}Au({cwd:e.cwd,profileName:e.profileName},o),console.log(Y(` \u2713 Pulled ${o.path} (sync base advanced).`))}se();import{statSync as FR}from"node:fs";import{resolve as UR}from"node:path";import{estimateBulkCost as WR,planPartitions as BR,readProjectConfig as HR,resolveModelForOperation as GR,runPartitioned as qR,trackedArticlePaths as VR}from"document360-engine";function Ln(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 Sg(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 yr=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 Aa(e,t){let n=t-e;return n>=300&&n>=t*.2}function At(e,t,n,o=Date.now(),r){let s=t.reduce((a,l)=>a+(l.inputTokens??0),0),i=t.reduce((a,l)=>a+(l.cacheReadTokens??0),0);return{seconds:Math.max(0,Math.round((o-e)/1e3)),outputTokens:t.reduce((a,l)=>a+l.outputTokens,0),inputTokens:s,...s>0?{cachedPct:Math.round(i/s*100)}:{},...r!==void 0?{activeSeconds:r}:{},costUsd:n}}function Ea(e){return e.activeSeconds!==void 0&&Aa(e.activeSeconds,e.seconds)?`${Nu(e.seconds)} elapsed \xB7 ${Nu(e.activeSeconds)} working`:Nu(e.seconds)}var Cg=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:`${e}`,Nu=e=>{if(e<60)return`${e}s`;let t=Math.floor(e/60);return t<60?`${t}m ${e%60}s`:`${Math.floor(t/60)}h ${t%60}m`};function en(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 ${Ea(e)}, ${Cg(e.inputTokens)}\u2192${Cg(e.outputTokens)} tokens${t}${n})`}import ke from"picocolors";import Ou from"wrap-ansi";import _u from"string-width";se();import On from"picocolors";import Na from"wrap-ansi";import Da 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|[<category>] --screenshots] [--preview] [--skip-review]",desc:"Save your articles to Document360 as drafts \u2014 readers don't see them until /publish (no arg: pick; --all: every candidate; --screenshots: re-save articles with captured shots so images embed, optionally narrowed to one category; --preview <path>: show exactly what would be sent, and send nothing). Blocked until each article has had /review --fix \u2014 AI-written text gets an editor first; --skip-review overrides deliberately",group:"publish"},{name:"publish",usage:"/publish [path|<category>|--all] [--skip-review]",desc:"Take the drafts on Document360 LIVE to your readers (the portal's own Publish). Always lists what would become visible and asks first; no arg or a category narrows it. Needs an editorial review \u2014 /review --blocked --fix",group:"publish"},{name:"style-guide",usage:"/style-guide [list | use <preset> | keep | pull [<n>] | learn | compile | explain <rule>]",desc:"Choose the writing rules your docs are held to. Bare: what is active now; list: every pack you can turn on; use: switch packs (records what is already there so nothing suddenly breaks); keep: settle on the rules you have today; pull: bring your Document360 project's own style guide down; learn: turn what your reviewers keep asking for into standing rules; compile: turn its mechanical statements into checks; explain: what one rule means and how to silence it",group:"docs"},{name:"lint",usage:"/lint [<category|path>] [--blocked] [--fix] [--full]",desc:"Lint the docs against the house rules: leaked internals, invented commands, stale facts, AI-tells, em dashes, callout shape (deterministic, no tokens). Every finding names the rule that produced it. Scope to a category/path; --blocked narrows to the errors that block publishing and leaves warnings and suggestions alone; --fix has the agent correct them in place; --full lists every finding instead of a capped summary",group:"docs"},{name:"review",usage:"/review [<category|path> | --all | --blocked | --stale] [--fix]",desc:"Independent senior-editor review: style guide, terminology/voice, grammar/clarity, structure, improvement suggestions. Bare: pick a category or everything; --blocked reads only the articles publishing is blocked on; --stale reads the ones the current editor has not read yet, so running it twice costs nothing; --all reviews the whole KB; --fix applies the corrections in place",group:"docs"},{name:"reorder",usage:"/reorder [<category> | --all]",desc:"Reorder articles within a category to the best reading order (renumbers NN- prefixes, fixes references + map); bare: pick a category or everything; new order syncs to Document360 on next /push",group:"docs"},{name:"structure",usage:"/structure",desc:"Show the documentation reading order (categories \u2192 articles) as it will appear on Document360",group:"docs"},{name:"status",usage:"/status [--all]",desc:'What stands between your work and your readers, before you spend anything: which articles no editor has read, which break a style rule your config makes blocking, which would show "[Screenshot: \u2026]" text to a reader, which are in conflict with the portal, and which are saved as drafts readers cannot see yet. Each group names the one command that clears it. Reads local files and the last sync \u2014 no network, no tokens. --all lists every article gate by gate',group:"publish"},{name:"retire",usage:"/retire [<path>]",desc:"Take an article off your readers on Document360 \u2014 it stops being visible, and nothing offers to publish it again. Nothing is deleted: the article, its version history and every reviewer comment stay. Bare: lists what is worth retiring (articles on Document360 that are no longer in your docs folder). /push puts one back \u2014 reviving is a publish like any other",group:"publish"},{name:"terms",usage:'/terms [<category>] [--all] [--approve "<term>"]',desc:"Is your knowledge base calling the same thing by the same name? Reads every article and reports terms spelled more than one way, short names that may be the long name abbreviated, and article titles out of step with the rest of their kind \u2014 the consistency an editor reading three articles at a time cannot see. Costs nothing and calls nothing. --approve records a spelling as the approved one, so every later run enforces it",group:"docs"},{name:"roadmap",usage:"/roadmap [--all | done [step]]",desc:"Show the docs campaign (the multi-session plan the agent maintains), grouped by the part of the job \u2014 progress + next step; `--all` also lists the steps a later pass replaced; `done` marks the next open step finished (add words from a title to pick another)",group:"docs"},{name:"audit",usage:"/audit [--auto on|off]",desc:"Gap analysis: code vs docs vs Document360 (what changed); --auto runs it at launch when code changed",group:"publish"},{name:"inbox",usage:"/inbox",desc:"Act on messages from the repo's coding agent (requests to document, answers to your questions)",group:"publish"},{name:"ask",usage:"/ask <question>",desc:"Ask your developers something the code cannot tell you: why a feature exists, when to use it, whether it can be undone",group:"publish"},{name:"share",usage:"/share [status|on|off]",desc:"Share your docs work with the team: get your builder's latest, then save + send yours (runs automatically; `off` leaves it to your coding agent)",group:"publish"},{name:"catch-up",usage:"/catch-up [--push]",desc:"Process ALL pending work (builder hints + requests + Document360 portal drift) \u2192 write \u2192 save to Document360 as drafts. --push does that last step for you, which still needs an editorial review first. For code changes, that's /audit",group:"publish"},{name:"comments",usage:"/comments [<article>] [--scope <category>] [--answer] [--all] [--resolve] [--answered] [--full]",desc:"Reviewer comments left on passages of your articles in the Document360 portal \u2014 bare: a table by article, pick a number to read its comments in full, then answer or go back; --answer: fix, push the draft, reply (threads stay open unless you add --resolve); --full re-reads every article",group:"publish"},{name:"pull",usage:"/pull [<path> | --status | --baseline]",desc:"Bring Document360 down: pull portal edits + import NEW portal articles. --status: drift report only \xB7 --baseline: set a sync base \xB7 <path>: one article / resolve a conflict",group:"publish"},{name:"resolve",usage:"/resolve [<path>]",desc:"Resolve conflicts (edited both here and on the portal): shows the diff, then keep local (push), take portal (pull), or skip \u2014 per article, or one answer for all remaining. Bare: walk them all",group:"publish"},{name:"convert",usage:"/convert [--scope <folder>] [--run]",desc:"Convert tracked articles to DFM (one-off legacy migration)",group:"publish"},{name:"profile",usage:"/profile [name|add <name> [env]]",desc:"Switch/create a Document360 connection (picker; s = session)",group:"setup"},{name:"workspace",usage:"/workspace [name]",desc:"Switch the Document360 workspace (picker)",group:"setup"},{name:"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"}],Pg={"/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 Tg(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(Pg[n])return Pg[n];let o=bo.find(r=>r.name===t);return o?o.desc:""}function Ag(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return bo.filter(n=>n.name.startsWith(t))}function Eg(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 AR=new RegExp(`^\\s*/(?:${bo.map(e=>e.name).join("|")})(?:\\s|$)`),Dg=e=>AR.test(e),Ng=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),jg=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),Ig=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function ER(e){let t=e.replace(/\r/g,"").split(`
|
|
338
|
-
`),n=[],o=0;for(;o<t.length;){let r=t[o];if(/^\s*```/.test(r)){let a=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)a.push(t[o++]);o++,n.push({kind:"code",lines:a});continue}if(
|
|
339
|
-
`).map(D=>
|
|
337
|
+
`},s=r(e),i=r(t);if(s===i)return null;let a=Math.max(20,n-10),l=fR("a","b",s,i,"","",{context:3}),d=0,w=0,g=[];l.hunks.forEach((C,R)=>{R>0&&g.push(mg.gray(" \u2026"));let T=C.oldStart,D=C.newStart,N=[],B=[],I=()=>{for(let X=0;X<N.length;X++){let q=X<B.length?wg(N[X],B[X]):void 0;w++,g.push(`${gR}${Au(T++)} - ${yg(N[X],a,q)}${gg}`)}for(let X=0;X<B.length;X++){let q=X<N.length?wg(N[X],B[X]):void 0;d++,g.push(`${wR}${Au(D++)} + ${yg(B[X],a,q)}${gg}`)}N=[],B=[]};for(let X of C.lines){let q=X[0],de=X.slice(1);q==="-"?N.push(de):q==="+"?B.push(de):(I(),g.push(mg.gray(Au(D))+" "+de.slice(0,a)),T++,D++)}I()});let $=Math.max(1,o),P=g.slice(0,$);return{added:d,removed:w,lines:P,hidden:Math.max(0,g.length-$)}}import{select as vg}from"@inquirer/prompts";import{applyPull as xg,computeSyncStatus as yR,isPullWouldBlankError as kg,localArticleTitle as bR,planPull as $g}from"document360-engine";function Ca(){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 Pa(){return"Publish your copy over the portal (settles it) \xB7 Skip?"}function bg(){return"(l publish yours \xB7 s skip \u2014 anything else stops, keeping your answers so far)"}function Ta(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 Eu(e){return`Cannot take the portal copy of ${e} \u2014 Document360 will not return it as markdown. Left as it was.`}se();var Aa=e=>e===1?"":"s";async function Du(e,t,n=1){console.log(""),console.log(`${Z("\u25CF")} ${qe(t.title)} ${xe(`(${t.path})`)}`);for(let i of t.notes)console.log(V(` \u26A0 ${i}`));let o=Et(t.oldContent,t.newContent,Math.max(40,(process.stdout.columns??80)-1),yr);if(o){console.log(xe(` \u23BF local \u2192 portal: +${o.added} / -${o.removed} line${Aa(o.added+o.removed)}`));for(let i of o.lines)console.log(i);o.hidden>0&&console.log(m(` \u2026 +${o.hidden} more diff lines`))}else console.log(m(" Local already matches the portal content \u2014 resolving just advances the sync base."));let r=n>1,s=await e.withPausedInput(()=>vg({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"?(xg({cwd:e.cwd,profileName:e.profileName},t),console.log(Y(" \u2713 Took the portal copy (local overwritten, sync base advanced).")),"took-portal"):s==="local"?"keep-local":s==="skip"?(console.log(m(" Skipped \u2014 still a conflict.")),"skipped"):s==="local-all"?"keep-local-all":s==="portal-all"?"took-portal-all":"skipped-all"}async function kR(e,t){console.log(""),console.log(`${Z("\u25CF")} ${qe(bR(e.cwd,t)??t)} ${xe(`(${t})`)}`);for(let o of Ca())console.log(V(` \u26A0 ${o}`));return await e.withPausedInput(()=>vg({message:Pa(),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(m(" Skipped \u2014 still a conflict.")),"skipped")}async function Rg(e,t){let n=Ve(t.cwd,t.profileName);if(!n.ok)return console.log(_(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let s=(await yR({cwd:t.cwd,profileName:t.profileName})).entries.filter(l=>l.status==="conflict"&&l.path).map(l=>l.path);if(o){if(!s.includes(o))return console.log(Y(`${o} isn't in conflict \u2014 nothing to resolve.`)),{kind:"continue"};s=[o]}if(s.length===0)return console.log(Y("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let i=[],a=[];for(let[l,d]of s.entries()){let w;try{w=await $g({cwd:t.cwd,profileName:t.profileName,relPath:d})}catch(P){if(!kg(P))throw P;await kR(t,d)==="keep-local"?i.push(d):a.push(d);continue}let g=await Du(t,w,s.length-l);if(g==="keep-local"&&i.push(d),!g.endsWith("-all"))continue;let $=s.slice(l);if(g==="keep-local-all")i.push(...$),console.log(m(` Keeping local for all ${$.length} \u2014 publishing them over the portal.`));else if(g==="took-portal-all"){let P=0;for(let C of $)try{xg({cwd:t.cwd,profileName:t.profileName},await $g({cwd:t.cwd,profileName:t.profileName,relPath:C})),P++}catch(R){console.log(_(` \u2717 ${C}: ${R.message}`)),kg(R)&&a.push(C)}console.log(Y(` \u2713 Took the portal copy of ${P} article${Aa(P)} (local overwritten, sync base advanced).`))}else console.log(m(` Skipped all ${$.length} \u2014 still conflict${Aa($.length)}.`));break}for(let l of Ta(a))console.log(V(`\u26A0 ${l}`));if(i.length>0)return console.log(m(`Publishing ${i.length} kept-local article${Aa(i.length)} over the portal\u2026`)),await Vt(t,i,0,{allowUnpullable:!0})}catch(r){console.log(_(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function Pg(e,t){let n=Ve(t.cwd,t.profileName);if(!n.ok)return console.log(_(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await TR(t),{kind:"continue"};if(o==="--baseline")return await AR(t,e.filter(i=>i!=="--baseline")),{kind:"continue"};if(o==="--compare")return await ER(t),{kind:"continue"};if(o)return console.log(_(`Unknown option: ${o}`)),console.log(m("Usage: /pull pull portal edits + import new portal articles")),console.log(m(" /pull <path> pull one article (or resolve a conflict)")),console.log(m(" /pull --status drift report only (no writes)")),console.log(m(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await DR(t,r),{kind:"continue"};console.log(m("Pulling changes from Document360\u2026"));let s=await ju({cwd:t.cwd,profileName:t.profileName});for(let i of Iu(s))console.log(i.tone==="ok"?Y(i.text):i.tone==="warn"?V(i.text):m(i.text));console.log("")}catch(r){r instanceof PR?console.log(_(r.message)):console.log(_(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function ju(e){let t=await Sg({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 Cg({cwd:e.cwd,profileName:e.profileName,relPath:o.path});Nu({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 xR({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});RR({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 Ea=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,bo=e=>e===1?"":"s";function Iu(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${bo(e.pulled.length)} into local: ${Ea(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${bo(e.imported.length)}: ${Ea(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${bo(e.toPublish)} changed locally \u2014 /push saves them to Document360.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${bo(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). (${Ea(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${bo(e.failed.length)} failed: ${Ea(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 TR(e){console.log(m("Checking Document360 for drift\u2026"));let t=Date.now(),n=await Sg({cwd:e.cwd,profileName:e.profileName});for(let o of Sa(n,Date.now()-t))console.log(o);console.log("")}async function AR(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(m(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await SR({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await CR({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(Y("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(Y(`\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(Y(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(V(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(m(` - ${s.path} (${s.reason})`))}}async function ER(e){console.log(m("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await vR({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(Y("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(_(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(V(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(V(` ${t.onlyInManifest.length} only in the manifest: ${t.onlyInManifest.slice(0,5).join(", ")}`)),console.log(m(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function DR(e,t){let n=t.replace(/\\/g,"/"),o=await Cg({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await Du(e,o)==="keep-local"&&(console.log(m(`Publishing ${o.path} over the portal\u2026`)),await Vt(e,[o.path]));return}console.log(""),console.log(`${Z("\u25CF")} ${qe(o.title)} ${xe(`(${o.path})`)}`);for(let i of o.notes)console.log(V(` \u26A0 ${i}`));let r=Et(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1),yr);if(!r){console.log(m(" Local file already matches the remote content \u2014 advancing the sync base only.")),Nu({cwd:e.cwd,profileName:e.profileName},o);return}console.log(xe(` \u23BF Added ${r.added} line${bo(r.added)}, removed ${r.removed} line${bo(r.removed)}`));for(let i of r.lines)console.log(i);if(r.hidden>0&&console.log(m(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>$R({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(m(" Skipped."));return}Nu({cwd:e.cwd,profileName:e.profileName},o),console.log(Y(` \u2713 Pulled ${o.path} (sync base advanced).`))}se();import{statSync as BR}from"node:fs";import{resolve as HR}from"node:path";import{estimateBulkCost as GR,planPartitions as qR,readProjectConfig as VR,resolveModelForOperation as YR,runPartitioned as KR,trackedArticlePaths as zR}from"document360-engine";function On(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 Tg(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 br=class{activeMs=0;last=0;timer=null;startedAt=0;stopped=null;start(t=Date.now()){this.timer||(this.startedAt=t,this.last=t,this.timer=setInterval(()=>this.tick(),1e3),this.timer.unref?.())}tick(t=Date.now()){let n=t-this.last;this.last=t,!(n<=0)&&(this.activeMs+=Math.min(n,5e3))}stop(t=Date.now()){return this.stopped?this.stopped:(this.timer&&(clearInterval(this.timer),this.timer=null),this.tick(t),this.stopped={activeSeconds:Math.max(0,Math.round(this.activeMs/1e3)),elapsedSeconds:Math.max(0,Math.round((t-this.startedAt)/1e3))},this.stopped)}};function Da(e,t){let n=t-e;return n>=300&&n>=t*.2}function Dt(e,t,n,o=Date.now(),r){let s=t.reduce((a,l)=>a+(l.inputTokens??0),0),i=t.reduce((a,l)=>a+(l.cacheReadTokens??0),0);return{seconds:Math.max(0,Math.round((o-e)/1e3)),outputTokens:t.reduce((a,l)=>a+l.outputTokens,0),inputTokens:s,...s>0?{cachedPct:Math.round(i/s*100)}:{},...r!==void 0?{activeSeconds:r}:{},costUsd:n}}function Na(e){return e.activeSeconds!==void 0&&Da(e.activeSeconds,e.seconds)?`${Lu(e.seconds)} elapsed \xB7 ${Lu(e.activeSeconds)} working`:Lu(e.seconds)}var Ag=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:`${e}`,Lu=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 tn(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 ${Na(e)}, ${Ag(e.inputTokens)}\u2192${Ag(e.outputTokens)} tokens${t}${n})`}import ke from"picocolors";import Fu from"wrap-ansi";import Uu from"string-width";se();import _n from"picocolors";import Ia from"wrap-ansi";import ja from"string-width";var ko=[{name:"init",usage:"/init",desc:"Pick an environment, scaffold .d360-writer/config.json, and set up the builder hand-off (prints the one-paste prompt)",group:"start"},{name:"login",usage:"/login",desc:"Sign in to Document360 (browser)",group:"start"},{name:"project",usage:"/project [name]",desc:"Choose the Document360 project (picker; lists all you can access)",group:"start"},{name:"devhints",usage:"/devhints",desc:"Re-show/refresh the builder hand-off prompt (set up by /init; run anytime to hand your repo agent the latest)",group:"start"},{name:"scope",usage:"/scope",desc:"Choose which repo folders back the docs (monorepos)",group:"start"},{name:"genre",usage:"/genre [web|cli|service|library|auto]",desc:"Set/show the product genre \u2014 picks the docs craft playbook (usually auto-detected; set it if it guessed wrong)",group:"start"},{name:"mcp",usage:"/mcp [list|add|remove]",desc:"Connect MCP servers (Notion, Linear, \u2026)",group:"start"},{name:"discover",usage:"/discover",desc:"Interview your builder to understand the product (identity, mental model, misconceptions, positioning) \u2192 pins a product brief that grounds the docs; asks focused questions and loops until confident",group:"docs"},{name:"draft",usage:"/draft [<feature>]",desc:"Draft a feature's articles from its PRDs/specs in .d360-writer/input/ + the code",group:"docs"},{name:"document",usage:"/document [<what>] [--push]",desc:"Document a shipped change \u2014 the agent picks the action (new section/article/update); bare: act on builder requests. --push then saves the result to Document360 as drafts, which still needs an editorial review first",group:"docs"},{name:"write",usage:"/write [--preview|--scope <cat>|<path>] [--rewrite] [--concurrency N] [--skip-style]",desc:"Write the planned articles in parallel (starts immediately; --preview shows plan + cost first; --rewrite regenerates already-written articles; --concurrency default 3). Anything that would block publishing is corrected in one automatic pass before the run finishes; --skip-style leaves it to /lint",group:"docs"},{name:"screenshot",usage:"/screenshot [author|capture|annotate|verify|checklist|list] [id|path|--all|--failed|--blocked]",desc:"Screenshots, one family \u2014 bare: pick what to do; author: write capture specs; capture: take the shots (--all re-shoots everything; --failed re-runs the ones that did not work; --blocked re-runs the ones waiting on app data); annotate: draw the callouts on shots already taken, no browser needed (--all --force re-draws after a wording or style change); verify: judge the finished pictures and mark them verified (both run automatically after a capture); checklist: what to stage + dev test-id requests; list: status + what to stage",group:"docs"},{name:"preview",usage:"/preview [path|id]",desc:"Render an article (no arg: pick from tracked)",group:"docs"},{name:"push",usage:"/push [path|--all|[<category>] --screenshots] [--preview] [--skip-review]",desc:"Save your articles to Document360 as drafts \u2014 readers don't see them until /publish (no arg: pick; --all: every candidate; --screenshots: re-save articles with captured shots so images embed, optionally narrowed to one category; --preview <path>: show exactly what would be sent, and send nothing). Blocked until each article has had /review --fix \u2014 AI-written text gets an editor first; --skip-review overrides deliberately",group:"publish"},{name:"publish",usage:"/publish [path|<category>|--all] [--skip-review]",desc:"Take the drafts on Document360 LIVE to your readers (the portal's own Publish). Always lists what would become visible and asks first; no arg or a category narrows it. Needs an editorial review \u2014 /review --blocked --fix",group:"publish"},{name:"style-guide",usage:"/style-guide [list | use <preset> | keep | pull [<n>] | learn | compile | explain <rule>]",desc:"Choose the writing rules your docs are held to. Bare: what is active now; list: every pack you can turn on; use: switch packs (records what is already there so nothing suddenly breaks); keep: settle on the rules you have today; pull: bring your Document360 project's own style guide down; learn: turn what your reviewers keep asking for into standing rules; compile: turn its mechanical statements into checks; explain: what one rule means and how to silence it",group:"docs"},{name:"lint",usage:"/lint [<category|path>] [--blocked] [--fix] [--full]",desc:"Lint the docs against the house rules: leaked internals, invented commands, stale facts, AI-tells, em dashes, callout shape (deterministic, no tokens). Every finding names the rule that produced it. Scope to a category/path; --blocked narrows to the errors that block publishing and leaves warnings and suggestions alone; --fix has the agent correct them in place; --full lists every finding instead of a capped summary",group:"docs"},{name:"review",usage:"/review [<category|path> | --all | --blocked | --stale] [--fix]",desc:"Independent senior-editor review: style guide, terminology/voice, grammar/clarity, structure, improvement suggestions. Bare: pick a category or everything; --blocked reads only the articles publishing is blocked on; --stale reads the ones the current editor has not read yet, so running it twice costs nothing; --all reviews the whole KB; --fix applies the corrections in place",group:"docs"},{name:"reorder",usage:"/reorder [<category> | --all]",desc:"Reorder articles within a category to the best reading order (renumbers NN- prefixes, fixes references + map); bare: pick a category or everything; new order syncs to Document360 on next /push",group:"docs"},{name:"structure",usage:"/structure",desc:"Show the documentation reading order (categories \u2192 articles) as it will appear on Document360",group:"docs"},{name:"status",usage:"/status [--all]",desc:'What stands between your work and your readers, before you spend anything: which articles no editor has read, which break a style rule your config makes blocking, which would show "[Screenshot: \u2026]" text to a reader, which are in conflict with the portal, and which are saved as drafts readers cannot see yet. Each group names the one command that clears it. Reads local files and the last sync \u2014 no network, no tokens. --all lists every article gate by gate',group:"publish"},{name:"retire",usage:"/retire [<path>]",desc:"Take an article off your readers on Document360 \u2014 it stops being visible, and nothing offers to publish it again. Nothing is deleted: the article, its version history and every reviewer comment stay. Bare: lists what is worth retiring (articles on Document360 that are no longer in your docs folder). /push puts one back \u2014 reviving is a publish like any other",group:"publish"},{name:"terms",usage:'/terms [<category>] [--all] [--approve "<term>"]',desc:"Is your knowledge base calling the same thing by the same name? Reads every article and reports terms spelled more than one way, short names that may be the long name abbreviated, and article titles out of step with the rest of their kind \u2014 the consistency an editor reading three articles at a time cannot see. Costs nothing and calls nothing. --approve records a spelling as the approved one, so every later run enforces it",group:"docs"},{name:"roadmap",usage:"/roadmap [--all | done [step]]",desc:"Show the docs campaign (the multi-session plan the agent maintains), grouped by the part of the job \u2014 progress + next step; `--all` also lists the steps a later pass replaced; `done` marks the next open step finished (add words from a title to pick another)",group:"docs"},{name:"audit",usage:"/audit [--auto on|off]",desc:"Gap analysis: code vs docs vs Document360 (what changed); --auto runs it at launch when code changed",group:"publish"},{name:"inbox",usage:"/inbox",desc:"Act on messages from the repo's coding agent (requests to document, answers to your questions)",group:"publish"},{name:"ask",usage:"/ask <question>",desc:"Ask your developers something the code cannot tell you: why a feature exists, when to use it, whether it can be undone",group:"publish"},{name:"share",usage:"/share [status|on|off]",desc:"Share your docs work with the team: get your builder's latest, then save + send yours (runs automatically; `off` leaves it to your coding agent)",group:"publish"},{name:"catch-up",usage:"/catch-up [--push]",desc:"Process ALL pending work (builder hints + requests + Document360 portal drift) \u2192 write \u2192 save to Document360 as drafts. --push does that last step for you, which still needs an editorial review first. For code changes, that's /audit",group:"publish"},{name:"comments",usage:"/comments [<article>] [--scope <category>] [--answer] [--all] [--resolve] [--answered] [--full]",desc:"Reviewer comments left on passages of your articles in the Document360 portal \u2014 bare: a table by article, pick a number to read its comments in full, then answer or go back; --answer: fix, push the draft, reply (threads stay open unless you add --resolve); --full re-reads every article",group:"publish"},{name:"pull",usage:"/pull [<path> | --status | --baseline]",desc:"Bring Document360 down: pull portal edits + import NEW portal articles. --status: drift report only \xB7 --baseline: set a sync base \xB7 <path>: one article / resolve a conflict",group:"publish"},{name:"resolve",usage:"/resolve [<path>]",desc:"Resolve conflicts (edited both here and on the portal): shows the diff, then keep local (push), take portal (pull), or skip \u2014 per article, or one answer for all remaining. Bare: walk them all",group:"publish"},{name:"convert",usage:"/convert [--scope <folder>] [--run]",desc:"Convert tracked articles to DFM (one-off legacy migration)",group:"publish"},{name:"profile",usage:"/profile [name|add <name> [env]]",desc:"Switch/create a Document360 connection (picker; s = session)",group:"setup"},{name:"workspace",usage:"/workspace [name]",desc:"Switch the Document360 workspace (picker)",group:"setup"},{name:"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"}],Eg={"/catch-up":"write up everything your builder flagged","/audit":"check the code for anything new or missing in the docs","/discover":"interview your builder so the docs are grounded in the real product","/pull":"pull edits + new articles from Document360","/push":"save your articles to Document360 as drafts","/publish":"take the signed-off drafts live to your readers","/write":"author the planned articles","/draft":"plan articles from PRDs + the code","/login":"sign in to Document360","/workspace":"choose the Document360 workspace","/project":"choose the Document360 project","/scope":"choose which folders back the docs","/genre":"set this repo's product type (picks the docs playbook)","/init":"set up this repo","/screenshot":"work the screenshot pipeline (author specs, take shots, draw the callouts)","/doctor":"run a health check","/logs":"show the last problem, and copy it for the team","/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 Dg(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(Eg[n])return Eg[n];let o=ko.find(r=>r.name===t);return o?o.desc:""}function Ng(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return ko.filter(n=>n.name.startsWith(t))}function jg(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 NR=new RegExp(`^\\s*/(?:${ko.map(e=>e.name).join("|")})(?:\\s|$)`),Ig=e=>NR.test(e),Lg=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Og=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),_g=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function jR(e){let t=e.replace(/\r/g,"").split(`
|
|
338
|
+
`),n=[],o=0;for(;o<t.length;){let r=t[o];if(/^\s*```/.test(r)){let a=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)a.push(t[o++]);o++,n.push({kind:"code",lines:a});continue}if(Lg(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&Og(t[o+1])){let a=_g(r);o+=2;let l=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)l.push(_g(t[o++]));n.push({kind:"table",header:a,rows:l});continue}let s=r.match(/^(#{1,6})\s+(.*)$/);if(s){n.push({kind:"heading",level:s[1].length,text:s[2]}),o++;continue}if(/^\s*([-*]|\d+\.)\s+/.test(r)){let a=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);){let l=t[o++];a.push({ordered:/^\s*\d+\.\s+/.test(l),text:l.replace(/^\s*([-*]|\d+\.)\s+/,"")})}n.push({kind:"list",items:a});continue}if(r.trim()===""){o++;continue}if(Ig(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])&&!Ig(t[o])&&!Lg(t[o])&&!(t[o].includes("|")&&o+1<t.length&&Og(t[o+1]));)i.push(t[o++]);n.push({kind:"para",text:i.join(" ")})}return n}function Ou(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?_n.bold(t.slice(2,-2)):t.startsWith("`")?Z(t.slice(1,-1)):_n.italic(t.slice(1,-1)))}var IR=(e,t)=>e+" ".repeat(Math.max(0,t-ja(e)));function Es(e,t,n,o={}){return Mg(e,t,n,o)}function Mg(e,t,n,o={}){let r=e.length,s=T=>Math.max(0,...T.split(`
|
|
339
|
+
`).map(D=>ja(D))),i=e.map((T,D)=>Math.max(ja(T),...t.map(N=>s(N[D]??"")))),a=Math.max(24,n),l=3*r+1,d=[...i],w=()=>d.reduce((T,D)=>T+D,0)+l,g=0;for(;w()>a&&g++<1e4;){let T=-1,D=6;for(let N=0;N<r;N++)d[N]>D&&(D=d[N],T=N);if(T===-1)break;d[T]-=1}let $=(T,D,N)=>_n.gray(T+d.map(B=>"\u2500".repeat(B+2)).join(D)+N),P=_n.gray("\u2502"),C=(T,D)=>{let N=d.map((q,de)=>{let ve=T[de]??"",Se=D?_n.bold(ve):o.plain?ve:Ou(ve);return ve.includes(`
|
|
340
340
|
`)?Se.split(`
|
|
341
|
-
`).flatMap(Te=>
|
|
342
|
-
`)):
|
|
343
|
-
`)}),
|
|
341
|
+
`).flatMap(Te=>Ia(Te,q,{hard:!0}).split(`
|
|
342
|
+
`)):Ia(Se,q,{hard:!0}).split(`
|
|
343
|
+
`)}),B=Math.max(...N.map(q=>q.length)),I=[],X=(q,de,ve)=>o.align?.[ve]==="right"?" ".repeat(Math.max(0,de-ja(q)))+q:IR(q,de);for(let q=0;q<B;q++)I.push(d.map((de,ve)=>`${P} ${X(N[ve][q]??"",de,ve)} `).join("")+P);return I.join(`
|
|
344
344
|
`)},R=[$("\u250C","\u252C","\u2510"),C(e,!0)];return R.push(t.length===0?$("\u2514","\u2534","\u2518"):$("\u251C","\u253C","\u2524")),t.forEach((T,D)=>{R.push(C(T,!1)),R.push(D===t.length-1?$("\u2514","\u2534","\u2518"):$("\u251C","\u253C","\u2524"))}),R.join(`
|
|
345
|
-
`)}function
|
|
345
|
+
`)}function LR(e,t){switch(e.kind){case"heading":return _n.bold(e.text);case"hr":return _n.gray("\u2500".repeat(t));case"para":return Ia(Ou(e.text),t);case"list":{let n=0;return e.items.map(o=>{let r=o.ordered?`${++n}.`:"\u2022",s=" ".repeat(2+r.length+1),[i="",...a]=Ia(Ou(o.text),Math.max(10,t-s.length)).split(`
|
|
346
346
|
`);return` ${r} ${i}`+a.map(l=>`
|
|
347
347
|
${s}${l}`).join("")}).join(`
|
|
348
|
-
`)}case"code":return e.lines.map(n=>
|
|
349
|
-
`);case"table":return
|
|
348
|
+
`)}case"code":return e.lines.map(n=>_n.gray(" "+n)).join(`
|
|
349
|
+
`);case"table":return Mg(e.header,e.rows,t)}}function _u(e,t){let n=Math.max(20,t);return jR(e).map(o=>LR(o,n)).join(`
|
|
350
350
|
|
|
351
|
-
`)}se();import
|
|
352
|
-
`);let r=2,s=3,i=
|
|
351
|
+
`)}se();import OR from"picocolors";var _R=[127,86,217],MR=[22,38,43],Fg={T:_R,E:MR},Ds=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],Mu=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,FR=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function Ug(){if(!OR.isColorSupported)return[];let e=Ds[0].length,t=[];for(let n=0;n<Ds.length;n+=2){let o="";for(let r=0;r<e;r++){let s=Fg[Ds[n][r]],i=n+1<Ds.length?Fg[Ds[n+1][r]]:void 0;s&&i?o+=`${Mu(s)}${FR(i)}\u2580\x1B[49m\x1B[39m`:s?o+=`${Mu(s)}\u2580\x1B[39m`:i?o+=`${Mu(i)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function Ns(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 yn(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function Bg(e,t,n){let o=e>0&&e<=n?e:t;return Math.max(0,Math.floor((n-o)/1e3))}function gt(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 kr=(e,t)=>` ${e.padEnd(13)}${t}`;function UR(e,t){let n=[hs("\u270E document360-writer")+ke.gray(` v${e.version} \xB7 engine v${e.engineVersion}${e.captureVersion?` \xB7 capture v${e.captureVersion}`:""}`),ke.gray(" Reads your code, writes your docs."),"",kr("Claude:",`${e.claude}${ke.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),kr("Document360:",e.configured?e.loggedOut?ke.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?ke.gray(` (${e.sessionHint})`):""}`:ke.yellow("not set up \u2014 run /init")),kr("Profile:",e.configured?`${e.profile}${ke.gray(` (${e.apiUrl})`)}${e.prod?ke.bold(ke.yellow(" \u26A0 PRODUCTION")):""}`:ke.gray("\u2014 (run /init)")),kr("Project:",e.project),kr("Mode:",ke.gray(e.mode)),kr("cwd:",ke.gray(e.cwd))],o=Ug();if(o.length===0)return n.join(`
|
|
352
|
+
`);let r=2,s=3,i=Uu(o[0]);if(!(t>=r+i+s+Math.max(...n.map(w=>Uu(w)))))return[...o.map(w=>" "+w),...n].join(`
|
|
353
353
|
`);let l=Math.max(0,Math.floor((n.length-o.length)/2)),d=[];for(let w=0;w<Math.max(o.length+l,n.length);w++){let g=o[w-l]??" ".repeat(i);d.push((" ".repeat(r)+g+" ".repeat(s)+(n[w]??"")).trimEnd())}return d.join(`
|
|
354
|
-
`)}var
|
|
355
|
-
`).flatMap(d=>
|
|
354
|
+
`)}var WR={error:ke.red,warn:ke.yellow,ok:ke.green,info:ke.gray},Wg=9;function Wu(e){return e.length>=Wg?`${e} `:e.padEnd(Wg)}function La(e){return e.replace(/^(\s*• |)([^\x00-\x7F][\u{1F000}-\u{1FAFF}️]*) (?=\S)/gmu,"$1$2 ")}function Bu(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return UR(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",s=Math.max(10,n-4),i=50,a=e.text.split(`
|
|
355
|
+
`).flatMap(d=>Fu(d,s,{hard:!0}).split(`
|
|
356
356
|
`)),l=Math.max(0,a.length-i);return l>0&&(a=[...a.slice(0,i),ke.dim(`\u2026 +${l} more lines`)]),`
|
|
357
|
-
`+a.map((d,w)=>o+(w===0?Z(" \u276F "):" ")+d+" ".repeat(Math.max(0,s-
|
|
357
|
+
`+a.map((d,w)=>o+(w===0?Z(" \u276F "):" ")+d+" ".repeat(Math.max(0,s-Uu(d))+1)+r).join(`
|
|
358
358
|
`)}case"assistant":return`
|
|
359
|
-
`+
|
|
360
|
-
`+
|
|
361
|
-
`+
|
|
359
|
+
`+_u(e.text,n);case"tool":{let o=e.arg!==null?ke.gray(`${e.sep}(${e.arg})`):"";return`
|
|
360
|
+
`+Fu(ke.gray("\u25CF ")+e.title+o,n)}case"doc":{let o=[e.category,e.note].filter(s=>!!s).map(s=>ke.gray(` \xB7 ${s}`)),r=e.loud?ke.gray(" \xB7 ")+ke.bold(ke.yellow(e.loud)):"";return`
|
|
361
|
+
`+Fu(ke.green("\u25CF ")+Z(ke.bold(Wu(e.verb)))+ke.bold(e.title)+o.join("")+r,n)}case"tool-result":{let o=e.isError?ke.red:ke.gray,r=e.lines.map((s,i)=>o((i===0?" \u23BF ":" ")+s));return e.hidden>0&&r.push(ke.dim(` \u2026 +${e.hidden} lines`)),r.join(`
|
|
362
362
|
`)}case"diff":{let o=i=>i===1?"":"s",s=[ke.gray(` \u23BF Added ${e.added} line${o(e.added)}, removed ${e.removed} line${o(e.removed)}`),...e.lines];return e.hidden>0&&s.push(ke.dim(` \u2026 +${e.hidden} more diff lines`)),s.join(`
|
|
363
|
-
`)}case"link":return e.lines.map(o=>Z(
|
|
363
|
+
`)}case"link":return e.lines.map(o=>Z(ms(` \u2B95 ${o}`))).join(`
|
|
364
364
|
`);case"preview":return`
|
|
365
|
-
`+
|
|
365
|
+
`+hs(`\u25A3 Preview \u2014 ${e.name}`)+`
|
|
366
366
|
|
|
367
|
-
`+
|
|
368
|
-
`+
|
|
369
|
-
`+e.text;case"done":{let o=e.inTokens&&e.inTokens>0?` \xB7 ${
|
|
370
|
-
`+(e.ok?ke.magenta("\u2736 "):ke.red("\u2736 "))+ke.gray(`Cooked for ${r} \xB7 ${
|
|
367
|
+
`+_u(e.text,n);case"note":return`
|
|
368
|
+
`+WR[e.tone](ms(La(e.text)));case"block":return`
|
|
369
|
+
`+e.text;case"done":{let o=e.inTokens&&e.inTokens>0?` \xB7 ${Ns(e.inTokens)} in${e.cachedPct!=null?` (${e.cachedPct}% cached)`:""}`:"",r=e.activeSeconds!==void 0&&Da(e.activeSeconds,e.seconds)?`${yn(e.seconds)} elapsed \xB7 ${yn(e.activeSeconds)} working`:yn(e.seconds),s=e.costUsd>0?` \xB7 this turn ${gt(e.costUsd)}`+(e.sessionCostUsd!==void 0&&e.sessionCostUsd>e.costUsd?` \xB7 session ${gt(e.sessionCostUsd)}`:""):"";return`
|
|
370
|
+
`+(e.ok?ke.magenta("\u2736 "):ke.red("\u2736 "))+ke.gray(`Cooked for ${r} \xB7 ${Ns(e.tokens)} tokens out${o}${s}`)}}}function Hg(e,t,n){let o=e.map(i=>Bu(i,t));if(n===void 0||n<=0)return o.join(`
|
|
371
371
|
`);let r=[],s=0;for(let i=o.length-1;i>=0;i--){let a=o[i].split(`
|
|
372
372
|
`).length;if(r.length>0&&s+a>n)break;r.unshift(o[i]),s+=a}return r.join(`
|
|
373
|
-
`)}var
|
|
373
|
+
`)}var Hu=3;function Gu(e){let t,n=!1;for(let r=0;r<e.length;r++){let s=e[r];s==="--run"||s==="--yes"?n=!0:s==="--scope"?t=e[++r]:s?.startsWith("--scope=")&&(t=s.slice(8))}return{scope:t?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0,run:n}}function qu(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Vu(e,t){return t.map(n=>{let o=0;try{o=BR(HR(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function Yu(e){return`Convert each of these articles to canonical Document360 Flavored Markdown (DFM) and re-publish each as a DRAFT. This is a mechanical syntax conversion, not a rewrite, so be efficient:
|
|
374
374
|
- Read ONLY the article files listed below. Do NOT read source code, other articles, or fetch the live portal; you already have everything you need.
|
|
375
375
|
- Convert in place: wrap callouts, FAQs, tabs, accordions, and media embeds per the d360-markdown skill. Preserve all wording, headings, and structure; change only GFM\u2192DFM syntax.
|
|
376
376
|
- Publish each as a draft with a single update call. Do NOT re-read, re-verify, or polish after converting, and skip articles already in DFM.
|
|
377
377
|
- Work only on these files:
|
|
378
378
|
`+e.paths.map(t=>`- ${t}`).join(`
|
|
379
|
-
`)}function
|
|
379
|
+
`)}function Ku(e,t,n){let o=e.reduce((a,l)=>a+l.paths.length,0),[r,s]=t.usd;return[`Convert ${o} article${o===1?"":"s"} to DFM in ${e.length} batch${e.length===1?"":"es"} (\u2264${n} agents at once):`,...e.map(a=>` \u2022 ${a.label} \u2014 ${a.paths.length} article${a.paths.length===1?"":"s"}`),"",`Estimated cost: ${gt(r)}\u2013${gt(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function zu(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),i=e.reduce((C,R)=>C+o(R),0),a=r.reduce((C,R)=>C+o(R),0),l=e.reduce((C,R)=>C+R.costUsd,0),d=e.reduce((C,R)=>C+R.outputTokens,0),w=n==="api"?`${gt(l)} total`:$r(d),g=`${r.length}/${e.length} batch${e.length===1?"":"es"} completed`,$=C=>`${C} article${C===1?"":"s"}`,P=[];if(s.length===0)P.push(`Converted ${$(i)} (${g}) successfully \xB7 ${w}.`);else{P.push(`Converted ${a}/${$(i)} (${g}) \xB7 ${w}.`),P.push(`${s.length} batch${s.length===1?"":"es"} failed \u2014 re-run /convert to retry:`);for(let C of s)P.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return P}async function Gg(e,t){if(!VR(t.cwd))return console.log(_("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=Gu(e),r=zR(t.cwd,t.profileName);if(r.length===0)return console.log(_("No tracked articles in d360-category-map.json. Save some to Document360 first (/push), then /convert.")),{kind:"continue"};let s=qu(r,n);if(s.length===0)return console.log(_(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let i=qR(s),a=`/convert${n?` --scope ${n}`:""} --run`,{model:l,forced:d}=YR(t.cwd,"light");if(!o){let g=GR({files:Vu(t.cwd,s),op:"convert",model:l});n&&console.log(m(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let $ of Ku(i,g,Hu))console.log($);return console.log(m(`Model: ${l}${d?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(m(`Run ${a} to start.`)),console.log(""),{kind:"continue"}}console.log(m(`Converting ${s.length} articles in ${i.length} batches (\u2264${Hu} agents at once) on ${l}\u2026`)),console.log(m(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let w=Date.now();try{for await(let g of KR({cwd:t.cwd,partitions:i,promptFor:Yu,concurrency:Hu,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:l}))if(g.type==="partition_status")g.status==="running"?console.log(m(` \u25B8 ${g.label} \u2014 converting\u2026`)):g.status==="done"?console.log(Y(` \u2713 ${g.label}`)):console.log(_(` \u2717 ${g.label}`));else if(g.type==="run_done"){console.log("");let $=process.env.ANTHROPIC_API_KEY?"api":"subscription",P=On(g,"The conversion");for(let C of P??zu(g.results,i,$))console.log(P||!g.ok?V(C):Y(C));console.log(m(tn(Dt(w,g.results,g.totalCostUsd))))}}catch(g){console.log(_(`Convert run failed: ${g.message}`))}return console.log(""),{kind:"continue"}}import{statSync as kS}from"node:fs";import{resolve as $S}from"node:path";import{CLAUDE_ACCOUNT_MISMATCH_HINT as vS,estimateBulkCost as xS,lintDocs as RS,planFindingPartitions as SS,planPartitions as CS,readDocsPlan as PS,readProjectConfig as ad,DEFAULT_DOCS_DIR as rw,resolveModelForOperation as ew,runPartitioned as tw,partitionCoverage as nw,stampArticles as ow,readReviewerNotes as TS,renderNotesForPrompt as AS,notesForPath as ES,CONTENT_CAP_VERSION as DS}from"document360-engine";se();import{lintDocs as ed,guidanceForRules as JR,planFindingPartitions as ZR,runPartitioned as eS,partitionCoverage as tS,resolveModelForOperation as nS,stampArticles as oS,applyDeterministicFixes as rS,isMechanical as sS}from"document360-engine";import{CONTENT_CAP_VERSION as qg}from"document360-engine";function Vg(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 Yg(e){return e.trim().split(/\s+/).slice(1).find(t=>!t.startsWith("--"))}function ut(e){return e==="review"?{reviewedCap:qg}:{checkedCap:qg}}import{gateFixTarget as XR}from"document360-engine";var Qu=e=>"ruleId"in e,Oa=e=>Qu(e)?e.severity:"warning",Mn=e=>e===1?"":"s";function Ju(e,t){let n=t??XR(e),o=n?` ${n}`:"";return e.unreviewed.length>0?`/review${o} --blocked --fix`:`/lint${o} --blocked --fix`}var Xu=new Map;var QR=e=>Qu(e)?e.fp||`${e.ruleId}:${e.path}:${e.line}:${e.term}`:`${e.kind}:${e.path}:${e.line}`;function js(e){let{cwd:t,after:n,scope:o,aborted:r,blocked:s}=e,i=n.filter(P=>Oa(P)==="error").length,a=n.filter(P=>Oa(P)==="warning").length,l=n.filter(P=>Oa(P)==="suggestion").length,d=Re("/lint","--blocked --fix",o);if(r){let P=Re("/lint",s?"--blocked --fix":"--fix",o);return{text:`Stopped. Nothing else changed \u2014 ${P} picks up where this left off.`,cmd:P}}if(i>0){let P=n.filter(N=>Oa(N)==="error"),C=new Set(P.map(N=>N.path)).size,R=`${t}::${o??""}`,T=P.map(QR).sort().join("|"),D=Xu.get(R)===T;if(Xu.set(R,T),D){let N=Re("/lint","--blocked --full",o),B=[...new Set(P.filter(Qu).map(I=>I.ruleId))];return{text:`The same ${i} error${Mn(i)} in ${C} article${Mn(C)} survived two ${d} passes, so a third would change nothing \u2014 ${i===1?"it needs":"they need"} a person. ${N} shows ${i===1?"it":"them"} in place. If ${B.length===1?`${B[0]} is`:"a rule is"} wrong for your product, switch it off in .d360-writer/config.json under "styleGuide": { "rules": { "<rule>": "off" } }.`,cmd:N}}return{text:`${i} error${Mn(i)} in ${C} article${Mn(C)} still block${i===1?"s":""} publishing. ${d} has another go at ${i===1?"it":"just those"} \u2014 if a second pass leaves the same ones, they need a human eye.`,cmd:d}}Xu.delete(`${t}::${o??""}`);let w=a>0&&l>0?`${a} warning${Mn(a)} and ${l} suggestion${Mn(l)} remain (neither blocks publishing). `:a>0?`${a} warning${Mn(a)} remain${a===1?"s":""}, which ${a===1?"does":"do"} not block publishing. `:l>0?`${l} suggestion${Mn(l)} remain${l===1?"s":""} \u2014 ${l===1?"it is":"they are"} judgment calls and ${l===1?"does":"do"} not block publishing. `:"",g=w===""?"\u2713 Nothing left to fix. ":`\u2713 ${w}`,$=o?"/push":"/push --all";return Yt(t,{text:`${g}Nothing is blocking${o?` in ${o}`:""} \u2014 ${$} saves the articles to Document360 as drafts.`,cmd:$},g,o)}var Ma={error:0,warning:1,suggestion:2},iS={error:"\u2717",warning:"\u26A0",suggestion:"\xB7"},aS=10,lS=8,cS=96,Kg=34,nn=e=>"ruleId"in e,Fn=e=>nn(e)?e.severity:"warning",td=e=>nn(e)?e.ruleId:e.kind,$o=e=>e.fileLine??e.line;function bn(e){return e.includes("--blocked")}function kn(e,t){return bn(t)?e.filter(n=>Fn(n)==="error"):e}function Is(e,t){return`/lint${t?` ${t}`:""}${bn(e)?" --blocked":""} --fix`}function Zu(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function _a(e){let t={error:0,warning:0,suggestion:0};for(let n of e)t[Fn(n)]++;return t}function zg(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 Ls(e,t={}){let n=t.baselined?[]:e.filter(g=>nn(g)&&g.baselined),o=t.baselined?e:e.filter(g=>!(nn(g)&&g.baselined)),r=n.length>0?[me("\u2139",`${n.length} issue${n.length===1?"":"s"} ${n.length===1?"was":"were"} already in your articles when you chose this style guide, so ${n.length===1?"it never blocks":"they never block"} publishing. /lint --baselined shows ${n.length===1?"it":"them"}.`)]:[];if(o.length===0)return[me("\u2713","No issues found \u2014 no leaked internals, unknown commands, stale version facts, AI-tells, em dashes, or broken callouts in the docs."),...r];let s=new Map;for(let g of o){let $=s.get(g.path)??[];$.push(g),s.set(g.path,$)}let i=_a(o),a=[me("\u26A0",`${o.length} issue${o.length===1?"":"s"} in ${s.size} article${s.size===1?"":"s"} \u2014 ${zg(i)}.`),""],l=[...s.entries()].sort((g,$)=>{let P=_a(g[1]);return _a($[1]).error-P.error||$[1].length-g[1].length||g[0].localeCompare($[0])}),d=t.full?l:l.slice(0,aS);for(let[g,$]of d){a.push(` ${g} ${m(zg(_a($)))}`);let P=new Map;for(let D of $){let N=td(D),B=P.get(N)??[];B.push(D),P.set(N,B)}let C=[...P.entries()].sort((D,N)=>Ma[Fn(D[1][0])]-Ma[Fn(N[1][0])]||N[1].length-D[1].length||D[0].localeCompare(N[0])),R=t.full?C:C.slice(0,lS);for(let[D,N]of R){let B=[...N].sort((ie,te)=>$o(ie)-$o(te)),I=iS[Fn(B[0])],q=new Set(B.map(ie=>ie.term)).size===1?` ${Zu(`"${B[0].term}"`,Kg)}`:"",de=B.length>1?m(` \xD7${B.length}`):"",ve=t.full?B[0].message:Zu(B[0].message,cS);a.push(` ${I} ${D}${de}${q}`),a.push(` ${m(ve)}`);let Se=B.map(ie=>q?`L${$o(ie)}`:`L${$o(ie)} ${Zu(`"${ie.term}"`,Kg)}`),Te=t.full?Se:Se.slice(0,12),he=Se.length-Te.length;a.push(` ${m(Te.join(", ")+(he>0?` \u2026+${he}`:""))}`)}let T=C.length-R.length;T>0&&a.push(m(` \u2026${T} more rule${T===1?"":"s"} fired here (/lint ${g} --full)`)),a.push("")}let w=l.length-d.length;return w>0&&(a.push(m(` \u2026and ${w} more article${w===1?"":"s"} (/lint <category> narrows \xB7 /lint --full lists every one)`)),a.push("")),a.push(...r),a}var uS=200;function Fa(e){let n=[...e.filter(l=>!(nn(l)&&l.baselined))].sort((l,d)=>Ma[Fn(l)]-Ma[Fn(d)]||l.path.localeCompare(d.path)||$o(l)-$o(d)),o=n.slice(0,uS),r=n.length-o.length,s=new Map;for(let l of o){let d=s.get(l.path)??[];d.push(l),s.set(l.path,d)}let i=[...s.entries()].map(([l,d])=>[l,...d.map(w=>` - L${$o(w)} [${td(w)}] (${Fn(w)}): "${w.term}": ${w.message}`)].join(`
|
|
380
380
|
`)).join(`
|
|
381
|
-
`),a=
|
|
382
|
-
`)}var
|
|
381
|
+
`),a=JR(o.map(l=>({id:td(l),message:l.message,link:nn(l)?l.link:void 0})));return["The documentation linter found issues in already-written articles. FIX each one by EDITING the","article in place. Do not rewrite whole articles; just resolve the flagged problems. Ground every change","in the actual product source (the authoritativeSourceFiles); never invent.","","Errors are listed first: those are defects of fact or structure, and they matter most.","",...a.length>0?["How to fix, by rule:",...a,""]:[],"Rules: edit ONLY the listed articles; do not touch others; do not publish; introduce no new internal","nouns, invented commands, or wrong facts. When done, every listed issue should be gone.","",...r>0?[`Note: ${r} further finding${r===1?"":"s"} were left out of this batch to keep it actionable. Run /lint --fix again afterwards to pick them up.`,""]:[],"Issues:",i].join(`
|
|
382
|
+
`)}var vr=3;function xr(e,t,n){let o=n.filter(a=>!(nn(a)&&a.baselined)),r=kn(o,t).filter(a=>nn(a)&&sS(a));if(r.length===0)return{fixed:0,skipped:0,lines:[],paths:[]};let s=rS(e,r),i=[];if(s.fixed.length>0){let a=new Set(s.fixed.map(l=>l.path)).size;i.push(Y(me("\u2713",`Fixed ${s.fixed.length} ${s.fixed.length===1?"issue":"issues"} in ${a} ${a===1?"article":"articles"} \u2014 a straight swap, so no model and no cost.`)))}return s.skipped.length>0&&i.push(m(` ${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 nd(e,t,n){let o=kn(n.filter(a=>!(nn(a)&&a.baselined)),t);if(o.length===0)return null;let r=t.find(a=>!a.startsWith("--")),s=Is(t,r),i=ZR(o);return i.length<=1?{kind:"single",prompt:Fa(o),display:s,findings:o.length}:{kind:"partitioned",partitions:i,display:s,articles:new Set(o.map(a=>a.path)).size,findings:o.length,promptFor:a=>{let l=new Set(a.paths);return Fa(o.filter(d=>l.has(d.path)))}}}function od(e,t,n){let o=t.find(l=>!l.startsWith("--")),r=o?` in ${o}`:"",s=n.filter(l=>!(nn(l)&&l.baselined)),i=new Set(s.map(l=>l.path)).size;return{lines:bn(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:Tt(e,Is(t,o))}}async function dS(e,t,n,o=[]){let{model:r}=nS(e.cwd,"standard");console.log(m(`Fixing ${t.findings} issue${t.findings===1?"":"s"} across ${t.articles} article${t.articles===1?"":"s"} in ${t.partitions.length} batches (\u2264${vr} 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 eS({cwd:e.cwd,partitions:t.partitions,promptFor:t.promptFor,concurrency:vr,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:r}))if(g.type==="partition_status")g.status==="running"?console.log(m(` \u25B8 ${g.label} \u2014 fixing\u2026`)):g.status==="done"?console.log(Y(` \u2713 ${g.label}`)):console.log(_(` \u2717 ${g.label}`));else if(g.type==="run_done"){let $=tS(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(m(tn(Dt(i,g.results,g.totalCostUsd)))),$.failed.length&&console.log(V(`\u26A0 ${$.failed.length} batch${$.failed.length===1?"":"es"} not fixed: ${$.failed.map(P=>P.label).join(", ")}`)),$.notRun.length&&console.log(V(`\u26A0 ${$.notRun.length} batch${$.notRun.length===1?"":"es"} never started \u2014 their articles are untouched.`)),g.blocked&&console.log(V(`\u26A0 ${g.blocked}`)),g.allEmpty&&console.log(V("\u26A0 No turn produced any work this run \u2014 nothing was changed.")),!g.allEmpty&&!g.blocked&&s.push(...$.covered)}}catch(g){return console.log(_(`Fix run failed: ${g.message}`)),{kind:"continue"}}if(s.length>0)try{oS(e.cwd,s,ut("lint"))}catch{}let l=ed({cwd:e.cwd,scope:n}).filter(g=>!g.baselined),d=kn(l,o);console.log("");for(let g of Ls(d))console.log(d.length===0?Y(g):V(g));if(qt(a))for(let g of Tt(e.cwd,Is(o,n)))console.log(Y(g));let w=js({cwd:e.cwd,after:d,before:t.findings,scope:n,blocked:bn(o)});return console.log(""),console.log(m(w.text)),{kind:"continue",ownNext:!0}}async function rd(e,t){let n=e.includes("--fix"),o=e.find(a=>!a.startsWith("--")),r=o?` ${o}`:"",s=ed({cwd:t.cwd,scope:o});if(n){let a=xr(t.cwd,e,s);for(let w of a.lines)console.log(w);let l=a.fixed>0?ed({cwd:t.cwd,scope:o}):s,d=nd(t.cwd,e,l);if(!d){let w=od(t.cwd,e,l);console.log(Y(w.lines[0]));for(let g of w.lines.slice(1))console.log(m(g));for(let g of w.closed)console.log(Y(g));return{kind:"continue",ownNext:!0}}return d.kind==="partitioned"?dS(t,d,o,e):(console.log(m(`Fixing ${d.findings} doc issue${d.findings===1?"":"s"} (run /lint again after to confirm)\u2026`)),{kind:"forward-to-agent",prompt:d.prompt,display:d.display})}let i=kn(s,e);console.log(m("Linting the docs (engine internals, unknown commands, stale facts, AI-tells, em dashes, callout shape)\u2026"));for(let a of Ls(i,{full:e.includes("--full"),baselined:e.includes("--baselined")}))console.log(i.length===0?Y(a):V(a));return i.length>0&&console.log(m(`Run /lint${r}${bn(e)?" --blocked":""} --fix to have the agent correct these.`)),console.log(""),{kind:"continue",ownNext:i.length>0}}var Xg=async(e,t)=>{let n=wn("check");return n&&console.log(m(`\u2192 ${n}`)),rd(e,t)};se();import{readProjectConfig as pS,loadProfileMap as hS,resolveActiveProfile as fS,desiredCategoryOrder as mS,desiredArticleOrder as gS,DEFAULT_DOCS_DIR as wS}from"document360-engine";var sd=e=>e.replace(/\\/g,"/"),Qg=e=>sd(e).split("/").pop()??e;function id(e){let t=Qg(e),n=t.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return n?n.charAt(0).toUpperCase()+n.slice(1):t}var yS=id;function Os(e,t){try{let n=pS(e);if(!n)return[];let o=fS(e,t),r=hS(e,o.name);if(!r)return[];let s=sd(n.docsDir??wS).replace(/\/+$/,""),i=new Map;for(let l of gS(r))i.set(l.categoryPath,(i.get(l.categoryPath)??0)+1);let a=[];for(let l of mS(r)){let d=sd(l.path),w=d.startsWith(`${s}/`)?d.slice(s.length+1):d===s?"":d;w&&a.push({token:w,label:yS(Qg(d)),count:i.get(l.path)??0})}return a}catch{return[]}}function Jg(e,t){let n=Os(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 Un(e,t){if(t.includes("--all")||t.includes("--blocked")||t.includes("--stale")||t.some(n=>n.startsWith("--scope="))||t.includes("--scope")&&!_s(t))return!1;for(let n=0;n<t.length;n++){let o=t[n];if(o.startsWith("--")){bS.has(o)&&n++;continue}return!1}return e==="write"?!t.includes("--preview")&&!t.includes("--dry-run"):e==="review"||e==="reorder"}var bS=new Set(["--scope","--concurrency"]);function Rr(e,t,n,o,r){if(r=r??Os(e,o),r.length<=1)return[];let s=n.filter(d=>d.startsWith("--")).join(" "),i=s?` ${s}`:"",a=`/${t}${i} --all`.replace(/\s+/g," "),l=d=>t==="write"?`/write --scope ${d}${i}`:`/${t} ${d}${i}`;return[`Bare /${t} covers the WHOLE knowledge base (${r.reduce((d,w)=>d+w.count,0)} articles). Pick a target:`,` ${a} (everything)`,...r.map(d=>` ${l(d.token)} (${d.label} \xB7 ${d.count} article${d.count===1?"":"s"})`)]}function _s(e){let t=e.indexOf("--scope");if(t===-1)return!1;let n=e[t+1];return n===void 0||n.startsWith("-")}function Zg(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 NS=3,jS=8;function ld(e){return e===void 0||!Number.isFinite(e)?NS:Math.max(1,Math.min(Math.floor(e),jS))}function Ms(e){let t,n,o=!1,r=!1,s,i=l=>{let d=Number(l);return l!==void 0&&Number.isFinite(d)?d:void 0};for(let l=0;l<e.length;l++){let d=e[l];if(d==="--preview"||d==="--dry-run")o=!0;else if(d==="--rewrite"||d==="--force")r=!0;else{if(d==="--run"||d==="--yes"||d==="--all")continue;d==="--scope"?t=e[++l]:d?.startsWith("--scope=")?t=d.slice(8):d==="--concurrency"?s=i(e[++l]):d?.startsWith("--concurrency=")?s=i(d.slice(14)):d&&!d.startsWith("--")&&(n=d)}}let a=l=>l?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:a(t),path:a(n),preview:o,concurrency:s,rewrite:r}}function IS(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function LS(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function cd(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+=kS($S(e,i)).size}catch{}return{path:r,bytes:s}})}function ud(e,t,n={}){let o=n.rewrite?"- Some or all of these articles ALREADY EXIST on disk \u2014 this is a re-author (rewrite/upgrade), NOT a first draft. For any that exist, do NOT preserve or lightly-edit the current file: RE-AUTHOR it from scratch against the plan + sources + the active doc-type playbook standard. The existing file is what you're replacing, and its structure is NOT the target; match only the project's voice/terminology.\n- PRESERVE REVIEWER ANCHORS. If the existing file contains `:comment[some text]{id=\"\u2026\"}` markers, each one is where a reviewer left a comment. Carry every marker into your new text, wrapping whatever passage now makes the point the old one made, and keep its `id` exactly. Dropping a marker silently detaches that reviewer's comment from the article \u2014 they keep the note and lose the place.\n":"",r=n.reviewerNotes?.trim()?`
|
|
383
383
|
WHAT REVIEWERS HAVE ASKED FOR ON THESE ARTICLES \u2014 apply each one as you write. These are real comments from the people who own these docs, so an article that ignores them will simply come back:
|
|
384
384
|
`+n.reviewerNotes.trim()+`
|
|
385
385
|
`:"";return`Run the write-article skill to author EACH documentation article listed below. For each path:
|
|
@@ -391,174 +391,174 @@ WHAT REVIEWERS HAVE ASKED FOR ON THESE ARTICLES \u2014 apply each one as you wri
|
|
|
391
391
|
- Each article is independent. Do NOT write, edit, or publish any article not in this list, and do NOT publish to Document360; these are local drafts.
|
|
392
392
|
Articles:
|
|
393
393
|
`+e.paths.map(s=>`- ${s}`).join(`
|
|
394
|
-
`)+r}function ld(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: ${Et(r)}\u2013${Et(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function cd(e,t,n,o){let r=R=>t[R.index]?.paths.length??0,s=e.filter(R=>R.ok),i=e.filter(R=>!R.ok),a=e.reduce((R,T)=>R+r(T),0),l=s.reduce((R,T)=>R+r(T),0),d=e.reduce((R,T)=>R+T.costUsd,0),w=e.reduce((R,T)=>R+T.outputTokens,0),g=n==="api"?`${Et(d)} total`:kr(w),$=`${s.length}/${e.length} batch${e.length===1?"":"es"} completed`,P=R=>`${R} article${R===1?"":"s"}`,C=[];if(i.length===0){C.push(`Wrote ${P(a)} (${$}) successfully \xB7 ${g}.`);let R=o?` ${o}`:"",T=o?"/push":"/push --all",D=o?`/screenshot author ${o}`:"/screenshot author --all";C.push("Next \u2014 an editorial review, because these were written by an AI:"),C.push(`/review${R} --fix`),C.push(`It reads every article and applies its fixes; ${T} then pushes them up (add screenshots first with ${D} if you want them).`)}else{C.push(`Wrote ${l}/${P(a)} (${$}) \xB7 ${g}.`),C.push(`${i.length} batch${i.length===1?"":"es"} failed \u2014 re-run /write${o?` --scope ${o}`:""} to retry the rest:`);for(let R of i)C.push(` \u2717 ${R.label}${R.error?` \u2014 ${R.error}`:""}`);i.some(R=>/rate-limited/i.test(R.error??""))&&(C.push("Claude rate-limited this run, not your usage allowance. Retry one batch at a time:"),C.push(`/write${o?` --scope ${o}`:""} --concurrency 1`)),i.some(R=>/usage limit has been reached/i.test(R.error??""))&&C.push(bS)}return C}function Rr(e,t,n){try{return $S({cwd:e,paths:n.map(o=>`${t}/${o}`)}).filter(o=>!o.baselined)}catch{return[]}}function ud(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 dd(e){let t=e.filter(o=>o.severity==="error");if(t.length===0)return null;let n=vS(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 _a(t.filter(s=>r.has(s.path)))}}}function pd(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 Ma(e,t,n){let o=(rd(e)?.docsDir??tw).replace(/\/+$/,""),r=t.map(a=>a.path);if(n.path){let a=DS(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=NS(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=In(e,o,s);if(i.length===0){let a=n.scope?` under "${n.scope}"`:"",l=n.scope?` --scope ${n.scope}`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${a} are already written. Use /write <path> to rewrite one, or /write${l} --rewrite to regenerate them all.`}}return{docsDir:o,targets:i,planCount:r.length}}function hd(e,t,n){let{targets:o}=Ma(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:od(s),count:i}))}async function nw(e,t){if(!rd(t.cwd))return console.log(_("No d360-writer config here. Run /init first.")),{kind:"continue"};if(Ls(e)){for(let I of zg(t.cwd,t.profileName))console.log(m(I));return{kind:"continue"}}let n=RS(t.cwd,(rd(t.cwd)?.docsDir??tw).replace(/\/+$/,""));if(n.length===0)return console.log(_("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};if(Un("write",e)){let I=hd(t.cwd,n,{rewrite:Os(e).rewrite}),X=xr(t.cwd,"write",e,t.profileName,I);if(X.length>0){for(let H of X)console.log(m(H));return{kind:"continue"}}}let{scope:o,path:r,preview:s,concurrency:i,rewrite:a}=Os(e),{docsDir:l,targets:d,reason:w,rewriting:g}=Ma(t.cwd,n,{scope:o,path:r,rewrite:a});if(d.length===0)return console.log(w?G(w):G("Nothing to write.")),{kind:"continue"};g&&console.log(G(`--rewrite: regenerating ${d.length} already-written article${d.length===1?"":"s"} (overwrites them; git has your baseline).`));let $=xS(d),P=sd(i),{model:C,forced:R}=Qg(t.cwd,"standard"),T=!!r;if(s&&!T){let I=kS({files:id(t.cwd,n,d),op:"write",model:C});o&&console.log(m(`Scope: ${o} (${d.length} pending).`));for(let X of ld($,I,P))console.log(X);return console.log(m(`Model: ${C}${R?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(m(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}let D=SS(t.cwd),N=d.filter(I=>PS(D,I).length>0).length;N>0&&console.log(m(` ${N} of these ${N===1?"has":"have"} reviewer comments \u2014 the writer gets them.`)),console.log(m(`Writing ${d.length} article${d.length===1?"":"s"} in ${$.length} batch${$.length===1?"":"es"} (\u2264${P} agents at once) on ${C}\u2026`)),console.log(m(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let W=Date.now();try{for await(let I of Jg({cwd:t.cwd,partitions:$,promptFor:X=>ad(X,l,{rewrite:g||T,reviewerNotes:CS(D,X.paths)}),concurrency:P,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:C}))if(I.type==="partition_status")I.status==="running"?console.log(m(` \u25B8 ${I.label} \u2014 writing\u2026`)):I.status==="done"?console.log(Y(` \u2713 ${I.label}`)):console.log(_(` \u2717 ${I.label}`));else if(I.type==="run_done"){console.log("");let X=process.env.ANTHROPIC_API_KEY?"api":"subscription",H=Ln(I,"The write");if(H){for(let Te of H)console.log(G(Te));continue}for(let Te of cd(I.results,$,X,o??r))console.log(I.ok?Y(Te):G(Te));if(console.log(m(en(At(W,I.results,I.totalCostUsd)))),I.ok)try{ew(t.cwd,d.map(Te=>`${l}/${Te}`),{writtenCap:TS,reviewedCap:0,checkedCap:0})}catch{}let de=Rr(t.cwd,l,d),ve=ud(de);ve&&console.log(G(ve));let Se=e.includes("--skip-style")?null:dd(de);if(Se){console.log(m(`Fixing ${Se.errors.length} style error(s) in ${Se.articles} article(s) \u2014 one pass\u2026`));let{model:Te}=Qg(t.cwd,"standard"),he=[];try{for await(let ie of Jg({cwd:t.cwd,partitions:Se.partitions,promptFor:Se.promptFor,concurrency:3,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:Te}))if(ie.type==="partition_status"&&ie.status!=="running")console.log(ie.status==="done"?Y(` \u2713 ${ie.label}`):_(` \u2717 ${ie.label}`));else if(ie.type==="run_done"&&!ie.allEmpty&&!ie.blocked){let te=Zg(Se.partitions,ie.results);te.notRun.length&&console.log(G(`\u26A0 ${te.notRun.length} style-fix batch${te.notRun.length===1?"":"es"} never started \u2014 their articles are untouched.`)),he.push(...te.covered)}}catch(ie){console.log(G(`Style fix pass failed: ${ie.message}`))}if(he.length>0)try{ew(t.cwd,he,ut("lint"))}catch{}for(let ie of pd(Se.errors.length,Rr(t.cwd,l,d)))console.log(ie.startsWith("\u2713")?Y(ie):G(ie))}{let Te=Zg($,I.results),he={aborted:!!I.aborted,partitions:$.length,failed:Te.failed.length,notRun:Te.notRun.length,leftBehind:Rr(t.cwd,l,d).filter(ie=>ie.severity==="error").length,...I.blocked?{blocked:I.blocked}:{},...I.allEmpty?{allEmpty:!0}:{},...I.bailedEmpty?{bailedEmpty:!0}:{}};if(Gt(he)){let ie=`/write${o?` --scope ${o}`:""}${e.includes("--rewrite")?" --rewrite":""}`;for(let te of Ct(t.cwd,ie))console.log(Y(te))}}}}catch(I){console.log(_(`Write run failed: ${I.message}`))}return console.log(""),{kind:"continue"}}se();import{existsSync as jS,readdirSync as ow,statSync as rw}from"node:fs";import{join as sw}from"node:path";import{inputDir as IS,readProjectConfig as LS}from"document360-engine";var iw=/\.(md|markdown|pdf|txt)$/i;function fd(e){let t=IS(e);if(!jS(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of ow(t)){let s=sw(t,r),i=!1;try{i=rw(s).isDirectory()}catch{continue}if(i){if(r.startsWith("."))continue;let a=OS(s);a>0&&n.push({name:r,docCount:a})}else iw.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function OS(e){let t=0;for(let n of ow(e))try{rw(sw(e,n)).isFile()&&iw.test(n)&&t++}catch{}return t}function md(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 Fa(e,t){return["Run the draft-from-prd skill.","",`Target scope: ${e?`the feature documents in .d360-writer/input/${e}/`:t?`the input docs in .d360-writer/input/ relevant to: "${t}"`:"the input docs in .d360-writer/input/"}.`,t&&!e?`Use "${t}" as the feature framing.`:"","","Follow the skill: (1) read those PRDs/specs as the primary source (intent, user-facing surface,","terminology, user stories, prerequisites); (2) locate and read the CODE that implements that surface","to pin exact UI strings/routes/states, and never fabricate; flag anything the PRD claims that you","cannot find in source; (3) propose a tight feature-scoped article set (\u22483\u20135) and pin it to",".d360-writer/plan.json + AGENT-PLAN.md, with each article's `sources` listing BOTH the PRD file(s)","AND the grounding code files; (4) flag overlaps with existing articles (do not merge). Then stop and","offer /write. Do NOT write the articles in this turn."].filter(Boolean).join(`
|
|
395
|
-
`)}var
|
|
396
|
-
`)}var
|
|
394
|
+
`)+r}function dd(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: ${gt(r)}\u2013${gt(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function pd(e,t,n,o){let r=R=>t[R.index]?.paths.length??0,s=e.filter(R=>R.ok),i=e.filter(R=>!R.ok),a=e.reduce((R,T)=>R+r(T),0),l=s.reduce((R,T)=>R+r(T),0),d=e.reduce((R,T)=>R+T.costUsd,0),w=e.reduce((R,T)=>R+T.outputTokens,0),g=n==="api"?`${gt(d)} total`:$r(w),$=`${s.length}/${e.length} batch${e.length===1?"":"es"} completed`,P=R=>`${R} article${R===1?"":"s"}`,C=[];if(i.length===0){C.push(`Wrote ${P(a)} (${$}) successfully \xB7 ${g}.`);let R=o?` ${o}`:"",T=o?"/push":"/push --all",D=o?`/screenshot author ${o}`:"/screenshot author --all";C.push("Next \u2014 an editorial review, because these were written by an AI:"),C.push(`/review${R} --fix`),C.push(`It reads every article and applies its fixes; ${T} then pushes them up (add screenshots first with ${D} if you want them).`)}else{C.push(`Wrote ${l}/${P(a)} (${$}) \xB7 ${g}.`),C.push(`${i.length} batch${i.length===1?"":"es"} failed \u2014 re-run /write${o?` --scope ${o}`:""} to retry the rest:`);for(let R of i)C.push(` \u2717 ${R.label}${R.error?` \u2014 ${R.error}`:""}`);i.some(R=>/rate-limited/i.test(R.error??""))&&(C.push("Claude rate-limited this run, not your usage allowance. Retry one batch at a time:"),C.push(`/write${o?` --scope ${o}`:""} --concurrency 1`)),i.some(R=>/usage limit has been reached/i.test(R.error??""))&&C.push(vS)}return C}function Sr(e,t,n){try{return RS({cwd:e,paths:n.map(o=>`${t}/${o}`)}).filter(o=>!o.baselined)}catch{return[]}}function hd(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 fd(e){let t=e.filter(o=>o.severity==="error");if(t.length===0)return null;let n=SS(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 Fa(t.filter(s=>r.has(s.path)))}}}function md(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 Ua(e,t,n){let o=(ad(e)?.docsDir??rw).replace(/\/+$/,""),r=t.map(a=>a.path);if(n.path){let a=IS(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=LS(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=Ln(e,o,s);if(i.length===0){let a=n.scope?` under "${n.scope}"`:"",l=n.scope?` --scope ${n.scope}`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${a} are already written. Use /write <path> to rewrite one, or /write${l} --rewrite to regenerate them all.`}}return{docsDir:o,targets:i,planCount:r.length}}function gd(e,t,n){let{targets:o}=Ua(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:id(s),count:i}))}async function sw(e,t){if(!ad(t.cwd))return console.log(_("No d360-writer config here. Run /init first.")),{kind:"continue"};if(_s(e)){for(let I of Jg(t.cwd,t.profileName))console.log(m(I));return{kind:"continue"}}let n=PS(t.cwd,(ad(t.cwd)?.docsDir??rw).replace(/\/+$/,""));if(n.length===0)return console.log(_("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};if(Un("write",e)){let I=gd(t.cwd,n,{rewrite:Ms(e).rewrite}),X=Rr(t.cwd,"write",e,t.profileName,I);if(X.length>0){for(let q of X)console.log(m(q));return{kind:"continue"}}}let{scope:o,path:r,preview:s,concurrency:i,rewrite:a}=Ms(e),{docsDir:l,targets:d,reason:w,rewriting:g}=Ua(t.cwd,n,{scope:o,path:r,rewrite:a});if(d.length===0)return console.log(w?V(w):V("Nothing to write.")),{kind:"continue"};g&&console.log(V(`--rewrite: regenerating ${d.length} already-written article${d.length===1?"":"s"} (overwrites them; git has your baseline).`));let $=CS(d),P=ld(i),{model:C,forced:R}=ew(t.cwd,"standard"),T=!!r;if(s&&!T){let I=xS({files:cd(t.cwd,n,d),op:"write",model:C});o&&console.log(m(`Scope: ${o} (${d.length} pending).`));for(let X of dd($,I,P))console.log(X);return console.log(m(`Model: ${C}${R?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(m(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}let D=TS(t.cwd),N=d.filter(I=>ES(D,I).length>0).length;N>0&&console.log(m(` ${N} of these ${N===1?"has":"have"} reviewer comments \u2014 the writer gets them.`)),console.log(m(`Writing ${d.length} article${d.length===1?"":"s"} in ${$.length} batch${$.length===1?"":"es"} (\u2264${P} agents at once) on ${C}\u2026`)),console.log(m(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let B=Date.now();try{for await(let I of tw({cwd:t.cwd,partitions:$,promptFor:X=>ud(X,l,{rewrite:g||T,reviewerNotes:AS(D,X.paths)}),concurrency:P,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:C}))if(I.type==="partition_status")I.status==="running"?console.log(m(` \u25B8 ${I.label} \u2014 writing\u2026`)):I.status==="done"?console.log(Y(` \u2713 ${I.label}`)):console.log(_(` \u2717 ${I.label}`));else if(I.type==="run_done"){console.log("");let X=process.env.ANTHROPIC_API_KEY?"api":"subscription",q=On(I,"The write");if(q){for(let Te of q)console.log(V(Te));continue}for(let Te of pd(I.results,$,X,o??r))console.log(I.ok?Y(Te):V(Te));if(console.log(m(tn(Dt(B,I.results,I.totalCostUsd)))),I.ok)try{ow(t.cwd,d.map(Te=>`${l}/${Te}`),{writtenCap:DS,reviewedCap:0,checkedCap:0})}catch{}let de=Sr(t.cwd,l,d),ve=hd(de);ve&&console.log(V(ve));let Se=e.includes("--skip-style")?null:fd(de);if(Se){console.log(m(`Fixing ${Se.errors.length} style error(s) in ${Se.articles} article(s) \u2014 one pass\u2026`));let{model:Te}=ew(t.cwd,"standard"),he=[];try{for await(let ie of tw({cwd:t.cwd,partitions:Se.partitions,promptFor:Se.promptFor,concurrency:3,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:Te}))if(ie.type==="partition_status"&&ie.status!=="running")console.log(ie.status==="done"?Y(` \u2713 ${ie.label}`):_(` \u2717 ${ie.label}`));else if(ie.type==="run_done"&&!ie.allEmpty&&!ie.blocked){let te=nw(Se.partitions,ie.results);te.notRun.length&&console.log(V(`\u26A0 ${te.notRun.length} style-fix batch${te.notRun.length===1?"":"es"} never started \u2014 their articles are untouched.`)),he.push(...te.covered)}}catch(ie){console.log(V(`Style fix pass failed: ${ie.message}`))}if(he.length>0)try{ow(t.cwd,he,ut("lint"))}catch{}for(let ie of md(Se.errors.length,Sr(t.cwd,l,d)))console.log(ie.startsWith("\u2713")?Y(ie):V(ie))}{let Te=nw($,I.results),he={aborted:!!I.aborted,partitions:$.length,failed:Te.failed.length,notRun:Te.notRun.length,leftBehind:Sr(t.cwd,l,d).filter(ie=>ie.severity==="error").length,...I.blocked?{blocked:I.blocked}:{},...I.allEmpty?{allEmpty:!0}:{},...I.bailedEmpty?{bailedEmpty:!0}:{}};if(qt(he)){let ie=`/write${o?` --scope ${o}`:""}${e.includes("--rewrite")?" --rewrite":""}`;for(let te of Tt(t.cwd,ie))console.log(Y(te))}}}}catch(I){console.log(_(`Write run failed: ${I.message}`))}return console.log(""),{kind:"continue"}}se();import{existsSync as OS,readdirSync as iw,statSync as aw}from"node:fs";import{join as lw}from"node:path";import{inputDir as _S,readProjectConfig as MS}from"document360-engine";var cw=/\.(md|markdown|pdf|txt)$/i;function wd(e){let t=_S(e);if(!OS(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of iw(t)){let s=lw(t,r),i=!1;try{i=aw(s).isDirectory()}catch{continue}if(i){if(r.startsWith("."))continue;let a=FS(s);a>0&&n.push({name:r,docCount:a})}else cw.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function FS(e){let t=0;for(let n of iw(e))try{aw(lw(e,n)).isFile()&&cw.test(n)&&t++}catch{}return t}function yd(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 Wa(e,t){return["Run the draft-from-prd skill.","",`Target scope: ${e?`the feature documents in .d360-writer/input/${e}/`:t?`the input docs in .d360-writer/input/ relevant to: "${t}"`:"the input docs in .d360-writer/input/"}.`,t&&!e?`Use "${t}" as the feature framing.`:"","","Follow the skill: (1) read those PRDs/specs as the primary source (intent, user-facing surface,","terminology, user stories, prerequisites); (2) locate and read the CODE that implements that surface","to pin exact UI strings/routes/states, and never fabricate; flag anything the PRD claims that you","cannot find in source; (3) propose a tight feature-scoped article set (\u22483\u20135) and pin it to",".d360-writer/plan.json + AGENT-PLAN.md, with each article's `sources` listing BOTH the PRD file(s)","AND the grounding code files; (4) flag overlaps with existing articles (do not merge). Then stop and","offer /write. Do NOT write the articles in this turn."].filter(Boolean).join(`
|
|
395
|
+
`)}var bd="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function uw(e,t){let n=t?.cwd??process.cwd();if(!MS(n))return console.log(_("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=wd(n);if(o.length===0&&r===0)return console.log(m(bd)),{kind:"continue"};let s=e.join(" ").trim();if(!s){if(o.length>1){console.log(m("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let l of o)console.log(` ${l.name} ${m(`(${l.docCount} doc${l.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let a=o[0]?.name??"";return{kind:"forward-to-agent",prompt:Wa(a),display:a?`/draft ${a}`:"/draft"}}let i=yd(o,s);return{kind:"forward-to-agent",prompt:Wa(i??"",i?void 0:s),display:`/draft ${s}`}}se();import{listOpenForDocs as US,readProjectConfig as WS}from"document360-engine";function kd(e){try{return US(e).filter(t=>t.kind==="request").length}catch{return 0}}function $d(e){let t=e.includes("--push")||e.includes("--publish"),n=e.includes(At),o=e.filter(r=>!r.startsWith("--")).join(" ").trim();return{push:t,skipReview:n,what:o}}function vd(e){let t=["Run the document-handoff skill.",""];return e?t.push(`The builder hand-off (what was shipped this session): "${e}".`,"Treat this as the Stage 1 hand-off: ground it in the cited/changed code + the architecture brief,","then decide and APPLY the right doc action: a new section, a new article, an update to existing","article(s), or a retirement, or a mix. No fixed shape; pick the smallest set that keeps the docs correct."):t.push("No description was given, so call d360_inbox and act on the OPEN `request` messages the builder left:","for each, run the document-handoff flow (ground \u2192 decide \u2192 apply) and mark the request `status: done`","with `resulting_articles` when finished."),t.push("","Draft only; do not publish. If you would create multiple new articles (a section), call","d360_estimate_cost and present the count + cost band first, then wait for the go-ahead."),t.join(`
|
|
396
|
+
`)}var xd="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 dw(e,t){let n=t?.cwd??process.cwd();if(!WS(n))return console.log(_("No d360-writer config here. Run /init first.")),{kind:"continue"};let{push:o,what:r}=$d(e);if(!r&&kd(n)===0)return console.log(m(xd)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --push":""}`;return{kind:"forward-to-agent",prompt:vd(r),display:s}}se();import{search as BS}from"@inquirer/prompts";import{findByName as HS,getSession as GS,listSessions as qS,relativeTime as hw}from"document360-engine";async function fw(e,t){let n=qS(t.cwd).filter(o=>o.uuid!==t.currentUuid());if(n.length===0)return console.log(m("No saved sessions for this repo yet \u2014 sessions auto-save as you work.")),{kind:"continue"};if(e.length>0){let o=e.join(" "),r=HS(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(_(`No session matches "${o}".`)),pw(n),{kind:"continue"})}if(!process.stdin.isTTY)return pw(n),console.log(m("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>BS({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} ${hw(a.updatedAt)}`,value:a.uuid,description:a.firstPrompt.slice(0,100)}))}})),r=GS(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function pw(e){console.log("");for(let t of e.slice(0,15))console.log(` ${Z(t.name)} ${m(hw(t.updatedAt))}`),console.log(` ${m(t.firstPrompt.slice(0,80))}`);console.log("")}se();import{renameSession as VS}from"document360-engine";function Rd(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 mw(e,t){let n=Rd(e.join(" "));if(!n)return console.log(_("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(VS(o,n)?console.log(Y(`\u2713 Session renamed to "${n}"`)):console.log(_("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(Y(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as gw,readProjectConfig as YS,writeProjectConfig as KS}from"document360-engine";se();function Sd(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=YS(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 gw().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},KS(o,e),null):`Unknown environment "${r}". Known: ${gw().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function ww(e,t){let n=e[0];if(!n)return Mi(t.cwd),{kind:"continue"};if(n==="add"){let o=Sd(t.cwd,e[1],e[2]);return o?(console.log(_(o)),{kind:"continue"}):(console.log(Y(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${Z(`/profile ${e[1]}`)} then ${Z("/login")}`),console.log(m(" Until you switch, this repo keeps using the current profile\u2019s environment.")),{kind:"continue"})}return Fi(t.cwd,n),Ui(t.cwd,n),console.log(m(" Restarting agent for the new profile\u2026")),{kind:"clear"}}se();import{select as zS}from"@inquirer/prompts";import{readProjectConfig as XS,readUserConfig as yw,resolveModelSetting as Cd,writeUserConfig as bw}from"document360-engine";var Nt=[{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 Ba(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=Nt.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function QS(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 Fs(e,t){let n=()=>Cd(e).model;if(t==="default"){let s=yw();return s.defaultModel?(delete s.defaultModel,bw(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${Cd(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}}bw({...yw(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=XS(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 kw(e,t){let n=e[0]?.trim();if(!n){let i=Cd(t.cwd);if(!process.stdin.isTTY)return console.log(`${qe("Model:")} ${Z(i.model)}${i.source==="auto"?m(" (auto)"):""}`),console.log(m(` source: ${QS(i)}`)),console.log(m(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let a=Ba(i),l;try{l=await t.withPausedInput(()=>zS({message:`Select model (current: ${i.model}${i.source==="auto"?" \xB7 auto":""})`,default:Nt[a].value,choices:Nt.map(($,P)=>({name:`${$.label}${P===a?" \u2714":""}`,value:$.value,description:$.desc}))}))}catch{return console.log(m("Cancelled.")),{kind:"continue"}}let{lines:d,changed:w,effective:g}=Fs(t.cwd,l??"default");for(let $ of d)console.log($.startsWith("\u26A0")?V($):$.startsWith("\u2713")?Y($):m($));return w&&await t.setModel(g),{kind:"continue"}}let{lines:o,changed:r,effective:s}=Fs(t.cwd,n);for(let i of o)console.log(i.startsWith("\u26A0")?V(i):i.startsWith("\u2713")?Y(i):m(i));return r&&await t.setModel(s),{kind:"continue"}}qa();async function Sw(e,t){return await t.withPausedInput(()=>rr(t.cwd)),{kind:"clear"}}async function Cw(e,t){return await t.withPausedInput(()=>Li(t.cwd,t.profileName)),{kind:"clear"}}se();import{resolveActiveProfile as vC}from"document360-engine";async function Pw(e,t){let n=!1;try{n=vC(t.cwd).production}catch{}return n?(console.log(V("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(m("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}se();var Tw=async(e,t)=>{try{await t.withPausedInput(()=>_i({}))}catch(n){if(console.log(_(`Login failed: ${n.message}`)),!Zi(t.cwd,t.profileName))return console.log(m("Your Document360 session still isn't working \u2014 run /login to try again.")),{kind:"continue",ownNext:!0}}return{kind:"continue"}};import{resolveActiveProfile as xC,clearTokens as RC,clearProfileProject as SC,listStoredSessions as CC,tokensProjectId as PC}from"document360-engine";se();async function Aw(e,t){let n,o,r,s;try{let g=xC(t.cwd,t.profileName);n=g.name,o=g.connection.name,r=g.project.projectId,s=g.project.projectName}catch(g){return console.log(_(g.message)),{kind:"continue"}}let i=e.includes("--all-projects"),a=CC(n).filter(g=>{let $=PC(g);return!!$&&$!==r}).length,l=RC(n,i?void 0:r);SC(t.cwd,n);let d=i||a===0?"":` Your sign-in for ${a} other project${a===1?"":"s"} is untouched (/logout --all-projects clears those too).`;console.log(l?i?Y(`\u2713 Signed out of every Document360 project for "${n}" and cleared this repo's project/workspace selection.`):Y(`\u2713 Signed out of ${s?`"${s}"`:`"${n}"`} and cleared its project/workspace selection.${d}`):m(`Profile "${n}" was not signed in. Cleared any project/workspace selection.${d}`)),console.log(m(`Run /login to sign back in to "${n}" (the ${o} environment) and pick a project.`));let w=Tn(t.cwd,t.profileName);return console.log(w?V(`\u26A0 ${w.why}. Signing out doesn\u2019t change the environment \u2014 ${w.cmd} does.`):m(" Different environment? That comes from the profile, not the login \u2014 /profile add <environment>.")),{kind:"continue"}}import{existsSync as Nw,readFileSync as Ad}from"node:fs";import{homedir as OC}from"node:os";import{basename as _C,join as Hs}from"node:path";import{readProjectConfig as MC,DEFAULT_OUTPUT_DIR as FC,existingAnnotatedShotPath as G6,resolveOutputDir as UC,shotArtifacts as WC}from"document360-engine";import wt from"picocolors";import{annotationsPath as TC,resolveOutputDir as AC,readProjectConfig as EC,DEFAULT_OUTPUT_DIR as DC,existingAnnotatedShotPath as NC}from"document360-engine";function jC(e){let n=e.filter(o=>o!=="--all"&&o!=="-a").find(o=>!o.startsWith("-"));return n?{mode:"single",id:n}:{mode:"all"}}function Ws(e){return e.filter(t=>t.state==="annotated").map(t=>t.id)}function on(e,t){let n=AC(e,EC(e)?.outputDir??DC),o=new Map(Fe(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(NC(n,i))}`,` facts: ${r(TC(n,i))}`,` article: ${a}`].join(`
|
|
397
397
|
`)}).join(`
|
|
398
398
|
`);return[`Run the review-screenshots skill over ${t.length} newly captured screenshot${t.length===1?"":"s"}.`,"","For EACH shot below:","1. READ THE IMAGE FILE. Actually look at the picture; this judgment cannot be made from the spec"," source or the JSON alone.","2. Read its facts JSON (the `capture` block records what the capture observed: image dimensions,"," crop origin, whether the origin was inferred rather than declared, selectors that never resolved,"," boxes that fell outside the frame, how many elements each highlight/redaction selector covered,"," and whether the page was still loading when the shutter fired).","3. Read the article to see what the placeholder promises the reader at that point.","4. Record a verdict with d360_verify_screenshot; every shot gets exactly one call.",' On "rejected": give a one-line plain-language reason, then FIX THE SPEC that produced it and pass'," repaired: true. Do not re-run the capture yourself; the user does that.","",s,"","Then report to the user briefly: ONE line per rejected shot naming the defect in plain words and what","you changed. Do NOT state counts, totals, or the re-capture command; an exact receipt is printed from","your recorded verdicts right after your report, so any number you state can only contradict it."].join(`
|
|
399
|
-
`)}function Wn(e){return`${J("\u2192",
|
|
400
|
-
${
|
|
401
|
-
`)}function
|
|
402
|
-
`):
|
|
403
|
-
`)}var
|
|
404
|
-
`)}function
|
|
405
|
-
/screenshot list --detail shows what each one needs`}function
|
|
406
|
-
`),cmd:o.length>0?`/screenshot ${l}`:r.length>0?w:t.length>0?i:a,tone:o.length>0||r.length>0?"warn":"info"}}function
|
|
407
|
-
Check them when you're ready: ${Re("/screenshot verify","",i)}`),{kind:"continue"};let N=T.filter(
|
|
408
|
-
`),display:"/screenshot checklist"}}function
|
|
409
|
-
`)}async function
|
|
410
|
-
`).map(s=>s.trim()).filter(Boolean).slice(-1)[0];return r?` \u2014 ${r}`:""};switch(e){case"no-git":return"This folder is not a git repository, so there is nowhere to share to. Your docs are still saved on this machine.";case"detached-head":return"This repo is not on a branch right now. Ask your builder to check out a branch, then run /share.";case"mid-operation":return"A merge or rebase is in progress here. Finish or cancel it first, then run /share.";case"no-upstream":return"This branch has no remote yet, so there is nowhere to send your work. Ask your builder to run: git push -u origin HEAD";case"disabled":return"Sharing is switched off for this repo. Turn it on: /share on";case"diverged":return"Your work and your builder's have both moved on, so they can't be combined automatically. Your work is committed and safe \u2014 ask your builder to merge the branch.";case"rejected":return"Someone pushed to this branch first, so your work could not be sent. It IS committed and safe \u2014 try /share again in a moment, or ask your builder to merge the branch.";case"auth":return"Git could not sign in to the remote. Ask your builder to set up your git credentials, then run /share.";case"network":return"Could not reach the remote. Check your connection, then run /share again.";case"hook-failed":return`This repo's own commit checks rejected the change${n(t)}. Ask your builder to take a look \u2014 your docs are safe on this machine.`;case"failed":return`Git could not finish the share${n(t)}. Your docs are safe on this machine \u2014 run /share to try again, or show this line to your builder.`}}function Va(e,t){let n=Xw(t);if(!n.commit)return[{tone:"info",text:"Sharing: off \u2014 d360-writer leaves its work for your coding agent to commit."},{tone:"info",text:"Turn it on: /share on"}];let o=fP(e);if(!o)return[{tone:"info",text:"Sharing: unavailable \u2014 this folder is not a git repository."}];if(!o.upstream)return[{tone:"warn",text:J("\u26A0")+`This branch (${o.branch??"detached"}) has no remote, so your work can't reach your team yet.`},{tone:"info",text:"Ask your builder to run: git push -u origin HEAD"}];let r=n.push===!0?"on":n.push==="unconfirmed"?"not set up yet":"off",s=[{tone:"info",text:`Sharing: ${o.branch} \u2192 ${o.upstream} \xB7 saving: on \xB7 sending: ${r}`}];return o.ahead>0?s.push({tone:"warn",text:J("\u26A0")+`${o.ahead} change${qs(o.ahead)} not shared yet \u2014 run /share`}):s.push({tone:"ok",text:J("\u2713")+"Everything is shared with your team."}),s}function qd(e,t,n){zw({...t,gitHandoff:{commit:n,push:n}},e);let o=n?{tone:"ok",text:J("\u2713")+"Sharing on \u2014 d360-writer will save and send its own work from now on."}:{tone:"ok",text:J("\u2713")+"Sharing off \u2014 d360-writer will leave its work for your coding agent to commit."};return n?[o,...Va(e,{...t,gitHandoff:{commit:!0,push:!0}})]:[o]}async function Ya(e,t){let n=[],o=Xw(t);if(!o.commit)return{lines:[{tone:"info",text:Bn("disabled")}],changed:!1};let r=t;o.push==="unconfirmed"&&mP(e,t)&&(r={...t,gitHandoff:{commit:!0,push:!0}},zw(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 hP(e);if(s.ok&&s.pulled>0){let d=[s.newHints>0?`${s.newHints} new hint${qs(s.newHints)}`:null,s.newMessages>0?`${s.newMessages} new message${qs(s.newMessages)}`:null].filter(Boolean);n.push({tone:"ok",text:J("\u2B07")+`Got your builder's latest${d.length?` \u2014 ${d.join(", ")}`:""}.`})}else!s.ok&&s.reason!=="no-upstream"&&s.reason!=="no-git"&&n.push({tone:"warn",text:J("\u26A0")+Bn(s.reason,s.detail)});let i=await pP(e,r);if(i.commit&&!i.commit.ok)return n.push({tone:"warn",text:J("\u26A0")+Bn(i.commit.reason,i.commit.detail)}),{lines:n,changed:!1};let a=i.commit?.ok?i.commit.committed.length:0;if(a>0&&n.push({tone:"ok",text:J("\u2713")+`Saved ${a} change${qs(a)} to the docs folder.`}),i.push&&!i.push.ok)return n.push({tone:"warn",text:J("\u26A0")+Bn(i.push.reason,i.push.detail)}),{lines:n,changed:a>0};let l=i.push?.ok?i.push.pushed:0;return l>0?n.push({tone:"ok",text:J("\u2B06")+`Shared ${l} change set${qs(l)} with your team.`}):a===0&&(s.ok&&s.pulled===0)?n.push({tone:"ok",text:J("\u2713")+"Everything is already shared with your team."}):a>0&&!i.push&&n.push({tone:"info",text:"Saved on this machine only. /share on lets d360-writer send it to your team too."}),{lines:n,changed:a>0||l>0||s.ok&&s.pulled>0}}var gP={ok:Y,info:xe,warn:G,error:_};async function Qw(e,t){let n=t.cwd,o=dP(n);if(!o)return console.log(_("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase(),s=a=>{for(let l of a)console.log(gP[l.tone](l.text))};if(r==="status")return s(Va(n,o)),{kind:"continue"};if(r==="on"||r==="off")return s(qd(n,o,r==="on")),{kind:"continue"};if(r)return console.log(_(`Unknown option "${r}". Use /share, /share status, /share on, or /share off.`)),{kind:"continue"};console.log(m("Exchanging work with your team\u2026"));let{lines:i}=await Ya(n,o);return s(i),{kind:"continue"}}function kn(e){let t=0,n=0,o=0,r=0;try{t=wP(e).length}catch{}try{let s=yP(e);n=s.filter(i=>i.kind==="request").length,o=s.filter(i=>i.kind==="answer").length}catch{}try{r=bP(e).length}catch{}return{hints:t,requests:n,answers:o,directives:r}}async function Yd(e){let t=Jw(e);if(!t)return[];if(!CP(e,t))return[];let n=await SP(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 ${Bn(n.reason,n.detail)}`}]}function Ka(e){let t=[];return e.hints&&t.push(`${e.hints} hint${e.hints===1?"":"s"}`),e.requests&&t.push(`${e.requests} request${e.requests===1?"":"s"}`),e.answers&&t.push(`${e.answers} answer${e.answers===1?"":"s"}`),e.directives&&t.push(`${e.directives} directive${e.directives===1?"":"s"}`),t.length?t.join(", "):null}function Kd(e){let t=Ka(e);return t?`Catching up on ${t}\u2026`:"Nothing queued from your builder \u2014 checking Document360 for reviewer comments and feedback\u2026"}function za(e){let t=Ka(e.queued);return t?{tone:"warn",note:`${J("\u26A0")}That run finished without writing anything, and ${t} ${e.queued.hints+e.queued.requests+e.queued.answers+e.queued.directives===1?"is":"are"} still queued \u2014 nothing was lost.`,lead:{cmd:"/catch-up",reason:"the queue is untouched, so running it again picks up the same work"}}:e.hold?{tone:"info",note:`${J("\u2139")}No articles changed \u2014 product discovery is still open, so new overview and concept pages are on hold.`,lead:null}:{tone:"info",note:`${J("\u2713")}Nothing needed writing \u2014 no articles changed.`,lead:null}}function zd(e){return{push:e.includes("--push")||e.includes("--publish"),skipReview:e.includes(Pt)}}function Vs(e){let t={hold:!1,openQuestions:0,answersPending:0};try{let n=PP(e);return!n||n.status==="confident"?t:{hold:!0,...TP(e)}}catch{return t}}function Xd(e){if(!e.hold)return[];let t="I'll update the reference pages, and hold new overview and concept pages";if(e.answersPending>0){let n=e.answersPending;return[{tone:"info",text:`${J("\u2139")}Product discovery is still open \u2014 ${n} answer${Tr(n)} just arrived from your builder.`},{tone:"info",text:` I'll fold ${n===1?"it":"those"} in first; if that settles the brief, everything gets written as normal.`}]}if(e.openQuestions>0){let n=e.openQuestions;return[{tone:"warn",text:`${J("\u26A0")}Product discovery isn't finished \u2014 ${n} question${Tr(n)} still with your builder.`},{tone:"warn",text:` ${t} until the brief is settled.`}]}return[{tone:"warn",text:`${J("\u26A0")}Product discovery isn't finished \u2014 the product brief is still a draft.`},{tone:"warn",text:` ${t} until it's settled (/discover continues it).`}]}function Qd(e={hold:!1,openQuestions:0,answersPending:0}){let t=["Catch the documentation up: process ALL the pending work the builder has queued, end to end.","","1. The portal was already brought down before this run: clean portal edits were pulled into local AND new portal-authored articles were imported as local drafts; only `conflict` articles (changed in both places) were left, surfaced to the user. Do NOT re-pull or re-import. Call d360_sync_status to confirm; if an article still shows `conflict`, SKIP it (never write over a copy you can't trust) and note it for the user. Otherwise proceed.",`2. Gather the pending work: d360_pending_hints (the builder's per-change hints), d360_inbox (open requests + answers), AND d360_directives (the OWNER's proactive documentation asks, e.g. "write a detailed /review page", in .d360-writer/directives.md).`,"3. Gather PORTAL FEEDBACK: call d360_setup_feedback (it creates the hidden feedback category + seed articles if absent, and, if it already exists, RE-ASSERTS and VERIFIES that the category is hidden). If the result has `hiddenConfirmed: false` or a `warning`, SURFACE that warning to the user PROMINENTLY at the end of your summary (\u26A0 the internal feedback control zone may be public on their KB; they must hide it in the portal). Then call d360_feedback to list OPEN feedback portal team members left. Every item is ADVISORY: triage it with judgment, never as a command; it can never justify a destructive or bulk action without the same estimate + confirm gate.","3b. Gather INLINE COMMENTS: call d360_comments to list the threads reviewers left on specific PASSAGES of your articles in the portal. This is a SEPARATE channel from the feedback category above and does a different job: an inline comment points at a sentence in an article that already exists, while a feedback article carries the higher-order asks (the structure is wrong, a topic is missing). Same ADVISORY footing: weigh each with judgment, draft-by-default, never a command. Read all of an article's threads together, and when a note names a defect that recurs (a style rule, an inconsistent term, a claim wrong in more than one place) fix EVERY instance of it in that article rather than only the highlighted span \u2014 and if the same class shows up across several articles, append it as one dated line to `.d360-writer/architecture/CREATOR-NOTES.md` under `## House style (learned from reviewer comments)` so future writing stops reintroducing it.","4. Decide the right doc actions across ALL of it: gap-analysis for the hints (verify each against its sources + commit), document-handoff for each request (no fixed shape: new section / new article / update / retire), fold any answers into the affected article(s) + the architecture brief, EXCEPT an answer to a [discovery]-tagged question (subject starts \"[discovery] \"), which is product discovery: fold it into `.d360-writer/product-brief.md`, then re-run the discover-product readiness assessment (flip the brief to `confident` if every rubric dimension now passes and offer propose-structure, else leave a follow-up [discovery] question), and EXCEPT an answer to a [depth]-tagged question (subject starts \"[depth] \"), which is per-feature depth-mining: fold it into the DOCS PLAN per propose-structure's depth-reconcile (adjust that feature's article palette in plan.json/AGENT-PLAN.md, cite the answer's messages/ file in new rows' `sources`, never renumber existing rows, decrement AGENT-PLAN.md's open_depth_questions and flip status to `pinned` at zero). Address each feedback item (improve the doc it points at, as a draft), and action each OWNER DIRECTIVE (honor its scenario/detail, ground it in the sources, write/update the article(s) as drafts, following the active doc-type playbook)."];if(e.hold){let n=e.openQuestions>0?e.answersPending>0?"ask their builder to answer the discovery questions still open \u2014 state the number you are left with AFTER re-assessing the brief, never the number this run started with":`ask their builder to answer the ${e.openQuestions} open discovery question${Tr(e.openQuestions)}`:"continue product discovery to settle the brief";t.push('4b. PRODUCT DISCOVERY IS UNFINISHED. The product brief (.d360-writer/product-brief.md) is not `confident` yet, so the narrative it grounds \u2014 what this product IS, who it is for, the core mental model, the misconceptions, the positioning \u2014 is not settled. Decide what follows AFTER step 4, never before: if the answers you just folded in completed the brief and you flipped it to `confident`, this instruction and 4c are VOID \u2014 write everything as normal. Otherwise HOLD the articles whose shape or framing would change once the brief is confident (overview/introduction, concept and explanation pages, getting-started, positioning, "who it is for") and write everything else normally \u2014 a changed flag, a new subcommand, a corrected behaviour, a deprecation or a screenshot on an EXISTING reference page does not need the brief. The test for each candidate article: would you rewrite this page after reading a finished brief? If yes, hold it; if no, write it.',`4c. A HELD item MUST stay queued. Do NOT stamp its hint consumed, do NOT mark its message done, and do NOT flip its directive to done in step 7 \u2014 the open hint IS the queue, so stamping one you did not write means that article is never written at all. In your closing summary, name every page you held in plain words, say their hints stay queued so nothing is lost, and give exactly one next step: ${n}.`)}return t.push("5. If that means writing more than one article, call d360_estimate_cost and show me the count + cost band first (the bulk gate), then proceed.","6. Write/update the articles as drafts, grounded in the cited sources.","7. Close the LOCAL loop (bookkeeping in the repo; nothing here is visible to a reviewer):"," \u2022 stamp consumed hints, and mark handled messages status: done with resulting_articles;"," \u2022 for each OWNER DIRECTIVE you actioned: call d360_directive_done with its exact title + the article path(s) you wrote (flips it to [done] in .d360-writer/directives.md);"," \u2022 reconcile the DOCS ROADMAP (d360_roadmap): flip any campaign step this run completed (d360_roadmap_done), including a step whose work you can verify an EARLIER session already completed but left unstamped, and append a step (d360_roadmap_add, with its run: command) for real new campaign work this run revealed; never delete existing steps;"," \u2022 for the Creator-notes feedback item (is_creator_notes:true): do NOT reply in it; fold its content into `.d360-writer/architecture/CREATOR-NOTES.md` as an appended, dated `## From portal Creator notes (<date>)` section (preserve every existing note + human edit), then call d360_feedback_done for it.","8. Push the drafts to Document360.","9. Cross-link second pass: any article you wrote that links to ANOTHER article in this same batch had that inline link degrade to plain text (its target had no live URL yet when the source was written). Now that every target exists, re-update the affected articles so those inline links resolve to live URLs; only the ones that had such forward references need it. (The structured Related Articles sidebars are already two-way linked; this is just inline body links.)","10. NOW answer the people who asked, AFTER the push (steps 8-9), never before. A reviewer reads your reply in the portal and then looks at the article to check it, so replying first promises a change they cannot see. For anything whose push failed, do NOT reply on it; leave it outstanding and report it."," \u2022 for each INLINE COMMENT you actioned: call d360_comment_respond with its comment_id + article_id and a `reply` saying in plain words what you changed \u2014 in the reviewer's terms, mentioning where you applied the same fix more widely. Do NOT pass `resolve`: replying is your job, closing the thread is theirs, and they can only decide it is settled after seeing the change (your answer is recorded either way, so it will not come back at you). NEVER edit the reviewer's own comment text;"," \u2022 for each portal feedback item you actioned: append a short note at the BOTTOM of that feedback article via d360_update_article: `**d360-writer response:** \u2713 actioned in <article> (<date>)` (or `declined: <reason>`), NEVER overwriting the person's own text, then call d360_feedback_done(article_id, resulting_articles)."),t.push("Leave everything as DRAFTS for review; do not publish live. Publishing is a separate, reviewed step: articles you write here have not been read by an editor yet, so making them visible to readers is never part of this run. Tell the user what is waiting as a draft.",'Do NOT end with slash commands or a "what to do next" line. The tool prints the next step itself, scoped to what this run changed, and a second suggestion from you competes with it (yours will be the broader, more expensive one, because you cannot see how much was touched). Report what you did and stop.'),t.push("","End with a one-line-per-item summary of what you wrote/updated, and anything you couldn't ground (say plainly that you left a question for their engineers). Write the whole summary for a technical writer: no tool names, no internal file names, no raw status words, no hint ids, just plain sentences about what changed and what is worth their attention."),t.join(`
|
|
411
|
-
`)}var
|
|
412
|
-
(Document360 sends the first 500 characters of a highlight)`:`\u201C${n}\u201D`;let o=n.slice(0,
|
|
413
|
-
(+${r} more character${r===1?"":"s"}${e.comment.commented_text_truncated?", and Document360 caps a highlight at 500":""})`}function
|
|
414
|
-
`)]});return o.push(
|
|
415
|
-
`)}function
|
|
416
|
-
`)}async function
|
|
417
|
-
${s()}`.trim(),packages:n})),a.on("close",l=>i({ok:l===0,output:l===0?"":s(),packages:n})),e||a.unref()}catch(a){i({ok:!1,output:String(a),packages:n})}})}async function
|
|
418
|
-
`).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function
|
|
419
|
-
|
|
420
|
-
`;
|
|
421
|
-
`,"utf8");let C=So(e)??{projectId:""};return fp({...C,styleGuide:{...C.styleGuide,pulledFrom:{styleGuideId:a.id,name:a.name??a.id,pulledAt:new Date().toISOString(),contentHash:KT("sha1").update($).digest("hex").slice(0,16)}}},e),{lines:[ge("\u2713",`Pulled "${a.name??a.id}" into .d360-writer/style-guide.md (${$.length.toLocaleString()} characters).`),...g,m(" This is PROSE, not rules \u2014 /review judges against it, and the writer now writes to it."),m(" Turn its mechanical parts into checks: /style-guide compile"),m(" Restarting the agent so it writes to the new guide\u2026")],restart:!0}}function JT(e){let t=pp(e).rules.filter(n=>n.pack.toLowerCase()===Xs.toLowerCase()).map(n=>n.id);return{prompt:OT({guide:_T(e),packName:Xs,existingRuleIds:t}),display:"/style-guide compile"}}function ZT(e){let t=UT(e),n=mp(t)?yy(t,"utf8").trim():"";return!n||!/^## /m.test(n)?{kind:"nothing",lines:[ge("\u2139","No reviewer comments have been read yet, so there is nothing to learn from."),m(" Reviewers comment on your drafts in Document360; /comments reads them, and every read"),m(" keeps a copy in .d360-writer/reviewer-notes.md. Run /comments first.")]}:{kind:"run",prompt:FT({notes:n,existingRules:MT(e),houseRulesFile:".d360-writer/house-rules.md"}),display:"/style-guide learn"}}function ky(){return[m(" Read what it wrote: git diff .d360-writer/house-rules.md"),m(" These rules apply from now on \u2014 the writer follows them and /review judges against them."),m(" Disagree with one? Delete the line. It is your file, and nothing regenerates it."),m(" Restarting the agent so it writes to the new rules\u2026")]}function $y(){return[m(` Review what it wrote: git diff .d360-writer/styles/${Xs}/`),m(` Anything it could not check mechanically is listed in .d360-writer/styles/${Xs}/UNCHECKABLE.md \u2014 /review judges those.`),m(` Turn them on when you are happy: /style-guide use ${Xs.toLowerCase()} (they start as warnings, never blocking)`)]}var wt=(e,t)=>`${e} ${t}${e===1?"":"s"}`,up=e=>/^v\d/i.test(e)?e:`v${e}`;function vy(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 eA(e){let n=So(e)?.styleGuide?.pulledFrom;return n?`.d360-writer/style-guide.md \u2014 pulled ${n.pulledAt.slice(0,10)} from "${n.name}"`:mp(wy(e))?".d360-writer/style-guide.md (yours)":"the built-in default"}function tA(e){let t=So(e),n=pp(e),o=(t?.styleGuide?.packs??[]).filter(Boolean),r=n.packs.filter(l=>l.name.toLowerCase()===Ro),s=n.packs.filter(l=>l.name.toLowerCase()!==Ro),i=[`Style guide: ${eA(e)}`,`Rule packs: ${s.length>0?s.map(l=>`${l.name.toLowerCase()} ${up(l.version)}`).join(", "):m("none chosen")}`,`Always on: ${m(`d360 (correctness, built in \u2014 ${wt(ol.length,"rule")})`)}`];for(let l of r)i.push(` ${m(`${l.name.toLowerCase()} ${up(l.version)} (anti-slop \u2014 ${wt(l.ruleCount,"rule")})`)}`);r.length>0&&(i.push(m(" Every article here is machine-written, so these cannot be switched off by")),i.push(m(" choosing another pack. styleGuide.humanise: false turns them off deliberately.")));let a=[...ol.map(l=>({severity:l.severity})),...n.rules.map(l=>({severity:l.severity}))];i.push("",`${wt(a.length,"rule")} active \xB7 ${vy(a)}`);try{let l=hp({cwd:e}),d=l.findings.filter(g=>!g.baselined),w=d.filter(g=>g.severity==="error").length;i.push(""),i.push(w===0?ge("\u2713",`No style errors across the docs${d.length>0?`, though ${wt(d.length,"other issue")} ${d.length===1?"is":"are"} reported`:""}.`):ge("\u2717",`${wt(w,"style error")} \u2014 /lint --blocked shows them, /lint --blocked --fix corrects them.`)),l.baselinedCount>0&&i.push(ge("\u2139",`${wt(l.baselinedCount,"issue")} ${l.baselinedCount===1?"was":"were"} already in your articles when this style guide was chosen, so ${l.baselinedCount===1?"it never blocks":"they never block"} publishing.`)),l.ruleErrors.length>0&&i.push(ge("\u26A0",`${wt(l.ruleErrors.length,"rule")} could not be loaded: ${l.ruleErrors.slice(0,2).map(g=>`${g.ruleId} (${g.reason})`).join("; ")}`))}catch{}return i.push(""),i.push(m(" See them all: /style-guide list \xB7 change: /style-guide use <preset> \xB7 one rule: /style-guide explain <rule>")),gp(e)&&(i.push(""),i.push("Nobody has settled this yet, and it is a decision \u2014 nothing above changed anything:"),i.push(" Happy with these rules? /style-guide keep"),i.push(" Want a stricter standard? /style-guide use microsoft (or google)"),i.push(m(" Worth settling now rather than later: it shapes every article written from here, and")),i.push(m(" changing it once a knowledge base exists means going back over what is already written."))),i}function dp(e){let t=So(e),n=new Set(gy(t?.styleGuide)),o=my(e),r=["Rule packs you can turn on:",""],s=Math.max(12,...o.map(i=>i.name.length));for(let i of o){let a=i.name.toLowerCase(),l=n.has(a),d=a===Ro,w=l?"\u2713":"\xB7",g=d?m("(always on)"):l?m("(active)"):"",$=i.local?m(" [yours]"):"";r.push(` ${w} ${a.padEnd(s)}${$} ${i.description??""}`),r.push(` ${m(`${wt(i.rules.length,"rule")} \xB7 ${vy(i.rules)} \xB7 ${up(i.version)}`)} ${g}`),i.errors.length>0&&r.push(ge("\u26A0",`${wt(i.errors.length,"rule")} in this pack could not be loaded \u2014 /style-guide explain names them.`))}return o.every(i=>i.name.toLowerCase()===Ro)&&(r.push(""),r.push(m(" The Microsoft and Google style guides are not installed in this build yet."))),r.push(""),r.push(m(" Turn one on: /style-guide use <name> (this replaces the chosen set, it does not add to it)")),r.push(m(" Several: /style-guide use microsoft,google")),r.push(m(" Back to none: /style-guide use none")),r}function nA(e,t){if(!t)return[ge("\u26A0","Name a rule: /style-guide explain Humanise.EmDash")];let n=pp(e),o=ol.find(d=>d.id.toLowerCase()===t.toLowerCase()),r=n.rules.find(d=>d.id.toLowerCase()===t.toLowerCase());if(!o&&!r){let d=[...ol.map(w=>w.id),...n.rules.map(w=>w.id)].filter(w=>w.toLowerCase().includes(t.toLowerCase())).slice(0,5);return[ge("\u26A0",`No active rule called "${t}".`),...d.length>0?[m(` Did you mean: ${d.join(", ")}`)]:[m(" /style-guide list shows the active packs.")]]}let s=o?.id??r.id,i=o?.severity??r.severity,a=o?"built in (correctness \u2014 always on)":`pack: ${r.pack.toLowerCase()}`,l=[`${s} ${i} \xB7 ${a}`,""];l.push(` ${o?.summary??r.message}`),r?.link&&l.push(m(` ${r.link}`)),r?.degraded&&(l.push(""),l.push(ge("\u26A0",`This rule is translated approximately: ${r.degraded}. It may match slightly more than the original does.`)));try{let d=hp({cwd:e}).findings.filter(g=>g.ruleId===s),w=d.filter(g=>!g.baselined);l.push(""),l.push(d.length===0?" Currently: no findings.":` Currently: ${wt(w.length,"finding")}${d.length!==w.length?`, plus ${d.length-w.length} baselined and hidden`:""}.`)}catch{}return l.push(""),o?(l.push(m(" Built-in checks are grounded in your product's own source and cannot be switched off \u2014 they")),l.push(m(" catch defects of fact, not matters of taste."))):(l.push(i==="error"?m(' This one BLOCKS publishing \u2014 your config sets it to "error" deliberately.'):m(" Style rules never block publishing. Fix it when you want to; it will not hold a page back.")),l.push(m(` Silence it everywhere: add "${s}": "off" to styleGuide.rules in .d360-writer/config.json`)),i!=="error"&&l.push(m(" Silence one passage: <!-- vale "+s+" = NO --> \u2026 <!-- vale "+s+" = YES -->"))),l}function oA(e,t){let n=(t??"").trim();if(!n)return{lines:[ge("\u26A0","Name the packs to use: /style-guide use microsoft (or `none`)"),...dp(e)],restart:!1};let o=n.toLowerCase()==="none"?[]:n.split(/[,\s]+/).map(d=>d.trim().toLowerCase()).filter(Boolean),r=new Map(my(e).map(d=>[d.name.toLowerCase(),d])),s=o.filter(d=>!r.has(d));if(s.length>0)return{lines:[ge("\u2717",`No rule pack named ${s.map(d=>`"${d}"`).join(", ")}.`),"",...dp(e)],restart:!1};let i=So(e)??{projectId:""};fp({...i,styleGuide:{...i.styleGuide,packs:o,decidedAt:new Date().toISOString()}},e),NT();let a=[ge("\u2192",`Switching to: ${o.length>0?o.join(", "):"the built-in checks only"}${o.includes(Ro)?"":` (+ ${Ro}, always on)`}\u2026`)];try{let d=hp({cwd:e}),w=new Set(d.findings.map(g=>g.path)).size;if(d.findings.length===0)a.push(ge("\u2713",w===0?"No articles yet \u2014 everything you write from here is held to the full set.":"Nothing to record: your articles are already clean against these rules."));else{let g=jT(e),$=DT(d.findings,LT(e));IT(e,$),a.push(ge("\u2713",`Recorded ${wt(d.findings.length,"existing issue")} across ${wt(w,"article")} as accepted.`),m(" .d360-writer/style-baseline.json \u2014 commit it. It defines what the publish gate lets through, and a"),m(" teammate with a different copy gets a different answer from the same gate."),ge("\u2713","Nothing is blocked today. New writing, and any paragraph you edit, is held to the full set.")),a.push(ge("\u2139",`Those ${wt(w,"article")} do not follow ${o.join(", ")} \u2014 they are exempt, not compliant.`),m(" To bring them up to it: /review --all --fix, then /lint --all --fix. That is a pass over every"),m(" article and it costs accordingly \u2014 which is why this is worth settling before a knowledge base exists.")),g&&a.push(m(` (Replaced the baseline recorded ${g.createdAt.slice(0,10)}.)`))}}catch(d){a.push(ge("\u26A0",`The packs are active, but recording what was already there failed: ${d instanceof Error?d.message:String(d)}`)),a.push(m(" Run /lint to see the current state before publishing."))}let l=by(e);return l&&a.push(l),a.push(m(" Restarting the agent so it writes to the new rules\u2026")),{lines:a,restart:!0}}async function sl(e,t){let{sub:n,value:o}=rl(e),r=s=>{for(let i of s)console.log(i);console.log("")};switch(n){case"list":return r(dp(t.cwd)),{kind:"continue"};case"explain":return r(nA(t.cwd,o)),{kind:"continue"};case"use":{let s=oA(t.cwd,o);return r(s.lines),s.restart?{kind:"clear"}:{kind:"continue"}}case"keep":return r(XT(t.cwd)),{kind:"continue"};case"pull":{let s=await QT(t.cwd,o,t.profileName);return r(s.lines),s.restart?{kind:"clear"}:{kind:"continue"}}case"compile":{let s=JT(t.cwd);return{kind:"forward-to-agent",prompt:s.prompt,display:s.display}}case"learn":{let s=ZT(t.cwd);return s.kind==="nothing"?(r(s.lines),{kind:"continue"}):{kind:"forward-to-agent",prompt:s.prompt,display:s.display}}default:return r(tA(t.cwd)),{kind:"continue"}}}se();import{lintDocs as al,loadStyleGuide as Iy,buildReviewPrompt as Ly,hasCaptureArtifacts as Oy,readProjectConfig as _y,DEFAULT_DOCS_DIR as My,listArticleFiles as Dr,normalizeScope as gA,planPartitions as wA,runPartitioned as yA,partitionCoverage as bA,resolveModelForOperation as kA,stampArticles as $A,reviewStalePaths as vA,readReviewerNotes as Fy,renderNotesForPrompt as Uy,readDocsPlan as xA,CONTENT_CAP_VERSION as RA}from"document360-engine";import{listArticleFiles as rA,lintDocs as sA,planFindingPartitions as iA,planPartitions as aA,readDocsPlan as lA,readProjectConfig as cA,runRate as wp,DEFAULT_DOCS_DIR as uA}from"document360-engine";function xy(e){switch(e.cmd){case"/review":return{concurrency:Hn,maxPerPartition:bp,minutesPerBatch:5};case"/write":return{concurrency:3,minutesPerBatch:4};case"/lint":return{concurrency:3,minutesPerBatch:2};default:return{concurrency:3,minutesPerBatch:2}}}function Ry(e,t){let n=sA({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:iA(o).length}}function Sy(e,t){try{if(t.cmd==="/write"){let n=(cA(e)?.docsDir??uA).replace(/\/+$/,""),o=lA(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:In(e,n,r)}return t.cmd==="/review"?Co(e,[...t.flags],t.scope):rA(e,t.scope)}catch{return null}}function Cy(e,t){let n=$n(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 $n(e,t){let n=Zt(t);if(!n||!hr(n))return null;let o=xy(n),r=n.cmd==="/lint"?Er(()=>Ry(e,n)):null,s=r?null:Sy(e,n),i=r?r.articles:s?.length??0;if(n.cmd==="/lint"?!r||i<4:!s||i<4)return null;let a=r?r.batches:aA(s,o.maxPerPartition?{maxPerPartition:o.maxPerPartition}:void 0).length,l=Math.ceil(a/o.concurrency),d=Er(()=>wp(e,n.cmd)),w=l*(d?.minutesPerWave??o.minutesPerBatch),g=r?r.lead:`${i} articles`,$=d?.usdPerArticle!==void 0?` \xB7 ~${Ey(i*d.usdPerArticle)}`:"";return`${g} \xB7 ${a} batch${a===1?"":"es"} \xB7 ~${Ay(w)}${$}`}function Py(e,t){let n=Zt(t);if(!n||!hr(n))return null;let o=Er(()=>wp(e,n.cmd));if(o?.usdPerArticle===void 0)return null;let r=n.cmd==="/lint"?Er(()=>Ry(e,n)):null,s=r?r.articles:Er(()=>Sy(e,n))?.length??0;return s===0?null:s*o.usdPerArticle*yp}var Ty=.7,yp=1.4;function Ay(e){let t=Math.max(1,Math.round(e*Ty)),n=Math.max(t,Math.round(e*yp));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 Ey(e){let t=e*Ty,n=e*yp;return n>=10?`$${Math.round(t)}\u2013${Math.round(n)}`:`$${t.toFixed(2)}\u2013${n.toFixed(2)}`}function Er(e){try{return e()}catch{return null}}function il(e,t,n,o){if(n<4||o<1)return null;let r=xy({cmd:t,scope:void 0,flags:new Set,args:[]}),s=Math.ceil(o/r.concurrency),i=Er(()=>wp(e,t)),a=s*(i?.minutesPerWave??r.minutesPerBatch),l=i?.usdPerArticle!==void 0?` \xB7 ~${Ey(n*i.usdPerArticle)}`:"";return`~${Ay(a)}${l}`}import{renderGapsForPrompt as Wy}from"document360-engine";import{recordRunSample as SA}from"document360-engine";se();import{readProjectConfig as dA,loadProfileMap as pA,resolveActiveProfile as hA,desiredCategoryOrder as fA,desiredArticleOrder as mA}from"document360-engine";function Dy(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}var Ny=e=>e.replace(/\\/g,"/").split("/").pop()??e;function Qs(e,t){try{if(!dA(e))return[];let n=hA(e,t),o=pA(e,n.name);if(!o)return[];let r=new Map;for(let i of mA(o)){let a=r.get(i.categoryPath);a?a.push(i):r.set(i.categoryPath,[i])}let s=[];for(let i of fA(o)){s.push(Dy(Ny(i.path)));for(let a of(r.get(i.path)??[]).sort((l,d)=>l.order-d.order))s.push(` ${Dy(Ny(a.path))}`)}return s}catch{return[]}}async function jy(e,t){let n=Qs(t.cwd,t.profileName);if(n.length===0)return console.log(m("No documentation structure yet \u2014 run /init and author some articles first.")),{kind:"continue"};console.log(Z("Documentation order (categories \u2192 articles):"));for(let o of n)console.log(o);return console.log(""),{kind:"continue"}}function kp(e,t){return Rs(e,Dr(e,t))}function $p(e,t){return vA(e,Dr(e,t),RA)}function Js(e){return e.includes("--blocked")||e.includes("--stale")}function Co(e,t,n){return t.includes("--blocked")?kp(e,n):t.includes("--stale")?$p(e,n):Dr(e,n)}function By(e,t,n){let o;try{o=xA(e)}catch{return[]}let r=new Map(o.map(i=>[i.path.replace(/\\/g,"/"),i])),s=[];for(let i of n){let a=i.replace(/\\/g,"/").replace(`${t}/`,""),l=r.get(a);l&&s.push({path:i,type:l.type,...l.purpose?{purpose:l.purpose}:{}})}return s}function Hy(e,t){let n=_y(e);if(!n)return null;let o=(n.docsDir??My).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),s=Js(t),i=t.find(T=>!T.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),a=al({cwd:e}),l=i?gA(o,i):"",d=l?a.filter(T=>T.path===`${o}/${l}`||T.path.startsWith(`${o}/${l}/`)):a,w=s?Co(e,t,i):void 0,g=w?d.filter(T=>w.includes(T.path)):d,$=i||s?"":Qs(e).join(`
|
|
422
|
-
`),P=
|
|
423
|
-
`),display:`/reorder${n?` ${n}`:""}`}}async function
|
|
424
|
-
`)}function Pp(e,t={}){let n=AA(e,t.profileName),o=[];if(n.rows.length===0)return o.push(Z("Publish readiness")),o.push(""),o.push(n.tracked===0?`${J("\u25CB",qe.gray)}No articles are tracked yet. /write authors them, /push saves them to Document360.`:`${J("\u2713",qe.green)}All ${n.tracked} articles are live and unchanged \u2014 nothing is waiting on you.`),n.orphans.length>0&&o.push(...Vy(n)),o.push(""),o.push(m(" Free \u2014 /status reads your local files and the last sync. It calls nothing.")),o;let r=n.rows.length,s=n.blocked.length;o.push(Z("Publish readiness")+m(` ${r} article${r===1?"":"s"} not yet settled with readers \xB7 ${s===0?"nothing blocked":`${s} blocked`}`)),o.push(""),t.all&&(o.push(...jA(n,t.width??100)),o.push(""));for(let l of DA(n)){o.push(` ${J(l.glyph,l.paint)}${l.title}${l.fix?m(` ${l.fix}`):""}`);for(let d of l.items.slice(0,Cp))o.push(m(` ${d}`));l.items.length>Cp&&o.push(m(` \u2026and ${l.items.length-Cp} more`)),o.push("")}let i=NA(n);if(i.length>0){for(let l of i)o.push(` ${l}`);o.push("")}let a=n.rows.filter(l=>l.localAhead).length;return a>0&&o.push(m(` ${a} changed here \u2014 /push saves ${a===1?"it":"them"} to Document360 as ${a===1?"a draft":"drafts"}. Readers see nothing until then.`)),n.draftPending.length>0&&o.push(m(` ${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(...Vy(n)),!t.all&&n.rows.length>0&&o.push(m(" /status --all shows every article, gate by gate.")),o.push(""),o.push(m(" Free \u2014 /status reads your local files and the last sync. It calls nothing.")),o}function Vy(e){let t=e.orphans.length;return[m(` ${t} article${t===1?"":"s"} on Document360 ${t===1?"is":"are"} not in your docs folder (${Je(e.orphans[0].path,40)}${t>1?`, +${t-1} more`:""}) \u2014 /doctor lists ${t===1?"it":"them"}.`)]}async function Yy(e,t){let n=e.some(o=>o==="--all"||o==="--full");for(let o of Pp(t.cwd,{profileName:t.profileName,all:n}))console.log(o);return{kind:"continue",ownNext:!0}}se();import{computeReadiness as IA,retireArticle as LA,retiredPaths as OA,normalizeScope as _A}from"document360-engine";import{select as MA}from"@inquirer/prompts";function Tp(e,t){let n=IA(e,t),o=OA(e,t),r=[Z("Take an article off your readers"),""];if(n.orphans.length>0){r.push(` ${J("\u25CB",m)}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(m(` ${Je(s.path)}`));n.orphans.length>8&&r.push(m(` \u2026and ${n.orphans.length-8} more`)),r.push("")}if(o.length>0){r.push(` ${J("\u2713",m)}Already retired \u2014 readers do not see ${o.length===1?"it":"these"}:`);for(let s of o.slice(0,5))r.push(m(` ${Je(s)}`));o.length>5&&r.push(m(` \u2026and ${o.length-5} more`)),r.push("")}return n.orphans.length===0&&o.length===0&&(r.push(m(" Nothing obvious to retire \u2014 every tracked article is still in your docs folder.")),r.push("")),r.push(m(" /retire <path> takes one off your readers. Any tracked article can be named, not just these.")),r.push(m(" Nothing is deleted: the article, its history and every reviewer comment stay on Document360.")),r.push(m(" /push puts one back \u2014 reviving is a publish like any other, with the same review.")),r}async function Ky(e,t){let n=t.cwd,o=e.find(a=>!a.startsWith("-"));if(!o){for(let a of Tp(n,t.profileName))console.log(a);return{kind:"continue",ownNext:!0}}let r=_A(n,o)||o;if(!(e.includes("--yes")||e.includes("-y"))&&(console.log(""),console.log(G(`This takes "${Je(r)}" off your readers on Document360.`)),console.log(m(" The article, its history and every reviewer comment stay \u2014 nothing is deleted.")),console.log(m(" /push puts it back later if you change your mind.")),console.log(""),await MA({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(m("Nothing changed.")),{kind:"continue",ownNext:!0};let i=await LA({cwd:n,path:r,profileName:t.profileName,now:new Date().toISOString()});return i.ok?(console.log(i.alreadyHidden?`${J("\u2713")}"${Je(r)}" was already invisible to readers. Recorded as retired, so nothing will offer to publish it again.`:`${J("\u2713")}"${Je(r)}" is no longer visible to your readers.`),console.log(m(" It is still on Document360 with its history and comments intact. /push puts it back.")),{kind:"continue",ownNext:!0}):(console.log(_(`${J("\u2717")}Could not retire "${Je(r)}" \u2014 ${i.error.message}`)),{kind:"continue",ownNext:!0})}se();import{scanTerminology as zy,approvalBlockedReason as Xy,readProjectConfig as FA,writeProjectConfig as UA,termKey as Ap,HEAD_NOUN_CAP as WA}from"document360-engine";import Yt from"picocolors";var BA=3,HA=e=>e.uses.map(t=>`${Yt.bold(t.form)} ${m(`${t.files.length} article${t.files.length===1?"":"s"}`)}`).join(m(" \xB7 "));function Ep(e,t={}){let n=zy(e,t.scope?{scope:t.scope}:{}),o=[];if(n.scanned===0)return[Z("Terminology"),"",`${J("\u25CB",m)}No articles to read yet.`,""];let r=n.variance.length+n.headings.length;if(o.push(Z("Terminology")+m(` ${n.scanned} article${n.scanned===1?"":"s"} read \xB7 ${r===0?"nothing inconsistent":`${r} to look at`}`)),o.push(""),n.variance.length>0){o.push(` ${J("\u2717",Yt.red)}The same term, spelled more than one way`);for(let s of n.variance){o.push(` ${HA(s)}`);let i=s.uses[s.uses.length-1],a=i.files.slice(0,BA);o.push(m(` "${i.form}" is in ${a.map(d=>Je(d,40)).join(", ")}${i.files.length>a.length?`, +${i.files.length-a.length} more`:""}`));let l=Xy(s);l?o.push(m(` ${l}`)):o.push(m(` /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,WA);o.push(` ${J("\u25CB",m)}Possibly the same thing under a short name \u2014 ${Yt.italic("your call")}`);for(let i of s)o.push(m(` ${i.uses.map(a=>a.form).join(" \xB7 ")}`));n.headNouns.length>s.length&&o.push(m(` \u2026and ${n.headNouns.length-s.length} more \u2014 /terms --all lists them`)),o.push(m(' A shared word is not proof of a shared meaning: "billing history" and "history" are')),o.push(m(" different things. Nothing is flagged as wrong here.")),o.push("")}if(n.headings.length>0){o.push(` ${J("\u26A0",Yt.yellow)}Titles out of step with the rest of their kind`);for(let s of n.headings)o.push(` ${Yt.bold(s.title)} ${m(`\u2014 ${Je(s.path,40)}`)}`),o.push(m(` the other ${s.peers} ${s.type} article${s.peers===1?"":"s"} look like "${s.example}"; this one starts ${GA(s.shape)}`));o.push("")}return r===0&&n.headNouns.length===0&&(o.push(` ${J("\u2713",Yt.green)}Every term is spelled one way, and every title matches its kind.`),o.push("")),o.push(m(' This compares spellings, not meanings: two different words for one thing (say "nav" and')),o.push(m(' "rail") look unrelated to it. Add the pair to your approved terms and every run enforces it.')),o.push(m(" Free \u2014 this read your articles and called nothing.")),o}function GA(e){return e==="gerund"?"with an -ing word":e==="how-to"?'with "How to"':"differently"}function Dp(e,t,n){let o=n??zy(e),r=Ap(t),s=o.variance.find(g=>g.uses.some($=>Ap($.form)===r));if(!s)return{wrote:!1,lines:[`${J("\u2717",Yt.red)}"${t}" is not one of the terms with competing spellings. /terms lists them.`]};let i=Xy(s);if(i)return{wrote:!1,lines:[`${J("\u2717",Yt.red)}That one cannot be recorded: ${i}.`,m(` The spellings in play are ${s.uses.map(g=>`"${g.form}"`).join(" and ")}.`)]};let a=s.uses.find(g=>Ap(g.form)===r).form,l=s.uses.filter(g=>g.form!==a).map(g=>g.form),d=FA(e);if(!d)return{wrote:!1,lines:[`${J("\u2717",Yt.red)}No project configuration here \u2014 run /init first.`]};let w={...d.terminologyGlossary??{}};for(let g of l)w[g]=a;return UA({...d,terminologyGlossary:w},e),{wrote:!0,lines:[`${J("\u2713",Yt.green)}"${a}" is now the approved spelling.`,m(` Added to your approved terms: ${l.map(g=>`"${g}" \u2192 "${a}"`).join(", ")}`),m(" Every run enforces it from now on, and /lint --fix corrects the others for free.")]}}async function Qy(e,t){let n=e.findIndex(s=>s==="--approve");if(n!==-1){let s=e[n+1];if(!s)return console.log(`${J("\u2717",Yt.red)}Name the spelling to approve, e.g. /terms --approve "drop-down".`),{kind:"continue",ownNext:!0};for(let i of Dp(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 Ep(t.cwd,{...r?{scope:r}:{},all:o}))console.log(s);return{kind:"continue",ownNext:!0}}se();import{readProjectConfig as qA,writeProjectConfig as Jy,isAppType as VA,playbookSkillName as YA,detectAppType as Zy}from"document360-engine";var eb=["web","cli","service","library"],KA=new Set(["web","cli"]);function Np(e){return KA.has(e)?`${YA(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function ll(e,t){let n=t.cwd,o=qA(n);if(!o)return console.log(_("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let s=o.appType??Zy(n);if(s){let i=o.appType?"set in config":"auto-detected";console.log(`${Z("Genre:")} ${s} (${i}) \u2014 ${Np(s)}`)}else console.log(G("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(m(`Set it: /genre <${eb.join("|")}> \xB7 revert to auto-detect: /genre auto`)),{kind:"continue"}}if(r==="auto"||r==="clear"){if(!o.appType)return console.log(m("Already on auto-detect (no genre set in config).")),{kind:"continue"};let{appType:s,...i}=o;Jy(i,n);let a=Zy(n);return console.log(Y(`\u2713 Genre reset to auto-detect \u2014 now: ${a?`${a} (${Np(a)})`:"unclassified (no playbook)"}.`)),console.log(m(" Restarting the agent so the loaded playbook matches\u2026")),{kind:"clear"}}return VA(r)?(Jy({...o,appType:r},n),console.log(Y(`\u2713 Genre set to ${r} \u2014 ${Np(r)}.`)),console.log(m(" Restarting the agent so the playbook loads\u2026")),{kind:"clear"}):(console.log(_(`Unknown genre "${r}". Choose one of: ${eb.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}var tb={help:vc,"?":vc,clear:$f,exit:xc,quit:xc,init:Ec,mcp:Ki,push:ba,publish:sg,audit:(e,t)=>Ss({cwd:t.cwd,profileName:t.profileName}),discover:lg,scope:ug,pull:Rg,resolve:$g,convert:Wg,write:nw,draft:aw,document:lw,resume:dw,rename:pw,profile:fw,model:ww,doctor:Ms,logs:mf,workspace:vw,project:xw,"allow-prod":Rw,login:Sw,logout:Cw,screenshot:async(e,t)=>{let n=ys(e);return n.mode==="capture"?Ld(n.rest,t):n.mode==="annotate"?Ud(n.rest,t):n.mode==="verify"?Pw(n.rest,t):n.mode==="checklist"?Pr(e,t):da(e,t)},capture:Ld,annotate:Ud,"capture-setup":Pr,devhints:Df,inbox:Vw,ask:Kw,"catch-up":Zw,comments:sy,update:ay,reset:py,lint:td,check:Yg,"style-guide":sl,review:Gy,reorder:qy,structure:jy,status:Yy,retire:Ky,terms:Qy,genre:ll,roadmap:qm,share:Qw,auto:ag};function nb(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 zA}from"node:child_process";import{recordAnalyzedCommit as XA,resolveActiveProfile as QA}from"document360-engine";function JA(e){try{let t=zA("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 Zs(e,t){try{let n=JA(e);if(!n)return null;let o=QA(e,t);return XA(e,o.name,n)?n:null}catch{return null}}En();var ob="Or just tell me what to write or update.";function ZA(e,t,n={}){let o=n.onlyScreenshots?"\u2713 Your writing is done \u2014 nothing is waiting to be written, reviewed, saved or taken live. Readers are seeing every article you have.":"\u2713 That\u2019s the full round trip \u2014 nothing is waiting to be written, reviewed, saved or taken live. Readers are seeing every article you have.";return n.listed?o:`${o}
|
|
425
|
-
|
|
426
|
-
Optional from here: ${e} of your ${t} docs campaign step${ye(t)} ${e===1?"is":"are"} still open (/roadmap shows them).`}var
|
|
427
|
-
\u2022 `),lead:{kind:"cmd",cmd:"/catch-up",reason:r},picker:null,follow:"Then /catch-up clears what\u2019s queued for the docs.",dependsOn:["discovery"]})}if(e.openComments>0){let r=e.openComments;n.push({key:"comments",bullet:`${r} reviewer comment${ye(r)} waiting on your articles`,lead:{kind:"cmd",cmd:"/comments",reason:"it shows what reviewers marked up in the portal, then lets you take it an article at a time"},picker:null,follow:`Then /comments shows the ${r} reviewer comment${ye(r)} waiting on your articles.`})}if(e.conflicts>0){let r=e.conflicts;n.push({key:"resolve",bullet:`${r} article${ye(r)} changed both here and on Document360 \u2014 /push skips ${r===1?"it":"these"}, and an audit can't trust your local copy until ${r===1?"it is":"they are"} settled`,lead:{kind:"cmd",cmd:"/resolve",reason:"it walks each one with you \u2014 keep yours, take the portal's, or skip"},picker:null,follow:`Then /resolve settles the ${r} article${ye(r)} changed in both places (keep yours / take the portal's / skip).`})}if(e.behind>0){let r=e.behind;n.push({key:"audit",bullet:`${r} code change${ye(r)} since your last docs check`,lead:{kind:"cmd",cmd:"/audit",reason:"it shows what the latest code changes touch (or /audit --auto on to run it for you)"},picker:null,follow:`After that, /audit covers the ${r} newer commit${ye(r)}.`,blockedBy:["resolve"]})}if(e.hasDocs&&e.pendingWrites>0){let r=e.pendingWrites;n.push({key:"write",bullet:`${r} planned article${ye(r)} still unwritten`,lead:{kind:"cmd",cmd:"/write",reason:"it finishes the articles already planned"},picker:null,follow:`Then /write finishes the ${r} planned article${ye(r)}.`,dependsOn:["genre","discovery","catchup","audit"]})}if(e.unreviewed>0){let r=e.unreviewed,s=Re("/review","--blocked --fix",e.unreviewedScope);n.push({key:"review",bullet:`${r} article${ye(r)} not yet live ${r===1?"carries":"carry"} text no editor has read`,lead:{kind:"cmd",cmd:s,reason:"these were written by an AI \u2014 it reads each one and applies its fixes, and nothing can be sent up or taken live until it has"},picker:null,follow:`Then ${s} reviews the ${r} unreviewed article${ye(r)} \u2014 nothing reaches your readers until it has.`,dependsOn:["catchup","comments"]})}if(e.styleErrors>0){let r=e.styleErrors,s=Re("/lint","--blocked --fix",e.styleErrorScope);n.push({key:"styleguide",bullet:`${r} article${ye(r)} not yet live break${r===1?"s":""} house style rules that block publishing`,lead:{kind:"cmd",cmd:s,reason:"finding them costs nothing and one pass corrects them in place \u2014 nothing can be sent up or taken live until it has"},picker:null,follow:`Then ${s} clears the style errors on ${r} article${ye(r)} \u2014 nothing reaches your readers until it has.`,dependsOn:["catchup","comments","review"]})}let o=e.shotsToAnnotate>0?{key:"annotate",bullet:`${e.shotsToAnnotate} screenshot${ye(e.shotsToAnnotate)} ${e.shotsToAnnotate===1?"has":"have"} been taken but ${e.shotsToAnnotate===1?"is":"are"} not finished \u2014 the callouts aren't drawn on, so ${e.shotsToAnnotate===1?"it cannot":"they cannot"} be published`,lead:{kind:"cmd",cmd:"/screenshot annotate",reason:"it draws the callouts on \u2014 no browser, about a second per picture"},picker:null,follow:`Then /screenshot annotate finishes the ${e.shotsToAnnotate} screenshot${ye(e.shotsToAnnotate)} already taken.`}:e.shotsToRecapture>0?{key:"annotate",bullet:`${e.shotsToRecapture} screenshot${ye(e.shotsToRecapture)} ${e.shotsToRecapture===1?"has":"have"} a plan for what to point at but no picture \u2014 the picture has to be taken again before anything can be drawn on it`,lead:{kind:"cmd",cmd:"/screenshot capture",reason:"it takes the picture again in a browser, and the callouts are drawn on straight after"},picker:null,follow:`Then /screenshot capture re-takes the ${e.shotsToRecapture} missing picture${ye(e.shotsToRecapture)}.`}:null;if(o&&e.localAhead>0&&n.push(o),e.localAhead>0){let r=e.localAhead;n.push({key:"publish",bullet:`${r} article${ye(r)} changed locally \u2014 ready to send to Document360`,lead:{kind:"cmd",cmd:"/push",reason:`it saves your ${r} local edit${ye(r)} to Document360 as drafts`},picker:null,follow:`Then /push saves your ${r} local edit${ye(r)} to Document360.`,dependsOn:["discovery","comments","audit","annotate"],blockedBy:["review","styleguide"]})}if(e.draftAhead>0){let r=e.draftAhead;n.push({key:"golive",bullet:`${r} article${ye(r)} ${r===1?"is":"are"} saved on Document360 but not live \u2014 your readers still see the previous version`,lead:{kind:"cmd",cmd:"/publish",reason:`it takes the ${r} draft${ye(r)} live to your readers \u2014 it lists them and asks first`},picker:null,follow:`Then /publish takes the ${r} draft${ye(r)} live \u2014 until it does, readers see the previous version.`,dependsOn:["comments"],blockedBy:["review","styleguide"]})}if(o&&e.localAhead===0&&n.push(o),e.hasDocs&&e.roadmap?.next){let r=e.roadmap,s=r.next,i=s.run?t?.scaleFor?.(s.run)??null:null,a=s.run?i:
|
|
399
|
+
`)}function Wn(e){return`${J("\u2192",wt.blue)}Verifying ${e} new screenshot${e===1?"":"s"} (reading each image)\u2026`}var IC=(e,t=88)=>{let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n};function Cr(e,t){if(t.length===0)return[];let n=gn(e).shots,o=[],r=[],s=[];for(let a of t){let l=n[a]?.review;l?l.verdict==="ok"?o.push(a):r.push({id:a,reason:l.reason??"no reason recorded",repaired:!!l.repaired}):s.push(a)}let i=[""];if(i.push(`${J("\u2714",wt.green)}${wt.green(`${o.length} verified`)}`+(r.length>0?` ${wt.magenta(`\u2691 ${r.length} flagged`)}`:"")+(s.length>0?` ${wt.yellow(`? ${s.length} not verified`)}`:"")+wt.gray(` ${t.length} shot${t.length===1?"":"s"} in this pass`)),r.length>0){let a=Math.max(...r.map(d=>d.id.length));for(let d of r)i.push(` ${wt.magenta(d.id.padEnd(a))} ${wt.gray(IC(d.reason))}`);let l=r.filter(d=>d.repaired).length;i.push(`${J("\u2192",wt.magenta)}Re-capture the ${r.length} flagged: ${wt.bold("/screenshot capture --failed")}`+(l<r.length?wt.gray(` (${r.length-l} still need${r.length-l===1?"s":""} a spec fix first)`):""))}return s.length>0&&i.push(`${J("\u26A0",wt.yellow)}No verdict recorded for ${s.slice(0,3).join(", ")}${s.length>3?`, +${s.length-3}`:""} \u2014 still awaiting verification. Run ${wt.bold("/screenshot verify")} again.`),i}async function Ew(e,t){let n=t?.cwd??process.cwd(),o=mo(n);o&&console.log(o);let r=Fe(n),s=jC(e);if(s.mode==="single"){let a=r.find(l=>l.id===s.id);return a?a.state==="captured"?(console.log(`"${s.id}" has been taken but the callouts aren't drawn on yet \u2014 /screenshot annotate ${s.id} finishes it.`),{kind:"continue"}):["annotated","verified","rejected"].includes(a.state)?{kind:"forward-to-agent",prompt:on(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=Ws(r);if(i.length===0){let a=r.filter(w=>w.state==="verified").length,l=r.filter(w=>w.state==="rejected").length,d=r.filter(w=>w.state==="captured").length;return console.log(d>0?`${d} shot${d===1?" is":"s are"} taken but not drawn on yet \u2014 /screenshot annotate finishes ${d===1?"it":"them"}, then there'll be something to verify.`:l>0?`Nothing left to verify. ${l} shot${l===1?"":"s"} failed verification \u2014 re-capture with: /screenshot capture --failed`:a>0?`All ${a} captured shot${a===1?" is":"s are"} already verified.`:"No captured screenshots to verify yet \u2014 /screenshot capture takes the shots first."),{kind:"continue"}}return{kind:"forward-to-agent",prompt:on(n,i),display:"/screenshot verify"}}import{spawn as Dw}from"node:child_process";var Td="d360-capture";function LC(e,t){if(t&&typeof e.pid=="number")try{process.kill(-e.pid,"SIGTERM");return}catch{}try{e.kill()}catch{}}function Bs(e){let t=process.platform==="win32",n=!t&&e.stdio==="pipe";return new Promise((o,r)=>{let s=t?Dw(`${Td} ${e.args.join(" ")}`,{cwd:e.cwd,shell:!0,stdio:e.stdio==="inherit"?"inherit":["ignore","pipe","pipe"],env:{...process.env,NO_UPDATE_NOTIFIER:"1"}}):Dw(Td,e.args,{cwd:e.cwd,shell:!1,detached:e.stdio==="pipe",stdio:e.stdio==="inherit"?"inherit":["ignore","pipe","pipe"],env:{...process.env,NO_UPDATE_NOTIFIER:"1"}}),i="";e.stdio==="pipe"&&(s.stdout?.on("data",l=>{i+=l.toString()}),s.stderr?.on("data",l=>{i+=l.toString()}));let a=()=>LC(s,n);e.signal?.addEventListener("abort",a,{once:!0}),s.on("error",l=>{if(e.signal?.removeEventListener("abort",a),l.code==="ENOENT"){o({exitCode:127,output:`${i}
|
|
400
|
+
${Td}: command not found`.trim()});return}r(l)}),s.on("close",l=>{e.signal?.removeEventListener("abort",a),o({exitCode:l??1,output:i})})})}var BC=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Ed(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:BC(t),retryBlocked:n}:{mode:"single",id:t}:{mode:"picker"}}function qs(e,t){let n=Fe(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 jw(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"),ru(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 Dd(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([...nm(e).filter(r=>n.has(r)),...o])].sort()}function Nd(e,t){let n=e.length;if(n===0)return null;let o=vs(e).length;return[`\u2298 ${n} shot${n===1?"":"s"} excluded \u2014 ${n===1?"its data prerequisite wasn't":"their data prerequisites weren't"} met last run. Stage the data, then:`,` ${t}`,` /screenshot list shows what to stage (${o} action${o===1?"":"s"}).`].join(`
|
|
401
|
+
`)}function HC(e,t){let n=MC(e)?.outputDir??FC;return WC(UC(e,n),t)}function jd(e,t,n,o){let r=HC(e,t);return(r.annotationsMtimeMs??0)>=o&&r.rawMtimeMs!==void 0?"captured":n===0?"skipped":"failed"}function Iw(e){let t=/⊘[^\n—]*—\s*(.+)/.exec(e);return t?t[1].trim():null}var GC=/element is not (?:enabled|visible|stable|editable)|intercepts pointer events|outside of the viewport|element is not attached/i;function Lw(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=>GC.test(s)).map(s=>s.replace(/^-\s*/,"")))].slice(0,2),r=t.find(s=>/locator resolved to/i.test(s))?.replace(/^-\s*/,"");return n.length>0||o.length>0?[...new Set([...n].slice(0,2)),...o,...r&&o.length>0?[r.length>120?`${r.slice(0,119)}\u2026`:r]:[]].join(`
|
|
402
|
+
`):Id(e)}function Id(e,t=4){let n=/captured\s+·|^▶ Annotating|^✓ \d+ captured|^\s*[⊘✗]\s+\S+\s*$|^▶ Running \d+ spec/;return e.split(/\r?\n/).map(r=>r.trimEnd()).filter(r=>r.trim().length>0&&!n.test(r.trim())).slice(-t).join(`
|
|
403
|
+
`)}var qC=/^[A-Za-z0-9._-]+$/;function Ld(e){return qC.test(e.id)?Bs({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 Ow(e,t=OC()){try{let n=JSON.parse(Ad(Hs(e,".d360-writer","capture.json"),"utf8").replace(/^/,"")),o=n.projectId;if(!o)try{o=JSON.parse(Ad(Hs(e,"package.json"),"utf8")).name}catch{}o||=_C(e);let r=Object.keys(n.profiles??{}),s=n.defaultProfile??(r.length===1?r[0]:r.includes("staging")?"staging":r[0]);return s?Nw(Hs(t,".document360-capture","auth-states",o,`${s}.json`)):!0}catch{return!0}}function _w(e){return Bs({args:["auth","--auto"],cwd:e.cwd,stdio:"pipe",signal:e.signal})}function Od(e,t){return e===127||/is not recognized as an internal or external command|command not found/i.test(t)}function Mw(e){try{let t=JSON.parse(Ad(Hs(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 vo(e){return Nw(Hs(e,".d360-writer","capture.json"))}function _d(){return["Screenshot capture is not configured in this repo yet (no `.d360-writer/capture.json`). Set it up","conversationally, and never tell the user to run `d360-capture init`:","","1. Find the live app URL yourself first: `.d360-writer/config.json` `appUrl`, the product brief, the"," architecture brief, the repo (README, deploy config). Present what you found for confirmation, or"," ask for it if unknown. In the SAME message also ask: (a) is that URL the production environment?"," (b) which prepared demo context should screenshots enter: the capture scope (read the product"," source to know what this product scopes by: project / workspace / org; a single-context product"," needs none). One short numbered message, then END YOUR TURN and wait for the answers.","2. On the answers, write `.d360-writer/capture.json` in exactly this shape (fill the values):","```json","{",' "projectId": "<projectId from .d360-writer/config.json>",',' "profiles": {',' "<production or staging, matching their answer>": {',' "connection": { "startUrl": "<the app URL>" },',' "production": <true when they said production>,',' "scope": { "<scopeKey>": "<their demo context>" }'," }"," },",' "defaultProfile": "<the same profile name>"',"}","```"," Omit `scope` for a single-context product. Do not add captureDir/outputDir (defaults apply).","3. Also record the app URL as `appUrl` in `.d360-writer/config.json`, adding/updating just that key,",' preserving everything else. It is the canonical "where the product lives" fact (you may use it to'," deep-link stable app screens from articles).","4. Close with the ONE remaining external step, then the retry:"," `d360-capture auth` (run in this repo's terminal; first time also `npm i -g document360-capture`)"," then `/screenshot capture`."].join(`
|
|
404
|
+
`)}function Fw(e,t){let n=e.filter(i=>i.state==="blocked"&&i.blockedBy!=="testid").length,o=e.filter(i=>i.state==="blocked"&&i.blockedBy==="testid").length,r=t+n+o;if(r===0)return null;let s=[];return t>0&&s.push(`${t} write${t===1?"s":""} real data`),n>0&&s.push(`${n} blocked on data`),o>0&&s.push(`${o} wait${o===1?"s":""} on a developer`),` ${r} held back \u2014 ${s.join(", ")}
|
|
405
|
+
/screenshot list --detail shows what each one needs`}function Uw(e,t){let n={newlyCaptured:[],newlyBlocked:[],stillBroken:[],newlyBroken:[],brokeDifferently:[],repairedNowBlocked:[],blockedAsBefore:[],blockedNewReason:[]};for(let o of t){let r=e.shots[o.id],s=r?.outcome;o.outcome==="captured"&&s!=="captured"?n.newlyCaptured.push(o.id):o.outcome==="failed"?s!=="failed"?n.newlyBroken.push(o.id):Gs(r?.reason)!==Gs(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):da(r?.reason??"")!==da(o.detail??"")?n.blockedNewReason.push(o.id):n.blockedAsBefore.push(o.id))}return n}function Gs(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 Ww(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?hr(o.detail):"no reason recorded"}`)}function Pr(e,t=2){return e.length<=t?e.join(" \xB7 "):`${e.slice(0,t).join(" \xB7 ")} \xB7 +${e.length-t}`}function Bw(e,t){if(!t)return[];let n=[],o=(i,a,l,d)=>{a>0&&n.push({glyph:i,label:`${a} ${l}`,tail:d})};if(o("\u2713",e.newlyCaptured.length,"newly captured",Pr(e.newlyCaptured)),o("\u2717",e.newlyBroken.length,"newly broken",Pr(e.newlyBroken)),o("\u2192",e.repairedNowBlocked.length,"repaired",`no longer broken \u2014 only data stands in the way \xB7 ${Pr(e.repairedNowBlocked)}`),o("\u2298",e.newlyBlocked.length,"newly blocked",Pr(e.newlyBlocked)),o("\u2192",e.blockedNewReason.length,"blocked on something new",`an earlier step now passes \xB7 ${Pr(e.blockedNewReason)}`),o("\u2192",e.brokeDifferently.length,"broken differently",`the previous cause is fixed \xB7 ${Pr(e.brokeDifferently)}`),o("\u2717",e.stillBroken.length,"still broken","same error \u2014 these need re-authoring"),o("\xB7",e.blockedAsBefore.length,"blocked as before","nothing staged since last time"),n.length===0)return[];let r=Math.max(...n.map(i=>i.label.length));return[""," Since your last run",...n.map(i=>` ${i.glyph} ${i.label.padEnd(r)} ${i.tail}`)]}function Hw(e){let t=e.results.filter(P=>P.outcome==="captured"),n=e.results.filter(P=>P.outcome==="skipped"),o=e.results.filter(P=>P.outcome==="failed"),r=e.unannotated??[],s=P=>P===1?"":"s";if(t.length+n.length+o.length===0)return null;let i=e.articles.length===1?`/push ${e.articles[0]}`:Re("/push","--screenshots",Zt(e.articles)),a=e.ids.length===1?`/screenshot capture ${e.ids[0]}`:"/screenshot capture",l=o[0]?.id,d=[];o.length>0&&d.push({glyph:"\u2717",cmd:`/screenshot ${l}`,why:`re-author the ${o.length===1?"broken spec":`first of ${o.length} broken specs`} \u2014 re-running fails the same way`});let w=Re("/screenshot annotate","",r.length===1?r[0]:void 0);r.length>0&&d.push({glyph:"\u25C8",cmd:w,why:`draw the callouts on ${r.length} shot${s(r.length)} \u2014 no browser, seconds; ${r.length===1?"it cannot":"they cannot"} publish until drawn`}),n.length>0&&d.push({glyph:"\u2298",cmd:"/screenshot list",why:`what to stage for the ${n.length} blocked shot${s(n.length)}`}),t.length>0&&r.length<t.length&&d.push({glyph:"\u2713",cmd:i,why:`embed the ${t.length-r.length} new PNG${s(t.length-r.length)}`});let g=Math.max(...d.map(P=>P.cmd.length));return{note:d.map(P=>`${P.glyph} ${P.cmd.padEnd(g)} ${P.why}`).join(`
|
|
406
|
+
`),cmd:o.length>0?`/screenshot ${l}`:r.length>0?w:t.length>0?i:a,tone:o.length>0||r.length>0?"warn":"info"}}function Gw(e,t){let n=new Map(Fe(e).map(o=>[o.id,o.file]));return[...new Set(t.map(o=>n.get(o)).filter(o=>!!o))].sort()}async function Md(e,t){let n=t?.cwd??process.cwd(),o=Ed(e);if(!vo(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}=qs(n,o.mode==="scope"?o.scope:void 0),l=Dd(n,a),d=(o.mode==="all"||o.mode==="scope")&&o.retryBlocked,w=o.mode==="single"?[o.id]:o.mode==="failed"?l:o.mode==="blocked"?i:o.mode==="picker"?r:[...r,...s,...d?i:[]];if(w.length===0)return o.mode==="failed"?console.log("No broken specs to re-run \u2014 /screenshot list shows where things stand."):o.mode==="blocked"?console.log("No shots are waiting on app data \u2014 /screenshot list shows where things stand."):console.log("No authored specs to capture yet \u2014 author them first: /screenshot"),{kind:"continue"};if(!d&&o.mode!=="single"&&o.mode!=="failed"&&o.mode!=="blocked"){let R=Nd(a.filter(T=>T.state==="blocked"),"/screenshot capture --blocked");R&&console.log(R)}let g=Date.now(),$=[];for(let R of w){console.log(`\u25B6 ${R}`);try{let{exitCode:T}=await Ld({cwd:n,id:R,stdio:"inherit"});$.push({id:R,outcome:jd(n,R,T,g)})}catch(T){if(T.code==="ENOENT")return console.log("d360-capture is not installed. Run: npm i -g document360-capture"),{kind:"continue"};$.push({id:R,outcome:"failed",detail:T.message})}}let P=R=>$.filter(T=>T.outcome===R).length;console.log(`\u2713 ${P("captured")} captured \xB7 \u2298 ${P("skipped")} skipped \xB7 \u2717 ${P("failed")} failed`);let C=$.filter(R=>R.outcome==="captured");return ta(n,$.map(R=>({id:R.id,outcome:R.outcome,reason:R.detail,specSource:go(n,R.id)})),new Date().toISOString()),C.length>0?(console.log(Wn(C.length)),{kind:"forward-to-agent",prompt:on(n,C.map(R=>R.id)),display:"/screenshot verify"}):{kind:"continue"}}import{readProjectConfig as VC,DEFAULT_OUTPUT_DIR as YC,resolveOutputDir as KC,shotArtifacts as zC,annotationCurrent as XC}from"document360-engine";ur();var qw="0.2.29";function Va(e=mt()){return dr(e,qw)}function Fd(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 Ud(e,t){let n=Fe(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 QC=/^[A-Za-z0-9._-]+$/;function JC(e){if(!QC.test(e.id))return Promise.reject(new Error(`Not a valid spec id: "${e.id}"`));let t=["annotate",e.id,...e.force?["--force"]:[]];return Bs({args:t,cwd:e.cwd,stdio:e.stdio,signal:e.signal})}function ZC(e,t,n,o){let r=KC(e,VC(e)?.outputDir??YC),s=zC(r,t);return(s.annotatedMtimeMs??0)>=o?"annotated":n===0&&XC(s)?"skipped":"failed"}function Wd(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 ${qw} or later, then /screenshot annotate becomes available.`}var Ya=8;function Vw(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:Re("/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>Ya?{glyph:"\u25C8",cmd:Re("/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:Re("/screenshot verify","",e.scope),why:`${n.length} picture${n.length===1?"":"s"} ready to check \u2014 no browser needed`}}async function Bd(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 JC({cwd:e.cwd,id:o,...e.force?{force:!0}:{},...e.signal?{signal:e.signal}:{},stdio:"pipe"}),i=ZC(e.cwd,o,r,t);n.push({id:o,outcome:i,...i==="failed"?{detail:eP(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 Hd(e,t){let n=t?.cwd??process.cwd(),o=Fd(e);if(!vo(n))return console.log("Screenshot capture is not set up in this repo yet. Run: d360-capture init"),{kind:"continue"};let r=mt();if(!Va(r))return console.log(Wd(r)),{kind:"continue"};let s=mo(n);s&&console.log(s);let i=o.mode==="scope"?o.scope:void 0,{pending:a,done:l,rows:d}=Ud(n,i),w=o.mode==="all"||o.mode==="scope"?o.force:!1,g=o.mode==="single"?[o.id]:w?[...a,...l]:a;if(g.length===0){let B=l.length>0;return console.log(B?`Every shot${i?` under ${i}`:""} is already drawn. Re-draw them anyway: /screenshot annotate --all --force`:"No shots have been taken yet \u2014 /screenshot capture takes them first."),{kind:"continue"}}let $=new Set(d.filter(B=>B.state==="verified").map(B=>B.id)),{results:P,cliMissing:C}=await Bd({cwd:n,ids:g,force:w});if(C)return console.log("d360-capture is not installed. Run: npm i -g document360-capture"),{kind:"continue"};let R=B=>P.filter(I=>I.outcome===B).length;console.log(`\u2713 ${R("annotated")} annotated`+(R("skipped")?` \xB7 ${R("skipped")} already current`:"")+(R("failed")?` \xB7 \u2717 ${R("failed")} failed`:""));for(let B of P.filter(I=>I.outcome==="failed"))console.log(` \u2717 ${B.id}${B.detail?` \u2014 ${B.detail}`:""}`);let T=P.filter(B=>B.outcome==="annotated").map(B=>B.id);if(T.length===0)return{kind:"continue"};let D=T.filter(B=>$.has(B)).length;if(D>Ya)return console.log(`\u26A0 ${D} verified shots were re-drawn, so their verdicts no longer describe the picture on disk.
|
|
407
|
+
Check them when you're ready: ${Re("/screenshot verify","",i)}`),{kind:"continue"};let N=T.filter(B=>!$.has(B)||D>0);return N.length===0?{kind:"continue"}:(console.log(Wn(N.length)),{kind:"forward-to-agent",prompt:on(n,N),display:"/screenshot verify"})}function eP(e){return e.split(/\r?\n/).map(n=>n.trim()).filter(n=>n.length>0&&!/^[▶✓↕]/.test(n)).at(-1)}se();import{existsSync as tP}from"node:fs";import{join as nP}from"node:path";import{builderChannelWired as oP,driftedAnchors as rP,readTestidRequests as sP,testidHandoffPrompt as iP,testidRequestPaths as aP,writerDir as lP}from"document360-engine";async function Tr(e,t){let n=t?.cwd;if(n){let r=cP(n);if(r){for(let s of r)console.log(s);return{kind:"continue",ownNext:!0}}}return{kind:"forward-to-agent",prompt:["Run the capture-setup-checklist skill.","","Scan every <!-- SCREENSHOT --> block across the docs tree (the configured docsDir), read each block\u2019s prerequisites,","anchor them to the capture scope keys in .d360-writer/capture.json, then synthesize a deduped, grouped","\u201Cstage this data\u201D checklist and write it to <captureDir>/CAPTURE-CHECKLIST.md. Separate transient/manual","states, flag any spec whose prerequisites are vague, and report the path when done.","","This run is also the RE-VERIFY pass for open selector requests: for every CAPTURE-TODO anchor, check the","snippet is still in its named file (an unrelated refactor can invalidate it with nobody touching the spec).","Where it is gone, re-locate the element and rewrite that CAPTURE-TODO with a current anchor and line.","or set anchorVerified:false when you cannot confirm it. /screenshot list --detail names the drifted ones."].join(`
|
|
408
|
+
`),display:"/screenshot checklist"}}function cP(e){let t;try{t=Fe(e)}catch{return null}let n=tP(nP(lP(e),"capture.json")),o=t.some(i=>i.state!=="placeholder");if(n||o)return null;let r=t.length,s=new Set(t.map(i=>i.file)).size;return r===0?[`${J("\u25CB",m)}No screenshots are planned yet, so there is nothing to stage.`,m(" A screenshot is planned by the article that needs it. /write adds the placeholders as it writes.")]:[`${J("\u25CB",m)}${r} screenshot${r===1?"":"s"} planned across ${s} article${s===1?"":"s"} \u2014 none captured, none with a spec, and no capture setup yet.`,m(" There is nothing to stage from yet: a checklist is built from what each spec needs, and no specs exist."),m(" /screenshot author writes the specs. Come back to /screenshot checklist once they exist and it will"),m(" tell you what data to stage and which test ids your developers still owe you."),"",m(" Free \u2014 this read your files and called nothing.")]}var Yw="-".repeat(64);function Kw(e){let t=sP(e);if(t.length===0)return null;let{mdRel:n}=aP(e),o=t.length,r=new Set(t.map(w=>w.file).filter(Boolean)).size,s=`${o} data-testid attribute${o===1?"":"s"}`,i=`${r} source file${r===1?"":"s"}`,a=iP(e,o),l=rP(t).length,d=l>0?[` \u26A0 ${l} of ${l===1?"them quotes":"them quote"} code that has changed since \u2014 still likely right,`,` but ${l===1?"it says":"they say"} so, and ${l===1?"asks":"ask"} to be found by description instead.`]:[];return oP(e)?{prompt:a,lines:[`\u{1F4CB} Developer hand-off \u2014 ${s} requested across ${i}.`,...d," Left in your builder's inbox: their coding agent is told about it at its next session, so",` there is nothing for you to relay. Detail: ${n}`]}:{prompt:a,lines:[`\u{1F4CB} Developer hand-off \u2014 ${s} requested across ${i}.`,...d,"\u26A0 Do NOT run this prompt here. d360-writer documents code; it does not change it \u2014"," these edits belong in your code repo. Open a SEPARATE terminal in:",` ${e}`," start Claude Code (or your coding agent), and paste everything between the lines."," Tip: run it in plan mode first \u2014 these are a hypothesis to verify, not a verified patch."," (Run /devhints once and requests like this reach your builder on their own.)","",Yw,a,Yw]}}Dn();se();import{listOpenForDocs as uP,readProjectConfig as dP}from"document360-engine";function Gd(e){try{return uP(e).length}catch{return 0}}function qd(){return["Process the two-way message inbox from the source repo's coding agent (the builder).","","1. Call d360_inbox to list the OPEN messages addressed to you.","2. For each message, act by its kind:",' \u2022 request ("document the X we shipped") \u2192 treat it as a session hand-off: run the document-handoff'," skill: read what changed, ground it in the cited sources + the architecture brief, then decide and"," apply the RIGHT doc action (new section, new article, update existing, or retire). No fixed shape.",' \u2022 answer to a [discovery]-tagged question (subject starts "[discovery] ") \u2192 this is product-discovery,'," not an article edit: fold the fact into `.d360-writer/product-brief.md` (updating the cited grounding,"," clearing the matching OPEN marker), then RE-RUN the discover-product readiness assessment, setting the"," brief's frontmatter status to `confident` and offer propose-structure if every rubric dimension now"," passes, else ask the next focused batch via d360_ask_builder. Do not touch articles for these.",' \u2022 answer to a [depth]-tagged question (subject starts "[depth] ") \u2192 this is per-feature depth-mining,'," not the brief and not an article edit: fold it into the DOCS PLAN per propose-structure's"," depth-reconcile: adjust that feature's article palette in plan.json/AGENT-PLAN.md (add rows citing"," the answer's .d360-writer/messages/ file in `sources`, never renumber existing rows), decrement"," open_depth_questions in AGENT-PLAN.md's frontmatter, and flip status to `pinned` at zero."," \u2022 answer (a reply to any other question you asked; `re` = your question id) \u2192 fold the fact into the"," affected article(s), and into `.d360-writer/architecture/` if it is durable product knowledge.","3. After acting on a message, mark it resolved: edit its file in `.d360-writer/messages/` and set the"," frontmatter `status: done` (add `done_at` with the current UTC time). Never delete the file.","4. Drafts only; do not publish unless explicitly asked. End with a one-line summary of what you did per"," message (and, for any request you could not fully ground, what you still need)."].join(`
|
|
409
|
+
`)}async function zw(e,t){let n=t?.cwd??process.cwd();return dP(n)?Gd(n)===0?(console.log(m("Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)")),{kind:"continue"}):{kind:"forward-to-agent",prompt:qd(),display:"/inbox"}:(console.log(_("No d360-writer config here. Run /init first.")),{kind:"continue"})}se();import{askBuilder as pP,openGapQuestions as Xw,readProjectConfig as hP}from"document360-engine";function Vs(e){try{return Xw(e).length}catch{return 0}}function Vd(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 Yd(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 Qw(e,t,n){let o=t?.cwd??process.cwd();if(!hP(o))return console.log(_("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e.join(" ").trim();if(r===""){for(let s of Yd(Xw(o)))console.log(s.startsWith(" \xB7")?m(s):s);return{kind:"continue",ownNext:!0}}try{let s=pP(o,{question:r,...n?{article:n}:{}}),i=Vs(o);for(let a of Vd(s.file,i))console.log(a.startsWith("\u2713")?Y(a):m(a))}catch(s){console.log(V(`Could not file the question: ${s.message}`))}return{kind:"continue",ownNext:!0}}se();import{listOpenHints as kP,listOpenForDocs as $P,listOpenDirectives as vP,readProjectConfig as ty,computeSyncStatus as xP,planPull as RP,applyPull as SP,planImport as CP,applyImport as PP,pullDocsUpdates as TP,handoffAvailable as AP,readProductBriefState as EP,readDiscoveryQueue as DP}from"document360-engine";se();import{readProjectConfig as fP,writeProjectConfig as Jw,reconcileDocsGit as mP,pullDocsUpdates as gP,probeGitState as wP,resolveGitHandoff as Zw,handoffAvailable as yP}from"document360-engine";var Ys=e=>e===1?"":"s";function Bn(e,t){let n=o=>{let r=(o??"").split(`
|
|
410
|
+
`).map(s=>s.trim()).filter(Boolean).slice(-1)[0];return r?` \u2014 ${r}`:""};switch(e){case"no-git":return"This folder is not a git repository, so there is nowhere to share to. Your docs are still saved on this machine.";case"detached-head":return"This repo is not on a branch right now. Ask your builder to check out a branch, then run /share.";case"mid-operation":return"A merge or rebase is in progress here. Finish or cancel it first, then run /share.";case"no-upstream":return"This branch has no remote yet, so there is nowhere to send your work. Ask your builder to run: git push -u origin HEAD";case"disabled":return"Sharing is switched off for this repo. Turn it on: /share on";case"diverged":return"Your work and your builder's have both moved on, so they can't be combined automatically. Your work is committed and safe \u2014 ask your builder to merge the branch.";case"rejected":return"Someone pushed to this branch first, so your work could not be sent. It IS committed and safe \u2014 try /share again in a moment, or ask your builder to merge the branch.";case"auth":return"Git could not sign in to the remote. Ask your builder to set up your git credentials, then run /share.";case"network":return"Could not reach the remote. Check your connection, then run /share again.";case"hook-failed":return`This repo's own commit checks rejected the change${n(t)}. Ask your builder to take a look \u2014 your docs are safe on this machine.`;case"failed":return`Git could not finish the share${n(t)}. Your docs are safe on this machine \u2014 run /share to try again, or show this line to your builder.`}}function Ka(e,t){let n=Zw(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=wP(e);if(!o)return[{tone:"info",text:"Sharing: unavailable \u2014 this folder is not a git repository."}];if(!o.upstream)return[{tone:"warn",text:J("\u26A0")+`This branch (${o.branch??"detached"}) has no remote, so your work can't reach your team yet.`},{tone:"info",text:"Ask your builder to run: git push -u origin HEAD"}];let r=n.push===!0?"on":n.push==="unconfirmed"?"not set up yet":"off",s=[{tone:"info",text:`Sharing: ${o.branch} \u2192 ${o.upstream} \xB7 saving: on \xB7 sending: ${r}`}];return o.ahead>0?s.push({tone:"warn",text:J("\u26A0")+`${o.ahead} change${Ys(o.ahead)} not shared yet \u2014 run /share`}):s.push({tone:"ok",text:J("\u2713")+"Everything is shared with your team."}),s}function Kd(e,t,n){Jw({...t,gitHandoff:{commit:n,push:n}},e);let o=n?{tone:"ok",text:J("\u2713")+"Sharing on \u2014 d360-writer will save and send its own work from now on."}:{tone:"ok",text:J("\u2713")+"Sharing off \u2014 d360-writer will leave its work for your coding agent to commit."};return n?[o,...Ka(e,{...t,gitHandoff:{commit:!0,push:!0}})]:[o]}async function za(e,t){let n=[],o=Zw(t);if(!o.commit)return{lines:[{tone:"info",text:Bn("disabled")}],changed:!1};let r=t;o.push==="unconfirmed"&&yP(e,t)&&(r={...t,gitHandoff:{commit:!0,push:!0}},Jw(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 gP(e);if(s.ok&&s.pulled>0){let d=[s.newHints>0?`${s.newHints} new hint${Ys(s.newHints)}`:null,s.newMessages>0?`${s.newMessages} new message${Ys(s.newMessages)}`:null].filter(Boolean);n.push({tone:"ok",text:J("\u2B07")+`Got your builder's latest${d.length?` \u2014 ${d.join(", ")}`:""}.`})}else!s.ok&&s.reason!=="no-upstream"&&s.reason!=="no-git"&&n.push({tone:"warn",text:J("\u26A0")+Bn(s.reason,s.detail)});let i=await mP(e,r);if(i.commit&&!i.commit.ok)return n.push({tone:"warn",text:J("\u26A0")+Bn(i.commit.reason,i.commit.detail)}),{lines:n,changed:!1};let a=i.commit?.ok?i.commit.committed.length:0;if(a>0&&n.push({tone:"ok",text:J("\u2713")+`Saved ${a} change${Ys(a)} to the docs folder.`}),i.push&&!i.push.ok)return n.push({tone:"warn",text:J("\u26A0")+Bn(i.push.reason,i.push.detail)}),{lines:n,changed:a>0};let l=i.push?.ok?i.push.pushed:0;return l>0?n.push({tone:"ok",text:J("\u2B06")+`Shared ${l} change set${Ys(l)} with your team.`}):a===0&&(s.ok&&s.pulled===0)?n.push({tone:"ok",text:J("\u2713")+"Everything is already shared with your team."}):a>0&&!i.push&&n.push({tone:"info",text:"Saved on this machine only. /share on lets d360-writer send it to your team too."}),{lines:n,changed:a>0||l>0||s.ok&&s.pulled>0}}var bP={ok:Y,info:xe,warn:V,error:_};async function ey(e,t){let n=t.cwd,o=fP(n);if(!o)return console.log(_("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase(),s=a=>{for(let l of a)console.log(bP[l.tone](l.text))};if(r==="status")return s(Ka(n,o)),{kind:"continue"};if(r==="on"||r==="off")return s(Kd(n,o,r==="on")),{kind:"continue"};if(r)return console.log(_(`Unknown option "${r}". Use /share, /share status, /share on, or /share off.`)),{kind:"continue"};console.log(m("Exchanging work with your team\u2026"));let{lines:i}=await za(n,o);return s(i),{kind:"continue"}}function $n(e){let t=0,n=0,o=0,r=0;try{t=kP(e).length}catch{}try{let s=$P(e);n=s.filter(i=>i.kind==="request").length,o=s.filter(i=>i.kind==="answer").length}catch{}try{r=vP(e).length}catch{}return{hints:t,requests:n,answers:o,directives:r}}async function Xd(e){let t=ty(e);if(!t)return[];if(!AP(e,t))return[];let n=await TP(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 ${Bn(n.reason,n.detail)}`}]}function Xa(e){let t=[];return e.hints&&t.push(`${e.hints} hint${e.hints===1?"":"s"}`),e.requests&&t.push(`${e.requests} request${e.requests===1?"":"s"}`),e.answers&&t.push(`${e.answers} answer${e.answers===1?"":"s"}`),e.directives&&t.push(`${e.directives} directive${e.directives===1?"":"s"}`),t.length?t.join(", "):null}function Qd(e){let t=Xa(e);return t?`Catching up on ${t}\u2026`:"Nothing queued from your builder \u2014 checking Document360 for reviewer comments and feedback\u2026"}function Qa(e){let t=Xa(e.queued);return t?{tone:"warn",note:`${J("\u26A0")}That run finished without writing anything, and ${t} ${e.queued.hints+e.queued.requests+e.queued.answers+e.queued.directives===1?"is":"are"} still queued \u2014 nothing was lost.`,lead:{cmd:"/catch-up",reason:"the queue is untouched, so running it again picks up the same work"}}:e.hold?{tone:"info",note:`${J("\u2139")}No articles changed \u2014 product discovery is still open, so new overview and concept pages are on hold.`,lead:null}:{tone:"info",note:`${J("\u2713")}Nothing needed writing \u2014 no articles changed.`,lead:null}}function Jd(e){return{push:e.includes("--push")||e.includes("--publish"),skipReview:e.includes(At)}}function Ks(e){let t={hold:!1,openQuestions:0,answersPending:0};try{let n=EP(e);return!n||n.status==="confident"?t:{hold:!0,...DP(e)}}catch{return t}}function Zd(e){if(!e.hold)return[];let t="I'll update the reference pages, and hold new overview and concept pages";if(e.answersPending>0){let n=e.answersPending;return[{tone:"info",text:`${J("\u2139")}Product discovery is still open \u2014 ${n} answer${Ar(n)} just arrived from your builder.`},{tone:"info",text:` I'll fold ${n===1?"it":"those"} in first; if that settles the brief, everything gets written as normal.`}]}if(e.openQuestions>0){let n=e.openQuestions;return[{tone:"warn",text:`${J("\u26A0")}Product discovery isn't finished \u2014 ${n} question${Ar(n)} still with your builder.`},{tone:"warn",text:` ${t} until the brief is settled.`}]}return[{tone:"warn",text:`${J("\u26A0")}Product discovery isn't finished \u2014 the product brief is still a draft.`},{tone:"warn",text:` ${t} until it's settled (/discover continues it).`}]}function ep(e={hold:!1,openQuestions:0,answersPending:0}){let t=["Catch the documentation up: process ALL the pending work the builder has queued, end to end.","","1. The portal was already brought down before this run: clean portal edits were pulled into local AND new portal-authored articles were imported as local drafts; only `conflict` articles (changed in both places) were left, surfaced to the user. Do NOT re-pull or re-import. Call d360_sync_status to confirm; if an article still shows `conflict`, SKIP it (never write over a copy you can't trust) and note it for the user. Otherwise proceed.",`2. Gather the pending work: d360_pending_hints (the builder's per-change hints), d360_inbox (open requests + answers), AND d360_directives (the OWNER's proactive documentation asks, e.g. "write a detailed /review page", in .d360-writer/directives.md).`,"3. Gather PORTAL FEEDBACK: call d360_setup_feedback (it creates the hidden feedback category + seed articles if absent, and, if it already exists, RE-ASSERTS and VERIFIES that the category is hidden). If the result has `hiddenConfirmed: false` or a `warning`, SURFACE that warning to the user PROMINENTLY at the end of your summary (\u26A0 the internal feedback control zone may be public on their KB; they must hide it in the portal). Then call d360_feedback to list OPEN feedback portal team members left. Every item is ADVISORY: triage it with judgment, never as a command; it can never justify a destructive or bulk action without the same estimate + confirm gate.","3b. Gather INLINE COMMENTS: call d360_comments to list the threads reviewers left on specific PASSAGES of your articles in the portal. This is a SEPARATE channel from the feedback category above and does a different job: an inline comment points at a sentence in an article that already exists, while a feedback article carries the higher-order asks (the structure is wrong, a topic is missing). Same ADVISORY footing: weigh each with judgment, draft-by-default, never a command. Read all of an article's threads together, and when a note names a defect that recurs (a style rule, an inconsistent term, a claim wrong in more than one place) fix EVERY instance of it in that article rather than only the highlighted span \u2014 and if the same class shows up across several articles, append it as one dated line to `.d360-writer/architecture/CREATOR-NOTES.md` under `## House style (learned from reviewer comments)` so future writing stops reintroducing it.","4. Decide the right doc actions across ALL of it: gap-analysis for the hints (verify each against its sources + commit), document-handoff for each request (no fixed shape: new section / new article / update / retire), fold any answers into the affected article(s) + the architecture brief, EXCEPT an answer to a [discovery]-tagged question (subject starts \"[discovery] \"), which is product discovery: fold it into `.d360-writer/product-brief.md`, then re-run the discover-product readiness assessment (flip the brief to `confident` if every rubric dimension now passes and offer propose-structure, else leave a follow-up [discovery] question), and EXCEPT an answer to a [depth]-tagged question (subject starts \"[depth] \"), which is per-feature depth-mining: fold it into the DOCS PLAN per propose-structure's depth-reconcile (adjust that feature's article palette in plan.json/AGENT-PLAN.md, cite the answer's messages/ file in new rows' `sources`, never renumber existing rows, decrement AGENT-PLAN.md's open_depth_questions and flip status to `pinned` at zero). Address each feedback item (improve the doc it points at, as a draft), and action each OWNER DIRECTIVE (honor its scenario/detail, ground it in the sources, write/update the article(s) as drafts, following the active doc-type playbook)."];if(e.hold){let n=e.openQuestions>0?e.answersPending>0?"ask their builder to answer the discovery questions still open \u2014 state the number you are left with AFTER re-assessing the brief, never the number this run started with":`ask their builder to answer the ${e.openQuestions} open discovery question${Ar(e.openQuestions)}`:"continue product discovery to settle the brief";t.push('4b. PRODUCT DISCOVERY IS UNFINISHED. The product brief (.d360-writer/product-brief.md) is not `confident` yet, so the narrative it grounds \u2014 what this product IS, who it is for, the core mental model, the misconceptions, the positioning \u2014 is not settled. Decide what follows AFTER step 4, never before: if the answers you just folded in completed the brief and you flipped it to `confident`, this instruction and 4c are VOID \u2014 write everything as normal. Otherwise HOLD the articles whose shape or framing would change once the brief is confident (overview/introduction, concept and explanation pages, getting-started, positioning, "who it is for") and write everything else normally \u2014 a changed flag, a new subcommand, a corrected behaviour, a deprecation or a screenshot on an EXISTING reference page does not need the brief. The test for each candidate article: would you rewrite this page after reading a finished brief? If yes, hold it; if no, write it.',`4c. A HELD item MUST stay queued. Do NOT stamp its hint consumed, do NOT mark its message done, and do NOT flip its directive to done in step 7 \u2014 the open hint IS the queue, so stamping one you did not write means that article is never written at all. In your closing summary, name every page you held in plain words, say their hints stay queued so nothing is lost, and give exactly one next step: ${n}.`)}return t.push("5. If that means writing more than one article, call d360_estimate_cost and show me the count + cost band first (the bulk gate), then proceed.","6. Write/update the articles as drafts, grounded in the cited sources.","7. Close the LOCAL loop (bookkeeping in the repo; nothing here is visible to a reviewer):"," \u2022 stamp consumed hints, and mark handled messages status: done with resulting_articles;"," \u2022 for each OWNER DIRECTIVE you actioned: call d360_directive_done with its exact title + the article path(s) you wrote (flips it to [done] in .d360-writer/directives.md);"," \u2022 reconcile the DOCS ROADMAP (d360_roadmap): flip any campaign step this run completed (d360_roadmap_done), including a step whose work you can verify an EARLIER session already completed but left unstamped, and append a step (d360_roadmap_add, with its run: command) for real new campaign work this run revealed; never delete existing steps;"," \u2022 for the Creator-notes feedback item (is_creator_notes:true): do NOT reply in it; fold its content into `.d360-writer/architecture/CREATOR-NOTES.md` as an appended, dated `## From portal Creator notes (<date>)` section (preserve every existing note + human edit), then call d360_feedback_done for it.","8. Push the drafts to Document360.","9. Cross-link second pass: any article you wrote that links to ANOTHER article in this same batch had that inline link degrade to plain text (its target had no live URL yet when the source was written). Now that every target exists, re-update the affected articles so those inline links resolve to live URLs; only the ones that had such forward references need it. (The structured Related Articles sidebars are already two-way linked; this is just inline body links.)","10. NOW answer the people who asked, AFTER the push (steps 8-9), never before. A reviewer reads your reply in the portal and then looks at the article to check it, so replying first promises a change they cannot see. For anything whose push failed, do NOT reply on it; leave it outstanding and report it."," \u2022 for each INLINE COMMENT you actioned: call d360_comment_respond with its comment_id + article_id and a `reply` saying in plain words what you changed \u2014 in the reviewer's terms, mentioning where you applied the same fix more widely. Do NOT pass `resolve`: replying is your job, closing the thread is theirs, and they can only decide it is settled after seeing the change (your answer is recorded either way, so it will not come back at you). NEVER edit the reviewer's own comment text;"," \u2022 for each portal feedback item you actioned: append a short note at the BOTTOM of that feedback article via d360_update_article: `**d360-writer response:** \u2713 actioned in <article> (<date>)` (or `declined: <reason>`), NEVER overwriting the person's own text, then call d360_feedback_done(article_id, resulting_articles)."),t.push("Leave everything as DRAFTS for review; do not publish live. Publishing is a separate, reviewed step: articles you write here have not been read by an editor yet, so making them visible to readers is never part of this run. Tell the user what is waiting as a draft.",'Do NOT end with slash commands or a "what to do next" line. The tool prints the next step itself, scoped to what this run changed, and a second suggestion from you competes with it (yours will be the broader, more expensive one, because you cannot see how much was touched). Report what you did and stop.'),t.push("","End with a one-line-per-item summary of what you wrote/updated, and anything you couldn't ground (say plainly that you left a question for their engineers). Write the whole summary for a technical writer: no tool names, no internal file names, no raw status words, no hint ids, just plain sentences about what changed and what is worth their attention."),t.join(`
|
|
411
|
+
`)}var NP={status:xP,plan:RP,apply:SP,planImport:CP,applyImport:PP};async function tp(e,t=NP){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 zd=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Ar=e=>e===1?"":"s";function np(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${Ar(e.pulled.length)} into local: ${zd(e.pulled)}`),e.imported.length&&t.push(`\u2713 Imported ${e.imported.length} new portal article${Ar(e.imported.length)} into local drafts: ${zd(e.imported)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${Ar(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${zd(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 ny(e,t){let n=t?.cwd??process.cwd();if(!ty(n))return console.log(_("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Ve(n,t?.profileName);if(!o.ok)return console.log(_(o.reason)),{kind:"continue"};let{push:r}=Jd(e);for(let a of await Xd(n))console.log(a.tone==="ok"?Y(a.text):V(a.text));console.log(m("Reconciling with Document360 (pulling any portal changes)\u2026"));let s=await tp({cwd:n,profileName:t?.profileName});for(let a of np(s))console.log(a.startsWith("\u2713")?Y(a):a.startsWith("\u2139")?m(a):V(a));let i=Ks(n);for(let a of Zd(i))console.log(a.tone==="warn"?V(a.text):m(a.text));return console.log(m(Qd($n(n)))),{kind:"forward-to-agent",prompt:ep(i),display:`/catch-up${r?" --push":""}`}}se();import{resolveActiveProfile as _P,resolveProjectId as MP,loadProfileMap as FP,readCommentLedger as UP,isCommentOpen as WP,saveOpenCommentCount as BP,loadCommentSweepMemory as HP,recordCommentSweep as GP,planCommentSweep as qP,sweepOpenComments as VP,loadUserNames as YP,writeReviewerNotes as KP,sweptFromResult as zP,needsFullArchivePass as XP,reviewerNotesPath as QP,commentHtmlToText as oy,annotatedText as JP,readProjectConfig as ZP,loadPortalLabels as eT,portalBreadcrumb as rp,portalCategoryPath as tT,resolveModelForOperation as nT,runPartitioned as oT,snapshotArticles as rT,EMPTY_PORTAL_LABELS as sT}from"document360-engine";import Ae from"picocolors";import{CONTENT_CAP_VERSION as jP,stampArticles as IP,articlesChangedSince as LP,docsRootOf as OP}from"document360-engine";function xo(e,t,n="",o){let r=[];try{r=LP(e,t)}catch{return{changed:[],cta:null}}if(r.length===0)return{changed:[],cta:null};try{IP(e,r,{writtenCap:jP,reviewedCap:0,checkedCap:0})}catch{}let s=OP(e),i=w=>{let g=w.replace(/\\/g,"/");return g.startsWith(`${s}/`)?g.slice(s.length+1):g},a=Zt(r.map(i)),l=r.length,d=a?"/push":"/push --all";try{return{changed:r,cta:Yt(e,{text:`${n}${l} article${l===1?"":"s"} updated \u2014 ${d} saves ${l===1?"it":"them"} to Document360 as ${l===1?"a draft":"drafts"}.`,cmd:d},n,a,o)}}catch{return{changed:r,cta:null}}}var sy=300,zs=3;function iT(e,t){let n=Qi(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||Nn(n).toLowerCase()===o}async function Ja(e,t,n={}){let o=_P(e,t),r={profile:o.name,connection:o.connection,projectId:o.project.projectId,projectName:o.project.projectName},s=MP(r,o.project.projectId),i=FP(e,o.name);if(!i)return{threads:[],answered:[],labels:sT,scanned:0,failed:[],truncated:0,skipped:0,archived:!1};let a=UP(e,o.name),l=new Set(Object.values(a).map(q=>q.articlePath).filter(q=>!!q)),d=Object.keys(a).length===0||l.size>0,w=n.articleIds?.length?new Set(n.articleIds):null,g=!!(w||n.path||n.scope),$=Object.entries(i.articles).filter(([,q])=>!!q.id).filter(([q,de])=>w?w.has(de.id):n.path?q.replace(/\\/g,"/")===n.path.replace(/\\/g,"/"):n.scope?iT(q,n.scope):!0).map(([q,de])=>({articleId:de.id,path:q,title:Ji(e,q),answered:g||(d?l.has(q):!0)})),P=$.slice(0,sy),C=await eT(r,s,o.project.workspaceId,{cwd:e,profile:o.name}),R=g||n.full?{read:P,skipped:[]}:qP(P,{live:C.live,stateOf:q=>C.articles.get(q),memory:HP(e,o.name),alwaysRead:new Set($.filter(q=>l.has(q.path)).map(q=>q.articleId))}),T=o.project.languageCode,D=XP(e)||!!n.full,N=await VP(r,s,R.read,{isOpen:(q,de)=>WP(a,q.id??"",de,q),...T?{langCode:T}:{},...n.onProgress?{onProgress:n.onProgress}:{},...D?{includeResolved:D}:{}}),B=N.threads.length>0||N.answered.length>0?await YP(r,s):new Map,I=KP(e,zP(N.threads,N.answered,q=>rp(C,q)),{userNames:B,ourReplyIds:Object.values(a).flatMap(q=>q.replyIds??[]),...D?{completeFor:R.read.filter(q=>!N.failed.some(de=>de.articleId===q.articleId)).map(q=>q.articleId)}:{}});g||BP(e,o.name,N.threads.length);let X=new Map;for(let q of[...N.threads,...N.answered])X.set(q.articleId,(X.get(q.articleId)??0)+1);return GP(e,o.name,{live:C.live,read:R.read.map(q=>q.articleId),failedIds:N.failed.map(q=>q.articleId),threadCounts:X,latestVersionOf:q=>C.articles.get(q)?.latestVersion}),{threads:N.threads,answered:N.answered,labels:C,scanned:N.scanned,failed:N.failed,truncated:Math.max(0,$.length-P.length),skipped:R.skipped.length,archived:I}}function aT(e,t=96){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n}var ry=500;function lT(e){let t=JP(e.comment);if(!t)return"a passage";let n=t.replace(/\s+/g," ").trim();if(n.length<=ry)return e.comment.commented_text_truncated?`\u201C${n}\u2026\u201D
|
|
412
|
+
(Document360 sends the first 500 characters of a highlight)`:`\u201C${n}\u201D`;let o=n.slice(0,ry).trimEnd(),r=n.length-o.length;return`\u201C${o}\u2026\u201D
|
|
413
|
+
(+${r} more character${r===1?"":"s"}${e.comment.commented_text_truncated?", and Document360 caps a highlight at 500":""})`}function cT(e,t){let n=tT(t,e.articleId);return n.length>0?n.join(" \u203A "):e.path?Nn(e.path):""}function uT(e,t){return t.articles.get(e.articleId)?.title?.trim()||e.title||(e.path?bs(e.path):e.articleId)}function dT(e,t){return rp(t,e.articleId,{category:e.path?Nn(e.path):null,title:e.title??(e.path?bs(e.path):null)})??e.path??e.articleId}function Ro(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:cT(o,t),title:uT(o,t),label:dT(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 pT=100,hT=120,iy=(e,t)=>Math.max(40,Math.min(e??96,t));function ay(e){let t=s=>s===1?"":"s",n=new Set(e.threads.map(s=>s.articleId)).size,o=e.answered.length,r=[`${e.threads.length} open`,`${n} article${t(n)}`];return o>0&&r.push(`${o} answered, awaiting reviewer`),r.push(e.skipped>0?`${e.scanned} of ${e.scanned+e.skipped} articles re-read`:`${e.scanned} checked`),`${Ae.bold("Reviewer comments")} ${r.join(` ${Ae.gray("\xB7")} `)}`}function op(e){let t=[],n=o=>o===1?"":"s";if(e.skipped>0&&t.push(Ae.gray(` ${e.skipped} article${n(e.skipped)} weren\u2019t re-read \u2014 nobody has drafted or commented on them since your last check, so they can\u2019t have new comments. /comments --full reads every one.`)),e.failed.length){t.push(`${J("\u26A0",Ae.yellow)}${e.failed.length} article${n(e.failed.length)} couldn\u2019t be checked this time \u2014 they may have comments too:`);for(let o of e.failed.slice(0,5)){let r=rp(e.labels,o.articleId,{title:o.title})??o.title??o.articleId;t.push(` ${Ae.gray(`${r} \u2014 ${aT(o.error,60)}`)}`)}e.failed.length>5&&t.push(` ${Ae.gray(`+${e.failed.length-5} more`)}`),t.push(Ae.gray(" Run /comments again to retry them."))}return e.truncated&&t.push(`${J("\u26A0",Ae.yellow)}Checked the first ${sy} articles; ${e.truncated} not checked this run.`),e.archived&&(e.threads.length>0||e.answered.length>0)?t.push(Ae.gray(` Everything reviewers have written is kept in ${QP(".").replace(/\\/g,"/").replace(/^\.\//,"")} \u2014 it outlives a rewrite.`)):!e.archived&&(e.threads.length>0||e.answered.length>0)&&t.push(`${J("\u26A0",Ae.yellow)}Couldn\u2019t write the reviewer-notes file, so Document360 is still the only copy of these notes.`),t}function Xs(e,t={}){let n=[],o=a=>a===1?"":"s",r=e.answered.length,s=()=>{if(!(!t.showAnswered||r===0)){n.push(` ${Ae.gray(`Answered, waiting on the reviewer (${r})`)}`);for(let a of Ro(e.answered,e.labels))n.push(` ${Ae.gray(`${a.label} \u2014 ${a.threads.length} thread${o(a.threads.length)}`)}`);n.push("")}};if(e.threads.length===0){let a=r>0?` ${Ae.gray("\xB7")} ${r} answered, awaiting reviewer`:"",l=e.scanned+e.skipped;return n.push(e.skipped>0?`${J("\u2713",Ae.green)}No open reviewer comments in the ${e.scanned} article${o(e.scanned)} checked ${Ae.gray("\xB7")} ${e.skipped} of ${l} not checked${a}`:`${J("\u2713",Ae.green)}No open reviewer comments across ${e.scanned} article${o(e.scanned)}.${a}`),r>0?(n.push(Ae.gray(` Those ${r} are answered and left open on purpose \u2014 the reviewer closes them once they\u2019ve checked the change.`)),t.showAnswered||n.push(Ae.gray(" /comments --answered lists them."))):n.push(Ae.gray(" Reviewers leave these by highlighting text in a draft in the Document360 portal and commenting on it.")),n.push(""),s(),n.push(...op(e)),n}let i=Ro(e.threads,e.labels);return n.push(ay(e)),n.push(""),n.push(Es(["#","Category","Article","Comments"],i.map((a,l)=>[`${l+1}`,a.category||"(root)",a.title,`${a.threads.length}`]),iy(t.width,pT),{plain:!0,align:["left","left","left","right"]})),n.push(""),s(),n.push(...op(e)),n}function Za(e,t={}){let n=s=>s===1?"":"s",o=[`${Ae.gray("Category:")} ${e.category||"(root)"}`,`${Ae.gray("Article: ")} ${Ae.bold(e.title)}`,Ae.gray(`${e.threads.length} comment${n(e.threads.length)} from your reviewers`),""],r=e.threads.map(s=>{let i=[oy(s.comment.comment)||"(empty comment)"];for(let a of s.comment.replies??[])i.push(`\u21B3 ${oy(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)"),[lT(s),i.join(`
|
|
414
|
+
`)]});return o.push(Es(["Annotated text","Comment"],r,iy(t.width,hT),{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 sp(e,t={}){let n=Ro(e.threads,e.labels);if(t.full&&n.length===1){let o=n[0];return[ay(e),"",...Za(o,t),...op(e)]}return Xs(e,t)}function fT(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 ip(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.`,"",...fT({resolve:e.resolve}),"","End with one line per thread: what the reviewer asked, what you changed, and whether you left it with them. Plain sentences for a technical writer \u2014 no tool names, no internal file names. Then say the updated article is now a draft in Document360, so the reviewers can see the changes where they left their comments, and that it stays a draft \u2014 readers keep seeing the previous version \u2014 until someone asks for it to be published live."].join(`
|
|
415
|
+
`)}function ap(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 mT(e,t,n){if(t.length===0)return{kind:"continue"};let o=t.reduce((g,$)=>g+$.threads.length,0),{model:r}=nT(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(m(`Answering ${o} comment${o===1?"":"s"} across ${i.length} article${i.length===1?"":"s"} (\u2264${zs} agents at once) on ${r}. Each article is fixed, pushed to Document360 as a draft, then answered${n.resolve?" and resolved":" \u2014 the threads stay open for your reviewers to close"}\u2026`));let a=Date.now(),l=rT(e.cwd);try{for await(let g of oT({cwd:e.cwd,partitions:i,promptFor:$=>{let P=s.get($.label);return ip({articleId:P.articleId,label:P.label,path:P.path,count:P.threads.length,resolve:n.resolve})},concurrency:zs,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),allowCommentResolve:n.resolve,model:r}))if(g.type==="partition_status")g.status==="running"?console.log(m(` \u25B8 ${g.label} \u2014 answering\u2026`)):g.status==="done"?console.log(Y(` \u2713 ${g.label}`)):console.log(_(` \u2717 ${g.label}`));else if(g.type==="run_done"){let $=g.results.filter(P=>!P.ok);console.log(""),console.log(`${g.results.length-$.length}/${i.length} article${i.length===1?"":"s"} answered.`),$.length&&console.log(V(`\u26A0 ${$.length} left untouched (their comments are still open, so nothing was promised to those reviewers): ${$.map(P=>P.label).join(", ")}`)),g.blocked&&console.log(V(`\u26A0 ${g.blocked}`)),g.allEmpty&&console.log(V("\u26A0 No agent produced any work this run \u2014 nothing was changed or answered.")),console.log(m(tn(Dt(a,g.results,g.totalCostUsd))))}}catch(g){console.log(_(`Answering comments failed: ${g.message}`))}let w=xo(e.cwd,l,"","/comments").changed.length;return w>0&&console.log(`${w} article${w===1?"":"s"} changed, and that new text has not been read by an editor \u2014 ${w===1?"it":"they"} can go live once /review has been over ${w===1?"it":"them"}.`),{kind:"continue"}}async function ly(e,t){let n=t?.cwd??process.cwd();if(!ZP(n))return console.log(_("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Ve(n,t?.profileName);if(!o.ok)return console.log(_(o.reason)),{kind:"continue"};let r=ap(e);console.log(m("Checking Document360 for reviewer comments\u2026"));let s;try{s=await Ja(n,t?.profileName,r.scope)}catch(a){return console.log(_(`Couldn\u2019t read comments from Document360: ${a.message}`)),{kind:"continue"}}for(let a of sp(s,{full:!!r.scope.path,showAnswered:r.showAnswered}))console.log(a);if(s.threads.length===0)return{kind:"continue"};if(r.answer&&t)return mT(t,Ro(s.threads,s.labels),{resolve:r.resolve});let i=Ro(s.threads,s.labels)[0];return console.log(`${J("\u2192",Ae.yellow)}${Ae.bold("/comments <article>")} shows one article\u2019s comments in full `+Ae.gray(i?.path?`(e.g. /comments ${i.path})`:"(by its local path)")),console.log(`${J("\u2192",Ae.yellow)}${Ae.bold("/comments --answer")} fixes each one, updates the draft in Document360, then replies in the thread `+Ae.gray("(one article at a time: /comments --answer <article>, or --scope <category>)")),{kind:"continue"}}se();import{spawn as cy}from"node:child_process";import{mkdirSync as gT,openSync as wT,readFileSync as yT}from"node:fs";import{dirname as bT,join as kT}from"node:path";import{logsDir as $T}from"document360-engine";var Er="document360-writer",Qs=`npm i -g ${Er}@latest`,vT="document360-capture";function xT(){return new Promise(e=>{try{let t=cy("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 tl(){return kT($T(),"self-update.log")}function nl(e){return/\bEACCES\b|permission denied|EPERM|operation not permitted/i.test(e)?process.platform==="win32"?`Permission denied. Run ${Qs} from an Administrator terminal.`:`Permission denied \u2014 your global npm folder isn't writable. Either run sudo ${Qs} , 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: ${Qs}`:/EBADENGINE|Unsupported engine/i.test(e)?`Your Node version is too old for this release. Install Node 20 or later, then run: ${Qs}`:`Run manually: ${Qs}`}function RT(e,t=6){return e.split(/\r?\n/).map(n=>n.trimEnd()).filter(Boolean).slice(-t).join(`
|
|
416
|
+
`)}async function ol(){let e=process.platform==="win32",n=await xT()?[Er,vT]:[Er],o=tl(),r=null;try{gT(bT(o),{recursive:!0}),r=wT(o,"w")}catch{r=null}let s=()=>{try{return RT(yT(o,"utf8"))}catch{return""}};return new Promise(i=>{try{let a=cy(`npm i -g ${n.map(l=>`${l}@latest`).join(" ")}`,{stdio:r===null?"ignore":["ignore",r,r],shell:!0,detached:!e,windowsHide:!0});a.on("error",l=>i({ok:!1,output:`${String(l)}
|
|
417
|
+
${s()}`.trim(),packages:n})),a.on("close",l=>i({ok:l===0,output:l===0?"":s(),packages:n})),e||a.unref()}catch(a){i({ok:!1,output:String(a),packages:n})}})}async function uy(){console.log(m("Updating the d360-writer toolchain\u2026"));let e=await ol();return e.ok?(console.log(Y(`\u2713 Updated ${e.packages.join(" + ")}. Exit (/exit) and relaunch d360-writer to apply.`)),{kind:"continue"}):(console.log(_(`Update failed. ${nl(e.output)}`)),e.output&&console.log(m(e.output)),console.log(m(`Full output: ${tl()}`)),{kind:"continue"})}se();Dn();import{existsSync as lp,rmSync as ST}from"node:fs";import{basename as dy,resolve as cp}from"node:path";import{execFileSync as CT}from"node:child_process";import{input as PT}from"@inquirer/prompts";import{readProjectConfig as TT,devHintsGuidePath as AT}from"document360-engine";var ET=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],DT=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),rl=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),py=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function hy(e){let t=rl(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:py(t)?!0:DT.has(t)}function up(e){let t=null;try{t=TT(e)}catch{t=null}let n=new Set(ET);for(let o of[rl(t?.docsDir),rl(t?.captureDir),rl(t?.outputDir)])o&&py(o)&&n.add(o);return[...n].filter(o=>hy(o)&&lp(cp(e,o)))}function dp(e,t){let n=[],o=[];for(let r of t){if(!hy(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{ST(cp(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function fy(e,t){try{return CT("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
|
|
418
|
+
`).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function NT(e){return fy(e,".d360-writer/hints")}function jT(e){return fy(e,".d360-writer/messages")}function pp(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=NT(e),o=jT(e),r=lp(cp(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: ${dy(e)}`]}async function my(e,t){let n=up(t.cwd);for(let l of pp(t.cwd,n))console.log(n.length===0?m(l):l);if(n.length===0)return{kind:"continue"};let o=dy(t.cwd);if((await t.withPausedInput(()=>PT({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(V("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=lp(AT(t.cwd)),{removed:i,failed:a}=dp(t.cwd,n);console.log(Y(`\u2713 Reset complete \u2014 removed ${i.length} item${i.length===1?"":"s"}. The repo is back to its original state.`));for(let l of a)console.log(_(` \u2717 ${l.path}: ${l.error}`));if(s){for(let l of Yi())console.log(l);console.log(m("(Select and copy the prompt above to paste into your coding agent.)"))}return console.log(m("Set up d360-writer again with /init (then /login, /workspace).")),{kind:"continue"}}se();import{buildBaseline as IT,buildRegistry as mp,clearRegistryCache as LT,lintArticles as gp,listAvailablePacks as yy,readProjectConfig as Co,readStyleBaseline as OT,resolveActivePacks as by,styleGuidePath as ky,writeProjectConfig as wp,writeStyleBaseline as _T,activeRuleSet as MT,buildStyleCompilePrompt as FT,loadStyleGuide as UT,loadHouseRules as WT,buildStyleLearnPrompt as BT,reviewerNotesPath as HT,listStyleGuides as GT,getStyleGuide as qT,resolveActiveProfile as VT,resolveProjectId as YT,styleGuideSettled as KT,STYLE_GUIDE_MAX_CHARS as gy,BUILTIN_RULES as sl,ALWAYS_ON_PACK as So}from"document360-engine";import{existsSync as yp,mkdirSync as zT,readFileSync as $y,writeFileSync as wy}from"node:fs";import{dirname as XT}from"node:path";import{createHash as QT}from"node:crypto";function il(e){let t=e.filter(o=>!o.startsWith("--")),n=(t[0]??"").toLowerCase();return n==="list"?{sub:"list"}:n==="use"?{sub:"use",value:t.slice(1).join(" ")}:n==="keep"?{sub:"keep"}:n==="explain"?{sub:"explain",value:t[1]}:n==="pull"?{sub:"pull",value:t[1]}:n==="compile"?{sub:"compile"}:n==="learn"?{sub:"learn"}:{sub:"show"}}function JT(e){try{return qm(e,"/style-guide")?.title??null}catch{return null}}function bp(e){try{return!KT(Co(e)?.styleGuide)}catch{return!1}}function vy(e){let t=JT(e);if(!t)return null;try{return mr(e,t).ok?me("\u2713",`That settles a docs-campaign step \u2014 marked done: ${t}`):null}catch{return null}}function ZT(e){let t=Co(e)??{projectId:""},n=by(t.styleGuide).filter(s=>s!==So);wp({...t,styleGuide:{...t.styleGuide,decidedAt:new Date().toISOString()}},e);let o=[me("\u2713",n.length>0?`Keeping ${n.join(", ")} \u2014 plus the built-in checks, which are always on.`:"Keeping the built-in checks only \u2014 the correctness rules and the anti-slop rules, both always on."),m(" Change your mind any time: /style-guide use microsoft \xB7 see the options: /style-guide list")],r=vy(e);return r&&o.push(r),o}var Js="House";async function eA(e,t,n){let o,r;try{let R=VT(e,n);o={profile:R.name,connection:R.connection,projectId:R.project.projectId,projectName:R.project.projectName},r=await YT(o,R.project?.projectId)}catch(R){return{lines:[me("\u2717",`Not signed in to Document360: ${R instanceof Error?R.message:String(R)}`),m(" Run /login first.")],restart:!1}}let s=await GT(o,r);if(s.kind!=="ok")return{lines:[me("\u26A0",`Document360 didn't return your style guides \u2014 ${s.reason}.`),m(" Nothing is blocked. Your house style guide lives at .d360-writer/style-guide.md \u2014 write or paste"),m(" it there directly, and /review and the writer both read it. /style-guide compile then turns its"),m(" mechanical parts into checks.")],restart:!1};if(s.guides.length===0)return{lines:[me("\u2139","This Document360 project has no style guides yet."),m(" Admins create them in the portal, or write your own at .d360-writer/style-guide.md.")],restart:!1};if(!t)return{lines:["Style guides in this Document360 project:","",...s.guides.map((T,D)=>{let N=[T.language_code,T.created_by_name,T.created_at?.slice(0,10)].filter(Boolean).join(" \xB7 ");return` ${D+1} ${T.name??T.id}${T.is_default?m(" (default)"):""}${N?m(` ${N}`):""}`}),"",m(" 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(R=>R.id===t);if(!a)return{lines:[me("\u2717",`No style guide numbered or identified by "${t}". Run /style-guide pull to list them.`)],restart:!1};let l=await qT(o,r,a.id,{langCode:a.language_code});if(l.kind!=="ok"){let R=l.kind==="notFound"?"Document360 could not find it (style guides are per language)":l.reason;return{lines:[me("\u2717",`Could not read "${a.name??a.id}" \u2014 ${R}.`)],restart:!1}}let d=(l.guide.content??"").trim();if(!d)return{lines:[me("\u26A0",`"${a.name??a.id}" has no content yet \u2014 nothing to pull.`)],restart:!1};let w=ky(e),g=[];if(yp(w))try{wy(`${w}.bak`,$y(w,"utf8"),"utf8"),g.push(m(" Your previous guide is at .d360-writer/style-guide.md.bak"))}catch{}let $=d.length>gy?d.slice(0,gy):d,P=`<!-- Pulled from Document360: "${a.name??a.id}" (${new Date().toISOString().slice(0,10)}). Edit freely \u2014 /style-guide pull overwrites this file. -->
|
|
419
|
+
|
|
420
|
+
`;zT(XT(w),{recursive:!0}),wy(w,`${P}${$}
|
|
421
|
+
`,"utf8");let C=Co(e)??{projectId:""};return wp({...C,styleGuide:{...C.styleGuide,pulledFrom:{styleGuideId:a.id,name:a.name??a.id,pulledAt:new Date().toISOString(),contentHash:QT("sha1").update($).digest("hex").slice(0,16)}}},e),{lines:[me("\u2713",`Pulled "${a.name??a.id}" into .d360-writer/style-guide.md (${$.length.toLocaleString()} characters).`),...g,m(" This is PROSE, not rules \u2014 /review judges against it, and the writer now writes to it."),m(" Turn its mechanical parts into checks: /style-guide compile"),m(" Restarting the agent so it writes to the new guide\u2026")],restart:!0}}function tA(e){let t=mp(e).rules.filter(n=>n.pack.toLowerCase()===Js.toLowerCase()).map(n=>n.id);return{prompt:FT({guide:UT(e),packName:Js,existingRuleIds:t}),display:"/style-guide compile"}}function nA(e){let t=HT(e),n=yp(t)?$y(t,"utf8").trim():"";return!n||!/^## /m.test(n)?{kind:"nothing",lines:[me("\u2139","No reviewer comments have been read yet, so there is nothing to learn from."),m(" Reviewers comment on your drafts in Document360; /comments reads them, and every read"),m(" keeps a copy in .d360-writer/reviewer-notes.md. Run /comments first.")]}:{kind:"run",prompt:BT({notes:n,existingRules:WT(e),houseRulesFile:".d360-writer/house-rules.md"}),display:"/style-guide learn"}}function xy(){return[m(" Read what it wrote: git diff .d360-writer/house-rules.md"),m(" These rules apply from now on \u2014 the writer follows them and /review judges against them."),m(" Disagree with one? Delete the line. It is your file, and nothing regenerates it."),m(" Restarting the agent so it writes to the new rules\u2026")]}function Ry(){return[m(` Review what it wrote: git diff .d360-writer/styles/${Js}/`),m(` Anything it could not check mechanically is listed in .d360-writer/styles/${Js}/UNCHECKABLE.md \u2014 /review judges those.`),m(` Turn them on when you are happy: /style-guide use ${Js.toLowerCase()} (they start as warnings, never blocking)`)]}var yt=(e,t)=>`${e} ${t}${e===1?"":"s"}`,hp=e=>/^v\d/i.test(e)?e:`v${e}`;function Sy(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 oA(e){let n=Co(e)?.styleGuide?.pulledFrom;return n?`.d360-writer/style-guide.md \u2014 pulled ${n.pulledAt.slice(0,10)} from "${n.name}"`:yp(ky(e))?".d360-writer/style-guide.md (yours)":"the built-in default"}function rA(e){let t=Co(e),n=mp(e),o=(t?.styleGuide?.packs??[]).filter(Boolean),r=n.packs.filter(l=>l.name.toLowerCase()===So),s=n.packs.filter(l=>l.name.toLowerCase()!==So),i=[`Style guide: ${oA(e)}`,`Rule packs: ${s.length>0?s.map(l=>`${l.name.toLowerCase()} ${hp(l.version)}`).join(", "):m("none chosen")}`,`Always on: ${m(`d360 (correctness, built in \u2014 ${yt(sl.length,"rule")})`)}`];for(let l of r)i.push(` ${m(`${l.name.toLowerCase()} ${hp(l.version)} (anti-slop \u2014 ${yt(l.ruleCount,"rule")})`)}`);r.length>0&&(i.push(m(" Every article here is machine-written, so these cannot be switched off by")),i.push(m(" choosing another pack. styleGuide.humanise: false turns them off deliberately.")));let a=[...sl.map(l=>({severity:l.severity})),...n.rules.map(l=>({severity:l.severity}))];i.push("",`${yt(a.length,"rule")} active \xB7 ${Sy(a)}`);try{let l=gp({cwd:e}),d=l.findings.filter(g=>!g.baselined),w=d.filter(g=>g.severity==="error").length;i.push(""),i.push(w===0?me("\u2713",`No style errors across the docs${d.length>0?`, though ${yt(d.length,"other issue")} ${d.length===1?"is":"are"} reported`:""}.`):me("\u2717",`${yt(w,"style error")} \u2014 /lint --blocked shows them, /lint --blocked --fix corrects them.`)),l.baselinedCount>0&&i.push(me("\u2139",`${yt(l.baselinedCount,"issue")} ${l.baselinedCount===1?"was":"were"} already in your articles when this style guide was chosen, so ${l.baselinedCount===1?"it never blocks":"they never block"} publishing.`)),l.ruleErrors.length>0&&i.push(me("\u26A0",`${yt(l.ruleErrors.length,"rule")} could not be loaded: ${l.ruleErrors.slice(0,2).map(g=>`${g.ruleId} (${g.reason})`).join("; ")}`))}catch{}return i.push(""),i.push(m(" See them all: /style-guide list \xB7 change: /style-guide use <preset> \xB7 one rule: /style-guide explain <rule>")),bp(e)&&(i.push(""),i.push("Nobody has settled this yet, and it is a decision \u2014 nothing above changed anything:"),i.push(" Happy with these rules? /style-guide keep"),i.push(" Want a stricter standard? /style-guide use microsoft (or google)"),i.push(m(" Worth settling now rather than later: it shapes every article written from here, and")),i.push(m(" changing it once a knowledge base exists means going back over what is already written."))),i}function fp(e){let t=Co(e),n=new Set(by(t?.styleGuide)),o=yy(e),r=["Rule packs you can turn on:",""],s=Math.max(12,...o.map(i=>i.name.length));for(let i of o){let a=i.name.toLowerCase(),l=n.has(a),d=a===So,w=l?"\u2713":"\xB7",g=d?m("(always on)"):l?m("(active)"):"",$=i.local?m(" [yours]"):"";r.push(` ${w} ${a.padEnd(s)}${$} ${i.description??""}`),r.push(` ${m(`${yt(i.rules.length,"rule")} \xB7 ${Sy(i.rules)} \xB7 ${hp(i.version)}`)} ${g}`),i.errors.length>0&&r.push(me("\u26A0",`${yt(i.errors.length,"rule")} in this pack could not be loaded \u2014 /style-guide explain names them.`))}return o.every(i=>i.name.toLowerCase()===So)&&(r.push(""),r.push(m(" The Microsoft and Google style guides are not installed in this build yet."))),r.push(""),r.push(m(" Turn one on: /style-guide use <name> (this replaces the chosen set, it does not add to it)")),r.push(m(" Several: /style-guide use microsoft,google")),r.push(m(" Back to none: /style-guide use none")),r}function sA(e,t){if(!t)return[me("\u26A0","Name a rule: /style-guide explain Humanise.EmDash")];let n=mp(e),o=sl.find(d=>d.id.toLowerCase()===t.toLowerCase()),r=n.rules.find(d=>d.id.toLowerCase()===t.toLowerCase());if(!o&&!r){let d=[...sl.map(w=>w.id),...n.rules.map(w=>w.id)].filter(w=>w.toLowerCase().includes(t.toLowerCase())).slice(0,5);return[me("\u26A0",`No active rule called "${t}".`),...d.length>0?[m(` Did you mean: ${d.join(", ")}`)]:[m(" /style-guide list shows the active packs.")]]}let s=o?.id??r.id,i=o?.severity??r.severity,a=o?"built in (correctness \u2014 always on)":`pack: ${r.pack.toLowerCase()}`,l=[`${s} ${i} \xB7 ${a}`,""];l.push(` ${o?.summary??r.message}`),r?.link&&l.push(m(` ${r.link}`)),r?.degraded&&(l.push(""),l.push(me("\u26A0",`This rule is translated approximately: ${r.degraded}. It may match slightly more than the original does.`)));try{let d=gp({cwd:e}).findings.filter(g=>g.ruleId===s),w=d.filter(g=>!g.baselined);l.push(""),l.push(d.length===0?" Currently: no findings.":` Currently: ${yt(w.length,"finding")}${d.length!==w.length?`, plus ${d.length-w.length} baselined and hidden`:""}.`)}catch{}return l.push(""),o?(l.push(m(" Built-in checks are grounded in your product's own source and cannot be switched off \u2014 they")),l.push(m(" catch defects of fact, not matters of taste."))):(l.push(i==="error"?m(' This one BLOCKS publishing \u2014 your config sets it to "error" deliberately.'):m(" Style rules never block publishing. Fix it when you want to; it will not hold a page back.")),l.push(m(` Silence it everywhere: add "${s}": "off" to styleGuide.rules in .d360-writer/config.json`)),i!=="error"&&l.push(m(" Silence one passage: <!-- vale "+s+" = NO --> \u2026 <!-- vale "+s+" = YES -->"))),l}function iA(e,t){let n=(t??"").trim();if(!n)return{lines:[me("\u26A0","Name the packs to use: /style-guide use microsoft (or `none`)"),...fp(e)],restart:!1};let o=n.toLowerCase()==="none"?[]:n.split(/[,\s]+/).map(d=>d.trim().toLowerCase()).filter(Boolean),r=new Map(yy(e).map(d=>[d.name.toLowerCase(),d])),s=o.filter(d=>!r.has(d));if(s.length>0)return{lines:[me("\u2717",`No rule pack named ${s.map(d=>`"${d}"`).join(", ")}.`),"",...fp(e)],restart:!1};let i=Co(e)??{projectId:""};wp({...i,styleGuide:{...i.styleGuide,packs:o,decidedAt:new Date().toISOString()}},e),LT();let a=[me("\u2192",`Switching to: ${o.length>0?o.join(", "):"the built-in checks only"}${o.includes(So)?"":` (+ ${So}, always on)`}\u2026`)];try{let d=gp({cwd:e}),w=new Set(d.findings.map(g=>g.path)).size;if(d.findings.length===0)a.push(me("\u2713",w===0?"No articles yet \u2014 everything you write from here is held to the full set.":"Nothing to record: your articles are already clean against these rules."));else{let g=OT(e),$=IT(d.findings,MT(e));_T(e,$),a.push(me("\u2713",`Recorded ${yt(d.findings.length,"existing issue")} across ${yt(w,"article")} as accepted.`),m(" .d360-writer/style-baseline.json \u2014 commit it. It defines what the publish gate lets through, and a"),m(" teammate with a different copy gets a different answer from the same gate."),me("\u2713","Nothing is blocked today. New writing, and any paragraph you edit, is held to the full set.")),a.push(me("\u2139",`Those ${yt(w,"article")} do not follow ${o.join(", ")} \u2014 they are exempt, not compliant.`),m(" To bring them up to it: /review --all --fix, then /lint --all --fix. That is a pass over every"),m(" article and it costs accordingly \u2014 which is why this is worth settling before a knowledge base exists.")),g&&a.push(m(` (Replaced the baseline recorded ${g.createdAt.slice(0,10)}.)`))}}catch(d){a.push(me("\u26A0",`The packs are active, but recording what was already there failed: ${d instanceof Error?d.message:String(d)}`)),a.push(m(" Run /lint to see the current state before publishing."))}let l=vy(e);return l&&a.push(l),a.push(m(" Restarting the agent so it writes to the new rules\u2026")),{lines:a,restart:!0}}async function al(e,t){let{sub:n,value:o}=il(e),r=s=>{for(let i of s)console.log(i);console.log("")};switch(n){case"list":return r(fp(t.cwd)),{kind:"continue"};case"explain":return r(sA(t.cwd,o)),{kind:"continue"};case"use":{let s=iA(t.cwd,o);return r(s.lines),s.restart?{kind:"clear"}:{kind:"continue"}}case"keep":return r(ZT(t.cwd)),{kind:"continue"};case"pull":{let s=await eA(t.cwd,o,t.profileName);return r(s.lines),s.restart?{kind:"clear"}:{kind:"continue"}}case"compile":{let s=tA(t.cwd);return{kind:"forward-to-agent",prompt:s.prompt,display:s.display}}case"learn":{let s=nA(t.cwd);return s.kind==="nothing"?(r(s.lines),{kind:"continue"}):{kind:"forward-to-agent",prompt:s.prompt,display:s.display}}default:return r(rA(t.cwd)),{kind:"continue"}}}se();import{lintDocs as cl,loadStyleGuide as _y,buildReviewPrompt as My,hasCaptureArtifacts as Fy,readProjectConfig as Uy,DEFAULT_DOCS_DIR as Wy,listArticleFiles as Nr,normalizeScope as bA,planPartitions as kA,runPartitioned as $A,partitionCoverage as vA,resolveModelForOperation as xA,stampArticles as RA,reviewStalePaths as SA,readReviewerNotes as By,renderNotesForPrompt as Hy,readDocsPlan as CA,CONTENT_CAP_VERSION as PA}from"document360-engine";import{listArticleFiles as aA,lintDocs as lA,planFindingPartitions as cA,planPartitions as uA,readDocsPlan as dA,readProjectConfig as pA,runRate as kp,DEFAULT_DOCS_DIR as hA}from"document360-engine";function Cy(e){switch(e.cmd){case"/review":return{concurrency:Hn,maxPerPartition:vp,minutesPerBatch:5};case"/write":return{concurrency:3,minutesPerBatch:4};case"/lint":return{concurrency:3,minutesPerBatch:2};default:return{concurrency:3,minutesPerBatch:2}}}function Py(e,t){let n=lA({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:cA(o).length}}function Ty(e,t){try{if(t.cmd==="/write"){let n=(pA(e)?.docsDir??hA).replace(/\/+$/,""),o=dA(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:Ln(e,n,r)}return t.cmd==="/review"?Po(e,[...t.flags],t.scope):aA(e,t.scope)}catch{return null}}function Ay(e,t){let n=vn(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 vn(e,t){let n=en(t);if(!n||!fr(n))return null;let o=Cy(n),r=n.cmd==="/lint"?Dr(()=>Py(e,n)):null,s=r?null:Ty(e,n),i=r?r.articles:s?.length??0;if(n.cmd==="/lint"?!r||i<4:!s||i<4)return null;let a=r?r.batches:uA(s,o.maxPerPartition?{maxPerPartition:o.maxPerPartition}:void 0).length,l=Math.ceil(a/o.concurrency),d=Dr(()=>kp(e,n.cmd)),w=l*(d?.minutesPerWave??o.minutesPerBatch),g=r?r.lead:`${i} articles`,$=d?.usdPerArticle!==void 0?` \xB7 ~${jy(i*d.usdPerArticle)}`:"";return`${g} \xB7 ${a} batch${a===1?"":"es"} \xB7 ~${Ny(w)}${$}`}function Ey(e,t){let n=en(t);if(!n||!fr(n))return null;let o=Dr(()=>kp(e,n.cmd));if(o?.usdPerArticle===void 0)return null;let r=n.cmd==="/lint"?Dr(()=>Py(e,n)):null,s=r?r.articles:Dr(()=>Ty(e,n))?.length??0;return s===0?null:s*o.usdPerArticle*$p}var Dy=.7,$p=1.4;function Ny(e){let t=Math.max(1,Math.round(e*Dy)),n=Math.max(t,Math.round(e*$p));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 jy(e){let t=e*Dy,n=e*$p;return n>=10?`$${Math.round(t)}\u2013${Math.round(n)}`:`$${t.toFixed(2)}\u2013${n.toFixed(2)}`}function Dr(e){try{return e()}catch{return null}}function ll(e,t,n,o){if(n<4||o<1)return null;let r=Cy({cmd:t,scope:void 0,flags:new Set,args:[]}),s=Math.ceil(o/r.concurrency),i=Dr(()=>kp(e,t)),a=s*(i?.minutesPerWave??r.minutesPerBatch),l=i?.usdPerArticle!==void 0?` \xB7 ~${jy(n*i.usdPerArticle)}`:"";return`~${Ny(a)}${l}`}import{renderGapsForPrompt as Gy}from"document360-engine";import{recordRunSample as TA}from"document360-engine";se();import{readProjectConfig as fA,loadProfileMap as mA,resolveActiveProfile as gA,desiredCategoryOrder as wA,desiredArticleOrder as yA}from"document360-engine";function Iy(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}var Ly=e=>e.replace(/\\/g,"/").split("/").pop()??e;function Zs(e,t){try{if(!fA(e))return[];let n=gA(e,t),o=mA(e,n.name);if(!o)return[];let r=new Map;for(let i of yA(o)){let a=r.get(i.categoryPath);a?a.push(i):r.set(i.categoryPath,[i])}let s=[];for(let i of wA(o)){s.push(Iy(Ly(i.path)));for(let a of(r.get(i.path)??[]).sort((l,d)=>l.order-d.order))s.push(` ${Iy(Ly(a.path))}`)}return s}catch{return[]}}async function Oy(e,t){let n=Zs(t.cwd,t.profileName);if(n.length===0)return console.log(m("No documentation structure yet \u2014 run /init and author some articles first.")),{kind:"continue"};console.log(Z("Documentation order (categories \u2192 articles):"));for(let o of n)console.log(o);return console.log(""),{kind:"continue"}}function xp(e,t){return Cs(e,Nr(e,t))}function Rp(e,t){return SA(e,Nr(e,t),PA)}function ei(e){return e.includes("--blocked")||e.includes("--stale")}function Po(e,t,n){return t.includes("--blocked")?xp(e,n):t.includes("--stale")?Rp(e,n):Nr(e,n)}function qy(e,t,n){let o;try{o=CA(e)}catch{return[]}let r=new Map(o.map(i=>[i.path.replace(/\\/g,"/"),i])),s=[];for(let i of n){let a=i.replace(/\\/g,"/").replace(`${t}/`,""),l=r.get(a);l&&s.push({path:i,type:l.type,...l.purpose?{purpose:l.purpose}:{}})}return s}function Vy(e,t){let n=Uy(e);if(!n)return null;let o=(n.docsDir??Wy).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),s=ei(t),i=t.find(T=>!T.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),a=cl({cwd:e}),l=i?bA(o,i):"",d=l?a.filter(T=>T.path===`${o}/${l}`||T.path.startsWith(`${o}/${l}/`)):a,w=s?Po(e,t,i):void 0,g=w?d.filter(T=>w.includes(T.path)):d,$=i||s?"":Zs(e).join(`
|
|
422
|
+
`),P=Fy(e,n),C=My({docsRoot:o,scope:i,styleGuide:_y(e),deterministicFindings:g,fix:r,structure:$||void 0,screenshots:P,...w?{paths:w}:{},reviewerNotes:Hy(By(e),w??Nr(e,i)),openGaps:Gy(e,w??Nr(e,i)),planRows:qy(e,o,w??Nr(e,i))}),R=t.includes("--blocked")?" --blocked":t.includes("--stale")?" --stale":"";return{prompt:C,display:`/review${i?` ${i}`:""}${R}${r?" --fix":""}`}}var AA=e=>"ruleId"in e,Hn=3,vp=3;function Sp(e,t){let n=Vy(e,t);if(!n)return null;let o=t.find(P=>!P.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),r=Po(e,t,o),s=kA(r,{maxPerPartition:vp});if(s.length<=1)return{kind:"single",...n};let i=Uy(e),a=(i?.docsDir??Wy).replace(/\\/g,"/").replace(/\/+$/,""),l=t.includes("--fix"),d=_y(e),w=cl({cwd:e}),g=By(e),$=Fy(e,i);return{kind:"partitioned",partitions:s,articles:r.length,wholeKb:!o&&!ei(t),display:n.display,promptFor:P=>{let C=new Set(P.paths);return My({docsRoot:a,styleGuide:d,deterministicFindings:w.filter(R=>C.has(R.path)),fix:l,screenshots:$,paths:P.paths,reviewerNotes:Hy(g,P.paths),openGaps:Gy(e,P.paths),planRows:qy(e,a,P.paths)})}}}function Cp(e,t){if(!ei(t))return null;let n=t.find(g=>!g.startsWith("--"));if(Po(e,t,n).length>0)return null;let o=t.includes("--blocked"),r=!!n&&n.endsWith(".md"),s=n?r?" here":` in ${n}`:"",a=o?`\u2713 Nothing is blocked${s} \u2014 ${n&&r?"it has":"every article has"} been through an editorial read.`:`\u2713 ${r?"This article has":`Every article${s} has`} already been read by the current editor \u2014 nothing to re-read.`,l=`/push${n?` ${n}`:" --all"}`,d=Yt(e,{text:`${l} saves ${r?"it":"what has changed"} to Document360 as ${r?"a draft":"drafts"}.`,cmd:l},"",n,"/review"),w=Tt(e,Vy(e,t)?.display??"");return{lines:[a,` ${d.text}`],closed:w,cta:d}}async function Yy(e,t){let n=Cp(t.cwd,e);if(n){console.log(Y(n.lines[0]));for(let r of n.lines.slice(1))console.log(m(r));for(let r of n.closed)console.log(Y(r));return{kind:"continue",ownNext:!0}}if(Un("review",e)){let r=Rr(t.cwd,"review",e,t.profileName);if(r.length>0){for(let s of r)console.log(m(s));return{kind:"continue"}}}let o=Sp(t.cwd,e);return o?o.kind==="single"?{kind:"forward-to-agent",prompt:o.prompt,display:o.display}:await EA(t,o,e.includes("--fix"),e.find(r=>!r.startsWith("--"))):(console.log(_("No d360-writer config here. Run /init first.")),{kind:"continue"})}async function EA(e,t,n,o){let{model:r}=xA(e.cwd,"standard"),s=ll(e.cwd,"/review",t.articles,t.partitions.length);console.log(m(`Reviewing ${t.articles} article${t.articles===1?"":"s"} in ${t.partitions.length} batches (\u2264${Hn} editors at once) on ${r}${n?", applying fixes":", report only"}${s?` \xB7 ${s}`:""}\u2026`));let i=Date.now(),a=new br;a.start();let l={aborted:!1,partitions:0,failed:0,notRun:0,producedNothing:!0};try{for await(let $ of $A({cwd:e.cwd,partitions:t.partitions,promptFor:t.promptFor,concurrency:Hn,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:r,scope:"review"}))if($.type==="partition_status")$.status==="running"?console.log(m(` \u25B8 ${$.label} \u2014 reviewing\u2026`)):$.status==="done"?console.log(Y(` \u2713 ${$.label}`)):console.log(_(` \u2717 ${$.label}`));else if($.type==="run_done"){let P=vA(t.partitions,$.results);l={aborted:!!$.aborted,partitions:t.partitions.length,failed:P.failed.length,notRun:P.notRun.length,...$.blocked?{blocked:$.blocked}:{},...$.allEmpty?{allEmpty:!0}:{},...$.bailedEmpty?{bailedEmpty:!0}:{}},console.log(""),console.log(`${$.results.length-P.failed.length}/${t.partitions.length} batches reviewed.`),P.failed.length&&console.log(V(`\u26A0 ${P.failed.length} not reviewed: ${P.failed.map(R=>R.label).join(", ")}`)),P.notRun.length&&console.log(V(`\u26A0 ${P.notRun.length} batch${P.notRun.length===1?"":"es"} never started \u2014 their articles are untouched.`)),$.blocked&&console.log(V(`\u26A0 ${$.blocked}`)),$.allEmpty&&console.log(V("\u26A0 No editor produced any work this run \u2014 nothing was reviewed or changed."));for(let R of Pp(t))console.log(m(R));if(n&&!$.allEmpty&&!$.blocked)try{RA(e.cwd,P.covered,ut("review"))}catch{}let C=a.stop();if(console.log(m(tn(Dt(i,$.results,$.totalCostUsd,Date.now(),C.activeSeconds)))),!$.allEmpty&&!$.blocked){let R=$.results.filter(T=>T.ok).length;TA(e.cwd,"review",{articles:P.covered.length,waves:Math.ceil(R/Math.max(1,Hn)),seconds:C.activeSeconds,costUsd:$.totalCostUsd})}}}catch($){return a.stop(),console.log(_(`Review failed: ${$.message}`)),{kind:"continue"}}if(a.stop(),n&&qt(l))for(let $ of Tt(e.cwd,t.display))console.log(Y($));if(!n)return{kind:"continue"};let d=xr(e.cwd,["--fix"],cl({cwd:e.cwd,scope:o}));for(let $ of d.lines)console.log($);let g=cl({cwd:e.cwd,scope:o}).filter($=>!$.baselined).filter($=>AA($)&&$.severity==="error");if(console.log(""),g.length>0){let $=Re("/lint","--blocked --fix",o);console.log(m(`Editor applied its fixes, but ${g.length} style error${g.length===1?"":"s"} remain \u2014 ${$} clears them (finding them costs nothing, one pass corrects them). It is the last paid pass before publishing: anything still standing after a second attempt is reported for a person rather than run again.`))}else console.log(m(Yt(e.cwd,{text:"\u2713 Reviewed and fixed. /push --all saves the articles to Document360 as drafts.",cmd:"/push --all"},"",o).text));return{kind:"continue",ownNext:!0}}function Pp(e){return e.partitions.length<2?[]:[`Each editor saw one slice of the docs, so reading order and terminology drift ${e.wholeKb?"ACROSS categories":"ACROSS the rest of the knowledge base"} were not judged.`,"/structure shows the reading order if you want to check it yourself."]}se();import{readProjectConfig as DA}from"document360-engine";function Tp(e,t){if(!DA(e))return null;let n=t.find(r=>!r.startsWith("--"));return{prompt:[`Reorder the articles within ${n?`the "${n}" category`:"each category"} to the best reading order.`,"Follow the manage-structure skill: decide the ideal order with senior-editor judgment per the doc-genre","playbook (overview / mental-model first; reference and troubleshooting/FAQ last), then APPLY it with the","d360_reorder_articles tool: one category at a time, all paths in the same category folder.",n?"":"If the CATEGORY order itself reads wrong too, fix that first with the d360_reorder_categories tool (folder paths under one parent, in the desired order).","Do not rename files or folders or edit the map by hand; the tools handle it. Report the new order, and","remind me it reaches Document360 on the next /push."].filter(Boolean).join(`
|
|
423
|
+
`),display:`/reorder${n?` ${n}`:""}`}}async function Ky(e,t){if(Un("reorder",e)){let o=Rr(t.cwd,"reorder",e,t.profileName);if(o.length>0){for(let r of o)console.log(m(r));return{kind:"continue"}}}let n=Tp(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(_("No d360-writer config here. Run /init first.")),{kind:"continue"})}se();import{computeReadiness as NA,readinessPlaceholderPlaces as jA}from"document360-engine";import Ye from"picocolors";var Ap=5;function Ze(e,t=58){let n=e.replace(/\\/g,"/");return n.length<=t?n:`\u2026${n.slice(n.length-t+1)}`}function IA(e){let t=[],n=e.verdict;if(e.conflicts.length>0&&t.push({glyph:"\u2717",paint:Ye.red,title:`Changed here and on Document360 (${e.conflicts.length})`,fix:"/resolve",items:e.conflicts.map(o=>Ze(o))}),n.unreviewed.length>0&&t.push({glyph:"\u2717",paint:Ye.red,title:`Never read by an editor (${n.unreviewed.length})`,fix:"/review --blocked --fix",items:n.unreviewed.map(o=>Ze(o))}),n.styleErrors.length>0){let o=n.styleErrors.reduce((r,s)=>r+s.errors,0);t.push({glyph:"\u2717",paint:Ye.red,title:`Break house style rules your config makes blocking (${o} error${o===1?"":"s"})`,fix:"/lint --blocked --fix",items:n.styleErrors.map(r=>`${Ze(r.path)} (${r.errors})`)})}if(n.placeholders.length>0){let o=jA(e);t.push({glyph:"\u2717",paint:Ye.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=>`${Ze(r.path)} (${r.missingShots.length+r.orphans})`)})}return t}function LA(e){let t=e.verdict,n=[];return e.conflicts.length===0&&n.push(`${J("\u2713",Ye.green)}Nothing is in conflict with Document360`),t.unreviewed.length===0&&n.push(`${J("\u2713",Ye.green)}Every article has been read by an editor`),t.styleErrors.length===0&&n.push(`${J("\u2713",Ye.green)}House style: nothing blocking`),t.placeholders.length===0&&n.push(`${J("\u2713",Ye.green)}No placeholder text would reach a reader`),n}function OA(e,t){if(e.rows.length===0)return[];let n=r=>r?Ye.green("\u2713"):Ye.red("\u2717"),o=e.rows.map((r,s)=>[String(s+1),Ze(r.path,46),n(r.reviewed),r.styleErrors===0?Ye.green("\u2713"):Ye.red(`\u2717 ${r.styleErrors}`),r.placeholders===0?Ye.green("\u2713"):Ye.red(`\u2717 ${r.placeholders}`),r.conflict?Ye.red("conflict"):r.draftPending?Ye.yellow("draft"):r.localAhead?m("not saved"):m("\u2014")]);return Es(["#","Article","Read","Style","Pictures","Document360"],o,t).split(`
|
|
424
|
+
`)}function Ep(e,t={}){let n=NA(e,t.profileName),o=[];if(n.rows.length===0)return o.push(Z("Publish readiness")),o.push(""),o.push(n.tracked===0?`${J("\u25CB",Ye.gray)}No articles are tracked yet. /write authors them, /push saves them to Document360.`:`${J("\u2713",Ye.green)}All ${n.tracked} articles are live and unchanged \u2014 nothing is waiting on you.`),n.orphans.length>0&&o.push(...zy(n)),o.push(""),o.push(m(" Free \u2014 /status reads your local files and the last sync. It calls nothing.")),o;let r=n.rows.length,s=n.blocked.length;o.push(Z("Publish readiness")+m(` ${r} article${r===1?"":"s"} not yet settled with readers \xB7 ${s===0?"nothing blocked":`${s} blocked`}`)),o.push(""),t.all&&(o.push(...OA(n,t.width??100)),o.push(""));for(let l of IA(n)){o.push(` ${J(l.glyph,l.paint)}${l.title}${l.fix?m(` ${l.fix}`):""}`);for(let d of l.items.slice(0,Ap))o.push(m(` ${d}`));l.items.length>Ap&&o.push(m(` \u2026and ${l.items.length-Ap} more`)),o.push("")}let i=LA(n);if(i.length>0){for(let l of i)o.push(` ${l}`);o.push("")}let a=n.rows.filter(l=>l.localAhead).length;return a>0&&o.push(m(` ${a} changed here \u2014 /push saves ${a===1?"it":"them"} to Document360 as ${a===1?"a draft":"drafts"}. Readers see nothing until then.`)),n.draftPending.length>0&&o.push(m(` ${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(...zy(n)),!t.all&&n.rows.length>0&&o.push(m(" /status --all shows every article, gate by gate.")),o.push(""),o.push(m(" Free \u2014 /status reads your local files and the last sync. It calls nothing.")),o}function zy(e){let t=e.orphans.length;return[m(` ${t} article${t===1?"":"s"} on Document360 ${t===1?"is":"are"} not in your docs folder (${Ze(e.orphans[0].path,40)}${t>1?`, +${t-1} more`:""}) \u2014 /doctor lists ${t===1?"it":"them"}.`)]}async function Xy(e,t){let n=e.some(o=>o==="--all"||o==="--full");for(let o of Ep(t.cwd,{profileName:t.profileName,all:n}))console.log(o);return{kind:"continue",ownNext:!0}}se();import{computeReadiness as _A,retireArticle as MA,retiredPaths as FA,normalizeScope as UA}from"document360-engine";import{select as WA}from"@inquirer/prompts";function Dp(e,t){let n=_A(e,t),o=FA(e,t),r=[Z("Take an article off your readers"),""];if(n.orphans.length>0){r.push(` ${J("\u25CB",m)}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(m(` ${Ze(s.path)}`));n.orphans.length>8&&r.push(m(` \u2026and ${n.orphans.length-8} more`)),r.push("")}if(o.length>0){r.push(` ${J("\u2713",m)}Already retired \u2014 readers do not see ${o.length===1?"it":"these"}:`);for(let s of o.slice(0,5))r.push(m(` ${Ze(s)}`));o.length>5&&r.push(m(` \u2026and ${o.length-5} more`)),r.push("")}return n.orphans.length===0&&o.length===0&&(r.push(m(" Nothing obvious to retire \u2014 every tracked article is still in your docs folder.")),r.push("")),r.push(m(" /retire <path> takes one off your readers. Any tracked article can be named, not just these.")),r.push(m(" Nothing is deleted: the article, its history and every reviewer comment stay on Document360.")),r.push(m(" /push puts one back \u2014 reviving is a publish like any other, with the same review.")),r}async function Qy(e,t){let n=t.cwd,o=e.find(a=>!a.startsWith("-"));if(!o){for(let a of Dp(n,t.profileName))console.log(a);return{kind:"continue",ownNext:!0}}let r=UA(n,o)||o;if(!(e.includes("--yes")||e.includes("-y"))&&(console.log(""),console.log(V(`This takes "${Ze(r)}" off your readers on Document360.`)),console.log(m(" The article, its history and every reviewer comment stay \u2014 nothing is deleted.")),console.log(m(" /push puts it back later if you change your mind.")),console.log(""),await WA({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(m("Nothing changed.")),{kind:"continue",ownNext:!0};let i=await MA({cwd:n,path:r,profileName:t.profileName,now:new Date().toISOString()});return i.ok?(console.log(i.alreadyHidden?`${J("\u2713")}"${Ze(r)}" was already invisible to readers. Recorded as retired, so nothing will offer to publish it again.`:`${J("\u2713")}"${Ze(r)}" is no longer visible to your readers.`),console.log(m(" It is still on Document360 with its history and comments intact. /push puts it back.")),{kind:"continue",ownNext:!0}):(console.log(_(`${J("\u2717")}Could not retire "${Ze(r)}" \u2014 ${i.error.message}`)),{kind:"continue",ownNext:!0})}se();import{scanTerminology as Jy,approvalBlockedReason as Zy,readProjectConfig as BA,writeProjectConfig as HA,termKey as Np,HEAD_NOUN_CAP as GA}from"document360-engine";import Kt from"picocolors";var qA=3,VA=e=>e.uses.map(t=>`${Kt.bold(t.form)} ${m(`${t.files.length} article${t.files.length===1?"":"s"}`)}`).join(m(" \xB7 "));function jp(e,t={}){let n=Jy(e,t.scope?{scope:t.scope}:{}),o=[];if(n.scanned===0)return[Z("Terminology"),"",`${J("\u25CB",m)}No articles to read yet.`,""];let r=n.variance.length+n.headings.length;if(o.push(Z("Terminology")+m(` ${n.scanned} article${n.scanned===1?"":"s"} read \xB7 ${r===0?"nothing inconsistent":`${r} to look at`}`)),o.push(""),n.variance.length>0){o.push(` ${J("\u2717",Kt.red)}The same term, spelled more than one way`);for(let s of n.variance){o.push(` ${VA(s)}`);let i=s.uses[s.uses.length-1],a=i.files.slice(0,qA);o.push(m(` "${i.form}" is in ${a.map(d=>Ze(d,40)).join(", ")}${i.files.length>a.length?`, +${i.files.length-a.length} more`:""}`));let l=Zy(s);l?o.push(m(` ${l}`)):o.push(m(` /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,GA);o.push(` ${J("\u25CB",m)}Possibly the same thing under a short name \u2014 ${Kt.italic("your call")}`);for(let i of s)o.push(m(` ${i.uses.map(a=>a.form).join(" \xB7 ")}`));n.headNouns.length>s.length&&o.push(m(` \u2026and ${n.headNouns.length-s.length} more \u2014 /terms --all lists them`)),o.push(m(' A shared word is not proof of a shared meaning: "billing history" and "history" are')),o.push(m(" different things. Nothing is flagged as wrong here.")),o.push("")}if(n.headings.length>0){o.push(` ${J("\u26A0",Kt.yellow)}Titles out of step with the rest of their kind`);for(let s of n.headings)o.push(` ${Kt.bold(s.title)} ${m(`\u2014 ${Ze(s.path,40)}`)}`),o.push(m(` the other ${s.peers} ${s.type} article${s.peers===1?"":"s"} look like "${s.example}"; this one starts ${YA(s.shape)}`));o.push("")}return r===0&&n.headNouns.length===0&&(o.push(` ${J("\u2713",Kt.green)}Every term is spelled one way, and every title matches its kind.`),o.push("")),o.push(m(' This compares spellings, not meanings: two different words for one thing (say "nav" and')),o.push(m(' "rail") look unrelated to it. Add the pair to your approved terms and every run enforces it.')),o.push(m(" Free \u2014 this read your articles and called nothing.")),o}function YA(e){return e==="gerund"?"with an -ing word":e==="how-to"?'with "How to"':"differently"}function Ip(e,t,n){let o=n??Jy(e),r=Np(t),s=o.variance.find(g=>g.uses.some($=>Np($.form)===r));if(!s)return{wrote:!1,lines:[`${J("\u2717",Kt.red)}"${t}" is not one of the terms with competing spellings. /terms lists them.`]};let i=Zy(s);if(i)return{wrote:!1,lines:[`${J("\u2717",Kt.red)}That one cannot be recorded: ${i}.`,m(` The spellings in play are ${s.uses.map(g=>`"${g.form}"`).join(" and ")}.`)]};let a=s.uses.find(g=>Np(g.form)===r).form,l=s.uses.filter(g=>g.form!==a).map(g=>g.form),d=BA(e);if(!d)return{wrote:!1,lines:[`${J("\u2717",Kt.red)}No project configuration here \u2014 run /init first.`]};let w={...d.terminologyGlossary??{}};for(let g of l)w[g]=a;return HA({...d,terminologyGlossary:w},e),{wrote:!0,lines:[`${J("\u2713",Kt.green)}"${a}" is now the approved spelling.`,m(` Added to your approved terms: ${l.map(g=>`"${g}" \u2192 "${a}"`).join(", ")}`),m(" Every run enforces it from now on, and /lint --fix corrects the others for free.")]}}async function eb(e,t){let n=e.findIndex(s=>s==="--approve");if(n!==-1){let s=e[n+1];if(!s)return console.log(`${J("\u2717",Kt.red)}Name the spelling to approve, e.g. /terms --approve "drop-down".`),{kind:"continue",ownNext:!0};for(let i of Ip(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 jp(t.cwd,{...r?{scope:r}:{},all:o}))console.log(s);return{kind:"continue",ownNext:!0}}se();import{readProjectConfig as KA,writeProjectConfig as tb,isAppType as zA,playbookSkillName as XA,detectAppType as nb}from"document360-engine";var ob=["web","cli","service","library"],QA=new Set(["web","cli"]);function Lp(e){return QA.has(e)?`${XA(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function ul(e,t){let n=t.cwd,o=KA(n);if(!o)return console.log(_("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let s=o.appType??nb(n);if(s){let i=o.appType?"set in config":"auto-detected";console.log(`${Z("Genre:")} ${s} (${i}) \u2014 ${Lp(s)}`)}else console.log(V("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(m(`Set it: /genre <${ob.join("|")}> \xB7 revert to auto-detect: /genre auto`)),{kind:"continue"}}if(r==="auto"||r==="clear"){if(!o.appType)return console.log(m("Already on auto-detect (no genre set in config).")),{kind:"continue"};let{appType:s,...i}=o;tb(i,n);let a=nb(n);return console.log(Y(`\u2713 Genre reset to auto-detect \u2014 now: ${a?`${a} (${Lp(a)})`:"unclassified (no playbook)"}.`)),console.log(m(" Restarting the agent so the loaded playbook matches\u2026")),{kind:"clear"}}return zA(r)?(tb({...o,appType:r},n),console.log(Y(`\u2713 Genre set to ${r} \u2014 ${Lp(r)}.`)),console.log(m(" Restarting the agent so the playbook loads\u2026")),{kind:"clear"}):(console.log(_(`Unknown genre "${r}". Choose one of: ${ob.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}var rb={help:Sc,"?":Sc,clear:Rf,exit:Cc,quit:Cc,init:jc,mcp:Xi,push:$a,publish:lg,audit:(e,t)=>Ps({cwd:t.cwd,profileName:t.profileName}),discover:dg,scope:hg,pull:Pg,resolve:Rg,convert:Gg,write:sw,draft:uw,document:dw,resume:fw,rename:mw,profile:ww,model:kw,doctor:Us,logs:yf,workspace:Sw,project:Cw,"allow-prod":Pw,login:Tw,logout:Aw,screenshot:async(e,t)=>{let n=ks(e);return n.mode==="capture"?Md(n.rest,t):n.mode==="annotate"?Hd(n.rest,t):n.mode==="verify"?Ew(n.rest,t):n.mode==="checklist"?Tr(e,t):ha(e,t)},capture:Md,annotate:Hd,"capture-setup":Tr,devhints:If,inbox:zw,ask:Qw,"catch-up":ny,comments:ly,update:uy,reset:my,lint:rd,check:Xg,"style-guide":al,review:Yy,reorder:Ky,structure:Oy,status:Xy,retire:Qy,terms:eb,genre:ul,roadmap:Km,share:ey,auto:ug};function sb(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 JA}from"node:child_process";import{recordAnalyzedCommit as ZA,resolveActiveProfile as eE}from"document360-engine";function tE(e){try{let t=JA("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 ti(e,t){try{let n=tE(e);if(!n)return null;let o=eE(e,t);return ZA(e,o.name,n)?n:null}catch{return null}}Dn();var ib="Or just tell me what to write or update.";function nE(e,t,n={}){let o=n.onlyScreenshots?"\u2713 Your writing is done \u2014 nothing is waiting to be written, reviewed, saved or taken live. Readers are seeing every article you have.":"\u2713 That\u2019s the full round trip \u2014 nothing is waiting to be written, reviewed, saved or taken live. Readers are seeing every article you have.";return n.listed?o:`${o}
|
|
425
|
+
|
|
426
|
+
Optional from here: ${e} of your ${t} docs campaign step${ye(t)} ${e===1?"is":"are"} still open (/roadmap shows them).`}var oE="Screenshots are the only thing still open \u2014 a separate job, and none of it changes your text:",rE="Optional depth, when you want it:",sE="Writing",iE="Screenshots \u2014 a separate job from the writing";function aE(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 lE='\u{1F4ED} No docs yet for this repo. Tell me "write the docs for this repo" and I\u2019ll read the code and draft a structure \u2014 or /audit to see what the docs should cover.';function ye(e){return e===1?"":"s"}function cE(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 lb(e,t){return e.length===t.length&&e.every((n,o)=>n===t[o])}function ab(e,t=150,n=1){let o=(e??"").replace(/\s+/g," ").trim();if(!o)return null;let r=/[.!?]\s+(?=["“'(A-Z])/g,s=o;for(let l=0;l<n;l++){let d=r.exec(o);if(!d)break;s=o.slice(0,d.index+1)}if(s.length<=t)return s;let i=s.slice(0,t),a=i.lastIndexOf(" ");return`${(a>t*.6?i.slice(0,a):i).replace(/[,;:]$/,"")}\u2026`}function Ir(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 To="write the docs for this repo",pl={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 uE(e,t){let n=[];if(e.sunsetEnv){let r=e.sunsetEnv,s=r.replacementProfile?`/profile ${r.replacementProfile}`:`/profile add ${r.replacement}`;n.push({key:"environment",bullet:`this repo publishes to the ${r.name} environment, which is being retired (${r.replacement} is the current one)`,lead:{kind:"cmd",cmd:s,reason:r.replacementProfile?`it switches to your ${r.replacement} profile (then /login if it asks)`:`it creates a ${r.replacement} profile and switches to it (then /login picks the project)`},picker:null,follow:null,tone:"warn"})}if(e.devhints!=="current"&&e.builderStarted){let r=e.devhintsToVersion?`v${e.devhintsToVersion}`:"a newer version",s=e.devhints==="stale"&&e.devhintsCompletedVersion?` (your builder is on v${e.devhintsCompletedVersion})`:"";n.push({key:"devhints",bullet:`dev\u2194docs protocol moved to ${r}${s} \u2014 your docs aren\u2019t blocked`,lead:{kind:"cmd",cmd:"/devhints",reason:`one paste updates your builder to ${r}`},picker:null,follow:"Also run /devhints when you get a second \u2014 your builder\u2019s protocol is behind.",tone:"warn"})}if(e.genreUnknown&&n.push({key:"genre",bullet:"the doc genre isn\u2019t set \u2014 I can\u2019t load the right doc-craft playbook yet",lead:null,picker:pl,follow:"Then pick the doc genre below (it sets the playbook I write with)."}),e.styleRules){let r=e.styleRules.articles;n.push({key:"styleRules",bullet:r>0?`the writing rules for these docs were never settled \u2014 and ${r} article${ye(r)} ${r===1?"is":"are"} already written to them`:"the writing rules for these docs aren\u2019t settled yet \u2014 worth answering before I write anything",lead:null,picker:{title:r>0?`Which writing rules should these docs follow? (${r} article${ye(r)} already written \u2014 changing this later means rewriting them)`:"Which writing rules should these docs follow? (this shapes every article I write)",lead:r>0?"Settle the writing rules below \u2014 one keypress. Keeping what you have is the usual answer once articles exist.":"Settle the writing rules below \u2014 one keypress, before I write anything to them.",exclusive:!0,options:e.styleRules.presets},follow:"Then settle the writing rules below \u2014 it shapes every article, and it gets dearer to change the longer it waits."})}if(e.autoChoice){let r=e.autoChoice.articles;n.push({key:"autoMode",bullet:r>0?`you haven\u2019t said whether I should run each step myself or wait for you \u2014 with ${r} article${ye(r)} 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 r=e.discovery.openQuestions;e.discovery.status==="pending"?n.push({key:"discovery",bullet:"your existing docs aren\u2019t grounded in a product brief yet",lead:{kind:"cmd",cmd:"/discover",reason:"it interviews your builder and grounds the docs before you rewrite or publish them"},picker:null,follow:"Then /discover grounds your docs in a product brief (do this before the rewrite/push steps)."}):r>0?n.push({key:"discovery",bullet:`product discovery is waiting on ${r} answer${ye(r)} from your builder \u2014 nudge them`,lead:null,picker:null,follow:"Discovery is waiting on your builder\u2019s answers \u2014 nudge them, then /catch-up folds the answers in once they reply."}):e.discovery.answersPending===0&&n.push({key:"discovery",bullet:"product discovery is ready to continue",lead:{kind:"cmd",cmd:"/discover",reason:"it continues interviewing your builder to ground the docs"},picker:null,follow:"Then /discover continues building the product brief."})}if(e.directives>0||e.pendingText){let r=e.directives>0&&e.pendingText?"it actions your directives and clears the builder\u2019s queue":e.directives>0?"it actions the directives you left":"it clears everything your builder queued",s=[];e.directives>0&&s.push(`${e.directives} owner directive${ye(e.directives)} waiting`);let i=e.discovery&&e.discovery.status!=="confident"?e.discovery.answersPending:0,a=i>0?` (${i} settle${i===1?"s":""} the product brief)`:"";e.pendingText&&s.push(`your builder left ${e.pendingText}${a}`),n.push({key:"catchup",bullet:s.join(`
|
|
427
|
+
\u2022 `),lead:{kind:"cmd",cmd:"/catch-up",reason:r},picker:null,follow:"Then /catch-up clears what\u2019s queued for the docs.",dependsOn:["discovery"]})}if(e.openComments>0){let r=e.openComments;n.push({key:"comments",bullet:`${r} reviewer comment${ye(r)} waiting on your articles`,lead:{kind:"cmd",cmd:"/comments",reason:"it shows what reviewers marked up in the portal, then lets you take it an article at a time"},picker:null,follow:`Then /comments shows the ${r} reviewer comment${ye(r)} waiting on your articles.`})}if(e.conflicts>0){let r=e.conflicts;n.push({key:"resolve",bullet:`${r} article${ye(r)} changed both here and on Document360 \u2014 /push skips ${r===1?"it":"these"}, and an audit can't trust your local copy until ${r===1?"it is":"they are"} settled`,lead:{kind:"cmd",cmd:"/resolve",reason:"it walks each one with you \u2014 keep yours, take the portal's, or skip"},picker:null,follow:`Then /resolve settles the ${r} article${ye(r)} changed in both places (keep yours / take the portal's / skip).`})}if(e.behind>0){let r=e.behind;n.push({key:"audit",bullet:`${r} code change${ye(r)} since your last docs check`,lead:{kind:"cmd",cmd:"/audit",reason:"it shows what the latest code changes touch (or /audit --auto on to run it for you)"},picker:null,follow:`After that, /audit covers the ${r} newer commit${ye(r)}.`,blockedBy:["resolve"]})}if(e.hasDocs&&e.pendingWrites>0){let r=e.pendingWrites;n.push({key:"write",bullet:`${r} planned article${ye(r)} still unwritten`,lead:{kind:"cmd",cmd:"/write",reason:"it finishes the articles already planned"},picker:null,follow:`Then /write finishes the ${r} planned article${ye(r)}.`,dependsOn:["genre","discovery","catchup","audit"]})}if(e.unreviewed>0){let r=e.unreviewed,s=Re("/review","--blocked --fix",e.unreviewedScope);n.push({key:"review",bullet:`${r} article${ye(r)} not yet live ${r===1?"carries":"carry"} text no editor has read`,lead:{kind:"cmd",cmd:s,reason:"these were written by an AI \u2014 it reads each one and applies its fixes, and nothing can be sent up or taken live until it has"},picker:null,follow:`Then ${s} reviews the ${r} unreviewed article${ye(r)} \u2014 nothing reaches your readers until it has.`,dependsOn:["catchup","comments"]})}if(e.styleErrors>0){let r=e.styleErrors,s=Re("/lint","--blocked --fix",e.styleErrorScope);n.push({key:"styleguide",bullet:`${r} article${ye(r)} not yet live break${r===1?"s":""} house style rules that block publishing`,lead:{kind:"cmd",cmd:s,reason:"finding them costs nothing and one pass corrects them in place \u2014 nothing can be sent up or taken live until it has"},picker:null,follow:`Then ${s} clears the style errors on ${r} article${ye(r)} \u2014 nothing reaches your readers until it has.`,dependsOn:["catchup","comments","review"]})}let o=e.shotsToAnnotate>0?{key:"annotate",bullet:`${e.shotsToAnnotate} screenshot${ye(e.shotsToAnnotate)} ${e.shotsToAnnotate===1?"has":"have"} been taken but ${e.shotsToAnnotate===1?"is":"are"} not finished \u2014 the callouts aren't drawn on, so ${e.shotsToAnnotate===1?"it cannot":"they cannot"} be published`,lead:{kind:"cmd",cmd:"/screenshot annotate",reason:"it draws the callouts on \u2014 no browser, about a second per picture"},picker:null,follow:`Then /screenshot annotate finishes the ${e.shotsToAnnotate} screenshot${ye(e.shotsToAnnotate)} already taken.`}:e.shotsToRecapture>0?{key:"annotate",bullet:`${e.shotsToRecapture} screenshot${ye(e.shotsToRecapture)} ${e.shotsToRecapture===1?"has":"have"} a plan for what to point at but no picture \u2014 the picture has to be taken again before anything can be drawn on it`,lead:{kind:"cmd",cmd:"/screenshot capture",reason:"it takes the picture again in a browser, and the callouts are drawn on straight after"},picker:null,follow:`Then /screenshot capture re-takes the ${e.shotsToRecapture} missing picture${ye(e.shotsToRecapture)}.`}:null;if(o&&e.localAhead>0&&n.push(o),e.localAhead>0){let r=e.localAhead;n.push({key:"publish",bullet:`${r} article${ye(r)} changed locally \u2014 ready to send to Document360`,lead:{kind:"cmd",cmd:"/push",reason:`it saves your ${r} local edit${ye(r)} to Document360 as drafts`},picker:null,follow:`Then /push saves your ${r} local edit${ye(r)} to Document360.`,dependsOn:["discovery","comments","audit","annotate"],blockedBy:["review","styleguide"]})}if(e.draftAhead>0){let r=e.draftAhead;n.push({key:"golive",bullet:`${r} article${ye(r)} ${r===1?"is":"are"} saved on Document360 but not live \u2014 your readers still see the previous version`,lead:{kind:"cmd",cmd:"/publish",reason:`it takes the ${r} draft${ye(r)} live to your readers \u2014 it lists them and asks first`},picker:null,follow:`Then /publish takes the ${r} draft${ye(r)} live \u2014 until it does, readers see the previous version.`,dependsOn:["comments"],blockedBy:["review","styleguide"]})}if(o&&e.localAhead===0&&n.push(o),e.hasDocs&&e.roadmap?.next){let r=e.roadmap,s=r.next,i=s.run?t?.scaleFor?.(s.run)??null:null,a=s.run?i:ab(s.body),l=s.run?i??void 0:ab(s.body,340,2)??void 0,d=`docs campaign: ${r.done} of ${r.total} step${ye(r.total)} done`,w=!!s.run&&cE(s.run,e.lastCommand);n.push(w?{key:"roadmap",bullet:`${d} \u2014 \u201C${s.title}\u201D is waiting on you
|
|
428
428
|
\u2022 You just ran ${s.run}. It showed you where things stand; the step stays open until you act on what it showed, or close it with /roadmap done.`,lead:null,picker:null,follow:null}:{key:"roadmap",bullet:`${d} \u2014 next: ${s.title}${a?`
|
|
429
429
|
\u2022 ${a}`:""}`,lead:s.run?{kind:"cmd",cmd:s.run,reason:"it\u2019s the next step of your docs campaign",...l?{detail:l}:{}}:{kind:"prompt",text:s.title,reason:"it\u2019s the next step of your docs campaign",...l?{detail:l}:{}},picker:null,follow:`Then the campaign continues: ${s.title} (/roadmap shows all ${r.total} steps).`,dependsOn:["genre","discovery","audit"],rowBullet:`${d} \u2014 this is next${a?`
|
|
430
430
|
\u2022 ${a}`:""}`})}if(e.handoff){let r=Math.max(e.handoff.unpushed,e.handoff.uncommitted>0?1:0),s=e.handoff.unpushed;r>0&&e.handoff.pushConsent==="unconfirmed"?n.push({key:"share",bullet:e.shareExplained?"your docs work is saved on this machine only \u2014 your team can't see it yet":["your docs work is saved on this machine only \u2014 your team can't see it yet","d360-writer keeps everything it produces in .d360-writer/ \u2014 your articles, the map linking","them to Document360, and the channel your builder leaves hints and answers in. It saves that","to git for you automatically, but it won't send anything to your team until you say so."].join(`
|
|
431
|
-
`),lead:{kind:"cmd",cmd:"/share",reason:"it sends your saved work to your team and brings back your builder's latest; after this once, I keep doing it for you"},picker:null,follow:null}):s>0&&n.push({key:"share",bullet:`\u26A0 ${s} docs change set${ye(s)} saved but not sent \u2014 someone else pushed to this branch first (your work is safe)`,lead:{kind:"cmd",cmd:"/share",reason:"it retries sending your saved work; if it keeps failing, your builder can merge the branch"},picker:null,follow:null})}else if(e.uncommittedDocs>0){let r=e.uncommittedDocs;n.push({key:"commit",bullet:`\u26A0 ${r} uncommitted change${ye(r)} under .d360-writer/ \u2014 tell your coding agent: "commit d360-writer's work"`,lead:null,picker:null,follow:null})}return n}function
|
|
432
|
-
`):N=[e,"",` ${
|
|
433
|
-
`),{note:[...o?[o]:[],N,
|
|
434
|
-
|
|
435
|
-
`),menu:T.map(I=>I.run??I.title)}}let i=
|
|
436
|
-
\u2022 `),N=C===i&&C.lead?.kind!=="answer"&&C.lead?.detail?[]:D;if(R&&C.lead){let X=T.replace(/^→\s+/,"");return[` ${R}. ${
|
|
437
|
-
`)}let
|
|
438
|
-
\u2022 `)}${
|
|
431
|
+
`),lead:{kind:"cmd",cmd:"/share",reason:"it sends your saved work to your team and brings back your builder's latest; after this once, I keep doing it for you"},picker:null,follow:null}):s>0&&n.push({key:"share",bullet:`\u26A0 ${s} docs change set${ye(s)} saved but not sent \u2014 someone else pushed to this branch first (your work is safe)`,lead:{kind:"cmd",cmd:"/share",reason:"it retries sending your saved work; if it keeps failing, your builder can merge the branch"},picker:null,follow:null})}else if(e.uncommittedDocs>0){let r=e.uncommittedDocs;n.push({key:"commit",bullet:`\u26A0 ${r} uncommitted change${ye(r)} under .d360-writer/ \u2014 tell your coding agent: "commit d360-writer's work"`,lead:null,picker:null,follow:null})}return n}function cb(e){return e.find(t=>t.lead||t.picker)??null}function dE(e){return e.kind==="cmd"?e.cmd:e.kind==="prompt"?`\u201C${e.text}\u201D`:""}function Lr(e){return e.kind==="cmd"?e.cmd:e.kind==="prompt"?e.text:null}function pE(e){return Lr(e)??""}function hE(e,t,n){let o=a=>(a??[]).map(l=>t.get(l)).filter(l=>l!==void 0&&l<n),r=a=>a.length===1?`${a[0]}`:`${a.slice(0,-1).join(", ")} and ${a[a.length-1]}`,s=o(e.blockedBy);if(s.length>0)return` (needs ${r(s)} first)`;let i=o(e.dependsOn);return i.length>0?` (better after ${r(i)})`:""}function dl(e,t,n,o=null,r,s=0){if(r&&r.length>0){let C=r.filter(fa),R=r.filter(I=>!fa(I)),T=[...R,...C],D=(I,X)=>` ${X+1}. ${I.title}${I.run?` \xB7 ${I.run}`:""}`,N;return C.length===0||R.length===0?N=[e,...T.map(D)].join(`
|
|
432
|
+
`):N=[e,"",` ${sE}`,...R.map((I,X)=>D(I,X)),"",` ${iE}`,...C.map((I,X)=>D(I,R.length+X))].join(`
|
|
433
|
+
`),{note:[...o?[o]:[],N,aE(T.length,n),ib].join(`
|
|
434
|
+
|
|
435
|
+
`),menu:T.map(I=>I.run??I.title)}}let i=cb(t),a=i?.picker?[]:t.filter(C=>C.lead),l=a.length>=2?a:[],d=new Map(l.map((C,R)=>[C.key,R+1])),w=[];i?.lead?w.push(Ir(i.lead)):i?.picker&&w.push(i.picker.lead);for(let C of t.filter(R=>R!==i&&!R.lead).slice(0,2))C.follow&&w.push(C.follow);l.length>=2&&n&&w.push(`Press 1\u2013${l.length} to pick a different one \u2014 the number fills the box, enter runs it.`);let g=w.join(" "),$=t.filter(C=>C.bullet).map(C=>{let R=d.get(C.key),[T="",...D]=(R&&C.lead?.kind==="prompt"&&C.rowBullet?C.rowBullet:C.bullet).split(`
|
|
436
|
+
\u2022 `),N=C===i&&C.lead?.kind!=="answer"&&C.lead?.detail?[]:D;if(R&&C.lead){let X=T.replace(/^→\s+/,"");return[` ${R}. ${dE(C.lead)} \u2014 ${X}${hE(C,d,R)}`,...N.map(de=>` ${de}`)].join(`
|
|
437
|
+
`)}let B=C.lead?.kind==="cmd"?C.lead.cmd:null;return` \u2022 ${[T,...N].join(`
|
|
438
|
+
\u2022 `)}${B&&!g.includes(B)?` \u2014 ${B}`:""}`}),P=o?[o,[e,...$].join(`
|
|
439
439
|
`)]:[[e,...$].join(`
|
|
440
|
-
`)];if(w.length&&P.push(w.join(" ")),s>0){let C=s;P.push(`${C} question${ye(C)} you asked your developers ${C===1?"is":"are"} still unanswered. Their reply arrives with your docs the next time either of you shares, and /inbox folds it in. Nothing is blocked meanwhile.`)}return P.push(
|
|
441
|
-
|
|
442
|
-
`),menu:l.map(C=>
|
|
443
|
-
|
|
444
|
-
${P}`:P;if(!e.ready)return{kind:"idle"};if(e.pendingAnswer)return{kind:"recommend",rec:{note:null,settled:null,tone:"info",lead:e.pendingAnswer.options>=2?{kind:"answer",options:e.pendingAnswer.options,reason:"the agent is waiting on your pick"}:null,picker:null,menu:[]}};let r=
|
|
445
|
-
`)){let o=n.trimEnd();if(/^\s*(```|~~~)/.test(o)){t=!t;continue}if(t)continue;let r=/^#\s+(\S.*)$/.exec(o);if(r)return
|
|
446
|
-
`)){if(n>t)break;let i=s.trimEnd();if(/^\s*(```|~~~)/.test(i))o=!o;else if(!o){let a=/^(#{2,6})\s+(\S.*)$/.exec(i);a&&(r=
|
|
447
|
-
`)){let n=t.replace(/^\s*(#{1,6}\s+|[-*+]\s+|>\s+|\d+[.)]\s+)/,"").replace(/^\s*\|/,"").trim();if(n)return
|
|
448
|
-
`).length;return{verb:"Draft",title:X,category:l,note:`new, ${
|
|
449
|
-
`)),category:l,note:P,articleKey:s,...
|
|
450
|
-
`);if(e==="Read"){let o=n.length,r=
|
|
451
|
-
`));return[`${o} line${o===1?"":"s"}${r?` \xB7 ${r}`:""}`]}if(e==="Glob"){if(/^no files found/i.test(t))return null;let o=n.filter(r=>r.trim()).length;return[`${o} file${o===1?"":"s"}`]}return e==="Grep"&&/^Found \d+/.test(n[0]??"")?[n[0]]:null}function
|
|
452
|
-
`).trimEnd();if(n&&
|
|
453
|
-
`);return{lines:s.slice(0,t).map(i=>Gn(i,
|
|
454
|
-
|
|
455
|
-
${Ce}`)}catch{}if(await
|
|
456
|
-
`))console.log(i(` ${a}`));s.rec.picker&&console.log(Z(` Pick one: ${s.rec.picker.options.map(a=>a.cmd).join(" \xB7 ")}`))}}catch{}}console.log(m(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}var
|
|
457
|
-
`))console.log(Y(` ${r}`))}else o.rec.settled&&!o.rec.lead&&console.log(m(" Nothing is waiting. /roadmap lists the optional campaign steps."));o.rec.lead&&console.log(m(` Next: ${
|
|
458
|
-
|
|
459
|
-
`);let l=[i.category,i.note].filter(w=>!!w).map(w=>xe(` \xB7 ${w}`)),d=i.loud?xe(" \xB7 ")+
|
|
460
|
-
|
|
461
|
-
`),console.log(`${xe("\u25CF")} ${a.title}${a.arg!==null?xe(`${a.sep}(${a.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let i=
|
|
462
|
-
`);let i=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(m(` (${
|
|
463
|
-
`),n=0;for(let s=t.length-1;s>=0;s--){let i=t[s];if(/^\s{0,3}\d{1,2}[.)]\s+\S/.test(i)){n++;continue}if(!(n>0&&/^\s+\S/.test(i)))break}return n<2?0:t.filter(s=>/^\s{0,3}\d{1,2}[.)]\s+\S/.test(s)).slice(-n).every((s,i)=>Number(/^\s{0,3}(\d{1,2})/.exec(s)[1])===i+1)?n:0}var
|
|
464
|
-
`),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){
|
|
465
|
-
`)}var
|
|
466
|
-
`).filter(s=>/^\s{0,3}\d{1,2}[.)]\s+\S/.test(s)).slice(-n).map(s=>{let i=s.replace(/^\s{0,3}\d{1,2}[.)]\s+/,"").trim(),a=
|
|
467
|
-
`).map(o=>o.trim()).filter(o=>o.length>3),n=t[t.length-1];return n?n.length>160?`${n.slice(0,157)}\u2026`:n:null}function
|
|
468
|
-
`)}var
|
|
469
|
-
\u2190/\u2192 or tab switch \xB7 1-5 jump${C+R>0?" \xB7 \u2191\u2193 scroll":""} \xB7 esc close \xB7 d360-writer v${r} \xB7 engine v${s}`})]})}var
|
|
470
|
-
`)){let i=s.trim().replace(
|
|
471
|
-
`)}function
|
|
472
|
-
`)||e.length>200}function
|
|
473
|
-
`).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function
|
|
474
|
-
`)){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
|
|
440
|
+
`)];if(w.length&&P.push(w.join(" ")),s>0){let C=s;P.push(`${C} question${ye(C)} you asked your developers ${C===1?"is":"are"} still unanswered. Their reply arrives with your docs the next time either of you shares, and /inbox folds it in. Nothing is blocked meanwhile.`)}return P.push(ib),{note:P.join(`
|
|
441
|
+
|
|
442
|
+
`),menu:l.map(C=>pE(C.lead))}}function ni(e,t){let n=t?.pickable===!0,o=P=>t?.header?`${t.header}
|
|
443
|
+
|
|
444
|
+
${P}`:P;if(!e.ready)return{kind:"idle"};if(e.pendingAnswer)return{kind:"recommend",rec:{note:null,settled:null,tone:"info",lead:e.pendingAnswer.options>=2?{kind:"answer",options:e.pendingAnswer.options,reason:"the agent is waiting on your pick"}:null,picker:null,menu:[]}};let r=uE(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(fa)&&e.roadmap.total-e.roadmap.done===i.length,l=s?nE(e.roadmap.total-e.roadmap.done,e.roadmap.total,{listed:i.length>0,onlyScreenshots:a}):null;if(!e.hasDocs){let P=cb(r);if(P&&(P.lead?.kind==="cmd"||P.picker)){let C=dl(t?.header??"\u{1F4ED} No docs yet for this repo \u2014 here\u2019s where things stand:",r,n,null,void 0,e.outboundQuestions);return{kind:"recommend",rec:{note:C.note,settled:null,tone:P.tone??"info",lead:P.lead,picker:P.picker,menu:C.menu}}}return{kind:"recommend",rec:{note:o(lE),settled:null,tone:"info",lead:{kind:"prompt",text:To,reason:"I\u2019ll read the code and draft a structure"},picker:null,menu:[]}}}if(r.length===0){let P=e.roadmap&&!e.roadmap.next?` Docs campaign complete \u2014 all ${e.roadmap.total} step${ye(e.roadmap.total)} done (/roadmap).`:"";return{kind:"recommend",rec:{note:o(`Welcome back. Your ${e.tracked} tracked article${ye(e.tracked)} for \u201C${e.profileName}\u201D are all in sync \u2014 /audit re-checks the code, /pull brings down portal edits.${P}`),settled:null,tone:"info",lead:null,picker:null,menu:[]}}}let d=r.filter(P=>P.lead||P.picker),w=d[0]??null;if(!w){let P=dl(t?.header??"Welcome back \u2014 where your docs stand:",r,n,null,void 0,e.outboundQuestions);return{kind:"recommend",rec:{note:P.note,settled:null,tone:"info",lead:null,picker:null,menu:P.menu}}}if((w.key==="audit"||d[1]?.key==="audit")&&e.behind>0&&e.autoAudit&&e.allowAutoAudit)return{kind:"autoAudit",note:o(`\u{1F4CB} ${e.behind} code change${ye(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`)};if(l){let P=dl(a?oE:rE,r,n,l,i,e.outboundQuestions);return{kind:"recommend",rec:{note:P.note,settled:l,tone:"info",lead:null,picker:null,menu:P.menu}}}let $=dl(t?.header??"Welcome back \u2014 where your docs stand:",r,n,l,void 0,e.outboundQuestions);return{kind:"recommend",rec:{note:$.note,settled:l,tone:w.tone??"info",lead:w.lead,picker:w.picker,menu:$.menu}}}import{existsSync as hl,readdirSync as Mp}from"node:fs";import{spawnSync as fE}from"node:child_process";import{join as fl}from"node:path";import{readProjectConfig as _p,resolveActiveProfile as hb,loadTokens as mE,isExpired as gE,loadProfileMap as fb,localAheadPaths as wE,loadKnownConflicts as yE,draftPendingPaths as bE,loadOpenCommentCount as kE,readDocsPlan as $E,devHintsGuidePath as vE,DEFAULT_DOCS_DIR as ml,roadmapProgress as xE,listRoadmap as ub,readProductBriefState as RE,readDiscoveryQueue as SE,reconcileCommitRequest as CE,reconcileTestidRequest as PE,snapshotHandoff as TE,shareExplainedPath as AE,unannotatedShotIds as EE,shotsNeedingRecapture as DE,resolveOutputDir as NE,DEFAULT_OUTPUT_DIR as jE,WRITER_DIRNAME as Op,styleGuideSettled as IE,autoModeSettled as LE,autoBudgetUsd as OE,listAvailablePacks as _E,listArticleFiles as db}from"document360-engine";Dn();var ME=5;function pb(e){try{return Mp(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function Fp(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>pb(fl(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&pb(fl(e,o)))}function Up(e,t){try{let n=_p(e);if(!n)return!1;let o=hb(e,t),r=fb(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=fl(e,(n.docsDir??ml).replace(/\/+$/,""));return!!(hl(s)&&Mp(s).length>0||hl(vE(e)))}catch{return!1}}function FE(e){let t=[`:(exclude)${Op}`],n=(e.docsDir??ml).replace(/\\/g,"/").replace(/\/+$/,"");return n&&!n.startsWith(`${Op}/`)&&n!==Op&&t.push(`:(exclude)${n}`),t}function UE(e,t,n){try{let o=fE("git",["rev-list","--count",`${t}..HEAD`,"--",".",...FE(n)],{cwd:e,encoding:"utf8",timeout:1200});return o.status===0&&parseInt((o.stdout||"").trim(),10)||0}catch{return 0}}function oi(e,t,n){try{let o=_p(e);if(!o)return null;let r=hb(e,t),s=mE(r.name,r.project.projectId),i=!!s&&(!gE(s)||!!s.refreshToken),a=Up(e,t)||!Fp(e,o.authoritativeSourceFiles),l=fb(e,r.name),d=l?Object.keys(l.articles).length:0,w=fl(e,(o.docsDir??ml).replace(/\/+$/,"")),g=!1;try{g=hl(w)&&Mp(w).length>0}catch{}let $=l?.lastAnalyzedCommit?UE(e,l.lastAnalyzedCommit,o):0,P=0;try{let be=(o.docsDir??ml).replace(/\/+$/,""),_e=$E(e,be);_e.length>0&&(P=Ln(e,be,_e.map(Kr=>Kr.path)).length)}catch{}let C=$n(e),R=Xa({...C,directives:0}),T=wE(e,t),D=new Set(yE(e,r.name)),N=T.filter(be=>D.has(be)).length,B=T.length-N,I=new Set(T),X=bE(e,t).filter(be=>!I.has(be)),q=X.length,de=[...T.filter(be=>!D.has(be)),...X],ve=Cs(e,de),Se=ve.length,Te=Zt(ve),he=null;try{if(!IE(o.styleGuide)){let be=_E(e).filter(_e=>_e.name.toLowerCase()!=="humanise");he={articles:db(e).length,presets:[{cmd:"/style-guide keep",desc:"the built-in rules only \u2014 correctness and anti-slop checks (nothing changes)"},...be.map(_e=>({cmd:`/style-guide use ${_e.name.toLowerCase()}`,desc:`${_e.name} style guide \u2014 ${_e.rules.length} more rules`}))]}}}catch{}let ie=null;try{LE(o)||(ie={articles:db(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 ${He(OE(o))} a run)`}]})}catch{}let te=0,Le;try{let be=ig(e,de);te=be.length,Le=Zt(be)}catch{}let je=0,Ce=0;try{let be=NE(e,_p(e)?.outputDir??jE);je=EE(be).length,Ce=DE(be).length}catch{}let Xe=kE(e,r.name),Xt=Gt(e),st=xE(e),It=st?{...st,open:ub(e).filter(be=>be.status==="open").slice(0,ME).map(be=>({title:be.title,...be.run?{run:be.run}:{},...be.stage?{stage:be.stage}:{}}))}:null,No=TE(e,o),Lt=CE(e,new Date().toISOString(),{supersededByHandoff:No!==null});PE(e,new Date().toISOString());let rn=Tn(e,t),jo=rn?{name:rn.name,replacement:rn.replacement,replacementProfile:rn.replacementProfile}:null,Io=RE(e),Vr=SE(e),Yr=Io?{status:Io.status,openQuestions:Vr.openQuestions,answersPending:Vr.answersPending}:null;return!Yr&&g&&ub(e).some(_e=>_e.status==="open"&&(_e.run??"").trim()==="/discover")&&(Yr={status:"pending",openQuestions:0,answersPending:0}),{ready:i&&a&&!n.claudeMissing,hasDocs:g,tracked:d,pendingText:R,directives:C.directives,behind:$,pendingWrites:P,localAhead:B,unreviewed:Se,unreviewedScope:Te,styleErrors:te,shotsToAnnotate:je,shotsToRecapture:Ce,styleErrorScope:Le,draftAhead:q,conflicts:N,openComments:Xe,outboundQuestions:Vs(e),autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:Xt.status,devhintsCompletedVersion:Xt.completedVersion,devhintsToVersion:Oe,builderStarted:mn(e),genreUnknown:n.genreUnknown,pendingAnswer:n.pendingAnswer??null,lastCommand:n.lastCommand??null,styleRules:he,autoChoice:ie,roadmap:It,discovery:Yr,uncommittedDocs:Lt.dirty.length,handoff:No,shareExplained:hl(AE(e)),sunsetEnv:jo}}catch{return null}}se();import{existsSync as HE,readFileSync as GE}from"node:fs";import{isAbsolute as qE,join as VE}from"node:path";import{DEFAULT_DOCS_DIR as YE,findPathByArticleId as KE,isArticleDocPath as zE,loadProfileMap as XE,readProjectConfig as QE,resolveActiveProfile as JE}from"document360-engine";function WE(){return process.platform==="win32"||process.platform==="darwin"}var BE=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function gl(e,t){let n=e.replace(/\\/g,"/"),o=`${BE(t)}/`,[r,s]=WE()?[n.toLowerCase(),o.toLowerCase()]:[n,o];return r.startsWith(s)?n.slice(o.length):null}var gb=70;function ZE(e,t){return{docsRoot:()=>(QE(e)?.docsDir??YE).replace(/\\/g,"/").replace(/\/+$/,""),read:n=>{try{let o=qE(n)?n:VE(e,n);return HE(o)?GE(o,"utf8"):null}catch{return null}},pathForArticleId:n=>{try{let o=XE(e,JE(e,t).name);return o?KE(o,n):null}catch{return null}}}}var Ao=(e,t=gb)=>{let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"};function ri(e){if(!e)return null;let t=!1;for(let n of e.split(`
|
|
445
|
+
`)){let o=n.trimEnd();if(/^\s*(```|~~~)/.test(o)){t=!t;continue}if(t)continue;let r=/^#\s+(\S.*)$/.exec(o);if(r)return Ao(r[1])}return null}var eD=new Set(["a","an","and","as","at","but","by","for","in","of","on","or","the","to","vs","with"]),tD=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 wb(e,t,n){let o=e.toLowerCase();return tD.has(o)?e.toUpperCase():!t&&eD.has(o)?o:!t&&!n?e:e.charAt(0).toUpperCase()+e.slice(1)}var yb=e=>e.replace(/^\d+[-_.]/,"").split(/[-_]/).filter(Boolean);function nD(e){let t=yb(e);return t.length===0?e:t.map((n,o)=>wb(n,o===0,!0)).join(" ")}function bb(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:nD(n[n.length-2])}function kb(e){let t=e.replace(/\\/g,"/").split("/").pop()??e,n=yb(t.replace(/\.(md|markdown)$/i,""));return n.length===0?t:n.map((o,r)=>wb(o,r===0,!1)).join(" ")}var oD=46;function rD(e,t){let n=0,o=!1,r=null;for(let s of e.split(`
|
|
446
|
+
`)){if(n>t)break;let i=s.trimEnd();if(/^\s*(```|~~~)/.test(i))o=!o;else if(!o){let a=/^(#{2,6})\s+(\S.*)$/.exec(i);a&&(r=Ao(a[2],gb))}n+=s.length+1}return r}function mb(e){for(let t of e.split(`
|
|
447
|
+
`)){let n=t.replace(/^\s*(#{1,6}\s+|[-*+]\s+|>\s+|\d+[.)]\s+)/,"").replace(/^\s*\|/,"").trim();if(n)return Ao(n,oD)}return null}var jt=e=>typeof e=="string"&&e?e:null,sD=e=>typeof e=="string"&&e.length>=8?`id ${e.slice(0,8)}\u2026`:null;function iD(e,t){return gl(e,t)??e.replace(/\\/g,"/")}function aD(e,t){let n=Et(e,t,200);return n?`+${n.added} \u2212${n.removed}`:"no change"}var lD=new Set(["Edit","MultiEdit","Write"]);function cD(e,t,n,o){if(!lD.has(e))return null;let r=jt(t.file_path);if(!r)return null;let s=iD(r,n),i=o.docsRoot();if(!(s===i||s.startsWith(`${i}/`)))return null;let a=s.slice(i.length+1);if(!a||!zE(a))return null;let l=bb(a),d=o.read(s),w=I=>ri(I)??ri(d)??kb(a);if(e==="Write"){let I=jt(t.content)??"",X=w(I);if(d===null){let q=I.replace(/\n$/,"").split(`
|
|
448
|
+
`).length;return{verb:"Draft",title:X,category:l,note:`new, ${q} lines`,articleKey:s}}return{verb:"Rewrite",title:X,category:l,note:aD(d,I),articleKey:s}}let g=Array.isArray(t.edits)?t.edits.map(I=>({from:jt(I.old_string)??"",to:jt(I.new_string)??""})):[{from:jt(t.old_string)??"",to:jt(t.new_string)??""}],$=g.reduce((I,X)=>{let q=Et(X.from,X.to,200);return q?{added:I.added+q.added,removed:I.removed+q.removed}:I},{added:0,removed:0}),P=$.added===0&&$.removed===0?"no change":`+${$.added} \u2212${$.removed}`,C=g[0],R=C&&d?rD(d,d.indexOf(C.from)):null,T=C?mb(C.to)??mb(C.from):null,D=g.length>1?` +${g.length-1} more`:"",N=T?`\u201C${T}\u201D${D}`:D.trim()||null,B=R?{title:`\u21B3 ${R}`,category:N,note:P}:N?{title:`\u21B3 ${N}`,category:null,note:P}:null;return{verb:"Update",title:w(g.map(I=>I.to).join(`
|
|
449
|
+
`)),category:l,note:P,articleKey:s,...B?{repeat:B}:{}}}function uD(e,t,n){let o=()=>{let r=jt(t.article_id),s=r?n.pathForArticleId(r):null;return(s?ri(n.read(s)):null)??(s?kb(s):sD(r)??"article")};switch(e){case"d360_create_article":{let r=jt(t.title);return r?{verb:"Create",title:Ao(r),category:bb(t.local_path),note:"Document360 draft"}:null}case"d360_update_article":return{verb:"Update",title:jt(t.title)?Ao(jt(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=jt(t.name);return r?{verb:"Create",title:Ao(r),category:null,note:"Document360 category"}:null}case"d360_upload_drive_file":{let r=jt(t.file_path);if(!r)return null;let s=r.replace(/\\/g,"/").split("/").pop()??r;return{verb:"Upload",title:Ao(s),category:null,note:"Document360 Drive",keepResult:!0}}default:return null}}function wl(e,t,n,o,r=ZE(n,o)){try{let s="mcp__document360__";return e.startsWith(s)?uD(e.slice(s.length),t,r):cD(e,t,n,r)}catch{return null}}var dD={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"},vb=160,Wp=200,xb=40;function Gn(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:pD(n)?"\u2026"+n.slice(n.length-(t-1)):n.slice(0,t-1)+"\u2026"}function pD(e){return!e.includes(" ")&&/[/\\]/.test(e)}function $b(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}: ${Gn(typeof r=="string"?r:JSON.stringify(r),xb)}`);return t.length>4&&n.push("\u2026"),Gn(n.join(", "),vb)}var hD=new Set(["file_path","notebook_path"]);function fD(e,t){return t?gl(e.replace(/\\/g,"/").replace(/\/+$/,""),t)??e:e}var Rb=e=>typeof e=="string"&&e?e:null;function mD(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});return e==="d360_sync_status"?n("Check sync status",null):null}function yl(e,t,n){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,s="",...i]=e.split("__"),a=i.join("__");if(s==="document360"){let w=mD(a,t);if(w)return w}let l=a.replace(/^d360_/,"").replace(/_/g," ");return{title:`${s==="document360"?"Document360":s.charAt(0).toUpperCase()+s.slice(1)}: ${l}`,sep:" ",arg:$b(t)}}let o=dD[e],r=o?t[o]:void 0;if(typeof r=="string"&&r){let s=o&&hD.has(o)?fD(r,n):r;return{title:e,sep:"",arg:Gn(s,vb)}}return{title:e,sep:"",arg:$b(t)}}function gD(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 wD(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(gD).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>Gn(r,Wp))]}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}: ${Gn(String(r),xb)}`);return n.length>0?[Gn(n.join(" \xB7 "),Wp)]:null}return null}function yD(e){let t=Rb(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function bD(e,t,n){switch(e){case"d360_create_article":{let o=yD(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=Rb(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 ${Gn(o[0],120)}`:""}`]}default:return null}}var Sb=new Set(["Edit","Write","MultiEdit","NotebookEdit"]);function kD(e){return e.replace(/^\s*\d+\t/,"")}function $D(e,t){if(Sb.has(e))return[];let n=t.split(`
|
|
450
|
+
`);if(e==="Read"){let o=n.length,r=ri(n.map(kD).join(`
|
|
451
|
+
`));return[`${o} line${o===1?"":"s"}${r?` \xB7 ${r}`:""}`]}if(e==="Glob"){if(/^no files found/i.test(t))return null;let o=n.filter(r=>r.trim()).length;return[`${o} file${o===1?"":"s"}`]}return e==="Grep"&&/^Found \d+/.test(n[0]??"")?[n[0]]:null}function bl(e,t=4,n,o){let r=e.replace(/\r\n/g,`
|
|
452
|
+
`).trimEnd();if(n&&Sb.has(n))return{lines:[],hidden:0};if(!r)return{lines:["(no output)"],hidden:0};if(n&&!n.startsWith("mcp__")){let i=$D(n,r);if(i)return{lines:i,hidden:0}}if(n?.startsWith("mcp__document360__")){let i=bD(n.slice(18),o,r);if(i)return{lines:i,hidden:0}}let s=wD(r)??r.split(`
|
|
453
|
+
`);return{lines:s.slice(0,t).map(i=>Gn(i,Wp)),hidden:Math.max(0,s.length-t)}}function kl(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function $l(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 Cb(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 vl(e){return Cb(e,"url")}function xl(e){return Cb(e,"preview_url")}function Pb(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 Ib=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/,Hp=null;function Eb(){return Hp===null&&(Hp=jD().verboseTranscript===!0),Hp}function YD(e,t,n,o){if(Ib.test(e))try{let r=jb(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,i=$l(t,n),a=vl(n);e.endsWith("publish_article")&&a&&console.log(Z(` \u2B95 Live: ${a}`));let l=xl(n);l?console.log(Z(` \u2B95 Preview: ${l}`)):i&&s&&console.log(Z(` \u2B95 Preview: ${kl(r.connection.portalUrl,s,i,r.project.languageCode??"en")}`))}catch{}}async function Lb(e=process.cwd(),t="auto",n,o){let r=xD(t);r.kind==="none"&&(console.error(""),console.error(_("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${Z("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${Z('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${Z("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${Z("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),KD(e,n);let s=RD(t),i=SD(s);console.log(i?V(` ${Tb(s)}`):m(` ${Tb(s)}`)),i?console.log(m(` ${i}`)):r.kind==="subscription"&&!r.stored&&console.log(m(" No sign-in found on this machine \u2014 trying your Claude session anyway.")),console.log("");let a=!1,l=Bp({cwd:e,profileName:n,allowProdWrites:a}),d={uuid:null,firstPrompt:null,titleFired:!1},w=vD({input:process.stdin,output:process.stdout}),g=[],$=null,P=!1;w.on("line",T=>{if($){let D=$;$=null,D(T)}else g.push(T)}),w.on("close",()=>{if(P=!0,$){let T=$;$=null,T(null)}});function C(){return g.length>0?Promise.resolve(g.shift()):P?Promise.resolve(null):(process.stdout.write(Z("> ")),new Promise(T=>{$=T}))}let R={cwd:e,version:o,profileName:n,allowProdWrites:()=>a,restartAgent:()=>{l.close(),l=Bp({cwd:e,profileName:n,allowProdWrites:a}),d={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>d.uuid,setPendingName:T=>{d.pendingName=T},setModel:async T=>l.setModel(T),withPausedInput:async T=>{w.pause();try{return await T()}finally{w.resume()}}};try{for(;;){let T=await C();if(T===null)break;let D=T.trim();if(D){if(D.startsWith("/")){let N=sb(D);if(!N)continue;let B=rb[N.name];if(!B){console.log(_(`Unknown command: /${N.name}`)),console.log(m("Type /help for the list."));continue}let I=await B(N.args,R);if(I.kind==="exit")break;if(I.kind==="clear"){R.restartAgent();continue}if(I.kind==="allow-prod"){a=!0,R.restartAgent(),console.log(Y("\u2713 Production writes authorized for this session.")),console.log("");continue}if(I.kind==="resume"){l.close(),l=Bp({cwd:e,resume:I.uuid,profileName:n,allowProdWrites:a});let X=CD(I.uuid);d={uuid:I.uuid,firstPrompt:X?.firstPrompt??null,titleFired:!0},Nb(I.uuid),console.log(Y(`\u2713 Resumed "${I.name}"`)),console.log("");continue}if(I.kind==="audit-blocked"){console.log(V(I.note)),console.log(m(` Run: ${I.lead.cmd} \u2014 ${I.lead.reason}.`)),console.log("");continue}if(I.kind==="forward-to-agent"){d.firstPrompt||(d.firstPrompt=I.display??I.prompt);let X=I.display??"",q=X.trim().split(/\s+/),de=Vg(X),ve=de?HD(e,Yg(X)):[],Se=q[0]==="/screenshot"&&(q[1]==="verify"||q[1]==="review"),Te=Se?q[2]&&!q[2].startsWith("--")?[q[2]]:Ws(Fe(e)):[],he=q[0]==="/catch-up"&&!de,ie=he?BD(e):null,te=he?$n(e):null,Le=he?Ks(e).hold:!1,je=I.prompt;if(X.startsWith("/"))try{let Ce=ma(e,X);Ce&&(je=`${je}
|
|
454
|
+
|
|
455
|
+
${Ce}`)}catch{}if(await Gp(l,je,r,d,e,n),de)try{WD(e,ve,ut(de))}catch{}if(ie){let Ce=xo(e,ie,"",q[0]);if(Ce.cta)console.log(m(Ce.cta.text));else if(te){let Xe=Qa({queued:te,hold:Le});Xe.note&&console.log(Xe.tone==="warn"?V(Xe.note):m(Xe.note)),Xe.lead&&console.log(m(` Run ${Xe.lead.cmd} \u2014 ${Xe.lead.reason}.`))}}if(q[0]==="/audit"&&!q.includes("--auto")&&ti(e,n),Se&&Te.length>0)try{for(let Ce of Cr(e,Te))console.log(Ce)}catch{}if(q[0]==="/push"){let Ce=await Ss(e,n);Ce&&console.log(m(Ce))}if((q[0]==="/catch-up"||q[0]==="/document")&&(q.includes("--push")||q.includes("--publish")))try{let Ce=await VD({cwd:e,profileName:n}),{clean:Xe,conflicts:Xt}=yo(Ce.entries);Xe.length===0?console.log(m("Nothing new to push \u2014 everything is already up to date on Document360.")):await Vt(R,Xe.map(st=>st.path),Xt.length,{skipReview:q.includes(At)})}catch(Ce){console.log(V(`Couldn't check what to push (${Ce.message}) \u2014 your drafts are saved; run /push when ready.`))}}else I.kind==="continue"&&I.ownNext||zD(e,n);continue}if(_D(D)){let N=MD(D);if(N){try{FD(e,{title:N,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}d.firstPrompt||(d.firstPrompt=D),await Gp(l,`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${N}". 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 "${N}" and the article path(s) you wrote.`,r,d,e,n);continue}}d.firstPrompt||(d.firstPrompt=D),await Gp(l,D,r,d,e,n)}}}finally{l.close(),w.close()}}function KD(e,t){console.log(""),console.log(hs("document360-writer")),console.log(m(` cwd: ${e}`));let n=DD(e);if(console.log(m(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(XD(e,t)),!ND(e))console.log(V(" 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(qi(e),!mn(e))for(let r of Vi(e))console.log(V(` ${r}`))}catch{}try{let r=ID(e);r.persisted&&r.appType?console.log(m(` \u2713 Detected a ${r.appType} app \u2014 enabled the ${r.appType}-doc-playbook (change with /genre).`)):r.source==="unknown"&&(o=!0)}catch{}try{let r=UD(e);for(let s of Wi(r.applied))console.log(V(` ${s}`));if(r.reopenedForRedaction)for(let s of Bi(r.reopenedForRedaction).split(/\r?\n/))console.log(V(` ${s}`))}catch{}try{let r=oi(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:o}),s=r?ni(r,{pickable:!1,scaleFor:i=>vn(e,i)}):null;if(s?.kind==="recommend"&&s.rec.note){let i=s.rec.tone==="warn"?V:m;for(let a of La(s.rec.note).split(`
|
|
456
|
+
`))console.log(i(` ${a}`));s.rec.picker&&console.log(Z(` Pick one: ${s.rec.picker.options.map(a=>a.cmd).join(" \xB7 ")}`))}}catch{}}console.log(m(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}var Db=!1;function zD(e,t){try{let n=oi(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:!1}),o=n?ni(n,{scaleFor:r=>vn(e,r)}):null;if(o?.kind!=="recommend")return;if(o.rec.settled&&!Db){Db=!0;for(let r of La(o.rec.settled).split(`
|
|
457
|
+
`))console.log(Y(` ${r}`))}else o.rec.settled&&!o.rec.lead&&console.log(m(" Nothing is waiting. /roadmap lists the optional campaign steps."));o.rec.lead&&console.log(m(` Next: ${Ir(o.rec.lead)}`))}catch{}}function XD(e,t){try{let n=jb(e,t),o=n.production?V(" \u26A0 PRODUCTION"):"",r=OD(n.name,n.project.projectId);if(!r)return m(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...Ab(r.idToken)??{},...Ab(r.accessToken)??{}},i=s.email??s.preferred_username??"signed in";return LD(r)&&!r.refreshToken?V(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):m(` Document360: ${i} \xB7 profile "${n.name}"${o}`)}catch(n){return m(` Document360: ${n.message.split(".")[0]}`)}}function QD(){console.error(""),console.error(`Sign in with your Claude subscription: run ${Z("claude")} once, then retry.`),console.error(` (No Claude Code? ${Z("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${Z("https://console.anthropic.com/settings/keys")}`)}function JD(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;AD({uuid:t,name:r??TD(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function ZD(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||ED(o,t).then(r=>{r&&PD(n,r)}).catch(()=>{})}async function Gp(e,t,n,o,r,s){let i=new Map,a=!1;for await(let l of e.send(t))l.type==="tool"&&Ib.test(l.name)&&(a=!0),eN(l,o,r,n,i,s);if(a)try{let l=qD(await GD({cwd:r,profileName:s}));l&&console.log(l.startsWith("\u26A0")?V(l):l)}catch{}}function eN(e,t,n,o,r,s){switch(e.type){case"session":t.uuid||JD(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let i=Eb()?null:wl(e.name,e.input,n,s);if(i){process.stdout.write(`
|
|
458
|
+
|
|
459
|
+
`);let l=[i.category,i.note].filter(w=>!!w).map(w=>xe(` \xB7 ${w}`)),d=i.loud?xe(" \xB7 ")+qe(V(i.loud)):"";console.log(`${Y("\u25CF")} ${Z(qe(Wu(i.verb)))}${qe(i.title)}${l.join("")}${d}`),r.set(e.id,{name:e.name,input:e.input,doc:!0,keepResult:i.keepResult});break}let a=yl(e.name,e.input,process.cwd());a&&(process.stdout.write(`
|
|
460
|
+
|
|
461
|
+
`),console.log(`${xe("\u25CF")} ${a.title}${a.arg!==null?xe(`${a.sep}(${a.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let i=Et(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!i)break;let a=l=>l===1?"":"s";console.log(xe(` \u23BF Added ${i.added} line${a(i.added)}, removed ${i.removed} line${a(i.removed)}`));for(let l of i.lines)console.log(l);i.hidden>0&&console.log(m(` \u2026 +${i.hidden} more diff lines`));break}case"tool_result":{let i=r.get(e.id);if(!i)break;r.delete(e.id);let l=i.doc&&!i.keepResult&&!e.isError?{lines:[],hidden:0}:bl(e.output,4,e.isError||Eb()?void 0:i.name,i.input),d=e.isError?_:xe;l.lines.forEach((w,g)=>console.log(d((g===0?" \u23BF ":" ")+w))),l.hidden>0&&console.log(m(` \u2026 +${l.hidden} lines`)),e.isError||YD(i.name,i.input,e.output,n);break}case"result":{process.stdout.write(`
|
|
462
|
+
`);let i=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(m(` (${Ns(i)}\u2192${Ns(e.outputTokens)} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(Nb(t.uuid),t.titleFired||ZD(t,n));break}case"error":console.error(""),e.kind==="limit"?console.log(V(`\u23F3 ${e.message}`)):console.error(_(`agent error: ${e.message}`)),e.note&&console.log(m(` ${e.note}`)),o.kind==="subscription"&&e.kind==="auth"&&QD();break}}import{render as fj}from"ink";import{resolveAuth as mj}from"document360-engine";import{useCallback as ne,useEffect as et,useMemo as Il,useRef as re,useState as le}from"react";import{Box as Ne,Text as G,useApp as WN,useInput as BN,useStdout as HN}from"ink";import{existsSync as Fr,readFileSync as Ll,readdirSync as GN,writeFileSync as Dk,mkdirSync as qN}from"node:fs";import{basename as ai,dirname as VN,isAbsolute as YN,join as li}from"node:path";import{createSession as Nk,classifyClaudeAuth as uh,CLAUDE_CODE_SETUP_HINT as KN,loginPkce as zN,toStoredTokens as XN,saveTokens as QN,getAccessToken as JN,D360AuthError as ZN,resolveActiveProfile as kt,resolveProjectId as e1,getArticle as t1,decodeJwtClaims as Gr,isExpired as Do,loadTokens as Vn,clearTokens as n1,rememberSessionProject as o1,listStoredSessions as r1,tokensProjectId as jk,clearProfileProject as s1,setTitle as i1,slugify as a1,touchSession as oh,upsertSession as l1,generateTitle as Ik,findByName as c1,listSessions as u1,renameSession as d1,suggestNextAction as p1,readProjectConfig as ge,writeProjectConfig as Lk,autoModeEnabled as Ok,autoBudgetUsd as Ol,DEFAULT_AUTO_BUDGET_USD as h1,WRITER_DIRNAME as f1,readUserConfig as _k,writeUserConfig as m1,resolveAndPersistAppType as g1,detectAppType as Mk,resolveModelSetting as dh,loadProfileMap as Fk,applyPull as _l,computeSyncStatus as Ml,lintDocs as Ur,compareRemoteSources as w1,planPull as Uk,recordRunSample as y1,pushArticles as b1,pushArticle as k1,PUSH_POOL_SIZE as $1,isPullWouldBlankError as Wk,localArticleTitle as Bk,establishBaselines as v1,rebaselineServerMeta as x1,inventoryRepo as R1,knownEnvironments as S1,currentEnvironments as Hk,sunsetEnvironment as Gk,resolveEnvironment as C1,planPartitions as rh,partitionEvenly as P1,screenshotPlaceholderIds as T1,trackedArticlePaths as A1,runPartitioned as ci,partitionCoverage as sh,estimateBulkCost as qk,resolveModelForOperation as ui,readDocsPlan as Vk,checkForUpdate as E1,detectInstallKind as D1,isSelfUpdatable as N1,devHintsGuidePath as Yk,toolFeedbackPath as Kk,reconcileToolFeedback as j1,reconcileUpgradeActions as I1,stampArticles as Wr,snapshotArticles as zk,listArticleFiles as L1,CONTENT_CAP_VERSION as O1,ENGINE_VERSION as r$,DEFAULT_DOCS_DIR as ph,docsRootOf as _1,setProfileProject as M1,writeCrashLog as F1,applyStructureOrder as ih,orderSyncLine as ah,applyRelatedArticles as Xk,relatedSyncLine as Qk,reconcileDocsGit as U1,shareExplainedPath as W1,ensureDir as B1}from"document360-engine";ur();Dn();import{spawn as Ob}from"node:child_process";function tN(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function nN(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?Ob([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):Ob(e,t,{stdio:["pipe","ignore","ignore"]});r.on("error",()=>o(!1)),r.on("close",i=>o(i===0)),r.stdin?.on("error",()=>o(!1));let s=process.platform==="win32"?Buffer.from("\uFEFF"+n,"utf16le"):Buffer.from(n,"utf8");r.stdin?.end(s)}catch{o(!1)}})}async function qp(e){for(let[t,n]of tN())if(await nN(t,n,e))return!0;return!1}var _b=/\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 Mb(e){let t=e.replace(/\s+$/,"").split(`
|
|
463
|
+
`),n=0;for(let s=t.length-1;s>=0;s--){let i=t[s];if(/^\s{0,3}\d{1,2}[.)]\s+\S/.test(i)){n++;continue}if(!(n>0&&/^\s+\S/.test(i)))break}return n<2?0:t.filter(s=>/^\s{0,3}\d{1,2}[.)]\s+\S/.test(s)).slice(-n).every((s,i)=>Number(/^\s{0,3}(\d{1,2})/.exec(s)[1])===i+1)?n:0}var oN=/\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 Fb(e){let t=e.trimEnd();if(!t)return null;let n=Mb(t);return n>=2?{options:n}:/\?[\s*_"')\]]*$/.test(t)||_b.test(t)||oN.test(t)?{options:0}:null}function Vp(e,t){if(t.closed)return e;let n=e.split(`
|
|
464
|
+
`),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){_b.test(s)&&(t.cueSeen=!0);continue}let i=/^(\s{0,3})[-*•]\s+(.*)$/.exec(s);i?(n[r]=`${i[1]}${++t.num}. ${i[2]}`,o=!0):o&&s.trim()!==""&&/^\S/.test(s)&&(t.closed=!0)}return n.join(`
|
|
465
|
+
`)}var rN=/^(?:(?:run|use|try|execute)\s+)?['"`*]?(\/[a-z][a-z-]*)['"`*]?((?:\s+(?:--?[a-z][\w-]*|\S*[/\\]\S*|\d{1,3}[-_][\w.-]*|[\w.-]+\.(?:md|markdown)))*)/i;function sN(e,t){let n=Mb(e);return n<2?[]:e.replace(/\s+$/,"").split(`
|
|
466
|
+
`).filter(s=>/^\s{0,3}\d{1,2}[.)]\s+\S/.test(s)).slice(-n).map(s=>{let i=s.replace(/^\s{0,3}\d{1,2}[.)]\s+/,"").trim(),a=rN.exec(i);if(!a)return null;let l=a[1].slice(1).toLowerCase();return t.has(l)?`${a[1]}${(a[2]??"").replace(/\s+/g," ").trimEnd()}`:null})}function Ub(e,t){let n=sN(e,t);return n.length<2||n.some(o=>o===null)?null:n}function iN(e){let t=e.split(`
|
|
467
|
+
`).map(o=>o.trim()).filter(o=>o.length>3),n=t[t.length-1];return n?n.length>160?`${n.slice(0,157)}\u2026`:n:null}function Or(e){if(e.usageLimit)return`${e.label}: ${e.usageLimit}`;let t=e.stderrTail?iN(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 aN={la:"local","l all":"local","local all":"local",pa:"portal","p all":"portal","portal all":"portal",sa:"skip","s all":"skip","skip all":"skip"},lN={L:"local",P:"portal",S:"skip"},cN={ya:"write","y all":"write","yes all":"write",na:"skip","n all":"skip","no all":"skip"},uN={Y:"write",N:"skip"};function Wb(e,t,n){let o=e.trim(),r=o.toLowerCase().replace(/\s+/g," ");return t[r]??(o.length===1?n[o]??null:null)}function Rl(e){return Wb(e,aN,lN)}function Bb(e){return Wb(e,cN,uN)}function Yp(e,t){let n=t?.max??12,o=t?.chrome??8;return Math.max(3,Math.min(n,(e??24)-o))}function Sl(e,t,n){if(e<=n)return{start:0,end:e,above:0,below:0};let o=Math.min(Math.max(0,t),e-1),r=Math.min(Math.max(0,o-Math.floor(n/2)),e-n),s=r+n;return{start:r,end:s,above:r,below:e-s}}function Kp(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 Hb(e){return e<2?null:`1-${e}`}function bt(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:Hb(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 Gb(e){if(e.multi)return"pick with space, then enter to save \xB7 esc to cancel\u2026";let t=e.rows===void 0?null:Hb(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 dN=[/\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],pN=[/\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/],hN=/^(read|glob|grep|ls|search|notebookread)$/i;function qb(e,t){return!e||!hN.test(e.trim())||pN.some(n=>n.test(t))?!1:dN.some(n=>n.test(t))}import{existsSync as fN,mkdirSync as mN,readFileSync as gN,writeFileSync as wN}from"node:fs";import{join as Vb}from"node:path";import{writerDir as yN}from"document360-engine";function Yb(e){return Vb(yN(e),".sessions")}function Kb(e,t){return Vb(Yb(e),`${t}.json`)}function zb(e,t,n){try{mN(Yb(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");wN(Kb(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function zp(e,t){try{let n=Kb(e,t);if(!fN(n))return[];let o=JSON.parse(gN(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var bN=e=>`\x1B]0;${e}\x07`,kN=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function Xb(e){process.stdout.isTTY&&process.stdout.write(e)}function _r(e){Xb(bN(e))}function Cl(e){Xb(kN(e))}var Pl=["\xB7 "," \xB7"],Tl="\u{1F7E3}";qa();var Qb=e=>e===1?"":"s";function Jb(e){let t=e.ran.length,n=t===0?"nothing to do":`${t} step${Qb(t)} done`;switch(e.reason.kind){case"settled":return{tone:"ok",text:`Auto mode finished \u2014 that is the full round trip. ${n}.`};case"nothingToDo":return t===0?{tone:"ok",text:"Auto mode had nothing to do \u2014 everything is already written, saved and live."}:{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 ${He(e.reason.spentUsd)} of ${He(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 Zb(e){switch(e.reason.kind){case"settled":case"nothingToDo":return{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"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 ek(e){let t=[Jb(e)],n=e.spentUsd>0?` \xB7 ${He(e.spentUsd)} of ${He(e.budgetUsd)}`:"";if(t.push({tone:"info",text:` ${Na({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${Qb(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.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(Zb(e)),t}function tk(e,t){let n=Jb(e).text,o=[`# Automatic run \u2014 ${t}`,"",n,""];if(o.push(`- Time: ${Na({seconds:e.seconds,...e.activeSeconds!==void 0?{activeSeconds:e.activeSeconds}:{}})}`),o.push(`- Spent: ${He(e.spentUsd)} of a ${He(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(Zb(e).text),o.push(""),o.join(`
|
|
468
|
+
`)}var nk=new Set(["/resolve","/pull","/screenshot","/login","/logout","/init","/reset","/discover","/genre","/style-guide","/scope","/profile","/project","/workspace","/model","/mcp","/share","/auto","/allow-prod"]),$N=new Set(["--skip-review","--skip-style","--skip-screenshots"]),vN=40,xN=2,RN=(e,t)=>e.what===t.what&&e.cmd===t.cmd;function Xp(e,t){return e.some(n=>RN(n,t))?e:[...e,t]}function SN(e){let t=en(e);if(!t||nk.has(t.cmd)||!fr(t))return!1;for(let n of t.flags)if($N.has(n))return!1;return!CN(t)}function CN(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 PN(e){let t=en(e);return!t||t.cmd!=="/push"||t.scope!==void 0||t.flags.has("--all")||t.flags.size>0?e:"/push --all"}function TN(e){return!e||e.kind!=="cmd"?null:e.cmd}function AN(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}:ok(e.cmd)}function ok(e){switch(en(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 EN=(e,t)=>e.ran.filter(n=>n===t).length;function rk(e,t,n){let o=t.parked,r=n.maxSteps??vN;if(t.ran.length>=r)return{kind:"stop",reason:{kind:"maxSteps",steps:t.ran.length},parked:o};if(e.settled)return{kind:"stop",reason:{kind:"settled"},parked:o};if(!e.lead&&!e.picker&&e.menu.length===0)return{kind:"stop",reason:{kind:"nothingToDo"},parked:o};e.picker&&(o=Xp(o,{what:`${e.picker.title} \u2014 that one is yours to answer.`,cmd:null}));let s=[{cmd:TN(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===To)return t.ran.includes(To)?{kind:"stop",reason:{kind:"noProgress",cmd:To},parked:o}:t.spentUsd>=n.budgetUsd?{kind:"stop",reason:{kind:"budget",spentUsd:t.spentUsd,limitUsd:n.budgetUsd,next:To},parked:o}:{kind:"prompt",text:To,parked:o};a.lead&&(o=Xp(o,AN(a.lead)));continue}if(i.has(a.cmd))continue;if(i.add(a.cmd),!SN(a.cmd)){let d=en(a.cmd);d&&nk.has(d.cmd)&&(o=Xp(o,ok(a.cmd)));continue}if(t.ran[t.ran.length-1]===a.cmd)return{kind:"stop",reason:{kind:"repeat",cmd:a.cmd},parked:o};if(EN(t,a.cmd)>=xN)return{kind:"stop",reason:{kind:"repeat",cmd:a.cmd},parked:o};if(t.lastClosedItsTarget===!1&&t.lastLeadKey&&t.lastLeadKey===a.cmd)return{kind:"stop",reason:{kind:"noProgress",cmd:a.cmd},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:a.cmd},parked:o}:{kind:"run",cmd:PN(a.cmd),parked:o}}return{kind:"stop",reason:{kind:"onlyBlocked"},parked:o}}var sk=()=>({fingerprint:null,counts:null,settled:0,spokenBaseline:null,lastSpokeAt:null,awaySince:null}),DN={hints:0,requests:0,answers:0,directives:0};function Qp(e,t){let n=e??DN;return{hints:Math.max(0,t.hints-n.hints),requests:Math.max(0,t.requests-n.requests),answers:Math.max(0,t.answers-n.answers),directives:Math.max(0,t.directives-n.directives)}}var Al=e=>e.hints===0&&e.requests===0&&e.answers===0&&e.directives===0,ik=e=>e.hints+e.requests+e.answers+e.directives,Jp=(e,t)=>e-t>=6e5;function ak(e){let{now:t,lastInputAt:n,fingerprint:o,counts:r,occupied:s,prev:i}=e,a=Jp(t,n),d=i.fingerprint!==null&&i.fingerprint!==o?0:i.settled+1,w={...i,fingerprint:o,counts:r,settled:d,awaySince:a?i.awaySince??t:null,spokenBaseline:i.spokenBaseline??r};if(a){let $=Qp(w.spokenBaseline,r);return{memory:w,speak:null,waiting:Al($)?null:$}}if(s)return{memory:w,speak:null,waiting:null};if(d<2)return{memory:w,speak:null,waiting:null};let g=Qp(i.spokenBaseline,r);return Al(g)?{memory:w,speak:null,waiting:null}:i.lastSpokeAt!==null&&t-i.lastSpokeAt<6e5?{memory:w,speak:null,waiting:null}:{memory:{...w,spokenBaseline:r,lastSpokeAt:t,settled:d},speak:g,waiting:null}}function lk(e,t,n){if(e.awaySince===null)return{kind:"none",memory:e};let o=t-e.awaySince,r=Qp(e.spokenBaseline,n),s={...e,awaySince:null,counts:n,spokenBaseline:n,lastSpokeAt:Al(r)?e.lastSpokeAt:t};return Al(r)?{kind:"none",memory:s}:{kind:o>=36e5?"briefing":"delta",memory:s,delta:r,awayMs:o}}function si(e){let t=[];return e.hints&&t.push(`${e.hints} hint${e.hints===1?"":"s"}`),e.requests&&t.push(`${e.requests} request${e.requests===1?"":"s"}`),e.answers&&t.push(`${e.answers} answer${e.answers===1?"":"s"}`),e.directives&&t.push(`${e.directives} directive${e.directives===1?"":"s"}`),t.length===0?"":t.length===1?t[0]:`${t.slice(0,-1).join(", ")} and ${t.at(-1)}`}function Zp(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 ck(e){return`\u{1F4E5} ${si(e)} just arrived from your builder \u2014 /catch-up folds ${ik(e)===1?"it":"them"} into the docs.`}function uk(e,t){return`\u{1F4E5} While you were away (${Zp(t)}): ${si(e)} from your builder \u2014 /catch-up folds ${ik(e)===1?"it":"them"} into the docs.`}function dk(e){return`\u{1F4E5} ${si(e)} waiting from your builder \xB7 tab to run /catch-up\u2026`}zi();import{publishGateVerdict as lh,publishGateLines as ch,blockedPaths as H1,SKIP_STYLE_FLAG as Jk,SKIP_SHOTS_FLAG as G1}from"document360-engine";import{askBuilder as q1,openGapQuestions as V1}from"document360-engine";import{retireArticle as Y1,normalizeScope as K1}from"document360-engine";se();import{Box as ii,Text as Ue}from"ink";import{jsx as We,jsxs as Mr}from"react/jsx-runtime";function NN({row:e,nameW:t,width:n}){let o=s=>Rc(s,n),r=(s,i)=>We(ii,{flexDirection:"column",children:s.map(i)});switch(e.t){case"head":return r(o(e.s),(s,i)=>We(Ue,{color:ae,bold:!0,children:s},i));case"text":return r(o(e.s),(s,i)=>We(Ue,{children:s},i));case"dim":return r(o(e.s),(s,i)=>We(Ue,{dimColor:!0,children:s},i));case"sub":return r(o(e.s),(s,i)=>We(Ue,{bold:!0,dimColor:!0,children:s},i));case"good":return r(o(e.s),(s,i)=>We(Ue,{color:"green",children:s},i));case"step":{let s=o(`${e.n}. ${e.s}`);return We(ii,{flexDirection:"column",children:s.map((i,a)=>a===0?Mr(Ue,{children:[We(Ue,{color:ae,children:`${e.n}. `}),i.slice(`${e.n}. `.length)]},a):We(Ue,{children:i},a))})}case"cmd":{let s=Hi(e.name,e.s,t,n),i=s.descLines.slice(s.nameOwnLine?0:1);return Mr(ii,{flexDirection:"column",children:[Mr(Ue,{children:[" ",We(Ue,{color:ae,children:s.nameCell}),!s.nameOwnLine&&We(Ue,{dimColor:!0,children:` ${s.descLines[0]??""}`})]}),i.map((a,l)=>We(Ue,{dimColor:!0,children:`${s.indent}${a}`},l))]})}case"gap":return We(Ue,{children:" "})}}function pk({tab:e,scroll:t,rows:n,width:o,version:r,engineVersion:s}){let i=ft[e]??ft[0],a=xc(i.rows),l=Math.max(20,o-2),d=6+ft.reduce((T,D)=>T+D.label.length+4,0),w="\u2500".repeat(Math.min(d,l)),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}`,$=xf({rows:n,inner:l,barWidth:d,footerWidth:g.length}),{visible:P,above:C,below:R}=vf(i.rows,{width:o,budget:$,scroll:t,nameW:a});return Mr(ii,{flexDirection:"column",paddingX:1,children:[Mr(Ue,{children:[We(Ue,{color:ae,bold:!0,children:"Help "}),ft.map((T,D)=>D===e?We(Ue,{color:"white",backgroundColor:ae,bold:!0,children:` ${T.label} `},T.key):We(Ue,{dimColor:!0,children:` ${T.label} `},T.key))]}),We(Ue,{color:ae,children:w}),Mr(ii,{flexDirection:"column",marginTop:1,children:[C>0?We(Ue,{dimColor:!0,children:`\u22EF ${C} more above`}):null,P.map((T,D)=>We(NN,{row:T,nameW:a,width:o},C+D)),R>0?We(Ue,{dimColor:!0,children:`\u22EF ${R} more below`}):null]}),We(Ue,{dimColor:!0,children:`
|
|
469
|
+
\u2190/\u2192 or tab switch \xB7 1-5 jump${C+R>0?" \xB7 \u2191\u2193 scroll":""} \xB7 esc close \xB7 d360-writer v${r} \xB7 engine v${s}`})]})}var jN=/^(?:\d+[.)]|[-*•])\s+/;function hk(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
|
|
470
|
+
`)){let i=s.trim().replace(jN,""),a=i.match(/^`([^`]+)`$/);a&&(i=a[1].trim());let l=i.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!l||!o.has(l[1].toLowerCase()))continue;let d=`/${l[1].toLowerCase()}${l[2]?` ${l[2]}`:""}`;if(r.includes(d)||r.push(d),r.length>=n)break}return r}se();function Eo(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function ze(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function El(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var IN=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function eh(e,t,n){if(!IN.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 th(e){return e.replace(/^[\w.-]+\//,"")}var Dl=16,fk={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function qn(e){return typeof e=="string"?e:e.cmd}function mk(e){return typeof e=="string"?void 0:e.desc}function nh(e){return e.trim().split(/\s+/).slice(1).join(" ")}function gk(e,t){let n=nh(t);return e.some(r=>qn(r).trim()===t.trim()||!!n&&nh(qn(r))===n)?e.filter(r=>qn(r).trim()!==t.trim()&&!(n&&nh(qn(r))===n)):[]}import{isDirectiveMention as z1,stripDirectiveMention as X1,appendDirective as Q1,reconcileTestidRequest as J1,builderChannelWired as Z1,pendingFingerprint as ej}from"document360-engine";var LN=/\[Pasted text #\d+ \+\d+ lines?\]/g;function wk(e){return e.replace(/\r\n?/g,`
|
|
471
|
+
`)}function yk(e){return e.includes(`
|
|
472
|
+
`)||e.length>200}function bk(e,t){let n=t.split(`
|
|
473
|
+
`).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function kk(e,t){return e.replace(LN,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 Nl(e,t){let n=Math.max(1,t),o=[],r=0;for(let s of e.split(`
|
|
474
|
+
`)){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 jl(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function vk(e,t,n){let o=jl(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 xk(e,t,n){let o=e[jl(e,t)];return n==="start"?o.start:o.end}var ON=new Set(["Edit","Write","MultiEdit","NotebookEdit"]),Rk={hint:"hint",message:"message",state:"state file",roadmap:"roadmap",directive:"directives",feedback:"tool-feedback"},_N=new Set(["hint","message","state"]),MN=["hint","message","roadmap","directive","feedback","state"];function FN(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 Sk(e,t){let n=e==="Read"?"read":ON.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=FN(r.slice(i+s.length));return a?{category:a,verb:n,path:r}:null}function Ck(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 MN)for(let s of["updated","read"]){let i=t.get(`${r}:${s}`)?.size??0;i!==0&&o.push(_N.has(r)?`${i} ${Rk[r]}${i===1?"":"s"} ${s}`:`${Rk[r]} ${s}`)}return o.length>0?o.join(" \xB7 "):null}function Pk(e,t,n){let o=Math.max(1,n),r=e.split(`
|
|
475
475
|
`),s=0;for(let i=r.length-1;i>=0;i--){let a=r[i];if(s+=Math.max(1,Math.ceil(a.length/o)),s>=t){let l=s-t;return{text:[l>0?a.slice(l*o):a,...r.slice(i+1)].join(`
|
|
476
|
-
`),truncated:i>0||l>0}}}return{text:e,truncated:!1}}function
|
|
477
|
-
`)){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
|
|
476
|
+
`),truncated:i>0||l>0}}}return{text:e,truncated:!1}}function Tk(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 Ak(e){let t=!1,n=0,o=0;for(let r of e.split(`
|
|
477
|
+
`)){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 Hr,jsx as H,jsxs as ce}from"react/jsx-runtime";var tj={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL",auto:"auto \u2014 right-sized for docs \xB7 /model to change"},Zk=` 1. /init \u2014 pick your Document360 environment & scaffold config
|
|
478
478
|
2. /login \u2014 sign in & pick your Document360 project (workspace auto-selected)
|
|
479
|
-
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function
|
|
480
|
-
`).length+1,console.log(p)},[
|
|
481
|
-
`)}catch{}u.picker&&(ie(u.picker.options.map(S=>({cmd:S.cmd,desc:S.desc}))),
|
|
482
|
-
`)}),pn(u.prompt,
|
|
483
|
-
${
|
|
484
|
-
Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!
|
|
485
|
-
${
|
|
486
|
-
`)}),pn(
|
|
487
|
-
`)}),b.reopenedForRedaction&&h({kind:"note",tone:"warn",text:
|
|
479
|
+
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function nj(e,t,n,o){let r=uh(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=dh(e),a=ge(e),l=(a?.docsDir??ph).replace(/\/+$/,""),d=a?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${l}/ + config`,w={version:t,engineVersion:r$,captureVersion:mt(),claude:s,model:i.model,modelSource:tj[i.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:a!==null,mode:d};if(a===null)return w;try{let g=kt(e,o);w.profile=g.name,w.apiUrl=g.connection.apiUrl,w.prod=g.production,w.project=g.project.projectName??g.project.projectId??"(chosen at login)";let $=Vn(g.name,g.project.projectId);if($){let P={...Gr($.idToken)??{},...Gr($.accessToken)??{}},C=P.email??P.preferred_username??"signed in";Do($)?$.refreshToken&&(w.who=C,w.loggedOut=!1,w.sessionHint="session expired \u2014 refreshing\u2026"):(w.who=C,w.loggedOut=!1,w.sessionHint=`session valid until ${new Date($.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return w}var oj=e=>e.mode==="local-only"?e.path:e.plan.path;function rj(e,t){try{let n=kt(e,t),o=Vn(n.name,n.project.projectId);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...Gr(o.idToken)??{},...Gr(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return Do(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 e$=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],qr=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],sj="Ask me to write or update an article\u2026",t$=2e3,ij=new Set(ko.map(e=>e.name));function Br({ch:e,dim:t}){let[n,o]=le(!0);return et(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),H(G,{inverse:n,color:t&&!n?"gray":void 0,children:e})}function xn({rows:e,cursor:t,cap:n,render:o}){let r=Sl(e.length,t,n);return ce(Hr,{children:[r.above>0?H(G,{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?H(G,{color:"gray",children:` \u22EF ${r.below} more below`}):null]})}var n$=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function o$(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var aj=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function lj({startTime:e,chars:t}){let[n,o]=le(0),r=re(Date.now());et(()=>{let d=setInterval(()=>o(w=>w+1),120);return()=>clearInterval(d)},[]);let s=qr[n%qr.length],i=e$[Math.floor(n/16)%e$.length],a=Bg(e,r.current,Date.now()),l=Math.round(t/4);return ce(Ne,{children:[H(G,{color:ae,children:` ${s} ${i}\u2026 `}),H(G,{color:"gray",children:`(${yn(a)} \xB7 ~${l} tokens \xB7 esc to interrupt)`})]})}function cj({step:e,cmd:t,startedAt:n,spentUsd:o,budgetUsd:r}){let[,s]=le(0);et(()=>{let l=setInterval(()=>s(d=>d+1),1e3);return()=>clearInterval(l)},[]);let i=Math.max(0,Math.round((Date.now()-n)/1e3)),a=o>0?` \xB7 ${gt(o)} of ${He(r)}`:` \xB7 limit ${He(r)}`;return ce(Ne,{flexDirection:"column",children:[ce(Ne,{children:[H(G,{color:ae,children:` \u23F5\u23F5 auto \xB7 step ${e} \xB7 `}),H(G,{color:ae,bold:!0,children:t})]}),H(G,{color:"gray",children:` ${yn(i)}${a} \xB7 esc stops`})]})}function uj({text:e}){let[t,n]=le(0);return et(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),H(Ne,{paddingX:1,children:H(G,{color:ae,children:`${qr[t%qr.length]} ${e}`})})}var dj=12e4;function pj({p:e}){let[t,n]=le(0);et(()=>{let D=setInterval(()=>n(N=>N+1),150);return()=>clearInterval(D)},[]);let o=qr[t%qr.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>=dj,l=e.verb??"Converting",d=e.unit??"article",w=e.rows.reduce((D,N)=>D+N.items,0),g=e.rows.reduce((D,N)=>D+(N.status==="done"?N.items:N.itemsDone??0),0),$=l.toLowerCase(),P=e.rows,C=0;if(P.length>Dl){let D=P.findIndex(B=>B.status==="active"||B.status==="pending"),N=Math.max(0,Math.min(D-2,P.length-Dl));C=P.slice(0,N).filter(B=>B.status==="done").length,P=P.slice(N,N+Dl)}let R=Math.min(40,Math.max(...P.map(D=>th(D.label).length),0)),T=D=>D==="failed"?"red":D==="active"?ae:void 0;return ce(Ne,{flexDirection:"column",children:[ce(Ne,{children:[H(G,{color:ae,children:` ${o} ${l} ${w} ${d}${w===1?"":"s"} `}),H(G,{color:"gray",children:e.agentless?`\xB7 ${g}/${w} ${d}${w===1?"":"s"} \xB7 ${yn(r)} \xB7 esc to stop`:`\xB7 ${g}/${w} ${d}${w===1?"":"s"} \xB7 ${e.done}/${e.total} batch${e.total===1?"":"es"} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${i} tokens \xB7 ${yn(r)} \xB7 esc to stop`})]}),C>0&&H(G,{dimColor:!0,children:` \u2714 +${C} done`}),P.map(D=>ce(G,{color:T(D.status),dimColor:D.status==="done"||D.status==="pending",children:[` ${fk[D.status]} ${th(D.label).padEnd(R)}`,D.status==="active"&&D.itemsDone!==void 0?` (${D.itemsDone}/${D.items} ${d}${D.items===1?"":"s"})`:D.status!=="pending"?` (${D.items} ${d}${D.items===1?"":"s"})`:"",D.status==="active"?` \u2190 ${$}\u2026`:""]},D.label)),a&&H(G,{color:"yellow",children:` \u26A0 no activity for ${yn(s)} \u2014 press esc to stop if it's wedged`}),a&&e.stalledNote?H(G,{color:"yellow",children:` ${e.stalledNote}`}):null]})}var hj=10800*1e3;function s$({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=WN(),[s,i]=le(n),[a,l]=le(null),[d,w]=le({text:"",pos:0}),g=d.text,$=ne(u=>{w(p=>{let c=typeof u=="function"?u(p.text):u;return{text:c,pos:c.length}})},[]),P=ne(u=>{w(p=>({text:p.text.slice(0,p.pos)+u+p.text.slice(p.pos),pos:p.pos+u.length}))},[]),C=ne(()=>{w(u=>{if(u.pos===0)return u;let p=u.text.slice(0,u.pos),c=$k(p)??p.slice(0,-1);return{text:c+u.text.slice(u.pos),pos:c.length}})},[]),[R,T]=le(!1),[D,N]=le(!1),[B,I]=le(0),[X,q]=le(!1),[de,ve]=le(null),[Se,Te]=le(null),[he,ie]=le([]),te=re(!1),Le=re(!1),je=re(null),Ce=re(!1),[Xe,Xt]=le(!1),st=re(!1),It=re(0),[No,Lt]=le(!1),[rn,jo]=le(!1),[Io,Vr]=le(null),[Yr,be]=le(0),_e=re(0),[Kr,Lo]=le(0),[Oo,di]=le(null),[_o,zr]=le(null),wh=re(new Map),d$=re(0),Mo=re([]),Ot=re(null);Ot.current===null&&(Ot.current=Nk({cwd:e,profileName:s,allowProdWrites:!1}));let sn=re({uuid:null,firstPrompt:null,titleFired:!1}),Xr=re(new Map),yh=re(null),Ul=re(null),pi=re(_k().verboseTranscript===!0),Rn=re(!1),Wl=re([]),Ee=re([]),an=re([]),_t=re([]),Fo=re(null),[bh,Yn]=le(null),Bl=re(null),[ln,Kn]=le(null),[Mt,Uo]=le(null),[Ft,Wo]=le(null),[Qe,Bo]=le(null),[it,zn]=le(null),[$t,Ho]=le(null),[Ut,Go]=le(null),[Wt,Xn]=le(null),[vt,cn]=le(null),[tt,Qr]=le(null),kh=re({value:0,at:0}),$h=re({value:0,at:0}),un=ne((u,p)=>{let{index:c,memory:f}=Kp($h.current,Number(u),p);return $h.current=f,c},[]),[dt,Qn]=le(null),[vh,qo]=le(null);et(()=>zr(null),[he]);let[xt,Jn]=le(null),[at,Vo]=le(null),[xh,Hl]=le([]),Zn=re([]),Jr=re(!1),Zr=re(null),Gl=re(null),[p$,Rh]=le(!1),Ge=re(null),[Rt,hi]=le(null),fi=re(!1),eo=re(!1),mi=re(!1),ql=re(null),[Yo,Sh]=le(null),Vl=re(null),Me=re(null),[Ko,pe]=le(null),[Ch,Be]=le(null),gi=re(!1),es=re(null),to=re(null),[St,no]=le(null),[ts,oo]=le(null),Sn=!!(Rt||Ft||Qe||it||$t||Ut||Wt||vt||tt||dt||xt||at||St||ts),ns=Il(()=>{try{return Ok(ge(e))}catch{return!1}},[e,B]),Ph=Ut?{verb:"publish live",cancel:"leave as drafts",rows:Ut.rows.length+1}:$t?{verb:"push as drafts",rows:$t.rows.length}:dt?{verb:"choose it",rows:dt.rows.length}:Wt?{verb:"run it",rows:Wt.rows.length}:vt?{verb:"open it",cancel:"close",rows:vt.rows.length-1}:Qe?{verb:"switch",rows:Qe.rows.length}:it?{verb:"switch",rows:it.rows.length}:Ft?{verb:"use it",rows:Ft.rows.length}:Mt?{verb:"switch",rows:Mt.rows.length,extra:["s this session only"]}:ln?{verb:"use it",rows:Nt.length}:at?{verb:"save",multi:!0}:null,[Th,ro]=le(0),[Ct,so]=le(0),[h$,Ah]=le(0),Yl=Il(()=>{try{let u=dh(e);return u.source==="auto"?`${u.model} (auto)`:u.model}catch{return null}},[e,h$]),{stdout:Je}=HN(),[,f$]=le(0),Eh=re(`${Je.columns??80}x${Je.rows??24}`),Ke=ne(()=>Math.max(20,(Je.columns??80)-1),[Je]),wi=ne(u=>{Mo.current.push(u);let p=Bu(u,Ke());zo.current+=p.split(`
|
|
480
|
+
`).length+1,console.log(p)},[Ke]),Kl=re([]),yi=ne(()=>{let u=Kl.current;if(u.length===0)return;Kl.current=[];let p=Ck(u);p&&wi({kind:"note",tone:"info",text:`\u25CF Housekeeping ${p}`})},[wi]),h=ne(u=>{yi(),wi(u)},[wi,yi]),lt=re({printed:[],armed:[],printedAt:0}),bi=re(null),zl=re([]),zo=re(0),ki=ne(()=>Ge.current!==null,[]),nt=ne((u,p)=>{ki()||(It.current++,lt.current.armed=[],ve(u),Te(p??null))},[ki]),Bt=ne(()=>{It.current++,lt.current.armed=[],ve(null),Te(null)},[]),os=ne(u=>{ki()||(It.current++,lt.current.armed=[],ve(null),Te(u))},[ki]),oe=ne(u=>nt(u,jr({kind:"cmd",cmd:u,reason:""})),[nt]),dn=ne((u,p)=>{if(!p?.silent&&u.note&&h({kind:"note",tone:p?.tone??u.tone,text:u.note}),!p?.silent&&u.note?.includes(".d360-writer/ \u2014 your articles"))try{let S=W1(e);B1(VN(S)),Dk(S,`${new Date().toISOString()}
|
|
481
|
+
`)}catch{}u.picker&&(ie(u.picker.options.map(S=>({cmd:S.cmd,desc:S.desc}))),qo(u.picker.title),zl.current=u.picker.exclusive?u.picker.options.map(S=>S.cmd.trim()):[]),!p?.silent&&u.note&&(lt.current.printed=u.menu,lt.current.printedAt=zo.current);let f=zo.current-lt.current.printedAt<Math.max(8,(Je.rows??24)-4)&&lb(lt.current.printed,u.menu)?u.menu:[];u.lead?(u.lead.kind==="answer"?os(jr(u.lead,f.length)):nt(u.lead.kind==="cmd"?u.lead.cmd:u.lead.text,jr(u.lead,f.length)),!p?.silent&&u.note&&(bi.current=Lr(u.lead))):!p?.silent&&!u.picker&&(Bt(),f.length>0&&os(`1\u2013${f.length} to pick a campaign step \xB7 nothing is waiting \xB7 or just ask me anything\u2026`)),lt.current.armed=f},[h,nt,os,e,Je]),De=ne((u,p,c="info")=>{lt.current.armed=[],u&&h({kind:"note",tone:c,text:u}),p&&(p.kind==="answer"?os(jr(p)):nt(p.kind==="cmd"?p.cmd:p.text,jr(p)),bi.current=u?Lr(p):null)},[h,nt,os]),Xo=ne((u,p,c,f="info")=>{if(u.producedNothing){De("Nothing was changed \u2014 the agent produced no output, so this command did nothing at all.",{kind:"cmd",cmd:"/doctor",reason:"it checks Claude sign-in + whether the model is reachable from this machine"},"warn");return}u.handedBack||De(p,c,f)},[De]),[io,Xl]=le(null),[m$,Dh]=le(!1),pn=ne((u,p)=>{Xl(u),Dh(!1),h({kind:"note",tone:"info",text:p?.hint??"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[h]),Ql=ne(()=>{J1(e,new Date().toISOString());let u=Kw(e);u&&(h({kind:"note",tone:"info",text:u.lines.join(`
|
|
482
|
+
`)}),pn(u.prompt,Z1(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,pn]),Jl=re(!1),Zl=ne(async()=>{try{if(Jl.current||!N1(D1())||ge(e)?.mode==="engineer")return;let u=await E1({pkg:Er,currentVersion:o,force:!0});if(!u.updateAvailable||!u.latest)return;Jl.current=!0,h({kind:"note",tone:"info",text:`\u2B06 Updating ${Er} ${u.current} \u2192 ${u.latest}\u2026 (wait for the \u2713 before you /exit)`}),jo(!0);let p=await ol().finally(()=>jo(!1));p.ok?(h({kind:"note",tone:"ok",text:`\u2713 Updated to v${u.latest} \u2014 run /exit, then relaunch to apply.`}),oe("/exit"),Vr(u.latest)):h({kind:"note",tone:"warn",text:`Update available (v${u.latest}) but auto-update failed. ${nl(p.output)}`})}catch{}},[e,o,h,oe]),rs=re(!1),ec=re(null),Nh=ne(async u=>{if(!rs.current)try{let p=ge(e);if(!p)return;let c=jh.current;if(!c)return;if(c.pushConsent!=="on"){if(c.uncommitted===0)return;rs.current=!0;try{let S=await U1(e,p);if(S.commit?.ok)ec.current=null;else if(S.commit&&!S.commit.ok){let M=`${S.commit.reason}:${S.commit.detail??""}`;ec.current!==M&&(ec.current=M,h({kind:"note",tone:"warn",text:`\u26A0 Couldn't save your docs work to git \u2014 ${Bn(S.commit.reason,S.commit.detail)}`}))}}finally{rs.current=!1}return}if(c.uncommitted===0&&c.unpushed===0&&!u.pull)return;rs.current=!0;try{let{lines:S,changed:M}=await za(e,p);for(let W of S)W.tone==="warn"||W.tone==="error"?h({kind:"note",tone:W.tone,text:W.text}):W.text.includes("\u2B07")&&h({kind:"note",tone:W.tone,text:W.text});M&&I(W=>W+1)}finally{rs.current=!1}}catch{}},[e,h]),ao=ne(u=>{let p=Ve(e,s);return p.ok?!0:(h({kind:"note",tone:"warn",text:p.reason}),to.current=u,oe("/login"),!1)},[e,s,h,oe]),[$i,tc]=le(null),jh=re(null),Ih=re(null),pt=ne((u,p)=>{let c=oi(e,s,{claudeMissing:uh(t).state==="missing",allowAutoAudit:u,genreUnknown:Ce.current,pendingAnswer:je.current,lastCommand:Ih.current});return jh.current=c?.handoff??null,c?ni(c,{header:p,pickable:!0,scaleFor:f=>vn(e,f)}):{kind:"idle"}},[e,s,t]),nc=re(Date.now()),ss=re(sk()),Lh=re(0),[Oh,_h]=le(null),is=re(!0),Qo=re(!1),vi=re(0),as=re(0);et(()=>{let u=setInterval(()=>{if(is.current){vi.current=0,as.current=0;return}if(!R)try{if(!Fr(Yk(e)))return;if(Gt(e).status==="current"){is.current=!0,vi.current=0,as.current=0;let c=Qo.current?`\u2713 Your builder finished the protocol update (v${Oe}) \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:",f=pt(!1,c),S=f.kind==="recommend"?f.rec:null;Xl(null),S?.note?dn(S,{tone:"ok"}):(h({kind:"note",tone:"ok",text:`${c}${S?.lead?` ${Ir(S.lead)}`:""}`}),S?.lead||S?.picker?dn(S,{silent:!0}):Qo.current||nt("write the docs for this repo")),I(M=>M+1);return}if(Qo.current)return;vi.current+=1;let p=vi.current;if((p===4||p%15===0)&&as.current<3){as.current+=1;let c=as.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";h({kind:"note",tone:"info",text:mn(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${c}`:`\u23F3 Waiting for your builder to run the prompt \u2014 paste it into your coding agent; I'll pick up automatically when it's done.${c}`})}}catch{}},4e3);return()=>clearInterval(u)},[e,R,h,pt,dn,nt]),et(()=>{let u=bh??ai(e);if(!R){Cl(0),_r(`${Tl} ${u}`);return}Cl(3);let p=0;_r(`${Pl[0]} ${u}`);let c=setInterval(()=>{p=(p+1)%Pl.length,_r(`${Pl[p]} ${u}`)},400);return()=>clearInterval(c)},[R,e,bh]),et(()=>()=>Cl(0),[]),et(()=>{let u=performance.now(),p=[],c=(b,k)=>{let x=performance.now();try{return k()}finally{let y=Math.round(performance.now()-x);y>=80&&p.push(`${b}: ${y}ms`)}};h({kind:"banner",info:c("banner",()=>nj(e,o,t,s))});let f=uh(t).state==="missing";if(f&&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.
|
|
483
|
+
${KN}
|
|
484
|
+
Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!ge(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:
|
|
485
|
+
${Zk}`}),oe(f?"/doctor":"/init");return}f&&oe("/doctor");try{let b=kt(e,s);b.project.projectId&&o1(b.name,b.project.projectId,b.project.projectName);let k=Vn(b.name,b.project.projectId),x=Ve(e,s);k&&Do(k)&&k.refreshToken?JN({profile:b.name,connection:b.connection,projectId:b.project.projectId,projectName:b.project.projectName}).then(()=>{h({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),I(y=>y+1)}).catch(y=>{if(y instanceof ZN&&y.transient){h({kind:"note",tone:"warn",text:"Couldn't reach Document360 to renew your session \u2014 your sign-in is intact, and I'll try again on your next command."});return}h({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 sign in again with /login."}),oe("/login"),I(v=>v+1)}):x.ok||(h({kind:"note",tone:"warn",text:x.reason}),oe("/login"))}catch{}try{let b=ge(e),k=kt(e,s),x=Vn(k.name,k.project.projectId);b&&x&&!Do(x)&&Fp(e,b.authoritativeSourceFiles)&&!Up(e,s)&&(h({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),oe("/scope"))}catch{}try{let b=c("resolve-genre",()=>g1(e));b.persisted&&b.appType?h({kind:"note",tone:"ok",text:`\u2713 Detected a ${b.appType} app \u2014 enabled the ${b.appType}-doc-playbook (change with /genre, or edit .d360-writer/config.json).`}):b.source==="unknown"&&ge(e)&&(Ce.current=!0)}catch{}let S=Gt(e);try{if(c("reconcile-devhints",()=>qi(e)),S.status!=="current"&&!mn(e)){let b=Vi(e);b.length&&(h({kind:"note",tone:"warn",text:b.join(`
|
|
486
|
+
`)}),pn(fo()),is.current=!1,Qo.current=!1)}}catch{}try{let b=c("reconcile-feedback",()=>j1(e));b.archived>0&&h({kind:"note",tone:"ok",text:`\u2713 Tidied ${b.archived} resolved item${b.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${b.open>0?`; ${b.open} still open`:""}.`})}catch{}try{let b=c("upgrade-actions",()=>I1(e));b.applied.length>0&&h({kind:"note",tone:"warn",text:Wi(b.applied).join(`
|
|
487
|
+
`)}),b.reopenedForRedaction&&h({kind:"note",tone:"warn",text:Bi(b.reopenedForRedaction)})}catch{}let M=c("ready-decision",()=>pt(!0));M.kind==="autoAudit"?(h({kind:"note",tone:"info",text:M.note}),Ps({cwd:e,profileName:s}).then(b=>{if(b.kind==="audit-blocked"){De(b.note,{kind:"cmd",cmd:b.lead.cmd,reason:b.lead.reason},"warn");return}b.kind!=="forward-to-agent"||!b.prompt||Pe(b.prompt,{display:b.display,quietUser:!0}).then(k=>{if(k.producedNothing)return;let x=va(e,s);if(x){De(x.note,{kind:"cmd",cmd:wr.cmd,reason:wr.reason},"warn"),I(y=>y+1);return}ti(e,s),I(y=>y+1)})})):M.kind==="recommend"&&dn(M.rec);let W=Math.round(performance.now()-u);W>=800&&F1({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${W}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${p.length?p.join(`
|
|
488
488
|
`):"no single phase \u226580ms"}
|
|
489
|
-
cwd: ${e}`}),
|
|
490
|
-
|
|
491
|
-
${E}`)}catch{}p?.quietUser||h({kind:"user",text:p?.echoDisplay&&p.display?p.display:u});let f=
|
|
492
|
-
`)}),
|
|
493
|
-
`)}),x||(
|
|
494
|
-
`)}),[h]),
|
|
495
|
-
`)});let L=S.stop();if(
|
|
496
|
-
`)}),
|
|
497
|
-
`)}),
|
|
498
|
-
`)}),c.blocked.length>0?
|
|
499
|
-
`):`${A}Authored specs \u2014 ${v}/${y.results.length} batches ok.${L}`}),
|
|
489
|
+
cwd: ${e}`}),Zl(),Nh({pull:!0})},[]),et(()=>{let u=setInterval(()=>{Zl()},hj);return()=>clearInterval(u)},[Zl]),et(()=>{let u=setInterval(()=>{try{let p=Date.now(),c=Jp(p,nc.current);if(Lh.current+=1,c&&Lh.current%Math.round(3e5/6e4)!==0)return;let f=ej(e),S=ss.current,M=f===S.fingerprint&&S.counts?S.counts:$n(e),W=ak({now:p,lastInputAt:nc.current,fingerprint:f,counts:M,occupied:R||X||he.length>0||g!==""||Sn||Ee.current.length>0,prev:S});if(ss.current=W.memory,_h(W.waiting),W.speak&&Ge.current===null){h({kind:"note",tone:"info",text:ck(W.speak)});let b=pt(!1);b.kind==="recommend"&&dn(b.rec,{silent:!0})}}catch{}},6e4);return()=>clearInterval(u)},[e,R,X,he.length,g,Sn,h,pt,dn]),et(()=>{if(R||X||te.current||ns&&!eo.current||de!==null||he.length>0||g!==""||io!==null||Ee.current.length>0||Fo.current||Sn)return;let u=pt(!1);if(u.kind==="recommend"&&(u.rec.lead||u.rec.picker||u.rec.menu.length>0)){dn(u.rec,{silent:!0});let p=u.rec.lead,c=p?Lr(p):u.rec.settled?"settled":null;c&&c!==bi.current&&(bi.current=c,u.rec.settled&&h({kind:"note",tone:"ok",text:u.rec.settled}),p&&h({kind:"note",tone:"info",text:Ir(p)}))}Nh({pull:!1})},[R,X,de,he,g,io,Sn,B,pt,Xe]);let ls=ne((u,p)=>{let c=Ge.current;if(Ge.current=null,fi.current=!1,mi.current=!1,!c)return;let f=Math.max(0,Math.round((Date.now()-c.startedAt)/1e3)),S={ran:c.ran,parked:p,spentUsd:Math.max(0,Ct-c.stepStartedSpend),budgetUsd:Ol(ge(e)),seconds:f,reason:u};for(let W of ek(S))h({kind:"note",tone:W.tone,text:W.text});try{let W=new Date().toISOString().replace(/[:.]/g,"-"),b=li(e,f1,"auto-runs");qN(b,{recursive:!0}),Dk(li(b,`${W}.md`),tk(S,new Date().toISOString()),"utf8")}catch{}let M=p.find(W=>W.cmd)?.cmd;M&&oe(M),Sh(null),I(W=>W+1)},[e,h,Ct,oe]);et(()=>{if(!ns||eo.current||mi.current||R||X||he.length>0||g!==""||io!==null||Ee.current.length>0||Fo.current||Sn)return;let u=Ge.current;if(u?.stopping){ls({kind:"stopped",how:"manual"},u.parked);return}let p=pt(!1);if(p.kind!=="recommend")return;let c=u??{ran:[],parked:[],spentUsd:0,startedAt:Date.now(),stopping:!1,stepStartedSpend:Ct},f=Vl.current,S=rk(p.rec,{ran:c.ran,parked:c.parked,spentUsd:Math.max(0,Ct-c.stepStartedSpend),...c.ran.length>0?{lastLeadKey:c.ran[c.ran.length-1]??null}:{},...f?{lastClosedItsTarget:qt(f)}:{}},{budgetUsd:Ol(ge(e))});if(S.kind==="stop"){if(!u&&S.reason.kind!=="onlyBlocked")return;if(!u){let b=p.rec.lead?Lr(p.rec.lead):"blocked";if(ql.current===b)return;ql.current=b}Ge.current=c,ls(S.reason,S.parked);return}if(!fi.current){let b=Ol(ge(e)),k=v=>{try{return v()}catch{return null}},x=S.kind==="run"?S.cmd:`\u201C${S.text}\u201D`,y=S.kind==="run"?k(()=>Ey(e,S.cmd)):null;hi({firstCmd:x,scale:S.kind==="run"?k(()=>vn(e,S.cmd)):null,budgetUsd:b,overBudget:y!==null&&y>b});return}let M=S.kind==="run"?S.cmd:S.text;c.parked=S.parked,c.ran=[...c.ran,M],Ge.current=c,Vl.current=null,h({kind:"block",text:Z(me("\u25B6",`Auto mode, step ${c.ran.length}: ${M}`))}),Sh({step:c.ran.length,cmd:M,startedAt:c.startedAt,spentUsd:Math.max(0,Ct-c.stepStartedSpend),budgetUsd:Ol(ge(e))}),ql.current=null,mi.current=!0,q(!0),(S.kind==="run"?uo(S.cmd):Pe(S.text,{display:S.text,quietUser:!0}).then(()=>{})).finally(()=>{mi.current=!1,q(!1)})},[ns,R,X,he,g,io,Sn,B,pt,ls]),et(()=>{let u=null,p=null,c=()=>{u&&clearTimeout(u),u=setTimeout(()=>{u=null;let f=`${Je.columns??80}x${Je.rows??24}`;f!==Eh.current&&(Eh.current=f,f$(S=>S+1),p&&clearTimeout(p),p=setTimeout(()=>{p=null;let S=Math.max(8,(Je.rows??24)-2);console.log("\x1B[?2026h\x1B[H\x1B[2J"+Hg(Mo.current,Ke(),S)+"\x1B[?2026l")},80))},400)};return Je.on("resize",c),()=>{u&&clearTimeout(u),p&&clearTimeout(p),Je.off("resize",c)}},[Je,Ke]);let ct=Math.max(20,(Je.columns??80)-1),Mh=Il(()=>rj(e,s),[e,s,B]),oc=(()=>{if(rn)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(Io!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${Io?` v${Io}`:""}\u2026`,isSetup:!0};if(Ph)return{text:Gb(Ph),isSetup:!0};if($i)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(io)return m$?{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(Oh)return{text:dk(Oh),isSetup:!0};if(Ee.current.length>0){let f=Ee.current.length,S=Ee.current[0].mode;return S==="local-only"?{text:"l publish yours over the portal \xB7 s skip \xB7 anything else cancels\u2026",isSetup:!0}:S==="conflict"?{text:f>1?`l keep local \xB7 p take portal \xB7 s skip \xB7 la/pa/sa for all ${f}\u2026`:"l keep local \xB7 p take portal \xB7 s skip \xB7 anything else cancels\u2026",isSetup:!0}:{text:f>1?`y to write \xB7 n to skip \xB7 ya/na for all ${f}\u2026`:"y to write \xB7 n to skip \xB7 anything else cancels\u2026",isSetup:!0}}let u=ge(e);if(!u)return{text:"Run /init to set up this repo (or /help)\u2026",isSetup:!0};let p=li(e,(u.docsDir??ph).replace(/\/+$/,"")),c=(()=>{try{return Fr(p)&&GN(p).length>0}catch{return!1}})();try{let f=kt(e,s),S=Vn(f.name,f.project.projectId);if(!(!!S&&!(Do(S)&&!S.refreshToken)))return{text:`Sign in with /login (profile "${f.name}")\u2026`,isSetup:!0};if(!f.project.projectId)return{text:"Sign in to Document360 to pick your project\u2026",isSetup:!0};if(!f.project.workspaceId&&!c)return{text:"Pick a workspace with /workspace\u2026",isSetup:!0}}catch{}return c?{text:sj,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),hn=Ng(g),rc=hn.length>0&&!R,g$=12,Qt=Yp(Je.rows),w$=Je.rows??24,Fh=Yp(Je.rows,{max:g$}),xi=Math.min(Kr,Math.max(0,hn.length-1)),lo=Sl(hn.length,xi,Fh).start,sc=hn.slice(lo,lo+Fh),ic=a!==null?Pk(a,8,ct):null,Ri=xt?xt.paths.filter(u=>!xt.query||u.toLowerCase().includes(xt.query.toLowerCase())).slice(0,8):[],Si=St?St.sessions.filter(u=>{let p=St.query.toLowerCase();return!p||u.name.toLowerCase().includes(p)||u.firstPrompt.toLowerCase().includes(p)}).slice(0,8):[],ot=ne((u,p)=>{Ot.current?.close(),Ot.current=Nk({cwd:e,resume:u,profileName:p??s,allowProdWrites:Rn.current}),u||(sn.current={uuid:null,firstPrompt:null,titleFired:!1},Yn(null)),ro(0),so(0)},[e,s]),Uh=ne((u,p,c)=>{if(n$.test(u))try{let f=kt(e,s),S=typeof p.project_id=="string"&&p.project_id||f.project.projectId,M=$l(p,c),W=[],b=Pb(p,c),k=b?`${b} \u2014 `:"",x=vl(c);u.endsWith("publish_article")&&x&&W.push(`${k}Live: ${x}`);let y=xl(c);y?W.push(`${k}Preview: ${y}`):M&&S&&W.push(`${k}Preview: ${kl(f.connection.portalUrl,S,M,f.project.languageCode??"en")}`),W.length>0&&h({kind:"link",lines:W})}catch{}},[e,s,h]),Pe=ne(async(u,p)=>{Lt(!0),te.current=!1,Le.current=!1,je.current=null,Bt(),ie([]),qo(null),Xl(null);let c=It.current;if(p?.display?.startsWith("/"))try{let E=ma(e,p.display);E&&(u=`${u}
|
|
490
|
+
|
|
491
|
+
${E}`)}catch{}p?.quietUser||h({kind:"user",text:p?.echoDisplay&&p.display?p.display:u});let f=sn.current;f.firstPrompt||(f.firstPrompt=p?.display??u),_e.current=Date.now(),be(0),T(!0),Xr.current.clear(),Ul.current=null;let S="",M=!1,W=!1,b=!1,k=!1,x="",y={num:0,closed:!1,cueSeen:!1},v=null,A=()=>{v||(v=setTimeout(()=>{v=null,l(x.length>0?x:null)},60))},L=()=>{v&&clearTimeout(v),v=null,l(null)},j=(E=!1)=>{let{head:z,keep:F}=Tk(x,E);z.trim()&&h({kind:"assistant",text:Vp(z.trimEnd(),y)}),x=F,L()};try{for await(let E of Ot.current.send(u))if(E.type==="session"){if(!f.uuid){f.uuid=E.sessionId;let z=new Date().toISOString(),F=Bl.current,U=F??a1(f.firstPrompt??"session");l1({uuid:E.sessionId,name:U,renamed:!!F,titled:!1,cwd:e,firstPrompt:f.firstPrompt??"",createdAt:z,updatedAt:z}),Yn(U),Bl.current=null}}else if(E.type==="text"){x+=E.delta,S+=E.delta;let z=Ak(x);if(z>0){let F=x.slice(0,z).trimEnd();F&&h({kind:"assistant",text:Vp(F,y)}),x=x.slice(z)}A(),be(F=>F+E.delta.length)}else if(E.type==="tool"){M=!0,n$.test(E.name)&&(W=!0);let F=(we=>typeof we=="string"&&we?we.replace(/\\/g,"/").toLowerCase():null)(E.input.file_path??E.input.notebook_path),U=["Edit","Write","MultiEdit","NotebookEdit"].includes(E.name),K=E.name==="Read"&&F!==null&&F===yh.current;yh.current=U?F:null;let ee=pi.current,ue=ee?null:Sk(E.name,E.input),fe=ee?null:wl(E.name,E.input,e,s);if(ue)Kl.current.push(ue);else if(fe){j();let we=fe.repeat&&fe.articleKey&&fe.articleKey===Ul.current?fe.repeat:fe;Ul.current=fe.articleKey??null,h({kind:"doc",verb:fe.verb,title:we.title,category:we.category,note:we.note,...fe.loud?{loud:fe.loud}:{}}),Xr.current.set(E.id,{name:E.name,input:E.input,doc:!0,keepResult:fe.keepResult})}else if(K)j(),h({kind:"tool",title:"Read",sep:"",arg:"re-checking the file it just edited"});else{let we=yl(E.name,E.input,e);we&&(j(),h({kind:"tool",title:we.title,sep:we.sep,arg:we.arg}),Xr.current.set(E.id,{name:E.name,input:E.input}))}}else if(E.type==="article_diff"){let z=Et(E.oldContent,E.newContent,Ke());z&&(j(),h({kind:"diff",added:z.added,removed:z.removed,lines:z.lines,hidden:z.hidden}))}else if(E.type==="tool_result"){E.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(E.output)&&(gi.current=!0);let z=Xr.current.get(E.id);if(z){Xr.current.delete(E.id),j();let U=z.doc&&!z.keepResult&&!E.isError?{lines:[],hidden:0}:bl(E.output,4,E.isError||pi.current?void 0:z.name,z.input),K=E.isError&&qb(z.name,E.output);U.lines.length>0&&h({kind:"tool-result",lines:U.lines,hidden:U.hidden,isError:E.isError&&!K}),E.isError||Uh(z.name,z.input,E.output)}}else if(E.type==="result"){j(!0),ro(K=>K+E.outputTokens),so(K=>Math.max(K,E.sessionCostUsd));let z=E.inputTokens+E.cacheReadTokens+E.cacheCreationTokens;if(h({kind:"done",seconds:Math.round((Date.now()-_e.current)/1e3),tokens:E.outputTokens,costUsd:E.costUsd,sessionCostUsd:Math.max(Ct,E.sessionCostUsd),ok:E.ok,...z>0?{inTokens:z,cachedPct:Math.round(E.cacheReadTokens/z*100)}:{}}),!b&&!M&&!S.trim()&&!Jr.current&&(k=!0,h({kind:"note",tone:"warn",text:"The agent produced no output \u2014 nothing ran this turn. Run /doctor: it runs a real turn with your skills and tools and reports what failed. Claude Code\u2019s own error was written either way \u2014 /logs shows it, and offers to copy it for the team."})),E.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(S))try{let K=Kk(e);if(Fr(K)){let ee=Ll(K,"utf8").trim();ee&&(tc(ee),h({kind:"note",tone:"info",text:"\u{1F6E0} Press c to copy this feedback \u2014 send it to the d360-writer team (Teams / Slack / email)."}))}}catch{}let F=E.ok?Fb(S):null;Le.current=F!==null,je.current=F;let U=E.ok?Ub(S,ij):null;if(U)Xt(!1),st.current=!1,ie(U);else if(E.ok&&(y.cueSeen||(F?.options??0)>=2))Xt(!0),st.current=!0,ie([]);else if(F)ie([]);else{let K=E.ok?hk(S,ko.map(ee=>ee.name)):[];if(K.length>0)oe(K[0]);else if(E.ok&&S.trim()&&!Le.current){let ee=pt(!1);ee.kind==="recommend"&&(ee.rec.lead||ee.rec.picker)||p1(u,S,e).then(ue=>{ue&&It.current===c&&nt(ue)}).catch(()=>{})}}if(f.uuid&&(oh(f.uuid),!f.titleFired)){f.titleFired=!0;let K=f.uuid,ee=f.firstPrompt;ee&&Ik(ee,e).then(ue=>{ue&&(i1(K,ue),Yn(ue))}).catch(()=>{})}}else E.type==="error"&&(j(!0),b=!0,E.kind==="auth"&&(gi.current=!0),h(E.kind==="limit"?{kind:"note",text:`\u23F3 ${E.message}`,tone:"warn"}:{kind:"note",text:`agent error: ${E.message}`,tone:"error"}),E.note&&h({kind:"note",text:E.note,tone:"info"}))}finally{if(T(!1),L(),yi(),W)try{let E=ah(await ih({cwd:e,profileName:s,onRateLimit:z=>Be(`Document360 rate limit \u2014 waiting ${Math.ceil(z.waitMs/1e3)}s\u2026`)}));E&&h({kind:"note",tone:E.startsWith("\u26A0")?"warn":"info",text:E})}catch{}finally{Be(null)}I(E=>E+1),sn.current.uuid&&zb(e,sn.current.uuid,Mo.current),gi.current?(gi.current=!1,es.current=p?.display??u,nt("/login","\u21E5 tab to run /login \u2014 then I\u2019ll re-send your last prompt\u2026")):es.current=null,Jr.current&&(Jr.current=!1,Zn.current.length>0&&(h({kind:"note",tone:"info",text:`(${Zn.current.length} queued message(s) discarded)`}),Zn.current=[],Hl([])),h({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}return{producedNothing:k,handedBack:je.current!==null}},[e,h,Uh,Ke,nt,oe,Bt,pt,yi]),Ci=ne(async()=>{try{Be("Checking Document360 for new reviewer comments\u2026"),await Ja(e,s,{onProgress:(u,p)=>Be(`Checking Document360 for new reviewer comments\u2026 ${u}/${p}`)})}catch{}finally{Be(null)}},[e,s]),ht=ne(async(u,p=0,c)=>{let f=lh(e,u,{allowUnreviewed:c?.skipReview===!0,allowStyleErrors:c?.skipStyle===!0});if(!f.clear){h({kind:"note",tone:"warn",text:ch(f,u.length,{act:"push"}).join(`
|
|
492
|
+
`)}),oe(Ju(f));return}_e.current=Date.now(),be(0),T(!0);let S=new AbortController;Me.current=S;let M={aborted:!1,partitions:0,failed:0,notRun:0,producedNothing:!0},W={retryable:0,stopped:!1},b=async(k,x)=>{let y=rh(k),v=new Map;for(let ee of y)for(let ue of ee.paths)v.set(ue,ee.label);let A=new Map(y.map(ee=>[ee.label,ee.paths.length])),L=new Set,j=Date.now();pe({verb:"Pushing",unit:"article",total:k.length,done:0,active:[],rows:Eo(y),tools:0,chars:0,lastAt:Date.now(),startedAt:j,agentless:!0}),h({kind:"note",tone:"info",text:x?`Resolving cross-links in ${k.length} article${k.length===1?"":"s"} whose targets were saved this run (second pass)\u2026 (esc to stop)`:`Pushing ${k.length} article${k.length===1?"":"s"} to Document360 (${$1} at a time)\u2026 (esc to stop)`});let E=await b1({cwd:e,profileName:s,paths:k,allowProdWrites:Rn.current,...c?.allowUnpullable===!0?{allowUnpullable:!0}:{},signal:S.signal,onEvent:ee=>{let ue=ee.type==="article_done"?ee.result.path:ee.type==="article_failed"?ee.failure.path:ee.path,fe=v.get(ue);if(!fe)return;if(ee.type==="article_start"){pe(Q=>Q&&!Q.active.includes(fe)?{...Q,active:[...Q.active,fe],rows:ze(Q.rows,fe,"active"),lastAt:Date.now()}:Q&&{...Q,lastAt:Date.now()});return}ee.type==="article_failed"&&L.add(fe);let we=(A.get(fe)??1)-1;A.set(fe,we),pe(Q=>{if(!Q)return Q;let $e={...Q,done:Q.done+1,rows:El(Q.rows,fe),lastAt:Date.now()};return we>0?$e:{...$e,active:$e.active.filter(Ie=>Ie!==fe),rows:ze($e.rows,fe,L.has(fe)?"failed":"done")}})}}),z=E.aborted||!!E.stopped,F=hu(e,k,s);x||(M={aborted:z,partitions:y.length,failed:E.failed.length,notRun:E.notRun.length,producedNothing:E.pushed.length===0,verifiedComplete:F>=k.length,leftBehind:p});let U=E.pushed.length>0;h({kind:"note",tone:z||E.failed.length>0||!U?"warn":"ok",text:(z?"Stopped. ":"")+fu(E,{recorded:F,elapsedMs:Date.now()-j,docsRoot:_1(e),...x?{}:{conflictsSkipped:p},...c?.scope?{scope:c.scope}:{}}).join(`
|
|
493
|
+
`)}),x||(W={retryable:E.failed.filter(ee=>!ee.refused).length,stopped:!!E.stopped});let K=pu(e,s);if(K&&h({kind:"note",tone:"info",text:K}),U){let ee=gr(e,s);ee&&h({kind:"note",tone:"info",text:ee})}if(!z&&U){try{let ue=await ih({cwd:e,profileName:s,onRateLimit:we=>Be(`Document360 rate limit \u2014 waiting ${Math.ceil(we.waitMs/1e3)}s\u2026`)}),fe=ah(ue);fe?h({kind:"note",tone:fe.startsWith("\u26A0")?"warn":"info",text:fe}):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{Be(null)}try{let ue=Qk(await Xk({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 ee=await Ss(e,s);ee&&h({kind:"note",tone:"info",text:ee})}return z};try{let k=await b(u,!1);if(!k){let y=await mu(e,s,u);y.length>0&&await b(y,!0),Cn(c?.scope?`/push ${c.scope}`:"/push --all",M)}let x=Re("/push",c?.scope?"":"--all",c?.scope);W.retryable>0?De(null,{kind:"cmd",cmd:x,reason:W.stopped?"Document360 stopped answering \u2014 your articles are unchanged, so this picks up where the run left off":`${W.retryable} article${W.retryable===1?"":"s"} could not be saved \u2014 this retries them`},"warn"):!k&&p>0&&De(null,{kind:"cmd",cmd:"/resolve",reason:`${p} conflict${p===1?"":"s"} still need settling \u2014 they were left untouched`},"warn")}catch(k){h({kind:"note",tone:"error",text:`Publish run failed: ${k.message}`})}finally{Me.current=null,pe(null),await Ci(),T(!1),I(k=>k+1)}},[e,s,h,t,De,Ci]),Jo=ne(u=>h({kind:"block",text:u.join(`
|
|
494
|
+
`)}),[h]),Zo=ne((u,p,c,f,S)=>{let M=Dt(u,p,c,Date.now(),S);h({kind:"done",seconds:M.seconds,tokens:M.outputTokens,costUsd:M.costUsd,ok:f,...M.activeSeconds!==void 0?{activeSeconds:M.activeSeconds}:{},sessionCostUsd:Ct+c,...M.inputTokens>0?{inTokens:M.inputTokens,...M.cachedPct!==void 0?{cachedPct:M.cachedPct}:{}}:{}})},[h,Ct]),Pi=ne(async u=>{let p=ui(e,"standard");_e.current=Date.now(),be(0),T(!0);let c=new AbortController;Me.current=c;let f=Date.now(),S=new br;S.start(),pe({verb:u.verb,unit:"article",total:u.partitions.length,done:0,active:[],rows:Eo(u.partitions),tools:0,chars:0,lastAt:Date.now(),startedAt:f}),h({kind:"note",tone:"info",text:`${u.headline} on ${p.model}\u2026 (esc to stop)`});let M=!0,W=[],b=!1,k={aborted:!1,partitions:0,failed:0,notRun:0,producedNothing:!0},x=new Set;try{for await(let y of ci({cwd:e,partitions:u.partitions,promptFor:u.promptFor,concurrency:u.concurrency,profileName:s,allowProdWrites:Rn.current,model:p.model,signal:c.signal,scope:u.scope}))if(y.type==="partition_status")y.status==="running"?pe(v=>v&&{...v,active:[...v.active,y.label],rows:ze(v.rows,y.label,"active"),lastAt:Date.now()}):pe(v=>v&&{...v,active:v.active.filter(A=>A!==y.label),done:v.done+1,rows:ze(v.rows,y.label,y.status==="done"?"done":"failed"),lastAt:Date.now()});else if(y.type==="partition_stalled"){let v=Or(y);pe(A=>A&&v?{...A,stalledNote:v}:A)}else if(y.type==="partition_event"){let v=null;if(y.event.type==="tool"){let A=eh(y.event.name,y.event.input,u.partitions[y.index]?.paths??[]);A&&!x.has(A)&&(x.add(A),v=y.label)}pe(A=>{if(!A)return A;let L={...A,lastAt:Date.now()};return y.event.type==="tool"?L.tools=A.tools+1:y.event.type==="text"&&(L.chars=A.chars+y.event.delta.length),v&&(L.rows=El(L.rows,v)),L})}else if(y.type==="run_done"){so(j=>j+y.totalCostUsd),ro(j=>j+y.results.reduce((E,z)=>E+z.outputTokens,0));let v=sh(u.partitions,y.results);M=!!y.allEmpty||!!y.blocked,b=!!y.aborted,k={aborted:!!y.aborted,partitions:u.partitions.length,failed:v.failed.length,notRun:v.notRun.length,...y.blocked?{blocked:y.blocked}:{},...y.allEmpty?{allEmpty:!0}:{},...y.bailedEmpty?{bailedEmpty:!0}:{}};let A=[`${y.aborted?"Stopped. ":""}${y.results.length-v.failed.length}/${u.partitions.length} batches ${u.doneNoun}.`,...v.failed.length?[`\u26A0 ${v.failed.length} not ${u.doneNoun} \u2014 their articles are unchanged: ${v.failed.map(j=>j.label).join(", ")}`]:[],...v.notRun.length?[`\u26A0 ${v.notRun.length} batch${v.notRun.length===1?"":"es"} never started \u2014 their articles are untouched.`]:[],...y.blocked?[`\u26A0 ${y.blocked}`]:[],...y.allEmpty?[u.emptyNote??"\u26A0 No turn produced any work this run \u2014 nothing was changed."]:[],...u.caveatLines??[]];h({kind:"note",tone:y.aborted||v.failed.length||v.notRun.length||y.blocked||y.allEmpty?"warn":"ok",text:A.join(`
|
|
495
|
+
`)});let L=S.stop();if(Zo(f,y.results,y.totalCostUsd,!b&&!M&&!v.failed.length,L.activeSeconds),u.calibrateAs){let j=y.results.filter(E=>E.ok).length;y1(e,u.calibrateAs,{articles:v.covered.length,waves:Math.ceil(j/Math.max(1,u.concurrency)),seconds:L.activeSeconds,costUsd:y.totalCostUsd})}M||(W=v.covered)}}catch(y){h({kind:"note",tone:"error",text:`${u.verb} failed: ${y.message}`})}finally{S.stop(),Me.current=null,pe(null),T(!1),I(y=>y+1)}return{producedNothing:M,covered:W,aborted:b,outcome:k}},[e,s,h,Zo]),y$=ne(async(u,p)=>{let c=await Pi({partitions:u.partitions,promptFor:u.promptFor,concurrency:Hn,verb:"Reviewing",doneNoun:"reviewed",headline:`Reviewing ${u.articles} article${u.articles===1?"":"s"} in ${u.partitions.length} batches (\u2264${Hn} editors at once)${p?", applying fixes as they go":", report only"}`+(()=>{let f=ll(e,"/review",u.articles,u.partitions.length);return f?` \xB7 ${f}`:""})(),caveatLines:Pp(u),emptyNote:"\u26A0 No editor produced any work this run \u2014 nothing was reviewed or changed.",calibrateAs:"/review",scope:"review"});if(p&&c.covered.length>0)try{Wr(e,c.covered,ut("review"))}catch{}return{producedNothing:c.producedNothing,aborted:c.aborted,outcome:c.outcome}},[e,Pi]),ac=ne(async(u,p)=>{if(u.length===0)return;let c=u.reduce((x,y)=>x+y.threads.length,0),f=new Map,S=u.map(x=>(f.set(x.label,x),{label:x.label,paths:x.path?[x.path]:[]})),M=ui(e,"standard");_e.current=Date.now(),be(0),T(!0);let W=new AbortController;Me.current=W;let b=Date.now(),k=zk(e);pe({verb:"Answering",unit:"article",total:S.length,done:0,active:[],rows:Eo(S),tools:0,chars:0,lastAt:Date.now(),startedAt:b}),h({kind:"note",tone:"info",text:`Answering ${c} comment${c===1?"":"s"} across ${S.length} article${S.length===1?"":"s"} (\u2264${zs} agents at once) on ${M.model}. Each article is fixed, pushed to Document360 as a draft, then answered in the thread${p.resolve?" and resolved":" \u2014 the threads stay open for your reviewers to close"}\u2026 (esc to stop)`});try{for await(let x of ci({cwd:e,partitions:S,promptFor:y=>{let v=f.get(y.label);return ip({articleId:v.articleId,label:v.label,path:v.path,count:v.threads.length,resolve:p.resolve})},concurrency:zs,profileName:s,allowProdWrites:Rn.current,allowCommentResolve:p.resolve,model:M.model,signal:W.signal}))if(x.type==="partition_status")x.status==="running"?pe(y=>y&&{...y,active:[...y.active,x.label],rows:ze(y.rows,x.label,"active"),lastAt:Date.now()}):pe(y=>y&&{...y,active:y.active.filter(v=>v!==x.label),done:y.done+1,rows:ze(y.rows,x.label,x.status==="done"?"done":"failed"),lastAt:Date.now()});else if(x.type==="partition_stalled"){let y=Or(x);pe(v=>v&&y?{...v,stalledNote:y}:v)}else if(x.type==="partition_event")pe(y=>{if(!y)return y;let v={...y,lastAt:Date.now()};return x.event.type==="tool"?v.tools=y.tools+1:x.event.type==="text"&&(v.chars=y.chars+x.event.delta.length),v});else if(x.type==="run_done"){so(F=>F+x.totalCostUsd),ro(F=>F+x.results.reduce((U,K)=>U+K.outputTokens,0));let y=sh(S,x.results),v=x.results.length-y.failed.length,A=x.aborted?"Stopped. ":"",L=[...y.failed.map(F=>F.label),...y.notRun.map(F=>F.label)],j=[`${A}${v}/${S.length} article${S.length===1?"":"s"} answered.`,...L.length?[`\u26A0 ${L.length} left untouched (their threads are still open, which is correct \u2014 nothing was promised to those reviewers): ${L.join(", ")}`]:[],...x.blocked?[`\u26A0 ${x.blocked}`]:[],...x.allEmpty?["\u26A0 No agent produced any work this run \u2014 nothing was changed or answered."]:[]];h({kind:"note",tone:x.aborted||L.length||x.blocked||x.allEmpty?"warn":"ok",text:j.join(`
|
|
496
|
+
`)}),Zo(b,x.results,x.totalCostUsd,!x.aborted&&!L.length&&!x.blocked&&!x.allEmpty);let E=new Set(L),z=[...p.rest??[],...u.filter(F=>E.has(F.label))];if(z.length>0&&!x.aborted&&p.report){let F=z.reduce((K,ee)=>K+ee.threads.length,0);h({kind:"note",tone:"info",text:`${F} comment${F===1?"":"s"} on ${z.length} other article${z.length===1?"":"s"} still open \u2014 pick the next one, or esc to stop here.`});let U={...p.report,threads:z.flatMap(K=>K.threads)};Jo(Xs(U,{width:Ke()})),cn({cursor:0,rows:el(z),groups:z,resolve:p.resolve,report:U})}else if(z.length>0&&!x.aborted){let F=z.map(K=>K.path).filter(K=>!!K),U=F.length===z.length?Zt(F):void 0;oe(U?F.length===1?`/comments ${U}`:`/comments --scope ${U}`:"/comments")}}}catch(x){h({kind:"note",tone:"error",text:`Answering comments failed: ${x.message}`})}finally{let y=xo(e,k,"","/comments").changed.length;y>0&&h({kind:"note",tone:"info",text:`${y} article${y===1?"":"s"} changed, and that new text has not been read by an editor \u2014 ${y===1?"it":"they"} can go live once /review has been over ${y===1?"it":"them"}.`}),Me.current=null,pe(null),T(!1),I(v=>v+1)}},[e,s,h,De,oe,Jo,Ke]),lc=ne(async(u,p)=>{if(!(p?.skipReview===!0||p?.skipStyle===!0)){let f=lh(e,[u],{});if(!f.clear){h({kind:"note",tone:"warn",text:ch(f,1,{act:"push"}).join(`
|
|
497
|
+
`)}),oe(Ju(f,u));return}}await ht([u],0,{skipReview:p?.skipReview,skipStyle:p?.skipStyle,scope:u});try{let f=await ka(e,s,u.replace(/\\/g,"/"));f.length>0&&(qo(`Related articles not yet saved to Document360 (${f.length}):`),ie([`/push --related ${u}`,...f.map(S=>`/push ${S}`)]))}catch{}},[e,s,Pe,ht]),Wh=ne(async(u,p)=>{T(!0);try{let c=await $u(e,s,u,{skipReview:p.skipReview,skipStyle:p.skipStyle,onProgress:(S,M,W)=>Be(`Publishing ${S+1}/${M} \u2014 ${W}\u2026`)}),f=c.blocked.length+c.failed.length;h({kind:"note",tone:f>0?"warn":"ok",text:vu(c).join(`
|
|
498
|
+
`)}),c.blocked.length>0?oe("/review --blocked --fix"):De(null,null)}catch(c){h({kind:"note",tone:"error",text:`Publishing failed: ${c.message}`})}finally{Be(null),await Ci(),T(!1),I(c=>c+1)}},[e,s,h,oe,De,Ci]),Bh=ne(async u=>{try{let p=await Ml({cwd:e,profileName:s}),{clean:c,conflicts:f}=yo(p.entries);if(c.length===0){h({kind:"note",tone:"info",text:"Nothing new to save \u2014 everything is already up to date on Document360."});return}await ht(c.map(S=>S.path),f.length,{skipReview:u?.skipReview,skipStyle:u?.skipStyle})}catch(p){h({kind:"note",tone:"warn",text:`Couldn\u2019t check what to save (${p.message}) \u2014 your articles are written; run /push when ready.`})}},[e,s,ht]),Cn=ne((u,p)=>{if(p&&(Vl.current=p),!(p&&!qt(p)))for(let c of Tt(e,u))h({kind:"note",tone:"ok",text:c})},[e,h]),Hh=ne(async(u,p)=>{let f=P1(u,3),S=ui(e,"standard"),M=new Map,W=new Map;for(let y of u){let v=go(e,y),A=Wc(e,y,v);if(A&&M.set(y,A),v!==null){let L=eu(v);L.length>0&&W.set(y,L)}}_e.current=Date.now(),be(0),T(!0);let b=new AbortController;Me.current=b;let k=Date.now();pe({verb:"Authoring",unit:"spec",total:f.length,done:0,active:[],rows:Eo(f),tools:0,chars:0,lastAt:Date.now(),startedAt:k}),h({kind:"note",tone:"info",text:`Authoring ${u.length} screenshot spec${u.length===1?"":"s"} in ${f.length} batch${f.length===1?"":"es"} (\u22646 agents at once) on ${S.model}${S.forced?" (forced)":""}\u2026 (esc to stop)`});let x=!1;try{for await(let y of ci({cwd:e,partitions:f,promptFor:v=>Lm(v,M,W),concurrency:6,profileName:s,allowProdWrites:Rn.current,model:S.model,signal:b.signal}))if(y.type==="partition_status")y.status==="running"?pe(v=>v&&{...v,active:[...v.active,y.label],rows:ze(v.rows,y.label,"active"),lastAt:Date.now()}):pe(v=>v&&{...v,active:v.active.filter(A=>A!==y.label),done:v.done+1,rows:ze(v.rows,y.label,y.status==="done"?"done":"failed"),lastAt:Date.now()});else if(y.type==="partition_stalled"){let v=Or(y);pe(A=>A&&v?{...A,stalledNote:v}:A)}else if(y.type==="partition_event")pe(v=>{if(!v)return v;let A={...v,lastAt:Date.now()};return y.event.type==="tool"?A.tools=v.tools+1:y.event.type==="text"&&(A.chars=v.chars+y.event.delta.length),A});else if(y.type==="run_done"){so(E=>E+y.totalCostUsd),ro(E=>E+y.results.reduce((z,F)=>z+F.outputTokens,0));let v=y.results.filter(E=>E.ok).length,A=y.aborted?"Stopped. ":"";x=!y.aborted&&p.setup;let L=y.aborted?"":x?" Refreshing the staging checklist\u2026":` Next: /screenshot capture${p.scope?` ${p.scope}`:" --all"} (or /screenshot checklist first for the staging checklist).`,j=On(y,"Spec authoring");h({kind:"note",tone:j||y.aborted?"warn":y.ok?"ok":"warn",text:j?j.join(`
|
|
499
|
+
`):`${A}Authored specs \u2014 ${v}/${y.results.length} batches ok.${L}`}),Zo(k,y.results,y.totalCostUsd,!j&&!y.aborted&&y.ok),j&&(oe("/doctor"),x=!1),!y.aborted&&y.ok&&!j&&Cn(p.runLine)}}catch(y){h({kind:"note",tone:"error",text:`Spec authoring failed: ${y.message}`})}finally{Me.current=null,pe(null),T(!1),I(y=>y+1)}if(x){let y=await Tr();y.kind==="forward-to-agent"&&y.prompt&&await Pe(y.prompt,{display:y.display,quietUser:!0}),Ql()}},[e,s,h,Pe,Cn,Ql]),Gh=ne(async u=>{let p=Wc(e,u,go(e,u))??void 0,c=await ha([u],void 0,{prior:p});c.kind==="forward-to-agent"&&c.prompt&&await Pe(c.prompt,{display:c.display,quietUser:!0}),km(e,u)&&De(`Spec ready \u2014 /screenshot capture ${u} takes the screenshot; bare /screenshot picks the next shot.`,{kind:"cmd",cmd:`/screenshot capture ${u}`,reason:""})},[e,Pe,De]),Ti=ne(async(u,p)=>{if(u.length===0)return{drawn:[],undrawn:[],cliMissing:!1};T(!0);let c=new AbortController;Me.current=c,pe({verb:"Drawing callouts",unit:"screenshot",total:u.length,done:0,active:[],rows:u.map(v=>({label:v,items:1,status:"pending"})),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()});let f=[],S=!1;try{let v=await Bd({cwd:e,ids:u,...p.force?{force:!0}:{},signal:c.signal,onStart:A=>pe(L=>L&&{...L,active:[A],rows:ze(L.rows,A,"active"),lastAt:Date.now()}),onDone:(A,L)=>pe(j=>j&&{...j,active:[],done:j.done+1,rows:ze(j.rows,A,L==="failed"?"failed":"done"),lastAt:Date.now()})});f=v.results,S=v.cliMissing??!1}catch(v){h({kind:"note",tone:"error",text:`Drawing the callouts failed: ${v.message}`})}finally{Me.current=null,pe(null),T(!1),I(v=>v+1)}if(S)return h({kind:"note",tone:"error",text:"d360-capture is not installed on this machine. Run: npm i -g document360-capture \u2014 then /screenshot annotate."}),{drawn:[],undrawn:u,cliMissing:!0};let M=f.filter(v=>v.outcome==="annotated").map(v=>v.id),W=f.filter(v=>v.outcome==="skipped").map(v=>v.id),b=u.filter(v=>!M.includes(v)&&!W.includes(v));if(h({kind:"note",tone:b.length?"warn":"ok",text:[`\u25C8 ${M.length} drawn`,W.length?`${W.length} already current`:"",b.length?`\u2717 ${b.length} not drawn`:""].filter(Boolean).join(" ")}),b.length>0){let v=Math.max(...b.map(A=>A.length));h({kind:"note",tone:"warn",text:b.map(A=>`\u2717 ${A.padEnd(v)} ${Gs(f.find(L=>L.id===A)?.detail)||"no picture was produced"}`).join(`
|
|
500
500
|
`)+`
|
|
501
|
-
${b.length===1?"It has":"They have"} no publishable picture yet. Re-take the shot: /screenshot capture`})}if(p.chainVerify===!1||M.length===0)return{drawn:M,undrawn:b,cliMissing:!1};let k=M.filter(v=>p.verifiedBefore.has(v)).length;if(k>
|
|
502
|
-
`)}),{drawn:M,undrawn:b,cliMissing:!1}},[e,h,De,Pe]),
|
|
503
|
-
${
|
|
504
|
-
${k}`:"")});let x=Date.now(),y=[];try{for(let U of u){if(S.signal.aborted)break;pe(
|
|
505
|
-
${U}`).join("")});let E=
|
|
506
|
-
`)}),L.length>0){let U=Math.max(...L.map(K=>K.id.length));h({kind:"note",tone:"error",text:L.map(K=>`\u2717 ${K.id.padEnd(U)} ${
|
|
507
|
-
`)})}
|
|
508
|
-
`)});return}let F=
|
|
509
|
-
`)}),pn(
|
|
510
|
-
`)}),pn(
|
|
511
|
-
${
|
|
512
|
-
`)}),b.copyText&&pn(b.copyText,{hint:b.notable?"\u2328 Press c to copy this problem report \u2014 then send it to the team (Teams / Slack / email).":"\u2328 Press c to copy this entry, if you want to send it to the team."});return}case"style-guide":{let b=
|
|
513
|
-
`)}),x&&(
|
|
514
|
-
`)});return}case"mcp":await
|
|
515
|
-
`)}),k&&h({kind:"note",tone:"warn",text:`\u26A0 ${k.why} \u2014 ${k.cmd} moves this repo.`});return}let b=[...
|
|
516
|
-
${L.path} \xB7 ${L.articleId?`updates article ${L.articleId}`:"would be created as a new article"}${j}`}),L.missingShots.length>0&&h({kind:"note",tone:"warn",text:`\u26A0 ${L.missingShots.length} screenshot${L.missingShots.length===1?"":"s"} not taken yet \u2014 the description publishes instead: ${L.missingShots.join(", ")}`}),h({kind:"note",tone:"info",text:L.body}),h({kind:"note",tone:"info",text:`Nothing was sent. /push ${L.path} saves it as a draft.`}),
|
|
501
|
+
${b.length===1?"It has":"They have"} no publishable picture yet. Re-take the shot: /screenshot capture`})}if(p.chainVerify===!1||M.length===0)return{drawn:M,undrawn:b,cliMissing:!1};let k=M.filter(v=>p.verifiedBefore.has(v)).length;if(k>Ya){let v=Vw({results:f,voidedVerdicts:k,...p.scope?{scope:p.scope}:{}});return v&&De(`${v.glyph} ${v.cmd} ${v.why}`,{kind:"cmd",cmd:v.cmd,reason:""},"warn"),{drawn:M,undrawn:b,cliMissing:!1}}let x=M.filter(v=>!p.verifiedBefore.has(v)||k>0);if(x.length===0)return{drawn:M,undrawn:b,cliMissing:!1};h({kind:"note",tone:"info",text:Wn(x.length)}),await Pe(on(e,x),{display:"/screenshot verify",quietUser:!0});let y=Cr(e,x);return y.length>0&&h({kind:"note",tone:"info",text:y.join(`
|
|
502
|
+
`)}),{drawn:M,undrawn:b,cliMissing:!1}},[e,h,De,Pe]),cs=ne(async(u,p)=>{if(!vo(e)){await Pe(_d(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(!Ow(e)){h({kind:"note",tone:"info",text:"No saved login for screenshot capture yet \u2014 opening a browser window. Sign in to your app (MFA included); I'll continue automatically once the session saves. (esc cancels)"}),T(!0),Be("Waiting for you to finish logging in (browser window)\u2026");let U=new AbortController;Me.current=U;let K;try{K=await _w({cwd:e,signal:U.signal})}catch(ee){h({kind:"note",tone:"error",text:`Could not launch the login: ${ee.message}`});return}finally{Me.current=null,Be(null),T(!1)}if(K.exitCode!==0){Od(K.exitCode,K.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(K.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:
|
|
503
|
+
${Id(K.output)}`});return}h({kind:"note",tone:"ok",text:"\u2713 Login saved \u2014 continuing with the capture."})}let c=new Map(u.map(U=>[U,Cm(e,U)])),f=0;if(u.length>1){let U=u.filter(K=>c.get(K).mutates);if(U.length>0&&(f=U.length,u=u.filter(K=>!c.get(K).mutates),u.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(u.length===1&&c.get(u[0]).mutates){let U=c.get(u[0]),K=Mw(e);h({kind:"note",tone:"warn",text:`\u26A0 This capture performs a REAL write in your app${U.what?`: ${Sm(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. `+(K.production?`This profile is PRODUCTION \u2014 the write lands in the LIVE tenant${K.url?` (${K.url})`:""}. If the spec cleans up after itself, confirm it did.`:"Tip: point the capture scope (.d360-writer/capture.json) at a demo/non-production context for shots like this.")})}T(!0);let S=new AbortController;Me.current=S;let M=u.map(U=>({label:U,items:1,status:"pending"}));pe({verb:"Capturing",unit:"screenshot",total:u.length,done:0,active:[],rows:M,tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()});let W=gn(e),b=Object.keys(W.shots).length>0,k=Fw(p?.heldBackBlocked??[],f);h({kind:"note",tone:"info",text:`Capturing ${u.length} screenshot${u.length===1?"":"s"} with d360-capture (a real browser drives your app)\u2026 (esc to stop)`+(k?`
|
|
504
|
+
${k}`:"")});let x=Date.now(),y=[];try{for(let U of u){if(S.signal.aborted)break;pe(we=>we&&{...we,active:[U],rows:ze(we.rows,U,"active"),lastAt:Date.now()});let{exitCode:K,output:ee}=await Ld({cwd:e,id:U,signal:S.signal,stdio:"pipe"});if(Od(K,ee)){h({kind:"note",tone:"error",text:"d360-capture is not installed on this machine. Run: npm i -g document360-capture \u2014 then /screenshot capture again."});return}let ue=S.signal.aborted&&K!==0?"failed":jd(e,U,K,x),fe=ue==="captured"?void 0:ue==="skipped"?Iw(ee)??"a data prerequisite isn't met \u2014 the spec's skip reason names what to stage":Lw(ee);y.push({id:U,outcome:ue,detail:fe}),pe(we=>we&&{...we,active:[],done:we.done+1,rows:ze(we.rows,U,ue==="captured"?"done":"failed"),lastAt:Date.now()})}}catch(U){h({kind:"note",tone:"error",text:`Capture run failed: ${U.message}`})}finally{Me.current=null,pe(null),T(!1),I(U=>U+1)}if(y.length===0)return;let v=y.filter(U=>U.outcome==="captured"),A=y.filter(U=>U.outcome==="skipped"),L=y.filter(U=>U.outcome==="failed"),j=u.length-y.length;h({kind:"note",tone:L.length?"warn":v.length?"ok":"info",text:[`\u2713 ${v.length} captured`,A.length?`\u2298 ${A.length} blocked`:"",L.length?`\u2717 ${L.length} broken`:"",j?`${j} not run (stopped)`:""].filter(Boolean).join(" ")+` ${y.length} run${f>0?` \xB7 ${f} held back`:""}`+Bw(Uw(W,y),b).map(U=>`
|
|
505
|
+
${U}`).join("")});let E=Ww(A);if(E.length>0&&h({kind:"note",tone:"info",text:E.join(`
|
|
506
|
+
`)}),L.length>0){let U=Math.max(...L.map(K=>K.id.length));h({kind:"note",tone:"error",text:L.map(K=>`\u2717 ${K.id.padEnd(U)} ${Gs(K.detail)}`).join(`
|
|
507
|
+
`)})}ta(e,y.map(U=>({id:U.id,outcome:U.outcome,reason:U.detail,specSource:go(e,U.id)})),new Date().toISOString()),y.length===u.length&&L.length===0&&A.length===0&&Cn(p?.runLine);let z=[];if(v.length>0&&Va()){let U=await Ti(v.map(K=>K.id),{verifiedBefore:new Set});if(U.cliMissing||(z=U.undrawn,U.drawn.length>0))return}else if(v.length>0){h({kind:"note",tone:"info",text:Wn(v.length)}),await Pe(on(e,v.map(K=>K.id)),{display:"/screenshot verify",quietUser:!0});let U=Cr(e,v.map(K=>K.id));U.length>0&&h({kind:"note",tone:"info",text:U.join(`
|
|
508
|
+
`)});return}let F=Hw({results:y,ids:u,articles:Gw(e,v.map(U=>U.id)),...z.length>0?{unannotated:z}:{}});F&&De(F.note,{kind:"cmd",cmd:F.cmd,reason:""},F.tone)},[e,h,De,Pe,Cn,Ti]),cc=ne(u=>{let p=Vn(u);if(!p||Do(p)&&!p.refreshToken)return null;let c={...Gr(p.idToken)??{},...Gr(p.accessToken)??{}};return c.email??c.preferred_username??"signed in"},[]),uc=ne((u,p)=>{if(p){let c=ge(e);c&&(c.defaultProfile=u,Lk(c,e))}i(u),ot(void 0,u),h({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${u}"${p?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),cc(u)||(h({kind:"note",tone:"warn",text:`Profile "${u}" is not signed in \u2014 sign in with /login.`}),oe("/login")),I(c=>c+1)},[e,h,ot,cc,oe]),Ai=ne((u,p,c)=>{ji(e,u,p,c.id,c.name),h({kind:"note",tone:"ok",text:`Switched to workspace "${c.name??c.id}" (agent restarted).`}),ot(),Fk(e,u)||(h({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),h({kind:"note",tone:"warn",text:"\u26A0 Before I write the docs, hand the prompt below to your builder (your repo's coding agent). It gives me the architecture brief that makes the docs accurate:"}),h({kind:"note",tone:"info",text:lr(ar(e)).join(`
|
|
509
|
+
`)}),pn(fo()),is.current=Gt(e).status==="current",Qo.current=mn(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,ot,pn]),Ei=ne(async u=>{let p;try{p=await fs(e,u)}catch{h({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),oe("/workspace");return}if(p.workspaces.length===0){h({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let c=p.workspaces.filter(S=>(S.workspace_type??"").toLowerCase()!=="apidocumentation"),f=c.length>0?c:p.workspaces;if(f.length===1){let S=f[0],M=p.workspaces.length-f.length;h({kind:"note",tone:"ok",text:`Selected the "${S.name??S.id}" workspace${M>0?" (skipped the API-documentation workspace)":""}.`}),Ai(p.profile,p.projectId,S);return}h({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${f.length} available).`}),oe("/workspace")},[e,h,Ai,oe]),Di=ne((u,p)=>{Ii(e,u,p.id,p.name),h({kind:"note",tone:"ok",text:`Project set to "${p.name??p.id}" (agent restarted).`}),ot(),Ei(u)},[e,h,ot,Ei]),qh=ne(async u=>{let p;try{p=kt(e,u)}catch{return}if(!p.project.workspaceId){if(p.project.projectId){if(!p.project.projectName)try{let{projects:c}=await fn(e,p.name),f=c.find(S=>S.id===p.project.projectId);f?.name&&M1(e,p.name,{projectName:f.name})}catch{}await Ei(p.name);return}try{let{projects:c}=await fn(e,p.name);if(c.length===1){let f=c[0];h({kind:"note",tone:"ok",text:`Using your Document360 project "${f.name??f.id}".`}),Di(p.name,{id:f.id,name:f.name});return}if(c.length>1){let f=c.map(S=>({id:S.id,name:S.name??S.id,sub:S.sub_domain}));h({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),zn({cursor:0,current:-1,rows:f,profile:p.name,environment:p.connection.name});return}}catch{}h({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),oe("/project")}},[e,h,Ei,Di,oe]),er=ne(()=>{let u=Ee.current[0];if(!u)return;if(Bt(),u.mode==="local-only"){h({kind:"note",tone:"info",text:`\u25CF ${u.title??u.path} (${u.path})`});for(let M of Ca())h({kind:"note",tone:"warn",text:`\u26A0 ${M}`});h({kind:"note",tone:"info",text:Pa()}),h({kind:"note",tone:"info",text:bg()});return}let{plan:p,mode:c}=u;h({kind:"note",tone:"info",text:`\u25CF ${p.title} (${p.path})`});for(let M of p.notes)h({kind:"note",tone:"warn",text:`\u26A0 ${M}`});p.overwritesLocalChanges&&c==="pull"&&h({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let f=Et(p.oldContent,p.newContent,Ke(),yr);h(f?{kind:"diff",added:f.added,removed:f.removed,lines:f.lines,hidden:f.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."});let S=Ee.current.length;c==="conflict"?(h({kind:"note",tone:"warn",text:"Conflict \u2014 edited both here and on the portal (diff shows local \u2192 portal)."}),h({kind:"note",tone:"info",text:"Keep local (publish, overwrites portal) \xB7 take Portal (overwrites local) \xB7 Skip?"}),h({kind:"note",tone:"info",text:S>1?`(l/p/s \xB7 la/pa/sa for all ${S} \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:S>1?`Write ${p.path}? (y/n \xB7 ya/na for all ${S} \u2014 anything else cancels)`:`Write ${p.path}? (y/n \u2014 anything else cancels)`})},[h,Ke,Bt]),co=ne(()=>{if(Ee.current.length>0){er();return}let u=_t.current;_t.current=[];let p=an.current;an.current=[];for(let c of Ta(p))h({kind:"note",tone:"warn",text:`\u26A0 ${c}`});u.length>0?(h({kind:"note",tone:"info",text:`Saving ${u.length} kept-local article${u.length===1?"":"s"} over the portal\u2026`}),ht(u,0,{allowUnpullable:!0})):p.length>0||oe("/pull")},[er,h,ht,oe]),dc=ne(u=>{let p=Rl(u);if(!p)return!1;let c=Ee.current.splice(0),f=c.length;if(p==="local"){for(let S of c)_t.current.push(oj(S));h({kind:"note",tone:"info",text:`Keeping local for all ${f} \u2014 will publish ${f===1?"it":"them"} over the portal.`})}else if(p==="portal"){let S=0;for(let M of c){if(M.mode==="local-only"){h({kind:"note",tone:"warn",text:`\u26A0 ${Eu(M.path)}`}),an.current.push(M.path);continue}try{_l({cwd:e,profileName:s},M.plan),S++}catch(W){h({kind:"note",tone:"error",text:`Take-portal failed for ${M.plan.path}: ${W.message}`})}}h({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${S} article${S===1?"":"s"} (local overwritten, sync base advanced).`})}else{for(let S of c)S.mode==="local-only"&&an.current.push(S.path);h({kind:"note",tone:"info",text:`Skipped all ${f} \u2014 still conflict${f===1?"":"s"}.`})}return co(),!0},[e,s,co,h]),Vh=ne(u=>{if(Ee.current.length===0)return!1;let p=u.trim(),c=p.toLowerCase(),f=Ee.current[0];if(f.mode==="local-only"){if(Rl(p))return dc(p);if(c==="l"||c==="local"||c==="publish")Ee.current.shift(),_t.current.push(f.path),h({kind:"note",tone:"info",text:`Publishing your copy of ${f.path} over the portal.`});else if(c==="s"||c==="skip")Ee.current.shift(),an.current.push(f.path),h({kind:"note",tone:"info",text:`Skipped ${f.path} \u2014 still a conflict.`});else{let M=Ee.current.splice(0),W=_t.current;return _t.current=[],an.current=[],h({kind:"note",tone:"info",text:`Resolve cancelled. ${M.length} conflict${M.length===1?"":"s"} left untouched.`+(W.length>0?` Saving the ${W.length} article${W.length===1?"":"s"} you already chose to keep - an answer you gave is not undone by stopping.`:"")}),W.length>0&&ht(W,0,{allowUnpullable:!0}),!0}return co(),!0}if(f.mode==="conflict"){if(Rl(p))return dc(p);if(c==="l"||c==="local")Ee.current.shift(),_t.current.push(f.plan.path),h({kind:"note",tone:"info",text:`Keeping local ${f.plan.path} \u2014 will publish over the portal.`});else if(c==="p"||c==="portal"){Ee.current.shift();try{_l({cwd:e,profileName:s},f.plan),h({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${f.plan.path} (local overwritten, sync base advanced).`})}catch(M){h({kind:"note",tone:"error",text:`Take-portal failed: ${M.message}`})}}else if(c==="s"||c==="skip"||c==="n")Ee.current.shift(),h({kind:"note",tone:"info",text:`Skipped ${f.plan.path} \u2014 still a conflict.`});else{let M=Ee.current.length;Ee.current=[];let W=_t.current;return _t.current=[],an.current=[],h({kind:"note",tone:"info",text:`Resolve cancelled. ${M} conflict${M===1?"":"s"} left untouched.`+(W.length>0?` Saving the ${W.length} article${W.length===1?"":"s"} you already chose to keep - an answer you gave is not undone by stopping.`:"")}),W.length>0&&ht(W,0,{allowUnpullable:!0}),!0}return co(),!0}let S=Bb(p);if(S){let M=Ee.current.splice(0);if(S==="skip")h({kind:"note",tone:"info",text:`Skipped all ${M.length} article${M.length===1?"":"s"}.`});else{let W=0;for(let b of M){if(b.mode==="local-only"){h({kind:"note",tone:"warn",text:`\u26A0 ${Eu(b.path)}`});continue}try{_l({cwd:e,profileName:s},b.plan),W++}catch(k){h({kind:"note",tone:"error",text:`Pull failed for ${b.plan.path}: ${k.message}`})}}h({kind:"note",tone:"ok",text:`\u2713 Pulled ${W} article${W===1?"":"s"} (sync base advanced).`})}return co(),!0}if(c==="y"||c==="yes"){let{plan:M}=f;Ee.current.shift();try{_l({cwd:e,profileName:s},M),h({kind:"note",tone:"ok",text:`\u2713 Pulled ${M.path} (sync base advanced).`})}catch(W){h({kind:"note",tone:"error",text:`Pull failed: ${W.message}`})}}else if(c==="n"||c==="no")Ee.current.shift(),h({kind:"note",tone:"info",text:`Skipped ${f.plan.path}.`});else{let M=Ee.current.length;return Ee.current=[],h({kind:"note",tone:"info",text:`Pull cancelled (${M} article(s) left untouched).`}),!0}return co(),!0},[e,s,co,h,dc]),pc=ne(async u=>{h({kind:"note",tone:"info",text:"Checking Document360 for conflicts\u2026"});try{let p=await Ml({cwd:e,profileName:s}),c=u?.replace(/\\/g,"/"),f=p.entries.filter(W=>W.status==="conflict"&&W.path).map(W=>W.path);if(c){if(!f.includes(c)){h({kind:"note",tone:"ok",text:`${c} isn\u2019t in conflict \u2014 nothing to resolve.`});return}f=[c]}if(f.length===0){h({kind:"note",tone:"ok",text:"\u2713 No conflicts \u2014 local and Document360 agree on every tracked article."});return}let S=[];for(let W of f)try{S.push({plan:await Uk({cwd:e,profileName:s,relPath:W}),mode:"conflict"})}catch(b){Wk(b)?S.push({mode:"local-only",path:W,title:Bk(e,W)}):h({kind:"note",tone:"error",text:`Could not load ${W} from Document360: ${b.message}`})}if(S.length===0)return;let M=S.some(W=>W.mode!=="local-only");h({kind:"note",tone:"info",text:M?`Resolving ${S.length} conflict${S.length===1?"":"s"} \u2014 for each: keep local, take portal, or skip.`:`Resolving ${S.length} conflict${S.length===1?"":"s"} \u2014 for each: publish your copy over the portal, or skip.`}),Ee.current=S,_t.current=[],an.current=[],er()}catch(p){h({kind:"note",tone:"error",text:`Could not compute sync status: ${p.message}`})}},[e,s,h,er]),Yh=ne(u=>{let p=Fo.current;if(!p)return!1;if(Fo.current=null,Bt(),u.trim()!==p.repoName)return h({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:c,failed:f}=dp(e,p.targets);h({kind:"note",tone:f.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${c.length} item${c.length===1?"":"s"}. The repo is back to its original state.`});for(let S of f)h({kind:"note",tone:"error",text:` \u2717 ${S.path}: ${S.error}`});return p.hadDevhints&&(h({kind:"note",tone:"warn",text:Yi().join(`
|
|
510
|
+
`)}),pn(Ec())),h({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
|
|
511
|
+
${Zk}`}),oe("/init"),Lt(!1),!0},[e,h,pn,Bt,oe]),uo=ne(async u=>{let p=u.slice(1).trim().split(/\s+/),c=(p[0]??"").toLowerCase(),f=p.slice(1);if(Ih.current=u.trim(),Lt(!0),_s(f)&&["write","lint","check","review","reorder"].includes(c)){let b=Os(e,s);if(b.length===0){h({kind:"note",tone:"warn",text:"No categories yet \u2014 author some articles first, then scope to one."});return}let k=x=>c==="write"?`/write ${Zg(f,x).join(" ")}`.trim():`/${c} ${[x,...f.filter(y=>y!=="--scope")].join(" ")}`.trim();if(b.length===1){uo(k(b[0].token));return}Qn({cursor:0,rows:b,run:x=>{uo(k(x))}});return}if(Un(c,f)){let b=c==="write"&&Ms(f).rewrite,k=c==="write"?gd(e,Vk(e),{rewrite:b}):Os(e,s);if(k.length>1){let x=f.filter(K=>K.startsWith("--")).join(" "),y=K=>K==="--blocked"?`/${c} --blocked${x?` ${x}`:""}`.trim():`/${c}${K?` ${c==="write"?`--scope ${K}`:K}`:""}${x?` ${x}`:""} ${K?"":"--all"}`.replace(/\s+/g," ").trim(),v=k.reduce((K,ee)=>K+ee.count,0),A={token:"",label:c==="review"?`Everything \u2014 all ${v} articles + structure (IA) review`:c==="reorder"?`Everything \u2014 reorder all ${k.length} categories`:b?`Everything \u2014 rewrite all ${v} planned articles`:`Everything \u2014 write all ${v} pending article${v===1?"":"s"}`,count:v},L=c==="review"?xp(e):[],j=L.length>0&&L.length<v?[{token:"--blocked",label:`Only what needs review \u2014 ${L.length} article${L.length===1?"":"s"} publishing is blocked on`,count:L.length}]:[],E=c==="review"?Rp(e):[],z=E.length>L.length&&E.length<v?[{token:"--stale",label:`Everything the current editor hasn\u2019t read \u2014 ${E.length} article${E.length===1?"":"s"}`,count:E.length}]:[],F=c==="write"?`Write which articles? (counts = ${b?"articles to regenerate":"still to write"})`:c==="review"?"Review what? (counts = articles)":"Reorder what?";Qn({cursor:0,rows:(K=>c==="review"||c==="write"?K.map(ee=>{let ue=(()=>{try{return Ay(e,y(ee.token))}catch{return null}})();return ue?{...ee,label:`${ee.label} \xB7 ${ue}`}:ee}):K)([...j,...z,A,...k]),run:K=>{uo(y(K))},title:F});return}}let S=async b=>{let k=Ed(b);if(!vo(e)){await Pe(_d(),{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 y=Dd(e,qs(e).rows);if(y.length===0){h({kind:"note",tone:"info",text:"No broken specs to re-run \u2014 /screenshot list shows where things stand."}),oe("/screenshot list");return}await cs(y);return}if(k.mode==="blocked"){let{blocked:y,rows:v}=qs(e);if(y.length===0){h({kind:"note",tone:"info",text:"No shots are waiting on app data \u2014 /screenshot list shows where things stand."}),oe("/screenshot list");return}let A=vs(v.filter(L=>L.state==="blocked")).length;h({kind:"note",tone:"info",text:`Re-running ${y.length} shot${y.length===1?"":"s"} that skipped on missing data last run.`+(A>0?` If you haven't staged ${A===1?"it":"those "+A+" things"} yet, ${y.length===1?"it":"they"} will skip again \u2014 /screenshot list has the worklist.`:"")}),await cs(y,{runLine:["/screenshot capture --blocked","/screenshot capture --all --retry-blocked"]});return}if(k.mode==="all"||k.mode==="scope"){let y=k.mode==="scope"?k.scope:void 0,{ready:v,captured:A,blocked:L,rows:j}=qs(e,y),E=[...v,...A,...k.retryBlocked?L:[]];if(E.length===0&&L.length>0&&!k.retryBlocked){let F=y?`/screenshot capture ${y} --retry-blocked`:"/screenshot capture --blocked";De(`All ${L.length} shot${L.length===1?"":"s"} in scope ${L.length===1?"is":"are"} blocked on data that wasn't staged last run \u2014 /screenshot list shows what to stage, then ${F}.`,{kind:"cmd",cmd:"/screenshot list",reason:""},"warn");return}if(E.length===0){h({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),oe("/screenshot");return}if(!k.retryBlocked){let F=y?`/screenshot capture ${y} --retry-blocked`:"/screenshot capture --blocked",U=Nd(j.filter(K=>K.state==="blocked"),F);U&&h({kind:"note",tone:"info",text:U})}let z=k.mode==="scope"?[`/screenshot capture ${k.scope}`,`/capture ${k.scope}`]:["/screenshot capture --all","/capture --all"];await cs(E,{runLine:z,...k.retryBlocked?{}:{heldBackBlocked:j.filter(F=>F.state==="blocked")}});return}let x=jw(Fe(e));if(x.length===0){h({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),oe("/screenshot");return}Xn({cursor:0,rows:x,title:"Capture screenshots \u2014 pick what to shoot:"})},M=async b=>{let k=Fd(b);if(!vo(e)){h({kind:"note",tone:"info",text:"Screenshot capture is not set up in this repo yet. Run /screenshot capture and it will walk you through it."}),oe("/screenshot capture");return}let x=mt();if(!Va(x)){h({kind:"note",tone:"info",text:Wd(x)}),oe("/update");return}let y=k.mode==="scope"?k.scope:void 0,{pending:v,done:A,rows:L}=Ud(e,y),j=k.mode==="all"||k.mode==="scope"?k.force:!1,E=k.mode==="single"?[k.id]:j?[...v,...A]:v;if(E.length===0){h({kind:"note",tone:"info",text:A.length>0?`Every shot${y?` under ${y}`:""} is already drawn on. To re-draw them anyway (after a wording or style change): /screenshot annotate --all --force`:"No shots have been taken yet \u2014 /screenshot capture takes them first."}),oe(A.length>0?"/screenshot annotate --all --force":"/screenshot capture");return}await Ti(E,{force:j,scope:y,verifiedBefore:new Set(L.filter(z=>z.state==="verified").map(z=>z.id))})},W=async()=>{let b=await Tr(f,{cwd:e,profileName:s});b.kind==="forward-to-agent"&&b.prompt&&await Pe(b.prompt,{display:b.display,quietUser:!0}),Ql()};switch(c){case"help":oo({tab:0,scroll:0});return;case"exit":case"quit":Ot.current?.close(),r();return;case"clear":ot(),Mo.current=[],lt.current={printed:[],armed:[],printedAt:zo.current},Lt(!1),Bt(),console.log("\x1B[?2026h\x1B[H\x1B[2J\x1B[3J\x1B[?2026l"),h({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let b;try{b=kt(e,s)}catch(k){h({kind:"note",tone:"error",text:k.message});return}h({kind:"note",tone:"info",text:`Profile "${b.name}" \u2192 ${b.connection.name} (${b.connection.apiUrl})${b.production?" \u26A0 PRODUCTION":""}`}),N(!0);try{let k=await zN(b.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},v=>h({kind:"note",tone:"info",text:v})),x=XN(b.name,k);QN(x),await kc(x,b.name,v=>h({kind:"note",tone:"info",text:v}));let y=jk(x);if(y){let v=kt(e,s).project;await bc(b.name,y,v.projectId===y?v.projectName:void 0)}if(h({kind:"note",tone:"ok",text:`\u2713 Logged in to "${b.name}" as ${Oi(Vn(b.name,y??void 0)??x)}`}),await qh(s),!to.current){let v=Ve(e,s);v.ok||(h({kind:"note",tone:"warn",text:v.reason}),oe("/login"))}if(to.current){let v=to.current;to.current=null;let A=Ve(e,s);A.ok?(h({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 tab to run ${v}.`}),oe(v)):(h({kind:"note",tone:"warn",text:`${A.reason} (then ${v}.)`}),oe("/login"),to.current=v)}else es.current&&(nt(es.current,"\u21E5 tab to re-send your last prompt\u2026"),es.current=null)}catch(k){if(h({kind:"note",tone:"error",text:`Login failed: ${k.message}`}),!Zi(e,s)){let x=to.current;h({kind:"note",tone:"warn",text:`Your Document360 session still isn't working, so nothing here can reach your portal${x?` \u2014 ${x} is still waiting`:""}. Run /login to try again.`}),oe("/login")}}finally{N(!1),I(k=>k+1)}return}case"allow-prod":{let b=!1;try{b=kt(e,s).production}catch{}if(!b){h({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}Rn.current=!0,ot(),h({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let b=Rd(f.join(" ")),k=sn.current.uuid;if(!k){if(!b){h({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}Bl.current=b,Yn(b),_r(`${Tl} ${b}`),h({kind:"note",tone:"ok",text:`Session will be named "${b}" once it starts.`});return}if(!b){h({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let x=sn.current.firstPrompt??"";Ik(x,e).then(y=>{y?(nt(`/rename ${y}`),h({kind:"note",tone:"info",text:`Suggestion: "${y}" \u2014 press tab to accept, or type /rename <your name>.`})):h({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>h({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}d1(k,b),Yn(b),_r(`${Tl} ${b}`),h({kind:"note",tone:"ok",text:`Session renamed to "${b}".`});return}case"profile":{let b=f[0],k=ge(e);if(!b){let x=Object.entries(k?.profiles??{});if(x.length===0){h({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let y=x.map(([L,j])=>({name:L,env:j.connection?.environment??"custom",prod:j.production===!0,who:cc(L)})),v=s??k?.defaultProfile,A=Math.max(0,y.findIndex(L=>L.name===v));Uo({cursor:A,current:A,rows:y});return}if(b==="add"){let x=Sd(e,f[1],f[2]);if(x){h({kind:"note",tone:"error",text:x});return}h({kind:"note",tone:"ok",text:`\u2713 Profile "${f[1]}" created (environment: ${f[2]??f[1]}).`}),uc(f[1],!0);return}if(!k?.profiles?.[b]){h({kind:"note",tone:"error",text:`Unknown profile "${b}". Create it: /profile add ${b} <environment>`});return}uc(b,!0);return}case"doctor":await Us(f,{cwd:e,version:o});return;case"logs":{let b=$c();h({kind:"note",tone:"info",text:b.lines.join(`
|
|
512
|
+
`)}),b.copyText&&pn(b.copyText,{hint:b.notable?"\u2328 Press c to copy this problem report \u2014 then send it to the team (Teams / Slack / email).":"\u2328 Press c to copy this entry, if you want to send it to the team."});return}case"style-guide":{let b=bp(e),k=await al(f,{cwd:e,profileName:s});if(b&&il(f).sub==="show"&&De(null,{kind:"cmd",cmd:"/style-guide keep",reason:""}),k.kind==="clear")ot(),h({kind:"note",tone:"ok",text:"\u2713 Agent restarted \u2014 it now writes to the new rules."});else if(k.kind==="forward-to-agent"){let x=il(f).sub==="learn";(await Pe(k.prompt,{display:k.display,quietUser:!0})).producedNothing||(h({kind:"note",tone:"info",text:(x?xy():Ry()).join(`
|
|
513
|
+
`)}),x&&(ot(),h({kind:"note",tone:"ok",text:"\u2713 Agent restarted \u2014 it now writes to your house rules."})))}I(x=>x+1);return}case"genre":{let b=ge(e)?.appType??null;(await ul(f,{cwd:e})).kind==="clear"&&(ge(e)?.appType??null)!==b&&(ot(),h({kind:"note",tone:"ok",text:"\u2713 Agent restarted \u2014 the doc-craft playbook for this genre is now loaded."}));try{Ce.current=!(ge(e)?.appType??Mk(e))}catch{}I(x=>x+1);return}case"roadmap":{if(f[0]?.toLowerCase()==="done"){let b=mr(e,f.slice(1).join(" ").trim());h({kind:"note",tone:b.ok?"ok":"warn",text:b.line}),I(k=>k+1);return}h({kind:"block",text:lu(e,{width:Ke(),all:f.some(b=>b.toLowerCase()==="--all")}).join(`
|
|
514
|
+
`)});return}case"mcp":await Xi(f);return;case"init":{if(ge(e)){let k=Tn(e,s);h({kind:"note",tone:"info",text:["This repo is already set up \u2014 /init won\u2019t overwrite it.",` Change environment: /profile add <${Hk().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(`
|
|
515
|
+
`)}),k&&h({kind:"note",tone:"warn",text:`\u26A0 ${k.why} \u2014 ${k.cmd} moves this repo.`});return}let b=[...Hk(),...S1().filter(k=>Gk(k))].map(k=>({name:k,apiUrl:C1(k).apiUrl,note:Gk(k)?"being retired":null}));Wo({cursor:0,rows:b});return}case"resume":{let b=f.join(" ").trim(),k=u1(e).filter(v=>v.uuid!==sn.current.uuid);if(!b){if(!k.length){h({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}no({query:"",cursor:0,sessions:k});return}let x=c1(e,b);if(!x){h({kind:"note",tone:"error",text:`No session matches "${b}".`});return}ot(x.uuid),sn.current={uuid:x.uuid,firstPrompt:x.firstPrompt,titleFired:!0},Yn(x.name),oh(x.uuid),Mo.current=[],lt.current={printed:[],armed:[],printedAt:zo.current};let y=zp(e,x.uuid);for(let v of y)h(v);h({kind:"note",tone:"ok",text:y.length?`Resumed "${x.name}" \u2014 restored ${y.length} message(s); continue where you left off.`:`Resumed "${x.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let b=f.join(" ").trim(),k;try{k=await fs(e,s)}catch(y){h({kind:"note",tone:"error",text:`Could not list workspaces: ${y.message}`});return}if(!b){let y=k.workspaces.map(A=>({id:A.id,name:A.name??A.id,type:A.workspace_type}));if(y.length===0){h({kind:"note",tone:"info",text:"No workspaces in this project."});return}let v=Math.max(0,y.findIndex(A=>A.id===k.current));Bo({cursor:v,current:v,rows:y,profile:k.profile,projectId:k.projectId,projectName:k.projectName,environment:k.environment});return}let x=mc(k.workspaces,b);if(!x){h({kind:"note",tone:"error",text:`No workspace matches "${b}".`});return}Ai(k.profile,k.projectId,x);return}case"project":{let b=f.join(" ").trim(),k;try{k=await fn(e,s)}catch(y){h({kind:"note",tone:"error",text:`Could not list projects: ${y.message} (signed in? try /login)`});return}if(!b){let y=k.projects.map(A=>({id:A.id,name:A.name??A.id,sub:A.sub_domain}));if(y.length===0){h({kind:"note",tone:"info",text:"No projects found for this identity."});return}let v=y.findIndex(A=>A.id===k.current);zn({cursor:Math.max(0,v),current:v,rows:y,profile:k.profile,environment:k.environment});return}let x=gc(k.projects,b);if(!x){h({kind:"note",tone:"error",text:`No project matches "${b}". Available: ${k.projects.map(y=>y.name??y.id).join(", ")}`});return}Di(k.profile,x);return}case"logout":{let b,k,x;try{let j=kt(e,s);b=j.name,k=j.project.projectId,x=j.project.projectName}catch(j){h({kind:"note",tone:"error",text:j.message});return}let y=f.includes("--all-projects"),v=r1(b).filter(j=>{let E=jk(j);return!!E&&E!==k}).length,A=n1(b,y?void 0:k);s1(e,b),ot(),I(j=>j+1);let L=y||v===0?"":` Your sign-in for ${v} other project${v===1?"":"s"} is untouched (/logout --all-projects clears those too).`;h({kind:"note",tone:A?"ok":"info",text:A?y?`\u2713 Signed out of every Document360 project for "${b}" and cleared this repo's project/workspace selection.`:`\u2713 Signed out of ${x?`"${x}"`:`"${b}"`} and cleared its project/workspace selection.${L}`:`Profile "${b}" was not signed in. Cleared any project/workspace selection.${L}`}),h({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),oe("/login");return}case"publish":{if(yu(f)){let E=wn("publish");E&&h({kind:"note",tone:"info",text:E}),await uo(`/push ${f.join(" ")}`.trim());return}if(!ao(u.trim()))return;let b=wn("publish");b&&h({kind:"note",tone:"info",text:b});let k=f.find(E=>!E.startsWith("--")),x={skipReview:f.includes(At),skipStyle:f.includes(Jk)};Be("Checking what is waiting to go live\u2026");let y;try{y=await bu(e,s,k)}catch(E){h({kind:"note",tone:"error",text:`Could not check Document360: ${E.message}`});return}finally{Be(null)}if(y.length===0){let E=ku(e,s,k);for(let z of E.lines)h({kind:"note",tone:z.startsWith("\u2713")?"ok":"info",text:z});E.ahead>0&&oe(Re("/push","",k));return}let v=lh(e,y.map(E=>E.path),{allowUnreviewed:x.skipReview,allowStyleErrors:x.skipStyle,checkScreenshots:!0,allowPlaceholders:f.includes(G1)}),A=H1(v),L=y.filter(E=>A.has(E.path)),j=y.filter(E=>!A.has(E.path));if(L.length>0)for(let E of ch(v,y.length,{scope:k,act:"publish",going:j.length}))h({kind:"note",tone:"warn",text:E});if(j.length===0){oe(Re("/review","--blocked --fix",k));return}if(y=j,Ge.current&&fi.current){h({kind:"note",tone:"info",text:`Taking ${y.length} draft${y.length===1?"":"s"} live \u2014 you approved this run when it started.`}),await Wh(y,x);return}h({kind:"note",tone:"info",text:`${y.length} draft${y.length===1?" is":"s are"} ahead of what readers see. Pick what goes live:`}),Go({cursor:0,rows:y,opts:x});return}case"push":{if(!ao(u.trim()))return;let b=f.includes(At),k=f.includes(Jk);if(f.includes("--preview")){let A=f.find(L=>!L.startsWith("--"));if(!A){h({kind:"note",tone:"error",text:"Which article? Use /push --preview <path> \u2014 a preview is per article."});return}try{let L=await k1({cwd:e,profileName:s,relPath:A.replace(/\\/g,"/"),preview:!0}),j=L.shots.length>0?` \xB7 ${L.shots.length} screenshot${L.shots.length===1?"":"s"} embedded`:"";h({kind:"note",tone:"info",text:`${L.title}
|
|
516
|
+
${L.path} \xB7 ${L.articleId?`updates article ${L.articleId}`:"would be created as a new article"}${j}`}),L.missingShots.length>0&&h({kind:"note",tone:"warn",text:`\u26A0 ${L.missingShots.length} screenshot${L.missingShots.length===1?"":"s"} not taken yet \u2014 the description publishes instead: ${L.missingShots.join(", ")}`}),h({kind:"note",tone:"info",text:L.body}),h({kind:"note",tone:"info",text:`Nothing was sent. /push ${L.path} saves it as a draft.`}),oe(`/push ${L.path}`)}catch(L){h({kind:"note",tone:"error",text:L.message})}return}if(f.includes("--screenshots")||f.includes("--shots")){let A=f.find(F=>!F.startsWith("--")),L=Fe(e),j=la(L,A);if(j.length===0){let F=L.filter(U=>U.state==="captured").length;h({kind:"note",tone:"info",text:F>0?`${F} screenshot${F===1?" has":"s have"} been taken but the callouts aren't drawn on yet, so there is nothing to embed \u2014 /screenshot annotate finishes ${F===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."}),F>0&&oe("/screenshot annotate");return}let E=ca(L,A);E&&h({kind:"note",tone:"warn",text:E});let z=ua(L);z&&h({kind:"note",tone:"warn",text:z}),h({kind:"note",tone:"info",text:`Re-saving ${j.length} article${j.length===1?"":"s"} with captured screenshots so the images embed\u2026`}),await ht(j,0,{skipReview:b,skipStyle:k,scope:Re("","--screenshots",A).trim()});return}if(f[0]==="--related"&&f[1]){let A=await ka(e,s,f[1].replace(/\\/g,"/"));if(A.length===0){h({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await ht(A,0,{skipReview:b,skipStyle:k,scope:`--related ${f[1]}`});return}let x=f.filter(A=>!A.startsWith("--"));if(x[0]){await lc(x[0],{skipReview:b,skipStyle:k});return}let y=f.includes("--all"),v=f.includes("--force");h({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let A=await Ml({cwd:e,profileName:s}),{clean:L,conflicts:j}=yo(A.entries),E=y&&v&&j.length>0,z=wa(A.entries);if(z>0&&h({kind:"note",tone:"warn",text:`\u26A0 ${z} article${z===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.`}),j.length>0&&!E&&h({kind:"note",tone:"warn",text:Rs(j.length)}),L.length===0&&!E){let F=gr(e,s);if(F&&h({kind:"note",tone:"info",text:F}),j.length>0){oe("/resolve");return}h({kind:"note",tone:"ok",text:z>0?"\u2713 Nothing else is ahead of Document360 to save.":"\u2713 Nothing is ahead of Document360 \u2014 nothing to save."});let U=A.counts["unknown-base"]??0;U>0&&h({kind:"note",tone:"info",text:`(${U} article(s) have no sync base yet \u2014 /push <path> saves one anyway if you need it.)`}),Be("Reconciling structure on Document360 (order + related articles)\u2026");try{let K=await ih({cwd:e,profileName:s,onRateLimit:fe=>Be(`Document360 rate limit \u2014 waiting ${Math.ceil(fe.waitMs/1e3)}s\u2026`)}),ee=Qk(await Xk({cwd:e,profileName:s})),ue=ah(K);ue?h({kind:"note",tone:ue.startsWith("\u26A0")?"warn":"info",text:ue}):K.skipped&&h({kind:"note",tone:"warn",text:`Order sync skipped: ${K.skipped}`}),ee&&h({kind:"note",tone:"info",text:ee}),K.failures?.length?oe("/structure"):(h({kind:"note",tone:"ok",text:ue||ee?"\u2713 Structure synced to Document360 \u2014 /structure shows the new category + article order.":"\u2713 Already in order \u2014 nothing to change."}),(ue||ee)&&oe("/structure"))}catch(K){h({kind:"note",tone:"warn",text:`Structure sync failed: ${K.message}`})}finally{Be(null)}return}if(y){let F=(E?[...L,...j]:L).map(U=>U.path);await ht(F,E?0:j.length,{skipReview:b,skipStyle:k,allowUnpullable:E});return}Ho({cursor:0,rows:sg(L,j),conflicts:j.length})}catch(A){h({kind:"note",tone:"error",text:`Could not compute sync status: ${A.message}`}),h({kind:"note",tone:"info",text:"Save one article on its own: /push <article-path>"})}return}case"resolve":{if(!ao(u.trim()))return;await pc(f.find(b=>!b.startsWith("--")));return}case"preview":{let b=f.join(" ").trim();if(!b){let x=[];try{x=Object.keys(Fk(e,kt(e,s).name)?.articles??{})}catch{}if(x.length===0){h({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}Jn({query:"",cursor:0,paths:x});return}let k=YN(b)?b:li(e,b);if(Fr(k)){try{h({kind:"preview",name:ai(k),text:o$(Ll(k,"utf8"))})}catch(x){h({kind:"note",tone:"error",text:`Could not read ${k}: ${x.message}`})}return}if(aj.test(b)){try{let x=kt(e,s),y={profile:x.name,connection:x.connection},v=x.project.projectId??e1(y),A=await t1(y,v,b);h({kind:"preview",name:A.title??b,text:A.content??"*(article has no content)*"})}catch(x){h({kind:"note",tone:"error",text:`Could not fetch article: ${x.message}`})}return}h({kind:"note",tone:"error",text:`"${b}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let b=f[0]?.trim();if(!b){let v=Ba(dh(e));Kn({cursor:v,current:v});return}let{lines:k,changed:x,effective:y}=Fs(e,b);for(let v of k)h({kind:"note",tone:v.startsWith("\u26A0")?"warn":v.startsWith("\u2713")?"ok":"info",text:v});x&&(Ah(v=>v+1),Ot.current?.setModel(y));return}case"verbose":{let b=f[0]?.trim().toLowerCase(),k=b==="on"?!0:b==="off"?!1:!pi.current;pi.current=k;try{m1({..._k(),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(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:b,run:k}=Gu(f),x=A1(e,s);if(x.length===0){h({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Save some to Document360 first (/push), then /convert."});return}let y=qu(x,b);if(y.length===0){h({kind:"note",tone:"error",text:`No tracked articles under "${b}". (${x.length} are tracked overall.)`});return}let v=rh(y),A=3,L=`/convert${b?` --scope ${b}`:""} --run`,j=ui(e,"light");if(!k){let F=qk({files:Vu(e,y),op:"convert",model:j.model}),U=b?`Scope: ${b} (${y.length} of ${x.length} tracked)
|
|
517
517
|
`:"",K=`
|
|
518
|
-
Model: ${j.model}${j.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;h({kind:"note",tone:"info",text:U+
|
|
519
|
-
`)+K}),
|
|
520
|
-
`):U+
|
|
521
|
-
`)}),
|
|
518
|
+
Model: ${j.model}${j.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;h({kind:"note",tone:"info",text:U+Ku(v,F,A).join(`
|
|
519
|
+
`)+K}),oe(L);return}_e.current=Date.now(),be(0),T(!0);let E=new AbortController;Me.current=E;let z=Date.now();pe({verb:"Converting",total:v.length,done:0,active:[],rows:Eo(v),tools:0,chars:0,lastAt:Date.now(),startedAt:z}),h({kind:"note",tone:"info",text:`Converting ${y.length} articles in ${v.length} batches (\u2264${A} agents at once) on ${j.model}\u2026 (esc to stop)`});try{for await(let F of ci({cwd:e,partitions:v,promptFor:Yu,concurrency:A,profileName:s,allowProdWrites:Rn.current,model:j.model,signal:E.signal}))if(F.type==="partition_status")F.status==="running"?pe(U=>U&&{...U,active:[...U.active,F.label],rows:ze(U.rows,F.label,"active"),lastAt:Date.now()}):pe(U=>U&&{...U,active:U.active.filter(K=>K!==F.label),done:U.done+1,rows:ze(U.rows,F.label,F.status==="done"?"done":"failed"),lastAt:Date.now()});else if(F.type==="partition_stalled"){let U=Or(F);pe(K=>K&&U?{...K,stalledNote:U}:K)}else if(F.type==="partition_event")pe(U=>{if(!U)return U;let K={...U,lastAt:Date.now()};return F.event.type==="tool"?K.tools=U.tools+1:F.event.type==="text"&&(K.chars=U.chars+F.event.delta.length),K});else if(F.type==="run_done"){so(ue=>ue+F.totalCostUsd),ro(ue=>ue+F.results.reduce((fe,we)=>fe+we.outputTokens,0));let U=F.aborted?"Stopped. ":"",K=t.kind==="api"?"api":"subscription",ee=On(F,"The conversion");h({kind:"note",tone:ee||F.aborted?"warn":F.ok?"ok":"warn",text:ee?ee.join(`
|
|
520
|
+
`):U+zu(F.results,v,K).join(`
|
|
521
|
+
`)}),Zo(z,F.results,F.totalCostUsd,!ee&&!F.aborted&&F.ok),ee&&oe("/doctor")}}catch(F){h({kind:"note",tone:"error",text:`Convert run failed: ${F.message}`})}finally{Me.current=null,pe(null),T(!1),I(F=>F+1)}return}case"write":{if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let b=Vk(e);if(b.length===0){h({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:k,path:x,preview:y,concurrency:v,rewrite:A}=Ms(f);if(!x&&!y&&!(ge(e)?.appType??Mk(e))){h({kind:"note",tone:"warn",text:`\u26A0 No doc genre is set, so no doc-craft playbook would load \u2014 all ${b.length} articles would be written generically.
|
|
522
522
|
Pick the genre below (one keypress), then run /write again \u2014 it changes structure, titles and depth for every article.
|
|
523
|
-
Not blocked: /write <path> still authors a single article, and /write --preview costs nothing.`}),ie(
|
|
523
|
+
Not blocked: /write <path> still authors a single article, and /write --preview costs nothing.`}),ie(pl.options.map(Q=>({cmd:Q.cmd,desc:Q.desc}))),qo(pl.title);return}let{docsDir:L,targets:j,reason:E,rewriting:z}=Ua(e,b,{scope:k,path:x,rewrite:A});if(j.length===0){h({kind:"note",tone:"warn",text:E??"Nothing to write."});return}z&&h({kind:"note",tone:"warn",text:`--rewrite: regenerating ${j.length} already-written article${j.length===1?"":"s"} (overwrites them; git has your baseline).`});let F=rh(j),U=ld(v),K=ui(e,"standard"),ee=!!x;if(y&&!ee){let Q=qk({files:cd(e,b,j),op:"write",model:K.model}),$e=k?`Scope: ${k} (${j.length} pending)
|
|
524
524
|
`:"",Ie=`
|
|
525
|
-
Model: ${K.model}${K.forced?" (forced)":" \u2014 authoring; /model to override"}`;h({kind:"note",tone:"info",text:$e+
|
|
526
|
-
`)+Ie}),
|
|
527
|
-
`):$e+
|
|
528
|
-
`)}),
|
|
529
|
-
`)})}if(!Q.aborted&&Q.ok){let
|
|
525
|
+
Model: ${K.model}${K.forced?" (forced)":" \u2014 authoring; /model to override"}`;h({kind:"note",tone:"info",text:$e+dd(F,Q,U).join(`
|
|
526
|
+
`)+Ie}),oe(`/write${k?` --scope ${k}`:""}`);return}_e.current=Date.now(),be(0),T(!0);let ue=new AbortController;Me.current=ue;let fe=Date.now();pe({verb:"Writing",total:F.length,done:0,active:[],rows:Eo(F),tools:0,chars:0,lastAt:Date.now(),startedAt:fe}),h({kind:"note",tone:"info",text:`Writing ${j.length} article${j.length===1?"":"s"} in ${F.length} batch${F.length===1?"":"es"} (\u2264${U} agents at once) on ${K.model}${K.forced?" (forced)":""}\u2026 (esc to stop)`});let we=new Set;try{for await(let Q of ci({cwd:e,partitions:F,promptFor:$e=>ud($e,L,{rewrite:z||ee}),concurrency:U,profileName:s,allowProdWrites:Rn.current,model:K.model,signal:ue.signal}))if(Q.type==="partition_status")Q.status==="running"?pe($e=>$e&&{...$e,active:[...$e.active,Q.label],rows:ze($e.rows,Q.label,"active"),lastAt:Date.now()}):pe($e=>$e&&{...$e,active:$e.active.filter(Ie=>Ie!==Q.label),done:$e.done+1,rows:ze($e.rows,Q.label,Q.status==="done"?"done":"failed"),lastAt:Date.now()});else if(Q.type==="partition_stalled"){let $e=Or(Q);pe(Ie=>Ie&&$e?{...Ie,stalledNote:$e}:Ie)}else if(Q.type==="partition_event"){let $e=null;if(Q.event.type==="tool"){let Ie=eh(Q.event.name,Q.event.input,F[Q.index]?.paths??[]);Ie&&!we.has(Ie)&&(we.add(Ie),$e=Q.label)}pe(Ie=>{if(!Ie)return Ie;let Ht={...Ie,lastAt:Date.now()};return Q.event.type==="tool"?Ht.tools=Ie.tools+1:Q.event.type==="text"&&(Ht.chars=Ie.chars+Q.event.delta.length),$e&&(Ht.rows=El(Ht.rows,$e)),Ht})}else if(Q.type==="run_done"){so(rt=>rt+Q.totalCostUsd),ro(rt=>rt+Q.results.reduce((Pt,ho)=>Pt+ho.outputTokens,0));let $e=Q.aborted?"Stopped. ":"",Ie=t.kind==="api"?"api":"subscription",Ht=On(Q,"The write");if(h({kind:"note",tone:Ht||Q.aborted?"warn":Q.ok?"ok":"warn",text:Ht?Ht.join(`
|
|
527
|
+
`):$e+pd(Q.results,F,Ie,k??x).join(`
|
|
528
|
+
`)}),Zo(fe,Q.results,Q.totalCostUsd,!Ht&&!Q.aborted&&Q.ok),Ht){oe("/doctor");continue}let Qh=Tg(Q);if(Qh&&h({kind:"note",tone:"warn",text:Qh}),!Q.aborted&&Q.ok)try{let rt=(we.size>0?[...we]:j).map(Pt=>`${L}/${Pt}`);Wr(e,rt,{writtenCap:O1,reviewedCap:0,checkedCap:0})}catch{}let po=Q.aborted?[]:Sr(e,L,j),Jh=hd(po);Jh&&h({kind:"note",tone:"warn",text:Jh});let nr=Q.aborted||f.includes("--skip-style")?null:fd(po);if(nr){let rt=nr.errors.length,Pt=await Pi({partitions:nr.partitions,promptFor:nr.promptFor,concurrency:vr,verb:"Fixing",doneNoun:"fixed",headline:`${rt} style error${rt===1?"":"s"} in ${nr.articles} of the new article${nr.articles===1?"":"s"} \u2014 fixing now, one pass`});if(Pt.covered.length>0)try{Wr(e,Pt.covered,ut("lint"))}catch{}po=Sr(e,L,j);let ho=md(rt,po);h({kind:"note",tone:ho[0].startsWith("\u2713")?"ok":"warn",text:ho.join(`
|
|
529
|
+
`)})}if(!Q.aborted&&Q.ok){let rt=k??x??"",Pt=rt?` ${rt}`:"",ho=po.some(or=>or.severity==="error");{let or=sh(F,Q.results);Cn(`/write${k?` --scope ${k}`:""}${f.includes("--rewrite")?" --rewrite":""}`,{aborted:Q.aborted,partitions:F.length,failed:or.failed.length,notRun:or.notRun.length,leftBehind:po.filter(v$=>v$.severity==="error").length,...Q.blocked?{blocked:Q.blocked}:{},...Q.allEmpty?{allEmpty:!0}:{},...Q.bailedEmpty?{bailedEmpty:!0}:{}})}let Zh=rt?"/push":"/push --all",$$=rt?`/screenshot author ${rt}`:"/screenshot author --all";De(ho?`Written, but ${po.filter(or=>or.severity==="error").length} style error(s) are still unfixed. /lint${Pt} --blocked --fix retries them, then /review${Pt} --fix for editorial quality, then ${Zh}.`:`Written. I\u2019d run /review${Pt} --fix next \u2014 editorial review that applies its fixes \u2014 then ${Zh} saves them to Document360 as drafts (add ${$$} first if you want images).`,{kind:"cmd",cmd:ho?`/lint${Pt} --blocked --fix`:`/review${Pt} --fix`,reason:""})}}}catch(Q){h({kind:"note",tone:"error",text:`Write run failed: ${Q.message}`})}finally{Me.current=null,pe(null),T(!1),I(Q=>Q+1)}return}case"draft":{if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:b,looseDocs:k}=wd(e);if(b.length===0&&k===0){h({kind:"note",tone:"info",text:bd});return}let x=f.join(" ").trim();if(!x&&b.length>1){h({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
|
|
530
530
|
${b.map(A=>` \u2022 ${A.name} (${A.docCount} doc${A.docCount===1?"":"s"})`).join(`
|
|
531
|
-
`)}`}),ie(b.map(A=>`/draft ${A.name}`));return}let y="",v;if(x){let A=
|
|
532
|
-
`)});return}if(b==="--baseline"){let y=f.find(j=>!j.startsWith("--")),v=y?y.replace(/\\/g,"/"):void 0;h({kind:"note",tone:"info",text:v?`Setting the sync baseline for ${v}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let A=await
|
|
531
|
+
`)}`}),ie(b.map(A=>`/draft ${A.name}`));return}let y="",v;if(x){let A=yd(b,x);A?y=A:v=x}else y=b[0]?.name??"";await Pe(Wa(y,v),{display:x?`/draft ${x}`:"/draft",quietUser:!0});return}case"pull":{if(!ao(u.trim()))return;let b=f.find(k=>k.startsWith("--"));try{if(b==="--status"){h({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let y=Date.now(),v=await Ml({cwd:e,profileName:s});h({kind:"note",tone:"info",text:Sa(v,Date.now()-y).join(`
|
|
532
|
+
`)});return}if(b==="--baseline"){let y=f.find(j=>!j.startsWith("--")),v=y?y.replace(/\\/g,"/"):void 0;h({kind:"note",tone:"info",text:v?`Setting the sync baseline for ${v}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let A=await v1({cwd:e,profileName:s,relPaths:v?[v]:void 0}),L=v?{rebaselined:[],skipped:[]}:await x1({cwd:e,profileName:s});if(A.baselined.length===0&&A.skipped.length===0&&L.rebaselined.length===0){h({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}A.baselined.length>0&&h({kind:"note",tone:"ok",text:`\u2713 Recorded ${A.baselined.length} article${A.baselined.length===1?"":"s"} as matching Document360 \u2014 they read in-sync until either side changes.`}),L.rebaselined.length>0&&h({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${L.rebaselined.length} article${L.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),A.skipped.length>0&&h({kind:"note",tone:"warn",text:`${A.skipped.length} skipped:
|
|
533
533
|
${A.skipped.map(j=>` - ${j.path} (${j.reason})`).join(`
|
|
534
|
-
`)}`}),I(j=>j+1);return}if(b==="--compare"){h({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let y=await
|
|
535
|
-
`)});return}if(b){h({kind:"note",tone:"error",text:`Unknown option: ${b} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let k=f[0];if(k){let y=k.replace(/\\/g,"/"),v;try{let A=await
|
|
536
|
-
`)});let L=A.fixed>0?
|
|
537
|
-
`)});for(let $e of Q.closed)h({kind:"note",tone:"ok",text:$e});return}let E={aborted:!1,partitions:0,failed:0,notRun:0};if(j.kind==="partitioned"){let Q=await
|
|
538
|
-
\u26A0 ${
|
|
539
|
-
`)}),
|
|
540
|
-
`)}),v.length>0){let A=
|
|
541
|
-
`)});return}case"status":{let b=f.some(k=>k==="--all"||k==="--full");h({kind:"block",text:
|
|
542
|
-
`)}),te.current=!0;return}case"retire":{let b=f.find(x=>!x.startsWith("-"));if(!b){h({kind:"block",text:
|
|
543
|
-
`)}),te.current=!0;return}let k=
|
|
544
|
-
`)}),
|
|
534
|
+
`)}`}),I(j=>j+1);return}if(b==="--compare"){h({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let y=await w1({cwd:e,profileName:s}),v=y.onlyInLegacy.length===0&&y.onlyInManifest.length===0&&y.mappedMissingFromManifest.length===0,A=[`Legacy listing: ${y.legacyCount} \xB7 Manifest: ${y.manifestCount} \xB7 in both: ${y.inBoth}`];v?A.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(y.mappedMissingFromManifest.length&&A.push(`\u2717 ${y.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${y.mappedMissingFromManifest.slice(0,5).join(", ")}`),y.onlyInLegacy.length&&A.push(`\u26A0 ${y.onlyInLegacy.length} only in the legacy listing: ${y.onlyInLegacy.slice(0,5).join(", ")}`),y.onlyInManifest.length&&A.push(`\u26A0 ${y.onlyInManifest.length} only in the manifest: ${y.onlyInManifest.slice(0,5).join(", ")}`),A.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),h({kind:"note",tone:v?"ok":"warn",text:A.join(`
|
|
535
|
+
`)});return}if(b){h({kind:"note",tone:"error",text:`Unknown option: ${b} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let k=f[0];if(k){let y=k.replace(/\\/g,"/"),v;try{let A=await Uk({cwd:e,profileName:s,relPath:y});v={plan:A,mode:A.overwritesLocalChanges?"conflict":"pull"}}catch(A){if(!Wk(A))throw A;v={mode:"local-only",path:y,title:Bk(e,y)}}Ee.current=[v],_t.current=[],an.current=[],er();return}h({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let x=await ju({cwd:e,profileName:s});for(let y of Iu(x))h({kind:"note",tone:y.tone,text:y.text});I(y=>y+1)}catch(k){h({kind:"note",tone:"error",text:`Pull failed: ${k.message}`})}return}case"scope":{if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let b=R1(e);if(b.length===0){h({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.'});return}Vo({cursor:0,rows:b.map(k=>({...k,checked:k.recommended}))});return}case"audit":{if(f[0]==="--auto"){let k=ge(e);if(!k){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let x=f[1]!=="off";Lk({...k,autoAudit:x},e),h({kind:"note",tone:"ok",text:x?"\u2713 Auto-audit ON \u2014 when you launch with code changes since the last audit, I\u2019ll run /audit automatically. (/audit --auto off to disable.)":"\u2713 Auto-audit OFF \u2014 I\u2019ll just nudge you to run /audit when code changed."});return}if(!ao(u.trim()))return;let b=await Ps({cwd:e,profileName:s});if(b.kind==="audit-blocked"){De(b.note,{kind:"cmd",cmd:b.lead.cmd,reason:b.lead.reason},"warn");return}if(b.kind==="forward-to-agent"&&b.prompt){let k=await Pe(b.prompt,{display:b.display,quietUser:!0}),x=va(e,s);if(x){De(x.note,{kind:"cmd",cmd:wr.cmd,reason:wr.reason},"warn"),I(y=>y+1);return}k.producedNothing||(ti(e,s),I(y=>y+1))}return}case"lint":case"check":{let b=wn(c);b&&h({kind:"note",tone:"info",text:`\u2192 ${b}`});let k=f.find(A=>!A.startsWith("--")),x=k?` ${k}`:"",y=Ur({cwd:e,scope:k}),v=kn(y,f);if(f.includes("--fix")){let A=xr(e,f,y);A.lines.length>0&&h({kind:"note",tone:"ok",text:A.lines.join(`
|
|
536
|
+
`)});let L=A.fixed>0?Ur({cwd:e,scope:k}):y,j=nd(e,f,L);if(!j){let Q=od(e,f,L);h({kind:"note",tone:"ok",text:Q.lines.join(`
|
|
537
|
+
`)});for(let $e of Q.closed)h({kind:"note",tone:"ok",text:$e});return}let E={aborted:!1,partitions:0,failed:0,notRun:0};if(j.kind==="partitioned"){let Q=await Pi({partitions:j.partitions,promptFor:j.promptFor,concurrency:vr,verb:"Fixing",doneNoun:"fixed",headline:`Fixing ${j.findings} issue${j.findings===1?"":"s"} across ${j.articles} article${j.articles===1?"":"s"} in ${j.partitions.length} batches (\u2264${vr} at once)`,calibrateAs:"/lint"});if(E=Q.outcome,Q.covered.length>0)try{Wr(e,Q.covered,ut("lint"))}catch{}if(Q.aborted){let $e=js({cwd:e,after:kn(Ur({cwd:e,scope:k}).filter(Ie=>!Ie.baselined),f),scope:k,aborted:!0,blocked:bn(f)});De($e.text,{kind:"cmd",cmd:$e.cmd,reason:""},"warn");return}}else{h({kind:"note",tone:"info",text:`Fixing ${j.findings} doc issue${j.findings===1?"":"s"}\u2026`});let Q=L1(e,k);await Pe(j.prompt,{display:j.display,quietUser:!0});try{Wr(e,Q,ut("lint"))}catch{}}let z=kn(Ur({cwd:e,scope:k}).filter(Q=>!Q.baselined),f),F=kn(L.filter(Q=>!Q.baselined),f),U=new Set(z.map(Q=>Q.fp)),K=new Set(F.map(Q=>Q.fp)),ee=F.filter(Q=>!U.has(Q.fp)).length,ue=z.filter(Q=>!K.has(Q.fp)).length,fe=ue>0?`
|
|
538
|
+
\u26A0 ${ue} new ${ue===1?"issue":"issues"} appeared in the rewrites \u2014 recasting a sentence is where these come from.`:"";h({kind:"note",tone:z.some(Q=>Q.severity==="error")?"warn":"ok",text:z.length===0?`\u2713 Lint: all ${F.length} issue${F.length===1?"":"s"} resolved.`:[`\u2713 Lint: fixed ${ee} of ${F.length}.${fe}`,"",...Ls(z)].join(`
|
|
539
|
+
`)}),Cn(Is(f,k),j.kind==="partitioned"?E:{aborted:!1,partitions:0,failed:0,notRun:0,verifiedComplete:z.length===0});let we=js({cwd:e,after:z,before:j.findings,scope:k,blocked:bn(f)});De(we.text,{kind:"cmd",cmd:we.cmd,reason:""});return}if(h({kind:"note",tone:v.length===0?"ok":"warn",text:Ls(v,{full:f.includes("--full"),baselined:f.includes("--baselined")}).join(`
|
|
540
|
+
`)}),v.length>0){let A=ya(e,k)===0&&ba(e,k)===0?"; /push --all saves them to Document360 as-is":"",L=`/lint${x}${bn(f)?" --blocked":""} --fix`,j=vn(e,L);De(`Found ${v.length} doc issue${v.length===1?"":"s"} above. ${L} has the agent fix them in place${j?` (${j})`:""} \u2014 or /review${x} --fix for the full editorial pass${A}.`,{kind:"cmd",cmd:L,reason:""})}return}case"structure":{let b=Zs(e,s);if(b.length===0){h({kind:"note",tone:"info",text:"No documentation structure yet \u2014 run /init and author some articles first."});return}h({kind:"note",tone:"info",text:["Documentation order (categories \u2192 articles):","",...b].join(`
|
|
541
|
+
`)});return}case"status":{let b=f.some(k=>k==="--all"||k==="--full");h({kind:"block",text:Ep(e,{profileName:s,all:b,width:Ke()}).join(`
|
|
542
|
+
`)}),te.current=!0;return}case"retire":{let b=f.find(x=>!x.startsWith("-"));if(!b){h({kind:"block",text:Dp(e,s).join(`
|
|
543
|
+
`)}),te.current=!0;return}let k=K1(e,b)||b;if(!f.includes("--yes")&&!f.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(`
|
|
544
|
+
`)}),nt(`/retire ${k} --yes`,"tab to take it off your readers \xB7 or keep typing");return}T(!0);try{let x=await Y1({cwd:e,path:k,profileName:s,now:new Date().toISOString()});h(x.ok?{kind:"note",tone:"ok",text:x.alreadyHidden?`\u2713 "${k}" was already invisible to readers. Recorded as retired, so nothing will offer to publish it again.
|
|
545
545
|
It stays on Document360 with its history and comments intact. /push puts it back.`:`\u2713 "${k}" is no longer visible to your readers.
|
|
546
|
-
It stays on Document360 with its history and comments intact. /push puts it back.`}:{kind:"note",tone:"error",text:`\u2717 Could not retire "${k}" \u2014 ${x.error.message}`})}finally{T(!1)}return}case"terms":{let b=f.findIndex(k=>k==="--approve");if(b!==-1){let k=f[b+1];h(k?{kind:"block",text:
|
|
547
|
-
`)}:{kind:"note",tone:"warn",text:'\u2717 Name the spelling to approve, e.g. /terms --approve "drop-down".'}),te.current=!0;return}h({kind:"block",text:
|
|
548
|
-
`)}),te.current=!0;return}case"reorder":{let b=
|
|
549
|
-
`)})}let j=x&&!L.producedNothing?
|
|
550
|
-
`)}),pn(
|
|
551
|
-
`)});return}try{let k=
|
|
552
|
-
`)})}catch(k){h({kind:"note",tone:"warn",text:`Could not file the question: ${k.message}`})}return}case"inbox":{if(!
|
|
553
|
-
`)});return}if(b.answer&&(b.all||b.scope.path||b.scope.scope||x.length===1)){
|
|
554
|
-
|
|
555
|
-
Full output: ${
|
|
556
|
-
`)});return}if(b.mode==="list"){if(!
|
|
557
|
-
`)});let z=Re("/push","--screenshots",A),F=
|
|
558
|
-
`)}),k&&h({kind:"note",tone:"info",text:k});let j=
|
|
559
|
-
`)}),et(si(e));return}default:h({kind:"note",tone:"error",text:`Unknown command: /${c} \u2014 type /help.`})}},[e,r,s,Zo,cc,h,tt,Pe,ht,sc,Bh]),ls=ne(u=>{let p=(u??g).trim();if($(""),ci(null),Io(0),p.startsWith("/")){te.current=!1,Le.current=!1,Ne.current=null,Wt(),Go(null);let f=Vl.current.includes(p);f&&(Vl.current=[]),ie(S=>f?[]:hk(S,p))}if(!p||(zt(!1),rt.current=!1,(Mo.current||Ee.current.length>0)&&h({kind:"user",text:p}),Gh(p))||Hh(p))return;Ml.current.push(p);let c=wk(p,mh.current);if(p.startsWith("/"))h({kind:"user",text:p}),H(!0),co(c).finally(()=>H(!1));else if(V1(c)){h({kind:"user",text:p});let f=Y1(c);if(!f)Pe(c,{display:p,quietUser:!0});else{try{K1(e,{title:f,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}Pe(`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${f}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${f}" and the article path(s) you wrote.`,{display:p,quietUser:!0})}}else{let f=Gm(e,c);Pe(f??c,{display:p})}},[g,Gh,Hh,co,Pe]),qh=ne(u=>{if(u.length>1){if(u.includes("\x1B"))return;let p=fk(u);if(mk(p)){let c=gk(++l$.current,p);mh.current.set(c,p),P(c)}else P(p);return}P(u)},[P]),er=Math.max(10,ct-6),Vh=Nl(()=>El(d.text,er),[d.text,er]),uc=ne(u=>w(p=>({...p,pos:Math.max(0,Math.min(p.text.length,p.pos+u))})),[]),Ei=ne(u=>w(p=>({...p,pos:bk(El(p.text,er),p.pos,u)})),[er]),cs=ne(u=>w(p=>({...p,pos:kk(El(p.text,er),p.pos,u)})),[er]),g$=["\x1B[H","\x1B[1~","\x1BOH"],w$=["\x1B[F","\x1B[4~","\x1BOF"],Yh=ne((u,p)=>p.leftArrow?(uc(-1),!0):p.rightArrow?(uc(1),!0):u&&g$.includes(u)?(cs("start"),!0):u&&w$.includes(u)?(cs("end"),!0):p.ctrl&&u==="a"?(cs("start"),!0):p.ctrl&&u==="e"?(cs("end"),!0):!1,[uc,cs]),dc=ne(()=>{if(Me.current){if(!Me.current.signal.aborted){let u=(Yo?.verb??"work").toLowerCase(),p=Yo?.unit??"article";h({kind:"note",tone:"warn",text:`\u238B Stopping the ${u} run (finishing in-flight ${p}s)\u2026`}),Me.current.abort()}return!0}return Qr.current?!1:(Qr.current=!0,h({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),Lt.current?.interrupt(),!0)},[Yo]);return FN((u,p)=>{if(p.ctrl&&u==="c"){if(Jr.current!==null&&Date.now()-Jr.current<Jk){Jr.current=null,Lt.current?.close(),r();return}Jr.current=Date.now(),vh(!0),Wl.current&&clearTimeout(Wl.current),Wl.current=setTimeout(()=>{Jr.current=null,vh(!1)},Jk),R?dc():g&&$("");return}if(os.current.awaySince!==null)try{let c=sk(os.current,Date.now(),kn(e));if(os.current=c.memory,Ih(null),c.kind==="delta"){h({kind:"note",tone:"info",text:ak(c.delta,c.awayMs)});let f=pt(!1);f.kind==="recommend"&&dn(f.rec,{silent:!0})}else if(c.kind==="briefing"){h({kind:"note",tone:"info",text:`\u{1F4E5} ${oi(c.delta)} arrived while you were away (${Xp(c.awayMs)}).`});let f=pt(!1);f.kind==="recommend"&&dn(f.rec)}}catch{}if(Zl.current=Date.now(),!D){if(xt){if(p.return){di(null),pi.current=!0,I(c=>c+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(u==="b"||u==="B"){di(null),$("/auto --budget ");return}if(p.escape){di(null),Vo.current=!0,at.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."}),I(c=>c+1);return}return}if(p.tab&&p.shift&&!Rn&&!an&&!tc){let c=we(e);if(!c){h({kind:"note",tone:"info",text:"Set this repo up first with /init \u2014 then shift+tab switches between auto and manual."});return}let f=!jk(c);$a(e,c,f),f&&(Vo.current=!1);let S=!f&&at.current!==null;S&&(at.current={...at.current,stopping:!0}),h({kind:"note",tone:"ok",text:S?"Manual mode \u2014 I'll finish what is running and stop there, then hand back. (shift+tab to change it back.)":`${f?"Auto mode ON":"Manual mode"} \u2014 ${Cs(f)} (shift+tab to change it back.)`}),I(M=>M+1);return}if(R){if(p.escape){if(at.current){Vo.current=!0;let c=at.current;dc(),is({kind:"stopped",how:"esc"},c.parked);return}dc();return}if(p.return){let c=g.trim();if(!c)return;Zn.current.push(c),Ul([...Zn.current]),$("");return}if(Yh(u,p))return;if(p.upArrow){Ei(-1);return}if(p.downArrow){Ei(1);return}if(p.backspace||p.delete){C();return}u&&!p.ctrl&&!p.meta&&qh(u);return}if(an){if(p.upArrow){Kn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Kn(c=>c&&{...c,cursor:Math.min(Dt.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=cn(u,Dt.length);c!==null&&Kn(f=>f&&{...f,cursor:c});return}if(p.return){let c=Dt[an.cursor];Kn(null);let{lines:f,changed:S,effective:M}=_s(e,c.value??"default");for(let B of f)h({kind:"note",tone:B.startsWith("\u26A0")?"warn":B.startsWith("\u2713")?"ok":"info",text:B});S&&(Ch(B=>B+1),Lt.current?.setModel(M));return}if(u==="s"){let c=Dt[an.cursor];Kn(null),Lt.current?.setModel(c.value??void 0),h({kind:"note",tone:"ok",text:`\u2713 Using ${c.label} for this session only (your saved default is unchanged).`});return}if(p.escape){Kn(null);return}return}if(_t){if(p.upArrow){Fo(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Fo(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=cn(u,_t.rows.length);c!==null&&Fo(f=>f&&{...f,cursor:c});return}if(p.return||u==="s"){let c=_t.rows[_t.cursor];Fo(null),ac(c.name,p.return===!0);return}if(p.escape){Fo(null);return}return}if(es){if(p.escape){no(null);return}if(p.leftArrow||p.tab&&p.shift){no(c=>c&&{tab:(c.tab-1+ft.length)%ft.length,scroll:0});return}if(p.rightArrow||p.tab){no(c=>c&&{tab:(c.tab+1)%ft.length,scroll:0});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=ft.length){no({tab:Number(u)-1,scroll:0});return}if(p.upArrow){no(c=>c&&{...c,scroll:Math.max(0,c.scroll-1)});return}if(p.downArrow){no(c=>{if(!c)return c;let f=(ft[c.tab]??ft[0]).rows.length;return{...c,scroll:Math.min(Math.max(0,f-1),c.scroll+1)}});return}return}if(Mt){if(p.upArrow){Uo(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Uo(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=cn(u,Mt.rows.length);c!==null&&Uo(f=>f&&{...f,cursor:c});return}if(p.return){let c=Mt.rows[Mt.cursor].name;if(Uo(null),!Tc(e,c).created){h({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}h({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${c}").`});let S=!1;try{let M=Vn(c);S=!!M&&!(Eo(M)&&!M.refreshToken)}catch{S=!1}h({kind:"note",tone:"info",text:S?`Next: sign in to ${c} and pick your project \u2014 you're already signed in here, so it'll be quick.`:`Next: sign in to Document360 (${c}) and pick your project.`}),re("/login"),I(M=>M+1);return}if(p.escape){Uo(null);return}return}if(Xe){if(p.upArrow){Wo(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Wo(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=cn(u,Xe.rows.length);c!==null&&Wo(f=>f&&{...f,cursor:c});return}if(p.return){let c=Xe.rows[Xe.cursor],{profile:f,projectId:S}=Xe;Wo(null),Pi(f,S,c);return}if(p.escape){Wo(null);return}return}if(st){if(p.upArrow){zn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){zn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=cn(u,st.rows.length);c!==null&&zn(f=>f&&{...f,cursor:c});return}if(p.return){let c=st.rows[st.cursor],{profile:f}=st;zn(null),Ai(f,c);return}if(p.escape){zn(null);return}return}if(it){if(p.upArrow){qo(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){qo(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u===" "){qo(c=>c&&{...c,rows:c.rows.map((f,S)=>S===c.cursor?{...f,checked:!f.checked}:f)});return}if(p.return){let c=it.rows.filter(f=>f.checked).map(f=>f.path);if(qo(null),c.length===0){h({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}Su(e,c),h({kind:"note",tone:"ok",text:`\u2713 Scoped to ${c.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let f of c)h({kind:"note",tone:"info",text:` ${f}`});h({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(p.escape){qo(null);return}return}if(dt){if(p.upArrow){Qn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Qn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=cn(u,dt.rows.length);c!==null&&Qn(f=>f&&{...f,cursor:c});return}if(p.return){let c=dt.rows[dt.cursor],f=dt.run;Qn(null),f(c.token);return}if(p.escape){Qn(null);return}return}if(kt){if(p.upArrow){Bo(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Bo(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=cn(u,kt.rows.length);c!==null&&Bo(f=>f&&{...f,cursor:c});return}if(p.return){let c=kt.rows[kt.cursor],f=kt.conflicts;Bo(null),c.conflict?cc(c.paths[0]):c.kind==="article"?sc(c.paths[0]):ht(c.paths,c.kind==="all"?f:0);return}if(p.escape){Bo(null);return}return}if(Ft){if(p.upArrow){Ho(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Ho(c=>c&&{...c,cursor:Math.min(c.rows.length,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=cn(u,Ft.rows.length+1);c!==null&&Ho(f=>f&&{...f,cursor:c});return}if(p.return){let{cursor:c,rows:f,opts:S}=Ft;Ho(null);let M=c===0?f:[f[c-1]];Mh(M,S);return}if(p.escape){Ho(null),h({kind:"note",tone:"info",text:"Left as drafts \u2014 nothing changed. /publish when they have been signed off."});return}return}if($t){let{rows:c}=$t;if(p.upArrow){ln(f=>f&&{...f,cursor:Math.max(0,f.cursor-1)});return}if(p.downArrow){ln(f=>f&&{...f,cursor:Math.min(c.length-1,f.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let f=qp(yh.current,Number(u),c.length-1);yh.current=f.memory,f.index!==null&&ln(S=>S&&{...S,cursor:f.index+1});return}if(u==="a"||u==="A"){ln(f=>f&&{...f,cursor:0});return}if(p.return){let f=c[$t.cursor],{groups:S,resolve:M,report:B}=$t;if(ln(null),f.kind==="all"){rc(S,{resolve:M,report:B});return}Qo(Qa(f.group,{width:Ve()})),Xr({group:f.group,cursor:0,fromList:!0,resolve:M,rest:S.filter(b=>b.articleId!==f.group.articleId),report:B});return}if(p.escape){ln(null),re("/comments");return}return}if(Ze){let c=()=>{let{rest:f,group:S,fromList:M,resolve:B,report:b}=Ze;if(Xr(null),!M||!b){re("/comments");return}let k=[S,...f].sort((x,y)=>x.category.localeCompare(y.category)||x.title.localeCompare(y.title));ln({cursor:0,rows:Ja(k),groups:k,resolve:B,report:b})};if(p.upArrow||p.downArrow){Xr(f=>f&&{...f,cursor:f.cursor===0?1:0});return}if(u==="y"||u==="Y"||p.return&&Ze.cursor===0){let{group:f,resolve:S,rest:M,report:B}=Ze;Xr(null),rc([f],{resolve:S,rest:M,...B?{report:B}:{}});return}if(u==="b"||u==="B"||p.escape||p.return){c();return}return}if(Ut){if(p.upArrow){Xn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Xn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=cn(u,Ut.rows.length);c!==null&&Xn(f=>f&&{...f,cursor:c});return}if(p.return){let c=Ut.rows[Ut.cursor];Xn(null),c.action==="capture"?as(c.ids,{runLine:c.kind==="all"?["/screenshot capture --all","/capture --all"]:void 0}):c.action==="annotate"?Ci(c.ids,{verifiedBefore:new Set(Fe(e).filter(f=>f.state==="verified").map(f=>f.id))}):c.kind==="shot"?Wh(c.ids[0]):Uh(c.ids,{setup:!0,runLine:c.kind==="all"?["/screenshot author --all","/screenshot --all"]:void 0});return}if(p.escape){Xn(null);return}return}if(vt){if(p.escape){Jn(null);return}if(p.upArrow){Jn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Jn(c=>c&&{...c,cursor:Math.min(Math.max(0,vi.length-1),c.cursor+1)});return}if(p.return){let c=vi[vt.cursor];if(c){Jn(null);try{h({kind:"preview",name:si(c),text:e$(jl(ii(e,c),"utf8"))})}catch(f){h({kind:"note",tone:"error",text:`Could not read ${c}: ${f.message}`})}}return}if(p.backspace||p.delete){Jn(c=>c&&{...c,query:c.query.slice(0,-1),cursor:0});return}if(u&&!p.ctrl&&!p.meta&&u.length===1){Jn(c=>c&&{...c,query:c.query+u,cursor:0});return}return}if(Rt){if(p.escape){to(null);return}if(p.upArrow){to(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){to(c=>c&&{...c,cursor:Math.min(Math.max(0,xi.length-1),c.cursor+1)});return}if(p.return){let c=xi[Rt.cursor];if(c){to(null),tt(c.uuid),rn.current={uuid:c.uuid,firstPrompt:c.firstPrompt,titleFired:!0},Yn(c.name),eh(c.uuid),_o.current=[],lt.current={printed:[],armed:[],printedAt:Ko.current};let f=Vp(e,c.uuid);for(let S of f)h(S);h({kind:"note",tone:"ok",text:f.length?`Resumed "${c.name}" \u2014 restored ${f.length} message(s); continue where you left off.`:`Resumed "${c.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(p.backspace||p.delete){to(c=>c&&{...c,query:c.query.slice(0,-1),cursor:0});return}if(u&&!p.ctrl&&!p.meta&&u.length===1){to(c=>c&&{...c,query:c.query+u,cursor:0});return}return}if(p.tab&&!g&&de){$(de),Wt();return}if(!g&&he.length>0&&!rt.current&&u&&/^[1-9]$/.test(u)){let c=he[Number(u)-1];if(c){$(qn(c));return}}if(!g&&he.length===0&&!rt.current&<.current.armed.length>0&&u&&/^[1-9]$/.test(u)){let c=lt.current.armed[Number(u)-1];if(c){$(c);return}}if(!g&&(bi||so)&&u==="c"&&!p.ctrl&&!p.meta&&!p.return&&!p.tab){let c=bi!=null;Bp(bi??so).then(S=>{h({kind:"note",tone:S?"ok":"warn",text:S?c?"\u2713 Copied the feedback to your clipboard \u2014 send it to the d360-writer team (Teams / Slack / email).":"\u2713 Copied the prompt to your clipboard \u2014 paste it into your repo's coding agent.":c?"Couldn't reach your clipboard \u2014 select the feedback above and copy it manually.":"Couldn't reach your clipboard \u2014 select the prompt above and copy it manually."}),S&&c&&Jl(null),S&&!c&&Th(!0)});return}if(!Yh(u,p)){if(tc){if(p.upArrow){Io(c=>Math.max(0,c-1));return}if(p.downArrow){Io(c=>Math.min(hn.length-1,c+1));return}if(p.tab){$("/"+(hn[Yr]?.name??"")+" "),Io(0);return}if(p.return){let c=hn[Yr];if(c){let f=g.trim().slice(1).split(/\s+/).slice(1).join(" ");if(Eg(c.usage)&&!f){$("/"+c.name+" "),Io(0);return}ls("/"+c.name+(f?" "+f:""));return}}}else{if(!g&&he.length>0&&!rt.current&&(p.upArrow||p.downArrow)){if(p.downArrow){Kr(c=>c===null?0:Math.min(he.length-1,c+1));return}if(Oo!==null){Kr(c=>c===null||c===0?null:c-1);return}}if(p.upArrow){if(g!==""&&Lo===null){Ei(-1);return}let c=Ml.current;if(!c.length)return;let f=Lo===null?c.length-1:Math.max(0,Lo-1);ci(f),$(c[f]??"");return}if(p.downArrow){if(g!==""&&Lo===null){Ei(1);return}let c=Ml.current;if(Lo===null)return;let f=Lo+1;f>=c.length?(ci(null),$("")):(ci(f),$(c[f]??""));return}}if(p.return){if(Oo!==null&&!g&&he[Oo]){let c=qn(he[Oo]);Kr(null),ls(c);return}ls();return}if(p.backspace||p.delete){C();return}if(p.escape){at.current&&(Vo.current=!0,is({kind:"stopped",how:"esc"},at.current.parked)),$(""),Io(0),Wt(),ie([]),Go(null),Kr(null),te.current=!0;return}u&&!p.ctrl&&!p.meta&&qh(u)}}}),ot(()=>{if(R||D)return;let u=Zn.current.shift();u!==void 0&&(Ul([...Zn.current]),ls(u))},[R,D,ls]),ue(je,{flexDirection:"column",width:ct,children:[oc!==null&&ue(je,{marginTop:1,flexDirection:"column",children:[oc.truncated&&q(V,{dimColor:!0,children:"\u2026"}),q(V,{children:oc.text})]}),R&&Yo?q(lj,{p:Yo}):null,xh?q(ij,{text:xh}):R&&!Yo?q(sj,{startTime:_e.current,chars:Vr}):null,q(je,{borderStyle:"round",borderColor:Lh.prod?"yellow":ae,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:g?Vh.map((u,p)=>{let c=d.text.slice(u.start,u.end),f=p===Dl(Vh,d.pos),S=Math.min(d.pos,u.end)-u.start;return ue(V,{children:[q(V,{color:ae,children:p===0?"> ":" "}),f?ue(Br,{children:[c.slice(0,S),q(Wr,{ch:c[S]??" "}),c.slice(S+1)]}):c||" "]},`${p}-${u.start}`)}):ue(V,{children:[q(V,{color:ae,children:"> "}),Rn?q(Wr,{ch:" "}):Se&&!R?ue(Br,{children:[q(Wr,{ch:Se[0],dim:!0}),q(V,{color:"gray",children:Se.slice(1)})]}):de&&!R?ue(Br,{children:[q(Wr,{ch:de[0],dim:!0}),q(V,{color:"gray",children:de.slice(1)}),q(V,{dimColor:!0,children:" (tab)"})]}):(ec.isSetup||!Do)&&!R?ue(Br,{children:[q(Wr,{ch:ec.text[0],dim:!0}),q(V,{color:"gray",children:ec.text.slice(1)})]}):q(Wr,{ch:" "})]})}),$h.length>0&&q(je,{flexDirection:"column",paddingX:1,children:$h.map((u,p)=>q(V,{color:"gray",children:`\u29D7 queued: ${u}`},`${p}-${u.slice(0,24)}`))}),xt?ue(je,{flexDirection:"column",paddingX:1,children:[q(V,{color:ae,bold:!0,children:"Auto mode \u2014 the full round trip"}),q(V,{color:"gray",children:` starting with ${xt.firstCmd}`}),xt.scale?q(V,{color:"gray",children:` ${xt.scale}`}):null,xt.scale&&!xt.scale.includes("$")?q(V,{color:"gray",children:" no cost estimate yet \u2014 this repo has not finished a run for me to measure"}):null,q(V,{color:"gray",children:` spending limit ${Ye(xt.budgetUsd)} \xB7 I stop and report if it is reached`}),q(V,{color:"gray",children:" screenshots are not part of an automatic run"}),xt.overBudget?q(V,{color:"yellow",children:`\u26A0 That is more than your ${Ye(xt.budgetUsd)} limit. I will stop partway and report what is left.`}):null,q(V,{dimColor:!0,children:xt.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"})]}):es?q(ck,{tab:es.tab,scroll:es.scroll,rows:f$,width:ct,version:o,engineVersion:t$}):an?ue(je,{flexDirection:"column",paddingX:1,children:[q(V,{color:ae,bold:!0,children:"Select model"}),q(V,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),Dt.map((u,p)=>ue(V,{color:p===an.cursor?ae:void 0,children:[p===an.cursor?"\u276F ":" ",`${p+1}. ${u.label}${p===an.current?" \u2714":""}`.padEnd(16),q(V,{color:"gray",children:` ${u.desc}`})]},u.label)),q(V,{dimColor:!0,children:yt({verb:"set as default",rows:Dt.length,extra:["s this session only"]})})]}):_t?ue(je,{flexDirection:"column",paddingX:1,children:[q(V,{color:ae,bold:!0,children:"Switch connection profile"}),q(vn,{rows:_t.rows,cursor:_t.cursor,cap:Xt,render:(u,p,c)=>ue(V,{color:c?ae:void 0,children:[c?"\u276F ":" ",`${p+1}. ${u.name}${p===_t.current?" \u2714":""}`.padEnd(20),q(V,{color:"gray",children:` ${u.env} \xB7 ${u.who??"not signed in"}`}),u.prod?q(V,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},u.name)}),q(V,{dimColor:!0,children:yt({verb:"switch (saved as default)",rows:_t.rows.length,extra:["s this session only"]})})]}):Mt?ue(je,{flexDirection:"column",paddingX:1,children:[q(V,{color:ae,bold:!0,children:"Pick your Document360 environment"}),q(vn,{rows:Mt.rows,cursor:Mt.cursor,cap:Xt,render:(u,p,c)=>ue(V,{color:c?ae:void 0,children:[c?"\u276F ":" ",`${p+1}. ${u.name}`.padEnd(16),q(V,{color:"gray",children:` ${u.apiUrl}`}),u.note?q(V,{color:"yellow",children:` \u26A0 ${u.note}`}):null]},u.name)}),q(V,{dimColor:!0,children:yt({verb:"use it",rows:Mt.rows.length})})]}):Xe?ue(je,{flexDirection:"column",paddingX:1,children:[q(V,{color:ae,bold:!0,children:"Switch workspace"}),q(V,{dimColor:!0,children:`environment ${Xe.environment} \xB7 project ${Xe.projectName??`${Xe.projectId.slice(0,8)}\u2026`}`}),q(vn,{rows:Xe.rows,cursor:Xe.cursor,cap:Xt,render:(u,p,c)=>ue(V,{color:c?ae:void 0,children:[c?"\u276F ":" ",`${p+1}. ${u.name}${p===Xe.current?" \u2714":""}`.padEnd(30),q(V,{color:"gray",children:u.type?` ${u.type}`:""})]},u.id)}),q(V,{dimColor:!0,children:yt({verb:"switch",rows:Xe.rows.length})})]}):st?ue(je,{flexDirection:"column",paddingX:1,children:[q(V,{color:ae,bold:!0,children:"Choose project"}),q(V,{dimColor:!0,children:`environment ${st.environment}`}),q(vn,{rows:st.rows,cursor:st.cursor,cap:Xt,render:(u,p,c)=>ue(V,{color:c?ae:void 0,children:[c?"\u276F ":" ",`${p+1}. ${u.name}${p===st.current?" \u2714":""}`.padEnd(30),q(V,{color:"gray",children:u.sub?` ${u.sub}`:""})]},u.id)}),q(V,{dimColor:!0,children:yt({verb:"switch",rows:st.rows.length})})]}):it?(()=>{let p=Math.min(Math.max(0,it.cursor-Math.floor(7)),Math.max(0,it.rows.length-14)),c=it.rows.slice(p,p+14),f=it.rows.filter(S=>S.checked).length;return ue(je,{flexDirection:"column",paddingX:1,children:[q(V,{color:ae,bold:!0,children:`Which folders back the user docs? (${f} selected of ${it.rows.length})`}),p>0?q(V,{dimColor:!0,children:` \u2191 ${p} more`}):null,c.map((S,M)=>{let B=p+M;return ue(V,{color:B===it.cursor?ae:void 0,children:[B===it.cursor?"\u276F ":" ",S.checked?"\u25C9 ":"\u25CB ",S.path.padEnd(Math.min(48,ct-34)),q(V,{color:"gray",children:va(S)})]},S.path)}),p+14<it.rows.length?q(V,{dimColor:!0,children:` \u2193 ${it.rows.length-p-14} more`}):null,q(V,{dimColor:!0,children:yt({verb:"save",multi:!0})})]})})():dt?ue(je,{flexDirection:"column",paddingX:1,children:[q(V,{color:ae,bold:!0,children:dt.title??"Which category? (pick one to scope to)"}),q(vn,{rows:dt.rows,cursor:dt.cursor,cap:Xt,render:(u,p,c)=>ue(V,{color:c?ae:void 0,children:[c?"\u276F ":" ",`${`${p+1}.`.padEnd(3)} ${u.label} (${u.count})`.padEnd(Math.min(44,Math.max(20,ct-24))),q(V,{color:"gray",children:` ${u.token}`})]},u.token)}),q(V,{dimColor:!0,children:yt({verb:"choose it",rows:dt.rows.length})})]}):kt?ue(je,{flexDirection:"column",paddingX:1,children:[q(V,{color:ae,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),q(vn,{rows:kt.rows,cursor:kt.cursor,cap:Xt,render:(u,p,c)=>ue(V,{color:c?ae:void 0,bold:u.kind==="category"&&!c,children:[c?"\u276F ":" ",`${u.indent?" ":" "}${`${p+1}.`.padEnd(3)} ${u.label}`.padEnd(Math.min(56,ct-24)),u.note?q(V,{color:"gray",children:` ${u.note}`}):null]},`${u.kind}:${u.paths.join(",")}`)}),q(V,{dimColor:!0,children:yt({verb:"push as drafts",rows:kt.rows.length})})]}):Ft?ue(je,{flexDirection:"column",paddingX:1,children:[q(V,{color:ae,bold:!0,children:"Publish live to your readers \u2014 this is what they will see:"}),q(vn,{rows:[{path:"",articleId:"",label:`Publish all ${Ft.rows.length} live`,version:void 0},...Ft.rows],cursor:Ft.cursor,cap:Xt,render:(u,p,c)=>ue(V,{color:c?ae:void 0,bold:p===0&&!c,children:[c?"\u276F ":" ",` ${`${p+1}.`.padEnd(3)} ${u.label}`.padEnd(Math.min(56,ct-24)),p>0?q(V,{color:"gray",children:` ${u.version?`draft v${u.version} \u2192 live`:"draft \u2192 live"}`}):null]},`${p}:${u.path||"all"}`)}),q(V,{dimColor:!0,children:yt({verb:"publish live",cancel:"leave as drafts",rows:Ft.rows.length+1})})]}):$t?ue(je,{flexDirection:"column",paddingX:1,children:[q(V,{color:ae,bold:!0,children:"Which comments do you want to look at?"}),q(vn,{rows:$t.rows,cursor:$t.cursor,cap:Xt,render:(u,p,c)=>ue(V,{color:c?ae:void 0,bold:u.kind==="all"&&!c,children:[c?"\u276F ":" ",`${(u.kind==="all"?"":`${u.n}.`).padEnd(4)}${u.label}`.padEnd(Math.min(56,Math.max(20,ct-24))),u.kind==="article"?q(V,{color:"gray",children:u.note}):null]},u.kind==="all"?"all":u.group.articleId)}),q(V,{dimColor:!0,children:yt({verb:"open it",cancel:"close",rows:$t.rows.length-1})}),$t.resolve?q(V,{dimColor:!0,children:"--resolve is on: threads you answer will be closed as well as replied to"}):null]}):Ze?ue(je,{flexDirection:"column",paddingX:1,children:[q(V,{color:ae,bold:!0,children:`${Ze.group.title} \u2014 ${Ze.group.threads.length} comment${Ze.group.threads.length===1?"":"s"}`}),ue(V,{color:Ze.cursor===0?ae:void 0,children:[Ze.cursor===0?"\u276F ":" ",Ze.resolve?"Yes \u2014 fix them, push the draft, reply and resolve":"Yes \u2014 fix them, push the draft to Document360, then reply"]}),ue(V,{color:Ze.cursor===1?ae:void 0,children:[Ze.cursor===1?"\u276F ":" ",Ze.fromList?"No \u2014 back to the list":"No \u2014 leave them for now"]}),q(V,{dimColor:!0,children:yt({verb:"open it",cancel:"go back",extra:["y answer"]})})]}):Ut?ue(je,{flexDirection:"column",paddingX:1,children:[q(V,{color:ae,bold:!0,children:Ut.title}),(()=>{let{rows:u,cursor:p}=Ut,c=xl(u.length,p,Xt),f=c.start,S=u.slice(c.start,c.end),M=`${u.length}.`.length+1,B=Em(u,Math.max(20,ct-4-M));return ue(Br,{children:[f>0?q(V,{color:"gray",children:` \u2026 ${f} more above`}):null,S.map((b,k)=>{let x=f+k,y=x===p,v=B[x];return ue(V,{color:y?ae:void 0,bold:(b.kind==="all"||b.kind==="category")&&!y,children:[y?"\u276F ":" ",`${x+1}.`.padEnd(M),v.head,v.note?q(V,{color:"gray",children:v.note}):null]},`${b.action}:${b.kind}:${b.ids.join(",")}`)}),c.below>0?q(V,{color:"gray",children:` \u2026 ${c.below} more below`}):null]})})(),q(V,{dimColor:!0,children:yt({verb:"run it",rows:Ut.rows.length})})]}):vt?ue(je,{flexDirection:"column",paddingX:1,children:[q(V,{color:ae,bold:!0,children:`Preview article${vt.query?` \u2014 filter: ${vt.query}`:" (type to filter)"}`}),vi.length===0?q(V,{color:"gray",children:"no articles match"}):vi.map((u,p)=>ue(V,{color:p===vt.cursor?ae:void 0,children:[p===vt.cursor?"\u276F ":" ",u]},u)),q(V,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):Rt?ue(je,{flexDirection:"column",paddingX:1,children:[q(V,{color:ae,bold:!0,children:`Resume session${Rt.query?` \u2014 filter: ${Rt.query}`:" (type to filter)"}`}),xi.length===0?q(V,{color:"gray",children:"no sessions match"}):xi.map((u,p)=>ue(V,{color:p===Rt.cursor?ae:void 0,children:[p===Rt.cursor?"\u276F ":" ",u.name.slice(0,28).padEnd(30),q(V,{color:p===Rt.cursor?ae:"gray",children:u.firstPrompt.slice(0,Math.max(10,ct-40))})]},u.uuid)),q(V,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):tc?ue(je,{flexDirection:"column",children:[ao>0?q(V,{dimColor:!0,children:` \u22EF ${ao} more above`}):null,nc.map((u,p)=>{let c=ao+p,f=u.name==="model"&&Gl?`${u.desc} (currently ${Gl})`:u.desc,S=Math.max(20,ct-4),M=u.usage.length>S?`${u.usage.slice(0,S-1)}\u2026`:u.usage,B=S-Math.max(M.length,22)-1,b=B<=1?"":f.length>B?`${f.slice(0,B-1)}\u2026`:f;return ue(V,{color:c===$i?ae:void 0,children:[c===$i?"\u276F ":" ",M.padEnd(22)," ",q(V,{color:c===$i?ae:"gray",children:b})]},u.name)}),ao+nc.length<hn.length?q(V,{dimColor:!0,children:` \u22EF ${hn.length-ao-nc.length} more below`}):null,q(V,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!R&&!g&&he.length>0?ue(je,{flexDirection:"column",paddingX:1,children:[kh?q(V,{color:ae,children:kh}):null,q(vn,{rows:he,cursor:Oo??0,cap:Xt,render:(u,p)=>{let c=p===Oo,f=qn(u),S=f.slice(0,Math.max(20,ct-7)),M=ct-S.length-9,B=M>=12?(pk(u)??Tg(f)).slice(0,M):"";return ue(V,{color:c?ae:void 0,children:[c?"\u276F ":" ",q(V,{color:ae,children:p+1})," ",S,B?q(V,{color:c?ae:void 0,dimColor:!c,children:` \u2014 ${B}`}):null]},f)}}),q(V,{dimColor:!0,children:`\u2191\u2193 choose \xB7 enter run \xB7 1-${he.length} fill \xB7 esc cancel`})]}):q(je,{paddingX:1,children:ue(V,{color:"gray",children:[Lh.prod?"\u26A0 PRODUCTION \xB7 ":"",q(V,{color:mi?ae:void 0,children:mi?"\u23F5\u23F5 auto":"\u23F5 manual"}),` \xB7 /help \xB7 ${Gl??"model n/a"}${t.kind==="api"?un>0?` \xB7 session ${Et(un)}`:"":Sh>0?` \xB7 ${kr(Sh)}`:""} \xB7 \u2191 history \xB7 shift+tab mode \xB7 ${c$?"press ctrl+c again to exit":"ctrl+c twice to exit"}`]})})]})}se();import{jsx as pj}from"react/jsx-runtime";async function o$(e=process.cwd(),t="auto",n,o="0.0.0"){let r=dj(t);r.kind==="none"&&(console.error(""),console.error(_("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${Z("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${Z("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=uj(pj(n$,{cwd:e,auth:r,profileName:n,version:o}),{exitOnCtrlC:!1});await s(),process.stdout.write(`
|
|
560
|
-
`),process.exit(0)}se();import{writeCrashLog as
|
|
561
|
-
`+_(`\u2717 d360-writer crashed: ${
|
|
546
|
+
It stays on Document360 with its history and comments intact. /push puts it back.`}:{kind:"note",tone:"error",text:`\u2717 Could not retire "${k}" \u2014 ${x.error.message}`})}finally{T(!1)}return}case"terms":{let b=f.findIndex(k=>k==="--approve");if(b!==-1){let k=f[b+1];h(k?{kind:"block",text:Ip(e,k.replace(/^["']|["']$/g,"")).lines.join(`
|
|
547
|
+
`)}:{kind:"note",tone:"warn",text:'\u2717 Name the spelling to approve, e.g. /terms --approve "drop-down".'}),te.current=!0;return}h({kind:"block",text:jp(e,{...f.find(k=>!k.startsWith("--"))?{scope:f.find(k=>!k.startsWith("--"))}:{},all:f.includes("--all")}).join(`
|
|
548
|
+
`)}),te.current=!0;return}case"reorder":{let b=Tp(e,f);if(!b){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let k=await Pe(b.prompt,{display:b.display,quietUser:!0}),x=Yt(e,{text:"Reordered locally \u2014 /push --all syncs the new order to Document360.",cmd:"/push --all"},"Reordered locally. ");Xo(k,x.text,{kind:"cmd",cmd:x.cmd,reason:""});return}case"review":{let b=Cp(e,f);if(b){h({kind:"note",tone:"ok",text:b.lines[0]});for(let j of b.closed)h({kind:"note",tone:"ok",text:j});De(b.cta.text,{kind:"cmd",cmd:b.cta.cmd,reason:""});return}let k=Sp(e,f);if(!k){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let x=f.includes("--fix"),y=f.find(j=>!j.startsWith("--")),v=x?Po(e,f,y):[],A={aborted:!1,partitions:0,failed:0,notRun:0},L;if(k.kind==="partitioned"){let j=await y$(k,x);A=j.outcome,L=j}else L=await Pe(k.prompt,{display:k.display,quietUser:!0}),A={...A,producedNothing:L.producedNothing};if("aborted"in L&&L.aborted){let j=f.includes("--blocked")?"--blocked --fix":f.includes("--stale")?"--stale --fix":"--fix",E=Re("/review",j,y);De(`Stopped \u2014 the batches that finished are saved. ${E} picks up the rest${y||ei(f)?"":", or narrow it with /review <category> --fix"}.`,{kind:"cmd",cmd:E,reason:""},"warn");return}if(k.kind!=="partitioned"&&x&&!L.producedNothing)try{Wr(e,v,ut("review"))}catch{}if(x&&Cn(`/review${y?` ${y}`:""}${f.includes("--all")?" --all":""}${f.includes("--blocked")?" --blocked":f.includes("--stale")?" --stale":""} --fix`,A),x){if(x&&!L.producedNothing){let z=xr(e,["--fix"],Ur({cwd:e,scope:y}));z.lines.length>0&&h({kind:"note",tone:"ok",text:z.lines.join(`
|
|
549
|
+
`)})}let j=x&&!L.producedNothing?Ur({cwd:e,scope:y}).filter(z=>!z.baselined&&z.severity==="error"):[];if(j.length>0){let z=new Set(j.map(K=>K.path)).size,F=`/lint${y?` ${y}`:""} --blocked --fix`,U=vn(e,F);h({kind:"note",tone:"warn",text:`\u26A0 The editor's rewrites left ${j.length} style error${j.length===1?"":"s"} in ${z} article${z===1?"":"s"} \u2014 recasting a sentence is where these appear.`}),Xo(L,`Editor applied its fixes, but ${j.length} style error${j.length===1?"":"s"} remain. ${F} clears ${j.length===1?"it":"just those"} \u2014 it costs nothing to find them and one pass to correct${U?` (${U})`:""}. 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:F,reason:""});return}let E=Yt(e,{text:`\u2713 Editor applied its fixes \u2014 your docs are corrected. /push${y?"":" --all"} saves them to Document360 as drafts (or /lint${y?` ${y}`:""} for an instant no-token re-scan first).`,cmd:y?"/push":"/push --all"},"\u2713 Editor applied its fixes to this scope. ",y);Xo(L,E.text,{kind:"cmd",cmd:E.cmd,reason:""})}else{let j=y?` ${y}`:"",E=ya(e,y)===0&&ba(e,y)===0?`; /push${y?"":" --all"} saves them to Document360 as-is`:"";Xo(L,`The review listed issues above. /review${j} --fix lets the editor apply them all (or /lint${j} --fix for just the deterministic ones${E}).`,{kind:"cmd",cmd:`/review${j} --fix`,reason:""})}return}case"capture-setup":{await W();return}case"devhints":{if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}h({kind:"note",tone:"info",text:lr(ar(e)).join(`
|
|
550
|
+
`)}),pn(fo()),is.current=Gt(e).status==="current",Qo.current=mn(e);return}case"discover":{if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await Pe(Pu(),{display:"/discover",quietUser:!0});return}case"ask":{if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let b=f.join(" ").trim();if(b===""){h({kind:"block",text:Yd(V1(e)).join(`
|
|
551
|
+
`)});return}try{let k=q1(e,{question:b});h({kind:"note",tone:"ok",text:Vd(k.file,Vs(e)).join(`
|
|
552
|
+
`)})}catch(k){h({kind:"note",tone:"warn",text:`Could not file the question: ${k.message}`})}return}case"inbox":{if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(Gd(e)===0){h({kind:"note",tone:"info",text:"Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)"});return}await Pe(qd(),{display:"/inbox",quietUser:!0});return}case"auto":{let b=ge(e);if(!b){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let k=Su(f);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 ${He(h1)}).`});return}let x=Cu(f,k.usd),y=v=>{for(let A of v)h({kind:"note",tone:A.tone,text:A.text});I(A=>A+1)};if(k.usd!==void 0&&!x){let v=Ru(e,b,k.usd);v&&y(v);return}if(!x||x==="status"){for(let v of As(b))h({kind:"note",tone:v.tone,text:v.text});return}if(x==="on"||x==="off"){x==="on"&&(eo.current=!1);let v=k.usd!==void 0?{...b,auto:{...b.auto,enabled:b.auto?.enabled===!0,budgetUsd:k.usd}}:b;y(xa(e,v,x==="on"));return}h({kind:"note",tone:"error",text:`I don't know "${x}". Use: /auto on \xB7 /auto off \xB7 /auto status \xB7 /auto --budget <amount>`});return}case"share":{let b=ge(e);if(!b){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let k=f[0]?.trim().toLowerCase();if(k==="status"){for(let y of Ka(e,b))h({kind:"note",tone:y.tone,text:y.text});return}if(k==="on"||k==="off"){for(let y of Kd(e,b,k==="on"))h({kind:"note",tone:y.tone,text:y.text});I(y=>y+1);return}if(k){h({kind:"note",tone:"error",text:`Unknown option: ${k} \u2014 use /share, /share status, /share on, or /share off.`});return}h({kind:"note",tone:"info",text:"Exchanging work with your team\u2026"});let x=await za(e,b);for(let y of x.lines)h({kind:"note",tone:y.tone,text:y.text});x.changed&&I(y=>y+1);return}case"feedback":{let b=Kk(e),k="";try{k=Fr(b)?Ll(b,"utf8"):""}catch{k=""}if(!/^## /m.test(k)){h({kind:"note",tone:"info",text:"No open d360-writer feedback to copy \u2014 nothing logged in .d360-writer/tool-feedback.md yet."});return}let x=await qp(k.trim());h({kind:"note",tone:x?"ok":"warn",text:x?"\u2713 Copied the d360-writer feedback to your clipboard \u2014 send it to the team (Teams / Slack / email).":`Couldn\u2019t reach your clipboard \u2014 open ${b} and copy it manually.`}),x&&tc(null);return}case"document":{if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{push:b,skipReview:k,what:x}=$d(f);if(!x&&kd(e)===0){h({kind:"note",tone:"info",text:xd});return}let y=`/document${x?` ${x}`:""}${b?" --push":""}`,v=await Pe(vd(x),{display:y,quietUser:!0});b&&!v.producedNothing&&await Bh({skipReview:k});return}case"catch-up":{if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!ao(u.trim()))return;let{push:b,skipReview:k}=Jd(f);for(let E of await Xd(e))h({kind:"note",tone:E.tone,text:E.text});h({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let x=await tp({cwd:e,profileName:s});for(let E of np(x))h({kind:"note",tone:E.startsWith("\u2713")?"ok":E.startsWith("\u2139")?"info":"warn",text:E});let y=Ks(e);for(let E of Zd(y))h({kind:"note",tone:E.tone,text:E.text});let v=$n(e);h({kind:"note",tone:"info",text:Qd(v)});let A=zk(e),L=await Pe(ep(y),{display:`/catch-up${b?" --push":""}`,quietUser:!0}),j=xo(e,A,"","/catch-up");if(b&&!L.producedNothing)await Bh({skipReview:k});else if(j.cta)Xo(L,j.cta.text,{kind:"cmd",cmd:j.cta.cmd,reason:""});else{let E=Qa({queued:v,hold:y.hold});Xo(L,E.note,E.lead?{kind:"cmd",cmd:E.lead.cmd,reason:E.lead.reason}:null,E.tone)}return}case"comments":{if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!ao(u.trim()))return;let b=ap(f);Be("Checking Document360 for reviewer comments\u2026"),T(!0);let k=null;try{k=await Ja(e,s,{...b.scope,onProgress:(y,v)=>Be(`Checking Document360 for reviewer comments\u2026 ${y}/${v}`)})}catch(y){h({kind:"note",tone:"error",text:`Couldn\u2019t read comments from Document360: ${y.message}`})}finally{T(!1),Be(null)}if(!k)return;I(y=>y+1);let x=Ro(k.threads,k.labels);if(k.threads.length===0){h({kind:"note",tone:"ok",text:Xs(k,{showAnswered:b.showAnswered,width:Ke()}).join(`
|
|
553
|
+
`)});return}if(b.answer&&(b.all||b.scope.path||b.scope.scope||x.length===1)){Jo(sp(k,{full:!0,showAnswered:b.showAnswered,width:Ke()})),await ac(x,{resolve:b.resolve});return}if(x.length===1){Jo(Za(x[0],{width:Ke()})),Qr({group:x[0],cursor:0,fromList:!1,resolve:b.resolve,rest:[]});return}Jo(Xs(k,{showAnswered:b.showAnswered,width:Ke()})),cn({cursor:0,rows:el(x),groups:x,resolve:b.resolve,report:k});return}case"update":{Jl.current=!0,h({kind:"note",tone:"info",text:"Updating the d360-writer toolchain\u2026 (don\u2019t close this window)"}),jo(!0);let b=await ol().finally(()=>jo(!1));b.ok?(h({kind:"note",tone:"ok",text:`\u2713 Updated ${b.packages.join(" + ")} \u2014 run /exit, then relaunch to apply.`}),oe("/exit"),Vr("")):(h({kind:"note",tone:"warn",text:`Update failed. ${nl(b.output)}`}),b.output&&h({kind:"note",tone:"info",text:`${b.output}
|
|
554
|
+
|
|
555
|
+
Full output: ${tl()}`}));return}case"screenshot":{let b=ks(f),k=mo(e);if(k&&b.mode!=="list"&&h({kind:"note",tone:"info",text:k}),b.mode==="capture"){await S(b.rest);return}if(b.mode==="annotate"){await M(b.rest);return}if(b.mode==="checklist"){await W();return}if(b.mode==="verify"){let v=Fe(e),A=b.rest.find(E=>!E.startsWith("-")),L=A?[A]:Ws(v);if(A&&!v.some(E=>E.id===A)){h({kind:"note",tone:"error",text:`No screenshot placeholder called "${A}". /screenshot list shows them all.`});return}if(L.length===0){let E=v.filter(F=>F.state==="rejected").length,z=v.filter(F=>F.state==="verified").length;h({kind:"note",tone:"info",text:E>0?`Nothing left to verify. ${E} shot${E===1?"":"s"} failed verification \u2014 re-capture with /screenshot capture --failed.`:z>0?`All ${z} captured shot${z===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:Wn(L.length)}),await Pe(on(e,L),{display:A?`/screenshot verify ${A}`:"/screenshot verify",quietUser:!0});let j=Cr(e,L);j.length>0&&h({kind:"note",tone:"info",text:j.join(`
|
|
556
|
+
`)});return}if(b.mode==="list"){if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let v=ge(e)?.docsDir??ph,A=ou(e,b.scope),L=Fe(e,A);if(b.picker){if(L.length===0){h({kind:"note",tone:"info",text:"No screenshot placeholders found in the docs."});return}let E=Im(L);if(E.length===0){h({kind:"note",tone:"info",text:pa(L,{docsDir:v}).join(`
|
|
557
|
+
`)});let z=Re("/push","--screenshots",A),F=Yt(e,{text:`\u2713 All ${L.length} screenshots are captured. ${z} saves them into the articles on Document360; /screenshot capture${A?` ${A}`:""} re-captures.`,cmd:z},`\u2713 All ${L.length} screenshots are captured. `,A);De(F.text,{kind:"cmd",cmd:F.cmd,reason:""});return}Xn({cursor:0,rows:E,title:"Screenshots \u2014 pick what to author or capture:"});return}h({kind:"note",tone:"info",text:pa(L,{scope:A,detail:b.detail,docsDir:v}).join(`
|
|
558
|
+
`)}),k&&h({kind:"note",tone:"info",text:k});let j=nu(L,A);j.key!=="done"&&oe(j.cmd);return}if(b.mode==="single"){await Gh(b.id);return}if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let x=b.mode==="scope"?b.scope:void 0,y=T1(e,{scope:x}).map(v=>v.id);if(y.length===0){h({kind:"note",tone:"info",text:x?`No screenshot placeholders under ${x}.`:"No screenshot placeholders found in the docs."});return}await Hh(y,{setup:b.setup,scope:b.mode==="scope"?b.scope:void 0,runLine:b.mode==="scope"?[`/screenshot author ${b.scope}`,`/screenshot ${b.scope}`]:["/screenshot author --all","/screenshot --all"]});return}case"capture":{await S(f);return}case"reset":{let b=up(e);if(b.length===0){h({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}Fo.current={repoName:ai(e),targets:b,hadDevhints:Fr(Yk(e))},h({kind:"note",tone:"warn",text:pp(e,b).join(`
|
|
559
|
+
`)}),nt(ai(e));return}default:h({kind:"note",tone:"error",text:`Unknown command: /${c} \u2014 type /help.`})}},[e,r,s,er,pc,h,ot,Pe,ht,lc,qh]),us=ne(u=>{let p=(u??g).trim();if($(""),di(null),Lo(0),p.startsWith("/")){te.current=!1,Le.current=!1,je.current=null,Bt(),qo(null);let f=zl.current.includes(p);f&&(zl.current=[]),ie(S=>f?[]:gk(S,p))}if(!p||(Xt(!1),st.current=!1,(Fo.current||Ee.current.length>0)&&h({kind:"user",text:p}),Yh(p))||Vh(p))return;Wl.current.push(p);let c=kk(p,wh.current);if(p.startsWith("/"))h({kind:"user",text:p}),q(!0),uo(c).finally(()=>q(!1));else if(z1(c)){h({kind:"user",text:p});let f=X1(c);if(!f)Pe(c,{display:p,quietUser:!0});else{try{Q1(e,{title:f,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}Pe(`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${f}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${f}" and the article path(s) you wrote.`,{display:p,quietUser:!0})}}else{let f=Ym(e,c);Pe(f??c,{display:p})}},[g,Yh,Vh,uo,Pe]),Kh=ne(u=>{if(u.length>1){if(u.includes("\x1B"))return;let p=wk(u);if(yk(p)){let c=bk(++d$.current,p);wh.current.set(c,p),P(c)}else P(p);return}P(u)},[P]),tr=Math.max(10,ct-6),zh=Il(()=>Nl(d.text,tr),[d.text,tr]),hc=ne(u=>w(p=>({...p,pos:Math.max(0,Math.min(p.text.length,p.pos+u))})),[]),Ni=ne(u=>w(p=>({...p,pos:vk(Nl(p.text,tr),p.pos,u)})),[tr]),ds=ne(u=>w(p=>({...p,pos:xk(Nl(p.text,tr),p.pos,u)})),[tr]),b$=["\x1B[H","\x1B[1~","\x1BOH"],k$=["\x1B[F","\x1B[4~","\x1BOF"],Xh=ne((u,p)=>p.leftArrow?(hc(-1),!0):p.rightArrow?(hc(1),!0):u&&b$.includes(u)?(ds("start"),!0):u&&k$.includes(u)?(ds("end"),!0):p.ctrl&&u==="a"?(ds("start"),!0):p.ctrl&&u==="e"?(ds("end"),!0):!1,[hc,ds]),fc=ne(()=>{if(Me.current){if(!Me.current.signal.aborted){let u=(Ko?.verb??"work").toLowerCase(),p=Ko?.unit??"article";h({kind:"note",tone:"warn",text:`\u238B Stopping the ${u} run (finishing in-flight ${p}s)\u2026`}),Me.current.abort()}return!0}return Jr.current?!1:(Jr.current=!0,h({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),Ot.current?.interrupt(),!0)},[Ko]);return BN((u,p)=>{if(p.ctrl&&u==="c"){if(Zr.current!==null&&Date.now()-Zr.current<t$){Zr.current=null,Ot.current?.close(),r();return}Zr.current=Date.now(),Rh(!0),Gl.current&&clearTimeout(Gl.current),Gl.current=setTimeout(()=>{Zr.current=null,Rh(!1)},t$),R?fc():g&&$("");return}if(ss.current.awaySince!==null&&Ge.current===null)try{let c=lk(ss.current,Date.now(),$n(e));if(ss.current=c.memory,_h(null),c.kind==="delta"){h({kind:"note",tone:"info",text:uk(c.delta,c.awayMs)});let f=pt(!1);f.kind==="recommend"&&dn(f.rec,{silent:!0})}else if(c.kind==="briefing"){h({kind:"note",tone:"info",text:`\u{1F4E5} ${si(c.delta)} arrived while you were away (${Zp(c.awayMs)}).`});let f=pt(!1);f.kind==="recommend"&&dn(f.rec)}}catch{}if(nc.current=Date.now(),!D){if(Rt){if(p.return){hi(null),fi.current=!0,I(c=>c+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(u==="b"||u==="B"){hi(null),$("/auto --budget ");return}if(p.escape){hi(null),eo.current=!0,Ge.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."}),I(c=>c+1);return}return}if(p.tab&&p.shift&&!Sn&&!ln&&!rc){let c=ge(e);if(!c){h({kind:"note",tone:"info",text:"Set this repo up first with /init \u2014 then shift+tab switches between auto and manual."});return}let f=!Ok(c);xa(e,c,f),f&&(eo.current=!1);let S=!f&&Ge.current!==null;S&&(Ge.current={...Ge.current,stopping:!0}),h({kind:"note",tone:"ok",text:S?"Manual mode \u2014 I'll finish what is running and stop there, then hand back. (shift+tab to change it back.)":`${f?"Auto mode ON":"Manual mode"} \u2014 ${Ts(f)} (shift+tab to change it back.)`}),I(M=>M+1);return}if(R){if(p.escape){if(Ge.current){eo.current=!0;let c=Ge.current;fc(),ls({kind:"stopped",how:"esc"},c.parked);return}fc();return}if(p.return){let c=g.trim();if(!c)return;Zn.current.push(c),Hl([...Zn.current]),$("");return}if(Xh(u,p))return;if(p.upArrow){Ni(-1);return}if(p.downArrow){Ni(1);return}if(p.backspace||p.delete){C();return}u&&!p.ctrl&&!p.meta&&Kh(u);return}if(ln){if(p.upArrow){Kn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Kn(c=>c&&{...c,cursor:Math.min(Nt.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=un(u,Nt.length);c!==null&&Kn(f=>f&&{...f,cursor:c});return}if(p.return){let c=Nt[ln.cursor];Kn(null);let{lines:f,changed:S,effective:M}=Fs(e,c.value??"default");for(let W of f)h({kind:"note",tone:W.startsWith("\u26A0")?"warn":W.startsWith("\u2713")?"ok":"info",text:W});S&&(Ah(W=>W+1),Ot.current?.setModel(M));return}if(u==="s"){let c=Nt[ln.cursor];Kn(null),Ot.current?.setModel(c.value??void 0),h({kind:"note",tone:"ok",text:`\u2713 Using ${c.label} for this session only (your saved default is unchanged).`});return}if(p.escape){Kn(null);return}return}if(Mt){if(p.upArrow){Uo(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Uo(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=un(u,Mt.rows.length);c!==null&&Uo(f=>f&&{...f,cursor:c});return}if(p.return||u==="s"){let c=Mt.rows[Mt.cursor];Uo(null),uc(c.name,p.return===!0);return}if(p.escape){Uo(null);return}return}if(ts){if(p.escape){oo(null);return}if(p.leftArrow||p.tab&&p.shift){oo(c=>c&&{tab:(c.tab-1+ft.length)%ft.length,scroll:0});return}if(p.rightArrow||p.tab){oo(c=>c&&{tab:(c.tab+1)%ft.length,scroll:0});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=ft.length){oo({tab:Number(u)-1,scroll:0});return}if(p.upArrow){oo(c=>c&&{...c,scroll:Math.max(0,c.scroll-1)});return}if(p.downArrow){oo(c=>{if(!c)return c;let f=(ft[c.tab]??ft[0]).rows.length;return{...c,scroll:Math.min(Math.max(0,f-1),c.scroll+1)}});return}return}if(Ft){if(p.upArrow){Wo(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Wo(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=un(u,Ft.rows.length);c!==null&&Wo(f=>f&&{...f,cursor:c});return}if(p.return){let c=Ft.rows[Ft.cursor].name;if(Wo(null),!Dc(e,c).created){h({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}h({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${c}").`});let S=!1;try{let M=Vn(c);S=!!M&&!(Do(M)&&!M.refreshToken)}catch{S=!1}h({kind:"note",tone:"info",text:S?`Next: sign in to ${c} and pick your project \u2014 you're already signed in here, so it'll be quick.`:`Next: sign in to Document360 (${c}) and pick your project.`}),oe("/login"),I(M=>M+1);return}if(p.escape){Wo(null);return}return}if(Qe){if(p.upArrow){Bo(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Bo(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=un(u,Qe.rows.length);c!==null&&Bo(f=>f&&{...f,cursor:c});return}if(p.return){let c=Qe.rows[Qe.cursor],{profile:f,projectId:S}=Qe;Bo(null),Ai(f,S,c);return}if(p.escape){Bo(null);return}return}if(it){if(p.upArrow){zn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){zn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=un(u,it.rows.length);c!==null&&zn(f=>f&&{...f,cursor:c});return}if(p.return){let c=it.rows[it.cursor],{profile:f}=it;zn(null),Di(f,c);return}if(p.escape){zn(null);return}return}if(at){if(p.upArrow){Vo(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Vo(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u===" "){Vo(c=>c&&{...c,rows:c.rows.map((f,S)=>S===c.cursor?{...f,checked:!f.checked}:f)});return}if(p.return){let c=at.rows.filter(f=>f.checked).map(f=>f.path);if(Vo(null),c.length===0){h({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}Tu(e,c),h({kind:"note",tone:"ok",text:`\u2713 Scoped to ${c.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let f of c)h({kind:"note",tone:"info",text:` ${f}`});h({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(p.escape){Vo(null);return}return}if(dt){if(p.upArrow){Qn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Qn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=un(u,dt.rows.length);c!==null&&Qn(f=>f&&{...f,cursor:c});return}if(p.return){let c=dt.rows[dt.cursor],f=dt.run;Qn(null),f(c.token);return}if(p.escape){Qn(null);return}return}if($t){if(p.upArrow){Ho(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Ho(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=un(u,$t.rows.length);c!==null&&Ho(f=>f&&{...f,cursor:c});return}if(p.return){let c=$t.rows[$t.cursor],f=$t.conflicts;Ho(null),c.conflict?pc(c.paths[0]):c.kind==="article"?lc(c.paths[0]):ht(c.paths,c.kind==="all"?f:0);return}if(p.escape){Ho(null);return}return}if(Ut){if(p.upArrow){Go(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Go(c=>c&&{...c,cursor:Math.min(c.rows.length,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=un(u,Ut.rows.length+1);c!==null&&Go(f=>f&&{...f,cursor:c});return}if(p.return){let{cursor:c,rows:f,opts:S}=Ut;Go(null);let M=c===0?f:[f[c-1]];Wh(M,S);return}if(p.escape){Go(null),h({kind:"note",tone:"info",text:"Left as drafts \u2014 nothing changed. /publish when they have been signed off."});return}return}if(vt){let{rows:c}=vt;if(p.upArrow){cn(f=>f&&{...f,cursor:Math.max(0,f.cursor-1)});return}if(p.downArrow){cn(f=>f&&{...f,cursor:Math.min(c.length-1,f.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let f=Kp(kh.current,Number(u),c.length-1);kh.current=f.memory,f.index!==null&&cn(S=>S&&{...S,cursor:f.index+1});return}if(u==="a"||u==="A"){cn(f=>f&&{...f,cursor:0});return}if(p.return){let f=c[vt.cursor],{groups:S,resolve:M,report:W}=vt;if(cn(null),f.kind==="all"){ac(S,{resolve:M,report:W});return}Jo(Za(f.group,{width:Ke()})),Qr({group:f.group,cursor:0,fromList:!0,resolve:M,rest:S.filter(b=>b.articleId!==f.group.articleId),report:W});return}if(p.escape){cn(null),oe("/comments");return}return}if(tt){let c=()=>{let{rest:f,group:S,fromList:M,resolve:W,report:b}=tt;if(Qr(null),!M||!b){oe("/comments");return}let k=[S,...f].sort((x,y)=>x.category.localeCompare(y.category)||x.title.localeCompare(y.title));cn({cursor:0,rows:el(k),groups:k,resolve:W,report:b})};if(p.upArrow||p.downArrow){Qr(f=>f&&{...f,cursor:f.cursor===0?1:0});return}if(u==="y"||u==="Y"||p.return&&tt.cursor===0){let{group:f,resolve:S,rest:M,report:W}=tt;Qr(null),ac([f],{resolve:S,rest:M,...W?{report:W}:{}});return}if(u==="b"||u==="B"||p.escape||p.return){c();return}return}if(Wt){if(p.upArrow){Xn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Xn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=un(u,Wt.rows.length);c!==null&&Xn(f=>f&&{...f,cursor:c});return}if(p.return){let c=Wt.rows[Wt.cursor];Xn(null),c.action==="capture"?cs(c.ids,{runLine:c.kind==="all"?["/screenshot capture --all","/capture --all"]:void 0}):c.action==="annotate"?Ti(c.ids,{verifiedBefore:new Set(Fe(e).filter(f=>f.state==="verified").map(f=>f.id))}):c.kind==="shot"?Gh(c.ids[0]):Hh(c.ids,{setup:!0,runLine:c.kind==="all"?["/screenshot author --all","/screenshot --all"]:void 0});return}if(p.escape){Xn(null);return}return}if(xt){if(p.escape){Jn(null);return}if(p.upArrow){Jn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Jn(c=>c&&{...c,cursor:Math.min(Math.max(0,Ri.length-1),c.cursor+1)});return}if(p.return){let c=Ri[xt.cursor];if(c){Jn(null);try{h({kind:"preview",name:ai(c),text:o$(Ll(li(e,c),"utf8"))})}catch(f){h({kind:"note",tone:"error",text:`Could not read ${c}: ${f.message}`})}}return}if(p.backspace||p.delete){Jn(c=>c&&{...c,query:c.query.slice(0,-1),cursor:0});return}if(u&&!p.ctrl&&!p.meta&&u.length===1){Jn(c=>c&&{...c,query:c.query+u,cursor:0});return}return}if(St){if(p.escape){no(null);return}if(p.upArrow){no(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){no(c=>c&&{...c,cursor:Math.min(Math.max(0,Si.length-1),c.cursor+1)});return}if(p.return){let c=Si[St.cursor];if(c){no(null),ot(c.uuid),sn.current={uuid:c.uuid,firstPrompt:c.firstPrompt,titleFired:!0},Yn(c.name),oh(c.uuid),Mo.current=[],lt.current={printed:[],armed:[],printedAt:zo.current};let f=zp(e,c.uuid);for(let S of f)h(S);h({kind:"note",tone:"ok",text:f.length?`Resumed "${c.name}" \u2014 restored ${f.length} message(s); continue where you left off.`:`Resumed "${c.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(p.backspace||p.delete){no(c=>c&&{...c,query:c.query.slice(0,-1),cursor:0});return}if(u&&!p.ctrl&&!p.meta&&u.length===1){no(c=>c&&{...c,query:c.query+u,cursor:0});return}return}if(p.tab&&!g&&de){$(de),Bt();return}if(!g&&he.length>0&&!st.current&&u&&/^[1-9]$/.test(u)){let c=he[Number(u)-1];if(c){$(qn(c));return}}if(!g&&he.length===0&&!st.current&<.current.armed.length>0&&u&&/^[1-9]$/.test(u)){let c=lt.current.armed[Number(u)-1];if(c){$(c);return}}if(!g&&($i||io)&&u==="c"&&!p.ctrl&&!p.meta&&!p.return&&!p.tab){let c=$i!=null;qp($i??io).then(S=>{h({kind:"note",tone:S?"ok":"warn",text:S?c?"\u2713 Copied the feedback to your clipboard \u2014 send it to the d360-writer team (Teams / Slack / email).":"\u2713 Copied the prompt to your clipboard \u2014 paste it into your repo's coding agent.":c?"Couldn't reach your clipboard \u2014 select the feedback above and copy it manually.":"Couldn't reach your clipboard \u2014 select the prompt above and copy it manually."}),S&&c&&tc(null),S&&!c&&Dh(!0)});return}if(!Xh(u,p)){if(rc){if(p.upArrow){Lo(c=>Math.max(0,c-1));return}if(p.downArrow){Lo(c=>Math.min(hn.length-1,c+1));return}if(p.tab){$("/"+(hn[Kr]?.name??"")+" "),Lo(0);return}if(p.return){let c=hn[Kr];if(c){let f=g.trim().slice(1).split(/\s+/).slice(1).join(" ");if(jg(c.usage)&&!f){$("/"+c.name+" "),Lo(0);return}us("/"+c.name+(f?" "+f:""));return}}}else{if(!g&&he.length>0&&!st.current&&(p.upArrow||p.downArrow)){if(p.downArrow){zr(c=>c===null?0:Math.min(he.length-1,c+1));return}if(_o!==null){zr(c=>c===null||c===0?null:c-1);return}}if(p.upArrow){if(g!==""&&Oo===null){Ni(-1);return}let c=Wl.current;if(!c.length)return;let f=Oo===null?c.length-1:Math.max(0,Oo-1);di(f),$(c[f]??"");return}if(p.downArrow){if(g!==""&&Oo===null){Ni(1);return}let c=Wl.current;if(Oo===null)return;let f=Oo+1;f>=c.length?(di(null),$("")):(di(f),$(c[f]??""));return}}if(p.return){if(_o!==null&&!g&&he[_o]){let c=qn(he[_o]);zr(null),us(c);return}us();return}if(p.backspace||p.delete){C();return}if(p.escape){Ge.current&&(eo.current=!0,ls({kind:"stopped",how:"esc"},Ge.current.parked)),$(""),Lo(0),Bt(),ie([]),qo(null),zr(null),te.current=!0;return}u&&!p.ctrl&&!p.meta&&Kh(u)}}}),et(()=>{if(R||D)return;let u=Zn.current.shift();u!==void 0&&(Hl([...Zn.current]),us(u))},[R,D,us]),ce(Ne,{flexDirection:"column",width:ct,children:[ic!==null&&ce(Ne,{marginTop:1,flexDirection:"column",children:[ic.truncated&&H(G,{dimColor:!0,children:"\u2026"}),H(G,{children:ic.text})]}),Yo?H(cj,{step:Yo.step,cmd:Yo.cmd,startedAt:Yo.startedAt,spentUsd:Math.max(Yo.spentUsd,Ct-(Ge.current?.stepStartedSpend??Ct)),budgetUsd:Yo.budgetUsd}):null,R&&Ko?H(pj,{p:Ko}):null,Ch?H(uj,{text:Ch}):R&&!Ko?H(lj,{startTime:_e.current,chars:Yr}):null,H(Ne,{borderStyle:"round",borderColor:Mh.prod?"yellow":ae,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:g?zh.map((u,p)=>{let c=d.text.slice(u.start,u.end),f=p===jl(zh,d.pos),S=Math.min(d.pos,u.end)-u.start;return ce(G,{children:[H(G,{color:ae,children:p===0?"> ":" "}),f?ce(Hr,{children:[c.slice(0,S),H(Br,{ch:c[S]??" "}),c.slice(S+1)]}):c||" "]},`${p}-${u.start}`)}):ce(G,{children:[H(G,{color:ae,children:"> "}),Sn?H(Br,{ch:" "}):Se&&!R?ce(Hr,{children:[H(Br,{ch:Se[0],dim:!0}),H(G,{color:"gray",children:Se.slice(1)})]}):de&&!R?ce(Hr,{children:[H(Br,{ch:de[0],dim:!0}),H(G,{color:"gray",children:de.slice(1)}),H(G,{dimColor:!0,children:" (tab)"})]}):(oc.isSetup||!No)&&!R?ce(Hr,{children:[H(Br,{ch:oc.text[0],dim:!0}),H(G,{color:"gray",children:oc.text.slice(1)})]}):H(Br,{ch:" "})]})}),xh.length>0&&H(Ne,{flexDirection:"column",paddingX:1,children:xh.map((u,p)=>H(G,{color:"gray",children:`\u29D7 queued: ${u}`},`${p}-${u.slice(0,24)}`))}),Rt?ce(Ne,{flexDirection:"column",paddingX:1,children:[H(G,{color:ae,bold:!0,children:"Auto mode \u2014 the full round trip"}),H(G,{color:"gray",children:` starting with ${Rt.firstCmd}`}),Rt.scale?H(G,{color:"gray",children:` ${Rt.scale}`}):null,Rt.scale&&!Rt.scale.includes("$")?H(G,{color:"gray",children:" no cost estimate yet \u2014 this repo has not finished a run for me to measure"}):null,H(G,{color:"gray",children:` spending limit ${He(Rt.budgetUsd)} \xB7 I stop and report if it is reached`}),H(G,{color:"gray",children:" screenshots are not part of an automatic run"}),Rt.overBudget?H(G,{color:"yellow",children:`\u26A0 That is more than your ${He(Rt.budgetUsd)} limit. I will stop partway and report what is left.`}):null,H(G,{dimColor:!0,children:Rt.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"})]}):ts?H(pk,{tab:ts.tab,scroll:ts.scroll,rows:w$,width:ct,version:o,engineVersion:r$}):ln?ce(Ne,{flexDirection:"column",paddingX:1,children:[H(G,{color:ae,bold:!0,children:"Select model"}),H(G,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),Nt.map((u,p)=>ce(G,{color:p===ln.cursor?ae:void 0,children:[p===ln.cursor?"\u276F ":" ",`${p+1}. ${u.label}${p===ln.current?" \u2714":""}`.padEnd(16),H(G,{color:"gray",children:` ${u.desc}`})]},u.label)),H(G,{dimColor:!0,children:bt({verb:"set as default",rows:Nt.length,extra:["s this session only"]})})]}):Mt?ce(Ne,{flexDirection:"column",paddingX:1,children:[H(G,{color:ae,bold:!0,children:"Switch connection profile"}),H(xn,{rows:Mt.rows,cursor:Mt.cursor,cap:Qt,render:(u,p,c)=>ce(G,{color:c?ae:void 0,children:[c?"\u276F ":" ",`${p+1}. ${u.name}${p===Mt.current?" \u2714":""}`.padEnd(20),H(G,{color:"gray",children:` ${u.env} \xB7 ${u.who??"not signed in"}`}),u.prod?H(G,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},u.name)}),H(G,{dimColor:!0,children:bt({verb:"switch (saved as default)",rows:Mt.rows.length,extra:["s this session only"]})})]}):Ft?ce(Ne,{flexDirection:"column",paddingX:1,children:[H(G,{color:ae,bold:!0,children:"Pick your Document360 environment"}),H(xn,{rows:Ft.rows,cursor:Ft.cursor,cap:Qt,render:(u,p,c)=>ce(G,{color:c?ae:void 0,children:[c?"\u276F ":" ",`${p+1}. ${u.name}`.padEnd(16),H(G,{color:"gray",children:` ${u.apiUrl}`}),u.note?H(G,{color:"yellow",children:` \u26A0 ${u.note}`}):null]},u.name)}),H(G,{dimColor:!0,children:bt({verb:"use it",rows:Ft.rows.length})})]}):Qe?ce(Ne,{flexDirection:"column",paddingX:1,children:[H(G,{color:ae,bold:!0,children:"Switch workspace"}),H(G,{dimColor:!0,children:`environment ${Qe.environment} \xB7 project ${Qe.projectName??`${Qe.projectId.slice(0,8)}\u2026`}`}),H(xn,{rows:Qe.rows,cursor:Qe.cursor,cap:Qt,render:(u,p,c)=>ce(G,{color:c?ae:void 0,children:[c?"\u276F ":" ",`${p+1}. ${u.name}${p===Qe.current?" \u2714":""}`.padEnd(30),H(G,{color:"gray",children:u.type?` ${u.type}`:""})]},u.id)}),H(G,{dimColor:!0,children:bt({verb:"switch",rows:Qe.rows.length})})]}):it?ce(Ne,{flexDirection:"column",paddingX:1,children:[H(G,{color:ae,bold:!0,children:"Choose project"}),H(G,{dimColor:!0,children:`environment ${it.environment}`}),H(xn,{rows:it.rows,cursor:it.cursor,cap:Qt,render:(u,p,c)=>ce(G,{color:c?ae:void 0,children:[c?"\u276F ":" ",`${p+1}. ${u.name}${p===it.current?" \u2714":""}`.padEnd(30),H(G,{color:"gray",children:u.sub?` ${u.sub}`:""})]},u.id)}),H(G,{dimColor:!0,children:bt({verb:"switch",rows:it.rows.length})})]}):at?(()=>{let p=Math.min(Math.max(0,at.cursor-Math.floor(7)),Math.max(0,at.rows.length-14)),c=at.rows.slice(p,p+14),f=at.rows.filter(S=>S.checked).length;return ce(Ne,{flexDirection:"column",paddingX:1,children:[H(G,{color:ae,bold:!0,children:`Which folders back the user docs? (${f} selected of ${at.rows.length})`}),p>0?H(G,{dimColor:!0,children:` \u2191 ${p} more`}):null,c.map((S,M)=>{let W=p+M;return ce(G,{color:W===at.cursor?ae:void 0,children:[W===at.cursor?"\u276F ":" ",S.checked?"\u25C9 ":"\u25CB ",S.path.padEnd(Math.min(48,ct-34)),H(G,{color:"gray",children:Ra(S)})]},S.path)}),p+14<at.rows.length?H(G,{dimColor:!0,children:` \u2193 ${at.rows.length-p-14} more`}):null,H(G,{dimColor:!0,children:bt({verb:"save",multi:!0})})]})})():dt?ce(Ne,{flexDirection:"column",paddingX:1,children:[H(G,{color:ae,bold:!0,children:dt.title??"Which category? (pick one to scope to)"}),H(xn,{rows:dt.rows,cursor:dt.cursor,cap:Qt,render:(u,p,c)=>ce(G,{color:c?ae:void 0,children:[c?"\u276F ":" ",`${`${p+1}.`.padEnd(3)} ${u.label} (${u.count})`.padEnd(Math.min(44,Math.max(20,ct-24))),H(G,{color:"gray",children:` ${u.token}`})]},u.token)}),H(G,{dimColor:!0,children:bt({verb:"choose it",rows:dt.rows.length})})]}):$t?ce(Ne,{flexDirection:"column",paddingX:1,children:[H(G,{color:ae,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),H(xn,{rows:$t.rows,cursor:$t.cursor,cap:Qt,render:(u,p,c)=>ce(G,{color:c?ae:void 0,bold:u.kind==="category"&&!c,children:[c?"\u276F ":" ",`${u.indent?" ":" "}${`${p+1}.`.padEnd(3)} ${u.label}`.padEnd(Math.min(56,ct-24)),u.note?H(G,{color:"gray",children:` ${u.note}`}):null]},`${u.kind}:${u.paths.join(",")}`)}),H(G,{dimColor:!0,children:bt({verb:"push as drafts",rows:$t.rows.length})})]}):Ut?ce(Ne,{flexDirection:"column",paddingX:1,children:[H(G,{color:ae,bold:!0,children:"Publish live to your readers \u2014 this is what they will see:"}),H(xn,{rows:[{path:"",articleId:"",label:`Publish all ${Ut.rows.length} live`,version:void 0},...Ut.rows],cursor:Ut.cursor,cap:Qt,render:(u,p,c)=>ce(G,{color:c?ae:void 0,bold:p===0&&!c,children:[c?"\u276F ":" ",` ${`${p+1}.`.padEnd(3)} ${u.label}`.padEnd(Math.min(56,ct-24)),p>0?H(G,{color:"gray",children:` ${u.version?`draft v${u.version} \u2192 live`:"draft \u2192 live"}`}):null]},`${p}:${u.path||"all"}`)}),H(G,{dimColor:!0,children:bt({verb:"publish live",cancel:"leave as drafts",rows:Ut.rows.length+1})})]}):vt?ce(Ne,{flexDirection:"column",paddingX:1,children:[H(G,{color:ae,bold:!0,children:"Which comments do you want to look at?"}),H(xn,{rows:vt.rows,cursor:vt.cursor,cap:Qt,render:(u,p,c)=>ce(G,{color:c?ae:void 0,bold:u.kind==="all"&&!c,children:[c?"\u276F ":" ",`${(u.kind==="all"?"":`${u.n}.`).padEnd(4)}${u.label}`.padEnd(Math.min(56,Math.max(20,ct-24))),u.kind==="article"?H(G,{color:"gray",children:u.note}):null]},u.kind==="all"?"all":u.group.articleId)}),H(G,{dimColor:!0,children:bt({verb:"open it",cancel:"close",rows:vt.rows.length-1})}),vt.resolve?H(G,{dimColor:!0,children:"--resolve is on: threads you answer will be closed as well as replied to"}):null]}):tt?ce(Ne,{flexDirection:"column",paddingX:1,children:[H(G,{color:ae,bold:!0,children:`${tt.group.title} \u2014 ${tt.group.threads.length} comment${tt.group.threads.length===1?"":"s"}`}),ce(G,{color:tt.cursor===0?ae:void 0,children:[tt.cursor===0?"\u276F ":" ",tt.resolve?"Yes \u2014 fix them, push the draft, reply and resolve":"Yes \u2014 fix them, push the draft to Document360, then reply"]}),ce(G,{color:tt.cursor===1?ae:void 0,children:[tt.cursor===1?"\u276F ":" ",tt.fromList?"No \u2014 back to the list":"No \u2014 leave them for now"]}),H(G,{dimColor:!0,children:bt({verb:"open it",cancel:"go back",extra:["y answer"]})})]}):Wt?ce(Ne,{flexDirection:"column",paddingX:1,children:[H(G,{color:ae,bold:!0,children:Wt.title}),(()=>{let{rows:u,cursor:p}=Wt,c=Sl(u.length,p,Qt),f=c.start,S=u.slice(c.start,c.end),M=`${u.length}.`.length+1,W=jm(u,Math.max(20,ct-4-M));return ce(Hr,{children:[f>0?H(G,{color:"gray",children:` \u2026 ${f} more above`}):null,S.map((b,k)=>{let x=f+k,y=x===p,v=W[x];return ce(G,{color:y?ae:void 0,bold:(b.kind==="all"||b.kind==="category")&&!y,children:[y?"\u276F ":" ",`${x+1}.`.padEnd(M),v.head,v.note?H(G,{color:"gray",children:v.note}):null]},`${b.action}:${b.kind}:${b.ids.join(",")}`)}),c.below>0?H(G,{color:"gray",children:` \u2026 ${c.below} more below`}):null]})})(),H(G,{dimColor:!0,children:bt({verb:"run it",rows:Wt.rows.length})})]}):xt?ce(Ne,{flexDirection:"column",paddingX:1,children:[H(G,{color:ae,bold:!0,children:`Preview article${xt.query?` \u2014 filter: ${xt.query}`:" (type to filter)"}`}),Ri.length===0?H(G,{color:"gray",children:"no articles match"}):Ri.map((u,p)=>ce(G,{color:p===xt.cursor?ae:void 0,children:[p===xt.cursor?"\u276F ":" ",u]},u)),H(G,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):St?ce(Ne,{flexDirection:"column",paddingX:1,children:[H(G,{color:ae,bold:!0,children:`Resume session${St.query?` \u2014 filter: ${St.query}`:" (type to filter)"}`}),Si.length===0?H(G,{color:"gray",children:"no sessions match"}):Si.map((u,p)=>ce(G,{color:p===St.cursor?ae:void 0,children:[p===St.cursor?"\u276F ":" ",u.name.slice(0,28).padEnd(30),H(G,{color:p===St.cursor?ae:"gray",children:u.firstPrompt.slice(0,Math.max(10,ct-40))})]},u.uuid)),H(G,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):rc?ce(Ne,{flexDirection:"column",children:[lo>0?H(G,{dimColor:!0,children:` \u22EF ${lo} more above`}):null,sc.map((u,p)=>{let c=lo+p,f=u.name==="model"&&Yl?`${u.desc} (currently ${Yl})`:u.desc,S=Math.max(20,ct-4),M=u.usage.length>S?`${u.usage.slice(0,S-1)}\u2026`:u.usage,W=S-Math.max(M.length,22)-1,b=W<=1?"":f.length>W?`${f.slice(0,W-1)}\u2026`:f;return ce(G,{color:c===xi?ae:void 0,children:[c===xi?"\u276F ":" ",M.padEnd(22)," ",H(G,{color:c===xi?ae:"gray",children:b})]},u.name)}),lo+sc.length<hn.length?H(G,{dimColor:!0,children:` \u22EF ${hn.length-lo-sc.length} more below`}):null,H(G,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!R&&!g&&he.length>0?ce(Ne,{flexDirection:"column",paddingX:1,children:[vh?H(G,{color:ae,children:vh}):null,H(xn,{rows:he,cursor:_o??0,cap:Qt,render:(u,p)=>{let c=p===_o,f=qn(u),S=f.slice(0,Math.max(20,ct-7)),M=ct-S.length-9,W=M>=12?(mk(u)??Dg(f)).slice(0,M):"";return ce(G,{color:c?ae:void 0,children:[c?"\u276F ":" ",H(G,{color:ae,children:p+1})," ",S,W?H(G,{color:c?ae:void 0,dimColor:!c,children:` \u2014 ${W}`}):null]},f)}}),H(G,{dimColor:!0,children:`\u2191\u2193 choose \xB7 enter run \xB7 1-${he.length} fill \xB7 esc cancel`})]}):H(Ne,{paddingX:1,children:ce(G,{color:"gray",children:[Mh.prod?"\u26A0 PRODUCTION \xB7 ":"",H(G,{color:ns?ae:void 0,children:ns?"\u23F5\u23F5 auto":"\u23F5 manual"}),` \xB7 /help \xB7 ${Yl??"model n/a"}${t.kind==="api"?Ct>0?` \xB7 session ${gt(Ct)}`:"":Th>0?` \xB7 ${$r(Th)}`:""} \xB7 \u2191 history \xB7 shift+tab mode \xB7 ${p$?"press ctrl+c again to exit":"ctrl+c twice to exit"}`]})})]})}se();import{jsx as gj}from"react/jsx-runtime";async function i$(e=process.cwd(),t="auto",n,o="0.0.0"){let r=mj(t);r.kind==="none"&&(console.error(""),console.error(_("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${Z("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${Z("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=fj(gj(s$,{cwd:e,auth:r,profileName:n,version:o}),{exitOnCtrlC:!1});await s(),process.stdout.write(`
|
|
560
|
+
`),process.exit(0)}se();import{writeCrashLog as hh,isBenignTransportError as wj}from"document360-engine";var a$=!1;function yj(e=process.stdout){return e.destroyed===!0||e.writable===!1}function fh(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function l$(e){if(a$)return;a$=!0;let t=(n,o)=>{if(wj(o)){hh({kind:n,level:"transport",message:fh(o),stack:o instanceof Error?o.stack:void 0,detail:e}),yj()&&(hh({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=hh({kind:n,level:"fatal",message:fh(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
|
|
561
|
+
`+_(`\u2717 d360-writer crashed: ${fh(o)}`)+`
|
|
562
562
|
`),r&&process.stderr.write(m(` Crash details: ${r}`)+`
|
|
563
563
|
`+m(" Run: d360-writer logs")+`
|
|
564
|
-
`),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var
|
|
564
|
+
`),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var vj=kj(import.meta.url),Fl=vj("../package.json");l$("d360-writer");var zt=new bj;function mh(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}zt.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=>{mh(e),await _i({profile:e.profile,manual:e.manual})});zt.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=>{mh(e),await pf({profile:e.profile,allProjects:e.allProjects})});zt.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{mh(e),await df({profile:e.profile})});var gh=zt.command("profile").description("Manage connection profiles for the current repo");gh.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>Mi(process.cwd()));gh.command("use <name>").description("Set the default profile for this repo").action(e=>Fi(process.cwd(),e));gh.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>Ui(process.cwd(),e));var c$=zt.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");c$.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>rr(process.cwd(),e.profile));c$.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await of(process.cwd(),e,t.profile)});var u$=zt.command("project").description("Choose the Document360 project for this repo (active profile's identity)");u$.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>Li(process.cwd(),e.profile));u$.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await sf(process.cwd(),e,t.profile)});zt.command("init").description("Scaffold .d360-writer/config.json for this repo (interactive)").action(async()=>{let{initCommand:e}=await Promise.resolve().then(()=>(zi(),Yf));await e()});zt.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(()=>vc());zt.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(()=>(qa(),Rw)),n=await t(process.cwd(),Fl.version);for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});zt.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(Fl.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($j.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 bf(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 Lb(e.cwd,e.auth,e.profile,Fl.version):await i$(e.cwd,e.auth,e.profile,Fl.version)});zt.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
|