document360-writer 0.5.157 → 0.5.159
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +132 -130
- package/package.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var Lp=Object.defineProperty;var In=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var cl=(e,t)=>{for(var n in t)Lp(e,n,{get:t[n],enumerable:!0})};import dt from"picocolors";var X,Mp,Up,Wp,ul,On,m,S,B,_,W,ue,Se,z=In(()=>{"use strict";X="#7f56d9",[Mp,Up,Wp]=[127,86,217],ul=e=>dt.isColorSupported?`\x1B[38;2;${Mp};${Up};${Wp}m${e}\x1B[39m`:e,On=e=>dt.bold(ul(e)),m=e=>dt.dim(e),S=e=>dt.red(e),B=e=>dt.yellow(e),_=e=>dt.green(e),W=ul,ue=e=>dt.gray(e),Se=e=>dt.bold(e)});import{existsSync as sn,writeFileSync as ht,readFileSync as Rh,readdirSync as Sh}from"node:fs";import{join as Tl}from"node:path";import{devHintsGuidePath as Bo,hintsDir as Dl,hooksDir as Al,architectureDir as Ol,messagesDir as $s,creatorNotesPath as El,devhintsStatePath as _l,directivesPath as jl,DIRECTIVES_HEADER as Ph,roadmapPath as Nl,ROADMAP_HEADER as Th,ensureDir as Mn,writeMessage as Dh,listOpenForDev as Ah}from"document360-engine";function Ll(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
|
|
3
3
|
|
|
4
4
|
<!-- devhints script v${de} \xB7 maintained by document360-writer (/devhints). -->
|
|
5
5
|
|
|
@@ -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 jh(){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 xs(e){try{let t=
|
|
238
|
-
`)}function
|
|
239
|
-
`)}),n.notifiedBuilder=!0))}catch{}return n}function Ho(e){if(!
|
|
240
|
-
`)}function Vo(){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):",
|
|
235
|
+
`}function ln(e){Mn(Dl(e)),Mn(Ol(e)),Mn($s(e));for(let n of[Dl(e),$s(e)]){let o=Tl(n,".gitkeep");sn(o)||ht(o,`# Keeps this document360-writer inbox tracked in git even when empty.
|
|
236
|
+
`)}sn(El(e))||ht(El(e),jh()),sn(jl(e))||ht(jl(e),Ph),sn(Nl(e))||ht(Nl(e),Th),ht(Bo(e),Ll()),Mn(Al(e)),ht(Tl(Al(e),"open-questions.mjs"),Eh);let t=Me(e);return Ul(e,new Date().toISOString()),t}async function Ml(e,t){for(let n of cn(ln(t.cwd)))console.log(n);return{kind:"continue"}}function Ot(){return[`This is document360-writer's dev hand-off setup (v${de}).`,'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": ${de},`,' "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 xs(e){try{let t=Rh(_l(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function Ul(e,t){let o={...xs(e)??{},emittedVersion:de,emittedAt:t};ht(_l(e),`${JSON.stringify(o,null,2)}
|
|
238
|
+
`)}function rt(e){try{return Sh(Ol(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function Me(e){let n=xs(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<de?"stale":"current",completedVersion:n}}function qo(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:de};try{if(!sn(Bo(e)))return n;let o=xs(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;de>r&&(Mn($s(e)),ht(Bo(e),Ll()),Ul(e,t),n.guideRefreshed=!0),de>s&&(Ah(e).some(u=>u.kind==="request"&&u.subject.startsWith(Il))||(Dh(e,{id:`onb${de}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${Il}${de})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${de}${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:","",Ot()].join(`
|
|
239
|
+
`)}),n.notifiedBuilder=!0))}catch{}return n}function Ho(e){if(!sn(Bo(e)))return[];let t=Me(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${de}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,an,Ot(),an,"(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 Vo(){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):",an,vs(),an]}function cn(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${de}.`," 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):",an,Ot(),an,"","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 an,de,Eh,Il,ft=In(()=>{"use strict";an="-".repeat(64),de=10,Eh=`#!/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,62 +275,62 @@ try {
|
|
|
275
275
|
} catch {
|
|
276
276
|
/* a session-start nudge must never break the session */
|
|
277
277
|
}
|
|
278
|
-
`;
|
|
279
|
-
`),"utf8")}async function Rs(){let e=process.cwd(),t=Bc(e);if(sn(t)&&!await Th({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(g("init cancelled.")),{kind:"continue"};let n=Yc(e)??Wc(e),o=await _n({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await _n({message:"Capture directory (where document360-capture .spec.ts files live):",default:Hc}),s=await _n({message:"Screenshot output directory:",default:Vc}),a=await _n({message:"Default connection profile name:",default:"berlin"}),u=await _n({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),h={projectId:o,docsDir:qc,captureDir:r,outputDir:s,profiles:{[a]:{connection:{environment:u},production:!1}},defaultProfile:a,authoritativeSourceFiles:zc(e)},k=jh(e);k?.terminologyGlossary&&(h.terminologyGlossary=k.terminologyGlossary),Fc(h,e),Gc(e);let b=on(e);console.log(""),console.log(O(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${W(`d360-writer login --profile ${a}`)} ${g("(sign in; project & workspace auto-selected)")}`),console.log("");for(let x of rn(b))console.log(x);return console.log(""),console.log(`${g("Then ask:")} ${W('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function Yc(e){let t=Go(e,"package.json");if(!sn(t))return null;try{return JSON.parse(Dh(t,"utf8")).name??null}catch{return null}}function zc(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])sn(Go(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Go(e,n);sn(o)&&!Ih(o)&&t.push(n)}return t}function Ih(e){try{return Ah(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var Yo=An(()=>{"use strict";Y();pt()});import{createRequire as Hm}from"node:module";import{existsSync as Vm,readFileSync as Gm}from"node:fs";import{dirname as $u,join as xu}from"node:path";function yr(){let e;try{e=Ym.resolve("document360-capture/helpers")}catch{return null}let t=$u(e);for(let n=0;n<5&&!Vm(xu(t,"package.json"));n++)t=$u(t);try{let n=JSON.parse(Gm(xu(t,"package.json"),"utf8"));return n.name==="document360-capture"&&n.version?n.version:null}catch{return null}}var Ym,Ni=An(()=>{"use strict";Ym=Hm(import.meta.url)});var Pu={};lc(Pu,{doctorCommand:()=>Yn,renderDoctorChecks:()=>Su,runDoctorChecks:()=>Ru});import{existsSync as zm}from"node:fs";import{d360GetAll as Km,getAccessToken as Xm,isExpired as Ii,loadProfileMap as Qm,loadTokens as Jm,packageSkillsDir as vu,ENGINE_VERSION as Zm,projectConfigPath as eg,readProjectConfig as tg,DEFAULT_DOCS_DIR as ng,fetchManifestSummary as og,resolveActiveProfile as rg,classifyClaudeAuth as sg,CLAUDE_CODE_SETUP_HINT as Cu,resolveModelSetting as ig,probeModel as ag,detectAppType as cg,playbookSkillName as lg,D360AuthError as ug}from"document360-engine";async function Ru(e,t){let n=[],o=yr();n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${Zm}${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=sg();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. ${Cu}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:Cu});let a=ig(e);if(n.push({level:"ok",label:`Model: ${a.model} (${a.source==="auto"?"auto \u2014 right-sized for docs; /model to change":a.source})`}),s.state==="ready"){let T=await ag(e,a.model??void 0);T.ok?n.push({level:"ok",label:`Model reachable \u2014 replied in ${(T.latencyMs/1e3).toFixed(1)}s`}):T.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 ${T.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 u=tg(e);if(!u)return n.push({level:"fail",label:`No ${eg(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${u.projectId}`});let h=(u.docsDir??ng).replace(/\/+$/,"");n.push(u.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 ${h}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let k=u.authoritativeSourceFiles??[];n.push(k.length>0?{level:"ok",label:`Sources: docs grounded in ${k.length} path(s) (${k.slice(0,3).join(", ")}${k.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=u.appType??cg(e);if(b){let T=u.appType?"from config":"auto-detected",E=b==="web"||b==="cli";n.push({level:"ok",label:`Genre: ${b} (${T})${E?` \u2192 ${lg(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 x;try{x=rg(e),n.push({level:"ok",label:`Profile: ${x.name} (${x.connection.name})${x.production?" \u26A0 PRODUCTION":""}`})}catch(T){return n.push({level:"fail",label:`Profile config: ${T.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let $=Jm(x.name);$?Ii($)&&!$.refreshToken?n.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):Ii($)?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($.expiresAt).toLocaleString()})`}):n.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${x.name})`}),n.push(x.project.workspaceId?{level:"ok",label:`Workspace: ${x.project.workspaceName??x.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let j=Qm(e,x.name);j?j.projectId&&x.project.projectId&&j.projectId!==x.project.projectId?n.push({level:"fail",label:`Category map projectId (${j.projectId}) \u2260 profile projectId (${x.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(j.articles).length} articles, ${Object.keys(j.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${x.name}" (created on first /publish)`}),n.push(zm(vu())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${vu()}`,fix:"Reinstall document360-writer (broken install)"});let v=Le(e);if(v.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${de})`}):v.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${v.completedVersion}, current is v${de}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),$&&(!Ii($)||$.refreshToken)){let T={profile:x.name,connection:x.connection};try{await Xm(T);let U=await Km(T,"/v3/projects");n.push({level:"ok",label:`API reachable (${x.connection.apiUrl}) \u2014 ${U.length} project(s) visible`})}catch(U){n.push({level:"fail",label:`API call failed: ${U.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let E=j?.projectId??x.project.projectId;if(E&&x.project.workspaceId)try{let U=await og(T,E,x.project.workspaceId);if(U){let L=(U.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Workspace sync manifest: available on ${x.connection.name} (${U.languages?.length??0} language${(U.languages?.length??0)===1?"":"s"}) \xB7 hash ${L||"(none)"}`})}else n.push({level:"warn",label:`Workspace sync manifest: not live on ${x.connection.name} yet`,fix:"No action needed \u2014 sync uses the per-article path until the manifest ships on this environment"})}catch(U){U instanceof ug||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(U.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${x.project.projectName??E})`,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 (${U.message.slice(0,80)})`})}}return n}function Su(e){let t=[""];for(let r of e){let s=r.level==="ok"?O("\u2713"):r.level==="warn"?B("\u26A0"):S("\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?O(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):S(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function Yn(e,t){console.log(g("Running checks\u2026"));for(let n of Su(await Ru(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var wr=An(()=>{"use strict";pt();Y();Ni()});import{Command as Ik}from"commander";import{createRequire as _k}from"node:module";import{AUTH_MODES as Ok}from"document360-engine";import{input as Kp}from"@inquirer/prompts";import{loginPkce as Xp,refreshTokens as Qp,toStoredTokens as gc,clearTokens as Jp,decodeJwtClaims as mc,isExpired as Zp,loadTokens as eh,saveTokens as yc,resolveActiveProfile as Oo,setProfileProject as th,readProjectConfig as nh}from"document360-engine";Y();import{select as Op}from"@inquirer/prompts";import{resolveActiveProfile as Lp,setProfileProject as Mp,resolveProjectId as Up,listWorkspaces as Wp}from"document360-engine";async function jn(e,t){let n=Lp(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Up(o);return{workspaces:await Wp(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var dc=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function gs(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 No(e,t,n,o,r){Mp(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function pc(e,t,n){let o;try{o=await jn(e,n)}catch(s){return console.log(S(`Could not list workspaces: ${s.message}`)),1}let r=gs(o.workspaces,t);return r?(No(e,o.profile,o.projectId,r.id,r.name),console.log(O(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(S(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function en(e,t){let n;try{n=await jn(e,t)}catch(k){console.log(S(`Could not list workspaces: ${k.message}`));return}let{workspaces:o,projectId:r,profile:s,current:a}=n;if(o.length===0){console.log(g("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let k of o)console.log(` ${k.id===a?W("\u25CF"):" "} ${dc(k)} ${g(k.id)}`);console.log(g("Run: d360-writer workspace use <name>"));return}let u=await Op({message:"Select the Document360 workspace for this repo:",choices:o.map(k=>({name:`${dc(k)}${k.id===a?" (current)":""}`,value:k.id}))}),h=o.find(k=>k.id===u);No(e,s,r,u,h?.name),console.log(O(`\u2713 Workspace set to "${h?.name??u}" for profile "${s}".`))}Y();import{select as Fp}from"@inquirer/prompts";import{resolveActiveProfile as Bp,setProfileProject as qp,listProjects as Hp}from"document360-engine";async function ut(e,t){let n=Bp(e,t),o={profile:n.name,connection:n.connection};return{projects:await Hp(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var hc=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function ys(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 Io(e,t,n,o){qp(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function fc(e,t,n){let o;try{o=await ut(e,n)}catch(s){return console.log(S(`Could not list projects: ${s.message}`)),1}let r=ys(o.projects,t);return r?(Io(e,o.profile,r.id,r.name),console.log(O(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log(S(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function _o(e,t){let n;try{n=await ut(e,t)}catch(h){console.log(S(`Could not list projects: ${h.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 h of o)console.log(` ${h.id===s?W("\u25CF"):" "} ${hc(h)} ${g(h.id)}`);console.log(g("Run: d360-writer project use <name>"));return}let a=await Fp({message:"Select the Document360 project for this repo:",choices:o.map(h=>({name:`${hc(h)}${h.id===s?" (current)":""}`,value:h.id}))}),u=o.find(h=>h.id===a);Io(e,r,a,u?.name),console.log(O(`\u2713 Project set to "${u?.name??a}" for profile "${r}". Next: pick a workspace.`))}Y();import Vp from"picocolors";function Gp(e=process.env){return e.FORCE_HYPERLINK==="0"||!Vp.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 Yp(e,t=e,n){return Gp(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var zp=/https?:\/\/[^\s\x1b]+/g;function Nn(e,t){return e.replace(zp,n=>Yp(n,n,t))}function wc(e){return{...mc(e.idToken)??{},...mc(e.accessToken)??{}}}function Lo(e){let t=wc(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 Mo(e){let t=Oo(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 Xp(n,{manual:e.manual,promptForRedirect:s=>Kp({message:s})},s=>console.log(Nn(s))),r=gc(t.name,o);if(yc(r),await ws(r,t.name,s=>console.log(g(s))),console.log(""),console.log(O(`\u2713 Logged in to "${t.name}" as ${Lo(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{nh(process.cwd())?.profiles?.[t.name]&&(console.log(""),await en(process.cwd(),t.name))}catch{}}async function ws(e,t,n){let r=wc(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Oo(process.cwd(),t).project.projectId)return;let a;try{let{projects:u}=await ut(process.cwd(),t);a=u.find(h=>h.id===r)?.name}catch{}th(process.cwd(),t,{projectId:r,projectName:a}),n(` Project "${a??r}" written to profile "${t}".`)}catch{}}async function kc(e){let t=Oo(process.cwd(),e.profile),n=t.connection,o=eh(t.name);if(!o){console.log(S(`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":""}: ${Lo(o)}`),Zp(o))if(o.refreshToken)try{let r=gc(t.name,await Qp(n,o.refreshToken));yc(r),console.log(O(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(B(`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(B("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 bc(e){let t=Oo(process.cwd(),e.profile);Jp(t.name)?console.log(O(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(g(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}Y();import{readProjectConfig as $c,writeProjectConfig as oh,resolveActiveProfile as rh,loadTokens as sh,isExpired as ih}from"document360-engine";function Uo(e){let t=$c(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(S("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?B(" \u26A0 PRODUCTION"):"",a=o.connection.environment??"(inline)",u=sh(n),h=u?ih(u)&&!u.refreshToken?B("expired"):g("logged in"):g("not logged in");console.log(`${r}${W(n)} \u2192 ${a}${s} [${h}]`)}console.log(""),console.log(g("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function Wo(e,t){let n=$c(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(S(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,oh(n,e);let o=n.profiles[t].production?B(" \u26A0 PRODUCTION"):"";console.log(O(`\u2713 Default profile is now "${t}"${o}`))}function Fo(e,t){try{let n=rh(e,t);console.log(""),console.log(`Profile ${W(n.name)}${n.production?B(" \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(S(n.message)),process.exitCode=1}}Y();import{existsSync as ah,readdirSync as ch,statSync as xc}from"node:fs";import{join as vc}from"node:path";import{apiLogDir as lh}from"document360-engine";function Cc(){let e=lh();if(console.log(""),console.log(`Document360 API logs: ${W(e)}`),!ah(e)){console.log(g(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=ch(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=(xc(vc(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=(xc(vc(e,r)).size/1024).toFixed(1);console.log(` ${S(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("")}Y();import{createSession as uh,resolveAuth as dh,findByName as ph,slugify as hh,touchSession as fh,upsertSession as mh,resolveActiveProfile as gh}from"document360-engine";async function Rc(e,t,n,o,r,s){let a=dh(n);a.kind==="none"&&(console.error(""),console.error(S("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)),a.kind==="subscription"&&console.error(g("Using your Claude subscription (no API key set)."));let u=null;try{u=gh(e,r)}catch($){console.error(S(`Document360 profile error: ${$.message}`)),process.exit(2)}u.production&&(console.error(B(`\u26A0 Profile "${u.name}" is PRODUCTION.`)),s||(console.error(S("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(g(" --yes given \u2014 proceeding against production.")));let h;if(o){let $=ph(e,o);$||(console.error(S(`No saved session matches "${o}" in this repo.`)),console.error(g("List sessions inside the REPL with /resume.")),process.exit(2)),h=$.uuid,console.error(g(`Resuming "${$.name}"`))}let k=uh({cwd:e,resume:h,profileName:r,allowProdWrites:s===!0}),b=h??null,x=1;for await(let $ of k.send(t))switch($.type){case"session":if(!b){b=$.sessionId;let j=new Date().toISOString();mh({uuid:b,name:hh(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:j,updatedAt:j})}break;case"text":process.stdout.write($.delta);break;case"tool":console.error(ue(` \u2699 ${$.name}`));break;case"result":x=$.ok?0:1,console.error(g(`(${$.inputTokens}\u2192${$.outputTokens} tokens`+($.costUsd>0?`, $${$.costUsd<.01?$.costUsd.toFixed(4):$.costUsd.toFixed(2)}`:"")+")")),$.ok||console.error(S("agent finished with an error result"));break;case"error":console.error(""),console.error(S(`agent error: ${$.message}`)),process.exit(1)}b&&fh(b),process.stdout.write(`
|
|
280
|
-
`),process.exit(x)}import{createInterface as By}from"node:readline/promises";import{createSession as ka,resolveAuth as qy,getSession as Hy,setTitle as Vy,slugify as Gy,touchSession as vd,upsertSession as Yy,generateTitle as zy,resolveActiveProfile as Cd,resolveModelSetting as Ky,readProjectConfig as Xy,resolveAndPersistAppType as Qy,decodeJwtClaims as xd,isExpired as Jy,loadTokens as Zy,isDirectiveMention as ew,stripDirectiveMention as tw,appendDirective as nw,reconcileUpgradeActions as ow,stampArticles as rw,listArticleFiles as sw,CONTENT_CAP_VERSION as iw}from"document360-engine";import{ENGINE_VERSION as wh}from"document360-engine";var Oe=[{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:"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 whose last run failed \u2014 the follow-up after re-authoring their specs."},{t:"cmd",name:"/screenshot capture --all --retry-blocked",s:"Include shots that skipped on missing data last run (a bulk run leaves them out by default)."},{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 (\u25CF captured \xB7 \u25D0 ready \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:"When a shot does not produce an 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:"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."}]}];function yh(e){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":return` ${e.name.padEnd(20)} ${e.s}`;case"gap":return""}}function Sc(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 Oe){n.push(`\u2500\u2500 ${o.label} \u2500\u2500`,"");for(let r of o.rows)n.push(yh(r));n.push("")}return n.push("Tip: anything not starting with / goes to the agent."),n}async function ks(e=[],t){console.log("");let n=t?.version?{version:t.version,engineVersion:wh}:void 0;for(let o of Sc(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"}}Y();import{getSession as kh}from"document360-engine";async function Pc(e,t){let n=t.currentUuid(),o=n?kh(n):void 0;return console.log(o?g(`
|
|
278
|
+
`;Il="Re-run dev\u2194docs onboarding (protocol v"});var Kl={};cl(Kl,{initCommand:()=>Rs,scaffoldInit:()=>Cs});import{input as Un,confirm as Nh}from"@inquirer/prompts";import{basename as Wl,join as Go}from"node:path";import{existsSync as un,readFileSync as Ih,readdirSync as Oh,writeFileSync as _h}from"node:fs";import{writeProjectConfig as Fl,readProjectConfig as Lh,projectConfigPath as Bl,writerDir as Mh,DEFAULT_DOCS_DIR as ql,DEFAULT_CAPTURE_DIR as Hl,DEFAULT_OUTPUT_DIR as Vl}from"document360-engine";function Cs(e,t="berlin"){let n=Bl(e);if(un(n))return{created:!1,path:n,profileName:""};let o={projectId:Yl(e)??Wl(e),docsDir:ql,captureDir:Hl,outputDir:Vl,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:zl(e)};return Fl(o,e),Gl(e),{created:!0,path:n,profileName:t}}function Gl(e){let t=Go(Mh(e),".gitignore");un(t)||_h(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
|
|
279
|
+
`),"utf8")}async function Rs(){let e=process.cwd(),t=Bl(e);if(un(t)&&!await Nh({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(m("init cancelled.")),{kind:"continue"};let n=Yl(e)??Wl(e),o=await Un({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await Un({message:"Capture directory (where document360-capture .spec.ts files live):",default:Hl}),s=await Un({message:"Screenshot output directory:",default:Vl}),a=await Un({message:"Default connection profile name:",default:"berlin"}),u=await Un({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),p={projectId:o,docsDir:ql,captureDir:r,outputDir:s,profiles:{[a]:{connection:{environment:u},production:!1}},defaultProfile:a,authoritativeSourceFiles:zl(e)},b=Lh(e);b?.terminologyGlossary&&(p.terminologyGlossary=b.terminologyGlossary),Fl(p,e),Gl(e);let k=ln(e);console.log(""),console.log(_(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${W(`d360-writer login --profile ${a}`)} ${m("(sign in; project & workspace auto-selected)")}`),console.log("");for(let $ of cn(k))console.log($);return console.log(""),console.log(`${m("Then ask:")} ${W('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function Yl(e){let t=Go(e,"package.json");if(!un(t))return null;try{return JSON.parse(Ih(t,"utf8")).name??null}catch{return null}}function zl(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])un(Go(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Go(e,n);un(o)&&!Uh(o)&&t.push(n)}return t}function Uh(e){try{return Oh(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var Yo=In(()=>{"use strict";z();ft()});import{createRequire as Xm}from"node:module";import{existsSync as Qm,readFileSync as Jm}from"node:fs";import{dirname as xu,join as vu}from"node:path";function yr(){let e;try{e=Zm.resolve("document360-capture/helpers")}catch{return null}let t=xu(e);for(let n=0;n<5&&!Qm(vu(t,"package.json"));n++)t=xu(t);try{let n=JSON.parse(Jm(vu(t,"package.json"),"utf8"));return n.name==="document360-capture"&&n.version?n.version:null}catch{return null}}var Zm,ji=In(()=>{"use strict";Zm=Xm(import.meta.url)});var Tu={};cl(Tu,{doctorCommand:()=>Xn,renderDoctorChecks:()=>Pu,runDoctorChecks:()=>Su});import{existsSync as eg}from"node:fs";import{d360GetAll as tg,getAccessToken as ng,isExpired as Ni,loadProfileMap as og,loadTokens as rg,packageSkillsDir as Cu,ENGINE_VERSION as sg,projectConfigPath as ig,readProjectConfig as ag,DEFAULT_DOCS_DIR as lg,fetchManifestSummary as cg,resolveActiveProfile as ug,classifyClaudeAuth as dg,CLAUDE_CODE_SETUP_HINT as Ru,resolveModelSetting as pg,probeModel as hg,detectAppType as fg,playbookSkillName as mg,D360AuthError as gg}from"document360-engine";async function Su(e,t){let n=[],o=yr();n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${sg}${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=dg();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. ${Ru}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:Ru});let a=pg(e);if(n.push({level:"ok",label:`Model: ${a.model} (${a.source==="auto"?"auto \u2014 right-sized for docs; /model to change":a.source})`}),s.state==="ready"){let D=await hg(e,a.model??void 0);D.ok?n.push({level:"ok",label:`Model reachable \u2014 replied in ${(D.latencyMs/1e3).toFixed(1)}s`}):D.timedOut?n.push({level:"fail",label:"Model unreachable \u2014 no response in 30s (a docs turn will hang, then end with 0 tokens / no output)",fix:`Usually a corporate proxy/firewall or org policy blocking the Claude model API. Check this machine's network access to the Claude endpoint; confirm with: claude -p "say hi"`}):n.push({level:"fail",label:`Model call failed \u2014 ${D.error??"no output"} (a docs turn will end with 0 tokens / no output)`,fix:'Check sign-in, the selected model (/model), and network access to the Claude endpoint; confirm with: claude -p "say hi"'})}let u=ag(e);if(!u)return n.push({level:"fail",label:`No ${ig(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${u.projectId}`});let p=(u.docsDir??lg).replace(/\/+$/,"");n.push(u.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 b=u.authoritativeSourceFiles??[];n.push(b.length>0?{level:"ok",label:`Sources: docs grounded in ${b.length} path(s) (${b.slice(0,3).join(", ")}${b.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 k=u.appType??fg(e);if(k){let D=u.appType?"from config":"auto-detected",E=k==="web"||k==="cli";n.push({level:"ok",label:`Genre: ${k} (${D})${E?` \u2192 ${mg(k)} 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{$=ug(e),n.push({level:"ok",label:`Profile: ${$.name} (${$.connection.name})${$.production?" \u26A0 PRODUCTION":""}`})}catch(D){return n.push({level:"fail",label:`Profile config: ${D.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let x=rg($.name);x?Ni(x)&&!x.refreshToken?n.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):Ni(x)?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(x.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 j=og(e,$.name);j?j.projectId&&$.project.projectId&&j.projectId!==$.project.projectId?n.push({level:"fail",label:`Category map projectId (${j.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(j.articles).length} articles, ${Object.keys(j.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${$.name}" (created on first /publish)`}),n.push(eg(Cu())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${Cu()}`,fix:"Reinstall document360-writer (broken install)"});let v=Me(e);if(v.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${de})`}):v.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${v.completedVersion}, current is v${de}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),x&&(!Ni(x)||x.refreshToken)){let D={profile:$.name,connection:$.connection};try{await ng(D);let U=await tg(D,"/v3/projects");n.push({level:"ok",label:`API reachable (${$.connection.apiUrl}) \u2014 ${U.length} project(s) visible`})}catch(U){n.push({level:"fail",label:`API call failed: ${U.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let E=j?.projectId??$.project.projectId;if(E&&$.project.workspaceId)try{let U=await cg(D,E,$.project.workspaceId);if(U){let L=(U.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Workspace sync manifest: available on ${$.connection.name} (${U.languages?.length??0} language${(U.languages?.length??0)===1?"":"s"}) \xB7 hash ${L||"(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(U){U instanceof gg||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(U.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${$.project.projectName??E})`,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 (${U.message.slice(0,80)})`})}}return n}function Pu(e){let t=[""];for(let r of e){let s=r.level==="ok"?_("\u2713"):r.level==="warn"?B("\u26A0"):S("\u2717");t.push(` ${s} ${r.label}${r.detail?m(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${m("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?_(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):S(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function Xn(e,t){console.log(m("Running checks\u2026"));for(let n of Pu(await Su(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var wr=In(()=>{"use strict";ft();z();ji()});import{Command as Wk}from"commander";import{createRequire as Fk}from"node:module";import{AUTH_MODES as Bk}from"document360-engine";import{input as eh}from"@inquirer/prompts";import{loginPkce as th,refreshTokens as nh,toStoredTokens as gl,clearTokens as oh,decodeJwtClaims as ml,isExpired as rh,loadTokens as sh,saveTokens as yl,resolveActiveProfile as _o,setProfileProject as ih,readProjectConfig as ah}from"document360-engine";z();import{select as Fp}from"@inquirer/prompts";import{resolveActiveProfile as Bp,setProfileProject as qp,resolveProjectId as Hp,listWorkspaces as Vp}from"document360-engine";async function _n(e,t){let n=Bp(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Hp(o);return{workspaces:await Vp(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var dl=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function gs(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 No(e,t,n,o,r){qp(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function pl(e,t,n){let o;try{o=await _n(e,n)}catch(s){return console.log(S(`Could not list workspaces: ${s.message}`)),1}let r=gs(o.workspaces,t);return r?(No(e,o.profile,o.projectId,r.id,r.name),console.log(_(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(S(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function rn(e,t){let n;try{n=await _n(e,t)}catch(b){console.log(S(`Could not list workspaces: ${b.message}`));return}let{workspaces:o,projectId:r,profile:s,current:a}=n;if(o.length===0){console.log(m("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let b of o)console.log(` ${b.id===a?W("\u25CF"):" "} ${dl(b)} ${m(b.id)}`);console.log(m("Run: d360-writer workspace use <name>"));return}let u=await Fp({message:"Select the Document360 workspace for this repo:",choices:o.map(b=>({name:`${dl(b)}${b.id===a?" (current)":""}`,value:b.id}))}),p=o.find(b=>b.id===u);No(e,s,r,u,p?.name),console.log(_(`\u2713 Workspace set to "${p?.name??u}" for profile "${s}".`))}z();import{select as Gp}from"@inquirer/prompts";import{resolveActiveProfile as Yp,setProfileProject as zp,listProjects as Kp}from"document360-engine";async function pt(e,t){let n=Yp(e,t),o={profile:n.name,connection:n.connection};return{projects:await Kp(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var hl=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function ys(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 Io(e,t,n,o){zp(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function fl(e,t,n){let o;try{o=await pt(e,n)}catch(s){return console.log(S(`Could not list projects: ${s.message}`)),1}let r=ys(o.projects,t);return r?(Io(e,o.profile,r.id,r.name),console.log(_(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log(S(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function Oo(e,t){let n;try{n=await pt(e,t)}catch(p){console.log(S(`Could not list projects: ${p.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(m("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"):" "} ${hl(p)} ${m(p.id)}`);console.log(m("Run: d360-writer project use <name>"));return}let a=await Gp({message:"Select the Document360 project for this repo:",choices:o.map(p=>({name:`${hl(p)}${p.id===s?" (current)":""}`,value:p.id}))}),u=o.find(p=>p.id===a);Io(e,r,a,u?.name),console.log(_(`\u2713 Project set to "${u?.name??a}" for profile "${r}". Next: pick a workspace.`))}z();import Xp from"picocolors";function Qp(e=process.env){return e.FORCE_HYPERLINK==="0"||!Xp.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 Jp(e,t=e,n){return Qp(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Zp=/https?:\/\/[^\s\x1b]+/g;function Ln(e,t){return e.replace(Zp,n=>Jp(n,n,t))}function wl(e){return{...ml(e.idToken)??{},...ml(e.accessToken)??{}}}function Lo(e){let t=wl(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 Mo(e){let t=_o(process.cwd(),e.profile),n=t.connection;console.log(m(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=await th(n,{manual:e.manual,promptForRedirect:s=>eh({message:s})},s=>console.log(Ln(s))),r=gl(t.name,o);if(yl(r),await ws(r,t.name,s=>console.log(m(s))),console.log(""),console.log(_(`\u2713 Logged in to "${t.name}" as ${Lo(r)}`)),console.log(m(` access token expires: ${r.expiresAt}`)),console.log(m(` refresh token: ${r.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{ah(process.cwd())?.profiles?.[t.name]&&(console.log(""),await rn(process.cwd(),t.name))}catch{}}async function ws(e,t,n){let r=wl(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(_o(process.cwd(),t).project.projectId)return;let a;try{let{projects:u}=await pt(process.cwd(),t);a=u.find(p=>p.id===r)?.name}catch{}ih(process.cwd(),t,{projectId:r,projectName:a}),n(` Project "${a??r}" written to profile "${t}".`)}catch{}}async function kl(e){let t=_o(process.cwd(),e.profile),n=t.connection,o=sh(t.name);if(!o){console.log(S(`Not logged in to Document360 (profile "${t.name}").`)),console.log(m(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${W(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Lo(o)}`),rh(o))if(o.refreshToken)try{let r=gl(t.name,await nh(n,o.refreshToken));yl(r),console.log(_(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(B(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(m(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(B("Session expired (no refresh token).")),console.log(m(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(m(` expires: ${o.expiresAt}`))}async function bl(e){let t=_o(process.cwd(),e.profile);oh(t.name)?console.log(_(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(m(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}z();import{readProjectConfig as $l,writeProjectConfig as lh,resolveActiveProfile as ch,loadTokens as uh,isExpired as dh}from"document360-engine";function Uo(e){let t=$l(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(S("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?B(" \u26A0 PRODUCTION"):"",a=o.connection.environment??"(inline)",u=uh(n),p=u?dh(u)&&!u.refreshToken?B("expired"):m("logged in"):m("not logged in");console.log(`${r}${W(n)} \u2192 ${a}${s} [${p}]`)}console.log(""),console.log(m("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function Wo(e,t){let n=$l(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(S(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,lh(n,e);let o=n.profiles[t].production?B(" \u26A0 PRODUCTION"):"";console.log(_(`\u2713 Default profile is now "${t}"${o}`))}function Fo(e,t){try{let n=ch(e,t);console.log(""),console.log(`Profile ${W(n.name)}${n.production?B(" \u26A0 PRODUCTION"):""}`),console.log(m(` api: ${n.connection.apiUrl}`)),console.log(m(` identity: ${n.connection.authorizationUrl}`)),console.log(m(` clientId: ${n.connection.clientId}`)),console.log(m(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(m(` project: ${n.project.projectId??"(set at login)"}`)),console.log(m(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(S(n.message)),process.exitCode=1}}z();import{existsSync as ph,readdirSync as hh,statSync as xl}from"node:fs";import{join as vl}from"node:path";import{apiLogDir as fh}from"document360-engine";function Cl(){let e=fh();if(console.log(""),console.log(`Document360 API logs: ${W(e)}`),!ph(e)){console.log(m(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=hh(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(m(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let s=(xl(vl(e,r)).size/1024).toFixed(1);console.log(` ${r} ${m(`${s} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${m("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let s=(xl(vl(e,r)).size/1024).toFixed(1);console.log(` ${S(r)} ${m(`${s} KB`)}`)}}console.log(""),console.log(m("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(m("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}z();import{createSession as mh,resolveAuth as gh,findByName as yh,slugify as wh,touchSession as kh,upsertSession as bh,resolveActiveProfile as $h}from"document360-engine";async function Rl(e,t,n,o,r,s){let a=gh(n);a.kind==="none"&&(console.error(""),console.error(S("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)),a.kind==="subscription"&&console.error(m("Using your Claude subscription (no API key set)."));let u=null;try{u=$h(e,r)}catch(x){console.error(S(`Document360 profile error: ${x.message}`)),process.exit(2)}u.production&&(console.error(B(`\u26A0 Profile "${u.name}" is PRODUCTION.`)),s||(console.error(S("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(m(" --yes given \u2014 proceeding against production.")));let p;if(o){let x=yh(e,o);x||(console.error(S(`No saved session matches "${o}" in this repo.`)),console.error(m("List sessions inside the REPL with /resume.")),process.exit(2)),p=x.uuid,console.error(m(`Resuming "${x.name}"`))}let b=mh({cwd:e,resume:p,profileName:r,allowProdWrites:s===!0}),k=p??null,$=1;for await(let x of b.send(t))switch(x.type){case"session":if(!k){k=x.sessionId;let j=new Date().toISOString();bh({uuid:k,name:wh(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:j,updatedAt:j})}break;case"text":process.stdout.write(x.delta);break;case"tool":console.error(ue(` \u2699 ${x.name}`));break;case"result":$=x.ok?0:1,console.error(m(`(${x.inputTokens}\u2192${x.outputTokens} tokens`+(x.costUsd>0?`, $${x.costUsd<.01?x.costUsd.toFixed(4):x.costUsd.toFixed(2)}`:"")+")")),x.ok||console.error(S("agent finished with an error result"));break;case"error":console.error(""),console.error(S(`agent error: ${x.message}`)),process.exit(1)}k&&kh(k),process.stdout.write(`
|
|
280
|
+
`),process.exit($)}import{createInterface as zy}from"node:readline/promises";import{createSession as ka,resolveAuth as Ky,getSession as Xy,setTitle as Qy,slugify as Jy,touchSession as Td,upsertSession as Zy,generateTitle as ew,resolveActiveProfile as Dd,resolveModelSetting as tw,readProjectConfig as nw,resolveAndPersistAppType as ow,decodeJwtClaims as Pd,isExpired as rw,loadTokens as sw,isDirectiveMention as iw,stripDirectiveMention as aw,appendDirective as lw,reconcileUpgradeActions as cw,stampArticles as uw,listArticleFiles as dw,CONTENT_CAP_VERSION as pw}from"document360-engine";import{ENGINE_VERSION as vh}from"document360-engine";var Le=[{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:"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 whose last run failed \u2014 the follow-up after re-authoring their specs."},{t:"cmd",name:"/screenshot capture --all --retry-blocked",s:"Include shots that skipped on missing data last run (a bulk run leaves them out by default)."},{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 (\u25CF captured \xB7 \u25D0 ready \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:"When a shot does not produce an 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:"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."}]}];function xh(e){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":return` ${e.name.padEnd(20)} ${e.s}`;case"gap":return""}}function Sl(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 Le){n.push(`\u2500\u2500 ${o.label} \u2500\u2500`,"");for(let r of o.rows)n.push(xh(r));n.push("")}return n.push("Tip: anything not starting with / goes to the agent."),n}async function ks(e=[],t){console.log("");let n=t?.version?{version:t.version,engineVersion:vh}:void 0;for(let o of Sl(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"}}z();import{getSession as Ch}from"document360-engine";async function Pl(e,t){let n=t.currentUuid(),o=n?Ch(n):void 0;return console.log(o?m(`
|
|
281
281
|
(conversation reset \u2014 "${o.name}" is still available via /resume)
|
|
282
|
-
`):
|
|
282
|
+
`):m(`
|
|
283
283
|
(conversation reset \u2014 agent will start fresh on the next prompt)
|
|
284
|
-
`)),{kind:"clear"}}async function bs(){return{kind:"exit"}}Yo();
|
|
284
|
+
`)),{kind:"clear"}}async function bs(){return{kind:"exit"}}Yo();z();import{readMcpConfig as Ss,writeMcpConfig as Xl}from"document360-engine";async function zo(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(Wh(),{kind:"continue"}):t==="add"?(Fh(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(Bh(e.slice(1)),{kind:"continue"}):(console.log(S(`Unknown /mcp subcommand: ${t}`)),console.log(m("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function Wh(){let e=Ss(),t=Object.keys(e.servers);if(t.length===0){console.log(m(`
|
|
285
285
|
No MCP servers registered. Add one with /mcp add <name> <type> <ref>
|
|
286
|
-
`));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 Oh(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(S("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(S(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=Ss(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let a={};for(let u=1;u<o.length;u++)if(o[u]==="-H"||o[u]==="--header"){let h=o[++u],k=h?.match(/^([^:=]+)[:=](.+)$/);if(!k){console.log(S(`-H expects key:value (no spaces). Got: ${h??"(nothing)"}`));return}a[k[1].trim()]=k[2].trim()}else{console.log(S(`Unexpected argument: ${o[u]}. After the URL, only -H key:value is allowed.`));return}s={type:n,url:o[0],headers:Object.keys(a).length>0?a:void 0}}r.servers[t]=s,Xc(r),console.log(""),console.log(O(`\u2713 Registered "${t}" (${n})`)),console.log(B(" 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 Lh(e){let t=e[0];if(!t){console.log(S("Usage: /mcp remove <name>"));return}let n=Ss();if(!n.servers[t]){console.log(S(`No server named "${t}".`));return}delete n.servers[t],Xc(n),console.log(O(`\u2713 Removed "${t}".`)),console.log(g(" Run /clear to drop it from the current session immediately."))}Y();import{readFileSync as wf}from"node:fs";import{join as kf}from"node:path";import{select as bf}from"@inquirer/prompts";import{computeSyncStatus as ir,planPartitions as $f,relatedArticlePaths as xf,resolveModelForOperation as vf,runPartitioned as Cf,loadProfileMap as Rf,resolveActiveProfile as Sf,resolveCrossLinks as Pf,applyStructureOrder as Nl,orderSyncLine as Il,applyRelatedArticles as _l,relatedSyncLine as Ol}from"document360-engine";import ne from"picocolors";import al from"wrap-ansi";import js from"string-width";Y();import ht from"picocolors";import Ps from"wrap-ansi";import Ts from"string-width";var an=[{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|checklist|list] [id|path|--all|--failed|--retry-blocked]",desc:"Screenshots, one family \u2014 bare: pick what to do; author: write capture specs; capture: take the shots (--failed re-runs broken ones; --retry-blocked re-tries shots waiting on data); 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 (hints + requests + drift) \u2192 write \u2192 push to Document360 (bare = drafts; --publish goes live)",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"}],Qc={"/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 Jc(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(Qc[n])return Qc[n];let o=an.find(r=>r.name===t);return o?o.desc:""}function Zc(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return an.filter(n=>n.name.startsWith(t))}function el(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}var Mh=new RegExp(`^\\s*/(?:${an.map(e=>e.name).join("|")})(?:\\s|$)`),tl=e=>Mh.test(e),nl=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),ol=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),rl=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function Uh(e){let t=e.replace(/\r/g,"").split(`
|
|
287
|
-
`),n=[],o=0;for(;o<t.length;){let r=t[o];if(/^\s*```/.test(r)){let u=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)u.push(t[o++]);o++,n.push({kind:"code",lines:u});continue}if(
|
|
288
|
-
`)}),U=Math.max(...E.map(
|
|
289
|
-
`)},j=[
|
|
290
|
-
`)}function
|
|
291
|
-
`);return` ${r} ${a}`+u.map(
|
|
292
|
-
${s}${
|
|
293
|
-
`)}case"code":return e.lines.map(n=>
|
|
294
|
-
`);case"table":return
|
|
295
|
-
|
|
296
|
-
`)}
|
|
297
|
-
`);let r=2,s=3,a=js(o[0]);if(!(t>=r+a+s+Math.max(...n.map(
|
|
298
|
-
`);let
|
|
299
|
-
`)}var
|
|
300
|
-
`).flatMap(
|
|
301
|
-
`)),
|
|
302
|
-
`+u.map((k
|
|
286
|
+
`));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)} ${m("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?m(` [headers: ${r.join(", ")}]`):"";console.log(` ${W(n)} ${m(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function Fh(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(S("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(S(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=Ss(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let a={};for(let u=1;u<o.length;u++)if(o[u]==="-H"||o[u]==="--header"){let p=o[++u],b=p?.match(/^([^:=]+)[:=](.+)$/);if(!b){console.log(S(`-H expects key:value (no spaces). Got: ${p??"(nothing)"}`));return}a[b[1].trim()]=b[2].trim()}else{console.log(S(`Unexpected argument: ${o[u]}. After the URL, only -H key:value is allowed.`));return}s={type:n,url:o[0],headers:Object.keys(a).length>0?a:void 0}}r.servers[t]=s,Xl(r),console.log(""),console.log(_(`\u2713 Registered "${t}" (${n})`)),console.log(B(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(m(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function Bh(e){let t=e[0];if(!t){console.log(S("Usage: /mcp remove <name>"));return}let n=Ss();if(!n.servers[t]){console.log(S(`No server named "${t}".`));return}delete n.servers[t],Xl(n),console.log(_(`\u2713 Removed "${t}".`)),console.log(m(" Run /clear to drop it from the current session immediately."))}z();import{readFileSync as Cf}from"node:fs";import{join as Rf}from"node:path";import{select as Sf}from"@inquirer/prompts";import{computeSyncStatus as ir,planPartitions as Pf,relatedArticlePaths as Tf,resolveModelForOperation as Df,runPartitioned as Af,loadProfileMap as Ef,resolveActiveProfile as jf,resolveCrossLinks as Nf,applyStructureOrder as Ic,orderSyncLine as Oc,applyRelatedArticles as _c,relatedSyncLine as Lc}from"document360-engine";import ne from"picocolors";import ac from"wrap-ansi";import js from"string-width";z();import mt from"picocolors";import Ps from"wrap-ansi";import Ts from"string-width";var dn=[{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|checklist|list] [id|path|--all|--failed|--retry-blocked]",desc:"Screenshots, one family \u2014 bare: pick what to do; author: write capture specs; capture: take the shots (--failed re-runs broken ones; --retry-blocked re-tries shots waiting on data); 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 (hints + requests + drift) \u2192 write \u2192 push to Document360 (bare = drafts; --publish goes live)",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"}],Ql={"/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 Jl(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(Ql[n])return Ql[n];let o=dn.find(r=>r.name===t);return o?o.desc:""}function Zl(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return dn.filter(n=>n.name.startsWith(t))}function ec(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}var qh=new RegExp(`^\\s*/(?:${dn.map(e=>e.name).join("|")})(?:\\s|$)`),tc=e=>qh.test(e),nc=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),oc=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),rc=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function Hh(e){let t=e.replace(/\r/g,"").split(`
|
|
287
|
+
`),n=[],o=0;for(;o<t.length;){let r=t[o];if(/^\s*```/.test(r)){let u=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)u.push(t[o++]);o++,n.push({kind:"code",lines:u});continue}if(nc(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&oc(t[o+1])){let u=rc(r);o+=2;let p=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)p.push(rc(t[o++]));n.push({kind:"table",header:u,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 u=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);){let p=t[o++];u.push({ordered:/^\s*\d+\.\s+/.test(p),text:p.replace(/^\s*([-*]|\d+\.)\s+/,"")})}n.push({kind:"list",items:u});continue}if(r.trim()===""){o++;continue}if(tc(r)){n.push({kind:"para",text:r.trim()}),o++;continue}let a=[];for(;o<t.length&&t[o].trim()!==""&&!/^\s*```/.test(t[o])&&!/^(#{1,6})\s/.test(t[o])&&!/^\s*([-*]|\d+\.)\s+/.test(t[o])&&!tc(t[o])&&!nc(t[o])&&!(t[o].includes("|")&&o+1<t.length&&oc(t[o+1]));)a.push(t[o++]);n.push({kind:"para",text:a.join(" ")})}return n}function Ds(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?mt.bold(t.slice(2,-2)):t.startsWith("`")?W(t.slice(1,-1)):mt.italic(t.slice(1,-1)))}var Vh=(e,t)=>e+" ".repeat(Math.max(0,t-Ts(e)));function Gh(e,t,n){let o=e.length,r=e.map((v,D)=>Math.max(Ts(v),...t.map(E=>Ts(E[D]??"")))),s=Math.max(24,n),a=3*o+1,u=[...r],p=()=>u.reduce((v,D)=>v+D,0)+a,b=0;for(;p()>s&&b++<1e4;){let v=-1,D=6;for(let E=0;E<o;E++)u[E]>D&&(D=u[E],v=E);if(v===-1)break;u[v]-=1}let k=(v,D,E)=>mt.gray(v+u.map(U=>"\u2500".repeat(U+2)).join(D)+E),$=mt.gray("\u2502"),x=(v,D)=>{let E=u.map((G,H)=>{let se=v[H]??"",qe=D?mt.bold(se):Ds(se);return Ps(qe,G,{hard:!0}).split(`
|
|
288
|
+
`)}),U=Math.max(...E.map(G=>G.length)),L=[];for(let G=0;G<U;G++)L.push(u.map((H,se)=>`${$} ${Vh(E[se][G]??"",H)} `).join("")+$);return L.join(`
|
|
289
|
+
`)},j=[k("\u250C","\u252C","\u2510"),x(e,!0)];return j.push(t.length===0?k("\u2514","\u2534","\u2518"):k("\u251C","\u253C","\u2524")),t.forEach((v,D)=>{j.push(x(v,!1)),j.push(D===t.length-1?k("\u2514","\u2534","\u2518"):k("\u251C","\u253C","\u2524"))}),j.join(`
|
|
290
|
+
`)}function Yh(e,t){switch(e.kind){case"heading":return mt.bold(e.text);case"hr":return mt.gray("\u2500".repeat(t));case"para":return Ps(Ds(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),[a="",...u]=Ps(Ds(o.text),Math.max(10,t-s.length)).split(`
|
|
291
|
+
`);return` ${r} ${a}`+u.map(p=>`
|
|
292
|
+
${s}${p}`).join("")}).join(`
|
|
293
|
+
`)}case"code":return e.lines.map(n=>mt.gray(" "+n)).join(`
|
|
294
|
+
`);case"table":return Gh(e.header,e.rows,t)}}function As(e,t){let n=Math.max(20,t);return Hh(e).map(o=>Yh(o,n)).join(`
|
|
295
|
+
|
|
296
|
+
`)}z();import zh from"picocolors";var Kh=[127,86,217],Xh=[22,38,43],sc={T:Kh,E:Xh},Wn=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],Es=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,Qh=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function ic(){if(!zh.isColorSupported)return[];let e=Wn[0].length,t=[];for(let n=0;n<Wn.length;n+=2){let o="";for(let r=0;r<e;r++){let s=sc[Wn[n][r]],a=n+1<Wn.length?sc[Wn[n+1][r]]:void 0;s&&a?o+=`${Es(s)}${Qh(a)}\u2580\x1B[49m\x1B[39m`:s?o+=`${Es(s)}\u2580\x1B[39m`:a?o+=`${Es(a)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function Fn(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 Bn(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function Pe(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function gt(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var pn=(e,t)=>` ${e.padEnd(13)}${t}`;function Jh(e,t){let n=[On("\u270E document360-writer")+ne.gray(` v${e.version} \xB7 engine v${e.engineVersion}${e.captureVersion?` \xB7 capture v${e.captureVersion}`:""}`),ne.gray(" Reads your code, writes your docs."),"",pn("Claude:",`${e.claude}${ne.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),pn("Document360:",e.configured?e.loggedOut?ne.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?ne.gray(` (${e.sessionHint})`):""}`:ne.yellow("not set up \u2014 run /init")),pn("Profile:",e.configured?`${e.profile}${ne.gray(` (${e.apiUrl})`)}${e.prod?ne.bold(ne.yellow(" \u26A0 PRODUCTION")):""}`:ne.gray("\u2014 (run /init)")),pn("Project:",e.project),pn("Mode:",ne.gray(e.mode)),pn("cwd:",ne.gray(e.cwd))],o=ic();if(o.length===0)return n.join(`
|
|
297
|
+
`);let r=2,s=3,a=js(o[0]);if(!(t>=r+a+s+Math.max(...n.map(k=>js(k)))))return[...o.map(k=>" "+k),...n].join(`
|
|
298
|
+
`);let p=Math.max(0,Math.floor((n.length-o.length)/2)),b=[];for(let k=0;k<Math.max(o.length+p,n.length);k++){let $=o[k-p]??" ".repeat(a);b.push((" ".repeat(r)+$+" ".repeat(s)+(n[k]??"")).trimEnd())}return b.join(`
|
|
299
|
+
`)}var Zh={error:ne.red,warn:ne.yellow,ok:ne.green,info:ne.gray};function Ns(e){return e.replace(/^(\s*• |)([^\x00-\x7F][\u{1F000}-\u{1FAFF}️]*) (?=\S)/gmu,"$1$2 ")}function Is(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return Jh(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",s=Math.max(10,n-4),a=50,u=e.text.split(`
|
|
300
|
+
`).flatMap(b=>ac(b,s,{hard:!0}).split(`
|
|
301
|
+
`)),p=Math.max(0,u.length-a);return p>0&&(u=[...u.slice(0,a),ne.dim(`\u2026 +${p} more lines`)]),`
|
|
302
|
+
`+u.map((b,k)=>o+(k===0?W(" \u276F "):" ")+b+" ".repeat(Math.max(0,s-js(b))+1)+r).join(`
|
|
303
303
|
`)}case"assistant":return`
|
|
304
304
|
`+As(e.text,n);case"tool":{let o=e.arg!==null?ne.gray(`${e.sep}(${e.arg})`):"";return`
|
|
305
|
-
`+
|
|
305
|
+
`+ac(ne.green("\u25CF ")+ne.bold(e.title)+o,n)}case"tool-result":{let o=e.isError?ne.red:ne.gray,r=e.lines.map((s,a)=>o((a===0?" \u23BF ":" ")+s));return e.hidden>0&&r.push(ne.dim(` \u2026 +${e.hidden} lines`)),r.join(`
|
|
306
306
|
`)}case"diff":{let o=a=>a===1?"":"s",s=[ne.gray(` \u23BF Added ${e.added} line${o(e.added)}, removed ${e.removed} line${o(e.removed)}`),...e.lines];return e.hidden>0&&s.push(ne.dim(` \u2026 +${e.hidden} more diff lines`)),s.join(`
|
|
307
|
-
`)}case"link":return e.lines.map(o=>W(
|
|
307
|
+
`)}case"link":return e.lines.map(o=>W(Ln(` \u2B95 ${o}`))).join(`
|
|
308
308
|
`);case"preview":return`
|
|
309
|
-
`+
|
|
309
|
+
`+On(`\u25A3 Preview \u2014 ${e.name}`)+`
|
|
310
310
|
|
|
311
311
|
`+As(e.text,n);case"note":return`
|
|
312
|
-
`+
|
|
313
|
-
`+(e.ok?ne.magenta("\u2736 "):ne.red("\u2736 "))+ne.gray(`Cooked for ${
|
|
314
|
-
`)}import{resolveActiveProfile as
|
|
315
|
-
`,"utf8")}function _s(e){return e&&/data-testid|\btest-?id\b|has(?:n't| not) landed/i.test(e)?"testid":"data"}function hl(e,t,n){if(t.length===0)return;let o=Wn(e);for(let r of t){let s=r.specSource?pl(r.specSource):void 0;o.shots[r.id]={outcome:r.outcome,at:n,...r.reason?{reason:r.reason}:{},...r.outcome==="skipped"?{blockedBy:_s(r.reason)}:{},...s?{specHash:s}:{}}}nf(e,o)}function Os(e,t,n){let o=e.shots[t];return!o||n===null||!o.specHash||o.specHash!==pl(n)?null:o}function fl(e){let t=Wn(e).shots;return Object.keys(t).filter(n=>t[n].outcome==="failed").sort()}function Ls(e,t,n){let o=Os(Wn(e),t,n);return o?.outcome==="failed"?o.reason??null:null}var bl=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function ml(e){let t=e.includes("--detail")||e.includes("-d"),n=e.find(o=>o!=="--detail"&&o!=="-d");return{mode:"list",scope:n?bl(n):void 0,...t?{detail:!0}:{}}}function Fn(e){let t=(e[0]??"").toLowerCase();if(t==="capture")return{mode:"capture",rest:e.slice(1)};if(t==="checklist"||t==="setup")return{mode:"checklist"};if(t==="list")return ml(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 ml(o.slice(1));let r=o[0];return r?r==="--all"?{mode:"all",setup:n}:/[\\/]/.test(r)||r.endsWith(".md")?{mode:"scope",scope:bl(r),setup:n}:{mode:"single",id:r}:{mode:"list",picker:!0}}function Ye(e,t){let n=ln(e),o=n?.captureDir??tr,r=n?.outputDir??of,s=(u,h)=>Jo(u)?Zo(u,h):er(e,u,h),a=Wn(e);return kl(e,{scope:t}).map(({id:u,file:h})=>{let k=s(o,`${u}.spec.ts`),b=null;if(Ms(k))try{b=Bs(k,"utf8")}catch{}let x=Ms(s(r,`${u}.png`)),$=b===null?null:Os(a,u,b),j=b!==null&&rf(b),v=x?"captured":b===null?"placeholder":j||$?.outcome==="skipped"?"blocked":$?.outcome==="failed"?"broken":"spec",T=b===null?void 0:xl(b),E=j?sf(b):$?.reason,U=j?"testid":$?.outcome==="skipped"?_s($.reason):void 0;return{id:u,file:h,state:v,...T?{mutates:T.mutates,...T.declared?{}:{undeclared:!0}}:{},...b!==null&&gl(b).length>0?{unguardedWaits:gl(b)}:{},...v==="blocked"||v==="broken"?{...E?{reason:E}:{},...U?{blockedBy:U}:{}}:{}}})}function nr(e,t){let n=ln(e)?.captureDir??tr,o=Jo(n)?Zo(n,`${t}.spec.ts`):er(e,n,`${t}.spec.ts`);try{return Bs(o,"utf8")}catch{return null}}function $l(e,t){let n=ln(e)?.captureDir??tr;return Ms(Jo(n)?Zo(n,`${t}.spec.ts`):er(e,n,`${t}.spec.ts`))}function xl(e){let t=/^\s*\/\/\s*CAPTURE-SAFETY:\s*(readonly|mutates)\b[\s—:–-]*(.*)$/im.exec(e);if(t)return{mutates:t[1].toLowerCase()==="mutates",declared:!0,what:t[2]?.trim()||void 0};let n=/setInputFiles/.test(e),o=/\{\s*name:\s*['"][^'"]*\b(create|import|save|apply|confirm|delete|submit|send|mint)\b[^'"]*['"][^}]*\}\s*\)\s*\.click\(/i.test(e),r=/\.fill\(/.test(e);return{mutates:n||r&&o,declared:!1}}function rf(e){return/(^|\n)\s*test\.skip\s*\(\s*['"`]/.test(e)}function sf(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 gl(e){let t=[],n=e.split(/\r?\n/);for(let[o,r]of n.entries()){if(!/\.waitFor\s*\(/.test(r))continue;let s=r;for(let a=o+1;a<n.length&&!/;\s*$/.test(s.trim())&&a<o+4;a++)s+=n[a];/\.catch\s*\(/.test(s)||t.push(o+1)}return t}function Hs(e){return(e??"").trim().replace(/[.\s]+$/,"")}function vl(e,t){let n=ln(e)?.captureDir??tr,o=Jo(n)?Zo(n,`${t}.spec.ts`):er(e,n,`${t}.spec.ts`);try{return xl(Bs(o,"utf8"))}catch{return{mutates:!1,declared:!1}}}function or(e){return[...new Set(e.filter(t=>t.state==="captured").map(t=>t.file))].sort()}var af={placeholder:"\u25CB",spec:"\u25D0",blocked:"\u2298",broken:"\u2717",captured:"\u25CF"},cf={placeholder:_.gray,spec:_.yellow,blocked:_.cyan,broken:_.red,captured:_.green},Cl=` ${_.green("\u25CF captured")} ${_.yellow("\u25D0 ready")} ${_.cyan("\u2298 blocked")} ${_.red("\u2717 broken")} ${_.gray("\u25CB to spec")}`;function ot(e,t=n=>n){return`${t(e)} `}function lf(e){let t=e.replace(/\s+/g," ").trim().replace(/^Prerequisite not met:\s*/i,""),n=/^(.*?[a-z0-9)"'”’])\.(?:\s|$)/i.exec(t);return(n?n[1]:t).trim()}function Vs(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=lf(o),a=`${r} ${s.toLowerCase()}`,u=t.get(a)??{reason:s,blockedBy:r,ids:[]};t.has(a)||t.set(a,u),u.ids.push(n.id)}return[...t.values()].sort((n,o)=>o.ids.length-n.ids.length||n.reason.localeCompare(o.reason))}function Rl(e){let t=Vs(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((u,h)=>u+h.ids.length,0);r.push(` ${_.bold("Stage this data")} ${_.gray(`\u2014 unblocks ${s} shot${s===1?"":"s"} in ${n.length} action${n.length===1?"":"s"}`)}`);let a=8;for(let u of n.slice(0,a)){let h=Un(u.reason,86);r.push(` ${_.cyan(mt(`${u.ids.length}\xD7`,4))} ${h[0]??""}`);for(let b of h.slice(1))r.push(` ${b}`);let k=u.ids.slice(0,4).join(" \xB7 ");r.push(_.gray(` ${k}${u.ids.length>4?` \xB7 +${u.ids.length-4} more`:""}`))}n.length>a&&r.push(_.gray(` \u2026 ${n.length-a} more staging action${n.length-a===1?"":"s"} \u2014 /screenshot list --detail`))}if(o.length>0){let s=o.reduce((a,u)=>a+u.ids.length,0);r.push(` ${ot("\u2298",_.cyan)}${s} shot${s===1?"":"s"} need${s===1?"s":""} a data-testid from your developers \u2014 ${_.bold("/screenshot checklist")} builds the hand-off.`)}return r}function Sl(e){let t=e.filter(o=>(o.unguardedWaits?.length??0)>0);if(t.length===0)return[];let n=t.reduce((o,r)=>o+(r.unguardedWaits?.length??0),0);return["",` ${ot("\u26A0",_.yellow)}${t.length} spec${t.length===1?"":"s"} ${t.length===1?"has":"have"} ${n} unguarded wait${n===1?"":"s"}`+_.gray(" \u2014 on missing data these fail with a stack trace instead of telling you what to stage"),_.gray(` ${t.slice(0,6).map(o=>`${o.id}:${o.unguardedWaits.join(",")}`).join(" \xB7 ")}${t.length>6?` \xB7 +${t.length-6} more`:""}`),_.gray(` Re-author to guard them: ${_.bold("/screenshot author <id>")}`)]}function Pl(e){let t=e.filter(o=>o.undeclared);if(t.length===0)return[];let n=t.filter(o=>o.mutates);return["",` ${ot("\u26A0",_.yellow)}${t.length} spec${t.length===1?"":"s"} carr${t.length===1?"ies":"y"} no CAPTURE-SAFETY declaration`+(n.length>0?_.gray(` \u2014 ${n.length} of them read as "writes real data" by heuristic, so bulk capture benches ${n.length===1?"it":"them"}`):""),_.gray(` ${t.slice(0,6).map(o=>o.id).join(" \xB7 ")}${t.length>6?` \xB7 +${t.length-6} more`:""}`),_.gray(` Re-author them to declare it: ${_.bold("/screenshot author <id>")}`)]}var Xo=(e,t)=>e.length>=t?e:e+" ".repeat(t-e.length),mt=(e,t)=>e.length>=t?e:" ".repeat(t-e.length)+e;function Tl(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 uf=new Set(["and","or","of","the","to","a","an","in","on","for","with","vs"]),df=new Set(["ai","api","cli","ui","ux","url","id","http","https","json","xml","sdk","csv","pdf","oauth","sso","mfa","io","faq"]);function pf(e){return e.replace(/[-_]+/g," ").trim().split(/\s+/).filter(Boolean).map((n,o)=>{let r=n.toLowerCase();return df.has(r)?r.toUpperCase():o>0&&uf.has(r)?r:r.charAt(0).toUpperCase()+r.slice(1)}).join(" ")}function Us(e){if(!e)return{num:"",name:"(docs root)"};let t=/^(\d+)[-_](.+)$/.exec(e);return{num:t?t[1]:"",name:pf(t?t[2]:e)}}function hf(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).pop()??e}function yl(e,t,n){let o=t>0?Math.round(e/t*n):0;return _.green("\u2588".repeat(o))+_.gray("\u2591".repeat(Math.max(0,n-o)))}function ff(e,t){let n=t>0?Math.round(e/t*100):0,o=mt(`${n}%`,4);return n===100?_.green(o):n>0?_.yellow(o):_.gray(o)}function Dl(e,t){let n=new Map;for(let o of e){let r=Tl(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 mf(e,t){let n=(L,V)=>L.filter(H=>H.state===V).length,o=e.length,r=n(e,"captured"),s=n(e,"spec"),a=n(e,"blocked"),u=n(e,"broken"),h=n(e,"placeholder"),k=new Set(e.map(L=>L.file)).size,b=Dl(e,t),x=[];x.push(` ${_.bold("Screenshots")} ${_.green(`${r}/${o} captured`)} ${_.gray("\xB7")} ${s>0?_.yellow(`${s} ready`):_.gray("0 ready")}`+(a>0?` ${_.gray("\xB7")} ${_.cyan(`${a} blocked`)}`:"")+(u>0?` ${_.gray("\xB7")} ${_.red(`${u} broken`)}`:"")+` ${_.gray("\xB7")} ${h>0?_.red(`${h} to spec`):_.gray("0 to spec")} `+_.gray(`across ${k} article${k===1?"":"s"}`));let $=o>0?Math.round(r/o*100):0;x.push(` [${yl(r,o,32)}] ${_.bold(`${$}%`)}`),x.push("");let j=b.map(([L])=>Us(L)),v=Math.min(32,Math.max(7,...j.map(L=>L.name.length))),T=L=>L.length>v?`${L.slice(0,v-1)}\u2026`:Xo(L,v),E=[{head:"Ready",w:5,state:"spec",color:_.yellow},...a>0?[{head:"Blocked",w:7,state:"blocked",color:_.cyan}]:[],...u>0?[{head:"Broken",w:6,state:"broken",color:_.red}]:[],{head:"To spec",w:7,state:"placeholder",color:_.red}];x.push(_.gray(` ${Xo("#",2)} ${Xo("Chapter",v)} ${mt("Captured",8)} ${E.map(L=>mt(L.head,L.w)).join(" ")} Progress`));for(let[L,[,V]]of b.entries()){let H=n(V,"captured"),re=V.length,{num:Fe,name:fe}=j[L],Ke=H===re,me=T(fe),Xe=E.map(be=>{let Be=n(V,be.state);return Be>0?be.color(mt(String(Be),be.w)):_.gray(mt("\u2014",be.w))}).join(" ");x.push(` ${_.cyan(Xo(Fe,2))} ${Ke?_.green(me):H>0?me:_.gray(me)} ${Ke?_.green(mt(`${H}/${re}`,8)):mt(`${H}/${re}`,8)} ${Xe} ${yl(H,re,10)} ${ff(H,re)}`)}x.push("");let U=u>0?` ${_.gray("\xB7")} ${u} spec${u===1?"":"s"} broken \u2014 ${_.bold(`/screenshot ${e.find(L=>L.state==="broken").id}`)} re-authors ${u===1?"it":"the first"}`:"";if(h>0)x.push(` ${ot("\u2192",_.yellow)}${h} placeholder${h===1?"":"s"} still need a spec \u2014 run ${_.bold("/screenshot author --all")}${U}`);else if(s>0){let L=e.filter(H=>H.state==="spec"&&H.mutates).length,V=L>0?_.gray(` \u2014 ${s-L} in one go; ${L} write${L===1?"s":""} real data and run${L===1?"s":""} one at a time`):"";x.push(` ${ot("\u2192",_.yellow)}${s} spec${s===1?"":"s"} ready to capture \u2014 run ${_.bold("/screenshot capture")}${V}${U}`)}else a>0?x.push(` ${ot("\u2192",_.cyan)}${a} shot${a===1?"":"s"} blocked \u2014 stage the data below, then ${_.bold("/screenshot capture --all --retry-blocked")}${U}`):u>0?x.push(` ${ot("\u2192",_.red)}${u} spec${u===1?"":"s"} broken \u2014 ${_.bold(`/screenshot ${e.find(L=>L.state==="broken").id}`)} re-authors ${u===1?"it":"the first"} (re-capturing fails the same way)`):x.push(` ${ot("\u2713",_.green)}all ${o} captured \u2014 ${_.bold("/publish")} embeds them in the articles`);if(r>0&&r<o){let L=b.filter(([,V])=>V.every(H=>H.state!=="captured")).map(([V])=>{let{num:H,name:re}=Us(V);return H?`${H} ${re}`:re});L.length>0&&x.push(_.gray(` Furthest behind: ${L.slice(0,5).join(" \xB7 ")}${L.length>5?" \u2026":""} (0% captured)`))}return x.push(...Rl(e),...Sl(e),...Pl(e)),x.push(""),x.push(Cl),x.push(_.gray(" Drill in: /screenshot list <chapter#> \xB7 /screenshot list --detail (all)")),x}function gf(e,t,n){let o=new Set(e.map(a=>a.file)),r=e.filter(a=>a.state==="captured").length,s=[` ${_.bold("Screenshots")}: ${e.length} placeholder${e.length===1?"":"s"} across ${o.size} article${o.size===1?"":"s"} \xB7 ${_.green(`${r} captured`)}${n?_.gray(` \xB7 scope ${n}`):""}`,""];for(let[a,u]of Dl(e,t)){let h=u.filter(j=>j.state==="captured").length,{num:k,name:b}=Us(a),x=k?`${k} \xB7 ${b}`:b;s.push(` ${_.bold(x)} ${_.gray(`(${h}/${u.length})`)}`);let $=new Map;for(let j of u){let v=hf(j.file),T=$.get(v)??[];$.has(v)||$.set(v,T),T.push(j)}for(let j of[...$.keys()].sort()){s.push(_.gray(` ${j}`));for(let v of $.get(j)){let T=cf[v.state];if(s.push(` ${ot(af[v.state],T)}${T(v.id)}`),(v.state==="blocked"||v.state==="broken")&&v.reason)for(let E of Un(v.reason,84))s.push(_.gray(` ${E}`))}}}return s.push(...Rl(e),...Sl(e),...Pl(e)),s.push("",Cl),s}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??qs;return t?.detail||n?gf(e,o,n):mf(e,o)}function Gs(e,t){if(!t||!/^\d+$/.test(t))return t;let n=ln(e)?.docsDir??qs,o=String(Number(t));for(let{file:r}of kl(e)){let s=Tl(r,n),a=/^(\d+)/.exec(s);if(a&&String(Number(a[1]))===o)return s}return t}function yf(e){let t=e.replace(/\\/g,"/").split("/").filter(Boolean),n=t.pop()??e;return{category:t.pop()??"(docs root)",article:n}}function Qo(e,t,n){let o=new Map;for(let s of t){let{category:a,article:u}=yf(s.file),h=o.get(a)??new Map;o.set(a,h);let k=h.get(u)??[];h.set(u,k),k.push(s)}let r=s=>n==="author"||!s.mutates;for(let s of[...o.keys()].sort()){let a=o.get(s),u=[...a.values()].flat().filter(r).map(h=>h.id);u.length>0&&e.push({kind:"category",action:n,label:`${s} (${u.length})`,ids:u,depth:1});for(let h of[...a.keys()].sort()){let k=a.get(h),b=k.filter(r).map(x=>x.id);b.length>0&&e.push({kind:"article",action:n,label:`${h} (${b.length})`,ids:b,depth:2});for(let x of k){let $=n==="capture"&&x.mutates?" \u26A0 creates real data \u2014 runs only alone":void 0;e.push({kind:"shot",action:n,label:x.id,ids:[x.id],depth:3,...$?{note:$}:{}})}}}}function wl(e,t=58){if(!e)return"";let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n}function Ys(e,t,n){let o=t.filter(r=>!r.mutates);o.length>1&&e.push({kind:"all",action:"capture",label:`Retry ${o.length} blocked shots (stage the data first)`,ids:o.map(r=>r.id),depth:0});for(let r of[...t].sort((s,a)=>s.id.localeCompare(a.id)))e.push({kind:"shot",action:"capture",label:r.id,ids:[r.id],depth:1,note:` \u2298 ${wl(r.reason)}`});n.length>1&&e.push({kind:"all",action:"author",label:`Re-author ${n.length} broken specs`,ids:n.map(r=>r.id),depth:0});for(let r of[...n].sort((s,a)=>s.id.localeCompare(a.id)))e.push({kind:"shot",action:"author",label:r.id,ids:[r.id],depth:1,note:` \u2717 ${wl(r.reason)} \u2014 re-authors`})}function Al(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}),Qo(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}),Qo(o,n,"capture"),Ys(o,e.filter(s=>s.state==="blocked"),e.filter(s=>s.state==="broken")),o}var Ws=["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.","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(`
|
|
316
|
-
`),Fs="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
|
|
312
|
+
`+Zh[e.tone](Ln(Ns(e.text)));case"done":{let o=e.inTokens&&e.inTokens>0?` \xB7 ${Fn(e.inTokens)} in${e.cachedPct!=null?` (${e.cachedPct}% cached)`:""}`:"";return`
|
|
313
|
+
`+(e.ok?ne.magenta("\u2736 "):ne.red("\u2736 "))+ne.gray(`Cooked for ${Bn(e.seconds)} \xB7 ${Fn(e.tokens)} tokens out${o}`+(e.costUsd>0?` \xB7 ${Pe(e.costUsd)}`:""))}}}function lc(e,t){return e.map(n=>Is(n,t)).join(`
|
|
314
|
+
`)}import{resolveActiveProfile as ef,loadTokens as tf,isExpired as nf,decodeJwtClaims as cc}from"document360-engine";function of(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function Ue(e,t){try{let n=ef(e,t),o=tf(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(nf(o)&&!o.refreshToken)return{ok:!1,reason:`Your Document360 session expired (profile "${n.name}"). Run /login.`};let r=n.project.projectId;if(r){let a={...cc(o.idToken)??{},...cc(o.accessToken)??{}}.doc360_project_id;if(typeof a=="string"&&a&&a!==r)return{ok:!1,reason:`Your Document360 session is signed into a different project than profile "${n.name}" (this profile's project is ${of(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}import{existsSync as Ms,readFileSync as Bs}from"node:fs";import{isAbsolute as Jo,join as Zo,resolve as er}from"node:path";import O from"picocolors";function qn(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 Ko(e){if(e.length===0)return[];let t=(s,a)=>`${s}${"\u2500".repeat(78)}${a}`,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,a)=>{a>0&&o.push(t("\u251C","\u2524")),o.push(n());for(let u of qn(`${a+1}. ${s.feature}`,76))o.push(n(u));o.push(n());for(let u of qn(s.why,73))o.push(n(` ${u}`));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}import{readProjectConfig as hn,screenshotPlaceholderIds as kc,DEFAULT_CAPTURE_DIR as tr,DEFAULT_OUTPUT_DIR as cf,DEFAULT_DOCS_DIR as qs}from"document360-engine";import{createHash as rf}from"node:crypto";import{readFileSync as sf,writeFileSync as af}from"node:fs";import{captureStatePath as dc}from"document360-engine";var uc={version:1,shots:{}};function pc(e){return rf("sha1").update(e).digest("hex").slice(0,12)}function _t(e){try{let t=JSON.parse(sf(dc(e),"utf8").replace(/^/,""));return!t||typeof t!="object"||t.version!==1||!t.shots?{...uc,shots:{}}:{version:1,shots:t.shots}}catch{return{...uc,shots:{}}}}function lf(e,t){af(dc(e),`${JSON.stringify(t,null,2)}
|
|
315
|
+
`,"utf8")}function Os(e){return e&&/data-testid|\btest-?id\b|has(?:n't| not) landed/i.test(e)?"testid":"data"}function hc(e,t,n){if(t.length===0)return;let o=_t(e);for(let r of t){let s=r.specSource?pc(r.specSource):void 0;o.shots[r.id]={outcome:r.outcome,at:n,...r.reason?{reason:r.reason}:{},...r.outcome==="skipped"?{blockedBy:Os(r.reason)}:{},...s?{specHash:s}:{}}}lf(e,o)}function _s(e,t,n){let o=e.shots[t];return!o||n===null||!o.specHash||o.specHash!==pc(n)?null:o}function fc(e){let t=_t(e).shots;return Object.keys(t).filter(n=>t[n].outcome==="failed").sort()}function Ls(e,t,n){let o=_s(_t(e),t,n);return o?.outcome==="failed"?o.reason??null:null}var bc=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function mc(e){let t=e.includes("--detail")||e.includes("-d"),n=e.find(o=>o!=="--detail"&&o!=="-d");return{mode:"list",scope:n?bc(n):void 0,...t?{detail:!0}:{}}}function Hn(e){let t=(e[0]??"").toLowerCase();if(t==="capture")return{mode:"capture",rest:e.slice(1)};if(t==="checklist"||t==="setup")return{mode:"checklist"};if(t==="list")return mc(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 mc(o.slice(1));let r=o[0];return r?r==="--all"?{mode:"all",setup:n}:/[\\/]/.test(r)||r.endsWith(".md")?{mode:"scope",scope:bc(r),setup:n}:{mode:"single",id:r}:{mode:"list",picker:!0}}function We(e,t){let n=hn(e),o=n?.captureDir??tr,r=n?.outputDir??cf,s=(u,p)=>Jo(u)?Zo(u,p):er(e,u,p),a=_t(e);return kc(e,{scope:t}).map(({id:u,file:p})=>{let b=s(o,`${u}.spec.ts`),k=null;if(Ms(b))try{k=Bs(b,"utf8")}catch{}let $=Ms(s(r,`${u}.png`)),x=k===null?null:_s(a,u,k),j=k!==null&&df(k),v=$?"captured":k===null?"placeholder":j||x?.outcome==="skipped"?"blocked":x?.outcome==="failed"?"broken":"spec",D=k===null?void 0:xc(k),E=j?pf(k):x?.reason,U=j?"testid":x?.outcome==="skipped"?Os(x.reason):void 0;return{id:u,file:p,state:v,...D?{mutates:D.mutates,...D.declared?{}:{undeclared:!0}}:{},...k!==null&&gc(k).length>0?{unguardedWaits:gc(k)}:{},...v==="blocked"||v==="broken"?{...E?{reason:E}:{},...U?{blockedBy:U}:{}}:{}}})}function nr(e,t){let n=hn(e)?.captureDir??tr,o=Jo(n)?Zo(n,`${t}.spec.ts`):er(e,n,`${t}.spec.ts`);try{return Bs(o,"utf8")}catch{return null}}function $c(e,t){let n=hn(e)?.captureDir??tr;return Ms(Jo(n)?Zo(n,`${t}.spec.ts`):er(e,n,`${t}.spec.ts`))}function uf(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 a=s[1].trim();if(!a||/^(CAPTURE-[A-Z]+:|TODO\b|NOTE\b|Grounding\b|\d+\.\s)/.test(a)||(o.push(a),o.join(" ").length>400))break}return o.join(" ")}function xc(e){let t=e.split(/\r?\n/),n=t.findIndex(u=>/^\s*\/\/\s*CAPTURE-SAFETY:\s*(readonly|mutates)\b/i.test(u)),o=n>=0?/^\s*\/\/\s*CAPTURE-SAFETY:\s*(readonly|mutates)\b[\s—:–-]*(.*)$/i.exec(t[n]):null;if(o){let u=uf(t,n,o[2]??"");return{mutates:o[1].toLowerCase()==="mutates",declared:!0,what:u||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),a=/\.fill\(/.test(e);return{mutates:r||a&&s,declared:!1}}function df(e){return/(^|\n)\s*test\.skip\s*\(\s*['"`]/.test(e)}function pf(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 gc(e){let t=r=>{if(/^\s*\*/.test(r))return"";let s=/(?<!:)\/\//.exec(r);return s?r.slice(0,s.index):r},n=[],o=e.split(/\r?\n/).map(t);for(let[r,s]of o.entries()){if(!/\.waitFor\s*\(/.test(s))continue;let a=s;for(let u=r+1;u<o.length&&!/;\s*$/.test(a.trim())&&u<r+4;u++)a+=o[u];/\.catch\s*\(/.test(a)||n.push(r+1)}return n}function vc(e){return(e??"").trim().replace(/[.\s]+$/,"")}function Cc(e,t){let n=hn(e)?.captureDir??tr,o=Jo(n)?Zo(n,`${t}.spec.ts`):er(e,n,`${t}.spec.ts`);try{return xc(Bs(o,"utf8"))}catch{return{mutates:!1,declared:!1}}}function or(e){return[...new Set(e.filter(t=>t.state==="captured").map(t=>t.file))].sort()}var hf={placeholder:"\u25CB",spec:"\u25D0",blocked:"\u2298",broken:"\u2717",captured:"\u25CF"},ff={placeholder:O.gray,spec:O.yellow,blocked:O.cyan,broken:O.red,captured:O.green},Rc=` ${O.green("\u25CF captured")} ${O.yellow("\u25D0 ready")} ${O.cyan("\u2298 blocked")} ${O.red("\u2717 broken")} ${O.gray("\u25CB to spec")}`;function st(e,t=n=>n){return`${t(e)} `}function mf(e){let t=e.replace(/\s+/g," ").trim().replace(/^Prerequisite not met:\s*/i,""),n=/^(.*?[a-z0-9)"'”’])\.(?:\s|$)/i.exec(t);return(n?n[1]:t).trim()}function Hs(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=mf(o),a=`${r} ${s.toLowerCase()}`,u=t.get(a)??{reason:s,blockedBy:r,ids:[]};t.has(a)||t.set(a,u),u.ids.push(n.id)}return[...t.values()].sort((n,o)=>o.ids.length-n.ids.length||n.reason.localeCompare(o.reason))}function Sc(e){let t=Hs(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((u,p)=>u+p.ids.length,0);r.push(` ${O.bold("Stage this data")} ${O.gray(`\u2014 unblocks ${s} shot${s===1?"":"s"} in ${n.length} action${n.length===1?"":"s"}`)}`);let a=8;for(let u of n.slice(0,a)){let p=qn(u.reason,86);r.push(` ${O.cyan(yt(`${u.ids.length}\xD7`,4))} ${p[0]??""}`);for(let k of p.slice(1))r.push(` ${k}`);let b=u.ids.slice(0,4).join(" \xB7 ");r.push(O.gray(` ${b}${u.ids.length>4?` \xB7 +${u.ids.length-4} more`:""}`))}n.length>a&&r.push(O.gray(` \u2026 ${n.length-a} more staging action${n.length-a===1?"":"s"} \u2014 /screenshot list --detail`))}if(o.length>0){let s=o.reduce((a,u)=>a+u.ids.length,0);r.push(` ${st("\u2298",O.cyan)}${s} shot${s===1?"":"s"} need${s===1?"s":""} a data-testid from your developers \u2014 ${O.bold("/screenshot checklist")} builds the hand-off.`)}return r}function Pc(e){let t=e.filter(o=>(o.unguardedWaits?.length??0)>0);if(t.length===0)return[];let n=t.reduce((o,r)=>o+(r.unguardedWaits?.length??0),0);return["",` ${st("\u26A0",O.yellow)}${t.length} spec${t.length===1?"":"s"} ${t.length===1?"has":"have"} ${n} unguarded wait${n===1?"":"s"}`+O.gray(" \u2014 on missing data these fail with a stack trace instead of telling you what to stage"),O.gray(` ${t.slice(0,6).map(o=>`${o.id}:${o.unguardedWaits.join(",")}`).join(" \xB7 ")}${t.length>6?` \xB7 +${t.length-6} more`:""}`),O.gray(` Re-author to guard them: ${O.bold("/screenshot author <id>")}`)]}function Tc(e){let t=e.filter(o=>o.undeclared);if(t.length===0)return[];let n=t.filter(o=>o.mutates);return["",` ${st("\u26A0",O.yellow)}${t.length} spec${t.length===1?"":"s"} carr${t.length===1?"ies":"y"} no CAPTURE-SAFETY declaration`+(n.length>0?O.gray(` \u2014 ${n.length} of them read as "writes real data" by heuristic, so bulk capture benches ${n.length===1?"it":"them"}`):""),O.gray(` ${t.slice(0,6).map(o=>o.id).join(" \xB7 ")}${t.length>6?` \xB7 +${t.length-6} more`:""}`),O.gray(` Re-author them to declare it: ${O.bold("/screenshot author <id>")}`)]}var Xo=(e,t)=>e.length>=t?e:e+" ".repeat(t-e.length),yt=(e,t)=>e.length>=t?e:" ".repeat(t-e.length)+e;function Dc(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 gf=new Set(["and","or","of","the","to","a","an","in","on","for","with","vs"]),yf=new Set(["ai","api","cli","ui","ux","url","id","http","https","json","xml","sdk","csv","pdf","oauth","sso","mfa","io","faq"]);function wf(e){return e.replace(/[-_]+/g," ").trim().split(/\s+/).filter(Boolean).map((n,o)=>{let r=n.toLowerCase();return yf.has(r)?r.toUpperCase():o>0&&gf.has(r)?r:r.charAt(0).toUpperCase()+r.slice(1)}).join(" ")}function Us(e){if(!e)return{num:"",name:"(docs root)"};let t=/^(\d+)[-_](.+)$/.exec(e);return{num:t?t[1]:"",name:wf(t?t[2]:e)}}function kf(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).pop()??e}function yc(e,t,n){let o=t>0?Math.round(e/t*n):0;return O.green("\u2588".repeat(o))+O.gray("\u2591".repeat(Math.max(0,n-o)))}function bf(e,t){let n=t>0?Math.round(e/t*100):0,o=yt(`${n}%`,4);return n===100?O.green(o):n>0?O.yellow(o):O.gray(o)}function Ac(e,t){let n=new Map;for(let o of e){let r=Dc(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 $f(e,t){let n=(L,G)=>L.filter(H=>H.state===G).length,o=e.length,r=n(e,"captured"),s=n(e,"spec"),a=n(e,"blocked"),u=n(e,"broken"),p=n(e,"placeholder"),b=new Set(e.map(L=>L.file)).size,k=Ac(e,t),$=[];$.push(` ${O.bold("Screenshots")} ${O.green(`${r}/${o} captured`)} ${O.gray("\xB7")} ${s>0?O.yellow(`${s} ready`):O.gray("0 ready")}`+(a>0?` ${O.gray("\xB7")} ${O.cyan(`${a} blocked`)}`:"")+(u>0?` ${O.gray("\xB7")} ${O.red(`${u} broken`)}`:"")+` ${O.gray("\xB7")} ${p>0?O.red(`${p} to spec`):O.gray("0 to spec")} `+O.gray(`across ${b} article${b===1?"":"s"}`));let x=o>0?Math.round(r/o*100):0;$.push(` [${yc(r,o,32)}] ${O.bold(`${x}%`)}`),$.push("");let j=k.map(([L])=>Us(L)),v=Math.min(32,Math.max(7,...j.map(L=>L.name.length))),D=L=>L.length>v?`${L.slice(0,v-1)}\u2026`:Xo(L,v),E=[{head:"Ready",w:5,state:"spec",color:O.yellow},...a>0?[{head:"Blocked",w:7,state:"blocked",color:O.cyan}]:[],...u>0?[{head:"Broken",w:6,state:"broken",color:O.red}]:[],{head:"To spec",w:7,state:"placeholder",color:O.red}];$.push(O.gray(` ${Xo("#",2)} ${Xo("Chapter",v)} ${yt("Captured",8)} ${E.map(L=>yt(L.head,L.w)).join(" ")} Progress`));for(let[L,[,G]]of k.entries()){let H=n(G,"captured"),se=G.length,{num:qe,name:fe}=j[L],Xe=H===se,me=D(fe),Qe=E.map(be=>{let He=n(G,be.state);return He>0?be.color(yt(String(He),be.w)):O.gray(yt("\u2014",be.w))}).join(" ");$.push(` ${O.cyan(Xo(qe,2))} ${Xe?O.green(me):H>0?me:O.gray(me)} ${Xe?O.green(yt(`${H}/${se}`,8)):yt(`${H}/${se}`,8)} ${Qe} ${yc(H,se,10)} ${bf(H,se)}`)}$.push("");let U=u>0?` ${O.gray("\xB7")} ${u} spec${u===1?"":"s"} broken \u2014 ${O.bold(`/screenshot ${e.find(L=>L.state==="broken").id}`)} re-authors ${u===1?"it":"the first"}`:"";if(p>0)$.push(` ${st("\u2192",O.yellow)}${p} placeholder${p===1?"":"s"} still need a spec \u2014 run ${O.bold("/screenshot author --all")}${U}`);else if(s>0){let L=e.filter(H=>H.state==="spec"&&H.mutates).length,G=L>0?O.gray(` \u2014 ${s-L} in one go; ${L} write${L===1?"s":""} real data and run${L===1?"s":""} one at a time`):"";$.push(` ${st("\u2192",O.yellow)}${s} spec${s===1?"":"s"} ready to capture \u2014 run ${O.bold("/screenshot capture")}${G}${U}`)}else a>0?$.push(` ${st("\u2192",O.cyan)}${a} shot${a===1?"":"s"} blocked \u2014 stage the data below, then ${O.bold("/screenshot capture --all --retry-blocked")}${U}`):u>0?$.push(` ${st("\u2192",O.red)}${u} spec${u===1?"":"s"} broken \u2014 ${O.bold(`/screenshot ${e.find(L=>L.state==="broken").id}`)} re-authors ${u===1?"it":"the first"} (re-capturing fails the same way)`):$.push(` ${st("\u2713",O.green)}all ${o} captured \u2014 ${O.bold("/publish")} embeds them in the articles`);if(r>0&&r<o){let L=k.filter(([,G])=>G.every(H=>H.state!=="captured")).map(([G])=>{let{num:H,name:se}=Us(G);return H?`${H} ${se}`:se});L.length>0&&$.push(O.gray(` Furthest behind: ${L.slice(0,5).join(" \xB7 ")}${L.length>5?" \u2026":""} (0% captured)`))}return $.push(...Sc(e),...Pc(e),...Tc(e)),$.push(""),$.push(Rc),$.push(O.gray(" Drill in: /screenshot list <chapter#> \xB7 /screenshot list --detail (all)")),$}function xf(e,t,n){let o=new Set(e.map(a=>a.file)),r=e.filter(a=>a.state==="captured").length,s=[` ${O.bold("Screenshots")}: ${e.length} placeholder${e.length===1?"":"s"} across ${o.size} article${o.size===1?"":"s"} \xB7 ${O.green(`${r} captured`)}${n?O.gray(` \xB7 scope ${n}`):""}`,""];for(let[a,u]of Ac(e,t)){let p=u.filter(j=>j.state==="captured").length,{num:b,name:k}=Us(a),$=b?`${b} \xB7 ${k}`:k;s.push(` ${O.bold($)} ${O.gray(`(${p}/${u.length})`)}`);let x=new Map;for(let j of u){let v=kf(j.file),D=x.get(v)??[];x.has(v)||x.set(v,D),D.push(j)}for(let j of[...x.keys()].sort()){s.push(O.gray(` ${j}`));for(let v of x.get(j)){let D=ff[v.state];if(s.push(` ${st(hf[v.state],D)}${D(v.id)}`),(v.state==="blocked"||v.state==="broken")&&v.reason)for(let E of qn(v.reason,84))s.push(O.gray(` ${E}`))}}}return s.push(...Sc(e),...Pc(e),...Tc(e)),s.push("",Rc),s}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??qs;return t?.detail||n?xf(e,o,n):$f(e,o)}function Vs(e,t){if(!t||!/^\d+$/.test(t))return t;let n=hn(e)?.docsDir??qs,o=String(Number(t));for(let{file:r}of kc(e)){let s=Dc(r,n),a=/^(\d+)/.exec(s);if(a&&String(Number(a[1]))===o)return s}return t}function vf(e){let t=e.replace(/\\/g,"/").split("/").filter(Boolean),n=t.pop()??e;return{category:t.pop()??"(docs root)",article:n}}function Qo(e,t,n){let o=new Map;for(let s of t){let{category:a,article:u}=vf(s.file),p=o.get(a)??new Map;o.set(a,p);let b=p.get(u)??[];p.set(u,b),b.push(s)}let r=s=>n==="author"||!s.mutates;for(let s of[...o.keys()].sort()){let a=o.get(s),u=[...a.values()].flat().filter(r).map(p=>p.id);u.length>0&&e.push({kind:"category",action:n,label:`${s} (${u.length})`,ids:u,depth:1});for(let p of[...a.keys()].sort()){let b=a.get(p),k=b.filter(r).map($=>$.id);k.length>0&&e.push({kind:"article",action:n,label:`${p} (${k.length})`,ids:k,depth:2});for(let $ of b){let x=n==="capture"&&$.mutates?" \u26A0 creates real data \u2014 runs only alone":void 0;e.push({kind:"shot",action:n,label:$.id,ids:[$.id],depth:3,...x?{note:x}:{}})}}}}function wc(e,t=58){if(!e)return"";let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n}function Gs(e,t,n){let o=t.filter(r=>!r.mutates);o.length>1&&e.push({kind:"all",action:"capture",label:`Retry ${o.length} blocked shots (stage the data first)`,ids:o.map(r=>r.id),depth:0});for(let r of[...t].sort((s,a)=>s.id.localeCompare(a.id)))e.push({kind:"shot",action:"capture",label:r.id,ids:[r.id],depth:1,note:` \u2298 ${wc(r.reason)}`});n.length>1&&e.push({kind:"all",action:"author",label:`Re-author ${n.length} broken specs`,ids:n.map(r=>r.id),depth:0});for(let r of[...n].sort((s,a)=>s.id.localeCompare(a.id)))e.push({kind:"shot",action:"author",label:r.id,ids:[r.id],depth:1,note:` \u2717 ${wc(r.reason)} \u2014 re-authors`})}function Ec(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}),Qo(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}),Qo(o,n,"capture"),Gs(o,e.filter(s=>s.state==="blocked"),e.filter(s=>s.state==="broken")),o}var Ws=["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 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.","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(`
|
|
316
|
+
`),Fs="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 jc(e,t){let n=e.paths.filter(o=>t?.get(o));return["Run the emit-screenshot-spec skill to author the document360-capture spec for EACH of these","SCREENSHOT placeholder ids:",e.paths.map(o=>`- ${o}`).join(`
|
|
317
317
|
`),"",...n.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).",...n.map(o=>`- ${o}: ${t.get(o).replace(/\s+/g," ").trim()}`),""]:[],"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.",Ws,Fs].join(`
|
|
318
|
-
`)}async function sr(e,t,n){let o=
|
|
318
|
+
`)}async function sr(e,t,n){let o=Hn(e);if(o.mode==="list"){let u=t?.cwd??process.cwd(),p=Vs(u,o.scope),b=hn(u)?.docsDir??qs,k=We(u,p);for(let $ of rr(k,{scope:p,detail:o.detail,docsDir:b}))console.log($);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.",Ws,Fs,...n?.lastFailure?["","REPAIR \u2014 the existing spec FAILED its last capture with:",n.lastFailure,'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."]:[]].join(`
|
|
319
319
|
`),display:`/screenshot ${o.id}`};if(o.mode==="capture"||o.mode==="checklist")return{kind:"continue"};let s=[`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-SETUP.md.":""} Report specs written, TODO data-testids, and data to stage.`,Ws,Fs].join(`
|
|
320
|
-
`),a=o.mode==="scope"?`/screenshot ${o.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:s,display:a}}var
|
|
321
|
-
`)}var
|
|
322
|
-
`)}function
|
|
323
|
-
`),display:"/audit"}}
|
|
324
|
-
`)}async function
|
|
320
|
+
`),a=o.mode==="scope"?`/screenshot ${o.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:s,display:a}}var Vn=3;function Ys(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(`
|
|
321
|
+
`)}var Nc={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function zs(e){return e.filter(t=>t.path!==null&&t.status in Nc&&!t.link).map(t=>({path:t.path,label:Nc[t.status]}))}function ar(e){let t=zs(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 lr(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 cr(e){return e.filter(t=>t.link).length}function Ks(e,t){try{let n=Ef(e,jf(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=Nf(Cf(Rf(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 If(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 Mc(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("/"),a=o.get(s);a?a.push(r):o.set(s,[r])}for(let r of[...o.keys()].sort()){let s=o.get(r).sort((a,u)=>a.path.localeCompare(u.path));n.push({kind:"category",label:`${If(r)} (${s.length})`,paths:s.map(a=>a.path),indent:!1});for(let a of s){let u=a.path.replace(/\\/g,"/").split("/").pop()??a.path;n.push({kind:"article",label:u,paths:[a.path],indent:!0,note:a.label})}}for(let r of[...t].sort((s,a)=>s.path.localeCompare(a.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 Gn(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(`
|
|
322
|
+
`)}function Xs(e,t,n){let o=x=>t[x.index]?.paths.length??0,r=e.filter(x=>x.ok),s=e.filter(x=>!x.ok),a=e.reduce((x,j)=>x+o(j),0),u=r.reduce((x,j)=>x+o(j),0),p=n==="api"?`${Pe(e.reduce((x,j)=>x+j.costUsd,0))} total`:gt(e.reduce((x,j)=>x+j.outputTokens,0)),b=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,k=x=>`${x} article${x===1?"":"s"}`,$=[];if(s.length===0)$.push(`Published ${k(a)} (${b}) successfully \xB7 ${p}.`),$.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{$.push(`Published ${u}/${k(a)} (${b}) \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 x of s)$.push(` \u2717 ${x.label}${x.error?` \u2014 ${x.error}`:""}`)}return $}async function wt(e,t){let{model:n}=Df(e.cwd,"standard"),o=async(r,s)=>{let a=Pf(r);console.log(m(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 ${a.length} partition${a.length===1?"":"s"} (\u2264${Vn} agents at once) on ${n}\u2026`)),s||console.log(m(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let u=!1;for await(let p of Af({cwd:e.cwd,partitions:a,promptFor:b=>Gn(b.paths),concurrency:Vn,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:n}))if(p.type==="partition_status")p.status==="running"?console.log(m(` \u25B8 ${p.label} \u2014 publishing\u2026`)):p.status==="done"?console.log(_(` \u2713 ${p.label}`)):console.log(S(` \u2717 ${p.label}`));else if(p.type==="run_done"){u=p.aborted,console.log("");let b=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let $ of Xs(p.results,a,b))console.log(p.ok?_($):B($));let k=Ks(e.cwd,e.profileName);k&&console.log(m(k));try{let $=Oc(await Ic({cwd:e.cwd,profileName:e.profileName}));$&&console.log(m($))}catch{}try{let $=Lc(await _c({cwd:e.cwd,profileName:e.profileName}));$&&console.log(m($))}catch{}}return u};try{if(!await o(t,!1)){let s=await Qs(e.cwd,e.profileName,t);s.length>0&&await o(s,!0)}}catch(r){console.log(S(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function ur(e,t,n){let o=Tf(e,n);if(o.length===0)return[];let r=new Set(zs((await ir({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function Qs(e,t,n){try{let o=new Set(n),r=await ir({cwd:e,profileName:t});return zs(r.entries).map(s=>s.path).filter(s=>o.has(s))}catch{return[]}}async function Uc(e,t){let n=Ue(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(S(n.reason)),{kind:"continue"};let o=e[0];if(e.includes("--screenshots")||e.includes("--shots")){let r=t?.cwd??process.cwd(),s=or(We(r));return s.length===0?(console.log(m("No captured screenshots yet \u2014 /screenshot capture first.")),{kind:"continue"}):t?await wt(t,s):{kind:"forward-to-agent",prompt:Gn(s),display:"/publish --screenshots"}}if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await ur(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return r.length===0?(console.log(_("\u2713 All related articles are already published.")),{kind:"continue"}):await wt(t,r)}if(o==="--all"){console.log(m("Checking what needs publishing\u2026"));try{let r=await ir({cwd:t?.cwd??process.cwd()}),{clean:s,conflicts:a}=ar(r.entries),u=cr(r.entries),p=e.includes("--force")&&a.length>0;u>0&&console.log(B(`\u26A0 ${u} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),a.length>0&&!p&&console.log(B(lr(a.length)));let b=p?[...s,...a]:s;if(b.length===0){if(a.length>0)return console.log(m("Resolve the conflicts: /resolve")),{kind:"continue"};if(console.log(_(u>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),t)try{let k=Oc(await Ic({cwd:t.cwd,profileName:t.profileName}));k&&console.log(m(k));let $=Lc(await _c({cwd:t.cwd,profileName:t.profileName}));$&&console.log(m($))}catch{}return{kind:"continue"}}return t?await wt(t,b.map(k=>k.path)):{kind:"forward-to-agent",prompt:Gn(b.map(k=>k.path)),display:"/publish --all"}}catch(r){return console.log(S(`Could not compute sync status: ${r.message}`)),{kind:"continue"}}}if(o&&o.startsWith("--")&&(o=e.find(r=>!r.startsWith("--"))??""),!o){console.log(m("Checking what needs publishing\u2026"));let r;try{let s=await ir({cwd:t?.cwd??process.cwd()}),{clean:a,conflicts:u}=ar(s.entries);r=a;let p=cr(s.entries);if(p>0&&console.log(B(`\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.`)),u.length>0&&console.log(B(lr(u.length))),r.length===0&&u.length>0)return console.log(m("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(s){return console.log(S(`Could not compute sync status: ${s.message}`)),console.log(m("Publish a specific article: /publish <article-path>")),{kind:"continue"}}if(r.length===0)return console.log(_("\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),console.log(m(" (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} ${m(`(${s.label})`)}`);return console.log(m("Run: /publish <article-path>")),{kind:"continue"}}try{o=await t.withPausedInput(()=>Sf({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(m("Cancelled.")),{kind:"continue"}}if(o==="--all")return await wt(t,r.map(s=>s.path))}return{kind:"forward-to-agent",prompt:Ys(o),display:`/publish ${o}`}}async function Yn(){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 and report if any article is in conflict or remote-ahead (the local copy cannot be trusted until resolved).","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(`
|
|
323
|
+
`),display:"/audit"}}z();import{readProjectConfig as Of}from"document360-engine";function Js(){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(`
|
|
324
|
+
`)}async function Wc(e,t){let n=t?.cwd??process.cwd();return Of(n)?{kind:"forward-to-agent",prompt:Js(),display:"/discover"}:(console.log(S("No d360-writer config here. Run /init first.")),{kind:"continue"})}z();import{checkbox as _f}from"@inquirer/prompts";import{inventoryRepo as Lf,readProjectConfig as Fc,writeProjectConfig as Mf}from"document360-engine";function Zs(e,t){let n=Fc(e);n&&(n.authoritativeSourceFiles=t,Mf(n,e))}function dr(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 Bc(e,t){let n=t?.cwd??process.cwd();if(!Fc(n))return console.log(S("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=Lf(n);if(o.length===0)return console.log(m('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} ${m(dr(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>_f({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${dr(s)})`,value:s.path,checked:s.recommended})),pageSize:20}))}catch{return console.log(m("Cancelled.")),{kind:"continue"}}if(r.length===0)return console.log(m("Nothing selected \u2014 scope unchanged.")),{kind:"continue"};Zs(n,r),console.log(_(`\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"}}z();import{confirm as zf}from"@inquirer/prompts";import{applyPull as ni,computeSyncStatus as Qc,compareRemoteSources as Kf,planPull as Jc,planImport as Xf,applyImport as Qf,establishBaselines as Jf,rebaselineServerMeta as Zf,D360AuthError as em}from"document360-engine";z();var qc=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /publish <path>):",paint:S,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /publish <path>:",paint:B,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:S,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:S,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint:ue,mark:"X"},{status:"untracked-local",header:"New here \u2014 not on Document360 yet (publish to add them):",paint:m,mark:"?"},{status:"untracked-remote",header:"On Document360 \u2014 not in your local docs yet (run /pull to import them):",paint:m,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:ue,mark:"\xB7"}];function Uf(e){return e.path?e.path:`${e.title??"(untitled)"} ${ue(`[${e.articleId}]`)}`}function Wf(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 pr(e,t){let n=[],o=e.entries.filter(k=>k.link);if(o.length>0){n.push(""),n.push(Se("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let k of o)n.push(` ${B("~")} ${B(k.path??"")} ${ue(`\u2192 "${k.link.title}"`)}`)}for(let k of qc){let $=e.entries.filter(x=>x.status===k.status&&!(k.status==="untracked-local"&&x.link));if($.length!==0){n.push(""),n.push(Se(k.header));for(let x of $)n.push(` ${k.paint(k.mark)} ${k.paint(Uf(x))}${x.detail?ue(` (${x.detail})`):""}`)}}let r=e.counts["in-sync"]??0,s=e.entries.length;n.push("");let a={"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"},u=o.length,p=s===r?_("\u2713 everything up to date"):[r>0?_(`\u2713 ${r} up to date`):null,u>0?`${u} to link`:null,...qc.map(k=>{let $=(e.counts[k.status]??0)-(k.status==="untracked-local"?u:0);return $>0?`${$} ${a[k.status]}`:null})].filter(Boolean).join(ue(" \xB7 ")),b=t!==void 0?` \xB7 synced in ${Wf(t)}`:"";return n.push(p+ue(` \xB7 ${s} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${b}`)),n}import{structuredPatch as Ff}from"diff";import Hc from"picocolors";var Vc=80,Bf="\x1B[48;2;74;28;28m",qf="\x1B[48;2;24;66;24m",Gc="\x1B[49m",ei=e=>String(e).padStart(5);function Yc(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}function zc(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 it(e,t,n){let o=x=>{let j=x.replace(/\r\n/g,`
|
|
325
325
|
`);return j.endsWith(`
|
|
326
326
|
`)||j===""?j:j+`
|
|
327
|
-
`},r=o(e),s=o(t);if(r===s)return null;let a=Math.max(20,n-10),u=_f("a","b",r,s,"","",{context:3}),h=0,k=0,b=[];u.hunks.forEach(($,j)=>{j>0&&b.push(ql.gray(" \u2026"));let v=$.oldStart,T=$.newStart,E=[],U=[],L=()=>{for(let V=0;V<E.length;V++){let H=V<U.length?Gl(E[V],U[V]):void 0;k++,b.push(`${Of}${ti(v++)} - ${Yl(E[V],a,H)}${Vl}`)}for(let V=0;V<U.length;V++){let H=V<E.length?Gl(E[V],U[V]):void 0;h++,b.push(`${Lf}${ti(T++)} + ${Yl(U[V],a,H)}${Vl}`)}E=[],U=[]};for(let V of $.lines){let H=V[0],re=V.slice(1);H==="-"?E.push(re):H==="+"?U.push(re):(L(),b.push(ql.gray(ti(T))+" "+re.slice(0,a)),v++,T++)}L()});let x=b.slice(0,Hl);return{added:h,removed:k,lines:x,hidden:Math.max(0,b.length-Hl)}}Y();import{select as Mf}from"@inquirer/prompts";import{applyPull as Uf,computeSyncStatus as Wf,planPull as Ff}from"document360-engine";var zl=e=>e===1?"":"s";async function ni(e,t){console.log(""),console.log(`${W("\u25CF")} ${Re(t.title)} ${ue(`(${t.path})`)}`);for(let r of t.notes)console.log(B(` \u26A0 ${r}`));let n=rt(t.oldContent,t.newContent,Math.max(40,(process.stdout.columns??80)-1));if(n){console.log(ue(` \u23BF local \u2192 portal: +${n.added} / -${n.removed} line${zl(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(()=>Mf({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"?(Uf({cwd:e.cwd,profileName:e.profileName},t),console.log(O(" \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 Kl(e,t){let n=Me(t.cwd,t.profileName);if(!n.ok)return console.log(S(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let s=(await Wf({cwd:t.cwd,profileName:t.profileName})).entries.filter(u=>u.status==="conflict"&&u.path).map(u=>u.path);if(o){if(!s.includes(o))return console.log(O(`${o} isn't in conflict \u2014 nothing to resolve.`)),{kind:"continue"};s=[o]}if(s.length===0)return console.log(O("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let a=[];for(let u of s){let h=await Ff({cwd:t.cwd,profileName:t.profileName,relPath:u});await ni(t,h)==="keep-local"&&a.push(u)}if(a.length>0)return console.log(g(`Publishing ${a.length} kept-local article${zl(a.length)} over the portal\u2026`)),await gt(t,a)}catch(r){console.log(S(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function Jl(e,t){let n=Me(t.cwd,t.profileName);if(!n.ok)return console.log(S(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await Kf(t),{kind:"continue"};if(o==="--baseline")return await Xf(t,e.filter(a=>a!=="--baseline")),{kind:"continue"};if(o==="--compare")return await Qf(t),{kind:"continue"};if(o)return console.log(S(`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 Jf(t,r),{kind:"continue"};console.log(g("Pulling changes from Document360\u2026"));let s=await ri({cwd:t.cwd,profileName:t.profileName});for(let a of si(s))console.log(a.tone==="ok"?O(a.text):a.tone==="warn"?B(a.text):g(a.text));console.log("")}catch(r){r instanceof zf?console.log(S(r.message)):console.log(S(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function ri(e){let t=await Xl({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 Ql({cwd:e.cwd,profileName:e.profileName,relPath:o.path});oi({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 Hf({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});Vf({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 hr=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,It=e=>e===1?"":"s";function si(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${It(e.pulled.length)} into local: ${hr(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${It(e.imported.length)}: ${hr(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${It(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${It(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). (${hr(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${It(e.failed.length)} failed: ${hr(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 Kf(e){console.log(g("Checking Document360 for drift\u2026"));let t=Date.now(),n=await Xl({cwd:e.cwd,profileName:e.profileName});for(let o of pr(n,Date.now()-t))console.log(o);console.log("")}async function Xf(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 Gf({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await Yf({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(O("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(O(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(O(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(B(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(g(` - ${s.path} (${s.reason})`))}}async function Qf(e){console.log(g("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await qf({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${Re(String(t.legacyCount))} \xB7 Manifest: ${Re(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(O("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(S(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(B(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(B(` ${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 Jf(e,t){let n=t.replace(/\\/g,"/"),o=await Ql({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await ni(e,o)==="keep-local"&&(console.log(g(`Publishing ${o.path} over the portal\u2026`)),await gt(e,[o.path]));return}console.log(""),console.log(`${W("\u25CF")} ${Re(o.title)} ${ue(`(${o.path})`)}`);for(let a of o.notes)console.log(B(` \u26A0 ${a}`));let r=rt(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.")),oi({cwd:e.cwd,profileName:e.profileName},o);return}console.log(ue(` \u23BF Added ${r.added} line${It(r.added)}, removed ${r.removed} line${It(r.removed)}`));for(let a of r.lines)console.log(a);if(r.hidden>0&&console.log(g(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>Bf({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(g(" Skipped."));return}oi({cwd:e.cwd,profileName:e.profileName},o),console.log(O(` \u2713 Pulled ${o.path} (sync base advanced).`))}Y();import{statSync as Zf}from"node:fs";import{resolve as em}from"node:path";import{estimateBulkCost as tm,planPartitions as nm,readProjectConfig as om,resolveModelForOperation as rm,runPartitioned as sm,trackedArticlePaths as im}from"document360-engine";var ii=3;function ai(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 ci(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function li(e,t){return t.map(n=>{let o=0;try{o=Zf(em(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function ui(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:
|
|
327
|
+
`},r=o(e),s=o(t);if(r===s)return null;let a=Math.max(20,n-10),u=Ff("a","b",r,s,"","",{context:3}),p=0,b=0,k=[];u.hunks.forEach((x,j)=>{j>0&&k.push(Hc.gray(" \u2026"));let v=x.oldStart,D=x.newStart,E=[],U=[],L=()=>{for(let G=0;G<E.length;G++){let H=G<U.length?Yc(E[G],U[G]):void 0;b++,k.push(`${Bf}${ei(v++)} - ${zc(E[G],a,H)}${Gc}`)}for(let G=0;G<U.length;G++){let H=G<E.length?Yc(E[G],U[G]):void 0;p++,k.push(`${qf}${ei(D++)} + ${zc(U[G],a,H)}${Gc}`)}E=[],U=[]};for(let G of x.lines){let H=G[0],se=G.slice(1);H==="-"?E.push(se):H==="+"?U.push(se):(L(),k.push(Hc.gray(ei(D))+" "+se.slice(0,a)),v++,D++)}L()});let $=k.slice(0,Vc);return{added:p,removed:b,lines:$,hidden:Math.max(0,k.length-Vc)}}z();import{select as Hf}from"@inquirer/prompts";import{applyPull as Vf,computeSyncStatus as Gf,planPull as Yf}from"document360-engine";var Kc=e=>e===1?"":"s";async function ti(e,t){console.log(""),console.log(`${W("\u25CF")} ${Se(t.title)} ${ue(`(${t.path})`)}`);for(let r of t.notes)console.log(B(` \u26A0 ${r}`));let n=it(t.oldContent,t.newContent,Math.max(40,(process.stdout.columns??80)-1));if(n){console.log(ue(` \u23BF local \u2192 portal: +${n.added} / -${n.removed} line${Kc(n.added+n.removed)}`));for(let r of n.lines)console.log(r);n.hidden>0&&console.log(m(` \u2026 +${n.hidden} more diff lines`))}else console.log(m(" Local already matches the portal content \u2014 resolving just advances the sync base."));let o=await e.withPausedInput(()=>Hf({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"?(Vf({cwd:e.cwd,profileName:e.profileName},t),console.log(_(" \u2713 Took the portal copy (local overwritten, sync base advanced).")),"took-portal"):o==="local"?"keep-local":(console.log(m(" Skipped \u2014 still a conflict.")),"skipped")}async function Xc(e,t){let n=Ue(t.cwd,t.profileName);if(!n.ok)return console.log(S(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let s=(await Gf({cwd:t.cwd,profileName:t.profileName})).entries.filter(u=>u.status==="conflict"&&u.path).map(u=>u.path);if(o){if(!s.includes(o))return console.log(_(`${o} isn't in conflict \u2014 nothing to resolve.`)),{kind:"continue"};s=[o]}if(s.length===0)return console.log(_("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let a=[];for(let u of s){let p=await Yf({cwd:t.cwd,profileName:t.profileName,relPath:u});await ti(t,p)==="keep-local"&&a.push(u)}if(a.length>0)return console.log(m(`Publishing ${a.length} kept-local article${Kc(a.length)} over the portal\u2026`)),await wt(t,a)}catch(r){console.log(S(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function Zc(e,t){let n=Ue(t.cwd,t.profileName);if(!n.ok)return console.log(S(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await tm(t),{kind:"continue"};if(o==="--baseline")return await nm(t,e.filter(a=>a!=="--baseline")),{kind:"continue"};if(o==="--compare")return await om(t),{kind:"continue"};if(o)return console.log(S(`Unknown option: ${o}`)),console.log(m("Usage: /pull pull portal edits + import new portal articles")),console.log(m(" /pull <path> pull one article (or resolve a conflict)")),console.log(m(" /pull --status drift report only (no writes)")),console.log(m(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await rm(t,r),{kind:"continue"};console.log(m("Pulling changes from Document360\u2026"));let s=await oi({cwd:t.cwd,profileName:t.profileName});for(let a of ri(s))console.log(a.tone==="ok"?_(a.text):a.tone==="warn"?B(a.text):m(a.text));console.log("")}catch(r){r instanceof em?console.log(S(r.message)):console.log(S(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function oi(e){let t=await Qc({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 Jc({cwd:e.cwd,profileName:e.profileName,relPath:o.path});ni({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 Xf({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});Qf({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 hr=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Lt=e=>e===1?"":"s";function ri(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${Lt(e.pulled.length)} into local: ${hr(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${Lt(e.imported.length)}: ${hr(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${Lt(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${Lt(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). (${hr(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${Lt(e.failed.length)} failed: ${hr(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 tm(e){console.log(m("Checking Document360 for drift\u2026"));let t=Date.now(),n=await Qc({cwd:e.cwd,profileName:e.profileName});for(let o of pr(n,Date.now()-t))console.log(o);console.log("")}async function nm(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(m(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await Jf({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await Zf({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(_("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(_(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(_(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(B(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(m(` - ${s.path} (${s.reason})`))}}async function om(e){console.log(m("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await Kf({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${Se(String(t.legacyCount))} \xB7 Manifest: ${Se(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(_("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(S(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(B(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(B(` ${t.onlyInManifest.length} only in the manifest: ${t.onlyInManifest.slice(0,5).join(", ")}`)),console.log(m(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function rm(e,t){let n=t.replace(/\\/g,"/"),o=await Jc({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await ti(e,o)==="keep-local"&&(console.log(m(`Publishing ${o.path} over the portal\u2026`)),await wt(e,[o.path]));return}console.log(""),console.log(`${W("\u25CF")} ${Se(o.title)} ${ue(`(${o.path})`)}`);for(let a of o.notes)console.log(B(` \u26A0 ${a}`));let r=it(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!r){console.log(m(" Local file already matches the remote content \u2014 advancing the sync base only.")),ni({cwd:e.cwd,profileName:e.profileName},o);return}console.log(ue(` \u23BF Added ${r.added} line${Lt(r.added)}, removed ${r.removed} line${Lt(r.removed)}`));for(let a of r.lines)console.log(a);if(r.hidden>0&&console.log(m(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>zf({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(m(" Skipped."));return}ni({cwd:e.cwd,profileName:e.profileName},o),console.log(_(` \u2713 Pulled ${o.path} (sync base advanced).`))}z();import{statSync as sm}from"node:fs";import{resolve as im}from"node:path";import{estimateBulkCost as am,planPartitions as lm,readProjectConfig as cm,resolveModelForOperation as um,runPartitioned as dm,trackedArticlePaths as pm}from"document360-engine";var si=3;function ii(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 ai(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function li(e,t){return t.map(n=>{let o=0;try{o=sm(im(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function ci(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:
|
|
328
328
|
- 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.
|
|
329
329
|
- 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.
|
|
330
330
|
- 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.
|
|
331
331
|
- Work only on these files:
|
|
332
332
|
`+e.paths.map(t=>`- ${t}`).join(`
|
|
333
|
-
`)}function
|
|
333
|
+
`)}function ui(e,t,n){let o=e.reduce((u,p)=>u+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(u=>` \u2022 ${u.label} \u2014 ${u.paths.length} article${u.paths.length===1?"":"s"}`),"",`Estimated cost: ${Pe(r)}\u2013${Pe(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function di(e,t,n){let o=v=>t[v.index]?.paths.length??0,r=e.filter(v=>v.ok),s=e.filter(v=>!v.ok),a=e.reduce((v,D)=>v+o(D),0),u=r.reduce((v,D)=>v+o(D),0),p=e.reduce((v,D)=>v+D.costUsd,0),b=e.reduce((v,D)=>v+D.outputTokens,0),k=n==="api"?`${Pe(p)} total`:gt(b),$=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,x=v=>`${v} article${v===1?"":"s"}`,j=[];if(s.length===0)j.push(`Converted ${x(a)} (${$}) successfully \xB7 ${k}.`);else{j.push(`Converted ${u}/${x(a)} (${$}) \xB7 ${k}.`),j.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let v of s)j.push(` \u2717 ${v.label}${v.error?` \u2014 ${v.error}`:""}`)}return j}async function eu(e,t){if(!cm(t.cwd))return console.log(S("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=ii(e),r=pm(t.cwd,t.profileName);if(r.length===0)return console.log(S("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let s=ai(r,n);if(s.length===0)return console.log(S(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let a=lm(s),u=`/convert${n?` --scope ${n}`:""} --run`,{model:p,forced:b}=um(t.cwd,"light");if(!o){let k=am({files:li(t.cwd,s),op:"convert",model:p});n&&console.log(m(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let $ of ui(a,k,si))console.log($);return console.log(m(`Model: ${p}${b?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(m(`Run ${u} to start.`)),console.log(""),{kind:"continue"}}console.log(m(`Converting ${s.length} articles across ${a.length} partitions (\u2264${si} agents at once) on ${p}\u2026`)),console.log(m(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let k of dm({cwd:t.cwd,partitions:a,promptFor:ci,concurrency:si,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:p}))if(k.type==="partition_status")k.status==="running"?console.log(m(` \u25B8 ${k.label} \u2014 converting\u2026`)):k.status==="done"?console.log(_(` \u2713 ${k.label}`)):console.log(S(` \u2717 ${k.label}`));else if(k.type==="run_done"){console.log("");let $=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let x of di(k.results,a,$))console.log(k.ok?_(x):B(x))}}catch(k){console.log(S(`Convert run failed: ${k.message}`))}return console.log(""),{kind:"continue"}}z();import{statSync as ou}from"node:fs";import{resolve as ru}from"node:path";import{estimateBulkCost as $m,lintDocs as xm,planPartitions as vm,readDocsPlan as Cm,readProjectConfig as su,DEFAULT_DOCS_DIR as Rm,resolveModelForOperation as Sm,runPartitioned as Pm,stampArticles as Tm,CONTENT_CAP_VERSION as Dm}from"document360-engine";import{readProjectConfig as hm,loadProfileMap as fm,resolveActiveProfile as mm,desiredCategoryOrder as gm,desiredArticleOrder as ym,DEFAULT_DOCS_DIR as wm}from"document360-engine";var pi=e=>e.replace(/\\/g,"/"),km=e=>pi(e).split("/").pop()??e;function bm(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}function zn(e,t){try{let n=hm(e);if(!n)return[];let o=mm(e,t),r=fm(e,o.name);if(!r)return[];let s=pi(n.docsDir??wm).replace(/\/+$/,""),a=new Map;for(let p of ym(r))a.set(p.categoryPath,(a.get(p.categoryPath)??0)+1);let u=[];for(let p of gm(r)){let b=pi(p.path),k=b.startsWith(`${s}/`)?b.slice(s.length+1):b===s?"":b;k&&u.push({token:k,label:bm(km(b)),count:a.get(p.path)??0})}return u}catch{return[]}}function tu(e,t){let n=zn(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 kt(e,t){return t.includes("--all")||t.some(n=>!n.startsWith("--"))?!1:e==="review"||e==="reorder"||e==="write"&&t.includes("--rewrite")}function fn(e,t,n,o){let r=zn(e,o);if(r.length<=1)return[];let s=n.filter(b=>b.startsWith("--")).join(" "),a=s?` ${s}`:"",u=`/${t}${a} --all`.replace(/\s+/g," "),p=b=>t==="write"?`/write --scope ${b}${a}`:`/${t} ${b}${a}`;return[`Bare /${t} covers the WHOLE knowledge base (${r.reduce((b,k)=>b+k.count,0)} articles). Pick a target:`,` ${u} (everything)`,...r.map(b=>` ${p(b.token)} (${b.label} \xB7 ${b.count} article${b.count===1?"":"s"})`)]}function fr(e){let t=e.indexOf("--scope");if(t===-1)return!1;let n=e[t+1];return n===void 0||n.startsWith("-")}function nu(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 Am=3,Em=8;function hi(e){return e===void 0||!Number.isFinite(e)?Am:Math.max(1,Math.min(Math.floor(e),Em))}function fi(e){let t,n,o=!1,r=!1,s,a=p=>{let b=Number(p);return p!==void 0&&Number.isFinite(b)?b:void 0};for(let p=0;p<e.length;p++){let b=e[p];if(b==="--preview"||b==="--dry-run")o=!0;else if(b==="--rewrite"||b==="--force")r=!0;else{if(b==="--run"||b==="--yes"||b==="--all")continue;b==="--scope"?t=e[++p]:b?.startsWith("--scope=")?t=b.slice(8):b==="--concurrency"?s=a(e[++p]):b?.startsWith("--concurrency=")?s=a(b.slice(14)):b&&!b.startsWith("--")&&(n=b)}}let u=p=>p?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:u(t),path:u(n),preview:o,concurrency:s,rewrite:r}}function jm(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function Nm(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 ou(ru(e,t,o)).size===0}catch{return!0}})}function gi(e,t,n){let o=new Map(t.map(r=>[r.path,r]));return n.map(r=>{let s=1;for(let a of o.get(r)?.sources??[])try{s+=ou(ru(e,a)).size}catch{}return{path:r,bytes:s}})}function yi(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.
|
|
334
334
|
`:"";return`Run the write-article skill to author EACH documentation article listed below. For each path:
|
|
335
335
|
- 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).
|
|
336
336
|
- 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).
|
|
@@ -340,95 +340,97 @@ ${s}${h}`).join("")}).join(`
|
|
|
340
340
|
- 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.
|
|
341
341
|
Articles:
|
|
342
342
|
`+e.paths.map(r=>`- ${r}`).join(`
|
|
343
|
-
`)}function
|
|
344
|
-
`)}var
|
|
345
|
-
`)}var
|
|
346
|
-
`)}function
|
|
343
|
+
`)}function wi(e,t,n){let o=e.reduce((a,u)=>a+u.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(a=>` \u2022 ${a.label} \u2014 ${a.paths.length} article${a.paths.length===1?"":"s"}`),"",`Estimated cost: ${Pe(r)}\u2013${Pe(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}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),a=e.reduce((v,D)=>v+o(D),0),u=r.reduce((v,D)=>v+o(D),0),p=e.reduce((v,D)=>v+D.costUsd,0),b=e.reduce((v,D)=>v+D.outputTokens,0),k=n==="api"?`${Pe(p)} total`:gt(b),$=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,x=v=>`${v} article${v===1?"":"s"}`,j=[];if(s.length===0)j.push(`Wrote ${x(a)} (${$}) successfully \xB7 ${k}.`),j.push("Next \u2014 push them to Document360:"),j.push("/publish --all"),j.push("Or add screenshots first with /screenshot author --all. Drafts are reviewable in the portal after publishing.");else{j.push(`Wrote ${u}/${x(a)} (${$}) \xB7 ${k}.`),j.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let v of s)j.push(` \u2717 ${v.label}${v.error?` \u2014 ${v.error}`:""}`)}return j}function bi(e,t,n){try{let o=xm({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 $i(e,t,n){let o=(su(e)?.docsDir??Rm).replace(/\/+$/,""),r=t.map(u=>u.path);if(n.path){let u=jm(n.path,o);return r.includes(u)?{docsDir:o,targets:[u],planCount:r.length}:{docsDir:o,targets:[],planCount:r.length,reason:`"${u}" isn't in the docs plan (.d360-writer/plan.json).`}}let s=Nm(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 a=mi(e,o,s);if(a.length===0){let u=n.scope?` under "${n.scope}"`:"",p=n.scope?` --scope ${n.scope}`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${u} are already written. Use /write <path> to rewrite one, or /write${p} --rewrite to regenerate them all.`}}return{docsDir:o,targets:a,planCount:r.length}}async function iu(e,t){if(!su(t.cwd))return console.log(S("No d360-writer config here. Run /init first.")),{kind:"continue"};if(fr(e)){for(let U of tu(t.cwd,t.profileName))console.log(m(U));return{kind:"continue"}}if(kt("write",e)){let U=fn(t.cwd,"write",e,t.profileName);if(U.length>0){for(let L of U)console.log(m(L));return{kind:"continue"}}}let n=Cm(t.cwd);if(n.length===0)return console.log(S("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:a,rewrite:u}=fi(e),{docsDir:p,targets:b,reason:k,rewriting:$}=$i(t.cwd,n,{scope:o,path:r,rewrite:u});if(b.length===0)return console.log(k?B(k):B("Nothing to write.")),{kind:"continue"};$&&console.log(B(`--rewrite: regenerating ${b.length} already-written article${b.length===1?"":"s"} (overwrites them; git has your baseline).`));let x=vm(b),j=hi(a),{model:v,forced:D}=Sm(t.cwd,"standard"),E=!!r;if(s&&!E){let U=$m({files:gi(t.cwd,n,b),op:"write",model:v});o&&console.log(m(`Scope: ${o} (${b.length} pending).`));for(let L of wi(x,U,j))console.log(L);return console.log(m(`Model: ${v}${D?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(m(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}console.log(m(`Writing ${b.length} article${b.length===1?"":"s"} across ${x.length} partition${x.length===1?"":"s"} (\u2264${j} agents at once) on ${v}\u2026`)),console.log(m(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let U of Pm({cwd:t.cwd,partitions:x,promptFor:L=>yi(L,p,{rewrite:$||E}),concurrency:j,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:v}))if(U.type==="partition_status")U.status==="running"?console.log(m(` \u25B8 ${U.label} \u2014 writing\u2026`)):U.status==="done"?console.log(_(` \u2713 ${U.label}`)):console.log(S(` \u2717 ${U.label}`));else if(U.type==="run_done"){console.log("");let L=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let H of ki(U.results,x,L))console.log(U.ok?_(H):B(H));if(U.ok)try{Tm(t.cwd,b.map(H=>`${p}/${H}`),{writtenCap:Dm})}catch{}let G=bi(t.cwd,p,b);G&&console.log(B(G))}}catch(U){console.log(S(`Write run failed: ${U.message}`))}return console.log(""),{kind:"continue"}}z();import{existsSync as Im,readdirSync as au,statSync as lu}from"node:fs";import{join as cu}from"node:path";import{inputDir as Om,readProjectConfig as _m}from"document360-engine";var uu=/\.(md|markdown|pdf|txt)$/i;function xi(e){let t=Om(e);if(!Im(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of au(t)){let s=cu(t,r),a=!1;try{a=lu(s).isDirectory()}catch{continue}if(a){if(r.startsWith("."))continue;let u=Lm(s);u>0&&n.push({name:r,docCount:u})}else uu.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function Lm(e){let t=0;for(let n of au(e))try{lu(cu(e,n)).isFile()&&uu.test(n)&&t++}catch{}return t}function vi(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(`
|
|
344
|
+
`)}var Ci="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function du(e,t){let n=t?.cwd??process.cwd();if(!_m(n))return console.log(S("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=xi(n);if(o.length===0&&r===0)return console.log(m(Ci)),{kind:"continue"};let s=e.join(" ").trim();if(!s){if(o.length>1){console.log(m("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let p of o)console.log(` ${p.name} ${m(`(${p.docCount} doc${p.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let u=o[0]?.name??"";return{kind:"forward-to-agent",prompt:mr(u),display:u?`/draft ${u}`:"/draft"}}let a=vi(o,s);return{kind:"forward-to-agent",prompt:mr(a??"",a?void 0:s),display:`/draft ${s}`}}z();import{listOpenForDocs as Mm,readProjectConfig as Um}from"document360-engine";function Ri(e){try{return Mm(e).filter(t=>t.kind==="request").length}catch{return 0}}function Si(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function Pi(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(`
|
|
345
|
+
`)}var Ti="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 pu(e,t){let n=t?.cwd??process.cwd();if(!Um(n))return console.log(S("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=Si(e);if(!r&&Ri(n)===0)return console.log(m(Ti)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:Pi(r,o),display:s}}z();import{search as Wm}from"@inquirer/prompts";import{findByName as Fm,getSession as Bm,listSessions as qm,relativeTime as fu}from"document360-engine";async function mu(e,t){let n=qm(t.cwd).filter(o=>o.uuid!==t.currentUuid());if(n.length===0)return console.log(m("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=Fm(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(S(`No session matches "${o}".`)),hu(n),{kind:"continue"})}if(!process.stdin.isTTY)return hu(n),console.log(m("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>Wm({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let a=(s??"").toLowerCase();return n.filter(u=>!a||u.name.toLowerCase().includes(a)||u.firstPrompt.toLowerCase().includes(a)).map(u=>({name:`${u.name} ${fu(u.updatedAt)}`,value:u.uuid,description:u.firstPrompt.slice(0,100)}))}})),r=Bm(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function hu(e){console.log("");for(let t of e.slice(0,15))console.log(` ${W(t.name)} ${m(fu(t.updatedAt))}`),console.log(` ${m(t.firstPrompt.slice(0,80))}`);console.log("")}z();import{renameSession as Hm}from"document360-engine";function Di(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 gu(e,t){let n=Di(e.join(" "));if(!n)return console.log(S("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(Hm(o,n)?console.log(_(`\u2713 Session renamed to "${n}"`)):console.log(S("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(_(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as yu,readProjectConfig as Vm,writeProjectConfig as Gm}from"document360-engine";z();function Ai(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=Vm(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 yu().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},Gm(o,e),null):`Unknown environment "${r}". Known: ${yu().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function wu(e,t){let n=e[0];if(!n)return Uo(t.cwd),{kind:"continue"};if(n==="add"){let o=Ai(t.cwd,e[1],e[2]);return o?(console.log(S(o)),{kind:"continue"}):(console.log(_(`\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 Wo(t.cwd,n),Fo(t.cwd,n),console.log(m(" Restarting agent for the new profile\u2026")),{kind:"clear"}}z();import{select as Ym}from"@inquirer/prompts";import{readProjectConfig as zm,readUserConfig as ku,resolveModelSetting as Ei,writeUserConfig as bu}from"document360-engine";var Ke=[{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 gr(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=Ke.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function Km(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 Kn(e,t){let n=()=>Ei(e).model;if(t==="default"){let s=ku();return s.defaultModel?(delete s.defaultModel,bu(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${Ei(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}}bu({...ku(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=zm(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 $u(e,t){let n=e[0]?.trim();if(!n){let a=Ei(t.cwd);if(!process.stdin.isTTY)return console.log(`${Se("Model:")} ${W(a.model)}${a.source==="auto"?m(" (auto)"):""}`),console.log(m(` source: ${Km(a)}`)),console.log(m(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let u=gr(a),p;try{p=await t.withPausedInput(()=>Ym({message:`Select model (current: ${a.model}${a.source==="auto"?" \xB7 auto":""})`,default:Ke[u].value,choices:Ke.map((x,j)=>({name:`${x.label}${j===u?" \u2714":""}`,value:x.value,description:x.desc}))}))}catch{return console.log(m("Cancelled.")),{kind:"continue"}}let{lines:b,changed:k,effective:$}=Kn(t.cwd,p??"default");for(let x of b)console.log(x.startsWith("\u26A0")?B(x):x.startsWith("\u2713")?_(x):m(x));return k&&await t.setModel($),{kind:"continue"}}let{lines:o,changed:r,effective:s}=Kn(t.cwd,n);for(let a of o)console.log(a.startsWith("\u26A0")?B(a):a.startsWith("\u2713")?_(a):m(a));return r&&await t.setModel(s),{kind:"continue"}}wr();async function Du(e,t){return await t.withPausedInput(()=>rn(t.cwd)),{kind:"clear"}}async function Au(e,t){return await t.withPausedInput(()=>Oo(t.cwd,t.profileName)),{kind:"clear"}}z();import{resolveActiveProfile as yg}from"document360-engine";async function Eu(e,t){let n=!1;try{n=yg(t.cwd).production}catch{}return n?(console.log(B("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(m("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}z();var ju=async(e,t)=>{try{await t.withPausedInput(()=>Mo({}))}catch(n){console.log(S(`Login failed: ${n.message}`))}return{kind:"continue"}};z();import{resolveActiveProfile as wg,clearTokens as kg,clearProfileProject as bg}from"document360-engine";async function Nu(e,t){let n;try{n=wg(t.cwd,t.profileName).name}catch(r){return console.log(S(r.message)),{kind:"continue"}}let o=kg(n);return bg(t.cwd,n),console.log(o?_(`\u2713 Signed out of "${n}" and cleared its project/workspace selection.`):m(`Profile "${n}" was not signed in. Cleared any project/workspace selection.`)),console.log(m("Run /login to sign in and pick a project.")),{kind:"continue"}}import{spawn as Iu}from"node:child_process";import{existsSync as _i,readFileSync as Oi,statSync as $g}from"node:fs";import{homedir as xg}from"node:os";import{basename as vg,isAbsolute as Cg,join as mn,resolve as Rg}from"node:path";import{readProjectConfig as Sg,DEFAULT_OUTPUT_DIR as Pg}from"document360-engine";var Tg=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Li(e){let t=e.find(o=>!o.startsWith("--")),n=e.includes("--retry-blocked");return e.includes("--failed")?{mode:"failed"}:e.includes("--all")?{mode:"all",retryBlocked:n}:t?/[\\/]/.test(t)||t.endsWith(".md")?{mode:"scope",scope:Tg(t),retryBlocked:n}:{mode:"single",id:t}:{mode:"picker"}}function kr(e,t){let n=We(e,t),o=r=>n.filter(s=>s.state===r).map(s=>s.id);return{ready:o("spec"),captured:o("captured"),blocked:o("blocked"),broken:o("broken"),rows:n}}function Ou(e){let t=e.filter(s=>s.state==="spec"),n=e.filter(s=>s.state==="captured"),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}),Qo(o,t,"capture"),Gs(o,e.filter(s=>s.state==="blocked"),e.filter(s=>s.state==="broken"));for(let s of[...n].sort((a,u)=>a.id.localeCompare(u.id)))o.push({kind:"shot",action:"capture",label:s.id,ids:[s.id],depth:1,note:" \u25CF captured \u2014 re-capture"});return o}function Mi(e,t){let n=new Set(t.filter(o=>o.state!=="placeholder").map(o=>o.id));return fc(e).filter(o=>n.has(o))}function Ui(e,t){let n=e.length;if(n===0)return null;let o=Hs(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(`
|
|
346
|
+
`)}function Dg(e,t){let n=Sg(e)?.outputDir??Pg;return Cg(n)?mn(n,`${t}.png`):Rg(e,n,`${t}.png`)}function Wi(e,t,n,o){let r=Dg(e,t);return _i(r)&&$g(r).mtimeMs>=o?"captured":n===0?"skipped":"failed"}function _u(e){let t=/⊘[^\n—]*—\s*(.+)/.exec(e);return t?t[1].trim():null}function Lu(e){let n=e.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).filter(o=>/\b\w*Error\b|Cannot navigate|Timeout \d+m?s (exceeded|waiting)|net::|browser has been closed/i.test(o)&&!/^Error Context:/i.test(o));return n.length>0?[...new Set(n)].slice(0,3).join(`
|
|
347
347
|
`):Fi(e)}function Fi(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(`
|
|
348
|
-
`)}var
|
|
349
|
-
`)}function
|
|
350
|
-
|
|
351
|
-
`)}async function
|
|
352
|
-
`)}var
|
|
353
|
-
`)
|
|
348
|
+
`)}var Ag=/^[A-Za-z0-9._-]+$/;function Bi(e){return new Promise((t,n)=>{if(!Ag.test(e.id)){n(new Error(`Not a valid spec id: "${e.id}"`));return}let o=Iu(`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",a=>{r+=a.toString()}),o.stderr?.on("data",a=>{r+=a.toString()}));let s=()=>{o.kill()};e.signal?.addEventListener("abort",s,{once:!0}),o.on("error",a=>{e.signal?.removeEventListener("abort",s),n(a)}),o.on("close",a=>{e.signal?.removeEventListener("abort",s),t({exitCode:a??1,output:r})})})}function Mu(e,t=xg()){try{let n=JSON.parse(Oi(mn(e,".d360-writer","capture.json"),"utf8").replace(/^/,"")),o=n.projectId;if(!o)try{o=JSON.parse(Oi(mn(e,"package.json"),"utf8")).name}catch{}o||=vg(e);let r=Object.keys(n.profiles??{}),s=n.defaultProfile??(r.length===1?r[0]:r.includes("staging")?"staging":r[0]);return s?_i(mn(t,".document360-capture","auth-states",o,`${s}.json`)):!0}catch{return!0}}function Uu(e){return new Promise((t,n)=>{let o=Iu("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",a=>{r+=a.toString()}),o.stderr?.on("data",a=>{r+=a.toString()});let s=()=>{o.kill()};e.signal?.addEventListener("abort",s,{once:!0}),o.on("error",a=>{e.signal?.removeEventListener("abort",s),n(a)}),o.on("close",a=>{e.signal?.removeEventListener("abort",s),t({exitCode:a??1,output:r})})})}function qi(e,t){return e===127||/is not recognized as an internal or external command|command not found/i.test(t)}function Wu(e){try{let t=JSON.parse(Oi(mn(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 _i(mn(e,".d360-writer","capture.json"))}function Hi(){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(`
|
|
349
|
+
`)}function Fu(e,t){let n=e.filter(a=>a.state==="blocked"&&a.blockedBy!=="testid").length,o=e.filter(a=>a.state==="blocked"&&a.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(", ")}
|
|
350
|
+
/screenshot list --detail shows what each one needs`}function Bu(e,t){let n=r=>e.shots[r]?.outcome,o={newlyCaptured:[],newlyBlocked:[],stillBroken:[],newlyBroken:[],blockedAsBefore:[]};for(let r of t){let s=n(r.id);r.outcome==="captured"&&s!=="captured"?o.newlyCaptured.push(r.id):r.outcome==="skipped"?(s==="skipped"?o.blockedAsBefore:o.newlyBlocked).push(r.id):r.outcome==="failed"&&(s==="failed"?o.stillBroken:o.newlyBroken).push(r.id)}return o}function qu(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 Ii(e,t=2){return e.length<=t?e.join(" \xB7 "):`${e.slice(0,t).join(" \xB7 ")} \xB7 +${e.length-t}`}function Hu(e,t){if(!t)return[];let n=[],o=(r,s,a,u)=>{s>0&&n.push(` ${r} ${`${s} ${a}`.padEnd(22)}${u}`)};return o("\u2713",e.newlyCaptured.length,"newly captured",Ii(e.newlyCaptured)),o("\u2717",e.newlyBroken.length,"newly broken",Ii(e.newlyBroken)),o("\u2298",e.newlyBlocked.length,"newly blocked",Ii(e.newlyBlocked)),o("\u2717",e.stillBroken.length,"still broken","unchanged \u2014 these need re-authoring"),o("\xB7",e.blockedAsBefore.length,"blocked as before","nothing staged since last time"),n.length>0?[""," Since your last run",...n]:[]}function Vu(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",a=e.ids.length===1?`/screenshot capture ${e.ids[0]}`:"/screenshot capture",u=o[0]?.id,p=[];o.length>0&&p.push({glyph:"\u2717",cmd:`/screenshot ${u}`,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 b=Math.max(...p.map($=>$.cmd.length));return{note:p.map($=>`${$.glyph} ${$.cmd.padEnd(b)} ${$.why}`).join(`
|
|
351
|
+
`),cmd:o.length>0?`/screenshot ${u}`:t.length>0?s:a,tone:o.length>0?"warn":"info"}}function Gu(e,t){let n=new Map(We(e).map(o=>[o.id,o.file]));return[...new Set(t.map(o=>n.get(o)).filter(o=>!!o))].sort()}async function Vi(e,t){let n=t?.cwd??process.cwd(),o=Li(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:a,rows:u}=kr(n,o.mode==="scope"?o.scope:void 0),p=Mi(n,u),b=(o.mode==="all"||o.mode==="scope")&&o.retryBlocked,k=o.mode==="single"?[o.id]:o.mode==="failed"?p:o.mode==="picker"?r:[...r,...s,...b?a:[]];if(k.length===0)return o.mode==="failed"?console.log("No broken specs to re-run \u2014 /screenshot list shows where things stand."):console.log("No authored specs to capture yet \u2014 author them first: /screenshot"),{kind:"continue"};if(!b&&o.mode!=="single"&&o.mode!=="failed"){let v=Ui(u.filter(D=>D.state==="blocked"),"/screenshot capture --all --retry-blocked");v&&console.log(v)}let $=Date.now(),x=[];for(let v of k){console.log(`\u25B6 ${v}`);try{let{exitCode:D}=await Bi({cwd:n,id:v,stdio:"inherit"});x.push({id:v,outcome:Wi(n,v,D,$)})}catch(D){if(D.code==="ENOENT")return console.log("d360-capture is not installed. Run: npm i -g document360-capture"),{kind:"continue"};x.push({id:v,outcome:"failed",detail:D.message})}}let j=v=>x.filter(D=>D.outcome===v).length;return console.log(`\u2713 ${j("captured")} captured \xB7 \u2298 ${j("skipped")} skipped \xB7 \u2717 ${j("failed")} failed`),{kind:"continue"}}import{existsSync as Eg,readFileSync as jg}from"node:fs";import{isAbsolute as Ng,join as Ig,resolve as Og}from"node:path";import{readProjectConfig as _g,DEFAULT_CAPTURE_DIR as Lg}from"document360-engine";async function gn(){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(`
|
|
352
|
+
`),display:"/screenshot checklist"}}var Yu="-".repeat(64);function Gi(e){let t=Lg;try{let k=_g(e);k?.captureDir&&(t=k.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=Ng(t)?Ig(t,"CAPTURE-TESTID-REQUESTS.json"):Og(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!Eg(n))return null;let o;try{let k=JSON.parse(jg(n,"utf8").replace(/^/,""));o=Array.isArray(k?.requests)?k.requests:[]}catch{return null}if(o.length===0)return null;let r=new Set(o.map(k=>k.file).filter(Boolean)).size,s=o.length,a=`${s} data-testid attribute${s===1?"":"s"}`,u=`${r} source file${r===1?"":"s"}`,p=`${t}/CAPTURE-TESTID-REQUESTS.md`,b=`${t}/CAPTURE-TESTID-REQUESTS.json`;return[`\u{1F4CB} Developer hand-off \u2014 ${a} requested across ${u}.`,"\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.","",Yu,`Read ${p} and ${b}. They list ${a} that d360-writer THINKS this repo needs for screenshot automation. Treat them as a hypothesis to VERIFY against the source \u2014 not a verified patch list.`,"","For EACH request in the JSON:",'1. Locate the element in THIS repo. Trace it from the route/page, not the feature name. If "anchorVerified" is false, find it by the "element"/"reason" description; otherwise confirm the "anchor" snippet still exists in "file".',"2. If the element already has a data-testid, skip it and note the existing one.","3. Confirm the attribute will reach the DOM: the rendering component must forward unknown props (a {...rest} spread or explicit pass-through). If it is a shared wrapper (e.g. Modal, ContextMenu) that destructures a fixed prop list, a data-testid is silently dropped \u2014 thread it through the component, or report it as needing a code change instead of forcing it.",'4. Only then add data-testid="<testid>" to the verified element. Add nothing else; do not rename, restructure, reformat, or change behaviour.',"","When done, report: which testids you added (file + element), which were already present, which requests were wrong (wrong file/anchor/page) with the correction, and which need threading through a shared component. Never force a request that does not match the source \u2014 flag it instead.",Yu]}ft();z();import{listOpenForDocs as Mg,readProjectConfig as Ug}from"document360-engine";function Yi(e){try{return Mg(e).length}catch{return 0}}function zi(){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(`
|
|
353
|
+
`)}async function zu(e,t){let n=t?.cwd??process.cwd();return Ug(n)?Yi(n)===0?(console.log(m("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:zi(),display:"/inbox"}:(console.log(S("No d360-writer config here. Run /init first.")),{kind:"continue"})}z();import{listOpenHints as Wg,listOpenForDocs as Fg,listOpenDirectives as Bg,readProjectConfig as qg,computeSyncStatus as Hg,planPull as Vg,applyPull as Gg,planImport as Yg,applyImport as zg}from"document360-engine";function Qn(e){let t=0,n=0,o=0,r=0;try{t=Wg(e).length}catch{}try{let s=Fg(e);n=s.filter(a=>a.kind==="request").length,o=s.filter(a=>a.kind==="answer").length}catch{}try{r=Bg(e).length}catch{}return{hints:t,requests:n,answers:o,directives:r}}function Jn(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 Xi(e){return{publish:e.includes("--publish")}}function Qi({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 (plus the d360_ask_builder question you left for it)."),t.join(`
|
|
354
|
+
`)}var Kg={status:Hg,plan:Vg,apply:Gg,planImport:Yg,applyImport:zg};async function Ji(e,t=Kg){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 Ki=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,$r=e=>e===1?"":"s";function Zi(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${$r(e.pulled.length)} into local: ${Ki(e.pulled)}`),e.imported.length&&t.push(`\u2713 Imported ${e.imported.length} new portal article${$r(e.imported.length)} into local drafts: ${Ki(e.imported)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${$r(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${Ki(e.conflicts)}`),e.failed.length&&t.push(`\u26A0 ${e.failed.length} pull/import${$r(e.failed.length)} failed \u2014 left for /pull.`),t}async function Ku(e,t){let n=t?.cwd??process.cwd();if(!qg(n))return console.log(S("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Ue(n,t?.profileName);if(!o.ok)return console.log(S(o.reason)),{kind:"continue"};let{publish:r}=Xi(e);console.log(m("Reconciling with Document360 (pulling any portal changes)\u2026"));let s=await Ji({cwd:n,profileName:t?.profileName});for(let u of Zi(s))console.log(u.startsWith("\u2713")?_(u):u.startsWith("\u2139")?m(u):B(u));let a=Jn(Qn(n));return console.log(m(a?`Catching up on ${a}\u2026`:"Checking for code changes the builder didn't hint\u2026")),{kind:"forward-to-agent",prompt:Qi({publish:r}),display:`/catch-up${r?" --publish":""}`}}z();import{spawn as Xu}from"node:child_process";var yn="document360-writer",xr=`npm i -g ${yn}@latest`,Xg="document360-capture";function Qg(){return new Promise(e=>{try{let t=Xu("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 Qg()?[yn,Xg]:[yn];return new Promise(o=>{try{let r=Xu(`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 Qu(){console.log(m("Updating the d360-writer toolchain\u2026"));let e=await vr();return e.ok?console.log(_(`\u2713 Updated ${e.packages.join(" + ")}. Exit (/exit) and relaunch d360-writer to apply.`)):console.log(S(`Update failed \u2014 run manually: ${xr}`)),{kind:"continue"}}z();ft();import{existsSync as ea,rmSync as Jg}from"node:fs";import{basename as Ju,resolve as ta}from"node:path";import{execFileSync as Zg}from"node:child_process";import{input as ey}from"@inquirer/prompts";import{readProjectConfig as ty,devHintsGuidePath as ny}from"document360-engine";var oy=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],ry=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),Cr=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),Zu=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function ed(e){let t=Cr(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:Zu(t)?!0:ry.has(t)}function na(e){let t=null;try{t=ty(e)}catch{t=null}let n=new Set(oy);for(let o of[Cr(t?.docsDir),Cr(t?.captureDir),Cr(t?.outputDir)])o&&Zu(o)&&n.add(o);return[...n].filter(o=>ed(o)&&ea(ta(e,o)))}function oa(e,t){let n=[],o=[];for(let r of t){if(!ed(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{Jg(ta(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function td(e,t){try{return Zg("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
|
|
355
|
+
`).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function sy(e){return td(e,".d360-writer/hints")}function iy(e){return td(e,".d360-writer/messages")}function ra(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=sy(e),o=iy(e),r=ea(ta(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: ${Ju(e)}`]}async function nd(e,t){let n=na(t.cwd);for(let p of ra(t.cwd,n))console.log(n.length===0?m(p):p);if(n.length===0)return{kind:"continue"};let o=Ju(t.cwd);if((await t.withPausedInput(()=>ey({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(B("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=ea(ny(t.cwd)),{removed:a,failed:u}=oa(t.cwd,n);console.log(_(`\u2713 Reset complete \u2014 removed ${a.length} item${a.length===1?"":"s"}. The repo is back to its original state.`));for(let p of u)console.log(S(` \u2717 ${p.path}: ${p.error}`));if(s){for(let p of Vo())console.log(p);console.log(m("(Select and copy the prompt above to paste into your coding agent.)"))}return console.log(m("Set up d360-writer again with /init (then /login, /workspace).")),{kind:"continue"}}z();import{lintDocs as ay}from"document360-engine";function Rr(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 sa(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(`
|
|
354
356
|
`)).join(`
|
|
355
357
|
`)].join(`
|
|
356
|
-
`)}async function
|
|
357
|
-
`);return{prompt:
|
|
358
|
-
`),display:`/reorder${n?` ${n}`:""}`}}async function
|
|
359
|
-
${a.map(
|
|
358
|
+
`)}async function od(e,t){let n=e.includes("--fix"),o=e.find(a=>!a.startsWith("--")),r=o?` ${o}`:"",s=ay({cwd:t.cwd,scope:o});if(n)return s.length===0?(console.log(_("\u2713 Nothing to fix \u2014 the docs are already clean.")),{kind:"continue"}):(console.log(m(`Fixing ${s.length} doc issue${s.length===1?"":"s"} (run /check again after to confirm)\u2026`)),{kind:"forward-to-agent",prompt:sa(s),display:`/check${r} --fix`});console.log(m("Linting the docs (engine internals, unknown commands, stale facts, AI-tells)\u2026"));for(let a of Rr(s))console.log(s.length===0?_(a):B(a));return s.length>0&&console.log(m("Run /check --fix to have the agent correct these.")),console.log(""),{kind:"continue"}}z();import{lintDocs as hy,loadStyleGuide as fy,buildReviewPrompt as my,readProjectConfig as gy,DEFAULT_DOCS_DIR as yy}from"document360-engine";z();import{readProjectConfig as ly,loadProfileMap as cy,resolveActiveProfile as uy,desiredCategoryOrder as dy,desiredArticleOrder as py}from"document360-engine";function rd(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}var sd=e=>e.replace(/\\/g,"/").split("/").pop()??e;function Zn(e,t){try{if(!ly(e))return[];let n=uy(e,t),o=cy(e,n.name);if(!o)return[];let r=new Map;for(let a of py(o)){let u=r.get(a.categoryPath);u?u.push(a):r.set(a.categoryPath,[a])}let s=[];for(let a of dy(o)){s.push(rd(sd(a.path)));for(let u of(r.get(a.path)??[]).sort((p,b)=>p.order-b.order))s.push(` ${rd(sd(u.path))}`)}return s}catch{return[]}}async function id(e,t){let n=Zn(t.cwd,t.profileName);if(n.length===0)return console.log(m("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 ia(e,t){let n=gy(e);if(!n)return null;let o=(n.docsDir??yy).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),s=t.find(k=>!k.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),a=hy({cwd:e}),u=s?a.filter(k=>k.path===`${o}/${s}`||k.path.startsWith(`${o}/${s}/`)):a,p=s?"":Zn(e).join(`
|
|
359
|
+
`);return{prompt:my({docsRoot:o,scope:s,styleGuide:fy(e),deterministicFindings:u,fix:r,structure:p||void 0}),display:`/review${s?` ${s}`:""}${r?" --fix":""}`}}async function ad(e,t){if(kt("review",e)){let o=fn(t.cwd,"review",e,t.profileName);if(o.length>0){for(let r of o)console.log(m(r));return{kind:"continue"}}}let n=ia(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(S("No d360-writer config here. Run /init first.")),{kind:"continue"})}z();import{readProjectConfig as wy}from"document360-engine";function aa(e,t){if(!wy(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(`
|
|
360
|
+
`),display:`/reorder${n?` ${n}`:""}`}}async function ld(e,t){if(kt("reorder",e)){let o=fn(t.cwd,"reorder",e,t.profileName);if(o.length>0){for(let r of o)console.log(m(r));return{kind:"continue"}}}let n=aa(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(S("No d360-writer config here. Run /init first.")),{kind:"continue"})}z();import{readProjectConfig as ky,writeProjectConfig as cd,isAppType as by,playbookSkillName as $y,detectAppType as ud}from"document360-engine";var dd=["web","cli","service","library"],xy=new Set(["web","cli"]);function la(e){return xy.has(e)?`${$y(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function Sr(e,t){let n=t.cwd,o=ky(n);if(!o)return console.log(S("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let s=o.appType??ud(n);if(s){let a=o.appType?"set in config":"auto-detected";console.log(`${W("Genre:")} ${s} (${a}) \u2014 ${la(s)}`)}else console.log(B("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(m(`Set it: /genre <${dd.join("|")}> \xB7 revert to auto-detect: /genre auto`)),{kind:"continue"}}if(r==="auto"||r==="clear"){if(!o.appType)return console.log(m("Already on auto-detect (no genre set in config).")),{kind:"continue"};let{appType:s,...a}=o;cd(a,n);let u=ud(n);return console.log(_(`\u2713 Genre reset to auto-detect \u2014 now: ${u?`${u} (${la(u)})`:"unclassified (no playbook)"} (applies from your next command).`)),{kind:"continue"}}return by(r)?(cd({...o,appType:r},n),console.log(_(`\u2713 Genre set to ${r} \u2014 ${la(r)} (applies from your next command).`)),{kind:"continue"}):(console.log(S(`Unknown genre "${r}". Choose one of: ${dd.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}z();import{listRoadmap as Pr,roadmapProgress as pd,stampRoadmapDone as vy}from"document360-engine";function ca(e){let t=Pr(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=pd(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 Tr(e,t){let n=Pr(e).filter(b=>b.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=b=>b.trim().toLowerCase(),s=n.find(b=>r(b.title)===r(o)),a=o?s?[s]:n.filter(b=>r(b.title).includes(r(o))):[n[0]];if(a.length>1)return{ok:!1,line:`"${o}" matches ${a.length} open steps \u2014 add a distinguishing word:
|
|
361
|
+
${a.map(b=>` \u25CB ${b.title}`).join(`
|
|
360
362
|
`)}`};if(a.length===0)return{ok:!1,line:`No open step matches "${o}". Open steps:
|
|
361
|
-
${n.map(
|
|
362
|
-
`)}`};let u=a[0].title;
|
|
363
|
-
`):null}function
|
|
363
|
+
${n.map(b=>` \u25CB ${b.title}`).join(`
|
|
364
|
+
`)}`};let u=a[0].title;vy(e,u,{doneAt:new Date().toISOString()});let p=pd(e)?.next;return{ok:!0,line:`\u2713 Marked done: ${u}${p?` \u2014 next up: ${p.title}${p.run?` (${p.run})`:""}`:" \u2014 that was the last step: campaign complete."}`}}function ua(e,t){let n=r=>r.trim().replace(/\s+/g," ").toLowerCase(),o=n(t);return o.startsWith("/")?Pr(e).find(r=>r.status==="open"&&!!r.run&&n(r.run)===o)??null:null}function hd(e,t){let n=ua(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(`
|
|
365
|
+
`):null}function fd(e,t){let n=t.trim().toLowerCase();if(!n)return null;let o=Pr(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:
|
|
364
366
|
${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(`
|
|
365
|
-
`):null}async function
|
|
366
|
-
\u2022 `),lead:{kind:"cmd",cmd:"/catch-up",reason:n},picker:null,follow:"Then /catch-up clears what\u2019s queued for the docs."})}if(e.hasDocs&&e.pendingWrites>0){let n=e.pendingWrites;t.push({key:"write",bullet:`${n} planned article${ge(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${ge(n)}.`})}if(e.localAhead>0){let n=e.localAhead;t.push({key:"publish",bullet:`${n} article${ge(n)} changed locally \u2014 ready to publish`,lead:{kind:"cmd",cmd:"/publish",reason:`it pushes your ${n} local edit${ge(n)} up to Document360`},picker:null,follow:`Then /publish pushes your ${n} local edit${ge(n)} up.`})}if(e.conflicts>0){let n=e.conflicts;t.push({key:"resolve",bullet:`${n} article${ge(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${ge(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${ge(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.behind>0){let n=e.behind;t.push({key:"audit",bullet:`${n} code change${ge(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${ge(n)}.`})}if(e.uncommittedDocs>0){let n=e.uncommittedDocs;t.push({key:"commit",bullet:`\u26A0 ${n} uncommitted change${ge(n)} under .d360-writer/ \u2014 tell your coding agent: "commit d360-writer's work"`,lead:null,picker:null,follow:null})}return t}function
|
|
367
|
-
`)];return r.length&&s.push(r.join(" ")),s.push(
|
|
368
|
-
|
|
369
|
-
`)}function
|
|
370
|
-
`).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let a=
|
|
371
|
-
`);return{lines:s.slice(0,t).map(a=>
|
|
372
|
-
`))console.log(a(` ${u}`));s.rec.picker&&console.log(W(` Pick one: ${s.rec.picker.options.map(u=>u.cmd).join(" \xB7 ")}`))}}catch{}}console.log(
|
|
373
|
-
|
|
374
|
-
`),console.log(`${
|
|
375
|
-
`);let s=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(
|
|
376
|
-
`),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){
|
|
377
|
-
`)}import{existsSync as
|
|
378
|
-
\u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close \xB7 d360-writer v${n} \xB7 engine v${o}`})]})}var
|
|
379
|
-
`)){let a=s.trim().replace(
|
|
380
|
-
`)}function
|
|
381
|
-
`)||e.length>200}function
|
|
382
|
-
`).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function
|
|
383
|
-
`)){if(s.length===0)o.push({start:r,end:r});else for(let a=0;a<s.length;a+=n)o.push({start:r+a,end:r+Math.min(a+n,s.length)});r+=s.length+1}return o.length>0?o:[{start:0,end:0}]}function qr(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function
|
|
384
|
-
`),s=0;for(let a=r.length-1;a>=0;a--){let u=r[a];if(s+=Math.max(1,Math.ceil(u.length/o)),s>=t){let
|
|
385
|
-
`),truncated:a>0||
|
|
386
|
-
`)){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
|
|
367
|
+
`):null}async function md(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let r=Tr(n,e.slice(1).join(" ").trim());return console.log(r.ok?_(r.line):B(r.line)),{kind:"continue"}}let o=ca(n);console.log(W(o[0]??""));for(let r of o.slice(1))console.log(r.startsWith("(")?m(r):r);return{kind:"continue"}}var gd={help:ks,"?":ks,clear:Pl,exit:bs,quit:bs,init:Rs,mcp:zo,publish:Uc,audit:Yn,discover:Wc,scope:Bc,pull:Zc,resolve:Xc,convert:eu,write:iu,draft:du,document:pu,resume:mu,rename:gu,profile:wu,model:$u,doctor:Xn,workspace:Du,project:Au,"allow-prod":Eu,login:ju,logout:Nu,screenshot:async(e,t)=>{let n=Hn(e);return n.mode==="capture"?Vi(n.rest,t):n.mode==="checklist"?gn():sr(e,t)},capture:Vi,"capture-setup":gn,devhints:Ml,inbox:zu,"catch-up":Ku,update:Qu,reset:nd,check:od,review:ad,reorder:ld,structure:id,genre:Sr,roadmap:md};function yd(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}ft();var Cy="Or just tell me what to write or update.",Ry='\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 ge(e){return e===1?"":"s"}function Dr(e){return e.kind==="cmd"?`\u21E5 tab to run ${e.cmd} \xB7 or just ask me anything\u2026`:null}function eo(e){return e.kind==="cmd"?`I\u2019d start with ${e.cmd} \u2014 ${e.reason}.`:`Just tell me: \u201C${e.text}\u201D.`}var Sy={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 Py(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:Sy,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${ge(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${ge(e.directives)} waiting`),e.pendingText&&o.push(`your builder left ${e.pendingText}`),t.push({key:"catchup",bullet:o.join(`
|
|
368
|
+
\u2022 `),lead:{kind:"cmd",cmd:"/catch-up",reason:n},picker:null,follow:"Then /catch-up clears what\u2019s queued for the docs."})}if(e.hasDocs&&e.pendingWrites>0){let n=e.pendingWrites;t.push({key:"write",bullet:`${n} planned article${ge(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${ge(n)}.`})}if(e.localAhead>0){let n=e.localAhead;t.push({key:"publish",bullet:`${n} article${ge(n)} changed locally \u2014 ready to publish`,lead:{kind:"cmd",cmd:"/publish",reason:`it pushes your ${n} local edit${ge(n)} up to Document360`},picker:null,follow:`Then /publish pushes your ${n} local edit${ge(n)} up.`})}if(e.conflicts>0){let n=e.conflicts;t.push({key:"resolve",bullet:`${n} article${ge(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${ge(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${ge(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.behind>0){let n=e.behind;t.push({key:"audit",bullet:`${n} code change${ge(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${ge(n)}.`})}if(e.uncommittedDocs>0){let n=e.uncommittedDocs;t.push({key:"commit",bullet:`\u26A0 ${n} uncommitted change${ge(n)} under .d360-writer/ \u2014 tell your coding agent: "commit d360-writer's work"`,lead:null,picker:null,follow:null})}return t}function wd(e){return e.find(t=>t.lead||t.picker)??null}function da(e,t){let n=t.filter(a=>a.bullet).map(a=>` \u2022 ${a.bullet}`),o=wd(t),r=[];o?.lead?r.push(eo(o.lead)):o?.picker&&r.push("Pick the genre below \u2014 one keypress, and it shapes everything I write.");for(let a of t.filter(u=>u!==o).slice(0,2))a.follow&&r.push(a.follow);let s=[[e,...n].join(`
|
|
369
|
+
`)];return r.length&&s.push(r.join(" ")),s.push(Cy),s.join(`
|
|
370
|
+
|
|
371
|
+
`)}function to(e){if(!e.ready)return{kind:"idle"};let t=Py(e);if(!e.hasDocs){let s=wd(t);return s&&(s.lead?.kind==="cmd"||s.picker)?{kind:"recommend",rec:{note:da("\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:Ry,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${ge(e.roadmap.total)} done (/roadmap).`:"";return{kind:"recommend",rec:{note:`Welcome back. Your ${e.tracked} tracked article${ge(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"||o.key==="roadmap"&&n[1]?.key==="audit")&&e.behind>0&&e.autoAudit&&e.allowAutoAudit?{kind:"autoAudit",note:`\u{1F4CB} ${e.behind} code change${ge(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`}:{kind:"recommend",rec:{note:da("Welcome back \u2014 where your docs stand:",t),tone:o.tone??"info",lead:o.lead,picker:o.picker}}:{kind:"recommend",rec:{note:da("Welcome back \u2014 where your docs stand:",t),tone:"info",lead:null,picker:null}}}import{existsSync as pa,readdirSync as fa}from"node:fs";import{spawnSync as Ty}from"node:child_process";import{join as Ar}from"node:path";import{readProjectConfig as bd,resolveActiveProfile as $d,loadTokens as Dy,isExpired as Ay,loadProfileMap as xd,localAheadPaths as Ey,loadKnownConflicts as jy,readDocsPlan as Ny,devHintsGuidePath as Iy,DEFAULT_DOCS_DIR as ha,roadmapProgress as Oy,listRoadmap as _y,readProductBriefState as Ly,reconcileCommitRequest as My}from"document360-engine";ft();function kd(e){try{return fa(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function ma(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>kd(Ar(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&kd(Ar(e,o)))}function ga(e,t){try{let n=bd(e);if(!n)return!1;let o=$d(e,t),r=xd(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=Ar(e,(n.docsDir??ha).replace(/\/+$/,""));return!!(pa(s)&&fa(s).length>0||pa(Iy(e)))}catch{return!1}}function no(e,t,n){try{let o=bd(e);if(!o)return null;let r=$d(e,t),s=Dy(r.name),a=!!s&&(!Ay(s)||!!s.refreshToken),u=ga(e,t)||!ma(e,o.authoritativeSourceFiles),p=xd(e,r.name),b=p?Object.keys(p.articles).length:0,k=Ar(e,(o.docsDir??ha).replace(/\/+$/,"")),$=!1;try{$=pa(k)&&fa(k).length>0}catch{}let x=0;if(p?.lastAnalyzedCommit)try{let me=Ty("git",["rev-list","--count",`${p.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});me.status===0&&(x=parseInt((me.stdout||"").trim(),10)||0)}catch{}let j=0;try{let me=Ny(e);if(me.length>0){let Qe=(o.docsDir??ha).replace(/\/+$/,"");j=mi(e,Qe,me.map(be=>be.path)).length}}catch{}let v=Qn(e),D=Jn({...v,directives:0}),E=Ey(e,t),U=new Set(jy(e,r.name)),L=E.filter(me=>U.has(me)).length,G=E.length-L,H=Me(e),se=Oy(e),qe=My(e,new Date().toISOString()),fe=Ly(e),Xe=fe?{status:fe.status,openQuestions:fe.openQuestions}:null;return!Xe&&$&&_y(e).some(Qe=>Qe.status==="open"&&(Qe.run??"").trim()==="/discover")&&(Xe={status:"pending",openQuestions:0}),{ready:a&&u&&!n.claudeMissing,hasDocs:$,tracked:b,pendingText:D,directives:v.directives,behind:x,pendingWrites:j,localAhead:G,conflicts:L,autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:H.status,devhintsCompletedVersion:H.completedVersion,devhintsToVersion:de,builderStarted:rt(e),genreUnknown:n.genreUnknown,roadmap:se,discovery:Xe,uncommittedDocs:qe.dirty.length}}catch{return null}}z();var Uy={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"},Cd=160,wa=200,Rd=40;function je(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function vd(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}: ${je(typeof r=="string"?r:JSON.stringify(r),Rd)}`);return t.length>4&&n.push("\u2026"),je(n.join(", "),Cd)}var Wy=new Set(["file_path","notebook_path"]);function Fy(e,t){if(!t)return e;let n=a=>a.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 bt=e=>typeof e=="string"&&e?e:null,ya=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function By(e){let t=bt(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 qy(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=bt(t.title);if(!o)return null;let r=By(t.local_path);return n("Create article",`"${je(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=bt(t.title),r=ya(t.article_id);return n("Update article",o?`"${je(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",ya(t.article_id)?`id ${ya(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",bt(t.name)?`"${je(bt(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=bt(t.file_path);return n("Upload image",o?je(o.replace(/\\/g,"/").split("/").pop()??o,60):null)}case"d360_sync_status":return n("Check sync status",null);default:return null}}function Er(e,t,n){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,s="",...a]=e.split("__"),u=a.join("__");if(s==="document360"){let k=qy(u,t);if(k)return k}let p=u.replace(/^d360_/,"").replace(/_/g," ");return{title:`${s==="document360"?"Document360":s.charAt(0).toUpperCase()+s.slice(1)}: ${p}`,sep:" ",arg:vd(t)}}let o=Uy[e],r=o?t[o]:void 0;if(typeof r=="string"&&r){let s=o&&Wy.has(o)?Fy(r,n):r;return{title:e,sep:"",arg:je(s,Cd)}}return{title:e,sep:"",arg:vd(t)}}function Hy(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 Vy(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(Hy).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>je(r,wa))]}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}: ${je(String(r),Rd)}`);return n.length>0?[je(n.join(" \xB7 "),wa)]:null}return null}function Gy(e){let t=bt(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function Yy(e,t,n){switch(e){case"d360_create_article":{let o=Gy(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=bt(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 ${je(o[0],120)}`:""}`]}default:return null}}function jr(e,t=4,n,o){let r=e.replace(/\r\n/g,`
|
|
372
|
+
`).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let a=Yy(n.slice(18),o,r);if(a)return{lines:a,hidden:0}}let s=Vy(r)??r.split(`
|
|
373
|
+
`);return{lines:s.slice(0,t).map(a=>je(a,wa)),hidden:Math.max(0,s.length-t)}}function Nr(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function Ir(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 Sd(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 Or(e){return Sd(e,"url")}function _r(e){return Sd(e,"preview_url")}var hw=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function fw(e,t,n,o){if(hw.test(e))try{let r=Dd(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,a=Ir(t,n),u=Or(n);e.endsWith("publish_article")&&u&&console.log(W(` \u2B95 Live: ${u}`));let p=_r(n);p?console.log(W(` \u2B95 Preview: ${p}`)):a&&s&&console.log(W(` \u2B95 Preview: ${Nr(r.connection.portalUrl,s,a,r.project.languageCode??"en")}`))}catch{}}async function Ad(e=process.cwd(),t="auto",n,o){let r=Ky(t);r.kind==="none"&&(console.error(""),console.error(S("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)),mw(e,n),r.kind==="subscription"&&(r.stored?console.log(m(" Using your Claude subscription (no API key set).")):console.log(m(" No API key or stored Claude Code login found \u2014 trying your Claude session anyway.")),console.log(""));let s=!1,a=ka({cwd:e,profileName:n,allowProdWrites:s}),u={uuid:null,firstPrompt:null,titleFired:!1},p=zy({input:process.stdin,output:process.stdout}),b=[],k=null,$=!1;p.on("line",v=>{if(k){let D=k;k=null,D(v)}else b.push(v)}),p.on("close",()=>{if($=!0,k){let v=k;k=null,v(null)}});function x(){return b.length>0?Promise.resolve(b.shift()):$?Promise.resolve(null):(process.stdout.write(W("> ")),new Promise(v=>{k=v}))}let j={cwd:e,version:o,profileName:n,allowProdWrites:()=>s,restartAgent:()=>{a.close(),a=ka({cwd:e,profileName:n,allowProdWrites:s}),u={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>u.uuid,setPendingName:v=>{u.pendingName=v},setModel:async v=>a.setModel(v),withPausedInput:async v=>{p.pause();try{return await v()}finally{p.resume()}}};try{for(;;){let v=await x();if(v===null)break;let D=v.trim();if(D){if(D.startsWith("/")){let E=yd(D);if(!E)continue;let U=gd[E.name];if(!U){console.log(S(`Unknown command: /${E.name}`)),console.log(m("Type /help for the list."));continue}let L=await U(E.args,j);if(L.kind==="exit")break;if(L.kind==="clear"){j.restartAgent();continue}if(L.kind==="allow-prod"){s=!0,j.restartAgent(),console.log(_("\u2713 Production writes authorized for this session.")),console.log("");continue}if(L.kind==="resume"){a.close(),a=ka({cwd:e,resume:L.uuid,profileName:n,allowProdWrites:s});let G=Xy(L.uuid);u={uuid:L.uuid,firstPrompt:G?.firstPrompt??null,titleFired:!0},Td(L.uuid),console.log(_(`\u2713 Resumed "${L.name}"`)),console.log("");continue}if(L.kind==="forward-to-agent"){u.firstPrompt||(u.firstPrompt=L.display??L.prompt);let G=(L.display??"").trim().split(/\s+/),H=(G[0]==="/check"||G[0]==="/review")&&G.includes("--fix"),se=G.slice(1).find(fe=>!fe.startsWith("--")),qe=H?dw(e,se):[];if(await ba(a,L.prompt,r,u,e),H)try{uw(e,qe,{reviewedCap:pw})}catch{}}else gw(e,n);continue}if(iw(D)){let E=aw(D);if(E){try{lw(e,{title:E,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}u.firstPrompt||(u.firstPrompt=D),await ba(a,`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${E}". 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 "${E}" and the article path(s) you wrote.`,r,u,e);continue}}u.firstPrompt||(u.firstPrompt=D),await ba(a,D,r,u,e)}}}finally{a.close(),p.close()}}function mw(e,t){console.log(""),console.log(On("document360-writer")),console.log(m(` cwd: ${e}`));let n=tw(e);if(console.log(m(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(yw(e,t)),!nw(e))console.log(B(" 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(qo(e),!rt(e))for(let r of Ho(e))console.log(B(` ${r}`))}catch{}try{let r=ow(e);r.persisted&&r.appType?console.log(m(` \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=cw(e);for(let s of Ko(r.applied))console.log(B(` ${s}`))}catch{}try{let r=no(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:o}),s=r?to(r):null;if(s?.kind==="recommend"&&s.rec.note){let a=s.rec.tone==="warn"?B:m;for(let u of Ns(s.rec.note).split(`
|
|
374
|
+
`))console.log(a(` ${u}`));s.rec.picker&&console.log(W(` Pick one: ${s.rec.picker.options.map(u=>u.cmd).join(" \xB7 ")}`))}}catch{}}console.log(m(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function gw(e,t){try{let n=no(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:!1}),o=n?to(n):null;o?.kind==="recommend"&&o.rec.lead&&console.log(m(` Next: ${eo(o.rec.lead)}`))}catch{}}function yw(e,t){try{let n=Dd(e,t),o=n.production?B(" \u26A0 PRODUCTION"):"",r=sw(n.name);if(!r)return m(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...Pd(r.idToken)??{},...Pd(r.accessToken)??{}},a=s.email??s.preferred_username??"signed in";return rw(r)&&!r.refreshToken?B(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):m(` Document360: ${a} \xB7 profile "${n.name}"${o}`)}catch(n){return m(` Document360: ${n.message.split(".")[0]}`)}}function ww(){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 kw(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;Zy({uuid:t,name:r??Jy(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function bw(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||ew(o,t).then(r=>{r&&Qy(n,r)}).catch(()=>{})}async function ba(e,t,n,o,r){let s=new Map;for await(let a of e.send(t))$w(a,o,r,n,s)}function $w(e,t,n,o,r){switch(e.type){case"session":t.uuid||kw(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let s=Er(e.name,e.input,process.cwd());s&&(process.stdout.write(`
|
|
375
|
+
|
|
376
|
+
`),console.log(`${_("\u25CF")} ${Se(s.title)}${s.arg!==null?ue(`${s.sep}(${s.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let s=it(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!s)break;let a=u=>u===1?"":"s";console.log(ue(` \u23BF Added ${s.added} line${a(s.added)}, removed ${s.removed} line${a(s.removed)}`));for(let u of s.lines)console.log(u);s.hidden>0&&console.log(m(` \u2026 +${s.hidden} more diff lines`));break}case"tool_result":{let s=r.get(e.id);if(!s)break;r.delete(e.id);let a=jr(e.output,4,e.isError?void 0:s.name,s.input),u=e.isError?S:ue;a.lines.forEach((p,b)=>console.log(u((b===0?" \u23BF ":" ")+p))),a.hidden>0&&console.log(m(` \u2026 +${a.hidden} lines`)),e.isError||fw(s.name,s.input,e.output,n);break}case"result":{process.stdout.write(`
|
|
377
|
+
`);let s=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(m(` (${Fn(s)}\u2192${Fn(e.outputTokens)} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(Td(t.uuid),t.titleFired||bw(t,n));break}case"error":console.error(""),console.error(S(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&ww();break}}import{render as _k}from"ink";import{resolveAuth as Lk}from"document360-engine";import{useCallback as Q,useEffect as Ie,useMemo as Sa,useRef as te,useState as K}from"react";import{Box as le,Text as N,useApp as _w,useInput as Lw,useStdout as Mw}from"ink";import{existsSync as kn,readFileSync as Hr,readdirSync as Uw}from"node:fs";import{basename as ro,isAbsolute as Ww,join as Pa}from"node:path";import{createSession as tp,classifyClaudeAuth as Na,CLAUDE_CODE_SETUP_HINT as Fw,loginPkce as Bw,toStoredTokens as qw,saveTokens as Hw,getAccessToken as Vw,resolveActiveProfile as Ne,resolveProjectId as Gw,getArticle as Yw,decodeJwtClaims as $n,isExpired as $t,loadTokens as Ut,clearTokens as zw,clearProfileProject as Kw,setTitle as Xw,slugify as Qw,touchSession as Ta,upsertSession as Jw,generateTitle as np,findByName as Zw,listSessions as ek,renameSession as tk,suggestNextAction as nk,readProjectConfig as ae,writeProjectConfig as op,resolveAndPersistAppType as ok,detectAppType as rk,resolveModelSetting as Ia,loadProfileMap as rp,applyPull as sp,computeSyncStatus as Da,lintDocs as ip,compareRemoteSources as sk,planPull as ap,establishBaselines as ik,rebaselineServerMeta as ak,inventoryRepo as lk,knownEnvironments as ck,resolveEnvironment as uk,planPartitions as Aa,partitionEvenly as dk,screenshotPlaceholderIds as pk,trackedArticlePaths as hk,runPartitioned as Vr,estimateBulkCost as lp,resolveModelForOperation as Gr,readDocsPlan as fk,checkForUpdate as mk,detectInstallKind as gk,isSelfUpdatable as yk,devHintsGuidePath as cp,toolFeedbackPath as up,reconcileToolFeedback as wk,reconcileUpgradeActions as kk,stampArticles as Ea,listArticleFiles as dp,CONTENT_CAP_VERSION as ja,ENGINE_VERSION as kp,DEFAULT_DOCS_DIR as Oa,setProfileProject as bk,writeCrashLog as $k,applyStructureOrder as pp,orderSyncLine as hp,applyRelatedArticles as fp,relatedSyncLine as mp}from"document360-engine";ji();ft();import{spawn as Ed}from"node:child_process";function xw(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function vw(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?Ed([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):Ed(e,t,{stdio:["pipe","ignore","ignore"]});r.on("error",()=>o(!1)),r.on("close",a=>o(a===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 $a(e){for(let[t,n]of xw())if(await vw(t,n,e))return!0;return!1}var Cw=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function xa(e,t){if(t.closed)return e;let n=e.split(`
|
|
378
|
+
`),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){Cw.test(s)&&(t.cueSeen=!0);continue}let a=/^(\s{0,3})[-*•]\s+(.*)$/.exec(s);a?(n[r]=`${a[1]}${++t.num}. ${a[2]}`,o=!0):o&&s.trim()!==""&&/^\S/.test(s)&&(t.closed=!0)}return n.join(`
|
|
379
|
+
`)}import{existsSync as Rw,mkdirSync as Sw,readFileSync as Pw,writeFileSync as Tw}from"node:fs";import{join as jd}from"node:path";import{writerDir as Dw}from"document360-engine";function Nd(e){return jd(Dw(e),".sessions")}function Id(e,t){return jd(Nd(e),`${t}.json`)}function Od(e,t,n){try{Sw(Nd(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");Tw(Id(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function va(e,t){try{let n=Id(e,t);if(!Rw(n))return[];let o=JSON.parse(Pw(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var Aw=e=>`\x1B]0;${e}\x07`,Ew=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function _d(e){process.stdout.isTTY&&process.stdout.write(e)}function wn(e){_d(Aw(e))}function Lr(e){_d(Ew(e))}var Mr=["\xB7 "," \xB7"],Ur="\u{1F7E3}";wr();Yo();z();import{Box as Ld,Text as he}from"ink";import{jsx as ye,jsxs as Wr}from"react/jsx-runtime";function jw({row:e}){switch(e.t){case"head":return ye(he,{color:X,bold:!0,children:e.s});case"text":return ye(he,{children:e.s});case"dim":return ye(he,{dimColor:!0,children:e.s});case"sub":return ye(he,{bold:!0,dimColor:!0,children:e.s});case"good":return ye(he,{color:"green",children:e.s});case"step":return Wr(he,{children:[ye(he,{color:X,children:`${e.n}. `}),e.s]});case"cmd":return Wr(he,{children:[" ",ye(he,{color:X,children:e.name.padEnd(20)}),ye(he,{dimColor:!0,children:e.s})]});case"gap":return ye(he,{children:" "})}}function Md({tab:e,width:t,version:n,engineVersion:o}){let r=Le[e]??Le[0],s=6+Le.reduce((u,p)=>u+p.label.length+4,0),a="\u2500".repeat(Math.min(s,Math.max(t-1,20)));return Wr(Ld,{flexDirection:"column",paddingX:1,children:[Wr(he,{children:[ye(he,{color:X,bold:!0,children:"Help "}),Le.map((u,p)=>p===e?ye(he,{color:"white",backgroundColor:X,bold:!0,children:` ${u.label} `},u.key):ye(he,{dimColor:!0,children:` ${u.label} `},u.key))]}),ye(he,{color:X,children:a}),ye(Ld,{flexDirection:"column",marginTop:1,children:r.rows.map((u,p)=>ye(jw,{row:u},p))}),ye(he,{dimColor:!0,children:`
|
|
380
|
+
\u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close \xB7 d360-writer v${n} \xB7 engine v${o}`})]})}var Nw=/^(?:\d+[.)]|[-*•])\s+/;function Ud(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
|
|
381
|
+
`)){let a=s.trim().replace(Nw,""),u=a.match(/^`([^`]+)`$/);u&&(a=u[1].trim());let p=a.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!p||!o.has(p[1].toLowerCase()))continue;let b=`/${p[1].toLowerCase()}${p[2]?` ${p[2]}`:""}`;if(r.includes(b)||r.push(b),r.length>=n)break}return r}z();function oo(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function Fe(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function Wd(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var Iw=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function Fd(e,t,n){if(!Iw.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 a=s.replace(/\\/g,"/");return r===a||r.endsWith(`/${a}`)})??null}function Ca(e){return e.replace(/^[\w.-]+\//,"")}var Fr=16,Bd={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function Mt(e){return typeof e=="string"?e:e.cmd}function qd(e){return typeof e=="string"?void 0:e.desc}function Ra(e){return e.trim().split(/\s+/).slice(1).join(" ")}function Hd(e,t){let n=Ra(t);return e.some(r=>Mt(r).trim()===t.trim()||!!n&&Ra(Mt(r))===n)?e.filter(r=>Mt(r).trim()!==t.trim()&&!(n&&Ra(Mt(r))===n)):[]}import{isDirectiveMention as xk,stripDirectiveMention as vk,appendDirective as Ck}from"document360-engine";var Ow=/\[Pasted text #\d+ \+\d+ lines?\]/g;function Vd(e){return e.replace(/\r\n?/g,`
|
|
382
|
+
`)}function Gd(e){return e.includes(`
|
|
383
|
+
`)||e.length>200}function Yd(e,t){let n=t.split(`
|
|
384
|
+
`).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function zd(e,t){return e.replace(Ow,n=>t.get(n)??n)}function Kd(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function Br(e,t){let n=Math.max(1,t),o=[],r=0;for(let s of e.split(`
|
|
385
|
+
`)){if(s.length===0)o.push({start:r,end:r});else for(let a=0;a<s.length;a+=n)o.push({start:r+a,end:r+Math.min(a+n,s.length)});r+=s.length+1}return o.length>0?o:[{start:0,end:0}]}function qr(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function Xd(e,t,n){let o=qr(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 Qd(e,t,n){let o=e[qr(e,t)];return n==="start"?o.start:o.end}function Jd(e,t,n){let o=Math.max(1,n),r=e.split(`
|
|
386
|
+
`),s=0;for(let a=r.length-1;a>=0;a--){let u=r[a];if(s+=Math.max(1,Math.ceil(u.length/o)),s>=t){let p=s-t;return{text:[p>0?u.slice(p*o):u,...r.slice(a+1)].join(`
|
|
387
|
+
`),truncated:a>0||p>0}}}return{text:e,truncated:!1}}function Zd(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 ep(e){let t=!1,n=0,o=0;for(let r of e.split(`
|
|
388
|
+
`)){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 so,jsx as I,jsxs as J}from"react/jsx-runtime";var Rk={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL",auto:"auto \u2014 right-sized for docs \xB7 /model to change"},gp=` 1. /init \u2014 pick your Document360 environment & scaffold config
|
|
387
389
|
2. /login \u2014 sign in & pick your Document360 project (workspace auto-selected)
|
|
388
|
-
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function
|
|
389
|
-
${
|
|
390
|
-
Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!
|
|
391
|
-
${
|
|
392
|
-
`)}),
|
|
393
|
-
`)})}catch{}let
|
|
390
|
+
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function Sk(e,t,n,o){let r=Na(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)",a=Ia(e),u=ae(e),p=(u?.docsDir??Oa).replace(/\/+$/,""),b=u?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${p}/ + config`,k={version:t,engineVersion:kp,captureVersion:yr(),claude:s,model:a.model,modelSource:Rk[a.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:u!==null,mode:b};if(u===null)return k;try{let $=Ne(e,o);k.profile=$.name,k.apiUrl=$.connection.apiUrl,k.prod=$.production,k.project=$.project.projectName??$.project.projectId??"(chosen at login)";let x=Ut($.name);if(x){let j={...$n(x.idToken)??{},...$n(x.accessToken)??{}},v=j.email??j.preferred_username??"signed in";$t(x)?x.refreshToken&&(k.who=v,k.loggedOut=!1,k.sessionHint="session expired \u2014 refreshing\u2026"):(k.who=v,k.loggedOut=!1,k.sessionHint=`session valid until ${new Date(x.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return k}function Pk(e,t){try{let n=Ne(e,t),o=Ut(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...$n(o.idToken)??{},...$n(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return $t(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 yp=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],xn=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Tk="Ask me to write or update an article\u2026";function bn({ch:e,dim:t}){let[n,o]=K(!0);return Ie(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),I(N,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var Dk=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function wp(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var Ak=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ek({startTime:e,chars:t}){let[n,o]=K(0);Ie(()=>{let p=setInterval(()=>o(b=>b+1),120);return()=>clearInterval(p)},[]);let r=xn[n%xn.length],s=yp[Math.floor(n/16)%yp.length],a=Math.floor((Date.now()-e)/1e3),u=Math.round(t/4);return J(le,{children:[I(N,{color:X,children:` ${r} ${s}\u2026 `}),I(N,{color:"gray",children:`(${Bn(a)} \xB7 ~${u} tokens \xB7 esc to interrupt)`})]})}function jk({text:e}){let[t,n]=K(0);return Ie(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),I(le,{paddingX:1,children:I(N,{color:X,children:`${xn[t%xn.length]} ${e}`})})}var Nk=12e4;function Ik({p:e}){let[t,n]=K(0);Ie(()=>{let E=setInterval(()=>n(U=>U+1),150);return()=>clearInterval(E)},[]);let o=xn[t%xn.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),a=Math.round(e.chars/4),u=Date.now()-e.lastAt>=Nk,p=e.verb??"Converting",b=e.unit??"article",k=e.rows.reduce((E,U)=>E+U.items,0),$=p.toLowerCase(),x=e.rows,j=0;if(x.length>Fr){let E=x.findIndex(L=>L.status==="active"||L.status==="pending"),U=Math.max(0,Math.min(E-2,x.length-Fr));j=x.slice(0,U).filter(L=>L.status==="done").length,x=x.slice(U,U+Fr)}let v=Math.min(40,Math.max(...x.map(E=>Ca(E.label).length),0)),D=E=>E==="failed"?"red":E==="active"?X:void 0;return J(le,{flexDirection:"column",children:[J(le,{children:[I(N,{color:X,children:` ${o} ${p} ${k} ${b}${k===1?"":"s"} `}),I(N,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${a} tokens \xB7 ${Bn(r)} \xB7 esc to stop`})]}),j>0&&I(N,{dimColor:!0,children:` \u2714 +${j} done`}),x.map(E=>J(N,{color:D(E.status),dimColor:E.status==="done"||E.status==="pending",children:[` ${Bd[E.status]} ${Ca(E.label).padEnd(v)}`,E.status==="active"&&E.itemsDone!==void 0?` (${E.itemsDone}/${E.items} ${b}${E.items===1?"":"s"})`:E.status!=="pending"?` (${E.items} ${b}${E.items===1?"":"s"})`:"",E.status==="active"?` \u2190 ${$}\u2026`:""]},E.label)),u&&I(N,{color:"yellow",children:` \u26A0 no activity for ${Bn(s)} \u2014 press esc to stop if it's wedged`})]})}var Ok=10800*1e3;function bp({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=_w(),[s,a]=K(n),[u,p]=K(null),[b,k]=K({text:"",pos:0}),$=b.text,x=Q(c=>{k(l=>{let i=typeof c=="function"?c(l.text):c;return{text:i,pos:i.length}})},[]),j=Q(c=>{k(l=>({text:l.text.slice(0,l.pos)+c+l.text.slice(l.pos),pos:l.pos+c.length}))},[]),v=Q(()=>{k(c=>{if(c.pos===0)return c;let l=c.text.slice(0,c.pos),i=Kd(l)??l.slice(0,-1);return{text:i+c.text.slice(c.pos),pos:i.length}})},[]),[D,E]=K(!1),[U,L]=K(!1),[G,H]=K(0),[se,qe]=K(!1),[fe,Xe]=K(null),[me,Qe]=K(null),[be,He]=K([]),io=te(!1),vn=te(!1),zr=te(!1),[Kr,Ua]=K(!1),ao=te(0),[Pp,lo]=K(!1),[Tp,co]=K(!1),[Xr,Wa]=K(null),[Dp,Wt]=K(0),xt=te(0),[Qr,Ft]=K(0),[Bt,uo]=K(null),Fa=te(new Map),Ap=te(0),qt=te([]),Oe=te(null);Oe.current===null&&(Oe.current=tp({cwd:e,profileName:s,allowProdWrites:!1}));let Je=te({uuid:null,firstPrompt:null,titleFired:!1}),po=te(new Map),Ba=te(null),Ht=te(!1),Jr=te([]),pe=te([]),Vt=te([]),ho=te(null),[qa,vt]=K(null),Zr=te(null),[Ct,Rt]=K(null),[Ze,Gt]=K(null),[et,Yt]=K(null),[$e,zt]=K(null),[Te,St]=K(null),[at,Kt]=K(null),[lt,Pt]=K(null),[tt,Tt]=K(null),[Ha,Cn]=K(null),[De,Dt]=K(null),[Ce,Xt]=K(null),[Va,es]=K([]),At=te([]),Rn=te(!1),we=te(null),[fo,ie]=K(null),[Ga,mo]=K(null),go=te(!1),Sn=te(null),Pn=te(null),[Ae,Et]=K(null),[yo,Tn]=K(null),ts=!!(et||$e||Te||at||lt||tt||De||Ce||Ae||yo),[Ya,Qt]=K(0),[za,Jt]=K(0),[Ep,Ka]=K(0),ns=Sa(()=>{try{let c=Ia(e);return c.source==="auto"?`${c.model} (auto)`:c.model}catch{return null}},[e,Ep]),{stdout:_e}=Mw(),[,jp]=K(0),Xa=te(`${_e.columns??80}x${_e.rows??24}`),ct=Q(()=>Math.max(20,(_e.columns??80)-1),[_e]),d=Q(c=>{qt.current.push(c),console.log(Is(c,ct()))},[ct]),xe=Q((c,l)=>{ao.current++,Xe(c),Qe(l??null)},[]),Ve=Q(()=>{ao.current++,Xe(null),Qe(null)},[]),Z=Q(c=>xe(c,Dr({kind:"cmd",cmd:c,reason:""})),[xe]),wo=Q((c,l)=>{!l?.silent&&c.note&&d({kind:"note",tone:c.tone,text:c.note}),c.picker&&(He(c.picker.options.map(i=>({cmd:i.cmd,desc:i.desc}))),Cn(c.picker.title)),c.lead&&xe(c.lead.kind==="cmd"?c.lead.cmd:c.lead.text,Dr(c.lead))},[d,xe]),ve=Q((c,l,i="info")=>{c&&d({kind:"note",tone:i,text:c}),l&&xe(l.kind==="cmd"?l.cmd:l.text,Dr(l))},[d,xe]),[Dn,os]=K(null),[Np,Qa]=K(!1),Zt=Q(c=>{os(c),Qa(!1),d({kind:"note",tone:"info",text:"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[d]),rs=te(!1),ss=Q(async()=>{try{if(rs.current||!yk(gk())||ae(e)?.mode==="engineer")return;let c=await mk({pkg:yn,currentVersion:o,force:!0});if(!c.updateAvailable||!c.latest)return;rs.current=!0,d({kind:"note",tone:"info",text:`\u2B06 Updating ${yn} ${c.current} \u2192 ${c.latest}\u2026 (wait for the \u2713 before you /exit)`}),co(!0),(await vr().finally(()=>co(!1))).ok?(d({kind:"note",tone:"ok",text:`\u2713 Updated to v${c.latest} \u2014 run /exit, then relaunch to apply.`}),Z("/exit"),Wa(c.latest)):d({kind:"note",tone:"warn",text:`Update available (v${c.latest}) but auto-update failed \u2014 run: ${xr}`})}catch{}},[e,o,d,Z]),ko=Q(c=>{let l=Ue(e,s);return l.ok?!0:(d({kind:"note",tone:"warn",text:l.reason}),Pn.current=c,Z("/login"),!1)},[e,s,d,Z]),[bo,is]=K(null),jt=Q(c=>{let l=no(e,s,{claudeMissing:Na(t).state==="missing",allowAutoAudit:c,genreUnknown:zr.current});return l?to(l):{kind:"idle"}},[e,s,t]),An=te(!0),en=te(!1),$o=te(0),En=te(0);Ie(()=>{let c=setInterval(()=>{if(An.current){$o.current=0,En.current=0;return}if(!D)try{if(!kn(cp(e)))return;if(Me(e).status==="current"){An.current=!0,$o.current=0,En.current=0;let i=jt(!1),f=i.kind==="recommend"?i.rec:null,P=en.current?`\u2713 Your builder finished the protocol update (v${de}) \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.";d({kind:"note",tone:"ok",text:`${P}${f?.lead?` ${eo(f.lead)}`:""}`}),os(null),f&&(f.lead||f.picker)?wo(f,{silent:!0}):en.current||xe("write the docs for this repo"),H(Y=>Y+1);return}if(en.current)return;$o.current+=1;let l=$o.current;if((l===4||l%15===0)&&En.current<3){En.current+=1;let i=En.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";d({kind:"note",tone:"info",text:rt(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${i}`:`\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.${i}`})}}catch{}},4e3);return()=>clearInterval(c)},[e,D,d,jt,wo,xe]),Ie(()=>{let c=qa??ro(e);if(!D){Lr(0),wn(`${Ur} ${c}`);return}Lr(3);let l=0;wn(`${Mr[0]} ${c}`);let i=setInterval(()=>{l=(l+1)%Mr.length,wn(`${Mr[l]} ${c}`)},400);return()=>clearInterval(i)},[D,e,qa]),Ie(()=>()=>Lr(0),[]),Ie(()=>{let c=performance.now(),l=[],i=(y,w)=>{let g=performance.now();try{return w()}finally{let C=Math.round(performance.now()-g);C>=80&&l.push(`${y}: ${C}ms`)}};d({kind:"banner",info:i("banner",()=>Sk(e,o,t,s))});let f=Na(t).state==="missing";if(f&&d({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.
|
|
391
|
+
${Fw}
|
|
392
|
+
Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!ae(e)){d({kind:"note",tone:"info",text:`Welcome! This repo isn't set up for d360-writer yet \u2014 three steps and you're writing docs:
|
|
393
|
+
${gp}`}),Z(f?"/doctor":"/init");return}f&&Z("/doctor");try{let y=Ne(e,s),w=Ut(y.name);w&&$t(w)&&w.refreshToken?Vw({profile:y.name,connection:y.connection}).then(()=>{d({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),H(g=>g+1)}).catch(()=>{d({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 sign in again with /login."}),Z("/login")}):(!w||$t(w))&&(d({kind:"note",tone:"warn",text:`Profile "${y.name}" is not signed in \u2014 sign in with /login.`}),Z("/login"))}catch{}try{let y=ae(e),w=Ne(e,s),g=Ut(w.name);y&&g&&!$t(g)&&ma(e,y.authoritativeSourceFiles)&&!ga(e,s)&&(d({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),Z("/scope"))}catch{}try{let y=i("resolve-genre",()=>ok(e));y.persisted&&y.appType?d({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"&&ae(e)&&(zr.current=!0)}catch{}let P=Me(e);try{if(i("reconcile-devhints",()=>qo(e)),P.status!=="current"&&!rt(e)){let y=Ho(e);y.length&&(d({kind:"note",tone:"warn",text:y.join(`
|
|
394
|
+
`)}),Zt(Ot()),An.current=!1,en.current=!1)}}catch{}try{let y=i("reconcile-feedback",()=>wk(e));y.archived>0&&d({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=i("upgrade-actions",()=>kk(e));y.applied.length>0&&d({kind:"note",tone:"warn",text:Ko(y.applied).join(`
|
|
395
|
+
`)})}catch{}let Y=i("ready-decision",()=>jt(!0));Y.kind==="autoAudit"?(d({kind:"note",tone:"info",text:Y.note}),Yn().then(y=>{y.kind==="forward-to-agent"&&y.prompt&&re(y.prompt,{display:y.display,quietUser:!0})})):Y.kind==="recommend"&&wo(Y.rec);let h=Math.round(performance.now()-c);h>=800&&$k({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${h}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${l.length?l.join(`
|
|
394
396
|
`):"no single phase \u226580ms"}
|
|
395
|
-
cwd: ${e}`}),ss()},[]),
|
|
396
|
-
|
|
397
|
-
${
|
|
398
|
-
`)});let A=
|
|
399
|
-
`)})}},[e,s,d,
|
|
400
|
-
${Fi(
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
`)}),
|
|
405
|
-
`)}),
|
|
406
|
-
${
|
|
407
|
-
`)})};switch(i){case"help":
|
|
408
|
-
`)});return}case"mcp":await zo(f);return;case"init":{if(
|
|
409
|
-
`:"",
|
|
410
|
-
Model: ${
|
|
411
|
-
`)+
|
|
412
|
-
`)})}}catch(M){d({kind:"note",tone:"error",text:`Convert run failed: ${M.message}`})}finally{we.current=null,
|
|
397
|
+
cwd: ${e}`}),ss()},[]),Ie(()=>{let c=setInterval(()=>{ss()},Ok);return()=>clearInterval(c)},[ss]),Ie(()=>{if(D||se||Kr||io.current||vn.current||fe!==null||be.length>0||$!==""||Dn!==null||pe.current.length>0||ho.current||ts)return;let c=jt(!1);c.kind==="recommend"&&(c.rec.lead||c.rec.picker)&&wo(c.rec,{silent:!0})},[D,se,fe,be,$,Dn,ts,G,jt,Kr]),Ie(()=>{let c=null,l=null,i=()=>{c&&clearTimeout(c),c=setTimeout(()=>{c=null;let f=`${_e.columns??80}x${_e.rows??24}`;f!==Xa.current&&(Xa.current=f,jp(P=>P+1),l&&clearTimeout(l),l=setTimeout(()=>{l=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+lc(qt.current,ct())+"\x1B[?2026l")},80))},400)};return _e.on("resize",i),()=>{c&&clearTimeout(c),l&&clearTimeout(l),_e.off("resize",i)}},[_e,ct]);let Ge=Math.max(20,(_e.columns??80)-1),Ja=Sa(()=>Pk(e,s),[e,s,G]),as=(()=>{if(Tp)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(Xr!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${Xr?` v${Xr}`:""}\u2026`,isSetup:!0};if(bo)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(Dn)return Np?{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 above \u2014 then paste it into your coding agent\u2026",isSetup:!0};if(pe.current.length>0)return pe.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 c=ae(e);if(!c)return{text:"Run /init to set up this repo (or /help)\u2026",isSetup:!0};let l=Pa(e,(c.docsDir??Oa).replace(/\/+$/,"")),i=(()=>{try{return kn(l)&&Uw(l).length>0}catch{return!1}})();try{let f=Ne(e,s),P=Ut(f.name);if(!(!!P&&!($t(P)&&!P.refreshToken)))return{text:`Sign in with /login (profile "${f.name}")\u2026`,isSetup:!0};if(!f.project.projectId)return{text:"Sign in to Document360 to pick your project\u2026",isSetup:!0};if(!f.project.workspaceId&&!i)return{text:"Pick a workspace with /workspace\u2026",isSetup:!0}}catch{}return i?{text:Tk,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),Ye=Zl($),Za=Ye.length>0&&!D,xo=Math.max(3,Math.min(12,(_e.rows??24)-8)),vo=Math.min(Qr,Math.max(0,Ye.length-1)),Nt=Ye.length<=xo?0:Math.min(Math.max(0,vo-Math.floor(xo/2)),Ye.length-xo),ls=Ye.slice(Nt,Nt+xo),cs=u!==null?Jd(u,8,Ge):null,Co=De?De.paths.filter(c=>!De.query||c.toLowerCase().includes(De.query.toLowerCase())).slice(0,8):[],Ro=Ae?Ae.sessions.filter(c=>{let l=Ae.query.toLowerCase();return!l||c.name.toLowerCase().includes(l)||c.firstPrompt.toLowerCase().includes(l)}).slice(0,8):[],Ee=Q((c,l)=>{Oe.current?.close(),Oe.current=tp({cwd:e,resume:c,profileName:l??s,allowProdWrites:Ht.current}),c||(Je.current={uuid:null,firstPrompt:null,titleFired:!1},vt(null)),Qt(0),Jt(0)},[e,s]),el=Q((c,l,i)=>{if(Dk.test(c))try{let f=Ne(e,s),P=typeof l.project_id=="string"&&l.project_id||f.project.projectId,Y=Ir(l,i),h=[],y=Or(i);c.endsWith("publish_article")&&y&&h.push(`Live: ${y}`);let w=_r(i);w?h.push(`Preview: ${w}`):Y&&P&&h.push(`Preview: ${Nr(f.connection.portalUrl,P,Y,f.project.languageCode??"en")}`),h.length>0&&d({kind:"link",lines:h})}catch{}},[e,s,d]),re=Q(async(c,l)=>{lo(!0),io.current=!1,vn.current=!1,Ve(),He([]),Cn(null),os(null);let i=ao.current;if(l?.display?.startsWith("/"))try{let R=hd(e,l.display);R&&(c=`${c}
|
|
398
|
+
|
|
399
|
+
${R}`)}catch{}l?.quietUser||d({kind:"user",text:l?.echoDisplay&&l.display?l.display:c});let f=Je.current;f.firstPrompt||(f.firstPrompt=l?.display??c),xt.current=Date.now(),Wt(0),E(!0),po.current.clear();let P="",Y=!1,h=!1,y="",w={num:0,closed:!1,cueSeen:!1},g=null,C=()=>{g||(g=setTimeout(()=>{g=null,p(y.length>0?y:null)},60))},A=()=>{g&&clearTimeout(g),g=null,p(null)},F=(R=!1)=>{let{head:q,keep:M}=Zd(y,R);q.trim()&&d({kind:"assistant",text:xa(q.trimEnd(),w)}),y=M,A()};try{for await(let R of Oe.current.send(c))if(R.type==="session"){if(!f.uuid){f.uuid=R.sessionId;let q=new Date().toISOString(),M=Zr.current,T=M??Qw(f.firstPrompt??"session");Jw({uuid:R.sessionId,name:T,renamed:!!M,titled:!1,cwd:e,firstPrompt:f.firstPrompt??"",createdAt:q,updatedAt:q}),vt(T),Zr.current=null}}else if(R.type==="text"){y+=R.delta,P+=R.delta;let q=ep(y);if(q>0){let M=y.slice(0,q).trimEnd();M&&d({kind:"assistant",text:xa(M,w)}),y=y.slice(q)}C(),Wt(M=>M+R.delta.length)}else if(R.type==="tool"){Y=!0;let M=(oe=>typeof oe=="string"&&oe?oe.replace(/\\/g,"/").toLowerCase():null)(R.input.file_path??R.input.notebook_path),T=["Edit","Write","MultiEdit","NotebookEdit"].includes(R.name),V=R.name==="Read"&&M!==null&&M===Ba.current;if(Ba.current=T?M:null,V)F(),d({kind:"tool",title:"Read",sep:"",arg:"(re-checking the file it just edited)"});else{let oe=Er(R.name,R.input,e);oe&&(F(),d({kind:"tool",title:oe.title,sep:oe.sep,arg:oe.arg}),po.current.set(R.id,{name:R.name,input:R.input}))}}else if(R.type==="article_diff"){let q=it(R.oldContent,R.newContent,ct());q&&(F(),d({kind:"diff",added:q.added,removed:q.removed,lines:q.lines,hidden:q.hidden}))}else if(R.type==="tool_result"){R.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(R.output)&&(go.current=!0);let q=po.current.get(R.id);if(q){po.current.delete(R.id),F();let M=jr(R.output,4,R.isError?void 0:q.name,q.input);d({kind:"tool-result",lines:M.lines,hidden:M.hidden,isError:R.isError}),R.isError||el(q.name,q.input,R.output)}}else if(R.type==="result"){F(!0),Qt(M=>M+R.outputTokens),Jt(M=>M+R.costUsd);let q=R.inputTokens+R.cacheReadTokens+R.cacheCreationTokens;if(d({kind:"done",seconds:Math.round((Date.now()-xt.current)/1e3),tokens:R.outputTokens,costUsd:R.costUsd,ok:R.ok,...q>0?{inTokens:q,cachedPct:Math.round(R.cacheReadTokens/q*100)}:{}}),!h&&!Y&&!P.trim()&&!Rn.current&&d({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)."}),R.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(P))try{let M=up(e);if(kn(M)){let T=Hr(M,"utf8").trim();T&&(is(T),d({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(vn.current=R.ok&&/\?[\s*_"')\]]*$/.test(P.trimEnd()),R.ok&&w.cueSeen)Ua(!0),He([]);else{let M=R.ok?Ud(P,dn.map(T=>T.name)):[];if(M.length>0)Z(M[0]);else if(R.ok&&P.trim()&&!vn.current){let T=jt(!1);T.kind==="recommend"&&(T.rec.lead||T.rec.picker)||nk(c,P,e).then(V=>{V&&ao.current===i&&xe(V)}).catch(()=>{})}}if(f.uuid&&(Ta(f.uuid),!f.titleFired)){f.titleFired=!0;let M=f.uuid,T=f.firstPrompt;T&&np(T,e).then(V=>{V&&(Xw(M,V),vt(V))}).catch(()=>{})}}else R.type==="error"&&(F(!0),h=!0,R.kind==="auth"&&(go.current=!0),d({kind:"note",text:`agent error: ${R.message}`,tone:"error"}))}finally{E(!1),A(),H(R=>R+1),Je.current.uuid&&Od(e,Je.current.uuid,qt.current),go.current?(go.current=!1,Sn.current=l?.display??c,xe("/login","\u21E5 tab to run /login \u2014 then I\u2019ll re-send your last prompt\u2026")):Sn.current=null,Rn.current&&(Rn.current=!1,At.current.length>0&&(d({kind:"note",tone:"info",text:`(${At.current.length} queued message(s) discarded)`}),At.current=[],es([])),d({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,d,el,ct,xe,Z,Ve,jt]),It=Q(async c=>{let l=Gr(e,"standard");xt.current=Date.now(),Wt(0),E(!0);let i=new AbortController;we.current=i;let f=async(P,Y)=>{let h=Aa(P);ie({verb:"Publishing",total:h.length,done:0,active:[],rows:oo(h),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:Y?`Resolving cross-links in ${P.length} article${P.length===1?"":"s"} whose targets published this run (second pass)\u2026 (esc to stop)`:`Publishing ${P.length} article${P.length===1?"":"s"} across ${h.length} partition${h.length===1?"":"s"} (\u2264${Vn} agents at once) on ${l.model}\u2026 (esc to stop)`});let y=!1;for await(let w of Vr({cwd:e,partitions:h,promptFor:g=>Gn(g.paths),concurrency:Vn,profileName:s,allowProdWrites:Ht.current,model:l.model,signal:i.signal}))if(w.type==="partition_status")w.status==="running"?ie(g=>g&&{...g,active:[...g.active,w.label],rows:Fe(g.rows,w.label,"active"),lastAt:Date.now()}):ie(g=>g&&{...g,active:g.active.filter(C=>C!==w.label),done:g.done+1,rows:Fe(g.rows,w.label,w.status==="done"?"done":"failed"),lastAt:Date.now()});else if(w.type==="partition_event")ie(g=>{if(!g)return g;let C={...g,lastAt:Date.now()};return w.event.type==="tool"?C.tools=g.tools+1:w.event.type==="text"&&(C.chars=g.chars+w.event.delta.length),C});else if(w.type==="run_done"){y=w.aborted,Jt(F=>F+w.totalCostUsd),Qt(F=>F+w.results.reduce((R,q)=>R+q.outputTokens,0));let g=w.aborted?"Stopped. ":"",C=t.kind==="api"?"api":"subscription";d({kind:"note",tone:w.aborted?"warn":w.ok?"ok":"warn",text:g+Xs(w.results,h,C).join(`
|
|
400
|
+
`)});let A=Ks(e,s);if(A&&d({kind:"note",tone:"info",text:A}),!w.aborted){try{let F=await pp({cwd:e,profileName:s}),R=hp(F);R?d({kind:"note",tone:"info",text:R}):F.skipped&&d({kind:"note",tone:"warn",text:`Order sync skipped: ${F.skipped}`})}catch(F){d({kind:"note",tone:"warn",text:`Order sync failed: ${F.message}`})}try{let F=mp(await fp({cwd:e,profileName:s}));F&&d({kind:"note",tone:"info",text:F})}catch(F){d({kind:"note",tone:"warn",text:`Related-articles sync failed: ${F.message}`})}}}return y};try{if(!await f(c,!1)){let Y=await Qs(e,s,c);Y.length>0&&await f(Y,!0)}}catch(P){d({kind:"note",tone:"error",text:`Publish run failed: ${P.message}`})}finally{we.current=null,ie(null),E(!1),H(P=>P+1)}},[e,s,d,t]),us=Q(async c=>{await re(Ys(c),{display:`/publish ${c}`,quietUser:!0});try{let l=await ur(e,s,c.replace(/\\/g,"/"));l.length>0&&(Cn(`Related articles not yet published (${l.length}):`),He([`/publish --related ${c}`,...l.map(i=>`/publish ${i}`)]))}catch{}},[e,s,re]),So=Q(c=>{if(c)try{for(let l of Array.isArray(c)?c:[c]){let i=ua(e,l);if(!i)continue;Tr(e,i.title).ok&&d({kind:"note",tone:"ok",text:`\u2713 That completed a docs-campaign step \u2014 marked done: ${i.title}`});return}}catch{}},[e,d]),tl=Q(async(c,l)=>{let f=dk(c,3),P=Gr(e,"standard"),Y=new Map;for(let w of c){let g=Ls(e,w,nr(e,w));g&&Y.set(w,g)}xt.current=Date.now(),Wt(0),E(!0);let h=new AbortController;we.current=h,ie({verb:"Authoring",unit:"spec",total:f.length,done:0,active:[],rows:oo(f),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Authoring ${c.length} screenshot spec${c.length===1?"":"s"} across ${f.length} partition${f.length===1?"":"s"} (\u22646 agents at once) on ${P.model}${P.forced?" (forced)":""}\u2026 (esc to stop)`});let y=!1;try{for await(let w of Vr({cwd:e,partitions:f,promptFor:g=>jc(g,Y),concurrency:6,profileName:s,allowProdWrites:Ht.current,model:P.model,signal:h.signal}))if(w.type==="partition_status")w.status==="running"?ie(g=>g&&{...g,active:[...g.active,w.label],rows:Fe(g.rows,w.label,"active"),lastAt:Date.now()}):ie(g=>g&&{...g,active:g.active.filter(C=>C!==w.label),done:g.done+1,rows:Fe(g.rows,w.label,w.status==="done"?"done":"failed"),lastAt:Date.now()});else if(w.type==="partition_event")ie(g=>{if(!g)return g;let C={...g,lastAt:Date.now()};return w.event.type==="tool"?C.tools=g.tools+1:w.event.type==="text"&&(C.chars=g.chars+w.event.delta.length),C});else if(w.type==="run_done"){Jt(F=>F+w.totalCostUsd),Qt(F=>F+w.results.reduce((R,q)=>R+q.outputTokens,0));let g=w.results.filter(F=>F.ok).length,C=w.aborted?"Stopped. ":"";y=!w.aborted&&l.setup;let A=w.aborted?"":y?" Refreshing the capture-setup checklist\u2026":" Next: /screenshot capture --all (or /screenshot checklist first for the staging checklist).";d({kind:"note",tone:w.aborted?"warn":w.ok?"ok":"warn",text:`${C}Authored specs \u2014 ${g}/${w.results.length} batches ok.${A}`}),!w.aborted&&w.ok&&So(l.runLine)}}catch(w){d({kind:"note",tone:"error",text:`Spec authoring failed: ${w.message}`})}finally{we.current=null,ie(null),E(!1),H(w=>w+1)}if(y){let w=await gn();w.kind==="forward-to-agent"&&w.prompt&&await re(w.prompt,{display:w.display,quietUser:!0});let g=Gi(e);g&&d({kind:"note",tone:"info",text:g.join(`
|
|
401
|
+
`)})}},[e,s,d,re,So]),nl=Q(async c=>{let l=Ls(e,c,nr(e,c))??void 0,i=await sr([c],void 0,{lastFailure:l});i.kind==="forward-to-agent"&&i.prompt&&await re(i.prompt,{display:i.display,quietUser:!0}),$c(e,c)&&ve(`Spec ready \u2014 /screenshot capture ${c} takes the screenshot; bare /screenshot picks the next shot.`,{kind:"cmd",cmd:`/screenshot capture ${c}`,reason:""})},[e,re,ve]),Po=Q(async(c,l)=>{if(!br(e)){await re(Hi(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(!Mu(e)){d({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)"}),E(!0),mo("Waiting for you to finish logging in (browser window)\u2026");let T=new AbortController;we.current=T;let V;try{V=await Uu({cwd:e,signal:T.signal})}catch(oe){d({kind:"note",tone:"error",text:`Could not launch the login: ${oe.message}`});return}finally{we.current=null,mo(null),E(!1)}if(V.exitCode!==0){qi(V.exitCode,V.output)?d({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(V.output)?d({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."}):d({kind:"note",tone:T.signal.aborted?"warn":"error",text:T.signal.aborted?"Login cancelled \u2014 nothing saved.":`Login did not complete:
|
|
402
|
+
${Fi(V.output)}`});return}d({kind:"note",tone:"ok",text:"\u2713 Login saved \u2014 continuing with the capture."})}let i=new Map(c.map(T=>[T,Cc(e,T)])),f=0;if(c.length>1){let T=c.filter(V=>i.get(V).mutates);if(T.length>0&&(f=T.length,c=c.filter(V=>!i.get(V).mutates),c.length===0)){d({kind:"note",tone:"warn",text:`\u26A0 All ${T.length} spec${T.length===1?"":"s"} in scope write real data, so a bulk run has nothing to do. Run one deliberately: /screenshot capture ${T[0]}`});return}}else if(c.length===1&&i.get(c[0]).mutates){let T=i.get(c[0]),V=Wu(e);d({kind:"note",tone:"warn",text:`\u26A0 This capture performs a REAL write in your app${T.what?`: ${vc(T.what)}`:T.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. `+(V.production?`This profile is PRODUCTION \u2014 the write lands in the LIVE tenant${V.url?` (${V.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.")})}E(!0);let P=new AbortController;we.current=P;let Y=c.map(T=>({label:T,items:1,status:"pending"}));ie({verb:"Capturing",unit:"screenshot",total:c.length,done:0,active:[],rows:Y,tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()});let h=_t(e),y=Object.keys(h.shots).length>0,w=Fu(We(e).filter(T=>!c.includes(T.id)),f);d({kind:"note",tone:"info",text:`Capturing ${c.length} screenshot${c.length===1?"":"s"} with d360-capture (a real browser drives your app)\u2026 (esc to stop)`+(w?`
|
|
403
|
+
${w}`:"")});let g=Date.now(),C=[];try{for(let T of c){if(P.signal.aborted)break;ie(Re=>Re&&{...Re,active:[T],rows:Fe(Re.rows,T,"active"),lastAt:Date.now()});let{exitCode:V,output:oe}=await Bi({cwd:e,id:T,signal:P.signal,stdio:"pipe"});if(qi(V,oe)){d({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 nt=P.signal.aborted&&V!==0?"failed":Wi(e,T,V,g),on=nt==="captured"?void 0:nt==="skipped"?_u(oe)??"a data prerequisite isn't met \u2014 the spec's skip reason names what to stage":Lu(oe);C.push({id:T,outcome:nt,detail:on}),ie(Re=>Re&&{...Re,active:[],done:Re.done+1,rows:Fe(Re.rows,T,nt==="captured"?"done":"failed"),lastAt:Date.now()})}}catch(T){d({kind:"note",tone:"error",text:`Capture run failed: ${T.message}`})}finally{we.current=null,ie(null),E(!1),H(T=>T+1)}if(C.length===0)return;let A=C.filter(T=>T.outcome==="captured"),F=C.filter(T=>T.outcome==="skipped"),R=C.filter(T=>T.outcome==="failed"),q=c.length-C.length;if(d({kind:"note",tone:R.length?"warn":A.length?"ok":"info",text:[`\u2713 ${A.length} captured`,F.length?`\u2298 ${F.length} blocked`:"",R.length?`\u2717 ${R.length} broken`:"",q?`${q} not run (stopped)`:""].filter(Boolean).join(" ")+` ${C.length} run${f>0?` \xB7 ${f} held back`:""}`+Hu(Bu(h,C),y).map(T=>`
|
|
404
|
+
${T}`).join("")}),R.length>0){let T=Math.max(...R.map(V=>V.id.length));d({kind:"note",tone:"error",text:R.map(V=>`\u2717 ${V.id.padEnd(T)} ${qu(V.detail)}`).join(`
|
|
405
|
+
`)})}hc(e,C.map(T=>({id:T.id,outcome:T.outcome,reason:T.detail,specSource:nr(e,T.id)})),new Date().toISOString());let M=Vu({results:C,ids:c,articles:Gu(e,A.map(T=>T.id))});M&&ve(M.note,{kind:"cmd",cmd:M.cmd,reason:""},M.tone),C.length===c.length&&R.length===0&&F.length===0&&So(l?.runLine)},[e,d,ve,re,So]),ds=Q(c=>{let l=Ut(c);if(!l||$t(l)&&!l.refreshToken)return null;let i={...$n(l.idToken)??{},...$n(l.accessToken)??{}};return i.email??i.preferred_username??"signed in"},[]),ps=Q((c,l)=>{if(l){let i=ae(e);i&&(i.defaultProfile=c,op(i,e))}a(c),Ee(void 0,c),d({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${c}"${l?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),ds(c)||(d({kind:"note",tone:"warn",text:`Profile "${c}" is not signed in \u2014 sign in with /login.`}),Z("/login")),H(i=>i+1)},[e,d,Ee,ds,Z]),To=Q((c,l,i)=>{No(e,c,l,i.id,i.name),d({kind:"note",tone:"ok",text:`Switched to workspace "${i.name??i.id}" (agent restarted).`}),Ee(),rp(e,c)||(d({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),d({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:"}),d({kind:"note",tone:"info",text:cn(ln(e)).join(`
|
|
406
|
+
`)}),Zt(Ot()),An.current=Me(e).status==="current",en.current=rt(e),d({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,d,Ee,Zt]),Do=Q(async c=>{let l;try{l=await _n(e,c)}catch{d({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),Z("/workspace");return}if(l.workspaces.length===0){d({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let i=l.workspaces.filter(P=>(P.workspace_type??"").toLowerCase()!=="apidocumentation"),f=i.length>0?i:l.workspaces;if(f.length===1){let P=f[0],Y=l.workspaces.length-f.length;d({kind:"note",tone:"ok",text:`Selected the "${P.name??P.id}" workspace${Y>0?" (skipped the API-documentation workspace)":""}.`}),To(l.profile,l.projectId,P);return}d({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${f.length} available).`}),Z("/workspace")},[e,d,To,Z]),Ao=Q((c,l)=>{Io(e,c,l.id,l.name),d({kind:"note",tone:"ok",text:`Project set to "${l.name??l.id}" (agent restarted).`}),Ee(),Do(c)},[e,d,Ee,Do]),ol=Q(async c=>{let l;try{l=Ne(e,c)}catch{return}if(!l.project.workspaceId){if(l.project.projectId){if(!l.project.projectName)try{let{projects:i}=await pt(e,l.name),f=i.find(P=>P.id===l.project.projectId);f?.name&&bk(e,l.name,{projectName:f.name})}catch{}await Do(l.name);return}try{let{projects:i}=await pt(e,l.name);if(i.length===1){let f=i[0];d({kind:"note",tone:"ok",text:`Using your Document360 project "${f.name??f.id}".`}),Ao(l.name,{id:f.id,name:f.name});return}if(i.length>1){let f=i.map(P=>({id:P.id,name:P.name??P.id,sub:P.sub_domain}));d({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),St({cursor:0,current:-1,rows:f,profile:l.name,environment:l.connection.name});return}}catch{}d({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),Z("/project")}},[e,d,Do,Ao,Z]),tn=Q(()=>{let c=pe.current[0];if(!c)return;Ve();let{plan:l,mode:i}=c;d({kind:"note",tone:"info",text:`\u25CF ${l.title} (${l.path})`});for(let P of l.notes)d({kind:"note",tone:"warn",text:`\u26A0 ${P}`});l.overwritesLocalChanges&&i==="pull"&&d({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let f=it(l.oldContent,l.newContent,ct());d(f?{kind:"diff",added:f.added,removed:f.removed,lines:f.lines,hidden:f.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."}),i==="conflict"?(d({kind:"note",tone:"warn",text:"Conflict \u2014 edited both here and on the portal (diff shows local \u2192 portal)."}),d({kind:"note",tone:"info",text:"Keep local (publish, overwrites portal) \xB7 take Portal (overwrites local) \xB7 Skip? (l/p/s \u2014 anything else cancels)"})):d({kind:"note",tone:"info",text:`Write ${l.path}? (y/n \u2014 anything else cancels)`})},[d,ct,Ve]),hs=Q(()=>{if(pe.current.length>0){tn();return}let c=Vt.current;Vt.current=[],c.length>0?(d({kind:"note",tone:"info",text:`Publishing ${c.length} kept-local article${c.length===1?"":"s"} over the portal\u2026`}),It(c)):Z("/pull")},[tn,d,It,Z]),rl=Q(c=>{if(pe.current.length===0)return!1;let l=c.trim().toLowerCase(),i=pe.current[0];if(i.mode==="conflict"){if(l==="l"||l==="local")pe.current.shift(),Vt.current.push(i.plan.path),d({kind:"note",tone:"info",text:`Keeping local ${i.plan.path} \u2014 will publish over the portal.`});else if(l==="p"||l==="portal"){pe.current.shift();try{sp({cwd:e,profileName:s},i.plan),d({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${i.plan.path} (local overwritten, sync base advanced).`})}catch(f){d({kind:"note",tone:"error",text:`Take-portal failed: ${f.message}`})}}else if(l==="s"||l==="skip"||l==="n")pe.current.shift(),d({kind:"note",tone:"info",text:`Skipped ${i.plan.path} \u2014 still a conflict.`});else{let f=pe.current.length;return pe.current=[],Vt.current=[],d({kind:"note",tone:"info",text:`Resolve cancelled (${f} conflict${f===1?"":"s"} left untouched).`}),!0}return hs(),!0}if(l==="y"||l==="yes"){let f=pe.current.shift().plan;try{sp({cwd:e,profileName:s},f),d({kind:"note",tone:"ok",text:`\u2713 Pulled ${f.path} (sync base advanced).`})}catch(P){d({kind:"note",tone:"error",text:`Pull failed: ${P.message}`})}}else if(l==="n"||l==="no"){let f=pe.current.shift().plan;d({kind:"note",tone:"info",text:`Skipped ${f.path}.`})}else{let f=pe.current.length;return pe.current=[],d({kind:"note",tone:"info",text:`Pull cancelled (${f} article(s) left untouched).`}),!0}return hs(),!0},[e,s,hs,d]),fs=Q(async c=>{d({kind:"note",tone:"info",text:"Checking Document360 for conflicts\u2026"});try{let l=await Da({cwd:e,profileName:s}),i=c?.replace(/\\/g,"/"),f=l.entries.filter(Y=>Y.status==="conflict"&&Y.path).map(Y=>Y.path);if(i){if(!f.includes(i)){d({kind:"note",tone:"ok",text:`${i} isn\u2019t in conflict \u2014 nothing to resolve.`});return}f=[i]}if(f.length===0){d({kind:"note",tone:"ok",text:"\u2713 No conflicts \u2014 local and Document360 agree on every tracked article."});return}let P=[];for(let Y of f)try{P.push({plan:await ap({cwd:e,profileName:s,relPath:Y}),mode:"conflict"})}catch(h){d({kind:"note",tone:"error",text:`Could not load ${Y} from Document360: ${h.message}`})}if(P.length===0)return;d({kind:"note",tone:"info",text:`Resolving ${P.length} conflict${P.length===1?"":"s"} \u2014 for each: keep local, take portal, or skip.`}),pe.current=P,Vt.current=[],tn()}catch(l){d({kind:"note",tone:"error",text:`Could not compute sync status: ${l.message}`})}},[e,s,d,tn]),sl=Q(c=>{let l=ho.current;if(!l)return!1;if(ho.current=null,Ve(),c.trim()!==l.repoName)return d({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:i,failed:f}=oa(e,l.targets);d({kind:"note",tone:f.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${i.length} item${i.length===1?"":"s"}. The repo is back to its original state.`});for(let P of f)d({kind:"note",tone:"error",text:` \u2717 ${P.path}: ${P.error}`});return l.hadDevhints&&(d({kind:"note",tone:"warn",text:Vo().join(`
|
|
407
|
+
`)}),Zt(vs())),d({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
|
|
408
|
+
${gp}`}),Z("/init"),lo(!1),!0},[e,d,Zt,Ve,Z]),jn=Q(async c=>{let l=c.slice(1).trim().split(/\s+/),i=(l[0]??"").toLowerCase(),f=l.slice(1);if(lo(!0),fr(f)&&["write","check","review","reorder"].includes(i)){let h=zn(e,s);if(h.length===0){d({kind:"note",tone:"warn",text:"No categories yet \u2014 author some articles first, then scope to one."});return}let y=w=>i==="write"?`/write ${nu(f,w).join(" ")}`.trim():`/${i} ${[w,...f.filter(g=>g!=="--scope")].join(" ")}`.trim();if(h.length===1){jn(y(h[0].token));return}Tt({cursor:0,rows:h,run:w=>{jn(y(w))}});return}if(kt(i,f)){let h=zn(e,s);if(h.length>1){let y=f.filter(A=>A.startsWith("--")).join(" "),w=A=>`/${i}${A?` ${i==="write"?`--scope ${A}`:A}`:""}${y?` ${y}`:""} ${A?"":"--all"}`.replace(/\s+/g," ").trim(),g=h.reduce((A,F)=>A+F.count,0),C={token:"",label:i==="review"?`Everything \u2014 all ${g} articles + structure (IA) review`:i==="reorder"?`Everything \u2014 reorder all ${h.length} categories`:`Everything \u2014 rewrite all ${g} planned articles`,count:g};Tt({cursor:0,rows:[C,...h],run:A=>{jn(w(A))}});return}}let P=async h=>{let y=Li(h);if(!br(e)){await re(Hi(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(y.mode==="single"){await Po([y.id],{runLine:[`/screenshot capture ${y.id}`,`/capture ${y.id}`]});return}if(y.mode==="failed"){let g=Mi(e,kr(e).rows);if(g.length===0){d({kind:"note",tone:"info",text:"No broken specs to re-run \u2014 /screenshot list shows where things stand."}),Z("/screenshot list");return}await Po(g);return}if(y.mode==="all"||y.mode==="scope"){let g=y.mode==="scope"?y.scope:void 0,{ready:C,captured:A,blocked:F,rows:R}=kr(e,g),q=[...C,...A,...y.retryBlocked?F:[]];if(q.length===0&&F.length>0&&!y.retryBlocked){let T=g?`/screenshot capture ${g} --retry-blocked`:"/screenshot capture --all --retry-blocked";ve(`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 ${T}.`,{kind:"cmd",cmd:"/screenshot list",reason:""},"warn");return}if(q.length===0){d({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),Z("/screenshot");return}if(!y.retryBlocked){let T=g?`/screenshot capture ${g} --retry-blocked`:"/screenshot capture --all --retry-blocked",V=Ui(R.filter(oe=>oe.state==="blocked"),T);V&&d({kind:"note",tone:"info",text:V})}let M=y.mode==="scope"?[`/screenshot capture ${y.scope}`,`/capture ${y.scope}`]:["/screenshot capture --all","/capture --all"];await Po(q,{runLine:M});return}let w=Ou(We(e));if(w.length===0){d({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),Z("/screenshot");return}Pt({cursor:0,rows:w,title:"Capture screenshots \u2014 pick what to shoot:"})},Y=async()=>{let h=await gn();h.kind==="forward-to-agent"&&h.prompt&&await re(h.prompt,{display:h.display,quietUser:!0});let y=Gi(e);y&&d({kind:"note",tone:"info",text:y.join(`
|
|
409
|
+
`)})};switch(i){case"help":Tn({tab:0});return;case"exit":case"quit":Oe.current?.close(),r();return;case"clear":Ee(),qt.current=[],lo(!1),Ve(),console.log("\x1B[?2026h\x1B[H\x1B[2J\x1B[3J\x1B[?2026l"),d({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let h;try{h=Ne(e,s)}catch(y){d({kind:"note",tone:"error",text:y.message});return}d({kind:"note",tone:"info",text:`Profile "${h.name}" \u2192 ${h.connection.name} (${h.connection.apiUrl})${h.production?" \u26A0 PRODUCTION":""}`}),L(!0);try{let y=await Bw(h.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},g=>d({kind:"note",tone:"info",text:g})),w=qw(h.name,y);if(Hw(w),await ws(w,h.name,g=>d({kind:"note",tone:"info",text:g})),d({kind:"note",tone:"ok",text:`\u2713 Logged in to "${h.name}" as ${Lo(w)}`}),await ol(s),Pn.current){let g=Pn.current;Pn.current=null;let C=Ue(e,s);C.ok?(d({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 tab to run ${g}.`}),Z(g)):(d({kind:"note",tone:"warn",text:`${C.reason} (then ${g}.)`}),Z("/login"),Pn.current=g)}else Sn.current&&(xe(Sn.current,"\u21E5 tab to re-send your last prompt\u2026"),Sn.current=null)}catch(y){d({kind:"note",tone:"error",text:`Login failed: ${y.message}`})}finally{L(!1),H(y=>y+1)}return}case"allow-prod":{let h=!1;try{h=Ne(e,s).production}catch{}if(!h){d({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}Ht.current=!0,Ee(),d({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let h=Di(f.join(" ")),y=Je.current.uuid;if(!y){if(!h){d({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}Zr.current=h,vt(h),wn(`${Ur} ${h}`),d({kind:"note",tone:"ok",text:`Session will be named "${h}" once it starts.`});return}if(!h){d({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let w=Je.current.firstPrompt??"";np(w,e).then(g=>{g?(xe(`/rename ${g}`),d({kind:"note",tone:"info",text:`Suggestion: "${g}" \u2014 press tab to accept, or type /rename <your name>.`})):d({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>d({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}tk(y,h),vt(h),wn(`${Ur} ${h}`),d({kind:"note",tone:"ok",text:`Session renamed to "${h}".`});return}case"profile":{let h=f[0],y=ae(e);if(!h){let w=Object.entries(y?.profiles??{});if(w.length===0){d({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let g=w.map(([F,R])=>({name:F,env:R.connection?.environment??"custom",prod:R.production===!0,who:ds(F)})),C=s??y?.defaultProfile,A=Math.max(0,g.findIndex(F=>F.name===C));Gt({cursor:A,current:A,rows:g});return}if(h==="add"){let w=Ai(e,f[1],f[2]);if(w){d({kind:"note",tone:"error",text:w});return}d({kind:"note",tone:"ok",text:`\u2713 Profile "${f[1]}" created (environment: ${f[2]??f[1]}).`}),ps(f[1],!1);return}if(!y?.profiles?.[h]){d({kind:"note",tone:"error",text:`Unknown profile "${h}". Create it: /profile add ${h} <environment>`});return}ps(h,!0);return}case"doctor":await Xn(f,{cwd:e,version:o});return;case"genre":{await Sr(f,{cwd:e});try{zr.current=!(ae(e)?.appType??rk(e))}catch{}H(h=>h+1);return}case"roadmap":{if(f[0]?.toLowerCase()==="done"){let h=Tr(e,f.slice(1).join(" ").trim());d({kind:"note",tone:h.ok?"ok":"warn",text:h.line}),H(y=>y+1);return}d({kind:"note",tone:"info",text:ca(e).join(`
|
|
410
|
+
`)});return}case"mcp":await zo(f);return;case"init":{if(ae(e)){d({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 h=ck().map(y=>({name:y,apiUrl:uk(y).apiUrl}));Yt({cursor:0,rows:h});return}case"resume":{let h=f.join(" ").trim(),y=ek(e).filter(C=>C.uuid!==Je.current.uuid);if(!h){if(!y.length){d({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}Et({query:"",cursor:0,sessions:y});return}let w=Zw(e,h);if(!w){d({kind:"note",tone:"error",text:`No session matches "${h}".`});return}Ee(w.uuid),Je.current={uuid:w.uuid,firstPrompt:w.firstPrompt,titleFired:!0},vt(w.name),Ta(w.uuid),qt.current=[];let g=va(e,w.uuid);for(let C of g)d(C);d({kind:"note",tone:"ok",text:g.length?`Resumed "${w.name}" \u2014 restored ${g.length} message(s); continue where you left off.`:`Resumed "${w.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let h=f.join(" ").trim(),y;try{y=await _n(e,s)}catch(g){d({kind:"note",tone:"error",text:`Could not list workspaces: ${g.message}`});return}if(!h){let g=y.workspaces.map(A=>({id:A.id,name:A.name??A.id,type:A.workspace_type}));if(g.length===0){d({kind:"note",tone:"info",text:"No workspaces in this project."});return}let C=Math.max(0,g.findIndex(A=>A.id===y.current));zt({cursor:C,current:C,rows:g,profile:y.profile,projectId:y.projectId,projectName:y.projectName,environment:y.environment});return}let w=gs(y.workspaces,h);if(!w){d({kind:"note",tone:"error",text:`No workspace matches "${h}".`});return}To(y.profile,y.projectId,w);return}case"project":{let h=f.join(" ").trim(),y;try{y=await pt(e,s)}catch(g){d({kind:"note",tone:"error",text:`Could not list projects: ${g.message} (signed in? try /login)`});return}if(!h){let g=y.projects.map(A=>({id:A.id,name:A.name??A.id,sub:A.sub_domain}));if(g.length===0){d({kind:"note",tone:"info",text:"No projects found for this identity."});return}let C=g.findIndex(A=>A.id===y.current);St({cursor:Math.max(0,C),current:C,rows:g,profile:y.profile,environment:y.environment});return}let w=ys(y.projects,h);if(!w){d({kind:"note",tone:"error",text:`No project matches "${h}". Available: ${y.projects.map(g=>g.name??g.id).join(", ")}`});return}Ao(y.profile,w);return}case"logout":{let h;try{h=Ne(e,s).name}catch(w){d({kind:"note",tone:"error",text:w.message});return}let y=zw(h);Kw(e,h),Ee(),H(w=>w+1),d({kind:"note",tone:y?"ok":"info",text:y?`\u2713 Signed out of "${h}" and cleared its project/workspace selection.`:`Profile "${h}" was not signed in. Cleared any project/workspace selection.`}),d({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),Z("/login");return}case"publish":{if(!ko(c.trim()))return;if(f.includes("--screenshots")||f.includes("--shots")){let g=or(We(e));if(g.length===0){d({kind:"note",tone:"info",text:"No captured screenshots yet \u2014 /screenshot capture first."});return}d({kind:"note",tone:"info",text:`Re-saving ${g.length} article${g.length===1?"":"s"} with captured screenshots so the images embed\u2026`}),await It(g);return}if(f[0]==="--related"&&f[1]){let g=await ur(e,s,f[1].replace(/\\/g,"/"));if(g.length===0){d({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await It(g);return}let h=f.filter(g=>!g.startsWith("--"));if(h[0]){await us(h[0]);return}let y=f.includes("--all"),w=f.includes("--force");d({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let g=await Da({cwd:e,profileName:s}),{clean:C,conflicts:A}=ar(g.entries),F=y&&w&&A.length>0,R=cr(g.entries);if(R>0&&d({kind:"note",tone:"warn",text:`\u26A0 ${R} article${R===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.`}),A.length>0&&!F&&d({kind:"note",tone:"warn",text:lr(A.length)}),C.length===0&&!F){if(A.length>0){Z("/resolve");return}d({kind:"note",tone:"ok",text:R>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let q=g.counts["unknown-base"]??0;q>0&&d({kind:"note",tone:"info",text:`(${q} article(s) have no sync base yet \u2014 publish those by path if needed.)`}),mo("Reconciling structure on Document360 (order + related articles)\u2026");try{let M=await pp({cwd:e,profileName:s}),T=mp(await fp({cwd:e,profileName:s})),V=hp(M);V?d({kind:"note",tone:"info",text:V}):M.skipped&&d({kind:"note",tone:"warn",text:`Order sync skipped: ${M.skipped}`}),T&&d({kind:"note",tone:"info",text:T}),d({kind:"note",tone:"ok",text:V||T?"\u2713 Structure synced to Document360 \u2014 /structure shows the new category + article order.":"\u2713 Already in order \u2014 nothing to change."}),(V||T)&&Z("/structure")}catch(M){d({kind:"note",tone:"warn",text:`Structure sync failed: ${M.message}`})}finally{mo(null)}return}if(y){let q=(F?[...C,...A]:C).map(M=>M.path);await It(q),A.length>0&&!F&&Z("/resolve");return}Kt({cursor:0,rows:Mc(C,A)})}catch(g){d({kind:"note",tone:"error",text:`Could not compute sync status: ${g.message}`}),d({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"resolve":{if(!ko(c.trim()))return;await fs(f.find(h=>!h.startsWith("--")));return}case"preview":{let h=f.join(" ").trim();if(!h){let w=[];try{w=Object.keys(rp(e,Ne(e,s).name)?.articles??{})}catch{}if(w.length===0){d({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}Dt({query:"",cursor:0,paths:w});return}let y=Ww(h)?h:Pa(e,h);if(kn(y)){try{d({kind:"preview",name:ro(y),text:wp(Hr(y,"utf8"))})}catch(w){d({kind:"note",tone:"error",text:`Could not read ${y}: ${w.message}`})}return}if(Ak.test(h)){try{let w=Ne(e,s),g={profile:w.name,connection:w.connection},C=w.project.projectId??Gw(g),A=await Yw(g,C,h);d({kind:"preview",name:A.title??h,text:A.content??"*(article has no content)*"})}catch(w){d({kind:"note",tone:"error",text:`Could not fetch article: ${w.message}`})}return}d({kind:"note",tone:"error",text:`"${h}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let h=f[0]?.trim();if(!h){let C=gr(Ia(e));Rt({cursor:C,current:C});return}let{lines:y,changed:w,effective:g}=Kn(e,h);for(let C of y)d({kind:"note",tone:C.startsWith("\u26A0")?"warn":C.startsWith("\u2713")?"ok":"info",text:C});w&&(Ka(C=>C+1),Oe.current?.setModel(g));return}case"convert":{if(!ae(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:h,run:y}=ii(f),w=hk(e,s);if(w.length===0){d({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let g=ai(w,h);if(g.length===0){d({kind:"note",tone:"error",text:`No tracked articles under "${h}". (${w.length} are tracked overall.)`});return}let C=Aa(g),A=3,F=`/convert${h?` --scope ${h}`:""} --run`,R=Gr(e,"light");if(!y){let M=lp({files:li(e,g),op:"convert",model:R.model}),T=h?`Scope: ${h} (${g.length} of ${w.length} tracked)
|
|
411
|
+
`:"",V=`
|
|
412
|
+
Model: ${R.model}${R.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;d({kind:"note",tone:"info",text:T+ui(C,M,A).join(`
|
|
413
|
+
`)+V}),Z(F);return}xt.current=Date.now(),Wt(0),E(!0);let q=new AbortController;we.current=q,ie({verb:"Converting",total:C.length,done:0,active:[],rows:oo(C),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Converting ${g.length} articles across ${C.length} partitions (\u2264${A} agents at once) on ${R.model}\u2026 (esc to stop)`});try{for await(let M of Vr({cwd:e,partitions:C,promptFor:ci,concurrency:A,profileName:s,allowProdWrites:Ht.current,model:R.model,signal:q.signal}))if(M.type==="partition_status")M.status==="running"?ie(T=>T&&{...T,active:[...T.active,M.label],rows:Fe(T.rows,M.label,"active"),lastAt:Date.now()}):ie(T=>T&&{...T,active:T.active.filter(V=>V!==M.label),done:T.done+1,rows:Fe(T.rows,M.label,M.status==="done"?"done":"failed"),lastAt:Date.now()});else if(M.type==="partition_event")ie(T=>{if(!T)return T;let V={...T,lastAt:Date.now()};return M.event.type==="tool"?V.tools=T.tools+1:M.event.type==="text"&&(V.chars=T.chars+M.event.delta.length),V});else if(M.type==="run_done"){Jt(oe=>oe+M.totalCostUsd),Qt(oe=>oe+M.results.reduce((nt,on)=>nt+on.outputTokens,0));let T=M.aborted?"Stopped. ":"",V=t.kind==="api"?"api":"subscription";d({kind:"note",tone:M.aborted?"warn":M.ok?"ok":"warn",text:T+di(M.results,C,V).join(`
|
|
414
|
+
`)})}}catch(M){d({kind:"note",tone:"error",text:`Convert run failed: ${M.message}`})}finally{we.current=null,ie(null),E(!1),H(M=>M+1)}return}case"write":{if(!ae(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let h=fk(e);if(h.length===0){d({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:w,preview:g,concurrency:C,rewrite:A}=fi(f),{docsDir:F,targets:R,reason:q,rewriting:M}=$i(e,h,{scope:y,path:w,rewrite:A});if(R.length===0){d({kind:"note",tone:"warn",text:q??"Nothing to write."});return}M&&d({kind:"note",tone:"warn",text:`--rewrite: regenerating ${R.length} already-written article${R.length===1?"":"s"} (overwrites them; git has your baseline).`});let T=Aa(R),V=hi(C),oe=Gr(e,"standard"),nt=!!w;if(g&&!nt){let ee=lp({files:gi(e,h,R),op:"write",model:oe.model}),ce=y?`Scope: ${y} (${R.length} pending)
|
|
413
415
|
`:"",ke=`
|
|
414
|
-
Model: ${
|
|
415
|
-
`)+ke}),Z(`/write${y?` --scope ${y}`:""}`);return}
|
|
416
|
-
`)}),!ee.aborted&&ee.ok)try{let
|
|
417
|
-
${
|
|
418
|
-
`)}`}),
|
|
419
|
-
`)});return}if(
|
|
420
|
-
${A.skipped.map(
|
|
421
|
-
`)}`}),H(
|
|
422
|
-
`)});return}if(
|
|
423
|
-
`)}),ve(
|
|
424
|
-
`)}),w.length>0&&ve(`Found ${w.length} doc issue${w.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
|
|
425
|
-
`)});return}case"reorder":{let
|
|
426
|
-
`)}),
|
|
427
|
-
`)}),ve(`\u2713 All ${A.length} screenshots are captured. /publish puts them in the articles; /screenshot capture re-captures.`,{kind:"cmd",cmd:"/publish",reason:""});return}
|
|
428
|
-
`)});let
|
|
429
|
-
`)}),xe(to(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${i} \u2014 type /help.`})}},[e,r,s,Jt,fs,d,Ae,oe,jt,us,oc]),To=X(l=>{let c=(l??x).trim();if($(""),ao(null),Mt(0),c.startsWith("/")&&(oo.current=!1,kn.current=!1,qe(),bn(null),Be(f=>Ud(f,c))),!c||(Ua(!1),sc(c))||rc(c))return;Jr.current.push(c);let i=qd(c,Fa.current);if(c.startsWith("/"))d({kind:"user",text:c}),Fe(!0),Tn(i).finally(()=>Fe(!1));else if(gk(i)){d({kind:"user",text:c});let f=yk(i);if(!f)oe(i,{display:c,quietUser:!0});else{try{wk(e,{title:f,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}oe(`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${f}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${f}" and the article path(s) you wrote.`,{display:c,quietUser:!0})}}else{let f=ld(e,i);oe(f??i,{display:c})}},[x,sc,rc,Tn,oe]),ic=X(l=>{if(l.length>1){if(l.includes("\x1B"))return;let c=Wd(l);if(Fd(c)){let i=Bd(++Rp.current,c);Fa.current.set(i,c),j(i)}else j(c);return}j(l)},[j]),Zt=Math.max(10,He-6),ac=Sa(()=>Br(k.text,Zt),[k.text,Zt]),ms=X(l=>b(c=>({...c,pos:Math.max(0,Math.min(c.text.length,c.pos+l))})),[]),Do=X(l=>b(c=>({...c,pos:Vd(Br(c.text,Zt),c.pos,l)})),[Zt]),Dn=X(l=>b(c=>({...c,pos:Gd(Br(c.text,Zt),c.pos,l)})),[Zt]),Dp=["\x1B[H","\x1B[1~","\x1BOH"],Ap=["\x1B[F","\x1B[4~","\x1BOF"],cc=X((l,c)=>c.leftArrow?(ms(-1),!0):c.rightArrow?(ms(1),!0):l&&Dp.includes(l)?(Dn("start"),!0):l&&Ap.includes(l)?(Dn("end"),!0):c.ctrl&&l==="a"?(Dn("start"),!0):c.ctrl&&l==="e"?(Dn("end"),!0):!1,[ms,Dn]);return Ew((l,c)=>{if(c.ctrl&&l==="c"){Ie.current?.close(),r();return}if(!U){if(T){if(c.escape){if(we.current){if(!we.current.signal.aborted){let i=(uo?.verb??"work").toLowerCase(),f=uo?.unit??"article";d({kind:"note",tone:"warn",text:`\u238B Stopping the ${i} run (finishing in-flight ${f}s)\u2026`}),we.current.abort()}return}$n.current||($n.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),Ie.current?.interrupt());return}if(c.return){let i=x.trim();if(!i)return;Tt.current.push(i),es([...Tt.current]),$("");return}if(cc(l,c))return;if(c.upArrow){Do(-1);return}if(c.downArrow){Do(1);return}if(c.backspace||c.delete){v();return}l&&!c.ctrl&&!c.meta&&ic(l);return}if(xt){if(c.upArrow){vt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(c.downArrow){vt(i=>i&&{...i,cursor:Math.min(ze.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=ze.length){vt(i=>i&&{...i,cursor:Number(l)-1});return}if(c.return){let i=ze[xt.cursor];vt(null);let{lines:f,changed:P,effective:G}=Gn(e,i.value??"default");for(let p of f)d({kind:"note",tone:p.startsWith("\u26A0")?"warn":p.startsWith("\u2713")?"ok":"info",text:p});P&&(Ka(p=>p+1),Ie.current?.setModel(G));return}if(l==="s"){let i=ze[xt.cursor];vt(null),Ie.current?.setModel(i.value??void 0),d({kind:"note",tone:"ok",text:`\u2713 Using ${i.label} for this session only (your saved default is unchanged).`});return}if(c.escape){vt(null);return}return}if(Je){if(c.upArrow){qt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(c.downArrow){qt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Je.rows.length){qt(i=>i&&{...i,cursor:Number(l)-1});return}if(c.return||l==="s"){let i=Je.rows[Je.cursor];qt(null),ps(i.name,c.return===!0);return}if(c.escape){qt(null);return}return}if(fo){if(c.escape){Cn(null);return}if(c.leftArrow||c.tab&&c.shift){Cn(i=>i&&{tab:(i.tab-1+Oe.length)%Oe.length});return}if(c.rightArrow||c.tab){Cn(i=>i&&{tab:(i.tab+1)%Oe.length});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Oe.length){Cn({tab:Number(l)-1});return}return}if(Ze){if(c.upArrow){Ht(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(c.downArrow){Ht(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Ze.rows.length){Ht(i=>i&&{...i,cursor:Number(l)-1});return}if(c.return){let i=Ze.rows[Ze.cursor].name;if(Ht(null),!Cs(e,i).created){d({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}d({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${i}").`});let P=!1;try{let G=Ot(i);P=!!G&&!(kt(G)&&!G.refreshToken)}catch{P=!1}d({kind:"note",tone:"info",text:P?`Next: sign in to ${i} and pick your project \u2014 you're already signed in here, so it'll be quick.`:`Next: sign in to Document360 (${i}) and pick your project.`}),Z("/login"),H(G=>G+1);return}if(c.escape){Ht(null);return}return}if($e){if(c.upArrow){Vt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(c.downArrow){Vt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=$e.rows.length){Vt(i=>i&&{...i,cursor:Number(l)-1});return}if(c.return){let i=$e.rows[$e.cursor],{profile:f,projectId:P}=$e;Vt(null),Ro(f,P,i);return}if(c.escape){Vt(null);return}return}if(Pe){if(c.upArrow){Ct(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(c.downArrow){Ct(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Pe.rows.length){Ct(i=>i&&{...i,cursor:Number(l)-1});return}if(c.return){let i=Pe.rows[Pe.cursor],{profile:f}=Pe;Ct(null),Po(f,i);return}if(c.escape){Ct(null);return}return}if(Ce){if(c.upArrow){Yt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(c.downArrow){Yt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l===" "){Yt(i=>i&&{...i,rows:i.rows.map((f,P)=>P===i.cursor?{...f,checked:!f.checked}:f)});return}if(c.return){let i=Ce.rows.filter(f=>f.checked).map(f=>f.path);if(Yt(null),i.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}ei(e,i),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${i.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let f of i)d({kind:"note",tone:"info",text:` ${f}`});d({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(c.escape){Yt(null);return}return}if(et){if(c.upArrow){St(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(c.downArrow){St(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=et.rows.length){St(i=>i&&{...i,cursor:Number(l)-1});return}if(c.return){let i=et.rows[et.cursor],f=et.run;St(null),f(i.token);return}if(c.escape){St(null);return}return}if(st){if(c.upArrow){Gt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(c.downArrow){Gt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=st.rows.length){Gt(i=>i&&{...i,cursor:Number(l)-1});return}if(c.return){let i=st.rows[st.cursor];Gt(null),i.conflict?fs(i.paths[0]):i.kind==="article"?us(i.paths[0]):jt(i.paths);return}if(c.escape){Gt(null);return}return}if(it){if(c.upArrow){Rt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(c.downArrow){Rt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=it.rows.length){Rt(i=>i&&{...i,cursor:Number(l)-1});return}if(c.return){let i=it.rows[it.cursor];Rt(null),i.action==="capture"?Co(i.ids,{runLine:i.kind==="all"?["/screenshot capture --all","/capture --all"]:void 0}):i.kind==="shot"?nc(i.ids[0]):tc(i.ids,{setup:!0,runLine:i.kind==="all"?["/screenshot author --all","/screenshot --all"]:void 0});return}if(c.escape){Rt(null);return}return}if(Te){if(c.escape){Pt(null);return}if(c.upArrow){Pt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(c.downArrow){Pt(i=>i&&{...i,cursor:Math.min(Math.max(0,$o.length-1),i.cursor+1)});return}if(c.return){let i=$o[Te.cursor];if(i){Pt(null);try{d({kind:"preview",name:to(i),text:hp(Hr(Pa(e,i),"utf8"))})}catch(f){d({kind:"note",tone:"error",text:`Could not read ${i}: ${f.message}`})}}return}if(c.backspace||c.delete){Pt(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(l&&!c.ctrl&&!c.meta&&l.length===1){Pt(i=>i&&{...i,query:i.query+l,cursor:0});return}return}if(De){if(c.escape){Dt(null);return}if(c.upArrow){Dt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(c.downArrow){Dt(i=>i&&{...i,cursor:Math.min(Math.max(0,xo.length-1),i.cursor+1)});return}if(c.return){let i=xo[De.cursor];if(i){Dt(null),Ae(i.uuid),Qe.current={uuid:i.uuid,firstPrompt:i.firstPrompt,titleFired:!0},$t(i.name),Ta(i.uuid),Wt.current=[];let f=va(e,i.uuid);for(let P of f)d(P);d({kind:"note",tone:"ok",text:f.length?`Resumed "${i.name}" \u2014 restored ${f.length} message(s); continue where you left off.`:`Resumed "${i.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(c.backspace||c.delete){Dt(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(l&&!c.ctrl&&!c.meta&&l.length===1){Dt(i=>i&&{...i,query:i.query+l,cursor:0});return}return}if(c.tab&&!x&&fe){$(fe),qe();return}if(!x&&be.length>0&&!Kr&&l&&/^[1-9]$/.test(l)){let i=be[Number(l)-1];if(i){$(_t(i));return}}if(!x&&(yo||Rn)&&l==="c"&&!c.ctrl&&!c.meta&&!c.return&&!c.tab){let i=yo!=null;$a(yo??Rn).then(P=>{d({kind:"note",tone:P?"ok":"warn",text:P?i?"\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.":i?"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."}),P&&i&&is(null),P&&!i&&Qa(!0)});return}if(!cc(l,c)){if(Za){if(c.upArrow){Mt(i=>Math.max(0,i-1));return}if(c.downArrow){Mt(i=>Math.min(Ve.length-1,i+1));return}if(c.tab){$("/"+(Ve[Qr]?.name??"")+" "),Mt(0);return}if(c.return){let i=Ve[Qr];if(i){let f=x.trim().slice(1).split(/\s+/).slice(1).join(" ");if(el(i.usage)&&!f){$("/"+i.name+" "),Mt(0);return}To("/"+i.name+(f?" "+f:""));return}}}else{if(c.upArrow){if(x!==""&&Ut===null){Do(-1);return}let i=Jr.current;if(!i.length)return;let f=Ut===null?i.length-1:Math.max(0,Ut-1);ao(f),$(i[f]??"");return}if(c.downArrow){if(x!==""&&Ut===null){Do(1);return}let i=Jr.current;if(Ut===null)return;let f=Ut+1;f>=i.length?(ao(null),$("")):(ao(f),$(i[f]??""));return}}if(c.return){To();return}if(c.backspace||c.delete){v();return}if(c.escape){$(""),Mt(0),qe(),Be([]),bn(null),oo.current=!0;return}l&&!c.ctrl&&!c.meta&&ic(l)}}}),Ne(()=>{if(T||U)return;let l=Tt.current.shift();l!==void 0&&(es([...Tt.current]),To(l))},[T,U,To]),Q(ae,{flexDirection:"column",width:He,children:[ls!==null&&Q(ae,{marginTop:1,flexDirection:"column",children:[ls.truncated&&I(N,{dimColor:!0,children:"\u2026"}),I(N,{children:ls.text})]}),T&&(uo?I(Tk,{p:uo}):I(Rk,{startTime:bt.current,chars:Cp})),!T&&Ga?I(Sk,{text:Ga}):null,I(ae,{borderStyle:"round",borderColor:Ja.prod?"yellow":K,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:x?ac.map((l,c)=>{let i=k.text.slice(l.start,l.end),f=c===qr(ac,k.pos),P=Math.min(k.pos,l.end)-l.start;return Q(N,{children:[I(N,{color:K,children:c===0?"> ":" "}),f?Q(no,{children:[i.slice(0,P),I(gn,{ch:i[P]??" "}),i.slice(P+1)]}):i||" "]},`${c}-${l.start}`)}):Q(N,{children:[I(N,{color:K,children:"> "}),ts?I(gn,{ch:" "}):fe&&!T&&me?Q(no,{children:[I(gn,{ch:me[0],dim:!0}),I(N,{color:"gray",children:me.slice(1)})]}):fe&&!T?Q(no,{children:[I(gn,{ch:fe[0],dim:!0}),I(N,{color:"gray",children:fe.slice(1)}),I(N,{dimColor:!0,children:" (tab)"})]}):(as.isSetup||!xp)&&!T?Q(no,{children:[I(gn,{ch:as.text[0],dim:!0}),I(N,{color:"gray",children:as.text.slice(1)})]}):I(gn,{ch:" "})]})}),Va.length>0&&I(ae,{flexDirection:"column",paddingX:1,children:Va.map((l,c)=>I(N,{color:"gray",children:`\u29D7 queued: ${l}`},`${c}-${l.slice(0,24)}`))}),fo?I(Nd,{tab:fo.tab,width:He,version:o,engineVersion:fp}):xt?Q(ae,{flexDirection:"column",paddingX:1,children:[I(N,{color:K,bold:!0,children:"Select model"}),I(N,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),ze.map((l,c)=>Q(N,{color:c===xt.cursor?K:void 0,children:[c===xt.cursor?"\u276F ":" ",`${c+1}. ${l.label}${c===xt.current?" \u2714":""}`.padEnd(16),I(N,{color:"gray",children:l.desc})]},l.label)),I(N,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Je?Q(ae,{flexDirection:"column",paddingX:1,children:[I(N,{color:K,bold:!0,children:"Switch connection profile"}),Je.rows.map((l,c)=>Q(N,{color:c===Je.cursor?K:void 0,children:[c===Je.cursor?"\u276F ":" ",`${c+1}. ${l.name}${c===Je.current?" \u2714":""}`.padEnd(20),I(N,{color:"gray",children:`${l.env} \xB7 ${l.who??"not signed in"}`}),l.prod?I(N,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},l.name)),I(N,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Ze?Q(ae,{flexDirection:"column",paddingX:1,children:[I(N,{color:K,bold:!0,children:"Pick your Document360 environment"}),Ze.rows.map((l,c)=>Q(N,{color:c===Ze.cursor?K:void 0,children:[c===Ze.cursor?"\u276F ":" ",`${c+1}. ${l.name}`.padEnd(16),I(N,{color:"gray",children:l.apiUrl})]},l.name)),I(N,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):$e?Q(ae,{flexDirection:"column",paddingX:1,children:[I(N,{color:K,bold:!0,children:"Switch workspace"}),I(N,{dimColor:!0,children:`environment ${$e.environment} \xB7 project ${$e.projectName??`${$e.projectId.slice(0,8)}\u2026`}`}),$e.rows.map((l,c)=>Q(N,{color:c===$e.cursor?K:void 0,children:[c===$e.cursor?"\u276F ":" ",`${c+1}. ${l.name}${c===$e.current?" \u2714":""}`.padEnd(30),I(N,{color:"gray",children:l.type??""})]},l.id)),I(N,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):Pe?Q(ae,{flexDirection:"column",paddingX:1,children:[I(N,{color:K,bold:!0,children:"Choose project"}),I(N,{dimColor:!0,children:`environment ${Pe.environment}`}),Pe.rows.map((l,c)=>Q(N,{color:c===Pe.cursor?K:void 0,children:[c===Pe.cursor?"\u276F ":" ",`${c+1}. ${l.name}${c===Pe.current?" \u2714":""}`.padEnd(30),I(N,{color:"gray",children:l.sub??""})]},l.id)),I(N,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):Ce?(()=>{let c=Math.min(Math.max(0,Ce.cursor-Math.floor(7)),Math.max(0,Ce.rows.length-14)),i=Ce.rows.slice(c,c+14),f=Ce.rows.filter(P=>P.checked).length;return Q(ae,{flexDirection:"column",paddingX:1,children:[I(N,{color:K,bold:!0,children:`Which folders back the user docs? (${f} selected of ${Ce.rows.length})`}),c>0?I(N,{dimColor:!0,children:` \u2191 ${c} more`}):null,i.map((P,G)=>{let p=c+G;return Q(N,{color:p===Ce.cursor?K:void 0,children:[p===Ce.cursor?"\u276F ":" ",P.checked?"\u25C9 ":"\u25CB ",P.path.padEnd(Math.min(48,He-34)),I(N,{color:"gray",children:dr(P)})]},P.path)}),c+14<Ce.rows.length?I(N,{dimColor:!0,children:` \u2193 ${Ce.rows.length-c-14} more`}):null,I(N,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():et?Q(ae,{flexDirection:"column",paddingX:1,children:[I(N,{color:K,bold:!0,children:"Which category? (pick one to scope to)"}),et.rows.map((l,c)=>{let i=c===et.cursor,f=`${c+1}.`.padEnd(3);return Q(N,{color:i?K:void 0,children:[i?"\u276F ":" ",`${f} ${l.label} (${l.count})`.padEnd(Math.min(44,Math.max(20,He-24))),I(N,{color:"gray",children:` ${l.token}`})]},l.token)}),I(N,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):st?Q(ae,{flexDirection:"column",paddingX:1,children:[I(N,{color:K,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),st.rows.map((l,c)=>{let i=c===st.cursor,f=l.indent?" ":" ",P=`${c+1}.`.padEnd(3);return Q(N,{color:i?K:void 0,bold:l.kind==="category"&&!i,children:[i?"\u276F ":" ",`${f}${P} ${l.label}`.padEnd(Math.min(56,He-24)),l.note?I(N,{color:"gray",children:l.note}):null]},`${l.kind}:${l.paths.join(",")}`)}),I(N,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):it?Q(ae,{flexDirection:"column",paddingX:1,children:[I(N,{color:K,bold:!0,children:it.title}),(()=>{let{rows:c,cursor:i}=it,f=Math.max(0,Math.min(i-Math.floor(12/2),c.length-12)),P=c.slice(f,f+12),G=`${c.length}.`.length+1;return Q(no,{children:[f>0?I(N,{color:"gray",children:` \u2026 ${f} more above`}):null,P.map((p,y)=>{let w=f+y,m=w===i;return Q(N,{color:m?K:void 0,bold:(p.kind==="all"||p.kind==="category")&&!m,children:[m?"\u276F ":" ",`${w+1}.`.padEnd(G)," ".repeat(p.depth),p.label,p.note?I(N,{color:"gray",children:p.note}):null]},`${p.action}:${p.kind}:${p.ids.join(",")}`)}),f+12<c.length?I(N,{color:"gray",children:` \u2026 ${c.length-f-12} more below`}):null]})})(),I(N,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter run \xB7 esc cancel"})]}):Te?Q(ae,{flexDirection:"column",paddingX:1,children:[I(N,{color:K,bold:!0,children:`Preview article${Te.query?` \u2014 filter: ${Te.query}`:" (type to filter)"}`}),$o.length===0?I(N,{color:"gray",children:"no articles match"}):$o.map((l,c)=>Q(N,{color:c===Te.cursor?K:void 0,children:[c===Te.cursor?"\u276F ":" ",l]},l)),I(N,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):De?Q(ae,{flexDirection:"column",paddingX:1,children:[I(N,{color:K,bold:!0,children:`Resume session${De.query?` \u2014 filter: ${De.query}`:" (type to filter)"}`}),xo.length===0?I(N,{color:"gray",children:"no sessions match"}):xo.map((l,c)=>Q(N,{color:c===De.cursor?K:void 0,children:[c===De.cursor?"\u276F ":" ",l.name.slice(0,28).padEnd(30),I(N,{color:c===De.cursor?K:"gray",children:l.firstPrompt.slice(0,Math.max(10,He-40))})]},l.uuid)),I(N,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Za?Q(ae,{flexDirection:"column",children:[Et>0?I(N,{dimColor:!0,children:` \u22EF ${Et} more above`}):null,cs.map((l,c)=>{let i=Et+c;return Q(N,{color:i===bo?K:void 0,children:[i===bo?"\u276F ":" ",l.usage.padEnd(22)," ",I(N,{color:i===bo?K:"gray",children:l.name==="model"&&ns?`${l.desc} (currently ${ns})`:l.desc})]},l.name)}),Et+cs.length<Ve.length?I(N,{dimColor:!0,children:` \u22EF ${Ve.length-Et-cs.length} more below`}):null,I(N,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!T&&!x&&be.length>0?Q(ae,{flexDirection:"column",paddingX:1,children:[Ha?I(N,{color:K,children:Ha}):null,be.map((l,c)=>{let i=_t(l),f=i.slice(0,Math.max(20,He-5)),P=He-f.length-7,G=P>=12?(Md(l)??Jc(i)).slice(0,P):"";return Q(N,{children:[I(N,{color:K,children:c+1})," ",f,G?I(N,{dimColor:!0,children:` \u2014 ${G}`}):null]},i)}),I(N,{dimColor:!0,children:`press 1-${be.length} to fill \xB7 esc cancel`})]}):I(ae,{paddingX:1,children:Q(N,{color:"gray",children:[Ja.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${ns??"model n/a"}${t.kind==="api"?za>0?` \xB7 ${Se(za)}`:"":Ya>0?` \xB7 ${ft(Ya)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}Y();import{jsx as jk}from"react/jsx-runtime";async function gp(e=process.cwd(),t="auto",n,o="0.0.0"){let r=Ek(t);r.kind==="none"&&(console.error(""),console.error(S("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}=Ak(jk(mp,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
|
|
430
|
-
`),process.exit(0)}
|
|
431
|
-
`+S(`\u2717 d360-writer crashed: ${
|
|
432
|
-
`),r&&process.stderr.write(
|
|
433
|
-
`+
|
|
434
|
-
`),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var
|
|
416
|
+
Model: ${oe.model}${oe.forced?" (forced)":" \u2014 authoring; /model to override"}`;d({kind:"note",tone:"info",text:ce+wi(T,ee,V).join(`
|
|
417
|
+
`)+ke}),Z(`/write${y?` --scope ${y}`:""}`);return}xt.current=Date.now(),Wt(0),E(!0);let on=new AbortController;we.current=on,ie({verb:"Writing",total:T.length,done:0,active:[],rows:oo(T),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Writing ${R.length} article${R.length===1?"":"s"} across ${T.length} partition${T.length===1?"":"s"} (\u2264${V} agents at once) on ${oe.model}${oe.forced?" (forced)":""}\u2026 (esc to stop)`});let Re=new Set;try{for await(let ee of Vr({cwd:e,partitions:T,promptFor:ce=>yi(ce,F,{rewrite:M||nt}),concurrency:V,profileName:s,allowProdWrites:Ht.current,model:oe.model,signal:on.signal}))if(ee.type==="partition_status")ee.status==="running"?ie(ce=>ce&&{...ce,active:[...ce.active,ee.label],rows:Fe(ce.rows,ee.label,"active"),lastAt:Date.now()}):ie(ce=>ce&&{...ce,active:ce.active.filter(ke=>ke!==ee.label),done:ce.done+1,rows:Fe(ce.rows,ee.label,ee.status==="done"?"done":"failed"),lastAt:Date.now()});else if(ee.type==="partition_event"){let ce=null;if(ee.event.type==="tool"){let ke=Fd(ee.event.name,ee.event.input,T[ee.index]?.paths??[]);ke&&!Re.has(ke)&&(Re.add(ke),ce=ee.label)}ie(ke=>{if(!ke)return ke;let ze={...ke,lastAt:Date.now()};return ee.event.type==="tool"?ze.tools=ke.tools+1:ee.event.type==="text"&&(ze.chars=ke.chars+ee.event.delta.length),ce&&(ze.rows=Wd(ze.rows,ce)),ze})}else if(ee.type==="run_done"){Jt(ut=>ut+ee.totalCostUsd),Qt(ut=>ut+ee.results.reduce((ot,_p)=>ot+_p.outputTokens,0));let ce=ee.aborted?"Stopped. ":"",ke=t.kind==="api"?"api":"subscription";if(d({kind:"note",tone:ee.aborted?"warn":ee.ok?"ok":"warn",text:ce+ki(ee.results,T,ke).join(`
|
|
418
|
+
`)}),!ee.aborted&&ee.ok)try{let ut=(Re.size>0?[...Re]:R).map(ot=>`${F}/${ot}`);Ea(e,ut,{writtenCap:ja})}catch{}let ze=ee.aborted?null:bi(e,F,R);if(ze&&d({kind:"note",tone:"warn",text:ze}),!ee.aborted&&ee.ok){let ut=y??w??"",ot=ut?` ${ut}`:"";ve(ze?`Written \u2014 but the checker flagged issues. I\u2019d fix those first with /check${ot} --fix, then /review${ot} --fix for editorial quality, then /publish --all (add /screenshot author --all first if you want images).`:`Written. I\u2019d run /review${ot} --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:ze?`/check${ot} --fix`:`/review${ot} --fix`,reason:""})}}}catch(ee){d({kind:"note",tone:"error",text:`Write run failed: ${ee.message}`})}finally{we.current=null,ie(null),E(!1),H(ee=>ee+1)}return}case"draft":{if(!ae(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:h,looseDocs:y}=xi(e);if(h.length===0&&y===0){d({kind:"note",tone:"info",text:Ci});return}let w=f.join(" ").trim();if(!w&&h.length>1){d({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
|
|
419
|
+
${h.map(A=>` \u2022 ${A.name} (${A.docCount} doc${A.docCount===1?"":"s"})`).join(`
|
|
420
|
+
`)}`}),He(h.map(A=>`/draft ${A.name}`));return}let g="",C;if(w){let A=vi(h,w);A?g=A:C=w}else g=h[0]?.name??"";await re(mr(g,C),{display:w?`/draft ${w}`:"/draft",quietUser:!0});return}case"pull":{if(!ko(c.trim()))return;let h=f.find(y=>y.startsWith("--"));try{if(h==="--status"){d({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let g=Date.now(),C=await Da({cwd:e,profileName:s});d({kind:"note",tone:"info",text:pr(C,Date.now()-g).join(`
|
|
421
|
+
`)});return}if(h==="--baseline"){let g=f.find(R=>!R.startsWith("--")),C=g?g.replace(/\\/g,"/"):void 0;d({kind:"note",tone:"info",text:C?`Setting the sync baseline for ${C}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let A=await ik({cwd:e,profileName:s,relPaths:C?[C]:void 0}),F=C?{rebaselined:[],skipped:[]}:await ak({cwd:e,profileName:s});if(A.baselined.length===0&&A.skipped.length===0&&F.rebaselined.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}A.baselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Baselined ${A.baselined.length} article${A.baselined.length===1?"":"s"} \u2014 they now read in-sync until either side changes.`}),F.rebaselined.length>0&&d({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.`}),A.skipped.length>0&&d({kind:"note",tone:"warn",text:`${A.skipped.length} skipped:
|
|
422
|
+
${A.skipped.map(R=>` - ${R.path} (${R.reason})`).join(`
|
|
423
|
+
`)}`}),H(R=>R+1);return}if(h==="--compare"){d({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let g=await sk({cwd:e,profileName:s}),C=g.onlyInLegacy.length===0&&g.onlyInManifest.length===0&&g.mappedMissingFromManifest.length===0,A=[`Legacy listing: ${g.legacyCount} \xB7 Manifest: ${g.manifestCount} \xB7 in both: ${g.inBoth}`];C?A.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(g.mappedMissingFromManifest.length&&A.push(`\u2717 ${g.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${g.mappedMissingFromManifest.slice(0,5).join(", ")}`),g.onlyInLegacy.length&&A.push(`\u26A0 ${g.onlyInLegacy.length} only in the legacy listing: ${g.onlyInLegacy.slice(0,5).join(", ")}`),g.onlyInManifest.length&&A.push(`\u26A0 ${g.onlyInManifest.length} only in the manifest: ${g.onlyInManifest.slice(0,5).join(", ")}`),A.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),d({kind:"note",tone:C?"ok":"warn",text:A.join(`
|
|
424
|
+
`)});return}if(h){d({kind:"note",tone:"error",text:`Unknown option: ${h} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let y=f[0];if(y){let g=await ap({cwd:e,profileName:s,relPath:y.replace(/\\/g,"/")});pe.current=[{plan:g,mode:g.overwritesLocalChanges?"conflict":"pull"}],Vt.current=[],tn();return}d({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let w=await oi({cwd:e,profileName:s});for(let g of ri(w))d({kind:"note",tone:g.tone,text:g.text});H(g=>g+1)}catch(y){d({kind:"note",tone:"error",text:`Pull failed: ${y.message}`})}return}case"scope":{if(!ae(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let h=lk(e);if(h.length===0){d({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.'});return}Xt({cursor:0,rows:h.map(y=>({...y,checked:y.recommended}))});return}case"audit":{if(f[0]==="--auto"){let y=ae(e);if(!y){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let w=f[1]!=="off";op({...y,autoAudit:w},e),d({kind:"note",tone:"ok",text:w?"\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 h=await Yn();h.kind==="forward-to-agent"&&h.prompt&&await re(h.prompt,{display:h.display,quietUser:!0});return}case"check":{let h=f.find(g=>!g.startsWith("--")),y=h?` ${h}`:"",w=ip({cwd:e,scope:h});if(f.includes("--fix")){if(w.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing to fix \u2014 the docs are already clean."});return}d({kind:"note",tone:"info",text:`Fixing ${w.length} doc issue${w.length===1?"":"s"}\u2026`});let g=dp(e,h);await re(sa(w),{display:`/check${y} --fix`,quietUser:!0});try{Ea(e,g,{reviewedCap:ja})}catch{}let C=ip({cwd:e,scope:h});d({kind:"note",tone:C.length===0?"ok":"warn",text:C.length===0?"\u2713 Doc-checker: all issues resolved.":Rr(C).join(`
|
|
425
|
+
`)}),ve(C.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}d({kind:"note",tone:w.length===0?"ok":"warn",text:Rr(w).join(`
|
|
426
|
+
`)}),w.length>0&&ve(`Found ${w.length} doc issue${w.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 h=Zn(e,s);if(h.length===0){d({kind:"note",tone:"info",text:"No documentation structure yet \u2014 run /init and author some articles first."});return}d({kind:"note",tone:"info",text:["Documentation order (categories \u2192 articles):","",...h].join(`
|
|
427
|
+
`)});return}case"reorder":{let h=aa(e,f);if(!h){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await re(h.prompt,{display:h.display,quietUser:!0}),ve("Reordered locally \u2014 /publish --all syncs the new order to Document360.",{kind:"cmd",cmd:"/publish --all",reason:""});return}case"review":{let h=ia(e,f);if(!h){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let y=f.includes("--fix"),w=f.find(C=>!C.startsWith("--")),g=y?dp(e,w):[];if(await re(h.prompt,{display:h.display,quietUser:!0}),y)try{Ea(e,g,{reviewedCap:ja})}catch{}if(y)ve("\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 C=f.filter(A=>A!=="--fix").join(" ");ve(`The review listed issues above. /review${C?` ${C}`:""} --fix lets the editor apply them all (or /check --fix for just the deterministic ones; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/review${C?` ${C}`:""} --fix`,reason:""})}return}case"capture-setup":{await Y();return}case"devhints":{if(!ae(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:cn(ln(e)).join(`
|
|
428
|
+
`)}),Zt(Ot()),An.current=Me(e).status==="current",en.current=rt(e);return}case"discover":{if(!ae(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await re(Js(),{display:"/discover",quietUser:!0});return}case"inbox":{if(!ae(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(Yi(e)===0){d({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 re(zi(),{display:"/inbox",quietUser:!0});return}case"feedback":{let h=up(e),y="";try{y=kn(h)?Hr(h,"utf8"):""}catch{y=""}if(!/^## /m.test(y)){d({kind:"note",tone:"info",text:"No open d360-writer feedback to copy \u2014 nothing logged in .d360-writer/tool-feedback.md yet."});return}let w=await $a(y.trim());d({kind:"note",tone:w?"ok":"warn",text:w?"\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 ${h} and copy it manually.`}),w&&is(null);return}case"document":{if(!ae(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:h,what:y}=Si(f);if(!y&&Ri(e)===0){d({kind:"note",tone:"info",text:Ti});return}let w=`/document${y?` ${y}`:""}${h?" --publish":""}`;await re(Pi(y,h),{display:w,quietUser:!0});return}case"catch-up":{if(!ae(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!ko(c.trim()))return;let{publish:h}=Xi(f);d({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let y=await Ji({cwd:e,profileName:s});for(let g of Zi(y))d({kind:"note",tone:g.startsWith("\u2713")?"ok":g.startsWith("\u2139")?"info":"warn",text:g});let w=Jn(Qn(e));d({kind:"note",tone:"info",text:w?`Catching up on ${w}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"}),await re(Qi({publish:h}),{display:`/catch-up${h?" --publish":""}`,quietUser:!0});return}case"update":{rs.current=!0,d({kind:"note",tone:"info",text:"Updating the d360-writer toolchain\u2026 (don\u2019t close this window)"}),co(!0);let h=await vr().finally(()=>co(!1));h.ok?(d({kind:"note",tone:"ok",text:`\u2713 Updated ${h.packages.join(" + ")} \u2014 run /exit, then relaunch to apply.`}),Z("/exit"),Wa("")):d({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${xr}`});return}case"screenshot":{let h=Hn(f);if(h.mode==="capture"){await P(h.rest);return}if(h.mode==="checklist"){await Y();return}if(h.mode==="list"){if(!ae(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let g=ae(e)?.docsDir??Oa,C=Vs(e,h.scope),A=We(e,C);if(h.picker){if(A.length===0){d({kind:"note",tone:"info",text:"No screenshot placeholders found in the docs."});return}let q=Ec(A);if(q.length===0){d({kind:"note",tone:"info",text:rr(A,{docsDir:g}).join(`
|
|
429
|
+
`)}),ve(`\u2713 All ${A.length} screenshots are captured. /publish puts them in the articles; /screenshot capture re-captures.`,{kind:"cmd",cmd:"/publish",reason:""});return}Pt({cursor:0,rows:q,title:"Screenshots \u2014 pick what to author or capture:"});return}d({kind:"note",tone:"info",text:rr(A,{scope:C,detail:h.detail,docsDir:g}).join(`
|
|
430
|
+
`)});let F=A.filter(q=>q.state==="placeholder").length,R=A.filter(q=>q.state==="spec").length;if(F>0){let q=C?`/screenshot author ${C}`:"/screenshot author --all";ve(`${F} of ${A.length} still need${F===1?"s":""} a spec \u2014 /screenshot author <id> authors one, ${q} authors them all in parallel.`,{kind:"cmd",cmd:q,reason:""})}else if(R>0){let q=C?`/screenshot capture ${C}`:"/screenshot capture";ve(`${R} spec${R===1?"":"s"} ready to capture \u2014 ${q} takes ${R===1?"it":"them"} (a real browser drives your app).`,{kind:"cmd",cmd:q,reason:""})}return}if(h.mode==="single"){await nl(h.id);return}if(!ae(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let y=h.mode==="scope"?h.scope:void 0,w=pk(e,{scope:y}).map(g=>g.id);if(w.length===0){d({kind:"note",tone:"info",text:y?`No screenshot placeholders under ${y}.`:"No screenshot placeholders found in the docs."});return}await tl(w,{setup:h.setup,runLine:h.mode==="scope"?[`/screenshot author ${h.scope}`,`/screenshot ${h.scope}`]:["/screenshot author --all","/screenshot --all"]});return}case"capture":{await P(f);return}case"reset":{let h=na(e);if(h.length===0){d({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}ho.current={repoName:ro(e),targets:h,hadDevhints:kn(cp(e))},d({kind:"note",tone:"warn",text:ra(e,h).join(`
|
|
431
|
+
`)}),xe(ro(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${i} \u2014 type /help.`})}},[e,r,s,tn,fs,d,Ee,re,It,us,ol]),Eo=Q(c=>{let l=(c??$).trim();if(x(""),uo(null),Ft(0),l.startsWith("/")&&(io.current=!1,vn.current=!1,Ve(),Cn(null),He(f=>Hd(f,l))),!l||(Ua(!1),sl(l))||rl(l))return;Jr.current.push(l);let i=zd(l,Fa.current);if(l.startsWith("/"))d({kind:"user",text:l}),qe(!0),jn(i).finally(()=>qe(!1));else if(xk(i)){d({kind:"user",text:l});let f=vk(i);if(!f)re(i,{display:l,quietUser:!0});else{try{Ck(e,{title:f,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}re(`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${f}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${f}" and the article path(s) you wrote.`,{display:l,quietUser:!0})}}else{let f=fd(e,i);re(f??i,{display:l})}},[$,sl,rl,jn,re]),il=Q(c=>{if(c.length>1){if(c.includes("\x1B"))return;let l=Vd(c);if(Gd(l)){let i=Yd(++Ap.current,l);Fa.current.set(i,l),j(i)}else j(l);return}j(c)},[j]),nn=Math.max(10,Ge-6),al=Sa(()=>Br(b.text,nn),[b.text,nn]),ms=Q(c=>k(l=>({...l,pos:Math.max(0,Math.min(l.text.length,l.pos+c))})),[]),jo=Q(c=>k(l=>({...l,pos:Xd(Br(l.text,nn),l.pos,c)})),[nn]),Nn=Q(c=>k(l=>({...l,pos:Qd(Br(l.text,nn),l.pos,c)})),[nn]),Ip=["\x1B[H","\x1B[1~","\x1BOH"],Op=["\x1B[F","\x1B[4~","\x1BOF"],ll=Q((c,l)=>l.leftArrow?(ms(-1),!0):l.rightArrow?(ms(1),!0):c&&Ip.includes(c)?(Nn("start"),!0):c&&Op.includes(c)?(Nn("end"),!0):l.ctrl&&c==="a"?(Nn("start"),!0):l.ctrl&&c==="e"?(Nn("end"),!0):!1,[ms,Nn]);return Lw((c,l)=>{if(l.ctrl&&c==="c"){Oe.current?.close(),r();return}if(!U){if(D){if(l.escape){if(we.current){if(!we.current.signal.aborted){let i=(fo?.verb??"work").toLowerCase(),f=fo?.unit??"article";d({kind:"note",tone:"warn",text:`\u238B Stopping the ${i} run (finishing in-flight ${f}s)\u2026`}),we.current.abort()}return}Rn.current||(Rn.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),Oe.current?.interrupt());return}if(l.return){let i=$.trim();if(!i)return;At.current.push(i),es([...At.current]),x("");return}if(ll(c,l))return;if(l.upArrow){jo(-1);return}if(l.downArrow){jo(1);return}if(l.backspace||l.delete){v();return}c&&!l.ctrl&&!l.meta&&il(c);return}if(Ct){if(l.upArrow){Rt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Rt(i=>i&&{...i,cursor:Math.min(Ke.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ke.length){Rt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Ke[Ct.cursor];Rt(null);let{lines:f,changed:P,effective:Y}=Kn(e,i.value??"default");for(let h of f)d({kind:"note",tone:h.startsWith("\u26A0")?"warn":h.startsWith("\u2713")?"ok":"info",text:h});P&&(Ka(h=>h+1),Oe.current?.setModel(Y));return}if(c==="s"){let i=Ke[Ct.cursor];Rt(null),Oe.current?.setModel(i.value??void 0),d({kind:"note",tone:"ok",text:`\u2713 Using ${i.label} for this session only (your saved default is unchanged).`});return}if(l.escape){Rt(null);return}return}if(Ze){if(l.upArrow){Gt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Gt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ze.rows.length){Gt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return||c==="s"){let i=Ze.rows[Ze.cursor];Gt(null),ps(i.name,l.return===!0);return}if(l.escape){Gt(null);return}return}if(yo){if(l.escape){Tn(null);return}if(l.leftArrow||l.tab&&l.shift){Tn(i=>i&&{tab:(i.tab-1+Le.length)%Le.length});return}if(l.rightArrow||l.tab){Tn(i=>i&&{tab:(i.tab+1)%Le.length});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Le.length){Tn({tab:Number(c)-1});return}return}if(et){if(l.upArrow){Yt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Yt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=et.rows.length){Yt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=et.rows[et.cursor].name;if(Yt(null),!Cs(e,i).created){d({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}d({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${i}").`});let P=!1;try{let Y=Ut(i);P=!!Y&&!($t(Y)&&!Y.refreshToken)}catch{P=!1}d({kind:"note",tone:"info",text:P?`Next: sign in to ${i} and pick your project \u2014 you're already signed in here, so it'll be quick.`:`Next: sign in to Document360 (${i}) and pick your project.`}),Z("/login"),H(Y=>Y+1);return}if(l.escape){Yt(null);return}return}if($e){if(l.upArrow){zt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){zt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=$e.rows.length){zt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=$e.rows[$e.cursor],{profile:f,projectId:P}=$e;zt(null),To(f,P,i);return}if(l.escape){zt(null);return}return}if(Te){if(l.upArrow){St(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){St(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Te.rows.length){St(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Te.rows[Te.cursor],{profile:f}=Te;St(null),Ao(f,i);return}if(l.escape){St(null);return}return}if(Ce){if(l.upArrow){Xt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Xt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c===" "){Xt(i=>i&&{...i,rows:i.rows.map((f,P)=>P===i.cursor?{...f,checked:!f.checked}:f)});return}if(l.return){let i=Ce.rows.filter(f=>f.checked).map(f=>f.path);if(Xt(null),i.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}Zs(e,i),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${i.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let f of i)d({kind:"note",tone:"info",text:` ${f}`});d({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(l.escape){Xt(null);return}return}if(tt){if(l.upArrow){Tt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Tt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=tt.rows.length){Tt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=tt.rows[tt.cursor],f=tt.run;Tt(null),f(i.token);return}if(l.escape){Tt(null);return}return}if(at){if(l.upArrow){Kt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Kt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=at.rows.length){Kt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=at.rows[at.cursor];Kt(null),i.conflict?fs(i.paths[0]):i.kind==="article"?us(i.paths[0]):It(i.paths);return}if(l.escape){Kt(null);return}return}if(lt){if(l.upArrow){Pt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Pt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=lt.rows.length){Pt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=lt.rows[lt.cursor];Pt(null),i.action==="capture"?Po(i.ids,{runLine:i.kind==="all"?["/screenshot capture --all","/capture --all"]:void 0}):i.kind==="shot"?nl(i.ids[0]):tl(i.ids,{setup:!0,runLine:i.kind==="all"?["/screenshot author --all","/screenshot --all"]:void 0});return}if(l.escape){Pt(null);return}return}if(De){if(l.escape){Dt(null);return}if(l.upArrow){Dt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Dt(i=>i&&{...i,cursor:Math.min(Math.max(0,Co.length-1),i.cursor+1)});return}if(l.return){let i=Co[De.cursor];if(i){Dt(null);try{d({kind:"preview",name:ro(i),text:wp(Hr(Pa(e,i),"utf8"))})}catch(f){d({kind:"note",tone:"error",text:`Could not read ${i}: ${f.message}`})}}return}if(l.backspace||l.delete){Dt(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(c&&!l.ctrl&&!l.meta&&c.length===1){Dt(i=>i&&{...i,query:i.query+c,cursor:0});return}return}if(Ae){if(l.escape){Et(null);return}if(l.upArrow){Et(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Et(i=>i&&{...i,cursor:Math.min(Math.max(0,Ro.length-1),i.cursor+1)});return}if(l.return){let i=Ro[Ae.cursor];if(i){Et(null),Ee(i.uuid),Je.current={uuid:i.uuid,firstPrompt:i.firstPrompt,titleFired:!0},vt(i.name),Ta(i.uuid),qt.current=[];let f=va(e,i.uuid);for(let P of f)d(P);d({kind:"note",tone:"ok",text:f.length?`Resumed "${i.name}" \u2014 restored ${f.length} message(s); continue where you left off.`:`Resumed "${i.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(l.backspace||l.delete){Et(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(c&&!l.ctrl&&!l.meta&&c.length===1){Et(i=>i&&{...i,query:i.query+c,cursor:0});return}return}if(l.tab&&!$&&fe){x(fe),Ve();return}if(!$&&be.length>0&&!Kr&&c&&/^[1-9]$/.test(c)){let i=be[Number(c)-1];if(i){x(Mt(i));return}}if(!$&&(bo||Dn)&&c==="c"&&!l.ctrl&&!l.meta&&!l.return&&!l.tab){let i=bo!=null;$a(bo??Dn).then(P=>{d({kind:"note",tone:P?"ok":"warn",text:P?i?"\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.":i?"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."}),P&&i&&is(null),P&&!i&&Qa(!0)});return}if(!ll(c,l)){if(Za){if(l.upArrow){Ft(i=>Math.max(0,i-1));return}if(l.downArrow){Ft(i=>Math.min(Ye.length-1,i+1));return}if(l.tab){x("/"+(Ye[Qr]?.name??"")+" "),Ft(0);return}if(l.return){let i=Ye[Qr];if(i){let f=$.trim().slice(1).split(/\s+/).slice(1).join(" ");if(ec(i.usage)&&!f){x("/"+i.name+" "),Ft(0);return}Eo("/"+i.name+(f?" "+f:""));return}}}else{if(l.upArrow){if($!==""&&Bt===null){jo(-1);return}let i=Jr.current;if(!i.length)return;let f=Bt===null?i.length-1:Math.max(0,Bt-1);uo(f),x(i[f]??"");return}if(l.downArrow){if($!==""&&Bt===null){jo(1);return}let i=Jr.current;if(Bt===null)return;let f=Bt+1;f>=i.length?(uo(null),x("")):(uo(f),x(i[f]??""));return}}if(l.return){Eo();return}if(l.backspace||l.delete){v();return}if(l.escape){x(""),Ft(0),Ve(),He([]),Cn(null),io.current=!0;return}c&&!l.ctrl&&!l.meta&&il(c)}}}),Ie(()=>{if(D||U)return;let c=At.current.shift();c!==void 0&&(es([...At.current]),Eo(c))},[D,U,Eo]),J(le,{flexDirection:"column",width:Ge,children:[cs!==null&&J(le,{marginTop:1,flexDirection:"column",children:[cs.truncated&&I(N,{dimColor:!0,children:"\u2026"}),I(N,{children:cs.text})]}),D&&(fo?I(Ik,{p:fo}):I(Ek,{startTime:xt.current,chars:Dp})),!D&&Ga?I(jk,{text:Ga}):null,I(le,{borderStyle:"round",borderColor:Ja.prod?"yellow":X,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:$?al.map((c,l)=>{let i=b.text.slice(c.start,c.end),f=l===qr(al,b.pos),P=Math.min(b.pos,c.end)-c.start;return J(N,{children:[I(N,{color:X,children:l===0?"> ":" "}),f?J(so,{children:[i.slice(0,P),I(bn,{ch:i[P]??" "}),i.slice(P+1)]}):i||" "]},`${l}-${c.start}`)}):J(N,{children:[I(N,{color:X,children:"> "}),ts?I(bn,{ch:" "}):fe&&!D&&me?J(so,{children:[I(bn,{ch:me[0],dim:!0}),I(N,{color:"gray",children:me.slice(1)})]}):fe&&!D?J(so,{children:[I(bn,{ch:fe[0],dim:!0}),I(N,{color:"gray",children:fe.slice(1)}),I(N,{dimColor:!0,children:" (tab)"})]}):(as.isSetup||!Pp)&&!D?J(so,{children:[I(bn,{ch:as.text[0],dim:!0}),I(N,{color:"gray",children:as.text.slice(1)})]}):I(bn,{ch:" "})]})}),Va.length>0&&I(le,{flexDirection:"column",paddingX:1,children:Va.map((c,l)=>I(N,{color:"gray",children:`\u29D7 queued: ${c}`},`${l}-${c.slice(0,24)}`))}),yo?I(Md,{tab:yo.tab,width:Ge,version:o,engineVersion:kp}):Ct?J(le,{flexDirection:"column",paddingX:1,children:[I(N,{color:X,bold:!0,children:"Select model"}),I(N,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),Ke.map((c,l)=>J(N,{color:l===Ct.cursor?X:void 0,children:[l===Ct.cursor?"\u276F ":" ",`${l+1}. ${c.label}${l===Ct.current?" \u2714":""}`.padEnd(16),I(N,{color:"gray",children:c.desc})]},c.label)),I(N,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Ze?J(le,{flexDirection:"column",paddingX:1,children:[I(N,{color:X,bold:!0,children:"Switch connection profile"}),Ze.rows.map((c,l)=>J(N,{color:l===Ze.cursor?X:void 0,children:[l===Ze.cursor?"\u276F ":" ",`${l+1}. ${c.name}${l===Ze.current?" \u2714":""}`.padEnd(20),I(N,{color:"gray",children:`${c.env} \xB7 ${c.who??"not signed in"}`}),c.prod?I(N,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},c.name)),I(N,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):et?J(le,{flexDirection:"column",paddingX:1,children:[I(N,{color:X,bold:!0,children:"Pick your Document360 environment"}),et.rows.map((c,l)=>J(N,{color:l===et.cursor?X:void 0,children:[l===et.cursor?"\u276F ":" ",`${l+1}. ${c.name}`.padEnd(16),I(N,{color:"gray",children:c.apiUrl})]},c.name)),I(N,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):$e?J(le,{flexDirection:"column",paddingX:1,children:[I(N,{color:X,bold:!0,children:"Switch workspace"}),I(N,{dimColor:!0,children:`environment ${$e.environment} \xB7 project ${$e.projectName??`${$e.projectId.slice(0,8)}\u2026`}`}),$e.rows.map((c,l)=>J(N,{color:l===$e.cursor?X:void 0,children:[l===$e.cursor?"\u276F ":" ",`${l+1}. ${c.name}${l===$e.current?" \u2714":""}`.padEnd(30),I(N,{color:"gray",children:c.type??""})]},c.id)),I(N,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):Te?J(le,{flexDirection:"column",paddingX:1,children:[I(N,{color:X,bold:!0,children:"Choose project"}),I(N,{dimColor:!0,children:`environment ${Te.environment}`}),Te.rows.map((c,l)=>J(N,{color:l===Te.cursor?X:void 0,children:[l===Te.cursor?"\u276F ":" ",`${l+1}. ${c.name}${l===Te.current?" \u2714":""}`.padEnd(30),I(N,{color:"gray",children:c.sub??""})]},c.id)),I(N,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):Ce?(()=>{let l=Math.min(Math.max(0,Ce.cursor-Math.floor(7)),Math.max(0,Ce.rows.length-14)),i=Ce.rows.slice(l,l+14),f=Ce.rows.filter(P=>P.checked).length;return J(le,{flexDirection:"column",paddingX:1,children:[I(N,{color:X,bold:!0,children:`Which folders back the user docs? (${f} selected of ${Ce.rows.length})`}),l>0?I(N,{dimColor:!0,children:` \u2191 ${l} more`}):null,i.map((P,Y)=>{let h=l+Y;return J(N,{color:h===Ce.cursor?X:void 0,children:[h===Ce.cursor?"\u276F ":" ",P.checked?"\u25C9 ":"\u25CB ",P.path.padEnd(Math.min(48,Ge-34)),I(N,{color:"gray",children:dr(P)})]},P.path)}),l+14<Ce.rows.length?I(N,{dimColor:!0,children:` \u2193 ${Ce.rows.length-l-14} more`}):null,I(N,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():tt?J(le,{flexDirection:"column",paddingX:1,children:[I(N,{color:X,bold:!0,children:"Which category? (pick one to scope to)"}),tt.rows.map((c,l)=>{let i=l===tt.cursor,f=`${l+1}.`.padEnd(3);return J(N,{color:i?X:void 0,children:[i?"\u276F ":" ",`${f} ${c.label} (${c.count})`.padEnd(Math.min(44,Math.max(20,Ge-24))),I(N,{color:"gray",children:` ${c.token}`})]},c.token)}),I(N,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):at?J(le,{flexDirection:"column",paddingX:1,children:[I(N,{color:X,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),at.rows.map((c,l)=>{let i=l===at.cursor,f=c.indent?" ":" ",P=`${l+1}.`.padEnd(3);return J(N,{color:i?X:void 0,bold:c.kind==="category"&&!i,children:[i?"\u276F ":" ",`${f}${P} ${c.label}`.padEnd(Math.min(56,Ge-24)),c.note?I(N,{color:"gray",children:c.note}):null]},`${c.kind}:${c.paths.join(",")}`)}),I(N,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):lt?J(le,{flexDirection:"column",paddingX:1,children:[I(N,{color:X,bold:!0,children:lt.title}),(()=>{let{rows:l,cursor:i}=lt,f=Math.max(0,Math.min(i-Math.floor(12/2),l.length-12)),P=l.slice(f,f+12),Y=`${l.length}.`.length+1;return J(so,{children:[f>0?I(N,{color:"gray",children:` \u2026 ${f} more above`}):null,P.map((h,y)=>{let w=f+y,g=w===i;return J(N,{color:g?X:void 0,bold:(h.kind==="all"||h.kind==="category")&&!g,children:[g?"\u276F ":" ",`${w+1}.`.padEnd(Y)," ".repeat(h.depth),h.label,h.note?I(N,{color:"gray",children:h.note}):null]},`${h.action}:${h.kind}:${h.ids.join(",")}`)}),f+12<l.length?I(N,{color:"gray",children:` \u2026 ${l.length-f-12} more below`}):null]})})(),I(N,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter run \xB7 esc cancel"})]}):De?J(le,{flexDirection:"column",paddingX:1,children:[I(N,{color:X,bold:!0,children:`Preview article${De.query?` \u2014 filter: ${De.query}`:" (type to filter)"}`}),Co.length===0?I(N,{color:"gray",children:"no articles match"}):Co.map((c,l)=>J(N,{color:l===De.cursor?X:void 0,children:[l===De.cursor?"\u276F ":" ",c]},c)),I(N,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):Ae?J(le,{flexDirection:"column",paddingX:1,children:[I(N,{color:X,bold:!0,children:`Resume session${Ae.query?` \u2014 filter: ${Ae.query}`:" (type to filter)"}`}),Ro.length===0?I(N,{color:"gray",children:"no sessions match"}):Ro.map((c,l)=>J(N,{color:l===Ae.cursor?X:void 0,children:[l===Ae.cursor?"\u276F ":" ",c.name.slice(0,28).padEnd(30),I(N,{color:l===Ae.cursor?X:"gray",children:c.firstPrompt.slice(0,Math.max(10,Ge-40))})]},c.uuid)),I(N,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Za?J(le,{flexDirection:"column",children:[Nt>0?I(N,{dimColor:!0,children:` \u22EF ${Nt} more above`}):null,ls.map((c,l)=>{let i=Nt+l;return J(N,{color:i===vo?X:void 0,children:[i===vo?"\u276F ":" ",c.usage.padEnd(22)," ",I(N,{color:i===vo?X:"gray",children:c.name==="model"&&ns?`${c.desc} (currently ${ns})`:c.desc})]},c.name)}),Nt+ls.length<Ye.length?I(N,{dimColor:!0,children:` \u22EF ${Ye.length-Nt-ls.length} more below`}):null,I(N,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!D&&!$&&be.length>0?J(le,{flexDirection:"column",paddingX:1,children:[Ha?I(N,{color:X,children:Ha}):null,be.map((c,l)=>{let i=Mt(c),f=i.slice(0,Math.max(20,Ge-5)),P=Ge-f.length-7,Y=P>=12?(qd(c)??Jl(i)).slice(0,P):"";return J(N,{children:[I(N,{color:X,children:l+1})," ",f,Y?I(N,{dimColor:!0,children:` \u2014 ${Y}`}):null]},i)}),I(N,{dimColor:!0,children:`press 1-${be.length} to fill \xB7 esc cancel`})]}):I(le,{paddingX:1,children:J(N,{color:"gray",children:[Ja.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${ns??"model n/a"}${t.kind==="api"?za>0?` \xB7 ${Pe(za)}`:"":Ya>0?` \xB7 ${gt(Ya)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}z();import{jsx as Mk}from"react/jsx-runtime";async function $p(e=process.cwd(),t="auto",n,o="0.0.0"){let r=Lk(t);r.kind==="none"&&(console.error(""),console.error(S("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}=_k(Mk(bp,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
|
|
432
|
+
`),process.exit(0)}z();import{writeCrashLog as xp,isBenignTransportError as Uk}from"document360-engine";var vp=!1;function _a(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function Cp(e){if(vp)return;vp=!0;let t=(n,o)=>{if(Uk(o)){xp({kind:n,level:"transport",message:_a(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=xp({kind:n,level:"fatal",message:_a(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
|
|
433
|
+
`+S(`\u2717 d360-writer crashed: ${_a(o)}`)+`
|
|
434
|
+
`),r&&process.stderr.write(m(` Crash details: ${r}`)+`
|
|
435
|
+
`+m(" Run: d360-writer logs")+`
|
|
436
|
+
`),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var qk=Fk(import.meta.url),Yr=qk("../package.json");Cp("d360-writer");var Be=new Wk;function La(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}Be.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=>{La(e),await Mo({profile:e.profile,manual:e.manual})});Be.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{La(e),await bl({profile:e.profile})});Be.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{La(e),await kl({profile:e.profile})});var Ma=Be.command("profile").description("Manage connection profiles for the current repo");Ma.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>Uo(process.cwd()));Ma.command("use <name>").description("Set the default profile for this repo").action(e=>Wo(process.cwd(),e));Ma.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>Fo(process.cwd(),e));var Rp=Be.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");Rp.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>rn(process.cwd(),e.profile));Rp.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await pl(process.cwd(),e,t.profile)});var Sp=Be.command("project").description("Choose the Document360 project for this repo (active profile's identity)");Sp.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>Oo(process.cwd(),e.profile));Sp.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await fl(process.cwd(),e,t.profile)});Be.command("init").description("Scaffold .d360-writer/config.json for this repo (interactive)").action(async()=>{let{initCommand:e}=await Promise.resolve().then(()=>(Yo(),Kl));await e()});Be.command("logs").description("Show the API + crash log files (send these to support when reporting a problem)").action(()=>Cl());Be.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(()=>(wr(),Tu)),n=await t(process.cwd(),Yr.version);for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});Be.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(Yr.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(Bk.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 Rl(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 Ad(e.cwd,e.auth,e.profile,Yr.version):await $p(e.cwd,e.auth,e.profile,Yr.version)});Be.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
|