document360-writer 0.5.268 → 0.5.269
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 +214 -213
- package/package.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var kk=Object.defineProperty;var Qr=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var gh=(e,t)=>{for(var n in t)kk(e,n,{get:t[n],enumerable:!0})};import gn from"picocolors";var ae,$k,vk,xk,wh,Jr,g,O,G,q,J,be,Be,me,se=Qr(()=>{"use strict";ae="#7f56d9",[$k,vk,xk]=[127,86,217],wh=e=>gn.isColorSupported?`\x1B[38;2;${$k};${vk};${xk}m${e}\x1B[39m`:e,Jr=e=>gn.bold(wh(e)),g=e=>gn.dim(e),O=e=>gn.red(e),G=e=>gn.yellow(e),q=e=>gn.green(e),J=wh,be=e=>gn.gray(e),Be=e=>gn.bold(e),me=(e,t)=>`${e} ${t}`});import{existsSync as Vo,writeFileSync as bn,readFileSync as $$,readdirSync as v$}from"node:fs";import{join as Hh}from"node:path";import{devHintsGuidePath as xi,hintsDir as Gh,hooksDir as qh,architectureDir as zh,messagesDir as zl,creatorNotesPath as Vh,devhintsStatePath as Xh,directivesPath as Yh,DIRECTIVES_HEADER as x$,roadmapPath as Kh,ROADMAP_HEADER as R$,ensureDir as ns,writeMessage as C$,listOpenForDev as S$,stampDone as P$}from"document360-engine";function Qh(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
|
|
3
3
|
|
|
4
4
|
<!-- devhints script v${Ie} \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 A$(){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 Ko(e){
|
|
253
|
-
`)}Vo(Vh(e))||bn(Vh(e),
|
|
254
|
-
`)}function
|
|
255
|
-
`)}function sn(e){try{return
|
|
256
|
-
`)}),n.notifiedBuilder=!0)}}catch{}return n}function
|
|
257
|
-
`)}function
|
|
252
|
+
`}function Ko(e){ns(Gh(e)),ns(zh(e)),ns(zl(e));for(let n of[Gh(e),zl(e)]){let o=Hh(n,".gitkeep");Vo(o)||bn(o,`# Keeps this document360-writer inbox tracked in git even when empty.
|
|
253
|
+
`)}Vo(Vh(e))||bn(Vh(e),A$()),Vo(Yh(e))||bn(Yh(e),x$),Vo(Kh(e))||bn(Kh(e),R$),bn(xi(e),Qh()),ns(qh(e)),bn(Hh(qh(e),"open-questions.mjs"),T$);let t=Ut(e);return Zh(e,new Date().toISOString()),t}async function Jh(e,t){for(let n of zo(Ko(t.cwd)))console.log(n);return{kind:"continue"}}function to(){return[`This is document360-writer's dev hand-off setup (v${Ie}).`,'Connect this repository to document360-writer (its "docs agent" \u2014 a separate tool that writes this',"product's user documentation from your code, but needs your intent). This prompt is SAFE TO RUN MORE","THAN ONCE \u2014 paste it again whenever the product changes. At each step: create what is missing, reconcile","what already exists, and never duplicate, clobber a refined file, or delete human-written notes. In order:","","1. Read `.d360-writer/DEV-HINTS-GUIDE.md` \u2014 the full dev\u2192docs hand-off protocol (Parts 1\u20136). Follow it.","2. Architecture brief in `.d360-writer/architecture/` (per the guide). First read"," `.d360-writer/architecture/CREATOR-NOTES.md` and treat it as authoritative (it may be empty; never"," modify it). Then:"," \u2022 If no brief exists yet, write it now \u2014 a USER-DOC-enabling brief: product intent, user-facing"," surfaces, features and why a user reaches for each, roles/permission gating, core workflows,"," terminology \u2014 every claim citing the source file(s) that prove it. Skip internals (services, data"," access, infra, build/CI, tests)."," \u2022 If a brief already exists, UPDATE it to match the current code: add new surfaces/features, correct"," what changed, remove what was deleted \u2014 but preserve accurate existing content and any human edits."," Do NOT rewrite it from scratch. If nothing changed, leave it as is.","3. Persist the ongoing rule so teammates' agents inherit it: this repo's agent-memory file (CLAUDE.md,"," or AGENTS.md \u2014 whichever this repo already uses; create CLAUDE.md if neither exists) should contain a",' short "Documentation hand-off" section saying: on every user-facing change, drop a hint file in'," `.d360-writer/hints/` and keep `.d360-writer/architecture/` current \u2014 and SURFACE each hint drop in"," your reply (name the file + the one-line surface), never silently; NEVER write or publish the"," user-facing articles yourself (that is the docs agent's job \u2014 you only hand off); each session,"," check `.d360-writer/messages/` for open questions from the docs agent and answer them promptly and"," in full \u2014 an open docs question BLOCKS the documentation, and `[discovery]` questions define the"," whole product brief, so answer those in depth; `git pull` at session start FIRST, because the docs"," agent may be on another machine and its questions only reach you when you pull; AND when the"," human types `@d360-writer <directive>` in your session, append it as an `## [open] <directive>` block"," to `.d360-writer/directives.md` (create if absent) and commit \u2014 do NOT action it yourself (the docs"," agent picks it up on its next /catch-up) \u2014 all per `.d360-writer/DEV-HINTS-GUIDE.md`. If that section"," is already there, leave it (refine in place only if"," wrong) \u2014 do NOT add a duplicate. Then commit `.d360-writer/` and the memory-file change ONLY if"," something actually changed.","4. Wire the SESSION-START QUESTION NUDGE so open docs questions surface every session \u2014 a memory rule"," alone (step 3) is easy to forget. d360-writer already scaffolded a portable, dependency-free checker"," at `.d360-writer/hooks/open-questions.mjs` (prints a one-line nudge when open `from: docs` questions"," exist; silent otherwise). Register it with YOUR coding agent's session-start mechanism:"," \u2022 Claude Code (this repo has a `.claude/` dir): add a `SessionStart` hook to `.claude/settings.json`"," (create the file if absent) that runs `node .d360-writer/hooks/open-questions.mjs` \u2014 its stdout is"," added to your context at session start. MERGE into any existing hooks, do NOT clobber other"," settings, and skip if that exact hook is already there. Shape:",' {"hooks":{"SessionStart":[{"hooks":[{"type":"command","command":"node .d360-writer/hooks/open-questions.mjs"}]}]}}'," \u2022 Codex / other agents: no stdout-injecting session hook yet \u2014 rely on the step-3 memory rule, and"," optionally run `node .d360-writer/hooks/open-questions.mjs` yourself when starting a docs-touching"," session. Wire the same command once your agent gains a session-start trigger."," Commit the hook config (`.claude/settings.json` or the equivalent) with the rest. Idempotent \u2014 leave"," an existing hook alone.","5. Two-way messages (Part 3). FIRST run `git pull` (fast-forward) if this repo has a remote \u2014 the docs"," agent may be a different person on a different machine, so their questions for you only EXIST in your",' checkout once you pull; skipping it makes an empty mailbox look like "no questions". If the pull'," cannot fast-forward, say so and continue rather than merging or rebasing to force it. Then check"," `.d360-writer/messages/` for open questions addressed to you"," (`from: docs`, `status: open`). Answer each IN FULL \u2014 an open docs question blocks the documentation,"," and `[discovery]`-tagged questions (what the product is, who it's for, its core mental model,"," misconceptions, positioning, terminology) define the whole product brief, so answer those in depth."," Fold durable facts into the architecture brief and drop a reply (`from: dev`, `kind: answer`,"," `re: <id>`) \u2014 then set the question's frontmatter `status: done`. If there are none, continue.","6. Then STOP and ask me for tribal knowledge \u2014 present it as a clearly-marked, standalone prompt on its"," own line (NOT buried in prose) and WAIT for my reply before doing anything else. Use this shape:",' "\u23F8 YOUR INPUT NEEDED \u2014 Any tribal knowledge that would help document this product? (folder map,',` terminology, what to prioritize or skip, gotchas.) Type it below, or reply 'none' / 'carry on' to skip."`," If I give you anything, phrase it clearly and append it to `.d360-writer/architecture/CREATOR-NOTES.md`"," (keep the existing header comment and every note already there; only add). If I say 'none'/'carry on', continue.",`7. Record completion: write/merge \`.d360-writer/devhints-state.json\` with {"completedVersion": ${Ie},`,' "completedAt": "<UTC now>", "completedCommit": "<current HEAD short sha>"} (preserve any other keys'," already in the file, e.g. emittedAt). Include this file in the commit from step 3.","8. Finish with a RECEIPT of what this run actually changed, then the right next step. Two parts.",""," (a) The receipt. A heading line, then one short bullet per thing that CHANGED \u2014 omit any bullet"," that did not happen, so a run that changed little stays three lines rather than ten. Report"," OUTCOMES, not the steps you took. Cover, where applicable: the protocol version you moved to; the"," architecture brief (created / N files updated / unchanged); how many docs questions you answered"," (and how many were `[discovery]`); how many hints you dropped \u2014 and when none, add one clause",' saying WHY, so "0 hints" reads as a judgement rather than an omission; whether you added to'," CREATOR-NOTES.md; whether you wired the session-start hook; and the commit you pushed. Shape:"," \u2705 Hand-off refreshed (protocol v11 \u2192 v12)"," \u2022 architecture brief: 2 files updated"," \u2022 answered 3 docs questions (1 [discovery])"," \u2022 dropped 0 hints \u2014 only internal test anchors changed"," \u2022 committed + pushed: <short sha>",' Say "\u2705 Setup complete" instead when this was the first-time setup (no brief existed before).',""," (b) The next step \u2014 chosen by what you are actually HANDING OVER. Do not print a command in every"," case, and never invent one to look helpful:"," \u2022 You answered a question, dropped a hint, or relayed an owner directive \u2192 the docs agent has a"," queue to fold in. Print, fenced on its own line so it copies cleanly:"," ```"," /catch-up"," ```"," \u2022 The docs folder configured in `.d360-writer/config.json` (default `.d360-writer/user-docs/`) is"," absent or empty \u2192 this repo has no docs yet, so it is a cold start:"," ```"," write the docs for this repo"," ```"," \u2022 You handed over NOTHING (no answers, no hints, no directives) and docs already exist \u2192 print NO",' command. Say: "Nothing new to hand over. Switch back to the document360-writer terminal \u2014 it',' will show you where things stand." The docs agent picks its own next action from the whole'," picture (its documentation campaign, coverage gaps, what is still unpublished); a command"," guessed from your side would override one it already knows to be better.",' When you DO print a block, precede it with "Back in the document360-writer terminal, paste this:"',' \u2014 or "Now switch to the document360-writer terminal and paste this:" on first-time setup.'].join(`
|
|
254
|
+
`)}function Ql(e){try{let t=$$(Xh(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function Zh(e,t){let o={...Ql(e)??{},emittedVersion:Ie,emittedAt:t};bn(Xh(e),`${JSON.stringify(o,null,2)}
|
|
255
|
+
`)}function sn(e){try{return v$(zh(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function Ut(e){let n=Ql(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<Ie?"stale":"current",completedVersion:n}}function E$(e){let t=new RegExp(`${Xl.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(\\d+)\\)`).exec(e);return t?Number(t[1]):null}function Ri(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,supersededRequests:[],toVersion:Ie};try{if(!Vo(xi(e)))return n;let o=Ql(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;if(Ie>r&&(ns(zl(e)),bn(xi(e),Qh()),Zh(e,t),n.guideRefreshed=!0),Ie>s){let i=S$(e).filter(l=>l.kind==="request"&&l.subject.startsWith(Xl)),a=i.filter(l=>(E$(l.subject)??Ie)>=Ie);for(let l of i.filter(d=>!a.includes(d)))P$(e,l.file,{doneAt:t,answeredBy:"docs"}),n.supersededRequests.push(l.subject);a.length===0&&(C$(e,{id:`onb${Ie}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${Xl}${Ie})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${Ie}${s?` (you last completed v${s})`:""}.`,"Re-run the hand-off so the docs agent and this repo stay in step \u2014 run this prompt here:","",to()].join(`
|
|
256
|
+
`)}),n.notifiedBuilder=!0)}}catch{}return n}function Ci(e){if(!Vo(xi(e)))return[];let t=Ut(e);return t.status==="current"?[]:[`\u{1F514} Your builder agent ${t.completedVersion?`is on v${t.completedVersion}`:"hasn't completed the hand-off yet"} \u2014 d360-writer's dev\u2194docs protocol is now v${Ie}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,Yo,to(),Yo,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function Jl(){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 Si(){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):",Yo,Jl(),Yo]}function zo(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${Ie}.`," Have them run the prompt below again \u2014 it now sets up two-way messages + on-demand docs.",""]:[],"\u2713 Wrote .d360-writer/DEV-HINTS-GUIDE.md + the .d360-writer/architecture/ (brief), .d360-writer/hints/, and .d360-writer/messages/ inboxes.","","\u{1F4CB} Copy this one prompt and run it in your repo's coding agent (Claude Code / Codex / Cursor):",Yo,to(),Yo,"","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 Yo,Ie,T$,Xl,kn=Qr(()=>{"use strict";Yo="-".repeat(64),Ie=12,T$=`#!/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
|
-
`;
|
|
295
|
+
`;Xl="Re-run dev\u2194docs onboarding (protocol v"});var pf={};gh(pf,{initCommand:()=>tc,scaffoldInit:()=>Zl,writeWriterGitignore:()=>ec});import{input as os,confirm as D$}from"@inquirer/prompts";import{basename as nf,join as Pi}from"node:path";import{existsSync as Xo,readFileSync as of,readdirSync as N$,writeFileSync as ef}from"node:fs";import{writeProjectConfig as rf,readProjectConfig as j$,projectConfigPath as sf,writerDir as I$,DEFAULT_DOCS_DIR as af,DEFAULT_CAPTURE_DIR as lf,DEFAULT_OUTPUT_DIR as cf}from"document360-engine";function Zl(e,t="berlin"){let n=sf(e);if(Xo(n))return{created:!1,path:n,profileName:""};let o={projectId:uf(e)??nf(e),docsDir:af,captureDir:lf,outputDir:cf,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:df(e)};return rf(o,e),ec(e),{created:!0,path:n,profileName:t}}function ec(e){let t=Pi(I$(e),".gitignore"),n="# Local/transient \u2014 the config files here ARE meant to be committed.";if(!Xo(t)){ef(t,[n,...tf,""].join(`
|
|
296
296
|
`),"utf8");return}let o;try{o=of(t,"utf8")}catch{return}let r=new Set(o.split(/\r?\n/).map(l=>l.trim())),s=tf.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;ef(t,`${o}${a}${s.join(i)}${i}`,"utf8")}async function Zl(){let e=process.cwd(),t=sf(e);if(Xo(t)&&!await E$({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(w("init cancelled.")),{kind:"continue"};let n=uf(e)??nf(e),o=await ts({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await ts({message:"Capture directory (where document360-capture .spec.ts files live):",default:lf}),s=await ts({message:"Screenshot output directory:",default:cf}),i=await ts({message:"Default connection profile name:",default:"berlin"}),a=await ts({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),l={projectId:o,docsDir:af,captureDir:r,outputDir:s,profiles:{[i]:{connection:{environment:a},production:!1}},defaultProfile:i,authoritativeSourceFiles:df(e)},d=N$(e);d?.terminologyGlossary&&(l.terminologyGlossary=d.terminologyGlossary),rf(l,e),Jl(e);let g=Ko(e);console.log(""),console.log(q(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${J(`d360-writer login --profile ${i}`)} ${w("(sign in; project & workspace auto-selected)")}`),console.log("");for(let f of zo(g))console.log(f);return console.log(""),console.log(`${w("Then ask:")} ${J('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function uf(e){let t=Si(e,"package.json");if(!Xo(t))return null;try{return JSON.parse(of(t,"utf8")).name??null}catch{return null}}function df(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Xo(Si(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Si(e,n);Xo(o)&&!I$(o)&&t.push(n)}return t}function I$(e){try{return D$(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var tf,Pi=zr(()=>{"use strict";se();kn();tf=[".sessions/","cache/"]});import{createRequire as X$}from"node:module";import{existsSync as Q$,readFileSync as J$}from"node:fs";import{dirname as $f,join as vf}from"node:path";function ut(){let e;try{e=Z$.resolve("document360-capture/helpers")}catch{return null}let t=$f(e);for(let n=0;n<5&&!Q$(vf(t,"package.json"));n++)t=$f(t);try{let n=JSON.parse(J$(vf(t,"package.json"),"utf8"));return n.name==="document360-capture"&&n.version?n.version:null}catch{return null}}var Z$,Qo=zr(()=>{"use strict";Z$=X$(import.meta.url)});var Fg={};gh(Fg,{doctorCommand:()=>$s,renderDoctorChecks:()=>Mg,runDoctorChecks:()=>_g});import{existsSync as WR}from"node:fs";import{d360GetAll as BR,getAccessToken as HR,isExpired as ba,loadProfileMap as GR,loadTokens as qR,listStoredSessions as VR,tokensProjectId as Hu,packageSkillsDir as Og,ENGINE_VERSION as YR,projectConfigPath as KR,readProjectConfig as zR,DEFAULT_DOCS_DIR as XR,fetchManifestSummary as QR,resolveActiveProfile as JR,classifyClaudeAuth as ZR,CLAUDE_CODE_SETUP_HINT as ka,resolveModelSetting as eC,probeModel as tC,probeAgentTurn as nC,stderrHeadline as oC,detectAppType as rC,playbookSkillName as sC,D360AuthError as iC,applyStructureOrder as aC}from"document360-engine";async function _g(e,t){let n=[],o=ut();n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${YR}${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=ZR();s.state==="ready"?n.push({level:"ok",label:`Claude auth: ${s.kind==="api"?"API key":"subscription (Claude Code login found)"}`}):s.state==="maybe"?n.push({level:"warn",label:"Claude: no Claude Code login found (may be in the macOS Keychain)",fix:`If a docs turn ends with no output, sign in to Claude Code. ${ka}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:ka});let i=eC(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 tC(e,i.model??void 0);if(D.ok){n.push({level:"ok",label:`Model reachable \u2014 replied in ${(D.latencyMs/1e3).toFixed(1)}s`});let L=await nC(e,i.model??void 0);if(L.ok)n.push({level:"ok",label:`Agent turn works \u2014 ran with your skills and tools in ${(L.latencyMs/1e3).toFixed(1)}s`});else{let B=oC(L.stderr),M=/auth|sign.?in|login|credential|token|401|expired/i.test(`${L.error??""} ${L.stderr??""}`);if(n.push({level:"fail",label:L.timedOut?"Agent turn never finished \u2014 the model answers, but a real turn with your skills and tools hangs":M?"Agent turn failed \u2014 your Claude sign-in has expired, so every /write, /review and /catch-up will do nothing":`Agent turn produced nothing \u2014 the model answers, but a real turn with your skills and tools ${L.producedNothing?"ends instantly with no output":`fails: ${L.error}`}`,fix:(B?`Claude Code said: "${B}". `:"")+(M?`Sign in again, then re-run /doctor. ${ka}`:"This is the failure behind an empty /write, /review or /catch-up. Run /logs for the whole thing \u2014 it offers to copy it so you can send it to the team.")}),M){let X=n.find(z=>z.label.startsWith("Claude auth:"));X&&(X.level="warn",X.label="Claude auth: a sign-in exists on this machine, but it is no longer valid",X.fix=`Sign in again. ${ka}`)}}}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=zR(e);if(!a)return n.push({level:"fail",label:`No ${KR(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${a.projectId}`});let l=(a.docsDir??XR).replace(/\/+$/,"");n.push(a.mode==="engineer"?{level:"warn",label:"Mode: engineer \u2014 agent may modify any source file (dogfooding)",fix:'Remove "mode" from .d360-writer/config.json for the writer-mode boundary'}:{level:"ok",label:`Mode: writer \u2014 edits limited to ${l}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let d=a.authoritativeSourceFiles??[];n.push(d.length>0?{level:"ok",label:`Sources: docs grounded in ${d.length} path(s) (${d.slice(0,3).join(", ")}${d.length>3?", \u2026":""})`}:{level:"warn",label:"Sources: not set \u2014 docs are grounded in the whole repo",fix:"Run: /scope to choose which files/folders the docs are written from"});let g=a.appType??rC(e);if(g){let D=a.appType?"from config":"auto-detected",L=g==="web"||g==="cli";n.push({level:"ok",label:`Genre: ${g} (${D})${L?` \u2192 ${sC(g)} loaded`:" \u2014 no doc-type playbook for this genre yet (generic skills)"}`})}else n.push({level:"warn",label:"Genre: unclassified \u2014 no doc-type playbook is loading (generic output)",fix:"Run /genre <web|cli|service|library> to pick \u2014 raises docs to that genre's craft bar"});let f;try{f=JR(e),n.push({level:"ok",label:`Profile: ${f.name} (${f.connection.name})${f.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 x=qR(f.name,f.project.projectId),P=VR(f.name).filter(D=>{let L=Hu(D);return!!L&&L!==f.project.projectId&&!(ba(D)&&!D.refreshToken)}),$=f.project.projectName?`"${f.project.projectName}"`:"this project";x?ba(x)&&!x.refreshToken?n.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):ba(x)?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 ${$} (until ${new Date(x.expiresAt).toLocaleString()})`}):n.push(P.length>0?{level:"fail",label:`Document360: not signed in to ${$} \u2014 signed in to ${P.map(D=>D.projectName?`"${D.projectName}"`:(Hu(D)??"").slice(0,8)+"\u2026").join(", ")} instead`,fix:`Run: /login and pick ${$} \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 ${f.name})`}),P.length>0&&n.push({level:"ok",label:`Other Document360 projects signed in on this machine: ${P.map(D=>D.projectName?`"${D.projectName}"`:(Hu(D)??"").slice(0,8)+"\u2026").join(", ")} (kept \u2014 each repo uses its own)`}),n.push(f.project.workspaceId?{level:"ok",label:`Workspace: ${f.project.workspaceName??f.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let C=GR(e,f.name);C?C.projectId&&f.project.projectId&&C.projectId!==f.project.projectId?n.push({level:"fail",label:`Category map projectId (${C.projectId}) \u2260 profile projectId (${f.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):n.push({level:"ok",label:`Category map: ${Object.keys(C.articles).length} articles, ${Object.keys(C.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${f.name}" (created on first /push)`}),n.push(WR(Og())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${Og()}`,fix:"Reinstall document360-writer (broken install)"});let A=Ut(e);if(A.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${Ie})`}):A.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${A.completedVersion}, current is v${Ie}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),x&&(!ba(x)||x.refreshToken)){let D={profile:f.name,connection:f.connection,projectId:f.project.projectId,projectName:f.project.projectName};try{await HR(D);let B=await BR(D,"/v3/projects");n.push({level:"ok",label:`API reachable (${f.connection.apiUrl}) \u2014 ${B.length} project(s) visible`})}catch(B){n.push({level:"fail",label:`API call failed: ${B.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let L=C?.projectId??f.project.projectId;if(L&&f.project.workspaceId){try{let B=await QR(D,L,f.project.workspaceId);if(B){let M=(B.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Your Document360 project: reachable on ${f.connection.name} (${B.languages?.length??0} language${(B.languages?.length??0)===1?"":"s"}) \xB7 version ${M||"(none)"}`})}else n.push({level:"ok",label:`Workspace sync manifest: not live on ${f.connection.name} yet \u2014 sync uses the per-article path (nothing to do)`})}catch(B){B instanceof iC||/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 (${f.project.projectName??L})`,fix:"Run /login and pick this repo's project \u2014 your token is scoped to another project"}):n.push({level:"warn",label:`Workspace sync manifest: probe failed (${B.message.slice(0,80)})`})}try{let B=await aC({cwd:e,profileName:f.name,dryRun:!0}),M=B.categoriesReordered+B.articlesReordered;if(B.skipped==="no category map")n.push({level:"ok",label:"Reading order: nothing to check yet (no articles published)"});else if(B.skipped)n.push({level:"warn",label:`Reading order: can't be checked (${B.skipped})`,fix:"Your article order on Document360 may not match your structure \u2014 /push syncs it once this resolves"});else if(B.unverified)n.push({level:"warn",label:`Reading order: ${B.unverified} of your articles aren't listed by Document360, so their order can't be set`,fix:"Usually means those articles are not live yet (the listing returns published articles). /publish takes them live, then /push re-syncs the order"});else if(M>0){let X=[B.categoriesReordered>0?`${B.categoriesReordered} categor${B.categoriesReordered===1?"y":"ies"}`:"",B.articlesReordered>0?`${B.articlesReordered} article${B.articlesReordered===1?"":"s"}`:""].filter(Boolean);n.push({level:"warn",label:`Reading order: ${X.join(" + ")} out of order on Document360`,fix:"Run /push \u2014 it re-syncs the order from your NN- folder/file prefixes"})}else n.push({level:"ok",label:"Reading order: Document360 matches your structure"});if(B.orphans?.length){let X=B.orphans;n.push({level:"warn",label:`${X.length} article${X.length===1?"":"s"} on Document360 ${X.length===1?"is":"are"} not in your docs folder: ${X.slice(0,3).map(z=>z.path).join(", ")}${X.length>3?`, +${X.length-3} more`:""}`,fix:"/retire <path> takes one off your readers \xB7 /pull <path> brings one back into your docs folder \u2014 until you choose, it stays live and d360-writer leaves it alone"})}}catch(B){n.push({level:"warn",label:`Reading order: check failed (${B.message.slice(0,80)})`})}}}return n}function Mg(e){let t=[""];for(let r of e){let s=r.level==="ok"?q("\u2713"):r.level==="warn"?G("\u26A0"):O("\u2717");t.push(` ${s} ${r.label}${r.detail?w(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${w("fix:")} ${J(r.fix)}`)}let n=e.filter(r=>r.level==="fail").length,o=e.filter(r=>r.level==="warn").length;return t.push(""),t.push(n===0?q(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):O(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function $s(e,t){console.log(w("Running checks\u2026"));for(let n of Mg(await _g(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var $a=zr(()=>{"use strict";kn();se();Qo()});import{Command as IN}from"commander";import{createRequire as LN}from"node:module";import{AUTH_MODES as ON}from"document360-engine";import{input as Fk}from"@inquirer/prompts";import{loginPkce as Uk,refreshTokens as Wk,toStoredTokens as Ch,clearTokens as Bk,decodeJwtClaims as xh,isExpired as Hk,loadTokens as Sh,saveTokens as Ph,listStoredSessions as Ml,tokensProjectId as yn,rememberSessionProject as Rh,resolveActiveProfile as Zr,setProfileProject as Gk,readProjectConfig as qk}from"document360-engine";se();import{select as xk}from"@inquirer/prompts";import{resolveActiveProfile as Rk,setProfileProject as Ck,resolveProjectId as Sk,listWorkspaces as Pk}from"document360-engine";async function Qr(e,t){let n=Rk(e,t),o={profile:n.name,connection:n.connection,projectId:n.project.projectId,projectName:n.project.projectName},r=n.project.projectId??Sk(o);return{workspaces:await Pk(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var yh=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function Ol(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){Ck(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function bh(e,t,n){let o;try{o=await Qr(e,n)}catch(s){return console.log(O(`Could not list workspaces: ${s.message}`)),1}let r=Ol(o.workspaces,t);return r?(di(e,o.profile,o.projectId,r.id,r.name),console.log(q(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(O(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function qo(e,t){let n;try{n=await Qr(e,t)}catch(d){console.log(O(`Could not list workspaces: ${d.message}`));return}let{workspaces:o,projectId:r,profile:s,current:i}=n;if(o.length===0){console.log(w("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let d of o)console.log(` ${d.id===i?J("\u25CF"):" "} ${yh(d)} ${w(d.id)}`);console.log(w("Run: d360-writer workspace use <name>"));return}let a=await xk({message:"Select the Document360 workspace for this repo:",choices:o.map(d=>({name:`${yh(d)}${d.id===i?" (current)":""}`,value:d.id}))}),l=o.find(d=>d.id===a);di(e,s,r,a,l?.name),console.log(q(`\u2713 Workspace set to "${l?.name??a}" for profile "${s}".`))}se();import{select as Tk}from"@inquirer/prompts";import{resolveActiveProfile as Ak,setProfileProject as Ek,listProjects as Dk}from"document360-engine";async function rn(e,t){let n=Ak(e,t),o={profile:n.name,connection:n.connection};return{projects:await Dk(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var kh=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function _l(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 pi(e,t,n,o){Ek(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function $h(e,t,n){let o;try{o=await rn(e,n)}catch(s){return console.log(O(`Could not list projects: ${s.message}`)),1}let r=_l(o.projects,t);return r?(pi(e,o.profile,r.id,r.name),console.log(q(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log(O(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function hi(e,t){let n;try{n=await rn(e,t)}catch(l){console.log(O(`Could not list projects: ${l.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(w("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let l of o)console.log(` ${l.id===s?J("\u25CF"):" "} ${kh(l)} ${w(l.id)}`);console.log(w("Run: d360-writer project use <name>"));return}let i=await Tk({message:"Select the Document360 project for this repo:",choices:o.map(l=>({name:`${kh(l)}${l.id===s?" (current)":""}`,value:l.id}))}),a=o.find(l=>l.id===i);pi(e,r,i,a?.name),console.log(q(`\u2713 Project set to "${a?.name??i}" for profile "${r}". Next: pick a workspace.`))}se();import Nk from"picocolors";function jk(e=process.env){return e.FORCE_HYPERLINK==="0"||!Nk.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 Ik(e,t=e,n){return jk(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Lk=/https?:\/\/[^\s\x1b]+/g;function Jr(e,t){return e.replace(Lk,n=>Ik(n,n,t))}import{readProjectConfig as vh,sunsetEnvironment as Ok,resolveActiveProfile as _k}from"document360-engine";function Mk(e,t){let n=vh(e);return Object.entries(n?.profiles??{}).find(([,o])=>(o.connection?.environment??"berlin")===t)?.[0]??null}function wn(e,t){try{if(!vh(e))return null;let n=_k(e,t),o=Ok(n.connection.name);if(!o)return null;let r=Mk(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 Th(e){return{...xh(e.idToken)??{},...xh(e.accessToken)??{}}}function fi(e){let t=Th(e),n=t.email??t.preferred_username??t.sub??"unknown",o=yn(e),r=e.projectName?` \xB7 project "${e.projectName}"`:o?` \xB7 project ${o}`:"";return`${n}${r}`}async function Fl(e,t,n){n&&Rh(e,t,n);try{let{projects:o}=await rn(process.cwd(),e);for(let r of Ml(e)){let s=yn(r);s&&Rh(e,s,o.find(i=>i.id===s)?.name)}}catch{}}function Vk(e,t,n){let o=yn(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 mi(e){let t=Zr(process.cwd(),e.profile),n=t.connection;console.log(w(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=wn(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 Uk(n,{manual:e.manual,promptForRedirect:g=>Fk({message:g})},g=>console.log(Jr(g))),s=Ch(t.name,r);Ph(s),await Ul(s,t.name,g=>console.log(w(g)));let i=yn(s),a=Zr(process.cwd(),e.profile).project;i&&await Fl(t.name,i,a.projectId===i?a.projectName:void 0);let l=Sh(t.name,i??void 0)??s;console.log(""),console.log(q(`\u2713 Logged in to "${t.name}" as ${fi(l)}`));let d=Vk(l,a.projectId,a.projectName);if(d&&console.log(G(d)),console.log(w(` access token expires: ${s.expiresAt}`)),console.log(w(` refresh token: ${s.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{qk(process.cwd())?.profiles?.[t.name]&&(console.log(""),await qo(process.cwd(),t.name))}catch{}}async function Ul(e,t,n){let r=Th(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Zr(process.cwd(),t).project.projectId)return;let i;try{let{projects:a}=await rn(process.cwd(),t);i=a.find(l=>l.id===r)?.name}catch{}Gk(process.cwd(),t,{projectId:r,projectName:i}),n(` Project "${i??r}" written to profile "${t}".`)}catch{}}async function Ah(e){let t=Zr(process.cwd(),e.profile),n=t.connection,o=Sh(t.name,t.project.projectId);if(!o){console.log(O(`Not logged in to Document360 (profile "${t.name}").`));let r=Ml(t.name).filter(s=>yn(s)&&yn(s)!==t.project.projectId);r.length>0&&console.log(w(`This repo's project needs its own sign-in. Signed in on this machine: ${r.map(s=>s.projectName??yn(s)).join(", ")}`)),console.log(w(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${J(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${fi(o)}`),Hk(o))if(o.refreshToken)try{let r=Ch(t.name,await Wk(n,o.refreshToken));Ph(r),console.log(q(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(G(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(w(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(G("Session expired (no refresh token).")),console.log(w(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(w(` expires: ${o.expiresAt}`))}async function Eh(e){let t=Zr(process.cwd(),e.profile),n=e.allProjects?void 0:t.project.projectId,o=t.project.projectName?`"${t.project.projectName}"`:`profile "${t.name}"`;if(Bk(t.name,n)){console.log(q(e.allProjects?`\u2713 Logged out of every Document360 project for profile "${t.name}".`:`\u2713 Logged out of ${o}.`));let r=Ml(t.name).filter(s=>yn(s)).length;r>0&&console.log(w(`Still signed in to ${r} other project${r===1?"":"s"} on this machine.`))}else console.log(w(`No Document360 session for ${o} \u2014 nothing to do.`))}se();import{readProjectConfig as Dh,writeProjectConfig as Yk,resolveActiveProfile as Kk,loadTokens as zk,isExpired as Xk}from"document360-engine";function gi(e){let t=Dh(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(O("No profiles in .d360-writer/config.json. Run: d360-writer init")),process.exitCode=1;return}console.log("");for(let[n,o]of Object.entries(t.profiles)){let r=n===t.defaultProfile?J("\u25CF "):" ",s=o.production?G(" \u26A0 PRODUCTION"):"",i=o.connection.environment??"(inline)",a=zk(n,o.project?.projectId),l=a?Xk(a)&&!a.refreshToken?G("expired"):w("logged in"):w("not logged in");console.log(`${r}${J(n)} \u2192 ${i}${s} [${l}]`)}console.log(""),console.log(w("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function wi(e,t){let n=Dh(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(O(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,Yk(n,e);let o=n.profiles[t].production?G(" \u26A0 PRODUCTION"):"";console.log(q(`\u2713 Default profile is now "${t}"${o}`))}function yi(e,t){try{let n=Kk(e,t);console.log(""),console.log(`Profile ${J(n.name)}${n.production?G(" \u26A0 PRODUCTION"):""}`),console.log(w(` api: ${n.connection.apiUrl}`)),console.log(w(` identity: ${n.connection.authorizationUrl}`)),console.log(w(` clientId: ${n.connection.clientId}`)),console.log(w(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(w(` project: ${n.project.projectId??"(set at login)"}`)),console.log(w(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(O(n.message)),process.exitCode=1}}se();import{existsSync as Ih,readdirSync as Qk,readFileSync as Jk,statSync as Zk}from"node:fs";import{join as Lh}from"node:path";import{apiLogDir as e$}from"document360-engine";var t$=30,n$=12e3;function o$(e){if(!Ih(e))return{api:[],crash:[]};try{let t=Qk(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 r$=/·\s*(empty-turn|agent-subprocess|uncaught|unhandled)\s*===/i,s$=/·\s*FATAL\s*·/i,i$=e=>s$.test(e)||r$.test(e);function a$(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(i$),r=o??n[n.length-1];return{text:r,when:/^=== (\S+)/.exec(r)?.[1]??"",count:n.length,notable:!!o}}function l$(e,t){let n=t[0];if(!n)return null;try{return a$(Jk(Lh(e,n),"utf8"))}catch{return null}}function Nh(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}var jh=(e,t)=>{try{return`${(Zk(Lh(e,t)).size/1024).toFixed(1)} KB`}catch{return""}};function Wl(){let e=e$(),{api:t,crash:n}=o$(e),o=l$(e,n),r=[];if(o){let s=o.text.split(/\r?\n/),i=s.slice(0,t$);r.push(o.notable?me("\u2717",`The last thing that went wrong \u2014 ${Nh(o.when)}:`):me("\u2139",`Nothing has failed. The most recent note d360-writer recorded \u2014 ${Nh(o.when)}:`)),r.push("");for(let a of i)r.push(` ${a}`);s.length>i.length&&r.push(w(` \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(w(` ${o.count} entries recorded today; this is the one worth reading.`)),o.notable&&r.push(w(" 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 ${J(e)}`),!Ih(e)||t.length===0&&n.length===0)return r.push(w(" 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 ${w("(send these if something crashed or a run did nothing)")}:`);for(let s of n.slice(0,14))r.push(` ${O(s)} ${w(jh(e,s))}`)}if(t.length>0){r.push(""),r.push("Document360 call logs:");for(let s of t.slice(0,14))r.push(` ${s} ${w(jh(e,s))}`)}return r.push(""),r.push(w("Failed calls include what was sent and returned (sign-in details removed, 4 KB cap).")),r.push(w("Set D360_LOG_BODIES=1 to record successful calls too.")),{lines:r,copyText:o?o.text.slice(0,n$):null,notable:!!o?.notable}}async function Oh(){return Bl(),{kind:"continue"}}function Bl(){let{lines:e,copyText:t}=Wl();console.log("");for(let n of e)console.log(n);t&&console.log(w("Inside d360-writer, /logs offers to copy this for you.")),console.log("")}se();import{createSession as c$,resolveAuth as u$,findByName as d$,slugify as p$,touchSession as h$,upsertSession as f$,resolveActiveProfile as m$}from"document360-engine";async function _h(e,t,n,o,r,s){let i=u$(n);i.kind==="none"&&(console.error(""),console.error(O("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${J("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${J("d360-writer --auth subscription")}`),process.exit(2)),i.kind==="subscription"&&console.error(w("Using your Claude subscription (no API key set)."));let a=null;try{a=m$(e,r)}catch(x){console.error(O(`Document360 profile error: ${x.message}`)),process.exit(2)}a.production&&(console.error(G(`\u26A0 Profile "${a.name}" is PRODUCTION.`)),s||(console.error(O("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(w(" --yes given \u2014 proceeding against production.")));let l;if(o){let x=d$(e,o);x||(console.error(O(`No saved session matches "${o}" in this repo.`)),console.error(w("List sessions inside the REPL with /resume.")),process.exit(2)),l=x.uuid,console.error(w(`Resuming "${x.name}"`))}let d=c$({cwd:e,resume:l,profileName:r,allowProdWrites:s===!0}),g=l??null,f=1;for await(let x of d.send(t))switch(x.type){case"session":if(!g){g=x.sessionId;let P=new Date().toISOString();f$({uuid:g,name:p$(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:P,updatedAt:P})}break;case"text":process.stdout.write(x.delta);break;case"tool":console.error(be(` \u2699 ${x.name}`));break;case"result":f=x.ok?0:1,console.error(w(`(${x.inputTokens}\u2192${x.outputTokens} tokens`+(x.costUsd>0?`, $${x.costUsd<.01?x.costUsd.toFixed(4):x.costUsd.toFixed(2)}`:"")+")")),x.ok||console.error(O("agent finished with an error result"));break;case"error":console.error(""),console.error(O(`agent error: ${x.message}`)),process.exit(1)}g&&h$(g),process.stdout.write(`
|
|
300
|
-
`),process.exit(
|
|
301
|
-
`)}var ct=[{key:"start",label:"Getting Started",rows:[{t:"text",s:"D360-Writer reads your codebase, generates end-user documentation, and publishes it to Document360."},{t:"text",s:"It needs Claude access \u2014 a Claude subscription (default) or an ANTHROPIC_API_KEY."},{t:"gap"},{t:"sub",s:"Quick start"},{t:"step",n:1,s:"Run /init \u2014 pick your environment, sign in, choose your project & workspace. It ends by printing a one-paste hand-off prompt."},{t:"step",n:2,s:"Paste that prompt into your repo's coding agent (Claude Code / Codex / Cursor). Let it finish, then follow its closing line. (Re-show it: /devhints)"},{t:"step",n:3,s:"Run /doctor to confirm every check is green."},{t:"step",n:4,s:'Type "write the docs for this repository" and follow the prompts.'},{t:"gap"},{t:"dim",s:"That's it \u2014 D360-Writer drafts your docs without you writing a line."},{t:"gap"},{t:"sub",s:"Tips"},{t:"text",s:"Just talk to it \u2014 anything not starting with / goes to the agent."},{t:"dim",s:"/ browses commands \xB7 \u2191 recalls history \xB7 esc interrupts a run \xB7 ctrl+c twice exits"},{t:"dim",s:"tab runs the suggestion \xB7 1-9 pick from a list \xB7 c copies whatever was offered for copying"}]},{key:"agentic",label:"Agentic",rows:[{t:"text",s:"Agentic Mode is designed for applications built using AI coding agents. D360-Writer works alongside your coding agent to continuously create and maintain your user documentation. Think of it as hiring a Technical Writer dedicated to your project."},{t:"gap"},{t:"text",s:"As your coding agent ships new features, it leaves documentation notes for D360-Writer. All you need to do is run the documentation loop."},{t:"gap"},{t:"sub",s:"Every few days"},{t:"cmd",name:"/catch-up",s:"Analyze the latest code changes, read the notes left by your coding agent, and update the documentation. Everything lands as a draft."},{t:"cmd",name:"/review --fix",s:"A senior editor reads every article and applies its fixes. Required before anything goes live \u2014 these were written by an AI."},{t:"cmd",name:"/review --blocked --fix",s:"The same editorial pass over only the articles publishing is blocked on \u2014 after a run that rewrote two of forty, this reads those two."},{t:"cmd",name:"/review --stale --fix",s:"The same pass over every article the current editor has not read yet \u2014 never reviewed, or reviewed before the editor last improved. Run it twice and the second run does nothing, so it is the safe way to catch a knowledge base up."},{t:"cmd",name:"/push --all",s:"Save the reviewed articles to Document360, as drafts."},{t:"cmd",name:"/publish --all",s:"Take those drafts live to your readers \u2014 it lists what will become visible and asks first."},{t:"dim",s:" (/catch-up --push runs the writing and the save back-to-back; going live stays a deliberate step)"},{t:"gap"},{t:"sub",s:"Whenever you need"},{t:"cmd",name:"/discover",s:"Interview your coding agent to understand the product (what it is, who it's for, the core idea, common misconceptions) \u2014 pins a product brief that grounds every article. Runs before writing a repo's docs; loops until confident."},{t:"cmd",name:"/audit",s:"Preview what has changed and identify missing documentation, without writing or publishing anything."},{t:"cmd",name:"/pull",s:"Bring Document360 down \u2014 pull edits made in the portal and import any new portal articles."},{t:"cmd",name:"/resolve",s:"Resolve conflicts when an article was edited both here and in the portal \u2014 review the diff, then keep yours, take the portal's, or skip."},{t:"cmd",name:"/comments",s:"The comments reviewers left on passages of your articles in the Document360 portal. You get a table \u2014 category, article, how many comments \u2014 and pick a number to read that article's comments in full (the highlighted passage beside what they said), then answer them or go back to the list. `a` answers everything. Each article is fixed, pushed to Document360 as an updated draft, and answered in the thread. Threads are left OPEN for the reviewer to close once they've checked the change; add --resolve to close the ones fully handled. --answered lists the ones already waiting on your reviewers; --full re-reads every article instead of only the ones that can have changed."},{t:"cmd",name:"/inbox",s:"Review and act on messages left by your coding agent."},{t:"cmd",name:"/ask <question>",s:"Ask your developers something the code cannot tell you: why a feature exists, when to use it, whether it can be undone. Costs nothing and does not stop your work."}]},{key:"assistant",label:"Assistant",rows:[{t:"text",s:"D360-Writer is your writing assistant \u2014 it does the writing, you decide what gets written and when."},{t:"text",s:"Best for large or complex monorepos: focus it on one feature, component, or set of source folders."},{t:"gap"},{t:"sub",s:"Just ask"},{t:"good",s:'"Write the documentation for the Multiple JWT feature we shipped in the latest release."'},{t:"gap"},{t:"sub",s:"Or use the pipeline"},{t:"cmd",name:"/scope",s:"Focus D360-Writer on specific source folders (monorepos)."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from its PRDs in .d360-writer/input/ + the code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview shows the plan + cost first)."},{t:"cmd",name:"/push",s:"Save the articles to Document360 as drafts. Requires an editorial review first \u2014 /review --fix."},{t:"cmd",name:"/push --preview <path>",s:"Show exactly what Document360 would receive for one article \u2014 details at the top and title removed, screenshots in place, links resolved. Sends nothing."},{t:"cmd",name:"/publish",s:"Take the drafts live to your readers, once they have been signed off."},{t:"cmd",name:"/status",s:"What stands between your work and your readers: which articles no editor has read, which break a blocking style rule, which would show placeholder text, and which are saved as drafts your readers cannot see yet. Each group names the one command that clears it. Costs nothing and calls nothing \u2014 run it before you publish, not after. --all shows every article gate by gate."},{t:"cmd",name:"/retire <path>",s:"Take an article off your readers: it stops being visible on Document360 and nothing offers to publish it again. Nothing is deleted \u2014 the article, its history and every reviewer comment stay, so a retirement is always reversible. Bare /retire lists what is worth retiring. /push puts one back."}]},{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."}]}],Mh=24;function Hl(e){let t=e.filter(n=>n.t==="cmd").map(n=>n.name.length);return t.length===0?Mh:Math.min(Mh,Math.max(...t))}function $i(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 g$(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=$i(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 Fh(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 ct){n.push(`\u2500\u2500 ${o.label} \u2500\u2500`,"");let r=
|
|
299
|
+
`)?"":i;ef(t,`${o}${a}${s.join(i)}${i}`,"utf8")}async function tc(){let e=process.cwd(),t=sf(e);if(Xo(t)&&!await D$({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(g("init cancelled.")),{kind:"continue"};let n=uf(e)??nf(e),o=await os({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await os({message:"Capture directory (where document360-capture .spec.ts files live):",default:lf}),s=await os({message:"Screenshot output directory:",default:cf}),i=await os({message:"Default connection profile name:",default:"berlin"}),a=await os({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),l={projectId:o,docsDir:af,captureDir:r,outputDir:s,profiles:{[i]:{connection:{environment:a},production:!1}},defaultProfile:i,authoritativeSourceFiles:df(e)},d=j$(e);d?.terminologyGlossary&&(l.terminologyGlossary=d.terminologyGlossary),rf(l,e),ec(e);let m=Ko(e);console.log(""),console.log(q(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${J(`d360-writer login --profile ${i}`)} ${g("(sign in; project & workspace auto-selected)")}`),console.log("");for(let w of zo(m))console.log(w);return console.log(""),console.log(`${g("Then ask:")} ${J('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function uf(e){let t=Pi(e,"package.json");if(!Xo(t))return null;try{return JSON.parse(of(t,"utf8")).name??null}catch{return null}}function df(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Xo(Pi(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Pi(e,n);Xo(o)&&!L$(o)&&t.push(n)}return t}function L$(e){try{return N$(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var tf,Ti=Qr(()=>{"use strict";se();kn();tf=[".sessions/","cache/"]});import{createRequire as Q$}from"node:module";import{existsSync as J$,readFileSync as Z$}from"node:fs";import{dirname as $f,join as vf}from"node:path";function ut(){let e;try{e=ev.resolve("document360-capture/helpers")}catch{return null}let t=$f(e);for(let n=0;n<5&&!J$(vf(t,"package.json"));n++)t=$f(t);try{let n=JSON.parse(Z$(vf(t,"package.json"),"utf8"));return n.name==="document360-capture"&&n.version?n.version:null}catch{return null}}var ev,Qo=Qr(()=>{"use strict";ev=Q$(import.meta.url)});var Fg={};gh(Fg,{doctorCommand:()=>xs,renderDoctorChecks:()=>Mg,runDoctorChecks:()=>_g});import{existsSync as BR}from"node:fs";import{d360GetAll as HR,getAccessToken as GR,isExpired as ka,loadProfileMap as qR,loadTokens as VR,listStoredSessions as YR,tokensProjectId as Gu,packageSkillsDir as Og,ENGINE_VERSION as KR,projectConfigPath as zR,readProjectConfig as XR,DEFAULT_DOCS_DIR as QR,fetchManifestSummary as JR,resolveActiveProfile as ZR,classifyClaudeAuth as eC,CLAUDE_CODE_SETUP_HINT as $a,resolveModelSetting as tC,probeModel as nC,probeAgentTurn as oC,stderrHeadline as rC,detectAppType as sC,playbookSkillName as iC,D360AuthError as aC,applyStructureOrder as lC}from"document360-engine";async function _g(e,t){let n=[],o=ut();n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${KR}${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=eC();s.state==="ready"?n.push({level:"ok",label:`Claude auth: ${s.kind==="api"?"API key":"subscription (Claude Code login found)"}`}):s.state==="maybe"?n.push({level:"warn",label:"Claude: no Claude Code login found (may be in the macOS Keychain)",fix:`If a docs turn ends with no output, sign in to Claude Code. ${$a}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:$a});let i=tC(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 nC(e,i.model??void 0);if(D.ok){n.push({level:"ok",label:`Model reachable \u2014 replied in ${(D.latencyMs/1e3).toFixed(1)}s`});let L=await oC(e,i.model??void 0);if(L.ok)n.push({level:"ok",label:`Agent turn works \u2014 ran with your skills and tools in ${(L.latencyMs/1e3).toFixed(1)}s`});else{let B=rC(L.stderr),M=/auth|sign.?in|login|credential|token|401|expired/i.test(`${L.error??""} ${L.stderr??""}`);if(n.push({level:"fail",label:L.timedOut?"Agent turn never finished \u2014 the model answers, but a real turn with your skills and tools hangs":M?"Agent turn failed \u2014 your Claude sign-in has expired, so every /write, /review and /catch-up will do nothing":`Agent turn produced nothing \u2014 the model answers, but a real turn with your skills and tools ${L.producedNothing?"ends instantly with no output":`fails: ${L.error}`}`,fix:(B?`Claude Code said: "${B}". `:"")+(M?`Sign in again, then re-run /doctor. ${$a}`:"This is the failure behind an empty /write, /review or /catch-up. Run /logs for the whole thing \u2014 it offers to copy it so you can send it to the team.")}),M){let X=n.find(z=>z.label.startsWith("Claude auth:"));X&&(X.level="warn",X.label="Claude auth: a sign-in exists on this machine, but it is no longer valid",X.fix=`Sign in again. ${$a}`)}}}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=XR(e);if(!a)return n.push({level:"fail",label:`No ${zR(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${a.projectId}`});let l=(a.docsDir??QR).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 m=a.appType??sC(e);if(m){let D=a.appType?"from config":"auto-detected",L=m==="web"||m==="cli";n.push({level:"ok",label:`Genre: ${m} (${D})${L?` \u2192 ${iC(m)} loaded`:" \u2014 no doc-type playbook for this genre yet (generic skills)"}`})}else n.push({level:"warn",label:"Genre: unclassified \u2014 no doc-type playbook is loading (generic output)",fix:"Run /genre <web|cli|service|library> to pick \u2014 raises docs to that genre's craft bar"});let w;try{w=ZR(e),n.push({level:"ok",label:`Profile: ${w.name} (${w.connection.name})${w.production?" \u26A0 PRODUCTION":""}`})}catch(D){return n.push({level:"fail",label:`Profile config: ${D.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let k=VR(w.name,w.project.projectId),S=YR(w.name).filter(D=>{let L=Gu(D);return!!L&&L!==w.project.projectId&&!(ka(D)&&!D.refreshToken)}),v=w.project.projectName?`"${w.project.projectName}"`:"this project";k?ka(k)&&!k.refreshToken?n.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):ka(k)?n.push({level:"ok",label:"Document360: logged in (access token expired \u2014 refreshes automatically on the next call)"}):n.push({level:"ok",label:`Document360: logged in to ${v} (until ${new Date(k.expiresAt).toLocaleString()})`}):n.push(S.length>0?{level:"fail",label:`Document360: not signed in to ${v} \u2014 signed in to ${S.map(D=>D.projectName?`"${D.projectName}"`:(Gu(D)??"").slice(0,8)+"\u2026").join(", ")} instead`,fix:`Run: /login and pick ${v} \u2014 each project needs its own sign-in, and both are then kept`}:{level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${w.name})`}),S.length>0&&n.push({level:"ok",label:`Other Document360 projects signed in on this machine: ${S.map(D=>D.projectName?`"${D.projectName}"`:(Gu(D)??"").slice(0,8)+"\u2026").join(", ")} (kept \u2014 each repo uses its own)`}),n.push(w.project.workspaceId?{level:"ok",label:`Workspace: ${w.project.workspaceName??w.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let C=qR(e,w.name);C?C.projectId&&w.project.projectId&&C.projectId!==w.project.projectId?n.push({level:"fail",label:`Category map projectId (${C.projectId}) \u2260 profile projectId (${w.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):n.push({level:"ok",label:`Category map: ${Object.keys(C.articles).length} articles, ${Object.keys(C.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${w.name}" (created on first /push)`}),n.push(BR(Og())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${Og()}`,fix:"Reinstall document360-writer (broken install)"});let A=Ut(e);if(A.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${Ie})`}):A.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${A.completedVersion}, current is v${Ie}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),k&&(!ka(k)||k.refreshToken)){let D={profile:w.name,connection:w.connection,projectId:w.project.projectId,projectName:w.project.projectName};try{await GR(D);let B=await HR(D,"/v3/projects");n.push({level:"ok",label:`API reachable (${w.connection.apiUrl}) \u2014 ${B.length} project(s) visible`})}catch(B){n.push({level:"fail",label:`API call failed: ${B.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let L=C?.projectId??w.project.projectId;if(L&&w.project.workspaceId){try{let B=await JR(D,L,w.project.workspaceId);if(B){let M=(B.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Your Document360 project: reachable on ${w.connection.name} (${B.languages?.length??0} language${(B.languages?.length??0)===1?"":"s"}) \xB7 version ${M||"(none)"}`})}else n.push({level:"ok",label:`Workspace sync manifest: not live on ${w.connection.name} yet \u2014 sync uses the per-article path (nothing to do)`})}catch(B){B instanceof aC||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(B.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${w.project.projectName??L})`,fix:"Run /login and pick this repo's project \u2014 your token is scoped to another project"}):n.push({level:"warn",label:`Workspace sync manifest: probe failed (${B.message.slice(0,80)})`})}try{let B=await lC({cwd:e,profileName:w.name,dryRun:!0}),M=B.categoriesReordered+B.articlesReordered;if(B.skipped==="no category map")n.push({level:"ok",label:"Reading order: nothing to check yet (no articles published)"});else if(B.skipped)n.push({level:"warn",label:`Reading order: can't be checked (${B.skipped})`,fix:"Your article order on Document360 may not match your structure \u2014 /push syncs it once this resolves"});else if(B.unverified)n.push({level:"warn",label:`Reading order: ${B.unverified} of your articles aren't listed by Document360, so their order can't be set`,fix:"Usually means those articles are not live yet (the listing returns published articles). /publish takes them live, then /push re-syncs the order"});else if(M>0){let X=[B.categoriesReordered>0?`${B.categoriesReordered} categor${B.categoriesReordered===1?"y":"ies"}`:"",B.articlesReordered>0?`${B.articlesReordered} article${B.articlesReordered===1?"":"s"}`:""].filter(Boolean);n.push({level:"warn",label:`Reading order: ${X.join(" + ")} out of order on Document360`,fix:"Run /push \u2014 it re-syncs the order from your NN- folder/file prefixes"})}else n.push({level:"ok",label:"Reading order: Document360 matches your structure"});if(B.orphans?.length){let X=B.orphans;n.push({level:"warn",label:`${X.length} article${X.length===1?"":"s"} on Document360 ${X.length===1?"is":"are"} not in your docs folder: ${X.slice(0,3).map(z=>z.path).join(", ")}${X.length>3?`, +${X.length-3} more`:""}`,fix:"/retire <path> takes one off your readers \xB7 /pull <path> brings one back into your docs folder \u2014 until you choose, it stays live and d360-writer leaves it alone"})}}catch(B){n.push({level:"warn",label:`Reading order: check failed (${B.message.slice(0,80)})`})}}}return n}function Mg(e){let t=[""];for(let r of e){let s=r.level==="ok"?q("\u2713"):r.level==="warn"?G("\u26A0"):O("\u2717");t.push(` ${s} ${r.label}${r.detail?g(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${g("fix:")} ${J(r.fix)}`)}let n=e.filter(r=>r.level==="fail").length,o=e.filter(r=>r.level==="warn").length;return t.push(""),t.push(n===0?q(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):O(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function xs(e,t){console.log(g("Running checks\u2026"));for(let n of Mg(await _g(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var va=Qr(()=>{"use strict";kn();se();Qo()});import{Command as ON}from"commander";import{createRequire as _N}from"node:module";import{AUTH_MODES as MN}from"document360-engine";import{input as Uk}from"@inquirer/prompts";import{loginPkce as Wk,refreshTokens as Bk,toStoredTokens as Ch,clearTokens as Hk,decodeJwtClaims as xh,isExpired as Gk,loadTokens as Sh,saveTokens as Ph,listStoredSessions as Ul,tokensProjectId as yn,rememberSessionProject as Rh,resolveActiveProfile as ts,setProfileProject as qk,readProjectConfig as Vk}from"document360-engine";se();import{select as Rk}from"@inquirer/prompts";import{resolveActiveProfile as Ck,setProfileProject as Sk,resolveProjectId as Pk,listWorkspaces as Tk}from"document360-engine";async function Zr(e,t){let n=Ck(e,t),o={profile:n.name,connection:n.connection,projectId:n.project.projectId,projectName:n.project.projectName},r=n.project.projectId??Pk(o);return{workspaces:await Tk(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var yh=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function Ml(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 pi(e,t,n,o,r){Sk(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function bh(e,t,n){let o;try{o=await Zr(e,n)}catch(s){return console.log(O(`Could not list workspaces: ${s.message}`)),1}let r=Ml(o.workspaces,t);return r?(pi(e,o.profile,o.projectId,r.id,r.name),console.log(q(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(O(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function qo(e,t){let n;try{n=await Zr(e,t)}catch(d){console.log(O(`Could not list workspaces: ${d.message}`));return}let{workspaces:o,projectId:r,profile:s,current:i}=n;if(o.length===0){console.log(g("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let d of o)console.log(` ${d.id===i?J("\u25CF"):" "} ${yh(d)} ${g(d.id)}`);console.log(g("Run: d360-writer workspace use <name>"));return}let a=await Rk({message:"Select the Document360 workspace for this repo:",choices:o.map(d=>({name:`${yh(d)}${d.id===i?" (current)":""}`,value:d.id}))}),l=o.find(d=>d.id===a);pi(e,s,r,a,l?.name),console.log(q(`\u2713 Workspace set to "${l?.name??a}" for profile "${s}".`))}se();import{select as Ak}from"@inquirer/prompts";import{resolveActiveProfile as Ek,setProfileProject as Dk,listProjects as Nk}from"document360-engine";async function rn(e,t){let n=Ek(e,t),o={profile:n.name,connection:n.connection};return{projects:await Nk(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var kh=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Fl(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 hi(e,t,n,o){Dk(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function $h(e,t,n){let o;try{o=await rn(e,n)}catch(s){return console.log(O(`Could not list projects: ${s.message}`)),1}let r=Fl(o.projects,t);return r?(hi(e,o.profile,r.id,r.name),console.log(q(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log(O(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function fi(e,t){let n;try{n=await rn(e,t)}catch(l){console.log(O(`Could not list projects: ${l.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(g("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let l of o)console.log(` ${l.id===s?J("\u25CF"):" "} ${kh(l)} ${g(l.id)}`);console.log(g("Run: d360-writer project use <name>"));return}let i=await Ak({message:"Select the Document360 project for this repo:",choices:o.map(l=>({name:`${kh(l)}${l.id===s?" (current)":""}`,value:l.id}))}),a=o.find(l=>l.id===i);hi(e,r,i,a?.name),console.log(q(`\u2713 Project set to "${a?.name??i}" for profile "${r}". Next: pick a workspace.`))}se();import jk from"picocolors";function Ik(e=process.env){return e.FORCE_HYPERLINK==="0"||!jk.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 Lk(e,t=e,n){return Ik(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Ok=/https?:\/\/[^\s\x1b]+/g;function es(e,t){return e.replace(Ok,n=>Lk(n,n,t))}import{readProjectConfig as vh,sunsetEnvironment as _k,resolveActiveProfile as Mk}from"document360-engine";function Fk(e,t){let n=vh(e);return Object.entries(n?.profiles??{}).find(([,o])=>(o.connection?.environment??"berlin")===t)?.[0]??null}function wn(e,t){try{if(!vh(e))return null;let n=Mk(e,t),o=_k(n.connection.name);if(!o)return null;let r=Fk(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 Th(e){return{...xh(e.idToken)??{},...xh(e.accessToken)??{}}}function mi(e){let t=Th(e),n=t.email??t.preferred_username??t.sub??"unknown",o=yn(e),r=e.projectName?` \xB7 project "${e.projectName}"`:o?` \xB7 project ${o}`:"";return`${n}${r}`}async function Wl(e,t,n){n&&Rh(e,t,n);try{let{projects:o}=await rn(process.cwd(),e);for(let r of Ul(e)){let s=yn(r);s&&Rh(e,s,o.find(i=>i.id===s)?.name)}}catch{}}function Yk(e,t,n){let o=yn(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 gi(e){let t=ts(process.cwd(),e.profile),n=t.connection;console.log(g(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=wn(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 Wk(n,{manual:e.manual,promptForRedirect:m=>Uk({message:m})},m=>console.log(es(m))),s=Ch(t.name,r);Ph(s),await Bl(s,t.name,m=>console.log(g(m)));let i=yn(s),a=ts(process.cwd(),e.profile).project;i&&await Wl(t.name,i,a.projectId===i?a.projectName:void 0);let l=Sh(t.name,i??void 0)??s;console.log(""),console.log(q(`\u2713 Logged in to "${t.name}" as ${mi(l)}`));let d=Yk(l,a.projectId,a.projectName);if(d&&console.log(G(d)),console.log(g(` access token expires: ${s.expiresAt}`)),console.log(g(` refresh token: ${s.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{Vk(process.cwd())?.profiles?.[t.name]&&(console.log(""),await qo(process.cwd(),t.name))}catch{}}async function Bl(e,t,n){let r=Th(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(ts(process.cwd(),t).project.projectId)return;let i;try{let{projects:a}=await rn(process.cwd(),t);i=a.find(l=>l.id===r)?.name}catch{}qk(process.cwd(),t,{projectId:r,projectName:i}),n(` Project "${i??r}" written to profile "${t}".`)}catch{}}async function Ah(e){let t=ts(process.cwd(),e.profile),n=t.connection,o=Sh(t.name,t.project.projectId);if(!o){console.log(O(`Not logged in to Document360 (profile "${t.name}").`));let r=Ul(t.name).filter(s=>yn(s)&&yn(s)!==t.project.projectId);r.length>0&&console.log(g(`This repo's project needs its own sign-in. Signed in on this machine: ${r.map(s=>s.projectName??yn(s)).join(", ")}`)),console.log(g(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${J(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${mi(o)}`),Gk(o))if(o.refreshToken)try{let r=Ch(t.name,await Bk(n,o.refreshToken));Ph(r),console.log(q(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(G(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(g(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(G("Session expired (no refresh token).")),console.log(g(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(g(` expires: ${o.expiresAt}`))}async function Eh(e){let t=ts(process.cwd(),e.profile),n=e.allProjects?void 0:t.project.projectId,o=t.project.projectName?`"${t.project.projectName}"`:`profile "${t.name}"`;if(Hk(t.name,n)){console.log(q(e.allProjects?`\u2713 Logged out of every Document360 project for profile "${t.name}".`:`\u2713 Logged out of ${o}.`));let r=Ul(t.name).filter(s=>yn(s)).length;r>0&&console.log(g(`Still signed in to ${r} other project${r===1?"":"s"} on this machine.`))}else console.log(g(`No Document360 session for ${o} \u2014 nothing to do.`))}se();import{readProjectConfig as Dh,writeProjectConfig as Kk,resolveActiveProfile as zk,loadTokens as Xk,isExpired as Qk}from"document360-engine";function wi(e){let t=Dh(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(O("No profiles in .d360-writer/config.json. Run: d360-writer init")),process.exitCode=1;return}console.log("");for(let[n,o]of Object.entries(t.profiles)){let r=n===t.defaultProfile?J("\u25CF "):" ",s=o.production?G(" \u26A0 PRODUCTION"):"",i=o.connection.environment??"(inline)",a=Xk(n,o.project?.projectId),l=a?Qk(a)&&!a.refreshToken?G("expired"):g("logged in"):g("not logged in");console.log(`${r}${J(n)} \u2192 ${i}${s} [${l}]`)}console.log(""),console.log(g("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function yi(e,t){let n=Dh(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(O(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,Kk(n,e);let o=n.profiles[t].production?G(" \u26A0 PRODUCTION"):"";console.log(q(`\u2713 Default profile is now "${t}"${o}`))}function bi(e,t){try{let n=zk(e,t);console.log(""),console.log(`Profile ${J(n.name)}${n.production?G(" \u26A0 PRODUCTION"):""}`),console.log(g(` api: ${n.connection.apiUrl}`)),console.log(g(` identity: ${n.connection.authorizationUrl}`)),console.log(g(` clientId: ${n.connection.clientId}`)),console.log(g(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(g(` project: ${n.project.projectId??"(set at login)"}`)),console.log(g(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(O(n.message)),process.exitCode=1}}se();import{existsSync as Ih,readdirSync as Jk,readFileSync as Zk,statSync as e$}from"node:fs";import{join as Lh}from"node:path";import{apiLogDir as t$}from"document360-engine";var n$=30,o$=12e3;function r$(e){if(!Ih(e))return{api:[],crash:[]};try{let t=Jk(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 s$=/·\s*(empty-turn|agent-subprocess|uncaught|unhandled)\s*===/i,i$=/·\s*FATAL\s*·/i,a$=e=>i$.test(e)||s$.test(e);function l$(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(a$),r=o??n[n.length-1];return{text:r,when:/^=== (\S+)/.exec(r)?.[1]??"",count:n.length,notable:!!o}}function c$(e,t){let n=t[0];if(!n)return null;try{return l$(Zk(Lh(e,n),"utf8"))}catch{return null}}function Nh(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}var jh=(e,t)=>{try{return`${(e$(Lh(e,t)).size/1024).toFixed(1)} KB`}catch{return""}};function Hl(){let e=t$(),{api:t,crash:n}=r$(e),o=c$(e,n),r=[];if(o){let s=o.text.split(/\r?\n/),i=s.slice(0,n$);r.push(o.notable?me("\u2717",`The last thing that went wrong \u2014 ${Nh(o.when)}:`):me("\u2139",`Nothing has failed. The most recent note d360-writer recorded \u2014 ${Nh(o.when)}:`)),r.push("");for(let a of i)r.push(` ${a}`);s.length>i.length&&r.push(g(` \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(g(` ${o.count} entries recorded today; this is the one worth reading.`)),o.notable&&r.push(g(" 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 ${J(e)}`),!Ih(e)||t.length===0&&n.length===0)return r.push(g(" 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 ${g("(send these if something crashed or a run did nothing)")}:`);for(let s of n.slice(0,14))r.push(` ${O(s)} ${g(jh(e,s))}`)}if(t.length>0){r.push(""),r.push("Document360 call logs:");for(let s of t.slice(0,14))r.push(` ${s} ${g(jh(e,s))}`)}return r.push(""),r.push(g("Failed calls include what was sent and returned (sign-in details removed, 4 KB cap).")),r.push(g("Set D360_LOG_BODIES=1 to record successful calls too.")),{lines:r,copyText:o?o.text.slice(0,o$):null,notable:!!o?.notable}}async function Oh(){return Gl(),{kind:"continue"}}function Gl(){let{lines:e,copyText:t}=Hl();console.log("");for(let n of e)console.log(n);t&&console.log(g("Inside d360-writer, /logs offers to copy this for you.")),console.log("")}se();import{createSession as u$,resolveAuth as d$,findByName as p$,slugify as h$,touchSession as f$,upsertSession as m$,resolveActiveProfile as g$}from"document360-engine";async function _h(e,t,n,o,r,s){let i=d$(n);i.kind==="none"&&(console.error(""),console.error(O("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${J("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${J("d360-writer --auth subscription")}`),process.exit(2)),i.kind==="subscription"&&console.error(g("Using your Claude subscription (no API key set)."));let a=null;try{a=g$(e,r)}catch(k){console.error(O(`Document360 profile error: ${k.message}`)),process.exit(2)}a.production&&(console.error(G(`\u26A0 Profile "${a.name}" is PRODUCTION.`)),s||(console.error(O("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(g(" --yes given \u2014 proceeding against production.")));let l;if(o){let k=p$(e,o);k||(console.error(O(`No saved session matches "${o}" in this repo.`)),console.error(g("List sessions inside the REPL with /resume.")),process.exit(2)),l=k.uuid,console.error(g(`Resuming "${k.name}"`))}let d=u$({cwd:e,resume:l,profileName:r,allowProdWrites:s===!0}),m=l??null,w=1;for await(let k of d.send(t))switch(k.type){case"session":if(!m){m=k.sessionId;let S=new Date().toISOString();m$({uuid:m,name:h$(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:S,updatedAt:S})}break;case"text":process.stdout.write(k.delta);break;case"tool":console.error(be(` \u2699 ${k.name}`));break;case"result":w=k.ok?0:1,console.error(g(`(${k.inputTokens}\u2192${k.outputTokens} tokens`+(k.costUsd>0?`, $${k.costUsd<.01?k.costUsd.toFixed(4):k.costUsd.toFixed(2)}`:"")+")")),k.ok||console.error(O("agent finished with an error result"));break;case"error":console.error(""),console.error(O(`agent error: ${k.message}`)),process.exit(1)}m&&f$(m),process.stdout.write(`
|
|
300
|
+
`),process.exit(w)}import{createInterface as oE}from"node:readline/promises";import{createSession as op,resolveAuth as rE,getSession as sE,setTitle as iE,slugify as aE,touchSession as My,upsertSession as lE,generateTitle as cE,resolveActiveProfile as Fy,resolveModelSetting as uE,readProjectConfig as dE,readUserConfig as pE,resolveAndPersistAppType as hE,decodeJwtClaims as Ly,isExpired as fE,loadTokens as mE,isDirectiveMention as gE,stripDirectiveMention as wE,appendDirective as yE,reconcileUpgradeActions as bE,stampArticles as kE,snapshotArticles as $E,listArticleFiles as vE,applyStructureOrder as xE,orderSyncLine as RE,computeSyncStatus as CE}from"document360-engine";import{ENGINE_VERSION as b$}from"document360-engine";function qt(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 ki(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 qt(`${i+1}. ${s.feature}`,76))o.push(n(a));o.push(n());for(let a of qt(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 $i(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 ct=[{key:"start",label:"Getting Started",rows:[{t:"text",s:"D360-Writer reads your codebase, generates end-user documentation, and publishes it to Document360."},{t:"text",s:"It needs Claude access \u2014 a Claude subscription (default) or an ANTHROPIC_API_KEY."},{t:"gap"},{t:"sub",s:"Quick start"},{t:"step",n:1,s:"Run /init \u2014 pick your environment, sign in, choose your project & workspace. It ends by printing a one-paste hand-off prompt."},{t:"step",n:2,s:"Paste that prompt into your repo's coding agent (Claude Code / Codex / Cursor). Let it finish, then follow its closing line. (Re-show it: /devhints)"},{t:"step",n:3,s:"Run /doctor to confirm every check is green."},{t:"step",n:4,s:'Type "write the docs for this repository" and follow the prompts.'},{t:"gap"},{t:"dim",s:"That's it \u2014 D360-Writer drafts your docs without you writing a line."},{t:"gap"},{t:"sub",s:"Tips"},{t:"text",s:"Just talk to it \u2014 anything not starting with / goes to the agent."},{t:"dim",s:"/ browses commands \xB7 \u2191 recalls history \xB7 esc interrupts a run \xB7 ctrl+c twice exits"},{t:"dim",s:"tab runs the suggestion \xB7 1-9 pick from a list \xB7 c copies whatever was offered for copying"}]},{key:"agentic",label:"Agentic",rows:[{t:"text",s:"Agentic Mode is designed for applications built using AI coding agents. D360-Writer works alongside your coding agent to continuously create and maintain your user documentation. Think of it as hiring a Technical Writer dedicated to your project."},{t:"gap"},{t:"text",s:"As your coding agent ships new features, it leaves documentation notes for D360-Writer. All you need to do is run the documentation loop."},{t:"gap"},{t:"sub",s:"Every few days"},{t:"cmd",name:"/catch-up",s:"Analyze the latest code changes, read the notes left by your coding agent, and update the documentation. Everything lands as a draft."},{t:"cmd",name:"/review --fix",s:"A senior editor reads every article and applies its fixes. Required before anything goes live \u2014 these were written by an AI."},{t:"cmd",name:"/review --blocked --fix",s:"The same editorial pass over only the articles publishing is blocked on \u2014 after a run that rewrote two of forty, this reads those two."},{t:"cmd",name:"/review --stale --fix",s:"The same pass over every article the current editor has not read yet \u2014 never reviewed, or reviewed before the editor last improved. Run it twice and the second run does nothing, so it is the safe way to catch a knowledge base up."},{t:"cmd",name:"/push --all",s:"Save the reviewed articles to Document360, as drafts."},{t:"cmd",name:"/publish --all",s:"Take those drafts live to your readers \u2014 it lists what will become visible and asks first."},{t:"dim",s:" (/catch-up --push runs the writing and the save back-to-back; going live stays a deliberate step)"},{t:"gap"},{t:"sub",s:"Whenever you need"},{t:"cmd",name:"/discover",s:"Interview your coding agent to understand the product (what it is, who it's for, the core idea, common misconceptions) \u2014 pins a product brief that grounds every article. Runs before writing a repo's docs; loops until confident."},{t:"cmd",name:"/audit",s:"Preview what has changed and identify missing documentation, without writing or publishing anything."},{t:"cmd",name:"/pull",s:"Bring Document360 down \u2014 pull edits made in the portal and import any new portal articles."},{t:"cmd",name:"/resolve",s:"Resolve conflicts when an article was edited both here and in the portal \u2014 review the diff, then keep yours, take the portal's, or skip."},{t:"cmd",name:"/comments",s:"The comments reviewers left on passages of your articles in the Document360 portal. You get a table \u2014 category, article, how many comments \u2014 and pick a number to read that article's comments in full (the highlighted passage beside what they said), then answer them or go back to the list. `a` answers everything. Each article is fixed, pushed to Document360 as an updated draft, and answered in the thread. Threads are left OPEN for the reviewer to close once they've checked the change; add --resolve to close the ones fully handled. --answered lists the ones already waiting on your reviewers; --full re-reads every article instead of only the ones that can have changed."},{t:"cmd",name:"/inbox",s:"Review and act on messages left by your coding agent."},{t:"cmd",name:"/ask <question>",s:"Ask your developers something the code cannot tell you: why a feature exists, when to use it, whether it can be undone. Costs nothing and does not stop your work."}]},{key:"assistant",label:"Assistant",rows:[{t:"text",s:"D360-Writer is your writing assistant \u2014 it does the writing, you decide what gets written and when."},{t:"text",s:"Best for large or complex monorepos: focus it on one feature, component, or set of source folders."},{t:"gap"},{t:"sub",s:"Just ask"},{t:"good",s:'"Write the documentation for the Multiple JWT feature we shipped in the latest release."'},{t:"gap"},{t:"sub",s:"Or use the pipeline"},{t:"cmd",name:"/scope",s:"Focus D360-Writer on specific source folders (monorepos)."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from its PRDs in .d360-writer/input/ + the code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview shows the plan + cost first)."},{t:"cmd",name:"/push",s:"Save the articles to Document360 as drafts. Requires an editorial review first \u2014 /review --fix."},{t:"cmd",name:"/push --preview <path>",s:"Show exactly what Document360 would receive for one article \u2014 details at the top and title removed, screenshots in place, links resolved. Sends nothing."},{t:"cmd",name:"/publish",s:"Take the drafts live to your readers, once they have been signed off."},{t:"cmd",name:"/status",s:"What stands between your work and your readers: which articles no editor has read, which break a blocking style rule, which would show placeholder text, and which are saved as drafts your readers cannot see yet. Each group names the one command that clears it. Costs nothing and calls nothing \u2014 run it before you publish, not after. --all shows every article gate by gate."},{t:"cmd",name:"/retire <path>",s:"Take an article off your readers: it stops being visible on Document360 and nothing offers to publish it again. Nothing is deleted \u2014 the article, its history and every reviewer comment stay, so a retirement is always reversible. Bare /retire lists what is worth retiring. /push puts one back."}]},{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."}]}],Mh=24;function ql(e){let t=e.filter(n=>n.t==="cmd").map(n=>n.name.length);return t.length===0?Mh:Math.min(Mh,Math.max(...t))}function vi(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 w$(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=vi(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 Fh(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 ct){n.push(`\u2500\u2500 ${o.label} \u2500\u2500`,"");let r=ql(o.rows);for(let s of o.rows)n.push(w$(s,r,100));n.push("")}return n.push("Tip: anything not starting with / goes to the agent."),n}function Vl(e,t){return qt(e,Math.max(10,Math.max(20,t)-2))}function y$(e,t,n){let o=Math.max(20,n),r=s=>Math.max(1,Vl(s,o).length);switch(e.t){case"gap":return 1;case"cmd":{let s=vi(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 Uh(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=y$(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 Wh(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 Yl(e=[],t){console.log("");let n=t?.version?{version:t.version,engineVersion:b$}:void 0;for(let o of Fh(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 k$}from"document360-engine";async function Bh(e,t){let n=t.currentUuid(),o=n?k$(n):void 0;return console.log(o?g(`
|
|
303
303
|
(conversation reset \u2014 "${o.name}" is still available via /resume)
|
|
304
|
-
`):
|
|
304
|
+
`):g(`
|
|
305
305
|
(conversation reset \u2014 agent will start fresh on the next prompt)
|
|
306
|
-
`)),{kind:"clear"}}async function
|
|
306
|
+
`)),{kind:"clear"}}async function Kl(){return{kind:"exit"}}Ti();se();import{readMcpConfig as nc,writeMcpConfig as hf}from"document360-engine";async function Ai(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(O$(),{kind:"continue"}):t==="add"?(_$(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(M$(e.slice(1)),{kind:"continue"}):(console.log(O(`Unknown /mcp subcommand: ${t}`)),console.log(g("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function O$(){let e=nc(),t=Object.keys(e.servers);if(t.length===0){console.log(g(`
|
|
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(` ${J(n)} ${
|
|
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(` ${J(n)} ${g("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?g(` [headers: ${r.join(", ")}]`):"";console.log(` ${J(n)} ${g(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function _$(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(O("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(O(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=nc(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let i={};for(let a=1;a<o.length;a++)if(o[a]==="-H"||o[a]==="--header"){let l=o[++a],d=l?.match(/^([^:=]+)[:=](.+)$/);if(!d){console.log(O(`-H expects key:value (no spaces). Got: ${l??"(nothing)"}`));return}i[d[1].trim()]=d[2].trim()}else{console.log(O(`Unexpected argument: ${o[a]}. After the URL, only -H key:value is allowed.`));return}s={type:n,url:o[0],headers:Object.keys(i).length>0?i:void 0}}r.servers[t]=s,hf(r),console.log(""),console.log(q(`\u2713 Registered "${t}" (${n})`)),console.log(G(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(g(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function M$(e){let t=e[0];if(!t){console.log(O("Usage: /mcp remove <name>"));return}let n=nc();if(!n.servers[t]){console.log(O(`No server named "${t}".`));return}delete n.servers[t],hf(n),console.log(q(`\u2713 Removed "${t}".`)),console.log(g(" Run /clear to drop it from the current session immediately."))}se();import{readFileSync as g0}from"node:fs";import{join as w0}from"node:path";import{select as y0}from"@inquirer/prompts";import{computeSyncStatus as zi,planPartitions as b0,relatedArticlePaths as k0,loadProfileMap as mm,draftPendingPaths as $0,resolveActiveProfile as Dc,unreviewedPaths as v0,styleErrorPaths as gm,publishGateVerdict as x0,publishGateLines as R0,pushArticles as C0,pushArticle as S0,PUSH_POOL_SIZE as P0,SKIP_STYLE_FLAG as T0,listArticleFiles as wm,ensureFeedbackChannel as A0,FEEDBACK_CATEGORY_NAME as hm,resolveCrossLinks as E0,applyStructureOrder as ym,orderSyncLine as bm,applyRelatedArticles as km,relatedSyncLine as $m}from"document360-engine";import{readFileSync as F$}from"node:fs";import{resolve as U$}from"node:path";import{prettyFolderName as ff}from"document360-engine";var $n=ff;function Ei(e){return e.replace(/\\/g,"/").split("/").slice(0,-1).join("/")}function rs(e){let t=e.replace(/\\/g,"/").split("/").pop()??e;return ff(t.replace(/\.md$/i,""))}function Di(e,t){try{return/^#\s+(.+)$/m.exec(F$(U$(e,t),"utf8"))?.[1]?.trim()??null}catch{return null}}import{resolveActiveProfile as W$,loadTokens as B$,isExpired as mf,listStoredSessions as H$,tokensProjectId as rc}from"document360-engine";function G$(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function oc(e,t){return t?`"${t}"`:e?G$(e):"this project"}function q$(e,t){return t?H$(e).filter(n=>{let o=rc(n);return!!o&&o!==t&&!(mf(n)&&!n.refreshToken)}):[]}function qe(e,t){try{let n=W$(e,t),o=n.project.projectId,r=oc(o,n.project.projectName),s=B$(n.name,o);if(!s){let a=q$(n.name,o);return a.length>0?{ok:!1,reason:`You're signed in to Document360 project ${a.map(d=>oc(rc(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(mf(s)&&!s.refreshToken)return{ok:!1,reason:`Your Document360 session for ${r} expired. Run /login.`};let i=rc(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 ${oc(i,s.projectName)}). Run /login and pick ${r}.`}:{ok:!0}}catch{return{ok:!0}}}import{existsSync as If,readFileSync as yc}from"node:fs";import{isAbsolute as Oi,join as _i,resolve as Mi}from"node:path";import I from"picocolors";import Ii from"string-width";import{readProjectConfig as xn,screenshotPlaceholderIds as Lf,screenshotMarkerProblemsInDocs as mv,DEFAULT_CAPTURE_DIR as Fi,DEFAULT_OUTPUT_DIR as bc,DEFAULT_DOCS_DIR as kc,resolveOutputDir as Of,migrateShotLayout as gv,reviewIsCurrent as wv,anchorPresent as yv,annotationCurrent as bv,captureLanded as kv,shotArtifacts as $v,RAW_SUBDIR as vv,ANNOTATED_SUBDIR as xv}from"document360-engine";import{createHash as sc}from"node:crypto";import{readFileSync as wf,writeFileSync as V$}from"node:fs";import{join as Y$}from"node:path";import{captureStatePath as yf}from"document360-engine";var gf={version:1,shots:{}};function K$(e){return e.replace(/^/,"").replace(/\r\n?/g,`
|
|
309
309
|
`).replace(/\n+$/,`
|
|
310
|
-
`)}function bf(e){return
|
|
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 bf(e){return sc("sha1").update(K$(e)).digest("hex").slice(0,12)}function z$(e){return sc("sha1").update(e).digest("hex").slice(0,12)}function Ni(e){try{let t=JSON.parse(wf(Y$(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 sc("sha1").update(`${o}|${r?.connection?.startUrl??""}|${i}`).digest("hex").slice(0,12)}catch{return null}}function an(e){try{let t=JSON.parse(wf(yf(e),"utf8").replace(/^/,""));return!t||typeof t!="object"||t.version!==1||!t.shots?{...gf,shots:{}}:{version:1,shots:t.shots}}catch{return{...gf,shots:{}}}}function X$(e,t){V$(yf(e),`${JSON.stringify(t,null,2)}
|
|
311
|
+
`,"utf8")}function ic(e){return e&&/data-testid|\btest-?id\b|has(?:n't| not) landed/i.test(e)?"testid":"data"}function ji(e,t,n){if(t.length===0)return;let o=an(e),r=Ni(e);for(let s of t){let i=s.specSource?bf(s.specSource):void 0;o.shots[s.id]={outcome:s.outcome,at:n,...s.reason?{reason:s.reason}:{},...s.outcome==="skipped"?{blockedBy:ic(s.reason)}:{},...i?{specHash:i}:{},...r?{envHash:r}:{}}}X$(e,o)}function ac(e,t,n,o){let r=e.shots[t];return!r||n===null||!r.specHash||r.specHash!==bf(n)&&r.specHash!==z$(n)||o&&r.envHash&&r.envHash!==o?null:r}function kf(e){let t=an(e).shots;return Object.keys(t).filter(n=>t[n].outcome==="failed").sort()}function lc(e,t,n){let o=ac(an(e),t,n,Ni(e));return!o||o.outcome==="captured"||!o.reason?null:{outcome:o.outcome,reason:o.reason}}Qo();import{existsSync as tv,readFileSync as Rf,readdirSync as Cf,writeFileSync as nv}from"node:fs";import{isAbsolute as ov,join as Sf,resolve as rv}from"node:path";import{readProjectConfig as sv,DEFAULT_CAPTURE_DIR as iv}from"document360-engine";var xf="0.2.25";function Jo(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 av=/^([ \t]*)await\s+([^\n;]+?)\.screenshot\(\{\s*path:\s*PLACEHOLDER\.saveTo\s*(?:,\s*fullPage:\s*(?:true|false)\s*)?,?\s*\}\)\s*;?[ \t]*$/m,lv=/^[ \t]*await\s+dumpAnnotations\(\s*page\s*,\s*PLACEHOLDER\s*\)\s*;?[ \t]*\r?\n?/m,Pf="(?:'([^']+)'|\"([^\"]+)\"|`([^`]+)`)",cv=new RegExp(`^page\\s*\\.\\s*locator\\(\\s*${Pf}\\s*\\)$`),Tf=e=>e[1]??e[2]??e[3]??null,uv=/^[A-Za-z_$][\w$]*$/;function dv(e,t){let o=new RegExp(`\\bconst\\s+${t}\\s*=\\s*page\\s*\\.\\s*locator\\(\\s*${Pf}\\s*\\)\\s*;`).exec(e);return o?Tf(o):null}function pv(e,t){let n=t.trim();if(n==="page")return null;let o=cv.exec(n);if(o){let r=Tf(o);return r?{selector:r}:{unresolved:!0}}if(uv.test(n)){let r=dv(e,n);return r?{selector:r}:{unresolved:!0}}return{unresolved:!0}}function Af(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=av.exec(e);if(!n)return null;let[o,r="",s=""]=n,i=pv(e,s);if(i===null)return null;if("unresolved"in i)return{unresolved:s.trim()};let a=/^([ \t]*)saveTo:\s*.+,[ \t]*$/m.exec(e);if(!a)return null;let l=i.selector.includes("'")?'"':"'",d=e.replace(a[0],`${a[0]}
|
|
312
|
+
${a[1]??" "}clipTo: ${l}${i.selector}${l},`);return d=d.replace(o,`${r}await captureShot(page, PLACEHOLDER);`),d=d.replace(lv,""),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'/,(m,w)=>`import {${w.replace(/\s*$/,"")}, captureShot } from 'document360-capture/helpers'`)),{next:d,selector:i.selector}}function hv(e){try{return Cf(e).filter(t=>t.endsWith(".spec.ts")).some(t=>{try{let n=Af(Rf(Sf(e,t),"utf8"));return n!==null&&!("unresolved"in n)}catch{return!1}})}catch{return!1}}function fv(e){let t=sv(e)?.captureDir??iv;return ov(t)?t:rv(e,t)}function Ef(e,t){let n={migrated:[],skipped:[]},o=fv(e);if(!tv(o))return n;let r=t?.captureVersion===void 0?ut():t.captureVersion;if(!Jo(r,xf))return hv(o)?{...n,heldBackForCapture:{installed:r,required:xf}}:n;let s;try{s=Cf(o).filter(i=>i.endsWith(".spec.ts"))}catch{return n}for(let i of s.sort()){let a=i.slice(0,-8),l=Sf(o,i);try{let d=Rf(l,"utf8"),m=Af(d);if(m===null)continue;if("unresolved"in m){n.skipped.push({id:a,receiver:m.unresolved});continue}nv(l,m.next,"utf8"),n.migrated.push(a)}catch{}}return n}function Df(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 Vt(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}Qo();var _f=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Nf(e){let t=e.includes("--detail")||e.includes("-d"),n=e.find(o=>o!=="--detail"&&o!=="-d");return{mode:"list",scope:n?_f(n):void 0,...t?{detail:!0}:{}}}function
|
|
315
|
-
`):null}function oo(e,t){let n=xn(e)?.captureDir??
|
|
316
|
-
`))||o.push(r+1));return o}function
|
|
314
|
+
`)}function Re(e,t,n){return`${e}${n?` ${n}`:""}${t?` ${t}`:""}`}function Vt(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}Qo();var _f=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Nf(e){let t=e.includes("--detail")||e.includes("-d"),n=e.find(o=>o!=="--detail"&&o!=="-d");return{mode:"list",scope:n?_f(n):void 0,...t?{detail:!0}:{}}}function ss(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 Nf(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 Nf(o.slice(1));let r=o[0];return r?r==="--all"?{mode:"all",setup:n}:/[\\/]/.test(r)||r.endsWith(".md")?{mode:"scope",scope:_f(r),setup:n}:{mode:"single",id:r}:{mode:"list",picker:!0}}function _e(e,t,n){let o=xn(e),r=o?.captureDir??Fi,s=o?.outputDir??bc,i=(w,k)=>Oi(w)?_i(w,k):Mi(e,w,k),a=an(e),l=n?.captureVersion===void 0?ut():n.captureVersion,d=Jo(l,Wf),m=Ni(e);return Lf(e,{scope:t}).map(({id:w,file:k})=>{let S=i(r,`${w}.spec.ts`),v=null;if(If(S))try{v=yc(S,"utf8")}catch{}let C=Of(e,s),A=$v(C,w),D=bv(A),L=kv(A),B=v===null?null:ac(a,w,v,m),M=a.shots[w]?.review,X=D&&wv(M,A.annotatedMtimeMs)?M:void 0,z=v!==null&&Sv(v),de=D&&X?.verdict==="ok"?"verified":D&&X?.verdict==="rejected"?"rejected":D?"annotated":L?"captured":v===null?"placeholder":z||B?.outcome==="skipped"?"blocked":B?.outcome==="failed"?"broken":"spec",ye=v===null?void 0:Ff(v),Se=z?Tv(v):B?.reason,ve=z?"testid":B?.outcome==="skipped"?ic(B.reason):void 0,fe=v===null?[]:Pv(e,v);return{id:w,file:k,state:de,...ye?{mutates:ye.mutates,...ye.declared?{}:{undeclared:!0}}:{},...v!==null&&dc(v).length>0?{unguardedWaits:dc(v)}:{},...v!==null&&uc(v).length>0?{unverifiedForce:uc(v)}:{},...v!==null&&pc(v).length>0?{handRolled:pc(v)}:{},...v!==null&&fc(v).length>0?{stalePause:fc(v)}:{},...v!==null&&d&&hc(v).length>0?{bareGoto:hc(v)}:{},...fe.length>0?{staleAnchor:fe}:{},...de==="blocked"||de==="broken"?{...Se?{reason:Se}:{},...ve?{blockedBy:ve}:{}}:{},...de==="rejected"?{...X?.reason?{reason:X.reason}:{},...X?.repaired?{repaired:!0}:{}}:{}}})}function Rv(e){let t=xn(e)?.outputDir??bc;return gv(Of(e,t))}function no(e){let t=Rv(e),n=xn(e)?.outputDir??bc,o=[];t>0&&o.push(`\u2195 Tidied ${t} screenshot file${t===1?"":"s"} into ${n}/{${vv},${xv}} \u2014 annotated/ is what publishes, raw/ is the pre-annotation intermediate.`);let r=Df(Ef(e));return r&&o.push(r),o.length>0?o.join(`
|
|
315
|
+
`):null}function oo(e,t){let n=xn(e)?.captureDir??Fi,o=Oi(n)?_i(n,`${t}.spec.ts`):Mi(e,n,`${t}.spec.ts`);try{return yc(o,"utf8")}catch{return null}}function Mf(e,t){let n=xn(e)?.captureDir??Fi;return If(Oi(n)?_i(n,`${t}.spec.ts`):Mi(e,n,`${t}.spec.ts`))}function Cv(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 Ff(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=Cv(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 Sv(e){return/(^|\n)\s*test\.skip\s*\(\s*['"`]/.test(e)}function Uf(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 Pv(e,t){let n=[];for(let o of Uf(t))yv(e,o.file,o.anchor)===!1&&n.push(o.testid??o.file??"unnamed request");return[...new Set(n)]}function Tv(e){let{testid:t,file:n}=Uf(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 is(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 uc(e,t=10){let n=is(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 dc(e){let t=[],n=is(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 pc(e){let t=[];for(let[n,o]of is(e).entries())(/\.screenshot\s*\(/.test(o)||/\bdumpAnnotations\s*\(/.test(o))&&t.push(n+1);return t}var Wf="0.2.28";function hc(e){let t=[];for(let[n,o]of is(e).entries())/\.goto\s*\(/.test(o)&&t.push(n+1);return t}function fc(e,t=6){let n=is(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 Dv={placeholder:"\u25CB",spec:"\u25D0",blocked:"\u2298",broken:"\u2717",captured:"\u25CF",annotated:"\u25C8",verified:"\u2714",rejected:"\u2691"},Nv={placeholder:I.gray,spec:I.yellow,blocked:I.cyan,broken:I.red,captured:I.yellow,annotated:I.blue,verified:I.green,rejected:I.magenta},jv=` ${I.green("\u2714 verified")} ${I.blue("\u25C8 to verify")} ${I.yellow("\u25CF to annotate")} ${I.yellow("\u25D0 ready")} ${I.magenta("\u2691 rejected")} ${I.cyan("\u2298 blocked")} ${I.red("\u2717 broken")} ${I.gray("\u25CB to spec")}`;function ee(e,t=n=>n){return`${t(e)} `}function er(e){return e.replace(/\s+/g," ").trim().replace(/^Prerequisites? not met[:—-]?\s*/i,"")}function Bi(e){let t=er(e),n=/^(.*?[a-z0-9)"'”’])\.(?:\s|$)/i.exec(t);return(n?n[1]:t).trim()}function ss(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=Bi(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 qf(e){let t=ss(e);if(t.length===0)return[];let n=t.filter(s=>s.blockedBy==="data"),o=t.filter(s=>s.blockedBy==="testid"),r=[""];if(n.length>0){let s=n.reduce((a,l)=>a+l.ids.length,0);r.push(` ${I.bold("Stage this data")} ${I.gray(`\u2014 unblocks ${s} shot${s===1?"":"s"} in ${n.length} action${n.length===1?"":"s"}`)}`);let i=8;for(let a of n.slice(0,i)){let l=qt(a.reason,86);r.push(` ${I.cyan(vn(`${a.ids.length}\xD7`,4))} ${l[0]??""}`);for(let g of l.slice(1))r.push(` ${g}`);let d=a.ids.slice(0,4).join(" \xB7 ");r.push(I.gray(` ${d}${a.ids.length>4?` \xB7 +${a.ids.length-4} more`:""}`))}n.length>i&&r.push(I.gray(` \u2026 ${n.length-i} more staging action${n.length-i===1?"":"s"} \u2014 /screenshot list --detail`))}if(o.length>0){let s=o.reduce((i,a)=>i+a.ids.length,0);r.push(` ${ee("\u2298",I.cyan)}${s} shot${s===1?"":"s"} need${s===1?"s":""} a data-testid from your developers \u2014 ${I.bold("/screenshot checklist")} builds the hand-off.`)}return r}function kc(e){if(e.length===0)return[];let t=e.slice(0,6),n=e.length;return["",` ${ee("\u26A0",I.yellow)}${n} screenshot marker${n===1?"":"s"} will be ignored \u2014 ${n===1?"it is":"they are"} not shaped the way the publish step needs`+I.gray(`, so ${n===1?"that picture":"those pictures"} would never be taken`),...t.map(o=>I.gray(` ${o.file}:${o.line} \u2014 ${o.reason}`)),...n>t.length?[I.gray(` \u2026and ${n-t.length} more`)]:[],I.gray(" Usually a reviewer comment wrapped around it. A marker must start its own line and carry an id:.")]}function Vf(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=["",` ${ee("\u26A0",I.yellow)}${r} selector request${r===1?"":"s"} quote${r===1?"s":""} source code that has since changed`+I.gray(" \u2014 your developers would go looking for something that isn't there any more"),I.gray(` Refresh the hand-off before sending it: ${I.bold("/screenshot checklist")}`)];return t&&s.push(I.gray(` ${o.slice(0,8).join(" \xB7 ")}${r>8?` \xB7 +${r-8} more`:""}`)),s}function Yf(e,t,n){let o=e.filter(g=>(g.unguardedWaits?.length??0)>0),r=e.filter(g=>g.undeclared),s=e.filter(g=>(g.handRolled?.length??0)>0),i=e.filter(g=>(g.stalePause?.length??0)>0),a=e.filter(g=>(g.bareGoto?.length??0)>0);if(o.length===0&&r.length===0&&s.length===0&&i.length===0&&a.length===0)return[];let l=["",` ${ee("\u26A0",I.yellow)}Some specs were written before later reliability fixes:`],d=(g,f)=>` ${g.slice(0,8).map(f).join(" \xB7 ")}${g.length>8?` \xB7 +${g.length-8} more`:""}`;if(o.length>0){let g=o.length;l.push(I.gray(` ${g} crash${g===1?"es":""} instead of telling you what to stage when the data ${g===1?"it needs":"they need"} is missing`)),t&&l.push(I.gray(d(o,f=>`${f.id}:${f.unguardedWaits.join(",")}`)))}if(a.length>0){let g=a.length;l.push(I.gray(` ${g} open${g===1?"s":""} pages the slow way, so ${g===1?"it stalls":"they stall"} for a minute and give up when several shots run at once`)),t&&l.push(I.gray(d(a,f=>`${f.id}:${f.bareGoto.join(",")}`)))}if(i.length>0){let g=i.length;l.push(I.gray(` ${g} decide${g===1?"s":""} "the data is missing" from a fixed pause, so data you HAVE staged can read as absent`)),t&&l.push(I.gray(d(i,f=>`${f.id}:${f.stalePause.join(",")}`)))}if(s.length>0){let g=s.length;l.push(I.gray(` ${g} take${g===1?"s":""} ${g===1?"its":"their"} own screenshot instead of the one call that positions the callouts too \u2014 on a cropped shot the numbers land in the wrong places, and nothing reports it`)),t&&l.push(I.gray(d(s,f=>`${f.id}:${f.handRolled.join(",")}`)))}if(r.length>0){let g=r.length,f=r.filter(x=>x.mutates).length;l.push(I.gray(` ${g} do${g===1?"es":""} not say whether ${g===1?"it changes":"they change"} data in your app`+(f>0?`, so ${f===1?"one is":`${f} are`} left out of bulk runs to be safe`:""))),t&&l.push(I.gray(d(r,x=>x.id)))}return n?.commandInLead||l.push(I.gray(` Re-write them all with the current rules: ${I.bold("/screenshot author --all")}`)),l}function Kf(e){let t=e.filter(n=>(n.unverifiedForce?.length??0)>0);return t.length===0?[]:["",` ${ee("\u26A0",I.red)}${t.length} spec${t.length===1?"":"s"} force-click past Playwright's safety checks without asserting the result`+I.gray(" \u2014 if the click lands on nothing, the shot photographs the unchanged screen"),I.gray(` ${t.slice(0,6).map(n=>`${n.id}:${n.unverifiedForce.join(",")}`).join(" \xB7 ")}${t.length>6?` \xB7 +${t.length-6} more`:""}`),I.gray(` Re-author to check what the click did: ${I.bold("/screenshot author <id>")}`)]}var Ii=(e,t)=>e.length>=t?e:e+" ".repeat(t-e.length),vn=(e,t)=>e.length>=t?e:" ".repeat(t-e.length)+e;function zf(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 Iv=new Set(["and","or","of","the","to","a","an","in","on","for","with","vs"]),Lv=new Set(["ai","api","cli","ui","ux","url","id","http","https","json","xml","sdk","csv","pdf","oauth","sso","mfa","io","faq"]);function Ov(e){return e.replace(/[-_]+/g," ").trim().split(/\s+/).filter(Boolean).map((n,o)=>{let r=n.toLowerCase();return Lv.has(r)?r.toUpperCase():o>0&&Iv.has(r)?r:r.charAt(0).toUpperCase()+r.slice(1)}).join(" ")}function hc(e){if(!e)return{num:"",name:"(docs root)"};let t=/^(\d+)[-_](.+)$/.exec(e);return{num:t?t[1]:"",name:Ov(t?t[2]:e)}}function _v(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).pop()??e}function jf(e,t,n){let o=t>0?Math.round(e/t*n):0;return I.green("\u2588".repeat(o))+I.gray("\u2591".repeat(Math.max(0,n-o)))}function Mv(e,t){let n=t>0?Math.round(e/t*100):0,o=vn(`${n}%`,4);return n===100?I.green(o):n>0?I.yellow(o):I.gray(o)}function Xf(e,t){let n=new Map;for(let o of e){let r=zf(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 $c(e,t){let n=A=>e.filter(D=>D.state===A).length,o=n("captured"),r=n("placeholder"),s=n("spec"),i=n("annotated"),a=n("blocked"),l=n("broken"),d=n("rejected"),g=e.filter(A=>A.state==="spec"&&A.mutates).length,f=s>g,x=e.filter(A=>(A.unguardedWaits?.length??0)>0||(A.bareGoto?.length??0)>0).length,P=e.filter(A=>(A.stalePause?.length??0)>0||(A.handRolled?.length??0)>0).length,$=s>0||a>0||l>0,C=(A,D="")=>Re(A,D,t);return o>0?{key:"annotate",cmd:C("/screenshot annotate")}:r>0?{key:"toSpec",cmd:t?`/screenshot author ${t}`:"/screenshot author --all"}:x>0&&$?{key:"crashy",cmd:t?`/screenshot author ${t}`:"/screenshot author --all"}:P>0&&$?{key:"wrongOutput",cmd:t?`/screenshot author ${t}`:"/screenshot author --all"}:s>0&&(f||i===0)?{key:"ready",cmd:C("/screenshot capture")}:i>0&&s>0?{key:"verify",cmd:C("/screenshot verify")}:a>0?{key:"blocked",cmd:C("/screenshot capture","--blocked")}:l>0?{key:"broken",cmd:`/screenshot ${e.find(A=>A.state==="broken").id}`}:i>0?{key:"verify",cmd:C("/screenshot verify")}:d>0?{key:"rejected",cmd:C("/screenshot capture","--failed")}:{key:"done",cmd:t?`/push ${t}`:"/push"}}function Fv(e,t,n=[]){let o=(te,je)=>te.filter(Ne=>Ne.state===je).length,r=e.length,s=o(e,"verified"),i=o(e,"annotated"),a=o(e,"captured"),l=o(e,"rejected"),d=o(e,"spec"),g=o(e,"blocked"),f=o(e,"broken"),x=o(e,"placeholder"),P=new Set(e.map(te=>te.file)).size,$=Xf(e,t),C=[];C.push(` ${I.bold("Screenshots")} ${I.green(`${s}/${r} verified`)} ${I.gray("\xB7")} ${i>0?I.blue(`${i} to verify`):I.gray("0 to verify")}`+(a>0?` ${I.gray("\xB7")} ${I.yellow(`${a} to annotate`)}`:"")+(l>0?` ${I.gray("\xB7")} ${I.magenta(`${l} rejected`)}`:"")+` ${I.gray("\xB7")} ${d>0?I.yellow(`${d} ready`):I.gray("0 ready")}`+(g>0?` ${I.gray("\xB7")} ${I.cyan(`${g} blocked`)}`:"")+(f>0?` ${I.gray("\xB7")} ${I.red(`${f} broken`)}`:"")+` ${I.gray("\xB7")} ${x>0?I.red(`${x} to spec`):I.gray("0 to spec")} `+I.gray(`across ${P} article${P===1?"":"s"}`));let A=r>0?Math.round(s/r*100):0;C.push(` [${jf(s,r,32)}] ${I.bold(`${A}%`)}`),C.push("");let D=$.map(([te])=>hc(te)),L=Math.min(32,Math.max(7,...D.map(te=>te.name.length))),B=te=>te.length>L?`${te.slice(0,L-1)}\u2026`:Ii(te,L),M=[...a>0?[{head:"To annotate",w:11,state:"captured",color:I.yellow}]:[],...i>0?[{head:"To verify",w:9,state:"annotated",color:I.blue}]:[],...l>0?[{head:"Rejected",w:8,state:"rejected",color:I.magenta}]:[],{head:"Ready",w:5,state:"spec",color:I.yellow},...g>0?[{head:"Blocked",w:7,state:"blocked",color:I.cyan}]:[],...f>0?[{head:"Broken",w:6,state:"broken",color:I.red}]:[],{head:"To spec",w:7,state:"placeholder",color:I.red}];C.push(I.gray(` ${Ii("#",2)} ${Ii("Chapter",L)} ${vn("Verified",8)} ${M.map(te=>vn(te.head,te.w)).join(" ")} Progress`));for(let[te,[,je]]of $.entries()){let Ne=o(je,"verified"),Ze=je.length,{num:bo,name:pn}=D[te],At=Ne===Ze,gt=B(pn),Tr=M.map(et=>{let ko=o(je,et.state);return ko>0?et.color(vn(String(ko),et.w)):I.gray(vn("\u2014",et.w))}).join(" ");C.push(` ${I.cyan(Ii(bo,2))} ${At?I.green(gt):Ne>0?gt:I.gray(gt)} ${At?I.green(vn(`${Ne}/${Ze}`,8)):vn(`${Ne}/${Ze}`,8)} ${Tr} ${jf(Ne,Ze,10)} ${Mv(Ne,Ze)}`)}C.push("");let X=f>0?` ${I.gray("\xB7")} ${f} spec${f===1?"":"s"} broken \u2014 ${I.bold(`/screenshot ${e.find(te=>te.state==="broken").id}`)} re-authors ${f===1?"it":"the first"}`:"",z=e.filter(te=>te.state==="spec"&&te.mutates).length,de=d>z,ye=e.filter(te=>(te.unguardedWaits?.length??0)>0||(te.bareGoto?.length??0)>0).length,Ce=e.filter(te=>(te.stalePause?.length??0)>0||(te.handRolled?.length??0)>0).length,ve=d>0||g>0||f>0,fe=!1,Z=$c(e).key;if(Z==="annotate")C.push(` ${ee("\u25C8",I.blue)}${a} shot${a===1?"":"s"} taken but not drawn on \u2014 run ${I.bold("/screenshot annotate")}`+I.gray(` \u2014 no browser, seconds; the callouts are what make ${a===1?"it":"them"} publishable`)+X);else if(Z==="toSpec")C.push(` ${ee("\u2192",I.yellow)}${x} placeholder${x===1?"":"s"} still need a spec \u2014 run ${I.bold("/screenshot author --all")}${X}`);else if(Z==="crashy")fe=!0,C.push(` ${ee("\u2192",I.yellow)}${ye} spec${ye===1?"":"s"} would crash mid-run \u2014 re-write ${ye===1?"it":"them"} first: ${I.bold("/screenshot author --all")}`+I.gray(` \xB7 then ${I.bold("/screenshot capture")} (no browser time wasted on ${ye===1?"a shot":"shots"} that can't finish)`)+X);else if(Z==="wrongOutput")fe=!0,C.push(` ${ee("\u2192",I.yellow)}${Ce} spec${Ce===1?"":"s"} would shoot the wrong thing \u2014 re-write ${Ce===1?"it":"them"} first: ${I.bold("/screenshot author --all")}`+I.gray(` \xB7 then ${I.bold("/screenshot capture")} (a false skip or a misplaced callout costs the same browser time as a good shot)`)+X);else if(Z==="ready"){let te=z>0?I.gray(` \u2014 ${d-z} in one go; ${z} write${z===1?"s":""} real data and run${z===1?"s":""} one at a time`):"";C.push(` ${ee("\u2192",I.yellow)}${d} spec${d===1?"":"s"} ready to capture \u2014 run ${I.bold("/screenshot capture")}${te}${X}`)}else if(Z==="verify"&&d>0)C.push(` ${ee("\u2192",I.blue)}${i} shot${i===1?"":"s"} awaiting verification \u2014 run ${I.bold("/screenshot verify")}`+I.gray(" \u2014 no browser needed")+I.gray(` \xB7 ${d} ready spec${d===1?"":"s"} write real data, so ${d===1?"it runs":"each runs"} only when named: /screenshot capture <id>`)+X);else if(Z==="blocked")C.push(` ${ee("\u2192",I.cyan)}${g} shot${g===1?"":"s"} blocked \u2014 stage the data below, then ${I.bold("/screenshot capture --blocked")}${X}`);else if(Z==="broken")C.push(` ${ee("\u2192",I.red)}${f} spec${f===1?"":"s"} broken \u2014 ${I.bold(`/screenshot ${e.find(te=>te.state==="broken").id}`)} re-authors ${f===1?"it":"the first"} (re-capturing fails the same way)`);else if(Z==="verify")C.push(` ${ee("\u2192",I.blue)}${i} shot${i===1?"":"s"} awaiting verification \u2014 run ${I.bold("/screenshot verify")}`+I.gray(" \u2014 it checks each picture against what its article needs (no browser, no re-capture)"));else if(Z==="rejected"){let te=e.filter(je=>je.state==="rejected"&&je.repaired).length;C.push(` ${ee("\u2691",I.magenta)}${l} shot${l===1?"":"s"} failed review \u2014 `+(te>0?`${te} spec${te===1?"":"s"} already repaired; re-capture with ${I.bold("/screenshot capture --failed")}`:`see the reasons below, then ${I.bold("/screenshot capture --failed")}`))}else C.push(` ${ee("\u2713",I.green)}all ${r} verified \u2014 ${I.bold("/push")} embeds them in the articles`);if(s>0&&s<r){let te=$.filter(([,je])=>je.every(Ne=>Ne.state!=="verified")).map(([je])=>{let{num:Ne,name:Ze}=hc(je);return Ne?`${Ne} ${Ze}`:Ze});te.length>0&&C.push(I.gray(` Furthest behind: ${te.slice(0,5).join(" \xB7 ")}${te.length>5?" \u2026":""} (0% verified)`))}return C.push(...qf(e),...Kf(e),...Yf(e,!1,{commandInLead:fe}),...Vf(e,!1),...kc(n)),C.push(""),C.push(I.gray(" Drill in: /screenshot list <chapter#> \xB7 /screenshot list --detail (all)")),C}function Uv(e,t,n,o=[]){let r=new Set(e.map(d=>d.file)),s=e.filter(d=>d.state==="verified").length,i=e.filter(d=>d.state==="annotated").length,a=e.filter(d=>d.state==="captured").length,l=[` ${I.bold("Screenshots")}: ${e.length} placeholder${e.length===1?"":"s"} across ${r.size} article${r.size===1?"":"s"} \xB7 ${I.green(`${s} verified`)}${i>0?I.blue(` \xB7 ${i} to verify`):""}${a>0?I.yellow(` \xB7 ${a} to annotate`):""}${n?I.gray(` \xB7 scope ${n}`):""}`,""];for(let[d,g]of Xf(e,t)){let f=g.filter(A=>A.state==="verified").length,{num:x,name:P}=hc(d),$=x?`${x} \xB7 ${P}`:P;l.push(` ${I.bold($)} ${I.gray(`(${f}/${g.length})`)}`);let C=new Map;for(let A of g){let D=_v(A.file),L=C.get(D)??[];C.has(D)||C.set(D,L),L.push(A)}for(let A of[...C.keys()].sort()){l.push(I.gray(` ${A}`));for(let D of C.get(A)){let L=Nv[D.state];if(l.push(` ${ee(Dv[D.state],L)}${L(D.id)}`),(D.state==="blocked"||D.state==="broken"||D.state==="rejected")&&D.reason){for(let B of qt(er(D.reason),84))l.push(I.gray(` ${B}`));D.state==="rejected"&&l.push(I.gray(` ${D.repaired?"spec repaired \u2014 re-capture to confirm":"spec not yet repaired"}`))}}}}return l.push(...qf(e),...Kf(e),...Yf(e,!0),...Vf(e,!0),...kc(o)),l.push("",jv),l}function Hi(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.",...kc(o)];let r=t?.docsDir??yc;return t?.detail||n?Uv(e,r,n,o):Fv(e,r,o)}function vc(e,t){if(!t||!/^\d+$/.test(t))return t;let n=xn(e)?.docsDir??yc,o=String(Number(t));for(let{file:r}of Lf(e)){let s=zf(r,n),i=/^(\d+)/.exec(s);if(i&&String(Number(i[1]))===o)return s}return t}function Qf(e,t){let r=e.map(a=>" ".repeat(a.depth)+a.label),s=Math.max(0,...e.map((a,l)=>a.note?ji(r[l]):0)),i=Math.min(s,Math.max(0,t-2-24));return e.map((a,l)=>{let d=r[l];if(!a.note)return{head:d,note:""};let g=Math.max(2,i+2-ji(d)),f=a.note.trim(),x=t-ji(d)-g;return{head:d+" ".repeat(g),note:x>1&&ji(f)>x?`${f.slice(0,x-1)}\u2026`:f}})}function Wv(e){let t=e.replace(/\\/g,"/").split("/").filter(Boolean),n=t.pop()??e;return{category:t.pop()??"(docs root)",article:n}}function Zo(e,t,n){let o=new Map;for(let s of t){let{category:i,article:a}=Wv(s.file),l=o.get(i)??new Map;o.set(i,l);let d=l.get(a)??[];l.set(a,d),d.push(s)}let r=s=>n!=="capture"||!s.mutates;for(let s of[...o.keys()].sort()){let i=o.get(s),a=[...i.values()].flat().filter(r).map(d=>d.id),l=a.length>0;l&&e.push({kind:"category",action:n,label:`${s} (${a.length})`,ids:a,depth:1});for(let d of[...i.keys()].sort()){let g=i.get(d),f=g.filter(r).map($=>$.id),x=f.length>0;x&&e.push({kind:"article",action:n,label:`${d} (${f.length})`,ids:f,depth:l?2:1});let P=(l?1:0)+(x?1:0)+1;for(let $ of g){let C=n==="capture"&&$.mutates?" \u26A0 creates real data \u2014 runs only alone":void 0;e.push({kind:"shot",action:n,label:$.id,ids:[$.id],depth:P,...C?{note:C}:{}})}}}}function ac(e){return e?er(e):""}function xc(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 ${ac(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 ${ac(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 ${ac(i.reason)}`})}}function Jf(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}),Zo(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}),Zo(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}),Zo(o,s,"annotate"),xc(o,e.filter(i=>i.state==="blocked"),e.filter(i=>i.state==="broken"),e.filter(i=>i.state==="rejected")),o}var fc=["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=>Bf(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.",
|
|
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 $c(e,t){let n=m=>`line${m.length===1?"":"s"} ${m.join(", ")}`,o=[],r=t?.captureVersion===void 0?ut():t.captureVersion,s=Jo(r,Wf)?hc(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=dc(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=pc(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=fc(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=uc(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 Bf(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 Hf(e){return(e??"").trim().replace(/[.\s]+$/,"")}function Gf(e,t){let n=xn(e)?.captureDir??Fi,o=Oi(n)?_i(n,`${t}.spec.ts`):Mi(e,n,`${t}.spec.ts`);try{return Ff(yc(o,"utf8"))}catch{return{mutates:!1,declared:!1}}}var Av=["annotated","verified","rejected"],Ev=e=>Av.includes(e);function Dv(e){return[...new Set(e.filter(t=>Ev(t.state)).map(t=>t.file))].sort()}function Ui(e,t){let n=Dv(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 Wi(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[`${ee("\u26A0",I.yellow)}${n.length} screenshot${r?" has":"s have"} been taken but the callouts aren't drawn on yet, so ${r?"it has":"they have"} no picture to publish:`,...n.map(s=>` ${I.yellow(s.id.padEnd(o))}`),` Publishing without ${r?"it":"them"}. Finish ${r?"it":"them"} first: ${I.bold(Re("/screenshot annotate","",t))}`].join(`
|
|
319
|
+
`)}function Bi(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[`${ee("\u26A0",I.yellow)}${t.length} screenshot${t.length===1?"":"s"} failed verification:`,...t.map(o=>` ${I.magenta(o.id.padEnd(n))} ${I.gray(er(o.reason??"no reason recorded"))}`),` Publishing anyway. Fix + re-capture: ${I.bold("/screenshot capture --failed")}`].join(`
|
|
320
|
+
`)}var Nv={placeholder:"\u25CB",spec:"\u25D0",blocked:"\u2298",broken:"\u2717",captured:"\u25CF",annotated:"\u25C8",verified:"\u2714",rejected:"\u2691"},jv={placeholder:I.gray,spec:I.yellow,blocked:I.cyan,broken:I.red,captured:I.yellow,annotated:I.blue,verified:I.green,rejected:I.magenta},Iv=` ${I.green("\u2714 verified")} ${I.blue("\u25C8 to verify")} ${I.yellow("\u25CF to annotate")} ${I.yellow("\u25D0 ready")} ${I.magenta("\u2691 rejected")} ${I.cyan("\u2298 blocked")} ${I.red("\u2717 broken")} ${I.gray("\u25CB to spec")}`;function ee(e,t=n=>n){return`${t(e)} `}function er(e){return e.replace(/\s+/g," ").trim().replace(/^Prerequisites? not met[:—-]?\s*/i,"")}function Hi(e){let t=er(e),n=/^(.*?[a-z0-9)"'”’])\.(?:\s|$)/i.exec(t);return(n?n[1]:t).trim()}function as(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=Hi(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 qf(e){let t=as(e);if(t.length===0)return[];let n=t.filter(s=>s.blockedBy==="data"),o=t.filter(s=>s.blockedBy==="testid"),r=[""];if(n.length>0){let s=n.reduce((a,l)=>a+l.ids.length,0);r.push(` ${I.bold("Stage this data")} ${I.gray(`\u2014 unblocks ${s} shot${s===1?"":"s"} in ${n.length} action${n.length===1?"":"s"}`)}`);let i=8;for(let a of n.slice(0,i)){let l=qt(a.reason,86);r.push(` ${I.cyan(vn(`${a.ids.length}\xD7`,4))} ${l[0]??""}`);for(let m of l.slice(1))r.push(` ${m}`);let d=a.ids.slice(0,4).join(" \xB7 ");r.push(I.gray(` ${d}${a.ids.length>4?` \xB7 +${a.ids.length-4} more`:""}`))}n.length>i&&r.push(I.gray(` \u2026 ${n.length-i} more staging action${n.length-i===1?"":"s"} \u2014 /screenshot list --detail`))}if(o.length>0){let s=o.reduce((i,a)=>i+a.ids.length,0);r.push(` ${ee("\u2298",I.cyan)}${s} shot${s===1?"":"s"} need${s===1?"s":""} a data-testid from your developers \u2014 ${I.bold("/screenshot checklist")} builds the hand-off.`)}return r}function vc(e){if(e.length===0)return[];let t=e.slice(0,6),n=e.length;return["",` ${ee("\u26A0",I.yellow)}${n} screenshot marker${n===1?"":"s"} will be ignored \u2014 ${n===1?"it is":"they are"} not shaped the way the publish step needs`+I.gray(`, so ${n===1?"that picture":"those pictures"} would never be taken`),...t.map(o=>I.gray(` ${o.file}:${o.line} \u2014 ${o.reason}`)),...n>t.length?[I.gray(` \u2026and ${n-t.length} more`)]:[],I.gray(" Usually a reviewer comment wrapped around it. A marker must start its own line and carry an id:.")]}function Vf(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=["",` ${ee("\u26A0",I.yellow)}${r} selector request${r===1?"":"s"} quote${r===1?"s":""} source code that has since changed`+I.gray(" \u2014 your developers would go looking for something that isn't there any more"),I.gray(` Refresh the hand-off before sending it: ${I.bold("/screenshot checklist")}`)];return t&&s.push(I.gray(` ${o.slice(0,8).join(" \xB7 ")}${r>8?` \xB7 +${r-8} more`:""}`)),s}function Yf(e,t,n){let o=e.filter(m=>(m.unguardedWaits?.length??0)>0),r=e.filter(m=>m.undeclared),s=e.filter(m=>(m.handRolled?.length??0)>0),i=e.filter(m=>(m.stalePause?.length??0)>0),a=e.filter(m=>(m.bareGoto?.length??0)>0);if(o.length===0&&r.length===0&&s.length===0&&i.length===0&&a.length===0)return[];let l=["",` ${ee("\u26A0",I.yellow)}Some specs were written before later reliability fixes:`],d=(m,w)=>` ${m.slice(0,8).map(w).join(" \xB7 ")}${m.length>8?` \xB7 +${m.length-8} more`:""}`;if(o.length>0){let m=o.length;l.push(I.gray(` ${m} crash${m===1?"es":""} instead of telling you what to stage when the data ${m===1?"it needs":"they need"} is missing`)),t&&l.push(I.gray(d(o,w=>`${w.id}:${w.unguardedWaits.join(",")}`)))}if(a.length>0){let m=a.length;l.push(I.gray(` ${m} open${m===1?"s":""} pages the slow way, so ${m===1?"it stalls":"they stall"} for a minute and give up when several shots run at once`)),t&&l.push(I.gray(d(a,w=>`${w.id}:${w.bareGoto.join(",")}`)))}if(i.length>0){let m=i.length;l.push(I.gray(` ${m} decide${m===1?"s":""} "the data is missing" from a fixed pause, so data you HAVE staged can read as absent`)),t&&l.push(I.gray(d(i,w=>`${w.id}:${w.stalePause.join(",")}`)))}if(s.length>0){let m=s.length;l.push(I.gray(` ${m} take${m===1?"s":""} ${m===1?"its":"their"} own screenshot instead of the one call that positions the callouts too \u2014 on a cropped shot the numbers land in the wrong places, and nothing reports it`)),t&&l.push(I.gray(d(s,w=>`${w.id}:${w.handRolled.join(",")}`)))}if(r.length>0){let m=r.length,w=r.filter(k=>k.mutates).length;l.push(I.gray(` ${m} do${m===1?"es":""} not say whether ${m===1?"it changes":"they change"} data in your app`+(w>0?`, so ${w===1?"one is":`${w} are`} left out of bulk runs to be safe`:""))),t&&l.push(I.gray(d(r,k=>k.id)))}return n?.commandInLead||l.push(I.gray(` Re-write them all with the current rules: ${I.bold("/screenshot author --all")}`)),l}function Kf(e){let t=e.filter(n=>(n.unverifiedForce?.length??0)>0);return t.length===0?[]:["",` ${ee("\u26A0",I.red)}${t.length} spec${t.length===1?"":"s"} force-click past Playwright's safety checks without asserting the result`+I.gray(" \u2014 if the click lands on nothing, the shot photographs the unchanged screen"),I.gray(` ${t.slice(0,6).map(n=>`${n.id}:${n.unverifiedForce.join(",")}`).join(" \xB7 ")}${t.length>6?` \xB7 +${t.length-6} more`:""}`),I.gray(` Re-author to check what the click did: ${I.bold("/screenshot author <id>")}`)]}var Li=(e,t)=>e.length>=t?e:e+" ".repeat(t-e.length),vn=(e,t)=>e.length>=t?e:" ".repeat(t-e.length)+e;function zf(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 Lv=new Set(["and","or","of","the","to","a","an","in","on","for","with","vs"]),Ov=new Set(["ai","api","cli","ui","ux","url","id","http","https","json","xml","sdk","csv","pdf","oauth","sso","mfa","io","faq"]);function _v(e){return e.replace(/[-_]+/g," ").trim().split(/\s+/).filter(Boolean).map((n,o)=>{let r=n.toLowerCase();return Ov.has(r)?r.toUpperCase():o>0&&Lv.has(r)?r:r.charAt(0).toUpperCase()+r.slice(1)}).join(" ")}function mc(e){if(!e)return{num:"",name:"(docs root)"};let t=/^(\d+)[-_](.+)$/.exec(e);return{num:t?t[1]:"",name:_v(t?t[2]:e)}}function Mv(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).pop()??e}function jf(e,t,n){let o=t>0?Math.round(e/t*n):0;return I.green("\u2588".repeat(o))+I.gray("\u2591".repeat(Math.max(0,n-o)))}function Fv(e,t){let n=t>0?Math.round(e/t*100):0,o=vn(`${n}%`,4);return n===100?I.green(o):n>0?I.yellow(o):I.gray(o)}function Xf(e,t){let n=new Map;for(let o of e){let r=zf(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 xc(e,t){let n=A=>e.filter(D=>D.state===A).length,o=n("captured"),r=n("placeholder"),s=n("spec"),i=n("annotated"),a=n("blocked"),l=n("broken"),d=n("rejected"),m=e.filter(A=>A.state==="spec"&&A.mutates).length,w=s>m,k=e.filter(A=>(A.unguardedWaits?.length??0)>0||(A.bareGoto?.length??0)>0).length,S=e.filter(A=>(A.stalePause?.length??0)>0||(A.handRolled?.length??0)>0).length,v=s>0||a>0||l>0,C=(A,D="")=>Re(A,D,t);return o>0?{key:"annotate",cmd:C("/screenshot annotate")}:r>0?{key:"toSpec",cmd:t?`/screenshot author ${t}`:"/screenshot author --all"}:k>0&&v?{key:"crashy",cmd:t?`/screenshot author ${t}`:"/screenshot author --all"}:S>0&&v?{key:"wrongOutput",cmd:t?`/screenshot author ${t}`:"/screenshot author --all"}:s>0&&(w||i===0)?{key:"ready",cmd:C("/screenshot capture")}:i>0&&s>0?{key:"verify",cmd:C("/screenshot verify")}:a>0?{key:"blocked",cmd:C("/screenshot capture","--blocked")}:l>0?{key:"broken",cmd:`/screenshot ${e.find(A=>A.state==="broken").id}`}:i>0?{key:"verify",cmd:C("/screenshot verify")}:d>0?{key:"rejected",cmd:C("/screenshot capture","--failed")}:{key:"done",cmd:t?`/push ${t}`:"/push"}}function Uv(e,t,n=[]){let o=(te,je)=>te.filter(Ne=>Ne.state===je).length,r=e.length,s=o(e,"verified"),i=o(e,"annotated"),a=o(e,"captured"),l=o(e,"rejected"),d=o(e,"spec"),m=o(e,"blocked"),w=o(e,"broken"),k=o(e,"placeholder"),S=new Set(e.map(te=>te.file)).size,v=Xf(e,t),C=[];C.push(` ${I.bold("Screenshots")} ${I.green(`${s}/${r} verified`)} ${I.gray("\xB7")} ${i>0?I.blue(`${i} to verify`):I.gray("0 to verify")}`+(a>0?` ${I.gray("\xB7")} ${I.yellow(`${a} to annotate`)}`:"")+(l>0?` ${I.gray("\xB7")} ${I.magenta(`${l} rejected`)}`:"")+` ${I.gray("\xB7")} ${d>0?I.yellow(`${d} ready`):I.gray("0 ready")}`+(m>0?` ${I.gray("\xB7")} ${I.cyan(`${m} blocked`)}`:"")+(w>0?` ${I.gray("\xB7")} ${I.red(`${w} broken`)}`:"")+` ${I.gray("\xB7")} ${k>0?I.red(`${k} to spec`):I.gray("0 to spec")} `+I.gray(`across ${S} article${S===1?"":"s"}`));let A=r>0?Math.round(s/r*100):0;C.push(` [${jf(s,r,32)}] ${I.bold(`${A}%`)}`),C.push("");let D=v.map(([te])=>mc(te)),L=Math.min(32,Math.max(7,...D.map(te=>te.name.length))),B=te=>te.length>L?`${te.slice(0,L-1)}\u2026`:Li(te,L),M=[...a>0?[{head:"To annotate",w:11,state:"captured",color:I.yellow}]:[],...i>0?[{head:"To verify",w:9,state:"annotated",color:I.blue}]:[],...l>0?[{head:"Rejected",w:8,state:"rejected",color:I.magenta}]:[],{head:"Ready",w:5,state:"spec",color:I.yellow},...m>0?[{head:"Blocked",w:7,state:"blocked",color:I.cyan}]:[],...w>0?[{head:"Broken",w:6,state:"broken",color:I.red}]:[],{head:"To spec",w:7,state:"placeholder",color:I.red}];C.push(I.gray(` ${Li("#",2)} ${Li("Chapter",L)} ${vn("Verified",8)} ${M.map(te=>vn(te.head,te.w)).join(" ")} Progress`));for(let[te,[,je]]of v.entries()){let Ne=o(je,"verified"),Ze=je.length,{num:bo,name:pn}=D[te],At=Ne===Ze,gt=B(pn),Er=M.map(et=>{let ko=o(je,et.state);return ko>0?et.color(vn(String(ko),et.w)):I.gray(vn("\u2014",et.w))}).join(" ");C.push(` ${I.cyan(Li(bo,2))} ${At?I.green(gt):Ne>0?gt:I.gray(gt)} ${At?I.green(vn(`${Ne}/${Ze}`,8)):vn(`${Ne}/${Ze}`,8)} ${Er} ${jf(Ne,Ze,10)} ${Fv(Ne,Ze)}`)}C.push("");let X=w>0?` ${I.gray("\xB7")} ${w} spec${w===1?"":"s"} broken \u2014 ${I.bold(`/screenshot ${e.find(te=>te.state==="broken").id}`)} re-authors ${w===1?"it":"the first"}`:"",z=e.filter(te=>te.state==="spec"&&te.mutates).length,de=d>z,ye=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,ve=d>0||m>0||w>0,fe=!1,Z=xc(e).key;if(Z==="annotate")C.push(` ${ee("\u25C8",I.blue)}${a} shot${a===1?"":"s"} taken but not drawn on \u2014 run ${I.bold("/screenshot annotate")}`+I.gray(` \u2014 no browser, seconds; the callouts are what make ${a===1?"it":"them"} publishable`)+X);else if(Z==="toSpec")C.push(` ${ee("\u2192",I.yellow)}${k} placeholder${k===1?"":"s"} still need a spec \u2014 run ${I.bold("/screenshot author --all")}${X}`);else if(Z==="crashy")fe=!0,C.push(` ${ee("\u2192",I.yellow)}${ye} spec${ye===1?"":"s"} would crash mid-run \u2014 re-write ${ye===1?"it":"them"} first: ${I.bold("/screenshot author --all")}`+I.gray(` \xB7 then ${I.bold("/screenshot capture")} (no browser time wasted on ${ye===1?"a shot":"shots"} that can't finish)`)+X);else if(Z==="wrongOutput")fe=!0,C.push(` ${ee("\u2192",I.yellow)}${Se} spec${Se===1?"":"s"} would shoot the wrong thing \u2014 re-write ${Se===1?"it":"them"} first: ${I.bold("/screenshot author --all")}`+I.gray(` \xB7 then ${I.bold("/screenshot capture")} (a false skip or a misplaced callout costs the same browser time as a good shot)`)+X);else if(Z==="ready"){let te=z>0?I.gray(` \u2014 ${d-z} in one go; ${z} write${z===1?"s":""} real data and run${z===1?"s":""} one at a time`):"";C.push(` ${ee("\u2192",I.yellow)}${d} spec${d===1?"":"s"} ready to capture \u2014 run ${I.bold("/screenshot capture")}${te}${X}`)}else if(Z==="verify"&&d>0)C.push(` ${ee("\u2192",I.blue)}${i} shot${i===1?"":"s"} awaiting verification \u2014 run ${I.bold("/screenshot verify")}`+I.gray(" \u2014 no browser needed")+I.gray(` \xB7 ${d} ready spec${d===1?"":"s"} write real data, so ${d===1?"it runs":"each runs"} only when named: /screenshot capture <id>`)+X);else if(Z==="blocked")C.push(` ${ee("\u2192",I.cyan)}${m} shot${m===1?"":"s"} blocked \u2014 stage the data below, then ${I.bold("/screenshot capture --blocked")}${X}`);else if(Z==="broken")C.push(` ${ee("\u2192",I.red)}${w} spec${w===1?"":"s"} broken \u2014 ${I.bold(`/screenshot ${e.find(te=>te.state==="broken").id}`)} re-authors ${w===1?"it":"the first"} (re-capturing fails the same way)`);else if(Z==="verify")C.push(` ${ee("\u2192",I.blue)}${i} shot${i===1?"":"s"} awaiting verification \u2014 run ${I.bold("/screenshot verify")}`+I.gray(" \u2014 it checks each picture against what its article needs (no browser, no re-capture)"));else if(Z==="rejected"){let te=e.filter(je=>je.state==="rejected"&&je.repaired).length;C.push(` ${ee("\u2691",I.magenta)}${l} shot${l===1?"":"s"} failed review \u2014 `+(te>0?`${te} spec${te===1?"":"s"} already repaired; re-capture with ${I.bold("/screenshot capture --failed")}`:`see the reasons below, then ${I.bold("/screenshot capture --failed")}`))}else C.push(` ${ee("\u2713",I.green)}all ${r} verified \u2014 ${I.bold("/push")} embeds them in the articles`);if(s>0&&s<r){let te=v.filter(([,je])=>je.every(Ne=>Ne.state!=="verified")).map(([je])=>{let{num:Ne,name:Ze}=mc(je);return Ne?`${Ne} ${Ze}`:Ze});te.length>0&&C.push(I.gray(` Furthest behind: ${te.slice(0,5).join(" \xB7 ")}${te.length>5?" \u2026":""} (0% verified)`))}return C.push(...qf(e),...Kf(e),...Yf(e,!1,{commandInLead:fe}),...Vf(e,!1),...vc(n)),C.push(""),C.push(I.gray(" Drill in: /screenshot list <chapter#> \xB7 /screenshot list --detail (all)")),C}function Wv(e,t,n,o=[]){let r=new Set(e.map(d=>d.file)),s=e.filter(d=>d.state==="verified").length,i=e.filter(d=>d.state==="annotated").length,a=e.filter(d=>d.state==="captured").length,l=[` ${I.bold("Screenshots")}: ${e.length} placeholder${e.length===1?"":"s"} across ${r.size} article${r.size===1?"":"s"} \xB7 ${I.green(`${s} verified`)}${i>0?I.blue(` \xB7 ${i} to verify`):""}${a>0?I.yellow(` \xB7 ${a} to annotate`):""}${n?I.gray(` \xB7 scope ${n}`):""}`,""];for(let[d,m]of Xf(e,t)){let w=m.filter(A=>A.state==="verified").length,{num:k,name:S}=mc(d),v=k?`${k} \xB7 ${S}`:S;l.push(` ${I.bold(v)} ${I.gray(`(${w}/${m.length})`)}`);let C=new Map;for(let A of m){let D=Mv(A.file),L=C.get(D)??[];C.has(D)||C.set(D,L),L.push(A)}for(let A of[...C.keys()].sort()){l.push(I.gray(` ${A}`));for(let D of C.get(A)){let L=jv[D.state];if(l.push(` ${ee(Nv[D.state],L)}${L(D.id)}`),(D.state==="blocked"||D.state==="broken"||D.state==="rejected")&&D.reason){for(let B of qt(er(D.reason),84))l.push(I.gray(` ${B}`));D.state==="rejected"&&l.push(I.gray(` ${D.repaired?"spec repaired \u2014 re-capture to confirm":"spec not yet repaired"}`))}}}}return l.push(...qf(e),...Kf(e),...Yf(e,!0),...Vf(e,!0),...vc(o)),l.push("",Iv),l}function Gi(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.",...vc(o)];let r=t?.docsDir??kc;return t?.detail||n?Wv(e,r,n,o):Uv(e,r,o)}function Rc(e,t){if(!t||!/^\d+$/.test(t))return t;let n=xn(e)?.docsDir??kc,o=String(Number(t));for(let{file:r}of Lf(e)){let s=zf(r,n),i=/^(\d+)/.exec(s);if(i&&String(Number(i[1]))===o)return s}return t}function Qf(e,t){let r=e.map(a=>" ".repeat(a.depth)+a.label),s=Math.max(0,...e.map((a,l)=>a.note?Ii(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 m=Math.max(2,i+2-Ii(d)),w=a.note.trim(),k=t-Ii(d)-m;return{head:d+" ".repeat(m),note:k>1&&Ii(w)>k?`${w.slice(0,k-1)}\u2026`:w}})}function Bv(e){let t=e.replace(/\\/g,"/").split("/").filter(Boolean),n=t.pop()??e;return{category:t.pop()??"(docs root)",article:n}}function Zo(e,t,n){let o=new Map;for(let s of t){let{category:i,article:a}=Bv(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 m=i.get(d),w=m.filter(r).map(v=>v.id),k=w.length>0;k&&e.push({kind:"article",action:n,label:`${d} (${w.length})`,ids:w,depth:l?2:1});let S=(l?1:0)+(k?1:0)+1;for(let v of m){let C=n==="capture"&&v.mutates?" \u26A0 creates real data \u2014 runs only alone":void 0;e.push({kind:"shot",action:n,label:v.id,ids:[v.id],depth:S,...C?{note:C}:{}})}}}}function cc(e){return e?er(e):""}function Cc(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 ${cc(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 ${cc(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 ${cc(i.reason)}`})}}function Jf(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}),Zo(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}),Zo(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}),Zo(o,s,"annotate"),Cc(o,e.filter(i=>i.state==="blocked"),e.filter(i=>i.state==="broken"),e.filter(i=>i.state==="rejected")),o}var gc=["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 Hv(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 wc="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 Zf(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=>Bf(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.",gc,wc].join(`
|
|
323
|
+
`)}async function qi(e,t,n){let o=ss(e),r=no(t?.cwd??process.cwd());if(r&&console.log(I.gray(r)),o.mode==="list"){let l=t?.cwd??process.cwd(),d=Rc(l,o.scope),m=xn(l)?.docsDir??kc,w=_e(l,d),k=mv(l,d?{scope:d}:{});for(let S of Gi(w,{scope:d,detail:o.detail,docsDir:m,markerProblems:k}))console.log(S);return{kind:"continue"}}if(o.mode==="single"){let l=oo(t?.cwd??process.cwd(),o.id),d=l===null?[]:$c(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.",gc,wc,...n?.prior?["",...Hv(n.prior)]:[],...d.length>0?["",...Bf(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.`,gc,wc].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 Vv,readProjectConfig as Yv,listOpenHints as Kv,listOpenForDocs as zv,listOpenDirectives as Xv,loadOpenCommentCount as Qv,resolveActiveProfile as Jv,DEFAULT_DOCS_DIR as Zv}from"document360-engine";import{statSync as Gv}from"node:fs";import{resolve as qv}from"node:path";function Rn(e,t,n){return n.filter(o=>{try{return Gv(qv(e,t,o)).size===0}catch{return!0}})}var ro=e=>e===1?"":"s";function e0(e){try{let t=(Yv(e)?.docsDir??Zv).replace(/\/+$/,""),n=Vv(e,t);return n.length===0?0:Rn(e,t,n.map(o=>o.path)).length}catch{return 0}}function t0(e){try{return Qv(e,Jv(e).name)}catch{return 0}}function n0(e){let t=s=>{try{return s().length}catch{return 0}},n=t(()=>Kv(e)),o=t(()=>zv(e)),r=t(()=>Xv(e));return{hints:n,messages:o,directives:r,total:n+o+r}}function em(e,t){let n=t?.just,o=n0(e);if(o.total>0&&n!=="/catch-up"){let i=[];return o.hints>0&&i.push(`${o.hints} hint${ro(o.hints)}`),o.messages>0&&i.push(`${o.messages} message${ro(o.messages)}`),o.directives>0&&i.push(`${o.directives} request${ro(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=t0(e);if(r>0&&n!=="/comments")return{cmd:"/comments",short:`${r} reviewer comment${ro(r)} ${r===1?"is":"are"} waiting on your articles`,text:`${r} reviewer comment${ro(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=e0(e);return s>0&&n!=="/write"?{cmd:"/write",short:`${s} planned article${ro(s)} ${s===1?"is":"are"} still unwritten`,text:`${s} planned article${ro(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 o0}from"document360-engine";var r0=new Set(["--scope","--concurrency","--model"]),s0=new Set(["/screenshot","/style-guide"]),i0=e=>e.trim().replace(/\s+/g," ").toLowerCase();function Vi(e){let t=i0(o0(e));if(!t.startsWith("/"))return null;let n=t.split(" ").filter(Boolean),o=n[0],r=1,s;s0.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 m=l.slice(0,d);i.add(m),m==="--scope"&&(a=l.slice(d+1)||void 0);continue}if(i.add(l),r0.has(l)){let m=n[r+1];m!==void 0&&!m.startsWith("-")&&(l==="--scope"&&(a=m),r++)}continue}if(l.startsWith("-")){i.add(l);continue}a??=l}return{cmd:o,...s?{sub:s}:{},flags:i,...a?{scope:a.replace(/\/+$/,"")}:{}}}function Sc(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 a0=new Set(["--all"]),l0=new Set(["--concurrency","--model","--verbose","--quiet"]),c0=new Set(["--scope"]);function tm(e){return[...e.flags].filter(t=>!a0.has(t)&&!l0.has(t)&&!c0.has(t)).sort().join(" ")}function nm(e,t){if(!t)return!1;let n=Vi(e),o=Vi(t);return!n||!o||n.cmd!==o.cmd||n.sub!==o.sub||!Sc(n)||tm(n)!==tm(o)?!1:n.scope===void 0||n.scope===o.scope}function Yt(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 ls,roadmapProgress as lm,stampRoadmapDone as m0}from"document360-engine";se();se();import{ROADMAP_STAGES as om}from"document360-engine";var rm=[...om,"other"],u0=[[/^\/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 Pc(e){let t=(e.stage??"").trim().toLowerCase();if(om.includes(t))return t;let n=(e.run??"").trim().toLowerCase();if(n.startsWith("/")){for(let[o,r]of u0)if(o.test(n))return r}return"other"}function Yi(e){return Pc(e)==="capture"}var d0={decide:"Decide",plan:"Plan",capture:"Screenshots",write:"Write",edit:"Edit",lint:"Style rules",save:"Save to Document360",golive:"Go live",other:"Other steps"};function sm(e){return e.status==="done"&&!!e.replacedBy}var Ac=e=>(e.run??"").trim().replace(/\s+/g," ").toLowerCase();function p0(e){let t=[];for(let o of e){let r=Ac(o);r&&!t.includes(r)&&t.push(r)}let n=o=>{let r=Ac(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 h0(e){let t=new Map;for(let o of e){let r=Pc(o),s=t.get(r);s?s.push(o):t.set(r,[o])}let n=[];for(let o of rm){let r=t.get(o);!r||r.length===0||n.push({key:o,label:d0[o],steps:p0(r),done:r.filter(s=>s.status==="done").length})}return n}var Tc=" ",im=e=>e.trim().toLowerCase();function f0(e,t){let n=Math.max(20,t.width-Tc.length),o=e.status==="done"?q("\u2713"):be("\u25CB"),r=e.status==="done"?g:t.isNext?J:m=>m,s=qt(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(m=>` \xB7 ${m}`).join(""),l=s.map((m,w)=>w===0?` ${o} ${r(m)}`:`${Tc}${r(m)}`);if(!a)return l;if((s[s.length-1]??"").length+a.length<=n)return l[l.length-1]+=be(a),l;for(let m of i)l.push(`${Tc}${be(`\xB7 ${m}`)}`);return l}function am(e,t={}){let n=Math.max(40,t.width??80),o=t.all?e:e.filter(a=>!sm(a)),r=e.length-o.length,s=e.filter(a=>a.status==="done").length,i=[J(`Docs roadmap \u2014 ${s} of ${e.length} step${e.length===1?"":"s"} done`)];for(let a of h0(o)){i.push(""),i.push(` ${Be(a.label)}${be(` \xB7 ${a.done} of ${a.steps.length}`)}`);let l="";for(let d of a.steps){let m=Ac(d);i.push(...f0(d,{width:n,showRun:!!m&&m!==l,isNext:!!t.next&&im(d.title)===im(t.next.title),showReplaced:!!t.all&&sm(d)})),l=m}}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(g(`(+${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 Ec(e,t={}){let n=ls(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=lm(e),r=am(n,{width:t.width,all:t.all,next:o.next});return r.push(g("(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(g('(d360-writer keeps the wording of its own steps current \u2014 add a "keep:" line to one to leave your version alone.)')),r}function tr(e,t){let n=ls(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 dm(e,t){let n=t.trim().toLowerCase();if(!n)return null;let o=
|
|
329
|
+
`)}`};let a=i[0].title;m0(e,a,{doneAt:new Date().toISOString()});let l=lm(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 cm(e,t){let n=r=>r.trim().replace(/\s+/g," ").toLowerCase(),o=n(t);return o.startsWith("/")?ls(e).find(r=>r.status==="open"&&!!r.run&&n(r.run)===o)??null:null}function um(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 ls(e))s.status==="open"&&n.some(i=>nm(i,s.run))&&(o.has(s.title)||(o.add(s.title),r.push(s.title)));return r}function vt(e,t){if(!t)return[];try{let n=um(e,t).filter(o=>tr(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 Ki(e,t){let n=um(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 dm(e,t){let n=t.trim().toLowerCase();if(!n)return null;let o=ls(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 pm(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let o=tr(n,e.slice(1).join(" ").trim());return console.log(o.ok?q(o.line):G(o.line)),{kind:"continue"}}for(let o of Tc(n,{all:e.some(r=>r.toLowerCase()==="--all")}))console.log(o);return{kind:"continue"}}var fm={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 pushing overwrites the portal edit"};function Ec(e){return e.filter(t=>t.path!==null&&t.status in fm&&!t.link).map(t=>({path:t.path,label:fm[t.status]}))}function so(e){let t=Ec(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 as(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 nr(e,t){let n=k0(e,t).length;return n===0?null:`\u2139 ${n} article${n===1?"":"s"} ${n===1?"is":"are"} saved on Document360 as a draft and not live yet \u2014 readers still see the previous version. /publish takes ${n===1?"it":"them"} live once ${n===1?"it has":"they have"} been signed off.`}function zi(e){return e.filter(t=>t.link).length}function Dc(e,t){try{let n=mm(e,Ac(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=A0(m0(g0(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 vm(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:`${$n(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 ls(e,t){try{let n=Ac(e,t),o=n.project.projectId,r=n.project.workspaceId;if(!o||!r)return null;let s=await T0({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 "${hm}" 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 "${hm}" folder on Document360 \u2014 it's where your reviewers leave feedback for d360-writer to action (confirmed hidden from readers; its README explains how). /catch-up picks up what they write.`}catch{return null}}var xt="--skip-review";function cs(e,t){return $0(e,t)}function Xi(e,t){try{return cs(e,wm(e,t)).length}catch{return 0}}function Bt(e,t,n="",o,r){let s=Xi(e,o),i=Qi(e,o),a=o?` ${o}`:"",l=o?"/push":"/push --all",d=em(e,{just:r}),g=!!o&&o.endsWith(".md"),f=d&&g?` (${d.short} \u2014 ${d.cmd} once this page is delivered.)`:"";if(d&&!g){let $=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}${$}`,cmd:d.cmd}}if(s===0&&i===0)return f?{...t,text:`${t.text}${f}`}:t;let x=o&&!o.endsWith(".md")?` in ${o}`:"";if(s>0){let $=s===1?"":"s",C=i>0?` ${i} also break house style rules \u2014 /lint${a} --blocked --fix clears those afterwards.`:"",A=`/review${a} --blocked --fix`;return{text:`${n}${s} article${$}${x} ${s===1?"carries":"carry"} text no editor has read, so pushing ${s===1?"it is":"them is"} blocked. ${A} reads ${s===1?"it":"just those"} and applies its fixes.${C} Then ${l}.${f}`,cmd:A}}return{text:`${n}${i} article${i===1?"":"s"}${x} 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}.${f}`,cmd:`/lint${a} --blocked --fix`}}function Qi(e,t){try{return gm(e,wm(e,t)).length}catch{return 0}}function xm(e,t){return gm(e,t)}function Nc(e,t,n){try{let o=mm(e,Ac(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 jc(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 ${D0(t.elapsedMs)}`:"",a=e.screenshotsUploaded>0?` \xB7 ${e.screenshotsUploaded} screenshot${e.screenshotsUploaded===1?"":"s"} uploaded`:"";if(s===0&&e.failed.length===0?r.push("Nothing was pushed \u2014 no articles were sent."):t.recorded<s?(r.push(`Pushed ${t.recorded}/${o(s)}${a}${i}.`),r.push(`${s-t.recorded} article${s-t.recorded===1?"":"s"} reported success but ${s-t.recorded===1?"is":"are"} not recorded in the category map \u2014 re-run ${n}.`)):(r.push(`Pushed ${o(s)}${e.created>0?` (${e.created} new)`:""}${a}${i}.`),r.push(`Saved on Document360 as draft${s===1?"":"s"} \u2014 readers don't see ${s===1?"it":"them"} until /publish takes ${s===1?"it":"them"} live.`)),e.failed.length>0){let l=e.failed.filter(d=>d.refused);r.push(`${e.failed.length} article${e.failed.length===1?"":"s"} could not be pushed:`);for(let d of e.failed)r.push(` \u2717 ${d.path} \u2014 ${d.error}`);l.length<e.failed.length&&r.push(`Re-run ${n} to retry the rest \u2014 articles already saved are sent again only if they changed.`)}if(e.notRun.length>0&&r.push(`\u26A0 ${o(e.notRun.length)} never started (the run was stopped): ${E0(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(as(t.conflictsSkipped)),r}var E0=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`;function D0(e){let t=Math.round(e/1e3);return t<60?`${t}s`:`${Math.floor(t/60)}m ${String(t%60).padStart(2,"0")}s`}async function Wt(e,t,n=0,o){let r=v0(e.cwd,t,{allowUnreviewed:o?.skipReview===!0,allowStyleErrors:o?.skipStyle===!0});if(!r.clear){for(let a of x0(r,t.length,{act:"push"}))console.log(G(a));return{kind:"continue"}}let s={aborted:!1,partitions:0,failed:0,notRun:0,producedNothing:!0},i=async(a,l)=>{let d=Date.now();console.log(w(l?`Resolving cross-links in ${a.length} article${a.length===1?"":"s"} whose targets published this run (second pass)\u2026`:`Pushing ${a.length} article${a.length===1?"":"s"} to Document360 (${S0} at a time)\u2026`));let g=await R0({cwd:e.cwd,...e.profileName?{profileName:e.profileName}:{},paths:a,allowProdWrites:e.allowProdWrites?.()===!0,...o?.allowUnpullable===!0?{allowUnpullable:!0}:{},onEvent:A=>{A.type==="article_done"?console.log(q(` \u2713 ${A.result.path}${A.result.action==="created"?" (new)":""}`)):A.type==="article_failed"&&console.log(O(` \u2717 ${A.failure.path} \u2014 ${A.failure.error}`))}});console.log("");let f=Nc(e.cwd,a,e.profileName);l||(s={aborted:g.aborted,partitions:y0(a).length,failed:g.failed.length,notRun:g.notRun.length,producedNothing:g.pushed.length===0,verifiedComplete:f>=a.length,leftBehind:n});let x=g.pushed.length>0;for(let A of jc(g,{recorded:f,elapsedMs:Date.now()-d,...l?{}:{conflictsSkipped:n},...o?.scope?{scope:o.scope}:{}}))console.log(x&&g.failed.length===0?q(A):G(A));if(!x)return g.aborted;let P=Dc(e.cwd,e.profileName);P&&console.log(w(P));let $=nr(e.cwd,e.profileName);$&&console.log(w($));try{let A=bm(await ym({cwd:e.cwd,profileName:e.profileName,onRateLimit:D=>console.log(w(` Document360 rate limit \u2014 waiting ${Math.ceil(D.waitMs/1e3)}s\u2026`))}));A&&console.log(A.startsWith("\u26A0")?G(A):w(A))}catch{}try{let A=$m(await km({cwd:e.cwd,profileName:e.profileName}));A&&console.log(w(A))}catch{}let C=await ls(e.cwd,e.profileName);return C&&console.log(w(C)),g.aborted};try{if(!await i(t,!1)){let l=await Ic(e.cwd,e.profileName,t);if(l.length>0&&await i(l,!0),Yt(s))for(let d of vt(e.cwd,o?.scope?`/push ${o.scope}`:"/push --all"))console.log(q(d))}}catch(a){console.log(O(`Push run failed: ${a.message}`))}return console.log(""),{kind:"continue"}}async function Ji(e,t,n){let o=b0(e,n);if(o.length===0)return[];let r=new Set(Ec((await Ki({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function Ic(e,t,n){try{let o=new Set(n),r=await Ki({cwd:e,profileName:t});return Ec(r.entries).map(s=>s.path).filter(s=>o.has(s))}catch{return[]}}async function N0(e,t,n){try{let o=await C0({cwd:e,...t?{profileName:t}:{},relPath:n.replace(/\\/g,"/"),preview:!0});console.log(""),console.log(q(`${o.title}`)),console.log(w(`${o.path} \xB7 ${o.articleId?`updates article ${o.articleId}`:"would be created as a new article"}`)),o.shots.length>0&&console.log(w(`${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(w("\u2500".repeat(Math.min(80,Math.max(20,(process.stdout.columns??80)-1))))),console.log(o.body),console.log(w("\u2500".repeat(Math.min(80,Math.max(20,(process.stdout.columns??80)-1))))),console.log(w(`Nothing was sent. Run /push ${o.path} to save it as a draft.`))}catch(o){console.log(O(o.message))}return{kind:"continue"}}async function Zi(e,t){let n=qe(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(O(n.reason)),{kind:"continue"};let o=e.includes(xt),r=e.includes(P0);if(e.includes("--preview")){let i=e.find(a=>!a.startsWith("--"));return i?await N0(t?.cwd??process.cwd(),t?.profileName,i):(console.log(O("Which article? Use /push --preview <path> \u2014 a preview is per article.")),{kind:"continue"})}let s=e[0];if(e.includes("--screenshots")||e.includes("--shots")){let i=t?.cwd??process.cwd(),a=e.find(P=>!P.startsWith("--")),l=_e(i),d=Fi(l,a);if(d.length===0){let P=l.filter($=>$.state==="captured").length;return console.log(w(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 g=Ui(l,a);g&&console.log(g);let f=Wi(l);f&&console.log(f);let x=Re("","--screenshots",a).trim();return await Wt(t??{cwd:process.cwd()},d,0,{skipReview:o,skipStyle:r,scope:x})}if(s==="--related"&&e[1]){if(!t)return{kind:"continue"};let i=await Ji(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return i.length===0?(console.log(q("\u2713 All related articles are already on Document360.")),{kind:"continue"}):await Wt(t,i,0,{skipReview:o,skipStyle:r,scope:`--related ${e[1]}`})}if(s==="--all"){console.log(w("Checking what needs pushing\u2026"));try{let i=await Ki({cwd:t?.cwd??process.cwd()}),{clean:a,conflicts:l}=so(i.entries),d=zi(i.entries),g=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&&!g&&console.log(G(as(l.length)));let f=g?[...a,...l]:a;if(f.length===0){if(l.length>0){let P=nr(t?.cwd??process.cwd(),t?.profileName);return P&&console.log(w(P)),console.log(w("Resolve the conflicts: /resolve")),{kind:"continue"}}console.log(q(d>0?"\u2713 Nothing else is ahead of Document360 to push.":"\u2713 Nothing is ahead of Document360 \u2014 nothing to push."));let x=nr(t?.cwd??process.cwd(),t?.profileName);if(x&&console.log(w(x)),t)try{let P=bm(await ym({cwd:t.cwd,profileName:t.profileName,onRateLimit:C=>console.log(w(` Document360 rate limit \u2014 waiting ${Math.ceil(C.waitMs/1e3)}s\u2026`))}));P&&console.log(P.startsWith("\u26A0")?G(P):w(P));let $=$m(await km({cwd:t.cwd,profileName:t.profileName}));$&&console.log(w($))}catch{}return{kind:"continue"}}return await Wt(t??{cwd:process.cwd()},f.map(x=>x.path),g?0:l.length,{skipReview:o,skipStyle:r,allowUnpullable:g})}catch(i){return console.log(O(`Could not compute sync status: ${i.message}`)),{kind:"continue"}}}if(s&&s.startsWith("--")&&(s=e.find(i=>!i.startsWith("--"))??""),!s){console.log(w("Checking what needs pushing\u2026"));let i,a=0;try{let l=await Ki({cwd:t?.cwd??process.cwd()}),{clean:d,conflicts:g}=so(l.entries);i=d,a=g.length;let f=zi(l.entries);if(f>0&&console.log(G(`\u26A0 ${f} article(s) already exist on Document360 but aren't linked \u2014 left out (pushing would duplicate them). Run /catch-up or ask me to link them first.`)),g.length>0&&console.log(G(as(g.length))),i.length===0&&g.length>0)return console.log(w("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(l){return console.log(O(`Could not compute sync status: ${l.message}`)),console.log(w("Push a specific article: /push <article-path>")),{kind:"continue"}}if(i.length===0)return console.log(q("\u2713 Nothing is ahead of Document360 \u2014 nothing to push.")),console.log(w(" (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} ${w(`(${l.label})`)}`);return console.log(w("Run: /push <article-path>")),{kind:"continue"}}try{s=await t.withPausedInput(()=>w0({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(w("Cancelled.")),{kind:"continue"}}if(s==="--all")return await Wt(t,i.map(l=>l.path),a,{skipReview:o,skipStyle:r})}return await Wt(t??{cwd:process.cwd()},[s],0,{skipReview:o,skipStyle:r,scope:s})}se();import{select as I0}from"@inquirer/prompts";import{computeSyncStatus as L0,localAheadPaths as O0,pendingDrafts as _0,publishArticleLive as M0,publishGateVerdict as F0,publishGateLines as U0,resolveActiveProfile as eI,SKIP_STYLE_FLAG as W0,SKIP_SHOTS_FLAG as B0}from"document360-engine";var j0={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."},Rm=new Set;function ln(e){let t=j0[e.replace(/^\//,"")];return!t||Rm.has(e)?null:(Rm.add(e),t)}var H0=150,G0=e=>e>0?new Promise(t=>setTimeout(t,e)):Promise.resolve(),Oc=e=>e===1?"":"s",Lc=e=>e.replace(/\\/g,"/").split("/").pop()??e;function _c(e){return e.includes("--screenshots")||e.includes("--shots")||e[0]==="--related"}async function Mc(e,t,n){await L0({cwd:e,profileName:t});let o=n?n.replace(/\\/g,"/").replace(/\/+$/,""):null;return _0(e,t).filter(r=>!o||r.path===o||r.path.startsWith(`${o}/`)).map(r=>({...r,label:q0(e,r.path)}))}function q0(e,t){let n=Ei(e,t)??ns(t),o=Ai(t),r=o?$n(o):"";return r?`${r} \u203A ${n}`:n}function V0(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 Fc(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=O0(e,t).filter(a=>!s||a===s||a.startsWith(`${s}/`)).length;return i>0&&r.push(`${i} article${Oc(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 Uc(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 M0({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 G0(H0)}return r}function Wc(e){let{published:t,blocked:n,failed:o}=e,r=[];if(t.length>0){r.push(`\u2713 ${t.length} article${Oc(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 ${Lc(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 ${Lc(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 Cm(e,t){let n=t?.cwd??process.cwd(),o=ln("publish");if(_c(e))return o&&console.log(w(`\u2192 ${o}`)),console.log(w("Running /push\u2026")),Zi(e,t);let r=qe(n,t?.profileName);if(!r.ok)return console.log(O(r.reason)),{kind:"continue"};o&&console.log(w(`\u2192 ${o}`));let s=e.includes(xt),i=e.includes(W0),a=e.includes(B0),l=e.includes("--all"),d=e.find($=>!$.startsWith("--"));console.log(w("Checking what is waiting to go live\u2026"));let g;try{g=await Mc(n,t?.profileName,d)}catch($){return console.log(O(`Could not check Document360: ${$.message}`)),{kind:"continue"}}if(g.length===0){for(let $ of Fc(n,t?.profileName,d).lines)console.log($.startsWith("\u2713")?q($):w($));return{kind:"continue"}}let f=F0(n,g.map($=>$.path),{allowUnreviewed:s,allowStyleErrors:i,checkScreenshots:!0,allowPlaceholders:a});if(!f.clear){for(let $ of U0(f,g.length,{scope:d,act:"publish"}))console.log(G($));return{kind:"continue"}}console.log(""),console.log(`${g.length} draft${Oc(g.length)} ${g.length===1?"is":"are"} ahead of what readers see:`);for(let $ of V0(g.slice(0,12)))console.log(w($));g.length>12&&console.log(w(` \u2026and ${g.length-12} more`)),console.log("");let x=g;if(!l){let $=await I0({message:"Publish live to your readers?",choices:[{name:`Yes \u2014 publish all ${g.length} live`,value:"all"},...g.slice(0,8).map(C=>({name:`Just ${C.label}`,value:C.path})),{name:"No \u2014 leave them as drafts",value:"none"}]});if($==="none")return console.log(w("Left as drafts. Nothing changed.")),{kind:"continue"};$!=="all"&&(x=g.filter(C=>C.path===$))}let P=await Uc(n,t?.profileName,x,{skipReview:s,skipStyle:i,onProgress:($,C,A)=>console.log(w(` \u25B8 ${$+1}/${C} ${Lc(A)}\u2026`))});console.log("");for(let $ of Wc(P))console.log($.startsWith("\u2713")?q($):$.startsWith("\u2717")?G($):w($));return{kind:"continue"}}import{loadKnownConflicts as Y0,localArticleTitle as K0,resolveActiveProfile as z0}from"document360-engine";function X0(e,t){let n=K0(e,t);return n||(t.split(/[\\/]/).pop()??t).replace(/\.md$/,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ")}function ea(e,t){let n=[];try{n=Y0(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=>X0(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 or={cmd:"/resolve",reason:"it walks each one with you \u2014 keep yours, take the portal's, or skip"};async function us(e){if(e?.cwd){let n=ea(e.cwd,e.profileName);if(n)return{kind:"audit-blocked",note:n.note,lead:or}}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 Sm(e,t){let n=t?.cwd??process.cwd();return
|
|
332
|
+
`):null}async function pm(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let o=tr(n,e.slice(1).join(" ").trim());return console.log(o.ok?q(o.line):G(o.line)),{kind:"continue"}}for(let o of Ec(n,{all:e.some(r=>r.toLowerCase()==="--all")}))console.log(o);return{kind:"continue"}}var fm={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 pushing overwrites the portal edit"};function Nc(e){return e.filter(t=>t.path!==null&&t.status in fm&&!t.link).map(t=>({path:t.path,label:fm[t.status]}))}function so(e){let t=Nc(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 cs(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 nr(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 Xi(e){return e.filter(t=>t.link).length}function jc(e,t){try{let n=mm(e,Dc(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=E0(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 vm(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:`${$n(r)} (${s.length})`,paths:s.map(i=>i.path),indent:!1});for(let i of s){let a=i.path.replace(/\\/g,"/").split("/").pop()??i.path;n.push({kind:"article",label:a,paths:[i.path],indent:!0,note:i.label})}}for(let r of[...t].sort((s,i)=>s.path.localeCompare(i.path))){let s=r.path.replace(/\\/g,"/").split("/").pop()??r.path;n.push({kind:"article",label:s,paths:[r.path],indent:!1,note:r.label,conflict:!0})}return n}async function us(e,t){try{let n=Dc(e,t),o=n.project.projectId,r=n.project.workspaceId;if(!o||!r)return null;let s=await A0({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 "${hm}" 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 "${hm}" folder on Document360 \u2014 it's where your reviewers leave feedback for d360-writer to action (confirmed hidden from readers; its README explains how). /catch-up picks up what they write.`}catch{return null}}var xt="--skip-review";function ds(e,t){return v0(e,t)}function Qi(e,t){try{return ds(e,wm(e,t)).length}catch{return 0}}function Bt(e,t,n="",o,r){let s=Qi(e,o),i=Ji(e,o),a=o?` ${o}`:"",l=o?"/push":"/push --all",d=em(e,{just:r}),m=!!o&&o.endsWith(".md"),w=d&&m?` (${d.short} \u2014 ${d.cmd} once this page is delivered.)`:"";if(d&&!m){let v=s>0?` (${s} article${s===1?"":"s"}${o&&!o.endsWith(".md")?` in ${o}`:""} ${s===1?"carries":"carry"} text no editor has read, so ${s===1?"it cannot":"they cannot"} be sent up until /review${a} --blocked --fix runs \u2014 that can wait until the writing is done.)`:i>0?` (${i} article${i===1?"":"s"} break${i===1?"s":""} house style rules that block sending up \u2014 /lint${a} --blocked --fix clears that whenever you want.)`:"";return{text:`${n}${d.text}${v}`,cmd:d.cmd}}if(s===0&&i===0)return w?{...t,text:`${t.text}${w}`}:t;let k=o&&!o.endsWith(".md")?` in ${o}`:"";if(s>0){let v=s===1?"":"s",C=i>0?` ${i} also break house style rules \u2014 /lint${a} --blocked --fix clears those afterwards.`:"",A=`/review${a} --blocked --fix`;return{text:`${n}${s} article${v}${k} ${s===1?"carries":"carry"} text no editor has read, so pushing ${s===1?"it is":"them is"} blocked. ${A} reads ${s===1?"it":"just those"} and applies its fixes.${C} Then ${l}.${w}`,cmd:A}}return{text:`${n}${i} article${i===1?"":"s"}${k} break${i===1?"s":""} house style rules that block publishing. /lint${a} --blocked --fix corrects them in place \u2014 finding them costs nothing \u2014 then ${l}.${w}`,cmd:`/lint${a} --blocked --fix`}}function Ji(e,t){try{return gm(e,wm(e,t)).length}catch{return 0}}function xm(e,t){return gm(e,t)}function Ic(e,t,n){try{let o=mm(e,Dc(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 Lc(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 ${N0(t.elapsedMs)}`:"",a=e.screenshotsUploaded>0?` \xB7 ${e.screenshotsUploaded} screenshot${e.screenshotsUploaded===1?"":"s"} uploaded`:"";if(s===0&&e.failed.length===0?r.push("Nothing was pushed \u2014 no articles were sent."):t.recorded<s?(r.push(`Pushed ${t.recorded}/${o(s)}${a}${i}.`),r.push(`${s-t.recorded} article${s-t.recorded===1?"":"s"} reported success but ${s-t.recorded===1?"is":"are"} not recorded in the category map \u2014 re-run ${n}.`)):(r.push(`Pushed ${o(s)}${e.created>0?` (${e.created} new)`:""}${a}${i}.`),r.push(`Saved on Document360 as draft${s===1?"":"s"} \u2014 readers don't see ${s===1?"it":"them"} until /publish takes ${s===1?"it":"them"} live.`)),e.failed.length>0){let l=e.failed.filter(d=>d.refused);r.push(`${e.failed.length} article${e.failed.length===1?"":"s"} could not be pushed:`);for(let d of e.failed)r.push(` \u2717 ${d.path} \u2014 ${d.error}`);l.length<e.failed.length&&r.push(`Re-run ${n} to retry the rest \u2014 articles already saved are sent again only if they changed.`)}if(e.notRun.length>0&&r.push(`\u26A0 ${o(e.notRun.length)} never started (the run was stopped): ${D0(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(cs(t.conflictsSkipped)),r}var D0=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`;function N0(e){let t=Math.round(e/1e3);return t<60?`${t}s`:`${Math.floor(t/60)}m ${String(t%60).padStart(2,"0")}s`}async function Wt(e,t,n=0,o){let r=x0(e.cwd,t,{allowUnreviewed:o?.skipReview===!0,allowStyleErrors:o?.skipStyle===!0});if(!r.clear){for(let a of R0(r,t.length,{act:"push"}))console.log(G(a));return{kind:"continue"}}let s={aborted:!1,partitions:0,failed:0,notRun:0,producedNothing:!0},i=async(a,l)=>{let d=Date.now();console.log(g(l?`Resolving cross-links in ${a.length} article${a.length===1?"":"s"} whose targets published this run (second pass)\u2026`:`Pushing ${a.length} article${a.length===1?"":"s"} to Document360 (${P0} at a time)\u2026`));let m=await C0({cwd:e.cwd,...e.profileName?{profileName:e.profileName}:{},paths:a,allowProdWrites:e.allowProdWrites?.()===!0,...o?.allowUnpullable===!0?{allowUnpullable:!0}:{},onEvent:A=>{A.type==="article_done"?console.log(q(` \u2713 ${A.result.path}${A.result.action==="created"?" (new)":""}`)):A.type==="article_failed"&&console.log(O(` \u2717 ${A.failure.path} \u2014 ${A.failure.error}`))}});console.log("");let w=Ic(e.cwd,a,e.profileName);l||(s={aborted:m.aborted,partitions:b0(a).length,failed:m.failed.length,notRun:m.notRun.length,producedNothing:m.pushed.length===0,verifiedComplete:w>=a.length,leftBehind:n});let k=m.pushed.length>0;for(let A of Lc(m,{recorded:w,elapsedMs:Date.now()-d,...l?{}:{conflictsSkipped:n},...o?.scope?{scope:o.scope}:{}}))console.log(k&&m.failed.length===0?q(A):G(A));if(!k)return m.aborted;let S=jc(e.cwd,e.profileName);S&&console.log(g(S));let v=nr(e.cwd,e.profileName);v&&console.log(g(v));try{let A=bm(await ym({cwd:e.cwd,profileName:e.profileName,onRateLimit:D=>console.log(g(` Document360 rate limit \u2014 waiting ${Math.ceil(D.waitMs/1e3)}s\u2026`))}));A&&console.log(A.startsWith("\u26A0")?G(A):g(A))}catch{}try{let A=$m(await km({cwd:e.cwd,profileName:e.profileName}));A&&console.log(g(A))}catch{}let C=await us(e.cwd,e.profileName);return C&&console.log(g(C)),m.aborted};try{if(!await i(t,!1)){let l=await Oc(e.cwd,e.profileName,t);if(l.length>0&&await i(l,!0),Yt(s))for(let d of vt(e.cwd,o?.scope?`/push ${o.scope}`:"/push --all"))console.log(q(d))}}catch(a){console.log(O(`Push run failed: ${a.message}`))}return console.log(""),{kind:"continue"}}async function Zi(e,t,n){let o=k0(e,n);if(o.length===0)return[];let r=new Set(Nc((await zi({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function Oc(e,t,n){try{let o=new Set(n),r=await zi({cwd:e,profileName:t});return Nc(r.entries).map(s=>s.path).filter(s=>o.has(s))}catch{return[]}}async function j0(e,t,n){try{let o=await S0({cwd:e,...t?{profileName:t}:{},relPath:n.replace(/\\/g,"/"),preview:!0});console.log(""),console.log(q(`${o.title}`)),console.log(g(`${o.path} \xB7 ${o.articleId?`updates article ${o.articleId}`:"would be created as a new article"}`)),o.shots.length>0&&console.log(g(`${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(g("\u2500".repeat(Math.min(80,Math.max(20,(process.stdout.columns??80)-1))))),console.log(o.body),console.log(g("\u2500".repeat(Math.min(80,Math.max(20,(process.stdout.columns??80)-1))))),console.log(g(`Nothing was sent. Run /push ${o.path} to save it as a draft.`))}catch(o){console.log(O(o.message))}return{kind:"continue"}}async function ea(e,t){let n=qe(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(O(n.reason)),{kind:"continue"};let o=e.includes(xt),r=e.includes(T0);if(e.includes("--preview")){let i=e.find(a=>!a.startsWith("--"));return i?await j0(t?.cwd??process.cwd(),t?.profileName,i):(console.log(O("Which article? Use /push --preview <path> \u2014 a preview is per article.")),{kind:"continue"})}let s=e[0];if(e.includes("--screenshots")||e.includes("--shots")){let i=t?.cwd??process.cwd(),a=e.find(S=>!S.startsWith("--")),l=_e(i),d=Ui(l,a);if(d.length===0){let S=l.filter(v=>v.state==="captured").length;return console.log(g(S>0?`${S} screenshot${S===1?" has":"s have"} been taken but the callouts aren't drawn on yet, so there is nothing to embed \u2014 /screenshot annotate finishes ${S===1?"it":"them"}.`:a?`No captured screenshots in ${a} \u2014 /push --screenshots covers the whole knowledge base.`:"No captured screenshots yet \u2014 /screenshot capture first.")),{kind:"continue"}}let m=Wi(l,a);m&&console.log(m);let w=Bi(l);w&&console.log(w);let k=Re("","--screenshots",a).trim();return await Wt(t??{cwd:process.cwd()},d,0,{skipReview:o,skipStyle:r,scope:k})}if(s==="--related"&&e[1]){if(!t)return{kind:"continue"};let i=await Zi(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return i.length===0?(console.log(q("\u2713 All related articles are already on Document360.")),{kind:"continue"}):await Wt(t,i,0,{skipReview:o,skipStyle:r,scope:`--related ${e[1]}`})}if(s==="--all"){console.log(g("Checking what needs pushing\u2026"));try{let i=await zi({cwd:t?.cwd??process.cwd()}),{clean:a,conflicts:l}=so(i.entries),d=Xi(i.entries),m=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&&!m&&console.log(G(cs(l.length)));let w=m?[...a,...l]:a;if(w.length===0){if(l.length>0){let S=nr(t?.cwd??process.cwd(),t?.profileName);return S&&console.log(g(S)),console.log(g("Resolve the conflicts: /resolve")),{kind:"continue"}}console.log(q(d>0?"\u2713 Nothing else is ahead of Document360 to push.":"\u2713 Nothing is ahead of Document360 \u2014 nothing to push."));let k=nr(t?.cwd??process.cwd(),t?.profileName);if(k&&console.log(g(k)),t)try{let S=bm(await ym({cwd:t.cwd,profileName:t.profileName,onRateLimit:C=>console.log(g(` Document360 rate limit \u2014 waiting ${Math.ceil(C.waitMs/1e3)}s\u2026`))}));S&&console.log(S.startsWith("\u26A0")?G(S):g(S));let v=$m(await km({cwd:t.cwd,profileName:t.profileName}));v&&console.log(g(v))}catch{}return{kind:"continue"}}return await Wt(t??{cwd:process.cwd()},w.map(k=>k.path),m?0:l.length,{skipReview:o,skipStyle:r,allowUnpullable:m})}catch(i){return console.log(O(`Could not compute sync status: ${i.message}`)),{kind:"continue"}}}if(s&&s.startsWith("--")&&(s=e.find(i=>!i.startsWith("--"))??""),!s){console.log(g("Checking what needs pushing\u2026"));let i,a=0;try{let l=await zi({cwd:t?.cwd??process.cwd()}),{clean:d,conflicts:m}=so(l.entries);i=d,a=m.length;let w=Xi(l.entries);if(w>0&&console.log(G(`\u26A0 ${w} article(s) already exist on Document360 but aren't linked \u2014 left out (pushing would duplicate them). Run /catch-up or ask me to link them first.`)),m.length>0&&console.log(G(cs(m.length))),i.length===0&&m.length>0)return console.log(g("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(l){return console.log(O(`Could not compute sync status: ${l.message}`)),console.log(g("Push a specific article: /push <article-path>")),{kind:"continue"}}if(i.length===0)return console.log(q("\u2713 Nothing is ahead of Document360 \u2014 nothing to push.")),console.log(g(" (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} ${g(`(${l.label})`)}`);return console.log(g("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(g("Cancelled.")),{kind:"continue"}}if(s==="--all")return await Wt(t,i.map(l=>l.path),a,{skipReview:o,skipStyle:r})}return await Wt(t??{cwd:process.cwd()},[s],0,{skipReview:o,skipStyle:r,scope:s})}se();import{select as L0}from"@inquirer/prompts";import{computeSyncStatus as O0,localAheadPaths as _0,pendingDrafts as M0,publishArticleLive as F0,publishGateVerdict as U0,publishGateLines as W0,resolveActiveProfile as nI,SKIP_STYLE_FLAG as B0,SKIP_SHOTS_FLAG as H0}from"document360-engine";var I0={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."},Rm=new Set;function ln(e){let t=I0[e.replace(/^\//,"")];return!t||Rm.has(e)?null:(Rm.add(e),t)}var G0=150,q0=e=>e>0?new Promise(t=>setTimeout(t,e)):Promise.resolve(),Mc=e=>e===1?"":"s",_c=e=>e.replace(/\\/g,"/").split("/").pop()??e;function Fc(e){return e.includes("--screenshots")||e.includes("--shots")||e[0]==="--related"}async function Uc(e,t,n){await O0({cwd:e,profileName:t});let o=n?n.replace(/\\/g,"/").replace(/\/+$/,""):null;return M0(e,t).filter(r=>!o||r.path===o||r.path.startsWith(`${o}/`)).map(r=>({...r,label:V0(e,r.path)}))}function V0(e,t){let n=Di(e,t)??rs(t),o=Ei(t),r=o?$n(o):"";return r?`${r} \u203A ${n}`:n}function Y0(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 Wc(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=_0(e,t).filter(a=>!s||a===s||a.startsWith(`${s}/`)).length;return i>0&&r.push(`${i} article${Mc(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 Bc(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 F0({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(G0)}return r}function Hc(e){let{published:t,blocked:n,failed:o}=e,r=[];if(t.length>0){r.push(`\u2713 ${t.length} article${Mc(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 ${_c(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 ${_c(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 Cm(e,t){let n=t?.cwd??process.cwd(),o=ln("publish");if(Fc(e))return o&&console.log(g(`\u2192 ${o}`)),console.log(g("Running /push\u2026")),ea(e,t);let r=qe(n,t?.profileName);if(!r.ok)return console.log(O(r.reason)),{kind:"continue"};o&&console.log(g(`\u2192 ${o}`));let s=e.includes(xt),i=e.includes(B0),a=e.includes(H0),l=e.includes("--all"),d=e.find(v=>!v.startsWith("--"));console.log(g("Checking what is waiting to go live\u2026"));let m;try{m=await Uc(n,t?.profileName,d)}catch(v){return console.log(O(`Could not check Document360: ${v.message}`)),{kind:"continue"}}if(m.length===0){for(let v of Wc(n,t?.profileName,d).lines)console.log(v.startsWith("\u2713")?q(v):g(v));return{kind:"continue"}}let w=U0(n,m.map(v=>v.path),{allowUnreviewed:s,allowStyleErrors:i,checkScreenshots:!0,allowPlaceholders:a});if(!w.clear){for(let v of W0(w,m.length,{scope:d,act:"publish"}))console.log(G(v));return{kind:"continue"}}console.log(""),console.log(`${m.length} draft${Mc(m.length)} ${m.length===1?"is":"are"} ahead of what readers see:`);for(let v of Y0(m.slice(0,12)))console.log(g(v));m.length>12&&console.log(g(` \u2026and ${m.length-12} more`)),console.log("");let k=m;if(!l){let v=await L0({message:"Publish live to your readers?",choices:[{name:`Yes \u2014 publish all ${m.length} live`,value:"all"},...m.slice(0,8).map(C=>({name:`Just ${C.label}`,value:C.path})),{name:"No \u2014 leave them as drafts",value:"none"}]});if(v==="none")return console.log(g("Left as drafts. Nothing changed.")),{kind:"continue"};v!=="all"&&(k=m.filter(C=>C.path===v))}let S=await Bc(n,t?.profileName,k,{skipReview:s,skipStyle:i,onProgress:(v,C,A)=>console.log(g(` \u25B8 ${v+1}/${C} ${_c(A)}\u2026`))});console.log("");for(let v of Hc(S))console.log(v.startsWith("\u2713")?q(v):v.startsWith("\u2717")?G(v):g(v));return{kind:"continue"}}import{loadKnownConflicts as K0,localArticleTitle as z0,resolveActiveProfile as X0}from"document360-engine";function Q0(e,t){let n=z0(e,t);return n||(t.split(/[\\/]/).pop()??t).replace(/\.md$/,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ")}function ta(e,t){let n=[];try{n=K0(e,X0(e,t).name)}catch{return null}if(n.length===0)return null;let o=n.length,r=n.slice(0,3).map(i=>Q0(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 or={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=ta(e.cwd,e.profileName);if(n)return{kind:"audit-blocked",note:n.note,lead:or}}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 J0}from"document360-engine";function Gc(){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 Sm(e,t){let n=t?.cwd??process.cwd();return J0(n)?{kind:"forward-to-agent",prompt:Gc(),display:"/discover"}:(console.log(O("No d360-writer config here. Run /init first.")),{kind:"continue"})}se();import{checkbox as Z0}from"@inquirer/prompts";import{inventoryRepo as ex,readProjectConfig as Pm,writeProjectConfig as tx}from"document360-engine";function qc(e,t){let n=Pm(e);n&&(n.authoritativeSourceFiles=t,tx(n,e))}function na(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 Tm(e,t){let n=t?.cwd??process.cwd();if(!Pm(n))return console.log(O("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=ex(n);if(o.length===0)return console.log(g('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(J("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${g(na(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>Z0({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${na(s)})`,value:s.path,checked:s.recommended})),pageSize:20}))}catch{return console.log(g("Cancelled.")),{kind:"continue"}}if(r.length===0)return console.log(g("Nothing selected \u2014 scope unchanged.")),{kind:"continue"};qc(n,r),console.log(q(`\u2713 Scoped to ${r.length} folder(s) \u2014 written to .d360-writer/config.json`));for(let s of r)console.log(` ${s}`);return console.log(""),{kind:"continue"}}se();import{confirm as dx}from"@inquirer/prompts";import{applyPull as zc,computeSyncStatus as Um,compareRemoteSources as px,planPull as Wm,planImport as hx,applyImport as fx,establishBaselines as mx,rebaselineServerMeta as gx,D360AuthError as wx}from"document360-engine";se();var Am=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /push <path>):",paint:O,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /push <path>:",paint:G,mark:"M"},{status:"remote-ahead",header:"Changed on Document360 \u2014 pull with /pull <path> (or just /pull):",paint:J,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:O,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:O,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint:be,mark:"X"},{status:"untracked-local",header:"New here \u2014 not on Document360 yet (publish to add them):",paint:g,mark:"?"},{status:"untracked-remote",header:"On Document360 \u2014 not in your local docs yet (run /pull to import them):",paint:g,mark:"?"},{status:"unknown-base",header:"Tracked, not yet compared \u2014 run /pull --baseline to set a baseline (or the next publish/pull sets one):",paint:be,mark:"\xB7"}];function nx(e){return e.path?e.path:`${e.title??"(untitled)"} ${be(`[${e.articleId}]`)}`}function ox(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 oa(e,t){let n=[],o=e.entries.filter(m=>m.link);if(o.length>0){n.push(""),n.push(Be("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let m of o)n.push(` ${G("~")} ${G(m.path??"")} ${be(`\u2192 "${m.link.title}"`)}`)}for(let m of Am){let w=e.entries.filter(k=>k.status===m.status&&!(m.status==="untracked-local"&&k.link));if(w.length!==0){n.push(""),n.push(Be(m.header));for(let k of w)n.push(` ${m.paint(m.mark)} ${m.paint(nx(k))}${k.detail?be(` (${k.detail})`):""}`)}}let r=e.counts["in-sync"]??0,s=e.entries.length;n.push("");let i={"in-sync":"up to date","local-ahead":"changed here","remote-ahead":"changed on Document360",conflict:"changed both places","untracked-local":"new here","untracked-remote":"only on Document360","deleted-local":"removed locally","deleted-remote":"gone from Document360",orphaned:"gone both sides","unknown-base":"not yet compared"},a=o.length,l=s===r?q("\u2713 everything up to date"):[r>0?q(`\u2713 ${r} up to date`):null,a>0?`${a} to link`:null,...Am.map(m=>{let w=(e.counts[m.status]??0)-(m.status==="untracked-local"?a:0);return w>0?`${w} ${i[m.status]}`:null})].filter(Boolean).join(be(" \xB7 ")),d=t!==void 0?` \xB7 synced in ${ox(t)}`:"";return n.push(l+be(` \xB7 ${s} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${d}`)),n}import{structuredPatch as rx}from"diff";import Em from"picocolors";var sx=80,rr=400,ix="\x1B[48;2;74;28;28m",ax="\x1B[48;2;24;66;24m",Dm="\x1B[49m",Vc=e=>String(e).padStart(5);function Nm(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}function jm(e,t,n){if(n===void 0||n<t-4)return e.slice(0,t);let o=Math.max(0,n-12);return`\u2026${e.slice(o).slice(0,Math.max(8,t-1))}`}function Rt(e,t,n,o=sx){let r=v=>{let C=v.replace(/\r\n/g,`
|
|
335
335
|
`);return C.endsWith(`
|
|
336
336
|
`)||C===""?C:C+`
|
|
337
|
-
`},s=r(e),i=r(t);if(s===i)return null;let a=Math.max(20,n-10),l=ox("a","b",s,i,"","",{context:3}),d=0,g=0,f=[];l.hunks.forEach(($,C)=>{C>0&&f.push(Em.gray(" \u2026"));let A=$.oldStart,D=$.newStart,L=[],B=[],M=()=>{for(let X=0;X<L.length;X++){let z=X<B.length?Nm(L[X],B[X]):void 0;g++,f.push(`${sx}${Gc(A++)} - ${jm(L[X],a,z)}${Dm}`)}for(let X=0;X<B.length;X++){let z=X<L.length?Nm(L[X],B[X]):void 0;d++,f.push(`${ix}${Gc(D++)} + ${jm(B[X],a,z)}${Dm}`)}L=[],B=[]};for(let X of $.lines){let z=X[0],de=X.slice(1);z==="-"?L.push(de):z==="+"?B.push(de):(M(),f.push(Em.gray(Gc(D))+" "+de.slice(0,a)),A++,D++)}M()});let x=Math.max(1,o),P=f.slice(0,x);return{added:d,removed:g,lines:P,hidden:Math.max(0,f.length-x)}}import{select as _m}from"@inquirer/prompts";import{applyPull as Mm,computeSyncStatus as ax,isPullWouldBlankError as Lm,localArticleTitle as lx,planPull as Om}from"document360-engine";function oa(){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 ra(){return"Publish your copy over the portal (settles it) \xB7 Skip?"}function Im(){return"(l publish yours \xB7 s skip \u2014 anything else stops, keeping your answers so far)"}function sa(e){if(e.length===0)return[];let t=e.length,n=e.slice(0,3).join(", ")+(t>3?`, +${t-3} more`:"");return[`${t} article${t===1?"":"s"} stay${t===1?"s":""} flagged \u2014 Document360 cannot hand ${t===1?"its":"their"} markdown back: ${n}`,"Two ways out: run /resolve and press l to publish your copy over the portal, or ask your Document360 admin to move the article back to the Markdown (Editor 3.0) editor, then run /resolve again."]}function qc(e){return`Cannot take the portal copy of ${e} \u2014 Document360 will not return it as markdown. Left as it was.`}se();var ia=e=>e===1?"":"s";async function Vc(e,t,n=1){console.log(""),console.log(`${J("\u25CF")} ${Be(t.title)} ${be(`(${t.path})`)}`);for(let i of t.notes)console.log(G(` \u26A0 ${i}`));let o=Rt(t.oldContent,t.newContent,Math.max(40,(process.stdout.columns??80)-1),rr);if(o){console.log(be(` \u23BF local \u2192 portal: +${o.added} / -${o.removed} line${ia(o.added+o.removed)}`));for(let i of o.lines)console.log(i);o.hidden>0&&console.log(w(` \u2026 +${o.hidden} more diff lines`))}else console.log(w(" Local already matches the portal content \u2014 resolving just advances the sync base."));let r=n>1,s=await e.withPausedInput(()=>_m({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"?(Mm({cwd:e.cwd,profileName:e.profileName},t),console.log(q(" \u2713 Took the portal copy (local overwritten, sync base advanced).")),"took-portal"):s==="local"?"keep-local":s==="skip"?(console.log(w(" Skipped \u2014 still a conflict.")),"skipped"):s==="local-all"?"keep-local-all":s==="portal-all"?"took-portal-all":"skipped-all"}async function cx(e,t){console.log(""),console.log(`${J("\u25CF")} ${Be(lx(e.cwd,t)??t)} ${be(`(${t})`)}`);for(let o of oa())console.log(G(` \u26A0 ${o}`));return await e.withPausedInput(()=>_m({message:ra(),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(w(" Skipped \u2014 still a conflict.")),"skipped")}async function Fm(e,t){let n=qe(t.cwd,t.profileName);if(!n.ok)return console.log(O(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let s=(await ax({cwd:t.cwd,profileName:t.profileName})).entries.filter(l=>l.status==="conflict"&&l.path).map(l=>l.path);if(o){if(!s.includes(o))return console.log(q(`${o} isn't in conflict \u2014 nothing to resolve.`)),{kind:"continue"};s=[o]}if(s.length===0)return console.log(q("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let i=[],a=[];for(let[l,d]of s.entries()){let g;try{g=await Om({cwd:t.cwd,profileName:t.profileName,relPath:d})}catch(P){if(!Lm(P))throw P;await cx(t,d)==="keep-local"?i.push(d):a.push(d);continue}let f=await Vc(t,g,s.length-l);if(f==="keep-local"&&i.push(d),!f.endsWith("-all"))continue;let x=s.slice(l);if(f==="keep-local-all")i.push(...x),console.log(w(` Keeping local for all ${x.length} \u2014 publishing them over the portal.`));else if(f==="took-portal-all"){let P=0;for(let $ of x)try{Mm({cwd:t.cwd,profileName:t.profileName},await Om({cwd:t.cwd,profileName:t.profileName,relPath:$})),P++}catch(C){console.log(O(` \u2717 ${$}: ${C.message}`)),Lm(C)&&a.push($)}console.log(q(` \u2713 Took the portal copy of ${P} article${ia(P)} (local overwritten, sync base advanced).`))}else console.log(w(` Skipped all ${x.length} \u2014 still conflict${ia(x.length)}.`));break}for(let l of sa(a))console.log(G(`\u26A0 ${l}`));if(i.length>0)return console.log(w(`Publishing ${i.length} kept-local article${ia(i.length)} over the portal\u2026`)),await Wt(t,i,0,{allowUnpullable:!0})}catch(r){console.log(O(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function Bm(e,t){let n=qe(t.cwd,t.profileName);if(!n.ok)return console.log(O(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await wx(t),{kind:"continue"};if(o==="--baseline")return await yx(t,e.filter(i=>i!=="--baseline")),{kind:"continue"};if(o==="--compare")return await bx(t),{kind:"continue"};if(o)return console.log(O(`Unknown option: ${o}`)),console.log(w("Usage: /pull pull portal edits + import new portal articles")),console.log(w(" /pull <path> pull one article (or resolve a conflict)")),console.log(w(" /pull --status drift report only (no writes)")),console.log(w(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await kx(t,r),{kind:"continue"};console.log(w("Pulling changes from Document360\u2026"));let s=await Kc({cwd:t.cwd,profileName:t.profileName});for(let i of zc(s))console.log(i.tone==="ok"?q(i.text):i.tone==="warn"?G(i.text):w(i.text));console.log("")}catch(r){r instanceof gx?console.log(O(r.message)):console.log(O(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function Kc(e){let t=await Um({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 Wm({cwd:e.cwd,profileName:e.profileName,relPath:o.path});Yc({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 px({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});hx({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 aa=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,io=e=>e===1?"":"s";function zc(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${io(e.pulled.length)} into local: ${aa(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${io(e.imported.length)}: ${aa(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${io(e.toPublish)} changed locally \u2014 /push saves them to Document360.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${io(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). (${aa(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${io(e.failed.length)} failed: ${aa(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 wx(e){console.log(w("Checking Document360 for drift\u2026"));let t=Date.now(),n=await Um({cwd:e.cwd,profileName:e.profileName});for(let o of na(n,Date.now()-t))console.log(o);console.log("")}async function yx(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(w(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await fx({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await mx({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(q("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(q(`\u2713 Recorded ${o.baselined.length} article(s) as matching Document360 \u2014 they read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(q(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(G(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(w(` - ${s.path} (${s.reason})`))}}async function bx(e){console.log(w("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await dx({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${Be(String(t.legacyCount))} \xB7 Manifest: ${Be(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(q("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(O(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(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(w(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function kx(e,t){let n=t.replace(/\\/g,"/"),o=await Wm({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await Vc(e,o)==="keep-local"&&(console.log(w(`Publishing ${o.path} over the portal\u2026`)),await Wt(e,[o.path]));return}console.log(""),console.log(`${J("\u25CF")} ${Be(o.title)} ${be(`(${o.path})`)}`);for(let i of o.notes)console.log(G(` \u26A0 ${i}`));let r=Rt(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1),rr);if(!r){console.log(w(" Local file already matches the remote content \u2014 advancing the sync base only.")),Yc({cwd:e.cwd,profileName:e.profileName},o);return}console.log(be(` \u23BF Added ${r.added} line${io(r.added)}, removed ${r.removed} line${io(r.removed)}`));for(let i of r.lines)console.log(i);if(r.hidden>0&&console.log(w(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>ux({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(w(" Skipped."));return}Yc({cwd:e.cwd,profileName:e.profileName},o),console.log(q(` \u2713 Pulled ${o.path} (sync base advanced).`))}se();import{statSync as Nx}from"node:fs";import{resolve as jx}from"node:path";import{estimateBulkCost as Ix,planPartitions as Lx,readProjectConfig as Ox,resolveModelForOperation as _x,runPartitioned as Mx,trackedArticlePaths as Fx}from"document360-engine";function Cn(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 Hm(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 sr=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 la(e,t){let n=t-e;return n>=300&&n>=t*.2}function Ct(e,t,n,o=Date.now(),r){let s=t.reduce((a,l)=>a+(l.inputTokens??0),0),i=t.reduce((a,l)=>a+(l.cacheReadTokens??0),0);return{seconds:Math.max(0,Math.round((o-e)/1e3)),outputTokens:t.reduce((a,l)=>a+l.outputTokens,0),inputTokens:s,...s>0?{cachedPct:Math.round(i/s*100)}:{},...r!==void 0?{activeSeconds:r}:{},costUsd:n}}function $x(e){return e.activeSeconds!==void 0&&la(e.activeSeconds,e.seconds)?`${Xc(e.seconds)} elapsed \xB7 ${Xc(e.activeSeconds)} working`:Xc(e.seconds)}var Gm=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:`${e}`,Xc=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 Kt(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 ${$x(e)}, ${Gm(e.inputTokens)}\u2192${Gm(e.outputTokens)} tokens${t}${n})`}import ge from"picocolors";import eu from"wrap-ansi";import tu from"string-width";se();import Sn from"picocolors";import ua from"wrap-ansi";import ca from"string-width";var ao=[{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:"roadmap",usage:"/roadmap [--all | done [step]]",desc:"Show the docs campaign (the multi-session plan the agent maintains), grouped by the part of the job \u2014 progress + next step; `--all` also lists the steps a later pass replaced; `done` marks the next open step finished (add words from a title to pick another)",group:"docs"},{name:"audit",usage:"/audit [--auto on|off]",desc:"Gap analysis: code vs docs vs Document360 (what changed); --auto runs it at launch when code changed",group:"publish"},{name:"inbox",usage:"/inbox",desc:"Act on messages from the repo's coding agent (requests to document, answers to your questions)",group:"publish"},{name:"ask",usage:"/ask <question>",desc:"Ask your developers something the code cannot tell you: why a feature exists, when to use it, whether it can be undone",group:"publish"},{name:"share",usage:"/share [status|on|off]",desc:"Share your docs work with the team: get your builder's latest, then save + send yours (runs automatically; `off` leaves it to your coding agent)",group:"publish"},{name:"catch-up",usage:"/catch-up [--push]",desc:"Process ALL pending work (builder hints + requests + Document360 portal drift) \u2192 write \u2192 save to Document360 as drafts. --push does that last step for you, which still needs an editorial review first. For code changes, that's /audit",group:"publish"},{name:"comments",usage:"/comments [<article>] [--scope <category>] [--answer] [--all] [--resolve] [--answered] [--full]",desc:"Reviewer comments left on passages of your articles in the Document360 portal \u2014 bare: a table by article, pick a number to read its comments in full, then answer or go back; --answer: fix, push the draft, reply (threads stay open unless you add --resolve); --full re-reads every article",group:"publish"},{name:"pull",usage:"/pull [<path> | --status | --baseline]",desc:"Bring Document360 down: pull portal edits + import NEW portal articles. --status: drift report only \xB7 --baseline: set a sync base \xB7 <path>: one article / resolve a conflict",group:"publish"},{name:"resolve",usage:"/resolve [<path>]",desc:"Resolve conflicts (edited both here and on the portal): shows the diff, then keep local (push), take portal (pull), or skip \u2014 per article, or one answer for all remaining. Bare: walk them all",group:"publish"},{name:"convert",usage:"/convert [--scope <folder>] [--run]",desc:"Convert tracked articles to DFM (one-off legacy migration)",group:"publish"},{name:"profile",usage:"/profile [name|add <name> [env]]",desc:"Switch/create a Document360 connection (picker; s = session)",group:"setup"},{name:"workspace",usage:"/workspace [name]",desc:"Switch the Document360 workspace (picker)",group:"setup"},{name:"model",usage:"/model [name|default]",desc:"Set the Claude model for d360-writer",group:"setup"},{name:"verbose",usage:"/verbose [on|off]",desc:"Show the raw transcript \u2014 every tool call with its file path and full result, instead of article-shaped cards with my bookkeeping collapsed (bare: toggle)",group:"setup"},{name:"logout",usage:"/logout [--all-projects]",desc:"Sign out of this project + clear its workspace selection (then /login to re-pick)",group:"setup"},{name:"allow-prod",usage:"/allow-prod",desc:"Authorize writes to a production profile",group:"setup"},{name:"doctor",usage:"/doctor",desc:"Health-check: auth, profile, workspace, map, API, and a real agent turn",group:"setup"},{name:"logs",usage:"/logs",desc:"Show the most recent problem d360-writer recorded, and where the logs are \u2014 press c to copy it for the team",group:"setup"},{name:"update",usage:"/update",desc:"Update d360-writer \u2014 and d360-capture when installed \u2014 to the latest versions (then relaunch)",group:"setup"},{name:"feedback",usage:"/feedback",desc:"Copy the repo's open d360-writer tool-feedback to your clipboard, to relay to the d360-writer team",group:"setup"},{name:"reset",usage:"/reset",desc:"[DANGER] Delete all d360-writer files (docs, config, screenshots); types repo name to confirm",group:"setup"},{name:"resume",usage:"/resume [name]",desc:"Resume a session (no arg lists them)",group:"session"},{name:"rename",usage:"/rename [name]",desc:"Name the session (no arg: suggest one)",group:"session"},{name:"clear",usage:"/clear",desc:"Clear the screen + reset the conversation (resumable)",group:"session"},{name:"help",usage:"/help",desc:"Show this help",group:"session"},{name:"exit",usage:"/exit",desc:"Quit",group:"session"}],qm={"/catch-up":"write up everything your builder flagged","/audit":"check the code for anything new or missing in the docs","/discover":"interview your builder so the docs are grounded in the real product","/pull":"pull edits + new articles from Document360","/push":"save your articles to Document360 as drafts","/publish":"take the signed-off drafts live to your readers","/write":"author the planned articles","/draft":"plan articles from PRDs + the code","/login":"sign in to Document360","/workspace":"choose the Document360 workspace","/project":"choose the Document360 project","/scope":"choose which folders back the docs","/genre":"set this repo's product type (picks the docs playbook)","/init":"set up this repo","/screenshot":"work the screenshot pipeline (author specs, take shots, draw the callouts)","/doctor":"run a health check","/logs":"show the last problem, and copy it for the team","/style-guide":"choose the writing rules your docs are held to","/lint":"check the docs against those rules (costs nothing)"};function Vm(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(qm[n])return qm[n];let o=ao.find(r=>r.name===t);return o?o.desc:""}function Ym(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return ao.filter(n=>n.name.startsWith(t))}function Km(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 vx=new RegExp(`^\\s*/(?:${ao.map(e=>e.name).join("|")})(?:\\s|$)`),zm=e=>vx.test(e),Xm=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Qm=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),Jm=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function xx(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(Xm(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&Qm(t[o+1])){let a=Jm(r);o+=2;let l=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)l.push(Jm(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(zm(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])&&!zm(t[o])&&!Xm(t[o])&&!(t[o].includes("|")&&o+1<t.length&&Qm(t[o+1]));)i.push(t[o++]);n.push({kind:"para",text:i.join(" ")})}return n}function
|
|
339
|
-
`).map(D=>
|
|
340
|
-
`)?
|
|
341
|
-
`).flatMap(ve=>
|
|
342
|
-
`)):
|
|
343
|
-
`)}),B=Math.max(...L.map(z=>z.length)),M=[],X=(z,de,ye)=>o.align?.[ye]==="right"?" ".repeat(Math.max(0,de-
|
|
344
|
-
`)},C=[
|
|
345
|
-
`)}function
|
|
337
|
+
`},s=r(e),i=r(t);if(s===i)return null;let a=Math.max(20,n-10),l=rx("a","b",s,i,"","",{context:3}),d=0,m=0,w=[];l.hunks.forEach((v,C)=>{C>0&&w.push(Em.gray(" \u2026"));let A=v.oldStart,D=v.newStart,L=[],B=[],M=()=>{for(let X=0;X<L.length;X++){let z=X<B.length?Nm(L[X],B[X]):void 0;m++,w.push(`${ix}${Vc(A++)} - ${jm(L[X],a,z)}${Dm}`)}for(let X=0;X<B.length;X++){let z=X<L.length?Nm(L[X],B[X]):void 0;d++,w.push(`${ax}${Vc(D++)} + ${jm(B[X],a,z)}${Dm}`)}L=[],B=[]};for(let X of v.lines){let z=X[0],de=X.slice(1);z==="-"?L.push(de):z==="+"?B.push(de):(M(),w.push(Em.gray(Vc(D))+" "+de.slice(0,a)),A++,D++)}M()});let k=Math.max(1,o),S=w.slice(0,k);return{added:d,removed:m,lines:S,hidden:Math.max(0,w.length-k)}}import{select as _m}from"@inquirer/prompts";import{applyPull as Mm,computeSyncStatus as lx,isPullWouldBlankError as Lm,localArticleTitle as cx,planPull as Om}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 Im(){return"(l publish yours \xB7 s skip \u2014 anything else stops, keeping your answers so far)"}function ia(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 Yc(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 Kc(e,t,n=1){console.log(""),console.log(`${J("\u25CF")} ${Be(t.title)} ${be(`(${t.path})`)}`);for(let i of t.notes)console.log(G(` \u26A0 ${i}`));let o=Rt(t.oldContent,t.newContent,Math.max(40,(process.stdout.columns??80)-1),rr);if(o){console.log(be(` \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(g(` \u2026 +${o.hidden} more diff lines`))}else console.log(g(" Local already matches the portal content \u2014 resolving just advances the sync base."));let r=n>1,s=await e.withPausedInput(()=>_m({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"?(Mm({cwd:e.cwd,profileName:e.profileName},t),console.log(q(" \u2713 Took the portal copy (local overwritten, sync base advanced).")),"took-portal"):s==="local"?"keep-local":s==="skip"?(console.log(g(" Skipped \u2014 still a conflict.")),"skipped"):s==="local-all"?"keep-local-all":s==="portal-all"?"took-portal-all":"skipped-all"}async function ux(e,t){console.log(""),console.log(`${J("\u25CF")} ${Be(cx(e.cwd,t)??t)} ${be(`(${t})`)}`);for(let o of ra())console.log(G(` \u26A0 ${o}`));return await e.withPausedInput(()=>_m({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(g(" Skipped \u2014 still a conflict.")),"skipped")}async function Fm(e,t){let n=qe(t.cwd,t.profileName);if(!n.ok)return console.log(O(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let s=(await lx({cwd:t.cwd,profileName:t.profileName})).entries.filter(l=>l.status==="conflict"&&l.path).map(l=>l.path);if(o){if(!s.includes(o))return console.log(q(`${o} isn't in conflict \u2014 nothing to resolve.`)),{kind:"continue"};s=[o]}if(s.length===0)return console.log(q("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let i=[],a=[];for(let[l,d]of s.entries()){let m;try{m=await Om({cwd:t.cwd,profileName:t.profileName,relPath:d})}catch(S){if(!Lm(S))throw S;await ux(t,d)==="keep-local"?i.push(d):a.push(d);continue}let w=await Kc(t,m,s.length-l);if(w==="keep-local"&&i.push(d),!w.endsWith("-all"))continue;let k=s.slice(l);if(w==="keep-local-all")i.push(...k),console.log(g(` Keeping local for all ${k.length} \u2014 publishing them over the portal.`));else if(w==="took-portal-all"){let S=0;for(let v of k)try{Mm({cwd:t.cwd,profileName:t.profileName},await Om({cwd:t.cwd,profileName:t.profileName,relPath:v})),S++}catch(C){console.log(O(` \u2717 ${v}: ${C.message}`)),Lm(C)&&a.push(v)}console.log(q(` \u2713 Took the portal copy of ${S} article${aa(S)} (local overwritten, sync base advanced).`))}else console.log(g(` Skipped all ${k.length} \u2014 still conflict${aa(k.length)}.`));break}for(let l of ia(a))console.log(G(`\u26A0 ${l}`));if(i.length>0)return console.log(g(`Publishing ${i.length} kept-local article${aa(i.length)} over the portal\u2026`)),await Wt(t,i,0,{allowUnpullable:!0})}catch(r){console.log(O(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function Bm(e,t){let n=qe(t.cwd,t.profileName);if(!n.ok)return console.log(O(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await yx(t),{kind:"continue"};if(o==="--baseline")return await bx(t,e.filter(i=>i!=="--baseline")),{kind:"continue"};if(o==="--compare")return await kx(t),{kind:"continue"};if(o)return console.log(O(`Unknown option: ${o}`)),console.log(g("Usage: /pull pull portal edits + import new portal articles")),console.log(g(" /pull <path> pull one article (or resolve a conflict)")),console.log(g(" /pull --status drift report only (no writes)")),console.log(g(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await $x(t,r),{kind:"continue"};console.log(g("Pulling changes from Document360\u2026"));let s=await Xc({cwd:t.cwd,profileName:t.profileName});for(let i of Qc(s))console.log(i.tone==="ok"?q(i.text):i.tone==="warn"?G(i.text):g(i.text));console.log("")}catch(r){r instanceof wx?console.log(O(r.message)):console.log(O(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function Xc(e){let t=await Um({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 Wm({cwd:e.cwd,profileName:e.profileName,relPath:o.path});zc({cwd:e.cwd,profileName:e.profileName},r),n.pulled.push(o.path)}catch(r){n.failed.push({ref:o.path,error:r.message})}else if(o.status==="untracked-remote"&&o.articleId)try{let r=await hx({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});fx({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 la=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,io=e=>e===1?"":"s";function Qc(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${io(e.pulled.length)} into local: ${la(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${io(e.imported.length)}: ${la(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${io(e.toPublish)} changed locally \u2014 /push saves them to Document360.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${io(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). (${la(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${io(e.failed.length)} failed: ${la(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 yx(e){console.log(g("Checking Document360 for drift\u2026"));let t=Date.now(),n=await Um({cwd:e.cwd,profileName:e.profileName});for(let o of oa(n,Date.now()-t))console.log(o);console.log("")}async function bx(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(g(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await mx({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await gx({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(q("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(q(`\u2713 Recorded ${o.baselined.length} article(s) as matching Document360 \u2014 they read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(q(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(G(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(g(` - ${s.path} (${s.reason})`))}}async function kx(e){console.log(g("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await px({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${Be(String(t.legacyCount))} \xB7 Manifest: ${Be(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(q("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(O(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(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(g(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function $x(e,t){let n=t.replace(/\\/g,"/"),o=await Wm({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await Kc(e,o)==="keep-local"&&(console.log(g(`Publishing ${o.path} over the portal\u2026`)),await Wt(e,[o.path]));return}console.log(""),console.log(`${J("\u25CF")} ${Be(o.title)} ${be(`(${o.path})`)}`);for(let i of o.notes)console.log(G(` \u26A0 ${i}`));let r=Rt(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1),rr);if(!r){console.log(g(" Local file already matches the remote content \u2014 advancing the sync base only.")),zc({cwd:e.cwd,profileName:e.profileName},o);return}console.log(be(` \u23BF Added ${r.added} line${io(r.added)}, removed ${r.removed} line${io(r.removed)}`));for(let i of r.lines)console.log(i);if(r.hidden>0&&console.log(g(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>dx({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(g(" Skipped."));return}zc({cwd:e.cwd,profileName:e.profileName},o),console.log(q(` \u2713 Pulled ${o.path} (sync base advanced).`))}se();import{statSync as jx}from"node:fs";import{resolve as Ix}from"node:path";import{estimateBulkCost as Lx,planPartitions as Ox,readProjectConfig as _x,resolveModelForOperation as Mx,runPartitioned as Fx,trackedArticlePaths as Ux}from"document360-engine";function Cn(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 Hm(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 sr=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 ca(e,t){let n=t-e;return n>=300&&n>=t*.2}function Ct(e,t,n,o=Date.now(),r){let s=t.reduce((a,l)=>a+(l.inputTokens??0),0),i=t.reduce((a,l)=>a+(l.cacheReadTokens??0),0);return{seconds:Math.max(0,Math.round((o-e)/1e3)),outputTokens:t.reduce((a,l)=>a+l.outputTokens,0),inputTokens:s,...s>0?{cachedPct:Math.round(i/s*100)}:{},...r!==void 0?{activeSeconds:r}:{},costUsd:n}}function vx(e){return e.activeSeconds!==void 0&&ca(e.activeSeconds,e.seconds)?`${Jc(e.seconds)} elapsed \xB7 ${Jc(e.activeSeconds)} working`:Jc(e.seconds)}var Gm=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:`${e}`,Jc=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 Kt(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 ${vx(e)}, ${Gm(e.inputTokens)}\u2192${Gm(e.outputTokens)} tokens${t}${n})`}import ge from"picocolors";import nu from"wrap-ansi";import ou from"string-width";se();import Sn from"picocolors";import da from"wrap-ansi";import ua from"string-width";var ao=[{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:"roadmap",usage:"/roadmap [--all | done [step]]",desc:"Show the docs campaign (the multi-session plan the agent maintains), grouped by the part of the job \u2014 progress + next step; `--all` also lists the steps a later pass replaced; `done` marks the next open step finished (add words from a title to pick another)",group:"docs"},{name:"audit",usage:"/audit [--auto on|off]",desc:"Gap analysis: code vs docs vs Document360 (what changed); --auto runs it at launch when code changed",group:"publish"},{name:"inbox",usage:"/inbox",desc:"Act on messages from the repo's coding agent (requests to document, answers to your questions)",group:"publish"},{name:"ask",usage:"/ask <question>",desc:"Ask your developers something the code cannot tell you: why a feature exists, when to use it, whether it can be undone",group:"publish"},{name:"share",usage:"/share [status|on|off]",desc:"Share your docs work with the team: get your builder's latest, then save + send yours (runs automatically; `off` leaves it to your coding agent)",group:"publish"},{name:"catch-up",usage:"/catch-up [--push]",desc:"Process ALL pending work (builder hints + requests + Document360 portal drift) \u2192 write \u2192 save to Document360 as drafts. --push does that last step for you, which still needs an editorial review first. For code changes, that's /audit",group:"publish"},{name:"comments",usage:"/comments [<article>] [--scope <category>] [--answer] [--all] [--resolve] [--answered] [--full]",desc:"Reviewer comments left on passages of your articles in the Document360 portal \u2014 bare: a table by article, pick a number to read its comments in full, then answer or go back; --answer: fix, push the draft, reply (threads stay open unless you add --resolve); --full re-reads every article",group:"publish"},{name:"pull",usage:"/pull [<path> | --status | --baseline]",desc:"Bring Document360 down: pull portal edits + import NEW portal articles. --status: drift report only \xB7 --baseline: set a sync base \xB7 <path>: one article / resolve a conflict",group:"publish"},{name:"resolve",usage:"/resolve [<path>]",desc:"Resolve conflicts (edited both here and on the portal): shows the diff, then keep local (push), take portal (pull), or skip \u2014 per article, or one answer for all remaining. Bare: walk them all",group:"publish"},{name:"convert",usage:"/convert [--scope <folder>] [--run]",desc:"Convert tracked articles to DFM (one-off legacy migration)",group:"publish"},{name:"profile",usage:"/profile [name|add <name> [env]]",desc:"Switch/create a Document360 connection (picker; s = session)",group:"setup"},{name:"workspace",usage:"/workspace [name]",desc:"Switch the Document360 workspace (picker)",group:"setup"},{name:"model",usage:"/model [name|default]",desc:"Set the Claude model for d360-writer",group:"setup"},{name:"verbose",usage:"/verbose [on|off]",desc:"Show the raw transcript \u2014 every tool call with its file path and full result, instead of article-shaped cards with my bookkeeping collapsed (bare: toggle)",group:"setup"},{name:"logout",usage:"/logout [--all-projects]",desc:"Sign out of this project + clear its workspace selection (then /login to re-pick)",group:"setup"},{name:"allow-prod",usage:"/allow-prod",desc:"Authorize writes to a production profile",group:"setup"},{name:"doctor",usage:"/doctor",desc:"Health-check: auth, profile, workspace, map, API, and a real agent turn",group:"setup"},{name:"logs",usage:"/logs",desc:"Show the most recent problem d360-writer recorded, and where the logs are \u2014 press c to copy it for the team",group:"setup"},{name:"update",usage:"/update",desc:"Update d360-writer \u2014 and d360-capture when installed \u2014 to the latest versions (then relaunch)",group:"setup"},{name:"feedback",usage:"/feedback",desc:"Copy the repo's open d360-writer tool-feedback to your clipboard, to relay to the d360-writer team",group:"setup"},{name:"reset",usage:"/reset",desc:"[DANGER] Delete all d360-writer files (docs, config, screenshots); types repo name to confirm",group:"setup"},{name:"resume",usage:"/resume [name]",desc:"Resume a session (no arg lists them)",group:"session"},{name:"rename",usage:"/rename [name]",desc:"Name the session (no arg: suggest one)",group:"session"},{name:"clear",usage:"/clear",desc:"Clear the screen + reset the conversation (resumable)",group:"session"},{name:"help",usage:"/help",desc:"Show this help",group:"session"},{name:"exit",usage:"/exit",desc:"Quit",group:"session"}],qm={"/catch-up":"write up everything your builder flagged","/audit":"check the code for anything new or missing in the docs","/discover":"interview your builder so the docs are grounded in the real product","/pull":"pull edits + new articles from Document360","/push":"save your articles to Document360 as drafts","/publish":"take the signed-off drafts live to your readers","/write":"author the planned articles","/draft":"plan articles from PRDs + the code","/login":"sign in to Document360","/workspace":"choose the Document360 workspace","/project":"choose the Document360 project","/scope":"choose which folders back the docs","/genre":"set this repo's product type (picks the docs playbook)","/init":"set up this repo","/screenshot":"work the screenshot pipeline (author specs, take shots, draw the callouts)","/doctor":"run a health check","/logs":"show the last problem, and copy it for the team","/style-guide":"choose the writing rules your docs are held to","/lint":"check the docs against those rules (costs nothing)"};function Vm(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(qm[n])return qm[n];let o=ao.find(r=>r.name===t);return o?o.desc:""}function Ym(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return ao.filter(n=>n.name.startsWith(t))}function Km(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 xx=new RegExp(`^\\s*/(?:${ao.map(e=>e.name).join("|")})(?:\\s|$)`),zm=e=>xx.test(e),Xm=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Qm=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),Jm=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function Rx(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(Xm(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&Qm(t[o+1])){let a=Jm(r);o+=2;let l=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)l.push(Jm(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(zm(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])&&!zm(t[o])&&!Xm(t[o])&&!(t[o].includes("|")&&o+1<t.length&&Qm(t[o+1]));)i.push(t[o++]);n.push({kind:"para",text:i.join(" ")})}return n}function Zc(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?Sn.bold(t.slice(2,-2)):t.startsWith("`")?J(t.slice(1,-1)):Sn.italic(t.slice(1,-1)))}var Cx=(e,t)=>e+" ".repeat(Math.max(0,t-ua(e)));function hs(e,t,n,o={}){return Zm(e,t,n,o)}function Zm(e,t,n,o={}){let r=e.length,s=A=>Math.max(0,...A.split(`
|
|
339
|
+
`).map(D=>ua(D))),i=e.map((A,D)=>Math.max(ua(A),...t.map(L=>s(L[D]??"")))),a=Math.max(24,n),l=3*r+1,d=[...i],m=()=>d.reduce((A,D)=>A+D,0)+l,w=0;for(;m()>a&&w++<1e4;){let A=-1,D=6;for(let L=0;L<r;L++)d[L]>D&&(D=d[L],A=L);if(A===-1)break;d[A]-=1}let k=(A,D,L)=>Sn.gray(A+d.map(B=>"\u2500".repeat(B+2)).join(D)+L),S=Sn.gray("\u2502"),v=(A,D)=>{let L=d.map((z,de)=>{let ye=A[de]??"",Se=D?Sn.bold(ye):o.plain?ye:Zc(ye);return ye.includes(`
|
|
340
|
+
`)?Se.split(`
|
|
341
|
+
`).flatMap(ve=>da(ve,z,{hard:!0}).split(`
|
|
342
|
+
`)):da(Se,z,{hard:!0}).split(`
|
|
343
|
+
`)}),B=Math.max(...L.map(z=>z.length)),M=[],X=(z,de,ye)=>o.align?.[ye]==="right"?" ".repeat(Math.max(0,de-ua(z)))+z:Cx(z,de);for(let z=0;z<B;z++)M.push(d.map((de,ye)=>`${S} ${X(L[ye][z]??"",de,ye)} `).join("")+S);return M.join(`
|
|
344
|
+
`)},C=[k("\u250C","\u252C","\u2510"),v(e,!0)];return C.push(t.length===0?k("\u2514","\u2534","\u2518"):k("\u251C","\u253C","\u2524")),t.forEach((A,D)=>{C.push(v(A,!1)),C.push(D===t.length-1?k("\u2514","\u2534","\u2518"):k("\u251C","\u253C","\u2524"))}),C.join(`
|
|
345
|
+
`)}function Sx(e,t){switch(e.kind){case"heading":return Sn.bold(e.text);case"hr":return Sn.gray("\u2500".repeat(t));case"para":return da(Zc(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]=da(Zc(o.text),Math.max(10,t-s.length)).split(`
|
|
346
346
|
`);return` ${r} ${i}`+a.map(l=>`
|
|
347
347
|
${s}${l}`).join("")}).join(`
|
|
348
348
|
`)}case"code":return e.lines.map(n=>Sn.gray(" "+n)).join(`
|
|
349
|
-
`);case"table":return Zm(e.header,e.rows,t)}}function
|
|
349
|
+
`);case"table":return Zm(e.header,e.rows,t)}}function eu(e,t){let n=Math.max(20,t);return Rx(e).map(o=>Sx(o,n)).join(`
|
|
350
350
|
|
|
351
|
-
`)}se();import
|
|
352
|
-
`);let r=2,s=3,i=
|
|
353
|
-
`);let l=Math.max(0,Math.floor((n.length-o.length)/2)),d=[];for(let
|
|
354
|
-
`)}var
|
|
355
|
-
`).flatMap(d=>
|
|
351
|
+
`)}se();import Px from"picocolors";var Tx=[127,86,217],Ax=[22,38,43],eg={T:Tx,E:Ax},fs=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],tu=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,Ex=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function tg(){if(!Px.isColorSupported)return[];let e=fs[0].length,t=[];for(let n=0;n<fs.length;n+=2){let o="";for(let r=0;r<e;r++){let s=eg[fs[n][r]],i=n+1<fs.length?eg[fs[n+1][r]]:void 0;s&&i?o+=`${tu(s)}${Ex(i)}\u2580\x1B[49m\x1B[39m`:s?o+=`${tu(s)}\u2580\x1B[39m`:i?o+=`${tu(i)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function ms(e){let t=n=>n.toFixed(1).endsWith(".0")?n.toFixed(0):n.toFixed(1);return e<1e3?String(e):e<1e6?`${t(e/1e3)}k`:`${t(e/1e6)}M`}function Pn(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function og(e,t,n){let o=e>0&&e<=n?e:t;return Math.max(0,Math.floor((n-o)/1e3))}function St(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function ar(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var ir=(e,t)=>` ${e.padEnd(13)}${t}`;function Dx(e,t){let n=[Jr("\u270E document360-writer")+ge.gray(` v${e.version} \xB7 engine v${e.engineVersion}${e.captureVersion?` \xB7 capture v${e.captureVersion}`:""}`),ge.gray(" Reads your code, writes your docs."),"",ir("Claude:",`${e.claude}${ge.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),ir("Document360:",e.configured?e.loggedOut?ge.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?ge.gray(` (${e.sessionHint})`):""}`:ge.yellow("not set up \u2014 run /init")),ir("Profile:",e.configured?`${e.profile}${ge.gray(` (${e.apiUrl})`)}${e.prod?ge.bold(ge.yellow(" \u26A0 PRODUCTION")):""}`:ge.gray("\u2014 (run /init)")),ir("Project:",e.project),ir("Mode:",ge.gray(e.mode)),ir("cwd:",ge.gray(e.cwd))],o=tg();if(o.length===0)return n.join(`
|
|
352
|
+
`);let r=2,s=3,i=ou(o[0]);if(!(t>=r+i+s+Math.max(...n.map(m=>ou(m)))))return[...o.map(m=>" "+m),...n].join(`
|
|
353
|
+
`);let l=Math.max(0,Math.floor((n.length-o.length)/2)),d=[];for(let m=0;m<Math.max(o.length+l,n.length);m++){let w=o[m-l]??" ".repeat(i);d.push((" ".repeat(r)+w+" ".repeat(s)+(n[m]??"")).trimEnd())}return d.join(`
|
|
354
|
+
`)}var Nx={error:ge.red,warn:ge.yellow,ok:ge.green,info:ge.gray},ng=9;function ru(e){return e.length>=ng?`${e} `:e.padEnd(ng)}function pa(e){return e.replace(/^(\s*• |)([^\x00-\x7F][\u{1F000}-\u{1FAFF}️]*) (?=\S)/gmu,"$1$2 ")}function su(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return Dx(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=>nu(d,s,{hard:!0}).split(`
|
|
356
356
|
`)),l=Math.max(0,a.length-i);return l>0&&(a=[...a.slice(0,i),ge.dim(`\u2026 +${l} more lines`)]),`
|
|
357
|
-
`+a.map((d,
|
|
357
|
+
`+a.map((d,m)=>o+(m===0?J(" \u276F "):" ")+d+" ".repeat(Math.max(0,s-ou(d))+1)+r).join(`
|
|
358
358
|
`)}case"assistant":return`
|
|
359
|
-
`+
|
|
360
|
-
`+
|
|
361
|
-
`+
|
|
359
|
+
`+eu(e.text,n);case"tool":{let o=e.arg!==null?ge.gray(`${e.sep}(${e.arg})`):"";return`
|
|
360
|
+
`+nu(ge.gray("\u25CF ")+e.title+o,n)}case"doc":{let o=[e.category,e.note].filter(s=>!!s).map(s=>ge.gray(` \xB7 ${s}`)),r=e.loud?ge.gray(" \xB7 ")+ge.bold(ge.yellow(e.loud)):"";return`
|
|
361
|
+
`+nu(ge.green("\u25CF ")+J(ge.bold(ru(e.verb)))+ge.bold(e.title)+o.join("")+r,n)}case"tool-result":{let o=e.isError?ge.red:ge.gray,r=e.lines.map((s,i)=>o((i===0?" \u23BF ":" ")+s));return e.hidden>0&&r.push(ge.dim(` \u2026 +${e.hidden} lines`)),r.join(`
|
|
362
362
|
`)}case"diff":{let o=i=>i===1?"":"s",s=[ge.gray(` \u23BF Added ${e.added} line${o(e.added)}, removed ${e.removed} line${o(e.removed)}`),...e.lines];return e.hidden>0&&s.push(ge.dim(` \u2026 +${e.hidden} more diff lines`)),s.join(`
|
|
363
|
-
`)}case"link":return e.lines.map(o=>J(
|
|
363
|
+
`)}case"link":return e.lines.map(o=>J(es(` \u2B95 ${o}`))).join(`
|
|
364
364
|
`);case"preview":return`
|
|
365
|
-
`+
|
|
365
|
+
`+Jr(`\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?ge.magenta("\u2736 "):ge.red("\u2736 "))+ge.gray(`Cooked for ${r} \xB7 ${
|
|
367
|
+
`+eu(e.text,n);case"note":return`
|
|
368
|
+
`+Nx[e.tone](es(pa(e.text)));case"block":return`
|
|
369
|
+
`+e.text;case"done":{let o=e.inTokens&&e.inTokens>0?` \xB7 ${ms(e.inTokens)} in${e.cachedPct!=null?` (${e.cachedPct}% cached)`:""}`:"",r=e.activeSeconds!==void 0&&ca(e.activeSeconds,e.seconds)?`${Pn(e.seconds)} elapsed \xB7 ${Pn(e.activeSeconds)} working`:Pn(e.seconds),s=e.costUsd>0?` \xB7 this turn ${St(e.costUsd)}`+(e.sessionCostUsd!==void 0&&e.sessionCostUsd>e.costUsd?` \xB7 session ${St(e.sessionCostUsd)}`:""):"";return`
|
|
370
|
+
`+(e.ok?ge.magenta("\u2736 "):ge.red("\u2736 "))+ge.gray(`Cooked for ${r} \xB7 ${ms(e.tokens)} tokens out${o}${s}`)}}}function rg(e,t,n){let o=e.map(i=>su(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 iu=3;function au(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 lu(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function cu(e,t){return t.map(n=>{let o=0;try{o=jx(Ix(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function uu(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 du(e,t,n){let o=e.reduce((a,l)=>a+l.paths.length,0),[r,s]=t.usd;return[`Convert ${o} article${o===1?"":"s"} to DFM in ${e.length} batch${e.length===1?"":"es"} (\u2264${n} agents at once):`,...e.map(a=>` \u2022 ${a.label} \u2014 ${a.paths.length} article${a.paths.length===1?"":"s"}`),"",`Estimated cost: ${St(r)}\u2013${St(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function pu(e,t,n){let o=v=>t[v.index]?.paths.length??0,r=e.filter(v=>v.ok),s=e.filter(v=>!v.ok),i=e.reduce((v,C)=>v+o(C),0),a=r.reduce((v,C)=>v+o(C),0),l=e.reduce((v,C)=>v+C.costUsd,0),d=e.reduce((v,C)=>v+C.outputTokens,0),m=n==="api"?`${St(l)} total`:ar(d),w=`${r.length}/${e.length} batch${e.length===1?"":"es"} completed`,k=v=>`${v} article${v===1?"":"s"}`,S=[];if(s.length===0)S.push(`Converted ${k(i)} (${w}) successfully \xB7 ${m}.`);else{S.push(`Converted ${a}/${k(i)} (${w}) \xB7 ${m}.`),S.push(`${s.length} batch${s.length===1?"":"es"} failed \u2014 re-run /convert to retry:`);for(let v of s)S.push(` \u2717 ${v.label}${v.error?` \u2014 ${v.error}`:""}`)}return S}async function sg(e,t){if(!_x(t.cwd))return console.log(O("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=au(e),r=Ux(t.cwd,t.profileName);if(r.length===0)return console.log(O("No tracked articles in d360-category-map.json. Save some to Document360 first (/push), then /convert.")),{kind:"continue"};let s=lu(r,n);if(s.length===0)return console.log(O(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let i=Ox(s),a=`/convert${n?` --scope ${n}`:""} --run`,{model:l,forced:d}=Mx(t.cwd,"light");if(!o){let w=Lx({files:cu(t.cwd,s),op:"convert",model:l});n&&console.log(g(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let k of du(i,w,iu))console.log(k);return console.log(g(`Model: ${l}${d?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(g(`Run ${a} to start.`)),console.log(""),{kind:"continue"}}console.log(g(`Converting ${s.length} articles in ${i.length} batches (\u2264${iu} agents at once) on ${l}\u2026`)),console.log(g(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let m=Date.now();try{for await(let w of Fx({cwd:t.cwd,partitions:i,promptFor:uu,concurrency:iu,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:l}))if(w.type==="partition_status")w.status==="running"?console.log(g(` \u25B8 ${w.label} \u2014 converting\u2026`)):w.status==="done"?console.log(q(` \u2713 ${w.label}`)):console.log(O(` \u2717 ${w.label}`));else if(w.type==="run_done"){console.log("");let k=process.env.ANTHROPIC_API_KEY?"api":"subscription",S=Cn(w,"The conversion");for(let v of S??pu(w.results,i,k))console.log(S||!w.ok?G(v):q(v));console.log(g(Kt(Ct(m,w.results,w.totalCostUsd))))}}catch(w){console.log(O(`Convert run failed: ${w.message}`))}return console.log(""),{kind:"continue"}}import{statSync as dR}from"node:fs";import{resolve as pR}from"node:path";import{estimateBulkCost as hR,lintDocs as fR,planFindingPartitions as mR,planPartitions as gR,readDocsPlan as wR,readProjectConfig as Ru,DEFAULT_DOCS_DIR as bg,resolveModelForOperation as mg,runPartitioned as gg,partitionCoverage as wg,stampArticles as yg,readReviewerNotes as yR,renderNotesForPrompt as bR,notesForPath as kR,CONTENT_CAP_VERSION as $R}from"document360-engine";se();import{lintDocs as wu,guidanceForRules as Hx,planFindingPartitions as Gx,runPartitioned as qx,partitionCoverage as Vx,resolveModelForOperation as Yx,stampArticles as Kx,applyDeterministicFixes as zx,isMechanical as Xx}from"document360-engine";import{CONTENT_CAP_VERSION as ig}from"document360-engine";function ag(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 lg(e){return e.trim().split(/\s+/).slice(1).find(t=>!t.startsWith("--"))}function st(e){return e==="review"?{reviewedCap:ig}:{checkedCap:ig}}import{gateFixTarget as Wx}from"document360-engine";var fu=e=>"ruleId"in e,ha=e=>fu(e)?e.severity:"warning",Tn=e=>e===1?"":"s";function mu(e,t){let n=t??Wx(e),o=n?` ${n}`:"";return e.unreviewed.length>0?`/review${o} --blocked --fix`:`/lint${o} --blocked --fix`}var hu=new Map;var Bx=e=>fu(e)?e.fp||`${e.ruleId}:${e.path}:${e.line}:${e.term}`:`${e.kind}:${e.path}:${e.line}`;function gs(e){let{cwd:t,after:n,scope:o,aborted:r,blocked:s}=e,i=n.filter(S=>ha(S)==="error").length,a=n.filter(S=>ha(S)==="warning").length,l=n.filter(S=>ha(S)==="suggestion").length,d=Re("/lint","--blocked --fix",o);if(r){let S=Re("/lint",s?"--blocked --fix":"--fix",o);return{text:`Stopped. Nothing else changed \u2014 ${S} picks up where this left off.`,cmd:S}}if(i>0){let S=n.filter(L=>ha(L)==="error"),v=new Set(S.map(L=>L.path)).size,C=`${t}::${o??""}`,A=S.map(Bx).sort().join("|"),D=hu.get(C)===A;if(hu.set(C,A),D){let L=Re("/lint","--blocked --full",o),B=[...new Set(S.filter(fu).map(M=>M.ruleId))];return{text:`The same ${i} error${Tn(i)} in ${v} article${Tn(v)} survived two ${d} passes, so a third would change nothing \u2014 ${i===1?"it needs":"they need"} a person. ${L} shows ${i===1?"it":"them"} in place. If ${B.length===1?`${B[0]} is`:"a rule is"} wrong for your product, switch it off in .d360-writer/config.json under "styleGuide": { "rules": { "<rule>": "off" } }.`,cmd:L}}return{text:`${i} error${Tn(i)} in ${v} article${Tn(v)} still block${i===1?"s":""} publishing. ${d} has another go at ${i===1?"it":"just those"} \u2014 if a second pass leaves the same ones, they need a human eye.`,cmd:d}}hu.delete(`${t}::${o??""}`);let m=a>0&&l>0?`${a} warning${Tn(a)} and ${l} suggestion${Tn(l)} remain (neither blocks publishing). `:a>0?`${a} warning${Tn(a)} remain${a===1?"s":""}, which ${a===1?"does":"do"} not block publishing. `:l>0?`${l} suggestion${Tn(l)} remain${l===1?"s":""} \u2014 ${l===1?"it is":"they are"} judgment calls and ${l===1?"does":"do"} not block publishing. `:"",w=m===""?"\u2713 Nothing left to fix. ":`\u2713 ${m}`,k=o?"/push":"/push --all";return Bt(t,{text:`${w}Nothing is blocking${o?` in ${o}`:""} \u2014 ${k} saves the articles to Document360 as drafts.`,cmd:k},w,o)}var ma={error:0,warning:1,suggestion:2},Qx={error:"\u2717",warning:"\u26A0",suggestion:"\xB7"},Jx=10,Zx=8,eR=96,cg=34,zt=e=>"ruleId"in e,An=e=>zt(e)?e.severity:"warning",yu=e=>zt(e)?e.ruleId:e.kind,lo=e=>e.fileLine??e.line;function cn(e){return e.includes("--blocked")}function un(e,t){return cn(t)?e.filter(n=>An(n)==="error"):e}function ws(e,t){return`/lint${t?` ${t}`:""}${cn(e)?" --blocked":""} --fix`}function gu(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function fa(e){let t={error:0,warning:0,suggestion:0};for(let n of e)t[An(n)]++;return t}function ug(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 ys(e,t={}){let n=t.baselined?[]:e.filter(w=>zt(w)&&w.baselined),o=t.baselined?e:e.filter(w=>!(zt(w)&&w.baselined)),r=n.length>0?[me("\u2139",`${n.length} issue${n.length===1?"":"s"} ${n.length===1?"was":"were"} already in your articles when you chose this style guide, so ${n.length===1?"it never blocks":"they never block"} publishing. /lint --baselined shows ${n.length===1?"it":"them"}.`)]:[];if(o.length===0)return[me("\u2713","No issues found \u2014 no leaked internals, unknown commands, stale version facts, AI-tells, em dashes, or broken callouts in the docs."),...r];let s=new Map;for(let w of o){let k=s.get(w.path)??[];k.push(w),s.set(w.path,k)}let i=fa(o),a=[me("\u26A0",`${o.length} issue${o.length===1?"":"s"} in ${s.size} article${s.size===1?"":"s"} \u2014 ${ug(i)}.`),""],l=[...s.entries()].sort((w,k)=>{let S=fa(w[1]);return fa(k[1]).error-S.error||k[1].length-w[1].length||w[0].localeCompare(k[0])}),d=t.full?l:l.slice(0,Jx);for(let[w,k]of d){a.push(` ${w} ${g(ug(fa(k)))}`);let S=new Map;for(let D of k){let L=yu(D),B=S.get(L)??[];B.push(D),S.set(L,B)}let v=[...S.entries()].sort((D,L)=>ma[An(D[1][0])]-ma[An(L[1][0])]||L[1].length-D[1].length||D[0].localeCompare(L[0])),C=t.full?v:v.slice(0,Zx);for(let[D,L]of C){let B=[...L].sort((Z,te)=>lo(Z)-lo(te)),M=Qx[An(B[0])],z=new Set(B.map(Z=>Z.term)).size===1?` ${gu(`"${B[0].term}"`,cg)}`:"",de=B.length>1?g(` \xD7${B.length}`):"",ye=t.full?B[0].message:gu(B[0].message,eR);a.push(` ${M} ${D}${de}${z}`),a.push(` ${g(ye)}`);let Se=B.map(Z=>z?`L${lo(Z)}`:`L${lo(Z)} ${gu(`"${Z.term}"`,cg)}`),ve=t.full?Se:Se.slice(0,12),fe=Se.length-ve.length;a.push(` ${g(ve.join(", ")+(fe>0?` \u2026+${fe}`:""))}`)}let A=v.length-C.length;A>0&&a.push(g(` \u2026${A} more rule${A===1?"":"s"} fired here (/lint ${w} --full)`)),a.push("")}let m=l.length-d.length;return m>0&&(a.push(g(` \u2026and ${m} more article${m===1?"":"s"} (/lint <category> narrows \xB7 /lint --full lists every one)`)),a.push("")),a.push(...r),a}var tR=200;function ga(e){let n=[...e.filter(l=>!(zt(l)&&l.baselined))].sort((l,d)=>ma[An(l)]-ma[An(d)]||l.path.localeCompare(d.path)||lo(l)-lo(d)),o=n.slice(0,tR),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(m=>` - L${lo(m)} [${yu(m)}] (${An(m)}): "${m.term}": ${m.message}`)].join(`
|
|
380
380
|
`)).join(`
|
|
381
|
-
`),a=
|
|
382
|
-
`)}var lr=3;function
|
|
381
|
+
`),a=Hx(o.map(l=>({id:yu(l),message:l.message,link:zt(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 lr=3;function cr(e,t,n){let o=n.filter(a=>!(zt(a)&&a.baselined)),r=un(o,t).filter(a=>zt(a)&&Xx(a));if(r.length===0)return{fixed:0,skipped:0,lines:[],paths:[]};let s=zx(e,r),i=[];if(s.fixed.length>0){let a=new Set(s.fixed.map(l=>l.path)).size;i.push(q(me("\u2713",`Fixed ${s.fixed.length} ${s.fixed.length===1?"issue":"issues"} in ${a} ${a===1?"article":"articles"} \u2014 a straight swap, so no model and no cost.`)))}return s.skipped.length>0&&i.push(g(` ${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 bu(e,t,n){let o=un(n.filter(a=>!(zt(a)&&a.baselined)),t);if(o.length===0)return null;let r=t.find(a=>!a.startsWith("--")),s=ws(t,r),i=Gx(o);return i.length<=1?{kind:"single",prompt:ga(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 ga(o.filter(d=>l.has(d.path)))}}}function ku(e,t,n){let o=t.find(l=>!l.startsWith("--")),r=o?` in ${o}`:"",s=n.filter(l=>!(zt(l)&&l.baselined)),i=new Set(s.map(l=>l.path)).size;return{lines:cn(t)?s.length===0?[`\u2713 Nothing is blocking publishing${r} \u2014 no style errors at all.`]:[`\u2713 Nothing is blocking publishing${r}. The ${s.length} issue${s.length===1?"":"s"} left ${s.length===1?"is a warning or a suggestion":"are warnings and suggestions"}, which never block it.`,` /lint${o?` ${o}`:""} --fix clears ${s.length===1?"it":"those"} too \u2014 ${s.length} issue${s.length===1?"":"s"} across ${i} article${i===1?"":"s"}.`]:[`\u2713 Nothing to fix${r} \u2014 the docs are already clean.`],closed:vt(e,ws(t,o))}}async function nR(e,t,n,o=[]){let{model:r}=Yx(e.cwd,"standard");console.log(g(`Fixing ${t.findings} issue${t.findings===1?"":"s"} across ${t.articles} article${t.articles===1?"":"s"} in ${t.partitions.length} batches (\u2264${lr} at once) on ${r}\u2026`));let s=[],i=Date.now(),a={aborted:!1,partitions:0,failed:0,notRun:0,producedNothing:!0};try{for await(let w of qx({cwd:e.cwd,partitions:t.partitions,promptFor:t.promptFor,concurrency:lr,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:r}))if(w.type==="partition_status")w.status==="running"?console.log(g(` \u25B8 ${w.label} \u2014 fixing\u2026`)):w.status==="done"?console.log(q(` \u2713 ${w.label}`)):console.log(O(` \u2717 ${w.label}`));else if(w.type==="run_done"){let k=Vx(t.partitions,w.results);a={aborted:!!w.aborted,partitions:t.partitions.length,failed:k.failed.length,notRun:k.notRun.length,...w.blocked?{blocked:w.blocked}:{},...w.allEmpty?{allEmpty:!0}:{},...w.bailedEmpty?{bailedEmpty:!0}:{}},console.log(g(Kt(Ct(i,w.results,w.totalCostUsd)))),k.failed.length&&console.log(G(`\u26A0 ${k.failed.length} batch${k.failed.length===1?"":"es"} not fixed: ${k.failed.map(S=>S.label).join(", ")}`)),k.notRun.length&&console.log(G(`\u26A0 ${k.notRun.length} batch${k.notRun.length===1?"":"es"} never started \u2014 their articles are untouched.`)),w.blocked&&console.log(G(`\u26A0 ${w.blocked}`)),w.allEmpty&&console.log(G("\u26A0 No turn produced any work this run \u2014 nothing was changed.")),!w.allEmpty&&!w.blocked&&s.push(...k.covered)}}catch(w){return console.log(O(`Fix run failed: ${w.message}`)),{kind:"continue"}}if(s.length>0)try{Kx(e.cwd,s,st("lint"))}catch{}let l=wu({cwd:e.cwd,scope:n}).filter(w=>!w.baselined),d=un(l,o);console.log("");for(let w of ys(d))console.log(d.length===0?q(w):G(w));if(Yt(a))for(let w of vt(e.cwd,ws(o,n)))console.log(q(w));let m=gs({cwd:e.cwd,after:d,before:t.findings,scope:n,blocked:cn(o)});return console.log(""),console.log(g(m.text)),{kind:"continue",ownNext:!0}}async function $u(e,t){let n=e.includes("--fix"),o=e.find(a=>!a.startsWith("--")),r=o?` ${o}`:"",s=wu({cwd:t.cwd,scope:o});if(n){let a=cr(t.cwd,e,s);for(let m of a.lines)console.log(m);let l=a.fixed>0?wu({cwd:t.cwd,scope:o}):s,d=bu(t.cwd,e,l);if(!d){let m=ku(t.cwd,e,l);console.log(q(m.lines[0]));for(let w of m.lines.slice(1))console.log(g(w));for(let w of m.closed)console.log(q(w));return{kind:"continue",ownNext:!0}}return d.kind==="partitioned"?nR(t,d,o,e):(console.log(g(`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=un(s,e);console.log(g("Linting the docs (engine internals, unknown commands, stale facts, AI-tells, em dashes, callout shape)\u2026"));for(let a of ys(i,{full:e.includes("--full"),baselined:e.includes("--baselined")}))console.log(i.length===0?q(a):G(a));return i.length>0&&console.log(g(`Run /lint${r}${cn(e)?" --blocked":""} --fix to have the agent correct these.`)),console.log(""),{kind:"continue",ownNext:i.length>0}}var dg=async(e,t)=>{let n=ln("check");return n&&console.log(g(`\u2192 ${n}`)),$u(e,t)};se();import{readProjectConfig as oR,loadProfileMap as rR,resolveActiveProfile as sR,desiredCategoryOrder as iR,desiredArticleOrder as aR,DEFAULT_DOCS_DIR as lR}from"document360-engine";var vu=e=>e.replace(/\\/g,"/"),pg=e=>vu(e).split("/").pop()??e;function xu(e){let t=pg(e),n=t.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return n?n.charAt(0).toUpperCase()+n.slice(1):t}var cR=xu;function bs(e,t){try{let n=oR(e);if(!n)return[];let o=sR(e,t),r=rR(e,o.name);if(!r)return[];let s=vu(n.docsDir??lR).replace(/\/+$/,""),i=new Map;for(let l of aR(r))i.set(l.categoryPath,(i.get(l.categoryPath)??0)+1);let a=[];for(let l of iR(r)){let d=vu(l.path),m=d.startsWith(`${s}/`)?d.slice(s.length+1):d===s?"":d;m&&a.push({token:m,label:cR(pg(d)),count:i.get(l.path)??0})}return a}catch{return[]}}function hg(e,t){let n=bs(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 En(e,t){if(t.includes("--all")||t.includes("--blocked")||t.includes("--stale")||t.some(n=>n.startsWith("--scope="))||t.includes("--scope")&&!ks(t))return!1;for(let n=0;n<t.length;n++){let o=t[n];if(o.startsWith("--")){uR.has(o)&&n++;continue}return!1}return e==="write"?!t.includes("--preview")&&!t.includes("--dry-run"):e==="review"||e==="reorder"}var uR=new Set(["--scope","--concurrency"]);function ur(e,t,n,o,r){if(r=r??bs(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,m)=>d+m.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 ks(e){let t=e.indexOf("--scope");if(t===-1)return!1;let n=e[t+1];return n===void 0||n.startsWith("-")}function fg(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 vR=3,xR=8;function Cu(e){return e===void 0||!Number.isFinite(e)?vR:Math.max(1,Math.min(Math.floor(e),xR))}function $s(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 RR(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function CR(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Su(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+=dR(pR(e,i)).size}catch{}return{path:r,bytes:s}})}function Pu(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,168 +391,169 @@ 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
|
|
395
|
-
`)}var
|
|
396
|
-
`)}var
|
|
394
|
+
`)+r}function Tu(e,t,n){let o=e.reduce((i,a)=>i+a.paths.length,0),[r,s]=t.usd;return[`Write ${o} article${o===1?"":"s"} in ${e.length} batch${e.length===1?"":"es"} (\u2264${n} agents at once):`,...e.map(i=>` \u2022 ${i.label} \u2014 ${i.paths.length} article${i.paths.length===1?"":"s"}`),"",`Estimated cost: ${St(r)}\u2013${St(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function Au(e,t,n,o){let r=C=>t[C.index]?.paths.length??0,s=e.filter(C=>C.ok),i=e.filter(C=>!C.ok),a=e.reduce((C,A)=>C+r(A),0),l=s.reduce((C,A)=>C+r(A),0),d=e.reduce((C,A)=>C+A.costUsd,0),m=e.reduce((C,A)=>C+A.outputTokens,0),w=n==="api"?`${St(d)} total`:ar(m),k=`${s.length}/${e.length} batch${e.length===1?"":"es"} completed`,S=C=>`${C} article${C===1?"":"s"}`,v=[];if(i.length===0){v.push(`Wrote ${S(a)} (${k}) successfully \xB7 ${w}.`);let C=o?` ${o}`:"",A=o?"/push":"/push --all",D=o?`/screenshot author ${o}`:"/screenshot author --all";v.push("Next \u2014 an editorial review, because these were written by an AI:"),v.push(`/review${C} --fix`),v.push(`It reads every article and applies its fixes; ${A} then pushes them up (add screenshots first with ${D} if you want them).`)}else{v.push(`Wrote ${l}/${S(a)} (${k}) \xB7 ${w}.`),v.push(`${i.length} batch${i.length===1?"":"es"} failed \u2014 re-run /write${o?` --scope ${o}`:""} to retry the rest:`);for(let C of i)v.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return v}function dr(e,t,n){try{return fR({cwd:e,paths:n.map(o=>`${t}/${o}`)}).filter(o=>!o.baselined)}catch{return[]}}function Eu(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 Du(e){let t=e.filter(o=>o.severity==="error");if(t.length===0)return null;let n=mR(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 ga(t.filter(s=>r.has(s.path)))}}}function Nu(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 wa(e,t,n){let o=(Ru(e)?.docsDir??bg).replace(/\/+$/,""),r=t.map(a=>a.path);if(n.path){let a=RR(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=CR(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=Rn(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 ju(e,t,n){let{targets:o}=wa(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:xu(s),count:i}))}async function kg(e,t){if(!Ru(t.cwd))return console.log(O("No d360-writer config here. Run /init first.")),{kind:"continue"};if(ks(e)){for(let M of hg(t.cwd,t.profileName))console.log(g(M));return{kind:"continue"}}let n=wR(t.cwd,(Ru(t.cwd)?.docsDir??bg).replace(/\/+$/,""));if(n.length===0)return console.log(O("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};if(En("write",e)){let M=ju(t.cwd,n,{rewrite:$s(e).rewrite}),X=ur(t.cwd,"write",e,t.profileName,M);if(X.length>0){for(let z of X)console.log(g(z));return{kind:"continue"}}}let{scope:o,path:r,preview:s,concurrency:i,rewrite:a}=$s(e),{docsDir:l,targets:d,reason:m,rewriting:w}=wa(t.cwd,n,{scope:o,path:r,rewrite:a});if(d.length===0)return console.log(m?G(m):G("Nothing to write.")),{kind:"continue"};w&&console.log(G(`--rewrite: regenerating ${d.length} already-written article${d.length===1?"":"s"} (overwrites them; git has your baseline).`));let k=gR(d),S=Cu(i),{model:v,forced:C}=mg(t.cwd,"standard"),A=!!r;if(s&&!A){let M=hR({files:Su(t.cwd,n,d),op:"write",model:v});o&&console.log(g(`Scope: ${o} (${d.length} pending).`));for(let X of Tu(k,M,S))console.log(X);return console.log(g(`Model: ${v}${C?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(g(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}let D=yR(t.cwd),L=d.filter(M=>kR(D,M).length>0).length;L>0&&console.log(g(` ${L} of these ${L===1?"has":"have"} reviewer comments \u2014 the writer gets them.`)),console.log(g(`Writing ${d.length} article${d.length===1?"":"s"} in ${k.length} batch${k.length===1?"":"es"} (\u2264${S} agents at once) on ${v}\u2026`)),console.log(g(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let B=Date.now();try{for await(let M of gg({cwd:t.cwd,partitions:k,promptFor:X=>Pu(X,l,{rewrite:w||A,reviewerNotes:bR(D,X.paths)}),concurrency:S,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:v}))if(M.type==="partition_status")M.status==="running"?console.log(g(` \u25B8 ${M.label} \u2014 writing\u2026`)):M.status==="done"?console.log(q(` \u2713 ${M.label}`)):console.log(O(` \u2717 ${M.label}`));else if(M.type==="run_done"){console.log("");let X=process.env.ANTHROPIC_API_KEY?"api":"subscription",z=Cn(M,"The write");if(z){for(let ve of z)console.log(G(ve));continue}for(let ve of Au(M.results,k,X,o??r))console.log(M.ok?q(ve):G(ve));if(console.log(g(Kt(Ct(B,M.results,M.totalCostUsd)))),M.ok)try{yg(t.cwd,d.map(ve=>`${l}/${ve}`),{writtenCap:$R,reviewedCap:0,checkedCap:0})}catch{}let de=dr(t.cwd,l,d),ye=Eu(de);ye&&console.log(G(ye));let Se=e.includes("--skip-style")?null:Du(de);if(Se){console.log(g(`Fixing ${Se.errors.length} style error(s) in ${Se.articles} article(s) \u2014 one pass\u2026`));let{model:ve}=mg(t.cwd,"standard"),fe=[];try{for await(let Z of gg({cwd:t.cwd,partitions:Se.partitions,promptFor:Se.promptFor,concurrency:3,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:ve}))if(Z.type==="partition_status"&&Z.status!=="running")console.log(Z.status==="done"?q(` \u2713 ${Z.label}`):O(` \u2717 ${Z.label}`));else if(Z.type==="run_done"&&!Z.allEmpty&&!Z.blocked){let te=wg(Se.partitions,Z.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.`)),fe.push(...te.covered)}}catch(Z){console.log(G(`Style fix pass failed: ${Z.message}`))}if(fe.length>0)try{yg(t.cwd,fe,st("lint"))}catch{}for(let Z of Nu(Se.errors.length,dr(t.cwd,l,d)))console.log(Z.startsWith("\u2713")?q(Z):G(Z))}{let ve=wg(k,M.results),fe={aborted:!!M.aborted,partitions:k.length,failed:ve.failed.length,notRun:ve.notRun.length,leftBehind:dr(t.cwd,l,d).filter(Z=>Z.severity==="error").length,...M.blocked?{blocked:M.blocked}:{},...M.allEmpty?{allEmpty:!0}:{},...M.bailedEmpty?{bailedEmpty:!0}:{}};if(Yt(fe)){let Z=`/write${o?` --scope ${o}`:""}${e.includes("--rewrite")?" --rewrite":""}`;for(let te of vt(t.cwd,Z))console.log(q(te))}}}}catch(M){console.log(O(`Write run failed: ${M.message}`))}return console.log(""),{kind:"continue"}}se();import{existsSync as SR,readdirSync as $g,statSync as vg}from"node:fs";import{join as xg}from"node:path";import{inputDir as PR,readProjectConfig as TR}from"document360-engine";var Rg=/\.(md|markdown|pdf|txt)$/i;function Iu(e){let t=PR(e);if(!SR(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of $g(t)){let s=xg(t,r),i=!1;try{i=vg(s).isDirectory()}catch{continue}if(i){if(r.startsWith("."))continue;let a=AR(s);a>0&&n.push({name:r,docCount:a})}else Rg.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function AR(e){let t=0;for(let n of $g(e))try{vg(xg(e,n)).isFile()&&Rg.test(n)&&t++}catch{}return t}function Lu(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 ya(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 Ou="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function Cg(e,t){let n=t?.cwd??process.cwd();if(!TR(n))return console.log(O("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=Iu(n);if(o.length===0&&r===0)return console.log(g(Ou)),{kind:"continue"};let s=e.join(" ").trim();if(!s){if(o.length>1){console.log(g("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let l of o)console.log(` ${l.name} ${g(`(${l.docCount} doc${l.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let a=o[0]?.name??"";return{kind:"forward-to-agent",prompt:ya(a),display:a?`/draft ${a}`:"/draft"}}let i=Lu(o,s);return{kind:"forward-to-agent",prompt:ya(i??"",i?void 0:s),display:`/draft ${s}`}}se();import{listOpenForDocs as ER,readProjectConfig as DR}from"document360-engine";function _u(e){try{return ER(e).filter(t=>t.kind==="request").length}catch{return 0}}function Mu(e){let t=e.includes("--push")||e.includes("--publish"),n=e.includes(xt),o=e.filter(r=>!r.startsWith("--")).join(" ").trim();return{push:t,skipReview:n,what:o}}function Fu(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 Uu="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 Sg(e,t){let n=t?.cwd??process.cwd();if(!DR(n))return console.log(O("No d360-writer config here. Run /init first.")),{kind:"continue"};let{push:o,what:r}=Mu(e);if(!r&&_u(n)===0)return console.log(g(Uu)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --push":""}`;return{kind:"forward-to-agent",prompt:Fu(r),display:s}}se();import{search as NR}from"@inquirer/prompts";import{findByName as jR,getSession as IR,listSessions as LR,relativeTime as Tg}from"document360-engine";async function Ag(e,t){let n=LR(t.cwd).filter(o=>o.uuid!==t.currentUuid());if(n.length===0)return console.log(g("No saved sessions for this repo yet \u2014 sessions auto-save as you work.")),{kind:"continue"};if(e.length>0){let o=e.join(" "),r=jR(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(O(`No session matches "${o}".`)),Pg(n),{kind:"continue"})}if(!process.stdin.isTTY)return Pg(n),console.log(g("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>NR({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} ${Tg(a.updatedAt)}`,value:a.uuid,description:a.firstPrompt.slice(0,100)}))}})),r=IR(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function Pg(e){console.log("");for(let t of e.slice(0,15))console.log(` ${J(t.name)} ${g(Tg(t.updatedAt))}`),console.log(` ${g(t.firstPrompt.slice(0,80))}`);console.log("")}se();import{renameSession as OR}from"document360-engine";function Wu(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 Eg(e,t){let n=Wu(e.join(" "));if(!n)return console.log(O("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(OR(o,n)?console.log(q(`\u2713 Session renamed to "${n}"`)):console.log(O("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(q(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as Dg,readProjectConfig as _R,writeProjectConfig as MR}from"document360-engine";se();function Bu(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=_R(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 Dg().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},MR(o,e),null):`Unknown environment "${r}". Known: ${Dg().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function Ng(e,t){let n=e[0];if(!n)return wi(t.cwd),{kind:"continue"};if(n==="add"){let o=Bu(t.cwd,e[1],e[2]);return o?(console.log(O(o)),{kind:"continue"}):(console.log(q(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${J(`/profile ${e[1]}`)} then ${J("/login")}`),console.log(g(" Until you switch, this repo keeps using the current profile\u2019s environment.")),{kind:"continue"})}return yi(t.cwd,n),bi(t.cwd,n),console.log(g(" Restarting agent for the new profile\u2026")),{kind:"clear"}}se();import{select as FR}from"@inquirer/prompts";import{readProjectConfig as UR,readUserConfig as jg,resolveModelSetting as Hu,writeUserConfig as Ig}from"document360-engine";var Pt=[{value:null,label:"Auto",desc:"Sonnet (latest) \u2014 right-sized for docs work (recommended); heavier models only when you pin them"},{value:"claude-fable-5",label:"Fable",desc:"Fable 5 \xB7 most capable, for the hardest and longest-running tasks"},{value:"opus",label:"Opus",desc:"Opus (latest) \xB7 best for everyday complex tasks"},{value:"sonnet",label:"Sonnet",desc:"Sonnet (latest) \xB7 efficient for routine tasks"},{value:"haiku",label:"Haiku",desc:"Haiku (latest) \xB7 fastest for quick answers"}];function ba(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=Pt.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function WR(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 vs(e,t){let n=()=>Hu(e).model;if(t==="default"){let s=jg();return s.defaultModel?(delete s.defaultModel,Ig(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${Hu(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}}Ig({...jg(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=UR(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 Lg(e,t){let n=e[0]?.trim();if(!n){let i=Hu(t.cwd);if(!process.stdin.isTTY)return console.log(`${Be("Model:")} ${J(i.model)}${i.source==="auto"?g(" (auto)"):""}`),console.log(g(` source: ${WR(i)}`)),console.log(g(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let a=ba(i),l;try{l=await t.withPausedInput(()=>FR({message:`Select model (current: ${i.model}${i.source==="auto"?" \xB7 auto":""})`,default:Pt[a].value,choices:Pt.map((k,S)=>({name:`${k.label}${S===a?" \u2714":""}`,value:k.value,description:k.desc}))}))}catch{return console.log(g("Cancelled.")),{kind:"continue"}}let{lines:d,changed:m,effective:w}=vs(t.cwd,l??"default");for(let k of d)console.log(k.startsWith("\u26A0")?G(k):k.startsWith("\u2713")?q(k):g(k));return m&&await t.setModel(w),{kind:"continue"}}let{lines:o,changed:r,effective:s}=vs(t.cwd,n);for(let i of o)console.log(i.startsWith("\u26A0")?G(i):i.startsWith("\u2713")?q(i):g(i));return r&&await t.setModel(s),{kind:"continue"}}va();async function Ug(e,t){return await t.withPausedInput(()=>qo(t.cwd)),{kind:"clear"}}async function Wg(e,t){return await t.withPausedInput(()=>fi(t.cwd,t.profileName)),{kind:"clear"}}se();import{resolveActiveProfile as cC}from"document360-engine";async function Bg(e,t){let n=!1;try{n=cC(t.cwd).production}catch{}return n?(console.log(G("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(g("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}se();var Hg=async(e,t)=>{try{await t.withPausedInput(()=>gi({}))}catch(n){console.log(O(`Login failed: ${n.message}`))}return{kind:"continue"}};import{resolveActiveProfile as uC,clearTokens as dC,clearProfileProject as pC,listStoredSessions as hC,tokensProjectId as fC}from"document360-engine";se();async function Gg(e,t){let n,o,r,s;try{let w=uC(t.cwd,t.profileName);n=w.name,o=w.connection.name,r=w.project.projectId,s=w.project.projectName}catch(w){return console.log(O(w.message)),{kind:"continue"}}let i=e.includes("--all-projects"),a=hC(n).filter(w=>{let k=fC(w);return!!k&&k!==r}).length,l=dC(n,i?void 0:r);pC(t.cwd,n);let d=i||a===0?"":` Your sign-in for ${a} other project${a===1?"":"s"} is untouched (/logout --all-projects clears those too).`;console.log(l?i?q(`\u2713 Signed out of every Document360 project for "${n}" and cleared this repo's project/workspace selection.`):q(`\u2713 Signed out of ${s?`"${s}"`:`"${n}"`} and cleared its project/workspace selection.${d}`):g(`Profile "${n}" was not signed in. Cleared any project/workspace selection.${d}`)),console.log(g(`Run /login to sign back in to "${n}" (the ${o} environment) and pick a project.`));let m=wn(t.cwd,t.profileName);return console.log(m?G(`\u26A0 ${m.why}. Signing out doesn\u2019t change the environment \u2014 ${m.cmd} does.`):g(" Different environment? That comes from the profile, not the login \u2014 /profile add <environment>.")),{kind:"continue"}}import{existsSync as Yg,readFileSync as Vu}from"node:fs";import{homedir as xC}from"node:os";import{basename as RC,join as Ss}from"node:path";import{readProjectConfig as CC,DEFAULT_OUTPUT_DIR as SC,existingAnnotatedShotPath as n3,resolveOutputDir as PC,shotArtifacts as TC}from"document360-engine";import dt from"picocolors";import{annotationsPath as mC,resolveOutputDir as gC,readProjectConfig as wC,DEFAULT_OUTPUT_DIR as yC,existingAnnotatedShotPath as bC}from"document360-engine";function kC(e){let n=e.filter(o=>o!=="--all"&&o!=="-a").find(o=>!o.startsWith("-"));return n?{mode:"single",id:n}:{mode:"all"}}function Rs(e){return e.filter(t=>t.state==="annotated").map(t=>t.id)}function Xt(e,t){let n=gC(e,wC(e)?.outputDir??yC),o=new Map(_e(e).map(i=>[i.id,i])),r=i=>i.replace(`${e}\\`,"").replace(`${e}/`,"").replace(/\\/g,"/"),s=t.map(i=>{let a=o.get(i)?.file??"(unknown article)";return[`- ${i}`,` image: ${r(bC(n,i))}`,` facts: ${r(mC(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 Dn(e){return`${ee("\u2192",dt.blue)}Verifying ${e} new screenshot${e===1?"":"s"} (reading each image)\u2026`}var
|
|
400
|
-
${
|
|
401
|
-
`)}function
|
|
402
|
-
`):
|
|
403
|
-
`)}var
|
|
399
|
+
`)}function Dn(e){return`${ee("\u2192",dt.blue)}Verifying ${e} new screenshot${e===1?"":"s"} (reading each image)\u2026`}var $C=(e,t=88)=>{let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n};function pr(e,t){if(t.length===0)return[];let n=an(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(`${ee("\u2714",dt.green)}${dt.green(`${o.length} verified`)}`+(r.length>0?` ${dt.magenta(`\u2691 ${r.length} flagged`)}`:"")+(s.length>0?` ${dt.yellow(`? ${s.length} not verified`)}`:"")+dt.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(` ${dt.magenta(d.id.padEnd(a))} ${dt.gray($C(d.reason))}`);let l=r.filter(d=>d.repaired).length;i.push(`${ee("\u2192",dt.magenta)}Re-capture the ${r.length} flagged: ${dt.bold("/screenshot capture --failed")}`+(l<r.length?dt.gray(` (${r.length-l} still need${r.length-l===1?"s":""} a spec fix first)`):""))}return s.length>0&&i.push(`${ee("\u26A0",dt.yellow)}No verdict recorded for ${s.slice(0,3).join(", ")}${s.length>3?`, +${s.length-3}`:""} \u2014 still awaiting verification. Run ${dt.bold("/screenshot verify")} again.`),i}async function qg(e,t){let n=t?.cwd??process.cwd(),o=no(n);o&&console.log(o);let r=_e(n),s=kC(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:Xt(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=Rs(r);if(i.length===0){let a=r.filter(m=>m.state==="verified").length,l=r.filter(m=>m.state==="rejected").length,d=r.filter(m=>m.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:Xt(n,i),display:"/screenshot verify"}}import{spawn as Vg}from"node:child_process";var qu="d360-capture";function vC(e,t){if(t&&typeof e.pid=="number")try{process.kill(-e.pid,"SIGTERM");return}catch{}try{e.kill()}catch{}}function Cs(e){let t=process.platform==="win32",n=!t&&e.stdio==="pipe";return new Promise((o,r)=>{let s=t?Vg(`${qu} ${e.args.join(" ")}`,{cwd:e.cwd,shell:!0,stdio:e.stdio==="inherit"?"inherit":["ignore","pipe","pipe"],env:{...process.env,NO_UPDATE_NOTIFIER:"1"}}):Vg(qu,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=()=>vC(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
|
+
${qu}: command not found`.trim()});return}r(l)}),s.on("close",l=>{e.signal?.removeEventListener("abort",a),o({exitCode:l??1,output:i})})})}var AC=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Yu(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:AC(t),retryBlocked:n}:{mode:"single",id:t}:{mode:"picker"}}function Ts(e,t){let n=_e(e,t),o=r=>n.filter(s=>s.state===r).map(s=>s.id);return{ready:o("spec"),captured:[...o("captured"),...o("annotated"),...o("verified"),...o("rejected")].sort(),blocked:o("blocked"),broken:o("broken"),rejected:o("rejected"),rows:n}}function Kg(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}),Zo(o,t,"capture"),Cc(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 Ku(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([...kf(e).filter(r=>n.has(r)),...o])].sort()}function zu(e,t){let n=e.length;if(n===0)return null;let o=as(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 EC(e,t){let n=CC(e)?.outputDir??SC;return TC(PC(e,n),t)}function Xu(e,t,n,o){let r=EC(e,t);return(r.annotationsMtimeMs??0)>=o&&r.rawMtimeMs!==void 0?"captured":n===0?"skipped":"failed"}function zg(e){let t=/⊘[^\n—]*—\s*(.+)/.exec(e);return t?t[1].trim():null}var DC=/element is not (?:enabled|visible|stable|editable)|intercepts pointer events|outside of the viewport|element is not attached/i;function Xg(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=>DC.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
|
+
`):Qu(e)}function Qu(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 NC=/^[A-Za-z0-9._-]+$/;function Ju(e){return NC.test(e.id)?Cs({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 Qg(e,t=xC()){try{let n=JSON.parse(Vu(Ss(e,".d360-writer","capture.json"),"utf8").replace(/^/,"")),o=n.projectId;if(!o)try{o=JSON.parse(Vu(Ss(e,"package.json"),"utf8")).name}catch{}o||=RC(e);let r=Object.keys(n.profiles??{}),s=n.defaultProfile??(r.length===1?r[0]:r.includes("staging")?"staging":r[0]);return s?Yg(Ss(t,".document360-capture","auth-states",o,`${s}.json`)):!0}catch{return!0}}function Jg(e){return Cs({args:["auth","--auto"],cwd:e.cwd,stdio:"pipe",signal:e.signal})}function Zu(e,t){return e===127||/is not recognized as an internal or external command|command not found/i.test(t)}function Zg(e){try{let t=JSON.parse(Vu(Ss(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 co(e){return Yg(Ss(e,".d360-writer","capture.json"))}function ed(){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
404
|
`)}function ew(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 tw(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):
|
|
406
|
-
`),cmd:o.length>0?`/screenshot ${l}`:r.length>0?
|
|
407
|
-
Check them when you're ready: ${Re("/screenshot verify","",i)}`),{kind:"continue"};let L=A.filter(B=>!
|
|
408
|
-
`),display:"/screenshot checklist"}}function
|
|
409
|
-
`)}async function uw(e,t){let n=t?.cwd??process.cwd();return
|
|
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 Ra(e,t){let n=fw(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=oS(e);if(!o)return[{tone:"info",text:"Sharing: unavailable \u2014 this folder is not a git repository."}];if(!o.upstream)return[{tone:"warn",text:ee("\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:ee("\u26A0")+`${o.ahead} change${Ts(o.ahead)} not shared yet \u2014 run /share`}):s.push({tone:"ok",text:ee("\u2713")+"Everything is shared with your team."}),s}function ud(e,t,n){hw({...t,gitHandoff:{commit:n,push:n}},e);let o=n?{tone:"ok",text:ee("\u2713")+"Sharing on \u2014 d360-writer will save and send its own work from now on."}:{tone:"ok",text:ee("\u2713")+"Sharing off \u2014 d360-writer will leave its work for your coding agent to commit."};return n?[o,...Ra(e,{...t,gitHandoff:{commit:!0,push:!0}})]:[o]}async function Ca(e,t){let n=[],o=fw(t);if(!o.commit)return{lines:[{tone:"info",text:Nn("disabled")}],changed:!1};let r=t;o.push==="unconfirmed"&&rS(e,t)&&(r={...t,gitHandoff:{commit:!0,push:!0}},hw(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 nS(e);if(s.ok&&s.pulled>0){let d=[s.newHints>0?`${s.newHints} new hint${Ts(s.newHints)}`:null,s.newMessages>0?`${s.newMessages} new message${Ts(s.newMessages)}`:null].filter(Boolean);n.push({tone:"ok",text:ee("\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:ee("\u26A0")+Nn(s.reason,s.detail)});let i=await tS(e,r);if(i.commit&&!i.commit.ok)return n.push({tone:"warn",text:ee("\u26A0")+Nn(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:ee("\u2713")+`Saved ${a} change${Ts(a)} to the docs folder.`}),i.push&&!i.push.ok)return n.push({tone:"warn",text:ee("\u26A0")+Nn(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:ee("\u2B06")+`Shared ${l} change set${Ts(l)} with your team.`}):a===0&&(s.ok&&s.pulled===0)?n.push({tone:"ok",text:ee("\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 sS={ok:q,info:be,warn:G,error:O};async function mw(e,t){let n=t.cwd,o=eS(n);if(!o)return console.log(O("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase(),s=a=>{for(let l of a)console.log(sS[l.tone](l.text))};if(r==="status")return s(Ra(n,o)),{kind:"continue"};if(r==="on"||r==="off")return s(ud(n,o,r==="on")),{kind:"continue"};if(r)return console.log(O(`Unknown option "${r}". Use /share, /share status, /share on, or /share off.`)),{kind:"continue"};console.log(w("Exchanging work with your team\u2026"));let{lines:i}=await Ca(n,o);return s(i),{kind:"continue"}}function uo(e){let t=0,n=0,o=0,r=0;try{t=iS(e).length}catch{}try{let s=aS(e);n=s.filter(i=>i.kind==="request").length,o=s.filter(i=>i.kind==="answer").length}catch{}try{r=lS(e).length}catch{}return{hints:t,requests:n,answers:o,directives:r}}async function pd(e){let t=gw(e);if(!t)return[];if(!mS(e,t))return[];let n=await fS(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 ${Nn(n.reason,n.detail)}`}]}function hd(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 fd(e){let t=hd(e);return t?`Catching up on ${t}\u2026`:"Nothing queued from your builder \u2014 checking Document360 for reviewer comments and feedback\u2026"}function md(e){return{push:e.includes("--push")||e.includes("--publish"),skipReview:e.includes(xt)}}function gd(e){let t={hold:!1,openQuestions:0,answersPending:0};try{let n=gS(e);return!n||n.status==="confident"?t:{hold:!0,...wS(e)}}catch{return t}}function wd(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:`${ee("\u2139")}Product discovery is still open \u2014 ${n} answer${fr(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:`${ee("\u26A0")}Product discovery isn't finished \u2014 ${n} question${fr(n)} still with your builder.`},{tone:"warn",text:` ${t} until the brief is settled.`}]}return[{tone:"warn",text:`${ee("\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 yd(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${fr(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
|
|
405
|
+
/screenshot list --detail shows what each one needs`}function tw(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):Ps(r?.reason)!==Ps(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):Hi(r?.reason??"")!==Hi(o.detail??"")?n.blockedNewReason.push(o.id):n.blockedAsBefore.push(o.id))}return n}function Ps(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 nw(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?er(o.detail):"no reason recorded"}`)}function hr(e,t=2){return e.length<=t?e.join(" \xB7 "):`${e.slice(0,t).join(" \xB7 ")} \xB7 +${e.length-t}`}function ow(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",hr(e.newlyCaptured)),o("\u2717",e.newlyBroken.length,"newly broken",hr(e.newlyBroken)),o("\u2192",e.repairedNowBlocked.length,"repaired",`no longer broken \u2014 only data stands in the way \xB7 ${hr(e.repairedNowBlocked)}`),o("\u2298",e.newlyBlocked.length,"newly blocked",hr(e.newlyBlocked)),o("\u2192",e.blockedNewReason.length,"blocked on something new",`an earlier step now passes \xB7 ${hr(e.blockedNewReason)}`),o("\u2192",e.brokeDifferently.length,"broken differently",`the previous cause is fixed \xB7 ${hr(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 rw(e){let t=e.results.filter(S=>S.outcome==="captured"),n=e.results.filter(S=>S.outcome==="skipped"),o=e.results.filter(S=>S.outcome==="failed"),r=e.unannotated??[],s=S=>S===1?"":"s";if(t.length+n.length+o.length===0)return null;let i=e.articles.length===1?`/push ${e.articles[0]}`:Re("/push","--screenshots",Vt(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 m=Re("/screenshot annotate","",r.length===1?r[0]:void 0);r.length>0&&d.push({glyph:"\u25C8",cmd:m,why:`draw the callouts on ${r.length} shot${s(r.length)} \u2014 no browser, seconds; ${r.length===1?"it cannot":"they cannot"} publish until drawn`}),n.length>0&&d.push({glyph:"\u2298",cmd:"/screenshot list",why:`what to stage for the ${n.length} blocked shot${s(n.length)}`}),t.length>0&&r.length<t.length&&d.push({glyph:"\u2713",cmd:i,why:`embed the ${t.length-r.length} new PNG${s(t.length-r.length)}`});let w=Math.max(...d.map(S=>S.cmd.length));return{note:d.map(S=>`${S.glyph} ${S.cmd.padEnd(w)} ${S.why}`).join(`
|
|
406
|
+
`),cmd:o.length>0?`/screenshot ${l}`:r.length>0?m:t.length>0?i:a,tone:o.length>0||r.length>0?"warn":"info"}}function sw(e,t){let n=new Map(_e(e).map(o=>[o.id,o.file]));return[...new Set(t.map(o=>n.get(o)).filter(o=>!!o))].sort()}async function td(e,t){let n=t?.cwd??process.cwd(),o=Yu(e);if(!co(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}=Ts(n,o.mode==="scope"?o.scope:void 0),l=Ku(n,a),d=(o.mode==="all"||o.mode==="scope")&&o.retryBlocked,m=o.mode==="single"?[o.id]:o.mode==="failed"?l:o.mode==="blocked"?i:o.mode==="picker"?r:[...r,...s,...d?i:[]];if(m.length===0)return o.mode==="failed"?console.log("No broken specs to re-run \u2014 /screenshot list shows where things stand."):o.mode==="blocked"?console.log("No shots are waiting on app data \u2014 /screenshot list shows where things stand."):console.log("No authored specs to capture yet \u2014 author them first: /screenshot"),{kind:"continue"};if(!d&&o.mode!=="single"&&o.mode!=="failed"&&o.mode!=="blocked"){let C=zu(a.filter(A=>A.state==="blocked"),"/screenshot capture --blocked");C&&console.log(C)}let w=Date.now(),k=[];for(let C of m){console.log(`\u25B6 ${C}`);try{let{exitCode:A}=await Ju({cwd:n,id:C,stdio:"inherit"});k.push({id:C,outcome:Xu(n,C,A,w)})}catch(A){if(A.code==="ENOENT")return console.log("d360-capture is not installed. Run: npm i -g document360-capture"),{kind:"continue"};k.push({id:C,outcome:"failed",detail:A.message})}}let S=C=>k.filter(A=>A.outcome===C).length;console.log(`\u2713 ${S("captured")} captured \xB7 \u2298 ${S("skipped")} skipped \xB7 \u2717 ${S("failed")} failed`);let v=k.filter(C=>C.outcome==="captured");return ji(n,k.map(C=>({id:C.id,outcome:C.outcome,reason:C.detail,specSource:oo(n,C.id)})),new Date().toISOString()),v.length>0?(console.log(Dn(v.length)),{kind:"forward-to-agent",prompt:Xt(n,v.map(C=>C.id)),display:"/screenshot verify"}):{kind:"continue"}}import{readProjectConfig as jC,DEFAULT_OUTPUT_DIR as IC,resolveOutputDir as LC,shotArtifacts as OC,annotationCurrent as _C}from"document360-engine";Qo();var iw="0.2.29";function xa(e=ut()){return Jo(e,iw)}function nd(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 od(e,t){let n=_e(e,t);return{pending:n.filter(o=>o.state==="captured").map(o=>o.id),done:n.filter(o=>o.state==="annotated"||o.state==="verified"||o.state==="rejected").map(o=>o.id),rows:n}}var MC=/^[A-Za-z0-9._-]+$/;function FC(e){if(!MC.test(e.id))return Promise.reject(new Error(`Not a valid spec id: "${e.id}"`));let t=["annotate",e.id,...e.force?["--force"]:[]];return Cs({args:t,cwd:e.cwd,stdio:e.stdio,signal:e.signal})}function UC(e,t,n,o){let r=LC(e,jC(e)?.outputDir??IC),s=OC(r,t);return(s.annotatedMtimeMs??0)>=o?"annotated":n===0&&_C(s)?"skipped":"failed"}function rd(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 ${iw} or later, then /screenshot annotate becomes available.`}var Ra=8;function aw(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>Ra?{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 sd(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 FC({cwd:e.cwd,id:o,...e.force?{force:!0}:{},...e.signal?{signal:e.signal}:{},stdio:"pipe"}),i=UC(e.cwd,o,r,t);n.push({id:o,outcome:i,...i==="failed"?{detail:WC(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 id(e,t){let n=t?.cwd??process.cwd(),o=nd(e);if(!co(n))return console.log("Screenshot capture is not set up in this repo yet. Run: d360-capture init"),{kind:"continue"};let r=ut();if(!xa(r))return console.log(rd(r)),{kind:"continue"};let s=no(n);s&&console.log(s);let i=o.mode==="scope"?o.scope:void 0,{pending:a,done:l,rows:d}=od(n,i),m=o.mode==="all"||o.mode==="scope"?o.force:!1,w=o.mode==="single"?[o.id]:m?[...a,...l]:a;if(w.length===0){let B=l.length>0;return console.log(B?`Every shot${i?` under ${i}`:""} is already drawn. Re-draw them anyway: /screenshot annotate --all --force`:"No shots have been taken yet \u2014 /screenshot capture takes them first."),{kind:"continue"}}let k=new Set(d.filter(B=>B.state==="verified").map(B=>B.id)),{results:S,cliMissing:v}=await sd({cwd:n,ids:w,force:m});if(v)return console.log("d360-capture is not installed. Run: npm i -g document360-capture"),{kind:"continue"};let C=B=>S.filter(M=>M.outcome===B).length;console.log(`\u2713 ${C("annotated")} annotated`+(C("skipped")?` \xB7 ${C("skipped")} already current`:"")+(C("failed")?` \xB7 \u2717 ${C("failed")} failed`:""));for(let B of S.filter(M=>M.outcome==="failed"))console.log(` \u2717 ${B.id}${B.detail?` \u2014 ${B.detail}`:""}`);let A=S.filter(B=>B.outcome==="annotated").map(B=>B.id);if(A.length===0)return{kind:"continue"};let D=A.filter(B=>k.has(B)).length;if(D>Ra)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 L=A.filter(B=>!k.has(B)||D>0);return L.length===0?{kind:"continue"}:(console.log(Dn(L.length)),{kind:"forward-to-agent",prompt:Xt(n,L),display:"/screenshot verify"})}function WC(e){return e.split(/\r?\n/).map(n=>n.trim()).filter(n=>n.length>0&&!/^[▶✓↕]/.test(n)).at(-1)}se();import{existsSync as BC}from"node:fs";import{join as HC}from"node:path";import{builderChannelWired as GC,driftedAnchors as qC,readTestidRequests as VC,testidHandoffPrompt as YC,testidRequestPaths as KC,writerDir as zC}from"document360-engine";async function fr(e,t){let n=t?.cwd;if(n){let r=XC(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 XC(e){let t;try{t=_e(e)}catch{return null}let n=BC(HC(zC(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?[`${ee("\u25CB",g)}No screenshots are planned yet, so there is nothing to stage.`,g(" A screenshot is planned by the article that needs it. /write adds the placeholders as it writes.")]:[`${ee("\u25CB",g)}${r} screenshot${r===1?"":"s"} planned across ${s} article${s===1?"":"s"} \u2014 none captured, none with a spec, and no capture setup yet.`,g(" There is nothing to stage from yet: a checklist is built from what each spec needs, and no specs exist."),g(" /screenshot author writes the specs. Come back to /screenshot checklist once they exist and it will"),g(" tell you what data to stage and which test ids your developers still owe you."),"",g(" Free \u2014 this read your files and called nothing.")]}var lw="-".repeat(64);function cw(e){let t=VC(e);if(t.length===0)return null;let{mdRel:n}=KC(e),o=t.length,r=new Set(t.map(m=>m.file).filter(Boolean)).size,s=`${o} data-testid attribute${o===1?"":"s"}`,i=`${r} source file${r===1?"":"s"}`,a=YC(e,o),l=qC(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 GC(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.)","",lw,a,lw]}}kn();se();import{listOpenForDocs as QC,readProjectConfig as JC}from"document360-engine";function ad(e){try{return QC(e).length}catch{return 0}}function ld(){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 uw(e,t){let n=t?.cwd??process.cwd();return JC(n)?ad(n)===0?(console.log(g("Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)")),{kind:"continue"}):{kind:"forward-to-agent",prompt:ld(),display:"/inbox"}:(console.log(O("No d360-writer config here. Run /init first.")),{kind:"continue"})}se();import{askBuilder as ZC,openGapQuestions as dw,readProjectConfig as eS}from"document360-engine";function As(e){try{return dw(e).length}catch{return 0}}function cd(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 ud(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 pw(e,t,n){let o=t?.cwd??process.cwd();if(!eS(o))return console.log(O("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e.join(" ").trim();if(r===""){for(let s of ud(dw(o)))console.log(s.startsWith(" \xB7")?g(s):s);return{kind:"continue",ownNext:!0}}try{let s=ZC(o,{question:r,...n?{article:n}:{}}),i=As(o);for(let a of cd(s.file,i))console.log(a.startsWith("\u2713")?q(a):g(a))}catch(s){console.log(G(`Could not file the question: ${s.message}`))}return{kind:"continue",ownNext:!0}}se();import{listOpenHints as aS,listOpenForDocs as lS,listOpenDirectives as cS,readProjectConfig as gw,computeSyncStatus as uS,planPull as dS,applyPull as pS,planImport as hS,applyImport as fS,pullDocsUpdates as mS,handoffAvailable as gS,readProductBriefState as wS,readDiscoveryQueue as yS}from"document360-engine";se();import{readProjectConfig as tS,writeProjectConfig as hw,reconcileDocsGit as nS,pullDocsUpdates as oS,probeGitState as rS,resolveGitHandoff as fw,handoffAvailable as sS}from"document360-engine";var Es=e=>e===1?"":"s";function Nn(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 Ca(e,t){let n=fw(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=rS(e);if(!o)return[{tone:"info",text:"Sharing: unavailable \u2014 this folder is not a git repository."}];if(!o.upstream)return[{tone:"warn",text:ee("\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:ee("\u26A0")+`${o.ahead} change${Es(o.ahead)} not shared yet \u2014 run /share`}):s.push({tone:"ok",text:ee("\u2713")+"Everything is shared with your team."}),s}function dd(e,t,n){hw({...t,gitHandoff:{commit:n,push:n}},e);let o=n?{tone:"ok",text:ee("\u2713")+"Sharing on \u2014 d360-writer will save and send its own work from now on."}:{tone:"ok",text:ee("\u2713")+"Sharing off \u2014 d360-writer will leave its work for your coding agent to commit."};return n?[o,...Ca(e,{...t,gitHandoff:{commit:!0,push:!0}})]:[o]}async function Sa(e,t){let n=[],o=fw(t);if(!o.commit)return{lines:[{tone:"info",text:Nn("disabled")}],changed:!1};let r=t;o.push==="unconfirmed"&&sS(e,t)&&(r={...t,gitHandoff:{commit:!0,push:!0}},hw(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 oS(e);if(s.ok&&s.pulled>0){let d=[s.newHints>0?`${s.newHints} new hint${Es(s.newHints)}`:null,s.newMessages>0?`${s.newMessages} new message${Es(s.newMessages)}`:null].filter(Boolean);n.push({tone:"ok",text:ee("\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:ee("\u26A0")+Nn(s.reason,s.detail)});let i=await nS(e,r);if(i.commit&&!i.commit.ok)return n.push({tone:"warn",text:ee("\u26A0")+Nn(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:ee("\u2713")+`Saved ${a} change${Es(a)} to the docs folder.`}),i.push&&!i.push.ok)return n.push({tone:"warn",text:ee("\u26A0")+Nn(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:ee("\u2B06")+`Shared ${l} change set${Es(l)} with your team.`}):a===0&&(s.ok&&s.pulled===0)?n.push({tone:"ok",text:ee("\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 iS={ok:q,info:be,warn:G,error:O};async function mw(e,t){let n=t.cwd,o=tS(n);if(!o)return console.log(O("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase(),s=a=>{for(let l of a)console.log(iS[l.tone](l.text))};if(r==="status")return s(Ca(n,o)),{kind:"continue"};if(r==="on"||r==="off")return s(dd(n,o,r==="on")),{kind:"continue"};if(r)return console.log(O(`Unknown option "${r}". Use /share, /share status, /share on, or /share off.`)),{kind:"continue"};console.log(g("Exchanging work with your team\u2026"));let{lines:i}=await Sa(n,o);return s(i),{kind:"continue"}}function uo(e){let t=0,n=0,o=0,r=0;try{t=aS(e).length}catch{}try{let s=lS(e);n=s.filter(i=>i.kind==="request").length,o=s.filter(i=>i.kind==="answer").length}catch{}try{r=cS(e).length}catch{}return{hints:t,requests:n,answers:o,directives:r}}async function hd(e){let t=gw(e);if(!t)return[];if(!gS(e,t))return[];let n=await mS(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 ${Nn(n.reason,n.detail)}`}]}function fd(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 md(e){let t=fd(e);return t?`Catching up on ${t}\u2026`:"Nothing queued from your builder \u2014 checking Document360 for reviewer comments and feedback\u2026"}function gd(e){return{push:e.includes("--push")||e.includes("--publish"),skipReview:e.includes(xt)}}function wd(e){let t={hold:!1,openQuestions:0,answersPending:0};try{let n=wS(e);return!n||n.status==="confident"?t:{hold:!0,...yS(e)}}catch{return t}}function yd(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:`${ee("\u2139")}Product discovery is still open \u2014 ${n} answer${mr(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:`${ee("\u26A0")}Product discovery isn't finished \u2014 ${n} question${mr(n)} still with your builder.`},{tone:"warn",text:` ${t} until the brief is settled.`}]}return[{tone:"warn",text:`${ee("\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 bd(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${mr(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 bS={status:uS,plan:dS,apply:pS,planImport:hS,applyImport:fS};async function kd(e,t=bS){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 pd=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,mr=e=>e===1?"":"s";function $d(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${mr(e.pulled.length)} into local: ${pd(e.pulled)}`),e.imported.length&&t.push(`\u2713 Imported ${e.imported.length} new portal article${mr(e.imported.length)} into local drafts: ${pd(e.imported)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${mr(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${pd(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 ww(e,t){let n=t?.cwd??process.cwd();if(!gw(n))return console.log(O("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=qe(n,t?.profileName);if(!o.ok)return console.log(O(o.reason)),{kind:"continue"};let{push:r}=gd(e);for(let a of await hd(n))console.log(a.tone==="ok"?q(a.text):G(a.text));console.log(g("Reconciling with Document360 (pulling any portal changes)\u2026"));let s=await kd({cwd:n,profileName:t?.profileName});for(let a of $d(s))console.log(a.startsWith("\u2713")?q(a):a.startsWith("\u2139")?g(a):G(a));let i=wd(n);for(let a of yd(i))console.log(a.tone==="warn"?G(a.text):g(a.text));return console.log(g(md(uo(n)))),{kind:"forward-to-agent",prompt:bd(i),display:`/catch-up${r?" --push":""}`}}se();import{resolveActiveProfile as RS,resolveProjectId as CS,loadProfileMap as SS,readCommentLedger as PS,isCommentOpen as TS,saveOpenCommentCount as AS,loadCommentSweepMemory as ES,recordCommentSweep as DS,planCommentSweep as NS,sweepOpenComments as jS,loadUserNames as IS,writeReviewerNotes as LS,sweptFromResult as OS,needsFullArchivePass as _S,reviewerNotesPath as MS,commentHtmlToText as yw,annotatedText as FS,readProjectConfig as US,loadPortalLabels as WS,portalBreadcrumb as xd,portalCategoryPath as BS,resolveModelForOperation as HS,runPartitioned as GS,snapshotArticles as qS,EMPTY_PORTAL_LABELS as VS}from"document360-engine";import Ce from"picocolors";import{CONTENT_CAP_VERSION as kS,stampArticles as $S,articlesChangedSince as vS,docsRootOf as xS}from"document360-engine";function po(e,t,n="",o){let r=[];try{r=vS(e,t)}catch{return{changed:[],cta:null}}if(r.length===0)return{changed:[],cta:null};try{$S(e,r,{writtenCap:kS,reviewedCap:0,checkedCap:0})}catch{}let s=xS(e),i=m=>{let w=m.replace(/\\/g,"/");return w.startsWith(`${s}/`)?w.slice(s.length+1):w},a=Vt(r.map(i)),l=r.length,d=a?"/push":"/push --all";try{return{changed:r,cta:Bt(e,{text:`${n}${l} article${l===1?"":"s"} updated \u2014 ${d} saves ${l===1?"it":"them"} to Document360 as ${l===1?"a draft":"drafts"}.`,cmd:d},n,a,o)}}catch{return{changed:r,cta:null}}}var kw=300,Ds=3;function YS(e,t){let n=Ei(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||$n(n).toLowerCase()===o}async function Pa(e,t,n={}){let o=RS(e,t),r={profile:o.name,connection:o.connection,projectId:o.project.projectId,projectName:o.project.projectName},s=CS(r,o.project.projectId),i=SS(e,o.name);if(!i)return{threads:[],answered:[],labels:VS,scanned:0,failed:[],truncated:0,skipped:0,archived:!1};let a=PS(e,o.name),l=new Set(Object.values(a).map(z=>z.articlePath).filter(z=>!!z)),d=Object.keys(a).length===0||l.size>0,m=n.articleIds?.length?new Set(n.articleIds):null,w=!!(m||n.path||n.scope),k=Object.entries(i.articles).filter(([,z])=>!!z.id).filter(([z,de])=>m?m.has(de.id):n.path?z.replace(/\\/g,"/")===n.path.replace(/\\/g,"/"):n.scope?YS(z,n.scope):!0).map(([z,de])=>({articleId:de.id,path:z,title:Di(e,z),answered:w||(d?l.has(z):!0)})),S=k.slice(0,kw),v=await WS(r,s,o.project.workspaceId,{cwd:e,profile:o.name}),C=w||n.full?{read:S,skipped:[]}:NS(S,{live:v.live,stateOf:z=>v.articles.get(z),memory:ES(e,o.name),alwaysRead:new Set(k.filter(z=>l.has(z.path)).map(z=>z.articleId))}),A=o.project.languageCode,D=_S(e)||!!n.full,L=await jS(r,s,C.read,{isOpen:(z,de)=>TS(a,z.id??"",de,z),...A?{langCode:A}:{},...n.onProgress?{onProgress:n.onProgress}:{},...D?{includeResolved:D}:{}}),B=L.threads.length>0||L.answered.length>0?await IS(r,s):new Map,M=LS(e,OS(L.threads,L.answered,z=>xd(v,z)),{userNames:B,ourReplyIds:Object.values(a).flatMap(z=>z.replyIds??[]),...D?{completeFor:C.read.filter(z=>!L.failed.some(de=>de.articleId===z.articleId)).map(z=>z.articleId)}:{}});w||AS(e,o.name,L.threads.length);let X=new Map;for(let z of[...L.threads,...L.answered])X.set(z.articleId,(X.get(z.articleId)??0)+1);return DS(e,o.name,{live:v.live,read:C.read.map(z=>z.articleId),failedIds:L.failed.map(z=>z.articleId),threadCounts:X,latestVersionOf:z=>v.articles.get(z)?.latestVersion}),{threads:L.threads,answered:L.answered,labels:v,scanned:L.scanned,failed:L.failed,truncated:Math.max(0,k.length-S.length),skipped:C.skipped.length,archived:M}}function KS(e,t=96){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n}var bw=500;function zS(e){let t=FS(e.comment);if(!t)return"a passage";let n=t.replace(/\s+/g," ").trim();if(n.length<=bw)return e.comment.commented_text_truncated?`\u201C${n}\u2026\u201D
|
|
412
412
|
(Document360 sends the first 500 characters of a highlight)`:`\u201C${n}\u201D`;let o=n.slice(0,bw).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
|
|
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 Cw(){console.log(
|
|
418
|
-
`).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function
|
|
419
|
-
|
|
420
|
-
`;
|
|
421
|
-
`,"utf8");let $=mo(e)??{projectId:""};return Ld({...$,styleGuide:{...$.styleGuide,pulledFrom:{styleGuideId:a.id,name:a.name??a.id,pulledAt:new Date().toISOString(),contentHash:_P("sha1").update(x).digest("hex").slice(0,16)}}},e),{lines:[me("\u2713",`Pulled "${a.name??a.id}" into .d360-writer/style-guide.md (${x.length.toLocaleString()} characters).`),...f,w(" This is PROSE, not rules \u2014 /review judges against it, and the writer now writes to it."),w(" Turn its mechanical parts into checks: /style-guide compile"),w(" Restarting the agent so it writes to the new guide\u2026")],restart:!0}}function WP(e){let t=jd(e).rules.filter(n=>n.pack.toLowerCase()===Ns.toLowerCase()).map(n=>n.id);return{prompt:CP({guide:SP(e),packName:Ns,existingRuleIds:t}),display:"/style-guide compile"}}function BP(e){let t=AP(e),n=Od(t)?Ow(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."),w(" Reviewers comment on your drafts in Document360; /comments reads them, and every read"),w(" keeps a copy in .d360-writer/reviewer-notes.md. Run /comments first.")]}:{kind:"run",prompt:TP({notes:n,existingRules:PP(e),houseRulesFile:".d360-writer/house-rules.md"}),display:"/style-guide learn"}}function Mw(){return[w(" Read what it wrote: git diff .d360-writer/house-rules.md"),w(" These rules apply from now on \u2014 the writer follows them and /review judges against them."),w(" Disagree with one? Delete the line. It is your file, and nothing regenerates it."),w(" Restarting the agent so it writes to the new rules\u2026")]}function Fw(){return[w(` Review what it wrote: git diff .d360-writer/styles/${Ns}/`),w(` Anything it could not check mechanically is listed in .d360-writer/styles/${Ns}/UNCHECKABLE.md \u2014 /review judges those.`),w(` Turn them on when you are happy: /style-guide use ${Ns.toLowerCase()} (they start as warnings, never blocking)`)]}var pt=(e,t)=>`${e} ${t}${e===1?"":"s"}`,Dd=e=>/^v\d/i.test(e)?e:`v${e}`;function Uw(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 HP(e){let n=mo(e)?.styleGuide?.pulledFrom;return n?`.d360-writer/style-guide.md \u2014 pulled ${n.pulledAt.slice(0,10)} from "${n.name}"`:Od(Lw(e))?".d360-writer/style-guide.md (yours)":"the built-in default"}function GP(e){let t=mo(e),n=jd(e),o=(t?.styleGuide?.packs??[]).filter(Boolean),r=n.packs.filter(l=>l.name.toLowerCase()===fo),s=n.packs.filter(l=>l.name.toLowerCase()!==fo),i=[`Style guide: ${HP(e)}`,`Rule packs: ${s.length>0?s.map(l=>`${l.name.toLowerCase()} ${Dd(l.version)}`).join(", "):w("none chosen")}`,`Always on: ${w(`d360 (correctness, built in \u2014 ${pt(ja.length,"rule")})`)}`];for(let l of r)i.push(` ${w(`${l.name.toLowerCase()} ${Dd(l.version)} (anti-slop \u2014 ${pt(l.ruleCount,"rule")})`)}`);r.length>0&&(i.push(w(" Every article here is machine-written, so these cannot be switched off by")),i.push(w(" choosing another pack. styleGuide.humanise: false turns them off deliberately.")));let a=[...ja.map(l=>({severity:l.severity})),...n.rules.map(l=>({severity:l.severity}))];i.push("",`${pt(a.length,"rule")} active \xB7 ${Uw(a)}`);try{let l=Id({cwd:e}),d=l.findings.filter(f=>!f.baselined),g=d.filter(f=>f.severity==="error").length;i.push(""),i.push(g===0?me("\u2713",`No style errors across the docs${d.length>0?`, though ${pt(d.length,"other issue")} ${d.length===1?"is":"are"} reported`:""}.`):me("\u2717",`${pt(g,"style error")} \u2014 /lint --blocked shows them, /lint --blocked --fix corrects them.`)),l.baselinedCount>0&&i.push(me("\u2139",`${pt(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",`${pt(l.ruleErrors.length,"rule")} could not be loaded: ${l.ruleErrors.slice(0,2).map(f=>`${f.ruleId} (${f.reason})`).join("; ")}`))}catch{}return i.push(""),i.push(w(" See them all: /style-guide list \xB7 change: /style-guide use <preset> \xB7 one rule: /style-guide explain <rule>")),_d(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(w(" Worth settling now rather than later: it shapes every article written from here, and")),i.push(w(" changing it once a knowledge base exists means going back over what is already written."))),i}function Nd(e){let t=mo(e),n=new Set(Iw(t?.styleGuide)),o=jw(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===fo,g=l?"\u2713":"\xB7",f=d?w("(always on)"):l?w("(active)"):"",x=i.local?w(" [yours]"):"";r.push(` ${g} ${a.padEnd(s)}${x} ${i.description??""}`),r.push(` ${w(`${pt(i.rules.length,"rule")} \xB7 ${Uw(i.rules)} \xB7 ${Dd(i.version)}`)} ${f}`),i.errors.length>0&&r.push(me("\u26A0",`${pt(i.errors.length,"rule")} in this pack could not be loaded \u2014 /style-guide explain names them.`))}return o.every(i=>i.name.toLowerCase()===fo)&&(r.push(""),r.push(w(" The Microsoft and Google style guides are not installed in this build yet."))),r.push(""),r.push(w(" Turn one on: /style-guide use <name> (this replaces the chosen set, it does not add to it)")),r.push(w(" Several: /style-guide use microsoft,google")),r.push(w(" Back to none: /style-guide use none")),r}function qP(e,t){if(!t)return[me("\u26A0","Name a rule: /style-guide explain Humanise.EmDash")];let n=jd(e),o=ja.find(d=>d.id.toLowerCase()===t.toLowerCase()),r=n.rules.find(d=>d.id.toLowerCase()===t.toLowerCase());if(!o&&!r){let d=[...ja.map(g=>g.id),...n.rules.map(g=>g.id)].filter(g=>g.toLowerCase().includes(t.toLowerCase())).slice(0,5);return[me("\u26A0",`No active rule called "${t}".`),...d.length>0?[w(` Did you mean: ${d.join(", ")}`)]:[w(" /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(w(` ${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=Id({cwd:e}).findings.filter(f=>f.ruleId===s),g=d.filter(f=>!f.baselined);l.push(""),l.push(d.length===0?" Currently: no findings.":` Currently: ${pt(g.length,"finding")}${d.length!==g.length?`, plus ${d.length-g.length} baselined and hidden`:""}.`)}catch{}return l.push(""),o?(l.push(w(" Built-in checks are grounded in your product's own source and cannot be switched off \u2014 they")),l.push(w(" catch defects of fact, not matters of taste."))):(l.push(i==="error"?w(' This one BLOCKS publishing \u2014 your config sets it to "error" deliberately.'):w(" Style rules never block publishing. Fix it when you want to; it will not hold a page back.")),l.push(w(` Silence it everywhere: add "${s}": "off" to styleGuide.rules in .d360-writer/config.json`)),i!=="error"&&l.push(w(" Silence one passage: <!-- vale "+s+" = NO --> \u2026 <!-- vale "+s+" = YES -->"))),l}function VP(e,t){let n=(t??"").trim();if(!n)return{lines:[me("\u26A0","Name the packs to use: /style-guide use microsoft (or `none`)"),...Nd(e)],restart:!1};let o=n.toLowerCase()==="none"?[]:n.split(/[,\s]+/).map(d=>d.trim().toLowerCase()).filter(Boolean),r=new Map(jw(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(", ")}.`),"",...Nd(e)],restart:!1};let i=mo(e)??{projectId:""};Ld({...i,styleGuide:{...i.styleGuide,packs:o,decidedAt:new Date().toISOString()}},e),$P();let a=[me("\u2192",`Switching to: ${o.length>0?o.join(", "):"the built-in checks only"}${o.includes(fo)?"":` (+ ${fo}, always on)`}\u2026`)];try{let d=Id({cwd:e}),g=new Set(d.findings.map(f=>f.path)).size;if(d.findings.length===0)a.push(me("\u2713",g===0?"No articles yet \u2014 everything you write from here is held to the full set.":"Nothing to record: your articles are already clean against these rules."));else{let f=vP(e),x=kP(d.findings,RP(e));xP(e,x),a.push(me("\u2713",`Recorded ${pt(d.findings.length,"existing issue")} across ${pt(g,"article")} as accepted.`),w(" .d360-writer/style-baseline.json \u2014 commit it. It defines what the publish gate lets through, and a"),w(" 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 ${pt(g,"article")} do not follow ${o.join(", ")} \u2014 they are exempt, not compliant.`),w(" To bring them up to it: /review --all --fix, then /lint --all --fix. That is a pass over every"),w(" article and it costs accordingly \u2014 which is why this is worth settling before a knowledge base exists.")),f&&a.push(w(` (Replaced the baseline recorded ${f.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(w(" Run /lint to see the current state before publishing."))}let l=_w(e);return l&&a.push(l),a.push(w(" Restarting the agent so it writes to the new rules\u2026")),{lines:a,restart:!0}}async function La(e,t){let{sub:n,value:o}=Ia(e),r=s=>{for(let i of s)console.log(i);console.log("")};switch(n){case"list":return r(Nd(t.cwd)),{kind:"continue"};case"explain":return r(qP(t.cwd,o)),{kind:"continue"};case"use":{let s=VP(t.cwd,o);return r(s.lines),s.restart?{kind:"clear"}:{kind:"continue"}}case"keep":return r(FP(t.cwd)),{kind:"continue"};case"pull":{let s=await UP(t.cwd,o,t.profileName);return r(s.lines),s.restart?{kind:"clear"}:{kind:"continue"}}case"compile":{let s=WP(t.cwd);return{kind:"forward-to-agent",prompt:s.prompt,display:s.display}}case"learn":{let s=BP(t.cwd);return s.kind==="nothing"?(r(s.lines),{kind:"continue"}):{kind:"forward-to-agent",prompt:s.prompt,display:s.display}}default:return r(GP(t.cwd)),{kind:"continue"}}}se();import{lintDocs as Ud,loadStyleGuide as Qw,buildReviewPrompt as Jw,readProjectConfig as Zw,DEFAULT_DOCS_DIR as ey,listArticleFiles as gr,normalizeScope as aT,planPartitions as lT,runPartitioned as cT,partitionCoverage as uT,resolveModelForOperation as dT,stampArticles as pT,reviewStalePaths as hT,readReviewerNotes as ty,renderNotesForPrompt as ny,readDocsPlan as fT,CONTENT_CAP_VERSION as mT}from"document360-engine";import{listArticleFiles as YP,lintDocs as KP,planFindingPartitions as zP,planPartitions as XP,readDocsPlan as QP,readProjectConfig as JP,runRate as Ww,DEFAULT_DOCS_DIR as ZP}from"document360-engine";function Bw(e){switch(e.cmd){case"/review":return{concurrency:In,maxPerPartition:Fd,minutesPerBatch:5};case"/write":return{concurrency:3,minutesPerBatch:4};case"/lint":return{concurrency:3,minutesPerBatch:2};default:return{concurrency:3,minutesPerBatch:2}}}function eT(e,t){let n=KP({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:zP(o).length}}function tT(e,t){try{if(t.cmd==="/write"){let n=(JP(e)?.docsDir??ZP).replace(/\/+$/,""),o=QP(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:Rn(e,n,r)}return t.cmd==="/review"?go(e,[...t.flags],t.scope):YP(e,t.scope)}catch{return null}}function Hw(e,t){let n=jn(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 jn(e,t){let n=qi(t);if(!n||!Rc(n))return null;let o=Bw(n),r=n.cmd==="/lint"?Md(()=>eT(e,n)):null,s=r?null:tT(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:XP(s,o.maxPerPartition?{maxPerPartition:o.maxPerPartition}:void 0).length,l=Math.ceil(a/o.concurrency),d=Md(()=>Ww(e,n.cmd)),g=l*(d?.minutesPerWave??o.minutesPerBatch),f=r?r.lead:`${i} articles`,x=d?.usdPerArticle!==void 0?` \xB7 ~${Yw(i*d.usdPerArticle)}`:"";return`${f} \xB7 ${a} batch${a===1?"":"es"} \xB7 ~${Vw(g)}${x}`}var Gw=.7,qw=1.4;function Vw(e){let t=Math.max(1,Math.round(e*Gw)),n=Math.max(t,Math.round(e*qw));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 Yw(e){let t=e*Gw,n=e*qw;return n>=10?`$${Math.round(t)}\u2013${Math.round(n)}`:`$${t.toFixed(2)}\u2013${n.toFixed(2)}`}function Md(e){try{return e()}catch{return null}}function Oa(e,t,n,o){if(n<4||o<1)return null;let r=Bw({cmd:t,scope:void 0,flags:new Set,args:[]}),s=Math.ceil(o/r.concurrency),i=Md(()=>Ww(e,t)),a=s*(i?.minutesPerWave??r.minutesPerBatch),l=i?.usdPerArticle!==void 0?` \xB7 ~${Yw(n*i.usdPerArticle)}`:"";return`~${Vw(a)}${l}`}import{renderGapsForPrompt as oy}from"document360-engine";import{recordRunSample as gT}from"document360-engine";se();import{readProjectConfig as nT,loadProfileMap as oT,resolveActiveProfile as rT,desiredCategoryOrder as sT,desiredArticleOrder as iT}from"document360-engine";function Kw(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}var zw=e=>e.replace(/\\/g,"/").split("/").pop()??e;function js(e,t){try{if(!nT(e))return[];let n=rT(e,t),o=oT(e,n.name);if(!o)return[];let r=new Map;for(let i of iT(o)){let a=r.get(i.categoryPath);a?a.push(i):r.set(i.categoryPath,[i])}let s=[];for(let i of sT(o)){s.push(Kw(zw(i.path)));for(let a of(r.get(i.path)??[]).sort((l,d)=>l.order-d.order))s.push(` ${Kw(zw(a.path))}`)}return s}catch{return[]}}async function Xw(e,t){let n=js(t.cwd,t.profileName);if(n.length===0)return console.log(w("No documentation structure yet \u2014 run /init and author some articles first.")),{kind:"continue"};console.log(J("Documentation order (categories \u2192 articles):"));for(let o of n)console.log(o);return console.log(""),{kind:"continue"}}function Wd(e,t){return cs(e,gr(e,t))}function Bd(e,t){return hT(e,gr(e,t),mT)}function Is(e){return e.includes("--blocked")||e.includes("--stale")}function go(e,t,n){return t.includes("--blocked")?Wd(e,n):t.includes("--stale")?Bd(e,n):gr(e,n)}function ry(e,t,n){let o;try{o=fT(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 sy(e,t){let n=Zw(e);if(!n)return null;let o=(n.docsDir??ey).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),s=Is(t),i=t.find(C=>!C.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),a=Ud({cwd:e}),l=i?aT(o,i):"",d=l?a.filter(C=>C.path===`${o}/${l}`||C.path.startsWith(`${o}/${l}/`)):a,g=s?go(e,t,i):void 0,f=g?d.filter(C=>g.includes(C.path)):d,x=i||s?"":js(e).join(`
|
|
422
|
-
`),
|
|
423
|
-
`),display:`/reorder${n?` ${n}`:""}`}}async function ay(e,t){if(En("reorder",e)){let o=
|
|
424
|
-
`)}function Kd(e,t={}){let n
|
|
425
|
-
|
|
426
|
-
Optional from here: ${e} of your ${t} docs campaign step${we(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${we(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${we(r)} waiting on your articles.`})}if(e.conflicts>0){let r=e.conflicts;n.push({key:"resolve",bullet:`${r} article${we(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${we(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${we(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${we(r)}.`,blockedBy:["resolve"]})}if(e.hasDocs&&e.pendingWrites>0){let r=e.pendingWrites;n.push({key:"write",bullet:`${r} planned article${we(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${we(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${we(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${we(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${we(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${we(r)} \u2014 nothing reaches your readers until it has.`,dependsOn:["catchup","comments","review"]})}let o=e.shotsToAnnotate>0?{key:"annotate",bullet:`${e.shotsToAnnotate} screenshot${we(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${we(e.shotsToAnnotate)} already taken.`}:e.shotsToRecapture>0?{key:"annotate",bullet:`${e.shotsToRecapture} screenshot${we(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${we(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${we(r)} changed locally \u2014 ready to send to Document360`,lead:{kind:"cmd",cmd:"/push",reason:`it saves your ${r} local edit${we(r)} to Document360 as drafts`},picker:null,follow:`Then /push saves your ${r} local edit${we(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${we(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${we(r)} live to your readers \u2014 it lists them and asks first`},picker:null,follow:`Then /publish takes the ${r} draft${we(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:wy(s.body),l=s.run?i??void 0:wy(s.body,340,2)??void 0,d=`docs campaign: ${r.done} of ${r.total} step${we(r.total)} done`,
|
|
413
|
+
(+${r} more character${r===1?"":"s"}${e.comment.commented_text_truncated?", and Document360 caps a highlight at 500":""})`}function XS(e,t){let n=BS(t,e.articleId);return n.length>0?n.join(" \u203A "):e.path?$n(e.path):""}function QS(e,t){return t.articles.get(e.articleId)?.title?.trim()||e.title||(e.path?rs(e.path):e.articleId)}function JS(e,t){return xd(t,e.articleId,{category:e.path?$n(e.path):null,title:e.title??(e.path?rs(e.path):null)})??e.path??e.articleId}function ho(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:XS(o,t),title:QS(o,t),label:JS(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 ZS=100,eP=120,$w=(e,t)=>Math.max(40,Math.min(e??96,t));function vw(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`),`${Ce.bold("Reviewer comments")} ${r.join(` ${Ce.gray("\xB7")} `)}`}function vd(e){let t=[],n=o=>o===1?"":"s";if(e.skipped>0&&t.push(Ce.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(`${ee("\u26A0",Ce.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=xd(e.labels,o.articleId,{title:o.title})??o.title??o.articleId;t.push(` ${Ce.gray(`${r} \u2014 ${KS(o.error,60)}`)}`)}e.failed.length>5&&t.push(` ${Ce.gray(`+${e.failed.length-5} more`)}`),t.push(Ce.gray(" Run /comments again to retry them."))}return e.truncated&&t.push(`${ee("\u26A0",Ce.yellow)}Checked the first ${kw} articles; ${e.truncated} not checked this run.`),e.archived&&(e.threads.length>0||e.answered.length>0)?t.push(Ce.gray(` Everything reviewers have written is kept in ${MS(".").replace(/\\/g,"/").replace(/^\.\//,"")} \u2014 it outlives a rewrite.`)):!e.archived&&(e.threads.length>0||e.answered.length>0)&&t.push(`${ee("\u26A0",Ce.yellow)}Couldn\u2019t write the reviewer-notes file, so Document360 is still the only copy of these notes.`),t}function Ns(e,t={}){let n=[],o=a=>a===1?"":"s",r=e.answered.length,s=()=>{if(!(!t.showAnswered||r===0)){n.push(` ${Ce.gray(`Answered, waiting on the reviewer (${r})`)}`);for(let a of ho(e.answered,e.labels))n.push(` ${Ce.gray(`${a.label} \u2014 ${a.threads.length} thread${o(a.threads.length)}`)}`);n.push("")}};if(e.threads.length===0){let a=r>0?` ${Ce.gray("\xB7")} ${r} answered, awaiting reviewer`:"",l=e.scanned+e.skipped;return n.push(e.skipped>0?`${ee("\u2713",Ce.green)}No open reviewer comments in the ${e.scanned} article${o(e.scanned)} checked ${Ce.gray("\xB7")} ${e.skipped} of ${l} not checked${a}`:`${ee("\u2713",Ce.green)}No open reviewer comments across ${e.scanned} article${o(e.scanned)}.${a}`),r>0?(n.push(Ce.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(Ce.gray(" /comments --answered lists them."))):n.push(Ce.gray(" Reviewers leave these by highlighting text in a draft in the Document360 portal and commenting on it.")),n.push(""),s(),n.push(...vd(e)),n}let i=ho(e.threads,e.labels);return n.push(vw(e)),n.push(""),n.push(hs(["#","Category","Article","Comments"],i.map((a,l)=>[`${l+1}`,a.category||"(root)",a.title,`${a.threads.length}`]),$w(t.width,ZS),{plain:!0,align:["left","left","left","right"]})),n.push(""),s(),n.push(...vd(e)),n}function Ta(e,t={}){let n=s=>s===1?"":"s",o=[`${Ce.gray("Category:")} ${e.category||"(root)"}`,`${Ce.gray("Article: ")} ${Ce.bold(e.title)}`,Ce.gray(`${e.threads.length} comment${n(e.threads.length)} from your reviewers`),""],r=e.threads.map(s=>{let i=[yw(s.comment.comment)||"(empty comment)"];for(let a of s.comment.replies??[])i.push(`\u21B3 ${yw(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)"),[zS(s),i.join(`
|
|
414
|
+
`)]});return o.push(hs(["Annotated text","Comment"],r,$w(t.width,eP),{plain:!0})),o.push(""),o}function Aa(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 Rd(e,t={}){let n=ho(e.threads,e.labels);if(t.full&&n.length===1){let o=n[0];return[vw(e),"",...Ta(o,t),...vd(e)]}return Ns(e,t)}function tP(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 Cd(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.`,"",...tP({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 Sd(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 nP(e,t,n){if(t.length===0)return{kind:"continue"};let o=t.reduce((w,k)=>w+k.threads.length,0),{model:r}=HS(e.cwd,"standard"),s=new Map(t.map(w=>[w.label,w])),i=t.map(w=>({label:w.label,paths:w.path?[w.path]:[]}));console.log(g(`Answering ${o} comment${o===1?"":"s"} across ${i.length} article${i.length===1?"":"s"} (\u2264${Ds} 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=qS(e.cwd);try{for await(let w of GS({cwd:e.cwd,partitions:i,promptFor:k=>{let S=s.get(k.label);return Cd({articleId:S.articleId,label:S.label,path:S.path,count:S.threads.length,resolve:n.resolve})},concurrency:Ds,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),allowCommentResolve:n.resolve,model:r}))if(w.type==="partition_status")w.status==="running"?console.log(g(` \u25B8 ${w.label} \u2014 answering\u2026`)):w.status==="done"?console.log(q(` \u2713 ${w.label}`)):console.log(O(` \u2717 ${w.label}`));else if(w.type==="run_done"){let k=w.results.filter(S=>!S.ok);console.log(""),console.log(`${w.results.length-k.length}/${i.length} article${i.length===1?"":"s"} answered.`),k.length&&console.log(G(`\u26A0 ${k.length} left untouched (their comments are still open, so nothing was promised to those reviewers): ${k.map(S=>S.label).join(", ")}`)),w.blocked&&console.log(G(`\u26A0 ${w.blocked}`)),w.allEmpty&&console.log(G("\u26A0 No agent produced any work this run \u2014 nothing was changed or answered.")),console.log(g(Kt(Ct(a,w.results,w.totalCostUsd))))}}catch(w){console.log(O(`Answering comments failed: ${w.message}`))}let m=po(e.cwd,l,"","/comments").changed.length;return m>0&&console.log(`${m} article${m===1?"":"s"} changed, and that new text has not been read by an editor \u2014 ${m===1?"it":"they"} can go live once /review has been over ${m===1?"it":"them"}.`),{kind:"continue"}}async function xw(e,t){let n=t?.cwd??process.cwd();if(!US(n))return console.log(O("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=qe(n,t?.profileName);if(!o.ok)return console.log(O(o.reason)),{kind:"continue"};let r=Sd(e);console.log(g("Checking Document360 for reviewer comments\u2026"));let s;try{s=await Pa(n,t?.profileName,r.scope)}catch(a){return console.log(O(`Couldn\u2019t read comments from Document360: ${a.message}`)),{kind:"continue"}}for(let a of Rd(s,{full:!!r.scope.path,showAnswered:r.showAnswered}))console.log(a);if(s.threads.length===0)return{kind:"continue"};if(r.answer&&t)return nP(t,ho(s.threads,s.labels),{resolve:r.resolve});let i=ho(s.threads,s.labels)[0];return console.log(`${ee("\u2192",Ce.yellow)}${Ce.bold("/comments <article>")} shows one article\u2019s comments in full `+Ce.gray(i?.path?`(e.g. /comments ${i.path})`:"(by its local path)")),console.log(`${ee("\u2192",Ce.yellow)}${Ce.bold("/comments --answer")} fixes each one, updates the draft in Document360, then replies in the thread `+Ce.gray("(one article at a time: /comments --answer <article>, or --scope <category>)")),{kind:"continue"}}se();import{spawn as Rw}from"node:child_process";import{mkdirSync as oP,openSync as rP,readFileSync as sP}from"node:fs";import{dirname as iP,join as aP}from"node:path";import{logsDir as lP}from"document360-engine";var gr="document360-writer",js=`npm i -g ${gr}@latest`,cP="document360-capture";function uP(){return new Promise(e=>{try{let t=Rw("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 Ea(){return aP(lP(),"self-update.log")}function Da(e){return/\bEACCES\b|permission denied|EPERM|operation not permitted/i.test(e)?process.platform==="win32"?`Permission denied. Run ${js} from an Administrator terminal.`:`Permission denied \u2014 your global npm folder isn't writable. Either run sudo ${js} , 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: ${js}`:/EBADENGINE|Unsupported engine/i.test(e)?`Your Node version is too old for this release. Install Node 20 or later, then run: ${js}`:`Run manually: ${js}`}function dP(e,t=6){return e.split(/\r?\n/).map(n=>n.trimEnd()).filter(Boolean).slice(-t).join(`
|
|
416
|
+
`)}async function Na(){let e=process.platform==="win32",n=await uP()?[gr,cP]:[gr],o=Ea(),r=null;try{oP(iP(o),{recursive:!0}),r=rP(o,"w")}catch{r=null}let s=()=>{try{return dP(sP(o,"utf8"))}catch{return""}};return new Promise(i=>{try{let a=Rw(`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 Cw(){console.log(g("Updating the d360-writer toolchain\u2026"));let e=await Na();return e.ok?(console.log(q(`\u2713 Updated ${e.packages.join(" + ")}. Exit (/exit) and relaunch d360-writer to apply.`)),{kind:"continue"}):(console.log(O(`Update failed. ${Da(e.output)}`)),e.output&&console.log(g(e.output)),console.log(g(`Full output: ${Ea()}`)),{kind:"continue"})}se();kn();import{existsSync as Pd,rmSync as pP}from"node:fs";import{basename as Sw,resolve as Td}from"node:path";import{execFileSync as hP}from"node:child_process";import{input as fP}from"@inquirer/prompts";import{readProjectConfig as mP,devHintsGuidePath as gP}from"document360-engine";var wP=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],yP=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),ja=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),Pw=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function Tw(e){let t=ja(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:Pw(t)?!0:yP.has(t)}function Ad(e){let t=null;try{t=mP(e)}catch{t=null}let n=new Set(wP);for(let o of[ja(t?.docsDir),ja(t?.captureDir),ja(t?.outputDir)])o&&Pw(o)&&n.add(o);return[...n].filter(o=>Tw(o)&&Pd(Td(e,o)))}function Ed(e,t){let n=[],o=[];for(let r of t){if(!Tw(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{pP(Td(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function Aw(e,t){try{return hP("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 bP(e){return Aw(e,".d360-writer/hints")}function kP(e){return Aw(e,".d360-writer/messages")}function Dd(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=bP(e),o=kP(e),r=Pd(Td(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: ${Sw(e)}`]}async function Ew(e,t){let n=Ad(t.cwd);for(let l of Dd(t.cwd,n))console.log(n.length===0?g(l):l);if(n.length===0)return{kind:"continue"};let o=Sw(t.cwd);if((await t.withPausedInput(()=>fP({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(G("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=Pd(gP(t.cwd)),{removed:i,failed:a}=Ed(t.cwd,n);console.log(q(`\u2713 Reset complete \u2014 removed ${i.length} item${i.length===1?"":"s"}. The repo is back to its original state.`));for(let l of a)console.log(O(` \u2717 ${l.path}: ${l.error}`));if(s){for(let l of Si())console.log(l);console.log(g("(Select and copy the prompt above to paste into your coding agent.)"))}return console.log(g("Set up d360-writer again with /init (then /login, /workspace).")),{kind:"continue"}}se();import{buildBaseline as $P,buildRegistry as Id,clearRegistryCache as vP,lintArticles as Ld,listAvailablePacks as jw,readProjectConfig as mo,readStyleBaseline as xP,resolveActivePacks as Iw,styleGuidePath as Lw,writeProjectConfig as Od,writeStyleBaseline as RP,activeRuleSet as CP,buildStyleCompilePrompt as SP,loadStyleGuide as PP,loadHouseRules as TP,buildStyleLearnPrompt as AP,reviewerNotesPath as EP,listStyleGuides as DP,getStyleGuide as NP,resolveActiveProfile as jP,resolveProjectId as IP,styleGuideSettled as LP,STYLE_GUIDE_MAX_CHARS as Dw,BUILTIN_RULES as Ia,ALWAYS_ON_PACK as fo}from"document360-engine";import{existsSync as _d,mkdirSync as OP,readFileSync as Ow,writeFileSync as Nw}from"node:fs";import{dirname as _P}from"node:path";import{createHash as MP}from"node:crypto";function La(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 FP(e){try{return cm(e,"/style-guide")?.title??null}catch{return null}}function Md(e){try{return!LP(mo(e)?.styleGuide)}catch{return!1}}function _w(e){let t=FP(e);if(!t)return null;try{return tr(e,t).ok?me("\u2713",`That settles a docs-campaign step \u2014 marked done: ${t}`):null}catch{return null}}function UP(e){let t=mo(e)??{projectId:""},n=Iw(t.styleGuide).filter(s=>s!==fo);Od({...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."),g(" Change your mind any time: /style-guide use microsoft \xB7 see the options: /style-guide list")],r=_w(e);return r&&o.push(r),o}var Is="House";async function WP(e,t,n){let o,r;try{let C=jP(e,n);o={profile:C.name,connection:C.connection,projectId:C.project.projectId,projectName:C.project.projectName},r=await IP(o,C.project?.projectId)}catch(C){return{lines:[me("\u2717",`Not signed in to Document360: ${C instanceof Error?C.message:String(C)}`),g(" Run /login first.")],restart:!1}}let s=await DP(o,r);if(s.kind!=="ok")return{lines:[me("\u26A0",`Document360 didn't return your style guides \u2014 ${s.reason}.`),g(" Nothing is blocked. Your house style guide lives at .d360-writer/style-guide.md \u2014 write or paste"),g(" it there directly, and /review and the writer both read it. /style-guide compile then turns its"),g(" mechanical parts into checks.")],restart:!1};if(s.guides.length===0)return{lines:[me("\u2139","This Document360 project has no style guides yet."),g(" Admins create them in the portal, or write your own at .d360-writer/style-guide.md.")],restart:!1};if(!t)return{lines:["Style guides in this Document360 project:","",...s.guides.map((A,D)=>{let L=[A.language_code,A.created_by_name,A.created_at?.slice(0,10)].filter(Boolean).join(" \xB7 ");return` ${D+1} ${A.name??A.id}${A.is_default?g(" (default)"):""}${L?g(` ${L}`):""}`}),"",g(" Pull one: /style-guide pull 1 (or paste its id)")],restart:!1};let i=Number(t),a=Number.isInteger(i)&&i>=1&&i<=s.guides.length?s.guides[i-1]:s.guides.find(C=>C.id===t);if(!a)return{lines:[me("\u2717",`No style guide numbered or identified by "${t}". Run /style-guide pull to list them.`)],restart:!1};let l=await NP(o,r,a.id,{langCode:a.language_code});if(l.kind!=="ok"){let C=l.kind==="notFound"?"Document360 could not find it (style guides are per language)":l.reason;return{lines:[me("\u2717",`Could not read "${a.name??a.id}" \u2014 ${C}.`)],restart:!1}}let d=(l.guide.content??"").trim();if(!d)return{lines:[me("\u26A0",`"${a.name??a.id}" has no content yet \u2014 nothing to pull.`)],restart:!1};let m=Lw(e),w=[];if(_d(m))try{Nw(`${m}.bak`,Ow(m,"utf8"),"utf8"),w.push(g(" Your previous guide is at .d360-writer/style-guide.md.bak"))}catch{}let k=d.length>Dw?d.slice(0,Dw):d,S=`<!-- Pulled from Document360: "${a.name??a.id}" (${new Date().toISOString().slice(0,10)}). Edit freely \u2014 /style-guide pull overwrites this file. -->
|
|
419
|
+
|
|
420
|
+
`;OP(_P(m),{recursive:!0}),Nw(m,`${S}${k}
|
|
421
|
+
`,"utf8");let v=mo(e)??{projectId:""};return Od({...v,styleGuide:{...v.styleGuide,pulledFrom:{styleGuideId:a.id,name:a.name??a.id,pulledAt:new Date().toISOString(),contentHash:MP("sha1").update(k).digest("hex").slice(0,16)}}},e),{lines:[me("\u2713",`Pulled "${a.name??a.id}" into .d360-writer/style-guide.md (${k.length.toLocaleString()} characters).`),...w,g(" This is PROSE, not rules \u2014 /review judges against it, and the writer now writes to it."),g(" Turn its mechanical parts into checks: /style-guide compile"),g(" Restarting the agent so it writes to the new guide\u2026")],restart:!0}}function BP(e){let t=Id(e).rules.filter(n=>n.pack.toLowerCase()===Is.toLowerCase()).map(n=>n.id);return{prompt:SP({guide:PP(e),packName:Is,existingRuleIds:t}),display:"/style-guide compile"}}function HP(e){let t=EP(e),n=_d(t)?Ow(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."),g(" Reviewers comment on your drafts in Document360; /comments reads them, and every read"),g(" keeps a copy in .d360-writer/reviewer-notes.md. Run /comments first.")]}:{kind:"run",prompt:AP({notes:n,existingRules:TP(e),houseRulesFile:".d360-writer/house-rules.md"}),display:"/style-guide learn"}}function Mw(){return[g(" Read what it wrote: git diff .d360-writer/house-rules.md"),g(" These rules apply from now on \u2014 the writer follows them and /review judges against them."),g(" Disagree with one? Delete the line. It is your file, and nothing regenerates it."),g(" Restarting the agent so it writes to the new rules\u2026")]}function Fw(){return[g(` Review what it wrote: git diff .d360-writer/styles/${Is}/`),g(` Anything it could not check mechanically is listed in .d360-writer/styles/${Is}/UNCHECKABLE.md \u2014 /review judges those.`),g(` Turn them on when you are happy: /style-guide use ${Is.toLowerCase()} (they start as warnings, never blocking)`)]}var pt=(e,t)=>`${e} ${t}${e===1?"":"s"}`,Nd=e=>/^v\d/i.test(e)?e:`v${e}`;function Uw(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 GP(e){let n=mo(e)?.styleGuide?.pulledFrom;return n?`.d360-writer/style-guide.md \u2014 pulled ${n.pulledAt.slice(0,10)} from "${n.name}"`:_d(Lw(e))?".d360-writer/style-guide.md (yours)":"the built-in default"}function qP(e){let t=mo(e),n=Id(e),o=(t?.styleGuide?.packs??[]).filter(Boolean),r=n.packs.filter(l=>l.name.toLowerCase()===fo),s=n.packs.filter(l=>l.name.toLowerCase()!==fo),i=[`Style guide: ${GP(e)}`,`Rule packs: ${s.length>0?s.map(l=>`${l.name.toLowerCase()} ${Nd(l.version)}`).join(", "):g("none chosen")}`,`Always on: ${g(`d360 (correctness, built in \u2014 ${pt(Ia.length,"rule")})`)}`];for(let l of r)i.push(` ${g(`${l.name.toLowerCase()} ${Nd(l.version)} (anti-slop \u2014 ${pt(l.ruleCount,"rule")})`)}`);r.length>0&&(i.push(g(" Every article here is machine-written, so these cannot be switched off by")),i.push(g(" choosing another pack. styleGuide.humanise: false turns them off deliberately.")));let a=[...Ia.map(l=>({severity:l.severity})),...n.rules.map(l=>({severity:l.severity}))];i.push("",`${pt(a.length,"rule")} active \xB7 ${Uw(a)}`);try{let l=Ld({cwd:e}),d=l.findings.filter(w=>!w.baselined),m=d.filter(w=>w.severity==="error").length;i.push(""),i.push(m===0?me("\u2713",`No style errors across the docs${d.length>0?`, though ${pt(d.length,"other issue")} ${d.length===1?"is":"are"} reported`:""}.`):me("\u2717",`${pt(m,"style error")} \u2014 /lint --blocked shows them, /lint --blocked --fix corrects them.`)),l.baselinedCount>0&&i.push(me("\u2139",`${pt(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",`${pt(l.ruleErrors.length,"rule")} could not be loaded: ${l.ruleErrors.slice(0,2).map(w=>`${w.ruleId} (${w.reason})`).join("; ")}`))}catch{}return i.push(""),i.push(g(" See them all: /style-guide list \xB7 change: /style-guide use <preset> \xB7 one rule: /style-guide explain <rule>")),Md(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(g(" Worth settling now rather than later: it shapes every article written from here, and")),i.push(g(" changing it once a knowledge base exists means going back over what is already written."))),i}function jd(e){let t=mo(e),n=new Set(Iw(t?.styleGuide)),o=jw(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===fo,m=l?"\u2713":"\xB7",w=d?g("(always on)"):l?g("(active)"):"",k=i.local?g(" [yours]"):"";r.push(` ${m} ${a.padEnd(s)}${k} ${i.description??""}`),r.push(` ${g(`${pt(i.rules.length,"rule")} \xB7 ${Uw(i.rules)} \xB7 ${Nd(i.version)}`)} ${w}`),i.errors.length>0&&r.push(me("\u26A0",`${pt(i.errors.length,"rule")} in this pack could not be loaded \u2014 /style-guide explain names them.`))}return o.every(i=>i.name.toLowerCase()===fo)&&(r.push(""),r.push(g(" The Microsoft and Google style guides are not installed in this build yet."))),r.push(""),r.push(g(" Turn one on: /style-guide use <name> (this replaces the chosen set, it does not add to it)")),r.push(g(" Several: /style-guide use microsoft,google")),r.push(g(" Back to none: /style-guide use none")),r}function VP(e,t){if(!t)return[me("\u26A0","Name a rule: /style-guide explain Humanise.EmDash")];let n=Id(e),o=Ia.find(d=>d.id.toLowerCase()===t.toLowerCase()),r=n.rules.find(d=>d.id.toLowerCase()===t.toLowerCase());if(!o&&!r){let d=[...Ia.map(m=>m.id),...n.rules.map(m=>m.id)].filter(m=>m.toLowerCase().includes(t.toLowerCase())).slice(0,5);return[me("\u26A0",`No active rule called "${t}".`),...d.length>0?[g(` Did you mean: ${d.join(", ")}`)]:[g(" /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(g(` ${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=Ld({cwd:e}).findings.filter(w=>w.ruleId===s),m=d.filter(w=>!w.baselined);l.push(""),l.push(d.length===0?" Currently: no findings.":` Currently: ${pt(m.length,"finding")}${d.length!==m.length?`, plus ${d.length-m.length} baselined and hidden`:""}.`)}catch{}return l.push(""),o?(l.push(g(" Built-in checks are grounded in your product's own source and cannot be switched off \u2014 they")),l.push(g(" catch defects of fact, not matters of taste."))):(l.push(i==="error"?g(' This one BLOCKS publishing \u2014 your config sets it to "error" deliberately.'):g(" Style rules never block publishing. Fix it when you want to; it will not hold a page back.")),l.push(g(` Silence it everywhere: add "${s}": "off" to styleGuide.rules in .d360-writer/config.json`)),i!=="error"&&l.push(g(" Silence one passage: <!-- vale "+s+" = NO --> \u2026 <!-- vale "+s+" = YES -->"))),l}function YP(e,t){let n=(t??"").trim();if(!n)return{lines:[me("\u26A0","Name the packs to use: /style-guide use microsoft (or `none`)"),...jd(e)],restart:!1};let o=n.toLowerCase()==="none"?[]:n.split(/[,\s]+/).map(d=>d.trim().toLowerCase()).filter(Boolean),r=new Map(jw(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(", ")}.`),"",...jd(e)],restart:!1};let i=mo(e)??{projectId:""};Od({...i,styleGuide:{...i.styleGuide,packs:o,decidedAt:new Date().toISOString()}},e),vP();let a=[me("\u2192",`Switching to: ${o.length>0?o.join(", "):"the built-in checks only"}${o.includes(fo)?"":` (+ ${fo}, always on)`}\u2026`)];try{let d=Ld({cwd:e}),m=new Set(d.findings.map(w=>w.path)).size;if(d.findings.length===0)a.push(me("\u2713",m===0?"No articles yet \u2014 everything you write from here is held to the full set.":"Nothing to record: your articles are already clean against these rules."));else{let w=xP(e),k=$P(d.findings,CP(e));RP(e,k),a.push(me("\u2713",`Recorded ${pt(d.findings.length,"existing issue")} across ${pt(m,"article")} as accepted.`),g(" .d360-writer/style-baseline.json \u2014 commit it. It defines what the publish gate lets through, and a"),g(" 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 ${pt(m,"article")} do not follow ${o.join(", ")} \u2014 they are exempt, not compliant.`),g(" To bring them up to it: /review --all --fix, then /lint --all --fix. That is a pass over every"),g(" article and it costs accordingly \u2014 which is why this is worth settling before a knowledge base exists.")),w&&a.push(g(` (Replaced the baseline recorded ${w.createdAt.slice(0,10)}.)`))}}catch(d){a.push(me("\u26A0",`The packs are active, but recording what was already there failed: ${d instanceof Error?d.message:String(d)}`)),a.push(g(" Run /lint to see the current state before publishing."))}let l=_w(e);return l&&a.push(l),a.push(g(" Restarting the agent so it writes to the new rules\u2026")),{lines:a,restart:!0}}async function Oa(e,t){let{sub:n,value:o}=La(e),r=s=>{for(let i of s)console.log(i);console.log("")};switch(n){case"list":return r(jd(t.cwd)),{kind:"continue"};case"explain":return r(VP(t.cwd,o)),{kind:"continue"};case"use":{let s=YP(t.cwd,o);return r(s.lines),s.restart?{kind:"clear"}:{kind:"continue"}}case"keep":return r(UP(t.cwd)),{kind:"continue"};case"pull":{let s=await WP(t.cwd,o,t.profileName);return r(s.lines),s.restart?{kind:"clear"}:{kind:"continue"}}case"compile":{let s=BP(t.cwd);return{kind:"forward-to-agent",prompt:s.prompt,display:s.display}}case"learn":{let s=HP(t.cwd);return s.kind==="nothing"?(r(s.lines),{kind:"continue"}):{kind:"forward-to-agent",prompt:s.prompt,display:s.display}}default:return r(qP(t.cwd)),{kind:"continue"}}}se();import{lintDocs as Ma,loadStyleGuide as Qw,buildReviewPrompt as Jw,readProjectConfig as Zw,DEFAULT_DOCS_DIR as ey,listArticleFiles as wr,normalizeScope as lT,planPartitions as cT,runPartitioned as uT,partitionCoverage as dT,resolveModelForOperation as pT,stampArticles as hT,reviewStalePaths as fT,readReviewerNotes as ty,renderNotesForPrompt as ny,readDocsPlan as mT,CONTENT_CAP_VERSION as gT}from"document360-engine";import{listArticleFiles as KP,lintDocs as zP,planFindingPartitions as XP,planPartitions as QP,readDocsPlan as JP,readProjectConfig as ZP,runRate as Ww,DEFAULT_DOCS_DIR as eT}from"document360-engine";function Bw(e){switch(e.cmd){case"/review":return{concurrency:In,maxPerPartition:Ud,minutesPerBatch:5};case"/write":return{concurrency:3,minutesPerBatch:4};case"/lint":return{concurrency:3,minutesPerBatch:2};default:return{concurrency:3,minutesPerBatch:2}}}function tT(e,t){let n=zP({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:XP(o).length}}function nT(e,t){try{if(t.cmd==="/write"){let n=(ZP(e)?.docsDir??eT).replace(/\/+$/,""),o=JP(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:Rn(e,n,r)}return t.cmd==="/review"?go(e,[...t.flags],t.scope):KP(e,t.scope)}catch{return null}}function Hw(e,t){let n=jn(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 jn(e,t){let n=Vi(t);if(!n||!Sc(n))return null;let o=Bw(n),r=n.cmd==="/lint"?Fd(()=>tT(e,n)):null,s=r?null:nT(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:QP(s,o.maxPerPartition?{maxPerPartition:o.maxPerPartition}:void 0).length,l=Math.ceil(a/o.concurrency),d=Fd(()=>Ww(e,n.cmd)),m=l*(d?.minutesPerWave??o.minutesPerBatch),w=r?r.lead:`${i} articles`,k=d?.usdPerArticle!==void 0?` \xB7 ~${Yw(i*d.usdPerArticle)}`:"";return`${w} \xB7 ${a} batch${a===1?"":"es"} \xB7 ~${Vw(m)}${k}`}var Gw=.7,qw=1.4;function Vw(e){let t=Math.max(1,Math.round(e*Gw)),n=Math.max(t,Math.round(e*qw));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 Yw(e){let t=e*Gw,n=e*qw;return n>=10?`$${Math.round(t)}\u2013${Math.round(n)}`:`$${t.toFixed(2)}\u2013${n.toFixed(2)}`}function Fd(e){try{return e()}catch{return null}}function _a(e,t,n,o){if(n<4||o<1)return null;let r=Bw({cmd:t,scope:void 0,flags:new Set,args:[]}),s=Math.ceil(o/r.concurrency),i=Fd(()=>Ww(e,t)),a=s*(i?.minutesPerWave??r.minutesPerBatch),l=i?.usdPerArticle!==void 0?` \xB7 ~${Yw(n*i.usdPerArticle)}`:"";return`~${Vw(a)}${l}`}import{renderGapsForPrompt as oy}from"document360-engine";import{recordRunSample as wT}from"document360-engine";se();import{readProjectConfig as oT,loadProfileMap as rT,resolveActiveProfile as sT,desiredCategoryOrder as iT,desiredArticleOrder as aT}from"document360-engine";function Kw(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}var zw=e=>e.replace(/\\/g,"/").split("/").pop()??e;function Ls(e,t){try{if(!oT(e))return[];let n=sT(e,t),o=rT(e,n.name);if(!o)return[];let r=new Map;for(let i of aT(o)){let a=r.get(i.categoryPath);a?a.push(i):r.set(i.categoryPath,[i])}let s=[];for(let i of iT(o)){s.push(Kw(zw(i.path)));for(let a of(r.get(i.path)??[]).sort((l,d)=>l.order-d.order))s.push(` ${Kw(zw(a.path))}`)}return s}catch{return[]}}async function Xw(e,t){let n=Ls(t.cwd,t.profileName);if(n.length===0)return console.log(g("No documentation structure yet \u2014 run /init and author some articles first.")),{kind:"continue"};console.log(J("Documentation order (categories \u2192 articles):"));for(let o of n)console.log(o);return console.log(""),{kind:"continue"}}function Wd(e,t){return ds(e,wr(e,t))}function Bd(e,t){return fT(e,wr(e,t),gT)}function Os(e){return e.includes("--blocked")||e.includes("--stale")}function go(e,t,n){return t.includes("--blocked")?Wd(e,n):t.includes("--stale")?Bd(e,n):wr(e,n)}function ry(e,t,n){let o;try{o=mT(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 sy(e,t){let n=Zw(e);if(!n)return null;let o=(n.docsDir??ey).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),s=Os(t),i=t.find(C=>!C.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),a=Ma({cwd:e}),l=i?lT(o,i):"",d=l?a.filter(C=>C.path===`${o}/${l}`||C.path.startsWith(`${o}/${l}/`)):a,m=s?go(e,t,i):void 0,w=m?d.filter(C=>m.includes(C.path)):d,k=i||s?"":Ls(e).join(`
|
|
422
|
+
`),S=Jw({docsRoot:o,scope:i,styleGuide:Qw(e),deterministicFindings:w,fix:r,structure:k||void 0,...m?{paths:m}:{},reviewerNotes:ny(ty(e),m??wr(e,i)),openGaps:oy(e,m??wr(e,i)),planRows:ry(e,o,m??wr(e,i))}),v=t.includes("--blocked")?" --blocked":t.includes("--stale")?" --stale":"";return{prompt:S,display:`/review${i?` ${i}`:""}${v}${r?" --fix":""}`}}var yT=e=>"ruleId"in e,In=3,Ud=3;function Hd(e,t){let n=sy(e,t);if(!n)return null;let o=t.find(k=>!k.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),r=go(e,t,o),s=cT(r,{maxPerPartition:Ud});if(s.length<=1)return{kind:"single",...n};let a=(Zw(e)?.docsDir??ey).replace(/\\/g,"/").replace(/\/+$/,""),l=t.includes("--fix"),d=Qw(e),m=Ma({cwd:e}),w=ty(e);return{kind:"partitioned",partitions:s,articles:r.length,wholeKb:!o&&!Os(t),display:n.display,promptFor:k=>{let S=new Set(k.paths);return Jw({docsRoot:a,styleGuide:d,deterministicFindings:m.filter(v=>S.has(v.path)),fix:l,paths:k.paths,reviewerNotes:ny(w,k.paths),openGaps:oy(e,k.paths),planRows:ry(e,a,k.paths)})}}}function Gd(e,t){if(!Os(t))return null;let n=t.find(w=>!w.startsWith("--"));if(go(e,t,n).length>0)return null;let o=t.includes("--blocked"),r=!!n&&n.endsWith(".md"),s=n?r?" here":` in ${n}`:"",a=o?`\u2713 Nothing is blocked${s} \u2014 ${n&&r?"it has":"every article has"} been through an editorial read.`:`\u2713 ${r?"This article has":`Every article${s} has`} already been read by the current editor \u2014 nothing to re-read.`,l=`/push${n?` ${n}`:" --all"}`,d=Bt(e,{text:`${l} saves ${r?"it":"what has changed"} to Document360 as ${r?"a draft":"drafts"}.`,cmd:l},"",n,"/review"),m=vt(e,sy(e,t)?.display??"");return{lines:[a,` ${d.text}`],closed:m,cta:d}}async function iy(e,t){let n=Gd(t.cwd,e);if(n){console.log(q(n.lines[0]));for(let r of n.lines.slice(1))console.log(g(r));for(let r of n.closed)console.log(q(r));return{kind:"continue",ownNext:!0}}if(En("review",e)){let r=ur(t.cwd,"review",e,t.profileName);if(r.length>0){for(let s of r)console.log(g(s));return{kind:"continue"}}}let o=Hd(t.cwd,e);return o?o.kind==="single"?{kind:"forward-to-agent",prompt:o.prompt,display:o.display}:await bT(t,o,e.includes("--fix"),e.find(r=>!r.startsWith("--"))):(console.log(O("No d360-writer config here. Run /init first.")),{kind:"continue"})}async function bT(e,t,n,o){let{model:r}=pT(e.cwd,"standard"),s=_a(e.cwd,"/review",t.articles,t.partitions.length);console.log(g(`Reviewing ${t.articles} article${t.articles===1?"":"s"} in ${t.partitions.length} batches (\u2264${In} editors at once) on ${r}${n?", applying fixes":", report only"}${s?` \xB7 ${s}`:""}\u2026`));let i=Date.now(),a=new sr;a.start();let l={aborted:!1,partitions:0,failed:0,notRun:0,producedNothing:!0};try{for await(let k of uT({cwd:e.cwd,partitions:t.partitions,promptFor:t.promptFor,concurrency:In,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:r,scope:"review"}))if(k.type==="partition_status")k.status==="running"?console.log(g(` \u25B8 ${k.label} \u2014 reviewing\u2026`)):k.status==="done"?console.log(q(` \u2713 ${k.label}`)):console.log(O(` \u2717 ${k.label}`));else if(k.type==="run_done"){let S=dT(t.partitions,k.results);l={aborted:!!k.aborted,partitions:t.partitions.length,failed:S.failed.length,notRun:S.notRun.length,...k.blocked?{blocked:k.blocked}:{},...k.allEmpty?{allEmpty:!0}:{},...k.bailedEmpty?{bailedEmpty:!0}:{}},console.log(""),console.log(`${k.results.length-S.failed.length}/${t.partitions.length} batches reviewed.`),S.failed.length&&console.log(G(`\u26A0 ${S.failed.length} not reviewed: ${S.failed.map(C=>C.label).join(", ")}`)),S.notRun.length&&console.log(G(`\u26A0 ${S.notRun.length} batch${S.notRun.length===1?"":"es"} never started \u2014 their articles are untouched.`)),k.blocked&&console.log(G(`\u26A0 ${k.blocked}`)),k.allEmpty&&console.log(G("\u26A0 No editor produced any work this run \u2014 nothing was reviewed or changed."));for(let C of qd(t))console.log(g(C));if(n&&!k.allEmpty&&!k.blocked)try{hT(e.cwd,S.covered,st("review"))}catch{}let v=a.stop();if(console.log(g(Kt(Ct(i,k.results,k.totalCostUsd,Date.now(),v.activeSeconds)))),!k.allEmpty&&!k.blocked){let C=k.results.filter(A=>A.ok).length;wT(e.cwd,"review",{articles:S.covered.length,waves:Math.ceil(C/Math.max(1,In)),seconds:v.activeSeconds,costUsd:k.totalCostUsd})}}}catch(k){return a.stop(),console.log(O(`Review failed: ${k.message}`)),{kind:"continue"}}if(a.stop(),n&&Yt(l))for(let k of vt(e.cwd,t.display))console.log(q(k));if(!n)return{kind:"continue"};let d=cr(e.cwd,["--fix"],Ma({cwd:e.cwd,scope:o}));for(let k of d.lines)console.log(k);let w=Ma({cwd:e.cwd,scope:o}).filter(k=>!k.baselined).filter(k=>yT(k)&&k.severity==="error");if(console.log(""),w.length>0){let k=Re("/lint","--blocked --fix",o);console.log(g(`Editor applied its fixes, but ${w.length} style error${w.length===1?"":"s"} remain \u2014 ${k} clears them (finding them costs nothing, one pass corrects them). It is the last paid pass before publishing: anything still standing after a second attempt is reported for a person rather than run again.`))}else console.log(g(Bt(e.cwd,{text:"\u2713 Reviewed and fixed. /push --all saves the articles to Document360 as drafts.",cmd:"/push --all"},"",o).text));return{kind:"continue",ownNext:!0}}function qd(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 kT}from"document360-engine";function Vd(e,t){if(!kT(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 ay(e,t){if(En("reorder",e)){let o=ur(t.cwd,"reorder",e,t.profileName);if(o.length>0){for(let r of o)console.log(g(r));return{kind:"continue"}}}let n=Vd(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(O("No d360-writer config here. Run /init first.")),{kind:"continue"})}se();import{computeReadiness as $T,readinessPlaceholderPlaces as vT}from"document360-engine";import He from"picocolors";var Yd=5;function ht(e,t=58){let n=e.replace(/\\/g,"/");return n.length<=t?n:`\u2026${n.slice(n.length-t+1)}`}function xT(e){let t=[],n=e.verdict;if(e.conflicts.length>0&&t.push({glyph:"\u2717",paint:He.red,title:`Changed here and on Document360 (${e.conflicts.length})`,fix:"/resolve",items:e.conflicts.map(o=>ht(o))}),n.unreviewed.length>0&&t.push({glyph:"\u2717",paint:He.red,title:`Never read by an editor (${n.unreviewed.length})`,fix:"/review --blocked --fix",items:n.unreviewed.map(o=>ht(o))}),n.styleErrors.length>0){let o=n.styleErrors.reduce((r,s)=>r+s.errors,0);t.push({glyph:"\u2717",paint:He.red,title:`Break house style rules your config makes blocking (${o} error${o===1?"":"s"})`,fix:"/lint --blocked --fix",items:n.styleErrors.map(r=>`${ht(r.path)} (${r.errors})`)})}if(n.placeholders.length>0){let o=vT(e);t.push({glyph:"\u2717",paint:He.red,title:`Would show "[Screenshot: \u2026]" to your readers (${n.placeholders.length} article${n.placeholders.length===1?"":"s"}, ${o} place${o===1?"":"s"})`,fix:"/screenshot",items:n.placeholders.map(r=>`${ht(r.path)} (${r.missingShots.length+r.orphans})`)})}return t}function RT(e){let t=e.verdict,n=[];return e.conflicts.length===0&&n.push(`${ee("\u2713",He.green)}Nothing is in conflict with Document360`),t.unreviewed.length===0&&n.push(`${ee("\u2713",He.green)}Every article has been read by an editor`),t.styleErrors.length===0&&n.push(`${ee("\u2713",He.green)}House style: nothing blocking`),t.placeholders.length===0&&n.push(`${ee("\u2713",He.green)}No placeholder text would reach a reader`),n}function CT(e,t){if(e.rows.length===0)return[];let n=r=>r?He.green("\u2713"):He.red("\u2717"),o=e.rows.map((r,s)=>[String(s+1),ht(r.path,46),n(r.reviewed),r.styleErrors===0?He.green("\u2713"):He.red(`\u2717 ${r.styleErrors}`),r.placeholders===0?He.green("\u2713"):He.red(`\u2717 ${r.placeholders}`),r.conflict?He.red("conflict"):r.draftPending?He.yellow("draft"):r.localAhead?g("not saved"):g("\u2014")]);return hs(["#","Article","Read","Style","Pictures","Document360"],o,t).split(`
|
|
424
|
+
`)}function Kd(e,t={}){let n=$T(e,t.profileName),o=[];if(n.rows.length===0)return o.push(J("Publish readiness")),o.push(""),o.push(n.tracked===0?`${ee("\u25CB",He.gray)}No articles are tracked yet. /write authors them, /push saves them to Document360.`:`${ee("\u2713",He.green)}All ${n.tracked} articles are live and unchanged \u2014 nothing is waiting on you.`),n.orphans.length>0&&o.push(...ly(n)),o.push(""),o.push(g(" 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(J("Publish readiness")+g(` ${r} article${r===1?"":"s"} not yet settled with readers \xB7 ${s===0?"nothing blocked":`${s} blocked`}`)),o.push(""),t.all&&(o.push(...CT(n,t.width??100)),o.push(""));for(let l of xT(n)){o.push(` ${ee(l.glyph,l.paint)}${l.title}${l.fix?g(` ${l.fix}`):""}`);for(let d of l.items.slice(0,Yd))o.push(g(` ${d}`));l.items.length>Yd&&o.push(g(` \u2026and ${l.items.length-Yd} more`)),o.push("")}let i=RT(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(g(` ${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(g(` ${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(...ly(n)),!t.all&&n.rows.length>0&&o.push(g(" /status --all shows every article, gate by gate.")),o.push(""),o.push(g(" Free \u2014 /status reads your local files and the last sync. It calls nothing.")),o}function ly(e){let t=e.orphans.length;return[g(` ${t} article${t===1?"":"s"} on Document360 ${t===1?"is":"are"} not in your docs folder (${ht(e.orphans[0].path,40)}${t>1?`, +${t-1} more`:""}) \u2014 /doctor lists ${t===1?"it":"them"}.`)]}async function cy(e,t){let n=e.some(o=>o==="--all"||o==="--full");for(let o of Kd(t.cwd,{profileName:t.profileName,all:n}))console.log(o);return{kind:"continue",ownNext:!0}}se();import{computeReadiness as ST,retireArticle as PT,retiredPaths as TT,normalizeScope as AT}from"document360-engine";import{select as ET}from"@inquirer/prompts";function zd(e,t){let n=ST(e,t),o=TT(e,t),r=[J("Take an article off your readers"),""];if(n.orphans.length>0){r.push(` ${ee("\u25CB",g)}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(g(` ${ht(s.path)}`));n.orphans.length>8&&r.push(g(` \u2026and ${n.orphans.length-8} more`)),r.push("")}if(o.length>0){r.push(` ${ee("\u2713",g)}Already retired \u2014 readers do not see ${o.length===1?"it":"these"}:`);for(let s of o.slice(0,5))r.push(g(` ${ht(s)}`));o.length>5&&r.push(g(` \u2026and ${o.length-5} more`)),r.push("")}return n.orphans.length===0&&o.length===0&&(r.push(g(" Nothing obvious to retire \u2014 every tracked article is still in your docs folder.")),r.push("")),r.push(g(" /retire <path> takes one off your readers. Any tracked article can be named, not just these.")),r.push(g(" Nothing is deleted: the article, its history and every reviewer comment stay on Document360.")),r.push(g(" /push puts one back \u2014 reviving is a publish like any other, with the same review.")),r}async function uy(e,t){let n=t.cwd,o=e.find(a=>!a.startsWith("-"));if(!o){for(let a of zd(n,t.profileName))console.log(a);return{kind:"continue",ownNext:!0}}let r=AT(n,o)||o;if(!(e.includes("--yes")||e.includes("-y"))&&(console.log(""),console.log(G(`This takes "${ht(r)}" off your readers on Document360.`)),console.log(g(" The article, its history and every reviewer comment stay \u2014 nothing is deleted.")),console.log(g(" /push puts it back later if you change your mind.")),console.log(""),await ET({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(g("Nothing changed.")),{kind:"continue",ownNext:!0};let i=await PT({cwd:n,path:r,profileName:t.profileName,now:new Date().toISOString()});return i.ok?(console.log(i.alreadyHidden?`${ee("\u2713")}"${ht(r)}" was already invisible to readers. Recorded as retired, so nothing will offer to publish it again.`:`${ee("\u2713")}"${ht(r)}" is no longer visible to your readers.`),console.log(g(" It is still on Document360 with its history and comments intact. /push puts it back.")),{kind:"continue",ownNext:!0}):(console.log(O(`${ee("\u2717")}Could not retire "${ht(r)}" \u2014 ${i.error.message}`)),{kind:"continue",ownNext:!0})}se();import{readProjectConfig as DT,writeProjectConfig as dy,isAppType as NT,playbookSkillName as jT,detectAppType as py}from"document360-engine";var hy=["web","cli","service","library"],IT=new Set(["web","cli"]);function Xd(e){return IT.has(e)?`${jT(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function Fa(e,t){let n=t.cwd,o=DT(n);if(!o)return console.log(O("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let s=o.appType??py(n);if(s){let i=o.appType?"set in config":"auto-detected";console.log(`${J("Genre:")} ${s} (${i}) \u2014 ${Xd(s)}`)}else console.log(G("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(g(`Set it: /genre <${hy.join("|")}> \xB7 revert to auto-detect: /genre auto`)),{kind:"continue"}}if(r==="auto"||r==="clear"){if(!o.appType)return console.log(g("Already on auto-detect (no genre set in config).")),{kind:"continue"};let{appType:s,...i}=o;dy(i,n);let a=py(n);return console.log(q(`\u2713 Genre reset to auto-detect \u2014 now: ${a?`${a} (${Xd(a)})`:"unclassified (no playbook)"}.`)),console.log(g(" Restarting the agent so the loaded playbook matches\u2026")),{kind:"clear"}}return NT(r)?(dy({...o,appType:r},n),console.log(q(`\u2713 Genre set to ${r} \u2014 ${Xd(r)}.`)),console.log(g(" Restarting the agent so the playbook loads\u2026")),{kind:"clear"}):(console.log(O(`Unknown genre "${r}". Choose one of: ${hy.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}var fy={help:Yl,"?":Yl,clear:Bh,exit:Kl,quit:Kl,init:tc,mcp:Ai,push:ea,publish:Cm,audit:(e,t)=>ps({cwd:t.cwd,profileName:t.profileName}),discover:Sm,scope:Tm,pull:Bm,resolve:Fm,convert:sg,write:kg,draft:Cg,document:Sg,resume:Ag,rename:Eg,profile:Ng,model:Lg,doctor:xs,logs:Oh,workspace:Ug,project:Wg,"allow-prod":Bg,login:Hg,logout:Gg,screenshot:async(e,t)=>{let n=ss(e);return n.mode==="capture"?td(n.rest,t):n.mode==="annotate"?id(n.rest,t):n.mode==="verify"?qg(n.rest,t):n.mode==="checklist"?fr(e,t):qi(e,t)},capture:td,annotate:id,"capture-setup":fr,devhints:Jh,inbox:uw,ask:pw,"catch-up":ww,comments:xw,update:Cw,reset:Ew,lint:$u,check:dg,"style-guide":Oa,review:iy,reorder:ay,structure:Xw,status:cy,retire:uy,genre:Fa,roadmap:pm,share:mw};function my(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 LT}from"node:child_process";import{recordAnalyzedCommit as OT,resolveActiveProfile as _T}from"document360-engine";function MT(e){try{let t=LT("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 _s(e,t){try{let n=MT(e);if(!n)return null;let o=_T(e,t);return OT(e,o.name,n)?n:null}catch{return null}}kn();var gy="Or just tell me what to write or update.";function FT(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${we(t)} ${e===1?"is":"are"} still open (/roadmap shows them).`}var UT="Screenshots are the only thing still open \u2014 a separate job, and none of it changes your text:",WT="Optional depth, when you want it:",BT="Writing",HT="Screenshots \u2014 a separate job from the writing";function GT(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 qT='\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 we(e){return e===1?"":"s"}function VT(e,t){if(!e||!t)return!1;let n=o=>o.trim().replace(/\s+/g," ").toLowerCase();return n(e)===n(t)}function yr(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 yy(e,t){return e.length===t.length&&e.every((n,o)=>n===t[o])}function wy(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 br(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 Wa={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 YT(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:Wa,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${we(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${we(r)} already written \u2014 changing this later means rewriting them)`:"Which writing rules should these docs follow? (this shapes every article I write)",lead:r>0?"Settle the writing rules below \u2014 one keypress. Keeping what you have is the usual answer once articles exist.":"Settle the writing rules below \u2014 one keypress, before I write anything to them.",exclusive:!0,options:e.styleRules.presets},follow:"Then settle the writing rules below \u2014 it shapes every article, and it gets dearer to change the longer it waits."})}if(e.discovery&&e.discovery.status!=="confident"){let r=e.discovery.openQuestions;e.discovery.status==="pending"?n.push({key:"discovery",bullet:"your existing docs aren\u2019t grounded in a product brief yet",lead:{kind:"cmd",cmd:"/discover",reason:"it interviews your builder and grounds the docs before you rewrite or publish them"},picker:null,follow:"Then /discover grounds your docs in a product brief (do this before the rewrite/push steps)."}):r>0?n.push({key:"discovery",bullet:`product discovery is waiting on ${r} answer${we(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${we(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${we(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${we(r)} waiting on your articles.`})}if(e.conflicts>0){let r=e.conflicts;n.push({key:"resolve",bullet:`${r} article${we(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${we(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${we(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${we(r)}.`,blockedBy:["resolve"]})}if(e.hasDocs&&e.pendingWrites>0){let r=e.pendingWrites;n.push({key:"write",bullet:`${r} planned article${we(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${we(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${we(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${we(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${we(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${we(r)} \u2014 nothing reaches your readers until it has.`,dependsOn:["catchup","comments","review"]})}let o=e.shotsToAnnotate>0?{key:"annotate",bullet:`${e.shotsToAnnotate} screenshot${we(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${we(e.shotsToAnnotate)} already taken.`}:e.shotsToRecapture>0?{key:"annotate",bullet:`${e.shotsToRecapture} screenshot${we(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${we(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${we(r)} changed locally \u2014 ready to send to Document360`,lead:{kind:"cmd",cmd:"/push",reason:`it saves your ${r} local edit${we(r)} to Document360 as drafts`},picker:null,follow:`Then /push saves your ${r} local edit${we(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${we(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${we(r)} live to your readers \u2014 it lists them and asks first`},picker:null,follow:`Then /publish takes the ${r} draft${we(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:wy(s.body),l=s.run?i??void 0:wy(s.body,340,2)??void 0,d=`docs campaign: ${r.done} of ${r.total} step${we(r.total)} done`,m=!!s.run&&VT(s.run,e.lastCommand);n.push(m?{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${we(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${we(r)} under .d360-writer/ \u2014 tell your coding agent: "commit d360-writer's work"`,lead:null,picker:null,follow:null})}return n}function by(e){return e.find(t=>t.lead||t.picker)??null}function
|
|
432
|
-
`):L=[e,"",` ${
|
|
433
|
-
`),{note:[...o?[o]:[],L,
|
|
434
|
-
|
|
435
|
-
`),menu:A.map(M=>M.run??M.title)}}let i=by(t),a=i?.picker?[]:t.filter(
|
|
436
|
-
\u2022 `),L
|
|
437
|
-
`)}let B
|
|
438
|
-
\u2022 `)}${B&&!
|
|
439
|
-
`)]:[[e,...
|
|
440
|
-
`)];if(
|
|
441
|
-
|
|
442
|
-
`),menu:l.map(
|
|
443
|
-
|
|
444
|
-
${
|
|
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
|
-
`).length;return{verb:"Draft",title:C,category:l,note:`new, ${A} lines`}}return{verb:"Rewrite",title:C,category:l,note:
|
|
447
|
-
`)),category:l,note:
|
|
448
|
-
`);if(e==="Read"){let o=n.length,r=
|
|
449
|
-
`));return[`${o} line${o===1?"":"s"}${r?` \xB7 ${r}`:""}`]}if(e==="Glob"){if(/^no files found/i.test(t))return null;let o=n.filter(r=>r.trim()).length;return[`${o} file${o===1?"":"s"}`]}return e==="Grep"&&/^Found \d+/.test(n[0]??"")?[n[0]]:null}function
|
|
450
|
-
`).trimEnd();if(n&&Ny.has(n))return{lines:[],hidden:0};if(!r)return{lines:["(no output)"],hidden:0};if(n&&!n.startsWith("mcp__")){let i=
|
|
451
|
-
`);return{lines:s.slice(0,t).map(i=>Ln(i,np)),hidden:Math.max(0,s.length-t)}}function
|
|
452
|
-
|
|
453
|
-
${Z}`)}catch{}if(await sp(i,fe,r,a,e,n),X)try{
|
|
454
|
-
`))console.log(i(` ${a}`));s.rec.picker&&console.log(J(` Pick one: ${s.rec.picker.options.map(a=>a.cmd).join(" \xB7 ")}`))}}catch{}}console.log(
|
|
455
|
-
`))console.log(q(` ${r}`))}else o.rec.settled&&!o.rec.lead&&console.log(
|
|
456
|
-
|
|
457
|
-
`);let l=[i.category,i.note].filter(
|
|
458
|
-
|
|
459
|
-
`),console.log(`${be("\u25CF")} ${a.title}${a.arg!==null?be(`${a.sep}(${a.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let i=Rt(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!i)break;let a=l=>l===1?"":"s";console.log(be(` \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(
|
|
460
|
-
`);let i=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(
|
|
461
|
-
`),n=0;for(let s=t.length-1;s>=0;s--){let i=t[s];if(/^\s{0,3}\d{1,2}[.)]\s+\S/.test(i)){n++;continue}if(!(n>0&&/^\s+\S/.test(i)))break}return n<2?0:t.filter(s=>/^\s{0,3}\d{1,2}[.)]\s+\S/.test(s)).slice(-n).every((s,i)=>Number(/^\s{0,3}(\d{1,2})/.exec(s)[1])===i+1)?n:0}var
|
|
462
|
-
`),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){
|
|
463
|
-
`)}var
|
|
464
|
-
`).filter(s=>/^\s{0,3}\d{1,2}[.)]\s+\S/.test(s)).slice(-n).map(s=>{let i=s.replace(/^\s{0,3}\d{1,2}[.)]\s+/,"").trim(),a=
|
|
465
|
-
`).map(o=>o.trim()).filter(o=>o.length>3),n=t[t.length-1];return n?n.length>160?`${n.slice(0,157)}\u2026`:n:null}function
|
|
466
|
-
\u2190/\u2192 or tab switch \xB7 1-5 jump${
|
|
467
|
-
`)){let i=s.trim().replace(
|
|
468
|
-
`)}function
|
|
469
|
-
`)||e.length>200}function
|
|
470
|
-
`).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function
|
|
471
|
-
`)){if(s.length===0)o.push({start:r,end:r});else for(let i=0;i<s.length;i+=n)o.push({start:r+i,end:r+Math.min(i+n,s.length)});r+=s.length+1}return o.length>0?o:[{start:0,end:0}]}function
|
|
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${we(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${we(r)} under .d360-writer/ \u2014 tell your coding agent: "commit d360-writer's work"`,lead:null,picker:null,follow:null})}return n}function by(e){return e.find(t=>t.lead||t.picker)??null}function KT(e){return e.kind==="cmd"?e.cmd:e.kind==="prompt"?`\u201C${e.text}\u201D`:""}function Ms(e){return e.kind==="cmd"?e.cmd:e.kind==="prompt"?e.text:null}function zT(e){return Ms(e)??""}function XT(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 Ua(e,t,n,o=null,r,s=0){if(r&&r.length>0){let v=r.filter(Yi),C=r.filter(M=>!Yi(M)),A=[...C,...v],D=(M,X)=>` ${X+1}. ${M.title}${M.run?` \xB7 ${M.run}`:""}`,L;return v.length===0||C.length===0?L=[e,...A.map(D)].join(`
|
|
432
|
+
`):L=[e,"",` ${BT}`,...C.map((M,X)=>D(M,X)),"",` ${HT}`,...v.map((M,X)=>D(M,C.length+X))].join(`
|
|
433
|
+
`),{note:[...o?[o]:[],L,GT(A.length,n),gy].join(`
|
|
434
|
+
|
|
435
|
+
`),menu:A.map(M=>M.run??M.title)}}let i=by(t),a=i?.picker?[]:t.filter(v=>v.lead),l=a.length>=2?a:[],d=new Map(l.map((v,C)=>[v.key,C+1])),m=[];i?.lead?m.push(br(i.lead)):i?.picker&&m.push(i.picker.lead);for(let v of t.filter(C=>C!==i&&!C.lead).slice(0,2))v.follow&&m.push(v.follow);l.length>=2&&n&&m.push(`Press 1\u2013${l.length} to pick a different one \u2014 the number fills the box, enter runs it.`);let w=m.join(" "),k=t.filter(v=>v.bullet).map(v=>{let C=d.get(v.key),[A="",...D]=(C&&v.lead?.kind==="prompt"&&v.rowBullet?v.rowBullet:v.bullet).split(`
|
|
436
|
+
\u2022 `),L=v===i&&v.lead?.kind!=="answer"&&v.lead?.detail?[]:D;if(C&&v.lead){let X=A.replace(/^→\s+/,"");return[` ${C}. ${KT(v.lead)} \u2014 ${X}${XT(v,d,C)}`,...L.map(de=>` ${de}`)].join(`
|
|
437
|
+
`)}let B=v.lead?.kind==="cmd"?v.lead.cmd:null;return` \u2022 ${[A,...L].join(`
|
|
438
|
+
\u2022 `)}${B&&!w.includes(B)?` \u2014 ${B}`:""}`}),S=o?[o,[e,...k].join(`
|
|
439
|
+
`)]:[[e,...k].join(`
|
|
440
|
+
`)];if(m.length&&S.push(m.join(" ")),s>0){let v=s;S.push(`${v} question${we(v)} you asked your developers ${v===1?"is":"are"} still unanswered. Their reply arrives with your docs the next time either of you shares, and /inbox folds it in. Nothing is blocked meanwhile.`)}return S.push(gy),{note:S.join(`
|
|
441
|
+
|
|
442
|
+
`),menu:l.map(v=>zT(v.lead))}}function Fs(e,t){let n=t?.pickable===!0,o=S=>t?.header?`${t.header}
|
|
443
|
+
|
|
444
|
+
${S}`:S;if(!e.ready)return{kind:"idle"};if(e.pendingAnswer)return{kind:"recommend",rec:{note:null,settled:null,tone:"info",lead:e.pendingAnswer.options>=2?{kind:"answer",options:e.pendingAnswer.options,reason:"the agent is waiting on your pick"}:null,picker:null,menu:[]}};let r=YT(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(Yi)&&e.roadmap.total-e.roadmap.done===i.length,l=s?FT(e.roadmap.total-e.roadmap.done,e.roadmap.total,{listed:i.length>0,onlyScreenshots:a}):null;if(!e.hasDocs){let S=by(r);if(S&&(S.lead?.kind==="cmd"||S.picker)){let v=Ua(t?.header??"\u{1F4ED} No docs yet for this repo \u2014 here\u2019s where things stand:",r,n,null,void 0,e.outboundQuestions);return{kind:"recommend",rec:{note:v.note,settled:null,tone:S.tone??"info",lead:S.lead,picker:S.picker,menu:v.menu}}}return{kind:"recommend",rec:{note:o(qT),settled:null,tone:"info",lead:{kind:"prompt",text:"write the docs for this repo",reason:"I\u2019ll read the code and draft a structure"},picker:null,menu:[]}}}if(r.length===0){let S=e.roadmap&&!e.roadmap.next?` Docs campaign complete \u2014 all ${e.roadmap.total} step${we(e.roadmap.total)} done (/roadmap).`:"";return{kind:"recommend",rec:{note:o(`Welcome back. Your ${e.tracked} tracked article${we(e.tracked)} for \u201C${e.profileName}\u201D are all in sync \u2014 /audit re-checks the code, /pull brings down portal edits.${S}`),settled:null,tone:"info",lead:null,picker:null,menu:[]}}}let d=r.filter(S=>S.lead||S.picker),m=d[0]??null;if(!m){let S=Ua(t?.header??"Welcome back \u2014 where your docs stand:",r,n,null,void 0,e.outboundQuestions);return{kind:"recommend",rec:{note:S.note,settled:null,tone:"info",lead:null,picker:null,menu:S.menu}}}if((m.key==="audit"||d[1]?.key==="audit")&&e.behind>0&&e.autoAudit&&e.allowAutoAudit)return{kind:"autoAudit",note:o(`\u{1F4CB} ${e.behind} code change${we(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`)};if(l){let S=Ua(a?UT:WT,r,n,l,i,e.outboundQuestions);return{kind:"recommend",rec:{note:S.note,settled:l,tone:"info",lead:null,picker:null,menu:S.menu}}}let k=Ua(t?.header??"Welcome back \u2014 where your docs stand:",r,n,l,void 0,e.outboundQuestions);return{kind:"recommend",rec:{note:k.note,settled:l,tone:m.tone??"info",lead:m.lead,picker:m.picker,menu:k.menu}}}import{existsSync as Ba,readdirSync as Zd}from"node:fs";import{spawnSync as QT}from"node:child_process";import{join as Ha}from"node:path";import{readProjectConfig as Jd,resolveActiveProfile as vy,loadTokens as JT,isExpired as ZT,loadProfileMap as xy,localAheadPaths as eA,loadKnownConflicts as tA,draftPendingPaths as nA,loadOpenCommentCount as oA,readDocsPlan as rA,devHintsGuidePath as sA,DEFAULT_DOCS_DIR as Ga,roadmapProgress as iA,listRoadmap as ky,readProductBriefState as aA,readDiscoveryQueue as lA,reconcileCommitRequest as cA,reconcileTestidRequest as uA,snapshotHandoff as dA,shareExplainedPath as pA,unannotatedShotIds as hA,shotsNeedingRecapture as fA,resolveOutputDir as mA,DEFAULT_OUTPUT_DIR as gA,WRITER_DIRNAME as Qd,styleGuideSettled as wA,listAvailablePacks as yA,listArticleFiles as bA}from"document360-engine";kn();var kA=5;function $y(e){try{return Zd(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function ep(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>$y(Ha(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&$y(Ha(e,o)))}function tp(e,t){try{let n=Jd(e);if(!n)return!1;let o=vy(e,t),r=xy(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=Ha(e,(n.docsDir??Ga).replace(/\/+$/,""));return!!(Ba(s)&&Zd(s).length>0||Ba(sA(e)))}catch{return!1}}function $A(e){let t=[`:(exclude)${Qd}`],n=(e.docsDir??Ga).replace(/\\/g,"/").replace(/\/+$/,"");return n&&!n.startsWith(`${Qd}/`)&&n!==Qd&&t.push(`:(exclude)${n}`),t}function vA(e,t,n){try{let o=QT("git",["rev-list","--count",`${t}..HEAD`,"--",".",...$A(n)],{cwd:e,encoding:"utf8",timeout:1200});return o.status===0&&parseInt((o.stdout||"").trim(),10)||0}catch{return 0}}function Us(e,t,n){try{let o=Jd(e);if(!o)return null;let r=vy(e,t),s=JT(r.name,r.project.projectId),i=!!s&&(!ZT(s)||!!s.refreshToken),a=tp(e,t)||!ep(e,o.authoritativeSourceFiles),l=xy(e,r.name),d=l?Object.keys(l.articles).length:0,m=Ha(e,(o.docsDir??Ga).replace(/\/+$/,"")),w=!1;try{w=Ba(m)&&Zd(m).length>0}catch{}let k=l?.lastAnalyzedCommit?vA(e,l.lastAnalyzedCommit,o):0,S=0;try{let Pe=(o.docsDir??Ga).replace(/\/+$/,""),Ue=rA(e,Pe);Ue.length>0&&(S=Rn(e,Pe,Ue.map(Et=>Et.path)).length)}catch{}let v=uo(e),C=fd({...v,directives:0}),A=eA(e,t),D=new Set(tA(e,r.name)),L=A.filter(Pe=>D.has(Pe)).length,B=A.length-L,M=new Set(A),X=nA(e,t).filter(Pe=>!M.has(Pe)),z=X.length,de=[...A.filter(Pe=>!D.has(Pe)),...X],ye=ds(e,de),Se=ye.length,ve=Vt(ye),fe=null;try{if(!wA(o.styleGuide)){let Pe=yA(e).filter(Ue=>Ue.name.toLowerCase()!=="humanise");fe={articles:bA(e).length,presets:[{cmd:"/style-guide keep",desc:"the built-in rules only \u2014 correctness and anti-slop checks (nothing changes)"},...Pe.map(Ue=>({cmd:`/style-guide use ${Ue.name.toLowerCase()}`,desc:`${Ue.name} style guide \u2014 ${Ue.rules.length} more rules`}))]}}}catch{}let Z=0,te;try{let Pe=xm(e,de);Z=Pe.length,te=Vt(Pe)}catch{}let je=0,Ne=0;try{let Pe=mA(e,Jd(e)?.outputDir??gA);je=hA(Pe).length,Ne=fA(Pe).length}catch{}let Ze=oA(e,r.name),bo=Ut(e),pn=iA(e),At=pn?{...pn,open:ky(e).filter(Pe=>Pe.status==="open").slice(0,kA).map(Pe=>({title:Pe.title,...Pe.run?{run:Pe.run}:{},...Pe.stage?{stage:Pe.stage}:{}}))}:null,gt=dA(e,o),Er=cA(e,new Date().toISOString(),{supersededByHandoff:gt!==null});uA(e,new Date().toISOString());let et=wn(e,t),ko=et?{name:et.name,replacement:et.replacement,replacementProfile:et.replacementProfile}:null,Mn=aA(e),$o=lA(e),vo=Mn?{status:Mn.status,openQuestions:$o.openQuestions,answersPending:$o.answersPending}:null;return!vo&&w&&ky(e).some(Ue=>Ue.status==="open"&&(Ue.run??"").trim()==="/discover")&&(vo={status:"pending",openQuestions:0,answersPending:0}),{ready:i&&a&&!n.claudeMissing,hasDocs:w,tracked:d,pendingText:C,directives:v.directives,behind:k,pendingWrites:S,localAhead:B,unreviewed:Se,unreviewedScope:ve,styleErrors:Z,shotsToAnnotate:je,shotsToRecapture:Ne,styleErrorScope:te,draftAhead:z,conflicts:L,openComments:Ze,outboundQuestions:As(e),autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:bo.status,devhintsCompletedVersion:bo.completedVersion,devhintsToVersion:Ie,builderStarted:sn(e),genreUnknown:n.genreUnknown,pendingAnswer:n.pendingAnswer??null,lastCommand:n.lastCommand??null,styleRules:fe,roadmap:At,discovery:vo,uncommittedDocs:Er.dirty.length,handoff:gt,shareExplained:Ba(pA(e)),sunsetEnv:ko}}catch{return null}}se();import{existsSync as CA,readFileSync as SA}from"node:fs";import{isAbsolute as PA,join as TA}from"node:path";import{DEFAULT_DOCS_DIR as AA,findPathByArticleId as EA,isArticleDocPath as DA,loadProfileMap as NA,readProjectConfig as jA,resolveActiveProfile as IA}from"document360-engine";function xA(){return process.platform==="win32"||process.platform==="darwin"}var RA=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function qa(e,t){let n=e.replace(/\\/g,"/"),o=`${RA(t)}/`,[r,s]=xA()?[n.toLowerCase(),o.toLowerCase()]:[n,o];return r.startsWith(s)?n.slice(o.length):null}var LA=70;function OA(e,t){return{docsRoot:()=>(jA(e)?.docsDir??AA).replace(/\\/g,"/").replace(/\/+$/,""),read:n=>{try{let o=PA(n)?n:TA(e,n);return CA(o)?SA(o,"utf8"):null}catch{return null}},pathForArticleId:n=>{try{let o=NA(e,IA(e,t).name);return o?EA(o,n):null}catch{return null}}}}var Ws=(e,t=LA)=>{let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"};function Bs(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 Ws(r[1])}return null}var _A=new Set(["a","an","and","as","at","but","by","for","in","of","on","or","the","to","vs","with"]),MA=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 Ry(e,t,n){let o=e.toLowerCase();return MA.has(o)?e.toUpperCase():!t&&_A.has(o)?o:!t&&!n?e:e.charAt(0).toUpperCase()+e.slice(1)}var Cy=e=>e.replace(/^\d+[-_.]/,"").split(/[-_]/).filter(Boolean);function FA(e){let t=Cy(e);return t.length===0?e:t.map((n,o)=>Ry(n,o===0,!0)).join(" ")}function Sy(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:FA(n[n.length-2])}function Py(e){let t=e.replace(/\\/g,"/").split("/").pop()??e,n=Cy(t.replace(/\.(md|markdown)$/i,""));return n.length===0?t:n.map((o,r)=>Ry(o,r===0,!1)).join(" ")}var Tt=e=>typeof e=="string"&&e?e:null,UA=e=>typeof e=="string"&&e.length>=8?`id ${e.slice(0,8)}\u2026`:null;function WA(e,t){return qa(e,t)??e.replace(/\\/g,"/")}function BA(e,t){let n=Rt(e,t,200);return n?`+${n.added} \u2212${n.removed}`:"no change"}var HA=new Set(["Edit","MultiEdit","Write"]);function GA(e,t,n,o){if(!HA.has(e))return null;let r=Tt(t.file_path);if(!r)return null;let s=WA(r,n),i=o.docsRoot();if(!(s===i||s.startsWith(`${i}/`)))return null;let a=s.slice(i.length+1);if(!a||!DA(a))return null;let l=Sy(a),d=o.read(s),m=v=>Bs(v)??Bs(d)??Py(a);if(e==="Write"){let v=Tt(t.content)??"",C=m(v);if(d===null){let A=v.replace(/\n$/,"").split(`
|
|
446
|
+
`).length;return{verb:"Draft",title:C,category:l,note:`new, ${A} lines`}}return{verb:"Rewrite",title:C,category:l,note:BA(d,v)}}let w=Array.isArray(t.edits)?t.edits.map(v=>({from:Tt(v.old_string)??"",to:Tt(v.new_string)??""})):[{from:Tt(t.old_string)??"",to:Tt(t.new_string)??""}],k=w.reduce((v,C)=>{let A=Rt(C.from,C.to,200);return A?{added:v.added+A.added,removed:v.removed+A.removed}:v},{added:0,removed:0}),S=k.added===0&&k.removed===0?"no change":`+${k.added} \u2212${k.removed}`;return{verb:"Update",title:m(w.map(v=>v.to).join(`
|
|
447
|
+
`)),category:l,note:S}}function qA(e,t,n){let o=()=>{let r=Tt(t.article_id),s=r?n.pathForArticleId(r):null;return(s?Bs(n.read(s)):null)??(s?Py(s):UA(r)??"article")};switch(e){case"d360_create_article":{let r=Tt(t.title);return r?{verb:"Create",title:Ws(r),category:Sy(t.local_path),note:"Document360 draft"}:null}case"d360_update_article":return{verb:"Update",title:Tt(t.title)?Ws(Tt(t.title)):o(),category:null,note:"Document360 draft"};case"d360_fork_article":return{verb:"Fork",title:o(),category:null,note:"new Document360 draft"};case"d360_publish_article":{let r=t.version_number;return{verb:"Publish",title:o(),category:null,note:typeof r=="number"?`v${r}`:null,loud:"LIVE"}}case"d360_unpublish_article":return{verb:"Unpublish",title:o(),category:null,note:"back to draft, removed from readers"};case"d360_create_category":{let r=Tt(t.name);return r?{verb:"Create",title:Ws(r),category:null,note:"Document360 category"}:null}case"d360_upload_drive_file":{let r=Tt(t.file_path);if(!r)return null;let s=r.replace(/\\/g,"/").split("/").pop()??r;return{verb:"Upload",title:Ws(s),category:null,note:"Document360 Drive",keepResult:!0}}default:return null}}function Va(e,t,n,o,r=OA(n,o)){try{let s="mcp__document360__";return e.startsWith(s)?qA(e.slice(s.length),t,r):GA(e,t,n,r)}catch{return null}}var VA={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"},Ay=160,np=200,Ey=40;function Ln(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:YA(n)?"\u2026"+n.slice(n.length-(t-1)):n.slice(0,t-1)+"\u2026"}function YA(e){return!e.includes(" ")&&/[/\\]/.test(e)}function Ty(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}: ${Ln(typeof r=="string"?r:JSON.stringify(r),Ey)}`);return t.length>4&&n.push("\u2026"),Ln(n.join(", "),Ay)}var KA=new Set(["file_path","notebook_path"]);function zA(e,t){return t?qa(e.replace(/\\/g,"/").replace(/\/+$/,""),t)??e:e}var Dy=e=>typeof e=="string"&&e?e:null;function XA(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});return e==="d360_sync_status"?n("Check sync status",null):null}function Ya(e,t,n){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,s="",...i]=e.split("__"),a=i.join("__");if(s==="document360"){let m=XA(a,t);if(m)return m}let l=a.replace(/^d360_/,"").replace(/_/g," ");return{title:`${s==="document360"?"Document360":s.charAt(0).toUpperCase()+s.slice(1)}: ${l}`,sep:" ",arg:Ty(t)}}let o=VA[e],r=o?t[o]:void 0;if(typeof r=="string"&&r){let s=o&&KA.has(o)?zA(r,n):r;return{title:e,sep:"",arg:Ln(s,Ay)}}return{title:e,sep:"",arg:Ty(t)}}function QA(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 JA(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(QA).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>Ln(r,np))]}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}: ${Ln(String(r),Ey)}`);return n.length>0?[Ln(n.join(" \xB7 "),np)]:null}return null}function ZA(e){let t=Dy(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function eE(e,t,n){switch(e){case"d360_create_article":{let o=ZA(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=Dy(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 ${Ln(o[0],120)}`:""}`]}default:return null}}var Ny=new Set(["Edit","Write","MultiEdit","NotebookEdit"]);function tE(e){return e.replace(/^\s*\d+\t/,"")}function nE(e,t){if(Ny.has(e))return[];let n=t.split(`
|
|
448
|
+
`);if(e==="Read"){let o=n.length,r=Bs(n.map(tE).join(`
|
|
449
|
+
`));return[`${o} line${o===1?"":"s"}${r?` \xB7 ${r}`:""}`]}if(e==="Glob"){if(/^no files found/i.test(t))return null;let o=n.filter(r=>r.trim()).length;return[`${o} file${o===1?"":"s"}`]}return e==="Grep"&&/^Found \d+/.test(n[0]??"")?[n[0]]:null}function Ka(e,t=4,n,o){let r=e.replace(/\r\n/g,`
|
|
450
|
+
`).trimEnd();if(n&&Ny.has(n))return{lines:[],hidden:0};if(!r)return{lines:["(no output)"],hidden:0};if(n&&!n.startsWith("mcp__")){let i=nE(n,r);if(i)return{lines:i,hidden:0}}if(n?.startsWith("mcp__document360__")){let i=eE(n.slice(18),o,r);if(i)return{lines:i,hidden:0}}let s=JA(r)??r.split(`
|
|
451
|
+
`);return{lines:s.slice(0,t).map(i=>Ln(i,np)),hidden:Math.max(0,s.length-t)}}function za(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function Xa(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 jy(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 Qa(e){return jy(e,"url")}function Ja(e){return jy(e,"preview_url")}function Iy(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 Uy=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/,rp=null;function Oy(){return rp===null&&(rp=pE().verboseTranscript===!0),rp}function SE(e,t,n,o){if(Uy.test(e))try{let r=Fy(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,i=Xa(t,n),a=Qa(n);e.endsWith("publish_article")&&a&&console.log(J(` \u2B95 Live: ${a}`));let l=Ja(n);l?console.log(J(` \u2B95 Preview: ${l}`)):i&&s&&console.log(J(` \u2B95 Preview: ${za(r.connection.portalUrl,s,i,r.project.languageCode??"en")}`))}catch{}}async function Wy(e=process.cwd(),t="auto",n,o){let r=rE(t);r.kind==="none"&&(console.error(""),console.error(O("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${J("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${J('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${J("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${J("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),PE(e,n),r.kind==="subscription"&&(r.stored?console.log(g(" Using your Claude subscription (no API key set).")):console.log(g(" No API key or stored Claude Code login found \u2014 trying your Claude session anyway.")),console.log(""));let s=!1,i=op({cwd:e,profileName:n,allowProdWrites:s}),a={uuid:null,firstPrompt:null,titleFired:!1},l=oE({input:process.stdin,output:process.stdout}),d=[],m=null,w=!1;l.on("line",v=>{if(m){let C=m;m=null,C(v)}else d.push(v)}),l.on("close",()=>{if(w=!0,m){let v=m;m=null,v(null)}});function k(){return d.length>0?Promise.resolve(d.shift()):w?Promise.resolve(null):(process.stdout.write(J("> ")),new Promise(v=>{m=v}))}let S={cwd:e,version:o,profileName:n,allowProdWrites:()=>s,restartAgent:()=>{i.close(),i=op({cwd:e,profileName:n,allowProdWrites:s}),a={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>a.uuid,setPendingName:v=>{a.pendingName=v},setModel:async v=>i.setModel(v),withPausedInput:async v=>{l.pause();try{return await v()}finally{l.resume()}}};try{for(;;){let v=await k();if(v===null)break;let C=v.trim();if(C){if(C.startsWith("/")){let A=my(C);if(!A)continue;let D=fy[A.name];if(!D){console.log(O(`Unknown command: /${A.name}`)),console.log(g("Type /help for the list."));continue}let L=await D(A.args,S);if(L.kind==="exit")break;if(L.kind==="clear"){S.restartAgent();continue}if(L.kind==="allow-prod"){s=!0,S.restartAgent(),console.log(q("\u2713 Production writes authorized for this session.")),console.log("");continue}if(L.kind==="resume"){i.close(),i=op({cwd:e,resume:L.uuid,profileName:n,allowProdWrites:s});let B=sE(L.uuid);a={uuid:L.uuid,firstPrompt:B?.firstPrompt??null,titleFired:!0},My(L.uuid),console.log(q(`\u2713 Resumed "${L.name}"`)),console.log("");continue}if(L.kind==="audit-blocked"){console.log(G(L.note)),console.log(g(` Run: ${L.lead.cmd} \u2014 ${L.lead.reason}.`)),console.log("");continue}if(L.kind==="forward-to-agent"){a.firstPrompt||(a.firstPrompt=L.display??L.prompt);let B=L.display??"",M=B.trim().split(/\s+/),X=ag(B),z=X?vE(e,lg(B)):[],de=M[0]==="/screenshot"&&(M[1]==="verify"||M[1]==="review"),ye=de?M[2]&&!M[2].startsWith("--")?[M[2]]:Rs(_e(e)):[],ve=M[0]==="/catch-up"&&!X?$E(e):null,fe=L.prompt;if(B.startsWith("/"))try{let Z=Ki(e,B);Z&&(fe=`${fe}
|
|
452
|
+
|
|
453
|
+
${Z}`)}catch{}if(await sp(i,fe,r,a,e,n),X)try{kE(e,z,st(X))}catch{}if(ve){let Z=po(e,ve,"",M[0]);Z.cta&&console.log(g(Z.cta.text))}if(M[0]==="/audit"&&!M.includes("--auto")&&_s(e,n),de&&ye.length>0)try{for(let Z of pr(e,ye))console.log(Z)}catch{}if(M[0]==="/push"){let Z=await us(e,n);Z&&console.log(g(Z))}if((M[0]==="/catch-up"||M[0]==="/document")&&(M.includes("--push")||M.includes("--publish")))try{let Z=await CE({cwd:e,profileName:n}),{clean:te,conflicts:je}=so(Z.entries);te.length===0?console.log(g("Nothing new to push \u2014 everything is already up to date on Document360.")):await Wt(S,te.map(Ne=>Ne.path),je.length,{skipReview:M.includes(xt)})}catch(Z){console.log(G(`Couldn't check what to push (${Z.message}) \u2014 your drafts are saved; run /push when ready.`))}}else L.kind==="continue"&&L.ownNext||TE(e,n);continue}if(gE(C)){let A=wE(C);if(A){try{yE(e,{title:A,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}a.firstPrompt||(a.firstPrompt=C),await sp(i,`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${A}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${A}" and the article path(s) you wrote.`,r,a,e,n);continue}}a.firstPrompt||(a.firstPrompt=C),await sp(i,C,r,a,e,n)}}}finally{i.close(),l.close()}}function PE(e,t){console.log(""),console.log(Jr("document360-writer")),console.log(g(` cwd: ${e}`));let n=uE(e);if(console.log(g(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(AE(e,t)),!dE(e))console.log(G(" 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(Ri(e),!sn(e))for(let r of Ci(e))console.log(G(` ${r}`))}catch{}try{let r=hE(e);r.persisted&&r.appType?console.log(g(` \u2713 Detected a ${r.appType} app \u2014 enabled the ${r.appType}-doc-playbook (change with /genre).`)):r.source==="unknown"&&(o=!0)}catch{}try{let r=bE(e);for(let s of ki(r.applied))console.log(G(` ${s}`));if(r.reopenedForRedaction)for(let s of $i(r.reopenedForRedaction).split(/\r?\n/))console.log(G(` ${s}`))}catch{}try{let r=Us(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:o}),s=r?Fs(r,{pickable:!1,scaleFor:i=>jn(e,i)}):null;if(s?.kind==="recommend"&&s.rec.note){let i=s.rec.tone==="warn"?G:g;for(let a of pa(s.rec.note).split(`
|
|
454
|
+
`))console.log(i(` ${a}`));s.rec.picker&&console.log(J(` Pick one: ${s.rec.picker.options.map(a=>a.cmd).join(" \xB7 ")}`))}}catch{}}console.log(g(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}var _y=!1;function TE(e,t){try{let n=Us(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:!1}),o=n?Fs(n,{scaleFor:r=>jn(e,r)}):null;if(o?.kind!=="recommend")return;if(o.rec.settled&&!_y){_y=!0;for(let r of pa(o.rec.settled).split(`
|
|
455
|
+
`))console.log(q(` ${r}`))}else o.rec.settled&&!o.rec.lead&&console.log(g(" Nothing is waiting. /roadmap lists the optional campaign steps."));o.rec.lead&&console.log(g(` Next: ${br(o.rec.lead)}`))}catch{}}function AE(e,t){try{let n=Fy(e,t),o=n.production?G(" \u26A0 PRODUCTION"):"",r=mE(n.name,n.project.projectId);if(!r)return g(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...Ly(r.idToken)??{},...Ly(r.accessToken)??{}},i=s.email??s.preferred_username??"signed in";return fE(r)&&!r.refreshToken?G(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):g(` Document360: ${i} \xB7 profile "${n.name}"${o}`)}catch(n){return g(` Document360: ${n.message.split(".")[0]}`)}}function EE(){console.error(""),console.error(`Sign in with your Claude subscription: run ${J("claude")} once, then retry.`),console.error(` (No Claude Code? ${J("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${J("https://console.anthropic.com/settings/keys")}`)}function DE(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;lE({uuid:t,name:r??aE(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function NE(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||cE(o,t).then(r=>{r&&iE(n,r)}).catch(()=>{})}async function sp(e,t,n,o,r,s){let i=new Map,a=!1;for await(let l of e.send(t))l.type==="tool"&&Uy.test(l.name)&&(a=!0),jE(l,o,r,n,i,s);if(a)try{let l=RE(await xE({cwd:r,profileName:s}));l&&console.log(l.startsWith("\u26A0")?G(l):l)}catch{}}function jE(e,t,n,o,r,s){switch(e.type){case"session":t.uuid||DE(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let i=Oy()?null:Va(e.name,e.input,n,s);if(i){process.stdout.write(`
|
|
456
|
+
|
|
457
|
+
`);let l=[i.category,i.note].filter(m=>!!m).map(m=>be(` \xB7 ${m}`)),d=i.loud?be(" \xB7 ")+Be(G(i.loud)):"";console.log(`${q("\u25CF")} ${J(Be(ru(i.verb)))}${Be(i.title)}${l.join("")}${d}`),r.set(e.id,{name:e.name,input:e.input,doc:!0,keepResult:i.keepResult});break}let a=Ya(e.name,e.input,process.cwd());a&&(process.stdout.write(`
|
|
458
|
+
|
|
459
|
+
`),console.log(`${be("\u25CF")} ${a.title}${a.arg!==null?be(`${a.sep}(${a.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let i=Rt(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!i)break;let a=l=>l===1?"":"s";console.log(be(` \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(g(` \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}:Ka(e.output,4,e.isError||Oy()?void 0:i.name,i.input),d=e.isError?O:be;l.lines.forEach((m,w)=>console.log(d((w===0?" \u23BF ":" ")+m))),l.hidden>0&&console.log(g(` \u2026 +${l.hidden} lines`)),e.isError||SE(i.name,i.input,e.output,n);break}case"result":{process.stdout.write(`
|
|
460
|
+
`);let i=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(g(` (${ms(i)}\u2192${ms(e.outputTokens)} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(My(t.uuid),t.titleFired||NE(t,n));break}case"error":console.error(""),e.kind==="limit"?console.log(G(`\u23F3 ${e.message}`)):console.error(O(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&EE();break}}import{render as DN}from"ink";import{resolveAuth as NN}from"document360-engine";import{useCallback as ne,useEffect as it,useMemo as wp,useRef as le,useState as ce}from"react";import{Box as De,Text as Y,useApp as uD,useInput as dD,useStdout as pD}from"ink";import{existsSync as xr,readFileSync as cl,readdirSync as hD,writeFileSync as fD}from"node:fs";import{basename as qs,dirname as mD,isAbsolute as gD,join as yp}from"node:path";import{createSession as Ab,classifyClaudeAuth as Sp,CLAUDE_CODE_SETUP_HINT as wD,loginPkce as yD,toStoredTokens as bD,saveTokens as kD,getAccessToken as $D,resolveActiveProfile as mt,resolveProjectId as vD,getArticle as xD,decodeJwtClaims as Tr,isExpired as yo,loadTokens as _n,clearTokens as RD,rememberSessionProject as CD,listStoredSessions as SD,tokensProjectId as Eb,clearProfileProject as PD,setTitle as TD,slugify as AD,touchSession as bp,upsertSession as ED,generateTitle as Db,findByName as DD,listSessions as ND,renameSession as jD,suggestNextAction as ID,readProjectConfig as $e,writeProjectConfig as Nb,readUserConfig as jb,writeUserConfig as LD,resolveAndPersistAppType as OD,detectAppType as Ib,resolveModelSetting as Pp,loadProfileMap as Lb,applyPull as ul,computeSyncStatus as dl,lintDocs as Rr,compareRemoteSources as _D,planPull as Ob,recordRunSample as MD,pushArticles as FD,pushArticle as UD,PUSH_POOL_SIZE as WD,isPullWouldBlankError as _b,localArticleTitle as Mb,establishBaselines as BD,rebaselineServerMeta as HD,inventoryRepo as GD,knownEnvironments as qD,currentEnvironments as Fb,sunsetEnvironment as Ub,resolveEnvironment as VD,planPartitions as kp,partitionEvenly as YD,screenshotPlaceholderIds as KD,trackedArticlePaths as zD,runPartitioned as Vs,partitionCoverage as $p,estimateBulkCost as Wb,resolveModelForOperation as Ys,readDocsPlan as Bb,checkForUpdate as XD,detectInstallKind as QD,isSelfUpdatable as JD,devHintsGuidePath as Hb,toolFeedbackPath as Gb,reconcileToolFeedback as ZD,reconcileUpgradeActions as eN,stampArticles as Cr,snapshotArticles as qb,listArticleFiles as tN,CONTENT_CAP_VERSION as nN,ENGINE_VERSION as ek,DEFAULT_DOCS_DIR as Tp,setProfileProject as oN,writeCrashLog as rN,applyStructureOrder as vp,orderSyncLine as xp,applyRelatedArticles as Vb,relatedSyncLine as Yb,reconcileDocsGit as sN,shareExplainedPath as iN,ensureDir as aN}from"document360-engine";Qo();kn();import{spawn as By}from"node:child_process";function IE(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function LE(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?By([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):By(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 ip(e){for(let[t,n]of IE())if(await LE(t,n,e))return!0;return!1}var Hy=/\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 Gy(e){let t=e.replace(/\s+$/,"").split(`
|
|
461
|
+
`),n=0;for(let s=t.length-1;s>=0;s--){let i=t[s];if(/^\s{0,3}\d{1,2}[.)]\s+\S/.test(i)){n++;continue}if(!(n>0&&/^\s+\S/.test(i)))break}return n<2?0:t.filter(s=>/^\s{0,3}\d{1,2}[.)]\s+\S/.test(s)).slice(-n).every((s,i)=>Number(/^\s{0,3}(\d{1,2})/.exec(s)[1])===i+1)?n:0}var OE=/\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 qy(e){let t=e.trimEnd();if(!t)return null;let n=Gy(t);return n>=2?{options:n}:/\?[\s*_"')\]]*$/.test(t)||Hy.test(t)||OE.test(t)?{options:0}:null}function ap(e,t){if(t.closed)return e;let n=e.split(`
|
|
462
|
+
`),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){Hy.test(s)&&(t.cueSeen=!0);continue}let i=/^(\s{0,3})[-*•]\s+(.*)$/.exec(s);i?(n[r]=`${i[1]}${++t.num}. ${i[2]}`,o=!0):o&&s.trim()!==""&&/^\S/.test(s)&&(t.closed=!0)}return n.join(`
|
|
463
|
+
`)}var _E=/^(?:(?:run|use|try|execute)\s+)?['"`*]?(\/[a-z][a-z-]*)['"`*]?((?:\s+(?:--?[a-z][\w-]*|\S*[/\\]\S*|\d{1,3}[-_][\w.-]*|[\w.-]+\.(?:md|markdown)))*)/i;function ME(e,t){let n=Gy(e);return n<2?[]:e.replace(/\s+$/,"").split(`
|
|
464
|
+
`).filter(s=>/^\s{0,3}\d{1,2}[.)]\s+\S/.test(s)).slice(-n).map(s=>{let i=s.replace(/^\s{0,3}\d{1,2}[.)]\s+/,"").trim(),a=_E.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 Vy(e,t){let n=ME(e,t);return n.length<2||n.some(o=>o===null)?null:n}function FE(e){let t=e.split(`
|
|
465
|
+
`).map(o=>o.trim()).filter(o=>o.length>3),n=t[t.length-1];return n?n.length>160?`${n.slice(0,157)}\u2026`:n:null}function kr(e){if(e.usageLimit)return`${e.label}: ${e.usageLimit}`;let t=e.stderrTail?FE(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 UE={la:"local","l all":"local","local all":"local",pa:"portal","p all":"portal","portal all":"portal",sa:"skip","s all":"skip","skip all":"skip"},WE={L:"local",P:"portal",S:"skip"},BE={ya:"write","y all":"write","yes all":"write",na:"skip","n all":"skip","no all":"skip"},HE={Y:"write",N:"skip"};function Yy(e,t,n){let o=e.trim(),r=o.toLowerCase().replace(/\s+/g," ");return t[r]??(o.length===1?n[o]??null:null)}function Za(e){return Yy(e,UE,WE)}function Ky(e){return Yy(e,BE,HE)}function lp(e,t){let n=t?.max??12,o=t?.chrome??8;return Math.max(3,Math.min(n,(e??24)-o))}function el(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 cp(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 zy(e){return e<2?null:`1-${e}`}function ft(e){let t=[];if(e.multi)t.push("\u2191\u2193 move","space toggle");else{t.push("\u2191\u2193 move");let n=e.rows===void 0?null:zy(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 Xy(e){if(e.multi)return"pick with space, then enter to save \xB7 esc to cancel\u2026";let t=e.rows===void 0?null:zy(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 GE=[/\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],qE=[/\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/],VE=/^(read|glob|grep|ls|search|notebookread)$/i;function Qy(e,t){return!e||!VE.test(e.trim())||qE.some(n=>n.test(t))?!1:GE.some(n=>n.test(t))}import{existsSync as YE,mkdirSync as KE,readFileSync as zE,writeFileSync as XE}from"node:fs";import{join as Jy}from"node:path";import{writerDir as QE}from"document360-engine";function Zy(e){return Jy(QE(e),".sessions")}function eb(e,t){return Jy(Zy(e),`${t}.json`)}function tb(e,t,n){try{KE(Zy(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");XE(eb(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function up(e,t){try{let n=eb(e,t);if(!YE(n))return[];let o=JSON.parse(zE(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var JE=e=>`\x1B]0;${e}\x07`,ZE=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function nb(e){process.stdout.isTTY&&process.stdout.write(e)}function $r(e){nb(JE(e))}function tl(e){nb(ZE(e))}var nl=["\xB7 "," \xB7"],ol="\u{1F7E3}";va();var ob=()=>({fingerprint:null,counts:null,settled:0,spokenBaseline:null,lastSpokeAt:null,awaySince:null}),eD={hints:0,requests:0,answers:0,directives:0};function dp(e,t){let n=e??eD;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 rl=e=>e.hints===0&&e.requests===0&&e.answers===0&&e.directives===0,rb=e=>e.hints+e.requests+e.answers+e.directives,pp=(e,t)=>e-t>=6e5;function sb(e){let{now:t,lastInputAt:n,fingerprint:o,counts:r,occupied:s,prev:i}=e,a=pp(t,n),d=i.fingerprint!==null&&i.fingerprint!==o?0:i.settled+1,m={...i,fingerprint:o,counts:r,settled:d,awaySince:a?i.awaySince??t:null,spokenBaseline:i.spokenBaseline??r};if(a){let k=dp(m.spokenBaseline,r);return{memory:m,speak:null,waiting:rl(k)?null:k}}if(s)return{memory:m,speak:null,waiting:null};if(d<2)return{memory:m,speak:null,waiting:null};let w=dp(i.spokenBaseline,r);return rl(w)?{memory:m,speak:null,waiting:null}:i.lastSpokeAt!==null&&t-i.lastSpokeAt<6e5?{memory:m,speak:null,waiting:null}:{memory:{...m,spokenBaseline:r,lastSpokeAt:t,settled:d},speak:w,waiting:null}}function ib(e,t,n){if(e.awaySince===null)return{kind:"none",memory:e};let o=t-e.awaySince,r=dp(e.spokenBaseline,n),s={...e,awaySince:null,counts:n,spokenBaseline:n,lastSpokeAt:rl(r)?e.lastSpokeAt:t};return rl(r)?{kind:"none",memory:s}:{kind:o>=36e5?"briefing":"delta",memory:s,delta:r,awayMs:o}}function Hs(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 hp(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 ab(e){return`\u{1F4E5} ${Hs(e)} just arrived from your builder \u2014 /catch-up folds ${rb(e)===1?"it":"them"} into the docs.`}function lb(e,t){return`\u{1F4E5} While you were away (${hp(t)}): ${Hs(e)} from your builder \u2014 /catch-up folds ${rb(e)===1?"it":"them"} into the docs.`}function cb(e){return`\u{1F4E5} ${Hs(e)} waiting from your builder \xB7 tab to run /catch-up\u2026`}Ti();import{publishGateVerdict as Rp,publishGateLines as Cp,SKIP_STYLE_FLAG as Kb,SKIP_SHOTS_FLAG as lN}from"document360-engine";import{askBuilder as cN,openGapQuestions as uN}from"document360-engine";import{retireArticle as dN,normalizeScope as pN}from"document360-engine";se();import{Box as Gs,Text as Me}from"ink";import{jsx as Fe,jsxs as vr}from"react/jsx-runtime";function tD({row:e,nameW:t,width:n}){let o=s=>Vl(s,n),r=(s,i)=>Fe(Gs,{flexDirection:"column",children:s.map(i)});switch(e.t){case"head":return r(o(e.s),(s,i)=>Fe(Me,{color:ae,bold:!0,children:s},i));case"text":return r(o(e.s),(s,i)=>Fe(Me,{children:s},i));case"dim":return r(o(e.s),(s,i)=>Fe(Me,{dimColor:!0,children:s},i));case"sub":return r(o(e.s),(s,i)=>Fe(Me,{bold:!0,dimColor:!0,children:s},i));case"good":return r(o(e.s),(s,i)=>Fe(Me,{color:"green",children:s},i));case"step":{let s=o(`${e.n}. ${e.s}`);return Fe(Gs,{flexDirection:"column",children:s.map((i,a)=>a===0?vr(Me,{children:[Fe(Me,{color:ae,children:`${e.n}. `}),i.slice(`${e.n}. `.length)]},a):Fe(Me,{children:i},a))})}case"cmd":{let s=vi(e.name,e.s,t,n),i=s.descLines.slice(s.nameOwnLine?0:1);return vr(Gs,{flexDirection:"column",children:[vr(Me,{children:[" ",Fe(Me,{color:ae,children:s.nameCell}),!s.nameOwnLine&&Fe(Me,{dimColor:!0,children:` ${s.descLines[0]??""}`})]}),i.map((a,l)=>Fe(Me,{dimColor:!0,children:`${s.indent}${a}`},l))]})}case"gap":return Fe(Me,{children:" "})}}function ub({tab:e,scroll:t,rows:n,width:o,version:r,engineVersion:s}){let i=ct[e]??ct[0],a=ql(i.rows),l=Math.max(20,o-2),d=6+ct.reduce((A,D)=>A+D.label.length+4,0),m="\u2500".repeat(Math.min(d,l)),w=`\u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 \u2191\u2193 scroll \xB7 esc close \xB7 d360-writer v${r} \xB7 engine v${s}`,k=Wh({rows:n,inner:l,barWidth:d,footerWidth:w.length}),{visible:S,above:v,below:C}=Uh(i.rows,{width:o,budget:k,scroll:t,nameW:a});return vr(Gs,{flexDirection:"column",paddingX:1,children:[vr(Me,{children:[Fe(Me,{color:ae,bold:!0,children:"Help "}),ct.map((A,D)=>D===e?Fe(Me,{color:"white",backgroundColor:ae,bold:!0,children:` ${A.label} `},A.key):Fe(Me,{dimColor:!0,children:` ${A.label} `},A.key))]}),Fe(Me,{color:ae,children:m}),vr(Gs,{flexDirection:"column",marginTop:1,children:[v>0?Fe(Me,{dimColor:!0,children:`\u22EF ${v} more above`}):null,S.map((A,D)=>Fe(tD,{row:A,nameW:a,width:o},v+D)),C>0?Fe(Me,{dimColor:!0,children:`\u22EF ${C} more below`}):null]}),Fe(Me,{dimColor:!0,children:`
|
|
466
|
+
\u2190/\u2192 or tab switch \xB7 1-5 jump${v+C>0?" \xB7 \u2191\u2193 scroll":""} \xB7 esc close \xB7 d360-writer v${r} \xB7 engine v${s}`})]})}var nD=/^(?:\d+[.)]|[-*•])\s+/;function db(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
|
|
467
|
+
`)){let i=s.trim().replace(nD,""),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 wo(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function Ve(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function sl(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var oD=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function fp(e,t,n){if(!oD.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 mp(e){return e.replace(/^[\w.-]+\//,"")}var il=16,pb={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function On(e){return typeof e=="string"?e:e.cmd}function hb(e){return typeof e=="string"?void 0:e.desc}function gp(e){return e.trim().split(/\s+/).slice(1).join(" ")}function fb(e,t){let n=gp(t);return e.some(r=>On(r).trim()===t.trim()||!!n&&gp(On(r))===n)?e.filter(r=>On(r).trim()!==t.trim()&&!(n&&gp(On(r))===n)):[]}import{isDirectiveMention as hN,stripDirectiveMention as fN,appendDirective as mN,reconcileTestidRequest as gN,builderChannelWired as wN,pendingFingerprint as yN}from"document360-engine";var rD=/\[Pasted text #\d+ \+\d+ lines?\]/g;function mb(e){return e.replace(/\r\n?/g,`
|
|
468
|
+
`)}function gb(e){return e.includes(`
|
|
469
|
+
`)||e.length>200}function wb(e,t){let n=t.split(`
|
|
470
|
+
`).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function yb(e,t){return e.replace(rD,n=>t.get(n)??n)}function bb(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function al(e,t){let n=Math.max(1,t),o=[],r=0;for(let s of e.split(`
|
|
471
|
+
`)){if(s.length===0)o.push({start:r,end:r});else for(let i=0;i<s.length;i+=n)o.push({start:r+i,end:r+Math.min(i+n,s.length)});r+=s.length+1}return o.length>0?o:[{start:0,end:0}]}function ll(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function kb(e,t,n){let o=ll(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 $b(e,t,n){let o=e[ll(e,t)];return n==="start"?o.start:o.end}var sD=new Set(["Edit","Write","MultiEdit","NotebookEdit"]),vb={hint:"hint",message:"message",state:"state file",roadmap:"roadmap",directive:"directives",feedback:"tool-feedback"},iD=new Set(["hint","message","state"]),aD=["hint","message","roadmap","directive","feedback","state"];function lD(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 xb(e,t){let n=e==="Read"?"read":sD.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=lD(r.slice(i+s.length));return a?{category:a,verb:n,path:r}:null}function Rb(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 aD)for(let s of["updated","read"]){let i=t.get(`${r}:${s}`)?.size??0;i!==0&&o.push(iD.has(r)?`${i} ${vb[r]}${i===1?"":"s"} ${s}`:`${vb[r]} ${s}`)}return o.length>0?o.join(" \xB7 "):null}function Cb(e,t,n){let o=Math.max(1,n),r=e.split(`
|
|
472
472
|
`),s=0;for(let i=r.length-1;i>=0;i--){let a=r[i];if(s+=Math.max(1,Math.ceil(a.length/o)),s>=t){let l=s-t;return{text:[l>0?a.slice(l*o):a,...r.slice(i+1)].join(`
|
|
473
|
-
`),truncated:i>0||l>0}}}return{text:e,truncated:!1}}function
|
|
474
|
-
`)){let s=o+r.length;/^\s*```/.test(r)?t=!t:!t&&r.trim()===""&&s<e.length&&(n=s+1),o=s+1}return n}import{Fragment as
|
|
473
|
+
`),truncated:i>0||l>0}}}return{text:e,truncated:!1}}function Sb(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 Pb(e){let t=!1,n=0,o=0;for(let r of e.split(`
|
|
474
|
+
`)){let s=o+r.length;/^\s*```/.test(r)?t=!t:!t&&r.trim()===""&&s<e.length&&(n=s+1),o=s+1}return n}import{Fragment as Pr,jsx as V,jsxs as ue}from"react/jsx-runtime";var bN={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL",auto:"auto \u2014 right-sized for docs \xB7 /model to change"},zb=` 1. /init \u2014 pick your Document360 environment & scaffold config
|
|
475
475
|
2. /login \u2014 sign in & pick your Document360 project (workspace auto-selected)
|
|
476
|
-
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function
|
|
477
|
-
`).length+1,console.log(p)},[Ge]),
|
|
478
|
-
`)}catch{}u.picker&&(Z(u.picker.options.map(T=>({cmd:T.cmd,desc:T.desc}))),No(u.picker.title),
|
|
479
|
-
`)}),nn(u.prompt,
|
|
480
|
-
${
|
|
476
|
+
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function kN(e,t,n,o){let r=Sp(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=Pp(e),a=$e(e),l=(a?.docsDir??Tp).replace(/\/+$/,""),d=a?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${l}/ + config`,m={version:t,engineVersion:ek,captureVersion:ut(),claude:s,model:i.model,modelSource:bN[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 m;try{let w=mt(e,o);m.profile=w.name,m.apiUrl=w.connection.apiUrl,m.prod=w.production,m.project=w.project.projectName??w.project.projectId??"(chosen at login)";let k=_n(w.name,w.project.projectId);if(k){let S={...Tr(k.idToken)??{},...Tr(k.accessToken)??{}},v=S.email??S.preferred_username??"signed in";yo(k)?k.refreshToken&&(m.who=v,m.loggedOut=!1,m.sessionHint="session expired \u2014 refreshing\u2026"):(m.who=v,m.loggedOut=!1,m.sessionHint=`session valid until ${new Date(k.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return m}var $N=e=>e.mode==="local-only"?e.path:e.plan.path;function vN(e,t){try{let n=mt(e,t),o=_n(n.name,n.project.projectId);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...Tr(o.idToken)??{},...Tr(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return yo(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 Xb=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],Ar=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],xN="Ask me to write or update an article\u2026",Qb=2e3,RN=new Set(ao.map(e=>e.name));function Sr({ch:e,dim:t}){let[n,o]=ce(!0);return it(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),V(Y,{inverse:n,color:t&&!n?"gray":void 0,children:e})}function dn({rows:e,cursor:t,cap:n,render:o}){let r=el(e.length,t,n);return ue(Pr,{children:[r.above>0?V(Y,{color:"gray",children:` \u22EF ${r.above} more above`}):null,e.slice(r.start,r.end).map((s,i)=>o(s,r.start+i,r.start+i===t)),r.below>0?V(Y,{color:"gray",children:` \u22EF ${r.below} more below`}):null]})}var Jb=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Zb(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var CN=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function SN({startTime:e,chars:t}){let[n,o]=ce(0),r=le(Date.now());it(()=>{let d=setInterval(()=>o(m=>m+1),120);return()=>clearInterval(d)},[]);let s=Ar[n%Ar.length],i=Xb[Math.floor(n/16)%Xb.length],a=og(e,r.current,Date.now()),l=Math.round(t/4);return ue(De,{children:[V(Y,{color:ae,children:` ${s} ${i}\u2026 `}),V(Y,{color:"gray",children:`(${Pn(a)} \xB7 ~${l} tokens \xB7 esc to interrupt)`})]})}function PN({text:e}){let[t,n]=ce(0);return it(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),V(De,{paddingX:1,children:V(Y,{color:ae,children:`${Ar[t%Ar.length]} ${e}`})})}var TN=12e4;function AN({p:e}){let[t,n]=ce(0);it(()=>{let D=setInterval(()=>n(L=>L+1),150);return()=>clearInterval(D)},[]);let o=Ar[t%Ar.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>=TN,l=e.verb??"Converting",d=e.unit??"article",m=e.rows.reduce((D,L)=>D+L.items,0),w=e.rows.reduce((D,L)=>D+(L.status==="done"?L.items:L.itemsDone??0),0),k=l.toLowerCase(),S=e.rows,v=0;if(S.length>il){let D=S.findIndex(B=>B.status==="active"||B.status==="pending"),L=Math.max(0,Math.min(D-2,S.length-il));v=S.slice(0,L).filter(B=>B.status==="done").length,S=S.slice(L,L+il)}let C=Math.min(40,Math.max(...S.map(D=>mp(D.label).length),0)),A=D=>D==="failed"?"red":D==="active"?ae:void 0;return ue(De,{flexDirection:"column",children:[ue(De,{children:[V(Y,{color:ae,children:` ${o} ${l} ${m} ${d}${m===1?"":"s"} `}),V(Y,{color:"gray",children:e.agentless?`\xB7 ${w}/${m} ${d}${m===1?"":"s"} \xB7 ${Pn(r)} \xB7 esc to stop`:`\xB7 ${w}/${m} ${d}${m===1?"":"s"} \xB7 ${e.done}/${e.total} batch${e.total===1?"":"es"} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${i} tokens \xB7 ${Pn(r)} \xB7 esc to stop`})]}),v>0&&V(Y,{dimColor:!0,children:` \u2714 +${v} done`}),S.map(D=>ue(Y,{color:A(D.status),dimColor:D.status==="done"||D.status==="pending",children:[` ${pb[D.status]} ${mp(D.label).padEnd(C)}`,D.status==="active"&&D.itemsDone!==void 0?` (${D.itemsDone}/${D.items} ${d}${D.items===1?"":"s"})`:D.status!=="pending"?` (${D.items} ${d}${D.items===1?"":"s"})`:"",D.status==="active"?` \u2190 ${k}\u2026`:""]},D.label)),a&&V(Y,{color:"yellow",children:` \u26A0 no activity for ${Pn(s)} \u2014 press esc to stop if it's wedged`}),a&&e.stalledNote?V(Y,{color:"yellow",children:` ${e.stalledNote}`}):null]})}var EN=10800*1e3;function tk({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=uD(),[s,i]=ce(n),[a,l]=ce(null),[d,m]=ce({text:"",pos:0}),w=d.text,k=ne(u=>{m(p=>{let c=typeof u=="function"?u(p.text):u;return{text:c,pos:c.length}})},[]),S=ne(u=>{m(p=>({text:p.text.slice(0,p.pos)+u+p.text.slice(p.pos),pos:p.pos+u.length}))},[]),v=ne(()=>{m(u=>{if(u.pos===0)return u;let p=u.text.slice(0,u.pos),c=bb(p)??p.slice(0,-1);return{text:c+u.text.slice(u.pos),pos:c.length}})},[]),[C,A]=ce(!1),[D,L]=ce(!1),[B,M]=ce(0),[X,z]=ce(!1),[de,ye]=ce(null),[Se,ve]=ce(null),[fe,Z]=ce([]),te=le(!1),je=le(!1),Ne=le(null),Ze=le(!1),[bo,pn]=ce(!1),At=le(!1),gt=le(0),[Er,et]=ce(!1),[ko,Mn]=ce(!1),[$o,vo]=ce(null),[Pe,Ue]=ce(0),Et=le(0),[hl,xo]=ce(0),[Ro,Ks]=ce(null),[Co,Dr]=ce(null),jp=le(new Map),ak=le(0),So=le([]),Dt=le(null);Dt.current===null&&(Dt.current=Ab({cwd:e,profileName:s,allowProdWrites:!1}));let Qt=le({uuid:null,firstPrompt:null,titleFired:!1}),Nr=le(new Map),Ip=le(null),zs=le(jb().verboseTranscript===!0),hn=le(!1),fl=le([]),Te=le([]),Jt=le([]),Nt=le([]),jr=le(null),[Lp,Fn]=ce(null),ml=le(null),[fn,Un]=ce(null),[jt,Po]=ce(null),[It,To]=ce(null),[Ye,Ao]=ce(null),[tt,Wn]=ce(null),[wt,Eo]=ce(null),[Lt,Do]=ce(null),[Ot,Bn]=ce(null),[yt,Zt]=ce(null),[ze,Ir]=ce(null),Op=le({value:0,at:0}),_p=le({value:0,at:0}),en=ne((u,p)=>{let{index:c,memory:f}=cp(_p.current,Number(u),p);return _p.current=f,c},[]),[at,Hn]=ce(null),[Mp,No]=ce(null);it(()=>Dr(null),[fe]);let[bt,Gn]=ce(null),[nt,jo]=ce(null),[Fp,gl]=ce([]),qn=le([]),Lr=le(!1),Or=le(null),wl=le(null),[lk,Up]=ce(!1),Le=le(null),[Io,he]=ce(null),[Wp,We]=ce(null),Xs=le(!1),_r=le(null),Lo=le(null),[kt,Vn]=ce(null),[Mr,Yn]=ce(null),Fr=!!(It||Ye||tt||wt||Lt||Ot||yt||ze||at||bt||nt||kt||Mr),Bp=Lt?{verb:"publish live",cancel:"leave as drafts",rows:Lt.rows.length+1}:wt?{verb:"push as drafts",rows:wt.rows.length}:at?{verb:"choose it",rows:at.rows.length}:Ot?{verb:"run it",rows:Ot.rows.length}:yt?{verb:"open it",cancel:"close",rows:yt.rows.length-1}:Ye?{verb:"switch",rows:Ye.rows.length}:tt?{verb:"switch",rows:tt.rows.length}:It?{verb:"use it",rows:It.rows.length}:jt?{verb:"switch",rows:jt.rows.length,extra:["s this session only"]}:fn?{verb:"use it",rows:Pt.length}:nt?{verb:"save",multi:!0}:null,[Hp,Kn]=ce(0),[Ur,zn]=ce(0),[ck,Gp]=ce(0),yl=wp(()=>{try{let u=Pp(e);return u.source==="auto"?`${u.model} (auto)`:u.model}catch{return null}},[e,ck]),{stdout:Ke}=pD(),[,uk]=ce(0),qp=le(`${Ke.columns??80}x${Ke.rows??24}`),Ge=ne(()=>Math.max(20,(Ke.columns??80)-1),[Ke]),Qs=ne(u=>{So.current.push(u);let p=su(u,Ge());Oo.current+=p.split(`
|
|
477
|
+
`).length+1,console.log(p)},[Ge]),bl=le([]),Js=ne(()=>{let u=bl.current;if(u.length===0)return;bl.current=[];let p=Rb(u);p&&Qs({kind:"note",tone:"info",text:`\u25CF Housekeeping ${p}`})},[Qs]),h=ne(u=>{Js(),Qs(u)},[Qs,Js]),ot=le({printed:[],armed:[],printedAt:0}),Zs=le(null),kl=le([]),Oo=le(0),Xe=ne((u,p)=>{gt.current++,ot.current.armed=[],ye(u),ve(p??null)},[]),_t=ne(()=>{gt.current++,ot.current.armed=[],ye(null),ve(null)},[]),Wr=ne(u=>{gt.current++,ot.current.armed=[],ye(null),ve(u)},[]),re=ne(u=>Xe(u,yr({kind:"cmd",cmd:u,reason:""})),[Xe]),tn=ne((u,p)=>{if(!p?.silent&&u.note&&h({kind:"note",tone:p?.tone??u.tone,text:u.note}),!p?.silent&&u.note?.includes(".d360-writer/ \u2014 your articles"))try{let T=iN(e);aN(mD(T)),fD(T,`${new Date().toISOString()}
|
|
478
|
+
`)}catch{}u.picker&&(Z(u.picker.options.map(T=>({cmd:T.cmd,desc:T.desc}))),No(u.picker.title),kl.current=u.picker.exclusive?u.picker.options.map(T=>T.cmd.trim()):[]),!p?.silent&&u.note&&(ot.current.printed=u.menu,ot.current.printedAt=Oo.current);let f=Oo.current-ot.current.printedAt<Math.max(8,(Ke.rows??24)-4)&&yy(ot.current.printed,u.menu)?u.menu:[];u.lead?(u.lead.kind==="answer"?Wr(yr(u.lead,f.length)):Xe(u.lead.kind==="cmd"?u.lead.cmd:u.lead.text,yr(u.lead,f.length)),!p?.silent&&u.note&&(Zs.current=Ms(u.lead))):!p?.silent&&!u.picker&&(_t(),f.length>0&&Wr(`1\u2013${f.length} to pick a campaign step \xB7 nothing is waiting \xB7 or just ask me anything\u2026`)),ot.current.armed=f},[h,Xe,Wr,e,Ke]),Ae=ne((u,p,c="info")=>{ot.current.armed=[],u&&h({kind:"note",tone:c,text:u}),p&&(p.kind==="answer"?Wr(yr(p)):Xe(p.kind==="cmd"?p.cmd:p.text,yr(p)),Zs.current=u?Ms(p):null)},[h,Xe,Wr]),Br=ne((u,p,c,f="info")=>{if(u.producedNothing){Ae("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||Ae(p,c,f)},[Ae]),[Hr,$l]=ce(null),[dk,Vp]=ce(!1),nn=ne((u,p)=>{$l(u),Vp(!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]),vl=ne(()=>{gN(e,new Date().toISOString());let u=cw(e);u&&(h({kind:"note",tone:"info",text:u.lines.join(`
|
|
479
|
+
`)}),nn(u.prompt,wN(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,nn]),xl=le(!1),Rl=ne(async()=>{try{if(xl.current||!JD(QD())||$e(e)?.mode==="engineer")return;let u=await XD({pkg:gr,currentVersion:o,force:!0});if(!u.updateAvailable||!u.latest)return;xl.current=!0,h({kind:"note",tone:"info",text:`\u2B06 Updating ${gr} ${u.current} \u2192 ${u.latest}\u2026 (wait for the \u2713 before you /exit)`}),Mn(!0);let p=await Na().finally(()=>Mn(!1));p.ok?(h({kind:"note",tone:"ok",text:`\u2713 Updated to v${u.latest} \u2014 run /exit, then relaunch to apply.`}),re("/exit"),vo(u.latest)):h({kind:"note",tone:"warn",text:`Update available (v${u.latest}) but auto-update failed. ${Da(p.output)}`})}catch{}},[e,o,h,re]),Gr=le(!1),Cl=le(null),Yp=ne(async u=>{if(!Gr.current)try{let p=$e(e);if(!p)return;let c=Kp.current;if(!c)return;if(c.pushConsent!=="on"){if(c.uncommitted===0)return;Gr.current=!0;try{let T=await sN(e,p);if(T.commit?.ok)Cl.current=null;else if(T.commit&&!T.commit.ok){let W=`${T.commit.reason}:${T.commit.detail??""}`;Cl.current!==W&&(Cl.current=W,h({kind:"note",tone:"warn",text:`\u26A0 Couldn't save your docs work to git \u2014 ${Nn(T.commit.reason,T.commit.detail)}`}))}}finally{Gr.current=!1}return}if(c.uncommitted===0&&c.unpushed===0&&!u.pull)return;Gr.current=!0;try{let{lines:T,changed:W}=await Sa(e,p);for(let H of T)H.tone==="warn"||H.tone==="error"?h({kind:"note",tone:H.tone,text:H.text}):H.text.includes("\u2B07")&&h({kind:"note",tone:H.tone,text:H.text});W&&M(H=>H+1)}finally{Gr.current=!1}}catch{}},[e,h]),Xn=ne(u=>{let p=qe(e,s);return p.ok?!0:(h({kind:"note",tone:"warn",text:p.reason}),Lo.current=u,re("/login"),!1)},[e,s,h,re]),[ei,Sl]=ce(null),Kp=le(null),zp=le(null),Mt=ne((u,p)=>{let c=Us(e,s,{claudeMissing:Sp(t).state==="missing",allowAutoAudit:u,genreUnknown:Ze.current,pendingAnswer:Ne.current,lastCommand:zp.current});return Kp.current=c?.handoff??null,c?Fs(c,{header:p,pickable:!0,scaleFor:f=>jn(e,f)}):{kind:"idle"}},[e,s,t]),Pl=le(Date.now()),qr=le(ob()),Xp=le(0),[Qp,Jp]=ce(null),Vr=le(!0),_o=le(!1),ti=le(0),Yr=le(0);it(()=>{let u=setInterval(()=>{if(Vr.current){ti.current=0,Yr.current=0;return}if(!C)try{if(!xr(Hb(e)))return;if(Ut(e).status==="current"){Vr.current=!0,ti.current=0,Yr.current=0;let c=_o.current?`\u2713 Your builder finished the protocol update (v${Ie}) \u2014 the dev\u2194docs hand-off is current again. Here\u2019s where your docs stand:`:"\u2713 Your builder finished the hand-off \u2014 the architecture brief is in. I can read this repo now and write accurate docs. Here\u2019s where things stand:",f=Mt(!1,c),T=f.kind==="recommend"?f.rec:null;$l(null),T?.note?tn(T,{tone:"ok"}):(h({kind:"note",tone:"ok",text:`${c}${T?.lead?` ${br(T.lead)}`:""}`}),T?.lead||T?.picker?tn(T,{silent:!0}):_o.current||Xe("write the docs for this repo")),M(W=>W+1);return}if(_o.current)return;ti.current+=1;let p=ti.current;if((p===4||p%15===0)&&Yr.current<3){Yr.current+=1;let c=Yr.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";h({kind:"note",tone:"info",text:sn(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${c}`:`\u23F3 Waiting for your builder to run the prompt \u2014 paste it into your coding agent; I'll pick up automatically when it's done.${c}`})}}catch{}},4e3);return()=>clearInterval(u)},[e,C,h,Mt,tn,Xe]),it(()=>{let u=Lp??qs(e);if(!C){tl(0),$r(`${ol} ${u}`);return}tl(3);let p=0;$r(`${nl[0]} ${u}`);let c=setInterval(()=>{p=(p+1)%nl.length,$r(`${nl[p]} ${u}`)},400);return()=>clearInterval(c)},[C,e,Lp]),it(()=>()=>tl(0),[]),it(()=>{let u=performance.now(),p=[],c=(y,$)=>{let R=performance.now();try{return $()}finally{let b=Math.round(performance.now()-R);b>=80&&p.push(`${y}: ${b}ms`)}};h({kind:"banner",info:c("banner",()=>kN(e,o,t,s))});let f=Sp(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.
|
|
480
|
+
${wD}
|
|
481
481
|
Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!$e(e)){h({kind:"note",tone:"info",text:`Welcome! This repo isn't set up for d360-writer yet \u2014 three steps and you're writing docs:
|
|
482
|
-
${
|
|
483
|
-
`)}),nn(to()),
|
|
484
|
-
`)}),y.reopenedForRedaction&&h({kind:"note",tone:"warn",text
|
|
482
|
+
${zb}`}),re(f?"/doctor":"/init");return}f&&re("/doctor");try{let y=mt(e,s);y.project.projectId&&CD(y.name,y.project.projectId,y.project.projectName);let $=_n(y.name,y.project.projectId),R=qe(e,s);$&&yo($)&&$.refreshToken?$D({profile:y.name,connection:y.connection,projectId:y.project.projectId,projectName:y.project.projectName}).then(()=>{h({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),M(b=>b+1)}).catch(()=>{h({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 sign in again with /login."}),re("/login")}):R.ok||(h({kind:"note",tone:"warn",text:R.reason}),re("/login"))}catch{}try{let y=$e(e),$=mt(e,s),R=_n($.name,$.project.projectId);y&&R&&!yo(R)&&ep(e,y.authoritativeSourceFiles)&&!tp(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."}),re("/scope"))}catch{}try{let y=c("resolve-genre",()=>OD(e));y.persisted&&y.appType?h({kind:"note",tone:"ok",text:`\u2713 Detected a ${y.appType} app \u2014 enabled the ${y.appType}-doc-playbook (change with /genre, or edit .d360-writer/config.json).`}):y.source==="unknown"&&$e(e)&&(Ze.current=!0)}catch{}let T=Ut(e);try{if(c("reconcile-devhints",()=>Ri(e)),T.status!=="current"&&!sn(e)){let y=Ci(e);y.length&&(h({kind:"note",tone:"warn",text:y.join(`
|
|
483
|
+
`)}),nn(to()),Vr.current=!1,_o.current=!1)}}catch{}try{let y=c("reconcile-feedback",()=>ZD(e));y.archived>0&&h({kind:"note",tone:"ok",text:`\u2713 Tidied ${y.archived} resolved item${y.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${y.open>0?`; ${y.open} still open`:""}.`})}catch{}try{let y=c("upgrade-actions",()=>eN(e));y.applied.length>0&&h({kind:"note",tone:"warn",text:ki(y.applied).join(`
|
|
484
|
+
`)}),y.reopenedForRedaction&&h({kind:"note",tone:"warn",text:$i(y.reopenedForRedaction)})}catch{}let W=c("ready-decision",()=>Mt(!0));W.kind==="autoAudit"?(h({kind:"note",tone:"info",text:W.note}),ps({cwd:e,profileName:s}).then(y=>{if(y.kind==="audit-blocked"){Ae(y.note,{kind:"cmd",cmd:y.lead.cmd,reason:y.lead.reason},"warn");return}y.kind!=="forward-to-agent"||!y.prompt||xe(y.prompt,{display:y.display,quietUser:!0}).then($=>{if($.producedNothing)return;let R=ta(e,s);if(R){Ae(R.note,{kind:"cmd",cmd:or.cmd,reason:or.reason},"warn"),M(b=>b+1);return}_s(e,s),M(b=>b+1)})})):W.kind==="recommend"&&tn(W.rec);let H=Math.round(performance.now()-u);H>=800&&rN({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${H}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${p.length?p.join(`
|
|
485
485
|
`):"no single phase \u226580ms"}
|
|
486
|
-
cwd: ${e}`}),
|
|
487
|
-
|
|
488
|
-
${j}`)}catch{}p?.quietUser||h({kind:"user",text:p?.echoDisplay&&p.display?p.display:u});let
|
|
489
|
-
`)}),re(
|
|
490
|
-
`)});let F=
|
|
491
|
-
`)}),[h]),Fo=ne((u,p,c,
|
|
492
|
-
`)});let N=T.stop();if(Fo(
|
|
493
|
-
`)}),Fo(y,R.results,R.totalCostUsd,!R.aborted&&!N.length&&!R.blocked&&!R.allEmpty);let j=new Set(N),K=[...p.rest??[],...u.filter(_=>j.has(_.label))];if(K.length>0&&!R.aborted&&p.report){let _=K.reduce((U,ie)=>U+ie.threads.length,0);h({kind:"note",tone:"info",text:`${_} comment${_===1?"":"s"} on ${K.length} other article${K.length===1?"":"s"} still open \u2014 pick the next one, or esc to stop here.`});let F={...p.report,threads:K.flatMap(U=>U.threads)};Mo(
|
|
494
|
-
`)}),re(
|
|
495
|
-
`)}),c.blocked.length>0?re("/review --blocked --fix"):
|
|
496
|
-
`):`${
|
|
486
|
+
cwd: ${e}`}),Rl(),Yp({pull:!0})},[]),it(()=>{let u=setInterval(()=>{Rl()},EN);return()=>clearInterval(u)},[Rl]),it(()=>{let u=setInterval(()=>{try{let p=Date.now(),c=pp(p,Pl.current);if(Xp.current+=1,c&&Xp.current%Math.round(3e5/6e4)!==0)return;let f=yN(e),T=qr.current,W=f===T.fingerprint&&T.counts?T.counts:uo(e),H=sb({now:p,lastInputAt:Pl.current,fingerprint:f,counts:W,occupied:C||X||fe.length>0||w!==""||Fr||Te.current.length>0,prev:T});if(qr.current=H.memory,Jp(H.waiting),H.speak){h({kind:"note",tone:"info",text:ab(H.speak)});let y=Mt(!1);y.kind==="recommend"&&tn(y.rec,{silent:!0})}}catch{}},6e4);return()=>clearInterval(u)},[e,C,X,fe.length,w,Fr,h,Mt,tn]),it(()=>{if(C||X||te.current||de!==null||fe.length>0||w!==""||Hr!==null||Te.current.length>0||jr.current||Fr)return;let u=Mt(!1);if(u.kind==="recommend"&&(u.rec.lead||u.rec.picker||u.rec.menu.length>0)){tn(u.rec,{silent:!0});let p=u.rec.lead,c=p?Ms(p):u.rec.settled?"settled":null;c&&c!==Zs.current&&(Zs.current=c,u.rec.settled&&h({kind:"note",tone:"ok",text:u.rec.settled}),p&&h({kind:"note",tone:"info",text:br(p)}))}Yp({pull:!1})},[C,X,de,fe,w,Hr,Fr,B,Mt,bo]),it(()=>{let u=null,p=null,c=()=>{u&&clearTimeout(u),u=setTimeout(()=>{u=null;let f=`${Ke.columns??80}x${Ke.rows??24}`;f!==qp.current&&(qp.current=f,uk(T=>T+1),p&&clearTimeout(p),p=setTimeout(()=>{p=null;let T=Math.max(8,(Ke.rows??24)-2);console.log("\x1B[?2026h\x1B[H\x1B[2J"+rg(So.current,Ge(),T)+"\x1B[?2026l")},80))},400)};return Ke.on("resize",c),()=>{u&&clearTimeout(u),p&&clearTimeout(p),Ke.off("resize",c)}},[Ke,Ge]);let rt=Math.max(20,(Ke.columns??80)-1),Zp=wp(()=>vN(e,s),[e,s,B]),Tl=(()=>{if(ko)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if($o!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${$o?` v${$o}`:""}\u2026`,isSetup:!0};if(Bp)return{text:Xy(Bp),isSetup:!0};if(ei)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(Hr)return dk?{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(Qp)return{text:cb(Qp),isSetup:!0};if(Te.current.length>0){let f=Te.current.length,T=Te.current[0].mode;return T==="local-only"?{text:"l publish yours over the portal \xB7 s skip \xB7 anything else cancels\u2026",isSetup:!0}:T==="conflict"?{text: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=$e(e);if(!u)return{text:"Run /init to set up this repo (or /help)\u2026",isSetup:!0};let p=yp(e,(u.docsDir??Tp).replace(/\/+$/,"")),c=(()=>{try{return xr(p)&&hD(p).length>0}catch{return!1}})();try{let f=mt(e,s),T=_n(f.name,f.project.projectId);if(!(!!T&&!(yo(T)&&!T.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:xN,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),on=Ym(w),eh=on.length>0&&!C,pk=12,Gt=lp(Ke.rows),hk=Ke.rows??24,th=lp(Ke.rows,{max:pk}),ni=Math.min(hl,Math.max(0,on.length-1)),Qn=el(on.length,ni,th).start,Al=on.slice(Qn,Qn+th),El=a!==null?Cb(a,8,rt):null,oi=bt?bt.paths.filter(u=>!bt.query||u.toLowerCase().includes(bt.query.toLowerCase())).slice(0,8):[],ri=kt?kt.sessions.filter(u=>{let p=kt.query.toLowerCase();return!p||u.name.toLowerCase().includes(p)||u.firstPrompt.toLowerCase().includes(p)}).slice(0,8):[],Qe=ne((u,p)=>{Dt.current?.close(),Dt.current=Ab({cwd:e,resume:u,profileName:p??s,allowProdWrites:hn.current}),u||(Qt.current={uuid:null,firstPrompt:null,titleFired:!1},Fn(null)),Kn(0),zn(0)},[e,s]),nh=ne((u,p,c)=>{if(Jb.test(u))try{let f=mt(e,s),T=typeof p.project_id=="string"&&p.project_id||f.project.projectId,W=Xa(p,c),H=[],y=Iy(p,c),$=y?`${y} \u2014 `:"",R=Qa(c);u.endsWith("publish_article")&&R&&H.push(`${$}Live: ${R}`);let b=Ja(c);b?H.push(`${$}Preview: ${b}`):W&&T&&H.push(`${$}Preview: ${za(f.connection.portalUrl,T,W,f.project.languageCode??"en")}`),H.length>0&&h({kind:"link",lines:H})}catch{}},[e,s,h]),xe=ne(async(u,p)=>{et(!0),te.current=!1,je.current=!1,Ne.current=null,_t(),Z([]),No(null),$l(null);let c=gt.current;if(p?.display?.startsWith("/"))try{let j=Ki(e,p.display);j&&(u=`${u}
|
|
487
|
+
|
|
488
|
+
${j}`)}catch{}p?.quietUser||h({kind:"user",text:p?.echoDisplay&&p.display?p.display:u});let f=Qt.current;f.firstPrompt||(f.firstPrompt=p?.display??u),Et.current=Date.now(),Ue(0),A(!0),Nr.current.clear();let T="",W=!1,H=!1,y=!1,$=!1,R="",b={num:0,closed:!1,cueSeen:!1},x=null,P=()=>{x||(x=setTimeout(()=>{x=null,l(R.length>0?R:null)},60))},N=()=>{x&&clearTimeout(x),x=null,l(null)},E=(j=!1)=>{let{head:K,keep:_}=Sb(R,j);K.trim()&&h({kind:"assistant",text:ap(K.trimEnd(),b)}),R=_,N()};try{for await(let j of Dt.current.send(u))if(j.type==="session"){if(!f.uuid){f.uuid=j.sessionId;let K=new Date().toISOString(),_=ml.current,F=_??AD(f.firstPrompt??"session");ED({uuid:j.sessionId,name:F,renamed:!!_,titled:!1,cwd:e,firstPrompt:f.firstPrompt??"",createdAt:K,updatedAt:K}),Fn(F),ml.current=null}}else if(j.type==="text"){R+=j.delta,T+=j.delta;let K=Pb(R);if(K>0){let _=R.slice(0,K).trimEnd();_&&h({kind:"assistant",text:ap(_,b)}),R=R.slice(K)}P(),Ue(_=>_+j.delta.length)}else if(j.type==="tool"){W=!0,Jb.test(j.name)&&(H=!0);let _=(pe=>typeof pe=="string"&&pe?pe.replace(/\\/g,"/").toLowerCase():null)(j.input.file_path??j.input.notebook_path),F=["Edit","Write","MultiEdit","NotebookEdit"].includes(j.name),U=j.name==="Read"&&_!==null&&_===Ip.current;Ip.current=F?_:null;let ie=zs.current,oe=ie?null:xb(j.name,j.input),Ee=ie?null:Va(j.name,j.input,e,s);if(oe)bl.current.push(oe);else if(Ee)E(),h({kind:"doc",verb:Ee.verb,title:Ee.title,category:Ee.category,note:Ee.note,...Ee.loud?{loud:Ee.loud}:{}}),Nr.current.set(j.id,{name:j.name,input:j.input,doc:!0,keepResult:Ee.keepResult});else if(U)E(),h({kind:"tool",title:"Read",sep:"",arg:"re-checking the file it just edited"});else{let pe=Ya(j.name,j.input,e);pe&&(E(),h({kind:"tool",title:pe.title,sep:pe.sep,arg:pe.arg}),Nr.current.set(j.id,{name:j.name,input:j.input}))}}else if(j.type==="article_diff"){let K=Rt(j.oldContent,j.newContent,Ge());K&&(E(),h({kind:"diff",added:K.added,removed:K.removed,lines:K.lines,hidden:K.hidden}))}else if(j.type==="tool_result"){j.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(j.output)&&(Xs.current=!0);let K=Nr.current.get(j.id);if(K){Nr.current.delete(j.id),E();let F=K.doc&&!K.keepResult&&!j.isError?{lines:[],hidden:0}:Ka(j.output,4,j.isError||zs.current?void 0:K.name,K.input),U=j.isError&&Qy(K.name,j.output);F.lines.length>0&&h({kind:"tool-result",lines:F.lines,hidden:F.hidden,isError:j.isError&&!U}),j.isError||nh(K.name,K.input,j.output)}}else if(j.type==="result"){E(!0),Kn(U=>U+j.outputTokens),zn(U=>Math.max(U,j.sessionCostUsd));let K=j.inputTokens+j.cacheReadTokens+j.cacheCreationTokens;if(h({kind:"done",seconds:Math.round((Date.now()-Et.current)/1e3),tokens:j.outputTokens,costUsd:j.costUsd,sessionCostUsd:Math.max(Ur,j.sessionCostUsd),ok:j.ok,...K>0?{inTokens:K,cachedPct:Math.round(j.cacheReadTokens/K*100)}:{}}),!y&&!W&&!T.trim()&&!Lr.current&&($=!0,h({kind:"note",tone:"warn",text:"The agent produced no output \u2014 nothing ran this turn. Run /doctor: it runs a real turn with your skills and tools and reports what failed. Claude Code\u2019s own error was written either way \u2014 /logs shows it, and offers to copy it for the team."})),j.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(T))try{let U=Gb(e);if(xr(U)){let ie=cl(U,"utf8").trim();ie&&(Sl(ie),h({kind:"note",tone:"info",text:"\u{1F6E0} Press c to copy this feedback \u2014 send it to the d360-writer team (Teams / Slack / email)."}))}}catch{}let _=j.ok?qy(T):null;je.current=_!==null,Ne.current=_;let F=j.ok?Vy(T,RN):null;if(F)pn(!1),At.current=!1,Z(F);else if(j.ok&&(b.cueSeen||(_?.options??0)>=2))pn(!0),At.current=!0,Z([]);else if(_)Z([]);else{let U=j.ok?db(T,ao.map(ie=>ie.name)):[];if(U.length>0)re(U[0]);else if(j.ok&&T.trim()&&!je.current){let ie=Mt(!1);ie.kind==="recommend"&&(ie.rec.lead||ie.rec.picker)||ID(u,T,e).then(oe=>{oe&>.current===c&&Xe(oe)}).catch(()=>{})}}if(f.uuid&&(bp(f.uuid),!f.titleFired)){f.titleFired=!0;let U=f.uuid,ie=f.firstPrompt;ie&&Db(ie,e).then(oe=>{oe&&(TD(U,oe),Fn(oe))}).catch(()=>{})}}else j.type==="error"&&(E(!0),y=!0,j.kind==="auth"&&(Xs.current=!0),h(j.kind==="limit"?{kind:"note",text:`\u23F3 ${j.message}`,tone:"warn"}:{kind:"note",text:`agent error: ${j.message}`,tone:"error"}))}finally{if(A(!1),N(),Js(),H)try{let j=xp(await vp({cwd:e,profileName:s,onRateLimit:K=>We(`Document360 rate limit \u2014 waiting ${Math.ceil(K.waitMs/1e3)}s\u2026`)}));j&&h({kind:"note",tone:j.startsWith("\u26A0")?"warn":"info",text:j})}catch{}finally{We(null)}M(j=>j+1),Qt.current.uuid&&tb(e,Qt.current.uuid,So.current),Xs.current?(Xs.current=!1,_r.current=p?.display??u,Xe("/login","\u21E5 tab to run /login \u2014 then I\u2019ll re-send your last prompt\u2026")):_r.current=null,Lr.current&&(Lr.current=!1,qn.current.length>0&&(h({kind:"note",tone:"info",text:`(${qn.current.length} queued message(s) discarded)`}),qn.current=[],gl([])),h({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}return{producedNothing:$,handedBack:Ne.current!==null}},[e,h,nh,Ge,Xe,re,_t,Mt,Js]),si=ne(async()=>{try{We("Checking Document360 for new reviewer comments\u2026"),await Pa(e,s,{onProgress:(u,p)=>We(`Checking Document360 for new reviewer comments\u2026 ${u}/${p}`)})}catch{}finally{We(null)}},[e,s]),lt=ne(async(u,p=0,c)=>{let f=Rp(e,u,{allowUnreviewed:c?.skipReview===!0,allowStyleErrors:c?.skipStyle===!0});if(!f.clear){h({kind:"note",tone:"warn",text:Cp(f,u.length,{act:"push"}).join(`
|
|
489
|
+
`)}),re(mu(f));return}Et.current=Date.now(),Ue(0),A(!0);let T=new AbortController;Le.current=T;let W={aborted:!1,partitions:0,failed:0,notRun:0,producedNothing:!0},H=async(y,$)=>{let R=kp(y),b=new Map;for(let U of R)for(let ie of U.paths)b.set(ie,U.label);let x=new Map(R.map(U=>[U.label,U.paths.length])),P=new Set,N=Date.now();he({verb:"Pushing",unit:"article",total:y.length,done:0,active:[],rows:wo(R),tools:0,chars:0,lastAt:Date.now(),startedAt:N,agentless:!0}),h({kind:"note",tone:"info",text:$?`Resolving cross-links in ${y.length} article${y.length===1?"":"s"} whose targets were saved this run (second pass)\u2026 (esc to stop)`:`Pushing ${y.length} article${y.length===1?"":"s"} to Document360 (${WD} at a time)\u2026 (esc to stop)`});let E=await FD({cwd:e,profileName:s,paths:y,allowProdWrites:hn.current,...c?.allowUnpullable===!0?{allowUnpullable:!0}:{},signal:T.signal,onEvent:U=>{let ie=U.type==="article_done"?U.result.path:U.type==="article_failed"?U.failure.path:U.path,oe=b.get(ie);if(!oe)return;if(U.type==="article_start"){he(pe=>pe&&!pe.active.includes(oe)?{...pe,active:[...pe.active,oe],rows:Ve(pe.rows,oe,"active"),lastAt:Date.now()}:pe&&{...pe,lastAt:Date.now()});return}U.type==="article_failed"&&P.add(oe);let Ee=(x.get(oe)??1)-1;x.set(oe,Ee),he(pe=>{if(!pe)return pe;let Q={...pe,done:pe.done+1,rows:sl(pe.rows,oe),lastAt:Date.now()};return Ee>0?Q:{...Q,active:Q.active.filter(ke=>ke!==oe),rows:Ve(Q.rows,oe,P.has(oe)?"failed":"done")}})}}),j=E.aborted,K=Ic(e,y,s);$||(W={aborted:j,partitions:R.length,failed:E.failed.length,notRun:E.notRun.length,producedNothing:E.pushed.length===0,verifiedComplete:K>=y.length,leftBehind:p});let _=E.pushed.length>0;h({kind:"note",tone:j||E.failed.length>0||!_?"warn":"ok",text:(j?"Stopped. ":"")+Lc(E,{recorded:K,elapsedMs:Date.now()-N,...$?{}:{conflictsSkipped:p},...c?.scope?{scope:c.scope}:{}}).join(`
|
|
490
|
+
`)});let F=jc(e,s);if(F&&h({kind:"note",tone:"info",text:F}),!j&&_){let U=nr(e,s);U&&h({kind:"note",tone:"info",text:U});try{let oe=await vp({cwd:e,profileName:s,onRateLimit:pe=>We(`Document360 rate limit \u2014 waiting ${Math.ceil(pe.waitMs/1e3)}s\u2026`)}),Ee=xp(oe);Ee?h({kind:"note",tone:Ee.startsWith("\u26A0")?"warn":"info",text:Ee}):oe.skipped&&h({kind:"note",tone:"warn",text:`Order sync skipped: ${oe.skipped}`})}catch(oe){h({kind:"note",tone:"warn",text:`Order sync failed: ${oe.message}`})}finally{We(null)}try{let oe=Yb(await Vb({cwd:e,profileName:s}));oe&&h({kind:"note",tone:"info",text:oe})}catch(oe){h({kind:"note",tone:"warn",text:`Related-articles sync failed: ${oe.message}`})}let ie=await us(e,s);ie&&h({kind:"note",tone:"info",text:ie})}return j};try{if(!await H(u,!1)){let $=await Oc(e,s,u);$.length>0&&await H($,!0),mn(c?.scope?`/push ${c.scope}`:"/push --all",W),p>0&&Ae(null,{kind:"cmd",cmd:"/resolve",reason:`${p} conflict${p===1?"":"s"} still need settling \u2014 they were left untouched`},"warn")}}catch(y){h({kind:"note",tone:"error",text:`Publish run failed: ${y.message}`})}finally{Le.current=null,he(null),await si(),A(!1),M(y=>y+1)}},[e,s,h,t,Ae,si]),Mo=ne(u=>h({kind:"block",text:u.join(`
|
|
491
|
+
`)}),[h]),Fo=ne((u,p,c,f,T)=>{let W=Ct(u,p,c,Date.now(),T);h({kind:"done",seconds:W.seconds,tokens:W.outputTokens,costUsd:W.costUsd,ok:f,...W.activeSeconds!==void 0?{activeSeconds:W.activeSeconds}:{},sessionCostUsd:Ur+c,...W.inputTokens>0?{inTokens:W.inputTokens,...W.cachedPct!==void 0?{cachedPct:W.cachedPct}:{}}:{}})},[h,Ur]),ii=ne(async u=>{let p=Ys(e,"standard");Et.current=Date.now(),Ue(0),A(!0);let c=new AbortController;Le.current=c;let f=Date.now(),T=new sr;T.start(),he({verb:u.verb,unit:"article",total:u.partitions.length,done:0,active:[],rows:wo(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 W=!0,H=[],y=!1,$={aborted:!1,partitions:0,failed:0,notRun:0,producedNothing:!0},R=new Set;try{for await(let b of Vs({cwd:e,partitions:u.partitions,promptFor:u.promptFor,concurrency:u.concurrency,profileName:s,allowProdWrites:hn.current,model:p.model,signal:c.signal,scope:u.scope}))if(b.type==="partition_status")b.status==="running"?he(x=>x&&{...x,active:[...x.active,b.label],rows:Ve(x.rows,b.label,"active"),lastAt:Date.now()}):he(x=>x&&{...x,active:x.active.filter(P=>P!==b.label),done:x.done+1,rows:Ve(x.rows,b.label,b.status==="done"?"done":"failed"),lastAt:Date.now()});else if(b.type==="partition_stalled"){let x=kr(b);he(P=>P&&x?{...P,stalledNote:x}:P)}else if(b.type==="partition_event"){let x=null;if(b.event.type==="tool"){let P=fp(b.event.name,b.event.input,u.partitions[b.index]?.paths??[]);P&&!R.has(P)&&(R.add(P),x=b.label)}he(P=>{if(!P)return P;let N={...P,lastAt:Date.now()};return b.event.type==="tool"?N.tools=P.tools+1:b.event.type==="text"&&(N.chars=P.chars+b.event.delta.length),x&&(N.rows=sl(N.rows,x)),N})}else if(b.type==="run_done"){zn(E=>E+b.totalCostUsd),Kn(E=>E+b.results.reduce((j,K)=>j+K.outputTokens,0));let x=$p(u.partitions,b.results);W=!!b.allEmpty||!!b.blocked,y=!!b.aborted,$={aborted:!!b.aborted,partitions:u.partitions.length,failed:x.failed.length,notRun:x.notRun.length,...b.blocked?{blocked:b.blocked}:{},...b.allEmpty?{allEmpty:!0}:{},...b.bailedEmpty?{bailedEmpty:!0}:{}};let P=[`${b.aborted?"Stopped. ":""}${b.results.length-x.failed.length}/${u.partitions.length} batches ${u.doneNoun}.`,...x.failed.length?[`\u26A0 ${x.failed.length} not ${u.doneNoun} \u2014 their articles are unchanged: ${x.failed.map(E=>E.label).join(", ")}`]:[],...x.notRun.length?[`\u26A0 ${x.notRun.length} batch${x.notRun.length===1?"":"es"} never started \u2014 their articles are untouched.`]:[],...b.blocked?[`\u26A0 ${b.blocked}`]:[],...b.allEmpty?[u.emptyNote??"\u26A0 No turn produced any work this run \u2014 nothing was changed."]:[],...u.caveatLines??[]];h({kind:"note",tone:b.aborted||x.failed.length||x.notRun.length||b.blocked||b.allEmpty?"warn":"ok",text:P.join(`
|
|
492
|
+
`)});let N=T.stop();if(Fo(f,b.results,b.totalCostUsd,!y&&!W&&!x.failed.length,N.activeSeconds),u.calibrateAs){let E=b.results.filter(j=>j.ok).length;MD(e,u.calibrateAs,{articles:x.covered.length,waves:Math.ceil(E/Math.max(1,u.concurrency)),seconds:N.activeSeconds,costUsd:b.totalCostUsd})}W||(H=x.covered)}}catch(b){h({kind:"note",tone:"error",text:`${u.verb} failed: ${b.message}`})}finally{T.stop(),Le.current=null,he(null),A(!1),M(b=>b+1)}return{producedNothing:W,covered:H,aborted:y,outcome:$}},[e,s,h,Fo]),fk=ne(async(u,p)=>{let c=await ii({partitions:u.partitions,promptFor:u.promptFor,concurrency:In,verb:"Reviewing",doneNoun:"reviewed",headline:`Reviewing ${u.articles} article${u.articles===1?"":"s"} in ${u.partitions.length} batches (\u2264${In} editors at once)${p?", applying fixes as they go":", report only"}`+(()=>{let f=_a(e,"/review",u.articles,u.partitions.length);return f?` \xB7 ${f}`:""})(),caveatLines:qd(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{Cr(e,c.covered,st("review"))}catch{}return{producedNothing:c.producedNothing,aborted:c.aborted,outcome:c.outcome}},[e,ii]),Dl=ne(async(u,p)=>{if(u.length===0)return;let c=u.reduce((R,b)=>R+b.threads.length,0),f=new Map,T=u.map(R=>(f.set(R.label,R),{label:R.label,paths:R.path?[R.path]:[]})),W=Ys(e,"standard");Et.current=Date.now(),Ue(0),A(!0);let H=new AbortController;Le.current=H;let y=Date.now(),$=qb(e);he({verb:"Answering",unit:"article",total:T.length,done:0,active:[],rows:wo(T),tools:0,chars:0,lastAt:Date.now(),startedAt:y}),h({kind:"note",tone:"info",text:`Answering ${c} comment${c===1?"":"s"} across ${T.length} article${T.length===1?"":"s"} (\u2264${Ds} agents at once) on ${W.model}. Each article is fixed, pushed to Document360 as a draft, then answered in the thread${p.resolve?" and resolved":" \u2014 the threads stay open for your reviewers to close"}\u2026 (esc to stop)`});try{for await(let R of Vs({cwd:e,partitions:T,promptFor:b=>{let x=f.get(b.label);return Cd({articleId:x.articleId,label:x.label,path:x.path,count:x.threads.length,resolve:p.resolve})},concurrency:Ds,profileName:s,allowProdWrites:hn.current,allowCommentResolve:p.resolve,model:W.model,signal:H.signal}))if(R.type==="partition_status")R.status==="running"?he(b=>b&&{...b,active:[...b.active,R.label],rows:Ve(b.rows,R.label,"active"),lastAt:Date.now()}):he(b=>b&&{...b,active:b.active.filter(x=>x!==R.label),done:b.done+1,rows:Ve(b.rows,R.label,R.status==="done"?"done":"failed"),lastAt:Date.now()});else if(R.type==="partition_stalled"){let b=kr(R);he(x=>x&&b?{...x,stalledNote:b}:x)}else if(R.type==="partition_event")he(b=>{if(!b)return b;let x={...b,lastAt:Date.now()};return R.event.type==="tool"?x.tools=b.tools+1:R.event.type==="text"&&(x.chars=b.chars+R.event.delta.length),x});else if(R.type==="run_done"){zn(_=>_+R.totalCostUsd),Kn(_=>_+R.results.reduce((F,U)=>F+U.outputTokens,0));let b=$p(T,R.results),x=R.results.length-b.failed.length,P=R.aborted?"Stopped. ":"",N=[...b.failed.map(_=>_.label),...b.notRun.map(_=>_.label)],E=[`${P}${x}/${T.length} article${T.length===1?"":"s"} answered.`,...N.length?[`\u26A0 ${N.length} left untouched (their threads are still open, which is correct \u2014 nothing was promised to those reviewers): ${N.join(", ")}`]:[],...R.blocked?[`\u26A0 ${R.blocked}`]:[],...R.allEmpty?["\u26A0 No agent produced any work this run \u2014 nothing was changed or answered."]:[]];h({kind:"note",tone:R.aborted||N.length||R.blocked||R.allEmpty?"warn":"ok",text:E.join(`
|
|
493
|
+
`)}),Fo(y,R.results,R.totalCostUsd,!R.aborted&&!N.length&&!R.blocked&&!R.allEmpty);let j=new Set(N),K=[...p.rest??[],...u.filter(_=>j.has(_.label))];if(K.length>0&&!R.aborted&&p.report){let _=K.reduce((U,ie)=>U+ie.threads.length,0);h({kind:"note",tone:"info",text:`${_} comment${_===1?"":"s"} on ${K.length} other article${K.length===1?"":"s"} still open \u2014 pick the next one, or esc to stop here.`});let F={...p.report,threads:K.flatMap(U=>U.threads)};Mo(Ns(F,{width:Ge()})),Zt({cursor:0,rows:Aa(K),groups:K,resolve:p.resolve,report:F})}else if(K.length>0&&!R.aborted){let _=K.map(U=>U.path).filter(U=>!!U),F=_.length===K.length?Vt(_):void 0;re(F?_.length===1?`/comments ${F}`:`/comments --scope ${F}`:"/comments")}}}catch(R){h({kind:"note",tone:"error",text:`Answering comments failed: ${R.message}`})}finally{let b=po(e,$,"","/comments").changed.length;b>0&&h({kind:"note",tone:"info",text:`${b} article${b===1?"":"s"} changed, and that new text has not been read by an editor \u2014 ${b===1?"it":"they"} can go live once /review has been over ${b===1?"it":"them"}.`}),Le.current=null,he(null),A(!1),M(x=>x+1)}},[e,s,h,Ae,re,Mo,Ge]),Nl=ne(async(u,p)=>{if(!(p?.skipReview===!0||p?.skipStyle===!0)){let f=Rp(e,[u],{});if(!f.clear){h({kind:"note",tone:"warn",text:Cp(f,1,{act:"push"}).join(`
|
|
494
|
+
`)}),re(mu(f,u));return}}await lt([u],0,{skipReview:p?.skipReview,skipStyle:p?.skipStyle,scope:u});try{let f=await Zi(e,s,u.replace(/\\/g,"/"));f.length>0&&(No(`Related articles not yet saved to Document360 (${f.length}):`),Z([`/push --related ${u}`,...f.map(T=>`/push ${T}`)]))}catch{}},[e,s,xe,lt]),mk=ne(async(u,p)=>{A(!0);try{let c=await Bc(e,s,u,{skipReview:p.skipReview,skipStyle:p.skipStyle,onProgress:(T,W,H)=>We(`Publishing ${T+1}/${W} \u2014 ${H}\u2026`)}),f=c.blocked.length+c.failed.length;h({kind:"note",tone:f>0?"warn":"ok",text:Hc(c).join(`
|
|
495
|
+
`)}),c.blocked.length>0?re("/review --blocked --fix"):Ae(null,null)}catch(c){h({kind:"note",tone:"error",text:`Publishing failed: ${c.message}`})}finally{We(null),await si(),A(!1),M(c=>c+1)}},[e,s,h,re,Ae,si]),oh=ne(async u=>{try{let p=await dl({cwd:e,profileName:s}),{clean:c,conflicts:f}=so(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 lt(c.map(T=>T.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,lt]),mn=ne((u,p)=>{if(!(p&&!Yt(p)))for(let c of vt(e,u))h({kind:"note",tone:"ok",text:c})},[e,h]),rh=ne(async(u,p)=>{let f=YD(u,3),T=Ys(e,"standard"),W=new Map,H=new Map;for(let b of u){let x=oo(e,b),P=lc(e,b,x);if(P&&W.set(b,P),x!==null){let N=$c(x);N.length>0&&H.set(b,N)}}Et.current=Date.now(),Ue(0),A(!0);let y=new AbortController;Le.current=y;let $=Date.now();he({verb:"Authoring",unit:"spec",total:f.length,done:0,active:[],rows:wo(f),tools:0,chars:0,lastAt:Date.now(),startedAt:$}),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 ${T.model}${T.forced?" (forced)":""}\u2026 (esc to stop)`});let R=!1;try{for await(let b of Vs({cwd:e,partitions:f,promptFor:x=>Zf(x,W,H),concurrency:6,profileName:s,allowProdWrites:hn.current,model:T.model,signal:y.signal}))if(b.type==="partition_status")b.status==="running"?he(x=>x&&{...x,active:[...x.active,b.label],rows:Ve(x.rows,b.label,"active"),lastAt:Date.now()}):he(x=>x&&{...x,active:x.active.filter(P=>P!==b.label),done:x.done+1,rows:Ve(x.rows,b.label,b.status==="done"?"done":"failed"),lastAt:Date.now()});else if(b.type==="partition_stalled"){let x=kr(b);he(P=>P&&x?{...P,stalledNote:x}:P)}else if(b.type==="partition_event")he(x=>{if(!x)return x;let P={...x,lastAt:Date.now()};return b.event.type==="tool"?P.tools=x.tools+1:b.event.type==="text"&&(P.chars=x.chars+b.event.delta.length),P});else if(b.type==="run_done"){zn(j=>j+b.totalCostUsd),Kn(j=>j+b.results.reduce((K,_)=>K+_.outputTokens,0));let x=b.results.filter(j=>j.ok).length,P=b.aborted?"Stopped. ":"";R=!b.aborted&&p.setup;let N=b.aborted?"":R?" Refreshing the staging checklist\u2026":` Next: /screenshot capture${p.scope?` ${p.scope}`:" --all"} (or /screenshot checklist first for the staging checklist).`,E=Cn(b,"Spec authoring");h({kind:"note",tone:E||b.aborted?"warn":b.ok?"ok":"warn",text:E?E.join(`
|
|
496
|
+
`):`${P}Authored specs \u2014 ${x}/${b.results.length} batches ok.${N}`}),Fo($,b.results,b.totalCostUsd,!E&&!b.aborted&&b.ok),E&&(re("/doctor"),R=!1),!b.aborted&&b.ok&&!E&&mn(p.runLine)}}catch(b){h({kind:"note",tone:"error",text:`Spec authoring failed: ${b.message}`})}finally{Le.current=null,he(null),A(!1),M(b=>b+1)}if(R){let b=await fr();b.kind==="forward-to-agent"&&b.prompt&&await xe(b.prompt,{display:b.display,quietUser:!0}),vl()}},[e,s,h,xe,mn,vl]),sh=ne(async u=>{let p=lc(e,u,oo(e,u))??void 0,c=await qi([u],void 0,{prior:p});c.kind==="forward-to-agent"&&c.prompt&&await xe(c.prompt,{display:c.display,quietUser:!0}),Mf(e,u)&&Ae(`Spec ready \u2014 /screenshot capture ${u} takes the screenshot; bare /screenshot picks the next shot.`,{kind:"cmd",cmd:`/screenshot capture ${u}`,reason:""})},[e,xe,Ae]),ai=ne(async(u,p)=>{if(u.length===0)return{drawn:[],undrawn:[],cliMissing:!1};A(!0);let c=new AbortController;Le.current=c,he({verb:"Drawing callouts",unit:"screenshot",total:u.length,done:0,active:[],rows:u.map(x=>({label:x,items:1,status:"pending"})),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()});let f=[],T=!1;try{let x=await sd({cwd:e,ids:u,...p.force?{force:!0}:{},signal:c.signal,onStart:P=>he(N=>N&&{...N,active:[P],rows:Ve(N.rows,P,"active"),lastAt:Date.now()}),onDone:(P,N)=>he(E=>E&&{...E,active:[],done:E.done+1,rows:Ve(E.rows,P,N==="failed"?"failed":"done"),lastAt:Date.now()})});f=x.results,T=x.cliMissing??!1}catch(x){h({kind:"note",tone:"error",text:`Drawing the callouts failed: ${x.message}`})}finally{Le.current=null,he(null),A(!1),M(x=>x+1)}if(T)return h({kind:"note",tone:"error",text:"d360-capture is not installed on this machine. Run: npm i -g document360-capture \u2014 then /screenshot annotate."}),{drawn:[],undrawn:u,cliMissing:!0};let W=f.filter(x=>x.outcome==="annotated").map(x=>x.id),H=f.filter(x=>x.outcome==="skipped").map(x=>x.id),y=u.filter(x=>!W.includes(x)&&!H.includes(x));if(h({kind:"note",tone:y.length?"warn":"ok",text:[`\u25C8 ${W.length} drawn`,H.length?`${H.length} already current`:"",y.length?`\u2717 ${y.length} not drawn`:""].filter(Boolean).join(" ")}),y.length>0){let x=Math.max(...y.map(P=>P.length));h({kind:"note",tone:"warn",text:y.map(P=>`\u2717 ${P.padEnd(x)} ${Ps(f.find(N=>N.id===P)?.detail)||"no picture was produced"}`).join(`
|
|
497
497
|
`)+`
|
|
498
|
-
${y.length===1?"It has":"They have"} no publishable picture yet. Re-take the shot: /screenshot capture`})}if(p.chainVerify===!1||W.length===0)return{drawn:W,undrawn:y,cliMissing:!1};let
|
|
499
|
-
`)}),{drawn:W,undrawn:y,cliMissing:!1}},[e,h,
|
|
500
|
-
${
|
|
501
|
-
${
|
|
502
|
-
${F}`).join("")});let j=nw(
|
|
503
|
-
`)}),N.length>0){let F=Math.max(...N.map(U=>U.id.length));h({kind:"note",tone:"error",text:N.map(U=>`\u2717 ${U.id.padEnd(F)} ${
|
|
504
|
-
`)})}
|
|
505
|
-
`)});return}let _=rw({results:b,ids:u,articles:sw(e,
|
|
506
|
-
`)}),nn(to()),
|
|
507
|
-
`)}),nn(
|
|
508
|
-
${
|
|
509
|
-
`)}),y.copyText&&nn(y.copyText,{hint:y.notable?"\u2328 Press c to copy this problem report \u2014 then send it to the team (Teams / Slack / email).":"\u2328 Press c to copy this entry, if you want to send it to the team."});return}case"style-guide":{let y=
|
|
510
|
-
`)}),R&&(Qe(),h({kind:"note",tone:"ok",text:"\u2713 Agent restarted \u2014 it now writes to your house rules."})))}M(R=>R+1);return}case"genre":{let y=$e(e)?.appType??null;(await
|
|
511
|
-
`)});return}case"mcp":await
|
|
512
|
-
`)})
|
|
513
|
-
${N.path} \xB7 ${N.articleId?`updates article ${N.articleId}`:"would be created as a new article"}${E}`}),N.missingShots.length>0&&h({kind:"note",tone:"warn",text:`\u26A0 ${N.missingShots.length} screenshot${N.missingShots.length===1?"":"s"} not taken yet \u2014 the description publishes instead: ${N.missingShots.join(", ")}`}),h({kind:"note",tone:"info",text:N.body}),h({kind:"note",tone:"info",text:`Nothing was sent. /push ${N.path} saves it as a draft.`}),re(`/push ${N.path}`)}catch(N){h({kind:"note",tone:"error",text:N.message})}return}if(
|
|
498
|
+
${y.length===1?"It has":"They have"} no publishable picture yet. Re-take the shot: /screenshot capture`})}if(p.chainVerify===!1||W.length===0)return{drawn:W,undrawn:y,cliMissing:!1};let $=W.filter(x=>p.verifiedBefore.has(x)).length;if($>Ra){let x=aw({results:f,voidedVerdicts:$,...p.scope?{scope:p.scope}:{}});return x&&Ae(`${x.glyph} ${x.cmd} ${x.why}`,{kind:"cmd",cmd:x.cmd,reason:""},"warn"),{drawn:W,undrawn:y,cliMissing:!1}}let R=W.filter(x=>!p.verifiedBefore.has(x)||$>0);if(R.length===0)return{drawn:W,undrawn:y,cliMissing:!1};h({kind:"note",tone:"info",text:Dn(R.length)}),await xe(Xt(e,R),{display:"/screenshot verify",quietUser:!0});let b=pr(e,R);return b.length>0&&h({kind:"note",tone:"info",text:b.join(`
|
|
499
|
+
`)}),{drawn:W,undrawn:y,cliMissing:!1}},[e,h,Ae,xe]),Kr=ne(async(u,p)=>{if(!co(e)){await xe(ed(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(!Qg(e)){h({kind:"note",tone:"info",text:"No saved login for screenshot capture yet \u2014 opening a browser window. Sign in to your app (MFA included); I'll continue automatically once the session saves. (esc cancels)"}),A(!0),We("Waiting for you to finish logging in (browser window)\u2026");let F=new AbortController;Le.current=F;let U;try{U=await Jg({cwd:e,signal:F.signal})}catch(ie){h({kind:"note",tone:"error",text:`Could not launch the login: ${ie.message}`});return}finally{Le.current=null,We(null),A(!1)}if(U.exitCode!==0){Zu(U.exitCode,U.output)?h({kind:"note",tone:"error",text:"d360-capture is not installed on this machine. Run: npm i -g document360-capture \u2014 then /screenshot capture again."}):/unknown option/i.test(U.output)?h({kind:"note",tone:"warn",text:"Your d360-capture is older than this writer. Update it: npm i -g document360-capture \u2014 then /screenshot capture again."}):h({kind:"note",tone:F.signal.aborted?"warn":"error",text:F.signal.aborted?"Login cancelled \u2014 nothing saved.":`Login did not complete:
|
|
500
|
+
${Qu(U.output)}`});return}h({kind:"note",tone:"ok",text:"\u2713 Login saved \u2014 continuing with the capture."})}let c=new Map(u.map(F=>[F,Gf(e,F)])),f=0;if(u.length>1){let F=u.filter(U=>c.get(U).mutates);if(F.length>0&&(f=F.length,u=u.filter(U=>!c.get(U).mutates),u.length===0)){h({kind:"note",tone:"warn",text:`\u26A0 All ${F.length} spec${F.length===1?"":"s"} in scope write real data, so a bulk run has nothing to do. Run one deliberately: /screenshot capture ${F[0]}`});return}}else if(u.length===1&&c.get(u[0]).mutates){let F=c.get(u[0]),U=Zg(e);h({kind:"note",tone:"warn",text:`\u26A0 This capture performs a REAL write in your app${F.what?`: ${Hf(F.what)}`:F.declared?"":" (detected from the spec: form fill + commit click / file upload)"}. Running because you named it explicitly \u2014 check the result and clean up what it created. `+(U.production?`This profile is PRODUCTION \u2014 the write lands in the LIVE tenant${U.url?` (${U.url})`:""}. If the spec cleans up after itself, confirm it did.`:"Tip: point the capture scope (.d360-writer/capture.json) at a demo/non-production context for shots like this.")})}A(!0);let T=new AbortController;Le.current=T;let W=u.map(F=>({label:F,items:1,status:"pending"}));he({verb:"Capturing",unit:"screenshot",total:u.length,done:0,active:[],rows:W,tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()});let H=an(e),y=Object.keys(H.shots).length>0,$=ew(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)`+($?`
|
|
501
|
+
${$}`:"")});let R=Date.now(),b=[];try{for(let F of u){if(T.signal.aborted)break;he(pe=>pe&&{...pe,active:[F],rows:Ve(pe.rows,F,"active"),lastAt:Date.now()});let{exitCode:U,output:ie}=await Ju({cwd:e,id:F,signal:T.signal,stdio:"pipe"});if(Zu(U,ie)){h({kind:"note",tone:"error",text:"d360-capture is not installed on this machine. Run: npm i -g document360-capture \u2014 then /screenshot capture again."});return}let oe=T.signal.aborted&&U!==0?"failed":Xu(e,F,U,R),Ee=oe==="captured"?void 0:oe==="skipped"?zg(ie)??"a data prerequisite isn't met \u2014 the spec's skip reason names what to stage":Xg(ie);b.push({id:F,outcome:oe,detail:Ee}),he(pe=>pe&&{...pe,active:[],done:pe.done+1,rows:Ve(pe.rows,F,oe==="captured"?"done":"failed"),lastAt:Date.now()})}}catch(F){h({kind:"note",tone:"error",text:`Capture run failed: ${F.message}`})}finally{Le.current=null,he(null),A(!1),M(F=>F+1)}if(b.length===0)return;let x=b.filter(F=>F.outcome==="captured"),P=b.filter(F=>F.outcome==="skipped"),N=b.filter(F=>F.outcome==="failed"),E=u.length-b.length;h({kind:"note",tone:N.length?"warn":x.length?"ok":"info",text:[`\u2713 ${x.length} captured`,P.length?`\u2298 ${P.length} blocked`:"",N.length?`\u2717 ${N.length} broken`:"",E?`${E} not run (stopped)`:""].filter(Boolean).join(" ")+` ${b.length} run${f>0?` \xB7 ${f} held back`:""}`+ow(tw(H,b),y).map(F=>`
|
|
502
|
+
${F}`).join("")});let j=nw(P);if(j.length>0&&h({kind:"note",tone:"info",text:j.join(`
|
|
503
|
+
`)}),N.length>0){let F=Math.max(...N.map(U=>U.id.length));h({kind:"note",tone:"error",text:N.map(U=>`\u2717 ${U.id.padEnd(F)} ${Ps(U.detail)}`).join(`
|
|
504
|
+
`)})}ji(e,b.map(F=>({id:F.id,outcome:F.outcome,reason:F.detail,specSource:oo(e,F.id)})),new Date().toISOString()),b.length===u.length&&N.length===0&&P.length===0&&mn(p?.runLine);let K=[];if(x.length>0&&xa()){let F=await ai(x.map(U=>U.id),{verifiedBefore:new Set});if(F.cliMissing||(K=F.undrawn,F.drawn.length>0))return}else if(x.length>0){h({kind:"note",tone:"info",text:Dn(x.length)}),await xe(Xt(e,x.map(U=>U.id)),{display:"/screenshot verify",quietUser:!0});let F=pr(e,x.map(U=>U.id));F.length>0&&h({kind:"note",tone:"info",text:F.join(`
|
|
505
|
+
`)});return}let _=rw({results:b,ids:u,articles:sw(e,x.map(F=>F.id)),...K.length>0?{unannotated:K}:{}});_&&Ae(_.note,{kind:"cmd",cmd:_.cmd,reason:""},_.tone)},[e,h,Ae,xe,mn,ai]),jl=ne(u=>{let p=_n(u);if(!p||yo(p)&&!p.refreshToken)return null;let c={...Tr(p.idToken)??{},...Tr(p.accessToken)??{}};return c.email??c.preferred_username??"signed in"},[]),Il=ne((u,p)=>{if(p){let c=$e(e);c&&(c.defaultProfile=u,Nb(c,e))}i(u),Qe(void 0,u),h({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${u}"${p?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),jl(u)||(h({kind:"note",tone:"warn",text:`Profile "${u}" is not signed in \u2014 sign in with /login.`}),re("/login")),M(c=>c+1)},[e,h,Qe,jl,re]),li=ne((u,p,c)=>{pi(e,u,p,c.id,c.name),h({kind:"note",tone:"ok",text:`Switched to workspace "${c.name??c.id}" (agent restarted).`}),Qe(),Lb(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:zo(Ko(e)).join(`
|
|
506
|
+
`)}),nn(to()),Vr.current=Ut(e).status==="current",_o.current=sn(e),h({kind:"note",tone:"info",text:`No separate builder agent? Then just ask me now: "write the docs for this repo" \u2014 I'll read the code directly.`}))},[e,h,Qe,nn]),ci=ne(async u=>{let p;try{p=await Zr(e,u)}catch{h({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),re("/workspace");return}if(p.workspaces.length===0){h({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let c=p.workspaces.filter(T=>(T.workspace_type??"").toLowerCase()!=="apidocumentation"),f=c.length>0?c:p.workspaces;if(f.length===1){let T=f[0],W=p.workspaces.length-f.length;h({kind:"note",tone:"ok",text:`Selected the "${T.name??T.id}" workspace${W>0?" (skipped the API-documentation workspace)":""}.`}),li(p.profile,p.projectId,T);return}h({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${f.length} available).`}),re("/workspace")},[e,h,li,re]),ui=ne((u,p)=>{hi(e,u,p.id,p.name),h({kind:"note",tone:"ok",text:`Project set to "${p.name??p.id}" (agent restarted).`}),Qe(),ci(u)},[e,h,Qe,ci]),ih=ne(async u=>{let p;try{p=mt(e,u)}catch{return}if(!p.project.workspaceId){if(p.project.projectId){if(!p.project.projectName)try{let{projects:c}=await rn(e,p.name),f=c.find(T=>T.id===p.project.projectId);f?.name&&oN(e,p.name,{projectName:f.name})}catch{}await ci(p.name);return}try{let{projects:c}=await rn(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}".`}),ui(p.name,{id:f.id,name:f.name});return}if(c.length>1){let f=c.map(T=>({id:T.id,name:T.name??T.id,sub:T.sub_domain}));h({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),Wn({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."}),re("/project")}},[e,h,ci,ui,re]),Uo=ne(()=>{let u=Te.current[0];if(!u)return;if(_t(),u.mode==="local-only"){h({kind:"note",tone:"info",text:`\u25CF ${u.title??u.path} (${u.path})`});for(let W of ra())h({kind:"note",tone:"warn",text:`\u26A0 ${W}`});h({kind:"note",tone:"info",text:sa()}),h({kind:"note",tone:"info",text:Im()});return}let{plan:p,mode:c}=u;h({kind:"note",tone:"info",text:`\u25CF ${p.title} (${p.path})`});for(let W of p.notes)h({kind:"note",tone:"warn",text:`\u26A0 ${W}`});p.overwritesLocalChanges&&c==="pull"&&h({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let f=Rt(p.oldContent,p.newContent,Ge(),rr);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 T=Te.current.length;c==="conflict"?(h({kind:"note",tone:"warn",text:"Conflict \u2014 edited both here and on the portal (diff shows local \u2192 portal)."}),h({kind:"note",tone:"info",text:"Keep local (publish, overwrites portal) \xB7 take Portal (overwrites local) \xB7 Skip?"}),h({kind:"note",tone:"info",text:T>1?`(l/p/s \xB7 la/pa/sa for all ${T} \u2014 anything else stops, keeping your answers so far)`:"(l/p/s \u2014 anything else stops, keeping your answers so far)"})):h({kind:"note",tone:"info",text:T>1?`Write ${p.path}? (y/n \xB7 ya/na for all ${T} \u2014 anything else cancels)`:`Write ${p.path}? (y/n \u2014 anything else cancels)`})},[h,Ge,_t]),Jn=ne(()=>{if(Te.current.length>0){Uo();return}let u=Nt.current;Nt.current=[];let p=Jt.current;Jt.current=[];for(let c of ia(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`}),lt(u,0,{allowUnpullable:!0})):p.length>0||re("/pull")},[Uo,h,lt,re]),Ll=ne(u=>{let p=Za(u);if(!p)return!1;let c=Te.current.splice(0),f=c.length;if(p==="local"){for(let T of c)Nt.current.push($N(T));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 T=0;for(let W of c){if(W.mode==="local-only"){h({kind:"note",tone:"warn",text:`\u26A0 ${Yc(W.path)}`}),Jt.current.push(W.path);continue}try{ul({cwd:e,profileName:s},W.plan),T++}catch(H){h({kind:"note",tone:"error",text:`Take-portal failed for ${W.plan.path}: ${H.message}`})}}h({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${T} article${T===1?"":"s"} (local overwritten, sync base advanced).`})}else{for(let T of c)T.mode==="local-only"&&Jt.current.push(T.path);h({kind:"note",tone:"info",text:`Skipped all ${f} \u2014 still conflict${f===1?"":"s"}.`})}return Jn(),!0},[e,s,Jn,h]),ah=ne(u=>{if(Te.current.length===0)return!1;let p=u.trim(),c=p.toLowerCase(),f=Te.current[0];if(f.mode==="local-only"){if(Za(p))return Ll(p);if(c==="l"||c==="local"||c==="publish")Te.current.shift(),Nt.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")Te.current.shift(),Jt.current.push(f.path),h({kind:"note",tone:"info",text:`Skipped ${f.path} \u2014 still a conflict.`});else{let W=Te.current.splice(0),H=Nt.current;return Nt.current=[],Jt.current=[],h({kind:"note",tone:"info",text:`Resolve cancelled. ${W.length} conflict${W.length===1?"":"s"} left untouched.`+(H.length>0?` Saving the ${H.length} article${H.length===1?"":"s"} you already chose to keep - an answer you gave is not undone by stopping.`:"")}),H.length>0&<(H,0,{allowUnpullable:!0}),!0}return Jn(),!0}if(f.mode==="conflict"){if(Za(p))return Ll(p);if(c==="l"||c==="local")Te.current.shift(),Nt.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"){Te.current.shift();try{ul({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(W){h({kind:"note",tone:"error",text:`Take-portal failed: ${W.message}`})}}else if(c==="s"||c==="skip"||c==="n")Te.current.shift(),h({kind:"note",tone:"info",text:`Skipped ${f.plan.path} \u2014 still a conflict.`});else{let W=Te.current.length;Te.current=[];let H=Nt.current;return Nt.current=[],Jt.current=[],h({kind:"note",tone:"info",text:`Resolve cancelled. ${W} conflict${W===1?"":"s"} left untouched.`+(H.length>0?` Saving the ${H.length} article${H.length===1?"":"s"} you already chose to keep - an answer you gave is not undone by stopping.`:"")}),H.length>0&<(H,0,{allowUnpullable:!0}),!0}return Jn(),!0}let T=Ky(p);if(T){let W=Te.current.splice(0);if(T==="skip")h({kind:"note",tone:"info",text:`Skipped all ${W.length} article${W.length===1?"":"s"}.`});else{let H=0;for(let y of W){if(y.mode==="local-only"){h({kind:"note",tone:"warn",text:`\u26A0 ${Yc(y.path)}`});continue}try{ul({cwd:e,profileName:s},y.plan),H++}catch($){h({kind:"note",tone:"error",text:`Pull failed for ${y.plan.path}: ${$.message}`})}}h({kind:"note",tone:"ok",text:`\u2713 Pulled ${H} article${H===1?"":"s"} (sync base advanced).`})}return Jn(),!0}if(c==="y"||c==="yes"){let{plan:W}=f;Te.current.shift();try{ul({cwd:e,profileName:s},W),h({kind:"note",tone:"ok",text:`\u2713 Pulled ${W.path} (sync base advanced).`})}catch(H){h({kind:"note",tone:"error",text:`Pull failed: ${H.message}`})}}else if(c==="n"||c==="no")Te.current.shift(),h({kind:"note",tone:"info",text:`Skipped ${f.plan.path}.`});else{let W=Te.current.length;return Te.current=[],h({kind:"note",tone:"info",text:`Pull cancelled (${W} article(s) left untouched).`}),!0}return Jn(),!0},[e,s,Jn,h,Ll]),Ol=ne(async u=>{h({kind:"note",tone:"info",text:"Checking Document360 for conflicts\u2026"});try{let p=await dl({cwd:e,profileName:s}),c=u?.replace(/\\/g,"/"),f=p.entries.filter(H=>H.status==="conflict"&&H.path).map(H=>H.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 T=[];for(let H of f)try{T.push({plan:await Ob({cwd:e,profileName:s,relPath:H}),mode:"conflict"})}catch(y){_b(y)?T.push({mode:"local-only",path:H,title:Mb(e,H)}):h({kind:"note",tone:"error",text:`Could not load ${H} from Document360: ${y.message}`})}if(T.length===0)return;let W=T.some(H=>H.mode!=="local-only");h({kind:"note",tone:"info",text:W?`Resolving ${T.length} conflict${T.length===1?"":"s"} \u2014 for each: keep local, take portal, or skip.`:`Resolving ${T.length} conflict${T.length===1?"":"s"} \u2014 for each: publish your copy over the portal, or skip.`}),Te.current=T,Nt.current=[],Jt.current=[],Uo()}catch(p){h({kind:"note",tone:"error",text:`Could not compute sync status: ${p.message}`})}},[e,s,h,Uo]),lh=ne(u=>{let p=jr.current;if(!p)return!1;if(jr.current=null,_t(),u.trim()!==p.repoName)return h({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:c,failed:f}=Ed(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 T of f)h({kind:"note",tone:"error",text:` \u2717 ${T.path}: ${T.error}`});return p.hadDevhints&&(h({kind:"note",tone:"warn",text:Si().join(`
|
|
507
|
+
`)}),nn(Jl())),h({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
|
|
508
|
+
${zb}`}),re("/init"),et(!1),!0},[e,h,nn,_t,re]),Wo=ne(async u=>{let p=u.slice(1).trim().split(/\s+/),c=(p[0]??"").toLowerCase(),f=p.slice(1);if(zp.current=u.trim(),et(!0),ks(f)&&["write","lint","check","review","reorder"].includes(c)){let y=bs(e,s);if(y.length===0){h({kind:"note",tone:"warn",text:"No categories yet \u2014 author some articles first, then scope to one."});return}let $=R=>c==="write"?`/write ${fg(f,R).join(" ")}`.trim():`/${c} ${[R,...f.filter(b=>b!=="--scope")].join(" ")}`.trim();if(y.length===1){Wo($(y[0].token));return}Hn({cursor:0,rows:y,run:R=>{Wo($(R))}});return}if(En(c,f)){let y=c==="write"&&$s(f).rewrite,$=c==="write"?ju(e,Bb(e),{rewrite:y}):bs(e,s);if($.length>1){let R=f.filter(U=>U.startsWith("--")).join(" "),b=U=>U==="--blocked"?`/${c} --blocked${R?` ${R}`:""}`.trim():`/${c}${U?` ${c==="write"?`--scope ${U}`:U}`:""}${R?` ${R}`:""} ${U?"":"--all"}`.replace(/\s+/g," ").trim(),x=$.reduce((U,ie)=>U+ie.count,0),P={token:"",label:c==="review"?`Everything \u2014 all ${x} articles + structure (IA) review`:c==="reorder"?`Everything \u2014 reorder all ${$.length} categories`:y?`Everything \u2014 rewrite all ${x} planned articles`:`Everything \u2014 write all ${x} pending article${x===1?"":"s"}`,count:x},N=c==="review"?Wd(e):[],E=N.length>0&&N.length<x?[{token:"--blocked",label:`Only what needs review \u2014 ${N.length} article${N.length===1?"":"s"} publishing is blocked on`,count:N.length}]:[],j=c==="review"?Bd(e):[],K=j.length>N.length&&j.length<x?[{token:"--stale",label:`Everything the current editor hasn\u2019t read \u2014 ${j.length} article${j.length===1?"":"s"}`,count:j.length}]:[],_=c==="write"?`Write which articles? (counts = ${y?"articles to regenerate":"still to write"})`:c==="review"?"Review what? (counts = articles)":"Reorder what?";Hn({cursor:0,rows:(U=>c==="review"||c==="write"?U.map(ie=>{let oe=(()=>{try{return Hw(e,b(ie.token))}catch{return null}})();return oe?{...ie,label:`${ie.label} \xB7 ${oe}`}:ie}):U)([...E,...K,P,...$]),run:U=>{Wo(b(U))},title:_});return}}let T=async y=>{let $=Yu(y);if(!co(e)){await xe(ed(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if($.mode==="single"){await Kr([$.id],{runLine:[`/screenshot capture ${$.id}`,`/capture ${$.id}`]});return}if($.mode==="failed"){let b=Ku(e,Ts(e).rows);if(b.length===0){h({kind:"note",tone:"info",text:"No broken specs to re-run \u2014 /screenshot list shows where things stand."}),re("/screenshot list");return}await Kr(b);return}if($.mode==="blocked"){let{blocked:b,rows:x}=Ts(e);if(b.length===0){h({kind:"note",tone:"info",text:"No shots are waiting on app data \u2014 /screenshot list shows where things stand."}),re("/screenshot list");return}let P=as(x.filter(N=>N.state==="blocked")).length;h({kind:"note",tone:"info",text:`Re-running ${b.length} shot${b.length===1?"":"s"} that skipped on missing data last run.`+(P>0?` If you haven't staged ${P===1?"it":"those "+P+" things"} yet, ${b.length===1?"it":"they"} will skip again \u2014 /screenshot list has the worklist.`:"")}),await Kr(b,{runLine:["/screenshot capture --blocked","/screenshot capture --all --retry-blocked"]});return}if($.mode==="all"||$.mode==="scope"){let b=$.mode==="scope"?$.scope:void 0,{ready:x,captured:P,blocked:N,rows:E}=Ts(e,b),j=[...x,...P,...$.retryBlocked?N:[]];if(j.length===0&&N.length>0&&!$.retryBlocked){let _=b?`/screenshot capture ${b} --retry-blocked`:"/screenshot capture --blocked";Ae(`All ${N.length} shot${N.length===1?"":"s"} in scope ${N.length===1?"is":"are"} blocked on data that wasn't staged last run \u2014 /screenshot list shows what to stage, then ${_}.`,{kind:"cmd",cmd:"/screenshot list",reason:""},"warn");return}if(j.length===0){h({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),re("/screenshot");return}if(!$.retryBlocked){let _=b?`/screenshot capture ${b} --retry-blocked`:"/screenshot capture --blocked",F=zu(E.filter(U=>U.state==="blocked"),_);F&&h({kind:"note",tone:"info",text:F})}let K=$.mode==="scope"?[`/screenshot capture ${$.scope}`,`/capture ${$.scope}`]:["/screenshot capture --all","/capture --all"];await Kr(j,{runLine:K,...$.retryBlocked?{}:{heldBackBlocked:E.filter(_=>_.state==="blocked")}});return}let R=Kg(_e(e));if(R.length===0){h({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),re("/screenshot");return}Bn({cursor:0,rows:R,title:"Capture screenshots \u2014 pick what to shoot:"})},W=async y=>{let $=nd(y);if(!co(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."}),re("/screenshot capture");return}let R=ut();if(!xa(R)){h({kind:"note",tone:"info",text:rd(R)}),re("/update");return}let b=$.mode==="scope"?$.scope:void 0,{pending:x,done:P,rows:N}=od(e,b),E=$.mode==="all"||$.mode==="scope"?$.force:!1,j=$.mode==="single"?[$.id]:E?[...x,...P]:x;if(j.length===0){h({kind:"note",tone:"info",text:P.length>0?`Every shot${b?` under ${b}`:""} is already drawn on. To re-draw them anyway (after a wording or style change): /screenshot annotate --all --force`:"No shots have been taken yet \u2014 /screenshot capture takes them first."}),re(P.length>0?"/screenshot annotate --all --force":"/screenshot capture");return}await ai(j,{force:E,scope:b,verifiedBefore:new Set(N.filter(K=>K.state==="verified").map(K=>K.id))})},H=async()=>{let y=await fr(f,{cwd:e,profileName:s});y.kind==="forward-to-agent"&&y.prompt&&await xe(y.prompt,{display:y.display,quietUser:!0}),vl()};switch(c){case"help":Yn({tab:0,scroll:0});return;case"exit":case"quit":Dt.current?.close(),r();return;case"clear":Qe(),So.current=[],ot.current={printed:[],armed:[],printedAt:Oo.current},et(!1),_t(),console.log("\x1B[?2026h\x1B[H\x1B[2J\x1B[3J\x1B[?2026l"),h({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let y;try{y=mt(e,s)}catch($){h({kind:"note",tone:"error",text:$.message});return}h({kind:"note",tone:"info",text:`Profile "${y.name}" \u2192 ${y.connection.name} (${y.connection.apiUrl})${y.production?" \u26A0 PRODUCTION":""}`}),L(!0);try{let $=await yD(y.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},x=>h({kind:"note",tone:"info",text:x})),R=bD(y.name,$);kD(R),await Bl(R,y.name,x=>h({kind:"note",tone:"info",text:x}));let b=Eb(R);if(b){let x=mt(e,s).project;await Wl(y.name,b,x.projectId===b?x.projectName:void 0)}if(h({kind:"note",tone:"ok",text:`\u2713 Logged in to "${y.name}" as ${mi(_n(y.name,b??void 0)??R)}`}),await ih(s),!Lo.current){let x=qe(e,s);x.ok||(h({kind:"note",tone:"warn",text:x.reason}),re("/login"))}if(Lo.current){let x=Lo.current;Lo.current=null;let P=qe(e,s);P.ok?(h({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 tab to run ${x}.`}),re(x)):(h({kind:"note",tone:"warn",text:`${P.reason} (then ${x}.)`}),re("/login"),Lo.current=x)}else _r.current&&(Xe(_r.current,"\u21E5 tab to re-send your last prompt\u2026"),_r.current=null)}catch($){h({kind:"note",tone:"error",text:`Login failed: ${$.message}`})}finally{L(!1),M($=>$+1)}return}case"allow-prod":{let y=!1;try{y=mt(e,s).production}catch{}if(!y){h({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}hn.current=!0,Qe(),h({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let y=Wu(f.join(" ")),$=Qt.current.uuid;if(!$){if(!y){h({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}ml.current=y,Fn(y),$r(`${ol} ${y}`),h({kind:"note",tone:"ok",text:`Session will be named "${y}" once it starts.`});return}if(!y){h({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let R=Qt.current.firstPrompt??"";Db(R,e).then(b=>{b?(Xe(`/rename ${b}`),h({kind:"note",tone:"info",text:`Suggestion: "${b}" \u2014 press tab to accept, or type /rename <your name>.`})):h({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>h({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}jD($,y),Fn(y),$r(`${ol} ${y}`),h({kind:"note",tone:"ok",text:`Session renamed to "${y}".`});return}case"profile":{let y=f[0],$=$e(e);if(!y){let R=Object.entries($?.profiles??{});if(R.length===0){h({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let b=R.map(([N,E])=>({name:N,env:E.connection?.environment??"custom",prod:E.production===!0,who:jl(N)})),x=s??$?.defaultProfile,P=Math.max(0,b.findIndex(N=>N.name===x));Po({cursor:P,current:P,rows:b});return}if(y==="add"){let R=Bu(e,f[1],f[2]);if(R){h({kind:"note",tone:"error",text:R});return}h({kind:"note",tone:"ok",text:`\u2713 Profile "${f[1]}" created (environment: ${f[2]??f[1]}).`}),Il(f[1],!0);return}if(!$?.profiles?.[y]){h({kind:"note",tone:"error",text:`Unknown profile "${y}". Create it: /profile add ${y} <environment>`});return}Il(y,!0);return}case"doctor":await xs(f,{cwd:e,version:o});return;case"logs":{let y=Hl();h({kind:"note",tone:"info",text:y.lines.join(`
|
|
509
|
+
`)}),y.copyText&&nn(y.copyText,{hint:y.notable?"\u2328 Press c to copy this problem report \u2014 then send it to the team (Teams / Slack / email).":"\u2328 Press c to copy this entry, if you want to send it to the team."});return}case"style-guide":{let y=Md(e),$=await Oa(f,{cwd:e,profileName:s});if(y&&La(f).sub==="show"&&Ae(null,{kind:"cmd",cmd:"/style-guide keep",reason:""}),$.kind==="clear")Qe(),h({kind:"note",tone:"ok",text:"\u2713 Agent restarted \u2014 it now writes to the new rules."});else if($.kind==="forward-to-agent"){let R=La(f).sub==="learn";(await xe($.prompt,{display:$.display,quietUser:!0})).producedNothing||(h({kind:"note",tone:"info",text:(R?Mw():Fw()).join(`
|
|
510
|
+
`)}),R&&(Qe(),h({kind:"note",tone:"ok",text:"\u2713 Agent restarted \u2014 it now writes to your house rules."})))}M(R=>R+1);return}case"genre":{let y=$e(e)?.appType??null;(await Fa(f,{cwd:e})).kind==="clear"&&($e(e)?.appType??null)!==y&&(Qe(),h({kind:"note",tone:"ok",text:"\u2713 Agent restarted \u2014 the doc-craft playbook for this genre is now loaded."}));try{Ze.current=!($e(e)?.appType??Ib(e))}catch{}M(R=>R+1);return}case"roadmap":{if(f[0]?.toLowerCase()==="done"){let y=tr(e,f.slice(1).join(" ").trim());h({kind:"note",tone:y.ok?"ok":"warn",text:y.line}),M($=>$+1);return}h({kind:"block",text:Ec(e,{width:Ge(),all:f.some(y=>y.toLowerCase()==="--all")}).join(`
|
|
511
|
+
`)});return}case"mcp":await Ai(f);return;case"init":{if($e(e)){let $=wn(e,s);h({kind:"note",tone:"info",text:["This repo is already set up \u2014 /init won\u2019t overwrite it.",` Change environment: /profile add <${Fb().join("|")}> then /profile <name> (the environment lives on the profile, not the login).`," Anything else: edit .d360-writer/config.json, or run d360-writer init for the CLI wizard."].join(`
|
|
512
|
+
`)}),$&&h({kind:"note",tone:"warn",text:`\u26A0 ${$.why} \u2014 ${$.cmd} moves this repo.`});return}let y=[...Fb(),...qD().filter($=>Ub($))].map($=>({name:$,apiUrl:VD($).apiUrl,note:Ub($)?"being retired":null}));To({cursor:0,rows:y});return}case"resume":{let y=f.join(" ").trim(),$=ND(e).filter(x=>x.uuid!==Qt.current.uuid);if(!y){if(!$.length){h({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}Vn({query:"",cursor:0,sessions:$});return}let R=DD(e,y);if(!R){h({kind:"note",tone:"error",text:`No session matches "${y}".`});return}Qe(R.uuid),Qt.current={uuid:R.uuid,firstPrompt:R.firstPrompt,titleFired:!0},Fn(R.name),bp(R.uuid),So.current=[],ot.current={printed:[],armed:[],printedAt:Oo.current};let b=up(e,R.uuid);for(let x of b)h(x);h({kind:"note",tone:"ok",text:b.length?`Resumed "${R.name}" \u2014 restored ${b.length} message(s); continue where you left off.`:`Resumed "${R.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let y=f.join(" ").trim(),$;try{$=await Zr(e,s)}catch(b){h({kind:"note",tone:"error",text:`Could not list workspaces: ${b.message}`});return}if(!y){let b=$.workspaces.map(P=>({id:P.id,name:P.name??P.id,type:P.workspace_type}));if(b.length===0){h({kind:"note",tone:"info",text:"No workspaces in this project."});return}let x=Math.max(0,b.findIndex(P=>P.id===$.current));Ao({cursor:x,current:x,rows:b,profile:$.profile,projectId:$.projectId,projectName:$.projectName,environment:$.environment});return}let R=Ml($.workspaces,y);if(!R){h({kind:"note",tone:"error",text:`No workspace matches "${y}".`});return}li($.profile,$.projectId,R);return}case"project":{let y=f.join(" ").trim(),$;try{$=await rn(e,s)}catch(b){h({kind:"note",tone:"error",text:`Could not list projects: ${b.message} (signed in? try /login)`});return}if(!y){let b=$.projects.map(P=>({id:P.id,name:P.name??P.id,sub:P.sub_domain}));if(b.length===0){h({kind:"note",tone:"info",text:"No projects found for this identity."});return}let x=b.findIndex(P=>P.id===$.current);Wn({cursor:Math.max(0,x),current:x,rows:b,profile:$.profile,environment:$.environment});return}let R=Fl($.projects,y);if(!R){h({kind:"note",tone:"error",text:`No project matches "${y}". Available: ${$.projects.map(b=>b.name??b.id).join(", ")}`});return}ui($.profile,R);return}case"logout":{let y,$,R;try{let E=mt(e,s);y=E.name,$=E.project.projectId,R=E.project.projectName}catch(E){h({kind:"note",tone:"error",text:E.message});return}let b=f.includes("--all-projects"),x=SD(y).filter(E=>{let j=Eb(E);return!!j&&j!==$}).length,P=RD(y,b?void 0:$);PD(e,y),Qe(),M(E=>E+1);let N=b||x===0?"":` Your sign-in for ${x} other project${x===1?"":"s"} is untouched (/logout --all-projects clears those too).`;h({kind:"note",tone:P?"ok":"info",text:P?b?`\u2713 Signed out of every Document360 project for "${y}" and cleared this repo's project/workspace selection.`:`\u2713 Signed out of ${R?`"${R}"`:`"${y}"`} and cleared its project/workspace selection.${N}`:`Profile "${y}" was not signed in. Cleared any project/workspace selection.${N}`}),h({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),re("/login");return}case"publish":{if(Fc(f)){let P=ln("publish");P&&h({kind:"note",tone:"info",text:P}),await Wo(`/push ${f.join(" ")}`.trim());return}if(!Xn(u.trim()))return;let y=ln("publish");y&&h({kind:"note",tone:"info",text:y});let $=f.find(P=>!P.startsWith("--")),R={skipReview:f.includes(xt),skipStyle:f.includes(Kb)};We("Checking what is waiting to go live\u2026");let b;try{b=await Uc(e,s,$)}catch(P){h({kind:"note",tone:"error",text:`Could not check Document360: ${P.message}`});return}finally{We(null)}if(b.length===0){let P=Wc(e,s,$);for(let N of P.lines)h({kind:"note",tone:N.startsWith("\u2713")?"ok":"info",text:N});P.ahead>0&&re(Re("/push","",$));return}let x=Rp(e,b.map(P=>P.path),{allowUnreviewed:R.skipReview,allowStyleErrors:R.skipStyle,checkScreenshots:!0,allowPlaceholders:f.includes(lN)});if(!x.clear){for(let P of Cp(x,b.length,{scope:$,act:"publish"}))h({kind:"note",tone:"warn",text:P});re(Re("/review","--blocked --fix",$));return}h({kind:"note",tone:"info",text:`${b.length} draft${b.length===1?" is":"s are"} ahead of what readers see. Pick what goes live:`}),Do({cursor:0,rows:b,opts:R});return}case"push":{if(!Xn(u.trim()))return;let y=f.includes(xt),$=f.includes(Kb);if(f.includes("--preview")){let P=f.find(N=>!N.startsWith("--"));if(!P){h({kind:"note",tone:"error",text:"Which article? Use /push --preview <path> \u2014 a preview is per article."});return}try{let N=await UD({cwd:e,profileName:s,relPath:P.replace(/\\/g,"/"),preview:!0}),E=N.shots.length>0?` \xB7 ${N.shots.length} screenshot${N.shots.length===1?"":"s"} embedded`:"";h({kind:"note",tone:"info",text:`${N.title}
|
|
513
|
+
${N.path} \xB7 ${N.articleId?`updates article ${N.articleId}`:"would be created as a new article"}${E}`}),N.missingShots.length>0&&h({kind:"note",tone:"warn",text:`\u26A0 ${N.missingShots.length} screenshot${N.missingShots.length===1?"":"s"} not taken yet \u2014 the description publishes instead: ${N.missingShots.join(", ")}`}),h({kind:"note",tone:"info",text:N.body}),h({kind:"note",tone:"info",text:`Nothing was sent. /push ${N.path} saves it as a draft.`}),re(`/push ${N.path}`)}catch(N){h({kind:"note",tone:"error",text:N.message})}return}if(f.includes("--screenshots")||f.includes("--shots")){let P=f.find(_=>!_.startsWith("--")),N=_e(e),E=Ui(N,P);if(E.length===0){let _=N.filter(F=>F.state==="captured").length;h({kind:"note",tone:"info",text:_>0?`${_} screenshot${_===1?" has":"s have"} been taken but the callouts aren't drawn on yet, so there is nothing to embed \u2014 /screenshot annotate finishes ${_===1?"it":"them"}.`:P?`No captured screenshots in ${P} \u2014 /push --screenshots covers the whole knowledge base.`:"No captured screenshots yet \u2014 /screenshot capture first."}),_>0&&re("/screenshot annotate");return}let j=Wi(N,P);j&&h({kind:"note",tone:"warn",text:j});let K=Bi(N);K&&h({kind:"note",tone:"warn",text:K}),h({kind:"note",tone:"info",text:`Re-saving ${E.length} article${E.length===1?"":"s"} with captured screenshots so the images embed\u2026`}),await lt(E,0,{skipReview:y,skipStyle:$,scope:Re("","--screenshots",P).trim()});return}if(f[0]==="--related"&&f[1]){let P=await Zi(e,s,f[1].replace(/\\/g,"/"));if(P.length===0){h({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await lt(P,0,{skipReview:y,skipStyle:$,scope:`--related ${f[1]}`});return}let R=f.filter(P=>!P.startsWith("--"));if(R[0]){await Nl(R[0],{skipReview:y,skipStyle:$});return}let b=f.includes("--all"),x=f.includes("--force");h({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let P=await dl({cwd:e,profileName:s}),{clean:N,conflicts:E}=so(P.entries),j=b&&x&&E.length>0,K=Xi(P.entries);if(K>0&&h({kind:"note",tone:"warn",text:`\u26A0 ${K} article${K===1?"":"s"} already exist on Document360 but aren\u2019t linked \u2014 left OUT of publish (publishing would duplicate them). Run /catch-up (or ask me to link them) first.`}),E.length>0&&!j&&h({kind:"note",tone:"warn",text:cs(E.length)}),N.length===0&&!j){let _=nr(e,s);if(_&&h({kind:"note",tone:"info",text:_}),E.length>0){re("/resolve");return}h({kind:"note",tone:"ok",text:K>0?"\u2713 Nothing else is ahead of Document360 to save.":"\u2713 Nothing is ahead of Document360 \u2014 nothing to save."});let F=P.counts["unknown-base"]??0;F>0&&h({kind:"note",tone:"info",text:`(${F} article(s) have no sync base yet \u2014 /push <path> saves one anyway if you need it.)`}),We("Reconciling structure on Document360 (order + related articles)\u2026");try{let U=await vp({cwd:e,profileName:s,onRateLimit:Ee=>We(`Document360 rate limit \u2014 waiting ${Math.ceil(Ee.waitMs/1e3)}s\u2026`)}),ie=Yb(await Vb({cwd:e,profileName:s})),oe=xp(U);oe?h({kind:"note",tone:oe.startsWith("\u26A0")?"warn":"info",text:oe}):U.skipped&&h({kind:"note",tone:"warn",text:`Order sync skipped: ${U.skipped}`}),ie&&h({kind:"note",tone:"info",text:ie}),U.failures?.length?re("/structure"):(h({kind:"note",tone:"ok",text:oe||ie?"\u2713 Structure synced to Document360 \u2014 /structure shows the new category + article order.":"\u2713 Already in order \u2014 nothing to change."}),(oe||ie)&&re("/structure"))}catch(U){h({kind:"note",tone:"warn",text:`Structure sync failed: ${U.message}`})}finally{We(null)}return}if(b){let _=(j?[...N,...E]:N).map(F=>F.path);await lt(_,j?0:E.length,{skipReview:y,skipStyle:$,allowUnpullable:j});return}Eo({cursor:0,rows:vm(N,E),conflicts:E.length})}catch(P){h({kind:"note",tone:"error",text:`Could not compute sync status: ${P.message}`}),h({kind:"note",tone:"info",text:"Save one article on its own: /push <article-path>"})}return}case"resolve":{if(!Xn(u.trim()))return;await Ol(f.find(y=>!y.startsWith("--")));return}case"preview":{let y=f.join(" ").trim();if(!y){let R=[];try{R=Object.keys(Lb(e,mt(e,s).name)?.articles??{})}catch{}if(R.length===0){h({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}Gn({query:"",cursor:0,paths:R});return}let $=gD(y)?y:yp(e,y);if(xr($)){try{h({kind:"preview",name:qs($),text:Zb(cl($,"utf8"))})}catch(R){h({kind:"note",tone:"error",text:`Could not read ${$}: ${R.message}`})}return}if(CN.test(y)){try{let R=mt(e,s),b={profile:R.name,connection:R.connection},x=R.project.projectId??vD(b),P=await xD(b,x,y);h({kind:"preview",name:P.title??y,text:P.content??"*(article has no content)*"})}catch(R){h({kind:"note",tone:"error",text:`Could not fetch article: ${R.message}`})}return}h({kind:"note",tone:"error",text:`"${y}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let y=f[0]?.trim();if(!y){let x=ba(Pp(e));Un({cursor:x,current:x});return}let{lines:$,changed:R,effective:b}=vs(e,y);for(let x of $)h({kind:"note",tone:x.startsWith("\u26A0")?"warn":x.startsWith("\u2713")?"ok":"info",text:x});R&&(Gp(x=>x+1),Dt.current?.setModel(b));return}case"verbose":{let y=f[0]?.trim().toLowerCase(),$=y==="on"?!0:y==="off"?!1:!zs.current;zs.current=$;try{LD({...jb(),verboseTranscript:$})}catch{h({kind:"note",tone:"warn",text:"\u26A0 Applied for this session, but the setting could not be saved."})}h({kind:"note",tone:"ok",text:$?"\u2713 Verbose transcript ON \u2014 every tool call with its file path and full result.":"\u2713 Verbose transcript OFF \u2014 doc work shown by article; my bookkeeping collapsed to one line."});return}case"convert":{if(!$e(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:y,run:$}=au(f),R=zD(e,s);if(R.length===0){h({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Save some to Document360 first (/push), then /convert."});return}let b=lu(R,y);if(b.length===0){h({kind:"note",tone:"error",text:`No tracked articles under "${y}". (${R.length} are tracked overall.)`});return}let x=kp(b),P=3,N=`/convert${y?` --scope ${y}`:""} --run`,E=Ys(e,"light");if(!$){let _=Wb({files:cu(e,b),op:"convert",model:E.model}),F=y?`Scope: ${y} (${b.length} of ${R.length} tracked)
|
|
514
514
|
`:"",U=`
|
|
515
|
-
Model: ${E.model}${E.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;h({kind:"note",tone:"info",text:F+
|
|
516
|
-
`)+U}),re(N);return}Et.current=Date.now(),Ue(0),A(!0);let j=new AbortController;Le.current=j;let K=Date.now();he({verb:"Converting",total:
|
|
517
|
-
`):F+
|
|
518
|
-
`)}),Fo(K,_.results,_.totalCostUsd,!ie&&!_.aborted&&_.ok),ie&&re("/doctor")}}catch(_){h({kind:"note",tone:"error",text:`Convert run failed: ${_.message}`})}finally{Le.current=null,he(null),A(!1),M(_=>_+1)}return}case"write":{if(!$e(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let y=
|
|
515
|
+
Model: ${E.model}${E.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;h({kind:"note",tone:"info",text:F+du(x,_,P).join(`
|
|
516
|
+
`)+U}),re(N);return}Et.current=Date.now(),Ue(0),A(!0);let j=new AbortController;Le.current=j;let K=Date.now();he({verb:"Converting",total:x.length,done:0,active:[],rows:wo(x),tools:0,chars:0,lastAt:Date.now(),startedAt:K}),h({kind:"note",tone:"info",text:`Converting ${b.length} articles in ${x.length} batches (\u2264${P} agents at once) on ${E.model}\u2026 (esc to stop)`});try{for await(let _ of Vs({cwd:e,partitions:x,promptFor:uu,concurrency:P,profileName:s,allowProdWrites:hn.current,model:E.model,signal:j.signal}))if(_.type==="partition_status")_.status==="running"?he(F=>F&&{...F,active:[...F.active,_.label],rows:Ve(F.rows,_.label,"active"),lastAt:Date.now()}):he(F=>F&&{...F,active:F.active.filter(U=>U!==_.label),done:F.done+1,rows:Ve(F.rows,_.label,_.status==="done"?"done":"failed"),lastAt:Date.now()});else if(_.type==="partition_stalled"){let F=kr(_);he(U=>U&&F?{...U,stalledNote:F}:U)}else if(_.type==="partition_event")he(F=>{if(!F)return F;let U={...F,lastAt:Date.now()};return _.event.type==="tool"?U.tools=F.tools+1:_.event.type==="text"&&(U.chars=F.chars+_.event.delta.length),U});else if(_.type==="run_done"){zn(oe=>oe+_.totalCostUsd),Kn(oe=>oe+_.results.reduce((Ee,pe)=>Ee+pe.outputTokens,0));let F=_.aborted?"Stopped. ":"",U=t.kind==="api"?"api":"subscription",ie=Cn(_,"The conversion");h({kind:"note",tone:ie||_.aborted?"warn":_.ok?"ok":"warn",text:ie?ie.join(`
|
|
517
|
+
`):F+pu(_.results,x,U).join(`
|
|
518
|
+
`)}),Fo(K,_.results,_.totalCostUsd,!ie&&!_.aborted&&_.ok),ie&&re("/doctor")}}catch(_){h({kind:"note",tone:"error",text:`Convert run failed: ${_.message}`})}finally{Le.current=null,he(null),A(!1),M(_=>_+1)}return}case"write":{if(!$e(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let y=Bb(e);if(y.length===0){h({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:$,path:R,preview:b,concurrency:x,rewrite:P}=$s(f);if(!R&&!b&&!($e(e)?.appType??Ib(e))){h({kind:"note",tone:"warn",text:`\u26A0 No doc genre is set, so no doc-craft playbook would load \u2014 all ${y.length} articles would be written generically.
|
|
519
519
|
Pick the genre below (one keypress), then run /write again \u2014 it changes structure, titles and depth for every article.
|
|
520
|
-
Not blocked: /write <path> still authors a single article, and /write --preview costs nothing.`}),Z(
|
|
520
|
+
Not blocked: /write <path> still authors a single article, and /write --preview costs nothing.`}),Z(Wa.options.map(Q=>({cmd:Q.cmd,desc:Q.desc}))),No(Wa.title);return}let{docsDir:N,targets:E,reason:j,rewriting:K}=wa(e,y,{scope:$,path:R,rewrite:P});if(E.length===0){h({kind:"note",tone:"warn",text:j??"Nothing to write."});return}K&&h({kind:"note",tone:"warn",text:`--rewrite: regenerating ${E.length} already-written article${E.length===1?"":"s"} (overwrites them; git has your baseline).`});let _=kp(E),F=Cu(x),U=Ys(e,"standard"),ie=!!R;if(b&&!ie){let Q=Wb({files:Su(e,y,E),op:"write",model:U.model}),ke=$?`Scope: ${$} (${E.length} pending)
|
|
521
521
|
`:"",Oe=`
|
|
522
|
-
Model: ${U.model}${U.forced?" (forced)":" \u2014 authoring; /model to override"}`;h({kind:"note",tone:"info",text:ke+
|
|
523
|
-
`)+Oe}),re(`/write${
|
|
524
|
-
`):ke+
|
|
525
|
-
`)}),Fo(Ee,Q.results,Q.totalCostUsd,!Ft&&!Q.aborted&&Q.ok),Ft){re("/doctor");continue}let hh=Hm(Q);if(hh&&h({kind:"note",tone:"warn",text:hh}),!Q.aborted&&Q.ok)try{let Je=(pe.size>0?[...pe]:E).map($t=>`${N}/${$t}`);
|
|
526
|
-
`)})}if(!Q.aborted&&Q.ok){let Je
|
|
527
|
-
${y.map(
|
|
528
|
-
`)}`}),Z(y.map(
|
|
529
|
-
`)});return}if(y==="--baseline"){let b=
|
|
530
|
-
${
|
|
531
|
-
`)}`}),M(E=>E+1);return}if(y==="--compare"){h({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let b=await
|
|
532
|
-
`)});return}if(y){h({kind:"note",tone:"error",text:`Unknown option: ${y} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let
|
|
533
|
-
`)});let N=
|
|
534
|
-
`)});for(let ke of Q.closed)h({kind:"note",tone:"ok",text:ke});return}let j={aborted:!1,partitions:0,failed:0,notRun:0};if(E.kind==="partitioned"){let Q=await
|
|
535
|
-
\u26A0 ${oe} new ${oe===1?"issue":"issues"} appeared in the rewrites \u2014 recasting a sentence is where these come from.`:"";h({kind:"note",tone:K.some(Q=>Q.severity==="error")?"warn":"ok",text:K.length===0?`\u2713 Lint: all ${_.length} issue${_.length===1?"":"s"} resolved.`:[`\u2713 Lint: fixed ${ie} of ${_.length}.${Ee}`,"",...
|
|
536
|
-
`)}),mn(
|
|
537
|
-
`)}),
|
|
538
|
-
`)});return}case"status":{let y=
|
|
539
|
-
`)}),te.current=!0;return}case"retire":{let y=
|
|
540
|
-
`)}),te.current=!0;return}let
|
|
541
|
-
`)}),Xe(`/retire ${
|
|
542
|
-
It stays on Document360 with its history and comments intact. /push puts it back.`:`\u2713 "${
|
|
543
|
-
It stays on Document360 with its history and comments intact. /push puts it back.`}:{kind:"note",tone:"error",text:`\u2717 Could not retire "${
|
|
544
|
-
`)})
|
|
545
|
-
`)});return}
|
|
546
|
-
`)})
|
|
547
|
-
`)})
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
`)});
|
|
552
|
-
`)})
|
|
553
|
-
`)}),Xe(Hs(e));return}default:h({kind:"note",tone:"error",text:`Unknown command: /${c} \u2014 type /help.`})}},[e,r,s,Uo,Il,h,Qe,xe,lt,El,ih]),Yr=ne(u=>{let p=(u??f).trim();if(x(""),Ys(null),xo(0),p.startsWith("/")){te.current=!1,je.current=!1,Ne.current=null,_t(),No(null);let m=yl.current.includes(p);m&&(yl.current=[]),Z(T=>m?[]:hb(T,p))}if(!p||(pn(!1),At.current=!1,(Dr.current||Pe.current.length>0)&&h({kind:"user",text:p}),lh(p))||ah(p))return;pl.current.push(p);let c=wb(p,jp.current);if(p.startsWith("/"))h({kind:"user",text:p}),z(!0),Wo(c).finally(()=>z(!1));else if(dN(c)){h({kind:"user",text:p});let m=pN(c);if(!m)xe(c,{display:p,quietUser:!0});else{try{hN(e,{title:m,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}xe(`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${m}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${m}" and the article path(s) you wrote.`,{display:p,quietUser:!0})}}else{let m=dm(e,c);xe(m??c,{display:p})}},[f,lh,ah,Wo,xe]),ch=ne(u=>{if(u.length>1){if(u.includes("\x1B"))return;let p=fb(u);if(mb(p)){let c=gb(++ik.current,p);jp.current.set(c,p),P(c)}else P(p);return}P(u)},[P]),Bo=Math.max(10,rt-6),uh=wp(()=>sl(d.text,Bo),[d.text,Bo]),Ll=ne(u=>g(p=>({...p,pos:Math.max(0,Math.min(p.text.length,p.pos+u))})),[]),ui=ne(u=>g(p=>({...p,pos:bb(sl(p.text,Bo),p.pos,u)})),[Bo]),Kr=ne(u=>g(p=>({...p,pos:kb(sl(p.text,Bo),p.pos,u)})),[Bo]),mk=["\x1B[H","\x1B[1~","\x1BOH"],gk=["\x1B[F","\x1B[4~","\x1BOF"],dh=ne((u,p)=>p.leftArrow?(Ll(-1),!0):p.rightArrow?(Ll(1),!0):u&&mk.includes(u)?(Kr("start"),!0):u&&gk.includes(u)?(Kr("end"),!0):p.ctrl&&u==="a"?(Kr("start"),!0):p.ctrl&&u==="e"?(Kr("end"),!0):!1,[Ll,Kr]),ph=ne(()=>{if(Le.current){if(!Le.current.signal.aborted){let u=(Io?.verb??"work").toLowerCase(),p=Io?.unit??"article";h({kind:"note",tone:"warn",text:`\u238B Stopping the ${u} run (finishing in-flight ${p}s)\u2026`}),Le.current.abort()}return!0}return jr.current?!1:(jr.current=!0,h({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),Dt.current?.interrupt(),!0)},[Io]);return cD((u,p)=>{if(p.ctrl&&u==="c"){if(Ir.current!==null&&Date.now()-Ir.current<Xb){Ir.current=null,Dt.current?.close(),r();return}Ir.current=Date.now(),Up(!0),ml.current&&clearTimeout(ml.current),ml.current=setTimeout(()=>{Ir.current=null,Up(!1)},Xb),C?ph():f&&x("");return}if(Hr.current.awaySince!==null)try{let c=sb(Hr.current,Date.now(),uo(e));if(Hr.current=c.memory,Jp(null),c.kind==="delta"){h({kind:"note",tone:"info",text:ab(c.delta,c.awayMs)});let m=Mt(!1);m.kind==="recommend"&&tn(m.rec,{silent:!0})}else if(c.kind==="briefing"){h({kind:"note",tone:"info",text:`\u{1F4E5} ${Ws(c.delta)} arrived while you were away (${hp(c.awayMs)}).`});let m=Mt(!1);m.kind==="recommend"&&tn(m.rec)}}catch{}if(Cl.current=Date.now(),!D){if(C){if(p.escape){ph();return}if(p.return){let c=f.trim();if(!c)return;qn.current.push(c),fl([...qn.current]),x("");return}if(dh(u,p))return;if(p.upArrow){ui(-1);return}if(p.downArrow){ui(1);return}if(p.backspace||p.delete){$();return}u&&!p.ctrl&&!p.meta&&ch(u);return}if(fn){if(p.upArrow){Un(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Un(c=>c&&{...c,cursor:Math.min(Pt.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=en(u,Pt.length);c!==null&&Un(m=>m&&{...m,cursor:c});return}if(p.return){let c=Pt[fn.cursor];Un(null);let{lines:m,changed:T,effective:W}=ks(e,c.value??"default");for(let H of m)h({kind:"note",tone:H.startsWith("\u26A0")?"warn":H.startsWith("\u2713")?"ok":"info",text:H});T&&(Gp(H=>H+1),Dt.current?.setModel(W));return}if(u==="s"){let c=Pt[fn.cursor];Un(null),Dt.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){Un(null);return}return}if(jt){if(p.upArrow){Po(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Po(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=en(u,jt.rows.length);c!==null&&Po(m=>m&&{...m,cursor:c});return}if(p.return||u==="s"){let c=jt.rows[jt.cursor];Po(null),Nl(c.name,p.return===!0);return}if(p.escape){Po(null);return}return}if(Or){if(p.escape){Yn(null);return}if(p.leftArrow||p.tab&&p.shift){Yn(c=>c&&{tab:(c.tab-1+ct.length)%ct.length,scroll:0});return}if(p.rightArrow||p.tab){Yn(c=>c&&{tab:(c.tab+1)%ct.length,scroll:0});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=ct.length){Yn({tab:Number(u)-1,scroll:0});return}if(p.upArrow){Yn(c=>c&&{...c,scroll:Math.max(0,c.scroll-1)});return}if(p.downArrow){Yn(c=>{if(!c)return c;let m=(ct[c.tab]??ct[0]).rows.length;return{...c,scroll:Math.min(Math.max(0,m-1),c.scroll+1)}});return}return}if(It){if(p.upArrow){To(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){To(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=en(u,It.rows.length);c!==null&&To(m=>m&&{...m,cursor:c});return}if(p.return){let c=It.rows[It.cursor].name;if(To(null),!Ql(e,c).created){h({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}h({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${c}").`});let T=!1;try{let W=_n(c);T=!!W&&!(yo(W)&&!W.refreshToken)}catch{T=!1}h({kind:"note",tone:"info",text:T?`Next: sign in to ${c} and pick your project \u2014 you're already signed in here, so it'll be quick.`:`Next: sign in to Document360 (${c}) and pick your project.`}),re("/login"),M(W=>W+1);return}if(p.escape){To(null);return}return}if(Ye){if(p.upArrow){Ao(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Ao(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=en(u,Ye.rows.length);c!==null&&Ao(m=>m&&{...m,cursor:c});return}if(p.return){let c=Ye.rows[Ye.cursor],{profile:m,projectId:T}=Ye;Ao(null),ai(m,T,c);return}if(p.escape){Ao(null);return}return}if(tt){if(p.upArrow){Wn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Wn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=en(u,tt.rows.length);c!==null&&Wn(m=>m&&{...m,cursor:c});return}if(p.return){let c=tt.rows[tt.cursor],{profile:m}=tt;Wn(null),ci(m,c);return}if(p.escape){Wn(null);return}return}if(nt){if(p.upArrow){jo(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){jo(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u===" "){jo(c=>c&&{...c,rows:c.rows.map((m,T)=>T===c.cursor?{...m,checked:!m.checked}:m)});return}if(p.return){let c=nt.rows.filter(m=>m.checked).map(m=>m.path);if(jo(null),c.length===0){h({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}Hc(e,c),h({kind:"note",tone:"ok",text:`\u2713 Scoped to ${c.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let m of c)h({kind:"note",tone:"info",text:` ${m}`});h({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(p.escape){jo(null);return}return}if(at){if(p.upArrow){Hn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Hn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=en(u,at.rows.length);c!==null&&Hn(m=>m&&{...m,cursor:c});return}if(p.return){let c=at.rows[at.cursor],m=at.run;Hn(null),m(c.token);return}if(p.escape){Hn(null);return}return}if(wt){if(p.upArrow){Eo(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Eo(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=en(u,wt.rows.length);c!==null&&Eo(m=>m&&{...m,cursor:c});return}if(p.return){let c=wt.rows[wt.cursor],m=wt.conflicts;Eo(null),c.conflict?Il(c.paths[0]):c.kind==="article"?El(c.paths[0]):lt(c.paths,c.kind==="all"?m:0);return}if(p.escape){Eo(null);return}return}if(Lt){if(p.upArrow){Do(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Do(c=>c&&{...c,cursor:Math.min(c.rows.length,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=en(u,Lt.rows.length+1);c!==null&&Do(m=>m&&{...m,cursor:c});return}if(p.return){let{cursor:c,rows:m,opts:T}=Lt;Do(null);let W=c===0?m:[m[c-1]];fk(W,T);return}if(p.escape){Do(null),h({kind:"note",tone:"info",text:"Left as drafts \u2014 nothing changed. /publish when they have been signed off."});return}return}if(yt){let{rows:c}=yt;if(p.upArrow){Zt(m=>m&&{...m,cursor:Math.max(0,m.cursor-1)});return}if(p.downArrow){Zt(m=>m&&{...m,cursor:Math.min(c.length-1,m.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let m=cp(Op.current,Number(u),c.length-1);Op.current=m.memory,m.index!==null&&Zt(T=>T&&{...T,cursor:m.index+1});return}if(u==="a"||u==="A"){Zt(m=>m&&{...m,cursor:0});return}if(p.return){let m=c[yt.cursor],{groups:T,resolve:W,report:H}=yt;if(Zt(null),m.kind==="all"){Al(T,{resolve:W,report:H});return}Mo(Pa(m.group,{width:Ge()})),Nr({group:m.group,cursor:0,fromList:!0,resolve:W,rest:T.filter(y=>y.articleId!==m.group.articleId),report:H});return}if(p.escape){Zt(null),re("/comments");return}return}if(ze){let c=()=>{let{rest:m,group:T,fromList:W,resolve:H,report:y}=ze;if(Nr(null),!W||!y){re("/comments");return}let k=[T,...m].sort((R,b)=>R.category.localeCompare(b.category)||R.title.localeCompare(b.title));Zt({cursor:0,rows:Ta(k),groups:k,resolve:H,report:y})};if(p.upArrow||p.downArrow){Nr(m=>m&&{...m,cursor:m.cursor===0?1:0});return}if(u==="y"||u==="Y"||p.return&&ze.cursor===0){let{group:m,resolve:T,rest:W,report:H}=ze;Nr(null),Al([m],{resolve:T,rest:W,...H?{report:H}:{}});return}if(u==="b"||u==="B"||p.escape||p.return){c();return}return}if(Ot){if(p.upArrow){Bn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Bn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=en(u,Ot.rows.length);c!==null&&Bn(m=>m&&{...m,cursor:c});return}if(p.return){let c=Ot.rows[Ot.cursor];Bn(null),c.action==="capture"?Vr(c.ids,{runLine:c.kind==="all"?["/screenshot capture --all","/capture --all"]:void 0}):c.action==="annotate"?ii(c.ids,{verifiedBefore:new Set(_e(e).filter(m=>m.state==="verified").map(m=>m.id))}):c.kind==="shot"?sh(c.ids[0]):rh(c.ids,{setup:!0,runLine:c.kind==="all"?["/screenshot author --all","/screenshot --all"]:void 0});return}if(p.escape){Bn(null);return}return}if(bt){if(p.escape){Gn(null);return}if(p.upArrow){Gn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Gn(c=>c&&{...c,cursor:Math.min(Math.max(0,ni.length-1),c.cursor+1)});return}if(p.return){let c=ni[bt.cursor];if(c){Gn(null);try{h({kind:"preview",name:Hs(c),text:Jb(al(yp(e,c),"utf8"))})}catch(m){h({kind:"note",tone:"error",text:`Could not read ${c}: ${m.message}`})}}return}if(p.backspace||p.delete){Gn(c=>c&&{...c,query:c.query.slice(0,-1),cursor:0});return}if(u&&!p.ctrl&&!p.meta&&u.length===1){Gn(c=>c&&{...c,query:c.query+u,cursor:0});return}return}if(kt){if(p.escape){Vn(null);return}if(p.upArrow){Vn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Vn(c=>c&&{...c,cursor:Math.min(Math.max(0,oi.length-1),c.cursor+1)});return}if(p.return){let c=oi[kt.cursor];if(c){Vn(null),Qe(c.uuid),Qt.current={uuid:c.uuid,firstPrompt:c.firstPrompt,titleFired:!0},Fn(c.name),bp(c.uuid),So.current=[],ot.current={printed:[],armed:[],printedAt:Oo.current};let m=up(e,c.uuid);for(let T of m)h(T);h({kind:"note",tone:"ok",text:m.length?`Resumed "${c.name}" \u2014 restored ${m.length} message(s); continue where you left off.`:`Resumed "${c.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(p.backspace||p.delete){Vn(c=>c&&{...c,query:c.query.slice(0,-1),cursor:0});return}if(u&&!p.ctrl&&!p.meta&&u.length===1){Vn(c=>c&&{...c,query:c.query+u,cursor:0});return}return}if(p.tab&&!f&&de){x(de),_t();return}if(!f&&fe.length>0&&!At.current&&u&&/^[1-9]$/.test(u)){let c=fe[Number(u)-1];if(c){x(On(c));return}}if(!f&&fe.length===0&&!At.current&&ot.current.armed.length>0&&u&&/^[1-9]$/.test(u)){let c=ot.current.armed[Number(u)-1];if(c){x(c);return}}if(!f&&(Zs||Wr)&&u==="c"&&!p.ctrl&&!p.meta&&!p.return&&!p.tab){let c=Zs!=null;ip(Zs??Wr).then(T=>{h({kind:"note",tone:T?"ok":"warn",text:T?c?"\u2713 Copied the feedback to your clipboard \u2014 send it to the d360-writer team (Teams / Slack / email).":"\u2713 Copied the prompt to your clipboard \u2014 paste it into your repo's coding agent.":c?"Couldn't reach your clipboard \u2014 select the feedback above and copy it manually.":"Couldn't reach your clipboard \u2014 select the prompt above and copy it manually."}),T&&c&&Rl(null),T&&!c&&Vp(!0)});return}if(!dh(u,p)){if(eh){if(p.upArrow){xo(c=>Math.max(0,c-1));return}if(p.downArrow){xo(c=>Math.min(on.length-1,c+1));return}if(p.tab){x("/"+(on[dl]?.name??"")+" "),xo(0);return}if(p.return){let c=on[dl];if(c){let m=f.trim().slice(1).split(/\s+/).slice(1).join(" ");if(Km(c.usage)&&!m){x("/"+c.name+" "),xo(0);return}Yr("/"+c.name+(m?" "+m:""));return}}}else{if(!f&&fe.length>0&&!At.current&&(p.upArrow||p.downArrow)){if(p.downArrow){Ar(c=>c===null?0:Math.min(fe.length-1,c+1));return}if(Co!==null){Ar(c=>c===null||c===0?null:c-1);return}}if(p.upArrow){if(f!==""&&Ro===null){ui(-1);return}let c=pl.current;if(!c.length)return;let m=Ro===null?c.length-1:Math.max(0,Ro-1);Ys(m),x(c[m]??"");return}if(p.downArrow){if(f!==""&&Ro===null){ui(1);return}let c=pl.current;if(Ro===null)return;let m=Ro+1;m>=c.length?(Ys(null),x("")):(Ys(m),x(c[m]??""));return}}if(p.return){if(Co!==null&&!f&&fe[Co]){let c=On(fe[Co]);Ar(null),Yr(c);return}Yr();return}if(p.backspace||p.delete){$();return}if(p.escape){x(""),xo(0),_t(),Z([]),No(null),Ar(null),te.current=!0;return}u&&!p.ctrl&&!p.meta&&ch(u)}}}),it(()=>{if(C||D)return;let u=qn.current.shift();u!==void 0&&(fl([...qn.current]),Yr(u))},[C,D,Yr]),ue(De,{flexDirection:"column",width:rt,children:[Tl!==null&&ue(De,{marginTop:1,flexDirection:"column",children:[Tl.truncated&&V(Y,{dimColor:!0,children:"\u2026"}),V(Y,{children:Tl.text})]}),C&&Io?V(PN,{p:Io}):null,Wp?V(CN,{text:Wp}):C&&!Io?V(RN,{startTime:Et.current,chars:Se}):null,V(De,{borderStyle:"round",borderColor:Zp.prod?"yellow":ae,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:f?uh.map((u,p)=>{let c=d.text.slice(u.start,u.end),m=p===il(uh,d.pos),T=Math.min(d.pos,u.end)-u.start;return ue(Y,{children:[V(Y,{color:ae,children:p===0?"> ":" "}),m?ue(Cr,{children:[c.slice(0,T),V(Rr,{ch:c[T]??" "}),c.slice(T+1)]}):c||" "]},`${p}-${u.start}`)}):ue(Y,{children:[V(Y,{color:ae,children:"> "}),_r?V(Rr,{ch:" "}):Ce&&!C?ue(Cr,{children:[V(Rr,{ch:Ce[0],dim:!0}),V(Y,{color:"gray",children:Ce.slice(1)})]}):de&&!C?ue(Cr,{children:[V(Rr,{ch:de[0],dim:!0}),V(Y,{color:"gray",children:de.slice(1)}),V(Y,{dimColor:!0,children:" (tab)"})]}):(Sl.isSetup||!Tr)&&!C?ue(Cr,{children:[V(Rr,{ch:Sl.text[0],dim:!0}),V(Y,{color:"gray",children:Sl.text.slice(1)})]}):V(Rr,{ch:" "})]})}),Fp.length>0&&V(De,{flexDirection:"column",paddingX:1,children:Fp.map((u,p)=>V(Y,{color:"gray",children:`\u29D7 queued: ${u}`},`${p}-${u.slice(0,24)}`))}),Or?V(cb,{tab:Or.tab,scroll:Or.scroll,rows:pk,width:rt,version:o,engineVersion:Zb}):fn?ue(De,{flexDirection:"column",paddingX:1,children:[V(Y,{color:ae,bold:!0,children:"Select model"}),V(Y,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),Pt.map((u,p)=>ue(Y,{color:p===fn.cursor?ae:void 0,children:[p===fn.cursor?"\u276F ":" ",`${p+1}. ${u.label}${p===fn.current?" \u2714":""}`.padEnd(16),V(Y,{color:"gray",children:` ${u.desc}`})]},u.label)),V(Y,{dimColor:!0,children:ft({verb:"set as default",rows:Pt.length,extra:["s this session only"]})})]}):jt?ue(De,{flexDirection:"column",paddingX:1,children:[V(Y,{color:ae,bold:!0,children:"Switch connection profile"}),V(dn,{rows:jt.rows,cursor:jt.cursor,cap:Gt,render:(u,p,c)=>ue(Y,{color:c?ae:void 0,children:[c?"\u276F ":" ",`${p+1}. ${u.name}${p===jt.current?" \u2714":""}`.padEnd(20),V(Y,{color:"gray",children:` ${u.env} \xB7 ${u.who??"not signed in"}`}),u.prod?V(Y,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},u.name)}),V(Y,{dimColor:!0,children:ft({verb:"switch (saved as default)",rows:jt.rows.length,extra:["s this session only"]})})]}):It?ue(De,{flexDirection:"column",paddingX:1,children:[V(Y,{color:ae,bold:!0,children:"Pick your Document360 environment"}),V(dn,{rows:It.rows,cursor:It.cursor,cap:Gt,render:(u,p,c)=>ue(Y,{color:c?ae:void 0,children:[c?"\u276F ":" ",`${p+1}. ${u.name}`.padEnd(16),V(Y,{color:"gray",children:` ${u.apiUrl}`}),u.note?V(Y,{color:"yellow",children:` \u26A0 ${u.note}`}):null]},u.name)}),V(Y,{dimColor:!0,children:ft({verb:"use it",rows:It.rows.length})})]}):Ye?ue(De,{flexDirection:"column",paddingX:1,children:[V(Y,{color:ae,bold:!0,children:"Switch workspace"}),V(Y,{dimColor:!0,children:`environment ${Ye.environment} \xB7 project ${Ye.projectName??`${Ye.projectId.slice(0,8)}\u2026`}`}),V(dn,{rows:Ye.rows,cursor:Ye.cursor,cap:Gt,render:(u,p,c)=>ue(Y,{color:c?ae:void 0,children:[c?"\u276F ":" ",`${p+1}. ${u.name}${p===Ye.current?" \u2714":""}`.padEnd(30),V(Y,{color:"gray",children:u.type?` ${u.type}`:""})]},u.id)}),V(Y,{dimColor:!0,children:ft({verb:"switch",rows:Ye.rows.length})})]}):tt?ue(De,{flexDirection:"column",paddingX:1,children:[V(Y,{color:ae,bold:!0,children:"Choose project"}),V(Y,{dimColor:!0,children:`environment ${tt.environment}`}),V(dn,{rows:tt.rows,cursor:tt.cursor,cap:Gt,render:(u,p,c)=>ue(Y,{color:c?ae:void 0,children:[c?"\u276F ":" ",`${p+1}. ${u.name}${p===tt.current?" \u2714":""}`.padEnd(30),V(Y,{color:"gray",children:u.sub?` ${u.sub}`:""})]},u.id)}),V(Y,{dimColor:!0,children:ft({verb:"switch",rows:tt.rows.length})})]}):nt?(()=>{let p=Math.min(Math.max(0,nt.cursor-Math.floor(7)),Math.max(0,nt.rows.length-14)),c=nt.rows.slice(p,p+14),m=nt.rows.filter(T=>T.checked).length;return ue(De,{flexDirection:"column",paddingX:1,children:[V(Y,{color:ae,bold:!0,children:`Which folders back the user docs? (${m} selected of ${nt.rows.length})`}),p>0?V(Y,{dimColor:!0,children:` \u2191 ${p} more`}):null,c.map((T,W)=>{let H=p+W;return ue(Y,{color:H===nt.cursor?ae:void 0,children:[H===nt.cursor?"\u276F ":" ",T.checked?"\u25C9 ":"\u25CB ",T.path.padEnd(Math.min(48,rt-34)),V(Y,{color:"gray",children:ta(T)})]},T.path)}),p+14<nt.rows.length?V(Y,{dimColor:!0,children:` \u2193 ${nt.rows.length-p-14} more`}):null,V(Y,{dimColor:!0,children:ft({verb:"save",multi:!0})})]})})():at?ue(De,{flexDirection:"column",paddingX:1,children:[V(Y,{color:ae,bold:!0,children:at.title??"Which category? (pick one to scope to)"}),V(dn,{rows:at.rows,cursor:at.cursor,cap:Gt,render:(u,p,c)=>ue(Y,{color:c?ae:void 0,children:[c?"\u276F ":" ",`${`${p+1}.`.padEnd(3)} ${u.label} (${u.count})`.padEnd(Math.min(44,Math.max(20,rt-24))),V(Y,{color:"gray",children:` ${u.token}`})]},u.token)}),V(Y,{dimColor:!0,children:ft({verb:"choose it",rows:at.rows.length})})]}):wt?ue(De,{flexDirection:"column",paddingX:1,children:[V(Y,{color:ae,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),V(dn,{rows:wt.rows,cursor:wt.cursor,cap:Gt,render:(u,p,c)=>ue(Y,{color:c?ae:void 0,bold:u.kind==="category"&&!c,children:[c?"\u276F ":" ",`${u.indent?" ":" "}${`${p+1}.`.padEnd(3)} ${u.label}`.padEnd(Math.min(56,rt-24)),u.note?V(Y,{color:"gray",children:` ${u.note}`}):null]},`${u.kind}:${u.paths.join(",")}`)}),V(Y,{dimColor:!0,children:ft({verb:"push as drafts",rows:wt.rows.length})})]}):Lt?ue(De,{flexDirection:"column",paddingX:1,children:[V(Y,{color:ae,bold:!0,children:"Publish live to your readers \u2014 this is what they will see:"}),V(dn,{rows:[{path:"",articleId:"",label:`Publish all ${Lt.rows.length} live`,version:void 0},...Lt.rows],cursor:Lt.cursor,cap:Gt,render:(u,p,c)=>ue(Y,{color:c?ae:void 0,bold:p===0&&!c,children:[c?"\u276F ":" ",` ${`${p+1}.`.padEnd(3)} ${u.label}`.padEnd(Math.min(56,rt-24)),p>0?V(Y,{color:"gray",children:` ${u.version?`draft v${u.version} \u2192 live`:"draft \u2192 live"}`}):null]},`${p}:${u.path||"all"}`)}),V(Y,{dimColor:!0,children:ft({verb:"publish live",cancel:"leave as drafts",rows:Lt.rows.length+1})})]}):yt?ue(De,{flexDirection:"column",paddingX:1,children:[V(Y,{color:ae,bold:!0,children:"Which comments do you want to look at?"}),V(dn,{rows:yt.rows,cursor:yt.cursor,cap:Gt,render:(u,p,c)=>ue(Y,{color:c?ae:void 0,bold:u.kind==="all"&&!c,children:[c?"\u276F ":" ",`${(u.kind==="all"?"":`${u.n}.`).padEnd(4)}${u.label}`.padEnd(Math.min(56,Math.max(20,rt-24))),u.kind==="article"?V(Y,{color:"gray",children:u.note}):null]},u.kind==="all"?"all":u.group.articleId)}),V(Y,{dimColor:!0,children:ft({verb:"open it",cancel:"close",rows:yt.rows.length-1})}),yt.resolve?V(Y,{dimColor:!0,children:"--resolve is on: threads you answer will be closed as well as replied to"}):null]}):ze?ue(De,{flexDirection:"column",paddingX:1,children:[V(Y,{color:ae,bold:!0,children:`${ze.group.title} \u2014 ${ze.group.threads.length} comment${ze.group.threads.length===1?"":"s"}`}),ue(Y,{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(Y,{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"]}),V(Y,{dimColor:!0,children:ft({verb:"open it",cancel:"go back",extra:["y answer"]})})]}):Ot?ue(De,{flexDirection:"column",paddingX:1,children:[V(Y,{color:ae,bold:!0,children:Ot.title}),(()=>{let{rows:u,cursor:p}=Ot,c=Ja(u.length,p,Gt),m=c.start,T=u.slice(c.start,c.end),W=`${u.length}.`.length+1,H=Qf(u,Math.max(20,rt-4-W));return ue(Cr,{children:[m>0?V(Y,{color:"gray",children:` \u2026 ${m} more above`}):null,T.map((y,k)=>{let R=m+k,b=R===p,v=H[R];return ue(Y,{color:b?ae:void 0,bold:(y.kind==="all"||y.kind==="category")&&!b,children:[b?"\u276F ":" ",`${R+1}.`.padEnd(W),v.head,v.note?V(Y,{color:"gray",children:v.note}):null]},`${y.action}:${y.kind}:${y.ids.join(",")}`)}),c.below>0?V(Y,{color:"gray",children:` \u2026 ${c.below} more below`}):null]})})(),V(Y,{dimColor:!0,children:ft({verb:"run it",rows:Ot.rows.length})})]}):bt?ue(De,{flexDirection:"column",paddingX:1,children:[V(Y,{color:ae,bold:!0,children:`Preview article${bt.query?` \u2014 filter: ${bt.query}`:" (type to filter)"}`}),ni.length===0?V(Y,{color:"gray",children:"no articles match"}):ni.map((u,p)=>ue(Y,{color:p===bt.cursor?ae:void 0,children:[p===bt.cursor?"\u276F ":" ",u]},u)),V(Y,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):kt?ue(De,{flexDirection:"column",paddingX:1,children:[V(Y,{color:ae,bold:!0,children:`Resume session${kt.query?` \u2014 filter: ${kt.query}`:" (type to filter)"}`}),oi.length===0?V(Y,{color:"gray",children:"no sessions match"}):oi.map((u,p)=>ue(Y,{color:p===kt.cursor?ae:void 0,children:[p===kt.cursor?"\u276F ":" ",u.name.slice(0,28).padEnd(30),V(Y,{color:p===kt.cursor?ae:"gray",children:u.firstPrompt.slice(0,Math.max(10,rt-40))})]},u.uuid)),V(Y,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):eh?ue(De,{flexDirection:"column",children:[Qn>0?V(Y,{dimColor:!0,children:` \u22EF ${Qn} more above`}):null,Pl.map((u,p)=>{let c=Qn+p,m=u.name==="model"&&gl?`${u.desc} (currently ${gl})`:u.desc,T=Math.max(20,rt-4),W=u.usage.length>T?`${u.usage.slice(0,T-1)}\u2026`:u.usage,H=T-Math.max(W.length,22)-1,y=H<=1?"":m.length>H?`${m.slice(0,H-1)}\u2026`:m;return ue(Y,{color:c===ti?ae:void 0,children:[c===ti?"\u276F ":" ",W.padEnd(22)," ",V(Y,{color:c===ti?ae:"gray",children:y})]},u.name)}),Qn+Pl.length<on.length?V(Y,{dimColor:!0,children:` \u22EF ${on.length-Qn-Pl.length} more below`}):null,V(Y,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!C&&!f&&fe.length>0?ue(De,{flexDirection:"column",paddingX:1,children:[Mp?V(Y,{color:ae,children:Mp}):null,V(dn,{rows:fe,cursor:Co??0,cap:Gt,render:(u,p)=>{let c=p===Co,m=On(u),T=m.slice(0,Math.max(20,rt-7)),W=rt-T.length-9,H=W>=12?(pb(u)??Vm(m)).slice(0,W):"";return ue(Y,{color:c?ae:void 0,children:[c?"\u276F ":" ",V(Y,{color:ae,children:p+1})," ",T,H?V(Y,{color:c?ae:void 0,dimColor:!c,children:` \u2014 ${H}`}):null]},m)}}),V(Y,{dimColor:!0,children:`\u2191\u2193 choose \xB7 enter run \xB7 1-${fe.length} fill \xB7 esc cancel`})]}):V(De,{paddingX:1,children:ue(Y,{color:"gray",children:[Zp.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${gl??"model n/a"}${t.kind==="api"?Mr>0?` \xB7 session ${St(Mr)}`:"":Hp>0?` \xB7 ${ar(Hp)}`:""} \xB7 \u2191 history \xB7 ${ak?"press ctrl+c again to exit":"ctrl+c twice to exit"}`]})})]})}se();import{jsx as DN}from"react/jsx-runtime";async function tk(e=process.cwd(),t="auto",n,o="0.0.0"){let r=EN(t);r.kind==="none"&&(console.error(""),console.error(O("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${J("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${J("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=AN(DN(ek,{cwd:e,auth:r,profileName:n,version:o}),{exitOnCtrlC:!1});await s(),process.stdout.write(`
|
|
554
|
-
`),process.exit(0)}se();import{writeCrashLog as Ap,isBenignTransportError as NN}from"document360-engine";var nk=!1;function jN(e=process.stdout){return e.destroyed===!0||e.writable===!1}function Ep(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function ok(e){if(nk)return;nk=!0;let t=(n,o)=>{if(NN(o)){Ap({kind:n,level:"transport",message:Ep(o),stack:o instanceof Error?o.stack:void 0,detail:e}),jN()&&(Ap({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=Ap({kind:n,level:"fatal",message:Ep(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
|
|
522
|
+
Model: ${U.model}${U.forced?" (forced)":" \u2014 authoring; /model to override"}`;h({kind:"note",tone:"info",text:ke+Tu(_,Q,F).join(`
|
|
523
|
+
`)+Oe}),re(`/write${$?` --scope ${$}`:""}`);return}Et.current=Date.now(),Ue(0),A(!0);let oe=new AbortController;Le.current=oe;let Ee=Date.now();he({verb:"Writing",total:_.length,done:0,active:[],rows:wo(_),tools:0,chars:0,lastAt:Date.now(),startedAt:Ee}),h({kind:"note",tone:"info",text:`Writing ${E.length} article${E.length===1?"":"s"} in ${_.length} batch${_.length===1?"":"es"} (\u2264${F} agents at once) on ${U.model}${U.forced?" (forced)":""}\u2026 (esc to stop)`});let pe=new Set;try{for await(let Q of Vs({cwd:e,partitions:_,promptFor:ke=>Pu(ke,N,{rewrite:K||ie}),concurrency:F,profileName:s,allowProdWrites:hn.current,model:U.model,signal:oe.signal}))if(Q.type==="partition_status")Q.status==="running"?he(ke=>ke&&{...ke,active:[...ke.active,Q.label],rows:Ve(ke.rows,Q.label,"active"),lastAt:Date.now()}):he(ke=>ke&&{...ke,active:ke.active.filter(Oe=>Oe!==Q.label),done:ke.done+1,rows:Ve(ke.rows,Q.label,Q.status==="done"?"done":"failed"),lastAt:Date.now()});else if(Q.type==="partition_stalled"){let ke=kr(Q);he(Oe=>Oe&&ke?{...Oe,stalledNote:ke}:Oe)}else if(Q.type==="partition_event"){let ke=null;if(Q.event.type==="tool"){let Oe=fp(Q.event.name,Q.event.input,_[Q.index]?.paths??[]);Oe&&!pe.has(Oe)&&(pe.add(Oe),ke=Q.label)}he(Oe=>{if(!Oe)return Oe;let Ft={...Oe,lastAt:Date.now()};return Q.event.type==="tool"?Ft.tools=Oe.tools+1:Q.event.type==="text"&&(Ft.chars=Oe.chars+Q.event.delta.length),ke&&(Ft.rows=sl(Ft.rows,ke)),Ft})}else if(Q.type==="run_done"){zn(Je=>Je+Q.totalCostUsd),Kn(Je=>Je+Q.results.reduce(($t,eo)=>$t+eo.outputTokens,0));let ke=Q.aborted?"Stopped. ":"",Oe=t.kind==="api"?"api":"subscription",Ft=Cn(Q,"The write");if(h({kind:"note",tone:Ft||Q.aborted?"warn":Q.ok?"ok":"warn",text:Ft?Ft.join(`
|
|
524
|
+
`):ke+Au(Q.results,_,Oe,$??R).join(`
|
|
525
|
+
`)}),Fo(Ee,Q.results,Q.totalCostUsd,!Ft&&!Q.aborted&&Q.ok),Ft){re("/doctor");continue}let hh=Hm(Q);if(hh&&h({kind:"note",tone:"warn",text:hh}),!Q.aborted&&Q.ok)try{let Je=(pe.size>0?[...pe]:E).map($t=>`${N}/${$t}`);Cr(e,Je,{writtenCap:nN,reviewedCap:0,checkedCap:0})}catch{}let Zn=Q.aborted?[]:dr(e,N,E),fh=Eu(Zn);fh&&h({kind:"note",tone:"warn",text:fh});let Ho=Q.aborted||f.includes("--skip-style")?null:Du(Zn);if(Ho){let Je=Ho.errors.length,$t=await ii({partitions:Ho.partitions,promptFor:Ho.promptFor,concurrency:lr,verb:"Fixing",doneNoun:"fixed",headline:`${Je} style error${Je===1?"":"s"} in ${Ho.articles} of the new article${Ho.articles===1?"":"s"} \u2014 fixing now, one pass`});if($t.covered.length>0)try{Cr(e,$t.covered,st("lint"))}catch{}Zn=dr(e,N,E);let eo=Nu(Je,Zn);h({kind:"note",tone:eo[0].startsWith("\u2713")?"ok":"warn",text:eo.join(`
|
|
526
|
+
`)})}if(!Q.aborted&&Q.ok){let Je=$??R??"",$t=Je?` ${Je}`:"",eo=Zn.some(Go=>Go.severity==="error");{let Go=$p(_,Q.results);mn(`/write${$?` --scope ${$}`:""}${f.includes("--rewrite")?" --rewrite":""}`,{aborted:Q.aborted,partitions:_.length,failed:Go.failed.length,notRun:Go.notRun.length,leftBehind:Zn.filter(bk=>bk.severity==="error").length,...Q.blocked?{blocked:Q.blocked}:{},...Q.allEmpty?{allEmpty:!0}:{},...Q.bailedEmpty?{bailedEmpty:!0}:{}})}let mh=Je?"/push":"/push --all",yk=Je?`/screenshot author ${Je}`:"/screenshot author --all";Ae(eo?`Written, but ${Zn.filter(Go=>Go.severity==="error").length} style error(s) are still unfixed. /lint${$t} --blocked --fix retries them, then /review${$t} --fix for editorial quality, then ${mh}.`:`Written. I\u2019d run /review${$t} --fix next \u2014 editorial review that applies its fixes \u2014 then ${mh} saves them to Document360 as drafts (add ${yk} first if you want images).`,{kind:"cmd",cmd:eo?`/lint${$t} --blocked --fix`:`/review${$t} --fix`,reason:""})}}}catch(Q){h({kind:"note",tone:"error",text:`Write run failed: ${Q.message}`})}finally{Le.current=null,he(null),A(!1),M(Q=>Q+1)}return}case"draft":{if(!$e(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:y,looseDocs:$}=Iu(e);if(y.length===0&&$===0){h({kind:"note",tone:"info",text:Ou});return}let R=f.join(" ").trim();if(!R&&y.length>1){h({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
|
|
527
|
+
${y.map(P=>` \u2022 ${P.name} (${P.docCount} doc${P.docCount===1?"":"s"})`).join(`
|
|
528
|
+
`)}`}),Z(y.map(P=>`/draft ${P.name}`));return}let b="",x;if(R){let P=Lu(y,R);P?b=P:x=R}else b=y[0]?.name??"";await xe(ya(b,x),{display:R?`/draft ${R}`:"/draft",quietUser:!0});return}case"pull":{if(!Xn(u.trim()))return;let y=f.find($=>$.startsWith("--"));try{if(y==="--status"){h({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let b=Date.now(),x=await dl({cwd:e,profileName:s});h({kind:"note",tone:"info",text:oa(x,Date.now()-b).join(`
|
|
529
|
+
`)});return}if(y==="--baseline"){let b=f.find(E=>!E.startsWith("--")),x=b?b.replace(/\\/g,"/"):void 0;h({kind:"note",tone:"info",text:x?`Setting the sync baseline for ${x}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let P=await BD({cwd:e,profileName:s,relPaths:x?[x]:void 0}),N=x?{rebaselined:[],skipped:[]}:await HD({cwd:e,profileName:s});if(P.baselined.length===0&&P.skipped.length===0&&N.rebaselined.length===0){h({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}P.baselined.length>0&&h({kind:"note",tone:"ok",text:`\u2713 Recorded ${P.baselined.length} article${P.baselined.length===1?"":"s"} as matching Document360 \u2014 they read in-sync until either side changes.`}),N.rebaselined.length>0&&h({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${N.rebaselined.length} article${N.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),P.skipped.length>0&&h({kind:"note",tone:"warn",text:`${P.skipped.length} skipped:
|
|
530
|
+
${P.skipped.map(E=>` - ${E.path} (${E.reason})`).join(`
|
|
531
|
+
`)}`}),M(E=>E+1);return}if(y==="--compare"){h({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let b=await _D({cwd:e,profileName:s}),x=b.onlyInLegacy.length===0&&b.onlyInManifest.length===0&&b.mappedMissingFromManifest.length===0,P=[`Legacy listing: ${b.legacyCount} \xB7 Manifest: ${b.manifestCount} \xB7 in both: ${b.inBoth}`];x?P.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(b.mappedMissingFromManifest.length&&P.push(`\u2717 ${b.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${b.mappedMissingFromManifest.slice(0,5).join(", ")}`),b.onlyInLegacy.length&&P.push(`\u26A0 ${b.onlyInLegacy.length} only in the legacy listing: ${b.onlyInLegacy.slice(0,5).join(", ")}`),b.onlyInManifest.length&&P.push(`\u26A0 ${b.onlyInManifest.length} only in the manifest: ${b.onlyInManifest.slice(0,5).join(", ")}`),P.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),h({kind:"note",tone:x?"ok":"warn",text:P.join(`
|
|
532
|
+
`)});return}if(y){h({kind:"note",tone:"error",text:`Unknown option: ${y} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let $=f[0];if($){let b=$.replace(/\\/g,"/"),x;try{let P=await Ob({cwd:e,profileName:s,relPath:b});x={plan:P,mode:P.overwritesLocalChanges?"conflict":"pull"}}catch(P){if(!_b(P))throw P;x={mode:"local-only",path:b,title:Mb(e,b)}}Te.current=[x],Nt.current=[],Jt.current=[],Uo();return}h({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let R=await Xc({cwd:e,profileName:s});for(let b of Qc(R))h({kind:"note",tone:b.tone,text:b.text});M(b=>b+1)}catch($){h({kind:"note",tone:"error",text:`Pull failed: ${$.message}`})}return}case"scope":{if(!$e(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let y=GD(e);if(y.length===0){h({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.'});return}jo({cursor:0,rows:y.map($=>({...$,checked:$.recommended}))});return}case"audit":{if(f[0]==="--auto"){let $=$e(e);if(!$){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let R=f[1]!=="off";Nb({...$,autoAudit:R},e),h({kind:"note",tone:"ok",text:R?"\u2713 Auto-audit ON \u2014 when you launch with code changes since the last audit, I\u2019ll run /audit automatically. (/audit --auto off to disable.)":"\u2713 Auto-audit OFF \u2014 I\u2019ll just nudge you to run /audit when code changed."});return}if(!Xn(u.trim()))return;let y=await ps({cwd:e,profileName:s});if(y.kind==="audit-blocked"){Ae(y.note,{kind:"cmd",cmd:y.lead.cmd,reason:y.lead.reason},"warn");return}if(y.kind==="forward-to-agent"&&y.prompt){let $=await xe(y.prompt,{display:y.display,quietUser:!0}),R=ta(e,s);if(R){Ae(R.note,{kind:"cmd",cmd:or.cmd,reason:or.reason},"warn"),M(b=>b+1);return}$.producedNothing||(_s(e,s),M(b=>b+1))}return}case"lint":case"check":{let y=ln(c);y&&h({kind:"note",tone:"info",text:`\u2192 ${y}`});let $=f.find(P=>!P.startsWith("--")),R=$?` ${$}`:"",b=Rr({cwd:e,scope:$}),x=un(b,f);if(f.includes("--fix")){let P=cr(e,f,b);P.lines.length>0&&h({kind:"note",tone:"ok",text:P.lines.join(`
|
|
533
|
+
`)});let N=P.fixed>0?Rr({cwd:e,scope:$}):b,E=bu(e,f,N);if(!E){let Q=ku(e,f,N);h({kind:"note",tone:"ok",text:Q.lines.join(`
|
|
534
|
+
`)});for(let ke of Q.closed)h({kind:"note",tone:"ok",text:ke});return}let j={aborted:!1,partitions:0,failed:0,notRun:0};if(E.kind==="partitioned"){let Q=await ii({partitions:E.partitions,promptFor:E.promptFor,concurrency:lr,verb:"Fixing",doneNoun:"fixed",headline:`Fixing ${E.findings} issue${E.findings===1?"":"s"} across ${E.articles} article${E.articles===1?"":"s"} in ${E.partitions.length} batches (\u2264${lr} at once)`,calibrateAs:"/lint"});if(j=Q.outcome,Q.covered.length>0)try{Cr(e,Q.covered,st("lint"))}catch{}if(Q.aborted){let ke=gs({cwd:e,after:un(Rr({cwd:e,scope:$}).filter(Oe=>!Oe.baselined),f),scope:$,aborted:!0,blocked:cn(f)});Ae(ke.text,{kind:"cmd",cmd:ke.cmd,reason:""},"warn");return}}else{h({kind:"note",tone:"info",text:`Fixing ${E.findings} doc issue${E.findings===1?"":"s"}\u2026`});let Q=tN(e,$);await xe(E.prompt,{display:E.display,quietUser:!0});try{Cr(e,Q,st("lint"))}catch{}}let K=un(Rr({cwd:e,scope:$}).filter(Q=>!Q.baselined),f),_=un(N.filter(Q=>!Q.baselined),f),F=new Set(K.map(Q=>Q.fp)),U=new Set(_.map(Q=>Q.fp)),ie=_.filter(Q=>!F.has(Q.fp)).length,oe=K.filter(Q=>!U.has(Q.fp)).length,Ee=oe>0?`
|
|
535
|
+
\u26A0 ${oe} new ${oe===1?"issue":"issues"} appeared in the rewrites \u2014 recasting a sentence is where these come from.`:"";h({kind:"note",tone:K.some(Q=>Q.severity==="error")?"warn":"ok",text:K.length===0?`\u2713 Lint: all ${_.length} issue${_.length===1?"":"s"} resolved.`:[`\u2713 Lint: fixed ${ie} of ${_.length}.${Ee}`,"",...ys(K)].join(`
|
|
536
|
+
`)}),mn(ws(f,$),E.kind==="partitioned"?j:{aborted:!1,partitions:0,failed:0,notRun:0,verifiedComplete:K.length===0});let pe=gs({cwd:e,after:K,before:E.findings,scope:$,blocked:cn(f)});Ae(pe.text,{kind:"cmd",cmd:pe.cmd,reason:""});return}if(h({kind:"note",tone:x.length===0?"ok":"warn",text:ys(x,{full:f.includes("--full"),baselined:f.includes("--baselined")}).join(`
|
|
537
|
+
`)}),x.length>0){let P=Qi(e,$)===0&&Ji(e,$)===0?"; /push --all saves them to Document360 as-is":"",N=`/lint${R}${cn(f)?" --blocked":""} --fix`,E=jn(e,N);Ae(`Found ${x.length} doc issue${x.length===1?"":"s"} above. ${N} has the agent fix them in place${E?` (${E})`:""} \u2014 or /review${R} --fix for the full editorial pass${P}.`,{kind:"cmd",cmd:N,reason:""})}return}case"structure":{let y=Ls(e,s);if(y.length===0){h({kind:"note",tone:"info",text:"No documentation structure yet \u2014 run /init and author some articles first."});return}h({kind:"note",tone:"info",text:["Documentation order (categories \u2192 articles):","",...y].join(`
|
|
538
|
+
`)});return}case"status":{let y=f.some($=>$==="--all"||$==="--full");h({kind:"block",text:Kd(e,{profileName:s,all:y,width:Ge()}).join(`
|
|
539
|
+
`)}),te.current=!0;return}case"retire":{let y=f.find(R=>!R.startsWith("-"));if(!y){h({kind:"block",text:zd(e,s).join(`
|
|
540
|
+
`)}),te.current=!0;return}let $=pN(e,y)||y;if(!f.includes("--yes")&&!f.includes("-y")){h({kind:"note",tone:"warn",text:[`\u26A0 This takes "${$}" off your readers on Document360.`," The article, its history and every reviewer comment stay \u2014 nothing is deleted."," /push puts it back later if you change your mind."].join(`
|
|
541
|
+
`)}),Xe(`/retire ${$} --yes`,"tab to take it off your readers \xB7 or keep typing");return}A(!0);try{let R=await dN({cwd:e,path:$,profileName:s,now:new Date().toISOString()});h(R.ok?{kind:"note",tone:"ok",text:R.alreadyHidden?`\u2713 "${$}" was already invisible to readers. Recorded as retired, so nothing will offer to publish it again.
|
|
542
|
+
It stays on Document360 with its history and comments intact. /push puts it back.`:`\u2713 "${$}" is no longer visible to your readers.
|
|
543
|
+
It stays on Document360 with its history and comments intact. /push puts it back.`}:{kind:"note",tone:"error",text:`\u2717 Could not retire "${$}" \u2014 ${R.error.message}`})}finally{A(!1)}return}case"reorder":{let y=Vd(e,f);if(!y){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let $=await xe(y.prompt,{display:y.display,quietUser:!0}),R=Bt(e,{text:"Reordered locally \u2014 /push --all syncs the new order to Document360.",cmd:"/push --all"},"Reordered locally. ");Br($,R.text,{kind:"cmd",cmd:R.cmd,reason:""});return}case"review":{let y=Gd(e,f);if(y){h({kind:"note",tone:"ok",text:y.lines[0]});for(let E of y.closed)h({kind:"note",tone:"ok",text:E});Ae(y.cta.text,{kind:"cmd",cmd:y.cta.cmd,reason:""});return}let $=Hd(e,f);if(!$){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let R=f.includes("--fix"),b=f.find(E=>!E.startsWith("--")),x=R?go(e,f,b):[],P={aborted:!1,partitions:0,failed:0,notRun:0},N;if($.kind==="partitioned"){let E=await fk($,R);P=E.outcome,N=E}else N=await xe($.prompt,{display:$.display,quietUser:!0}),P={...P,producedNothing:N.producedNothing};if("aborted"in N&&N.aborted){let E=f.includes("--blocked")?"--blocked --fix":f.includes("--stale")?"--stale --fix":"--fix",j=Re("/review",E,b);Ae(`Stopped \u2014 the batches that finished are saved. ${j} picks up the rest${b||Os(f)?"":", or narrow it with /review <category> --fix"}.`,{kind:"cmd",cmd:j,reason:""},"warn");return}if($.kind!=="partitioned"&&R&&!N.producedNothing)try{Cr(e,x,st("review"))}catch{}if(R&&mn(`/review${b?` ${b}`:""}${f.includes("--all")?" --all":""}${f.includes("--blocked")?" --blocked":f.includes("--stale")?" --stale":""} --fix`,P),R){if(R&&!N.producedNothing){let K=cr(e,["--fix"],Rr({cwd:e,scope:b}));K.lines.length>0&&h({kind:"note",tone:"ok",text:K.lines.join(`
|
|
544
|
+
`)})}let E=R&&!N.producedNothing?Rr({cwd:e,scope:b}).filter(K=>!K.baselined&&K.severity==="error"):[];if(E.length>0){let K=new Set(E.map(U=>U.path)).size,_=`/lint${b?` ${b}`:""} --blocked --fix`,F=jn(e,_);h({kind:"note",tone:"warn",text:`\u26A0 The editor's rewrites left ${E.length} style error${E.length===1?"":"s"} in ${K} article${K===1?"":"s"} \u2014 recasting a sentence is where these appear.`}),Br(N,`Editor applied its fixes, but ${E.length} style error${E.length===1?"":"s"} remain. ${_} clears ${E.length===1?"it":"just those"} \u2014 it costs nothing to find them and one pass to correct${F?` (${F})`:""}. It is the last paid pass before publishing: anything still standing after a second attempt is reported for a person rather than run again.`,{kind:"cmd",cmd:_,reason:""});return}let j=Bt(e,{text:`\u2713 Editor applied its fixes \u2014 your docs are corrected. /push${b?"":" --all"} saves them to Document360 as drafts (or /lint${b?` ${b}`:""} for an instant no-token re-scan first).`,cmd:b?"/push":"/push --all"},"\u2713 Editor applied its fixes to this scope. ",b);Br(N,j.text,{kind:"cmd",cmd:j.cmd,reason:""})}else{let E=b?` ${b}`:"",j=Qi(e,b)===0&&Ji(e,b)===0?`; /push${b?"":" --all"} saves them to Document360 as-is`:"";Br(N,`The review listed issues above. /review${E} --fix lets the editor apply them all (or /lint${E} --fix for just the deterministic ones${j}).`,{kind:"cmd",cmd:`/review${E} --fix`,reason:""})}return}case"capture-setup":{await H();return}case"devhints":{if(!$e(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}h({kind:"note",tone:"info",text:zo(Ko(e)).join(`
|
|
545
|
+
`)}),nn(to()),Vr.current=Ut(e).status==="current",_o.current=sn(e);return}case"discover":{if(!$e(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await xe(Gc(),{display:"/discover",quietUser:!0});return}case"ask":{if(!$e(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let y=f.join(" ").trim();if(y===""){h({kind:"block",text:ud(uN(e)).join(`
|
|
546
|
+
`)});return}try{let $=cN(e,{question:y});h({kind:"note",tone:"ok",text:cd($.file,As(e)).join(`
|
|
547
|
+
`)})}catch($){h({kind:"note",tone:"warn",text:`Could not file the question: ${$.message}`})}return}case"inbox":{if(!$e(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(ad(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 xe(ld(),{display:"/inbox",quietUser:!0});return}case"share":{let y=$e(e);if(!y){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let $=f[0]?.trim().toLowerCase();if($==="status"){for(let b of Ca(e,y))h({kind:"note",tone:b.tone,text:b.text});return}if($==="on"||$==="off"){for(let b of dd(e,y,$==="on"))h({kind:"note",tone:b.tone,text:b.text});M(b=>b+1);return}if($){h({kind:"note",tone:"error",text:`Unknown option: ${$} \u2014 use /share, /share status, /share on, or /share off.`});return}h({kind:"note",tone:"info",text:"Exchanging work with your team\u2026"});let R=await Sa(e,y);for(let b of R.lines)h({kind:"note",tone:b.tone,text:b.text});R.changed&&M(b=>b+1);return}case"feedback":{let y=Gb(e),$="";try{$=xr(y)?cl(y,"utf8"):""}catch{$=""}if(!/^## /m.test($)){h({kind:"note",tone:"info",text:"No open d360-writer feedback to copy \u2014 nothing logged in .d360-writer/tool-feedback.md yet."});return}let R=await ip($.trim());h({kind:"note",tone:R?"ok":"warn",text:R?"\u2713 Copied the d360-writer feedback to your clipboard \u2014 send it to the team (Teams / Slack / email).":`Couldn\u2019t reach your clipboard \u2014 open ${y} and copy it manually.`}),R&&Sl(null);return}case"document":{if(!$e(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{push:y,skipReview:$,what:R}=Mu(f);if(!R&&_u(e)===0){h({kind:"note",tone:"info",text:Uu});return}let b=`/document${R?` ${R}`:""}${y?" --push":""}`,x=await xe(Fu(R),{display:b,quietUser:!0});y&&!x.producedNothing&&await oh({skipReview:$});return}case"catch-up":{if(!$e(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!Xn(u.trim()))return;let{push:y,skipReview:$}=gd(f);for(let E of await hd(e))h({kind:"note",tone:E.tone,text:E.text});h({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let R=await kd({cwd:e,profileName:s});for(let E of $d(R))h({kind:"note",tone:E.startsWith("\u2713")?"ok":E.startsWith("\u2139")?"info":"warn",text:E});let b=wd(e);for(let E of yd(b))h({kind:"note",tone:E.tone,text:E.text});h({kind:"note",tone:"info",text:md(uo(e))});let x=qb(e),P=await xe(bd(b),{display:`/catch-up${y?" --push":""}`,quietUser:!0}),N=po(e,x,"","/catch-up");y&&!P.producedNothing?await oh({skipReview:$}):N.cta&&Br(P,N.cta.text,{kind:"cmd",cmd:N.cta.cmd,reason:""});return}case"comments":{if(!$e(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!Xn(u.trim()))return;let y=Sd(f);We("Checking Document360 for reviewer comments\u2026"),A(!0);let $=null;try{$=await Pa(e,s,{...y.scope,onProgress:(b,x)=>We(`Checking Document360 for reviewer comments\u2026 ${b}/${x}`)})}catch(b){h({kind:"note",tone:"error",text:`Couldn\u2019t read comments from Document360: ${b.message}`})}finally{A(!1),We(null)}if(!$)return;M(b=>b+1);let R=ho($.threads,$.labels);if($.threads.length===0){h({kind:"note",tone:"ok",text:Ns($,{showAnswered:y.showAnswered,width:Ge()}).join(`
|
|
548
|
+
`)});return}if(y.answer&&(y.all||y.scope.path||y.scope.scope||R.length===1)){Mo(Rd($,{full:!0,showAnswered:y.showAnswered,width:Ge()})),await Dl(R,{resolve:y.resolve});return}if(R.length===1){Mo(Ta(R[0],{width:Ge()})),Ir({group:R[0],cursor:0,fromList:!1,resolve:y.resolve,rest:[]});return}Mo(Ns($,{showAnswered:y.showAnswered,width:Ge()})),Zt({cursor:0,rows:Aa(R),groups:R,resolve:y.resolve,report:$});return}case"update":{xl.current=!0,h({kind:"note",tone:"info",text:"Updating the d360-writer toolchain\u2026 (don\u2019t close this window)"}),Mn(!0);let y=await Na().finally(()=>Mn(!1));y.ok?(h({kind:"note",tone:"ok",text:`\u2713 Updated ${y.packages.join(" + ")} \u2014 run /exit, then relaunch to apply.`}),re("/exit"),vo("")):(h({kind:"note",tone:"warn",text:`Update failed. ${Da(y.output)}`}),y.output&&h({kind:"note",tone:"info",text:`${y.output}
|
|
549
|
+
|
|
550
|
+
Full output: ${Ea()}`}));return}case"screenshot":{let y=ss(f),$=no(e);if($&&y.mode!=="list"&&h({kind:"note",tone:"info",text:$}),y.mode==="capture"){await T(y.rest);return}if(y.mode==="annotate"){await W(y.rest);return}if(y.mode==="checklist"){await H();return}if(y.mode==="verify"){let x=_e(e),P=y.rest.find(j=>!j.startsWith("-")),N=P?[P]:Rs(x);if(P&&!x.some(j=>j.id===P)){h({kind:"note",tone:"error",text:`No screenshot placeholder called "${P}". /screenshot list shows them all.`});return}if(N.length===0){let j=x.filter(_=>_.state==="rejected").length,K=x.filter(_=>_.state==="verified").length;h({kind:"note",tone:"info",text:j>0?`Nothing left to verify. ${j} shot${j===1?"":"s"} failed verification \u2014 re-capture with /screenshot capture --failed.`:K>0?`All ${K} captured shot${K===1?" is":"s are"} already verified.`:"No captured screenshots to verify yet \u2014 /screenshot capture takes the shots first."});return}h({kind:"note",tone:"info",text:Dn(N.length)}),await xe(Xt(e,N),{display:P?`/screenshot verify ${P}`:"/screenshot verify",quietUser:!0});let E=pr(e,N);E.length>0&&h({kind:"note",tone:"info",text:E.join(`
|
|
551
|
+
`)});return}if(y.mode==="list"){if(!$e(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let x=$e(e)?.docsDir??Tp,P=Rc(e,y.scope),N=_e(e,P);if(y.picker){if(N.length===0){h({kind:"note",tone:"info",text:"No screenshot placeholders found in the docs."});return}let j=Jf(N);if(j.length===0){h({kind:"note",tone:"info",text:Gi(N,{docsDir:x}).join(`
|
|
552
|
+
`)});let K=Re("/push","--screenshots",P),_=Bt(e,{text:`\u2713 All ${N.length} screenshots are captured. ${K} saves them into the articles on Document360; /screenshot capture${P?` ${P}`:""} re-captures.`,cmd:K},`\u2713 All ${N.length} screenshots are captured. `,P);Ae(_.text,{kind:"cmd",cmd:_.cmd,reason:""});return}Bn({cursor:0,rows:j,title:"Screenshots \u2014 pick what to author or capture:"});return}h({kind:"note",tone:"info",text:Gi(N,{scope:P,detail:y.detail,docsDir:x}).join(`
|
|
553
|
+
`)}),$&&h({kind:"note",tone:"info",text:$});let E=xc(N,P);E.key!=="done"&&re(E.cmd);return}if(y.mode==="single"){await sh(y.id);return}if(!$e(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let R=y.mode==="scope"?y.scope:void 0,b=KD(e,{scope:R}).map(x=>x.id);if(b.length===0){h({kind:"note",tone:"info",text:R?`No screenshot placeholders under ${R}.`:"No screenshot placeholders found in the docs."});return}await rh(b,{setup:y.setup,scope:y.mode==="scope"?y.scope:void 0,runLine:y.mode==="scope"?[`/screenshot author ${y.scope}`,`/screenshot ${y.scope}`]:["/screenshot author --all","/screenshot --all"]});return}case"capture":{await T(f);return}case"reset":{let y=Ad(e);if(y.length===0){h({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}jr.current={repoName:qs(e),targets:y,hadDevhints:xr(Hb(e))},h({kind:"note",tone:"warn",text:Dd(e,y).join(`
|
|
554
|
+
`)}),Xe(qs(e));return}default:h({kind:"note",tone:"error",text:`Unknown command: /${c} \u2014 type /help.`})}},[e,r,s,Uo,Ol,h,Qe,xe,lt,Nl,ih]),zr=ne(u=>{let p=(u??w).trim();if(k(""),Ks(null),xo(0),p.startsWith("/")){te.current=!1,je.current=!1,Ne.current=null,_t(),No(null);let f=kl.current.includes(p);f&&(kl.current=[]),Z(T=>f?[]:fb(T,p))}if(!p||(pn(!1),At.current=!1,(jr.current||Te.current.length>0)&&h({kind:"user",text:p}),lh(p))||ah(p))return;fl.current.push(p);let c=yb(p,jp.current);if(p.startsWith("/"))h({kind:"user",text:p}),z(!0),Wo(c).finally(()=>z(!1));else if(hN(c)){h({kind:"user",text:p});let f=fN(c);if(!f)xe(c,{display:p,quietUser:!0});else{try{mN(e,{title:f,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}xe(`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=dm(e,c);xe(f??c,{display:p})}},[w,lh,ah,Wo,xe]),ch=ne(u=>{if(u.length>1){if(u.includes("\x1B"))return;let p=mb(u);if(gb(p)){let c=wb(++ak.current,p);jp.current.set(c,p),S(c)}else S(p);return}S(u)},[S]),Bo=Math.max(10,rt-6),uh=wp(()=>al(d.text,Bo),[d.text,Bo]),_l=ne(u=>m(p=>({...p,pos:Math.max(0,Math.min(p.text.length,p.pos+u))})),[]),di=ne(u=>m(p=>({...p,pos:kb(al(p.text,Bo),p.pos,u)})),[Bo]),Xr=ne(u=>m(p=>({...p,pos:$b(al(p.text,Bo),p.pos,u)})),[Bo]),gk=["\x1B[H","\x1B[1~","\x1BOH"],wk=["\x1B[F","\x1B[4~","\x1BOF"],dh=ne((u,p)=>p.leftArrow?(_l(-1),!0):p.rightArrow?(_l(1),!0):u&&gk.includes(u)?(Xr("start"),!0):u&&wk.includes(u)?(Xr("end"),!0):p.ctrl&&u==="a"?(Xr("start"),!0):p.ctrl&&u==="e"?(Xr("end"),!0):!1,[_l,Xr]),ph=ne(()=>{if(Le.current){if(!Le.current.signal.aborted){let u=(Io?.verb??"work").toLowerCase(),p=Io?.unit??"article";h({kind:"note",tone:"warn",text:`\u238B Stopping the ${u} run (finishing in-flight ${p}s)\u2026`}),Le.current.abort()}return!0}return Lr.current?!1:(Lr.current=!0,h({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),Dt.current?.interrupt(),!0)},[Io]);return dD((u,p)=>{if(p.ctrl&&u==="c"){if(Or.current!==null&&Date.now()-Or.current<Qb){Or.current=null,Dt.current?.close(),r();return}Or.current=Date.now(),Up(!0),wl.current&&clearTimeout(wl.current),wl.current=setTimeout(()=>{Or.current=null,Up(!1)},Qb),C?ph():w&&k("");return}if(qr.current.awaySince!==null)try{let c=ib(qr.current,Date.now(),uo(e));if(qr.current=c.memory,Jp(null),c.kind==="delta"){h({kind:"note",tone:"info",text:lb(c.delta,c.awayMs)});let f=Mt(!1);f.kind==="recommend"&&tn(f.rec,{silent:!0})}else if(c.kind==="briefing"){h({kind:"note",tone:"info",text:`\u{1F4E5} ${Hs(c.delta)} arrived while you were away (${hp(c.awayMs)}).`});let f=Mt(!1);f.kind==="recommend"&&tn(f.rec)}}catch{}if(Pl.current=Date.now(),!D){if(C){if(p.escape){ph();return}if(p.return){let c=w.trim();if(!c)return;qn.current.push(c),gl([...qn.current]),k("");return}if(dh(u,p))return;if(p.upArrow){di(-1);return}if(p.downArrow){di(1);return}if(p.backspace||p.delete){v();return}u&&!p.ctrl&&!p.meta&&ch(u);return}if(fn){if(p.upArrow){Un(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Un(c=>c&&{...c,cursor:Math.min(Pt.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=en(u,Pt.length);c!==null&&Un(f=>f&&{...f,cursor:c});return}if(p.return){let c=Pt[fn.cursor];Un(null);let{lines:f,changed:T,effective:W}=vs(e,c.value??"default");for(let H of f)h({kind:"note",tone:H.startsWith("\u26A0")?"warn":H.startsWith("\u2713")?"ok":"info",text:H});T&&(Gp(H=>H+1),Dt.current?.setModel(W));return}if(u==="s"){let c=Pt[fn.cursor];Un(null),Dt.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){Un(null);return}return}if(jt){if(p.upArrow){Po(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Po(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=en(u,jt.rows.length);c!==null&&Po(f=>f&&{...f,cursor:c});return}if(p.return||u==="s"){let c=jt.rows[jt.cursor];Po(null),Il(c.name,p.return===!0);return}if(p.escape){Po(null);return}return}if(Mr){if(p.escape){Yn(null);return}if(p.leftArrow||p.tab&&p.shift){Yn(c=>c&&{tab:(c.tab-1+ct.length)%ct.length,scroll:0});return}if(p.rightArrow||p.tab){Yn(c=>c&&{tab:(c.tab+1)%ct.length,scroll:0});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=ct.length){Yn({tab:Number(u)-1,scroll:0});return}if(p.upArrow){Yn(c=>c&&{...c,scroll:Math.max(0,c.scroll-1)});return}if(p.downArrow){Yn(c=>{if(!c)return c;let f=(ct[c.tab]??ct[0]).rows.length;return{...c,scroll:Math.min(Math.max(0,f-1),c.scroll+1)}});return}return}if(It){if(p.upArrow){To(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){To(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=en(u,It.rows.length);c!==null&&To(f=>f&&{...f,cursor:c});return}if(p.return){let c=It.rows[It.cursor].name;if(To(null),!Zl(e,c).created){h({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}h({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${c}").`});let T=!1;try{let W=_n(c);T=!!W&&!(yo(W)&&!W.refreshToken)}catch{T=!1}h({kind:"note",tone:"info",text:T?`Next: sign in to ${c} and pick your project \u2014 you're already signed in here, so it'll be quick.`:`Next: sign in to Document360 (${c}) and pick your project.`}),re("/login"),M(W=>W+1);return}if(p.escape){To(null);return}return}if(Ye){if(p.upArrow){Ao(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Ao(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=en(u,Ye.rows.length);c!==null&&Ao(f=>f&&{...f,cursor:c});return}if(p.return){let c=Ye.rows[Ye.cursor],{profile:f,projectId:T}=Ye;Ao(null),li(f,T,c);return}if(p.escape){Ao(null);return}return}if(tt){if(p.upArrow){Wn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Wn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=en(u,tt.rows.length);c!==null&&Wn(f=>f&&{...f,cursor:c});return}if(p.return){let c=tt.rows[tt.cursor],{profile:f}=tt;Wn(null),ui(f,c);return}if(p.escape){Wn(null);return}return}if(nt){if(p.upArrow){jo(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){jo(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u===" "){jo(c=>c&&{...c,rows:c.rows.map((f,T)=>T===c.cursor?{...f,checked:!f.checked}:f)});return}if(p.return){let c=nt.rows.filter(f=>f.checked).map(f=>f.path);if(jo(null),c.length===0){h({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}qc(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){jo(null);return}return}if(at){if(p.upArrow){Hn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Hn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=en(u,at.rows.length);c!==null&&Hn(f=>f&&{...f,cursor:c});return}if(p.return){let c=at.rows[at.cursor],f=at.run;Hn(null),f(c.token);return}if(p.escape){Hn(null);return}return}if(wt){if(p.upArrow){Eo(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Eo(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=en(u,wt.rows.length);c!==null&&Eo(f=>f&&{...f,cursor:c});return}if(p.return){let c=wt.rows[wt.cursor],f=wt.conflicts;Eo(null),c.conflict?Ol(c.paths[0]):c.kind==="article"?Nl(c.paths[0]):lt(c.paths,c.kind==="all"?f:0);return}if(p.escape){Eo(null);return}return}if(Lt){if(p.upArrow){Do(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Do(c=>c&&{...c,cursor:Math.min(c.rows.length,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=en(u,Lt.rows.length+1);c!==null&&Do(f=>f&&{...f,cursor:c});return}if(p.return){let{cursor:c,rows:f,opts:T}=Lt;Do(null);let W=c===0?f:[f[c-1]];mk(W,T);return}if(p.escape){Do(null),h({kind:"note",tone:"info",text:"Left as drafts \u2014 nothing changed. /publish when they have been signed off."});return}return}if(yt){let{rows:c}=yt;if(p.upArrow){Zt(f=>f&&{...f,cursor:Math.max(0,f.cursor-1)});return}if(p.downArrow){Zt(f=>f&&{...f,cursor:Math.min(c.length-1,f.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let f=cp(Op.current,Number(u),c.length-1);Op.current=f.memory,f.index!==null&&Zt(T=>T&&{...T,cursor:f.index+1});return}if(u==="a"||u==="A"){Zt(f=>f&&{...f,cursor:0});return}if(p.return){let f=c[yt.cursor],{groups:T,resolve:W,report:H}=yt;if(Zt(null),f.kind==="all"){Dl(T,{resolve:W,report:H});return}Mo(Ta(f.group,{width:Ge()})),Ir({group:f.group,cursor:0,fromList:!0,resolve:W,rest:T.filter(y=>y.articleId!==f.group.articleId),report:H});return}if(p.escape){Zt(null),re("/comments");return}return}if(ze){let c=()=>{let{rest:f,group:T,fromList:W,resolve:H,report:y}=ze;if(Ir(null),!W||!y){re("/comments");return}let $=[T,...f].sort((R,b)=>R.category.localeCompare(b.category)||R.title.localeCompare(b.title));Zt({cursor:0,rows:Aa($),groups:$,resolve:H,report:y})};if(p.upArrow||p.downArrow){Ir(f=>f&&{...f,cursor:f.cursor===0?1:0});return}if(u==="y"||u==="Y"||p.return&&ze.cursor===0){let{group:f,resolve:T,rest:W,report:H}=ze;Ir(null),Dl([f],{resolve:T,rest:W,...H?{report:H}:{}});return}if(u==="b"||u==="B"||p.escape||p.return){c();return}return}if(Ot){if(p.upArrow){Bn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Bn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let c=en(u,Ot.rows.length);c!==null&&Bn(f=>f&&{...f,cursor:c});return}if(p.return){let c=Ot.rows[Ot.cursor];Bn(null),c.action==="capture"?Kr(c.ids,{runLine:c.kind==="all"?["/screenshot capture --all","/capture --all"]:void 0}):c.action==="annotate"?ai(c.ids,{verifiedBefore:new Set(_e(e).filter(f=>f.state==="verified").map(f=>f.id))}):c.kind==="shot"?sh(c.ids[0]):rh(c.ids,{setup:!0,runLine:c.kind==="all"?["/screenshot author --all","/screenshot --all"]:void 0});return}if(p.escape){Bn(null);return}return}if(bt){if(p.escape){Gn(null);return}if(p.upArrow){Gn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Gn(c=>c&&{...c,cursor:Math.min(Math.max(0,oi.length-1),c.cursor+1)});return}if(p.return){let c=oi[bt.cursor];if(c){Gn(null);try{h({kind:"preview",name:qs(c),text:Zb(cl(yp(e,c),"utf8"))})}catch(f){h({kind:"note",tone:"error",text:`Could not read ${c}: ${f.message}`})}}return}if(p.backspace||p.delete){Gn(c=>c&&{...c,query:c.query.slice(0,-1),cursor:0});return}if(u&&!p.ctrl&&!p.meta&&u.length===1){Gn(c=>c&&{...c,query:c.query+u,cursor:0});return}return}if(kt){if(p.escape){Vn(null);return}if(p.upArrow){Vn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(p.downArrow){Vn(c=>c&&{...c,cursor:Math.min(Math.max(0,ri.length-1),c.cursor+1)});return}if(p.return){let c=ri[kt.cursor];if(c){Vn(null),Qe(c.uuid),Qt.current={uuid:c.uuid,firstPrompt:c.firstPrompt,titleFired:!0},Fn(c.name),bp(c.uuid),So.current=[],ot.current={printed:[],armed:[],printedAt:Oo.current};let f=up(e,c.uuid);for(let T of f)h(T);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){Vn(c=>c&&{...c,query:c.query.slice(0,-1),cursor:0});return}if(u&&!p.ctrl&&!p.meta&&u.length===1){Vn(c=>c&&{...c,query:c.query+u,cursor:0});return}return}if(p.tab&&!w&&de){k(de),_t();return}if(!w&&fe.length>0&&!At.current&&u&&/^[1-9]$/.test(u)){let c=fe[Number(u)-1];if(c){k(On(c));return}}if(!w&&fe.length===0&&!At.current&&ot.current.armed.length>0&&u&&/^[1-9]$/.test(u)){let c=ot.current.armed[Number(u)-1];if(c){k(c);return}}if(!w&&(ei||Hr)&&u==="c"&&!p.ctrl&&!p.meta&&!p.return&&!p.tab){let c=ei!=null;ip(ei??Hr).then(T=>{h({kind:"note",tone:T?"ok":"warn",text:T?c?"\u2713 Copied the feedback to your clipboard \u2014 send it to the d360-writer team (Teams / Slack / email).":"\u2713 Copied the prompt to your clipboard \u2014 paste it into your repo's coding agent.":c?"Couldn't reach your clipboard \u2014 select the feedback above and copy it manually.":"Couldn't reach your clipboard \u2014 select the prompt above and copy it manually."}),T&&c&&Sl(null),T&&!c&&Vp(!0)});return}if(!dh(u,p)){if(eh){if(p.upArrow){xo(c=>Math.max(0,c-1));return}if(p.downArrow){xo(c=>Math.min(on.length-1,c+1));return}if(p.tab){k("/"+(on[hl]?.name??"")+" "),xo(0);return}if(p.return){let c=on[hl];if(c){let f=w.trim().slice(1).split(/\s+/).slice(1).join(" ");if(Km(c.usage)&&!f){k("/"+c.name+" "),xo(0);return}zr("/"+c.name+(f?" "+f:""));return}}}else{if(!w&&fe.length>0&&!At.current&&(p.upArrow||p.downArrow)){if(p.downArrow){Dr(c=>c===null?0:Math.min(fe.length-1,c+1));return}if(Co!==null){Dr(c=>c===null||c===0?null:c-1);return}}if(p.upArrow){if(w!==""&&Ro===null){di(-1);return}let c=fl.current;if(!c.length)return;let f=Ro===null?c.length-1:Math.max(0,Ro-1);Ks(f),k(c[f]??"");return}if(p.downArrow){if(w!==""&&Ro===null){di(1);return}let c=fl.current;if(Ro===null)return;let f=Ro+1;f>=c.length?(Ks(null),k("")):(Ks(f),k(c[f]??""));return}}if(p.return){if(Co!==null&&!w&&fe[Co]){let c=On(fe[Co]);Dr(null),zr(c);return}zr();return}if(p.backspace||p.delete){v();return}if(p.escape){k(""),xo(0),_t(),Z([]),No(null),Dr(null),te.current=!0;return}u&&!p.ctrl&&!p.meta&&ch(u)}}}),it(()=>{if(C||D)return;let u=qn.current.shift();u!==void 0&&(gl([...qn.current]),zr(u))},[C,D,zr]),ue(De,{flexDirection:"column",width:rt,children:[El!==null&&ue(De,{marginTop:1,flexDirection:"column",children:[El.truncated&&V(Y,{dimColor:!0,children:"\u2026"}),V(Y,{children:El.text})]}),C&&Io?V(AN,{p:Io}):null,Wp?V(PN,{text:Wp}):C&&!Io?V(SN,{startTime:Et.current,chars:Pe}):null,V(De,{borderStyle:"round",borderColor:Zp.prod?"yellow":ae,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:w?uh.map((u,p)=>{let c=d.text.slice(u.start,u.end),f=p===ll(uh,d.pos),T=Math.min(d.pos,u.end)-u.start;return ue(Y,{children:[V(Y,{color:ae,children:p===0?"> ":" "}),f?ue(Pr,{children:[c.slice(0,T),V(Sr,{ch:c[T]??" "}),c.slice(T+1)]}):c||" "]},`${p}-${u.start}`)}):ue(Y,{children:[V(Y,{color:ae,children:"> "}),Fr?V(Sr,{ch:" "}):Se&&!C?ue(Pr,{children:[V(Sr,{ch:Se[0],dim:!0}),V(Y,{color:"gray",children:Se.slice(1)})]}):de&&!C?ue(Pr,{children:[V(Sr,{ch:de[0],dim:!0}),V(Y,{color:"gray",children:de.slice(1)}),V(Y,{dimColor:!0,children:" (tab)"})]}):(Tl.isSetup||!Er)&&!C?ue(Pr,{children:[V(Sr,{ch:Tl.text[0],dim:!0}),V(Y,{color:"gray",children:Tl.text.slice(1)})]}):V(Sr,{ch:" "})]})}),Fp.length>0&&V(De,{flexDirection:"column",paddingX:1,children:Fp.map((u,p)=>V(Y,{color:"gray",children:`\u29D7 queued: ${u}`},`${p}-${u.slice(0,24)}`))}),Mr?V(ub,{tab:Mr.tab,scroll:Mr.scroll,rows:hk,width:rt,version:o,engineVersion:ek}):fn?ue(De,{flexDirection:"column",paddingX:1,children:[V(Y,{color:ae,bold:!0,children:"Select model"}),V(Y,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),Pt.map((u,p)=>ue(Y,{color:p===fn.cursor?ae:void 0,children:[p===fn.cursor?"\u276F ":" ",`${p+1}. ${u.label}${p===fn.current?" \u2714":""}`.padEnd(16),V(Y,{color:"gray",children:` ${u.desc}`})]},u.label)),V(Y,{dimColor:!0,children:ft({verb:"set as default",rows:Pt.length,extra:["s this session only"]})})]}):jt?ue(De,{flexDirection:"column",paddingX:1,children:[V(Y,{color:ae,bold:!0,children:"Switch connection profile"}),V(dn,{rows:jt.rows,cursor:jt.cursor,cap:Gt,render:(u,p,c)=>ue(Y,{color:c?ae:void 0,children:[c?"\u276F ":" ",`${p+1}. ${u.name}${p===jt.current?" \u2714":""}`.padEnd(20),V(Y,{color:"gray",children:` ${u.env} \xB7 ${u.who??"not signed in"}`}),u.prod?V(Y,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},u.name)}),V(Y,{dimColor:!0,children:ft({verb:"switch (saved as default)",rows:jt.rows.length,extra:["s this session only"]})})]}):It?ue(De,{flexDirection:"column",paddingX:1,children:[V(Y,{color:ae,bold:!0,children:"Pick your Document360 environment"}),V(dn,{rows:It.rows,cursor:It.cursor,cap:Gt,render:(u,p,c)=>ue(Y,{color:c?ae:void 0,children:[c?"\u276F ":" ",`${p+1}. ${u.name}`.padEnd(16),V(Y,{color:"gray",children:` ${u.apiUrl}`}),u.note?V(Y,{color:"yellow",children:` \u26A0 ${u.note}`}):null]},u.name)}),V(Y,{dimColor:!0,children:ft({verb:"use it",rows:It.rows.length})})]}):Ye?ue(De,{flexDirection:"column",paddingX:1,children:[V(Y,{color:ae,bold:!0,children:"Switch workspace"}),V(Y,{dimColor:!0,children:`environment ${Ye.environment} \xB7 project ${Ye.projectName??`${Ye.projectId.slice(0,8)}\u2026`}`}),V(dn,{rows:Ye.rows,cursor:Ye.cursor,cap:Gt,render:(u,p,c)=>ue(Y,{color:c?ae:void 0,children:[c?"\u276F ":" ",`${p+1}. ${u.name}${p===Ye.current?" \u2714":""}`.padEnd(30),V(Y,{color:"gray",children:u.type?` ${u.type}`:""})]},u.id)}),V(Y,{dimColor:!0,children:ft({verb:"switch",rows:Ye.rows.length})})]}):tt?ue(De,{flexDirection:"column",paddingX:1,children:[V(Y,{color:ae,bold:!0,children:"Choose project"}),V(Y,{dimColor:!0,children:`environment ${tt.environment}`}),V(dn,{rows:tt.rows,cursor:tt.cursor,cap:Gt,render:(u,p,c)=>ue(Y,{color:c?ae:void 0,children:[c?"\u276F ":" ",`${p+1}. ${u.name}${p===tt.current?" \u2714":""}`.padEnd(30),V(Y,{color:"gray",children:u.sub?` ${u.sub}`:""})]},u.id)}),V(Y,{dimColor:!0,children:ft({verb:"switch",rows:tt.rows.length})})]}):nt?(()=>{let p=Math.min(Math.max(0,nt.cursor-Math.floor(7)),Math.max(0,nt.rows.length-14)),c=nt.rows.slice(p,p+14),f=nt.rows.filter(T=>T.checked).length;return ue(De,{flexDirection:"column",paddingX:1,children:[V(Y,{color:ae,bold:!0,children:`Which folders back the user docs? (${f} selected of ${nt.rows.length})`}),p>0?V(Y,{dimColor:!0,children:` \u2191 ${p} more`}):null,c.map((T,W)=>{let H=p+W;return ue(Y,{color:H===nt.cursor?ae:void 0,children:[H===nt.cursor?"\u276F ":" ",T.checked?"\u25C9 ":"\u25CB ",T.path.padEnd(Math.min(48,rt-34)),V(Y,{color:"gray",children:na(T)})]},T.path)}),p+14<nt.rows.length?V(Y,{dimColor:!0,children:` \u2193 ${nt.rows.length-p-14} more`}):null,V(Y,{dimColor:!0,children:ft({verb:"save",multi:!0})})]})})():at?ue(De,{flexDirection:"column",paddingX:1,children:[V(Y,{color:ae,bold:!0,children:at.title??"Which category? (pick one to scope to)"}),V(dn,{rows:at.rows,cursor:at.cursor,cap:Gt,render:(u,p,c)=>ue(Y,{color:c?ae:void 0,children:[c?"\u276F ":" ",`${`${p+1}.`.padEnd(3)} ${u.label} (${u.count})`.padEnd(Math.min(44,Math.max(20,rt-24))),V(Y,{color:"gray",children:` ${u.token}`})]},u.token)}),V(Y,{dimColor:!0,children:ft({verb:"choose it",rows:at.rows.length})})]}):wt?ue(De,{flexDirection:"column",paddingX:1,children:[V(Y,{color:ae,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),V(dn,{rows:wt.rows,cursor:wt.cursor,cap:Gt,render:(u,p,c)=>ue(Y,{color:c?ae:void 0,bold:u.kind==="category"&&!c,children:[c?"\u276F ":" ",`${u.indent?" ":" "}${`${p+1}.`.padEnd(3)} ${u.label}`.padEnd(Math.min(56,rt-24)),u.note?V(Y,{color:"gray",children:` ${u.note}`}):null]},`${u.kind}:${u.paths.join(",")}`)}),V(Y,{dimColor:!0,children:ft({verb:"push as drafts",rows:wt.rows.length})})]}):Lt?ue(De,{flexDirection:"column",paddingX:1,children:[V(Y,{color:ae,bold:!0,children:"Publish live to your readers \u2014 this is what they will see:"}),V(dn,{rows:[{path:"",articleId:"",label:`Publish all ${Lt.rows.length} live`,version:void 0},...Lt.rows],cursor:Lt.cursor,cap:Gt,render:(u,p,c)=>ue(Y,{color:c?ae:void 0,bold:p===0&&!c,children:[c?"\u276F ":" ",` ${`${p+1}.`.padEnd(3)} ${u.label}`.padEnd(Math.min(56,rt-24)),p>0?V(Y,{color:"gray",children:` ${u.version?`draft v${u.version} \u2192 live`:"draft \u2192 live"}`}):null]},`${p}:${u.path||"all"}`)}),V(Y,{dimColor:!0,children:ft({verb:"publish live",cancel:"leave as drafts",rows:Lt.rows.length+1})})]}):yt?ue(De,{flexDirection:"column",paddingX:1,children:[V(Y,{color:ae,bold:!0,children:"Which comments do you want to look at?"}),V(dn,{rows:yt.rows,cursor:yt.cursor,cap:Gt,render:(u,p,c)=>ue(Y,{color:c?ae:void 0,bold:u.kind==="all"&&!c,children:[c?"\u276F ":" ",`${(u.kind==="all"?"":`${u.n}.`).padEnd(4)}${u.label}`.padEnd(Math.min(56,Math.max(20,rt-24))),u.kind==="article"?V(Y,{color:"gray",children:u.note}):null]},u.kind==="all"?"all":u.group.articleId)}),V(Y,{dimColor:!0,children:ft({verb:"open it",cancel:"close",rows:yt.rows.length-1})}),yt.resolve?V(Y,{dimColor:!0,children:"--resolve is on: threads you answer will be closed as well as replied to"}):null]}):ze?ue(De,{flexDirection:"column",paddingX:1,children:[V(Y,{color:ae,bold:!0,children:`${ze.group.title} \u2014 ${ze.group.threads.length} comment${ze.group.threads.length===1?"":"s"}`}),ue(Y,{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(Y,{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"]}),V(Y,{dimColor:!0,children:ft({verb:"open it",cancel:"go back",extra:["y answer"]})})]}):Ot?ue(De,{flexDirection:"column",paddingX:1,children:[V(Y,{color:ae,bold:!0,children:Ot.title}),(()=>{let{rows:u,cursor:p}=Ot,c=el(u.length,p,Gt),f=c.start,T=u.slice(c.start,c.end),W=`${u.length}.`.length+1,H=Qf(u,Math.max(20,rt-4-W));return ue(Pr,{children:[f>0?V(Y,{color:"gray",children:` \u2026 ${f} more above`}):null,T.map((y,$)=>{let R=f+$,b=R===p,x=H[R];return ue(Y,{color:b?ae:void 0,bold:(y.kind==="all"||y.kind==="category")&&!b,children:[b?"\u276F ":" ",`${R+1}.`.padEnd(W),x.head,x.note?V(Y,{color:"gray",children:x.note}):null]},`${y.action}:${y.kind}:${y.ids.join(",")}`)}),c.below>0?V(Y,{color:"gray",children:` \u2026 ${c.below} more below`}):null]})})(),V(Y,{dimColor:!0,children:ft({verb:"run it",rows:Ot.rows.length})})]}):bt?ue(De,{flexDirection:"column",paddingX:1,children:[V(Y,{color:ae,bold:!0,children:`Preview article${bt.query?` \u2014 filter: ${bt.query}`:" (type to filter)"}`}),oi.length===0?V(Y,{color:"gray",children:"no articles match"}):oi.map((u,p)=>ue(Y,{color:p===bt.cursor?ae:void 0,children:[p===bt.cursor?"\u276F ":" ",u]},u)),V(Y,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):kt?ue(De,{flexDirection:"column",paddingX:1,children:[V(Y,{color:ae,bold:!0,children:`Resume session${kt.query?` \u2014 filter: ${kt.query}`:" (type to filter)"}`}),ri.length===0?V(Y,{color:"gray",children:"no sessions match"}):ri.map((u,p)=>ue(Y,{color:p===kt.cursor?ae:void 0,children:[p===kt.cursor?"\u276F ":" ",u.name.slice(0,28).padEnd(30),V(Y,{color:p===kt.cursor?ae:"gray",children:u.firstPrompt.slice(0,Math.max(10,rt-40))})]},u.uuid)),V(Y,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):eh?ue(De,{flexDirection:"column",children:[Qn>0?V(Y,{dimColor:!0,children:` \u22EF ${Qn} more above`}):null,Al.map((u,p)=>{let c=Qn+p,f=u.name==="model"&&yl?`${u.desc} (currently ${yl})`:u.desc,T=Math.max(20,rt-4),W=u.usage.length>T?`${u.usage.slice(0,T-1)}\u2026`:u.usage,H=T-Math.max(W.length,22)-1,y=H<=1?"":f.length>H?`${f.slice(0,H-1)}\u2026`:f;return ue(Y,{color:c===ni?ae:void 0,children:[c===ni?"\u276F ":" ",W.padEnd(22)," ",V(Y,{color:c===ni?ae:"gray",children:y})]},u.name)}),Qn+Al.length<on.length?V(Y,{dimColor:!0,children:` \u22EF ${on.length-Qn-Al.length} more below`}):null,V(Y,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!C&&!w&&fe.length>0?ue(De,{flexDirection:"column",paddingX:1,children:[Mp?V(Y,{color:ae,children:Mp}):null,V(dn,{rows:fe,cursor:Co??0,cap:Gt,render:(u,p)=>{let c=p===Co,f=On(u),T=f.slice(0,Math.max(20,rt-7)),W=rt-T.length-9,H=W>=12?(hb(u)??Vm(f)).slice(0,W):"";return ue(Y,{color:c?ae:void 0,children:[c?"\u276F ":" ",V(Y,{color:ae,children:p+1})," ",T,H?V(Y,{color:c?ae:void 0,dimColor:!c,children:` \u2014 ${H}`}):null]},f)}}),V(Y,{dimColor:!0,children:`\u2191\u2193 choose \xB7 enter run \xB7 1-${fe.length} fill \xB7 esc cancel`})]}):V(De,{paddingX:1,children:ue(Y,{color:"gray",children:[Zp.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${yl??"model n/a"}${t.kind==="api"?Ur>0?` \xB7 session ${St(Ur)}`:"":Hp>0?` \xB7 ${ar(Hp)}`:""} \xB7 \u2191 history \xB7 ${lk?"press ctrl+c again to exit":"ctrl+c twice to exit"}`]})})]})}se();import{jsx as jN}from"react/jsx-runtime";async function nk(e=process.cwd(),t="auto",n,o="0.0.0"){let r=NN(t);r.kind==="none"&&(console.error(""),console.error(O("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${J("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${J("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=DN(jN(tk,{cwd:e,auth:r,profileName:n,version:o}),{exitOnCtrlC:!1});await s(),process.stdout.write(`
|
|
555
|
+
`),process.exit(0)}se();import{writeCrashLog as Ap,isBenignTransportError as IN}from"document360-engine";var ok=!1;function LN(e=process.stdout){return e.destroyed===!0||e.writable===!1}function Ep(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function rk(e){if(ok)return;ok=!0;let t=(n,o)=>{if(IN(o)){Ap({kind:n,level:"transport",message:Ep(o),stack:o instanceof Error?o.stack:void 0,detail:e}),LN()&&(Ap({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=Ap({kind:n,level:"fatal",message:Ep(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
|
|
555
556
|
`+O(`\u2717 d360-writer crashed: ${Ep(o)}`)+`
|
|
556
|
-
`),r&&process.stderr.write(
|
|
557
|
-
`+
|
|
558
|
-
`),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var _N
|
|
557
|
+
`),r&&process.stderr.write(g(` Crash details: ${r}`)+`
|
|
558
|
+
`+g(" Run: d360-writer logs")+`
|
|
559
|
+
`),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var FN=_N(import.meta.url),pl=FN("../package.json");rk("d360-writer");var Ht=new ON;function Dp(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}Ht.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=>{Dp(e),await gi({profile:e.profile,manual:e.manual})});Ht.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=>{Dp(e),await Eh({profile:e.profile,allProjects:e.allProjects})});Ht.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Dp(e),await Ah({profile:e.profile})});var Np=Ht.command("profile").description("Manage connection profiles for the current repo");Np.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>wi(process.cwd()));Np.command("use <name>").description("Set the default profile for this repo").action(e=>yi(process.cwd(),e));Np.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>bi(process.cwd(),e));var sk=Ht.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");sk.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>qo(process.cwd(),e.profile));sk.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await bh(process.cwd(),e,t.profile)});var ik=Ht.command("project").description("Choose the Document360 project for this repo (active profile's identity)");ik.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>fi(process.cwd(),e.profile));ik.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await $h(process.cwd(),e,t.profile)});Ht.command("init").description("Scaffold .d360-writer/config.json for this repo (interactive)").action(async()=>{let{initCommand:e}=await Promise.resolve().then(()=>(Ti(),pf));await e()});Ht.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(()=>Gl());Ht.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(()=>(va(),Fg)),n=await t(process.cwd(),pl.version);for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});Ht.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(pl.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(MN.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 _h(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 Wy(e.cwd,e.auth,e.profile,pl.version):await nk(e.cwd,e.auth,e.profile,pl.version)});Ht.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
|