document360-writer 0.5.222 → 0.5.223
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 +132 -132
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var Bm=Object.defineProperty;var Ro=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var nu=(e,t)=>{for(var n in t)Bm(e,n,{get:t[n],enumerable:!0})};import jt from"picocolors";var te,Hm,qm,Gm,ou,So,b,j,W,B,q,fe,je,Q=Ro(()=>{"use strict";te="#7f56d9",[Hm,qm,Gm]=[127,86,217],ou=e=>jt.isColorSupported?`\x1B[38;2;${Hm};${qm};${Gm}m${e}\x1B[39m`:e,So=e=>jt.bold(ou(e)),b=e=>jt.dim(e),j=e=>jt.red(e),W=e=>jt.yellow(e),B=e=>jt.green(e),q=ou,fe=e=>jt.gray(e),je=e=>jt.bold(e)});import{existsSync as Ln,writeFileSync as _t,readFileSync as Ig,readdirSync as Og}from"node:fs";import{join as Ru}from"node:path";import{devHintsGuidePath as zr,hintsDir as Su,hooksDir as Pu,architectureDir as Nu,messagesDir as Fi,creatorNotesPath as Tu,devhintsStatePath as ju,directivesPath as Eu,DIRECTIVES_HEADER as Lg,roadmapPath as Au,ROADMAP_HEADER as _g,ensureDir as Eo,writeMessage as Mg,listOpenForDev as Ug}from"document360-engine";function Iu(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
|
|
3
3
|
|
|
4
4
|
<!-- devhints script v${xe} \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 Wg(){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 Mn(e){
|
|
253
|
-
`)}Ln(Tu(e))||_t(Tu(e),
|
|
254
|
-
`)}function Wi(e){try{let t=
|
|
255
|
-
`)}function $t(e){try{return
|
|
256
|
-
`)}),n.notifiedBuilder=!0))}catch{}return n}function Jr(e){if(!Ln(zr(e)))return[];let t=
|
|
257
|
-
`)}function Qr(){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):",_n,Bi(),_n]}function Un(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${xe}.`," 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):",_n,dn(),_n,"","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 _n,xe,
|
|
252
|
+
`}function Mn(e){Eo(Su(e)),Eo(Nu(e)),Eo(Fi(e));for(let n of[Su(e),Fi(e)]){let o=Ru(n,".gitkeep");Ln(o)||_t(o,`# Keeps this document360-writer inbox tracked in git even when empty.
|
|
253
|
+
`)}Ln(Tu(e))||_t(Tu(e),Wg()),Ln(Eu(e))||_t(Eu(e),Lg),Ln(Au(e))||_t(Au(e),_g),_t(zr(e),Iu()),Eo(Pu(e)),_t(Ru(Pu(e),"open-questions.mjs"),Fg);let t=it(e);return Lu(e,new Date().toISOString()),t}async function Ou(e,t){for(let n of Un(Mn(t.cwd)))console.log(n);return{kind:"continue"}}function dn(){return[`This is document360-writer's dev hand-off setup (v${xe}).`,'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": ${xe},`,' "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 Wi(e){try{let t=Ig(ju(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function Lu(e,t){let o={...Wi(e)??{},emittedVersion:xe,emittedAt:t};_t(ju(e),`${JSON.stringify(o,null,2)}
|
|
255
|
+
`)}function $t(e){try{return Og(Nu(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function it(e){let n=Wi(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<xe?"stale":"current",completedVersion:n}}function Xr(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:xe};try{if(!Ln(zr(e)))return n;let o=Wi(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;xe>r&&(Eo(Fi(e)),_t(zr(e),Iu()),Lu(e,t),n.guideRefreshed=!0),xe>s&&(Ug(e).some(a=>a.kind==="request"&&a.subject.startsWith(Du))||(Mg(e,{id:`onb${xe}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${Du}${xe})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${xe}${s?` (you last completed v${s})`:""}.`,"Re-run the hand-off so the docs agent and this repo stay in step \u2014 run this prompt here:","",dn()].join(`
|
|
256
|
+
`)}),n.notifiedBuilder=!0))}catch{}return n}function Jr(e){if(!Ln(zr(e)))return[];let t=it(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${xe}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,_n,dn(),_n,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function Bi(){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 Qr(){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):",_n,Bi(),_n]}function Un(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${xe}.`," 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):",_n,dn(),_n,"","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 _n,xe,Fg,Du,Mt=Ro(()=>{"use strict";_n="-".repeat(64),xe=12,Fg=`#!/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,30 +292,30 @@ try {
|
|
|
292
292
|
} catch {
|
|
293
293
|
/* a session-start nudge must never break the session */
|
|
294
294
|
}
|
|
295
|
-
`;Du="Re-run dev\u2194docs onboarding (protocol v"});var Vu={};nu(Vu,{initCommand:()=>qi,scaffoldInit:()=>Hi});import{input as
|
|
296
|
-
`),"utf8")}async function qi(){let e=process.cwd(),t=Uu(e);if(Fn(t)&&!await Wg({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(b("init cancelled.")),{kind:"continue"};let n=qu(e)??_u(e),o=await Eo({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await Eo({message:"Capture directory (where document360-capture .spec.ts files live):",default:Wu}),s=await Eo({message:"Screenshot output directory:",default:Bu}),i=await Eo({message:"Default connection profile name:",default:"berlin"}),a=await Eo({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),u={projectId:o,docsDir:Fu,captureDir:r,outputDir:s,profiles:{[i]:{connection:{environment:a},production:!1}},defaultProfile:i,authoritativeSourceFiles:Gu(e)},h=Gg(e);h?.terminologyGlossary&&(u.terminologyGlossary=h.terminologyGlossary),Mu(u,e),Hu(e);let g=Mn(e);console.log(""),console.log(B(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${q(`d360-writer login --profile ${i}`)} ${b("(sign in; project & workspace auto-selected)")}`),console.log("");for(let k of Un(g))console.log(k);return console.log(""),console.log(`${b("Then ask:")} ${q('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function qu(e){let t=Zr(e,"package.json");if(!Fn(t))return null;try{return JSON.parse(Bg(t,"utf8")).name??null}catch{return null}}function Gu(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Fn(Zr(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Zr(e,n);Fn(o)&&!Yg(o)&&t.push(n)}return t}function Yg(e){try{return Hg(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var es=Co(()=>{"use strict";Q();Mt()});import{createRequire as ww}from"node:module";import{existsSync as yw,readFileSync as kw}from"node:fs";import{dirname as gd,join as wd}from"node:path";function xt(){let e;try{e=bw.resolve("document360-capture/helpers")}catch{return null}let t=gd(e);for(let n=0;n<5&&!yw(wd(t,"package.json"));n++)t=gd(t);try{let n=JSON.parse(kw(wd(t,"package.json"),"utf8"));return n.name==="document360-capture"&&n.version?n.version:null}catch{return null}}var bw,jo=Co(()=>{"use strict";bw=ww(import.meta.url)});var qp={};nu(qp,{doctorCommand:()=>Vo,renderDoctorChecks:()=>Hp,runDoctorChecks:()=>Bp});import{existsSync as Nk}from"node:fs";import{d360GetAll as jk,getAccessToken as Ik,isExpired as ul,loadProfileMap as Ok,loadTokens as Lk,packageSkillsDir as Fp,ENGINE_VERSION as _k,projectConfigPath as Mk,readProjectConfig as Uk,DEFAULT_DOCS_DIR as Fk,fetchManifestSummary as Wk,resolveActiveProfile as Bk,classifyClaudeAuth as Hk,CLAUDE_CODE_SETUP_HINT as Wp,resolveModelSetting as qk,probeModel as Gk,detectAppType as Vk,playbookSkillName as Yk,D360AuthError as Kk,applyStructureOrder as zk}from"document360-engine";async function Bp(e,t){let n=[],o=xt();n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${_k}${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=Hk();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. ${Wp}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:Wp});let i=qk(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 S=await Gk(e,i.model??void 0);S.ok?n.push({level:"ok",label:`Model reachable \u2014 replied in ${(S.latencyMs/1e3).toFixed(1)}s`}):S.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 ${S.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=Uk(e);if(!a)return n.push({level:"fail",label:`No ${Mk(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${a.projectId}`});let u=(a.docsDir??Fk).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 ${u}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let h=a.authoritativeSourceFiles??[];n.push(h.length>0?{level:"ok",label:`Sources: docs grounded in ${h.length} path(s) (${h.slice(0,3).join(", ")}${h.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??Vk(e);if(g){let S=a.appType?"from config":"auto-detected",R=g==="web"||g==="cli";n.push({level:"ok",label:`Genre: ${g} (${S})${R?` \u2192 ${Yk(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=Bk(e),n.push({level:"ok",label:`Profile: ${k.name} (${k.connection.name})${k.production?" \u26A0 PRODUCTION":""}`})}catch(S){return n.push({level:"fail",label:`Profile config: ${S.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let x=Lk(k.name);x?ul(x)&&!x.refreshToken?n.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):ul(x)?n.push({level:"ok",label:"Document360: logged in (access token expired \u2014 refreshes automatically on the next call)"}):n.push({level:"ok",label:`Document360: logged in (until ${new Date(x.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 T=Ok(e,k.name);T?T.projectId&&k.project.projectId&&T.projectId!==k.project.projectId?n.push({level:"fail",label:`Category map projectId (${T.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(T.articles).length} articles, ${Object.keys(T.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${k.name}" (created on first /publish)`}),n.push(Nk(Fp())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${Fp()}`,fix:"Reinstall document360-writer (broken install)"});let C=st(e);if(C.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${xe})`}):C.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${C.completedVersion}, current is v${xe}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),x&&(!ul(x)||x.refreshToken)){let S={profile:k.name,connection:k.connection};try{await Ik(S);let N=await jk(S,"/v3/projects");n.push({level:"ok",label:`API reachable (${k.connection.apiUrl}) \u2014 ${N.length} project(s) visible`})}catch(N){n.push({level:"fail",label:`API call failed: ${N.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let R=T?.projectId??k.project.projectId;if(R&&k.project.workspaceId){try{let N=await Wk(S,R,k.project.workspaceId);if(N){let V=(N.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Workspace sync manifest: available on ${k.connection.name} (${N.languages?.length??0} language${(N.languages?.length??0)===1?"":"s"}) \xB7 hash ${V||"(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(N){N instanceof Kk||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(N.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${k.project.projectName??R})`,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 (${N.message.slice(0,80)})`})}try{let N=await zk({cwd:e,profileName:k.name,dryRun:!0}),V=N.categoriesReordered+N.articlesReordered;if(N.skipped==="no category map")n.push({level:"ok",label:"Reading order: nothing to check yet (no articles published)"});else if(N.skipped)n.push({level:"warn",label:`Reading order: can't be checked (${N.skipped})`,fix:"Your article order on Document360 may not match your structure \u2014 /publish syncs it once this resolves"});else if(N.unverified)n.push({level:"warn",label:`Reading order: ${N.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(V>0){let K=[N.categoriesReordered>0?`${N.categoriesReordered} categor${N.categoriesReordered===1?"y":"ies"}`:"",N.articlesReordered>0?`${N.articlesReordered} article${N.articlesReordered===1?"":"s"}`:""].filter(Boolean);n.push({level:"warn",label:`Reading order: ${K.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(N){n.push({level:"warn",label:`Reading order: check failed (${N.message.slice(0,80)})`})}}}return n}function Hp(e){let t=[""];for(let r of e){let s=r.level==="ok"?B("\u2713"):r.level==="warn"?W("\u26A0"):j("\u2717");t.push(` ${s} ${r.label}${r.detail?b(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${b("fix:")} ${q(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?B(`\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 Vo(e,t){console.log(b("Running checks\u2026"));for(let n of Hp(await Bp(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var Es=Co(()=>{"use strict";Mt();Q();jo()});import{Command as Q0}from"commander";import{createRequire as Z0}from"node:module";import{AUTH_MODES as eC}from"document360-engine";import{input as ag}from"@inquirer/prompts";import{loginPkce as lg,refreshTokens as cg,toStoredTokens as uu,clearTokens as ug,decodeJwtClaims as cu,isExpired as dg,loadTokens as pg,saveTokens as du,resolveActiveProfile as Fr,setProfileProject as hg,readProjectConfig as fg}from"document360-engine";Q();import{select as Gm}from"@inquirer/prompts";import{resolveActiveProfile as Vm,setProfileProject as Ym,resolveProjectId as Km,listWorkspaces as zm}from"document360-engine";async function So(e,t){let n=Vm(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Km(o);return{workspaces:await zm(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var ru=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function ji(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 _r(e,t,n,o,r){Ym(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function su(e,t,n){let o;try{o=await So(e,n)}catch(s){return console.log(j(`Could not list workspaces: ${s.message}`)),1}let r=ji(o.workspaces,t);return r?(_r(e,o.profile,o.projectId,r.id,r.name),console.log(B(`\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 On(e,t){let n;try{n=await So(e,t)}catch(h){console.log(j(`Could not list workspaces: ${h.message}`));return}let{workspaces:o,projectId:r,profile:s,current:i}=n;if(o.length===0){console.log(b("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let h of o)console.log(` ${h.id===i?q("\u25CF"):" "} ${ru(h)} ${b(h.id)}`);console.log(b("Run: d360-writer workspace use <name>"));return}let a=await Gm({message:"Select the Document360 workspace for this repo:",choices:o.map(h=>({name:`${ru(h)}${h.id===i?" (current)":""}`,value:h.id}))}),u=o.find(h=>h.id===a);_r(e,s,r,a,u?.name),console.log(B(`\u2713 Workspace set to "${u?.name??a}" for profile "${s}".`))}Q();import{select as Xm}from"@inquirer/prompts";import{resolveActiveProfile as Jm,setProfileProject as Qm,listProjects as Zm}from"document360-engine";async function It(e,t){let n=Jm(e,t),o={profile:n.name,connection:n.connection};return{projects:await Zm(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var iu=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Ii(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 Mr(e,t,n,o){Qm(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function au(e,t,n){let o;try{o=await It(e,n)}catch(s){return console.log(j(`Could not list projects: ${s.message}`)),1}let r=Ii(o.projects,t);return r?(Mr(e,o.profile,r.id,r.name),console.log(B(`\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 Ur(e,t){let n;try{n=await It(e,t)}catch(u){console.log(j(`Could not list projects: ${u.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(b("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let u of o)console.log(` ${u.id===s?q("\u25CF"):" "} ${iu(u)} ${b(u.id)}`);console.log(b("Run: d360-writer project use <name>"));return}let i=await Xm({message:"Select the Document360 project for this repo:",choices:o.map(u=>({name:`${iu(u)}${u.id===s?" (current)":""}`,value:u.id}))}),a=o.find(u=>u.id===i);Mr(e,r,i,a?.name),console.log(B(`\u2713 Project set to "${a?.name??i}" for profile "${r}". Next: pick a workspace.`))}Q();import eg from"picocolors";function tg(e=process.env){return e.FORCE_HYPERLINK==="0"||!eg.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 ng(e,t=e,n){return tg(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var og=/https?:\/\/[^\s\x1b]+/g;function Po(e,t){return e.replace(og,n=>ng(n,n,t))}import{readProjectConfig as lu,sunsetEnvironment as rg,resolveActiveProfile as sg}from"document360-engine";function ig(e,t){let n=lu(e);return Object.entries(n?.profiles??{}).find(([,o])=>(o.connection?.environment??"berlin")===t)?.[0]??null}function Ot(e,t){try{if(!lu(e))return null;let n=sg(e,t),o=rg(n.connection.name);if(!o)return null;let r=ig(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 pu(e){return{...cu(e.idToken)??{},...cu(e.accessToken)??{}}}function Wr(e){let t=pu(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 Br(e){let t=Fr(process.cwd(),e.profile),n=t.connection;console.log(b(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=Ot(process.cwd(),e.profile);o&&(console.log(W(`\u26A0 ${o.why} \u2014 and signing in does NOT change it (the environment comes from the profile, not the login).`)),console.log(W(` To move: ${o.cmd}${o.replacementProfile?"":", then /login"}`)));let r=await lg(n,{manual:e.manual,promptForRedirect:i=>ag({message:i})},i=>console.log(Po(i))),s=uu(t.name,r);if(du(s),await Oi(s,t.name,i=>console.log(b(i))),console.log(""),console.log(B(`\u2713 Logged in to "${t.name}" as ${Wr(s)}`)),console.log(b(` access token expires: ${s.expiresAt}`)),console.log(b(` refresh token: ${s.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{fg(process.cwd())?.profiles?.[t.name]&&(console.log(""),await On(process.cwd(),t.name))}catch{}}async function Oi(e,t,n){let r=pu(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Fr(process.cwd(),t).project.projectId)return;let i;try{let{projects:a}=await It(process.cwd(),t);i=a.find(u=>u.id===r)?.name}catch{}hg(process.cwd(),t,{projectId:r,projectName:i}),n(` Project "${i??r}" written to profile "${t}".`)}catch{}}async function hu(e){let t=Fr(process.cwd(),e.profile),n=t.connection,o=pg(t.name);if(!o){console.log(j(`Not logged in to Document360 (profile "${t.name}").`)),console.log(b(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${q(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Wr(o)}`),dg(o))if(o.refreshToken)try{let r=uu(t.name,await cg(n,o.refreshToken));du(r),console.log(B(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(W(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(b(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(W("Session expired (no refresh token).")),console.log(b(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(b(` expires: ${o.expiresAt}`))}async function fu(e){let t=Fr(process.cwd(),e.profile);ug(t.name)?console.log(B(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(b(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}Q();import{readProjectConfig as mu,writeProjectConfig as mg,resolveActiveProfile as gg,loadTokens as wg,isExpired as yg}from"document360-engine";function Hr(e){let t=mu(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?q("\u25CF "):" ",s=o.production?W(" \u26A0 PRODUCTION"):"",i=o.connection.environment??"(inline)",a=wg(n),u=a?yg(a)&&!a.refreshToken?W("expired"):b("logged in"):b("not logged in");console.log(`${r}${q(n)} \u2192 ${i}${s} [${u}]`)}console.log(""),console.log(b("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function qr(e,t){let n=mu(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,mg(n,e);let o=n.profiles[t].production?W(" \u26A0 PRODUCTION"):"";console.log(B(`\u2713 Default profile is now "${t}"${o}`))}function Gr(e,t){try{let n=gg(e,t);console.log(""),console.log(`Profile ${q(n.name)}${n.production?W(" \u26A0 PRODUCTION"):""}`),console.log(b(` api: ${n.connection.apiUrl}`)),console.log(b(` identity: ${n.connection.authorizationUrl}`)),console.log(b(` clientId: ${n.connection.clientId}`)),console.log(b(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(b(` project: ${n.project.projectId??"(set at login)"}`)),console.log(b(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(j(n.message)),process.exitCode=1}}Q();import{existsSync as kg,readdirSync as bg,statSync as gu}from"node:fs";import{join as wu}from"node:path";import{apiLogDir as $g}from"document360-engine";function yu(){let e=$g();if(console.log(""),console.log(`Document360 API logs: ${q(e)}`),!kg(e)){console.log(b(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=bg(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(b(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let s=(gu(wu(e,r)).size/1024).toFixed(1);console.log(` ${r} ${b(`${s} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${b("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let s=(gu(wu(e,r)).size/1024).toFixed(1);console.log(` ${j(r)} ${b(`${s} KB`)}`)}}console.log(""),console.log(b("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(b("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}Q();import{createSession as vg,resolveAuth as xg,findByName as Cg,slugify as Rg,touchSession as Sg,upsertSession as Pg,resolveActiveProfile as Tg}from"document360-engine";async function ku(e,t,n,o,r,s){let i=xg(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 ${q("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${q("d360-writer --auth subscription")}`),process.exit(2)),i.kind==="subscription"&&console.error(b("Using your Claude subscription (no API key set)."));let a=null;try{a=Tg(e,r)}catch(x){console.error(j(`Document360 profile error: ${x.message}`)),process.exit(2)}a.production&&(console.error(W(`\u26A0 Profile "${a.name}" is PRODUCTION.`)),s||(console.error(j("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(b(" --yes given \u2014 proceeding against production.")));let u;if(o){let x=Cg(e,o);x||(console.error(j(`No saved session matches "${o}" in this repo.`)),console.error(b("List sessions inside the REPL with /resume.")),process.exit(2)),u=x.uuid,console.error(b(`Resuming "${x.name}"`))}let h=vg({cwd:e,resume:u,profileName:r,allowProdWrites:s===!0}),g=u??null,k=1;for await(let x of h.send(t))switch(x.type){case"session":if(!g){g=x.sessionId;let T=new Date().toISOString();Pg({uuid:g,name:Rg(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:T,updatedAt:T})}break;case"text":process.stdout.write(x.delta);break;case"tool":console.error(fe(` \u2699 ${x.name}`));break;case"result":k=x.ok?0:1,console.error(b(`(${x.inputTokens}\u2192${x.outputTokens} tokens`+(x.costUsd>0?`, $${x.costUsd<.01?x.costUsd.toFixed(4):x.costUsd.toFixed(2)}`:"")+")")),x.ok||console.error(j("agent finished with an error result"));break;case"error":console.error(""),console.error(j(`agent error: ${x.message}`)),process.exit(1)}g&&Sg(g),process.stdout.write(`
|
|
297
|
-
`),process.exit(k)}import{createInterface as
|
|
298
|
-
`)}var Fe=[{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:"/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:"See the comments reviewers left on passages of your articles in the Document360 portal, then pick what to handle \u2014 everything, one category, or one article at a time. 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."},{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."},{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 pick an article, or all (--answer fixes + replies; --resolve also closes them)."},{t:"cmd",name:"/inbox",s:"Act on your coding agent's messages."},{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."}]}],bu=24;function Li(e){let t=e.filter(n=>n.t==="cmd").map(n=>n.name.length);return t.length===0?bu:Math.min(bu,Math.max(...t))}function Kr(e,t,n,o){let r=" ".repeat(2+n+1),s=Math.max(24,o-r.length-2),i=Lt(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 Eg(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=Kr(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 $u(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 Fe){n.push(`\u2500\u2500 ${o.label} \u2500\u2500`,"");let r=Li(o.rows);for(let s of o.rows)n.push(
|
|
295
|
+
`;Du="Re-run dev\u2194docs onboarding (protocol v"});var Vu={};nu(Vu,{initCommand:()=>qi,scaffoldInit:()=>Hi});import{input as Ao,confirm as Bg}from"@inquirer/prompts";import{basename as _u,join as Zr}from"node:path";import{existsSync as Fn,readFileSync as Hg,readdirSync as qg,writeFileSync as Gg}from"node:fs";import{writeProjectConfig as Mu,readProjectConfig as Vg,projectConfigPath as Uu,writerDir as Yg,DEFAULT_DOCS_DIR as Fu,DEFAULT_CAPTURE_DIR as Wu,DEFAULT_OUTPUT_DIR as Bu}from"document360-engine";function Hi(e,t="berlin"){let n=Uu(e);if(Fn(n))return{created:!1,path:n,profileName:""};let o={projectId:qu(e)??_u(e),docsDir:Fu,captureDir:Wu,outputDir:Bu,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:Gu(e)};return Mu(o,e),Hu(e),{created:!0,path:n,profileName:t}}function Hu(e){let t=Zr(Yg(e),".gitignore");Fn(t)||Gg(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
|
|
296
|
+
`),"utf8")}async function qi(){let e=process.cwd(),t=Uu(e);if(Fn(t)&&!await Bg({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(b("init cancelled.")),{kind:"continue"};let n=qu(e)??_u(e),o=await Ao({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await Ao({message:"Capture directory (where document360-capture .spec.ts files live):",default:Wu}),s=await Ao({message:"Screenshot output directory:",default:Bu}),i=await Ao({message:"Default connection profile name:",default:"berlin"}),a=await Ao({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),u={projectId:o,docsDir:Fu,captureDir:r,outputDir:s,profiles:{[i]:{connection:{environment:a},production:!1}},defaultProfile:i,authoritativeSourceFiles:Gu(e)},h=Vg(e);h?.terminologyGlossary&&(u.terminologyGlossary=h.terminologyGlossary),Mu(u,e),Hu(e);let g=Mn(e);console.log(""),console.log(B(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${q(`d360-writer login --profile ${i}`)} ${b("(sign in; project & workspace auto-selected)")}`),console.log("");for(let k of Un(g))console.log(k);return console.log(""),console.log(`${b("Then ask:")} ${q('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function qu(e){let t=Zr(e,"package.json");if(!Fn(t))return null;try{return JSON.parse(Hg(t,"utf8")).name??null}catch{return null}}function Gu(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Fn(Zr(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Zr(e,n);Fn(o)&&!Kg(o)&&t.push(n)}return t}function Kg(e){try{return qg(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var es=Ro(()=>{"use strict";Q();Mt()});import{createRequire as yw}from"node:module";import{existsSync as kw,readFileSync as bw}from"node:fs";import{dirname as wd,join as yd}from"node:path";function xt(){let e;try{e=$w.resolve("document360-capture/helpers")}catch{return null}let t=wd(e);for(let n=0;n<5&&!kw(yd(t,"package.json"));n++)t=wd(t);try{let n=JSON.parse(bw(yd(t,"package.json"),"utf8"));return n.name==="document360-capture"&&n.version?n.version:null}catch{return null}}var $w,Io=Ro(()=>{"use strict";$w=yw(import.meta.url)});var Gp={};nu(Gp,{doctorCommand:()=>Yo,renderDoctorChecks:()=>qp,runDoctorChecks:()=>Hp});import{existsSync as jk}from"node:fs";import{d360GetAll as Ik,getAccessToken as Ok,isExpired as ul,loadProfileMap as Lk,loadTokens as _k,packageSkillsDir as Wp,ENGINE_VERSION as Mk,projectConfigPath as Uk,readProjectConfig as Fk,DEFAULT_DOCS_DIR as Wk,fetchManifestSummary as Bk,resolveActiveProfile as Hk,classifyClaudeAuth as qk,CLAUDE_CODE_SETUP_HINT as Bp,resolveModelSetting as Gk,probeModel as Vk,detectAppType as Yk,playbookSkillName as Kk,D360AuthError as zk,applyStructureOrder as Xk}from"document360-engine";async function Hp(e,t){let n=[],o=xt();n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${Mk}${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=qk();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. ${Bp}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:Bp});let i=Gk(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 S=await Vk(e,i.model??void 0);S.ok?n.push({level:"ok",label:`Model reachable \u2014 replied in ${(S.latencyMs/1e3).toFixed(1)}s`}):S.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 ${S.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=Fk(e);if(!a)return n.push({level:"fail",label:`No ${Uk(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${a.projectId}`});let u=(a.docsDir??Wk).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 ${u}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let h=a.authoritativeSourceFiles??[];n.push(h.length>0?{level:"ok",label:`Sources: docs grounded in ${h.length} path(s) (${h.slice(0,3).join(", ")}${h.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??Yk(e);if(g){let S=a.appType?"from config":"auto-detected",R=g==="web"||g==="cli";n.push({level:"ok",label:`Genre: ${g} (${S})${R?` \u2192 ${Kk(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=Hk(e),n.push({level:"ok",label:`Profile: ${k.name} (${k.connection.name})${k.production?" \u26A0 PRODUCTION":""}`})}catch(S){return n.push({level:"fail",label:`Profile config: ${S.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let x=_k(k.name);x?ul(x)&&!x.refreshToken?n.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):ul(x)?n.push({level:"ok",label:"Document360: logged in (access token expired \u2014 refreshes automatically on the next call)"}):n.push({level:"ok",label:`Document360: logged in (until ${new Date(x.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 T=Lk(e,k.name);T?T.projectId&&k.project.projectId&&T.projectId!==k.project.projectId?n.push({level:"fail",label:`Category map projectId (${T.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(T.articles).length} articles, ${Object.keys(T.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${k.name}" (created on first /publish)`}),n.push(jk(Wp())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${Wp()}`,fix:"Reinstall document360-writer (broken install)"});let C=it(e);if(C.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${xe})`}):C.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${C.completedVersion}, current is v${xe}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),x&&(!ul(x)||x.refreshToken)){let S={profile:k.name,connection:k.connection};try{await Ok(S);let N=await Ik(S,"/v3/projects");n.push({level:"ok",label:`API reachable (${k.connection.apiUrl}) \u2014 ${N.length} project(s) visible`})}catch(N){n.push({level:"fail",label:`API call failed: ${N.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let R=T?.projectId??k.project.projectId;if(R&&k.project.workspaceId){try{let N=await Bk(S,R,k.project.workspaceId);if(N){let V=(N.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Workspace sync manifest: available on ${k.connection.name} (${N.languages?.length??0} language${(N.languages?.length??0)===1?"":"s"}) \xB7 hash ${V||"(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(N){N instanceof zk||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(N.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${k.project.projectName??R})`,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 (${N.message.slice(0,80)})`})}try{let N=await Xk({cwd:e,profileName:k.name,dryRun:!0}),V=N.categoriesReordered+N.articlesReordered;if(N.skipped==="no category map")n.push({level:"ok",label:"Reading order: nothing to check yet (no articles published)"});else if(N.skipped)n.push({level:"warn",label:`Reading order: can't be checked (${N.skipped})`,fix:"Your article order on Document360 may not match your structure \u2014 /publish syncs it once this resolves"});else if(N.unverified)n.push({level:"warn",label:`Reading order: ${N.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(V>0){let K=[N.categoriesReordered>0?`${N.categoriesReordered} categor${N.categoriesReordered===1?"y":"ies"}`:"",N.articlesReordered>0?`${N.articlesReordered} article${N.articlesReordered===1?"":"s"}`:""].filter(Boolean);n.push({level:"warn",label:`Reading order: ${K.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(N){n.push({level:"warn",label:`Reading order: check failed (${N.message.slice(0,80)})`})}}}return n}function qp(e){let t=[""];for(let r of e){let s=r.level==="ok"?B("\u2713"):r.level==="warn"?W("\u26A0"):j("\u2717");t.push(` ${s} ${r.label}${r.detail?b(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${b("fix:")} ${q(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?B(`\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 Yo(e,t){console.log(b("Running checks\u2026"));for(let n of qp(await Hp(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var Es=Ro(()=>{"use strict";Mt();Q();Io()});import{Command as Z0}from"commander";import{createRequire as eC}from"node:module";import{AUTH_MODES as tC}from"document360-engine";import{input as lg}from"@inquirer/prompts";import{loginPkce as cg,refreshTokens as ug,toStoredTokens as uu,clearTokens as dg,decodeJwtClaims as cu,isExpired as pg,loadTokens as hg,saveTokens as du,resolveActiveProfile as Fr,setProfileProject as fg,readProjectConfig as mg}from"document360-engine";Q();import{select as Vm}from"@inquirer/prompts";import{resolveActiveProfile as Ym,setProfileProject as Km,resolveProjectId as zm,listWorkspaces as Xm}from"document360-engine";async function Po(e,t){let n=Ym(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??zm(o);return{workspaces:await Xm(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var ru=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function ji(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 _r(e,t,n,o,r){Km(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function su(e,t,n){let o;try{o=await Po(e,n)}catch(s){return console.log(j(`Could not list workspaces: ${s.message}`)),1}let r=ji(o.workspaces,t);return r?(_r(e,o.profile,o.projectId,r.id,r.name),console.log(B(`\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 On(e,t){let n;try{n=await Po(e,t)}catch(h){console.log(j(`Could not list workspaces: ${h.message}`));return}let{workspaces:o,projectId:r,profile:s,current:i}=n;if(o.length===0){console.log(b("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let h of o)console.log(` ${h.id===i?q("\u25CF"):" "} ${ru(h)} ${b(h.id)}`);console.log(b("Run: d360-writer workspace use <name>"));return}let a=await Vm({message:"Select the Document360 workspace for this repo:",choices:o.map(h=>({name:`${ru(h)}${h.id===i?" (current)":""}`,value:h.id}))}),u=o.find(h=>h.id===a);_r(e,s,r,a,u?.name),console.log(B(`\u2713 Workspace set to "${u?.name??a}" for profile "${s}".`))}Q();import{select as Jm}from"@inquirer/prompts";import{resolveActiveProfile as Qm,setProfileProject as Zm,listProjects as eg}from"document360-engine";async function It(e,t){let n=Qm(e,t),o={profile:n.name,connection:n.connection};return{projects:await eg(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var iu=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Ii(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 Mr(e,t,n,o){Zm(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function au(e,t,n){let o;try{o=await It(e,n)}catch(s){return console.log(j(`Could not list projects: ${s.message}`)),1}let r=Ii(o.projects,t);return r?(Mr(e,o.profile,r.id,r.name),console.log(B(`\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 Ur(e,t){let n;try{n=await It(e,t)}catch(u){console.log(j(`Could not list projects: ${u.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(b("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let u of o)console.log(` ${u.id===s?q("\u25CF"):" "} ${iu(u)} ${b(u.id)}`);console.log(b("Run: d360-writer project use <name>"));return}let i=await Jm({message:"Select the Document360 project for this repo:",choices:o.map(u=>({name:`${iu(u)}${u.id===s?" (current)":""}`,value:u.id}))}),a=o.find(u=>u.id===i);Mr(e,r,i,a?.name),console.log(B(`\u2713 Project set to "${a?.name??i}" for profile "${r}". Next: pick a workspace.`))}Q();import tg from"picocolors";function ng(e=process.env){return e.FORCE_HYPERLINK==="0"||!tg.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 og(e,t=e,n){return ng(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var rg=/https?:\/\/[^\s\x1b]+/g;function To(e,t){return e.replace(rg,n=>og(n,n,t))}import{readProjectConfig as lu,sunsetEnvironment as sg,resolveActiveProfile as ig}from"document360-engine";function ag(e,t){let n=lu(e);return Object.entries(n?.profiles??{}).find(([,o])=>(o.connection?.environment??"berlin")===t)?.[0]??null}function Ot(e,t){try{if(!lu(e))return null;let n=ig(e,t),o=sg(n.connection.name);if(!o)return null;let r=ag(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 pu(e){return{...cu(e.idToken)??{},...cu(e.accessToken)??{}}}function Wr(e){let t=pu(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 Br(e){let t=Fr(process.cwd(),e.profile),n=t.connection;console.log(b(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=Ot(process.cwd(),e.profile);o&&(console.log(W(`\u26A0 ${o.why} \u2014 and signing in does NOT change it (the environment comes from the profile, not the login).`)),console.log(W(` To move: ${o.cmd}${o.replacementProfile?"":", then /login"}`)));let r=await cg(n,{manual:e.manual,promptForRedirect:i=>lg({message:i})},i=>console.log(To(i))),s=uu(t.name,r);if(du(s),await Oi(s,t.name,i=>console.log(b(i))),console.log(""),console.log(B(`\u2713 Logged in to "${t.name}" as ${Wr(s)}`)),console.log(b(` access token expires: ${s.expiresAt}`)),console.log(b(` refresh token: ${s.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{mg(process.cwd())?.profiles?.[t.name]&&(console.log(""),await On(process.cwd(),t.name))}catch{}}async function Oi(e,t,n){let r=pu(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Fr(process.cwd(),t).project.projectId)return;let i;try{let{projects:a}=await It(process.cwd(),t);i=a.find(u=>u.id===r)?.name}catch{}fg(process.cwd(),t,{projectId:r,projectName:i}),n(` Project "${i??r}" written to profile "${t}".`)}catch{}}async function hu(e){let t=Fr(process.cwd(),e.profile),n=t.connection,o=hg(t.name);if(!o){console.log(j(`Not logged in to Document360 (profile "${t.name}").`)),console.log(b(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${q(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Wr(o)}`),pg(o))if(o.refreshToken)try{let r=uu(t.name,await ug(n,o.refreshToken));du(r),console.log(B(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(W(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(b(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(W("Session expired (no refresh token).")),console.log(b(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(b(` expires: ${o.expiresAt}`))}async function fu(e){let t=Fr(process.cwd(),e.profile);dg(t.name)?console.log(B(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(b(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}Q();import{readProjectConfig as mu,writeProjectConfig as gg,resolveActiveProfile as wg,loadTokens as yg,isExpired as kg}from"document360-engine";function Hr(e){let t=mu(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?q("\u25CF "):" ",s=o.production?W(" \u26A0 PRODUCTION"):"",i=o.connection.environment??"(inline)",a=yg(n),u=a?kg(a)&&!a.refreshToken?W("expired"):b("logged in"):b("not logged in");console.log(`${r}${q(n)} \u2192 ${i}${s} [${u}]`)}console.log(""),console.log(b("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function qr(e,t){let n=mu(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,gg(n,e);let o=n.profiles[t].production?W(" \u26A0 PRODUCTION"):"";console.log(B(`\u2713 Default profile is now "${t}"${o}`))}function Gr(e,t){try{let n=wg(e,t);console.log(""),console.log(`Profile ${q(n.name)}${n.production?W(" \u26A0 PRODUCTION"):""}`),console.log(b(` api: ${n.connection.apiUrl}`)),console.log(b(` identity: ${n.connection.authorizationUrl}`)),console.log(b(` clientId: ${n.connection.clientId}`)),console.log(b(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(b(` project: ${n.project.projectId??"(set at login)"}`)),console.log(b(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(j(n.message)),process.exitCode=1}}Q();import{existsSync as bg,readdirSync as $g,statSync as gu}from"node:fs";import{join as wu}from"node:path";import{apiLogDir as vg}from"document360-engine";function yu(){let e=vg();if(console.log(""),console.log(`Document360 API logs: ${q(e)}`),!bg(e)){console.log(b(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=$g(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(b(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let s=(gu(wu(e,r)).size/1024).toFixed(1);console.log(` ${r} ${b(`${s} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${b("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let s=(gu(wu(e,r)).size/1024).toFixed(1);console.log(` ${j(r)} ${b(`${s} KB`)}`)}}console.log(""),console.log(b("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(b("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}Q();import{createSession as xg,resolveAuth as Cg,findByName as Rg,slugify as Sg,touchSession as Pg,upsertSession as Tg,resolveActiveProfile as Eg}from"document360-engine";async function ku(e,t,n,o,r,s){let i=Cg(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 ${q("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${q("d360-writer --auth subscription")}`),process.exit(2)),i.kind==="subscription"&&console.error(b("Using your Claude subscription (no API key set)."));let a=null;try{a=Eg(e,r)}catch(x){console.error(j(`Document360 profile error: ${x.message}`)),process.exit(2)}a.production&&(console.error(W(`\u26A0 Profile "${a.name}" is PRODUCTION.`)),s||(console.error(j("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(b(" --yes given \u2014 proceeding against production.")));let u;if(o){let x=Rg(e,o);x||(console.error(j(`No saved session matches "${o}" in this repo.`)),console.error(b("List sessions inside the REPL with /resume.")),process.exit(2)),u=x.uuid,console.error(b(`Resuming "${x.name}"`))}let h=xg({cwd:e,resume:u,profileName:r,allowProdWrites:s===!0}),g=u??null,k=1;for await(let x of h.send(t))switch(x.type){case"session":if(!g){g=x.sessionId;let T=new Date().toISOString();Tg({uuid:g,name:Sg(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:T,updatedAt:T})}break;case"text":process.stdout.write(x.delta);break;case"tool":console.error(fe(` \u2699 ${x.name}`));break;case"result":k=x.ok?0:1,console.error(b(`(${x.inputTokens}\u2192${x.outputTokens} tokens`+(x.costUsd>0?`, $${x.costUsd<.01?x.costUsd.toFixed(4):x.costUsd.toFixed(2)}`:"")+")")),x.ok||console.error(j("agent finished with an error result"));break;case"error":console.error(""),console.error(j(`agent error: ${x.message}`)),process.exit(1)}g&&Pg(g),process.stdout.write(`
|
|
297
|
+
`),process.exit(k)}import{createInterface as Bv}from"node:readline/promises";import{createSession as Zl,resolveAuth as Hv,getSession as qv,setTitle as Gv,slugify as Vv,touchSession as hf,upsertSession as Yv,generateTitle as Kv,resolveActiveProfile as ff,resolveModelSetting as zv,readProjectConfig as Xv,readUserConfig as Jv,resolveAndPersistAppType as Qv,decodeJwtClaims as df,isExpired as Zv,loadTokens as ex,isDirectiveMention as tx,stripDirectiveMention as nx,appendDirective as ox,reconcileUpgradeActions as rx,stampArticles as sx,listArticleFiles as ix,applyStructureOrder as ax,orderSyncLine as lx,computeSyncStatus as cx}from"document360-engine";import{ENGINE_VERSION as Ng}from"document360-engine";function Lt(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 Vr(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 Lt(`${i+1}. ${s.feature}`,76))o.push(n(a));o.push(n());for(let a of Lt(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 Yr(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 Fe=[{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:"/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:"See the comments reviewers left on passages of your articles in the Document360 portal, then pick what to handle \u2014 everything, one category, or one article at a time. 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."},{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."},{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 pick an article, or all (--answer fixes + replies; --resolve also closes them)."},{t:"cmd",name:"/inbox",s:"Act on your coding agent's messages."},{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."}]}],bu=24;function Li(e){let t=e.filter(n=>n.t==="cmd").map(n=>n.name.length);return t.length===0?bu:Math.min(bu,Math.max(...t))}function Kr(e,t,n,o){let r=" ".repeat(2+n+1),s=Math.max(24,o-r.length-2),i=Lt(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 Ag(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=Kr(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 $u(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 Fe){n.push(`\u2500\u2500 ${o.label} \u2500\u2500`,"");let r=Li(o.rows);for(let s of o.rows)n.push(Ag(s,r,100));n.push("")}return n.push("Tip: anything not starting with / goes to the agent."),n}function _i(e,t){return Lt(e,Math.max(10,Math.max(20,t)-2))}function Dg(e,t,n){let o=Math.max(20,n),r=s=>Math.max(1,_i(s,o).length);switch(e.t){case"gap":return 1;case"cmd":{let s=Kr(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 vu(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=Dg(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 xu(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 Mi(e=[],t){console.log("");let n=t?.version?{version:t.version,engineVersion:Ng}:void 0;for(let o of $u(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"}}Q();import{getSession as jg}from"document360-engine";async function Cu(e,t){let n=t.currentUuid(),o=n?jg(n):void 0;return console.log(o?b(`
|
|
300
300
|
(conversation reset \u2014 "${o.name}" is still available via /resume)
|
|
301
301
|
`):b(`
|
|
302
302
|
(conversation reset \u2014 agent will start fresh on the next prompt)
|
|
303
|
-
`)),{kind:"clear"}}async function Ui(){return{kind:"exit"}}es();Q();import{readMcpConfig as Gi,writeMcpConfig as Yu}from"document360-engine";async function ts(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(
|
|
303
|
+
`)),{kind:"clear"}}async function Ui(){return{kind:"exit"}}es();Q();import{readMcpConfig as Gi,writeMcpConfig as Yu}from"document360-engine";async function ts(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(zg(),{kind:"continue"}):t==="add"?(Xg(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(Jg(e.slice(1)),{kind:"continue"}):(console.log(j(`Unknown /mcp subcommand: ${t}`)),console.log(b("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function zg(){let e=Gi(),t=Object.keys(e.servers);if(t.length===0){console.log(b(`
|
|
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(` ${q(n)} ${b("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?b(` [headers: ${r.join(", ")}]`):"";console.log(` ${q(n)} ${b(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function zg(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=Gi(),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 u=o[++a],h=u?.match(/^([^:=]+)[:=](.+)$/);if(!h){console.log(j(`-H expects key:value (no spaces). Got: ${u??"(nothing)"}`));return}i[h[1].trim()]=h[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,Yu(r),console.log(""),console.log(B(`\u2713 Registered "${t}" (${n})`)),console.log(W(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(b(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function Xg(e){let t=e[0];if(!t){console.log(j("Usage: /mcp remove <name>"));return}let n=Gi();if(!n.servers[t]){console.log(j(`No server named "${t}".`));return}delete n.servers[t],Yu(n),console.log(B(`\u2713 Removed "${t}".`)),console.log(b(" Run /clear to drop it from the current session immediately."))}Q();import{readFileSync as ay}from"node:fs";import{join as ly}from"node:path";import{select as cy}from"@inquirer/prompts";import{computeSyncStatus as ys,planPartitions as uy,relatedArticlePaths as dy,resolveModelForOperation as py,runPartitioned as hy,loadProfileMap as zd,resolveActiveProfile as va,unreviewedPaths as fy,listArticleFiles as my,ensureFeedbackChannel as gy,FEEDBACK_CATEGORY_NAME as wy,resolveCrossLinks as yy,applyStructureOrder as Xd,orderSyncLine as Jd,applyRelatedArticles as Qd,relatedSyncLine as Zd}from"document360-engine";import{readFileSync as Jg}from"node:fs";import{resolve as Qg}from"node:path";import{prettyFolderName as Ku}from"document360-engine";var Wn=Ku;function zu(e){return e.replace(/\\/g,"/").split("/").slice(0,-1).join("/")}function Vi(e){let t=e.replace(/\\/g,"/").split("/").pop()??e;return Ku(t.replace(/\.md$/i,""))}function Xu(e,t){try{return/^#\s+(.+)$/m.exec(Jg(Qg(e,t),"utf8"))?.[1]?.trim()??null}catch{return null}}import ie from"picocolors";import Qi from"wrap-ansi";import Zi from"string-width";Q();import Ut from"picocolors";import Yi from"wrap-ansi";import Ki from"string-width";var Bn=[{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]",desc:"Write the planned articles in parallel (starts immediately; --preview shows plan + cost first; --rewrite regenerates already-written articles; --concurrency default 3)",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|--screenshots] [--skip-review]",desc:"Publish to Document360 (no arg: pick; --all: every candidate; --screenshots: re-save articles with captured shots so images embed). Blocked until each article has had /review --fix \u2014 AI-written text gets an editor first; --skip-review overrides deliberately",group:"publish"},{name:"check",usage:"/check [<category|path>] [--fix]",desc:"Check docs for leaked internals, invented commands, and stale facts (deterministic, no tokens). Scope to a category/path; --fix has the agent correct the findings in place",group:"docs"},{name:"review",usage:"/review [<category|path> | --all] [--fix]",desc:"Independent senior-editor review: style guide, terminology/voice, grammar/clarity, structure, improvement suggestions. Bare: pick a category or everything; --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]",desc:"Reviewer comments left on passages of your articles in the Document360 portal \u2014 bare: show what's open, then pick an article to handle; --answer: fix, push the draft, reply (threads stay open unless you add --resolve)",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"}],Ju={"/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"};function Qu(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(Ju[n])return Ju[n];let o=Bn.find(r=>r.name===t);return o?o.desc:""}function Zu(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return Bn.filter(n=>n.name.startsWith(t))}function ed(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}var Zg=new RegExp(`^\\s*/(?:${Bn.map(e=>e.name).join("|")})(?:\\s|$)`),td=e=>Zg.test(e),nd=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),od=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),rd=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function ew(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(nd(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&od(t[o+1])){let a=rd(r);o+=2;let u=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)u.push(rd(t[o++]));n.push({kind:"table",header:a,rows:u});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 u=t[o++];a.push({ordered:/^\s*\d+\.\s+/.test(u),text:u.replace(/^\s*([-*]|\d+\.)\s+/,"")})}n.push({kind:"list",items:a});continue}if(r.trim()===""){o++;continue}if(td(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])&&!td(t[o])&&!nd(t[o])&&!(t[o].includes("|")&&o+1<t.length&&od(t[o+1]));)i.push(t[o++]);n.push({kind:"para",text:i.join(" ")})}return n}function zi(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?Ut.bold(t.slice(2,-2)):t.startsWith("`")?q(t.slice(1,-1)):Ut.italic(t.slice(1,-1)))}var
|
|
307
|
-
`)}),N=Math.max(...R.map(K=>K.length)),V=[];for(let K=0;K<N;K++)V.push(a.map((G,ae)=>`${k} ${
|
|
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(` ${q(n)} ${b("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?b(` [headers: ${r.join(", ")}]`):"";console.log(` ${q(n)} ${b(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function Xg(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=Gi(),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 u=o[++a],h=u?.match(/^([^:=]+)[:=](.+)$/);if(!h){console.log(j(`-H expects key:value (no spaces). Got: ${u??"(nothing)"}`));return}i[h[1].trim()]=h[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,Yu(r),console.log(""),console.log(B(`\u2713 Registered "${t}" (${n})`)),console.log(W(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(b(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function Jg(e){let t=e[0];if(!t){console.log(j("Usage: /mcp remove <name>"));return}let n=Gi();if(!n.servers[t]){console.log(j(`No server named "${t}".`));return}delete n.servers[t],Yu(n),console.log(B(`\u2713 Removed "${t}".`)),console.log(b(" Run /clear to drop it from the current session immediately."))}Q();import{readFileSync as ly}from"node:fs";import{join as cy}from"node:path";import{select as uy}from"@inquirer/prompts";import{computeSyncStatus as ys,planPartitions as dy,relatedArticlePaths as py,resolveModelForOperation as hy,runPartitioned as fy,loadProfileMap as Xd,resolveActiveProfile as va,unreviewedPaths as my,listArticleFiles as gy,ensureFeedbackChannel as wy,FEEDBACK_CATEGORY_NAME as yy,resolveCrossLinks as ky,applyStructureOrder as Jd,orderSyncLine as Qd,applyRelatedArticles as Zd,relatedSyncLine as ep}from"document360-engine";import{readFileSync as Qg}from"node:fs";import{resolve as Zg}from"node:path";import{prettyFolderName as Ku}from"document360-engine";var Wn=Ku;function zu(e){return e.replace(/\\/g,"/").split("/").slice(0,-1).join("/")}function Vi(e){let t=e.replace(/\\/g,"/").split("/").pop()??e;return Ku(t.replace(/\.md$/i,""))}function Xu(e,t){try{return/^#\s+(.+)$/m.exec(Qg(Zg(e,t),"utf8"))?.[1]?.trim()??null}catch{return null}}import ie from"picocolors";import Qi from"wrap-ansi";import Zi from"string-width";Q();import Ut from"picocolors";import Yi from"wrap-ansi";import Ki from"string-width";var Bn=[{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]",desc:"Write the planned articles in parallel (starts immediately; --preview shows plan + cost first; --rewrite regenerates already-written articles; --concurrency default 3)",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|--screenshots] [--skip-review]",desc:"Publish to Document360 (no arg: pick; --all: every candidate; --screenshots: re-save articles with captured shots so images embed). Blocked until each article has had /review --fix \u2014 AI-written text gets an editor first; --skip-review overrides deliberately",group:"publish"},{name:"check",usage:"/check [<category|path>] [--fix]",desc:"Check docs for leaked internals, invented commands, and stale facts (deterministic, no tokens). Scope to a category/path; --fix has the agent correct the findings in place",group:"docs"},{name:"review",usage:"/review [<category|path> | --all] [--fix]",desc:"Independent senior-editor review: style guide, terminology/voice, grammar/clarity, structure, improvement suggestions. Bare: pick a category or everything; --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]",desc:"Reviewer comments left on passages of your articles in the Document360 portal \u2014 bare: show what's open, then pick an article to handle; --answer: fix, push the draft, reply (threads stay open unless you add --resolve)",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"}],Ju={"/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"};function Qu(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(Ju[n])return Ju[n];let o=Bn.find(r=>r.name===t);return o?o.desc:""}function Zu(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return Bn.filter(n=>n.name.startsWith(t))}function ed(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}var ew=new RegExp(`^\\s*/(?:${Bn.map(e=>e.name).join("|")})(?:\\s|$)`),td=e=>ew.test(e),nd=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),od=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),rd=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function tw(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(nd(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&od(t[o+1])){let a=rd(r);o+=2;let u=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)u.push(rd(t[o++]));n.push({kind:"table",header:a,rows:u});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 u=t[o++];a.push({ordered:/^\s*\d+\.\s+/.test(u),text:u.replace(/^\s*([-*]|\d+\.)\s+/,"")})}n.push({kind:"list",items:a});continue}if(r.trim()===""){o++;continue}if(td(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])&&!td(t[o])&&!nd(t[o])&&!(t[o].includes("|")&&o+1<t.length&&od(t[o+1]));)i.push(t[o++]);n.push({kind:"para",text:i.join(" ")})}return n}function zi(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?Ut.bold(t.slice(2,-2)):t.startsWith("`")?q(t.slice(1,-1)):Ut.italic(t.slice(1,-1)))}var nw=(e,t)=>e+" ".repeat(Math.max(0,t-Ki(e)));function ow(e,t,n){let o=e.length,r=e.map((C,S)=>Math.max(Ki(C),...t.map(R=>Ki(R[S]??"")))),s=Math.max(24,n),i=3*o+1,a=[...r],u=()=>a.reduce((C,S)=>C+S,0)+i,h=0;for(;u()>s&&h++<1e4;){let C=-1,S=6;for(let R=0;R<o;R++)a[R]>S&&(S=a[R],C=R);if(C===-1)break;a[C]-=1}let g=(C,S,R)=>Ut.gray(C+a.map(N=>"\u2500".repeat(N+2)).join(S)+R),k=Ut.gray("\u2502"),x=(C,S)=>{let R=a.map((K,G)=>{let ae=C[G]??"",Ce=S?Ut.bold(ae):zi(ae);return Yi(Ce,K,{hard:!0}).split(`
|
|
307
|
+
`)}),N=Math.max(...R.map(K=>K.length)),V=[];for(let K=0;K<N;K++)V.push(a.map((G,ae)=>`${k} ${nw(R[ae][K]??"",G)} `).join("")+k);return V.join(`
|
|
308
308
|
`)},T=[g("\u250C","\u252C","\u2510"),x(e,!0)];return T.push(t.length===0?g("\u2514","\u2534","\u2518"):g("\u251C","\u253C","\u2524")),t.forEach((C,S)=>{T.push(x(C,!1)),T.push(S===t.length-1?g("\u2514","\u2534","\u2518"):g("\u251C","\u253C","\u2524"))}),T.join(`
|
|
309
|
-
`)}function
|
|
309
|
+
`)}function rw(e,t){switch(e.kind){case"heading":return Ut.bold(e.text);case"hr":return Ut.gray("\u2500".repeat(t));case"para":return Yi(zi(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]=Yi(zi(o.text),Math.max(10,t-s.length)).split(`
|
|
310
310
|
`);return` ${r} ${i}`+a.map(u=>`
|
|
311
311
|
${s}${u}`).join("")}).join(`
|
|
312
312
|
`)}case"code":return e.lines.map(n=>Ut.gray(" "+n)).join(`
|
|
313
|
-
`);case"table":return
|
|
313
|
+
`);case"table":return ow(e.header,e.rows,t)}}function Xi(e,t){let n=Math.max(20,t);return tw(e).map(o=>rw(o,n)).join(`
|
|
314
314
|
|
|
315
|
-
`)}Q();import
|
|
315
|
+
`)}Q();import sw from"picocolors";var iw=[127,86,217],aw=[22,38,43],sd={T:iw,E:aw},Do=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],Ji=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,lw=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function id(){if(!sw.isColorSupported)return[];let e=Do[0].length,t=[];for(let n=0;n<Do.length;n+=2){let o="";for(let r=0;r<e;r++){let s=sd[Do[n][r]],i=n+1<Do.length?sd[Do[n+1][r]]:void 0;s&&i?o+=`${Ji(s)}${lw(i)}\u2580\x1B[49m\x1B[39m`:s?o+=`${Ji(s)}\u2580\x1B[39m`:i?o+=`${Ji(i)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function No(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 jo(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function ld(e,t,n){let o=e>0&&e<=n?e:t;return Math.max(0,Math.floor((n-o)/1e3))}function We(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function Ft(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var Hn=(e,t)=>` ${e.padEnd(13)}${t}`;function cw(e,t){let n=[So("\u270E document360-writer")+ie.gray(` v${e.version} \xB7 engine v${e.engineVersion}${e.captureVersion?` \xB7 capture v${e.captureVersion}`:""}`),ie.gray(" Reads your code, writes your docs."),"",Hn("Claude:",`${e.claude}${ie.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),Hn("Document360:",e.configured?e.loggedOut?ie.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?ie.gray(` (${e.sessionHint})`):""}`:ie.yellow("not set up \u2014 run /init")),Hn("Profile:",e.configured?`${e.profile}${ie.gray(` (${e.apiUrl})`)}${e.prod?ie.bold(ie.yellow(" \u26A0 PRODUCTION")):""}`:ie.gray("\u2014 (run /init)")),Hn("Project:",e.project),Hn("Mode:",ie.gray(e.mode)),Hn("cwd:",ie.gray(e.cwd))],o=id();if(o.length===0)return n.join(`
|
|
316
316
|
`);let r=2,s=3,i=Zi(o[0]);if(!(t>=r+i+s+Math.max(...n.map(g=>Zi(g)))))return[...o.map(g=>" "+g),...n].join(`
|
|
317
317
|
`);let u=Math.max(0,Math.floor((n.length-o.length)/2)),h=[];for(let g=0;g<Math.max(o.length+u,n.length);g++){let k=o[g-u]??" ".repeat(i);h.push((" ".repeat(r)+k+" ".repeat(s)+(n[g]??"")).trimEnd())}return h.join(`
|
|
318
|
-
`)}var
|
|
318
|
+
`)}var uw={error:ie.red,warn:ie.yellow,ok:ie.green,info:ie.gray},ad=9;function ea(e){return e.length>=ad?`${e} `:e.padEnd(ad)}function ta(e){return e.replace(/^(\s*• |)([^\x00-\x7F][\u{1F000}-\u{1FAFF}️]*) (?=\S)/gmu,"$1$2 ")}function na(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return cw(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(`
|
|
319
319
|
`).flatMap(h=>Qi(h,s,{hard:!0}).split(`
|
|
320
320
|
`)),u=Math.max(0,a.length-i);return u>0&&(a=[...a.slice(0,i),ie.dim(`\u2026 +${u} more lines`)]),`
|
|
321
321
|
`+a.map((h,g)=>o+(g===0?q(" \u276F "):" ")+h+" ".repeat(Math.max(0,s-Zi(h))+1)+r).join(`
|
|
@@ -324,41 +324,41 @@ ${s}${u}`).join("")}).join(`
|
|
|
324
324
|
`+Qi(ie.gray("\u25CF ")+e.title+o,n)}case"doc":{let o=[e.category,e.note].filter(s=>!!s).map(s=>ie.gray(` \xB7 ${s}`)),r=e.loud?ie.gray(" \xB7 ")+ie.bold(ie.yellow(e.loud)):"";return`
|
|
325
325
|
`+Qi(ie.green("\u25CF ")+q(ie.bold(ea(e.verb)))+ie.bold(e.title)+o.join("")+r,n)}case"tool-result":{let o=e.isError?ie.red:ie.gray,r=e.lines.map((s,i)=>o((i===0?" \u23BF ":" ")+s));return e.hidden>0&&r.push(ie.dim(` \u2026 +${e.hidden} lines`)),r.join(`
|
|
326
326
|
`)}case"diff":{let o=i=>i===1?"":"s",s=[ie.gray(` \u23BF Added ${e.added} line${o(e.added)}, removed ${e.removed} line${o(e.removed)}`),...e.lines];return e.hidden>0&&s.push(ie.dim(` \u2026 +${e.hidden} more diff lines`)),s.join(`
|
|
327
|
-
`)}case"link":return e.lines.map(o=>q(
|
|
327
|
+
`)}case"link":return e.lines.map(o=>q(To(` \u2B95 ${o}`))).join(`
|
|
328
328
|
`);case"preview":return`
|
|
329
|
-
`+
|
|
329
|
+
`+So(`\u25A3 Preview \u2014 ${e.name}`)+`
|
|
330
330
|
|
|
331
331
|
`+Xi(e.text,n);case"note":return`
|
|
332
|
-
`+
|
|
333
|
-
`+(e.ok?ie.magenta("\u2736 "):ie.red("\u2736 "))+ie.gray(`Cooked for ${
|
|
334
|
-
`)}import{resolveActiveProfile as
|
|
335
|
-
`,"utf8")}function oa(e){return e&&/data-testid|\btest-?id\b|has(?:n't| not) landed/i.test(e)?"testid":"data"}function rs(e,t,n){if(t.length===0)return;let o=vt(e),r=os(e);for(let s of t){let i=s.specSource?
|
|
336
|
-
${a[1]??" "}clipTo: ${u}${i.selector}${u},`);return h=h.replace(o,`${r}await captureShot(page, PLACEHOLDER);`),h=h.replace(
|
|
332
|
+
`+uw[e.tone](To(ta(e.text)));case"done":{let o=e.inTokens&&e.inTokens>0?` \xB7 ${No(e.inTokens)} in${e.cachedPct!=null?` (${e.cachedPct}% cached)`:""}`:"";return`
|
|
333
|
+
`+(e.ok?ie.magenta("\u2736 "):ie.red("\u2736 "))+ie.gray(`Cooked for ${jo(e.seconds)} \xB7 ${No(e.tokens)} tokens out${o}`+(e.costUsd>0?` \xB7 ${We(e.costUsd)}`:""))}}}function cd(e,t){return e.map(n=>na(n,t)).join(`
|
|
334
|
+
`)}import{resolveActiveProfile as dw,loadTokens as pw,isExpired as hw,decodeJwtClaims as ud}from"document360-engine";function fw(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function Be(e,t){try{let n=dw(e,t),o=pw(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(hw(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={...ud(o.idToken)??{},...ud(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 ${fw(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}function pt(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 ns(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 aa,readFileSync as ga}from"node:fs";import{isAbsolute as cs,join as us,resolve as ds}from"node:path";import A from"picocolors";import is from"string-width";import{readProjectConfig as Bt,screenshotPlaceholderIds as Ad,DEFAULT_CAPTURE_DIR as ps,DEFAULT_OUTPUT_DIR as wa,DEFAULT_DOCS_DIR as ya,existingAnnotatedShotPath as Lw,resolveOutputDir as Dd,migrateShotLayout as _w,reviewIsCurrent as Mw,shotImageMtimeMs as Uw,anchorPresent as Fw,RAW_SUBDIR as Ww,ANNOTATED_SUBDIR as Bw}from"document360-engine";import{createHash as pd}from"node:crypto";import{readFileSync as hd,writeFileSync as mw}from"node:fs";import{join as gw}from"node:path";import{captureStatePath as fd}from"document360-engine";var dd={version:1,shots:{}};function md(e){return pd("sha1").update(e).digest("hex").slice(0,12)}function os(e){try{let t=JSON.parse(hd(gw(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 pd("sha1").update(`${o}|${r?.connection?.startUrl??""}|${i}`).digest("hex").slice(0,12)}catch{return null}}function vt(e){try{let t=JSON.parse(hd(fd(e),"utf8").replace(/^/,""));return!t||typeof t!="object"||t.version!==1||!t.shots?{...dd,shots:{}}:{version:1,shots:t.shots}}catch{return{...dd,shots:{}}}}function ww(e,t){mw(fd(e),`${JSON.stringify(t,null,2)}
|
|
335
|
+
`,"utf8")}function oa(e){return e&&/data-testid|\btest-?id\b|has(?:n't| not) landed/i.test(e)?"testid":"data"}function rs(e,t,n){if(t.length===0)return;let o=vt(e),r=os(e);for(let s of t){let i=s.specSource?md(s.specSource):void 0;o.shots[s.id]={outcome:s.outcome,at:n,...s.reason?{reason:s.reason}:{},...s.outcome==="skipped"?{blockedBy:oa(s.reason)}:{},...i?{specHash:i}:{},...r?{envHash:r}:{}}}ww(e,o)}function ra(e,t,n,o){let r=e.shots[t];return!r||n===null||!r.specHash||r.specHash!==md(n)||o&&r.envHash&&r.envHash!==o?null:r}function gd(e){let t=vt(e).shots;return Object.keys(t).filter(n=>t[n].outcome==="failed").sort()}function sa(e,t,n){let o=ra(vt(e),t,n,os(e));return!o||o.outcome==="captured"||!o.reason?null:{outcome:o.outcome,reason:o.reason}}Io();import{existsSync as vw,readFileSync as bd,readdirSync as $d,writeFileSync as xw}from"node:fs";import{isAbsolute as Cw,join as vd,resolve as Rw}from"node:path";import{readProjectConfig as Sw,DEFAULT_CAPTURE_DIR as Pw}from"document360-engine";var kd="0.2.25";function ss(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 Tw=/^([ \t]*)await\s+([^\n;]+?)\.screenshot\(\{\s*path:\s*PLACEHOLDER\.saveTo\s*(?:,\s*fullPage:\s*(?:true|false)\s*)?,?\s*\}\)\s*;?[ \t]*$/m,Ew=/^[ \t]*await\s+dumpAnnotations\(\s*page\s*,\s*PLACEHOLDER\s*\)\s*;?[ \t]*\r?\n?/m,xd="(?:'([^']+)'|\"([^\"]+)\"|`([^`]+)`)",Aw=new RegExp(`^page\\s*\\.\\s*locator\\(\\s*${xd}\\s*\\)$`),Cd=e=>e[1]??e[2]??e[3]??null,Dw=/^[A-Za-z_$][\w$]*$/;function Nw(e,t){let o=new RegExp(`\\bconst\\s+${t}\\s*=\\s*page\\s*\\.\\s*locator\\(\\s*${xd}\\s*\\)\\s*;`).exec(e);return o?Cd(o):null}function jw(e,t){let n=t.trim();if(n==="page")return null;let o=Aw.exec(n);if(o){let r=Cd(o);return r?{selector:r}:{unresolved:!0}}if(Dw.test(n)){let r=Nw(e,n);return r?{selector:r}:{unresolved:!0}}return{unresolved:!0}}function Rd(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=Tw.exec(e);if(!n)return null;let[o,r="",s=""]=n,i=jw(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 u=i.selector.includes("'")?'"':"'",h=e.replace(a[0],`${a[0]}
|
|
336
|
+
${a[1]??" "}clipTo: ${u}${i.selector}${u},`);return h=h.replace(o,`${r}await captureShot(page, PLACEHOLDER);`),h=h.replace(Ew,""),h=h.replace(/\bdumpAnnotations\b(?=[^\n]*from 'document360-capture\/helpers')/,"captureShot"),/from 'document360-capture\/helpers'/.test(h)&&!/\bcaptureShot\b[^\n]*from 'document360-capture\/helpers'/.test(h)&&(h=h.replace(/import \{([^}]*)\} from 'document360-capture\/helpers'/,(g,k)=>`import {${k.replace(/\s*$/,"")}, captureShot } from 'document360-capture/helpers'`)),{next:h,selector:i.selector}}function Iw(e){try{return $d(e).filter(t=>t.endsWith(".spec.ts")).some(t=>{try{let n=Rd(bd(vd(e,t),"utf8"));return n!==null&&!("unresolved"in n)}catch{return!1}})}catch{return!1}}function Ow(e){let t=Sw(e)?.captureDir??Pw;return Cw(t)?t:Rw(e,t)}function Sd(e,t){let n={migrated:[],skipped:[]},o=Ow(e);if(!vw(o))return n;let r=t?.captureVersion===void 0?xt():t.captureVersion;if(!ss(r,kd))return Iw(o)?{...n,heldBackForCapture:{installed:r,required:kd}}:n;let s;try{s=$d(o).filter(i=>i.endsWith(".spec.ts"))}catch{return n}for(let i of s.sort()){let a=i.slice(0,-8),u=vd(o,i);try{let h=bd(u,"utf8"),g=Rd(h);if(g===null)continue;if("unresolved"in g){n.skipped.push({id:a,receiver:g.unresolved});continue}xw(u,g.next,"utf8"),n.migrated.push(a)}catch{}}return n}function Pd(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.
|
|
337
337
|
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(`
|
|
338
|
-
`)}
|
|
339
|
-
`):null}function pn(e,t){let n=Bt(e)?.captureDir??ps,o=cs(n)?us(n,`${t}.spec.ts`):ds(e,n,`${t}.spec.ts`);try{return ga(o,"utf8")}catch{return null}}function
|
|
340
|
-
`))||o.push(r+1));return o}function ca(e){let t=[],n=
|
|
338
|
+
`)}Io();var Nd=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Td(e){let t=e.includes("--detail")||e.includes("-d"),n=e.find(o=>o!=="--detail"&&o!=="-d");return{mode:"list",scope:n?Nd(n):void 0,...t?{detail:!0}:{}}}function Oo(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 Td(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 Td(o.slice(1));let r=o[0];return r?r==="--all"?{mode:"all",setup:n}:/[\\/]/.test(r)||r.endsWith(".md")?{mode:"scope",scope:Nd(r),setup:n}:{mode:"single",id:r}:{mode:"list",picker:!0}}function Ae(e,t,n){let o=Bt(e),r=o?.captureDir??ps,s=o?.outputDir??wa,i=(k,x)=>cs(k)?us(k,x):ds(e,k,x),a=vt(e),u=n?.captureVersion===void 0?xt():n.captureVersion,h=ss(u,Ld),g=os(e);return Ad(e,{scope:t}).map(({id:k,file:x})=>{let T=i(r,`${k}.spec.ts`),C=null;if(aa(T))try{C=ga(T,"utf8")}catch{}let S=Dd(e,s),R=aa(Lw(S,k)),N=C===null?null:ra(a,k,C,g),V=a.shots[k]?.review,K=R&&Mw(V,Uw(S,k))?V:void 0,G=C!==null&&Gw(C),ae=R&&K?.verdict==="ok"?"verified":R&&K?.verdict==="rejected"?"rejected":R?"captured":C===null?"placeholder":G||N?.outcome==="skipped"?"blocked":N?.outcome==="failed"?"broken":"spec",Ce=C===null?void 0:Id(C),ke=G?Yw(C):N?.reason,De=G?"testid":N?.outcome==="skipped"?oa(N.reason):void 0,be=C===null?[]:Vw(e,C);return{id:k,file:x,state:ae,...Ce?{mutates:Ce.mutates,...Ce.declared?{}:{undeclared:!0}}:{},...C!==null&&ca(C).length>0?{unguardedWaits:ca(C)}:{},...C!==null&&la(C).length>0?{unverifiedForce:la(C)}:{},...C!==null&&ua(C).length>0?{handRolled:ua(C)}:{},...C!==null&&pa(C).length>0?{stalePause:pa(C)}:{},...C!==null&&h&&da(C).length>0?{bareGoto:da(C)}:{},...be.length>0?{staleAnchor:be}:{},...ae==="blocked"||ae==="broken"?{...ke?{reason:ke}:{},...De?{blockedBy:De}:{}}:{},...ae==="rejected"?{...K?.reason?{reason:K.reason}:{},...K?.repaired?{repaired:!0}:{}}:{}}})}function Hw(e){let t=Bt(e)?.outputDir??wa;return _w(Dd(e,t))}function Lo(e){let t=Hw(e),n=Bt(e)?.outputDir??wa,o=[];t>0&&o.push(`\u2195 Tidied ${t} screenshot file${t===1?"":"s"} into ${n}/{${Ww},${Bw}} \u2014 annotated/ is what publishes, raw/ is the pre-annotation intermediate.`);let r=Pd(Sd(e));return r&&o.push(r),o.length>0?o.join(`
|
|
339
|
+
`):null}function pn(e,t){let n=Bt(e)?.captureDir??ps,o=cs(n)?us(n,`${t}.spec.ts`):ds(e,n,`${t}.spec.ts`);try{return ga(o,"utf8")}catch{return null}}function jd(e,t){let n=Bt(e)?.captureDir??ps;return aa(cs(n)?us(n,`${t}.spec.ts`):ds(e,n,`${t}.spec.ts`))}function qw(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 Id(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=qw(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 Gw(e){return/(^|\n)\s*test\.skip\s*\(\s*['"`]/.test(e)}function Od(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 Vw(e,t){let n=[];for(let o of Od(t))Fw(e,o.file,o.anchor)===!1&&n.push(o.testid??o.file??"unnamed request");return[...new Set(n)]}function Yw(e){let{testid:t,file:n}=Od(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 _o(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 la(e,t=10){let n=_o(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(`
|
|
340
|
+
`))||o.push(r+1));return o}function ca(e){let t=[],n=_o(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 ua(e){let t=[];for(let[n,o]of _o(e).entries())(/\.screenshot\s*\(/.test(o)||/\bdumpAnnotations\s*\(/.test(o))&&t.push(n+1);return t}var Ld="0.2.28";function da(e){let t=[];for(let[n,o]of _o(e).entries())/\.goto\s*\(/.test(o)&&t.push(n+1);return t}function pa(e,t=6){let n=_o(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(`
|
|
341
341
|
`);if(!/test\.skip\s*\(/.test(i)||!/\.count\s*\(\s*\)/.test(i))continue;let a=n.slice(Math.max(0,r-t),r+1).join(`
|
|
342
|
-
`);/\.waitFor\s*\(|Promise\.race\s*\(|waitForFunction\s*\(|waitForSelector\s*\(/.test(a)||o.push(r+1)}return o}function ka(e,t){let n=g=>`line${g.length===1?"":"s"} ${g.join(", ")}`,o=[],r=t?.captureVersion===void 0?xt():t.captureVersion,s=ss(r,
|
|
343
|
-
`)}var zw={placeholder:"\u25CB",spec:"\u25D0",blocked:"\u2298",broken:"\u2717",captured:"\u25CF",verified:"\u2714",rejected:"\u2691"},Xw={placeholder:A.gray,spec:A.yellow,blocked:A.cyan,broken:A.red,captured:A.blue,verified:A.green,rejected:A.magenta},Jw=` ${A.green("\u2714 verified")} ${A.blue("\u25CF to verify")} ${A.yellow("\u25D0 ready")} ${A.magenta("\u2691 rejected")} ${A.cyan("\u2298 blocked")} ${A.red("\u2717 broken")} ${A.gray("\u25CB to spec")}`;function oe(e,t=n=>n){return`${t(e)} `}function qn(e){return e.replace(/\s+/g," ").trim().replace(/^Prerequisites? not met[:—-]?\s*/i,"")}function ms(e){let t=qn(e),n=/^(.*?[a-z0-9)"'”’])\.(?:\s|$)/i.exec(t);return(n?n[1]:t).trim()}function _o(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=ms(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 Ud(e){let t=_o(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,u)=>a+u.ids.length,0);r.push(` ${A.bold("Stage this data")} ${A.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 u=Lt(a.reason,86);r.push(` ${A.cyan(Wt(`${a.ids.length}\xD7`,4))} ${u[0]??""}`);for(let g of u.slice(1))r.push(` ${g}`);let h=a.ids.slice(0,4).join(" \xB7 ");r.push(A.gray(` ${h}${a.ids.length>4?` \xB7 +${a.ids.length-4} more`:""}`))}n.length>i&&r.push(A.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(` ${oe("\u2298",A.cyan)}${s} shot${s===1?"":"s"} need${s===1?"s":""} a data-testid from your developers \u2014 ${A.bold("/screenshot checklist")} builds the hand-off.`)}return r}function Fd(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=["",` ${oe("\u26A0",A.yellow)}${r} selector request${r===1?"":"s"} quote${r===1?"s":""} source code that has since changed`+A.gray(" \u2014 your developers would go looking for something that isn't there any more"),A.gray(` Refresh the hand-off before sending it: ${A.bold("/screenshot checklist")}`)];return t&&s.push(A.gray(` ${o.slice(0,8).join(" \xB7 ")}${r>8?` \xB7 +${r-8} more`:""}`)),s}function Wd(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 u=["",` ${oe("\u26A0",A.yellow)}Some specs were written before later reliability fixes:`],h=(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;u.push(A.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&&u.push(A.gray(h(o,k=>`${k.id}:${k.unguardedWaits.join(",")}`)))}if(a.length>0){let g=a.length;u.push(A.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&&u.push(A.gray(h(a,k=>`${k.id}:${k.bareGoto.join(",")}`)))}if(i.length>0){let g=i.length;u.push(A.gray(` ${g} decide${g===1?"s":""} "the data is missing" from a fixed pause, so data you HAVE staged can read as absent`)),t&&u.push(A.gray(h(i,k=>`${k.id}:${k.stalePause.join(",")}`)))}if(s.length>0){let g=s.length;u.push(A.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&&u.push(A.gray(h(s,k=>`${k.id}:${k.handRolled.join(",")}`)))}if(r.length>0){let g=r.length,k=r.filter(x=>x.mutates).length;u.push(A.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&&u.push(A.gray(h(r,x=>x.id)))}return n?.commandInLead||u.push(A.gray(` Re-write them all with the current rules: ${A.bold("/screenshot author --all")}`)),u}function Bd(e){let t=e.filter(n=>(n.unverifiedForce?.length??0)>0);return t.length===0?[]:["",` ${oe("\u26A0",A.red)}${t.length} spec${t.length===1?"":"s"} force-click past Playwright's safety checks without asserting the result`+A.gray(" \u2014 if the click lands on nothing, the shot photographs the unchanged screen"),A.gray(` ${t.slice(0,6).map(n=>`${n.id}:${n.unverifiedForce.join(",")}`).join(" \xB7 ")}${t.length>6?` \xB7 +${t.length-6} more`:""}`),A.gray(` Re-author to check what the click did: ${A.bold("/screenshot author <id>")}`)]}var as=(e,t)=>e.length>=t?e:e+" ".repeat(t-e.length),Wt=(e,t)=>e.length>=t?e:" ".repeat(t-e.length)+e;function Hd(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 Qw=new Set(["and","or","of","the","to","a","an","in","on","for","with","vs"]),Zw=new Set(["ai","api","cli","ui","ux","url","id","http","https","json","xml","sdk","csv","pdf","oauth","sso","mfa","io","faq"]);function ey(e){return e.replace(/[-_]+/g," ").trim().split(/\s+/).filter(Boolean).map((n,o)=>{let r=n.toLowerCase();return Zw.has(r)?r.toUpperCase():o>0&&Qw.has(r)?r:r.charAt(0).toUpperCase()+r.slice(1)}).join(" ")}function ha(e){if(!e)return{num:"",name:"(docs root)"};let t=/^(\d+)[-_](.+)$/.exec(e);return{num:t?t[1]:"",name:ey(t?t[2]:e)}}function ty(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).pop()??e}function Td(e,t,n){let o=t>0?Math.round(e/t*n):0;return A.green("\u2588".repeat(o))+A.gray("\u2591".repeat(Math.max(0,n-o)))}function ny(e,t){let n=t>0?Math.round(e/t*100):0,o=Wt(`${n}%`,4);return n===100?A.green(o):n>0?A.yellow(o):A.gray(o)}function qd(e,t){let n=new Map;for(let o of e){let r=Hd(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 oy(e,t){let n=(z,pe)=>z.filter(le=>le.state===pe).length,o=e.length,r=n(e,"verified"),s=n(e,"captured"),i=n(e,"rejected"),a=n(e,"spec"),u=n(e,"blocked"),h=n(e,"broken"),g=n(e,"placeholder"),k=new Set(e.map(z=>z.file)).size,x=qd(e,t),T=[];T.push(` ${A.bold("Screenshots")} ${A.green(`${r}/${o} verified`)} ${A.gray("\xB7")} ${s>0?A.blue(`${s} to verify`):A.gray("0 to verify")}`+(i>0?` ${A.gray("\xB7")} ${A.magenta(`${i} rejected`)}`:"")+` ${A.gray("\xB7")} ${a>0?A.yellow(`${a} ready`):A.gray("0 ready")}`+(u>0?` ${A.gray("\xB7")} ${A.cyan(`${u} blocked`)}`:"")+(h>0?` ${A.gray("\xB7")} ${A.red(`${h} broken`)}`:"")+` ${A.gray("\xB7")} ${g>0?A.red(`${g} to spec`):A.gray("0 to spec")} `+A.gray(`across ${k} article${k===1?"":"s"}`));let C=o>0?Math.round(r/o*100):0;T.push(` [${Td(r,o,32)}] ${A.bold(`${C}%`)}`),T.push("");let S=x.map(([z])=>ha(z)),R=Math.min(32,Math.max(7,...S.map(z=>z.name.length))),N=z=>z.length>R?`${z.slice(0,R-1)}\u2026`:as(z,R),V=[...s>0?[{head:"To verify",w:9,state:"captured",color:A.blue}]:[],...i>0?[{head:"Rejected",w:8,state:"rejected",color:A.magenta}]:[],{head:"Ready",w:5,state:"spec",color:A.yellow},...u>0?[{head:"Blocked",w:7,state:"blocked",color:A.cyan}]:[],...h>0?[{head:"Broken",w:6,state:"broken",color:A.red}]:[],{head:"To spec",w:7,state:"placeholder",color:A.red}];T.push(A.gray(` ${as("#",2)} ${as("Chapter",R)} ${Wt("Verified",8)} ${V.map(z=>Wt(z.head,z.w)).join(" ")} Progress`));for(let[z,[,pe]]of x.entries()){let le=n(pe,"verified"),Se=pe.length,{num:Pe,name:Qe}=S[z],Ct=le===Se,Yt=N(Qe),fr=V.map(at=>{let mr=n(pe,at.state);return mr>0?at.color(Wt(String(mr),at.w)):A.gray(Wt("\u2014",at.w))}).join(" ");T.push(` ${A.cyan(as(Pe,2))} ${Ct?A.green(Yt):le>0?Yt:A.gray(Yt)} ${Ct?A.green(Wt(`${le}/${Se}`,8)):Wt(`${le}/${Se}`,8)} ${fr} ${Td(le,Se,10)} ${ny(le,Se)}`)}T.push("");let K=h>0?` ${A.gray("\xB7")} ${h} spec${h===1?"":"s"} broken \u2014 ${A.bold(`/screenshot ${e.find(z=>z.state==="broken").id}`)} re-authors ${h===1?"it":"the first"}`:"",G=e.filter(z=>z.state==="spec"&&z.mutates).length,ae=a>G,Ce=e.filter(z=>(z.unguardedWaits?.length??0)>0||(z.bareGoto?.length??0)>0).length,ke=e.filter(z=>(z.stalePause?.length??0)>0||(z.handRolled?.length??0)>0).length,De=a>0||u>0||h>0,be=!1;if(g>0)T.push(` ${oe("\u2192",A.yellow)}${g} placeholder${g===1?"":"s"} still need a spec \u2014 run ${A.bold("/screenshot author --all")}${K}`);else if(Ce>0&&De)be=!0,T.push(` ${oe("\u2192",A.yellow)}${Ce} spec${Ce===1?"":"s"} would crash mid-run \u2014 re-write ${Ce===1?"it":"them"} first: ${A.bold("/screenshot author --all")}`+A.gray(` \xB7 then ${A.bold("/screenshot capture")} (no browser time wasted on ${Ce===1?"a shot":"shots"} that can't finish)`)+K);else if(ke>0&&De)be=!0,T.push(` ${oe("\u2192",A.yellow)}${ke} spec${ke===1?"":"s"} would shoot the wrong thing \u2014 re-write ${ke===1?"it":"them"} first: ${A.bold("/screenshot author --all")}`+A.gray(` \xB7 then ${A.bold("/screenshot capture")} (a false skip or a misplaced callout costs the same browser time as a good shot)`)+K);else if(a>0&&(ae||s===0)){let z=G>0?A.gray(` \u2014 ${a-G} in one go; ${G} write${G===1?"s":""} real data and run${G===1?"s":""} one at a time`):"";T.push(` ${oe("\u2192",A.yellow)}${a} spec${a===1?"":"s"} ready to capture \u2014 run ${A.bold("/screenshot capture")}${z}${K}`)}else if(s>0&&a>0)T.push(` ${oe("\u2192",A.blue)}${s} shot${s===1?"":"s"} awaiting verification \u2014 run ${A.bold("/screenshot verify")}`+A.gray(" \u2014 no browser needed")+A.gray(` \xB7 ${a} ready spec${a===1?"":"s"} write real data, so ${a===1?"it runs":"each runs"} only when named: /screenshot capture <id>`)+K);else if(u>0)T.push(` ${oe("\u2192",A.cyan)}${u} shot${u===1?"":"s"} blocked \u2014 stage the data below, then ${A.bold("/screenshot capture --blocked")}${K}`);else if(h>0)T.push(` ${oe("\u2192",A.red)}${h} spec${h===1?"":"s"} broken \u2014 ${A.bold(`/screenshot ${e.find(z=>z.state==="broken").id}`)} re-authors ${h===1?"it":"the first"} (re-capturing fails the same way)`);else if(s>0)T.push(` ${oe("\u2192",A.blue)}${s} shot${s===1?"":"s"} awaiting verification \u2014 run ${A.bold("/screenshot verify")}`+A.gray(" \u2014 it checks each picture against what its article needs (no browser, no re-capture)"));else if(i>0){let z=e.filter(pe=>pe.state==="rejected"&&pe.repaired).length;T.push(` ${oe("\u2691",A.magenta)}${i} shot${i===1?"":"s"} failed review \u2014 `+(z>0?`${z} spec${z===1?"":"s"} already repaired; re-capture with ${A.bold("/screenshot capture --failed")}`:`see the reasons below, then ${A.bold("/screenshot capture --failed")}`))}else T.push(` ${oe("\u2713",A.green)}all ${o} verified \u2014 ${A.bold("/publish")} embeds them in the articles`);if(r>0&&r<o){let z=x.filter(([,pe])=>pe.every(le=>le.state!=="verified")).map(([pe])=>{let{num:le,name:Se}=ha(pe);return le?`${le} ${Se}`:Se});z.length>0&&T.push(A.gray(` Furthest behind: ${z.slice(0,5).join(" \xB7 ")}${z.length>5?" \u2026":""} (0% verified)`))}return T.push(...Ud(e),...Bd(e),...Wd(e,!1,{commandInLead:be}),...Fd(e,!1)),T.push(""),T.push(A.gray(" Drill in: /screenshot list <chapter#> \xB7 /screenshot list --detail (all)")),T}function ry(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=[` ${A.bold("Screenshots")}: ${e.length} placeholder${e.length===1?"":"s"} across ${o.size} article${o.size===1?"":"s"} \xB7 ${A.green(`${r} verified`)}${s>0?A.blue(` \xB7 ${s} to verify`):""}${n?A.gray(` \xB7 scope ${n}`):""}`,""];for(let[a,u]of qd(e,t)){let h=u.filter(C=>C.state==="verified").length,{num:g,name:k}=ha(a),x=g?`${g} \xB7 ${k}`:k;i.push(` ${A.bold(x)} ${A.gray(`(${h}/${u.length})`)}`);let T=new Map;for(let C of u){let S=ty(C.file),R=T.get(S)??[];T.has(S)||T.set(S,R),R.push(C)}for(let C of[...T.keys()].sort()){i.push(A.gray(` ${C}`));for(let S of T.get(C)){let R=Xw[S.state];if(i.push(` ${oe(zw[S.state],R)}${R(S.id)}`),(S.state==="blocked"||S.state==="broken"||S.state==="rejected")&&S.reason){for(let N of Lt(qn(S.reason),84))i.push(A.gray(` ${N}`));S.state==="rejected"&&i.push(A.gray(` ${S.repaired?"spec repaired \u2014 re-capture to confirm":"spec not yet repaired"}`))}}}}return i.push(...Ud(e),...Bd(e),...Wd(e,!0),...Fd(e,!0)),i.push("",Jw),i}function gs(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??ya;return t?.detail||n?ry(e,o,n):oy(e,o)}function ba(e,t){if(!t||!/^\d+$/.test(t))return t;let n=Bt(e)?.docsDir??ya,o=String(Number(t));for(let{file:r}of Ed(e)){let s=Hd(r,n),i=/^(\d+)/.exec(s);if(i&&String(Number(i[1]))===o)return s}return t}function Gd(e,t){let r=e.map(a=>" ".repeat(a.depth)+a.label),s=Math.max(0,...e.map((a,u)=>a.note?is(r[u]):0)),i=Math.min(s,Math.max(0,t-2-24));return e.map((a,u)=>{let h=r[u];if(!a.note)return{head:h,note:""};let g=Math.max(2,i+2-is(h)),k=a.note.trim(),x=t-is(h)-g;return{head:h+" ".repeat(g),note:x>1&&is(k)>x?`${k.slice(0,x-1)}\u2026`:k}})}function sy(e){let t=e.replace(/\\/g,"/").split("/").filter(Boolean),n=t.pop()??e;return{category:t.pop()??"(docs root)",article:n}}function ls(e,t,n){let o=new Map;for(let s of t){let{category:i,article:a}=sy(s.file),u=o.get(i)??new Map;o.set(i,u);let h=u.get(a)??[];u.set(a,h),h.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(h=>h.id),u=a.length>0;u&&e.push({kind:"category",action:n,label:`${s} (${a.length})`,ids:a,depth:1});for(let h of[...i.keys()].sort()){let g=i.get(h),k=g.filter(r).map(C=>C.id),x=k.length>0;x&&e.push({kind:"article",action:n,label:`${h} (${k.length})`,ids:k,depth:u?2:1});let T=(u?1:0)+(x?1:0)+1;for(let C of g){let S=n==="capture"&&C.mutates?" \u26A0 creates real data \u2014 runs only alone":void 0;e.push({kind:"shot",action:n,label:C.id,ids:[C.id],depth:T,...S?{note:S}:{}})}}}}function ia(e){return e?qn(e):""}function $a(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,u)=>a.id.localeCompare(u.id)))e.push({kind:"shot",action:"capture",label:i.id,ids:[i.id],depth:1,note:` \u2298 ${ia(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,u)=>a.id.localeCompare(u.id)))e.push({kind:"shot",action:"author",label:i.id,ids:[i.id],depth:1,note:` \u2717 re-authors \u2014 ${ia(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,u)=>a.id.localeCompare(u.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 ${ia(i.reason)}`})}}function Vd(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}),ls(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}),ls(o,n,"capture"),$a(o,e.filter(s=>s.state==="blocked"),e.filter(s=>s.state==="broken"),e.filter(s=>s.state==="rejected")),o}var fa=["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(`
|
|
344
|
-
`);function
|
|
345
|
-
`),"",...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(u=>
|
|
346
|
-
`)}async function ws(e,t,n){let o=
|
|
342
|
+
`);/\.waitFor\s*\(|Promise\.race\s*\(|waitForFunction\s*\(|waitForSelector\s*\(/.test(a)||o.push(r+1)}return o}function ka(e,t){let n=g=>`line${g.length===1?"":"s"} ${g.join(", ")}`,o=[],r=t?.captureVersion===void 0?xt():t.captureVersion,s=ss(r,Ld)?da(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=ca(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=ua(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 u=pa(e);u.length>0&&o.push(`- ${n(u)}: 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 h=la(e);return h.length>0&&o.push(`- ${n(h)}: 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 _d(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 Md(e){return(e??"").trim().replace(/[.\s]+$/,"")}function Ud(e,t){let n=Bt(e)?.captureDir??ps,o=cs(n)?us(n,`${t}.spec.ts`):ds(e,n,`${t}.spec.ts`);try{return Id(ga(o,"utf8"))}catch{return{mutates:!1,declared:!1}}}var Kw=["captured","verified","rejected"],zw=e=>Kw.includes(e);function hs(e){return[...new Set(e.filter(t=>zw(t.state)).map(t=>t.file))].sort()}function fs(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[`${oe("\u26A0",A.yellow)}${t.length} screenshot${t.length===1?"":"s"} failed verification:`,...t.map(o=>` ${A.magenta(o.id.padEnd(n))} ${A.gray(qn(o.reason??"no reason recorded"))}`),` Publishing anyway. Fix + re-capture: ${A.bold("/screenshot capture --failed")}`].join(`
|
|
343
|
+
`)}var Xw={placeholder:"\u25CB",spec:"\u25D0",blocked:"\u2298",broken:"\u2717",captured:"\u25CF",verified:"\u2714",rejected:"\u2691"},Jw={placeholder:A.gray,spec:A.yellow,blocked:A.cyan,broken:A.red,captured:A.blue,verified:A.green,rejected:A.magenta},Qw=` ${A.green("\u2714 verified")} ${A.blue("\u25CF to verify")} ${A.yellow("\u25D0 ready")} ${A.magenta("\u2691 rejected")} ${A.cyan("\u2298 blocked")} ${A.red("\u2717 broken")} ${A.gray("\u25CB to spec")}`;function oe(e,t=n=>n){return`${t(e)} `}function qn(e){return e.replace(/\s+/g," ").trim().replace(/^Prerequisites? not met[:—-]?\s*/i,"")}function ms(e){let t=qn(e),n=/^(.*?[a-z0-9)"'”’])\.(?:\s|$)/i.exec(t);return(n?n[1]:t).trim()}function Mo(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=ms(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 Fd(e){let t=Mo(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,u)=>a+u.ids.length,0);r.push(` ${A.bold("Stage this data")} ${A.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 u=Lt(a.reason,86);r.push(` ${A.cyan(Wt(`${a.ids.length}\xD7`,4))} ${u[0]??""}`);for(let g of u.slice(1))r.push(` ${g}`);let h=a.ids.slice(0,4).join(" \xB7 ");r.push(A.gray(` ${h}${a.ids.length>4?` \xB7 +${a.ids.length-4} more`:""}`))}n.length>i&&r.push(A.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(` ${oe("\u2298",A.cyan)}${s} shot${s===1?"":"s"} need${s===1?"s":""} a data-testid from your developers \u2014 ${A.bold("/screenshot checklist")} builds the hand-off.`)}return r}function Wd(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=["",` ${oe("\u26A0",A.yellow)}${r} selector request${r===1?"":"s"} quote${r===1?"s":""} source code that has since changed`+A.gray(" \u2014 your developers would go looking for something that isn't there any more"),A.gray(` Refresh the hand-off before sending it: ${A.bold("/screenshot checklist")}`)];return t&&s.push(A.gray(` ${o.slice(0,8).join(" \xB7 ")}${r>8?` \xB7 +${r-8} more`:""}`)),s}function Bd(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 u=["",` ${oe("\u26A0",A.yellow)}Some specs were written before later reliability fixes:`],h=(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;u.push(A.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&&u.push(A.gray(h(o,k=>`${k.id}:${k.unguardedWaits.join(",")}`)))}if(a.length>0){let g=a.length;u.push(A.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&&u.push(A.gray(h(a,k=>`${k.id}:${k.bareGoto.join(",")}`)))}if(i.length>0){let g=i.length;u.push(A.gray(` ${g} decide${g===1?"s":""} "the data is missing" from a fixed pause, so data you HAVE staged can read as absent`)),t&&u.push(A.gray(h(i,k=>`${k.id}:${k.stalePause.join(",")}`)))}if(s.length>0){let g=s.length;u.push(A.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&&u.push(A.gray(h(s,k=>`${k.id}:${k.handRolled.join(",")}`)))}if(r.length>0){let g=r.length,k=r.filter(x=>x.mutates).length;u.push(A.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&&u.push(A.gray(h(r,x=>x.id)))}return n?.commandInLead||u.push(A.gray(` Re-write them all with the current rules: ${A.bold("/screenshot author --all")}`)),u}function Hd(e){let t=e.filter(n=>(n.unverifiedForce?.length??0)>0);return t.length===0?[]:["",` ${oe("\u26A0",A.red)}${t.length} spec${t.length===1?"":"s"} force-click past Playwright's safety checks without asserting the result`+A.gray(" \u2014 if the click lands on nothing, the shot photographs the unchanged screen"),A.gray(` ${t.slice(0,6).map(n=>`${n.id}:${n.unverifiedForce.join(",")}`).join(" \xB7 ")}${t.length>6?` \xB7 +${t.length-6} more`:""}`),A.gray(` Re-author to check what the click did: ${A.bold("/screenshot author <id>")}`)]}var as=(e,t)=>e.length>=t?e:e+" ".repeat(t-e.length),Wt=(e,t)=>e.length>=t?e:" ".repeat(t-e.length)+e;function qd(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 Zw=new Set(["and","or","of","the","to","a","an","in","on","for","with","vs"]),ey=new Set(["ai","api","cli","ui","ux","url","id","http","https","json","xml","sdk","csv","pdf","oauth","sso","mfa","io","faq"]);function ty(e){return e.replace(/[-_]+/g," ").trim().split(/\s+/).filter(Boolean).map((n,o)=>{let r=n.toLowerCase();return ey.has(r)?r.toUpperCase():o>0&&Zw.has(r)?r:r.charAt(0).toUpperCase()+r.slice(1)}).join(" ")}function ha(e){if(!e)return{num:"",name:"(docs root)"};let t=/^(\d+)[-_](.+)$/.exec(e);return{num:t?t[1]:"",name:ty(t?t[2]:e)}}function ny(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).pop()??e}function Ed(e,t,n){let o=t>0?Math.round(e/t*n):0;return A.green("\u2588".repeat(o))+A.gray("\u2591".repeat(Math.max(0,n-o)))}function oy(e,t){let n=t>0?Math.round(e/t*100):0,o=Wt(`${n}%`,4);return n===100?A.green(o):n>0?A.yellow(o):A.gray(o)}function Gd(e,t){let n=new Map;for(let o of e){let r=qd(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 ry(e,t){let n=(z,pe)=>z.filter(le=>le.state===pe).length,o=e.length,r=n(e,"verified"),s=n(e,"captured"),i=n(e,"rejected"),a=n(e,"spec"),u=n(e,"blocked"),h=n(e,"broken"),g=n(e,"placeholder"),k=new Set(e.map(z=>z.file)).size,x=Gd(e,t),T=[];T.push(` ${A.bold("Screenshots")} ${A.green(`${r}/${o} verified`)} ${A.gray("\xB7")} ${s>0?A.blue(`${s} to verify`):A.gray("0 to verify")}`+(i>0?` ${A.gray("\xB7")} ${A.magenta(`${i} rejected`)}`:"")+` ${A.gray("\xB7")} ${a>0?A.yellow(`${a} ready`):A.gray("0 ready")}`+(u>0?` ${A.gray("\xB7")} ${A.cyan(`${u} blocked`)}`:"")+(h>0?` ${A.gray("\xB7")} ${A.red(`${h} broken`)}`:"")+` ${A.gray("\xB7")} ${g>0?A.red(`${g} to spec`):A.gray("0 to spec")} `+A.gray(`across ${k} article${k===1?"":"s"}`));let C=o>0?Math.round(r/o*100):0;T.push(` [${Ed(r,o,32)}] ${A.bold(`${C}%`)}`),T.push("");let S=x.map(([z])=>ha(z)),R=Math.min(32,Math.max(7,...S.map(z=>z.name.length))),N=z=>z.length>R?`${z.slice(0,R-1)}\u2026`:as(z,R),V=[...s>0?[{head:"To verify",w:9,state:"captured",color:A.blue}]:[],...i>0?[{head:"Rejected",w:8,state:"rejected",color:A.magenta}]:[],{head:"Ready",w:5,state:"spec",color:A.yellow},...u>0?[{head:"Blocked",w:7,state:"blocked",color:A.cyan}]:[],...h>0?[{head:"Broken",w:6,state:"broken",color:A.red}]:[],{head:"To spec",w:7,state:"placeholder",color:A.red}];T.push(A.gray(` ${as("#",2)} ${as("Chapter",R)} ${Wt("Verified",8)} ${V.map(z=>Wt(z.head,z.w)).join(" ")} Progress`));for(let[z,[,pe]]of x.entries()){let le=n(pe,"verified"),Se=pe.length,{num:Pe,name:Ze}=S[z],Ct=le===Se,Yt=N(Ze),mr=V.map(lt=>{let gr=n(pe,lt.state);return gr>0?lt.color(Wt(String(gr),lt.w)):A.gray(Wt("\u2014",lt.w))}).join(" ");T.push(` ${A.cyan(as(Pe,2))} ${Ct?A.green(Yt):le>0?Yt:A.gray(Yt)} ${Ct?A.green(Wt(`${le}/${Se}`,8)):Wt(`${le}/${Se}`,8)} ${mr} ${Ed(le,Se,10)} ${oy(le,Se)}`)}T.push("");let K=h>0?` ${A.gray("\xB7")} ${h} spec${h===1?"":"s"} broken \u2014 ${A.bold(`/screenshot ${e.find(z=>z.state==="broken").id}`)} re-authors ${h===1?"it":"the first"}`:"",G=e.filter(z=>z.state==="spec"&&z.mutates).length,ae=a>G,Ce=e.filter(z=>(z.unguardedWaits?.length??0)>0||(z.bareGoto?.length??0)>0).length,ke=e.filter(z=>(z.stalePause?.length??0)>0||(z.handRolled?.length??0)>0).length,De=a>0||u>0||h>0,be=!1;if(g>0)T.push(` ${oe("\u2192",A.yellow)}${g} placeholder${g===1?"":"s"} still need a spec \u2014 run ${A.bold("/screenshot author --all")}${K}`);else if(Ce>0&&De)be=!0,T.push(` ${oe("\u2192",A.yellow)}${Ce} spec${Ce===1?"":"s"} would crash mid-run \u2014 re-write ${Ce===1?"it":"them"} first: ${A.bold("/screenshot author --all")}`+A.gray(` \xB7 then ${A.bold("/screenshot capture")} (no browser time wasted on ${Ce===1?"a shot":"shots"} that can't finish)`)+K);else if(ke>0&&De)be=!0,T.push(` ${oe("\u2192",A.yellow)}${ke} spec${ke===1?"":"s"} would shoot the wrong thing \u2014 re-write ${ke===1?"it":"them"} first: ${A.bold("/screenshot author --all")}`+A.gray(` \xB7 then ${A.bold("/screenshot capture")} (a false skip or a misplaced callout costs the same browser time as a good shot)`)+K);else if(a>0&&(ae||s===0)){let z=G>0?A.gray(` \u2014 ${a-G} in one go; ${G} write${G===1?"s":""} real data and run${G===1?"s":""} one at a time`):"";T.push(` ${oe("\u2192",A.yellow)}${a} spec${a===1?"":"s"} ready to capture \u2014 run ${A.bold("/screenshot capture")}${z}${K}`)}else if(s>0&&a>0)T.push(` ${oe("\u2192",A.blue)}${s} shot${s===1?"":"s"} awaiting verification \u2014 run ${A.bold("/screenshot verify")}`+A.gray(" \u2014 no browser needed")+A.gray(` \xB7 ${a} ready spec${a===1?"":"s"} write real data, so ${a===1?"it runs":"each runs"} only when named: /screenshot capture <id>`)+K);else if(u>0)T.push(` ${oe("\u2192",A.cyan)}${u} shot${u===1?"":"s"} blocked \u2014 stage the data below, then ${A.bold("/screenshot capture --blocked")}${K}`);else if(h>0)T.push(` ${oe("\u2192",A.red)}${h} spec${h===1?"":"s"} broken \u2014 ${A.bold(`/screenshot ${e.find(z=>z.state==="broken").id}`)} re-authors ${h===1?"it":"the first"} (re-capturing fails the same way)`);else if(s>0)T.push(` ${oe("\u2192",A.blue)}${s} shot${s===1?"":"s"} awaiting verification \u2014 run ${A.bold("/screenshot verify")}`+A.gray(" \u2014 it checks each picture against what its article needs (no browser, no re-capture)"));else if(i>0){let z=e.filter(pe=>pe.state==="rejected"&&pe.repaired).length;T.push(` ${oe("\u2691",A.magenta)}${i} shot${i===1?"":"s"} failed review \u2014 `+(z>0?`${z} spec${z===1?"":"s"} already repaired; re-capture with ${A.bold("/screenshot capture --failed")}`:`see the reasons below, then ${A.bold("/screenshot capture --failed")}`))}else T.push(` ${oe("\u2713",A.green)}all ${o} verified \u2014 ${A.bold("/publish")} embeds them in the articles`);if(r>0&&r<o){let z=x.filter(([,pe])=>pe.every(le=>le.state!=="verified")).map(([pe])=>{let{num:le,name:Se}=ha(pe);return le?`${le} ${Se}`:Se});z.length>0&&T.push(A.gray(` Furthest behind: ${z.slice(0,5).join(" \xB7 ")}${z.length>5?" \u2026":""} (0% verified)`))}return T.push(...Fd(e),...Hd(e),...Bd(e,!1,{commandInLead:be}),...Wd(e,!1)),T.push(""),T.push(A.gray(" Drill in: /screenshot list <chapter#> \xB7 /screenshot list --detail (all)")),T}function sy(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=[` ${A.bold("Screenshots")}: ${e.length} placeholder${e.length===1?"":"s"} across ${o.size} article${o.size===1?"":"s"} \xB7 ${A.green(`${r} verified`)}${s>0?A.blue(` \xB7 ${s} to verify`):""}${n?A.gray(` \xB7 scope ${n}`):""}`,""];for(let[a,u]of Gd(e,t)){let h=u.filter(C=>C.state==="verified").length,{num:g,name:k}=ha(a),x=g?`${g} \xB7 ${k}`:k;i.push(` ${A.bold(x)} ${A.gray(`(${h}/${u.length})`)}`);let T=new Map;for(let C of u){let S=ny(C.file),R=T.get(S)??[];T.has(S)||T.set(S,R),R.push(C)}for(let C of[...T.keys()].sort()){i.push(A.gray(` ${C}`));for(let S of T.get(C)){let R=Jw[S.state];if(i.push(` ${oe(Xw[S.state],R)}${R(S.id)}`),(S.state==="blocked"||S.state==="broken"||S.state==="rejected")&&S.reason){for(let N of Lt(qn(S.reason),84))i.push(A.gray(` ${N}`));S.state==="rejected"&&i.push(A.gray(` ${S.repaired?"spec repaired \u2014 re-capture to confirm":"spec not yet repaired"}`))}}}}return i.push(...Fd(e),...Hd(e),...Bd(e,!0),...Wd(e,!0)),i.push("",Qw),i}function gs(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??ya;return t?.detail||n?sy(e,o,n):ry(e,o)}function ba(e,t){if(!t||!/^\d+$/.test(t))return t;let n=Bt(e)?.docsDir??ya,o=String(Number(t));for(let{file:r}of Ad(e)){let s=qd(r,n),i=/^(\d+)/.exec(s);if(i&&String(Number(i[1]))===o)return s}return t}function Vd(e,t){let r=e.map(a=>" ".repeat(a.depth)+a.label),s=Math.max(0,...e.map((a,u)=>a.note?is(r[u]):0)),i=Math.min(s,Math.max(0,t-2-24));return e.map((a,u)=>{let h=r[u];if(!a.note)return{head:h,note:""};let g=Math.max(2,i+2-is(h)),k=a.note.trim(),x=t-is(h)-g;return{head:h+" ".repeat(g),note:x>1&&is(k)>x?`${k.slice(0,x-1)}\u2026`:k}})}function iy(e){let t=e.replace(/\\/g,"/").split("/").filter(Boolean),n=t.pop()??e;return{category:t.pop()??"(docs root)",article:n}}function ls(e,t,n){let o=new Map;for(let s of t){let{category:i,article:a}=iy(s.file),u=o.get(i)??new Map;o.set(i,u);let h=u.get(a)??[];u.set(a,h),h.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(h=>h.id),u=a.length>0;u&&e.push({kind:"category",action:n,label:`${s} (${a.length})`,ids:a,depth:1});for(let h of[...i.keys()].sort()){let g=i.get(h),k=g.filter(r).map(C=>C.id),x=k.length>0;x&&e.push({kind:"article",action:n,label:`${h} (${k.length})`,ids:k,depth:u?2:1});let T=(u?1:0)+(x?1:0)+1;for(let C of g){let S=n==="capture"&&C.mutates?" \u26A0 creates real data \u2014 runs only alone":void 0;e.push({kind:"shot",action:n,label:C.id,ids:[C.id],depth:T,...S?{note:S}:{}})}}}}function ia(e){return e?qn(e):""}function $a(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,u)=>a.id.localeCompare(u.id)))e.push({kind:"shot",action:"capture",label:i.id,ids:[i.id],depth:1,note:` \u2298 ${ia(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,u)=>a.id.localeCompare(u.id)))e.push({kind:"shot",action:"author",label:i.id,ids:[i.id],depth:1,note:` \u2717 re-authors \u2014 ${ia(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,u)=>a.id.localeCompare(u.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 ${ia(i.reason)}`})}}function Yd(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}),ls(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}),ls(o,n,"capture"),$a(o,e.filter(s=>s.state==="blocked"),e.filter(s=>s.state==="broken"),e.filter(s=>s.state==="rejected")),o}var fa=["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(`
|
|
344
|
+
`);function ay(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 ma="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 Kd(e,t,n){let o=e.paths,r=o.filter(u=>t?.get(u)?.outcome==="failed"),s=o.filter(u=>t?.get(u)?.outcome==="skipped"),i=u=>`- ${u}: ${t.get(u).reason.replace(/\s+/g," ").trim()}`,a=o.filter(u=>(n?.get(u)?.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(u=>`- ${u}`).join(`
|
|
345
|
+
`),"",...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(u=>_d(n.get(u),`RULE VIOLATIONS already in ${u}'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.",fa,ma].join(`
|
|
346
|
+
`)}async function ws(e,t,n){let o=Oo(e),r=Lo(t?.cwd??process.cwd());if(r&&console.log(A.gray(r)),o.mode==="list"){let u=t?.cwd??process.cwd(),h=ba(u,o.scope),g=Bt(u)?.docsDir??ya,k=Ae(u,h);for(let x of gs(k,{scope:h,detail:o.detail,docsDir:g}))console.log(x);return{kind:"continue"}}if(o.mode==="single"){let u=pn(t?.cwd??process.cwd(),o.id),h=u===null?[]:ka(u);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.",fa,ma,...n?.prior?["",...ay(n.prior)]:[],...h.length>0?["",..._d(h,"RULE VIOLATIONS already in the existing spec \u2014 fix every one:")]:[]].join(`
|
|
347
347
|
`),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.`,fa,ma].join(`
|
|
348
|
-
`),a=o.mode==="scope"?`/screenshot ${o.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:i,display:a}}var
|
|
349
|
-
`)}var
|
|
350
|
-
`)}async function Gn(e,t){try{let n=va(e,t),o=n.project.projectId,r=n.project.workspaceId;return!o||!r||(await gy({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 "${wy}" 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 ft="--skip-review";function mn(e,t){return fy(e,t)}function Sa(e,t){try{return mn(e,my(e,t)).length}catch{return 0}}function Fo(e,t,n=""){let o=Sa(e);return o===0?t:{text:`${n}${o} article${o===1?"":"s"} ${o===1?"has":"have"} never been editorially reviewed, so publishing is blocked until then. /review --fix reads each one and applies its fixes \u2014 then /publish --all.`,cmd:"/review --fix"}}function bs(e,t,n){let o=e.length,r=o===t?`all ${t} article${t===1?"":"s"}`:`${o} of the ${t} articles`,s=e.slice(0,3).map(i=>` \xB7 ${i.split("/").pop()}`);return[`\u2717 Not published \u2014 ${r} in this run ${o===1?"has":"have"} never been through an editorial review.`,...s,...o>s.length?[` \xB7 \u2026and ${o-s.length} more`]:[],"",`These were written by an AI. Run /review${n?` ${n}`:""} --fix first \u2014 a senior-editor pass that reads every article and applies its fixes \u2014 then publish.`,`(Deliberately publishing without a review: add ${ft}.)`]}function Pa(e,t,n){try{let o=zd(e,va(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 Ta(e,t,n,o=0,r){let s=R=>t[R.index]?.paths.length??0,i=e.filter(R=>R.ok),a=e.filter(R=>!R.ok),u=e.reduce((R,N)=>R+s(N),0),h=i.reduce((R,N)=>R+s(N),0),g=n==="api"?`${We(e.reduce((R,N)=>R+N.costUsd,0))} total`:Ft(e.reduce((R,N)=>R+N.outputTokens,0)),k=`${i.length}/${e.length} partition${e.length===1?"":"s"}`,x=R=>`${R} article${R===1?"":"s"}`,T=[],C=r?pt({blocked:r.blocked,allEmpty:r.allEmpty,aborted:!1},"The publish"):null;if(C)return T.push(...C),T.push("Nothing reached Document360. Re-run /publish --all once that is fixed."),o>0&&T.push(hn(o)),T;if(r&&u>0&&r.recorded===0){T.push(`\u2717 Nothing was published \u2014 the ${x(u)} in this run are not recorded in the category map, so none of them reached Document360.`),T.push("Run /doctor (this is usually the agent runtime not running), then re-run /publish --all.");for(let R of a)R.error&&T.push(` \u2717 ${R.label} \u2014 ${R.error}`);return o>0&&T.push(hn(o)),T}if(a.length===0&&(!r||r.recorded>=u))T.push(`Published ${x(u)} (${k}) successfully \xB7 ${g}.`),T.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else if(a.length===0&&r)T.push(`Published ${r.recorded}/${x(u)} (${k}) \xB7 ${g}.`),T.push(`${u-r.recorded} article${u-r.recorded===1?"":"s"} reported no error but ${u-r.recorded===1?"is":"are"} not recorded as published \u2014 re-run /publish --all to retry just those.`);else{T.push(`Published ${r?r.recorded:h}/${x(u)} (${k}) \xB7 ${g}.`),T.push(`${a.length} partition${a.length===1?"":"s"} failed \u2014 re-run /publish --all to retry just the rest (published articles are skipped):`);for(let R of a)T.push(` \u2717 ${R.label}${R.error?` \u2014 ${R.error}`:""}`)}let S=r?ns(r):null;return S&&T.push(S),o>0&&T.push(hn(o)),T}async function ht(e,t,n=0,o){if(!o?.skipReview){let i=mn(e.cwd,t);if(i.length>0){for(let a of bs(i,t.length))console.log(W(a));return{kind:"continue"}}}let{model:r}=py(e.cwd,"standard"),s=async(i,a)=>{let u=uy(i);console.log(b(a?`Resolving cross-links in ${i.length} article${i.length===1?"":"s"} whose targets published this run (second pass)\u2026`:`Publishing ${i.length} article${i.length===1?"":"s"} across ${u.length} partition${u.length===1?"":"s"} (\u2264${Mo} agents at once) on ${r}\u2026`)),a||console.log(b(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let h=!1;for await(let g of hy({cwd:e.cwd,partitions:u,promptFor:k=>Uo(k.paths),concurrency:Mo,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),allowUnreviewedPublish:o?.skipReview===!0,model:r}))if(g.type==="partition_status")g.status==="running"?console.log(b(` \u25B8 ${g.label} \u2014 publishing\u2026`)):g.status==="done"?console.log(B(` \u2713 ${g.label}`)):console.log(j(` \u2717 ${g.label}`));else if(g.type==="run_done"){h=g.aborted,console.log("");let k=process.env.ANTHROPIC_API_KEY?"api":"subscription",x=Pa(e.cwd,i,e.profileName),T=!g.aborted&&(!!g.blocked||!!g.allEmpty||i.length>0&&x===0);for(let R of Ta(g.results,u,k,a?0:n,{recorded:x,...g.blocked?{blocked:g.blocked}:{},...g.allEmpty?{allEmpty:!0}:{}}))console.log(g.ok&&!T?B(R):W(R));if(T)continue;let C=Ra(e.cwd,e.profileName);C&&console.log(b(C));try{let R=Jd(await Xd({cwd:e.cwd,profileName:e.profileName,onRateLimit:N=>console.log(b(` Document360 rate limit \u2014 waiting ${Math.ceil(N.waitMs/1e3)}s\u2026`))}));R&&console.log(R.startsWith("\u26A0")?W(R):b(R))}catch{}try{let R=Zd(await Qd({cwd:e.cwd,profileName:e.profileName}));R&&console.log(b(R))}catch{}let S=await Gn(e.cwd,e.profileName);S&&console.log(b(S))}return h};try{if(!await s(t,!1)){let a=await Ea(e.cwd,e.profileName,t);a.length>0&&await s(a,!0)}}catch(i){console.log(j(`Publish run failed: ${i.message}`))}return console.log(""),{kind:"continue"}}async function $s(e,t,n){let o=dy(e,n);if(o.length===0)return[];let r=new Set(Ca((await ys({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function Ea(e,t,n){try{let o=new Set(n),r=await ys({cwd:e,profileName:t});return Ca(r.entries).map(s=>s.path).filter(s=>o.has(s))}catch{return[]}}async function tp(e,t){let n=Be(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(j(n.reason)),{kind:"continue"};let o=e.includes(ft),r=e[0];if(e.includes("--screenshots")||e.includes("--shots")){let s=t?.cwd??process.cwd(),i=Ae(s),a=hs(i);if(a.length===0)return console.log(b("No captured screenshots yet \u2014 /screenshot capture first.")),{kind:"continue"};let u=fs(i);return u&&console.log(u),t?await ht(t,a,0,{skipReview:o}):{kind:"forward-to-agent",prompt:Uo(a),display:"/publish --screenshots"}}if(r==="--related"&&e[1]){if(!t)return{kind:"continue"};let s=await $s(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return s.length===0?(console.log(B("\u2713 All related articles are already published.")),{kind:"continue"}):await ht(t,s,0,{skipReview:o})}if(r==="--all"){console.log(b("Checking what needs publishing\u2026"));try{let s=await ys({cwd:t?.cwd??process.cwd()}),{clean:i,conflicts:a}=fn(s.entries),u=ks(s.entries),h=e.includes("--force")&&a.length>0;u>0&&console.log(W(`\u26A0 ${u} 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.`)),a.length>0&&!h&&console.log(W(hn(a.length)));let g=h?[...i,...a]:i;if(g.length===0){if(a.length>0)return console.log(b("Resolve the conflicts: /resolve")),{kind:"continue"};if(console.log(B(u>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),t)try{let k=Jd(await Xd({cwd:t.cwd,profileName:t.profileName,onRateLimit:T=>console.log(b(` Document360 rate limit \u2014 waiting ${Math.ceil(T.waitMs/1e3)}s\u2026`))}));k&&console.log(k.startsWith("\u26A0")?W(k):b(k));let x=Zd(await Qd({cwd:t.cwd,profileName:t.profileName}));x&&console.log(b(x))}catch{}return{kind:"continue"}}return t?await ht(t,g.map(k=>k.path),h?0:a.length,{skipReview:o}):{kind:"forward-to-agent",prompt:Uo(g.map(k=>k.path)),display:"/publish --all"}}catch(s){return console.log(j(`Could not compute sync status: ${s.message}`)),{kind:"continue"}}}if(r&&r.startsWith("--")&&(r=e.find(s=>!s.startsWith("--"))??""),!r){console.log(b("Checking what needs publishing\u2026"));let s,i=0;try{let a=await ys({cwd:t?.cwd??process.cwd()}),{clean:u,conflicts:h}=fn(a.entries);s=u,i=h.length;let g=ks(a.entries);if(g>0&&console.log(W(`\u26A0 ${g} 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.`)),h.length>0&&console.log(W(hn(h.length))),s.length===0&&h.length>0)return console.log(b("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(a){return console.log(j(`Could not compute sync status: ${a.message}`)),console.log(b("Publish a specific article: /publish <article-path>")),{kind:"continue"}}if(s.length===0)return console.log(B("\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),console.log(b(" (Articles without a sync base are unverified \u2014 publish those by path if needed.)")),{kind:"continue"};if(!process.stdin.isTTY||!t){for(let a of s)console.log(` ${a.path} ${b(`(${a.label})`)}`);return console.log(b("Run: /publish <article-path>")),{kind:"continue"}}try{r=await t.withPausedInput(()=>cy({message:"Publish which article?",choices:[...s.length>1?[{name:`All ${s.length} candidates`,value:"--all",description:"one agent run over every candidate"}]:[],...s.map(a=>({name:a.path,value:a.path,description:a.label}))]}))}catch{return console.log(b("Cancelled.")),{kind:"continue"}}if(r==="--all")return await ht(t,s.map(a=>a.path),i,{skipReview:o})}return{kind:"forward-to-agent",prompt:xa(r),display:`/publish ${r}`}}async function Wo(){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(`
|
|
351
|
-
`),display:"/audit"}}Q();import{readProjectConfig as
|
|
352
|
-
`)}async function
|
|
348
|
+
`),a=o.mode==="scope"?`/screenshot ${o.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:i,display:a}}var Uo=3;function xa(e){return[`Run the publish-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 and remind me to publish the draft manually in the Document360 portal."].join(`
|
|
349
|
+
`)}var zd={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function Ca(e){return e.filter(t=>t.path!==null&&t.status in zd&&!t.link).map(t=>({path:t.path,label:zd[t.status]}))}function fn(e){let t=Ca(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 hn(e){let t=e!==1;return`\u26A0 ${e} conflict${t?"s":""} NOT published (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 /publish <path> to keep yours, /pull <path> to take the portal's).`}function ks(e){return e.filter(t=>t.link).length}function Ra(e,t){try{let n=Xd(e,va(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=ky(ly(cy(e,r),"utf8"),r,n).unresolved}catch{}return o===0?null:`\u2139 ${o} cross-link${o===1?"":"s"} point to pages not published yet \u2014 they show as plain text for now and turn into live links once those pages are published.`}catch{return null}}function tp(e,t=[]){let n=[];e.length>1&&n.push({kind:"all",label:`Publish 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:`${Wn(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 Fo(e){return[`Run the publish-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) and remind me drafts need review in the portal."].join(`
|
|
350
|
+
`)}async function Gn(e,t){try{let n=va(e,t),o=n.project.projectId,r=n.project.workspaceId;return!o||!r||(await wy({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 "${yy}" 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 ft="--skip-review";function mn(e,t){return my(e,t)}function Sa(e,t){try{return mn(e,gy(e,t)).length}catch{return 0}}function Wo(e,t,n=""){let o=Sa(e);return o===0?t:{text:`${n}${o} article${o===1?"":"s"} ${o===1?"has":"have"} never been editorially reviewed, so publishing is blocked until then. /review --fix reads each one and applies its fixes \u2014 then /publish --all.`,cmd:"/review --fix"}}function bs(e,t,n){let o=e.length,r=o===t?`all ${t} article${t===1?"":"s"}`:`${o} of the ${t} articles`,s=e.slice(0,3).map(i=>` \xB7 ${i.split("/").pop()}`);return[`\u2717 Not published \u2014 ${r} in this run ${o===1?"has":"have"} never been through an editorial review.`,...s,...o>s.length?[` \xB7 \u2026and ${o-s.length} more`]:[],"",`These were written by an AI. Run /review${n?` ${n}`:""} --fix first \u2014 a senior-editor pass that reads every article and applies its fixes \u2014 then publish.`,`(Deliberately publishing without a review: add ${ft}.)`]}function Pa(e,t,n){try{let o=Xd(e,va(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 Ta(e,t,n,o=0,r){let s=R=>t[R.index]?.paths.length??0,i=e.filter(R=>R.ok),a=e.filter(R=>!R.ok),u=e.reduce((R,N)=>R+s(N),0),h=i.reduce((R,N)=>R+s(N),0),g=n==="api"?`${We(e.reduce((R,N)=>R+N.costUsd,0))} total`:Ft(e.reduce((R,N)=>R+N.outputTokens,0)),k=`${i.length}/${e.length} partition${e.length===1?"":"s"}`,x=R=>`${R} article${R===1?"":"s"}`,T=[],C=r?pt({blocked:r.blocked,allEmpty:r.allEmpty,aborted:!1},"The publish"):null;if(C)return T.push(...C),T.push("Nothing reached Document360. Re-run /publish --all once that is fixed."),o>0&&T.push(hn(o)),T;if(r&&u>0&&r.recorded===0){T.push(`\u2717 Nothing was published \u2014 the ${x(u)} in this run are not recorded in the category map, so none of them reached Document360.`),T.push("Run /doctor (this is usually the agent runtime not running), then re-run /publish --all.");for(let R of a)R.error&&T.push(` \u2717 ${R.label} \u2014 ${R.error}`);return o>0&&T.push(hn(o)),T}if(a.length===0&&(!r||r.recorded>=u))T.push(`Published ${x(u)} (${k}) successfully \xB7 ${g}.`),T.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else if(a.length===0&&r)T.push(`Published ${r.recorded}/${x(u)} (${k}) \xB7 ${g}.`),T.push(`${u-r.recorded} article${u-r.recorded===1?"":"s"} reported no error but ${u-r.recorded===1?"is":"are"} not recorded as published \u2014 re-run /publish --all to retry just those.`);else{T.push(`Published ${r?r.recorded:h}/${x(u)} (${k}) \xB7 ${g}.`),T.push(`${a.length} partition${a.length===1?"":"s"} failed \u2014 re-run /publish --all to retry just the rest (published articles are skipped):`);for(let R of a)T.push(` \u2717 ${R.label}${R.error?` \u2014 ${R.error}`:""}`)}let S=r?ns(r):null;return S&&T.push(S),o>0&&T.push(hn(o)),T}async function ht(e,t,n=0,o){if(!o?.skipReview){let i=mn(e.cwd,t);if(i.length>0){for(let a of bs(i,t.length))console.log(W(a));return{kind:"continue"}}}let{model:r}=hy(e.cwd,"standard"),s=async(i,a)=>{let u=dy(i);console.log(b(a?`Resolving cross-links in ${i.length} article${i.length===1?"":"s"} whose targets published this run (second pass)\u2026`:`Publishing ${i.length} article${i.length===1?"":"s"} across ${u.length} partition${u.length===1?"":"s"} (\u2264${Uo} agents at once) on ${r}\u2026`)),a||console.log(b(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let h=!1;for await(let g of fy({cwd:e.cwd,partitions:u,promptFor:k=>Fo(k.paths),concurrency:Uo,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),allowUnreviewedPublish:o?.skipReview===!0,model:r}))if(g.type==="partition_status")g.status==="running"?console.log(b(` \u25B8 ${g.label} \u2014 publishing\u2026`)):g.status==="done"?console.log(B(` \u2713 ${g.label}`)):console.log(j(` \u2717 ${g.label}`));else if(g.type==="run_done"){h=g.aborted,console.log("");let k=process.env.ANTHROPIC_API_KEY?"api":"subscription",x=Pa(e.cwd,i,e.profileName),T=!g.aborted&&(!!g.blocked||!!g.allEmpty||i.length>0&&x===0);for(let R of Ta(g.results,u,k,a?0:n,{recorded:x,...g.blocked?{blocked:g.blocked}:{},...g.allEmpty?{allEmpty:!0}:{}}))console.log(g.ok&&!T?B(R):W(R));if(T)continue;let C=Ra(e.cwd,e.profileName);C&&console.log(b(C));try{let R=Qd(await Jd({cwd:e.cwd,profileName:e.profileName,onRateLimit:N=>console.log(b(` Document360 rate limit \u2014 waiting ${Math.ceil(N.waitMs/1e3)}s\u2026`))}));R&&console.log(R.startsWith("\u26A0")?W(R):b(R))}catch{}try{let R=ep(await Zd({cwd:e.cwd,profileName:e.profileName}));R&&console.log(b(R))}catch{}let S=await Gn(e.cwd,e.profileName);S&&console.log(b(S))}return h};try{if(!await s(t,!1)){let a=await Ea(e.cwd,e.profileName,t);a.length>0&&await s(a,!0)}}catch(i){console.log(j(`Publish run failed: ${i.message}`))}return console.log(""),{kind:"continue"}}async function $s(e,t,n){let o=py(e,n);if(o.length===0)return[];let r=new Set(Ca((await ys({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function Ea(e,t,n){try{let o=new Set(n),r=await ys({cwd:e,profileName:t});return Ca(r.entries).map(s=>s.path).filter(s=>o.has(s))}catch{return[]}}async function np(e,t){let n=Be(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(j(n.reason)),{kind:"continue"};let o=e.includes(ft),r=e[0];if(e.includes("--screenshots")||e.includes("--shots")){let s=t?.cwd??process.cwd(),i=Ae(s),a=hs(i);if(a.length===0)return console.log(b("No captured screenshots yet \u2014 /screenshot capture first.")),{kind:"continue"};let u=fs(i);return u&&console.log(u),t?await ht(t,a,0,{skipReview:o}):{kind:"forward-to-agent",prompt:Fo(a),display:"/publish --screenshots"}}if(r==="--related"&&e[1]){if(!t)return{kind:"continue"};let s=await $s(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return s.length===0?(console.log(B("\u2713 All related articles are already published.")),{kind:"continue"}):await ht(t,s,0,{skipReview:o})}if(r==="--all"){console.log(b("Checking what needs publishing\u2026"));try{let s=await ys({cwd:t?.cwd??process.cwd()}),{clean:i,conflicts:a}=fn(s.entries),u=ks(s.entries),h=e.includes("--force")&&a.length>0;u>0&&console.log(W(`\u26A0 ${u} 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.`)),a.length>0&&!h&&console.log(W(hn(a.length)));let g=h?[...i,...a]:i;if(g.length===0){if(a.length>0)return console.log(b("Resolve the conflicts: /resolve")),{kind:"continue"};if(console.log(B(u>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),t)try{let k=Qd(await Jd({cwd:t.cwd,profileName:t.profileName,onRateLimit:T=>console.log(b(` Document360 rate limit \u2014 waiting ${Math.ceil(T.waitMs/1e3)}s\u2026`))}));k&&console.log(k.startsWith("\u26A0")?W(k):b(k));let x=ep(await Zd({cwd:t.cwd,profileName:t.profileName}));x&&console.log(b(x))}catch{}return{kind:"continue"}}return t?await ht(t,g.map(k=>k.path),h?0:a.length,{skipReview:o}):{kind:"forward-to-agent",prompt:Fo(g.map(k=>k.path)),display:"/publish --all"}}catch(s){return console.log(j(`Could not compute sync status: ${s.message}`)),{kind:"continue"}}}if(r&&r.startsWith("--")&&(r=e.find(s=>!s.startsWith("--"))??""),!r){console.log(b("Checking what needs publishing\u2026"));let s,i=0;try{let a=await ys({cwd:t?.cwd??process.cwd()}),{clean:u,conflicts:h}=fn(a.entries);s=u,i=h.length;let g=ks(a.entries);if(g>0&&console.log(W(`\u26A0 ${g} 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.`)),h.length>0&&console.log(W(hn(h.length))),s.length===0&&h.length>0)return console.log(b("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(a){return console.log(j(`Could not compute sync status: ${a.message}`)),console.log(b("Publish a specific article: /publish <article-path>")),{kind:"continue"}}if(s.length===0)return console.log(B("\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),console.log(b(" (Articles without a sync base are unverified \u2014 publish those by path if needed.)")),{kind:"continue"};if(!process.stdin.isTTY||!t){for(let a of s)console.log(` ${a.path} ${b(`(${a.label})`)}`);return console.log(b("Run: /publish <article-path>")),{kind:"continue"}}try{r=await t.withPausedInput(()=>uy({message:"Publish which article?",choices:[...s.length>1?[{name:`All ${s.length} candidates`,value:"--all",description:"one agent run over every candidate"}]:[],...s.map(a=>({name:a.path,value:a.path,description:a.label}))]}))}catch{return console.log(b("Cancelled.")),{kind:"continue"}}if(r==="--all")return await ht(t,s.map(a=>a.path),i,{skipReview:o})}return{kind:"forward-to-agent",prompt:xa(r),display:`/publish ${r}`}}async function Bo(){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(`
|
|
351
|
+
`),display:"/audit"}}Q();import{readProjectConfig as by}from"document360-engine";function Aa(){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(`
|
|
352
|
+
`)}async function op(e,t){let n=t?.cwd??process.cwd();return by(n)?{kind:"forward-to-agent",prompt:Aa(),display:"/discover"}:(console.log(j("No d360-writer config here. Run /init first.")),{kind:"continue"})}Q();import{checkbox as $y}from"@inquirer/prompts";import{inventoryRepo as vy,readProjectConfig as rp,writeProjectConfig as xy}from"document360-engine";function Da(e,t){let n=rp(e);n&&(n.authoritativeSourceFiles=t,xy(n,e))}function vs(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 sp(e,t){let n=t?.cwd??process.cwd();if(!rp(n))return console.log(j("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=vy(n);if(o.length===0)return console.log(b('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(q("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${b(vs(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>$y({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${vs(s)})`,value:s.path,checked:s.recommended})),pageSize:20}))}catch{return console.log(b("Cancelled.")),{kind:"continue"}}if(r.length===0)return console.log(b("Nothing selected \u2014 scope unchanged.")),{kind:"continue"};Da(n,r),console.log(B(`\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"}}Q();import{confirm as Dy}from"@inquirer/prompts";import{applyPull as Ia,computeSyncStatus as mp,compareRemoteSources as Ny,planPull as gp,planImport as jy,applyImport as Iy,establishBaselines as Oy,rebaselineServerMeta as Ly,D360AuthError as _y}from"document360-engine";Q();var ip=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /publish <path>):",paint:j,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /publish <path>:",paint:W,mark:"M"},{status:"remote-ahead",header:"Changed on Document360 \u2014 pull with /pull <path> (or just /pull):",paint:q,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:j,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:j,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint:fe,mark:"X"},{status:"untracked-local",header:"New here \u2014 not on Document360 yet (publish to add them):",paint:b,mark:"?"},{status:"untracked-remote",header:"On Document360 \u2014 not in your local docs yet (run /pull to import them):",paint:b,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:fe,mark:"\xB7"}];function Cy(e){return e.path?e.path:`${e.title??"(untitled)"} ${fe(`[${e.articleId}]`)}`}function Ry(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 xs(e,t){let n=[],o=e.entries.filter(g=>g.link);if(o.length>0){n.push(""),n.push(je("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let g of o)n.push(` ${W("~")} ${W(g.path??"")} ${fe(`\u2192 "${g.link.title}"`)}`)}for(let g of ip){let k=e.entries.filter(x=>x.status===g.status&&!(g.status==="untracked-local"&&x.link));if(k.length!==0){n.push(""),n.push(je(g.header));for(let x of k)n.push(` ${g.paint(g.mark)} ${g.paint(Cy(x))}${x.detail?fe(` (${x.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,u=s===r?B("\u2713 everything up to date"):[r>0?B(`\u2713 ${r} up to date`):null,a>0?`${a} to link`:null,...ip.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(fe(" \xB7 ")),h=t!==void 0?` \xB7 synced in ${Ry(t)}`:"";return n.push(u+fe(` \xB7 ${s} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${h}`)),n}import{structuredPatch as Sy}from"diff";import ap from"picocolors";var lp=80,Py="\x1B[48;2;74;28;28m",Ty="\x1B[48;2;24;66;24m",cp="\x1B[49m",Na=e=>String(e).padStart(5);function up(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}function dp(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 Xe(e,t,n){let o=x=>{let T=x.replace(/\r\n/g,`
|
|
353
353
|
`);return T.endsWith(`
|
|
354
354
|
`)||T===""?T:T+`
|
|
355
|
-
`},r=o(e),s=o(t);if(r===s)return null;let i=Math.max(20,n-10),a=Ry("a","b",r,s,"","",{context:3}),u=0,h=0,g=[];a.hunks.forEach((x,T)=>{T>0&&g.push(ip.gray(" \u2026"));let C=x.oldStart,S=x.newStart,R=[],N=[],V=()=>{for(let K=0;K<R.length;K++){let G=K<N.length?cp(R[K],N[K]):void 0;h++,g.push(`${Sy}${Na(C++)} - ${up(R[K],i,G)}${lp}`)}for(let K=0;K<N.length;K++){let G=K<R.length?cp(R[K],N[K]):void 0;u++,g.push(`${Py}${Na(S++)} + ${up(N[K],i,G)}${lp}`)}R=[],N=[]};for(let K of x.lines){let G=K[0],ae=K.slice(1);G==="-"?R.push(ae):G==="+"?N.push(ae):(V(),g.push(ip.gray(Na(S))+" "+ae.slice(0,i)),C++,S++)}V()});let k=g.slice(0,ap);return{added:u,removed:h,lines:k,hidden:Math.max(0,g.length-ap)}}Q();import{select as Ty}from"@inquirer/prompts";import{applyPull as pp,computeSyncStatus as Ey,planPull as dp}from"document360-engine";var Cs=e=>e===1?"":"s";async function ja(e,t,n=1){console.log(""),console.log(`${q("\u25CF")} ${je(t.title)} ${fe(`(${t.path})`)}`);for(let i of t.notes)console.log(W(` \u26A0 ${i}`));let o=ze(t.oldContent,t.newContent,Math.max(40,(process.stdout.columns??80)-1));if(o){console.log(fe(` \u23BF local \u2192 portal: +${o.added} / -${o.removed} line${Cs(o.added+o.removed)}`));for(let i of o.lines)console.log(i);o.hidden>0&&console.log(b(` \u2026 +${o.hidden} more diff lines`))}else console.log(b(" Local already matches the portal content \u2014 resolving just advances the sync base."));let r=n>1,s=await e.withPausedInput(()=>Ty({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"?(pp({cwd:e.cwd,profileName:e.profileName},t),console.log(B(" \u2713 Took the portal copy (local overwritten, sync base advanced).")),"took-portal"):s==="local"?"keep-local":s==="skip"?(console.log(b(" Skipped \u2014 still a conflict.")),"skipped"):s==="local-all"?"keep-local-all":s==="portal-all"?"took-portal-all":"skipped-all"}async function hp(e,t){let n=Be(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 Ey({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(B(`${o} isn't in conflict \u2014 nothing to resolve.`)),{kind:"continue"};s=[o]}if(s.length===0)return console.log(B("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let i=[];for(let[a,u]of s.entries()){let h=await dp({cwd:t.cwd,profileName:t.profileName,relPath:u}),g=await ja(t,h,s.length-a);if(g==="keep-local"&&i.push(u),!g.endsWith("-all"))continue;let k=s.slice(a);if(g==="keep-local-all")i.push(...k),console.log(b(` Keeping local for all ${k.length} \u2014 publishing them over the portal.`));else if(g==="took-portal-all"){let x=0;for(let T of k)try{pp({cwd:t.cwd,profileName:t.profileName},await dp({cwd:t.cwd,profileName:t.profileName,relPath:T})),x++}catch(C){console.log(j(` \u2717 ${T}: ${C.message}`))}console.log(B(` \u2713 Took the portal copy of ${x} article${Cs(x)} (local overwritten, sync base advanced).`))}else console.log(b(` Skipped all ${k.length} \u2014 still conflict${Cs(k.length)}.`));break}if(i.length>0)return console.log(b(`Publishing ${i.length} kept-local article${Cs(i.length)} over the portal\u2026`)),await ht(t,i)}catch(r){console.log(j(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function gp(e,t){let n=Be(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 _y(t),{kind:"continue"};if(o==="--baseline")return await My(t,e.filter(i=>i!=="--baseline")),{kind:"continue"};if(o==="--compare")return await Uy(t),{kind:"continue"};if(o)return console.log(j(`Unknown option: ${o}`)),console.log(b("Usage: /pull pull portal edits + import new portal articles")),console.log(b(" /pull <path> pull one article (or resolve a conflict)")),console.log(b(" /pull --status drift report only (no writes)")),console.log(b(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await Fy(t,r),{kind:"continue"};console.log(b("Pulling changes from Document360\u2026"));let s=await Oa({cwd:t.cwd,profileName:t.profileName});for(let i of La(s))console.log(i.tone==="ok"?B(i.text):i.tone==="warn"?W(i.text):b(i.text));console.log("")}catch(r){r instanceof Ly?console.log(j(r.message)):console.log(j(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function Oa(e){let t=await fp({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 mp({cwd:e.cwd,profileName:e.profileName,relPath:o.path});Ia({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 Ny({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});jy({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 Rs=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,gn=e=>e===1?"":"s";function La(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${gn(e.pulled.length)} into local: ${Rs(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${gn(e.imported.length)}: ${Rs(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${gn(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${gn(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). (${Rs(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${gn(e.failed.length)} failed: ${Rs(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 _y(e){console.log(b("Checking Document360 for drift\u2026"));let t=Date.now(),n=await fp({cwd:e.cwd,profileName:e.profileName});for(let o of xs(n,Date.now()-t))console.log(o);console.log("")}async function My(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(b(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await Iy({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await Oy({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(B("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(B(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(B(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(W(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(b(` - ${s.path} (${s.reason})`))}}async function Uy(e){console.log(b("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await Dy({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${je(String(t.legacyCount))} \xB7 Manifest: ${je(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(B("\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(W(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(W(` ${t.onlyInManifest.length} only in the manifest: ${t.onlyInManifest.slice(0,5).join(", ")}`)),console.log(b(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function Fy(e,t){let n=t.replace(/\\/g,"/"),o=await mp({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await ja(e,o)==="keep-local"&&(console.log(b(`Publishing ${o.path} over the portal\u2026`)),await ht(e,[o.path]));return}console.log(""),console.log(`${q("\u25CF")} ${je(o.title)} ${fe(`(${o.path})`)}`);for(let i of o.notes)console.log(W(` \u26A0 ${i}`));let r=ze(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!r){console.log(b(" Local file already matches the remote content \u2014 advancing the sync base only.")),Ia({cwd:e.cwd,profileName:e.profileName},o);return}console.log(fe(` \u23BF Added ${r.added} line${gn(r.added)}, removed ${r.removed} line${gn(r.removed)}`));for(let i of r.lines)console.log(i);if(r.hidden>0&&console.log(b(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>Ay({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(b(" Skipped."));return}Ia({cwd:e.cwd,profileName:e.profileName},o),console.log(B(` \u2713 Pulled ${o.path} (sync base advanced).`))}Q();import{statSync as Wy}from"node:fs";import{resolve as By}from"node:path";import{estimateBulkCost as Hy,planPartitions as qy,readProjectConfig as Gy,resolveModelForOperation as Vy,runPartitioned as Yy,trackedArticlePaths as Ky}from"document360-engine";var _a=3;function Ma(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 Ua(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Fa(e,t){return t.map(n=>{let o=0;try{o=Wy(By(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function Wa(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:
|
|
355
|
+
`},r=o(e),s=o(t);if(r===s)return null;let i=Math.max(20,n-10),a=Sy("a","b",r,s,"","",{context:3}),u=0,h=0,g=[];a.hunks.forEach((x,T)=>{T>0&&g.push(ap.gray(" \u2026"));let C=x.oldStart,S=x.newStart,R=[],N=[],V=()=>{for(let K=0;K<R.length;K++){let G=K<N.length?up(R[K],N[K]):void 0;h++,g.push(`${Py}${Na(C++)} - ${dp(R[K],i,G)}${cp}`)}for(let K=0;K<N.length;K++){let G=K<R.length?up(R[K],N[K]):void 0;u++,g.push(`${Ty}${Na(S++)} + ${dp(N[K],i,G)}${cp}`)}R=[],N=[]};for(let K of x.lines){let G=K[0],ae=K.slice(1);G==="-"?R.push(ae):G==="+"?N.push(ae):(V(),g.push(ap.gray(Na(S))+" "+ae.slice(0,i)),C++,S++)}V()});let k=g.slice(0,lp);return{added:u,removed:h,lines:k,hidden:Math.max(0,g.length-lp)}}Q();import{select as Ey}from"@inquirer/prompts";import{applyPull as hp,computeSyncStatus as Ay,planPull as pp}from"document360-engine";var Cs=e=>e===1?"":"s";async function ja(e,t,n=1){console.log(""),console.log(`${q("\u25CF")} ${je(t.title)} ${fe(`(${t.path})`)}`);for(let i of t.notes)console.log(W(` \u26A0 ${i}`));let o=Xe(t.oldContent,t.newContent,Math.max(40,(process.stdout.columns??80)-1));if(o){console.log(fe(` \u23BF local \u2192 portal: +${o.added} / -${o.removed} line${Cs(o.added+o.removed)}`));for(let i of o.lines)console.log(i);o.hidden>0&&console.log(b(` \u2026 +${o.hidden} more diff lines`))}else console.log(b(" Local already matches the portal content \u2014 resolving just advances the sync base."));let r=n>1,s=await e.withPausedInput(()=>Ey({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"?(hp({cwd:e.cwd,profileName:e.profileName},t),console.log(B(" \u2713 Took the portal copy (local overwritten, sync base advanced).")),"took-portal"):s==="local"?"keep-local":s==="skip"?(console.log(b(" Skipped \u2014 still a conflict.")),"skipped"):s==="local-all"?"keep-local-all":s==="portal-all"?"took-portal-all":"skipped-all"}async function fp(e,t){let n=Be(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 Ay({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(B(`${o} isn't in conflict \u2014 nothing to resolve.`)),{kind:"continue"};s=[o]}if(s.length===0)return console.log(B("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let i=[];for(let[a,u]of s.entries()){let h=await pp({cwd:t.cwd,profileName:t.profileName,relPath:u}),g=await ja(t,h,s.length-a);if(g==="keep-local"&&i.push(u),!g.endsWith("-all"))continue;let k=s.slice(a);if(g==="keep-local-all")i.push(...k),console.log(b(` Keeping local for all ${k.length} \u2014 publishing them over the portal.`));else if(g==="took-portal-all"){let x=0;for(let T of k)try{hp({cwd:t.cwd,profileName:t.profileName},await pp({cwd:t.cwd,profileName:t.profileName,relPath:T})),x++}catch(C){console.log(j(` \u2717 ${T}: ${C.message}`))}console.log(B(` \u2713 Took the portal copy of ${x} article${Cs(x)} (local overwritten, sync base advanced).`))}else console.log(b(` Skipped all ${k.length} \u2014 still conflict${Cs(k.length)}.`));break}if(i.length>0)return console.log(b(`Publishing ${i.length} kept-local article${Cs(i.length)} over the portal\u2026`)),await ht(t,i)}catch(r){console.log(j(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function wp(e,t){let n=Be(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 My(t),{kind:"continue"};if(o==="--baseline")return await Uy(t,e.filter(i=>i!=="--baseline")),{kind:"continue"};if(o==="--compare")return await Fy(t),{kind:"continue"};if(o)return console.log(j(`Unknown option: ${o}`)),console.log(b("Usage: /pull pull portal edits + import new portal articles")),console.log(b(" /pull <path> pull one article (or resolve a conflict)")),console.log(b(" /pull --status drift report only (no writes)")),console.log(b(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await Wy(t,r),{kind:"continue"};console.log(b("Pulling changes from Document360\u2026"));let s=await Oa({cwd:t.cwd,profileName:t.profileName});for(let i of La(s))console.log(i.tone==="ok"?B(i.text):i.tone==="warn"?W(i.text):b(i.text));console.log("")}catch(r){r instanceof _y?console.log(j(r.message)):console.log(j(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function Oa(e){let t=await mp({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 gp({cwd:e.cwd,profileName:e.profileName,relPath:o.path});Ia({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 jy({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});Iy({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 Rs=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,gn=e=>e===1?"":"s";function La(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${gn(e.pulled.length)} into local: ${Rs(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${gn(e.imported.length)}: ${Rs(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${gn(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${gn(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). (${Rs(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${gn(e.failed.length)} failed: ${Rs(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 My(e){console.log(b("Checking Document360 for drift\u2026"));let t=Date.now(),n=await mp({cwd:e.cwd,profileName:e.profileName});for(let o of xs(n,Date.now()-t))console.log(o);console.log("")}async function Uy(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(b(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await Oy({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await Ly({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(B("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(B(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(B(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(W(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(b(` - ${s.path} (${s.reason})`))}}async function Fy(e){console.log(b("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await Ny({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${je(String(t.legacyCount))} \xB7 Manifest: ${je(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(B("\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(W(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(W(` ${t.onlyInManifest.length} only in the manifest: ${t.onlyInManifest.slice(0,5).join(", ")}`)),console.log(b(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function Wy(e,t){let n=t.replace(/\\/g,"/"),o=await gp({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await ja(e,o)==="keep-local"&&(console.log(b(`Publishing ${o.path} over the portal\u2026`)),await ht(e,[o.path]));return}console.log(""),console.log(`${q("\u25CF")} ${je(o.title)} ${fe(`(${o.path})`)}`);for(let i of o.notes)console.log(W(` \u26A0 ${i}`));let r=Xe(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!r){console.log(b(" Local file already matches the remote content \u2014 advancing the sync base only.")),Ia({cwd:e.cwd,profileName:e.profileName},o);return}console.log(fe(` \u23BF Added ${r.added} line${gn(r.added)}, removed ${r.removed} line${gn(r.removed)}`));for(let i of r.lines)console.log(i);if(r.hidden>0&&console.log(b(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>Dy({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(b(" Skipped."));return}Ia({cwd:e.cwd,profileName:e.profileName},o),console.log(B(` \u2713 Pulled ${o.path} (sync base advanced).`))}Q();import{statSync as By}from"node:fs";import{resolve as Hy}from"node:path";import{estimateBulkCost as qy,planPartitions as Gy,readProjectConfig as Vy,resolveModelForOperation as Yy,runPartitioned as Ky,trackedArticlePaths as zy}from"document360-engine";var _a=3;function Ma(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 Ua(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Fa(e,t){return t.map(n=>{let o=0;try{o=By(Hy(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function Wa(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:
|
|
356
356
|
- 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.
|
|
357
357
|
- 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.
|
|
358
358
|
- 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.
|
|
359
359
|
- Work only on these files:
|
|
360
360
|
`+e.paths.map(t=>`- ${t}`).join(`
|
|
361
|
-
`)}function Ba(e,t,n){let o=e.reduce((a,u)=>a+u.paths.length,0),[r,s]=t.usd;return[`Convert ${o} article${o===1?"":"s"} to DFM across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(a=>` \u2022 ${a.label} \u2014 ${a.paths.length} article${a.paths.length===1?"":"s"}`),"",`Estimated cost: ${We(r)}\u2013${We(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function Ha(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),i=e.reduce((C,S)=>C+o(S),0),a=r.reduce((C,S)=>C+o(S),0),u=e.reduce((C,S)=>C+S.costUsd,0),h=e.reduce((C,S)=>C+S.outputTokens,0),g=n==="api"?`${We(u)} total`:Ft(h),k=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,x=C=>`${C} article${C===1?"":"s"}`,T=[];if(s.length===0)T.push(`Converted ${x(i)} (${k}) successfully \xB7 ${g}.`);else{T.push(`Converted ${a}/${x(i)} (${k}) \xB7 ${g}.`),T.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let C of s)T.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return T}async function
|
|
361
|
+
`)}function Ba(e,t,n){let o=e.reduce((a,u)=>a+u.paths.length,0),[r,s]=t.usd;return[`Convert ${o} article${o===1?"":"s"} to DFM across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(a=>` \u2022 ${a.label} \u2014 ${a.paths.length} article${a.paths.length===1?"":"s"}`),"",`Estimated cost: ${We(r)}\u2013${We(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function Ha(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),i=e.reduce((C,S)=>C+o(S),0),a=r.reduce((C,S)=>C+o(S),0),u=e.reduce((C,S)=>C+S.costUsd,0),h=e.reduce((C,S)=>C+S.outputTokens,0),g=n==="api"?`${We(u)} total`:Ft(h),k=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,x=C=>`${C} article${C===1?"":"s"}`,T=[];if(s.length===0)T.push(`Converted ${x(i)} (${k}) successfully \xB7 ${g}.`);else{T.push(`Converted ${a}/${x(i)} (${k}) \xB7 ${g}.`),T.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let C of s)T.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return T}async function yp(e,t){if(!Vy(t.cwd))return console.log(j("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=Ma(e),r=zy(t.cwd,t.profileName);if(r.length===0)return console.log(j("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let s=Ua(r,n);if(s.length===0)return console.log(j(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let i=Gy(s),a=`/convert${n?` --scope ${n}`:""} --run`,{model:u,forced:h}=Yy(t.cwd,"light");if(!o){let g=qy({files:Fa(t.cwd,s),op:"convert",model:u});n&&console.log(b(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let k of Ba(i,g,_a))console.log(k);return console.log(b(`Model: ${u}${h?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(b(`Run ${a} to start.`)),console.log(""),{kind:"continue"}}console.log(b(`Converting ${s.length} articles across ${i.length} partitions (\u2264${_a} agents at once) on ${u}\u2026`)),console.log(b(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let g of Ky({cwd:t.cwd,partitions:i,promptFor:Wa,concurrency:_a,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:u}))if(g.type==="partition_status")g.status==="running"?console.log(b(` \u25B8 ${g.label} \u2014 converting\u2026`)):g.status==="done"?console.log(B(` \u2713 ${g.label}`)):console.log(j(` \u2717 ${g.label}`));else if(g.type==="run_done"){console.log("");let k=process.env.ANTHROPIC_API_KEY?"api":"subscription",x=pt(g,"The conversion");for(let T of x??Ha(g.results,i,k))console.log(x||!g.ok?W(T):B(T))}}catch(g){console.log(j(`Convert run failed: ${g.message}`))}return console.log(""),{kind:"continue"}}Q();import{statSync as vp}from"node:fs";import{resolve as xp}from"node:path";import{estimateBulkCost as rk,lintDocs as sk,planPartitions as ik,readDocsPlan as ak,readProjectConfig as Cp,DEFAULT_DOCS_DIR as lk,resolveModelForOperation as ck,runPartitioned as uk,stampArticles as dk,CONTENT_CAP_VERSION as pk}from"document360-engine";import{readProjectConfig as Xy,loadProfileMap as Jy,resolveActiveProfile as Qy,desiredCategoryOrder as Zy,desiredArticleOrder as ek,DEFAULT_DOCS_DIR as tk}from"document360-engine";var qa=e=>e.replace(/\\/g,"/"),kp=e=>qa(e).split("/").pop()??e;function Ga(e){let t=kp(e),n=t.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return n?n.charAt(0).toUpperCase()+n.slice(1):t}var nk=Ga;function Ho(e,t){try{let n=Xy(e);if(!n)return[];let o=Qy(e,t),r=Jy(e,o.name);if(!r)return[];let s=qa(n.docsDir??tk).replace(/\/+$/,""),i=new Map;for(let u of ek(r))i.set(u.categoryPath,(i.get(u.categoryPath)??0)+1);let a=[];for(let u of Zy(r)){let h=qa(u.path),g=h.startsWith(`${s}/`)?h.slice(s.length+1):h===s?"":h;g&&a.push({token:g,label:nk(kp(h)),count:i.get(u.path)??0})}return a}catch{return[]}}function bp(e,t){let n=Ho(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 Ht(e,t){if(t.includes("--all")||t.some(n=>n.startsWith("--scope="))||t.includes("--scope")&&!qo(t))return!1;for(let n=0;n<t.length;n++){let o=t[n];if(o.startsWith("--")){ok.has(o)&&n++;continue}return!1}return e==="write"?!t.includes("--preview")&&!t.includes("--dry-run"):e==="review"||e==="reorder"}var ok=new Set(["--scope","--concurrency"]);function Vn(e,t,n,o,r){if(r=r??Ho(e,o),r.length<=1)return[];let s=n.filter(h=>h.startsWith("--")).join(" "),i=s?` ${s}`:"",a=`/${t}${i} --all`.replace(/\s+/g," "),u=h=>t==="write"?`/write --scope ${h}${i}`:`/${t} ${h}${i}`;return[`Bare /${t} covers the WHOLE knowledge base (${r.reduce((h,g)=>h+g.count,0)} articles). Pick a target:`,` ${a} (everything)`,...r.map(h=>` ${u(h.token)} (${h.label} \xB7 ${h.count} article${h.count===1?"":"s"})`)]}function qo(e){let t=e.indexOf("--scope");if(t===-1)return!1;let n=e[t+1];return n===void 0||n.startsWith("-")}function $p(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 hk=3,fk=8;function Va(e){return e===void 0||!Number.isFinite(e)?hk:Math.max(1,Math.min(Math.floor(e),fk))}function Go(e){let t,n,o=!1,r=!1,s,i=u=>{let h=Number(u);return u!==void 0&&Number.isFinite(h)?h:void 0};for(let u=0;u<e.length;u++){let h=e[u];if(h==="--preview"||h==="--dry-run")o=!0;else if(h==="--rewrite"||h==="--force")r=!0;else{if(h==="--run"||h==="--yes"||h==="--all")continue;h==="--scope"?t=e[++u]:h?.startsWith("--scope=")?t=h.slice(8):h==="--concurrency"?s=i(e[++u]):h?.startsWith("--concurrency=")?s=i(h.slice(14)):h&&!h.startsWith("--")&&(n=h)}}let a=u=>u?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:a(t),path:a(n),preview:o,concurrency:s,rewrite:r}}function mk(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function gk(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Ya(e,t,n){return n.filter(o=>{try{return vp(xp(e,t,o)).size===0}catch{return!0}})}function Ka(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+=vp(xp(e,i)).size}catch{}return{path:r,bytes:s}})}function za(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.
|
|
362
362
|
`:"";return`Run the write-article skill to author EACH documentation article listed below. For each path:
|
|
363
363
|
- 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).
|
|
364
364
|
- 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).
|
|
@@ -368,129 +368,129 @@ ${a[1]??" "}clipTo: ${u}${i.selector}${u},`);return h=h.replace(o,`${r}await ca
|
|
|
368
368
|
- 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.
|
|
369
369
|
Articles:
|
|
370
370
|
`+e.paths.map(r=>`- ${r}`).join(`
|
|
371
|
-
`)}function Xa(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"} across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(i=>` \u2022 ${i.label} \u2014 ${i.paths.length} article${i.paths.length===1?"":"s"}`),"",`Estimated cost: ${We(r)}\u2013${We(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function Ja(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),i=e.reduce((C,S)=>C+o(S),0),a=r.reduce((C,S)=>C+o(S),0),u=e.reduce((C,S)=>C+S.costUsd,0),h=e.reduce((C,S)=>C+S.outputTokens,0),g=n==="api"?`${We(u)} total`:Ft(h),k=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,x=C=>`${C} article${C===1?"":"s"}`,T=[];if(s.length===0)T.push(`Wrote ${x(i)} (${k}) successfully \xB7 ${g}.`),T.push("Next \u2014 an editorial review, because these were written by an AI:"),T.push("/review --fix"),T.push("It reads every article and applies its fixes; /publish --all then pushes them up (add screenshots first with /screenshot author --all if you want them).");else{T.push(`Wrote ${a}/${x(i)} (${k}) \xB7 ${g}.`),T.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let C of s)T.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return T}function Qa(e,t,n){try{let o=
|
|
372
|
-
`)}var nl="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function
|
|
373
|
-
`)}var il="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
|
|
371
|
+
`)}function Xa(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"} across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(i=>` \u2022 ${i.label} \u2014 ${i.paths.length} article${i.paths.length===1?"":"s"}`),"",`Estimated cost: ${We(r)}\u2013${We(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function Ja(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),i=e.reduce((C,S)=>C+o(S),0),a=r.reduce((C,S)=>C+o(S),0),u=e.reduce((C,S)=>C+S.costUsd,0),h=e.reduce((C,S)=>C+S.outputTokens,0),g=n==="api"?`${We(u)} total`:Ft(h),k=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,x=C=>`${C} article${C===1?"":"s"}`,T=[];if(s.length===0)T.push(`Wrote ${x(i)} (${k}) successfully \xB7 ${g}.`),T.push("Next \u2014 an editorial review, because these were written by an AI:"),T.push("/review --fix"),T.push("It reads every article and applies its fixes; /publish --all then pushes them up (add screenshots first with /screenshot author --all if you want them).");else{T.push(`Wrote ${a}/${x(i)} (${k}) \xB7 ${g}.`),T.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let C of s)T.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return T}function Qa(e,t,n){try{let o=sk({cwd:e,paths:n.map(s=>`${t}/${s}`)});if(o.length===0)return null;let r=new Set(o.map(s=>s.path)).size;return`\u26A0 Doc-checker: ${o.length} issue${o.length===1?"":"s"} in ${r} of the new article${r===1?"":"s"} (leaked internals / unknown commands / stale facts / AI-tells / em dashes) \u2014 /check --fix corrects them.`}catch{return null}}function Ss(e,t,n){let o=(Cp(e)?.docsDir??lk).replace(/\/+$/,""),r=t.map(a=>a.path);if(n.path){let a=mk(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=gk(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=Ya(e,o,s);if(i.length===0){let a=n.scope?` under "${n.scope}"`:"",u=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${u} --rewrite to regenerate them all.`}}return{docsDir:o,targets:i,planCount:r.length}}function Za(e,t,n){let{targets:o}=Ss(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:Ga(s),count:i}))}async function Rp(e,t){if(!Cp(t.cwd))return console.log(j("No d360-writer config here. Run /init first.")),{kind:"continue"};if(qo(e)){for(let N of bp(t.cwd,t.profileName))console.log(b(N));return{kind:"continue"}}let n=ak(t.cwd);if(n.length===0)return console.log(j("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};if(Ht("write",e)){let N=Za(t.cwd,n,{rewrite:Go(e).rewrite}),V=Vn(t.cwd,"write",e,t.profileName,N);if(V.length>0){for(let K of V)console.log(b(K));return{kind:"continue"}}}let{scope:o,path:r,preview:s,concurrency:i,rewrite:a}=Go(e),{docsDir:u,targets:h,reason:g,rewriting:k}=Ss(t.cwd,n,{scope:o,path:r,rewrite:a});if(h.length===0)return console.log(g?W(g):W("Nothing to write.")),{kind:"continue"};k&&console.log(W(`--rewrite: regenerating ${h.length} already-written article${h.length===1?"":"s"} (overwrites them; git has your baseline).`));let x=ik(h),T=Va(i),{model:C,forced:S}=ck(t.cwd,"standard"),R=!!r;if(s&&!R){let N=rk({files:Ka(t.cwd,n,h),op:"write",model:C});o&&console.log(b(`Scope: ${o} (${h.length} pending).`));for(let V of Xa(x,N,T))console.log(V);return console.log(b(`Model: ${C}${S?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(b(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}console.log(b(`Writing ${h.length} article${h.length===1?"":"s"} across ${x.length} partition${x.length===1?"":"s"} (\u2264${T} agents at once) on ${C}\u2026`)),console.log(b(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let N of uk({cwd:t.cwd,partitions:x,promptFor:V=>za(V,u,{rewrite:k||R}),concurrency:T,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:C}))if(N.type==="partition_status")N.status==="running"?console.log(b(` \u25B8 ${N.label} \u2014 writing\u2026`)):N.status==="done"?console.log(B(` \u2713 ${N.label}`)):console.log(j(` \u2717 ${N.label}`));else if(N.type==="run_done"){console.log("");let V=process.env.ANTHROPIC_API_KEY?"api":"subscription",K=pt(N,"The write");if(K){for(let ae of K)console.log(W(ae));continue}for(let ae of Ja(N.results,x,V))console.log(N.ok?B(ae):W(ae));if(N.ok)try{dk(t.cwd,h.map(ae=>`${u}/${ae}`),{writtenCap:pk,reviewedCap:0,checkedCap:0})}catch{}let G=Qa(t.cwd,u,h);G&&console.log(W(G))}}catch(N){console.log(j(`Write run failed: ${N.message}`))}return console.log(""),{kind:"continue"}}Q();import{existsSync as wk,readdirSync as Sp,statSync as Pp}from"node:fs";import{join as Tp}from"node:path";import{inputDir as yk,readProjectConfig as kk}from"document360-engine";var Ep=/\.(md|markdown|pdf|txt)$/i;function el(e){let t=yk(e);if(!wk(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of Sp(t)){let s=Tp(t,r),i=!1;try{i=Pp(s).isDirectory()}catch{continue}if(i){if(r.startsWith("."))continue;let a=bk(s);a>0&&n.push({name:r,docCount:a})}else Ep.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function bk(e){let t=0;for(let n of Sp(e))try{Pp(Tp(e,n)).isFile()&&Ep.test(n)&&t++}catch{}return t}function tl(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 Ps(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(`
|
|
372
|
+
`)}var nl="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function Ap(e,t){let n=t?.cwd??process.cwd();if(!kk(n))return console.log(j("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=el(n);if(o.length===0&&r===0)return console.log(b(nl)),{kind:"continue"};let s=e.join(" ").trim();if(!s){if(o.length>1){console.log(b("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let u of o)console.log(` ${u.name} ${b(`(${u.docCount} doc${u.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let a=o[0]?.name??"";return{kind:"forward-to-agent",prompt:Ps(a),display:a?`/draft ${a}`:"/draft"}}let i=tl(o,s);return{kind:"forward-to-agent",prompt:Ps(i??"",i?void 0:s),display:`/draft ${s}`}}Q();import{listOpenForDocs as $k,readProjectConfig as vk}from"document360-engine";function ol(e){try{return $k(e).filter(t=>t.kind==="request").length}catch{return 0}}function rl(e){let t=e.includes("--publish"),n=e.includes(ft),o=e.filter(r=>!r.startsWith("--")).join(" ").trim();return{publish:t,skipReview:n,what:o}}function sl(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(`
|
|
373
|
+
`)}var il="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 Dp(e,t){let n=t?.cwd??process.cwd();if(!vk(n))return console.log(j("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=rl(e);if(!r&&ol(n)===0)return console.log(b(il)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:sl(r),display:s}}Q();import{search as xk}from"@inquirer/prompts";import{findByName as Ck,getSession as Rk,listSessions as Sk,relativeTime as jp}from"document360-engine";async function Ip(e,t){let n=Sk(t.cwd).filter(o=>o.uuid!==t.currentUuid());if(n.length===0)return console.log(b("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=Ck(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(j(`No session matches "${o}".`)),Np(n),{kind:"continue"})}if(!process.stdin.isTTY)return Np(n),console.log(b("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>xk({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} ${jp(a.updatedAt)}`,value:a.uuid,description:a.firstPrompt.slice(0,100)}))}})),r=Rk(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function Np(e){console.log("");for(let t of e.slice(0,15))console.log(` ${q(t.name)} ${b(jp(t.updatedAt))}`),console.log(` ${b(t.firstPrompt.slice(0,80))}`);console.log("")}Q();import{renameSession as Pk}from"document360-engine";function al(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 Op(e,t){let n=al(e.join(" "));if(!n)return console.log(j("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(Pk(o,n)?console.log(B(`\u2713 Session renamed to "${n}"`)):console.log(j("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(B(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as Lp,readProjectConfig as Tk,writeProjectConfig as Ek}from"document360-engine";Q();function ll(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=Tk(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 Lp().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},Ek(o,e),null):`Unknown environment "${r}". Known: ${Lp().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function _p(e,t){let n=e[0];if(!n)return Hr(t.cwd),{kind:"continue"};if(n==="add"){let o=ll(t.cwd,e[1],e[2]);return o?(console.log(j(o)),{kind:"continue"}):(console.log(B(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${q(`/profile ${e[1]}`)} then ${q("/login")}`),console.log(b(" Until you switch, this repo keeps using the current profile\u2019s environment.")),{kind:"continue"})}return qr(t.cwd,n),Gr(t.cwd,n),console.log(b(" Restarting agent for the new profile\u2026")),{kind:"clear"}}Q();import{select as Ak}from"@inquirer/prompts";import{readProjectConfig as Dk,readUserConfig as Mp,resolveModelSetting as cl,writeUserConfig as Up}from"document360-engine";var mt=[{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 Ts(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=mt.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function Nk(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 Vo(e,t){let n=()=>cl(e).model;if(t==="default"){let s=Mp();return s.defaultModel?(delete s.defaultModel,Up(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${cl(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}}Up({...Mp(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=Dk(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 Fp(e,t){let n=e[0]?.trim();if(!n){let i=cl(t.cwd);if(!process.stdin.isTTY)return console.log(`${je("Model:")} ${q(i.model)}${i.source==="auto"?b(" (auto)"):""}`),console.log(b(` source: ${Nk(i)}`)),console.log(b(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let a=Ts(i),u;try{u=await t.withPausedInput(()=>Ak({message:`Select model (current: ${i.model}${i.source==="auto"?" \xB7 auto":""})`,default:mt[a].value,choices:mt.map((x,T)=>({name:`${x.label}${T===a?" \u2714":""}`,value:x.value,description:x.desc}))}))}catch{return console.log(b("Cancelled.")),{kind:"continue"}}let{lines:h,changed:g,effective:k}=Vo(t.cwd,u??"default");for(let x of h)console.log(x.startsWith("\u26A0")?W(x):x.startsWith("\u2713")?B(x):b(x));return g&&await t.setModel(k),{kind:"continue"}}let{lines:o,changed:r,effective:s}=Vo(t.cwd,n);for(let i of o)console.log(i.startsWith("\u26A0")?W(i):i.startsWith("\u2713")?B(i):b(i));return r&&await t.setModel(s),{kind:"continue"}}Es();async function Vp(e,t){return await t.withPausedInput(()=>On(t.cwd)),{kind:"clear"}}async function Yp(e,t){return await t.withPausedInput(()=>Ur(t.cwd,t.profileName)),{kind:"clear"}}Q();import{resolveActiveProfile as Jk}from"document360-engine";async function Kp(e,t){let n=!1;try{n=Jk(t.cwd).production}catch{}return n?(console.log(W("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(b("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}Q();var zp=async(e,t)=>{try{await t.withPausedInput(()=>Br({}))}catch(n){console.log(j(`Login failed: ${n.message}`))}return{kind:"continue"}};import{resolveActiveProfile as Qk,clearTokens as Zk,clearProfileProject as eb}from"document360-engine";Q();async function Xp(e,t){let n,o;try{let i=Qk(t.cwd,t.profileName);n=i.name,o=i.connection.name}catch(i){return console.log(j(i.message)),{kind:"continue"}}let r=Zk(n);eb(t.cwd,n),console.log(r?B(`\u2713 Signed out of "${n}" and cleared its project/workspace selection.`):b(`Profile "${n}" was not signed in. Cleared any project/workspace selection.`)),console.log(b(`Run /login to sign back in to "${n}" (the ${o} environment) and pick a project.`));let s=Ot(t.cwd,t.profileName);return console.log(s?W(`\u26A0 ${s.why}. Signing out doesn\u2019t change the environment \u2014 ${s.cmd} does.`):b(" Different environment? That comes from the profile, not the login \u2014 /profile add <environment>.")),{kind:"continue"}}import{spawn as Qp}from"node:child_process";import{existsSync as pl,readFileSync as dl,statSync as lb}from"node:fs";import{homedir as cb}from"node:os";import{basename as ub,join as Jo}from"node:path";import{readProjectConfig as db,DEFAULT_OUTPUT_DIR as pb,existingAnnotatedShotPath as hb,resolveOutputDir as fb}from"document360-engine";import He from"picocolors";import{annotationsPath as tb,resolveOutputDir as nb,readProjectConfig as ob,DEFAULT_OUTPUT_DIR as rb,existingAnnotatedShotPath as sb}from"document360-engine";function ib(e){let n=e.filter(o=>o!=="--all"&&o!=="-a").find(o=>!o.startsWith("-"));return n?{mode:"single",id:n}:{mode:"all"}}function Ko(e){return e.filter(t=>t.state==="captured").map(t=>t.id)}function wn(e,t){let n=nb(e,ob(e)?.outputDir??rb),o=new Map(Ae(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(sb(n,i))}`,` facts: ${r(tb(n,i))}`,` article: ${a}`].join(`
|
|
374
374
|
`)}).join(`
|
|
375
375
|
`);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(`
|
|
376
|
-
`)}function
|
|
377
|
-
`)}function
|
|
376
|
+
`)}function zo(e){return`${oe("\u2192",He.blue)}Verifying ${e} new screenshot${e===1?"":"s"} (reading each image)\u2026`}var ab=(e,t=88)=>{let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n};function Xo(e,t){if(t.length===0)return[];let n=vt(e).shots,o=[],r=[],s=[];for(let a of t){let u=n[a]?.review;u?u.verdict==="ok"?o.push(a):r.push({id:a,reason:u.reason??"no reason recorded",repaired:!!u.repaired}):s.push(a)}let i=[""];if(i.push(`${oe("\u2714",He.green)}${He.green(`${o.length} verified`)}`+(r.length>0?` ${He.magenta(`\u2691 ${r.length} flagged`)}`:"")+(s.length>0?` ${He.yellow(`? ${s.length} not verified`)}`:"")+He.gray(` ${t.length} shot${t.length===1?"":"s"} in this pass`)),r.length>0){let a=Math.max(...r.map(h=>h.id.length));for(let h of r)i.push(` ${He.magenta(h.id.padEnd(a))} ${He.gray(ab(h.reason))}`);let u=r.filter(h=>h.repaired).length;i.push(`${oe("\u2192",He.magenta)}Re-capture the ${r.length} flagged: ${He.bold("/screenshot capture --failed")}`+(u<r.length?He.gray(` (${r.length-u} still need${r.length-u===1?"s":""} a spec fix first)`):""))}return s.length>0&&i.push(`${oe("\u26A0",He.yellow)}No verdict recorded for ${s.slice(0,3).join(", ")}${s.length>3?`, +${s.length-3}`:""} \u2014 still awaiting verification. Run ${He.bold("/screenshot verify")} again.`),i}async function Jp(e,t){let n=t?.cwd??process.cwd(),o=Lo(n);o&&console.log(o);let r=Ae(n),s=ib(e);if(s.mode==="single"){let a=r.find(u=>u.id===s.id);return a?["captured","verified","rejected"].includes(a.state)?{kind:"forward-to-agent",prompt:wn(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=Ko(r);if(i.length===0){let a=r.filter(h=>h.state==="verified").length,u=r.filter(h=>h.state==="rejected").length;return console.log(u>0?`Nothing left to verify. ${u} shot${u===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:wn(n,i),display:"/screenshot verify"}}var mb=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function hl(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:mb(t),retryBlocked:n}:{mode:"single",id:t}:{mode:"picker"}}function Qo(e,t){let n=Ae(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 Zp(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}),ls(o,t,"capture"),$a(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 fl(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([...gd(e).filter(r=>n.has(r)),...o])].sort()}function ml(e,t){let n=e.length;if(n===0)return null;let o=Mo(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(`
|
|
377
|
+
`)}function gb(e,t){let n=db(e)?.outputDir??pb;return hb(fb(e,n),t)}function gl(e,t,n,o){let r=gb(e,t);return pl(r)&&lb(r).mtimeMs>=o?"captured":n===0?"skipped":"failed"}function eh(e){let t=/⊘[^\n—]*—\s*(.+)/.exec(e);return t?t[1].trim():null}var wb=/element is not (?:enabled|visible|stable|editable)|intercepts pointer events|outside of the viewport|element is not attached/i;function th(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=>wb.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(`
|
|
378
378
|
`):wl(e)}function wl(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(`
|
|
379
|
-
`)}var
|
|
380
|
-
`)}function
|
|
381
|
-
/screenshot list --detail shows what each one needs`}function
|
|
382
|
-
`),cmd:o.length>0?`/screenshot ${a}`:t.length>0?s:i,tone:o.length>0?"warn":"info"}}function
|
|
383
|
-
`),display:"/screenshot checklist"}}var
|
|
384
|
-
`)}async function
|
|
385
|
-
`).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 Ns(e,t){let n=fh(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=Tb(e);if(!o)return[{tone:"info",text:"Sharing: unavailable \u2014 this folder is not a git repository."}];if(!o.upstream)return[{tone:"warn",text:oe("\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:oe("\u26A0")+`${o.ahead} change${Qo(o.ahead)} not shared yet \u2014 run /share`}):s.push({tone:"ok",text:oe("\u2713")+"Everything is shared with your team."}),s}function Cl(e,t,n){hh({...t,gitHandoff:{commit:n,push:n}},e);let o=n?{tone:"ok",text:oe("\u2713")+"Sharing on \u2014 d360-writer will save and send its own work from now on."}:{tone:"ok",text:oe("\u2713")+"Sharing off \u2014 d360-writer will leave its work for your coding agent to commit."};return n?[o,...Ns(e,{...t,gitHandoff:{commit:!0,push:!0}})]:[o]}async function js(e,t){let n=[],o=fh(t);if(!o.commit)return{lines:[{tone:"info",text:qt("disabled")}],changed:!1};let r=t;o.push==="unconfirmed"&&Eb(e,t)&&(r={...t,gitHandoff:{commit:!0,push:!0}},hh(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 Pb(e);if(s.ok&&s.pulled>0){let h=[s.newHints>0?`${s.newHints} new hint${Qo(s.newHints)}`:null,s.newMessages>0?`${s.newMessages} new message${Qo(s.newMessages)}`:null].filter(Boolean);n.push({tone:"ok",text:oe("\u2B07")+`Got your builder's latest${h.length?` \u2014 ${h.join(", ")}`:""}.`})}else!s.ok&&s.reason!=="no-upstream"&&s.reason!=="no-git"&&n.push({tone:"warn",text:oe("\u26A0")+qt(s.reason,s.detail)});let i=await Sb(e,r);if(i.commit&&!i.commit.ok)return n.push({tone:"warn",text:oe("\u26A0")+qt(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:oe("\u2713")+`Saved ${a} change${Qo(a)} to the docs folder.`}),i.push&&!i.push.ok)return n.push({tone:"warn",text:oe("\u26A0")+qt(i.push.reason,i.push.detail)}),{lines:n,changed:a>0};let u=i.push?.ok?i.push.pushed:0;return u>0?n.push({tone:"ok",text:oe("\u2B06")+`Shared ${u} change set${Qo(u)} with your team.`}):a===0&&(s.ok&&s.pulled===0)?n.push({tone:"ok",text:oe("\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||u>0||s.ok&&s.pulled>0}}var Ab={ok:B,info:fe,warn:W,error:j};async function mh(e,t){let n=t.cwd,o=Rb(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 u of a)console.log(Ab[u.tone](u.text))};if(r==="status")return s(Ns(n,o)),{kind:"continue"};if(r==="on"||r==="off")return s(Cl(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(b("Exchanging work with your team\u2026"));let{lines:i}=await js(n,o);return s(i),{kind:"continue"}}function yn(e){let t=0,n=0,o=0,r=0;try{t=Db(e).length}catch{}try{let s=Nb(e);n=s.filter(i=>i.kind==="request").length,o=s.filter(i=>i.kind==="answer").length}catch{}try{r=jb(e).length}catch{}return{hints:t,requests:n,answers:o,directives:r}}async function Pl(e){let t=gh(e);if(!t)return[];if(!Fb(e,t))return[];let n=await Ub(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 ${qt(n.reason,n.detail)}`}]}function Zo(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 Tl(e){return{publish:e.includes("--publish"),skipReview:e.includes(ft)}}function El(){let e=["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).","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)."];return e.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 and let them run the review and the publish."),e.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."),e.join(`
|
|
386
|
-
`)}var Wb={status:Ib,plan:Ob,apply:Lb,planImport:_b,applyImport:Mb};async function Al(e,t=Wb){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 Rl=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Sl=e=>e===1?"":"s";function Dl(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${Sl(e.pulled.length)} into local: ${Rl(e.pulled)}`),e.imported.length&&t.push(`\u2713 Imported ${e.imported.length} new portal article${Sl(e.imported.length)} into local drafts: ${Rl(e.imported)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${Sl(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${Rl(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 wh(e,t){let n=t?.cwd??process.cwd();if(!gh(n))return console.log(j("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Be(n,t?.profileName);if(!o.ok)return console.log(j(o.reason)),{kind:"continue"};let{publish:r}=Tl(e);for(let a of await Pl(n))console.log(a.tone==="ok"?B(a.text):W(a.text));console.log(b("Reconciling with Document360 (pulling any portal changes)\u2026"));let s=await Al({cwd:n,profileName:t?.profileName});for(let a of Dl(s))console.log(a.startsWith("\u2713")?B(a):a.startsWith("\u2139")?b(a):W(a));let i=Zo(yn(n));return console.log(b(i?`Catching up on ${i}\u2026`:"Checking for code changes the builder didn't hint\u2026")),{kind:"forward-to-agent",prompt:El(),display:`/catch-up${r?" --publish":""}`}}Q();import{resolveActiveProfile as Bb,resolveProjectId as Hb,loadProfileMap as qb,readCommentLedger as Gb,isCommentOpen as Vb,saveOpenCommentCount as Yb,sweepOpenComments as Kb,commentHtmlToText as yh,annotatedText as zb,readProjectConfig as Xb,loadPortalLabels as Jb,portalBreadcrumb as Qb,portalCategoryPath as Zb,resolveModelForOperation as e$,runPartitioned as t$,EMPTY_PORTAL_LABELS as n$}from"document360-engine";import we from"picocolors";var kh=300,o$=3,er=3;function r$(e,t){let n=zu(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||Wn(n).toLowerCase()===o}async function jl(e,t,n={}){let o=Bb(e,t),r={profile:o.name,connection:o.connection},s=Hb(r,o.project.projectId),i=qb(e,o.name);if(!i)return{threads:[],answered:[],labels:n$,scanned:0,failed:[],truncated:0};let a=Gb(e,o.name),u=new Set(Object.values(a).map(N=>N.articlePath).filter(N=>!!N)),h=Object.keys(a).length===0||u.size>0,g=n.articleIds?.length?new Set(n.articleIds):null,k=!!(g||n.path||n.scope),x=Object.entries(i.articles).filter(([,N])=>!!N.id).filter(([N,V])=>g?g.has(V.id):n.path?N.replace(/\\/g,"/")===n.path.replace(/\\/g,"/"):n.scope?r$(N,n.scope):!0).map(([N,V])=>({articleId:V.id,path:N,title:Xu(e,N),answered:k||(h?u.has(N):!0)})),T=x.slice(0,kh),C=o.project.languageCode,S=await Kb(r,s,T,{isOpen:(N,V)=>Vb(a,N,V),...C?{langCode:C}:{},...n.onProgress?{onProgress:n.onProgress}:{}});k||Yb(e,o.name,S.threads.length);let R=await Jb(r,s,o.project.workspaceId,{cwd:e,profile:o.name});return{threads:S.threads,answered:S.answered,labels:R,scanned:S.scanned,failed:S.failed,truncated:Math.max(0,x.length-T.length)}}function Nl(e,t=96){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n}function s$(e){let t=zb(e.comment);if(!t)return"a passage";let n=e.comment.commented_text_truncated?"\u2026":"";return`\u201C${Nl(t,48)}${n}\u201D`}function i$(e,t){let n=Zb(t,e.articleId);return n.length>0?n.join(" \u203A "):e.path?Wn(e.path):""}function a$(e,t){return t.articles.get(e.articleId)?.title?.trim()||e.title||(e.path?Vi(e.path):e.articleId)}function l$(e,t){return Qb(t,e.articleId,{category:e.path?Wn(e.path):null,title:e.title??(e.path?Vi(e.path):null)})??e.path??e.articleId}function zn(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:i$(o,t),title:a$(o,t),label:l$(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))}function Is(e,t={}){let n=[],o=u=>u===1?"":"s",r=e.answered.length,s=r>0?` ${we.gray("\xB7")} ${r} answered, awaiting reviewer`:"",i=()=>{if(!(!t.showAnswered||r===0)){n.push(` ${we.gray(`Answered, waiting on the reviewer (${r})`)}`);for(let u of zn(e.answered,e.labels))n.push(` ${we.gray(`${u.label} \u2014 ${u.threads.length} thread${o(u.threads.length)}`)}`);n.push("")}};if(e.threads.length===0)return n.push(`${oe("\u2713",we.green)}No open reviewer comments across ${e.scanned} article${o(e.scanned)}.${s}`),r>0?(n.push(we.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(we.gray(" /comments --answered lists them."))):n.push(we.gray(" Reviewers leave these by highlighting text in a draft in the Document360 portal and commenting on it.")),n.push(""),i(),e.failed.length&&n.push(`${oe("\u26A0",we.yellow)}${e.failed.length} article${o(e.failed.length)} couldn\u2019t be checked this time \u2014 they may have comments.`),n;let a=zn(e.threads,e.labels);n.push(`${we.bold("Reviewer comments")} ${e.threads.length} open ${we.gray("\xB7")} ${a.length} article${o(a.length)}${s} ${we.gray("\xB7")} ${e.scanned} checked`),n.push("");for(let u of a){n.push(` ${we.cyan(u.label)}`);let h=t.full?u.threads:u.threads.slice(0,o$);for(let k of h){n.push(` ${oe("\u25CF",we.blue)}${we.gray(s$(k))} ${Nl(yh(k.comment.comment))}`);let x=k.comment.replies??[];x.length>0&&n.push(` ${we.gray(`\u21B3 ${x.length} repl${x.length===1?"y":"ies"} \u2014 latest: ${Nl(yh(x[x.length-1]?.comment),72)}`)}`),k.canResolve||n.push(` ${we.gray("(you can reply, but not resolve this one \u2014 your role lacks the permission)")}`)}let g=u.threads.length-h.length;g>0&&n.push(` ${we.gray(`+${g} more comment${o(g)} on this article`)}`),n.push("")}return i(),e.failed.length&&n.push(`${oe("\u26A0",we.yellow)}${e.failed.length} article${o(e.failed.length)} couldn\u2019t be checked this time \u2014 they may have comments too.`),e.truncated&&n.push(`${oe("\u26A0",we.yellow)}Checked the first ${kh} articles; ${e.truncated} not checked this run.`),n}function bh(e,t){let n=zn(e,t),o=[],r=i=>i===1?"":"s";n.length>1&&o.push({kind:"all",label:`Answer all ${e.length} comment${r(e.length)} (${n.length} articles)`,articleIds:n.map(i=>i.articleId),paths:n.map(i=>i.path).filter(i=>!!i),count:e.length,indent:!1});let s=new Map;for(let i of n){let a=s.get(i.category);a?a.push(i):s.set(i.category,[i])}for(let[i,a]of s){let u=a.reduce((h,g)=>h+g.threads.length,0);a.length>1&&o.push({kind:"category",label:`${i||"(root)"} (${u})`,articleIds:a.map(h=>h.articleId),paths:a.map(h=>h.path).filter(h=>!!h),count:u,indent:!1});for(let h of a)o.push({kind:"article",label:a.length>1?h.title:h.label,articleIds:[h.articleId],paths:h.path?[h.path]:[],count:h.threads.length,indent:a.length>1,note:`${h.threads.length} comment${r(h.threads.length)}`})}return o}function c$(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 (publish-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 Il(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.`,"",...c$({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 /publish makes it live."].join(`
|
|
387
|
-
`)}function Ol(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==="--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
|
|
388
|
-
`).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function
|
|
379
|
+
`)}var yb=/^[A-Za-z0-9._-]+$/;function yl(e){return new Promise((t,n)=>{if(!yb.test(e.id)){n(new Error(`Not a valid spec id: "${e.id}"`));return}let o=Qp(`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 nh(e,t=cb()){try{let n=JSON.parse(dl(Jo(e,".d360-writer","capture.json"),"utf8").replace(/^/,"")),o=n.projectId;if(!o)try{o=JSON.parse(dl(Jo(e,"package.json"),"utf8")).name}catch{}o||=ub(e);let r=Object.keys(n.profiles??{}),s=n.defaultProfile??(r.length===1?r[0]:r.includes("staging")?"staging":r[0]);return s?pl(Jo(t,".document360-capture","auth-states",o,`${s}.json`)):!0}catch{return!0}}function oh(e){return new Promise((t,n)=>{let o=Qp("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 kl(e,t){return e===127||/is not recognized as an internal or external command|command not found/i.test(t)}function rh(e){try{let t=JSON.parse(dl(Jo(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 Ds(e){return pl(Jo(e,".d360-writer","capture.json"))}function bl(){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(`
|
|
380
|
+
`)}function sh(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(", ")}
|
|
381
|
+
/screenshot list --detail shows what each one needs`}function ih(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):As(r?.reason)!==As(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):ms(r?.reason??"")!==ms(o.detail??"")?n.blockedNewReason.push(o.id):n.blockedAsBefore.push(o.id))}return n}function As(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 ah(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?qn(o.detail):"no reason recorded"}`)}function Yn(e,t=2){return e.length<=t?e.join(" \xB7 "):`${e.slice(0,t).join(" \xB7 ")} \xB7 +${e.length-t}`}function lh(e,t){if(!t)return[];let n=[],o=(i,a,u,h)=>{a>0&&n.push({glyph:i,label:`${a} ${u}`,tail:h})};if(o("\u2713",e.newlyCaptured.length,"newly captured",Yn(e.newlyCaptured)),o("\u2717",e.newlyBroken.length,"newly broken",Yn(e.newlyBroken)),o("\u2192",e.repairedNowBlocked.length,"repaired",`no longer broken \u2014 only data stands in the way \xB7 ${Yn(e.repairedNowBlocked)}`),o("\u2298",e.newlyBlocked.length,"newly blocked",Yn(e.newlyBlocked)),o("\u2192",e.blockedNewReason.length,"blocked on something new",`an earlier step now passes \xB7 ${Yn(e.blockedNewReason)}`),o("\u2192",e.brokeDifferently.length,"broken differently",`the previous cause is fixed \xB7 ${Yn(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 ch(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?`/publish ${e.articles[0]}`:"/publish --screenshots",i=e.ids.length===1?`/screenshot capture ${e.ids[0]}`:"/screenshot capture",a=o[0]?.id,u=[];o.length>0&&u.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&&u.push({glyph:"\u2298",cmd:"/screenshot list",why:`what to stage for the ${n.length} blocked shot${r(n.length)}`}),t.length>0&&u.push({glyph:"\u2713",cmd:s,why:`embed the ${t.length} new PNG${r(t.length)}`});let h=Math.max(...u.map(k=>k.cmd.length));return{note:u.map(k=>`${k.glyph} ${k.cmd.padEnd(h)} ${k.why}`).join(`
|
|
382
|
+
`),cmd:o.length>0?`/screenshot ${a}`:t.length>0?s:i,tone:o.length>0?"warn":"info"}}function uh(e,t){let n=new Map(Ae(e).map(o=>[o.id,o.file]));return[...new Set(t.map(o=>n.get(o)).filter(o=>!!o))].sort()}async function $l(e,t){let n=t?.cwd??process.cwd(),o=hl(e);if(!Ds(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}=Qo(n,o.mode==="scope"?o.scope:void 0),u=fl(n,a),h=(o.mode==="all"||o.mode==="scope")&&o.retryBlocked,g=o.mode==="single"?[o.id]:o.mode==="failed"?u:o.mode==="blocked"?i:o.mode==="picker"?r:[...r,...s,...h?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(!h&&o.mode!=="single"&&o.mode!=="failed"&&o.mode!=="blocked"){let S=ml(a.filter(R=>R.state==="blocked"),"/screenshot capture --blocked");S&&console.log(S)}let k=Date.now(),x=[];for(let S of g){console.log(`\u25B6 ${S}`);try{let{exitCode:R}=await yl({cwd:n,id:S,stdio:"inherit"});x.push({id:S,outcome:gl(n,S,R,k)})}catch(R){if(R.code==="ENOENT")return console.log("d360-capture is not installed. Run: npm i -g document360-capture"),{kind:"continue"};x.push({id:S,outcome:"failed",detail:R.message})}}let T=S=>x.filter(R=>R.outcome===S).length;console.log(`\u2713 ${T("captured")} captured \xB7 \u2298 ${T("skipped")} skipped \xB7 \u2717 ${T("failed")} failed`);let C=x.filter(S=>S.outcome==="captured");return rs(n,x.map(S=>({id:S.id,outcome:S.outcome,reason:S.detail,specSource:pn(n,S.id)})),new Date().toISOString()),C.length>0?(console.log(zo(C.length)),{kind:"forward-to-agent",prompt:wn(n,C.map(S=>S.id)),display:"/screenshot verify"}):{kind:"continue"}}import{builderChannelWired as kb,driftedAnchors as bb,readTestidRequests as $b,testidHandoffPrompt as vb,testidRequestPaths as xb}from"document360-engine";async function Kn(){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(`
|
|
383
|
+
`),display:"/screenshot checklist"}}var dh="-".repeat(64);function ph(e){let t=$b(e);if(t.length===0)return null;let{mdRel:n}=xb(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=vb(e,o),u=bb(t).length,h=u>0?[` \u26A0 ${u} of ${u===1?"them quotes":"them quote"} code that has changed since \u2014 still likely right,`,` but ${u===1?"it says":"they say"} so, and ${u===1?"asks":"ask"} to be found by description instead.`]:[];return kb(e)?{prompt:a,lines:[`\u{1F4CB} Developer hand-off \u2014 ${s} requested across ${i}.`,...h," 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}.`,...h,"\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.)","",dh,a,dh]}}Mt();Q();import{listOpenForDocs as Cb,readProjectConfig as Rb}from"document360-engine";function vl(e){try{return Cb(e).length}catch{return 0}}function xl(){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(`
|
|
384
|
+
`)}async function hh(e,t){let n=t?.cwd??process.cwd();return Rb(n)?vl(n)===0?(console.log(b("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:xl(),display:"/inbox"}:(console.log(j("No d360-writer config here. Run /init first.")),{kind:"continue"})}Q();import{listOpenHints as Nb,listOpenForDocs as jb,listOpenDirectives as Ib,readProjectConfig as wh,computeSyncStatus as Ob,planPull as Lb,applyPull as _b,planImport as Mb,applyImport as Ub,pullDocsUpdates as Fb,handoffAvailable as Wb}from"document360-engine";Q();import{readProjectConfig as Sb,writeProjectConfig as fh,reconcileDocsGit as Pb,pullDocsUpdates as Tb,probeGitState as Eb,resolveGitHandoff as mh,handoffAvailable as Ab}from"document360-engine";var Zo=e=>e===1?"":"s";function qt(e,t){let n=o=>{let r=(o??"").split(`
|
|
385
|
+
`).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 Ns(e,t){let n=mh(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=Eb(e);if(!o)return[{tone:"info",text:"Sharing: unavailable \u2014 this folder is not a git repository."}];if(!o.upstream)return[{tone:"warn",text:oe("\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:oe("\u26A0")+`${o.ahead} change${Zo(o.ahead)} not shared yet \u2014 run /share`}):s.push({tone:"ok",text:oe("\u2713")+"Everything is shared with your team."}),s}function Cl(e,t,n){fh({...t,gitHandoff:{commit:n,push:n}},e);let o=n?{tone:"ok",text:oe("\u2713")+"Sharing on \u2014 d360-writer will save and send its own work from now on."}:{tone:"ok",text:oe("\u2713")+"Sharing off \u2014 d360-writer will leave its work for your coding agent to commit."};return n?[o,...Ns(e,{...t,gitHandoff:{commit:!0,push:!0}})]:[o]}async function js(e,t){let n=[],o=mh(t);if(!o.commit)return{lines:[{tone:"info",text:qt("disabled")}],changed:!1};let r=t;o.push==="unconfirmed"&&Ab(e,t)&&(r={...t,gitHandoff:{commit:!0,push:!0}},fh(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 Tb(e);if(s.ok&&s.pulled>0){let h=[s.newHints>0?`${s.newHints} new hint${Zo(s.newHints)}`:null,s.newMessages>0?`${s.newMessages} new message${Zo(s.newMessages)}`:null].filter(Boolean);n.push({tone:"ok",text:oe("\u2B07")+`Got your builder's latest${h.length?` \u2014 ${h.join(", ")}`:""}.`})}else!s.ok&&s.reason!=="no-upstream"&&s.reason!=="no-git"&&n.push({tone:"warn",text:oe("\u26A0")+qt(s.reason,s.detail)});let i=await Pb(e,r);if(i.commit&&!i.commit.ok)return n.push({tone:"warn",text:oe("\u26A0")+qt(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:oe("\u2713")+`Saved ${a} change${Zo(a)} to the docs folder.`}),i.push&&!i.push.ok)return n.push({tone:"warn",text:oe("\u26A0")+qt(i.push.reason,i.push.detail)}),{lines:n,changed:a>0};let u=i.push?.ok?i.push.pushed:0;return u>0?n.push({tone:"ok",text:oe("\u2B06")+`Shared ${u} change set${Zo(u)} with your team.`}):a===0&&(s.ok&&s.pulled===0)?n.push({tone:"ok",text:oe("\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||u>0||s.ok&&s.pulled>0}}var Db={ok:B,info:fe,warn:W,error:j};async function gh(e,t){let n=t.cwd,o=Sb(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 u of a)console.log(Db[u.tone](u.text))};if(r==="status")return s(Ns(n,o)),{kind:"continue"};if(r==="on"||r==="off")return s(Cl(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(b("Exchanging work with your team\u2026"));let{lines:i}=await js(n,o);return s(i),{kind:"continue"}}function yn(e){let t=0,n=0,o=0,r=0;try{t=Nb(e).length}catch{}try{let s=jb(e);n=s.filter(i=>i.kind==="request").length,o=s.filter(i=>i.kind==="answer").length}catch{}try{r=Ib(e).length}catch{}return{hints:t,requests:n,answers:o,directives:r}}async function Pl(e){let t=wh(e);if(!t)return[];if(!Wb(e,t))return[];let n=await Fb(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 ${qt(n.reason,n.detail)}`}]}function er(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 Tl(e){return{publish:e.includes("--publish"),skipReview:e.includes(ft)}}function El(){let e=["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).","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)."];return e.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 and let them run the review and the publish."),e.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."),e.join(`
|
|
386
|
+
`)}var Bb={status:Ob,plan:Lb,apply:_b,planImport:Mb,applyImport:Ub};async function Al(e,t=Bb){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 Rl=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Sl=e=>e===1?"":"s";function Dl(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${Sl(e.pulled.length)} into local: ${Rl(e.pulled)}`),e.imported.length&&t.push(`\u2713 Imported ${e.imported.length} new portal article${Sl(e.imported.length)} into local drafts: ${Rl(e.imported)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${Sl(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${Rl(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 yh(e,t){let n=t?.cwd??process.cwd();if(!wh(n))return console.log(j("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Be(n,t?.profileName);if(!o.ok)return console.log(j(o.reason)),{kind:"continue"};let{publish:r}=Tl(e);for(let a of await Pl(n))console.log(a.tone==="ok"?B(a.text):W(a.text));console.log(b("Reconciling with Document360 (pulling any portal changes)\u2026"));let s=await Al({cwd:n,profileName:t?.profileName});for(let a of Dl(s))console.log(a.startsWith("\u2713")?B(a):a.startsWith("\u2139")?b(a):W(a));let i=er(yn(n));return console.log(b(i?`Catching up on ${i}\u2026`:"Checking for code changes the builder didn't hint\u2026")),{kind:"forward-to-agent",prompt:El(),display:`/catch-up${r?" --publish":""}`}}Q();import{resolveActiveProfile as Hb,resolveProjectId as qb,loadProfileMap as Gb,readCommentLedger as Vb,isCommentOpen as Yb,saveOpenCommentCount as Kb,sweepOpenComments as zb,commentHtmlToText as kh,annotatedText as Xb,readProjectConfig as Jb,loadPortalLabels as Qb,portalBreadcrumb as Zb,portalCategoryPath as e$,resolveModelForOperation as t$,runPartitioned as n$,EMPTY_PORTAL_LABELS as o$}from"document360-engine";import we from"picocolors";var bh=300,r$=3,tr=3;function s$(e,t){let n=zu(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||Wn(n).toLowerCase()===o}async function jl(e,t,n={}){let o=Hb(e,t),r={profile:o.name,connection:o.connection},s=qb(r,o.project.projectId),i=Gb(e,o.name);if(!i)return{threads:[],answered:[],labels:o$,scanned:0,failed:[],truncated:0};let a=Vb(e,o.name),u=new Set(Object.values(a).map(N=>N.articlePath).filter(N=>!!N)),h=Object.keys(a).length===0||u.size>0,g=n.articleIds?.length?new Set(n.articleIds):null,k=!!(g||n.path||n.scope),x=Object.entries(i.articles).filter(([,N])=>!!N.id).filter(([N,V])=>g?g.has(V.id):n.path?N.replace(/\\/g,"/")===n.path.replace(/\\/g,"/"):n.scope?s$(N,n.scope):!0).map(([N,V])=>({articleId:V.id,path:N,title:Xu(e,N),answered:k||(h?u.has(N):!0)})),T=x.slice(0,bh),C=o.project.languageCode,S=await zb(r,s,T,{isOpen:(N,V)=>Yb(a,N,V),...C?{langCode:C}:{},...n.onProgress?{onProgress:n.onProgress}:{}});k||Kb(e,o.name,S.threads.length);let R=await Qb(r,s,o.project.workspaceId,{cwd:e,profile:o.name});return{threads:S.threads,answered:S.answered,labels:R,scanned:S.scanned,failed:S.failed,truncated:Math.max(0,x.length-T.length)}}function Nl(e,t=96){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n}function i$(e){let t=Xb(e.comment);if(!t)return"a passage";let n=e.comment.commented_text_truncated?"\u2026":"";return`\u201C${Nl(t,48)}${n}\u201D`}function a$(e,t){let n=e$(t,e.articleId);return n.length>0?n.join(" \u203A "):e.path?Wn(e.path):""}function l$(e,t){return t.articles.get(e.articleId)?.title?.trim()||e.title||(e.path?Vi(e.path):e.articleId)}function c$(e,t){return Zb(t,e.articleId,{category:e.path?Wn(e.path):null,title:e.title??(e.path?Vi(e.path):null)})??e.path??e.articleId}function zn(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:a$(o,t),title:l$(o,t),label:c$(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))}function Is(e,t={}){let n=[],o=u=>u===1?"":"s",r=e.answered.length,s=r>0?` ${we.gray("\xB7")} ${r} answered, awaiting reviewer`:"",i=()=>{if(!(!t.showAnswered||r===0)){n.push(` ${we.gray(`Answered, waiting on the reviewer (${r})`)}`);for(let u of zn(e.answered,e.labels))n.push(` ${we.gray(`${u.label} \u2014 ${u.threads.length} thread${o(u.threads.length)}`)}`);n.push("")}};if(e.threads.length===0)return n.push(`${oe("\u2713",we.green)}No open reviewer comments across ${e.scanned} article${o(e.scanned)}.${s}`),r>0?(n.push(we.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(we.gray(" /comments --answered lists them."))):n.push(we.gray(" Reviewers leave these by highlighting text in a draft in the Document360 portal and commenting on it.")),n.push(""),i(),e.failed.length&&n.push(`${oe("\u26A0",we.yellow)}${e.failed.length} article${o(e.failed.length)} couldn\u2019t be checked this time \u2014 they may have comments.`),n;let a=zn(e.threads,e.labels);n.push(`${we.bold("Reviewer comments")} ${e.threads.length} open ${we.gray("\xB7")} ${a.length} article${o(a.length)}${s} ${we.gray("\xB7")} ${e.scanned} checked`),n.push("");for(let u of a){n.push(` ${we.cyan(u.label)}`);let h=t.full?u.threads:u.threads.slice(0,r$);for(let k of h){n.push(` ${oe("\u25CF",we.blue)}${we.gray(i$(k))} ${Nl(kh(k.comment.comment))}`);let x=k.comment.replies??[];x.length>0&&n.push(` ${we.gray(`\u21B3 ${x.length} repl${x.length===1?"y":"ies"} \u2014 latest: ${Nl(kh(x[x.length-1]?.comment),72)}`)}`),k.canResolve||n.push(` ${we.gray("(you can reply, but not resolve this one \u2014 your role lacks the permission)")}`)}let g=u.threads.length-h.length;g>0&&n.push(` ${we.gray(`+${g} more comment${o(g)} on this article`)}`),n.push("")}return i(),e.failed.length&&n.push(`${oe("\u26A0",we.yellow)}${e.failed.length} article${o(e.failed.length)} couldn\u2019t be checked this time \u2014 they may have comments too.`),e.truncated&&n.push(`${oe("\u26A0",we.yellow)}Checked the first ${bh} articles; ${e.truncated} not checked this run.`),n}function $h(e,t){let n=zn(e,t),o=[],r=i=>i===1?"":"s";n.length>1&&o.push({kind:"all",label:`Answer all ${e.length} comment${r(e.length)} (${n.length} articles)`,articleIds:n.map(i=>i.articleId),paths:n.map(i=>i.path).filter(i=>!!i),count:e.length,indent:!1});let s=new Map;for(let i of n){let a=s.get(i.category);a?a.push(i):s.set(i.category,[i])}for(let[i,a]of s){let u=a.reduce((h,g)=>h+g.threads.length,0);a.length>1&&o.push({kind:"category",label:`${i||"(root)"} (${u})`,articleIds:a.map(h=>h.articleId),paths:a.map(h=>h.path).filter(h=>!!h),count:u,indent:!1});for(let h of a)o.push({kind:"article",label:a.length>1?h.title:h.label,articleIds:[h.articleId],paths:h.path?[h.path]:[],count:h.threads.length,indent:a.length>1,note:`${h.threads.length} comment${r(h.threads.length)}`})}return o}function u$(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 (publish-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 Il(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.`,"",...u$({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 /publish makes it live."].join(`
|
|
387
|
+
`)}function Ol(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==="--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 d$(e,t,n){if(t.length===0)return{kind:"continue"};let o=t.reduce((a,u)=>a+u.threads.length,0),{model:r}=t$(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(b(`Answering ${o} comment${o===1?"":"s"} across ${i.length} article${i.length===1?"":"s"} (\u2264${tr} 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 n$({cwd:e.cwd,partitions:i,promptFor:u=>{let h=s.get(u.label);return Il({articleId:h.articleId,label:h.label,path:h.path,count:h.threads.length,resolve:n.resolve})},concurrency:tr,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),allowCommentResolve:n.resolve,model:r}))if(a.type==="partition_status")a.status==="running"?console.log(b(` \u25B8 ${a.label} \u2014 answering\u2026`)):a.status==="done"?console.log(B(` \u2713 ${a.label}`)):console.log(j(` \u2717 ${a.label}`));else if(a.type==="run_done"){let u=a.results.filter(h=>!h.ok);console.log(""),console.log(`${a.results.length-u.length}/${i.length} article${i.length===1?"":"s"} answered.`),u.length&&console.log(W(`\u26A0 ${u.length} left untouched (their comments are still open, so nothing was promised to those reviewers): ${u.map(h=>h.label).join(", ")}`)),a.blocked&&console.log(W(`\u26A0 ${a.blocked}`)),a.allEmpty&&console.log(W("\u26A0 No agent produced any work this run \u2014 nothing was changed or answered."))}}catch(a){console.log(j(`Answering comments failed: ${a.message}`))}return{kind:"continue"}}async function vh(e,t){let n=t?.cwd??process.cwd();if(!Jb(n))return console.log(j("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Be(n,t?.profileName);if(!o.ok)return console.log(j(o.reason)),{kind:"continue"};let r=Ol(e);console.log(b("Checking Document360 for reviewer comments\u2026"));let s;try{s=await jl(n,t?.profileName,r.scope)}catch(i){return console.log(j(`Couldn\u2019t read comments from Document360: ${i.message}`)),{kind:"continue"}}for(let i of Is(s,{full:!!r.scope.path,showAnswered:r.showAnswered}))console.log(i);return s.threads.length===0?{kind:"continue"}:r.answer&&t?d$(t,zn(s.threads,s.labels),{resolve:r.resolve}):(console.log(`${oe("\u2192",we.yellow)}${we.bold("/comments --answer")} fixes each one, updates the draft in Document360, then replies in the thread `+we.gray("(one article at a time: /comments --answer <article>, or --scope <category>)")),{kind:"continue"})}Q();import{spawn as xh}from"node:child_process";var Xn="document360-writer",Os=`npm i -g ${Xn}@latest`,p$="document360-capture";function h$(){return new Promise(e=>{try{let t=xh("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 Ls(){let e=process.platform==="win32",n=await h$()?[Xn,p$]:[Xn];return new Promise(o=>{try{let r=xh(`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 Ch(){console.log(b("Updating the d360-writer toolchain\u2026"));let e=await Ls();return e.ok?console.log(B(`\u2713 Updated ${e.packages.join(" + ")}. Exit (/exit) and relaunch d360-writer to apply.`)):console.log(j(`Update failed \u2014 run manually: ${Os}`)),{kind:"continue"}}Q();Mt();import{existsSync as Ll,rmSync as f$}from"node:fs";import{basename as Rh,resolve as _l}from"node:path";import{execFileSync as m$}from"node:child_process";import{input as g$}from"@inquirer/prompts";import{readProjectConfig as w$,devHintsGuidePath as y$}from"document360-engine";var k$=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],b$=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),_s=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),Sh=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function Ph(e){let t=_s(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:Sh(t)?!0:b$.has(t)}function Ml(e){let t=null;try{t=w$(e)}catch{t=null}let n=new Set(k$);for(let o of[_s(t?.docsDir),_s(t?.captureDir),_s(t?.outputDir)])o&&Sh(o)&&n.add(o);return[...n].filter(o=>Ph(o)&&Ll(_l(e,o)))}function Ul(e,t){let n=[],o=[];for(let r of t){if(!Ph(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{f$(_l(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function Th(e,t){try{return m$("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
|
|
388
|
+
`).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function $$(e){return Th(e,".d360-writer/hints")}function v$(e){return Th(e,".d360-writer/messages")}function Fl(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=$$(e),o=v$(e),r=Ll(_l(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: ${Rh(e)}`]}async function Eh(e,t){let n=Ml(t.cwd);for(let u of Fl(t.cwd,n))console.log(n.length===0?b(u):u);if(n.length===0)return{kind:"continue"};let o=Rh(t.cwd);if((await t.withPausedInput(()=>g$({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(W("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=Ll(y$(t.cwd)),{removed:i,failed:a}=Ul(t.cwd,n);console.log(B(`\u2713 Reset complete \u2014 removed ${i.length} item${i.length===1?"":"s"}. The repo is back to its original state.`));for(let u of a)console.log(j(` \u2717 ${u.path}: ${u.error}`));if(s){for(let u of Qr())console.log(u);console.log(b("(Select and copy the prompt above to paste into your coding agent.)"))}return console.log(b("Set up d360-writer again with /init (then /login, /workspace).")),{kind:"continue"}}Q();import{lintDocs as x$}from"document360-engine";function Ms(e){if(e.length===0)return["\u2713 No issues found \u2014 no leaked internals, unknown commands, stale version facts, AI-tells, or em dashes in the docs."];let t=new Map;for(let o of e){let r=t.get(o.path)??[];r.push(o),t.set(o.path,r)}let n=[`\u26A0 ${e.length} doc issue${e.length===1?"":"s"} in ${t.size} article${t.size===1?"":"s"} (leaked internals / unknown commands / stale facts / AI-tells / em dashes):`];for(let[o,r]of t){n.push(` ${o}`);for(let s of r)n.push(` L${s.line}: "${s.term}" \u2014 ${s.message}`)}return n}function Wl(e){let t=new Map;for(let o of e){let r=t.get(o.path)??[];r.push(o),t.set(o.path,r)}return["The documentation quality check 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.","","How to fix, by issue type:","- internal-leak (an agent codename, an internal skill name, or a d360_* tool name): this is the"," documentation engine's own machinery and must NOT appear in user docs. Reword the sentence to describe"," the behavior in plain user terms, or delete the internal aside. Do NOT swap it for another internal term.","- unknown-command: the named /command or --flag does not exist in the product source. Find the correct"," command/flag in the source and use it; if there is no real equivalent, remove the claim.","- stale-fact: the version contradicts the product's package.json engines. Correct it to the real value.","- ai-tell: a machine-sounding buzzword (e.g. delve, leverage, furthermore, robust). Rewrite the phrase in"," plain, direct developer language; preserve the meaning; do NOT swap one buzzword for another.","- ai-punctuation: an em dash in prose. Recast the sentence with the punctuation a human technical writer"," would have used, chosen per sentence rather than applied uniformly: a comma for a light aside, a colon"," when what follows explains what precedes it, a period when it is really two sentences, parentheses for a"," true aside, or nothing at all when the clause can just be cut. Do NOT swap the em dash for a hyphen, an"," en dash, or a semicolon; that keeps the same tell. Preserve the meaning and keep the sentence readable:"," if a recast reads worse than the original, restructure the sentence instead of forcing a substitution.","- stray-file: a junk *.publish.md file (a publish transform wrongly written to disk). DELETE the file.",' Do not edit it, do not publish it; the real article is its sibling without ".publish". Nothing else changes.',"","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.","","Issues:",[...t.entries()].map(([o,r])=>[o,...r.map(s=>` - L${s.line} [${s.kind}]: "${s.term}": ${s.message}`)].join(`
|
|
389
389
|
`)).join(`
|
|
390
390
|
`)].join(`
|
|
391
|
-
`)}async function
|
|
392
|
-
`);return{prompt:
|
|
393
|
-
`),display:`/reorder${n?` ${n}`:""}`}}async function
|
|
391
|
+
`)}async function Ah(e,t){let n=e.includes("--fix"),o=e.find(i=>!i.startsWith("--")),r=o?` ${o}`:"",s=x$({cwd:t.cwd,scope:o});if(n)return s.length===0?(console.log(B("\u2713 Nothing to fix \u2014 the docs are already clean.")),{kind:"continue"}):(console.log(b(`Fixing ${s.length} doc issue${s.length===1?"":"s"} (run /check again after to confirm)\u2026`)),{kind:"forward-to-agent",prompt:Wl(s),display:`/check${r} --fix`});console.log(b("Linting the docs (engine internals, unknown commands, stale facts, AI-tells, em dashes)\u2026"));for(let i of Ms(s))console.log(s.length===0?B(i):W(i));return s.length>0&&console.log(b("Run /check --fix to have the agent correct these.")),console.log(""),{kind:"continue"}}Q();import{lintDocs as E$,loadStyleGuide as A$,buildReviewPrompt as D$,readProjectConfig as N$,DEFAULT_DOCS_DIR as j$}from"document360-engine";Q();import{readProjectConfig as C$,loadProfileMap as R$,resolveActiveProfile as S$,desiredCategoryOrder as P$,desiredArticleOrder as T$}from"document360-engine";function Dh(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}var Nh=e=>e.replace(/\\/g,"/").split("/").pop()??e;function nr(e,t){try{if(!C$(e))return[];let n=S$(e,t),o=R$(e,n.name);if(!o)return[];let r=new Map;for(let i of T$(o)){let a=r.get(i.categoryPath);a?a.push(i):r.set(i.categoryPath,[i])}let s=[];for(let i of P$(o)){s.push(Dh(Nh(i.path)));for(let a of(r.get(i.path)??[]).sort((u,h)=>u.order-h.order))s.push(` ${Dh(Nh(a.path))}`)}return s}catch{return[]}}async function jh(e,t){let n=nr(t.cwd,t.profileName);if(n.length===0)return console.log(b("No documentation structure yet \u2014 run /init and author some articles first.")),{kind:"continue"};console.log(q("Documentation order (categories \u2192 articles):"));for(let o of n)console.log(o);return console.log(""),{kind:"continue"}}function Bl(e,t){let n=N$(e);if(!n)return null;let o=(n.docsDir??j$).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),s=t.find(g=>!g.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),i=E$({cwd:e}),a=s?i.filter(g=>g.path===`${o}/${s}`||g.path.startsWith(`${o}/${s}/`)):i,u=s?"":nr(e).join(`
|
|
392
|
+
`);return{prompt:D$({docsRoot:o,scope:s,styleGuide:A$(e),deterministicFindings:a,fix:r,structure:u||void 0}),display:`/review${s?` ${s}`:""}${r?" --fix":""}`}}async function Ih(e,t){if(Ht("review",e)){let o=Vn(t.cwd,"review",e,t.profileName);if(o.length>0){for(let r of o)console.log(b(r));return{kind:"continue"}}}let n=Bl(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(j("No d360-writer config here. Run /init first.")),{kind:"continue"})}Q();import{readProjectConfig as I$}from"document360-engine";function Hl(e,t){if(!I$(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 /publish."].filter(Boolean).join(`
|
|
393
|
+
`),display:`/reorder${n?` ${n}`:""}`}}async function Oh(e,t){if(Ht("reorder",e)){let o=Vn(t.cwd,"reorder",e,t.profileName);if(o.length>0){for(let r of o)console.log(b(r));return{kind:"continue"}}}let n=Hl(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(j("No d360-writer config here. Run /init first.")),{kind:"continue"})}Q();import{readProjectConfig as O$,writeProjectConfig as Lh,isAppType as L$,playbookSkillName as _$,detectAppType as _h}from"document360-engine";var Mh=["web","cli","service","library"],M$=new Set(["web","cli"]);function ql(e){return M$.has(e)?`${_$(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function Us(e,t){let n=t.cwd,o=O$(n);if(!o)return console.log(j("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let s=o.appType??_h(n);if(s){let i=o.appType?"set in config":"auto-detected";console.log(`${q("Genre:")} ${s} (${i}) \u2014 ${ql(s)}`)}else console.log(W("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(b(`Set it: /genre <${Mh.join("|")}> \xB7 revert to auto-detect: /genre auto`)),{kind:"continue"}}if(r==="auto"||r==="clear"){if(!o.appType)return console.log(b("Already on auto-detect (no genre set in config).")),{kind:"continue"};let{appType:s,...i}=o;Lh(i,n);let a=_h(n);return console.log(B(`\u2713 Genre reset to auto-detect \u2014 now: ${a?`${a} (${ql(a)})`:"unclassified (no playbook)"}.`)),console.log(b(" Restarting the agent so the loaded playbook matches\u2026")),{kind:"clear"}}return L$(r)?(Lh({...o,appType:r},n),console.log(B(`\u2713 Genre set to ${r} \u2014 ${ql(r)}.`)),console.log(b(" Restarting the agent so the playbook loads\u2026")),{kind:"clear"}):(console.log(j(`Unknown genre "${r}". Choose one of: ${Mh.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}Q();import{listRoadmap as Fs,roadmapProgress as Uh,stampRoadmapDone as U$}from"document360-engine";function Gl(e){let t=Fs(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=Uh(e),o=[`Docs roadmap \u2014 ${n.done} of ${n.total} step${n.total===1?"":"s"} done:`,""];for(let r of t)o.push(` ${r.status==="done"?"\u2713":"\u25CB"} ${r.title}${r.run?` \xB7 ${r.run}`:""}`);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.)"),o}function Ws(e,t){let n=Fs(e).filter(h=>h.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=h=>h.trim().toLowerCase(),s=n.find(h=>r(h.title)===r(o)),i=o?s?[s]:n.filter(h=>r(h.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:
|
|
394
394
|
${i.map(h=>` \u25CB ${h.title}`).join(`
|
|
395
395
|
`)}`};if(i.length===0)return{ok:!1,line:`No open step matches "${o}". Open steps:
|
|
396
396
|
${n.map(h=>` \u25CB ${h.title}`).join(`
|
|
397
|
-
`)}`};let a=i[0].title;
|
|
398
|
-
`):null}function
|
|
397
|
+
`)}`};let a=i[0].title;U$(e,a,{doneAt:new Date().toISOString()});let u=Uh(e)?.next;return{ok:!0,line:`\u2713 Marked done: ${a}${u?` \u2014 next up: ${u.title}${u.run?` (${u.run})`:""}`:" \u2014 that was the last step: campaign complete."}`}}function Vl(e,t){let n=r=>r.trim().replace(/\s+/g," ").toLowerCase(),o=n(t);return o.startsWith("/")?Fs(e).find(r=>r.status==="open"&&!!r.run&&n(r.run)===o)??null:null}function Fh(e,t){let n=Vl(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(`
|
|
398
|
+
`):null}function Wh(e,t){let n=t.trim().toLowerCase();if(!n)return null;let o=Fs(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:
|
|
399
399
|
${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(`
|
|
400
|
-
`):null}async function
|
|
400
|
+
`):null}async function Bh(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let r=Ws(n,e.slice(1).join(" ").trim());return console.log(r.ok?B(r.line):W(r.line)),{kind:"continue"}}let o=Gl(n);console.log(q(o[0]??""));for(let r of o.slice(1))console.log(r.startsWith("(")?b(r):r);return{kind:"continue"}}var Hh={help:Mi,"?":Mi,clear:Cu,exit:Ui,quit:Ui,init:qi,mcp:ts,publish:np,audit:Bo,discover:op,scope:sp,pull:wp,resolve:fp,convert:yp,write:Rp,draft:Ap,document:Dp,resume:Ip,rename:Op,profile:_p,model:Fp,doctor:Yo,workspace:Vp,project:Yp,"allow-prod":Kp,login:zp,logout:Xp,screenshot:async(e,t)=>{let n=Oo(e);return n.mode==="capture"?$l(n.rest,t):n.mode==="verify"?Jp(n.rest,t):n.mode==="checklist"?Kn():ws(e,t)},capture:$l,"capture-setup":Kn,devhints:Ou,inbox:hh,"catch-up":yh,comments:vh,update:Ch,reset:Eh,check:Ah,review:Ih,reorder:Oh,structure:jh,genre:Us,roadmap:Bh,share:gh};function qh(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 F$}from"node:child_process";import{recordAnalyzedCommit as W$,resolveActiveProfile as B$}from"document360-engine";function H$(e){try{let t=F$("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 or(e,t){try{let n=H$(e);if(!n)return null;let o=B$(e,t);return W$(e,o.name,n)?n:null}catch{return null}}import{CONTENT_CAP_VERSION as Gh}from"document360-engine";function Vh(e){let t=e.trim().split(/\s+/);return t.includes("--fix")?t[0]==="/review"?"review":t[0]==="/check"?"check":null:null}function Yh(e){return e.trim().split(/\s+/).slice(1).find(t=>!t.startsWith("--"))}function rr(e){return e==="review"?{reviewedCap:Gh}:{checkedCap:Gh}}Mt();var q$="Or just tell me what to write or update.",G$='\u{1F4ED} No docs yet for this repo. Tell me "write the docs for this repo" and I\u2019ll read the code and draft a structure \u2014 or /audit to see what the docs should cover.';function ye(e){return e===1?"":"s"}function Jn(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 Kh(e,t){return e.length===t.length&&e.every((n,o)=>n===t[o])}function sr(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 Bs={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 V$(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:Bs,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;t.push(e.discovery.status==="pending"?{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/publish steps)."}:n>0?{key:"discovery",bullet:`product discovery is waiting on ${n} answer${ye(n)} from your builder \u2014 nudge them`,lead:null,picker:null,follow:"Discovery is waiting on your builder\u2019s answers \u2014 nudge them, then /catch-up folds the answers in once they reply."}:{key:"discovery",bullet:"product discovery is ready to continue",lead:{kind:"cmd",cmd:"/discover",reason:"it continues interviewing your builder to ground the docs"},picker:null,follow:"Then /discover continues building the product brief."})}if(e.directives>0||e.pendingText){let n=e.directives>0&&e.pendingText?"it actions your directives and clears the builder\u2019s queue":e.directives>0?"it actions the directives you left":"it clears everything your builder queued",o=[];e.directives>0&&o.push(`${e.directives} owner directive${ye(e.directives)} waiting`),e.pendingText&&o.push(`your builder left ${e.pendingText}`),t.push({key:"catchup",bullet:o.join(`
|
|
401
401
|
\u2022 `),lead:{kind:"cmd",cmd:"/catch-up",reason:n},picker:null,follow:"Then /catch-up clears what\u2019s queued for the docs."})}if(e.openComments>0){let n=e.openComments;t.push({key:"comments",bullet:`${n} reviewer comment${ye(n)} waiting on your articles`,lead:{kind:"cmd",cmd:"/comments",reason:"it shows what reviewers marked up in the portal, then lets you take it an article at a time"},picker:null,follow:`Then /comments shows the ${n} reviewer comment${ye(n)} waiting on your articles.`})}if(e.behind>0){let n=e.behind;t.push({key:"audit",bullet:`${n} code change${ye(n)} since your last docs check`,lead:{kind:"cmd",cmd:"/audit",reason:"it shows what the latest code changes touch (or /audit --auto on to run it for you)"},picker:null,follow:`After that, /audit covers the ${n} newer commit${ye(n)}.`})}if(e.hasDocs&&e.pendingWrites>0){let n=e.pendingWrites;t.push({key:"write",bullet:`${n} planned article${ye(n)} still unwritten`,lead:{kind:"cmd",cmd:"/write",reason:"it finishes the articles already planned"},picker:null,follow:`Then /write finishes the ${n} planned article${ye(n)}.`,dependsOn:["genre","discovery","catchup","audit"]})}if(e.unreviewed>0){let n=e.unreviewed;t.push({key:"review",bullet:`${n} article${ye(n)} ready to publish ${n===1?"has":"have"} never been editorially reviewed`,lead:{kind:"cmd",cmd:"/review --fix",reason:"these were written by an AI \u2014 it reads each one and applies its fixes, and /publish stays blocked until it has"},picker:null,follow:`Then /review --fix reviews the ${n} unreviewed article${ye(n)} \u2014 /publish is blocked until it has.`})}if(e.localAhead>0){let n=e.localAhead;t.push({key:"publish",bullet:`${n} article${ye(n)} changed locally \u2014 ready to publish`,lead:{kind:"cmd",cmd:"/publish",reason:`it pushes your ${n} local edit${ye(n)} up to Document360`},picker:null,follow:`Then /publish pushes your ${n} local edit${ye(n)} up.`,dependsOn:["discovery","audit"],blockedBy:["review"]})}if(e.conflicts>0){let n=e.conflicts;t.push({key:"resolve",bullet:`${n} article${ye(n)} changed both here and on Document360 (conflicts) \u2014 /publish skips these`,lead:{kind:"cmd",cmd:"/resolve",reason:"it walks each conflict \u2014 keep yours, take the portal's, or skip"},picker:null,follow:`Then /resolve settles the ${n} conflict${ye(n)} (keep yours / take the portal's / skip).`})}if(e.hasDocs&&e.roadmap?.next){let n=e.roadmap,o=n.next;t.push({key:"roadmap",bullet:`docs campaign: ${n.done} of ${n.total} step${ye(n.total)} done \u2014 next: ${o.title}`,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:`docs campaign: ${n.done} of ${n.total} step${ye(n.total)} done \u2014 this is next`})}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(`
|
|
402
|
-
`),lead:{kind:"cmd",cmd:"/share",reason:"it sends your saved work to your team and brings back your builder's latest; after this once, I keep doing it for you"},picker:null,follow:null}):o>0&&t.push({key:"share",bullet:`\u26A0 ${o} docs change set${ye(o)} saved but not sent \u2014 someone else pushed to this branch first (your work is safe)`,lead:{kind:"cmd",cmd:"/share",reason:"it retries sending your saved work; if it keeps failing, your builder can merge the branch"},picker:null,follow:null})}else if(e.uncommittedDocs>0){let n=e.uncommittedDocs;t.push({key:"commit",bullet:`\u26A0 ${n} uncommitted change${ye(n)} under .d360-writer/ \u2014 tell your coding agent: "commit d360-writer's work"`,lead:null,picker:null,follow:null})}return t}function
|
|
403
|
-
\u2022 `);if(x&&k.lead){let R=T.replace(/^→\s+/,"");return[` ${x}. ${
|
|
402
|
+
`),lead:{kind:"cmd",cmd:"/share",reason:"it sends your saved work to your team and brings back your builder's latest; after this once, I keep doing it for you"},picker:null,follow:null}):o>0&&t.push({key:"share",bullet:`\u26A0 ${o} docs change set${ye(o)} saved but not sent \u2014 someone else pushed to this branch first (your work is safe)`,lead:{kind:"cmd",cmd:"/share",reason:"it retries sending your saved work; if it keeps failing, your builder can merge the branch"},picker:null,follow:null})}else if(e.uncommittedDocs>0){let n=e.uncommittedDocs;t.push({key:"commit",bullet:`\u26A0 ${n} uncommitted change${ye(n)} under .d360-writer/ \u2014 tell your coding agent: "commit d360-writer's work"`,lead:null,picker:null,follow:null})}return t}function zh(e){return e.find(t=>t.lead||t.picker)??null}function Y$(e){return e.kind==="cmd"?e.cmd:e.kind==="prompt"?`\u201C${e.text}\u201D`:""}function K$(e){return e.kind==="cmd"?e.cmd:e.kind==="prompt"?e.text:""}function z$(e,t,n){let o=a=>(a??[]).map(u=>t.get(u)).filter(u=>u!==void 0&&u<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 Yl(e,t,n){let o=zh(t),r=o?.picker?[]:t.filter(k=>k.lead),s=r.length>=2?r:[],i=new Map(s.map((k,x)=>[k.key,x+1])),a=[];o?.lead?a.push(sr(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(x=>x!==o&&!x.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 u=a.join(" "),h=t.filter(k=>k.bullet).map(k=>{let x=i.get(k.key),[T="",...C]=(x&&k.lead?.kind==="prompt"&&k.rowBullet?k.rowBullet:k.bullet).split(`
|
|
403
|
+
\u2022 `);if(x&&k.lead){let R=T.replace(/^→\s+/,"");return[` ${x}. ${Y$(k.lead)} \u2014 ${R}${z$(k,i,x)}`,...C.map(V=>` ${V}`)].join(`
|
|
404
404
|
`)}let S=k.lead?.kind==="cmd"?k.lead.cmd:null;return` \u2022 ${k.bullet}${S&&!u.includes(S)?` \u2014 ${S}`:""}`}),g=[[e,...h].join(`
|
|
405
|
-
`)];return a.length&&g.push(a.join(" ")),g.push(
|
|
405
|
+
`)];return a.length&&g.push(a.join(" ")),g.push(q$),{note:g.join(`
|
|
406
406
|
|
|
407
|
-
`),menu:s.map(k=>
|
|
407
|
+
`),menu:s.map(k=>K$(k.lead))}}function ir(e,t){let n=t?.pickable===!0,o=h=>t?.header?`${t.header}
|
|
408
408
|
|
|
409
|
-
${h}`:h;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=
|
|
410
|
-
`)){let o=n.trimEnd();if(/^\s*(```|~~~)/.test(o)){t=!t;continue}if(t)continue;let r=/^#\s+(\S.*)$/.exec(o);if(r)return
|
|
411
|
-
`).length;return{verb:"Draft",title:S,category:u,note:`new, ${R} lines`}}return{verb:"Rewrite",title:S,category:u,note:
|
|
412
|
-
`)),category:u,note:T}}function
|
|
413
|
-
`);if(e==="Read"){let o=n.length,r=
|
|
409
|
+
${h}`:h;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=V$(e);if(!e.hasDocs){let h=zh(r);if(h&&(h.lead?.kind==="cmd"||h.picker)){let g=Yl(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:h.tone??"info",lead:h.lead,picker:h.picker,menu:g.menu}}}return{kind:"recommend",rec:{note:o(G$),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 h=e.roadmap&&!e.roadmap.next?` Docs campaign complete \u2014 all ${e.roadmap.total} step${ye(e.roadmap.total)} done (/roadmap).`:"";return{kind:"recommend",rec:{note:o(`Welcome back. Your ${e.tracked} tracked article${ye(e.tracked)} for \u201C${e.profileName}\u201D are all in sync \u2014 /audit re-checks the code, /pull brings down portal edits.${h}`),tone:"info",lead:null,picker:null,menu:[]}}}let s=r.filter(h=>h.lead||h.picker),i=s[0]??null;if(!i){let h=Yl(t?.header??"Welcome back \u2014 where your docs stand:",r,n);return{kind:"recommend",rec:{note:h.note,tone:"info",lead:null,picker:null,menu:h.menu}}}if((i.key==="audit"||s[1]?.key==="audit")&&e.behind>0&&e.autoAudit&&e.allowAutoAudit)return{kind:"autoAudit",note:o(`\u{1F4CB} ${e.behind} code change${ye(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`)};let u=Yl(t?.header??"Welcome back \u2014 where your docs stand:",r,n);return{kind:"recommend",rec:{note:u.note,tone:i.tone??"info",lead:i.lead,picker:i.picker,menu:u.menu}}}import{existsSync as Hs,readdirSync as zl}from"node:fs";import{spawnSync as X$}from"node:child_process";import{join as qs}from"node:path";import{readProjectConfig as Jh,resolveActiveProfile as Qh,loadTokens as J$,isExpired as Q$,loadProfileMap as Zh,localAheadPaths as Z$,loadKnownConflicts as ev,loadOpenCommentCount as tv,readDocsPlan as nv,devHintsGuidePath as ov,DEFAULT_DOCS_DIR as Kl,roadmapProgress as rv,listRoadmap as sv,readProductBriefState as iv,reconcileCommitRequest as av,reconcileTestidRequest as lv,snapshotHandoff as cv,shareExplainedPath as uv}from"document360-engine";Mt();function Xh(e){try{return zl(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function Xl(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>Xh(qs(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&Xh(qs(e,o)))}function Jl(e,t){try{let n=Jh(e);if(!n)return!1;let o=Qh(e,t),r=Zh(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=qs(e,(n.docsDir??Kl).replace(/\/+$/,""));return!!(Hs(s)&&zl(s).length>0||Hs(ov(e)))}catch{return!1}}function ar(e,t,n){try{let o=Jh(e);if(!o)return null;let r=Qh(e,t),s=J$(r.name),i=!!s&&(!Q$(s)||!!s.refreshToken),a=Jl(e,t)||!Xl(e,o.authoritativeSourceFiles),u=Zh(e,r.name),h=u?Object.keys(u.articles).length:0,g=qs(e,(o.docsDir??Kl).replace(/\/+$/,"")),k=!1;try{k=Hs(g)&&zl(g).length>0}catch{}let x=0;if(u?.lastAnalyzedCommit)try{let Pe=X$("git",["rev-list","--count",`${u.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});Pe.status===0&&(x=parseInt((Pe.stdout||"").trim(),10)||0)}catch{}let T=0;try{let Pe=nv(e);if(Pe.length>0){let Ze=(o.docsDir??Kl).replace(/\/+$/,"");T=Ya(e,Ze,Pe.map(Ct=>Ct.path)).length}}catch{}let C=yn(e),S=er({...C,directives:0}),R=Z$(e,t),N=new Set(ev(e,r.name)),V=R.filter(Pe=>N.has(Pe)).length,K=R.length-V,G=mn(e,R.filter(Pe=>!N.has(Pe))).length,ae=tv(e,r.name),Ce=it(e),ke=rv(e),De=cv(e,o),be=av(e,new Date().toISOString(),{supersededByHandoff:De!==null});lv(e,new Date().toISOString());let z=Ot(e,t),pe=z?{name:z.name,replacement:z.replacement,replacementProfile:z.replacementProfile}:null,le=iv(e),Se=le?{status:le.status,openQuestions:le.openQuestions}:null;return!Se&&k&&sv(e).some(Ze=>Ze.status==="open"&&(Ze.run??"").trim()==="/discover")&&(Se={status:"pending",openQuestions:0}),{ready:i&&a&&!n.claudeMissing,hasDocs:k,tracked:h,pendingText:S,directives:C.directives,behind:x,pendingWrites:T,localAhead:K,unreviewed:G,conflicts:V,openComments:ae,autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:Ce.status,devhintsCompletedVersion:Ce.completedVersion,devhintsToVersion:xe,builderStarted:$t(e),genreUnknown:n.genreUnknown,pendingAnswer:n.pendingAnswer??null,roadmap:ke,discovery:Se,uncommittedDocs:be.dirty.length,handoff:De,shareExplained:Hs(uv(e)),sunsetEnv:pe}}catch{return null}}Q();import{existsSync as dv,readFileSync as pv}from"node:fs";import{isAbsolute as hv,join as fv}from"node:path";import{DEFAULT_DOCS_DIR as mv,findPathByArticleId as gv,isArticleDocPath as wv,loadProfileMap as yv,readProjectConfig as kv,resolveActiveProfile as bv}from"document360-engine";var $v=70;function vv(e,t){return{docsRoot:()=>(kv(e)?.docsDir??mv).replace(/\\/g,"/").replace(/\/+$/,""),read:n=>{try{let o=hv(n)?n:fv(e,n);return dv(o)?pv(o,"utf8"):null}catch{return null}},pathForArticleId:n=>{try{let o=yv(e,bv(e,t).name);return o?gv(o,n):null}catch{return null}}}}var lr=(e,t=$v)=>{let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"};function cr(e){if(!e)return null;let t=!1;for(let n of e.split(`
|
|
410
|
+
`)){let o=n.trimEnd();if(/^\s*(```|~~~)/.test(o)){t=!t;continue}if(t)continue;let r=/^#\s+(\S.*)$/.exec(o);if(r)return lr(r[1])}return null}var xv=new Set(["a","an","and","as","at","but","by","for","in","of","on","or","the","to","vs","with"]),Cv=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 ef(e,t,n){let o=e.toLowerCase();return Cv.has(o)?e.toUpperCase():!t&&xv.has(o)?o:!t&&!n?e:e.charAt(0).toUpperCase()+e.slice(1)}var tf=e=>e.replace(/^\d+[-_.]/,"").split(/[-_]/).filter(Boolean);function Rv(e){let t=tf(e);return t.length===0?e:t.map((n,o)=>ef(n,o===0,!0)).join(" ")}function nf(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:Rv(n[n.length-2])}function of(e){let t=e.replace(/\\/g,"/").split("/").pop()??e,n=tf(t.replace(/\.(md|markdown)$/i,""));return n.length===0?t:n.map((o,r)=>ef(o,r===0,!1)).join(" ")}var Je=e=>typeof e=="string"&&e?e:null,Sv=e=>typeof e=="string"&&e.length>=8?`id ${e.slice(0,8)}\u2026`:null;function Pv(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 Tv(e,t){let n=Xe(e,t,200);return n?`+${n.added} \u2212${n.removed}`:"no change"}var Ev=new Set(["Edit","MultiEdit","Write"]);function Av(e,t,n,o){if(!Ev.has(e))return null;let r=Je(t.file_path);if(!r)return null;let s=Pv(r,n),i=o.docsRoot();if(!(s===i||s.startsWith(`${i}/`)))return null;let a=s.slice(i.length+1);if(!a||!wv(a))return null;let u=nf(a),h=o.read(s),g=C=>cr(C)??cr(h)??of(a);if(e==="Write"){let C=Je(t.content)??"",S=g(C);if(h===null){let R=C.replace(/\n$/,"").split(`
|
|
411
|
+
`).length;return{verb:"Draft",title:S,category:u,note:`new, ${R} lines`}}return{verb:"Rewrite",title:S,category:u,note:Tv(h,C)}}let k=Array.isArray(t.edits)?t.edits.map(C=>({from:Je(C.old_string)??"",to:Je(C.new_string)??""})):[{from:Je(t.old_string)??"",to:Je(t.new_string)??""}],x=k.reduce((C,S)=>{let R=Xe(S.from,S.to,200);return R?{added:C.added+R.added,removed:C.removed+R.removed}:C},{added:0,removed:0}),T=x.added===0&&x.removed===0?"no change":`+${x.added} \u2212${x.removed}`;return{verb:"Update",title:g(k.map(C=>C.to).join(`
|
|
412
|
+
`)),category:u,note:T}}function Dv(e,t,n){let o=()=>{let r=Je(t.article_id),s=r?n.pathForArticleId(r):null;return(s?cr(n.read(s)):null)??(s?of(s):Sv(r)??"article")};switch(e){case"d360_create_article":{let r=Je(t.title);return r?{verb:"Create",title:lr(r),category:nf(t.local_path),note:"Document360 draft"}:null}case"d360_update_article":return{verb:"Update",title:Je(t.title)?lr(Je(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=Je(t.name);return r?{verb:"Create",title:lr(r),category:null,note:"Document360 category"}:null}case"d360_upload_drive_file":{let r=Je(t.file_path);if(!r)return null;let s=r.replace(/\\/g,"/").split("/").pop()??r;return{verb:"Upload",title:lr(s),category:null,note:"Document360 Drive",keepResult:!0}}default:return null}}function Gs(e,t,n,o,r=vv(n,o)){try{let s="mcp__document360__";return e.startsWith(s)?Dv(e.slice(s.length),t,r):Av(e,t,n,r)}catch{return null}}var Nv={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"},sf=160,Ql=200,af=40;function Gt(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function rf(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}: ${Gt(typeof r=="string"?r:JSON.stringify(r),af)}`);return t.length>4&&n.push("\u2026"),Gt(n.join(", "),sf)}var jv=new Set(["file_path","notebook_path"]);function Iv(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 lf=e=>typeof e=="string"&&e?e:null;function Ov(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});return e==="d360_sync_status"?n("Check sync status",null):null}function Vs(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=Ov(a,t);if(g)return g}let u=a.replace(/^d360_/,"").replace(/_/g," ");return{title:`${s==="document360"?"Document360":s.charAt(0).toUpperCase()+s.slice(1)}: ${u}`,sep:" ",arg:rf(t)}}let o=Nv[e],r=o?t[o]:void 0;if(typeof r=="string"&&r){let s=o&&jv.has(o)?Iv(r,n):r;return{title:e,sep:"",arg:Gt(s,sf)}}return{title:e,sep:"",arg:rf(t)}}function Lv(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 _v(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(Lv).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>Gt(r,Ql))]}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}: ${Gt(String(r),af)}`);return n.length>0?[Gt(n.join(" \xB7 "),Ql)]:null}return null}function Mv(e){let t=lf(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function Uv(e,t,n){switch(e){case"d360_create_article":{let o=Mv(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=lf(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 ${Gt(o[0],120)}`:""}`]}default:return null}}var cf=new Set(["Edit","Write","MultiEdit","NotebookEdit"]);function Fv(e){return e.replace(/^\s*\d+\t/,"")}function Wv(e,t){if(cf.has(e))return[];let n=t.split(`
|
|
413
|
+
`);if(e==="Read"){let o=n.length,r=cr(n.map(Fv).join(`
|
|
414
414
|
`));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 Ys(e,t=4,n,o){let r=e.replace(/\r\n/g,`
|
|
415
|
-
`).trimEnd();if(n&&
|
|
416
|
-
`);return{lines:s.slice(0,t).map(i=>Gt(i,Ql)),hidden:Math.max(0,s.length-t)}}function Ks(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function zs(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
|
|
417
|
-
`))console.log(i(` ${a}`));s.rec.picker&&console.log(q(` Pick one: ${s.rec.picker.options.map(a=>a.cmd).join(" \xB7 ")}`))}}catch{}}console.log(b(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function
|
|
415
|
+
`).trimEnd();if(n&&cf.has(n))return{lines:[],hidden:0};if(!r)return{lines:["(no output)"],hidden:0};if(n&&!n.startsWith("mcp__")){let i=Wv(n,r);if(i)return{lines:i,hidden:0}}if(n?.startsWith("mcp__document360__")){let i=Uv(n.slice(18),o,r);if(i)return{lines:i,hidden:0}}let s=_v(r)??r.split(`
|
|
416
|
+
`);return{lines:s.slice(0,t).map(i=>Gt(i,Ql)),hidden:Math.max(0,s.length-t)}}function Ks(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function zs(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 uf(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 Xs(e){return uf(e,"url")}function Js(e){return uf(e,"preview_url")}var mf=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/,ec=null;function pf(){return ec===null&&(ec=Jv().verboseTranscript===!0),ec}function ux(e,t,n,o){if(mf.test(e))try{let r=ff(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,i=zs(t,n),a=Xs(n);e.endsWith("publish_article")&&a&&console.log(q(` \u2B95 Live: ${a}`));let u=Js(n);u?console.log(q(` \u2B95 Preview: ${u}`)):i&&s&&console.log(q(` \u2B95 Preview: ${Ks(r.connection.portalUrl,s,i,r.project.languageCode??"en")}`))}catch{}}async function gf(e=process.cwd(),t="auto",n,o){let r=Hv(t);r.kind==="none"&&(console.error(""),console.error(j("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${q("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${q('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${q("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${q("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),dx(e,n),r.kind==="subscription"&&(r.stored?console.log(b(" Using your Claude subscription (no API key set).")):console.log(b(" No API key or stored Claude Code login found \u2014 trying your Claude session anyway.")),console.log(""));let s=!1,i=Zl({cwd:e,profileName:n,allowProdWrites:s}),a={uuid:null,firstPrompt:null,titleFired:!1},u=Bv({input:process.stdin,output:process.stdout}),h=[],g=null,k=!1;u.on("line",C=>{if(g){let S=g;g=null,S(C)}else h.push(C)}),u.on("close",()=>{if(k=!0,g){let C=g;g=null,C(null)}});function x(){return h.length>0?Promise.resolve(h.shift()):k?Promise.resolve(null):(process.stdout.write(q("> ")),new Promise(C=>{g=C}))}let T={cwd:e,version:o,profileName:n,allowProdWrites:()=>s,restartAgent:()=>{i.close(),i=Zl({cwd:e,profileName:n,allowProdWrites:s}),a={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>a.uuid,setPendingName:C=>{a.pendingName=C},setModel:async C=>i.setModel(C),withPausedInput:async C=>{u.pause();try{return await C()}finally{u.resume()}}};try{for(;;){let C=await x();if(C===null)break;let S=C.trim();if(S){if(S.startsWith("/")){let R=qh(S);if(!R)continue;let N=Hh[R.name];if(!N){console.log(j(`Unknown command: /${R.name}`)),console.log(b("Type /help for the list."));continue}let V=await N(R.args,T);if(V.kind==="exit")break;if(V.kind==="clear"){T.restartAgent();continue}if(V.kind==="allow-prod"){s=!0,T.restartAgent(),console.log(B("\u2713 Production writes authorized for this session.")),console.log("");continue}if(V.kind==="resume"){i.close(),i=Zl({cwd:e,resume:V.uuid,profileName:n,allowProdWrites:s});let K=qv(V.uuid);a={uuid:V.uuid,firstPrompt:K?.firstPrompt??null,titleFired:!0},hf(V.uuid),console.log(B(`\u2713 Resumed "${V.name}"`)),console.log("");continue}if(V.kind==="forward-to-agent"){a.firstPrompt||(a.firstPrompt=V.display??V.prompt);let K=V.display??"",G=K.trim().split(/\s+/),ae=Vh(K),Ce=ae?ix(e,Yh(K)):[],ke=G[0]==="/screenshot"&&(G[1]==="verify"||G[1]==="review"),De=ke?G[2]&&!G[2].startsWith("--")?[G[2]]:Ko(Ae(e)):[];if(await tc(i,V.prompt,r,a,e,n),ae)try{sx(e,Ce,rr(ae))}catch{}if(G[0]==="/audit"&&!G.includes("--auto")&&or(e,n),ke&&De.length>0)try{for(let be of Xo(e,De))console.log(be)}catch{}if(G[0]==="/publish"){let be=await Gn(e,n);be&&console.log(b(be))}if((G[0]==="/catch-up"||G[0]==="/document")&&G.includes("--publish"))try{let be=await cx({cwd:e,profileName:n}),{clean:z,conflicts:pe}=fn(be.entries);z.length===0?console.log(b("Nothing new to publish \u2014 everything is already up to date on Document360.")):await ht(T,z.map(le=>le.path),pe.length,{skipReview:G.includes(ft)})}catch(be){console.log(W(`Couldn't check what to publish (${be.message}) \u2014 your drafts are saved; run /publish when ready.`))}}else px(e,n);continue}if(tx(S)){let R=nx(S);if(R){try{ox(e,{title:R,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}a.firstPrompt||(a.firstPrompt=S),await tc(i,`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${R}". 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 "${R}" and the article path(s) you wrote.`,r,a,e,n);continue}}a.firstPrompt||(a.firstPrompt=S),await tc(i,S,r,a,e,n)}}}finally{i.close(),u.close()}}function dx(e,t){console.log(""),console.log(So("document360-writer")),console.log(b(` cwd: ${e}`));let n=zv(e);if(console.log(b(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(hx(e,t)),!Xv(e))console.log(W(" 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(Xr(e),!$t(e))for(let r of Jr(e))console.log(W(` ${r}`))}catch{}try{let r=Qv(e);r.persisted&&r.appType?console.log(b(` \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=rx(e);for(let s of Vr(r.applied))console.log(W(` ${s}`));if(r.reopenedForRedaction)for(let s of Yr(r.reopenedForRedaction).split(/\r?\n/))console.log(W(` ${s}`))}catch{}try{let r=ar(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:o}),s=r?ir(r,{pickable:!1}):null;if(s?.kind==="recommend"&&s.rec.note){let i=s.rec.tone==="warn"?W:b;for(let a of ta(s.rec.note).split(`
|
|
417
|
+
`))console.log(i(` ${a}`));s.rec.picker&&console.log(q(` Pick one: ${s.rec.picker.options.map(a=>a.cmd).join(" \xB7 ")}`))}}catch{}}console.log(b(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function px(e,t){try{let n=ar(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:!1}),o=n?ir(n):null;o?.kind==="recommend"&&o.rec.lead&&console.log(b(` Next: ${sr(o.rec.lead)}`))}catch{}}function hx(e,t){try{let n=ff(e,t),o=n.production?W(" \u26A0 PRODUCTION"):"",r=ex(n.name);if(!r)return b(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...df(r.idToken)??{},...df(r.accessToken)??{}},i=s.email??s.preferred_username??"signed in";return Zv(r)&&!r.refreshToken?W(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):b(` Document360: ${i} \xB7 profile "${n.name}"${o}`)}catch(n){return b(` Document360: ${n.message.split(".")[0]}`)}}function fx(){console.error(""),console.error(`Sign in with your Claude subscription: run ${q("claude")} once, then retry.`),console.error(` (No Claude Code? ${q("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${q("https://console.anthropic.com/settings/keys")}`)}function mx(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;Yv({uuid:t,name:r??Vv(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function gx(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||Kv(o,t).then(r=>{r&&Gv(n,r)}).catch(()=>{})}async function tc(e,t,n,o,r,s){let i=new Map,a=!1;for await(let u of e.send(t))u.type==="tool"&&mf.test(u.name)&&(a=!0),wx(u,o,r,n,i,s);if(a)try{let u=lx(await ax({cwd:r,profileName:s}));u&&console.log(u.startsWith("\u26A0")?W(u):u)}catch{}}function wx(e,t,n,o,r,s){switch(e.type){case"session":t.uuid||mx(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let i=pf()?null:Gs(e.name,e.input,n,s);if(i){process.stdout.write(`
|
|
418
418
|
|
|
419
419
|
`);let u=[i.category,i.note].filter(g=>!!g).map(g=>fe(` \xB7 ${g}`)),h=i.loud?fe(" \xB7 ")+je(W(i.loud)):"";console.log(`${B("\u25CF")} ${q(je(ea(i.verb)))}${je(i.title)}${u.join("")}${h}`),r.set(e.id,{name:e.name,input:e.input,doc:!0,keepResult:i.keepResult});break}let a=Vs(e.name,e.input,process.cwd());a&&(process.stdout.write(`
|
|
420
420
|
|
|
421
|
-
`),console.log(`${fe("\u25CF")} ${a.title}${a.arg!==null?fe(`${a.sep}(${a.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let i=
|
|
422
|
-
`);let i=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(b(` (${
|
|
423
|
-
`),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
|
|
424
|
-
`),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){
|
|
425
|
-
`)}var
|
|
426
|
-
\u2190/\u2192 or tab switch \xB7 1-5 jump${C+S>0?" \xB7 \u2191\u2193 scroll":""} \xB7 esc close \xB7 d360-writer v${r} \xB7 engine v${s}`})]})}var
|
|
427
|
-
`)){let i=s.trim().replace(
|
|
428
|
-
`)}function
|
|
429
|
-
`)||e.length>200}function
|
|
430
|
-
`).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function
|
|
431
|
-
`)){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 si(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function
|
|
421
|
+
`),console.log(`${fe("\u25CF")} ${a.title}${a.arg!==null?fe(`${a.sep}(${a.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let i=Xe(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!i)break;let a=u=>u===1?"":"s";console.log(fe(` \u23BF Added ${i.added} line${a(i.added)}, removed ${i.removed} line${a(i.removed)}`));for(let u of i.lines)console.log(u);i.hidden>0&&console.log(b(` \u2026 +${i.hidden} more diff lines`));break}case"tool_result":{let i=r.get(e.id);if(!i)break;r.delete(e.id);let u=i.doc&&!i.keepResult&&!e.isError?{lines:[],hidden:0}:Ys(e.output,4,e.isError||pf()?void 0:i.name,i.input),h=e.isError?j:fe;u.lines.forEach((g,k)=>console.log(h((k===0?" \u23BF ":" ")+g))),u.hidden>0&&console.log(b(` \u2026 +${u.hidden} lines`)),e.isError||ux(i.name,i.input,e.output,n);break}case"result":{process.stdout.write(`
|
|
422
|
+
`);let i=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(b(` (${No(i)}\u2192${No(e.outputTokens)} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(hf(t.uuid),t.titleFired||gx(t,n));break}case"error":console.error(""),e.kind==="limit"?console.log(W(`\u23F3 ${e.message}`)):console.error(j(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&fx();break}}import{render as z0}from"ink";import{resolveAuth as X0}from"document360-engine";import{useCallback as X,useEffect as Ge,useMemo as dc,useRef as re,useState as Z}from"react";import{Box as ge,Text as _,useApp as Bx,useInput as Hx,useStdout as qx}from"ink";import{existsSync as to,readFileSync as ii,readdirSync as Gx,writeFileSync as Vx}from"node:fs";import{basename as pr,dirname as Yx,isAbsolute as Kx,join as pc}from"node:path";import{createSession as nm,classifyClaudeAuth as yc,CLAUDE_CODE_SETUP_HINT as zx,loginPkce as Xx,toStoredTokens as Jx,saveTokens as Qx,getAccessToken as Zx,resolveActiveProfile as Qe,resolveProjectId as e0,getArticle as t0,decodeJwtClaims as ro,isExpired as Vt,loadTokens as $n,clearTokens as n0,clearProfileProject as o0,setTitle as r0,slugify as s0,touchSession as hc,upsertSession as i0,generateTitle as om,findByName as a0,listSessions as l0,renameSession as c0,suggestNextAction as u0,readProjectConfig as de,writeProjectConfig as rm,readUserConfig as sm,writeUserConfig as d0,resolveAndPersistAppType as p0,detectAppType as im,resolveModelSetting as kc,loadProfileMap as am,applyPull as ai,computeSyncStatus as li,lintDocs as lm,compareRemoteSources as h0,planPull as cm,establishBaselines as f0,rebaselineServerMeta as m0,inventoryRepo as g0,knownEnvironments as w0,currentEnvironments as um,sunsetEnvironment as dm,resolveEnvironment as y0,planPartitions as fc,partitionEvenly as k0,screenshotPlaceholderIds as b0,trackedArticlePaths as $0,runPartitioned as hr,estimateBulkCost as pm,resolveModelForOperation as fr,readDocsPlan as hm,checkForUpdate as v0,detectInstallKind as x0,isSelfUpdatable as C0,devHintsGuidePath as fm,toolFeedbackPath as mm,reconcileToolFeedback as R0,reconcileUpgradeActions as S0,stampArticles as mc,listArticleFiles as gm,CONTENT_CAP_VERSION as P0,ENGINE_VERSION as xm,DEFAULT_DOCS_DIR as bc,setProfileProject as T0,writeCrashLog as E0,applyStructureOrder as gc,orderSyncLine as wc,applyRelatedArticles as wm,relatedSyncLine as ym,reconcileDocsGit as A0,shareExplainedPath as D0,ensureDir as N0}from"document360-engine";Io();Mt();import{spawn as wf}from"node:child_process";function yx(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function kx(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?wf([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):wf(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 nc(e){for(let[t,n]of yx())if(await kx(t,n,e))return!0;return!1}var yf=/\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 bx(e){let t=e.replace(/\s+$/,"").split(`
|
|
423
|
+
`),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 kf(e){let t=e.trimEnd();if(!t)return null;let n=bx(t);return n>=2?{options:n}:/\?[\s*_"')\]]*$/.test(t)||yf.test(t)?{options:0}:null}function oc(e,t){if(t.closed)return e;let n=e.split(`
|
|
424
|
+
`),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){yf.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(`
|
|
425
|
+
`)}var $x={la:"local","l all":"local","local all":"local",pa:"portal","p all":"portal","portal all":"portal",sa:"skip","s all":"skip","skip all":"skip"},vx={L:"local",P:"portal",S:"skip"},xx={ya:"write","y all":"write","yes all":"write",na:"skip","n all":"skip","no all":"skip"},Cx={Y:"write",N:"skip"};function bf(e,t,n){let o=e.trim(),r=o.toLowerCase().replace(/\s+/g," ");return t[r]??(o.length===1?n[o]??null:null)}function $f(e){return bf(e,$x,vx)}function vf(e){return bf(e,xx,Cx)}function rc(e,t){let n=t?.max??12,o=t?.chrome??8;return Math.max(3,Math.min(n,(e??24)-o))}function Qs(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}}import{existsSync as Rx,mkdirSync as Sx,readFileSync as Px,writeFileSync as Tx}from"node:fs";import{join as xf}from"node:path";import{writerDir as Ex}from"document360-engine";function Cf(e){return xf(Ex(e),".sessions")}function Rf(e,t){return xf(Cf(e),`${t}.json`)}function Sf(e,t,n){try{Sx(Cf(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");Tx(Rf(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function sc(e,t){try{let n=Rf(e,t);if(!Rx(n))return[];let o=JSON.parse(Px(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var Ax=e=>`\x1B]0;${e}\x07`,Dx=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function Pf(e){process.stdout.isTTY&&process.stdout.write(e)}function Qn(e){Pf(Ax(e))}function Zs(e){Pf(Dx(e))}var ei=["\xB7 "," \xB7"],ti="\u{1F7E3}";Es();var Tf=()=>({fingerprint:null,counts:null,settled:0,spokenBaseline:null,lastSpokeAt:null,awaySince:null}),Nx={hints:0,requests:0,answers:0,directives:0};function ic(e,t){let n=e??Nx;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 ni=e=>e.hints===0&&e.requests===0&&e.answers===0&&e.directives===0,Ef=e=>e.hints+e.requests+e.answers+e.directives,ac=(e,t)=>e-t>=6e5;function Af(e){let{now:t,lastInputAt:n,fingerprint:o,counts:r,occupied:s,prev:i}=e,a=ac(t,n),h=i.fingerprint!==null&&i.fingerprint!==o?0:i.settled+1,g={...i,fingerprint:o,counts:r,settled:h,awaySince:a?i.awaySince??t:null,spokenBaseline:i.spokenBaseline??r};if(a){let x=ic(g.spokenBaseline,r);return{memory:g,speak:null,waiting:ni(x)?null:x}}if(s)return{memory:g,speak:null,waiting:null};if(h<2)return{memory:g,speak:null,waiting:null};let k=ic(i.spokenBaseline,r);return ni(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:h},speak:k,waiting:null}}function Df(e,t,n){if(e.awaySince===null)return{kind:"none",memory:e};let o=t-e.awaySince,r=ic(e.spokenBaseline,n),s={...e,awaySince:null,counts:n,spokenBaseline:n,lastSpokeAt:ni(r)?e.lastSpokeAt:t};return ni(r)?{kind:"none",memory:s}:{kind:o>=36e5?"briefing":"delta",memory:s,delta:r,awayMs:o}}function ur(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 lc(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 Nf(e){return`\u{1F4E5} ${ur(e)} just arrived from your builder \u2014 /catch-up folds ${Ef(e)===1?"it":"them"} into the docs.`}function jf(e,t){return`\u{1F4E5} While you were away (${lc(t)}): ${ur(e)} from your builder \u2014 /catch-up folds ${Ef(e)===1?"it":"them"} into the docs.`}function If(e){return`\u{1F4E5} ${ur(e)} waiting from your builder \xB7 tab to run /catch-up\u2026`}es();Q();import{Box as dr,Text as $e}from"ink";import{jsx as ve,jsxs as Zn}from"react/jsx-runtime";function jx({row:e,nameW:t,width:n}){let o=s=>_i(s,n),r=(s,i)=>ve(dr,{flexDirection:"column",children:s.map(i)});switch(e.t){case"head":return r(o(e.s),(s,i)=>ve($e,{color:te,bold:!0,children:s},i));case"text":return r(o(e.s),(s,i)=>ve($e,{children:s},i));case"dim":return r(o(e.s),(s,i)=>ve($e,{dimColor:!0,children:s},i));case"sub":return r(o(e.s),(s,i)=>ve($e,{bold:!0,dimColor:!0,children:s},i));case"good":return r(o(e.s),(s,i)=>ve($e,{color:"green",children:s},i));case"step":{let s=o(`${e.n}. ${e.s}`);return ve(dr,{flexDirection:"column",children:s.map((i,a)=>a===0?Zn($e,{children:[ve($e,{color:te,children:`${e.n}. `}),i.slice(`${e.n}. `.length)]},a):ve($e,{children:i},a))})}case"cmd":{let s=Kr(e.name,e.s,t,n),i=s.descLines.slice(s.nameOwnLine?0:1);return Zn(dr,{flexDirection:"column",children:[Zn($e,{children:[" ",ve($e,{color:te,children:s.nameCell}),!s.nameOwnLine&&ve($e,{dimColor:!0,children:` ${s.descLines[0]??""}`})]}),i.map((a,u)=>ve($e,{dimColor:!0,children:`${s.indent}${a}`},u))]})}case"gap":return ve($e,{children:" "})}}function Of({tab:e,scroll:t,rows:n,width:o,version:r,engineVersion:s}){let i=Fe[e]??Fe[0],a=Li(i.rows),u=Math.max(20,o-2),h=6+Fe.reduce((R,N)=>R+N.label.length+4,0),g="\u2500".repeat(Math.min(h,u)),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}`,x=xu({rows:n,inner:u,barWidth:h,footerWidth:k.length}),{visible:T,above:C,below:S}=vu(i.rows,{width:o,budget:x,scroll:t,nameW:a});return Zn(dr,{flexDirection:"column",paddingX:1,children:[Zn($e,{children:[ve($e,{color:te,bold:!0,children:"Help "}),Fe.map((R,N)=>N===e?ve($e,{color:"white",backgroundColor:te,bold:!0,children:` ${R.label} `},R.key):ve($e,{dimColor:!0,children:` ${R.label} `},R.key))]}),ve($e,{color:te,children:g}),Zn(dr,{flexDirection:"column",marginTop:1,children:[C>0?ve($e,{dimColor:!0,children:`\u22EF ${C} more above`}):null,T.map((R,N)=>ve(jx,{row:R,nameW:a,width:o},C+N)),S>0?ve($e,{dimColor:!0,children:`\u22EF ${S} more below`}):null]}),ve($e,{dimColor:!0,children:`
|
|
426
|
+
\u2190/\u2192 or tab switch \xB7 1-5 jump${C+S>0?" \xB7 \u2191\u2193 scroll":""} \xB7 esc close \xB7 d360-writer v${r} \xB7 engine v${s}`})]})}var Ix=/^(?:\d+[.)]|[-*•])\s+/;function Lf(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
|
|
427
|
+
`)){let i=s.trim().replace(Ix,""),a=i.match(/^`([^`]+)`$/);a&&(i=a[1].trim());let u=i.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!u||!o.has(u[1].toLowerCase()))continue;let h=`/${u[1].toLowerCase()}${u[2]?` ${u[2]}`:""}`;if(r.includes(h)||r.push(h),r.length>=n)break}return r}Q();function eo(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function qe(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function _f(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var Ox=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function Mf(e,t,n){if(!Ox.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 cc(e){return e.replace(/^[\w.-]+\//,"")}var oi=16,Uf={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function kn(e){return typeof e=="string"?e:e.cmd}function Ff(e){return typeof e=="string"?void 0:e.desc}function uc(e){return e.trim().split(/\s+/).slice(1).join(" ")}function Wf(e,t){let n=uc(t);return e.some(r=>kn(r).trim()===t.trim()||!!n&&uc(kn(r))===n)?e.filter(r=>kn(r).trim()!==t.trim()&&!(n&&uc(kn(r))===n)):[]}import{isDirectiveMention as j0,stripDirectiveMention as I0,appendDirective as O0,reconcileTestidRequest as L0,builderChannelWired as _0,pendingFingerprint as M0}from"document360-engine";var Lx=/\[Pasted text #\d+ \+\d+ lines?\]/g;function Bf(e){return e.replace(/\r\n?/g,`
|
|
428
|
+
`)}function Hf(e){return e.includes(`
|
|
429
|
+
`)||e.length>200}function qf(e,t){let n=t.split(`
|
|
430
|
+
`).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function Gf(e,t){return e.replace(Lx,n=>t.get(n)??n)}function Vf(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function ri(e,t){let n=Math.max(1,t),o=[],r=0;for(let s of e.split(`
|
|
431
|
+
`)){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 si(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function Yf(e,t,n){let o=si(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 Kf(e,t,n){let o=e[si(e,t)];return n==="start"?o.start:o.end}var _x=new Set(["Edit","Write","MultiEdit","NotebookEdit"]),zf={hint:"hint",message:"message",state:"state file",roadmap:"roadmap",directive:"directives",feedback:"tool-feedback"},Mx=new Set(["hint","message","state"]),Ux=["hint","message","roadmap","directive","feedback","state"];function Fx(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 Xf(e,t){let n=e==="Read"?"read":_x.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=Fx(r.slice(i+s.length));return a?{category:a,verb:n,path:r}:null}function Jf(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 Ux)for(let s of["updated","read"]){let i=t.get(`${r}:${s}`)?.size??0;i!==0&&o.push(Mx.has(r)?`${i} ${zf[r]}${i===1?"":"s"} ${s}`:`${zf[r]} ${s}`)}return o.length>0?o.join(" \xB7 "):null}function Qf(e,t,n){let o=Math.max(1,n),r=e.split(`
|
|
432
432
|
`),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 u=s-t;return{text:[u>0?a.slice(u*o):a,...r.slice(i+1)].join(`
|
|
433
|
-
`),truncated:i>0||u>0}}}return{text:e,truncated:!1}}function
|
|
434
|
-
`)){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 oo,jsx as L,jsxs as ne}from"react/jsx-runtime";var
|
|
433
|
+
`),truncated:i>0||u>0}}}return{text:e,truncated:!1}}function Zf(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 em(e){let t=!1,n=0,o=0;for(let r of e.split(`
|
|
434
|
+
`)){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 oo,jsx as L,jsxs as ne}from"react/jsx-runtime";var U0={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL",auto:"auto \u2014 right-sized for docs \xB7 /model to change"},km=` 1. /init \u2014 pick your Document360 environment & scaffold config
|
|
435
435
|
2. /login \u2014 sign in & pick your Document360 project (workspace auto-selected)
|
|
436
|
-
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function
|
|
437
|
-
`)}catch{}c.picker&&(le(c.picker.options.map(w=>({cmd:w.cmd,desc:w.desc}))),An(c.picker.title)),!d?.silent&&c.note&&(
|
|
438
|
-
`)}),At(c.prompt,
|
|
439
|
-
${
|
|
436
|
+
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function F0(e,t,n,o){let r=yc(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=kc(e),a=de(e),u=(a?.docsDir??bc).replace(/\/+$/,""),h=a?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${u}/ + config`,g={version:t,engineVersion:xm,captureVersion:xt(),claude:s,model:i.model,modelSource:U0[i.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:a!==null,mode:h};if(a===null)return g;try{let k=Qe(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 x=$n(k.name);if(x){let T={...ro(x.idToken)??{},...ro(x.accessToken)??{}},C=T.email??T.preferred_username??"signed in";Vt(x)?x.refreshToken&&(g.who=C,g.loggedOut=!1,g.sessionHint="session expired \u2014 refreshing\u2026"):(g.who=C,g.loggedOut=!1,g.sessionHint=`session valid until ${new Date(x.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return g}function W0(e,t){try{let n=Qe(e,t),o=$n(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...ro(o.idToken)??{},...ro(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return Vt(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 bm=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],so=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],B0="Ask me to write or update an article\u2026";function no({ch:e,dim:t}){let[n,o]=Z(!0);return Ge(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),L(_,{inverse:n,color:t&&!n?"gray":void 0,children:e})}function bn({rows:e,cursor:t,cap:n,render:o}){let r=Qs(e.length,t,n);return ne(oo,{children:[r.above>0?L(_,{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?L(_,{color:"gray",children:` \u22EF ${r.below} more below`}):null]})}var $m=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function vm(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var H0=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function q0({startTime:e,chars:t}){let[n,o]=Z(0),r=re(Date.now());Ge(()=>{let h=setInterval(()=>o(g=>g+1),120);return()=>clearInterval(h)},[]);let s=so[n%so.length],i=bm[Math.floor(n/16)%bm.length],a=ld(e,r.current,Date.now()),u=Math.round(t/4);return ne(ge,{children:[L(_,{color:te,children:` ${s} ${i}\u2026 `}),L(_,{color:"gray",children:`(${jo(a)} \xB7 ~${u} tokens \xB7 esc to interrupt)`})]})}function G0({text:e}){let[t,n]=Z(0);return Ge(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),L(ge,{paddingX:1,children:L(_,{color:te,children:`${so[t%so.length]} ${e}`})})}var V0=12e4;function Y0({p:e}){let[t,n]=Z(0);Ge(()=>{let R=setInterval(()=>n(N=>N+1),150);return()=>clearInterval(R)},[]);let o=so[t%so.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>=V0,u=e.verb??"Converting",h=e.unit??"article",g=e.rows.reduce((R,N)=>R+N.items,0),k=u.toLowerCase(),x=e.rows,T=0;if(x.length>oi){let R=x.findIndex(V=>V.status==="active"||V.status==="pending"),N=Math.max(0,Math.min(R-2,x.length-oi));T=x.slice(0,N).filter(V=>V.status==="done").length,x=x.slice(N,N+oi)}let C=Math.min(40,Math.max(...x.map(R=>cc(R.label).length),0)),S=R=>R==="failed"?"red":R==="active"?te:void 0;return ne(ge,{flexDirection:"column",children:[ne(ge,{children:[L(_,{color:te,children:` ${o} ${u} ${g} ${h}${g===1?"":"s"} `}),L(_,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${i} tokens \xB7 ${jo(r)} \xB7 esc to stop`})]}),T>0&&L(_,{dimColor:!0,children:` \u2714 +${T} done`}),x.map(R=>ne(_,{color:S(R.status),dimColor:R.status==="done"||R.status==="pending",children:[` ${Uf[R.status]} ${cc(R.label).padEnd(C)}`,R.status==="active"&&R.itemsDone!==void 0?` (${R.itemsDone}/${R.items} ${h}${R.items===1?"":"s"})`:R.status!=="pending"?` (${R.items} ${h}${R.items===1?"":"s"})`:"",R.status==="active"?` \u2190 ${k}\u2026`:""]},R.label)),a&&L(_,{color:"yellow",children:` \u26A0 no activity for ${jo(s)} \u2014 press esc to stop if it's wedged`})]})}var K0=10800*1e3;function Cm({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=Bx(),[s,i]=Z(n),[a,u]=Z(null),[h,g]=Z({text:"",pos:0}),k=h.text,x=X(c=>{g(d=>{let l=typeof c=="function"?c(d.text):c;return{text:l,pos:l.length}})},[]),T=X(c=>{g(d=>({text:d.text.slice(0,d.pos)+c+d.text.slice(d.pos),pos:d.pos+c.length}))},[]),C=X(()=>{g(c=>{if(c.pos===0)return c;let d=c.text.slice(0,c.pos),l=Vf(d)??d.slice(0,-1);return{text:l+c.text.slice(c.pos),pos:l.length}})},[]),[S,R]=Z(!1),[N,V]=Z(!1),[K,G]=Z(0),[ae,Ce]=Z(!1),[ke,De]=Z(null),[be,z]=Z(null),[pe,le]=Z([]),Se=re(!1),Pe=re(!1),Ze=re(null),Ct=re(!1),[Yt,mr]=Z(!1),lt=re(0),[gr,wr]=Z(!1),[Dm,yr]=Z(!1),[ui,Cc]=Z(null),[Nm,Kt]=Z(0),Rt=re(0),[di,vn]=Z(0),[xn,kr]=Z(null),Rc=re(new Map),jm=re(0),Cn=re([]),et=re(null);et.current===null&&(et.current=nm({cwd:e,profileName:s,allowProdWrites:!1}));let gt=re({uuid:null,firstPrompt:null,titleFired:!1}),io=re(new Map),Sc=re(null),br=re(sm().verboseTranscript===!0),zt=re(!1),pi=re([]),me=re([]),Xt=re([]),ao=re(null),[Pc,Jt]=Z(null),hi=re(null),[Qt,Zt]=Z(null),[St,Rn]=Z(null),[Pt,Sn]=Z(null),[Oe,Pn]=Z(null),[tt,en]=Z(null),[wt,Tn]=Z(null),[Tt,tn]=Z(null),[nt,En]=Z(null),[ct,nn]=Z(null),[Tc,An]=Z(null),[Ve,on]=Z(null),[Le,Dn]=Z(null),[Ec,fi]=Z([]),rn=re([]),lo=re(!1),Te=re(null),[co,ce]=Z(null),[Ac,Ye]=Z(null),$r=re(!1),uo=re(null),po=re(null),[Ke,sn]=Z(null),[ho,an]=Z(null),fo=!!(Pt||Oe||tt||wt||Tt||nt||ct||Ve||Le||Ke||ho),[Dc,ln]=Z(0),[Nc,cn]=Z(0),[Im,jc]=Z(0),mi=dc(()=>{try{let c=kc(e);return c.source==="auto"?`${c.model} (auto)`:c.model}catch{return null}},[e,Im]),{stdout:_e}=qx(),[,Om]=Z(0),Ic=re(`${_e.columns??80}x${_e.rows??24}`),Et=X(()=>Math.max(20,(_e.columns??80)-1),[_e]),vr=X(c=>{Cn.current.push(c),console.log(na(c,Et()))},[Et]),gi=re([]),xr=X(()=>{let c=gi.current;if(c.length===0)return;gi.current=[];let d=Jf(c);d&&vr({kind:"note",tone:"info",text:`\u25CF Housekeeping ${d}`})},[vr]),p=X(c=>{xr(),vr(c)},[vr,xr]),ze=re({printed:[],armed:[]}),Ie=X((c,d)=>{lt.current++,ze.current.armed=[],De(c),z(d??null)},[]),ut=X(()=>{lt.current++,ze.current.armed=[],De(null),z(null)},[]),Cr=X(c=>{lt.current++,ze.current.armed=[],De(null),z(c)},[]),ee=X(c=>Ie(c,Jn({kind:"cmd",cmd:c,reason:""})),[Ie]),yt=X((c,d)=>{if(!d?.silent&&c.note&&p({kind:"note",tone:d?.tone??c.tone,text:c.note}),!d?.silent&&c.note?.includes(".d360-writer/ \u2014 your articles"))try{let w=D0(e);N0(Yx(w)),Vx(w,`${new Date().toISOString()}
|
|
437
|
+
`)}catch{}c.picker&&(le(c.picker.options.map(w=>({cmd:w.cmd,desc:w.desc}))),An(c.picker.title)),!d?.silent&&c.note&&(ze.current.printed=c.menu);let l=Kh(ze.current.printed,c.menu)?c.menu:[];c.lead&&(c.lead.kind==="answer"?Cr(Jn(c.lead,l.length)):Ie(c.lead.kind==="cmd"?c.lead.cmd:c.lead.text,Jn(c.lead,l.length))),ze.current.armed=l},[p,Ie,Cr]),Ee=X((c,d,l="info")=>{ze.current.armed=[],c&&p({kind:"note",tone:l,text:c}),d&&(d.kind==="answer"?Cr(Jn(d)):Ie(d.kind==="cmd"?d.cmd:d.text,Jn(d)))},[p,Ie,Cr]),wi=X((c,d,l,w="info")=>{if(c.producedNothing){Ee("Nothing was changed \u2014 the agent produced no output, so this command did nothing at all.",{kind:"cmd",cmd:"/doctor",reason:"it checks Claude sign-in + whether the model is reachable from this machine"},"warn");return}Ee(d,l,w)},[Ee]),[mo,yi]=Z(null),[Lm,Oc]=Z(!1),At=X((c,d)=>{yi(c),Oc(!1),p({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)."})},[p]),ki=X(()=>{L0(e,new Date().toISOString());let c=ph(e);c&&(p({kind:"note",tone:"info",text:c.lines.join(`
|
|
438
|
+
`)}),At(c.prompt,_0(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,p,At]),bi=re(!1),$i=X(async()=>{try{if(bi.current||!C0(x0())||de(e)?.mode==="engineer")return;let c=await v0({pkg:Xn,currentVersion:o,force:!0});if(!c.updateAvailable||!c.latest)return;bi.current=!0,p({kind:"note",tone:"info",text:`\u2B06 Updating ${Xn} ${c.current} \u2192 ${c.latest}\u2026 (wait for the \u2713 before you /exit)`}),yr(!0),(await Ls().finally(()=>yr(!1))).ok?(p({kind:"note",tone:"ok",text:`\u2713 Updated to v${c.latest} \u2014 run /exit, then relaunch to apply.`}),ee("/exit"),Cc(c.latest)):p({kind:"note",tone:"warn",text:`Update available (v${c.latest}) but auto-update failed \u2014 run: ${Os}`})}catch{}},[e,o,p,ee]),go=re(!1),vi=re(null),Lc=X(async c=>{if(!go.current)try{let d=de(e);if(!d)return;let l=_c.current;if(!l)return;if(l.pushConsent!=="on"){if(l.uncommitted===0)return;go.current=!0;try{let E=await A0(e,d);if(E.commit?.ok)vi.current=null;else if(E.commit&&!E.commit.ok){let F=`${E.commit.reason}:${E.commit.detail??""}`;vi.current!==F&&(vi.current=F,p({kind:"note",tone:"warn",text:`\u26A0 Couldn't save your docs work to git \u2014 ${qt(E.commit.reason,E.commit.detail)}`}))}}finally{go.current=!1}return}if(l.uncommitted===0&&l.unpushed===0&&!c.pull)return;go.current=!0;try{let{lines:E,changed:F}=await js(e,d);for(let f of E)f.tone==="warn"||f.tone==="error"?p({kind:"note",tone:f.tone,text:f.text}):f.text.includes("\u2B07")&&p({kind:"note",tone:f.tone,text:f.text});F&&G(f=>f+1)}finally{go.current=!1}}catch{}},[e,p]),wo=X(c=>{let d=Be(e,s);return d.ok?!0:(p({kind:"note",tone:"warn",text:d.reason}),po.current=c,ee("/login"),!1)},[e,s,p,ee]),[Rr,xi]=Z(null),_c=re(null),ot=X((c,d)=>{let l=ar(e,s,{claudeMissing:yc(t).state==="missing",allowAutoAudit:c,genreUnknown:Ct.current,pendingAnswer:Ze.current});return _c.current=l?.handoff??null,l?ir(l,{header:d,pickable:!0}):{kind:"idle"}},[e,s,t]),Ci=re(Date.now()),yo=re(Tf()),Mc=re(0),[Uc,Fc]=Z(null),ko=re(!0),Nn=re(!1),Sr=re(0),bo=re(0);Ge(()=>{let c=setInterval(()=>{if(ko.current){Sr.current=0,bo.current=0;return}if(!S)try{if(!to(fm(e)))return;if(it(e).status==="current"){ko.current=!0,Sr.current=0,bo.current=0;let l=Nn.current?`\u2713 Your builder finished the protocol update (v${xe}) \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=ot(!1,l),E=w.kind==="recommend"?w.rec:null;yi(null),E?.note?yt(E,{tone:"ok"}):(p({kind:"note",tone:"ok",text:`${l}${E?.lead?` ${sr(E.lead)}`:""}`}),E?.lead||E?.picker?yt(E,{silent:!0}):Nn.current||Ie("write the docs for this repo")),G(F=>F+1);return}if(Nn.current)return;Sr.current+=1;let d=Sr.current;if((d===4||d%15===0)&&bo.current<3){bo.current+=1;let l=bo.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";p({kind:"note",tone:"info",text:$t(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${l}`:`\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.${l}`})}}catch{}},4e3);return()=>clearInterval(c)},[e,S,p,ot,yt,Ie]),Ge(()=>{let c=Pc??pr(e);if(!S){Zs(0),Qn(`${ti} ${c}`);return}Zs(3);let d=0;Qn(`${ei[0]} ${c}`);let l=setInterval(()=>{d=(d+1)%ei.length,Qn(`${ei[d]} ${c}`)},400);return()=>clearInterval(l)},[S,e,Pc]),Ge(()=>()=>Zs(0),[]),Ge(()=>{let c=performance.now(),d=[],l=(m,$)=>{let y=performance.now();try{return $()}finally{let v=Math.round(performance.now()-y);v>=80&&d.push(`${m}: ${v}ms`)}};p({kind:"banner",info:l("banner",()=>F0(e,o,t,s))});let w=yc(t).state==="missing";if(w&&p({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.
|
|
439
|
+
${zx}
|
|
440
440
|
Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!de(e)){p({kind:"note",tone:"info",text:`Welcome! This repo isn't set up for d360-writer yet \u2014 three steps and you're writing docs:
|
|
441
|
-
${
|
|
442
|
-
`)}),At(dn()),
|
|
443
|
-
`)}),m.reopenedForRedaction&&p({kind:"note",tone:"warn",text:Yr(m.reopenedForRedaction)})}catch{}let F=l("ready-decision",()=>
|
|
441
|
+
${km}`}),ee(w?"/doctor":"/init");return}w&&ee("/doctor");try{let m=Qe(e,s),$=$n(m.name);$&&Vt($)&&$.refreshToken?Zx({profile:m.name,connection:m.connection}).then(()=>{p({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),G(y=>y+1)}).catch(()=>{p({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 sign in again with /login."}),ee("/login")}):(!$||Vt($))&&(p({kind:"note",tone:"warn",text:`Profile "${m.name}" is not signed in \u2014 sign in with /login.`}),ee("/login"))}catch{}try{let m=de(e),$=Qe(e,s),y=$n($.name);m&&y&&!Vt(y)&&Xl(e,m.authoritativeSourceFiles)&&!Jl(e,s)&&(p({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),ee("/scope"))}catch{}try{let m=l("resolve-genre",()=>p0(e));m.persisted&&m.appType?p({kind:"note",tone:"ok",text:`\u2713 Detected a ${m.appType} app \u2014 enabled the ${m.appType}-doc-playbook (change with /genre, or edit .d360-writer/config.json).`}):m.source==="unknown"&&de(e)&&(Ct.current=!0)}catch{}let E=it(e);try{if(l("reconcile-devhints",()=>Xr(e)),E.status!=="current"&&!$t(e)){let m=Jr(e);m.length&&(p({kind:"note",tone:"warn",text:m.join(`
|
|
442
|
+
`)}),At(dn()),ko.current=!1,Nn.current=!1)}}catch{}try{let m=l("reconcile-feedback",()=>R0(e));m.archived>0&&p({kind:"note",tone:"ok",text:`\u2713 Tidied ${m.archived} resolved item${m.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${m.open>0?`; ${m.open} still open`:""}.`})}catch{}try{let m=l("upgrade-actions",()=>S0(e));m.applied.length>0&&p({kind:"note",tone:"warn",text:Vr(m.applied).join(`
|
|
443
|
+
`)}),m.reopenedForRedaction&&p({kind:"note",tone:"warn",text:Yr(m.reopenedForRedaction)})}catch{}let F=l("ready-decision",()=>ot(!0));F.kind==="autoAudit"?(p({kind:"note",tone:"info",text:F.note}),Bo().then(m=>{m.kind!=="forward-to-agent"||!m.prompt||he(m.prompt,{display:m.display,quietUser:!0}).then($=>{$.producedNothing||(or(e,s),G(y=>y+1))})})):F.kind==="recommend"&&yt(F.rec);let f=Math.round(performance.now()-c);f>=800&&E0({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${f}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${d.length?d.join(`
|
|
444
444
|
`):"no single phase \u226580ms"}
|
|
445
|
-
cwd: ${e}`}),$i(),Lc({pull:!0})},[]),Ge(()=>{let c=setInterval(()=>{$i()},
|
|
446
|
-
|
|
447
|
-
${D}`)}catch{}d?.quietUser||p({kind:"user",text:d?.echoDisplay&&d.display?d.display:c});let w=gt.current;w.firstPrompt||(w.firstPrompt=d?.display??c),Rt.current=Date.now(),Kt(0),R(!0),io.current.clear();let E="",F=!1,f=!1,m=!1,$=!1,y="",v={num:0,closed:!1,cueSeen:!1},P=null,M=()=>{P||(P=setTimeout(()=>{P=null,u(y.length>0?y:null)},60))},H=()=>{P&&clearTimeout(P),P=null,u(null)},J=(D=!1)=>{let{head:O,keep:I}=
|
|
448
|
-
`)}),ee("/review --fix");return}}let w=
|
|
449
|
-
`)});let D=Ra(e,s);if(D&&p({kind:"note",tone:"info",text:D}),!v.aborted&&!J){try{let I=await gc({cwd:e,profileName:s,onRateLimit:se=>
|
|
450
|
-
`)}),!m.aborted&&!m.blocked&&!m.allEmpty&&y>0){let M=
|
|
451
|
-
`)}),ee("/review --fix");return}await he(xa(c),{display:`/publish ${c}`,quietUser:!0})}let l=d?.skipReview?null:await Gn(e,s);l&&p({kind:"note",tone:"info",text:l});try{let w=await $s(e,s,c.replace(/\\/g,"/"));w.length>0&&(An(`Related articles not yet published (${w.length}):`),le([`/publish --related ${c}`,...w.map(E=>`/publish ${E}`)]))}catch{}},[e,s,he,
|
|
452
|
-
`):`${P}Authored specs \u2014 ${v}/${y.results.length} batches ok.${M}`}),H&&(ee("/doctor"),$=!1),!y.aborted&&y.ok&&!H&&Ar(d.runLine)}}catch(y){p({kind:"note",tone:"error",text:`Spec authoring failed: ${y.message}`})}finally{Te.current=null,ce(null),R(!1),G(y=>y+1)}if($){let y=await Kn();y.kind==="forward-to-agent"&&y.prompt&&await he(y.prompt,{display:y.display,quietUser:!0}),ki()}},[e,s,p,he,Ar,ki]),Kc=X(async c=>{let d=sa(e,c,pn(e,c))??void 0,l=await ws([c],void 0,{prior:d});l.kind==="forward-to-agent"&&l.prompt&&await he(l.prompt,{display:l.display,quietUser:!0}),
|
|
453
|
-
${wl(U.output)}`});return}p({kind:"note",tone:"ok",text:"\u2713 Login saved \u2014 continuing with the capture."})}let l=new Map(c.map(I=>[I,
|
|
454
|
-
${$}`:"")});let y=Date.now(),v=[];try{for(let I of c){if(E.signal.aborted)break;ce(Y=>Y&&{...Y,active:[I],rows:qe(Y.rows,I,"active"),lastAt:Date.now()});let{exitCode:U,output:se}=await yl({cwd:e,id:I,signal:E.signal,stdio:"pipe"});if(kl(U,se)){p({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 Re=E.signal.aborted&&U!==0?"failed":gl(e,I,U,y),
|
|
455
|
-
${I}`).join("")});let D=
|
|
445
|
+
cwd: ${e}`}),$i(),Lc({pull:!0})},[]),Ge(()=>{let c=setInterval(()=>{$i()},K0);return()=>clearInterval(c)},[$i]),Ge(()=>{let c=setInterval(()=>{try{let d=Date.now(),l=ac(d,Ci.current);if(Mc.current+=1,l&&Mc.current%Math.round(3e5/6e4)!==0)return;let w=M0(e),E=yo.current,F=w===E.fingerprint&&E.counts?E.counts:yn(e),f=Af({now:d,lastInputAt:Ci.current,fingerprint:w,counts:F,occupied:S||ae||pe.length>0||k!==""||fo||me.current.length>0,prev:E});if(yo.current=f.memory,Fc(f.waiting),f.speak){p({kind:"note",tone:"info",text:Nf(f.speak)});let m=ot(!1);m.kind==="recommend"&&yt(m.rec,{silent:!0})}}catch{}},6e4);return()=>clearInterval(c)},[e,S,ae,pe.length,k,fo,p,ot,yt]),Ge(()=>{if(S||ae||Se.current||ke!==null||pe.length>0||k!==""||mo!==null||me.current.length>0||ao.current||fo)return;let c=ot(!1);c.kind==="recommend"&&(c.rec.lead||c.rec.picker)&&yt(c.rec,{silent:!0}),Lc({pull:!1})},[S,ae,ke,pe,k,mo,fo,K,ot,Yt]),Ge(()=>{let c=null,d=null,l=()=>{c&&clearTimeout(c),c=setTimeout(()=>{c=null;let w=`${_e.columns??80}x${_e.rows??24}`;w!==Ic.current&&(Ic.current=w,Om(E=>E+1),d&&clearTimeout(d),d=setTimeout(()=>{d=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+cd(Cn.current,Et())+"\x1B[?2026l")},80))},400)};return _e.on("resize",l),()=>{c&&clearTimeout(c),d&&clearTimeout(d),_e.off("resize",l)}},[_e,Et]);let Me=Math.max(20,(_e.columns??80)-1),Wc=dc(()=>W0(e,s),[e,s,K]),Ri=(()=>{if(Dm)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(ui!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${ui?` v${ui}`:""}\u2026`,isSetup:!0};if(Rr)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(mo)return Lm?{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(Uc)return{text:If(Uc),isSetup:!0};if(me.current.length>0){let w=me.current.length;return me.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 c=de(e);if(!c)return{text:"Run /init to set up this repo (or /help)\u2026",isSetup:!0};let d=pc(e,(c.docsDir??bc).replace(/\/+$/,"")),l=(()=>{try{return to(d)&&Gx(d).length>0}catch{return!1}})();try{let w=Qe(e,s),E=$n(w.name);if(!(!!E&&!(Vt(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&&!l)return{text:"Pick a workspace with /workspace\u2026",isSetup:!0}}catch{}return l?{text:B0,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),kt=Zu(k),Bc=kt.length>0&&!S,_m=12,Dt=rc(_e.rows),Mm=_e.rows??24,Hc=rc(_e.rows,{max:_m}),Pr=Math.min(di,Math.max(0,kt.length-1)),un=Qs(kt.length,Pr,Hc).start,Si=kt.slice(un,un+Hc),Pi=a!==null?Qf(a,8,Me):null,Tr=Ve?Ve.paths.filter(c=>!Ve.query||c.toLowerCase().includes(Ve.query.toLowerCase())).slice(0,8):[],Er=Ke?Ke.sessions.filter(c=>{let d=Ke.query.toLowerCase();return!d||c.name.toLowerCase().includes(d)||c.firstPrompt.toLowerCase().includes(d)}).slice(0,8):[],Ue=X((c,d)=>{et.current?.close(),et.current=nm({cwd:e,resume:c,profileName:d??s,allowProdWrites:zt.current}),c||(gt.current={uuid:null,firstPrompt:null,titleFired:!1},Jt(null)),ln(0),cn(0)},[e,s]),qc=X((c,d,l)=>{if($m.test(c))try{let w=Qe(e,s),E=typeof d.project_id=="string"&&d.project_id||w.project.projectId,F=zs(d,l),f=[],m=Xs(l);c.endsWith("publish_article")&&m&&f.push(`Live: ${m}`);let $=Js(l);$?f.push(`Preview: ${$}`):F&&E&&f.push(`Preview: ${Ks(w.connection.portalUrl,E,F,w.project.languageCode??"en")}`),f.length>0&&p({kind:"link",lines:f})}catch{}},[e,s,p]),he=X(async(c,d)=>{wr(!0),Se.current=!1,Pe.current=!1,Ze.current=null,ut(),le([]),An(null),yi(null);let l=lt.current;if(d?.display?.startsWith("/"))try{let D=Fh(e,d.display);D&&(c=`${c}
|
|
446
|
+
|
|
447
|
+
${D}`)}catch{}d?.quietUser||p({kind:"user",text:d?.echoDisplay&&d.display?d.display:c});let w=gt.current;w.firstPrompt||(w.firstPrompt=d?.display??c),Rt.current=Date.now(),Kt(0),R(!0),io.current.clear();let E="",F=!1,f=!1,m=!1,$=!1,y="",v={num:0,closed:!1,cueSeen:!1},P=null,M=()=>{P||(P=setTimeout(()=>{P=null,u(y.length>0?y:null)},60))},H=()=>{P&&clearTimeout(P),P=null,u(null)},J=(D=!1)=>{let{head:O,keep:I}=Zf(y,D);O.trim()&&p({kind:"assistant",text:oc(O.trimEnd(),v)}),y=I,H()};try{for await(let D of et.current.send(c))if(D.type==="session"){if(!w.uuid){w.uuid=D.sessionId;let O=new Date().toISOString(),I=hi.current,U=I??s0(w.firstPrompt??"session");i0({uuid:D.sessionId,name:U,renamed:!!I,titled:!1,cwd:e,firstPrompt:w.firstPrompt??"",createdAt:O,updatedAt:O}),Jt(U),hi.current=null}}else if(D.type==="text"){y+=D.delta,E+=D.delta;let O=em(y);if(O>0){let I=y.slice(0,O).trimEnd();I&&p({kind:"assistant",text:oc(I,v)}),y=y.slice(O)}M(),Kt(I=>I+D.delta.length)}else if(D.type==="tool"){F=!0,$m.test(D.name)&&(f=!0);let I=(ue=>typeof ue=="string"&&ue?ue.replace(/\\/g,"/").toLowerCase():null)(D.input.file_path??D.input.notebook_path),U=["Edit","Write","MultiEdit","NotebookEdit"].includes(D.name),se=D.name==="Read"&&I!==null&&I===Sc.current;Sc.current=U?I:null;let Re=br.current,st=Re?null:Xf(D.name,D.input),Y=Re?null:Gs(D.name,D.input,e,s);if(st)gi.current.push(st);else if(Y)J(),p({kind:"doc",verb:Y.verb,title:Y.title,category:Y.category,note:Y.note,...Y.loud?{loud:Y.loud}:{}}),io.current.set(D.id,{name:D.name,input:D.input,doc:!0,keepResult:Y.keepResult});else if(se)J(),p({kind:"tool",title:"Read",sep:"",arg:"re-checking the file it just edited"});else{let ue=Vs(D.name,D.input,e);ue&&(J(),p({kind:"tool",title:ue.title,sep:ue.sep,arg:ue.arg}),io.current.set(D.id,{name:D.name,input:D.input}))}}else if(D.type==="article_diff"){let O=Xe(D.oldContent,D.newContent,Et());O&&(J(),p({kind:"diff",added:O.added,removed:O.removed,lines:O.lines,hidden:O.hidden}))}else if(D.type==="tool_result"){D.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(D.output)&&($r.current=!0);let O=io.current.get(D.id);if(O){io.current.delete(D.id),J();let U=O.doc&&!O.keepResult&&!D.isError?{lines:[],hidden:0}:Ys(D.output,4,D.isError||br.current?void 0:O.name,O.input);U.lines.length>0&&p({kind:"tool-result",lines:U.lines,hidden:U.hidden,isError:D.isError}),D.isError||qc(O.name,O.input,D.output)}}else if(D.type==="result"){J(!0),ln(U=>U+D.outputTokens),cn(U=>U+D.costUsd);let O=D.inputTokens+D.cacheReadTokens+D.cacheCreationTokens;if(p({kind:"done",seconds:Math.round((Date.now()-Rt.current)/1e3),tokens:D.outputTokens,costUsd:D.costUsd,ok:D.ok,...O>0?{inTokens:O,cachedPct:Math.round(D.cacheReadTokens/O*100)}:{}}),!m&&!F&&!E.trim()&&!lo.current&&($=!0,p({kind:"note",tone:"warn",text:"The agent produced no output \u2014 nothing ran this turn. Two usual causes: the Claude model/runtime (check /doctor \u2014 sign-in + reachability), or a Claude usage limit reached mid-session, which ends every turn instantly and leaves /doctor completely clean."})),D.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(E))try{let U=mm(e);if(to(U)){let se=ii(U,"utf8").trim();se&&(xi(se),p({kind:"note",tone:"info",text:"\u{1F6E0} Press c to copy this feedback \u2014 send it to the d360-writer team (Teams / Slack / email)."}))}}catch{}let I=D.ok?kf(E):null;if(Pe.current=I!==null,Ze.current=I,D.ok&&(v.cueSeen||(I?.options??0)>=2))mr(!0),le([]);else if(I)le([]);else{let U=D.ok?Lf(E,Bn.map(se=>se.name)):[];if(U.length>0)ee(U[0]);else if(D.ok&&E.trim()&&!Pe.current){let se=ot(!1);se.kind==="recommend"&&(se.rec.lead||se.rec.picker)||u0(c,E,e).then(Re=>{Re&<.current===l&&Ie(Re)}).catch(()=>{})}}if(w.uuid&&(hc(w.uuid),!w.titleFired)){w.titleFired=!0;let U=w.uuid,se=w.firstPrompt;se&&om(se,e).then(Re=>{Re&&(r0(U,Re),Jt(Re))}).catch(()=>{})}}else D.type==="error"&&(J(!0),m=!0,D.kind==="auth"&&($r.current=!0),p(D.kind==="limit"?{kind:"note",text:`\u23F3 ${D.message}`,tone:"warn"}:{kind:"note",text:`agent error: ${D.message}`,tone:"error"}))}finally{if(R(!1),H(),xr(),f)try{let D=wc(await gc({cwd:e,profileName:s,onRateLimit:O=>Ye(`Document360 rate limit \u2014 waiting ${Math.ceil(O.waitMs/1e3)}s\u2026`)}));D&&p({kind:"note",tone:D.startsWith("\u26A0")?"warn":"info",text:D})}catch{}finally{Ye(null)}G(D=>D+1),gt.current.uuid&&Sf(e,gt.current.uuid,Cn.current),$r.current?($r.current=!1,uo.current=d?.display??c,Ie("/login","\u21E5 tab to run /login \u2014 then I\u2019ll re-send your last prompt\u2026")):uo.current=null,lo.current&&(lo.current=!1,rn.current.length>0&&(p({kind:"note",tone:"info",text:`(${rn.current.length} queued message(s) discarded)`}),rn.current=[],fi([])),p({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}return{producedNothing:$}},[e,p,qc,Et,Ie,ee,ut,ot,xr]),rt=X(async(c,d=0,l)=>{if(!l?.skipReview){let f=mn(e,c);if(f.length>0){p({kind:"note",tone:"warn",text:bs(f,c.length).join(`
|
|
448
|
+
`)}),ee("/review --fix");return}}let w=fr(e,"standard");Rt.current=Date.now(),Kt(0),R(!0);let E=new AbortController;Te.current=E;let F=async(f,m)=>{let $=fc(f);ce({verb:"Publishing",total:$.length,done:0,active:[],rows:eo($),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),p({kind:"note",tone:"info",text:m?`Resolving cross-links in ${f.length} article${f.length===1?"":"s"} whose targets published this run (second pass)\u2026 (esc to stop)`:`Publishing ${f.length} article${f.length===1?"":"s"} across ${$.length} partition${$.length===1?"":"s"} (\u2264${Uo} agents at once) on ${w.model}\u2026 (esc to stop)`});let y=!1;for await(let v of hr({cwd:e,partitions:$,promptFor:P=>Fo(P.paths),concurrency:Uo,profileName:s,allowProdWrites:zt.current,allowUnreviewedPublish:l?.skipReview===!0,model:w.model,signal:E.signal}))if(v.type==="partition_status")v.status==="running"?ce(P=>P&&{...P,active:[...P.active,v.label],rows:qe(P.rows,v.label,"active"),lastAt:Date.now()}):ce(P=>P&&{...P,active:P.active.filter(M=>M!==v.label),done:P.done+1,rows:qe(P.rows,v.label,v.status==="done"?"done":"failed"),lastAt:Date.now()});else if(v.type==="partition_event")ce(P=>{if(!P)return P;let M={...P,lastAt:Date.now()};return v.event.type==="tool"?M.tools=P.tools+1:v.event.type==="text"&&(M.chars=P.chars+v.event.delta.length),M});else if(v.type==="run_done"){y=v.aborted,cn(O=>O+v.totalCostUsd),ln(O=>O+v.results.reduce((I,U)=>I+U.outputTokens,0));let P=v.aborted?"Stopped. ":"",M=t.kind==="api"?"api":"subscription",H=Pa(e,c,s),J=!v.aborted&&(!!v.blocked||!!v.allEmpty||c.length>0&&H===0);p({kind:"note",tone:v.aborted?"warn":v.ok&&!J?"ok":"warn",text:P+Ta(v.results,$,M,m?0:d,{recorded:H,...v.blocked?{blocked:v.blocked}:{},...v.allEmpty?{allEmpty:!0}:{},...v.bailedEmpty?{bailedEmpty:!0,notRun:v.notRun??0}:{}}).join(`
|
|
449
|
+
`)});let D=Ra(e,s);if(D&&p({kind:"note",tone:"info",text:D}),!v.aborted&&!J){try{let I=await gc({cwd:e,profileName:s,onRateLimit:se=>Ye(`Document360 rate limit \u2014 waiting ${Math.ceil(se.waitMs/1e3)}s\u2026`)}),U=wc(I);U?p({kind:"note",tone:U.startsWith("\u26A0")?"warn":"info",text:U}):I.skipped&&p({kind:"note",tone:"warn",text:`Order sync skipped: ${I.skipped}`})}catch(I){p({kind:"note",tone:"warn",text:`Order sync failed: ${I.message}`})}finally{Ye(null)}try{let I=ym(await wm({cwd:e,profileName:s}));I&&p({kind:"note",tone:"info",text:I})}catch(I){p({kind:"note",tone:"warn",text:`Related-articles sync failed: ${I.message}`})}let O=await Gn(e,s);O&&p({kind:"note",tone:"info",text:O})}}return y};try{if(!await F(c,!1)){let m=await Ea(e,s,c);m.length>0&&await F(m,!0),d>0&&Ee(null,{kind:"cmd",cmd:"/resolve",reason:`${d} conflict${d===1?"":"s"} still need settling \u2014 they were left untouched`},"warn")}}catch(f){p({kind:"note",tone:"error",text:`Publish run failed: ${f.message}`})}finally{Te.current=null,ce(null),R(!1),G(f=>f+1)}},[e,s,p,t,Ee]),Gc=X(async(c,d)=>{if(c.length===0)return;let l=c.reduce((m,$)=>m+$.threads.length,0),w=new Map,E=c.map(m=>(w.set(m.label,m),{label:m.label,paths:m.path?[m.path]:[]})),F=fr(e,"standard");Rt.current=Date.now(),Kt(0),R(!0);let f=new AbortController;Te.current=f,ce({verb:"Answering",unit:"article",total:E.length,done:0,active:[],rows:eo(E),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),p({kind:"note",tone:"info",text:`Answering ${l} comment${l===1?"":"s"} across ${E.length} article${E.length===1?"":"s"} (\u2264${tr} agents at once) on ${F.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 m of hr({cwd:e,partitions:E,promptFor:$=>{let y=w.get($.label);return Il({articleId:y.articleId,label:y.label,path:y.path,count:y.threads.length,resolve:d.resolve})},concurrency:tr,profileName:s,allowProdWrites:zt.current,allowCommentResolve:d.resolve,model:F.model,signal:f.signal}))if(m.type==="partition_status")m.status==="running"?ce($=>$&&{...$,active:[...$.active,m.label],rows:qe($.rows,m.label,"active"),lastAt:Date.now()}):ce($=>$&&{...$,active:$.active.filter(y=>y!==m.label),done:$.done+1,rows:qe($.rows,m.label,m.status==="done"?"done":"failed"),lastAt:Date.now()});else if(m.type==="partition_event")ce($=>{if(!$)return $;let y={...$,lastAt:Date.now()};return m.event.type==="tool"?y.tools=$.tools+1:m.event.type==="text"&&(y.chars=$.chars+m.event.delta.length),y});else if(m.type==="run_done"){cn(M=>M+m.totalCostUsd),ln(M=>M+m.results.reduce((H,J)=>H+J.outputTokens,0));let $=m.results.filter(M=>!M.ok),y=m.results.length-$.length,P=[`${m.aborted?"Stopped. ":""}${y}/${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(M=>M.label).join(", ")}`]:[],...m.blocked?[`\u26A0 ${m.blocked}`]:[],...m.allEmpty?["\u26A0 No agent produced any work this run \u2014 nothing was changed or answered."]:[]];if(p({kind:"note",tone:m.aborted||$.length||m.blocked||m.allEmpty?"warn":"ok",text:P.join(`
|
|
450
|
+
`)}),!m.aborted&&!m.blocked&&!m.allEmpty&&y>0){let M=Wo(e,{text:"",cmd:"/publish --all"});Ee(M.cmd==="/publish --all"?null:M.text,{kind:"cmd",cmd:M.cmd,reason:M.cmd==="/publish --all"?"the fixed articles are drafts on Document360 \u2014 this makes them live":""})}}}catch(m){p({kind:"note",tone:"error",text:`Answering comments failed: ${m.message}`})}finally{Te.current=null,ce(null),R(!1),G(m=>m+1)}},[e,s,p,Ee]),Ti=X(async(c,d)=>{if(d?.skipReview)await rt([c],0,{skipReview:!0});else{let w=mn(e,[c]);if(w.length>0){p({kind:"note",tone:"warn",text:bs(w,1).join(`
|
|
451
|
+
`)}),ee("/review --fix");return}await he(xa(c),{display:`/publish ${c}`,quietUser:!0})}let l=d?.skipReview?null:await Gn(e,s);l&&p({kind:"note",tone:"info",text:l});try{let w=await $s(e,s,c.replace(/\\/g,"/"));w.length>0&&(An(`Related articles not yet published (${w.length}):`),le([`/publish --related ${c}`,...w.map(E=>`/publish ${E}`)]))}catch{}},[e,s,he,rt]),Vc=X(async c=>{try{let d=await li({cwd:e,profileName:s}),{clean:l,conflicts:w}=fn(d.entries);if(l.length===0){p({kind:"note",tone:"info",text:"Nothing new to publish \u2014 everything is already up to date on Document360."});return}await rt(l.map(E=>E.path),w.length,{skipReview:c?.skipReview})}catch(d){p({kind:"note",tone:"warn",text:`Couldn\u2019t check what to publish (${d.message}) \u2014 your drafts are saved; run /publish when ready.`})}},[e,s,rt]),Ar=X(c=>{if(c)try{for(let d of Array.isArray(c)?c:[c]){let l=Vl(e,d);if(!l)continue;Ws(e,l.title).ok&&p({kind:"note",tone:"ok",text:`\u2713 That completed a docs-campaign step \u2014 marked done: ${l.title}`});return}}catch{}},[e,p]),Yc=X(async(c,d)=>{let w=k0(c,3),E=fr(e,"standard"),F=new Map,f=new Map;for(let y of c){let v=pn(e,y),P=sa(e,y,v);if(P&&F.set(y,P),v!==null){let M=ka(v);M.length>0&&f.set(y,M)}}Rt.current=Date.now(),Kt(0),R(!0);let m=new AbortController;Te.current=m,ce({verb:"Authoring",unit:"spec",total:w.length,done:0,active:[],rows:eo(w),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),p({kind:"note",tone:"info",text:`Authoring ${c.length} screenshot spec${c.length===1?"":"s"} across ${w.length} partition${w.length===1?"":"s"} (\u22646 agents at once) on ${E.model}${E.forced?" (forced)":""}\u2026 (esc to stop)`});let $=!1;try{for await(let y of hr({cwd:e,partitions:w,promptFor:v=>Kd(v,F,f),concurrency:6,profileName:s,allowProdWrites:zt.current,model:E.model,signal:m.signal}))if(y.type==="partition_status")y.status==="running"?ce(v=>v&&{...v,active:[...v.active,y.label],rows:qe(v.rows,y.label,"active"),lastAt:Date.now()}):ce(v=>v&&{...v,active:v.active.filter(P=>P!==y.label),done:v.done+1,rows:qe(v.rows,y.label,y.status==="done"?"done":"failed"),lastAt:Date.now()});else if(y.type==="partition_event")ce(v=>{if(!v)return v;let P={...v,lastAt:Date.now()};return y.event.type==="tool"?P.tools=v.tools+1:y.event.type==="text"&&(P.chars=v.chars+y.event.delta.length),P});else if(y.type==="run_done"){cn(J=>J+y.totalCostUsd),ln(J=>J+y.results.reduce((D,O)=>D+O.outputTokens,0));let v=y.results.filter(J=>J.ok).length,P=y.aborted?"Stopped. ":"";$=!y.aborted&&d.setup;let M=y.aborted?"":$?" Refreshing the staging checklist\u2026":" Next: /screenshot capture --all (or /screenshot checklist first for the staging checklist).",H=pt(y,"Spec authoring");p({kind:"note",tone:H||y.aborted?"warn":y.ok?"ok":"warn",text:H?H.join(`
|
|
452
|
+
`):`${P}Authored specs \u2014 ${v}/${y.results.length} batches ok.${M}`}),H&&(ee("/doctor"),$=!1),!y.aborted&&y.ok&&!H&&Ar(d.runLine)}}catch(y){p({kind:"note",tone:"error",text:`Spec authoring failed: ${y.message}`})}finally{Te.current=null,ce(null),R(!1),G(y=>y+1)}if($){let y=await Kn();y.kind==="forward-to-agent"&&y.prompt&&await he(y.prompt,{display:y.display,quietUser:!0}),ki()}},[e,s,p,he,Ar,ki]),Kc=X(async c=>{let d=sa(e,c,pn(e,c))??void 0,l=await ws([c],void 0,{prior:d});l.kind==="forward-to-agent"&&l.prompt&&await he(l.prompt,{display:l.display,quietUser:!0}),jd(e,c)&&Ee(`Spec ready \u2014 /screenshot capture ${c} takes the screenshot; bare /screenshot picks the next shot.`,{kind:"cmd",cmd:`/screenshot capture ${c}`,reason:""})},[e,he,Ee]),$o=X(async(c,d)=>{if(!Ds(e)){await he(bl(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(!nh(e)){p({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)"}),R(!0),Ye("Waiting for you to finish logging in (browser window)\u2026");let I=new AbortController;Te.current=I;let U;try{U=await oh({cwd:e,signal:I.signal})}catch(se){p({kind:"note",tone:"error",text:`Could not launch the login: ${se.message}`});return}finally{Te.current=null,Ye(null),R(!1)}if(U.exitCode!==0){kl(U.exitCode,U.output)?p({kind:"note",tone:"error",text:"d360-capture is not installed on this machine. Run: npm i -g document360-capture \u2014 then /screenshot capture again."}):/unknown option/i.test(U.output)?p({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."}):p({kind:"note",tone:I.signal.aborted?"warn":"error",text:I.signal.aborted?"Login cancelled \u2014 nothing saved.":`Login did not complete:
|
|
453
|
+
${wl(U.output)}`});return}p({kind:"note",tone:"ok",text:"\u2713 Login saved \u2014 continuing with the capture."})}let l=new Map(c.map(I=>[I,Ud(e,I)])),w=0;if(c.length>1){let I=c.filter(U=>l.get(U).mutates);if(I.length>0&&(w=I.length,c=c.filter(U=>!l.get(U).mutates),c.length===0)){p({kind:"note",tone:"warn",text:`\u26A0 All ${I.length} spec${I.length===1?"":"s"} in scope write real data, so a bulk run has nothing to do. Run one deliberately: /screenshot capture ${I[0]}`});return}}else if(c.length===1&&l.get(c[0]).mutates){let I=l.get(c[0]),U=rh(e);p({kind:"note",tone:"warn",text:`\u26A0 This capture performs a REAL write in your app${I.what?`: ${Md(I.what)}`:I.declared?"":" (detected from the spec: form fill + commit click / file upload)"}. Running because you named it explicitly \u2014 check the result and clean up what it created. `+(U.production?`This profile is PRODUCTION \u2014 the write lands in the LIVE tenant${U.url?` (${U.url})`:""}. If the spec cleans up after itself, confirm it did.`:"Tip: point the capture scope (.d360-writer/capture.json) at a demo/non-production context for shots like this.")})}R(!0);let E=new AbortController;Te.current=E;let F=c.map(I=>({label:I,items:1,status:"pending"}));ce({verb:"Capturing",unit:"screenshot",total:c.length,done:0,active:[],rows:F,tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()});let f=vt(e),m=Object.keys(f.shots).length>0,$=sh(d?.heldBackBlocked??[],w);p({kind:"note",tone:"info",text:`Capturing ${c.length} screenshot${c.length===1?"":"s"} with d360-capture (a real browser drives your app)\u2026 (esc to stop)`+($?`
|
|
454
|
+
${$}`:"")});let y=Date.now(),v=[];try{for(let I of c){if(E.signal.aborted)break;ce(Y=>Y&&{...Y,active:[I],rows:qe(Y.rows,I,"active"),lastAt:Date.now()});let{exitCode:U,output:se}=await yl({cwd:e,id:I,signal:E.signal,stdio:"pipe"});if(kl(U,se)){p({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 Re=E.signal.aborted&&U!==0?"failed":gl(e,I,U,y),st=Re==="captured"?void 0:Re==="skipped"?eh(se)??"a data prerequisite isn't met \u2014 the spec's skip reason names what to stage":th(se);v.push({id:I,outcome:Re,detail:st}),ce(Y=>Y&&{...Y,active:[],done:Y.done+1,rows:qe(Y.rows,I,Re==="captured"?"done":"failed"),lastAt:Date.now()})}}catch(I){p({kind:"note",tone:"error",text:`Capture run failed: ${I.message}`})}finally{Te.current=null,ce(null),R(!1),G(I=>I+1)}if(v.length===0)return;let P=v.filter(I=>I.outcome==="captured"),M=v.filter(I=>I.outcome==="skipped"),H=v.filter(I=>I.outcome==="failed"),J=c.length-v.length;p({kind:"note",tone:H.length?"warn":P.length?"ok":"info",text:[`\u2713 ${P.length} captured`,M.length?`\u2298 ${M.length} blocked`:"",H.length?`\u2717 ${H.length} broken`:"",J?`${J} not run (stopped)`:""].filter(Boolean).join(" ")+` ${v.length} run${w>0?` \xB7 ${w} held back`:""}`+lh(ih(f,v),m).map(I=>`
|
|
455
|
+
${I}`).join("")});let D=ah(M);if(D.length>0&&p({kind:"note",tone:"info",text:D.join(`
|
|
456
456
|
`)}),H.length>0){let I=Math.max(...H.map(U=>U.id.length));p({kind:"note",tone:"error",text:H.map(U=>`\u2717 ${U.id.padEnd(I)} ${As(U.detail)}`).join(`
|
|
457
|
-
`)})}if(rs(e,v.map(I=>({id:I.id,outcome:I.outcome,reason:I.detail,specSource:pn(e,I.id)})),new Date().toISOString()),v.length===c.length&&H.length===0&&M.length===0&&Ar(d?.runLine),P.length>0){let I=P.map(se=>se.id);p({kind:"note",tone:"info",text:
|
|
458
|
-
`)});return}let O=
|
|
459
|
-
`)}),At(dn()),
|
|
457
|
+
`)})}if(rs(e,v.map(I=>({id:I.id,outcome:I.outcome,reason:I.detail,specSource:pn(e,I.id)})),new Date().toISOString()),v.length===c.length&&H.length===0&&M.length===0&&Ar(d?.runLine),P.length>0){let I=P.map(se=>se.id);p({kind:"note",tone:"info",text:zo(I.length)}),await he(wn(e,I),{display:"/screenshot verify",quietUser:!0});let U=Xo(e,I);U.length>0&&p({kind:"note",tone:"info",text:U.join(`
|
|
458
|
+
`)});return}let O=ch({results:v,ids:c,articles:uh(e,P.map(I=>I.id))});O&&Ee(O.note,{kind:"cmd",cmd:O.cmd,reason:""},O.tone)},[e,p,Ee,he,Ar]),Ei=X(c=>{let d=$n(c);if(!d||Vt(d)&&!d.refreshToken)return null;let l={...ro(d.idToken)??{},...ro(d.accessToken)??{}};return l.email??l.preferred_username??"signed in"},[]),Ai=X((c,d)=>{if(d){let l=de(e);l&&(l.defaultProfile=c,rm(l,e))}i(c),Ue(void 0,c),p({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${c}"${d?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),Ei(c)||(p({kind:"note",tone:"warn",text:`Profile "${c}" is not signed in \u2014 sign in with /login.`}),ee("/login")),G(l=>l+1)},[e,p,Ue,Ei,ee]),Dr=X((c,d,l)=>{_r(e,c,d,l.id,l.name),p({kind:"note",tone:"ok",text:`Switched to workspace "${l.name??l.id}" (agent restarted).`}),Ue(),am(e,c)||(p({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),p({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:"}),p({kind:"note",tone:"info",text:Un(Mn(e)).join(`
|
|
459
|
+
`)}),At(dn()),ko.current=it(e).status==="current",Nn.current=$t(e),p({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,p,Ue,At]),Nr=X(async c=>{let d;try{d=await Po(e,c)}catch{p({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),ee("/workspace");return}if(d.workspaces.length===0){p({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let l=d.workspaces.filter(E=>(E.workspace_type??"").toLowerCase()!=="apidocumentation"),w=l.length>0?l:d.workspaces;if(w.length===1){let E=w[0],F=d.workspaces.length-w.length;p({kind:"note",tone:"ok",text:`Selected the "${E.name??E.id}" workspace${F>0?" (skipped the API-documentation workspace)":""}.`}),Dr(d.profile,d.projectId,E);return}p({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${w.length} available).`}),ee("/workspace")},[e,p,Dr,ee]),jr=X((c,d)=>{Mr(e,c,d.id,d.name),p({kind:"note",tone:"ok",text:`Project set to "${d.name??d.id}" (agent restarted).`}),Ue(),Nr(c)},[e,p,Ue,Nr]),zc=X(async c=>{let d;try{d=Qe(e,c)}catch{return}if(!d.project.workspaceId){if(d.project.projectId){if(!d.project.projectName)try{let{projects:l}=await It(e,d.name),w=l.find(E=>E.id===d.project.projectId);w?.name&&T0(e,d.name,{projectName:w.name})}catch{}await Nr(d.name);return}try{let{projects:l}=await It(e,d.name);if(l.length===1){let w=l[0];p({kind:"note",tone:"ok",text:`Using your Document360 project "${w.name??w.id}".`}),jr(d.name,{id:w.id,name:w.name});return}if(l.length>1){let w=l.map(E=>({id:E.id,name:E.name??E.id,sub:E.sub_domain}));p({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),en({cursor:0,current:-1,rows:w,profile:d.name,environment:d.connection.name});return}}catch{}p({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),ee("/project")}},[e,p,Nr,jr,ee]),jn=X(()=>{let c=me.current[0];if(!c)return;ut();let{plan:d,mode:l}=c;p({kind:"note",tone:"info",text:`\u25CF ${d.title} (${d.path})`});for(let F of d.notes)p({kind:"note",tone:"warn",text:`\u26A0 ${F}`});d.overwritesLocalChanges&&l==="pull"&&p({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let w=Xe(d.oldContent,d.newContent,Et());p(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=me.current.length;l==="conflict"?(p({kind:"note",tone:"warn",text:"Conflict \u2014 edited both here and on the portal (diff shows local \u2192 portal)."}),p({kind:"note",tone:"info",text:"Keep local (publish, overwrites portal) \xB7 take Portal (overwrites local) \xB7 Skip?"}),p({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)"})):p({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)`})},[p,Et,ut]),vo=X(()=>{if(me.current.length>0){jn();return}let c=Xt.current;Xt.current=[],c.length>0?(p({kind:"note",tone:"info",text:`Publishing ${c.length} kept-local article${c.length===1?"":"s"} over the portal\u2026`}),rt(c)):ee("/pull")},[jn,p,rt,ee]),Xc=X(c=>{if(me.current.length===0)return!1;let d=c.trim(),l=d.toLowerCase(),w=me.current[0];if(w.mode==="conflict"){let F=$f(d);if(F){let f=me.current.splice(0),m=f.length;if(F==="local"){for(let $ of f)Xt.current.push($.plan.path);p({kind:"note",tone:"info",text:`Keeping local for all ${m} \u2014 will publish ${m===1?"it":"them"} over the portal.`})}else if(F==="portal"){let $=0;for(let y of f)try{ai({cwd:e,profileName:s},y.plan),$++}catch(v){p({kind:"note",tone:"error",text:`Take-portal failed for ${y.plan.path}: ${v.message}`})}p({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${$} article${$===1?"":"s"} (local overwritten, sync base advanced).`})}else p({kind:"note",tone:"info",text:`Skipped all ${m} \u2014 still conflict${m===1?"":"s"}.`});return vo(),!0}if(l==="l"||l==="local")me.current.shift(),Xt.current.push(w.plan.path),p({kind:"note",tone:"info",text:`Keeping local ${w.plan.path} \u2014 will publish over the portal.`});else if(l==="p"||l==="portal"){me.current.shift();try{ai({cwd:e,profileName:s},w.plan),p({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${w.plan.path} (local overwritten, sync base advanced).`})}catch(f){p({kind:"note",tone:"error",text:`Take-portal failed: ${f.message}`})}}else if(l==="s"||l==="skip"||l==="n")me.current.shift(),p({kind:"note",tone:"info",text:`Skipped ${w.plan.path} \u2014 still a conflict.`});else{let f=me.current.length;return me.current=[],Xt.current=[],p({kind:"note",tone:"info",text:`Resolve cancelled (${f} conflict${f===1?"":"s"} left untouched).`}),!0}return vo(),!0}let E=vf(d);if(E){let F=me.current.splice(0);if(E==="skip")p({kind:"note",tone:"info",text:`Skipped all ${F.length} article${F.length===1?"":"s"}.`});else{let f=0;for(let m of F)try{ai({cwd:e,profileName:s},m.plan),f++}catch($){p({kind:"note",tone:"error",text:`Pull failed for ${m.plan.path}: ${$.message}`})}p({kind:"note",tone:"ok",text:`\u2713 Pulled ${f} article${f===1?"":"s"} (sync base advanced).`})}return vo(),!0}if(l==="y"||l==="yes"){let F=me.current.shift().plan;try{ai({cwd:e,profileName:s},F),p({kind:"note",tone:"ok",text:`\u2713 Pulled ${F.path} (sync base advanced).`})}catch(f){p({kind:"note",tone:"error",text:`Pull failed: ${f.message}`})}}else if(l==="n"||l==="no"){let F=me.current.shift().plan;p({kind:"note",tone:"info",text:`Skipped ${F.path}.`})}else{let F=me.current.length;return me.current=[],p({kind:"note",tone:"info",text:`Pull cancelled (${F} article(s) left untouched).`}),!0}return vo(),!0},[e,s,vo,p]),Di=X(async c=>{p({kind:"note",tone:"info",text:"Checking Document360 for conflicts\u2026"});try{let d=await li({cwd:e,profileName:s}),l=c?.replace(/\\/g,"/"),w=d.entries.filter(F=>F.status==="conflict"&&F.path).map(F=>F.path);if(l){if(!w.includes(l)){p({kind:"note",tone:"ok",text:`${l} isn\u2019t in conflict \u2014 nothing to resolve.`});return}w=[l]}if(w.length===0){p({kind:"note",tone:"ok",text:"\u2713 No conflicts \u2014 local and Document360 agree on every tracked article."});return}let E=[];for(let F of w)try{E.push({plan:await cm({cwd:e,profileName:s,relPath:F}),mode:"conflict"})}catch(f){p({kind:"note",tone:"error",text:`Could not load ${F} from Document360: ${f.message}`})}if(E.length===0)return;p({kind:"note",tone:"info",text:`Resolving ${E.length} conflict${E.length===1?"":"s"} \u2014 for each: keep local, take portal, or skip.`}),me.current=E,Xt.current=[],jn()}catch(d){p({kind:"note",tone:"error",text:`Could not compute sync status: ${d.message}`})}},[e,s,p,jn]),Jc=X(c=>{let d=ao.current;if(!d)return!1;if(ao.current=null,ut(),c.trim()!==d.repoName)return p({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:l,failed:w}=Ul(e,d.targets);p({kind:"note",tone:w.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${l.length} item${l.length===1?"":"s"}. The repo is back to its original state.`});for(let E of w)p({kind:"note",tone:"error",text:` \u2717 ${E.path}: ${E.error}`});return d.hadDevhints&&(p({kind:"note",tone:"warn",text:Qr().join(`
|
|
460
460
|
`)}),At(Bi())),p({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
|
|
461
|
-
${
|
|
462
|
-
`)});return}case"mcp":await ts(w);return;case"init":{if(de(e)){let m=Ot(e,s);p({kind:"note",tone:"info",text:["This repo is already set up \u2014 /init won\u2019t overwrite it.",` Change environment: /profile add <${
|
|
463
|
-
`)}),m&&p({kind:"note",tone:"warn",text:`\u26A0 ${m.why} \u2014 ${m.cmd} moves this repo.`});return}let f=[...
|
|
461
|
+
${km}`}),ee("/init"),wr(!1),!0},[e,p,At,ut,ee]),xo=X(async c=>{let d=c.slice(1).trim().split(/\s+/),l=(d[0]??"").toLowerCase(),w=d.slice(1);if(wr(!0),qo(w)&&["write","check","review","reorder"].includes(l)){let f=Ho(e,s);if(f.length===0){p({kind:"note",tone:"warn",text:"No categories yet \u2014 author some articles first, then scope to one."});return}let m=$=>l==="write"?`/write ${$p(w,$).join(" ")}`.trim():`/${l} ${[$,...w.filter(y=>y!=="--scope")].join(" ")}`.trim();if(f.length===1){xo(m(f[0].token));return}nn({cursor:0,rows:f,run:$=>{xo(m($))}});return}if(Ht(l,w)){let f=l==="write"&&Go(w).rewrite,m=l==="write"?Za(e,hm(e),{rewrite:f}):Ho(e,s);if(m.length>1){let $=w.filter(H=>H.startsWith("--")).join(" "),y=H=>`/${l}${H?` ${l==="write"?`--scope ${H}`:H}`:""}${$?` ${$}`:""} ${H?"":"--all"}`.replace(/\s+/g," ").trim(),v=m.reduce((H,J)=>H+J.count,0),P={token:"",label:l==="review"?`Everything \u2014 all ${v} articles + structure (IA) review`:l==="reorder"?`Everything \u2014 reorder all ${m.length} categories`:f?`Everything \u2014 rewrite all ${v} planned articles`:`Everything \u2014 write all ${v} pending article${v===1?"":"s"}`,count:v},M=l==="write"?`Write which articles? (counts = ${f?"articles to regenerate":"still to write"})`:l==="review"?"Review what? (counts = articles)":"Reorder what?";nn({cursor:0,rows:[P,...m],run:H=>{xo(y(H))},title:M});return}}let E=async f=>{let m=hl(f);if(!Ds(e)){await he(bl(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(m.mode==="single"){await $o([m.id],{runLine:[`/screenshot capture ${m.id}`,`/capture ${m.id}`]});return}if(m.mode==="failed"){let y=fl(e,Qo(e).rows);if(y.length===0){p({kind:"note",tone:"info",text:"No broken specs to re-run \u2014 /screenshot list shows where things stand."}),ee("/screenshot list");return}await $o(y);return}if(m.mode==="blocked"){let{blocked:y,rows:v}=Qo(e);if(y.length===0){p({kind:"note",tone:"info",text:"No shots are waiting on app data \u2014 /screenshot list shows where things stand."}),ee("/screenshot list");return}let P=Mo(v.filter(M=>M.state==="blocked")).length;p({kind:"note",tone:"info",text:`Re-running ${y.length} shot${y.length===1?"":"s"} that skipped on missing data last run.`+(P>0?` If you haven't staged ${P===1?"it":"those "+P+" things"} yet, ${y.length===1?"it":"they"} will skip again \u2014 /screenshot list has the worklist.`:"")}),await $o(y,{runLine:["/screenshot capture --blocked","/screenshot capture --all --retry-blocked"]});return}if(m.mode==="all"||m.mode==="scope"){let y=m.mode==="scope"?m.scope:void 0,{ready:v,captured:P,blocked:M,rows:H}=Qo(e,y),J=[...v,...P,...m.retryBlocked?M:[]];if(J.length===0&&M.length>0&&!m.retryBlocked){let O=y?`/screenshot capture ${y} --retry-blocked`:"/screenshot capture --blocked";Ee(`All ${M.length} shot${M.length===1?"":"s"} in scope ${M.length===1?"is":"are"} blocked on data that wasn't staged last run \u2014 /screenshot list shows what to stage, then ${O}.`,{kind:"cmd",cmd:"/screenshot list",reason:""},"warn");return}if(J.length===0){p({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),ee("/screenshot");return}if(!m.retryBlocked){let O=y?`/screenshot capture ${y} --retry-blocked`:"/screenshot capture --blocked",I=ml(H.filter(U=>U.state==="blocked"),O);I&&p({kind:"note",tone:"info",text:I})}let D=m.mode==="scope"?[`/screenshot capture ${m.scope}`,`/capture ${m.scope}`]:["/screenshot capture --all","/capture --all"];await $o(J,{runLine:D,...m.retryBlocked?{}:{heldBackBlocked:H.filter(O=>O.state==="blocked")}});return}let $=Zp(Ae(e));if($.length===0){p({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),ee("/screenshot");return}tn({cursor:0,rows:$,title:"Capture screenshots \u2014 pick what to shoot:"})},F=async()=>{let f=await Kn();f.kind==="forward-to-agent"&&f.prompt&&await he(f.prompt,{display:f.display,quietUser:!0}),ki()};switch(l){case"help":an({tab:0,scroll:0});return;case"exit":case"quit":et.current?.close(),r();return;case"clear":Ue(),Cn.current=[],ze.current={printed:[],armed:[]},wr(!1),ut(),console.log("\x1B[?2026h\x1B[H\x1B[2J\x1B[3J\x1B[?2026l"),p({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let f;try{f=Qe(e,s)}catch(m){p({kind:"note",tone:"error",text:m.message});return}p({kind:"note",tone:"info",text:`Profile "${f.name}" \u2192 ${f.connection.name} (${f.connection.apiUrl})${f.production?" \u26A0 PRODUCTION":""}`}),V(!0);try{let m=await Xx(f.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},y=>p({kind:"note",tone:"info",text:y})),$=Jx(f.name,m);if(Qx($),await Oi($,f.name,y=>p({kind:"note",tone:"info",text:y})),p({kind:"note",tone:"ok",text:`\u2713 Logged in to "${f.name}" as ${Wr($)}`}),await zc(s),po.current){let y=po.current;po.current=null;let v=Be(e,s);v.ok?(p({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 tab to run ${y}.`}),ee(y)):(p({kind:"note",tone:"warn",text:`${v.reason} (then ${y}.)`}),ee("/login"),po.current=y)}else uo.current&&(Ie(uo.current,"\u21E5 tab to re-send your last prompt\u2026"),uo.current=null)}catch(m){p({kind:"note",tone:"error",text:`Login failed: ${m.message}`})}finally{V(!1),G(m=>m+1)}return}case"allow-prod":{let f=!1;try{f=Qe(e,s).production}catch{}if(!f){p({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}zt.current=!0,Ue(),p({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let f=al(w.join(" ")),m=gt.current.uuid;if(!m){if(!f){p({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}hi.current=f,Jt(f),Qn(`${ti} ${f}`),p({kind:"note",tone:"ok",text:`Session will be named "${f}" once it starts.`});return}if(!f){p({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let $=gt.current.firstPrompt??"";om($,e).then(y=>{y?(Ie(`/rename ${y}`),p({kind:"note",tone:"info",text:`Suggestion: "${y}" \u2014 press tab to accept, or type /rename <your name>.`})):p({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>p({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}c0(m,f),Jt(f),Qn(`${ti} ${f}`),p({kind:"note",tone:"ok",text:`Session renamed to "${f}".`});return}case"profile":{let f=w[0],m=de(e);if(!f){let $=Object.entries(m?.profiles??{});if($.length===0){p({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let y=$.map(([M,H])=>({name:M,env:H.connection?.environment??"custom",prod:H.production===!0,who:Ei(M)})),v=s??m?.defaultProfile,P=Math.max(0,y.findIndex(M=>M.name===v));Rn({cursor:P,current:P,rows:y});return}if(f==="add"){let $=ll(e,w[1],w[2]);if($){p({kind:"note",tone:"error",text:$});return}p({kind:"note",tone:"ok",text:`\u2713 Profile "${w[1]}" created (environment: ${w[2]??w[1]}).`}),Ai(w[1],!0);return}if(!m?.profiles?.[f]){p({kind:"note",tone:"error",text:`Unknown profile "${f}". Create it: /profile add ${f} <environment>`});return}Ai(f,!0);return}case"doctor":await Yo(w,{cwd:e,version:o});return;case"genre":{let f=de(e)?.appType??null;(await Us(w,{cwd:e})).kind==="clear"&&(de(e)?.appType??null)!==f&&(Ue(),p({kind:"note",tone:"ok",text:"\u2713 Agent restarted \u2014 the doc-craft playbook for this genre is now loaded."}));try{Ct.current=!(de(e)?.appType??im(e))}catch{}G($=>$+1);return}case"roadmap":{if(w[0]?.toLowerCase()==="done"){let f=Ws(e,w.slice(1).join(" ").trim());p({kind:"note",tone:f.ok?"ok":"warn",text:f.line}),G(m=>m+1);return}p({kind:"note",tone:"info",text:Gl(e).join(`
|
|
462
|
+
`)});return}case"mcp":await ts(w);return;case"init":{if(de(e)){let m=Ot(e,s);p({kind:"note",tone:"info",text:["This repo is already set up \u2014 /init won\u2019t overwrite it.",` Change environment: /profile add <${um().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(`
|
|
463
|
+
`)}),m&&p({kind:"note",tone:"warn",text:`\u26A0 ${m.why} \u2014 ${m.cmd} moves this repo.`});return}let f=[...um(),...w0().filter(m=>dm(m))].map(m=>({name:m,apiUrl:y0(m).apiUrl,note:dm(m)?"being retired":null}));Sn({cursor:0,rows:f});return}case"resume":{let f=w.join(" ").trim(),m=l0(e).filter(v=>v.uuid!==gt.current.uuid);if(!f){if(!m.length){p({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}sn({query:"",cursor:0,sessions:m});return}let $=a0(e,f);if(!$){p({kind:"note",tone:"error",text:`No session matches "${f}".`});return}Ue($.uuid),gt.current={uuid:$.uuid,firstPrompt:$.firstPrompt,titleFired:!0},Jt($.name),hc($.uuid),Cn.current=[],ze.current={printed:[],armed:[]};let y=sc(e,$.uuid);for(let v of y)p(v);p({kind:"note",tone:"ok",text:y.length?`Resumed "${$.name}" \u2014 restored ${y.length} message(s); continue where you left off.`:`Resumed "${$.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let f=w.join(" ").trim(),m;try{m=await Po(e,s)}catch(y){p({kind:"note",tone:"error",text:`Could not list workspaces: ${y.message}`});return}if(!f){let y=m.workspaces.map(P=>({id:P.id,name:P.name??P.id,type:P.workspace_type}));if(y.length===0){p({kind:"note",tone:"info",text:"No workspaces in this project."});return}let v=Math.max(0,y.findIndex(P=>P.id===m.current));Pn({cursor:v,current:v,rows:y,profile:m.profile,projectId:m.projectId,projectName:m.projectName,environment:m.environment});return}let $=ji(m.workspaces,f);if(!$){p({kind:"note",tone:"error",text:`No workspace matches "${f}".`});return}Dr(m.profile,m.projectId,$);return}case"project":{let f=w.join(" ").trim(),m;try{m=await It(e,s)}catch(y){p({kind:"note",tone:"error",text:`Could not list projects: ${y.message} (signed in? try /login)`});return}if(!f){let y=m.projects.map(P=>({id:P.id,name:P.name??P.id,sub:P.sub_domain}));if(y.length===0){p({kind:"note",tone:"info",text:"No projects found for this identity."});return}let v=y.findIndex(P=>P.id===m.current);en({cursor:Math.max(0,v),current:v,rows:y,profile:m.profile,environment:m.environment});return}let $=Ii(m.projects,f);if(!$){p({kind:"note",tone:"error",text:`No project matches "${f}". Available: ${m.projects.map(y=>y.name??y.id).join(", ")}`});return}jr(m.profile,$);return}case"logout":{let f;try{f=Qe(e,s).name}catch($){p({kind:"note",tone:"error",text:$.message});return}let m=n0(f);o0(e,f),Ue(),G($=>$+1),p({kind:"note",tone:m?"ok":"info",text:m?`\u2713 Signed out of "${f}" and cleared its project/workspace selection.`:`Profile "${f}" was not signed in. Cleared any project/workspace selection.`}),p({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),ee("/login");return}case"publish":{if(!wo(c.trim()))return;let f=w.includes(ft);if(w.includes("--screenshots")||w.includes("--shots")){let v=Ae(e),P=hs(v);if(P.length===0){p({kind:"note",tone:"info",text:"No captured screenshots yet \u2014 /screenshot capture first."});return}let M=fs(v);M&&p({kind:"note",tone:"warn",text:M}),p({kind:"note",tone:"info",text:`Re-saving ${P.length} article${P.length===1?"":"s"} with captured screenshots so the images embed\u2026`}),await rt(P,0,{skipReview:f});return}if(w[0]==="--related"&&w[1]){let v=await $s(e,s,w[1].replace(/\\/g,"/"));if(v.length===0){p({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await rt(v,0,{skipReview:f});return}let m=w.filter(v=>!v.startsWith("--"));if(m[0]){await Ti(m[0],{skipReview:f});return}let $=w.includes("--all"),y=w.includes("--force");p({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let v=await li({cwd:e,profileName:s}),{clean:P,conflicts:M}=fn(v.entries),H=$&&y&&M.length>0,J=ks(v.entries);if(J>0&&p({kind:"note",tone:"warn",text:`\u26A0 ${J} article${J===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.`}),M.length>0&&!H&&p({kind:"note",tone:"warn",text:hn(M.length)}),P.length===0&&!H){if(M.length>0){ee("/resolve");return}p({kind:"note",tone:"ok",text:J>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let D=v.counts["unknown-base"]??0;D>0&&p({kind:"note",tone:"info",text:`(${D} article(s) have no sync base yet \u2014 publish those by path if needed.)`}),Ye("Reconciling structure on Document360 (order + related articles)\u2026");try{let O=await gc({cwd:e,profileName:s,onRateLimit:se=>Ye(`Document360 rate limit \u2014 waiting ${Math.ceil(se.waitMs/1e3)}s\u2026`)}),I=ym(await wm({cwd:e,profileName:s})),U=wc(O);U?p({kind:"note",tone:U.startsWith("\u26A0")?"warn":"info",text:U}):O.skipped&&p({kind:"note",tone:"warn",text:`Order sync skipped: ${O.skipped}`}),I&&p({kind:"note",tone:"info",text:I}),O.failures?.length?ee("/structure"):(p({kind:"note",tone:"ok",text:U||I?"\u2713 Structure synced to Document360 \u2014 /structure shows the new category + article order.":"\u2713 Already in order \u2014 nothing to change."}),(U||I)&&ee("/structure"))}catch(O){p({kind:"note",tone:"warn",text:`Structure sync failed: ${O.message}`})}finally{Ye(null)}return}if($){let D=(H?[...P,...M]:P).map(O=>O.path);await rt(D,H?0:M.length,{skipReview:f});return}Tn({cursor:0,rows:tp(P,M),conflicts:M.length})}catch(v){p({kind:"note",tone:"error",text:`Could not compute sync status: ${v.message}`}),p({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"resolve":{if(!wo(c.trim()))return;await Di(w.find(f=>!f.startsWith("--")));return}case"preview":{let f=w.join(" ").trim();if(!f){let $=[];try{$=Object.keys(am(e,Qe(e,s).name)?.articles??{})}catch{}if($.length===0){p({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}on({query:"",cursor:0,paths:$});return}let m=Kx(f)?f:pc(e,f);if(to(m)){try{p({kind:"preview",name:pr(m),text:vm(ii(m,"utf8"))})}catch($){p({kind:"note",tone:"error",text:`Could not read ${m}: ${$.message}`})}return}if(H0.test(f)){try{let $=Qe(e,s),y={profile:$.name,connection:$.connection},v=$.project.projectId??e0(y),P=await t0(y,v,f);p({kind:"preview",name:P.title??f,text:P.content??"*(article has no content)*"})}catch($){p({kind:"note",tone:"error",text:`Could not fetch article: ${$.message}`})}return}p({kind:"note",tone:"error",text:`"${f}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let f=w[0]?.trim();if(!f){let v=Ts(kc(e));Zt({cursor:v,current:v});return}let{lines:m,changed:$,effective:y}=Vo(e,f);for(let v of m)p({kind:"note",tone:v.startsWith("\u26A0")?"warn":v.startsWith("\u2713")?"ok":"info",text:v});$&&(jc(v=>v+1),et.current?.setModel(y));return}case"verbose":{let f=w[0]?.trim().toLowerCase(),m=f==="on"?!0:f==="off"?!1:!br.current;br.current=m;try{d0({...sm(),verboseTranscript:m})}catch{p({kind:"note",tone:"warn",text:"\u26A0 Applied for this session, but the setting could not be saved."})}p({kind:"note",tone:"ok",text:m?"\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(!de(e)){p({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:f,run:m}=Ma(w),$=$0(e,s);if($.length===0){p({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let y=Ua($,f);if(y.length===0){p({kind:"note",tone:"error",text:`No tracked articles under "${f}". (${$.length} are tracked overall.)`});return}let v=fc(y),P=3,M=`/convert${f?` --scope ${f}`:""} --run`,H=fr(e,"light");if(!m){let D=pm({files:Fa(e,y),op:"convert",model:H.model}),O=f?`Scope: ${f} (${y.length} of ${$.length} tracked)
|
|
464
464
|
`:"",I=`
|
|
465
465
|
Model: ${H.model}${H.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;p({kind:"note",tone:"info",text:O+Ba(v,D,P).join(`
|
|
466
|
-
`)+I}),ee(M);return}Rt.current=Date.now(),Kt(0),R(!0);let J=new AbortController;Te.current=J,ce({verb:"Converting",total:v.length,done:0,active:[],rows:eo(v),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),p({kind:"note",tone:"info",text:`Converting ${y.length} articles across ${v.length} partitions (\u2264${P} agents at once) on ${H.model}\u2026 (esc to stop)`});try{for await(let D of
|
|
466
|
+
`)+I}),ee(M);return}Rt.current=Date.now(),Kt(0),R(!0);let J=new AbortController;Te.current=J,ce({verb:"Converting",total:v.length,done:0,active:[],rows:eo(v),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),p({kind:"note",tone:"info",text:`Converting ${y.length} articles across ${v.length} partitions (\u2264${P} agents at once) on ${H.model}\u2026 (esc to stop)`});try{for await(let D of hr({cwd:e,partitions:v,promptFor:Wa,concurrency:P,profileName:s,allowProdWrites:zt.current,model:H.model,signal:J.signal}))if(D.type==="partition_status")D.status==="running"?ce(O=>O&&{...O,active:[...O.active,D.label],rows:qe(O.rows,D.label,"active"),lastAt:Date.now()}):ce(O=>O&&{...O,active:O.active.filter(I=>I!==D.label),done:O.done+1,rows:qe(O.rows,D.label,D.status==="done"?"done":"failed"),lastAt:Date.now()});else if(D.type==="partition_event")ce(O=>{if(!O)return O;let I={...O,lastAt:Date.now()};return D.event.type==="tool"?I.tools=O.tools+1:D.event.type==="text"&&(I.chars=O.chars+D.event.delta.length),I});else if(D.type==="run_done"){cn(se=>se+D.totalCostUsd),ln(se=>se+D.results.reduce((Re,st)=>Re+st.outputTokens,0));let O=D.aborted?"Stopped. ":"",I=t.kind==="api"?"api":"subscription",U=pt(D,"The conversion");p({kind:"note",tone:U||D.aborted?"warn":D.ok?"ok":"warn",text:U?U.join(`
|
|
467
467
|
`):O+Ha(D.results,v,I).join(`
|
|
468
|
-
`)}),U&&ee("/doctor")}}catch(D){p({kind:"note",tone:"error",text:`Convert run failed: ${D.message}`})}finally{Te.current=null,ce(null),R(!1),G(D=>D+1)}return}case"write":{if(!de(e)){p({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let f=
|
|
468
|
+
`)}),U&&ee("/doctor")}}catch(D){p({kind:"note",tone:"error",text:`Convert run failed: ${D.message}`})}finally{Te.current=null,ce(null),R(!1),G(D=>D+1)}return}case"write":{if(!de(e)){p({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let f=hm(e);if(f.length===0){p({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:m,path:$,preview:y,concurrency:v,rewrite:P}=Go(w);if(!$&&!y&&!(de(e)?.appType??im(e))){p({kind:"note",tone:"warn",text:`\u26A0 No doc genre is set, so no doc-craft playbook would load \u2014 all ${f.length} articles would be written generically.
|
|
469
469
|
Pick the genre below (one keypress), then run /write again \u2014 it changes structure, titles and depth for every article.
|
|
470
|
-
Not blocked: /write <path> still authors a single article, and /write --preview costs nothing.`}),le(Bs.options.map(Y=>({cmd:Y.cmd,desc:Y.desc}))),An(Bs.title);return}let{docsDir:M,targets:H,reason:J,rewriting:D}=Ss(e,f,{scope:m,path:$,rewrite:P});if(H.length===0){p({kind:"note",tone:"warn",text:J??"Nothing to write."});return}D&&p({kind:"note",tone:"warn",text:`--rewrite: regenerating ${H.length} already-written article${H.length===1?"":"s"} (overwrites them; git has your baseline).`});let O=fc(H),I=Va(v),U=
|
|
470
|
+
Not blocked: /write <path> still authors a single article, and /write --preview costs nothing.`}),le(Bs.options.map(Y=>({cmd:Y.cmd,desc:Y.desc}))),An(Bs.title);return}let{docsDir:M,targets:H,reason:J,rewriting:D}=Ss(e,f,{scope:m,path:$,rewrite:P});if(H.length===0){p({kind:"note",tone:"warn",text:J??"Nothing to write."});return}D&&p({kind:"note",tone:"warn",text:`--rewrite: regenerating ${H.length} already-written article${H.length===1?"":"s"} (overwrites them; git has your baseline).`});let O=fc(H),I=Va(v),U=fr(e,"standard"),se=!!$;if(y&&!se){let Y=pm({files:Ka(e,f,H),op:"write",model:U.model}),ue=m?`Scope: ${m} (${H.length} pending)
|
|
471
471
|
`:"",Ne=`
|
|
472
472
|
Model: ${U.model}${U.forced?" (forced)":" \u2014 authoring; /model to override"}`;p({kind:"note",tone:"info",text:ue+Xa(O,Y,I).join(`
|
|
473
|
-
`)+Ne}),ee(`/write${m?` --scope ${m}`:""}`);return}Rt.current=Date.now(),Kt(0),R(!0);let Re=new AbortController;Te.current=Re,ce({verb:"Writing",total:O.length,done:0,active:[],rows:eo(O),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),p({kind:"note",tone:"info",text:`Writing ${H.length} article${H.length===1?"":"s"} across ${O.length} partition${O.length===1?"":"s"} (\u2264${I} agents at once) on ${U.model}${U.forced?" (forced)":""}\u2026 (esc to stop)`});let
|
|
473
|
+
`)+Ne}),ee(`/write${m?` --scope ${m}`:""}`);return}Rt.current=Date.now(),Kt(0),R(!0);let Re=new AbortController;Te.current=Re,ce({verb:"Writing",total:O.length,done:0,active:[],rows:eo(O),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),p({kind:"note",tone:"info",text:`Writing ${H.length} article${H.length===1?"":"s"} across ${O.length} partition${O.length===1?"":"s"} (\u2264${I} agents at once) on ${U.model}${U.forced?" (forced)":""}\u2026 (esc to stop)`});let st=new Set;try{for await(let Y of hr({cwd:e,partitions:O,promptFor:ue=>za(ue,M,{rewrite:D||se}),concurrency:I,profileName:s,allowProdWrites:zt.current,model:U.model,signal:Re.signal}))if(Y.type==="partition_status")Y.status==="running"?ce(ue=>ue&&{...ue,active:[...ue.active,Y.label],rows:qe(ue.rows,Y.label,"active"),lastAt:Date.now()}):ce(ue=>ue&&{...ue,active:ue.active.filter(Ne=>Ne!==Y.label),done:ue.done+1,rows:qe(ue.rows,Y.label,Y.status==="done"?"done":"failed"),lastAt:Date.now()});else if(Y.type==="partition_event"){let ue=null;if(Y.event.type==="tool"){let Ne=Mf(Y.event.name,Y.event.input,O[Y.index]?.paths??[]);Ne&&!st.has(Ne)&&(st.add(Ne),ue=Y.label)}ce(Ne=>{if(!Ne)return Ne;let dt={...Ne,lastAt:Date.now()};return Y.event.type==="tool"?dt.tools=Ne.tools+1:Y.event.type==="text"&&(dt.chars=Ne.chars+Y.event.delta.length),ue&&(dt.rows=_f(dt.rows,ue)),dt})}else if(Y.type==="run_done"){cn(Nt=>Nt+Y.totalCostUsd),ln(Nt=>Nt+Y.results.reduce((bt,Wm)=>bt+Wm.outputTokens,0));let ue=Y.aborted?"Stopped. ":"",Ne=t.kind==="api"?"api":"subscription",dt=pt(Y,"The write");if(p({kind:"note",tone:dt||Y.aborted?"warn":Y.ok?"ok":"warn",text:dt?dt.join(`
|
|
474
474
|
`):ue+Ja(Y.results,O,Ne).join(`
|
|
475
|
-
`)}),dt){ee("/doctor");continue}let tu=ns(Y);if(tu&&p({kind:"note",tone:"warn",text:tu}),!Y.aborted&&Y.ok)try{let Nt=(
|
|
475
|
+
`)}),dt){ee("/doctor");continue}let tu=ns(Y);if(tu&&p({kind:"note",tone:"warn",text:tu}),!Y.aborted&&Y.ok)try{let Nt=(st.size>0?[...st]:H).map(bt=>`${M}/${bt}`);mc(e,Nt,{writtenCap:P0,reviewedCap:0,checkedCap:0})}catch{}let Lr=Y.aborted?null:Qa(e,M,H);if(Lr&&p({kind:"note",tone:"warn",text:Lr}),!Y.aborted&&Y.ok){let Nt=m??$??"",bt=Nt?` ${Nt}`:"";Ee(Lr?`Written \u2014 but the checker flagged issues. I\u2019d fix those first with /check${bt} --fix, then /review${bt} --fix for editorial quality, then /publish --all (add /screenshot author --all first if you want images).`:`Written. I\u2019d run /review${bt} --fix next \u2014 editorial review that applies its fixes \u2014 then /publish --all pushes the drafts up (add /screenshot author --all first if you want images).`,{kind:"cmd",cmd:Lr?`/check${bt} --fix`:`/review${bt} --fix`,reason:""})}}}catch(Y){p({kind:"note",tone:"error",text:`Write run failed: ${Y.message}`})}finally{Te.current=null,ce(null),R(!1),G(Y=>Y+1)}return}case"draft":{if(!de(e)){p({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:f,looseDocs:m}=el(e);if(f.length===0&&m===0){p({kind:"note",tone:"info",text:nl});return}let $=w.join(" ").trim();if(!$&&f.length>1){p({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
|
|
476
476
|
${f.map(P=>` \u2022 ${P.name} (${P.docCount} doc${P.docCount===1?"":"s"})`).join(`
|
|
477
|
-
`)}`}),le(f.map(P=>`/draft ${P.name}`));return}let y="",v;if($){let P=tl(f,$);P?y=P:v=$}else y=f[0]?.name??"";await he(Ps(y,v),{display:$?`/draft ${$}`:"/draft",quietUser:!0});return}case"pull":{if(!
|
|
478
|
-
`)});return}if(f==="--baseline"){let y=w.find(H=>!H.startsWith("--")),v=y?y.replace(/\\/g,"/"):void 0;p({kind:"note",tone:"info",text:v?`Setting the sync baseline for ${v}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let P=await
|
|
477
|
+
`)}`}),le(f.map(P=>`/draft ${P.name}`));return}let y="",v;if($){let P=tl(f,$);P?y=P:v=$}else y=f[0]?.name??"";await he(Ps(y,v),{display:$?`/draft ${$}`:"/draft",quietUser:!0});return}case"pull":{if(!wo(c.trim()))return;let f=w.find(m=>m.startsWith("--"));try{if(f==="--status"){p({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let y=Date.now(),v=await li({cwd:e,profileName:s});p({kind:"note",tone:"info",text:xs(v,Date.now()-y).join(`
|
|
478
|
+
`)});return}if(f==="--baseline"){let y=w.find(H=>!H.startsWith("--")),v=y?y.replace(/\\/g,"/"):void 0;p({kind:"note",tone:"info",text:v?`Setting the sync baseline for ${v}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let P=await f0({cwd:e,profileName:s,relPaths:v?[v]:void 0}),M=v?{rebaselined:[],skipped:[]}:await m0({cwd:e,profileName:s});if(P.baselined.length===0&&P.skipped.length===0&&M.rebaselined.length===0){p({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}P.baselined.length>0&&p({kind:"note",tone:"ok",text:`\u2713 Baselined ${P.baselined.length} article${P.baselined.length===1?"":"s"} \u2014 they now read in-sync until either side changes.`}),M.rebaselined.length>0&&p({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${M.rebaselined.length} article${M.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),P.skipped.length>0&&p({kind:"note",tone:"warn",text:`${P.skipped.length} skipped:
|
|
479
479
|
${P.skipped.map(H=>` - ${H.path} (${H.reason})`).join(`
|
|
480
|
-
`)}`}),G(H=>H+1);return}if(f==="--compare"){p({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let y=await
|
|
481
|
-
`)});return}if(f){p({kind:"note",tone:"error",text:`Unknown option: ${f} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let m=w[0];if(m){let y=await
|
|
480
|
+
`)}`}),G(H=>H+1);return}if(f==="--compare"){p({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let y=await h0({cwd:e,profileName:s}),v=y.onlyInLegacy.length===0&&y.onlyInManifest.length===0&&y.mappedMissingFromManifest.length===0,P=[`Legacy listing: ${y.legacyCount} \xB7 Manifest: ${y.manifestCount} \xB7 in both: ${y.inBoth}`];v?P.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(y.mappedMissingFromManifest.length&&P.push(`\u2717 ${y.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${y.mappedMissingFromManifest.slice(0,5).join(", ")}`),y.onlyInLegacy.length&&P.push(`\u26A0 ${y.onlyInLegacy.length} only in the legacy listing: ${y.onlyInLegacy.slice(0,5).join(", ")}`),y.onlyInManifest.length&&P.push(`\u26A0 ${y.onlyInManifest.length} only in the manifest: ${y.onlyInManifest.slice(0,5).join(", ")}`),P.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),p({kind:"note",tone:v?"ok":"warn",text:P.join(`
|
|
481
|
+
`)});return}if(f){p({kind:"note",tone:"error",text:`Unknown option: ${f} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let m=w[0];if(m){let y=await cm({cwd:e,profileName:s,relPath:m.replace(/\\/g,"/")});me.current=[{plan:y,mode:y.overwritesLocalChanges?"conflict":"pull"}],Xt.current=[],jn();return}p({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let $=await Oa({cwd:e,profileName:s});for(let y of La($))p({kind:"note",tone:y.tone,text:y.text});G(y=>y+1)}catch(m){p({kind:"note",tone:"error",text:`Pull failed: ${m.message}`})}return}case"scope":{if(!de(e)){p({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let f=g0(e);if(f.length===0){p({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.'});return}Dn({cursor:0,rows:f.map(m=>({...m,checked:m.recommended}))});return}case"audit":{if(w[0]==="--auto"){let m=de(e);if(!m){p({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let $=w[1]!=="off";rm({...m,autoAudit:$},e),p({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 f=await Bo();f.kind==="forward-to-agent"&&f.prompt&&((await he(f.prompt,{display:f.display,quietUser:!0})).producedNothing||(or(e,s),G($=>$+1)));return}case"check":{let f=w.find(y=>!y.startsWith("--")),m=f?` ${f}`:"",$=lm({cwd:e,scope:f});if(w.includes("--fix")){if($.length===0){p({kind:"note",tone:"ok",text:"\u2713 Nothing to fix \u2014 the docs are already clean."});return}p({kind:"note",tone:"info",text:`Fixing ${$.length} doc issue${$.length===1?"":"s"}\u2026`});let y=gm(e,f);await he(Wl($),{display:`/check${m} --fix`,quietUser:!0});try{mc(e,y,rr("check"))}catch{}let v=lm({cwd:e,scope:f});p({kind:"note",tone:v.length===0?"ok":"warn",text:v.length===0?"\u2713 Doc-checker: all issues resolved.":Ms(v).join(`
|
|
482
482
|
`)}),Ee(v.length===0?`Deterministic issues fixed. Next: /review${m} --fix for editorial quality (style, grammar, structure), then /publish --all.`:`Some issues remain \u2014 /review${m} --fix runs the editorial review + fixes, then /publish --all.`,{kind:"cmd",cmd:`/review${m} --fix`,reason:""});return}if(p({kind:"note",tone:$.length===0?"ok":"warn",text:Ms($).join(`
|
|
483
|
-
`)}),$.length>0){let y=Sa(e,f)===0?"; /publish --all publishes as-is":"";Ee(`Found ${$.length} doc issue${$.length===1?"":"s"} above. /check${m} --fix has the agent fix them in place (or /review${m} --fix for the full editorial pass${y}).`,{kind:"cmd",cmd:`/check${m} --fix`,reason:""})}return}case"structure":{let f=
|
|
484
|
-
`)});return}case"reorder":{let f=Hl(e,w);if(!f){p({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=await he(f.prompt,{display:f.display,quietUser:!0}),$=
|
|
485
|
-
`)}),At(dn()),
|
|
483
|
+
`)}),$.length>0){let y=Sa(e,f)===0?"; /publish --all publishes as-is":"";Ee(`Found ${$.length} doc issue${$.length===1?"":"s"} above. /check${m} --fix has the agent fix them in place (or /review${m} --fix for the full editorial pass${y}).`,{kind:"cmd",cmd:`/check${m} --fix`,reason:""})}return}case"structure":{let f=nr(e,s);if(f.length===0){p({kind:"note",tone:"info",text:"No documentation structure yet \u2014 run /init and author some articles first."});return}p({kind:"note",tone:"info",text:["Documentation order (categories \u2192 articles):","",...f].join(`
|
|
484
|
+
`)});return}case"reorder":{let f=Hl(e,w);if(!f){p({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=await he(f.prompt,{display:f.display,quietUser:!0}),$=Wo(e,{text:"Reordered locally \u2014 /publish --all syncs the new order to Document360.",cmd:"/publish --all"},"Reordered locally. ");wi(m,$.text,{kind:"cmd",cmd:$.cmd,reason:""});return}case"review":{let f=Bl(e,w);if(!f){p({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=w.includes("--fix"),$=w.find(P=>!P.startsWith("--")),y=m?gm(e,$):[],v=await he(f.prompt,{display:f.display,quietUser:!0});if(m&&!v.producedNothing)try{mc(e,y,rr("review"))}catch{}if(m){let P=Wo(e,{text:"\u2713 Editor applied its fixes \u2014 your docs are corrected. /publish --all pushes them up (or /check for an instant no-token re-scan first).",cmd:"/publish --all"},"\u2713 Editor applied its fixes to this scope. ");wi(v,P.text,{kind:"cmd",cmd:P.cmd,reason:""})}else{let P=w.filter(M=>M!=="--fix").join(" ");wi(v,`The review listed issues above. /review${P?` ${P}`:""} --fix lets the editor apply them all (or /check --fix for just the deterministic ones; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/review${P?` ${P}`:""} --fix`,reason:""})}return}case"capture-setup":{await F();return}case"devhints":{if(!de(e)){p({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}p({kind:"note",tone:"info",text:Un(Mn(e)).join(`
|
|
485
|
+
`)}),At(dn()),ko.current=it(e).status==="current",Nn.current=$t(e);return}case"discover":{if(!de(e)){p({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await he(Aa(),{display:"/discover",quietUser:!0});return}case"inbox":{if(!de(e)){p({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(vl(e)===0){p({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 he(xl(),{display:"/inbox",quietUser:!0});return}case"share":{let f=de(e);if(!f){p({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=w[0]?.trim().toLowerCase();if(m==="status"){for(let y of Ns(e,f))p({kind:"note",tone:y.tone,text:y.text});return}if(m==="on"||m==="off"){for(let y of Cl(e,f,m==="on"))p({kind:"note",tone:y.tone,text:y.text});G(y=>y+1);return}if(m){p({kind:"note",tone:"error",text:`Unknown option: ${m} \u2014 use /share, /share status, /share on, or /share off.`});return}p({kind:"note",tone:"info",text:"Exchanging work with your team\u2026"});let $=await js(e,f);for(let y of $.lines)p({kind:"note",tone:y.tone,text:y.text});$.changed&&G(y=>y+1);return}case"feedback":{let f=mm(e),m="";try{m=to(f)?ii(f,"utf8"):""}catch{m=""}if(!/^## /m.test(m)){p({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 nc(m.trim());p({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 ${f} and copy it manually.`}),$&&xi(null);return}case"document":{if(!de(e)){p({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:f,skipReview:m,what:$}=rl(w);if(!$&&ol(e)===0){p({kind:"note",tone:"info",text:il});return}let y=`/document${$?` ${$}`:""}${f?" --publish":""}`,v=await he(sl($),{display:y,quietUser:!0});f&&!v.producedNothing&&await Vc({skipReview:m});return}case"catch-up":{if(!de(e)){p({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!wo(c.trim()))return;let{publish:f,skipReview:m}=Tl(w);for(let P of await Pl(e))p({kind:"note",tone:P.tone,text:P.text});p({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let $=await Al({cwd:e,profileName:s});for(let P of Dl($))p({kind:"note",tone:P.startsWith("\u2713")?"ok":P.startsWith("\u2139")?"info":"warn",text:P});let y=er(yn(e));p({kind:"note",tone:"info",text:y?`Catching up on ${y}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"});let v=await he(El(),{display:`/catch-up${f?" --publish":""}`,quietUser:!0});f&&!v.producedNothing&&await Vc({skipReview:m});return}case"comments":{if(!de(e)){p({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!wo(c.trim()))return;let f=Ol(w);Ye("Checking Document360 for reviewer comments\u2026"),R(!0);let m=null;try{m=await jl(e,s,{...f.scope,onProgress:(y,v)=>Ye(`Checking Document360 for reviewer comments\u2026 ${y}/${v}`)})}catch(y){p({kind:"note",tone:"error",text:`Couldn\u2019t read comments from Document360: ${y.message}`})}finally{R(!1),Ye(null)}if(!m)return;G(y=>y+1);let $=zn(m.threads,m.labels);if(m.threads.length===0){p({kind:"note",tone:"ok",text:Is(m,{showAnswered:f.showAnswered}).join(`
|
|
486
486
|
`)});return}if(p({kind:"note",tone:"info",text:Is(m,{full:!!f.scope.path,showAnswered:f.showAnswered}).join(`
|
|
487
|
-
`)}),f.answer&&(f.all||f.scope.path||f.scope.scope||$.length===1)){await Gc($,{resolve:f.resolve});return}En({cursor:0,rows
|
|
488
|
-
`)});return}if(f.mode==="list"){if(!de(e)){p({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let v=de(e)?.docsDir??bc,P=ba(e,f.scope),M=Ae(e,P);if(f.picker){if(M.length===0){p({kind:"note",tone:"info",text:"No screenshot placeholders found in the docs."});return}let U=
|
|
489
|
-
`)});let se=
|
|
490
|
-
`)}),m&&p({kind:"note",tone:"info",text:m});let H=M.filter(U=>U.state==="placeholder").length,J=M.filter(U=>U.state==="spec").length,D=M.filter(U=>U.state==="captured").length,O=M.filter(U=>U.state==="rejected").length,I=M.filter(U=>U.state==="spec"&&!U.mutates).length;H>0?ee(P?`/screenshot author ${P}`:"/screenshot author --all"):J>0&&(I>0||D===0)?ee(P?`/screenshot capture ${P}`:"/screenshot capture"):D>0?ee("/screenshot verify"):O>0&&ee("/screenshot capture --failed");return}if(f.mode==="single"){await Kc(f.id);return}if(!de(e)){p({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let $=f.mode==="scope"?f.scope:void 0,y=
|
|
491
|
-
`)}),Ie(dr(e));return}default:p({kind:"note",tone:"error",text:`Unknown command: /${l} \u2014 type /help.`})}},[e,r,s,jn,Di,p,Ue,he,ot,Ti,zc]),Ir=X(c=>{let d=(c??k).trim();if(x(""),yr(null),vn(0),d.startsWith("/")&&(Se.current=!1,Pe.current=!1,Qe.current=null,ut(),An(null),le(w=>Ff(w,d))),!d||(fr(!1),(ao.current||me.current.length>0)&&p({kind:"user",text:d}),Jc(d))||Xc(d))return;pi.current.push(d);let l=qf(d,Rc.current);if(d.startsWith("/"))p({kind:"user",text:d}),Ce(!0),vo(l).finally(()=>Ce(!1));else if(N0(l)){p({kind:"user",text:d});let w=j0(l);if(!w)he(l,{display:d,quietUser:!0});else{try{I0(e,{title:w,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}he(`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=Fh(e,l);he(w??l,{display:d})}},[k,Jc,Xc,vo,he]),Qc=X(c=>{if(c.length>1){if(c.includes("\x1B"))return;let d=Wf(c);if(Bf(d)){let l=Hf(++Nm.current,d);Rc.current.set(l,d),T(l)}else T(d);return}T(c)},[T]),In=Math.max(10,Me-6),Zc=dc(()=>ri(h.text,In),[h.text,In]),Ni=X(c=>g(d=>({...d,pos:Math.max(0,Math.min(d.text.length,d.pos+c))})),[]),Or=X(c=>g(d=>({...d,pos:Vf(ri(d.text,In),d.pos,c)})),[In]),xo=X(c=>g(d=>({...d,pos:Yf(ri(d.text,In),d.pos,c)})),[In]),Mm=["\x1B[H","\x1B[1~","\x1BOH"],Um=["\x1B[F","\x1B[4~","\x1BOF"],eu=X((c,d)=>d.leftArrow?(Ni(-1),!0):d.rightArrow?(Ni(1),!0):c&&Mm.includes(c)?(xo("start"),!0):c&&Um.includes(c)?(xo("end"),!0):d.ctrl&&c==="a"?(xo("start"),!0):d.ctrl&&c==="e"?(xo("end"),!0):!1,[Ni,xo]);return Bx((c,d)=>{if(d.ctrl&&c==="c"){Ze.current?.close(),r();return}if(wo.current.awaySince!==null)try{let l=Af(wo.current,Date.now(),yn(e));if(wo.current=l.memory,Fc(null),l.kind==="delta"){p({kind:"note",tone:"info",text:Nf(l.delta,l.awayMs)});let w=nt(!1);w.kind==="recommend"&&yt(w.rec,{silent:!0})}else if(l.kind==="briefing"){p({kind:"note",tone:"info",text:`\u{1F4E5} ${cr(l.delta)} arrived while you were away (${lc(l.awayMs)}).`});let w=nt(!1);w.kind==="recommend"&&yt(w.rec)}}catch{}if(Ci.current=Date.now(),!N){if(S){if(d.escape){if(Te.current){if(!Te.current.signal.aborted){let l=(br?.verb??"work").toLowerCase(),w=br?.unit??"article";p({kind:"note",tone:"warn",text:`\u238B Stopping the ${l} run (finishing in-flight ${w}s)\u2026`}),Te.current.abort()}return}lo.current||(lo.current=!0,p({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),Ze.current?.interrupt());return}if(d.return){let l=k.trim();if(!l)return;rn.current.push(l),fi([...rn.current]),x("");return}if(eu(c,d))return;if(d.upArrow){Or(-1);return}if(d.downArrow){Or(1);return}if(d.backspace||d.delete){C();return}c&&!d.ctrl&&!d.meta&&Qc(c);return}if(Qt){if(d.upArrow){Zt(l=>l&&{...l,cursor:Math.max(0,l.cursor-1)});return}if(d.downArrow){Zt(l=>l&&{...l,cursor:Math.min(mt.length-1,l.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=mt.length){Zt(l=>l&&{...l,cursor:Number(c)-1});return}if(d.return){let l=mt[Qt.cursor];Zt(null);let{lines:w,changed:E,effective:F}=Go(e,l.value??"default");for(let f of w)p({kind:"note",tone:f.startsWith("\u26A0")?"warn":f.startsWith("\u2713")?"ok":"info",text:f});E&&(jc(f=>f+1),Ze.current?.setModel(F));return}if(c==="s"){let l=mt[Qt.cursor];Zt(null),Ze.current?.setModel(l.value??void 0),p({kind:"note",tone:"ok",text:`\u2713 Using ${l.label} for this session only (your saved default is unchanged).`});return}if(d.escape){Zt(null);return}return}if(St){if(d.upArrow){Rn(l=>l&&{...l,cursor:Math.max(0,l.cursor-1)});return}if(d.downArrow){Rn(l=>l&&{...l,cursor:Math.min(l.rows.length-1,l.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=St.rows.length){Rn(l=>l&&{...l,cursor:Number(c)-1});return}if(d.return||c==="s"){let l=St.rows[St.cursor];Rn(null),Ai(l.name,d.return===!0);return}if(d.escape){Rn(null);return}return}if(po){if(d.escape){an(null);return}if(d.leftArrow||d.tab&&d.shift){an(l=>l&&{tab:(l.tab-1+Fe.length)%Fe.length,scroll:0});return}if(d.rightArrow||d.tab){an(l=>l&&{tab:(l.tab+1)%Fe.length,scroll:0});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Fe.length){an({tab:Number(c)-1,scroll:0});return}if(d.upArrow){an(l=>l&&{...l,scroll:Math.max(0,l.scroll-1)});return}if(d.downArrow){an(l=>{if(!l)return l;let w=(Fe[l.tab]??Fe[0]).rows.length;return{...l,scroll:Math.min(Math.max(0,w-1),l.scroll+1)}});return}return}if(Pt){if(d.upArrow){Sn(l=>l&&{...l,cursor:Math.max(0,l.cursor-1)});return}if(d.downArrow){Sn(l=>l&&{...l,cursor:Math.min(l.rows.length-1,l.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Pt.rows.length){Sn(l=>l&&{...l,cursor:Number(c)-1});return}if(d.return){let l=Pt.rows[Pt.cursor].name;if(Sn(null),!Hi(e,l).created){p({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}p({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${l}").`});let E=!1;try{let F=$n(l);E=!!F&&!(Vt(F)&&!F.refreshToken)}catch{E=!1}p({kind:"note",tone:"info",text:E?`Next: sign in to ${l} and pick your project \u2014 you're already signed in here, so it'll be quick.`:`Next: sign in to Document360 (${l}) and pick your project.`}),ee("/login"),G(F=>F+1);return}if(d.escape){Sn(null);return}return}if(Oe){if(d.upArrow){Pn(l=>l&&{...l,cursor:Math.max(0,l.cursor-1)});return}if(d.downArrow){Pn(l=>l&&{...l,cursor:Math.min(l.rows.length-1,l.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Oe.rows.length){Pn(l=>l&&{...l,cursor:Number(c)-1});return}if(d.return){let l=Oe.rows[Oe.cursor],{profile:w,projectId:E}=Oe;Pn(null),Dr(w,E,l);return}if(d.escape){Pn(null);return}return}if(et){if(d.upArrow){en(l=>l&&{...l,cursor:Math.max(0,l.cursor-1)});return}if(d.downArrow){en(l=>l&&{...l,cursor:Math.min(l.rows.length-1,l.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=et.rows.length){en(l=>l&&{...l,cursor:Number(c)-1});return}if(d.return){let l=et.rows[et.cursor],{profile:w}=et;en(null),jr(w,l);return}if(d.escape){en(null);return}return}if(Le){if(d.upArrow){Dn(l=>l&&{...l,cursor:Math.max(0,l.cursor-1)});return}if(d.downArrow){Dn(l=>l&&{...l,cursor:Math.min(l.rows.length-1,l.cursor+1)});return}if(c===" "){Dn(l=>l&&{...l,rows:l.rows.map((w,E)=>E===l.cursor?{...w,checked:!w.checked}:w)});return}if(d.return){let l=Le.rows.filter(w=>w.checked).map(w=>w.path);if(Dn(null),l.length===0){p({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}Da(e,l),p({kind:"note",tone:"ok",text:`\u2713 Scoped to ${l.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let w of l)p({kind:"note",tone:"info",text:` ${w}`});p({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(d.escape){Dn(null);return}return}if(lt){if(d.upArrow){nn(l=>l&&{...l,cursor:Math.max(0,l.cursor-1)});return}if(d.downArrow){nn(l=>l&&{...l,cursor:Math.min(l.rows.length-1,l.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=lt.rows.length){nn(l=>l&&{...l,cursor:Number(c)-1});return}if(d.return){let l=lt.rows[lt.cursor],w=lt.run;nn(null),w(l.token);return}if(d.escape){nn(null);return}return}if(wt){if(d.upArrow){Tn(l=>l&&{...l,cursor:Math.max(0,l.cursor-1)});return}if(d.downArrow){Tn(l=>l&&{...l,cursor:Math.min(l.rows.length-1,l.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=wt.rows.length){Tn(l=>l&&{...l,cursor:Number(c)-1});return}if(d.return){let l=wt.rows[wt.cursor],w=wt.conflicts;Tn(null),l.conflict?Di(l.paths[0]):l.kind==="article"?Ti(l.paths[0]):ot(l.paths,l.kind==="all"?w:0);return}if(d.escape){Tn(null);return}return}if(tt){if(d.upArrow){En(l=>l&&{...l,cursor:Math.max(0,l.cursor-1)});return}if(d.downArrow){En(l=>l&&{...l,cursor:Math.min(l.rows.length-1,l.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=tt.rows.length){En(l=>l&&{...l,cursor:Number(c)-1});return}if(d.return){let l=tt.rows[tt.cursor],w=new Set(l.articleIds),E=tt.groups.filter(f=>w.has(f.articleId)),F=tt.resolve;En(null),Gc(E,{resolve:F});return}if(d.escape){En(null);return}return}if(Tt){if(d.upArrow){tn(l=>l&&{...l,cursor:Math.max(0,l.cursor-1)});return}if(d.downArrow){tn(l=>l&&{...l,cursor:Math.min(l.rows.length-1,l.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Tt.rows.length){tn(l=>l&&{...l,cursor:Number(c)-1});return}if(d.return){let l=Tt.rows[Tt.cursor];tn(null),l.action==="capture"?bo(l.ids,{runLine:l.kind==="all"?["/screenshot capture --all","/capture --all"]:void 0}):l.kind==="shot"?Kc(l.ids[0]):Yc(l.ids,{setup:!0,runLine:l.kind==="all"?["/screenshot author --all","/screenshot --all"]:void 0});return}if(d.escape){tn(null);return}return}if(Ve){if(d.escape){on(null);return}if(d.upArrow){on(l=>l&&{...l,cursor:Math.max(0,l.cursor-1)});return}if(d.downArrow){on(l=>l&&{...l,cursor:Math.min(Math.max(0,Tr.length-1),l.cursor+1)});return}if(d.return){let l=Tr[Ve.cursor];if(l){on(null);try{p({kind:"preview",name:dr(l),text:$m(ii(pc(e,l),"utf8"))})}catch(w){p({kind:"note",tone:"error",text:`Could not read ${l}: ${w.message}`})}}return}if(d.backspace||d.delete){on(l=>l&&{...l,query:l.query.slice(0,-1),cursor:0});return}if(c&&!d.ctrl&&!d.meta&&c.length===1){on(l=>l&&{...l,query:l.query+c,cursor:0});return}return}if(Ye){if(d.escape){sn(null);return}if(d.upArrow){sn(l=>l&&{...l,cursor:Math.max(0,l.cursor-1)});return}if(d.downArrow){sn(l=>l&&{...l,cursor:Math.min(Math.max(0,Er.length-1),l.cursor+1)});return}if(d.return){let l=Er[Ye.cursor];if(l){sn(null),Ue(l.uuid),gt.current={uuid:l.uuid,firstPrompt:l.firstPrompt,titleFired:!0},Jt(l.name),hc(l.uuid),Cn.current=[],Ke.current={printed:[],armed:[]};let w=sc(e,l.uuid);for(let E of w)p(E);p({kind:"note",tone:"ok",text:w.length?`Resumed "${l.name}" \u2014 restored ${w.length} message(s); continue where you left off.`:`Resumed "${l.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(d.backspace||d.delete){sn(l=>l&&{...l,query:l.query.slice(0,-1),cursor:0});return}if(c&&!d.ctrl&&!d.meta&&c.length===1){sn(l=>l&&{...l,query:l.query+c,cursor:0});return}return}if(d.tab&&!k&&ke){x(ke),ut();return}if(!k&&pe.length>0&&!Yt&&c&&/^[1-9]$/.test(c)){let l=pe[Number(c)-1];if(l){x(kn(l));return}}if(!k&&pe.length===0&&!Yt&&Ke.current.armed.length>0&&c&&/^[1-9]$/.test(c)){let l=Ke.current.armed[Number(c)-1];if(l){x(l);return}}if(!k&&(Rr||fo)&&c==="c"&&!d.ctrl&&!d.meta&&!d.return&&!d.tab){let l=Rr!=null;nc(Rr??fo).then(E=>{p({kind:"note",tone:E?"ok":"warn",text:E?l?"\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.":l?"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&&l&&xi(null),E&&!l&&Oc(!0)});return}if(!eu(c,d)){if(Bc){if(d.upArrow){vn(l=>Math.max(0,l-1));return}if(d.downArrow){vn(l=>Math.min(kt.length-1,l+1));return}if(d.tab){x("/"+(kt[di]?.name??"")+" "),vn(0);return}if(d.return){let l=kt[di];if(l){let w=k.trim().slice(1).split(/\s+/).slice(1).join(" ");if(ed(l.usage)&&!w){x("/"+l.name+" "),vn(0);return}Ir("/"+l.name+(w?" "+w:""));return}}}else{if(d.upArrow){if(k!==""&&xn===null){Or(-1);return}let l=pi.current;if(!l.length)return;let w=xn===null?l.length-1:Math.max(0,xn-1);yr(w),x(l[w]??"");return}if(d.downArrow){if(k!==""&&xn===null){Or(1);return}let l=pi.current;if(xn===null)return;let w=xn+1;w>=l.length?(yr(null),x("")):(yr(w),x(l[w]??""));return}}if(d.return){Ir();return}if(d.backspace||d.delete){C();return}if(d.escape){x(""),vn(0),ut(),le([]),An(null),Se.current=!0;return}c&&!d.ctrl&&!d.meta&&Qc(c)}}}),Ge(()=>{if(S||N)return;let c=rn.current.shift();c!==void 0&&(fi([...rn.current]),Ir(c))},[S,N,Ir]),ne(ge,{flexDirection:"column",width:Me,children:[Pi!==null&&ne(ge,{marginTop:1,flexDirection:"column",children:[Pi.truncated&&L(_,{dimColor:!0,children:"\u2026"}),L(_,{children:Pi.text})]}),S&&(br?L(V0,{p:br}):L(H0,{startTime:Rt.current,chars:Dm})),!S&&Ac?L(q0,{text:Ac}):null,L(ge,{borderStyle:"round",borderColor:Wc.prod?"yellow":te,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:k?Zc.map((c,d)=>{let l=h.text.slice(c.start,c.end),w=d===si(Zc,h.pos),E=Math.min(h.pos,c.end)-c.start;return ne(_,{children:[L(_,{color:te,children:d===0?"> ":" "}),w?ne(oo,{children:[l.slice(0,E),L(no,{ch:l[E]??" "}),l.slice(E+1)]}):l||" "]},`${d}-${c.start}`)}):ne(_,{children:[L(_,{color:te,children:"> "}),ho?L(no,{ch:" "}):ke&&!S&&be?ne(oo,{children:[L(no,{ch:be[0],dim:!0}),L(_,{color:"gray",children:be.slice(1)})]}):ke&&!S?ne(oo,{children:[L(no,{ch:ke[0],dim:!0}),L(_,{color:"gray",children:ke.slice(1)}),L(_,{dimColor:!0,children:" (tab)"})]}):(Ri.isSetup||!mr)&&!S?ne(oo,{children:[L(no,{ch:Ri.text[0],dim:!0}),L(_,{color:"gray",children:Ri.text.slice(1)})]}):L(no,{ch:" "})]})}),Ec.length>0&&L(ge,{flexDirection:"column",paddingX:1,children:Ec.map((c,d)=>L(_,{color:"gray",children:`\u29D7 queued: ${c}`},`${d}-${c.slice(0,24)}`))}),po?L(If,{tab:po.tab,scroll:po.scroll,rows:_m,width:Me,version:o,engineVersion:vm}):Qt?ne(ge,{flexDirection:"column",paddingX:1,children:[L(_,{color:te,bold:!0,children:"Select model"}),L(_,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),mt.map((c,d)=>ne(_,{color:d===Qt.cursor?te:void 0,children:[d===Qt.cursor?"\u276F ":" ",`${d+1}. ${c.label}${d===Qt.current?" \u2714":""}`.padEnd(16),L(_,{color:"gray",children:c.desc})]},c.label)),L(_,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):St?ne(ge,{flexDirection:"column",paddingX:1,children:[L(_,{color:te,bold:!0,children:"Switch connection profile"}),L(bn,{rows:St.rows,cursor:St.cursor,cap:Dt,render:(c,d,l)=>ne(_,{color:l?te:void 0,children:[l?"\u276F ":" ",`${d+1}. ${c.name}${d===St.current?" \u2714":""}`.padEnd(20),L(_,{color:"gray",children:`${c.env} \xB7 ${c.who??"not signed in"}`}),c.prod?L(_,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},c.name)}),L(_,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Pt?ne(ge,{flexDirection:"column",paddingX:1,children:[L(_,{color:te,bold:!0,children:"Pick your Document360 environment"}),L(bn,{rows:Pt.rows,cursor:Pt.cursor,cap:Dt,render:(c,d,l)=>ne(_,{color:l?te:void 0,children:[l?"\u276F ":" ",`${d+1}. ${c.name}`.padEnd(16),L(_,{color:"gray",children:c.apiUrl}),c.note?L(_,{color:"yellow",children:` \u26A0 ${c.note}`}):null]},c.name)}),L(_,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):Oe?ne(ge,{flexDirection:"column",paddingX:1,children:[L(_,{color:te,bold:!0,children:"Switch workspace"}),L(_,{dimColor:!0,children:`environment ${Oe.environment} \xB7 project ${Oe.projectName??`${Oe.projectId.slice(0,8)}\u2026`}`}),L(bn,{rows:Oe.rows,cursor:Oe.cursor,cap:Dt,render:(c,d,l)=>ne(_,{color:l?te:void 0,children:[l?"\u276F ":" ",`${d+1}. ${c.name}${d===Oe.current?" \u2714":""}`.padEnd(30),L(_,{color:"gray",children:c.type??""})]},c.id)}),L(_,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):et?ne(ge,{flexDirection:"column",paddingX:1,children:[L(_,{color:te,bold:!0,children:"Choose project"}),L(_,{dimColor:!0,children:`environment ${et.environment}`}),L(bn,{rows:et.rows,cursor:et.cursor,cap:Dt,render:(c,d,l)=>ne(_,{color:l?te:void 0,children:[l?"\u276F ":" ",`${d+1}. ${c.name}${d===et.current?" \u2714":""}`.padEnd(30),L(_,{color:"gray",children:c.sub??""})]},c.id)}),L(_,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):Le?(()=>{let d=Math.min(Math.max(0,Le.cursor-Math.floor(7)),Math.max(0,Le.rows.length-14)),l=Le.rows.slice(d,d+14),w=Le.rows.filter(E=>E.checked).length;return ne(ge,{flexDirection:"column",paddingX:1,children:[L(_,{color:te,bold:!0,children:`Which folders back the user docs? (${w} selected of ${Le.rows.length})`}),d>0?L(_,{dimColor:!0,children:` \u2191 ${d} more`}):null,l.map((E,F)=>{let f=d+F;return ne(_,{color:f===Le.cursor?te:void 0,children:[f===Le.cursor?"\u276F ":" ",E.checked?"\u25C9 ":"\u25CB ",E.path.padEnd(Math.min(48,Me-34)),L(_,{color:"gray",children:vs(E)})]},E.path)}),d+14<Le.rows.length?L(_,{dimColor:!0,children:` \u2193 ${Le.rows.length-d-14} more`}):null,L(_,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():lt?ne(ge,{flexDirection:"column",paddingX:1,children:[L(_,{color:te,bold:!0,children:lt.title??"Which category? (pick one to scope to)"}),L(bn,{rows:lt.rows,cursor:lt.cursor,cap:Dt,render:(c,d,l)=>ne(_,{color:l?te:void 0,children:[l?"\u276F ":" ",`${`${d+1}.`.padEnd(3)} ${c.label} (${c.count})`.padEnd(Math.min(44,Math.max(20,Me-24))),L(_,{color:"gray",children:` ${c.token}`})]},c.token)}),L(_,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):wt?ne(ge,{flexDirection:"column",paddingX:1,children:[L(_,{color:te,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),L(bn,{rows:wt.rows,cursor:wt.cursor,cap:Dt,render:(c,d,l)=>ne(_,{color:l?te:void 0,bold:c.kind==="category"&&!l,children:[l?"\u276F ":" ",`${c.indent?" ":" "}${`${d+1}.`.padEnd(3)} ${c.label}`.padEnd(Math.min(56,Me-24)),c.note?L(_,{color:"gray",children:c.note}):null]},`${c.kind}:${c.paths.join(",")}`)}),L(_,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):tt?ne(ge,{flexDirection:"column",paddingX:1,children:[L(_,{color:te,bold:!0,children:"Answer reviewer comments \u2014 pick what to handle:"}),L(bn,{rows:tt.rows,cursor:tt.cursor,cap:Dt,render:(c,d,l)=>ne(_,{color:l?te:void 0,bold:c.kind==="category"&&!l,children:[l?"\u276F ":" ",`${c.indent?" ":" "}${`${d+1}.`.padEnd(3)} ${c.label}`.padEnd(Math.min(56,Me-24)),c.kind==="article"&&c.note?L(_,{color:"gray",children:c.note}):null]},`${c.kind}:${c.articleIds.join(",")}`)}),L(_,{dimColor:!0,children:tt.resolve?"\u2191\u2193 move \xB7 1-9 jump \xB7 enter fix, push a draft, reply + resolve \xB7 esc cancel":"\u2191\u2193 move \xB7 1-9 jump \xB7 enter fix, push a draft, reply (thread stays open) \xB7 esc cancel"})]}):Tt?ne(ge,{flexDirection:"column",paddingX:1,children:[L(_,{color:te,bold:!0,children:Tt.title}),(()=>{let{rows:c,cursor:d}=Tt,l=Qs(c.length,d,Dt),w=l.start,E=c.slice(l.start,l.end),F=`${c.length}.`.length+1,f=Gd(c,Math.max(20,Me-4-F));return ne(oo,{children:[w>0?L(_,{color:"gray",children:` \u2026 ${w} more above`}):null,E.map((m,$)=>{let y=w+$,v=y===d,P=f[y];return ne(_,{color:v?te:void 0,bold:(m.kind==="all"||m.kind==="category")&&!v,children:[v?"\u276F ":" ",`${y+1}.`.padEnd(F),P.head,P.note?L(_,{color:"gray",children:P.note}):null]},`${m.action}:${m.kind}:${m.ids.join(",")}`)}),l.below>0?L(_,{color:"gray",children:` \u2026 ${l.below} more below`}):null]})})(),L(_,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter run \xB7 esc cancel"})]}):Ve?ne(ge,{flexDirection:"column",paddingX:1,children:[L(_,{color:te,bold:!0,children:`Preview article${Ve.query?` \u2014 filter: ${Ve.query}`:" (type to filter)"}`}),Tr.length===0?L(_,{color:"gray",children:"no articles match"}):Tr.map((c,d)=>ne(_,{color:d===Ve.cursor?te:void 0,children:[d===Ve.cursor?"\u276F ":" ",c]},c)),L(_,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):Ye?ne(ge,{flexDirection:"column",paddingX:1,children:[L(_,{color:te,bold:!0,children:`Resume session${Ye.query?` \u2014 filter: ${Ye.query}`:" (type to filter)"}`}),Er.length===0?L(_,{color:"gray",children:"no sessions match"}):Er.map((c,d)=>ne(_,{color:d===Ye.cursor?te:void 0,children:[d===Ye.cursor?"\u276F ":" ",c.name.slice(0,28).padEnd(30),L(_,{color:d===Ye.cursor?te:"gray",children:c.firstPrompt.slice(0,Math.max(10,Me-40))})]},c.uuid)),L(_,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Bc?ne(ge,{flexDirection:"column",children:[un>0?L(_,{dimColor:!0,children:` \u22EF ${un} more above`}):null,Si.map((c,d)=>{let l=un+d,w=c.name==="model"&&mi?`${c.desc} (currently ${mi})`:c.desc,E=Math.max(20,Me-4),F=c.usage.length>E?`${c.usage.slice(0,E-1)}\u2026`:c.usage,f=E-Math.max(F.length,22)-1,m=f<=1?"":w.length>f?`${w.slice(0,f-1)}\u2026`:w;return ne(_,{color:l===Pr?te:void 0,children:[l===Pr?"\u276F ":" ",F.padEnd(22)," ",L(_,{color:l===Pr?te:"gray",children:m})]},c.name)}),un+Si.length<kt.length?L(_,{dimColor:!0,children:` \u22EF ${kt.length-un-Si.length} more below`}):null,L(_,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!S&&!k&&pe.length>0?ne(ge,{flexDirection:"column",paddingX:1,children:[Tc?L(_,{color:te,children:Tc}):null,pe.map((c,d)=>{let l=kn(c),w=l.slice(0,Math.max(20,Me-5)),E=Me-w.length-7,F=E>=12?(Uf(c)??Qu(l)).slice(0,E):"";return ne(_,{children:[L(_,{color:te,children:d+1})," ",w,F?L(_,{dimColor:!0,children:` \u2014 ${F}`}):null]},l)}),L(_,{dimColor:!0,children:`press 1-${pe.length} to fill \xB7 esc cancel`})]}):L(ge,{paddingX:1,children:ne(_,{color:"gray",children:[Wc.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${mi??"model n/a"}${t.kind==="api"?Nc>0?` \xB7 ${We(Nc)}`:"":Dc>0?` \xB7 ${Ft(Dc)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}Q();import{jsx as X0}from"react/jsx-runtime";async function Cm(e=process.cwd(),t="auto",n,o="0.0.0"){let r=z0(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 ${q("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${q("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=K0(X0(xm,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
|
|
492
|
-
`),process.exit(0)}Q();import{writeCrashLog as
|
|
487
|
+
`)}),f.answer&&(f.all||f.scope.path||f.scope.scope||$.length===1)){await Gc($,{resolve:f.resolve});return}En({cursor:0,rows:$h(m.threads,m.labels),groups:$,resolve:f.resolve});return}case"update":{bi.current=!0,p({kind:"note",tone:"info",text:"Updating the d360-writer toolchain\u2026 (don\u2019t close this window)"}),yr(!0);let f=await Ls().finally(()=>yr(!1));f.ok?(p({kind:"note",tone:"ok",text:`\u2713 Updated ${f.packages.join(" + ")} \u2014 run /exit, then relaunch to apply.`}),ee("/exit"),Cc("")):p({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${Os}`});return}case"screenshot":{let f=Oo(w),m=Lo(e);if(m&&f.mode!=="list"&&p({kind:"note",tone:"info",text:m}),f.mode==="capture"){await E(f.rest);return}if(f.mode==="checklist"){await F();return}if(f.mode==="verify"){let v=Ae(e),P=f.rest.find(J=>!J.startsWith("-")),M=P?[P]:Ko(v);if(P&&!v.some(J=>J.id===P)){p({kind:"note",tone:"error",text:`No screenshot placeholder called "${P}". /screenshot list shows them all.`});return}if(M.length===0){let J=v.filter(O=>O.state==="rejected").length,D=v.filter(O=>O.state==="verified").length;p({kind:"note",tone:"info",text:J>0?`Nothing left to verify. ${J} shot${J===1?"":"s"} failed verification \u2014 re-capture with /screenshot capture --failed.`:D>0?`All ${D} captured shot${D===1?" is":"s are"} already verified.`:"No captured screenshots to verify yet \u2014 /screenshot capture takes the shots first."});return}p({kind:"note",tone:"info",text:zo(M.length)}),await he(wn(e,M),{display:P?`/screenshot verify ${P}`:"/screenshot verify",quietUser:!0});let H=Xo(e,M);H.length>0&&p({kind:"note",tone:"info",text:H.join(`
|
|
488
|
+
`)});return}if(f.mode==="list"){if(!de(e)){p({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let v=de(e)?.docsDir??bc,P=ba(e,f.scope),M=Ae(e,P);if(f.picker){if(M.length===0){p({kind:"note",tone:"info",text:"No screenshot placeholders found in the docs."});return}let U=Yd(M);if(U.length===0){p({kind:"note",tone:"info",text:gs(M,{docsDir:v}).join(`
|
|
489
|
+
`)});let se=Wo(e,{text:`\u2713 All ${M.length} screenshots are captured. /publish puts them in the articles; /screenshot capture re-captures.`,cmd:"/publish"},`\u2713 All ${M.length} screenshots are captured. `);Ee(se.text,{kind:"cmd",cmd:se.cmd,reason:""});return}tn({cursor:0,rows:U,title:"Screenshots \u2014 pick what to author or capture:"});return}p({kind:"note",tone:"info",text:gs(M,{scope:P,detail:f.detail,docsDir:v}).join(`
|
|
490
|
+
`)}),m&&p({kind:"note",tone:"info",text:m});let H=M.filter(U=>U.state==="placeholder").length,J=M.filter(U=>U.state==="spec").length,D=M.filter(U=>U.state==="captured").length,O=M.filter(U=>U.state==="rejected").length,I=M.filter(U=>U.state==="spec"&&!U.mutates).length;H>0?ee(P?`/screenshot author ${P}`:"/screenshot author --all"):J>0&&(I>0||D===0)?ee(P?`/screenshot capture ${P}`:"/screenshot capture"):D>0?ee("/screenshot verify"):O>0&&ee("/screenshot capture --failed");return}if(f.mode==="single"){await Kc(f.id);return}if(!de(e)){p({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let $=f.mode==="scope"?f.scope:void 0,y=b0(e,{scope:$}).map(v=>v.id);if(y.length===0){p({kind:"note",tone:"info",text:$?`No screenshot placeholders under ${$}.`:"No screenshot placeholders found in the docs."});return}await Yc(y,{setup:f.setup,runLine:f.mode==="scope"?[`/screenshot author ${f.scope}`,`/screenshot ${f.scope}`]:["/screenshot author --all","/screenshot --all"]});return}case"capture":{await E(w);return}case"reset":{let f=Ml(e);if(f.length===0){p({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}ao.current={repoName:pr(e),targets:f,hadDevhints:to(fm(e))},p({kind:"note",tone:"warn",text:Fl(e,f).join(`
|
|
491
|
+
`)}),Ie(pr(e));return}default:p({kind:"note",tone:"error",text:`Unknown command: /${l} \u2014 type /help.`})}},[e,r,s,jn,Di,p,Ue,he,rt,Ti,zc]),Ir=X(c=>{let d=(c??k).trim();if(x(""),kr(null),vn(0),d.startsWith("/")&&(Se.current=!1,Pe.current=!1,Ze.current=null,ut(),An(null),le(w=>Wf(w,d))),!d||(mr(!1),(ao.current||me.current.length>0)&&p({kind:"user",text:d}),Jc(d))||Xc(d))return;pi.current.push(d);let l=Gf(d,Rc.current);if(d.startsWith("/"))p({kind:"user",text:d}),Ce(!0),xo(l).finally(()=>Ce(!1));else if(j0(l)){p({kind:"user",text:d});let w=I0(l);if(!w)he(l,{display:d,quietUser:!0});else{try{O0(e,{title:w,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}he(`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=Wh(e,l);he(w??l,{display:d})}},[k,Jc,Xc,xo,he]),Qc=X(c=>{if(c.length>1){if(c.includes("\x1B"))return;let d=Bf(c);if(Hf(d)){let l=qf(++jm.current,d);Rc.current.set(l,d),T(l)}else T(d);return}T(c)},[T]),In=Math.max(10,Me-6),Zc=dc(()=>ri(h.text,In),[h.text,In]),Ni=X(c=>g(d=>({...d,pos:Math.max(0,Math.min(d.text.length,d.pos+c))})),[]),Or=X(c=>g(d=>({...d,pos:Yf(ri(d.text,In),d.pos,c)})),[In]),Co=X(c=>g(d=>({...d,pos:Kf(ri(d.text,In),d.pos,c)})),[In]),Um=["\x1B[H","\x1B[1~","\x1BOH"],Fm=["\x1B[F","\x1B[4~","\x1BOF"],eu=X((c,d)=>d.leftArrow?(Ni(-1),!0):d.rightArrow?(Ni(1),!0):c&&Um.includes(c)?(Co("start"),!0):c&&Fm.includes(c)?(Co("end"),!0):d.ctrl&&c==="a"?(Co("start"),!0):d.ctrl&&c==="e"?(Co("end"),!0):!1,[Ni,Co]);return Hx((c,d)=>{if(d.ctrl&&c==="c"){et.current?.close(),r();return}if(yo.current.awaySince!==null)try{let l=Df(yo.current,Date.now(),yn(e));if(yo.current=l.memory,Fc(null),l.kind==="delta"){p({kind:"note",tone:"info",text:jf(l.delta,l.awayMs)});let w=ot(!1);w.kind==="recommend"&&yt(w.rec,{silent:!0})}else if(l.kind==="briefing"){p({kind:"note",tone:"info",text:`\u{1F4E5} ${ur(l.delta)} arrived while you were away (${lc(l.awayMs)}).`});let w=ot(!1);w.kind==="recommend"&&yt(w.rec)}}catch{}if(Ci.current=Date.now(),!N){if(S){if(d.escape){if(Te.current){if(!Te.current.signal.aborted){let l=(co?.verb??"work").toLowerCase(),w=co?.unit??"article";p({kind:"note",tone:"warn",text:`\u238B Stopping the ${l} run (finishing in-flight ${w}s)\u2026`}),Te.current.abort()}return}lo.current||(lo.current=!0,p({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),et.current?.interrupt());return}if(d.return){let l=k.trim();if(!l)return;rn.current.push(l),fi([...rn.current]),x("");return}if(eu(c,d))return;if(d.upArrow){Or(-1);return}if(d.downArrow){Or(1);return}if(d.backspace||d.delete){C();return}c&&!d.ctrl&&!d.meta&&Qc(c);return}if(Qt){if(d.upArrow){Zt(l=>l&&{...l,cursor:Math.max(0,l.cursor-1)});return}if(d.downArrow){Zt(l=>l&&{...l,cursor:Math.min(mt.length-1,l.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=mt.length){Zt(l=>l&&{...l,cursor:Number(c)-1});return}if(d.return){let l=mt[Qt.cursor];Zt(null);let{lines:w,changed:E,effective:F}=Vo(e,l.value??"default");for(let f of w)p({kind:"note",tone:f.startsWith("\u26A0")?"warn":f.startsWith("\u2713")?"ok":"info",text:f});E&&(jc(f=>f+1),et.current?.setModel(F));return}if(c==="s"){let l=mt[Qt.cursor];Zt(null),et.current?.setModel(l.value??void 0),p({kind:"note",tone:"ok",text:`\u2713 Using ${l.label} for this session only (your saved default is unchanged).`});return}if(d.escape){Zt(null);return}return}if(St){if(d.upArrow){Rn(l=>l&&{...l,cursor:Math.max(0,l.cursor-1)});return}if(d.downArrow){Rn(l=>l&&{...l,cursor:Math.min(l.rows.length-1,l.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=St.rows.length){Rn(l=>l&&{...l,cursor:Number(c)-1});return}if(d.return||c==="s"){let l=St.rows[St.cursor];Rn(null),Ai(l.name,d.return===!0);return}if(d.escape){Rn(null);return}return}if(ho){if(d.escape){an(null);return}if(d.leftArrow||d.tab&&d.shift){an(l=>l&&{tab:(l.tab-1+Fe.length)%Fe.length,scroll:0});return}if(d.rightArrow||d.tab){an(l=>l&&{tab:(l.tab+1)%Fe.length,scroll:0});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Fe.length){an({tab:Number(c)-1,scroll:0});return}if(d.upArrow){an(l=>l&&{...l,scroll:Math.max(0,l.scroll-1)});return}if(d.downArrow){an(l=>{if(!l)return l;let w=(Fe[l.tab]??Fe[0]).rows.length;return{...l,scroll:Math.min(Math.max(0,w-1),l.scroll+1)}});return}return}if(Pt){if(d.upArrow){Sn(l=>l&&{...l,cursor:Math.max(0,l.cursor-1)});return}if(d.downArrow){Sn(l=>l&&{...l,cursor:Math.min(l.rows.length-1,l.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Pt.rows.length){Sn(l=>l&&{...l,cursor:Number(c)-1});return}if(d.return){let l=Pt.rows[Pt.cursor].name;if(Sn(null),!Hi(e,l).created){p({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}p({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${l}").`});let E=!1;try{let F=$n(l);E=!!F&&!(Vt(F)&&!F.refreshToken)}catch{E=!1}p({kind:"note",tone:"info",text:E?`Next: sign in to ${l} and pick your project \u2014 you're already signed in here, so it'll be quick.`:`Next: sign in to Document360 (${l}) and pick your project.`}),ee("/login"),G(F=>F+1);return}if(d.escape){Sn(null);return}return}if(Oe){if(d.upArrow){Pn(l=>l&&{...l,cursor:Math.max(0,l.cursor-1)});return}if(d.downArrow){Pn(l=>l&&{...l,cursor:Math.min(l.rows.length-1,l.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Oe.rows.length){Pn(l=>l&&{...l,cursor:Number(c)-1});return}if(d.return){let l=Oe.rows[Oe.cursor],{profile:w,projectId:E}=Oe;Pn(null),Dr(w,E,l);return}if(d.escape){Pn(null);return}return}if(tt){if(d.upArrow){en(l=>l&&{...l,cursor:Math.max(0,l.cursor-1)});return}if(d.downArrow){en(l=>l&&{...l,cursor:Math.min(l.rows.length-1,l.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=tt.rows.length){en(l=>l&&{...l,cursor:Number(c)-1});return}if(d.return){let l=tt.rows[tt.cursor],{profile:w}=tt;en(null),jr(w,l);return}if(d.escape){en(null);return}return}if(Le){if(d.upArrow){Dn(l=>l&&{...l,cursor:Math.max(0,l.cursor-1)});return}if(d.downArrow){Dn(l=>l&&{...l,cursor:Math.min(l.rows.length-1,l.cursor+1)});return}if(c===" "){Dn(l=>l&&{...l,rows:l.rows.map((w,E)=>E===l.cursor?{...w,checked:!w.checked}:w)});return}if(d.return){let l=Le.rows.filter(w=>w.checked).map(w=>w.path);if(Dn(null),l.length===0){p({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}Da(e,l),p({kind:"note",tone:"ok",text:`\u2713 Scoped to ${l.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let w of l)p({kind:"note",tone:"info",text:` ${w}`});p({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(d.escape){Dn(null);return}return}if(ct){if(d.upArrow){nn(l=>l&&{...l,cursor:Math.max(0,l.cursor-1)});return}if(d.downArrow){nn(l=>l&&{...l,cursor:Math.min(l.rows.length-1,l.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=ct.rows.length){nn(l=>l&&{...l,cursor:Number(c)-1});return}if(d.return){let l=ct.rows[ct.cursor],w=ct.run;nn(null),w(l.token);return}if(d.escape){nn(null);return}return}if(wt){if(d.upArrow){Tn(l=>l&&{...l,cursor:Math.max(0,l.cursor-1)});return}if(d.downArrow){Tn(l=>l&&{...l,cursor:Math.min(l.rows.length-1,l.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=wt.rows.length){Tn(l=>l&&{...l,cursor:Number(c)-1});return}if(d.return){let l=wt.rows[wt.cursor],w=wt.conflicts;Tn(null),l.conflict?Di(l.paths[0]):l.kind==="article"?Ti(l.paths[0]):rt(l.paths,l.kind==="all"?w:0);return}if(d.escape){Tn(null);return}return}if(nt){if(d.upArrow){En(l=>l&&{...l,cursor:Math.max(0,l.cursor-1)});return}if(d.downArrow){En(l=>l&&{...l,cursor:Math.min(l.rows.length-1,l.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=nt.rows.length){En(l=>l&&{...l,cursor:Number(c)-1});return}if(d.return){let l=nt.rows[nt.cursor],w=new Set(l.articleIds),E=nt.groups.filter(f=>w.has(f.articleId)),F=nt.resolve;En(null),Gc(E,{resolve:F});return}if(d.escape){En(null);return}return}if(Tt){if(d.upArrow){tn(l=>l&&{...l,cursor:Math.max(0,l.cursor-1)});return}if(d.downArrow){tn(l=>l&&{...l,cursor:Math.min(l.rows.length-1,l.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Tt.rows.length){tn(l=>l&&{...l,cursor:Number(c)-1});return}if(d.return){let l=Tt.rows[Tt.cursor];tn(null),l.action==="capture"?$o(l.ids,{runLine:l.kind==="all"?["/screenshot capture --all","/capture --all"]:void 0}):l.kind==="shot"?Kc(l.ids[0]):Yc(l.ids,{setup:!0,runLine:l.kind==="all"?["/screenshot author --all","/screenshot --all"]:void 0});return}if(d.escape){tn(null);return}return}if(Ve){if(d.escape){on(null);return}if(d.upArrow){on(l=>l&&{...l,cursor:Math.max(0,l.cursor-1)});return}if(d.downArrow){on(l=>l&&{...l,cursor:Math.min(Math.max(0,Tr.length-1),l.cursor+1)});return}if(d.return){let l=Tr[Ve.cursor];if(l){on(null);try{p({kind:"preview",name:pr(l),text:vm(ii(pc(e,l),"utf8"))})}catch(w){p({kind:"note",tone:"error",text:`Could not read ${l}: ${w.message}`})}}return}if(d.backspace||d.delete){on(l=>l&&{...l,query:l.query.slice(0,-1),cursor:0});return}if(c&&!d.ctrl&&!d.meta&&c.length===1){on(l=>l&&{...l,query:l.query+c,cursor:0});return}return}if(Ke){if(d.escape){sn(null);return}if(d.upArrow){sn(l=>l&&{...l,cursor:Math.max(0,l.cursor-1)});return}if(d.downArrow){sn(l=>l&&{...l,cursor:Math.min(Math.max(0,Er.length-1),l.cursor+1)});return}if(d.return){let l=Er[Ke.cursor];if(l){sn(null),Ue(l.uuid),gt.current={uuid:l.uuid,firstPrompt:l.firstPrompt,titleFired:!0},Jt(l.name),hc(l.uuid),Cn.current=[],ze.current={printed:[],armed:[]};let w=sc(e,l.uuid);for(let E of w)p(E);p({kind:"note",tone:"ok",text:w.length?`Resumed "${l.name}" \u2014 restored ${w.length} message(s); continue where you left off.`:`Resumed "${l.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(d.backspace||d.delete){sn(l=>l&&{...l,query:l.query.slice(0,-1),cursor:0});return}if(c&&!d.ctrl&&!d.meta&&c.length===1){sn(l=>l&&{...l,query:l.query+c,cursor:0});return}return}if(d.tab&&!k&&ke){x(ke),ut();return}if(!k&&pe.length>0&&!Yt&&c&&/^[1-9]$/.test(c)){let l=pe[Number(c)-1];if(l){x(kn(l));return}}if(!k&&pe.length===0&&!Yt&&ze.current.armed.length>0&&c&&/^[1-9]$/.test(c)){let l=ze.current.armed[Number(c)-1];if(l){x(l);return}}if(!k&&(Rr||mo)&&c==="c"&&!d.ctrl&&!d.meta&&!d.return&&!d.tab){let l=Rr!=null;nc(Rr??mo).then(E=>{p({kind:"note",tone:E?"ok":"warn",text:E?l?"\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.":l?"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&&l&&xi(null),E&&!l&&Oc(!0)});return}if(!eu(c,d)){if(Bc){if(d.upArrow){vn(l=>Math.max(0,l-1));return}if(d.downArrow){vn(l=>Math.min(kt.length-1,l+1));return}if(d.tab){x("/"+(kt[di]?.name??"")+" "),vn(0);return}if(d.return){let l=kt[di];if(l){let w=k.trim().slice(1).split(/\s+/).slice(1).join(" ");if(ed(l.usage)&&!w){x("/"+l.name+" "),vn(0);return}Ir("/"+l.name+(w?" "+w:""));return}}}else{if(d.upArrow){if(k!==""&&xn===null){Or(-1);return}let l=pi.current;if(!l.length)return;let w=xn===null?l.length-1:Math.max(0,xn-1);kr(w),x(l[w]??"");return}if(d.downArrow){if(k!==""&&xn===null){Or(1);return}let l=pi.current;if(xn===null)return;let w=xn+1;w>=l.length?(kr(null),x("")):(kr(w),x(l[w]??""));return}}if(d.return){Ir();return}if(d.backspace||d.delete){C();return}if(d.escape){x(""),vn(0),ut(),le([]),An(null),Se.current=!0;return}c&&!d.ctrl&&!d.meta&&Qc(c)}}}),Ge(()=>{if(S||N)return;let c=rn.current.shift();c!==void 0&&(fi([...rn.current]),Ir(c))},[S,N,Ir]),ne(ge,{flexDirection:"column",width:Me,children:[Pi!==null&&ne(ge,{marginTop:1,flexDirection:"column",children:[Pi.truncated&&L(_,{dimColor:!0,children:"\u2026"}),L(_,{children:Pi.text})]}),S&&co?L(Y0,{p:co}):null,Ac?L(G0,{text:Ac}):S&&!co?L(q0,{startTime:Rt.current,chars:Nm}):null,L(ge,{borderStyle:"round",borderColor:Wc.prod?"yellow":te,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:k?Zc.map((c,d)=>{let l=h.text.slice(c.start,c.end),w=d===si(Zc,h.pos),E=Math.min(h.pos,c.end)-c.start;return ne(_,{children:[L(_,{color:te,children:d===0?"> ":" "}),w?ne(oo,{children:[l.slice(0,E),L(no,{ch:l[E]??" "}),l.slice(E+1)]}):l||" "]},`${d}-${c.start}`)}):ne(_,{children:[L(_,{color:te,children:"> "}),fo?L(no,{ch:" "}):ke&&!S&&be?ne(oo,{children:[L(no,{ch:be[0],dim:!0}),L(_,{color:"gray",children:be.slice(1)})]}):ke&&!S?ne(oo,{children:[L(no,{ch:ke[0],dim:!0}),L(_,{color:"gray",children:ke.slice(1)}),L(_,{dimColor:!0,children:" (tab)"})]}):(Ri.isSetup||!gr)&&!S?ne(oo,{children:[L(no,{ch:Ri.text[0],dim:!0}),L(_,{color:"gray",children:Ri.text.slice(1)})]}):L(no,{ch:" "})]})}),Ec.length>0&&L(ge,{flexDirection:"column",paddingX:1,children:Ec.map((c,d)=>L(_,{color:"gray",children:`\u29D7 queued: ${c}`},`${d}-${c.slice(0,24)}`))}),ho?L(Of,{tab:ho.tab,scroll:ho.scroll,rows:Mm,width:Me,version:o,engineVersion:xm}):Qt?ne(ge,{flexDirection:"column",paddingX:1,children:[L(_,{color:te,bold:!0,children:"Select model"}),L(_,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),mt.map((c,d)=>ne(_,{color:d===Qt.cursor?te:void 0,children:[d===Qt.cursor?"\u276F ":" ",`${d+1}. ${c.label}${d===Qt.current?" \u2714":""}`.padEnd(16),L(_,{color:"gray",children:c.desc})]},c.label)),L(_,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):St?ne(ge,{flexDirection:"column",paddingX:1,children:[L(_,{color:te,bold:!0,children:"Switch connection profile"}),L(bn,{rows:St.rows,cursor:St.cursor,cap:Dt,render:(c,d,l)=>ne(_,{color:l?te:void 0,children:[l?"\u276F ":" ",`${d+1}. ${c.name}${d===St.current?" \u2714":""}`.padEnd(20),L(_,{color:"gray",children:`${c.env} \xB7 ${c.who??"not signed in"}`}),c.prod?L(_,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},c.name)}),L(_,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Pt?ne(ge,{flexDirection:"column",paddingX:1,children:[L(_,{color:te,bold:!0,children:"Pick your Document360 environment"}),L(bn,{rows:Pt.rows,cursor:Pt.cursor,cap:Dt,render:(c,d,l)=>ne(_,{color:l?te:void 0,children:[l?"\u276F ":" ",`${d+1}. ${c.name}`.padEnd(16),L(_,{color:"gray",children:c.apiUrl}),c.note?L(_,{color:"yellow",children:` \u26A0 ${c.note}`}):null]},c.name)}),L(_,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):Oe?ne(ge,{flexDirection:"column",paddingX:1,children:[L(_,{color:te,bold:!0,children:"Switch workspace"}),L(_,{dimColor:!0,children:`environment ${Oe.environment} \xB7 project ${Oe.projectName??`${Oe.projectId.slice(0,8)}\u2026`}`}),L(bn,{rows:Oe.rows,cursor:Oe.cursor,cap:Dt,render:(c,d,l)=>ne(_,{color:l?te:void 0,children:[l?"\u276F ":" ",`${d+1}. ${c.name}${d===Oe.current?" \u2714":""}`.padEnd(30),L(_,{color:"gray",children:c.type??""})]},c.id)}),L(_,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):tt?ne(ge,{flexDirection:"column",paddingX:1,children:[L(_,{color:te,bold:!0,children:"Choose project"}),L(_,{dimColor:!0,children:`environment ${tt.environment}`}),L(bn,{rows:tt.rows,cursor:tt.cursor,cap:Dt,render:(c,d,l)=>ne(_,{color:l?te:void 0,children:[l?"\u276F ":" ",`${d+1}. ${c.name}${d===tt.current?" \u2714":""}`.padEnd(30),L(_,{color:"gray",children:c.sub??""})]},c.id)}),L(_,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):Le?(()=>{let d=Math.min(Math.max(0,Le.cursor-Math.floor(7)),Math.max(0,Le.rows.length-14)),l=Le.rows.slice(d,d+14),w=Le.rows.filter(E=>E.checked).length;return ne(ge,{flexDirection:"column",paddingX:1,children:[L(_,{color:te,bold:!0,children:`Which folders back the user docs? (${w} selected of ${Le.rows.length})`}),d>0?L(_,{dimColor:!0,children:` \u2191 ${d} more`}):null,l.map((E,F)=>{let f=d+F;return ne(_,{color:f===Le.cursor?te:void 0,children:[f===Le.cursor?"\u276F ":" ",E.checked?"\u25C9 ":"\u25CB ",E.path.padEnd(Math.min(48,Me-34)),L(_,{color:"gray",children:vs(E)})]},E.path)}),d+14<Le.rows.length?L(_,{dimColor:!0,children:` \u2193 ${Le.rows.length-d-14} more`}):null,L(_,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():ct?ne(ge,{flexDirection:"column",paddingX:1,children:[L(_,{color:te,bold:!0,children:ct.title??"Which category? (pick one to scope to)"}),L(bn,{rows:ct.rows,cursor:ct.cursor,cap:Dt,render:(c,d,l)=>ne(_,{color:l?te:void 0,children:[l?"\u276F ":" ",`${`${d+1}.`.padEnd(3)} ${c.label} (${c.count})`.padEnd(Math.min(44,Math.max(20,Me-24))),L(_,{color:"gray",children:` ${c.token}`})]},c.token)}),L(_,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):wt?ne(ge,{flexDirection:"column",paddingX:1,children:[L(_,{color:te,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),L(bn,{rows:wt.rows,cursor:wt.cursor,cap:Dt,render:(c,d,l)=>ne(_,{color:l?te:void 0,bold:c.kind==="category"&&!l,children:[l?"\u276F ":" ",`${c.indent?" ":" "}${`${d+1}.`.padEnd(3)} ${c.label}`.padEnd(Math.min(56,Me-24)),c.note?L(_,{color:"gray",children:c.note}):null]},`${c.kind}:${c.paths.join(",")}`)}),L(_,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):nt?ne(ge,{flexDirection:"column",paddingX:1,children:[L(_,{color:te,bold:!0,children:"Answer reviewer comments \u2014 pick what to handle:"}),L(bn,{rows:nt.rows,cursor:nt.cursor,cap:Dt,render:(c,d,l)=>ne(_,{color:l?te:void 0,bold:c.kind==="category"&&!l,children:[l?"\u276F ":" ",`${c.indent?" ":" "}${`${d+1}.`.padEnd(3)} ${c.label}`.padEnd(Math.min(56,Me-24)),c.kind==="article"&&c.note?L(_,{color:"gray",children:c.note}):null]},`${c.kind}:${c.articleIds.join(",")}`)}),L(_,{dimColor:!0,children:nt.resolve?"\u2191\u2193 move \xB7 1-9 jump \xB7 enter fix, push a draft, reply + resolve \xB7 esc cancel":"\u2191\u2193 move \xB7 1-9 jump \xB7 enter fix, push a draft, reply (thread stays open) \xB7 esc cancel"})]}):Tt?ne(ge,{flexDirection:"column",paddingX:1,children:[L(_,{color:te,bold:!0,children:Tt.title}),(()=>{let{rows:c,cursor:d}=Tt,l=Qs(c.length,d,Dt),w=l.start,E=c.slice(l.start,l.end),F=`${c.length}.`.length+1,f=Vd(c,Math.max(20,Me-4-F));return ne(oo,{children:[w>0?L(_,{color:"gray",children:` \u2026 ${w} more above`}):null,E.map((m,$)=>{let y=w+$,v=y===d,P=f[y];return ne(_,{color:v?te:void 0,bold:(m.kind==="all"||m.kind==="category")&&!v,children:[v?"\u276F ":" ",`${y+1}.`.padEnd(F),P.head,P.note?L(_,{color:"gray",children:P.note}):null]},`${m.action}:${m.kind}:${m.ids.join(",")}`)}),l.below>0?L(_,{color:"gray",children:` \u2026 ${l.below} more below`}):null]})})(),L(_,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter run \xB7 esc cancel"})]}):Ve?ne(ge,{flexDirection:"column",paddingX:1,children:[L(_,{color:te,bold:!0,children:`Preview article${Ve.query?` \u2014 filter: ${Ve.query}`:" (type to filter)"}`}),Tr.length===0?L(_,{color:"gray",children:"no articles match"}):Tr.map((c,d)=>ne(_,{color:d===Ve.cursor?te:void 0,children:[d===Ve.cursor?"\u276F ":" ",c]},c)),L(_,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):Ke?ne(ge,{flexDirection:"column",paddingX:1,children:[L(_,{color:te,bold:!0,children:`Resume session${Ke.query?` \u2014 filter: ${Ke.query}`:" (type to filter)"}`}),Er.length===0?L(_,{color:"gray",children:"no sessions match"}):Er.map((c,d)=>ne(_,{color:d===Ke.cursor?te:void 0,children:[d===Ke.cursor?"\u276F ":" ",c.name.slice(0,28).padEnd(30),L(_,{color:d===Ke.cursor?te:"gray",children:c.firstPrompt.slice(0,Math.max(10,Me-40))})]},c.uuid)),L(_,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Bc?ne(ge,{flexDirection:"column",children:[un>0?L(_,{dimColor:!0,children:` \u22EF ${un} more above`}):null,Si.map((c,d)=>{let l=un+d,w=c.name==="model"&&mi?`${c.desc} (currently ${mi})`:c.desc,E=Math.max(20,Me-4),F=c.usage.length>E?`${c.usage.slice(0,E-1)}\u2026`:c.usage,f=E-Math.max(F.length,22)-1,m=f<=1?"":w.length>f?`${w.slice(0,f-1)}\u2026`:w;return ne(_,{color:l===Pr?te:void 0,children:[l===Pr?"\u276F ":" ",F.padEnd(22)," ",L(_,{color:l===Pr?te:"gray",children:m})]},c.name)}),un+Si.length<kt.length?L(_,{dimColor:!0,children:` \u22EF ${kt.length-un-Si.length} more below`}):null,L(_,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!S&&!k&&pe.length>0?ne(ge,{flexDirection:"column",paddingX:1,children:[Tc?L(_,{color:te,children:Tc}):null,pe.map((c,d)=>{let l=kn(c),w=l.slice(0,Math.max(20,Me-5)),E=Me-w.length-7,F=E>=12?(Ff(c)??Qu(l)).slice(0,E):"";return ne(_,{children:[L(_,{color:te,children:d+1})," ",w,F?L(_,{dimColor:!0,children:` \u2014 ${F}`}):null]},l)}),L(_,{dimColor:!0,children:`press 1-${pe.length} to fill \xB7 esc cancel`})]}):L(ge,{paddingX:1,children:ne(_,{color:"gray",children:[Wc.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${mi??"model n/a"}${t.kind==="api"?Nc>0?` \xB7 ${We(Nc)}`:"":Dc>0?` \xB7 ${Ft(Dc)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}Q();import{jsx as J0}from"react/jsx-runtime";async function Rm(e=process.cwd(),t="auto",n,o="0.0.0"){let r=X0(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 ${q("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${q("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=z0(J0(Cm,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
|
|
492
|
+
`),process.exit(0)}Q();import{writeCrashLog as Sm,isBenignTransportError as Q0}from"document360-engine";var Pm=!1;function $c(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function Tm(e){if(Pm)return;Pm=!0;let t=(n,o)=>{if(Q0(o)){Sm({kind:n,level:"transport",message:$c(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=Sm({kind:n,level:"fatal",message:$c(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
|
|
493
493
|
`+j(`\u2717 d360-writer crashed: ${$c(o)}`)+`
|
|
494
494
|
`),r&&process.stderr.write(b(` Crash details: ${r}`)+`
|
|
495
495
|
`+b(" Run: d360-writer logs")+`
|
|
496
|
-
`),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var
|
|
496
|
+
`),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var nC=eC(import.meta.url),ci=nC("../package.json");Tm("d360-writer");var at=new Z0;function vc(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}at.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=>{vc(e),await Br({profile:e.profile,manual:e.manual})});at.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{vc(e),await fu({profile:e.profile})});at.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{vc(e),await hu({profile:e.profile})});var xc=at.command("profile").description("Manage connection profiles for the current repo");xc.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>Hr(process.cwd()));xc.command("use <name>").description("Set the default profile for this repo").action(e=>qr(process.cwd(),e));xc.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>Gr(process.cwd(),e));var Em=at.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");Em.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>On(process.cwd(),e.profile));Em.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await su(process.cwd(),e,t.profile)});var Am=at.command("project").description("Choose the Document360 project for this repo (active profile's identity)");Am.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>Ur(process.cwd(),e.profile));Am.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await au(process.cwd(),e,t.profile)});at.command("init").description("Scaffold .d360-writer/config.json for this repo (interactive)").action(async()=>{let{initCommand:e}=await Promise.resolve().then(()=>(es(),Vu));await e()});at.command("logs").description("Show the API + crash log files (send these to support when reporting a problem)").action(()=>yu());at.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(()=>(Es(),Gp)),n=await t(process.cwd(),ci.version);for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});at.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(ci.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(tC.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 ku(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 gf(e.cwd,e.auth,e.profile,ci.version):await Rm(e.cwd,e.auth,e.profile,ci.version)});at.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
|