document360-writer 0.5.195 → 0.5.196
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 +141 -142
- package/package.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var bh=Object.defineProperty;var Gn=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var Al=(e,t)=>{for(var n in t)bh(e,n,{get:t[n],enumerable:!0})};import mt from"picocolors";var Z,$h,vh,xh,jl,Yn,g,A,H,U,W,fe,Ee,X=Gn(()=>{"use strict";Z="#7f56d9",[$h,vh,xh]=[127,86,217],jl=e=>mt.isColorSupported?`\x1B[38;2;${$h};${vh};${xh}m${e}\x1B[39m`:e,Yn=e=>mt.bold(jl(e)),g=e=>mt.dim(e),A=e=>mt.red(e),H=e=>mt.yellow(e),U=e=>mt.green(e),W=jl,fe=e=>mt.gray(e),Ee=e=>mt.bold(e)});import{existsSync as gn,writeFileSync as yt,readFileSync as cf,readdirSync as df}from"node:fs";import{join as Ql}from"node:path";import{devHintsGuidePath as ar,hintsDir as Jl,hooksDir as Zl,architectureDir as rc,messagesDir as Hs,creatorNotesPath as ec,devhintsStatePath as sc,directivesPath as tc,DIRECTIVES_HEADER as uf,roadmapPath as nc,ROADMAP_HEADER as pf,ensureDir as Xn,writeMessage as hf,listOpenForDev as ff}from"document360-engine";function ic(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
|
|
3
3
|
|
|
4
|
-
<!-- devhints script v${
|
|
4
|
+
<!-- devhints script v${me} \xB7 maintained by document360-writer (/devhints). -->
|
|
5
5
|
|
|
6
6
|
This repo's user documentation is written by **document360-writer** ("the docs agent"), a separate agent.
|
|
7
7
|
It can read your code, but code alone can't tell it the *intent* \u2014 WHY a feature exists, which of a
|
|
@@ -218,7 +218,7 @@ do it**:
|
|
|
218
218
|
**Do NOT write or action the documentation yourself** \u2014 same boundary as Part 2. Writing the article is the
|
|
219
219
|
docs agent's job; it actions open directives on its next \`/catch-up\` (as drafts) and flips each to \`[done]\`
|
|
220
220
|
with the article it wrote. You are only the relay so the ask is captured durably and travels via git.
|
|
221
|
-
`}function
|
|
221
|
+
`}function gf(){return`# Creator notes (optional \u2014 for the docs agent and the builder)
|
|
222
222
|
|
|
223
223
|
<!-- The ORIGINAL CREATOR's context. Most repos leave this empty \u2014 that's fine.
|
|
224
224
|
The builder agent reads this FIRST and treats it as authoritative when writing the architecture
|
|
@@ -232,12 +232,12 @@ Anything only a human knows that would help document this product. For example:
|
|
|
232
232
|
- Gotchas or non-obvious behavior.
|
|
233
233
|
|
|
234
234
|
(Replace these examples with your notes, or leave the file as-is to skip \u2014 it's optional.)
|
|
235
|
-
`}function
|
|
236
|
-
`)}
|
|
237
|
-
`)}function
|
|
238
|
-
`)}function
|
|
239
|
-
`)}),n.notifiedBuilder=!0))}catch{}return n}function
|
|
240
|
-
`)}function
|
|
235
|
+
`}function wn(e){Xn(Jl(e)),Xn(rc(e)),Xn(Hs(e));for(let n of[Jl(e),Hs(e)]){let o=Ql(n,".gitkeep");gn(o)||yt(o,`# Keeps this document360-writer inbox tracked in git even when empty.
|
|
236
|
+
`)}gn(ec(e))||yt(ec(e),gf()),gn(tc(e))||yt(tc(e),uf),gn(nc(e))||yt(nc(e),pf),yt(ar(e),ic()),Xn(Zl(e)),yt(Ql(Zl(e),"open-questions.mjs"),mf);let t=Ge(e);return lc(e,new Date().toISOString()),t}async function ac(e,t){for(let n of kn(wn(t.cwd)))console.log(n);return{kind:"continue"}}function qt(){return[`This is document360-writer's dev hand-off setup (v${me}).`,'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; 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): 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": ${me},`,' "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. When everything is done, print the completion line, THEN the next command as its own copy-paste"," block so it is unmistakable. Pick the matching first line:",' \u2022 first-time setup: "\u2705 Setup complete. Now switch to the document360-writer terminal and paste this:"',' \u2022 a refresh (brief/notes already existed): "\u2705 Hand-off refreshed. Back in the document360-writer terminal, paste this:"'," Then, on its OWN line, fenced as a code block so it copies cleanly:"," ```"," write the docs for this repo"," ```"].join(`
|
|
237
|
+
`)}function qs(e){try{let t=cf(sc(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function lc(e,t){let o={...qs(e)??{},emittedVersion:me,emittedAt:t};yt(sc(e),`${JSON.stringify(o,null,2)}
|
|
238
|
+
`)}function at(e){try{return df(rc(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function Ge(e){let n=qs(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<me?"stale":"current",completedVersion:n}}function lr(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:me};try{if(!gn(ar(e)))return n;let o=qs(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;me>r&&(Xn(Hs(e)),yt(ar(e),ic()),lc(e,t),n.guideRefreshed=!0),me>s&&(ff(e).some(l=>l.kind==="request"&&l.subject.startsWith(oc))||(hf(e,{id:`onb${me}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${oc}${me})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${me}${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:","",qt()].join(`
|
|
239
|
+
`)}),n.notifiedBuilder=!0))}catch{}return n}function cr(e){if(!gn(ar(e)))return[];let t=Ge(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${me}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,yn,qt(),yn,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function Vs(){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(`
|
|
240
|
+
`)}function dr(){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):",yn,Vs(),yn]}function kn(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${me}.`," 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):",yn,qt(),yn,"","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 yn,me,mf,oc,wt=Gn(()=>{"use strict";yn="-".repeat(64),me=10,mf=`#!/usr/bin/env node
|
|
241
241
|
// d360-writer \u2014 session-start nudge for the builder ("John"). Surfaces open questions the docs agent
|
|
242
242
|
// ("Julie") left in .d360-writer/messages/ so they get answered, not forgotten. Self-contained (no deps);
|
|
243
243
|
// wired into your coding agent's session-start trigger by /devhints. See .d360-writer/DEV-HINTS-GUIDE.md.
|
|
@@ -275,70 +275,70 @@ try {
|
|
|
275
275
|
} catch {
|
|
276
276
|
/* a session-start nudge must never break the session */
|
|
277
277
|
}
|
|
278
|
-
`;
|
|
279
|
-
`),"utf8")}async function qs(){let e=process.cwd(),t=dl(e);if(kn(t)&&!await gf({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(g("init cancelled.")),{kind:"continue"};let n=ml(e)??cl(e),o=await Xn({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await Xn({message:"Capture directory (where document360-capture .spec.ts files live):",default:pl}),s=await Xn({message:"Screenshot output directory:",default:hl}),i=await Xn({message:"Default connection profile name:",default:"berlin"}),c=await Xn({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),p={projectId:o,docsDir:ul,captureDir:r,outputDir:s,profiles:{[i]:{connection:{environment:c},production:!1}},defaultProfile:i,authoritativeSourceFiles:gl(e)},h=bf(e);h?.terminologyGlossary&&(p.terminologyGlossary=h.terminologyGlossary),ll(p,e),fl(e);let b=yn(e);console.log(""),console.log(U(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${W(`d360-writer login --profile ${i}`)} ${g("(sign in; project & workspace auto-selected)")}`),console.log("");for(let $ of wn(b))console.log($);return console.log(""),console.log(`${g("Then ask:")} ${W('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function ml(e){let t=lr(e,"package.json");if(!kn(t))return null;try{return JSON.parse(yf(t,"utf8")).name??null}catch{return null}}function gl(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])kn(lr(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=lr(e,n);kn(o)&&!vf(o)&&t.push(n)}return t}function vf(e){try{return wf(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var dr=Vn(()=>{"use strict";K();wt()});import{createRequire as qf}from"node:module";import{existsSync as Vf,readFileSync as Gf}from"node:fs";import{dirname as Ml,join as Ul}from"node:path";function vn(){let e;try{e=Yf.resolve("document360-capture/helpers")}catch{return null}let t=Ml(e);for(let n=0;n<5&&!Vf(Ul(t,"package.json"));n++)t=Ml(t);try{let n=JSON.parse(Gf(Ul(t,"package.json"),"utf8"));return n.name==="document360-capture"&&n.version?n.version:null}catch{return null}}var Yf,fr=Vn(()=>{"use strict";Yf=qf(import.meta.url)});var cu={};Dc(cu,{doctorCommand:()=>co,renderDoctorChecks:()=>au,runDoctorChecks:()=>iu});import{existsSync as sy}from"node:fs";import{d360GetAll as iy,getAccessToken as ay,isExpired as Ji,loadProfileMap as cy,loadTokens as ly,packageSkillsDir as ru,ENGINE_VERSION as dy,projectConfigPath as uy,readProjectConfig as py,DEFAULT_DOCS_DIR as hy,fetchManifestSummary as fy,resolveActiveProfile as my,classifyClaudeAuth as gy,CLAUDE_CODE_SETUP_HINT as su,resolveModelSetting as yy,probeModel as wy,detectAppType as ky,playbookSkillName as by,D360AuthError as $y,applyStructureOrder as vy}from"document360-engine";async function iu(e,t){let n=[],o=vn();n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${dy}${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=gy();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. ${su}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:su});let i=yy(e);if(n.push({level:"ok",label:`Model: ${i.model} (${i.source==="auto"?"auto \u2014 right-sized for docs; /model to change":i.source})`}),s.state==="ready"){let C=await wy(e,i.model??void 0);C.ok?n.push({level:"ok",label:`Model reachable \u2014 replied in ${(C.latencyMs/1e3).toFixed(1)}s`}):C.timedOut?n.push({level:"fail",label:"Model unreachable \u2014 no response in 30s (a docs turn will hang, then end with 0 tokens / no output)",fix:`Usually a corporate proxy/firewall or org policy blocking the Claude model API. Check this machine's network access to the Claude endpoint; confirm with: claude -p "say hi"`}):n.push({level:"fail",label:`Model call failed \u2014 ${C.error??"no output"} (a docs turn will end with 0 tokens / no output)`,fix:'Check sign-in, the selected model (/model), and network access to the Claude endpoint; confirm with: claude -p "say hi"'})}let c=py(e);if(!c)return n.push({level:"fail",label:`No ${uy(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${c.projectId}`});let p=(c.docsDir??hy).replace(/\/+$/,"");n.push(c.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 ${p}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let h=c.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 b=c.appType??ky(e);if(b){let C=c.appType?"from config":"auto-detected",P=b==="web"||b==="cli";n.push({level:"ok",label:`Genre: ${b} (${C})${P?` \u2192 ${by(b)} 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 $;try{$=my(e),n.push({level:"ok",label:`Profile: ${$.name} (${$.connection.name})${$.production?" \u26A0 PRODUCTION":""}`})}catch(C){return n.push({level:"fail",label:`Profile config: ${C.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let v=ly($.name);v?Ji(v)&&!v.refreshToken?n.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):Ji(v)?n.push({level:"warn",label:"Document360: token expired \u2014 will auto-refresh on next call"}):n.push({level:"ok",label:`Document360: logged in (until ${new Date(v.expiresAt).toLocaleString()})`}):n.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${$.name})`}),n.push($.project.workspaceId?{level:"ok",label:`Workspace: ${$.project.workspaceName??$.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let A=cy(e,$.name);A?A.projectId&&$.project.projectId&&A.projectId!==$.project.projectId?n.push({level:"fail",label:`Category map projectId (${A.projectId}) \u2260 profile projectId (${$.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):n.push({level:"ok",label:`Category map: ${Object.keys(A.articles).length} articles, ${Object.keys(A.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${$.name}" (created on first /publish)`}),n.push(sy(ru())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${ru()}`,fix:"Reinstall document360-writer (broken install)"});let R=qe(e);if(R.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${ge})`}):R.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${R.completedVersion}, current is v${ge}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),v&&(!Ji(v)||v.refreshToken)){let C={profile:$.name,connection:$.connection};try{await ay(C);let I=await iy(C,"/v3/projects");n.push({level:"ok",label:`API reachable (${$.connection.apiUrl}) \u2014 ${I.length} project(s) visible`})}catch(I){n.push({level:"fail",label:`API call failed: ${I.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let P=A?.projectId??$.project.projectId;if(P&&$.project.workspaceId){try{let I=await fy(C,P,$.project.workspaceId);if(I){let Y=(I.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Workspace sync manifest: available on ${$.connection.name} (${I.languages?.length??0} language${(I.languages?.length??0)===1?"":"s"}) \xB7 hash ${Y||"(none)"}`})}else n.push({level:"warn",label:`Workspace sync manifest: not live on ${$.connection.name} yet`,fix:"No action needed \u2014 sync uses the per-article path until the manifest ships on this environment"})}catch(I){I instanceof $y||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(I.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${$.project.projectName??P})`,fix:"Run /login and pick this repo's project \u2014 your token is scoped to another project"}):n.push({level:"warn",label:`Workspace sync manifest: probe failed (${I.message.slice(0,80)})`})}try{let I=await vy({cwd:e,profileName:$.name,dryRun:!0}),Y=I.categoriesReordered+I.articlesReordered;if(I.skipped)n.push({level:"warn",label:`Reading order: can't be checked (${I.skipped})`,fix:"Your article order on Document360 may not match your structure \u2014 /publish syncs it once this resolves"});else if(I.unverified)n.push({level:"warn",label:`Reading order: ${I.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(Y>0){let V=[I.categoriesReordered>0?`${I.categoriesReordered} categor${I.categoriesReordered===1?"y":"ies"}`:"",I.articlesReordered>0?`${I.articlesReordered} article${I.articlesReordered===1?"":"s"}`:""].filter(Boolean);n.push({level:"warn",label:`Reading order: ${V.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(I){n.push({level:"warn",label:`Reading order: check failed (${I.message.slice(0,80)})`})}}}return n}function au(e){let t=[""];for(let r of e){let s=r.level==="ok"?U("\u2713"):r.level==="warn"?H("\u26A0"):E("\u2717");t.push(` ${s} ${r.label}${r.detail?g(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${g("fix:")} ${W(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?U(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):E(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function co(e,t){console.log(g("Running checks\u2026"));for(let n of au(await iu(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var Mr=Vn(()=>{"use strict";wt();K();fr()});import{Command as Zb}from"commander";import{createRequire as e$}from"node:module";import{AUTH_MODES as t$}from"document360-engine";import{input as Lh}from"@inquirer/prompts";import{loginPkce as _h,refreshTokens as Mh,toStoredTokens as _c,clearTokens as Uh,decodeJwtClaims as Lc,isExpired as Fh,loadTokens as Wh,saveTokens as Mc,resolveActiveProfile as Qo,setProfileProject as Bh,readProjectConfig as Hh}from"document360-engine";K();import{select as xh}from"@inquirer/prompts";import{resolveActiveProfile as Ch,setProfileProject as Rh,resolveProjectId as Sh,listWorkspaces as Ph}from"document360-engine";async function Yn(e,t){let n=Ch(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Sh(o);return{workspaces:await Ph(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var jc=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function Ns(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 zo(e,t,n,o,r){Rh(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function Nc(e,t,n){let o;try{o=await Yn(e,n)}catch(s){return console.log(E(`Could not list workspaces: ${s.message}`)),1}let r=Ns(o.workspaces,t);return r?(zo(e,o.profile,o.projectId,r.id,r.name),console.log(U(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(E(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function fn(e,t){let n;try{n=await Yn(e,t)}catch(h){console.log(E(`Could not list workspaces: ${h.message}`));return}let{workspaces:o,projectId:r,profile:s,current:i}=n;if(o.length===0){console.log(g("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let h of o)console.log(` ${h.id===i?W("\u25CF"):" "} ${jc(h)} ${g(h.id)}`);console.log(g("Run: d360-writer workspace use <name>"));return}let c=await xh({message:"Select the Document360 workspace for this repo:",choices:o.map(h=>({name:`${jc(h)}${h.id===i?" (current)":""}`,value:h.id}))}),p=o.find(h=>h.id===c);zo(e,s,r,c,p?.name),console.log(U(`\u2713 Workspace set to "${p?.name??c}" for profile "${s}".`))}K();import{select as Th}from"@inquirer/prompts";import{resolveActiveProfile as Eh,setProfileProject as Dh,listProjects as Ah}from"document360-engine";async function gt(e,t){let n=Eh(e,t),o={profile:n.name,connection:n.connection};return{projects:await Ah(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var Ic=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Is(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 Ko(e,t,n,o){Dh(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function Oc(e,t,n){let o;try{o=await gt(e,n)}catch(s){return console.log(E(`Could not list projects: ${s.message}`)),1}let r=Is(o.projects,t);return r?(Ko(e,o.profile,r.id,r.name),console.log(U(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log(E(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function Xo(e,t){let n;try{n=await gt(e,t)}catch(p){console.log(E(`Could not list projects: ${p.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(g("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let p of o)console.log(` ${p.id===s?W("\u25CF"):" "} ${Ic(p)} ${g(p.id)}`);console.log(g("Run: d360-writer project use <name>"));return}let i=await Th({message:"Select the Document360 project for this repo:",choices:o.map(p=>({name:`${Ic(p)}${p.id===s?" (current)":""}`,value:p.id}))}),c=o.find(p=>p.id===i);Ko(e,r,i,c?.name),console.log(U(`\u2713 Project set to "${c?.name??i}" for profile "${r}". Next: pick a workspace.`))}K();import jh from"picocolors";function Nh(e=process.env){return e.FORCE_HYPERLINK==="0"||!jh.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 Ih(e,t=e,n){return Nh(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Oh=/https?:\/\/[^\s\x1b]+/g;function zn(e,t){return e.replace(Oh,n=>Ih(n,n,t))}function Uc(e){return{...Lc(e.idToken)??{},...Lc(e.accessToken)??{}}}function Jo(e){let t=Uc(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 Zo(e){let t=Qo(process.cwd(),e.profile),n=t.connection;console.log(g(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=await _h(n,{manual:e.manual,promptForRedirect:s=>Lh({message:s})},s=>console.log(zn(s))),r=_c(t.name,o);if(Mc(r),await Os(r,t.name,s=>console.log(g(s))),console.log(""),console.log(U(`\u2713 Logged in to "${t.name}" as ${Jo(r)}`)),console.log(g(` access token expires: ${r.expiresAt}`)),console.log(g(` refresh token: ${r.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{Hh(process.cwd())?.profiles?.[t.name]&&(console.log(""),await fn(process.cwd(),t.name))}catch{}}async function Os(e,t,n){let r=Uc(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Qo(process.cwd(),t).project.projectId)return;let i;try{let{projects:c}=await gt(process.cwd(),t);i=c.find(p=>p.id===r)?.name}catch{}Bh(process.cwd(),t,{projectId:r,projectName:i}),n(` Project "${i??r}" written to profile "${t}".`)}catch{}}async function Fc(e){let t=Qo(process.cwd(),e.profile),n=t.connection,o=Wh(t.name);if(!o){console.log(E(`Not logged in to Document360 (profile "${t.name}").`)),console.log(g(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${W(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Jo(o)}`),Fh(o))if(o.refreshToken)try{let r=_c(t.name,await Mh(n,o.refreshToken));Mc(r),console.log(U(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(H(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(g(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(H("Session expired (no refresh token).")),console.log(g(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(g(` expires: ${o.expiresAt}`))}async function Wc(e){let t=Qo(process.cwd(),e.profile);Uh(t.name)?console.log(U(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(g(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}K();import{readProjectConfig as Bc,writeProjectConfig as qh,resolveActiveProfile as Vh,loadTokens as Gh,isExpired as Yh}from"document360-engine";function er(e){let t=Bc(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(E("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?W("\u25CF "):" ",s=o.production?H(" \u26A0 PRODUCTION"):"",i=o.connection.environment??"(inline)",c=Gh(n),p=c?Yh(c)&&!c.refreshToken?H("expired"):g("logged in"):g("not logged in");console.log(`${r}${W(n)} \u2192 ${i}${s} [${p}]`)}console.log(""),console.log(g("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function tr(e,t){let n=Bc(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(E(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,qh(n,e);let o=n.profiles[t].production?H(" \u26A0 PRODUCTION"):"";console.log(U(`\u2713 Default profile is now "${t}"${o}`))}function nr(e,t){try{let n=Vh(e,t);console.log(""),console.log(`Profile ${W(n.name)}${n.production?H(" \u26A0 PRODUCTION"):""}`),console.log(g(` api: ${n.connection.apiUrl}`)),console.log(g(` identity: ${n.connection.authorizationUrl}`)),console.log(g(` clientId: ${n.connection.clientId}`)),console.log(g(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(g(` project: ${n.project.projectId??"(set at login)"}`)),console.log(g(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(E(n.message)),process.exitCode=1}}K();import{existsSync as zh,readdirSync as Kh,statSync as Hc}from"node:fs";import{join as qc}from"node:path";import{apiLogDir as Xh}from"document360-engine";function Vc(){let e=Xh();if(console.log(""),console.log(`Document360 API logs: ${W(e)}`),!zh(e)){console.log(g(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Kh(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(g(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let s=(Hc(qc(e,r)).size/1024).toFixed(1);console.log(` ${r} ${g(`${s} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${g("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let s=(Hc(qc(e,r)).size/1024).toFixed(1);console.log(` ${E(r)} ${g(`${s} KB`)}`)}}console.log(""),console.log(g("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(g("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}K();import{createSession as Qh,resolveAuth as Jh,findByName as Zh,slugify as ef,touchSession as tf,upsertSession as nf,resolveActiveProfile as of}from"document360-engine";async function Gc(e,t,n,o,r,s){let i=Jh(n);i.kind==="none"&&(console.error(""),console.error(E("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${W("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${W("d360-writer --auth subscription")}`),process.exit(2)),i.kind==="subscription"&&console.error(g("Using your Claude subscription (no API key set)."));let c=null;try{c=of(e,r)}catch(v){console.error(E(`Document360 profile error: ${v.message}`)),process.exit(2)}c.production&&(console.error(H(`\u26A0 Profile "${c.name}" is PRODUCTION.`)),s||(console.error(E("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(g(" --yes given \u2014 proceeding against production.")));let p;if(o){let v=Zh(e,o);v||(console.error(E(`No saved session matches "${o}" in this repo.`)),console.error(g("List sessions inside the REPL with /resume.")),process.exit(2)),p=v.uuid,console.error(g(`Resuming "${v.name}"`))}let h=Qh({cwd:e,resume:p,profileName:r,allowProdWrites:s===!0}),b=p??null,$=1;for await(let v of h.send(t))switch(v.type){case"session":if(!b){b=v.sessionId;let A=new Date().toISOString();nf({uuid:b,name:ef(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:A,updatedAt:A})}break;case"text":process.stdout.write(v.delta);break;case"tool":console.error(me(` \u2699 ${v.name}`));break;case"result":$=v.ok?0:1,console.error(g(`(${v.inputTokens}\u2192${v.outputTokens} tokens`+(v.costUsd>0?`, $${v.costUsd<.01?v.costUsd.toFixed(4):v.costUsd.toFixed(2)}`:"")+")")),v.ok||console.error(E("agent finished with an error result"));break;case"error":console.error(""),console.error(E(`agent error: ${v.message}`)),process.exit(1)}b&&tf(b),process.stdout.write(`
|
|
280
|
-
`),process.exit($)}import{createInterface as
|
|
281
|
-
`)}var He=[{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"}]},{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 --publish",s:"Analyze the latest code changes, read the notes left by your coding agent, update the documentation, and publish the changes."},{t:"dim",s:" (or run /catch-up to review drafts first, then /publish when you're ready)"},{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:"/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."}]},{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 goes live)."},{t:"cmd",name:"/publish",s:"Publish to Document360 (--all or a path)."},{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)."},{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:"/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."}]}],Yc=24;function Ls(e){let t=e.filter(n=>n.t==="cmd").map(n=>n.name.length);return t.length===0?Yc:Math.min(Yc,Math.max(...t))}function _s(e,t,n,o){let r=" ".repeat(2+n+1),s=Math.max(24,o-r.length-2),i=Bt(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 rf(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=_s(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(`
|
|
282
|
-
`)}case"gap":return""}}function
|
|
278
|
+
`;oc="Re-run dev\u2194docs onboarding (protocol v"});var wc={};Al(wc,{initCommand:()=>Ys,scaffoldInit:()=>Gs});import{input as Qn,confirm as yf}from"@inquirer/prompts";import{basename as cc,join as ur}from"node:path";import{existsSync as bn,readFileSync as wf,readdirSync as kf,writeFileSync as bf}from"node:fs";import{writeProjectConfig as dc,readProjectConfig as $f,projectConfigPath as uc,writerDir as vf,DEFAULT_DOCS_DIR as pc,DEFAULT_CAPTURE_DIR as hc,DEFAULT_OUTPUT_DIR as fc}from"document360-engine";function Gs(e,t="berlin"){let n=uc(e);if(bn(n))return{created:!1,path:n,profileName:""};let o={projectId:gc(e)??cc(e),docsDir:pc,captureDir:hc,outputDir:fc,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:yc(e)};return dc(o,e),mc(e),{created:!0,path:n,profileName:t}}function mc(e){let t=ur(vf(e),".gitignore");bn(t)||bf(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
|
|
279
|
+
`),"utf8")}async function Ys(){let e=process.cwd(),t=uc(e);if(bn(t)&&!await yf({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(g("init cancelled.")),{kind:"continue"};let n=gc(e)??cc(e),o=await Qn({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await Qn({message:"Capture directory (where document360-capture .spec.ts files live):",default:hc}),s=await Qn({message:"Screenshot output directory:",default:fc}),i=await Qn({message:"Default connection profile name:",default:"berlin"}),l=await Qn({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),p={projectId:o,docsDir:pc,captureDir:r,outputDir:s,profiles:{[i]:{connection:{environment:l},production:!1}},defaultProfile:i,authoritativeSourceFiles:yc(e)},h=$f(e);h?.terminologyGlossary&&(p.terminologyGlossary=h.terminologyGlossary),dc(p,e),mc(e);let b=wn(e);console.log(""),console.log(U(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${W(`d360-writer login --profile ${i}`)} ${g("(sign in; project & workspace auto-selected)")}`),console.log("");for(let $ of kn(b))console.log($);return console.log(""),console.log(`${g("Then ask:")} ${W('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function gc(e){let t=ur(e,"package.json");if(!bn(t))return null;try{return JSON.parse(wf(t,"utf8")).name??null}catch{return null}}function yc(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])bn(ur(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=ur(e,n);bn(o)&&!xf(o)&&t.push(n)}return t}function xf(e){try{return kf(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var pr=Gn(()=>{"use strict";X();wt()});import{createRequire as Vf}from"node:module";import{existsSync as Gf,readFileSync as Yf}from"node:fs";import{dirname as Uc,join as Fc}from"node:path";function xn(){let e;try{e=zf.resolve("document360-capture/helpers")}catch{return null}let t=Uc(e);for(let n=0;n<5&&!Gf(Fc(t,"package.json"));n++)t=Uc(t);try{let n=JSON.parse(Yf(Fc(t,"package.json"),"utf8"));return n.name==="document360-capture"&&n.version?n.version:null}catch{return null}}var zf,gr=Gn(()=>{"use strict";zf=Vf(import.meta.url)});var cu={};Al(cu,{doctorCommand:()=>co,renderDoctorChecks:()=>lu,runDoctorChecks:()=>au});import{existsSync as iy}from"node:fs";import{d360GetAll as ay,getAccessToken as ly,isExpired as ta,loadProfileMap as cy,loadTokens as dy,packageSkillsDir as su,ENGINE_VERSION as uy,projectConfigPath as py,readProjectConfig as hy,DEFAULT_DOCS_DIR as fy,fetchManifestSummary as my,resolveActiveProfile as gy,classifyClaudeAuth as yy,CLAUDE_CODE_SETUP_HINT as iu,resolveModelSetting as wy,probeModel as ky,detectAppType as by,playbookSkillName as $y,D360AuthError as vy,applyStructureOrder as xy}from"document360-engine";async function au(e,t){let n=[],o=xn();n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${uy}${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=yy();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. ${iu}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:iu});let i=wy(e);if(n.push({level:"ok",label:`Model: ${i.model} (${i.source==="auto"?"auto \u2014 right-sized for docs; /model to change":i.source})`}),s.state==="ready"){let C=await ky(e,i.model??void 0);C.ok?n.push({level:"ok",label:`Model reachable \u2014 replied in ${(C.latencyMs/1e3).toFixed(1)}s`}):C.timedOut?n.push({level:"fail",label:"Model unreachable \u2014 no response in 30s (a docs turn will hang, then end with 0 tokens / no output)",fix:`Usually a corporate proxy/firewall or org policy blocking the Claude model API. Check this machine's network access to the Claude endpoint; confirm with: claude -p "say hi"`}):n.push({level:"fail",label:`Model call failed \u2014 ${C.error??"no output"} (a docs turn will end with 0 tokens / no output)`,fix:'Check sign-in, the selected model (/model), and network access to the Claude endpoint; confirm with: claude -p "say hi"'})}let l=hy(e);if(!l)return n.push({level:"fail",label:`No ${py(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${l.projectId}`});let p=(l.docsDir??fy).replace(/\/+$/,"");n.push(l.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 ${p}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let h=l.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 b=l.appType??by(e);if(b){let C=l.appType?"from config":"auto-detected",T=b==="web"||b==="cli";n.push({level:"ok",label:`Genre: ${b} (${C})${T?` \u2192 ${$y(b)} 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 $;try{$=gy(e),n.push({level:"ok",label:`Profile: ${$.name} (${$.connection.name})${$.production?" \u26A0 PRODUCTION":""}`})}catch(C){return n.push({level:"fail",label:`Profile config: ${C.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let v=dy($.name);v?ta(v)&&!v.refreshToken?n.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):ta(v)?n.push({level:"warn",label:"Document360: token expired \u2014 will auto-refresh on next call"}):n.push({level:"ok",label:`Document360: logged in (until ${new Date(v.expiresAt).toLocaleString()})`}):n.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${$.name})`}),n.push($.project.workspaceId?{level:"ok",label:`Workspace: ${$.project.workspaceName??$.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let E=cy(e,$.name);E?E.projectId&&$.project.projectId&&E.projectId!==$.project.projectId?n.push({level:"fail",label:`Category map projectId (${E.projectId}) \u2260 profile projectId (${$.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(E.articles).length} articles, ${Object.keys(E.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${$.name}" (created on first /publish)`}),n.push(iy(su())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${su()}`,fix:"Reinstall document360-writer (broken install)"});let R=Ge(e);if(R.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${me})`}):R.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${R.completedVersion}, current is v${me}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),v&&(!ta(v)||v.refreshToken)){let C={profile:$.name,connection:$.connection};try{await ly(C);let I=await ay(C,"/v3/projects");n.push({level:"ok",label:`API reachable (${$.connection.apiUrl}) \u2014 ${I.length} project(s) visible`})}catch(I){n.push({level:"fail",label:`API call failed: ${I.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let T=E?.projectId??$.project.projectId;if(T&&$.project.workspaceId){try{let I=await my(C,T,$.project.workspaceId);if(I){let z=(I.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Workspace sync manifest: available on ${$.connection.name} (${I.languages?.length??0} language${(I.languages?.length??0)===1?"":"s"}) \xB7 hash ${z||"(none)"}`})}else n.push({level:"warn",label:`Workspace sync manifest: not live on ${$.connection.name} yet`,fix:"No action needed \u2014 sync uses the per-article path until the manifest ships on this environment"})}catch(I){I instanceof vy||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(I.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${$.project.projectName??T})`,fix:"Run /login and pick this repo's project \u2014 your token is scoped to another project"}):n.push({level:"warn",label:`Workspace sync manifest: probe failed (${I.message.slice(0,80)})`})}try{let I=await xy({cwd:e,profileName:$.name,dryRun:!0}),z=I.categoriesReordered+I.articlesReordered;if(I.skipped)n.push({level:"warn",label:`Reading order: can't be checked (${I.skipped})`,fix:"Your article order on Document360 may not match your structure \u2014 /publish syncs it once this resolves"});else if(I.unverified)n.push({level:"warn",label:`Reading order: ${I.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(z>0){let V=[I.categoriesReordered>0?`${I.categoriesReordered} categor${I.categoriesReordered===1?"y":"ies"}`:"",I.articlesReordered>0?`${I.articlesReordered} article${I.articlesReordered===1?"":"s"}`:""].filter(Boolean);n.push({level:"warn",label:`Reading order: ${V.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(I){n.push({level:"warn",label:`Reading order: check failed (${I.message.slice(0,80)})`})}}}return n}function lu(e){let t=[""];for(let r of e){let s=r.level==="ok"?U("\u2713"):r.level==="warn"?H("\u26A0"):A("\u2717");t.push(` ${s} ${r.label}${r.detail?g(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${g("fix:")} ${W(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?U(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):A(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function co(e,t){console.log(g("Running checks\u2026"));for(let n of lu(await au(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var Fr=Gn(()=>{"use strict";wt();X();gr()});import{Command as e$}from"commander";import{createRequire as t$}from"node:module";import{AUTH_MODES as n$}from"document360-engine";import{input as _h}from"@inquirer/prompts";import{loginPkce as Mh,refreshTokens as Uh,toStoredTokens as Ml,clearTokens as Fh,decodeJwtClaims as _l,isExpired as Wh,loadTokens as Bh,saveTokens as Ul,resolveActiveProfile as Zo,setProfileProject as Hh,readProjectConfig as qh}from"document360-engine";X();import{select as Ch}from"@inquirer/prompts";import{resolveActiveProfile as Rh,setProfileProject as Sh,resolveProjectId as Ph,listWorkspaces as Th}from"document360-engine";async function zn(e,t){let n=Rh(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Ph(o);return{workspaces:await Th(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var Nl=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function Ls(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 Xo(e,t,n,o,r){Sh(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function Il(e,t,n){let o;try{o=await zn(e,n)}catch(s){return console.log(A(`Could not list workspaces: ${s.message}`)),1}let r=Ls(o.workspaces,t);return r?(Xo(e,o.profile,o.projectId,r.id,r.name),console.log(U(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(A(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function mn(e,t){let n;try{n=await zn(e,t)}catch(h){console.log(A(`Could not list workspaces: ${h.message}`));return}let{workspaces:o,projectId:r,profile:s,current:i}=n;if(o.length===0){console.log(g("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let h of o)console.log(` ${h.id===i?W("\u25CF"):" "} ${Nl(h)} ${g(h.id)}`);console.log(g("Run: d360-writer workspace use <name>"));return}let l=await Ch({message:"Select the Document360 workspace for this repo:",choices:o.map(h=>({name:`${Nl(h)}${h.id===i?" (current)":""}`,value:h.id}))}),p=o.find(h=>h.id===l);Xo(e,s,r,l,p?.name),console.log(U(`\u2713 Workspace set to "${p?.name??l}" for profile "${s}".`))}X();import{select as Dh}from"@inquirer/prompts";import{resolveActiveProfile as Eh,setProfileProject as Ah,listProjects as jh}from"document360-engine";async function gt(e,t){let n=Eh(e,t),o={profile:n.name,connection:n.connection};return{projects:await jh(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var Ol=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function _s(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 Qo(e,t,n,o){Ah(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function Ll(e,t,n){let o;try{o=await gt(e,n)}catch(s){return console.log(A(`Could not list projects: ${s.message}`)),1}let r=_s(o.projects,t);return r?(Qo(e,o.profile,r.id,r.name),console.log(U(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log(A(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function Jo(e,t){let n;try{n=await gt(e,t)}catch(p){console.log(A(`Could not list projects: ${p.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(g("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let p of o)console.log(` ${p.id===s?W("\u25CF"):" "} ${Ol(p)} ${g(p.id)}`);console.log(g("Run: d360-writer project use <name>"));return}let i=await Dh({message:"Select the Document360 project for this repo:",choices:o.map(p=>({name:`${Ol(p)}${p.id===s?" (current)":""}`,value:p.id}))}),l=o.find(p=>p.id===i);Qo(e,r,i,l?.name),console.log(U(`\u2713 Project set to "${l?.name??i}" for profile "${r}". Next: pick a workspace.`))}X();import Nh from"picocolors";function Ih(e=process.env){return e.FORCE_HYPERLINK==="0"||!Nh.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 Oh(e,t=e,n){return Ih(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Lh=/https?:\/\/[^\s\x1b]+/g;function Kn(e,t){return e.replace(Lh,n=>Oh(n,n,t))}function Fl(e){return{..._l(e.idToken)??{},..._l(e.accessToken)??{}}}function er(e){let t=Fl(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 tr(e){let t=Zo(process.cwd(),e.profile),n=t.connection;console.log(g(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=await Mh(n,{manual:e.manual,promptForRedirect:s=>_h({message:s})},s=>console.log(Kn(s))),r=Ml(t.name,o);if(Ul(r),await Ms(r,t.name,s=>console.log(g(s))),console.log(""),console.log(U(`\u2713 Logged in to "${t.name}" as ${er(r)}`)),console.log(g(` access token expires: ${r.expiresAt}`)),console.log(g(` refresh token: ${r.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{qh(process.cwd())?.profiles?.[t.name]&&(console.log(""),await mn(process.cwd(),t.name))}catch{}}async function Ms(e,t,n){let r=Fl(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Zo(process.cwd(),t).project.projectId)return;let i;try{let{projects:l}=await gt(process.cwd(),t);i=l.find(p=>p.id===r)?.name}catch{}Hh(process.cwd(),t,{projectId:r,projectName:i}),n(` Project "${i??r}" written to profile "${t}".`)}catch{}}async function Wl(e){let t=Zo(process.cwd(),e.profile),n=t.connection,o=Bh(t.name);if(!o){console.log(A(`Not logged in to Document360 (profile "${t.name}").`)),console.log(g(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${W(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${er(o)}`),Wh(o))if(o.refreshToken)try{let r=Ml(t.name,await Uh(n,o.refreshToken));Ul(r),console.log(U(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(H(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(g(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(H("Session expired (no refresh token).")),console.log(g(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(g(` expires: ${o.expiresAt}`))}async function Bl(e){let t=Zo(process.cwd(),e.profile);Fh(t.name)?console.log(U(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(g(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}X();import{readProjectConfig as Hl,writeProjectConfig as Vh,resolveActiveProfile as Gh,loadTokens as Yh,isExpired as zh}from"document360-engine";function nr(e){let t=Hl(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(A("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?W("\u25CF "):" ",s=o.production?H(" \u26A0 PRODUCTION"):"",i=o.connection.environment??"(inline)",l=Yh(n),p=l?zh(l)&&!l.refreshToken?H("expired"):g("logged in"):g("not logged in");console.log(`${r}${W(n)} \u2192 ${i}${s} [${p}]`)}console.log(""),console.log(g("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function or(e,t){let n=Hl(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(A(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,Vh(n,e);let o=n.profiles[t].production?H(" \u26A0 PRODUCTION"):"";console.log(U(`\u2713 Default profile is now "${t}"${o}`))}function rr(e,t){try{let n=Gh(e,t);console.log(""),console.log(`Profile ${W(n.name)}${n.production?H(" \u26A0 PRODUCTION"):""}`),console.log(g(` api: ${n.connection.apiUrl}`)),console.log(g(` identity: ${n.connection.authorizationUrl}`)),console.log(g(` clientId: ${n.connection.clientId}`)),console.log(g(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(g(` project: ${n.project.projectId??"(set at login)"}`)),console.log(g(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(A(n.message)),process.exitCode=1}}X();import{existsSync as Kh,readdirSync as Xh,statSync as ql}from"node:fs";import{join as Vl}from"node:path";import{apiLogDir as Qh}from"document360-engine";function Gl(){let e=Qh();if(console.log(""),console.log(`Document360 API logs: ${W(e)}`),!Kh(e)){console.log(g(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Xh(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(g(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let s=(ql(Vl(e,r)).size/1024).toFixed(1);console.log(` ${r} ${g(`${s} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${g("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let s=(ql(Vl(e,r)).size/1024).toFixed(1);console.log(` ${A(r)} ${g(`${s} KB`)}`)}}console.log(""),console.log(g("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(g("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}X();import{createSession as Jh,resolveAuth as Zh,findByName as ef,slugify as tf,touchSession as nf,upsertSession as of,resolveActiveProfile as rf}from"document360-engine";async function Yl(e,t,n,o,r,s){let i=Zh(n);i.kind==="none"&&(console.error(""),console.error(A("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${W("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${W("d360-writer --auth subscription")}`),process.exit(2)),i.kind==="subscription"&&console.error(g("Using your Claude subscription (no API key set)."));let l=null;try{l=rf(e,r)}catch(v){console.error(A(`Document360 profile error: ${v.message}`)),process.exit(2)}l.production&&(console.error(H(`\u26A0 Profile "${l.name}" is PRODUCTION.`)),s||(console.error(A("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(g(" --yes given \u2014 proceeding against production.")));let p;if(o){let v=ef(e,o);v||(console.error(A(`No saved session matches "${o}" in this repo.`)),console.error(g("List sessions inside the REPL with /resume.")),process.exit(2)),p=v.uuid,console.error(g(`Resuming "${v.name}"`))}let h=Jh({cwd:e,resume:p,profileName:r,allowProdWrites:s===!0}),b=p??null,$=1;for await(let v of h.send(t))switch(v.type){case"session":if(!b){b=v.sessionId;let E=new Date().toISOString();of({uuid:b,name:tf(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:E,updatedAt:E})}break;case"text":process.stdout.write(v.delta);break;case"tool":console.error(fe(` \u2699 ${v.name}`));break;case"result":$=v.ok?0:1,console.error(g(`(${v.inputTokens}\u2192${v.outputTokens} tokens`+(v.costUsd>0?`, $${v.costUsd<.01?v.costUsd.toFixed(4):v.costUsd.toFixed(2)}`:"")+")")),v.ok||console.error(A("agent finished with an error result"));break;case"error":console.error(""),console.error(A(`agent error: ${v.message}`)),process.exit(1)}b&&nf(b),process.stdout.write(`
|
|
280
|
+
`),process.exit($)}import{createInterface as ak}from"node:readline/promises";import{createSession as Ua,resolveAuth as lk,getSession as ck,setTitle as dk,slugify as uk,touchSession as up,upsertSession as pk,generateTitle as hk,resolveActiveProfile as pp,resolveModelSetting as fk,readProjectConfig as mk,resolveAndPersistAppType as gk,decodeJwtClaims as dp,isExpired as yk,loadTokens as wk,isDirectiveMention as kk,stripDirectiveMention as bk,appendDirective as $k,reconcileUpgradeActions as vk,stampArticles as xk,listArticleFiles as Ck,CONTENT_CAP_VERSION as Rk,applyStructureOrder as Sk,orderSyncLine as Pk}from"document360-engine";import{ENGINE_VERSION as af}from"document360-engine";function Ht(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 sr(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 l of Ht(`${i+1}. ${s.feature}`,76))o.push(n(l));o.push(n());for(let l of Ht(s.why,73))o.push(n(` ${l}`));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 ir(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(`
|
|
281
|
+
`)}var Ve=[{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 --publish",s:"Analyze the latest code changes, read the notes left by your coding agent, update the documentation, and publish the changes."},{t:"dim",s:" (or run /catch-up to review drafts first, then /publish when you're ready)"},{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:"/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."}]},{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 goes live)."},{t:"cmd",name:"/publish",s:"Publish to Document360 (--all or a path)."},{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)."},{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:"/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."}]}],zl=24;function Us(e){let t=e.filter(n=>n.t==="cmd").map(n=>n.name.length);return t.length===0?zl:Math.min(zl,Math.max(...t))}function Fs(e,t,n,o){let r=" ".repeat(2+n+1),s=Math.max(24,o-r.length-2),i=Ht(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 sf(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=Fs(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(`
|
|
282
|
+
`)}case"gap":return""}}function Kl(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 Ve){n.push(`\u2500\u2500 ${o.label} \u2500\u2500`,"");let r=Us(o.rows);for(let s of o.rows)n.push(sf(s,r,100));n.push("")}return n.push("Tip: anything not starting with / goes to the agent."),n}async function Ws(e=[],t){console.log("");let n=t?.version?{version:t.version,engineVersion:af}:void 0;for(let o of Kl(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"}}X();import{getSession as lf}from"document360-engine";async function Xl(e,t){let n=t.currentUuid(),o=n?lf(n):void 0;return console.log(o?g(`
|
|
283
283
|
(conversation reset \u2014 "${o.name}" is still available via /resume)
|
|
284
284
|
`):g(`
|
|
285
285
|
(conversation reset \u2014 agent will start fresh on the next prompt)
|
|
286
|
-
`)),{kind:"clear"}}async function
|
|
286
|
+
`)),{kind:"clear"}}async function Bs(){return{kind:"exit"}}pr();X();import{readMcpConfig as zs,writeMcpConfig as kc}from"document360-engine";async function hr(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(Cf(),{kind:"continue"}):t==="add"?(Rf(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(Sf(e.slice(1)),{kind:"continue"}):(console.log(A(`Unknown /mcp subcommand: ${t}`)),console.log(g("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function Cf(){let e=zs(),t=Object.keys(e.servers);if(t.length===0){console.log(g(`
|
|
287
287
|
No MCP servers registered. Add one with /mcp add <name> <type> <ref>
|
|
288
|
-
`));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(` ${W(n)} ${g("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?g(` [headers: ${r.join(", ")}]`):"";console.log(` ${W(n)} ${g(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function Cf(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(E("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(E(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=Vs(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let i={};for(let c=1;c<o.length;c++)if(o[c]==="-H"||o[c]==="--header"){let p=o[++c],h=p?.match(/^([^:=]+)[:=](.+)$/);if(!h){console.log(E(`-H expects key:value (no spaces). Got: ${p??"(nothing)"}`));return}i[h[1].trim()]=h[2].trim()}else{console.log(E(`Unexpected argument: ${o[c]}. 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,wl(r),console.log(""),console.log(U(`\u2713 Registered "${t}" (${n})`)),console.log(H(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(g(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function Rf(e){let t=e[0];if(!t){console.log(E("Usage: /mcp remove <name>"));return}let n=Vs();if(!n.servers[t]){console.log(E(`No server named "${t}".`));return}delete n.servers[t],wl(n),console.log(U(`\u2713 Removed "${t}".`)),console.log(g(" Run /clear to drop it from the current session immediately."))}K();import{readFileSync as Nm}from"node:fs";import{join as Im}from"node:path";import{select as Om}from"@inquirer/prompts";import{computeSyncStatus as Pr,planPartitions as Lm,relatedArticlePaths as _m,resolveModelForOperation as Mm,runPartitioned as Um,loadProfileMap as Fm,resolveActiveProfile as Wm,resolveCrossLinks as Bm,applyStructureOrder as gd,orderSyncLine as yd,applyRelatedArticles as wd,relatedSyncLine as kd}from"document360-engine";import se from"picocolors";import El from"wrap-ansi";import Qs from"string-width";K();import kt from"picocolors";import Gs from"wrap-ansi";import Ys 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",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]",desc:"Publish to Document360 (no arg: pick; --all: every candidate; --screenshots: re-save articles with captured shots so images embed)",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:"catch-up",usage:"/catch-up [--publish]",desc:"Process ALL pending work (builder hints + requests + Document360 portal drift) \u2192 write \u2192 push to Document360 (bare = drafts; --publish goes live). For code changes, that's /audit",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 for each. 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:"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"}],kl={"/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 bl(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(kl[n])return kl[n];let o=bn.find(r=>r.name===t);return o?o.desc:""}function $l(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return bn.filter(n=>n.name.startsWith(t))}function vl(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}var Sf=new RegExp(`^\\s*/(?:${bn.map(e=>e.name).join("|")})(?:\\s|$)`),xl=e=>Sf.test(e),Cl=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Rl=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),Sl=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function Pf(e){let t=e.replace(/\r/g,"").split(`
|
|
289
|
-
`),n=[],o=0;for(;o<t.length;){let r=t[o];if(/^\s*```/.test(r)){let
|
|
290
|
-
`)}),I=Math.max(...
|
|
291
|
-
`)},
|
|
292
|
-
`)}function
|
|
293
|
-
`);return` ${r} ${i}`+
|
|
288
|
+
`));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(` ${W(n)} ${g("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?g(` [headers: ${r.join(", ")}]`):"";console.log(` ${W(n)} ${g(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function Rf(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(A("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(A(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=zs(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let i={};for(let l=1;l<o.length;l++)if(o[l]==="-H"||o[l]==="--header"){let p=o[++l],h=p?.match(/^([^:=]+)[:=](.+)$/);if(!h){console.log(A(`-H expects key:value (no spaces). Got: ${p??"(nothing)"}`));return}i[h[1].trim()]=h[2].trim()}else{console.log(A(`Unexpected argument: ${o[l]}. 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,kc(r),console.log(""),console.log(U(`\u2713 Registered "${t}" (${n})`)),console.log(H(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(g(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function Sf(e){let t=e[0];if(!t){console.log(A("Usage: /mcp remove <name>"));return}let n=zs();if(!n.servers[t]){console.log(A(`No server named "${t}".`));return}delete n.servers[t],kc(n),console.log(U(`\u2713 Removed "${t}".`)),console.log(g(" Run /clear to drop it from the current session immediately."))}X();import{readFileSync as Im}from"node:fs";import{join as Om}from"node:path";import{select as Lm}from"@inquirer/prompts";import{computeSyncStatus as Dr,planPartitions as _m,relatedArticlePaths as Mm,resolveModelForOperation as Um,runPartitioned as Fm,loadProfileMap as Wm,resolveActiveProfile as Bm,resolveCrossLinks as Hm,applyStructureOrder as yd,orderSyncLine as wd,applyRelatedArticles as kd,relatedSyncLine as bd}from"document360-engine";import re from"picocolors";import Ec from"wrap-ansi";import ei from"string-width";X();import kt from"picocolors";import Ks from"wrap-ansi";import Xs from"string-width";var $n=[{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",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]",desc:"Publish to Document360 (no arg: pick; --all: every candidate; --screenshots: re-save articles with captured shots so images embed)",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:"catch-up",usage:"/catch-up [--publish]",desc:"Process ALL pending work (builder hints + requests + Document360 portal drift) \u2192 write \u2192 push to Document360 (bare = drafts; --publish goes live). For code changes, that's /audit",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 for each. 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:"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"}],bc={"/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 $c(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(bc[n])return bc[n];let o=$n.find(r=>r.name===t);return o?o.desc:""}function vc(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return $n.filter(n=>n.name.startsWith(t))}function xc(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}var Pf=new RegExp(`^\\s*/(?:${$n.map(e=>e.name).join("|")})(?:\\s|$)`),Cc=e=>Pf.test(e),Rc=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Sc=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),Pc=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function Tf(e){let t=e.replace(/\r/g,"").split(`
|
|
289
|
+
`),n=[],o=0;for(;o<t.length;){let r=t[o];if(/^\s*```/.test(r)){let l=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)l.push(t[o++]);o++,n.push({kind:"code",lines:l});continue}if(Rc(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&Sc(t[o+1])){let l=Pc(r);o+=2;let p=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)p.push(Pc(t[o++]));n.push({kind:"table",header:l,rows:p});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 l=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);){let p=t[o++];l.push({ordered:/^\s*\d+\.\s+/.test(p),text:p.replace(/^\s*([-*]|\d+\.)\s+/,"")})}n.push({kind:"list",items:l});continue}if(r.trim()===""){o++;continue}if(Cc(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])&&!Cc(t[o])&&!Rc(t[o])&&!(t[o].includes("|")&&o+1<t.length&&Sc(t[o+1]));)i.push(t[o++]);n.push({kind:"para",text:i.join(" ")})}return n}function Qs(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?kt.bold(t.slice(2,-2)):t.startsWith("`")?W(t.slice(1,-1)):kt.italic(t.slice(1,-1)))}var Df=(e,t)=>e+" ".repeat(Math.max(0,t-Xs(e)));function Ef(e,t,n){let o=e.length,r=e.map((R,C)=>Math.max(Xs(R),...t.map(T=>Xs(T[C]??"")))),s=Math.max(24,n),i=3*o+1,l=[...r],p=()=>l.reduce((R,C)=>R+C,0)+i,h=0;for(;p()>s&&h++<1e4;){let R=-1,C=6;for(let T=0;T<o;T++)l[T]>C&&(C=l[T],R=T);if(R===-1)break;l[R]-=1}let b=(R,C,T)=>kt.gray(R+l.map(I=>"\u2500".repeat(I+2)).join(C)+T),$=kt.gray("\u2502"),v=(R,C)=>{let T=l.map((V,K)=>{let ue=R[K]??"",Se=C?kt.bold(ue):Qs(ue);return Ks(Se,V,{hard:!0}).split(`
|
|
290
|
+
`)}),I=Math.max(...T.map(V=>V.length)),z=[];for(let V=0;V<I;V++)z.push(l.map((K,ue)=>`${$} ${Df(T[ue][V]??"",K)} `).join("")+$);return z.join(`
|
|
291
|
+
`)},E=[b("\u250C","\u252C","\u2510"),v(e,!0)];return E.push(t.length===0?b("\u2514","\u2534","\u2518"):b("\u251C","\u253C","\u2524")),t.forEach((R,C)=>{E.push(v(R,!1)),E.push(C===t.length-1?b("\u2514","\u2534","\u2518"):b("\u251C","\u253C","\u2524"))}),E.join(`
|
|
292
|
+
`)}function Af(e,t){switch(e.kind){case"heading":return kt.bold(e.text);case"hr":return kt.gray("\u2500".repeat(t));case"para":return Ks(Qs(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="",...l]=Ks(Qs(o.text),Math.max(10,t-s.length)).split(`
|
|
293
|
+
`);return` ${r} ${i}`+l.map(p=>`
|
|
294
294
|
${s}${p}`).join("")}).join(`
|
|
295
295
|
`)}case"code":return e.lines.map(n=>kt.gray(" "+n)).join(`
|
|
296
|
-
`);case"table":return Ef(e.header,e.rows,t)}}function
|
|
296
|
+
`);case"table":return Ef(e.header,e.rows,t)}}function Js(e,t){let n=Math.max(20,t);return Tf(e).map(o=>Af(o,n)).join(`
|
|
297
297
|
|
|
298
|
-
`)}
|
|
299
|
-
`);let r=2,s=3,i=
|
|
298
|
+
`)}X();import jf from"picocolors";var Nf=[127,86,217],If=[22,38,43],Tc={T:Nf,E:If},Jn=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],Zs=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,Of=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function Dc(){if(!jf.isColorSupported)return[];let e=Jn[0].length,t=[];for(let n=0;n<Jn.length;n+=2){let o="";for(let r=0;r<e;r++){let s=Tc[Jn[n][r]],i=n+1<Jn.length?Tc[Jn[n+1][r]]:void 0;s&&i?o+=`${Zs(s)}${Of(i)}\u2580\x1B[49m\x1B[39m`:s?o+=`${Zs(s)}\u2580\x1B[39m`:i?o+=`${Zs(i)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function Zn(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 eo(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function Ae(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function bt(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var vn=(e,t)=>` ${e.padEnd(13)}${t}`;function Lf(e,t){let n=[Yn("\u270E document360-writer")+re.gray(` v${e.version} \xB7 engine v${e.engineVersion}${e.captureVersion?` \xB7 capture v${e.captureVersion}`:""}`),re.gray(" Reads your code, writes your docs."),"",vn("Claude:",`${e.claude}${re.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),vn("Document360:",e.configured?e.loggedOut?re.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?re.gray(` (${e.sessionHint})`):""}`:re.yellow("not set up \u2014 run /init")),vn("Profile:",e.configured?`${e.profile}${re.gray(` (${e.apiUrl})`)}${e.prod?re.bold(re.yellow(" \u26A0 PRODUCTION")):""}`:re.gray("\u2014 (run /init)")),vn("Project:",e.project),vn("Mode:",re.gray(e.mode)),vn("cwd:",re.gray(e.cwd))],o=Dc();if(o.length===0)return n.join(`
|
|
299
|
+
`);let r=2,s=3,i=ei(o[0]);if(!(t>=r+i+s+Math.max(...n.map(b=>ei(b)))))return[...o.map(b=>" "+b),...n].join(`
|
|
300
300
|
`);let p=Math.max(0,Math.floor((n.length-o.length)/2)),h=[];for(let b=0;b<Math.max(o.length+p,n.length);b++){let $=o[b-p]??" ".repeat(i);h.push((" ".repeat(r)+$+" ".repeat(s)+(n[b]??"")).trimEnd())}return h.join(`
|
|
301
|
-
`)}var
|
|
302
|
-
`).flatMap(h=>
|
|
303
|
-
`)),p=Math.max(0,
|
|
304
|
-
`+
|
|
301
|
+
`)}var _f={error:re.red,warn:re.yellow,ok:re.green,info:re.gray};function ti(e){return e.replace(/^(\s*• |)([^\x00-\x7F][\u{1F000}-\u{1FAFF}️]*) (?=\S)/gmu,"$1$2 ")}function ni(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return Lf(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",s=Math.max(10,n-4),i=50,l=e.text.split(`
|
|
302
|
+
`).flatMap(h=>Ec(h,s,{hard:!0}).split(`
|
|
303
|
+
`)),p=Math.max(0,l.length-i);return p>0&&(l=[...l.slice(0,i),re.dim(`\u2026 +${p} more lines`)]),`
|
|
304
|
+
`+l.map((h,b)=>o+(b===0?W(" \u276F "):" ")+h+" ".repeat(Math.max(0,s-ei(h))+1)+r).join(`
|
|
305
305
|
`)}case"assistant":return`
|
|
306
|
-
`+
|
|
307
|
-
`+
|
|
308
|
-
`)}case"diff":{let o=i=>i===1?"":"s",s=[
|
|
309
|
-
`)}case"link":return e.lines.map(o=>W(
|
|
306
|
+
`+Js(e.text,n);case"tool":{let o=e.arg!==null?re.gray(`${e.sep}(${e.arg})`):"";return`
|
|
307
|
+
`+Ec(re.green("\u25CF ")+re.bold(e.title)+o,n)}case"tool-result":{let o=e.isError?re.red:re.gray,r=e.lines.map((s,i)=>o((i===0?" \u23BF ":" ")+s));return e.hidden>0&&r.push(re.dim(` \u2026 +${e.hidden} lines`)),r.join(`
|
|
308
|
+
`)}case"diff":{let o=i=>i===1?"":"s",s=[re.gray(` \u23BF Added ${e.added} line${o(e.added)}, removed ${e.removed} line${o(e.removed)}`),...e.lines];return e.hidden>0&&s.push(re.dim(` \u2026 +${e.hidden} more diff lines`)),s.join(`
|
|
309
|
+
`)}case"link":return e.lines.map(o=>W(Kn(` \u2B95 ${o}`))).join(`
|
|
310
310
|
`);case"preview":return`
|
|
311
|
-
`+
|
|
312
|
-
|
|
313
|
-
`+
|
|
314
|
-
`+
|
|
315
|
-
`+(e.ok?
|
|
316
|
-
`)}import{resolveActiveProfile as
|
|
317
|
-
`,"utf8")}function
|
|
318
|
-
${
|
|
311
|
+
`+Yn(`\u25A3 Preview \u2014 ${e.name}`)+`
|
|
312
|
+
|
|
313
|
+
`+Js(e.text,n);case"note":return`
|
|
314
|
+
`+_f[e.tone](Kn(ti(e.text)));case"done":{let o=e.inTokens&&e.inTokens>0?` \xB7 ${Zn(e.inTokens)} in${e.cachedPct!=null?` (${e.cachedPct}% cached)`:""}`:"";return`
|
|
315
|
+
`+(e.ok?re.magenta("\u2736 "):re.red("\u2736 "))+re.gray(`Cooked for ${eo(e.seconds)} \xB7 ${Zn(e.tokens)} tokens out${o}`+(e.costUsd>0?` \xB7 ${Ae(e.costUsd)}`:""))}}}function Ac(e,t){return e.map(n=>ni(n,t)).join(`
|
|
316
|
+
`)}import{resolveActiveProfile as Mf,loadTokens as Uf,isExpired as Ff,decodeJwtClaims as jc}from"document360-engine";function Wf(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function Ye(e,t){try{let n=Mf(e,t),o=Uf(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(Ff(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={...jc(o.idToken)??{},...jc(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 ${Wf(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}import{existsSync as ai,readFileSync as ui}from"node:fs";import{isAbsolute as br,join as $r,resolve as vr}from"node:path";import P from"picocolors";import yr from"string-width";import{readProjectConfig as vt,screenshotPlaceholderIds as ed,DEFAULT_CAPTURE_DIR as xr,DEFAULT_OUTPUT_DIR as pi,DEFAULT_DOCS_DIR as hi,existingAnnotatedShotPath as dm,resolveOutputDir as td,migrateShotLayout as um,reviewIsCurrent as pm,shotImageMtimeMs as hm,RAW_SUBDIR as fm,ANNOTATED_SUBDIR as mm}from"document360-engine";import{createHash as Ic}from"node:crypto";import{readFileSync as Oc,writeFileSync as Bf}from"node:fs";import{join as Hf}from"node:path";import{captureStatePath as Lc}from"document360-engine";var Nc={version:1,shots:{}};function _c(e){return Ic("sha1").update(e).digest("hex").slice(0,12)}function fr(e){try{let t=JSON.parse(Oc(Hf(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(l=>`${l}=${s[l]}`).join("&");return Ic("sha1").update(`${o}|${r?.connection?.startUrl??""}|${i}`).digest("hex").slice(0,12)}catch{return null}}function lt(e){try{let t=JSON.parse(Oc(Lc(e),"utf8").replace(/^/,""));return!t||typeof t!="object"||t.version!==1||!t.shots?{...Nc,shots:{}}:{version:1,shots:t.shots}}catch{return{...Nc,shots:{}}}}function qf(e,t){Bf(Lc(e),`${JSON.stringify(t,null,2)}
|
|
317
|
+
`,"utf8")}function oi(e){return e&&/data-testid|\btest-?id\b|has(?:n't| not) landed/i.test(e)?"testid":"data"}function mr(e,t,n){if(t.length===0)return;let o=lt(e),r=fr(e);for(let s of t){let i=s.specSource?_c(s.specSource):void 0;o.shots[s.id]={outcome:s.outcome,at:n,...s.reason?{reason:s.reason}:{},...s.outcome==="skipped"?{blockedBy:oi(s.reason)}:{},...i?{specHash:i}:{},...r?{envHash:r}:{}}}qf(e,o)}function ri(e,t,n,o){let r=e.shots[t];return!r||n===null||!r.specHash||r.specHash!==_c(n)||o&&r.envHash&&r.envHash!==o?null:r}function Mc(e){let t=lt(e).shots;return Object.keys(t).filter(n=>t[n].outcome==="failed").sort()}function si(e,t,n){let o=ri(lt(e),t,n,fr(e));return!o||o.outcome==="captured"||!o.reason?null:{outcome:o.outcome,reason:o.reason}}gr();import{existsSync as Kf,readFileSync as Bc,readdirSync as Hc,writeFileSync as Xf}from"node:fs";import{isAbsolute as Qf,join as qc,resolve as Jf}from"node:path";import{readProjectConfig as Zf,DEFAULT_CAPTURE_DIR as em}from"document360-engine";var Wc="0.2.25";function tm(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 nm=/^([ \t]*)await\s+([^\n;]+?)\.screenshot\(\{\s*path:\s*PLACEHOLDER\.saveTo\s*(?:,\s*fullPage:\s*(?:true|false)\s*)?,?\s*\}\)\s*;?[ \t]*$/m,om=/^[ \t]*await\s+dumpAnnotations\(\s*page\s*,\s*PLACEHOLDER\s*\)\s*;?[ \t]*\r?\n?/m,Vc="(?:'([^']+)'|\"([^\"]+)\"|`([^`]+)`)",rm=new RegExp(`^page\\s*\\.\\s*locator\\(\\s*${Vc}\\s*\\)$`),Gc=e=>e[1]??e[2]??e[3]??null,sm=/^[A-Za-z_$][\w$]*$/;function im(e,t){let o=new RegExp(`\\bconst\\s+${t}\\s*=\\s*page\\s*\\.\\s*locator\\(\\s*${Vc}\\s*\\)\\s*;`).exec(e);return o?Gc(o):null}function am(e,t){let n=t.trim();if(n==="page")return null;let o=rm.exec(n);if(o){let r=Gc(o);return r?{selector:r}:{unresolved:!0}}if(sm.test(n)){let r=im(e,n);return r?{selector:r}:{unresolved:!0}}return{unresolved:!0}}function Yc(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=nm.exec(e);if(!n)return null;let[o,r="",s=""]=n,i=am(e,s);if(i===null)return null;if("unresolved"in i)return{unresolved:s.trim()};let l=/^([ \t]*)saveTo:\s*.+,[ \t]*$/m.exec(e);if(!l)return null;let p=i.selector.includes("'")?'"':"'",h=e.replace(l[0],`${l[0]}
|
|
318
|
+
${l[1]??" "}clipTo: ${p}${i.selector}${p},`);return h=h.replace(o,`${r}await captureShot(page, PLACEHOLDER);`),h=h.replace(om,""),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'/,(b,$)=>`import {${$.replace(/\s*$/,"")}, captureShot } from 'document360-capture/helpers'`)),{next:h,selector:i.selector}}function lm(e){try{return Hc(e).filter(t=>t.endsWith(".spec.ts")).some(t=>{try{let n=Yc(Bc(qc(e,t),"utf8"));return n!==null&&!("unresolved"in n)}catch{return!1}})}catch{return!1}}function cm(e){let t=Zf(e)?.captureDir??em;return Qf(t)?t:Jf(e,t)}function zc(e,t){let n={migrated:[],skipped:[]},o=cm(e);if(!Kf(o))return n;let r=t?.captureVersion===void 0?xn():t.captureVersion;if(!tm(r,Wc))return lm(o)?{...n,heldBackForCapture:{installed:r,required:Wc}}:n;let s;try{s=Hc(o).filter(i=>i.endsWith(".spec.ts"))}catch{return n}for(let i of s.sort()){let l=i.slice(0,-8),p=qc(o,i);try{let h=Bc(p,"utf8"),b=Yc(h);if(b===null)continue;if("unresolved"in b){n.skipped.push({id:l,receiver:b.unresolved});continue}Xf(p,b.next,"utf8"),n.migrated.push(l)}catch{}}return n}function Kc(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.
|
|
319
319
|
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(`
|
|
320
|
-
`)}var
|
|
321
|
-
`):null}function
|
|
322
|
-
`))||o.push(r+1));return o}function
|
|
323
|
-
`)}var $m={placeholder:"\u25CB",spec:"\u25D0",blocked:"\u2298",broken:"\u2717",captured:"\u25CF",verified:"\u2714",rejected:"\u2691"},vm={placeholder:D.gray,spec:D.yellow,blocked:D.cyan,broken:D.red,captured:D.blue,verified:D.green,rejected:D.magenta},xm=` ${D.green("\u2714 verified")} ${D.blue("\u25CF to verify")} ${D.yellow("\u25D0 ready")} ${D.magenta("\u2691 rejected")} ${D.cyan("\u2298 blocked")} ${D.red("\u2717 broken")} ${D.gray("\u25CB to spec")}`;function we(e,t=n=>n){return`${t(e)} `}function Cn(e){return e.replace(/\s+/g," ").trim().replace(/^Prerequisites? not met[:—-]?\s*/i,"")}function Cr(e){let t=Cn(e),n=/^(.*?[a-z0-9)"'”’])\.(?:\s|$)/i.exec(t);return(n?n[1]:t).trim()}function no(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=Cr(o),i=`${r} ${s.toLowerCase()}`,c=t.get(i)??{reason:s,blockedBy:r,ids:[]};t.has(i)||t.set(i,c),c.ids.push(n.id)}return[...t.values()].sort((n,o)=>o.ids.length-n.ids.length||n.reason.localeCompare(o.reason))}function ad(e){let t=no(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((c,p)=>c+p.ids.length,0);r.push(` ${D.bold("Stage this data")} ${D.gray(`\u2014 unblocks ${s} shot${s===1?"":"s"} in ${n.length} action${n.length===1?"":"s"}`)}`);let i=8;for(let c of n.slice(0,i)){let p=Bt(c.reason,86);r.push(` ${D.cyan($t(`${c.ids.length}\xD7`,4))} ${p[0]??""}`);for(let b of p.slice(1))r.push(` ${b}`);let h=c.ids.slice(0,4).join(" \xB7 ");r.push(D.gray(` ${h}${c.ids.length>4?` \xB7 +${c.ids.length-4} more`:""}`))}n.length>i&&r.push(D.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,c)=>i+c.ids.length,0);r.push(` ${we("\u2298",D.cyan)}${s} shot${s===1?"":"s"} need${s===1?"s":""} a data-testid from your developers \u2014 ${D.bold("/screenshot checklist")} builds the hand-off.`)}return r}function cd(e,t){let n=e.filter(i=>(i.unguardedWaits?.length??0)>0),o=e.filter(i=>i.undeclared);if(n.length===0&&o.length===0)return[];let r=["",` ${we("\u26A0",D.yellow)}Some specs were written before later reliability fixes:`],s=(i,c)=>` ${i.slice(0,8).map(c).join(" \xB7 ")}${i.length>8?` \xB7 +${i.length-8} more`:""}`;if(n.length>0){let i=n.length;r.push(D.gray(` ${i} crash${i===1?"es":""} instead of telling you what to stage when the data ${i===1?"it needs":"they need"} is missing`)),t&&r.push(D.gray(s(n,c=>`${c.id}:${c.unguardedWaits.join(",")}`)))}if(o.length>0){let i=o.length,c=o.filter(p=>p.mutates).length;r.push(D.gray(` ${i} do${i===1?"es":""} not say whether ${i===1?"it changes":"they change"} data in your app`+(c>0?`, so ${c===1?"one is":`${c} are`} left out of bulk runs to be safe`:""))),t&&r.push(D.gray(s(o,p=>p.id)))}return r.push(D.gray(` Re-write them all with the current rules: ${D.bold("/screenshot author --all")}`)),r}function ld(e){let t=e.filter(n=>(n.unverifiedForce?.length??0)>0);return t.length===0?[]:["",` ${we("\u26A0",D.red)}${t.length} spec${t.length===1?"":"s"} force-click past Playwright's safety checks without asserting the result`+D.gray(" \u2014 if the click lands on nothing, the shot photographs the unchanged screen"),D.gray(` ${t.slice(0,6).map(n=>`${n.id}:${n.unverifiedForce.join(",")}`).join(" \xB7 ")}${t.length>6?` \xB7 +${t.length-6} more`:""}`),D.gray(` Re-author to check what the click did: ${D.bold("/screenshot author <id>")}`)]}var gr=(e,t)=>e.length>=t?e:e+" ".repeat(t-e.length),$t=(e,t)=>e.length>=t?e:" ".repeat(t-e.length)+e;function dd(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 Cm=new Set(["and","or","of","the","to","a","an","in","on","for","with","vs"]),Rm=new Set(["ai","api","cli","ui","ux","url","id","http","https","json","xml","sdk","csv","pdf","oauth","sso","mfa","io","faq"]);function Sm(e){return e.replace(/[-_]+/g," ").trim().split(/\s+/).filter(Boolean).map((n,o)=>{let r=n.toLowerCase();return Rm.has(r)?r.toUpperCase():o>0&&Cm.has(r)?r:r.charAt(0).toUpperCase()+r.slice(1)}).join(" ")}function si(e){if(!e)return{num:"",name:"(docs root)"};let t=/^(\d+)[-_](.+)$/.exec(e);return{num:t?t[1]:"",name:Sm(t?t[2]:e)}}function Pm(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).pop()??e}function Jl(e,t,n){let o=t>0?Math.round(e/t*n):0;return D.green("\u2588".repeat(o))+D.gray("\u2591".repeat(Math.max(0,n-o)))}function Tm(e,t){let n=t>0?Math.round(e/t*100):0,o=$t(`${n}%`,4);return n===100?D.green(o):n>0?D.yellow(o):D.gray(o)}function ud(e,t){let n=new Map;for(let o of e){let r=dd(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 Em(e,t){let n=(J,re)=>J.filter(le=>le.state===re).length,o=e.length,r=n(e,"verified"),s=n(e,"captured"),i=n(e,"rejected"),c=n(e,"spec"),p=n(e,"blocked"),h=n(e,"broken"),b=n(e,"placeholder"),$=new Set(e.map(J=>J.file)).size,v=ud(e,t),A=[];A.push(` ${D.bold("Screenshots")} ${D.green(`${r}/${o} verified`)} ${D.gray("\xB7")} ${s>0?D.blue(`${s} to verify`):D.gray("0 to verify")}`+(i>0?` ${D.gray("\xB7")} ${D.magenta(`${i} rejected`)}`:"")+` ${D.gray("\xB7")} ${c>0?D.yellow(`${c} ready`):D.gray("0 ready")}`+(p>0?` ${D.gray("\xB7")} ${D.cyan(`${p} blocked`)}`:"")+(h>0?` ${D.gray("\xB7")} ${D.red(`${h} broken`)}`:"")+` ${D.gray("\xB7")} ${b>0?D.red(`${b} to spec`):D.gray("0 to spec")} `+D.gray(`across ${$} article${$===1?"":"s"}`));let R=o>0?Math.round(r/o*100):0;A.push(` [${Jl(r,o,32)}] ${D.bold(`${R}%`)}`),A.push("");let C=v.map(([J])=>si(J)),P=Math.min(32,Math.max(7,...C.map(J=>J.name.length))),I=J=>J.length>P?`${J.slice(0,P-1)}\u2026`:gr(J,P),Y=[...s>0?[{head:"To verify",w:9,state:"captured",color:D.blue}]:[],...i>0?[{head:"Rejected",w:8,state:"rejected",color:D.magenta}]:[],{head:"Ready",w:5,state:"spec",color:D.yellow},...p>0?[{head:"Blocked",w:7,state:"blocked",color:D.cyan}]:[],...h>0?[{head:"Broken",w:6,state:"broken",color:D.red}]:[],{head:"To spec",w:7,state:"placeholder",color:D.red}];A.push(D.gray(` ${gr("#",2)} ${gr("Chapter",P)} ${$t("Verified",8)} ${Y.map(J=>$t(J.head,J.w)).join(" ")} Progress`));for(let[J,[,re]]of v.entries()){let le=n(re,"verified"),ae=re.length,{num:Ze,name:Fe}=C[J],ze=le===ae,lt=I(Fe),Pt=Y.map(dt=>{let zt=n(re,dt.state);return zt>0?dt.color($t(String(zt),dt.w)):D.gray($t("\u2014",dt.w))}).join(" ");A.push(` ${D.cyan(gr(Ze,2))} ${ze?D.green(lt):le>0?lt:D.gray(lt)} ${ze?D.green($t(`${le}/${ae}`,8)):$t(`${le}/${ae}`,8)} ${Pt} ${Jl(le,ae,10)} ${Tm(le,ae)}`)}A.push("");let V=h>0?` ${D.gray("\xB7")} ${h} spec${h===1?"":"s"} broken \u2014 ${D.bold(`/screenshot ${e.find(J=>J.state==="broken").id}`)} re-authors ${h===1?"it":"the first"}`:"",z=e.filter(J=>J.state==="spec"&&J.mutates).length,he=c>z;if(b>0)A.push(` ${we("\u2192",D.yellow)}${b} placeholder${b===1?"":"s"} still need a spec \u2014 run ${D.bold("/screenshot author --all")}${V}`);else if(c>0&&(he||s===0)){let J=z>0?D.gray(` \u2014 ${c-z} in one go; ${z} write${z===1?"s":""} real data and run${z===1?"s":""} one at a time`):"";A.push(` ${we("\u2192",D.yellow)}${c} spec${c===1?"":"s"} ready to capture \u2014 run ${D.bold("/screenshot capture")}${J}${V}`)}else if(s>0&&c>0)A.push(` ${we("\u2192",D.blue)}${s} shot${s===1?"":"s"} awaiting verification \u2014 run ${D.bold("/screenshot verify")}`+D.gray(" \u2014 no browser needed")+D.gray(` \xB7 ${c} ready spec${c===1?"":"s"} write real data, so ${c===1?"it runs":"each runs"} only when named: /screenshot capture <id>`)+V);else if(p>0)A.push(` ${we("\u2192",D.cyan)}${p} shot${p===1?"":"s"} blocked \u2014 stage the data below, then ${D.bold("/screenshot capture --blocked")}${V}`);else if(h>0)A.push(` ${we("\u2192",D.red)}${h} spec${h===1?"":"s"} broken \u2014 ${D.bold(`/screenshot ${e.find(J=>J.state==="broken").id}`)} re-authors ${h===1?"it":"the first"} (re-capturing fails the same way)`);else if(s>0)A.push(` ${we("\u2192",D.blue)}${s} shot${s===1?"":"s"} awaiting verification \u2014 run ${D.bold("/screenshot verify")}`+D.gray(" \u2014 it checks each picture against what its article needs (no browser, no re-capture)"));else if(i>0){let J=e.filter(re=>re.state==="rejected"&&re.repaired).length;A.push(` ${we("\u2691",D.magenta)}${i} shot${i===1?"":"s"} failed review \u2014 `+(J>0?`${J} spec${J===1?"":"s"} already repaired; re-capture with ${D.bold("/screenshot capture --failed")}`:`see the reasons below, then ${D.bold("/screenshot capture --failed")}`))}else A.push(` ${we("\u2713",D.green)}all ${o} verified \u2014 ${D.bold("/publish")} embeds them in the articles`);if(r>0&&r<o){let J=v.filter(([,re])=>re.every(le=>le.state!=="verified")).map(([re])=>{let{num:le,name:ae}=si(re);return le?`${le} ${ae}`:ae});J.length>0&&A.push(D.gray(` Furthest behind: ${J.slice(0,5).join(" \xB7 ")}${J.length>5?" \u2026":""} (0% verified)`))}return A.push(...ad(e),...ld(e),...cd(e,!1)),A.push(""),A.push(D.gray(" Drill in: /screenshot list <chapter#> \xB7 /screenshot list --detail (all)")),A}function Dm(e,t,n){let o=new Set(e.map(c=>c.file)),r=e.filter(c=>c.state==="verified").length,s=e.filter(c=>c.state==="captured").length,i=[` ${D.bold("Screenshots")}: ${e.length} placeholder${e.length===1?"":"s"} across ${o.size} article${o.size===1?"":"s"} \xB7 ${D.green(`${r} verified`)}${s>0?D.blue(` \xB7 ${s} to verify`):""}${n?D.gray(` \xB7 scope ${n}`):""}`,""];for(let[c,p]of ud(e,t)){let h=p.filter(R=>R.state==="verified").length,{num:b,name:$}=si(c),v=b?`${b} \xB7 ${$}`:$;i.push(` ${D.bold(v)} ${D.gray(`(${h}/${p.length})`)}`);let A=new Map;for(let R of p){let C=Pm(R.file),P=A.get(C)??[];A.has(C)||A.set(C,P),P.push(R)}for(let R of[...A.keys()].sort()){i.push(D.gray(` ${R}`));for(let C of A.get(R)){let P=vm[C.state];if(i.push(` ${we($m[C.state],P)}${P(C.id)}`),(C.state==="blocked"||C.state==="broken"||C.state==="rejected")&&C.reason){for(let I of Bt(Cn(C.reason),84))i.push(D.gray(` ${I}`));C.state==="rejected"&&i.push(D.gray(` ${C.repaired?"spec repaired \u2014 re-capture to confirm":"spec not yet repaired"}`))}}}}return i.push(...ad(e),...ld(e),...cd(e,!0)),i.push("",xm),i}function Rr(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??di;return t?.detail||n?Dm(e,o,n):Em(e,o)}function ui(e,t){if(!t||!/^\d+$/.test(t))return t;let n=vt(e)?.docsDir??di,o=String(Number(t));for(let{file:r}of Zl(e)){let s=dd(r,n),i=/^(\d+)/.exec(s);if(i&&String(Number(i[1]))===o)return s}return t}function pd(e,t){let r=e.map(c=>" ".repeat(c.depth)+c.label),s=Math.max(0,...e.map((c,p)=>c.note?mr(r[p]):0)),i=Math.min(s,Math.max(0,t-2-24));return e.map((c,p)=>{let h=r[p];if(!c.note)return{head:h,note:""};let b=Math.max(2,i+2-mr(h)),$=c.note.trim(),v=t-mr(h)-b;return{head:h+" ".repeat(b),note:v>1&&mr($)>v?`${$.slice(0,v-1)}\u2026`:$}})}function Am(e){let t=e.replace(/\\/g,"/").split("/").filter(Boolean),n=t.pop()??e;return{category:t.pop()??"(docs root)",article:n}}function yr(e,t,n){let o=new Map;for(let s of t){let{category:i,article:c}=Am(s.file),p=o.get(i)??new Map;o.set(i,p);let h=p.get(c)??[];p.set(c,h),h.push(s)}let r=s=>n==="author"||!s.mutates;for(let s of[...o.keys()].sort()){let i=o.get(s),c=[...i.values()].flat().filter(r).map(h=>h.id),p=c.length>0;p&&e.push({kind:"category",action:n,label:`${s} (${c.length})`,ids:c,depth:1});for(let h of[...i.keys()].sort()){let b=i.get(h),$=b.filter(r).map(R=>R.id),v=$.length>0;v&&e.push({kind:"article",action:n,label:`${h} (${$.length})`,ids:$,depth:p?2:1});let A=(p?1:0)+(v?1:0)+1;for(let R of b){let C=n==="capture"&&R.mutates?" \u26A0 creates real data \u2014 runs only alone":void 0;e.push({kind:"shot",action:n,label:R.id,ids:[R.id],depth:A,...C?{note:C}:{}})}}}}function oi(e){return e?Cn(e):""}function pi(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((c,p)=>c.id.localeCompare(p.id)))e.push({kind:"shot",action:"capture",label:i.id,ids:[i.id],depth:1,note:` \u2298 ${oi(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((c,p)=>c.id.localeCompare(p.id)))e.push({kind:"shot",action:"author",label:i.id,ids:[i.id],depth:1,note:` \u2717 re-authors \u2014 ${oi(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((c,p)=>c.id.localeCompare(p.id))){let c=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 ${c} \u2014 ${oi(i.reason)}`})}}function hd(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}),yr(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}),yr(o,n,"capture"),pi(o,e.filter(s=>s.state==="blocked"),e.filter(s=>s.state==="broken"),e.filter(s=>s.state==="rejected")),o}var ii=["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 page.screenshot()/dumpAnnotations() 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.","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.","Before you finish, re-read each spec you wrote and check all three rules line by line."].join(`
|
|
324
|
-
`);function
|
|
325
|
-
`),"",...o.length>0?["REPAIR \u2014 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).",...o.map(s),""]:[],...r.length>0?["REPAIR \u2014 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 \u2014 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.",...r.map(s),""]:[],"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.",
|
|
326
|
-
`)}async function
|
|
327
|
-
`),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.`,
|
|
328
|
-
`),
|
|
329
|
-
`)}var
|
|
330
|
-
`)}function
|
|
331
|
-
`),display:"/audit"}}
|
|
332
|
-
`)}async function
|
|
333
|
-
`);return
|
|
334
|
-
`)||
|
|
335
|
-
`},r=o(e),s=o(t);if(r===s)return null;let i=Math.max(20,n-10),c=Xm("a","b",r,s,"","",{context:3}),p=0,h=0,b=[];c.hunks.forEach((v,A)=>{A>0&&b.push(Sd.gray(" \u2026"));let R=v.oldStart,C=v.newStart,P=[],I=[],Y=()=>{for(let V=0;V<P.length;V++){let z=V<I.length?Ed(P[V],I[V]):void 0;h++,b.push(`${Qm}${bi(R++)} - ${Dd(P[V],i,z)}${Td}`)}for(let V=0;V<I.length;V++){let z=V<P.length?Ed(P[V],I[V]):void 0;p++,b.push(`${Jm}${bi(C++)} + ${Dd(I[V],i,z)}${Td}`)}P=[],I=[]};for(let V of v.lines){let z=V[0],he=V.slice(1);z==="-"?P.push(he):z==="+"?I.push(he):(Y(),b.push(Sd.gray(bi(C))+" "+he.slice(0,i)),R++,C++)}Y()});let $=b.slice(0,Pd);return{added:p,removed:h,lines:$,hidden:Math.max(0,b.length-Pd)}}K();import{select as Zm}from"@inquirer/prompts";import{applyPull as eg,computeSyncStatus as tg,planPull as ng}from"document360-engine";var Ad=e=>e===1?"":"s";async function $i(e,t){console.log(""),console.log(`${W("\u25CF")} ${Te(t.title)} ${me(`(${t.path})`)}`);for(let r of t.notes)console.log(H(` \u26A0 ${r}`));let n=ct(t.oldContent,t.newContent,Math.max(40,(process.stdout.columns??80)-1));if(n){console.log(me(` \u23BF local \u2192 portal: +${n.added} / -${n.removed} line${Ad(n.added+n.removed)}`));for(let r of n.lines)console.log(r);n.hidden>0&&console.log(g(` \u2026 +${n.hidden} more diff lines`))}else console.log(g(" Local already matches the portal content \u2014 resolving just advances the sync base."));let o=await e.withPausedInput(()=>Zm({message:`Conflict \u2014 ${t.path}`,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"}]})).catch(()=>"skip");return o==="portal"?(eg({cwd:e.cwd,profileName:e.profileName},t),console.log(U(" \u2713 Took the portal copy (local overwritten, sync base advanced).")),"took-portal"):o==="local"?"keep-local":(console.log(g(" Skipped \u2014 still a conflict.")),"skipped")}async function jd(e,t){let n=Ve(t.cwd,t.profileName);if(!n.ok)return console.log(E(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let s=(await tg({cwd:t.cwd,profileName:t.profileName})).entries.filter(c=>c.status==="conflict"&&c.path).map(c=>c.path);if(o){if(!s.includes(o))return console.log(U(`${o} isn't in conflict \u2014 nothing to resolve.`)),{kind:"continue"};s=[o]}if(s.length===0)return console.log(U("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let i=[];for(let c of s){let p=await ng({cwd:t.cwd,profileName:t.profileName,relPath:c});await $i(t,p)==="keep-local"&&i.push(c)}if(i.length>0)return console.log(g(`Publishing ${i.length} kept-local article${Ad(i.length)} over the portal\u2026`)),await xt(t,i)}catch(r){console.log(E(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function Od(e,t){let n=Ve(t.cwd,t.profileName);if(!n.ok)return console.log(E(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await dg(t),{kind:"continue"};if(o==="--baseline")return await ug(t,e.filter(i=>i!=="--baseline")),{kind:"continue"};if(o==="--compare")return await pg(t),{kind:"continue"};if(o)return console.log(E(`Unknown option: ${o}`)),console.log(g("Usage: /pull pull portal edits + import new portal articles")),console.log(g(" /pull <path> pull one article (or resolve a conflict)")),console.log(g(" /pull --status drift report only (no writes)")),console.log(g(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await hg(t,r),{kind:"continue"};console.log(g("Pulling changes from Document360\u2026"));let s=await xi({cwd:t.cwd,profileName:t.profileName});for(let i of Ci(s))console.log(i.tone==="ok"?U(i.text):i.tone==="warn"?H(i.text):g(i.text));console.log("")}catch(r){r instanceof lg?console.log(E(r.message)):console.log(E(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function xi(e){let t=await Nd({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 Id({cwd:e.cwd,profileName:e.profileName,relPath:o.path});vi({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 sg({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});ig({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 Ir=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,qt=e=>e===1?"":"s";function Ci(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${qt(e.pulled.length)} into local: ${Ir(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${qt(e.imported.length)}: ${Ir(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${qt(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${qt(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). (${Ir(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${qt(e.failed.length)} failed: ${Ir(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 dg(e){console.log(g("Checking Document360 for drift\u2026"));let t=Date.now(),n=await Nd({cwd:e.cwd,profileName:e.profileName});for(let o of Nr(n,Date.now()-t))console.log(o);console.log("")}async function ug(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(g(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await ag({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await cg({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(U("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(U(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(U(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(H(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(g(` - ${s.path} (${s.reason})`))}}async function pg(e){console.log(g("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await rg({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${Te(String(t.legacyCount))} \xB7 Manifest: ${Te(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(U("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(E(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(H(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(H(` ${t.onlyInManifest.length} only in the manifest: ${t.onlyInManifest.slice(0,5).join(", ")}`)),console.log(g(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function hg(e,t){let n=t.replace(/\\/g,"/"),o=await Id({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await $i(e,o)==="keep-local"&&(console.log(g(`Publishing ${o.path} over the portal\u2026`)),await xt(e,[o.path]));return}console.log(""),console.log(`${W("\u25CF")} ${Te(o.title)} ${me(`(${o.path})`)}`);for(let i of o.notes)console.log(H(` \u26A0 ${i}`));let r=ct(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!r){console.log(g(" Local file already matches the remote content \u2014 advancing the sync base only.")),vi({cwd:e.cwd,profileName:e.profileName},o);return}console.log(me(` \u23BF Added ${r.added} line${qt(r.added)}, removed ${r.removed} line${qt(r.removed)}`));for(let i of r.lines)console.log(i);if(r.hidden>0&&console.log(g(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>og({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(g(" Skipped."));return}vi({cwd:e.cwd,profileName:e.profileName},o),console.log(U(` \u2713 Pulled ${o.path} (sync base advanced).`))}K();import{statSync as fg}from"node:fs";import{resolve as mg}from"node:path";import{estimateBulkCost as gg,planPartitions as yg,readProjectConfig as wg,resolveModelForOperation as kg,runPartitioned as bg,trackedArticlePaths as $g}from"document360-engine";var Ri=3;function Si(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 Pi(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Ti(e,t){return t.map(n=>{let o=0;try{o=fg(mg(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function Ei(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 \u2014 be efficient:
|
|
320
|
+
`)}var nd=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Xc(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 to(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 Xc(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 Xc(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 ve(e,t){let n=vt(e),o=n?.captureDir??xr,r=n?.outputDir??pi,s=(p,h)=>br(p)?$r(p,h):vr(e,p,h),i=lt(e),l=fr(e);return ed(e,{scope:t}).map(({id:p,file:h})=>{let b=s(o,`${p}.spec.ts`),$=null;if(ai(b))try{$=ui(b,"utf8")}catch{}let v=td(e,r),E=ai(dm(v,p)),R=$===null?null:ri(i,p,$,l),C=i.shots[p]?.review,T=E&&pm(C,hm(v,p))?C:void 0,I=$!==null&&wm($),z=E&&T?.verdict==="ok"?"verified":E&&T?.verdict==="rejected"?"rejected":E?"captured":$===null?"placeholder":I||R?.outcome==="skipped"?"blocked":R?.outcome==="failed"?"broken":"spec",V=$===null?void 0:rd($),K=I?km($):R?.reason,ue=I?"testid":R?.outcome==="skipped"?oi(R.reason):void 0;return{id:p,file:h,state:z,...V?{mutates:V.mutates,...V.declared?{}:{undeclared:!0}}:{},...$!==null&&Jc($).length>0?{unguardedWaits:Jc($)}:{},...$!==null&&Qc($).length>0?{unverifiedForce:Qc($)}:{},...z==="blocked"||z==="broken"?{...K?{reason:K}:{},...ue?{blockedBy:ue}:{}}:{},...z==="rejected"?{...T?.reason?{reason:T.reason}:{},...T?.repaired?{repaired:!0}:{}}:{}}})}function gm(e){let t=vt(e)?.outputDir??pi;return um(td(e,t))}function no(e){let t=gm(e),n=vt(e)?.outputDir??pi,o=[];t>0&&o.push(`\u2195 Tidied ${t} screenshot file${t===1?"":"s"} into ${n}/{${fm},${mm}} \u2014 annotated/ is what publishes, raw/ is the pre-annotation intermediate.`);let r=Kc(zc(e));return r&&o.push(r),o.length>0?o.join(`
|
|
321
|
+
`):null}function Cn(e,t){let n=vt(e)?.captureDir??xr,o=br(n)?$r(n,`${t}.spec.ts`):vr(e,n,`${t}.spec.ts`);try{return ui(o,"utf8")}catch{return null}}function od(e,t){let n=vt(e)?.captureDir??xr;return ai(br(n)?$r(n,`${t}.spec.ts`):vr(e,n,`${t}.spec.ts`))}function ym(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 rd(e){let t=e.split(/\r?\n/),n=t.findIndex(l=>/^\s*\/\/\s*CAPTURE-SAFETY:\s*(readonly|mutates)\b/i.test(l)),o=n>=0?/^\s*\/\/\s*CAPTURE-SAFETY:\s*(readonly|mutates)\b[\s—:–-]*(.*)$/i.exec(t[n]):null;if(o){let l=ym(t,n,o[2]??"");return{mutates:o[1].toLowerCase()==="mutates",declared:!0,what:l||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 wm(e){return/(^|\n)\s*test\.skip\s*\(\s*['"`]/.test(e)}function km(e){let t=/\/\/\s*CAPTURE-TODO:\s*(\{.*\})\s*$/m.exec(e),n,o;if(t)try{let s=JSON.parse(t[1]);n=s.testid,o=s.file}catch{}return`Inert until your developers add ${n?`data-testid="${n}"${o?` in ${o}`:""}`:"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 sd(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 Qc(e,t=10){let n=sd(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(`
|
|
322
|
+
`))||o.push(r+1));return o}function Jc(e){let t=[],n=sd(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 id(e){return(e??"").trim().replace(/[.\s]+$/,"")}function ad(e,t){let n=vt(e)?.captureDir??xr,o=br(n)?$r(n,`${t}.spec.ts`):vr(e,n,`${t}.spec.ts`);try{return rd(ui(o,"utf8"))}catch{return{mutates:!1,declared:!1}}}var bm=["captured","verified","rejected"],$m=e=>bm.includes(e);function Cr(e){return[...new Set(e.filter(t=>$m(t.state)).map(t=>t.file))].sort()}function Rr(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[`${ge("\u26A0",P.yellow)}${t.length} screenshot${t.length===1?"":"s"} failed verification:`,...t.map(o=>` ${P.magenta(o.id.padEnd(n))} ${P.gray(Rn(o.reason??"no reason recorded"))}`),` Publishing anyway. Fix + re-capture: ${P.bold("/screenshot capture --failed")}`].join(`
|
|
323
|
+
`)}var vm={placeholder:"\u25CB",spec:"\u25D0",blocked:"\u2298",broken:"\u2717",captured:"\u25CF",verified:"\u2714",rejected:"\u2691"},xm={placeholder:P.gray,spec:P.yellow,blocked:P.cyan,broken:P.red,captured:P.blue,verified:P.green,rejected:P.magenta},Cm=` ${P.green("\u2714 verified")} ${P.blue("\u25CF to verify")} ${P.yellow("\u25D0 ready")} ${P.magenta("\u2691 rejected")} ${P.cyan("\u2298 blocked")} ${P.red("\u2717 broken")} ${P.gray("\u25CB to spec")}`;function ge(e,t=n=>n){return`${t(e)} `}function Rn(e){return e.replace(/\s+/g," ").trim().replace(/^Prerequisites? not met[:—-]?\s*/i,"")}function Sr(e){let t=Rn(e),n=/^(.*?[a-z0-9)"'”’])\.(?:\s|$)/i.exec(t);return(n?n[1]:t).trim()}function oo(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=Sr(o),i=`${r} ${s.toLowerCase()}`,l=t.get(i)??{reason:s,blockedBy:r,ids:[]};t.has(i)||t.set(i,l),l.ids.push(n.id)}return[...t.values()].sort((n,o)=>o.ids.length-n.ids.length||n.reason.localeCompare(o.reason))}function ld(e){let t=oo(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((l,p)=>l+p.ids.length,0);r.push(` ${P.bold("Stage this data")} ${P.gray(`\u2014 unblocks ${s} shot${s===1?"":"s"} in ${n.length} action${n.length===1?"":"s"}`)}`);let i=8;for(let l of n.slice(0,i)){let p=Ht(l.reason,86);r.push(` ${P.cyan($t(`${l.ids.length}\xD7`,4))} ${p[0]??""}`);for(let b of p.slice(1))r.push(` ${b}`);let h=l.ids.slice(0,4).join(" \xB7 ");r.push(P.gray(` ${h}${l.ids.length>4?` \xB7 +${l.ids.length-4} more`:""}`))}n.length>i&&r.push(P.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,l)=>i+l.ids.length,0);r.push(` ${ge("\u2298",P.cyan)}${s} shot${s===1?"":"s"} need${s===1?"s":""} a data-testid from your developers \u2014 ${P.bold("/screenshot checklist")} builds the hand-off.`)}return r}function cd(e,t,n){let o=e.filter(l=>(l.unguardedWaits?.length??0)>0),r=e.filter(l=>l.undeclared);if(o.length===0&&r.length===0)return[];let s=["",` ${ge("\u26A0",P.yellow)}Some specs were written before later reliability fixes:`],i=(l,p)=>` ${l.slice(0,8).map(p).join(" \xB7 ")}${l.length>8?` \xB7 +${l.length-8} more`:""}`;if(o.length>0){let l=o.length;s.push(P.gray(` ${l} crash${l===1?"es":""} instead of telling you what to stage when the data ${l===1?"it needs":"they need"} is missing`)),t&&s.push(P.gray(i(o,p=>`${p.id}:${p.unguardedWaits.join(",")}`)))}if(r.length>0){let l=r.length,p=r.filter(h=>h.mutates).length;s.push(P.gray(` ${l} do${l===1?"es":""} not say whether ${l===1?"it changes":"they change"} data in your app`+(p>0?`, so ${p===1?"one is":`${p} are`} left out of bulk runs to be safe`:""))),t&&s.push(P.gray(i(r,h=>h.id)))}return n?.commandInLead||s.push(P.gray(` Re-write them all with the current rules: ${P.bold("/screenshot author --all")}`)),s}function dd(e){let t=e.filter(n=>(n.unverifiedForce?.length??0)>0);return t.length===0?[]:["",` ${ge("\u26A0",P.red)}${t.length} spec${t.length===1?"":"s"} force-click past Playwright's safety checks without asserting the result`+P.gray(" \u2014 if the click lands on nothing, the shot photographs the unchanged screen"),P.gray(` ${t.slice(0,6).map(n=>`${n.id}:${n.unverifiedForce.join(",")}`).join(" \xB7 ")}${t.length>6?` \xB7 +${t.length-6} more`:""}`),P.gray(` Re-author to check what the click did: ${P.bold("/screenshot author <id>")}`)]}var wr=(e,t)=>e.length>=t?e:e+" ".repeat(t-e.length),$t=(e,t)=>e.length>=t?e:" ".repeat(t-e.length)+e;function ud(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 Rm=new Set(["and","or","of","the","to","a","an","in","on","for","with","vs"]),Sm=new Set(["ai","api","cli","ui","ux","url","id","http","https","json","xml","sdk","csv","pdf","oauth","sso","mfa","io","faq"]);function Pm(e){return e.replace(/[-_]+/g," ").trim().split(/\s+/).filter(Boolean).map((n,o)=>{let r=n.toLowerCase();return Sm.has(r)?r.toUpperCase():o>0&&Rm.has(r)?r:r.charAt(0).toUpperCase()+r.slice(1)}).join(" ")}function li(e){if(!e)return{num:"",name:"(docs root)"};let t=/^(\d+)[-_](.+)$/.exec(e);return{num:t?t[1]:"",name:Pm(t?t[2]:e)}}function Tm(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).pop()??e}function Zc(e,t,n){let o=t>0?Math.round(e/t*n):0;return P.green("\u2588".repeat(o))+P.gray("\u2591".repeat(Math.max(0,n-o)))}function Dm(e,t){let n=t>0?Math.round(e/t*100):0,o=$t(`${n}%`,4);return n===100?P.green(o):n>0?P.yellow(o):P.gray(o)}function pd(e,t){let n=new Map;for(let o of e){let r=ud(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 Em(e,t){let n=(Y,pe)=>Y.filter(ae=>ae.state===pe).length,o=e.length,r=n(e,"verified"),s=n(e,"captured"),i=n(e,"rejected"),l=n(e,"spec"),p=n(e,"blocked"),h=n(e,"broken"),b=n(e,"placeholder"),$=new Set(e.map(Y=>Y.file)).size,v=pd(e,t),E=[];E.push(` ${P.bold("Screenshots")} ${P.green(`${r}/${o} verified`)} ${P.gray("\xB7")} ${s>0?P.blue(`${s} to verify`):P.gray("0 to verify")}`+(i>0?` ${P.gray("\xB7")} ${P.magenta(`${i} rejected`)}`:"")+` ${P.gray("\xB7")} ${l>0?P.yellow(`${l} ready`):P.gray("0 ready")}`+(p>0?` ${P.gray("\xB7")} ${P.cyan(`${p} blocked`)}`:"")+(h>0?` ${P.gray("\xB7")} ${P.red(`${h} broken`)}`:"")+` ${P.gray("\xB7")} ${b>0?P.red(`${b} to spec`):P.gray("0 to spec")} `+P.gray(`across ${$} article${$===1?"":"s"}`));let R=o>0?Math.round(r/o*100):0;E.push(` [${Zc(r,o,32)}] ${P.bold(`${R}%`)}`),E.push("");let C=v.map(([Y])=>li(Y)),T=Math.min(32,Math.max(7,...C.map(Y=>Y.name.length))),I=Y=>Y.length>T?`${Y.slice(0,T-1)}\u2026`:wr(Y,T),z=[...s>0?[{head:"To verify",w:9,state:"captured",color:P.blue}]:[],...i>0?[{head:"Rejected",w:8,state:"rejected",color:P.magenta}]:[],{head:"Ready",w:5,state:"spec",color:P.yellow},...p>0?[{head:"Blocked",w:7,state:"blocked",color:P.cyan}]:[],...h>0?[{head:"Broken",w:6,state:"broken",color:P.red}]:[],{head:"To spec",w:7,state:"placeholder",color:P.red}];E.push(P.gray(` ${wr("#",2)} ${wr("Chapter",T)} ${$t("Verified",8)} ${z.map(Y=>$t(Y.head,Y.w)).join(" ")} Progress`));for(let[Y,[,pe]]of v.entries()){let ae=n(pe,"verified"),$e=pe.length,{num:Kt,name:Pt}=C[Y],Xt=ae===$e,Tt=I(Pt),So=z.map(et=>{let Po=n(pe,et.state);return Po>0?et.color($t(String(Po),et.w)):P.gray($t("\u2014",et.w))}).join(" ");E.push(` ${P.cyan(wr(Kt,2))} ${Xt?P.green(Tt):ae>0?Tt:P.gray(Tt)} ${Xt?P.green($t(`${ae}/${$e}`,8)):$t(`${ae}/${$e}`,8)} ${So} ${Zc(ae,$e,10)} ${Dm(ae,$e)}`)}E.push("");let V=h>0?` ${P.gray("\xB7")} ${h} spec${h===1?"":"s"} broken \u2014 ${P.bold(`/screenshot ${e.find(Y=>Y.state==="broken").id}`)} re-authors ${h===1?"it":"the first"}`:"",K=e.filter(Y=>Y.state==="spec"&&Y.mutates).length,ue=l>K,Se=e.filter(Y=>(Y.unguardedWaits?.length??0)>0).length,ke=l>0||p>0||h>0,Ne=!1;if(b>0)E.push(` ${ge("\u2192",P.yellow)}${b} placeholder${b===1?"":"s"} still need a spec \u2014 run ${P.bold("/screenshot author --all")}${V}`);else if(Se>0&&ke)Ne=!0,E.push(` ${ge("\u2192",P.yellow)}${Se} spec${Se===1?"":"s"} would crash mid-run \u2014 re-write ${Se===1?"it":"them"} first: ${P.bold("/screenshot author --all")}`+P.gray(` \xB7 then ${P.bold("/screenshot capture")} (no browser time wasted on ${Se===1?"a shot":"shots"} that can't finish)`)+V);else if(l>0&&(ue||s===0)){let Y=K>0?P.gray(` \u2014 ${l-K} in one go; ${K} write${K===1?"s":""} real data and run${K===1?"s":""} one at a time`):"";E.push(` ${ge("\u2192",P.yellow)}${l} spec${l===1?"":"s"} ready to capture \u2014 run ${P.bold("/screenshot capture")}${Y}${V}`)}else if(s>0&&l>0)E.push(` ${ge("\u2192",P.blue)}${s} shot${s===1?"":"s"} awaiting verification \u2014 run ${P.bold("/screenshot verify")}`+P.gray(" \u2014 no browser needed")+P.gray(` \xB7 ${l} ready spec${l===1?"":"s"} write real data, so ${l===1?"it runs":"each runs"} only when named: /screenshot capture <id>`)+V);else if(p>0)E.push(` ${ge("\u2192",P.cyan)}${p} shot${p===1?"":"s"} blocked \u2014 stage the data below, then ${P.bold("/screenshot capture --blocked")}${V}`);else if(h>0)E.push(` ${ge("\u2192",P.red)}${h} spec${h===1?"":"s"} broken \u2014 ${P.bold(`/screenshot ${e.find(Y=>Y.state==="broken").id}`)} re-authors ${h===1?"it":"the first"} (re-capturing fails the same way)`);else if(s>0)E.push(` ${ge("\u2192",P.blue)}${s} shot${s===1?"":"s"} awaiting verification \u2014 run ${P.bold("/screenshot verify")}`+P.gray(" \u2014 it checks each picture against what its article needs (no browser, no re-capture)"));else if(i>0){let Y=e.filter(pe=>pe.state==="rejected"&&pe.repaired).length;E.push(` ${ge("\u2691",P.magenta)}${i} shot${i===1?"":"s"} failed review \u2014 `+(Y>0?`${Y} spec${Y===1?"":"s"} already repaired; re-capture with ${P.bold("/screenshot capture --failed")}`:`see the reasons below, then ${P.bold("/screenshot capture --failed")}`))}else E.push(` ${ge("\u2713",P.green)}all ${o} verified \u2014 ${P.bold("/publish")} embeds them in the articles`);if(r>0&&r<o){let Y=v.filter(([,pe])=>pe.every(ae=>ae.state!=="verified")).map(([pe])=>{let{num:ae,name:$e}=li(pe);return ae?`${ae} ${$e}`:$e});Y.length>0&&E.push(P.gray(` Furthest behind: ${Y.slice(0,5).join(" \xB7 ")}${Y.length>5?" \u2026":""} (0% verified)`))}return E.push(...ld(e),...dd(e),...cd(e,!1,{commandInLead:Ne})),E.push(""),E.push(P.gray(" Drill in: /screenshot list <chapter#> \xB7 /screenshot list --detail (all)")),E}function Am(e,t,n){let o=new Set(e.map(l=>l.file)),r=e.filter(l=>l.state==="verified").length,s=e.filter(l=>l.state==="captured").length,i=[` ${P.bold("Screenshots")}: ${e.length} placeholder${e.length===1?"":"s"} across ${o.size} article${o.size===1?"":"s"} \xB7 ${P.green(`${r} verified`)}${s>0?P.blue(` \xB7 ${s} to verify`):""}${n?P.gray(` \xB7 scope ${n}`):""}`,""];for(let[l,p]of pd(e,t)){let h=p.filter(R=>R.state==="verified").length,{num:b,name:$}=li(l),v=b?`${b} \xB7 ${$}`:$;i.push(` ${P.bold(v)} ${P.gray(`(${h}/${p.length})`)}`);let E=new Map;for(let R of p){let C=Tm(R.file),T=E.get(C)??[];E.has(C)||E.set(C,T),T.push(R)}for(let R of[...E.keys()].sort()){i.push(P.gray(` ${R}`));for(let C of E.get(R)){let T=xm[C.state];if(i.push(` ${ge(vm[C.state],T)}${T(C.id)}`),(C.state==="blocked"||C.state==="broken"||C.state==="rejected")&&C.reason){for(let I of Ht(Rn(C.reason),84))i.push(P.gray(` ${I}`));C.state==="rejected"&&i.push(P.gray(` ${C.repaired?"spec repaired \u2014 re-capture to confirm":"spec not yet repaired"}`))}}}}return i.push(...ld(e),...dd(e),...cd(e,!0)),i.push("",Cm),i}function Pr(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??hi;return t?.detail||n?Am(e,o,n):Em(e,o)}function fi(e,t){if(!t||!/^\d+$/.test(t))return t;let n=vt(e)?.docsDir??hi,o=String(Number(t));for(let{file:r}of ed(e)){let s=ud(r,n),i=/^(\d+)/.exec(s);if(i&&String(Number(i[1]))===o)return s}return t}function hd(e,t){let r=e.map(l=>" ".repeat(l.depth)+l.label),s=Math.max(0,...e.map((l,p)=>l.note?yr(r[p]):0)),i=Math.min(s,Math.max(0,t-2-24));return e.map((l,p)=>{let h=r[p];if(!l.note)return{head:h,note:""};let b=Math.max(2,i+2-yr(h)),$=l.note.trim(),v=t-yr(h)-b;return{head:h+" ".repeat(b),note:v>1&&yr($)>v?`${$.slice(0,v-1)}\u2026`:$}})}function jm(e){let t=e.replace(/\\/g,"/").split("/").filter(Boolean),n=t.pop()??e;return{category:t.pop()??"(docs root)",article:n}}function kr(e,t,n){let o=new Map;for(let s of t){let{category:i,article:l}=jm(s.file),p=o.get(i)??new Map;o.set(i,p);let h=p.get(l)??[];p.set(l,h),h.push(s)}let r=s=>n==="author"||!s.mutates;for(let s of[...o.keys()].sort()){let i=o.get(s),l=[...i.values()].flat().filter(r).map(h=>h.id),p=l.length>0;p&&e.push({kind:"category",action:n,label:`${s} (${l.length})`,ids:l,depth:1});for(let h of[...i.keys()].sort()){let b=i.get(h),$=b.filter(r).map(R=>R.id),v=$.length>0;v&&e.push({kind:"article",action:n,label:`${h} (${$.length})`,ids:$,depth:p?2:1});let E=(p?1:0)+(v?1:0)+1;for(let R of b){let C=n==="capture"&&R.mutates?" \u26A0 creates real data \u2014 runs only alone":void 0;e.push({kind:"shot",action:n,label:R.id,ids:[R.id],depth:E,...C?{note:C}:{}})}}}}function ii(e){return e?Rn(e):""}function mi(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((l,p)=>l.id.localeCompare(p.id)))e.push({kind:"shot",action:"capture",label:i.id,ids:[i.id],depth:1,note:` \u2298 ${ii(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((l,p)=>l.id.localeCompare(p.id)))e.push({kind:"shot",action:"author",label:i.id,ids:[i.id],depth:1,note:` \u2717 re-authors \u2014 ${ii(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((l,p)=>l.id.localeCompare(p.id))){let l=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 ${l} \u2014 ${ii(i.reason)}`})}}function fd(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}),kr(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}),kr(o,n,"capture"),mi(o,e.filter(s=>s.state==="blocked"),e.filter(s=>s.state==="broken"),e.filter(s=>s.state==="rejected")),o}var ci=["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 page.screenshot()/dumpAnnotations() 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.","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.","Before you finish, re-read each spec you wrote and check all three rules line by line."].join(`
|
|
324
|
+
`);function Nm(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 di="MANDATORY, check before you finish: every spec you write or touch must carry exactly one `// CAPTURE-SAFETY: readonly` or `// CAPTURE-SAFETY: mutates \u2014 <what it creates>; cleanup: <how>` line at the top. Re-read each file you wrote and add it if missing \u2014 a spec without it is classified by guesswork. A fail-by-design spec (the app rejects the input) is `readonly`.";function md(e,t){let n=e.paths,o=n.filter(i=>t?.get(i)?.outcome==="failed"),r=n.filter(i=>t?.get(i)?.outcome==="skipped"),s=i=>`- ${i}: ${t.get(i).reason.replace(/\s+/g," ").trim()}`;return["Run the emit-screenshot-spec skill to author the document360-capture spec for EACH of these","SCREENSHOT placeholder ids:",e.paths.map(i=>`- ${i}`).join(`
|
|
325
|
+
`),"",...o.length>0?["REPAIR \u2014 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).",...o.map(s),""]:[],...r.length>0?["REPAIR \u2014 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 \u2014 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.",...r.map(s),""]:[],"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.",ci,di].join(`
|
|
326
|
+
`)}async function Tr(e,t,n){let o=to(e),r=no(t?.cwd??process.cwd());if(r&&console.log(P.gray(r)),o.mode==="list"){let p=t?.cwd??process.cwd(),h=fi(p,o.scope),b=vt(p)?.docsDir??hi,$=ve(p,h);for(let v of Pr($,{scope:h,detail:o.detail,docsDir:b}))console.log(v);return{kind:"continue"}}if(o.mode==="single")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 \u2014 spec path, data to`,"stage, dev requests only if any, and the capture command; no grounding narration.",ci,di,...n?.prior?["",...Nm(n.prior)]:[]].join(`
|
|
327
|
+
`),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.`,ci,di].join(`
|
|
328
|
+
`),l=o.mode==="scope"?`/screenshot ${o.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:i,display:l}}var ro=3;function gi(e){return[`Run the publish-to-d360 skill for the article at: ${e}`,"","Steps you must follow:","1. Read the article markdown \u2014 use 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 \u2014 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(`
|
|
329
|
+
`)}var gd={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function yi(e){return e.filter(t=>t.path!==null&&t.status in gd&&!t.link).map(t=>({path:t.path,label:gd[t.status]}))}function Er(e){let t=yi(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 Ar(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 jr(e){return e.filter(t=>t.link).length}function wi(e,t){try{let n=Wm(e,Bm(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=Hm(Im(Om(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 qm(e){let t=e.replace(/\\/g,"/").split("/").pop()??e,n=t.replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return n?n.charAt(0).toUpperCase()+n.slice(1):t}function $d(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,l)=>i.path.localeCompare(l.path));n.push({kind:"category",label:`${qm(r)} (${s.length})`,paths:s.map(i=>i.path),indent:!1});for(let i of s){let l=i.path.replace(/\\/g,"/").split("/").pop()??i.path;n.push({kind:"article",label:l,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 so(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 \u2014 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(`
|
|
330
|
+
`)}function ki(e,t,n){let o=v=>t[v.index]?.paths.length??0,r=e.filter(v=>v.ok),s=e.filter(v=>!v.ok),i=e.reduce((v,E)=>v+o(E),0),l=r.reduce((v,E)=>v+o(E),0),p=n==="api"?`${Ae(e.reduce((v,E)=>v+E.costUsd,0))} total`:bt(e.reduce((v,E)=>v+E.outputTokens,0)),h=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,b=v=>`${v} article${v===1?"":"s"}`,$=[];if(s.length===0)$.push(`Published ${b(i)} (${h}) successfully \xB7 ${p}.`),$.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{$.push(`Published ${l}/${b(i)} (${h}) \xB7 ${p}.`),$.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /publish --all to retry just the rest (published articles are skipped):`);for(let v of s)$.push(` \u2717 ${v.label}${v.error?` \u2014 ${v.error}`:""}`)}return $}async function xt(e,t){let{model:n}=Um(e.cwd,"standard"),o=async(r,s)=>{let i=_m(r);console.log(g(s?`Resolving cross-links in ${r.length} article${r.length===1?"":"s"} whose targets published this run (second pass)\u2026`:`Publishing ${r.length} article${r.length===1?"":"s"} across ${i.length} partition${i.length===1?"":"s"} (\u2264${ro} agents at once) on ${n}\u2026`)),s||console.log(g(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let l=!1;for await(let p of Fm({cwd:e.cwd,partitions:i,promptFor:h=>so(h.paths),concurrency:ro,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:n}))if(p.type==="partition_status")p.status==="running"?console.log(g(` \u25B8 ${p.label} \u2014 publishing\u2026`)):p.status==="done"?console.log(U(` \u2713 ${p.label}`)):console.log(A(` \u2717 ${p.label}`));else if(p.type==="run_done"){l=p.aborted,console.log("");let h=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let $ of ki(p.results,i,h))console.log(p.ok?U($):H($));let b=wi(e.cwd,e.profileName);b&&console.log(g(b));try{let $=wd(await yd({cwd:e.cwd,profileName:e.profileName,onRateLimit:v=>console.log(g(` Document360 rate limit \u2014 waiting ${Math.ceil(v.waitMs/1e3)}s\u2026`))}));$&&console.log(g($))}catch{}try{let $=bd(await kd({cwd:e.cwd,profileName:e.profileName}));$&&console.log(g($))}catch{}}return l};try{if(!await o(t,!1)){let s=await bi(e.cwd,e.profileName,t);s.length>0&&await o(s,!0)}}catch(r){console.log(A(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function Nr(e,t,n){let o=Mm(e,n);if(o.length===0)return[];let r=new Set(yi((await Dr({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function bi(e,t,n){try{let o=new Set(n),r=await Dr({cwd:e,profileName:t});return yi(r.entries).map(s=>s.path).filter(s=>o.has(s))}catch{return[]}}async function vd(e,t){let n=Ye(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(A(n.reason)),{kind:"continue"};let o=e[0];if(e.includes("--screenshots")||e.includes("--shots")){let r=t?.cwd??process.cwd(),s=ve(r),i=Cr(s);if(i.length===0)return console.log(g("No captured screenshots yet \u2014 /screenshot capture first.")),{kind:"continue"};let l=Rr(s);return l&&console.log(l),t?await xt(t,i):{kind:"forward-to-agent",prompt:so(i),display:"/publish --screenshots"}}if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await Nr(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return r.length===0?(console.log(U("\u2713 All related articles are already published.")),{kind:"continue"}):await xt(t,r)}if(o==="--all"){console.log(g("Checking what needs publishing\u2026"));try{let r=await Dr({cwd:t?.cwd??process.cwd()}),{clean:s,conflicts:i}=Er(r.entries),l=jr(r.entries),p=e.includes("--force")&&i.length>0;l>0&&console.log(H(`\u26A0 ${l} 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.`)),i.length>0&&!p&&console.log(H(Ar(i.length)));let h=p?[...s,...i]:s;if(h.length===0){if(i.length>0)return console.log(g("Resolve the conflicts: /resolve")),{kind:"continue"};if(console.log(U(l>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),t)try{let b=wd(await yd({cwd:t.cwd,profileName:t.profileName,onRateLimit:v=>console.log(g(` Document360 rate limit \u2014 waiting ${Math.ceil(v.waitMs/1e3)}s\u2026`))}));b&&console.log(g(b));let $=bd(await kd({cwd:t.cwd,profileName:t.profileName}));$&&console.log(g($))}catch{}return{kind:"continue"}}return t?await xt(t,h.map(b=>b.path)):{kind:"forward-to-agent",prompt:so(h.map(b=>b.path)),display:"/publish --all"}}catch(r){return console.log(A(`Could not compute sync status: ${r.message}`)),{kind:"continue"}}}if(o&&o.startsWith("--")&&(o=e.find(r=>!r.startsWith("--"))??""),!o){console.log(g("Checking what needs publishing\u2026"));let r;try{let s=await Dr({cwd:t?.cwd??process.cwd()}),{clean:i,conflicts:l}=Er(s.entries);r=i;let p=jr(s.entries);if(p>0&&console.log(H(`\u26A0 ${p} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),l.length>0&&console.log(H(Ar(l.length))),r.length===0&&l.length>0)return console.log(g("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(s){return console.log(A(`Could not compute sync status: ${s.message}`)),console.log(g("Publish a specific article: /publish <article-path>")),{kind:"continue"}}if(r.length===0)return console.log(U("\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),console.log(g(" (Articles without a sync base are unverified \u2014 publish those by path if needed.)")),{kind:"continue"};if(!process.stdin.isTTY||!t){for(let s of r)console.log(` ${s.path} ${g(`(${s.label})`)}`);return console.log(g("Run: /publish <article-path>")),{kind:"continue"}}try{o=await t.withPausedInput(()=>Lm({message:"Publish which article?",choices:[...r.length>1?[{name:`All ${r.length} candidates`,value:"--all",description:"one agent run over every candidate"}]:[],...r.map(s=>({name:s.path,value:s.path,description:s.label}))]}))}catch{return console.log(g("Cancelled.")),{kind:"continue"}}if(o==="--all")return await xt(t,r.map(s=>s.path))}return{kind:"forward-to-agent",prompt:gi(o),display:`/publish ${o}`}}async function io(){return{kind:"forward-to-agent",prompt:["Run the gap-analysis skill against this repo.","","Follow its stages in order:","1. d360_sync_status first \u2014 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 \u2014 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 \u2014 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 \u2014 backfill them.","4. Output the proposal table: | Article (path or proposed title) | Action (create | update | retire | link) | Reason | Evidence | Scope |, then advance lastAnalyzedCommit and stamp consumed hints.","","Do not start writing or updating any article yet \u2014 the proposal table is the deliverable."].join(`
|
|
331
|
+
`),display:"/audit"}}X();import{readProjectConfig as Vm}from"document360-engine";function $i(){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 \u2014 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 \u2014 every claim cited to its grounding \u2014 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 \u2014 the'," 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(`
|
|
332
|
+
`)}async function xd(e,t){let n=t?.cwd??process.cwd();return Vm(n)?{kind:"forward-to-agent",prompt:$i(),display:"/discover"}:(console.log(A("No d360-writer config here. Run /init first.")),{kind:"continue"})}X();import{checkbox as Gm}from"@inquirer/prompts";import{inventoryRepo as Ym,readProjectConfig as Cd,writeProjectConfig as zm}from"document360-engine";function vi(e,t){let n=Cd(e);n&&(n.authoritativeSourceFiles=t,zm(n,e))}function Ir(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 Rd(e,t){let n=t?.cwd??process.cwd();if(!Cd(n))return console.log(A("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=Ym(n);if(o.length===0)return console.log(g('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(W("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${g(Ir(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>Gm({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${Ir(s)})`,value:s.path,checked:s.recommended})),pageSize:20}))}catch{return console.log(g("Cancelled.")),{kind:"continue"}}if(r.length===0)return console.log(g("Nothing selected \u2014 scope unchanged.")),{kind:"continue"};vi(n,r),console.log(U(`\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"}}X();import{confirm as rg}from"@inquirer/prompts";import{applyPull as Ri,computeSyncStatus as Id,compareRemoteSources as sg,planPull as Od,planImport as ig,applyImport as ag,establishBaselines as lg,rebaselineServerMeta as cg,D360AuthError as dg}from"document360-engine";X();var Sd=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /publish <path>):",paint:A,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /publish <path>:",paint:H,mark:"M"},{status:"remote-ahead",header:"Changed on Document360 \u2014 pull with /pull <path> (or just /pull):",paint:W,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:A,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:A,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:g,mark:"?"},{status:"untracked-remote",header:"On Document360 \u2014 not in your local docs yet (run /pull to import them):",paint:g,mark:"?"},{status:"unknown-base",header:"Tracked, not yet compared \u2014 run /pull --baseline to set a baseline (or the next publish/pull sets one):",paint:fe,mark:"\xB7"}];function Km(e){return e.path?e.path:`${e.title??"(untitled)"} ${fe(`[${e.articleId}]`)}`}function Xm(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 Or(e,t){let n=[],o=e.entries.filter(b=>b.link);if(o.length>0){n.push(""),n.push(Ee("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let b of o)n.push(` ${H("~")} ${H(b.path??"")} ${fe(`\u2192 "${b.link.title}"`)}`)}for(let b of Sd){let $=e.entries.filter(v=>v.status===b.status&&!(b.status==="untracked-local"&&v.link));if($.length!==0){n.push(""),n.push(Ee(b.header));for(let v of $)n.push(` ${b.paint(b.mark)} ${b.paint(Km(v))}${v.detail?fe(` (${v.detail})`):""}`)}}let r=e.counts["in-sync"]??0,s=e.entries.length;n.push("");let i={"in-sync":"up to date","local-ahead":"changed here","remote-ahead":"changed on Document360",conflict:"changed both places","untracked-local":"new here","untracked-remote":"only on Document360","deleted-local":"removed locally","deleted-remote":"gone from Document360",orphaned:"gone both sides","unknown-base":"not yet compared"},l=o.length,p=s===r?U("\u2713 everything up to date"):[r>0?U(`\u2713 ${r} up to date`):null,l>0?`${l} to link`:null,...Sd.map(b=>{let $=(e.counts[b.status]??0)-(b.status==="untracked-local"?l:0);return $>0?`${$} ${i[b.status]}`:null})].filter(Boolean).join(fe(" \xB7 ")),h=t!==void 0?` \xB7 synced in ${Xm(t)}`:"";return n.push(p+fe(` \xB7 ${s} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${h}`)),n}import{structuredPatch as Qm}from"diff";import Pd from"picocolors";var Td=80,Jm="\x1B[48;2;74;28;28m",Zm="\x1B[48;2;24;66;24m",Dd="\x1B[49m",xi=e=>String(e).padStart(5);function Ed(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}function Ad(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 ct(e,t,n){let o=v=>{let E=v.replace(/\r\n/g,`
|
|
333
|
+
`);return E.endsWith(`
|
|
334
|
+
`)||E===""?E:E+`
|
|
335
|
+
`},r=o(e),s=o(t);if(r===s)return null;let i=Math.max(20,n-10),l=Qm("a","b",r,s,"","",{context:3}),p=0,h=0,b=[];l.hunks.forEach((v,E)=>{E>0&&b.push(Pd.gray(" \u2026"));let R=v.oldStart,C=v.newStart,T=[],I=[],z=()=>{for(let V=0;V<T.length;V++){let K=V<I.length?Ed(T[V],I[V]):void 0;h++,b.push(`${Jm}${xi(R++)} - ${Ad(T[V],i,K)}${Dd}`)}for(let V=0;V<I.length;V++){let K=V<T.length?Ed(T[V],I[V]):void 0;p++,b.push(`${Zm}${xi(C++)} + ${Ad(I[V],i,K)}${Dd}`)}T=[],I=[]};for(let V of v.lines){let K=V[0],ue=V.slice(1);K==="-"?T.push(ue):K==="+"?I.push(ue):(z(),b.push(Pd.gray(xi(C))+" "+ue.slice(0,i)),R++,C++)}z()});let $=b.slice(0,Td);return{added:p,removed:h,lines:$,hidden:Math.max(0,b.length-Td)}}X();import{select as eg}from"@inquirer/prompts";import{applyPull as tg,computeSyncStatus as ng,planPull as og}from"document360-engine";var jd=e=>e===1?"":"s";async function Ci(e,t){console.log(""),console.log(`${W("\u25CF")} ${Ee(t.title)} ${fe(`(${t.path})`)}`);for(let r of t.notes)console.log(H(` \u26A0 ${r}`));let n=ct(t.oldContent,t.newContent,Math.max(40,(process.stdout.columns??80)-1));if(n){console.log(fe(` \u23BF local \u2192 portal: +${n.added} / -${n.removed} line${jd(n.added+n.removed)}`));for(let r of n.lines)console.log(r);n.hidden>0&&console.log(g(` \u2026 +${n.hidden} more diff lines`))}else console.log(g(" Local already matches the portal content \u2014 resolving just advances the sync base."));let o=await e.withPausedInput(()=>eg({message:`Conflict \u2014 ${t.path}`,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"}]})).catch(()=>"skip");return o==="portal"?(tg({cwd:e.cwd,profileName:e.profileName},t),console.log(U(" \u2713 Took the portal copy (local overwritten, sync base advanced).")),"took-portal"):o==="local"?"keep-local":(console.log(g(" Skipped \u2014 still a conflict.")),"skipped")}async function Nd(e,t){let n=Ye(t.cwd,t.profileName);if(!n.ok)return console.log(A(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let s=(await ng({cwd:t.cwd,profileName:t.profileName})).entries.filter(l=>l.status==="conflict"&&l.path).map(l=>l.path);if(o){if(!s.includes(o))return console.log(U(`${o} isn't in conflict \u2014 nothing to resolve.`)),{kind:"continue"};s=[o]}if(s.length===0)return console.log(U("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let i=[];for(let l of s){let p=await og({cwd:t.cwd,profileName:t.profileName,relPath:l});await Ci(t,p)==="keep-local"&&i.push(l)}if(i.length>0)return console.log(g(`Publishing ${i.length} kept-local article${jd(i.length)} over the portal\u2026`)),await xt(t,i)}catch(r){console.log(A(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function Ld(e,t){let n=Ye(t.cwd,t.profileName);if(!n.ok)return console.log(A(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await ug(t),{kind:"continue"};if(o==="--baseline")return await pg(t,e.filter(i=>i!=="--baseline")),{kind:"continue"};if(o==="--compare")return await hg(t),{kind:"continue"};if(o)return console.log(A(`Unknown option: ${o}`)),console.log(g("Usage: /pull pull portal edits + import new portal articles")),console.log(g(" /pull <path> pull one article (or resolve a conflict)")),console.log(g(" /pull --status drift report only (no writes)")),console.log(g(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await fg(t,r),{kind:"continue"};console.log(g("Pulling changes from Document360\u2026"));let s=await Si({cwd:t.cwd,profileName:t.profileName});for(let i of Pi(s))console.log(i.tone==="ok"?U(i.text):i.tone==="warn"?H(i.text):g(i.text));console.log("")}catch(r){r instanceof dg?console.log(A(r.message)):console.log(A(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function Si(e){let t=await Id({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 Od({cwd:e.cwd,profileName:e.profileName,relPath:o.path});Ri({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 ig({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});ag({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 Lr=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Vt=e=>e===1?"":"s";function Pi(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${Vt(e.pulled.length)} into local: ${Lr(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${Vt(e.imported.length)}: ${Lr(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${Vt(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${Vt(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). (${Lr(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${Vt(e.failed.length)} failed: ${Lr(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 ug(e){console.log(g("Checking Document360 for drift\u2026"));let t=Date.now(),n=await Id({cwd:e.cwd,profileName:e.profileName});for(let o of Or(n,Date.now()-t))console.log(o);console.log("")}async function pg(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(g(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await lg({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await cg({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(U("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(U(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(U(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(H(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(g(` - ${s.path} (${s.reason})`))}}async function hg(e){console.log(g("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await sg({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${Ee(String(t.legacyCount))} \xB7 Manifest: ${Ee(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(U("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(A(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(H(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(H(` ${t.onlyInManifest.length} only in the manifest: ${t.onlyInManifest.slice(0,5).join(", ")}`)),console.log(g(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function fg(e,t){let n=t.replace(/\\/g,"/"),o=await Od({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await Ci(e,o)==="keep-local"&&(console.log(g(`Publishing ${o.path} over the portal\u2026`)),await xt(e,[o.path]));return}console.log(""),console.log(`${W("\u25CF")} ${Ee(o.title)} ${fe(`(${o.path})`)}`);for(let i of o.notes)console.log(H(` \u26A0 ${i}`));let r=ct(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!r){console.log(g(" Local file already matches the remote content \u2014 advancing the sync base only.")),Ri({cwd:e.cwd,profileName:e.profileName},o);return}console.log(fe(` \u23BF Added ${r.added} line${Vt(r.added)}, removed ${r.removed} line${Vt(r.removed)}`));for(let i of r.lines)console.log(i);if(r.hidden>0&&console.log(g(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>rg({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(g(" Skipped."));return}Ri({cwd:e.cwd,profileName:e.profileName},o),console.log(U(` \u2713 Pulled ${o.path} (sync base advanced).`))}X();import{statSync as mg}from"node:fs";import{resolve as gg}from"node:path";import{estimateBulkCost as yg,planPartitions as wg,readProjectConfig as kg,resolveModelForOperation as bg,runPartitioned as $g,trackedArticlePaths as vg}from"document360-engine";var Ti=3;function Di(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 Ei(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Ai(e,t){return t.map(n=>{let o=0;try{o=mg(gg(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function ji(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 \u2014 be efficient:
|
|
336
336
|
- Read ONLY the article files listed below. Do NOT read source code, other articles, or fetch the live portal \u2014 you already have everything you need.
|
|
337
337
|
- 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.
|
|
338
338
|
- 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.
|
|
339
339
|
- Work only on these files:
|
|
340
340
|
`+e.paths.map(t=>`- ${t}`).join(`
|
|
341
|
-
`)}function
|
|
341
|
+
`)}function Ni(e,t,n){let o=e.reduce((l,p)=>l+p.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(l=>` \u2022 ${l.label} \u2014 ${l.paths.length} article${l.paths.length===1?"":"s"}`),"",`Estimated cost: ${Ae(r)}\u2013${Ae(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function Ii(e,t,n){let o=R=>t[R.index]?.paths.length??0,r=e.filter(R=>R.ok),s=e.filter(R=>!R.ok),i=e.reduce((R,C)=>R+o(C),0),l=r.reduce((R,C)=>R+o(C),0),p=e.reduce((R,C)=>R+C.costUsd,0),h=e.reduce((R,C)=>R+C.outputTokens,0),b=n==="api"?`${Ae(p)} total`:bt(h),$=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,v=R=>`${R} article${R===1?"":"s"}`,E=[];if(s.length===0)E.push(`Converted ${v(i)} (${$}) successfully \xB7 ${b}.`);else{E.push(`Converted ${l}/${v(i)} (${$}) \xB7 ${b}.`),E.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let R of s)E.push(` \u2717 ${R.label}${R.error?` \u2014 ${R.error}`:""}`)}return E}async function _d(e,t){if(!kg(t.cwd))return console.log(A("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=Di(e),r=vg(t.cwd,t.profileName);if(r.length===0)return console.log(A("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let s=Ei(r,n);if(s.length===0)return console.log(A(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let i=wg(s),l=`/convert${n?` --scope ${n}`:""} --run`,{model:p,forced:h}=bg(t.cwd,"light");if(!o){let b=yg({files:Ai(t.cwd,s),op:"convert",model:p});n&&console.log(g(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let $ of Ni(i,b,Ti))console.log($);return console.log(g(`Model: ${p}${h?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(g(`Run ${l} to start.`)),console.log(""),{kind:"continue"}}console.log(g(`Converting ${s.length} articles across ${i.length} partitions (\u2264${Ti} agents at once) on ${p}\u2026`)),console.log(g(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let b of $g({cwd:t.cwd,partitions:i,promptFor:ji,concurrency:Ti,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:p}))if(b.type==="partition_status")b.status==="running"?console.log(g(` \u25B8 ${b.label} \u2014 converting\u2026`)):b.status==="done"?console.log(U(` \u2713 ${b.label}`)):console.log(A(` \u2717 ${b.label}`));else if(b.type==="run_done"){console.log("");let $=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let v of Ii(b.results,i,$))console.log(b.ok?U(v):H(v))}}catch(b){console.log(A(`Convert run failed: ${b.message}`))}return console.log(""),{kind:"continue"}}X();import{statSync as Fd}from"node:fs";import{resolve as Wd}from"node:path";import{estimateBulkCost as Ag,lintDocs as jg,planPartitions as Ng,readDocsPlan as Ig,readProjectConfig as Bd,DEFAULT_DOCS_DIR as Og,resolveModelForOperation as Lg,runPartitioned as _g,stampArticles as Mg,CONTENT_CAP_VERSION as Ug}from"document360-engine";import{readProjectConfig as xg,loadProfileMap as Cg,resolveActiveProfile as Rg,desiredCategoryOrder as Sg,desiredArticleOrder as Pg,DEFAULT_DOCS_DIR as Tg}from"document360-engine";var Oi=e=>e.replace(/\\/g,"/"),Dg=e=>Oi(e).split("/").pop()??e;function Eg(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}function ao(e,t){try{let n=xg(e);if(!n)return[];let o=Rg(e,t),r=Cg(e,o.name);if(!r)return[];let s=Oi(n.docsDir??Tg).replace(/\/+$/,""),i=new Map;for(let p of Pg(r))i.set(p.categoryPath,(i.get(p.categoryPath)??0)+1);let l=[];for(let p of Sg(r)){let h=Oi(p.path),b=h.startsWith(`${s}/`)?h.slice(s.length+1):h===s?"":h;b&&l.push({token:b,label:Eg(Dg(h)),count:i.get(p.path)??0})}return l}catch{return[]}}function Md(e,t){let n=ao(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 Ct(e,t){return t.includes("--all")||t.some(n=>!n.startsWith("--"))?!1:e==="review"||e==="reorder"||e==="write"&&t.includes("--rewrite")}function Sn(e,t,n,o){let r=ao(e,o);if(r.length<=1)return[];let s=n.filter(h=>h.startsWith("--")).join(" "),i=s?` ${s}`:"",l=`/${t}${i} --all`.replace(/\s+/g," "),p=h=>t==="write"?`/write --scope ${h}${i}`:`/${t} ${h}${i}`;return[`Bare /${t} covers the WHOLE knowledge base (${r.reduce((h,b)=>h+b.count,0)} articles). Pick a target:`,` ${l} (everything)`,...r.map(h=>` ${p(h.token)} (${h.label} \xB7 ${h.count} article${h.count===1?"":"s"})`)]}function _r(e){let t=e.indexOf("--scope");if(t===-1)return!1;let n=e[t+1];return n===void 0||n.startsWith("-")}function Ud(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 Fg=3,Wg=8;function Li(e){return e===void 0||!Number.isFinite(e)?Fg:Math.max(1,Math.min(Math.floor(e),Wg))}function _i(e){let t,n,o=!1,r=!1,s,i=p=>{let h=Number(p);return p!==void 0&&Number.isFinite(h)?h:void 0};for(let p=0;p<e.length;p++){let h=e[p];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[++p]:h?.startsWith("--scope=")?t=h.slice(8):h==="--concurrency"?s=i(e[++p]):h?.startsWith("--concurrency=")?s=i(h.slice(14)):h&&!h.startsWith("--")&&(n=h)}}let l=p=>p?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:l(t),path:l(n),preview:o,concurrency:s,rewrite:r}}function Bg(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function Hg(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Mi(e,t,n){return n.filter(o=>{try{return Fd(Wd(e,t,o)).size===0}catch{return!0}})}function Ui(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+=Fd(Wd(e,i)).size}catch{}return{path:r,bytes:s}})}function Fi(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 \u2014 its structure is NOT the target; match only the project's voice/terminology.
|
|
342
342
|
`:"";return`Run the write-article skill to author EACH documentation article listed below. For each path:
|
|
343
343
|
- 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).
|
|
344
344
|
- 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).
|
|
@@ -348,103 +348,102 @@ ${c[1]??" "}clipTo: ${p}${i.selector}${p},`);return h=h.replace(o,`${r}await ca
|
|
|
348
348
|
- Each article is independent. Do NOT write, edit, or publish any article not in this list, and do NOT publish to Document360 \u2014 these are local drafts.
|
|
349
349
|
Articles:
|
|
350
350
|
`+e.paths.map(r=>`- ${r}`).join(`
|
|
351
|
-
`)}function
|
|
352
|
-
`)}var
|
|
353
|
-
`)}var
|
|
351
|
+
`)}function Wi(e,t,n){let o=e.reduce((i,l)=>i+l.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: ${Ae(r)}\u2013${Ae(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function Bi(e,t,n){let o=R=>t[R.index]?.paths.length??0,r=e.filter(R=>R.ok),s=e.filter(R=>!R.ok),i=e.reduce((R,C)=>R+o(C),0),l=r.reduce((R,C)=>R+o(C),0),p=e.reduce((R,C)=>R+C.costUsd,0),h=e.reduce((R,C)=>R+C.outputTokens,0),b=n==="api"?`${Ae(p)} total`:bt(h),$=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,v=R=>`${R} article${R===1?"":"s"}`,E=[];if(s.length===0)E.push(`Wrote ${v(i)} (${$}) successfully \xB7 ${b}.`),E.push("Next \u2014 push them to Document360:"),E.push("/publish --all"),E.push("Or add screenshots first with /screenshot author --all. Drafts are reviewable in the portal after publishing.");else{E.push(`Wrote ${l}/${v(i)} (${$}) \xB7 ${b}.`),E.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let R of s)E.push(` \u2717 ${R.label}${R.error?` \u2014 ${R.error}`:""}`)}return E}function Hi(e,t,n){try{let o=jg({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) \u2014 /check --fix corrects them.`}catch{return null}}function qi(e,t,n){let o=(Bd(e)?.docsDir??Og).replace(/\/+$/,""),r=t.map(l=>l.path);if(n.path){let l=Bg(n.path,o);return r.includes(l)?{docsDir:o,targets:[l],planCount:r.length}:{docsDir:o,targets:[],planCount:r.length,reason:`"${l}" isn't in the docs plan (.d360-writer/plan.json).`}}let s=Hg(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=Mi(e,o,s);if(i.length===0){let l=n.scope?` under "${n.scope}"`:"",p=n.scope?` --scope ${n.scope}`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${l} are already written. Use /write <path> to rewrite one, or /write${p} --rewrite to regenerate them all.`}}return{docsDir:o,targets:i,planCount:r.length}}async function Hd(e,t){if(!Bd(t.cwd))return console.log(A("No d360-writer config here. Run /init first.")),{kind:"continue"};if(_r(e)){for(let I of Md(t.cwd,t.profileName))console.log(g(I));return{kind:"continue"}}if(Ct("write",e)){let I=Sn(t.cwd,"write",e,t.profileName);if(I.length>0){for(let z of I)console.log(g(z));return{kind:"continue"}}}let n=Ig(t.cwd);if(n.length===0)return console.log(A("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};let{scope:o,path:r,preview:s,concurrency:i,rewrite:l}=_i(e),{docsDir:p,targets:h,reason:b,rewriting:$}=qi(t.cwd,n,{scope:o,path:r,rewrite:l});if(h.length===0)return console.log(b?H(b):H("Nothing to write.")),{kind:"continue"};$&&console.log(H(`--rewrite: regenerating ${h.length} already-written article${h.length===1?"":"s"} (overwrites them; git has your baseline).`));let v=Ng(h),E=Li(i),{model:R,forced:C}=Lg(t.cwd,"standard"),T=!!r;if(s&&!T){let I=Ag({files:Ui(t.cwd,n,h),op:"write",model:R});o&&console.log(g(`Scope: ${o} (${h.length} pending).`));for(let z of Wi(v,I,E))console.log(z);return console.log(g(`Model: ${R}${C?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(g(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}console.log(g(`Writing ${h.length} article${h.length===1?"":"s"} across ${v.length} partition${v.length===1?"":"s"} (\u2264${E} agents at once) on ${R}\u2026`)),console.log(g(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let I of _g({cwd:t.cwd,partitions:v,promptFor:z=>Fi(z,p,{rewrite:$||T}),concurrency:E,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:R}))if(I.type==="partition_status")I.status==="running"?console.log(g(` \u25B8 ${I.label} \u2014 writing\u2026`)):I.status==="done"?console.log(U(` \u2713 ${I.label}`)):console.log(A(` \u2717 ${I.label}`));else if(I.type==="run_done"){console.log("");let z=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let K of Bi(I.results,v,z))console.log(I.ok?U(K):H(K));if(I.ok)try{Mg(t.cwd,h.map(K=>`${p}/${K}`),{writtenCap:Ug})}catch{}let V=Hi(t.cwd,p,h);V&&console.log(H(V))}}catch(I){console.log(A(`Write run failed: ${I.message}`))}return console.log(""),{kind:"continue"}}X();import{existsSync as qg,readdirSync as qd,statSync as Vd}from"node:fs";import{join as Gd}from"node:path";import{inputDir as Vg,readProjectConfig as Gg}from"document360-engine";var Yd=/\.(md|markdown|pdf|txt)$/i;function Vi(e){let t=Vg(e);if(!qg(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of qd(t)){let s=Gd(t,r),i=!1;try{i=Vd(s).isDirectory()}catch{continue}if(i){if(r.startsWith("."))continue;let l=Yg(s);l>0&&n.push({name:r,docCount:l})}else Yd.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function Yg(e){let t=0;for(let n of qd(e))try{Vd(Gd(e,n)).isFile()&&Yd.test(n)&&t++}catch{}return t}function Gi(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 Mr(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 \u2014 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(`
|
|
352
|
+
`)}var Yi="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function zd(e,t){let n=t?.cwd??process.cwd();if(!Gg(n))return console.log(A("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=Vi(n);if(o.length===0&&r===0)return console.log(g(Yi)),{kind:"continue"};let s=e.join(" ").trim();if(!s){if(o.length>1){console.log(g("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let p of o)console.log(` ${p.name} ${g(`(${p.docCount} doc${p.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let l=o[0]?.name??"";return{kind:"forward-to-agent",prompt:Mr(l),display:l?`/draft ${l}`:"/draft"}}let i=Gi(o,s);return{kind:"forward-to-agent",prompt:Mr(i??"",i?void 0:s),display:`/draft ${s}`}}X();import{listOpenForDocs as zg,readProjectConfig as Kg}from"document360-engine";function zi(e){try{return zg(e).filter(t=>t.kind==="request").length}catch{return 0}}function Ki(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function Xi(e,t=!1){let n=["Run the document-handoff skill.",""];return e?n.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 \u2014 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."):n.push("No description was given \u2014 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."),n.push("","Draft only \u2014 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&&n.push("","After the drafts exist and the user confirms any bulk gate, publish the new/updated articles to","Document360 (the publish-to-d360 skill). On a production profile, respect the write-guard."),n.join(`
|
|
353
|
+
`)}var Qi="Nothing to document yet. Say what changed: /document <what you shipped> \u2014 or have the builder drop a request via their /devhints hand-off.";async function Kd(e,t){let n=t?.cwd??process.cwd();if(!Kg(n))return console.log(A("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=Ki(e);if(!r&&zi(n)===0)return console.log(g(Qi)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:Xi(r,o),display:s}}X();import{search as Xg}from"@inquirer/prompts";import{findByName as Qg,getSession as Jg,listSessions as Zg,relativeTime as Qd}from"document360-engine";async function Jd(e,t){let n=Zg(t.cwd).filter(o=>o.uuid!==t.currentUuid());if(n.length===0)return console.log(g("No saved sessions for this repo yet \u2014 sessions auto-save as you work.")),{kind:"continue"};if(e.length>0){let o=e.join(" "),r=Qg(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(A(`No session matches "${o}".`)),Xd(n),{kind:"continue"})}if(!process.stdin.isTTY)return Xd(n),console.log(g("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>Xg({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let i=(s??"").toLowerCase();return n.filter(l=>!i||l.name.toLowerCase().includes(i)||l.firstPrompt.toLowerCase().includes(i)).map(l=>({name:`${l.name} ${Qd(l.updatedAt)}`,value:l.uuid,description:l.firstPrompt.slice(0,100)}))}})),r=Jg(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function Xd(e){console.log("");for(let t of e.slice(0,15))console.log(` ${W(t.name)} ${g(Qd(t.updatedAt))}`),console.log(` ${g(t.firstPrompt.slice(0,80))}`);console.log("")}X();import{renameSession as ey}from"document360-engine";function Ji(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 Zd(e,t){let n=Ji(e.join(" "));if(!n)return console.log(A("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(ey(o,n)?console.log(U(`\u2713 Session renamed to "${n}"`)):console.log(A("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(U(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as eu,readProjectConfig as ty,writeProjectConfig as ny}from"document360-engine";X();function Zi(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=ty(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 eu().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},ny(o,e),null):`Unknown environment "${r}". Known: ${eu().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function tu(e,t){let n=e[0];if(!n)return nr(t.cwd),{kind:"continue"};if(n==="add"){let o=Zi(t.cwd,e[1],e[2]);return o?(console.log(A(o)),{kind:"continue"}):(console.log(U(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${W(`/profile ${e[1]}`)} then ${W("/login")}`),{kind:"continue"})}return or(t.cwd,n),rr(t.cwd,n),console.log(g(" Restarting agent for the new profile\u2026")),{kind:"clear"}}X();import{select as oy}from"@inquirer/prompts";import{readProjectConfig as ry,readUserConfig as nu,resolveModelSetting as ea,writeUserConfig as ou}from"document360-engine";var Ze=[{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 Ur(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=Ze.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function sy(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 lo(e,t){let n=()=>ea(e).model;if(t==="default"){let s=nu();return s.defaultModel?(delete s.defaultModel,ou(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${ea(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}}ou({...nu(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=ry(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 ru(e,t){let n=e[0]?.trim();if(!n){let i=ea(t.cwd);if(!process.stdin.isTTY)return console.log(`${Ee("Model:")} ${W(i.model)}${i.source==="auto"?g(" (auto)"):""}`),console.log(g(` source: ${sy(i)}`)),console.log(g(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let l=Ur(i),p;try{p=await t.withPausedInput(()=>oy({message:`Select model (current: ${i.model}${i.source==="auto"?" \xB7 auto":""})`,default:Ze[l].value,choices:Ze.map((v,E)=>({name:`${v.label}${E===l?" \u2714":""}`,value:v.value,description:v.desc}))}))}catch{return console.log(g("Cancelled.")),{kind:"continue"}}let{lines:h,changed:b,effective:$}=lo(t.cwd,p??"default");for(let v of h)console.log(v.startsWith("\u26A0")?H(v):v.startsWith("\u2713")?U(v):g(v));return b&&await t.setModel($),{kind:"continue"}}let{lines:o,changed:r,effective:s}=lo(t.cwd,n);for(let i of o)console.log(i.startsWith("\u26A0")?H(i):i.startsWith("\u2713")?U(i):g(i));return r&&await t.setModel(s),{kind:"continue"}}Fr();async function du(e,t){return await t.withPausedInput(()=>mn(t.cwd)),{kind:"clear"}}async function uu(e,t){return await t.withPausedInput(()=>Jo(t.cwd,t.profileName)),{kind:"clear"}}X();import{resolveActiveProfile as Cy}from"document360-engine";async function pu(e,t){let n=!1;try{n=Cy(t.cwd).production}catch{}return n?(console.log(H("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(g("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}X();var hu=async(e,t)=>{try{await t.withPausedInput(()=>tr({}))}catch(n){console.log(A(`Login failed: ${n.message}`))}return{kind:"continue"}};X();import{resolveActiveProfile as Ry,clearTokens as Sy,clearProfileProject as Py}from"document360-engine";async function fu(e,t){let n;try{n=Ry(t.cwd,t.profileName).name}catch(r){return console.log(A(r.message)),{kind:"continue"}}let o=Sy(n);return Py(t.cwd,n),console.log(o?U(`\u2713 Signed out of "${n}" and cleared its project/workspace selection.`):g(`Profile "${n}" was not signed in. Cleared any project/workspace selection.`)),console.log(g("Run /login to sign in and pick a project.")),{kind:"continue"}}import{spawn as gu}from"node:child_process";import{existsSync as oa,readFileSync as na,statSync as Oy}from"node:fs";import{homedir as Ly}from"node:os";import{basename as _y,join as fo}from"node:path";import{readProjectConfig as My,DEFAULT_OUTPUT_DIR as Uy,existingAnnotatedShotPath as Fy,resolveOutputDir as Wy}from"document360-engine";import je from"picocolors";import{annotationsPath as Ty,resolveOutputDir as Dy,readProjectConfig as Ey,DEFAULT_OUTPUT_DIR as Ay,existingAnnotatedShotPath as jy}from"document360-engine";function Ny(e){let n=e.filter(o=>o!=="--all"&&o!=="-a").find(o=>!o.startsWith("-"));return n?{mode:"single",id:n}:{mode:"all"}}function uo(e){return e.filter(t=>t.state==="captured").map(t=>t.id)}function Gt(e,t){let n=Dy(e,Ey(e)?.outputDir??Ay),o=new Map(ve(e).map(i=>[i.id,i])),r=i=>i.replace(`${e}\\`,"").replace(`${e}/`,"").replace(/\\/g,"/"),s=t.map(i=>{let l=o.get(i)?.file??"(unknown article)";return[`- ${i}`,` image: ${r(jy(n,i))}`,` facts: ${r(Ty(n,i))}`,` article: ${l}`].join(`
|
|
354
354
|
`)}).join(`
|
|
355
355
|
`);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 \u2014 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 \u2014 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 \u2014 an exact receipt is printed from","your recorded verdicts right after your report, so any number you state can only contradict it."].join(`
|
|
356
|
-
`)}function
|
|
357
|
-
`)}function
|
|
358
|
-
`):
|
|
359
|
-
`)}var
|
|
360
|
-
`)}function
|
|
361
|
-
/screenshot list --detail shows what each one needs`}function
|
|
362
|
-
`),cmd:o.length>0?`/screenshot ${
|
|
363
|
-
`),display:"/screenshot checklist"}}var
|
|
364
|
-
`)}async function
|
|
365
|
-
`)}var
|
|
366
|
-
`).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function
|
|
356
|
+
`)}function po(e){return`${ge("\u2192",je.blue)}Verifying ${e} new screenshot${e===1?"":"s"} (reading each image)\u2026`}var Iy=(e,t=88)=>{let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n};function ho(e,t){if(t.length===0)return[];let n=lt(e).shots,o=[],r=[],s=[];for(let l of t){let p=n[l]?.review;p?p.verdict==="ok"?o.push(l):r.push({id:l,reason:p.reason??"no reason recorded",repaired:!!p.repaired}):s.push(l)}let i=[""];if(i.push(`${ge("\u2714",je.green)}${je.green(`${o.length} verified`)}`+(r.length>0?` ${je.magenta(`\u2691 ${r.length} flagged`)}`:"")+(s.length>0?` ${je.yellow(`? ${s.length} not verified`)}`:"")+je.gray(` ${t.length} shot${t.length===1?"":"s"} in this pass`)),r.length>0){let l=Math.max(...r.map(h=>h.id.length));for(let h of r)i.push(` ${je.magenta(h.id.padEnd(l))} ${je.gray(Iy(h.reason))}`);let p=r.filter(h=>h.repaired).length;i.push(`${ge("\u2192",je.magenta)}Re-capture the ${r.length} flagged: ${je.bold("/screenshot capture --failed")}`+(p<r.length?je.gray(` (${r.length-p} still need${r.length-p===1?"s":""} a spec fix first)`):""))}return s.length>0&&i.push(`${ge("\u26A0",je.yellow)}No verdict recorded for ${s.slice(0,3).join(", ")}${s.length>3?`, +${s.length-3}`:""} \u2014 still awaiting verification. Run ${je.bold("/screenshot verify")} again.`),i}async function mu(e,t){let n=t?.cwd??process.cwd(),o=no(n);o&&console.log(o);let r=ve(n),s=Ny(e);if(s.mode==="single"){let l=r.find(p=>p.id===s.id);return l?["captured","verified","rejected"].includes(l.state)?{kind:"forward-to-agent",prompt:Gt(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=uo(r);if(i.length===0){let l=r.filter(h=>h.state==="verified").length,p=r.filter(h=>h.state==="rejected").length;return console.log(p>0?`Nothing left to verify. ${p} shot${p===1?"":"s"} failed verification \u2014 re-capture with: /screenshot capture --failed`:l>0?`All ${l} captured shot${l===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:Gt(n,i),display:"/screenshot verify"}}var By=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function ra(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:By(t),retryBlocked:n}:{mode:"single",id:t}:{mode:"picker"}}function mo(e,t){let n=ve(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 yu(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}),kr(o,t,"capture"),mi(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,l)=>i.id.localeCompare(l.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 sa(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([...Mc(e).filter(r=>n.has(r)),...o])].sort()}function ia(e,t){let n=e.length;if(n===0)return null;let o=oo(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(`
|
|
357
|
+
`)}function Hy(e,t){let n=My(e)?.outputDir??Uy;return Fy(Wy(e,n),t)}function aa(e,t,n,o){let r=Hy(e,t);return oa(r)&&Oy(r).mtimeMs>=o?"captured":n===0?"skipped":"failed"}function wu(e){let t=/⊘[^\n—]*—\s*(.+)/.exec(e);return t?t[1].trim():null}var qy=/element is not (?:enabled|visible|stable|editable)|intercepts pointer events|outside of the viewport|element is not attached/i;function ku(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=>qy.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(`
|
|
358
|
+
`):la(e)}function la(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(`
|
|
359
|
+
`)}var Vy=/^[A-Za-z0-9._-]+$/;function ca(e){return new Promise((t,n)=>{if(!Vy.test(e.id)){n(new Error(`Not a valid spec id: "${e.id}"`));return}let o=gu(`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 bu(e,t=Ly()){try{let n=JSON.parse(na(fo(e,".d360-writer","capture.json"),"utf8").replace(/^/,"")),o=n.projectId;if(!o)try{o=JSON.parse(na(fo(e,"package.json"),"utf8")).name}catch{}o||=_y(e);let r=Object.keys(n.profiles??{}),s=n.defaultProfile??(r.length===1?r[0]:r.includes("staging")?"staging":r[0]);return s?oa(fo(t,".document360-capture","auth-states",o,`${s}.json`)):!0}catch{return!0}}function $u(e){return new Promise((t,n)=>{let o=gu("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 da(e,t){return e===127||/is not recognized as an internal or external command|command not found/i.test(t)}function vu(e){try{let t=JSON.parse(na(fo(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 Br(e){return oa(fo(e,".d360-writer","capture.json"))}function ua(){return["Screenshot capture is not configured in this repo yet (no `.d360-writer/capture.json`). Set it up","conversationally \u2014 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 \u2014 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 \u2014 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` \u2014 add/update 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(`
|
|
360
|
+
`)}function xu(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(", ")}
|
|
361
|
+
/screenshot list --detail shows what each one needs`}function Cu(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):Wr(r?.reason)!==Wr(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):Sr(r?.reason??"")!==Sr(o.detail??"")?n.blockedNewReason.push(o.id):n.blockedAsBefore.push(o.id))}return n}function Wr(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 Ru(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?Rn(o.detail):"no reason recorded"}`)}function Pn(e,t=2){return e.length<=t?e.join(" \xB7 "):`${e.slice(0,t).join(" \xB7 ")} \xB7 +${e.length-t}`}function Su(e,t){if(!t)return[];let n=[],o=(i,l,p,h)=>{l>0&&n.push({glyph:i,label:`${l} ${p}`,tail:h})};if(o("\u2713",e.newlyCaptured.length,"newly captured",Pn(e.newlyCaptured)),o("\u2717",e.newlyBroken.length,"newly broken",Pn(e.newlyBroken)),o("\u2192",e.repairedNowBlocked.length,"repaired",`no longer broken \u2014 only data stands in the way \xB7 ${Pn(e.repairedNowBlocked)}`),o("\u2298",e.newlyBlocked.length,"newly blocked",Pn(e.newlyBlocked)),o("\u2192",e.blockedNewReason.length,"blocked on something new",`an earlier step now passes \xB7 ${Pn(e.blockedNewReason)}`),o("\u2192",e.brokeDifferently.length,"broken differently",`the previous cause is fixed \xB7 ${Pn(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 Pu(e){let t=e.results.filter($=>$.outcome==="captured"),n=e.results.filter($=>$.outcome==="skipped"),o=e.results.filter($=>$.outcome==="failed"),r=$=>$===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",l=o[0]?.id,p=[];o.length>0&&p.push({glyph:"\u2717",cmd:`/screenshot ${l}`,why:`re-author the ${o.length===1?"broken spec":`first of ${o.length} broken specs`} \u2014 re-running fails the same way`}),n.length>0&&p.push({glyph:"\u2298",cmd:"/screenshot list",why:`what to stage for the ${n.length} blocked shot${r(n.length)}`}),t.length>0&&p.push({glyph:"\u2713",cmd:s,why:`embed the ${t.length} new PNG${r(t.length)}`});let h=Math.max(...p.map($=>$.cmd.length));return{note:p.map($=>`${$.glyph} ${$.cmd.padEnd(h)} ${$.why}`).join(`
|
|
362
|
+
`),cmd:o.length>0?`/screenshot ${l}`:t.length>0?s:i,tone:o.length>0?"warn":"info"}}function Tu(e,t){let n=new Map(ve(e).map(o=>[o.id,o.file]));return[...new Set(t.map(o=>n.get(o)).filter(o=>!!o))].sort()}async function pa(e,t){let n=t?.cwd??process.cwd(),o=ra(e);if(!Br(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:l}=mo(n,o.mode==="scope"?o.scope:void 0),p=sa(n,l),h=(o.mode==="all"||o.mode==="scope")&&o.retryBlocked,b=o.mode==="single"?[o.id]:o.mode==="failed"?p:o.mode==="blocked"?i:o.mode==="picker"?r:[...r,...s,...h?i:[]];if(b.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 C=ia(l.filter(T=>T.state==="blocked"),"/screenshot capture --blocked");C&&console.log(C)}let $=Date.now(),v=[];for(let C of b){console.log(`\u25B6 ${C}`);try{let{exitCode:T}=await ca({cwd:n,id:C,stdio:"inherit"});v.push({id:C,outcome:aa(n,C,T,$)})}catch(T){if(T.code==="ENOENT")return console.log("d360-capture is not installed. Run: npm i -g document360-capture"),{kind:"continue"};v.push({id:C,outcome:"failed",detail:T.message})}}let E=C=>v.filter(T=>T.outcome===C).length;console.log(`\u2713 ${E("captured")} captured \xB7 \u2298 ${E("skipped")} skipped \xB7 \u2717 ${E("failed")} failed`);let R=v.filter(C=>C.outcome==="captured");return mr(n,v.map(C=>({id:C.id,outcome:C.outcome,reason:C.detail,specSource:Cn(n,C.id)})),new Date().toISOString()),R.length>0?(console.log(po(R.length)),{kind:"forward-to-agent",prompt:Gt(n,R.map(C=>C.id)),display:"/screenshot verify"}):{kind:"continue"}}import{builderChannelWired as Gy,readTestidRequests as Yy,testidHandoffPrompt as zy,testidRequestPaths as Ky}from"document360-engine";async function Tn(){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."].join(`
|
|
363
|
+
`),display:"/screenshot checklist"}}var Du="-".repeat(64);function Eu(e){let t=Yy(e);if(t.length===0)return null;let{mdRel:n}=Ky(e),o=t.length,r=new Set(t.map(p=>p.file).filter(Boolean)).size,s=`${o} data-testid attribute${o===1?"":"s"}`,i=`${r} source file${r===1?"":"s"}`,l=zy(e,o);return Gy(e)?{prompt:l,lines:[`\u{1F4CB} Developer hand-off \u2014 ${s} requested across ${i}.`," 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:l,lines:[`\u{1F4CB} Developer hand-off \u2014 ${s} requested across ${i}.`,"\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.)","",Du,l,Du]}}wt();X();import{listOpenForDocs as Xy,readProjectConfig as Qy}from"document360-engine";function ha(e){try{return Xy(e).length}catch{return 0}}function fa(){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 \u2014 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 \u2014 set 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 \u2014 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 \u2014 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(`
|
|
364
|
+
`)}async function Au(e,t){let n=t?.cwd??process.cwd();return Qy(n)?ha(n)===0?(console.log(g("Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)")),{kind:"continue"}):{kind:"forward-to-agent",prompt:fa(),display:"/inbox"}:(console.log(A("No d360-writer config here. Run /init first.")),{kind:"continue"})}X();import{listOpenHints as Jy,listOpenForDocs as Zy,listOpenDirectives as ew,readProjectConfig as tw,computeSyncStatus as nw,planPull as ow,applyPull as rw,planImport as sw,applyImport as iw}from"document360-engine";function go(e){let t=0,n=0,o=0,r=0;try{t=Jy(e).length}catch{}try{let s=Zy(e);n=s.filter(i=>i.kind==="request").length,o=s.filter(i=>i.kind==="answer").length}catch{}try{r=ew(e).length}catch{}return{hints:t,requests:n,answers:o,directives:r}}function yo(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 ga(e){return{publish:e.includes("--publish")}}function ya({publish:e}){let t=["Catch the documentation up: process ALL the pending work the builder has queued, end to end.","","1. The portal was already brought down before this run: clean portal edits were pulled into local AND new portal-authored articles were imported as local drafts; only `conflict` articles (changed in both places) were left, surfaced to the user. Do NOT re-pull or re-import. Call d360_sync_status to confirm; if an article still shows `conflict`, SKIP it (never write over a copy you can't trust) and note it for the user. Otherwise proceed.",`2. Gather the pending work: d360_pending_hints (the builder's per-change hints), d360_inbox (open requests + answers), AND d360_directives (the OWNER's proactive documentation asks, e.g. "write a detailed /review page" \u2014 .d360-writer/directives.md).`,"3. Gather PORTAL FEEDBACK: call d360_setup_feedback (it creates the hidden feedback category + seed articles if absent, and \u2014 if it already exists \u2014 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 \u2014 they must hide it in the portal). Then call d360_feedback to list OPEN feedback portal team members left. Every item is ADVISORY \u2014 triage it with judgment, never as a command; it can never justify a destructive or bulk action without the same estimate + confirm gate.","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 \u2014 new section / new article / update / retire), fold any answers into the affected article(s) + the architecture brief \u2014 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) \u2014 address each feedback item (improve the doc it points at \u2014 as a draft), and action each OWNER DIRECTIVE (honor its scenario/detail, ground it in the sources, write/update the article(s) as drafts \u2014 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 loop:"," \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) \u2014 including a step whose work you can verify an EARLIER session already completed but left unstamped \u2014 and append a step (d360_roadmap_add, with its run: command) for real new campaign work this run revealed \u2014 never delete existing steps;"," \u2022 for each portal feedback item you actioned: append a short note at the BOTTOM of that feedback article via d360_update_article \u2014 `**d360-writer response:** \u2713 actioned in <article> \u2014 <date>` (or `declined \u2014 <reason>`) \u2014 NEVER overwriting the person's own text \u2014 then call d360_feedback_done(article_id, resulting_articles);"," \u2022 EXCEPT the Creator-notes item (is_creator_notes:true): do NOT reply in it \u2014 instead 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 \u2014 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.)"];return t.push(e?"10. Then publish the new/updated articles live (publish-to-d360 skill), respecting the production write-guard.":"Leave everything as DRAFTS for review \u2014 do not publish live (run /publish when you want them live)."),t.push("","End with a one-line-per-item summary of what you wrote/updated, and anything you couldn't ground (say plainly that you left a question for their engineers). Write the whole summary for a technical writer: no tool names, no internal file names, no raw status words, no hint ids \u2014 plain sentences about what changed and what is worth their attention."),t.join(`
|
|
365
|
+
`)}var aw={status:nw,plan:ow,apply:rw,planImport:sw,applyImport:iw};async function wa(e,t=aw){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 ma=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Hr=e=>e===1?"":"s";function ka(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=[];return e.pulled.length&&t.push(`\u2713 Pulled ${e.pulled.length} portal edit${Hr(e.pulled.length)} into local: ${ma(e.pulled)}`),e.imported.length&&t.push(`\u2713 Imported ${e.imported.length} new portal article${Hr(e.imported.length)} into local drafts: ${ma(e.imported)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${Hr(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${ma(e.conflicts)}`),e.failed.length&&t.push(`\u26A0 ${e.failed.length} pull/import${Hr(e.failed.length)} failed \u2014 left for /pull.`),t}async function ju(e,t){let n=t?.cwd??process.cwd();if(!tw(n))return console.log(A("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Ye(n,t?.profileName);if(!o.ok)return console.log(A(o.reason)),{kind:"continue"};let{publish:r}=ga(e);console.log(g("Reconciling with Document360 (pulling any portal changes)\u2026"));let s=await wa({cwd:n,profileName:t?.profileName});for(let l of ka(s))console.log(l.startsWith("\u2713")?U(l):l.startsWith("\u2139")?g(l):H(l));let i=yo(go(n));return console.log(g(i?`Catching up on ${i}\u2026`:"Checking for code changes the builder didn't hint\u2026")),{kind:"forward-to-agent",prompt:ya({publish:r}),display:`/catch-up${r?" --publish":""}`}}X();import{spawn as Nu}from"node:child_process";var Dn="document360-writer",qr=`npm i -g ${Dn}@latest`,lw="document360-capture";function cw(){return new Promise(e=>{try{let t=Nu("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 Vr(){let e=process.platform==="win32",n=await cw()?[Dn,lw]:[Dn];return new Promise(o=>{try{let r=Nu(`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 Iu(){console.log(g("Updating the d360-writer toolchain\u2026"));let e=await Vr();return e.ok?console.log(U(`\u2713 Updated ${e.packages.join(" + ")}. Exit (/exit) and relaunch d360-writer to apply.`)):console.log(A(`Update failed \u2014 run manually: ${qr}`)),{kind:"continue"}}X();wt();import{existsSync as ba,rmSync as dw}from"node:fs";import{basename as Ou,resolve as $a}from"node:path";import{execFileSync as uw}from"node:child_process";import{input as pw}from"@inquirer/prompts";import{readProjectConfig as hw,devHintsGuidePath as fw}from"document360-engine";var mw=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],gw=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),Gr=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),Lu=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function _u(e){let t=Gr(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:Lu(t)?!0:gw.has(t)}function va(e){let t=null;try{t=hw(e)}catch{t=null}let n=new Set(mw);for(let o of[Gr(t?.docsDir),Gr(t?.captureDir),Gr(t?.outputDir)])o&&Lu(o)&&n.add(o);return[...n].filter(o=>_u(o)&&ba($a(e,o)))}function xa(e,t){let n=[],o=[];for(let r of t){if(!_u(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{dw($a(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function Mu(e,t){try{return uw("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
|
|
366
|
+
`).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function yw(e){return Mu(e,".d360-writer/hints")}function ww(e){return Mu(e,".d360-writer/messages")}function Ca(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=yw(e),o=ww(e),r=ba($a(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: ${Ou(e)}`]}async function Uu(e,t){let n=va(t.cwd);for(let p of Ca(t.cwd,n))console.log(n.length===0?g(p):p);if(n.length===0)return{kind:"continue"};let o=Ou(t.cwd);if((await t.withPausedInput(()=>pw({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(H("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=ba(fw(t.cwd)),{removed:i,failed:l}=xa(t.cwd,n);console.log(U(`\u2713 Reset complete \u2014 removed ${i.length} item${i.length===1?"":"s"}. The repo is back to its original state.`));for(let p of l)console.log(A(` \u2717 ${p.path}: ${p.error}`));if(s){for(let p of dr())console.log(p);console.log(g("(Select and copy the prompt above to paste into your coding agent.)"))}return console.log(g("Set up d360-writer again with /init (then /login, /workspace).")),{kind:"continue"}}X();import{lintDocs as kw}from"document360-engine";function Yr(e){if(e.length===0)return["\u2713 No issues found \u2014 no leaked internals, unknown commands, stale version facts, or AI-tells 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):`];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 Ra(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 \u2014 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 \u2014 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.","- stray-file: a junk *.publish.md file (a publish transform wrongly written to disk). DELETE the file \u2014",' 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}" \u2014 ${s.message}`)].join(`
|
|
367
367
|
`)).join(`
|
|
368
368
|
`)].join(`
|
|
369
|
-
`)}async function
|
|
370
|
-
`);return{prompt:
|
|
371
|
-
`),display:`/reorder${n?` ${n}`:""}`}}async function
|
|
369
|
+
`)}async function Fu(e,t){let n=e.includes("--fix"),o=e.find(i=>!i.startsWith("--")),r=o?` ${o}`:"",s=kw({cwd:t.cwd,scope:o});if(n)return s.length===0?(console.log(U("\u2713 Nothing to fix \u2014 the docs are already clean.")),{kind:"continue"}):(console.log(g(`Fixing ${s.length} doc issue${s.length===1?"":"s"} (run /check again after to confirm)\u2026`)),{kind:"forward-to-agent",prompt:Ra(s),display:`/check${r} --fix`});console.log(g("Linting the docs (engine internals, unknown commands, stale facts, AI-tells)\u2026"));for(let i of Yr(s))console.log(s.length===0?U(i):H(i));return s.length>0&&console.log(g("Run /check --fix to have the agent correct these.")),console.log(""),{kind:"continue"}}X();import{lintDocs as Rw,loadStyleGuide as Sw,buildReviewPrompt as Pw,readProjectConfig as Tw,DEFAULT_DOCS_DIR as Dw}from"document360-engine";X();import{readProjectConfig as bw,loadProfileMap as $w,resolveActiveProfile as vw,desiredCategoryOrder as xw,desiredArticleOrder as Cw}from"document360-engine";function Wu(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}var Bu=e=>e.replace(/\\/g,"/").split("/").pop()??e;function wo(e,t){try{if(!bw(e))return[];let n=vw(e,t),o=$w(e,n.name);if(!o)return[];let r=new Map;for(let i of Cw(o)){let l=r.get(i.categoryPath);l?l.push(i):r.set(i.categoryPath,[i])}let s=[];for(let i of xw(o)){s.push(Wu(Bu(i.path)));for(let l of(r.get(i.path)??[]).sort((p,h)=>p.order-h.order))s.push(` ${Wu(Bu(l.path))}`)}return s}catch{return[]}}async function Hu(e,t){let n=wo(t.cwd,t.profileName);if(n.length===0)return console.log(g("No documentation structure yet \u2014 run /init and author some articles first.")),{kind:"continue"};console.log(W("Documentation order (categories \u2192 articles):"));for(let o of n)console.log(o);return console.log(""),{kind:"continue"}}function Sa(e,t){let n=Tw(e);if(!n)return null;let o=(n.docsDir??Dw).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),s=t.find(b=>!b.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),i=Rw({cwd:e}),l=s?i.filter(b=>b.path===`${o}/${s}`||b.path.startsWith(`${o}/${s}/`)):i,p=s?"":wo(e).join(`
|
|
370
|
+
`);return{prompt:Pw({docsRoot:o,scope:s,styleGuide:Sw(e),deterministicFindings:l,fix:r,structure:p||void 0}),display:`/review${s?` ${s}`:""}${r?" --fix":""}`}}async function qu(e,t){if(Ct("review",e)){let o=Sn(t.cwd,"review",e,t.profileName);if(o.length>0){for(let r of o)console.log(g(r));return{kind:"continue"}}}let n=Sa(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(A("No d360-writer config here. Run /init first.")),{kind:"continue"})}X();import{readProjectConfig as Ew}from"document360-engine";function Pa(e,t){if(!Ew(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 \u2014 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(`
|
|
371
|
+
`),display:`/reorder${n?` ${n}`:""}`}}async function Vu(e,t){if(Ct("reorder",e)){let o=Sn(t.cwd,"reorder",e,t.profileName);if(o.length>0){for(let r of o)console.log(g(r));return{kind:"continue"}}}let n=Pa(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(A("No d360-writer config here. Run /init first.")),{kind:"continue"})}X();import{readProjectConfig as Aw,writeProjectConfig as Gu,isAppType as jw,playbookSkillName as Nw,detectAppType as Yu}from"document360-engine";var zu=["web","cli","service","library"],Iw=new Set(["web","cli"]);function Ta(e){return Iw.has(e)?`${Nw(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function zr(e,t){let n=t.cwd,o=Aw(n);if(!o)return console.log(A("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let s=o.appType??Yu(n);if(s){let i=o.appType?"set in config":"auto-detected";console.log(`${W("Genre:")} ${s} (${i}) \u2014 ${Ta(s)}`)}else console.log(H("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(g(`Set it: /genre <${zu.join("|")}> \xB7 revert to auto-detect: /genre auto`)),{kind:"continue"}}if(r==="auto"||r==="clear"){if(!o.appType)return console.log(g("Already on auto-detect (no genre set in config).")),{kind:"continue"};let{appType:s,...i}=o;Gu(i,n);let l=Yu(n);return console.log(U(`\u2713 Genre reset to auto-detect \u2014 now: ${l?`${l} (${Ta(l)})`:"unclassified (no playbook)"} (applies from your next command).`)),{kind:"continue"}}return jw(r)?(Gu({...o,appType:r},n),console.log(U(`\u2713 Genre set to ${r} \u2014 ${Ta(r)} (applies from your next command).`)),{kind:"continue"}):(console.log(A(`Unknown genre "${r}". Choose one of: ${zu.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}X();import{listRoadmap as Kr,roadmapProgress as Ku,stampRoadmapDone as Ow}from"document360-engine";function Da(e){let t=Kr(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=Ku(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 Xr(e,t){let n=Kr(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:
|
|
372
372
|
${i.map(h=>` \u25CB ${h.title}`).join(`
|
|
373
373
|
`)}`};if(i.length===0)return{ok:!1,line:`No open step matches "${o}". Open steps:
|
|
374
374
|
${n.map(h=>` \u25CB ${h.title}`).join(`
|
|
375
|
-
`)}`};let
|
|
376
|
-
`):null}function
|
|
375
|
+
`)}`};let l=i[0].title;Ow(e,l,{doneAt:new Date().toISOString()});let p=Ku(e)?.next;return{ok:!0,line:`\u2713 Marked done: ${l}${p?` \u2014 next up: ${p.title}${p.run?` (${p.run})`:""}`:" \u2014 that was the last step: campaign complete."}`}}function Ea(e,t){let n=r=>r.trim().replace(/\s+/g," ").toLowerCase(),o=n(t);return o.startsWith("/")?Kr(e).find(r=>r.status==="open"&&!!r.run&&n(r.run)===o)??null:null}function Xu(e,t){let n=Ea(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(`
|
|
376
|
+
`):null}function Qu(e,t){let n=t.trim().toLowerCase();if(!n)return null;let o=Kr(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:
|
|
377
377
|
${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(`
|
|
378
|
-
`):null}async function
|
|
379
|
-
\u2022 `),lead:{kind:"cmd",cmd:"/catch-up",reason:n},picker:null,follow:"Then /catch-up clears what\u2019s queued for the docs."})}if(e.behind>0){let n=e.behind;t.push({key:"audit",bullet:`${n} code change${
|
|
380
|
-
`)];return o.length&&i.push(o.join(" ")),i.push(
|
|
381
|
-
|
|
382
|
-
`)}function
|
|
383
|
-
`).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let i=
|
|
384
|
-
`);return{lines:s.slice(0,t).map(i=>
|
|
385
|
-
`))console.log(i(` ${
|
|
386
|
-
|
|
387
|
-
`),console.log(`${U("\u25CF")} ${
|
|
388
|
-
`);let s=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(g(` (${
|
|
389
|
-
`),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){
|
|
390
|
-
`)}import{existsSync as
|
|
391
|
-
\u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close \xB7 d360-writer v${n} \xB7 engine v${o}`})]})}var
|
|
392
|
-
`)){let i=s.trim().replace(
|
|
393
|
-
`)}function
|
|
394
|
-
`)||e.length>200}function
|
|
395
|
-
`).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function
|
|
396
|
-
`)){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
|
|
397
|
-
`),s=0;for(let i=r.length-1;i>=0;i--){let
|
|
398
|
-
`),truncated:i>0||p>0}}}return{text:e,truncated:!1}}function
|
|
399
|
-
`)){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
|
|
378
|
+
`):null}async function Ju(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let r=Xr(n,e.slice(1).join(" ").trim());return console.log(r.ok?U(r.line):H(r.line)),{kind:"continue"}}let o=Da(n);console.log(W(o[0]??""));for(let r of o.slice(1))console.log(r.startsWith("(")?g(r):r);return{kind:"continue"}}var Zu={help:Ws,"?":Ws,clear:Xl,exit:Bs,quit:Bs,init:Ys,mcp:hr,publish:vd,audit:io,discover:xd,scope:Rd,pull:Ld,resolve:Nd,convert:_d,write:Hd,draft:zd,document:Kd,resume:Jd,rename:Zd,profile:tu,model:ru,doctor:co,workspace:du,project:uu,"allow-prod":pu,login:hu,logout:fu,screenshot:async(e,t)=>{let n=to(e);return n.mode==="capture"?pa(n.rest,t):n.mode==="verify"?mu(n.rest,t):n.mode==="checklist"?Tn():Tr(e,t)},capture:pa,"capture-setup":Tn,devhints:ac,inbox:Au,"catch-up":ju,update:Iu,reset:Uu,check:Fu,review:qu,reorder:Vu,structure:Hu,genre:zr,roadmap:Ju};function ep(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}wt();var Lw="Or just tell me what to write or update.",_w='\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 xe(e){return e===1?"":"s"}function Qr(e){return e.kind==="cmd"?`\u21E5 tab to run ${e.cmd} \xB7 or just ask me anything\u2026`:null}function ko(e){return e.kind==="cmd"?`I\u2019d start with ${e.cmd} \u2014 ${e.reason}.`:`Just tell me: \u201C${e.text}\u201D.`}var Mw={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 Uw(e){let t=[];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:Mw,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${xe(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${xe(e.directives)} waiting`),e.pendingText&&o.push(`your builder left ${e.pendingText}`),t.push({key:"catchup",bullet:o.join(`
|
|
379
|
+
\u2022 `),lead:{kind:"cmd",cmd:"/catch-up",reason:n},picker:null,follow:"Then /catch-up clears what\u2019s queued for the docs."})}if(e.behind>0){let n=e.behind;t.push({key:"audit",bullet:`${n} code change${xe(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${xe(n)}.`})}if(e.hasDocs&&e.pendingWrites>0){let n=e.pendingWrites;t.push({key:"write",bullet:`${n} planned article${xe(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${xe(n)}.`})}if(e.localAhead>0){let n=e.localAhead;t.push({key:"publish",bullet:`${n} article${xe(n)} changed locally \u2014 ready to publish`,lead:{kind:"cmd",cmd:"/publish",reason:`it pushes your ${n} local edit${xe(n)} up to Document360`},picker:null,follow:`Then /publish pushes your ${n} local edit${xe(n)} up.`})}if(e.conflicts>0){let n=e.conflicts;t.push({key:"resolve",bullet:`${n} article${xe(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${xe(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${xe(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).`})}if(e.uncommittedDocs>0){let n=e.uncommittedDocs;t.push({key:"commit",bullet:`\u26A0 ${n} uncommitted change${xe(n)} under .d360-writer/ \u2014 tell your coding agent: "commit d360-writer's work"`,lead:null,picker:null,follow:null})}return t}function tp(e){return e.find(t=>t.lead||t.picker)??null}function Aa(e,t){let n=tp(t),o=[];n?.lead?o.push(ko(n.lead)):n?.picker&&o.push("Pick the genre below \u2014 one keypress, and it shapes everything I write.");for(let l of t.filter(p=>p!==n).slice(0,2))l.follow&&o.push(l.follow);let r=o.join(" "),s=t.filter(l=>l.bullet).map(l=>{let p=l.lead?.kind==="cmd"?l.lead.cmd:null;return` \u2022 ${l.bullet}${p&&!r.includes(p)?` \u2014 ${p}`:""}`}),i=[[e,...s].join(`
|
|
380
|
+
`)];return o.length&&i.push(o.join(" ")),i.push(Lw),i.join(`
|
|
381
|
+
|
|
382
|
+
`)}function bo(e){if(!e.ready)return{kind:"idle"};let t=Uw(e);if(!e.hasDocs){let s=tp(t);return s&&(s.lead?.kind==="cmd"||s.picker)?{kind:"recommend",rec:{note:Aa("\u{1F4ED} No docs yet for this repo \u2014 here\u2019s where things stand:",t),tone:s.tone??"info",lead:s.lead,picker:s.picker}}:{kind:"recommend",rec:{note:_w,tone:"info",lead:{kind:"prompt",text:"write the docs for this repo",reason:"I\u2019ll read the code and draft a structure"},picker:null}}}if(t.length===0){let s=e.roadmap&&!e.roadmap.next?` Docs campaign complete \u2014 all ${e.roadmap.total} step${xe(e.roadmap.total)} done (/roadmap).`:"";return{kind:"recommend",rec:{note:`Welcome back. Your ${e.tracked} tracked article${xe(e.tracked)} for \u201C${e.profileName}\u201D are all in sync \u2014 /audit re-checks the code, /pull brings down portal edits.${s}`,tone:"info",lead:null,picker:null}}}let n=t.filter(s=>s.lead||s.picker),o=n[0]??null;return o?(o.key==="audit"||n[1]?.key==="audit")&&e.behind>0&&e.autoAudit&&e.allowAutoAudit?{kind:"autoAudit",note:`\u{1F4CB} ${e.behind} code change${xe(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`}:{kind:"recommend",rec:{note:Aa("Welcome back \u2014 where your docs stand:",t),tone:o.tone??"info",lead:o.lead,picker:o.picker}}:{kind:"recommend",rec:{note:Aa("Welcome back \u2014 where your docs stand:",t),tone:"info",lead:null,picker:null}}}import{existsSync as ja,readdirSync as Ia}from"node:fs";import{spawnSync as Fw}from"node:child_process";import{join as Jr}from"node:path";import{readProjectConfig as op,resolveActiveProfile as rp,loadTokens as Ww,isExpired as Bw,loadProfileMap as sp,localAheadPaths as Hw,loadKnownConflicts as qw,readDocsPlan as Vw,devHintsGuidePath as Gw,DEFAULT_DOCS_DIR as Na,roadmapProgress as Yw,listRoadmap as zw,readProductBriefState as Kw,reconcileCommitRequest as Xw,reconcileTestidRequest as Qw}from"document360-engine";wt();function np(e){try{return Ia(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function Oa(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>np(Jr(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&np(Jr(e,o)))}function La(e,t){try{let n=op(e);if(!n)return!1;let o=rp(e,t),r=sp(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=Jr(e,(n.docsDir??Na).replace(/\/+$/,""));return!!(ja(s)&&Ia(s).length>0||ja(Gw(e)))}catch{return!1}}function $o(e,t,n){try{let o=op(e);if(!o)return null;let r=rp(e,t),s=Ww(r.name),i=!!s&&(!Bw(s)||!!s.refreshToken),l=La(e,t)||!Oa(e,o.authoritativeSourceFiles),p=sp(e,r.name),h=p?Object.keys(p.articles).length:0,b=Jr(e,(o.docsDir??Na).replace(/\/+$/,"")),$=!1;try{$=ja(b)&&Ia(b).length>0}catch{}let v=0;if(p?.lastAnalyzedCommit)try{let Y=Fw("git",["rev-list","--count",`${p.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});Y.status===0&&(v=parseInt((Y.stdout||"").trim(),10)||0)}catch{}let E=0;try{let Y=Vw(e);if(Y.length>0){let pe=(o.docsDir??Na).replace(/\/+$/,"");E=Mi(e,pe,Y.map(ae=>ae.path)).length}}catch{}let R=go(e),C=yo({...R,directives:0}),T=Hw(e,t),I=new Set(qw(e,r.name)),z=T.filter(Y=>I.has(Y)).length,V=T.length-z,K=Ge(e),ue=Yw(e),Se=Xw(e,new Date().toISOString());Qw(e,new Date().toISOString());let ke=Kw(e),Ne=ke?{status:ke.status,openQuestions:ke.openQuestions}:null;return!Ne&&$&&zw(e).some(pe=>pe.status==="open"&&(pe.run??"").trim()==="/discover")&&(Ne={status:"pending",openQuestions:0}),{ready:i&&l&&!n.claudeMissing,hasDocs:$,tracked:h,pendingText:C,directives:R.directives,behind:v,pendingWrites:E,localAhead:V,conflicts:z,autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:K.status,devhintsCompletedVersion:K.completedVersion,devhintsToVersion:me,builderStarted:at(e),genreUnknown:n.genreUnknown,roadmap:ue,discovery:Ne,uncommittedDocs:Se.dirty.length}}catch{return null}}X();var Jw={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"},ap=160,Ma=200,lp=40;function Fe(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function ip(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}: ${Fe(typeof r=="string"?r:JSON.stringify(r),lp)}`);return t.length>4&&n.push("\u2026"),Fe(n.join(", "),ap)}var Zw=new Set(["file_path","notebook_path"]);function ek(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 Rt=e=>typeof e=="string"&&e?e:null,_a=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function tk(e){let t=Rt(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);if(n.length<2)return null;let o=n[n.length-2],r=o.replace(/^\d+[-_.]/,"").split(/[-_]/).filter(Boolean);return r.length===0?o:r.map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" ")}function nk(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=Rt(t.title);if(!o)return null;let r=tk(t.local_path);return n("Create article",`"${Fe(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=Rt(t.title),r=_a(t.article_id);return n("Update article",o?`"${Fe(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",_a(t.article_id)?`id ${_a(t.article_id)}\u2026`:null);case"d360_publish_article":{let o=t.version_number;return n("Publish article LIVE",typeof o=="number"?`v${o}`:null)}case"d360_unpublish_article":return n("Unpublish article",null);case"d360_create_category":return n("Create category",Rt(t.name)?`"${Fe(Rt(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=Rt(t.file_path);return n("Upload image",o?Fe(o.replace(/\\/g,"/").split("/").pop()??o,60):null)}case"d360_sync_status":return n("Check sync status",null);default:return null}}function Zr(e,t,n){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,s="",...i]=e.split("__"),l=i.join("__");if(s==="document360"){let b=nk(l,t);if(b)return b}let p=l.replace(/^d360_/,"").replace(/_/g," ");return{title:`${s==="document360"?"Document360":s.charAt(0).toUpperCase()+s.slice(1)}: ${p}`,sep:" ",arg:ip(t)}}let o=Jw[e],r=o?t[o]:void 0;if(typeof r=="string"&&r){let s=o&&Zw.has(o)?ek(r,n):r;return{title:e,sep:"",arg:Fe(s,ap)}}return{title:e,sep:"",arg:ip(t)}}function ok(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 rk(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(ok).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>Fe(r,Ma))]}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}: ${Fe(String(r),lp)}`);return n.length>0?[Fe(n.join(" \xB7 "),Ma)]:null}return null}function sk(e){let t=Rt(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function ik(e,t,n){switch(e){case"d360_create_article":{let o=sk(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=Rt(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 ${Fe(o[0],120)}`:""}`]}default:return null}}function es(e,t=4,n,o){let r=e.replace(/\r\n/g,`
|
|
383
|
+
`).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let i=ik(n.slice(18),o,r);if(i)return{lines:i,hidden:0}}let s=rk(r)??r.split(`
|
|
384
|
+
`);return{lines:s.slice(0,t).map(i=>Fe(i,Ma)),hidden:Math.max(0,s.length-t)}}function ts(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function ns(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 cp(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 os(e){return cp(e,"url")}function rs(e){return cp(e,"preview_url")}var hp=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Tk(e,t,n,o){if(hp.test(e))try{let r=pp(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,i=ns(t,n),l=os(n);e.endsWith("publish_article")&&l&&console.log(W(` \u2B95 Live: ${l}`));let p=rs(n);p?console.log(W(` \u2B95 Preview: ${p}`)):i&&s&&console.log(W(` \u2B95 Preview: ${ts(r.connection.portalUrl,s,i,r.project.languageCode??"en")}`))}catch{}}async function fp(e=process.cwd(),t="auto",n,o){let r=lk(t);r.kind==="none"&&(console.error(""),console.error(A("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${W("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${W('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${W("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${W("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),Dk(e,n),r.kind==="subscription"&&(r.stored?console.log(g(" Using your Claude subscription (no API key set).")):console.log(g(" No API key or stored Claude Code login found \u2014 trying your Claude session anyway.")),console.log(""));let s=!1,i=Ua({cwd:e,profileName:n,allowProdWrites:s}),l={uuid:null,firstPrompt:null,titleFired:!1},p=ak({input:process.stdin,output:process.stdout}),h=[],b=null,$=!1;p.on("line",R=>{if(b){let C=b;b=null,C(R)}else h.push(R)}),p.on("close",()=>{if($=!0,b){let R=b;b=null,R(null)}});function v(){return h.length>0?Promise.resolve(h.shift()):$?Promise.resolve(null):(process.stdout.write(W("> ")),new Promise(R=>{b=R}))}let E={cwd:e,version:o,profileName:n,allowProdWrites:()=>s,restartAgent:()=>{i.close(),i=Ua({cwd:e,profileName:n,allowProdWrites:s}),l={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>l.uuid,setPendingName:R=>{l.pendingName=R},setModel:async R=>i.setModel(R),withPausedInput:async R=>{p.pause();try{return await R()}finally{p.resume()}}};try{for(;;){let R=await v();if(R===null)break;let C=R.trim();if(C){if(C.startsWith("/")){let T=ep(C);if(!T)continue;let I=Zu[T.name];if(!I){console.log(A(`Unknown command: /${T.name}`)),console.log(g("Type /help for the list."));continue}let z=await I(T.args,E);if(z.kind==="exit")break;if(z.kind==="clear"){E.restartAgent();continue}if(z.kind==="allow-prod"){s=!0,E.restartAgent(),console.log(U("\u2713 Production writes authorized for this session.")),console.log("");continue}if(z.kind==="resume"){i.close(),i=Ua({cwd:e,resume:z.uuid,profileName:n,allowProdWrites:s});let V=ck(z.uuid);l={uuid:z.uuid,firstPrompt:V?.firstPrompt??null,titleFired:!0},up(z.uuid),console.log(U(`\u2713 Resumed "${z.name}"`)),console.log("");continue}if(z.kind==="forward-to-agent"){l.firstPrompt||(l.firstPrompt=z.display??z.prompt);let V=(z.display??"").trim().split(/\s+/),K=(V[0]==="/check"||V[0]==="/review")&&V.includes("--fix"),ue=V.slice(1).find(Y=>!Y.startsWith("--")),Se=K?Ck(e,ue):[],ke=V[0]==="/screenshot"&&(V[1]==="verify"||V[1]==="review"),Ne=ke?V[2]&&!V[2].startsWith("--")?[V[2]]:uo(ve(e)):[];if(await Fa(i,z.prompt,r,l,e,n),K)try{xk(e,Se,{reviewedCap:Rk})}catch{}if(ke&&Ne.length>0)try{for(let Y of ho(e,Ne))console.log(Y)}catch{}}else Ek(e,n);continue}if(kk(C)){let T=bk(C);if(T){try{$k(e,{title:T,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}l.firstPrompt||(l.firstPrompt=C),await Fa(i,`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${T}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${T}" and the article path(s) you wrote.`,r,l,e,n);continue}}l.firstPrompt||(l.firstPrompt=C),await Fa(i,C,r,l,e,n)}}}finally{i.close(),p.close()}}function Dk(e,t){console.log(""),console.log(Yn("document360-writer")),console.log(g(` cwd: ${e}`));let n=fk(e);if(console.log(g(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(Ak(e,t)),!mk(e))console.log(H(" First run: /init (scaffolds config + prints the builder hand-off prompt) \u2192 /login, then ask me to write the docs."));else{let o=!1;try{if(lr(e),!at(e))for(let r of cr(e))console.log(H(` ${r}`))}catch{}try{let r=gk(e);r.persisted&&r.appType?console.log(g(` \u2713 Detected a ${r.appType} app \u2014 enabled the ${r.appType}-doc-playbook (change with /genre).`)):r.source==="unknown"&&(o=!0)}catch{}try{let r=vk(e);for(let s of sr(r.applied))console.log(H(` ${s}`));if(r.reopenedForRedaction)for(let s of ir(r.reopenedForRedaction).split(/\r?\n/))console.log(H(` ${s}`))}catch{}try{let r=$o(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:o}),s=r?bo(r):null;if(s?.kind==="recommend"&&s.rec.note){let i=s.rec.tone==="warn"?H:g;for(let l of ti(s.rec.note).split(`
|
|
385
|
+
`))console.log(i(` ${l}`));s.rec.picker&&console.log(W(` Pick one: ${s.rec.picker.options.map(l=>l.cmd).join(" \xB7 ")}`))}}catch{}}console.log(g(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function Ek(e,t){try{let n=$o(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:!1}),o=n?bo(n):null;o?.kind==="recommend"&&o.rec.lead&&console.log(g(` Next: ${ko(o.rec.lead)}`))}catch{}}function Ak(e,t){try{let n=pp(e,t),o=n.production?H(" \u26A0 PRODUCTION"):"",r=wk(n.name);if(!r)return g(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...dp(r.idToken)??{},...dp(r.accessToken)??{}},i=s.email??s.preferred_username??"signed in";return yk(r)&&!r.refreshToken?H(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):g(` Document360: ${i} \xB7 profile "${n.name}"${o}`)}catch(n){return g(` Document360: ${n.message.split(".")[0]}`)}}function jk(){console.error(""),console.error(`Sign in with your Claude subscription: run ${W("claude")} once, then retry.`),console.error(` (No Claude Code? ${W("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${W("https://console.anthropic.com/settings/keys")}`)}function Nk(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;pk({uuid:t,name:r??uk(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function Ik(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||hk(o,t).then(r=>{r&&dk(n,r)}).catch(()=>{})}async function Fa(e,t,n,o,r,s){let i=new Map,l=!1;for await(let p of e.send(t))p.type==="tool"&&hp.test(p.name)&&(l=!0),Ok(p,o,r,n,i);if(l)try{let p=Pk(await Sk({cwd:r,profileName:s}));p&&console.log(p)}catch{}}function Ok(e,t,n,o,r){switch(e.type){case"session":t.uuid||Nk(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let s=Zr(e.name,e.input,process.cwd());s&&(process.stdout.write(`
|
|
386
|
+
|
|
387
|
+
`),console.log(`${U("\u25CF")} ${Ee(s.title)}${s.arg!==null?fe(`${s.sep}(${s.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let s=ct(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!s)break;let i=l=>l===1?"":"s";console.log(fe(` \u23BF Added ${s.added} line${i(s.added)}, removed ${s.removed} line${i(s.removed)}`));for(let l of s.lines)console.log(l);s.hidden>0&&console.log(g(` \u2026 +${s.hidden} more diff lines`));break}case"tool_result":{let s=r.get(e.id);if(!s)break;r.delete(e.id);let i=es(e.output,4,e.isError?void 0:s.name,s.input),l=e.isError?A:fe;i.lines.forEach((p,h)=>console.log(l((h===0?" \u23BF ":" ")+p))),i.hidden>0&&console.log(g(` \u2026 +${i.hidden} lines`)),e.isError||Tk(s.name,s.input,e.output,n);break}case"result":{process.stdout.write(`
|
|
388
|
+
`);let s=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(g(` (${Zn(s)}\u2192${Zn(e.outputTokens)} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(up(t.uuid),t.titleFired||Ik(t,n));break}case"error":console.error(""),console.error(A(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&jk();break}}import{render as Xb}from"ink";import{resolveAuth as Qb}from"document360-engine";import{useCallback as ee,useEffect as Be,useMemo as Ya,useRef as oe,useState as Q}from"react";import{Box as ce,Text as O,useApp as Kk,useInput as Xk,useStdout as Qk}from"ink";import{existsSync as An,readFileSync as us,readdirSync as Jk}from"node:fs";import{basename as Co,isAbsolute as Zk,join as za}from"node:path";import{createSession as Fp,classifyClaudeAuth as nl,CLAUDE_CODE_SETUP_HINT as eb,loginPkce as tb,toStoredTokens as nb,saveTokens as ob,getAccessToken as rb,resolveActiveProfile as We,resolveProjectId as sb,getArticle as ib,decodeJwtClaims as Nn,isExpired as St,loadTokens as zt,clearTokens as ab,clearProfileProject as lb,setTitle as cb,slugify as db,touchSession as Ka,upsertSession as ub,generateTitle as Wp,findByName as pb,listSessions as hb,renameSession as fb,suggestNextAction as mb,readProjectConfig as le,writeProjectConfig as Bp,resolveAndPersistAppType as gb,detectAppType as yb,resolveModelSetting as ol,loadProfileMap as Hp,applyPull as qp,computeSyncStatus as Xa,lintDocs as Vp,compareRemoteSources as wb,planPull as Gp,establishBaselines as kb,rebaselineServerMeta as bb,inventoryRepo as $b,knownEnvironments as vb,resolveEnvironment as xb,planPartitions as Qa,partitionEvenly as Cb,screenshotPlaceholderIds as Rb,trackedArticlePaths as Sb,runPartitioned as ps,estimateBulkCost as Yp,resolveModelForOperation as hs,readDocsPlan as Pb,checkForUpdate as Tb,detectInstallKind as Db,isSelfUpdatable as Eb,devHintsGuidePath as zp,toolFeedbackPath as Kp,reconcileToolFeedback as Ab,reconcileUpgradeActions as jb,stampArticles as Ja,listArticleFiles as Xp,CONTENT_CAP_VERSION as Za,ENGINE_VERSION as oh,DEFAULT_DOCS_DIR as rl,setProfileProject as Nb,writeCrashLog as Ib,applyStructureOrder as el,orderSyncLine as tl,applyRelatedArticles as Qp,relatedSyncLine as Jp}from"document360-engine";gr();wt();import{spawn as mp}from"node:child_process";function Lk(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function _k(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?mp([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):mp(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 Wa(e){for(let[t,n]of Lk())if(await _k(t,n,e))return!0;return!1}var gp=/\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 yp(e){let t=e.trimEnd();return t?/\?[\s*_"')\]]*$/.test(t)||gp.test(t):!1}function Ba(e,t){if(t.closed)return e;let n=e.split(`
|
|
389
|
+
`),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){gp.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(`
|
|
390
|
+
`)}import{existsSync as Mk,mkdirSync as Uk,readFileSync as Fk,writeFileSync as Wk}from"node:fs";import{join as wp}from"node:path";import{writerDir as Bk}from"document360-engine";function kp(e){return wp(Bk(e),".sessions")}function bp(e,t){return wp(kp(e),`${t}.json`)}function $p(e,t,n){try{Uk(kp(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");Wk(bp(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function Ha(e,t){try{let n=bp(e,t);if(!Mk(n))return[];let o=JSON.parse(Fk(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var Hk=e=>`\x1B]0;${e}\x07`,qk=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function vp(e){process.stdout.isTTY&&process.stdout.write(e)}function En(e){vp(Hk(e))}function ss(e){vp(qk(e))}var is=["\xB7 "," \xB7"],as="\u{1F7E3}";Fr();pr();X();import{Box as qa,Text as we}from"ink";import{jsx as be,jsxs as vo}from"react/jsx-runtime";function Vk({row:e,nameW:t,width:n}){switch(e.t){case"head":return be(we,{color:Z,bold:!0,children:e.s});case"text":return be(we,{children:e.s});case"dim":return be(we,{dimColor:!0,children:e.s});case"sub":return be(we,{bold:!0,dimColor:!0,children:e.s});case"good":return be(we,{color:"green",children:e.s});case"step":return vo(we,{children:[be(we,{color:Z,children:`${e.n}. `}),e.s]});case"cmd":{let o=Fs(e.name,e.s,t,n),r=o.descLines.slice(o.nameOwnLine?0:1);return vo(qa,{flexDirection:"column",children:[vo(we,{children:[" ",be(we,{color:Z,children:o.nameCell}),!o.nameOwnLine&&be(we,{dimColor:!0,children:` ${o.descLines[0]??""}`})]}),r.map((s,i)=>be(we,{dimColor:!0,children:`${o.indent}${s}`},i))]})}case"gap":return be(we,{children:" "})}}function xp({tab:e,width:t,version:n,engineVersion:o}){let r=Ve[e]??Ve[0],s=6+Ve.reduce((l,p)=>l+p.label.length+4,0),i="\u2500".repeat(Math.min(s,Math.max(t-1,20)));return vo(qa,{flexDirection:"column",paddingX:1,children:[vo(we,{children:[be(we,{color:Z,bold:!0,children:"Help "}),Ve.map((l,p)=>p===e?be(we,{color:"white",backgroundColor:Z,bold:!0,children:` ${l.label} `},l.key):be(we,{dimColor:!0,children:` ${l.label} `},l.key))]}),be(we,{color:Z,children:i}),be(qa,{flexDirection:"column",marginTop:1,children:r.rows.map((l,p)=>be(Vk,{row:l,nameW:Us(r.rows),width:t},p))}),be(we,{dimColor:!0,children:`
|
|
391
|
+
\u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close \xB7 d360-writer v${n} \xB7 engine v${o}`})]})}var Gk=/^(?:\d+[.)]|[-*•])\s+/;function Cp(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
|
|
392
|
+
`)){let i=s.trim().replace(Gk,""),l=i.match(/^`([^`]+)`$/);l&&(i=l[1].trim());let p=i.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!p||!o.has(p[1].toLowerCase()))continue;let h=`/${p[1].toLowerCase()}${p[2]?` ${p[2]}`:""}`;if(r.includes(h)||r.push(h),r.length>=n)break}return r}X();function xo(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function ze(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function Rp(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var Yk=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function Sp(e,t,n){if(!Yk.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 Va(e){return e.replace(/^[\w.-]+\//,"")}var ls=16,Pp={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function Yt(e){return typeof e=="string"?e:e.cmd}function Tp(e){return typeof e=="string"?void 0:e.desc}function Ga(e){return e.trim().split(/\s+/).slice(1).join(" ")}function Dp(e,t){let n=Ga(t);return e.some(r=>Yt(r).trim()===t.trim()||!!n&&Ga(Yt(r))===n)?e.filter(r=>Yt(r).trim()!==t.trim()&&!(n&&Ga(Yt(r))===n)):[]}import{isDirectiveMention as Ob,stripDirectiveMention as Lb,appendDirective as _b,reconcileTestidRequest as Mb,builderChannelWired as Ub}from"document360-engine";var zk=/\[Pasted text #\d+ \+\d+ lines?\]/g;function Ep(e){return e.replace(/\r\n?/g,`
|
|
393
|
+
`)}function Ap(e){return e.includes(`
|
|
394
|
+
`)||e.length>200}function jp(e,t){let n=t.split(`
|
|
395
|
+
`).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function Np(e,t){return e.replace(zk,n=>t.get(n)??n)}function Ip(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function cs(e,t){let n=Math.max(1,t),o=[],r=0;for(let s of e.split(`
|
|
396
|
+
`)){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 ds(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function Op(e,t,n){let o=ds(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 Lp(e,t,n){let o=e[ds(e,t)];return n==="start"?o.start:o.end}function _p(e,t,n){let o=Math.max(1,n),r=e.split(`
|
|
397
|
+
`),s=0;for(let i=r.length-1;i>=0;i--){let l=r[i];if(s+=Math.max(1,Math.ceil(l.length/o)),s>=t){let p=s-t;return{text:[p>0?l.slice(p*o):l,...r.slice(i+1)].join(`
|
|
398
|
+
`),truncated:i>0||p>0}}}return{text:e,truncated:!1}}function Mp(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 Up(e){let t=!1,n=0,o=0;for(let r of e.split(`
|
|
399
|
+
`)){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 Ro,jsx as L,jsxs as ne}from"react/jsx-runtime";var Fb={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL",auto:"auto \u2014 right-sized for docs \xB7 /model to change"},Zp=` 1. /init \u2014 pick your Document360 environment & scaffold config
|
|
400
400
|
2. /login \u2014 sign in & pick your Document360 project (workspace auto-selected)
|
|
401
|
-
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function
|
|
402
|
-
${
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
`)}),
|
|
406
|
-
`)}),
|
|
401
|
+
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function Wb(e,t,n,o){let r=nl(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=ol(e),l=le(e),p=(l?.docsDir??rl).replace(/\/+$/,""),h=l?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${p}/ + config`,b={version:t,engineVersion:oh,captureVersion:xn(),claude:s,model:i.model,modelSource:Fb[i.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:l!==null,mode:h};if(l===null)return b;try{let $=We(e,o);b.profile=$.name,b.apiUrl=$.connection.apiUrl,b.prod=$.production,b.project=$.project.projectName??$.project.projectId??"(chosen at login)";let v=zt($.name);if(v){let E={...Nn(v.idToken)??{},...Nn(v.accessToken)??{}},R=E.email??E.preferred_username??"signed in";St(v)?v.refreshToken&&(b.who=R,b.loggedOut=!1,b.sessionHint="session expired \u2014 refreshing\u2026"):(b.who=R,b.loggedOut=!1,b.sessionHint=`session valid until ${new Date(v.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return b}function Bb(e,t){try{let n=We(e,t),o=zt(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...Nn(o.idToken)??{},...Nn(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return St(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 eh=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],In=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Hb="Ask me to write or update an article\u2026";function jn({ch:e,dim:t}){let[n,o]=Q(!0);return Be(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),L(O,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var th=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function nh(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var qb=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Vb({startTime:e,chars:t}){let[n,o]=Q(0);Be(()=>{let p=setInterval(()=>o(h=>h+1),120);return()=>clearInterval(p)},[]);let r=In[n%In.length],s=eh[Math.floor(n/16)%eh.length],i=Math.floor((Date.now()-e)/1e3),l=Math.round(t/4);return ne(ce,{children:[L(O,{color:Z,children:` ${r} ${s}\u2026 `}),L(O,{color:"gray",children:`(${eo(i)} \xB7 ~${l} tokens \xB7 esc to interrupt)`})]})}function Gb({text:e}){let[t,n]=Q(0);return Be(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),L(ce,{paddingX:1,children:L(O,{color:Z,children:`${In[t%In.length]} ${e}`})})}var Yb=12e4;function zb({p:e}){let[t,n]=Q(0);Be(()=>{let T=setInterval(()=>n(I=>I+1),150);return()=>clearInterval(T)},[]);let o=In[t%In.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),i=Math.round(e.chars/4),l=Date.now()-e.lastAt>=Yb,p=e.verb??"Converting",h=e.unit??"article",b=e.rows.reduce((T,I)=>T+I.items,0),$=p.toLowerCase(),v=e.rows,E=0;if(v.length>ls){let T=v.findIndex(z=>z.status==="active"||z.status==="pending"),I=Math.max(0,Math.min(T-2,v.length-ls));E=v.slice(0,I).filter(z=>z.status==="done").length,v=v.slice(I,I+ls)}let R=Math.min(40,Math.max(...v.map(T=>Va(T.label).length),0)),C=T=>T==="failed"?"red":T==="active"?Z:void 0;return ne(ce,{flexDirection:"column",children:[ne(ce,{children:[L(O,{color:Z,children:` ${o} ${p} ${b} ${h}${b===1?"":"s"} `}),L(O,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${i} tokens \xB7 ${eo(r)} \xB7 esc to stop`})]}),E>0&&L(O,{dimColor:!0,children:` \u2714 +${E} done`}),v.map(T=>ne(O,{color:C(T.status),dimColor:T.status==="done"||T.status==="pending",children:[` ${Pp[T.status]} ${Va(T.label).padEnd(R)}`,T.status==="active"&&T.itemsDone!==void 0?` (${T.itemsDone}/${T.items} ${h}${T.items===1?"":"s"})`:T.status!=="pending"?` (${T.items} ${h}${T.items===1?"":"s"})`:"",T.status==="active"?` \u2190 ${$}\u2026`:""]},T.label)),l&&L(O,{color:"yellow",children:` \u26A0 no activity for ${eo(s)} \u2014 press esc to stop if it's wedged`})]})}var Kb=10800*1e3;function rh({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=Kk(),[s,i]=Q(n),[l,p]=Q(null),[h,b]=Q({text:"",pos:0}),$=h.text,v=ee(d=>{b(c=>{let a=typeof d=="function"?d(c.text):d;return{text:a,pos:a.length}})},[]),E=ee(d=>{b(c=>({text:c.text.slice(0,c.pos)+d+c.text.slice(c.pos),pos:c.pos+d.length}))},[]),R=ee(()=>{b(d=>{if(d.pos===0)return d;let c=d.text.slice(0,d.pos),a=Ip(c)??c.slice(0,-1);return{text:a+d.text.slice(d.pos),pos:a.length}})},[]),[C,T]=Q(!1),[I,z]=Q(!1),[V,K]=Q(0),[ue,Se]=Q(!1),[ke,Ne]=Q(null),[Y,pe]=Q(null),[ae,$e]=Q([]),Kt=oe(!1),Pt=oe(!1),Xt=oe(!1),[Tt,So]=Q(!1),et=oe(0),[Po,To]=Q(!1),[uh,Do]=Q(!1),[ms,ll]=Q(null),[ph,Qt]=Q(0),Dt=oe(0),[gs,Jt]=Q(0),[Zt,Eo]=Q(null),cl=oe(new Map),hh=oe(0),en=oe([]),He=oe(null);He.current===null&&(He.current=Fp({cwd:e,profileName:s,allowProdWrites:!1}));let tt=oe({uuid:null,firstPrompt:null,titleFired:!1}),Ao=oe(new Map),dl=oe(null),tn=oe(!1),ys=oe([]),ye=oe([]),nn=oe([]),jo=oe(null),[ul,Et]=Q(null),ws=oe(null),[At,jt]=Q(null),[nt,on]=Q(null),[ot,rn]=Q(null),[Pe,sn]=Q(null),[Ie,Nt]=Q(null),[dt,an]=Q(null),[ut,It]=Q(null),[rt,Ot]=Q(null),[pl,On]=Q(null),[Oe,Lt]=Q(null),[De,ln]=Q(null),[hl,ks]=Q([]),_t=oe([]),Ln=oe(!1),Ce=oe(null),[No,ie]=Q(null),[fl,Mt]=Q(null),Io=oe(!1),_n=oe(null),Mn=oe(null),[Le,Ut]=Q(null),[Oo,Un]=Q(null),bs=!!(ot||Pe||Ie||dt||ut||rt||Oe||De||Le||Oo),[ml,cn]=Q(0),[gl,dn]=Q(0),[fh,yl]=Q(0),$s=Ya(()=>{try{let d=ol(e);return d.source==="auto"?`${d.model} (auto)`:d.model}catch{return null}},[e,fh]),{stdout:qe}=Qk(),[,mh]=Q(0),wl=oe(`${qe.columns??80}x${qe.rows??24}`),pt=ee(()=>Math.max(20,(qe.columns??80)-1),[qe]),u=ee(d=>{en.current.push(d),console.log(ni(d,pt()))},[pt]),Te=ee((d,c)=>{et.current++,Ne(d),pe(c??null)},[]),Xe=ee(()=>{et.current++,Ne(null),pe(null)},[]),te=ee(d=>Te(d,Qr({kind:"cmd",cmd:d,reason:""})),[Te]),Lo=ee((d,c)=>{!c?.silent&&d.note&&u({kind:"note",tone:d.tone,text:d.note}),d.picker&&($e(d.picker.options.map(a=>({cmd:a.cmd,desc:a.desc}))),On(d.picker.title)),d.lead&&Te(d.lead.kind==="cmd"?d.lead.cmd:d.lead.text,Qr(d.lead))},[u,Te]),_e=ee((d,c,a="info")=>{d&&u({kind:"note",tone:a,text:d}),c&&Te(c.kind==="cmd"?c.cmd:c.text,Qr(c))},[u,Te]),[Fn,vs]=Q(null),[gh,kl]=Q(!1),ht=ee((d,c)=>{vs(d),kl(!1),u({kind:"note",tone:"info",text:c?.hint??"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[u]),xs=ee(()=>{Mb(e,new Date().toISOString());let d=Eu(e);d&&(u({kind:"note",tone:"info",text:d.lines.join(`
|
|
402
|
+
`)}),ht(d.prompt,Ub(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,u,ht]),Cs=oe(!1),Rs=ee(async()=>{try{if(Cs.current||!Eb(Db())||le(e)?.mode==="engineer")return;let d=await Tb({pkg:Dn,currentVersion:o,force:!0});if(!d.updateAvailable||!d.latest)return;Cs.current=!0,u({kind:"note",tone:"info",text:`\u2B06 Updating ${Dn} ${d.current} \u2192 ${d.latest}\u2026 (wait for the \u2713 before you /exit)`}),Do(!0),(await Vr().finally(()=>Do(!1))).ok?(u({kind:"note",tone:"ok",text:`\u2713 Updated to v${d.latest} \u2014 run /exit, then relaunch to apply.`}),te("/exit"),ll(d.latest)):u({kind:"note",tone:"warn",text:`Update available (v${d.latest}) but auto-update failed \u2014 run: ${qr}`})}catch{}},[e,o,u,te]),_o=ee(d=>{let c=Ye(e,s);return c.ok?!0:(u({kind:"note",tone:"warn",text:c.reason}),Mn.current=d,te("/login"),!1)},[e,s,u,te]),[Mo,Ss]=Q(null),Ft=ee(d=>{let c=$o(e,s,{claudeMissing:nl(t).state==="missing",allowAutoAudit:d,genreUnknown:Xt.current});return c?bo(c):{kind:"idle"}},[e,s,t]),Wn=oe(!0),un=oe(!1),Uo=oe(0),Bn=oe(0);Be(()=>{let d=setInterval(()=>{if(Wn.current){Uo.current=0,Bn.current=0;return}if(!C)try{if(!An(zp(e)))return;if(Ge(e).status==="current"){Wn.current=!0,Uo.current=0,Bn.current=0;let a=Ft(!1),m=a.kind==="recommend"?a.rec:null,D=un.current?`\u2713 Your builder finished the protocol update (v${me}) \u2014 the dev\u2194docs hand-off is current again.`:"\u2713 Your builder finished the hand-off \u2014 the architecture brief is in. I can read this repo now and write accurate docs.";u({kind:"note",tone:"ok",text:`${D}${m?.lead?` ${ko(m.lead)}`:""}`}),vs(null),m&&(m.lead||m.picker)?Lo(m,{silent:!0}):un.current||Te("write the docs for this repo"),K(G=>G+1);return}if(un.current)return;Uo.current+=1;let c=Uo.current;if((c===4||c%15===0)&&Bn.current<3){Bn.current+=1;let a=Bn.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";u({kind:"note",tone:"info",text:at(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${a}`:`\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.${a}`})}}catch{}},4e3);return()=>clearInterval(d)},[e,C,u,Ft,Lo,Te]),Be(()=>{let d=ul??Co(e);if(!C){ss(0),En(`${as} ${d}`);return}ss(3);let c=0;En(`${is[0]} ${d}`);let a=setInterval(()=>{c=(c+1)%is.length,En(`${is[c]} ${d}`)},400);return()=>clearInterval(a)},[C,e,ul]),Be(()=>()=>ss(0),[]),Be(()=>{let d=performance.now(),c=[],a=(y,k)=>{let w=performance.now();try{return k()}finally{let x=Math.round(performance.now()-w);x>=80&&c.push(`${y}: ${x}ms`)}};u({kind:"banner",info:a("banner",()=>Wb(e,o,t,s))});let m=nl(t).state==="missing";if(m&&u({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.
|
|
403
|
+
${eb}
|
|
404
|
+
Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!le(e)){u({kind:"note",tone:"info",text:`Welcome! This repo isn't set up for d360-writer yet \u2014 three steps and you're writing docs:
|
|
405
|
+
${Zp}`}),te(m?"/doctor":"/init");return}m&&te("/doctor");try{let y=We(e,s),k=zt(y.name);k&&St(k)&&k.refreshToken?rb({profile:y.name,connection:y.connection}).then(()=>{u({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),K(w=>w+1)}).catch(()=>{u({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 sign in again with /login."}),te("/login")}):(!k||St(k))&&(u({kind:"note",tone:"warn",text:`Profile "${y.name}" is not signed in \u2014 sign in with /login.`}),te("/login"))}catch{}try{let y=le(e),k=We(e,s),w=zt(k.name);y&&w&&!St(w)&&Oa(e,y.authoritativeSourceFiles)&&!La(e,s)&&(u({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),te("/scope"))}catch{}try{let y=a("resolve-genre",()=>gb(e));y.persisted&&y.appType?u({kind:"note",tone:"ok",text:`\u2713 Detected a ${y.appType} app \u2014 enabled the ${y.appType}-doc-playbook (change with /genre, or edit .d360-writer/config.json).`}):y.source==="unknown"&&le(e)&&(Xt.current=!0)}catch{}let D=Ge(e);try{if(a("reconcile-devhints",()=>lr(e)),D.status!=="current"&&!at(e)){let y=cr(e);y.length&&(u({kind:"note",tone:"warn",text:y.join(`
|
|
406
|
+
`)}),ht(qt()),Wn.current=!1,un.current=!1)}}catch{}try{let y=a("reconcile-feedback",()=>Ab(e));y.archived>0&&u({kind:"note",tone:"ok",text:`\u2713 Tidied ${y.archived} resolved item${y.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${y.open>0?`; ${y.open} still open`:""}.`})}catch{}try{let y=a("upgrade-actions",()=>jb(e));y.applied.length>0&&u({kind:"note",tone:"warn",text:sr(y.applied).join(`
|
|
407
|
+
`)}),y.reopenedForRedaction&&u({kind:"note",tone:"warn",text:ir(y.reopenedForRedaction)})}catch{}let G=a("ready-decision",()=>Ft(!0));G.kind==="autoAudit"?(u({kind:"note",tone:"info",text:G.note}),io().then(y=>{y.kind==="forward-to-agent"&&y.prompt&&se(y.prompt,{display:y.display,quietUser:!0})})):G.kind==="recommend"&&Lo(G.rec);let f=Math.round(performance.now()-d);f>=800&&Ib({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${f}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${c.length?c.join(`
|
|
407
408
|
`):"no single phase \u226580ms"}
|
|
408
|
-
cwd: ${e}`}),
|
|
409
|
-
|
|
410
|
-
${j}`)}catch{}
|
|
411
|
-
`)});let S=
|
|
412
|
-
|
|
413
|
-
${
|
|
414
|
-
${
|
|
415
|
-
|
|
416
|
-
`)}),q.length>0){let N=
|
|
417
|
-
`)})}
|
|
418
|
-
`)})
|
|
419
|
-
`)}),
|
|
420
|
-
`)}),
|
|
421
|
-
|
|
422
|
-
`)})};switch(a){case"help":Mn({tab:0});return;case"exit":case"quit":We.current?.close(),r();return;case"clear":Le(),Jt.current=[],So(!1),Ke(),console.log("\x1B[?2026h\x1B[H\x1B[2J\x1B[3J\x1B[?2026l"),u({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let f;try{f=Me(e,s)}catch(y){u({kind:"note",tone:"error",text:y.message});return}u({kind:"note",tone:"info",text:`Profile "${f.name}" \u2192 ${f.connection.name} (${f.connection.apiUrl})${f.production?" \u26A0 PRODUCTION":""}`}),Y(!0);try{let y=await nb(f.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},w=>u({kind:"note",tone:"info",text:w})),k=ob(f.name,y);if(rb(k),await Os(k,f.name,w=>u({kind:"note",tone:"info",text:w})),u({kind:"note",tone:"ok",text:`\u2713 Logged in to "${f.name}" as ${Jo(k)}`}),await Cc(s),_n.current){let w=_n.current;_n.current=null;let x=Ve(e,s);x.ok?(u({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 tab to run ${w}.`}),te(w)):(u({kind:"note",tone:"warn",text:`${x.reason} (then ${w}.)`}),te("/login"),_n.current=w)}else Ln.current&&(Se(Ln.current,"\u21E5 tab to re-send your last prompt\u2026"),Ln.current=null)}catch(y){u({kind:"note",tone:"error",text:`Login failed: ${y.message}`})}finally{Y(!1),z(y=>y+1)}return}case"allow-prod":{let f=!1;try{f=Me(e,s).production}catch{}if(!f){u({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}Zt.current=!0,Le(),u({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let f=Ki(m.join(" ")),y=et.current.uuid;if(!y){if(!f){u({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}gs.current=f,Et(f),En(`${ss} ${f}`),u({kind:"note",tone:"ok",text:`Session will be named "${f}" once it starts.`});return}if(!f){u({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let k=et.current.firstPrompt??"";Up(k,e).then(w=>{w?(Se(`/rename ${w}`),u({kind:"note",tone:"info",text:`Suggestion: "${w}" \u2014 press tab to accept, or type /rename <your name>.`})):u({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>u({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}mb(y,f),Et(f),En(`${ss} ${f}`),u({kind:"note",tone:"ok",text:`Session renamed to "${f}".`});return}case"profile":{let f=m[0],y=de(e);if(!f){let k=Object.entries(y?.profiles??{});if(k.length===0){u({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let w=k.map(([F,q])=>({name:F,env:q.connection?.environment??"custom",prod:q.production===!0,who:Ts(F)})),x=s??y?.defaultProfile,S=Math.max(0,w.findIndex(F=>F.name===x));tn({cursor:S,current:S,rows:w});return}if(f==="add"){let k=Xi(e,m[1],m[2]);if(k){u({kind:"note",tone:"error",text:k});return}u({kind:"note",tone:"ok",text:`\u2713 Profile "${m[1]}" created (environment: ${m[2]??m[1]}).`}),Es(m[1],!1);return}if(!y?.profiles?.[f]){u({kind:"note",tone:"error",text:`Unknown profile "${f}". Create it: /profile add ${f} <environment>`});return}Es(f,!0);return}case"doctor":await co(m,{cwd:e,version:o});return;case"genre":{await Gr(m,{cwd:e});try{dt.current=!(de(e)?.appType??wb(e))}catch{}z(f=>f+1);return}case"roadmap":{if(m[0]?.toLowerCase()==="done"){let f=zr(e,m.slice(1).join(" ").trim());u({kind:"note",tone:f.ok?"ok":"warn",text:f.line}),z(y=>y+1);return}u({kind:"note",tone:"info",text:Pa(e).join(`
|
|
423
|
-
`)});return}case"mcp":await ur(m);return;case"init":{if(de(e)){u({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer/config.json directly (or d360-writer init for the CLI wizard)."});return}let f=xb().map(y=>({name:y,apiUrl:Cb(y).apiUrl}));nn({cursor:0,rows:f});return}case"resume":{let f=m.join(" ").trim(),y=fb(e).filter(x=>x.uuid!==et.current.uuid);if(!f){if(!y.length){u({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}Mt({query:"",cursor:0,sessions:y});return}let k=hb(e,f);if(!k){u({kind:"note",tone:"error",text:`No session matches "${f}".`});return}Le(k.uuid),et.current={uuid:k.uuid,firstPrompt:k.firstPrompt,titleFired:!0},Et(k.name),Ya(k.uuid),Jt.current=[];let w=Wa(e,k.uuid);for(let x of w)u(x);u({kind:"note",tone:"ok",text:w.length?`Resumed "${k.name}" \u2014 restored ${w.length} message(s); continue where you left off.`:`Resumed "${k.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let f=m.join(" ").trim(),y;try{y=await Yn(e,s)}catch(w){u({kind:"note",tone:"error",text:`Could not list workspaces: ${w.message}`});return}if(!f){let w=y.workspaces.map(S=>({id:S.id,name:S.name??S.id,type:S.workspace_type}));if(w.length===0){u({kind:"note",tone:"info",text:"No workspaces in this project."});return}let x=Math.max(0,w.findIndex(S=>S.id===y.current));on({cursor:x,current:x,rows:w,profile:y.profile,projectId:y.projectId,projectName:y.projectName,environment:y.environment});return}let k=Ns(y.workspaces,f);if(!k){u({kind:"note",tone:"error",text:`No workspace matches "${f}".`});return}Ho(y.profile,y.projectId,k);return}case"project":{let f=m.join(" ").trim(),y;try{y=await gt(e,s)}catch(w){u({kind:"note",tone:"error",text:`Could not list projects: ${w.message} (signed in? try /login)`});return}if(!f){let w=y.projects.map(S=>({id:S.id,name:S.name??S.id,sub:S.sub_domain}));if(w.length===0){u({kind:"note",tone:"info",text:"No projects found for this identity."});return}let x=w.findIndex(S=>S.id===y.current);jt({cursor:Math.max(0,x),current:x,rows:w,profile:y.profile,environment:y.environment});return}let k=Is(y.projects,f);if(!k){u({kind:"note",tone:"error",text:`No project matches "${f}". Available: ${y.projects.map(w=>w.name??w.id).join(", ")}`});return}Vo(y.profile,k);return}case"logout":{let f;try{f=Me(e,s).name}catch(k){u({kind:"note",tone:"error",text:k.message});return}let y=cb(f);lb(e,f),Le(),z(k=>k+1),u({kind:"note",tone:y?"ok":"info",text:y?`\u2713 Signed out of "${f}" and cleared its project/workspace selection.`:`Profile "${f}" was not signed in. Cleared any project/workspace selection.`}),u({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),te("/login");return}case"publish":{if(!Oo(d.trim()))return;if(m.includes("--screenshots")||m.includes("--shots")){let w=$e(e),x=vr(w);if(x.length===0){u({kind:"note",tone:"info",text:"No captured screenshots yet \u2014 /screenshot capture first."});return}let S=xr(w);S&&u({kind:"note",tone:"warn",text:S}),u({kind:"note",tone:"info",text:`Re-saving ${x.length} article${x.length===1?"":"s"} with captured screenshots so the images embed\u2026`}),await Wt(x);return}if(m[0]==="--related"&&m[1]){let w=await Ar(e,s,m[1].replace(/\\/g,"/"));if(w.length===0){u({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await Wt(w);return}let f=m.filter(w=>!w.startsWith("--"));if(f[0]){await Ps(f[0]);return}let y=m.includes("--all"),k=m.includes("--force");u({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let w=await za({cwd:e,profileName:s}),{clean:x,conflicts:S}=Tr(w.entries),F=y&&k&&S.length>0,q=Dr(w.entries);if(q>0&&u({kind:"note",tone:"warn",text:`\u26A0 ${q} article${q===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.`}),S.length>0&&!F&&u({kind:"note",tone:"warn",text:Er(S.length)}),x.length===0&&!F){if(S.length>0){te("/resolve");return}u({kind:"note",tone:"ok",text:q>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let j=w.counts["unknown-base"]??0;j>0&&u({kind:"note",tone:"info",text:`(${j} article(s) have no sync base yet \u2014 publish those by path if needed.)`}),_t("Reconciling structure on Document360 (order + related articles)\u2026");try{let M=await Ja({cwd:e,profileName:s,onRateLimit:B=>_t(`Document360 rate limit \u2014 waiting ${Math.ceil(B.waitMs/1e3)}s\u2026`)}),_=Xp(await Kp({cwd:e,profileName:s})),N=Za(M);N?u({kind:"note",tone:"info",text:N}):M.skipped&&u({kind:"note",tone:"warn",text:`Order sync skipped: ${M.skipped}`}),_&&u({kind:"note",tone:"info",text:_}),u({kind:"note",tone:"ok",text:N||_?"\u2713 Structure synced to Document360 \u2014 /structure shows the new category + article order.":"\u2713 Already in order \u2014 nothing to change."}),(N||_)&&te("/structure")}catch(M){u({kind:"note",tone:"warn",text:`Structure sync failed: ${M.message}`})}finally{_t(null)}return}if(y){let j=(F?[...x,...S]:x).map(M=>M.path);await Wt(j),S.length>0&&!F&&te("/resolve");return}rn({cursor:0,rows:bd(x,S)})}catch(w){u({kind:"note",tone:"error",text:`Could not compute sync status: ${w.message}`}),u({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"resolve":{if(!Oo(d.trim()))return;await As(m.find(f=>!f.startsWith("--")));return}case"preview":{let f=m.join(" ").trim();if(!f){let k=[];try{k=Object.keys(Wp(e,Me(e,s).name)?.articles??{})}catch{}if(k.length===0){u({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}Ot({query:"",cursor:0,paths:k});return}let y=eb(f)?f:Ga(e,f);if(Dn(y)){try{u({kind:"preview",name:xo(y),text:eh(ls(y,"utf8"))})}catch(k){u({kind:"note",tone:"error",text:`Could not read ${y}: ${k.message}`})}return}if(Hb.test(f)){try{let k=Me(e,s),w={profile:k.name,connection:k.connection},x=k.project.projectId??ib(w),S=await ab(w,x,f);u({kind:"preview",name:S.title??f,text:S.content??"*(article has no content)*"})}catch(k){u({kind:"note",tone:"error",text:`Could not fetch article: ${k.message}`})}return}u({kind:"note",tone:"error",text:`"${f}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let f=m[0]?.trim();if(!f){let x=_r(tc(e));At({cursor:x,current:x});return}let{lines:y,changed:k,effective:w}=ao(e,f);for(let x of y)u({kind:"note",tone:x.startsWith("\u26A0")?"warn":x.startsWith("\u2713")?"ok":"info",text:x});k&&(gc(x=>x+1),We.current?.setModel(w));return}case"convert":{if(!de(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:f,run:y}=Si(m),k=Pb(e,s);if(k.length===0){u({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let w=Pi(k,f);if(w.length===0){u({kind:"note",tone:"error",text:`No tracked articles under "${f}". (${k.length} are tracked overall.)`});return}let x=Ka(w),S=3,F=`/convert${f?` --scope ${f}`:""} --run`,q=us(e,"light");if(!y){let M=Vp({files:Ti(e,w),op:"convert",model:q.model}),_=f?`Scope: ${f} (${w.length} of ${k.length} tracked)
|
|
409
|
+
cwd: ${e}`}),Rs()},[]),Be(()=>{let d=setInterval(()=>{Rs()},Kb);return()=>clearInterval(d)},[Rs]),Be(()=>{if(C||ue||Tt||Kt.current||Pt.current||ke!==null||ae.length>0||$!==""||Fn!==null||ye.current.length>0||jo.current||bs)return;let d=Ft(!1);d.kind==="recommend"&&(d.rec.lead||d.rec.picker)&&Lo(d.rec,{silent:!0})},[C,ue,ke,ae,$,Fn,bs,V,Ft,Tt]),Be(()=>{let d=null,c=null,a=()=>{d&&clearTimeout(d),d=setTimeout(()=>{d=null;let m=`${qe.columns??80}x${qe.rows??24}`;m!==wl.current&&(wl.current=m,mh(D=>D+1),c&&clearTimeout(c),c=setTimeout(()=>{c=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+Ac(en.current,pt())+"\x1B[?2026l")},80))},400)};return qe.on("resize",a),()=>{d&&clearTimeout(d),c&&clearTimeout(c),qe.off("resize",a)}},[qe,pt]);let Me=Math.max(20,(qe.columns??80)-1),bl=Ya(()=>Bb(e,s),[e,s,V]),Ps=(()=>{if(uh)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(ms!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${ms?` v${ms}`:""}\u2026`,isSetup:!0};if(Mo)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(Fn)return gh?{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(ye.current.length>0)return ye.current[0].mode==="conflict"?{text:"l keep local \xB7 p take portal \xB7 s skip \xB7 anything else cancels\u2026",isSetup:!0}:{text:"y to write \xB7 n to skip \xB7 anything else cancels\u2026",isSetup:!0};let d=le(e);if(!d)return{text:"Run /init to set up this repo (or /help)\u2026",isSetup:!0};let c=za(e,(d.docsDir??rl).replace(/\/+$/,"")),a=(()=>{try{return An(c)&&Jk(c).length>0}catch{return!1}})();try{let m=We(e,s),D=zt(m.name);if(!(!!D&&!(St(D)&&!D.refreshToken)))return{text:`Sign in with /login (profile "${m.name}")\u2026`,isSetup:!0};if(!m.project.projectId)return{text:"Sign in to Document360 to pick your project\u2026",isSetup:!0};if(!m.project.workspaceId&&!a)return{text:"Pick a workspace with /workspace\u2026",isSetup:!0}}catch{}return a?{text:Hb,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),Qe=vc($),$l=Qe.length>0&&!C,Fo=Math.max(3,Math.min(12,(qe.rows??24)-8)),Wo=Math.min(gs,Math.max(0,Qe.length-1)),Wt=Qe.length<=Fo?0:Math.min(Math.max(0,Wo-Math.floor(Fo/2)),Qe.length-Fo),Ts=Qe.slice(Wt,Wt+Fo),Ds=l!==null?_p(l,8,Me):null,Bo=Oe?Oe.paths.filter(d=>!Oe.query||d.toLowerCase().includes(Oe.query.toLowerCase())).slice(0,8):[],Ho=Le?Le.sessions.filter(d=>{let c=Le.query.toLowerCase();return!c||d.name.toLowerCase().includes(c)||d.firstPrompt.toLowerCase().includes(c)}).slice(0,8):[],Ue=ee((d,c)=>{He.current?.close(),He.current=Fp({cwd:e,resume:d,profileName:c??s,allowProdWrites:tn.current}),d||(tt.current={uuid:null,firstPrompt:null,titleFired:!1},Et(null)),cn(0),dn(0)},[e,s]),vl=ee((d,c,a)=>{if(th.test(d))try{let m=We(e,s),D=typeof c.project_id=="string"&&c.project_id||m.project.projectId,G=ns(c,a),f=[],y=os(a);d.endsWith("publish_article")&&y&&f.push(`Live: ${y}`);let k=rs(a);k?f.push(`Preview: ${k}`):G&&D&&f.push(`Preview: ${ts(m.connection.portalUrl,D,G,m.project.languageCode??"en")}`),f.length>0&&u({kind:"link",lines:f})}catch{}},[e,s,u]),se=ee(async(d,c)=>{To(!0),Kt.current=!1,Pt.current=!1,Xe(),$e([]),On(null),vs(null);let a=et.current;if(c?.display?.startsWith("/"))try{let j=Xu(e,c.display);j&&(d=`${d}
|
|
410
|
+
|
|
411
|
+
${j}`)}catch{}c?.quietUser||u({kind:"user",text:c?.echoDisplay&&c.display?c.display:d});let m=tt.current;m.firstPrompt||(m.firstPrompt=c?.display??d),Dt.current=Date.now(),Qt(0),T(!0),Ao.current.clear();let D="",G=!1,f=!1,y=!1,k="",w={num:0,closed:!1,cueSeen:!1},x=null,S=()=>{x||(x=setTimeout(()=>{x=null,p(k.length>0?k:null)},60))},F=()=>{x&&clearTimeout(x),x=null,p(null)},q=(j=!1)=>{let{head:M,keep:_}=Mp(k,j);M.trim()&&u({kind:"assistant",text:Ba(M.trimEnd(),w)}),k=_,F()};try{for await(let j of He.current.send(d))if(j.type==="session"){if(!m.uuid){m.uuid=j.sessionId;let M=new Date().toISOString(),_=ws.current,N=_??db(m.firstPrompt??"session");ub({uuid:j.sessionId,name:N,renamed:!!_,titled:!1,cwd:e,firstPrompt:m.firstPrompt??"",createdAt:M,updatedAt:M}),Et(N),ws.current=null}}else if(j.type==="text"){k+=j.delta,D+=j.delta;let M=Up(k);if(M>0){let _=k.slice(0,M).trimEnd();_&&u({kind:"assistant",text:Ba(_,w)}),k=k.slice(M)}S(),Qt(_=>_+j.delta.length)}else if(j.type==="tool"){G=!0,th.test(j.name)&&(f=!0);let _=(de=>typeof de=="string"&&de?de.replace(/\\/g,"/").toLowerCase():null)(j.input.file_path??j.input.notebook_path),N=["Edit","Write","MultiEdit","NotebookEdit"].includes(j.name),B=j.name==="Read"&&_!==null&&_===dl.current;if(dl.current=N?_:null,B)q(),u({kind:"tool",title:"Read",sep:"",arg:"(re-checking the file it just edited)"});else{let de=Zr(j.name,j.input,e);de&&(q(),u({kind:"tool",title:de.title,sep:de.sep,arg:de.arg}),Ao.current.set(j.id,{name:j.name,input:j.input}))}}else if(j.type==="article_diff"){let M=ct(j.oldContent,j.newContent,pt());M&&(q(),u({kind:"diff",added:M.added,removed:M.removed,lines:M.lines,hidden:M.hidden}))}else if(j.type==="tool_result"){j.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(j.output)&&(Io.current=!0);let M=Ao.current.get(j.id);if(M){Ao.current.delete(j.id),q();let _=es(j.output,4,j.isError?void 0:M.name,M.input);u({kind:"tool-result",lines:_.lines,hidden:_.hidden,isError:j.isError}),j.isError||vl(M.name,M.input,j.output)}}else if(j.type==="result"){q(!0),cn(_=>_+j.outputTokens),dn(_=>_+j.costUsd);let M=j.inputTokens+j.cacheReadTokens+j.cacheCreationTokens;if(u({kind:"done",seconds:Math.round((Date.now()-Dt.current)/1e3),tokens:j.outputTokens,costUsd:j.costUsd,ok:j.ok,...M>0?{inTokens:M,cachedPct:Math.round(j.cacheReadTokens/M*100)}:{}}),!y&&!G&&!D.trim()&&!Ln.current&&u({kind:"note",tone:"warn",text:"The agent produced no output. This usually means the Claude model/runtime did not start \u2014 check sign-in and model with /doctor (on a subscription, make sure Claude Code is logged in on this machine)."}),j.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(D))try{let _=Kp(e);if(An(_)){let N=us(_,"utf8").trim();N&&(Ss(N),u({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{}if(Pt.current=j.ok&&yp(D),j.ok&&w.cueSeen)So(!0),$e([]);else{let _=j.ok?Cp(D,$n.map(N=>N.name)):[];if(_.length>0)te(_[0]);else if(j.ok&&D.trim()&&!Pt.current){let N=Ft(!1);N.kind==="recommend"&&(N.rec.lead||N.rec.picker)||mb(d,D,e).then(B=>{B&&et.current===a&&Te(B)}).catch(()=>{})}}if(m.uuid&&(Ka(m.uuid),!m.titleFired)){m.titleFired=!0;let _=m.uuid,N=m.firstPrompt;N&&Wp(N,e).then(B=>{B&&(cb(_,B),Et(B))}).catch(()=>{})}}else j.type==="error"&&(q(!0),y=!0,j.kind==="auth"&&(Io.current=!0),u({kind:"note",text:`agent error: ${j.message}`,tone:"error"}))}finally{if(T(!1),F(),f)try{let j=tl(await el({cwd:e,profileName:s,onRateLimit:M=>Mt(`Document360 rate limit \u2014 waiting ${Math.ceil(M.waitMs/1e3)}s\u2026`)}));j&&u({kind:"note",tone:j.startsWith("\u26A0")?"warn":"info",text:j})}catch{}K(j=>j+1),tt.current.uuid&&$p(e,tt.current.uuid,en.current),Io.current?(Io.current=!1,_n.current=c?.display??d,Te("/login","\u21E5 tab to run /login \u2014 then I\u2019ll re-send your last prompt\u2026")):_n.current=null,Ln.current&&(Ln.current=!1,_t.current.length>0&&(u({kind:"note",tone:"info",text:`(${_t.current.length} queued message(s) discarded)`}),_t.current=[],ks([])),u({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,u,vl,pt,Te,te,Xe,Ft]),Bt=ee(async d=>{let c=hs(e,"standard");Dt.current=Date.now(),Qt(0),T(!0);let a=new AbortController;Ce.current=a;let m=async(D,G)=>{let f=Qa(D);ie({verb:"Publishing",total:f.length,done:0,active:[],rows:xo(f),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:G?`Resolving cross-links in ${D.length} article${D.length===1?"":"s"} whose targets published this run (second pass)\u2026 (esc to stop)`:`Publishing ${D.length} article${D.length===1?"":"s"} across ${f.length} partition${f.length===1?"":"s"} (\u2264${ro} agents at once) on ${c.model}\u2026 (esc to stop)`});let y=!1;for await(let k of ps({cwd:e,partitions:f,promptFor:w=>so(w.paths),concurrency:ro,profileName:s,allowProdWrites:tn.current,model:c.model,signal:a.signal}))if(k.type==="partition_status")k.status==="running"?ie(w=>w&&{...w,active:[...w.active,k.label],rows:ze(w.rows,k.label,"active"),lastAt:Date.now()}):ie(w=>w&&{...w,active:w.active.filter(x=>x!==k.label),done:w.done+1,rows:ze(w.rows,k.label,k.status==="done"?"done":"failed"),lastAt:Date.now()});else if(k.type==="partition_event")ie(w=>{if(!w)return w;let x={...w,lastAt:Date.now()};return k.event.type==="tool"?x.tools=w.tools+1:k.event.type==="text"&&(x.chars=w.chars+k.event.delta.length),x});else if(k.type==="run_done"){y=k.aborted,dn(F=>F+k.totalCostUsd),cn(F=>F+k.results.reduce((q,j)=>q+j.outputTokens,0));let w=k.aborted?"Stopped. ":"",x=t.kind==="api"?"api":"subscription";u({kind:"note",tone:k.aborted?"warn":k.ok?"ok":"warn",text:w+ki(k.results,f,x).join(`
|
|
412
|
+
`)});let S=wi(e,s);if(S&&u({kind:"note",tone:"info",text:S}),!k.aborted){try{let F=await el({cwd:e,profileName:s,onRateLimit:j=>Mt(`Document360 rate limit \u2014 waiting ${Math.ceil(j.waitMs/1e3)}s\u2026`)}),q=tl(F);q?u({kind:"note",tone:"info",text:q}):F.skipped&&u({kind:"note",tone:"warn",text:`Order sync skipped: ${F.skipped}`})}catch(F){u({kind:"note",tone:"warn",text:`Order sync failed: ${F.message}`})}try{let F=Jp(await Qp({cwd:e,profileName:s}));F&&u({kind:"note",tone:"info",text:F})}catch(F){u({kind:"note",tone:"warn",text:`Related-articles sync failed: ${F.message}`})}}}return y};try{if(!await m(d,!1)){let G=await bi(e,s,d);G.length>0&&await m(G,!0)}}catch(D){u({kind:"note",tone:"error",text:`Publish run failed: ${D.message}`})}finally{Ce.current=null,ie(null),T(!1),K(D=>D+1)}},[e,s,u,t]),Es=ee(async d=>{await se(gi(d),{display:`/publish ${d}`,quietUser:!0});try{let c=await Nr(e,s,d.replace(/\\/g,"/"));c.length>0&&(On(`Related articles not yet published (${c.length}):`),$e([`/publish --related ${d}`,...c.map(a=>`/publish ${a}`)]))}catch{}},[e,s,se]),qo=ee(d=>{if(d)try{for(let c of Array.isArray(d)?d:[d]){let a=Ea(e,c);if(!a)continue;Xr(e,a.title).ok&&u({kind:"note",tone:"ok",text:`\u2713 That completed a docs-campaign step \u2014 marked done: ${a.title}`});return}}catch{}},[e,u]),xl=ee(async(d,c)=>{let m=Cb(d,3),D=hs(e,"standard"),G=new Map;for(let k of d){let w=si(e,k,Cn(e,k));w&&G.set(k,w)}Dt.current=Date.now(),Qt(0),T(!0);let f=new AbortController;Ce.current=f,ie({verb:"Authoring",unit:"spec",total:m.length,done:0,active:[],rows:xo(m),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Authoring ${d.length} screenshot spec${d.length===1?"":"s"} across ${m.length} partition${m.length===1?"":"s"} (\u22646 agents at once) on ${D.model}${D.forced?" (forced)":""}\u2026 (esc to stop)`});let y=!1;try{for await(let k of ps({cwd:e,partitions:m,promptFor:w=>md(w,G),concurrency:6,profileName:s,allowProdWrites:tn.current,model:D.model,signal:f.signal}))if(k.type==="partition_status")k.status==="running"?ie(w=>w&&{...w,active:[...w.active,k.label],rows:ze(w.rows,k.label,"active"),lastAt:Date.now()}):ie(w=>w&&{...w,active:w.active.filter(x=>x!==k.label),done:w.done+1,rows:ze(w.rows,k.label,k.status==="done"?"done":"failed"),lastAt:Date.now()});else if(k.type==="partition_event")ie(w=>{if(!w)return w;let x={...w,lastAt:Date.now()};return k.event.type==="tool"?x.tools=w.tools+1:k.event.type==="text"&&(x.chars=w.chars+k.event.delta.length),x});else if(k.type==="run_done"){dn(F=>F+k.totalCostUsd),cn(F=>F+k.results.reduce((q,j)=>q+j.outputTokens,0));let w=k.results.filter(F=>F.ok).length,x=k.aborted?"Stopped. ":"";y=!k.aborted&&c.setup;let S=k.aborted?"":y?" Refreshing the staging checklist\u2026":" Next: /screenshot capture --all (or /screenshot checklist first for the staging checklist).";u({kind:"note",tone:k.aborted?"warn":k.ok?"ok":"warn",text:`${x}Authored specs \u2014 ${w}/${k.results.length} batches ok.${S}`}),!k.aborted&&k.ok&&qo(c.runLine)}}catch(k){u({kind:"note",tone:"error",text:`Spec authoring failed: ${k.message}`})}finally{Ce.current=null,ie(null),T(!1),K(k=>k+1)}if(y){let k=await Tn();k.kind==="forward-to-agent"&&k.prompt&&await se(k.prompt,{display:k.display,quietUser:!0}),xs()}},[e,s,u,se,qo,xs]),Cl=ee(async d=>{let c=si(e,d,Cn(e,d))??void 0,a=await Tr([d],void 0,{prior:c});a.kind==="forward-to-agent"&&a.prompt&&await se(a.prompt,{display:a.display,quietUser:!0}),od(e,d)&&_e(`Spec ready \u2014 /screenshot capture ${d} takes the screenshot; bare /screenshot picks the next shot.`,{kind:"cmd",cmd:`/screenshot capture ${d}`,reason:""})},[e,se,_e]),Hn=ee(async(d,c)=>{if(!Br(e)){await se(ua(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(!bu(e)){u({kind:"note",tone:"info",text:"No saved login for screenshot capture yet \u2014 opening a browser window. Sign in to your app (MFA included); I'll continue automatically once the session saves. (esc cancels)"}),T(!0),Mt("Waiting for you to finish logging in (browser window)\u2026");let N=new AbortController;Ce.current=N;let B;try{B=await $u({cwd:e,signal:N.signal})}catch(de){u({kind:"note",tone:"error",text:`Could not launch the login: ${de.message}`});return}finally{Ce.current=null,Mt(null),T(!1)}if(B.exitCode!==0){da(B.exitCode,B.output)?u({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(B.output)?u({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."}):u({kind:"note",tone:N.signal.aborted?"warn":"error",text:N.signal.aborted?"Login cancelled \u2014 nothing saved.":`Login did not complete:
|
|
413
|
+
${la(B.output)}`});return}u({kind:"note",tone:"ok",text:"\u2713 Login saved \u2014 continuing with the capture."})}let a=new Map(d.map(N=>[N,ad(e,N)])),m=0;if(d.length>1){let N=d.filter(B=>a.get(B).mutates);if(N.length>0&&(m=N.length,d=d.filter(B=>!a.get(B).mutates),d.length===0)){u({kind:"note",tone:"warn",text:`\u26A0 All ${N.length} spec${N.length===1?"":"s"} in scope write real data, so a bulk run has nothing to do. Run one deliberately: /screenshot capture ${N[0]}`});return}}else if(d.length===1&&a.get(d[0]).mutates){let N=a.get(d[0]),B=vu(e);u({kind:"note",tone:"warn",text:`\u26A0 This capture performs a REAL write in your app${N.what?`: ${id(N.what)}`:N.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. `+(B.production?`This profile is PRODUCTION \u2014 the write lands in the LIVE tenant${B.url?` (${B.url})`:""}. If the spec cleans up after itself, confirm it did.`:"Tip: point the capture scope (.d360-writer/capture.json) at a demo/non-production context for shots like this.")})}T(!0);let D=new AbortController;Ce.current=D;let G=d.map(N=>({label:N,items:1,status:"pending"}));ie({verb:"Capturing",unit:"screenshot",total:d.length,done:0,active:[],rows:G,tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()});let f=lt(e),y=Object.keys(f.shots).length>0,k=xu(c?.heldBackBlocked??[],m);u({kind:"note",tone:"info",text:`Capturing ${d.length} screenshot${d.length===1?"":"s"} with d360-capture (a real browser drives your app)\u2026 (esc to stop)`+(k?`
|
|
414
|
+
${k}`:"")});let w=Date.now(),x=[];try{for(let N of d){if(D.signal.aborted)break;ie(J=>J&&{...J,active:[N],rows:ze(J.rows,N,"active"),lastAt:Date.now()});let{exitCode:B,output:de}=await ca({cwd:e,id:N,signal:D.signal,stdio:"pipe"});if(da(B,de)){u({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 st=D.signal.aborted&&B!==0?"failed":aa(e,N,B,w),fn=st==="captured"?void 0:st==="skipped"?wu(de)??"a data prerequisite isn't met \u2014 the spec's skip reason names what to stage":ku(de);x.push({id:N,outcome:st,detail:fn}),ie(J=>J&&{...J,active:[],done:J.done+1,rows:ze(J.rows,N,st==="captured"?"done":"failed"),lastAt:Date.now()})}}catch(N){u({kind:"note",tone:"error",text:`Capture run failed: ${N.message}`})}finally{Ce.current=null,ie(null),T(!1),K(N=>N+1)}if(x.length===0)return;let S=x.filter(N=>N.outcome==="captured"),F=x.filter(N=>N.outcome==="skipped"),q=x.filter(N=>N.outcome==="failed"),j=d.length-x.length;u({kind:"note",tone:q.length?"warn":S.length?"ok":"info",text:[`\u2713 ${S.length} captured`,F.length?`\u2298 ${F.length} blocked`:"",q.length?`\u2717 ${q.length} broken`:"",j?`${j} not run (stopped)`:""].filter(Boolean).join(" ")+` ${x.length} run${m>0?` \xB7 ${m} held back`:""}`+Su(Cu(f,x),y).map(N=>`
|
|
415
|
+
${N}`).join("")});let M=Ru(F);if(M.length>0&&u({kind:"note",tone:"info",text:M.join(`
|
|
416
|
+
`)}),q.length>0){let N=Math.max(...q.map(B=>B.id.length));u({kind:"note",tone:"error",text:q.map(B=>`\u2717 ${B.id.padEnd(N)} ${Wr(B.detail)}`).join(`
|
|
417
|
+
`)})}if(mr(e,x.map(N=>({id:N.id,outcome:N.outcome,reason:N.detail,specSource:Cn(e,N.id)})),new Date().toISOString()),x.length===d.length&&q.length===0&&F.length===0&&qo(c?.runLine),S.length>0){let N=S.map(de=>de.id);u({kind:"note",tone:"info",text:po(N.length)}),await se(Gt(e,N),{display:"/screenshot verify",quietUser:!0});let B=ho(e,N);B.length>0&&u({kind:"note",tone:"info",text:B.join(`
|
|
418
|
+
`)});return}let _=Pu({results:x,ids:d,articles:Tu(e,S.map(N=>N.id))});_&&_e(_.note,{kind:"cmd",cmd:_.cmd,reason:""},_.tone)},[e,u,_e,se,qo]),As=ee(d=>{let c=zt(d);if(!c||St(c)&&!c.refreshToken)return null;let a={...Nn(c.idToken)??{},...Nn(c.accessToken)??{}};return a.email??a.preferred_username??"signed in"},[]),js=ee((d,c)=>{if(c){let a=le(e);a&&(a.defaultProfile=d,Bp(a,e))}i(d),Ue(void 0,d),u({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${d}"${c?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),As(d)||(u({kind:"note",tone:"warn",text:`Profile "${d}" is not signed in \u2014 sign in with /login.`}),te("/login")),K(a=>a+1)},[e,u,Ue,As,te]),Vo=ee((d,c,a)=>{Xo(e,d,c,a.id,a.name),u({kind:"note",tone:"ok",text:`Switched to workspace "${a.name??a.id}" (agent restarted).`}),Ue(),Hp(e,d)||(u({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),u({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:"}),u({kind:"note",tone:"info",text:kn(wn(e)).join(`
|
|
419
|
+
`)}),ht(qt()),Wn.current=Ge(e).status==="current",un.current=at(e),u({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,u,Ue,ht]),Go=ee(async d=>{let c;try{c=await zn(e,d)}catch{u({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),te("/workspace");return}if(c.workspaces.length===0){u({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let a=c.workspaces.filter(D=>(D.workspace_type??"").toLowerCase()!=="apidocumentation"),m=a.length>0?a:c.workspaces;if(m.length===1){let D=m[0],G=c.workspaces.length-m.length;u({kind:"note",tone:"ok",text:`Selected the "${D.name??D.id}" workspace${G>0?" (skipped the API-documentation workspace)":""}.`}),Vo(c.profile,c.projectId,D);return}u({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${m.length} available).`}),te("/workspace")},[e,u,Vo,te]),Yo=ee((d,c)=>{Qo(e,d,c.id,c.name),u({kind:"note",tone:"ok",text:`Project set to "${c.name??c.id}" (agent restarted).`}),Ue(),Go(d)},[e,u,Ue,Go]),Rl=ee(async d=>{let c;try{c=We(e,d)}catch{return}if(!c.project.workspaceId){if(c.project.projectId){if(!c.project.projectName)try{let{projects:a}=await gt(e,c.name),m=a.find(D=>D.id===c.project.projectId);m?.name&&Nb(e,c.name,{projectName:m.name})}catch{}await Go(c.name);return}try{let{projects:a}=await gt(e,c.name);if(a.length===1){let m=a[0];u({kind:"note",tone:"ok",text:`Using your Document360 project "${m.name??m.id}".`}),Yo(c.name,{id:m.id,name:m.name});return}if(a.length>1){let m=a.map(D=>({id:D.id,name:D.name??D.id,sub:D.sub_domain}));u({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),Nt({cursor:0,current:-1,rows:m,profile:c.name,environment:c.connection.name});return}}catch{}u({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),te("/project")}},[e,u,Go,Yo,te]),pn=ee(()=>{let d=ye.current[0];if(!d)return;Xe();let{plan:c,mode:a}=d;u({kind:"note",tone:"info",text:`\u25CF ${c.title} (${c.path})`});for(let D of c.notes)u({kind:"note",tone:"warn",text:`\u26A0 ${D}`});c.overwritesLocalChanges&&a==="pull"&&u({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let m=ct(c.oldContent,c.newContent,pt());u(m?{kind:"diff",added:m.added,removed:m.removed,lines:m.lines,hidden:m.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."}),a==="conflict"?(u({kind:"note",tone:"warn",text:"Conflict \u2014 edited both here and on the portal (diff shows local \u2192 portal)."}),u({kind:"note",tone:"info",text:"Keep local (publish, overwrites portal) \xB7 take Portal (overwrites local) \xB7 Skip? (l/p/s \u2014 anything else cancels)"})):u({kind:"note",tone:"info",text:`Write ${c.path}? (y/n \u2014 anything else cancels)`})},[u,pt,Xe]),Ns=ee(()=>{if(ye.current.length>0){pn();return}let d=nn.current;nn.current=[],d.length>0?(u({kind:"note",tone:"info",text:`Publishing ${d.length} kept-local article${d.length===1?"":"s"} over the portal\u2026`}),Bt(d)):te("/pull")},[pn,u,Bt,te]),Sl=ee(d=>{if(ye.current.length===0)return!1;let c=d.trim().toLowerCase(),a=ye.current[0];if(a.mode==="conflict"){if(c==="l"||c==="local")ye.current.shift(),nn.current.push(a.plan.path),u({kind:"note",tone:"info",text:`Keeping local ${a.plan.path} \u2014 will publish over the portal.`});else if(c==="p"||c==="portal"){ye.current.shift();try{qp({cwd:e,profileName:s},a.plan),u({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${a.plan.path} (local overwritten, sync base advanced).`})}catch(m){u({kind:"note",tone:"error",text:`Take-portal failed: ${m.message}`})}}else if(c==="s"||c==="skip"||c==="n")ye.current.shift(),u({kind:"note",tone:"info",text:`Skipped ${a.plan.path} \u2014 still a conflict.`});else{let m=ye.current.length;return ye.current=[],nn.current=[],u({kind:"note",tone:"info",text:`Resolve cancelled (${m} conflict${m===1?"":"s"} left untouched).`}),!0}return Ns(),!0}if(c==="y"||c==="yes"){let m=ye.current.shift().plan;try{qp({cwd:e,profileName:s},m),u({kind:"note",tone:"ok",text:`\u2713 Pulled ${m.path} (sync base advanced).`})}catch(D){u({kind:"note",tone:"error",text:`Pull failed: ${D.message}`})}}else if(c==="n"||c==="no"){let m=ye.current.shift().plan;u({kind:"note",tone:"info",text:`Skipped ${m.path}.`})}else{let m=ye.current.length;return ye.current=[],u({kind:"note",tone:"info",text:`Pull cancelled (${m} article(s) left untouched).`}),!0}return Ns(),!0},[e,s,Ns,u]),Is=ee(async d=>{u({kind:"note",tone:"info",text:"Checking Document360 for conflicts\u2026"});try{let c=await Xa({cwd:e,profileName:s}),a=d?.replace(/\\/g,"/"),m=c.entries.filter(G=>G.status==="conflict"&&G.path).map(G=>G.path);if(a){if(!m.includes(a)){u({kind:"note",tone:"ok",text:`${a} isn\u2019t in conflict \u2014 nothing to resolve.`});return}m=[a]}if(m.length===0){u({kind:"note",tone:"ok",text:"\u2713 No conflicts \u2014 local and Document360 agree on every tracked article."});return}let D=[];for(let G of m)try{D.push({plan:await Gp({cwd:e,profileName:s,relPath:G}),mode:"conflict"})}catch(f){u({kind:"note",tone:"error",text:`Could not load ${G} from Document360: ${f.message}`})}if(D.length===0)return;u({kind:"note",tone:"info",text:`Resolving ${D.length} conflict${D.length===1?"":"s"} \u2014 for each: keep local, take portal, or skip.`}),ye.current=D,nn.current=[],pn()}catch(c){u({kind:"note",tone:"error",text:`Could not compute sync status: ${c.message}`})}},[e,s,u,pn]),Pl=ee(d=>{let c=jo.current;if(!c)return!1;if(jo.current=null,Xe(),d.trim()!==c.repoName)return u({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:a,failed:m}=xa(e,c.targets);u({kind:"note",tone:m.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${a.length} item${a.length===1?"":"s"}. The repo is back to its original state.`});for(let D of m)u({kind:"note",tone:"error",text:` \u2717 ${D.path}: ${D.error}`});return c.hadDevhints&&(u({kind:"note",tone:"warn",text:dr().join(`
|
|
420
|
+
`)}),ht(Vs())),u({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
|
|
421
|
+
${Zp}`}),te("/init"),To(!1),!0},[e,u,ht,Xe,te]),qn=ee(async d=>{let c=d.slice(1).trim().split(/\s+/),a=(c[0]??"").toLowerCase(),m=c.slice(1);if(To(!0),_r(m)&&["write","check","review","reorder"].includes(a)){let f=ao(e,s);if(f.length===0){u({kind:"note",tone:"warn",text:"No categories yet \u2014 author some articles first, then scope to one."});return}let y=k=>a==="write"?`/write ${Ud(m,k).join(" ")}`.trim():`/${a} ${[k,...m.filter(w=>w!=="--scope")].join(" ")}`.trim();if(f.length===1){qn(y(f[0].token));return}Ot({cursor:0,rows:f,run:k=>{qn(y(k))}});return}if(Ct(a,m)){let f=ao(e,s);if(f.length>1){let y=m.filter(S=>S.startsWith("--")).join(" "),k=S=>`/${a}${S?` ${a==="write"?`--scope ${S}`:S}`:""}${y?` ${y}`:""} ${S?"":"--all"}`.replace(/\s+/g," ").trim(),w=f.reduce((S,F)=>S+F.count,0),x={token:"",label:a==="review"?`Everything \u2014 all ${w} articles + structure (IA) review`:a==="reorder"?`Everything \u2014 reorder all ${f.length} categories`:`Everything \u2014 rewrite all ${w} planned articles`,count:w};Ot({cursor:0,rows:[x,...f],run:S=>{qn(k(S))}});return}}let D=async f=>{let y=ra(f);if(!Br(e)){await se(ua(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(y.mode==="single"){await Hn([y.id],{runLine:[`/screenshot capture ${y.id}`,`/capture ${y.id}`]});return}if(y.mode==="failed"){let w=sa(e,mo(e).rows);if(w.length===0){u({kind:"note",tone:"info",text:"No broken specs to re-run \u2014 /screenshot list shows where things stand."}),te("/screenshot list");return}await Hn(w);return}if(y.mode==="blocked"){let{blocked:w,rows:x}=mo(e);if(w.length===0){u({kind:"note",tone:"info",text:"No shots are waiting on app data \u2014 /screenshot list shows where things stand."}),te("/screenshot list");return}let S=oo(x.filter(F=>F.state==="blocked")).length;u({kind:"note",tone:"info",text:`Re-running ${w.length} shot${w.length===1?"":"s"} that skipped on missing data last run.`+(S>0?` If you haven't staged ${S===1?"it":"those "+S+" things"} yet, ${w.length===1?"it":"they"} will skip again \u2014 /screenshot list has the worklist.`:"")}),await Hn(w,{runLine:["/screenshot capture --blocked","/screenshot capture --all --retry-blocked"]});return}if(y.mode==="all"||y.mode==="scope"){let w=y.mode==="scope"?y.scope:void 0,{ready:x,captured:S,blocked:F,rows:q}=mo(e,w),j=[...x,...S,...y.retryBlocked?F:[]];if(j.length===0&&F.length>0&&!y.retryBlocked){let _=w?`/screenshot capture ${w} --retry-blocked`:"/screenshot capture --blocked";_e(`All ${F.length} shot${F.length===1?"":"s"} in scope ${F.length===1?"is":"are"} blocked on data that wasn't staged last run \u2014 /screenshot list shows what to stage, then ${_}.`,{kind:"cmd",cmd:"/screenshot list",reason:""},"warn");return}if(j.length===0){u({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),te("/screenshot");return}if(!y.retryBlocked){let _=w?`/screenshot capture ${w} --retry-blocked`:"/screenshot capture --blocked",N=ia(q.filter(B=>B.state==="blocked"),_);N&&u({kind:"note",tone:"info",text:N})}let M=y.mode==="scope"?[`/screenshot capture ${y.scope}`,`/capture ${y.scope}`]:["/screenshot capture --all","/capture --all"];await Hn(j,{runLine:M,...y.retryBlocked?{}:{heldBackBlocked:q.filter(_=>_.state==="blocked")}});return}let k=yu(ve(e));if(k.length===0){u({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),te("/screenshot");return}It({cursor:0,rows:k,title:"Capture screenshots \u2014 pick what to shoot:"})},G=async()=>{let f=await Tn();f.kind==="forward-to-agent"&&f.prompt&&await se(f.prompt,{display:f.display,quietUser:!0}),xs()};switch(a){case"help":Un({tab:0});return;case"exit":case"quit":He.current?.close(),r();return;case"clear":Ue(),en.current=[],To(!1),Xe(),console.log("\x1B[?2026h\x1B[H\x1B[2J\x1B[3J\x1B[?2026l"),u({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let f;try{f=We(e,s)}catch(y){u({kind:"note",tone:"error",text:y.message});return}u({kind:"note",tone:"info",text:`Profile "${f.name}" \u2192 ${f.connection.name} (${f.connection.apiUrl})${f.production?" \u26A0 PRODUCTION":""}`}),z(!0);try{let y=await tb(f.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},w=>u({kind:"note",tone:"info",text:w})),k=nb(f.name,y);if(ob(k),await Ms(k,f.name,w=>u({kind:"note",tone:"info",text:w})),u({kind:"note",tone:"ok",text:`\u2713 Logged in to "${f.name}" as ${er(k)}`}),await Rl(s),Mn.current){let w=Mn.current;Mn.current=null;let x=Ye(e,s);x.ok?(u({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 tab to run ${w}.`}),te(w)):(u({kind:"note",tone:"warn",text:`${x.reason} (then ${w}.)`}),te("/login"),Mn.current=w)}else _n.current&&(Te(_n.current,"\u21E5 tab to re-send your last prompt\u2026"),_n.current=null)}catch(y){u({kind:"note",tone:"error",text:`Login failed: ${y.message}`})}finally{z(!1),K(y=>y+1)}return}case"allow-prod":{let f=!1;try{f=We(e,s).production}catch{}if(!f){u({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}tn.current=!0,Ue(),u({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let f=Ji(m.join(" ")),y=tt.current.uuid;if(!y){if(!f){u({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}ws.current=f,Et(f),En(`${as} ${f}`),u({kind:"note",tone:"ok",text:`Session will be named "${f}" once it starts.`});return}if(!f){u({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let k=tt.current.firstPrompt??"";Wp(k,e).then(w=>{w?(Te(`/rename ${w}`),u({kind:"note",tone:"info",text:`Suggestion: "${w}" \u2014 press tab to accept, or type /rename <your name>.`})):u({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>u({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}fb(y,f),Et(f),En(`${as} ${f}`),u({kind:"note",tone:"ok",text:`Session renamed to "${f}".`});return}case"profile":{let f=m[0],y=le(e);if(!f){let k=Object.entries(y?.profiles??{});if(k.length===0){u({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let w=k.map(([F,q])=>({name:F,env:q.connection?.environment??"custom",prod:q.production===!0,who:As(F)})),x=s??y?.defaultProfile,S=Math.max(0,w.findIndex(F=>F.name===x));on({cursor:S,current:S,rows:w});return}if(f==="add"){let k=Zi(e,m[1],m[2]);if(k){u({kind:"note",tone:"error",text:k});return}u({kind:"note",tone:"ok",text:`\u2713 Profile "${m[1]}" created (environment: ${m[2]??m[1]}).`}),js(m[1],!1);return}if(!y?.profiles?.[f]){u({kind:"note",tone:"error",text:`Unknown profile "${f}". Create it: /profile add ${f} <environment>`});return}js(f,!0);return}case"doctor":await co(m,{cwd:e,version:o});return;case"genre":{await zr(m,{cwd:e});try{Xt.current=!(le(e)?.appType??yb(e))}catch{}K(f=>f+1);return}case"roadmap":{if(m[0]?.toLowerCase()==="done"){let f=Xr(e,m.slice(1).join(" ").trim());u({kind:"note",tone:f.ok?"ok":"warn",text:f.line}),K(y=>y+1);return}u({kind:"note",tone:"info",text:Da(e).join(`
|
|
422
|
+
`)});return}case"mcp":await hr(m);return;case"init":{if(le(e)){u({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer/config.json directly (or d360-writer init for the CLI wizard)."});return}let f=vb().map(y=>({name:y,apiUrl:xb(y).apiUrl}));rn({cursor:0,rows:f});return}case"resume":{let f=m.join(" ").trim(),y=hb(e).filter(x=>x.uuid!==tt.current.uuid);if(!f){if(!y.length){u({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}Ut({query:"",cursor:0,sessions:y});return}let k=pb(e,f);if(!k){u({kind:"note",tone:"error",text:`No session matches "${f}".`});return}Ue(k.uuid),tt.current={uuid:k.uuid,firstPrompt:k.firstPrompt,titleFired:!0},Et(k.name),Ka(k.uuid),en.current=[];let w=Ha(e,k.uuid);for(let x of w)u(x);u({kind:"note",tone:"ok",text:w.length?`Resumed "${k.name}" \u2014 restored ${w.length} message(s); continue where you left off.`:`Resumed "${k.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let f=m.join(" ").trim(),y;try{y=await zn(e,s)}catch(w){u({kind:"note",tone:"error",text:`Could not list workspaces: ${w.message}`});return}if(!f){let w=y.workspaces.map(S=>({id:S.id,name:S.name??S.id,type:S.workspace_type}));if(w.length===0){u({kind:"note",tone:"info",text:"No workspaces in this project."});return}let x=Math.max(0,w.findIndex(S=>S.id===y.current));sn({cursor:x,current:x,rows:w,profile:y.profile,projectId:y.projectId,projectName:y.projectName,environment:y.environment});return}let k=Ls(y.workspaces,f);if(!k){u({kind:"note",tone:"error",text:`No workspace matches "${f}".`});return}Vo(y.profile,y.projectId,k);return}case"project":{let f=m.join(" ").trim(),y;try{y=await gt(e,s)}catch(w){u({kind:"note",tone:"error",text:`Could not list projects: ${w.message} (signed in? try /login)`});return}if(!f){let w=y.projects.map(S=>({id:S.id,name:S.name??S.id,sub:S.sub_domain}));if(w.length===0){u({kind:"note",tone:"info",text:"No projects found for this identity."});return}let x=w.findIndex(S=>S.id===y.current);Nt({cursor:Math.max(0,x),current:x,rows:w,profile:y.profile,environment:y.environment});return}let k=_s(y.projects,f);if(!k){u({kind:"note",tone:"error",text:`No project matches "${f}". Available: ${y.projects.map(w=>w.name??w.id).join(", ")}`});return}Yo(y.profile,k);return}case"logout":{let f;try{f=We(e,s).name}catch(k){u({kind:"note",tone:"error",text:k.message});return}let y=ab(f);lb(e,f),Ue(),K(k=>k+1),u({kind:"note",tone:y?"ok":"info",text:y?`\u2713 Signed out of "${f}" and cleared its project/workspace selection.`:`Profile "${f}" was not signed in. Cleared any project/workspace selection.`}),u({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),te("/login");return}case"publish":{if(!_o(d.trim()))return;if(m.includes("--screenshots")||m.includes("--shots")){let w=ve(e),x=Cr(w);if(x.length===0){u({kind:"note",tone:"info",text:"No captured screenshots yet \u2014 /screenshot capture first."});return}let S=Rr(w);S&&u({kind:"note",tone:"warn",text:S}),u({kind:"note",tone:"info",text:`Re-saving ${x.length} article${x.length===1?"":"s"} with captured screenshots so the images embed\u2026`}),await Bt(x);return}if(m[0]==="--related"&&m[1]){let w=await Nr(e,s,m[1].replace(/\\/g,"/"));if(w.length===0){u({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await Bt(w);return}let f=m.filter(w=>!w.startsWith("--"));if(f[0]){await Es(f[0]);return}let y=m.includes("--all"),k=m.includes("--force");u({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let w=await Xa({cwd:e,profileName:s}),{clean:x,conflicts:S}=Er(w.entries),F=y&&k&&S.length>0,q=jr(w.entries);if(q>0&&u({kind:"note",tone:"warn",text:`\u26A0 ${q} article${q===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.`}),S.length>0&&!F&&u({kind:"note",tone:"warn",text:Ar(S.length)}),x.length===0&&!F){if(S.length>0){te("/resolve");return}u({kind:"note",tone:"ok",text:q>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let j=w.counts["unknown-base"]??0;j>0&&u({kind:"note",tone:"info",text:`(${j} article(s) have no sync base yet \u2014 publish those by path if needed.)`}),Mt("Reconciling structure on Document360 (order + related articles)\u2026");try{let M=await el({cwd:e,profileName:s,onRateLimit:B=>Mt(`Document360 rate limit \u2014 waiting ${Math.ceil(B.waitMs/1e3)}s\u2026`)}),_=Jp(await Qp({cwd:e,profileName:s})),N=tl(M);N?u({kind:"note",tone:"info",text:N}):M.skipped&&u({kind:"note",tone:"warn",text:`Order sync skipped: ${M.skipped}`}),_&&u({kind:"note",tone:"info",text:_}),u({kind:"note",tone:"ok",text:N||_?"\u2713 Structure synced to Document360 \u2014 /structure shows the new category + article order.":"\u2713 Already in order \u2014 nothing to change."}),(N||_)&&te("/structure")}catch(M){u({kind:"note",tone:"warn",text:`Structure sync failed: ${M.message}`})}finally{Mt(null)}return}if(y){let j=(F?[...x,...S]:x).map(M=>M.path);await Bt(j),S.length>0&&!F&&te("/resolve");return}an({cursor:0,rows:$d(x,S)})}catch(w){u({kind:"note",tone:"error",text:`Could not compute sync status: ${w.message}`}),u({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"resolve":{if(!_o(d.trim()))return;await Is(m.find(f=>!f.startsWith("--")));return}case"preview":{let f=m.join(" ").trim();if(!f){let k=[];try{k=Object.keys(Hp(e,We(e,s).name)?.articles??{})}catch{}if(k.length===0){u({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}Lt({query:"",cursor:0,paths:k});return}let y=Zk(f)?f:za(e,f);if(An(y)){try{u({kind:"preview",name:Co(y),text:nh(us(y,"utf8"))})}catch(k){u({kind:"note",tone:"error",text:`Could not read ${y}: ${k.message}`})}return}if(qb.test(f)){try{let k=We(e,s),w={profile:k.name,connection:k.connection},x=k.project.projectId??sb(w),S=await ib(w,x,f);u({kind:"preview",name:S.title??f,text:S.content??"*(article has no content)*"})}catch(k){u({kind:"note",tone:"error",text:`Could not fetch article: ${k.message}`})}return}u({kind:"note",tone:"error",text:`"${f}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let f=m[0]?.trim();if(!f){let x=Ur(ol(e));jt({cursor:x,current:x});return}let{lines:y,changed:k,effective:w}=lo(e,f);for(let x of y)u({kind:"note",tone:x.startsWith("\u26A0")?"warn":x.startsWith("\u2713")?"ok":"info",text:x});k&&(yl(x=>x+1),He.current?.setModel(w));return}case"convert":{if(!le(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:f,run:y}=Di(m),k=Sb(e,s);if(k.length===0){u({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let w=Ei(k,f);if(w.length===0){u({kind:"note",tone:"error",text:`No tracked articles under "${f}". (${k.length} are tracked overall.)`});return}let x=Qa(w),S=3,F=`/convert${f?` --scope ${f}`:""} --run`,q=hs(e,"light");if(!y){let M=Yp({files:Ai(e,w),op:"convert",model:q.model}),_=f?`Scope: ${f} (${w.length} of ${k.length} tracked)
|
|
424
423
|
`:"",N=`
|
|
425
|
-
Model: ${q.model}${q.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;u({kind:"note",tone:"info",text:_+
|
|
426
|
-
`)+N}),te(F);return}
|
|
427
|
-
`)})}}catch(M){u({kind:"note",tone:"error",text:`Convert run failed: ${M.message}`})}finally{
|
|
428
|
-
`:"",
|
|
429
|
-
Model: ${B.model}${B.forced?" (forced)":" \u2014 authoring; /model to override"}`;u({kind:"note",tone:"info",text:
|
|
430
|
-
`)+
|
|
431
|
-
`)}),!
|
|
424
|
+
Model: ${q.model}${q.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;u({kind:"note",tone:"info",text:_+Ni(x,M,S).join(`
|
|
425
|
+
`)+N}),te(F);return}Dt.current=Date.now(),Qt(0),T(!0);let j=new AbortController;Ce.current=j,ie({verb:"Converting",total:x.length,done:0,active:[],rows:xo(x),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Converting ${w.length} articles across ${x.length} partitions (\u2264${S} agents at once) on ${q.model}\u2026 (esc to stop)`});try{for await(let M of ps({cwd:e,partitions:x,promptFor:ji,concurrency:S,profileName:s,allowProdWrites:tn.current,model:q.model,signal:j.signal}))if(M.type==="partition_status")M.status==="running"?ie(_=>_&&{..._,active:[..._.active,M.label],rows:ze(_.rows,M.label,"active"),lastAt:Date.now()}):ie(_=>_&&{..._,active:_.active.filter(N=>N!==M.label),done:_.done+1,rows:ze(_.rows,M.label,M.status==="done"?"done":"failed"),lastAt:Date.now()});else if(M.type==="partition_event")ie(_=>{if(!_)return _;let N={..._,lastAt:Date.now()};return M.event.type==="tool"?N.tools=_.tools+1:M.event.type==="text"&&(N.chars=_.chars+M.event.delta.length),N});else if(M.type==="run_done"){dn(B=>B+M.totalCostUsd),cn(B=>B+M.results.reduce((de,st)=>de+st.outputTokens,0));let _=M.aborted?"Stopped. ":"",N=t.kind==="api"?"api":"subscription";u({kind:"note",tone:M.aborted?"warn":M.ok?"ok":"warn",text:_+Ii(M.results,x,N).join(`
|
|
426
|
+
`)})}}catch(M){u({kind:"note",tone:"error",text:`Convert run failed: ${M.message}`})}finally{Ce.current=null,ie(null),T(!1),K(M=>M+1)}return}case"write":{if(!le(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let f=Pb(e);if(f.length===0){u({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:y,path:k,preview:w,concurrency:x,rewrite:S}=_i(m),{docsDir:F,targets:q,reason:j,rewriting:M}=qi(e,f,{scope:y,path:k,rewrite:S});if(q.length===0){u({kind:"note",tone:"warn",text:j??"Nothing to write."});return}M&&u({kind:"note",tone:"warn",text:`--rewrite: regenerating ${q.length} already-written article${q.length===1?"":"s"} (overwrites them; git has your baseline).`});let _=Qa(q),N=Li(x),B=hs(e,"standard"),de=!!k;if(w&&!de){let J=Yp({files:Ui(e,f,q),op:"write",model:B.model}),he=y?`Scope: ${y} (${q.length} pending)
|
|
427
|
+
`:"",Re=`
|
|
428
|
+
Model: ${B.model}${B.forced?" (forced)":" \u2014 authoring; /model to override"}`;u({kind:"note",tone:"info",text:he+Wi(_,J,N).join(`
|
|
429
|
+
`)+Re}),te(`/write${y?` --scope ${y}`:""}`);return}Dt.current=Date.now(),Qt(0),T(!0);let st=new AbortController;Ce.current=st,ie({verb:"Writing",total:_.length,done:0,active:[],rows:xo(_),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Writing ${q.length} article${q.length===1?"":"s"} across ${_.length} partition${_.length===1?"":"s"} (\u2264${N} agents at once) on ${B.model}${B.forced?" (forced)":""}\u2026 (esc to stop)`});let fn=new Set;try{for await(let J of ps({cwd:e,partitions:_,promptFor:he=>Fi(he,F,{rewrite:M||de}),concurrency:N,profileName:s,allowProdWrites:tn.current,model:B.model,signal:st.signal}))if(J.type==="partition_status")J.status==="running"?ie(he=>he&&{...he,active:[...he.active,J.label],rows:ze(he.rows,J.label,"active"),lastAt:Date.now()}):ie(he=>he&&{...he,active:he.active.filter(Re=>Re!==J.label),done:he.done+1,rows:ze(he.rows,J.label,J.status==="done"?"done":"failed"),lastAt:Date.now()});else if(J.type==="partition_event"){let he=null;if(J.event.type==="tool"){let Re=Sp(J.event.name,J.event.input,_[J.index]?.paths??[]);Re&&!fn.has(Re)&&(fn.add(Re),he=J.label)}ie(Re=>{if(!Re)return Re;let Je={...Re,lastAt:Date.now()};return J.event.type==="tool"?Je.tools=Re.tools+1:J.event.type==="text"&&(Je.chars=Re.chars+J.event.delta.length),he&&(Je.rows=Rp(Je.rows,he)),Je})}else if(J.type==="run_done"){dn(ft=>ft+J.totalCostUsd),cn(ft=>ft+J.results.reduce((it,kh)=>it+kh.outputTokens,0));let he=J.aborted?"Stopped. ":"",Re=t.kind==="api"?"api":"subscription";if(u({kind:"note",tone:J.aborted?"warn":J.ok?"ok":"warn",text:he+Bi(J.results,_,Re).join(`
|
|
430
|
+
`)}),!J.aborted&&J.ok)try{let ft=(fn.size>0?[...fn]:q).map(it=>`${F}/${it}`);Ja(e,ft,{writtenCap:Za})}catch{}let Je=J.aborted?null:Hi(e,F,q);if(Je&&u({kind:"note",tone:"warn",text:Je}),!J.aborted&&J.ok){let ft=y??k??"",it=ft?` ${ft}`:"";_e(Je?`Written \u2014 but the checker flagged issues. I\u2019d fix those first with /check${it} --fix, then /review${it} --fix for editorial quality, then /publish --all (add /screenshot author --all first if you want images).`:`Written. I\u2019d run /review${it} --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:Je?`/check${it} --fix`:`/review${it} --fix`,reason:""})}}}catch(J){u({kind:"note",tone:"error",text:`Write run failed: ${J.message}`})}finally{Ce.current=null,ie(null),T(!1),K(J=>J+1)}return}case"draft":{if(!le(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:f,looseDocs:y}=Vi(e);if(f.length===0&&y===0){u({kind:"note",tone:"info",text:Yi});return}let k=m.join(" ").trim();if(!k&&f.length>1){u({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
|
|
432
431
|
${f.map(S=>` \u2022 ${S.name} (${S.docCount} doc${S.docCount===1?"":"s"})`).join(`
|
|
433
|
-
`)}`})
|
|
434
|
-
`)});return}if(f==="--baseline"){let w=m.find(q=>!q.startsWith("--")),x=w?w.replace(/\\/g,"/"):void 0;u({kind:"note",tone:"info",text:x?`Setting the sync baseline for ${x}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let S=await
|
|
432
|
+
`)}`}),$e(f.map(S=>`/draft ${S.name}`));return}let w="",x;if(k){let S=Gi(f,k);S?w=S:x=k}else w=f[0]?.name??"";await se(Mr(w,x),{display:k?`/draft ${k}`:"/draft",quietUser:!0});return}case"pull":{if(!_o(d.trim()))return;let f=m.find(y=>y.startsWith("--"));try{if(f==="--status"){u({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let w=Date.now(),x=await Xa({cwd:e,profileName:s});u({kind:"note",tone:"info",text:Or(x,Date.now()-w).join(`
|
|
433
|
+
`)});return}if(f==="--baseline"){let w=m.find(q=>!q.startsWith("--")),x=w?w.replace(/\\/g,"/"):void 0;u({kind:"note",tone:"info",text:x?`Setting the sync baseline for ${x}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let S=await kb({cwd:e,profileName:s,relPaths:x?[x]:void 0}),F=x?{rebaselined:[],skipped:[]}:await bb({cwd:e,profileName:s});if(S.baselined.length===0&&S.skipped.length===0&&F.rebaselined.length===0){u({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}S.baselined.length>0&&u({kind:"note",tone:"ok",text:`\u2713 Baselined ${S.baselined.length} article${S.baselined.length===1?"":"s"} \u2014 they now read in-sync until either side changes.`}),F.rebaselined.length>0&&u({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${F.rebaselined.length} article${F.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),S.skipped.length>0&&u({kind:"note",tone:"warn",text:`${S.skipped.length} skipped:
|
|
435
434
|
${S.skipped.map(q=>` - ${q.path} (${q.reason})`).join(`
|
|
436
|
-
`)}`}),
|
|
437
|
-
`)});return}if(f){u({kind:"note",tone:"error",text:`Unknown option: ${f} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let y=m[0];if(y){let w=await
|
|
438
|
-
`)}),
|
|
439
|
-
`)}),k.length>0&&
|
|
440
|
-
`)});return}case"reorder":{let f=
|
|
441
|
-
`)}),
|
|
442
|
-
`)});return}if(f.mode==="list"){if(!
|
|
443
|
-
`)}),
|
|
444
|
-
`)}),y&&u({kind:"note",tone:"info",text:y});let q=F.filter(B=>B.state==="placeholder").length,j=F.filter(B=>B.state==="spec").length,M=F.filter(B=>B.state==="captured").length,_=F.filter(B=>B.state==="rejected").length,N=F.filter(B=>B.state==="spec"&&!B.mutates).length;q>0?te(S?`/screenshot author ${S}`:"/screenshot author --all"):j>0&&(N>0||M===0)?te(S?`/screenshot capture ${S}`:"/screenshot capture"):M>0?te("/screenshot verify"):_>0&&te("/screenshot capture --failed");return}if(f.mode==="single"){await
|
|
445
|
-
`)}),Se(xo(e));return}default:u({kind:"note",tone:"error",text:`Unknown command: /${a} \u2014 type /help.`})}},[e,r,s,un,As,u,Le,ie,Wt,Ps,Cc]),Go=ee(d=>{let l=(d??$).trim();if(v(""),To(null),Xt(0),l.startsWith("/")&&(lt.current=!1,Pt.current=!1,Ke(),In(null),ze(m=>Pp(m,l))),!l||(ic(!1),Sc(l))||Rc(l))return;ms.current.push(l);let a=Ap(l,cc.current);if(l.startsWith("/"))u({kind:"user",text:l}),J(!0),Hn(a).finally(()=>J(!1));else if(Lb(a)){u({kind:"user",text:l});let m=_b(a);if(!m)ie(a,{display:l,quietUser:!0});else{try{Mb(e,{title:m,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}ie(`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${m}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${m}" and the article path(s) you wrote.`,{display:l,quietUser:!0})}}else{let m=Ku(e,a);ie(m??a,{display:l})}},[$,Sc,Rc,Hn,ie]),Pc=ee(d=>{if(d.length>1){if(d.includes("\x1B"))return;let l=Tp(d);if(Ep(l)){let a=Dp(++ph.current,l);cc.current.set(a,l),A(a)}else A(l);return}A(d)},[A]),pn=Math.max(10,Oe-6),Tc=Va(()=>as(h.text,pn),[h.text,pn]),js=ee(d=>b(l=>({...l,pos:Math.max(0,Math.min(l.text.length,l.pos+d))})),[]),Yo=ee(d=>b(l=>({...l,pos:Np(as(l.text,pn),l.pos,d)})),[pn]),qn=ee(d=>b(l=>({...l,pos:Ip(as(l.text,pn),l.pos,d)})),[pn]),gh=["\x1B[H","\x1B[1~","\x1BOH"],yh=["\x1B[F","\x1B[4~","\x1BOF"],Ec=ee((d,l)=>l.leftArrow?(js(-1),!0):l.rightArrow?(js(1),!0):d&&gh.includes(d)?(qn("start"),!0):d&&yh.includes(d)?(qn("end"),!0):l.ctrl&&d==="a"?(qn("start"),!0):l.ctrl&&d==="e"?(qn("end"),!0):!1,[js,qn]);return Qk((d,l)=>{if(l.ctrl&&d==="c"){We.current?.close(),r();return}if(!I){if(C){if(l.escape){if(xe.current){if(!xe.current.signal.aborted){let a=(Ao?.verb??"work").toLowerCase(),m=Ao?.unit??"article";u({kind:"note",tone:"warn",text:`\u238B Stopping the ${a} run (finishing in-flight ${m}s)\u2026`}),xe.current.abort()}return}On.current||(On.current=!0,u({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),We.current?.interrupt());return}if(l.return){let a=$.trim();if(!a)return;Lt.current.push(a),ys([...Lt.current]),v("");return}if(Ec(d,l))return;if(l.upArrow){Yo(-1);return}if(l.downArrow){Yo(1);return}if(l.backspace||l.delete){R();return}d&&!l.ctrl&&!l.meta&&Pc(d);return}if(Dt){if(l.upArrow){At(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){At(a=>a&&{...a,cursor:Math.min(Je.length-1,a.cursor+1)});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=Je.length){At(a=>a&&{...a,cursor:Number(d)-1});return}if(l.return){let a=Je[Dt.cursor];At(null);let{lines:m,changed:T,effective:G}=ao(e,a.value??"default");for(let f of m)u({kind:"note",tone:f.startsWith("\u26A0")?"warn":f.startsWith("\u2713")?"ok":"info",text:f});T&&(gc(f=>f+1),We.current?.setModel(G));return}if(d==="s"){let a=Je[Dt.cursor];At(null),We.current?.setModel(a.value??void 0),u({kind:"note",tone:"ok",text:`\u2713 Using ${a.label} for this session only (your saved default is unchanged).`});return}if(l.escape){At(null);return}return}if(tt){if(l.upArrow){tn(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){tn(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=tt.rows.length){tn(a=>a&&{...a,cursor:Number(d)-1});return}if(l.return||d==="s"){let a=tt.rows[tt.cursor];tn(null),Es(a.name,l.return===!0);return}if(l.escape){tn(null);return}return}if(No){if(l.escape){Mn(null);return}if(l.leftArrow||l.tab&&l.shift){Mn(a=>a&&{tab:(a.tab-1+He.length)%He.length});return}if(l.rightArrow||l.tab){Mn(a=>a&&{tab:(a.tab+1)%He.length});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=He.length){Mn({tab:Number(d)-1});return}return}if(nt){if(l.upArrow){nn(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){nn(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=nt.rows.length){nn(a=>a&&{...a,cursor:Number(d)-1});return}if(l.return){let a=nt.rows[nt.cursor].name;if(nn(null),!Hs(e,a).created){u({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}u({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${a}").`});let T=!1;try{let G=Yt(a);T=!!G&&!(St(G)&&!G.refreshToken)}catch{T=!1}u({kind:"note",tone:"info",text:T?`Next: sign in to ${a} and pick your project \u2014 you're already signed in here, so it'll be quick.`:`Next: sign in to Document360 (${a}) and pick your project.`}),te("/login"),z(G=>G+1);return}if(l.escape){nn(null);return}return}if(Re){if(l.upArrow){on(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){on(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=Re.rows.length){on(a=>a&&{...a,cursor:Number(d)-1});return}if(l.return){let a=Re.rows[Re.cursor],{profile:m,projectId:T}=Re;on(null),Ho(m,T,a);return}if(l.escape){on(null);return}return}if(Ae){if(l.upArrow){jt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){jt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=Ae.rows.length){jt(a=>a&&{...a,cursor:Number(d)-1});return}if(l.return){let a=Ae.rows[Ae.cursor],{profile:m}=Ae;jt(null),Vo(m,a);return}if(l.escape){jt(null);return}return}if(Pe){if(l.upArrow){sn(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){sn(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(d===" "){sn(a=>a&&{...a,rows:a.rows.map((m,T)=>T===a.cursor?{...m,checked:!m.checked}:m)});return}if(l.return){let a=Pe.rows.filter(m=>m.checked).map(m=>m.path);if(sn(null),a.length===0){u({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}ki(e,a),u({kind:"note",tone:"ok",text:`\u2713 Scoped to ${a.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let m of a)u({kind:"note",tone:"info",text:` ${m}`});u({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(l.escape){sn(null);return}return}if(ot){if(l.upArrow){It(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){It(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=ot.rows.length){It(a=>a&&{...a,cursor:Number(d)-1});return}if(l.return){let a=ot.rows[ot.cursor],m=ot.run;It(null),m(a.token);return}if(l.escape){It(null);return}return}if(ut){if(l.upArrow){rn(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){rn(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=ut.rows.length){rn(a=>a&&{...a,cursor:Number(d)-1});return}if(l.return){let a=ut.rows[ut.cursor];rn(null),a.conflict?As(a.paths[0]):a.kind==="article"?Ps(a.paths[0]):Wt(a.paths);return}if(l.escape){rn(null);return}return}if(pt){if(l.upArrow){Nt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){Nt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=pt.rows.length){Nt(a=>a&&{...a,cursor:Number(d)-1});return}if(l.return){let a=pt.rows[pt.cursor];Nt(null),a.action==="capture"?Bn(a.ids,{runLine:a.kind==="all"?["/screenshot capture --all","/capture --all"]:void 0}):a.kind==="shot"?xc(a.ids[0]):vc(a.ids,{setup:!0,runLine:a.kind==="all"?["/screenshot author --all","/screenshot --all"]:void 0});return}if(l.escape){Nt(null);return}return}if(je){if(l.escape){Ot(null);return}if(l.upArrow){Ot(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){Ot(a=>a&&{...a,cursor:Math.min(Math.max(0,Fo.length-1),a.cursor+1)});return}if(l.return){let a=Fo[je.cursor];if(a){Ot(null);try{u({kind:"preview",name:xo(a),text:eh(ls(Ga(e,a),"utf8"))})}catch(m){u({kind:"note",tone:"error",text:`Could not read ${a}: ${m.message}`})}}return}if(l.backspace||l.delete){Ot(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(d&&!l.ctrl&&!l.meta&&d.length===1){Ot(a=>a&&{...a,query:a.query+d,cursor:0});return}return}if(Ne){if(l.escape){Mt(null);return}if(l.upArrow){Mt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(l.downArrow){Mt(a=>a&&{...a,cursor:Math.min(Math.max(0,Wo.length-1),a.cursor+1)});return}if(l.return){let a=Wo[Ne.cursor];if(a){Mt(null),Le(a.uuid),et.current={uuid:a.uuid,firstPrompt:a.firstPrompt,titleFired:!0},Et(a.name),Ya(a.uuid),Jt.current=[];let m=Wa(e,a.uuid);for(let T of m)u(T);u({kind:"note",tone:"ok",text:m.length?`Resumed "${a.name}" \u2014 restored ${m.length} message(s); continue where you left off.`:`Resumed "${a.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(l.backspace||l.delete){Mt(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(d&&!l.ctrl&&!l.meta&&d.length===1){Mt(a=>a&&{...a,query:a.query+d,cursor:0});return}return}if(l.tab&&!$&&re){v(re),Ke();return}if(!$&&Fe.length>0&&!zt&&d&&/^[1-9]$/.test(d)){let a=Fe[Number(d)-1];if(a){v(Gt(a));return}}if(!$&&(Lo||Un)&&d==="c"&&!l.ctrl&&!l.meta&&!l.return&&!l.tab){let a=Lo!=null;Ua(Lo??Un).then(T=>{u({kind:"note",tone:T?"ok":"warn",text:T?a?"\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.":a?"Couldn't reach your clipboard \u2014 select the feedback above and copy it manually.":"Couldn't reach your clipboard \u2014 select the prompt above and copy it manually."}),T&&a&&xs(null),T&&!a&&wc(!0)});return}if(!Ec(d,l)){if(bc){if(l.upArrow){Xt(a=>Math.max(0,a-1));return}if(l.downArrow){Xt(a=>Math.min(Xe.length-1,a+1));return}if(l.tab){v("/"+(Xe[fs]?.name??"")+" "),Xt(0);return}if(l.return){let a=Xe[fs];if(a){let m=$.trim().slice(1).split(/\s+/).slice(1).join(" ");if(vl(a.usage)&&!m){v("/"+a.name+" "),Xt(0);return}Go("/"+a.name+(m?" "+m:""));return}}}else{if(l.upArrow){if($!==""&&Qt===null){Yo(-1);return}let a=ms.current;if(!a.length)return;let m=Qt===null?a.length-1:Math.max(0,Qt-1);To(m),v(a[m]??"");return}if(l.downArrow){if($!==""&&Qt===null){Yo(1);return}let a=ms.current;if(Qt===null)return;let m=Qt+1;m>=a.length?(To(null),v("")):(To(m),v(a[m]??""));return}}if(l.return){Go();return}if(l.backspace||l.delete){R();return}if(l.escape){v(""),Xt(0),Ke(),ze([]),In(null),lt.current=!0;return}d&&!l.ctrl&&!l.meta&&Pc(d)}}}),Ue(()=>{if(C||I)return;let d=Lt.current.shift();d!==void 0&&(ys([...Lt.current]),Go(d))},[C,I,Go]),ne(ue,{flexDirection:"column",width:Oe,children:[Ss!==null&&ne(ue,{marginTop:1,flexDirection:"column",children:[Ss.truncated&&L(O,{dimColor:!0,children:"\u2026"}),L(O,{children:Ss.text})]}),C&&(Ao?L(Yb,{p:Ao}):L(qb,{startTime:Tt.current,chars:uh})),!C&&hc?L(Vb,{text:hc}):null,L(ue,{borderStyle:"round",borderColor:kc.prod?"yellow":Z,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:$?Tc.map((d,l)=>{let a=h.text.slice(d.start,d.end),m=l===cs(Tc,h.pos),T=Math.min(h.pos,d.end)-d.start;return ne(O,{children:[L(O,{color:Z,children:l===0?"> ":" "}),m?ne(Co,{children:[a.slice(0,T),L(An,{ch:a[T]??" "}),a.slice(T+1)]}):a||" "]},`${l}-${d.start}`)}):ne(O,{children:[L(O,{color:Z,children:"> "}),ws?L(An,{ch:" "}):re&&!C&&ae?ne(Co,{children:[L(An,{ch:ae[0],dim:!0}),L(O,{color:"gray",children:ae.slice(1)})]}):re&&!C?ne(Co,{children:[L(An,{ch:re[0],dim:!0}),L(O,{color:"gray",children:re.slice(1)}),L(O,{dimColor:!0,children:" (tab)"})]}):(Cs.isSetup||!lh)&&!C?ne(Co,{children:[L(An,{ch:Cs.text[0],dim:!0}),L(O,{color:"gray",children:Cs.text.slice(1)})]}):L(An,{ch:" "})]})}),pc.length>0&&L(ue,{flexDirection:"column",paddingX:1,children:pc.map((d,l)=>L(O,{color:"gray",children:`\u29D7 queued: ${d}`},`${l}-${d.slice(0,24)}`))}),No?L($p,{tab:No.tab,width:Oe,version:o,engineVersion:th}):Dt?ne(ue,{flexDirection:"column",paddingX:1,children:[L(O,{color:Z,bold:!0,children:"Select model"}),L(O,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),Je.map((d,l)=>ne(O,{color:l===Dt.cursor?Z:void 0,children:[l===Dt.cursor?"\u276F ":" ",`${l+1}. ${d.label}${l===Dt.current?" \u2714":""}`.padEnd(16),L(O,{color:"gray",children:d.desc})]},d.label)),L(O,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):tt?ne(ue,{flexDirection:"column",paddingX:1,children:[L(O,{color:Z,bold:!0,children:"Switch connection profile"}),tt.rows.map((d,l)=>ne(O,{color:l===tt.cursor?Z:void 0,children:[l===tt.cursor?"\u276F ":" ",`${l+1}. ${d.name}${l===tt.current?" \u2714":""}`.padEnd(20),L(O,{color:"gray",children:`${d.env} \xB7 ${d.who??"not signed in"}`}),d.prod?L(O,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},d.name)),L(O,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):nt?ne(ue,{flexDirection:"column",paddingX:1,children:[L(O,{color:Z,bold:!0,children:"Pick your Document360 environment"}),nt.rows.map((d,l)=>ne(O,{color:l===nt.cursor?Z:void 0,children:[l===nt.cursor?"\u276F ":" ",`${l+1}. ${d.name}`.padEnd(16),L(O,{color:"gray",children:d.apiUrl})]},d.name)),L(O,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):Re?ne(ue,{flexDirection:"column",paddingX:1,children:[L(O,{color:Z,bold:!0,children:"Switch workspace"}),L(O,{dimColor:!0,children:`environment ${Re.environment} \xB7 project ${Re.projectName??`${Re.projectId.slice(0,8)}\u2026`}`}),Re.rows.map((d,l)=>ne(O,{color:l===Re.cursor?Z:void 0,children:[l===Re.cursor?"\u276F ":" ",`${l+1}. ${d.name}${l===Re.current?" \u2714":""}`.padEnd(30),L(O,{color:"gray",children:d.type??""})]},d.id)),L(O,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):Ae?ne(ue,{flexDirection:"column",paddingX:1,children:[L(O,{color:Z,bold:!0,children:"Choose project"}),L(O,{dimColor:!0,children:`environment ${Ae.environment}`}),Ae.rows.map((d,l)=>ne(O,{color:l===Ae.cursor?Z:void 0,children:[l===Ae.cursor?"\u276F ":" ",`${l+1}. ${d.name}${l===Ae.current?" \u2714":""}`.padEnd(30),L(O,{color:"gray",children:d.sub??""})]},d.id)),L(O,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):Pe?(()=>{let l=Math.min(Math.max(0,Pe.cursor-Math.floor(7)),Math.max(0,Pe.rows.length-14)),a=Pe.rows.slice(l,l+14),m=Pe.rows.filter(T=>T.checked).length;return ne(ue,{flexDirection:"column",paddingX:1,children:[L(O,{color:Z,bold:!0,children:`Which folders back the user docs? (${m} selected of ${Pe.rows.length})`}),l>0?L(O,{dimColor:!0,children:` \u2191 ${l} more`}):null,a.map((T,G)=>{let f=l+G;return ne(O,{color:f===Pe.cursor?Z:void 0,children:[f===Pe.cursor?"\u276F ":" ",T.checked?"\u25C9 ":"\u25CB ",T.path.padEnd(Math.min(48,Oe-34)),L(O,{color:"gray",children:jr(T)})]},T.path)}),l+14<Pe.rows.length?L(O,{dimColor:!0,children:` \u2193 ${Pe.rows.length-l-14} more`}):null,L(O,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():ot?ne(ue,{flexDirection:"column",paddingX:1,children:[L(O,{color:Z,bold:!0,children:"Which category? (pick one to scope to)"}),ot.rows.map((d,l)=>{let a=l===ot.cursor,m=`${l+1}.`.padEnd(3);return ne(O,{color:a?Z:void 0,children:[a?"\u276F ":" ",`${m} ${d.label} (${d.count})`.padEnd(Math.min(44,Math.max(20,Oe-24))),L(O,{color:"gray",children:` ${d.token}`})]},d.token)}),L(O,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):ut?ne(ue,{flexDirection:"column",paddingX:1,children:[L(O,{color:Z,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),ut.rows.map((d,l)=>{let a=l===ut.cursor,m=d.indent?" ":" ",T=`${l+1}.`.padEnd(3);return ne(O,{color:a?Z:void 0,bold:d.kind==="category"&&!a,children:[a?"\u276F ":" ",`${m}${T} ${d.label}`.padEnd(Math.min(56,Oe-24)),d.note?L(O,{color:"gray",children:d.note}):null]},`${d.kind}:${d.paths.join(",")}`)}),L(O,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):pt?ne(ue,{flexDirection:"column",paddingX:1,children:[L(O,{color:Z,bold:!0,children:pt.title}),(()=>{let{rows:l,cursor:a}=pt,m=Math.max(0,Math.min(a-Math.floor(12/2),l.length-12)),T=l.slice(m,m+12),G=`${l.length}.`.length+1,f=pd(l,Math.max(20,Oe-4-G));return ne(Co,{children:[m>0?L(O,{color:"gray",children:` \u2026 ${m} more above`}):null,T.map((y,k)=>{let w=m+k,x=w===a,S=f[w];return ne(O,{color:x?Z:void 0,bold:(y.kind==="all"||y.kind==="category")&&!x,children:[x?"\u276F ":" ",`${w+1}.`.padEnd(G),S.head,S.note?L(O,{color:"gray",children:S.note}):null]},`${y.action}:${y.kind}:${y.ids.join(",")}`)}),m+12<l.length?L(O,{color:"gray",children:` \u2026 ${l.length-m-12} more below`}):null]})})(),L(O,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter run \xB7 esc cancel"})]}):je?ne(ue,{flexDirection:"column",paddingX:1,children:[L(O,{color:Z,bold:!0,children:`Preview article${je.query?` \u2014 filter: ${je.query}`:" (type to filter)"}`}),Fo.length===0?L(O,{color:"gray",children:"no articles match"}):Fo.map((d,l)=>ne(O,{color:l===je.cursor?Z:void 0,children:[l===je.cursor?"\u276F ":" ",d]},d)),L(O,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):Ne?ne(ue,{flexDirection:"column",paddingX:1,children:[L(O,{color:Z,bold:!0,children:`Resume session${Ne.query?` \u2014 filter: ${Ne.query}`:" (type to filter)"}`}),Wo.length===0?L(O,{color:"gray",children:"no sessions match"}):Wo.map((d,l)=>ne(O,{color:l===Ne.cursor?Z:void 0,children:[l===Ne.cursor?"\u276F ":" ",d.name.slice(0,28).padEnd(30),L(O,{color:l===Ne.cursor?Z:"gray",children:d.firstPrompt.slice(0,Math.max(10,Oe-40))})]},d.uuid)),L(O,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):bc?ne(ue,{flexDirection:"column",children:[Ft>0?L(O,{dimColor:!0,children:` \u22EF ${Ft} more above`}):null,Rs.map((d,l)=>{let a=Ft+l,m=d.name==="model"&&ks?`${d.desc} (currently ${ks})`:d.desc,T=Math.max(20,Oe-4),G=d.usage.length>T?`${d.usage.slice(0,T-1)}\u2026`:d.usage,f=T-Math.max(G.length,22)-1,y=f<=1?"":m.length>f?`${m.slice(0,f-1)}\u2026`:m;return ne(O,{color:a===Uo?Z:void 0,children:[a===Uo?"\u276F ":" ",G.padEnd(22)," ",L(O,{color:a===Uo?Z:"gray",children:y})]},d.name)}),Ft+Rs.length<Xe.length?L(O,{dimColor:!0,children:` \u22EF ${Xe.length-Ft-Rs.length} more below`}):null,L(O,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!C&&!$&&Fe.length>0?ne(ue,{flexDirection:"column",paddingX:1,children:[uc?L(O,{color:Z,children:uc}):null,Fe.map((d,l)=>{let a=Gt(d),m=a.slice(0,Math.max(20,Oe-5)),T=Oe-m.length-7,G=T>=12?(Sp(d)??bl(a)).slice(0,T):"";return ne(O,{children:[L(O,{color:Z,children:l+1})," ",m,G?L(O,{dimColor:!0,children:` \u2014 ${G}`}):null]},a)}),L(O,{dimColor:!0,children:`press 1-${Fe.length} to fill \xB7 esc cancel`})]}):L(ue,{paddingX:1,children:ne(O,{color:"gray",children:[kc.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${ks??"model n/a"}${t.kind==="api"?mc>0?` \xB7 ${Ee(mc)}`:"":fc>0?` \xB7 ${bt(fc)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}K();import{jsx as Qb}from"react/jsx-runtime";async function oh(e=process.cwd(),t="auto",n,o="0.0.0"){let r=Xb(t);r.kind==="none"&&(console.error(""),console.error(E("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${W("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${W("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=Kb(Qb(nh,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
|
|
446
|
-
`),process.exit(0)}
|
|
447
|
-
`+
|
|
435
|
+
`)}`}),K(q=>q+1);return}if(f==="--compare"){u({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let w=await wb({cwd:e,profileName:s}),x=w.onlyInLegacy.length===0&&w.onlyInManifest.length===0&&w.mappedMissingFromManifest.length===0,S=[`Legacy listing: ${w.legacyCount} \xB7 Manifest: ${w.manifestCount} \xB7 in both: ${w.inBoth}`];x?S.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(w.mappedMissingFromManifest.length&&S.push(`\u2717 ${w.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${w.mappedMissingFromManifest.slice(0,5).join(", ")}`),w.onlyInLegacy.length&&S.push(`\u26A0 ${w.onlyInLegacy.length} only in the legacy listing: ${w.onlyInLegacy.slice(0,5).join(", ")}`),w.onlyInManifest.length&&S.push(`\u26A0 ${w.onlyInManifest.length} only in the manifest: ${w.onlyInManifest.slice(0,5).join(", ")}`),S.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),u({kind:"note",tone:x?"ok":"warn",text:S.join(`
|
|
436
|
+
`)});return}if(f){u({kind:"note",tone:"error",text:`Unknown option: ${f} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let y=m[0];if(y){let w=await Gp({cwd:e,profileName:s,relPath:y.replace(/\\/g,"/")});ye.current=[{plan:w,mode:w.overwritesLocalChanges?"conflict":"pull"}],nn.current=[],pn();return}u({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let k=await Si({cwd:e,profileName:s});for(let w of Pi(k))u({kind:"note",tone:w.tone,text:w.text});K(w=>w+1)}catch(y){u({kind:"note",tone:"error",text:`Pull failed: ${y.message}`})}return}case"scope":{if(!le(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let f=$b(e);if(f.length===0){u({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.'});return}ln({cursor:0,rows:f.map(y=>({...y,checked:y.recommended}))});return}case"audit":{if(m[0]==="--auto"){let y=le(e);if(!y){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let k=m[1]!=="off";Bp({...y,autoAudit:k},e),u({kind:"note",tone:"ok",text:k?"\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 io();f.kind==="forward-to-agent"&&f.prompt&&await se(f.prompt,{display:f.display,quietUser:!0});return}case"check":{let f=m.find(w=>!w.startsWith("--")),y=f?` ${f}`:"",k=Vp({cwd:e,scope:f});if(m.includes("--fix")){if(k.length===0){u({kind:"note",tone:"ok",text:"\u2713 Nothing to fix \u2014 the docs are already clean."});return}u({kind:"note",tone:"info",text:`Fixing ${k.length} doc issue${k.length===1?"":"s"}\u2026`});let w=Xp(e,f);await se(Ra(k),{display:`/check${y} --fix`,quietUser:!0});try{Ja(e,w,{reviewedCap:Za})}catch{}let x=Vp({cwd:e,scope:f});u({kind:"note",tone:x.length===0?"ok":"warn",text:x.length===0?"\u2713 Doc-checker: all issues resolved.":Yr(x).join(`
|
|
437
|
+
`)}),_e(x.length===0?`Deterministic issues fixed. Next: /review${y} --fix for editorial quality (style, grammar, structure), then /publish --all.`:`Some issues remain \u2014 /review${y} --fix runs the editorial review + fixes, then /publish --all.`,{kind:"cmd",cmd:`/review${y} --fix`,reason:""});return}u({kind:"note",tone:k.length===0?"ok":"warn",text:Yr(k).join(`
|
|
438
|
+
`)}),k.length>0&&_e(`Found ${k.length} doc issue${k.length===1?"":"s"} above. /check${y} --fix has the agent fix them in place (or /review${y} --fix for the full editorial pass; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/check${y} --fix`,reason:""});return}case"structure":{let f=wo(e,s);if(f.length===0){u({kind:"note",tone:"info",text:"No documentation structure yet \u2014 run /init and author some articles first."});return}u({kind:"note",tone:"info",text:["Documentation order (categories \u2192 articles):","",...f].join(`
|
|
439
|
+
`)});return}case"reorder":{let f=Pa(e,m);if(!f){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await se(f.prompt,{display:f.display,quietUser:!0}),_e("Reordered locally \u2014 /publish --all syncs the new order to Document360.",{kind:"cmd",cmd:"/publish --all",reason:""});return}case"review":{let f=Sa(e,m);if(!f){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let y=m.includes("--fix"),k=m.find(x=>!x.startsWith("--")),w=y?Xp(e,k):[];if(await se(f.prompt,{display:f.display,quietUser:!0}),y)try{Ja(e,w,{reviewedCap:Za})}catch{}if(y)_e("\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).",{kind:"cmd",cmd:"/publish --all",reason:""});else{let x=m.filter(S=>S!=="--fix").join(" ");_e(`The review listed issues above. /review${x?` ${x}`:""} --fix lets the editor apply them all (or /check --fix for just the deterministic ones; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/review${x?` ${x}`:""} --fix`,reason:""})}return}case"capture-setup":{await G();return}case"devhints":{if(!le(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}u({kind:"note",tone:"info",text:kn(wn(e)).join(`
|
|
440
|
+
`)}),ht(qt()),Wn.current=Ge(e).status==="current",un.current=at(e);return}case"discover":{if(!le(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await se($i(),{display:"/discover",quietUser:!0});return}case"inbox":{if(!le(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(ha(e)===0){u({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 se(fa(),{display:"/inbox",quietUser:!0});return}case"feedback":{let f=Kp(e),y="";try{y=An(f)?us(f,"utf8"):""}catch{y=""}if(!/^## /m.test(y)){u({kind:"note",tone:"info",text:"No open d360-writer feedback to copy \u2014 nothing logged in .d360-writer/tool-feedback.md yet."});return}let k=await Wa(y.trim());u({kind:"note",tone:k?"ok":"warn",text:k?"\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.`}),k&&Ss(null);return}case"document":{if(!le(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:f,what:y}=Ki(m);if(!y&&zi(e)===0){u({kind:"note",tone:"info",text:Qi});return}let k=`/document${y?` ${y}`:""}${f?" --publish":""}`;await se(Xi(y,f),{display:k,quietUser:!0});return}case"catch-up":{if(!le(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!_o(d.trim()))return;let{publish:f}=ga(m);u({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let y=await wa({cwd:e,profileName:s});for(let w of ka(y))u({kind:"note",tone:w.startsWith("\u2713")?"ok":w.startsWith("\u2139")?"info":"warn",text:w});let k=yo(go(e));u({kind:"note",tone:"info",text:k?`Catching up on ${k}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"}),await se(ya({publish:f}),{display:`/catch-up${f?" --publish":""}`,quietUser:!0});return}case"update":{Cs.current=!0,u({kind:"note",tone:"info",text:"Updating the d360-writer toolchain\u2026 (don\u2019t close this window)"}),Do(!0);let f=await Vr().finally(()=>Do(!1));f.ok?(u({kind:"note",tone:"ok",text:`\u2713 Updated ${f.packages.join(" + ")} \u2014 run /exit, then relaunch to apply.`}),te("/exit"),ll("")):u({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${qr}`});return}case"screenshot":{let f=to(m),y=no(e);if(y&&f.mode!=="list"&&u({kind:"note",tone:"info",text:y}),f.mode==="capture"){await D(f.rest);return}if(f.mode==="checklist"){await G();return}if(f.mode==="verify"){let x=ve(e),S=f.rest.find(j=>!j.startsWith("-")),F=S?[S]:uo(x);if(S&&!x.some(j=>j.id===S)){u({kind:"note",tone:"error",text:`No screenshot placeholder called "${S}". /screenshot list shows them all.`});return}if(F.length===0){let j=x.filter(_=>_.state==="rejected").length,M=x.filter(_=>_.state==="verified").length;u({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.`:M>0?`All ${M} captured shot${M===1?" is":"s are"} already verified.`:"No captured screenshots to verify yet \u2014 /screenshot capture takes the shots first."});return}u({kind:"note",tone:"info",text:po(F.length)}),await se(Gt(e,F),{display:S?`/screenshot verify ${S}`:"/screenshot verify",quietUser:!0});let q=ho(e,F);q.length>0&&u({kind:"note",tone:"info",text:q.join(`
|
|
441
|
+
`)});return}if(f.mode==="list"){if(!le(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let x=le(e)?.docsDir??rl,S=fi(e,f.scope),F=ve(e,S);if(f.picker){if(F.length===0){u({kind:"note",tone:"info",text:"No screenshot placeholders found in the docs."});return}let B=fd(F);if(B.length===0){u({kind:"note",tone:"info",text:Pr(F,{docsDir:x}).join(`
|
|
442
|
+
`)}),_e(`\u2713 All ${F.length} screenshots are captured. /publish puts them in the articles; /screenshot capture re-captures.`,{kind:"cmd",cmd:"/publish",reason:""});return}It({cursor:0,rows:B,title:"Screenshots \u2014 pick what to author or capture:"});return}u({kind:"note",tone:"info",text:Pr(F,{scope:S,detail:f.detail,docsDir:x}).join(`
|
|
443
|
+
`)}),y&&u({kind:"note",tone:"info",text:y});let q=F.filter(B=>B.state==="placeholder").length,j=F.filter(B=>B.state==="spec").length,M=F.filter(B=>B.state==="captured").length,_=F.filter(B=>B.state==="rejected").length,N=F.filter(B=>B.state==="spec"&&!B.mutates).length;q>0?te(S?`/screenshot author ${S}`:"/screenshot author --all"):j>0&&(N>0||M===0)?te(S?`/screenshot capture ${S}`:"/screenshot capture"):M>0?te("/screenshot verify"):_>0&&te("/screenshot capture --failed");return}if(f.mode==="single"){await Cl(f.id);return}if(!le(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let k=f.mode==="scope"?f.scope:void 0,w=Rb(e,{scope:k}).map(x=>x.id);if(w.length===0){u({kind:"note",tone:"info",text:k?`No screenshot placeholders under ${k}.`:"No screenshot placeholders found in the docs."});return}await xl(w,{setup:f.setup,runLine:f.mode==="scope"?[`/screenshot author ${f.scope}`,`/screenshot ${f.scope}`]:["/screenshot author --all","/screenshot --all"]});return}case"capture":{await D(m);return}case"reset":{let f=va(e);if(f.length===0){u({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}jo.current={repoName:Co(e),targets:f,hadDevhints:An(zp(e))},u({kind:"note",tone:"warn",text:Ca(e,f).join(`
|
|
444
|
+
`)}),Te(Co(e));return}default:u({kind:"note",tone:"error",text:`Unknown command: /${a} \u2014 type /help.`})}},[e,r,s,pn,Is,u,Ue,se,Bt,Es,Rl]),zo=ee(d=>{let c=(d??$).trim();if(v(""),Eo(null),Jt(0),c.startsWith("/")&&(Kt.current=!1,Pt.current=!1,Xe(),On(null),$e(m=>Dp(m,c))),!c||(So(!1),Pl(c))||Sl(c))return;ys.current.push(c);let a=Np(c,cl.current);if(c.startsWith("/"))u({kind:"user",text:c}),Se(!0),qn(a).finally(()=>Se(!1));else if(Ob(a)){u({kind:"user",text:c});let m=Lb(a);if(!m)se(a,{display:c,quietUser:!0});else{try{_b(e,{title:m,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}se(`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${m}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${m}" and the article path(s) you wrote.`,{display:c,quietUser:!0})}}else{let m=Qu(e,a);se(m??a,{display:c})}},[$,Pl,Sl,qn,se]),Tl=ee(d=>{if(d.length>1){if(d.includes("\x1B"))return;let c=Ep(d);if(Ap(c)){let a=jp(++hh.current,c);cl.current.set(a,c),E(a)}else E(c);return}E(d)},[E]),hn=Math.max(10,Me-6),Dl=Ya(()=>cs(h.text,hn),[h.text,hn]),Os=ee(d=>b(c=>({...c,pos:Math.max(0,Math.min(c.text.length,c.pos+d))})),[]),Ko=ee(d=>b(c=>({...c,pos:Op(cs(c.text,hn),c.pos,d)})),[hn]),Vn=ee(d=>b(c=>({...c,pos:Lp(cs(c.text,hn),c.pos,d)})),[hn]),yh=["\x1B[H","\x1B[1~","\x1BOH"],wh=["\x1B[F","\x1B[4~","\x1BOF"],El=ee((d,c)=>c.leftArrow?(Os(-1),!0):c.rightArrow?(Os(1),!0):d&&yh.includes(d)?(Vn("start"),!0):d&&wh.includes(d)?(Vn("end"),!0):c.ctrl&&d==="a"?(Vn("start"),!0):c.ctrl&&d==="e"?(Vn("end"),!0):!1,[Os,Vn]);return Xk((d,c)=>{if(c.ctrl&&d==="c"){He.current?.close(),r();return}if(!I){if(C){if(c.escape){if(Ce.current){if(!Ce.current.signal.aborted){let a=(No?.verb??"work").toLowerCase(),m=No?.unit??"article";u({kind:"note",tone:"warn",text:`\u238B Stopping the ${a} run (finishing in-flight ${m}s)\u2026`}),Ce.current.abort()}return}Ln.current||(Ln.current=!0,u({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),He.current?.interrupt());return}if(c.return){let a=$.trim();if(!a)return;_t.current.push(a),ks([..._t.current]),v("");return}if(El(d,c))return;if(c.upArrow){Ko(-1);return}if(c.downArrow){Ko(1);return}if(c.backspace||c.delete){R();return}d&&!c.ctrl&&!c.meta&&Tl(d);return}if(At){if(c.upArrow){jt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(c.downArrow){jt(a=>a&&{...a,cursor:Math.min(Ze.length-1,a.cursor+1)});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=Ze.length){jt(a=>a&&{...a,cursor:Number(d)-1});return}if(c.return){let a=Ze[At.cursor];jt(null);let{lines:m,changed:D,effective:G}=lo(e,a.value??"default");for(let f of m)u({kind:"note",tone:f.startsWith("\u26A0")?"warn":f.startsWith("\u2713")?"ok":"info",text:f});D&&(yl(f=>f+1),He.current?.setModel(G));return}if(d==="s"){let a=Ze[At.cursor];jt(null),He.current?.setModel(a.value??void 0),u({kind:"note",tone:"ok",text:`\u2713 Using ${a.label} for this session only (your saved default is unchanged).`});return}if(c.escape){jt(null);return}return}if(nt){if(c.upArrow){on(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(c.downArrow){on(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=nt.rows.length){on(a=>a&&{...a,cursor:Number(d)-1});return}if(c.return||d==="s"){let a=nt.rows[nt.cursor];on(null),js(a.name,c.return===!0);return}if(c.escape){on(null);return}return}if(Oo){if(c.escape){Un(null);return}if(c.leftArrow||c.tab&&c.shift){Un(a=>a&&{tab:(a.tab-1+Ve.length)%Ve.length});return}if(c.rightArrow||c.tab){Un(a=>a&&{tab:(a.tab+1)%Ve.length});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=Ve.length){Un({tab:Number(d)-1});return}return}if(ot){if(c.upArrow){rn(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(c.downArrow){rn(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=ot.rows.length){rn(a=>a&&{...a,cursor:Number(d)-1});return}if(c.return){let a=ot.rows[ot.cursor].name;if(rn(null),!Gs(e,a).created){u({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}u({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${a}").`});let D=!1;try{let G=zt(a);D=!!G&&!(St(G)&&!G.refreshToken)}catch{D=!1}u({kind:"note",tone:"info",text:D?`Next: sign in to ${a} and pick your project \u2014 you're already signed in here, so it'll be quick.`:`Next: sign in to Document360 (${a}) and pick your project.`}),te("/login"),K(G=>G+1);return}if(c.escape){rn(null);return}return}if(Pe){if(c.upArrow){sn(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(c.downArrow){sn(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=Pe.rows.length){sn(a=>a&&{...a,cursor:Number(d)-1});return}if(c.return){let a=Pe.rows[Pe.cursor],{profile:m,projectId:D}=Pe;sn(null),Vo(m,D,a);return}if(c.escape){sn(null);return}return}if(Ie){if(c.upArrow){Nt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(c.downArrow){Nt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=Ie.rows.length){Nt(a=>a&&{...a,cursor:Number(d)-1});return}if(c.return){let a=Ie.rows[Ie.cursor],{profile:m}=Ie;Nt(null),Yo(m,a);return}if(c.escape){Nt(null);return}return}if(De){if(c.upArrow){ln(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(c.downArrow){ln(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(d===" "){ln(a=>a&&{...a,rows:a.rows.map((m,D)=>D===a.cursor?{...m,checked:!m.checked}:m)});return}if(c.return){let a=De.rows.filter(m=>m.checked).map(m=>m.path);if(ln(null),a.length===0){u({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}vi(e,a),u({kind:"note",tone:"ok",text:`\u2713 Scoped to ${a.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let m of a)u({kind:"note",tone:"info",text:` ${m}`});u({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(c.escape){ln(null);return}return}if(rt){if(c.upArrow){Ot(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(c.downArrow){Ot(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=rt.rows.length){Ot(a=>a&&{...a,cursor:Number(d)-1});return}if(c.return){let a=rt.rows[rt.cursor],m=rt.run;Ot(null),m(a.token);return}if(c.escape){Ot(null);return}return}if(dt){if(c.upArrow){an(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(c.downArrow){an(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=dt.rows.length){an(a=>a&&{...a,cursor:Number(d)-1});return}if(c.return){let a=dt.rows[dt.cursor];an(null),a.conflict?Is(a.paths[0]):a.kind==="article"?Es(a.paths[0]):Bt(a.paths);return}if(c.escape){an(null);return}return}if(ut){if(c.upArrow){It(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(c.downArrow){It(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(d&&/^[1-9]$/.test(d)&&Number(d)<=ut.rows.length){It(a=>a&&{...a,cursor:Number(d)-1});return}if(c.return){let a=ut.rows[ut.cursor];It(null),a.action==="capture"?Hn(a.ids,{runLine:a.kind==="all"?["/screenshot capture --all","/capture --all"]:void 0}):a.kind==="shot"?Cl(a.ids[0]):xl(a.ids,{setup:!0,runLine:a.kind==="all"?["/screenshot author --all","/screenshot --all"]:void 0});return}if(c.escape){It(null);return}return}if(Oe){if(c.escape){Lt(null);return}if(c.upArrow){Lt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(c.downArrow){Lt(a=>a&&{...a,cursor:Math.min(Math.max(0,Bo.length-1),a.cursor+1)});return}if(c.return){let a=Bo[Oe.cursor];if(a){Lt(null);try{u({kind:"preview",name:Co(a),text:nh(us(za(e,a),"utf8"))})}catch(m){u({kind:"note",tone:"error",text:`Could not read ${a}: ${m.message}`})}}return}if(c.backspace||c.delete){Lt(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(d&&!c.ctrl&&!c.meta&&d.length===1){Lt(a=>a&&{...a,query:a.query+d,cursor:0});return}return}if(Le){if(c.escape){Ut(null);return}if(c.upArrow){Ut(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(c.downArrow){Ut(a=>a&&{...a,cursor:Math.min(Math.max(0,Ho.length-1),a.cursor+1)});return}if(c.return){let a=Ho[Le.cursor];if(a){Ut(null),Ue(a.uuid),tt.current={uuid:a.uuid,firstPrompt:a.firstPrompt,titleFired:!0},Et(a.name),Ka(a.uuid),en.current=[];let m=Ha(e,a.uuid);for(let D of m)u(D);u({kind:"note",tone:"ok",text:m.length?`Resumed "${a.name}" \u2014 restored ${m.length} message(s); continue where you left off.`:`Resumed "${a.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(c.backspace||c.delete){Ut(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(d&&!c.ctrl&&!c.meta&&d.length===1){Ut(a=>a&&{...a,query:a.query+d,cursor:0});return}return}if(c.tab&&!$&&ke){v(ke),Xe();return}if(!$&&ae.length>0&&!Tt&&d&&/^[1-9]$/.test(d)){let a=ae[Number(d)-1];if(a){v(Yt(a));return}}if(!$&&(Mo||Fn)&&d==="c"&&!c.ctrl&&!c.meta&&!c.return&&!c.tab){let a=Mo!=null;Wa(Mo??Fn).then(D=>{u({kind:"note",tone:D?"ok":"warn",text:D?a?"\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.":a?"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."}),D&&a&&Ss(null),D&&!a&&kl(!0)});return}if(!El(d,c)){if($l){if(c.upArrow){Jt(a=>Math.max(0,a-1));return}if(c.downArrow){Jt(a=>Math.min(Qe.length-1,a+1));return}if(c.tab){v("/"+(Qe[gs]?.name??"")+" "),Jt(0);return}if(c.return){let a=Qe[gs];if(a){let m=$.trim().slice(1).split(/\s+/).slice(1).join(" ");if(xc(a.usage)&&!m){v("/"+a.name+" "),Jt(0);return}zo("/"+a.name+(m?" "+m:""));return}}}else{if(c.upArrow){if($!==""&&Zt===null){Ko(-1);return}let a=ys.current;if(!a.length)return;let m=Zt===null?a.length-1:Math.max(0,Zt-1);Eo(m),v(a[m]??"");return}if(c.downArrow){if($!==""&&Zt===null){Ko(1);return}let a=ys.current;if(Zt===null)return;let m=Zt+1;m>=a.length?(Eo(null),v("")):(Eo(m),v(a[m]??""));return}}if(c.return){zo();return}if(c.backspace||c.delete){R();return}if(c.escape){v(""),Jt(0),Xe(),$e([]),On(null),Kt.current=!0;return}d&&!c.ctrl&&!c.meta&&Tl(d)}}}),Be(()=>{if(C||I)return;let d=_t.current.shift();d!==void 0&&(ks([..._t.current]),zo(d))},[C,I,zo]),ne(ce,{flexDirection:"column",width:Me,children:[Ds!==null&&ne(ce,{marginTop:1,flexDirection:"column",children:[Ds.truncated&&L(O,{dimColor:!0,children:"\u2026"}),L(O,{children:Ds.text})]}),C&&(No?L(zb,{p:No}):L(Vb,{startTime:Dt.current,chars:ph})),!C&&fl?L(Gb,{text:fl}):null,L(ce,{borderStyle:"round",borderColor:bl.prod?"yellow":Z,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:$?Dl.map((d,c)=>{let a=h.text.slice(d.start,d.end),m=c===ds(Dl,h.pos),D=Math.min(h.pos,d.end)-d.start;return ne(O,{children:[L(O,{color:Z,children:c===0?"> ":" "}),m?ne(Ro,{children:[a.slice(0,D),L(jn,{ch:a[D]??" "}),a.slice(D+1)]}):a||" "]},`${c}-${d.start}`)}):ne(O,{children:[L(O,{color:Z,children:"> "}),bs?L(jn,{ch:" "}):ke&&!C&&Y?ne(Ro,{children:[L(jn,{ch:Y[0],dim:!0}),L(O,{color:"gray",children:Y.slice(1)})]}):ke&&!C?ne(Ro,{children:[L(jn,{ch:ke[0],dim:!0}),L(O,{color:"gray",children:ke.slice(1)}),L(O,{dimColor:!0,children:" (tab)"})]}):(Ps.isSetup||!Po)&&!C?ne(Ro,{children:[L(jn,{ch:Ps.text[0],dim:!0}),L(O,{color:"gray",children:Ps.text.slice(1)})]}):L(jn,{ch:" "})]})}),hl.length>0&&L(ce,{flexDirection:"column",paddingX:1,children:hl.map((d,c)=>L(O,{color:"gray",children:`\u29D7 queued: ${d}`},`${c}-${d.slice(0,24)}`))}),Oo?L(xp,{tab:Oo.tab,width:Me,version:o,engineVersion:oh}):At?ne(ce,{flexDirection:"column",paddingX:1,children:[L(O,{color:Z,bold:!0,children:"Select model"}),L(O,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),Ze.map((d,c)=>ne(O,{color:c===At.cursor?Z:void 0,children:[c===At.cursor?"\u276F ":" ",`${c+1}. ${d.label}${c===At.current?" \u2714":""}`.padEnd(16),L(O,{color:"gray",children:d.desc})]},d.label)),L(O,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):nt?ne(ce,{flexDirection:"column",paddingX:1,children:[L(O,{color:Z,bold:!0,children:"Switch connection profile"}),nt.rows.map((d,c)=>ne(O,{color:c===nt.cursor?Z:void 0,children:[c===nt.cursor?"\u276F ":" ",`${c+1}. ${d.name}${c===nt.current?" \u2714":""}`.padEnd(20),L(O,{color:"gray",children:`${d.env} \xB7 ${d.who??"not signed in"}`}),d.prod?L(O,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},d.name)),L(O,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):ot?ne(ce,{flexDirection:"column",paddingX:1,children:[L(O,{color:Z,bold:!0,children:"Pick your Document360 environment"}),ot.rows.map((d,c)=>ne(O,{color:c===ot.cursor?Z:void 0,children:[c===ot.cursor?"\u276F ":" ",`${c+1}. ${d.name}`.padEnd(16),L(O,{color:"gray",children:d.apiUrl})]},d.name)),L(O,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):Pe?ne(ce,{flexDirection:"column",paddingX:1,children:[L(O,{color:Z,bold:!0,children:"Switch workspace"}),L(O,{dimColor:!0,children:`environment ${Pe.environment} \xB7 project ${Pe.projectName??`${Pe.projectId.slice(0,8)}\u2026`}`}),Pe.rows.map((d,c)=>ne(O,{color:c===Pe.cursor?Z:void 0,children:[c===Pe.cursor?"\u276F ":" ",`${c+1}. ${d.name}${c===Pe.current?" \u2714":""}`.padEnd(30),L(O,{color:"gray",children:d.type??""})]},d.id)),L(O,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):Ie?ne(ce,{flexDirection:"column",paddingX:1,children:[L(O,{color:Z,bold:!0,children:"Choose project"}),L(O,{dimColor:!0,children:`environment ${Ie.environment}`}),Ie.rows.map((d,c)=>ne(O,{color:c===Ie.cursor?Z:void 0,children:[c===Ie.cursor?"\u276F ":" ",`${c+1}. ${d.name}${c===Ie.current?" \u2714":""}`.padEnd(30),L(O,{color:"gray",children:d.sub??""})]},d.id)),L(O,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):De?(()=>{let c=Math.min(Math.max(0,De.cursor-Math.floor(7)),Math.max(0,De.rows.length-14)),a=De.rows.slice(c,c+14),m=De.rows.filter(D=>D.checked).length;return ne(ce,{flexDirection:"column",paddingX:1,children:[L(O,{color:Z,bold:!0,children:`Which folders back the user docs? (${m} selected of ${De.rows.length})`}),c>0?L(O,{dimColor:!0,children:` \u2191 ${c} more`}):null,a.map((D,G)=>{let f=c+G;return ne(O,{color:f===De.cursor?Z:void 0,children:[f===De.cursor?"\u276F ":" ",D.checked?"\u25C9 ":"\u25CB ",D.path.padEnd(Math.min(48,Me-34)),L(O,{color:"gray",children:Ir(D)})]},D.path)}),c+14<De.rows.length?L(O,{dimColor:!0,children:` \u2193 ${De.rows.length-c-14} more`}):null,L(O,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():rt?ne(ce,{flexDirection:"column",paddingX:1,children:[L(O,{color:Z,bold:!0,children:"Which category? (pick one to scope to)"}),rt.rows.map((d,c)=>{let a=c===rt.cursor,m=`${c+1}.`.padEnd(3);return ne(O,{color:a?Z:void 0,children:[a?"\u276F ":" ",`${m} ${d.label} (${d.count})`.padEnd(Math.min(44,Math.max(20,Me-24))),L(O,{color:"gray",children:` ${d.token}`})]},d.token)}),L(O,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):dt?ne(ce,{flexDirection:"column",paddingX:1,children:[L(O,{color:Z,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),dt.rows.map((d,c)=>{let a=c===dt.cursor,m=d.indent?" ":" ",D=`${c+1}.`.padEnd(3);return ne(O,{color:a?Z:void 0,bold:d.kind==="category"&&!a,children:[a?"\u276F ":" ",`${m}${D} ${d.label}`.padEnd(Math.min(56,Me-24)),d.note?L(O,{color:"gray",children:d.note}):null]},`${d.kind}:${d.paths.join(",")}`)}),L(O,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):ut?ne(ce,{flexDirection:"column",paddingX:1,children:[L(O,{color:Z,bold:!0,children:ut.title}),(()=>{let{rows:c,cursor:a}=ut,m=Math.max(0,Math.min(a-Math.floor(12/2),c.length-12)),D=c.slice(m,m+12),G=`${c.length}.`.length+1,f=hd(c,Math.max(20,Me-4-G));return ne(Ro,{children:[m>0?L(O,{color:"gray",children:` \u2026 ${m} more above`}):null,D.map((y,k)=>{let w=m+k,x=w===a,S=f[w];return ne(O,{color:x?Z:void 0,bold:(y.kind==="all"||y.kind==="category")&&!x,children:[x?"\u276F ":" ",`${w+1}.`.padEnd(G),S.head,S.note?L(O,{color:"gray",children:S.note}):null]},`${y.action}:${y.kind}:${y.ids.join(",")}`)}),m+12<c.length?L(O,{color:"gray",children:` \u2026 ${c.length-m-12} more below`}):null]})})(),L(O,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter run \xB7 esc cancel"})]}):Oe?ne(ce,{flexDirection:"column",paddingX:1,children:[L(O,{color:Z,bold:!0,children:`Preview article${Oe.query?` \u2014 filter: ${Oe.query}`:" (type to filter)"}`}),Bo.length===0?L(O,{color:"gray",children:"no articles match"}):Bo.map((d,c)=>ne(O,{color:c===Oe.cursor?Z:void 0,children:[c===Oe.cursor?"\u276F ":" ",d]},d)),L(O,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):Le?ne(ce,{flexDirection:"column",paddingX:1,children:[L(O,{color:Z,bold:!0,children:`Resume session${Le.query?` \u2014 filter: ${Le.query}`:" (type to filter)"}`}),Ho.length===0?L(O,{color:"gray",children:"no sessions match"}):Ho.map((d,c)=>ne(O,{color:c===Le.cursor?Z:void 0,children:[c===Le.cursor?"\u276F ":" ",d.name.slice(0,28).padEnd(30),L(O,{color:c===Le.cursor?Z:"gray",children:d.firstPrompt.slice(0,Math.max(10,Me-40))})]},d.uuid)),L(O,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):$l?ne(ce,{flexDirection:"column",children:[Wt>0?L(O,{dimColor:!0,children:` \u22EF ${Wt} more above`}):null,Ts.map((d,c)=>{let a=Wt+c,m=d.name==="model"&&$s?`${d.desc} (currently ${$s})`:d.desc,D=Math.max(20,Me-4),G=d.usage.length>D?`${d.usage.slice(0,D-1)}\u2026`:d.usage,f=D-Math.max(G.length,22)-1,y=f<=1?"":m.length>f?`${m.slice(0,f-1)}\u2026`:m;return ne(O,{color:a===Wo?Z:void 0,children:[a===Wo?"\u276F ":" ",G.padEnd(22)," ",L(O,{color:a===Wo?Z:"gray",children:y})]},d.name)}),Wt+Ts.length<Qe.length?L(O,{dimColor:!0,children:` \u22EF ${Qe.length-Wt-Ts.length} more below`}):null,L(O,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!C&&!$&&ae.length>0?ne(ce,{flexDirection:"column",paddingX:1,children:[pl?L(O,{color:Z,children:pl}):null,ae.map((d,c)=>{let a=Yt(d),m=a.slice(0,Math.max(20,Me-5)),D=Me-m.length-7,G=D>=12?(Tp(d)??$c(a)).slice(0,D):"";return ne(O,{children:[L(O,{color:Z,children:c+1})," ",m,G?L(O,{dimColor:!0,children:` \u2014 ${G}`}):null]},a)}),L(O,{dimColor:!0,children:`press 1-${ae.length} to fill \xB7 esc cancel`})]}):L(ce,{paddingX:1,children:ne(O,{color:"gray",children:[bl.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${$s??"model n/a"}${t.kind==="api"?gl>0?` \xB7 ${Ae(gl)}`:"":ml>0?` \xB7 ${bt(ml)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}X();import{jsx as Jb}from"react/jsx-runtime";async function sh(e=process.cwd(),t="auto",n,o="0.0.0"){let r=Qb(t);r.kind==="none"&&(console.error(""),console.error(A("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${W("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${W("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=Xb(Jb(rh,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
|
|
445
|
+
`),process.exit(0)}X();import{writeCrashLog as ih,isBenignTransportError as Zb}from"document360-engine";var ah=!1;function sl(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function lh(e){if(ah)return;ah=!0;let t=(n,o)=>{if(Zb(o)){ih({kind:n,level:"transport",message:sl(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=ih({kind:n,level:"fatal",message:sl(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
|
|
446
|
+
`+A(`\u2717 d360-writer crashed: ${sl(o)}`)+`
|
|
448
447
|
`),r&&process.stderr.write(g(` Crash details: ${r}`)+`
|
|
449
448
|
`+g(" Run: d360-writer logs")+`
|
|
450
|
-
`),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var
|
|
449
|
+
`),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var o$=t$(import.meta.url),fs=o$("../package.json");lh("d360-writer");var Ke=new e$;function il(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}Ke.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=>{il(e),await tr({profile:e.profile,manual:e.manual})});Ke.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{il(e),await Bl({profile:e.profile})});Ke.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{il(e),await Wl({profile:e.profile})});var al=Ke.command("profile").description("Manage connection profiles for the current repo");al.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>nr(process.cwd()));al.command("use <name>").description("Set the default profile for this repo").action(e=>or(process.cwd(),e));al.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>rr(process.cwd(),e));var ch=Ke.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");ch.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>mn(process.cwd(),e.profile));ch.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await Il(process.cwd(),e,t.profile)});var dh=Ke.command("project").description("Choose the Document360 project for this repo (active profile's identity)");dh.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>Jo(process.cwd(),e.profile));dh.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await Ll(process.cwd(),e,t.profile)});Ke.command("init").description("Scaffold .d360-writer/config.json for this repo (interactive)").action(async()=>{let{initCommand:e}=await Promise.resolve().then(()=>(pr(),wc));await e()});Ke.command("logs").description("Show the API + crash log files (send these to support when reporting a problem)").action(()=>Gl());Ke.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(()=>(Fr(),cu)),n=await t(process.cwd(),fs.version);for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});Ke.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(fs.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(n$.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 Yl(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 fp(e.cwd,e.auth,e.profile,fs.version):await sh(e.cwd,e.auth,e.profile,fs.version)});Ke.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
|