document360-writer 0.5.244 → 0.5.246
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 +177 -177
- package/package.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var Gy=Object.defineProperty;var dr=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var Td=(e,t)=>{for(var n in t)Gy(e,n,{get:t[n],enumerable:!0})};import en from"picocolors";var ee,Vy,Yy,Ky,Ad,pr,y,j,G,V,z,$e,Ge,we,te=dr(()=>{"use strict";ee="#7f56d9",[Vy,Yy,Ky]=[127,86,217],Ad=e=>en.isColorSupported?`\x1B[38;2;${Vy};${Yy};${Ky}m${e}\x1B[39m`:e,pr=e=>en.bold(Ad(e)),y=e=>en.dim(e),j=e=>en.red(e),G=e=>en.yellow(e),V=e=>en.green(e),z=Ad,$e=e=>en.gray(e),Ge=e=>en.bold(e),we=(e,t)=>`${e} ${t}`});import{existsSync as ho,writeFileSync as rn,readFileSync as _w,readdirSync as Mw}from"node:fs";import{join as Qd}from"node:path";import{devHintsGuidePath as Is,hintsDir as Jd,hooksDir as Zd,architectureDir as op,messagesDir as La,creatorNotesPath as ep,devhintsStatePath as rp,directivesPath as tp,DIRECTIVES_HEADER as Fw,roadmapPath as np,ROADMAP_HEADER as Ww,ensureDir as mr,writeMessage as Uw,listOpenForDev as Bw,stampDone as Hw}from"document360-engine";function sp(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
|
|
3
3
|
|
|
4
4
|
<!-- devhints script v${Te} \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 Gw(){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 mo(e){mr(
|
|
253
|
-
`)}ho(
|
|
254
|
-
`)}function
|
|
255
|
-
`)}function Ft(e){try{return
|
|
256
|
-
`)}),n.notifiedBuilder=!0)}}catch{}return n}function
|
|
257
|
-
`)}function
|
|
252
|
+
`}function mo(e){mr(Jd(e)),mr(op(e)),mr(La(e));for(let n of[Jd(e),La(e)]){let o=Qd(n,".gitkeep");ho(o)||rn(o,`# Keeps this document360-writer inbox tracked in git even when empty.
|
|
253
|
+
`)}ho(ep(e))||rn(ep(e),Gw()),ho(tp(e))||rn(tp(e),Fw),ho(np(e))||rn(np(e),Ww),rn(Is(e),sp()),mr(Zd(e)),rn(Qd(Zd(e),"open-questions.mjs"),qw);let t=kt(e);return ap(e,new Date().toISOString()),t}async function ip(e,t){for(let n of go(mo(t.cwd)))console.log(n);return{kind:"continue"}}function Dn(){return[`This is document360-writer's dev hand-off setup (v${Te}).`,'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": ${Te},`,' "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 _a(e){try{let t=_w(rp(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function ap(e,t){let o={..._a(e)??{},emittedVersion:Te,emittedAt:t};rn(rp(e),`${JSON.stringify(o,null,2)}
|
|
255
|
+
`)}function Ft(e){try{return Mw(op(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function kt(e){let n=_a(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<Te?"stale":"current",completedVersion:n}}function Vw(e){let t=new RegExp(`${Oa.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(\\d+)\\)`).exec(e);return t?Number(t[1]):null}function Ls(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,supersededRequests:[],toVersion:Te};try{if(!ho(Is(e)))return n;let o=_a(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;if(Te>r&&(mr(La(e)),rn(Is(e),sp()),ap(e,t),n.guideRefreshed=!0),Te>s){let i=Bw(e).filter(l=>l.kind==="request"&&l.subject.startsWith(Oa)),a=i.filter(l=>(Vw(l.subject)??Te)>=Te);for(let l of i.filter(p=>!a.includes(p)))Hw(e,l.file,{doneAt:t,answeredBy:"docs"}),n.supersededRequests.push(l.subject);a.length===0&&(Uw(e,{id:`onb${Te}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${Oa}${Te})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${Te}${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:","",Dn()].join(`
|
|
256
|
+
`)}),n.notifiedBuilder=!0)}}catch{}return n}function Os(e){if(!ho(Is(e)))return[];let t=kt(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${Te}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,fo,Dn(),fo,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function Ma(){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 _s(){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):",fo,Ma(),fo]}function go(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${Te}.`," 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):",fo,Dn(),fo,"","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 fo,Te,qw,Oa,sn=dr(()=>{"use strict";fo="-".repeat(64),Te=12,qw=`#!/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,82 +292,82 @@ try {
|
|
|
292
292
|
} catch {
|
|
293
293
|
/* a session-start nudge must never break the session */
|
|
294
294
|
}
|
|
295
|
-
`;
|
|
296
|
-
`),"utf8")}async function Ua(){let e=process.cwd(),t=lp(e);if(yo(t)&&!await Gw({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(y("init cancelled.")),{kind:"continue"};let n=hp(e)??ip(e),o=await gr({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await gr({message:"Capture directory (where document360-capture .spec.ts files live):",default:up}),s=await gr({message:"Screenshot output directory:",default:dp}),i=await gr({message:"Default connection profile name:",default:"berlin"}),a=await gr({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),l={projectId:o,docsDir:cp,captureDir:r,outputDir:s,profiles:{[i]:{connection:{environment:a},production:!1}},defaultProfile:i,authoritativeSourceFiles:fp(e)},p=zw(e);p?.terminologyGlossary&&(l.terminologyGlossary=p.terminologyGlossary),ap(l,e),pp(e);let m=mo(e);console.log(""),console.log(V(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${z(`d360-writer login --profile ${i}`)} ${y("(sign in; project & workspace auto-selected)")}`),console.log("");for(let w of go(m))console.log(w);return console.log(""),console.log(`${y("Then ask:")} ${z('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function hp(e){let t=Fs(e,"package.json");if(!yo(t))return null;try{return JSON.parse(Vw(t,"utf8")).name??null}catch{return null}}function fp(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])yo(Fs(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Fs(e,n);yo(o)&&!Qw(o)&&t.push(n)}return t}function Qw(e){try{return Yw(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var Ws=dr(()=>{"use strict";ne();sn()});import{createRequire as bk}from"node:module";import{existsSync as $k,readFileSync as vk}from"node:fs";import{dirname as Up,join as Bp}from"node:path";function nt(){let e;try{e=xk.resolve("document360-capture/helpers")}catch{return null}let t=Up(e);for(let n=0;n<5&&!$k(Bp(t,"package.json"));n++)t=Up(t);try{let n=JSON.parse(vk(Bp(t,"package.json"),"utf8"));return n.name==="document360-capture"&&n.version?n.version:null}catch{return null}}var xk,$o=dr(()=>{"use strict";xk=bk(import.meta.url)});var Df={};Sd(Df,{doctorCommand:()=>Ir,renderDoctorChecks:()=>Ef,runDoctorChecks:()=>Af});import{existsSync as lv}from"node:fs";import{d360GetAll as cv,getAccessToken as uv,isExpired as bc,loadProfileMap as dv,loadTokens as pv,packageSkillsDir as Pf,ENGINE_VERSION as hv,projectConfigPath as fv,readProjectConfig as mv,DEFAULT_DOCS_DIR as gv,fetchManifestSummary as yv,resolveActiveProfile as wv,classifyClaudeAuth as kv,CLAUDE_CODE_SETUP_HINT as Tf,resolveModelSetting as bv,probeModel as $v,detectAppType as vv,playbookSkillName as xv,D360AuthError as Cv,applyStructureOrder as Rv}from"document360-engine";async function Af(e,t){let n=[],o=nt();n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${hv}${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=kv();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. ${Tf}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:Tf});let i=bv(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 R=await $v(e,i.model??void 0);R.ok?n.push({level:"ok",label:`Model reachable \u2014 replied in ${(R.latencyMs/1e3).toFixed(1)}s`}):R.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 ${R.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=mv(e);if(!a)return n.push({level:"fail",label:`No ${fv(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${a.projectId}`});let l=(a.docsDir??gv).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 p=a.authoritativeSourceFiles??[];n.push(p.length>0?{level:"ok",label:`Sources: docs grounded in ${p.length} path(s) (${p.slice(0,3).join(", ")}${p.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??vv(e);if(m){let R=a.appType?"from config":"auto-detected",S=m==="web"||m==="cli";n.push({level:"ok",label:`Genre: ${m} (${R})${S?` \u2192 ${xv(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=wv(e),n.push({level:"ok",label:`Profile: ${w.name} (${w.connection.name})${w.production?" \u26A0 PRODUCTION":""}`})}catch(R){return n.push({level:"fail",label:`Profile config: ${R.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let $=pv(w.name);$?bc($)&&!$.refreshToken?n.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):bc($)?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 (until ${new Date($.expiresAt).toLocaleString()})`}):n.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${w.name})`}),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 T=dv(e,w.name);T?T.projectId&&w.project.projectId&&T.projectId!==w.project.projectId?n.push({level:"fail",label:`Category map projectId (${T.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(T.articles).length} articles, ${Object.keys(T.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${w.name}" (created on first /push)`}),n.push(lv(Pf())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${Pf()}`,fix:"Reinstall document360-writer (broken install)"});let C=kt(e);if(C.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${Te})`}):C.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${C.completedVersion}, current is v${Te}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),$&&(!bc($)||$.refreshToken)){let R={profile:w.name,connection:w.connection};try{await uv(R);let E=await cv(R,"/v3/projects");n.push({level:"ok",label:`API reachable (${w.connection.apiUrl}) \u2014 ${E.length} project(s) visible`})}catch(E){n.push({level:"fail",label:`API call failed: ${E.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let S=T?.projectId??w.project.projectId;if(S&&w.project.workspaceId){try{let E=await yv(R,S,w.project.workspaceId);if(E){let I=(E.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Your Document360 project: reachable on ${w.connection.name} (${E.languages?.length??0} language${(E.languages?.length??0)===1?"":"s"}) \xB7 version ${I||"(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(E){E instanceof Cv||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(E.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${w.project.projectName??S})`,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 (${E.message.slice(0,80)})`})}try{let E=await Rv({cwd:e,profileName:w.name,dryRun:!0}),I=E.categoriesReordered+E.articlesReordered;if(E.skipped==="no category map")n.push({level:"ok",label:"Reading order: nothing to check yet (no articles published)"});else if(E.skipped)n.push({level:"warn",label:`Reading order: can't be checked (${E.skipped})`,fix:"Your article order on Document360 may not match your structure \u2014 /push syncs it once this resolves"});else if(E.unverified)n.push({level:"warn",label:`Reading order: ${E.unverified} of your articles aren't listed by Document360, so their order can't be set`,fix:"Usually means those articles are not live yet (the listing returns published articles). /publish takes them live, then /push re-syncs the order"});else if(I>0){let L=[E.categoriesReordered>0?`${E.categoriesReordered} categor${E.categoriesReordered===1?"y":"ies"}`:"",E.articlesReordered>0?`${E.articlesReordered} article${E.articlesReordered===1?"":"s"}`:""].filter(Boolean);n.push({level:"warn",label:`Reading order: ${L.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"})}catch(E){n.push({level:"warn",label:`Reading order: check failed (${E.message.slice(0,80)})`})}}}return n}function Ef(e){let t=[""];for(let r of e){let s=r.level==="ok"?V("\u2713"):r.level==="warn"?q("\u26A0"):j("\u2717");t.push(` ${s} ${r.label}${r.detail?y(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${y("fix:")} ${z(r.fix)}`)}let n=e.filter(r=>r.level==="fail").length,o=e.filter(r=>r.level==="warn").length;return t.push(""),t.push(n===0?V(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):j(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function Ir(e,t){console.log(y("Running checks\u2026"));for(let n of Ef(await Af(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var $i=dr(()=>{"use strict";sn();ne();$o()});import{Command as PP}from"commander";import{createRequire as TP}from"node:module";import{AUTH_MODES as AP}from"document360-engine";import{input as cw}from"@inquirer/prompts";import{loginPkce as uw,refreshTokens as dw,toStoredTokens as Id,clearTokens as pw,decodeJwtClaims as jd,isExpired as hw,loadTokens as fw,saveTokens as Ld,resolveActiveProfile as Ss,setProfileProject as mw,readProjectConfig as gw}from"document360-engine";ne();import{select as Yy}from"@inquirer/prompts";import{resolveActiveProfile as Ky,setProfileProject as zy,resolveProjectId as Xy,listWorkspaces as Qy}from"document360-engine";async function hr(e,t){let n=Ky(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Xy(o);return{workspaces:await Qy(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var Td=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function Aa(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 xs(e,t,n,o,r){zy(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function Ad(e,t,n){let o;try{o=await hr(e,n)}catch(s){return console.log(j(`Could not list workspaces: ${s.message}`)),1}let r=Aa(o.workspaces,t);return r?(xs(e,o.profile,o.projectId,r.id,r.name),console.log(V(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(j(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function po(e,t){let n;try{n=await hr(e,t)}catch(p){console.log(j(`Could not list workspaces: ${p.message}`));return}let{workspaces:o,projectId:r,profile:s,current:i}=n;if(o.length===0){console.log(y("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let p of o)console.log(` ${p.id===i?z("\u25CF"):" "} ${Td(p)} ${y(p.id)}`);console.log(y("Run: d360-writer workspace use <name>"));return}let a=await Yy({message:"Select the Document360 workspace for this repo:",choices:o.map(p=>({name:`${Td(p)}${p.id===i?" (current)":""}`,value:p.id}))}),l=o.find(p=>p.id===a);xs(e,s,r,a,l?.name),console.log(V(`\u2713 Workspace set to "${l?.name??a}" for profile "${s}".`))}ne();import{select as Jy}from"@inquirer/prompts";import{resolveActiveProfile as Zy,setProfileProject as ew,listProjects as tw}from"document360-engine";async function tn(e,t){let n=Zy(e,t),o={profile:n.name,connection:n.connection};return{projects:await tw(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var Ed=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Ea(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 Cs(e,t,n,o){ew(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function Dd(e,t,n){let o;try{o=await tn(e,n)}catch(s){return console.log(j(`Could not list projects: ${s.message}`)),1}let r=Ea(o.projects,t);return r?(Cs(e,o.profile,r.id,r.name),console.log(V(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log(j(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function Rs(e,t){let n;try{n=await tn(e,t)}catch(l){console.log(j(`Could not list projects: ${l.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(y("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let l of o)console.log(` ${l.id===s?z("\u25CF"):" "} ${Ed(l)} ${y(l.id)}`);console.log(y("Run: d360-writer project use <name>"));return}let i=await Jy({message:"Select the Document360 project for this repo:",choices:o.map(l=>({name:`${Ed(l)}${l.id===s?" (current)":""}`,value:l.id}))}),a=o.find(l=>l.id===i);Cs(e,r,i,a?.name),console.log(V(`\u2713 Project set to "${a?.name??i}" for profile "${r}". Next: pick a workspace.`))}ne();import nw from"picocolors";function ow(e=process.env){return e.FORCE_HYPERLINK==="0"||!nw.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 rw(e,t=e,n){return ow(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var sw=/https?:\/\/[^\s\x1b]+/g;function fr(e,t){return e.replace(sw,n=>rw(n,n,t))}import{readProjectConfig as Nd,sunsetEnvironment as iw,resolveActiveProfile as aw}from"document360-engine";function lw(e,t){let n=Nd(e);return Object.entries(n?.profiles??{}).find(([,o])=>(o.connection?.environment??"berlin")===t)?.[0]??null}function nn(e,t){try{if(!Nd(e))return null;let n=aw(e,t),o=iw(n.connection.name);if(!o)return null;let r=lw(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 Od(e){return{...jd(e.idToken)??{},...jd(e.accessToken)??{}}}function Ps(e){let t=Od(e),n=t.email??t.preferred_username??t.sub??"unknown",o=t.doc360_project_id?` \xB7 project ${t.doc360_project_id}`:"";return`${n}${o}`}async function Ts(e){let t=Ss(process.cwd(),e.profile),n=t.connection;console.log(y(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=nn(process.cwd(),e.profile);o&&(console.log(q(`\u26A0 ${o.why} \u2014 and signing in does NOT change it (the environment comes from the profile, not the login).`)),console.log(q(` To move: ${o.cmd}${o.replacementProfile?"":", then /login"}`)));let r=await uw(n,{manual:e.manual,promptForRedirect:i=>cw({message:i})},i=>console.log(fr(i))),s=Id(t.name,r);if(Ld(s),await Da(s,t.name,i=>console.log(y(i))),console.log(""),console.log(V(`\u2713 Logged in to "${t.name}" as ${Ps(s)}`)),console.log(y(` access token expires: ${s.expiresAt}`)),console.log(y(` refresh token: ${s.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{gw(process.cwd())?.profiles?.[t.name]&&(console.log(""),await po(process.cwd(),t.name))}catch{}}async function Da(e,t,n){let r=Od(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Ss(process.cwd(),t).project.projectId)return;let i;try{let{projects:a}=await tn(process.cwd(),t);i=a.find(l=>l.id===r)?.name}catch{}mw(process.cwd(),t,{projectId:r,projectName:i}),n(` Project "${i??r}" written to profile "${t}".`)}catch{}}async function _d(e){let t=Ss(process.cwd(),e.profile),n=t.connection,o=fw(t.name);if(!o){console.log(j(`Not logged in to Document360 (profile "${t.name}").`)),console.log(y(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${z(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Ps(o)}`),hw(o))if(o.refreshToken)try{let r=Id(t.name,await dw(n,o.refreshToken));Ld(r),console.log(V(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(q(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(y(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(q("Session expired (no refresh token).")),console.log(y(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(y(` expires: ${o.expiresAt}`))}async function Md(e){let t=Ss(process.cwd(),e.profile);pw(t.name)?console.log(V(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(y(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}ne();import{readProjectConfig as Fd,writeProjectConfig as yw,resolveActiveProfile as ww,loadTokens as kw,isExpired as bw}from"document360-engine";function As(e){let t=Fd(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(j("No profiles in .d360-writer/config.json. Run: d360-writer init")),process.exitCode=1;return}console.log("");for(let[n,o]of Object.entries(t.profiles)){let r=n===t.defaultProfile?z("\u25CF "):" ",s=o.production?q(" \u26A0 PRODUCTION"):"",i=o.connection.environment??"(inline)",a=kw(n),l=a?bw(a)&&!a.refreshToken?q("expired"):y("logged in"):y("not logged in");console.log(`${r}${z(n)} \u2192 ${i}${s} [${l}]`)}console.log(""),console.log(y("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function Es(e,t){let n=Fd(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(j(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,yw(n,e);let o=n.profiles[t].production?q(" \u26A0 PRODUCTION"):"";console.log(V(`\u2713 Default profile is now "${t}"${o}`))}function Ds(e,t){try{let n=ww(e,t);console.log(""),console.log(`Profile ${z(n.name)}${n.production?q(" \u26A0 PRODUCTION"):""}`),console.log(y(` api: ${n.connection.apiUrl}`)),console.log(y(` identity: ${n.connection.authorizationUrl}`)),console.log(y(` clientId: ${n.connection.clientId}`)),console.log(y(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(y(` project: ${n.project.projectId??"(set at login)"}`)),console.log(y(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(j(n.message)),process.exitCode=1}}ne();import{existsSync as $w,readdirSync as vw,statSync as Wd}from"node:fs";import{join as Ud}from"node:path";import{apiLogDir as xw}from"document360-engine";function Bd(){let e=xw();if(console.log(""),console.log(`Document360 API logs: ${z(e)}`),!$w(e)){console.log(y(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=vw(e),n=t.filter(r=>r.endsWith(".jsonl")).sort().reverse(),o=t.filter(r=>/^crash-\d{4}-\d{2}-\d{2}\.log$/.test(r)).sort().reverse();n.length===0&&o.length===0&&console.log(y(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let s=(Wd(Ud(e,r)).size/1024).toFixed(1);console.log(` ${r} ${y(`${s} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${y("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let s=(Wd(Ud(e,r)).size/1024).toFixed(1);console.log(` ${j(r)} ${y(`${s} KB`)}`)}}console.log(""),console.log(y("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(y("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}ne();import{createSession as Cw,resolveAuth as Rw,findByName as Sw,slugify as Pw,touchSession as Tw,upsertSession as Aw,resolveActiveProfile as Ew}from"document360-engine";async function Hd(e,t,n,o,r,s){let i=Rw(n);i.kind==="none"&&(console.error(""),console.error(j("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${z("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${z("d360-writer --auth subscription")}`),process.exit(2)),i.kind==="subscription"&&console.error(y("Using your Claude subscription (no API key set)."));let a=null;try{a=Ew(e,r)}catch($){console.error(j(`Document360 profile error: ${$.message}`)),process.exit(2)}a.production&&(console.error(q(`\u26A0 Profile "${a.name}" is PRODUCTION.`)),s||(console.error(j("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(y(" --yes given \u2014 proceeding against production.")));let l;if(o){let $=Sw(e,o);$||(console.error(j(`No saved session matches "${o}" in this repo.`)),console.error(y("List sessions inside the REPL with /resume.")),process.exit(2)),l=$.uuid,console.error(y(`Resuming "${$.name}"`))}let p=Cw({cwd:e,resume:l,profileName:r,allowProdWrites:s===!0}),m=l??null,w=1;for await(let $ of p.send(t))switch($.type){case"session":if(!m){m=$.sessionId;let T=new Date().toISOString();Aw({uuid:m,name:Pw(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:T,updatedAt:T})}break;case"text":process.stdout.write($.delta);break;case"tool":console.error(be(` \u2699 ${$.name}`));break;case"result":w=$.ok?0:1,console.error(y(`(${$.inputTokens}\u2192${$.outputTokens} tokens`+($.costUsd>0?`, $${$.costUsd<.01?$.costUsd.toFixed(4):$.costUsd.toFixed(2)}`:"")+")")),$.ok||console.error(j("agent finished with an error result"));break;case"error":console.error(""),console.error(j(`agent error: ${$.message}`)),process.exit(1)}m&&Tw(m),process.stdout.write(`
|
|
297
|
-
`),process.exit(w)}import{createInterface as
|
|
298
|
-
`)}var et=[{key:"start",label:"Getting Started",rows:[{t:"text",s:"D360-Writer reads your codebase, generates end-user documentation, and publishes it to Document360."},{t:"text",s:"It needs Claude access \u2014 a Claude subscription (default) or an ANTHROPIC_API_KEY."},{t:"gap"},{t:"sub",s:"Quick start"},{t:"step",n:1,s:"Run /init \u2014 pick your environment, sign in, choose your project & workspace. It ends by printing a one-paste hand-off prompt."},{t:"step",n:2,s:"Paste that prompt into your repo's coding agent (Claude Code / Codex / Cursor). Let it finish, then follow its closing line. (Re-show it: /devhints)"},{t:"step",n:3,s:"Run /doctor to confirm every check is green."},{t:"step",n:4,s:'Type "write the docs for this repository" and follow the prompts.'},{t:"gap"},{t:"dim",s:"That's it \u2014 D360-Writer drafts your docs without you writing a line."},{t:"gap"},{t:"sub",s:"Tips"},{t:"text",s:"Just talk to it \u2014 anything not starting with / goes to the agent."},{t:"dim",s:"/ browses commands \xB7 \u2191 recalls history \xB7 esc interrupts a run \xB7 ctrl+c exits"},{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:"/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."}]},{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:"/publish",s:"Take the drafts live to your readers, once they have been signed off."}]},{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."},{t:"cmd",name:"/project",s:"Choose the Document360 project."},{t:"cmd",name:"/workspace",s:"Switch the workspace."},{t:"cmd",name:"/scope",s:"Choose which repo folders back the docs (monorepos)."},{t:"cmd",name:"/devhints",s:"Re-show the builder hand-off prompt."},{t:"gap"},{t:"sub",s:"Agentic \u2014 keep docs in sync"},{t:"cmd",name:"/roadmap",s:"The docs campaign: progress + the next step (`done` marks the next step finished)."},{t:"cmd",name:"/catch-up",s:"Do all pending work \u2192 drafts (--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:"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. `pull` brings your Document360 project's own style guide down so the writer works to it; `compile` turns its 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. Deterministic, costs nothing to run; --fix has the agent correct what it found."},{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. 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."},{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."}]}],qd=24;function Na(e){let t=e.filter(n=>n.t==="cmd").map(n=>n.name.length);return t.length===0?qd:Math.min(qd,Math.max(...t))}function Is(e,t,n,o){let r=" ".repeat(2+n+1),s=Math.max(24,o-r.length-2),i=on(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 Dw(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=Is(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(`
|
|
299
|
-
`)}case"gap":return""}}function
|
|
295
|
+
`;Oa="Re-run dev\u2194docs onboarding (protocol v"});var yp={};Td(yp,{initCommand:()=>Wa,scaffoldInit:()=>Fa});import{input as gr,confirm as Yw}from"@inquirer/prompts";import{basename as lp,join as Ms}from"node:path";import{existsSync as yo,readFileSync as Kw,readdirSync as zw,writeFileSync as Xw}from"node:fs";import{writeProjectConfig as cp,readProjectConfig as Qw,projectConfigPath as up,writerDir as Jw,DEFAULT_DOCS_DIR as dp,DEFAULT_CAPTURE_DIR as pp,DEFAULT_OUTPUT_DIR as hp}from"document360-engine";function Fa(e,t="berlin"){let n=up(e);if(yo(n))return{created:!1,path:n,profileName:""};let o={projectId:mp(e)??lp(e),docsDir:dp,captureDir:pp,outputDir:hp,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:gp(e)};return cp(o,e),fp(e),{created:!0,path:n,profileName:t}}function fp(e){let t=Ms(Jw(e),".gitignore");yo(t)||Xw(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
|
|
296
|
+
`),"utf8")}async function Wa(){let e=process.cwd(),t=up(e);if(yo(t)&&!await Yw({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(y("init cancelled.")),{kind:"continue"};let n=mp(e)??lp(e),o=await gr({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await gr({message:"Capture directory (where document360-capture .spec.ts files live):",default:pp}),s=await gr({message:"Screenshot output directory:",default:hp}),i=await gr({message:"Default connection profile name:",default:"berlin"}),a=await gr({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),l={projectId:o,docsDir:dp,captureDir:r,outputDir:s,profiles:{[i]:{connection:{environment:a},production:!1}},defaultProfile:i,authoritativeSourceFiles:gp(e)},p=Qw(e);p?.terminologyGlossary&&(l.terminologyGlossary=p.terminologyGlossary),cp(l,e),fp(e);let m=mo(e);console.log(""),console.log(V(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${z(`d360-writer login --profile ${i}`)} ${y("(sign in; project & workspace auto-selected)")}`),console.log("");for(let w of go(m))console.log(w);return console.log(""),console.log(`${y("Then ask:")} ${z('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function mp(e){let t=Ms(e,"package.json");if(!yo(t))return null;try{return JSON.parse(Kw(t,"utf8")).name??null}catch{return null}}function gp(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])yo(Ms(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Ms(e,n);yo(o)&&!Zw(o)&&t.push(n)}return t}function Zw(e){try{return zw(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var Fs=dr(()=>{"use strict";te();sn()});import{createRequire as vk}from"node:module";import{existsSync as xk,readFileSync as Rk}from"node:fs";import{dirname as Hp,join as qp}from"node:path";function nt(){let e;try{e=Ck.resolve("document360-capture/helpers")}catch{return null}let t=Hp(e);for(let n=0;n<5&&!xk(qp(t,"package.json"));n++)t=Hp(t);try{let n=JSON.parse(Rk(qp(t,"package.json"),"utf8"));return n.name==="document360-capture"&&n.version?n.version:null}catch{return null}}var Ck,$o=dr(()=>{"use strict";Ck=vk(import.meta.url)});var jf={};Td(jf,{doctorCommand:()=>Ir,renderDoctorChecks:()=>Nf,runDoctorChecks:()=>Df});import{existsSync as pv}from"node:fs";import{d360GetAll as hv,getAccessToken as fv,isExpired as kc,loadProfileMap as mv,loadTokens as gv,packageSkillsDir as Af,ENGINE_VERSION as yv,projectConfigPath as wv,readProjectConfig as kv,DEFAULT_DOCS_DIR as bv,fetchManifestSummary as $v,resolveActiveProfile as vv,classifyClaudeAuth as xv,CLAUDE_CODE_SETUP_HINT as Ef,resolveModelSetting as Rv,probeModel as Cv,detectAppType as Sv,playbookSkillName as Pv,D360AuthError as Tv,applyStructureOrder as Av}from"document360-engine";async function Df(e,t){let n=[],o=nt();n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${yv}${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=xv();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. ${Ef}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:Ef});let i=Rv(e);if(n.push({level:"ok",label:`Model: ${i.model} (${i.source==="auto"?"auto \u2014 right-sized for docs; /model to change":i.source})`}),s.state==="ready"){let C=await Cv(e,i.model??void 0);C.ok?n.push({level:"ok",label:`Model reachable \u2014 replied in ${(C.latencyMs/1e3).toFixed(1)}s`}):C.timedOut?n.push({level:"fail",label:"Model unreachable \u2014 no response in 30s (a docs turn will hang, then end with 0 tokens / no output)",fix:`Usually a corporate proxy/firewall or org policy blocking the Claude model API. Check this machine's network access to the Claude endpoint; confirm with: claude -p "say hi"`}):n.push({level:"fail",label:`Model call failed \u2014 ${C.error??"no output"} (a docs turn will end with 0 tokens / no output)`,fix:'Check sign-in, the selected model (/model), and network access to the Claude endpoint; confirm with: claude -p "say hi"'})}let a=kv(e);if(!a)return n.push({level:"fail",label:`No ${wv(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${a.projectId}`});let l=(a.docsDir??bv).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 p=a.authoritativeSourceFiles??[];n.push(p.length>0?{level:"ok",label:`Sources: docs grounded in ${p.length} path(s) (${p.slice(0,3).join(", ")}${p.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??Sv(e);if(m){let C=a.appType?"from config":"auto-detected",S=m==="web"||m==="cli";n.push({level:"ok",label:`Genre: ${m} (${C})${S?` \u2192 ${Pv(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=vv(e),n.push({level:"ok",label:`Profile: ${w.name} (${w.connection.name})${w.production?" \u26A0 PRODUCTION":""}`})}catch(C){return n.push({level:"fail",label:`Profile config: ${C.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let $=gv(w.name);$?kc($)&&!$.refreshToken?n.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):kc($)?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 (until ${new Date($.expiresAt).toLocaleString()})`}):n.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${w.name})`}),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 T=mv(e,w.name);T?T.projectId&&w.project.projectId&&T.projectId!==w.project.projectId?n.push({level:"fail",label:`Category map projectId (${T.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(T.articles).length} articles, ${Object.keys(T.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${w.name}" (created on first /push)`}),n.push(pv(Af())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${Af()}`,fix:"Reinstall document360-writer (broken install)"});let R=kt(e);if(R.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${Te})`}):R.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${R.completedVersion}, current is v${Te}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),$&&(!kc($)||$.refreshToken)){let C={profile:w.name,connection:w.connection};try{await fv(C);let E=await hv(C,"/v3/projects");n.push({level:"ok",label:`API reachable (${w.connection.apiUrl}) \u2014 ${E.length} project(s) visible`})}catch(E){n.push({level:"fail",label:`API call failed: ${E.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let S=T?.projectId??w.project.projectId;if(S&&w.project.workspaceId){try{let E=await $v(C,S,w.project.workspaceId);if(E){let I=(E.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Your Document360 project: reachable on ${w.connection.name} (${E.languages?.length??0} language${(E.languages?.length??0)===1?"":"s"}) \xB7 version ${I||"(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(E){E instanceof Tv||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(E.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${w.project.projectName??S})`,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 (${E.message.slice(0,80)})`})}try{let E=await Av({cwd:e,profileName:w.name,dryRun:!0}),I=E.categoriesReordered+E.articlesReordered;if(E.skipped==="no category map")n.push({level:"ok",label:"Reading order: nothing to check yet (no articles published)"});else if(E.skipped)n.push({level:"warn",label:`Reading order: can't be checked (${E.skipped})`,fix:"Your article order on Document360 may not match your structure \u2014 /push syncs it once this resolves"});else if(E.unverified)n.push({level:"warn",label:`Reading order: ${E.unverified} of your articles aren't listed by Document360, so their order can't be set`,fix:"Usually means those articles are not live yet (the listing returns published articles). /publish takes them live, then /push re-syncs the order"});else if(I>0){let L=[E.categoriesReordered>0?`${E.categoriesReordered} categor${E.categoriesReordered===1?"y":"ies"}`:"",E.articlesReordered>0?`${E.articlesReordered} article${E.articlesReordered===1?"":"s"}`:""].filter(Boolean);n.push({level:"warn",label:`Reading order: ${L.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"})}catch(E){n.push({level:"warn",label:`Reading order: check failed (${E.message.slice(0,80)})`})}}}return n}function Nf(e){let t=[""];for(let r of e){let s=r.level==="ok"?V("\u2713"):r.level==="warn"?G("\u26A0"):j("\u2717");t.push(` ${s} ${r.label}${r.detail?y(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${y("fix:")} ${z(r.fix)}`)}let n=e.filter(r=>r.level==="fail").length,o=e.filter(r=>r.level==="warn").length;return t.push(""),t.push(n===0?V(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):j(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function Ir(e,t){console.log(y("Running checks\u2026"));for(let n of Nf(await Df(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var bi=dr(()=>{"use strict";sn();te();$o()});import{Command as NP}from"commander";import{createRequire as jP}from"node:module";import{AUTH_MODES as IP}from"document360-engine";import{input as dw}from"@inquirer/prompts";import{loginPkce as pw,refreshTokens as hw,toStoredTokens as Od,clearTokens as fw,decodeJwtClaims as Ld,isExpired as mw,loadTokens as gw,saveTokens as _d,resolveActiveProfile as Cs,setProfileProject as yw,readProjectConfig as ww}from"document360-engine";te();import{select as zy}from"@inquirer/prompts";import{resolveActiveProfile as Xy,setProfileProject as Qy,resolveProjectId as Jy,listWorkspaces as Zy}from"document360-engine";async function hr(e,t){let n=Xy(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Jy(o);return{workspaces:await Zy(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var Ed=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function Ta(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 vs(e,t,n,o,r){Qy(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function Dd(e,t,n){let o;try{o=await hr(e,n)}catch(s){return console.log(j(`Could not list workspaces: ${s.message}`)),1}let r=Ta(o.workspaces,t);return r?(vs(e,o.profile,o.projectId,r.id,r.name),console.log(V(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(j(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function po(e,t){let n;try{n=await hr(e,t)}catch(p){console.log(j(`Could not list workspaces: ${p.message}`));return}let{workspaces:o,projectId:r,profile:s,current:i}=n;if(o.length===0){console.log(y("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let p of o)console.log(` ${p.id===i?z("\u25CF"):" "} ${Ed(p)} ${y(p.id)}`);console.log(y("Run: d360-writer workspace use <name>"));return}let a=await zy({message:"Select the Document360 workspace for this repo:",choices:o.map(p=>({name:`${Ed(p)}${p.id===i?" (current)":""}`,value:p.id}))}),l=o.find(p=>p.id===a);vs(e,s,r,a,l?.name),console.log(V(`\u2713 Workspace set to "${l?.name??a}" for profile "${s}".`))}te();import{select as ew}from"@inquirer/prompts";import{resolveActiveProfile as tw,setProfileProject as nw,listProjects as ow}from"document360-engine";async function tn(e,t){let n=tw(e,t),o={profile:n.name,connection:n.connection};return{projects:await ow(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var Nd=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Aa(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 xs(e,t,n,o){nw(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function jd(e,t,n){let o;try{o=await tn(e,n)}catch(s){return console.log(j(`Could not list projects: ${s.message}`)),1}let r=Aa(o.projects,t);return r?(xs(e,o.profile,r.id,r.name),console.log(V(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log(j(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function Rs(e,t){let n;try{n=await tn(e,t)}catch(l){console.log(j(`Could not list projects: ${l.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(y("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let l of o)console.log(` ${l.id===s?z("\u25CF"):" "} ${Nd(l)} ${y(l.id)}`);console.log(y("Run: d360-writer project use <name>"));return}let i=await ew({message:"Select the Document360 project for this repo:",choices:o.map(l=>({name:`${Nd(l)}${l.id===s?" (current)":""}`,value:l.id}))}),a=o.find(l=>l.id===i);xs(e,r,i,a?.name),console.log(V(`\u2713 Project set to "${a?.name??i}" for profile "${r}". Next: pick a workspace.`))}te();import rw from"picocolors";function sw(e=process.env){return e.FORCE_HYPERLINK==="0"||!rw.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 iw(e,t=e,n){return sw(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var aw=/https?:\/\/[^\s\x1b]+/g;function fr(e,t){return e.replace(aw,n=>iw(n,n,t))}import{readProjectConfig as Id,sunsetEnvironment as lw,resolveActiveProfile as cw}from"document360-engine";function uw(e,t){let n=Id(e);return Object.entries(n?.profiles??{}).find(([,o])=>(o.connection?.environment??"berlin")===t)?.[0]??null}function nn(e,t){try{if(!Id(e))return null;let n=cw(e,t),o=lw(n.connection.name);if(!o)return null;let r=uw(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 Md(e){return{...Ld(e.idToken)??{},...Ld(e.accessToken)??{}}}function Ss(e){let t=Md(e),n=t.email??t.preferred_username??t.sub??"unknown",o=t.doc360_project_id?` \xB7 project ${t.doc360_project_id}`:"";return`${n}${o}`}async function Ps(e){let t=Cs(process.cwd(),e.profile),n=t.connection;console.log(y(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=nn(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 pw(n,{manual:e.manual,promptForRedirect:i=>dw({message:i})},i=>console.log(fr(i))),s=Od(t.name,r);if(_d(s),await Ea(s,t.name,i=>console.log(y(i))),console.log(""),console.log(V(`\u2713 Logged in to "${t.name}" as ${Ss(s)}`)),console.log(y(` access token expires: ${s.expiresAt}`)),console.log(y(` refresh token: ${s.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{ww(process.cwd())?.profiles?.[t.name]&&(console.log(""),await po(process.cwd(),t.name))}catch{}}async function Ea(e,t,n){let r=Md(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Cs(process.cwd(),t).project.projectId)return;let i;try{let{projects:a}=await tn(process.cwd(),t);i=a.find(l=>l.id===r)?.name}catch{}yw(process.cwd(),t,{projectId:r,projectName:i}),n(` Project "${i??r}" written to profile "${t}".`)}catch{}}async function Fd(e){let t=Cs(process.cwd(),e.profile),n=t.connection,o=gw(t.name);if(!o){console.log(j(`Not logged in to Document360 (profile "${t.name}").`)),console.log(y(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${z(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Ss(o)}`),mw(o))if(o.refreshToken)try{let r=Od(t.name,await hw(n,o.refreshToken));_d(r),console.log(V(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(G(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(y(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(G("Session expired (no refresh token).")),console.log(y(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(y(` expires: ${o.expiresAt}`))}async function Wd(e){let t=Cs(process.cwd(),e.profile);fw(t.name)?console.log(V(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(y(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}te();import{readProjectConfig as Ud,writeProjectConfig as kw,resolveActiveProfile as bw,loadTokens as $w,isExpired as vw}from"document360-engine";function Ts(e){let t=Ud(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(j("No profiles in .d360-writer/config.json. Run: d360-writer init")),process.exitCode=1;return}console.log("");for(let[n,o]of Object.entries(t.profiles)){let r=n===t.defaultProfile?z("\u25CF "):" ",s=o.production?G(" \u26A0 PRODUCTION"):"",i=o.connection.environment??"(inline)",a=$w(n),l=a?vw(a)&&!a.refreshToken?G("expired"):y("logged in"):y("not logged in");console.log(`${r}${z(n)} \u2192 ${i}${s} [${l}]`)}console.log(""),console.log(y("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function As(e,t){let n=Ud(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(j(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,kw(n,e);let o=n.profiles[t].production?G(" \u26A0 PRODUCTION"):"";console.log(V(`\u2713 Default profile is now "${t}"${o}`))}function Es(e,t){try{let n=bw(e,t);console.log(""),console.log(`Profile ${z(n.name)}${n.production?G(" \u26A0 PRODUCTION"):""}`),console.log(y(` api: ${n.connection.apiUrl}`)),console.log(y(` identity: ${n.connection.authorizationUrl}`)),console.log(y(` clientId: ${n.connection.clientId}`)),console.log(y(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(y(` project: ${n.project.projectId??"(set at login)"}`)),console.log(y(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(j(n.message)),process.exitCode=1}}te();import{existsSync as xw,readdirSync as Rw,statSync as Bd}from"node:fs";import{join as Hd}from"node:path";import{apiLogDir as Cw}from"document360-engine";function qd(){let e=Cw();if(console.log(""),console.log(`Document360 API logs: ${z(e)}`),!xw(e)){console.log(y(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Rw(e),n=t.filter(r=>r.endsWith(".jsonl")).sort().reverse(),o=t.filter(r=>/^crash-\d{4}-\d{2}-\d{2}\.log$/.test(r)).sort().reverse();n.length===0&&o.length===0&&console.log(y(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let s=(Bd(Hd(e,r)).size/1024).toFixed(1);console.log(` ${r} ${y(`${s} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${y("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let s=(Bd(Hd(e,r)).size/1024).toFixed(1);console.log(` ${j(r)} ${y(`${s} KB`)}`)}}console.log(""),console.log(y("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(y("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}te();import{createSession as Sw,resolveAuth as Pw,findByName as Tw,slugify as Aw,touchSession as Ew,upsertSession as Dw,resolveActiveProfile as Nw}from"document360-engine";async function Gd(e,t,n,o,r,s){let i=Pw(n);i.kind==="none"&&(console.error(""),console.error(j("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${z("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${z("d360-writer --auth subscription")}`),process.exit(2)),i.kind==="subscription"&&console.error(y("Using your Claude subscription (no API key set)."));let a=null;try{a=Nw(e,r)}catch($){console.error(j(`Document360 profile error: ${$.message}`)),process.exit(2)}a.production&&(console.error(G(`\u26A0 Profile "${a.name}" is PRODUCTION.`)),s||(console.error(j("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(y(" --yes given \u2014 proceeding against production.")));let l;if(o){let $=Tw(e,o);$||(console.error(j(`No saved session matches "${o}" in this repo.`)),console.error(y("List sessions inside the REPL with /resume.")),process.exit(2)),l=$.uuid,console.error(y(`Resuming "${$.name}"`))}let p=Sw({cwd:e,resume:l,profileName:r,allowProdWrites:s===!0}),m=l??null,w=1;for await(let $ of p.send(t))switch($.type){case"session":if(!m){m=$.sessionId;let T=new Date().toISOString();Dw({uuid:m,name:Aw(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:T,updatedAt:T})}break;case"text":process.stdout.write($.delta);break;case"tool":console.error($e(` \u2699 ${$.name}`));break;case"result":w=$.ok?0:1,console.error(y(`(${$.inputTokens}\u2192${$.outputTokens} tokens`+($.costUsd>0?`, $${$.costUsd<.01?$.costUsd.toFixed(4):$.costUsd.toFixed(2)}`:"")+")")),$.ok||console.error(j("agent finished with an error result"));break;case"error":console.error(""),console.error(j(`agent error: ${$.message}`)),process.exit(1)}m&&Ew(m),process.stdout.write(`
|
|
297
|
+
`),process.exit(w)}import{createInterface as wC}from"node:readline/promises";import{createSession as xu,resolveAuth as kC,getSession as bC,setTitle as $C,slugify as vC,touchSession as fg,upsertSession as xC,generateTitle as RC,resolveActiveProfile as mg,resolveModelSetting as CC,readProjectConfig as SC,readUserConfig as PC,resolveAndPersistAppType as TC,decodeJwtClaims as pg,isExpired as AC,loadTokens as EC,isDirectiveMention as DC,stripDirectiveMention as NC,appendDirective as jC,reconcileUpgradeActions as IC,stampArticles as LC,snapshotArticles as OC,listArticleFiles as _C,applyStructureOrder as MC,orderSyncLine as FC,computeSyncStatus as WC}from"document360-engine";import{ENGINE_VERSION as Lw}from"document360-engine";function on(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 Ds(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 on(`${i+1}. ${s.feature}`,76))o.push(n(a));o.push(n());for(let a of on(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 Ns(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(`
|
|
298
|
+
`)}var et=[{key:"start",label:"Getting Started",rows:[{t:"text",s:"D360-Writer reads your codebase, generates end-user documentation, and publishes it to Document360."},{t:"text",s:"It needs Claude access \u2014 a Claude subscription (default) or an ANTHROPIC_API_KEY."},{t:"gap"},{t:"sub",s:"Quick start"},{t:"step",n:1,s:"Run /init \u2014 pick your environment, sign in, choose your project & workspace. It ends by printing a one-paste hand-off prompt."},{t:"step",n:2,s:"Paste that prompt into your repo's coding agent (Claude Code / Codex / Cursor). Let it finish, then follow its closing line. (Re-show it: /devhints)"},{t:"step",n:3,s:"Run /doctor to confirm every check is green."},{t:"step",n:4,s:'Type "write the docs for this repository" and follow the prompts.'},{t:"gap"},{t:"dim",s:"That's it \u2014 D360-Writer drafts your docs without you writing a line."},{t:"gap"},{t:"sub",s:"Tips"},{t:"text",s:"Just talk to it \u2014 anything not starting with / goes to the agent."},{t:"dim",s:"/ browses commands \xB7 \u2191 recalls history \xB7 esc interrupts a run \xB7 ctrl+c exits"},{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:"/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."}]},{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:"/publish",s:"Take the drafts live to your readers, once they have been signed off."}]},{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."},{t:"cmd",name:"/project",s:"Choose the Document360 project."},{t:"cmd",name:"/workspace",s:"Switch the workspace."},{t:"cmd",name:"/scope",s:"Choose which repo folders back the docs (monorepos)."},{t:"cmd",name:"/devhints",s:"Re-show the builder hand-off prompt."},{t:"gap"},{t:"sub",s:"Agentic \u2014 keep docs in sync"},{t:"cmd",name:"/roadmap",s:"The docs campaign: progress + the next step (`done` marks the next step finished)."},{t:"cmd",name:"/catch-up",s:"Do all pending work \u2192 drafts (--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:"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. `pull` brings your Document360 project's own style guide down so the writer works to it; `compile` turns its 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. Deterministic, costs nothing to run; --fix has the agent correct what it found."},{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. 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."},{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."}]}],Vd=24;function Da(e){let t=e.filter(n=>n.t==="cmd").map(n=>n.name.length);return t.length===0?Vd:Math.min(Vd,Math.max(...t))}function js(e,t,n,o){let r=" ".repeat(2+n+1),s=Math.max(24,o-r.length-2),i=on(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 jw(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=js(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(`
|
|
299
|
+
`)}case"gap":return""}}function Yd(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 et){n.push(`\u2500\u2500 ${o.label} \u2500\u2500`,"");let r=Da(o.rows);for(let s of o.rows)n.push(jw(s,r,100));n.push("")}return n.push("Tip: anything not starting with / goes to the agent."),n}function Na(e,t){return on(e,Math.max(10,Math.max(20,t)-2))}function Iw(e,t,n){let o=Math.max(20,n),r=s=>Math.max(1,Na(s,o).length);switch(e.t){case"gap":return 1;case"cmd":{let s=js(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 Kd(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=Iw(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 zd(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 ja(e=[],t){console.log("");let n=t?.version?{version:t.version,engineVersion:Lw}:void 0;for(let o of Yd(n))console.log(o);return console.log(""),console.log("Reporting a problem? Run `d360-writer logs` for the API log files."),console.log(""),{kind:"continue"}}te();import{getSession as Ow}from"document360-engine";async function Xd(e,t){let n=t.currentUuid(),o=n?Ow(n):void 0;return console.log(o?y(`
|
|
300
300
|
(conversation reset \u2014 "${o.name}" is still available via /resume)
|
|
301
301
|
`):y(`
|
|
302
302
|
(conversation reset \u2014 agent will start fresh on the next prompt)
|
|
303
|
-
`)),{kind:"clear"}}async function
|
|
303
|
+
`)),{kind:"clear"}}async function Ia(){return{kind:"exit"}}Fs();te();import{readMcpConfig as Ua,writeMcpConfig as wp}from"document360-engine";async function Ws(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(ek(),{kind:"continue"}):t==="add"?(tk(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(nk(e.slice(1)),{kind:"continue"}):(console.log(j(`Unknown /mcp subcommand: ${t}`)),console.log(y("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function ek(){let e=Ua(),t=Object.keys(e.servers);if(t.length===0){console.log(y(`
|
|
304
304
|
No MCP servers registered. Add one with /mcp add <name> <type> <ref>
|
|
305
|
-
`));return}console.log(""),console.log("Registered MCP servers (~/.document360-writer/mcp.json):");for(let n of t){let o=e.servers[n];if(o.type==="stdio")console.log(` ${z(n)} ${y("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?y(` [headers: ${r.join(", ")}]`):"";console.log(` ${z(n)} ${y(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function Zw(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(j("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(j(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=Ba(),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],p=l?.match(/^([^:=]+)[:=](.+)$/);if(!p){console.log(j(`-H expects key:value (no spaces). Got: ${l??"(nothing)"}`));return}i[p[1].trim()]=p[2].trim()}else{console.log(j(`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,gp(r),console.log(""),console.log(V(`\u2713 Registered "${t}" (${n})`)),console.log(q(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(y(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function ek(e){let t=e[0];if(!t){console.log(j("Usage: /mcp remove <name>"));return}let n=Ba();if(!n.servers[t]){console.log(j(`No server named "${t}".`));return}delete n.servers[t],gp(n),console.log(V(`\u2713 Removed "${t}".`)),console.log(y(" Run /clear to drop it from the current session immediately."))}ne();import{readFileSync as pb}from"node:fs";import{join as hb}from"node:path";import{select as fb}from"@inquirer/prompts";import{computeSyncStatus as si,planPartitions as mb,relatedArticlePaths as gb,resolveModelForOperation as yb,runPartitioned as wb,loadProfileMap as $h,draftPendingPaths as kb,resolveActiveProfile as wl,unreviewedPaths as bb,styleErrorPaths as vh,publishGateVerdict as $b,publishGateLines as vb,SKIP_STYLE_FLAG as xb,listArticleFiles as xh,ensureFeedbackChannel as Cb,FEEDBACK_CATEGORY_NAME as Rb,resolveCrossLinks as Sb,applyStructureOrder as Ch,orderSyncLine as Rh,applyRelatedArticles as Sh,relatedSyncLine as Ph}from"document360-engine";import{readFileSync as tk}from"node:fs";import{resolve as nk}from"node:path";import{prettyFolderName as yp}from"document360-engine";var wo=yp;function wp(e){return e.replace(/\\/g,"/").split("/").slice(0,-1).join("/")}function Ha(e){let t=e.replace(/\\/g,"/").split("/").pop()??e;return yp(t.replace(/\.md$/i,""))}function kp(e,t){try{return/^#\s+(.+)$/m.exec(tk(nk(e,t),"utf8"))?.[1]?.trim()??null}catch{return null}}import pe from"picocolors";import Ka from"wrap-ansi";import za from"string-width";ne();import an from"picocolors";import Hs from"wrap-ansi";import Bs from"string-width";var ko=[{name:"init",usage:"/init",desc:"Pick an environment, scaffold .d360-writer/config.json, and set up the builder hand-off (prints the one-paste prompt)",group:"start"},{name:"login",usage:"/login",desc:"Sign in to Document360 (browser)",group:"start"},{name:"project",usage:"/project [name]",desc:"Choose the Document360 project (picker; lists all you can access)",group:"start"},{name:"devhints",usage:"/devhints",desc:"Re-show/refresh the builder hand-off prompt (set up by /init; run anytime to hand your repo agent the latest)",group:"start"},{name:"scope",usage:"/scope",desc:"Choose which repo folders back the docs (monorepos)",group:"start"},{name:"genre",usage:"/genre [web|cli|service|library|auto]",desc:"Set/show the product genre \u2014 picks the docs craft playbook (usually auto-detected; set it if it guessed wrong)",group:"start"},{name:"mcp",usage:"/mcp [list|add|remove]",desc:"Connect MCP servers (Notion, Linear, \u2026)",group:"start"},{name:"discover",usage:"/discover",desc:"Interview your builder to understand the product (identity, mental model, misconceptions, positioning) \u2192 pins a product brief that grounds the docs; asks focused questions and loops until confident",group:"docs"},{name:"draft",usage:"/draft [<feature>]",desc:"Draft a feature's articles from its PRDs/specs in .d360-writer/input/ + the code",group:"docs"},{name:"document",usage:"/document [<what>] [--push]",desc:"Document a shipped change \u2014 the agent picks the action (new section/article/update); bare: act on builder requests. --push then saves the result to Document360 as drafts, which still needs an editorial review first",group:"docs"},{name:"write",usage:"/write [--preview|--scope <cat>|<path>] [--rewrite] [--concurrency N] [--skip-style]",desc:"Write the planned articles in parallel (starts immediately; --preview shows plan + cost first; --rewrite regenerates already-written articles; --concurrency default 3). Anything that would block publishing is corrected in one automatic pass before the run finishes; --skip-style leaves it to /lint",group:"docs"},{name:"screenshot",usage:"/screenshot [author|capture|annotate|verify|checklist|list] [id|path|--all|--failed|--blocked]",desc:"Screenshots, one family \u2014 bare: pick what to do; author: write capture specs; capture: take the shots (--all re-shoots everything; --failed re-runs the ones that did not work; --blocked re-runs the ones waiting on app data); annotate: draw the callouts on shots already taken, no browser needed (--all --force re-draws after a wording or style change); verify: judge the finished pictures and mark them verified (both run automatically after a capture); checklist: what to stage + dev test-id requests; list: status + what to stage",group:"docs"},{name:"preview",usage:"/preview [path|id]",desc:"Render an article (no arg: pick from tracked)",group:"docs"},{name:"push",usage:"/push [path|--all|[<category>] --screenshots] [--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). 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> | pull [<n>] | 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); pull: bring your Document360 project's own style guide down; 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>] [--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; --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] [--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; --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:"roadmap",usage:"/roadmap [done [step]]",desc:"Show the docs campaign (the multi-session plan the agent maintains) \u2014 progress + next step; `done` marks the next open step finished (add words from a title to pick another)",group:"docs"},{name:"audit",usage:"/audit [--auto on|off]",desc:"Gap analysis: code vs docs vs Document360 (what changed); --auto runs it at launch when code changed",group:"publish"},{name:"inbox",usage:"/inbox",desc:"Act on messages from the repo's coding agent (requests to document, answers to your questions)",group:"publish"},{name:"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",desc:"Sign out + clear project/workspace selection (then /login to re-pick)",group:"setup"},{name:"allow-prod",usage:"/allow-prod",desc:"Authorize writes to a production profile",group:"setup"},{name:"doctor",usage:"/doctor",desc:"Health-check: auth, profile, workspace, map, API",group:"setup"},{name:"update",usage:"/update",desc:"Update d360-writer \u2014 and d360-capture when installed \u2014 to the latest versions (then relaunch)",group:"setup"},{name:"feedback",usage:"/feedback",desc:"Copy the repo's open d360-writer tool-feedback to your clipboard, to relay to the d360-writer team",group:"setup"},{name:"reset",usage:"/reset",desc:"[DANGER] Delete all d360-writer files (docs, config, screenshots); types repo name to confirm",group:"setup"},{name:"resume",usage:"/resume [name]",desc:"Resume a session (no arg lists them)",group:"session"},{name:"rename",usage:"/rename [name]",desc:"Name the session (no arg: suggest one)",group:"session"},{name:"clear",usage:"/clear",desc:"Clear the screen + reset the conversation (resumable)",group:"session"},{name:"help",usage:"/help",desc:"Show this help",group:"session"},{name:"exit",usage:"/exit",desc:"Quit",group:"session"}],bp={"/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","/style-guide":"choose the writing rules your docs are held to","/lint":"check the docs against those rules (costs nothing)"};function $p(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(bp[n])return bp[n];let o=ko.find(r=>r.name===t);return o?o.desc:""}function vp(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return ko.filter(n=>n.name.startsWith(t))}function xp(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 ok=new RegExp(`^\\s*/(?:${ko.map(e=>e.name).join("|")})(?:\\s|$)`),Cp=e=>ok.test(e),Rp=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Sp=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),Pp=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function rk(e){let t=e.replace(/\r/g,"").split(`
|
|
306
|
-
`),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(
|
|
307
|
-
`).map(E=>
|
|
305
|
+
`));return}console.log(""),console.log("Registered MCP servers (~/.document360-writer/mcp.json):");for(let n of t){let o=e.servers[n];if(o.type==="stdio")console.log(` ${z(n)} ${y("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?y(` [headers: ${r.join(", ")}]`):"";console.log(` ${z(n)} ${y(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function tk(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(j("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(j(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=Ua(),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],p=l?.match(/^([^:=]+)[:=](.+)$/);if(!p){console.log(j(`-H expects key:value (no spaces). Got: ${l??"(nothing)"}`));return}i[p[1].trim()]=p[2].trim()}else{console.log(j(`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,wp(r),console.log(""),console.log(V(`\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(y(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function nk(e){let t=e[0];if(!t){console.log(j("Usage: /mcp remove <name>"));return}let n=Ua();if(!n.servers[t]){console.log(j(`No server named "${t}".`));return}delete n.servers[t],wp(n),console.log(V(`\u2713 Removed "${t}".`)),console.log(y(" Run /clear to drop it from the current session immediately."))}te();import{readFileSync as fb}from"node:fs";import{join as mb}from"node:path";import{select as gb}from"@inquirer/prompts";import{computeSyncStatus as ri,planPartitions as yb,relatedArticlePaths as wb,resolveModelForOperation as kb,runPartitioned as bb,loadProfileMap as xh,draftPendingPaths as $b,resolveActiveProfile as yl,unreviewedPaths as vb,styleErrorPaths as Rh,publishGateVerdict as xb,publishGateLines as Rb,SKIP_STYLE_FLAG as Cb,listArticleFiles as Ch,ensureFeedbackChannel as Sb,FEEDBACK_CATEGORY_NAME as Pb,resolveCrossLinks as Tb,applyStructureOrder as Sh,orderSyncLine as Ph,applyRelatedArticles as Th,relatedSyncLine as Ah}from"document360-engine";import{readFileSync as ok}from"node:fs";import{resolve as rk}from"node:path";import{prettyFolderName as kp}from"document360-engine";var wo=kp;function bp(e){return e.replace(/\\/g,"/").split("/").slice(0,-1).join("/")}function Ba(e){let t=e.replace(/\\/g,"/").split("/").pop()??e;return kp(t.replace(/\.md$/i,""))}function $p(e,t){try{return/^#\s+(.+)$/m.exec(ok(rk(e,t),"utf8"))?.[1]?.trim()??null}catch{return null}}import pe from"picocolors";import Ya from"wrap-ansi";import Ka from"string-width";te();import an from"picocolors";import Bs from"wrap-ansi";import Us from"string-width";var ko=[{name:"init",usage:"/init",desc:"Pick an environment, scaffold .d360-writer/config.json, and set up the builder hand-off (prints the one-paste prompt)",group:"start"},{name:"login",usage:"/login",desc:"Sign in to Document360 (browser)",group:"start"},{name:"project",usage:"/project [name]",desc:"Choose the Document360 project (picker; lists all you can access)",group:"start"},{name:"devhints",usage:"/devhints",desc:"Re-show/refresh the builder hand-off prompt (set up by /init; run anytime to hand your repo agent the latest)",group:"start"},{name:"scope",usage:"/scope",desc:"Choose which repo folders back the docs (monorepos)",group:"start"},{name:"genre",usage:"/genre [web|cli|service|library|auto]",desc:"Set/show the product genre \u2014 picks the docs craft playbook (usually auto-detected; set it if it guessed wrong)",group:"start"},{name:"mcp",usage:"/mcp [list|add|remove]",desc:"Connect MCP servers (Notion, Linear, \u2026)",group:"start"},{name:"discover",usage:"/discover",desc:"Interview your builder to understand the product (identity, mental model, misconceptions, positioning) \u2192 pins a product brief that grounds the docs; asks focused questions and loops until confident",group:"docs"},{name:"draft",usage:"/draft [<feature>]",desc:"Draft a feature's articles from its PRDs/specs in .d360-writer/input/ + the code",group:"docs"},{name:"document",usage:"/document [<what>] [--push]",desc:"Document a shipped change \u2014 the agent picks the action (new section/article/update); bare: act on builder requests. --push then saves the result to Document360 as drafts, which still needs an editorial review first",group:"docs"},{name:"write",usage:"/write [--preview|--scope <cat>|<path>] [--rewrite] [--concurrency N] [--skip-style]",desc:"Write the planned articles in parallel (starts immediately; --preview shows plan + cost first; --rewrite regenerates already-written articles; --concurrency default 3). Anything that would block publishing is corrected in one automatic pass before the run finishes; --skip-style leaves it to /lint",group:"docs"},{name:"screenshot",usage:"/screenshot [author|capture|annotate|verify|checklist|list] [id|path|--all|--failed|--blocked]",desc:"Screenshots, one family \u2014 bare: pick what to do; author: write capture specs; capture: take the shots (--all re-shoots everything; --failed re-runs the ones that did not work; --blocked re-runs the ones waiting on app data); annotate: draw the callouts on shots already taken, no browser needed (--all --force re-draws after a wording or style change); verify: judge the finished pictures and mark them verified (both run automatically after a capture); checklist: what to stage + dev test-id requests; list: status + what to stage",group:"docs"},{name:"preview",usage:"/preview [path|id]",desc:"Render an article (no arg: pick from tracked)",group:"docs"},{name:"push",usage:"/push [path|--all|[<category>] --screenshots] [--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). 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> | pull [<n>] | 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); pull: bring your Document360 project's own style guide down; 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>] [--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; --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] [--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; --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:"roadmap",usage:"/roadmap [done [step]]",desc:"Show the docs campaign (the multi-session plan the agent maintains) \u2014 progress + next step; `done` marks the next open step finished (add words from a title to pick another)",group:"docs"},{name:"audit",usage:"/audit [--auto on|off]",desc:"Gap analysis: code vs docs vs Document360 (what changed); --auto runs it at launch when code changed",group:"publish"},{name:"inbox",usage:"/inbox",desc:"Act on messages from the repo's coding agent (requests to document, answers to your questions)",group:"publish"},{name:"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",desc:"Sign out + clear project/workspace selection (then /login to re-pick)",group:"setup"},{name:"allow-prod",usage:"/allow-prod",desc:"Authorize writes to a production profile",group:"setup"},{name:"doctor",usage:"/doctor",desc:"Health-check: auth, profile, workspace, map, API",group:"setup"},{name:"update",usage:"/update",desc:"Update d360-writer \u2014 and d360-capture when installed \u2014 to the latest versions (then relaunch)",group:"setup"},{name:"feedback",usage:"/feedback",desc:"Copy the repo's open d360-writer tool-feedback to your clipboard, to relay to the d360-writer team",group:"setup"},{name:"reset",usage:"/reset",desc:"[DANGER] Delete all d360-writer files (docs, config, screenshots); types repo name to confirm",group:"setup"},{name:"resume",usage:"/resume [name]",desc:"Resume a session (no arg lists them)",group:"session"},{name:"rename",usage:"/rename [name]",desc:"Name the session (no arg: suggest one)",group:"session"},{name:"clear",usage:"/clear",desc:"Clear the screen + reset the conversation (resumable)",group:"session"},{name:"help",usage:"/help",desc:"Show this help",group:"session"},{name:"exit",usage:"/exit",desc:"Quit",group:"session"}],vp={"/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","/style-guide":"choose the writing rules your docs are held to","/lint":"check the docs against those rules (costs nothing)"};function xp(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(vp[n])return vp[n];let o=ko.find(r=>r.name===t);return o?o.desc:""}function Rp(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return ko.filter(n=>n.name.startsWith(t))}function Cp(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 sk=new RegExp(`^\\s*/(?:${ko.map(e=>e.name).join("|")})(?:\\s|$)`),Sp=e=>sk.test(e),Pp=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Tp=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),Ap=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function ik(e){let t=e.replace(/\r/g,"").split(`
|
|
306
|
+
`),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(Pp(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&Tp(t[o+1])){let a=Ap(r);o+=2;let l=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)l.push(Ap(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(Sp(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])&&!Sp(t[o])&&!Pp(t[o])&&!(t[o].includes("|")&&o+1<t.length&&Tp(t[o+1]));)i.push(t[o++]);n.push({kind:"para",text:i.join(" ")})}return n}function Ha(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?an.bold(t.slice(2,-2)):t.startsWith("`")?z(t.slice(1,-1)):an.italic(t.slice(1,-1)))}var ak=(e,t)=>e+" ".repeat(Math.max(0,t-Us(e)));function qa(e,t,n,o={}){return Ep(e,t,n,o)}function Ep(e,t,n,o={}){let r=e.length,s=S=>Math.max(0,...S.split(`
|
|
307
|
+
`).map(E=>Us(E))),i=e.map((S,E)=>Math.max(Us(S),...t.map(I=>s(I[E]??"")))),a=Math.max(24,n),l=3*r+1,p=[...i],m=()=>p.reduce((S,E)=>S+E,0)+l,w=0;for(;m()>a&&w++<1e4;){let S=-1,E=6;for(let I=0;I<r;I++)p[I]>E&&(E=p[I],S=I);if(S===-1)break;p[S]-=1}let $=(S,E,I)=>an.gray(S+p.map(L=>"\u2500".repeat(L+2)).join(E)+I),T=an.gray("\u2502"),R=(S,E)=>{let I=p.map((ue,ie)=>{let he=S[ie]??"",de=E?an.bold(he):o.plain?he:Ha(he);return he.includes(`
|
|
308
308
|
`)?de.split(`
|
|
309
|
-
`).flatMap(
|
|
310
|
-
`)):
|
|
311
|
-
`)}),L=Math.max(...I.map(ue=>ue.length)),Y=[],ce=(ue,
|
|
312
|
-
`)},
|
|
313
|
-
`)}function
|
|
309
|
+
`).flatMap(ke=>Bs(ke,ue,{hard:!0}).split(`
|
|
310
|
+
`)):Bs(de,ue,{hard:!0}).split(`
|
|
311
|
+
`)}),L=Math.max(...I.map(ue=>ue.length)),Y=[],ce=(ue,ie,he)=>o.align?.[he]==="right"?" ".repeat(Math.max(0,ie-Us(ue)))+ue:ak(ue,ie);for(let ue=0;ue<L;ue++)Y.push(p.map((ie,he)=>`${T} ${ce(I[he][ue]??"",ie,he)} `).join("")+T);return Y.join(`
|
|
312
|
+
`)},C=[$("\u250C","\u252C","\u2510"),R(e,!0)];return C.push(t.length===0?$("\u2514","\u2534","\u2518"):$("\u251C","\u253C","\u2524")),t.forEach((S,E)=>{C.push(R(S,!1)),C.push(E===t.length-1?$("\u2514","\u2534","\u2518"):$("\u251C","\u253C","\u2524"))}),C.join(`
|
|
313
|
+
`)}function lk(e,t){switch(e.kind){case"heading":return an.bold(e.text);case"hr":return an.gray("\u2500".repeat(t));case"para":return Bs(Ha(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]=Bs(Ha(o.text),Math.max(10,t-s.length)).split(`
|
|
314
314
|
`);return` ${r} ${i}`+a.map(l=>`
|
|
315
315
|
${s}${l}`).join("")}).join(`
|
|
316
316
|
`)}case"code":return e.lines.map(n=>an.gray(" "+n)).join(`
|
|
317
|
-
`);case"table":return
|
|
317
|
+
`);case"table":return Ep(e.header,e.rows,t)}}function Ga(e,t){let n=Math.max(20,t);return ik(e).map(o=>lk(o,n)).join(`
|
|
318
318
|
|
|
319
|
-
`)}
|
|
320
|
-
`);let r=2,s=3,i=
|
|
319
|
+
`)}te();import ck from"picocolors";var uk=[127,86,217],dk=[22,38,43],Dp={T:uk,E:dk},yr=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],Va=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,pk=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function Np(){if(!ck.isColorSupported)return[];let e=yr[0].length,t=[];for(let n=0;n<yr.length;n+=2){let o="";for(let r=0;r<e;r++){let s=Dp[yr[n][r]],i=n+1<yr.length?Dp[yr[n+1][r]]:void 0;s&&i?o+=`${Va(s)}${pk(i)}\u2580\x1B[49m\x1B[39m`:s?o+=`${Va(s)}\u2580\x1B[39m`:i?o+=`${Va(i)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function wr(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 kr(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function Ip(e,t,n){let o=e>0&&e<=n?e:t;return Math.max(0,Math.floor((n-o)/1e3))}function tt(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function ln(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var bo=(e,t)=>` ${e.padEnd(13)}${t}`;function hk(e,t){let n=[pr("\u270E document360-writer")+pe.gray(` v${e.version} \xB7 engine v${e.engineVersion}${e.captureVersion?` \xB7 capture v${e.captureVersion}`:""}`),pe.gray(" Reads your code, writes your docs."),"",bo("Claude:",`${e.claude}${pe.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),bo("Document360:",e.configured?e.loggedOut?pe.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?pe.gray(` (${e.sessionHint})`):""}`:pe.yellow("not set up \u2014 run /init")),bo("Profile:",e.configured?`${e.profile}${pe.gray(` (${e.apiUrl})`)}${e.prod?pe.bold(pe.yellow(" \u26A0 PRODUCTION")):""}`:pe.gray("\u2014 (run /init)")),bo("Project:",e.project),bo("Mode:",pe.gray(e.mode)),bo("cwd:",pe.gray(e.cwd))],o=Np();if(o.length===0)return n.join(`
|
|
320
|
+
`);let r=2,s=3,i=Ka(o[0]);if(!(t>=r+i+s+Math.max(...n.map(m=>Ka(m)))))return[...o.map(m=>" "+m),...n].join(`
|
|
321
321
|
`);let l=Math.max(0,Math.floor((n.length-o.length)/2)),p=[];for(let m=0;m<Math.max(o.length+l,n.length);m++){let w=o[m-l]??" ".repeat(i);p.push((" ".repeat(r)+w+" ".repeat(s)+(n[m]??"")).trimEnd())}return p.join(`
|
|
322
|
-
`)}var
|
|
323
|
-
`).flatMap(p=>
|
|
322
|
+
`)}var fk={error:pe.red,warn:pe.yellow,ok:pe.green,info:pe.gray},jp=9;function za(e){return e.length>=jp?`${e} `:e.padEnd(jp)}function Xa(e){return e.replace(/^(\s*• |)([^\x00-\x7F][\u{1F000}-\u{1FAFF}️]*) (?=\S)/gmu,"$1$2 ")}function Qa(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return hk(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(`
|
|
323
|
+
`).flatMap(p=>Ya(p,s,{hard:!0}).split(`
|
|
324
324
|
`)),l=Math.max(0,a.length-i);return l>0&&(a=[...a.slice(0,i),pe.dim(`\u2026 +${l} more lines`)]),`
|
|
325
|
-
`+a.map((p,m)=>o+(m===0?z(" \u276F "):" ")+p+" ".repeat(Math.max(0,s-
|
|
325
|
+
`+a.map((p,m)=>o+(m===0?z(" \u276F "):" ")+p+" ".repeat(Math.max(0,s-Ka(p))+1)+r).join(`
|
|
326
326
|
`)}case"assistant":return`
|
|
327
|
-
`+
|
|
328
|
-
`+
|
|
329
|
-
`+
|
|
327
|
+
`+Ga(e.text,n);case"tool":{let o=e.arg!==null?pe.gray(`${e.sep}(${e.arg})`):"";return`
|
|
328
|
+
`+Ya(pe.gray("\u25CF ")+e.title+o,n)}case"doc":{let o=[e.category,e.note].filter(s=>!!s).map(s=>pe.gray(` \xB7 ${s}`)),r=e.loud?pe.gray(" \xB7 ")+pe.bold(pe.yellow(e.loud)):"";return`
|
|
329
|
+
`+Ya(pe.green("\u25CF ")+z(pe.bold(za(e.verb)))+pe.bold(e.title)+o.join("")+r,n)}case"tool-result":{let o=e.isError?pe.red:pe.gray,r=e.lines.map((s,i)=>o((i===0?" \u23BF ":" ")+s));return e.hidden>0&&r.push(pe.dim(` \u2026 +${e.hidden} lines`)),r.join(`
|
|
330
330
|
`)}case"diff":{let o=i=>i===1?"":"s",s=[pe.gray(` \u23BF Added ${e.added} line${o(e.added)}, removed ${e.removed} line${o(e.removed)}`),...e.lines];return e.hidden>0&&s.push(pe.dim(` \u2026 +${e.hidden} more diff lines`)),s.join(`
|
|
331
331
|
`)}case"link":return e.lines.map(o=>z(fr(` \u2B95 ${o}`))).join(`
|
|
332
332
|
`);case"preview":return`
|
|
333
333
|
`+pr(`\u25A3 Preview \u2014 ${e.name}`)+`
|
|
334
334
|
|
|
335
|
-
`+
|
|
336
|
-
`+
|
|
335
|
+
`+Ga(e.text,n);case"note":return`
|
|
336
|
+
`+fk[e.tone](fr(Xa(e.text)));case"block":return`
|
|
337
337
|
`+e.text;case"done":{let o=e.inTokens&&e.inTokens>0?` \xB7 ${wr(e.inTokens)} in${e.cachedPct!=null?` (${e.cachedPct}% cached)`:""}`:"";return`
|
|
338
|
-
`+(e.ok?pe.magenta("\u2736 "):pe.red("\u2736 "))+pe.gray(`Cooked for ${kr(e.seconds)} \xB7 ${wr(e.tokens)} tokens out${o}`+(e.costUsd>0?` \xB7 ${tt(e.costUsd)}`:""))}}}function
|
|
339
|
-
`)}import{resolveActiveProfile as
|
|
340
|
-
`,"utf8")}function
|
|
341
|
-
${a[1]??" "}clipTo: ${l}${i.selector}${l},`);return p=p.replace(o,`${r}await captureShot(page, PLACEHOLDER);`),p=p.replace(
|
|
338
|
+
`+(e.ok?pe.magenta("\u2736 "):pe.red("\u2736 "))+pe.gray(`Cooked for ${kr(e.seconds)} \xB7 ${wr(e.tokens)} tokens out${o}`+(e.costUsd>0?` \xB7 ${tt(e.costUsd)}`:""))}}}function Lp(e,t){return e.map(n=>Qa(n,t)).join(`
|
|
339
|
+
`)}import{resolveActiveProfile as mk,loadTokens as gk,isExpired as yk,decodeJwtClaims as Op}from"document360-engine";function wk(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function Ve(e,t){try{let n=mk(e,t),o=gk(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(yk(o)&&!o.refreshToken)return{ok:!1,reason:`Your Document360 session expired (profile "${n.name}"). Run /login.`};let r=n.project.projectId;if(r){let i={...Op(o.idToken)??{},...Op(o.accessToken)??{}}.doc360_project_id;if(typeof i=="string"&&i&&i!==r)return{ok:!1,reason:`Your Document360 session is signed into a different project than profile "${n.name}" (this profile's project is ${wk(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}function Ct(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 partition produced no output, so no agent actually ran.`,"Most likely a Claude usage/session limit \u2014 it ends every turn instantly and leaves /doctor clean, so wait for the reset and re-run. If you have plenty of quota left, /doctor checks sign-in + model reachability."]:null}function Hs(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.`}import{existsSync as nh,readFileSync as ul}from"node:fs";import{isAbsolute as Ks,join as zs,resolve as Xs}from"node:path";import N from"picocolors";import Vs from"string-width";import{readProjectConfig as un,screenshotPlaceholderIds as oh,DEFAULT_CAPTURE_DIR as Qs,DEFAULT_OUTPUT_DIR as dl,DEFAULT_DOCS_DIR as pl,resolveOutputDir as rh,migrateShotLayout as Wk,reviewIsCurrent as Uk,anchorPresent as Bk,annotationCurrent as Hk,captureLanded as qk,shotArtifacts as Gk,RAW_SUBDIR as Vk,ANNOTATED_SUBDIR as Yk}from"document360-engine";import{createHash as Mp}from"node:crypto";import{readFileSync as Fp,writeFileSync as kk}from"node:fs";import{join as bk}from"node:path";import{captureStatePath as Wp}from"document360-engine";var _p={version:1,shots:{}};function Up(e){return Mp("sha1").update(e).digest("hex").slice(0,12)}function qs(e){try{let t=JSON.parse(Fp(bk(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 Mp("sha1").update(`${o}|${r?.connection?.startUrl??""}|${i}`).digest("hex").slice(0,12)}catch{return null}}function Wt(e){try{let t=JSON.parse(Fp(Wp(e),"utf8").replace(/^/,""));return!t||typeof t!="object"||t.version!==1||!t.shots?{..._p,shots:{}}:{version:1,shots:t.shots}}catch{return{..._p,shots:{}}}}function $k(e,t){kk(Wp(e),`${JSON.stringify(t,null,2)}
|
|
340
|
+
`,"utf8")}function Ja(e){return e&&/data-testid|\btest-?id\b|has(?:n't| not) landed/i.test(e)?"testid":"data"}function Gs(e,t,n){if(t.length===0)return;let o=Wt(e),r=qs(e);for(let s of t){let i=s.specSource?Up(s.specSource):void 0;o.shots[s.id]={outcome:s.outcome,at:n,...s.reason?{reason:s.reason}:{},...s.outcome==="skipped"?{blockedBy:Ja(s.reason)}:{},...i?{specHash:i}:{},...r?{envHash:r}:{}}}$k(e,o)}function Za(e,t,n,o){let r=e.shots[t];return!r||n===null||!r.specHash||r.specHash!==Up(n)||o&&r.envHash&&r.envHash!==o?null:r}function Bp(e){let t=Wt(e).shots;return Object.keys(t).filter(n=>t[n].outcome==="failed").sort()}function el(e,t,n){let o=Za(Wt(e),t,n,qs(e));return!o||o.outcome==="captured"||!o.reason?null:{outcome:o.outcome,reason:o.reason}}$o();import{existsSync as Sk,readFileSync as Vp,readdirSync as Yp,writeFileSync as Pk}from"node:fs";import{isAbsolute as Tk,join as Kp,resolve as Ak}from"node:path";import{readProjectConfig as Ek,DEFAULT_CAPTURE_DIR as Dk}from"document360-engine";var Gp="0.2.25";function vo(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 Nk=/^([ \t]*)await\s+([^\n;]+?)\.screenshot\(\{\s*path:\s*PLACEHOLDER\.saveTo\s*(?:,\s*fullPage:\s*(?:true|false)\s*)?,?\s*\}\)\s*;?[ \t]*$/m,jk=/^[ \t]*await\s+dumpAnnotations\(\s*page\s*,\s*PLACEHOLDER\s*\)\s*;?[ \t]*\r?\n?/m,zp="(?:'([^']+)'|\"([^\"]+)\"|`([^`]+)`)",Ik=new RegExp(`^page\\s*\\.\\s*locator\\(\\s*${zp}\\s*\\)$`),Xp=e=>e[1]??e[2]??e[3]??null,Lk=/^[A-Za-z_$][\w$]*$/;function Ok(e,t){let o=new RegExp(`\\bconst\\s+${t}\\s*=\\s*page\\s*\\.\\s*locator\\(\\s*${zp}\\s*\\)\\s*;`).exec(e);return o?Xp(o):null}function _k(e,t){let n=t.trim();if(n==="page")return null;let o=Ik.exec(n);if(o){let r=Xp(o);return r?{selector:r}:{unresolved:!0}}if(Lk.test(n)){let r=Ok(e,n);return r?{selector:r}:{unresolved:!0}}return{unresolved:!0}}function Qp(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=Nk.exec(e);if(!n)return null;let[o,r="",s=""]=n,i=_k(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("'")?'"':"'",p=e.replace(a[0],`${a[0]}
|
|
341
|
+
${a[1]??" "}clipTo: ${l}${i.selector}${l},`);return p=p.replace(o,`${r}await captureShot(page, PLACEHOLDER);`),p=p.replace(jk,""),p=p.replace(/\bdumpAnnotations\b(?=[^\n]*from 'document360-capture\/helpers')/,"captureShot"),/from 'document360-capture\/helpers'/.test(p)&&!/\bcaptureShot\b[^\n]*from 'document360-capture\/helpers'/.test(p)&&(p=p.replace(/import \{([^}]*)\} from 'document360-capture\/helpers'/,(m,w)=>`import {${w.replace(/\s*$/,"")}, captureShot } from 'document360-capture/helpers'`)),{next:p,selector:i.selector}}function Mk(e){try{return Yp(e).filter(t=>t.endsWith(".spec.ts")).some(t=>{try{let n=Qp(Vp(Kp(e,t),"utf8"));return n!==null&&!("unresolved"in n)}catch{return!1}})}catch{return!1}}function Fk(e){let t=Ek(e)?.captureDir??Dk;return Tk(t)?t:Ak(e,t)}function Jp(e,t){let n={migrated:[],skipped:[]},o=Fk(e);if(!Sk(o))return n;let r=t?.captureVersion===void 0?nt():t.captureVersion;if(!vo(r,Gp))return Mk(o)?{...n,heldBackForCapture:{installed:r,required:Gp}}:n;let s;try{s=Yp(o).filter(i=>i.endsWith(".spec.ts"))}catch{return n}for(let i of s.sort()){let a=i.slice(0,-8),l=Kp(o,i);try{let p=Vp(l,"utf8"),m=Qp(p);if(m===null)continue;if("unresolved"in m){n.skipped.push({id:a,receiver:m.unresolved});continue}Pk(l,m.next,"utf8"),n.migrated.push(a)}catch{}}return n}function Zp(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.
|
|
342
342
|
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(`
|
|
343
|
-
`)}function
|
|
344
|
-
`):null}function jn(e,t){let n=un(e)?.captureDir??
|
|
345
|
-
`))||o.push(r+1));return o}function
|
|
343
|
+
`)}function be(e,t,n){return`${e}${n?` ${n}`:""}${t?` ${t}`:""}`}function St(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}$o();var sh=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function eh(e){let t=e.includes("--detail")||e.includes("-d"),n=e.find(o=>o!=="--detail"&&o!=="-d");return{mode:"list",scope:n?sh(n):void 0,...t?{detail:!0}:{}}}function br(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 eh(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 eh(o.slice(1));let r=o[0];return r?r==="--all"?{mode:"all",setup:n}:/[\\/]/.test(r)||r.endsWith(".md")?{mode:"scope",scope:sh(r),setup:n}:{mode:"single",id:r}:{mode:"list",picker:!0}}function Le(e,t,n){let o=un(e),r=o?.captureDir??Qs,s=o?.outputDir??dl,i=(w,$)=>Ks(w)?zs(w,$):Xs(e,w,$),a=Wt(e),l=n?.captureVersion===void 0?nt():n.captureVersion,p=vo(l,ch),m=qs(e);return oh(e,{scope:t}).map(({id:w,file:$})=>{let T=i(r,`${w}.spec.ts`),R=null;if(nh(T))try{R=ul(T,"utf8")}catch{}let C=rh(e,s),S=Gk(C,w),E=Hk(S),I=qk(S),L=R===null?null:Za(a,w,R,m),Y=a.shots[w]?.review,ce=E&&Uk(Y,S.annotatedMtimeMs)?Y:void 0,ue=R!==null&&Xk(R),ie=E&&ce?.verdict==="ok"?"verified":E&&ce?.verdict==="rejected"?"rejected":E?"annotated":I?"captured":R===null?"placeholder":ue||L?.outcome==="skipped"?"blocked":L?.outcome==="failed"?"broken":"spec",he=R===null?void 0:ah(R),de=ue?Jk(R):L?.reason,ke=ue?"testid":L?.outcome==="skipped"?Ja(L.reason):void 0,ae=R===null?[]:Qk(e,R);return{id:w,file:$,state:ie,...he?{mutates:he.mutates,...he.declared?{}:{undeclared:!0}}:{},...R!==null&&ol(R).length>0?{unguardedWaits:ol(R)}:{},...R!==null&&nl(R).length>0?{unverifiedForce:nl(R)}:{},...R!==null&&rl(R).length>0?{handRolled:rl(R)}:{},...R!==null&&il(R).length>0?{stalePause:il(R)}:{},...R!==null&&p&&sl(R).length>0?{bareGoto:sl(R)}:{},...ae.length>0?{staleAnchor:ae}:{},...ie==="blocked"||ie==="broken"?{...de?{reason:de}:{},...ke?{blockedBy:ke}:{}}:{},...ie==="rejected"?{...ce?.reason?{reason:ce.reason}:{},...ce?.repaired?{repaired:!0}:{}}:{}}})}function Kk(e){let t=un(e)?.outputDir??dl;return Wk(rh(e,t))}function Nn(e){let t=Kk(e),n=un(e)?.outputDir??dl,o=[];t>0&&o.push(`\u2195 Tidied ${t} screenshot file${t===1?"":"s"} into ${n}/{${Vk},${Yk}} \u2014 annotated/ is what publishes, raw/ is the pre-annotation intermediate.`);let r=Zp(Jp(e));return r&&o.push(r),o.length>0?o.join(`
|
|
344
|
+
`):null}function jn(e,t){let n=un(e)?.captureDir??Qs,o=Ks(n)?zs(n,`${t}.spec.ts`):Xs(e,n,`${t}.spec.ts`);try{return ul(o,"utf8")}catch{return null}}function ih(e,t){let n=un(e)?.captureDir??Qs;return nh(Ks(n)?zs(n,`${t}.spec.ts`):Xs(e,n,`${t}.spec.ts`))}function zk(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 ah(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=zk(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 Xk(e){return/(^|\n)\s*test\.skip\s*\(\s*['"`]/.test(e)}function lh(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 Qk(e,t){let n=[];for(let o of lh(t))Bk(e,o.file,o.anchor)===!1&&n.push(o.testid??o.file??"unnamed request");return[...new Set(n)]}function Jk(e){let{testid:t,file:n}=lh(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 $r(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 nl(e,t=10){let n=$r(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(`
|
|
345
|
+
`))||o.push(r+1));return o}function ol(e){let t=[],n=$r(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 rl(e){let t=[];for(let[n,o]of $r(e).entries())(/\.screenshot\s*\(/.test(o)||/\bdumpAnnotations\s*\(/.test(o))&&t.push(n+1);return t}var ch="0.2.28";function sl(e){let t=[];for(let[n,o]of $r(e).entries())/\.goto\s*\(/.test(o)&&t.push(n+1);return t}function il(e,t=6){let n=$r(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(`
|
|
346
346
|
`);if(!/test\.skip\s*\(/.test(i)||!/\.count\s*\(\s*\)/.test(i))continue;let a=n.slice(Math.max(0,r-t),r+1).join(`
|
|
347
|
-
`);/\.waitFor\s*\(|Promise\.race\s*\(|waitForFunction\s*\(|waitForSelector\s*\(/.test(a)||o.push(r+1)}return o}function
|
|
348
|
-
`)}function
|
|
349
|
-
`)}var eb={placeholder:"\u25CB",spec:"\u25D0",blocked:"\u2298",broken:"\u2717",captured:"\u25CF",annotated:"\u25C8",verified:"\u2714",rejected:"\u2691"},tb={placeholder:N.gray,spec:N.yellow,blocked:N.cyan,broken:N.red,captured:N.yellow,annotated:N.blue,verified:N.green,rejected:N.magenta},nb=` ${N.green("\u2714 verified")} ${N.blue("\u25C8 to verify")} ${N.yellow("\u25CF to annotate")} ${N.yellow("\u25D0 ready")} ${N.magenta("\u2691 rejected")} ${N.cyan("\u2298 blocked")} ${N.red("\u2717 broken")} ${N.gray("\u25CB to spec")}`;function se(e,t=n=>n){return`${t(e)} `}function Co(e){return e.replace(/\s+/g," ").trim().replace(/^Prerequisites? not met[:—-]?\s*/i,"")}function ni(e){let t=Co(e),n=/^(.*?[a-z0-9)"'”’])\.(?:\s|$)/i.exec(t);return(n?n[1]:t).trim()}function vr(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=ni(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 dh(e){let t=vr(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(` ${N.bold("Stage this data")} ${N.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=on(a.reason,86);r.push(` ${N.cyan(cn(`${a.ids.length}\xD7`,4))} ${l[0]??""}`);for(let m of l.slice(1))r.push(` ${m}`);let p=a.ids.slice(0,4).join(" \xB7 ");r.push(N.gray(` ${p}${a.ids.length>4?` \xB7 +${a.ids.length-4} more`:""}`))}n.length>i&&r.push(N.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(` ${se("\u2298",N.cyan)}${s} shot${s===1?"":"s"} need${s===1?"s":""} a data-testid from your developers \u2014 ${N.bold("/screenshot checklist")} builds the hand-off.`)}return r}function ph(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=["",` ${se("\u26A0",N.yellow)}${r} selector request${r===1?"":"s"} quote${r===1?"s":""} source code that has since changed`+N.gray(" \u2014 your developers would go looking for something that isn't there any more"),N.gray(` Refresh the hand-off before sending it: ${N.bold("/screenshot checklist")}`)];return t&&s.push(N.gray(` ${o.slice(0,8).join(" \xB7 ")}${r>8?` \xB7 +${r-8} more`:""}`)),s}function hh(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=["",` ${se("\u26A0",N.yellow)}Some specs were written before later reliability fixes:`],p=(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(N.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(N.gray(p(o,w=>`${w.id}:${w.unguardedWaits.join(",")}`)))}if(a.length>0){let m=a.length;l.push(N.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(N.gray(p(a,w=>`${w.id}:${w.bareGoto.join(",")}`)))}if(i.length>0){let m=i.length;l.push(N.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(N.gray(p(i,w=>`${w.id}:${w.stalePause.join(",")}`)))}if(s.length>0){let m=s.length;l.push(N.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(N.gray(p(s,w=>`${w.id}:${w.handRolled.join(",")}`)))}if(r.length>0){let m=r.length,w=r.filter($=>$.mutates).length;l.push(N.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(N.gray(p(r,$=>$.id)))}return n?.commandInLead||l.push(N.gray(` Re-write them all with the current rules: ${N.bold("/screenshot author --all")}`)),l}function fh(e){let t=e.filter(n=>(n.unverifiedForce?.length??0)>0);return t.length===0?[]:["",` ${se("\u26A0",N.red)}${t.length} spec${t.length===1?"":"s"} force-click past Playwright's safety checks without asserting the result`+N.gray(" \u2014 if the click lands on nothing, the shot photographs the unchanged screen"),N.gray(` ${t.slice(0,6).map(n=>`${n.id}:${n.unverifiedForce.join(",")}`).join(" \xB7 ")}${t.length>6?` \xB7 +${t.length-6} more`:""}`),N.gray(` Re-author to check what the click did: ${N.bold("/screenshot author <id>")}`)]}var Ks=(e,t)=>e.length>=t?e:e+" ".repeat(t-e.length),cn=(e,t)=>e.length>=t?e:" ".repeat(t-e.length)+e;function mh(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 ob=new Set(["and","or","of","the","to","a","an","in","on","for","with","vs"]),rb=new Set(["ai","api","cli","ui","ux","url","id","http","https","json","xml","sdk","csv","pdf","oauth","sso","mfa","io","faq"]);function sb(e){return e.replace(/[-_]+/g," ").trim().split(/\s+/).filter(Boolean).map((n,o)=>{let r=n.toLowerCase();return rb.has(r)?r.toUpperCase():o>0&&ob.has(r)?r:r.charAt(0).toUpperCase()+r.slice(1)}).join(" ")}function ll(e){if(!e)return{num:"",name:"(docs root)"};let t=/^(\d+)[-_](.+)$/.exec(e);return{num:t?t[1]:"",name:sb(t?t[2]:e)}}function ib(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).pop()??e}function Zp(e,t,n){let o=t>0?Math.round(e/t*n):0;return N.green("\u2588".repeat(o))+N.gray("\u2591".repeat(Math.max(0,n-o)))}function ab(e,t){let n=t>0?Math.round(e/t*100):0,o=cn(`${n}%`,4);return n===100?N.green(o):n>0?N.yellow(o):N.gray(o)}function gh(e,t){let n=new Map;for(let o of e){let r=mh(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 ml(e,t){let n=S=>e.filter(E=>E.state===S).length,o=n("captured"),r=n("placeholder"),s=n("spec"),i=n("annotated"),a=n("blocked"),l=n("broken"),p=n("rejected"),m=e.filter(S=>S.state==="spec"&&S.mutates).length,w=s>m,$=e.filter(S=>(S.unguardedWaits?.length??0)>0||(S.bareGoto?.length??0)>0).length,T=e.filter(S=>(S.stalePause?.length??0)>0||(S.handRolled?.length??0)>0).length,C=s>0||a>0||l>0,R=(S,E="")=>ke(S,E,t);return o>0?{key:"annotate",cmd:R("/screenshot annotate")}:r>0?{key:"toSpec",cmd:t?`/screenshot author ${t}`:"/screenshot author --all"}:$>0&&C?{key:"crashy",cmd:t?`/screenshot author ${t}`:"/screenshot author --all"}:T>0&&C?{key:"wrongOutput",cmd:t?`/screenshot author ${t}`:"/screenshot author --all"}:s>0&&(w||i===0)?{key:"ready",cmd:R("/screenshot capture")}:i>0&&s>0?{key:"verify",cmd:R("/screenshot verify")}:a>0?{key:"blocked",cmd:R("/screenshot capture","--blocked")}:l>0?{key:"broken",cmd:`/screenshot ${e.find(S=>S.state==="broken").id}`}:i>0?{key:"verify",cmd:R("/screenshot verify")}:p>0?{key:"rejected",cmd:R("/screenshot capture","--failed")}:{key:"done",cmd:t?`/push ${t}`:"/push"}}function lb(e,t){let n=(X,Re)=>X.filter(Se=>Se.state===Re).length,o=e.length,r=n(e,"verified"),s=n(e,"annotated"),i=n(e,"captured"),a=n(e,"rejected"),l=n(e,"spec"),p=n(e,"blocked"),m=n(e,"broken"),w=n(e,"placeholder"),$=new Set(e.map(X=>X.file)).size,T=gh(e,t),C=[];C.push(` ${N.bold("Screenshots")} ${N.green(`${r}/${o} verified`)} ${N.gray("\xB7")} ${s>0?N.blue(`${s} to verify`):N.gray("0 to verify")}`+(i>0?` ${N.gray("\xB7")} ${N.yellow(`${i} to annotate`)}`:"")+(a>0?` ${N.gray("\xB7")} ${N.magenta(`${a} rejected`)}`:"")+` ${N.gray("\xB7")} ${l>0?N.yellow(`${l} ready`):N.gray("0 ready")}`+(p>0?` ${N.gray("\xB7")} ${N.cyan(`${p} blocked`)}`:"")+(m>0?` ${N.gray("\xB7")} ${N.red(`${m} broken`)}`:"")+` ${N.gray("\xB7")} ${w>0?N.red(`${w} to spec`):N.gray("0 to spec")} `+N.gray(`across ${$} article${$===1?"":"s"}`));let R=o>0?Math.round(r/o*100):0;C.push(` [${Zp(r,o,32)}] ${N.bold(`${R}%`)}`),C.push("");let S=T.map(([X])=>ll(X)),E=Math.min(32,Math.max(7,...S.map(X=>X.name.length))),I=X=>X.length>E?`${X.slice(0,E-1)}\u2026`:Ks(X,E),L=[...i>0?[{head:"To annotate",w:11,state:"captured",color:N.yellow}]:[],...s>0?[{head:"To verify",w:9,state:"annotated",color:N.blue}]:[],...a>0?[{head:"Rejected",w:8,state:"rejected",color:N.magenta}]:[],{head:"Ready",w:5,state:"spec",color:N.yellow},...p>0?[{head:"Blocked",w:7,state:"blocked",color:N.cyan}]:[],...m>0?[{head:"Broken",w:6,state:"broken",color:N.red}]:[],{head:"To spec",w:7,state:"placeholder",color:N.red}];C.push(N.gray(` ${Ks("#",2)} ${Ks("Chapter",E)} ${cn("Verified",8)} ${L.map(X=>cn(X.head,X.w)).join(" ")} Progress`));for(let[X,[,Re]]of T.entries()){let Se=n(Re,"verified"),Fe=Re.length,{num:Bt,name:yn}=S[X],$t=Se===Fe,ft=I(yn),Gn=L.map(st=>{let Ht=n(Re,st.state);return Ht>0?st.color(cn(String(Ht),st.w)):N.gray(cn("\u2014",st.w))}).join(" ");C.push(` ${N.cyan(Ks(Bt,2))} ${$t?N.green(ft):Se>0?ft:N.gray(ft)} ${$t?N.green(cn(`${Se}/${Fe}`,8)):cn(`${Se}/${Fe}`,8)} ${Gn} ${Zp(Se,Fe,10)} ${ab(Se,Fe)}`)}C.push("");let Y=m>0?` ${N.gray("\xB7")} ${m} spec${m===1?"":"s"} broken \u2014 ${N.bold(`/screenshot ${e.find(X=>X.state==="broken").id}`)} re-authors ${m===1?"it":"the first"}`:"",ce=e.filter(X=>X.state==="spec"&&X.mutates).length,ue=l>ce,ae=e.filter(X=>(X.unguardedWaits?.length??0)>0||(X.bareGoto?.length??0)>0).length,he=e.filter(X=>(X.stalePause?.length??0)>0||(X.handRolled?.length??0)>0).length,de=l>0||p>0||m>0,Ce=!1,ee=ml(e).key;if(ee==="annotate")C.push(` ${se("\u25C8",N.blue)}${i} shot${i===1?"":"s"} taken but not drawn on \u2014 run ${N.bold("/screenshot annotate")}`+N.gray(` \u2014 no browser, seconds; the callouts are what make ${i===1?"it":"them"} publishable`)+Y);else if(ee==="toSpec")C.push(` ${se("\u2192",N.yellow)}${w} placeholder${w===1?"":"s"} still need a spec \u2014 run ${N.bold("/screenshot author --all")}${Y}`);else if(ee==="crashy")Ce=!0,C.push(` ${se("\u2192",N.yellow)}${ae} spec${ae===1?"":"s"} would crash mid-run \u2014 re-write ${ae===1?"it":"them"} first: ${N.bold("/screenshot author --all")}`+N.gray(` \xB7 then ${N.bold("/screenshot capture")} (no browser time wasted on ${ae===1?"a shot":"shots"} that can't finish)`)+Y);else if(ee==="wrongOutput")Ce=!0,C.push(` ${se("\u2192",N.yellow)}${he} spec${he===1?"":"s"} would shoot the wrong thing \u2014 re-write ${he===1?"it":"them"} first: ${N.bold("/screenshot author --all")}`+N.gray(` \xB7 then ${N.bold("/screenshot capture")} (a false skip or a misplaced callout costs the same browser time as a good shot)`)+Y);else if(ee==="ready"){let X=ce>0?N.gray(` \u2014 ${l-ce} in one go; ${ce} write${ce===1?"s":""} real data and run${ce===1?"s":""} one at a time`):"";C.push(` ${se("\u2192",N.yellow)}${l} spec${l===1?"":"s"} ready to capture \u2014 run ${N.bold("/screenshot capture")}${X}${Y}`)}else if(ee==="verify"&&l>0)C.push(` ${se("\u2192",N.blue)}${s} shot${s===1?"":"s"} awaiting verification \u2014 run ${N.bold("/screenshot verify")}`+N.gray(" \u2014 no browser needed")+N.gray(` \xB7 ${l} ready spec${l===1?"":"s"} write real data, so ${l===1?"it runs":"each runs"} only when named: /screenshot capture <id>`)+Y);else if(ee==="blocked")C.push(` ${se("\u2192",N.cyan)}${p} shot${p===1?"":"s"} blocked \u2014 stage the data below, then ${N.bold("/screenshot capture --blocked")}${Y}`);else if(ee==="broken")C.push(` ${se("\u2192",N.red)}${m} spec${m===1?"":"s"} broken \u2014 ${N.bold(`/screenshot ${e.find(X=>X.state==="broken").id}`)} re-authors ${m===1?"it":"the first"} (re-capturing fails the same way)`);else if(ee==="verify")C.push(` ${se("\u2192",N.blue)}${s} shot${s===1?"":"s"} awaiting verification \u2014 run ${N.bold("/screenshot verify")}`+N.gray(" \u2014 it checks each picture against what its article needs (no browser, no re-capture)"));else if(ee==="rejected"){let X=e.filter(Re=>Re.state==="rejected"&&Re.repaired).length;C.push(` ${se("\u2691",N.magenta)}${a} shot${a===1?"":"s"} failed review \u2014 `+(X>0?`${X} spec${X===1?"":"s"} already repaired; re-capture with ${N.bold("/screenshot capture --failed")}`:`see the reasons below, then ${N.bold("/screenshot capture --failed")}`))}else C.push(` ${se("\u2713",N.green)}all ${o} verified \u2014 ${N.bold("/push")} embeds them in the articles`);if(r>0&&r<o){let X=T.filter(([,Re])=>Re.every(Se=>Se.state!=="verified")).map(([Re])=>{let{num:Se,name:Fe}=ll(Re);return Se?`${Se} ${Fe}`:Fe});X.length>0&&C.push(N.gray(` Furthest behind: ${X.slice(0,5).join(" \xB7 ")}${X.length>5?" \u2026":""} (0% verified)`))}return C.push(...dh(e),...fh(e),...hh(e,!1,{commandInLead:Ce}),...ph(e,!1)),C.push(""),C.push(N.gray(" Drill in: /screenshot list <chapter#> \xB7 /screenshot list --detail (all)")),C}function cb(e,t,n){let o=new Set(e.map(l=>l.file)),r=e.filter(l=>l.state==="verified").length,s=e.filter(l=>l.state==="annotated").length,i=e.filter(l=>l.state==="captured").length,a=[` ${N.bold("Screenshots")}: ${e.length} placeholder${e.length===1?"":"s"} across ${o.size} article${o.size===1?"":"s"} \xB7 ${N.green(`${r} verified`)}${s>0?N.blue(` \xB7 ${s} to verify`):""}${i>0?N.yellow(` \xB7 ${i} to annotate`):""}${n?N.gray(` \xB7 scope ${n}`):""}`,""];for(let[l,p]of gh(e,t)){let m=p.filter(R=>R.state==="verified").length,{num:w,name:$}=ll(l),T=w?`${w} \xB7 ${$}`:$;a.push(` ${N.bold(T)} ${N.gray(`(${m}/${p.length})`)}`);let C=new Map;for(let R of p){let S=ib(R.file),E=C.get(S)??[];C.has(S)||C.set(S,E),E.push(R)}for(let R of[...C.keys()].sort()){a.push(N.gray(` ${R}`));for(let S of C.get(R)){let E=tb[S.state];if(a.push(` ${se(eb[S.state],E)}${E(S.id)}`),(S.state==="blocked"||S.state==="broken"||S.state==="rejected")&&S.reason){for(let I of on(Co(S.reason),84))a.push(N.gray(` ${I}`));S.state==="rejected"&&a.push(N.gray(` ${S.repaired?"spec repaired \u2014 re-capture to confirm":"spec not yet repaired"}`))}}}}return a.push(...dh(e),...fh(e),...hh(e,!0),...ph(e,!0)),a.push("",nb),a}function oi(e,t){let n=t?.scope;if(e.length===0)return[n?`No screenshot placeholders under ${n}.`:"No screenshot placeholders found in the docs."];let o=t?.docsDir??hl;return t?.detail||n?cb(e,o,n):lb(e,o)}function gl(e,t){if(!t||!/^\d+$/.test(t))return t;let n=un(e)?.docsDir??hl,o=String(Number(t));for(let{file:r}of th(e)){let s=mh(r,n),i=/^(\d+)/.exec(s);if(i&&String(Number(i[1]))===o)return s}return t}function yh(e,t){let r=e.map(a=>" ".repeat(a.depth)+a.label),s=Math.max(0,...e.map((a,l)=>a.note?Ys(r[l]):0)),i=Math.min(s,Math.max(0,t-2-24));return e.map((a,l)=>{let p=r[l];if(!a.note)return{head:p,note:""};let m=Math.max(2,i+2-Ys(p)),w=a.note.trim(),$=t-Ys(p)-m;return{head:p+" ".repeat(m),note:$>1&&Ys(w)>$?`${w.slice(0,$-1)}\u2026`:w}})}function ub(e){let t=e.replace(/\\/g,"/").split("/").filter(Boolean),n=t.pop()??e;return{category:t.pop()??"(docs root)",article:n}}function xo(e,t,n){let o=new Map;for(let s of t){let{category:i,article:a}=ub(s.file),l=o.get(i)??new Map;o.set(i,l);let p=l.get(a)??[];l.set(a,p),p.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(p=>p.id),l=a.length>0;l&&e.push({kind:"category",action:n,label:`${s} (${a.length})`,ids:a,depth:1});for(let p of[...i.keys()].sort()){let m=i.get(p),w=m.filter(r).map(C=>C.id),$=w.length>0;$&&e.push({kind:"article",action:n,label:`${p} (${w.length})`,ids:w,depth:l?2:1});let T=(l?1:0)+($?1:0)+1;for(let C of m){let R=n==="capture"&&C.mutates?" \u26A0 creates real data \u2014 runs only alone":void 0;e.push({kind:"shot",action:n,label:C.id,ids:[C.id],depth:T,...R?{note:R}:{}})}}}}function nl(e){return e?Co(e):""}function yl(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 ${nl(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 ${nl(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 ${nl(i.reason)}`})}}function wh(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}),xo(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}),xo(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}),xo(o,s,"annotate"),yl(o,e.filter(i=>i.state==="blocked"),e.filter(i=>i.state==="broken"),e.filter(i=>i.state==="rejected")),o}var cl=["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(`
|
|
350
|
-
`);function
|
|
351
|
-
`),"",...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=>
|
|
352
|
-
`)}async function
|
|
353
|
-
`),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.`,cl
|
|
354
|
-
`),a=o.mode==="scope"?`/screenshot ${o.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:i,display:a}}var xr=3;function
|
|
355
|
-
`)}var
|
|
356
|
-
`)}async function So(e,t){try{let n=wl(e,t),o=n.project.projectId,r=n.project.workspaceId;return!o||!r||(await Cb({profile:n.name,connection:n.connection},{cwd:e,profile:n.name,projectPath:`/v3/projects/${o}`,workspaceId:r,verifyHidden:!1})).kind!=="created"?null:`\u2139 Created a hidden "${Rb}" folder on Document360 \u2014 it's where your reviewers leave feedback for d360-writer to action (hidden from readers; its README explains how). /catch-up picks up what they write.`}catch{return null}}var ct="--skip-review";function Rr(e,t){return bb(e,t)}function ai(e,t){try{return Rr(e,xh(e,t)).length}catch{return 0}}function Tt(e,t,n="",o){let r=ai(e,o),s=vl(e,o);if(r===0&&s===0)return t;let i=o?` ${o}`:"",a=o?"/push":"/push --all",l=o&&!o.endsWith(".md")?` in ${o}`:"";if(r>0){let m=r===1?"":"s",w=s>0?` ${s} also break house style rules \u2014 /lint${i} --fix clears those afterwards.`:"",$=`/review${i} --blocked --fix`;return{text:`${n}${r} article${m}${l} ${r===1?"carries":"carry"} text no editor has read, so pushing ${r===1?"it is":"them is"} blocked. ${$} reads ${r===1?"it":"just those"} and applies its fixes.${w} Then ${a}.`,cmd:$}}return{text:`${n}${s} article${s===1?"":"s"}${l} break${s===1?"s":""} house style rules that block publishing. /lint${i} --fix corrects them in place \u2014 finding them costs nothing \u2014 then ${a}.`,cmd:`/lint${i} --fix`}}function vl(e,t){try{return vh(e,xh(e,t)).length}catch{return 0}}function Ah(e,t){return vh(e,t)}function xl(e,t,n){try{let o=$h(e,wl(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 Cl(e,t,n,o=0,r,s){let i=`/push${s?` ${s}`:" --all"}`,a=I=>t[I.index]?.paths.length??0,l=e.filter(I=>I.ok),p=e.filter(I=>!I.ok),m=e.reduce((I,L)=>I+a(L),0),w=l.reduce((I,L)=>I+a(L),0),$=n==="api"?`${tt(e.reduce((I,L)=>I+L.costUsd,0))} total`:ln(e.reduce((I,L)=>I+L.outputTokens,0)),T=`${l.length}/${e.length} batch${e.length===1?"":"es"}`,C=I=>`${I} article${I===1?"":"s"}`,R=[],S=r?Rt({blocked:r.blocked,allEmpty:r.allEmpty,aborted:!1},"The push"):null;if(S)return R.push(...S),R.push(`Nothing reached Document360. Re-run ${i} once that is fixed.`),o>0&&R.push(In(o)),R;if(r&&m>0&&r.recorded===0){R.push(`\u2717 Nothing was pushed \u2014 the ${C(m)} in this run are not recorded in the category map, so none of them reached Document360.`),R.push(`Run /doctor (this is usually the agent runtime not running), then re-run ${i}.`);for(let I of p)I.error&&R.push(` \u2717 ${I.label} \u2014 ${I.error}`);return o>0&&R.push(In(o)),R}if(p.length===0&&(!r||r.recorded>=m))R.push(`Pushed ${C(m)} (${T}) successfully \xB7 ${$}.`),R.push(`Saved on Document360 as draft${m===1?"":"s"} \u2014 readers don't see ${m===1?"it":"them"} until /publish takes ${m===1?"it":"them"} live.`);else if(p.length===0&&r)R.push(`Pushed ${r.recorded}/${C(m)} (${T}) \xB7 ${$}.`),R.push(`${m-r.recorded} article${m-r.recorded===1?"":"s"} reported no error but ${m-r.recorded===1?"is":"are"} not recorded on Document360 \u2014 re-run ${i} to retry just those.`);else{R.push(`Pushed ${r?r.recorded:w}/${C(m)} (${T}) \xB7 ${$}.`),R.push(`${p.length} batch${p.length===1?"":"es"} failed \u2014 re-run ${i} to retry just the rest (articles already on Document360 are skipped):`);for(let I of p)R.push(` \u2717 ${I.label}${I.error?` \u2014 ${I.error}`:""}`)}let E=r?qs(r):null;return E&&R.push(E),o>0&&R.push(In(o)),R}async function Pt(e,t,n=0,o){let r=$b(e.cwd,t,{allowUnreviewed:o?.skipReview===!0,allowStyleErrors:o?.skipStyle===!0});if(!r.clear){for(let a of vb(r,t.length))console.log(q(a));return{kind:"continue"}}let{model:s}=yb(e.cwd,"standard"),i=async(a,l)=>{let p=mb(a);console.log(y(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"} in ${p.length} batch${p.length===1?"":"es"} (\u2264${xr} agents at once) on ${s}\u2026`)),l||console.log(y(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let m=!1;for await(let w of wb({cwd:e.cwd,partitions:p,promptFor:$=>Cr($.paths),concurrency:xr,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),allowUnreviewedPublish:o?.skipReview===!0,allowStyleErrors:o?.skipStyle===!0,model:s}))if(w.type==="partition_status")w.status==="running"?console.log(y(` \u25B8 ${w.label} \u2014 pushing\u2026`)):w.status==="done"?console.log(V(` \u2713 ${w.label}`)):console.log(j(` \u2717 ${w.label}`));else if(w.type==="run_done"){m=w.aborted,console.log("");let $=process.env.ANTHROPIC_API_KEY?"api":"subscription",T=xl(e.cwd,a,e.profileName),C=!w.aborted&&(!!w.blocked||!!w.allEmpty||a.length>0&&T===0);for(let I of Cl(w.results,p,$,l?0:n,{recorded:T,...w.blocked?{blocked:w.blocked}:{},...w.allEmpty?{allEmpty:!0}:{}},o?.scope))console.log(w.ok&&!C?V(I):q(I));if(C)continue;let R=$l(e.cwd,e.profileName);R&&console.log(y(R));let S=Ro(e.cwd,e.profileName);S&&console.log(y(S));try{let I=Rh(await Ch({cwd:e.cwd,profileName:e.profileName,onRateLimit:L=>console.log(y(` Document360 rate limit \u2014 waiting ${Math.ceil(L.waitMs/1e3)}s\u2026`))}));I&&console.log(I.startsWith("\u26A0")?q(I):y(I))}catch{}try{let I=Ph(await Sh({cwd:e.cwd,profileName:e.profileName}));I&&console.log(y(I))}catch{}let E=await So(e.cwd,e.profileName);E&&console.log(y(E))}return m};try{if(!await i(t,!1)){let l=await Rl(e.cwd,e.profileName,t);l.length>0&&await i(l,!0)}}catch(a){console.log(j(`Push run failed: ${a.message}`))}return console.log(""),{kind:"continue"}}async function li(e,t,n){let o=gb(e,n);if(o.length===0)return[];let r=new Set(bl((await si({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function Rl(e,t,n){try{let o=new Set(n),r=await si({cwd:e,profileName:t});return bl(r.entries).map(s=>s.path).filter(s=>o.has(s))}catch{return[]}}async function ci(e,t){let n=Ve(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(j(n.reason)),{kind:"continue"};let o=e.includes(ct),r=e.includes(xb),s=e[0];if(e.includes("--screenshots")||e.includes("--shots")){let i=t?.cwd??process.cwd(),a=e.find(T=>!T.startsWith("--")),l=Le(i),p=Zs(l,a);if(p.length===0){let T=l.filter(C=>C.state==="captured").length;return console.log(y(T>0?`${T} screenshot${T===1?" has":"s have"} been taken but the callouts aren't drawn on yet, so there is nothing to embed \u2014 /screenshot annotate finishes ${T===1?"it":"them"}.`:a?`No captured screenshots in ${a} \u2014 /push --screenshots covers the whole knowledge base.`:"No captured screenshots yet \u2014 /screenshot capture first.")),{kind:"continue"}}let m=ei(l,a);m&&console.log(m);let w=ti(l);w&&console.log(w);let $=ke("","--screenshots",a).trim();return t?await Pt(t,p,0,{skipReview:o,skipStyle:r,scope:$}):{kind:"forward-to-agent",prompt:Cr(p),display:`/push ${$}`}}if(s==="--related"&&e[1]){if(!t)return{kind:"continue"};let i=await li(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return i.length===0?(console.log(V("\u2713 All related articles are already on Document360.")),{kind:"continue"}):await Pt(t,i,0,{skipReview:o,skipStyle:r,scope:`--related ${e[1]}`})}if(s==="--all"){console.log(y("Checking what needs pushing\u2026"));try{let i=await si({cwd:t?.cwd??process.cwd()}),{clean:a,conflicts:l}=Ln(i.entries),p=ii(i.entries),m=e.includes("--force")&&l.length>0;p>0&&console.log(q(`\u26A0 ${p} 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(q(In(l.length)));let w=m?[...a,...l]:a;if(w.length===0){if(l.length>0){let T=Ro(t?.cwd??process.cwd(),t?.profileName);return T&&console.log(y(T)),console.log(y("Resolve the conflicts: /resolve")),{kind:"continue"}}console.log(V(p>0?"\u2713 Nothing else is ahead of Document360 to push.":"\u2713 Nothing is ahead of Document360 \u2014 nothing to push."));let $=Ro(t?.cwd??process.cwd(),t?.profileName);if($&&console.log(y($)),t)try{let T=Rh(await Ch({cwd:t.cwd,profileName:t.profileName,onRateLimit:R=>console.log(y(` Document360 rate limit \u2014 waiting ${Math.ceil(R.waitMs/1e3)}s\u2026`))}));T&&console.log(T.startsWith("\u26A0")?q(T):y(T));let C=Ph(await Sh({cwd:t.cwd,profileName:t.profileName}));C&&console.log(y(C))}catch{}return{kind:"continue"}}return t?await Pt(t,w.map($=>$.path),m?0:l.length,{skipReview:o,skipStyle:r}):{kind:"forward-to-agent",prompt:Cr(w.map($=>$.path)),display:"/push --all"}}catch(i){return console.log(j(`Could not compute sync status: ${i.message}`)),{kind:"continue"}}}if(s&&s.startsWith("--")&&(s=e.find(i=>!i.startsWith("--"))??""),!s){console.log(y("Checking what needs pushing\u2026"));let i,a=0;try{let l=await si({cwd:t?.cwd??process.cwd()}),{clean:p,conflicts:m}=Ln(l.entries);i=p,a=m.length;let w=ii(l.entries);if(w>0&&console.log(q(`\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(q(In(m.length))),i.length===0&&m.length>0)return console.log(y("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(l){return console.log(j(`Could not compute sync status: ${l.message}`)),console.log(y("Push a specific article: /push <article-path>")),{kind:"continue"}}if(i.length===0)return console.log(V("\u2713 Nothing is ahead of Document360 \u2014 nothing to push.")),console.log(y(" (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} ${y(`(${l.label})`)}`);return console.log(y("Run: /push <article-path>")),{kind:"continue"}}try{s=await t.withPausedInput(()=>fb({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(y("Cancelled.")),{kind:"continue"}}if(s==="--all")return await Pt(t,i.map(l=>l.path),a,{skipReview:o,skipStyle:r})}return{kind:"forward-to-agent",prompt:kl(s),display:`/push ${s}`}}ne();import{select as Tb}from"@inquirer/prompts";import{computeSyncStatus as Ab,localAheadPaths as Eb,pendingDrafts as Db,publishArticleLive as Nb,publishGateVerdict as jb,publishGateLines as Ib,resolveActiveProfile as GA,SKIP_STYLE_FLAG as Lb}from"document360-engine";var Pb={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."},Eh=new Set;function Ut(e){let t=Pb[e.replace(/^\//,"")];return!t||Eh.has(e)?null:(Eh.add(e),t)}var Ob=150,_b=e=>e>0?new Promise(t=>setTimeout(t,e)):Promise.resolve(),Pl=e=>e===1?"":"s",Sl=e=>e.replace(/\\/g,"/").split("/").pop()??e;function Tl(e){return e.includes("--screenshots")||e.includes("--shots")||e[0]==="--related"}async function Al(e,t,n){await Ab({cwd:e,profileName:t});let o=n?n.replace(/\\/g,"/").replace(/\/+$/,""):null;return Db(e,t).filter(r=>!o||r.path===o||r.path.startsWith(`${o}/`)).map(r=>({...r,label:r.path}))}function Mb(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 El(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=Eb(e,t).filter(a=>!s||a===s||a.startsWith(`${s}/`)).length;return i>0&&r.push(`${i} article${Pl(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 Dl(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 Nb({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 _b(Ob)}return r}function Nl(e){let{published:t,blocked:n,failed:o}=e,r=[];if(t.length>0){r.push(`\u2713 ${t.length} article${Pl(t.length)} ${t.length===1?"is":"are"} now live \u2014 readers see ${t.length===1?"it":"them"} now.`);for(let s of t.slice(0,3))s.url&&r.push(` \u2B95 ${s.url}`)}if(n.length>0){r.push(`\u2717 ${n.length} refused by the publish gates \u2014 /review --blocked --fix clears ${n.length===1?"it":"them"}:`);for(let s of n.slice(0,3))r.push(` \xB7 ${Sl(s.path)}`);n.length>3&&r.push(` \xB7 \u2026and ${n.length-3} more`)}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 ${Sl(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 Dh(e,t){let n=t?.cwd??process.cwd(),o=Ut("publish");if(Tl(e))return o&&console.log(y(`\u2192 ${o}`)),console.log(y("Running /push\u2026")),ci(e,t);let r=Ve(n,t?.profileName);if(!r.ok)return console.log(j(r.reason)),{kind:"continue"};o&&console.log(y(`\u2192 ${o}`));let s=e.includes(ct),i=e.includes(Lb),a=e.includes("--all"),l=e.find(T=>!T.startsWith("--"));console.log(y("Checking what is waiting to go live\u2026"));let p;try{p=await Al(n,t?.profileName,l)}catch(T){return console.log(j(`Could not check Document360: ${T.message}`)),{kind:"continue"}}if(p.length===0){for(let T of El(n,t?.profileName,l).lines)console.log(T.startsWith("\u2713")?V(T):y(T));return{kind:"continue"}}let m=jb(n,p.map(T=>T.path),{allowUnreviewed:s,allowStyleErrors:i});if(!m.clear){for(let T of Ib(m,p.length,l))console.log(q(T));return{kind:"continue"}}console.log(""),console.log(`${p.length} draft${Pl(p.length)} ${p.length===1?"is":"are"} ahead of what readers see:`);for(let T of Mb(p.slice(0,12)))console.log(y(T));p.length>12&&console.log(y(` \u2026and ${p.length-12} more`)),console.log("");let w=p;if(!a){let T=await Tb({message:"Publish live to your readers?",choices:[{name:`Yes \u2014 publish all ${p.length} live`,value:"all"},...p.slice(0,8).map(C=>({name:`Just ${C.label}`,value:C.path})),{name:"No \u2014 leave them as drafts",value:"none"}]});if(T==="none")return console.log(y("Left as drafts. Nothing changed.")),{kind:"continue"};T!=="all"&&(w=p.filter(C=>C.path===T))}let $=await Dl(n,t?.profileName,w,{skipReview:s,skipStyle:i,onProgress:(T,C,R)=>console.log(y(` \u25B8 ${T+1}/${C} ${Sl(R)}\u2026`))});console.log("");for(let T of Nl($))console.log(T.startsWith("\u2713")?V(T):T.startsWith("\u2717")?q(T):y(T));return{kind:"continue"}}async function Sr(){return{kind:"forward-to-agent",prompt:["Run the gap-analysis skill against this repo.","","Follow its stages in order:","1. d360_sync_status first; stop if any article is changed in both places, or changed on Document360 and not yet pulled down (the local copy cannot be trusted until that is resolved). Say which articles and what to do about them, in plain words, never the internal status word.","2. git diff since the lastAnalyzedCommit marker in d360-category-map.json (or last 30 days if no marker), filtered to the authoritativeSourceFiles paths.","2.5. d360_pending_hints: 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(`
|
|
357
|
-
`),display:"/audit"}}
|
|
358
|
-
`)}async function
|
|
347
|
+
`);/\.waitFor\s*\(|Promise\.race\s*\(|waitForFunction\s*\(|waitForSelector\s*\(/.test(a)||o.push(r+1)}return o}function hl(e,t){let n=m=>`line${m.length===1?"":"s"} ${m.join(", ")}`,o=[],r=t?.captureVersion===void 0?nt():t.captureVersion,s=vo(r,ch)?sl(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=ol(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=rl(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=il(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 p=nl(e);return p.length>0&&o.push(`- ${n(p)}: 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 uh(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 dh(e){return(e??"").trim().replace(/[.\s]+$/,"")}function ph(e,t){let n=un(e)?.captureDir??Qs,o=Ks(n)?zs(n,`${t}.spec.ts`):Xs(e,n,`${t}.spec.ts`);try{return ah(ul(o,"utf8"))}catch{return{mutates:!1,declared:!1}}}var Zk=["annotated","verified","rejected"],eb=e=>Zk.includes(e);function tb(e){return[...new Set(e.filter(t=>eb(t.state)).map(t=>t.file))].sort()}function Js(e,t){let n=tb(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 Zs(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[`${re("\u26A0",N.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=>` ${N.yellow(s.id.padEnd(o))}`),` Publishing without ${r?"it":"them"}. Finish ${r?"it":"them"} first: ${N.bold(be("/screenshot annotate","",t))}`].join(`
|
|
348
|
+
`)}function ei(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[`${re("\u26A0",N.yellow)}${t.length} screenshot${t.length===1?"":"s"} failed verification:`,...t.map(o=>` ${N.magenta(o.id.padEnd(n))} ${N.gray(Ro(o.reason??"no reason recorded"))}`),` Publishing anyway. Fix + re-capture: ${N.bold("/screenshot capture --failed")}`].join(`
|
|
349
|
+
`)}var nb={placeholder:"\u25CB",spec:"\u25D0",blocked:"\u2298",broken:"\u2717",captured:"\u25CF",annotated:"\u25C8",verified:"\u2714",rejected:"\u2691"},ob={placeholder:N.gray,spec:N.yellow,blocked:N.cyan,broken:N.red,captured:N.yellow,annotated:N.blue,verified:N.green,rejected:N.magenta},rb=` ${N.green("\u2714 verified")} ${N.blue("\u25C8 to verify")} ${N.yellow("\u25CF to annotate")} ${N.yellow("\u25D0 ready")} ${N.magenta("\u2691 rejected")} ${N.cyan("\u2298 blocked")} ${N.red("\u2717 broken")} ${N.gray("\u25CB to spec")}`;function re(e,t=n=>n){return`${t(e)} `}function Ro(e){return e.replace(/\s+/g," ").trim().replace(/^Prerequisites? not met[:—-]?\s*/i,"")}function ti(e){let t=Ro(e),n=/^(.*?[a-z0-9)"'”’])\.(?:\s|$)/i.exec(t);return(n?n[1]:t).trim()}function vr(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=ti(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 hh(e){let t=vr(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(` ${N.bold("Stage this data")} ${N.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=on(a.reason,86);r.push(` ${N.cyan(cn(`${a.ids.length}\xD7`,4))} ${l[0]??""}`);for(let m of l.slice(1))r.push(` ${m}`);let p=a.ids.slice(0,4).join(" \xB7 ");r.push(N.gray(` ${p}${a.ids.length>4?` \xB7 +${a.ids.length-4} more`:""}`))}n.length>i&&r.push(N.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(` ${re("\u2298",N.cyan)}${s} shot${s===1?"":"s"} need${s===1?"s":""} a data-testid from your developers \u2014 ${N.bold("/screenshot checklist")} builds the hand-off.`)}return r}function fh(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=["",` ${re("\u26A0",N.yellow)}${r} selector request${r===1?"":"s"} quote${r===1?"s":""} source code that has since changed`+N.gray(" \u2014 your developers would go looking for something that isn't there any more"),N.gray(` Refresh the hand-off before sending it: ${N.bold("/screenshot checklist")}`)];return t&&s.push(N.gray(` ${o.slice(0,8).join(" \xB7 ")}${r>8?` \xB7 +${r-8} more`:""}`)),s}function mh(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=["",` ${re("\u26A0",N.yellow)}Some specs were written before later reliability fixes:`],p=(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(N.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(N.gray(p(o,w=>`${w.id}:${w.unguardedWaits.join(",")}`)))}if(a.length>0){let m=a.length;l.push(N.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(N.gray(p(a,w=>`${w.id}:${w.bareGoto.join(",")}`)))}if(i.length>0){let m=i.length;l.push(N.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(N.gray(p(i,w=>`${w.id}:${w.stalePause.join(",")}`)))}if(s.length>0){let m=s.length;l.push(N.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(N.gray(p(s,w=>`${w.id}:${w.handRolled.join(",")}`)))}if(r.length>0){let m=r.length,w=r.filter($=>$.mutates).length;l.push(N.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(N.gray(p(r,$=>$.id)))}return n?.commandInLead||l.push(N.gray(` Re-write them all with the current rules: ${N.bold("/screenshot author --all")}`)),l}function gh(e){let t=e.filter(n=>(n.unverifiedForce?.length??0)>0);return t.length===0?[]:["",` ${re("\u26A0",N.red)}${t.length} spec${t.length===1?"":"s"} force-click past Playwright's safety checks without asserting the result`+N.gray(" \u2014 if the click lands on nothing, the shot photographs the unchanged screen"),N.gray(` ${t.slice(0,6).map(n=>`${n.id}:${n.unverifiedForce.join(",")}`).join(" \xB7 ")}${t.length>6?` \xB7 +${t.length-6} more`:""}`),N.gray(` Re-author to check what the click did: ${N.bold("/screenshot author <id>")}`)]}var Ys=(e,t)=>e.length>=t?e:e+" ".repeat(t-e.length),cn=(e,t)=>e.length>=t?e:" ".repeat(t-e.length)+e;function yh(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 sb=new Set(["and","or","of","the","to","a","an","in","on","for","with","vs"]),ib=new Set(["ai","api","cli","ui","ux","url","id","http","https","json","xml","sdk","csv","pdf","oauth","sso","mfa","io","faq"]);function ab(e){return e.replace(/[-_]+/g," ").trim().split(/\s+/).filter(Boolean).map((n,o)=>{let r=n.toLowerCase();return ib.has(r)?r.toUpperCase():o>0&&sb.has(r)?r:r.charAt(0).toUpperCase()+r.slice(1)}).join(" ")}function al(e){if(!e)return{num:"",name:"(docs root)"};let t=/^(\d+)[-_](.+)$/.exec(e);return{num:t?t[1]:"",name:ab(t?t[2]:e)}}function lb(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).pop()??e}function th(e,t,n){let o=t>0?Math.round(e/t*n):0;return N.green("\u2588".repeat(o))+N.gray("\u2591".repeat(Math.max(0,n-o)))}function cb(e,t){let n=t>0?Math.round(e/t*100):0,o=cn(`${n}%`,4);return n===100?N.green(o):n>0?N.yellow(o):N.gray(o)}function wh(e,t){let n=new Map;for(let o of e){let r=yh(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 fl(e,t){let n=S=>e.filter(E=>E.state===S).length,o=n("captured"),r=n("placeholder"),s=n("spec"),i=n("annotated"),a=n("blocked"),l=n("broken"),p=n("rejected"),m=e.filter(S=>S.state==="spec"&&S.mutates).length,w=s>m,$=e.filter(S=>(S.unguardedWaits?.length??0)>0||(S.bareGoto?.length??0)>0).length,T=e.filter(S=>(S.stalePause?.length??0)>0||(S.handRolled?.length??0)>0).length,R=s>0||a>0||l>0,C=(S,E="")=>be(S,E,t);return o>0?{key:"annotate",cmd:C("/screenshot annotate")}:r>0?{key:"toSpec",cmd:t?`/screenshot author ${t}`:"/screenshot author --all"}:$>0&&R?{key:"crashy",cmd:t?`/screenshot author ${t}`:"/screenshot author --all"}:T>0&&R?{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(S=>S.state==="broken").id}`}:i>0?{key:"verify",cmd:C("/screenshot verify")}:p>0?{key:"rejected",cmd:C("/screenshot capture","--failed")}:{key:"done",cmd:t?`/push ${t}`:"/push"}}function ub(e,t){let n=(X,Ce)=>X.filter(Se=>Se.state===Ce).length,o=e.length,r=n(e,"verified"),s=n(e,"annotated"),i=n(e,"captured"),a=n(e,"rejected"),l=n(e,"spec"),p=n(e,"blocked"),m=n(e,"broken"),w=n(e,"placeholder"),$=new Set(e.map(X=>X.file)).size,T=wh(e,t),R=[];R.push(` ${N.bold("Screenshots")} ${N.green(`${r}/${o} verified`)} ${N.gray("\xB7")} ${s>0?N.blue(`${s} to verify`):N.gray("0 to verify")}`+(i>0?` ${N.gray("\xB7")} ${N.yellow(`${i} to annotate`)}`:"")+(a>0?` ${N.gray("\xB7")} ${N.magenta(`${a} rejected`)}`:"")+` ${N.gray("\xB7")} ${l>0?N.yellow(`${l} ready`):N.gray("0 ready")}`+(p>0?` ${N.gray("\xB7")} ${N.cyan(`${p} blocked`)}`:"")+(m>0?` ${N.gray("\xB7")} ${N.red(`${m} broken`)}`:"")+` ${N.gray("\xB7")} ${w>0?N.red(`${w} to spec`):N.gray("0 to spec")} `+N.gray(`across ${$} article${$===1?"":"s"}`));let C=o>0?Math.round(r/o*100):0;R.push(` [${th(r,o,32)}] ${N.bold(`${C}%`)}`),R.push("");let S=T.map(([X])=>al(X)),E=Math.min(32,Math.max(7,...S.map(X=>X.name.length))),I=X=>X.length>E?`${X.slice(0,E-1)}\u2026`:Ys(X,E),L=[...i>0?[{head:"To annotate",w:11,state:"captured",color:N.yellow}]:[],...s>0?[{head:"To verify",w:9,state:"annotated",color:N.blue}]:[],...a>0?[{head:"Rejected",w:8,state:"rejected",color:N.magenta}]:[],{head:"Ready",w:5,state:"spec",color:N.yellow},...p>0?[{head:"Blocked",w:7,state:"blocked",color:N.cyan}]:[],...m>0?[{head:"Broken",w:6,state:"broken",color:N.red}]:[],{head:"To spec",w:7,state:"placeholder",color:N.red}];R.push(N.gray(` ${Ys("#",2)} ${Ys("Chapter",E)} ${cn("Verified",8)} ${L.map(X=>cn(X.head,X.w)).join(" ")} Progress`));for(let[X,[,Ce]]of T.entries()){let Se=n(Ce,"verified"),Fe=Ce.length,{num:Bt,name:yn}=S[X],$t=Se===Fe,ft=I(yn),Gn=L.map(st=>{let Ht=n(Ce,st.state);return Ht>0?st.color(cn(String(Ht),st.w)):N.gray(cn("\u2014",st.w))}).join(" ");R.push(` ${N.cyan(Ys(Bt,2))} ${$t?N.green(ft):Se>0?ft:N.gray(ft)} ${$t?N.green(cn(`${Se}/${Fe}`,8)):cn(`${Se}/${Fe}`,8)} ${Gn} ${th(Se,Fe,10)} ${cb(Se,Fe)}`)}R.push("");let Y=m>0?` ${N.gray("\xB7")} ${m} spec${m===1?"":"s"} broken \u2014 ${N.bold(`/screenshot ${e.find(X=>X.state==="broken").id}`)} re-authors ${m===1?"it":"the first"}`:"",ce=e.filter(X=>X.state==="spec"&&X.mutates).length,ue=l>ce,ie=e.filter(X=>(X.unguardedWaits?.length??0)>0||(X.bareGoto?.length??0)>0).length,he=e.filter(X=>(X.stalePause?.length??0)>0||(X.handRolled?.length??0)>0).length,de=l>0||p>0||m>0,ke=!1,ae=fl(e).key;if(ae==="annotate")R.push(` ${re("\u25C8",N.blue)}${i} shot${i===1?"":"s"} taken but not drawn on \u2014 run ${N.bold("/screenshot annotate")}`+N.gray(` \u2014 no browser, seconds; the callouts are what make ${i===1?"it":"them"} publishable`)+Y);else if(ae==="toSpec")R.push(` ${re("\u2192",N.yellow)}${w} placeholder${w===1?"":"s"} still need a spec \u2014 run ${N.bold("/screenshot author --all")}${Y}`);else if(ae==="crashy")ke=!0,R.push(` ${re("\u2192",N.yellow)}${ie} spec${ie===1?"":"s"} would crash mid-run \u2014 re-write ${ie===1?"it":"them"} first: ${N.bold("/screenshot author --all")}`+N.gray(` \xB7 then ${N.bold("/screenshot capture")} (no browser time wasted on ${ie===1?"a shot":"shots"} that can't finish)`)+Y);else if(ae==="wrongOutput")ke=!0,R.push(` ${re("\u2192",N.yellow)}${he} spec${he===1?"":"s"} would shoot the wrong thing \u2014 re-write ${he===1?"it":"them"} first: ${N.bold("/screenshot author --all")}`+N.gray(` \xB7 then ${N.bold("/screenshot capture")} (a false skip or a misplaced callout costs the same browser time as a good shot)`)+Y);else if(ae==="ready"){let X=ce>0?N.gray(` \u2014 ${l-ce} in one go; ${ce} write${ce===1?"s":""} real data and run${ce===1?"s":""} one at a time`):"";R.push(` ${re("\u2192",N.yellow)}${l} spec${l===1?"":"s"} ready to capture \u2014 run ${N.bold("/screenshot capture")}${X}${Y}`)}else if(ae==="verify"&&l>0)R.push(` ${re("\u2192",N.blue)}${s} shot${s===1?"":"s"} awaiting verification \u2014 run ${N.bold("/screenshot verify")}`+N.gray(" \u2014 no browser needed")+N.gray(` \xB7 ${l} ready spec${l===1?"":"s"} write real data, so ${l===1?"it runs":"each runs"} only when named: /screenshot capture <id>`)+Y);else if(ae==="blocked")R.push(` ${re("\u2192",N.cyan)}${p} shot${p===1?"":"s"} blocked \u2014 stage the data below, then ${N.bold("/screenshot capture --blocked")}${Y}`);else if(ae==="broken")R.push(` ${re("\u2192",N.red)}${m} spec${m===1?"":"s"} broken \u2014 ${N.bold(`/screenshot ${e.find(X=>X.state==="broken").id}`)} re-authors ${m===1?"it":"the first"} (re-capturing fails the same way)`);else if(ae==="verify")R.push(` ${re("\u2192",N.blue)}${s} shot${s===1?"":"s"} awaiting verification \u2014 run ${N.bold("/screenshot verify")}`+N.gray(" \u2014 it checks each picture against what its article needs (no browser, no re-capture)"));else if(ae==="rejected"){let X=e.filter(Ce=>Ce.state==="rejected"&&Ce.repaired).length;R.push(` ${re("\u2691",N.magenta)}${a} shot${a===1?"":"s"} failed review \u2014 `+(X>0?`${X} spec${X===1?"":"s"} already repaired; re-capture with ${N.bold("/screenshot capture --failed")}`:`see the reasons below, then ${N.bold("/screenshot capture --failed")}`))}else R.push(` ${re("\u2713",N.green)}all ${o} verified \u2014 ${N.bold("/push")} embeds them in the articles`);if(r>0&&r<o){let X=T.filter(([,Ce])=>Ce.every(Se=>Se.state!=="verified")).map(([Ce])=>{let{num:Se,name:Fe}=al(Ce);return Se?`${Se} ${Fe}`:Fe});X.length>0&&R.push(N.gray(` Furthest behind: ${X.slice(0,5).join(" \xB7 ")}${X.length>5?" \u2026":""} (0% verified)`))}return R.push(...hh(e),...gh(e),...mh(e,!1,{commandInLead:ke}),...fh(e,!1)),R.push(""),R.push(N.gray(" Drill in: /screenshot list <chapter#> \xB7 /screenshot list --detail (all)")),R}function db(e,t,n){let o=new Set(e.map(l=>l.file)),r=e.filter(l=>l.state==="verified").length,s=e.filter(l=>l.state==="annotated").length,i=e.filter(l=>l.state==="captured").length,a=[` ${N.bold("Screenshots")}: ${e.length} placeholder${e.length===1?"":"s"} across ${o.size} article${o.size===1?"":"s"} \xB7 ${N.green(`${r} verified`)}${s>0?N.blue(` \xB7 ${s} to verify`):""}${i>0?N.yellow(` \xB7 ${i} to annotate`):""}${n?N.gray(` \xB7 scope ${n}`):""}`,""];for(let[l,p]of wh(e,t)){let m=p.filter(C=>C.state==="verified").length,{num:w,name:$}=al(l),T=w?`${w} \xB7 ${$}`:$;a.push(` ${N.bold(T)} ${N.gray(`(${m}/${p.length})`)}`);let R=new Map;for(let C of p){let S=lb(C.file),E=R.get(S)??[];R.has(S)||R.set(S,E),E.push(C)}for(let C of[...R.keys()].sort()){a.push(N.gray(` ${C}`));for(let S of R.get(C)){let E=ob[S.state];if(a.push(` ${re(nb[S.state],E)}${E(S.id)}`),(S.state==="blocked"||S.state==="broken"||S.state==="rejected")&&S.reason){for(let I of on(Ro(S.reason),84))a.push(N.gray(` ${I}`));S.state==="rejected"&&a.push(N.gray(` ${S.repaired?"spec repaired \u2014 re-capture to confirm":"spec not yet repaired"}`))}}}}return a.push(...hh(e),...gh(e),...mh(e,!0),...fh(e,!0)),a.push("",rb),a}function ni(e,t){let n=t?.scope;if(e.length===0)return[n?`No screenshot placeholders under ${n}.`:"No screenshot placeholders found in the docs."];let o=t?.docsDir??pl;return t?.detail||n?db(e,o,n):ub(e,o)}function ml(e,t){if(!t||!/^\d+$/.test(t))return t;let n=un(e)?.docsDir??pl,o=String(Number(t));for(let{file:r}of oh(e)){let s=yh(r,n),i=/^(\d+)/.exec(s);if(i&&String(Number(i[1]))===o)return s}return t}function kh(e,t){let r=e.map(a=>" ".repeat(a.depth)+a.label),s=Math.max(0,...e.map((a,l)=>a.note?Vs(r[l]):0)),i=Math.min(s,Math.max(0,t-2-24));return e.map((a,l)=>{let p=r[l];if(!a.note)return{head:p,note:""};let m=Math.max(2,i+2-Vs(p)),w=a.note.trim(),$=t-Vs(p)-m;return{head:p+" ".repeat(m),note:$>1&&Vs(w)>$?`${w.slice(0,$-1)}\u2026`:w}})}function pb(e){let t=e.replace(/\\/g,"/").split("/").filter(Boolean),n=t.pop()??e;return{category:t.pop()??"(docs root)",article:n}}function xo(e,t,n){let o=new Map;for(let s of t){let{category:i,article:a}=pb(s.file),l=o.get(i)??new Map;o.set(i,l);let p=l.get(a)??[];l.set(a,p),p.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(p=>p.id),l=a.length>0;l&&e.push({kind:"category",action:n,label:`${s} (${a.length})`,ids:a,depth:1});for(let p of[...i.keys()].sort()){let m=i.get(p),w=m.filter(r).map(R=>R.id),$=w.length>0;$&&e.push({kind:"article",action:n,label:`${p} (${w.length})`,ids:w,depth:l?2:1});let T=(l?1:0)+($?1:0)+1;for(let R of m){let C=n==="capture"&&R.mutates?" \u26A0 creates real data \u2014 runs only alone":void 0;e.push({kind:"shot",action:n,label:R.id,ids:[R.id],depth:T,...C?{note:C}:{}})}}}}function tl(e){return e?Ro(e):""}function gl(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 ${tl(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 ${tl(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 ${tl(i.reason)}`})}}function bh(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}),xo(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}),xo(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}),xo(o,s,"annotate"),gl(o,e.filter(i=>i.state==="blocked"),e.filter(i=>i.state==="broken"),e.filter(i=>i.state==="rejected")),o}var ll=["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(`
|
|
350
|
+
`);function hb(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 cl="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 $h(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(`
|
|
351
|
+
`),"",...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=>uh(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.",ll,cl].join(`
|
|
352
|
+
`)}async function oi(e,t,n){let o=br(e),r=Nn(t?.cwd??process.cwd());if(r&&console.log(N.gray(r)),o.mode==="list"){let l=t?.cwd??process.cwd(),p=ml(l,o.scope),m=un(l)?.docsDir??pl,w=Le(l,p);for(let $ of ni(w,{scope:p,detail:o.detail,docsDir:m}))console.log($);return{kind:"continue"}}if(o.mode==="single"){let l=jn(t?.cwd??process.cwd(),o.id),p=l===null?[]:hl(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.",ll,cl,...n?.prior?["",...hb(n.prior)]:[],...p.length>0?["",...uh(p,"RULE VIOLATIONS already in the existing spec \u2014 fix every one:")]:[]].join(`
|
|
353
|
+
`),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.`,ll,cl].join(`
|
|
354
|
+
`),a=o.mode==="scope"?`/screenshot ${o.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:i,display:a}}var xr=3;function wl(e){return[`Run the push-to-d360 skill for the article at: ${e}`,"","Steps you must follow:","1. Read the article markdown, using the repo-relative path exactly as given above (it resolves against the working directory; do not reconstruct an absolute path).","2. Compute the D360 publish form (strip the YAML frontmatter and the H1 title, normalize cross-article links). For each <!-- SCREENSHOT ... --> block, read its id BEFORE stripping the block: when <outputDir>/<id>.png exists (the annotated capture), upload it (d360_search_drive first to reuse, else d360_upload_drive_file) and replace the visible [Screenshot: ...] line with the image markdown; only when no PNG exists does the visible line stay as text.","3. Look up the article ID in <repo>/d360-category-map.json. If present, call the document360 MCP update-article tool. If absent, call create-article with local_path set to the repo-relative .md path (the tool records the new ID + sync base in the category map itself; do not edit the articles map by hand).","4. Report what changed. The article is saved on Document360 as a DRAFT \u2014 do not take it live; /publish does that once it has been signed off."].join(`
|
|
355
|
+
`)}var vh={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 pushing overwrites the portal edit"};function kl(e){return e.filter(t=>t.path!==null&&t.status in vh&&!t.link).map(t=>({path:t.path,label:vh[t.status]}))}function Ln(e){let t=kl(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 In(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 Co(e,t){let n=$b(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. Run /publish to take ${n===1?"it":"them"} live once ${n===1?"it has":"they have"} been signed off.`}function si(e){return e.filter(t=>t.link).length}function bl(e,t){try{let n=xh(e,yl(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=Tb(fb(mb(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 Eh(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:`${wo(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}function Rr(e){return[`Run the push-to-d360 skill for ALL of these ${e.length} articles, one by one:`,"",...e.map(t=>`- ${t}`),"","Use the repo-relative paths exactly as listed (they resolve against the working directory; do not reconstruct absolute paths). Apply the normal per-article publish flow (frontmatter/H1/screenshot-comment strips, link normalization; update when mapped, create with local_path when not). Compute each publish form IN MEMORY and pass it straight to the tool, and NEVER write it to disk (no *.publish.md siblings, no temp copies anywhere in the docs tree; the local .md files stay untouched). If one article fails, note it and continue. Finish with a summary table (article | created/updated | failures). Everything you write is a DRAFT \u2014 never take an article live."].join(`
|
|
356
|
+
`)}async function So(e,t){try{let n=yl(e,t),o=n.project.projectId,r=n.project.workspaceId;return!o||!r||(await Sb({profile:n.name,connection:n.connection},{cwd:e,profile:n.name,projectPath:`/v3/projects/${o}`,workspaceId:r,verifyHidden:!1})).kind!=="created"?null:`\u2139 Created a hidden "${Pb}" folder on Document360 \u2014 it's where your reviewers leave feedback for d360-writer to action (hidden from readers; its README explains how). /catch-up picks up what they write.`}catch{return null}}var ct="--skip-review";function Cr(e,t){return vb(e,t)}function ii(e,t){try{return Cr(e,Ch(e,t)).length}catch{return 0}}function Tt(e,t,n="",o){let r=ii(e,o),s=$l(e,o);if(r===0&&s===0)return t;let i=o?` ${o}`:"",a=o?"/push":"/push --all",l=o&&!o.endsWith(".md")?` in ${o}`:"";if(r>0){let m=r===1?"":"s",w=s>0?` ${s} also break house style rules \u2014 /lint${i} --fix clears those afterwards.`:"",$=`/review${i} --blocked --fix`;return{text:`${n}${r} article${m}${l} ${r===1?"carries":"carry"} text no editor has read, so pushing ${r===1?"it is":"them is"} blocked. ${$} reads ${r===1?"it":"just those"} and applies its fixes.${w} Then ${a}.`,cmd:$}}return{text:`${n}${s} article${s===1?"":"s"}${l} break${s===1?"s":""} house style rules that block publishing. /lint${i} --fix corrects them in place \u2014 finding them costs nothing \u2014 then ${a}.`,cmd:`/lint${i} --fix`}}function $l(e,t){try{return Rh(e,Ch(e,t)).length}catch{return 0}}function Dh(e,t){return Rh(e,t)}function vl(e,t,n){try{let o=xh(e,yl(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 xl(e,t,n,o=0,r,s){let i=`/push${s?` ${s}`:" --all"}`,a=I=>t[I.index]?.paths.length??0,l=e.filter(I=>I.ok),p=e.filter(I=>!I.ok),m=e.reduce((I,L)=>I+a(L),0),w=l.reduce((I,L)=>I+a(L),0),$=n==="api"?`${tt(e.reduce((I,L)=>I+L.costUsd,0))} total`:ln(e.reduce((I,L)=>I+L.outputTokens,0)),T=`${l.length}/${e.length} batch${e.length===1?"":"es"}`,R=I=>`${I} article${I===1?"":"s"}`,C=[],S=r?Ct({blocked:r.blocked,allEmpty:r.allEmpty,aborted:!1},"The push"):null;if(S)return C.push(...S),C.push(`Nothing reached Document360. Re-run ${i} once that is fixed.`),o>0&&C.push(In(o)),C;if(r&&m>0&&r.recorded===0){C.push(`\u2717 Nothing was pushed \u2014 the ${R(m)} in this run are not recorded in the category map, so none of them reached Document360.`),C.push(`Run /doctor (this is usually the agent runtime not running), then re-run ${i}.`);for(let I of p)I.error&&C.push(` \u2717 ${I.label} \u2014 ${I.error}`);return o>0&&C.push(In(o)),C}if(p.length===0&&(!r||r.recorded>=m))C.push(`Pushed ${R(m)} (${T}) successfully \xB7 ${$}.`),C.push(`Saved on Document360 as draft${m===1?"":"s"} \u2014 readers don't see ${m===1?"it":"them"} until /publish takes ${m===1?"it":"them"} live.`);else if(p.length===0&&r)C.push(`Pushed ${r.recorded}/${R(m)} (${T}) \xB7 ${$}.`),C.push(`${m-r.recorded} article${m-r.recorded===1?"":"s"} reported no error but ${m-r.recorded===1?"is":"are"} not recorded on Document360 \u2014 re-run ${i} to retry just those.`);else{C.push(`Pushed ${r?r.recorded:w}/${R(m)} (${T}) \xB7 ${$}.`),C.push(`${p.length} batch${p.length===1?"":"es"} failed \u2014 re-run ${i} to retry just the rest (articles already on Document360 are skipped):`);for(let I of p)C.push(` \u2717 ${I.label}${I.error?` \u2014 ${I.error}`:""}`)}let E=r?Hs(r):null;return E&&C.push(E),o>0&&C.push(In(o)),C}async function Pt(e,t,n=0,o){let r=xb(e.cwd,t,{allowUnreviewed:o?.skipReview===!0,allowStyleErrors:o?.skipStyle===!0});if(!r.clear){for(let a of Rb(r,t.length))console.log(G(a));return{kind:"continue"}}let{model:s}=kb(e.cwd,"standard"),i=async(a,l)=>{let p=yb(a);console.log(y(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"} in ${p.length} batch${p.length===1?"":"es"} (\u2264${xr} agents at once) on ${s}\u2026`)),l||console.log(y(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let m=!1;for await(let w of bb({cwd:e.cwd,partitions:p,promptFor:$=>Rr($.paths),concurrency:xr,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),allowUnreviewedPublish:o?.skipReview===!0,allowStyleErrors:o?.skipStyle===!0,model:s}))if(w.type==="partition_status")w.status==="running"?console.log(y(` \u25B8 ${w.label} \u2014 pushing\u2026`)):w.status==="done"?console.log(V(` \u2713 ${w.label}`)):console.log(j(` \u2717 ${w.label}`));else if(w.type==="run_done"){m=w.aborted,console.log("");let $=process.env.ANTHROPIC_API_KEY?"api":"subscription",T=vl(e.cwd,a,e.profileName),R=!w.aborted&&(!!w.blocked||!!w.allEmpty||a.length>0&&T===0);for(let I of xl(w.results,p,$,l?0:n,{recorded:T,...w.blocked?{blocked:w.blocked}:{},...w.allEmpty?{allEmpty:!0}:{}},o?.scope))console.log(w.ok&&!R?V(I):G(I));if(R)continue;let C=bl(e.cwd,e.profileName);C&&console.log(y(C));let S=Co(e.cwd,e.profileName);S&&console.log(y(S));try{let I=Ph(await Sh({cwd:e.cwd,profileName:e.profileName,onRateLimit:L=>console.log(y(` Document360 rate limit \u2014 waiting ${Math.ceil(L.waitMs/1e3)}s\u2026`))}));I&&console.log(I.startsWith("\u26A0")?G(I):y(I))}catch{}try{let I=Ah(await Th({cwd:e.cwd,profileName:e.profileName}));I&&console.log(y(I))}catch{}let E=await So(e.cwd,e.profileName);E&&console.log(y(E))}return m};try{if(!await i(t,!1)){let l=await Rl(e.cwd,e.profileName,t);l.length>0&&await i(l,!0)}}catch(a){console.log(j(`Push run failed: ${a.message}`))}return console.log(""),{kind:"continue"}}async function ai(e,t,n){let o=wb(e,n);if(o.length===0)return[];let r=new Set(kl((await ri({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function Rl(e,t,n){try{let o=new Set(n),r=await ri({cwd:e,profileName:t});return kl(r.entries).map(s=>s.path).filter(s=>o.has(s))}catch{return[]}}async function li(e,t){let n=Ve(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(j(n.reason)),{kind:"continue"};let o=e.includes(ct),r=e.includes(Cb),s=e[0];if(e.includes("--screenshots")||e.includes("--shots")){let i=t?.cwd??process.cwd(),a=e.find(T=>!T.startsWith("--")),l=Le(i),p=Js(l,a);if(p.length===0){let T=l.filter(R=>R.state==="captured").length;return console.log(y(T>0?`${T} screenshot${T===1?" has":"s have"} been taken but the callouts aren't drawn on yet, so there is nothing to embed \u2014 /screenshot annotate finishes ${T===1?"it":"them"}.`:a?`No captured screenshots in ${a} \u2014 /push --screenshots covers the whole knowledge base.`:"No captured screenshots yet \u2014 /screenshot capture first.")),{kind:"continue"}}let m=Zs(l,a);m&&console.log(m);let w=ei(l);w&&console.log(w);let $=be("","--screenshots",a).trim();return t?await Pt(t,p,0,{skipReview:o,skipStyle:r,scope:$}):{kind:"forward-to-agent",prompt:Rr(p),display:`/push ${$}`}}if(s==="--related"&&e[1]){if(!t)return{kind:"continue"};let i=await ai(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return i.length===0?(console.log(V("\u2713 All related articles are already on Document360.")),{kind:"continue"}):await Pt(t,i,0,{skipReview:o,skipStyle:r,scope:`--related ${e[1]}`})}if(s==="--all"){console.log(y("Checking what needs pushing\u2026"));try{let i=await ri({cwd:t?.cwd??process.cwd()}),{clean:a,conflicts:l}=Ln(i.entries),p=si(i.entries),m=e.includes("--force")&&l.length>0;p>0&&console.log(G(`\u26A0 ${p} 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(In(l.length)));let w=m?[...a,...l]:a;if(w.length===0){if(l.length>0){let T=Co(t?.cwd??process.cwd(),t?.profileName);return T&&console.log(y(T)),console.log(y("Resolve the conflicts: /resolve")),{kind:"continue"}}console.log(V(p>0?"\u2713 Nothing else is ahead of Document360 to push.":"\u2713 Nothing is ahead of Document360 \u2014 nothing to push."));let $=Co(t?.cwd??process.cwd(),t?.profileName);if($&&console.log(y($)),t)try{let T=Ph(await Sh({cwd:t.cwd,profileName:t.profileName,onRateLimit:C=>console.log(y(` Document360 rate limit \u2014 waiting ${Math.ceil(C.waitMs/1e3)}s\u2026`))}));T&&console.log(T.startsWith("\u26A0")?G(T):y(T));let R=Ah(await Th({cwd:t.cwd,profileName:t.profileName}));R&&console.log(y(R))}catch{}return{kind:"continue"}}return t?await Pt(t,w.map($=>$.path),m?0:l.length,{skipReview:o,skipStyle:r}):{kind:"forward-to-agent",prompt:Rr(w.map($=>$.path)),display:"/push --all"}}catch(i){return console.log(j(`Could not compute sync status: ${i.message}`)),{kind:"continue"}}}if(s&&s.startsWith("--")&&(s=e.find(i=>!i.startsWith("--"))??""),!s){console.log(y("Checking what needs pushing\u2026"));let i,a=0;try{let l=await ri({cwd:t?.cwd??process.cwd()}),{clean:p,conflicts:m}=Ln(l.entries);i=p,a=m.length;let w=si(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(In(m.length))),i.length===0&&m.length>0)return console.log(y("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(l){return console.log(j(`Could not compute sync status: ${l.message}`)),console.log(y("Push a specific article: /push <article-path>")),{kind:"continue"}}if(i.length===0)return console.log(V("\u2713 Nothing is ahead of Document360 \u2014 nothing to push.")),console.log(y(" (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} ${y(`(${l.label})`)}`);return console.log(y("Run: /push <article-path>")),{kind:"continue"}}try{s=await t.withPausedInput(()=>gb({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(y("Cancelled.")),{kind:"continue"}}if(s==="--all")return await Pt(t,i.map(l=>l.path),a,{skipReview:o,skipStyle:r})}return{kind:"forward-to-agent",prompt:wl(s),display:`/push ${s}`}}te();import{select as Eb}from"@inquirer/prompts";import{computeSyncStatus as Db,localAheadPaths as Nb,pendingDrafts as jb,publishArticleLive as Ib,publishGateVerdict as Lb,publishGateLines as Ob,resolveActiveProfile as XA,SKIP_STYLE_FLAG as _b}from"document360-engine";var Ab={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."},Nh=new Set;function Ut(e){let t=Ab[e.replace(/^\//,"")];return!t||Nh.has(e)?null:(Nh.add(e),t)}var Mb=150,Fb=e=>e>0?new Promise(t=>setTimeout(t,e)):Promise.resolve(),Sl=e=>e===1?"":"s",Cl=e=>e.replace(/\\/g,"/").split("/").pop()??e;function Pl(e){return e.includes("--screenshots")||e.includes("--shots")||e[0]==="--related"}async function Tl(e,t,n){await Db({cwd:e,profileName:t});let o=n?n.replace(/\\/g,"/").replace(/\/+$/,""):null;return jb(e,t).filter(r=>!o||r.path===o||r.path.startsWith(`${o}/`)).map(r=>({...r,label:r.path}))}function Wb(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 Al(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=Nb(e,t).filter(a=>!s||a===s||a.startsWith(`${s}/`)).length;return i>0&&r.push(`${i} article${Sl(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 El(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 Ib({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 Fb(Mb)}return r}function Dl(e){let{published:t,blocked:n,failed:o}=e,r=[];if(t.length>0){r.push(`\u2713 ${t.length} article${Sl(t.length)} ${t.length===1?"is":"are"} now live \u2014 readers see ${t.length===1?"it":"them"} now.`);for(let s of t.slice(0,3))s.url&&r.push(` \u2B95 ${s.url}`)}if(n.length>0){r.push(`\u2717 ${n.length} refused by the publish gates \u2014 /review --blocked --fix clears ${n.length===1?"it":"them"}:`);for(let s of n.slice(0,3))r.push(` \xB7 ${Cl(s.path)}`);n.length>3&&r.push(` \xB7 \u2026and ${n.length-3} more`)}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 ${Cl(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 jh(e,t){let n=t?.cwd??process.cwd(),o=Ut("publish");if(Pl(e))return o&&console.log(y(`\u2192 ${o}`)),console.log(y("Running /push\u2026")),li(e,t);let r=Ve(n,t?.profileName);if(!r.ok)return console.log(j(r.reason)),{kind:"continue"};o&&console.log(y(`\u2192 ${o}`));let s=e.includes(ct),i=e.includes(_b),a=e.includes("--all"),l=e.find(T=>!T.startsWith("--"));console.log(y("Checking what is waiting to go live\u2026"));let p;try{p=await Tl(n,t?.profileName,l)}catch(T){return console.log(j(`Could not check Document360: ${T.message}`)),{kind:"continue"}}if(p.length===0){for(let T of Al(n,t?.profileName,l).lines)console.log(T.startsWith("\u2713")?V(T):y(T));return{kind:"continue"}}let m=Lb(n,p.map(T=>T.path),{allowUnreviewed:s,allowStyleErrors:i});if(!m.clear){for(let T of Ob(m,p.length,l))console.log(G(T));return{kind:"continue"}}console.log(""),console.log(`${p.length} draft${Sl(p.length)} ${p.length===1?"is":"are"} ahead of what readers see:`);for(let T of Wb(p.slice(0,12)))console.log(y(T));p.length>12&&console.log(y(` \u2026and ${p.length-12} more`)),console.log("");let w=p;if(!a){let T=await Eb({message:"Publish live to your readers?",choices:[{name:`Yes \u2014 publish all ${p.length} live`,value:"all"},...p.slice(0,8).map(R=>({name:`Just ${R.label}`,value:R.path})),{name:"No \u2014 leave them as drafts",value:"none"}]});if(T==="none")return console.log(y("Left as drafts. Nothing changed.")),{kind:"continue"};T!=="all"&&(w=p.filter(R=>R.path===T))}let $=await El(n,t?.profileName,w,{skipReview:s,skipStyle:i,onProgress:(T,R,C)=>console.log(y(` \u25B8 ${T+1}/${R} ${Cl(C)}\u2026`))});console.log("");for(let T of Dl($))console.log(T.startsWith("\u2713")?V(T):T.startsWith("\u2717")?G(T):y(T));return{kind:"continue"}}async function Sr(){return{kind:"forward-to-agent",prompt:["Run the gap-analysis skill against this repo.","","Follow its stages in order:","1. d360_sync_status first; stop if any article is changed in both places, or changed on Document360 and not yet pulled down (the local copy cannot be trusted until that is resolved). Say which articles and what to do about them, in plain words, never the internal status word.","2. git diff since the lastAnalyzedCommit marker in d360-category-map.json (or last 30 days if no marker), filtered to the authoritativeSourceFiles paths.","2.5. d360_pending_hints: 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(`
|
|
357
|
+
`),display:"/audit"}}te();import{readProjectConfig as Ub}from"document360-engine";function Nl(){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(`
|
|
358
|
+
`)}async function Ih(e,t){let n=t?.cwd??process.cwd();return Ub(n)?{kind:"forward-to-agent",prompt:Nl(),display:"/discover"}:(console.log(j("No d360-writer config here. Run /init first.")),{kind:"continue"})}te();import{checkbox as Bb}from"@inquirer/prompts";import{inventoryRepo as Hb,readProjectConfig as Lh,writeProjectConfig as qb}from"document360-engine";function jl(e,t){let n=Lh(e);n&&(n.authoritativeSourceFiles=t,qb(n,e))}function ci(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 Oh(e,t){let n=t?.cwd??process.cwd();if(!Lh(n))return console.log(j("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=Hb(n);if(o.length===0)return console.log(y('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(z("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${y(ci(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>Bb({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${ci(s)})`,value:s.path,checked:s.recommended})),pageSize:20}))}catch{return console.log(y("Cancelled.")),{kind:"continue"}}if(r.length===0)return console.log(y("Nothing selected \u2014 scope unchanged.")),{kind:"continue"};jl(n,r),console.log(V(`\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"}}te();import{confirm as Jb}from"@inquirer/prompts";import{applyPull as Ol,computeSyncStatus as Vh,compareRemoteSources as Zb,planPull as Yh,planImport as e$,applyImport as t$,establishBaselines as n$,rebaselineServerMeta as o$,D360AuthError as r$}from"document360-engine";te();var _h=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /push <path>):",paint:j,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:z,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:j,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:j,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint:$e,mark:"X"},{status:"untracked-local",header:"New here \u2014 not on Document360 yet (publish to add them):",paint:y,mark:"?"},{status:"untracked-remote",header:"On Document360 \u2014 not in your local docs yet (run /pull to import them):",paint:y,mark:"?"},{status:"unknown-base",header:"Tracked, not yet compared \u2014 run /pull --baseline to set a baseline (or the next publish/pull sets one):",paint:$e,mark:"\xB7"}];function Gb(e){return e.path?e.path:`${e.title??"(untitled)"} ${$e(`[${e.articleId}]`)}`}function Vb(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 ui(e,t){let n=[],o=e.entries.filter(m=>m.link);if(o.length>0){n.push(""),n.push(Ge("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??"")} ${$e(`\u2192 "${m.link.title}"`)}`)}for(let m of _h){let w=e.entries.filter($=>$.status===m.status&&!(m.status==="untracked-local"&&$.link));if(w.length!==0){n.push(""),n.push(Ge(m.header));for(let $ of w)n.push(` ${m.paint(m.mark)} ${m.paint(Gb($))}${$.detail?$e(` (${$.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?V("\u2713 everything up to date"):[r>0?V(`\u2713 ${r} up to date`):null,a>0?`${a} to link`:null,..._h.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($e(" \xB7 ")),p=t!==void 0?` \xB7 synced in ${Vb(t)}`:"";return n.push(l+$e(` \xB7 ${s} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${p}`)),n}import{structuredPatch as Yb}from"diff";import Mh from"picocolors";var Fh=80,Kb="\x1B[48;2;74;28;28m",zb="\x1B[48;2;24;66;24m",Wh="\x1B[49m",Il=e=>String(e).padStart(5);function Uh(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}function Bh(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 ut(e,t,n){let o=$=>{let T=$.replace(/\r\n/g,`
|
|
359
359
|
`);return T.endsWith(`
|
|
360
360
|
`)||T===""?T:T+`
|
|
361
|
-
`},r=o(e),s=o(t);if(r===s)return null;let i=Math.max(20,n-10),a=Gb("a","b",r,s,"","",{context:3}),l=0,p=0,m=[];a.hunks.forEach(($,T)=>{T>0&&m.push(Oh.gray(" \u2026"));let C=$.oldStart,R=$.newStart,S=[],E=[],I=()=>{for(let L=0;L<S.length;L++){let Y=L<E.length?Fh(S[L],E[L]):void 0;p++,m.push(`${Vb}${Ll(C++)} - ${Wh(S[L],i,Y)}${Mh}`)}for(let L=0;L<E.length;L++){let Y=L<S.length?Fh(S[L],E[L]):void 0;l++,m.push(`${Yb}${Ll(R++)} + ${Wh(E[L],i,Y)}${Mh}`)}S=[],E=[]};for(let L of $.lines){let Y=L[0],ce=L.slice(1);Y==="-"?S.push(ce):Y==="+"?E.push(ce):(I(),m.push(Oh.gray(Ll(R))+" "+ce.slice(0,i)),C++,R++)}I()});let w=m.slice(0,_h);return{added:l,removed:p,lines:w,hidden:Math.max(0,m.length-_h)}}ne();import{select as Kb}from"@inquirer/prompts";import{applyPull as Bh,computeSyncStatus as zb,planPull as Uh}from"document360-engine";var pi=e=>e===1?"":"s";async function Ol(e,t,n=1){console.log(""),console.log(`${z("\u25CF")} ${Ge(t.title)} ${be(`(${t.path})`)}`);for(let i of t.notes)console.log(q(` \u26A0 ${i}`));let o=ut(t.oldContent,t.newContent,Math.max(40,(process.stdout.columns??80)-1));if(o){console.log(be(` \u23BF local \u2192 portal: +${o.added} / -${o.removed} line${pi(o.added+o.removed)}`));for(let i of o.lines)console.log(i);o.hidden>0&&console.log(y(` \u2026 +${o.hidden} more diff lines`))}else console.log(y(" Local already matches the portal content \u2014 resolving just advances the sync base."));let r=n>1,s=await e.withPausedInput(()=>Kb({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"?(Bh({cwd:e.cwd,profileName:e.profileName},t),console.log(V(" \u2713 Took the portal copy (local overwritten, sync base advanced).")),"took-portal"):s==="local"?"keep-local":s==="skip"?(console.log(y(" Skipped \u2014 still a conflict.")),"skipped"):s==="local-all"?"keep-local-all":s==="portal-all"?"took-portal-all":"skipped-all"}async function Hh(e,t){let n=Ve(t.cwd,t.profileName);if(!n.ok)return console.log(j(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let s=(await zb({cwd:t.cwd,profileName:t.profileName})).entries.filter(a=>a.status==="conflict"&&a.path).map(a=>a.path);if(o){if(!s.includes(o))return console.log(V(`${o} isn't in conflict \u2014 nothing to resolve.`)),{kind:"continue"};s=[o]}if(s.length===0)return console.log(V("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let i=[];for(let[a,l]of s.entries()){let p=await Uh({cwd:t.cwd,profileName:t.profileName,relPath:l}),m=await Ol(t,p,s.length-a);if(m==="keep-local"&&i.push(l),!m.endsWith("-all"))continue;let w=s.slice(a);if(m==="keep-local-all")i.push(...w),console.log(y(` Keeping local for all ${w.length} \u2014 publishing them over the portal.`));else if(m==="took-portal-all"){let $=0;for(let T of w)try{Bh({cwd:t.cwd,profileName:t.profileName},await Uh({cwd:t.cwd,profileName:t.profileName,relPath:T})),$++}catch(C){console.log(j(` \u2717 ${T}: ${C.message}`))}console.log(V(` \u2713 Took the portal copy of ${$} article${pi($)} (local overwritten, sync base advanced).`))}else console.log(y(` Skipped all ${w.length} \u2014 still conflict${pi(w.length)}.`));break}if(i.length>0)return console.log(y(`Publishing ${i.length} kept-local article${pi(i.length)} over the portal\u2026`)),await Pt(t,i)}catch(r){console.log(j(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function Vh(e,t){let n=Ve(t.cwd,t.profileName);if(!n.ok)return console.log(j(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await o$(t),{kind:"continue"};if(o==="--baseline")return await r$(t,e.filter(i=>i!=="--baseline")),{kind:"continue"};if(o==="--compare")return await s$(t),{kind:"continue"};if(o)return console.log(j(`Unknown option: ${o}`)),console.log(y("Usage: /pull pull portal edits + import new portal articles")),console.log(y(" /pull <path> pull one article (or resolve a conflict)")),console.log(y(" /pull --status drift report only (no writes)")),console.log(y(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await i$(t,r),{kind:"continue"};console.log(y("Pulling changes from Document360\u2026"));let s=await Ml({cwd:t.cwd,profileName:t.profileName});for(let i of Fl(s))console.log(i.tone==="ok"?V(i.text):i.tone==="warn"?q(i.text):y(i.text));console.log("")}catch(r){r instanceof n$?console.log(j(r.message)):console.log(j(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function Ml(e){let t=await qh({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 Gh({cwd:e.cwd,profileName:e.profileName,relPath:o.path});_l({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 Jb({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});Zb({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 hi=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,On=e=>e===1?"":"s";function Fl(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${On(e.pulled.length)} into local: ${hi(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${On(e.imported.length)}: ${hi(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${On(e.toPublish)} changed locally \u2014 /push saves them to Document360.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${On(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). (${hi(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${On(e.failed.length)} failed: ${hi(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 o$(e){console.log(y("Checking Document360 for drift\u2026"));let t=Date.now(),n=await qh({cwd:e.cwd,profileName:e.profileName});for(let o of di(n,Date.now()-t))console.log(o);console.log("")}async function r$(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(y(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await e$({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await t$({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(V("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(V(`\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(V(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(q(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(y(` - ${s.path} (${s.reason})`))}}async function s$(e){console.log(y("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await Qb({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${Ge(String(t.legacyCount))} \xB7 Manifest: ${Ge(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(V("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(j(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(q(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(q(` ${t.onlyInManifest.length} only in the manifest: ${t.onlyInManifest.slice(0,5).join(", ")}`)),console.log(y(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function i$(e,t){let n=t.replace(/\\/g,"/"),o=await Gh({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await Ol(e,o)==="keep-local"&&(console.log(y(`Publishing ${o.path} over the portal\u2026`)),await Pt(e,[o.path]));return}console.log(""),console.log(`${z("\u25CF")} ${Ge(o.title)} ${be(`(${o.path})`)}`);for(let i of o.notes)console.log(q(` \u26A0 ${i}`));let r=ut(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!r){console.log(y(" Local file already matches the remote content \u2014 advancing the sync base only.")),_l({cwd:e.cwd,profileName:e.profileName},o);return}console.log(be(` \u23BF Added ${r.added} line${On(r.added)}, removed ${r.removed} line${On(r.removed)}`));for(let i of r.lines)console.log(i);if(r.hidden>0&&console.log(y(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>Xb({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(y(" Skipped."));return}_l({cwd:e.cwd,profileName:e.profileName},o),console.log(V(` \u2713 Pulled ${o.path} (sync base advanced).`))}ne();import{statSync as a$}from"node:fs";import{resolve as l$}from"node:path";import{estimateBulkCost as c$,planPartitions as u$,readProjectConfig as d$,resolveModelForOperation as p$,runPartitioned as h$,trackedArticlePaths as f$}from"document360-engine";var Wl=3;function Ul(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 Bl(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Hl(e,t){return t.map(n=>{let o=0;try{o=a$(l$(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function ql(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:
|
|
361
|
+
`},r=o(e),s=o(t);if(r===s)return null;let i=Math.max(20,n-10),a=Yb("a","b",r,s,"","",{context:3}),l=0,p=0,m=[];a.hunks.forEach(($,T)=>{T>0&&m.push(Mh.gray(" \u2026"));let R=$.oldStart,C=$.newStart,S=[],E=[],I=()=>{for(let L=0;L<S.length;L++){let Y=L<E.length?Uh(S[L],E[L]):void 0;p++,m.push(`${Kb}${Il(R++)} - ${Bh(S[L],i,Y)}${Wh}`)}for(let L=0;L<E.length;L++){let Y=L<S.length?Uh(S[L],E[L]):void 0;l++,m.push(`${zb}${Il(C++)} + ${Bh(E[L],i,Y)}${Wh}`)}S=[],E=[]};for(let L of $.lines){let Y=L[0],ce=L.slice(1);Y==="-"?S.push(ce):Y==="+"?E.push(ce):(I(),m.push(Mh.gray(Il(C))+" "+ce.slice(0,i)),R++,C++)}I()});let w=m.slice(0,Fh);return{added:l,removed:p,lines:w,hidden:Math.max(0,m.length-Fh)}}te();import{select as Xb}from"@inquirer/prompts";import{applyPull as qh,computeSyncStatus as Qb,planPull as Hh}from"document360-engine";var di=e=>e===1?"":"s";async function Ll(e,t,n=1){console.log(""),console.log(`${z("\u25CF")} ${Ge(t.title)} ${$e(`(${t.path})`)}`);for(let i of t.notes)console.log(G(` \u26A0 ${i}`));let o=ut(t.oldContent,t.newContent,Math.max(40,(process.stdout.columns??80)-1));if(o){console.log($e(` \u23BF local \u2192 portal: +${o.added} / -${o.removed} line${di(o.added+o.removed)}`));for(let i of o.lines)console.log(i);o.hidden>0&&console.log(y(` \u2026 +${o.hidden} more diff lines`))}else console.log(y(" Local already matches the portal content \u2014 resolving just advances the sync base."));let r=n>1,s=await e.withPausedInput(()=>Xb({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"?(qh({cwd:e.cwd,profileName:e.profileName},t),console.log(V(" \u2713 Took the portal copy (local overwritten, sync base advanced).")),"took-portal"):s==="local"?"keep-local":s==="skip"?(console.log(y(" Skipped \u2014 still a conflict.")),"skipped"):s==="local-all"?"keep-local-all":s==="portal-all"?"took-portal-all":"skipped-all"}async function Gh(e,t){let n=Ve(t.cwd,t.profileName);if(!n.ok)return console.log(j(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let s=(await Qb({cwd:t.cwd,profileName:t.profileName})).entries.filter(a=>a.status==="conflict"&&a.path).map(a=>a.path);if(o){if(!s.includes(o))return console.log(V(`${o} isn't in conflict \u2014 nothing to resolve.`)),{kind:"continue"};s=[o]}if(s.length===0)return console.log(V("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let i=[];for(let[a,l]of s.entries()){let p=await Hh({cwd:t.cwd,profileName:t.profileName,relPath:l}),m=await Ll(t,p,s.length-a);if(m==="keep-local"&&i.push(l),!m.endsWith("-all"))continue;let w=s.slice(a);if(m==="keep-local-all")i.push(...w),console.log(y(` Keeping local for all ${w.length} \u2014 publishing them over the portal.`));else if(m==="took-portal-all"){let $=0;for(let T of w)try{qh({cwd:t.cwd,profileName:t.profileName},await Hh({cwd:t.cwd,profileName:t.profileName,relPath:T})),$++}catch(R){console.log(j(` \u2717 ${T}: ${R.message}`))}console.log(V(` \u2713 Took the portal copy of ${$} article${di($)} (local overwritten, sync base advanced).`))}else console.log(y(` Skipped all ${w.length} \u2014 still conflict${di(w.length)}.`));break}if(i.length>0)return console.log(y(`Publishing ${i.length} kept-local article${di(i.length)} over the portal\u2026`)),await Pt(t,i)}catch(r){console.log(j(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function Kh(e,t){let n=Ve(t.cwd,t.profileName);if(!n.ok)return console.log(j(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await s$(t),{kind:"continue"};if(o==="--baseline")return await i$(t,e.filter(i=>i!=="--baseline")),{kind:"continue"};if(o==="--compare")return await a$(t),{kind:"continue"};if(o)return console.log(j(`Unknown option: ${o}`)),console.log(y("Usage: /pull pull portal edits + import new portal articles")),console.log(y(" /pull <path> pull one article (or resolve a conflict)")),console.log(y(" /pull --status drift report only (no writes)")),console.log(y(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await l$(t,r),{kind:"continue"};console.log(y("Pulling changes from Document360\u2026"));let s=await _l({cwd:t.cwd,profileName:t.profileName});for(let i of Ml(s))console.log(i.tone==="ok"?V(i.text):i.tone==="warn"?G(i.text):y(i.text));console.log("")}catch(r){r instanceof r$?console.log(j(r.message)):console.log(j(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function _l(e){let t=await Vh({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 Yh({cwd:e.cwd,profileName:e.profileName,relPath:o.path});Ol({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 e$({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});t$({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 pi=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,On=e=>e===1?"":"s";function Ml(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${On(e.pulled.length)} into local: ${pi(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${On(e.imported.length)}: ${pi(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${On(e.toPublish)} changed locally \u2014 /push saves them to Document360.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${On(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). (${pi(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${On(e.failed.length)} failed: ${pi(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 s$(e){console.log(y("Checking Document360 for drift\u2026"));let t=Date.now(),n=await Vh({cwd:e.cwd,profileName:e.profileName});for(let o of ui(n,Date.now()-t))console.log(o);console.log("")}async function i$(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(y(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await n$({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await o$({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(V("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(V(`\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(V(`\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(y(` - ${s.path} (${s.reason})`))}}async function a$(e){console.log(y("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await Zb({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${Ge(String(t.legacyCount))} \xB7 Manifest: ${Ge(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(V("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(j(`\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(y(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function l$(e,t){let n=t.replace(/\\/g,"/"),o=await Yh({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await Ll(e,o)==="keep-local"&&(console.log(y(`Publishing ${o.path} over the portal\u2026`)),await Pt(e,[o.path]));return}console.log(""),console.log(`${z("\u25CF")} ${Ge(o.title)} ${$e(`(${o.path})`)}`);for(let i of o.notes)console.log(G(` \u26A0 ${i}`));let r=ut(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!r){console.log(y(" Local file already matches the remote content \u2014 advancing the sync base only.")),Ol({cwd:e.cwd,profileName:e.profileName},o);return}console.log($e(` \u23BF Added ${r.added} line${On(r.added)}, removed ${r.removed} line${On(r.removed)}`));for(let i of r.lines)console.log(i);if(r.hidden>0&&console.log(y(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>Jb({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(y(" Skipped."));return}Ol({cwd:e.cwd,profileName:e.profileName},o),console.log(V(` \u2713 Pulled ${o.path} (sync base advanced).`))}te();import{statSync as c$}from"node:fs";import{resolve as u$}from"node:path";import{estimateBulkCost as d$,planPartitions as p$,readProjectConfig as h$,resolveModelForOperation as f$,runPartitioned as m$,trackedArticlePaths as g$}from"document360-engine";var Fl=3;function Wl(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 Ul(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Bl(e,t){return t.map(n=>{let o=0;try{o=c$(u$(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function Hl(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:
|
|
362
362
|
- 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.
|
|
363
363
|
- 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.
|
|
364
364
|
- 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.
|
|
365
365
|
- Work only on these files:
|
|
366
366
|
`+e.paths.map(t=>`- ${t}`).join(`
|
|
367
|
-
`)}function
|
|
367
|
+
`)}function ql(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: ${tt(r)}\u2013${tt(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function Gl(e,t,n){let o=R=>t[R.index]?.paths.length??0,r=e.filter(R=>R.ok),s=e.filter(R=>!R.ok),i=e.reduce((R,C)=>R+o(C),0),a=r.reduce((R,C)=>R+o(C),0),l=e.reduce((R,C)=>R+C.costUsd,0),p=e.reduce((R,C)=>R+C.outputTokens,0),m=n==="api"?`${tt(l)} total`:ln(p),w=`${r.length}/${e.length} batch${e.length===1?"":"es"} completed`,$=R=>`${R} article${R===1?"":"s"}`,T=[];if(s.length===0)T.push(`Converted ${$(i)} (${w}) successfully \xB7 ${m}.`);else{T.push(`Converted ${a}/${$(i)} (${w}) \xB7 ${m}.`),T.push(`${s.length} batch${s.length===1?"":"es"} failed \u2014 re-run /convert to retry:`);for(let R of s)T.push(` \u2717 ${R.label}${R.error?` \u2014 ${R.error}`:""}`)}return T}async function zh(e,t){if(!h$(t.cwd))return console.log(j("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=Wl(e),r=g$(t.cwd,t.profileName);if(r.length===0)return console.log(j("No tracked articles in d360-category-map.json. Save some to Document360 first (/push), then /convert.")),{kind:"continue"};let s=Ul(r,n);if(s.length===0)return console.log(j(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let i=p$(s),a=`/convert${n?` --scope ${n}`:""} --run`,{model:l,forced:p}=f$(t.cwd,"light");if(!o){let m=d$({files:Bl(t.cwd,s),op:"convert",model:l});n&&console.log(y(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let w of ql(i,m,Fl))console.log(w);return console.log(y(`Model: ${l}${p?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(y(`Run ${a} to start.`)),console.log(""),{kind:"continue"}}console.log(y(`Converting ${s.length} articles in ${i.length} batches (\u2264${Fl} agents at once) on ${l}\u2026`)),console.log(y(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let m of m$({cwd:t.cwd,partitions:i,promptFor:Hl,concurrency:Fl,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:l}))if(m.type==="partition_status")m.status==="running"?console.log(y(` \u25B8 ${m.label} \u2014 converting\u2026`)):m.status==="done"?console.log(V(` \u2713 ${m.label}`)):console.log(j(` \u2717 ${m.label}`));else if(m.type==="run_done"){console.log("");let w=process.env.ANTHROPIC_API_KEY?"api":"subscription",$=Ct(m,"The conversion");for(let T of $??Gl(m.results,i,w))console.log($||!m.ok?G(T):V(T))}}catch(m){console.log(j(`Convert run failed: ${m.message}`))}return console.log(""),{kind:"continue"}}import{statSync as uf}from"node:fs";import{resolve as df}from"node:path";import{estimateBulkCost as M$,lintDocs as F$,planFindingPartitions as W$,planPartitions as U$,readDocsPlan as B$,readProjectConfig as pf,DEFAULT_DOCS_DIR as H$,resolveModelForOperation as af,runPartitioned as lf,partitionCoverage as q$,stampArticles as cf,CONTENT_CAP_VERSION as G$}from"document360-engine";te();import{lintDocs as tf,guidanceForRules as w$,planFindingPartitions as k$,runPartitioned as b$,partitionCoverage as $$,resolveModelForOperation as v$,stampArticles as x$}from"document360-engine";import{CONTENT_CAP_VERSION as Xh}from"document360-engine";function Qh(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 Jh(e){return e.trim().split(/\s+/).slice(1).find(t=>!t.startsWith("--"))}function Qe(e){return e==="review"?{reviewedCap:Xh}:{checkedCap:Xh}}var y$=e=>"ruleId"in e,hi=e=>y$(e)?e.severity:"warning",Po=e=>e===1?"":"s";function Vl(e,t){let n=[...new Set([...e.unreviewed,...e.styleErrors.map(s=>s.path)])],o=t??(n.length===1?n[0]:void 0),r=o?` ${o}`:"";return e.unreviewed.length>0?`/review${r} --blocked --fix`:`/lint${r} --fix`}function Pr(e){let{cwd:t,after:n,scope:o,aborted:r}=e,s=n.filter($=>hi($)==="error").length,i=n.filter($=>hi($)==="warning").length,a=n.filter($=>hi($)==="suggestion").length,l=be("/lint","--fix",o);if(r)return{text:`Stopped. Nothing else changed \u2014 ${l} picks up where this left off.`,cmd:l};if(s>0){let $=new Set(n.filter(T=>hi(T)==="error").map(T=>T.path)).size;return{text:`${s} error${Po(s)} in ${$} article${Po($)} still block${s===1?"s":""} publishing. ${l} has another go at them \u2014 if a second pass leaves the same ones, they need a human eye.`,cmd:l}}let p=i>0&&a>0?`${i} warning${Po(i)} and ${a} suggestion${Po(a)} remain (neither blocks publishing). `:i>0?`${i} warning${Po(i)} remain${i===1?"s":""}, which ${i===1?"does":"do"} not block publishing. `:a>0?`${a} suggestion${Po(a)} remain${a===1?"s":""} \u2014 ${a===1?"it is":"they are"} judgment calls and ${a===1?"does":"do"} not block publishing. `:"",m=p===""?"\u2713 Nothing left to fix. ":`\u2713 ${p}`,w=o?"/push":"/push --all";return Tt(t,{text:`${m}Nothing is blocking${o?` in ${o}`:""} \u2014 ${w} saves the articles to Document360 as drafts.`,cmd:w},m,o)}var mi={error:0,warning:1,suggestion:2},R$={error:"\u2717",warning:"\u26A0",suggestion:"\xB7"},C$=10,S$=8,P$=96,Zh=34,Mn=e=>"ruleId"in e,_n=e=>Mn(e)?e.severity:"warning",Kl=e=>Mn(e)?e.ruleId:e.kind;function Yl(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function fi(e){let t={error:0,warning:0,suggestion:0};for(let n of e)t[_n(n)]++;return t}function ef(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 Tr(e,t={}){let n=t.baselined?[]:e.filter(w=>Mn(w)&&w.baselined),o=t.baselined?e:e.filter(w=>!(Mn(w)&&w.baselined)),r=n.length>0?[we("\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[we("\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 $=s.get(w.path)??[];$.push(w),s.set(w.path,$)}let i=fi(o),a=[we("\u26A0",`${o.length} issue${o.length===1?"":"s"} in ${s.size} article${s.size===1?"":"s"} \u2014 ${ef(i)}.`),""],l=[...s.entries()].sort((w,$)=>{let T=fi(w[1]);return fi($[1]).error-T.error||$[1].length-w[1].length||w[0].localeCompare($[0])}),p=t.full?l:l.slice(0,C$);for(let[w,$]of p){a.push(` ${w} ${y(ef(fi($)))}`);let T=new Map;for(let E of $){let I=Kl(E),L=T.get(I)??[];L.push(E),T.set(I,L)}let R=[...T.entries()].sort((E,I)=>mi[_n(E[1][0])]-mi[_n(I[1][0])]||I[1].length-E[1].length||E[0].localeCompare(I[0])),C=t.full?R:R.slice(0,S$);for(let[E,I]of C){let L=[...I].sort((X,Ce)=>X.line-Ce.line),Y=R$[_n(L[0])],ue=new Set(L.map(X=>X.term)).size===1?` ${Yl(`"${L[0].term}"`,Zh)}`:"",ie=L.length>1?y(` \xD7${L.length}`):"",he=t.full?L[0].message:Yl(L[0].message,P$);a.push(` ${Y} ${E}${ie}${ue}`),a.push(` ${y(he)}`);let de=L.map(X=>ue?`L${X.line}`:`L${X.line} ${Yl(`"${X.term}"`,Zh)}`),ke=t.full?de:de.slice(0,12),ae=de.length-ke.length;a.push(` ${y(ke.join(", ")+(ae>0?` \u2026+${ae}`:""))}`)}let S=R.length-C.length;S>0&&a.push(y(` \u2026${S} more rule${S===1?"":"s"} fired here (/lint ${w} --full)`)),a.push("")}let m=l.length-p.length;return m>0&&(a.push(y(` \u2026and ${m} more article${m===1?"":"s"} (/lint <category> narrows \xB7 /lint --full lists every one)`)),a.push("")),a.push(...r),a}var T$=200;function gi(e){let n=[...e.filter(l=>!(Mn(l)&&l.baselined))].sort((l,p)=>mi[_n(l)]-mi[_n(p)]||l.path.localeCompare(p.path)||l.line-p.line),o=n.slice(0,T$),r=n.length-o.length,s=new Map;for(let l of o){let p=s.get(l.path)??[];p.push(l),s.set(l.path,p)}let i=[...s.entries()].map(([l,p])=>[l,...p.map(m=>` - L${m.line} [${Kl(m)}] (${_n(m)}): "${m.term}": ${m.message}`)].join(`
|
|
368
368
|
`)).join(`
|
|
369
|
-
`),a=
|
|
370
|
-
`)}var To=3;function
|
|
369
|
+
`),a=w$(o.map(l=>({id:Kl(l),message:l.message,link:Mn(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(`
|
|
370
|
+
`)}var To=3;function zl(e,t,n){let o=n.filter(a=>!(Mn(a)&&a.baselined));if(o.length===0)return null;let r=t.find(a=>!a.startsWith("--")),s=`/lint${r?` ${r}`:""} --fix`,i=k$(o);return i.length<=1?{kind:"single",prompt:gi(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 gi(o.filter(p=>l.has(p.path)))}}}async function A$(e,t,n){let{model:o}=v$(e.cwd,"standard");console.log(y(`Fixing ${t.findings} issue${t.findings===1?"":"s"} across ${t.articles} article${t.articles===1?"":"s"} in ${t.partitions.length} batches (\u2264${To} at once) on ${o}\u2026`));let r=[];try{for await(let a of b$({cwd:e.cwd,partitions:t.partitions,promptFor:t.promptFor,concurrency:To,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:o}))if(a.type==="partition_status")a.status==="running"?console.log(y(` \u25B8 ${a.label} \u2014 fixing\u2026`)):a.status==="done"?console.log(V(` \u2713 ${a.label}`)):console.log(j(` \u2717 ${a.label}`));else if(a.type==="run_done"){let l=$$(t.partitions,a.results);l.failed.length&&console.log(G(`\u26A0 ${l.failed.length} batch${l.failed.length===1?"":"es"} not fixed: ${l.failed.map(p=>p.label).join(", ")}`)),l.notRun.length&&console.log(G(`\u26A0 ${l.notRun.length} batch${l.notRun.length===1?"":"es"} never started \u2014 their articles are untouched.`)),a.blocked&&console.log(G(`\u26A0 ${a.blocked}`)),a.allEmpty&&console.log(G("\u26A0 No turn produced any work this run \u2014 nothing was changed.")),!a.allEmpty&&!a.blocked&&r.push(...l.covered)}}catch(a){return console.log(j(`Fix run failed: ${a.message}`)),{kind:"continue"}}if(r.length>0)try{x$(e.cwd,r,Qe("lint"))}catch{}let s=tf({cwd:e.cwd,scope:n}).filter(a=>!a.baselined);console.log("");for(let a of Tr(s))console.log(s.length===0?V(a):G(a));let i=Pr({cwd:e.cwd,after:s,before:t.findings,scope:n});return console.log(""),console.log(y(i.text)),{kind:"continue",ownNext:!0}}async function Xl(e,t){let n=e.includes("--fix"),o=e.find(i=>!i.startsWith("--")),r=o?` ${o}`:"",s=tf({cwd:t.cwd,scope:o});if(n){let i=zl(t.cwd,e,s);return i?i.kind==="partitioned"?A$(t,i,o):(console.log(y(`Fixing ${i.findings} doc issue${i.findings===1?"":"s"} (run /lint again after to confirm)\u2026`)),{kind:"forward-to-agent",prompt:i.prompt,display:`/lint${r} --fix`}):(console.log(V("\u2713 Nothing to fix \u2014 the docs are already clean.")),{kind:"continue"})}console.log(y("Linting the docs (engine internals, unknown commands, stale facts, AI-tells, em dashes, callout shape)\u2026"));for(let i of Tr(s,{full:e.includes("--full"),baselined:e.includes("--baselined")}))console.log(s.length===0?V(i):G(i));return s.length>0&&console.log(y(`Run /lint${r} --fix to have the agent correct these.`)),console.log(""),{kind:"continue",ownNext:s.length>0}}var nf=async(e,t)=>{let n=Ut("check");return n&&console.log(y(`\u2192 ${n}`)),Xl(e,t)};te();import{readProjectConfig as E$,loadProfileMap as D$,resolveActiveProfile as N$,desiredCategoryOrder as j$,desiredArticleOrder as I$,DEFAULT_DOCS_DIR as L$}from"document360-engine";var Ql=e=>e.replace(/\\/g,"/"),of=e=>Ql(e).split("/").pop()??e;function Jl(e){let t=of(e),n=t.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return n?n.charAt(0).toUpperCase()+n.slice(1):t}var O$=Jl;function Ar(e,t){try{let n=E$(e);if(!n)return[];let o=N$(e,t),r=D$(e,o.name);if(!r)return[];let s=Ql(n.docsDir??L$).replace(/\/+$/,""),i=new Map;for(let l of I$(r))i.set(l.categoryPath,(i.get(l.categoryPath)??0)+1);let a=[];for(let l of j$(r)){let p=Ql(l.path),m=p.startsWith(`${s}/`)?p.slice(s.length+1):p===s?"":p;m&&a.push({token:m,label:O$(of(p)),count:i.get(l.path)??0})}return a}catch{return[]}}function rf(e,t){let n=Ar(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 dn(e,t){if(t.includes("--all")||t.includes("--blocked")||t.some(n=>n.startsWith("--scope="))||t.includes("--scope")&&!Er(t))return!1;for(let n=0;n<t.length;n++){let o=t[n];if(o.startsWith("--")){_$.has(o)&&n++;continue}return!1}return e==="write"?!t.includes("--preview")&&!t.includes("--dry-run"):e==="review"||e==="reorder"}var _$=new Set(["--scope","--concurrency"]);function Ao(e,t,n,o,r){if(r=r??Ar(e,o),r.length<=1)return[];let s=n.filter(p=>p.startsWith("--")).join(" "),i=s?` ${s}`:"",a=`/${t}${i} --all`.replace(/\s+/g," "),l=p=>t==="write"?`/write --scope ${p}${i}`:`/${t} ${p}${i}`;return[`Bare /${t} covers the WHOLE knowledge base (${r.reduce((p,m)=>p+m.count,0)} articles). Pick a target:`,` ${a} (everything)`,...r.map(p=>` ${l(p.token)} (${p.label} \xB7 ${p.count} article${p.count===1?"":"s"})`)]}function Er(e){let t=e.indexOf("--scope");if(t===-1)return!1;let n=e[t+1];return n===void 0||n.startsWith("-")}function sf(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 V$=3,Y$=8;function Zl(e){return e===void 0||!Number.isFinite(e)?V$:Math.max(1,Math.min(Math.floor(e),Y$))}function Dr(e){let t,n,o=!1,r=!1,s,i=l=>{let p=Number(l);return l!==void 0&&Number.isFinite(p)?p:void 0};for(let l=0;l<e.length;l++){let p=e[l];if(p==="--preview"||p==="--dry-run")o=!0;else if(p==="--rewrite"||p==="--force")r=!0;else{if(p==="--run"||p==="--yes"||p==="--all")continue;p==="--scope"?t=e[++l]:p?.startsWith("--scope=")?t=p.slice(8):p==="--concurrency"?s=i(e[++l]):p?.startsWith("--concurrency=")?s=i(p.slice(14)):p&&!p.startsWith("--")&&(n=p)}}let a=l=>l?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:a(t),path:a(n),preview:o,concurrency:s,rewrite:r}}function K$(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function z$(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function ec(e,t,n){return n.filter(o=>{try{return uf(df(e,t,o)).size===0}catch{return!0}})}function tc(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+=uf(df(e,i)).size}catch{}return{path:r,bytes:s}})}function nc(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.
|
|
371
371
|
`:"";return`Run the write-article skill to author EACH documentation article listed below. For each path:
|
|
372
372
|
- It is relative to ${t}/. Look up its entry (matching "path") in .d360-writer/plan.json for its purpose, its \`type\` (concept | task | reference | faq | tutorial | troubleshooting | best-practices | use-case; missing \u21D2 task), and the source files it draws from (AGENT-PLAN.md has the same table).
|
|
373
373
|
- Use the skeleton for that \`type\` (see write-article): a \`concept\`/overview page opens with what the product IS + its mental model and takes NO Prerequisites/Steps; only a \`task\` or \`tutorial\` page gets numbered steps (a tutorial ends every stage with a visible checkpoint); a \`troubleshooting\` page is symptom \u2192 cause \u2192 fix. Titles follow the type grammar (task: "How to <verb> <object>"; concept: "Understanding <X>"; troubleshooting: the symptom the user sees).
|
|
@@ -377,143 +377,143 @@ ${a[1]??" "}clipTo: ${l}${i.selector}${l},`);return p=p.replace(o,`${r}await ca
|
|
|
377
377
|
- 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.
|
|
378
378
|
Articles:
|
|
379
379
|
`+e.paths.map(r=>`- ${r}`).join(`
|
|
380
|
-
`)}function
|
|
381
|
-
`)}var
|
|
382
|
-
`)}var
|
|
380
|
+
`)}function oc(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: ${tt(r)}\u2013${tt(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function rc(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,S)=>C+r(S),0),l=s.reduce((C,S)=>C+r(S),0),p=e.reduce((C,S)=>C+S.costUsd,0),m=e.reduce((C,S)=>C+S.outputTokens,0),w=n==="api"?`${tt(p)} total`:ln(m),$=`${s.length}/${e.length} batch${e.length===1?"":"es"} completed`,T=C=>`${C} article${C===1?"":"s"}`,R=[];if(i.length===0){R.push(`Wrote ${T(a)} (${$}) successfully \xB7 ${w}.`);let C=o?` ${o}`:"",S=o?"/push":"/push --all",E=o?`/screenshot author ${o}`:"/screenshot author --all";R.push("Next \u2014 an editorial review, because these were written by an AI:"),R.push(`/review${C} --fix`),R.push(`It reads every article and applies its fixes; ${S} then pushes them up (add screenshots first with ${E} if you want them).`)}else{R.push(`Wrote ${l}/${T(a)} (${$}) \xB7 ${w}.`),R.push(`${i.length} batch${i.length===1?"":"es"} failed \u2014 re-run /write${o?` --scope ${o}`:""} to retry the rest:`);for(let C of i)R.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return R}function Nr(e,t,n){try{return F$({cwd:e,paths:n.map(o=>`${t}/${o}`)}).filter(o=>!o.baselined)}catch{return[]}}function sc(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 ic(e){let t=e.filter(o=>o.severity==="error");if(t.length===0)return null;let n=W$(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 gi(t.filter(s=>r.has(s.path)))}}}function ac(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 --fix retries them. Exactly one automatic pass runs, so a loop can never spin here."]}function yi(e,t,n){let o=(pf(e)?.docsDir??H$).replace(/\/+$/,""),r=t.map(a=>a.path);if(n.path){let a=K$(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=z$(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=ec(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 lc(e,t,n){let{targets:o}=yi(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:Jl(s),count:i}))}async function hf(e,t){if(!pf(t.cwd))return console.log(j("No d360-writer config here. Run /init first.")),{kind:"continue"};if(Er(e)){for(let E of rf(t.cwd,t.profileName))console.log(y(E));return{kind:"continue"}}let n=B$(t.cwd);if(n.length===0)return console.log(j("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};if(dn("write",e)){let E=lc(t.cwd,n,{rewrite:Dr(e).rewrite}),I=Ao(t.cwd,"write",e,t.profileName,E);if(I.length>0){for(let L of I)console.log(y(L));return{kind:"continue"}}}let{scope:o,path:r,preview:s,concurrency:i,rewrite:a}=Dr(e),{docsDir:l,targets:p,reason:m,rewriting:w}=yi(t.cwd,n,{scope:o,path:r,rewrite:a});if(p.length===0)return console.log(m?G(m):G("Nothing to write.")),{kind:"continue"};w&&console.log(G(`--rewrite: regenerating ${p.length} already-written article${p.length===1?"":"s"} (overwrites them; git has your baseline).`));let $=U$(p),T=Zl(i),{model:R,forced:C}=af(t.cwd,"standard"),S=!!r;if(s&&!S){let E=M$({files:tc(t.cwd,n,p),op:"write",model:R});o&&console.log(y(`Scope: ${o} (${p.length} pending).`));for(let I of oc($,E,T))console.log(I);return console.log(y(`Model: ${R}${C?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(y(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}console.log(y(`Writing ${p.length} article${p.length===1?"":"s"} in ${$.length} batch${$.length===1?"":"es"} (\u2264${T} agents at once) on ${R}\u2026`)),console.log(y(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let E of lf({cwd:t.cwd,partitions:$,promptFor:I=>nc(I,l,{rewrite:w||S}),concurrency:T,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:R}))if(E.type==="partition_status")E.status==="running"?console.log(y(` \u25B8 ${E.label} \u2014 writing\u2026`)):E.status==="done"?console.log(V(` \u2713 ${E.label}`)):console.log(j(` \u2717 ${E.label}`));else if(E.type==="run_done"){console.log("");let I=process.env.ANTHROPIC_API_KEY?"api":"subscription",L=Ct(E,"The write");if(L){for(let ie of L)console.log(G(ie));continue}for(let ie of rc(E.results,$,I,o??r))console.log(E.ok?V(ie):G(ie));if(E.ok)try{cf(t.cwd,p.map(ie=>`${l}/${ie}`),{writtenCap:G$,reviewedCap:0,checkedCap:0})}catch{}let Y=Nr(t.cwd,l,p),ce=sc(Y);ce&&console.log(G(ce));let ue=e.includes("--skip-style")?null:ic(Y);if(ue){console.log(y(`Fixing ${ue.errors.length} style error(s) in ${ue.articles} article(s) \u2014 one pass\u2026`));let{model:ie}=af(t.cwd,"standard"),he=[];try{for await(let de of lf({cwd:t.cwd,partitions:ue.partitions,promptFor:ue.promptFor,concurrency:3,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:ie}))if(de.type==="partition_status"&&de.status!=="running")console.log(de.status==="done"?V(` \u2713 ${de.label}`):j(` \u2717 ${de.label}`));else if(de.type==="run_done"&&!de.allEmpty&&!de.blocked){let ke=q$(ue.partitions,de.results);ke.notRun.length&&console.log(G(`\u26A0 ${ke.notRun.length} style-fix batch${ke.notRun.length===1?"":"es"} never started \u2014 their articles are untouched.`)),he.push(...ke.covered)}}catch(de){console.log(G(`Style fix pass failed: ${de.message}`))}if(he.length>0)try{cf(t.cwd,he,Qe("lint"))}catch{}for(let de of ac(ue.errors.length,Nr(t.cwd,l,p)))console.log(de.startsWith("\u2713")?V(de):G(de))}}}catch(E){console.log(j(`Write run failed: ${E.message}`))}return console.log(""),{kind:"continue"}}te();import{existsSync as X$,readdirSync as ff,statSync as mf}from"node:fs";import{join as gf}from"node:path";import{inputDir as Q$,readProjectConfig as J$}from"document360-engine";var yf=/\.(md|markdown|pdf|txt)$/i;function cc(e){let t=Q$(e);if(!X$(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of ff(t)){let s=gf(t,r),i=!1;try{i=mf(s).isDirectory()}catch{continue}if(i){if(r.startsWith("."))continue;let a=Z$(s);a>0&&n.push({name:r,docCount:a})}else yf.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function Z$(e){let t=0;for(let n of ff(e))try{mf(gf(e,n)).isFile()&&yf.test(n)&&t++}catch{}return t}function uc(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 wi(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(`
|
|
381
|
+
`)}var dc="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function wf(e,t){let n=t?.cwd??process.cwd();if(!J$(n))return console.log(j("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=cc(n);if(o.length===0&&r===0)return console.log(y(dc)),{kind:"continue"};let s=e.join(" ").trim();if(!s){if(o.length>1){console.log(y("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let l of o)console.log(` ${l.name} ${y(`(${l.docCount} doc${l.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let a=o[0]?.name??"";return{kind:"forward-to-agent",prompt:wi(a),display:a?`/draft ${a}`:"/draft"}}let i=uc(o,s);return{kind:"forward-to-agent",prompt:wi(i??"",i?void 0:s),display:`/draft ${s}`}}te();import{listOpenForDocs as ev,readProjectConfig as tv}from"document360-engine";function pc(e){try{return ev(e).filter(t=>t.kind==="request").length}catch{return 0}}function hc(e){let t=e.includes("--push")||e.includes("--publish"),n=e.includes(ct),o=e.filter(r=>!r.startsWith("--")).join(" ").trim();return{push:t,skipReview:n,what:o}}function fc(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(`
|
|
382
|
+
`)}var mc="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 kf(e,t){let n=t?.cwd??process.cwd();if(!tv(n))return console.log(j("No d360-writer config here. Run /init first.")),{kind:"continue"};let{push:o,what:r}=hc(e);if(!r&&pc(n)===0)return console.log(y(mc)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --push":""}`;return{kind:"forward-to-agent",prompt:fc(r),display:s}}te();import{search as nv}from"@inquirer/prompts";import{findByName as ov,getSession as rv,listSessions as sv,relativeTime as $f}from"document360-engine";async function vf(e,t){let n=sv(t.cwd).filter(o=>o.uuid!==t.currentUuid());if(n.length===0)return console.log(y("No saved sessions for this repo yet \u2014 sessions auto-save as you work.")),{kind:"continue"};if(e.length>0){let o=e.join(" "),r=ov(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(j(`No session matches "${o}".`)),bf(n),{kind:"continue"})}if(!process.stdin.isTTY)return bf(n),console.log(y("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>nv({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} ${$f(a.updatedAt)}`,value:a.uuid,description:a.firstPrompt.slice(0,100)}))}})),r=rv(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function bf(e){console.log("");for(let t of e.slice(0,15))console.log(` ${z(t.name)} ${y($f(t.updatedAt))}`),console.log(` ${y(t.firstPrompt.slice(0,80))}`);console.log("")}te();import{renameSession as iv}from"document360-engine";function gc(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 xf(e,t){let n=gc(e.join(" "));if(!n)return console.log(j("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(iv(o,n)?console.log(V(`\u2713 Session renamed to "${n}"`)):console.log(j("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(V(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as Rf,readProjectConfig as av,writeProjectConfig as lv}from"document360-engine";te();function yc(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=av(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 Rf().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},lv(o,e),null):`Unknown environment "${r}". Known: ${Rf().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function Cf(e,t){let n=e[0];if(!n)return Ts(t.cwd),{kind:"continue"};if(n==="add"){let o=yc(t.cwd,e[1],e[2]);return o?(console.log(j(o)),{kind:"continue"}):(console.log(V(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${z(`/profile ${e[1]}`)} then ${z("/login")}`),console.log(y(" Until you switch, this repo keeps using the current profile\u2019s environment.")),{kind:"continue"})}return As(t.cwd,n),Es(t.cwd,n),console.log(y(" Restarting agent for the new profile\u2026")),{kind:"clear"}}te();import{select as cv}from"@inquirer/prompts";import{readProjectConfig as uv,readUserConfig as Sf,resolveModelSetting as wc,writeUserConfig as Pf}from"document360-engine";var At=[{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 ki(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=At.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function dv(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 jr(e,t){let n=()=>wc(e).model;if(t==="default"){let s=Sf();return s.defaultModel?(delete s.defaultModel,Pf(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${wc(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}}Pf({...Sf(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=uv(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 Tf(e,t){let n=e[0]?.trim();if(!n){let i=wc(t.cwd);if(!process.stdin.isTTY)return console.log(`${Ge("Model:")} ${z(i.model)}${i.source==="auto"?y(" (auto)"):""}`),console.log(y(` source: ${dv(i)}`)),console.log(y(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let a=ki(i),l;try{l=await t.withPausedInput(()=>cv({message:`Select model (current: ${i.model}${i.source==="auto"?" \xB7 auto":""})`,default:At[a].value,choices:At.map(($,T)=>({name:`${$.label}${T===a?" \u2714":""}`,value:$.value,description:$.desc}))}))}catch{return console.log(y("Cancelled.")),{kind:"continue"}}let{lines:p,changed:m,effective:w}=jr(t.cwd,l??"default");for(let $ of p)console.log($.startsWith("\u26A0")?G($):$.startsWith("\u2713")?V($):y($));return m&&await t.setModel(w),{kind:"continue"}}let{lines:o,changed:r,effective:s}=jr(t.cwd,n);for(let i of o)console.log(i.startsWith("\u26A0")?G(i):i.startsWith("\u2713")?V(i):y(i));return r&&await t.setModel(s),{kind:"continue"}}bi();async function If(e,t){return await t.withPausedInput(()=>po(t.cwd)),{kind:"clear"}}async function Lf(e,t){return await t.withPausedInput(()=>Rs(t.cwd,t.profileName)),{kind:"clear"}}te();import{resolveActiveProfile as Ev}from"document360-engine";async function Of(e,t){let n=!1;try{n=Ev(t.cwd).production}catch{}return n?(console.log(G("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(y("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}te();var _f=async(e,t)=>{try{await t.withPausedInput(()=>Ps({}))}catch(n){console.log(j(`Login failed: ${n.message}`))}return{kind:"continue"}};import{resolveActiveProfile as Dv,clearTokens as Nv,clearProfileProject as jv}from"document360-engine";te();async function Mf(e,t){let n,o;try{let i=Dv(t.cwd,t.profileName);n=i.name,o=i.connection.name}catch(i){return console.log(j(i.message)),{kind:"continue"}}let r=Nv(n);jv(t.cwd,n),console.log(r?V(`\u2713 Signed out of "${n}" and cleared its project/workspace selection.`):y(`Profile "${n}" was not signed in. Cleared any project/workspace selection.`)),console.log(y(`Run /login to sign back in to "${n}" (the ${o} environment) and pick a project.`));let s=nn(t.cwd,t.profileName);return console.log(s?G(`\u26A0 ${s.why}. Signing out doesn\u2019t change the environment \u2014 ${s.cmd} does.`):y(" Different environment? That comes from the profile, not the login \u2014 /profile add <environment>.")),{kind:"continue"}}import{spawn as Wf}from"node:child_process";import{existsSync as Uf,readFileSync as bc}from"node:fs";import{homedir as Uv}from"node:os";import{basename as Bv,join as Or}from"node:path";import{readProjectConfig as Hv,DEFAULT_OUTPUT_DIR as qv,existingAnnotatedShotPath as f1,resolveOutputDir as Gv,shotArtifacts as Vv}from"document360-engine";import ot from"picocolors";import{annotationsPath as Iv,resolveOutputDir as Lv,readProjectConfig as Ov,DEFAULT_OUTPUT_DIR as _v,existingAnnotatedShotPath as Mv}from"document360-engine";function Fv(e){let n=e.filter(o=>o!=="--all"&&o!=="-a").find(o=>!o.startsWith("-"));return n?{mode:"single",id:n}:{mode:"all"}}function Lr(e){return e.filter(t=>t.state==="annotated").map(t=>t.id)}function Et(e,t){let n=Lv(e,Ov(e)?.outputDir??_v),o=new Map(Le(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(Mv(n,i))}`,` facts: ${r(Iv(n,i))}`,` article: ${a}`].join(`
|
|
383
383
|
`)}).join(`
|
|
384
384
|
`);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(`
|
|
385
|
-
`)}function pn(e){return`${
|
|
386
|
-
`)}function
|
|
387
|
-
`):
|
|
388
|
-
`)}var
|
|
389
|
-
`)}function
|
|
390
|
-
/screenshot list --detail shows what each one needs`}function
|
|
391
|
-
`),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
|
|
392
|
-
Check them when you're ready: ${
|
|
393
|
-
`),display:"/screenshot checklist"}}var
|
|
394
|
-
`)}async function
|
|
395
|
-
`).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 Ci(e,t){let n=rm(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=hx(e);if(!o)return[{tone:"info",text:"Sharing: unavailable \u2014 this folder is not a git repository."}];if(!o.upstream)return[{tone:"warn",text:se("\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:se("\u26A0")+`${o.ahead} change${Fr(o.ahead)} not shared yet \u2014 run /share`}):s.push({tone:"ok",text:se("\u2713")+"Everything is shared with your team."}),s}function Mc(e,t,n){om({...t,gitHandoff:{commit:n,push:n}},e);let o=n?{tone:"ok",text:se("\u2713")+"Sharing on \u2014 d360-writer will save and send its own work from now on."}:{tone:"ok",text:se("\u2713")+"Sharing off \u2014 d360-writer will leave its work for your coding agent to commit."};return n?[o,...Ci(e,{...t,gitHandoff:{commit:!0,push:!0}})]:[o]}async function Ri(e,t){let n=[],o=rm(t);if(!o.commit)return{lines:[{tone:"info",text:hn("disabled")}],changed:!1};let r=t;o.push==="unconfirmed"&&fx(e,t)&&(r={...t,gitHandoff:{commit:!0,push:!0}},om(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 px(e);if(s.ok&&s.pulled>0){let p=[s.newHints>0?`${s.newHints} new hint${Fr(s.newHints)}`:null,s.newMessages>0?`${s.newMessages} new message${Fr(s.newMessages)}`:null].filter(Boolean);n.push({tone:"ok",text:se("\u2B07")+`Got your builder's latest${p.length?` \u2014 ${p.join(", ")}`:""}.`})}else!s.ok&&s.reason!=="no-upstream"&&s.reason!=="no-git"&&n.push({tone:"warn",text:se("\u26A0")+hn(s.reason,s.detail)});let i=await dx(e,r);if(i.commit&&!i.commit.ok)return n.push({tone:"warn",text:se("\u26A0")+hn(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:se("\u2713")+`Saved ${a} change${Fr(a)} to the docs folder.`}),i.push&&!i.push.ok)return n.push({tone:"warn",text:se("\u26A0")+hn(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:se("\u2B06")+`Shared ${l} change set${Fr(l)} with your team.`}):a===0&&(s.ok&&s.pulled===0)?n.push({tone:"ok",text:se("\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 mx={ok:V,info:be,warn:q,error:j};async function sm(e,t){let n=t.cwd,o=ux(n);if(!o)return console.log(j("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(mx[l.tone](l.text))};if(r==="status")return s(Ci(n,o)),{kind:"continue"};if(r==="on"||r==="off")return s(Mc(n,o,r==="on")),{kind:"continue"};if(r)return console.log(j(`Unknown option "${r}". Use /share, /share status, /share on, or /share off.`)),{kind:"continue"};console.log(y("Exchanging work with your team\u2026"));let{lines:i}=await Ri(n,o);return s(i),{kind:"continue"}}function Wn(e){let t=0,n=0,o=0,r=0;try{t=gx(e).length}catch{}try{let s=yx(e);n=s.filter(i=>i.kind==="request").length,o=s.filter(i=>i.kind==="answer").length}catch{}try{r=wx(e).length}catch{}return{hints:t,requests:n,answers:o,directives:r}}async function Wc(e){let t=im(e);if(!t)return[];if(!Rx(e,t))return[];let n=await Cx(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 ${hn(n.reason,n.detail)}`}]}function Wr(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 Uc(e){return{push:e.includes("--push")||e.includes("--publish"),skipReview:e.includes(ct)}}function Bc(e){let t={hold:!1,openQuestions:0,answersPending:0};try{let n=Sx(e);return!n||n.status==="confident"?t:{hold:!0,...Px(e)}}catch{return t}}function Hc(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:`${se("\u2139")}Product discovery is still open \u2014 ${n} answer${jo(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:`${se("\u26A0")}Product discovery isn't finished \u2014 ${n} question${jo(n)} still with your builder.`},{tone:"warn",text:` ${t} until the brief is settled.`}]}return[{tone:"warn",text:`${se("\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 qc(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${jo(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(`
|
|
396
|
-
`)}var
|
|
397
|
-
(Document360 sends the first 500 characters of a highlight)`:`\u201C${n}\u201D`;let o=n.slice(0,
|
|
398
|
-
(+${r} more character${r===1?"":"s"}${e.comment.commented_text_truncated?", and Document360 caps a highlight at 500":""})`}function
|
|
399
|
-
`)]});return o.push(
|
|
400
|
-
`)}function
|
|
401
|
-
`).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function
|
|
402
|
-
|
|
403
|
-
`;
|
|
404
|
-
`,"utf8");let C=qr(e)??{projectId:""};return Sm({...C,styleGuide:{...C.styleGuide,pulledFrom:{styleGuideId:a.id,name:a.name??a.id,pulledAt:new Date().toISOString(),contentHash:T0("sha1").update($).digest("hex").slice(0,16)}}},e),{lines:[we("\u2713",`Pulled "${a.name??a.id}" into .d360-writer/style-guide.md (${$.length.toLocaleString()} characters).`),...w,y(" This is PROSE, not rules \u2014 /review judges against it, and the writer now writes to it."),y(" Turn its mechanical parts into checks: /style-guide compile"),y(" Restarting the agent so it writes to the new guide\u2026")],restart:!0}}function D0(e){let t=su(e).rules.filter(n=>n.pack.toLowerCase()===Hr.toLowerCase()).map(n=>n.id);return{prompt:k0({guide:b0(e),packName:Hr,existingRuleIds:t}),display:"/style-guide compile"}}function Tm(){return[y(` Review what it wrote: git diff .d360-writer/styles/${Hr}/`),y(` Anything it could not check mechanically is listed in .d360-writer/styles/${Hr}/UNCHECKABLE.md \u2014 /review judges those.`),y(` Turn them on when you are happy: /style-guide use ${Hr.toLowerCase()} (they start as warnings, never blocking)`)]}var dt=(e,t)=>`${e} ${t}${e===1?"":"s"}`,ou=e=>/^v\d/i.test(e)?e:`v${e}`;function Am(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 N0(e){let n=qr(e)?.styleGuide?.pulledFrom;return n?`.d360-writer/style-guide.md \u2014 pulled ${n.pulledAt.slice(0,10)} from "${n.name}"`:Pm(Rm(e))?".d360-writer/style-guide.md (yours)":"the built-in default"}function j0(e){let t=qr(e),n=su(e),o=(t?.styleGuide?.packs??[]).filter(Boolean),r=n.packs.filter(l=>l.name.toLowerCase()===Lo),s=n.packs.filter(l=>l.name.toLowerCase()!==Lo),i=[`Style guide: ${N0(e)}`,`Rule packs: ${s.length>0?s.map(l=>`${l.name.toLowerCase()} ${ou(l.version)}`).join(", "):y("none chosen")}`,`Always on: ${y(`d360 (correctness, built in \u2014 ${dt(Di.length,"rule")})`)}`];for(let l of r)i.push(` ${y(`${l.name.toLowerCase()} ${ou(l.version)} (anti-slop \u2014 ${dt(l.ruleCount,"rule")})`)}`);r.length>0&&(i.push(y(" Every article here is machine-written, so these cannot be switched off by")),i.push(y(" choosing another pack. styleGuide.humanise: false turns them off deliberately.")));let a=[...Di.map(l=>({severity:l.severity})),...n.rules.map(l=>({severity:l.severity}))];i.push("",`${dt(a.length,"rule")} active \xB7 ${Am(a)}`);try{let l=iu({cwd:e}),p=l.findings.filter(w=>!w.baselined),m=p.filter(w=>w.severity==="error").length;i.push(""),i.push(m===0?we("\u2713",`No style errors across the docs${p.length>0?`, though ${dt(p.length,"other issue")} ${p.length===1?"is":"are"} reported`:""}.`):we("\u2717",`${dt(m,"style error")} \u2014 /lint shows them, /lint --fix corrects them.`)),l.baselinedCount>0&&i.push(we("\u2139",`${dt(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(we("\u26A0",`${dt(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(y(" See them all: /style-guide list \xB7 change: /style-guide use <preset> \xB7 one rule: /style-guide explain <rule>")),i}function ru(e){let t=qr(e),n=new Set(g0(t?.styleGuide)),o=Cm(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),p=a===Lo,m=l?"\u2713":"\xB7",w=p?y("(always on)"):l?y("(active)"):"",$=i.local?y(" [yours]"):"";r.push(` ${m} ${a.padEnd(s)}${$} ${i.description??""}`),r.push(` ${y(`${dt(i.rules.length,"rule")} \xB7 ${Am(i.rules)} \xB7 ${ou(i.version)}`)} ${w}`),i.errors.length>0&&r.push(we("\u26A0",`${dt(i.errors.length,"rule")} in this pack could not be loaded \u2014 /style-guide explain names them.`))}return o.every(i=>i.name.toLowerCase()===Lo)&&(r.push(""),r.push(y(" The Microsoft and Google style guides are not installed in this build yet."))),r.push(""),r.push(y(" Turn one on: /style-guide use <name> (this replaces the chosen set, it does not add to it)")),r.push(y(" Several: /style-guide use microsoft,google")),r.push(y(" Back to none: /style-guide use none")),r}function I0(e,t){if(!t)return[we("\u26A0","Name a rule: /style-guide explain Humanise.EmDash")];let n=su(e),o=Di.find(p=>p.id.toLowerCase()===t.toLowerCase()),r=n.rules.find(p=>p.id.toLowerCase()===t.toLowerCase());if(!o&&!r){let p=[...Di.map(m=>m.id),...n.rules.map(m=>m.id)].filter(m=>m.toLowerCase().includes(t.toLowerCase())).slice(0,5);return[we("\u26A0",`No active rule called "${t}".`),...p.length>0?[y(` Did you mean: ${p.join(", ")}`)]:[y(" /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(y(` ${r.link}`)),r?.degraded&&(l.push(""),l.push(we("\u26A0",`This rule is translated approximately: ${r.degraded}. It may match slightly more than the original does.`)));try{let p=iu({cwd:e}).findings.filter(w=>w.ruleId===s),m=p.filter(w=>!w.baselined);l.push(""),l.push(p.length===0?" Currently: no findings.":` Currently: ${dt(m.length,"finding")}${p.length!==m.length?`, plus ${p.length-m.length} baselined and hidden`:""}.`)}catch{}return l.push(""),o?(l.push(y(" Built-in checks are grounded in your product's own source and cannot be switched off \u2014 they")),l.push(y(" catch defects of fact, not matters of taste."))):(l.push(y(` Silence it everywhere: add "${s}": "off" to styleGuide.rules in .d360-writer/config.json`)),i!=="error"&&l.push(y(" Silence one passage: <!-- vale "+s+" = NO --> \u2026 <!-- vale "+s+" = YES -->"))),l}function L0(e,t){let n=(t??"").trim();if(!n)return{lines:[we("\u26A0","Name the packs to use: /style-guide use microsoft (or `none`)"),...ru(e)],restart:!1};let o=n.toLowerCase()==="none"?[]:n.split(/[,\s]+/).map(l=>l.trim().toLowerCase()).filter(Boolean),r=new Map(Cm(e).map(l=>[l.name.toLowerCase(),l])),s=o.filter(l=>!r.has(l));if(s.length>0)return{lines:[we("\u2717",`No rule pack named ${s.map(l=>`"${l}"`).join(", ")}.`),"",...ru(e)],restart:!1};let i=qr(e)??{projectId:""};Sm({...i,styleGuide:{...i.styleGuide,packs:o}},e),f0();let a=[we("\u2192",`Switching to: ${o.length>0?o.join(", "):"the built-in checks only"}${o.includes(Lo)?"":` (+ ${Lo}, always on)`}\u2026`)];try{let l=iu({cwd:e}),p=new Set(l.findings.map(m=>m.path)).size;if(l.findings.length===0)a.push(we("\u2713",p===0?"No articles yet \u2014 everything you write from here is held to the full set.":"Nothing to record: your articles are already clean against these rules."));else{let m=m0(e),w=h0(l.findings,w0(e));y0(e,w),a.push(we("\u2713",`Recorded ${dt(l.findings.length,"existing issue")} across ${dt(p,"article")} as accepted.`),y(" .d360-writer/style-baseline.json \u2014 commit it. It defines what the publish gate lets through, and a"),y(" teammate with a different copy gets a different answer from the same gate."),we("\u2713","Nothing is blocked today. New writing, and any paragraph you edit, is held to the full set.")),m&&a.push(y(` (Replaced the baseline recorded ${m.createdAt.slice(0,10)}.)`))}}catch(l){a.push(we("\u26A0",`The packs are active, but recording what was already there failed: ${l instanceof Error?l.message:String(l)}`)),a.push(y(" Run /lint to see the current state before publishing."))}return a.push(y(" Restarting the agent so it writes to the new rules\u2026")),{lines:a,restart:!0}}async function Ni(e,t){let{sub:n,value:o}=A0(e),r=s=>{for(let i of s)console.log(i);console.log("")};switch(n){case"list":return r(ru(t.cwd)),{kind:"continue"};case"explain":return r(I0(t.cwd,o)),{kind:"continue"};case"use":{let s=L0(t.cwd,o);return r(s.lines),s.restart?{kind:"clear"}:{kind:"continue"}}case"pull":{let s=await E0(t.cwd,o,t.profileName);return r(s.lines),s.restart?{kind:"clear"}:{kind:"continue"}}case"compile":{let s=D0(t.cwd);return{kind:"forward-to-agent",prompt:s.prompt,display:s.display}}default:return r(j0(t.cwd)),{kind:"continue"}}}ne();import{lintDocs as au,loadStyleGuide as jm,buildReviewPrompt as Im,readProjectConfig as Lm,DEFAULT_DOCS_DIR as Om,listArticleFiles as _m,planPartitions as U0,runPartitioned as B0,resolveModelForOperation as H0,stampArticles as q0}from"document360-engine";ne();import{readProjectConfig as O0,loadProfileMap as _0,resolveActiveProfile as M0,desiredCategoryOrder as F0,desiredArticleOrder as W0}from"document360-engine";function Em(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}var Dm=e=>e.replace(/\\/g,"/").split("/").pop()??e;function Gr(e,t){try{if(!O0(e))return[];let n=M0(e,t),o=_0(e,n.name);if(!o)return[];let r=new Map;for(let i of W0(o)){let a=r.get(i.categoryPath);a?a.push(i):r.set(i.categoryPath,[i])}let s=[];for(let i of F0(o)){s.push(Em(Dm(i.path)));for(let a of(r.get(i.path)??[]).sort((l,p)=>l.order-p.order))s.push(` ${Em(Dm(a.path))}`)}return s}catch{return[]}}async function Nm(e,t){let n=Gr(t.cwd,t.profileName);if(n.length===0)return console.log(y("No documentation structure yet \u2014 run /init and author some articles first.")),{kind:"continue"};console.log(z("Documentation order (categories \u2192 articles):"));for(let o of n)console.log(o);return console.log(""),{kind:"continue"}}function Yr(e,t){return Rr(e,_m(e,t))}function G0(e,t,n){return t.includes("--blocked")?Yr(e,n):_m(e,n)}function V0(e,t){let n=Lm(e);if(!n)return null;let o=(n.docsDir??Om).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),s=t.includes("--blocked"),i=t.find(T=>!T.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),a=au({cwd:e}),l=i?a.filter(T=>T.path===`${o}/${i}`||T.path.startsWith(`${o}/${i}/`)):a,p=s?Yr(e,i):void 0,m=p?l.filter(T=>p.includes(T.path)):l,w=i||s?"":Gr(e).join(`
|
|
405
|
-
`);return{prompt:
|
|
406
|
-
`),display:`/reorder${n?` ${n}`:""}`}}async function
|
|
385
|
+
`)}function pn(e){return`${re("\u2192",ot.blue)}Verifying ${e} new screenshot${e===1?"":"s"} (reading each image)\u2026`}var Wv=(e,t=88)=>{let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n};function Eo(e,t){if(t.length===0)return[];let n=Wt(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(`${re("\u2714",ot.green)}${ot.green(`${o.length} verified`)}`+(r.length>0?` ${ot.magenta(`\u2691 ${r.length} flagged`)}`:"")+(s.length>0?` ${ot.yellow(`? ${s.length} not verified`)}`:"")+ot.gray(` ${t.length} shot${t.length===1?"":"s"} in this pass`)),r.length>0){let a=Math.max(...r.map(p=>p.id.length));for(let p of r)i.push(` ${ot.magenta(p.id.padEnd(a))} ${ot.gray(Wv(p.reason))}`);let l=r.filter(p=>p.repaired).length;i.push(`${re("\u2192",ot.magenta)}Re-capture the ${r.length} flagged: ${ot.bold("/screenshot capture --failed")}`+(l<r.length?ot.gray(` (${r.length-l} still need${r.length-l===1?"s":""} a spec fix first)`):""))}return s.length>0&&i.push(`${re("\u26A0",ot.yellow)}No verdict recorded for ${s.slice(0,3).join(", ")}${s.length>3?`, +${s.length-3}`:""} \u2014 still awaiting verification. Run ${ot.bold("/screenshot verify")} again.`),i}async function Ff(e,t){let n=t?.cwd??process.cwd(),o=Nn(n);o&&console.log(o);let r=Le(n),s=Fv(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:Et(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=Lr(r);if(i.length===0){let a=r.filter(m=>m.state==="verified").length,l=r.filter(m=>m.state==="rejected").length,p=r.filter(m=>m.state==="captured").length;return console.log(p>0?`${p} shot${p===1?" is":"s are"} taken but not drawn on yet \u2014 /screenshot annotate finishes ${p===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:Et(n,i),display:"/screenshot verify"}}var Yv=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function $c(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:Yv(t),retryBlocked:n}:{mode:"single",id:t}:{mode:"picker"}}function Mr(e,t){let n=Le(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 Bf(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}),xo(o,t,"capture"),gl(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 vc(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([...Bp(e).filter(r=>n.has(r)),...o])].sort()}function xc(e,t){let n=e.length;if(n===0)return null;let o=vr(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(`
|
|
386
|
+
`)}function Kv(e,t){let n=Hv(e)?.outputDir??qv;return Vv(Gv(e,n),t)}function Rc(e,t,n,o){let r=Kv(e,t);return(r.annotationsMtimeMs??0)>=o&&r.rawMtimeMs!==void 0?"captured":n===0?"skipped":"failed"}function Hf(e){let t=/⊘[^\n—]*—\s*(.+)/.exec(e);return t?t[1].trim():null}var zv=/element is not (?:enabled|visible|stable|editable)|intercepts pointer events|outside of the viewport|element is not attached/i;function qf(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=>zv.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(`
|
|
387
|
+
`):Cc(e)}function Cc(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(`
|
|
388
|
+
`)}var Xv=/^[A-Za-z0-9._-]+$/;function Sc(e){return new Promise((t,n)=>{if(!Xv.test(e.id)){n(new Error(`Not a valid spec id: "${e.id}"`));return}let o=Wf(`d360-capture capture ${e.id}`,{cwd:e.cwd,shell:!0,stdio:e.stdio==="inherit"?"inherit":["ignore","pipe","pipe"],env:{...process.env,NO_UPDATE_NOTIFIER:"1"}}),r="";e.stdio==="pipe"&&(o.stdout?.on("data",i=>{r+=i.toString()}),o.stderr?.on("data",i=>{r+=i.toString()}));let s=()=>{o.kill()};e.signal?.addEventListener("abort",s,{once:!0}),o.on("error",i=>{e.signal?.removeEventListener("abort",s),n(i)}),o.on("close",i=>{e.signal?.removeEventListener("abort",s),t({exitCode:i??1,output:r})})})}function Gf(e,t=Uv()){try{let n=JSON.parse(bc(Or(e,".d360-writer","capture.json"),"utf8").replace(/^/,"")),o=n.projectId;if(!o)try{o=JSON.parse(bc(Or(e,"package.json"),"utf8")).name}catch{}o||=Bv(e);let r=Object.keys(n.profiles??{}),s=n.defaultProfile??(r.length===1?r[0]:r.includes("staging")?"staging":r[0]);return s?Uf(Or(t,".document360-capture","auth-states",o,`${s}.json`)):!0}catch{return!0}}function Vf(e){return new Promise((t,n)=>{let o=Wf("d360-capture auth --auto",{cwd:e.cwd,shell:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,NO_UPDATE_NOTIFIER:"1"}}),r="";o.stdout?.on("data",i=>{r+=i.toString()}),o.stderr?.on("data",i=>{r+=i.toString()});let s=()=>{o.kill()};e.signal?.addEventListener("abort",s,{once:!0}),o.on("error",i=>{e.signal?.removeEventListener("abort",s),n(i)}),o.on("close",i=>{e.signal?.removeEventListener("abort",s),t({exitCode:i??1,output:r})})})}function Pc(e,t){return e===127||/is not recognized as an internal or external command|command not found/i.test(t)}function Yf(e){try{let t=JSON.parse(bc(Or(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 Fn(e){return Uf(Or(e,".d360-writer","capture.json"))}function Tc(){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(`
|
|
389
|
+
`)}function Kf(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(", ")}
|
|
390
|
+
/screenshot list --detail shows what each one needs`}function zf(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):_r(r?.reason)!==_r(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):ti(r?.reason??"")!==ti(o.detail??"")?n.blockedNewReason.push(o.id):n.blockedAsBefore.push(o.id))}return n}function _r(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 Xf(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?Ro(o.detail):"no reason recorded"}`)}function Do(e,t=2){return e.length<=t?e.join(" \xB7 "):`${e.slice(0,t).join(" \xB7 ")} \xB7 +${e.length-t}`}function Qf(e,t){if(!t)return[];let n=[],o=(i,a,l,p)=>{a>0&&n.push({glyph:i,label:`${a} ${l}`,tail:p})};if(o("\u2713",e.newlyCaptured.length,"newly captured",Do(e.newlyCaptured)),o("\u2717",e.newlyBroken.length,"newly broken",Do(e.newlyBroken)),o("\u2192",e.repairedNowBlocked.length,"repaired",`no longer broken \u2014 only data stands in the way \xB7 ${Do(e.repairedNowBlocked)}`),o("\u2298",e.newlyBlocked.length,"newly blocked",Do(e.newlyBlocked)),o("\u2192",e.blockedNewReason.length,"blocked on something new",`an earlier step now passes \xB7 ${Do(e.blockedNewReason)}`),o("\u2192",e.brokeDifferently.length,"broken differently",`the previous cause is fixed \xB7 ${Do(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 Jf(e){let t=e.results.filter(T=>T.outcome==="captured"),n=e.results.filter(T=>T.outcome==="skipped"),o=e.results.filter(T=>T.outcome==="failed"),r=e.unannotated??[],s=T=>T===1?"":"s";if(t.length+n.length+o.length===0)return null;let i=e.articles.length===1?`/push ${e.articles[0]}`:be("/push","--screenshots",St(e.articles)),a=e.ids.length===1?`/screenshot capture ${e.ids[0]}`:"/screenshot capture",l=o[0]?.id,p=[];o.length>0&&p.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=be("/screenshot annotate","",r.length===1?r[0]:void 0);r.length>0&&p.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&&p.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&&p.push({glyph:"\u2713",cmd:i,why:`embed the ${t.length-r.length} new PNG${s(t.length-r.length)}`});let w=Math.max(...p.map(T=>T.cmd.length));return{note:p.map(T=>`${T.glyph} ${T.cmd.padEnd(w)} ${T.why}`).join(`
|
|
391
|
+
`),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 Zf(e,t){let n=new Map(Le(e).map(o=>[o.id,o.file]));return[...new Set(t.map(o=>n.get(o)).filter(o=>!!o))].sort()}async function Ac(e,t){let n=t?.cwd??process.cwd(),o=$c(e);if(!Fn(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}=Mr(n,o.mode==="scope"?o.scope:void 0),l=vc(n,a),p=(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,...p?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(!p&&o.mode!=="single"&&o.mode!=="failed"&&o.mode!=="blocked"){let C=xc(a.filter(S=>S.state==="blocked"),"/screenshot capture --blocked");C&&console.log(C)}let w=Date.now(),$=[];for(let C of m){console.log(`\u25B6 ${C}`);try{let{exitCode:S}=await Sc({cwd:n,id:C,stdio:"inherit"});$.push({id:C,outcome:Rc(n,C,S,w)})}catch(S){if(S.code==="ENOENT")return console.log("d360-capture is not installed. Run: npm i -g document360-capture"),{kind:"continue"};$.push({id:C,outcome:"failed",detail:S.message})}}let T=C=>$.filter(S=>S.outcome===C).length;console.log(`\u2713 ${T("captured")} captured \xB7 \u2298 ${T("skipped")} skipped \xB7 \u2717 ${T("failed")} failed`);let R=$.filter(C=>C.outcome==="captured");return Gs(n,$.map(C=>({id:C.id,outcome:C.outcome,reason:C.detail,specSource:jn(n,C.id)})),new Date().toISOString()),R.length>0?(console.log(pn(R.length)),{kind:"forward-to-agent",prompt:Et(n,R.map(C=>C.id)),display:"/screenshot verify"}):{kind:"continue"}}import{spawn as Qv}from"node:child_process";import{readProjectConfig as Jv,DEFAULT_OUTPUT_DIR as Zv,resolveOutputDir as ex,shotArtifacts as tx,annotationCurrent as nx}from"document360-engine";$o();var em="0.2.29";function $i(e=nt()){return vo(e,em)}function Ec(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 Dc(e,t){let n=Le(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 ox=/^[A-Za-z0-9._-]+$/;function rx(e){return new Promise((t,n)=>{if(!ox.test(e.id)){n(new Error(`Not a valid spec id: "${e.id}"`));return}let o=Qv(`d360-capture annotate ${e.id}${e.force?" --force":""}`,{cwd:e.cwd,shell:!0,stdio:e.stdio==="inherit"?"inherit":["ignore","pipe","pipe"],env:{...process.env,NO_UPDATE_NOTIFIER:"1"}}),r="";e.stdio==="pipe"&&(o.stdout?.on("data",i=>{r+=i.toString()}),o.stderr?.on("data",i=>{r+=i.toString()}));let s=()=>{o.kill()};e.signal?.addEventListener("abort",s,{once:!0}),o.on("error",i=>{e.signal?.removeEventListener("abort",s),n(i)}),o.on("close",i=>{e.signal?.removeEventListener("abort",s),t({exitCode:i??1,output:r})})})}function sx(e,t,n,o){let r=ex(e,Jv(e)?.outputDir??Zv),s=tx(r,t);return(s.annotatedMtimeMs??0)>=o?"annotated":n===0&&nx(s)?"skipped":"failed"}function Nc(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 ${em} or later, then /screenshot annotate becomes available.`}var vi=8;function tm(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:be("/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>vi?{glyph:"\u25C8",cmd:be("/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:be("/screenshot verify","",e.scope),why:`${n.length} picture${n.length===1?"":"s"} ready to check \u2014 no browser needed`}}async function jc(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 rx({cwd:e.cwd,id:o,...e.force?{force:!0}:{},...e.signal?{signal:e.signal}:{},stdio:"pipe"}),i=sx(e.cwd,o,r,t);n.push({id:o,outcome:i,...i==="failed"?{detail:ix(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 Ic(e,t){let n=t?.cwd??process.cwd(),o=Ec(e);if(!Fn(n))return console.log("Screenshot capture is not set up in this repo yet. Run: d360-capture init"),{kind:"continue"};let r=nt();if(!$i(r))return console.log(Nc(r)),{kind:"continue"};let s=Nn(n);s&&console.log(s);let i=o.mode==="scope"?o.scope:void 0,{pending:a,done:l,rows:p}=Dc(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 L=l.length>0;return console.log(L?`Every shot${i?` under ${i}`:""} is already drawn. Re-draw them anyway: /screenshot annotate --all --force`:"No shots have been taken yet \u2014 /screenshot capture takes them first."),{kind:"continue"}}let $=new Set(p.filter(L=>L.state==="verified").map(L=>L.id)),{results:T,cliMissing:R}=await jc({cwd:n,ids:w,force:m});if(R)return console.log("d360-capture is not installed. Run: npm i -g document360-capture"),{kind:"continue"};let C=L=>T.filter(Y=>Y.outcome===L).length;console.log(`\u2713 ${C("annotated")} annotated`+(C("skipped")?` \xB7 ${C("skipped")} already current`:"")+(C("failed")?` \xB7 \u2717 ${C("failed")} failed`:""));for(let L of T.filter(Y=>Y.outcome==="failed"))console.log(` \u2717 ${L.id}${L.detail?` \u2014 ${L.detail}`:""}`);let S=T.filter(L=>L.outcome==="annotated").map(L=>L.id);if(S.length===0)return{kind:"continue"};let E=S.filter(L=>$.has(L)).length;if(E>vi)return console.log(`\u26A0 ${E} verified shots were re-drawn, so their verdicts no longer describe the picture on disk.
|
|
392
|
+
Check them when you're ready: ${be("/screenshot verify","",i)}`),{kind:"continue"};let I=S.filter(L=>!$.has(L)||E>0);return I.length===0?{kind:"continue"}:(console.log(pn(I.length)),{kind:"forward-to-agent",prompt:Et(n,I),display:"/screenshot verify"})}function ix(e){return e.split(/\r?\n/).map(n=>n.trim()).filter(n=>n.length>0&&!/^[▶✓↕]/.test(n)).at(-1)}import{builderChannelWired as ax,driftedAnchors as lx,readTestidRequests as cx,testidHandoffPrompt as ux,testidRequestPaths as dx}from"document360-engine";async function No(){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(`
|
|
393
|
+
`),display:"/screenshot checklist"}}var nm="-".repeat(64);function om(e){let t=cx(e);if(t.length===0)return null;let{mdRel:n}=dx(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=ux(e,o),l=lx(t).length,p=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 ax(e)?{prompt:a,lines:[`\u{1F4CB} Developer hand-off \u2014 ${s} requested across ${i}.`,...p," 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}.`,...p,"\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.)","",nm,a,nm]}}sn();te();import{listOpenForDocs as px,readProjectConfig as hx}from"document360-engine";function Lc(e){try{return px(e).length}catch{return 0}}function Oc(){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(`
|
|
394
|
+
`)}async function rm(e,t){let n=t?.cwd??process.cwd();return hx(n)?Lc(n)===0?(console.log(y("Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)")),{kind:"continue"}):{kind:"forward-to-agent",prompt:Oc(),display:"/inbox"}:(console.log(j("No d360-writer config here. Run /init first.")),{kind:"continue"})}te();import{listOpenHints as bx,listOpenForDocs as $x,listOpenDirectives as vx,readProjectConfig as lm,computeSyncStatus as xx,planPull as Rx,applyPull as Cx,planImport as Sx,applyImport as Px,pullDocsUpdates as Tx,handoffAvailable as Ax,readProductBriefState as Ex,readDiscoveryQueue as Dx}from"document360-engine";te();import{readProjectConfig as fx,writeProjectConfig as sm,reconcileDocsGit as mx,pullDocsUpdates as gx,probeGitState as yx,resolveGitHandoff as im,handoffAvailable as wx}from"document360-engine";var Fr=e=>e===1?"":"s";function hn(e,t){let n=o=>{let r=(o??"").split(`
|
|
395
|
+
`).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 xi(e,t){let n=im(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=yx(e);if(!o)return[{tone:"info",text:"Sharing: unavailable \u2014 this folder is not a git repository."}];if(!o.upstream)return[{tone:"warn",text:re("\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:re("\u26A0")+`${o.ahead} change${Fr(o.ahead)} not shared yet \u2014 run /share`}):s.push({tone:"ok",text:re("\u2713")+"Everything is shared with your team."}),s}function _c(e,t,n){sm({...t,gitHandoff:{commit:n,push:n}},e);let o=n?{tone:"ok",text:re("\u2713")+"Sharing on \u2014 d360-writer will save and send its own work from now on."}:{tone:"ok",text:re("\u2713")+"Sharing off \u2014 d360-writer will leave its work for your coding agent to commit."};return n?[o,...xi(e,{...t,gitHandoff:{commit:!0,push:!0}})]:[o]}async function Ri(e,t){let n=[],o=im(t);if(!o.commit)return{lines:[{tone:"info",text:hn("disabled")}],changed:!1};let r=t;o.push==="unconfirmed"&&wx(e,t)&&(r={...t,gitHandoff:{commit:!0,push:!0}},sm(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 gx(e);if(s.ok&&s.pulled>0){let p=[s.newHints>0?`${s.newHints} new hint${Fr(s.newHints)}`:null,s.newMessages>0?`${s.newMessages} new message${Fr(s.newMessages)}`:null].filter(Boolean);n.push({tone:"ok",text:re("\u2B07")+`Got your builder's latest${p.length?` \u2014 ${p.join(", ")}`:""}.`})}else!s.ok&&s.reason!=="no-upstream"&&s.reason!=="no-git"&&n.push({tone:"warn",text:re("\u26A0")+hn(s.reason,s.detail)});let i=await mx(e,r);if(i.commit&&!i.commit.ok)return n.push({tone:"warn",text:re("\u26A0")+hn(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:re("\u2713")+`Saved ${a} change${Fr(a)} to the docs folder.`}),i.push&&!i.push.ok)return n.push({tone:"warn",text:re("\u26A0")+hn(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:re("\u2B06")+`Shared ${l} change set${Fr(l)} with your team.`}):a===0&&(s.ok&&s.pulled===0)?n.push({tone:"ok",text:re("\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 kx={ok:V,info:$e,warn:G,error:j};async function am(e,t){let n=t.cwd,o=fx(n);if(!o)return console.log(j("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(kx[l.tone](l.text))};if(r==="status")return s(xi(n,o)),{kind:"continue"};if(r==="on"||r==="off")return s(_c(n,o,r==="on")),{kind:"continue"};if(r)return console.log(j(`Unknown option "${r}". Use /share, /share status, /share on, or /share off.`)),{kind:"continue"};console.log(y("Exchanging work with your team\u2026"));let{lines:i}=await Ri(n,o);return s(i),{kind:"continue"}}function Wn(e){let t=0,n=0,o=0,r=0;try{t=bx(e).length}catch{}try{let s=$x(e);n=s.filter(i=>i.kind==="request").length,o=s.filter(i=>i.kind==="answer").length}catch{}try{r=vx(e).length}catch{}return{hints:t,requests:n,answers:o,directives:r}}async function Fc(e){let t=lm(e);if(!t)return[];if(!Ax(e,t))return[];let n=await Tx(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 ${hn(n.reason,n.detail)}`}]}function Wc(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 Uc(e){let t=Wc(e);return t?`Catching up on ${t}\u2026`:"Nothing queued from your builder \u2014 checking Document360 for reviewer comments and feedback\u2026"}function Bc(e){return{push:e.includes("--push")||e.includes("--publish"),skipReview:e.includes(ct)}}function Hc(e){let t={hold:!1,openQuestions:0,answersPending:0};try{let n=Ex(e);return!n||n.status==="confident"?t:{hold:!0,...Dx(e)}}catch{return t}}function qc(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:`${re("\u2139")}Product discovery is still open \u2014 ${n} answer${jo(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:`${re("\u26A0")}Product discovery isn't finished \u2014 ${n} question${jo(n)} still with your builder.`},{tone:"warn",text:` ${t} until the brief is settled.`}]}return[{tone:"warn",text:`${re("\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 Gc(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${jo(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(`
|
|
396
|
+
`)}var Nx={status:xx,plan:Rx,apply:Cx,planImport:Sx,applyImport:Px};async function Vc(e,t=Nx){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 Mc=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,jo=e=>e===1?"":"s";function Yc(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${jo(e.pulled.length)} into local: ${Mc(e.pulled)}`),e.imported.length&&t.push(`\u2713 Imported ${e.imported.length} new portal article${jo(e.imported.length)} into local drafts: ${Mc(e.imported)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${jo(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${Mc(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 cm(e,t){let n=t?.cwd??process.cwd();if(!lm(n))return console.log(j("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Ve(n,t?.profileName);if(!o.ok)return console.log(j(o.reason)),{kind:"continue"};let{push:r}=Bc(e);for(let a of await Fc(n))console.log(a.tone==="ok"?V(a.text):G(a.text));console.log(y("Reconciling with Document360 (pulling any portal changes)\u2026"));let s=await Vc({cwd:n,profileName:t?.profileName});for(let a of Yc(s))console.log(a.startsWith("\u2713")?V(a):a.startsWith("\u2139")?y(a):G(a));let i=Hc(n);for(let a of qc(i))console.log(a.tone==="warn"?G(a.text):y(a.text));return console.log(y(Uc(Wn(n)))),{kind:"forward-to-agent",prompt:Gc(i),display:`/catch-up${r?" --push":""}`}}te();import{resolveActiveProfile as jx,resolveProjectId as Ix,loadProfileMap as Lx,readCommentLedger as Ox,isCommentOpen as _x,saveOpenCommentCount as Mx,loadCommentSweepMemory as Fx,recordCommentSweep as Wx,planCommentSweep as Ux,sweepOpenComments as Bx,commentHtmlToText as um,annotatedText as Hx,readProjectConfig as qx,loadPortalLabels as Gx,portalBreadcrumb as pm,portalCategoryPath as Vx,resolveModelForOperation as Yx,runPartitioned as Kx,EMPTY_PORTAL_LABELS as zx}from"document360-engine";import ve from"picocolors";var hm=300,Wr=3;function Xx(e,t){let n=bp(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||wo(n).toLowerCase()===o}async function zc(e,t,n={}){let o=jx(e,t),r={profile:o.name,connection:o.connection},s=Ix(r,o.project.projectId),i=Lx(e,o.name);if(!i)return{threads:[],answered:[],labels:zx,scanned:0,failed:[],truncated:0,skipped:0};let a=Ox(e,o.name),l=new Set(Object.values(a).map(L=>L.articlePath).filter(L=>!!L)),p=Object.keys(a).length===0||l.size>0,m=n.articleIds?.length?new Set(n.articleIds):null,w=!!(m||n.path||n.scope),$=Object.entries(i.articles).filter(([,L])=>!!L.id).filter(([L,Y])=>m?m.has(Y.id):n.path?L.replace(/\\/g,"/")===n.path.replace(/\\/g,"/"):n.scope?Xx(L,n.scope):!0).map(([L,Y])=>({articleId:Y.id,path:L,title:$p(e,L),answered:w||(p?l.has(L):!0)})),T=$.slice(0,hm),R=await Gx(r,s,o.project.workspaceId,{cwd:e,profile:o.name}),C=w||n.full?{read:T,skipped:[]}:Ux(T,{live:R.live,stateOf:L=>R.articles.get(L),memory:Fx(e,o.name),alwaysRead:new Set($.filter(L=>l.has(L.path)).map(L=>L.articleId))}),S=o.project.languageCode,E=await Bx(r,s,C.read,{isOpen:(L,Y)=>_x(a,L,Y),...S?{langCode:S}:{},...n.onProgress?{onProgress:n.onProgress}:{}});w||Mx(e,o.name,E.threads.length);let I=new Map;for(let L of[...E.threads,...E.answered])I.set(L.articleId,(I.get(L.articleId)??0)+1);return Wx(e,o.name,{live:R.live,read:C.read.map(L=>L.articleId),failedIds:E.failed.map(L=>L.articleId),threadCounts:I,latestVersionOf:L=>R.articles.get(L)?.latestVersion}),{threads:E.threads,answered:E.answered,labels:R,scanned:E.scanned,failed:E.failed,truncated:Math.max(0,$.length-T.length),skipped:C.skipped.length}}function Qx(e,t=96){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n}var dm=500;function Jx(e){let t=Hx(e.comment);if(!t)return"a passage";let n=t.replace(/\s+/g," ").trim();if(n.length<=dm)return e.comment.commented_text_truncated?`\u201C${n}\u2026\u201D
|
|
397
|
+
(Document360 sends the first 500 characters of a highlight)`:`\u201C${n}\u201D`;let o=n.slice(0,dm).trimEnd(),r=n.length-o.length;return`\u201C${o}\u2026\u201D
|
|
398
|
+
(+${r} more character${r===1?"":"s"}${e.comment.commented_text_truncated?", and Document360 caps a highlight at 500":""})`}function Zx(e,t){let n=Vx(t,e.articleId);return n.length>0?n.join(" \u203A "):e.path?wo(e.path):""}function e0(e,t){return t.articles.get(e.articleId)?.title?.trim()||e.title||(e.path?Ba(e.path):e.articleId)}function t0(e,t){return pm(t,e.articleId,{category:e.path?wo(e.path):null,title:e.title??(e.path?Ba(e.path):null)})??e.path??e.articleId}function Un(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:Zx(o,t),title:e0(o,t),label:t0(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 n0=100,o0=120,fm=(e,t)=>Math.max(40,Math.min(e??96,t));function mm(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`),`${ve.bold("Reviewer comments")} ${r.join(` ${ve.gray("\xB7")} `)}`}function Kc(e){let t=[],n=o=>o===1?"":"s";if(e.skipped>0&&t.push(ve.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(`${re("\u26A0",ve.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=pm(e.labels,o.articleId,{title:o.title})??o.title??o.articleId;t.push(` ${ve.gray(`${r} \u2014 ${Qx(o.error,60)}`)}`)}e.failed.length>5&&t.push(` ${ve.gray(`+${e.failed.length-5} more`)}`),t.push(ve.gray(" Run /comments again to retry them."))}return e.truncated&&t.push(`${re("\u26A0",ve.yellow)}Checked the first ${hm} articles; ${e.truncated} not checked this run.`),t}function Ur(e,t={}){let n=[],o=a=>a===1?"":"s",r=e.answered.length,s=()=>{if(!(!t.showAnswered||r===0)){n.push(` ${ve.gray(`Answered, waiting on the reviewer (${r})`)}`);for(let a of Un(e.answered,e.labels))n.push(` ${ve.gray(`${a.label} \u2014 ${a.threads.length} thread${o(a.threads.length)}`)}`);n.push("")}};if(e.threads.length===0){let a=r>0?` ${ve.gray("\xB7")} ${r} answered, awaiting reviewer`:"";return n.push(`${re("\u2713",ve.green)}No open reviewer comments across ${e.scanned} article${o(e.scanned)}.${a}`),r>0?(n.push(ve.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(ve.gray(" /comments --answered lists them."))):n.push(ve.gray(" Reviewers leave these by highlighting text in a draft in the Document360 portal and commenting on it.")),n.push(""),s(),n.push(...Kc(e)),n}let i=Un(e.threads,e.labels);return n.push(mm(e)),n.push(""),n.push(qa(["#","Category","Article","Comments"],i.map((a,l)=>[`${l+1}`,a.category||"(root)",a.title,`${a.threads.length}`]),fm(t.width,n0),{plain:!0,align:["left","left","left","right"]})),n.push(""),s(),n.push(...Kc(e)),n}function Ci(e,t={}){let n=s=>s===1?"":"s",o=[`${ve.gray("Category:")} ${e.category||"(root)"}`,`${ve.gray("Article: ")} ${ve.bold(e.title)}`,ve.gray(`${e.threads.length} comment${n(e.threads.length)} from your reviewers`),""],r=e.threads.map(s=>{let i=[um(s.comment.comment)||"(empty comment)"];for(let a of s.comment.replies??[])i.push(`\u21B3 ${um(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)"),[Jx(s),i.join(`
|
|
399
|
+
`)]});return o.push(qa(["Annotated text","Comment"],r,fm(t.width,o0),{plain:!0})),o.push(""),o}function Si(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 Xc(e,t={}){let n=Un(e.threads,e.labels);if(t.full&&n.length===1){let o=n[0];return[mm(e),"",...Ci(o,t),...Kc(e)]}return Ur(e,t)}function r0(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 (push-to-d360 skill: d360_update_article, with auto_fork when it is already published). 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 Qc(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.`,"",...r0({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(`
|
|
400
|
+
`)}function Jc(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 s0(e,t,n){if(t.length===0)return{kind:"continue"};let o=t.reduce((a,l)=>a+l.threads.length,0),{model:r}=Yx(e.cwd,"standard"),s=new Map(t.map(a=>[a.label,a])),i=t.map(a=>({label:a.label,paths:a.path?[a.path]:[]}));console.log(y(`Answering ${o} comment${o===1?"":"s"} across ${i.length} article${i.length===1?"":"s"} (\u2264${Wr} 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`));try{for await(let a of Kx({cwd:e.cwd,partitions:i,promptFor:l=>{let p=s.get(l.label);return Qc({articleId:p.articleId,label:p.label,path:p.path,count:p.threads.length,resolve:n.resolve})},concurrency:Wr,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),allowCommentResolve:n.resolve,model:r}))if(a.type==="partition_status")a.status==="running"?console.log(y(` \u25B8 ${a.label} \u2014 answering\u2026`)):a.status==="done"?console.log(V(` \u2713 ${a.label}`)):console.log(j(` \u2717 ${a.label}`));else if(a.type==="run_done"){let l=a.results.filter(p=>!p.ok);console.log(""),console.log(`${a.results.length-l.length}/${i.length} article${i.length===1?"":"s"} answered.`),l.length&&console.log(G(`\u26A0 ${l.length} left untouched (their comments are still open, so nothing was promised to those reviewers): ${l.map(p=>p.label).join(", ")}`)),a.blocked&&console.log(G(`\u26A0 ${a.blocked}`)),a.allEmpty&&console.log(G("\u26A0 No agent produced any work this run \u2014 nothing was changed or answered."))}}catch(a){console.log(j(`Answering comments failed: ${a.message}`))}return{kind:"continue"}}async function gm(e,t){let n=t?.cwd??process.cwd();if(!qx(n))return console.log(j("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Ve(n,t?.profileName);if(!o.ok)return console.log(j(o.reason)),{kind:"continue"};let r=Jc(e);console.log(y("Checking Document360 for reviewer comments\u2026"));let s;try{s=await zc(n,t?.profileName,r.scope)}catch(a){return console.log(j(`Couldn\u2019t read comments from Document360: ${a.message}`)),{kind:"continue"}}for(let a of Xc(s,{full:!!r.scope.path,showAnswered:r.showAnswered}))console.log(a);if(s.threads.length===0)return{kind:"continue"};if(r.answer&&t)return s0(t,Un(s.threads,s.labels),{resolve:r.resolve});let i=Un(s.threads,s.labels)[0];return console.log(`${re("\u2192",ve.yellow)}${ve.bold("/comments <article>")} shows one article\u2019s comments in full `+ve.gray(i?.path?`(e.g. /comments ${i.path})`:"(by its local path)")),console.log(`${re("\u2192",ve.yellow)}${ve.bold("/comments --answer")} fixes each one, updates the draft in Document360, then replies in the thread `+ve.gray("(one article at a time: /comments --answer <article>, or --scope <category>)")),{kind:"continue"}}te();import{spawn as ym}from"node:child_process";var Io="document360-writer",Pi=`npm i -g ${Io}@latest`,i0="document360-capture";function a0(){return new Promise(e=>{try{let t=ym("d360-capture --version",{stdio:"ignore",shell:!0,windowsHide:!0});t.on("error",()=>e(!1)),t.on("close",n=>e(n===0))}catch{e(!1)}})}async function Ti(){let e=process.platform==="win32",n=await a0()?[Io,i0]:[Io];return new Promise(o=>{try{let r=ym(`npm i -g ${n.map(s=>`${s}@latest`).join(" ")}`,{stdio:"ignore",shell:!0,detached:!e,windowsHide:!0});r.on("error",s=>o({ok:!1,output:String(s),packages:n})),r.on("close",s=>o({ok:s===0,output:"",packages:n})),e||r.unref()}catch(r){o({ok:!1,output:String(r),packages:n})}})}async function wm(){console.log(y("Updating the d360-writer toolchain\u2026"));let e=await Ti();return e.ok?console.log(V(`\u2713 Updated ${e.packages.join(" + ")}. Exit (/exit) and relaunch d360-writer to apply.`)):console.log(j(`Update failed \u2014 run manually: ${Pi}`)),{kind:"continue"}}te();sn();import{existsSync as Zc,rmSync as l0}from"node:fs";import{basename as km,resolve as eu}from"node:path";import{execFileSync as c0}from"node:child_process";import{input as u0}from"@inquirer/prompts";import{readProjectConfig as d0,devHintsGuidePath as p0}from"document360-engine";var h0=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],f0=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),Ai=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),bm=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function $m(e){let t=Ai(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:bm(t)?!0:f0.has(t)}function tu(e){let t=null;try{t=d0(e)}catch{t=null}let n=new Set(h0);for(let o of[Ai(t?.docsDir),Ai(t?.captureDir),Ai(t?.outputDir)])o&&bm(o)&&n.add(o);return[...n].filter(o=>$m(o)&&Zc(eu(e,o)))}function nu(e,t){let n=[],o=[];for(let r of t){if(!$m(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{l0(eu(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function vm(e,t){try{return c0("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
|
|
401
|
+
`).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function m0(e){return vm(e,".d360-writer/hints")}function g0(e){return vm(e,".d360-writer/messages")}function ou(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=m0(e),o=g0(e),r=Zc(eu(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: ${km(e)}`]}async function xm(e,t){let n=tu(t.cwd);for(let l of ou(t.cwd,n))console.log(n.length===0?y(l):l);if(n.length===0)return{kind:"continue"};let o=km(t.cwd);if((await t.withPausedInput(()=>u0({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(G("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=Zc(p0(t.cwd)),{removed:i,failed:a}=nu(t.cwd,n);console.log(V(`\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(j(` \u2717 ${l.path}: ${l.error}`));if(s){for(let l of _s())console.log(l);console.log(y("(Select and copy the prompt above to paste into your coding agent.)"))}return console.log(y("Set up d360-writer again with /init (then /login, /workspace).")),{kind:"continue"}}te();import{buildBaseline as y0,buildRegistry as iu,clearRegistryCache as w0,lintArticles as au,listAvailablePacks as Sm,readProjectConfig as Hr,readStyleBaseline as k0,resolveActivePacks as b0,styleGuidePath as Pm,writeProjectConfig as Tm,writeStyleBaseline as $0,activeRuleSet as v0,buildStyleCompilePrompt as x0,loadStyleGuide as R0,listStyleGuides as C0,getStyleGuide as S0,resolveActiveProfile as P0,resolveProjectId as T0,STYLE_GUIDE_MAX_CHARS as Rm,BUILTIN_RULES as Ei,ALWAYS_ON_PACK as Lo}from"document360-engine";import{existsSync as Am,mkdirSync as A0,readFileSync as E0,writeFileSync as Cm}from"node:fs";import{dirname as D0}from"node:path";import{createHash as N0}from"node:crypto";function j0(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==="explain"?{sub:"explain",value:t[1]}:n==="pull"?{sub:"pull",value:t[1]}:n==="compile"?{sub:"compile"}:{sub:"show"}}var Br="House";async function I0(e,t,n){let o,r;try{let C=P0(e,n);o={profile:C.name,connection:C.connection},r=await T0(o,C.project?.projectId)}catch(C){return{lines:[we("\u2717",`Not signed in to Document360: ${C instanceof Error?C.message:String(C)}`),y(" Run /login first.")],restart:!1}}let s=await C0(o,r);if(s.kind!=="ok")return{lines:[we("\u26A0",`Document360 didn't return your style guides \u2014 ${s.reason}.`),y(" Nothing is blocked. Your house style guide lives at .d360-writer/style-guide.md \u2014 write or paste"),y(" it there directly, and /review and the writer both read it. /style-guide compile then turns its"),y(" mechanical parts into checks.")],restart:!1};if(s.guides.length===0)return{lines:[we("\u2139","This Document360 project has no style guides yet."),y(" 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((S,E)=>{let I=[S.language_code,S.created_by_name,S.created_at?.slice(0,10)].filter(Boolean).join(" \xB7 ");return` ${E+1} ${S.name??S.id}${S.is_default?y(" (default)"):""}${I?y(` ${I}`):""}`}),"",y(" 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:[we("\u2717",`No style guide numbered or identified by "${t}". Run /style-guide pull to list them.`)],restart:!1};let l=await S0(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:[we("\u2717",`Could not read "${a.name??a.id}" \u2014 ${C}.`)],restart:!1}}let p=(l.guide.content??"").trim();if(!p)return{lines:[we("\u26A0",`"${a.name??a.id}" has no content yet \u2014 nothing to pull.`)],restart:!1};let m=Pm(e),w=[];if(Am(m))try{Cm(`${m}.bak`,E0(m,"utf8"),"utf8"),w.push(y(" Your previous guide is at .d360-writer/style-guide.md.bak"))}catch{}let $=p.length>Rm?p.slice(0,Rm):p,T=`<!-- Pulled from Document360: "${a.name??a.id}" (${new Date().toISOString().slice(0,10)}). Edit freely \u2014 /style-guide pull overwrites this file. -->
|
|
402
|
+
|
|
403
|
+
`;A0(D0(m),{recursive:!0}),Cm(m,`${T}${$}
|
|
404
|
+
`,"utf8");let R=Hr(e)??{projectId:""};return Tm({...R,styleGuide:{...R.styleGuide,pulledFrom:{styleGuideId:a.id,name:a.name??a.id,pulledAt:new Date().toISOString(),contentHash:N0("sha1").update($).digest("hex").slice(0,16)}}},e),{lines:[we("\u2713",`Pulled "${a.name??a.id}" into .d360-writer/style-guide.md (${$.length.toLocaleString()} characters).`),...w,y(" This is PROSE, not rules \u2014 /review judges against it, and the writer now writes to it."),y(" Turn its mechanical parts into checks: /style-guide compile"),y(" Restarting the agent so it writes to the new guide\u2026")],restart:!0}}function L0(e){let t=iu(e).rules.filter(n=>n.pack.toLowerCase()===Br.toLowerCase()).map(n=>n.id);return{prompt:x0({guide:R0(e),packName:Br,existingRuleIds:t}),display:"/style-guide compile"}}function Em(){return[y(` Review what it wrote: git diff .d360-writer/styles/${Br}/`),y(` Anything it could not check mechanically is listed in .d360-writer/styles/${Br}/UNCHECKABLE.md \u2014 /review judges those.`),y(` Turn them on when you are happy: /style-guide use ${Br.toLowerCase()} (they start as warnings, never blocking)`)]}var dt=(e,t)=>`${e} ${t}${e===1?"":"s"}`,ru=e=>/^v\d/i.test(e)?e:`v${e}`;function Dm(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 O0(e){let n=Hr(e)?.styleGuide?.pulledFrom;return n?`.d360-writer/style-guide.md \u2014 pulled ${n.pulledAt.slice(0,10)} from "${n.name}"`:Am(Pm(e))?".d360-writer/style-guide.md (yours)":"the built-in default"}function _0(e){let t=Hr(e),n=iu(e),o=(t?.styleGuide?.packs??[]).filter(Boolean),r=n.packs.filter(l=>l.name.toLowerCase()===Lo),s=n.packs.filter(l=>l.name.toLowerCase()!==Lo),i=[`Style guide: ${O0(e)}`,`Rule packs: ${s.length>0?s.map(l=>`${l.name.toLowerCase()} ${ru(l.version)}`).join(", "):y("none chosen")}`,`Always on: ${y(`d360 (correctness, built in \u2014 ${dt(Ei.length,"rule")})`)}`];for(let l of r)i.push(` ${y(`${l.name.toLowerCase()} ${ru(l.version)} (anti-slop \u2014 ${dt(l.ruleCount,"rule")})`)}`);r.length>0&&(i.push(y(" Every article here is machine-written, so these cannot be switched off by")),i.push(y(" choosing another pack. styleGuide.humanise: false turns them off deliberately.")));let a=[...Ei.map(l=>({severity:l.severity})),...n.rules.map(l=>({severity:l.severity}))];i.push("",`${dt(a.length,"rule")} active \xB7 ${Dm(a)}`);try{let l=au({cwd:e}),p=l.findings.filter(w=>!w.baselined),m=p.filter(w=>w.severity==="error").length;i.push(""),i.push(m===0?we("\u2713",`No style errors across the docs${p.length>0?`, though ${dt(p.length,"other issue")} ${p.length===1?"is":"are"} reported`:""}.`):we("\u2717",`${dt(m,"style error")} \u2014 /lint shows them, /lint --fix corrects them.`)),l.baselinedCount>0&&i.push(we("\u2139",`${dt(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(we("\u26A0",`${dt(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(y(" See them all: /style-guide list \xB7 change: /style-guide use <preset> \xB7 one rule: /style-guide explain <rule>")),i}function su(e){let t=Hr(e),n=new Set(b0(t?.styleGuide)),o=Sm(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),p=a===Lo,m=l?"\u2713":"\xB7",w=p?y("(always on)"):l?y("(active)"):"",$=i.local?y(" [yours]"):"";r.push(` ${m} ${a.padEnd(s)}${$} ${i.description??""}`),r.push(` ${y(`${dt(i.rules.length,"rule")} \xB7 ${Dm(i.rules)} \xB7 ${ru(i.version)}`)} ${w}`),i.errors.length>0&&r.push(we("\u26A0",`${dt(i.errors.length,"rule")} in this pack could not be loaded \u2014 /style-guide explain names them.`))}return o.every(i=>i.name.toLowerCase()===Lo)&&(r.push(""),r.push(y(" The Microsoft and Google style guides are not installed in this build yet."))),r.push(""),r.push(y(" Turn one on: /style-guide use <name> (this replaces the chosen set, it does not add to it)")),r.push(y(" Several: /style-guide use microsoft,google")),r.push(y(" Back to none: /style-guide use none")),r}function M0(e,t){if(!t)return[we("\u26A0","Name a rule: /style-guide explain Humanise.EmDash")];let n=iu(e),o=Ei.find(p=>p.id.toLowerCase()===t.toLowerCase()),r=n.rules.find(p=>p.id.toLowerCase()===t.toLowerCase());if(!o&&!r){let p=[...Ei.map(m=>m.id),...n.rules.map(m=>m.id)].filter(m=>m.toLowerCase().includes(t.toLowerCase())).slice(0,5);return[we("\u26A0",`No active rule called "${t}".`),...p.length>0?[y(` Did you mean: ${p.join(", ")}`)]:[y(" /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(y(` ${r.link}`)),r?.degraded&&(l.push(""),l.push(we("\u26A0",`This rule is translated approximately: ${r.degraded}. It may match slightly more than the original does.`)));try{let p=au({cwd:e}).findings.filter(w=>w.ruleId===s),m=p.filter(w=>!w.baselined);l.push(""),l.push(p.length===0?" Currently: no findings.":` Currently: ${dt(m.length,"finding")}${p.length!==m.length?`, plus ${p.length-m.length} baselined and hidden`:""}.`)}catch{}return l.push(""),o?(l.push(y(" Built-in checks are grounded in your product's own source and cannot be switched off \u2014 they")),l.push(y(" catch defects of fact, not matters of taste."))):(l.push(y(` Silence it everywhere: add "${s}": "off" to styleGuide.rules in .d360-writer/config.json`)),i!=="error"&&l.push(y(" Silence one passage: <!-- vale "+s+" = NO --> \u2026 <!-- vale "+s+" = YES -->"))),l}function F0(e,t){let n=(t??"").trim();if(!n)return{lines:[we("\u26A0","Name the packs to use: /style-guide use microsoft (or `none`)"),...su(e)],restart:!1};let o=n.toLowerCase()==="none"?[]:n.split(/[,\s]+/).map(l=>l.trim().toLowerCase()).filter(Boolean),r=new Map(Sm(e).map(l=>[l.name.toLowerCase(),l])),s=o.filter(l=>!r.has(l));if(s.length>0)return{lines:[we("\u2717",`No rule pack named ${s.map(l=>`"${l}"`).join(", ")}.`),"",...su(e)],restart:!1};let i=Hr(e)??{projectId:""};Tm({...i,styleGuide:{...i.styleGuide,packs:o}},e),w0();let a=[we("\u2192",`Switching to: ${o.length>0?o.join(", "):"the built-in checks only"}${o.includes(Lo)?"":` (+ ${Lo}, always on)`}\u2026`)];try{let l=au({cwd:e}),p=new Set(l.findings.map(m=>m.path)).size;if(l.findings.length===0)a.push(we("\u2713",p===0?"No articles yet \u2014 everything you write from here is held to the full set.":"Nothing to record: your articles are already clean against these rules."));else{let m=k0(e),w=y0(l.findings,v0(e));$0(e,w),a.push(we("\u2713",`Recorded ${dt(l.findings.length,"existing issue")} across ${dt(p,"article")} as accepted.`),y(" .d360-writer/style-baseline.json \u2014 commit it. It defines what the publish gate lets through, and a"),y(" teammate with a different copy gets a different answer from the same gate."),we("\u2713","Nothing is blocked today. New writing, and any paragraph you edit, is held to the full set.")),m&&a.push(y(` (Replaced the baseline recorded ${m.createdAt.slice(0,10)}.)`))}}catch(l){a.push(we("\u26A0",`The packs are active, but recording what was already there failed: ${l instanceof Error?l.message:String(l)}`)),a.push(y(" Run /lint to see the current state before publishing."))}return a.push(y(" Restarting the agent so it writes to the new rules\u2026")),{lines:a,restart:!0}}async function Di(e,t){let{sub:n,value:o}=j0(e),r=s=>{for(let i of s)console.log(i);console.log("")};switch(n){case"list":return r(su(t.cwd)),{kind:"continue"};case"explain":return r(M0(t.cwd,o)),{kind:"continue"};case"use":{let s=F0(t.cwd,o);return r(s.lines),s.restart?{kind:"clear"}:{kind:"continue"}}case"pull":{let s=await I0(t.cwd,o,t.profileName);return r(s.lines),s.restart?{kind:"clear"}:{kind:"continue"}}case"compile":{let s=L0(t.cwd);return{kind:"forward-to-agent",prompt:s.prompt,display:s.display}}default:return r(_0(t.cwd)),{kind:"continue"}}}te();import{lintDocs as lu,loadStyleGuide as Lm,buildReviewPrompt as Om,readProjectConfig as _m,DEFAULT_DOCS_DIR as Mm,listArticleFiles as Fm,planPartitions as G0,runPartitioned as V0,partitionCoverage as Y0,resolveModelForOperation as K0,stampArticles as z0}from"document360-engine";te();import{readProjectConfig as W0,loadProfileMap as U0,resolveActiveProfile as B0,desiredCategoryOrder as H0,desiredArticleOrder as q0}from"document360-engine";function Nm(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}var jm=e=>e.replace(/\\/g,"/").split("/").pop()??e;function qr(e,t){try{if(!W0(e))return[];let n=B0(e,t),o=U0(e,n.name);if(!o)return[];let r=new Map;for(let i of q0(o)){let a=r.get(i.categoryPath);a?a.push(i):r.set(i.categoryPath,[i])}let s=[];for(let i of H0(o)){s.push(Nm(jm(i.path)));for(let a of(r.get(i.path)??[]).sort((l,p)=>l.order-p.order))s.push(` ${Nm(jm(a.path))}`)}return s}catch{return[]}}async function Im(e,t){let n=qr(t.cwd,t.profileName);if(n.length===0)return console.log(y("No documentation structure yet \u2014 run /init and author some articles first.")),{kind:"continue"};console.log(z("Documentation order (categories \u2192 articles):"));for(let o of n)console.log(o);return console.log(""),{kind:"continue"}}function Vr(e,t){return Cr(e,Fm(e,t))}function cu(e,t,n){return t.includes("--blocked")?Vr(e,n):Fm(e,n)}function X0(e,t){let n=_m(e);if(!n)return null;let o=(n.docsDir??Mm).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),s=t.includes("--blocked"),i=t.find(T=>!T.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),a=lu({cwd:e}),l=i?a.filter(T=>T.path===`${o}/${i}`||T.path.startsWith(`${o}/${i}/`)):a,p=s?Vr(e,i):void 0,m=p?l.filter(T=>p.includes(T.path)):l,w=i||s?"":qr(e).join(`
|
|
405
|
+
`);return{prompt:Om({docsRoot:o,scope:i,styleGuide:Lm(e),deterministicFindings:m,fix:r,structure:w||void 0,...p?{paths:p}:{}}),display:`/review${i?` ${i}`:""}${s?" --blocked":""}${r?" --fix":""}`}}var Q0=e=>"ruleId"in e,Gr=3,J0=3;function uu(e,t){let n=X0(e,t);if(!n)return null;let o=t.find(w=>!w.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),r=cu(e,t,o),s=G0(r,{maxPerPartition:J0});if(s.length<=1)return{kind:"single",...n};let a=(_m(e)?.docsDir??Mm).replace(/\\/g,"/").replace(/\/+$/,""),l=t.includes("--fix"),p=Lm(e),m=lu({cwd:e});return{kind:"partitioned",partitions:s,articles:r.length,wholeKb:!o&&!t.includes("--blocked"),display:n.display,promptFor:w=>{let $=new Set(w.paths);return Om({docsRoot:a,styleGuide:p,deterministicFindings:m.filter(T=>$.has(T.path)),fix:l,paths:w.paths})}}}async function Wm(e,t){if(e.includes("--blocked")&&Vr(t.cwd,e.find(o=>!o.startsWith("--"))).length===0)return console.log(V("\u2713 Nothing is blocked \u2014 every article has been through an editorial read.")),console.log(y(" /review --all --fix re-reviews everything; /push --all saves what has changed to Document360.")),{kind:"continue",ownNext:!0};if(dn("review",e)){let o=Ao(t.cwd,"review",e,t.profileName);if(o.length>0){for(let r of o)console.log(y(r));return{kind:"continue"}}}let n=uu(t.cwd,e);return n?n.kind==="single"?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:await Z0(t,n,e.includes("--fix"),e.find(o=>!o.startsWith("--"))):(console.log(j("No d360-writer config here. Run /init first.")),{kind:"continue"})}async function Z0(e,t,n,o){let{model:r}=K0(e.cwd,"standard");console.log(y(`Reviewing ${t.articles} article${t.articles===1?"":"s"} in ${t.partitions.length} batches (\u2264${Gr} editors at once) on ${r}${n?", applying fixes":", report only"}\u2026`));try{for await(let a of V0({cwd:e.cwd,partitions:t.partitions,promptFor:t.promptFor,concurrency:Gr,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:r}))if(a.type==="partition_status")a.status==="running"?console.log(y(` \u25B8 ${a.label} \u2014 reviewing\u2026`)):a.status==="done"?console.log(V(` \u2713 ${a.label}`)):console.log(j(` \u2717 ${a.label}`));else if(a.type==="run_done"){let l=Y0(t.partitions,a.results);console.log(""),console.log(`${a.results.length-l.failed.length}/${t.partitions.length} batches reviewed.`),l.failed.length&&console.log(G(`\u26A0 ${l.failed.length} not reviewed: ${l.failed.map(p=>p.label).join(", ")}`)),l.notRun.length&&console.log(G(`\u26A0 ${l.notRun.length} batch${l.notRun.length===1?"":"es"} never started \u2014 their articles are untouched.`)),a.blocked&&console.log(G(`\u26A0 ${a.blocked}`)),a.allEmpty&&console.log(G("\u26A0 No editor produced any work this run \u2014 nothing was reviewed or changed."));for(let p of du(t))console.log(y(p));if(n&&!a.allEmpty&&!a.blocked)try{z0(e.cwd,l.covered,Qe("review"))}catch{}}}catch(a){return console.log(j(`Review failed: ${a.message}`)),{kind:"continue"}}if(!n)return{kind:"continue"};let i=lu({cwd:e.cwd,scope:o}).filter(a=>!a.baselined).filter(a=>Q0(a)&&a.severity==="error");if(console.log(""),i.length>0){let a=be("/lint","--fix",o);console.log(y(`Editor applied its fixes, but ${i.length} style error${i.length===1?"":"s"} remain \u2014 ${a} clears them (finding them costs nothing, one pass corrects them).`))}else console.log(y(Tt(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 du(e){return e.wholeKb?["Each editor saw one slice of the docs, so reading order and terminology drift ACROSS categories were not judged.","/structure shows the reading order if you want to check it yourself."]:[]}te();import{readProjectConfig as eR}from"document360-engine";function pu(e,t){if(!eR(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(`
|
|
406
|
+
`),display:`/reorder${n?` ${n}`:""}`}}async function Um(e,t){if(dn("reorder",e)){let o=Ao(t.cwd,"reorder",e,t.profileName);if(o.length>0){for(let r of o)console.log(y(r));return{kind:"continue"}}}let n=pu(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(j("No d360-writer config here. Run /init first.")),{kind:"continue"})}te();import{readProjectConfig as tR,writeProjectConfig as Bm,isAppType as nR,playbookSkillName as oR,detectAppType as Hm}from"document360-engine";var qm=["web","cli","service","library"],rR=new Set(["web","cli"]);function hu(e){return rR.has(e)?`${oR(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function Ni(e,t){let n=t.cwd,o=tR(n);if(!o)return console.log(j("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let s=o.appType??Hm(n);if(s){let i=o.appType?"set in config":"auto-detected";console.log(`${z("Genre:")} ${s} (${i}) \u2014 ${hu(s)}`)}else console.log(G("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(y(`Set it: /genre <${qm.join("|")}> \xB7 revert to auto-detect: /genre auto`)),{kind:"continue"}}if(r==="auto"||r==="clear"){if(!o.appType)return console.log(y("Already on auto-detect (no genre set in config).")),{kind:"continue"};let{appType:s,...i}=o;Bm(i,n);let a=Hm(n);return console.log(V(`\u2713 Genre reset to auto-detect \u2014 now: ${a?`${a} (${hu(a)})`:"unclassified (no playbook)"}.`)),console.log(y(" Restarting the agent so the loaded playbook matches\u2026")),{kind:"clear"}}return nR(r)?(Bm({...o,appType:r},n),console.log(V(`\u2713 Genre set to ${r} \u2014 ${hu(r)}.`)),console.log(y(" Restarting the agent so the playbook loads\u2026")),{kind:"clear"}):(console.log(j(`Unknown genre "${r}". Choose one of: ${qm.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}te();import{listRoadmap as ji,roadmapProgress as Gm,stampRoadmapDone as sR}from"document360-engine";function fu(e){let t=ji(e);if(t.length===0)return["No docs roadmap yet \u2014 the docs agent seeds .d360-writer/roadmap.md when it pins a structure,","and adds steps as the app changes. You can also write steps by hand (## [open] <step>), or ask:",'"propose the docs roadmap for this repo".'];let n=Gm(e),o=[`Docs roadmap \u2014 ${n.done} of ${n.total} step${n.total===1?"":"s"} done:`,""];for(let r of t){let s=r.status==="done"&&r.replacedBy?` \xB7 replaced by \u201C${r.replacedBy}\u201D`:"";o.push(` ${r.status==="done"?"\u2713":"\u25CB"} ${r.title}${r.run?` \xB7 ${r.run}`:""}${s}`)}return o.push(""),o.push(n.next?`Next: ${n.next.title}${n.next.run?` \u2014 ${n.next.run}`:""}`:"Campaign complete \u2014 the docs agent adds new steps as the app changes."),o.push("(Edit .d360-writer/roadmap.md freely \xB7 /roadmap done marks the next step you finished yourself \u2014 add words from a title to pick another.)"),t.some(r=>r.stepId)&&o.push('(d360-writer keeps the wording of its own steps current \u2014 add a "keep:" line to one to leave your version alone.)'),o}function Ii(e,t){let n=ji(e).filter(p=>p.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=p=>p.trim().toLowerCase(),s=n.find(p=>r(p.title)===r(o)),i=o?s?[s]:n.filter(p=>r(p.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:
|
|
407
407
|
${i.map(p=>` \u25CB ${p.title}`).join(`
|
|
408
408
|
`)}`};if(i.length===0)return{ok:!1,line:`No open step matches "${o}". Open steps:
|
|
409
409
|
${n.map(p=>` \u25CB ${p.title}`).join(`
|
|
410
|
-
`)}`};let a=i[0].title;
|
|
411
|
-
`):null}function
|
|
410
|
+
`)}`};let a=i[0].title;sR(e,a,{doneAt:new Date().toISOString()});let l=Gm(e)?.next;return{ok:!0,line:`\u2713 Marked done: ${a}${l?` \u2014 next up: ${l.title}${l.run?` (${l.run})`:""}`:" \u2014 that was the last step: campaign complete."}`}}function mu(e,t){let n=r=>r.trim().replace(/\s+/g," ").toLowerCase(),o=n(t);return o.startsWith("/")?ji(e).find(r=>r.status==="open"&&!!r.run&&n(r.run)===o)??null:null}function Vm(e,t){let n=mu(e,t);return n?[`Note: this command executes the open docs-roadmap step "${n.title}".`,`Close the loop IN THE SAME TURN the step's goal state is reached: call d360_roadmap_done with exactly the title "${n.title}", then tell the user it is marked done \u2014 including when you find the goal already holds ("no action needed" completes the STEP, not just the turn). Leave it open ONLY if the work is genuinely incomplete, and say exactly what remains.`].join(`
|
|
411
|
+
`):null}function Ym(e,t){let n=t.trim().toLowerCase();if(!n)return null;let o=ji(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:
|
|
412
412
|
${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(`
|
|
413
|
-
`):null}async function
|
|
414
|
-
\u2022 `),lead:{kind:"cmd",cmd:"/catch-up",reason:n},picker:null,follow:"Then /catch-up clears what\u2019s queued for the docs.",dependsOn:["discovery"]})}if(e.openComments>0){let n=e.openComments;t.push({key:"comments",bullet:`${n} reviewer comment${ye(n)} 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 ${n} reviewer comment${ye(n)} waiting on your articles.`})}if(e.behind>0){let n=e.behind;t.push({key:"audit",bullet:`${n} code change${ye(n)} since your last docs check`,lead:{kind:"cmd",cmd:"/audit",reason:"it shows what the latest code changes touch (or /audit --auto on to run it for you)"},picker:null,follow:`After that, /audit covers the ${n} newer commit${ye(n)}.`})}if(e.hasDocs&&e.pendingWrites>0){let n=e.pendingWrites;t.push({key:"write",bullet:`${n} planned article${ye(n)} still unwritten`,lead:{kind:"cmd",cmd:"/write",reason:"it finishes the articles already planned"},picker:null,follow:`Then /write finishes the ${n} planned article${ye(n)}.`,dependsOn:["genre","discovery","catchup","audit"]})}if(e.unreviewed>0){let n=e.unreviewed,o=
|
|
413
|
+
`):null}async function Km(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let r=Ii(n,e.slice(1).join(" ").trim());return console.log(r.ok?V(r.line):G(r.line)),{kind:"continue"}}let o=fu(n);console.log(z(o[0]??""));for(let r of o.slice(1))console.log(r.startsWith("(")?y(r):r);return{kind:"continue"}}var zm={help:ja,"?":ja,clear:Xd,exit:Ia,quit:Ia,init:Wa,mcp:Ws,push:li,publish:jh,audit:Sr,discover:Ih,scope:Oh,pull:Kh,resolve:Gh,convert:zh,write:hf,draft:wf,document:kf,resume:vf,rename:xf,profile:Cf,model:Tf,doctor:Ir,workspace:If,project:Lf,"allow-prod":Of,login:_f,logout:Mf,screenshot:async(e,t)=>{let n=br(e);return n.mode==="capture"?Ac(n.rest,t):n.mode==="annotate"?Ic(n.rest,t):n.mode==="verify"?Ff(n.rest,t):n.mode==="checklist"?No():oi(e,t)},capture:Ac,annotate:Ic,"capture-setup":No,devhints:ip,inbox:rm,"catch-up":cm,comments:gm,update:wm,reset:xm,lint:Xl,check:nf,"style-guide":Di,review:Wm,reorder:Um,structure:Im,genre:Ni,roadmap:Km,share:am};function Xm(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 iR}from"node:child_process";import{recordAnalyzedCommit as aR,resolveActiveProfile as lR}from"document360-engine";function cR(e){try{let t=iR("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 Yr(e,t){try{let n=cR(e);if(!n)return null;let o=lR(e,t);return aR(e,o.name,n)?n:null}catch{return null}}import{CONTENT_CAP_VERSION as uR,stampArticles as dR,articlesChangedSince as pR,docsRootOf as hR}from"document360-engine";function Li(e,t,n=""){let o=[];try{o=pR(e,t)}catch{return{changed:[],cta:null}}if(o.length===0)return{changed:[],cta:null};try{dR(e,o,{writtenCap:uR,reviewedCap:0,checkedCap:0})}catch{}let r=hR(e),s=p=>{let m=p.replace(/\\/g,"/");return m.startsWith(`${r}/`)?m.slice(r.length+1):m},i=St(o.map(s)),a=o.length,l=i?"/push":"/push --all";try{return{changed:o,cta:Tt(e,{text:`${n}${a} article${a===1?"":"s"} updated \u2014 ${l} saves ${a===1?"it":"them"} to Document360 as ${a===1?"a draft":"drafts"}.`,cmd:l},n,i)}}catch{return{changed:o,cta:null}}}sn();var fR="Or just tell me what to write or update.",mR='\u{1F4ED} No docs yet for this repo. Tell me "write the docs for this repo" and I\u2019ll read the code and draft a structure \u2014 or /audit to see what the docs should cover.';function ye(e){return e===1?"":"s"}function Oo(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 Qm(e,t){return e.length===t.length&&e.every((n,o)=>n===t[o])}function gR(e,t=150){let n=(e??"").replace(/\s+/g," ").trim();if(!n)return null;let o=/[.!?]\s+(?=["“'(A-Z])/.exec(n),r=o?n.slice(0,o.index+1):n;if(r.length<=t)return r;let s=r.slice(0,t),i=s.lastIndexOf(" ");return`${(i>t*.6?s.slice(0,i):s).replace(/[,;:]$/,"")}\u2026`}function Kr(e){return e.kind==="cmd"?`I\u2019d start with ${e.cmd} \u2014 ${e.reason}.`:e.kind==="answer"?e.options>=2?`Answer above (1\u2013${e.options}), or say what you want instead.`:"Answer above, or say what you want instead.":`Just tell me: \u201C${e.text}\u201D.`}var Oi={title:"What kind of product is this repo? (sets the doc-craft playbook \u2014 otherwise the docs stay generic)",options:[{cmd:"/genre web",desc:"web app / SaaS UI"},{cmd:"/genre cli",desc:"command-line tool"},{cmd:"/genre service",desc:"API / backend service"},{cmd:"/genre library",desc:"SDK / library"}]};function yR(e){let t=[];if(e.sunsetEnv){let n=e.sunsetEnv,o=n.replacementProfile?`/profile ${n.replacementProfile}`:`/profile add ${n.replacement}`;t.push({key:"environment",bullet:`this repo publishes to the ${n.name} environment, which is being retired (${n.replacement} is the current one)`,lead:{kind:"cmd",cmd:o,reason:n.replacementProfile?`it switches to your ${n.replacement} profile (then /login if it asks)`:`it creates a ${n.replacement} profile and switches to it (then /login picks the project)`},picker:null,follow:null,tone:"warn"})}if(e.devhints!=="current"&&e.builderStarted){let n=e.devhintsToVersion?`v${e.devhintsToVersion}`:"a newer version",o=e.devhints==="stale"&&e.devhintsCompletedVersion?` (your builder is on v${e.devhintsCompletedVersion})`:"";t.push({key:"devhints",bullet:`dev\u2194docs protocol moved to ${n}${o} \u2014 your docs aren\u2019t blocked`,lead:{kind:"cmd",cmd:"/devhints",reason:`one paste updates your builder to ${n}`},picker:null,follow:"Also run /devhints when you get a second \u2014 your builder\u2019s protocol is behind.",tone:"warn"})}if(e.genreUnknown&&t.push({key:"genre",bullet:"the doc genre isn\u2019t set \u2014 I can\u2019t load the right doc-craft playbook yet",lead:null,picker:Oi,follow:"Then pick the doc genre below (it sets the playbook I write with)."}),e.discovery&&e.discovery.status!=="confident"){let n=e.discovery.openQuestions;e.discovery.status==="pending"?t.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)."}):n>0?t.push({key:"discovery",bullet:`product discovery is waiting on ${n} answer${ye(n)} from your builder \u2014 nudge them`,lead:null,picker:null,follow:"Discovery is waiting on your builder\u2019s answers \u2014 nudge them, then /catch-up folds the answers in once they reply."}):e.discovery.answersPending===0&&t.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 n=e.directives>0&&e.pendingText?"it actions your directives and clears the builder\u2019s queue":e.directives>0?"it actions the directives you left":"it clears everything your builder queued",o=[];e.directives>0&&o.push(`${e.directives} owner directive${ye(e.directives)} waiting`);let r=e.discovery&&e.discovery.status!=="confident"?e.discovery.answersPending:0,s=r>0?` (${r} settle${r===1?"s":""} the product brief)`:"";e.pendingText&&o.push(`your builder left ${e.pendingText}${s}`),t.push({key:"catchup",bullet:o.join(`
|
|
414
|
+
\u2022 `),lead:{kind:"cmd",cmd:"/catch-up",reason:n},picker:null,follow:"Then /catch-up clears what\u2019s queued for the docs.",dependsOn:["discovery"]})}if(e.openComments>0){let n=e.openComments;t.push({key:"comments",bullet:`${n} reviewer comment${ye(n)} 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 ${n} reviewer comment${ye(n)} waiting on your articles.`})}if(e.behind>0){let n=e.behind;t.push({key:"audit",bullet:`${n} code change${ye(n)} since your last docs check`,lead:{kind:"cmd",cmd:"/audit",reason:"it shows what the latest code changes touch (or /audit --auto on to run it for you)"},picker:null,follow:`After that, /audit covers the ${n} newer commit${ye(n)}.`})}if(e.hasDocs&&e.pendingWrites>0){let n=e.pendingWrites;t.push({key:"write",bullet:`${n} planned article${ye(n)} still unwritten`,lead:{kind:"cmd",cmd:"/write",reason:"it finishes the articles already planned"},picker:null,follow:`Then /write finishes the ${n} planned article${ye(n)}.`,dependsOn:["genre","discovery","catchup","audit"]})}if(e.unreviewed>0){let n=e.unreviewed,o=be("/review","--blocked --fix",e.unreviewedScope);t.push({key:"review",bullet:`${n} article${ye(n)} ready to send to Document360 ${n===1?"has":"have"} never been editorially reviewed`,lead:{kind:"cmd",cmd:o,reason:"these were written by an AI \u2014 it reads each one and applies its fixes, and /push stays blocked until it has"},picker:null,follow:`Then ${o} reviews the ${n} unreviewed article${ye(n)} \u2014 /push is blocked until it has.`})}if(e.styleErrors>0){let n=e.styleErrors,o=be("/lint","--fix",e.styleErrorScope);t.push({key:"styleguide",bullet:`${n} article${ye(n)} ready to send to Document360 break${n===1?"s":""} house style rules that block publishing`,lead:{kind:"cmd",cmd:o,reason:"finding them costs nothing and one pass corrects them in place \u2014 /push stays blocked until it has"},picker:null,follow:`Then ${o} clears the style errors on ${n} article${ye(n)} \u2014 /push is blocked until it has.`,dependsOn:["review"]})}if(e.shotsToAnnotate>0){let n=e.shotsToAnnotate;t.push({key:"annotate",bullet:`${n} screenshot${ye(n)} ${n===1?"has":"have"} been taken but ${n===1?"is":"are"} not finished \u2014 the callouts aren't drawn on, so ${n===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 ${n} screenshot${ye(n)} already taken.`})}if(e.localAhead>0){let n=e.localAhead;t.push({key:"publish",bullet:`${n} article${ye(n)} changed locally \u2014 ready to send to Document360`,lead:{kind:"cmd",cmd:"/push",reason:`it saves your ${n} local edit${ye(n)} to Document360 as drafts`},picker:null,follow:`Then /push saves your ${n} local edit${ye(n)} to Document360.`,dependsOn:["discovery","audit","annotate"],blockedBy:["review","styleguide"]})}if(e.conflicts>0){let n=e.conflicts;t.push({key:"resolve",bullet:`${n} article${ye(n)} changed both here and on Document360 (conflicts) \u2014 /push skips these`,lead:{kind:"cmd",cmd:"/resolve",reason:"it walks each conflict \u2014 keep yours, take the portal's, or skip"},picker:null,follow:`Then /resolve settles the ${n} conflict${ye(n)} (keep yours / take the portal's / skip).`})}if(e.draftAhead>0){let n=e.draftAhead;t.push({key:"golive",bullet:`${n} article${ye(n)} ${n===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 ${n} draft${ye(n)} live to your readers \u2014 it lists them and asks first`},picker:null,follow:`Then /publish takes the ${n} draft${ye(n)} live \u2014 until it does, readers see the previous version.`,blockedBy:["review","styleguide"]})}if(e.hasDocs&&e.roadmap?.next){let n=e.roadmap,o=n.next,r=o.run?null:gR(o.body),s=`docs campaign: ${n.done} of ${n.total} step${ye(n.total)} done`;t.push({key:"roadmap",bullet:`${s} \u2014 next: ${o.title}${r?`
|
|
415
415
|
\u2022 ${r}`:""}`,lead:o.run?{kind:"cmd",cmd:o.run,reason:"it\u2019s the next step of your docs campaign"}:{kind:"prompt",text:o.title,reason:"it\u2019s the next step of your docs campaign"},picker:null,follow:`Then the campaign continues: ${o.title} (/roadmap shows all ${n.total} steps).`,dependsOn:["genre","discovery","audit"],rowBullet:`${s} \u2014 this is next${r?`
|
|
416
416
|
\u2022 ${r}`:""}`})}if(e.handoff){let n=Math.max(e.handoff.unpushed,e.handoff.uncommitted>0?1:0),o=e.handoff.unpushed;n>0&&e.handoff.pushConsent==="unconfirmed"?t.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(`
|
|
417
|
-
`),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}):o>0&&t.push({key:"share",bullet:`\u26A0 ${o} docs change set${ye(o)} 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 n=e.uncommittedDocs;t.push({key:"commit",bullet:`\u26A0 ${n} uncommitted change${ye(n)} under .d360-writer/ \u2014 tell your coding agent: "commit d360-writer's work"`,lead:null,picker:null,follow:null})}return t}function
|
|
418
|
-
\u2022 `);if($&&w.lead){let S=T.replace(/^→\s+/,"");return[` ${$}. ${
|
|
419
|
-
`)}let
|
|
420
|
-
`)];return a.length&&m.push(a.join(" ")),m.push(
|
|
421
|
-
|
|
422
|
-
`),menu:s.map(w=>
|
|
423
|
-
|
|
424
|
-
${p}`:p;if(!e.ready)return{kind:"idle"};if(e.pendingAnswer)return{kind:"recommend",rec:{note: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=
|
|
425
|
-
`)){let o=n.trimEnd();if(/^\s*(```|~~~)/.test(o)){t=!t;continue}if(t)continue;let r=/^#\s+(\S.*)$/.exec(o);if(r)return
|
|
426
|
-
`).length;return{verb:"Draft",title:
|
|
427
|
-
`)),category:l,note:T}}function
|
|
428
|
-
`);if(e==="Read"){let o=n.length,r=
|
|
429
|
-
`));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
|
|
430
|
-
`).trimEnd();if(n&&
|
|
431
|
-
`);return{lines:s.slice(0,t).map(i=>fn(i,
|
|
432
|
-
`))console.log(i(` ${a}`));s.rec.picker&&console.log(z(` Pick one: ${s.rec.picker.options.map(a=>a.cmd).join(" \xB7 ")}`))}}catch{}}console.log(y(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function
|
|
433
|
-
|
|
434
|
-
`);let l=[i.category,i.note].filter(m=>!!m).map(m
|
|
435
|
-
|
|
436
|
-
`),console.log(`${
|
|
437
|
-
`);let i=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(y(` (${wr(i)}\u2192${wr(e.outputTokens)} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(
|
|
438
|
-
`),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}function
|
|
439
|
-
`),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){
|
|
440
|
-
`)}var
|
|
441
|
-
\u2190/\u2192 or tab switch \xB7 1-5 jump${C
|
|
442
|
-
`)){let i=s.trim().replace(
|
|
443
|
-
`)}function
|
|
444
|
-
`)||e.length>200}function
|
|
445
|
-
`).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function
|
|
446
|
-
`)){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
|
|
417
|
+
`),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}):o>0&&t.push({key:"share",bullet:`\u26A0 ${o} docs change set${ye(o)} 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 n=e.uncommittedDocs;t.push({key:"commit",bullet:`\u26A0 ${n} uncommitted change${ye(n)} under .d360-writer/ \u2014 tell your coding agent: "commit d360-writer's work"`,lead:null,picker:null,follow:null})}return t}function Jm(e){return e.find(t=>t.lead||t.picker)??null}function wR(e){return e.kind==="cmd"?e.cmd:e.kind==="prompt"?`\u201C${e.text}\u201D`:""}function kR(e){return e.kind==="cmd"?e.cmd:e.kind==="prompt"?e.text:""}function bR(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 gu(e,t,n){let o=Jm(t),r=o?.picker?[]:t.filter(w=>w.lead),s=r.length>=2?r:[],i=new Map(s.map((w,$)=>[w.key,$+1])),a=[];o?.lead?a.push(Kr(o.lead)):o?.picker&&a.push("Pick the genre below \u2014 one keypress, and it shapes everything I write.");for(let w of t.filter($=>$!==o&&!$.lead).slice(0,2))w.follow&&a.push(w.follow);s.length>=2&&n&&a.push(`Press 1\u2013${s.length} to pick a different one \u2014 the number fills the box, enter runs it.`);let l=a.join(" "),p=t.filter(w=>w.bullet).map(w=>{let $=i.get(w.key),[T="",...R]=($&&w.lead?.kind==="prompt"&&w.rowBullet?w.rowBullet:w.bullet).split(`
|
|
418
|
+
\u2022 `);if($&&w.lead){let S=T.replace(/^→\s+/,"");return[` ${$}. ${wR(w.lead)} \u2014 ${S}${bR(w,i,$)}`,...R.map(I=>` ${I}`)].join(`
|
|
419
|
+
`)}let C=w.lead?.kind==="cmd"?w.lead.cmd:null;return` \u2022 ${w.bullet}${C&&!l.includes(C)?` \u2014 ${C}`:""}`}),m=[[e,...p].join(`
|
|
420
|
+
`)];return a.length&&m.push(a.join(" ")),m.push(fR),{note:m.join(`
|
|
421
|
+
|
|
422
|
+
`),menu:s.map(w=>kR(w.lead))}}function zr(e,t){let n=t?.pickable===!0,o=p=>t?.header?`${t.header}
|
|
423
|
+
|
|
424
|
+
${p}`:p;if(!e.ready)return{kind:"idle"};if(e.pendingAnswer)return{kind:"recommend",rec:{note: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=yR(e);if(!e.hasDocs){let p=Jm(r);if(p&&(p.lead?.kind==="cmd"||p.picker)){let m=gu(t?.header??"\u{1F4ED} No docs yet for this repo \u2014 here\u2019s where things stand:",r,n);return{kind:"recommend",rec:{note:m.note,tone:p.tone??"info",lead:p.lead,picker:p.picker,menu:m.menu}}}return{kind:"recommend",rec:{note:o(mR),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 p=e.roadmap&&!e.roadmap.next?` Docs campaign complete \u2014 all ${e.roadmap.total} step${ye(e.roadmap.total)} done (/roadmap).`:"";return{kind:"recommend",rec:{note:o(`Welcome back. Your ${e.tracked} tracked article${ye(e.tracked)} for \u201C${e.profileName}\u201D are all in sync \u2014 /audit re-checks the code, /pull brings down portal edits.${p}`),tone:"info",lead:null,picker:null,menu:[]}}}let s=r.filter(p=>p.lead||p.picker),i=s[0]??null;if(!i){let p=gu(t?.header??"Welcome back \u2014 where your docs stand:",r,n);return{kind:"recommend",rec:{note:p.note,tone:"info",lead:null,picker:null,menu:p.menu}}}if((i.key==="audit"||s[1]?.key==="audit")&&e.behind>0&&e.autoAudit&&e.allowAutoAudit)return{kind:"autoAudit",note:o(`\u{1F4CB} ${e.behind} code change${ye(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`)};let l=gu(t?.header??"Welcome back \u2014 where your docs stand:",r,n);return{kind:"recommend",rec:{note:l.note,tone:i.tone??"info",lead:i.lead,picker:i.picker,menu:l.menu}}}import{existsSync as _i,readdirSync as ku}from"node:fs";import{spawnSync as $R}from"node:child_process";import{join as Mi}from"node:path";import{readProjectConfig as yu,resolveActiveProfile as eg,loadTokens as vR,isExpired as xR,loadProfileMap as tg,localAheadPaths as RR,loadKnownConflicts as CR,draftPendingPaths as SR,loadOpenCommentCount as PR,readDocsPlan as TR,devHintsGuidePath as AR,DEFAULT_DOCS_DIR as wu,roadmapProgress as ER,listRoadmap as DR,readProductBriefState as NR,readDiscoveryQueue as jR,reconcileCommitRequest as IR,reconcileTestidRequest as LR,snapshotHandoff as OR,shareExplainedPath as _R,unannotatedShotIds as MR,resolveOutputDir as FR,DEFAULT_OUTPUT_DIR as WR}from"document360-engine";sn();function Zm(e){try{return ku(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function bu(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>Zm(Mi(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&Zm(Mi(e,o)))}function $u(e,t){try{let n=yu(e);if(!n)return!1;let o=eg(e,t),r=tg(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=Mi(e,(n.docsDir??wu).replace(/\/+$/,""));return!!(_i(s)&&ku(s).length>0||_i(AR(e)))}catch{return!1}}function Xr(e,t,n){try{let o=yu(e);if(!o)return null;let r=eg(e,t),s=vR(r.name),i=!!s&&(!xR(s)||!!s.refreshToken),a=$u(e,t)||!bu(e,o.authoritativeSourceFiles),l=tg(e,r.name),p=l?Object.keys(l.articles).length:0,m=Mi(e,(o.docsDir??wu).replace(/\/+$/,"")),w=!1;try{w=_i(m)&&ku(m).length>0}catch{}let $=0;if(l?.lastAnalyzedCommit)try{let Pe=$R("git",["rev-list","--count",`${l.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});Pe.status===0&&($=parseInt((Pe.stdout||"").trim(),10)||0)}catch{}let T=0;try{let Pe=TR(e);if(Pe.length>0){let qt=(o.docsDir??wu).replace(/\/+$/,"");T=ec(e,qt,Pe.map(ns=>ns.path)).length}}catch{}let R=Wn(e),C=Wc({...R,directives:0}),S=RR(e,t),E=new Set(CR(e,r.name)),I=S.filter(Pe=>E.has(Pe)).length,L=S.length-I,Y=S.filter(Pe=>!E.has(Pe)),ce=Cr(e,Y),ue=ce.length,ie=St(ce),he=0,de;try{let Pe=Dh(e,Y);he=Pe.length,de=St(Pe)}catch{}let ke=0;try{let Pe=FR(e,yu(e)?.outputDir??WR);ke=MR(Pe).length}catch{}let ae=new Set(S),X=SR(e,t).filter(Pe=>!ae.has(Pe)).length,Ce=PR(e,r.name),Se=kt(e),Fe=ER(e),Bt=OR(e,o),yn=IR(e,new Date().toISOString(),{supersededByHandoff:Bt!==null});LR(e,new Date().toISOString());let $t=nn(e,t),ft=$t?{name:$t.name,replacement:$t.replacement,replacementProfile:$t.replacementProfile}:null,Gn=NR(e),st=jR(e),Ht=Gn?{status:Gn.status,openQuestions:st.openQuestions,answersPending:st.answersPending}:null;return!Ht&&w&&DR(e).some(qt=>qt.status==="open"&&(qt.run??"").trim()==="/discover")&&(Ht={status:"pending",openQuestions:0,answersPending:0}),{ready:i&&a&&!n.claudeMissing,hasDocs:w,tracked:p,pendingText:C,directives:R.directives,behind:$,pendingWrites:T,localAhead:L,unreviewed:ue,unreviewedScope:ie,styleErrors:he,shotsToAnnotate:ke,styleErrorScope:de,draftAhead:X,conflicts:I,openComments:Ce,autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:Se.status,devhintsCompletedVersion:Se.completedVersion,devhintsToVersion:Te,builderStarted:Ft(e),genreUnknown:n.genreUnknown,pendingAnswer:n.pendingAnswer??null,roadmap:Fe,discovery:Ht,uncommittedDocs:yn.dirty.length,handoff:Bt,shareExplained:_i(_R(e)),sunsetEnv:ft}}catch{return null}}te();import{existsSync as UR,readFileSync as BR}from"node:fs";import{isAbsolute as HR,join as qR}from"node:path";import{DEFAULT_DOCS_DIR as GR,findPathByArticleId as VR,isArticleDocPath as YR,loadProfileMap as KR,readProjectConfig as zR,resolveActiveProfile as XR}from"document360-engine";var QR=70;function JR(e,t){return{docsRoot:()=>(zR(e)?.docsDir??GR).replace(/\\/g,"/").replace(/\/+$/,""),read:n=>{try{let o=HR(n)?n:qR(e,n);return UR(o)?BR(o,"utf8"):null}catch{return null}},pathForArticleId:n=>{try{let o=KR(e,XR(e,t).name);return o?VR(o,n):null}catch{return null}}}}var Qr=(e,t=QR)=>{let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"};function Jr(e){if(!e)return null;let t=!1;for(let n of e.split(`
|
|
425
|
+
`)){let o=n.trimEnd();if(/^\s*(```|~~~)/.test(o)){t=!t;continue}if(t)continue;let r=/^#\s+(\S.*)$/.exec(o);if(r)return Qr(r[1])}return null}var ZR=new Set(["a","an","and","as","at","but","by","for","in","of","on","or","the","to","vs","with"]),eC=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 ng(e,t,n){let o=e.toLowerCase();return eC.has(o)?e.toUpperCase():!t&&ZR.has(o)?o:!t&&!n?e:e.charAt(0).toUpperCase()+e.slice(1)}var og=e=>e.replace(/^\d+[-_.]/,"").split(/[-_]/).filter(Boolean);function tC(e){let t=og(e);return t.length===0?e:t.map((n,o)=>ng(n,o===0,!0)).join(" ")}function rg(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:tC(n[n.length-2])}function sg(e){let t=e.replace(/\\/g,"/").split("/").pop()??e,n=og(t.replace(/\.(md|markdown)$/i,""));return n.length===0?t:n.map((o,r)=>ng(o,r===0,!1)).join(" ")}var pt=e=>typeof e=="string"&&e?e:null,nC=e=>typeof e=="string"&&e.length>=8?`id ${e.slice(0,8)}\u2026`:null;function oC(e,t){let n=i=>i.replace(/\\/g,"/").replace(/\/+$/,""),o=e.replace(/\\/g,"/"),r=`${n(t)}/`;return(process.platform==="win32"?o.toLowerCase().startsWith(r.toLowerCase()):o.startsWith(r))?o.slice(r.length):o}function rC(e,t){let n=ut(e,t,200);return n?`+${n.added} \u2212${n.removed}`:"no change"}var sC=new Set(["Edit","MultiEdit","Write"]);function iC(e,t,n,o){if(!sC.has(e))return null;let r=pt(t.file_path);if(!r)return null;let s=oC(r,n),i=o.docsRoot();if(!(s===i||s.startsWith(`${i}/`)))return null;let a=s.slice(i.length+1);if(!a||!YR(a))return null;let l=rg(a),p=o.read(s),m=R=>Jr(R)??Jr(p)??sg(a);if(e==="Write"){let R=pt(t.content)??"",C=m(R);if(p===null){let S=R.replace(/\n$/,"").split(`
|
|
426
|
+
`).length;return{verb:"Draft",title:C,category:l,note:`new, ${S} lines`}}return{verb:"Rewrite",title:C,category:l,note:rC(p,R)}}let w=Array.isArray(t.edits)?t.edits.map(R=>({from:pt(R.old_string)??"",to:pt(R.new_string)??""})):[{from:pt(t.old_string)??"",to:pt(t.new_string)??""}],$=w.reduce((R,C)=>{let S=ut(C.from,C.to,200);return S?{added:R.added+S.added,removed:R.removed+S.removed}:R},{added:0,removed:0}),T=$.added===0&&$.removed===0?"no change":`+${$.added} \u2212${$.removed}`;return{verb:"Update",title:m(w.map(R=>R.to).join(`
|
|
427
|
+
`)),category:l,note:T}}function aC(e,t,n){let o=()=>{let r=pt(t.article_id),s=r?n.pathForArticleId(r):null;return(s?Jr(n.read(s)):null)??(s?sg(s):nC(r)??"article")};switch(e){case"d360_create_article":{let r=pt(t.title);return r?{verb:"Create",title:Qr(r),category:rg(t.local_path),note:"Document360 draft"}:null}case"d360_update_article":return{verb:"Update",title:pt(t.title)?Qr(pt(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=pt(t.name);return r?{verb:"Create",title:Qr(r),category:null,note:"Document360 category"}:null}case"d360_upload_drive_file":{let r=pt(t.file_path);if(!r)return null;let s=r.replace(/\\/g,"/").split("/").pop()??r;return{verb:"Upload",title:Qr(s),category:null,note:"Document360 Drive",keepResult:!0}}default:return null}}function Fi(e,t,n,o,r=JR(n,o)){try{let s="mcp__document360__";return e.startsWith(s)?aC(e.slice(s.length),t,r):iC(e,t,n,r)}catch{return null}}var lC={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"},ag=160,vu=200,lg=40;function fn(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function ig(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}: ${fn(typeof r=="string"?r:JSON.stringify(r),lg)}`);return t.length>4&&n.push("\u2026"),fn(n.join(", "),ag)}var cC=new Set(["file_path","notebook_path"]);function uC(e,t){if(!t)return e;let n=i=>i.replace(/\\/g,"/").replace(/\/+$/,""),o=n(e),r=`${n(t)}/`;return(process.platform==="win32"?o.toLowerCase().startsWith(r.toLowerCase()):o.startsWith(r))?o.slice(r.length):e}var cg=e=>typeof e=="string"&&e?e:null;function dC(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});return e==="d360_sync_status"?n("Check sync status",null):null}function Wi(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=dC(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:ig(t)}}let o=lC[e],r=o?t[o]:void 0;if(typeof r=="string"&&r){let s=o&&cC.has(o)?uC(r,n):r;return{title:e,sep:"",arg:fn(s,ag)}}return{title:e,sep:"",arg:ig(t)}}function pC(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 hC(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(pC).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>fn(r,vu))]}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}: ${fn(String(r),lg)}`);return n.length>0?[fn(n.join(" \xB7 "),vu)]:null}return null}function fC(e){let t=cg(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function mC(e,t,n){switch(e){case"d360_create_article":{let o=fC(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=cg(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 ${fn(o[0],120)}`:""}`]}default:return null}}var ug=new Set(["Edit","Write","MultiEdit","NotebookEdit"]);function gC(e){return e.replace(/^\s*\d+\t/,"")}function yC(e,t){if(ug.has(e))return[];let n=t.split(`
|
|
428
|
+
`);if(e==="Read"){let o=n.length,r=Jr(n.map(gC).join(`
|
|
429
|
+
`));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 Ui(e,t=4,n,o){let r=e.replace(/\r\n/g,`
|
|
430
|
+
`).trimEnd();if(n&&ug.has(n))return{lines:[],hidden:0};if(!r)return{lines:["(no output)"],hidden:0};if(n&&!n.startsWith("mcp__")){let i=yC(n,r);if(i)return{lines:i,hidden:0}}if(n?.startsWith("mcp__document360__")){let i=mC(n.slice(18),o,r);if(i)return{lines:i,hidden:0}}let s=hC(r)??r.split(`
|
|
431
|
+
`);return{lines:s.slice(0,t).map(i=>fn(i,vu)),hidden:Math.max(0,s.length-t)}}function Bi(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function Hi(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 dg(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 qi(e){return dg(e,"url")}function Gi(e){return dg(e,"preview_url")}var gg=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/,Ru=null;function hg(){return Ru===null&&(Ru=PC().verboseTranscript===!0),Ru}function UC(e,t,n,o){if(gg.test(e))try{let r=mg(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,i=Hi(t,n),a=qi(n);e.endsWith("publish_article")&&a&&console.log(z(` \u2B95 Live: ${a}`));let l=Gi(n);l?console.log(z(` \u2B95 Preview: ${l}`)):i&&s&&console.log(z(` \u2B95 Preview: ${Bi(r.connection.portalUrl,s,i,r.project.languageCode??"en")}`))}catch{}}async function yg(e=process.cwd(),t="auto",n,o){let r=kC(t);r.kind==="none"&&(console.error(""),console.error(j("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${z("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${z('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${z("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${z("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),BC(e,n),r.kind==="subscription"&&(r.stored?console.log(y(" Using your Claude subscription (no API key set).")):console.log(y(" No API key or stored Claude Code login found \u2014 trying your Claude session anyway.")),console.log(""));let s=!1,i=xu({cwd:e,profileName:n,allowProdWrites:s}),a={uuid:null,firstPrompt:null,titleFired:!1},l=wC({input:process.stdin,output:process.stdout}),p=[],m=null,w=!1;l.on("line",R=>{if(m){let C=m;m=null,C(R)}else p.push(R)}),l.on("close",()=>{if(w=!0,m){let R=m;m=null,R(null)}});function $(){return p.length>0?Promise.resolve(p.shift()):w?Promise.resolve(null):(process.stdout.write(z("> ")),new Promise(R=>{m=R}))}let T={cwd:e,version:o,profileName:n,allowProdWrites:()=>s,restartAgent:()=>{i.close(),i=xu({cwd:e,profileName:n,allowProdWrites:s}),a={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>a.uuid,setPendingName:R=>{a.pendingName=R},setModel:async R=>i.setModel(R),withPausedInput:async R=>{l.pause();try{return await R()}finally{l.resume()}}};try{for(;;){let R=await $();if(R===null)break;let C=R.trim();if(C){if(C.startsWith("/")){let S=Xm(C);if(!S)continue;let E=zm[S.name];if(!E){console.log(j(`Unknown command: /${S.name}`)),console.log(y("Type /help for the list."));continue}let I=await E(S.args,T);if(I.kind==="exit")break;if(I.kind==="clear"){T.restartAgent();continue}if(I.kind==="allow-prod"){s=!0,T.restartAgent(),console.log(V("\u2713 Production writes authorized for this session.")),console.log("");continue}if(I.kind==="resume"){i.close(),i=xu({cwd:e,resume:I.uuid,profileName:n,allowProdWrites:s});let L=bC(I.uuid);a={uuid:I.uuid,firstPrompt:L?.firstPrompt??null,titleFired:!0},fg(I.uuid),console.log(V(`\u2713 Resumed "${I.name}"`)),console.log("");continue}if(I.kind==="forward-to-agent"){a.firstPrompt||(a.firstPrompt=I.display??I.prompt);let L=I.display??"",Y=L.trim().split(/\s+/),ce=Qh(L),ue=ce?_C(e,Jh(L)):[],ie=Y[0]==="/screenshot"&&(Y[1]==="verify"||Y[1]==="review"),he=ie?Y[2]&&!Y[2].startsWith("--")?[Y[2]]:Lr(Le(e)):[],ke=Y[0]==="/catch-up"&&!ce?OC(e):null;if(await Cu(i,I.prompt,r,a,e,n),ce)try{LC(e,ue,Qe(ce))}catch{}if(ke){let ae=Li(e,ke);ae.cta&&console.log(y(ae.cta.text))}if(Y[0]==="/audit"&&!Y.includes("--auto")&&Yr(e,n),ie&&he.length>0)try{for(let ae of Eo(e,he))console.log(ae)}catch{}if(Y[0]==="/push"){let ae=await So(e,n);ae&&console.log(y(ae))}if((Y[0]==="/catch-up"||Y[0]==="/document")&&(Y.includes("--push")||Y.includes("--publish")))try{let ae=await WC({cwd:e,profileName:n}),{clean:X,conflicts:Ce}=Ln(ae.entries);X.length===0?console.log(y("Nothing new to push \u2014 everything is already up to date on Document360.")):await Pt(T,X.map(Se=>Se.path),Ce.length,{skipReview:Y.includes(ct)})}catch(ae){console.log(G(`Couldn't check what to push (${ae.message}) \u2014 your drafts are saved; run /push when ready.`))}}else I.kind==="continue"&&I.ownNext||HC(e,n);continue}if(DC(C)){let S=NC(C);if(S){try{jC(e,{title:S,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}a.firstPrompt||(a.firstPrompt=C),await Cu(i,`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${S}". 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 "${S}" and the article path(s) you wrote.`,r,a,e,n);continue}}a.firstPrompt||(a.firstPrompt=C),await Cu(i,C,r,a,e,n)}}}finally{i.close(),l.close()}}function BC(e,t){console.log(""),console.log(pr("document360-writer")),console.log(y(` cwd: ${e}`));let n=CC(e);if(console.log(y(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(qC(e,t)),!SC(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(Ls(e),!Ft(e))for(let r of Os(e))console.log(G(` ${r}`))}catch{}try{let r=TC(e);r.persisted&&r.appType?console.log(y(` \u2713 Detected a ${r.appType} app \u2014 enabled the ${r.appType}-doc-playbook (change with /genre).`)):r.source==="unknown"&&(o=!0)}catch{}try{let r=IC(e);for(let s of Ds(r.applied))console.log(G(` ${s}`));if(r.reopenedForRedaction)for(let s of Ns(r.reopenedForRedaction).split(/\r?\n/))console.log(G(` ${s}`))}catch{}try{let r=Xr(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:o}),s=r?zr(r,{pickable:!1}):null;if(s?.kind==="recommend"&&s.rec.note){let i=s.rec.tone==="warn"?G:y;for(let a of Xa(s.rec.note).split(`
|
|
432
|
+
`))console.log(i(` ${a}`));s.rec.picker&&console.log(z(` Pick one: ${s.rec.picker.options.map(a=>a.cmd).join(" \xB7 ")}`))}}catch{}}console.log(y(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function HC(e,t){try{let n=Xr(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:!1}),o=n?zr(n):null;o?.kind==="recommend"&&o.rec.lead&&console.log(y(` Next: ${Kr(o.rec.lead)}`))}catch{}}function qC(e,t){try{let n=mg(e,t),o=n.production?G(" \u26A0 PRODUCTION"):"",r=EC(n.name);if(!r)return y(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...pg(r.idToken)??{},...pg(r.accessToken)??{}},i=s.email??s.preferred_username??"signed in";return AC(r)&&!r.refreshToken?G(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):y(` Document360: ${i} \xB7 profile "${n.name}"${o}`)}catch(n){return y(` Document360: ${n.message.split(".")[0]}`)}}function GC(){console.error(""),console.error(`Sign in with your Claude subscription: run ${z("claude")} once, then retry.`),console.error(` (No Claude Code? ${z("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${z("https://console.anthropic.com/settings/keys")}`)}function VC(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;xC({uuid:t,name:r??vC(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function YC(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||RC(o,t).then(r=>{r&&$C(n,r)}).catch(()=>{})}async function Cu(e,t,n,o,r,s){let i=new Map,a=!1;for await(let l of e.send(t))l.type==="tool"&&gg.test(l.name)&&(a=!0),KC(l,o,r,n,i,s);if(a)try{let l=FC(await MC({cwd:r,profileName:s}));l&&console.log(l.startsWith("\u26A0")?G(l):l)}catch{}}function KC(e,t,n,o,r,s){switch(e.type){case"session":t.uuid||VC(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let i=hg()?null:Fi(e.name,e.input,n,s);if(i){process.stdout.write(`
|
|
433
|
+
|
|
434
|
+
`);let l=[i.category,i.note].filter(m=>!!m).map(m=>$e(` \xB7 ${m}`)),p=i.loud?$e(" \xB7 ")+Ge(G(i.loud)):"";console.log(`${V("\u25CF")} ${z(Ge(za(i.verb)))}${Ge(i.title)}${l.join("")}${p}`),r.set(e.id,{name:e.name,input:e.input,doc:!0,keepResult:i.keepResult});break}let a=Wi(e.name,e.input,process.cwd());a&&(process.stdout.write(`
|
|
435
|
+
|
|
436
|
+
`),console.log(`${$e("\u25CF")} ${a.title}${a.arg!==null?$e(`${a.sep}(${a.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let i=ut(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!i)break;let a=l=>l===1?"":"s";console.log($e(` \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(y(` \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}:Ui(e.output,4,e.isError||hg()?void 0:i.name,i.input),p=e.isError?j:$e;l.lines.forEach((m,w)=>console.log(p((w===0?" \u23BF ":" ")+m))),l.hidden>0&&console.log(y(` \u2026 +${l.hidden} lines`)),e.isError||UC(i.name,i.input,e.output,n);break}case"result":{process.stdout.write(`
|
|
437
|
+
`);let i=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(y(` (${wr(i)}\u2192${wr(e.outputTokens)} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(fg(t.uuid),t.titleFired||YC(t,n));break}case"error":console.error(""),e.kind==="limit"?console.log(G(`\u23F3 ${e.message}`)):console.error(j(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&GC();break}}import{render as TP}from"ink";import{resolveAuth as AP}from"document360-engine";import{useCallback as Z,useEffect as rt,useMemo as Lu,useRef as se,useState as ne}from"react";import{Box as xe,Text as q,useApp as kS,useInput as bS,useStdout as $S}from"ink";import{existsSync as Fo,readFileSync as ea,readdirSync as vS,writeFileSync as xS}from"node:fs";import{basename as ts,dirname as RS,isAbsolute as CS,join as Ou}from"node:path";import{createSession as ry,classifyClaudeAuth as Hu,CLAUDE_CODE_SETUP_HINT as SS,loginPkce as PS,toStoredTokens as TS,saveTokens as AS,getAccessToken as ES,resolveActiveProfile as ht,resolveProjectId as DS,getArticle as NS,decodeJwtClaims as Go,isExpired as gn,loadTokens as qn,clearTokens as jS,clearProfileProject as IS,setTitle as LS,slugify as OS,touchSession as _u,upsertSession as _S,generateTitle as sy,findByName as MS,listSessions as FS,renameSession as WS,suggestNextAction as US,readProjectConfig as ge,writeProjectConfig as iy,readUserConfig as ay,writeUserConfig as BS,resolveAndPersistAppType as HS,detectAppType as ly,resolveModelSetting as qu,loadProfileMap as cy,applyPull as ta,computeSyncStatus as na,lintDocs as oa,compareRemoteSources as qS,planPull as uy,establishBaselines as GS,rebaselineServerMeta as VS,inventoryRepo as YS,knownEnvironments as KS,currentEnvironments as dy,sunsetEnvironment as py,resolveEnvironment as zS,planPartitions as Mu,partitionEvenly as XS,screenshotPlaceholderIds as QS,trackedArticlePaths as JS,runPartitioned as Wo,partitionCoverage as hy,estimateBulkCost as fy,resolveModelForOperation as Uo,readDocsPlan as my,checkForUpdate as ZS,detectInstallKind as eP,isSelfUpdatable as tP,devHintsGuidePath as gy,toolFeedbackPath as yy,reconcileToolFeedback as nP,reconcileUpgradeActions as oP,stampArticles as Bo,snapshotArticles as rP,listArticleFiles as sP,CONTENT_CAP_VERSION as iP,ENGINE_VERSION as Cy,DEFAULT_DOCS_DIR as Gu,setProfileProject as aP,writeCrashLog as lP,applyStructureOrder as Fu,orderSyncLine as Wu,applyRelatedArticles as wy,relatedSyncLine as ky,reconcileDocsGit as cP,shareExplainedPath as uP,ensureDir as dP}from"document360-engine";$o();sn();import{spawn as wg}from"node:child_process";function zC(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function XC(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?wg([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):wg(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 Su(e){for(let[t,n]of zC())if(await XC(t,n,e))return!0;return!1}var kg=/\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 QC(e){let t=e.replace(/\s+$/,"").split(`
|
|
438
|
+
`),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}function bg(e){let t=e.trimEnd();if(!t)return null;let n=QC(t);return n>=2?{options:n}:/\?[\s*_"')\]]*$/.test(t)||kg.test(t)?{options:0}:null}function Pu(e,t){if(t.closed)return e;let n=e.split(`
|
|
439
|
+
`),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){kg.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(`
|
|
440
|
+
`)}var JC={la:"local","l all":"local","local all":"local",pa:"portal","p all":"portal","portal all":"portal",sa:"skip","s all":"skip","skip all":"skip"},ZC={L:"local",P:"portal",S:"skip"},eS={ya:"write","y all":"write","yes all":"write",na:"skip","n all":"skip","no all":"skip"},tS={Y:"write",N:"skip"};function $g(e,t,n){let o=e.trim(),r=o.toLowerCase().replace(/\s+/g," ");return t[r]??(o.length===1?n[o]??null:null)}function vg(e){return $g(e,JC,ZC)}function xg(e){return $g(e,eS,tS)}function Tu(e,t){let n=t?.max??12,o=t?.chrome??8;return Math.max(3,Math.min(n,(e??24)-o))}function Vi(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 Rg(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}}}import{existsSync as nS,mkdirSync as oS,readFileSync as rS,writeFileSync as sS}from"node:fs";import{join as Cg}from"node:path";import{writerDir as iS}from"document360-engine";function Sg(e){return Cg(iS(e),".sessions")}function Pg(e,t){return Cg(Sg(e),`${t}.json`)}function Tg(e,t,n){try{oS(Sg(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");sS(Pg(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function Au(e,t){try{let n=Pg(e,t);if(!nS(n))return[];let o=JSON.parse(rS(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var aS=e=>`\x1B]0;${e}\x07`,lS=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function Ag(e){process.stdout.isTTY&&process.stdout.write(e)}function _o(e){Ag(aS(e))}function Yi(e){Ag(lS(e))}var Ki=["\xB7 "," \xB7"],zi="\u{1F7E3}";bi();var Eg=()=>({fingerprint:null,counts:null,settled:0,spokenBaseline:null,lastSpokeAt:null,awaySince:null}),cS={hints:0,requests:0,answers:0,directives:0};function Eu(e,t){let n=e??cS;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 Xi=e=>e.hints===0&&e.requests===0&&e.answers===0&&e.directives===0,Dg=e=>e.hints+e.requests+e.answers+e.directives,Du=(e,t)=>e-t>=6e5;function Ng(e){let{now:t,lastInputAt:n,fingerprint:o,counts:r,occupied:s,prev:i}=e,a=Du(t,n),p=i.fingerprint!==null&&i.fingerprint!==o?0:i.settled+1,m={...i,fingerprint:o,counts:r,settled:p,awaySince:a?i.awaySince??t:null,spokenBaseline:i.spokenBaseline??r};if(a){let $=Eu(m.spokenBaseline,r);return{memory:m,speak:null,waiting:Xi($)?null:$}}if(s)return{memory:m,speak:null,waiting:null};if(p<2)return{memory:m,speak:null,waiting:null};let w=Eu(i.spokenBaseline,r);return Xi(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:p},speak:w,waiting:null}}function jg(e,t,n){if(e.awaySince===null)return{kind:"none",memory:e};let o=t-e.awaySince,r=Eu(e.spokenBaseline,n),s={...e,awaySince:null,counts:n,spokenBaseline:n,lastSpokeAt:Xi(r)?e.lastSpokeAt:t};return Xi(r)?{kind:"none",memory:s}:{kind:o>=36e5?"briefing":"delta",memory:s,delta:r,awayMs:o}}function Zr(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 Nu(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 Ig(e){return`\u{1F4E5} ${Zr(e)} just arrived from your builder \u2014 /catch-up folds ${Dg(e)===1?"it":"them"} into the docs.`}function Lg(e,t){return`\u{1F4E5} While you were away (${Nu(t)}): ${Zr(e)} from your builder \u2014 /catch-up folds ${Dg(e)===1?"it":"them"} into the docs.`}function Og(e){return`\u{1F4E5} ${Zr(e)} waiting from your builder \xB7 tab to run /catch-up\u2026`}Fs();import{publishGateVerdict as Uu,publishGateLines as Bu,SKIP_STYLE_FLAG as by}from"document360-engine";te();import{Box as es,Text as De}from"ink";import{jsx as Ne,jsxs as Mo}from"react/jsx-runtime";function uS({row:e,nameW:t,width:n}){let o=s=>Na(s,n),r=(s,i)=>Ne(es,{flexDirection:"column",children:s.map(i)});switch(e.t){case"head":return r(o(e.s),(s,i)=>Ne(De,{color:ee,bold:!0,children:s},i));case"text":return r(o(e.s),(s,i)=>Ne(De,{children:s},i));case"dim":return r(o(e.s),(s,i)=>Ne(De,{dimColor:!0,children:s},i));case"sub":return r(o(e.s),(s,i)=>Ne(De,{bold:!0,dimColor:!0,children:s},i));case"good":return r(o(e.s),(s,i)=>Ne(De,{color:"green",children:s},i));case"step":{let s=o(`${e.n}. ${e.s}`);return Ne(es,{flexDirection:"column",children:s.map((i,a)=>a===0?Mo(De,{children:[Ne(De,{color:ee,children:`${e.n}. `}),i.slice(`${e.n}. `.length)]},a):Ne(De,{children:i},a))})}case"cmd":{let s=js(e.name,e.s,t,n),i=s.descLines.slice(s.nameOwnLine?0:1);return Mo(es,{flexDirection:"column",children:[Mo(De,{children:[" ",Ne(De,{color:ee,children:s.nameCell}),!s.nameOwnLine&&Ne(De,{dimColor:!0,children:` ${s.descLines[0]??""}`})]}),i.map((a,l)=>Ne(De,{dimColor:!0,children:`${s.indent}${a}`},l))]})}case"gap":return Ne(De,{children:" "})}}function _g({tab:e,scroll:t,rows:n,width:o,version:r,engineVersion:s}){let i=et[e]??et[0],a=Da(i.rows),l=Math.max(20,o-2),p=6+et.reduce((S,E)=>S+E.label.length+4,0),m="\u2500".repeat(Math.min(p,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}`,$=zd({rows:n,inner:l,barWidth:p,footerWidth:w.length}),{visible:T,above:R,below:C}=Kd(i.rows,{width:o,budget:$,scroll:t,nameW:a});return Mo(es,{flexDirection:"column",paddingX:1,children:[Mo(De,{children:[Ne(De,{color:ee,bold:!0,children:"Help "}),et.map((S,E)=>E===e?Ne(De,{color:"white",backgroundColor:ee,bold:!0,children:` ${S.label} `},S.key):Ne(De,{dimColor:!0,children:` ${S.label} `},S.key))]}),Ne(De,{color:ee,children:m}),Mo(es,{flexDirection:"column",marginTop:1,children:[R>0?Ne(De,{dimColor:!0,children:`\u22EF ${R} more above`}):null,T.map((S,E)=>Ne(uS,{row:S,nameW:a,width:o},R+E)),C>0?Ne(De,{dimColor:!0,children:`\u22EF ${C} more below`}):null]}),Ne(De,{dimColor:!0,children:`
|
|
441
|
+
\u2190/\u2192 or tab switch \xB7 1-5 jump${R+C>0?" \xB7 \u2191\u2193 scroll":""} \xB7 esc close \xB7 d360-writer v${r} \xB7 engine v${s}`})]})}var dS=/^(?:\d+[.)]|[-*•])\s+/;function Mg(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
|
|
442
|
+
`)){let i=s.trim().replace(dS,""),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 p=`/${l[1].toLowerCase()}${l[2]?` ${l[2]}`:""}`;if(r.includes(p)||r.push(p),r.length>=n)break}return r}te();function Bn(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function _e(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function Fg(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var pS=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function Wg(e,t,n){if(!pS.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 ju(e){return e.replace(/^[\w.-]+\//,"")}var Qi=16,Ug={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function Hn(e){return typeof e=="string"?e:e.cmd}function Bg(e){return typeof e=="string"?void 0:e.desc}function Iu(e){return e.trim().split(/\s+/).slice(1).join(" ")}function Hg(e,t){let n=Iu(t);return e.some(r=>Hn(r).trim()===t.trim()||!!n&&Iu(Hn(r))===n)?e.filter(r=>Hn(r).trim()!==t.trim()&&!(n&&Iu(Hn(r))===n)):[]}import{isDirectiveMention as pP,stripDirectiveMention as hP,appendDirective as fP,reconcileTestidRequest as mP,builderChannelWired as gP,pendingFingerprint as yP}from"document360-engine";var hS=/\[Pasted text #\d+ \+\d+ lines?\]/g;function qg(e){return e.replace(/\r\n?/g,`
|
|
443
|
+
`)}function Gg(e){return e.includes(`
|
|
444
|
+
`)||e.length>200}function Vg(e,t){let n=t.split(`
|
|
445
|
+
`).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function Yg(e,t){return e.replace(hS,n=>t.get(n)??n)}function Kg(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function Ji(e,t){let n=Math.max(1,t),o=[],r=0;for(let s of e.split(`
|
|
446
|
+
`)){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 Zi(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function zg(e,t,n){let o=Zi(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 Xg(e,t,n){let o=e[Zi(e,t)];return n==="start"?o.start:o.end}var fS=new Set(["Edit","Write","MultiEdit","NotebookEdit"]),Qg={hint:"hint",message:"message",state:"state file",roadmap:"roadmap",directive:"directives",feedback:"tool-feedback"},mS=new Set(["hint","message","state"]),gS=["hint","message","roadmap","directive","feedback","state"];function yS(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 Jg(e,t){let n=e==="Read"?"read":fS.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=yS(r.slice(i+s.length));return a?{category:a,verb:n,path:r}:null}function Zg(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 gS)for(let s of["updated","read"]){let i=t.get(`${r}:${s}`)?.size??0;i!==0&&o.push(mS.has(r)?`${i} ${Qg[r]}${i===1?"":"s"} ${s}`:`${Qg[r]} ${s}`)}return o.length>0?o.join(" \xB7 "):null}function ey(e,t,n){let o=Math.max(1,n),r=e.split(`
|
|
447
447
|
`),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(`
|
|
448
|
-
`),truncated:i>0||l>0}}}return{text:e,truncated:!1}}function
|
|
449
|
-
`)){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 qo,jsx as
|
|
448
|
+
`),truncated:i>0||l>0}}}return{text:e,truncated:!1}}function ty(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 ny(e){let t=!1,n=0,o=0;for(let r of e.split(`
|
|
449
|
+
`)){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 qo,jsx as H,jsxs as oe}from"react/jsx-runtime";var wP={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL",auto:"auto \u2014 right-sized for docs \xB7 /model to change"},$y=` 1. /init \u2014 pick your Document360 environment & scaffold config
|
|
450
450
|
2. /login \u2014 sign in & pick your Document360 project (workspace auto-selected)
|
|
451
|
-
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function
|
|
452
|
-
`).length+1,console.log(d)},[Be]),
|
|
453
|
-
`)}catch{}u.picker&&(X(u.picker.options.map(A=>({cmd:A.cmd,desc:A.desc}))),eo(u.picker.title)),!d?.silent&&u.note&&(Ye.current.printed=u.menu,Ye.current.printedAt=no.current);let g=no.current-Ye.current.printedAt<Math.max(8,(Ue.rows??24)-4)&&
|
|
454
|
-
`)}),Zt(u.prompt,
|
|
455
|
-
${
|
|
451
|
+
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function kP(e,t,n,o){let r=Hu(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=qu(e),a=ge(e),l=(a?.docsDir??Gu).replace(/\/+$/,""),p=a?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${l}/ + config`,m={version:t,engineVersion:Cy,captureVersion:nt(),claude:s,model:i.model,modelSource:wP[i.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:a!==null,mode:p};if(a===null)return m;try{let w=ht(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 $=qn(w.name);if($){let T={...Go($.idToken)??{},...Go($.accessToken)??{}},R=T.email??T.preferred_username??"signed in";gn($)?$.refreshToken&&(m.who=R,m.loggedOut=!1,m.sessionHint="session expired \u2014 refreshing\u2026"):(m.who=R,m.loggedOut=!1,m.sessionHint=`session valid until ${new Date($.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return m}function bP(e,t){try{let n=ht(e,t),o=qn(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...Go(o.idToken)??{},...Go(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return gn(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 vy=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],Vo=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],$P="Ask me to write or update an article\u2026";function Ho({ch:e,dim:t}){let[n,o]=ne(!0);return rt(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),H(q,{inverse:n,color:t&&!n?"gray":void 0,children:e})}function mn({rows:e,cursor:t,cap:n,render:o}){let r=Vi(e.length,t,n);return oe(qo,{children:[r.above>0?H(q,{color:"gray",children:` \u22EF ${r.above} more above`}):null,e.slice(r.start,r.end).map((s,i)=>o(s,r.start+i,r.start+i===t)),r.below>0?H(q,{color:"gray",children:` \u22EF ${r.below} more below`}):null]})}var xy=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Ry(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var vP=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function xP({startTime:e,chars:t}){let[n,o]=ne(0),r=se(Date.now());rt(()=>{let p=setInterval(()=>o(m=>m+1),120);return()=>clearInterval(p)},[]);let s=Vo[n%Vo.length],i=vy[Math.floor(n/16)%vy.length],a=Ip(e,r.current,Date.now()),l=Math.round(t/4);return oe(xe,{children:[H(q,{color:ee,children:` ${s} ${i}\u2026 `}),H(q,{color:"gray",children:`(${kr(a)} \xB7 ~${l} tokens \xB7 esc to interrupt)`})]})}function RP({text:e}){let[t,n]=ne(0);return rt(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),H(xe,{paddingX:1,children:H(q,{color:ee,children:`${Vo[t%Vo.length]} ${e}`})})}var CP=12e4;function SP({p:e}){let[t,n]=ne(0);rt(()=>{let S=setInterval(()=>n(E=>E+1),150);return()=>clearInterval(S)},[]);let o=Vo[t%Vo.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>=CP,l=e.verb??"Converting",p=e.unit??"article",m=e.rows.reduce((S,E)=>S+E.items,0),w=l.toLowerCase(),$=e.rows,T=0;if($.length>Qi){let S=$.findIndex(I=>I.status==="active"||I.status==="pending"),E=Math.max(0,Math.min(S-2,$.length-Qi));T=$.slice(0,E).filter(I=>I.status==="done").length,$=$.slice(E,E+Qi)}let R=Math.min(40,Math.max(...$.map(S=>ju(S.label).length),0)),C=S=>S==="failed"?"red":S==="active"?ee:void 0;return oe(xe,{flexDirection:"column",children:[oe(xe,{children:[H(q,{color:ee,children:` ${o} ${l} ${m} ${p}${m===1?"":"s"} `}),H(q,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${i} tokens \xB7 ${kr(r)} \xB7 esc to stop`})]}),T>0&&H(q,{dimColor:!0,children:` \u2714 +${T} done`}),$.map(S=>oe(q,{color:C(S.status),dimColor:S.status==="done"||S.status==="pending",children:[` ${Ug[S.status]} ${ju(S.label).padEnd(R)}`,S.status==="active"&&S.itemsDone!==void 0?` (${S.itemsDone}/${S.items} ${p}${S.items===1?"":"s"})`:S.status!=="pending"?` (${S.items} ${p}${S.items===1?"":"s"})`:"",S.status==="active"?` \u2190 ${w}\u2026`:""]},S.label)),a&&H(q,{color:"yellow",children:` \u26A0 no activity for ${kr(s)} \u2014 press esc to stop if it's wedged`})]})}var PP=10800*1e3;function Sy({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=kS(),[s,i]=ne(n),[a,l]=ne(null),[p,m]=ne({text:"",pos:0}),w=p.text,$=Z(u=>{m(d=>{let c=typeof u=="function"?u(d.text):u;return{text:c,pos:c.length}})},[]),T=Z(u=>{m(d=>({text:d.text.slice(0,d.pos)+u+d.text.slice(d.pos),pos:d.pos+u.length}))},[]),R=Z(()=>{m(u=>{if(u.pos===0)return u;let d=u.text.slice(0,u.pos),c=Kg(d)??d.slice(0,-1);return{text:c+u.text.slice(u.pos),pos:c.length}})},[]),[C,S]=ne(!1),[E,I]=ne(!1),[L,Y]=ne(0),[ce,ue]=ne(!1),[ie,he]=ne(null),[de,ke]=ne(null),[ae,X]=ne([]),Ce=se(!1),Se=se(!1),Fe=se(null),Bt=se(!1),[yn,$t]=ne(!1),ft=se(0),[Gn,st]=ne(!1),[Ht,Pe]=ne(!1),[qt,ns]=ne(null),[jy,Gt]=ne(0),Dt=se(0),[sa,Vn]=ne(0),[Yn,os]=ne(null),zu=se(new Map),Iy=se(0),Kn=se([]),mt=se(null);mt.current===null&&(mt.current=ry({cwd:e,profileName:s,allowProdWrites:!1}));let Nt=se({uuid:null,firstPrompt:null,titleFired:!1}),Yo=se(new Map),Xu=se(null),rs=se(ay().verboseTranscript===!0),Vt=se(!1),ia=se([]),Re=se([]),wn=se([]),Ko=se(null),[Qu,kn]=ne(null),aa=se(null),[bn,$n]=ne(null),[Yt,zn]=ne(null),[Kt,Xn]=ne(null),[Je,Qn]=ne(null),[gt,vn]=ne(null),[jt,Jn]=ne(null),[zt,Zn]=ne(null),[Xt,xn]=ne(null),[It,Lt]=ne(null),[We,zo]=ne(null),Ju=se({value:0,at:0}),[vt,Rn]=ne(null),[Zu,eo]=ne(null),[it,Cn]=ne(null),[Ze,to]=ne(null),[ed,la]=ne([]),Sn=se([]),Xo=se(!1),Ae=se(null),[Qo,le]=ne(null),[td,Me]=ne(null),ss=se(!1),Jo=se(null),Zo=se(null),[at,Pn]=ne(null),[er,Tn]=ne(null),tr=!!(Kt||Je||gt||jt||zt||Xt||It||We||vt||it||Ze||at||er),[nd,Qt]=ne(0),[od,Jt]=ne(0),[Ly,rd]=ne(0),ca=Lu(()=>{try{let u=qu(e);return u.source==="auto"?`${u.model} (auto)`:u.model}catch{return null}},[e,Ly]),{stdout:Ue}=$S(),[,Oy]=ne(0),sd=se(`${Ue.columns??80}x${Ue.rows??24}`),Be=Z(()=>Math.max(20,(Ue.columns??80)-1),[Ue]),is=Z(u=>{Kn.current.push(u);let d=Qa(u,Be());no.current+=d.split(`
|
|
452
|
+
`).length+1,console.log(d)},[Be]),ua=se([]),as=Z(()=>{let u=ua.current;if(u.length===0)return;ua.current=[];let d=Zg(u);d&&is({kind:"note",tone:"info",text:`\u25CF Housekeeping ${d}`})},[is]),h=Z(u=>{as(),is(u)},[is,as]),Ye=se({printed:[],armed:[],printedAt:0}),no=se(0),Ke=Z((u,d)=>{ft.current++,Ye.current.armed=[],he(u),ke(d??null)},[]),xt=Z(()=>{ft.current++,Ye.current.armed=[],he(null),ke(null)},[]),ls=Z(u=>{ft.current++,Ye.current.armed=[],he(null),ke(u)},[]),J=Z(u=>Ke(u,Oo({kind:"cmd",cmd:u,reason:""})),[Ke]),Ot=Z((u,d)=>{if(!d?.silent&&u.note&&h({kind:"note",tone:d?.tone??u.tone,text:u.note}),!d?.silent&&u.note?.includes(".d360-writer/ \u2014 your articles"))try{let A=uP(e);dP(RS(A)),xS(A,`${new Date().toISOString()}
|
|
453
|
+
`)}catch{}u.picker&&(X(u.picker.options.map(A=>({cmd:A.cmd,desc:A.desc}))),eo(u.picker.title)),!d?.silent&&u.note&&(Ye.current.printed=u.menu,Ye.current.printedAt=no.current);let g=no.current-Ye.current.printedAt<Math.max(8,(Ue.rows??24)-4)&&Qm(Ye.current.printed,u.menu)?u.menu:[];u.lead&&(u.lead.kind==="answer"?ls(Oo(u.lead,g.length)):Ke(u.lead.kind==="cmd"?u.lead.cmd:u.lead.text,Oo(u.lead,g.length))),Ye.current.armed=g},[h,Ke,ls,e,Ue]),Ee=Z((u,d,c="info")=>{Ye.current.armed=[],u&&h({kind:"note",tone:c,text:u}),d&&(d.kind==="answer"?ls(Oo(d)):Ke(d.kind==="cmd"?d.cmd:d.text,Oo(d)))},[h,Ke,ls]),nr=Z((u,d,c,g="info")=>{if(u.producedNothing){Ee("Nothing was changed \u2014 the agent produced no output, so this command did nothing at all.",{kind:"cmd",cmd:"/doctor",reason:"it checks Claude sign-in + whether the model is reachable from this machine"},"warn");return}Ee(d,c,g)},[Ee]),[or,da]=ne(null),[_y,id]=ne(!1),Zt=Z((u,d)=>{da(u),id(!1),h({kind:"note",tone:"info",text:d?.hint??"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[h]),pa=Z(()=>{mP(e,new Date().toISOString());let u=om(e);u&&(h({kind:"note",tone:"info",text:u.lines.join(`
|
|
454
|
+
`)}),Zt(u.prompt,gP(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,Zt]),ha=se(!1),fa=Z(async()=>{try{if(ha.current||!tP(eP())||ge(e)?.mode==="engineer")return;let u=await ZS({pkg:Io,currentVersion:o,force:!0});if(!u.updateAvailable||!u.latest)return;ha.current=!0,h({kind:"note",tone:"info",text:`\u2B06 Updating ${Io} ${u.current} \u2192 ${u.latest}\u2026 (wait for the \u2713 before you /exit)`}),Pe(!0),(await Ti().finally(()=>Pe(!1))).ok?(h({kind:"note",tone:"ok",text:`\u2713 Updated to v${u.latest} \u2014 run /exit, then relaunch to apply.`}),J("/exit"),ns(u.latest)):h({kind:"note",tone:"warn",text:`Update available (v${u.latest}) but auto-update failed \u2014 run: ${Pi}`})}catch{}},[e,o,h,J]),rr=se(!1),ma=se(null),ad=Z(async u=>{if(!rr.current)try{let d=ge(e);if(!d)return;let c=ld.current;if(!c)return;if(c.pushConsent!=="on"){if(c.uncommitted===0)return;rr.current=!0;try{let A=await cP(e,d);if(A.commit?.ok)ma.current=null;else if(A.commit&&!A.commit.ok){let U=`${A.commit.reason}:${A.commit.detail??""}`;ma.current!==U&&(ma.current=U,h({kind:"note",tone:"warn",text:`\u26A0 Couldn't save your docs work to git \u2014 ${hn(A.commit.reason,A.commit.detail)}`}))}}finally{rr.current=!1}return}if(c.uncommitted===0&&c.unpushed===0&&!u.pull)return;rr.current=!0;try{let{lines:A,changed:U}=await Ri(e,d);for(let O of A)O.tone==="warn"||O.tone==="error"?h({kind:"note",tone:O.tone,text:O.text}):O.text.includes("\u2B07")&&h({kind:"note",tone:O.tone,text:O.text});U&&Y(O=>O+1)}finally{rr.current=!1}}catch{}},[e,h]),oo=Z(u=>{let d=Ve(e,s);return d.ok?!0:(h({kind:"note",tone:"warn",text:d.reason}),Zo.current=u,J("/login"),!1)},[e,s,h,J]),[cs,ga]=ne(null),ld=se(null),yt=Z((u,d)=>{let c=Xr(e,s,{claudeMissing:Hu(t).state==="missing",allowAutoAudit:u,genreUnknown:Bt.current,pendingAnswer:Fe.current});return ld.current=c?.handoff??null,c?zr(c,{header:d,pickable:!0}):{kind:"idle"}},[e,s,t]),ya=se(Date.now()),sr=se(Eg()),cd=se(0),[ud,dd]=ne(null),ir=se(!0),ro=se(!1),us=se(0),ar=se(0);rt(()=>{let u=setInterval(()=>{if(ir.current){us.current=0,ar.current=0;return}if(!C)try{if(!Fo(gy(e)))return;if(kt(e).status==="current"){ir.current=!0,us.current=0,ar.current=0;let c=ro.current?`\u2713 Your builder finished the protocol update (v${Te}) \u2014 the dev\u2194docs hand-off is current again. Here\u2019s where your docs stand:`:"\u2713 Your builder finished the hand-off \u2014 the architecture brief is in. I can read this repo now and write accurate docs. Here\u2019s where things stand:",g=yt(!1,c),A=g.kind==="recommend"?g.rec:null;da(null),A?.note?Ot(A,{tone:"ok"}):(h({kind:"note",tone:"ok",text:`${c}${A?.lead?` ${Kr(A.lead)}`:""}`}),A?.lead||A?.picker?Ot(A,{silent:!0}):ro.current||Ke("write the docs for this repo")),Y(U=>U+1);return}if(ro.current)return;us.current+=1;let d=us.current;if((d===4||d%15===0)&&ar.current<3){ar.current+=1;let c=ar.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";h({kind:"note",tone:"info",text:Ft(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,yt,Ot,Ke]),rt(()=>{let u=Qu??ts(e);if(!C){Yi(0),_o(`${zi} ${u}`);return}Yi(3);let d=0;_o(`${Ki[0]} ${u}`);let c=setInterval(()=>{d=(d+1)%Ki.length,_o(`${Ki[d]} ${u}`)},400);return()=>clearInterval(c)},[C,e,Qu]),rt(()=>()=>Yi(0),[]),rt(()=>{let u=performance.now(),d=[],c=(f,k)=>{let b=performance.now();try{return k()}finally{let x=Math.round(performance.now()-b);x>=80&&d.push(`${f}: ${x}ms`)}};h({kind:"banner",info:c("banner",()=>kP(e,o,t,s))});let g=Hu(t).state==="missing";if(g&&h({kind:"note",tone:"warn",text:`\u26A0 Set up Claude first \u2014 d360-writer's agent runs on Claude Code, and it's not signed in on this machine yet.
|
|
455
|
+
${SS}
|
|
456
456
|
Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!ge(e)){h({kind:"note",tone:"info",text:`Welcome! This repo isn't set up for d360-writer yet \u2014 three steps and you're writing docs:
|
|
457
|
-
${
|
|
458
|
-
`)}),Zt(Dn()),ir.current=!1,ro.current=!1)}}catch{}try{let f=c("reconcile-feedback",()=>
|
|
459
|
-
`)}),f.reopenedForRedaction&&h({kind:"note",tone:"warn",text:
|
|
457
|
+
${$y}`}),J(g?"/doctor":"/init");return}g&&J("/doctor");try{let f=ht(e,s),k=qn(f.name);k&&gn(k)&&k.refreshToken?ES({profile:f.name,connection:f.connection}).then(()=>{h({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),Y(b=>b+1)}).catch(()=>{h({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 sign in again with /login."}),J("/login")}):(!k||gn(k))&&(h({kind:"note",tone:"warn",text:`Profile "${f.name}" is not signed in \u2014 sign in with /login.`}),J("/login"))}catch{}try{let f=ge(e),k=ht(e,s),b=qn(k.name);f&&b&&!gn(b)&&bu(e,f.authoritativeSourceFiles)&&!$u(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."}),J("/scope"))}catch{}try{let f=c("resolve-genre",()=>HS(e));f.persisted&&f.appType?h({kind:"note",tone:"ok",text:`\u2713 Detected a ${f.appType} app \u2014 enabled the ${f.appType}-doc-playbook (change with /genre, or edit .d360-writer/config.json).`}):f.source==="unknown"&&ge(e)&&(Bt.current=!0)}catch{}let A=kt(e);try{if(c("reconcile-devhints",()=>Ls(e)),A.status!=="current"&&!Ft(e)){let f=Os(e);f.length&&(h({kind:"note",tone:"warn",text:f.join(`
|
|
458
|
+
`)}),Zt(Dn()),ir.current=!1,ro.current=!1)}}catch{}try{let f=c("reconcile-feedback",()=>nP(e));f.archived>0&&h({kind:"note",tone:"ok",text:`\u2713 Tidied ${f.archived} resolved item${f.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${f.open>0?`; ${f.open} still open`:""}.`})}catch{}try{let f=c("upgrade-actions",()=>oP(e));f.applied.length>0&&h({kind:"note",tone:"warn",text:Ds(f.applied).join(`
|
|
459
|
+
`)}),f.reopenedForRedaction&&h({kind:"note",tone:"warn",text:Ns(f.reopenedForRedaction)})}catch{}let U=c("ready-decision",()=>yt(!0));U.kind==="autoAudit"?(h({kind:"note",tone:"info",text:U.note}),Sr().then(f=>{f.kind!=="forward-to-agent"||!f.prompt||fe(f.prompt,{display:f.display,quietUser:!0}).then(k=>{k.producedNothing||(Yr(e,s),Y(b=>b+1))})})):U.kind==="recommend"&&Ot(U.rec);let O=Math.round(performance.now()-u);O>=800&&lP({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${O}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${d.length?d.join(`
|
|
460
460
|
`):"no single phase \u226580ms"}
|
|
461
|
-
cwd: ${e}`}),
|
|
462
|
-
|
|
463
|
-
${D}`)}catch{}d?.quietUser||h({kind:"user",text:d?.echoDisplay&&d.display?d.display:u});let g=Nt.current;g.firstPrompt||(g.firstPrompt=d?.display??u),Dt.current=Date.now(),Gt(0),S(!0),Yo.current.clear();let A="",U=!1,O=!1,f=!1,k=!1,b="",
|
|
464
|
-
`)}),J(
|
|
465
|
-
`)});let
|
|
466
|
-
`)}),[h]),
|
|
467
|
-
`)})
|
|
468
|
-
`)});let
|
|
469
|
-
`)}),J(
|
|
470
|
-
`)}),c.blocked.length>0?J("/review --blocked --fix"):Ee(null,null)}catch(c){h({kind:"note",tone:"error",text:`Publishing failed: ${c.message}`})}finally{Me(null),S(!1),Y(c=>c+1)}},[e,s,h,J,Ee]),
|
|
471
|
-
`):`${
|
|
461
|
+
cwd: ${e}`}),fa(),ad({pull:!0})},[]),rt(()=>{let u=setInterval(()=>{fa()},PP);return()=>clearInterval(u)},[fa]),rt(()=>{let u=setInterval(()=>{try{let d=Date.now(),c=Du(d,ya.current);if(cd.current+=1,c&&cd.current%Math.round(3e5/6e4)!==0)return;let g=yP(e),A=sr.current,U=g===A.fingerprint&&A.counts?A.counts:Wn(e),O=Ng({now:d,lastInputAt:ya.current,fingerprint:g,counts:U,occupied:C||ce||ae.length>0||w!==""||tr||Re.current.length>0,prev:A});if(sr.current=O.memory,dd(O.waiting),O.speak){h({kind:"note",tone:"info",text:Ig(O.speak)});let f=yt(!1);f.kind==="recommend"&&Ot(f.rec,{silent:!0})}}catch{}},6e4);return()=>clearInterval(u)},[e,C,ce,ae.length,w,tr,h,yt,Ot]),rt(()=>{if(C||ce||Ce.current||ie!==null||ae.length>0||w!==""||or!==null||Re.current.length>0||Ko.current||tr)return;let u=yt(!1);u.kind==="recommend"&&(u.rec.lead||u.rec.picker)&&Ot(u.rec,{silent:!0}),ad({pull:!1})},[C,ce,ie,ae,w,or,tr,L,yt,yn]),rt(()=>{let u=null,d=null,c=()=>{u&&clearTimeout(u),u=setTimeout(()=>{u=null;let g=`${Ue.columns??80}x${Ue.rows??24}`;g!==sd.current&&(sd.current=g,Oy(A=>A+1),d&&clearTimeout(d),d=setTimeout(()=>{d=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+Lp(Kn.current,Be())+"\x1B[?2026l")},80))},400)};return Ue.on("resize",c),()=>{u&&clearTimeout(u),d&&clearTimeout(d),Ue.off("resize",c)}},[Ue,Be]);let ze=Math.max(20,(Ue.columns??80)-1),pd=Lu(()=>bP(e,s),[e,s,L]),wa=(()=>{if(Ht)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(qt!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${qt?` v${qt}`:""}\u2026`,isSetup:!0};if(cs)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(or)return _y?{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(ud)return{text:Og(ud),isSetup:!0};if(Re.current.length>0){let g=Re.current.length;return Re.current[0].mode==="conflict"?{text:g>1?`l keep local \xB7 p take portal \xB7 s skip \xB7 la/pa/sa for all ${g}\u2026`:"l keep local \xB7 p take portal \xB7 s skip \xB7 anything else cancels\u2026",isSetup:!0}:{text:g>1?`y to write \xB7 n to skip \xB7 ya/na for all ${g}\u2026`:"y to write \xB7 n to skip \xB7 anything else cancels\u2026",isSetup:!0}}let u=ge(e);if(!u)return{text:"Run /init to set up this repo (or /help)\u2026",isSetup:!0};let d=Ou(e,(u.docsDir??Gu).replace(/\/+$/,"")),c=(()=>{try{return Fo(d)&&vS(d).length>0}catch{return!1}})();try{let g=ht(e,s),A=qn(g.name);if(!(!!A&&!(gn(A)&&!A.refreshToken)))return{text:`Sign in with /login (profile "${g.name}")\u2026`,isSetup:!0};if(!g.project.projectId)return{text:"Sign in to Document360 to pick your project\u2026",isSetup:!0};if(!g.project.workspaceId&&!c)return{text:"Pick a workspace with /workspace\u2026",isSetup:!0}}catch{}return c?{text:$P,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),_t=Rp(w),hd=_t.length>0&&!C,My=12,Mt=Tu(Ue.rows),Fy=Ue.rows??24,fd=Tu(Ue.rows,{max:My}),ds=Math.min(sa,Math.max(0,_t.length-1)),An=Vi(_t.length,ds,fd).start,ka=_t.slice(An,An+fd),ba=a!==null?ey(a,8,ze):null,ps=it?it.paths.filter(u=>!it.query||u.toLowerCase().includes(it.query.toLowerCase())).slice(0,8):[],hs=at?at.sessions.filter(u=>{let d=at.query.toLowerCase();return!d||u.name.toLowerCase().includes(d)||u.firstPrompt.toLowerCase().includes(d)}).slice(0,8):[],Xe=Z((u,d)=>{mt.current?.close(),mt.current=ry({cwd:e,resume:u,profileName:d??s,allowProdWrites:Vt.current}),u||(Nt.current={uuid:null,firstPrompt:null,titleFired:!1},kn(null)),Qt(0),Jt(0)},[e,s]),md=Z((u,d,c)=>{if(xy.test(u))try{let g=ht(e,s),A=typeof d.project_id=="string"&&d.project_id||g.project.projectId,U=Hi(d,c),O=[],f=qi(c);u.endsWith("publish_article")&&f&&O.push(`Live: ${f}`);let k=Gi(c);k?O.push(`Preview: ${k}`):U&&A&&O.push(`Preview: ${Bi(g.connection.portalUrl,A,U,g.project.languageCode??"en")}`),O.length>0&&h({kind:"link",lines:O})}catch{}},[e,s,h]),fe=Z(async(u,d)=>{st(!0),Ce.current=!1,Se.current=!1,Fe.current=null,xt(),X([]),eo(null),da(null);let c=ft.current;if(d?.display?.startsWith("/"))try{let D=Vm(e,d.display);D&&(u=`${u}
|
|
462
|
+
|
|
463
|
+
${D}`)}catch{}d?.quietUser||h({kind:"user",text:d?.echoDisplay&&d.display?d.display:u});let g=Nt.current;g.firstPrompt||(g.firstPrompt=d?.display??u),Dt.current=Date.now(),Gt(0),S(!0),Yo.current.clear();let A="",U=!1,O=!1,f=!1,k=!1,b="",x={num:0,closed:!1,cueSeen:!1},v=null,P=()=>{v||(v=setTimeout(()=>{v=null,l(b.length>0?b:null)},60))},W=()=>{v&&clearTimeout(v),v=null,l(null)},F=(D=!1)=>{let{head:M,keep:B}=ty(b,D);M.trim()&&h({kind:"assistant",text:Pu(M.trimEnd(),x)}),b=B,W()};try{for await(let D of mt.current.send(u))if(D.type==="session"){if(!g.uuid){g.uuid=D.sessionId;let M=new Date().toISOString(),B=aa.current,_=B??OS(g.firstPrompt??"session");_S({uuid:D.sessionId,name:_,renamed:!!B,titled:!1,cwd:e,firstPrompt:g.firstPrompt??"",createdAt:M,updatedAt:M}),kn(_),aa.current=null}}else if(D.type==="text"){b+=D.delta,A+=D.delta;let M=ny(b);if(M>0){let B=b.slice(0,M).trimEnd();B&&h({kind:"assistant",text:Pu(B,x)}),b=b.slice(M)}P(),Gt(B=>B+D.delta.length)}else if(D.type==="tool"){U=!0,xy.test(D.name)&&(O=!0);let B=(Q=>typeof Q=="string"&&Q?Q.replace(/\\/g,"/").toLowerCase():null)(D.input.file_path??D.input.notebook_path),_=["Edit","Write","MultiEdit","NotebookEdit"].includes(D.name),K=D.name==="Read"&&B!==null&&B===Xu.current;Xu.current=_?B:null;let me=rs.current,Oe=me?null:Jg(D.name,D.input),Ie=me?null:Fi(D.name,D.input,e,s);if(Oe)ua.current.push(Oe);else if(Ie)F(),h({kind:"doc",verb:Ie.verb,title:Ie.title,category:Ie.category,note:Ie.note,...Ie.loud?{loud:Ie.loud}:{}}),Yo.current.set(D.id,{name:D.name,input:D.input,doc:!0,keepResult:Ie.keepResult});else if(K)F(),h({kind:"tool",title:"Read",sep:"",arg:"re-checking the file it just edited"});else{let Q=Wi(D.name,D.input,e);Q&&(F(),h({kind:"tool",title:Q.title,sep:Q.sep,arg:Q.arg}),Yo.current.set(D.id,{name:D.name,input:D.input}))}}else if(D.type==="article_diff"){let M=ut(D.oldContent,D.newContent,Be());M&&(F(),h({kind:"diff",added:M.added,removed:M.removed,lines:M.lines,hidden:M.hidden}))}else if(D.type==="tool_result"){D.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(D.output)&&(ss.current=!0);let M=Yo.current.get(D.id);if(M){Yo.current.delete(D.id),F();let _=M.doc&&!M.keepResult&&!D.isError?{lines:[],hidden:0}:Ui(D.output,4,D.isError||rs.current?void 0:M.name,M.input);_.lines.length>0&&h({kind:"tool-result",lines:_.lines,hidden:_.hidden,isError:D.isError}),D.isError||md(M.name,M.input,D.output)}}else if(D.type==="result"){F(!0),Qt(_=>_+D.outputTokens),Jt(_=>_+D.costUsd);let M=D.inputTokens+D.cacheReadTokens+D.cacheCreationTokens;if(h({kind:"done",seconds:Math.round((Date.now()-Dt.current)/1e3),tokens:D.outputTokens,costUsd:D.costUsd,ok:D.ok,...M>0?{inTokens:M,cachedPct:Math.round(D.cacheReadTokens/M*100)}:{}}),!f&&!U&&!A.trim()&&!Xo.current&&(k=!0,h({kind:"note",tone:"warn",text:"The agent produced no output \u2014 nothing ran this turn. Two usual causes: the Claude model/runtime (check /doctor \u2014 sign-in + reachability), or a Claude usage limit reached mid-session, which ends every turn instantly and leaves /doctor completely clean."})),D.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(A))try{let _=yy(e);if(Fo(_)){let K=ea(_,"utf8").trim();K&&(ga(K),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 B=D.ok?bg(A):null;if(Se.current=B!==null,Fe.current=B,D.ok&&(x.cueSeen||(B?.options??0)>=2))$t(!0),X([]);else if(B)X([]);else{let _=D.ok?Mg(A,ko.map(K=>K.name)):[];if(_.length>0)J(_[0]);else if(D.ok&&A.trim()&&!Se.current){let K=yt(!1);K.kind==="recommend"&&(K.rec.lead||K.rec.picker)||US(u,A,e).then(me=>{me&&ft.current===c&&Ke(me)}).catch(()=>{})}}if(g.uuid&&(_u(g.uuid),!g.titleFired)){g.titleFired=!0;let _=g.uuid,K=g.firstPrompt;K&&sy(K,e).then(me=>{me&&(LS(_,me),kn(me))}).catch(()=>{})}}else D.type==="error"&&(F(!0),f=!0,D.kind==="auth"&&(ss.current=!0),h(D.kind==="limit"?{kind:"note",text:`\u23F3 ${D.message}`,tone:"warn"}:{kind:"note",text:`agent error: ${D.message}`,tone:"error"}))}finally{if(S(!1),W(),as(),O)try{let D=Wu(await Fu({cwd:e,profileName:s,onRateLimit:M=>Me(`Document360 rate limit \u2014 waiting ${Math.ceil(M.waitMs/1e3)}s\u2026`)}));D&&h({kind:"note",tone:D.startsWith("\u26A0")?"warn":"info",text:D})}catch{}finally{Me(null)}Y(D=>D+1),Nt.current.uuid&&Tg(e,Nt.current.uuid,Kn.current),ss.current?(ss.current=!1,Jo.current=d?.display??u,Ke("/login","\u21E5 tab to run /login \u2014 then I\u2019ll re-send your last prompt\u2026")):Jo.current=null,Xo.current&&(Xo.current=!1,Sn.current.length>0&&(h({kind:"note",tone:"info",text:`(${Sn.current.length} queued message(s) discarded)`}),Sn.current=[],la([])),h({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}return{producedNothing:k}},[e,h,md,Be,Ke,J,xt,yt,as]),wt=Z(async(u,d=0,c)=>{let g=Uu(e,u,{allowUnreviewed:c?.skipReview===!0,allowStyleErrors:c?.skipStyle===!0});if(!g.clear){h({kind:"note",tone:"warn",text:Bu(g,u.length).join(`
|
|
464
|
+
`)}),J(Vl(g));return}let A=Uo(e,"standard");Dt.current=Date.now(),Gt(0),S(!0);let U=new AbortController;Ae.current=U;let O=async(f,k)=>{let b=Mu(f);le({verb:"Pushing",total:b.length,done:0,active:[],rows:Bn(b),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),h({kind:"note",tone:"info",text:k?`Resolving cross-links in ${f.length} article${f.length===1?"":"s"} whose targets were saved this run (second pass)\u2026 (esc to stop)`:`Pushing ${f.length} article${f.length===1?"":"s"} in ${b.length} batch${b.length===1?"":"es"} (\u2264${xr} agents at once) on ${A.model}\u2026 (esc to stop)`});let x=!1;for await(let v of Wo({cwd:e,partitions:b,promptFor:P=>Rr(P.paths),concurrency:xr,profileName:s,allowProdWrites:Vt.current,allowUnreviewedPublish:c?.skipReview===!0,allowStyleErrors:c?.skipStyle===!0,model:A.model,signal:U.signal}))if(v.type==="partition_status")v.status==="running"?le(P=>P&&{...P,active:[...P.active,v.label],rows:_e(P.rows,v.label,"active"),lastAt:Date.now()}):le(P=>P&&{...P,active:P.active.filter(W=>W!==v.label),done:P.done+1,rows:_e(P.rows,v.label,v.status==="done"?"done":"failed"),lastAt:Date.now()});else if(v.type==="partition_event")le(P=>{if(!P)return P;let W={...P,lastAt:Date.now()};return v.event.type==="tool"?W.tools=P.tools+1:v.event.type==="text"&&(W.chars=P.chars+v.event.delta.length),W});else if(v.type==="run_done"){x=v.aborted,Jt(B=>B+v.totalCostUsd),Qt(B=>B+v.results.reduce((_,K)=>_+K.outputTokens,0));let P=v.aborted?"Stopped. ":"",W=t.kind==="api"?"api":"subscription",F=vl(e,u,s),D=!v.aborted&&(!!v.blocked||!!v.allEmpty||u.length>0&&F===0);h({kind:"note",tone:v.aborted?"warn":v.ok&&!D?"ok":"warn",text:P+xl(v.results,b,W,k?0:d,{recorded:F,...v.blocked?{blocked:v.blocked}:{},...v.allEmpty?{allEmpty:!0}:{},...v.bailedEmpty?{bailedEmpty:!0,notRun:v.notRun??0}:{}},c?.scope).join(`
|
|
465
|
+
`)});let M=bl(e,s);if(M&&h({kind:"note",tone:"info",text:M}),!v.aborted&&!D){let B=Co(e,s);B&&h({kind:"note",tone:"info",text:B})}if(!v.aborted&&!D){try{let _=await Fu({cwd:e,profileName:s,onRateLimit:me=>Me(`Document360 rate limit \u2014 waiting ${Math.ceil(me.waitMs/1e3)}s\u2026`)}),K=Wu(_);K?h({kind:"note",tone:K.startsWith("\u26A0")?"warn":"info",text:K}):_.skipped&&h({kind:"note",tone:"warn",text:`Order sync skipped: ${_.skipped}`})}catch(_){h({kind:"note",tone:"warn",text:`Order sync failed: ${_.message}`})}finally{Me(null)}try{let _=ky(await wy({cwd:e,profileName:s}));_&&h({kind:"note",tone:"info",text:_})}catch(_){h({kind:"note",tone:"warn",text:`Related-articles sync failed: ${_.message}`})}let B=await So(e,s);B&&h({kind:"note",tone:"info",text:B})}}return x};try{if(!await O(u,!1)){let k=await Rl(e,s,u);k.length>0&&await O(k,!0),d>0&&Ee(null,{kind:"cmd",cmd:"/resolve",reason:`${d} conflict${d===1?"":"s"} still need settling \u2014 they were left untouched`},"warn")}}catch(f){h({kind:"note",tone:"error",text:`Publish run failed: ${f.message}`})}finally{Ae.current=null,le(null),S(!1),Y(f=>f+1)}},[e,s,h,t,Ee]),so=Z(u=>h({kind:"block",text:u.join(`
|
|
466
|
+
`)}),[h]),fs=Z(async u=>{let d=Uo(e,"standard");Dt.current=Date.now(),Gt(0),S(!0);let c=new AbortController;Ae.current=c,le({verb:u.verb,unit:"article",total:u.partitions.length,done:0,active:[],rows:Bn(u.partitions),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),h({kind:"note",tone:"info",text:`${u.headline} on ${d.model}\u2026 (esc to stop)`});let g=!0,A=[],U=!1;try{for await(let O of Wo({cwd:e,partitions:u.partitions,promptFor:u.promptFor,concurrency:u.concurrency,profileName:s,allowProdWrites:Vt.current,model:d.model,signal:c.signal}))if(O.type==="partition_status")O.status==="running"?le(f=>f&&{...f,active:[...f.active,O.label],rows:_e(f.rows,O.label,"active"),lastAt:Date.now()}):le(f=>f&&{...f,active:f.active.filter(k=>k!==O.label),done:f.done+1,rows:_e(f.rows,O.label,O.status==="done"?"done":"failed"),lastAt:Date.now()});else if(O.type==="partition_event")le(f=>{if(!f)return f;let k={...f,lastAt:Date.now()};return O.event.type==="tool"?k.tools=f.tools+1:O.event.type==="text"&&(k.chars=f.chars+O.event.delta.length),k});else if(O.type==="run_done"){Jt(b=>b+O.totalCostUsd),Qt(b=>b+O.results.reduce((x,v)=>x+v.outputTokens,0));let f=hy(u.partitions,O.results);g=!!O.allEmpty||!!O.blocked,U=!!O.aborted;let k=[`${O.aborted?"Stopped. ":""}${O.results.length-f.failed.length}/${u.partitions.length} batches ${u.doneNoun}.`,...f.failed.length?[`\u26A0 ${f.failed.length} not ${u.doneNoun} \u2014 their articles are unchanged: ${f.failed.map(b=>b.label).join(", ")}`]:[],...f.notRun.length?[`\u26A0 ${f.notRun.length} batch${f.notRun.length===1?"":"es"} never started \u2014 their articles are untouched.`]:[],...O.blocked?[`\u26A0 ${O.blocked}`]:[],...O.allEmpty?[u.emptyNote??"\u26A0 No turn produced any work this run \u2014 nothing was changed."]:[],...u.caveatLines??[]];h({kind:"note",tone:O.aborted||f.failed.length||f.notRun.length||O.blocked||O.allEmpty?"warn":"ok",text:k.join(`
|
|
467
|
+
`)}),g||(A=f.covered)}}catch(O){h({kind:"note",tone:"error",text:`${u.verb} failed: ${O.message}`})}finally{Ae.current=null,le(null),S(!1),Y(O=>O+1)}return{producedNothing:g,covered:A,aborted:U}},[e,s,h]),Wy=Z(async(u,d)=>{let c=await fs({partitions:u.partitions,promptFor:u.promptFor,concurrency:Gr,verb:"Reviewing",doneNoun:"reviewed",headline:`Reviewing ${u.articles} article${u.articles===1?"":"s"} in ${u.partitions.length} batches (\u2264${Gr} editors at once)${d?", applying fixes as they go":", report only"}`,caveatLines:du(u),emptyNote:"\u26A0 No editor produced any work this run \u2014 nothing was reviewed or changed."});if(d&&c.covered.length>0)try{Bo(e,c.covered,Qe("review"))}catch{}return{producedNothing:c.producedNothing,aborted:c.aborted}},[e,fs]),$a=Z(async(u,d)=>{if(u.length===0)return;let c=u.reduce((f,k)=>f+k.threads.length,0),g=new Map,A=u.map(f=>(g.set(f.label,f),{label:f.label,paths:f.path?[f.path]:[]})),U=Uo(e,"standard");Dt.current=Date.now(),Gt(0),S(!0);let O=new AbortController;Ae.current=O,le({verb:"Answering",unit:"article",total:A.length,done:0,active:[],rows:Bn(A),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),h({kind:"note",tone:"info",text:`Answering ${c} comment${c===1?"":"s"} across ${A.length} article${A.length===1?"":"s"} (\u2264${Wr} agents at once) on ${U.model}. Each article is fixed, pushed to Document360 as a draft, then answered in the thread${d.resolve?" and resolved":" \u2014 the threads stay open for your reviewers to close"}\u2026 (esc to stop)`});try{for await(let f of Wo({cwd:e,partitions:A,promptFor:k=>{let b=g.get(k.label);return Qc({articleId:b.articleId,label:b.label,path:b.path,count:b.threads.length,resolve:d.resolve})},concurrency:Wr,profileName:s,allowProdWrites:Vt.current,allowCommentResolve:d.resolve,model:U.model,signal:O.signal}))if(f.type==="partition_status")f.status==="running"?le(k=>k&&{...k,active:[...k.active,f.label],rows:_e(k.rows,f.label,"active"),lastAt:Date.now()}):le(k=>k&&{...k,active:k.active.filter(b=>b!==f.label),done:k.done+1,rows:_e(k.rows,f.label,f.status==="done"?"done":"failed"),lastAt:Date.now()});else if(f.type==="partition_event")le(k=>{if(!k)return k;let b={...k,lastAt:Date.now()};return f.event.type==="tool"?b.tools=k.tools+1:f.event.type==="text"&&(b.chars=k.chars+f.event.delta.length),b});else if(f.type==="run_done"){Jt(D=>D+f.totalCostUsd),Qt(D=>D+f.results.reduce((M,B)=>M+B.outputTokens,0));let k=hy(A,f.results),b=f.results.length-k.failed.length,x=f.aborted?"Stopped. ":"",v=[...k.failed.map(D=>D.label),...k.notRun.map(D=>D.label)],P=[`${x}${b}/${A.length} article${A.length===1?"":"s"} answered.`,...v.length?[`\u26A0 ${v.length} left untouched (their threads are still open, which is correct \u2014 nothing was promised to those reviewers): ${v.join(", ")}`]:[],...f.blocked?[`\u26A0 ${f.blocked}`]:[],...f.allEmpty?["\u26A0 No agent produced any work this run \u2014 nothing was changed or answered."]:[]];h({kind:"note",tone:f.aborted||v.length||f.blocked||f.allEmpty?"warn":"ok",text:P.join(`
|
|
468
|
+
`)});let W=new Set(v),F=[...d.rest??[],...u.filter(D=>W.has(D.label))];if(F.length>0&&!f.aborted&&d.report){let D=F.reduce((B,_)=>B+_.threads.length,0);h({kind:"note",tone:"info",text:`${D} comment${D===1?"":"s"} on ${F.length} other article${F.length===1?"":"s"} still open \u2014 pick the next one, or esc to stop here.`});let M={...d.report,threads:F.flatMap(B=>B.threads)};so(Ur(M,{width:Be()})),Lt({cursor:0,rows:Si(F),groups:F,resolve:d.resolve,report:M})}else if(F.length>0&&!f.aborted){let D=F.map(B=>B.path).filter(B=>!!B),M=D.length===F.length?St(D):void 0;J(M?D.length===1?`/comments ${M}`:`/comments --scope ${M}`:"/comments")}}}catch(f){h({kind:"note",tone:"error",text:`Answering comments failed: ${f.message}`})}finally{Ae.current=null,le(null),S(!1),Y(f=>f+1)}},[e,s,h,Ee,J,so,Be]),va=Z(async(u,d)=>{if(d?.skipReview===!0||d?.skipStyle===!0)await wt([u],0,{skipReview:d?.skipReview,skipStyle:d?.skipStyle,scope:u});else{let A=Uu(e,[u],{});if(!A.clear){h({kind:"note",tone:"warn",text:Bu(A,1).join(`
|
|
469
|
+
`)}),J(Vl(A,u));return}await fe(wl(u),{display:`/publish ${u}`,quietUser:!0})}let g=d?.skipReview?null:await So(e,s);g&&h({kind:"note",tone:"info",text:g});try{let A=await ai(e,s,u.replace(/\\/g,"/"));A.length>0&&(eo(`Related articles not yet published (${A.length}):`),X([`/publish --related ${u}`,...A.map(U=>`/publish ${U}`)]))}catch{}},[e,s,fe,wt]),Uy=Z(async(u,d)=>{S(!0);try{let c=await El(e,s,u,{skipReview:d.skipReview,skipStyle:d.skipStyle,onProgress:(A,U,O)=>Me(`Publishing ${A+1}/${U} \u2014 ${O}\u2026`)}),g=c.blocked.length+c.failed.length;h({kind:"note",tone:g>0?"warn":"ok",text:Dl(c).join(`
|
|
470
|
+
`)}),c.blocked.length>0?J("/review --blocked --fix"):Ee(null,null)}catch(c){h({kind:"note",tone:"error",text:`Publishing failed: ${c.message}`})}finally{Me(null),S(!1),Y(c=>c+1)}},[e,s,h,J,Ee]),gd=Z(async u=>{try{let d=await na({cwd:e,profileName:s}),{clean:c,conflicts:g}=Ln(d.entries);if(c.length===0){h({kind:"note",tone:"info",text:"Nothing new to publish \u2014 everything is already up to date on Document360."});return}await wt(c.map(A=>A.path),g.length,{skipReview:u?.skipReview,skipStyle:u?.skipStyle})}catch(d){h({kind:"note",tone:"warn",text:`Couldn\u2019t check what to publish (${d.message}) \u2014 your drafts are saved; run /publish when ready.`})}},[e,s,wt]),ms=Z(u=>{if(u)try{for(let d of Array.isArray(u)?u:[u]){let c=mu(e,d);if(!c)continue;Ii(e,c.title).ok&&h({kind:"note",tone:"ok",text:`\u2713 That completed a docs-campaign step \u2014 marked done: ${c.title}`});return}}catch{}},[e,h]),yd=Z(async(u,d)=>{let g=XS(u,3),A=Uo(e,"standard"),U=new Map,O=new Map;for(let b of u){let x=jn(e,b),v=el(e,b,x);if(v&&U.set(b,v),x!==null){let P=hl(x);P.length>0&&O.set(b,P)}}Dt.current=Date.now(),Gt(0),S(!0);let f=new AbortController;Ae.current=f,le({verb:"Authoring",unit:"spec",total:g.length,done:0,active:[],rows:Bn(g),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),h({kind:"note",tone:"info",text:`Authoring ${u.length} screenshot spec${u.length===1?"":"s"} in ${g.length} batch${g.length===1?"":"es"} (\u22646 agents at once) on ${A.model}${A.forced?" (forced)":""}\u2026 (esc to stop)`});let k=!1;try{for await(let b of Wo({cwd:e,partitions:g,promptFor:x=>$h(x,U,O),concurrency:6,profileName:s,allowProdWrites:Vt.current,model:A.model,signal:f.signal}))if(b.type==="partition_status")b.status==="running"?le(x=>x&&{...x,active:[...x.active,b.label],rows:_e(x.rows,b.label,"active"),lastAt:Date.now()}):le(x=>x&&{...x,active:x.active.filter(v=>v!==b.label),done:x.done+1,rows:_e(x.rows,b.label,b.status==="done"?"done":"failed"),lastAt:Date.now()});else if(b.type==="partition_event")le(x=>{if(!x)return x;let v={...x,lastAt:Date.now()};return b.event.type==="tool"?v.tools=x.tools+1:b.event.type==="text"&&(v.chars=x.chars+b.event.delta.length),v});else if(b.type==="run_done"){Jt(F=>F+b.totalCostUsd),Qt(F=>F+b.results.reduce((D,M)=>D+M.outputTokens,0));let x=b.results.filter(F=>F.ok).length,v=b.aborted?"Stopped. ":"";k=!b.aborted&&d.setup;let P=b.aborted?"":k?" Refreshing the staging checklist\u2026":` Next: /screenshot capture${d.scope?` ${d.scope}`:" --all"} (or /screenshot checklist first for the staging checklist).`,W=Ct(b,"Spec authoring");h({kind:"note",tone:W||b.aborted?"warn":b.ok?"ok":"warn",text:W?W.join(`
|
|
471
|
+
`):`${v}Authored specs \u2014 ${x}/${b.results.length} batches ok.${P}`}),W&&(J("/doctor"),k=!1),!b.aborted&&b.ok&&!W&&ms(d.runLine)}}catch(b){h({kind:"note",tone:"error",text:`Spec authoring failed: ${b.message}`})}finally{Ae.current=null,le(null),S(!1),Y(b=>b+1)}if(k){let b=await No();b.kind==="forward-to-agent"&&b.prompt&&await fe(b.prompt,{display:b.display,quietUser:!0}),pa()}},[e,s,h,fe,ms,pa]),wd=Z(async u=>{let d=el(e,u,jn(e,u))??void 0,c=await oi([u],void 0,{prior:d});c.kind==="forward-to-agent"&&c.prompt&&await fe(c.prompt,{display:c.display,quietUser:!0}),ih(e,u)&&Ee(`Spec ready \u2014 /screenshot capture ${u} takes the screenshot; bare /screenshot picks the next shot.`,{kind:"cmd",cmd:`/screenshot capture ${u}`,reason:""})},[e,fe,Ee]),gs=Z(async(u,d)=>{if(u.length===0)return{drawn:[],undrawn:[],cliMissing:!1};S(!0);let c=new AbortController;Ae.current=c,le({verb:"Drawing callouts",unit:"screenshot",total:u.length,done:0,active:[],rows:u.map(v=>({label:v,items:1,status:"pending"})),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()});let g=[],A=!1;try{let v=await jc({cwd:e,ids:u,...d.force?{force:!0}:{},signal:c.signal,onStart:P=>le(W=>W&&{...W,active:[P],rows:_e(W.rows,P,"active"),lastAt:Date.now()}),onDone:(P,W)=>le(F=>F&&{...F,active:[],done:F.done+1,rows:_e(F.rows,P,W==="failed"?"failed":"done"),lastAt:Date.now()})});g=v.results,A=v.cliMissing??!1}catch(v){h({kind:"note",tone:"error",text:`Drawing the callouts failed: ${v.message}`})}finally{Ae.current=null,le(null),S(!1),Y(v=>v+1)}if(A)return h({kind:"note",tone:"error",text:"d360-capture is not installed on this machine. Run: npm i -g document360-capture \u2014 then /screenshot annotate."}),{drawn:[],undrawn:u,cliMissing:!0};let U=g.filter(v=>v.outcome==="annotated").map(v=>v.id),O=g.filter(v=>v.outcome==="skipped").map(v=>v.id),f=u.filter(v=>!U.includes(v)&&!O.includes(v));if(h({kind:"note",tone:f.length?"warn":"ok",text:[`\u25C8 ${U.length} drawn`,O.length?`${O.length} already current`:"",f.length?`\u2717 ${f.length} not drawn`:""].filter(Boolean).join(" ")}),f.length>0){let v=Math.max(...f.map(P=>P.length));h({kind:"note",tone:"warn",text:f.map(P=>`\u2717 ${P.padEnd(v)} ${_r(g.find(W=>W.id===P)?.detail)||"no picture was produced"}`).join(`
|
|
472
472
|
`)+`
|
|
473
|
-
${f.length===1?"It has":"They have"} no publishable picture yet. Re-take the shot: /screenshot capture`})}if(d.chainVerify===!1||U.length===0)return{drawn:U,undrawn:f,cliMissing:!1};let k=U.filter(
|
|
474
|
-
`)}),{drawn:U,undrawn:f,cliMissing:!1}},[e,h,Ee,fe]),lr=Z(async(u,d)=>{if(!Fn(e)){await fe(
|
|
475
|
-
${
|
|
476
|
-
${k}`:"")});let b=Date.now(),
|
|
477
|
-
${
|
|
478
|
-
`)}),
|
|
479
|
-
`)})}
|
|
480
|
-
`)});return}let
|
|
481
|
-
`)}),Zt(Dn()),ir.current=kt(e).status==="current",ro.current=Ft(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,Xe,Zt]),
|
|
482
|
-
`)}),Zt(
|
|
483
|
-
${
|
|
484
|
-
`)})),Y(k=>k+1);return}case"genre":{let f=ge(e)?.appType??null;(await
|
|
485
|
-
`)});return}case"mcp":await
|
|
486
|
-
`)}),k&&h({kind:"note",tone:"warn",text:`\u26A0 ${k.why} \u2014 ${k.cmd} moves this repo.`});return}let f=[...
|
|
487
|
-
`:"",
|
|
488
|
-
Model: ${F.model}${F.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;h({kind:"note",tone:"info",text:
|
|
489
|
-
`)+
|
|
490
|
-
`):
|
|
491
|
-
`)}),K&&J("/doctor")}}catch(
|
|
473
|
+
${f.length===1?"It has":"They have"} no publishable picture yet. Re-take the shot: /screenshot capture`})}if(d.chainVerify===!1||U.length===0)return{drawn:U,undrawn:f,cliMissing:!1};let k=U.filter(v=>d.verifiedBefore.has(v)).length;if(k>vi){let v=tm({results:g,voidedVerdicts:k,...d.scope?{scope:d.scope}:{}});return v&&Ee(`${v.glyph} ${v.cmd} ${v.why}`,{kind:"cmd",cmd:v.cmd,reason:""},"warn"),{drawn:U,undrawn:f,cliMissing:!1}}let b=U.filter(v=>!d.verifiedBefore.has(v)||k>0);if(b.length===0)return{drawn:U,undrawn:f,cliMissing:!1};h({kind:"note",tone:"info",text:pn(b.length)}),await fe(Et(e,b),{display:"/screenshot verify",quietUser:!0});let x=Eo(e,b);return x.length>0&&h({kind:"note",tone:"info",text:x.join(`
|
|
474
|
+
`)}),{drawn:U,undrawn:f,cliMissing:!1}},[e,h,Ee,fe]),lr=Z(async(u,d)=>{if(!Fn(e)){await fe(Tc(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(!Gf(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)"}),S(!0),Me("Waiting for you to finish logging in (browser window)\u2026");let _=new AbortController;Ae.current=_;let K;try{K=await Vf({cwd:e,signal:_.signal})}catch(me){h({kind:"note",tone:"error",text:`Could not launch the login: ${me.message}`});return}finally{Ae.current=null,Me(null),S(!1)}if(K.exitCode!==0){Pc(K.exitCode,K.output)?h({kind:"note",tone:"error",text:"d360-capture is not installed on this machine. Run: npm i -g document360-capture \u2014 then /screenshot capture again."}):/unknown option/i.test(K.output)?h({kind:"note",tone:"warn",text:"Your d360-capture is older than this writer. Update it: npm i -g document360-capture \u2014 then /screenshot capture again."}):h({kind:"note",tone:_.signal.aborted?"warn":"error",text:_.signal.aborted?"Login cancelled \u2014 nothing saved.":`Login did not complete:
|
|
475
|
+
${Cc(K.output)}`});return}h({kind:"note",tone:"ok",text:"\u2713 Login saved \u2014 continuing with the capture."})}let c=new Map(u.map(_=>[_,ph(e,_)])),g=0;if(u.length>1){let _=u.filter(K=>c.get(K).mutates);if(_.length>0&&(g=_.length,u=u.filter(K=>!c.get(K).mutates),u.length===0)){h({kind:"note",tone:"warn",text:`\u26A0 All ${_.length} spec${_.length===1?"":"s"} in scope write real data, so a bulk run has nothing to do. Run one deliberately: /screenshot capture ${_[0]}`});return}}else if(u.length===1&&c.get(u[0]).mutates){let _=c.get(u[0]),K=Yf(e);h({kind:"note",tone:"warn",text:`\u26A0 This capture performs a REAL write in your app${_.what?`: ${dh(_.what)}`:_.declared?"":" (detected from the spec: form fill + commit click / file upload)"}. Running because you named it explicitly \u2014 check the result and clean up what it created. `+(K.production?`This profile is PRODUCTION \u2014 the write lands in the LIVE tenant${K.url?` (${K.url})`:""}. If the spec cleans up after itself, confirm it did.`:"Tip: point the capture scope (.d360-writer/capture.json) at a demo/non-production context for shots like this.")})}S(!0);let A=new AbortController;Ae.current=A;let U=u.map(_=>({label:_,items:1,status:"pending"}));le({verb:"Capturing",unit:"screenshot",total:u.length,done:0,active:[],rows:U,tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()});let O=Wt(e),f=Object.keys(O.shots).length>0,k=Kf(d?.heldBackBlocked??[],g);h({kind:"note",tone:"info",text:`Capturing ${u.length} screenshot${u.length===1?"":"s"} with d360-capture (a real browser drives your app)\u2026 (esc to stop)`+(k?`
|
|
476
|
+
${k}`:"")});let b=Date.now(),x=[];try{for(let _ of u){if(A.signal.aborted)break;le(Q=>Q&&{...Q,active:[_],rows:_e(Q.rows,_,"active"),lastAt:Date.now()});let{exitCode:K,output:me}=await Sc({cwd:e,id:_,signal:A.signal,stdio:"pipe"});if(Pc(K,me)){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=A.signal.aborted&&K!==0?"failed":Rc(e,_,K,b),Ie=Oe==="captured"?void 0:Oe==="skipped"?Hf(me)??"a data prerequisite isn't met \u2014 the spec's skip reason names what to stage":qf(me);x.push({id:_,outcome:Oe,detail:Ie}),le(Q=>Q&&{...Q,active:[],done:Q.done+1,rows:_e(Q.rows,_,Oe==="captured"?"done":"failed"),lastAt:Date.now()})}}catch(_){h({kind:"note",tone:"error",text:`Capture run failed: ${_.message}`})}finally{Ae.current=null,le(null),S(!1),Y(_=>_+1)}if(x.length===0)return;let v=x.filter(_=>_.outcome==="captured"),P=x.filter(_=>_.outcome==="skipped"),W=x.filter(_=>_.outcome==="failed"),F=u.length-x.length;h({kind:"note",tone:W.length?"warn":v.length?"ok":"info",text:[`\u2713 ${v.length} captured`,P.length?`\u2298 ${P.length} blocked`:"",W.length?`\u2717 ${W.length} broken`:"",F?`${F} not run (stopped)`:""].filter(Boolean).join(" ")+` ${x.length} run${g>0?` \xB7 ${g} held back`:""}`+Qf(zf(O,x),f).map(_=>`
|
|
477
|
+
${_}`).join("")});let D=Xf(P);if(D.length>0&&h({kind:"note",tone:"info",text:D.join(`
|
|
478
|
+
`)}),W.length>0){let _=Math.max(...W.map(K=>K.id.length));h({kind:"note",tone:"error",text:W.map(K=>`\u2717 ${K.id.padEnd(_)} ${_r(K.detail)}`).join(`
|
|
479
|
+
`)})}Gs(e,x.map(_=>({id:_.id,outcome:_.outcome,reason:_.detail,specSource:jn(e,_.id)})),new Date().toISOString()),x.length===u.length&&W.length===0&&P.length===0&&ms(d?.runLine);let M=[];if(v.length>0&&$i()){let _=await gs(v.map(K=>K.id),{verifiedBefore:new Set});if(_.cliMissing||(M=_.undrawn,_.drawn.length>0))return}else if(v.length>0){h({kind:"note",tone:"info",text:pn(v.length)}),await fe(Et(e,v.map(K=>K.id)),{display:"/screenshot verify",quietUser:!0});let _=Eo(e,v.map(K=>K.id));_.length>0&&h({kind:"note",tone:"info",text:_.join(`
|
|
480
|
+
`)});return}let B=Jf({results:x,ids:u,articles:Zf(e,v.map(_=>_.id)),...M.length>0?{unannotated:M}:{}});B&&Ee(B.note,{kind:"cmd",cmd:B.cmd,reason:""},B.tone)},[e,h,Ee,fe,ms,gs]),xa=Z(u=>{let d=qn(u);if(!d||gn(d)&&!d.refreshToken)return null;let c={...Go(d.idToken)??{},...Go(d.accessToken)??{}};return c.email??c.preferred_username??"signed in"},[]),Ra=Z((u,d)=>{if(d){let c=ge(e);c&&(c.defaultProfile=u,iy(c,e))}i(u),Xe(void 0,u),h({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${u}"${d?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),xa(u)||(h({kind:"note",tone:"warn",text:`Profile "${u}" is not signed in \u2014 sign in with /login.`}),J("/login")),Y(c=>c+1)},[e,h,Xe,xa,J]),ys=Z((u,d,c)=>{vs(e,u,d,c.id,c.name),h({kind:"note",tone:"ok",text:`Switched to workspace "${c.name??c.id}" (agent restarted).`}),Xe(),cy(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:go(mo(e)).join(`
|
|
481
|
+
`)}),Zt(Dn()),ir.current=kt(e).status==="current",ro.current=Ft(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,Xe,Zt]),ws=Z(async u=>{let d;try{d=await hr(e,u)}catch{h({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),J("/workspace");return}if(d.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=d.workspaces.filter(A=>(A.workspace_type??"").toLowerCase()!=="apidocumentation"),g=c.length>0?c:d.workspaces;if(g.length===1){let A=g[0],U=d.workspaces.length-g.length;h({kind:"note",tone:"ok",text:`Selected the "${A.name??A.id}" workspace${U>0?" (skipped the API-documentation workspace)":""}.`}),ys(d.profile,d.projectId,A);return}h({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${g.length} available).`}),J("/workspace")},[e,h,ys,J]),ks=Z((u,d)=>{xs(e,u,d.id,d.name),h({kind:"note",tone:"ok",text:`Project set to "${d.name??d.id}" (agent restarted).`}),Xe(),ws(u)},[e,h,Xe,ws]),kd=Z(async u=>{let d;try{d=ht(e,u)}catch{return}if(!d.project.workspaceId){if(d.project.projectId){if(!d.project.projectName)try{let{projects:c}=await tn(e,d.name),g=c.find(A=>A.id===d.project.projectId);g?.name&&aP(e,d.name,{projectName:g.name})}catch{}await ws(d.name);return}try{let{projects:c}=await tn(e,d.name);if(c.length===1){let g=c[0];h({kind:"note",tone:"ok",text:`Using your Document360 project "${g.name??g.id}".`}),ks(d.name,{id:g.id,name:g.name});return}if(c.length>1){let g=c.map(A=>({id:A.id,name:A.name??A.id,sub:A.sub_domain}));h({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),vn({cursor:0,current:-1,rows:g,profile:d.name,environment:d.connection.name});return}}catch{}h({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),J("/project")}},[e,h,ws,ks,J]),io=Z(()=>{let u=Re.current[0];if(!u)return;xt();let{plan:d,mode:c}=u;h({kind:"note",tone:"info",text:`\u25CF ${d.title} (${d.path})`});for(let U of d.notes)h({kind:"note",tone:"warn",text:`\u26A0 ${U}`});d.overwritesLocalChanges&&c==="pull"&&h({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let g=ut(d.oldContent,d.newContent,Be());h(g?{kind:"diff",added:g.added,removed:g.removed,lines:g.lines,hidden:g.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."});let A=Re.current.length;c==="conflict"?(h({kind:"note",tone:"warn",text:"Conflict \u2014 edited both here and on the portal (diff shows local \u2192 portal)."}),h({kind:"note",tone:"info",text:"Keep local (publish, overwrites portal) \xB7 take Portal (overwrites local) \xB7 Skip?"}),h({kind:"note",tone:"info",text:A>1?`(l/p/s \xB7 la/pa/sa for all ${A} \u2014 anything else cancels)`:"(l/p/s \u2014 anything else cancels)"})):h({kind:"note",tone:"info",text:A>1?`Write ${d.path}? (y/n \xB7 ya/na for all ${A} \u2014 anything else cancels)`:`Write ${d.path}? (y/n \u2014 anything else cancels)`})},[h,Be,xt]),cr=Z(()=>{if(Re.current.length>0){io();return}let u=wn.current;wn.current=[],u.length>0?(h({kind:"note",tone:"info",text:`Publishing ${u.length} kept-local article${u.length===1?"":"s"} over the portal\u2026`}),wt(u)):J("/pull")},[io,h,wt,J]),bd=Z(u=>{if(Re.current.length===0)return!1;let d=u.trim(),c=d.toLowerCase(),g=Re.current[0];if(g.mode==="conflict"){let U=vg(d);if(U){let O=Re.current.splice(0),f=O.length;if(U==="local"){for(let k of O)wn.current.push(k.plan.path);h({kind:"note",tone:"info",text:`Keeping local for all ${f} \u2014 will publish ${f===1?"it":"them"} over the portal.`})}else if(U==="portal"){let k=0;for(let b of O)try{ta({cwd:e,profileName:s},b.plan),k++}catch(x){h({kind:"note",tone:"error",text:`Take-portal failed for ${b.plan.path}: ${x.message}`})}h({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${k} article${k===1?"":"s"} (local overwritten, sync base advanced).`})}else h({kind:"note",tone:"info",text:`Skipped all ${f} \u2014 still conflict${f===1?"":"s"}.`});return cr(),!0}if(c==="l"||c==="local")Re.current.shift(),wn.current.push(g.plan.path),h({kind:"note",tone:"info",text:`Keeping local ${g.plan.path} \u2014 will publish over the portal.`});else if(c==="p"||c==="portal"){Re.current.shift();try{ta({cwd:e,profileName:s},g.plan),h({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${g.plan.path} (local overwritten, sync base advanced).`})}catch(O){h({kind:"note",tone:"error",text:`Take-portal failed: ${O.message}`})}}else if(c==="s"||c==="skip"||c==="n")Re.current.shift(),h({kind:"note",tone:"info",text:`Skipped ${g.plan.path} \u2014 still a conflict.`});else{let O=Re.current.length;return Re.current=[],wn.current=[],h({kind:"note",tone:"info",text:`Resolve cancelled (${O} conflict${O===1?"":"s"} left untouched).`}),!0}return cr(),!0}let A=xg(d);if(A){let U=Re.current.splice(0);if(A==="skip")h({kind:"note",tone:"info",text:`Skipped all ${U.length} article${U.length===1?"":"s"}.`});else{let O=0;for(let f of U)try{ta({cwd:e,profileName:s},f.plan),O++}catch(k){h({kind:"note",tone:"error",text:`Pull failed for ${f.plan.path}: ${k.message}`})}h({kind:"note",tone:"ok",text:`\u2713 Pulled ${O} article${O===1?"":"s"} (sync base advanced).`})}return cr(),!0}if(c==="y"||c==="yes"){let U=Re.current.shift().plan;try{ta({cwd:e,profileName:s},U),h({kind:"note",tone:"ok",text:`\u2713 Pulled ${U.path} (sync base advanced).`})}catch(O){h({kind:"note",tone:"error",text:`Pull failed: ${O.message}`})}}else if(c==="n"||c==="no"){let U=Re.current.shift().plan;h({kind:"note",tone:"info",text:`Skipped ${U.path}.`})}else{let U=Re.current.length;return Re.current=[],h({kind:"note",tone:"info",text:`Pull cancelled (${U} article(s) left untouched).`}),!0}return cr(),!0},[e,s,cr,h]),Ca=Z(async u=>{h({kind:"note",tone:"info",text:"Checking Document360 for conflicts\u2026"});try{let d=await na({cwd:e,profileName:s}),c=u?.replace(/\\/g,"/"),g=d.entries.filter(U=>U.status==="conflict"&&U.path).map(U=>U.path);if(c){if(!g.includes(c)){h({kind:"note",tone:"ok",text:`${c} isn\u2019t in conflict \u2014 nothing to resolve.`});return}g=[c]}if(g.length===0){h({kind:"note",tone:"ok",text:"\u2713 No conflicts \u2014 local and Document360 agree on every tracked article."});return}let A=[];for(let U of g)try{A.push({plan:await uy({cwd:e,profileName:s,relPath:U}),mode:"conflict"})}catch(O){h({kind:"note",tone:"error",text:`Could not load ${U} from Document360: ${O.message}`})}if(A.length===0)return;h({kind:"note",tone:"info",text:`Resolving ${A.length} conflict${A.length===1?"":"s"} \u2014 for each: keep local, take portal, or skip.`}),Re.current=A,wn.current=[],io()}catch(d){h({kind:"note",tone:"error",text:`Could not compute sync status: ${d.message}`})}},[e,s,h,io]),$d=Z(u=>{let d=Ko.current;if(!d)return!1;if(Ko.current=null,xt(),u.trim()!==d.repoName)return h({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:c,failed:g}=nu(e,d.targets);h({kind:"note",tone:g.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${c.length} item${c.length===1?"":"s"}. The repo is back to its original state.`});for(let A of g)h({kind:"note",tone:"error",text:` \u2717 ${A.path}: ${A.error}`});return d.hadDevhints&&(h({kind:"note",tone:"warn",text:_s().join(`
|
|
482
|
+
`)}),Zt(Ma())),h({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
|
|
483
|
+
${$y}`}),J("/init"),st(!1),!0},[e,h,Zt,xt,J]),ao=Z(async u=>{let d=u.slice(1).trim().split(/\s+/),c=(d[0]??"").toLowerCase(),g=d.slice(1);if(st(!0),Er(g)&&["write","lint","check","review","reorder"].includes(c)){let f=Ar(e,s);if(f.length===0){h({kind:"note",tone:"warn",text:"No categories yet \u2014 author some articles first, then scope to one."});return}let k=b=>c==="write"?`/write ${sf(g,b).join(" ")}`.trim():`/${c} ${[b,...g.filter(x=>x!=="--scope")].join(" ")}`.trim();if(f.length===1){ao(k(f[0].token));return}Rn({cursor:0,rows:f,run:b=>{ao(k(b))}});return}if(dn(c,g)){let f=c==="write"&&Dr(g).rewrite,k=c==="write"?lc(e,my(e),{rewrite:f}):Ar(e,s);if(k.length>1){let b=g.filter(M=>M.startsWith("--")).join(" "),x=M=>M==="--blocked"?`/${c} --blocked${b?` ${b}`:""}`.trim():`/${c}${M?` ${c==="write"?`--scope ${M}`:M}`:""}${b?` ${b}`:""} ${M?"":"--all"}`.replace(/\s+/g," ").trim(),v=k.reduce((M,B)=>M+B.count,0),P={token:"",label:c==="review"?`Everything \u2014 all ${v} articles + structure (IA) review`:c==="reorder"?`Everything \u2014 reorder all ${k.length} categories`:f?`Everything \u2014 rewrite all ${v} planned articles`:`Everything \u2014 write all ${v} pending article${v===1?"":"s"}`,count:v},W=c==="review"?Vr(e):[],F=W.length>0&&W.length<v?[{token:"--blocked",label:`Only what needs review \u2014 ${W.length} article${W.length===1?"":"s"} publishing is blocked on`,count:W.length}]:[],D=c==="write"?`Write which articles? (counts = ${f?"articles to regenerate":"still to write"})`:c==="review"?"Review what? (counts = articles)":"Reorder what?";Rn({cursor:0,rows:[...F,P,...k],run:M=>{ao(x(M))},title:D});return}}let A=async f=>{let k=$c(f);if(!Fn(e)){await fe(Tc(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(k.mode==="single"){await lr([k.id],{runLine:[`/screenshot capture ${k.id}`,`/capture ${k.id}`]});return}if(k.mode==="failed"){let x=vc(e,Mr(e).rows);if(x.length===0){h({kind:"note",tone:"info",text:"No broken specs to re-run \u2014 /screenshot list shows where things stand."}),J("/screenshot list");return}await lr(x);return}if(k.mode==="blocked"){let{blocked:x,rows:v}=Mr(e);if(x.length===0){h({kind:"note",tone:"info",text:"No shots are waiting on app data \u2014 /screenshot list shows where things stand."}),J("/screenshot list");return}let P=vr(v.filter(W=>W.state==="blocked")).length;h({kind:"note",tone:"info",text:`Re-running ${x.length} shot${x.length===1?"":"s"} that skipped on missing data last run.`+(P>0?` If you haven't staged ${P===1?"it":"those "+P+" things"} yet, ${x.length===1?"it":"they"} will skip again \u2014 /screenshot list has the worklist.`:"")}),await lr(x,{runLine:["/screenshot capture --blocked","/screenshot capture --all --retry-blocked"]});return}if(k.mode==="all"||k.mode==="scope"){let x=k.mode==="scope"?k.scope:void 0,{ready:v,captured:P,blocked:W,rows:F}=Mr(e,x),D=[...v,...P,...k.retryBlocked?W:[]];if(D.length===0&&W.length>0&&!k.retryBlocked){let B=x?`/screenshot capture ${x} --retry-blocked`:"/screenshot capture --blocked";Ee(`All ${W.length} shot${W.length===1?"":"s"} in scope ${W.length===1?"is":"are"} blocked on data that wasn't staged last run \u2014 /screenshot list shows what to stage, then ${B}.`,{kind:"cmd",cmd:"/screenshot list",reason:""},"warn");return}if(D.length===0){h({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),J("/screenshot");return}if(!k.retryBlocked){let B=x?`/screenshot capture ${x} --retry-blocked`:"/screenshot capture --blocked",_=xc(F.filter(K=>K.state==="blocked"),B);_&&h({kind:"note",tone:"info",text:_})}let M=k.mode==="scope"?[`/screenshot capture ${k.scope}`,`/capture ${k.scope}`]:["/screenshot capture --all","/capture --all"];await lr(D,{runLine:M,...k.retryBlocked?{}:{heldBackBlocked:F.filter(B=>B.state==="blocked")}});return}let b=Bf(Le(e));if(b.length===0){h({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),J("/screenshot");return}xn({cursor:0,rows:b,title:"Capture screenshots \u2014 pick what to shoot:"})},U=async f=>{let k=Ec(f);if(!Fn(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."}),J("/screenshot capture");return}let b=nt();if(!$i(b)){h({kind:"note",tone:"info",text:Nc(b)}),J("/update");return}let x=k.mode==="scope"?k.scope:void 0,{pending:v,done:P,rows:W}=Dc(e,x),F=k.mode==="all"||k.mode==="scope"?k.force:!1,D=k.mode==="single"?[k.id]:F?[...v,...P]:v;if(D.length===0){h({kind:"note",tone:"info",text:P.length>0?`Every shot${x?` under ${x}`:""} 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."}),J(P.length>0?"/screenshot annotate --all --force":"/screenshot capture");return}await gs(D,{force:F,scope:x,verifiedBefore:new Set(W.filter(M=>M.state==="verified").map(M=>M.id))})},O=async()=>{let f=await No();f.kind==="forward-to-agent"&&f.prompt&&await fe(f.prompt,{display:f.display,quietUser:!0}),pa()};switch(c){case"help":Tn({tab:0,scroll:0});return;case"exit":case"quit":mt.current?.close(),r();return;case"clear":Xe(),Kn.current=[],Ye.current={printed:[],armed:[],printedAt:no.current},st(!1),xt(),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 f;try{f=ht(e,s)}catch(k){h({kind:"note",tone:"error",text:k.message});return}h({kind:"note",tone:"info",text:`Profile "${f.name}" \u2192 ${f.connection.name} (${f.connection.apiUrl})${f.production?" \u26A0 PRODUCTION":""}`}),I(!0);try{let k=await PS(f.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},x=>h({kind:"note",tone:"info",text:x})),b=TS(f.name,k);if(AS(b),await Ea(b,f.name,x=>h({kind:"note",tone:"info",text:x})),h({kind:"note",tone:"ok",text:`\u2713 Logged in to "${f.name}" as ${Ss(b)}`}),await kd(s),Zo.current){let x=Zo.current;Zo.current=null;let v=Ve(e,s);v.ok?(h({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 tab to run ${x}.`}),J(x)):(h({kind:"note",tone:"warn",text:`${v.reason} (then ${x}.)`}),J("/login"),Zo.current=x)}else Jo.current&&(Ke(Jo.current,"\u21E5 tab to re-send your last prompt\u2026"),Jo.current=null)}catch(k){h({kind:"note",tone:"error",text:`Login failed: ${k.message}`})}finally{I(!1),Y(k=>k+1)}return}case"allow-prod":{let f=!1;try{f=ht(e,s).production}catch{}if(!f){h({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}Vt.current=!0,Xe(),h({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let f=gc(g.join(" ")),k=Nt.current.uuid;if(!k){if(!f){h({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}aa.current=f,kn(f),_o(`${zi} ${f}`),h({kind:"note",tone:"ok",text:`Session will be named "${f}" once it starts.`});return}if(!f){h({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let b=Nt.current.firstPrompt??"";sy(b,e).then(x=>{x?(Ke(`/rename ${x}`),h({kind:"note",tone:"info",text:`Suggestion: "${x}" \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}WS(k,f),kn(f),_o(`${zi} ${f}`),h({kind:"note",tone:"ok",text:`Session renamed to "${f}".`});return}case"profile":{let f=g[0],k=ge(e);if(!f){let b=Object.entries(k?.profiles??{});if(b.length===0){h({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let x=b.map(([W,F])=>({name:W,env:F.connection?.environment??"custom",prod:F.production===!0,who:xa(W)})),v=s??k?.defaultProfile,P=Math.max(0,x.findIndex(W=>W.name===v));zn({cursor:P,current:P,rows:x});return}if(f==="add"){let b=yc(e,g[1],g[2]);if(b){h({kind:"note",tone:"error",text:b});return}h({kind:"note",tone:"ok",text:`\u2713 Profile "${g[1]}" created (environment: ${g[2]??g[1]}).`}),Ra(g[1],!0);return}if(!k?.profiles?.[f]){h({kind:"note",tone:"error",text:`Unknown profile "${f}". Create it: /profile add ${f} <environment>`});return}Ra(f,!0);return}case"doctor":await Ir(g,{cwd:e,version:o});return;case"style-guide":{let f=await Di(g,{cwd:e,profileName:s});f.kind==="clear"?(Xe(),h({kind:"note",tone:"ok",text:"\u2713 Agent restarted \u2014 it now writes to the new rules."})):f.kind==="forward-to-agent"&&((await fe(f.prompt,{display:f.display,quietUser:!0})).producedNothing||h({kind:"note",tone:"info",text:Em().join(`
|
|
484
|
+
`)})),Y(k=>k+1);return}case"genre":{let f=ge(e)?.appType??null;(await Ni(g,{cwd:e})).kind==="clear"&&(ge(e)?.appType??null)!==f&&(Xe(),h({kind:"note",tone:"ok",text:"\u2713 Agent restarted \u2014 the doc-craft playbook for this genre is now loaded."}));try{Bt.current=!(ge(e)?.appType??ly(e))}catch{}Y(b=>b+1);return}case"roadmap":{if(g[0]?.toLowerCase()==="done"){let f=Ii(e,g.slice(1).join(" ").trim());h({kind:"note",tone:f.ok?"ok":"warn",text:f.line}),Y(k=>k+1);return}h({kind:"note",tone:"info",text:fu(e).join(`
|
|
485
|
+
`)});return}case"mcp":await Ws(g);return;case"init":{if(ge(e)){let k=nn(e,s);h({kind:"note",tone:"info",text:["This repo is already set up \u2014 /init won\u2019t overwrite it.",` Change environment: /profile add <${dy().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(`
|
|
486
|
+
`)}),k&&h({kind:"note",tone:"warn",text:`\u26A0 ${k.why} \u2014 ${k.cmd} moves this repo.`});return}let f=[...dy(),...KS().filter(k=>py(k))].map(k=>({name:k,apiUrl:zS(k).apiUrl,note:py(k)?"being retired":null}));Xn({cursor:0,rows:f});return}case"resume":{let f=g.join(" ").trim(),k=FS(e).filter(v=>v.uuid!==Nt.current.uuid);if(!f){if(!k.length){h({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}Pn({query:"",cursor:0,sessions:k});return}let b=MS(e,f);if(!b){h({kind:"note",tone:"error",text:`No session matches "${f}".`});return}Xe(b.uuid),Nt.current={uuid:b.uuid,firstPrompt:b.firstPrompt,titleFired:!0},kn(b.name),_u(b.uuid),Kn.current=[],Ye.current={printed:[],armed:[],printedAt:no.current};let x=Au(e,b.uuid);for(let v of x)h(v);h({kind:"note",tone:"ok",text:x.length?`Resumed "${b.name}" \u2014 restored ${x.length} message(s); continue where you left off.`:`Resumed "${b.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let f=g.join(" ").trim(),k;try{k=await hr(e,s)}catch(x){h({kind:"note",tone:"error",text:`Could not list workspaces: ${x.message}`});return}if(!f){let x=k.workspaces.map(P=>({id:P.id,name:P.name??P.id,type:P.workspace_type}));if(x.length===0){h({kind:"note",tone:"info",text:"No workspaces in this project."});return}let v=Math.max(0,x.findIndex(P=>P.id===k.current));Qn({cursor:v,current:v,rows:x,profile:k.profile,projectId:k.projectId,projectName:k.projectName,environment:k.environment});return}let b=Ta(k.workspaces,f);if(!b){h({kind:"note",tone:"error",text:`No workspace matches "${f}".`});return}ys(k.profile,k.projectId,b);return}case"project":{let f=g.join(" ").trim(),k;try{k=await tn(e,s)}catch(x){h({kind:"note",tone:"error",text:`Could not list projects: ${x.message} (signed in? try /login)`});return}if(!f){let x=k.projects.map(P=>({id:P.id,name:P.name??P.id,sub:P.sub_domain}));if(x.length===0){h({kind:"note",tone:"info",text:"No projects found for this identity."});return}let v=x.findIndex(P=>P.id===k.current);vn({cursor:Math.max(0,v),current:v,rows:x,profile:k.profile,environment:k.environment});return}let b=Aa(k.projects,f);if(!b){h({kind:"note",tone:"error",text:`No project matches "${f}". Available: ${k.projects.map(x=>x.name??x.id).join(", ")}`});return}ks(k.profile,b);return}case"logout":{let f;try{f=ht(e,s).name}catch(b){h({kind:"note",tone:"error",text:b.message});return}let k=jS(f);IS(e,f),Xe(),Y(b=>b+1),h({kind:"note",tone:k?"ok":"info",text:k?`\u2713 Signed out of "${f}" and cleared its project/workspace selection.`:`Profile "${f}" was not signed in. Cleared any project/workspace selection.`}),h({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),J("/login");return}case"publish":{if(Pl(g)){let P=Ut("publish");P&&h({kind:"note",tone:"info",text:P}),await ao(`/push ${g.join(" ")}`.trim());return}if(!oo(u.trim()))return;let f=Ut("publish");f&&h({kind:"note",tone:"info",text:f});let k=g.find(P=>!P.startsWith("--")),b={skipReview:g.includes(ct),skipStyle:g.includes(by)};Me("Checking what is waiting to go live\u2026");let x;try{x=await Tl(e,s,k)}catch(P){h({kind:"note",tone:"error",text:`Could not check Document360: ${P.message}`});return}finally{Me(null)}if(x.length===0){let P=Al(e,s,k);for(let W of P.lines)h({kind:"note",tone:W.startsWith("\u2713")?"ok":"info",text:W});P.ahead>0&&J(be("/push","",k));return}let v=Uu(e,x.map(P=>P.path),{allowUnreviewed:b.skipReview,allowStyleErrors:b.skipStyle});if(!v.clear){for(let P of Bu(v,x.length,k))h({kind:"note",tone:"warn",text:P});J(be("/review","--blocked --fix",k));return}h({kind:"note",tone:"info",text:`${x.length} draft${x.length===1?" is":"s are"} ahead of what readers see. Pick what goes live:`}),Zn({cursor:0,rows:x,opts:b});return}case"push":{if(!oo(u.trim()))return;let f=g.includes(ct),k=g.includes(by);if(g.includes("--screenshots")||g.includes("--shots")){let P=g.find(B=>!B.startsWith("--")),W=Le(e),F=Js(W,P);if(F.length===0){let B=W.filter(_=>_.state==="captured").length;h({kind:"note",tone:"info",text:B>0?`${B} screenshot${B===1?" has":"s have"} been taken but the callouts aren't drawn on yet, so there is nothing to embed \u2014 /screenshot annotate finishes ${B===1?"it":"them"}.`:P?`No captured screenshots in ${P} \u2014 /publish --screenshots covers the whole knowledge base.`:"No captured screenshots yet \u2014 /screenshot capture first."}),B>0&&J("/screenshot annotate");return}let D=Zs(W,P);D&&h({kind:"note",tone:"warn",text:D});let M=ei(W);M&&h({kind:"note",tone:"warn",text:M}),h({kind:"note",tone:"info",text:`Re-saving ${F.length} article${F.length===1?"":"s"} with captured screenshots so the images embed\u2026`}),await wt(F,0,{skipReview:f,skipStyle:k,scope:be("","--screenshots",P).trim()});return}if(g[0]==="--related"&&g[1]){let P=await ai(e,s,g[1].replace(/\\/g,"/"));if(P.length===0){h({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await wt(P,0,{skipReview:f,skipStyle:k,scope:`--related ${g[1]}`});return}let b=g.filter(P=>!P.startsWith("--"));if(b[0]){await va(b[0],{skipReview:f,skipStyle:k});return}let x=g.includes("--all"),v=g.includes("--force");h({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let P=await na({cwd:e,profileName:s}),{clean:W,conflicts:F}=Ln(P.entries),D=x&&v&&F.length>0,M=si(P.entries);if(M>0&&h({kind:"note",tone:"warn",text:`\u26A0 ${M} article${M===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.`}),F.length>0&&!D&&h({kind:"note",tone:"warn",text:In(F.length)}),W.length===0&&!D){let B=Co(e,s);if(B&&h({kind:"note",tone:"info",text:B}),F.length>0){J("/resolve");return}h({kind:"note",tone:"ok",text:M>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let _=P.counts["unknown-base"]??0;_>0&&h({kind:"note",tone:"info",text:`(${_} article(s) have no sync base yet \u2014 publish those by path if needed.)`}),Me("Reconciling structure on Document360 (order + related articles)\u2026");try{let K=await Fu({cwd:e,profileName:s,onRateLimit:Ie=>Me(`Document360 rate limit \u2014 waiting ${Math.ceil(Ie.waitMs/1e3)}s\u2026`)}),me=ky(await wy({cwd:e,profileName:s})),Oe=Wu(K);Oe?h({kind:"note",tone:Oe.startsWith("\u26A0")?"warn":"info",text:Oe}):K.skipped&&h({kind:"note",tone:"warn",text:`Order sync skipped: ${K.skipped}`}),me&&h({kind:"note",tone:"info",text:me}),K.failures?.length?J("/structure"):(h({kind:"note",tone:"ok",text:Oe||me?"\u2713 Structure synced to Document360 \u2014 /structure shows the new category + article order.":"\u2713 Already in order \u2014 nothing to change."}),(Oe||me)&&J("/structure"))}catch(K){h({kind:"note",tone:"warn",text:`Structure sync failed: ${K.message}`})}finally{Me(null)}return}if(x){let B=(D?[...W,...F]:W).map(_=>_.path);await wt(B,D?0:F.length,{skipReview:f,skipStyle:k});return}Jn({cursor:0,rows:Eh(W,F),conflicts:F.length})}catch(P){h({kind:"note",tone:"error",text:`Could not compute sync status: ${P.message}`}),h({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"resolve":{if(!oo(u.trim()))return;await Ca(g.find(f=>!f.startsWith("--")));return}case"preview":{let f=g.join(" ").trim();if(!f){let b=[];try{b=Object.keys(cy(e,ht(e,s).name)?.articles??{})}catch{}if(b.length===0){h({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}Cn({query:"",cursor:0,paths:b});return}let k=CS(f)?f:Ou(e,f);if(Fo(k)){try{h({kind:"preview",name:ts(k),text:Ry(ea(k,"utf8"))})}catch(b){h({kind:"note",tone:"error",text:`Could not read ${k}: ${b.message}`})}return}if(vP.test(f)){try{let b=ht(e,s),x={profile:b.name,connection:b.connection},v=b.project.projectId??DS(x),P=await NS(x,v,f);h({kind:"preview",name:P.title??f,text:P.content??"*(article has no content)*"})}catch(b){h({kind:"note",tone:"error",text:`Could not fetch article: ${b.message}`})}return}h({kind:"note",tone:"error",text:`"${f}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let f=g[0]?.trim();if(!f){let v=ki(qu(e));$n({cursor:v,current:v});return}let{lines:k,changed:b,effective:x}=jr(e,f);for(let v of k)h({kind:"note",tone:v.startsWith("\u26A0")?"warn":v.startsWith("\u2713")?"ok":"info",text:v});b&&(rd(v=>v+1),mt.current?.setModel(x));return}case"verbose":{let f=g[0]?.trim().toLowerCase(),k=f==="on"?!0:f==="off"?!1:!rs.current;rs.current=k;try{BS({...ay(),verboseTranscript:k})}catch{h({kind:"note",tone:"warn",text:"\u26A0 Applied for this session, but the setting could not be saved."})}h({kind:"note",tone:"ok",text:k?"\u2713 Verbose transcript ON \u2014 every tool call with its file path and full result.":"\u2713 Verbose transcript OFF \u2014 doc work shown by article; my bookkeeping collapsed to one line."});return}case"convert":{if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:f,run:k}=Wl(g),b=JS(e,s);if(b.length===0){h({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let x=Ul(b,f);if(x.length===0){h({kind:"note",tone:"error",text:`No tracked articles under "${f}". (${b.length} are tracked overall.)`});return}let v=Mu(x),P=3,W=`/convert${f?` --scope ${f}`:""} --run`,F=Uo(e,"light");if(!k){let M=fy({files:Bl(e,x),op:"convert",model:F.model}),B=f?`Scope: ${f} (${x.length} of ${b.length} tracked)
|
|
487
|
+
`:"",_=`
|
|
488
|
+
Model: ${F.model}${F.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;h({kind:"note",tone:"info",text:B+ql(v,M,P).join(`
|
|
489
|
+
`)+_}),J(W);return}Dt.current=Date.now(),Gt(0),S(!0);let D=new AbortController;Ae.current=D,le({verb:"Converting",total:v.length,done:0,active:[],rows:Bn(v),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),h({kind:"note",tone:"info",text:`Converting ${x.length} articles in ${v.length} batches (\u2264${P} agents at once) on ${F.model}\u2026 (esc to stop)`});try{for await(let M of Wo({cwd:e,partitions:v,promptFor:Hl,concurrency:P,profileName:s,allowProdWrites:Vt.current,model:F.model,signal:D.signal}))if(M.type==="partition_status")M.status==="running"?le(B=>B&&{...B,active:[...B.active,M.label],rows:_e(B.rows,M.label,"active"),lastAt:Date.now()}):le(B=>B&&{...B,active:B.active.filter(_=>_!==M.label),done:B.done+1,rows:_e(B.rows,M.label,M.status==="done"?"done":"failed"),lastAt:Date.now()});else if(M.type==="partition_event")le(B=>{if(!B)return B;let _={...B,lastAt:Date.now()};return M.event.type==="tool"?_.tools=B.tools+1:M.event.type==="text"&&(_.chars=B.chars+M.event.delta.length),_});else if(M.type==="run_done"){Jt(me=>me+M.totalCostUsd),Qt(me=>me+M.results.reduce((Oe,Ie)=>Oe+Ie.outputTokens,0));let B=M.aborted?"Stopped. ":"",_=t.kind==="api"?"api":"subscription",K=Ct(M,"The conversion");h({kind:"note",tone:K||M.aborted?"warn":M.ok?"ok":"warn",text:K?K.join(`
|
|
490
|
+
`):B+Gl(M.results,v,_).join(`
|
|
491
|
+
`)}),K&&J("/doctor")}}catch(M){h({kind:"note",tone:"error",text:`Convert run failed: ${M.message}`})}finally{Ae.current=null,le(null),S(!1),Y(M=>M+1)}return}case"write":{if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let f=my(e);if(f.length===0){h({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:k,path:b,preview:x,concurrency:v,rewrite:P}=Dr(g);if(!b&&!x&&!(ge(e)?.appType??ly(e))){h({kind:"note",tone:"warn",text:`\u26A0 No doc genre is set, so no doc-craft playbook would load \u2014 all ${f.length} articles would be written generically.
|
|
492
492
|
Pick the genre below (one keypress), then run /write again \u2014 it changes structure, titles and depth for every article.
|
|
493
|
-
Not blocked: /write <path> still authors a single article, and /write --preview costs nothing.`}),X(
|
|
493
|
+
Not blocked: /write <path> still authors a single article, and /write --preview costs nothing.`}),X(Oi.options.map(Q=>({cmd:Q.cmd,desc:Q.desc}))),eo(Oi.title);return}let{docsDir:W,targets:F,reason:D,rewriting:M}=yi(e,f,{scope:k,path:b,rewrite:P});if(F.length===0){h({kind:"note",tone:"warn",text:D??"Nothing to write."});return}M&&h({kind:"note",tone:"warn",text:`--rewrite: regenerating ${F.length} already-written article${F.length===1?"":"s"} (overwrites them; git has your baseline).`});let B=Mu(F),_=Zl(v),K=Uo(e,"standard"),me=!!b;if(x&&!me){let Q=fy({files:tc(e,f,F),op:"write",model:K.model}),je=k?`Scope: ${k} (${F.length} pending)
|
|
494
494
|
`:"",He=`
|
|
495
|
-
Model: ${K.model}${K.forced?" (forced)":" \u2014 authoring; /model to override"}`;h({kind:"note",tone:"info",text:je+
|
|
496
|
-
`)+He}),J(`/write${k?` --scope ${k}`:""}`);return}Dt.current=Date.now(),Gt(0),S(!0);let Oe=new AbortController;Ae.current=Oe,le({verb:"Writing",total:
|
|
497
|
-
`):je+
|
|
498
|
-
`)}),
|
|
499
|
-
`)})}if(!Q.aborted&&Q.ok){let qe=k??b??"",lt=qe?` ${qe}`:"",En=co.some(
|
|
495
|
+
Model: ${K.model}${K.forced?" (forced)":" \u2014 authoring; /model to override"}`;h({kind:"note",tone:"info",text:je+oc(B,Q,_).join(`
|
|
496
|
+
`)+He}),J(`/write${k?` --scope ${k}`:""}`);return}Dt.current=Date.now(),Gt(0),S(!0);let Oe=new AbortController;Ae.current=Oe,le({verb:"Writing",total:B.length,done:0,active:[],rows:Bn(B),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),h({kind:"note",tone:"info",text:`Writing ${F.length} article${F.length===1?"":"s"} in ${B.length} batch${B.length===1?"":"es"} (\u2264${_} agents at once) on ${K.model}${K.forced?" (forced)":""}\u2026 (esc to stop)`});let Ie=new Set;try{for await(let Q of Wo({cwd:e,partitions:B,promptFor:je=>nc(je,W,{rewrite:M||me}),concurrency:_,profileName:s,allowProdWrites:Vt.current,model:K.model,signal:Oe.signal}))if(Q.type==="partition_status")Q.status==="running"?le(je=>je&&{...je,active:[...je.active,Q.label],rows:_e(je.rows,Q.label,"active"),lastAt:Date.now()}):le(je=>je&&{...je,active:je.active.filter(He=>He!==Q.label),done:je.done+1,rows:_e(je.rows,Q.label,Q.status==="done"?"done":"failed"),lastAt:Date.now()});else if(Q.type==="partition_event"){let je=null;if(Q.event.type==="tool"){let He=Wg(Q.event.name,Q.event.input,B[Q.index]?.paths??[]);He&&!Ie.has(He)&&(Ie.add(He),je=Q.label)}le(He=>{if(!He)return He;let Rt={...He,lastAt:Date.now()};return Q.event.type==="tool"?Rt.tools=He.tools+1:Q.event.type==="text"&&(Rt.chars=He.chars+Q.event.delta.length),je&&(Rt.rows=Fg(Rt.rows,je)),Rt})}else if(Q.type==="run_done"){Jt(qe=>qe+Q.totalCostUsd),Qt(qe=>qe+Q.results.reduce((lt,En)=>lt+En.outputTokens,0));let je=Q.aborted?"Stopped. ":"",He=t.kind==="api"?"api":"subscription",Rt=Ct(Q,"The write");if(h({kind:"note",tone:Rt||Q.aborted?"warn":Q.ok?"ok":"warn",text:Rt?Rt.join(`
|
|
497
|
+
`):je+rc(Q.results,B,He,k??b).join(`
|
|
498
|
+
`)}),Rt){J("/doctor");continue}let Cd=Hs(Q);if(Cd&&h({kind:"note",tone:"warn",text:Cd}),!Q.aborted&&Q.ok)try{let qe=(Ie.size>0?[...Ie]:F).map(lt=>`${W}/${lt}`);Bo(e,qe,{writtenCap:iP,reviewedCap:0,checkedCap:0})}catch{}let co=Q.aborted?[]:Nr(e,W,F),Sd=sc(co);Sd&&h({kind:"note",tone:"warn",text:Sd});let uo=Q.aborted||g.includes("--skip-style")?null:ic(co);if(uo){let qe=uo.errors.length,lt=await fs({partitions:uo.partitions,promptFor:uo.promptFor,concurrency:To,verb:"Fixing",doneNoun:"fixed",headline:`${qe} style error${qe===1?"":"s"} in ${uo.articles} of the new article${uo.articles===1?"":"s"} \u2014 fixing now, one pass`});if(lt.covered.length>0)try{Bo(e,lt.covered,Qe("lint"))}catch{}co=Nr(e,W,F);let En=ac(qe,co);h({kind:"note",tone:En[0].startsWith("\u2713")?"ok":"warn",text:En.join(`
|
|
499
|
+
`)})}if(!Q.aborted&&Q.ok){let qe=k??b??"",lt=qe?` ${qe}`:"",En=co.some(Pa=>Pa.severity==="error"),Pd=qe?"/publish":"/publish --all",qy=qe?`/screenshot author ${qe}`:"/screenshot author --all";Ee(En?`Written, but ${co.filter(Pa=>Pa.severity==="error").length} style error(s) are still unfixed. /lint${lt} --fix retries them, then /review${lt} --fix for editorial quality, then ${Pd}.`:`Written. I\u2019d run /review${lt} --fix next \u2014 editorial review that applies its fixes \u2014 then ${Pd} pushes the drafts up (add ${qy} first if you want images).`,{kind:"cmd",cmd:En?`/lint${lt} --fix`:`/review${lt} --fix`,reason:""})}}}catch(Q){h({kind:"note",tone:"error",text:`Write run failed: ${Q.message}`})}finally{Ae.current=null,le(null),S(!1),Y(Q=>Q+1)}return}case"draft":{if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:f,looseDocs:k}=cc(e);if(f.length===0&&k===0){h({kind:"note",tone:"info",text:dc});return}let b=g.join(" ").trim();if(!b&&f.length>1){h({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
|
|
500
500
|
${f.map(P=>` \u2022 ${P.name} (${P.docCount} doc${P.docCount===1?"":"s"})`).join(`
|
|
501
|
-
`)}`}),X(f.map(P=>`/draft ${P.name}`));return}let
|
|
502
|
-
`)});return}if(f==="--baseline"){let
|
|
501
|
+
`)}`}),X(f.map(P=>`/draft ${P.name}`));return}let x="",v;if(b){let P=uc(f,b);P?x=P:v=b}else x=f[0]?.name??"";await fe(wi(x,v),{display:b?`/draft ${b}`:"/draft",quietUser:!0});return}case"pull":{if(!oo(u.trim()))return;let f=g.find(k=>k.startsWith("--"));try{if(f==="--status"){h({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let x=Date.now(),v=await na({cwd:e,profileName:s});h({kind:"note",tone:"info",text:ui(v,Date.now()-x).join(`
|
|
502
|
+
`)});return}if(f==="--baseline"){let x=g.find(F=>!F.startsWith("--")),v=x?x.replace(/\\/g,"/"):void 0;h({kind:"note",tone:"info",text:v?`Setting the sync baseline for ${v}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let P=await GS({cwd:e,profileName:s,relPaths:v?[v]:void 0}),W=v?{rebaselined:[],skipped:[]}:await VS({cwd:e,profileName:s});if(P.baselined.length===0&&P.skipped.length===0&&W.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.`}),W.rebaselined.length>0&&h({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${W.rebaselined.length} article${W.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),P.skipped.length>0&&h({kind:"note",tone:"warn",text:`${P.skipped.length} skipped:
|
|
503
503
|
${P.skipped.map(F=>` - ${F.path} (${F.reason})`).join(`
|
|
504
|
-
`)}`}),Y(F=>F+1);return}if(f==="--compare"){h({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let
|
|
505
|
-
`)});return}if(f){h({kind:"note",tone:"error",text:`Unknown option: ${f} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let k=g[0];if(k){let
|
|
506
|
-
`)});let F=Pr({cwd:e,after:P,before:
|
|
507
|
-
`)}),
|
|
508
|
-
`)});return}case"reorder":{let f=
|
|
509
|
-
`)}),Zt(Dn()),ir.current=kt(e).status==="current",ro.current=Ft(e);return}case"discover":{if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await fe(
|
|
510
|
-
`)});return}if(f.answer&&(f.all||f.scope.path||f.scope.scope||b.length===1)){so(
|
|
511
|
-
`)});return}if(f.mode==="list"){if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let
|
|
512
|
-
`)});let
|
|
513
|
-
`)}),k&&h({kind:"note",tone:"info",text:k});let F=
|
|
514
|
-
`)}),Ke(ns(e));return}default:h({kind:"note",tone:"error",text:`Unknown command: /${c} \u2014 type /help.`})}},[e,r,s,io,Sa,h,Xe,fe,wt,xa,yd]),$s=Z(u=>{let d=(u??w).trim();if($(""),rs(null),Vn(0),d.startsWith("/")&&(Re.current=!1,Se.current=!1,Fe.current=null,xt(),eo(null),X(g=>Ug(g,d))),!d||($t(!1),(Ko.current||xe.current.length>0)&&h({kind:"user",text:d}),kd(d))||wd(d))return;aa.current.push(d);let c=Gg(d,Yu.current);if(d.startsWith("/"))h({kind:"user",text:d}),ue(!0),ao(c).finally(()=>ue(!1));else if(aP(c)){h({kind:"user",text:d});let g=lP(c);if(!g)fe(c,{display:d,quietUser:!0});else{try{cP(e,{title:g,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}fe(`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${g}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${g}" and the article path(s) you wrote.`,{display:d,quietUser:!0})}}else{let g=Gm(e,c);fe(g??c,{display:d})}},[w,kd,wd,ao,fe]),bd=Z(u=>{if(u.length>1){if(u.includes("\x1B"))return;let d=Bg(u);if(Hg(d)){let c=qg(++Ny.current,d);Yu.current.set(c,d),T(c)}else T(d);return}T(u)},[T]),lo=Math.max(10,ze-6),$d=ju(()=>Zi(p.text,lo),[p.text,lo]),Pa=Z(u=>m(d=>({...d,pos:Math.max(0,Math.min(d.text.length,d.pos+u))})),[]),vs=Z(u=>m(d=>({...d,pos:Yg(Zi(d.text,lo),d.pos,u)})),[lo]),ur=Z(u=>m(d=>({...d,pos:Kg(Zi(d.text,lo),d.pos,u)})),[lo]),Wy=["\x1B[H","\x1B[1~","\x1BOH"],Uy=["\x1B[F","\x1B[4~","\x1BOF"],vd=Z((u,d)=>d.leftArrow?(Pa(-1),!0):d.rightArrow?(Pa(1),!0):u&&Wy.includes(u)?(ur("start"),!0):u&&Uy.includes(u)?(ur("end"),!0):d.ctrl&&u==="a"?(ur("start"),!0):d.ctrl&&u==="e"?(ur("end"),!0):!1,[Pa,ur]);return gS((u,d)=>{if(d.ctrl&&u==="c"){mt.current?.close(),r();return}if(sr.current.awaySince!==null)try{let c=Dg(sr.current,Date.now(),Wn(e));if(sr.current=c.memory,cd(null),c.kind==="delta"){h({kind:"note",tone:"info",text:jg(c.delta,c.awayMs)});let g=yt(!1);g.kind==="recommend"&&Ot(g.rec,{silent:!0})}else if(c.kind==="briefing"){h({kind:"note",tone:"info",text:`\u{1F4E5} ${es(c.delta)} arrived while you were away (${Eu(c.awayMs)}).`});let g=yt(!1);g.kind==="recommend"&&Ot(g.rec)}}catch{}if(wa.current=Date.now(),!E){if(R){if(d.escape){if(Ae.current){if(!Ae.current.signal.aborted){let c=(Qo?.verb??"work").toLowerCase(),g=Qo?.unit??"article";h({kind:"note",tone:"warn",text:`\u238B Stopping the ${c} run (finishing in-flight ${g}s)\u2026`}),Ae.current.abort()}return}Xo.current||(Xo.current=!0,h({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),mt.current?.interrupt());return}if(d.return){let c=w.trim();if(!c)return;Sn.current.push(c),ca([...Sn.current]),$("");return}if(vd(u,d))return;if(d.upArrow){vs(-1);return}if(d.downArrow){vs(1);return}if(d.backspace||d.delete){C();return}u&&!d.ctrl&&!d.meta&&bd(u);return}if(bn){if(d.upArrow){$n(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){$n(c=>c&&{...c,cursor:Math.min(At.length-1,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=At.length){$n(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let c=At[bn.cursor];$n(null);let{lines:g,changed:A,effective:U}=jr(e,c.value??"default");for(let O of g)h({kind:"note",tone:O.startsWith("\u26A0")?"warn":O.startsWith("\u2713")?"ok":"info",text:O});A&&(nd(O=>O+1),mt.current?.setModel(U));return}if(u==="s"){let c=At[bn.cursor];$n(null),mt.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(d.escape){$n(null);return}return}if(Yt){if(d.upArrow){zn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){zn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=Yt.rows.length){zn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return||u==="s"){let c=Yt.rows[Yt.cursor];zn(null),Ra(c.name,d.return===!0);return}if(d.escape){zn(null);return}return}if(er){if(d.escape){Tn(null);return}if(d.leftArrow||d.tab&&d.shift){Tn(c=>c&&{tab:(c.tab-1+et.length)%et.length,scroll:0});return}if(d.rightArrow||d.tab){Tn(c=>c&&{tab:(c.tab+1)%et.length,scroll:0});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=et.length){Tn({tab:Number(u)-1,scroll:0});return}if(d.upArrow){Tn(c=>c&&{...c,scroll:Math.max(0,c.scroll-1)});return}if(d.downArrow){Tn(c=>{if(!c)return c;let g=(et[c.tab]??et[0]).rows.length;return{...c,scroll:Math.min(Math.max(0,g-1),c.scroll+1)}});return}return}if(Kt){if(d.upArrow){Xn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){Xn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=Kt.rows.length){Xn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let c=Kt.rows[Kt.cursor].name;if(Xn(null),!Wa(e,c).created){h({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}h({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${c}").`});let A=!1;try{let U=qn(c);A=!!U&&!(gn(U)&&!U.refreshToken)}catch{A=!1}h({kind:"note",tone:"info",text:A?`Next: sign in to ${c} and pick your project \u2014 you're already signed in here, so it'll be quick.`:`Next: sign in to Document360 (${c}) and pick your project.`}),J("/login"),Y(U=>U+1);return}if(d.escape){Xn(null);return}return}if(Je){if(d.upArrow){Qn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){Qn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=Je.rows.length){Qn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let c=Je.rows[Je.cursor],{profile:g,projectId:A}=Je;Qn(null),ws(g,A,c);return}if(d.escape){Qn(null);return}return}if(gt){if(d.upArrow){vn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){vn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=gt.rows.length){vn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let c=gt.rows[gt.cursor],{profile:g}=gt;vn(null),bs(g,c);return}if(d.escape){vn(null);return}return}if(Ze){if(d.upArrow){to(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){to(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u===" "){to(c=>c&&{...c,rows:c.rows.map((g,A)=>A===c.cursor?{...g,checked:!g.checked}:g)});return}if(d.return){let c=Ze.rows.filter(g=>g.checked).map(g=>g.path);if(to(null),c.length===0){h({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}Il(e,c),h({kind:"note",tone:"ok",text:`\u2713 Scoped to ${c.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let g of c)h({kind:"note",tone:"info",text:` ${g}`});h({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(d.escape){to(null);return}return}if(vt){if(d.upArrow){Cn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){Cn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=vt.rows.length){Cn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let c=vt.rows[vt.cursor],g=vt.run;Cn(null),g(c.token);return}if(d.escape){Cn(null);return}return}if(jt){if(d.upArrow){Jn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){Jn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=jt.rows.length){Jn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let c=jt.rows[jt.cursor],g=jt.conflicts;Jn(null),c.conflict?Sa(c.paths[0]):c.kind==="article"?xa(c.paths[0]):wt(c.paths,c.kind==="all"?g:0);return}if(d.escape){Jn(null);return}return}if(zt){if(d.upArrow){Zn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){Zn(c=>c&&{...c,cursor:Math.min(c.rows.length,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=zt.rows.length+1){Zn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let{cursor:c,rows:g,opts:A}=zt;Zn(null);let U=c===0?g:[g[c-1]];Fy(U,A);return}if(d.escape){Zn(null),h({kind:"note",tone:"info",text:"Left as drafts \u2014 nothing changed. /publish when they have been signed off."});return}return}if(It){let{rows:c}=It;if(d.upArrow){Lt(g=>g&&{...g,cursor:Math.max(0,g.cursor-1)});return}if(d.downArrow){Lt(g=>g&&{...g,cursor:Math.min(c.length-1,g.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let g=vg(Xu.current,Number(u),c.length-1);Xu.current=g.memory,g.index!==null&&Lt(A=>A&&{...A,cursor:g.index+1});return}if(u==="a"||u==="A"){Lt(g=>g&&{...g,cursor:0});return}if(d.return){let g=c[It.cursor],{groups:A,resolve:U,report:O}=It;if(Lt(null),g.kind==="all"){va(A,{resolve:U,report:O});return}so(Si(g.group,{width:Be()})),zo({group:g.group,cursor:0,fromList:!0,resolve:U,rest:A.filter(f=>f.articleId!==g.group.articleId),report:O});return}if(d.escape){Lt(null),J("/comments");return}return}if(We){let c=()=>{let{rest:g,group:A,fromList:U,resolve:O,report:f}=We;if(zo(null),!U||!f){J("/comments");return}let k=[A,...g].sort((b,v)=>b.category.localeCompare(v.category)||b.title.localeCompare(v.title));Lt({cursor:0,rows:Pi(k),groups:k,resolve:O,report:f})};if(d.upArrow||d.downArrow){zo(g=>g&&{...g,cursor:g.cursor===0?1:0});return}if(u==="y"||u==="Y"||d.return&&We.cursor===0){let{group:g,resolve:A,rest:U,report:O}=We;zo(null),va([g],{resolve:A,rest:U,...O?{report:O}:{}});return}if(u==="b"||u==="B"||d.escape||d.return){c();return}return}if(Xt){if(d.upArrow){xn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){xn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=Xt.rows.length){xn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let c=Xt.rows[Xt.cursor];xn(null),c.action==="capture"?lr(c.ids,{runLine:c.kind==="all"?["/screenshot capture --all","/capture --all"]:void 0}):c.action==="annotate"?ys(c.ids,{verifiedBefore:new Set(Le(e).filter(g=>g.state==="verified").map(g=>g.id))}):c.kind==="shot"?gd(c.ids[0]):md(c.ids,{setup:!0,runLine:c.kind==="all"?["/screenshot author --all","/screenshot --all"]:void 0});return}if(d.escape){xn(null);return}return}if(it){if(d.escape){Rn(null);return}if(d.upArrow){Rn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){Rn(c=>c&&{...c,cursor:Math.min(Math.max(0,hs.length-1),c.cursor+1)});return}if(d.return){let c=hs[it.cursor];if(c){Rn(null);try{h({kind:"preview",name:ns(c),text:vy(ta(Iu(e,c),"utf8"))})}catch(g){h({kind:"note",tone:"error",text:`Could not read ${c}: ${g.message}`})}}return}if(d.backspace||d.delete){Rn(c=>c&&{...c,query:c.query.slice(0,-1),cursor:0});return}if(u&&!d.ctrl&&!d.meta&&u.length===1){Rn(c=>c&&{...c,query:c.query+u,cursor:0});return}return}if(at){if(d.escape){Pn(null);return}if(d.upArrow){Pn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){Pn(c=>c&&{...c,cursor:Math.min(Math.max(0,fs.length-1),c.cursor+1)});return}if(d.return){let c=fs[at.cursor];if(c){Pn(null),Xe(c.uuid),Nt.current={uuid:c.uuid,firstPrompt:c.firstPrompt,titleFired:!0},kn(c.name),Lu(c.uuid),Kn.current=[],Ye.current={printed:[],armed:[],printedAt:no.current};let g=Pu(e,c.uuid);for(let A of g)h(A);h({kind:"note",tone:"ok",text:g.length?`Resumed "${c.name}" \u2014 restored ${g.length} message(s); continue where you left off.`:`Resumed "${c.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(d.backspace||d.delete){Pn(c=>c&&{...c,query:c.query.slice(0,-1),cursor:0});return}if(u&&!d.ctrl&&!d.meta&&u.length===1){Pn(c=>c&&{...c,query:c.query+u,cursor:0});return}return}if(d.tab&&!w&&ae){$(ae),xt();return}if(!w&&ee.length>0&&!yn&&u&&/^[1-9]$/.test(u)){let c=ee[Number(u)-1];if(c){$(Hn(c));return}}if(!w&&ee.length===0&&!yn&&Ye.current.armed.length>0&&u&&/^[1-9]$/.test(u)){let c=Ye.current.armed[Number(u)-1];if(c){$(c);return}}if(!w&&(us||or)&&u==="c"&&!d.ctrl&&!d.meta&&!d.return&&!d.tab){let c=us!=null;Cu(us??or).then(A=>{h({kind:"note",tone:A?"ok":"warn",text:A?c?"\u2713 Copied the feedback to your clipboard \u2014 send it to the d360-writer team (Teams / Slack / email).":"\u2713 Copied the prompt to your clipboard \u2014 paste it into your repo's coding agent.":c?"Couldn't reach your clipboard \u2014 select the feedback above and copy it manually.":"Couldn't reach your clipboard \u2014 select the prompt above and copy it manually."}),A&&c&&ya(null),A&&!c&&rd(!0)});return}if(!vd(u,d)){if(dd){if(d.upArrow){Vn(c=>Math.max(0,c-1));return}if(d.downArrow){Vn(c=>Math.min(_t.length-1,c+1));return}if(d.tab){$("/"+(_t[ia]?.name??"")+" "),Vn(0);return}if(d.return){let c=_t[ia];if(c){let g=w.trim().slice(1).split(/\s+/).slice(1).join(" ");if(xp(c.usage)&&!g){$("/"+c.name+" "),Vn(0);return}$s("/"+c.name+(g?" "+g:""));return}}}else{if(d.upArrow){if(w!==""&&Yn===null){vs(-1);return}let c=aa.current;if(!c.length)return;let g=Yn===null?c.length-1:Math.max(0,Yn-1);rs(g),$(c[g]??"");return}if(d.downArrow){if(w!==""&&Yn===null){vs(1);return}let c=aa.current;if(Yn===null)return;let g=Yn+1;g>=c.length?(rs(null),$("")):(rs(g),$(c[g]??""));return}}if(d.return){$s();return}if(d.backspace||d.delete){C();return}if(d.escape){$(""),Vn(0),xt(),X([]),eo(null),Re.current=!0;return}u&&!d.ctrl&&!d.meta&&bd(u)}}}),rt(()=>{if(R||E)return;let u=Sn.current.shift();u!==void 0&&(ca([...Sn.current]),$s(u))},[R,E,$s]),re(ve,{flexDirection:"column",width:ze,children:[$a!==null&&re(ve,{marginTop:1,flexDirection:"column",children:[$a.truncated&&B(H,{dimColor:!0,children:"\u2026"}),B(H,{children:$a.text})]}),R&&Qo?B($P,{p:Qo}):null,Zu?B(kP,{text:Zu}):R&&!Qo?B(wP,{startTime:Dt.current,chars:Dy}):null,B(ve,{borderStyle:"round",borderColor:ud.prod?"yellow":te,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:w?$d.map((u,d)=>{let c=p.text.slice(u.start,u.end),g=d===ea($d,p.pos),A=Math.min(p.pos,u.end)-u.start;return re(H,{children:[B(H,{color:te,children:d===0?"> ":" "}),g?re(qo,{children:[c.slice(0,A),B(Ho,{ch:c[A]??" "}),c.slice(A+1)]}):c||" "]},`${d}-${u.start}`)}):re(H,{children:[B(H,{color:te,children:"> "}),tr?B(Ho,{ch:" "}):ae&&!R&&de?re(qo,{children:[B(Ho,{ch:de[0],dim:!0}),B(H,{color:"gray",children:de.slice(1)})]}):ae&&!R?re(qo,{children:[B(Ho,{ch:ae[0],dim:!0}),B(H,{color:"gray",children:ae.slice(1)}),B(H,{dimColor:!0,children:" (tab)"})]}):(ka.isSetup||!Gn)&&!R?re(qo,{children:[B(Ho,{ch:ka.text[0],dim:!0}),B(H,{color:"gray",children:ka.text.slice(1)})]}):B(Ho,{ch:" "})]})}),Ju.length>0&&B(ve,{flexDirection:"column",paddingX:1,children:Ju.map((u,d)=>B(H,{color:"gray",children:`\u29D7 queued: ${u}`},`${d}-${u.slice(0,24)}`))}),er?B(Lg,{tab:er.tab,scroll:er.scroll,rows:_y,width:ze,version:o,engineVersion:xy}):bn?re(ve,{flexDirection:"column",paddingX:1,children:[B(H,{color:te,bold:!0,children:"Select model"}),B(H,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),At.map((u,d)=>re(H,{color:d===bn.cursor?te:void 0,children:[d===bn.cursor?"\u276F ":" ",`${d+1}. ${u.label}${d===bn.current?" \u2714":""}`.padEnd(16),B(H,{color:"gray",children:u.desc})]},u.label)),B(H,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Yt?re(ve,{flexDirection:"column",paddingX:1,children:[B(H,{color:te,bold:!0,children:"Switch connection profile"}),B(mn,{rows:Yt.rows,cursor:Yt.cursor,cap:Mt,render:(u,d,c)=>re(H,{color:c?te:void 0,children:[c?"\u276F ":" ",`${d+1}. ${u.name}${d===Yt.current?" \u2714":""}`.padEnd(20),B(H,{color:"gray",children:`${u.env} \xB7 ${u.who??"not signed in"}`}),u.prod?B(H,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},u.name)}),B(H,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Kt?re(ve,{flexDirection:"column",paddingX:1,children:[B(H,{color:te,bold:!0,children:"Pick your Document360 environment"}),B(mn,{rows:Kt.rows,cursor:Kt.cursor,cap:Mt,render:(u,d,c)=>re(H,{color:c?te:void 0,children:[c?"\u276F ":" ",`${d+1}. ${u.name}`.padEnd(16),B(H,{color:"gray",children:u.apiUrl}),u.note?B(H,{color:"yellow",children:` \u26A0 ${u.note}`}):null]},u.name)}),B(H,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):Je?re(ve,{flexDirection:"column",paddingX:1,children:[B(H,{color:te,bold:!0,children:"Switch workspace"}),B(H,{dimColor:!0,children:`environment ${Je.environment} \xB7 project ${Je.projectName??`${Je.projectId.slice(0,8)}\u2026`}`}),B(mn,{rows:Je.rows,cursor:Je.cursor,cap:Mt,render:(u,d,c)=>re(H,{color:c?te:void 0,children:[c?"\u276F ":" ",`${d+1}. ${u.name}${d===Je.current?" \u2714":""}`.padEnd(30),B(H,{color:"gray",children:u.type??""})]},u.id)}),B(H,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):gt?re(ve,{flexDirection:"column",paddingX:1,children:[B(H,{color:te,bold:!0,children:"Choose project"}),B(H,{dimColor:!0,children:`environment ${gt.environment}`}),B(mn,{rows:gt.rows,cursor:gt.cursor,cap:Mt,render:(u,d,c)=>re(H,{color:c?te:void 0,children:[c?"\u276F ":" ",`${d+1}. ${u.name}${d===gt.current?" \u2714":""}`.padEnd(30),B(H,{color:"gray",children:u.sub??""})]},u.id)}),B(H,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):Ze?(()=>{let d=Math.min(Math.max(0,Ze.cursor-Math.floor(7)),Math.max(0,Ze.rows.length-14)),c=Ze.rows.slice(d,d+14),g=Ze.rows.filter(A=>A.checked).length;return re(ve,{flexDirection:"column",paddingX:1,children:[B(H,{color:te,bold:!0,children:`Which folders back the user docs? (${g} selected of ${Ze.rows.length})`}),d>0?B(H,{dimColor:!0,children:` \u2191 ${d} more`}):null,c.map((A,U)=>{let O=d+U;return re(H,{color:O===Ze.cursor?te:void 0,children:[O===Ze.cursor?"\u276F ":" ",A.checked?"\u25C9 ":"\u25CB ",A.path.padEnd(Math.min(48,ze-34)),B(H,{color:"gray",children:ui(A)})]},A.path)}),d+14<Ze.rows.length?B(H,{dimColor:!0,children:` \u2193 ${Ze.rows.length-d-14} more`}):null,B(H,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():vt?re(ve,{flexDirection:"column",paddingX:1,children:[B(H,{color:te,bold:!0,children:vt.title??"Which category? (pick one to scope to)"}),B(mn,{rows:vt.rows,cursor:vt.cursor,cap:Mt,render:(u,d,c)=>re(H,{color:c?te:void 0,children:[c?"\u276F ":" ",`${`${d+1}.`.padEnd(3)} ${u.label} (${u.count})`.padEnd(Math.min(44,Math.max(20,ze-24))),B(H,{color:"gray",children:` ${u.token}`})]},u.token)}),B(H,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):jt?re(ve,{flexDirection:"column",paddingX:1,children:[B(H,{color:te,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),B(mn,{rows:jt.rows,cursor:jt.cursor,cap:Mt,render:(u,d,c)=>re(H,{color:c?te:void 0,bold:u.kind==="category"&&!c,children:[c?"\u276F ":" ",`${u.indent?" ":" "}${`${d+1}.`.padEnd(3)} ${u.label}`.padEnd(Math.min(56,ze-24)),u.note?B(H,{color:"gray",children:u.note}):null]},`${u.kind}:${u.paths.join(",")}`)}),B(H,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter push (draft) \xB7 esc cancel"})]}):zt?re(ve,{flexDirection:"column",paddingX:1,children:[B(H,{color:te,bold:!0,children:"Publish live to your readers \u2014 this is what they will see:"}),B(mn,{rows:[{path:"",articleId:"",label:`Publish all ${zt.rows.length} live`,version:void 0},...zt.rows],cursor:zt.cursor,cap:Mt,render:(u,d,c)=>re(H,{color:c?te:void 0,bold:d===0&&!c,children:[c?"\u276F ":" ",` ${`${d+1}.`.padEnd(3)} ${u.label}`.padEnd(Math.min(56,ze-24)),d>0?B(H,{color:"gray",children:u.version?`draft v${u.version} \u2192 live`:"draft \u2192 live"}):null]},`${d}:${u.path||"all"}`)}),B(H,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish LIVE \xB7 esc leave as drafts"})]}):It?re(ve,{flexDirection:"column",paddingX:1,children:[B(H,{color:te,bold:!0,children:"Which comments do you want to look at?"}),B(mn,{rows:It.rows,cursor:It.cursor,cap:Mt,render:(u,d,c)=>re(H,{color:c?te: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,ze-24))),u.kind==="article"?B(H,{color:"gray",children:u.note}):null]},u.kind==="all"?"all":u.group.articleId)}),B(H,{dimColor:!0,children:"\u2191\u2193 move \xB7 type a number \xB7 enter \xB7 esc close"}),It.resolve?B(H,{dimColor:!0,children:"--resolve is on: threads you answer will be closed as well as replied to"}):null]}):We?re(ve,{flexDirection:"column",paddingX:1,children:[B(H,{color:te,bold:!0,children:`${We.group.title} \u2014 ${We.group.threads.length} comment${We.group.threads.length===1?"":"s"}`}),re(H,{color:We.cursor===0?te:void 0,children:[We.cursor===0?"\u276F ":" ",We.resolve?"Yes \u2014 fix them, push the draft, reply and resolve":"Yes \u2014 fix them, push the draft to Document360, then reply"]}),re(H,{color:We.cursor===1?te:void 0,children:[We.cursor===1?"\u276F ":" ",We.fromList?"No \u2014 back to the list":"No \u2014 leave them for now"]}),B(H,{dimColor:!0,children:"\u2191\u2193 move \xB7 enter select \xB7 y answer \xB7 esc back"})]}):Xt?re(ve,{flexDirection:"column",paddingX:1,children:[B(H,{color:te,bold:!0,children:Xt.title}),(()=>{let{rows:u,cursor:d}=Xt,c=Yi(u.length,d,Mt),g=c.start,A=u.slice(c.start,c.end),U=`${u.length}.`.length+1,O=yh(u,Math.max(20,ze-4-U));return re(qo,{children:[g>0?B(H,{color:"gray",children:` \u2026 ${g} more above`}):null,A.map((f,k)=>{let b=g+k,v=b===d,x=O[b];return re(H,{color:v?te:void 0,bold:(f.kind==="all"||f.kind==="category")&&!v,children:[v?"\u276F ":" ",`${b+1}.`.padEnd(U),x.head,x.note?B(H,{color:"gray",children:x.note}):null]},`${f.action}:${f.kind}:${f.ids.join(",")}`)}),c.below>0?B(H,{color:"gray",children:` \u2026 ${c.below} more below`}):null]})})(),B(H,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter run \xB7 esc cancel"})]}):it?re(ve,{flexDirection:"column",paddingX:1,children:[B(H,{color:te,bold:!0,children:`Preview article${it.query?` \u2014 filter: ${it.query}`:" (type to filter)"}`}),hs.length===0?B(H,{color:"gray",children:"no articles match"}):hs.map((u,d)=>re(H,{color:d===it.cursor?te:void 0,children:[d===it.cursor?"\u276F ":" ",u]},u)),B(H,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):at?re(ve,{flexDirection:"column",paddingX:1,children:[B(H,{color:te,bold:!0,children:`Resume session${at.query?` \u2014 filter: ${at.query}`:" (type to filter)"}`}),fs.length===0?B(H,{color:"gray",children:"no sessions match"}):fs.map((u,d)=>re(H,{color:d===at.cursor?te:void 0,children:[d===at.cursor?"\u276F ":" ",u.name.slice(0,28).padEnd(30),B(H,{color:d===at.cursor?te:"gray",children:u.firstPrompt.slice(0,Math.max(10,ze-40))})]},u.uuid)),B(H,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):dd?re(ve,{flexDirection:"column",children:[An>0?B(H,{dimColor:!0,children:` \u22EF ${An} more above`}):null,ba.map((u,d)=>{let c=An+d,g=u.name==="model"&&ua?`${u.desc} (currently ${ua})`:u.desc,A=Math.max(20,ze-4),U=u.usage.length>A?`${u.usage.slice(0,A-1)}\u2026`:u.usage,O=A-Math.max(U.length,22)-1,f=O<=1?"":g.length>O?`${g.slice(0,O-1)}\u2026`:g;return re(H,{color:c===ps?te:void 0,children:[c===ps?"\u276F ":" ",U.padEnd(22)," ",B(H,{color:c===ps?te:"gray",children:f})]},u.name)}),An+ba.length<_t.length?B(H,{dimColor:!0,children:` \u22EF ${_t.length-An-ba.length} more below`}):null,B(H,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!R&&!w&&ee.length>0?re(ve,{flexDirection:"column",paddingX:1,children:[Qu?B(H,{color:te,children:Qu}):null,ee.map((u,d)=>{let c=Hn(u),g=c.slice(0,Math.max(20,ze-5)),A=ze-g.length-7,U=A>=12?(Wg(u)??$p(c)).slice(0,A):"";return re(H,{children:[B(H,{color:te,children:d+1})," ",g,U?B(H,{dimColor:!0,children:` \u2014 ${U}`}):null]},c)}),B(H,{dimColor:!0,children:`press 1-${ee.length} to fill \xB7 esc cancel`})]}):B(ve,{paddingX:1,children:re(H,{color:"gray",children:[ud.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${ua??"model n/a"}${t.kind==="api"?td>0?` \xB7 ${tt(td)}`:"":ed>0?` \xB7 ${ln(ed)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}ne();import{jsx as RP}from"react/jsx-runtime";async function Ry(e=process.cwd(),t="auto",n,o="0.0.0"){let r=CP(t);r.kind==="none"&&(console.error(""),console.error(j("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${z("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${z("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=xP(RP(Cy,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
|
|
515
|
-
`),process.exit(0)}
|
|
516
|
-
`+j(`\u2717 d360-writer crashed: ${
|
|
504
|
+
`)}`}),Y(F=>F+1);return}if(f==="--compare"){h({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let x=await qS({cwd:e,profileName:s}),v=x.onlyInLegacy.length===0&&x.onlyInManifest.length===0&&x.mappedMissingFromManifest.length===0,P=[`Legacy listing: ${x.legacyCount} \xB7 Manifest: ${x.manifestCount} \xB7 in both: ${x.inBoth}`];v?P.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(x.mappedMissingFromManifest.length&&P.push(`\u2717 ${x.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${x.mappedMissingFromManifest.slice(0,5).join(", ")}`),x.onlyInLegacy.length&&P.push(`\u26A0 ${x.onlyInLegacy.length} only in the legacy listing: ${x.onlyInLegacy.slice(0,5).join(", ")}`),x.onlyInManifest.length&&P.push(`\u26A0 ${x.onlyInManifest.length} only in the manifest: ${x.onlyInManifest.slice(0,5).join(", ")}`),P.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),h({kind:"note",tone:v?"ok":"warn",text:P.join(`
|
|
505
|
+
`)});return}if(f){h({kind:"note",tone:"error",text:`Unknown option: ${f} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let k=g[0];if(k){let x=await uy({cwd:e,profileName:s,relPath:k.replace(/\\/g,"/")});Re.current=[{plan:x,mode:x.overwritesLocalChanges?"conflict":"pull"}],wn.current=[],io();return}h({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let b=await _l({cwd:e,profileName:s});for(let x of Ml(b))h({kind:"note",tone:x.tone,text:x.text});Y(x=>x+1)}catch(k){h({kind:"note",tone:"error",text:`Pull failed: ${k.message}`})}return}case"scope":{if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let f=YS(e);if(f.length===0){h({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.'});return}to({cursor:0,rows:f.map(k=>({...k,checked:k.recommended}))});return}case"audit":{if(g[0]==="--auto"){let k=ge(e);if(!k){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let b=g[1]!=="off";iy({...k,autoAudit:b},e),h({kind:"note",tone:"ok",text:b?"\u2713 Auto-audit ON \u2014 when you launch with code changes since the last audit, I\u2019ll run /audit automatically. (/audit --auto off to disable.)":"\u2713 Auto-audit OFF \u2014 I\u2019ll just nudge you to run /audit when code changed."});return}let f=await Sr();f.kind==="forward-to-agent"&&f.prompt&&((await fe(f.prompt,{display:f.display,quietUser:!0})).producedNothing||(Yr(e,s),Y(b=>b+1)));return}case"lint":case"check":{let f=Ut(c);f&&h({kind:"note",tone:"info",text:`\u2192 ${f}`});let k=g.find(v=>!v.startsWith("--")),b=k?` ${k}`:"",x=oa({cwd:e,scope:k});if(g.includes("--fix")){let v=zl(e,g,x);if(!v){h({kind:"note",tone:"ok",text:"\u2713 Nothing to fix \u2014 the docs are already clean."});return}if(v.kind==="partitioned"){let D=await fs({partitions:v.partitions,promptFor:v.promptFor,concurrency:To,verb:"Fixing",doneNoun:"fixed",headline:`Fixing ${v.findings} issue${v.findings===1?"":"s"} across ${v.articles} article${v.articles===1?"":"s"} in ${v.partitions.length} batches (\u2264${To} at once)`});if(D.covered.length>0)try{Bo(e,D.covered,Qe("lint"))}catch{}if(D.aborted){let M=Pr({cwd:e,after:oa({cwd:e,scope:k}).filter(B=>!B.baselined),scope:k,aborted:!0});Ee(M.text,{kind:"cmd",cmd:M.cmd,reason:""},"warn");return}}else{h({kind:"note",tone:"info",text:`Fixing ${v.findings} doc issue${v.findings===1?"":"s"}\u2026`});let D=sP(e,k);await fe(v.prompt,{display:v.display,quietUser:!0});try{Bo(e,D,Qe("lint"))}catch{}}let P=oa({cwd:e,scope:k}).filter(D=>!D.baselined),W=Math.max(0,v.findings-P.length);h({kind:"note",tone:P.some(D=>D.severity==="error")?"warn":"ok",text:P.length===0?`\u2713 Lint: all ${v.findings} issue${v.findings===1?"":"s"} resolved.`:[`\u2713 Lint: fixed ${W} of ${v.findings}.`,"",...Tr(P)].join(`
|
|
506
|
+
`)});let F=Pr({cwd:e,after:P,before:v.findings,scope:k});Ee(F.text,{kind:"cmd",cmd:F.cmd,reason:""});return}if(h({kind:"note",tone:x.length===0?"ok":"warn",text:Tr(x,{full:g.includes("--full"),baselined:g.includes("--baselined")}).join(`
|
|
507
|
+
`)}),x.length>0){let v=ii(e,k)===0?"; /publish --all publishes as-is":"";Ee(`Found ${x.length} doc issue${x.length===1?"":"s"} above. /lint${b} --fix has the agent fix them in place (or /review${b} --fix for the full editorial pass${v}).`,{kind:"cmd",cmd:`/lint${b} --fix`,reason:""})}return}case"structure":{let f=qr(e,s);if(f.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):","",...f].join(`
|
|
508
|
+
`)});return}case"reorder":{let f=pu(e,g);if(!f){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let k=await fe(f.prompt,{display:f.display,quietUser:!0}),b=Tt(e,{text:"Reordered locally \u2014 /publish --all syncs the new order to Document360.",cmd:"/publish --all"},"Reordered locally. ");nr(k,b.text,{kind:"cmd",cmd:b.cmd,reason:""});return}case"review":{let f=uu(e,g);if(!f){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let k=g.includes("--fix"),b=g.find(P=>!P.startsWith("--")),x=k?cu(e,g,b):[],v=f.kind==="partitioned"?await Wy(f,k):await fe(f.prompt,{display:f.display,quietUser:!0});if("aborted"in v&&v.aborted){let P=g.includes("--blocked")?"--blocked --fix":"--fix",W=be("/review",P,b);Ee(`Stopped \u2014 the batches that finished are saved. ${W} picks up the rest${b||g.includes("--blocked")?"":", or narrow it with /review <category> --fix"}.`,{kind:"cmd",cmd:W,reason:""},"warn");return}if(f.kind!=="partitioned"&&k&&!v.producedNothing)try{Bo(e,x,Qe("review"))}catch{}if(k){let P=k&&!v.producedNothing?oa({cwd:e,scope:b}).filter(F=>!F.baselined&&F.severity==="error"):[];if(P.length>0){let F=new Set(P.map(D=>D.path)).size;h({kind:"note",tone:"warn",text:`\u26A0 The editor's rewrites left ${P.length} style error${P.length===1?"":"s"} in ${F} article${F===1?"":"s"} \u2014 recasting a sentence is where these appear.`}),nr(v,`Editor applied its fixes, but ${P.length} style error${P.length===1?"":"s"} remain. /lint${b?` ${b}`:""} --fix clears them \u2014 it costs nothing to find them and one pass to correct.`,{kind:"cmd",cmd:`/lint${b?` ${b}`:""} --fix`,reason:""});return}let W=Tt(e,{text:`\u2713 Editor applied its fixes \u2014 your docs are corrected. /publish${b?"":" --all"} pushes them up (or /lint${b?` ${b}`:""} for an instant no-token re-scan first).`,cmd:b?"/publish":"/publish --all"},"\u2713 Editor applied its fixes to this scope. ",b);nr(v,W.text,{kind:"cmd",cmd:W.cmd,reason:""})}else{let P=b?` ${b}`:"",W=ii(e,b)===0&&$l(e,b)===0?`; /publish${b?"":" --all"} publishes as-is`:"";nr(v,`The review listed issues above. /review${P} --fix lets the editor apply them all (or /lint${P} --fix for just the deterministic ones${W}).`,{kind:"cmd",cmd:`/review${P} --fix`,reason:""})}return}case"capture-setup":{await O();return}case"devhints":{if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}h({kind:"note",tone:"info",text:go(mo(e)).join(`
|
|
509
|
+
`)}),Zt(Dn()),ir.current=kt(e).status==="current",ro.current=Ft(e);return}case"discover":{if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await fe(Nl(),{display:"/discover",quietUser:!0});return}case"inbox":{if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(Lc(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 fe(Oc(),{display:"/inbox",quietUser:!0});return}case"share":{let f=ge(e);if(!f){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let k=g[0]?.trim().toLowerCase();if(k==="status"){for(let x of xi(e,f))h({kind:"note",tone:x.tone,text:x.text});return}if(k==="on"||k==="off"){for(let x of _c(e,f,k==="on"))h({kind:"note",tone:x.tone,text:x.text});Y(x=>x+1);return}if(k){h({kind:"note",tone:"error",text:`Unknown option: ${k} \u2014 use /share, /share status, /share on, or /share off.`});return}h({kind:"note",tone:"info",text:"Exchanging work with your team\u2026"});let b=await Ri(e,f);for(let x of b.lines)h({kind:"note",tone:x.tone,text:x.text});b.changed&&Y(x=>x+1);return}case"feedback":{let f=yy(e),k="";try{k=Fo(f)?ea(f,"utf8"):""}catch{k=""}if(!/^## /m.test(k)){h({kind:"note",tone:"info",text:"No open d360-writer feedback to copy \u2014 nothing logged in .d360-writer/tool-feedback.md yet."});return}let b=await Su(k.trim());h({kind:"note",tone:b?"ok":"warn",text:b?"\u2713 Copied the d360-writer feedback to your clipboard \u2014 send it to the team (Teams / Slack / email).":`Couldn\u2019t reach your clipboard \u2014 open ${f} and copy it manually.`}),b&&ga(null);return}case"document":{if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{push:f,skipReview:k,what:b}=hc(g);if(!b&&pc(e)===0){h({kind:"note",tone:"info",text:mc});return}let x=`/document${b?` ${b}`:""}${f?" --push":""}`,v=await fe(fc(b),{display:x,quietUser:!0});f&&!v.producedNothing&&await gd({skipReview:k});return}case"catch-up":{if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!oo(u.trim()))return;let{push:f,skipReview:k}=Bc(g);for(let F of await Fc(e))h({kind:"note",tone:F.tone,text:F.text});h({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let b=await Vc({cwd:e,profileName:s});for(let F of Yc(b))h({kind:"note",tone:F.startsWith("\u2713")?"ok":F.startsWith("\u2139")?"info":"warn",text:F});let x=Hc(e);for(let F of qc(x))h({kind:"note",tone:F.tone,text:F.text});h({kind:"note",tone:"info",text:Uc(Wn(e))});let v=rP(e),P=await fe(Gc(x),{display:`/catch-up${f?" --push":""}`,quietUser:!0}),W=Li(e,v);f&&!P.producedNothing?await gd({skipReview:k}):W.cta&&nr(P,W.cta.text,{kind:"cmd",cmd:W.cta.cmd,reason:""});return}case"comments":{if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!oo(u.trim()))return;let f=Jc(g);Me("Checking Document360 for reviewer comments\u2026"),S(!0);let k=null;try{k=await zc(e,s,{...f.scope,onProgress:(x,v)=>Me(`Checking Document360 for reviewer comments\u2026 ${x}/${v}`)})}catch(x){h({kind:"note",tone:"error",text:`Couldn\u2019t read comments from Document360: ${x.message}`})}finally{S(!1),Me(null)}if(!k)return;Y(x=>x+1);let b=Un(k.threads,k.labels);if(k.threads.length===0){h({kind:"note",tone:"ok",text:Ur(k,{showAnswered:f.showAnswered,width:Be()}).join(`
|
|
510
|
+
`)});return}if(f.answer&&(f.all||f.scope.path||f.scope.scope||b.length===1)){so(Xc(k,{full:!0,showAnswered:f.showAnswered,width:Be()})),await $a(b,{resolve:f.resolve});return}if(b.length===1){so(Ci(b[0],{width:Be()})),zo({group:b[0],cursor:0,fromList:!1,resolve:f.resolve,rest:[]});return}so(Ur(k,{showAnswered:f.showAnswered,width:Be()})),Lt({cursor:0,rows:Si(b),groups:b,resolve:f.resolve,report:k});return}case"update":{ha.current=!0,h({kind:"note",tone:"info",text:"Updating the d360-writer toolchain\u2026 (don\u2019t close this window)"}),Pe(!0);let f=await Ti().finally(()=>Pe(!1));f.ok?(h({kind:"note",tone:"ok",text:`\u2713 Updated ${f.packages.join(" + ")} \u2014 run /exit, then relaunch to apply.`}),J("/exit"),ns("")):h({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${Pi}`});return}case"screenshot":{let f=br(g),k=Nn(e);if(k&&f.mode!=="list"&&h({kind:"note",tone:"info",text:k}),f.mode==="capture"){await A(f.rest);return}if(f.mode==="annotate"){await U(f.rest);return}if(f.mode==="checklist"){await O();return}if(f.mode==="verify"){let v=Le(e),P=f.rest.find(D=>!D.startsWith("-")),W=P?[P]:Lr(v);if(P&&!v.some(D=>D.id===P)){h({kind:"note",tone:"error",text:`No screenshot placeholder called "${P}". /screenshot list shows them all.`});return}if(W.length===0){let D=v.filter(B=>B.state==="rejected").length,M=v.filter(B=>B.state==="verified").length;h({kind:"note",tone:"info",text:D>0?`Nothing left to verify. ${D} shot${D===1?"":"s"} failed verification \u2014 re-capture with /screenshot capture --failed.`:M>0?`All ${M} captured shot${M===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:pn(W.length)}),await fe(Et(e,W),{display:P?`/screenshot verify ${P}`:"/screenshot verify",quietUser:!0});let F=Eo(e,W);F.length>0&&h({kind:"note",tone:"info",text:F.join(`
|
|
511
|
+
`)});return}if(f.mode==="list"){if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let v=ge(e)?.docsDir??Gu,P=ml(e,f.scope),W=Le(e,P);if(f.picker){if(W.length===0){h({kind:"note",tone:"info",text:"No screenshot placeholders found in the docs."});return}let D=bh(W);if(D.length===0){h({kind:"note",tone:"info",text:ni(W,{docsDir:v}).join(`
|
|
512
|
+
`)});let M=Tt(e,{text:`\u2713 All ${W.length} screenshots are captured. /publish${P?` ${P}`:""} puts them in the articles; /screenshot capture${P?` ${P}`:""} re-captures.`,cmd:P?`/publish ${P}`:"/publish"},`\u2713 All ${W.length} screenshots are captured. `,P);Ee(M.text,{kind:"cmd",cmd:M.cmd,reason:""});return}xn({cursor:0,rows:D,title:"Screenshots \u2014 pick what to author or capture:"});return}h({kind:"note",tone:"info",text:ni(W,{scope:P,detail:f.detail,docsDir:v}).join(`
|
|
513
|
+
`)}),k&&h({kind:"note",tone:"info",text:k});let F=fl(W,P);F.key!=="done"&&J(F.cmd);return}if(f.mode==="single"){await wd(f.id);return}if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let b=f.mode==="scope"?f.scope:void 0,x=QS(e,{scope:b}).map(v=>v.id);if(x.length===0){h({kind:"note",tone:"info",text:b?`No screenshot placeholders under ${b}.`:"No screenshot placeholders found in the docs."});return}await yd(x,{setup:f.setup,scope:f.mode==="scope"?f.scope:void 0,runLine:f.mode==="scope"?[`/screenshot author ${f.scope}`,`/screenshot ${f.scope}`]:["/screenshot author --all","/screenshot --all"]});return}case"capture":{await A(g);return}case"reset":{let f=tu(e);if(f.length===0){h({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}Ko.current={repoName:ts(e),targets:f,hadDevhints:Fo(gy(e))},h({kind:"note",tone:"warn",text:ou(e,f).join(`
|
|
514
|
+
`)}),Ke(ts(e));return}default:h({kind:"note",tone:"error",text:`Unknown command: /${c} \u2014 type /help.`})}},[e,r,s,io,Ca,h,Xe,fe,wt,va,kd]),bs=Z(u=>{let d=(u??w).trim();if($(""),os(null),Vn(0),d.startsWith("/")&&(Ce.current=!1,Se.current=!1,Fe.current=null,xt(),eo(null),X(g=>Hg(g,d))),!d||($t(!1),(Ko.current||Re.current.length>0)&&h({kind:"user",text:d}),$d(d))||bd(d))return;ia.current.push(d);let c=Yg(d,zu.current);if(d.startsWith("/"))h({kind:"user",text:d}),ue(!0),ao(c).finally(()=>ue(!1));else if(pP(c)){h({kind:"user",text:d});let g=hP(c);if(!g)fe(c,{display:d,quietUser:!0});else{try{fP(e,{title:g,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}fe(`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${g}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${g}" and the article path(s) you wrote.`,{display:d,quietUser:!0})}}else{let g=Ym(e,c);fe(g??c,{display:d})}},[w,$d,bd,ao,fe]),vd=Z(u=>{if(u.length>1){if(u.includes("\x1B"))return;let d=qg(u);if(Gg(d)){let c=Vg(++Iy.current,d);zu.current.set(c,d),T(c)}else T(d);return}T(u)},[T]),lo=Math.max(10,ze-6),xd=Lu(()=>Ji(p.text,lo),[p.text,lo]),Sa=Z(u=>m(d=>({...d,pos:Math.max(0,Math.min(d.text.length,d.pos+u))})),[]),$s=Z(u=>m(d=>({...d,pos:zg(Ji(d.text,lo),d.pos,u)})),[lo]),ur=Z(u=>m(d=>({...d,pos:Xg(Ji(d.text,lo),d.pos,u)})),[lo]),By=["\x1B[H","\x1B[1~","\x1BOH"],Hy=["\x1B[F","\x1B[4~","\x1BOF"],Rd=Z((u,d)=>d.leftArrow?(Sa(-1),!0):d.rightArrow?(Sa(1),!0):u&&By.includes(u)?(ur("start"),!0):u&&Hy.includes(u)?(ur("end"),!0):d.ctrl&&u==="a"?(ur("start"),!0):d.ctrl&&u==="e"?(ur("end"),!0):!1,[Sa,ur]);return bS((u,d)=>{if(d.ctrl&&u==="c"){mt.current?.close(),r();return}if(sr.current.awaySince!==null)try{let c=jg(sr.current,Date.now(),Wn(e));if(sr.current=c.memory,dd(null),c.kind==="delta"){h({kind:"note",tone:"info",text:Lg(c.delta,c.awayMs)});let g=yt(!1);g.kind==="recommend"&&Ot(g.rec,{silent:!0})}else if(c.kind==="briefing"){h({kind:"note",tone:"info",text:`\u{1F4E5} ${Zr(c.delta)} arrived while you were away (${Nu(c.awayMs)}).`});let g=yt(!1);g.kind==="recommend"&&Ot(g.rec)}}catch{}if(ya.current=Date.now(),!E){if(C){if(d.escape){if(Ae.current){if(!Ae.current.signal.aborted){let c=(Qo?.verb??"work").toLowerCase(),g=Qo?.unit??"article";h({kind:"note",tone:"warn",text:`\u238B Stopping the ${c} run (finishing in-flight ${g}s)\u2026`}),Ae.current.abort()}return}Xo.current||(Xo.current=!0,h({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),mt.current?.interrupt());return}if(d.return){let c=w.trim();if(!c)return;Sn.current.push(c),la([...Sn.current]),$("");return}if(Rd(u,d))return;if(d.upArrow){$s(-1);return}if(d.downArrow){$s(1);return}if(d.backspace||d.delete){R();return}u&&!d.ctrl&&!d.meta&&vd(u);return}if(bn){if(d.upArrow){$n(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){$n(c=>c&&{...c,cursor:Math.min(At.length-1,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=At.length){$n(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let c=At[bn.cursor];$n(null);let{lines:g,changed:A,effective:U}=jr(e,c.value??"default");for(let O of g)h({kind:"note",tone:O.startsWith("\u26A0")?"warn":O.startsWith("\u2713")?"ok":"info",text:O});A&&(rd(O=>O+1),mt.current?.setModel(U));return}if(u==="s"){let c=At[bn.cursor];$n(null),mt.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(d.escape){$n(null);return}return}if(Yt){if(d.upArrow){zn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){zn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=Yt.rows.length){zn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return||u==="s"){let c=Yt.rows[Yt.cursor];zn(null),Ra(c.name,d.return===!0);return}if(d.escape){zn(null);return}return}if(er){if(d.escape){Tn(null);return}if(d.leftArrow||d.tab&&d.shift){Tn(c=>c&&{tab:(c.tab-1+et.length)%et.length,scroll:0});return}if(d.rightArrow||d.tab){Tn(c=>c&&{tab:(c.tab+1)%et.length,scroll:0});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=et.length){Tn({tab:Number(u)-1,scroll:0});return}if(d.upArrow){Tn(c=>c&&{...c,scroll:Math.max(0,c.scroll-1)});return}if(d.downArrow){Tn(c=>{if(!c)return c;let g=(et[c.tab]??et[0]).rows.length;return{...c,scroll:Math.min(Math.max(0,g-1),c.scroll+1)}});return}return}if(Kt){if(d.upArrow){Xn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){Xn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=Kt.rows.length){Xn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let c=Kt.rows[Kt.cursor].name;if(Xn(null),!Fa(e,c).created){h({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}h({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${c}").`});let A=!1;try{let U=qn(c);A=!!U&&!(gn(U)&&!U.refreshToken)}catch{A=!1}h({kind:"note",tone:"info",text:A?`Next: sign in to ${c} and pick your project \u2014 you're already signed in here, so it'll be quick.`:`Next: sign in to Document360 (${c}) and pick your project.`}),J("/login"),Y(U=>U+1);return}if(d.escape){Xn(null);return}return}if(Je){if(d.upArrow){Qn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){Qn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=Je.rows.length){Qn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let c=Je.rows[Je.cursor],{profile:g,projectId:A}=Je;Qn(null),ys(g,A,c);return}if(d.escape){Qn(null);return}return}if(gt){if(d.upArrow){vn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){vn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=gt.rows.length){vn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let c=gt.rows[gt.cursor],{profile:g}=gt;vn(null),ks(g,c);return}if(d.escape){vn(null);return}return}if(Ze){if(d.upArrow){to(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){to(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u===" "){to(c=>c&&{...c,rows:c.rows.map((g,A)=>A===c.cursor?{...g,checked:!g.checked}:g)});return}if(d.return){let c=Ze.rows.filter(g=>g.checked).map(g=>g.path);if(to(null),c.length===0){h({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}jl(e,c),h({kind:"note",tone:"ok",text:`\u2713 Scoped to ${c.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let g of c)h({kind:"note",tone:"info",text:` ${g}`});h({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(d.escape){to(null);return}return}if(vt){if(d.upArrow){Rn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){Rn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=vt.rows.length){Rn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let c=vt.rows[vt.cursor],g=vt.run;Rn(null),g(c.token);return}if(d.escape){Rn(null);return}return}if(jt){if(d.upArrow){Jn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){Jn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=jt.rows.length){Jn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let c=jt.rows[jt.cursor],g=jt.conflicts;Jn(null),c.conflict?Ca(c.paths[0]):c.kind==="article"?va(c.paths[0]):wt(c.paths,c.kind==="all"?g:0);return}if(d.escape){Jn(null);return}return}if(zt){if(d.upArrow){Zn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){Zn(c=>c&&{...c,cursor:Math.min(c.rows.length,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=zt.rows.length+1){Zn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let{cursor:c,rows:g,opts:A}=zt;Zn(null);let U=c===0?g:[g[c-1]];Uy(U,A);return}if(d.escape){Zn(null),h({kind:"note",tone:"info",text:"Left as drafts \u2014 nothing changed. /publish when they have been signed off."});return}return}if(It){let{rows:c}=It;if(d.upArrow){Lt(g=>g&&{...g,cursor:Math.max(0,g.cursor-1)});return}if(d.downArrow){Lt(g=>g&&{...g,cursor:Math.min(c.length-1,g.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let g=Rg(Ju.current,Number(u),c.length-1);Ju.current=g.memory,g.index!==null&&Lt(A=>A&&{...A,cursor:g.index+1});return}if(u==="a"||u==="A"){Lt(g=>g&&{...g,cursor:0});return}if(d.return){let g=c[It.cursor],{groups:A,resolve:U,report:O}=It;if(Lt(null),g.kind==="all"){$a(A,{resolve:U,report:O});return}so(Ci(g.group,{width:Be()})),zo({group:g.group,cursor:0,fromList:!0,resolve:U,rest:A.filter(f=>f.articleId!==g.group.articleId),report:O});return}if(d.escape){Lt(null),J("/comments");return}return}if(We){let c=()=>{let{rest:g,group:A,fromList:U,resolve:O,report:f}=We;if(zo(null),!U||!f){J("/comments");return}let k=[A,...g].sort((b,x)=>b.category.localeCompare(x.category)||b.title.localeCompare(x.title));Lt({cursor:0,rows:Si(k),groups:k,resolve:O,report:f})};if(d.upArrow||d.downArrow){zo(g=>g&&{...g,cursor:g.cursor===0?1:0});return}if(u==="y"||u==="Y"||d.return&&We.cursor===0){let{group:g,resolve:A,rest:U,report:O}=We;zo(null),$a([g],{resolve:A,rest:U,...O?{report:O}:{}});return}if(u==="b"||u==="B"||d.escape||d.return){c();return}return}if(Xt){if(d.upArrow){xn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){xn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=Xt.rows.length){xn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let c=Xt.rows[Xt.cursor];xn(null),c.action==="capture"?lr(c.ids,{runLine:c.kind==="all"?["/screenshot capture --all","/capture --all"]:void 0}):c.action==="annotate"?gs(c.ids,{verifiedBefore:new Set(Le(e).filter(g=>g.state==="verified").map(g=>g.id))}):c.kind==="shot"?wd(c.ids[0]):yd(c.ids,{setup:!0,runLine:c.kind==="all"?["/screenshot author --all","/screenshot --all"]:void 0});return}if(d.escape){xn(null);return}return}if(it){if(d.escape){Cn(null);return}if(d.upArrow){Cn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){Cn(c=>c&&{...c,cursor:Math.min(Math.max(0,ps.length-1),c.cursor+1)});return}if(d.return){let c=ps[it.cursor];if(c){Cn(null);try{h({kind:"preview",name:ts(c),text:Ry(ea(Ou(e,c),"utf8"))})}catch(g){h({kind:"note",tone:"error",text:`Could not read ${c}: ${g.message}`})}}return}if(d.backspace||d.delete){Cn(c=>c&&{...c,query:c.query.slice(0,-1),cursor:0});return}if(u&&!d.ctrl&&!d.meta&&u.length===1){Cn(c=>c&&{...c,query:c.query+u,cursor:0});return}return}if(at){if(d.escape){Pn(null);return}if(d.upArrow){Pn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){Pn(c=>c&&{...c,cursor:Math.min(Math.max(0,hs.length-1),c.cursor+1)});return}if(d.return){let c=hs[at.cursor];if(c){Pn(null),Xe(c.uuid),Nt.current={uuid:c.uuid,firstPrompt:c.firstPrompt,titleFired:!0},kn(c.name),_u(c.uuid),Kn.current=[],Ye.current={printed:[],armed:[],printedAt:no.current};let g=Au(e,c.uuid);for(let A of g)h(A);h({kind:"note",tone:"ok",text:g.length?`Resumed "${c.name}" \u2014 restored ${g.length} message(s); continue where you left off.`:`Resumed "${c.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(d.backspace||d.delete){Pn(c=>c&&{...c,query:c.query.slice(0,-1),cursor:0});return}if(u&&!d.ctrl&&!d.meta&&u.length===1){Pn(c=>c&&{...c,query:c.query+u,cursor:0});return}return}if(d.tab&&!w&&ie){$(ie),xt();return}if(!w&&ae.length>0&&!yn&&u&&/^[1-9]$/.test(u)){let c=ae[Number(u)-1];if(c){$(Hn(c));return}}if(!w&&ae.length===0&&!yn&&Ye.current.armed.length>0&&u&&/^[1-9]$/.test(u)){let c=Ye.current.armed[Number(u)-1];if(c){$(c);return}}if(!w&&(cs||or)&&u==="c"&&!d.ctrl&&!d.meta&&!d.return&&!d.tab){let c=cs!=null;Su(cs??or).then(A=>{h({kind:"note",tone:A?"ok":"warn",text:A?c?"\u2713 Copied the feedback to your clipboard \u2014 send it to the d360-writer team (Teams / Slack / email).":"\u2713 Copied the prompt to your clipboard \u2014 paste it into your repo's coding agent.":c?"Couldn't reach your clipboard \u2014 select the feedback above and copy it manually.":"Couldn't reach your clipboard \u2014 select the prompt above and copy it manually."}),A&&c&&ga(null),A&&!c&&id(!0)});return}if(!Rd(u,d)){if(hd){if(d.upArrow){Vn(c=>Math.max(0,c-1));return}if(d.downArrow){Vn(c=>Math.min(_t.length-1,c+1));return}if(d.tab){$("/"+(_t[sa]?.name??"")+" "),Vn(0);return}if(d.return){let c=_t[sa];if(c){let g=w.trim().slice(1).split(/\s+/).slice(1).join(" ");if(Cp(c.usage)&&!g){$("/"+c.name+" "),Vn(0);return}bs("/"+c.name+(g?" "+g:""));return}}}else{if(d.upArrow){if(w!==""&&Yn===null){$s(-1);return}let c=ia.current;if(!c.length)return;let g=Yn===null?c.length-1:Math.max(0,Yn-1);os(g),$(c[g]??"");return}if(d.downArrow){if(w!==""&&Yn===null){$s(1);return}let c=ia.current;if(Yn===null)return;let g=Yn+1;g>=c.length?(os(null),$("")):(os(g),$(c[g]??""));return}}if(d.return){bs();return}if(d.backspace||d.delete){R();return}if(d.escape){$(""),Vn(0),xt(),X([]),eo(null),Ce.current=!0;return}u&&!d.ctrl&&!d.meta&&vd(u)}}}),rt(()=>{if(C||E)return;let u=Sn.current.shift();u!==void 0&&(la([...Sn.current]),bs(u))},[C,E,bs]),oe(xe,{flexDirection:"column",width:ze,children:[ba!==null&&oe(xe,{marginTop:1,flexDirection:"column",children:[ba.truncated&&H(q,{dimColor:!0,children:"\u2026"}),H(q,{children:ba.text})]}),C&&Qo?H(SP,{p:Qo}):null,td?H(RP,{text:td}):C&&!Qo?H(xP,{startTime:Dt.current,chars:jy}):null,H(xe,{borderStyle:"round",borderColor:pd.prod?"yellow":ee,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:w?xd.map((u,d)=>{let c=p.text.slice(u.start,u.end),g=d===Zi(xd,p.pos),A=Math.min(p.pos,u.end)-u.start;return oe(q,{children:[H(q,{color:ee,children:d===0?"> ":" "}),g?oe(qo,{children:[c.slice(0,A),H(Ho,{ch:c[A]??" "}),c.slice(A+1)]}):c||" "]},`${d}-${u.start}`)}):oe(q,{children:[H(q,{color:ee,children:"> "}),tr?H(Ho,{ch:" "}):ie&&!C&&de?oe(qo,{children:[H(Ho,{ch:de[0],dim:!0}),H(q,{color:"gray",children:de.slice(1)})]}):ie&&!C?oe(qo,{children:[H(Ho,{ch:ie[0],dim:!0}),H(q,{color:"gray",children:ie.slice(1)}),H(q,{dimColor:!0,children:" (tab)"})]}):(wa.isSetup||!Gn)&&!C?oe(qo,{children:[H(Ho,{ch:wa.text[0],dim:!0}),H(q,{color:"gray",children:wa.text.slice(1)})]}):H(Ho,{ch:" "})]})}),ed.length>0&&H(xe,{flexDirection:"column",paddingX:1,children:ed.map((u,d)=>H(q,{color:"gray",children:`\u29D7 queued: ${u}`},`${d}-${u.slice(0,24)}`))}),er?H(_g,{tab:er.tab,scroll:er.scroll,rows:Fy,width:ze,version:o,engineVersion:Cy}):bn?oe(xe,{flexDirection:"column",paddingX:1,children:[H(q,{color:ee,bold:!0,children:"Select model"}),H(q,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),At.map((u,d)=>oe(q,{color:d===bn.cursor?ee:void 0,children:[d===bn.cursor?"\u276F ":" ",`${d+1}. ${u.label}${d===bn.current?" \u2714":""}`.padEnd(16),H(q,{color:"gray",children:u.desc})]},u.label)),H(q,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Yt?oe(xe,{flexDirection:"column",paddingX:1,children:[H(q,{color:ee,bold:!0,children:"Switch connection profile"}),H(mn,{rows:Yt.rows,cursor:Yt.cursor,cap:Mt,render:(u,d,c)=>oe(q,{color:c?ee:void 0,children:[c?"\u276F ":" ",`${d+1}. ${u.name}${d===Yt.current?" \u2714":""}`.padEnd(20),H(q,{color:"gray",children:`${u.env} \xB7 ${u.who??"not signed in"}`}),u.prod?H(q,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},u.name)}),H(q,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Kt?oe(xe,{flexDirection:"column",paddingX:1,children:[H(q,{color:ee,bold:!0,children:"Pick your Document360 environment"}),H(mn,{rows:Kt.rows,cursor:Kt.cursor,cap:Mt,render:(u,d,c)=>oe(q,{color:c?ee:void 0,children:[c?"\u276F ":" ",`${d+1}. ${u.name}`.padEnd(16),H(q,{color:"gray",children:u.apiUrl}),u.note?H(q,{color:"yellow",children:` \u26A0 ${u.note}`}):null]},u.name)}),H(q,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):Je?oe(xe,{flexDirection:"column",paddingX:1,children:[H(q,{color:ee,bold:!0,children:"Switch workspace"}),H(q,{dimColor:!0,children:`environment ${Je.environment} \xB7 project ${Je.projectName??`${Je.projectId.slice(0,8)}\u2026`}`}),H(mn,{rows:Je.rows,cursor:Je.cursor,cap:Mt,render:(u,d,c)=>oe(q,{color:c?ee:void 0,children:[c?"\u276F ":" ",`${d+1}. ${u.name}${d===Je.current?" \u2714":""}`.padEnd(30),H(q,{color:"gray",children:u.type??""})]},u.id)}),H(q,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):gt?oe(xe,{flexDirection:"column",paddingX:1,children:[H(q,{color:ee,bold:!0,children:"Choose project"}),H(q,{dimColor:!0,children:`environment ${gt.environment}`}),H(mn,{rows:gt.rows,cursor:gt.cursor,cap:Mt,render:(u,d,c)=>oe(q,{color:c?ee:void 0,children:[c?"\u276F ":" ",`${d+1}. ${u.name}${d===gt.current?" \u2714":""}`.padEnd(30),H(q,{color:"gray",children:u.sub??""})]},u.id)}),H(q,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):Ze?(()=>{let d=Math.min(Math.max(0,Ze.cursor-Math.floor(7)),Math.max(0,Ze.rows.length-14)),c=Ze.rows.slice(d,d+14),g=Ze.rows.filter(A=>A.checked).length;return oe(xe,{flexDirection:"column",paddingX:1,children:[H(q,{color:ee,bold:!0,children:`Which folders back the user docs? (${g} selected of ${Ze.rows.length})`}),d>0?H(q,{dimColor:!0,children:` \u2191 ${d} more`}):null,c.map((A,U)=>{let O=d+U;return oe(q,{color:O===Ze.cursor?ee:void 0,children:[O===Ze.cursor?"\u276F ":" ",A.checked?"\u25C9 ":"\u25CB ",A.path.padEnd(Math.min(48,ze-34)),H(q,{color:"gray",children:ci(A)})]},A.path)}),d+14<Ze.rows.length?H(q,{dimColor:!0,children:` \u2193 ${Ze.rows.length-d-14} more`}):null,H(q,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():vt?oe(xe,{flexDirection:"column",paddingX:1,children:[H(q,{color:ee,bold:!0,children:vt.title??"Which category? (pick one to scope to)"}),H(mn,{rows:vt.rows,cursor:vt.cursor,cap:Mt,render:(u,d,c)=>oe(q,{color:c?ee:void 0,children:[c?"\u276F ":" ",`${`${d+1}.`.padEnd(3)} ${u.label} (${u.count})`.padEnd(Math.min(44,Math.max(20,ze-24))),H(q,{color:"gray",children:` ${u.token}`})]},u.token)}),H(q,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):jt?oe(xe,{flexDirection:"column",paddingX:1,children:[H(q,{color:ee,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),H(mn,{rows:jt.rows,cursor:jt.cursor,cap:Mt,render:(u,d,c)=>oe(q,{color:c?ee:void 0,bold:u.kind==="category"&&!c,children:[c?"\u276F ":" ",`${u.indent?" ":" "}${`${d+1}.`.padEnd(3)} ${u.label}`.padEnd(Math.min(56,ze-24)),u.note?H(q,{color:"gray",children:u.note}):null]},`${u.kind}:${u.paths.join(",")}`)}),H(q,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter push (draft) \xB7 esc cancel"})]}):zt?oe(xe,{flexDirection:"column",paddingX:1,children:[H(q,{color:ee,bold:!0,children:"Publish live to your readers \u2014 this is what they will see:"}),H(mn,{rows:[{path:"",articleId:"",label:`Publish all ${zt.rows.length} live`,version:void 0},...zt.rows],cursor:zt.cursor,cap:Mt,render:(u,d,c)=>oe(q,{color:c?ee:void 0,bold:d===0&&!c,children:[c?"\u276F ":" ",` ${`${d+1}.`.padEnd(3)} ${u.label}`.padEnd(Math.min(56,ze-24)),d>0?H(q,{color:"gray",children:u.version?`draft v${u.version} \u2192 live`:"draft \u2192 live"}):null]},`${d}:${u.path||"all"}`)}),H(q,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish LIVE \xB7 esc leave as drafts"})]}):It?oe(xe,{flexDirection:"column",paddingX:1,children:[H(q,{color:ee,bold:!0,children:"Which comments do you want to look at?"}),H(mn,{rows:It.rows,cursor:It.cursor,cap:Mt,render:(u,d,c)=>oe(q,{color:c?ee: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,ze-24))),u.kind==="article"?H(q,{color:"gray",children:u.note}):null]},u.kind==="all"?"all":u.group.articleId)}),H(q,{dimColor:!0,children:"\u2191\u2193 move \xB7 type a number \xB7 enter \xB7 esc close"}),It.resolve?H(q,{dimColor:!0,children:"--resolve is on: threads you answer will be closed as well as replied to"}):null]}):We?oe(xe,{flexDirection:"column",paddingX:1,children:[H(q,{color:ee,bold:!0,children:`${We.group.title} \u2014 ${We.group.threads.length} comment${We.group.threads.length===1?"":"s"}`}),oe(q,{color:We.cursor===0?ee:void 0,children:[We.cursor===0?"\u276F ":" ",We.resolve?"Yes \u2014 fix them, push the draft, reply and resolve":"Yes \u2014 fix them, push the draft to Document360, then reply"]}),oe(q,{color:We.cursor===1?ee:void 0,children:[We.cursor===1?"\u276F ":" ",We.fromList?"No \u2014 back to the list":"No \u2014 leave them for now"]}),H(q,{dimColor:!0,children:"\u2191\u2193 move \xB7 enter select \xB7 y answer \xB7 esc back"})]}):Xt?oe(xe,{flexDirection:"column",paddingX:1,children:[H(q,{color:ee,bold:!0,children:Xt.title}),(()=>{let{rows:u,cursor:d}=Xt,c=Vi(u.length,d,Mt),g=c.start,A=u.slice(c.start,c.end),U=`${u.length}.`.length+1,O=kh(u,Math.max(20,ze-4-U));return oe(qo,{children:[g>0?H(q,{color:"gray",children:` \u2026 ${g} more above`}):null,A.map((f,k)=>{let b=g+k,x=b===d,v=O[b];return oe(q,{color:x?ee:void 0,bold:(f.kind==="all"||f.kind==="category")&&!x,children:[x?"\u276F ":" ",`${b+1}.`.padEnd(U),v.head,v.note?H(q,{color:"gray",children:v.note}):null]},`${f.action}:${f.kind}:${f.ids.join(",")}`)}),c.below>0?H(q,{color:"gray",children:` \u2026 ${c.below} more below`}):null]})})(),H(q,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter run \xB7 esc cancel"})]}):it?oe(xe,{flexDirection:"column",paddingX:1,children:[H(q,{color:ee,bold:!0,children:`Preview article${it.query?` \u2014 filter: ${it.query}`:" (type to filter)"}`}),ps.length===0?H(q,{color:"gray",children:"no articles match"}):ps.map((u,d)=>oe(q,{color:d===it.cursor?ee:void 0,children:[d===it.cursor?"\u276F ":" ",u]},u)),H(q,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):at?oe(xe,{flexDirection:"column",paddingX:1,children:[H(q,{color:ee,bold:!0,children:`Resume session${at.query?` \u2014 filter: ${at.query}`:" (type to filter)"}`}),hs.length===0?H(q,{color:"gray",children:"no sessions match"}):hs.map((u,d)=>oe(q,{color:d===at.cursor?ee:void 0,children:[d===at.cursor?"\u276F ":" ",u.name.slice(0,28).padEnd(30),H(q,{color:d===at.cursor?ee:"gray",children:u.firstPrompt.slice(0,Math.max(10,ze-40))})]},u.uuid)),H(q,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):hd?oe(xe,{flexDirection:"column",children:[An>0?H(q,{dimColor:!0,children:` \u22EF ${An} more above`}):null,ka.map((u,d)=>{let c=An+d,g=u.name==="model"&&ca?`${u.desc} (currently ${ca})`:u.desc,A=Math.max(20,ze-4),U=u.usage.length>A?`${u.usage.slice(0,A-1)}\u2026`:u.usage,O=A-Math.max(U.length,22)-1,f=O<=1?"":g.length>O?`${g.slice(0,O-1)}\u2026`:g;return oe(q,{color:c===ds?ee:void 0,children:[c===ds?"\u276F ":" ",U.padEnd(22)," ",H(q,{color:c===ds?ee:"gray",children:f})]},u.name)}),An+ka.length<_t.length?H(q,{dimColor:!0,children:` \u22EF ${_t.length-An-ka.length} more below`}):null,H(q,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!C&&!w&&ae.length>0?oe(xe,{flexDirection:"column",paddingX:1,children:[Zu?H(q,{color:ee,children:Zu}):null,ae.map((u,d)=>{let c=Hn(u),g=c.slice(0,Math.max(20,ze-5)),A=ze-g.length-7,U=A>=12?(Bg(u)??xp(c)).slice(0,A):"";return oe(q,{children:[H(q,{color:ee,children:d+1})," ",g,U?H(q,{dimColor:!0,children:` \u2014 ${U}`}):null]},c)}),H(q,{dimColor:!0,children:`press 1-${ae.length} to fill \xB7 esc cancel`})]}):H(xe,{paddingX:1,children:oe(q,{color:"gray",children:[pd.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${ca??"model n/a"}${t.kind==="api"?od>0?` \xB7 ${tt(od)}`:"":nd>0?` \xB7 ${ln(nd)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}te();import{jsx as EP}from"react/jsx-runtime";async function Py(e=process.cwd(),t="auto",n,o="0.0.0"){let r=AP(t);r.kind==="none"&&(console.error(""),console.error(j("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${z("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${z("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=TP(EP(Sy,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
|
|
515
|
+
`),process.exit(0)}te();import{writeCrashLog as Ty,isBenignTransportError as DP}from"document360-engine";var Ay=!1;function Vu(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function Ey(e){if(Ay)return;Ay=!0;let t=(n,o)=>{if(DP(o)){Ty({kind:n,level:"transport",message:Vu(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=Ty({kind:n,level:"fatal",message:Vu(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
|
|
516
|
+
`+j(`\u2717 d360-writer crashed: ${Vu(o)}`)+`
|
|
517
517
|
`),r&&process.stderr.write(y(` Crash details: ${r}`)+`
|
|
518
518
|
`+y(" Run: d360-writer logs")+`
|
|
519
|
-
`),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var
|
|
519
|
+
`),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var LP=jP(import.meta.url),ra=LP("../package.json");Ey("d360-writer");var bt=new NP;function Yu(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}bt.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=>{Yu(e),await Ps({profile:e.profile,manual:e.manual})});bt.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Yu(e),await Wd({profile:e.profile})});bt.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Yu(e),await Fd({profile:e.profile})});var Ku=bt.command("profile").description("Manage connection profiles for the current repo");Ku.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>Ts(process.cwd()));Ku.command("use <name>").description("Set the default profile for this repo").action(e=>As(process.cwd(),e));Ku.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>Es(process.cwd(),e));var Dy=bt.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");Dy.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>po(process.cwd(),e.profile));Dy.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await Dd(process.cwd(),e,t.profile)});var Ny=bt.command("project").description("Choose the Document360 project for this repo (active profile's identity)");Ny.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>Rs(process.cwd(),e.profile));Ny.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await jd(process.cwd(),e,t.profile)});bt.command("init").description("Scaffold .d360-writer/config.json for this repo (interactive)").action(async()=>{let{initCommand:e}=await Promise.resolve().then(()=>(Fs(),yp));await e()});bt.command("logs").description("Show the API + crash log files (send these to support when reporting a problem)").action(()=>qd());bt.command("doctor").description("Health-check: node, Claude auth, Document360 login, profile/workspace, category map, API reachability").action(async()=>{let{renderDoctorChecks:e,runDoctorChecks:t}=await Promise.resolve().then(()=>(bi(),jf)),n=await t(process.cwd(),ra.version);for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});bt.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(ra.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(IP.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 Gd(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 yg(e.cwd,e.auth,e.profile,ra.version):await Py(e.cwd,e.auth,e.profile,ra.version)});bt.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
|