document360-writer 0.5.241 → 0.5.243
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 +189 -186
- package/package.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var Ay=Object.defineProperty;var or=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var gd=(e,t)=>{for(var n in t)Ay(e,n,{get:t[n],enumerable:!0})};import Qt from"picocolors";var Z,Dy,Ny,jy,yd,rr,y,N,H,G,K,$e,We,ke,ee=or(()=>{"use strict";Z="#7f56d9",[Dy,Ny,jy]=[127,86,217],yd=e=>Qt.isColorSupported?`\x1B[38;2;${Dy};${Ny};${jy}m${e}\x1B[39m`:e,rr=e=>Qt.bold(yd(e)),y=e=>Qt.dim(e),N=e=>Qt.red(e),H=e=>Qt.yellow(e),G=e=>Qt.green(e),K=yd,$e=e=>Qt.gray(e),We=e=>Qt.bold(e),ke=(e,t)=>`${e} ${t}`});import{existsSync as ao,writeFileSync as tn,readFileSync as vw,readdirSync as xw}from"node:fs";import{join as Fd}from"node:path";import{devHintsGuidePath as Ts,hintsDir as Wd,hooksDir as Ud,architectureDir as Gd,messagesDir as Aa,creatorNotesPath as Bd,devhintsStatePath as Vd,directivesPath as Hd,DIRECTIVES_HEADER as Cw,roadmapPath as qd,ROADMAP_HEADER as Rw,ensureDir as ar,writeMessage as Sw,listOpenForDev as Pw,stampDone as Tw}from"document360-engine";function Yd(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
|
|
3
3
|
|
|
4
4
|
<!-- devhints script v${Re} \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 Aw(){return`# Creator notes (optional \u2014 for the docs agent and the builder)
|
|
239
239
|
|
|
240
240
|
<!-- The ORIGINAL CREATOR's context. Most repos leave this empty \u2014 that's fine.
|
|
241
241
|
The builder agent reads this FIRST and treats it as authoritative when writing the architecture
|
|
@@ -249,12 +249,12 @@ Anything only a human knows that would help document this product. For example:
|
|
|
249
249
|
- Gotchas or non-obvious behavior.
|
|
250
250
|
|
|
251
251
|
(Replace these examples with your notes, or leave the file as-is to skip \u2014 it's optional.)
|
|
252
|
-
`}function
|
|
253
|
-
`)}
|
|
254
|
-
`)}function
|
|
255
|
-
`)}function
|
|
256
|
-
`)}),n.notifiedBuilder=!0)}}catch{}return n}function
|
|
257
|
-
`)}function
|
|
252
|
+
`}function co(e){ar(Wd(e)),ar(Gd(e)),ar(Aa(e));for(let n of[Wd(e),Aa(e)]){let o=Fd(n,".gitkeep");ao(o)||tn(o,`# Keeps this document360-writer inbox tracked in git even when empty.
|
|
253
|
+
`)}ao(Bd(e))||tn(Bd(e),Aw()),ao(Hd(e))||tn(Hd(e),Cw),ao(qd(e))||tn(qd(e),Rw),tn(Ts(e),Yd()),ar(Ud(e)),tn(Fd(Ud(e),"open-questions.mjs"),Ew);let t=mt(e);return zd(e,new Date().toISOString()),t}async function Kd(e,t){for(let n of uo(co(t.cwd)))console.log(n);return{kind:"continue"}}function Pn(){return[`This is document360-writer's dev hand-off setup (v${Re}).`,'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": ${Re},`,' "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 Na(e){try{let t=vw(Vd(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function zd(e,t){let o={...Na(e)??{},emittedVersion:Re,emittedAt:t};tn(Vd(e),`${JSON.stringify(o,null,2)}
|
|
255
|
+
`)}function Ot(e){try{return xw(Gd(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function mt(e){let n=Na(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<Re?"stale":"current",completedVersion:n}}function Dw(e){let t=new RegExp(`${Da.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(\\d+)\\)`).exec(e);return t?Number(t[1]):null}function Es(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,supersededRequests:[],toVersion:Re};try{if(!ao(Ts(e)))return n;let o=Na(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;if(Re>r&&(ar(Aa(e)),tn(Ts(e),Yd()),zd(e,t),n.guideRefreshed=!0),Re>s){let i=Pw(e).filter(l=>l.kind==="request"&&l.subject.startsWith(Da)),a=i.filter(l=>(Dw(l.subject)??Re)>=Re);for(let l of i.filter(p=>!a.includes(p)))Tw(e,l.file,{doneAt:t,answeredBy:"docs"}),n.supersededRequests.push(l.subject);a.length===0&&(Sw(e,{id:`onb${Re}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${Da}${Re})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${Re}${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:","",Pn()].join(`
|
|
256
|
+
`)}),n.notifiedBuilder=!0)}}catch{}return n}function As(e){if(!ao(Ts(e)))return[];let t=mt(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${Re}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,lo,Pn(),lo,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function ja(){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 Ds(){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):",lo,ja(),lo]}function uo(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${Re}.`," 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):",lo,Pn(),lo,"","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 lo,Re,Ew,Da,nn=or(()=>{"use strict";lo="-".repeat(64),Re=12,Ew=`#!/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,81 +292,81 @@ try {
|
|
|
292
292
|
} catch {
|
|
293
293
|
/* a session-start nudge must never break the session */
|
|
294
294
|
}
|
|
295
|
-
`;
|
|
296
|
-
`),"utf8")}async function Da(){let e=process.cwd(),t=Wd(e);if(io(t)&&!await kw({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(w("init cancelled.")),{kind:"continue"};let n=Gd(e)??Md(e),o=await sr({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await sr({message:"Capture directory (where document360-capture .spec.ts files live):",default:Bd}),s=await sr({message:"Screenshot output directory:",default:Hd}),i=await sr({message:"Default connection profile name:",default:"berlin"}),a=await sr({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),l={projectId:o,docsDir:Ud,captureDir:r,outputDir:s,profiles:{[i]:{connection:{environment:a},production:!1}},defaultProfile:i,authoritativeSourceFiles:Vd(e)},p=Cw(e);p?.terminologyGlossary&&(l.terminologyGlossary=p.terminologyGlossary),Fd(l,e),qd(e);let g=ro(e);console.log(""),console.log(V(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${K(`d360-writer login --profile ${i}`)} ${w("(sign in; project & workspace auto-selected)")}`),console.log("");for(let y of so(g))console.log(y);return console.log(""),console.log(`${w("Then ask:")} ${K('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function Gd(e){let t=Es(e,"package.json");if(!io(t))return null;try{return JSON.parse($w(t,"utf8")).name??null}catch{return null}}function Vd(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])io(Es(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Es(e,n);io(o)&&!Sw(o)&&t.push(n)}return t}function Sw(e){try{return vw(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var As=er(()=>{"use strict";ee();en()});import{createRequire as zw}from"node:module";import{existsSync as Xw,readFileSync as Qw}from"node:fs";import{dirname as bp,join as kp}from"node:path";function Ot(){let e;try{e=Jw.resolve("document360-capture/helpers")}catch{return null}let t=bp(e);for(let n=0;n<5&&!Xw(kp(t,"package.json"));n++)t=bp(t);try{let n=JSON.parse(Qw(kp(t,"package.json"),"utf8"));return n.name==="document360-capture"&&n.version?n.version:null}catch{return null}}var Jw,cr=er(()=>{"use strict";Jw=zw(import.meta.url)});var lf={};rd(lf,{doctorCommand:()=>Rr,renderDoctorChecks:()=>af,runDoctorChecks:()=>sf});import{existsSync as C$}from"node:fs";import{d360GetAll as R$,getAccessToken as S$,isExpired as rc,loadProfileMap as P$,loadTokens as T$,packageSkillsDir as of,ENGINE_VERSION as E$,projectConfigPath as A$,readProjectConfig as D$,DEFAULT_DOCS_DIR as N$,fetchManifestSummary as j$,resolveActiveProfile as I$,classifyClaudeAuth as L$,CLAUDE_CODE_SETUP_HINT as rf,resolveModelSetting as O$,probeModel as _$,detectAppType as M$,playbookSkillName as F$,D360AuthError as W$,applyStructureOrder as U$}from"document360-engine";async function sf(e,t){let n=[],o=Ot();n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${E$}${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=L$();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. ${rf}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:rf});let i=O$(e);if(n.push({level:"ok",label:`Model: ${i.model} (${i.source==="auto"?"auto \u2014 right-sized for docs; /model to change":i.source})`}),s.state==="ready"){let x=await _$(e,i.model??void 0);x.ok?n.push({level:"ok",label:`Model reachable \u2014 replied in ${(x.latencyMs/1e3).toFixed(1)}s`}):x.timedOut?n.push({level:"fail",label:"Model unreachable \u2014 no response in 30s (a docs turn will hang, then end with 0 tokens / no output)",fix:`Usually a corporate proxy/firewall or org policy blocking the Claude model API. Check this machine's network access to the Claude endpoint; confirm with: claude -p "say hi"`}):n.push({level:"fail",label:`Model call failed \u2014 ${x.error??"no output"} (a docs turn will end with 0 tokens / no output)`,fix:'Check sign-in, the selected model (/model), and network access to the Claude endpoint; confirm with: claude -p "say hi"'})}let a=D$(e);if(!a)return n.push({level:"fail",label:`No ${A$(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${a.projectId}`});let l=(a.docsDir??N$).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 g=a.appType??M$(e);if(g){let x=a.appType?"from config":"auto-detected",P=g==="web"||g==="cli";n.push({level:"ok",label:`Genre: ${g} (${x})${P?` \u2192 ${F$(g)} loaded`:" \u2014 no doc-type playbook for this genre yet (generic skills)"}`})}else n.push({level:"warn",label:"Genre: unclassified \u2014 no doc-type playbook is loading (generic output)",fix:"Run /genre <web|cli|service|library> to pick \u2014 raises docs to that genre's craft bar"});let y;try{y=I$(e),n.push({level:"ok",label:`Profile: ${y.name} (${y.connection.name})${y.production?" \u26A0 PRODUCTION":""}`})}catch(x){return n.push({level:"fail",label:`Profile config: ${x.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let v=T$(y.name);v?rc(v)&&!v.refreshToken?n.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):rc(v)?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(v.expiresAt).toLocaleString()})`}):n.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${y.name})`}),n.push(y.project.workspaceId?{level:"ok",label:`Workspace: ${y.project.workspaceName??y.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let A=P$(e,y.name);A?A.projectId&&y.project.projectId&&A.projectId!==y.project.projectId?n.push({level:"fail",label:`Category map projectId (${A.projectId}) \u2260 profile projectId (${y.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(A.articles).length} articles, ${Object.keys(A.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${y.name}" (created on first /publish)`}),n.push(C$(of())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${of()}`,fix:"Reinstall document360-writer (broken install)"});let S=ft(e);if(S.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${Re})`}):S.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${S.completedVersion}, current is v${Re}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),v&&(!rc(v)||v.refreshToken)){let x={profile:y.name,connection:y.connection};try{await S$(x);let D=await R$(x,"/v3/projects");n.push({level:"ok",label:`API reachable (${y.connection.apiUrl}) \u2014 ${D.length} project(s) visible`})}catch(D){n.push({level:"fail",label:`API call failed: ${D.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let P=A?.projectId??y.project.projectId;if(P&&y.project.workspaceId){try{let D=await j$(x,P,y.project.workspaceId);if(D){let I=(D.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Workspace sync manifest: available on ${y.connection.name} (${D.languages?.length??0} language${(D.languages?.length??0)===1?"":"s"}) \xB7 hash ${I||"(none)"}`})}else n.push({level:"ok",label:`Workspace sync manifest: not live on ${y.connection.name} yet \u2014 sync uses the per-article path (nothing to do)`})}catch(D){D instanceof W$||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(D.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${y.project.projectName??P})`,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 (${D.message.slice(0,80)})`})}try{let D=await U$({cwd:e,profileName:y.name,dryRun:!0}),I=D.categoriesReordered+D.articlesReordered;if(D.skipped==="no category map")n.push({level:"ok",label:"Reading order: nothing to check yet (no articles published)"});else if(D.skipped)n.push({level:"warn",label:`Reading order: can't be checked (${D.skipped})`,fix:"Your article order on Document360 may not match your structure \u2014 /publish syncs it once this resolves"});else if(D.unverified)n.push({level:"warn",label:`Reading order: ${D.unverified} of your articles aren't listed by Document360, so their order can't be set`,fix:"Usually means those articles are not published (the listing returns published articles). Publish them, then /publish re-syncs the order"});else if(I>0){let O=[D.categoriesReordered>0?`${D.categoriesReordered} categor${D.categoriesReordered===1?"y":"ies"}`:"",D.articlesReordered>0?`${D.articlesReordered} article${D.articlesReordered===1?"":"s"}`:""].filter(Boolean);n.push({level:"warn",label:`Reading order: ${O.join(" + ")} out of order on Document360`,fix:"Run /publish \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(D){n.push({level:"warn",label:`Reading order: check failed (${D.message.slice(0,80)})`})}}}return n}function af(e){let t=[""];for(let r of e){let s=r.level==="ok"?V("\u2713"):r.level==="warn"?H("\u26A0"):j("\u2717");t.push(` ${s} ${r.label}${r.detail?w(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${w("fix:")} ${K(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 Rr(e,t){console.log(w("Running checks\u2026"));for(let n of af(await sf(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var di=er(()=>{"use strict";en();ee();cr()});import{Command as DS}from"commander";import{createRequire as NS}from"node:module";import{AUTH_MODES as jS}from"document360-engine";import{input as My}from"@inquirer/prompts";import{loginPkce as Fy,refreshTokens as Wy,toStoredTokens as pd,clearTokens as Uy,decodeJwtClaims as dd,isExpired as By,loadTokens as Hy,saveTokens as hd,resolveActiveProfile as gs,setProfileProject as qy,readProjectConfig as Gy}from"document360-engine";ee();import{select as vy}from"@inquirer/prompts";import{resolveActiveProfile as xy,setProfileProject as Cy,resolveProjectId as Ry,listWorkspaces as Sy}from"document360-engine";async function nr(e,t){let n=xy(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Ry(o);return{workspaces:await Sy(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var id=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function ba(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 hs(e,t,n,o,r){Cy(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function ad(e,t,n){let o;try{o=await nr(e,n)}catch(s){return console.log(j(`Could not list workspaces: ${s.message}`)),1}let r=ba(o.workspaces,t);return r?(hs(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 to(e,t){let n;try{n=await nr(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(w("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let p of o)console.log(` ${p.id===i?K("\u25CF"):" "} ${id(p)} ${w(p.id)}`);console.log(w("Run: d360-writer workspace use <name>"));return}let a=await vy({message:"Select the Document360 workspace for this repo:",choices:o.map(p=>({name:`${id(p)}${p.id===i?" (current)":""}`,value:p.id}))}),l=o.find(p=>p.id===a);hs(e,s,r,a,l?.name),console.log(V(`\u2713 Workspace set to "${l?.name??a}" for profile "${s}".`))}ee();import{select as Py}from"@inquirer/prompts";import{resolveActiveProfile as Ty,setProfileProject as Ey,listProjects as Ay}from"document360-engine";async function Xt(e,t){let n=Ty(e,t),o={profile:n.name,connection:n.connection};return{projects:await Ay(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var ld=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function ka(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 fs(e,t,n,o){Ey(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function cd(e,t,n){let o;try{o=await Xt(e,n)}catch(s){return console.log(j(`Could not list projects: ${s.message}`)),1}let r=ka(o.projects,t);return r?(fs(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 ms(e,t){let n;try{n=await Xt(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(w("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let l of o)console.log(` ${l.id===s?K("\u25CF"):" "} ${ld(l)} ${w(l.id)}`);console.log(w("Run: d360-writer project use <name>"));return}let i=await Py({message:"Select the Document360 project for this repo:",choices:o.map(l=>({name:`${ld(l)}${l.id===s?" (current)":""}`,value:l.id}))}),a=o.find(l=>l.id===i);fs(e,r,i,a?.name),console.log(V(`\u2713 Project set to "${a?.name??i}" for profile "${r}". Next: pick a workspace.`))}ee();import Dy from"picocolors";function Ny(e=process.env){return e.FORCE_HYPERLINK==="0"||!Dy.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 jy(e,t=e,n){return Ny(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Iy=/https?:\/\/[^\s\x1b]+/g;function or(e,t){return e.replace(Iy,n=>jy(n,n,t))}import{readProjectConfig as ud,sunsetEnvironment as Ly,resolveActiveProfile as Oy}from"document360-engine";function _y(e,t){let n=ud(e);return Object.entries(n?.profiles??{}).find(([,o])=>(o.connection?.environment??"berlin")===t)?.[0]??null}function Qt(e,t){try{if(!ud(e))return null;let n=Oy(e,t),o=Ly(n.connection.name);if(!o)return null;let r=_y(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 fd(e){return{...dd(e.idToken)??{},...dd(e.accessToken)??{}}}function ys(e){let t=fd(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 ws(e){let t=gs(process.cwd(),e.profile),n=t.connection;console.log(w(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=Qt(process.cwd(),e.profile);o&&(console.log(H(`\u26A0 ${o.why} \u2014 and signing in does NOT change it (the environment comes from the profile, not the login).`)),console.log(H(` To move: ${o.cmd}${o.replacementProfile?"":", then /login"}`)));let r=await Fy(n,{manual:e.manual,promptForRedirect:i=>My({message:i})},i=>console.log(or(i))),s=pd(t.name,r);if(hd(s),await $a(s,t.name,i=>console.log(w(i))),console.log(""),console.log(V(`\u2713 Logged in to "${t.name}" as ${ys(s)}`)),console.log(w(` access token expires: ${s.expiresAt}`)),console.log(w(` refresh token: ${s.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{Gy(process.cwd())?.profiles?.[t.name]&&(console.log(""),await to(process.cwd(),t.name))}catch{}}async function $a(e,t,n){let r=fd(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(gs(process.cwd(),t).project.projectId)return;let i;try{let{projects:a}=await Xt(process.cwd(),t);i=a.find(l=>l.id===r)?.name}catch{}qy(process.cwd(),t,{projectId:r,projectName:i}),n(` Project "${i??r}" written to profile "${t}".`)}catch{}}async function md(e){let t=gs(process.cwd(),e.profile),n=t.connection,o=Hy(t.name);if(!o){console.log(j(`Not logged in to Document360 (profile "${t.name}").`)),console.log(w(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${K(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${ys(o)}`),By(o))if(o.refreshToken)try{let r=pd(t.name,await Wy(n,o.refreshToken));hd(r),console.log(V(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(H(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(w(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(H("Session expired (no refresh token).")),console.log(w(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(w(` expires: ${o.expiresAt}`))}async function gd(e){let t=gs(process.cwd(),e.profile);Uy(t.name)?console.log(V(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(w(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}ee();import{readProjectConfig as yd,writeProjectConfig as Vy,resolveActiveProfile as Yy,loadTokens as Ky,isExpired as zy}from"document360-engine";function bs(e){let t=yd(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?K("\u25CF "):" ",s=o.production?H(" \u26A0 PRODUCTION"):"",i=o.connection.environment??"(inline)",a=Ky(n),l=a?zy(a)&&!a.refreshToken?H("expired"):w("logged in"):w("not logged in");console.log(`${r}${K(n)} \u2192 ${i}${s} [${l}]`)}console.log(""),console.log(w("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function ks(e,t){let n=yd(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,Vy(n,e);let o=n.profiles[t].production?H(" \u26A0 PRODUCTION"):"";console.log(V(`\u2713 Default profile is now "${t}"${o}`))}function $s(e,t){try{let n=Yy(e,t);console.log(""),console.log(`Profile ${K(n.name)}${n.production?H(" \u26A0 PRODUCTION"):""}`),console.log(w(` api: ${n.connection.apiUrl}`)),console.log(w(` identity: ${n.connection.authorizationUrl}`)),console.log(w(` clientId: ${n.connection.clientId}`)),console.log(w(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(w(` project: ${n.project.projectId??"(set at login)"}`)),console.log(w(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(j(n.message)),process.exitCode=1}}ee();import{existsSync as Xy,readdirSync as Qy,statSync as wd}from"node:fs";import{join as bd}from"node:path";import{apiLogDir as Jy}from"document360-engine";function kd(){let e=Jy();if(console.log(""),console.log(`Document360 API logs: ${K(e)}`),!Xy(e)){console.log(w(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Qy(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(w(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let s=(wd(bd(e,r)).size/1024).toFixed(1);console.log(` ${r} ${w(`${s} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${w("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let s=(wd(bd(e,r)).size/1024).toFixed(1);console.log(` ${j(r)} ${w(`${s} KB`)}`)}}console.log(""),console.log(w("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(w("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}ee();import{createSession as Zy,resolveAuth as ew,findByName as tw,slugify as nw,touchSession as ow,upsertSession as rw,resolveActiveProfile as sw}from"document360-engine";async function $d(e,t,n,o,r,s){let i=ew(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 ${K("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${K("d360-writer --auth subscription")}`),process.exit(2)),i.kind==="subscription"&&console.error(w("Using your Claude subscription (no API key set)."));let a=null;try{a=sw(e,r)}catch(v){console.error(j(`Document360 profile error: ${v.message}`)),process.exit(2)}a.production&&(console.error(H(`\u26A0 Profile "${a.name}" is PRODUCTION.`)),s||(console.error(j("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(w(" --yes given \u2014 proceeding against production.")));let l;if(o){let v=tw(e,o);v||(console.error(j(`No saved session matches "${o}" in this repo.`)),console.error(w("List sessions inside the REPL with /resume.")),process.exit(2)),l=v.uuid,console.error(w(`Resuming "${v.name}"`))}let p=Zy({cwd:e,resume:l,profileName:r,allowProdWrites:s===!0}),g=l??null,y=1;for await(let v of p.send(t))switch(v.type){case"session":if(!g){g=v.sessionId;let A=new Date().toISOString();rw({uuid:g,name:nw(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:A,updatedAt:A})}break;case"text":process.stdout.write(v.delta);break;case"tool":console.error($e(` \u2699 ${v.name}`));break;case"result":y=v.ok?0:1,console.error(w(`(${v.inputTokens}\u2192${v.outputTokens} tokens`+(v.costUsd>0?`, $${v.costUsd<.01?v.costUsd.toFixed(4):v.costUsd.toFixed(2)}`:"")+")")),v.ok||console.error(j("agent finished with an error result"));break;case"error":console.error(""),console.error(j(`agent error: ${v.message}`)),process.exit(1)}g&&ow(g),process.stdout.write(`
|
|
297
|
-
`),process.exit(
|
|
298
|
-
`)}var Xe=[{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:"/publish --all",s:"Push the reviewed articles live to your readers."},{t:"dim",s:" (/catch-up --publish runs the first and last steps back-to-back, once the review is done)"},{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:"/publish",s:"Publish the articles to Document360. Requires an editorial review first \u2014 /review --fix."}]},{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, captures, annotates."},{t:"step",n:4,s:"Each new shot is then checked automatically: D360-Writer looks at the picture and marks it \u2714 verified, or flags what is wrong and fixes the spec for you."},{t:"step",n:5,s:"Run /publish --screenshots \u2014 it re-saves the articles with captured shots so the images embed on Document360. Put a category in front (/publish 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 verify",s:"Look at the captured 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 \u25CF to verify \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, not \u25CF captured. A captured shot only means a file exists; it counts as done once the picture has been looked at and judged fit for the article."},{t:"gap"},{t:"sub",s:"When a shot does not produce a usable image"},{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 (--publish then runs the gated publish)."},{t:"cmd",name:"/share",s:"Exchange work with your team: get your builder's latest, send yours (automatic; `off` to stop)."},{t:"cmd",name:"/publish",s:"Publish to Document360 (--all or a path). Needs /review --fix 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 va(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 Cs(e,t,n,o){let r=" ".repeat(2+n+1),s=Math.max(24,o-r.length-2),i=Jt(t,s);return e.length>n?{nameCell:e,descLines:i,indent:r,nameOwnLine:!0}:{nameCell:e.padEnd(n),descLines:i,indent:r,nameOwnLine:!1}}function iw(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=Cs(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
|
+
`;Da="Re-run dev\u2194docs onboarding (protocol v"});var sp={};gd(sp,{initCommand:()=>La,scaffoldInit:()=>Ia});import{input as lr,confirm as Nw}from"@inquirer/prompts";import{basename as Xd,join as Ns}from"node:path";import{existsSync as po,readFileSync as jw,readdirSync as Iw,writeFileSync as Lw}from"node:fs";import{writeProjectConfig as Qd,readProjectConfig as Ow,projectConfigPath as Jd,writerDir as _w,DEFAULT_DOCS_DIR as Zd,DEFAULT_CAPTURE_DIR as ep,DEFAULT_OUTPUT_DIR as tp}from"document360-engine";function Ia(e,t="berlin"){let n=Jd(e);if(po(n))return{created:!1,path:n,profileName:""};let o={projectId:op(e)??Xd(e),docsDir:Zd,captureDir:ep,outputDir:tp,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:rp(e)};return Qd(o,e),np(e),{created:!0,path:n,profileName:t}}function np(e){let t=Ns(_w(e),".gitignore");po(t)||Lw(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
|
|
296
|
+
`),"utf8")}async function La(){let e=process.cwd(),t=Jd(e);if(po(t)&&!await Nw({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(y("init cancelled.")),{kind:"continue"};let n=op(e)??Xd(e),o=await lr({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await lr({message:"Capture directory (where document360-capture .spec.ts files live):",default:ep}),s=await lr({message:"Screenshot output directory:",default:tp}),i=await lr({message:"Default connection profile name:",default:"berlin"}),a=await lr({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),l={projectId:o,docsDir:Zd,captureDir:r,outputDir:s,profiles:{[i]:{connection:{environment:a},production:!1}},defaultProfile:i,authoritativeSourceFiles:rp(e)},p=Ow(e);p?.terminologyGlossary&&(l.terminologyGlossary=p.terminologyGlossary),Qd(l,e),np(e);let g=co(e);console.log(""),console.log(G(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${K(`d360-writer login --profile ${i}`)} ${y("(sign in; project & workspace auto-selected)")}`),console.log("");for(let k of uo(g))console.log(k);return console.log(""),console.log(`${y("Then ask:")} ${K('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function op(e){let t=Ns(e,"package.json");if(!po(t))return null;try{return JSON.parse(jw(t,"utf8")).name??null}catch{return null}}function rp(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])po(Ns(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Ns(e,n);po(o)&&!Mw(o)&&t.push(n)}return t}function Mw(e){try{return Iw(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var js=or(()=>{"use strict";ee();nn()});import{createRequire as ak}from"node:module";import{existsSync as lk,readFileSync as ck}from"node:fs";import{dirname as Dp,join as Np}from"node:path";function Mt(){let e;try{e=uk.resolve("document360-capture/helpers")}catch{return null}let t=Dp(e);for(let n=0;n<5&&!lk(Np(t,"package.json"));n++)t=Dp(t);try{let n=JSON.parse(ck(Np(t,"package.json"),"utf8"));return n.name==="document360-capture"&&n.version?n.version:null}catch{return null}}var uk,pr=or(()=>{"use strict";uk=ak(import.meta.url)});var bf={};gd(bf,{doctorCommand:()=>Tr,renderDoctorChecks:()=>kf,runDoctorChecks:()=>wf});import{existsSync as K$}from"node:fs";import{d360GetAll as z$,getAccessToken as X$,isExpired as fc,loadProfileMap as Q$,loadTokens as J$,packageSkillsDir as gf,ENGINE_VERSION as Z$,projectConfigPath as ev,readProjectConfig as tv,DEFAULT_DOCS_DIR as nv,fetchManifestSummary as ov,resolveActiveProfile as rv,classifyClaudeAuth as sv,CLAUDE_CODE_SETUP_HINT as yf,resolveModelSetting as iv,probeModel as av,detectAppType as lv,playbookSkillName as cv,D360AuthError as uv,applyStructureOrder as dv}from"document360-engine";async function wf(e,t){let n=[],o=Mt();n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${Z$}${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=sv();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. ${yf}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:yf});let i=iv(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 av(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=tv(e);if(!a)return n.push({level:"fail",label:`No ${ev(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${a.projectId}`});let l=(a.docsDir??nv).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 g=a.appType??lv(e);if(g){let C=a.appType?"from config":"auto-detected",T=g==="web"||g==="cli";n.push({level:"ok",label:`Genre: ${g} (${C})${T?` \u2192 ${cv(g)} loaded`:" \u2014 no doc-type playbook for this genre yet (generic skills)"}`})}else n.push({level:"warn",label:"Genre: unclassified \u2014 no doc-type playbook is loading (generic output)",fix:"Run /genre <web|cli|service|library> to pick \u2014 raises docs to that genre's craft bar"});let k;try{k=rv(e),n.push({level:"ok",label:`Profile: ${k.name} (${k.connection.name})${k.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 v=J$(k.name);v?fc(v)&&!v.refreshToken?n.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):fc(v)?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(v.expiresAt).toLocaleString()})`}):n.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${k.name})`}),n.push(k.project.workspaceId?{level:"ok",label:`Workspace: ${k.project.workspaceName??k.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let P=Q$(e,k.name);P?P.projectId&&k.project.projectId&&P.projectId!==k.project.projectId?n.push({level:"fail",label:`Category map projectId (${P.projectId}) \u2260 profile projectId (${k.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(P.articles).length} articles, ${Object.keys(P.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${k.name}" (created on first /push)`}),n.push(K$(gf())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${gf()}`,fix:"Reinstall document360-writer (broken install)"});let S=mt(e);if(S.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${Re})`}):S.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${S.completedVersion}, current is v${Re}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),v&&(!fc(v)||v.refreshToken)){let C={profile:k.name,connection:k.connection};try{await X$(C);let D=await z$(C,"/v3/projects");n.push({level:"ok",label:`API reachable (${k.connection.apiUrl}) \u2014 ${D.length} project(s) visible`})}catch(D){n.push({level:"fail",label:`API call failed: ${D.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let T=P?.projectId??k.project.projectId;if(T&&k.project.workspaceId){try{let D=await ov(C,T,k.project.workspaceId);if(D){let I=(D.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Your Document360 project: reachable on ${k.connection.name} (${D.languages?.length??0} language${(D.languages?.length??0)===1?"":"s"}) \xB7 version ${I||"(none)"}`})}else n.push({level:"ok",label:`Workspace sync manifest: not live on ${k.connection.name} yet \u2014 sync uses the per-article path (nothing to do)`})}catch(D){D instanceof uv||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(D.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${k.project.projectName??T})`,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 (${D.message.slice(0,80)})`})}try{let D=await dv({cwd:e,profileName:k.name,dryRun:!0}),I=D.categoriesReordered+D.articlesReordered;if(D.skipped==="no category map")n.push({level:"ok",label:"Reading order: nothing to check yet (no articles published)"});else if(D.skipped)n.push({level:"warn",label:`Reading order: can't be checked (${D.skipped})`,fix:"Your article order on Document360 may not match your structure \u2014 /push syncs it once this resolves"});else if(D.unverified)n.push({level:"warn",label:`Reading order: ${D.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 O=[D.categoriesReordered>0?`${D.categoriesReordered} categor${D.categoriesReordered===1?"y":"ies"}`:"",D.articlesReordered>0?`${D.articlesReordered} article${D.articlesReordered===1?"":"s"}`:""].filter(Boolean);n.push({level:"warn",label:`Reading order: ${O.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(D){n.push({level:"warn",label:`Reading order: check failed (${D.message.slice(0,80)})`})}}}return n}function kf(e){let t=[""];for(let r of e){let s=r.level==="ok"?G("\u2713"):r.level==="warn"?H("\u26A0"):N("\u2717");t.push(` ${s} ${r.label}${r.detail?y(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${y("fix:")} ${K(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?G(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):N(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function Tr(e,t){console.log(y("Running checks\u2026"));for(let n of kf(await wf(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var mi=or(()=>{"use strict";nn();ee();pr()});import{Command as tP}from"commander";import{createRequire as nP}from"node:module";import{AUTH_MODES as oP}from"document360-engine";import{input as Xy}from"@inquirer/prompts";import{loginPkce as Qy,refreshTokens as Jy,toStoredTokens as Cd,clearTokens as Zy,decodeJwtClaims as xd,isExpired as ew,loadTokens as tw,saveTokens as Rd,resolveActiveProfile as ks,setProfileProject as nw,readProjectConfig as ow}from"document360-engine";ee();import{select as Iy}from"@inquirer/prompts";import{resolveActiveProfile as Ly,setProfileProject as Oy,resolveProjectId as _y,listWorkspaces as My}from"document360-engine";async function sr(e,t){let n=Ly(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??_y(o);return{workspaces:await My(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var wd=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function xa(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 gs(e,t,n,o,r){Oy(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function kd(e,t,n){let o;try{o=await sr(e,n)}catch(s){return console.log(N(`Could not list workspaces: ${s.message}`)),1}let r=xa(o.workspaces,t);return r?(gs(e,o.profile,o.projectId,r.id,r.name),console.log(G(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(N(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function io(e,t){let n;try{n=await sr(e,t)}catch(p){console.log(N(`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?K("\u25CF"):" "} ${wd(p)} ${y(p.id)}`);console.log(y("Run: d360-writer workspace use <name>"));return}let a=await Iy({message:"Select the Document360 workspace for this repo:",choices:o.map(p=>({name:`${wd(p)}${p.id===i?" (current)":""}`,value:p.id}))}),l=o.find(p=>p.id===a);gs(e,s,r,a,l?.name),console.log(G(`\u2713 Workspace set to "${l?.name??a}" for profile "${s}".`))}ee();import{select as Fy}from"@inquirer/prompts";import{resolveActiveProfile as Wy,setProfileProject as Uy,listProjects as By}from"document360-engine";async function Jt(e,t){let n=Wy(e,t),o={profile:n.name,connection:n.connection};return{projects:await By(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var bd=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Ca(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 ys(e,t,n,o){Uy(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function $d(e,t,n){let o;try{o=await Jt(e,n)}catch(s){return console.log(N(`Could not list projects: ${s.message}`)),1}let r=Ca(o.projects,t);return r?(ys(e,o.profile,r.id,r.name),console.log(G(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log(N(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function ws(e,t){let n;try{n=await Jt(e,t)}catch(l){console.log(N(`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?K("\u25CF"):" "} ${bd(l)} ${y(l.id)}`);console.log(y("Run: d360-writer project use <name>"));return}let i=await Fy({message:"Select the Document360 project for this repo:",choices:o.map(l=>({name:`${bd(l)}${l.id===s?" (current)":""}`,value:l.id}))}),a=o.find(l=>l.id===i);ys(e,r,i,a?.name),console.log(G(`\u2713 Project set to "${a?.name??i}" for profile "${r}". Next: pick a workspace.`))}ee();import Hy from"picocolors";function qy(e=process.env){return e.FORCE_HYPERLINK==="0"||!Hy.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 Gy(e,t=e,n){return qy(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Vy=/https?:\/\/[^\s\x1b]+/g;function ir(e,t){return e.replace(Vy,n=>Gy(n,n,t))}import{readProjectConfig as vd,sunsetEnvironment as Yy,resolveActiveProfile as Ky}from"document360-engine";function zy(e,t){let n=vd(e);return Object.entries(n?.profiles??{}).find(([,o])=>(o.connection?.environment??"berlin")===t)?.[0]??null}function Zt(e,t){try{if(!vd(e))return null;let n=Ky(e,t),o=Yy(n.connection.name);if(!o)return null;let r=zy(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 Sd(e){return{...xd(e.idToken)??{},...xd(e.accessToken)??{}}}function bs(e){let t=Sd(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 $s(e){let t=ks(process.cwd(),e.profile),n=t.connection;console.log(y(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=Zt(process.cwd(),e.profile);o&&(console.log(H(`\u26A0 ${o.why} \u2014 and signing in does NOT change it (the environment comes from the profile, not the login).`)),console.log(H(` To move: ${o.cmd}${o.replacementProfile?"":", then /login"}`)));let r=await Qy(n,{manual:e.manual,promptForRedirect:i=>Xy({message:i})},i=>console.log(ir(i))),s=Cd(t.name,r);if(Rd(s),await Ra(s,t.name,i=>console.log(y(i))),console.log(""),console.log(G(`\u2713 Logged in to "${t.name}" as ${bs(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{ow(process.cwd())?.profiles?.[t.name]&&(console.log(""),await io(process.cwd(),t.name))}catch{}}async function Ra(e,t,n){let r=Sd(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(ks(process.cwd(),t).project.projectId)return;let i;try{let{projects:a}=await Jt(process.cwd(),t);i=a.find(l=>l.id===r)?.name}catch{}nw(process.cwd(),t,{projectId:r,projectName:i}),n(` Project "${i??r}" written to profile "${t}".`)}catch{}}async function Pd(e){let t=ks(process.cwd(),e.profile),n=t.connection,o=tw(t.name);if(!o){console.log(N(`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 ${K(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${bs(o)}`),ew(o))if(o.refreshToken)try{let r=Cd(t.name,await Jy(n,o.refreshToken));Rd(r),console.log(G(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(H(`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(H("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 Td(e){let t=ks(process.cwd(),e.profile);Zy(t.name)?console.log(G(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(y(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}ee();import{readProjectConfig as Ed,writeProjectConfig as rw,resolveActiveProfile as sw,loadTokens as iw,isExpired as aw}from"document360-engine";function vs(e){let t=Ed(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(N("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?K("\u25CF "):" ",s=o.production?H(" \u26A0 PRODUCTION"):"",i=o.connection.environment??"(inline)",a=iw(n),l=a?aw(a)&&!a.refreshToken?H("expired"):y("logged in"):y("not logged in");console.log(`${r}${K(n)} \u2192 ${i}${s} [${l}]`)}console.log(""),console.log(y("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function xs(e,t){let n=Ed(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(N(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,rw(n,e);let o=n.profiles[t].production?H(" \u26A0 PRODUCTION"):"";console.log(G(`\u2713 Default profile is now "${t}"${o}`))}function Cs(e,t){try{let n=sw(e,t);console.log(""),console.log(`Profile ${K(n.name)}${n.production?H(" \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(N(n.message)),process.exitCode=1}}ee();import{existsSync as lw,readdirSync as cw,statSync as Ad}from"node:fs";import{join as Dd}from"node:path";import{apiLogDir as uw}from"document360-engine";function Nd(){let e=uw();if(console.log(""),console.log(`Document360 API logs: ${K(e)}`),!lw(e)){console.log(y(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=cw(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=(Ad(Dd(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=(Ad(Dd(e,r)).size/1024).toFixed(1);console.log(` ${N(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("")}ee();import{createSession as dw,resolveAuth as pw,findByName as hw,slugify as fw,touchSession as mw,upsertSession as gw,resolveActiveProfile as yw}from"document360-engine";async function jd(e,t,n,o,r,s){let i=pw(n);i.kind==="none"&&(console.error(""),console.error(N("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${K("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${K("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=yw(e,r)}catch(v){console.error(N(`Document360 profile error: ${v.message}`)),process.exit(2)}a.production&&(console.error(H(`\u26A0 Profile "${a.name}" is PRODUCTION.`)),s||(console.error(N("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 v=hw(e,o);v||(console.error(N(`No saved session matches "${o}" in this repo.`)),console.error(y("List sessions inside the REPL with /resume.")),process.exit(2)),l=v.uuid,console.error(y(`Resuming "${v.name}"`))}let p=dw({cwd:e,resume:l,profileName:r,allowProdWrites:s===!0}),g=l??null,k=1;for await(let v of p.send(t))switch(v.type){case"session":if(!g){g=v.sessionId;let P=new Date().toISOString();gw({uuid:g,name:fw(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:P,updatedAt:P})}break;case"text":process.stdout.write(v.delta);break;case"tool":console.error($e(` \u2699 ${v.name}`));break;case"result":k=v.ok?0:1,console.error(y(`(${v.inputTokens}\u2192${v.outputTokens} tokens`+(v.costUsd>0?`, $${v.costUsd<.01?v.costUsd.toFixed(4):v.costUsd.toFixed(2)}`:"")+")")),v.ok||console.error(N("agent finished with an error result"));break;case"error":console.error(""),console.error(N(`agent error: ${v.message}`)),process.exit(1)}g&&mw(g),process.stdout.write(`
|
|
297
|
+
`),process.exit(k)}import{createInterface as BC}from"node:readline/promises";import{createSession as uu,resolveAuth as HC,getSession as qC,setTitle as GC,slugify as VC,touchSession as Zm,upsertSession as YC,generateTitle as KC,resolveActiveProfile as eg,resolveModelSetting as zC,readProjectConfig as XC,readUserConfig as QC,resolveAndPersistAppType as JC,decodeJwtClaims as Qm,isExpired as ZC,loadTokens as eR,isDirectiveMention as tR,stripDirectiveMention as nR,appendDirective as oR,reconcileUpgradeActions as rR,stampArticles as sR,snapshotArticles as iR,listArticleFiles as aR,applyStructureOrder as lR,orderSyncLine as cR,computeSyncStatus as uR}from"document360-engine";import{ENGINE_VERSION as bw}from"document360-engine";function en(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 Rs(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 en(`${i+1}. ${s.feature}`,76))o.push(n(a));o.push(n());for(let a of en(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 Ss(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 Je=[{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, captures, annotates."},{t:"step",n:4,s:"Each new shot is then checked automatically: D360-Writer looks at the picture and marks it \u2714 verified, or flags what is wrong and fixes the spec for you."},{t:"step",n:5,s:"Run /push --screenshots \u2014 it re-saves the articles with captured 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 verify",s:"Look at the captured 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 \u25CF to verify \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, not \u25CF captured. A captured shot only means a file exists; it counts as done once the picture has been looked at and judged fit for the article."},{t:"gap"},{t:"sub",s:"When a shot does not produce a usable image"},{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."}]}],Id=24;function Sa(e){let t=e.filter(n=>n.t==="cmd").map(n=>n.name.length);return t.length===0?Id:Math.min(Id,Math.max(...t))}function Ps(e,t,n,o){let r=" ".repeat(2+n+1),s=Math.max(24,o-r.length-2),i=en(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 ww(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=Ps(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 Ld(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 Je){n.push(`\u2500\u2500 ${o.label} \u2500\u2500`,"");let r=Sa(o.rows);for(let s of o.rows)n.push(ww(s,r,100));n.push("")}return n.push("Tip: anything not starting with / goes to the agent."),n}function Pa(e,t){return en(e,Math.max(10,Math.max(20,t)-2))}function kw(e,t,n){let o=Math.max(20,n),r=s=>Math.max(1,Pa(s,o).length);switch(e.t){case"gap":return 1;case"cmd":{let s=Ps(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 Od(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=kw(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 _d(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 Ta(e=[],t){console.log("");let n=t?.version?{version:t.version,engineVersion:bw}:void 0;for(let o of Ld(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"}}ee();import{getSession as $w}from"document360-engine";async function Md(e,t){let n=t.currentUuid(),o=n?$w(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 Ea(){return{kind:"exit"}}js();ee();import{readMcpConfig as Oa,writeMcpConfig as ip}from"document360-engine";async function Is(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(Fw(),{kind:"continue"}):t==="add"?(Ww(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(Uw(e.slice(1)),{kind:"continue"}):(console.log(N(`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 Fw(){let e=Oa(),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(` ${K(n)} ${w("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?w(` [headers: ${r.join(", ")}]`):"";console.log(` ${K(n)} ${w(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function Tw(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=Na(),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,Kd(r),console.log(""),console.log(V(`\u2713 Registered "${t}" (${n})`)),console.log(H(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(w(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function Ew(e){let t=e[0];if(!t){console.log(j("Usage: /mcp remove <name>"));return}let n=Na();if(!n.servers[t]){console.log(j(`No server named "${t}".`));return}delete n.servers[t],Kd(n),console.log(V(`\u2713 Removed "${t}".`)),console.log(w(" Run /clear to drop it from the current session immediately."))}ee();import{readFileSync as Wb}from"node:fs";import{join as Ub}from"node:path";import{select as Bb}from"@inquirer/prompts";import{computeSyncStatus as Xs,planPartitions as Hb,relatedArticlePaths as qb,resolveModelForOperation as Gb,runPartitioned as Vb,loadProfileMap as Jp,draftPendingPaths as Yb,resolveActiveProfile as ll,unreviewedPaths as Kb,styleErrorPaths as Zp,publishGateVerdict as zb,publishGateLines as Xb,SKIP_STYLE_FLAG as Qb,listArticleFiles as eh,ensureFeedbackChannel as Jb,FEEDBACK_CATEGORY_NAME as Zb,resolveCrossLinks as ek,applyStructureOrder as th,orderSyncLine as nh,applyRelatedArticles as oh,relatedSyncLine as rh}from"document360-engine";import{readFileSync as Aw}from"node:fs";import{resolve as Dw}from"node:path";import{prettyFolderName as zd}from"document360-engine";var ao=zd;function Xd(e){return e.replace(/\\/g,"/").split("/").slice(0,-1).join("/")}function ja(e){let t=e.replace(/\\/g,"/").split("/").pop()??e;return zd(t.replace(/\.md$/i,""))}function Qd(e,t){try{return/^#\s+(.+)$/m.exec(Aw(Dw(e,t),"utf8"))?.[1]?.trim()??null}catch{return null}}import pe from"picocolors";import Ma from"wrap-ansi";import Fa from"string-width";ee();import tn from"picocolors";import js from"wrap-ansi";import Ns from"string-width";var lo=[{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>] [--publish]",desc:"Document a shipped change \u2014 the agent picks the action (new section/article/update); bare: act on builder requests. --publish then runs the normal publish, 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|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); verify: judge the captured pictures and mark them verified (runs 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:"publish",usage:"/publish [path|--all|[<category>] --screenshots] [--skip-review]",desc:"Publish to Document360 (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:"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 /publish",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 [--publish]",desc:"Process ALL pending work (builder hints + requests + Document360 portal drift) \u2192 write \u2192 push to Document360 as drafts. --publish then runs the normal publish, 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 (publish), 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"}],Jd={"/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","/publish":"publish your drafts to Document360","/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)","/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 Zd(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(Jd[n])return Jd[n];let o=lo.find(r=>r.name===t);return o?o.desc:""}function ep(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return lo.filter(n=>n.name.startsWith(t))}function tp(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 Nw=new RegExp(`^\\s*/(?:${lo.map(e=>e.name).join("|")})(?:\\s|$)`),np=e=>Nw.test(e),op=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),rp=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),sp=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function jw(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(D=>
|
|
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(` ${K(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(` ${K(n)} ${y(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function Ww(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(N("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(N(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=Oa(),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(N(`-H expects key:value (no spaces). Got: ${l??"(nothing)"}`));return}i[p[1].trim()]=p[2].trim()}else{console.log(N(`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,ip(r),console.log(""),console.log(G(`\u2713 Registered "${t}" (${n})`)),console.log(H(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(y(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function Uw(e){let t=e[0];if(!t){console.log(N("Usage: /mcp remove <name>"));return}let n=Oa();if(!n.servers[t]){console.log(N(`No server named "${t}".`));return}delete n.servers[t],ip(n),console.log(G(`\u2713 Removed "${t}".`)),console.log(y(" Run /clear to drop it from the current session immediately."))}ee();import{readFileSync as Jk}from"node:fs";import{join as Zk}from"node:path";import{select as eb}from"@inquirer/prompts";import{computeSyncStatus as Zs,planPartitions as tb,relatedArticlePaths as nb,resolveModelForOperation as ob,runPartitioned as rb,loadProfileMap as uh,draftPendingPaths as sb,resolveActiveProfile as pl,unreviewedPaths as ib,styleErrorPaths as dh,publishGateVerdict as ab,publishGateLines as lb,SKIP_STYLE_FLAG as cb,listArticleFiles as ph,ensureFeedbackChannel as ub,FEEDBACK_CATEGORY_NAME as db,resolveCrossLinks as pb,applyStructureOrder as hh,orderSyncLine as fh,applyRelatedArticles as mh,relatedSyncLine as gh}from"document360-engine";import{readFileSync as Bw}from"node:fs";import{resolve as Hw}from"node:path";import{prettyFolderName as ap}from"document360-engine";var ho=ap;function lp(e){return e.replace(/\\/g,"/").split("/").slice(0,-1).join("/")}function _a(e){let t=e.replace(/\\/g,"/").split("/").pop()??e;return ap(t.replace(/\.md$/i,""))}function cp(e,t){try{return/^#\s+(.+)$/m.exec(Bw(Hw(e,t),"utf8"))?.[1]?.trim()??null}catch{return null}}import pe from"picocolors";import Ba from"wrap-ansi";import Ha from"string-width";ee();import on from"picocolors";import Os from"wrap-ansi";import Ls from"string-width";var fo=[{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|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); verify: judge the captured pictures and mark them verified (runs 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"}],up={"/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)","/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 dp(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(up[n])return up[n];let o=fo.find(r=>r.name===t);return o?o.desc:""}function pp(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return fo.filter(n=>n.name.startsWith(t))}function hp(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 qw=new RegExp(`^\\s*/(?:${fo.map(e=>e.name).join("|")})(?:\\s|$)`),fp=e=>qw.test(e),mp=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),gp=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),yp=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function Gw(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(mp(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&gp(t[o+1])){let a=yp(r);o+=2;let l=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)l.push(yp(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(fp(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])&&!fp(t[o])&&!mp(t[o])&&!(t[o].includes("|")&&o+1<t.length&&gp(t[o+1]));)i.push(t[o++]);n.push({kind:"para",text:i.join(" ")})}return n}function Ma(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?on.bold(t.slice(2,-2)):t.startsWith("`")?K(t.slice(1,-1)):on.italic(t.slice(1,-1)))}var Vw=(e,t)=>e+" ".repeat(Math.max(0,t-Ls(e)));function Fa(e,t,n,o={}){return wp(e,t,n,o)}function wp(e,t,n,o={}){let r=e.length,s=T=>Math.max(0,...T.split(`
|
|
307
|
+
`).map(D=>Ls(D))),i=e.map((T,D)=>Math.max(Ls(T),...t.map(I=>s(I[D]??"")))),a=Math.max(24,n),l=3*r+1,p=[...i],g=()=>p.reduce((T,D)=>T+D,0)+l,k=0;for(;g()>a&&k++<1e4;){let T=-1,D=6;for(let I=0;I<r;I++)p[I]>D&&(D=p[I],T=I);if(T===-1)break;p[T]-=1}let v=(T,D,I)=>on.gray(T+p.map(O=>"\u2500".repeat(O+2)).join(D)+I),P=on.gray("\u2502"),S=(T,D)=>{let I=p.map((ae,le)=>{let he=T[le]??"",ce=D?on.bold(he):o.plain?he:Ma(he);return he.includes(`
|
|
308
308
|
`)?ce.split(`
|
|
309
|
-
`).flatMap(X=>
|
|
310
|
-
`)):
|
|
311
|
-
`)}),O=Math.max(...I.map(ae=>ae.length)),Y=[],fe=(ae,le,he)=>o.align?.[he]==="right"?" ".repeat(Math.max(0,le-
|
|
312
|
-
`)},
|
|
313
|
-
`)}function
|
|
309
|
+
`).flatMap(X=>Os(X,ae,{hard:!0}).split(`
|
|
310
|
+
`)):Os(ce,ae,{hard:!0}).split(`
|
|
311
|
+
`)}),O=Math.max(...I.map(ae=>ae.length)),Y=[],fe=(ae,le,he)=>o.align?.[he]==="right"?" ".repeat(Math.max(0,le-Ls(ae)))+ae:Vw(ae,le);for(let ae=0;ae<O;ae++)Y.push(p.map((le,he)=>`${P} ${fe(I[he][ae]??"",le,he)} `).join("")+P);return Y.join(`
|
|
312
|
+
`)},C=[v("\u250C","\u252C","\u2510"),S(e,!0)];return C.push(t.length===0?v("\u2514","\u2534","\u2518"):v("\u251C","\u253C","\u2524")),t.forEach((T,D)=>{C.push(S(T,!1)),C.push(D===t.length-1?v("\u2514","\u2534","\u2518"):v("\u251C","\u253C","\u2524"))}),C.join(`
|
|
313
|
+
`)}function Yw(e,t){switch(e.kind){case"heading":return on.bold(e.text);case"hr":return on.gray("\u2500".repeat(t));case"para":return Os(Ma(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]=Os(Ma(o.text),Math.max(10,t-s.length)).split(`
|
|
314
314
|
`);return` ${r} ${i}`+a.map(l=>`
|
|
315
315
|
${s}${l}`).join("")}).join(`
|
|
316
|
-
`)}case"code":return e.lines.map(n=>
|
|
317
|
-
`);case"table":return
|
|
318
|
-
|
|
319
|
-
`)}ee();import
|
|
320
|
-
`);let r=2,s=3,i=
|
|
321
|
-
`);let l=Math.max(0,Math.floor((n.length-o.length)/2)),p=[];for(let g=0;g<Math.max(o.length+l,n.length);g++){let
|
|
322
|
-
`)}var
|
|
323
|
-
`).flatMap(p=>
|
|
316
|
+
`)}case"code":return e.lines.map(n=>on.gray(" "+n)).join(`
|
|
317
|
+
`);case"table":return wp(e.header,e.rows,t)}}function Wa(e,t){let n=Math.max(20,t);return Gw(e).map(o=>Yw(o,n)).join(`
|
|
318
|
+
|
|
319
|
+
`)}ee();import Kw from"picocolors";var zw=[127,86,217],Xw=[22,38,43],kp={T:zw,E:Xw},cr=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],Ua=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,Qw=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function bp(){if(!Kw.isColorSupported)return[];let e=cr[0].length,t=[];for(let n=0;n<cr.length;n+=2){let o="";for(let r=0;r<e;r++){let s=kp[cr[n][r]],i=n+1<cr.length?kp[cr[n+1][r]]:void 0;s&&i?o+=`${Ua(s)}${Qw(i)}\u2580\x1B[49m\x1B[39m`:s?o+=`${Ua(s)}\u2580\x1B[39m`:i?o+=`${Ua(i)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function ur(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 dr(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function vp(e,t,n){let o=e>0&&e<=n?e:t;return Math.max(0,Math.floor((n-o)/1e3))}function Ze(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function rn(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var mo=(e,t)=>` ${e.padEnd(13)}${t}`;function Jw(e,t){let n=[rr("\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."),"",mo("Claude:",`${e.claude}${pe.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),mo("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")),mo("Profile:",e.configured?`${e.profile}${pe.gray(` (${e.apiUrl})`)}${e.prod?pe.bold(pe.yellow(" \u26A0 PRODUCTION")):""}`:pe.gray("\u2014 (run /init)")),mo("Project:",e.project),mo("Mode:",pe.gray(e.mode)),mo("cwd:",pe.gray(e.cwd))],o=bp();if(o.length===0)return n.join(`
|
|
320
|
+
`);let r=2,s=3,i=Ha(o[0]);if(!(t>=r+i+s+Math.max(...n.map(g=>Ha(g)))))return[...o.map(g=>" "+g),...n].join(`
|
|
321
|
+
`);let l=Math.max(0,Math.floor((n.length-o.length)/2)),p=[];for(let g=0;g<Math.max(o.length+l,n.length);g++){let k=o[g-l]??" ".repeat(i);p.push((" ".repeat(r)+k+" ".repeat(s)+(n[g]??"")).trimEnd())}return p.join(`
|
|
322
|
+
`)}var Zw={error:pe.red,warn:pe.yellow,ok:pe.green,info:pe.gray},$p=9;function qa(e){return e.length>=$p?`${e} `:e.padEnd($p)}function Ga(e){return e.replace(/^(\s*• |)([^\x00-\x7F][\u{1F000}-\u{1FAFF}️]*) (?=\S)/gmu,"$1$2 ")}function Va(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return Jw(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=>Ba(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,g)=>o+(g===0?K(" \u276F "):" ")+p+" ".repeat(Math.max(0,s-
|
|
325
|
+
`+a.map((p,g)=>o+(g===0?K(" \u276F "):" ")+p+" ".repeat(Math.max(0,s-Ha(p))+1)+r).join(`
|
|
326
326
|
`)}case"assistant":return`
|
|
327
|
-
`+
|
|
328
|
-
`+
|
|
329
|
-
`+
|
|
327
|
+
`+Wa(e.text,n);case"tool":{let o=e.arg!==null?pe.gray(`${e.sep}(${e.arg})`):"";return`
|
|
328
|
+
`+Ba(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
|
+
`+Ba(pe.green("\u25CF ")+K(pe.bold(qa(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
|
-
`)}case"link":return e.lines.map(o=>K(
|
|
331
|
+
`)}case"link":return e.lines.map(o=>K(ir(` \u2B95 ${o}`))).join(`
|
|
332
332
|
`);case"preview":return`
|
|
333
|
-
`+
|
|
334
|
-
|
|
335
|
-
`+
|
|
336
|
-
`+
|
|
337
|
-
`+e.text;case"done":{let o=e.inTokens&&e.inTokens>0?` \xB7 ${
|
|
338
|
-
`+(e.ok?pe.magenta("\u2736 "):pe.red("\u2736 "))+pe.gray(`Cooked for ${
|
|
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(
|
|
333
|
+
`+rr(`\u25A3 Preview \u2014 ${e.name}`)+`
|
|
334
|
+
|
|
335
|
+
`+Wa(e.text,n);case"note":return`
|
|
336
|
+
`+Zw[e.tone](ir(Ga(e.text)));case"block":return`
|
|
337
|
+
`+e.text;case"done":{let o=e.inTokens&&e.inTokens>0?` \xB7 ${ur(e.inTokens)} in${e.cachedPct!=null?` (${e.cachedPct}% cached)`:""}`:"";return`
|
|
338
|
+
`+(e.ok?pe.magenta("\u2736 "):pe.red("\u2736 "))+pe.gray(`Cooked for ${dr(e.seconds)} \xB7 ${ur(e.tokens)} tokens out${o}`+(e.costUsd>0?` \xB7 ${Ze(e.costUsd)}`:""))}}}function xp(e,t){return e.map(n=>Va(n,t)).join(`
|
|
339
|
+
`)}import{resolveActiveProfile as ek,loadTokens as tk,isExpired as nk,decodeJwtClaims as Cp}from"document360-engine";function ok(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function Ue(e,t){try{let n=ek(e,t),o=tk(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(nk(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={...Cp(o.idToken)??{},...Cp(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 ${ok(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}function $t(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 _s(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 Qa,readFileSync as il}from"node:fs";import{isAbsolute as qs,join as Gs,resolve as Vs}from"node:path";import j from"picocolors";import Us from"string-width";import{readProjectConfig as an,screenshotPlaceholderIds as qp,DEFAULT_CAPTURE_DIR as Ys,DEFAULT_OUTPUT_DIR as al,DEFAULT_DOCS_DIR as ll,existingAnnotatedShotPath as Rk,resolveOutputDir as Gp,migrateShotLayout as Sk,reviewIsCurrent as Pk,shotImageMtimeMs as Tk,anchorPresent as Ek,RAW_SUBDIR as Ak,ANNOTATED_SUBDIR as Dk}from"document360-engine";import{createHash as Sp}from"node:crypto";import{readFileSync as Pp,writeFileSync as rk}from"node:fs";import{join as sk}from"node:path";import{captureStatePath as Tp}from"document360-engine";var Rp={version:1,shots:{}};function Ep(e){return Sp("sha1").update(e).digest("hex").slice(0,12)}function Ms(e){try{let t=JSON.parse(Pp(sk(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 Sp("sha1").update(`${o}|${r?.connection?.startUrl??""}|${i}`).digest("hex").slice(0,12)}catch{return null}}function _t(e){try{let t=JSON.parse(Pp(Tp(e),"utf8").replace(/^/,""));return!t||typeof t!="object"||t.version!==1||!t.shots?{...Rp,shots:{}}:{version:1,shots:t.shots}}catch{return{...Rp,shots:{}}}}function ik(e,t){rk(Tp(e),`${JSON.stringify(t,null,2)}
|
|
340
|
+
`,"utf8")}function Ya(e){return e&&/data-testid|\btest-?id\b|has(?:n't| not) landed/i.test(e)?"testid":"data"}function Fs(e,t,n){if(t.length===0)return;let o=_t(e),r=Ms(e);for(let s of t){let i=s.specSource?Ep(s.specSource):void 0;o.shots[s.id]={outcome:s.outcome,at:n,...s.reason?{reason:s.reason}:{},...s.outcome==="skipped"?{blockedBy:Ya(s.reason)}:{},...i?{specHash:i}:{},...r?{envHash:r}:{}}}ik(e,o)}function Ka(e,t,n,o){let r=e.shots[t];return!r||n===null||!r.specHash||r.specHash!==Ep(n)||o&&r.envHash&&r.envHash!==o?null:r}function Ap(e){let t=_t(e).shots;return Object.keys(t).filter(n=>t[n].outcome==="failed").sort()}function za(e,t,n){let o=Ka(_t(e),t,n,Ms(e));return!o||o.outcome==="captured"||!o.reason?null:{outcome:o.outcome,reason:o.reason}}pr();import{existsSync as dk,readFileSync as Ip,readdirSync as Lp,writeFileSync as pk}from"node:fs";import{isAbsolute as hk,join as Op,resolve as fk}from"node:path";import{readProjectConfig as mk,DEFAULT_CAPTURE_DIR as gk}from"document360-engine";var jp="0.2.25";function Ws(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 yk=/^([ \t]*)await\s+([^\n;]+?)\.screenshot\(\{\s*path:\s*PLACEHOLDER\.saveTo\s*(?:,\s*fullPage:\s*(?:true|false)\s*)?,?\s*\}\)\s*;?[ \t]*$/m,wk=/^[ \t]*await\s+dumpAnnotations\(\s*page\s*,\s*PLACEHOLDER\s*\)\s*;?[ \t]*\r?\n?/m,_p="(?:'([^']+)'|\"([^\"]+)\"|`([^`]+)`)",kk=new RegExp(`^page\\s*\\.\\s*locator\\(\\s*${_p}\\s*\\)$`),Mp=e=>e[1]??e[2]??e[3]??null,bk=/^[A-Za-z_$][\w$]*$/;function $k(e,t){let o=new RegExp(`\\bconst\\s+${t}\\s*=\\s*page\\s*\\.\\s*locator\\(\\s*${_p}\\s*\\)\\s*;`).exec(e);return o?Mp(o):null}function vk(e,t){let n=t.trim();if(n==="page")return null;let o=kk.exec(n);if(o){let r=Mp(o);return r?{selector:r}:{unresolved:!0}}if(bk.test(n)){let r=$k(e,n);return r?{selector:r}:{unresolved:!0}}return{unresolved:!0}}function Fp(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=yk.exec(e);if(!n)return null;let[o,r="",s=""]=n,i=vk(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(wk,""),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'/,(g,k)=>`import {${k.replace(/\s*$/,"")}, captureShot } from 'document360-capture/helpers'`)),{next:p,selector:i.selector}}function xk(e){try{return Lp(e).filter(t=>t.endsWith(".spec.ts")).some(t=>{try{let n=Fp(Ip(Op(e,t),"utf8"));return n!==null&&!("unresolved"in n)}catch{return!1}})}catch{return!1}}function Ck(e){let t=mk(e)?.captureDir??gk;return hk(t)?t:fk(e,t)}function Wp(e,t){let n={migrated:[],skipped:[]},o=Ck(e);if(!dk(o))return n;let r=t?.captureVersion===void 0?Mt():t.captureVersion;if(!Ws(r,jp))return xk(o)?{...n,heldBackForCapture:{installed:r,required:jp}}:n;let s;try{s=Lp(o).filter(i=>i.endsWith(".spec.ts"))}catch{return n}for(let i of s.sort()){let a=i.slice(0,-8),l=Op(o,i);try{let p=Ip(l,"utf8"),g=Fp(p);if(g===null)continue;if("unresolved"in g){n.skipped.push({id:a,receiver:g.unresolved});continue}pk(l,g.next,"utf8"),n.migrated.push(a)}catch{}}return n}function Up(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
|
-
`)}
|
|
344
|
-
`):null}function
|
|
345
|
-
`))||o.push(r+1));return o}function
|
|
343
|
+
`)}pr();var Vp=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Bp(e){let t=e.includes("--detail")||e.includes("-d"),n=e.find(o=>o!=="--detail"&&o!=="-d");return{mode:"list",scope:n?Vp(n):void 0,...t?{detail:!0}:{}}}function hr(e){let t=(e[0]??"").toLowerCase();if(t==="capture")return{mode:"capture",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 Bp(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 Bp(o.slice(1));let r=o[0];return r?r==="--all"?{mode:"all",setup:n}:/[\\/]/.test(r)||r.endsWith(".md")?{mode:"scope",scope:Vp(r),setup:n}:{mode:"single",id:r}:{mode:"list",picker:!0}}function Ie(e,t,n){let o=an(e),r=o?.captureDir??Ys,s=o?.outputDir??al,i=(k,v)=>qs(k)?Gs(k,v):Vs(e,k,v),a=_t(e),l=n?.captureVersion===void 0?Mt():n.captureVersion,p=Ws(l,Xp),g=Ms(e);return qp(e,{scope:t}).map(({id:k,file:v})=>{let P=i(r,`${k}.spec.ts`),S=null;if(Qa(P))try{S=il(P,"utf8")}catch{}let C=Gp(e,s),T=Qa(Rk(C,k)),D=S===null?null:Ka(a,k,S,g),I=a.shots[k]?.review,O=T&&Pk(I,Tk(C,k))?I:void 0,Y=S!==null&&Ik(S),fe=T&&O?.verdict==="ok"?"verified":T&&O?.verdict==="rejected"?"rejected":T?"captured":S===null?"placeholder":Y||D?.outcome==="skipped"?"blocked":D?.outcome==="failed"?"broken":"spec",ae=S===null?void 0:Kp(S),le=Y?Ok(S):D?.reason,he=Y?"testid":D?.outcome==="skipped"?Ya(D.reason):void 0,ce=S===null?[]:Lk(e,S);return{id:k,file:v,state:fe,...ae?{mutates:ae.mutates,...ae.declared?{}:{undeclared:!0}}:{},...S!==null&&Za(S).length>0?{unguardedWaits:Za(S)}:{},...S!==null&&Ja(S).length>0?{unverifiedForce:Ja(S)}:{},...S!==null&&el(S).length>0?{handRolled:el(S)}:{},...S!==null&&nl(S).length>0?{stalePause:nl(S)}:{},...S!==null&&p&&tl(S).length>0?{bareGoto:tl(S)}:{},...ce.length>0?{staleAnchor:ce}:{},...fe==="blocked"||fe==="broken"?{...le?{reason:le}:{},...he?{blockedBy:he}:{}}:{},...fe==="rejected"?{...O?.reason?{reason:O.reason}:{},...O?.repaired?{repaired:!0}:{}}:{}}})}function Nk(e){let t=an(e)?.outputDir??al;return Sk(Gp(e,t))}function fr(e){let t=Nk(e),n=an(e)?.outputDir??al,o=[];t>0&&o.push(`\u2195 Tidied ${t} screenshot file${t===1?"":"s"} into ${n}/{${Ak},${Dk}} \u2014 annotated/ is what publishes, raw/ is the pre-annotation intermediate.`);let r=Up(Wp(e));return r&&o.push(r),o.length>0?o.join(`
|
|
344
|
+
`):null}function Tn(e,t){let n=an(e)?.captureDir??Ys,o=qs(n)?Gs(n,`${t}.spec.ts`):Vs(e,n,`${t}.spec.ts`);try{return il(o,"utf8")}catch{return null}}function Yp(e,t){let n=an(e)?.captureDir??Ys;return Qa(qs(n)?Gs(n,`${t}.spec.ts`):Vs(e,n,`${t}.spec.ts`))}function jk(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 Kp(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=jk(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 Ik(e){return/(^|\n)\s*test\.skip\s*\(\s*['"`]/.test(e)}function zp(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 Lk(e,t){let n=[];for(let o of zp(t))Ek(e,o.file,o.anchor)===!1&&n.push(o.testid??o.file??"unnamed request");return[...new Set(n)]}function Ok(e){let{testid:t,file:n}=zp(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 mr(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 Ja(e,t=10){let n=mr(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 Za(e){let t=[],n=mr(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 el(e){let t=[];for(let[n,o]of mr(e).entries())(/\.screenshot\s*\(/.test(o)||/\bdumpAnnotations\s*\(/.test(o))&&t.push(n+1);return t}var Xp="0.2.28";function tl(e){let t=[];for(let[n,o]of mr(e).entries())/\.goto\s*\(/.test(o)&&t.push(n+1);return t}function nl(e,t=6){let n=mr(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
|
-
`)}var Tb={placeholder:"\u25CB",spec:"\u25D0",blocked:"\u2298",broken:"\u2717",captured:"\u25CF",verified:"\u2714",rejected:"\u2691"},Eb={placeholder:N.gray,spec:N.yellow,blocked:N.cyan,broken:N.red,captured:N.blue,verified:N.green,rejected:N.magenta},Ab=` ${N.green("\u2714 verified")} ${N.blue("\u25CF to verify")} ${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 uo(e){return e.replace(/\s+/g," ").trim().replace(/^Prerequisites? not met[:—-]?\s*/i,"")}function Ys(e){let t=uo(e),n=/^(.*?[a-z0-9)"'”’])\.(?:\s|$)/i.exec(t);return(n?n[1]:t).trim()}function hr(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=Ys(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 Bp(e){let t=hr(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=Jt(a.reason,86);r.push(` ${N.cyan(on(`${a.ids.length}\xD7`,4))} ${l[0]??""}`);for(let g of l.slice(1))r.push(` ${g}`);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 Hp(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 qp(e,t,n){let o=e.filter(g=>(g.unguardedWaits?.length??0)>0),r=e.filter(g=>g.undeclared),s=e.filter(g=>(g.handRolled?.length??0)>0),i=e.filter(g=>(g.stalePause?.length??0)>0),a=e.filter(g=>(g.bareGoto?.length??0)>0);if(o.length===0&&r.length===0&&s.length===0&&i.length===0&&a.length===0)return[];let l=["",` ${re("\u26A0",N.yellow)}Some specs were written before later reliability fixes:`],p=(g,y)=>` ${g.slice(0,8).map(y).join(" \xB7 ")}${g.length>8?` \xB7 +${g.length-8} more`:""}`;if(o.length>0){let g=o.length;l.push(N.gray(` ${g} crash${g===1?"es":""} instead of telling you what to stage when the data ${g===1?"it needs":"they need"} is missing`)),t&&l.push(N.gray(p(o,y=>`${y.id}:${y.unguardedWaits.join(",")}`)))}if(a.length>0){let g=a.length;l.push(N.gray(` ${g} open${g===1?"s":""} pages the slow way, so ${g===1?"it stalls":"they stall"} for a minute and give up when several shots run at once`)),t&&l.push(N.gray(p(a,y=>`${y.id}:${y.bareGoto.join(",")}`)))}if(i.length>0){let g=i.length;l.push(N.gray(` ${g} decide${g===1?"s":""} "the data is missing" from a fixed pause, so data you HAVE staged can read as absent`)),t&&l.push(N.gray(p(i,y=>`${y.id}:${y.stalePause.join(",")}`)))}if(s.length>0){let g=s.length;l.push(N.gray(` ${g} take${g===1?"s":""} ${g===1?"its":"their"} own screenshot instead of the one call that positions the callouts too \u2014 on a cropped shot the numbers land in the wrong places, and nothing reports it`)),t&&l.push(N.gray(p(s,y=>`${y.id}:${y.handRolled.join(",")}`)))}if(r.length>0){let g=r.length,y=r.filter(v=>v.mutates).length;l.push(N.gray(` ${g} do${g===1?"es":""} not say whether ${g===1?"it changes":"they change"} data in your app`+(y>0?`, so ${y===1?"one is":`${y} are`} left out of bulk runs to be safe`:""))),t&&l.push(N.gray(p(r,v=>v.id)))}return n?.commandInLead||l.push(N.gray(` Re-write them all with the current rules: ${N.bold("/screenshot author --all")}`)),l}function Gp(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 Fs=(e,t)=>e.length>=t?e:e+" ".repeat(t-e.length),on=(e,t)=>e.length>=t?e:" ".repeat(t-e.length)+e;function Vp(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 Db=new Set(["and","or","of","the","to","a","an","in","on","for","with","vs"]),Nb=new Set(["ai","api","cli","ui","ux","url","id","http","https","json","xml","sdk","csv","pdf","oauth","sso","mfa","io","faq"]);function jb(e){return e.replace(/[-_]+/g," ").trim().split(/\s+/).filter(Boolean).map((n,o)=>{let r=n.toLowerCase();return Nb.has(r)?r.toUpperCase():o>0&&Db.has(r)?r:r.charAt(0).toUpperCase()+r.slice(1)}).join(" ")}function Za(e){if(!e)return{num:"",name:"(docs root)"};let t=/^(\d+)[-_](.+)$/.exec(e);return{num:t?t[1]:"",name:jb(t?t[2]:e)}}function Ib(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).pop()??e}function Dp(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 Lb(e,t){let n=t>0?Math.round(e/t*100):0,o=on(`${n}%`,4);return n===100?N.green(o):n>0?N.yellow(o):N.gray(o)}function Yp(e,t){let n=new Map;for(let o of e){let r=Vp(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 Ob(e,t){let n=(X,Z)=>X.filter(ue=>ue.state===Z).length,o=e.length,r=n(e,"verified"),s=n(e,"captured"),i=n(e,"rejected"),a=n(e,"spec"),l=n(e,"blocked"),p=n(e,"broken"),g=n(e,"placeholder"),y=new Set(e.map(X=>X.file)).size,v=Yp(e,t),A=[];A.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.magenta(`${i} rejected`)}`:"")+` ${N.gray("\xB7")} ${a>0?N.yellow(`${a} ready`):N.gray("0 ready")}`+(l>0?` ${N.gray("\xB7")} ${N.cyan(`${l} blocked`)}`:"")+(p>0?` ${N.gray("\xB7")} ${N.red(`${p} broken`)}`:"")+` ${N.gray("\xB7")} ${g>0?N.red(`${g} to spec`):N.gray("0 to spec")} `+N.gray(`across ${y} article${y===1?"":"s"}`));let S=o>0?Math.round(r/o*100):0;A.push(` [${Dp(r,o,32)}] ${N.bold(`${S}%`)}`),A.push("");let x=v.map(([X])=>Za(X)),P=Math.min(32,Math.max(7,...x.map(X=>X.name.length))),D=X=>X.length>P?`${X.slice(0,P-1)}\u2026`:Fs(X,P),I=[...s>0?[{head:"To verify",w:9,state:"captured",color:N.blue}]:[],...i>0?[{head:"Rejected",w:8,state:"rejected",color:N.magenta}]:[],{head:"Ready",w:5,state:"spec",color:N.yellow},...l>0?[{head:"Blocked",w:7,state:"blocked",color:N.cyan}]:[],...p>0?[{head:"Broken",w:6,state:"broken",color:N.red}]:[],{head:"To spec",w:7,state:"placeholder",color:N.red}];A.push(N.gray(` ${Fs("#",2)} ${Fs("Chapter",P)} ${on("Verified",8)} ${I.map(X=>on(X.head,X.w)).join(" ")} Progress`));for(let[X,[,Z]]of v.entries()){let ue=n(Z,"verified"),Te=Z.length,{num:gt,name:Rt}=x[X],Mt=ue===Te,tt=D(Rt),Mn=I.map(Ge=>{let un=n(Z,Ge.state);return un>0?Ge.color(on(String(un),Ge.w)):N.gray(on("\u2014",Ge.w))}).join(" ");A.push(` ${N.cyan(Fs(gt,2))} ${Mt?N.green(tt):ue>0?tt:N.gray(tt)} ${Mt?N.green(on(`${ue}/${Te}`,8)):on(`${ue}/${Te}`,8)} ${Mn} ${Dp(ue,Te,10)} ${Lb(ue,Te)}`)}A.push("");let O=p>0?` ${N.gray("\xB7")} ${p} spec${p===1?"":"s"} broken \u2014 ${N.bold(`/screenshot ${e.find(X=>X.state==="broken").id}`)} re-authors ${p===1?"it":"the first"}`:"",Y=e.filter(X=>X.state==="spec"&&X.mutates).length,fe=a>Y,ae=e.filter(X=>(X.unguardedWaits?.length??0)>0||(X.bareGoto?.length??0)>0).length,le=e.filter(X=>(X.stalePause?.length??0)>0||(X.handRolled?.length??0)>0).length,he=a>0||l>0||p>0,ce=!1;if(g>0)A.push(` ${re("\u2192",N.yellow)}${g} placeholder${g===1?"":"s"} still need a spec \u2014 run ${N.bold("/screenshot author --all")}${O}`);else if(ae>0&&he)ce=!0,A.push(` ${re("\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)`)+O);else if(le>0&&he)ce=!0,A.push(` ${re("\u2192",N.yellow)}${le} spec${le===1?"":"s"} would shoot the wrong thing \u2014 re-write ${le===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)`)+O);else if(a>0&&(fe||s===0)){let X=Y>0?N.gray(` \u2014 ${a-Y} in one go; ${Y} write${Y===1?"s":""} real data and run${Y===1?"s":""} one at a time`):"";A.push(` ${re("\u2192",N.yellow)}${a} spec${a===1?"":"s"} ready to capture \u2014 run ${N.bold("/screenshot capture")}${X}${O}`)}else if(s>0&&a>0)A.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 ${a} ready spec${a===1?"":"s"} write real data, so ${a===1?"it runs":"each runs"} only when named: /screenshot capture <id>`)+O);else if(l>0)A.push(` ${re("\u2192",N.cyan)}${l} shot${l===1?"":"s"} blocked \u2014 stage the data below, then ${N.bold("/screenshot capture --blocked")}${O}`);else if(p>0)A.push(` ${re("\u2192",N.red)}${p} spec${p===1?"":"s"} broken \u2014 ${N.bold(`/screenshot ${e.find(X=>X.state==="broken").id}`)} re-authors ${p===1?"it":"the first"} (re-capturing fails the same way)`);else if(s>0)A.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(i>0){let X=e.filter(Z=>Z.state==="rejected"&&Z.repaired).length;A.push(` ${re("\u2691",N.magenta)}${i} shot${i===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 A.push(` ${re("\u2713",N.green)}all ${o} verified \u2014 ${N.bold("/publish")} embeds them in the articles`);if(r>0&&r<o){let X=v.filter(([,Z])=>Z.every(ue=>ue.state!=="verified")).map(([Z])=>{let{num:ue,name:Te}=Za(Z);return ue?`${ue} ${Te}`:Te});X.length>0&&A.push(N.gray(` Furthest behind: ${X.slice(0,5).join(" \xB7 ")}${X.length>5?" \u2026":""} (0% verified)`))}return A.push(...Bp(e),...Gp(e),...qp(e,!1,{commandInLead:ce}),...Hp(e,!1)),A.push(""),A.push(N.gray(" Drill in: /screenshot list <chapter#> \xB7 /screenshot list --detail (all)")),A}function _b(e,t,n){let o=new Set(e.map(a=>a.file)),r=e.filter(a=>a.state==="verified").length,s=e.filter(a=>a.state==="captured").length,i=[` ${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`):""}${n?N.gray(` \xB7 scope ${n}`):""}`,""];for(let[a,l]of Yp(e,t)){let p=l.filter(S=>S.state==="verified").length,{num:g,name:y}=Za(a),v=g?`${g} \xB7 ${y}`:y;i.push(` ${N.bold(v)} ${N.gray(`(${p}/${l.length})`)}`);let A=new Map;for(let S of l){let x=Ib(S.file),P=A.get(x)??[];A.has(x)||A.set(x,P),P.push(S)}for(let S of[...A.keys()].sort()){i.push(N.gray(` ${S}`));for(let x of A.get(S)){let P=Eb[x.state];if(i.push(` ${re(Tb[x.state],P)}${P(x.id)}`),(x.state==="blocked"||x.state==="broken"||x.state==="rejected")&&x.reason){for(let D of Jt(uo(x.reason),84))i.push(N.gray(` ${D}`));x.state==="rejected"&&i.push(N.gray(` ${x.repaired?"spec repaired \u2014 re-capture to confirm":"spec not yet repaired"}`))}}}}return i.push(...Bp(e),...Gp(e),...qp(e,!0),...Hp(e,!0)),i.push("",Ab),i}function Ks(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??rl;return t?.detail||n?_b(e,o,n):Ob(e,o)}function il(e,t){if(!t||!/^\d+$/.test(t))return t;let n=rn(e)?.docsDir??rl,o=String(Number(t));for(let{file:r}of Np(e)){let s=Vp(r,n),i=/^(\d+)/.exec(s);if(i&&String(Number(i[1]))===o)return s}return t}function Kp(e,t){let r=e.map(a=>" ".repeat(a.depth)+a.label),s=Math.max(0,...e.map((a,l)=>a.note?Ms(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 g=Math.max(2,i+2-Ms(p)),y=a.note.trim(),v=t-Ms(p)-g;return{head:p+" ".repeat(g),note:v>1&&Ms(y)>v?`${y.slice(0,v-1)}\u2026`:y}})}function Mb(e){let t=e.replace(/\\/g,"/").split("/").filter(Boolean),n=t.pop()??e;return{category:t.pop()??"(docs root)",article:n}}function Ws(e,t,n){let o=new Map;for(let s of t){let{category:i,article:a}=Mb(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==="author"||!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 g=i.get(p),y=g.filter(r).map(S=>S.id),v=y.length>0;v&&e.push({kind:"article",action:n,label:`${p} (${y.length})`,ids:y,depth:l?2:1});let A=(l?1:0)+(v?1:0)+1;for(let S of g){let x=n==="capture"&&S.mutates?" \u26A0 creates real data \u2014 runs only alone":void 0;e.push({kind:"shot",action:n,label:S.id,ids:[S.id],depth:A,...x?{note:x}:{}})}}}}function Va(e){return e?uo(e):""}function al(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 ${Va(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 ${Va(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 ${Va(i.reason)}`})}}function zp(e){let t=e.filter(s=>s.state==="placeholder"),n=e.filter(s=>s.state==="spec"),o=[];t.length>1&&o.push({kind:"all",action:"author",label:`Author all ${t.length} remaining specs`,ids:t.map(s=>s.id),depth:0}),Ws(o,t,"author");let r=n.filter(s=>!s.mutates);return r.length>1&&o.push({kind:"all",action:"capture",label:`Capture all ${r.length} ready specs`,ids:r.map(s=>s.id),depth:0}),Ws(o,n,"capture"),al(o,e.filter(s=>s.state==="blocked"),e.filter(s=>s.state==="broken"),e.filter(s=>s.state==="rejected")),o}var el=["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(`
|
|
349
|
-
`);function
|
|
350
|
-
`),"",...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=>
|
|
351
|
-
`)}async function
|
|
352
|
-
`),display:`/screenshot ${o.id}`}}if(o.mode==="capture"||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.`,
|
|
353
|
-
`),a=o.mode==="scope"?`/screenshot ${o.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:i,display:a}}function
|
|
354
|
-
`)}var
|
|
355
|
-
`)}async function ho(e,t){try{let n=ll(e,t),o=n.project.projectId,r=n.project.workspaceId;return!o||!r||(await Jb({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 "${Zb}" 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 _t="--skip-review";function gr(e,t){return Kb(e,t)}function Js(e,t){try{return gr(e,eh(e,t)).length}catch{return 0}}function xt(e,t,n="",o){let r=Js(e,o),s=pl(e,o);if(r===0&&s===0)return t;let i=o?` ${o}`:"",a=o?"/publish":"/publish --all",l=o&&!o.endsWith(".md")?` in ${o}`:"";if(r>0){let g=r===1?"":"s",y=s>0?` ${s} also break house style rules \u2014 /lint${i} --fix clears those afterwards.`:"",v=`/review${i} --blocked --fix`;return{text:`${n}${r} article${g}${l} ${r===1?"carries":"carry"} text no editor has read, so publishing ${r===1?"it is":"them is"} blocked. ${v} reads ${r===1?"it":"just those"} and applies its fixes.${y} Then ${a}.`,cmd:v}}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 pl(e,t){try{return Zp(e,eh(e,t)).length}catch{return 0}}function ih(e,t){return Zp(e,t)}function hl(e,t,n){try{let o=Jp(e,ll(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 fl(e,t,n,o=0,r,s){let i=`/publish${s?` ${s}`:" --all"}`,a=I=>t[I.index]?.paths.length??0,l=e.filter(I=>I.ok),p=e.filter(I=>!I.ok),g=e.reduce((I,O)=>I+a(O),0),y=l.reduce((I,O)=>I+a(O),0),v=n==="api"?`${Qe(e.reduce((I,O)=>I+O.costUsd,0))} total`:nn(e.reduce((I,O)=>I+O.outputTokens,0)),A=`${l.length}/${e.length} partition${e.length===1?"":"s"}`,S=I=>`${I} article${I===1?"":"s"}`,x=[],P=r?kt({blocked:r.blocked,allEmpty:r.allEmpty,aborted:!1},"The publish"):null;if(P)return x.push(...P),x.push(`Nothing reached Document360. Re-run ${i} once that is fixed.`),o>0&&x.push(Sn(o)),x;if(r&&g>0&&r.recorded===0){x.push(`\u2717 Nothing was published \u2014 the ${S(g)} in this run are not recorded in the category map, so none of them reached Document360.`),x.push(`Run /doctor (this is usually the agent runtime not running), then re-run ${i}.`);for(let I of p)I.error&&x.push(` \u2717 ${I.label} \u2014 ${I.error}`);return o>0&&x.push(Sn(o)),x}if(p.length===0&&(!r||r.recorded>=g))x.push(`Published ${S(g)} (${A}) successfully \xB7 ${v}.`),x.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else if(p.length===0&&r)x.push(`Published ${r.recorded}/${S(g)} (${A}) \xB7 ${v}.`),x.push(`${g-r.recorded} article${g-r.recorded===1?"":"s"} reported no error but ${g-r.recorded===1?"is":"are"} not recorded as published \u2014 re-run ${i} to retry just those.`);else{x.push(`Published ${r?r.recorded:y}/${S(g)} (${A}) \xB7 ${v}.`),x.push(`${p.length} partition${p.length===1?"":"s"} failed \u2014 re-run ${i} to retry just the rest (published articles are skipped):`);for(let I of p)x.push(` \u2717 ${I.label}${I.error?` \u2014 ${I.error}`:""}`)}let D=r?Is(r):null;return D&&x.push(D),o>0&&x.push(Sn(o)),x}async function vt(e,t,n=0,o){let r=zb(e.cwd,t,{allowUnreviewed:o?.skipReview===!0,allowStyleErrors:o?.skipStyle===!0});if(!r.clear){for(let a of Xb(r,t.length))console.log(H(a));return{kind:"continue"}}let{model:s}=Gb(e.cwd,"standard"),i=async(a,l)=>{let p=Hb(a);console.log(w(l?`Resolving cross-links in ${a.length} article${a.length===1?"":"s"} whose targets published this run (second pass)\u2026`:`Publishing ${a.length} article${a.length===1?"":"s"} across ${p.length} partition${p.length===1?"":"s"} (\u2264${fr} agents at once) on ${s}\u2026`)),l||console.log(w(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let g=!1;for await(let y of Vb({cwd:e.cwd,partitions:p,promptFor:v=>mr(v.paths),concurrency:fr,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),allowUnreviewedPublish:o?.skipReview===!0,allowStyleErrors:o?.skipStyle===!0,model:s}))if(y.type==="partition_status")y.status==="running"?console.log(w(` \u25B8 ${y.label} \u2014 publishing\u2026`)):y.status==="done"?console.log(V(` \u2713 ${y.label}`)):console.log(j(` \u2717 ${y.label}`));else if(y.type==="run_done"){g=y.aborted,console.log("");let v=process.env.ANTHROPIC_API_KEY?"api":"subscription",A=hl(e.cwd,a,e.profileName),S=!y.aborted&&(!!y.blocked||!!y.allEmpty||a.length>0&&A===0);for(let I of fl(y.results,p,v,l?0:n,{recorded:A,...y.blocked?{blocked:y.blocked}:{},...y.allEmpty?{allEmpty:!0}:{}},o?.scope))console.log(y.ok&&!S?V(I):H(I));if(S)continue;let x=dl(e.cwd,e.profileName);x&&console.log(w(x));let P=po(e.cwd,e.profileName);P&&console.log(w(P));try{let I=nh(await th({cwd:e.cwd,profileName:e.profileName,onRateLimit:O=>console.log(w(` Document360 rate limit \u2014 waiting ${Math.ceil(O.waitMs/1e3)}s\u2026`))}));I&&console.log(I.startsWith("\u26A0")?H(I):w(I))}catch{}try{let I=rh(await oh({cwd:e.cwd,profileName:e.profileName}));I&&console.log(w(I))}catch{}let D=await ho(e.cwd,e.profileName);D&&console.log(w(D))}return g};try{if(!await i(t,!1)){let l=await ml(e.cwd,e.profileName,t);l.length>0&&await i(l,!0)}}catch(a){console.log(j(`Publish run failed: ${a.message}`))}return console.log(""),{kind:"continue"}}async function Zs(e,t,n){let o=qb(e,n);if(o.length===0)return[];let r=new Set(ul((await Xs({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function ml(e,t,n){try{let o=new Set(n),r=await Xs({cwd:e,profileName:t});return ul(r.entries).map(s=>s.path).filter(s=>o.has(s))}catch{return[]}}async function ah(e,t){let n=Je(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(j(n.reason)),{kind:"continue"};let o=e.includes(_t),r=e.includes(Qb),s=e[0];if(e.includes("--screenshots")||e.includes("--shots")){let i=t?.cwd??process.cwd(),a=e.find(v=>!v.startsWith("--")),l=Ne(i),p=Gs(l,a);if(p.length===0)return console.log(w(a?`No captured screenshots in ${a} \u2014 /publish --screenshots covers the whole knowledge base.`:"No captured screenshots yet \u2014 /screenshot capture first.")),{kind:"continue"};let g=Vs(l);g&&console.log(g);let y=Fe("","--screenshots",a).trim();return t?await vt(t,p,0,{skipReview:o,skipStyle:r,scope:y}):{kind:"forward-to-agent",prompt:mr(p),display:`/publish ${y}`}}if(s==="--related"&&e[1]){if(!t)return{kind:"continue"};let i=await Zs(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return i.length===0?(console.log(V("\u2713 All related articles are already published.")),{kind:"continue"}):await vt(t,i,0,{skipReview:o,skipStyle:r,scope:`--related ${e[1]}`})}if(s==="--all"){console.log(w("Checking what needs publishing\u2026"));try{let i=await Xs({cwd:t?.cwd??process.cwd()}),{clean:a,conflicts:l}=Pn(i.entries),p=Qs(i.entries),g=e.includes("--force")&&l.length>0;p>0&&console.log(H(`\u26A0 ${p} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),l.length>0&&!g&&console.log(H(Sn(l.length)));let y=g?[...a,...l]:a;if(y.length===0){if(l.length>0){let A=po(t?.cwd??process.cwd(),t?.profileName);return A&&console.log(w(A)),console.log(w("Resolve the conflicts: /resolve")),{kind:"continue"}}console.log(V(p>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."));let v=po(t?.cwd??process.cwd(),t?.profileName);if(v&&console.log(w(v)),t)try{let A=nh(await th({cwd:t.cwd,profileName:t.profileName,onRateLimit:x=>console.log(w(` Document360 rate limit \u2014 waiting ${Math.ceil(x.waitMs/1e3)}s\u2026`))}));A&&console.log(A.startsWith("\u26A0")?H(A):w(A));let S=rh(await oh({cwd:t.cwd,profileName:t.profileName}));S&&console.log(w(S))}catch{}return{kind:"continue"}}return t?await vt(t,y.map(v=>v.path),g?0:l.length,{skipReview:o,skipStyle:r}):{kind:"forward-to-agent",prompt:mr(y.map(v=>v.path)),display:"/publish --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(w("Checking what needs publishing\u2026"));let i,a=0;try{let l=await Xs({cwd:t?.cwd??process.cwd()}),{clean:p,conflicts:g}=Pn(l.entries);i=p,a=g.length;let y=Qs(l.entries);if(y>0&&console.log(H(`\u26A0 ${y} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),g.length>0&&console.log(H(Sn(g.length))),i.length===0&&g.length>0)return console.log(w("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(l){return console.log(j(`Could not compute sync status: ${l.message}`)),console.log(w("Publish a specific article: /publish <article-path>")),{kind:"continue"}}if(i.length===0)return console.log(V("\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),console.log(w(" (Articles without a sync base are unverified \u2014 publish those by path if needed.)")),{kind:"continue"};if(!process.stdin.isTTY||!t){for(let l of i)console.log(` ${l.path} ${w(`(${l.label})`)}`);return console.log(w("Run: /publish <article-path>")),{kind:"continue"}}try{s=await t.withPausedInput(()=>Bb({message:"Publish which article?",choices:[...i.length>1?[{name:`All ${i.length} candidates`,value:"--all",description:"one agent run over every candidate"}]:[],...i.map(l=>({name:l.path,value:l.path,description:l.label}))]}))}catch{return console.log(w("Cancelled.")),{kind:"continue"}}if(s==="--all")return await vt(t,i.map(l=>l.path),a,{skipReview:o,skipStyle:r})}return{kind:"forward-to-agent",prompt:cl(s),display:`/publish ${s}`}}async function yr(){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(`
|
|
356
|
-
`),display:"/audit"}}ee();import{readProjectConfig as
|
|
357
|
-
`)}async function
|
|
358
|
-
`);return
|
|
359
|
-
`)||
|
|
360
|
-
`},r=o(e),s=o(t);if(r===s)return null;let i=Math.max(20,n-10),a=ak("a","b",r,s,"","",{context:3}),l=0,p=0,g=[];a.hunks.forEach((v,A)=>{A>0&&g.push(ph.gray(" \u2026"));let S=v.oldStart,x=v.newStart,P=[],D=[],I=()=>{for(let O=0;O<P.length;O++){let Y=O<D.length?mh(P[O],D[O]):void 0;p++,g.push(`${lk}${wl(S++)} - ${gh(P[O],i,Y)}${fh}`)}for(let O=0;O<D.length;O++){let Y=O<P.length?mh(P[O],D[O]):void 0;l++,g.push(`${ck}${wl(x++)} + ${gh(D[O],i,Y)}${fh}`)}P=[],D=[]};for(let O of v.lines){let Y=O[0],fe=O.slice(1);Y==="-"?P.push(fe):Y==="+"?D.push(fe):(I(),g.push(ph.gray(wl(x))+" "+fe.slice(0,i)),S++,x++)}I()});let y=g.slice(0,hh);return{added:l,removed:p,lines:y,hidden:Math.max(0,g.length-hh)}}ee();import{select as uk}from"@inquirer/prompts";import{applyPull as wh,computeSyncStatus as dk,planPull as yh}from"document360-engine";var ni=e=>e===1?"":"s";async function bl(e,t,n=1){console.log(""),console.log(`${K("\u25CF")} ${Me(t.title)} ${$e(`(${t.path})`)}`);for(let i of t.notes)console.log(H(` \u26A0 ${i}`));let o=it(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${ni(o.added+o.removed)}`));for(let i of o.lines)console.log(i);o.hidden>0&&console.log(w(` \u2026 +${o.hidden} more diff lines`))}else console.log(w(" Local already matches the portal content \u2014 resolving just advances the sync base."));let r=n>1,s=await e.withPausedInput(()=>uk({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"?(wh({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(w(" Skipped \u2014 still a conflict.")),"skipped"):s==="local-all"?"keep-local-all":s==="portal-all"?"took-portal-all":"skipped-all"}async function bh(e,t){let n=Je(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 dk({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 yh({cwd:t.cwd,profileName:t.profileName,relPath:l}),g=await bl(t,p,s.length-a);if(g==="keep-local"&&i.push(l),!g.endsWith("-all"))continue;let y=s.slice(a);if(g==="keep-local-all")i.push(...y),console.log(w(` Keeping local for all ${y.length} \u2014 publishing them over the portal.`));else if(g==="took-portal-all"){let v=0;for(let A of y)try{wh({cwd:t.cwd,profileName:t.profileName},await yh({cwd:t.cwd,profileName:t.profileName,relPath:A})),v++}catch(S){console.log(j(` \u2717 ${A}: ${S.message}`))}console.log(V(` \u2713 Took the portal copy of ${v} article${ni(v)} (local overwritten, sync base advanced).`))}else console.log(w(` Skipped all ${y.length} \u2014 still conflict${ni(y.length)}.`));break}if(i.length>0)return console.log(w(`Publishing ${i.length} kept-local article${ni(i.length)} over the portal\u2026`)),await vt(t,i)}catch(r){console.log(j(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function vh(e,t){let n=Je(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 bk(t),{kind:"continue"};if(o==="--baseline")return await kk(t,e.filter(i=>i!=="--baseline")),{kind:"continue"};if(o==="--compare")return await $k(t),{kind:"continue"};if(o)return console.log(j(`Unknown option: ${o}`)),console.log(w("Usage: /pull pull portal edits + import new portal articles")),console.log(w(" /pull <path> pull one article (or resolve a conflict)")),console.log(w(" /pull --status drift report only (no writes)")),console.log(w(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await vk(t,r),{kind:"continue"};console.log(w("Pulling changes from Document360\u2026"));let s=await $l({cwd:t.cwd,profileName:t.profileName});for(let i of vl(s))console.log(i.tone==="ok"?V(i.text):i.tone==="warn"?H(i.text):w(i.text));console.log("")}catch(r){r instanceof wk?console.log(j(r.message)):console.log(j(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function $l(e){let t=await kh({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 $h({cwd:e.cwd,profileName:e.profileName,relPath:o.path});kl({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 fk({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});mk({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 oi=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Tn=e=>e===1?"":"s";function vl(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${Tn(e.pulled.length)} into local: ${oi(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${Tn(e.imported.length)}: ${oi(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${Tn(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${Tn(e.conflicts.length)} changed both here and on Document360 \u2014 left untouched. Resolve them: /resolve (or /publish <path> to keep yours, /pull <path> to take the portal's). (${oi(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${Tn(e.failed.length)} failed: ${oi(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 bk(e){console.log(w("Checking Document360 for drift\u2026"));let t=Date.now(),n=await kh({cwd:e.cwd,profileName:e.profileName});for(let o of ti(n,Date.now()-t))console.log(o);console.log("")}async function kk(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(w(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await gk({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await yk({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 Baselined ${o.baselined.length} article(s) \u2014 they now 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(H(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(w(` - ${s.path} (${s.reason})`))}}async function $k(e){console.log(w("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await hk({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${Me(String(t.legacyCount))} \xB7 Manifest: ${Me(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(H(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(H(` ${t.onlyInManifest.length} only in the manifest: ${t.onlyInManifest.slice(0,5).join(", ")}`)),console.log(w(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function vk(e,t){let n=t.replace(/\\/g,"/"),o=await $h({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await bl(e,o)==="keep-local"&&(console.log(w(`Publishing ${o.path} over the portal\u2026`)),await vt(e,[o.path]));return}console.log(""),console.log(`${K("\u25CF")} ${Me(o.title)} ${$e(`(${o.path})`)}`);for(let i of o.notes)console.log(H(` \u26A0 ${i}`));let r=it(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!r){console.log(w(" Local file already matches the remote content \u2014 advancing the sync base only.")),kl({cwd:e.cwd,profileName:e.profileName},o);return}console.log($e(` \u23BF Added ${r.added} line${Tn(r.added)}, removed ${r.removed} line${Tn(r.removed)}`));for(let i of r.lines)console.log(i);if(r.hidden>0&&console.log(w(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>pk({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(w(" Skipped."));return}kl({cwd:e.cwd,profileName:e.profileName},o),console.log(V(` \u2713 Pulled ${o.path} (sync base advanced).`))}ee();import{statSync as xk}from"node:fs";import{resolve as Ck}from"node:path";import{estimateBulkCost as Rk,planPartitions as Sk,readProjectConfig as Pk,resolveModelForOperation as Tk,runPartitioned as Ek,trackedArticlePaths as Ak}from"document360-engine";var xl=3;function Cl(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 Rl(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Sl(e,t){return t.map(n=>{let o=0;try{o=xk(Ck(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function Pl(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:
|
|
347
|
+
`);/\.waitFor\s*\(|Promise\.race\s*\(|waitForFunction\s*\(|waitForSelector\s*\(/.test(a)||o.push(r+1)}return o}function cl(e,t){let n=g=>`line${g.length===1?"":"s"} ${g.join(", ")}`,o=[],r=t?.captureVersion===void 0?Mt():t.captureVersion,s=Ws(r,Xp)?tl(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=Za(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=el(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=nl(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=Ja(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 Qp(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 Jp(e){return(e??"").trim().replace(/[.\s]+$/,"")}function Zp(e,t){let n=an(e)?.captureDir??Ys,o=qs(n)?Gs(n,`${t}.spec.ts`):Vs(e,n,`${t}.spec.ts`);try{return Kp(il(o,"utf8"))}catch{return{mutates:!1,declared:!1}}}var _k=["captured","verified","rejected"],Mk=e=>_k.includes(e);function Fk(e){return[...new Set(e.filter(t=>Mk(t.state)).map(t=>t.file))].sort()}function Ks(e,t){let n=Fk(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){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",j.yellow)}${t.length} screenshot${t.length===1?"":"s"} failed verification:`,...t.map(o=>` ${j.magenta(o.id.padEnd(n))} ${j.gray(go(o.reason??"no reason recorded"))}`),` Publishing anyway. Fix + re-capture: ${j.bold("/screenshot capture --failed")}`].join(`
|
|
348
|
+
`)}var Wk={placeholder:"\u25CB",spec:"\u25D0",blocked:"\u2298",broken:"\u2717",captured:"\u25CF",verified:"\u2714",rejected:"\u2691"},Uk={placeholder:j.gray,spec:j.yellow,blocked:j.cyan,broken:j.red,captured:j.blue,verified:j.green,rejected:j.magenta},Bk=` ${j.green("\u2714 verified")} ${j.blue("\u25CF to verify")} ${j.yellow("\u25D0 ready")} ${j.magenta("\u2691 rejected")} ${j.cyan("\u2298 blocked")} ${j.red("\u2717 broken")} ${j.gray("\u25CB to spec")}`;function re(e,t=n=>n){return`${t(e)} `}function go(e){return e.replace(/\s+/g," ").trim().replace(/^Prerequisites? not met[:—-]?\s*/i,"")}function Xs(e){let t=go(e),n=/^(.*?[a-z0-9)"'”’])\.(?:\s|$)/i.exec(t);return(n?n[1]:t).trim()}function gr(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=Xs(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 eh(e){let t=gr(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(` ${j.bold("Stage this data")} ${j.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=en(a.reason,86);r.push(` ${j.cyan(sn(`${a.ids.length}\xD7`,4))} ${l[0]??""}`);for(let g of l.slice(1))r.push(` ${g}`);let p=a.ids.slice(0,4).join(" \xB7 ");r.push(j.gray(` ${p}${a.ids.length>4?` \xB7 +${a.ids.length-4} more`:""}`))}n.length>i&&r.push(j.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",j.cyan)}${s} shot${s===1?"":"s"} need${s===1?"s":""} a data-testid from your developers \u2014 ${j.bold("/screenshot checklist")} builds the hand-off.`)}return r}function th(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",j.yellow)}${r} selector request${r===1?"":"s"} quote${r===1?"s":""} source code that has since changed`+j.gray(" \u2014 your developers would go looking for something that isn't there any more"),j.gray(` Refresh the hand-off before sending it: ${j.bold("/screenshot checklist")}`)];return t&&s.push(j.gray(` ${o.slice(0,8).join(" \xB7 ")}${r>8?` \xB7 +${r-8} more`:""}`)),s}function nh(e,t,n){let o=e.filter(g=>(g.unguardedWaits?.length??0)>0),r=e.filter(g=>g.undeclared),s=e.filter(g=>(g.handRolled?.length??0)>0),i=e.filter(g=>(g.stalePause?.length??0)>0),a=e.filter(g=>(g.bareGoto?.length??0)>0);if(o.length===0&&r.length===0&&s.length===0&&i.length===0&&a.length===0)return[];let l=["",` ${re("\u26A0",j.yellow)}Some specs were written before later reliability fixes:`],p=(g,k)=>` ${g.slice(0,8).map(k).join(" \xB7 ")}${g.length>8?` \xB7 +${g.length-8} more`:""}`;if(o.length>0){let g=o.length;l.push(j.gray(` ${g} crash${g===1?"es":""} instead of telling you what to stage when the data ${g===1?"it needs":"they need"} is missing`)),t&&l.push(j.gray(p(o,k=>`${k.id}:${k.unguardedWaits.join(",")}`)))}if(a.length>0){let g=a.length;l.push(j.gray(` ${g} open${g===1?"s":""} pages the slow way, so ${g===1?"it stalls":"they stall"} for a minute and give up when several shots run at once`)),t&&l.push(j.gray(p(a,k=>`${k.id}:${k.bareGoto.join(",")}`)))}if(i.length>0){let g=i.length;l.push(j.gray(` ${g} decide${g===1?"s":""} "the data is missing" from a fixed pause, so data you HAVE staged can read as absent`)),t&&l.push(j.gray(p(i,k=>`${k.id}:${k.stalePause.join(",")}`)))}if(s.length>0){let g=s.length;l.push(j.gray(` ${g} take${g===1?"s":""} ${g===1?"its":"their"} own screenshot instead of the one call that positions the callouts too \u2014 on a cropped shot the numbers land in the wrong places, and nothing reports it`)),t&&l.push(j.gray(p(s,k=>`${k.id}:${k.handRolled.join(",")}`)))}if(r.length>0){let g=r.length,k=r.filter(v=>v.mutates).length;l.push(j.gray(` ${g} do${g===1?"es":""} not say whether ${g===1?"it changes":"they change"} data in your app`+(k>0?`, so ${k===1?"one is":`${k} are`} left out of bulk runs to be safe`:""))),t&&l.push(j.gray(p(r,v=>v.id)))}return n?.commandInLead||l.push(j.gray(` Re-write them all with the current rules: ${j.bold("/screenshot author --all")}`)),l}function oh(e){let t=e.filter(n=>(n.unverifiedForce?.length??0)>0);return t.length===0?[]:["",` ${re("\u26A0",j.red)}${t.length} spec${t.length===1?"":"s"} force-click past Playwright's safety checks without asserting the result`+j.gray(" \u2014 if the click lands on nothing, the shot photographs the unchanged screen"),j.gray(` ${t.slice(0,6).map(n=>`${n.id}:${n.unverifiedForce.join(",")}`).join(" \xB7 ")}${t.length>6?` \xB7 +${t.length-6} more`:""}`),j.gray(` Re-author to check what the click did: ${j.bold("/screenshot author <id>")}`)]}var Bs=(e,t)=>e.length>=t?e:e+" ".repeat(t-e.length),sn=(e,t)=>e.length>=t?e:" ".repeat(t-e.length)+e;function rh(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 Hk=new Set(["and","or","of","the","to","a","an","in","on","for","with","vs"]),qk=new Set(["ai","api","cli","ui","ux","url","id","http","https","json","xml","sdk","csv","pdf","oauth","sso","mfa","io","faq"]);function Gk(e){return e.replace(/[-_]+/g," ").trim().split(/\s+/).filter(Boolean).map((n,o)=>{let r=n.toLowerCase();return qk.has(r)?r.toUpperCase():o>0&&Hk.has(r)?r:r.charAt(0).toUpperCase()+r.slice(1)}).join(" ")}function ol(e){if(!e)return{num:"",name:"(docs root)"};let t=/^(\d+)[-_](.+)$/.exec(e);return{num:t?t[1]:"",name:Gk(t?t[2]:e)}}function Vk(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).pop()??e}function Hp(e,t,n){let o=t>0?Math.round(e/t*n):0;return j.green("\u2588".repeat(o))+j.gray("\u2591".repeat(Math.max(0,n-o)))}function Yk(e,t){let n=t>0?Math.round(e/t*100):0,o=sn(`${n}%`,4);return n===100?j.green(o):n>0?j.yellow(o):j.gray(o)}function sh(e,t){let n=new Map;for(let o of e){let r=rh(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 Kk(e,t){let n=(X,ne)=>X.filter(ue=>ue.state===ne).length,o=e.length,r=n(e,"verified"),s=n(e,"captured"),i=n(e,"rejected"),a=n(e,"spec"),l=n(e,"blocked"),p=n(e,"broken"),g=n(e,"placeholder"),k=new Set(e.map(X=>X.file)).size,v=sh(e,t),P=[];P.push(` ${j.bold("Screenshots")} ${j.green(`${r}/${o} verified`)} ${j.gray("\xB7")} ${s>0?j.blue(`${s} to verify`):j.gray("0 to verify")}`+(i>0?` ${j.gray("\xB7")} ${j.magenta(`${i} rejected`)}`:"")+` ${j.gray("\xB7")} ${a>0?j.yellow(`${a} ready`):j.gray("0 ready")}`+(l>0?` ${j.gray("\xB7")} ${j.cyan(`${l} blocked`)}`:"")+(p>0?` ${j.gray("\xB7")} ${j.red(`${p} broken`)}`:"")+` ${j.gray("\xB7")} ${g>0?j.red(`${g} to spec`):j.gray("0 to spec")} `+j.gray(`across ${k} article${k===1?"":"s"}`));let S=o>0?Math.round(r/o*100):0;P.push(` [${Hp(r,o,32)}] ${j.bold(`${S}%`)}`),P.push("");let C=v.map(([X])=>ol(X)),T=Math.min(32,Math.max(7,...C.map(X=>X.name.length))),D=X=>X.length>T?`${X.slice(0,T-1)}\u2026`:Bs(X,T),I=[...s>0?[{head:"To verify",w:9,state:"captured",color:j.blue}]:[],...i>0?[{head:"Rejected",w:8,state:"rejected",color:j.magenta}]:[],{head:"Ready",w:5,state:"spec",color:j.yellow},...l>0?[{head:"Blocked",w:7,state:"blocked",color:j.cyan}]:[],...p>0?[{head:"Broken",w:6,state:"broken",color:j.red}]:[],{head:"To spec",w:7,state:"placeholder",color:j.red}];P.push(j.gray(` ${Bs("#",2)} ${Bs("Chapter",T)} ${sn("Verified",8)} ${I.map(X=>sn(X.head,X.w)).join(" ")} Progress`));for(let[X,[,ne]]of v.entries()){let ue=n(ne,"verified"),Te=ne.length,{num:yt,name:St}=C[X],Wt=ue===Te,nt=D(St),Wn=I.map(Ke=>{let hn=n(ne,Ke.state);return hn>0?Ke.color(sn(String(hn),Ke.w)):j.gray(sn("\u2014",Ke.w))}).join(" ");P.push(` ${j.cyan(Bs(yt,2))} ${Wt?j.green(nt):ue>0?nt:j.gray(nt)} ${Wt?j.green(sn(`${ue}/${Te}`,8)):sn(`${ue}/${Te}`,8)} ${Wn} ${Hp(ue,Te,10)} ${Yk(ue,Te)}`)}P.push("");let O=p>0?` ${j.gray("\xB7")} ${p} spec${p===1?"":"s"} broken \u2014 ${j.bold(`/screenshot ${e.find(X=>X.state==="broken").id}`)} re-authors ${p===1?"it":"the first"}`:"",Y=e.filter(X=>X.state==="spec"&&X.mutates).length,fe=a>Y,ae=e.filter(X=>(X.unguardedWaits?.length??0)>0||(X.bareGoto?.length??0)>0).length,le=e.filter(X=>(X.stalePause?.length??0)>0||(X.handRolled?.length??0)>0).length,he=a>0||l>0||p>0,ce=!1;if(g>0)P.push(` ${re("\u2192",j.yellow)}${g} placeholder${g===1?"":"s"} still need a spec \u2014 run ${j.bold("/screenshot author --all")}${O}`);else if(ae>0&&he)ce=!0,P.push(` ${re("\u2192",j.yellow)}${ae} spec${ae===1?"":"s"} would crash mid-run \u2014 re-write ${ae===1?"it":"them"} first: ${j.bold("/screenshot author --all")}`+j.gray(` \xB7 then ${j.bold("/screenshot capture")} (no browser time wasted on ${ae===1?"a shot":"shots"} that can't finish)`)+O);else if(le>0&&he)ce=!0,P.push(` ${re("\u2192",j.yellow)}${le} spec${le===1?"":"s"} would shoot the wrong thing \u2014 re-write ${le===1?"it":"them"} first: ${j.bold("/screenshot author --all")}`+j.gray(` \xB7 then ${j.bold("/screenshot capture")} (a false skip or a misplaced callout costs the same browser time as a good shot)`)+O);else if(a>0&&(fe||s===0)){let X=Y>0?j.gray(` \u2014 ${a-Y} in one go; ${Y} write${Y===1?"s":""} real data and run${Y===1?"s":""} one at a time`):"";P.push(` ${re("\u2192",j.yellow)}${a} spec${a===1?"":"s"} ready to capture \u2014 run ${j.bold("/screenshot capture")}${X}${O}`)}else if(s>0&&a>0)P.push(` ${re("\u2192",j.blue)}${s} shot${s===1?"":"s"} awaiting verification \u2014 run ${j.bold("/screenshot verify")}`+j.gray(" \u2014 no browser needed")+j.gray(` \xB7 ${a} ready spec${a===1?"":"s"} write real data, so ${a===1?"it runs":"each runs"} only when named: /screenshot capture <id>`)+O);else if(l>0)P.push(` ${re("\u2192",j.cyan)}${l} shot${l===1?"":"s"} blocked \u2014 stage the data below, then ${j.bold("/screenshot capture --blocked")}${O}`);else if(p>0)P.push(` ${re("\u2192",j.red)}${p} spec${p===1?"":"s"} broken \u2014 ${j.bold(`/screenshot ${e.find(X=>X.state==="broken").id}`)} re-authors ${p===1?"it":"the first"} (re-capturing fails the same way)`);else if(s>0)P.push(` ${re("\u2192",j.blue)}${s} shot${s===1?"":"s"} awaiting verification \u2014 run ${j.bold("/screenshot verify")}`+j.gray(" \u2014 it checks each picture against what its article needs (no browser, no re-capture)"));else if(i>0){let X=e.filter(ne=>ne.state==="rejected"&&ne.repaired).length;P.push(` ${re("\u2691",j.magenta)}${i} shot${i===1?"":"s"} failed review \u2014 `+(X>0?`${X} spec${X===1?"":"s"} already repaired; re-capture with ${j.bold("/screenshot capture --failed")}`:`see the reasons below, then ${j.bold("/screenshot capture --failed")}`))}else P.push(` ${re("\u2713",j.green)}all ${o} verified \u2014 ${j.bold("/push")} embeds them in the articles`);if(r>0&&r<o){let X=v.filter(([,ne])=>ne.every(ue=>ue.state!=="verified")).map(([ne])=>{let{num:ue,name:Te}=ol(ne);return ue?`${ue} ${Te}`:Te});X.length>0&&P.push(j.gray(` Furthest behind: ${X.slice(0,5).join(" \xB7 ")}${X.length>5?" \u2026":""} (0% verified)`))}return P.push(...eh(e),...oh(e),...nh(e,!1,{commandInLead:ce}),...th(e,!1)),P.push(""),P.push(j.gray(" Drill in: /screenshot list <chapter#> \xB7 /screenshot list --detail (all)")),P}function zk(e,t,n){let o=new Set(e.map(a=>a.file)),r=e.filter(a=>a.state==="verified").length,s=e.filter(a=>a.state==="captured").length,i=[` ${j.bold("Screenshots")}: ${e.length} placeholder${e.length===1?"":"s"} across ${o.size} article${o.size===1?"":"s"} \xB7 ${j.green(`${r} verified`)}${s>0?j.blue(` \xB7 ${s} to verify`):""}${n?j.gray(` \xB7 scope ${n}`):""}`,""];for(let[a,l]of sh(e,t)){let p=l.filter(S=>S.state==="verified").length,{num:g,name:k}=ol(a),v=g?`${g} \xB7 ${k}`:k;i.push(` ${j.bold(v)} ${j.gray(`(${p}/${l.length})`)}`);let P=new Map;for(let S of l){let C=Vk(S.file),T=P.get(C)??[];P.has(C)||P.set(C,T),T.push(S)}for(let S of[...P.keys()].sort()){i.push(j.gray(` ${S}`));for(let C of P.get(S)){let T=Uk[C.state];if(i.push(` ${re(Wk[C.state],T)}${T(C.id)}`),(C.state==="blocked"||C.state==="broken"||C.state==="rejected")&&C.reason){for(let D of en(go(C.reason),84))i.push(j.gray(` ${D}`));C.state==="rejected"&&i.push(j.gray(` ${C.repaired?"spec repaired \u2014 re-capture to confirm":"spec not yet repaired"}`))}}}}return i.push(...eh(e),...oh(e),...nh(e,!0),...th(e,!0)),i.push("",Bk),i}function Qs(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??ll;return t?.detail||n?zk(e,o,n):Kk(e,o)}function ul(e,t){if(!t||!/^\d+$/.test(t))return t;let n=an(e)?.docsDir??ll,o=String(Number(t));for(let{file:r}of qp(e)){let s=rh(r,n),i=/^(\d+)/.exec(s);if(i&&String(Number(i[1]))===o)return s}return t}function ih(e,t){let r=e.map(a=>" ".repeat(a.depth)+a.label),s=Math.max(0,...e.map((a,l)=>a.note?Us(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 g=Math.max(2,i+2-Us(p)),k=a.note.trim(),v=t-Us(p)-g;return{head:p+" ".repeat(g),note:v>1&&Us(k)>v?`${k.slice(0,v-1)}\u2026`:k}})}function Xk(e){let t=e.replace(/\\/g,"/").split("/").filter(Boolean),n=t.pop()??e;return{category:t.pop()??"(docs root)",article:n}}function Hs(e,t,n){let o=new Map;for(let s of t){let{category:i,article:a}=Xk(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==="author"||!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 g=i.get(p),k=g.filter(r).map(S=>S.id),v=k.length>0;v&&e.push({kind:"article",action:n,label:`${p} (${k.length})`,ids:k,depth:l?2:1});let P=(l?1:0)+(v?1:0)+1;for(let S of g){let C=n==="capture"&&S.mutates?" \u26A0 creates real data \u2014 runs only alone":void 0;e.push({kind:"shot",action:n,label:S.id,ids:[S.id],depth:P,...C?{note:C}:{}})}}}}function Xa(e){return e?go(e):""}function dl(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 ${Xa(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 ${Xa(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 ${Xa(i.reason)}`})}}function ah(e){let t=e.filter(s=>s.state==="placeholder"),n=e.filter(s=>s.state==="spec"),o=[];t.length>1&&o.push({kind:"all",action:"author",label:`Author all ${t.length} remaining specs`,ids:t.map(s=>s.id),depth:0}),Hs(o,t,"author");let r=n.filter(s=>!s.mutates);return r.length>1&&o.push({kind:"all",action:"capture",label:`Capture all ${r.length} ready specs`,ids:r.map(s=>s.id),depth:0}),Hs(o,n,"capture"),dl(o,e.filter(s=>s.state==="blocked"),e.filter(s=>s.state==="broken"),e.filter(s=>s.state==="rejected")),o}var rl=["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(`
|
|
349
|
+
`);function Qk(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 sl="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 lh(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(`
|
|
350
|
+
`),"",...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=>Qp(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.",rl,sl].join(`
|
|
351
|
+
`)}async function Js(e,t,n){let o=hr(e),r=fr(t?.cwd??process.cwd());if(r&&console.log(j.gray(r)),o.mode==="list"){let l=t?.cwd??process.cwd(),p=ul(l,o.scope),g=an(l)?.docsDir??ll,k=Ie(l,p);for(let v of Qs(k,{scope:p,detail:o.detail,docsDir:g}))console.log(v);return{kind:"continue"}}if(o.mode==="single"){let l=Tn(t?.cwd??process.cwd(),o.id),p=l===null?[]:cl(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.",rl,sl,...n?.prior?["",...Qk(n.prior)]:[],...p.length>0?["",...Qp(p,"RULE VIOLATIONS already in the existing spec \u2014 fix every one:")]:[]].join(`
|
|
352
|
+
`),display:`/screenshot ${o.id}`}}if(o.mode==="capture"||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.`,rl,sl].join(`
|
|
353
|
+
`),a=o.mode==="scope"?`/screenshot ${o.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:i,display:a}}function Ne(e,t,n){return`${e}${n?` ${n}`:""}${t?` ${t}`:""}`}function vt(e){if(e.length===0)return;let t=e.map(r=>r.replace(/\\/g,"/"));if(t.length===1)return t[0];let n=r=>r.split("/").slice(0,-1).join("/"),o=n(t[0]);if(o!=="")return t.every(r=>n(r)===o)?o:void 0}var yr=3;function hl(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(`
|
|
354
|
+
`)}var ch={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 pushing overwrites the portal edit"};function fl(e){return e.filter(t=>t.path!==null&&t.status in ch&&!t.link).map(t=>({path:t.path,label:ch[t.status]}))}function An(e){let t=fl(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 En(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 yo(e,t){let n=sb(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 ei(e){return e.filter(t=>t.link).length}function ml(e,t){try{let n=uh(e,pl(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=pb(Jk(Zk(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 yh(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:`${ho(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 wr(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(`
|
|
355
|
+
`)}async function wo(e,t){try{let n=pl(e,t),o=n.project.projectId,r=n.project.workspaceId;return!o||!r||(await ub({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 "${db}" 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 it="--skip-review";function kr(e,t){return ib(e,t)}function ti(e,t){try{return kr(e,ph(e,t)).length}catch{return 0}}function Ct(e,t,n="",o){let r=ti(e,o),s=gl(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 g=r===1?"":"s",k=s>0?` ${s} also break house style rules \u2014 /lint${i} --fix clears those afterwards.`:"",v=`/review${i} --blocked --fix`;return{text:`${n}${r} article${g}${l} ${r===1?"carries":"carry"} text no editor has read, so pushing ${r===1?"it is":"them is"} blocked. ${v} reads ${r===1?"it":"just those"} and applies its fixes.${k} Then ${a}.`,cmd:v}}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 gl(e,t){try{return dh(e,ph(e,t)).length}catch{return 0}}function wh(e,t){return dh(e,t)}function yl(e,t,n){try{let o=uh(e,pl(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 wl(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),g=e.reduce((I,O)=>I+a(O),0),k=l.reduce((I,O)=>I+a(O),0),v=n==="api"?`${Ze(e.reduce((I,O)=>I+O.costUsd,0))} total`:rn(e.reduce((I,O)=>I+O.outputTokens,0)),P=`${l.length}/${e.length} batch${e.length===1?"":"es"}`,S=I=>`${I} article${I===1?"":"s"}`,C=[],T=r?$t({blocked:r.blocked,allEmpty:r.allEmpty,aborted:!1},"The push"):null;if(T)return C.push(...T),C.push(`Nothing reached Document360. Re-run ${i} once that is fixed.`),o>0&&C.push(En(o)),C;if(r&&g>0&&r.recorded===0){C.push(`\u2717 Nothing was pushed \u2014 the ${S(g)} 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(En(o)),C}if(p.length===0&&(!r||r.recorded>=g))C.push(`Pushed ${S(g)} (${P}) successfully \xB7 ${v}.`),C.push(`Saved on Document360 as draft${g===1?"":"s"} \u2014 readers don't see ${g===1?"it":"them"} until /publish takes ${g===1?"it":"them"} live.`);else if(p.length===0&&r)C.push(`Pushed ${r.recorded}/${S(g)} (${P}) \xB7 ${v}.`),C.push(`${g-r.recorded} article${g-r.recorded===1?"":"s"} reported no error but ${g-r.recorded===1?"is":"are"} not recorded on Document360 \u2014 re-run ${i} to retry just those.`);else{C.push(`Pushed ${r?r.recorded:k}/${S(g)} (${P}) \xB7 ${v}.`),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 D=r?_s(r):null;return D&&C.push(D),o>0&&C.push(En(o)),C}async function xt(e,t,n=0,o){let r=ab(e.cwd,t,{allowUnreviewed:o?.skipReview===!0,allowStyleErrors:o?.skipStyle===!0});if(!r.clear){for(let a of lb(r,t.length))console.log(H(a));return{kind:"continue"}}let{model:s}=ob(e.cwd,"standard"),i=async(a,l)=>{let p=tb(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${yr} agents at once) on ${s}\u2026`)),l||console.log(y(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let g=!1;for await(let k of rb({cwd:e.cwd,partitions:p,promptFor:v=>wr(v.paths),concurrency:yr,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),allowUnreviewedPublish:o?.skipReview===!0,allowStyleErrors:o?.skipStyle===!0,model:s}))if(k.type==="partition_status")k.status==="running"?console.log(y(` \u25B8 ${k.label} \u2014 pushing\u2026`)):k.status==="done"?console.log(G(` \u2713 ${k.label}`)):console.log(N(` \u2717 ${k.label}`));else if(k.type==="run_done"){g=k.aborted,console.log("");let v=process.env.ANTHROPIC_API_KEY?"api":"subscription",P=yl(e.cwd,a,e.profileName),S=!k.aborted&&(!!k.blocked||!!k.allEmpty||a.length>0&&P===0);for(let I of wl(k.results,p,v,l?0:n,{recorded:P,...k.blocked?{blocked:k.blocked}:{},...k.allEmpty?{allEmpty:!0}:{}},o?.scope))console.log(k.ok&&!S?G(I):H(I));if(S)continue;let C=ml(e.cwd,e.profileName);C&&console.log(y(C));let T=yo(e.cwd,e.profileName);T&&console.log(y(T));try{let I=fh(await hh({cwd:e.cwd,profileName:e.profileName,onRateLimit:O=>console.log(y(` Document360 rate limit \u2014 waiting ${Math.ceil(O.waitMs/1e3)}s\u2026`))}));I&&console.log(I.startsWith("\u26A0")?H(I):y(I))}catch{}try{let I=gh(await mh({cwd:e.cwd,profileName:e.profileName}));I&&console.log(y(I))}catch{}let D=await wo(e.cwd,e.profileName);D&&console.log(y(D))}return g};try{if(!await i(t,!1)){let l=await kl(e.cwd,e.profileName,t);l.length>0&&await i(l,!0)}}catch(a){console.log(N(`Push run failed: ${a.message}`))}return console.log(""),{kind:"continue"}}async function ni(e,t,n){let o=nb(e,n);if(o.length===0)return[];let r=new Set(fl((await Zs({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function kl(e,t,n){try{let o=new Set(n),r=await Zs({cwd:e,profileName:t});return fl(r.entries).map(s=>s.path).filter(s=>o.has(s))}catch{return[]}}async function oi(e,t){let n=Ue(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(N(n.reason)),{kind:"continue"};let o=e.includes(it),r=e.includes(cb),s=e[0];if(e.includes("--screenshots")||e.includes("--shots")){let i=t?.cwd??process.cwd(),a=e.find(v=>!v.startsWith("--")),l=Ie(i),p=Ks(l,a);if(p.length===0)return console.log(y(a?`No captured screenshots in ${a} \u2014 /push --screenshots covers the whole knowledge base.`:"No captured screenshots yet \u2014 /screenshot capture first.")),{kind:"continue"};let g=zs(l);g&&console.log(g);let k=Ne("","--screenshots",a).trim();return t?await xt(t,p,0,{skipReview:o,skipStyle:r,scope:k}):{kind:"forward-to-agent",prompt:wr(p),display:`/push ${k}`}}if(s==="--related"&&e[1]){if(!t)return{kind:"continue"};let i=await ni(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return i.length===0?(console.log(G("\u2713 All related articles are already on Document360.")),{kind:"continue"}):await xt(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 Zs({cwd:t?.cwd??process.cwd()}),{clean:a,conflicts:l}=An(i.entries),p=ei(i.entries),g=e.includes("--force")&&l.length>0;p>0&&console.log(H(`\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&&!g&&console.log(H(En(l.length)));let k=g?[...a,...l]:a;if(k.length===0){if(l.length>0){let P=yo(t?.cwd??process.cwd(),t?.profileName);return P&&console.log(y(P)),console.log(y("Resolve the conflicts: /resolve")),{kind:"continue"}}console.log(G(p>0?"\u2713 Nothing else is ahead of Document360 to push.":"\u2713 Nothing is ahead of Document360 \u2014 nothing to push."));let v=yo(t?.cwd??process.cwd(),t?.profileName);if(v&&console.log(y(v)),t)try{let P=fh(await hh({cwd:t.cwd,profileName:t.profileName,onRateLimit:C=>console.log(y(` Document360 rate limit \u2014 waiting ${Math.ceil(C.waitMs/1e3)}s\u2026`))}));P&&console.log(P.startsWith("\u26A0")?H(P):y(P));let S=gh(await mh({cwd:t.cwd,profileName:t.profileName}));S&&console.log(y(S))}catch{}return{kind:"continue"}}return t?await xt(t,k.map(v=>v.path),g?0:l.length,{skipReview:o,skipStyle:r}):{kind:"forward-to-agent",prompt:wr(k.map(v=>v.path)),display:"/push --all"}}catch(i){return console.log(N(`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 Zs({cwd:t?.cwd??process.cwd()}),{clean:p,conflicts:g}=An(l.entries);i=p,a=g.length;let k=ei(l.entries);if(k>0&&console.log(H(`\u26A0 ${k} article(s) already exist on Document360 but aren't linked \u2014 left out (pushing would duplicate them). Run /catch-up or ask me to link them first.`)),g.length>0&&console.log(H(En(g.length))),i.length===0&&g.length>0)return console.log(y("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(l){return console.log(N(`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(G("\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(()=>eb({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 xt(t,i.map(l=>l.path),a,{skipReview:o,skipStyle:r})}return{kind:"forward-to-agent",prompt:hl(s),display:`/push ${s}`}}ee();import{select as fb}from"@inquirer/prompts";import{computeSyncStatus as mb,localAheadPaths as gb,pendingDrafts as yb,publishArticleLive as wb,publishGateVerdict as kb,publishGateLines as bb,resolveActiveProfile as wE,SKIP_STYLE_FLAG as $b}from"document360-engine";var hb={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."},kh=new Set;function Ft(e){let t=hb[e.replace(/^\//,"")];return!t||kh.has(e)?null:(kh.add(e),t)}var vb=150,xb=e=>e>0?new Promise(t=>setTimeout(t,e)):Promise.resolve(),$l=e=>e===1?"":"s",bl=e=>e.replace(/\\/g,"/").split("/").pop()??e;function vl(e){return e.includes("--screenshots")||e.includes("--shots")||e[0]==="--related"}async function xl(e,t,n){await mb({cwd:e,profileName:t});let o=n?n.replace(/\\/g,"/").replace(/\/+$/,""):null;return yb(e,t).filter(r=>!o||r.path===o||r.path.startsWith(`${o}/`)).map(r=>({...r,label:r.path}))}function Cb(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 Cl(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=gb(e,t).filter(a=>!s||a===s||a.startsWith(`${s}/`)).length;return i>0&&r.push(`${i} article${$l(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 Rl(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 wb({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 xb(vb)}return r}function Sl(e){let{published:t,blocked:n,failed:o}=e,r=[];if(t.length>0){r.push(`\u2713 ${t.length} article${$l(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 ${bl(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 ${bl(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 bh(e,t){let n=t?.cwd??process.cwd(),o=Ft("publish");if(vl(e))return o&&console.log(y(`\u2192 ${o}`)),console.log(y("Running /push\u2026")),oi(e,t);let r=Ue(n,t?.profileName);if(!r.ok)return console.log(N(r.reason)),{kind:"continue"};o&&console.log(y(`\u2192 ${o}`));let s=e.includes(it),i=e.includes($b),a=e.includes("--all"),l=e.find(P=>!P.startsWith("--"));console.log(y("Checking what is waiting to go live\u2026"));let p;try{p=await xl(n,t?.profileName,l)}catch(P){return console.log(N(`Could not check Document360: ${P.message}`)),{kind:"continue"}}if(p.length===0){for(let P of Cl(n,t?.profileName,l).lines)console.log(P.startsWith("\u2713")?G(P):y(P));return{kind:"continue"}}let g=kb(n,p.map(P=>P.path),{allowUnreviewed:s,allowStyleErrors:i});if(!g.clear){for(let P of bb(g,p.length,l))console.log(H(P));return{kind:"continue"}}console.log(""),console.log(`${p.length} draft${$l(p.length)} ${p.length===1?"is":"are"} ahead of what readers see:`);for(let P of Cb(p.slice(0,12)))console.log(y(P));p.length>12&&console.log(y(` \u2026and ${p.length-12} more`)),console.log("");let k=p;if(!a){let P=await fb({message:"Publish live to your readers?",choices:[{name:`Yes \u2014 publish all ${p.length} live`,value:"all"},...p.slice(0,8).map(S=>({name:`Just ${S.label}`,value:S.path})),{name:"No \u2014 leave them as drafts",value:"none"}]});if(P==="none")return console.log(y("Left as drafts. Nothing changed.")),{kind:"continue"};P!=="all"&&(k=p.filter(S=>S.path===P))}let v=await Rl(n,t?.profileName,k,{skipReview:s,skipStyle:i,onProgress:(P,S,C)=>console.log(y(` \u25B8 ${P+1}/${S} ${bl(C)}\u2026`))});console.log("");for(let P of Sl(v))console.log(P.startsWith("\u2713")?G(P):P.startsWith("\u2717")?H(P):y(P));return{kind:"continue"}}async function br(){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(`
|
|
356
|
+
`),display:"/audit"}}ee();import{readProjectConfig as Rb}from"document360-engine";function Pl(){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(`
|
|
357
|
+
`)}async function $h(e,t){let n=t?.cwd??process.cwd();return Rb(n)?{kind:"forward-to-agent",prompt:Pl(),display:"/discover"}:(console.log(N("No d360-writer config here. Run /init first.")),{kind:"continue"})}ee();import{checkbox as Sb}from"@inquirer/prompts";import{inventoryRepo as Pb,readProjectConfig as vh,writeProjectConfig as Tb}from"document360-engine";function Tl(e,t){let n=vh(e);n&&(n.authoritativeSourceFiles=t,Tb(n,e))}function ri(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 xh(e,t){let n=t?.cwd??process.cwd();if(!vh(n))return console.log(N("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=Pb(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(K("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${y(ri(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>Sb({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${ri(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"};Tl(n,r),console.log(G(`\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"}}ee();import{confirm as Ob}from"@inquirer/prompts";import{applyPull as Dl,computeSyncStatus as jh,compareRemoteSources as _b,planPull as Ih,planImport as Mb,applyImport as Fb,establishBaselines as Wb,rebaselineServerMeta as Ub,D360AuthError as Bb}from"document360-engine";ee();var Ch=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /push <path>):",paint:N,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /push <path>:",paint:H,mark:"M"},{status:"remote-ahead",header:"Changed on Document360 \u2014 pull with /pull <path> (or just /pull):",paint:K,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:N,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:N,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 Eb(e){return e.path?e.path:`${e.title??"(untitled)"} ${$e(`[${e.articleId}]`)}`}function Ab(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 si(e,t){let n=[],o=e.entries.filter(g=>g.link);if(o.length>0){n.push(""),n.push(We("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let g of o)n.push(` ${H("~")} ${H(g.path??"")} ${$e(`\u2192 "${g.link.title}"`)}`)}for(let g of Ch){let k=e.entries.filter(v=>v.status===g.status&&!(g.status==="untracked-local"&&v.link));if(k.length!==0){n.push(""),n.push(We(g.header));for(let v of k)n.push(` ${g.paint(g.mark)} ${g.paint(Eb(v))}${v.detail?$e(` (${v.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?G("\u2713 everything up to date"):[r>0?G(`\u2713 ${r} up to date`):null,a>0?`${a} to link`:null,...Ch.map(g=>{let k=(e.counts[g.status]??0)-(g.status==="untracked-local"?a:0);return k>0?`${k} ${i[g.status]}`:null})].filter(Boolean).join($e(" \xB7 ")),p=t!==void 0?` \xB7 synced in ${Ab(t)}`:"";return n.push(l+$e(` \xB7 ${s} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${p}`)),n}import{structuredPatch as Db}from"diff";import Rh from"picocolors";var Sh=80,Nb="\x1B[48;2;74;28;28m",jb="\x1B[48;2;24;66;24m",Ph="\x1B[49m",El=e=>String(e).padStart(5);function Th(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}function Eh(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 at(e,t,n){let o=v=>{let P=v.replace(/\r\n/g,`
|
|
358
|
+
`);return P.endsWith(`
|
|
359
|
+
`)||P===""?P:P+`
|
|
360
|
+
`},r=o(e),s=o(t);if(r===s)return null;let i=Math.max(20,n-10),a=Db("a","b",r,s,"","",{context:3}),l=0,p=0,g=[];a.hunks.forEach((v,P)=>{P>0&&g.push(Rh.gray(" \u2026"));let S=v.oldStart,C=v.newStart,T=[],D=[],I=()=>{for(let O=0;O<T.length;O++){let Y=O<D.length?Th(T[O],D[O]):void 0;p++,g.push(`${Nb}${El(S++)} - ${Eh(T[O],i,Y)}${Ph}`)}for(let O=0;O<D.length;O++){let Y=O<T.length?Th(T[O],D[O]):void 0;l++,g.push(`${jb}${El(C++)} + ${Eh(D[O],i,Y)}${Ph}`)}T=[],D=[]};for(let O of v.lines){let Y=O[0],fe=O.slice(1);Y==="-"?T.push(fe):Y==="+"?D.push(fe):(I(),g.push(Rh.gray(El(C))+" "+fe.slice(0,i)),S++,C++)}I()});let k=g.slice(0,Sh);return{added:l,removed:p,lines:k,hidden:Math.max(0,g.length-Sh)}}ee();import{select as Ib}from"@inquirer/prompts";import{applyPull as Dh,computeSyncStatus as Lb,planPull as Ah}from"document360-engine";var ii=e=>e===1?"":"s";async function Al(e,t,n=1){console.log(""),console.log(`${K("\u25CF")} ${We(t.title)} ${$e(`(${t.path})`)}`);for(let i of t.notes)console.log(H(` \u26A0 ${i}`));let o=at(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${ii(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(()=>Ib({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"?(Dh({cwd:e.cwd,profileName:e.profileName},t),console.log(G(" \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 Nh(e,t){let n=Ue(t.cwd,t.profileName);if(!n.ok)return console.log(N(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let s=(await Lb({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(G(`${o} isn't in conflict \u2014 nothing to resolve.`)),{kind:"continue"};s=[o]}if(s.length===0)return console.log(G("\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 Ah({cwd:t.cwd,profileName:t.profileName,relPath:l}),g=await Al(t,p,s.length-a);if(g==="keep-local"&&i.push(l),!g.endsWith("-all"))continue;let k=s.slice(a);if(g==="keep-local-all")i.push(...k),console.log(y(` Keeping local for all ${k.length} \u2014 publishing them over the portal.`));else if(g==="took-portal-all"){let v=0;for(let P of k)try{Dh({cwd:t.cwd,profileName:t.profileName},await Ah({cwd:t.cwd,profileName:t.profileName,relPath:P})),v++}catch(S){console.log(N(` \u2717 ${P}: ${S.message}`))}console.log(G(` \u2713 Took the portal copy of ${v} article${ii(v)} (local overwritten, sync base advanced).`))}else console.log(y(` Skipped all ${k.length} \u2014 still conflict${ii(k.length)}.`));break}if(i.length>0)return console.log(y(`Publishing ${i.length} kept-local article${ii(i.length)} over the portal\u2026`)),await xt(t,i)}catch(r){console.log(N(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function Lh(e,t){let n=Ue(t.cwd,t.profileName);if(!n.ok)return console.log(N(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await Hb(t),{kind:"continue"};if(o==="--baseline")return await qb(t,e.filter(i=>i!=="--baseline")),{kind:"continue"};if(o==="--compare")return await Gb(t),{kind:"continue"};if(o)return console.log(N(`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 Vb(t,r),{kind:"continue"};console.log(y("Pulling changes from Document360\u2026"));let s=await Nl({cwd:t.cwd,profileName:t.profileName});for(let i of jl(s))console.log(i.tone==="ok"?G(i.text):i.tone==="warn"?H(i.text):y(i.text));console.log("")}catch(r){r instanceof Bb?console.log(N(r.message)):console.log(N(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function Nl(e){let t=await jh({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 Ih({cwd:e.cwd,profileName:e.profileName,relPath:o.path});Dl({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 Mb({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});Fb({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 ai=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Dn=e=>e===1?"":"s";function jl(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${Dn(e.pulled.length)} into local: ${ai(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${Dn(e.imported.length)}: ${ai(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${Dn(e.toPublish)} changed locally \u2014 /push saves them to Document360.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${Dn(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). (${ai(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${Dn(e.failed.length)} failed: ${ai(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 Hb(e){console.log(y("Checking Document360 for drift\u2026"));let t=Date.now(),n=await jh({cwd:e.cwd,profileName:e.profileName});for(let o of si(n,Date.now()-t))console.log(o);console.log("")}async function qb(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 Wb({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await Ub({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(G("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(G(`\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(G(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(H(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(y(` - ${s.path} (${s.reason})`))}}async function Gb(e){console.log(y("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await _b({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${We(String(t.legacyCount))} \xB7 Manifest: ${We(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(G("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(N(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(H(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(H(` ${t.onlyInManifest.length} only in the manifest: ${t.onlyInManifest.slice(0,5).join(", ")}`)),console.log(y(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function Vb(e,t){let n=t.replace(/\\/g,"/"),o=await Ih({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await Al(e,o)==="keep-local"&&(console.log(y(`Publishing ${o.path} over the portal\u2026`)),await xt(e,[o.path]));return}console.log(""),console.log(`${K("\u25CF")} ${We(o.title)} ${$e(`(${o.path})`)}`);for(let i of o.notes)console.log(H(` \u26A0 ${i}`));let r=at(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.")),Dl({cwd:e.cwd,profileName:e.profileName},o);return}console.log($e(` \u23BF Added ${r.added} line${Dn(r.added)}, removed ${r.removed} line${Dn(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(()=>Ob({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(y(" Skipped."));return}Dl({cwd:e.cwd,profileName:e.profileName},o),console.log(G(` \u2713 Pulled ${o.path} (sync base advanced).`))}ee();import{statSync as Yb}from"node:fs";import{resolve as Kb}from"node:path";import{estimateBulkCost as zb,planPartitions as Xb,readProjectConfig as Qb,resolveModelForOperation as Jb,runPartitioned as Zb,trackedArticlePaths as e$}from"document360-engine";var Il=3;function Ll(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 Ol(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function _l(e,t){return t.map(n=>{let o=0;try{o=Yb(Kb(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function Ml(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
361
|
- 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.
|
|
362
362
|
- 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.
|
|
363
363
|
- 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.
|
|
364
364
|
- Work only on these files:
|
|
365
365
|
`+e.paths.map(t=>`- ${t}`).join(`
|
|
366
|
-
`)}function
|
|
366
|
+
`)}function Fl(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: ${Ze(r)}\u2013${Ze(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function Wl(e,t,n){let o=S=>t[S.index]?.paths.length??0,r=e.filter(S=>S.ok),s=e.filter(S=>!S.ok),i=e.reduce((S,C)=>S+o(C),0),a=r.reduce((S,C)=>S+o(C),0),l=e.reduce((S,C)=>S+C.costUsd,0),p=e.reduce((S,C)=>S+C.outputTokens,0),g=n==="api"?`${Ze(l)} total`:rn(p),k=`${r.length}/${e.length} batch${e.length===1?"":"es"} completed`,v=S=>`${S} article${S===1?"":"s"}`,P=[];if(s.length===0)P.push(`Converted ${v(i)} (${k}) successfully \xB7 ${g}.`);else{P.push(`Converted ${a}/${v(i)} (${k}) \xB7 ${g}.`),P.push(`${s.length} batch${s.length===1?"":"es"} failed \u2014 re-run /convert to retry:`);for(let S of s)P.push(` \u2717 ${S.label}${S.error?` \u2014 ${S.error}`:""}`)}return P}async function Oh(e,t){if(!Qb(t.cwd))return console.log(N("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=Ll(e),r=e$(t.cwd,t.profileName);if(r.length===0)return console.log(N("No tracked articles in d360-category-map.json. Save some to Document360 first (/push), then /convert.")),{kind:"continue"};let s=Ol(r,n);if(s.length===0)return console.log(N(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let i=Xb(s),a=`/convert${n?` --scope ${n}`:""} --run`,{model:l,forced:p}=Jb(t.cwd,"light");if(!o){let g=zb({files:_l(t.cwd,s),op:"convert",model:l});n&&console.log(y(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let k of Fl(i,g,Il))console.log(k);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${Il} 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 g of Zb({cwd:t.cwd,partitions:i,promptFor:Ml,concurrency:Il,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:l}))if(g.type==="partition_status")g.status==="running"?console.log(y(` \u25B8 ${g.label} \u2014 converting\u2026`)):g.status==="done"?console.log(G(` \u2713 ${g.label}`)):console.log(N(` \u2717 ${g.label}`));else if(g.type==="run_done"){console.log("");let k=process.env.ANTHROPIC_API_KEY?"api":"subscription",v=$t(g,"The conversion");for(let P of v??Wl(g.results,i,k))console.log(v||!g.ok?H(P):G(P))}}catch(g){console.log(N(`Convert run failed: ${g.message}`))}return console.log(""),{kind:"continue"}}import{statSync as Xh}from"node:fs";import{resolve as Qh}from"node:path";import{estimateBulkCost as $$,lintDocs as v$,planFindingPartitions as x$,planPartitions as C$,readDocsPlan as R$,readProjectConfig as Jh,DEFAULT_DOCS_DIR as S$,resolveModelForOperation as Yh,runPartitioned as Kh,stampArticles as zh,CONTENT_CAP_VERSION as P$}from"document360-engine";ee();import{lintDocs as Bh,guidanceForRules as n$,planFindingPartitions as o$,runPartitioned as r$,resolveModelForOperation as s$,stampArticles as i$}from"document360-engine";import{CONTENT_CAP_VERSION as _h}from"document360-engine";function Mh(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 Fh(e){return e.trim().split(/\s+/).slice(1).find(t=>!t.startsWith("--"))}function Ye(e){return e==="review"?{reviewedCap:_h}:{checkedCap:_h}}var t$=e=>"ruleId"in e,li=e=>t$(e)?e.severity:"warning",ko=e=>e===1?"":"s";function Ul(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 $r(e){let{cwd:t,after:n,scope:o,aborted:r}=e,s=n.filter(v=>li(v)==="error").length,i=n.filter(v=>li(v)==="warning").length,a=n.filter(v=>li(v)==="suggestion").length,l=Ne("/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 v=new Set(n.filter(P=>li(P)==="error").map(P=>P.path)).size;return{text:`${s} error${ko(s)} in ${v} article${ko(v)} 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${ko(i)} and ${a} suggestion${ko(a)} remain (neither blocks publishing). `:i>0?`${i} warning${ko(i)} remain${i===1?"s":""}, which ${i===1?"does":"do"} not block publishing. `:a>0?`${a} suggestion${ko(a)} remain${a===1?"s":""} \u2014 ${a===1?"it is":"they are"} judgment calls and ${a===1?"does":"do"} not block publishing. `:"",g=p===""?"\u2713 Nothing left to fix. ":`\u2713 ${p}`,k=o?"/push":"/push --all";return Ct(t,{text:`${g}Nothing is blocking${o?` in ${o}`:""} \u2014 ${k} saves the articles to Document360 as drafts.`,cmd:k},g,o)}var ui={error:0,warning:1,suggestion:2},a$={error:"\u2717",warning:"\u26A0",suggestion:"\xB7"},l$=10,c$=8,u$=96,Wh=34,jn=e=>"ruleId"in e,Nn=e=>jn(e)?e.severity:"warning",Hl=e=>jn(e)?e.ruleId:e.kind;function Bl(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function ci(e){let t={error:0,warning:0,suggestion:0};for(let n of e)t[Nn(n)]++;return t}function Uh(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 vr(e,t={}){let n=t.baselined?[]:e.filter(k=>jn(k)&&k.baselined),o=t.baselined?e:e.filter(k=>!(jn(k)&&k.baselined)),r=n.length>0?[ke("\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[ke("\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 k of o){let v=s.get(k.path)??[];v.push(k),s.set(k.path,v)}let i=ci(o),a=[ke("\u26A0",`${o.length} issue${o.length===1?"":"s"} in ${s.size} article${s.size===1?"":"s"} \u2014 ${Uh(i)}.`),""],l=[...s.entries()].sort((k,v)=>{let P=ci(k[1]);return ci(v[1]).error-P.error||v[1].length-k[1].length||k[0].localeCompare(v[0])}),p=t.full?l:l.slice(0,l$);for(let[k,v]of p){a.push(` ${k} ${y(Uh(ci(v)))}`);let P=new Map;for(let D of v){let I=Hl(D),O=P.get(I)??[];O.push(D),P.set(I,O)}let S=[...P.entries()].sort((D,I)=>ui[Nn(D[1][0])]-ui[Nn(I[1][0])]||I[1].length-D[1].length||D[0].localeCompare(I[0])),C=t.full?S:S.slice(0,c$);for(let[D,I]of C){let O=[...I].sort((ue,Te)=>ue.line-Te.line),Y=a$[Nn(O[0])],ae=new Set(O.map(ue=>ue.term)).size===1?` ${Bl(`"${O[0].term}"`,Wh)}`:"",le=O.length>1?y(` \xD7${O.length}`):"",he=t.full?O[0].message:Bl(O[0].message,u$);a.push(` ${Y} ${D}${le}${ae}`),a.push(` ${y(he)}`);let ce=O.map(ue=>ae?`L${ue.line}`:`L${ue.line} ${Bl(`"${ue.term}"`,Wh)}`),X=t.full?ce:ce.slice(0,12),ne=ce.length-X.length;a.push(` ${y(X.join(", ")+(ne>0?` \u2026+${ne}`:""))}`)}let T=S.length-C.length;T>0&&a.push(y(` \u2026${T} more rule${T===1?"":"s"} fired here (/lint ${k} --full)`)),a.push("")}let g=l.length-p.length;return g>0&&(a.push(y(` \u2026and ${g} more article${g===1?"":"s"} (/lint <category> narrows \xB7 /lint --full lists every one)`)),a.push("")),a.push(...r),a}var d$=200;function di(e){let n=[...e.filter(l=>!(jn(l)&&l.baselined))].sort((l,p)=>ui[Nn(l)]-ui[Nn(p)]||l.path.localeCompare(p.path)||l.line-p.line),o=n.slice(0,d$),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(g=>` - L${g.line} [${Hl(g)}] (${Nn(g)}): "${g.term}": ${g.message}`)].join(`
|
|
367
367
|
`)).join(`
|
|
368
|
-
`),a=
|
|
369
|
-
`)}var
|
|
368
|
+
`),a=n$(o.map(l=>({id:Hl(l),message:l.message,link:jn(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(`
|
|
369
|
+
`)}var bo=3;function ql(e,t,n){let o=n.filter(a=>!(jn(a)&&a.baselined));if(o.length===0)return null;let r=t.find(a=>!a.startsWith("--")),s=`/lint${r?` ${r}`:""} --fix`,i=o$(o);return i.length<=1?{kind:"single",prompt:di(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 di(o.filter(p=>l.has(p.path)))}}}async function p$(e,t,n){let{model:o}=s$(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${bo} at once) on ${o}\u2026`));let r=[];try{for await(let a of r$({cwd:e.cwd,partitions:t.partitions,promptFor:t.promptFor,concurrency:bo,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(G(` \u2713 ${a.label}`)):console.log(N(` \u2717 ${a.label}`));else if(a.type==="run_done"){let l=a.results.filter(p=>!p.ok);if(l.length&&console.log(H(`\u26A0 ${l.length} batch${l.length===1?"":"es"} not fixed: ${l.map(p=>p.label).join(", ")}`)),a.blocked&&console.log(H(`\u26A0 ${a.blocked}`)),a.allEmpty&&console.log(H("\u26A0 No turn produced any work this run \u2014 nothing was changed.")),!a.allEmpty&&!a.blocked){let p=new Set(l.map(g=>g.label));r.push(...t.partitions.filter(g=>!p.has(g.label)).flatMap(g=>g.paths))}}}catch(a){return console.log(N(`Fix run failed: ${a.message}`)),{kind:"continue"}}if(r.length>0)try{i$(e.cwd,r,Ye("lint"))}catch{}let s=Bh({cwd:e.cwd,scope:n}).filter(a=>!a.baselined);console.log("");for(let a of vr(s))console.log(s.length===0?G(a):H(a));let i=$r({cwd:e.cwd,after:s,before:t.findings,scope:n});return console.log(""),console.log(y(i.text)),{kind:"continue",ownNext:!0}}async function Gl(e,t){let n=e.includes("--fix"),o=e.find(i=>!i.startsWith("--")),r=o?` ${o}`:"",s=Bh({cwd:t.cwd,scope:o});if(n){let i=ql(t.cwd,e,s);return i?i.kind==="partitioned"?p$(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(G("\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 vr(s,{full:e.includes("--full"),baselined:e.includes("--baselined")}))console.log(s.length===0?G(i):H(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 Hh=async(e,t)=>{let n=Ft("check");return n&&console.log(y(`\u2192 ${n}`)),Gl(e,t)};ee();import{readProjectConfig as h$,loadProfileMap as f$,resolveActiveProfile as m$,desiredCategoryOrder as g$,desiredArticleOrder as y$,DEFAULT_DOCS_DIR as w$}from"document360-engine";var Vl=e=>e.replace(/\\/g,"/"),qh=e=>Vl(e).split("/").pop()??e;function Yl(e){let t=qh(e),n=t.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return n?n.charAt(0).toUpperCase()+n.slice(1):t}var k$=Yl;function xr(e,t){try{let n=h$(e);if(!n)return[];let o=m$(e,t),r=f$(e,o.name);if(!r)return[];let s=Vl(n.docsDir??w$).replace(/\/+$/,""),i=new Map;for(let l of y$(r))i.set(l.categoryPath,(i.get(l.categoryPath)??0)+1);let a=[];for(let l of g$(r)){let p=Vl(l.path),g=p.startsWith(`${s}/`)?p.slice(s.length+1):p===s?"":p;g&&a.push({token:g,label:k$(qh(p)),count:i.get(l.path)??0})}return a}catch{return[]}}function Gh(e,t){let n=xr(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 ln(e,t){if(t.includes("--all")||t.includes("--blocked")||t.some(n=>n.startsWith("--scope="))||t.includes("--scope")&&!Cr(t))return!1;for(let n=0;n<t.length;n++){let o=t[n];if(o.startsWith("--")){b$.has(o)&&n++;continue}return!1}return e==="write"?!t.includes("--preview")&&!t.includes("--dry-run"):e==="review"||e==="reorder"}var b$=new Set(["--scope","--concurrency"]);function $o(e,t,n,o,r){if(r=r??xr(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,g)=>p+g.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 Cr(e){let t=e.indexOf("--scope");if(t===-1)return!1;let n=e[t+1];return n===void 0||n.startsWith("-")}function Vh(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 T$=3,E$=8;function Kl(e){return e===void 0||!Number.isFinite(e)?T$:Math.max(1,Math.min(Math.floor(e),E$))}function Rr(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 A$(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function D$(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function zl(e,t,n){return n.filter(o=>{try{return Xh(Qh(e,t,o)).size===0}catch{return!0}})}function Xl(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+=Xh(Qh(e,i)).size}catch{}return{path:r,bytes:s}})}function Ql(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.
|
|
370
370
|
`:"";return`Run the write-article skill to author EACH documentation article listed below. For each path:
|
|
371
371
|
- 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).
|
|
372
372
|
- 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).
|
|
@@ -376,136 +376,139 @@ ${a[1]??" "}clipTo: ${l}${i.selector}${l},`);return p=p.replace(o,`${r}await ca
|
|
|
376
376
|
- 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.
|
|
377
377
|
Articles:
|
|
378
378
|
`+e.paths.map(r=>`- ${r}`).join(`
|
|
379
|
-
`)}function
|
|
380
|
-
`)}var
|
|
381
|
-
`)}var
|
|
379
|
+
`)}function Jl(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: ${Ze(r)}\u2013${Ze(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function Zl(e,t,n,o){let r=C=>t[C.index]?.paths.length??0,s=e.filter(C=>C.ok),i=e.filter(C=>!C.ok),a=e.reduce((C,T)=>C+r(T),0),l=s.reduce((C,T)=>C+r(T),0),p=e.reduce((C,T)=>C+T.costUsd,0),g=e.reduce((C,T)=>C+T.outputTokens,0),k=n==="api"?`${Ze(p)} total`:rn(g),v=`${s.length}/${e.length} batch${e.length===1?"":"es"} completed`,P=C=>`${C} article${C===1?"":"s"}`,S=[];if(i.length===0){S.push(`Wrote ${P(a)} (${v}) successfully \xB7 ${k}.`);let C=o?` ${o}`:"",T=o?"/push":"/push --all",D=o?`/screenshot author ${o}`:"/screenshot author --all";S.push("Next \u2014 an editorial review, because these were written by an AI:"),S.push(`/review${C} --fix`),S.push(`It reads every article and applies its fixes; ${T} then pushes them up (add screenshots first with ${D} if you want them).`)}else{S.push(`Wrote ${l}/${P(a)} (${v}) \xB7 ${k}.`),S.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)S.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return S}function Sr(e,t,n){try{return v$({cwd:e,paths:n.map(o=>`${t}/${o}`)}).filter(o=>!o.baselined)}catch{return[]}}function ec(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 tc(e){let t=e.filter(o=>o.severity==="error");if(t.length===0)return null;let n=x$(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 di(t.filter(s=>r.has(s.path)))}}}function nc(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 pi(e,t,n){let o=(Jh(e)?.docsDir??S$).replace(/\/+$/,""),r=t.map(a=>a.path);if(n.path){let a=A$(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=D$(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=zl(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 oc(e,t,n){let{targets:o}=pi(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:Yl(s),count:i}))}async function Zh(e,t){if(!Jh(t.cwd))return console.log(N("No d360-writer config here. Run /init first.")),{kind:"continue"};if(Cr(e)){for(let D of Gh(t.cwd,t.profileName))console.log(y(D));return{kind:"continue"}}let n=R$(t.cwd);if(n.length===0)return console.log(N("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};if(ln("write",e)){let D=oc(t.cwd,n,{rewrite:Rr(e).rewrite}),I=$o(t.cwd,"write",e,t.profileName,D);if(I.length>0){for(let O of I)console.log(y(O));return{kind:"continue"}}}let{scope:o,path:r,preview:s,concurrency:i,rewrite:a}=Rr(e),{docsDir:l,targets:p,reason:g,rewriting:k}=pi(t.cwd,n,{scope:o,path:r,rewrite:a});if(p.length===0)return console.log(g?H(g):H("Nothing to write.")),{kind:"continue"};k&&console.log(H(`--rewrite: regenerating ${p.length} already-written article${p.length===1?"":"s"} (overwrites them; git has your baseline).`));let v=C$(p),P=Kl(i),{model:S,forced:C}=Yh(t.cwd,"standard"),T=!!r;if(s&&!T){let D=$$({files:Xl(t.cwd,n,p),op:"write",model:S});o&&console.log(y(`Scope: ${o} (${p.length} pending).`));for(let I of Jl(v,D,P))console.log(I);return console.log(y(`Model: ${S}${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 ${v.length} batch${v.length===1?"":"es"} (\u2264${P} agents at once) on ${S}\u2026`)),console.log(y(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let D of Kh({cwd:t.cwd,partitions:v,promptFor:I=>Ql(I,l,{rewrite:k||T}),concurrency:P,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:S}))if(D.type==="partition_status")D.status==="running"?console.log(y(` \u25B8 ${D.label} \u2014 writing\u2026`)):D.status==="done"?console.log(G(` \u2713 ${D.label}`)):console.log(N(` \u2717 ${D.label}`));else if(D.type==="run_done"){console.log("");let I=process.env.ANTHROPIC_API_KEY?"api":"subscription",O=$t(D,"The write");if(O){for(let le of O)console.log(H(le));continue}for(let le of Zl(D.results,v,I,o??r))console.log(D.ok?G(le):H(le));if(D.ok)try{zh(t.cwd,p.map(le=>`${l}/${le}`),{writtenCap:P$,reviewedCap:0,checkedCap:0})}catch{}let Y=Sr(t.cwd,l,p),fe=ec(Y);fe&&console.log(H(fe));let ae=e.includes("--skip-style")?null:tc(Y);if(ae){console.log(y(`Fixing ${ae.errors.length} style error(s) in ${ae.articles} article(s) \u2014 one pass\u2026`));let{model:le}=Yh(t.cwd,"standard"),he=[];try{for await(let ce of Kh({cwd:t.cwd,partitions:ae.partitions,promptFor:ae.promptFor,concurrency:3,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:le}))if(ce.type==="partition_status"&&ce.status!=="running")console.log(ce.status==="done"?G(` \u2713 ${ce.label}`):N(` \u2717 ${ce.label}`));else if(ce.type==="run_done"&&!ce.allEmpty&&!ce.blocked){let X=new Set(ce.results.filter(ne=>!ne.ok).map(ne=>ne.label));he.push(...ae.partitions.filter(ne=>!X.has(ne.label)).flatMap(ne=>ne.paths))}}catch(ce){console.log(H(`Style fix pass failed: ${ce.message}`))}if(he.length>0)try{zh(t.cwd,he,Ye("lint"))}catch{}for(let ce of nc(ae.errors.length,Sr(t.cwd,l,p)))console.log(ce.startsWith("\u2713")?G(ce):H(ce))}}}catch(D){console.log(N(`Write run failed: ${D.message}`))}return console.log(""),{kind:"continue"}}ee();import{existsSync as N$,readdirSync as ef,statSync as tf}from"node:fs";import{join as nf}from"node:path";import{inputDir as j$,readProjectConfig as I$}from"document360-engine";var of=/\.(md|markdown|pdf|txt)$/i;function rc(e){let t=j$(e);if(!N$(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of ef(t)){let s=nf(t,r),i=!1;try{i=tf(s).isDirectory()}catch{continue}if(i){if(r.startsWith("."))continue;let a=L$(s);a>0&&n.push({name:r,docCount:a})}else of.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function L$(e){let t=0;for(let n of ef(e))try{tf(nf(e,n)).isFile()&&of.test(n)&&t++}catch{}return t}function sc(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 hi(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(`
|
|
380
|
+
`)}var ic="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function rf(e,t){let n=t?.cwd??process.cwd();if(!I$(n))return console.log(N("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=rc(n);if(o.length===0&&r===0)return console.log(y(ic)),{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:hi(a),display:a?`/draft ${a}`:"/draft"}}let i=sc(o,s);return{kind:"forward-to-agent",prompt:hi(i??"",i?void 0:s),display:`/draft ${s}`}}ee();import{listOpenForDocs as O$,readProjectConfig as _$}from"document360-engine";function ac(e){try{return O$(e).filter(t=>t.kind==="request").length}catch{return 0}}function lc(e){let t=e.includes("--push")||e.includes("--publish"),n=e.includes(it),o=e.filter(r=>!r.startsWith("--")).join(" ").trim();return{push:t,skipReview:n,what:o}}function cc(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(`
|
|
381
|
+
`)}var uc="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 sf(e,t){let n=t?.cwd??process.cwd();if(!_$(n))return console.log(N("No d360-writer config here. Run /init first.")),{kind:"continue"};let{push:o,what:r}=lc(e);if(!r&&ac(n)===0)return console.log(y(uc)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --push":""}`;return{kind:"forward-to-agent",prompt:cc(r),display:s}}ee();import{search as M$}from"@inquirer/prompts";import{findByName as F$,getSession as W$,listSessions as U$,relativeTime as lf}from"document360-engine";async function cf(e,t){let n=U$(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=F$(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(N(`No session matches "${o}".`)),af(n),{kind:"continue"})}if(!process.stdin.isTTY)return af(n),console.log(y("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>M$({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} ${lf(a.updatedAt)}`,value:a.uuid,description:a.firstPrompt.slice(0,100)}))}})),r=W$(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function af(e){console.log("");for(let t of e.slice(0,15))console.log(` ${K(t.name)} ${y(lf(t.updatedAt))}`),console.log(` ${y(t.firstPrompt.slice(0,80))}`);console.log("")}ee();import{renameSession as B$}from"document360-engine";function dc(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 uf(e,t){let n=dc(e.join(" "));if(!n)return console.log(N("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(B$(o,n)?console.log(G(`\u2713 Session renamed to "${n}"`)):console.log(N("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(G(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as df,readProjectConfig as H$,writeProjectConfig as q$}from"document360-engine";ee();function pc(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=H$(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 df().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},q$(o,e),null):`Unknown environment "${r}". Known: ${df().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function pf(e,t){let n=e[0];if(!n)return vs(t.cwd),{kind:"continue"};if(n==="add"){let o=pc(t.cwd,e[1],e[2]);return o?(console.log(N(o)),{kind:"continue"}):(console.log(G(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${K(`/profile ${e[1]}`)} then ${K("/login")}`),console.log(y(" Until you switch, this repo keeps using the current profile\u2019s environment.")),{kind:"continue"})}return xs(t.cwd,n),Cs(t.cwd,n),console.log(y(" Restarting agent for the new profile\u2026")),{kind:"clear"}}ee();import{select as G$}from"@inquirer/prompts";import{readProjectConfig as V$,readUserConfig as hf,resolveModelSetting as hc,writeUserConfig as ff}from"document360-engine";var Rt=[{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 fi(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=Rt.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function Y$(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 Pr(e,t){let n=()=>hc(e).model;if(t==="default"){let s=hf();return s.defaultModel?(delete s.defaultModel,ff(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${hc(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}}ff({...hf(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=V$(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 mf(e,t){let n=e[0]?.trim();if(!n){let i=hc(t.cwd);if(!process.stdin.isTTY)return console.log(`${We("Model:")} ${K(i.model)}${i.source==="auto"?y(" (auto)"):""}`),console.log(y(` source: ${Y$(i)}`)),console.log(y(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let a=fi(i),l;try{l=await t.withPausedInput(()=>G$({message:`Select model (current: ${i.model}${i.source==="auto"?" \xB7 auto":""})`,default:Rt[a].value,choices:Rt.map((v,P)=>({name:`${v.label}${P===a?" \u2714":""}`,value:v.value,description:v.desc}))}))}catch{return console.log(y("Cancelled.")),{kind:"continue"}}let{lines:p,changed:g,effective:k}=Pr(t.cwd,l??"default");for(let v of p)console.log(v.startsWith("\u26A0")?H(v):v.startsWith("\u2713")?G(v):y(v));return g&&await t.setModel(k),{kind:"continue"}}let{lines:o,changed:r,effective:s}=Pr(t.cwd,n);for(let i of o)console.log(i.startsWith("\u26A0")?H(i):i.startsWith("\u2713")?G(i):y(i));return r&&await t.setModel(s),{kind:"continue"}}mi();async function $f(e,t){return await t.withPausedInput(()=>io(t.cwd)),{kind:"clear"}}async function vf(e,t){return await t.withPausedInput(()=>ws(t.cwd,t.profileName)),{kind:"clear"}}ee();import{resolveActiveProfile as pv}from"document360-engine";async function xf(e,t){let n=!1;try{n=pv(t.cwd).production}catch{}return n?(console.log(H("\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"})}ee();var Cf=async(e,t)=>{try{await t.withPausedInput(()=>$s({}))}catch(n){console.log(N(`Login failed: ${n.message}`))}return{kind:"continue"}};import{resolveActiveProfile as hv,clearTokens as fv,clearProfileProject as mv}from"document360-engine";ee();async function Rf(e,t){let n,o;try{let i=hv(t.cwd,t.profileName);n=i.name,o=i.connection.name}catch(i){return console.log(N(i.message)),{kind:"continue"}}let r=fv(n);mv(t.cwd,n),console.log(r?G(`\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=Zt(t.cwd,t.profileName);return console.log(s?H(`\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 Pf}from"node:child_process";import{existsSync as gc,readFileSync as mc,statSync as xv}from"node:fs";import{homedir as Cv}from"node:os";import{basename as Rv,join as Nr}from"node:path";import{readProjectConfig as Sv,DEFAULT_OUTPUT_DIR as Pv,existingAnnotatedShotPath as Tv,resolveOutputDir as Ev}from"document360-engine";import et from"picocolors";import{annotationsPath as gv,resolveOutputDir as yv,readProjectConfig as wv,DEFAULT_OUTPUT_DIR as kv,existingAnnotatedShotPath as bv}from"document360-engine";function $v(e){let n=e.filter(o=>o!=="--all"&&o!=="-a").find(o=>!o.startsWith("-"));return n?{mode:"single",id:n}:{mode:"all"}}function Er(e){return e.filter(t=>t.state==="captured").map(t=>t.id)}function In(e,t){let n=yv(e,wv(e)?.outputDir??kv),o=new Map(Ie(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(bv(n,i))}`,` facts: ${r(gv(n,i))}`,` article: ${a}`].join(`
|
|
382
382
|
`)}).join(`
|
|
383
383
|
`);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(`
|
|
384
|
-
`)}function
|
|
385
|
-
`)}function
|
|
386
|
-
`)
|
|
387
|
-
`)}var
|
|
388
|
-
`)}function
|
|
389
|
-
/screenshot list --detail shows what each one needs`}function
|
|
390
|
-
`),cmd:o.length>0?`/screenshot ${a}`:t.length>0?s:i,tone:o.length>0?"warn":"info"}}function
|
|
391
|
-
`),display:"/screenshot checklist"}}var
|
|
392
|
-
`)}async function
|
|
393
|
-
`).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 fi(e,t){let n=Nf(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=kv(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${Dr(o.ahead)} not shared yet \u2014 run /share`}):s.push({tone:"ok",text:re("\u2713")+"Everything is shared with your team."}),s}function wc(e,t,n){Df({...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,...fi(e,{...t,gitHandoff:{commit:!0,push:!0}})]:[o]}async function mi(e,t){let n=[],o=Nf(t);if(!o.commit)return{lines:[{tone:"info",text:an("disabled")}],changed:!1};let r=t;o.push==="unconfirmed"&&$v(e,t)&&(r={...t,gitHandoff:{commit:!0,push:!0}},Df(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 bv(e);if(s.ok&&s.pulled>0){let p=[s.newHints>0?`${s.newHints} new hint${Dr(s.newHints)}`:null,s.newMessages>0?`${s.newMessages} new message${Dr(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")+an(s.reason,s.detail)});let i=await wv(e,r);if(i.commit&&!i.commit.ok)return n.push({tone:"warn",text:re("\u26A0")+an(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${Dr(a)} to the docs folder.`}),i.push&&!i.push.ok)return n.push({tone:"warn",text:re("\u26A0")+an(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${Dr(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 vv={ok:V,info:$e,warn:H,error:j};async function jf(e,t){let n=t.cwd,o=yv(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(vv[l.tone](l.text))};if(r==="status")return s(fi(n,o)),{kind:"continue"};if(r==="on"||r==="off")return s(wc(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(w("Exchanging work with your team\u2026"));let{lines:i}=await mi(n,o);return s(i),{kind:"continue"}}function Nn(e){let t=0,n=0,o=0,r=0;try{t=xv(e).length}catch{}try{let s=Cv(e);n=s.filter(i=>i.kind==="request").length,o=s.filter(i=>i.kind==="answer").length}catch{}try{r=Rv(e).length}catch{}return{hints:t,requests:n,answers:o,directives:r}}async function kc(e){let t=If(e);if(!t)return[];if(!Nv(e,t))return[];let n=await Dv(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 ${an(n.reason,n.detail)}`}]}function Nr(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 $c(e){return{publish:e.includes("--publish"),skipReview:e.includes(_t)}}function vc(e){let t={hold:!1,openQuestions:0,answersPending:0};try{let n=jv(e);return!n||n.status==="confident"?t:{hold:!0,...Iv(e)}}catch{return t}}function xc(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${bo(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${bo(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 Cc(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${bo(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(`
|
|
394
|
-
`)}var
|
|
395
|
-
(Document360 sends the first 500 characters of a highlight)`:`\u201C${n}\u201D`;let o=n.slice(0,
|
|
396
|
-
(+${r} more character${r===1?"":"s"}${e.comment.commented_text_truncated?", and Document360 caps a highlight at 500":""})`}function
|
|
397
|
-
`)]});return o.push(
|
|
398
|
-
`)}function
|
|
399
|
-
`).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function
|
|
400
|
-
|
|
401
|
-
`;
|
|
402
|
-
`,"utf8");let S=Or(e)??{projectId:""};return em({...S,styleGuide:{...S.styleGuide,pulledFrom:{styleGuideId:a.id,name:a.name??a.id,pulledAt:new Date().toISOString(),contentHash:Lx("sha1").update(v).digest("hex").slice(0,16)}}},e),{lines:[be("\u2713",`Pulled "${a.name??a.id}" into .d360-writer/style-guide.md (${v.length.toLocaleString()} characters).`),...y,w(" This is PROSE, not rules \u2014 /review judges against it, and the writer now writes to it."),w(" Turn its mechanical parts into checks: /style-guide compile"),w(" Restarting the agent so it writes to the new guide\u2026")],restart:!0}}function Mx(e){let t=Fc(e).rules.filter(n=>n.pack.toLowerCase()===Lr.toLowerCase()).map(n=>n.id);return{prompt:Sx({guide:Px(e),packName:Lr,existingRuleIds:t}),display:"/style-guide compile"}}function nm(){return[w(` Review what it wrote: git diff .d360-writer/styles/${Lr}/`),w(` Anything it could not check mechanically is listed in .d360-writer/styles/${Lr}/UNCHECKABLE.md \u2014 /review judges those.`),w(` Turn them on when you are happy: /style-guide use ${Lr.toLowerCase()} (they start as warnings, never blocking)`)]}var at=(e,t)=>`${e} ${t}${e===1?"":"s"}`,_c=e=>/^v\d/i.test(e)?e:`v${e}`;function om(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 Fx(e){let n=Or(e)?.styleGuide?.pulledFrom;return n?`.d360-writer/style-guide.md \u2014 pulled ${n.pulledAt.slice(0,10)} from "${n.name}"`:tm(Zf(e))?".d360-writer/style-guide.md (yours)":"the built-in default"}function Wx(e){let t=Or(e),n=Fc(e),o=(t?.styleGuide?.packs??[]).filter(Boolean),r=n.packs.filter(l=>l.name.toLowerCase()===$o),s=n.packs.filter(l=>l.name.toLowerCase()!==$o),i=[`Style guide: ${Fx(e)}`,`Rule packs: ${s.length>0?s.map(l=>`${l.name.toLowerCase()} ${_c(l.version)}`).join(", "):w("none chosen")}`,`Always on: ${w(`d360 (correctness, built in \u2014 ${at($i.length,"rule")})`)}`];for(let l of r)i.push(` ${w(`${l.name.toLowerCase()} ${_c(l.version)} (anti-slop \u2014 ${at(l.ruleCount,"rule")})`)}`);r.length>0&&(i.push(w(" Every article here is machine-written, so these cannot be switched off by")),i.push(w(" choosing another pack. styleGuide.humanise: false turns them off deliberately.")));let a=[...$i.map(l=>({severity:l.severity})),...n.rules.map(l=>({severity:l.severity}))];i.push("",`${at(a.length,"rule")} active \xB7 ${om(a)}`);try{let l=Wc({cwd:e}),p=l.findings.filter(y=>!y.baselined),g=p.filter(y=>y.severity==="error").length;i.push(""),i.push(g===0?be("\u2713",`No style errors across the docs${p.length>0?`, though ${at(p.length,"other issue")} ${p.length===1?"is":"are"} reported`:""}.`):be("\u2717",`${at(g,"style error")} \u2014 /lint shows them, /lint --fix corrects them.`)),l.baselinedCount>0&&i.push(be("\u2139",`${at(l.baselinedCount,"pre-existing issue")} recorded as accepted when a pack was adopted, so they never block.`)),l.ruleErrors.length>0&&i.push(be("\u26A0",`${at(l.ruleErrors.length,"rule")} could not be loaded: ${l.ruleErrors.slice(0,2).map(y=>`${y.ruleId} (${y.reason})`).join("; ")}`))}catch{}return i.push(""),i.push(w(" See them all: /style-guide list \xB7 change: /style-guide use <preset> \xB7 one rule: /style-guide explain <rule>")),i}function Mc(e){let t=Or(e),n=new Set(xx(t?.styleGuide)),o=Jf(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===$o,g=l?"\u2713":"\xB7",y=p?w("(always on)"):l?w("(active)"):"",v=i.local?w(" [yours]"):"";r.push(` ${g} ${a.padEnd(s)}${v} ${i.description??""}`),r.push(` ${w(`${at(i.rules.length,"rule")} \xB7 ${om(i.rules)} \xB7 ${_c(i.version)}`)} ${y}`),i.errors.length>0&&r.push(be("\u26A0",`${at(i.errors.length,"rule")} in this pack could not be loaded \u2014 /style-guide explain names them.`))}return o.every(i=>i.name.toLowerCase()===$o)&&(r.push(""),r.push(w(" The Microsoft and Google style guides are not installed in this build yet."))),r.push(""),r.push(w(" Turn one on: /style-guide use <name> (this replaces the chosen set, it does not add to it)")),r.push(w(" Several: /style-guide use microsoft,google")),r.push(w(" Back to none: /style-guide use none")),r}function Ux(e,t){if(!t)return[be("\u26A0","Name a rule: /style-guide explain Humanise.EmDash")];let n=Fc(e),o=$i.find(p=>p.id.toLowerCase()===t.toLowerCase()),r=n.rules.find(p=>p.id.toLowerCase()===t.toLowerCase());if(!o&&!r){let p=[...$i.map(g=>g.id),...n.rules.map(g=>g.id)].filter(g=>g.toLowerCase().includes(t.toLowerCase())).slice(0,5);return[be("\u26A0",`No active rule called "${t}".`),...p.length>0?[w(` Did you mean: ${p.join(", ")}`)]:[w(" /style-guide list shows the active packs.")]]}let s=o?.id??r.id,i=o?.severity??r.severity,a=o?"built in (correctness \u2014 always on)":`pack: ${r.pack.toLowerCase()}`,l=[`${s} ${i} \xB7 ${a}`,""];l.push(` ${o?.summary??r.message}`),r?.link&&l.push(w(` ${r.link}`)),r?.degraded&&(l.push(""),l.push(be("\u26A0",`This rule is translated approximately: ${r.degraded}. It may match slightly more than the original does.`)));try{let p=Wc({cwd:e}).findings.filter(y=>y.ruleId===s),g=p.filter(y=>!y.baselined);l.push(""),l.push(p.length===0?" Currently: no findings.":` Currently: ${at(g.length,"finding")}${p.length!==g.length?`, plus ${p.length-g.length} baselined and hidden`:""}.`)}catch{}return l.push(""),o?(l.push(w(" Built-in checks are grounded in your product's own source and cannot be switched off \u2014 they")),l.push(w(" catch defects of fact, not matters of taste."))):(l.push(w(` Silence it everywhere: add "${s}": "off" to styleGuide.rules in .d360-writer/config.json`)),i!=="error"&&l.push(w(" Silence one passage: <!-- vale "+s+" = NO --> \u2026 <!-- vale "+s+" = YES -->"))),l}function Bx(e,t){let n=(t??"").trim();if(!n)return{lines:[be("\u26A0","Name the packs to use: /style-guide use microsoft (or `none`)"),...Mc(e)],restart:!1};let o=n.toLowerCase()==="none"?[]:n.split(/[,\s]+/).map(l=>l.trim().toLowerCase()).filter(Boolean),r=new Map(Jf(e).map(l=>[l.name.toLowerCase(),l])),s=o.filter(l=>!r.has(l));if(s.length>0)return{lines:[be("\u2717",`No rule pack named ${s.map(l=>`"${l}"`).join(", ")}.`),"",...Mc(e)],restart:!1};let i=Or(e)??{projectId:""};em({...i,styleGuide:{...i.styleGuide,packs:o}},e),$x();let a=[be("\u2192",`Switching to: ${o.length>0?o.join(", "):"the built-in checks only"}${o.includes($o)?"":` (+ ${$o}, always on)`}\u2026`)];try{let l=Wc({cwd:e}),p=new Set(l.findings.map(g=>g.path)).size;if(l.findings.length===0)a.push(be("\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 g=vx(e),y=kx(l.findings,Rx(e));Cx(e,y),a.push(be("\u2713",`Recorded ${at(l.findings.length,"existing issue")} across ${at(p,"article")} as accepted.`),w(" .d360-writer/style-baseline.json \u2014 commit it. It defines what the publish gate lets through, and a"),w(" teammate with a different copy gets a different answer from the same gate."),be("\u2713","Nothing is blocked today. New writing, and any paragraph you edit, is held to the full set.")),g&&a.push(w(` (Replaced the baseline recorded ${g.createdAt.slice(0,10)}.)`))}}catch(l){a.push(be("\u26A0",`The packs are active, but recording what was already there failed: ${l instanceof Error?l.message:String(l)}`)),a.push(w(" Run /lint to see the current state before publishing."))}return a.push(w(" Restarting the agent so it writes to the new rules\u2026")),{lines:a,restart:!0}}async function vi(e,t){let{sub:n,value:o}=Ox(e),r=s=>{for(let i of s)console.log(i);console.log("")};switch(n){case"list":return r(Mc(t.cwd)),{kind:"continue"};case"explain":return r(Ux(t.cwd,o)),{kind:"continue"};case"use":{let s=Bx(t.cwd,o);return r(s.lines),s.restart?{kind:"clear"}:{kind:"continue"}}case"pull":{let s=await _x(t.cwd,o,t.profileName);return r(s.lines),s.restart?{kind:"clear"}:{kind:"continue"}}case"compile":{let s=Mx(t.cwd);return{kind:"forward-to-agent",prompt:s.prompt,display:s.display}}default:return r(Wx(t.cwd)),{kind:"continue"}}}ee();import{lintDocs as Uc,loadStyleGuide as am,buildReviewPrompt as lm,readProjectConfig as cm,DEFAULT_DOCS_DIR as um,listArticleFiles as dm,planPartitions as Kx,runPartitioned as zx,resolveModelForOperation as Xx,stampArticles as Qx}from"document360-engine";ee();import{readProjectConfig as Hx,loadProfileMap as qx,resolveActiveProfile as Gx,desiredCategoryOrder as Vx,desiredArticleOrder as Yx}from"document360-engine";function rm(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}var sm=e=>e.replace(/\\/g,"/").split("/").pop()??e;function _r(e,t){try{if(!Hx(e))return[];let n=Gx(e,t),o=qx(e,n.name);if(!o)return[];let r=new Map;for(let i of Yx(o)){let a=r.get(i.categoryPath);a?a.push(i):r.set(i.categoryPath,[i])}let s=[];for(let i of Vx(o)){s.push(rm(sm(i.path)));for(let a of(r.get(i.path)??[]).sort((l,p)=>l.order-p.order))s.push(` ${rm(sm(a.path))}`)}return s}catch{return[]}}async function im(e,t){let n=_r(t.cwd,t.profileName);if(n.length===0)return console.log(w("No documentation structure yet \u2014 run /init and author some articles first.")),{kind:"continue"};console.log(K("Documentation order (categories \u2192 articles):"));for(let o of n)console.log(o);return console.log(""),{kind:"continue"}}function Fr(e,t){return gr(e,dm(e,t))}function Jx(e,t,n){return t.includes("--blocked")?Fr(e,n):dm(e,n)}function Zx(e,t){let n=cm(e);if(!n)return null;let o=(n.docsDir??um).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),s=t.includes("--blocked"),i=t.find(A=>!A.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),a=Uc({cwd:e}),l=i?a.filter(A=>A.path===`${o}/${i}`||A.path.startsWith(`${o}/${i}/`)):a,p=s?Fr(e,i):void 0,g=p?l.filter(A=>p.includes(A.path)):l,y=i||s?"":_r(e).join(`
|
|
403
|
-
`);return{prompt:
|
|
404
|
-
`),display:`/reorder${n?` ${n}`:""}`}}async function
|
|
384
|
+
`)}function Ar(e){return`${re("\u2192",et.blue)}Verifying ${e} new screenshot${e===1?"":"s"} (reading each image)\u2026`}var vv=(e,t=88)=>{let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n};function Dr(e,t){if(t.length===0)return[];let n=_t(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",et.green)}${et.green(`${o.length} verified`)}`+(r.length>0?` ${et.magenta(`\u2691 ${r.length} flagged`)}`:"")+(s.length>0?` ${et.yellow(`? ${s.length} not verified`)}`:"")+et.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(` ${et.magenta(p.id.padEnd(a))} ${et.gray(vv(p.reason))}`);let l=r.filter(p=>p.repaired).length;i.push(`${re("\u2192",et.magenta)}Re-capture the ${r.length} flagged: ${et.bold("/screenshot capture --failed")}`+(l<r.length?et.gray(` (${r.length-l} still need${r.length-l===1?"s":""} a spec fix first)`):""))}return s.length>0&&i.push(`${re("\u26A0",et.yellow)}No verdict recorded for ${s.slice(0,3).join(", ")}${s.length>3?`, +${s.length-3}`:""} \u2014 still awaiting verification. Run ${et.bold("/screenshot verify")} again.`),i}async function Sf(e,t){let n=t?.cwd??process.cwd(),o=fr(n);o&&console.log(o);let r=Ie(n),s=$v(e);if(s.mode==="single"){let a=r.find(l=>l.id===s.id);return a?["captured","verified","rejected"].includes(a.state)?{kind:"forward-to-agent",prompt:In(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=Er(r);if(i.length===0){let a=r.filter(p=>p.state==="verified").length,l=r.filter(p=>p.state==="rejected").length;return console.log(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:In(n,i),display:"/screenshot verify"}}var Av=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function yc(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:Av(t),retryBlocked:n}:{mode:"single",id:t}:{mode:"picker"}}function jr(e,t){let n=Ie(e,t),o=r=>n.filter(s=>s.state===r).map(s=>s.id);return{ready:o("spec"),captured:[...o("captured"),...o("verified"),...o("rejected")].sort(),blocked:o("blocked"),broken:o("broken"),rejected:o("rejected"),rows:n}}function Tf(e){let t=e.filter(s=>s.state==="spec"),n=e.filter(s=>s.state==="captured"||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}),Hs(o,t,"capture"),dl(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":" \u25CF to verify \u2014 re-capture";o.push({kind:"shot",action:"capture",label:s.id,ids:[s.id],depth:1,note:i})}return o}function wc(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([...Ap(e).filter(r=>n.has(r)),...o])].sort()}function kc(e,t){let n=e.length;if(n===0)return null;let o=gr(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(`
|
|
385
|
+
`)}function Dv(e,t){let n=Sv(e)?.outputDir??Pv;return Tv(Ev(e,n),t)}function bc(e,t,n,o){let r=Dv(e,t);return gc(r)&&xv(r).mtimeMs>=o?"captured":n===0?"skipped":"failed"}function Ef(e){let t=/⊘[^\n—]*—\s*(.+)/.exec(e);return t?t[1].trim():null}var Nv=/element is not (?:enabled|visible|stable|editable)|intercepts pointer events|outside of the viewport|element is not attached/i;function Af(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=>Nv.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(`
|
|
386
|
+
`):$c(e)}function $c(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(`
|
|
387
|
+
`)}var jv=/^[A-Za-z0-9._-]+$/;function vc(e){return new Promise((t,n)=>{if(!jv.test(e.id)){n(new Error(`Not a valid spec id: "${e.id}"`));return}let o=Pf(`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 Df(e,t=Cv()){try{let n=JSON.parse(mc(Nr(e,".d360-writer","capture.json"),"utf8").replace(/^/,"")),o=n.projectId;if(!o)try{o=JSON.parse(mc(Nr(e,"package.json"),"utf8")).name}catch{}o||=Rv(e);let r=Object.keys(n.profiles??{}),s=n.defaultProfile??(r.length===1?r[0]:r.includes("staging")?"staging":r[0]);return s?gc(Nr(t,".document360-capture","auth-states",o,`${s}.json`)):!0}catch{return!0}}function Nf(e){return new Promise((t,n)=>{let o=Pf("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 xc(e,t){return e===127||/is not recognized as an internal or external command|command not found/i.test(t)}function jf(e){try{let t=JSON.parse(mc(Nr(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 yi(e){return gc(Nr(e,".d360-writer","capture.json"))}function Cc(){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(`
|
|
388
|
+
`)}function If(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(", ")}
|
|
389
|
+
/screenshot list --detail shows what each one needs`}function Lf(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):gi(r?.reason)!==gi(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):Xs(r?.reason??"")!==Xs(o.detail??"")?n.blockedNewReason.push(o.id):n.blockedAsBefore.push(o.id))}return n}function gi(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 Of(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?go(o.detail):"no reason recorded"}`)}function vo(e,t=2){return e.length<=t?e.join(" \xB7 "):`${e.slice(0,t).join(" \xB7 ")} \xB7 +${e.length-t}`}function _f(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",vo(e.newlyCaptured)),o("\u2717",e.newlyBroken.length,"newly broken",vo(e.newlyBroken)),o("\u2192",e.repairedNowBlocked.length,"repaired",`no longer broken \u2014 only data stands in the way \xB7 ${vo(e.repairedNowBlocked)}`),o("\u2298",e.newlyBlocked.length,"newly blocked",vo(e.newlyBlocked)),o("\u2192",e.blockedNewReason.length,"blocked on something new",`an earlier step now passes \xB7 ${vo(e.blockedNewReason)}`),o("\u2192",e.brokeDifferently.length,"broken differently",`the previous cause is fixed \xB7 ${vo(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 Mf(e){let t=e.results.filter(k=>k.outcome==="captured"),n=e.results.filter(k=>k.outcome==="skipped"),o=e.results.filter(k=>k.outcome==="failed"),r=k=>k===1?"":"s";if(t.length+n.length+o.length===0)return null;let s=e.articles.length===1?`/push ${e.articles[0]}`:Ne("/push","--screenshots",vt(e.articles)),i=e.ids.length===1?`/screenshot capture ${e.ids[0]}`:"/screenshot capture",a=o[0]?.id,l=[];o.length>0&&l.push({glyph:"\u2717",cmd:`/screenshot ${a}`,why:`re-author the ${o.length===1?"broken spec":`first of ${o.length} broken specs`} \u2014 re-running fails the same way`}),n.length>0&&l.push({glyph:"\u2298",cmd:"/screenshot list",why:`what to stage for the ${n.length} blocked shot${r(n.length)}`}),t.length>0&&l.push({glyph:"\u2713",cmd:s,why:`embed the ${t.length} new PNG${r(t.length)}`});let p=Math.max(...l.map(k=>k.cmd.length));return{note:l.map(k=>`${k.glyph} ${k.cmd.padEnd(p)} ${k.why}`).join(`
|
|
390
|
+
`),cmd:o.length>0?`/screenshot ${a}`:t.length>0?s:i,tone:o.length>0?"warn":"info"}}function Ff(e,t){let n=new Map(Ie(e).map(o=>[o.id,o.file]));return[...new Set(t.map(o=>n.get(o)).filter(o=>!!o))].sort()}async function Rc(e,t){let n=t?.cwd??process.cwd(),o=yc(e);if(!yi(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}=jr(n,o.mode==="scope"?o.scope:void 0),l=wc(n,a),p=(o.mode==="all"||o.mode==="scope")&&o.retryBlocked,g=o.mode==="single"?[o.id]:o.mode==="failed"?l:o.mode==="blocked"?i:o.mode==="picker"?r:[...r,...s,...p?i:[]];if(g.length===0)return o.mode==="failed"?console.log("No broken specs to re-run \u2014 /screenshot list shows where things stand."):o.mode==="blocked"?console.log("No shots are waiting on app data \u2014 /screenshot list shows where things stand."):console.log("No authored specs to capture yet \u2014 author them first: /screenshot"),{kind:"continue"};if(!p&&o.mode!=="single"&&o.mode!=="failed"&&o.mode!=="blocked"){let C=kc(a.filter(T=>T.state==="blocked"),"/screenshot capture --blocked");C&&console.log(C)}let k=Date.now(),v=[];for(let C of g){console.log(`\u25B6 ${C}`);try{let{exitCode:T}=await vc({cwd:n,id:C,stdio:"inherit"});v.push({id:C,outcome:bc(n,C,T,k)})}catch(T){if(T.code==="ENOENT")return console.log("d360-capture is not installed. Run: npm i -g document360-capture"),{kind:"continue"};v.push({id:C,outcome:"failed",detail:T.message})}}let P=C=>v.filter(T=>T.outcome===C).length;console.log(`\u2713 ${P("captured")} captured \xB7 \u2298 ${P("skipped")} skipped \xB7 \u2717 ${P("failed")} failed`);let S=v.filter(C=>C.outcome==="captured");return Fs(n,v.map(C=>({id:C.id,outcome:C.outcome,reason:C.detail,specSource:Tn(n,C.id)})),new Date().toISOString()),S.length>0?(console.log(Ar(S.length)),{kind:"forward-to-agent",prompt:In(n,S.map(C=>C.id)),display:"/screenshot verify"}):{kind:"continue"}}import{builderChannelWired as Iv,driftedAnchors as Lv,readTestidRequests as Ov,testidHandoffPrompt as _v,testidRequestPaths as Mv}from"document360-engine";async function xo(){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(`
|
|
391
|
+
`),display:"/screenshot checklist"}}var Wf="-".repeat(64);function Uf(e){let t=Ov(e);if(t.length===0)return null;let{mdRel:n}=Mv(e),o=t.length,r=new Set(t.map(g=>g.file).filter(Boolean)).size,s=`${o} data-testid attribute${o===1?"":"s"}`,i=`${r} source file${r===1?"":"s"}`,a=_v(e,o),l=Lv(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 Iv(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.)","",Wf,a,Wf]}}nn();ee();import{listOpenForDocs as Fv,readProjectConfig as Wv}from"document360-engine";function Sc(e){try{return Fv(e).length}catch{return 0}}function Pc(){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(`
|
|
392
|
+
`)}async function Bf(e,t){let n=t?.cwd??process.cwd();return Wv(n)?Sc(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:Pc(),display:"/inbox"}:(console.log(N("No d360-writer config here. Run /init first.")),{kind:"continue"})}ee();import{listOpenHints as Yv,listOpenForDocs as Kv,listOpenDirectives as zv,readProjectConfig as Vf,computeSyncStatus as Xv,planPull as Qv,applyPull as Jv,planImport as Zv,applyImport as ex,pullDocsUpdates as tx,handoffAvailable as nx,readProductBriefState as ox,readDiscoveryQueue as rx}from"document360-engine";ee();import{readProjectConfig as Uv,writeProjectConfig as Hf,reconcileDocsGit as Bv,pullDocsUpdates as Hv,probeGitState as qv,resolveGitHandoff as qf,handoffAvailable as Gv}from"document360-engine";var Ir=e=>e===1?"":"s";function cn(e,t){let n=o=>{let r=(o??"").split(`
|
|
393
|
+
`).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 wi(e,t){let n=qf(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=qv(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${Ir(o.ahead)} not shared yet \u2014 run /share`}):s.push({tone:"ok",text:re("\u2713")+"Everything is shared with your team."}),s}function Tc(e,t,n){Hf({...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,...wi(e,{...t,gitHandoff:{commit:!0,push:!0}})]:[o]}async function ki(e,t){let n=[],o=qf(t);if(!o.commit)return{lines:[{tone:"info",text:cn("disabled")}],changed:!1};let r=t;o.push==="unconfirmed"&&Gv(e,t)&&(r={...t,gitHandoff:{commit:!0,push:!0}},Hf(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 Hv(e);if(s.ok&&s.pulled>0){let p=[s.newHints>0?`${s.newHints} new hint${Ir(s.newHints)}`:null,s.newMessages>0?`${s.newMessages} new message${Ir(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")+cn(s.reason,s.detail)});let i=await Bv(e,r);if(i.commit&&!i.commit.ok)return n.push({tone:"warn",text:re("\u26A0")+cn(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${Ir(a)} to the docs folder.`}),i.push&&!i.push.ok)return n.push({tone:"warn",text:re("\u26A0")+cn(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${Ir(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 Vv={ok:G,info:$e,warn:H,error:N};async function Gf(e,t){let n=t.cwd,o=Uv(n);if(!o)return console.log(N("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(Vv[l.tone](l.text))};if(r==="status")return s(wi(n,o)),{kind:"continue"};if(r==="on"||r==="off")return s(Tc(n,o,r==="on")),{kind:"continue"};if(r)return console.log(N(`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 ki(n,o);return s(i),{kind:"continue"}}function Ln(e){let t=0,n=0,o=0,r=0;try{t=Yv(e).length}catch{}try{let s=Kv(e);n=s.filter(i=>i.kind==="request").length,o=s.filter(i=>i.kind==="answer").length}catch{}try{r=zv(e).length}catch{}return{hints:t,requests:n,answers:o,directives:r}}async function Ac(e){let t=Vf(e);if(!t)return[];if(!nx(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 ${cn(n.reason,n.detail)}`}]}function Lr(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 Dc(e){return{push:e.includes("--push")||e.includes("--publish"),skipReview:e.includes(it)}}function Nc(e){let t={hold:!1,openQuestions:0,answersPending:0};try{let n=ox(e);return!n||n.status==="confident"?t:{hold:!0,...rx(e)}}catch{return t}}function jc(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${Co(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${Co(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 Ic(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${Co(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(`
|
|
394
|
+
`)}var sx={status:Xv,plan:Qv,apply:Jv,planImport:Zv,applyImport:ex};async function Lc(e,t=sx){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 Ec=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Co=e=>e===1?"":"s";function Oc(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${Co(e.pulled.length)} into local: ${Ec(e.pulled)}`),e.imported.length&&t.push(`\u2713 Imported ${e.imported.length} new portal article${Co(e.imported.length)} into local drafts: ${Ec(e.imported)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${Co(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${Ec(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 Yf(e,t){let n=t?.cwd??process.cwd();if(!Vf(n))return console.log(N("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Ue(n,t?.profileName);if(!o.ok)return console.log(N(o.reason)),{kind:"continue"};let{push:r}=Dc(e);for(let l of await Ac(n))console.log(l.tone==="ok"?G(l.text):H(l.text));console.log(y("Reconciling with Document360 (pulling any portal changes)\u2026"));let s=await Lc({cwd:n,profileName:t?.profileName});for(let l of Oc(s))console.log(l.startsWith("\u2713")?G(l):l.startsWith("\u2139")?y(l):H(l));let i=Nc(n);for(let l of jc(i))console.log(l.tone==="warn"?H(l.text):y(l.text));let a=Lr(Ln(n));return console.log(y(a?`Catching up on ${a}\u2026`:"Checking for code changes the builder didn't hint\u2026")),{kind:"forward-to-agent",prompt:Ic(i),display:`/catch-up${r?" --push":""}`}}ee();import{resolveActiveProfile as ix,resolveProjectId as ax,loadProfileMap as lx,readCommentLedger as cx,isCommentOpen as ux,saveOpenCommentCount as dx,loadCommentSweepMemory as px,recordCommentSweep as hx,planCommentSweep as fx,sweepOpenComments as mx,commentHtmlToText as Kf,annotatedText as gx,readProjectConfig as yx,loadPortalLabels as wx,portalBreadcrumb as Xf,portalCategoryPath as kx,resolveModelForOperation as bx,runPartitioned as $x,EMPTY_PORTAL_LABELS as vx}from"document360-engine";import ve from"picocolors";var Qf=300,Or=3;function xx(e,t){let n=lp(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||ho(n).toLowerCase()===o}async function Mc(e,t,n={}){let o=ix(e,t),r={profile:o.name,connection:o.connection},s=ax(r,o.project.projectId),i=lx(e,o.name);if(!i)return{threads:[],answered:[],labels:vx,scanned:0,failed:[],truncated:0,skipped:0};let a=cx(e,o.name),l=new Set(Object.values(a).map(O=>O.articlePath).filter(O=>!!O)),p=Object.keys(a).length===0||l.size>0,g=n.articleIds?.length?new Set(n.articleIds):null,k=!!(g||n.path||n.scope),v=Object.entries(i.articles).filter(([,O])=>!!O.id).filter(([O,Y])=>g?g.has(Y.id):n.path?O.replace(/\\/g,"/")===n.path.replace(/\\/g,"/"):n.scope?xx(O,n.scope):!0).map(([O,Y])=>({articleId:Y.id,path:O,title:cp(e,O),answered:k||(p?l.has(O):!0)})),P=v.slice(0,Qf),S=await wx(r,s,o.project.workspaceId,{cwd:e,profile:o.name}),C=k||n.full?{read:P,skipped:[]}:fx(P,{live:S.live,stateOf:O=>S.articles.get(O),memory:px(e,o.name),alwaysRead:new Set(v.filter(O=>l.has(O.path)).map(O=>O.articleId))}),T=o.project.languageCode,D=await mx(r,s,C.read,{isOpen:(O,Y)=>ux(a,O,Y),...T?{langCode:T}:{},...n.onProgress?{onProgress:n.onProgress}:{}});k||dx(e,o.name,D.threads.length);let I=new Map;for(let O of[...D.threads,...D.answered])I.set(O.articleId,(I.get(O.articleId)??0)+1);return hx(e,o.name,{live:S.live,read:C.read.map(O=>O.articleId),failedIds:D.failed.map(O=>O.articleId),threadCounts:I,latestVersionOf:O=>S.articles.get(O)?.latestVersion}),{threads:D.threads,answered:D.answered,labels:S,scanned:D.scanned,failed:D.failed,truncated:Math.max(0,v.length-P.length),skipped:C.skipped.length}}function Cx(e,t=96){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n}var zf=500;function Rx(e){let t=gx(e.comment);if(!t)return"a passage";let n=t.replace(/\s+/g," ").trim();if(n.length<=zf)return e.comment.commented_text_truncated?`\u201C${n}\u2026\u201D
|
|
395
|
+
(Document360 sends the first 500 characters of a highlight)`:`\u201C${n}\u201D`;let o=n.slice(0,zf).trimEnd(),r=n.length-o.length;return`\u201C${o}\u2026\u201D
|
|
396
|
+
(+${r} more character${r===1?"":"s"}${e.comment.commented_text_truncated?", and Document360 caps a highlight at 500":""})`}function Sx(e,t){let n=kx(t,e.articleId);return n.length>0?n.join(" \u203A "):e.path?ho(e.path):""}function Px(e,t){return t.articles.get(e.articleId)?.title?.trim()||e.title||(e.path?_a(e.path):e.articleId)}function Tx(e,t){return Xf(t,e.articleId,{category:e.path?ho(e.path):null,title:e.title??(e.path?_a(e.path):null)})??e.path??e.articleId}function On(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:Sx(o,t),title:Px(o,t),label:Tx(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 Ex=100,Ax=120,Jf=(e,t)=>Math.max(40,Math.min(e??96,t));function Zf(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 _c(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=Xf(e.labels,o.articleId,{title:o.title})??o.title??o.articleId;t.push(` ${ve.gray(`${r} \u2014 ${Cx(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 ${Qf} articles; ${e.truncated} not checked this run.`),t}function _r(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 On(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(..._c(e)),n}let i=On(e.threads,e.labels);return n.push(Zf(e)),n.push(""),n.push(Fa(["#","Category","Article","Comments"],i.map((a,l)=>[`${l+1}`,a.category||"(root)",a.title,`${a.threads.length}`]),Jf(t.width,Ex),{plain:!0,align:["left","left","left","right"]})),n.push(""),s(),n.push(..._c(e)),n}function bi(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=[Kf(s.comment.comment)||"(empty comment)"];for(let a of s.comment.replies??[])i.push(`\u21B3 ${Kf(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)"),[Rx(s),i.join(`
|
|
397
|
+
`)]});return o.push(Fa(["Annotated text","Comment"],r,Jf(t.width,Ax),{plain:!0})),o.push(""),o}function $i(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 Fc(e,t={}){let n=On(e.threads,e.labels);if(t.full&&n.length===1){let o=n[0];return[Zf(e),"",...bi(o,t),..._c(e)]}return _r(e,t)}function Dx(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 Wc(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.`,"",...Dx({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(`
|
|
398
|
+
`)}function Uc(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 Nx(e,t,n){if(t.length===0)return{kind:"continue"};let o=t.reduce((a,l)=>a+l.threads.length,0),{model:r}=bx(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${Or} 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 $x({cwd:e.cwd,partitions:i,promptFor:l=>{let p=s.get(l.label);return Wc({articleId:p.articleId,label:p.label,path:p.path,count:p.threads.length,resolve:n.resolve})},concurrency:Or,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(G(` \u2713 ${a.label}`)):console.log(N(` \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(H(`\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(H(`\u26A0 ${a.blocked}`)),a.allEmpty&&console.log(H("\u26A0 No agent produced any work this run \u2014 nothing was changed or answered."))}}catch(a){console.log(N(`Answering comments failed: ${a.message}`))}return{kind:"continue"}}async function em(e,t){let n=t?.cwd??process.cwd();if(!yx(n))return console.log(N("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Ue(n,t?.profileName);if(!o.ok)return console.log(N(o.reason)),{kind:"continue"};let r=Uc(e);console.log(y("Checking Document360 for reviewer comments\u2026"));let s;try{s=await Mc(n,t?.profileName,r.scope)}catch(a){return console.log(N(`Couldn\u2019t read comments from Document360: ${a.message}`)),{kind:"continue"}}for(let a of Fc(s,{full:!!r.scope.path,showAnswered:r.showAnswered}))console.log(a);if(s.threads.length===0)return{kind:"continue"};if(r.answer&&t)return Nx(t,On(s.threads,s.labels),{resolve:r.resolve});let i=On(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"}}ee();import{spawn as tm}from"node:child_process";var Ro="document360-writer",vi=`npm i -g ${Ro}@latest`,jx="document360-capture";function Ix(){return new Promise(e=>{try{let t=tm("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 xi(){let e=process.platform==="win32",n=await Ix()?[Ro,jx]:[Ro];return new Promise(o=>{try{let r=tm(`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 nm(){console.log(y("Updating the d360-writer toolchain\u2026"));let e=await xi();return e.ok?console.log(G(`\u2713 Updated ${e.packages.join(" + ")}. Exit (/exit) and relaunch d360-writer to apply.`)):console.log(N(`Update failed \u2014 run manually: ${vi}`)),{kind:"continue"}}ee();nn();import{existsSync as Bc,rmSync as Lx}from"node:fs";import{basename as om,resolve as Hc}from"node:path";import{execFileSync as Ox}from"node:child_process";import{input as _x}from"@inquirer/prompts";import{readProjectConfig as Mx,devHintsGuidePath as Fx}from"document360-engine";var Wx=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],Ux=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),Ci=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),rm=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function sm(e){let t=Ci(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:rm(t)?!0:Ux.has(t)}function qc(e){let t=null;try{t=Mx(e)}catch{t=null}let n=new Set(Wx);for(let o of[Ci(t?.docsDir),Ci(t?.captureDir),Ci(t?.outputDir)])o&&rm(o)&&n.add(o);return[...n].filter(o=>sm(o)&&Bc(Hc(e,o)))}function Gc(e,t){let n=[],o=[];for(let r of t){if(!sm(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{Lx(Hc(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function im(e,t){try{return Ox("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
|
|
399
|
+
`).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function Bx(e){return im(e,".d360-writer/hints")}function Hx(e){return im(e,".d360-writer/messages")}function Vc(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=Bx(e),o=Hx(e),r=Bc(Hc(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: ${om(e)}`]}async function am(e,t){let n=qc(t.cwd);for(let l of Vc(t.cwd,n))console.log(n.length===0?y(l):l);if(n.length===0)return{kind:"continue"};let o=om(t.cwd);if((await t.withPausedInput(()=>_x({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(H("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=Bc(Fx(t.cwd)),{removed:i,failed:a}=Gc(t.cwd,n);console.log(G(`\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(N(` \u2717 ${l.path}: ${l.error}`));if(s){for(let l of Ds())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"}}ee();import{buildBaseline as qx,buildRegistry as zc,clearRegistryCache as Gx,lintArticles as Xc,listAvailablePacks as um,readProjectConfig as Fr,readStyleBaseline as Vx,resolveActivePacks as Yx,styleGuidePath as dm,writeProjectConfig as pm,writeStyleBaseline as Kx,activeRuleSet as zx,buildStyleCompilePrompt as Xx,loadStyleGuide as Qx,listStyleGuides as Jx,getStyleGuide as Zx,resolveActiveProfile as e0,resolveProjectId as t0,STYLE_GUIDE_MAX_CHARS as lm,BUILTIN_RULES as Ri,ALWAYS_ON_PACK as So}from"document360-engine";import{existsSync as hm,mkdirSync as n0,readFileSync as o0,writeFileSync as cm}from"node:fs";import{dirname as r0}from"node:path";import{createHash as s0}from"node:crypto";function i0(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 Mr="House";async function a0(e,t,n){let o,r;try{let C=e0(e,n);o={profile:C.name,connection:C.connection},r=await t0(o,C.project?.projectId)}catch(C){return{lines:[ke("\u2717",`Not signed in to Document360: ${C instanceof Error?C.message:String(C)}`),y(" Run /login first.")],restart:!1}}let s=await Jx(o,r);if(s.kind!=="ok")return{lines:[ke("\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:[ke("\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((T,D)=>{let I=[T.language_code,T.created_by_name,T.created_at?.slice(0,10)].filter(Boolean).join(" \xB7 ");return` ${D+1} ${T.name??T.id}${T.is_default?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:[ke("\u2717",`No style guide numbered or identified by "${t}". Run /style-guide pull to list them.`)],restart:!1};let l=await Zx(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:[ke("\u2717",`Could not read "${a.name??a.id}" \u2014 ${C}.`)],restart:!1}}let p=(l.guide.content??"").trim();if(!p)return{lines:[ke("\u26A0",`"${a.name??a.id}" has no content yet \u2014 nothing to pull.`)],restart:!1};let g=dm(e),k=[];if(hm(g))try{cm(`${g}.bak`,o0(g,"utf8"),"utf8"),k.push(y(" Your previous guide is at .d360-writer/style-guide.md.bak"))}catch{}let v=p.length>lm?p.slice(0,lm):p,P=`<!-- Pulled from Document360: "${a.name??a.id}" (${new Date().toISOString().slice(0,10)}). Edit freely \u2014 /style-guide pull overwrites this file. -->
|
|
400
|
+
|
|
401
|
+
`;n0(r0(g),{recursive:!0}),cm(g,`${P}${v}
|
|
402
|
+
`,"utf8");let S=Fr(e)??{projectId:""};return pm({...S,styleGuide:{...S.styleGuide,pulledFrom:{styleGuideId:a.id,name:a.name??a.id,pulledAt:new Date().toISOString(),contentHash:s0("sha1").update(v).digest("hex").slice(0,16)}}},e),{lines:[ke("\u2713",`Pulled "${a.name??a.id}" into .d360-writer/style-guide.md (${v.length.toLocaleString()} characters).`),...k,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=zc(e).rules.filter(n=>n.pack.toLowerCase()===Mr.toLowerCase()).map(n=>n.id);return{prompt:Xx({guide:Qx(e),packName:Mr,existingRuleIds:t}),display:"/style-guide compile"}}function fm(){return[y(` Review what it wrote: git diff .d360-writer/styles/${Mr}/`),y(` Anything it could not check mechanically is listed in .d360-writer/styles/${Mr}/UNCHECKABLE.md \u2014 /review judges those.`),y(` Turn them on when you are happy: /style-guide use ${Mr.toLowerCase()} (they start as warnings, never blocking)`)]}var lt=(e,t)=>`${e} ${t}${e===1?"":"s"}`,Yc=e=>/^v\d/i.test(e)?e:`v${e}`;function mm(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 c0(e){let n=Fr(e)?.styleGuide?.pulledFrom;return n?`.d360-writer/style-guide.md \u2014 pulled ${n.pulledAt.slice(0,10)} from "${n.name}"`:hm(dm(e))?".d360-writer/style-guide.md (yours)":"the built-in default"}function u0(e){let t=Fr(e),n=zc(e),o=(t?.styleGuide?.packs??[]).filter(Boolean),r=n.packs.filter(l=>l.name.toLowerCase()===So),s=n.packs.filter(l=>l.name.toLowerCase()!==So),i=[`Style guide: ${c0(e)}`,`Rule packs: ${s.length>0?s.map(l=>`${l.name.toLowerCase()} ${Yc(l.version)}`).join(", "):y("none chosen")}`,`Always on: ${y(`d360 (correctness, built in \u2014 ${lt(Ri.length,"rule")})`)}`];for(let l of r)i.push(` ${y(`${l.name.toLowerCase()} ${Yc(l.version)} (anti-slop \u2014 ${lt(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=[...Ri.map(l=>({severity:l.severity})),...n.rules.map(l=>({severity:l.severity}))];i.push("",`${lt(a.length,"rule")} active \xB7 ${mm(a)}`);try{let l=Xc({cwd:e}),p=l.findings.filter(k=>!k.baselined),g=p.filter(k=>k.severity==="error").length;i.push(""),i.push(g===0?ke("\u2713",`No style errors across the docs${p.length>0?`, though ${lt(p.length,"other issue")} ${p.length===1?"is":"are"} reported`:""}.`):ke("\u2717",`${lt(g,"style error")} \u2014 /lint shows them, /lint --fix corrects them.`)),l.baselinedCount>0&&i.push(ke("\u2139",`${lt(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(ke("\u26A0",`${lt(l.ruleErrors.length,"rule")} could not be loaded: ${l.ruleErrors.slice(0,2).map(k=>`${k.ruleId} (${k.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 Kc(e){let t=Fr(e),n=new Set(Yx(t?.styleGuide)),o=um(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===So,g=l?"\u2713":"\xB7",k=p?y("(always on)"):l?y("(active)"):"",v=i.local?y(" [yours]"):"";r.push(` ${g} ${a.padEnd(s)}${v} ${i.description??""}`),r.push(` ${y(`${lt(i.rules.length,"rule")} \xB7 ${mm(i.rules)} \xB7 ${Yc(i.version)}`)} ${k}`),i.errors.length>0&&r.push(ke("\u26A0",`${lt(i.errors.length,"rule")} in this pack could not be loaded \u2014 /style-guide explain names them.`))}return o.every(i=>i.name.toLowerCase()===So)&&(r.push(""),r.push(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 d0(e,t){if(!t)return[ke("\u26A0","Name a rule: /style-guide explain Humanise.EmDash")];let n=zc(e),o=Ri.find(p=>p.id.toLowerCase()===t.toLowerCase()),r=n.rules.find(p=>p.id.toLowerCase()===t.toLowerCase());if(!o&&!r){let p=[...Ri.map(g=>g.id),...n.rules.map(g=>g.id)].filter(g=>g.toLowerCase().includes(t.toLowerCase())).slice(0,5);return[ke("\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(ke("\u26A0",`This rule is translated approximately: ${r.degraded}. It may match slightly more than the original does.`)));try{let p=Xc({cwd:e}).findings.filter(k=>k.ruleId===s),g=p.filter(k=>!k.baselined);l.push(""),l.push(p.length===0?" Currently: no findings.":` Currently: ${lt(g.length,"finding")}${p.length!==g.length?`, plus ${p.length-g.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 p0(e,t){let n=(t??"").trim();if(!n)return{lines:[ke("\u26A0","Name the packs to use: /style-guide use microsoft (or `none`)"),...Kc(e)],restart:!1};let o=n.toLowerCase()==="none"?[]:n.split(/[,\s]+/).map(l=>l.trim().toLowerCase()).filter(Boolean),r=new Map(um(e).map(l=>[l.name.toLowerCase(),l])),s=o.filter(l=>!r.has(l));if(s.length>0)return{lines:[ke("\u2717",`No rule pack named ${s.map(l=>`"${l}"`).join(", ")}.`),"",...Kc(e)],restart:!1};let i=Fr(e)??{projectId:""};pm({...i,styleGuide:{...i.styleGuide,packs:o}},e),Gx();let a=[ke("\u2192",`Switching to: ${o.length>0?o.join(", "):"the built-in checks only"}${o.includes(So)?"":` (+ ${So}, always on)`}\u2026`)];try{let l=Xc({cwd:e}),p=new Set(l.findings.map(g=>g.path)).size;if(l.findings.length===0)a.push(ke("\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 g=Vx(e),k=qx(l.findings,zx(e));Kx(e,k),a.push(ke("\u2713",`Recorded ${lt(l.findings.length,"existing issue")} across ${lt(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."),ke("\u2713","Nothing is blocked today. New writing, and any paragraph you edit, is held to the full set.")),g&&a.push(y(` (Replaced the baseline recorded ${g.createdAt.slice(0,10)}.)`))}}catch(l){a.push(ke("\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 Si(e,t){let{sub:n,value:o}=i0(e),r=s=>{for(let i of s)console.log(i);console.log("")};switch(n){case"list":return r(Kc(t.cwd)),{kind:"continue"};case"explain":return r(d0(t.cwd,o)),{kind:"continue"};case"use":{let s=p0(t.cwd,o);return r(s.lines),s.restart?{kind:"clear"}:{kind:"continue"}}case"pull":{let s=await a0(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(u0(t.cwd)),{kind:"continue"}}}ee();import{lintDocs as Qc,loadStyleGuide as km,buildReviewPrompt as bm,readProjectConfig as $m,DEFAULT_DOCS_DIR as vm,listArticleFiles as xm,planPartitions as w0,runPartitioned as k0,resolveModelForOperation as b0,stampArticles as $0}from"document360-engine";ee();import{readProjectConfig as h0,loadProfileMap as f0,resolveActiveProfile as m0,desiredCategoryOrder as g0,desiredArticleOrder as y0}from"document360-engine";function gm(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}var ym=e=>e.replace(/\\/g,"/").split("/").pop()??e;function Wr(e,t){try{if(!h0(e))return[];let n=m0(e,t),o=f0(e,n.name);if(!o)return[];let r=new Map;for(let i of y0(o)){let a=r.get(i.categoryPath);a?a.push(i):r.set(i.categoryPath,[i])}let s=[];for(let i of g0(o)){s.push(gm(ym(i.path)));for(let a of(r.get(i.path)??[]).sort((l,p)=>l.order-p.order))s.push(` ${gm(ym(a.path))}`)}return s}catch{return[]}}async function wm(e,t){let n=Wr(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(K("Documentation order (categories \u2192 articles):"));for(let o of n)console.log(o);return console.log(""),{kind:"continue"}}function Br(e,t){return kr(e,xm(e,t))}function v0(e,t,n){return t.includes("--blocked")?Br(e,n):xm(e,n)}function x0(e,t){let n=$m(e);if(!n)return null;let o=(n.docsDir??vm).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),s=t.includes("--blocked"),i=t.find(P=>!P.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),a=Qc({cwd:e}),l=i?a.filter(P=>P.path===`${o}/${i}`||P.path.startsWith(`${o}/${i}/`)):a,p=s?Br(e,i):void 0,g=p?l.filter(P=>p.includes(P.path)):l,k=i||s?"":Wr(e).join(`
|
|
403
|
+
`);return{prompt:bm({docsRoot:o,scope:i,styleGuide:km(e),deterministicFindings:g,fix:r,structure:k||void 0,...p?{paths:p}:{}}),display:`/review${i?` ${i}`:""}${s?" --blocked":""}${r?" --fix":""}`}}var C0=e=>"ruleId"in e,Ur=3,R0=3;function Jc(e,t){let n=x0(e,t);if(!n)return null;let o=t.find(k=>!k.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),r=v0(e,t,o),s=w0(r,{maxPerPartition:R0});if(s.length<=1)return{kind:"single",...n};let a=($m(e)?.docsDir??vm).replace(/\\/g,"/").replace(/\/+$/,""),l=t.includes("--fix"),p=km(e),g=Qc({cwd:e});return{kind:"partitioned",partitions:s,articles:r.length,wholeKb:!o&&!t.includes("--blocked"),display:n.display,promptFor:k=>{let v=new Set(k.paths);return bm({docsRoot:a,styleGuide:p,deterministicFindings:g.filter(P=>v.has(P.path)),fix:l,paths:k.paths})}}}async function Cm(e,t){if(e.includes("--blocked")&&Br(t.cwd,e.find(o=>!o.startsWith("--"))).length===0)return console.log(G("\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(ln("review",e)){let o=$o(t.cwd,"review",e,t.profileName);if(o.length>0){for(let r of o)console.log(y(r));return{kind:"continue"}}}let n=Jc(t.cwd,e);return n?n.kind==="single"?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:await S0(t,n,e.includes("--fix"),e.find(o=>!o.startsWith("--"))):(console.log(N("No d360-writer config here. Run /init first.")),{kind:"continue"})}async function S0(e,t,n,o){let{model:r}=b0(e.cwd,"standard");console.log(y(`Reviewing ${t.articles} article${t.articles===1?"":"s"} in ${t.partitions.length} batches (\u2264${Ur} editors at once) on ${r}${n?", applying fixes":", report only"}\u2026`));try{for await(let a of k0({cwd:e.cwd,partitions:t.partitions,promptFor:t.promptFor,concurrency:Ur,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(G(` \u2713 ${a.label}`)):console.log(N(` \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}/${t.partitions.length} batches reviewed.`),l.length&&console.log(H(`\u26A0 ${l.length} not reviewed: ${l.map(p=>p.label).join(", ")}`)),a.blocked&&console.log(H(`\u26A0 ${a.blocked}`)),a.allEmpty&&console.log(H("\u26A0 No editor produced any work this run \u2014 nothing was reviewed or changed."));for(let p of Zc(t))console.log(y(p));if(n&&!a.allEmpty&&!a.blocked){let p=new Set(l.map(k=>k.label)),g=t.partitions.filter(k=>!p.has(k.label)).flatMap(k=>k.paths);try{$0(e.cwd,g,Ye("review"))}catch{}}}}catch(a){return console.log(N(`Review failed: ${a.message}`)),{kind:"continue"}}if(!n)return{kind:"continue"};let i=Qc({cwd:e.cwd,scope:o}).filter(a=>!a.baselined).filter(a=>C0(a)&&a.severity==="error");if(console.log(""),i.length>0){let a=Ne("/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(Ct(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 Zc(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."]:[]}ee();import{readProjectConfig as P0}from"document360-engine";function eu(e,t){if(!P0(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(`
|
|
404
|
+
`),display:`/reorder${n?` ${n}`:""}`}}async function Rm(e,t){if(ln("reorder",e)){let o=$o(t.cwd,"reorder",e,t.profileName);if(o.length>0){for(let r of o)console.log(y(r));return{kind:"continue"}}}let n=eu(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(N("No d360-writer config here. Run /init first.")),{kind:"continue"})}ee();import{readProjectConfig as T0,writeProjectConfig as Sm,isAppType as E0,playbookSkillName as A0,detectAppType as Pm}from"document360-engine";var Tm=["web","cli","service","library"],D0=new Set(["web","cli"]);function tu(e){return D0.has(e)?`${A0(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function Pi(e,t){let n=t.cwd,o=T0(n);if(!o)return console.log(N("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let s=o.appType??Pm(n);if(s){let i=o.appType?"set in config":"auto-detected";console.log(`${K("Genre:")} ${s} (${i}) \u2014 ${tu(s)}`)}else console.log(H("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(y(`Set it: /genre <${Tm.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;Sm(i,n);let a=Pm(n);return console.log(G(`\u2713 Genre reset to auto-detect \u2014 now: ${a?`${a} (${tu(a)})`:"unclassified (no playbook)"}.`)),console.log(y(" Restarting the agent so the loaded playbook matches\u2026")),{kind:"clear"}}return E0(r)?(Sm({...o,appType:r},n),console.log(G(`\u2713 Genre set to ${r} \u2014 ${tu(r)}.`)),console.log(y(" Restarting the agent so the playbook loads\u2026")),{kind:"clear"}):(console.log(N(`Unknown genre "${r}". Choose one of: ${Tm.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}ee();import{listRoadmap as Ti,roadmapProgress as Em,stampRoadmapDone as N0}from"document360-engine";function nu(e){let t=Ti(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=Em(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 Ei(e,t){let n=Ti(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:
|
|
405
405
|
${i.map(p=>` \u25CB ${p.title}`).join(`
|
|
406
406
|
`)}`};if(i.length===0)return{ok:!1,line:`No open step matches "${o}". Open steps:
|
|
407
407
|
${n.map(p=>` \u25CB ${p.title}`).join(`
|
|
408
|
-
`)}`};let a=i[0].title;
|
|
409
|
-
`):null}function
|
|
408
|
+
`)}`};let a=i[0].title;N0(e,a,{doneAt:new Date().toISOString()});let l=Em(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 ou(e,t){let n=r=>r.trim().replace(/\s+/g," ").toLowerCase(),o=n(t);return o.startsWith("/")?Ti(e).find(r=>r.status==="open"&&!!r.run&&n(r.run)===o)??null:null}function Am(e,t){let n=ou(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(`
|
|
409
|
+
`):null}function Dm(e,t){let n=t.trim().toLowerCase();if(!n)return null;let o=Ti(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:
|
|
410
410
|
${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(`
|
|
411
|
-
`):null}async function
|
|
412
|
-
\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${
|
|
413
|
-
|
|
414
|
-
\u2022 `)
|
|
415
|
-
`)}let
|
|
416
|
-
`)
|
|
417
|
-
|
|
418
|
-
`)
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
`))
|
|
424
|
-
`);
|
|
425
|
-
`));return
|
|
426
|
-
`)
|
|
427
|
-
`);return
|
|
428
|
-
`)
|
|
429
|
-
|
|
430
|
-
`);
|
|
431
|
-
|
|
432
|
-
`),
|
|
433
|
-
|
|
434
|
-
`),
|
|
435
|
-
`)
|
|
436
|
-
`)
|
|
437
|
-
|
|
438
|
-
`)){let
|
|
439
|
-
`)}function
|
|
440
|
-
`)||e.length
|
|
441
|
-
`)
|
|
442
|
-
`)
|
|
411
|
+
`):null}async function Nm(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let r=Ei(n,e.slice(1).join(" ").trim());return console.log(r.ok?G(r.line):H(r.line)),{kind:"continue"}}let o=nu(n);console.log(K(o[0]??""));for(let r of o.slice(1))console.log(r.startsWith("(")?y(r):r);return{kind:"continue"}}var jm={help:Ta,"?":Ta,clear:Md,exit:Ea,quit:Ea,init:La,mcp:Is,push:oi,publish:bh,audit:br,discover:$h,scope:xh,pull:Lh,resolve:Nh,convert:Oh,write:Zh,draft:rf,document:sf,resume:cf,rename:uf,profile:pf,model:mf,doctor:Tr,workspace:$f,project:vf,"allow-prod":xf,login:Cf,logout:Rf,screenshot:async(e,t)=>{let n=hr(e);return n.mode==="capture"?Rc(n.rest,t):n.mode==="verify"?Sf(n.rest,t):n.mode==="checklist"?xo():Js(e,t)},capture:Rc,"capture-setup":xo,devhints:Kd,inbox:Bf,"catch-up":Yf,comments:em,update:nm,reset:am,lint:Gl,check:Hh,"style-guide":Si,review:Cm,reorder:Rm,structure:wm,genre:Pi,roadmap:Nm,share:Gf};function Im(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 j0}from"node:child_process";import{recordAnalyzedCommit as I0,resolveActiveProfile as L0}from"document360-engine";function O0(e){try{let t=j0("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 Hr(e,t){try{let n=O0(e);if(!n)return null;let o=L0(e,t);return I0(e,o.name,n)?n:null}catch{return null}}import{CONTENT_CAP_VERSION as _0,stampArticles as M0,articlesChangedSince as F0,docsRootOf as W0}from"document360-engine";function Ai(e,t,n=""){let o=[];try{o=F0(e,t)}catch{return{changed:[],cta:null}}if(o.length===0)return{changed:[],cta:null};try{M0(e,o,{writtenCap:_0,reviewedCap:0,checkedCap:0})}catch{}let r=W0(e),s=p=>{let g=p.replace(/\\/g,"/");return g.startsWith(`${r}/`)?g.slice(r.length+1):g},i=vt(o.map(s)),a=o.length,l=i?"/push":"/push --all";try{return{changed:o,cta:Ct(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}}}nn();var U0="Or just tell me what to write or update.",B0='\u{1F4ED} No docs yet for this repo. Tell me "write the docs for this repo" and I\u2019ll read the code and draft a structure \u2014 or /audit to see what the docs should cover.';function be(e){return e===1?"":"s"}function Po(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 Lm(e,t){return e.length===t.length&&e.every((n,o)=>n===t[o])}function H0(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 qr(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 Di={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 q0(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:Di,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${be(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${be(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(`
|
|
412
|
+
\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${be(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${be(n)} waiting on your articles.`})}if(e.behind>0){let n=e.behind;t.push({key:"audit",bullet:`${n} code change${be(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${be(n)}.`})}if(e.hasDocs&&e.pendingWrites>0){let n=e.pendingWrites;t.push({key:"write",bullet:`${n} planned article${be(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${be(n)}.`,dependsOn:["genre","discovery","catchup","audit"]})}if(e.unreviewed>0){let n=e.unreviewed,o=Ne("/review","--blocked --fix",e.unreviewedScope);t.push({key:"review",bullet:`${n} article${be(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${be(n)} \u2014 /push is blocked until it has.`})}if(e.styleErrors>0){let n=e.styleErrors,o=Ne("/lint","--fix",e.styleErrorScope);t.push({key:"styleguide",bullet:`${n} article${be(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${be(n)} \u2014 /push is blocked until it has.`,dependsOn:["review"]})}if(e.localAhead>0){let n=e.localAhead;t.push({key:"publish",bullet:`${n} article${be(n)} changed locally \u2014 ready to send to Document360`,lead:{kind:"cmd",cmd:"/push",reason:`it saves your ${n} local edit${be(n)} to Document360 as drafts`},picker:null,follow:`Then /push saves your ${n} local edit${be(n)} to Document360.`,dependsOn:["discovery","audit"],blockedBy:["review","styleguide"]})}if(e.conflicts>0){let n=e.conflicts;t.push({key:"resolve",bullet:`${n} article${be(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${be(n)} (keep yours / take the portal's / skip).`})}if(e.draftAhead>0){let n=e.draftAhead;t.push({key:"golive",bullet:`${n} article${be(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${be(n)} live to your readers \u2014 it lists them and asks first`},picker:null,follow:`Then /publish takes the ${n} draft${be(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:H0(o.body),s=`docs campaign: ${n.done} of ${n.total} step${be(n.total)} done`;t.push({key:"roadmap",bullet:`${s} \u2014 next: ${o.title}${r?`
|
|
413
|
+
\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?`
|
|
414
|
+
\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(`
|
|
415
|
+
`),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${be(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${be(n)} under .d360-writer/ \u2014 tell your coding agent: "commit d360-writer's work"`,lead:null,picker:null,follow:null})}return t}function Om(e){return e.find(t=>t.lead||t.picker)??null}function G0(e){return e.kind==="cmd"?e.cmd:e.kind==="prompt"?`\u201C${e.text}\u201D`:""}function V0(e){return e.kind==="cmd"?e.cmd:e.kind==="prompt"?e.text:""}function Y0(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 ru(e,t,n){let o=Om(t),r=o?.picker?[]:t.filter(k=>k.lead),s=r.length>=2?r:[],i=new Map(s.map((k,v)=>[k.key,v+1])),a=[];o?.lead?a.push(qr(o.lead)):o?.picker&&a.push("Pick the genre below \u2014 one keypress, and it shapes everything I write.");for(let k of t.filter(v=>v!==o&&!v.lead).slice(0,2))k.follow&&a.push(k.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(k=>k.bullet).map(k=>{let v=i.get(k.key),[P="",...S]=(v&&k.lead?.kind==="prompt"&&k.rowBullet?k.rowBullet:k.bullet).split(`
|
|
416
|
+
\u2022 `);if(v&&k.lead){let T=P.replace(/^→\s+/,"");return[` ${v}. ${G0(k.lead)} \u2014 ${T}${Y0(k,i,v)}`,...S.map(I=>` ${I}`)].join(`
|
|
417
|
+
`)}let C=k.lead?.kind==="cmd"?k.lead.cmd:null;return` \u2022 ${k.bullet}${C&&!l.includes(C)?` \u2014 ${C}`:""}`}),g=[[e,...p].join(`
|
|
418
|
+
`)];return a.length&&g.push(a.join(" ")),g.push(U0),{note:g.join(`
|
|
419
|
+
|
|
420
|
+
`),menu:s.map(k=>V0(k.lead))}}function Gr(e,t){let n=t?.pickable===!0,o=p=>t?.header?`${t.header}
|
|
421
|
+
|
|
422
|
+
${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=q0(e);if(!e.hasDocs){let p=Om(r);if(p&&(p.lead?.kind==="cmd"||p.picker)){let g=ru(t?.header??"\u{1F4ED} No docs yet for this repo \u2014 here\u2019s where things stand:",r,n);return{kind:"recommend",rec:{note:g.note,tone:p.tone??"info",lead:p.lead,picker:p.picker,menu:g.menu}}}return{kind:"recommend",rec:{note:o(B0),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${be(e.roadmap.total)} done (/roadmap).`:"";return{kind:"recommend",rec:{note:o(`Welcome back. Your ${e.tracked} tracked article${be(e.tracked)} for \u201C${e.profileName}\u201D are all in sync \u2014 /audit re-checks the code, /pull brings down portal edits.${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=ru(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${be(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`)};let l=ru(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 Ni,readdirSync as iu}from"node:fs";import{spawnSync as K0}from"node:child_process";import{join as ji}from"node:path";import{readProjectConfig as Mm,resolveActiveProfile as Fm,loadTokens as z0,isExpired as X0,loadProfileMap as Wm,localAheadPaths as Q0,loadKnownConflicts as J0,draftPendingPaths as Z0,loadOpenCommentCount as eC,readDocsPlan as tC,devHintsGuidePath as nC,DEFAULT_DOCS_DIR as su,roadmapProgress as oC,listRoadmap as rC,readProductBriefState as sC,readDiscoveryQueue as iC,reconcileCommitRequest as aC,reconcileTestidRequest as lC,snapshotHandoff as cC,shareExplainedPath as uC}from"document360-engine";nn();function _m(e){try{return iu(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function au(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>_m(ji(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&_m(ji(e,o)))}function lu(e,t){try{let n=Mm(e);if(!n)return!1;let o=Fm(e,t),r=Wm(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=ji(e,(n.docsDir??su).replace(/\/+$/,""));return!!(Ni(s)&&iu(s).length>0||Ni(nC(e)))}catch{return!1}}function Vr(e,t,n){try{let o=Mm(e);if(!o)return null;let r=Fm(e,t),s=z0(r.name),i=!!s&&(!X0(s)||!!s.refreshToken),a=lu(e,t)||!au(e,o.authoritativeSourceFiles),l=Wm(e,r.name),p=l?Object.keys(l.articles).length:0,g=ji(e,(o.docsDir??su).replace(/\/+$/,"")),k=!1;try{k=Ni(g)&&iu(g).length>0}catch{}let v=0;if(l?.lastAnalyzedCommit)try{let De=K0("git",["rev-list","--count",`${l.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});De.status===0&&(v=parseInt((De.stdout||"").trim(),10)||0)}catch{}let P=0;try{let De=tC(e);if(De.length>0){let Pt=(o.docsDir??su).replace(/\/+$/,"");P=zl(e,Pt,De.map(Mo=>Mo.path)).length}}catch{}let S=Ln(e),C=Lr({...S,directives:0}),T=Q0(e,t),D=new Set(J0(e,r.name)),I=T.filter(De=>D.has(De)).length,O=T.length-I,Y=T.filter(De=>!D.has(De)),fe=kr(e,Y),ae=fe.length,le=vt(fe),he=0,ce;try{let De=wh(e,Y);he=De.length,ce=vt(De)}catch{}let X=new Set(T),ne=Z0(e,t).filter(De=>!X.has(De)).length,ue=eC(e,r.name),Te=mt(e),yt=oC(e),St=cC(e,o),Wt=aC(e,new Date().toISOString(),{supersededByHandoff:St!==null});lC(e,new Date().toISOString());let nt=Zt(e,t),Wn=nt?{name:nt.name,replacement:nt.replacement,replacementProfile:nt.replacementProfile}:null,Ke=sC(e),hn=iC(e),Ut=Ke?{status:Ke.status,openQuestions:hn.openQuestions,answersPending:hn.answersPending}:null;return!Ut&&k&&rC(e).some(Pt=>Pt.status==="open"&&(Pt.run??"").trim()==="/discover")&&(Ut={status:"pending",openQuestions:0,answersPending:0}),{ready:i&&a&&!n.claudeMissing,hasDocs:k,tracked:p,pendingText:C,directives:S.directives,behind:v,pendingWrites:P,localAhead:O,unreviewed:ae,unreviewedScope:le,styleErrors:he,styleErrorScope:ce,draftAhead:ne,conflicts:I,openComments:ue,autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:Te.status,devhintsCompletedVersion:Te.completedVersion,devhintsToVersion:Re,builderStarted:Ot(e),genreUnknown:n.genreUnknown,pendingAnswer:n.pendingAnswer??null,roadmap:yt,discovery:Ut,uncommittedDocs:Wt.dirty.length,handoff:St,shareExplained:Ni(uC(e)),sunsetEnv:Wn}}catch{return null}}ee();import{existsSync as dC,readFileSync as pC}from"node:fs";import{isAbsolute as hC,join as fC}from"node:path";import{DEFAULT_DOCS_DIR as mC,findPathByArticleId as gC,isArticleDocPath as yC,loadProfileMap as wC,readProjectConfig as kC,resolveActiveProfile as bC}from"document360-engine";var $C=70;function vC(e,t){return{docsRoot:()=>(kC(e)?.docsDir??mC).replace(/\\/g,"/").replace(/\/+$/,""),read:n=>{try{let o=hC(n)?n:fC(e,n);return dC(o)?pC(o,"utf8"):null}catch{return null}},pathForArticleId:n=>{try{let o=wC(e,bC(e,t).name);return o?gC(o,n):null}catch{return null}}}}var Yr=(e,t=$C)=>{let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"};function Kr(e){if(!e)return null;let t=!1;for(let n of e.split(`
|
|
423
|
+
`)){let o=n.trimEnd();if(/^\s*(```|~~~)/.test(o)){t=!t;continue}if(t)continue;let r=/^#\s+(\S.*)$/.exec(o);if(r)return Yr(r[1])}return null}var xC=new Set(["a","an","and","as","at","but","by","for","in","of","on","or","the","to","vs","with"]),CC=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 Um(e,t,n){let o=e.toLowerCase();return CC.has(o)?e.toUpperCase():!t&&xC.has(o)?o:!t&&!n?e:e.charAt(0).toUpperCase()+e.slice(1)}var Bm=e=>e.replace(/^\d+[-_.]/,"").split(/[-_]/).filter(Boolean);function RC(e){let t=Bm(e);return t.length===0?e:t.map((n,o)=>Um(n,o===0,!0)).join(" ")}function Hm(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:RC(n[n.length-2])}function qm(e){let t=e.replace(/\\/g,"/").split("/").pop()??e,n=Bm(t.replace(/\.(md|markdown)$/i,""));return n.length===0?t:n.map((o,r)=>Um(o,r===0,!1)).join(" ")}var ct=e=>typeof e=="string"&&e?e:null,SC=e=>typeof e=="string"&&e.length>=8?`id ${e.slice(0,8)}\u2026`:null;function PC(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 TC(e,t){let n=at(e,t,200);return n?`+${n.added} \u2212${n.removed}`:"no change"}var EC=new Set(["Edit","MultiEdit","Write"]);function AC(e,t,n,o){if(!EC.has(e))return null;let r=ct(t.file_path);if(!r)return null;let s=PC(r,n),i=o.docsRoot();if(!(s===i||s.startsWith(`${i}/`)))return null;let a=s.slice(i.length+1);if(!a||!yC(a))return null;let l=Hm(a),p=o.read(s),g=S=>Kr(S)??Kr(p)??qm(a);if(e==="Write"){let S=ct(t.content)??"",C=g(S);if(p===null){let T=S.replace(/\n$/,"").split(`
|
|
424
|
+
`).length;return{verb:"Draft",title:C,category:l,note:`new, ${T} lines`}}return{verb:"Rewrite",title:C,category:l,note:TC(p,S)}}let k=Array.isArray(t.edits)?t.edits.map(S=>({from:ct(S.old_string)??"",to:ct(S.new_string)??""})):[{from:ct(t.old_string)??"",to:ct(t.new_string)??""}],v=k.reduce((S,C)=>{let T=at(C.from,C.to,200);return T?{added:S.added+T.added,removed:S.removed+T.removed}:S},{added:0,removed:0}),P=v.added===0&&v.removed===0?"no change":`+${v.added} \u2212${v.removed}`;return{verb:"Update",title:g(k.map(S=>S.to).join(`
|
|
425
|
+
`)),category:l,note:P}}function DC(e,t,n){let o=()=>{let r=ct(t.article_id),s=r?n.pathForArticleId(r):null;return(s?Kr(n.read(s)):null)??(s?qm(s):SC(r)??"article")};switch(e){case"d360_create_article":{let r=ct(t.title);return r?{verb:"Create",title:Yr(r),category:Hm(t.local_path),note:"Document360 draft"}:null}case"d360_update_article":return{verb:"Update",title:ct(t.title)?Yr(ct(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=ct(t.name);return r?{verb:"Create",title:Yr(r),category:null,note:"Document360 category"}:null}case"d360_upload_drive_file":{let r=ct(t.file_path);if(!r)return null;let s=r.replace(/\\/g,"/").split("/").pop()??r;return{verb:"Upload",title:Yr(s),category:null,note:"Document360 Drive",keepResult:!0}}default:return null}}function Ii(e,t,n,o,r=vC(n,o)){try{let s="mcp__document360__";return e.startsWith(s)?DC(e.slice(s.length),t,r):AC(e,t,n,r)}catch{return null}}var NC={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"},Vm=160,cu=200,Ym=40;function un(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function Gm(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}: ${un(typeof r=="string"?r:JSON.stringify(r),Ym)}`);return t.length>4&&n.push("\u2026"),un(n.join(", "),Vm)}var jC=new Set(["file_path","notebook_path"]);function IC(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 Km=e=>typeof e=="string"&&e?e:null;function LC(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});return e==="d360_sync_status"?n("Check sync status",null):null}function Li(e,t,n){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,s="",...i]=e.split("__"),a=i.join("__");if(s==="document360"){let g=LC(a,t);if(g)return g}let l=a.replace(/^d360_/,"").replace(/_/g," ");return{title:`${s==="document360"?"Document360":s.charAt(0).toUpperCase()+s.slice(1)}: ${l}`,sep:" ",arg:Gm(t)}}let o=NC[e],r=o?t[o]:void 0;if(typeof r=="string"&&r){let s=o&&jC.has(o)?IC(r,n):r;return{title:e,sep:"",arg:un(s,Vm)}}return{title:e,sep:"",arg:Gm(t)}}function OC(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 _C(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(OC).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>un(r,cu))]}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}: ${un(String(r),Ym)}`);return n.length>0?[un(n.join(" \xB7 "),cu)]:null}return null}function MC(e){let t=Km(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function FC(e,t,n){switch(e){case"d360_create_article":{let o=MC(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=Km(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 ${un(o[0],120)}`:""}`]}default:return null}}var zm=new Set(["Edit","Write","MultiEdit","NotebookEdit"]);function WC(e){return e.replace(/^\s*\d+\t/,"")}function UC(e,t){if(zm.has(e))return[];let n=t.split(`
|
|
426
|
+
`);if(e==="Read"){let o=n.length,r=Kr(n.map(WC).join(`
|
|
427
|
+
`));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 Oi(e,t=4,n,o){let r=e.replace(/\r\n/g,`
|
|
428
|
+
`).trimEnd();if(n&&zm.has(n))return{lines:[],hidden:0};if(!r)return{lines:["(no output)"],hidden:0};if(n&&!n.startsWith("mcp__")){let i=UC(n,r);if(i)return{lines:i,hidden:0}}if(n?.startsWith("mcp__document360__")){let i=FC(n.slice(18),o,r);if(i)return{lines:i,hidden:0}}let s=_C(r)??r.split(`
|
|
429
|
+
`);return{lines:s.slice(0,t).map(i=>un(i,cu)),hidden:Math.max(0,s.length-t)}}function _i(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function Mi(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 Xm(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 Fi(e){return Xm(e,"url")}function Wi(e){return Xm(e,"preview_url")}var tg=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/,du=null;function Jm(){return du===null&&(du=QC().verboseTranscript===!0),du}function dR(e,t,n,o){if(tg.test(e))try{let r=eg(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,i=Mi(t,n),a=Fi(n);e.endsWith("publish_article")&&a&&console.log(K(` \u2B95 Live: ${a}`));let l=Wi(n);l?console.log(K(` \u2B95 Preview: ${l}`)):i&&s&&console.log(K(` \u2B95 Preview: ${_i(r.connection.portalUrl,s,i,r.project.languageCode??"en")}`))}catch{}}async function ng(e=process.cwd(),t="auto",n,o){let r=HC(t);r.kind==="none"&&(console.error(""),console.error(N("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${K("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${K('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${K("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${K("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),pR(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=uu({cwd:e,profileName:n,allowProdWrites:s}),a={uuid:null,firstPrompt:null,titleFired:!1},l=BC({input:process.stdin,output:process.stdout}),p=[],g=null,k=!1;l.on("line",S=>{if(g){let C=g;g=null,C(S)}else p.push(S)}),l.on("close",()=>{if(k=!0,g){let S=g;g=null,S(null)}});function v(){return p.length>0?Promise.resolve(p.shift()):k?Promise.resolve(null):(process.stdout.write(K("> ")),new Promise(S=>{g=S}))}let P={cwd:e,version:o,profileName:n,allowProdWrites:()=>s,restartAgent:()=>{i.close(),i=uu({cwd:e,profileName:n,allowProdWrites:s}),a={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>a.uuid,setPendingName:S=>{a.pendingName=S},setModel:async S=>i.setModel(S),withPausedInput:async S=>{l.pause();try{return await S()}finally{l.resume()}}};try{for(;;){let S=await v();if(S===null)break;let C=S.trim();if(C){if(C.startsWith("/")){let T=Im(C);if(!T)continue;let D=jm[T.name];if(!D){console.log(N(`Unknown command: /${T.name}`)),console.log(y("Type /help for the list."));continue}let I=await D(T.args,P);if(I.kind==="exit")break;if(I.kind==="clear"){P.restartAgent();continue}if(I.kind==="allow-prod"){s=!0,P.restartAgent(),console.log(G("\u2713 Production writes authorized for this session.")),console.log("");continue}if(I.kind==="resume"){i.close(),i=uu({cwd:e,resume:I.uuid,profileName:n,allowProdWrites:s});let O=qC(I.uuid);a={uuid:I.uuid,firstPrompt:O?.firstPrompt??null,titleFired:!0},Zm(I.uuid),console.log(G(`\u2713 Resumed "${I.name}"`)),console.log("");continue}if(I.kind==="forward-to-agent"){a.firstPrompt||(a.firstPrompt=I.display??I.prompt);let O=I.display??"",Y=O.trim().split(/\s+/),fe=Mh(O),ae=fe?aR(e,Fh(O)):[],le=Y[0]==="/screenshot"&&(Y[1]==="verify"||Y[1]==="review"),he=le?Y[2]&&!Y[2].startsWith("--")?[Y[2]]:Er(Ie(e)):[],X=Y[0]==="/catch-up"&&!fe?iR(e):null;if(await pu(i,I.prompt,r,a,e,n),fe)try{sR(e,ae,Ye(fe))}catch{}if(X){let ne=Ai(e,X);ne.cta&&console.log(y(ne.cta.text))}if(Y[0]==="/audit"&&!Y.includes("--auto")&&Hr(e,n),le&&he.length>0)try{for(let ne of Dr(e,he))console.log(ne)}catch{}if(Y[0]==="/push"){let ne=await wo(e,n);ne&&console.log(y(ne))}if((Y[0]==="/catch-up"||Y[0]==="/document")&&(Y.includes("--push")||Y.includes("--publish")))try{let ne=await uR({cwd:e,profileName:n}),{clean:ue,conflicts:Te}=An(ne.entries);ue.length===0?console.log(y("Nothing new to push \u2014 everything is already up to date on Document360.")):await xt(P,ue.map(yt=>yt.path),Te.length,{skipReview:Y.includes(it)})}catch(ne){console.log(H(`Couldn't check what to push (${ne.message}) \u2014 your drafts are saved; run /push when ready.`))}}else I.kind==="continue"&&I.ownNext||hR(e,n);continue}if(tR(C)){let T=nR(C);if(T){try{oR(e,{title:T,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}a.firstPrompt||(a.firstPrompt=C),await pu(i,`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${T}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${T}" and the article path(s) you wrote.`,r,a,e,n);continue}}a.firstPrompt||(a.firstPrompt=C),await pu(i,C,r,a,e,n)}}}finally{i.close(),l.close()}}function pR(e,t){console.log(""),console.log(rr("document360-writer")),console.log(y(` cwd: ${e}`));let n=zC(e);if(console.log(y(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(fR(e,t)),!XC(e))console.log(H(" First run: /init (scaffolds config + prints the builder hand-off prompt) \u2192 /login, then ask me to write the docs."));else{let o=!1;try{if(Es(e),!Ot(e))for(let r of As(e))console.log(H(` ${r}`))}catch{}try{let r=JC(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=rR(e);for(let s of Rs(r.applied))console.log(H(` ${s}`));if(r.reopenedForRedaction)for(let s of Ss(r.reopenedForRedaction).split(/\r?\n/))console.log(H(` ${s}`))}catch{}try{let r=Vr(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:o}),s=r?Gr(r,{pickable:!1}):null;if(s?.kind==="recommend"&&s.rec.note){let i=s.rec.tone==="warn"?H:y;for(let a of Ga(s.rec.note).split(`
|
|
430
|
+
`))console.log(i(` ${a}`));s.rec.picker&&console.log(K(` 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 hR(e,t){try{let n=Vr(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:!1}),o=n?Gr(n):null;o?.kind==="recommend"&&o.rec.lead&&console.log(y(` Next: ${qr(o.rec.lead)}`))}catch{}}function fR(e,t){try{let n=eg(e,t),o=n.production?H(" \u26A0 PRODUCTION"):"",r=eR(n.name);if(!r)return y(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...Qm(r.idToken)??{},...Qm(r.accessToken)??{}},i=s.email??s.preferred_username??"signed in";return ZC(r)&&!r.refreshToken?H(` 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 mR(){console.error(""),console.error(`Sign in with your Claude subscription: run ${K("claude")} once, then retry.`),console.error(` (No Claude Code? ${K("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${K("https://console.anthropic.com/settings/keys")}`)}function gR(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;YC({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 yR(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||KC(o,t).then(r=>{r&&GC(n,r)}).catch(()=>{})}async function pu(e,t,n,o,r,s){let i=new Map,a=!1;for await(let l of e.send(t))l.type==="tool"&&tg.test(l.name)&&(a=!0),wR(l,o,r,n,i,s);if(a)try{let l=cR(await lR({cwd:r,profileName:s}));l&&console.log(l.startsWith("\u26A0")?H(l):l)}catch{}}function wR(e,t,n,o,r,s){switch(e.type){case"session":t.uuid||gR(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let i=Jm()?null:Ii(e.name,e.input,n,s);if(i){process.stdout.write(`
|
|
431
|
+
|
|
432
|
+
`);let l=[i.category,i.note].filter(g=>!!g).map(g=>$e(` \xB7 ${g}`)),p=i.loud?$e(" \xB7 ")+We(H(i.loud)):"";console.log(`${G("\u25CF")} ${K(We(qa(i.verb)))}${We(i.title)}${l.join("")}${p}`),r.set(e.id,{name:e.name,input:e.input,doc:!0,keepResult:i.keepResult});break}let a=Li(e.name,e.input,process.cwd());a&&(process.stdout.write(`
|
|
433
|
+
|
|
434
|
+
`),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=at(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}:Oi(e.output,4,e.isError||Jm()?void 0:i.name,i.input),p=e.isError?N:$e;l.lines.forEach((g,k)=>console.log(p((k===0?" \u23BF ":" ")+g))),l.hidden>0&&console.log(y(` \u2026 +${l.hidden} lines`)),e.isError||dR(i.name,i.input,e.output,n);break}case"result":{process.stdout.write(`
|
|
435
|
+
`);let i=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(y(` (${ur(i)}\u2192${ur(e.outputTokens)} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(Zm(t.uuid),t.titleFired||yR(t,n));break}case"error":console.error(""),e.kind==="limit"?console.log(H(`\u23F3 ${e.message}`)):console.error(N(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&mR();break}}import{render as QS}from"ink";import{resolveAuth as JS}from"document360-engine";import{useCallback as J,useEffect as tt,useMemo as vu,useRef as se,useState as te}from"react";import{Box as xe,Text as U,useApp as HR,useInput as qR,useStdout as GR}from"ink";import{existsSync as Ao,readFileSync as zi,readdirSync as VR,writeFileSync as YR}from"node:fs";import{basename as Qr,dirname as KR,isAbsolute as zR,join as xu}from"node:path";import{createSession as Hg,classifyClaudeAuth as Au,CLAUDE_CODE_SETUP_HINT as XR,loginPkce as QR,toStoredTokens as JR,saveTokens as ZR,getAccessToken as eS,resolveActiveProfile as ut,resolveProjectId as tS,getArticle as nS,decodeJwtClaims as Oo,isExpired as pn,loadTokens as Fn,clearTokens as oS,clearProfileProject as rS,setTitle as sS,slugify as iS,touchSession as Cu,upsertSession as aS,generateTitle as qg,findByName as lS,listSessions as cS,renameSession as uS,suggestNextAction as dS,readProjectConfig as ge,writeProjectConfig as Gg,readUserConfig as Vg,writeUserConfig as pS,resolveAndPersistAppType as hS,detectAppType as Yg,resolveModelSetting as Du,loadProfileMap as Kg,applyPull as Xi,computeSyncStatus as Qi,lintDocs as Ji,compareRemoteSources as fS,planPull as zg,establishBaselines as mS,rebaselineServerMeta as gS,inventoryRepo as yS,knownEnvironments as wS,currentEnvironments as Xg,sunsetEnvironment as Qg,resolveEnvironment as kS,planPartitions as Ru,partitionEvenly as bS,screenshotPlaceholderIds as $S,trackedArticlePaths as vS,runPartitioned as Do,estimateBulkCost as Jg,resolveModelForOperation as No,readDocsPlan as Zg,checkForUpdate as xS,detectInstallKind as CS,isSelfUpdatable as RS,devHintsGuidePath as ey,toolFeedbackPath as ty,reconcileToolFeedback as SS,reconcileUpgradeActions as PS,stampArticles as jo,snapshotArticles as TS,listArticleFiles as ny,CONTENT_CAP_VERSION as ES,ENGINE_VERSION as uy,DEFAULT_DOCS_DIR as Nu,setProfileProject as AS,writeCrashLog as DS,applyStructureOrder as Su,orderSyncLine as Pu,applyRelatedArticles as oy,relatedSyncLine as ry,reconcileDocsGit as NS,shareExplainedPath as jS,ensureDir as IS}from"document360-engine";pr();nn();import{spawn as og}from"node:child_process";function kR(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function bR(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?og([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):og(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 hu(e){for(let[t,n]of kR())if(await bR(t,n,e))return!0;return!1}var rg=/\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 $R(e){let t=e.replace(/\s+$/,"").split(`
|
|
436
|
+
`),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 sg(e){let t=e.trimEnd();if(!t)return null;let n=$R(t);return n>=2?{options:n}:/\?[\s*_"')\]]*$/.test(t)||rg.test(t)?{options:0}:null}function fu(e,t){if(t.closed)return e;let n=e.split(`
|
|
437
|
+
`),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){rg.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(`
|
|
438
|
+
`)}var vR={la:"local","l all":"local","local all":"local",pa:"portal","p all":"portal","portal all":"portal",sa:"skip","s all":"skip","skip all":"skip"},xR={L:"local",P:"portal",S:"skip"},CR={ya:"write","y all":"write","yes all":"write",na:"skip","n all":"skip","no all":"skip"},RR={Y:"write",N:"skip"};function ig(e,t,n){let o=e.trim(),r=o.toLowerCase().replace(/\s+/g," ");return t[r]??(o.length===1?n[o]??null:null)}function ag(e){return ig(e,vR,xR)}function lg(e){return ig(e,CR,RR)}function mu(e,t){let n=t?.max??12,o=t?.chrome??8;return Math.max(3,Math.min(n,(e??24)-o))}function Ui(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 cg(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 SR,mkdirSync as PR,readFileSync as TR,writeFileSync as ER}from"node:fs";import{join as ug}from"node:path";import{writerDir as AR}from"document360-engine";function dg(e){return ug(AR(e),".sessions")}function pg(e,t){return ug(dg(e),`${t}.json`)}function hg(e,t,n){try{PR(dg(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");ER(pg(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function gu(e,t){try{let n=pg(e,t);if(!SR(n))return[];let o=JSON.parse(TR(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var DR=e=>`\x1B]0;${e}\x07`,NR=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function fg(e){process.stdout.isTTY&&process.stdout.write(e)}function To(e){fg(DR(e))}function Bi(e){fg(NR(e))}var Hi=["\xB7 "," \xB7"],qi="\u{1F7E3}";mi();var mg=()=>({fingerprint:null,counts:null,settled:0,spokenBaseline:null,lastSpokeAt:null,awaySince:null}),jR={hints:0,requests:0,answers:0,directives:0};function yu(e,t){let n=e??jR;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 Gi=e=>e.hints===0&&e.requests===0&&e.answers===0&&e.directives===0,gg=e=>e.hints+e.requests+e.answers+e.directives,wu=(e,t)=>e-t>=6e5;function yg(e){let{now:t,lastInputAt:n,fingerprint:o,counts:r,occupied:s,prev:i}=e,a=wu(t,n),p=i.fingerprint!==null&&i.fingerprint!==o?0:i.settled+1,g={...i,fingerprint:o,counts:r,settled:p,awaySince:a?i.awaySince??t:null,spokenBaseline:i.spokenBaseline??r};if(a){let v=yu(g.spokenBaseline,r);return{memory:g,speak:null,waiting:Gi(v)?null:v}}if(s)return{memory:g,speak:null,waiting:null};if(p<2)return{memory:g,speak:null,waiting:null};let k=yu(i.spokenBaseline,r);return Gi(k)?{memory:g,speak:null,waiting:null}:i.lastSpokeAt!==null&&t-i.lastSpokeAt<6e5?{memory:g,speak:null,waiting:null}:{memory:{...g,spokenBaseline:r,lastSpokeAt:t,settled:p},speak:k,waiting:null}}function wg(e,t,n){if(e.awaySince===null)return{kind:"none",memory:e};let o=t-e.awaySince,r=yu(e.spokenBaseline,n),s={...e,awaySince:null,counts:n,spokenBaseline:n,lastSpokeAt:Gi(r)?e.lastSpokeAt:t};return Gi(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 ku(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 kg(e){return`\u{1F4E5} ${zr(e)} just arrived from your builder \u2014 /catch-up folds ${gg(e)===1?"it":"them"} into the docs.`}function bg(e,t){return`\u{1F4E5} While you were away (${ku(t)}): ${zr(e)} from your builder \u2014 /catch-up folds ${gg(e)===1?"it":"them"} into the docs.`}function $g(e){return`\u{1F4E5} ${zr(e)} waiting from your builder \xB7 tab to run /catch-up\u2026`}js();import{publishGateVerdict as Tu,publishGateLines as Eu,SKIP_STYLE_FLAG as sy}from"document360-engine";ee();import{Box as Xr,Text as Se}from"ink";import{jsx as Pe,jsxs as Eo}from"react/jsx-runtime";function IR({row:e,nameW:t,width:n}){let o=s=>Pa(s,n),r=(s,i)=>Pe(Xr,{flexDirection:"column",children:s.map(i)});switch(e.t){case"head":return r(o(e.s),(s,i)=>Pe(Se,{color:Z,bold:!0,children:s},i));case"text":return r(o(e.s),(s,i)=>Pe(Se,{children:s},i));case"dim":return r(o(e.s),(s,i)=>Pe(Se,{dimColor:!0,children:s},i));case"sub":return r(o(e.s),(s,i)=>Pe(Se,{bold:!0,dimColor:!0,children:s},i));case"good":return r(o(e.s),(s,i)=>Pe(Se,{color:"green",children:s},i));case"step":{let s=o(`${e.n}. ${e.s}`);return Pe(Xr,{flexDirection:"column",children:s.map((i,a)=>a===0?Eo(Se,{children:[Pe(Se,{color:Z,children:`${e.n}. `}),i.slice(`${e.n}. `.length)]},a):Pe(Se,{children:i},a))})}case"cmd":{let s=Ps(e.name,e.s,t,n),i=s.descLines.slice(s.nameOwnLine?0:1);return Eo(Xr,{flexDirection:"column",children:[Eo(Se,{children:[" ",Pe(Se,{color:Z,children:s.nameCell}),!s.nameOwnLine&&Pe(Se,{dimColor:!0,children:` ${s.descLines[0]??""}`})]}),i.map((a,l)=>Pe(Se,{dimColor:!0,children:`${s.indent}${a}`},l))]})}case"gap":return Pe(Se,{children:" "})}}function vg({tab:e,scroll:t,rows:n,width:o,version:r,engineVersion:s}){let i=Je[e]??Je[0],a=Sa(i.rows),l=Math.max(20,o-2),p=6+Je.reduce((T,D)=>T+D.label.length+4,0),g="\u2500".repeat(Math.min(p,l)),k=`\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}`,v=_d({rows:n,inner:l,barWidth:p,footerWidth:k.length}),{visible:P,above:S,below:C}=Od(i.rows,{width:o,budget:v,scroll:t,nameW:a});return Eo(Xr,{flexDirection:"column",paddingX:1,children:[Eo(Se,{children:[Pe(Se,{color:Z,bold:!0,children:"Help "}),Je.map((T,D)=>D===e?Pe(Se,{color:"white",backgroundColor:Z,bold:!0,children:` ${T.label} `},T.key):Pe(Se,{dimColor:!0,children:` ${T.label} `},T.key))]}),Pe(Se,{color:Z,children:g}),Eo(Xr,{flexDirection:"column",marginTop:1,children:[S>0?Pe(Se,{dimColor:!0,children:`\u22EF ${S} more above`}):null,P.map((T,D)=>Pe(IR,{row:T,nameW:a,width:o},S+D)),C>0?Pe(Se,{dimColor:!0,children:`\u22EF ${C} more below`}):null]}),Pe(Se,{dimColor:!0,children:`
|
|
439
|
+
\u2190/\u2192 or tab switch \xB7 1-5 jump${S+C>0?" \xB7 \u2191\u2193 scroll":""} \xB7 esc close \xB7 d360-writer v${r} \xB7 engine v${s}`})]})}var LR=/^(?:\d+[.)]|[-*•])\s+/;function xg(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
|
|
440
|
+
`)){let i=s.trim().replace(LR,""),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}ee();function _n(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function Be(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function Cg(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var OR=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function Rg(e,t,n){if(!OR.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 bu(e){return e.replace(/^[\w.-]+\//,"")}var Vi=16,Sg={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function Mn(e){return typeof e=="string"?e:e.cmd}function Pg(e){return typeof e=="string"?void 0:e.desc}function $u(e){return e.trim().split(/\s+/).slice(1).join(" ")}function Tg(e,t){let n=$u(t);return e.some(r=>Mn(r).trim()===t.trim()||!!n&&$u(Mn(r))===n)?e.filter(r=>Mn(r).trim()!==t.trim()&&!(n&&$u(Mn(r))===n)):[]}import{isDirectiveMention as LS,stripDirectiveMention as OS,appendDirective as _S,reconcileTestidRequest as MS,builderChannelWired as FS,pendingFingerprint as WS}from"document360-engine";var _R=/\[Pasted text #\d+ \+\d+ lines?\]/g;function Eg(e){return e.replace(/\r\n?/g,`
|
|
441
|
+
`)}function Ag(e){return e.includes(`
|
|
442
|
+
`)||e.length>200}function Dg(e,t){let n=t.split(`
|
|
443
|
+
`).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function Ng(e,t){return e.replace(_R,n=>t.get(n)??n)}function jg(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function Yi(e,t){let n=Math.max(1,t),o=[],r=0;for(let s of e.split(`
|
|
444
|
+
`)){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 Ki(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function Ig(e,t,n){let o=Ki(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 Lg(e,t,n){let o=e[Ki(e,t)];return n==="start"?o.start:o.end}var MR=new Set(["Edit","Write","MultiEdit","NotebookEdit"]),Og={hint:"hint",message:"message",state:"state file",roadmap:"roadmap",directive:"directives",feedback:"tool-feedback"},FR=new Set(["hint","message","state"]),WR=["hint","message","roadmap","directive","feedback","state"];function UR(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 _g(e,t){let n=e==="Read"?"read":MR.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=UR(r.slice(i+s.length));return a?{category:a,verb:n,path:r}:null}function Mg(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 WR)for(let s of["updated","read"]){let i=t.get(`${r}:${s}`)?.size??0;i!==0&&o.push(FR.has(r)?`${i} ${Og[r]}${i===1?"":"s"} ${s}`:`${Og[r]} ${s}`)}return o.length>0?o.join(" \xB7 "):null}function Fg(e,t,n){let o=Math.max(1,n),r=e.split(`
|
|
443
445
|
`),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(`
|
|
444
|
-
`),truncated:i>0||l>0}}}return{text:e,truncated:!1}}function
|
|
445
|
-
`)){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
|
|
446
|
+
`),truncated:i>0||l>0}}}return{text:e,truncated:!1}}function Wg(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 Ug(e){let t=!1,n=0,o=0;for(let r of e.split(`
|
|
447
|
+
`)){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 Lo,jsx as F,jsxs as oe}from"react/jsx-runtime";var US={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL",auto:"auto \u2014 right-sized for docs \xB7 /model to change"},iy=` 1. /init \u2014 pick your Document360 environment & scaffold config
|
|
446
448
|
2. /login \u2014 sign in & pick your Document360 project (workspace auto-selected)
|
|
447
|
-
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function
|
|
448
|
-
`).length+1,console.log(d)},[
|
|
449
|
-
`)}catch{}u.picker&&(ue(u.picker.options.map(
|
|
450
|
-
`)}),
|
|
451
|
-
${
|
|
449
|
+
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function BS(e,t,n,o){let r=Au(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=Du(e),a=ge(e),l=(a?.docsDir??Nu).replace(/\/+$/,""),p=a?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${l}/ + config`,g={version:t,engineVersion:uy,captureVersion:Mt(),claude:s,model:i.model,modelSource:US[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 g;try{let k=ut(e,o);g.profile=k.name,g.apiUrl=k.connection.apiUrl,g.prod=k.production,g.project=k.project.projectName??k.project.projectId??"(chosen at login)";let v=Fn(k.name);if(v){let P={...Oo(v.idToken)??{},...Oo(v.accessToken)??{}},S=P.email??P.preferred_username??"signed in";pn(v)?v.refreshToken&&(g.who=S,g.loggedOut=!1,g.sessionHint="session expired \u2014 refreshing\u2026"):(g.who=S,g.loggedOut=!1,g.sessionHint=`session valid until ${new Date(v.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return g}function HS(e,t){try{let n=ut(e,t),o=Fn(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...Oo(o.idToken)??{},...Oo(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return pn(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 ay=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],_o=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],qS="Ask me to write or update an article\u2026";function Io({ch:e,dim:t}){let[n,o]=te(!0);return tt(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),F(U,{inverse:n,color:t&&!n?"gray":void 0,children:e})}function dn({rows:e,cursor:t,cap:n,render:o}){let r=Ui(e.length,t,n);return oe(Lo,{children:[r.above>0?F(U,{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?F(U,{color:"gray",children:` \u22EF ${r.below} more below`}):null]})}var ly=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function cy(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var GS=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function VS({startTime:e,chars:t}){let[n,o]=te(0),r=se(Date.now());tt(()=>{let p=setInterval(()=>o(g=>g+1),120);return()=>clearInterval(p)},[]);let s=_o[n%_o.length],i=ay[Math.floor(n/16)%ay.length],a=vp(e,r.current,Date.now()),l=Math.round(t/4);return oe(xe,{children:[F(U,{color:Z,children:` ${s} ${i}\u2026 `}),F(U,{color:"gray",children:`(${dr(a)} \xB7 ~${l} tokens \xB7 esc to interrupt)`})]})}function YS({text:e}){let[t,n]=te(0);return tt(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),F(xe,{paddingX:1,children:F(U,{color:Z,children:`${_o[t%_o.length]} ${e}`})})}var KS=12e4;function zS({p:e}){let[t,n]=te(0);tt(()=>{let T=setInterval(()=>n(D=>D+1),150);return()=>clearInterval(T)},[]);let o=_o[t%_o.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>=KS,l=e.verb??"Converting",p=e.unit??"article",g=e.rows.reduce((T,D)=>T+D.items,0),k=l.toLowerCase(),v=e.rows,P=0;if(v.length>Vi){let T=v.findIndex(I=>I.status==="active"||I.status==="pending"),D=Math.max(0,Math.min(T-2,v.length-Vi));P=v.slice(0,D).filter(I=>I.status==="done").length,v=v.slice(D,D+Vi)}let S=Math.min(40,Math.max(...v.map(T=>bu(T.label).length),0)),C=T=>T==="failed"?"red":T==="active"?Z:void 0;return oe(xe,{flexDirection:"column",children:[oe(xe,{children:[F(U,{color:Z,children:` ${o} ${l} ${g} ${p}${g===1?"":"s"} `}),F(U,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${i} tokens \xB7 ${dr(r)} \xB7 esc to stop`})]}),P>0&&F(U,{dimColor:!0,children:` \u2714 +${P} done`}),v.map(T=>oe(U,{color:C(T.status),dimColor:T.status==="done"||T.status==="pending",children:[` ${Sg[T.status]} ${bu(T.label).padEnd(S)}`,T.status==="active"&&T.itemsDone!==void 0?` (${T.itemsDone}/${T.items} ${p}${T.items===1?"":"s"})`:T.status!=="pending"?` (${T.items} ${p}${T.items===1?"":"s"})`:"",T.status==="active"?` \u2190 ${k}\u2026`:""]},T.label)),a&&F(U,{color:"yellow",children:` \u26A0 no activity for ${dr(s)} \u2014 press esc to stop if it's wedged`})]})}var XS=10800*1e3;function dy({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=HR(),[s,i]=te(n),[a,l]=te(null),[p,g]=te({text:"",pos:0}),k=p.text,v=J(u=>{g(d=>{let c=typeof u=="function"?u(d.text):u;return{text:c,pos:c.length}})},[]),P=J(u=>{g(d=>({text:d.text.slice(0,d.pos)+u+d.text.slice(d.pos),pos:d.pos+u.length}))},[]),S=J(()=>{g(u=>{if(u.pos===0)return u;let d=u.text.slice(0,u.pos),c=jg(d)??d.slice(0,-1);return{text:c+u.text.slice(u.pos),pos:c.length}})},[]),[C,T]=te(!1),[D,I]=te(!1),[O,Y]=te(0),[fe,ae]=te(!1),[le,he]=te(null),[ce,X]=te(null),[ne,ue]=te([]),Te=se(!1),yt=se(!1),St=se(null),Wt=se(!1),[nt,Wn]=te(!1),Ke=se(0),[hn,Ut]=te(!1),[De,Pt]=te(!1),[Mo,Ou]=te(null),[wy,Bt]=te(0),Tt=se(0),[ea,Un]=te(0),[Bn,Jr]=te(null),_u=se(new Map),ky=se(0),Hn=se([]),dt=se(null);dt.current===null&&(dt.current=Hg({cwd:e,profileName:s,allowProdWrites:!1}));let Et=se({uuid:null,firstPrompt:null,titleFired:!1}),Fo=se(new Map),Mu=se(null),Zr=se(Vg().verboseTranscript===!0),Ht=se(!1),ta=se([]),Ce=se([]),fn=se([]),Wo=se(null),[Fu,mn]=te(null),na=se(null),[gn,yn]=te(null),[qt,qn]=te(null),[Gt,Gn]=te(null),[ze,Vn]=te(null),[pt,wn]=te(null),[At,Yn]=te(null),[Vt,Kn]=te(null),[Yt,kn]=te(null),[Dt,Nt]=te(null),[Le,Uo]=te(null),Wu=se({value:0,at:0}),[wt,bn]=te(null),[Uu,zn]=te(null),[ot,$n]=te(null),[Xe,Xn]=te(null),[Bu,oa]=te([]),vn=se([]),Bo=se(!1),Ee=se(null),[Ho,de]=te(null),[Hu,je]=te(null),es=se(!1),qo=se(null),Go=se(null),[rt,xn]=te(null),[Vo,Cn]=te(null),Yo=!!(Gt||ze||pt||At||Vt||Yt||Dt||Le||wt||ot||Xe||rt||Vo),[qu,Kt]=te(0),[Gu,zt]=te(0),[by,Vu]=te(0),ra=vu(()=>{try{let u=Du(e);return u.source==="auto"?`${u.model} (auto)`:u.model}catch{return null}},[e,by]),{stdout:Oe}=GR(),[,$y]=te(0),Yu=se(`${Oe.columns??80}x${Oe.rows??24}`),_e=J(()=>Math.max(20,(Oe.columns??80)-1),[Oe]),ts=J(u=>{Hn.current.push(u);let d=Va(u,_e());Qn.current+=d.split(`
|
|
450
|
+
`).length+1,console.log(d)},[_e]),sa=se([]),ns=J(()=>{let u=sa.current;if(u.length===0)return;sa.current=[];let d=Mg(u);d&&ts({kind:"note",tone:"info",text:`\u25CF Housekeeping ${d}`})},[ts]),h=J(u=>{ns(),ts(u)},[ts,ns]),He=se({printed:[],armed:[],printedAt:0}),Qn=se(0),qe=J((u,d)=>{Ke.current++,He.current.armed=[],he(u),X(d??null)},[]),kt=J(()=>{Ke.current++,He.current.armed=[],he(null),X(null)},[]),os=J(u=>{Ke.current++,He.current.armed=[],he(null),X(u)},[]),Q=J(u=>qe(u,Po({kind:"cmd",cmd:u,reason:""})),[qe]),jt=J((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 E=jS(e);IS(KR(E)),YR(E,`${new Date().toISOString()}
|
|
451
|
+
`)}catch{}u.picker&&(ue(u.picker.options.map(E=>({cmd:E.cmd,desc:E.desc}))),zn(u.picker.title)),!d?.silent&&u.note&&(He.current.printed=u.menu,He.current.printedAt=Qn.current);let w=Qn.current-He.current.printedAt<Math.max(8,(Oe.rows??24)-4)&&Lm(He.current.printed,u.menu)?u.menu:[];u.lead&&(u.lead.kind==="answer"?os(Po(u.lead,w.length)):qe(u.lead.kind==="cmd"?u.lead.cmd:u.lead.text,Po(u.lead,w.length))),He.current.armed=w},[h,qe,os,e,Oe]),Ae=J((u,d,c="info")=>{He.current.armed=[],u&&h({kind:"note",tone:c,text:u}),d&&(d.kind==="answer"?os(Po(d)):qe(d.kind==="cmd"?d.cmd:d.text,Po(d)))},[h,qe,os]),Ko=J((u,d,c,w="info")=>{if(u.producedNothing){Ae("Nothing was changed \u2014 the agent produced no output, so this command did nothing at all.",{kind:"cmd",cmd:"/doctor",reason:"it checks Claude sign-in + whether the model is reachable from this machine"},"warn");return}Ae(d,c,w)},[Ae]),[zo,ia]=te(null),[vy,Ku]=te(!1),Xt=J((u,d)=>{ia(u),Ku(!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]),aa=J(()=>{MS(e,new Date().toISOString());let u=Uf(e);u&&(h({kind:"note",tone:"info",text:u.lines.join(`
|
|
452
|
+
`)}),Xt(u.prompt,FS(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,Xt]),la=se(!1),ca=J(async()=>{try{if(la.current||!RS(CS())||ge(e)?.mode==="engineer")return;let u=await xS({pkg:Ro,currentVersion:o,force:!0});if(!u.updateAvailable||!u.latest)return;la.current=!0,h({kind:"note",tone:"info",text:`\u2B06 Updating ${Ro} ${u.current} \u2192 ${u.latest}\u2026 (wait for the \u2713 before you /exit)`}),Pt(!0),(await xi().finally(()=>Pt(!1))).ok?(h({kind:"note",tone:"ok",text:`\u2713 Updated to v${u.latest} \u2014 run /exit, then relaunch to apply.`}),Q("/exit"),Ou(u.latest)):h({kind:"note",tone:"warn",text:`Update available (v${u.latest}) but auto-update failed \u2014 run: ${vi}`})}catch{}},[e,o,h,Q]),Xo=se(!1),ua=se(null),zu=J(async u=>{if(!Xo.current)try{let d=ge(e);if(!d)return;let c=Xu.current;if(!c)return;if(c.pushConsent!=="on"){if(c.uncommitted===0)return;Xo.current=!0;try{let E=await NS(e,d);if(E.commit?.ok)ua.current=null;else if(E.commit&&!E.commit.ok){let B=`${E.commit.reason}:${E.commit.detail??""}`;ua.current!==B&&(ua.current=B,h({kind:"note",tone:"warn",text:`\u26A0 Couldn't save your docs work to git \u2014 ${cn(E.commit.reason,E.commit.detail)}`}))}}finally{Xo.current=!1}return}if(c.uncommitted===0&&c.unpushed===0&&!u.pull)return;Xo.current=!0;try{let{lines:E,changed:B}=await ki(e,d);for(let m of E)m.tone==="warn"||m.tone==="error"?h({kind:"note",tone:m.tone,text:m.text}):m.text.includes("\u2B07")&&h({kind:"note",tone:m.tone,text:m.text});B&&Y(m=>m+1)}finally{Xo.current=!1}}catch{}},[e,h]),Jn=J(u=>{let d=Ue(e,s);return d.ok?!0:(h({kind:"note",tone:"warn",text:d.reason}),Go.current=u,Q("/login"),!1)},[e,s,h,Q]),[rs,da]=te(null),Xu=se(null),ht=J((u,d)=>{let c=Vr(e,s,{claudeMissing:Au(t).state==="missing",allowAutoAudit:u,genreUnknown:Wt.current,pendingAnswer:St.current});return Xu.current=c?.handoff??null,c?Gr(c,{header:d,pickable:!0}):{kind:"idle"}},[e,s,t]),pa=se(Date.now()),Qo=se(mg()),Qu=se(0),[Ju,Zu]=te(null),Jo=se(!0),Zn=se(!1),ss=se(0),Zo=se(0);tt(()=>{let u=setInterval(()=>{if(Jo.current){ss.current=0,Zo.current=0;return}if(!C)try{if(!Ao(ey(e)))return;if(mt(e).status==="current"){Jo.current=!0,ss.current=0,Zo.current=0;let c=Zn.current?`\u2713 Your builder finished the protocol update (v${Re}) \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:",w=ht(!1,c),E=w.kind==="recommend"?w.rec:null;ia(null),E?.note?jt(E,{tone:"ok"}):(h({kind:"note",tone:"ok",text:`${c}${E?.lead?` ${qr(E.lead)}`:""}`}),E?.lead||E?.picker?jt(E,{silent:!0}):Zn.current||qe("write the docs for this repo")),Y(B=>B+1);return}if(Zn.current)return;ss.current+=1;let d=ss.current;if((d===4||d%15===0)&&Zo.current<3){Zo.current+=1;let c=Zo.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";h({kind:"note",tone:"info",text:Ot(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,ht,jt,qe]),tt(()=>{let u=Fu??Qr(e);if(!C){Bi(0),To(`${qi} ${u}`);return}Bi(3);let d=0;To(`${Hi[0]} ${u}`);let c=setInterval(()=>{d=(d+1)%Hi.length,To(`${Hi[d]} ${u}`)},400);return()=>clearInterval(c)},[C,e,Fu]),tt(()=>()=>Bi(0),[]),tt(()=>{let u=performance.now(),d=[],c=(f,$)=>{let b=performance.now();try{return $()}finally{let R=Math.round(performance.now()-b);R>=80&&d.push(`${f}: ${R}ms`)}};h({kind:"banner",info:c("banner",()=>BS(e,o,t,s))});let w=Au(t).state==="missing";if(w&&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.
|
|
453
|
+
${XR}
|
|
452
454
|
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:
|
|
453
|
-
${
|
|
454
|
-
`)}),
|
|
455
|
-
`)}),f.reopenedForRedaction&&h({kind:"note",tone:"warn",text:
|
|
455
|
+
${iy}`}),Q(w?"/doctor":"/init");return}w&&Q("/doctor");try{let f=ut(e,s),$=Fn(f.name);$&&pn($)&&$.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."}),Q("/login")}):(!$||pn($))&&(h({kind:"note",tone:"warn",text:`Profile "${f.name}" is not signed in \u2014 sign in with /login.`}),Q("/login"))}catch{}try{let f=ge(e),$=ut(e,s),b=Fn($.name);f&&b&&!pn(b)&&au(e,f.authoritativeSourceFiles)&&!lu(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."}),Q("/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)&&(Wt.current=!0)}catch{}let E=mt(e);try{if(c("reconcile-devhints",()=>Es(e)),E.status!=="current"&&!Ot(e)){let f=As(e);f.length&&(h({kind:"note",tone:"warn",text:f.join(`
|
|
456
|
+
`)}),Xt(Pn()),Jo.current=!1,Zn.current=!1)}}catch{}try{let f=c("reconcile-feedback",()=>SS(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",()=>PS(e));f.applied.length>0&&h({kind:"note",tone:"warn",text:Rs(f.applied).join(`
|
|
457
|
+
`)}),f.reopenedForRedaction&&h({kind:"note",tone:"warn",text:Ss(f.reopenedForRedaction)})}catch{}let B=c("ready-decision",()=>ht(!0));B.kind==="autoAudit"?(h({kind:"note",tone:"info",text:B.note}),br().then(f=>{f.kind!=="forward-to-agent"||!f.prompt||ye(f.prompt,{display:f.display,quietUser:!0}).then($=>{$.producedNothing||(Hr(e,s),Y(b=>b+1))})})):B.kind==="recommend"&&jt(B.rec);let m=Math.round(performance.now()-u);m>=800&&DS({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${m}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${d.length?d.join(`
|
|
456
458
|
`):"no single phase \u226580ms"}
|
|
457
|
-
cwd: ${e}`}),
|
|
458
|
-
|
|
459
|
-
${
|
|
460
|
-
`)}),
|
|
461
|
-
`)});let
|
|
462
|
-
`)}),[h]),
|
|
463
|
-
`)}),!
|
|
464
|
-
`)});let
|
|
465
|
-
`)}),
|
|
466
|
-
`)
|
|
467
|
-
${
|
|
468
|
-
${$}
|
|
469
|
-
${
|
|
470
|
-
`)})
|
|
471
|
-
`)})
|
|
472
|
-
`)})
|
|
473
|
-
`)})
|
|
474
|
-
`)}),
|
|
475
|
-
|
|
476
|
-
`)})),
|
|
477
|
-
`)});return}case"
|
|
478
|
-
`)})
|
|
459
|
+
cwd: ${e}`}),ca(),zu({pull:!0})},[]),tt(()=>{let u=setInterval(()=>{ca()},XS);return()=>clearInterval(u)},[ca]),tt(()=>{let u=setInterval(()=>{try{let d=Date.now(),c=wu(d,pa.current);if(Qu.current+=1,c&&Qu.current%Math.round(3e5/6e4)!==0)return;let w=WS(e),E=Qo.current,B=w===E.fingerprint&&E.counts?E.counts:Ln(e),m=yg({now:d,lastInputAt:pa.current,fingerprint:w,counts:B,occupied:C||fe||ne.length>0||k!==""||Yo||Ce.current.length>0,prev:E});if(Qo.current=m.memory,Zu(m.waiting),m.speak){h({kind:"note",tone:"info",text:kg(m.speak)});let f=ht(!1);f.kind==="recommend"&&jt(f.rec,{silent:!0})}}catch{}},6e4);return()=>clearInterval(u)},[e,C,fe,ne.length,k,Yo,h,ht,jt]),tt(()=>{if(C||fe||Te.current||le!==null||ne.length>0||k!==""||zo!==null||Ce.current.length>0||Wo.current||Yo)return;let u=ht(!1);u.kind==="recommend"&&(u.rec.lead||u.rec.picker)&&jt(u.rec,{silent:!0}),zu({pull:!1})},[C,fe,le,ne,k,zo,Yo,O,ht,nt]),tt(()=>{let u=null,d=null,c=()=>{u&&clearTimeout(u),u=setTimeout(()=>{u=null;let w=`${Oe.columns??80}x${Oe.rows??24}`;w!==Yu.current&&(Yu.current=w,$y(E=>E+1),d&&clearTimeout(d),d=setTimeout(()=>{d=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+xp(Hn.current,_e())+"\x1B[?2026l")},80))},400)};return Oe.on("resize",c),()=>{u&&clearTimeout(u),d&&clearTimeout(d),Oe.off("resize",c)}},[Oe,_e]);let Ge=Math.max(20,(Oe.columns??80)-1),ed=vu(()=>HS(e,s),[e,s,O]),ha=(()=>{if(De)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(Mo!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${Mo?` v${Mo}`:""}\u2026`,isSetup:!0};if(rs)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(zo)return vy?{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(Ju)return{text:$g(Ju),isSetup:!0};if(Ce.current.length>0){let w=Ce.current.length;return Ce.current[0].mode==="conflict"?{text:w>1?`l keep local \xB7 p take portal \xB7 s skip \xB7 la/pa/sa for all ${w}\u2026`:"l keep local \xB7 p take portal \xB7 s skip \xB7 anything else cancels\u2026",isSetup:!0}:{text:w>1?`y to write \xB7 n to skip \xB7 ya/na for all ${w}\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=xu(e,(u.docsDir??Nu).replace(/\/+$/,"")),c=(()=>{try{return Ao(d)&&VR(d).length>0}catch{return!1}})();try{let w=ut(e,s),E=Fn(w.name);if(!(!!E&&!(pn(E)&&!E.refreshToken)))return{text:`Sign in with /login (profile "${w.name}")\u2026`,isSetup:!0};if(!w.project.projectId)return{text:"Sign in to Document360 to pick your project\u2026",isSetup:!0};if(!w.project.workspaceId&&!c)return{text:"Pick a workspace with /workspace\u2026",isSetup:!0}}catch{}return c?{text:qS,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),It=pp(k),td=It.length>0&&!C,xy=12,Lt=mu(Oe.rows),Cy=Oe.rows??24,nd=mu(Oe.rows,{max:xy}),is=Math.min(ea,Math.max(0,It.length-1)),Rn=Ui(It.length,is,nd).start,fa=It.slice(Rn,Rn+nd),ma=a!==null?Fg(a,8,Ge):null,as=ot?ot.paths.filter(u=>!ot.query||u.toLowerCase().includes(ot.query.toLowerCase())).slice(0,8):[],ls=rt?rt.sessions.filter(u=>{let d=rt.query.toLowerCase();return!d||u.name.toLowerCase().includes(d)||u.firstPrompt.toLowerCase().includes(d)}).slice(0,8):[],Ve=J((u,d)=>{dt.current?.close(),dt.current=Hg({cwd:e,resume:u,profileName:d??s,allowProdWrites:Ht.current}),u||(Et.current={uuid:null,firstPrompt:null,titleFired:!1},mn(null)),Kt(0),zt(0)},[e,s]),od=J((u,d,c)=>{if(ly.test(u))try{let w=ut(e,s),E=typeof d.project_id=="string"&&d.project_id||w.project.projectId,B=Mi(d,c),m=[],f=Fi(c);u.endsWith("publish_article")&&f&&m.push(`Live: ${f}`);let $=Wi(c);$?m.push(`Preview: ${$}`):B&&E&&m.push(`Preview: ${_i(w.connection.portalUrl,E,B,w.project.languageCode??"en")}`),m.length>0&&h({kind:"link",lines:m})}catch{}},[e,s,h]),ye=J(async(u,d)=>{Ut(!0),Te.current=!1,yt.current=!1,St.current=null,kt(),ue([]),zn(null),ia(null);let c=Ke.current;if(d?.display?.startsWith("/"))try{let A=Am(e,d.display);A&&(u=`${u}
|
|
460
|
+
|
|
461
|
+
${A}`)}catch{}d?.quietUser||h({kind:"user",text:d?.echoDisplay&&d.display?d.display:u});let w=Et.current;w.firstPrompt||(w.firstPrompt=d?.display??u),Tt.current=Date.now(),Bt(0),T(!0),Fo.current.clear();let E="",B=!1,m=!1,f=!1,$=!1,b="",R={num:0,closed:!1,cueSeen:!1},x=null,_=()=>{x||(x=setTimeout(()=>{x=null,l(b.length>0?b:null)},60))},W=()=>{x&&clearTimeout(x),x=null,l(null)},V=(A=!1)=>{let{head:M,keep:L}=Wg(b,A);M.trim()&&h({kind:"assistant",text:fu(M.trimEnd(),R)}),b=L,W()};try{for await(let A of dt.current.send(u))if(A.type==="session"){if(!w.uuid){w.uuid=A.sessionId;let M=new Date().toISOString(),L=na.current,q=L??iS(w.firstPrompt??"session");aS({uuid:A.sessionId,name:q,renamed:!!L,titled:!1,cwd:e,firstPrompt:w.firstPrompt??"",createdAt:M,updatedAt:M}),mn(q),na.current=null}}else if(A.type==="text"){b+=A.delta,E+=A.delta;let M=Ug(b);if(M>0){let L=b.slice(0,M).trimEnd();L&&h({kind:"assistant",text:fu(L,R)}),b=b.slice(M)}_(),Bt(L=>L+A.delta.length)}else if(A.type==="tool"){B=!0,ly.test(A.name)&&(m=!0);let L=(me=>typeof me=="string"&&me?me.replace(/\\/g,"/").toLowerCase():null)(A.input.file_path??A.input.notebook_path),q=["Edit","Write","MultiEdit","NotebookEdit"].includes(A.name),ie=A.name==="Read"&&L!==null&&L===Mu.current;Mu.current=q?L:null;let we=Zr.current,Qe=we?null:_g(A.name,A.input),z=we?null:Ii(A.name,A.input,e,s);if(Qe)sa.current.push(Qe);else if(z)V(),h({kind:"doc",verb:z.verb,title:z.title,category:z.category,note:z.note,...z.loud?{loud:z.loud}:{}}),Fo.current.set(A.id,{name:A.name,input:A.input,doc:!0,keepResult:z.keepResult});else if(ie)V(),h({kind:"tool",title:"Read",sep:"",arg:"re-checking the file it just edited"});else{let me=Li(A.name,A.input,e);me&&(V(),h({kind:"tool",title:me.title,sep:me.sep,arg:me.arg}),Fo.current.set(A.id,{name:A.name,input:A.input}))}}else if(A.type==="article_diff"){let M=at(A.oldContent,A.newContent,_e());M&&(V(),h({kind:"diff",added:M.added,removed:M.removed,lines:M.lines,hidden:M.hidden}))}else if(A.type==="tool_result"){A.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(A.output)&&(es.current=!0);let M=Fo.current.get(A.id);if(M){Fo.current.delete(A.id),V();let q=M.doc&&!M.keepResult&&!A.isError?{lines:[],hidden:0}:Oi(A.output,4,A.isError||Zr.current?void 0:M.name,M.input);q.lines.length>0&&h({kind:"tool-result",lines:q.lines,hidden:q.hidden,isError:A.isError}),A.isError||od(M.name,M.input,A.output)}}else if(A.type==="result"){V(!0),Kt(q=>q+A.outputTokens),zt(q=>q+A.costUsd);let M=A.inputTokens+A.cacheReadTokens+A.cacheCreationTokens;if(h({kind:"done",seconds:Math.round((Date.now()-Tt.current)/1e3),tokens:A.outputTokens,costUsd:A.costUsd,ok:A.ok,...M>0?{inTokens:M,cachedPct:Math.round(A.cacheReadTokens/M*100)}:{}}),!f&&!B&&!E.trim()&&!Bo.current&&($=!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."})),A.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(E))try{let q=ty(e);if(Ao(q)){let ie=zi(q,"utf8").trim();ie&&(da(ie),h({kind:"note",tone:"info",text:"\u{1F6E0} Press c to copy this feedback \u2014 send it to the d360-writer team (Teams / Slack / email)."}))}}catch{}let L=A.ok?sg(E):null;if(yt.current=L!==null,St.current=L,A.ok&&(R.cueSeen||(L?.options??0)>=2))Wn(!0),ue([]);else if(L)ue([]);else{let q=A.ok?xg(E,fo.map(ie=>ie.name)):[];if(q.length>0)Q(q[0]);else if(A.ok&&E.trim()&&!yt.current){let ie=ht(!1);ie.kind==="recommend"&&(ie.rec.lead||ie.rec.picker)||dS(u,E,e).then(we=>{we&&Ke.current===c&&qe(we)}).catch(()=>{})}}if(w.uuid&&(Cu(w.uuid),!w.titleFired)){w.titleFired=!0;let q=w.uuid,ie=w.firstPrompt;ie&&qg(ie,e).then(we=>{we&&(sS(q,we),mn(we))}).catch(()=>{})}}else A.type==="error"&&(V(!0),f=!0,A.kind==="auth"&&(es.current=!0),h(A.kind==="limit"?{kind:"note",text:`\u23F3 ${A.message}`,tone:"warn"}:{kind:"note",text:`agent error: ${A.message}`,tone:"error"}))}finally{if(T(!1),W(),ns(),m)try{let A=Pu(await Su({cwd:e,profileName:s,onRateLimit:M=>je(`Document360 rate limit \u2014 waiting ${Math.ceil(M.waitMs/1e3)}s\u2026`)}));A&&h({kind:"note",tone:A.startsWith("\u26A0")?"warn":"info",text:A})}catch{}finally{je(null)}Y(A=>A+1),Et.current.uuid&&hg(e,Et.current.uuid,Hn.current),es.current?(es.current=!1,qo.current=d?.display??u,qe("/login","\u21E5 tab to run /login \u2014 then I\u2019ll re-send your last prompt\u2026")):qo.current=null,Bo.current&&(Bo.current=!1,vn.current.length>0&&(h({kind:"note",tone:"info",text:`(${vn.current.length} queued message(s) discarded)`}),vn.current=[],oa([])),h({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}return{producedNothing:$}},[e,h,od,_e,qe,Q,kt,ht,ns]),ft=J(async(u,d=0,c)=>{let w=Tu(e,u,{allowUnreviewed:c?.skipReview===!0,allowStyleErrors:c?.skipStyle===!0});if(!w.clear){h({kind:"note",tone:"warn",text:Eu(w,u.length).join(`
|
|
462
|
+
`)}),Q(Ul(w));return}let E=No(e,"standard");Tt.current=Date.now(),Bt(0),T(!0);let B=new AbortController;Ee.current=B;let m=async(f,$)=>{let b=Ru(f);de({verb:"Pushing",total:b.length,done:0,active:[],rows:_n(b),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),h({kind:"note",tone:"info",text:$?`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${yr} agents at once) on ${E.model}\u2026 (esc to stop)`});let R=!1;for await(let x of Do({cwd:e,partitions:b,promptFor:_=>wr(_.paths),concurrency:yr,profileName:s,allowProdWrites:Ht.current,allowUnreviewedPublish:c?.skipReview===!0,allowStyleErrors:c?.skipStyle===!0,model:E.model,signal:B.signal}))if(x.type==="partition_status")x.status==="running"?de(_=>_&&{..._,active:[..._.active,x.label],rows:Be(_.rows,x.label,"active"),lastAt:Date.now()}):de(_=>_&&{..._,active:_.active.filter(W=>W!==x.label),done:_.done+1,rows:Be(_.rows,x.label,x.status==="done"?"done":"failed"),lastAt:Date.now()});else if(x.type==="partition_event")de(_=>{if(!_)return _;let W={..._,lastAt:Date.now()};return x.event.type==="tool"?W.tools=_.tools+1:x.event.type==="text"&&(W.chars=_.chars+x.event.delta.length),W});else if(x.type==="run_done"){R=x.aborted,zt(L=>L+x.totalCostUsd),Kt(L=>L+x.results.reduce((q,ie)=>q+ie.outputTokens,0));let _=x.aborted?"Stopped. ":"",W=t.kind==="api"?"api":"subscription",V=yl(e,u,s),A=!x.aborted&&(!!x.blocked||!!x.allEmpty||u.length>0&&V===0);h({kind:"note",tone:x.aborted?"warn":x.ok&&!A?"ok":"warn",text:_+wl(x.results,b,W,$?0:d,{recorded:V,...x.blocked?{blocked:x.blocked}:{},...x.allEmpty?{allEmpty:!0}:{},...x.bailedEmpty?{bailedEmpty:!0,notRun:x.notRun??0}:{}},c?.scope).join(`
|
|
463
|
+
`)});let M=ml(e,s);if(M&&h({kind:"note",tone:"info",text:M}),!x.aborted&&!A){let L=yo(e,s);L&&h({kind:"note",tone:"info",text:L})}if(!x.aborted&&!A){try{let q=await Su({cwd:e,profileName:s,onRateLimit:we=>je(`Document360 rate limit \u2014 waiting ${Math.ceil(we.waitMs/1e3)}s\u2026`)}),ie=Pu(q);ie?h({kind:"note",tone:ie.startsWith("\u26A0")?"warn":"info",text:ie}):q.skipped&&h({kind:"note",tone:"warn",text:`Order sync skipped: ${q.skipped}`})}catch(q){h({kind:"note",tone:"warn",text:`Order sync failed: ${q.message}`})}finally{je(null)}try{let q=ry(await oy({cwd:e,profileName:s}));q&&h({kind:"note",tone:"info",text:q})}catch(q){h({kind:"note",tone:"warn",text:`Related-articles sync failed: ${q.message}`})}let L=await wo(e,s);L&&h({kind:"note",tone:"info",text:L})}}return R};try{if(!await m(u,!1)){let $=await kl(e,s,u);$.length>0&&await m($,!0),d>0&&Ae(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{Ee.current=null,de(null),T(!1),Y(f=>f+1)}},[e,s,h,t,Ae]),eo=J(u=>h({kind:"block",text:u.join(`
|
|
464
|
+
`)}),[h]),cs=J(async u=>{let d=No(e,"standard");Tt.current=Date.now(),Bt(0),T(!0);let c=new AbortController;Ee.current=c,de({verb:u.verb,unit:"article",total:u.partitions.length,done:0,active:[],rows:_n(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 w=!0,E=[],B=!1;try{for await(let m of Do({cwd:e,partitions:u.partitions,promptFor:u.promptFor,concurrency:u.concurrency,profileName:s,allowProdWrites:Ht.current,model:d.model,signal:c.signal}))if(m.type==="partition_status")m.status==="running"?de(f=>f&&{...f,active:[...f.active,m.label],rows:Be(f.rows,m.label,"active"),lastAt:Date.now()}):de(f=>f&&{...f,active:f.active.filter($=>$!==m.label),done:f.done+1,rows:Be(f.rows,m.label,m.status==="done"?"done":"failed"),lastAt:Date.now()});else if(m.type==="partition_event")de(f=>{if(!f)return f;let $={...f,lastAt:Date.now()};return m.event.type==="tool"?$.tools=f.tools+1:m.event.type==="text"&&($.chars=f.chars+m.event.delta.length),$});else if(m.type==="run_done"){zt(b=>b+m.totalCostUsd),Kt(b=>b+m.results.reduce((R,x)=>R+x.outputTokens,0));let f=m.results.filter(b=>!b.ok);w=!!m.allEmpty||!!m.blocked,B=!!m.aborted;let $=[`${m.aborted?"Stopped. ":""}${m.results.length-f.length}/${u.partitions.length} batches ${u.doneNoun}.`,...f.length?[`\u26A0 ${f.length} not ${u.doneNoun} \u2014 their articles are unchanged: ${f.map(b=>b.label).join(", ")}`]:[],...m.blocked?[`\u26A0 ${m.blocked}`]:[],...m.allEmpty?[u.emptyNote??"\u26A0 No turn produced any work this run \u2014 nothing was changed."]:[],...u.caveatLines??[]];if(h({kind:"note",tone:m.aborted||f.length||m.blocked||m.allEmpty?"warn":"ok",text:$.join(`
|
|
465
|
+
`)}),!w){let b=new Set(f.map(R=>R.label));E=u.partitions.filter(R=>!b.has(R.label)).flatMap(R=>R.paths)}}}catch(m){h({kind:"note",tone:"error",text:`${u.verb} failed: ${m.message}`})}finally{Ee.current=null,de(null),T(!1),Y(m=>m+1)}return{producedNothing:w,covered:E,aborted:B}},[e,s,h]),Ry=J(async(u,d)=>{let c=await cs({partitions:u.partitions,promptFor:u.promptFor,concurrency:Ur,verb:"Reviewing",doneNoun:"reviewed",headline:`Reviewing ${u.articles} article${u.articles===1?"":"s"} in ${u.partitions.length} batches (\u2264${Ur} editors at once)${d?", applying fixes as they go":", report only"}`,caveatLines:Zc(u),emptyNote:"\u26A0 No editor produced any work this run \u2014 nothing was reviewed or changed."});if(d&&c.covered.length>0)try{jo(e,c.covered,Ye("review"))}catch{}return{producedNothing:c.producedNothing,aborted:c.aborted}},[e,cs]),ga=J(async(u,d)=>{if(u.length===0)return;let c=u.reduce((f,$)=>f+$.threads.length,0),w=new Map,E=u.map(f=>(w.set(f.label,f),{label:f.label,paths:f.path?[f.path]:[]})),B=No(e,"standard");Tt.current=Date.now(),Bt(0),T(!0);let m=new AbortController;Ee.current=m,de({verb:"Answering",unit:"article",total:E.length,done:0,active:[],rows:_n(E),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),h({kind:"note",tone:"info",text:`Answering ${c} comment${c===1?"":"s"} across ${E.length} article${E.length===1?"":"s"} (\u2264${Or} agents at once) on ${B.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 Do({cwd:e,partitions:E,promptFor:$=>{let b=w.get($.label);return Wc({articleId:b.articleId,label:b.label,path:b.path,count:b.threads.length,resolve:d.resolve})},concurrency:Or,profileName:s,allowProdWrites:Ht.current,allowCommentResolve:d.resolve,model:B.model,signal:m.signal}))if(f.type==="partition_status")f.status==="running"?de($=>$&&{...$,active:[...$.active,f.label],rows:Be($.rows,f.label,"active"),lastAt:Date.now()}):de($=>$&&{...$,active:$.active.filter(b=>b!==f.label),done:$.done+1,rows:Be($.rows,f.label,f.status==="done"?"done":"failed"),lastAt:Date.now()});else if(f.type==="partition_event")de($=>{if(!$)return $;let b={...$,lastAt:Date.now()};return f.event.type==="tool"?b.tools=$.tools+1:f.event.type==="text"&&(b.chars=$.chars+f.event.delta.length),b});else if(f.type==="run_done"){zt(V=>V+f.totalCostUsd),Kt(V=>V+f.results.reduce((A,M)=>A+M.outputTokens,0));let $=f.results.filter(V=>!V.ok),b=f.results.length-$.length,x=[`${f.aborted?"Stopped. ":""}${b}/${E.length} article${E.length===1?"":"s"} answered.`,...$.length?[`\u26A0 ${$.length} left untouched (their threads are still open, which is correct \u2014 nothing was promised to those reviewers): ${$.map(V=>V.label).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||$.length||f.blocked||f.allEmpty?"warn":"ok",text:x.join(`
|
|
466
|
+
`)});let _=new Set($.map(V=>V.label)),W=[...d.rest??[],...u.filter(V=>_.has(V.label))];if(W.length>0&&!f.aborted&&d.report){let V=W.reduce((M,L)=>M+L.threads.length,0);h({kind:"note",tone:"info",text:`${V} comment${V===1?"":"s"} on ${W.length} other article${W.length===1?"":"s"} still open \u2014 pick the next one, or esc to stop here.`});let A={...d.report,threads:W.flatMap(M=>M.threads)};eo(_r(A,{width:_e()})),Nt({cursor:0,rows:$i(W),groups:W,resolve:d.resolve,report:A})}else if(W.length>0&&!f.aborted){let V=W.map(M=>M.path).filter(M=>!!M),A=V.length===W.length?vt(V):void 0;Q(A?V.length===1?`/comments ${A}`:`/comments --scope ${A}`:"/comments")}}}catch(f){h({kind:"note",tone:"error",text:`Answering comments failed: ${f.message}`})}finally{Ee.current=null,de(null),T(!1),Y(f=>f+1)}},[e,s,h,Ae,Q,eo,_e]),ya=J(async(u,d)=>{if(d?.skipReview===!0||d?.skipStyle===!0)await ft([u],0,{skipReview:d?.skipReview,skipStyle:d?.skipStyle,scope:u});else{let E=Tu(e,[u],{});if(!E.clear){h({kind:"note",tone:"warn",text:Eu(E,1).join(`
|
|
467
|
+
`)}),Q(Ul(E,u));return}await ye(hl(u),{display:`/publish ${u}`,quietUser:!0})}let w=d?.skipReview?null:await wo(e,s);w&&h({kind:"note",tone:"info",text:w});try{let E=await ni(e,s,u.replace(/\\/g,"/"));E.length>0&&(zn(`Related articles not yet published (${E.length}):`),ue([`/publish --related ${u}`,...E.map(B=>`/publish ${B}`)]))}catch{}},[e,s,ye,ft]),Sy=J(async(u,d)=>{T(!0);try{let c=await Rl(e,s,u,{skipReview:d.skipReview,skipStyle:d.skipStyle,onProgress:(E,B,m)=>je(`Publishing ${E+1}/${B} \u2014 ${m}\u2026`)}),w=c.blocked.length+c.failed.length;h({kind:"note",tone:w>0?"warn":"ok",text:Sl(c).join(`
|
|
468
|
+
`)}),c.blocked.length>0?Q("/review --blocked --fix"):Ae(null,null)}catch(c){h({kind:"note",tone:"error",text:`Publishing failed: ${c.message}`})}finally{je(null),T(!1),Y(c=>c+1)}},[e,s,h,Q,Ae]),rd=J(async u=>{try{let d=await Qi({cwd:e,profileName:s}),{clean:c,conflicts:w}=An(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 ft(c.map(E=>E.path),w.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,ft]),us=J(u=>{if(u)try{for(let d of Array.isArray(u)?u:[u]){let c=ou(e,d);if(!c)continue;Ei(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]),sd=J(async(u,d)=>{let w=bS(u,3),E=No(e,"standard"),B=new Map,m=new Map;for(let b of u){let R=Tn(e,b),x=za(e,b,R);if(x&&B.set(b,x),R!==null){let _=cl(R);_.length>0&&m.set(b,_)}}Tt.current=Date.now(),Bt(0),T(!0);let f=new AbortController;Ee.current=f,de({verb:"Authoring",unit:"spec",total:w.length,done:0,active:[],rows:_n(w),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 ${w.length} batch${w.length===1?"":"es"} (\u22646 agents at once) on ${E.model}${E.forced?" (forced)":""}\u2026 (esc to stop)`});let $=!1;try{for await(let b of Do({cwd:e,partitions:w,promptFor:R=>lh(R,B,m),concurrency:6,profileName:s,allowProdWrites:Ht.current,model:E.model,signal:f.signal}))if(b.type==="partition_status")b.status==="running"?de(R=>R&&{...R,active:[...R.active,b.label],rows:Be(R.rows,b.label,"active"),lastAt:Date.now()}):de(R=>R&&{...R,active:R.active.filter(x=>x!==b.label),done:R.done+1,rows:Be(R.rows,b.label,b.status==="done"?"done":"failed"),lastAt:Date.now()});else if(b.type==="partition_event")de(R=>{if(!R)return R;let x={...R,lastAt:Date.now()};return b.event.type==="tool"?x.tools=R.tools+1:b.event.type==="text"&&(x.chars=R.chars+b.event.delta.length),x});else if(b.type==="run_done"){zt(V=>V+b.totalCostUsd),Kt(V=>V+b.results.reduce((A,M)=>A+M.outputTokens,0));let R=b.results.filter(V=>V.ok).length,x=b.aborted?"Stopped. ":"";$=!b.aborted&&d.setup;let _=b.aborted?"":$?" Refreshing the staging checklist\u2026":` Next: /screenshot capture${d.scope?` ${d.scope}`:" --all"} (or /screenshot checklist first for the staging checklist).`,W=$t(b,"Spec authoring");h({kind:"note",tone:W||b.aborted?"warn":b.ok?"ok":"warn",text:W?W.join(`
|
|
469
|
+
`):`${x}Authored specs \u2014 ${R}/${b.results.length} batches ok.${_}`}),W&&(Q("/doctor"),$=!1),!b.aborted&&b.ok&&!W&&us(d.runLine)}}catch(b){h({kind:"note",tone:"error",text:`Spec authoring failed: ${b.message}`})}finally{Ee.current=null,de(null),T(!1),Y(b=>b+1)}if($){let b=await xo();b.kind==="forward-to-agent"&&b.prompt&&await ye(b.prompt,{display:b.display,quietUser:!0}),aa()}},[e,s,h,ye,us,aa]),id=J(async u=>{let d=za(e,u,Tn(e,u))??void 0,c=await Js([u],void 0,{prior:d});c.kind==="forward-to-agent"&&c.prompt&&await ye(c.prompt,{display:c.display,quietUser:!0}),Yp(e,u)&&Ae(`Spec ready \u2014 /screenshot capture ${u} takes the screenshot; bare /screenshot picks the next shot.`,{kind:"cmd",cmd:`/screenshot capture ${u}`,reason:""})},[e,ye,Ae]),er=J(async(u,d)=>{if(!yi(e)){await ye(Cc(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(!Df(e)){h({kind:"note",tone:"info",text:"No saved login for screenshot capture yet \u2014 opening a browser window. Sign in to your app (MFA included); I'll continue automatically once the session saves. (esc cancels)"}),T(!0),je("Waiting for you to finish logging in (browser window)\u2026");let L=new AbortController;Ee.current=L;let q;try{q=await Nf({cwd:e,signal:L.signal})}catch(ie){h({kind:"note",tone:"error",text:`Could not launch the login: ${ie.message}`});return}finally{Ee.current=null,je(null),T(!1)}if(q.exitCode!==0){xc(q.exitCode,q.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(q.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:L.signal.aborted?"warn":"error",text:L.signal.aborted?"Login cancelled \u2014 nothing saved.":`Login did not complete:
|
|
470
|
+
${$c(q.output)}`});return}h({kind:"note",tone:"ok",text:"\u2713 Login saved \u2014 continuing with the capture."})}let c=new Map(u.map(L=>[L,Zp(e,L)])),w=0;if(u.length>1){let L=u.filter(q=>c.get(q).mutates);if(L.length>0&&(w=L.length,u=u.filter(q=>!c.get(q).mutates),u.length===0)){h({kind:"note",tone:"warn",text:`\u26A0 All ${L.length} spec${L.length===1?"":"s"} in scope write real data, so a bulk run has nothing to do. Run one deliberately: /screenshot capture ${L[0]}`});return}}else if(u.length===1&&c.get(u[0]).mutates){let L=c.get(u[0]),q=jf(e);h({kind:"note",tone:"warn",text:`\u26A0 This capture performs a REAL write in your app${L.what?`: ${Jp(L.what)}`:L.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. `+(q.production?`This profile is PRODUCTION \u2014 the write lands in the LIVE tenant${q.url?` (${q.url})`:""}. If the spec cleans up after itself, confirm it did.`:"Tip: point the capture scope (.d360-writer/capture.json) at a demo/non-production context for shots like this.")})}T(!0);let E=new AbortController;Ee.current=E;let B=u.map(L=>({label:L,items:1,status:"pending"}));de({verb:"Capturing",unit:"screenshot",total:u.length,done:0,active:[],rows:B,tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()});let m=_t(e),f=Object.keys(m.shots).length>0,$=If(d?.heldBackBlocked??[],w);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)`+($?`
|
|
471
|
+
${$}`:"")});let b=Date.now(),R=[];try{for(let L of u){if(E.signal.aborted)break;de(z=>z&&{...z,active:[L],rows:Be(z.rows,L,"active"),lastAt:Date.now()});let{exitCode:q,output:ie}=await vc({cwd:e,id:L,signal:E.signal,stdio:"pipe"});if(xc(q,ie)){h({kind:"note",tone:"error",text:"d360-capture is not installed on this machine. Run: npm i -g document360-capture \u2014 then /screenshot capture again."});return}let we=E.signal.aborted&&q!==0?"failed":bc(e,L,q,b),Qe=we==="captured"?void 0:we==="skipped"?Ef(ie)??"a data prerequisite isn't met \u2014 the spec's skip reason names what to stage":Af(ie);R.push({id:L,outcome:we,detail:Qe}),de(z=>z&&{...z,active:[],done:z.done+1,rows:Be(z.rows,L,we==="captured"?"done":"failed"),lastAt:Date.now()})}}catch(L){h({kind:"note",tone:"error",text:`Capture run failed: ${L.message}`})}finally{Ee.current=null,de(null),T(!1),Y(L=>L+1)}if(R.length===0)return;let x=R.filter(L=>L.outcome==="captured"),_=R.filter(L=>L.outcome==="skipped"),W=R.filter(L=>L.outcome==="failed"),V=u.length-R.length;h({kind:"note",tone:W.length?"warn":x.length?"ok":"info",text:[`\u2713 ${x.length} captured`,_.length?`\u2298 ${_.length} blocked`:"",W.length?`\u2717 ${W.length} broken`:"",V?`${V} not run (stopped)`:""].filter(Boolean).join(" ")+` ${R.length} run${w>0?` \xB7 ${w} held back`:""}`+_f(Lf(m,R),f).map(L=>`
|
|
472
|
+
${L}`).join("")});let A=Of(_);if(A.length>0&&h({kind:"note",tone:"info",text:A.join(`
|
|
473
|
+
`)}),W.length>0){let L=Math.max(...W.map(q=>q.id.length));h({kind:"note",tone:"error",text:W.map(q=>`\u2717 ${q.id.padEnd(L)} ${gi(q.detail)}`).join(`
|
|
474
|
+
`)})}if(Fs(e,R.map(L=>({id:L.id,outcome:L.outcome,reason:L.detail,specSource:Tn(e,L.id)})),new Date().toISOString()),R.length===u.length&&W.length===0&&_.length===0&&us(d?.runLine),x.length>0){let L=x.map(ie=>ie.id);h({kind:"note",tone:"info",text:Ar(L.length)}),await ye(In(e,L),{display:"/screenshot verify",quietUser:!0});let q=Dr(e,L);q.length>0&&h({kind:"note",tone:"info",text:q.join(`
|
|
475
|
+
`)});return}let M=Mf({results:R,ids:u,articles:Ff(e,x.map(L=>L.id))});M&&Ae(M.note,{kind:"cmd",cmd:M.cmd,reason:""},M.tone)},[e,h,Ae,ye,us]),wa=J(u=>{let d=Fn(u);if(!d||pn(d)&&!d.refreshToken)return null;let c={...Oo(d.idToken)??{},...Oo(d.accessToken)??{}};return c.email??c.preferred_username??"signed in"},[]),ka=J((u,d)=>{if(d){let c=ge(e);c&&(c.defaultProfile=u,Gg(c,e))}i(u),Ve(void 0,u),h({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${u}"${d?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),wa(u)||(h({kind:"note",tone:"warn",text:`Profile "${u}" is not signed in \u2014 sign in with /login.`}),Q("/login")),Y(c=>c+1)},[e,h,Ve,wa,Q]),ds=J((u,d,c)=>{gs(e,u,d,c.id,c.name),h({kind:"note",tone:"ok",text:`Switched to workspace "${c.name??c.id}" (agent restarted).`}),Ve(),Kg(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:uo(co(e)).join(`
|
|
476
|
+
`)}),Xt(Pn()),Jo.current=mt(e).status==="current",Zn.current=Ot(e),h({kind:"note",tone:"info",text:`No separate builder agent? Then just ask me now: "write the docs for this repo" \u2014 I'll read the code directly.`}))},[e,h,Ve,Xt]),ps=J(async u=>{let d;try{d=await sr(e,u)}catch{h({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),Q("/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(E=>(E.workspace_type??"").toLowerCase()!=="apidocumentation"),w=c.length>0?c:d.workspaces;if(w.length===1){let E=w[0],B=d.workspaces.length-w.length;h({kind:"note",tone:"ok",text:`Selected the "${E.name??E.id}" workspace${B>0?" (skipped the API-documentation workspace)":""}.`}),ds(d.profile,d.projectId,E);return}h({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${w.length} available).`}),Q("/workspace")},[e,h,ds,Q]),hs=J((u,d)=>{ys(e,u,d.id,d.name),h({kind:"note",tone:"ok",text:`Project set to "${d.name??d.id}" (agent restarted).`}),Ve(),ps(u)},[e,h,Ve,ps]),ad=J(async u=>{let d;try{d=ut(e,u)}catch{return}if(!d.project.workspaceId){if(d.project.projectId){if(!d.project.projectName)try{let{projects:c}=await Jt(e,d.name),w=c.find(E=>E.id===d.project.projectId);w?.name&&AS(e,d.name,{projectName:w.name})}catch{}await ps(d.name);return}try{let{projects:c}=await Jt(e,d.name);if(c.length===1){let w=c[0];h({kind:"note",tone:"ok",text:`Using your Document360 project "${w.name??w.id}".`}),hs(d.name,{id:w.id,name:w.name});return}if(c.length>1){let w=c.map(E=>({id:E.id,name:E.name??E.id,sub:E.sub_domain}));h({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),wn({cursor:0,current:-1,rows:w,profile:d.name,environment:d.connection.name});return}}catch{}h({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),Q("/project")}},[e,h,ps,hs,Q]),to=J(()=>{let u=Ce.current[0];if(!u)return;kt();let{plan:d,mode:c}=u;h({kind:"note",tone:"info",text:`\u25CF ${d.title} (${d.path})`});for(let B of d.notes)h({kind:"note",tone:"warn",text:`\u26A0 ${B}`});d.overwritesLocalChanges&&c==="pull"&&h({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let w=at(d.oldContent,d.newContent,_e());h(w?{kind:"diff",added:w.added,removed:w.removed,lines:w.lines,hidden:w.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."});let E=Ce.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:E>1?`(l/p/s \xB7 la/pa/sa for all ${E} \u2014 anything else cancels)`:"(l/p/s \u2014 anything else cancels)"})):h({kind:"note",tone:"info",text:E>1?`Write ${d.path}? (y/n \xB7 ya/na for all ${E} \u2014 anything else cancels)`:`Write ${d.path}? (y/n \u2014 anything else cancels)`})},[h,_e,kt]),tr=J(()=>{if(Ce.current.length>0){to();return}let u=fn.current;fn.current=[],u.length>0?(h({kind:"note",tone:"info",text:`Publishing ${u.length} kept-local article${u.length===1?"":"s"} over the portal\u2026`}),ft(u)):Q("/pull")},[to,h,ft,Q]),ld=J(u=>{if(Ce.current.length===0)return!1;let d=u.trim(),c=d.toLowerCase(),w=Ce.current[0];if(w.mode==="conflict"){let B=ag(d);if(B){let m=Ce.current.splice(0),f=m.length;if(B==="local"){for(let $ of m)fn.current.push($.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(B==="portal"){let $=0;for(let b of m)try{Xi({cwd:e,profileName:s},b.plan),$++}catch(R){h({kind:"note",tone:"error",text:`Take-portal failed for ${b.plan.path}: ${R.message}`})}h({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${$} article${$===1?"":"s"} (local overwritten, sync base advanced).`})}else h({kind:"note",tone:"info",text:`Skipped all ${f} \u2014 still conflict${f===1?"":"s"}.`});return tr(),!0}if(c==="l"||c==="local")Ce.current.shift(),fn.current.push(w.plan.path),h({kind:"note",tone:"info",text:`Keeping local ${w.plan.path} \u2014 will publish over the portal.`});else if(c==="p"||c==="portal"){Ce.current.shift();try{Xi({cwd:e,profileName:s},w.plan),h({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${w.plan.path} (local overwritten, sync base advanced).`})}catch(m){h({kind:"note",tone:"error",text:`Take-portal failed: ${m.message}`})}}else if(c==="s"||c==="skip"||c==="n")Ce.current.shift(),h({kind:"note",tone:"info",text:`Skipped ${w.plan.path} \u2014 still a conflict.`});else{let m=Ce.current.length;return Ce.current=[],fn.current=[],h({kind:"note",tone:"info",text:`Resolve cancelled (${m} conflict${m===1?"":"s"} left untouched).`}),!0}return tr(),!0}let E=lg(d);if(E){let B=Ce.current.splice(0);if(E==="skip")h({kind:"note",tone:"info",text:`Skipped all ${B.length} article${B.length===1?"":"s"}.`});else{let m=0;for(let f of B)try{Xi({cwd:e,profileName:s},f.plan),m++}catch($){h({kind:"note",tone:"error",text:`Pull failed for ${f.plan.path}: ${$.message}`})}h({kind:"note",tone:"ok",text:`\u2713 Pulled ${m} article${m===1?"":"s"} (sync base advanced).`})}return tr(),!0}if(c==="y"||c==="yes"){let B=Ce.current.shift().plan;try{Xi({cwd:e,profileName:s},B),h({kind:"note",tone:"ok",text:`\u2713 Pulled ${B.path} (sync base advanced).`})}catch(m){h({kind:"note",tone:"error",text:`Pull failed: ${m.message}`})}}else if(c==="n"||c==="no"){let B=Ce.current.shift().plan;h({kind:"note",tone:"info",text:`Skipped ${B.path}.`})}else{let B=Ce.current.length;return Ce.current=[],h({kind:"note",tone:"info",text:`Pull cancelled (${B} article(s) left untouched).`}),!0}return tr(),!0},[e,s,tr,h]),ba=J(async u=>{h({kind:"note",tone:"info",text:"Checking Document360 for conflicts\u2026"});try{let d=await Qi({cwd:e,profileName:s}),c=u?.replace(/\\/g,"/"),w=d.entries.filter(B=>B.status==="conflict"&&B.path).map(B=>B.path);if(c){if(!w.includes(c)){h({kind:"note",tone:"ok",text:`${c} isn\u2019t in conflict \u2014 nothing to resolve.`});return}w=[c]}if(w.length===0){h({kind:"note",tone:"ok",text:"\u2713 No conflicts \u2014 local and Document360 agree on every tracked article."});return}let E=[];for(let B of w)try{E.push({plan:await zg({cwd:e,profileName:s,relPath:B}),mode:"conflict"})}catch(m){h({kind:"note",tone:"error",text:`Could not load ${B} from Document360: ${m.message}`})}if(E.length===0)return;h({kind:"note",tone:"info",text:`Resolving ${E.length} conflict${E.length===1?"":"s"} \u2014 for each: keep local, take portal, or skip.`}),Ce.current=E,fn.current=[],to()}catch(d){h({kind:"note",tone:"error",text:`Could not compute sync status: ${d.message}`})}},[e,s,h,to]),cd=J(u=>{let d=Wo.current;if(!d)return!1;if(Wo.current=null,kt(),u.trim()!==d.repoName)return h({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:c,failed:w}=Gc(e,d.targets);h({kind:"note",tone:w.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 E of w)h({kind:"note",tone:"error",text:` \u2717 ${E.path}: ${E.error}`});return d.hadDevhints&&(h({kind:"note",tone:"warn",text:Ds().join(`
|
|
477
|
+
`)}),Xt(ja())),h({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
|
|
478
|
+
${iy}`}),Q("/init"),Ut(!1),!0},[e,h,Xt,kt,Q]),no=J(async u=>{let d=u.slice(1).trim().split(/\s+/),c=(d[0]??"").toLowerCase(),w=d.slice(1);if(Ut(!0),Cr(w)&&["write","lint","check","review","reorder"].includes(c)){let m=xr(e,s);if(m.length===0){h({kind:"note",tone:"warn",text:"No categories yet \u2014 author some articles first, then scope to one."});return}let f=$=>c==="write"?`/write ${Vh(w,$).join(" ")}`.trim():`/${c} ${[$,...w.filter(b=>b!=="--scope")].join(" ")}`.trim();if(m.length===1){no(f(m[0].token));return}bn({cursor:0,rows:m,run:$=>{no(f($))}});return}if(ln(c,w)){let m=c==="write"&&Rr(w).rewrite,f=c==="write"?oc(e,Zg(e),{rewrite:m}):xr(e,s);if(f.length>1){let $=w.filter(A=>A.startsWith("--")).join(" "),b=A=>A==="--blocked"?`/${c} --blocked${$?` ${$}`:""}`.trim():`/${c}${A?` ${c==="write"?`--scope ${A}`:A}`:""}${$?` ${$}`:""} ${A?"":"--all"}`.replace(/\s+/g," ").trim(),R=f.reduce((A,M)=>A+M.count,0),x={token:"",label:c==="review"?`Everything \u2014 all ${R} articles + structure (IA) review`:c==="reorder"?`Everything \u2014 reorder all ${f.length} categories`:m?`Everything \u2014 rewrite all ${R} planned articles`:`Everything \u2014 write all ${R} pending article${R===1?"":"s"}`,count:R},_=c==="review"?Br(e):[],W=_.length>0&&_.length<R?[{token:"--blocked",label:`Only what needs review \u2014 ${_.length} article${_.length===1?"":"s"} publishing is blocked on`,count:_.length}]:[],V=c==="write"?`Write which articles? (counts = ${m?"articles to regenerate":"still to write"})`:c==="review"?"Review what? (counts = articles)":"Reorder what?";bn({cursor:0,rows:[...W,x,...f],run:A=>{no(b(A))},title:V});return}}let E=async m=>{let f=yc(m);if(!yi(e)){await ye(Cc(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(f.mode==="single"){await er([f.id],{runLine:[`/screenshot capture ${f.id}`,`/capture ${f.id}`]});return}if(f.mode==="failed"){let b=wc(e,jr(e).rows);if(b.length===0){h({kind:"note",tone:"info",text:"No broken specs to re-run \u2014 /screenshot list shows where things stand."}),Q("/screenshot list");return}await er(b);return}if(f.mode==="blocked"){let{blocked:b,rows:R}=jr(e);if(b.length===0){h({kind:"note",tone:"info",text:"No shots are waiting on app data \u2014 /screenshot list shows where things stand."}),Q("/screenshot list");return}let x=gr(R.filter(_=>_.state==="blocked")).length;h({kind:"note",tone:"info",text:`Re-running ${b.length} shot${b.length===1?"":"s"} that skipped on missing data last run.`+(x>0?` If you haven't staged ${x===1?"it":"those "+x+" things"} yet, ${b.length===1?"it":"they"} will skip again \u2014 /screenshot list has the worklist.`:"")}),await er(b,{runLine:["/screenshot capture --blocked","/screenshot capture --all --retry-blocked"]});return}if(f.mode==="all"||f.mode==="scope"){let b=f.mode==="scope"?f.scope:void 0,{ready:R,captured:x,blocked:_,rows:W}=jr(e,b),V=[...R,...x,...f.retryBlocked?_:[]];if(V.length===0&&_.length>0&&!f.retryBlocked){let M=b?`/screenshot capture ${b} --retry-blocked`:"/screenshot capture --blocked";Ae(`All ${_.length} shot${_.length===1?"":"s"} in scope ${_.length===1?"is":"are"} blocked on data that wasn't staged last run \u2014 /screenshot list shows what to stage, then ${M}.`,{kind:"cmd",cmd:"/screenshot list",reason:""},"warn");return}if(V.length===0){h({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),Q("/screenshot");return}if(!f.retryBlocked){let M=b?`/screenshot capture ${b} --retry-blocked`:"/screenshot capture --blocked",L=kc(W.filter(q=>q.state==="blocked"),M);L&&h({kind:"note",tone:"info",text:L})}let A=f.mode==="scope"?[`/screenshot capture ${f.scope}`,`/capture ${f.scope}`]:["/screenshot capture --all","/capture --all"];await er(V,{runLine:A,...f.retryBlocked?{}:{heldBackBlocked:W.filter(M=>M.state==="blocked")}});return}let $=Tf(Ie(e));if($.length===0){h({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),Q("/screenshot");return}kn({cursor:0,rows:$,title:"Capture screenshots \u2014 pick what to shoot:"})},B=async()=>{let m=await xo();m.kind==="forward-to-agent"&&m.prompt&&await ye(m.prompt,{display:m.display,quietUser:!0}),aa()};switch(c){case"help":Cn({tab:0,scroll:0});return;case"exit":case"quit":dt.current?.close(),r();return;case"clear":Ve(),Hn.current=[],He.current={printed:[],armed:[],printedAt:Qn.current},Ut(!1),kt(),console.log("\x1B[?2026h\x1B[H\x1B[2J\x1B[3J\x1B[?2026l"),h({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let m;try{m=ut(e,s)}catch(f){h({kind:"note",tone:"error",text:f.message});return}h({kind:"note",tone:"info",text:`Profile "${m.name}" \u2192 ${m.connection.name} (${m.connection.apiUrl})${m.production?" \u26A0 PRODUCTION":""}`}),I(!0);try{let f=await QR(m.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},b=>h({kind:"note",tone:"info",text:b})),$=JR(m.name,f);if(ZR($),await Ra($,m.name,b=>h({kind:"note",tone:"info",text:b})),h({kind:"note",tone:"ok",text:`\u2713 Logged in to "${m.name}" as ${bs($)}`}),await ad(s),Go.current){let b=Go.current;Go.current=null;let R=Ue(e,s);R.ok?(h({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 tab to run ${b}.`}),Q(b)):(h({kind:"note",tone:"warn",text:`${R.reason} (then ${b}.)`}),Q("/login"),Go.current=b)}else qo.current&&(qe(qo.current,"\u21E5 tab to re-send your last prompt\u2026"),qo.current=null)}catch(f){h({kind:"note",tone:"error",text:`Login failed: ${f.message}`})}finally{I(!1),Y(f=>f+1)}return}case"allow-prod":{let m=!1;try{m=ut(e,s).production}catch{}if(!m){h({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}Ht.current=!0,Ve(),h({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let m=dc(w.join(" ")),f=Et.current.uuid;if(!f){if(!m){h({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}na.current=m,mn(m),To(`${qi} ${m}`),h({kind:"note",tone:"ok",text:`Session will be named "${m}" once it starts.`});return}if(!m){h({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let $=Et.current.firstPrompt??"";qg($,e).then(b=>{b?(qe(`/rename ${b}`),h({kind:"note",tone:"info",text:`Suggestion: "${b}" \u2014 press tab to accept, or type /rename <your name>.`})):h({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>h({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}uS(f,m),mn(m),To(`${qi} ${m}`),h({kind:"note",tone:"ok",text:`Session renamed to "${m}".`});return}case"profile":{let m=w[0],f=ge(e);if(!m){let $=Object.entries(f?.profiles??{});if($.length===0){h({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let b=$.map(([_,W])=>({name:_,env:W.connection?.environment??"custom",prod:W.production===!0,who:wa(_)})),R=s??f?.defaultProfile,x=Math.max(0,b.findIndex(_=>_.name===R));qn({cursor:x,current:x,rows:b});return}if(m==="add"){let $=pc(e,w[1],w[2]);if($){h({kind:"note",tone:"error",text:$});return}h({kind:"note",tone:"ok",text:`\u2713 Profile "${w[1]}" created (environment: ${w[2]??w[1]}).`}),ka(w[1],!0);return}if(!f?.profiles?.[m]){h({kind:"note",tone:"error",text:`Unknown profile "${m}". Create it: /profile add ${m} <environment>`});return}ka(m,!0);return}case"doctor":await Tr(w,{cwd:e,version:o});return;case"style-guide":{let m=await Si(w,{cwd:e,profileName:s});m.kind==="clear"?(Ve(),h({kind:"note",tone:"ok",text:"\u2713 Agent restarted \u2014 it now writes to the new rules."})):m.kind==="forward-to-agent"&&((await ye(m.prompt,{display:m.display,quietUser:!0})).producedNothing||h({kind:"note",tone:"info",text:fm().join(`
|
|
479
|
+
`)})),Y(f=>f+1);return}case"genre":{let m=ge(e)?.appType??null;(await Pi(w,{cwd:e})).kind==="clear"&&(ge(e)?.appType??null)!==m&&(Ve(),h({kind:"note",tone:"ok",text:"\u2713 Agent restarted \u2014 the doc-craft playbook for this genre is now loaded."}));try{Wt.current=!(ge(e)?.appType??Yg(e))}catch{}Y($=>$+1);return}case"roadmap":{if(w[0]?.toLowerCase()==="done"){let m=Ei(e,w.slice(1).join(" ").trim());h({kind:"note",tone:m.ok?"ok":"warn",text:m.line}),Y(f=>f+1);return}h({kind:"note",tone:"info",text:nu(e).join(`
|
|
480
|
+
`)});return}case"mcp":await Is(w);return;case"init":{if(ge(e)){let f=Zt(e,s);h({kind:"note",tone:"info",text:["This repo is already set up \u2014 /init won\u2019t overwrite it.",` Change environment: /profile add <${Xg().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(`
|
|
481
|
+
`)}),f&&h({kind:"note",tone:"warn",text:`\u26A0 ${f.why} \u2014 ${f.cmd} moves this repo.`});return}let m=[...Xg(),...wS().filter(f=>Qg(f))].map(f=>({name:f,apiUrl:kS(f).apiUrl,note:Qg(f)?"being retired":null}));Gn({cursor:0,rows:m});return}case"resume":{let m=w.join(" ").trim(),f=cS(e).filter(R=>R.uuid!==Et.current.uuid);if(!m){if(!f.length){h({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}xn({query:"",cursor:0,sessions:f});return}let $=lS(e,m);if(!$){h({kind:"note",tone:"error",text:`No session matches "${m}".`});return}Ve($.uuid),Et.current={uuid:$.uuid,firstPrompt:$.firstPrompt,titleFired:!0},mn($.name),Cu($.uuid),Hn.current=[],He.current={printed:[],armed:[],printedAt:Qn.current};let b=gu(e,$.uuid);for(let R of b)h(R);h({kind:"note",tone:"ok",text:b.length?`Resumed "${$.name}" \u2014 restored ${b.length} message(s); continue where you left off.`:`Resumed "${$.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let m=w.join(" ").trim(),f;try{f=await sr(e,s)}catch(b){h({kind:"note",tone:"error",text:`Could not list workspaces: ${b.message}`});return}if(!m){let b=f.workspaces.map(x=>({id:x.id,name:x.name??x.id,type:x.workspace_type}));if(b.length===0){h({kind:"note",tone:"info",text:"No workspaces in this project."});return}let R=Math.max(0,b.findIndex(x=>x.id===f.current));Vn({cursor:R,current:R,rows:b,profile:f.profile,projectId:f.projectId,projectName:f.projectName,environment:f.environment});return}let $=xa(f.workspaces,m);if(!$){h({kind:"note",tone:"error",text:`No workspace matches "${m}".`});return}ds(f.profile,f.projectId,$);return}case"project":{let m=w.join(" ").trim(),f;try{f=await Jt(e,s)}catch(b){h({kind:"note",tone:"error",text:`Could not list projects: ${b.message} (signed in? try /login)`});return}if(!m){let b=f.projects.map(x=>({id:x.id,name:x.name??x.id,sub:x.sub_domain}));if(b.length===0){h({kind:"note",tone:"info",text:"No projects found for this identity."});return}let R=b.findIndex(x=>x.id===f.current);wn({cursor:Math.max(0,R),current:R,rows:b,profile:f.profile,environment:f.environment});return}let $=Ca(f.projects,m);if(!$){h({kind:"note",tone:"error",text:`No project matches "${m}". Available: ${f.projects.map(b=>b.name??b.id).join(", ")}`});return}hs(f.profile,$);return}case"logout":{let m;try{m=ut(e,s).name}catch($){h({kind:"note",tone:"error",text:$.message});return}let f=oS(m);rS(e,m),Ve(),Y($=>$+1),h({kind:"note",tone:f?"ok":"info",text:f?`\u2713 Signed out of "${m}" and cleared its project/workspace selection.`:`Profile "${m}" was not signed in. Cleared any project/workspace selection.`}),h({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),Q("/login");return}case"publish":{if(vl(w)){let x=Ft("publish");x&&h({kind:"note",tone:"info",text:x}),await no(`/push ${w.join(" ")}`.trim());return}if(!Jn(u.trim()))return;let m=Ft("publish");m&&h({kind:"note",tone:"info",text:m});let f=w.find(x=>!x.startsWith("--")),$={skipReview:w.includes(it),skipStyle:w.includes(sy)};je("Checking what is waiting to go live\u2026");let b;try{b=await xl(e,s,f)}catch(x){h({kind:"note",tone:"error",text:`Could not check Document360: ${x.message}`});return}finally{je(null)}if(b.length===0){let x=Cl(e,s,f);for(let _ of x.lines)h({kind:"note",tone:_.startsWith("\u2713")?"ok":"info",text:_});x.ahead>0&&Q(Ne("/push","",f));return}let R=Tu(e,b.map(x=>x.path),{allowUnreviewed:$.skipReview,allowStyleErrors:$.skipStyle});if(!R.clear){for(let x of Eu(R,b.length,f))h({kind:"note",tone:"warn",text:x});Q(Ne("/review","--blocked --fix",f));return}h({kind:"note",tone:"info",text:`${b.length} draft${b.length===1?" is":"s are"} ahead of what readers see. Pick what goes live:`}),Kn({cursor:0,rows:b,opts:$});return}case"push":{if(!Jn(u.trim()))return;let m=w.includes(it),f=w.includes(sy);if(w.includes("--screenshots")||w.includes("--shots")){let x=w.find(A=>!A.startsWith("--")),_=Ie(e),W=Ks(_,x);if(W.length===0){h({kind:"note",tone:"info",text:x?`No captured screenshots in ${x} \u2014 /publish --screenshots covers the whole knowledge base.`:"No captured screenshots yet \u2014 /screenshot capture first."});return}let V=zs(_);V&&h({kind:"note",tone:"warn",text:V}),h({kind:"note",tone:"info",text:`Re-saving ${W.length} article${W.length===1?"":"s"} with captured screenshots so the images embed\u2026`}),await ft(W,0,{skipReview:m,skipStyle:f,scope:Ne("","--screenshots",x).trim()});return}if(w[0]==="--related"&&w[1]){let x=await ni(e,s,w[1].replace(/\\/g,"/"));if(x.length===0){h({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await ft(x,0,{skipReview:m,skipStyle:f,scope:`--related ${w[1]}`});return}let $=w.filter(x=>!x.startsWith("--"));if($[0]){await ya($[0],{skipReview:m,skipStyle:f});return}let b=w.includes("--all"),R=w.includes("--force");h({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let x=await Qi({cwd:e,profileName:s}),{clean:_,conflicts:W}=An(x.entries),V=b&&R&&W.length>0,A=ei(x.entries);if(A>0&&h({kind:"note",tone:"warn",text:`\u26A0 ${A} article${A===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.`}),W.length>0&&!V&&h({kind:"note",tone:"warn",text:En(W.length)}),_.length===0&&!V){let M=yo(e,s);if(M&&h({kind:"note",tone:"info",text:M}),W.length>0){Q("/resolve");return}h({kind:"note",tone:"ok",text:A>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let L=x.counts["unknown-base"]??0;L>0&&h({kind:"note",tone:"info",text:`(${L} article(s) have no sync base yet \u2014 publish those by path if needed.)`}),je("Reconciling structure on Document360 (order + related articles)\u2026");try{let q=await Su({cwd:e,profileName:s,onRateLimit:Qe=>je(`Document360 rate limit \u2014 waiting ${Math.ceil(Qe.waitMs/1e3)}s\u2026`)}),ie=ry(await oy({cwd:e,profileName:s})),we=Pu(q);we?h({kind:"note",tone:we.startsWith("\u26A0")?"warn":"info",text:we}):q.skipped&&h({kind:"note",tone:"warn",text:`Order sync skipped: ${q.skipped}`}),ie&&h({kind:"note",tone:"info",text:ie}),q.failures?.length?Q("/structure"):(h({kind:"note",tone:"ok",text:we||ie?"\u2713 Structure synced to Document360 \u2014 /structure shows the new category + article order.":"\u2713 Already in order \u2014 nothing to change."}),(we||ie)&&Q("/structure"))}catch(q){h({kind:"note",tone:"warn",text:`Structure sync failed: ${q.message}`})}finally{je(null)}return}if(b){let M=(V?[..._,...W]:_).map(L=>L.path);await ft(M,V?0:W.length,{skipReview:m,skipStyle:f});return}Yn({cursor:0,rows:yh(_,W),conflicts:W.length})}catch(x){h({kind:"note",tone:"error",text:`Could not compute sync status: ${x.message}`}),h({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"resolve":{if(!Jn(u.trim()))return;await ba(w.find(m=>!m.startsWith("--")));return}case"preview":{let m=w.join(" ").trim();if(!m){let $=[];try{$=Object.keys(Kg(e,ut(e,s).name)?.articles??{})}catch{}if($.length===0){h({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}$n({query:"",cursor:0,paths:$});return}let f=zR(m)?m:xu(e,m);if(Ao(f)){try{h({kind:"preview",name:Qr(f),text:cy(zi(f,"utf8"))})}catch($){h({kind:"note",tone:"error",text:`Could not read ${f}: ${$.message}`})}return}if(GS.test(m)){try{let $=ut(e,s),b={profile:$.name,connection:$.connection},R=$.project.projectId??tS(b),x=await nS(b,R,m);h({kind:"preview",name:x.title??m,text:x.content??"*(article has no content)*"})}catch($){h({kind:"note",tone:"error",text:`Could not fetch article: ${$.message}`})}return}h({kind:"note",tone:"error",text:`"${m}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let m=w[0]?.trim();if(!m){let R=fi(Du(e));yn({cursor:R,current:R});return}let{lines:f,changed:$,effective:b}=Pr(e,m);for(let R of f)h({kind:"note",tone:R.startsWith("\u26A0")?"warn":R.startsWith("\u2713")?"ok":"info",text:R});$&&(Vu(R=>R+1),dt.current?.setModel(b));return}case"verbose":{let m=w[0]?.trim().toLowerCase(),f=m==="on"?!0:m==="off"?!1:!Zr.current;Zr.current=f;try{pS({...Vg(),verboseTranscript:f})}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:f?"\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:m,run:f}=Ll(w),$=vS(e,s);if($.length===0){h({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let b=Ol($,m);if(b.length===0){h({kind:"note",tone:"error",text:`No tracked articles under "${m}". (${$.length} are tracked overall.)`});return}let R=Ru(b),x=3,_=`/convert${m?` --scope ${m}`:""} --run`,W=No(e,"light");if(!f){let A=Jg({files:_l(e,b),op:"convert",model:W.model}),M=m?`Scope: ${m} (${b.length} of ${$.length} tracked)
|
|
479
482
|
`:"",L=`
|
|
480
|
-
Model: ${
|
|
481
|
-
`)+L}),
|
|
482
|
-
`):
|
|
483
|
-
`)}),
|
|
483
|
+
Model: ${W.model}${W.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;h({kind:"note",tone:"info",text:M+Fl(R,A,x).join(`
|
|
484
|
+
`)+L}),Q(_);return}Tt.current=Date.now(),Bt(0),T(!0);let V=new AbortController;Ee.current=V,de({verb:"Converting",total:R.length,done:0,active:[],rows:_n(R),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),h({kind:"note",tone:"info",text:`Converting ${b.length} articles in ${R.length} batches (\u2264${x} agents at once) on ${W.model}\u2026 (esc to stop)`});try{for await(let A of Do({cwd:e,partitions:R,promptFor:Ml,concurrency:x,profileName:s,allowProdWrites:Ht.current,model:W.model,signal:V.signal}))if(A.type==="partition_status")A.status==="running"?de(M=>M&&{...M,active:[...M.active,A.label],rows:Be(M.rows,A.label,"active"),lastAt:Date.now()}):de(M=>M&&{...M,active:M.active.filter(L=>L!==A.label),done:M.done+1,rows:Be(M.rows,A.label,A.status==="done"?"done":"failed"),lastAt:Date.now()});else if(A.type==="partition_event")de(M=>{if(!M)return M;let L={...M,lastAt:Date.now()};return A.event.type==="tool"?L.tools=M.tools+1:A.event.type==="text"&&(L.chars=M.chars+A.event.delta.length),L});else if(A.type==="run_done"){zt(ie=>ie+A.totalCostUsd),Kt(ie=>ie+A.results.reduce((we,Qe)=>we+Qe.outputTokens,0));let M=A.aborted?"Stopped. ":"",L=t.kind==="api"?"api":"subscription",q=$t(A,"The conversion");h({kind:"note",tone:q||A.aborted?"warn":A.ok?"ok":"warn",text:q?q.join(`
|
|
485
|
+
`):M+Wl(A.results,R,L).join(`
|
|
486
|
+
`)}),q&&Q("/doctor")}}catch(A){h({kind:"note",tone:"error",text:`Convert run failed: ${A.message}`})}finally{Ee.current=null,de(null),T(!1),Y(A=>A+1)}return}case"write":{if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=Zg(e);if(m.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:f,path:$,preview:b,concurrency:R,rewrite:x}=Rr(w);if(!$&&!b&&!(ge(e)?.appType??Yg(e))){h({kind:"note",tone:"warn",text:`\u26A0 No doc genre is set, so no doc-craft playbook would load \u2014 all ${m.length} articles would be written generically.
|
|
484
487
|
Pick the genre below (one keypress), then run /write again \u2014 it changes structure, titles and depth for every article.
|
|
485
|
-
Not blocked: /write <path> still authors a single article, and /write --preview costs nothing.`}),ue(
|
|
486
|
-
`:"",
|
|
487
|
-
Model: ${
|
|
488
|
-
`)+
|
|
489
|
-
`):me+
|
|
490
|
-
`)}),bt){
|
|
491
|
-
`)})}if(!z.aborted&&z.ok){let
|
|
492
|
-
${m.map(
|
|
493
|
-
`)}`}),ue(m.map(
|
|
494
|
-
`)});return}if(m==="--baseline"){let
|
|
495
|
-
${
|
|
496
|
-
`)}`}),Y(
|
|
497
|
-
`)});return}if(m){h({kind:"note",tone:"error",text:`Unknown option: ${m} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let f=
|
|
498
|
-
`)});let
|
|
499
|
-
`)}),
|
|
500
|
-
`)});return}case"reorder":{let m=
|
|
501
|
-
`)}),
|
|
502
|
-
`)});return}if(m.answer&&(m.all||m.scope.path||m.scope.scope||$.length===1)){
|
|
503
|
-
`)});return}if(m.mode==="list"){if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let R=ge(e)?.docsDir??
|
|
504
|
-
`)});let ie=
|
|
505
|
-
`)}),f&&h({kind:"note",tone:"info",text:f});let
|
|
506
|
-
`)}),Be(Kr(e));return}default:h({kind:"note",tone:"error",text:`Unknown command: /${c} \u2014 type /help.`})}},[e,r,s,Qn,ga,h,He,ye,ht,ha,zu]),ds=Q(u=>{let d=(u??y).trim();if(v(""),zr(null),Fn(0),d.startsWith("/")&&(Te.current=!1,gt.current=!1,Rt.current=null,wt(),Vn(null),ue(b=>gg(b,d))),!d||(Mn(!1),(Lo.current||xe.current.length>0)&&h({kind:"user",text:d}),Qu(d))||Xu(d))return;Qi.current.push(d);let c=kg(d,Ru.current);if(d.startsWith("/"))h({kind:"user",text:d}),ae(!0),Jo(c).finally(()=>ae(!1));else if(dS(c)){h({kind:"user",text:d});let b=pS(c);if(!b)ye(c,{display:d,quietUser:!0});else{try{hS(e,{title:b,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}ye(`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${b}". 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 "${b}" and the article path(s) you wrote.`,{display:d,quietUser:!0})}}else{let b=bm(e,c);ye(b??c,{display:d})}},[y,Qu,Xu,Jo,ye]),Ju=Q(u=>{if(u.length>1){if(u.includes("\x1B"))return;let d=yg(u);if(wg(d)){let c=bg(++ly.current,d);Ru.current.set(c,d),A(c)}else A(d);return}A(u)},[A]),Jn=Math.max(10,Ke-6),Zu=pu(()=>Hi(p.text,Jn),[p.text,Jn]),ya=Q(u=>g(d=>({...d,pos:Math.max(0,Math.min(d.text.length,d.pos+u))})),[]),ps=Q(u=>g(d=>({...d,pos:vg(Hi(d.text,Jn),d.pos,u)})),[Jn]),Zo=Q(u=>g(d=>({...d,pos:xg(Hi(d.text,Jn),d.pos,u)})),[Jn]),my=["\x1B[H","\x1B[1~","\x1BOH"],gy=["\x1B[F","\x1B[4~","\x1BOF"],ed=Q((u,d)=>d.leftArrow?(ya(-1),!0):d.rightArrow?(ya(1),!0):u&&my.includes(u)?(Zo("start"),!0):u&&gy.includes(u)?(Zo("end"),!0):d.ctrl&&u==="a"?(Zo("start"),!0):d.ctrl&&u==="e"?(Zo("end"),!0):!1,[ya,Zo]);return bR((u,d)=>{if(d.ctrl&&u==="c"){ut.current?.close(),r();return}if(Yo.current.awaySince!==null)try{let c=ig(Yo.current,Date.now(),Nn(e));if(Yo.current=c.memory,Uu(null),c.kind==="delta"){h({kind:"note",tone:"info",text:lg(c.delta,c.awayMs)});let b=pt(!1);b.kind==="recommend"&&Nt(b.rec,{silent:!0})}else if(c.kind==="briefing"){h({kind:"note",tone:"info",text:`\u{1F4E5} ${Vr(c.delta)} arrived while you were away (${cu(c.awayMs)}).`});let b=pt(!1);b.kind==="recommend"&&Nt(b.rec)}}catch{}if(la.current=Date.now(),!D){if(x){if(d.escape){if(Ee.current){if(!Ee.current.signal.aborted){let c=(Mo?.verb??"work").toLowerCase(),b=Mo?.unit??"article";h({kind:"note",tone:"warn",text:`\u238B Stopping the ${c} run (finishing in-flight ${b}s)\u2026`}),Ee.current.abort()}return}_o.current||(_o.current=!0,h({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),ut.current?.interrupt());return}if(d.return){let c=y.trim();if(!c)return;bn.current.push(c),Zi([...bn.current]),v("");return}if(ed(u,d))return;if(d.upArrow){ps(-1);return}if(d.downArrow){ps(1);return}if(d.backspace||d.delete){S();return}u&&!d.ctrl&&!d.meta&&Ju(u);return}if(hn){if(d.upArrow){fn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){fn(c=>c&&{...c,cursor:Math.min(Ct.length-1,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=Ct.length){fn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let c=Ct[hn.cursor];fn(null);let{lines:b,changed:T,effective:q}=Cr(e,c.value??"default");for(let m of b)h({kind:"note",tone:m.startsWith("\u26A0")?"warn":m.startsWith("\u2713")?"ok":"info",text:m});T&&(Iu(m=>m+1),ut.current?.setModel(q));return}if(u==="s"){let c=Ct[hn.cursor];fn(null),ut.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){fn(null);return}return}if(Bt){if(d.upArrow){Bn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){Bn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=Bt.rows.length){Bn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return||u==="s"){let c=Bt.rows[Bt.cursor];Bn(null),ma(c.name,d.return===!0);return}if(d.escape){Bn(null);return}return}if(Uo){if(d.escape){$n(null);return}if(d.leftArrow||d.tab&&d.shift){$n(c=>c&&{tab:(c.tab-1+Xe.length)%Xe.length,scroll:0});return}if(d.rightArrow||d.tab){$n(c=>c&&{tab:(c.tab+1)%Xe.length,scroll:0});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=Xe.length){$n({tab:Number(u)-1,scroll:0});return}if(d.upArrow){$n(c=>c&&{...c,scroll:Math.max(0,c.scroll-1)});return}if(d.downArrow){$n(c=>{if(!c)return c;let b=(Xe[c.tab]??Xe[0]).rows.length;return{...c,scroll:Math.min(Math.max(0,b-1),c.scroll+1)}});return}return}if(Ht){if(d.upArrow){Hn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){Hn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=Ht.rows.length){Hn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let c=Ht.rows[Ht.cursor].name;if(Hn(null),!Aa(e,c).created){h({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}h({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${c}").`});let T=!1;try{let q=_n(c);T=!!q&&!(cn(q)&&!q.refreshToken)}catch{T=!1}h({kind:"note",tone:"info",text:T?`Next: sign in to ${c} and pick your project \u2014 you're already signed in here, so it'll be quick.`:`Next: sign in to Document360 (${c}) and pick your project.`}),J("/login"),Y(q=>q+1);return}if(d.escape){Hn(null);return}return}if(Ve){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)<=Ve.rows.length){qn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let c=Ve.rows[Ve.cursor],{profile:b,projectId:T}=Ve;qn(null),ls(b,T,c);return}if(d.escape){qn(null);return}return}if(dt){if(d.upArrow){mn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){mn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=dt.rows.length){mn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let c=dt.rows[dt.cursor],{profile:b}=dt;mn(null),us(b,c);return}if(d.escape){mn(null);return}return}if(Ye){if(d.upArrow){Yn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){Yn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u===" "){Yn(c=>c&&{...c,rows:c.rows.map((b,T)=>T===c.cursor?{...b,checked:!b.checked}:b)});return}if(d.return){let c=Ye.rows.filter(b=>b.checked).map(b=>b.path);if(Yn(null),c.length===0){h({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}yl(e,c),h({kind:"note",tone:"ok",text:`\u2713 Scoped to ${c.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let b of c)h({kind:"note",tone:"info",text:` ${b}`});h({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(d.escape){Yn(null);return}return}if(yt){if(d.upArrow){yn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){yn(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){yn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let c=yt.rows[yt.cursor],b=yt.run;yn(null),b(c.token);return}if(d.escape){yn(null);return}return}if(Et){if(d.upArrow){Gn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){Gn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=Et.rows.length){Gn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let c=Et.rows[Et.cursor],b=Et.conflicts;Gn(null),c.conflict?ga(c.paths[0]):c.kind==="article"?ha(c.paths[0]):ht(c.paths,c.kind==="all"?b:0);return}if(d.escape){Gn(null);return}return}if(At){let{rows:c}=At;if(d.upArrow){Dt(b=>b&&{...b,cursor:Math.max(0,b.cursor-1)});return}if(d.downArrow){Dt(b=>b&&{...b,cursor:Math.min(c.length-1,b.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let b=Qm(Tu.current,Number(u),c.length-1);Tu.current=b.memory,b.index!==null&&Dt(T=>T&&{...T,cursor:b.index+1});return}if(u==="a"||u==="A"){Dt(b=>b&&{...b,cursor:0});return}if(d.return){let b=c[At.cursor],{groups:T,resolve:q,report:m}=At;if(Dt(null),b.kind==="all"){pa(T,{resolve:q,report:m});return}Xn(gi(b.group,{width:Le()})),Oo({group:b.group,cursor:0,fromList:!0,resolve:q,rest:T.filter(f=>f.articleId!==b.group.articleId),report:m});return}if(d.escape){Dt(null),J("/comments");return}return}if(je){let c=()=>{let{rest:b,group:T,fromList:q,resolve:m,report:f}=je;if(Oo(null),!q||!f){J("/comments");return}let $=[T,...b].sort((k,R)=>k.category.localeCompare(R.category)||k.title.localeCompare(R.title));Dt({cursor:0,rows:yi($),groups:$,resolve:m,report:f})};if(d.upArrow||d.downArrow){Oo(b=>b&&{...b,cursor:b.cursor===0?1:0});return}if(u==="y"||u==="Y"||d.return&&je.cursor===0){let{group:b,resolve:T,rest:q,report:m}=je;Oo(null),pa([b],{resolve:T,rest:q,...m?{report:m}:{}});return}if(u==="b"||u==="B"||d.escape||d.return){c();return}return}if(qt){if(d.upArrow){gn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){gn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=qt.rows.length){gn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let c=qt.rows[qt.cursor];gn(null),c.action==="capture"?Xo(c.ids,{runLine:c.kind==="all"?["/screenshot capture --all","/capture --all"]:void 0}):c.kind==="shot"?Ku(c.ids[0]):Yu(c.ids,{setup:!0,runLine:c.kind==="all"?["/screenshot author --all","/screenshot --all"]:void 0});return}if(d.escape){gn(null);return}return}if(nt){if(d.escape){wn(null);return}if(d.upArrow){wn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){wn(c=>c&&{...c,cursor:Math.min(Math.max(0,rs.length-1),c.cursor+1)});return}if(d.return){let c=rs[nt.cursor];if(c){wn(null);try{h({kind:"preview",name:Kr(c),text:Jg(Gi(hu(e,c),"utf8"))})}catch(b){h({kind:"note",tone:"error",text:`Could not read ${c}: ${b.message}`})}}return}if(d.backspace||d.delete){wn(c=>c&&{...c,query:c.query.slice(0,-1),cursor:0});return}if(u&&!d.ctrl&&!d.meta&&u.length===1){wn(c=>c&&{...c,query:c.query+u,cursor:0});return}return}if(rt){if(d.escape){kn(null);return}if(d.upArrow){kn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){kn(c=>c&&{...c,cursor:Math.min(Math.max(0,ss.length-1),c.cursor+1)});return}if(d.return){let c=ss[rt.cursor];if(c){kn(null),He(c.uuid),Tt.current={uuid:c.uuid,firstPrompt:c.firstPrompt,titleFired:!0},pn(c.name),fu(c.uuid),Un.current=[],Ue.current={printed:[],armed:[],printedAt:Kn.current};let b=iu(e,c.uuid);for(let T of b)h(T);h({kind:"note",tone:"ok",text:b.length?`Resumed "${c.name}" \u2014 restored ${b.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){kn(c=>c&&{...c,query:c.query.slice(0,-1),cursor:0});return}if(u&&!d.ctrl&&!d.meta&&u.length===1){kn(c=>c&&{...c,query:c.query+u,cursor:0});return}return}if(d.tab&&!y&&le){v(le),wt();return}if(!y&&Z.length>0&&!tt&&u&&/^[1-9]$/.test(u)){let c=Z[Number(u)-1];if(c){v(Ln(c));return}}if(!y&&Z.length===0&&!tt&&Ue.current.armed.length>0&&u&&/^[1-9]$/.test(u)){let c=Ue.current.armed[Number(u)-1];if(c){v(c);return}}if(!y&&(ts||qo)&&u==="c"&&!d.ctrl&&!d.meta&&!d.return&&!d.tab){let c=ts!=null;ou(ts??qo).then(T=>{h({kind:"note",tone:T?"ok":"warn",text:T?c?"\u2713 Copied the feedback to your clipboard \u2014 send it to the d360-writer team (Teams / Slack / email).":"\u2713 Copied the prompt to your clipboard \u2014 paste it into your repo's coding agent.":c?"Couldn't reach your clipboard \u2014 select the feedback above and copy it manually.":"Couldn't reach your clipboard \u2014 select the prompt above and copy it manually."}),T&&c&&aa(null),T&&!c&&Ou(!0)});return}if(!ed(u,d)){if(Hu){if(d.upArrow){Fn(c=>Math.max(0,c-1));return}if(d.downArrow){Fn(c=>Math.min(jt.length-1,c+1));return}if(d.tab){v("/"+(jt[Xi]?.name??"")+" "),Fn(0);return}if(d.return){let c=jt[Xi];if(c){let b=y.trim().slice(1).split(/\s+/).slice(1).join(" ");if(tp(c.usage)&&!b){v("/"+c.name+" "),Fn(0);return}ds("/"+c.name+(b?" "+b:""));return}}}else{if(d.upArrow){if(y!==""&&Wn===null){ps(-1);return}let c=Qi.current;if(!c.length)return;let b=Wn===null?c.length-1:Math.max(0,Wn-1);zr(b),v(c[b]??"");return}if(d.downArrow){if(y!==""&&Wn===null){ps(1);return}let c=Qi.current;if(Wn===null)return;let b=Wn+1;b>=c.length?(zr(null),v("")):(zr(b),v(c[b]??""));return}}if(d.return){ds();return}if(d.backspace||d.delete){S();return}if(d.escape){v(""),Fn(0),wt(),ue([]),Vn(null),Te.current=!0;return}u&&!d.ctrl&&!d.meta&&Ju(u)}}}),et(()=>{if(x||D)return;let u=bn.current.shift();u!==void 0&&(Zi([...bn.current]),ds(u))},[x,D,ds]),oe(Ce,{flexDirection:"column",width:Ke,children:[da!==null&&oe(Ce,{marginTop:1,flexDirection:"column",children:[da.truncated&&W(U,{dimColor:!0,children:"\u2026"}),W(U,{children:da.text})]}),x&&Mo?W(RS,{p:Mo}):null,Du?W(xS,{text:Du}):x&&!Mo?W(vS,{startTime:Pt.current,chars:ay}):null,W(Ce,{borderStyle:"round",borderColor:Bu.prod?"yellow":ne,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:y?Zu.map((u,d)=>{let c=p.text.slice(u.start,u.end),b=d===qi(Zu,p.pos),T=Math.min(p.pos,u.end)-u.start;return oe(U,{children:[W(U,{color:ne,children:d===0?"> ":" "}),b?oe(Ao,{children:[c.slice(0,T),W(Eo,{ch:c[T]??" "}),c.slice(T+1)]}):c||" "]},`${d}-${u.start}`)}):oe(U,{children:[W(U,{color:ne,children:"> "}),Bo?W(Eo,{ch:" "}):le&&!x&&ce?oe(Ao,{children:[W(Eo,{ch:ce[0],dim:!0}),W(U,{color:"gray",children:ce.slice(1)})]}):le&&!x?oe(Ao,{children:[W(Eo,{ch:le[0],dim:!0}),W(U,{color:"gray",children:le.slice(1)}),W(U,{dimColor:!0,children:" (tab)"})]}):(ca.isSetup||!un)&&!x?oe(Ao,{children:[W(Eo,{ch:ca.text[0],dim:!0}),W(U,{color:"gray",children:ca.text.slice(1)})]}):W(Eo,{ch:" "})]})}),Au.length>0&&W(Ce,{flexDirection:"column",paddingX:1,children:Au.map((u,d)=>W(U,{color:"gray",children:`\u29D7 queued: ${u}`},`${d}-${u.slice(0,24)}`))}),Uo?W(ug,{tab:Uo.tab,scroll:Uo.scroll,rows:hy,width:Ke,version:o,engineVersion:Zg}):hn?oe(Ce,{flexDirection:"column",paddingX:1,children:[W(U,{color:ne,bold:!0,children:"Select model"}),W(U,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),Ct.map((u,d)=>oe(U,{color:d===hn.cursor?ne:void 0,children:[d===hn.cursor?"\u276F ":" ",`${d+1}. ${u.label}${d===hn.current?" \u2714":""}`.padEnd(16),W(U,{color:"gray",children:u.desc})]},u.label)),W(U,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Bt?oe(Ce,{flexDirection:"column",paddingX:1,children:[W(U,{color:ne,bold:!0,children:"Switch connection profile"}),W(On,{rows:Bt.rows,cursor:Bt.cursor,cap:Kt,render:(u,d,c)=>oe(U,{color:c?ne:void 0,children:[c?"\u276F ":" ",`${d+1}. ${u.name}${d===Bt.current?" \u2714":""}`.padEnd(20),W(U,{color:"gray",children:`${u.env} \xB7 ${u.who??"not signed in"}`}),u.prod?W(U,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},u.name)}),W(U,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Ht?oe(Ce,{flexDirection:"column",paddingX:1,children:[W(U,{color:ne,bold:!0,children:"Pick your Document360 environment"}),W(On,{rows:Ht.rows,cursor:Ht.cursor,cap:Kt,render:(u,d,c)=>oe(U,{color:c?ne:void 0,children:[c?"\u276F ":" ",`${d+1}. ${u.name}`.padEnd(16),W(U,{color:"gray",children:u.apiUrl}),u.note?W(U,{color:"yellow",children:` \u26A0 ${u.note}`}):null]},u.name)}),W(U,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):Ve?oe(Ce,{flexDirection:"column",paddingX:1,children:[W(U,{color:ne,bold:!0,children:"Switch workspace"}),W(U,{dimColor:!0,children:`environment ${Ve.environment} \xB7 project ${Ve.projectName??`${Ve.projectId.slice(0,8)}\u2026`}`}),W(On,{rows:Ve.rows,cursor:Ve.cursor,cap:Kt,render:(u,d,c)=>oe(U,{color:c?ne:void 0,children:[c?"\u276F ":" ",`${d+1}. ${u.name}${d===Ve.current?" \u2714":""}`.padEnd(30),W(U,{color:"gray",children:u.type??""})]},u.id)}),W(U,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):dt?oe(Ce,{flexDirection:"column",paddingX:1,children:[W(U,{color:ne,bold:!0,children:"Choose project"}),W(U,{dimColor:!0,children:`environment ${dt.environment}`}),W(On,{rows:dt.rows,cursor:dt.cursor,cap:Kt,render:(u,d,c)=>oe(U,{color:c?ne:void 0,children:[c?"\u276F ":" ",`${d+1}. ${u.name}${d===dt.current?" \u2714":""}`.padEnd(30),W(U,{color:"gray",children:u.sub??""})]},u.id)}),W(U,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):Ye?(()=>{let d=Math.min(Math.max(0,Ye.cursor-Math.floor(7)),Math.max(0,Ye.rows.length-14)),c=Ye.rows.slice(d,d+14),b=Ye.rows.filter(T=>T.checked).length;return oe(Ce,{flexDirection:"column",paddingX:1,children:[W(U,{color:ne,bold:!0,children:`Which folders back the user docs? (${b} selected of ${Ye.rows.length})`}),d>0?W(U,{dimColor:!0,children:` \u2191 ${d} more`}):null,c.map((T,q)=>{let m=d+q;return oe(U,{color:m===Ye.cursor?ne:void 0,children:[m===Ye.cursor?"\u276F ":" ",T.checked?"\u25C9 ":"\u25CB ",T.path.padEnd(Math.min(48,Ke-34)),W(U,{color:"gray",children:ei(T)})]},T.path)}),d+14<Ye.rows.length?W(U,{dimColor:!0,children:` \u2193 ${Ye.rows.length-d-14} more`}):null,W(U,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():yt?oe(Ce,{flexDirection:"column",paddingX:1,children:[W(U,{color:ne,bold:!0,children:yt.title??"Which category? (pick one to scope to)"}),W(On,{rows:yt.rows,cursor:yt.cursor,cap:Kt,render:(u,d,c)=>oe(U,{color:c?ne:void 0,children:[c?"\u276F ":" ",`${`${d+1}.`.padEnd(3)} ${u.label} (${u.count})`.padEnd(Math.min(44,Math.max(20,Ke-24))),W(U,{color:"gray",children:` ${u.token}`})]},u.token)}),W(U,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):Et?oe(Ce,{flexDirection:"column",paddingX:1,children:[W(U,{color:ne,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),W(On,{rows:Et.rows,cursor:Et.cursor,cap:Kt,render:(u,d,c)=>oe(U,{color:c?ne:void 0,bold:u.kind==="category"&&!c,children:[c?"\u276F ":" ",`${u.indent?" ":" "}${`${d+1}.`.padEnd(3)} ${u.label}`.padEnd(Math.min(56,Ke-24)),u.note?W(U,{color:"gray",children:u.note}):null]},`${u.kind}:${u.paths.join(",")}`)}),W(U,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):At?oe(Ce,{flexDirection:"column",paddingX:1,children:[W(U,{color:ne,bold:!0,children:"Which comments do you want to look at?"}),W(On,{rows:At.rows,cursor:At.cursor,cap:Kt,render:(u,d,c)=>oe(U,{color:c?ne: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,Ke-24))),u.kind==="article"?W(U,{color:"gray",children:u.note}):null]},u.kind==="all"?"all":u.group.articleId)}),W(U,{dimColor:!0,children:"\u2191\u2193 move \xB7 type a number \xB7 enter \xB7 esc close"}),At.resolve?W(U,{dimColor:!0,children:"--resolve is on: threads you answer will be closed as well as replied to"}):null]}):je?oe(Ce,{flexDirection:"column",paddingX:1,children:[W(U,{color:ne,bold:!0,children:`${je.group.title} \u2014 ${je.group.threads.length} comment${je.group.threads.length===1?"":"s"}`}),oe(U,{color:je.cursor===0?ne:void 0,children:[je.cursor===0?"\u276F ":" ",je.resolve?"Yes \u2014 fix them, push the draft, reply and resolve":"Yes \u2014 fix them, push the draft to Document360, then reply"]}),oe(U,{color:je.cursor===1?ne:void 0,children:[je.cursor===1?"\u276F ":" ",je.fromList?"No \u2014 back to the list":"No \u2014 leave them for now"]}),W(U,{dimColor:!0,children:"\u2191\u2193 move \xB7 enter select \xB7 y answer \xB7 esc back"})]}):qt?oe(Ce,{flexDirection:"column",paddingX:1,children:[W(U,{color:ne,bold:!0,children:qt.title}),(()=>{let{rows:u,cursor:d}=qt,c=_i(u.length,d,Kt),b=c.start,T=u.slice(c.start,c.end),q=`${u.length}.`.length+1,m=Kp(u,Math.max(20,Ke-4-q));return oe(Ao,{children:[b>0?W(U,{color:"gray",children:` \u2026 ${b} more above`}):null,T.map((f,$)=>{let k=b+$,R=k===d,C=m[k];return oe(U,{color:R?ne:void 0,bold:(f.kind==="all"||f.kind==="category")&&!R,children:[R?"\u276F ":" ",`${k+1}.`.padEnd(q),C.head,C.note?W(U,{color:"gray",children:C.note}):null]},`${f.action}:${f.kind}:${f.ids.join(",")}`)}),c.below>0?W(U,{color:"gray",children:` \u2026 ${c.below} more below`}):null]})})(),W(U,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter run \xB7 esc cancel"})]}):nt?oe(Ce,{flexDirection:"column",paddingX:1,children:[W(U,{color:ne,bold:!0,children:`Preview article${nt.query?` \u2014 filter: ${nt.query}`:" (type to filter)"}`}),rs.length===0?W(U,{color:"gray",children:"no articles match"}):rs.map((u,d)=>oe(U,{color:d===nt.cursor?ne:void 0,children:[d===nt.cursor?"\u276F ":" ",u]},u)),W(U,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):rt?oe(Ce,{flexDirection:"column",paddingX:1,children:[W(U,{color:ne,bold:!0,children:`Resume session${rt.query?` \u2014 filter: ${rt.query}`:" (type to filter)"}`}),ss.length===0?W(U,{color:"gray",children:"no sessions match"}):ss.map((u,d)=>oe(U,{color:d===rt.cursor?ne:void 0,children:[d===rt.cursor?"\u276F ":" ",u.name.slice(0,28).padEnd(30),W(U,{color:d===rt.cursor?ne:"gray",children:u.firstPrompt.slice(0,Math.max(10,Ke-40))})]},u.uuid)),W(U,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Hu?oe(Ce,{flexDirection:"column",children:[vn>0?W(U,{dimColor:!0,children:` \u22EF ${vn} more above`}):null,ua.map((u,d)=>{let c=vn+d,b=u.name==="model"&&ea?`${u.desc} (currently ${ea})`:u.desc,T=Math.max(20,Ke-4),q=u.usage.length>T?`${u.usage.slice(0,T-1)}\u2026`:u.usage,m=T-Math.max(q.length,22)-1,f=m<=1?"":b.length>m?`${b.slice(0,m-1)}\u2026`:b;return oe(U,{color:c===os?ne:void 0,children:[c===os?"\u276F ":" ",q.padEnd(22)," ",W(U,{color:c===os?ne:"gray",children:f})]},u.name)}),vn+ua.length<jt.length?W(U,{dimColor:!0,children:` \u22EF ${jt.length-vn-ua.length} more below`}):null,W(U,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!x&&!y&&Z.length>0?oe(Ce,{flexDirection:"column",paddingX:1,children:[Eu?W(U,{color:ne,children:Eu}):null,Z.map((u,d)=>{let c=Ln(u),b=c.slice(0,Math.max(20,Ke-5)),T=Ke-b.length-7,q=T>=12?(mg(u)??Zd(c)).slice(0,T):"";return oe(U,{children:[W(U,{color:ne,children:d+1})," ",b,q?W(U,{dimColor:!0,children:` \u2014 ${q}`}):null]},c)}),W(U,{dimColor:!0,children:`press 1-${Z.length} to fill \xB7 esc cancel`})]}):W(Ce,{paddingX:1,children:oe(U,{color:"gray",children:[Bu.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${ea??"model n/a"}${t.kind==="api"?ju>0?` \xB7 ${Qe(ju)}`:"":Nu>0?` \xB7 ${nn(Nu)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}ee();import{jsx as ES}from"react/jsx-runtime";async function ty(e=process.cwd(),t="auto",n,o="0.0.0"){let r=TS(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 ${K("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${K("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=PS(ES(ey,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
|
|
507
|
-
`),process.exit(0)}ee();import{writeCrashLog as
|
|
508
|
-
`+
|
|
509
|
-
`),r&&process.stderr.write(
|
|
510
|
-
`+
|
|
511
|
-
`),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var
|
|
488
|
+
Not blocked: /write <path> still authors a single article, and /write --preview costs nothing.`}),ue(Di.options.map(z=>({cmd:z.cmd,desc:z.desc}))),zn(Di.title);return}let{docsDir:_,targets:W,reason:V,rewriting:A}=pi(e,m,{scope:f,path:$,rewrite:x});if(W.length===0){h({kind:"note",tone:"warn",text:V??"Nothing to write."});return}A&&h({kind:"note",tone:"warn",text:`--rewrite: regenerating ${W.length} already-written article${W.length===1?"":"s"} (overwrites them; git has your baseline).`});let M=Ru(W),L=Kl(R),q=No(e,"standard"),ie=!!$;if(b&&!ie){let z=Jg({files:Xl(e,m,W),op:"write",model:q.model}),me=f?`Scope: ${f} (${W.length} pending)
|
|
489
|
+
`:"",Me=`
|
|
490
|
+
Model: ${q.model}${q.forced?" (forced)":" \u2014 authoring; /model to override"}`;h({kind:"note",tone:"info",text:me+Jl(M,z,L).join(`
|
|
491
|
+
`)+Me}),Q(`/write${f?` --scope ${f}`:""}`);return}Tt.current=Date.now(),Bt(0),T(!0);let we=new AbortController;Ee.current=we,de({verb:"Writing",total:M.length,done:0,active:[],rows:_n(M),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),h({kind:"note",tone:"info",text:`Writing ${W.length} article${W.length===1?"":"s"} in ${M.length} batch${M.length===1?"":"es"} (\u2264${L} agents at once) on ${q.model}${q.forced?" (forced)":""}\u2026 (esc to stop)`});let Qe=new Set;try{for await(let z of Do({cwd:e,partitions:M,promptFor:me=>Ql(me,_,{rewrite:A||ie}),concurrency:L,profileName:s,allowProdWrites:Ht.current,model:q.model,signal:we.signal}))if(z.type==="partition_status")z.status==="running"?de(me=>me&&{...me,active:[...me.active,z.label],rows:Be(me.rows,z.label,"active"),lastAt:Date.now()}):de(me=>me&&{...me,active:me.active.filter(Me=>Me!==z.label),done:me.done+1,rows:Be(me.rows,z.label,z.status==="done"?"done":"failed"),lastAt:Date.now()});else if(z.type==="partition_event"){let me=null;if(z.event.type==="tool"){let Me=Rg(z.event.name,z.event.input,M[z.index]?.paths??[]);Me&&!Qe.has(Me)&&(Qe.add(Me),me=z.label)}de(Me=>{if(!Me)return Me;let bt={...Me,lastAt:Date.now()};return z.event.type==="tool"?bt.tools=Me.tools+1:z.event.type==="text"&&(bt.chars=Me.chars+z.event.delta.length),me&&(bt.rows=Cg(bt.rows,me)),bt})}else if(z.type==="run_done"){zt(Fe=>Fe+z.totalCostUsd),Kt(Fe=>Fe+z.results.reduce((st,Sn)=>st+Sn.outputTokens,0));let me=z.aborted?"Stopped. ":"",Me=t.kind==="api"?"api":"subscription",bt=$t(z,"The write");if(h({kind:"note",tone:bt||z.aborted?"warn":z.ok?"ok":"warn",text:bt?bt.join(`
|
|
492
|
+
`):me+Zl(z.results,M,Me,f??$).join(`
|
|
493
|
+
`)}),bt){Q("/doctor");continue}let hd=_s(z);if(hd&&h({kind:"note",tone:"warn",text:hd}),!z.aborted&&z.ok)try{let Fe=(Qe.size>0?[...Qe]:W).map(st=>`${_}/${st}`);jo(e,Fe,{writtenCap:ES,reviewedCap:0,checkedCap:0})}catch{}let ro=z.aborted?[]:Sr(e,_,W),fd=ec(ro);fd&&h({kind:"note",tone:"warn",text:fd});let so=z.aborted||w.includes("--skip-style")?null:tc(ro);if(so){let Fe=so.errors.length,st=await cs({partitions:so.partitions,promptFor:so.promptFor,concurrency:bo,verb:"Fixing",doneNoun:"fixed",headline:`${Fe} style error${Fe===1?"":"s"} in ${so.articles} of the new article${so.articles===1?"":"s"} \u2014 fixing now, one pass`});if(st.covered.length>0)try{jo(e,st.covered,Ye("lint"))}catch{}ro=Sr(e,_,W);let Sn=nc(Fe,ro);h({kind:"note",tone:Sn[0].startsWith("\u2713")?"ok":"warn",text:Sn.join(`
|
|
494
|
+
`)})}if(!z.aborted&&z.ok){let Fe=f??$??"",st=Fe?` ${Fe}`:"",Sn=ro.some(va=>va.severity==="error"),md=Fe?"/publish":"/publish --all",Ey=Fe?`/screenshot author ${Fe}`:"/screenshot author --all";Ae(Sn?`Written, but ${ro.filter(va=>va.severity==="error").length} style error(s) are still unfixed. /lint${st} --fix retries them, then /review${st} --fix for editorial quality, then ${md}.`:`Written. I\u2019d run /review${st} --fix next \u2014 editorial review that applies its fixes \u2014 then ${md} pushes the drafts up (add ${Ey} first if you want images).`,{kind:"cmd",cmd:Sn?`/lint${st} --fix`:`/review${st} --fix`,reason:""})}}}catch(z){h({kind:"note",tone:"error",text:`Write run failed: ${z.message}`})}finally{Ee.current=null,de(null),T(!1),Y(z=>z+1)}return}case"draft":{if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:m,looseDocs:f}=rc(e);if(m.length===0&&f===0){h({kind:"note",tone:"info",text:ic});return}let $=w.join(" ").trim();if(!$&&m.length>1){h({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
|
|
495
|
+
${m.map(x=>` \u2022 ${x.name} (${x.docCount} doc${x.docCount===1?"":"s"})`).join(`
|
|
496
|
+
`)}`}),ue(m.map(x=>`/draft ${x.name}`));return}let b="",R;if($){let x=sc(m,$);x?b=x:R=$}else b=m[0]?.name??"";await ye(hi(b,R),{display:$?`/draft ${$}`:"/draft",quietUser:!0});return}case"pull":{if(!Jn(u.trim()))return;let m=w.find(f=>f.startsWith("--"));try{if(m==="--status"){h({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let b=Date.now(),R=await Qi({cwd:e,profileName:s});h({kind:"note",tone:"info",text:si(R,Date.now()-b).join(`
|
|
497
|
+
`)});return}if(m==="--baseline"){let b=w.find(W=>!W.startsWith("--")),R=b?b.replace(/\\/g,"/"):void 0;h({kind:"note",tone:"info",text:R?`Setting the sync baseline for ${R}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let x=await mS({cwd:e,profileName:s,relPaths:R?[R]:void 0}),_=R?{rebaselined:[],skipped:[]}:await gS({cwd:e,profileName:s});if(x.baselined.length===0&&x.skipped.length===0&&_.rebaselined.length===0){h({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}x.baselined.length>0&&h({kind:"note",tone:"ok",text:`\u2713 Recorded ${x.baselined.length} article${x.baselined.length===1?"":"s"} as matching Document360 \u2014 they read in-sync until either side changes.`}),_.rebaselined.length>0&&h({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${_.rebaselined.length} article${_.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),x.skipped.length>0&&h({kind:"note",tone:"warn",text:`${x.skipped.length} skipped:
|
|
498
|
+
${x.skipped.map(W=>` - ${W.path} (${W.reason})`).join(`
|
|
499
|
+
`)}`}),Y(W=>W+1);return}if(m==="--compare"){h({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let b=await fS({cwd:e,profileName:s}),R=b.onlyInLegacy.length===0&&b.onlyInManifest.length===0&&b.mappedMissingFromManifest.length===0,x=[`Legacy listing: ${b.legacyCount} \xB7 Manifest: ${b.manifestCount} \xB7 in both: ${b.inBoth}`];R?x.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(b.mappedMissingFromManifest.length&&x.push(`\u2717 ${b.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${b.mappedMissingFromManifest.slice(0,5).join(", ")}`),b.onlyInLegacy.length&&x.push(`\u26A0 ${b.onlyInLegacy.length} only in the legacy listing: ${b.onlyInLegacy.slice(0,5).join(", ")}`),b.onlyInManifest.length&&x.push(`\u26A0 ${b.onlyInManifest.length} only in the manifest: ${b.onlyInManifest.slice(0,5).join(", ")}`),x.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),h({kind:"note",tone:R?"ok":"warn",text:x.join(`
|
|
500
|
+
`)});return}if(m){h({kind:"note",tone:"error",text:`Unknown option: ${m} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let f=w[0];if(f){let b=await zg({cwd:e,profileName:s,relPath:f.replace(/\\/g,"/")});Ce.current=[{plan:b,mode:b.overwritesLocalChanges?"conflict":"pull"}],fn.current=[],to();return}h({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let $=await Nl({cwd:e,profileName:s});for(let b of jl($))h({kind:"note",tone:b.tone,text:b.text});Y(b=>b+1)}catch(f){h({kind:"note",tone:"error",text:`Pull failed: ${f.message}`})}return}case"scope":{if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=yS(e);if(m.length===0){h({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.'});return}Xn({cursor:0,rows:m.map(f=>({...f,checked:f.recommended}))});return}case"audit":{if(w[0]==="--auto"){let f=ge(e);if(!f){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let $=w[1]!=="off";Gg({...f,autoAudit:$},e),h({kind:"note",tone:"ok",text:$?"\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 m=await br();m.kind==="forward-to-agent"&&m.prompt&&((await ye(m.prompt,{display:m.display,quietUser:!0})).producedNothing||(Hr(e,s),Y($=>$+1)));return}case"lint":case"check":{let m=Ft(c);m&&h({kind:"note",tone:"info",text:`\u2192 ${m}`});let f=w.find(R=>!R.startsWith("--")),$=f?` ${f}`:"",b=Ji({cwd:e,scope:f});if(w.includes("--fix")){let R=ql(e,w,b);if(!R){h({kind:"note",tone:"ok",text:"\u2713 Nothing to fix \u2014 the docs are already clean."});return}if(R.kind==="partitioned"){let V=await cs({partitions:R.partitions,promptFor:R.promptFor,concurrency:bo,verb:"Fixing",doneNoun:"fixed",headline:`Fixing ${R.findings} issue${R.findings===1?"":"s"} across ${R.articles} article${R.articles===1?"":"s"} in ${R.partitions.length} batches (\u2264${bo} at once)`});if(V.covered.length>0)try{jo(e,V.covered,Ye("lint"))}catch{}if(V.aborted){let A=$r({cwd:e,after:Ji({cwd:e,scope:f}).filter(M=>!M.baselined),scope:f,aborted:!0});Ae(A.text,{kind:"cmd",cmd:A.cmd,reason:""},"warn");return}}else{h({kind:"note",tone:"info",text:`Fixing ${R.findings} doc issue${R.findings===1?"":"s"}\u2026`});let V=ny(e,f);await ye(R.prompt,{display:R.display,quietUser:!0});try{jo(e,V,Ye("lint"))}catch{}}let x=Ji({cwd:e,scope:f}).filter(V=>!V.baselined),_=Math.max(0,R.findings-x.length);h({kind:"note",tone:x.some(V=>V.severity==="error")?"warn":"ok",text:x.length===0?`\u2713 Lint: all ${R.findings} issue${R.findings===1?"":"s"} resolved.`:[`\u2713 Lint: fixed ${_} of ${R.findings}.`,"",...vr(x)].join(`
|
|
501
|
+
`)});let W=$r({cwd:e,after:x,before:R.findings,scope:f});Ae(W.text,{kind:"cmd",cmd:W.cmd,reason:""});return}if(h({kind:"note",tone:b.length===0?"ok":"warn",text:vr(b,{full:w.includes("--full"),baselined:w.includes("--baselined")}).join(`
|
|
502
|
+
`)}),b.length>0){let R=ti(e,f)===0?"; /publish --all publishes as-is":"";Ae(`Found ${b.length} doc issue${b.length===1?"":"s"} above. /lint${$} --fix has the agent fix them in place (or /review${$} --fix for the full editorial pass${R}).`,{kind:"cmd",cmd:`/lint${$} --fix`,reason:""})}return}case"structure":{let m=Wr(e,s);if(m.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):","",...m].join(`
|
|
503
|
+
`)});return}case"reorder":{let m=eu(e,w);if(!m){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let f=await ye(m.prompt,{display:m.display,quietUser:!0}),$=Ct(e,{text:"Reordered locally \u2014 /publish --all syncs the new order to Document360.",cmd:"/publish --all"},"Reordered locally. ");Ko(f,$.text,{kind:"cmd",cmd:$.cmd,reason:""});return}case"review":{let m=Jc(e,w);if(!m){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let f=w.includes("--fix"),$=w.find(x=>!x.startsWith("--")),b=f?ny(e,$):[],R=m.kind==="partitioned"?await Ry(m,f):await ye(m.prompt,{display:m.display,quietUser:!0});if("aborted"in R&&R.aborted){let x=Ne("/review","--fix",$);Ae(`Stopped \u2014 the partitions that finished are saved. ${x} picks up the rest${$?"":", or narrow it with /review <category> --fix"}.`,{kind:"cmd",cmd:x,reason:""},"warn");return}if(m.kind!=="partitioned"&&f&&!R.producedNothing)try{jo(e,b,Ye("review"))}catch{}if(f){let x=f&&!R.producedNothing?Ji({cwd:e,scope:$}).filter(W=>!W.baselined&&W.severity==="error"):[];if(x.length>0){let W=new Set(x.map(V=>V.path)).size;h({kind:"note",tone:"warn",text:`\u26A0 The editor's rewrites left ${x.length} style error${x.length===1?"":"s"} in ${W} article${W===1?"":"s"} \u2014 recasting a sentence is where these appear.`}),Ko(R,`Editor applied its fixes, but ${x.length} style error${x.length===1?"":"s"} remain. /lint${$?` ${$}`:""} --fix clears them \u2014 it costs nothing to find them and one pass to correct.`,{kind:"cmd",cmd:`/lint${$?` ${$}`:""} --fix`,reason:""});return}let _=Ct(e,{text:`\u2713 Editor applied its fixes \u2014 your docs are corrected. /publish${$?"":" --all"} pushes them up (or /lint${$?` ${$}`:""} for an instant no-token re-scan first).`,cmd:$?"/publish":"/publish --all"},"\u2713 Editor applied its fixes to this scope. ",$);Ko(R,_.text,{kind:"cmd",cmd:_.cmd,reason:""})}else{let x=$?` ${$}`:"",_=ti(e,$)===0&&gl(e,$)===0?`; /publish${$?"":" --all"} publishes as-is`:"";Ko(R,`The review listed issues above. /review${x} --fix lets the editor apply them all (or /lint${x} --fix for just the deterministic ones${_}).`,{kind:"cmd",cmd:`/review${x} --fix`,reason:""})}return}case"capture-setup":{await B();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:uo(co(e)).join(`
|
|
504
|
+
`)}),Xt(Pn()),Jo.current=mt(e).status==="current",Zn.current=Ot(e);return}case"discover":{if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await ye(Pl(),{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(Sc(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 ye(Pc(),{display:"/inbox",quietUser:!0});return}case"share":{let m=ge(e);if(!m){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let f=w[0]?.trim().toLowerCase();if(f==="status"){for(let b of wi(e,m))h({kind:"note",tone:b.tone,text:b.text});return}if(f==="on"||f==="off"){for(let b of Tc(e,m,f==="on"))h({kind:"note",tone:b.tone,text:b.text});Y(b=>b+1);return}if(f){h({kind:"note",tone:"error",text:`Unknown option: ${f} \u2014 use /share, /share status, /share on, or /share off.`});return}h({kind:"note",tone:"info",text:"Exchanging work with your team\u2026"});let $=await ki(e,m);for(let b of $.lines)h({kind:"note",tone:b.tone,text:b.text});$.changed&&Y(b=>b+1);return}case"feedback":{let m=ty(e),f="";try{f=Ao(m)?zi(m,"utf8"):""}catch{f=""}if(!/^## /m.test(f)){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 $=await hu(f.trim());h({kind:"note",tone:$?"ok":"warn",text:$?"\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 ${m} and copy it manually.`}),$&&da(null);return}case"document":{if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{push:m,skipReview:f,what:$}=lc(w);if(!$&&ac(e)===0){h({kind:"note",tone:"info",text:uc});return}let b=`/document${$?` ${$}`:""}${m?" --push":""}`,R=await ye(cc($),{display:b,quietUser:!0});m&&!R.producedNothing&&await rd({skipReview:f});return}case"catch-up":{if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!Jn(u.trim()))return;let{push:m,skipReview:f}=Dc(w);for(let V of await Ac(e))h({kind:"note",tone:V.tone,text:V.text});h({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let $=await Lc({cwd:e,profileName:s});for(let V of Oc($))h({kind:"note",tone:V.startsWith("\u2713")?"ok":V.startsWith("\u2139")?"info":"warn",text:V});let b=Nc(e);for(let V of jc(b))h({kind:"note",tone:V.tone,text:V.text});let R=Lr(Ln(e));h({kind:"note",tone:"info",text:R?`Catching up on ${R}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"});let x=TS(e),_=await ye(Ic(b),{display:`/catch-up${m?" --push":""}`,quietUser:!0}),W=Ai(e,x);m&&!_.producedNothing?await rd({skipReview:f}):W.cta&&Ko(_,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(!Jn(u.trim()))return;let m=Uc(w);je("Checking Document360 for reviewer comments\u2026"),T(!0);let f=null;try{f=await Mc(e,s,{...m.scope,onProgress:(b,R)=>je(`Checking Document360 for reviewer comments\u2026 ${b}/${R}`)})}catch(b){h({kind:"note",tone:"error",text:`Couldn\u2019t read comments from Document360: ${b.message}`})}finally{T(!1),je(null)}if(!f)return;Y(b=>b+1);let $=On(f.threads,f.labels);if(f.threads.length===0){h({kind:"note",tone:"ok",text:_r(f,{showAnswered:m.showAnswered,width:_e()}).join(`
|
|
505
|
+
`)});return}if(m.answer&&(m.all||m.scope.path||m.scope.scope||$.length===1)){eo(Fc(f,{full:!0,showAnswered:m.showAnswered,width:_e()})),await ga($,{resolve:m.resolve});return}if($.length===1){eo(bi($[0],{width:_e()})),Uo({group:$[0],cursor:0,fromList:!1,resolve:m.resolve,rest:[]});return}eo(_r(f,{showAnswered:m.showAnswered,width:_e()})),Nt({cursor:0,rows:$i($),groups:$,resolve:m.resolve,report:f});return}case"update":{la.current=!0,h({kind:"note",tone:"info",text:"Updating the d360-writer toolchain\u2026 (don\u2019t close this window)"}),Pt(!0);let m=await xi().finally(()=>Pt(!1));m.ok?(h({kind:"note",tone:"ok",text:`\u2713 Updated ${m.packages.join(" + ")} \u2014 run /exit, then relaunch to apply.`}),Q("/exit"),Ou("")):h({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${vi}`});return}case"screenshot":{let m=hr(w),f=fr(e);if(f&&m.mode!=="list"&&h({kind:"note",tone:"info",text:f}),m.mode==="capture"){await E(m.rest);return}if(m.mode==="checklist"){await B();return}if(m.mode==="verify"){let R=Ie(e),x=m.rest.find(V=>!V.startsWith("-")),_=x?[x]:Er(R);if(x&&!R.some(V=>V.id===x)){h({kind:"note",tone:"error",text:`No screenshot placeholder called "${x}". /screenshot list shows them all.`});return}if(_.length===0){let V=R.filter(M=>M.state==="rejected").length,A=R.filter(M=>M.state==="verified").length;h({kind:"note",tone:"info",text:V>0?`Nothing left to verify. ${V} shot${V===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."});return}h({kind:"note",tone:"info",text:Ar(_.length)}),await ye(In(e,_),{display:x?`/screenshot verify ${x}`:"/screenshot verify",quietUser:!0});let W=Dr(e,_);W.length>0&&h({kind:"note",tone:"info",text:W.join(`
|
|
506
|
+
`)});return}if(m.mode==="list"){if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let R=ge(e)?.docsDir??Nu,x=ul(e,m.scope),_=Ie(e,x);if(m.picker){if(_.length===0){h({kind:"note",tone:"info",text:"No screenshot placeholders found in the docs."});return}let q=ah(_);if(q.length===0){h({kind:"note",tone:"info",text:Qs(_,{docsDir:R}).join(`
|
|
507
|
+
`)});let ie=Ct(e,{text:`\u2713 All ${_.length} screenshots are captured. /publish${x?` ${x}`:""} puts them in the articles; /screenshot capture${x?` ${x}`:""} re-captures.`,cmd:x?`/publish ${x}`:"/publish"},`\u2713 All ${_.length} screenshots are captured. `,x);Ae(ie.text,{kind:"cmd",cmd:ie.cmd,reason:""});return}kn({cursor:0,rows:q,title:"Screenshots \u2014 pick what to author or capture:"});return}h({kind:"note",tone:"info",text:Qs(_,{scope:x,detail:m.detail,docsDir:R}).join(`
|
|
508
|
+
`)}),f&&h({kind:"note",tone:"info",text:f});let W=_.filter(q=>q.state==="placeholder").length,V=_.filter(q=>q.state==="spec").length,A=_.filter(q=>q.state==="captured").length,M=_.filter(q=>q.state==="rejected").length,L=_.filter(q=>q.state==="spec"&&!q.mutates).length;W>0?Q(x?`/screenshot author ${x}`:"/screenshot author --all"):V>0&&(L>0||A===0)?Q(x?`/screenshot capture ${x}`:"/screenshot capture"):A>0?Q(x?`/screenshot verify ${x}`:"/screenshot verify"):M>0&&Q(x?`/screenshot capture ${x} --failed`:"/screenshot capture --failed");return}if(m.mode==="single"){await id(m.id);return}if(!ge(e)){h({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let $=m.mode==="scope"?m.scope:void 0,b=$S(e,{scope:$}).map(R=>R.id);if(b.length===0){h({kind:"note",tone:"info",text:$?`No screenshot placeholders under ${$}.`:"No screenshot placeholders found in the docs."});return}await sd(b,{setup:m.setup,scope:m.mode==="scope"?m.scope:void 0,runLine:m.mode==="scope"?[`/screenshot author ${m.scope}`,`/screenshot ${m.scope}`]:["/screenshot author --all","/screenshot --all"]});return}case"capture":{await E(w);return}case"reset":{let m=qc(e);if(m.length===0){h({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}Wo.current={repoName:Qr(e),targets:m,hadDevhints:Ao(ey(e))},h({kind:"note",tone:"warn",text:Vc(e,m).join(`
|
|
509
|
+
`)}),qe(Qr(e));return}default:h({kind:"note",tone:"error",text:`Unknown command: /${c} \u2014 type /help.`})}},[e,r,s,to,ba,h,Ve,ye,ft,ya,ad]),fs=J(u=>{let d=(u??k).trim();if(v(""),Jr(null),Un(0),d.startsWith("/")&&(Te.current=!1,yt.current=!1,St.current=null,kt(),zn(null),ue(w=>Tg(w,d))),!d||(Wn(!1),(Wo.current||Ce.current.length>0)&&h({kind:"user",text:d}),cd(d))||ld(d))return;ta.current.push(d);let c=Ng(d,_u.current);if(d.startsWith("/"))h({kind:"user",text:d}),ae(!0),no(c).finally(()=>ae(!1));else if(LS(c)){h({kind:"user",text:d});let w=OS(c);if(!w)ye(c,{display:d,quietUser:!0});else{try{_S(e,{title:w,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}ye(`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${w}". 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 "${w}" and the article path(s) you wrote.`,{display:d,quietUser:!0})}}else{let w=Dm(e,c);ye(w??c,{display:d})}},[k,cd,ld,no,ye]),ud=J(u=>{if(u.length>1){if(u.includes("\x1B"))return;let d=Eg(u);if(Ag(d)){let c=Dg(++ky.current,d);_u.current.set(c,d),P(c)}else P(d);return}P(u)},[P]),oo=Math.max(10,Ge-6),dd=vu(()=>Yi(p.text,oo),[p.text,oo]),$a=J(u=>g(d=>({...d,pos:Math.max(0,Math.min(d.text.length,d.pos+u))})),[]),ms=J(u=>g(d=>({...d,pos:Ig(Yi(d.text,oo),d.pos,u)})),[oo]),nr=J(u=>g(d=>({...d,pos:Lg(Yi(d.text,oo),d.pos,u)})),[oo]),Py=["\x1B[H","\x1B[1~","\x1BOH"],Ty=["\x1B[F","\x1B[4~","\x1BOF"],pd=J((u,d)=>d.leftArrow?($a(-1),!0):d.rightArrow?($a(1),!0):u&&Py.includes(u)?(nr("start"),!0):u&&Ty.includes(u)?(nr("end"),!0):d.ctrl&&u==="a"?(nr("start"),!0):d.ctrl&&u==="e"?(nr("end"),!0):!1,[$a,nr]);return qR((u,d)=>{if(d.ctrl&&u==="c"){dt.current?.close(),r();return}if(Qo.current.awaySince!==null)try{let c=wg(Qo.current,Date.now(),Ln(e));if(Qo.current=c.memory,Zu(null),c.kind==="delta"){h({kind:"note",tone:"info",text:bg(c.delta,c.awayMs)});let w=ht(!1);w.kind==="recommend"&&jt(w.rec,{silent:!0})}else if(c.kind==="briefing"){h({kind:"note",tone:"info",text:`\u{1F4E5} ${zr(c.delta)} arrived while you were away (${ku(c.awayMs)}).`});let w=ht(!1);w.kind==="recommend"&&jt(w.rec)}}catch{}if(pa.current=Date.now(),!D){if(C){if(d.escape){if(Ee.current){if(!Ee.current.signal.aborted){let c=(Ho?.verb??"work").toLowerCase(),w=Ho?.unit??"article";h({kind:"note",tone:"warn",text:`\u238B Stopping the ${c} run (finishing in-flight ${w}s)\u2026`}),Ee.current.abort()}return}Bo.current||(Bo.current=!0,h({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),dt.current?.interrupt());return}if(d.return){let c=k.trim();if(!c)return;vn.current.push(c),oa([...vn.current]),v("");return}if(pd(u,d))return;if(d.upArrow){ms(-1);return}if(d.downArrow){ms(1);return}if(d.backspace||d.delete){S();return}u&&!d.ctrl&&!d.meta&&ud(u);return}if(gn){if(d.upArrow){yn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){yn(c=>c&&{...c,cursor:Math.min(Rt.length-1,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=Rt.length){yn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let c=Rt[gn.cursor];yn(null);let{lines:w,changed:E,effective:B}=Pr(e,c.value??"default");for(let m of w)h({kind:"note",tone:m.startsWith("\u26A0")?"warn":m.startsWith("\u2713")?"ok":"info",text:m});E&&(Vu(m=>m+1),dt.current?.setModel(B));return}if(u==="s"){let c=Rt[gn.cursor];yn(null),dt.current?.setModel(c.value??void 0),h({kind:"note",tone:"ok",text:`\u2713 Using ${c.label} for this session only (your saved default is unchanged).`});return}if(d.escape){yn(null);return}return}if(qt){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)<=qt.rows.length){qn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return||u==="s"){let c=qt.rows[qt.cursor];qn(null),ka(c.name,d.return===!0);return}if(d.escape){qn(null);return}return}if(Vo){if(d.escape){Cn(null);return}if(d.leftArrow||d.tab&&d.shift){Cn(c=>c&&{tab:(c.tab-1+Je.length)%Je.length,scroll:0});return}if(d.rightArrow||d.tab){Cn(c=>c&&{tab:(c.tab+1)%Je.length,scroll:0});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=Je.length){Cn({tab:Number(u)-1,scroll:0});return}if(d.upArrow){Cn(c=>c&&{...c,scroll:Math.max(0,c.scroll-1)});return}if(d.downArrow){Cn(c=>{if(!c)return c;let w=(Je[c.tab]??Je[0]).rows.length;return{...c,scroll:Math.min(Math.max(0,w-1),c.scroll+1)}});return}return}if(Gt){if(d.upArrow){Gn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){Gn(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){Gn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let c=Gt.rows[Gt.cursor].name;if(Gn(null),!Ia(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 E=!1;try{let B=Fn(c);E=!!B&&!(pn(B)&&!B.refreshToken)}catch{E=!1}h({kind:"note",tone:"info",text:E?`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.`}),Q("/login"),Y(B=>B+1);return}if(d.escape){Gn(null);return}return}if(ze){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)<=ze.rows.length){Vn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let c=ze.rows[ze.cursor],{profile:w,projectId:E}=ze;Vn(null),ds(w,E,c);return}if(d.escape){Vn(null);return}return}if(pt){if(d.upArrow){wn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){wn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=pt.rows.length){wn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let c=pt.rows[pt.cursor],{profile:w}=pt;wn(null),hs(w,c);return}if(d.escape){wn(null);return}return}if(Xe){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===" "){Xn(c=>c&&{...c,rows:c.rows.map((w,E)=>E===c.cursor?{...w,checked:!w.checked}:w)});return}if(d.return){let c=Xe.rows.filter(w=>w.checked).map(w=>w.path);if(Xn(null),c.length===0){h({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}Tl(e,c),h({kind:"note",tone:"ok",text:`\u2713 Scoped to ${c.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let w of c)h({kind:"note",tone:"info",text:` ${w}`});h({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(d.escape){Xn(null);return}return}if(wt){if(d.upArrow){bn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){bn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=wt.rows.length){bn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let c=wt.rows[wt.cursor],w=wt.run;bn(null),w(c.token);return}if(d.escape){bn(null);return}return}if(At){if(d.upArrow){Yn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){Yn(c=>c&&{...c,cursor:Math.min(c.rows.length-1,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=At.rows.length){Yn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let c=At.rows[At.cursor],w=At.conflicts;Yn(null),c.conflict?ba(c.paths[0]):c.kind==="article"?ya(c.paths[0]):ft(c.paths,c.kind==="all"?w:0);return}if(d.escape){Yn(null);return}return}if(Vt){if(d.upArrow){Kn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){Kn(c=>c&&{...c,cursor:Math.min(c.rows.length,c.cursor+1)});return}if(u&&/^[1-9]$/.test(u)&&Number(u)<=Vt.rows.length+1){Kn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let{cursor:c,rows:w,opts:E}=Vt;Kn(null);let B=c===0?w:[w[c-1]];Sy(B,E);return}if(d.escape){Kn(null),h({kind:"note",tone:"info",text:"Left as drafts \u2014 nothing changed. /publish when they have been signed off."});return}return}if(Dt){let{rows:c}=Dt;if(d.upArrow){Nt(w=>w&&{...w,cursor:Math.max(0,w.cursor-1)});return}if(d.downArrow){Nt(w=>w&&{...w,cursor:Math.min(c.length-1,w.cursor+1)});return}if(u&&/^[0-9]$/.test(u)){let w=cg(Wu.current,Number(u),c.length-1);Wu.current=w.memory,w.index!==null&&Nt(E=>E&&{...E,cursor:w.index+1});return}if(u==="a"||u==="A"){Nt(w=>w&&{...w,cursor:0});return}if(d.return){let w=c[Dt.cursor],{groups:E,resolve:B,report:m}=Dt;if(Nt(null),w.kind==="all"){ga(E,{resolve:B,report:m});return}eo(bi(w.group,{width:_e()})),Uo({group:w.group,cursor:0,fromList:!0,resolve:B,rest:E.filter(f=>f.articleId!==w.group.articleId),report:m});return}if(d.escape){Nt(null),Q("/comments");return}return}if(Le){let c=()=>{let{rest:w,group:E,fromList:B,resolve:m,report:f}=Le;if(Uo(null),!B||!f){Q("/comments");return}let $=[E,...w].sort((b,R)=>b.category.localeCompare(R.category)||b.title.localeCompare(R.title));Nt({cursor:0,rows:$i($),groups:$,resolve:m,report:f})};if(d.upArrow||d.downArrow){Uo(w=>w&&{...w,cursor:w.cursor===0?1:0});return}if(u==="y"||u==="Y"||d.return&&Le.cursor===0){let{group:w,resolve:E,rest:B,report:m}=Le;Uo(null),ga([w],{resolve:E,rest:B,...m?{report:m}:{}});return}if(u==="b"||u==="B"||d.escape||d.return){c();return}return}if(Yt){if(d.upArrow){kn(c=>c&&{...c,cursor:Math.max(0,c.cursor-1)});return}if(d.downArrow){kn(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){kn(c=>c&&{...c,cursor:Number(u)-1});return}if(d.return){let c=Yt.rows[Yt.cursor];kn(null),c.action==="capture"?er(c.ids,{runLine:c.kind==="all"?["/screenshot capture --all","/capture --all"]:void 0}):c.kind==="shot"?id(c.ids[0]):sd(c.ids,{setup:!0,runLine:c.kind==="all"?["/screenshot author --all","/screenshot --all"]:void 0});return}if(d.escape){kn(null);return}return}if(ot){if(d.escape){$n(null);return}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(Math.max(0,as.length-1),c.cursor+1)});return}if(d.return){let c=as[ot.cursor];if(c){$n(null);try{h({kind:"preview",name:Qr(c),text:cy(zi(xu(e,c),"utf8"))})}catch(w){h({kind:"note",tone:"error",text:`Could not read ${c}: ${w.message}`})}}return}if(d.backspace||d.delete){$n(c=>c&&{...c,query:c.query.slice(0,-1),cursor:0});return}if(u&&!d.ctrl&&!d.meta&&u.length===1){$n(c=>c&&{...c,query:c.query+u,cursor:0});return}return}if(rt){if(d.escape){xn(null);return}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(Math.max(0,ls.length-1),c.cursor+1)});return}if(d.return){let c=ls[rt.cursor];if(c){xn(null),Ve(c.uuid),Et.current={uuid:c.uuid,firstPrompt:c.firstPrompt,titleFired:!0},mn(c.name),Cu(c.uuid),Hn.current=[],He.current={printed:[],armed:[],printedAt:Qn.current};let w=gu(e,c.uuid);for(let E of w)h(E);h({kind:"note",tone:"ok",text:w.length?`Resumed "${c.name}" \u2014 restored ${w.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){xn(c=>c&&{...c,query:c.query.slice(0,-1),cursor:0});return}if(u&&!d.ctrl&&!d.meta&&u.length===1){xn(c=>c&&{...c,query:c.query+u,cursor:0});return}return}if(d.tab&&!k&&le){v(le),kt();return}if(!k&&ne.length>0&&!nt&&u&&/^[1-9]$/.test(u)){let c=ne[Number(u)-1];if(c){v(Mn(c));return}}if(!k&&ne.length===0&&!nt&&He.current.armed.length>0&&u&&/^[1-9]$/.test(u)){let c=He.current.armed[Number(u)-1];if(c){v(c);return}}if(!k&&(rs||zo)&&u==="c"&&!d.ctrl&&!d.meta&&!d.return&&!d.tab){let c=rs!=null;hu(rs??zo).then(E=>{h({kind:"note",tone:E?"ok":"warn",text:E?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."}),E&&c&&da(null),E&&!c&&Ku(!0)});return}if(!pd(u,d)){if(td){if(d.upArrow){Un(c=>Math.max(0,c-1));return}if(d.downArrow){Un(c=>Math.min(It.length-1,c+1));return}if(d.tab){v("/"+(It[ea]?.name??"")+" "),Un(0);return}if(d.return){let c=It[ea];if(c){let w=k.trim().slice(1).split(/\s+/).slice(1).join(" ");if(hp(c.usage)&&!w){v("/"+c.name+" "),Un(0);return}fs("/"+c.name+(w?" "+w:""));return}}}else{if(d.upArrow){if(k!==""&&Bn===null){ms(-1);return}let c=ta.current;if(!c.length)return;let w=Bn===null?c.length-1:Math.max(0,Bn-1);Jr(w),v(c[w]??"");return}if(d.downArrow){if(k!==""&&Bn===null){ms(1);return}let c=ta.current;if(Bn===null)return;let w=Bn+1;w>=c.length?(Jr(null),v("")):(Jr(w),v(c[w]??""));return}}if(d.return){fs();return}if(d.backspace||d.delete){S();return}if(d.escape){v(""),Un(0),kt(),ue([]),zn(null),Te.current=!0;return}u&&!d.ctrl&&!d.meta&&ud(u)}}}),tt(()=>{if(C||D)return;let u=vn.current.shift();u!==void 0&&(oa([...vn.current]),fs(u))},[C,D,fs]),oe(xe,{flexDirection:"column",width:Ge,children:[ma!==null&&oe(xe,{marginTop:1,flexDirection:"column",children:[ma.truncated&&F(U,{dimColor:!0,children:"\u2026"}),F(U,{children:ma.text})]}),C&&Ho?F(zS,{p:Ho}):null,Hu?F(YS,{text:Hu}):C&&!Ho?F(VS,{startTime:Tt.current,chars:wy}):null,F(xe,{borderStyle:"round",borderColor:ed.prod?"yellow":Z,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:k?dd.map((u,d)=>{let c=p.text.slice(u.start,u.end),w=d===Ki(dd,p.pos),E=Math.min(p.pos,u.end)-u.start;return oe(U,{children:[F(U,{color:Z,children:d===0?"> ":" "}),w?oe(Lo,{children:[c.slice(0,E),F(Io,{ch:c[E]??" "}),c.slice(E+1)]}):c||" "]},`${d}-${u.start}`)}):oe(U,{children:[F(U,{color:Z,children:"> "}),Yo?F(Io,{ch:" "}):le&&!C&&ce?oe(Lo,{children:[F(Io,{ch:ce[0],dim:!0}),F(U,{color:"gray",children:ce.slice(1)})]}):le&&!C?oe(Lo,{children:[F(Io,{ch:le[0],dim:!0}),F(U,{color:"gray",children:le.slice(1)}),F(U,{dimColor:!0,children:" (tab)"})]}):(ha.isSetup||!hn)&&!C?oe(Lo,{children:[F(Io,{ch:ha.text[0],dim:!0}),F(U,{color:"gray",children:ha.text.slice(1)})]}):F(Io,{ch:" "})]})}),Bu.length>0&&F(xe,{flexDirection:"column",paddingX:1,children:Bu.map((u,d)=>F(U,{color:"gray",children:`\u29D7 queued: ${u}`},`${d}-${u.slice(0,24)}`))}),Vo?F(vg,{tab:Vo.tab,scroll:Vo.scroll,rows:Cy,width:Ge,version:o,engineVersion:uy}):gn?oe(xe,{flexDirection:"column",paddingX:1,children:[F(U,{color:Z,bold:!0,children:"Select model"}),F(U,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),Rt.map((u,d)=>oe(U,{color:d===gn.cursor?Z:void 0,children:[d===gn.cursor?"\u276F ":" ",`${d+1}. ${u.label}${d===gn.current?" \u2714":""}`.padEnd(16),F(U,{color:"gray",children:u.desc})]},u.label)),F(U,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):qt?oe(xe,{flexDirection:"column",paddingX:1,children:[F(U,{color:Z,bold:!0,children:"Switch connection profile"}),F(dn,{rows:qt.rows,cursor:qt.cursor,cap:Lt,render:(u,d,c)=>oe(U,{color:c?Z:void 0,children:[c?"\u276F ":" ",`${d+1}. ${u.name}${d===qt.current?" \u2714":""}`.padEnd(20),F(U,{color:"gray",children:`${u.env} \xB7 ${u.who??"not signed in"}`}),u.prod?F(U,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},u.name)}),F(U,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Gt?oe(xe,{flexDirection:"column",paddingX:1,children:[F(U,{color:Z,bold:!0,children:"Pick your Document360 environment"}),F(dn,{rows:Gt.rows,cursor:Gt.cursor,cap:Lt,render:(u,d,c)=>oe(U,{color:c?Z:void 0,children:[c?"\u276F ":" ",`${d+1}. ${u.name}`.padEnd(16),F(U,{color:"gray",children:u.apiUrl}),u.note?F(U,{color:"yellow",children:` \u26A0 ${u.note}`}):null]},u.name)}),F(U,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):ze?oe(xe,{flexDirection:"column",paddingX:1,children:[F(U,{color:Z,bold:!0,children:"Switch workspace"}),F(U,{dimColor:!0,children:`environment ${ze.environment} \xB7 project ${ze.projectName??`${ze.projectId.slice(0,8)}\u2026`}`}),F(dn,{rows:ze.rows,cursor:ze.cursor,cap:Lt,render:(u,d,c)=>oe(U,{color:c?Z:void 0,children:[c?"\u276F ":" ",`${d+1}. ${u.name}${d===ze.current?" \u2714":""}`.padEnd(30),F(U,{color:"gray",children:u.type??""})]},u.id)}),F(U,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):pt?oe(xe,{flexDirection:"column",paddingX:1,children:[F(U,{color:Z,bold:!0,children:"Choose project"}),F(U,{dimColor:!0,children:`environment ${pt.environment}`}),F(dn,{rows:pt.rows,cursor:pt.cursor,cap:Lt,render:(u,d,c)=>oe(U,{color:c?Z:void 0,children:[c?"\u276F ":" ",`${d+1}. ${u.name}${d===pt.current?" \u2714":""}`.padEnd(30),F(U,{color:"gray",children:u.sub??""})]},u.id)}),F(U,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):Xe?(()=>{let d=Math.min(Math.max(0,Xe.cursor-Math.floor(7)),Math.max(0,Xe.rows.length-14)),c=Xe.rows.slice(d,d+14),w=Xe.rows.filter(E=>E.checked).length;return oe(xe,{flexDirection:"column",paddingX:1,children:[F(U,{color:Z,bold:!0,children:`Which folders back the user docs? (${w} selected of ${Xe.rows.length})`}),d>0?F(U,{dimColor:!0,children:` \u2191 ${d} more`}):null,c.map((E,B)=>{let m=d+B;return oe(U,{color:m===Xe.cursor?Z:void 0,children:[m===Xe.cursor?"\u276F ":" ",E.checked?"\u25C9 ":"\u25CB ",E.path.padEnd(Math.min(48,Ge-34)),F(U,{color:"gray",children:ri(E)})]},E.path)}),d+14<Xe.rows.length?F(U,{dimColor:!0,children:` \u2193 ${Xe.rows.length-d-14} more`}):null,F(U,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():wt?oe(xe,{flexDirection:"column",paddingX:1,children:[F(U,{color:Z,bold:!0,children:wt.title??"Which category? (pick one to scope to)"}),F(dn,{rows:wt.rows,cursor:wt.cursor,cap:Lt,render:(u,d,c)=>oe(U,{color:c?Z:void 0,children:[c?"\u276F ":" ",`${`${d+1}.`.padEnd(3)} ${u.label} (${u.count})`.padEnd(Math.min(44,Math.max(20,Ge-24))),F(U,{color:"gray",children:` ${u.token}`})]},u.token)}),F(U,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):At?oe(xe,{flexDirection:"column",paddingX:1,children:[F(U,{color:Z,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),F(dn,{rows:At.rows,cursor:At.cursor,cap:Lt,render:(u,d,c)=>oe(U,{color:c?Z:void 0,bold:u.kind==="category"&&!c,children:[c?"\u276F ":" ",`${u.indent?" ":" "}${`${d+1}.`.padEnd(3)} ${u.label}`.padEnd(Math.min(56,Ge-24)),u.note?F(U,{color:"gray",children:u.note}):null]},`${u.kind}:${u.paths.join(",")}`)}),F(U,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter push (draft) \xB7 esc cancel"})]}):Vt?oe(xe,{flexDirection:"column",paddingX:1,children:[F(U,{color:Z,bold:!0,children:"Publish live to your readers \u2014 this is what they will see:"}),F(dn,{rows:[{path:"",articleId:"",label:`Publish all ${Vt.rows.length} live`,version:void 0},...Vt.rows],cursor:Vt.cursor,cap:Lt,render:(u,d,c)=>oe(U,{color:c?Z:void 0,bold:d===0&&!c,children:[c?"\u276F ":" ",` ${`${d+1}.`.padEnd(3)} ${u.label}`.padEnd(Math.min(56,Ge-24)),d>0?F(U,{color:"gray",children:u.version?`draft v${u.version} \u2192 live`:"draft \u2192 live"}):null]},`${d}:${u.path||"all"}`)}),F(U,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish LIVE \xB7 esc leave as drafts"})]}):Dt?oe(xe,{flexDirection:"column",paddingX:1,children:[F(U,{color:Z,bold:!0,children:"Which comments do you want to look at?"}),F(dn,{rows:Dt.rows,cursor:Dt.cursor,cap:Lt,render:(u,d,c)=>oe(U,{color:c?Z: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,Ge-24))),u.kind==="article"?F(U,{color:"gray",children:u.note}):null]},u.kind==="all"?"all":u.group.articleId)}),F(U,{dimColor:!0,children:"\u2191\u2193 move \xB7 type a number \xB7 enter \xB7 esc close"}),Dt.resolve?F(U,{dimColor:!0,children:"--resolve is on: threads you answer will be closed as well as replied to"}):null]}):Le?oe(xe,{flexDirection:"column",paddingX:1,children:[F(U,{color:Z,bold:!0,children:`${Le.group.title} \u2014 ${Le.group.threads.length} comment${Le.group.threads.length===1?"":"s"}`}),oe(U,{color:Le.cursor===0?Z:void 0,children:[Le.cursor===0?"\u276F ":" ",Le.resolve?"Yes \u2014 fix them, push the draft, reply and resolve":"Yes \u2014 fix them, push the draft to Document360, then reply"]}),oe(U,{color:Le.cursor===1?Z:void 0,children:[Le.cursor===1?"\u276F ":" ",Le.fromList?"No \u2014 back to the list":"No \u2014 leave them for now"]}),F(U,{dimColor:!0,children:"\u2191\u2193 move \xB7 enter select \xB7 y answer \xB7 esc back"})]}):Yt?oe(xe,{flexDirection:"column",paddingX:1,children:[F(U,{color:Z,bold:!0,children:Yt.title}),(()=>{let{rows:u,cursor:d}=Yt,c=Ui(u.length,d,Lt),w=c.start,E=u.slice(c.start,c.end),B=`${u.length}.`.length+1,m=ih(u,Math.max(20,Ge-4-B));return oe(Lo,{children:[w>0?F(U,{color:"gray",children:` \u2026 ${w} more above`}):null,E.map((f,$)=>{let b=w+$,R=b===d,x=m[b];return oe(U,{color:R?Z:void 0,bold:(f.kind==="all"||f.kind==="category")&&!R,children:[R?"\u276F ":" ",`${b+1}.`.padEnd(B),x.head,x.note?F(U,{color:"gray",children:x.note}):null]},`${f.action}:${f.kind}:${f.ids.join(",")}`)}),c.below>0?F(U,{color:"gray",children:` \u2026 ${c.below} more below`}):null]})})(),F(U,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter run \xB7 esc cancel"})]}):ot?oe(xe,{flexDirection:"column",paddingX:1,children:[F(U,{color:Z,bold:!0,children:`Preview article${ot.query?` \u2014 filter: ${ot.query}`:" (type to filter)"}`}),as.length===0?F(U,{color:"gray",children:"no articles match"}):as.map((u,d)=>oe(U,{color:d===ot.cursor?Z:void 0,children:[d===ot.cursor?"\u276F ":" ",u]},u)),F(U,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):rt?oe(xe,{flexDirection:"column",paddingX:1,children:[F(U,{color:Z,bold:!0,children:`Resume session${rt.query?` \u2014 filter: ${rt.query}`:" (type to filter)"}`}),ls.length===0?F(U,{color:"gray",children:"no sessions match"}):ls.map((u,d)=>oe(U,{color:d===rt.cursor?Z:void 0,children:[d===rt.cursor?"\u276F ":" ",u.name.slice(0,28).padEnd(30),F(U,{color:d===rt.cursor?Z:"gray",children:u.firstPrompt.slice(0,Math.max(10,Ge-40))})]},u.uuid)),F(U,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):td?oe(xe,{flexDirection:"column",children:[Rn>0?F(U,{dimColor:!0,children:` \u22EF ${Rn} more above`}):null,fa.map((u,d)=>{let c=Rn+d,w=u.name==="model"&&ra?`${u.desc} (currently ${ra})`:u.desc,E=Math.max(20,Ge-4),B=u.usage.length>E?`${u.usage.slice(0,E-1)}\u2026`:u.usage,m=E-Math.max(B.length,22)-1,f=m<=1?"":w.length>m?`${w.slice(0,m-1)}\u2026`:w;return oe(U,{color:c===is?Z:void 0,children:[c===is?"\u276F ":" ",B.padEnd(22)," ",F(U,{color:c===is?Z:"gray",children:f})]},u.name)}),Rn+fa.length<It.length?F(U,{dimColor:!0,children:` \u22EF ${It.length-Rn-fa.length} more below`}):null,F(U,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!C&&!k&&ne.length>0?oe(xe,{flexDirection:"column",paddingX:1,children:[Uu?F(U,{color:Z,children:Uu}):null,ne.map((u,d)=>{let c=Mn(u),w=c.slice(0,Math.max(20,Ge-5)),E=Ge-w.length-7,B=E>=12?(Pg(u)??dp(c)).slice(0,E):"";return oe(U,{children:[F(U,{color:Z,children:d+1})," ",w,B?F(U,{dimColor:!0,children:` \u2014 ${B}`}):null]},c)}),F(U,{dimColor:!0,children:`press 1-${ne.length} to fill \xB7 esc cancel`})]}):F(xe,{paddingX:1,children:oe(U,{color:"gray",children:[ed.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${ra??"model n/a"}${t.kind==="api"?Gu>0?` \xB7 ${Ze(Gu)}`:"":qu>0?` \xB7 ${rn(qu)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}ee();import{jsx as ZS}from"react/jsx-runtime";async function py(e=process.cwd(),t="auto",n,o="0.0.0"){let r=JS(t);r.kind==="none"&&(console.error(""),console.error(N("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${K("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${K("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=QS(ZS(dy,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
|
|
510
|
+
`),process.exit(0)}ee();import{writeCrashLog as hy,isBenignTransportError as eP}from"document360-engine";var fy=!1;function ju(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function my(e){if(fy)return;fy=!0;let t=(n,o)=>{if(eP(o)){hy({kind:n,level:"transport",message:ju(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=hy({kind:n,level:"fatal",message:ju(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
|
|
511
|
+
`+N(`\u2717 d360-writer crashed: ${ju(o)}`)+`
|
|
512
|
+
`),r&&process.stderr.write(y(` Crash details: ${r}`)+`
|
|
513
|
+
`+y(" Run: d360-writer logs")+`
|
|
514
|
+
`),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var rP=nP(import.meta.url),Zi=rP("../package.json");my("d360-writer");var gt=new tP;function Iu(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}gt.command("login").description("Sign in to Document360 (browser OAuth; project chosen during login)").option("--profile <name>","Connection profile (defaults to the repo's defaultProfile)").option("--env <name>",!1).option("--manual","No local listener \u2014 paste the redirect URL instead (SSH/locked-down setups)").action(async e=>{Iu(e),await $s({profile:e.profile,manual:e.manual})});gt.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Iu(e),await Td({profile:e.profile})});gt.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Iu(e),await Pd({profile:e.profile})});var Lu=gt.command("profile").description("Manage connection profiles for the current repo");Lu.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>vs(process.cwd()));Lu.command("use <name>").description("Set the default profile for this repo").action(e=>xs(process.cwd(),e));Lu.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>Cs(process.cwd(),e));var gy=gt.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");gy.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>io(process.cwd(),e.profile));gy.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await kd(process.cwd(),e,t.profile)});var yy=gt.command("project").description("Choose the Document360 project for this repo (active profile's identity)");yy.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>ws(process.cwd(),e.profile));yy.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await $d(process.cwd(),e,t.profile)});gt.command("init").description("Scaffold .d360-writer/config.json for this repo (interactive)").action(async()=>{let{initCommand:e}=await Promise.resolve().then(()=>(js(),sp));await e()});gt.command("logs").description("Show the API + crash log files (send these to support when reporting a problem)").action(()=>Nd());gt.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(()=>(mi(),bf)),n=await t(process.cwd(),Zi.version);for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});gt.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(Zi.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(oP.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 jd(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 ng(e.cwd,e.auth,e.profile,Zi.version):await py(e.cwd,e.auth,e.profile,Zi.version)});gt.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
|