document360-writer 0.5.130 → 0.5.131
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 +108 -108
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var Cu=Object.defineProperty;var mo=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var ga=(e,t)=>{for(var n in t)Cu(e,n,{get:t[n],enumerable:!0})};import tt from"picocolors";var q,Ru,Su,Pu,wa,xn,m,C,O,j,L,ie,be,F=mo(()=>{"use strict";q="#7f56d9",[Ru,Su,Pu]=[127,86,217],wa=e=>tt.isColorSupported?`\x1B[38;2;${Ru};${Su};${Pu}m${e}\x1B[39m`:e,xn=e=>tt.bold(wa(e)),m=e=>tt.dim(e),C=e=>tt.red(e),O=e=>tt.yellow(e),j=e=>tt.green(e),L=wa,ie=e=>tt.gray(e),be=e=>tt.bold(e)});import{existsSync as Xt,writeFileSync as ot,readFileSync as pp,readdirSync as hp}from"node:fs";import{join as _a}from"node:path";import{devHintsGuidePath as Ro,hintsDir as La,hooksDir as Oa,architectureDir as Ha,messagesDir as zr,creatorNotesPath as Ma,devhintsStatePath as qa,directivesPath as Ua,DIRECTIVES_HEADER as fp,roadmapPath as Wa,ROADMAP_HEADER as mp,ensureDir as Rn,writeMessage as gp,listOpenForDev as wp}from"document360-engine";function Ba(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
|
|
3
3
|
|
|
4
4
|
<!-- devhints script v${ae} \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 kp(){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 Jt(e){Rn(
|
|
236
|
-
`)}Xt(
|
|
237
|
-
`)}function
|
|
238
|
-
`)}function ze(e){try{return
|
|
239
|
-
`)}),n.notifiedBuilder=!0))}catch{}return n}function Po(e){if(!Xt(Ro(e)))return[];let t=Ie(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${ae}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,Qt,vt(),Qt,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function
|
|
240
|
-
`)}function To(){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):",Qt,
|
|
235
|
+
`}function Jt(e){Rn(La(e)),Rn(Ha(e)),Rn(zr(e));for(let n of[La(e),zr(e)]){let o=_a(n,".gitkeep");Xt(o)||ot(o,`# Keeps this document360-writer inbox tracked in git even when empty.
|
|
236
|
+
`)}Xt(Ma(e))||ot(Ma(e),kp()),Xt(Ua(e))||ot(Ua(e),fp),Xt(Wa(e))||ot(Wa(e),mp),ot(Ro(e),Ba()),Rn(Oa(e)),ot(_a(Oa(e),"open-questions.mjs"),yp);let t=Ie(e);return Ga(e,new Date().toISOString()),t}async function Va(e,t){for(let n of Zt(Jt(t.cwd)))console.log(n);return{kind:"continue"}}function vt(){return[`This is document360-writer's dev hand-off setup (v${ae}).`,'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": ${ae},`,' "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 Kr(e){try{let t=pp(qa(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function Ga(e,t){let o={...Kr(e)??{},emittedVersion:ae,emittedAt:t};ot(qa(e),`${JSON.stringify(o,null,2)}
|
|
238
|
+
`)}function ze(e){try{return hp(Ha(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function Ie(e){let n=Kr(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<ae?"stale":"current",completedVersion:n}}function So(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:ae};try{if(!Xt(Ro(e)))return n;let o=Kr(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;ae>r&&(Rn(zr(e)),ot(Ro(e),Ba()),Ga(e,t),n.guideRefreshed=!0),ae>s&&(wp(e).some(p=>p.kind==="request"&&p.subject.startsWith(Fa))||(gp(e,{id:`onb${ae}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${Fa}${ae})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${ae}${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:","",vt()].join(`
|
|
239
|
+
`)}),n.notifiedBuilder=!0))}catch{}return n}function Po(e){if(!Xt(Ro(e)))return[];let t=Ie(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${ae}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,Qt,vt(),Qt,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function Xr(){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 To(){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):",Qt,Xr(),Qt]}function Zt(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${ae}.`," 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):",Qt,vt(),Qt,"","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 Qt,ae,yp,Fa,rt=mo(()=>{"use strict";Qt="-".repeat(64),ae=10,yp=`#!/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,56 +275,56 @@ try {
|
|
|
275
275
|
} catch {
|
|
276
276
|
/* a session-start nudge must never break the session */
|
|
277
277
|
}
|
|
278
|
-
`;
|
|
279
|
-
`),"utf8")}async function Xr(){let e=process.cwd(),t=za(e);if(en(t)&&!await yp({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(m("init cancelled.")),{kind:"continue"};let n=Za(e)??Ga(e),o=await Sn({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await Sn({message:"Capture directory (where document360-capture .spec.ts files live):",default:Xa}),s=await Sn({message:"Screenshot output directory:",default:Qa}),a=await Sn({message:"Default connection profile name:",default:"berlin"}),p=await Sn({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),g={projectId:o,docsDir:Ka,captureDir:r,outputDir:s,profiles:{[a]:{connection:{environment:p},production:!1}},defaultProfile:a,authoritativeSourceFiles:el(e)},k=xp(e);k?.terminologyGlossary&&(g.terminologyGlossary=k.terminologyGlossary),Ya(g,e),Ja(e);let y=Jt(e);console.log(""),console.log(E(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${_(`d360-writer login --profile ${a}`)} ${m("(sign in; project & workspace auto-selected)")}`),console.log("");for(let S of Zt(y))console.log(S);return console.log(""),console.log(`${m("Then ask:")} ${_('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function Za(e){let t=Do(e,"package.json");if(!en(t))return null;try{return JSON.parse(kp(t,"utf8")).name??null}catch{return null}}function el(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])en(Do(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Do(e,n);en(o)&&!Cp(o)&&t.push(n)}return t}function Cp(e){try{return bp(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var Ao=mo(()=>{"use strict";W();rt()});var cc={};ma(cc,{doctorCommand:()=>In,renderDoctorChecks:()=>lc,runDoctorChecks:()=>ac});import{existsSync as gf}from"node:fs";import{d360GetAll as wf,getAccessToken as yf,isExpired as Vs,loadProfileMap as kf,loadTokens as bf,packageSkillsDir as sc,ENGINE_VERSION as $f,projectConfigPath as xf,readProjectConfig as vf,DEFAULT_DOCS_DIR as Cf,fetchManifestSummary as Rf,resolveActiveProfile as Sf,classifyClaudeAuth as Pf,CLAUDE_CODE_SETUP_HINT as ic,resolveModelSetting as Tf,probeModel as Df,detectAppType as Af,playbookSkillName as jf,D360AuthError as Ef}from"document360-engine";async function ac(e,t){let n=[];n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${$f}`});let o=Number(process.versions.node.split(".")[0]);n.push(o>=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 r=Pf();r.state==="ready"?n.push({level:"ok",label:`Claude auth: ${r.kind==="api"?"API key":"subscription (Claude Code login found)"}`}):r.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. ${ic}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:ic});let s=Tf(e);if(n.push({level:"ok",label:`Model: ${s.model} (${s.source==="auto"?"auto \u2014 right-sized for docs; /model to change":s.source})`}),r.state==="ready"){let R=await Df(e,s.model??void 0);R.ok?n.push({level:"ok",label:`Model reachable \u2014 replied in ${(R.latencyMs/1e3).toFixed(1)}s`}):R.timedOut?n.push({level:"fail",label:"Model unreachable \u2014 no response in 30s (a docs turn will hang, then end with 0 tokens / no output)",fix:`Usually a corporate proxy/firewall or org policy blocking the Claude model API. Check this machine's network access to the Claude endpoint; confirm with: claude -p "say hi"`}):n.push({level:"fail",label:`Model call failed \u2014 ${R.error??"no output"} (a docs turn will end with 0 tokens / no output)`,fix:'Check sign-in, the selected model (/model), and network access to the Claude endpoint; confirm with: claude -p "say hi"'})}let a=vf(e);if(!a)return n.push({level:"fail",label:`No ${xf(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${a.projectId}`});let p=(a.docsDir??Cf).replace(/\/+$/,"");n.push(a.mode==="engineer"?{level:"warn",label:"Mode: engineer \u2014 agent may modify any source file (dogfooding)",fix:'Remove "mode" from .d360-writer/config.json for the writer-mode boundary'}:{level:"ok",label:`Mode: writer \u2014 edits limited to ${p}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let g=a.authoritativeSourceFiles??[];n.push(g.length>0?{level:"ok",label:`Sources: docs grounded in ${g.length} path(s) (${g.slice(0,3).join(", ")}${g.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=a.appType??Af(e);if(k){let R=a.appType?"from config":"auto-detected",N=k==="web"||k==="cli";n.push({level:"ok",label:`Genre: ${k} (${R})${N?` \u2192 ${jf(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 y;try{y=Sf(e),n.push({level:"ok",label:`Profile: ${y.name} (${y.connection.name})${y.production?" \u26A0 PRODUCTION":""}`})}catch(R){return n.push({level:"fail",label:`Profile config: ${R.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let S=bf(y.name);S?Vs(S)&&!S.refreshToken?n.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):Vs(S)?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(S.expiresAt).toLocaleString()})`}):n.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${y.name})`}),n.push(y.project.workspaceId?{level:"ok",label:`Workspace: ${y.project.workspaceName??y.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let v=kf(e,y.name);v?v.projectId&&y.project.projectId&&v.projectId!==y.project.projectId?n.push({level:"fail",label:`Category map projectId (${v.projectId}) \u2260 profile projectId (${y.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):n.push({level:"ok",label:`Category map: ${Object.keys(v.articles).length} articles, ${Object.keys(v.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${y.name}" (created on first /publish)`}),n.push(gf(sc())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${sc()}`,fix:"Reinstall document360-writer (broken install)"});let I=Ie(e);if(I.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${ae})`}):I.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${I.completedVersion}, current is v${ae}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),S&&(!Vs(S)||S.refreshToken)){let R={profile:y.name,connection:y.connection};try{await yf(R);let T=await wf(R,"/v3/projects");n.push({level:"ok",label:`API reachable (${y.connection.apiUrl}) \u2014 ${T.length} project(s) visible`})}catch(T){n.push({level:"fail",label:`API call failed: ${T.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let N=v?.projectId??y.project.projectId;if(N&&y.project.workspaceId)try{let T=await Rf(R,N,y.project.workspaceId);if(T){let L=(T.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Workspace sync manifest: available on ${y.connection.name} (${T.languages?.length??0} language${(T.languages?.length??0)===1?"":"s"}) \xB7 hash ${L||"(none)"}`})}else n.push({level:"warn",label:`Workspace sync manifest: not live on ${y.connection.name} yet`,fix:"No action needed \u2014 sync uses the per-article path until the manifest ships on this environment"})}catch(T){T instanceof Ef||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(T.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${y.project.projectName??N})`,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 (${T.message.slice(0,80)})`})}}return n}function lc(e){let t=[""];for(let r of e){let s=r.level==="ok"?E("\u2713"):r.level==="warn"?O("\u26A0"):C("\u2717");t.push(` ${s} ${r.label}${r.detail?m(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${m("fix:")} ${_(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?E(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):C(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function In(e,t){console.log(m("Running checks\u2026"));for(let n of lc(await ac(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var Bo=mo(()=>{"use strict";rt();W()});import{Command as ny}from"commander";import{createRequire as oy}from"node:module";import{AUTH_MODES as ry}from"document360-engine";import{input as Uu}from"@inquirer/prompts";import{loginPkce as Wu,refreshTokens as Fu,toStoredTokens as xa,clearTokens as Hu,decodeJwtClaims as $a,isExpired as qu,loadTokens as Bu,saveTokens as va,resolveActiveProfile as ko,setProfileProject as Vu,readProjectConfig as Gu}from"document360-engine";W();import{select as Su}from"@inquirer/prompts";import{resolveActiveProfile as Pu,setProfileProject as Tu,resolveProjectId as Du,listWorkspaces as Au}from"document360-engine";async function vn(e,t){let n=Pu(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Du(o);return{workspaces:await Au(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var wa=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function Fr(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 go(e,t,n,o,r){Tu(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function ya(e,t,n){let o;try{o=await vn(e,n)}catch(s){return console.log(C(`Could not list workspaces: ${s.message}`)),1}let r=Fr(o.workspaces,t);return r?(go(e,o.profile,o.projectId,r.id,r.name),console.log(E(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(C(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function Kt(e,t){let n;try{n=await vn(e,t)}catch(k){console.log(C(`Could not list workspaces: ${k.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 k of o)console.log(` ${k.id===a?_("\u25CF"):" "} ${wa(k)} ${m(k.id)}`);console.log(m("Run: d360-writer workspace use <name>"));return}let p=await Su({message:"Select the Document360 workspace for this repo:",choices:o.map(k=>({name:`${wa(k)}${k.id===a?" (current)":""}`,value:k.id}))}),g=o.find(k=>k.id===p);go(e,s,r,p,g?.name),console.log(E(`\u2713 Workspace set to "${g?.name??p}" for profile "${s}".`))}W();import{select as ju}from"@inquirer/prompts";import{resolveActiveProfile as Eu,setProfileProject as Nu,listProjects as Iu}from"document360-engine";async function nt(e,t){let n=Eu(e,t),o={profile:n.name,connection:n.connection};return{projects:await Iu(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var ka=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Hr(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 wo(e,t,n,o){Nu(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function ba(e,t,n){let o;try{o=await nt(e,n)}catch(s){return console.log(C(`Could not list projects: ${s.message}`)),1}let r=Hr(o.projects,t);return r?(wo(e,o.profile,r.id,r.name),console.log(E(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log(C(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function yo(e,t){let n;try{n=await nt(e,t)}catch(g){console.log(C(`Could not list projects: ${g.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 g of o)console.log(` ${g.id===s?_("\u25CF"):" "} ${ka(g)} ${m(g.id)}`);console.log(m("Run: d360-writer project use <name>"));return}let a=await ju({message:"Select the Document360 project for this repo:",choices:o.map(g=>({name:`${ka(g)}${g.id===s?" (current)":""}`,value:g.id}))}),p=o.find(g=>g.id===a);wo(e,r,a,p?.name),console.log(E(`\u2713 Project set to "${p?.name??a}" for profile "${r}". Next: pick a workspace.`))}W();import _u from"picocolors";function Ou(e=process.env){return e.FORCE_HYPERLINK==="0"||!_u.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 Lu(e,t=e,n){return Ou(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Mu=/https?:\/\/[^\s\x1b]+/g;function Cn(e,t){return e.replace(Mu,n=>Lu(n,n,t))}function Ca(e){return{...$a(e.idToken)??{},...$a(e.accessToken)??{}}}function bo(e){let t=Ca(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 $o(e){let t=ko(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 Wu(n,{manual:e.manual,promptForRedirect:s=>Uu({message:s})},s=>console.log(Cn(s))),r=xa(t.name,o);if(va(r),await qr(r,t.name,s=>console.log(m(s))),console.log(""),console.log(E(`\u2713 Logged in to "${t.name}" as ${bo(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{Gu(process.cwd())?.profiles?.[t.name]&&(console.log(""),await Kt(process.cwd(),t.name))}catch{}}async function qr(e,t,n){let r=Ca(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(ko(process.cwd(),t).project.projectId)return;let a;try{let{projects:p}=await nt(process.cwd(),t);a=p.find(g=>g.id===r)?.name}catch{}Vu(process.cwd(),t,{projectId:r,projectName:a}),n(` Project "${a??r}" written to profile "${t}".`)}catch{}}async function Ra(e){let t=ko(process.cwd(),e.profile),n=t.connection,o=Bu(t.name);if(!o){console.log(C(`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 ${_(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${bo(o)}`),qu(o))if(o.refreshToken)try{let r=xa(t.name,await Fu(n,o.refreshToken));va(r),console.log(E(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(O(`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(O("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 Sa(e){let t=ko(process.cwd(),e.profile);Hu(t.name)?console.log(E(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(m(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}W();import{readProjectConfig as Pa,writeProjectConfig as Yu,resolveActiveProfile as zu,loadTokens as Ku,isExpired as Xu}from"document360-engine";function xo(e){let t=Pa(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(C("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?_("\u25CF "):" ",s=o.production?O(" \u26A0 PRODUCTION"):"",a=o.connection.environment??"(inline)",p=Ku(n),g=p?Xu(p)&&!p.refreshToken?O("expired"):m("logged in"):m("not logged in");console.log(`${r}${_(n)} \u2192 ${a}${s} [${g}]`)}console.log(""),console.log(m("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function vo(e,t){let n=Pa(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(C(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,Yu(n,e);let o=n.profiles[t].production?O(" \u26A0 PRODUCTION"):"";console.log(E(`\u2713 Default profile is now "${t}"${o}`))}function Co(e,t){try{let n=zu(e,t);console.log(""),console.log(`Profile ${_(n.name)}${n.production?O(" \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(C(n.message)),process.exitCode=1}}W();import{existsSync as Qu,readdirSync as Ju,statSync as Ta}from"node:fs";import{join as Da}from"node:path";import{apiLogDir as Zu}from"document360-engine";function Aa(){let e=Zu();if(console.log(""),console.log(`Document360 API logs: ${_(e)}`),!Qu(e)){console.log(m(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Ju(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=(Ta(Da(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=(Ta(Da(e,r)).size/1024).toFixed(1);console.log(` ${C(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("")}W();import{createSession as ep,resolveAuth as tp,findByName as np,slugify as op,touchSession as rp,upsertSession as sp,resolveActiveProfile as ip}from"document360-engine";async function ja(e,t,n,o,r,s){let a=tp(n);a.kind==="none"&&(console.error(""),console.error(C("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${_("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${_("d360-writer --auth subscription")}`),process.exit(2)),a.kind==="subscription"&&console.error(m("Using your Claude subscription (no API key set)."));let p=null;try{p=ip(e,r)}catch(v){console.error(C(`Document360 profile error: ${v.message}`)),process.exit(2)}p.production&&(console.error(O(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),s||(console.error(C("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(m(" --yes given \u2014 proceeding against production.")));let g;if(o){let v=np(e,o);v||(console.error(C(`No saved session matches "${o}" in this repo.`)),console.error(m("List sessions inside the REPL with /resume.")),process.exit(2)),g=v.uuid,console.error(m(`Resuming "${v.name}"`))}let k=ep({cwd:e,resume:g,profileName:r,allowProdWrites:s===!0}),y=g??null,S=1;for await(let v of k.send(t))switch(v.type){case"session":if(!y){y=v.sessionId;let I=new Date().toISOString();sp({uuid:y,name:op(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:I,updatedAt:I})}break;case"text":process.stdout.write(v.delta);break;case"tool":console.error(ie(` \u2699 ${v.name}`));break;case"result":S=v.ok?0:1,console.error(m(`(${v.inputTokens}\u2192${v.outputTokens} tokens`+(v.costUsd>0?`, $${v.costUsd<.01?v.costUsd.toFixed(4):v.costUsd.toFixed(2)}`:"")+")")),v.ok||console.error(C("agent finished with an error result"));break;case"error":console.error(""),console.error(C(`agent error: ${v.message}`)),process.exit(1)}y&&rp(y),process.stdout.write(`
|
|
280
|
-
`),process.exit(S)}import{createInterface as
|
|
278
|
+
`;Fa="Re-run dev\u2194docs onboarding (protocol v"});var nl={};ga(nl,{initCommand:()=>Jr,scaffoldInit:()=>Qr});import{input as Sn,confirm as bp}from"@inquirer/prompts";import{basename as Ya,join as Do}from"node:path";import{existsSync as en,readFileSync as $p,readdirSync as xp,writeFileSync as vp}from"node:fs";import{writeProjectConfig as za,readProjectConfig as Cp,projectConfigPath as Ka,writerDir as Rp,DEFAULT_DOCS_DIR as Xa,DEFAULT_CAPTURE_DIR as Qa,DEFAULT_OUTPUT_DIR as Ja}from"document360-engine";function Qr(e,t="berlin"){let n=Ka(e);if(en(n))return{created:!1,path:n,profileName:""};let o={projectId:el(e)??Ya(e),docsDir:Xa,captureDir:Qa,outputDir:Ja,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:tl(e)};return za(o,e),Za(e),{created:!0,path:n,profileName:t}}function Za(e){let t=Do(Rp(e),".gitignore");en(t)||vp(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
|
|
279
|
+
`),"utf8")}async function Jr(){let e=process.cwd(),t=Ka(e);if(en(t)&&!await bp({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(m("init cancelled.")),{kind:"continue"};let n=el(e)??Ya(e),o=await Sn({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await Sn({message:"Capture directory (where document360-capture .spec.ts files live):",default:Qa}),s=await Sn({message:"Screenshot output directory:",default:Ja}),a=await Sn({message:"Default connection profile name:",default:"berlin"}),p=await Sn({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),g={projectId:o,docsDir:Xa,captureDir:r,outputDir:s,profiles:{[a]:{connection:{environment:p},production:!1}},defaultProfile:a,authoritativeSourceFiles:tl(e)},k=Cp(e);k?.terminologyGlossary&&(g.terminologyGlossary=k.terminologyGlossary),za(g,e),Za(e);let y=Jt(e);console.log(""),console.log(j(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${L(`d360-writer login --profile ${a}`)} ${m("(sign in; project & workspace auto-selected)")}`),console.log("");for(let S of Zt(y))console.log(S);return console.log(""),console.log(`${m("Then ask:")} ${L('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function el(e){let t=Do(e,"package.json");if(!en(t))return null;try{return JSON.parse($p(t,"utf8")).name??null}catch{return null}}function tl(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])en(Do(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Do(e,n);en(o)&&!Sp(o)&&t.push(n)}return t}function Sp(e){try{return xp(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var Ao=mo(()=>{"use strict";F();rt()});var dc={};ga(dc,{doctorCommand:()=>In,renderDoctorChecks:()=>cc,runDoctorChecks:()=>lc});import{existsSync as yf}from"node:fs";import{d360GetAll as kf,getAccessToken as bf,isExpired as Ys,loadProfileMap as $f,loadTokens as xf,packageSkillsDir as ic,ENGINE_VERSION as vf,projectConfigPath as Cf,readProjectConfig as Rf,DEFAULT_DOCS_DIR as Sf,fetchManifestSummary as Pf,resolveActiveProfile as Tf,classifyClaudeAuth as Df,CLAUDE_CODE_SETUP_HINT as ac,resolveModelSetting as Af,probeModel as jf,detectAppType as Ef,playbookSkillName as Nf,D360AuthError as If}from"document360-engine";async function lc(e,t){let n=[];n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${vf}`});let o=Number(process.versions.node.split(".")[0]);n.push(o>=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 r=Df();r.state==="ready"?n.push({level:"ok",label:`Claude auth: ${r.kind==="api"?"API key":"subscription (Claude Code login found)"}`}):r.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. ${ac}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:ac});let s=Af(e);if(n.push({level:"ok",label:`Model: ${s.model} (${s.source==="auto"?"auto \u2014 right-sized for docs; /model to change":s.source})`}),r.state==="ready"){let R=await jf(e,s.model??void 0);R.ok?n.push({level:"ok",label:`Model reachable \u2014 replied in ${(R.latencyMs/1e3).toFixed(1)}s`}):R.timedOut?n.push({level:"fail",label:"Model unreachable \u2014 no response in 30s (a docs turn will hang, then end with 0 tokens / no output)",fix:`Usually a corporate proxy/firewall or org policy blocking the Claude model API. Check this machine's network access to the Claude endpoint; confirm with: claude -p "say hi"`}):n.push({level:"fail",label:`Model call failed \u2014 ${R.error??"no output"} (a docs turn will end with 0 tokens / no output)`,fix:'Check sign-in, the selected model (/model), and network access to the Claude endpoint; confirm with: claude -p "say hi"'})}let a=Rf(e);if(!a)return n.push({level:"fail",label:`No ${Cf(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${a.projectId}`});let p=(a.docsDir??Sf).replace(/\/+$/,"");n.push(a.mode==="engineer"?{level:"warn",label:"Mode: engineer \u2014 agent may modify any source file (dogfooding)",fix:'Remove "mode" from .d360-writer/config.json for the writer-mode boundary'}:{level:"ok",label:`Mode: writer \u2014 edits limited to ${p}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let g=a.authoritativeSourceFiles??[];n.push(g.length>0?{level:"ok",label:`Sources: docs grounded in ${g.length} path(s) (${g.slice(0,3).join(", ")}${g.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=a.appType??Ef(e);if(k){let R=a.appType?"from config":"auto-detected",E=k==="web"||k==="cli";n.push({level:"ok",label:`Genre: ${k} (${R})${E?` \u2192 ${Nf(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 y;try{y=Tf(e),n.push({level:"ok",label:`Profile: ${y.name} (${y.connection.name})${y.production?" \u26A0 PRODUCTION":""}`})}catch(R){return n.push({level:"fail",label:`Profile config: ${R.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let S=xf(y.name);S?Ys(S)&&!S.refreshToken?n.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):Ys(S)?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(S.expiresAt).toLocaleString()})`}):n.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${y.name})`}),n.push(y.project.workspaceId?{level:"ok",label:`Workspace: ${y.project.workspaceName??y.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let v=$f(e,y.name);v?v.projectId&&y.project.projectId&&v.projectId!==y.project.projectId?n.push({level:"fail",label:`Category map projectId (${v.projectId}) \u2260 profile projectId (${y.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):n.push({level:"ok",label:`Category map: ${Object.keys(v.articles).length} articles, ${Object.keys(v.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${y.name}" (created on first /publish)`}),n.push(yf(ic())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${ic()}`,fix:"Reinstall document360-writer (broken install)"});let _=Ie(e);if(_.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${ae})`}):_.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${_.completedVersion}, current is v${ae}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),S&&(!Ys(S)||S.refreshToken)){let R={profile:y.name,connection:y.connection};try{await bf(R);let T=await kf(R,"/v3/projects");n.push({level:"ok",label:`API reachable (${y.connection.apiUrl}) \u2014 ${T.length} project(s) visible`})}catch(T){n.push({level:"fail",label:`API call failed: ${T.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let E=v?.projectId??y.project.projectId;if(E&&y.project.workspaceId)try{let T=await Pf(R,E,y.project.workspaceId);if(T){let U=(T.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Workspace sync manifest: available on ${y.connection.name} (${T.languages?.length??0} language${(T.languages?.length??0)===1?"":"s"}) \xB7 hash ${U||"(none)"}`})}else n.push({level:"warn",label:`Workspace sync manifest: not live on ${y.connection.name} yet`,fix:"No action needed \u2014 sync uses the per-article path until the manifest ships on this environment"})}catch(T){T instanceof If||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(T.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${y.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 (${T.message.slice(0,80)})`})}}return n}function cc(e){let t=[""];for(let r of e){let s=r.level==="ok"?j("\u2713"):r.level==="warn"?O("\u26A0"):C("\u2717");t.push(` ${s} ${r.label}${r.detail?m(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${m("fix:")} ${L(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?j(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):C(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function In(e,t){console.log(m("Running checks\u2026"));for(let n of cc(await lc(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var Bo=mo(()=>{"use strict";rt();F()});import{Command as ry}from"commander";import{createRequire as sy}from"node:module";import{AUTH_MODES as iy}from"document360-engine";import{input as Fu}from"@inquirer/prompts";import{loginPkce as Hu,refreshTokens as qu,toStoredTokens as va,clearTokens as Bu,decodeJwtClaims as xa,isExpired as Vu,loadTokens as Gu,saveTokens as Ca,resolveActiveProfile as ko,setProfileProject as Yu,readProjectConfig as zu}from"document360-engine";F();import{select as Tu}from"@inquirer/prompts";import{resolveActiveProfile as Du,setProfileProject as Au,resolveProjectId as ju,listWorkspaces as Eu}from"document360-engine";async function vn(e,t){let n=Du(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??ju(o);return{workspaces:await Eu(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var ya=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function qr(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 go(e,t,n,o,r){Au(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function ka(e,t,n){let o;try{o=await vn(e,n)}catch(s){return console.log(C(`Could not list workspaces: ${s.message}`)),1}let r=qr(o.workspaces,t);return r?(go(e,o.profile,o.projectId,r.id,r.name),console.log(j(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(C(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function Kt(e,t){let n;try{n=await vn(e,t)}catch(k){console.log(C(`Could not list workspaces: ${k.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 k of o)console.log(` ${k.id===a?L("\u25CF"):" "} ${ya(k)} ${m(k.id)}`);console.log(m("Run: d360-writer workspace use <name>"));return}let p=await Tu({message:"Select the Document360 workspace for this repo:",choices:o.map(k=>({name:`${ya(k)}${k.id===a?" (current)":""}`,value:k.id}))}),g=o.find(k=>k.id===p);go(e,s,r,p,g?.name),console.log(j(`\u2713 Workspace set to "${g?.name??p}" for profile "${s}".`))}F();import{select as Nu}from"@inquirer/prompts";import{resolveActiveProfile as Iu,setProfileProject as _u,listProjects as Lu}from"document360-engine";async function nt(e,t){let n=Iu(e,t),o={profile:n.name,connection:n.connection};return{projects:await Lu(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var ba=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Br(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 wo(e,t,n,o){_u(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function $a(e,t,n){let o;try{o=await nt(e,n)}catch(s){return console.log(C(`Could not list projects: ${s.message}`)),1}let r=Br(o.projects,t);return r?(wo(e,o.profile,r.id,r.name),console.log(j(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log(C(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function yo(e,t){let n;try{n=await nt(e,t)}catch(g){console.log(C(`Could not list projects: ${g.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 g of o)console.log(` ${g.id===s?L("\u25CF"):" "} ${ba(g)} ${m(g.id)}`);console.log(m("Run: d360-writer project use <name>"));return}let a=await Nu({message:"Select the Document360 project for this repo:",choices:o.map(g=>({name:`${ba(g)}${g.id===s?" (current)":""}`,value:g.id}))}),p=o.find(g=>g.id===a);wo(e,r,a,p?.name),console.log(j(`\u2713 Project set to "${p?.name??a}" for profile "${r}". Next: pick a workspace.`))}F();import Ou from"picocolors";function Mu(e=process.env){return e.FORCE_HYPERLINK==="0"||!Ou.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 Uu(e,t=e,n){return Mu(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Wu=/https?:\/\/[^\s\x1b]+/g;function Cn(e,t){return e.replace(Wu,n=>Uu(n,n,t))}function Ra(e){return{...xa(e.idToken)??{},...xa(e.accessToken)??{}}}function bo(e){let t=Ra(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 $o(e){let t=ko(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 Hu(n,{manual:e.manual,promptForRedirect:s=>Fu({message:s})},s=>console.log(Cn(s))),r=va(t.name,o);if(Ca(r),await Vr(r,t.name,s=>console.log(m(s))),console.log(""),console.log(j(`\u2713 Logged in to "${t.name}" as ${bo(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{zu(process.cwd())?.profiles?.[t.name]&&(console.log(""),await Kt(process.cwd(),t.name))}catch{}}async function Vr(e,t,n){let r=Ra(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(ko(process.cwd(),t).project.projectId)return;let a;try{let{projects:p}=await nt(process.cwd(),t);a=p.find(g=>g.id===r)?.name}catch{}Yu(process.cwd(),t,{projectId:r,projectName:a}),n(` Project "${a??r}" written to profile "${t}".`)}catch{}}async function Sa(e){let t=ko(process.cwd(),e.profile),n=t.connection,o=Gu(t.name);if(!o){console.log(C(`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 ${L(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${bo(o)}`),Vu(o))if(o.refreshToken)try{let r=va(t.name,await qu(n,o.refreshToken));Ca(r),console.log(j(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(O(`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(O("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 Pa(e){let t=ko(process.cwd(),e.profile);Bu(t.name)?console.log(j(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(m(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}F();import{readProjectConfig as Ta,writeProjectConfig as Ku,resolveActiveProfile as Xu,loadTokens as Qu,isExpired as Ju}from"document360-engine";function xo(e){let t=Ta(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(C("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?L("\u25CF "):" ",s=o.production?O(" \u26A0 PRODUCTION"):"",a=o.connection.environment??"(inline)",p=Qu(n),g=p?Ju(p)&&!p.refreshToken?O("expired"):m("logged in"):m("not logged in");console.log(`${r}${L(n)} \u2192 ${a}${s} [${g}]`)}console.log(""),console.log(m("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function vo(e,t){let n=Ta(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(C(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,Ku(n,e);let o=n.profiles[t].production?O(" \u26A0 PRODUCTION"):"";console.log(j(`\u2713 Default profile is now "${t}"${o}`))}function Co(e,t){try{let n=Xu(e,t);console.log(""),console.log(`Profile ${L(n.name)}${n.production?O(" \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(C(n.message)),process.exitCode=1}}F();import{existsSync as Zu,readdirSync as ep,statSync as Da}from"node:fs";import{join as Aa}from"node:path";import{apiLogDir as tp}from"document360-engine";function ja(){let e=tp();if(console.log(""),console.log(`Document360 API logs: ${L(e)}`),!Zu(e)){console.log(m(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=ep(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=(Da(Aa(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=(Da(Aa(e,r)).size/1024).toFixed(1);console.log(` ${C(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("")}F();import{createSession as np,resolveAuth as op,findByName as rp,slugify as sp,touchSession as ip,upsertSession as ap,resolveActiveProfile as lp}from"document360-engine";async function Ea(e,t,n,o,r,s){let a=op(n);a.kind==="none"&&(console.error(""),console.error(C("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${L("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${L("d360-writer --auth subscription")}`),process.exit(2)),a.kind==="subscription"&&console.error(m("Using your Claude subscription (no API key set)."));let p=null;try{p=lp(e,r)}catch(v){console.error(C(`Document360 profile error: ${v.message}`)),process.exit(2)}p.production&&(console.error(O(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),s||(console.error(C("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(m(" --yes given \u2014 proceeding against production.")));let g;if(o){let v=rp(e,o);v||(console.error(C(`No saved session matches "${o}" in this repo.`)),console.error(m("List sessions inside the REPL with /resume.")),process.exit(2)),g=v.uuid,console.error(m(`Resuming "${v.name}"`))}let k=np({cwd:e,resume:g,profileName:r,allowProdWrites:s===!0}),y=g??null,S=1;for await(let v of k.send(t))switch(v.type){case"session":if(!y){y=v.sessionId;let _=new Date().toISOString();ap({uuid:y,name:sp(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:_,updatedAt:_})}break;case"text":process.stdout.write(v.delta);break;case"tool":console.error(ie(` \u2699 ${v.name}`));break;case"result":S=v.ok?0:1,console.error(m(`(${v.inputTokens}\u2192${v.outputTokens} tokens`+(v.costUsd>0?`, $${v.costUsd<.01?v.costUsd.toFixed(4):v.costUsd.toFixed(2)}`:"")+")")),v.ok||console.error(C("agent finished with an error result"));break;case"error":console.error(""),console.error(C(`agent error: ${v.message}`)),process.exit(1)}y&&ip(y),process.stdout.write(`
|
|
280
|
+
`),process.exit(S)}import{createInterface as pg}from"node:readline/promises";import{createSession as Si,resolveAuth as hg,getSession as fg,setTitle as mg,slugify as gg,touchSession as fd,upsertSession as wg,generateTitle as yg,resolveActiveProfile as md,resolveModelSetting as kg,readProjectConfig as bg,resolveAndPersistAppType as $g,decodeJwtClaims as hd,isExpired as xg,loadTokens as vg,isDirectiveMention as Cg,stripDirectiveMention as Rg,appendDirective as Sg,reconcileUpgradeActions as Pg,stampArticles as Tg,listArticleFiles as Dg,CONTENT_CAP_VERSION as Ag}from"document360-engine";import{ENGINE_VERSION as dp}from"document360-engine";var Ne=[{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 --all to author 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 /capture \u2014 the writer drives a real browser that signs in, navigates, captures, annotates."},{t:"step",n:4,s:"Re-run /publish so the images go live on Document360."},{t:"gap"},{t:"sub",s:"Helpers"},{t:"cmd",name:"/screenshot",s:"Pick a shot to author or capture (bare); /screenshot --list prints full capture status."},{t:"cmd",name:"/capture",s:"Take the screenshots for authored specs (bare = pick; id/path/--all)."},{t:"cmd",name:"/capture-setup",s:"Re-show the data-staging + test-id checklist (auto-runs after /screenshot --all)."},{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:"Author-picker (bare); author specs with <id>, a path, or --all; --list for status."},{t:"cmd",name:"/capture",s:"Take the screenshots (bare = pick ready specs; id/path/--all)."},{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 cp(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 Na(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 Ne){n.push(`\u2500\u2500 ${o.label} \u2500\u2500`,"");for(let r of o.rows)n.push(cp(r));n.push("")}return n.push("Tip: anything not starting with / goes to the agent."),n}async function Gr(e=[],t){console.log("");let n=t?.version?{version:t.version,engineVersion:dp}:void 0;for(let o of Na(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"}}F();import{getSession as up}from"document360-engine";async function Ia(e,t){let n=t.currentUuid(),o=n?up(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
|
|
284
|
+
`)),{kind:"clear"}}async function Yr(){return{kind:"exit"}}Ao();F();import{readMcpConfig as Zr,writeMcpConfig as ol}from"document360-engine";async function jo(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(Pp(),{kind:"continue"}):t==="add"?(Tp(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(Dp(e.slice(1)),{kind:"continue"}):(console.log(C(`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 Pp(){let e=Zr(),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(` ${_(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(` ${_(n)} ${m(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function Sp(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(C("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(C(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=Qr(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let a={};for(let p=1;p<o.length;p++)if(o[p]==="-H"||o[p]==="--header"){let g=o[++p],k=g?.match(/^([^:=]+)[:=](.+)$/);if(!k){console.log(C(`-H expects key:value (no spaces). Got: ${g??"(nothing)"}`));return}a[k[1].trim()]=k[2].trim()}else{console.log(C(`Unexpected argument: ${o[p]}. 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,nl(r),console.log(""),console.log(E(`\u2713 Registered "${t}" (${n})`)),console.log(O(" 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 Pp(e){let t=e[0];if(!t){console.log(C("Usage: /mcp remove <name>"));return}let n=Qr();if(!n.servers[t]){console.log(C(`No server named "${t}".`));return}delete n.servers[t],nl(n),console.log(E(`\u2713 Removed "${t}".`)),console.log(m(" Run /clear to drop it from the current session immediately."))}W();import{readFileSync as qp}from"node:fs";import{join as Bp}from"node:path";import{select as Vp}from"@inquirer/prompts";import{computeSyncStatus as Eo,planPartitions as Gp,relatedArticlePaths as Yp,resolveModelForOperation as zp,runPartitioned as Kp,loadProfileMap as Xp,resolveActiveProfile as Qp,resolveCrossLinks as Jp,applyStructureOrder as wl,orderSyncLine as yl,applyRelatedArticles as kl,relatedSyncLine as bl}from"document360-engine";import J from"picocolors";import hl from"wrap-ansi";import os from"string-width";W();import st from"picocolors";import Jr from"wrap-ansi";import Zr from"string-width";var tn=[{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 [id|path|--all]",desc:"bare: pick a shot to author or capture; id/path/--all: author capture specs (bulk also refreshes the capture checklist; --no-setup skips); --list: status",group:"docs"},{name:"capture",usage:"/capture [id|path|--all]",desc:"bare: pick ready specs to shoot; id/path/--all: take the screenshots (drives d360-capture \u2014 no separate terminal)",group:"docs"},{name:"capture-setup",usage:"/capture-setup",desc:"Re-run the data-staging checklist + dev test-id requests (auto-runs after /screenshot --all)",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]",desc:"Publish to Document360 (no arg: pick; --all: every candidate)",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 to the latest version (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"}],ol={"/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":"author screenshot capture specs","/capture":"take the screenshots for authored specs","/doctor":"run a health check"};function rl(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(ol[n])return ol[n];let o=tn.find(r=>r.name===t);return o?o.desc:""}function sl(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return tn.filter(n=>n.name.startsWith(t))}function il(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}var Tp=new RegExp(`^\\s*/(?:${tn.map(e=>e.name).join("|")})(?:\\s|$)`),al=e=>Tp.test(e),ll=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),cl=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),dl=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function Dp(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 p=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)p.push(t[o++]);o++,n.push({kind:"code",lines:p});continue}if(
|
|
288
|
-
`)}),
|
|
289
|
-
`)},
|
|
290
|
-
`)}function
|
|
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(` ${L(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(` ${L(n)} ${m(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function Tp(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(C("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(C(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=Zr(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let a={};for(let p=1;p<o.length;p++)if(o[p]==="-H"||o[p]==="--header"){let g=o[++p],k=g?.match(/^([^:=]+)[:=](.+)$/);if(!k){console.log(C(`-H expects key:value (no spaces). Got: ${g??"(nothing)"}`));return}a[k[1].trim()]=k[2].trim()}else{console.log(C(`Unexpected argument: ${o[p]}. 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,ol(r),console.log(""),console.log(j(`\u2713 Registered "${t}" (${n})`)),console.log(O(" 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 Dp(e){let t=e[0];if(!t){console.log(C("Usage: /mcp remove <name>"));return}let n=Zr();if(!n.servers[t]){console.log(C(`No server named "${t}".`));return}delete n.servers[t],ol(n),console.log(j(`\u2713 Removed "${t}".`)),console.log(m(" Run /clear to drop it from the current session immediately."))}F();import{readFileSync as Vp}from"node:fs";import{join as Gp}from"node:path";import{select as Yp}from"@inquirer/prompts";import{computeSyncStatus as Eo,planPartitions as zp,relatedArticlePaths as Kp,resolveModelForOperation as Xp,runPartitioned as Qp,loadProfileMap as Jp,resolveActiveProfile as Zp,resolveCrossLinks as eh,applyStructureOrder as yl,orderSyncLine as kl,applyRelatedArticles as bl,relatedSyncLine as $l}from"document360-engine";import J from"picocolors";import fl from"wrap-ansi";import ss from"string-width";F();import st from"picocolors";import es from"wrap-ansi";import ts from"string-width";var tn=[{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 [id|path|--all]",desc:"bare: pick a shot to author or capture; id/path/--all: author capture specs (bulk also refreshes the capture checklist; --no-setup skips); --list: status",group:"docs"},{name:"capture",usage:"/capture [id|path|--all]",desc:"bare: pick ready specs to shoot; id/path/--all: take the screenshots (drives d360-capture \u2014 no separate terminal)",group:"docs"},{name:"capture-setup",usage:"/capture-setup",desc:"Re-run the data-staging checklist + dev test-id requests (auto-runs after /screenshot --all)",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]",desc:"Publish to Document360 (no arg: pick; --all: every candidate)",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 to the latest version (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"}],rl={"/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":"author screenshot capture specs","/capture":"take the screenshots for authored specs","/doctor":"run a health check"};function sl(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(rl[n])return rl[n];let o=tn.find(r=>r.name===t);return o?o.desc:""}function il(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return tn.filter(n=>n.name.startsWith(t))}function al(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}var Ap=new RegExp(`^\\s*/(?:${tn.map(e=>e.name).join("|")})(?:\\s|$)`),ll=e=>Ap.test(e),cl=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),dl=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),ul=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function jp(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 p=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)p.push(t[o++]);o++,n.push({kind:"code",lines:p});continue}if(cl(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&dl(t[o+1])){let p=ul(r);o+=2;let g=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)g.push(ul(t[o++]));n.push({kind:"table",header:p,rows:g});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 p=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);){let g=t[o++];p.push({ordered:/^\s*\d+\.\s+/.test(g),text:g.replace(/^\s*([-*]|\d+\.)\s+/,"")})}n.push({kind:"list",items:p});continue}if(r.trim()===""){o++;continue}if(ll(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])&&!ll(t[o])&&!cl(t[o])&&!(t[o].includes("|")&&o+1<t.length&&dl(t[o+1]));)a.push(t[o++]);n.push({kind:"para",text:a.join(" ")})}return n}function ns(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?st.bold(t.slice(2,-2)):t.startsWith("`")?L(t.slice(1,-1)):st.italic(t.slice(1,-1)))}var Ep=(e,t)=>e+" ".repeat(Math.max(0,t-ts(e)));function Np(e,t,n){let o=e.length,r=e.map((R,E)=>Math.max(ts(R),...t.map(T=>ts(T[E]??"")))),s=Math.max(24,n),a=3*o+1,p=[...r],g=()=>p.reduce((R,E)=>R+E,0)+a,k=0;for(;g()>s&&k++<1e4;){let R=-1,E=6;for(let T=0;T<o;T++)p[T]>E&&(E=p[T],R=T);if(R===-1)break;p[R]-=1}let y=(R,E,T)=>st.gray(R+p.map(U=>"\u2500".repeat(U+2)).join(E)+T),S=st.gray("\u2502"),v=(R,E)=>{let T=p.map((Y,z)=>{let pe=R[z]??"",Xe=E?st.bold(pe):ns(pe);return es(Xe,Y,{hard:!0}).split(`
|
|
288
|
+
`)}),U=Math.max(...T.map(Y=>Y.length)),G=[];for(let Y=0;Y<U;Y++)G.push(p.map((z,pe)=>`${S} ${Ep(T[pe][Y]??"",z)} `).join("")+S);return G.join(`
|
|
289
|
+
`)},_=[y("\u250C","\u252C","\u2510"),v(e,!0)];return _.push(t.length===0?y("\u2514","\u2534","\u2518"):y("\u251C","\u253C","\u2524")),t.forEach((R,E)=>{_.push(v(R,!1)),_.push(E===t.length-1?y("\u2514","\u2534","\u2518"):y("\u251C","\u253C","\u2524"))}),_.join(`
|
|
290
|
+
`)}function Ip(e,t){switch(e.kind){case"heading":return st.bold(e.text);case"hr":return st.gray("\u2500".repeat(t));case"para":return es(ns(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="",...p]=es(ns(o.text),Math.max(10,t-s.length)).split(`
|
|
291
291
|
`);return` ${r} ${a}`+p.map(g=>`
|
|
292
292
|
${s}${g}`).join("")}).join(`
|
|
293
293
|
`)}case"code":return e.lines.map(n=>st.gray(" "+n)).join(`
|
|
294
|
-
`);case"table":return
|
|
294
|
+
`);case"table":return Np(e.header,e.rows,t)}}function os(e,t){let n=Math.max(20,t);return jp(e).map(o=>Ip(o,n)).join(`
|
|
295
295
|
|
|
296
|
-
`)}
|
|
297
|
-
`);let r=2,s=3,a=
|
|
296
|
+
`)}F();import _p from"picocolors";var Lp=[127,86,217],Op=[22,38,43],pl={T:Lp,E:Op},Pn=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],rs=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,Mp=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function hl(){if(!_p.isColorSupported)return[];let e=Pn[0].length,t=[];for(let n=0;n<Pn.length;n+=2){let o="";for(let r=0;r<e;r++){let s=pl[Pn[n][r]],a=n+1<Pn.length?pl[Pn[n+1][r]]:void 0;s&&a?o+=`${rs(s)}${Mp(a)}\u2580\x1B[49m\x1B[39m`:s?o+=`${rs(s)}\u2580\x1B[39m`:a?o+=`${rs(a)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function Tn(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 Dn(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function $e(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function it(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var nn=(e,t)=>` ${e.padEnd(13)}${t}`;function Up(e,t){let n=[xn("\u270E document360-writer")+J.gray(` v${e.version} \xB7 engine v${e.engineVersion}`),J.gray(" Reads your code, writes your docs."),"",nn("Claude:",`${e.claude}${J.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),nn("Document360:",e.configured?e.loggedOut?J.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?J.gray(` (${e.sessionHint})`):""}`:J.yellow("not set up \u2014 run /init")),nn("Profile:",e.configured?`${e.profile}${J.gray(` (${e.apiUrl})`)}${e.prod?J.bold(J.yellow(" \u26A0 PRODUCTION")):""}`:J.gray("\u2014 (run /init)")),nn("Project:",e.project),nn("Mode:",J.gray(e.mode)),nn("cwd:",J.gray(e.cwd))],o=hl();if(o.length===0)return n.join(`
|
|
297
|
+
`);let r=2,s=3,a=ss(o[0]);if(!(t>=r+a+s+Math.max(...n.map(y=>ss(y)))))return[...o.map(y=>" "+y),...n].join(`
|
|
298
298
|
`);let g=Math.max(0,Math.floor((n.length-o.length)/2)),k=[];for(let y=0;y<Math.max(o.length+g,n.length);y++){let S=o[y-g]??" ".repeat(a);k.push((" ".repeat(r)+S+" ".repeat(s)+(n[y]??"")).trimEnd())}return k.join(`
|
|
299
|
-
`)}var
|
|
300
|
-
`).flatMap(k=>
|
|
299
|
+
`)}var Wp={error:J.red,warn:J.yellow,ok:J.green,info:J.gray};function is(e){return e.replace(/^(\s*• |)([^\x00-\x7F][\u{1F000}-\u{1FAFF}️]*) (?=\S)/gmu,"$1$2 ")}function as(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return Up(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",s=Math.max(10,n-4),a=50,p=e.text.split(`
|
|
300
|
+
`).flatMap(k=>fl(k,s,{hard:!0}).split(`
|
|
301
301
|
`)),g=Math.max(0,p.length-a);return g>0&&(p=[...p.slice(0,a),J.dim(`\u2026 +${g} more lines`)]),`
|
|
302
|
-
`+p.map((k,y)=>o+(y===0?
|
|
302
|
+
`+p.map((k,y)=>o+(y===0?L(" \u276F "):" ")+k+" ".repeat(Math.max(0,s-ss(k))+1)+r).join(`
|
|
303
303
|
`)}case"assistant":return`
|
|
304
|
-
`+
|
|
305
|
-
`+
|
|
304
|
+
`+os(e.text,n);case"tool":{let o=e.arg!==null?J.gray(`${e.sep}(${e.arg})`):"";return`
|
|
305
|
+
`+fl(J.green("\u25CF ")+J.bold(e.title)+o,n)}case"tool-result":{let o=e.isError?J.red:J.gray,r=e.lines.map((s,a)=>o((a===0?" \u23BF ":" ")+s));return e.hidden>0&&r.push(J.dim(` \u2026 +${e.hidden} lines`)),r.join(`
|
|
306
306
|
`)}case"diff":{let o=a=>a===1?"":"s",s=[J.gray(` \u23BF Added ${e.added} line${o(e.added)}, removed ${e.removed} line${o(e.removed)}`),...e.lines];return e.hidden>0&&s.push(J.dim(` \u2026 +${e.hidden} more diff lines`)),s.join(`
|
|
307
|
-
`)}case"link":return e.lines.map(o=>
|
|
307
|
+
`)}case"link":return e.lines.map(o=>L(Cn(` \u2B95 ${o}`))).join(`
|
|
308
308
|
`);case"preview":return`
|
|
309
309
|
`+xn(`\u25A3 Preview \u2014 ${e.name}`)+`
|
|
310
310
|
|
|
311
|
-
`+
|
|
312
|
-
`+
|
|
313
|
-
`+(e.ok?J.magenta("\u2736 "):J.red("\u2736 "))+J.gray(`Cooked for ${Dn(e.seconds)} \xB7 ${Tn(e.tokens)} tokens out${o}`+(e.costUsd>0?` \xB7 ${$e(e.costUsd)}`:""))}}}function
|
|
314
|
-
`)}import{resolveActiveProfile as
|
|
315
|
-
`)}var
|
|
316
|
-
`)}function
|
|
317
|
-
`),display:"/audit"}}
|
|
318
|
-
`)}async function
|
|
319
|
-
`);return
|
|
320
|
-
`)||
|
|
321
|
-
`},r=o(e),s=o(t);if(r===s)return null;let a=Math.max(20,n-10),p=ih("a","b",r,s,"","",{context:3}),g=0,k=0,y=[];p.hunks.forEach((v,I)=>{I>0&&y.push(Pl.gray(" \u2026"));let R=v.oldStart,N=v.newStart,T=[],L=[],G=()=>{for(let Y=0;Y<T.length;Y++){let z=Y<L.length?Al(T[Y],L[Y]):void 0;k++,y.push(`${ah}${hs(R++)} - ${jl(T[Y],a,z)}${Dl}`)}for(let Y=0;Y<L.length;Y++){let z=Y<T.length?Al(T[Y],L[Y]):void 0;g++,y.push(`${lh}${hs(N++)} + ${jl(L[Y],a,z)}${Dl}`)}T=[],L=[]};for(let Y of v.lines){let z=Y[0],pe=Y.slice(1);z==="-"?T.push(pe):z==="+"?L.push(pe):(G(),y.push(Pl.gray(hs(N))+" "+pe.slice(0,a)),R++,N++)}G()});let S=y.slice(0,Tl);return{added:g,removed:k,lines:S,hidden:Math.max(0,y.length-Tl)}}W();import{select as ch}from"@inquirer/prompts";import{applyPull as dh,computeSyncStatus as uh,planPull as ph}from"document360-engine";var El=e=>e===1?"":"s";async function fs(e,t){console.log(""),console.log(`${_("\u25CF")} ${be(t.title)} ${ie(`(${t.path})`)}`);for(let r of t.notes)console.log(O(` \u26A0 ${r}`));let n=Ke(t.oldContent,t.newContent,Math.max(40,(process.stdout.columns??80)-1));if(n){console.log(ie(` \u23BF local \u2192 portal: +${n.added} / -${n.removed} line${El(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(()=>ch({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"?(dh({cwd:e.cwd,profileName:e.profileName},t),console.log(E(" \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 Nl(e,t){let n=_e(t.cwd,t.profileName);if(!n.ok)return console.log(C(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let s=(await uh({cwd:t.cwd,profileName:t.profileName})).entries.filter(p=>p.status==="conflict"&&p.path).map(p=>p.path);if(o){if(!s.includes(o))return console.log(E(`${o} isn't in conflict \u2014 nothing to resolve.`)),{kind:"continue"};s=[o]}if(s.length===0)return console.log(E("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let a=[];for(let p of s){let g=await ph({cwd:t.cwd,profileName:t.profileName,relPath:p});await fs(t,g)==="keep-local"&&a.push(p)}if(a.length>0)return console.log(m(`Publishing ${a.length} kept-local article${El(a.length)} over the portal\u2026`)),await Ct(t,a)}catch(r){console.log(C(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function Ol(e,t){let n=_e(t.cwd,t.profileName);if(!n.ok)return console.log(C(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await bh(t),{kind:"continue"};if(o==="--baseline")return await $h(t,e.filter(a=>a!=="--baseline")),{kind:"continue"};if(o==="--compare")return await xh(t),{kind:"continue"};if(o)return console.log(C(`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 vh(t,r),{kind:"continue"};console.log(m("Pulling changes from Document360\u2026"));let s=await gs({cwd:t.cwd,profileName:t.profileName});for(let a of ws(s))console.log(a.tone==="ok"?E(a.text):a.tone==="warn"?O(a.text):m(a.text));console.log("")}catch(r){r instanceof kh?console.log(C(r.message)):console.log(C(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function gs(e){let t=await Il({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 _l({cwd:e.cwd,profileName:e.profileName,relPath:o.path});ms({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 mh({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});gh({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 Wo=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Rt=e=>e===1?"":"s";function ws(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${Rt(e.pulled.length)} into local: ${Wo(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${Rt(e.imported.length)}: ${Wo(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${Rt(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${Rt(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). (${Wo(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${Rt(e.failed.length)} failed: ${Wo(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 bh(e){console.log(m("Checking Document360 for drift\u2026"));let t=Date.now(),n=await Il({cwd:e.cwd,profileName:e.profileName});for(let o of Uo(n,Date.now()-t))console.log(o);console.log("")}async function $h(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 wh({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await yh({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(E("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(E(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(E(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(O(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(m(` - ${s.path} (${s.reason})`))}}async function xh(e){console.log(m("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await fh({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${be(String(t.legacyCount))} \xB7 Manifest: ${be(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(E("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(C(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(O(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(O(` ${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 vh(e,t){let n=t.replace(/\\/g,"/"),o=await _l({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await fs(e,o)==="keep-local"&&(console.log(m(`Publishing ${o.path} over the portal\u2026`)),await Ct(e,[o.path]));return}console.log(""),console.log(`${_("\u25CF")} ${be(o.title)} ${ie(`(${o.path})`)}`);for(let a of o.notes)console.log(O(` \u26A0 ${a}`));let r=Ke(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.")),ms({cwd:e.cwd,profileName:e.profileName},o);return}console.log(ie(` \u23BF Added ${r.added} line${Rt(r.added)}, removed ${r.removed} line${Rt(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(()=>hh({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(m(" Skipped."));return}ms({cwd:e.cwd,profileName:e.profileName},o),console.log(E(` \u2713 Pulled ${o.path} (sync base advanced).`))}W();import{statSync as Ch}from"node:fs";import{resolve as Rh}from"node:path";import{estimateBulkCost as Sh,planPartitions as Ph,readProjectConfig as Th,resolveModelForOperation as Dh,runPartitioned as Ah,trackedArticlePaths as jh}from"document360-engine";var ys=3;function ks(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 bs(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function $s(e,t){return t.map(n=>{let o=0;try{o=Ch(Rh(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function xs(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:
|
|
311
|
+
`+os(e.text,n);case"note":return`
|
|
312
|
+
`+Wp[e.tone](Cn(is(e.text)));case"done":{let o=e.inTokens&&e.inTokens>0?` \xB7 ${Tn(e.inTokens)} in${e.cachedPct!=null?` (${e.cachedPct}% cached)`:""}`:"";return`
|
|
313
|
+
`+(e.ok?J.magenta("\u2736 "):J.red("\u2736 "))+J.gray(`Cooked for ${Dn(e.seconds)} \xB7 ${Tn(e.tokens)} tokens out${o}`+(e.costUsd>0?` \xB7 ${$e(e.costUsd)}`:""))}}}function ml(e,t){return e.map(n=>as(n,t)).join(`
|
|
314
|
+
`)}import{resolveActiveProfile as Fp,loadTokens as Hp,isExpired as qp,decodeJwtClaims as gl}from"document360-engine";function Bp(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function _e(e,t){try{let n=Fp(e,t),o=Hp(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(qp(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={...gl(o.idToken)??{},...gl(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 ${Bp(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}var An=3;function ls(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, strip every <!-- SCREENSHOT ... --> block while keeping the visible [Screenshot: ...] line, normalize cross-article links).","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(`
|
|
315
|
+
`)}var wl={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function cs(e){return e.filter(t=>t.path!==null&&t.status in wl&&!t.link).map(t=>({path:t.path,label:wl[t.status]}))}function No(e){let t=cs(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 Io(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 _o(e){return e.filter(t=>t.link).length}function ds(e,t){try{let n=Jp(e,Zp(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=eh(Vp(Gp(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 th(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 xl(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,p)=>a.path.localeCompare(p.path));n.push({kind:"category",label:`${th(r)} (${s.length})`,paths:s.map(a=>a.path),indent:!1});for(let a of s){let p=a.path.replace(/\\/g,"/").split("/").pop()??a.path;n.push({kind:"article",label:p,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 Lo(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(`
|
|
316
|
+
`)}function us(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,_)=>v+o(_),0),p=r.reduce((v,_)=>v+o(_),0),g=n==="api"?`${$e(e.reduce((v,_)=>v+_.costUsd,0))} total`:it(e.reduce((v,_)=>v+_.outputTokens,0)),k=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,y=v=>`${v} article${v===1?"":"s"}`,S=[];if(s.length===0)S.push(`Published ${y(a)} (${k}) successfully \xB7 ${g}.`),S.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{S.push(`Published ${p}/${y(a)} (${k}) \xB7 ${g}.`),S.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /publish --all to retry just the rest (published articles are skipped):`);for(let v of s)S.push(` \u2717 ${v.label}${v.error?` \u2014 ${v.error}`:""}`)}return S}async function Ct(e,t){let{model:n}=Xp(e.cwd,"standard"),o=async(r,s)=>{let a=zp(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${An} agents at once) on ${n}\u2026`)),s||console.log(m(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let p=!1;for await(let g of Qp({cwd:e.cwd,partitions:a,promptFor:k=>Lo(k.paths),concurrency:An,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:n}))if(g.type==="partition_status")g.status==="running"?console.log(m(` \u25B8 ${g.label} \u2014 publishing\u2026`)):g.status==="done"?console.log(j(` \u2713 ${g.label}`)):console.log(C(` \u2717 ${g.label}`));else if(g.type==="run_done"){p=g.aborted,console.log("");let k=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let S of us(g.results,a,k))console.log(g.ok?j(S):O(S));let y=ds(e.cwd,e.profileName);y&&console.log(m(y));try{let S=kl(await yl({cwd:e.cwd,profileName:e.profileName}));S&&console.log(m(S))}catch{}try{let S=$l(await bl({cwd:e.cwd,profileName:e.profileName}));S&&console.log(m(S))}catch{}}return p};try{if(!await o(t,!1)){let s=await ps(e.cwd,e.profileName,t);s.length>0&&await o(s,!0)}}catch(r){console.log(C(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function Oo(e,t,n){let o=Kp(e,n);if(o.length===0)return[];let r=new Set(cs((await Eo({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function ps(e,t,n){try{let o=new Set(n),r=await Eo({cwd:e,profileName:t});return cs(r.entries).map(s=>s.path).filter(s=>o.has(s))}catch{return[]}}async function vl(e,t){let n=_e(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(C(n.reason)),{kind:"continue"};let o=e[0];if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await Oo(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return r.length===0?(console.log(j("\u2713 All related articles are already published.")),{kind:"continue"}):await Ct(t,r)}if(o==="--all"){console.log(m("Checking what needs publishing\u2026"));try{let r=await Eo({cwd:t?.cwd??process.cwd()}),{clean:s,conflicts:a}=No(r.entries),p=_o(r.entries),g=e.includes("--force")&&a.length>0;p>0&&console.log(O(`\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.`)),a.length>0&&!g&&console.log(O(Io(a.length)));let k=g?[...s,...a]:s;if(k.length===0){if(a.length>0)return console.log(m("Resolve the conflicts: /resolve")),{kind:"continue"};if(console.log(j(p>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),t)try{let y=kl(await yl({cwd:t.cwd,profileName:t.profileName}));y&&console.log(m(y));let S=$l(await bl({cwd:t.cwd,profileName:t.profileName}));S&&console.log(m(S))}catch{}return{kind:"continue"}}return t?await Ct(t,k.map(y=>y.path)):{kind:"forward-to-agent",prompt:Lo(k.map(y=>y.path)),display:"/publish --all"}}catch(r){return console.log(C(`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 Eo({cwd:t?.cwd??process.cwd()}),{clean:a,conflicts:p}=No(s.entries);r=a;let g=_o(s.entries);if(g>0&&console.log(O(`\u26A0 ${g} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),p.length>0&&console.log(O(Io(p.length))),r.length===0&&p.length>0)return console.log(m("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(s){return console.log(C(`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(j("\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(()=>Yp({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 Ct(t,r.map(s=>s.path))}return{kind:"forward-to-agent",prompt:ls(o),display:`/publish ${o}`}}async function jn(){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(`
|
|
317
|
+
`),display:"/audit"}}F();import{readProjectConfig as nh}from"document360-engine";function hs(){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(`
|
|
318
|
+
`)}async function Cl(e,t){let n=t?.cwd??process.cwd();return nh(n)?{kind:"forward-to-agent",prompt:hs(),display:"/discover"}:(console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"})}F();import{checkbox as oh}from"@inquirer/prompts";import{inventoryRepo as rh,readProjectConfig as Rl,writeProjectConfig as sh}from"document360-engine";function fs(e,t){let n=Rl(e);n&&(n.authoritativeSourceFiles=t,sh(n,e))}function Mo(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 Sl(e,t){let n=t?.cwd??process.cwd();if(!Rl(n))return console.log(C("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=rh(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(L("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${m(Mo(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>oh({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${Mo(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"};fs(n,r),console.log(j(`\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"}}F();import{confirm as mh}from"@inquirer/prompts";import{applyPull as ws,computeSyncStatus as _l,compareRemoteSources as gh,planPull as Ll,planImport as wh,applyImport as yh,establishBaselines as kh,rebaselineServerMeta as bh,D360AuthError as $h}from"document360-engine";F();var Pl=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /publish <path>):",paint:C,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /publish <path>:",paint:O,mark:"M"},{status:"remote-ahead",header:"Changed on Document360 \u2014 pull with /pull <path> (or just /pull):",paint:L,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:C,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:C,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint:ie,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:ie,mark:"\xB7"}];function ih(e){return e.path?e.path:`${e.title??"(untitled)"} ${ie(`[${e.articleId}]`)}`}function ah(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 Uo(e,t){let n=[],o=e.entries.filter(y=>y.link);if(o.length>0){n.push(""),n.push(be("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let y of o)n.push(` ${O("~")} ${O(y.path??"")} ${ie(`\u2192 "${y.link.title}"`)}`)}for(let y of Pl){let S=e.entries.filter(v=>v.status===y.status&&!(y.status==="untracked-local"&&v.link));if(S.length!==0){n.push(""),n.push(be(y.header));for(let v of S)n.push(` ${y.paint(y.mark)} ${y.paint(ih(v))}${v.detail?ie(` (${v.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"},p=o.length,g=s===r?j("\u2713 everything up to date"):[r>0?j(`\u2713 ${r} up to date`):null,p>0?`${p} to link`:null,...Pl.map(y=>{let S=(e.counts[y.status]??0)-(y.status==="untracked-local"?p:0);return S>0?`${S} ${a[y.status]}`:null})].filter(Boolean).join(ie(" \xB7 ")),k=t!==void 0?` \xB7 synced in ${ah(t)}`:"";return n.push(g+ie(` \xB7 ${s} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${k}`)),n}import{structuredPatch as lh}from"diff";import Tl from"picocolors";var Dl=80,ch="\x1B[48;2;74;28;28m",dh="\x1B[48;2;24;66;24m",Al="\x1B[49m",ms=e=>String(e).padStart(5);function jl(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}function El(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 Ke(e,t,n){let o=v=>{let _=v.replace(/\r\n/g,`
|
|
319
|
+
`);return _.endsWith(`
|
|
320
|
+
`)||_===""?_:_+`
|
|
321
|
+
`},r=o(e),s=o(t);if(r===s)return null;let a=Math.max(20,n-10),p=lh("a","b",r,s,"","",{context:3}),g=0,k=0,y=[];p.hunks.forEach((v,_)=>{_>0&&y.push(Tl.gray(" \u2026"));let R=v.oldStart,E=v.newStart,T=[],U=[],G=()=>{for(let Y=0;Y<T.length;Y++){let z=Y<U.length?jl(T[Y],U[Y]):void 0;k++,y.push(`${ch}${ms(R++)} - ${El(T[Y],a,z)}${Al}`)}for(let Y=0;Y<U.length;Y++){let z=Y<T.length?jl(T[Y],U[Y]):void 0;g++,y.push(`${dh}${ms(E++)} + ${El(U[Y],a,z)}${Al}`)}T=[],U=[]};for(let Y of v.lines){let z=Y[0],pe=Y.slice(1);z==="-"?T.push(pe):z==="+"?U.push(pe):(G(),y.push(Tl.gray(ms(E))+" "+pe.slice(0,a)),R++,E++)}G()});let S=y.slice(0,Dl);return{added:g,removed:k,lines:S,hidden:Math.max(0,y.length-Dl)}}F();import{select as uh}from"@inquirer/prompts";import{applyPull as ph,computeSyncStatus as hh,planPull as fh}from"document360-engine";var Nl=e=>e===1?"":"s";async function gs(e,t){console.log(""),console.log(`${L("\u25CF")} ${be(t.title)} ${ie(`(${t.path})`)}`);for(let r of t.notes)console.log(O(` \u26A0 ${r}`));let n=Ke(t.oldContent,t.newContent,Math.max(40,(process.stdout.columns??80)-1));if(n){console.log(ie(` \u23BF local \u2192 portal: +${n.added} / -${n.removed} line${Nl(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(()=>uh({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"?(ph({cwd:e.cwd,profileName:e.profileName},t),console.log(j(" \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 Il(e,t){let n=_e(t.cwd,t.profileName);if(!n.ok)return console.log(C(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let s=(await hh({cwd:t.cwd,profileName:t.profileName})).entries.filter(p=>p.status==="conflict"&&p.path).map(p=>p.path);if(o){if(!s.includes(o))return console.log(j(`${o} isn't in conflict \u2014 nothing to resolve.`)),{kind:"continue"};s=[o]}if(s.length===0)return console.log(j("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let a=[];for(let p of s){let g=await fh({cwd:t.cwd,profileName:t.profileName,relPath:p});await gs(t,g)==="keep-local"&&a.push(p)}if(a.length>0)return console.log(m(`Publishing ${a.length} kept-local article${Nl(a.length)} over the portal\u2026`)),await Ct(t,a)}catch(r){console.log(C(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function Ol(e,t){let n=_e(t.cwd,t.profileName);if(!n.ok)return console.log(C(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await xh(t),{kind:"continue"};if(o==="--baseline")return await vh(t,e.filter(a=>a!=="--baseline")),{kind:"continue"};if(o==="--compare")return await Ch(t),{kind:"continue"};if(o)return console.log(C(`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 Rh(t,r),{kind:"continue"};console.log(m("Pulling changes from Document360\u2026"));let s=await ys({cwd:t.cwd,profileName:t.profileName});for(let a of ks(s))console.log(a.tone==="ok"?j(a.text):a.tone==="warn"?O(a.text):m(a.text));console.log("")}catch(r){r instanceof $h?console.log(C(r.message)):console.log(C(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function ys(e){let t=await _l({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 Ll({cwd:e.cwd,profileName:e.profileName,relPath:o.path});ws({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 wh({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});yh({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 Wo=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Rt=e=>e===1?"":"s";function ks(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${Rt(e.pulled.length)} into local: ${Wo(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${Rt(e.imported.length)}: ${Wo(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${Rt(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${Rt(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). (${Wo(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${Rt(e.failed.length)} failed: ${Wo(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 xh(e){console.log(m("Checking Document360 for drift\u2026"));let t=Date.now(),n=await _l({cwd:e.cwd,profileName:e.profileName});for(let o of Uo(n,Date.now()-t))console.log(o);console.log("")}async function vh(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 kh({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await bh({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(j("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(j(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(j(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(O(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(m(` - ${s.path} (${s.reason})`))}}async function Ch(e){console.log(m("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await gh({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${be(String(t.legacyCount))} \xB7 Manifest: ${be(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(j("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(C(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(O(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(O(` ${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 Rh(e,t){let n=t.replace(/\\/g,"/"),o=await Ll({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await gs(e,o)==="keep-local"&&(console.log(m(`Publishing ${o.path} over the portal\u2026`)),await Ct(e,[o.path]));return}console.log(""),console.log(`${L("\u25CF")} ${be(o.title)} ${ie(`(${o.path})`)}`);for(let a of o.notes)console.log(O(` \u26A0 ${a}`));let r=Ke(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.")),ws({cwd:e.cwd,profileName:e.profileName},o);return}console.log(ie(` \u23BF Added ${r.added} line${Rt(r.added)}, removed ${r.removed} line${Rt(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(()=>mh({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(m(" Skipped."));return}ws({cwd:e.cwd,profileName:e.profileName},o),console.log(j(` \u2713 Pulled ${o.path} (sync base advanced).`))}F();import{statSync as Sh}from"node:fs";import{resolve as Ph}from"node:path";import{estimateBulkCost as Th,planPartitions as Dh,readProjectConfig as Ah,resolveModelForOperation as jh,runPartitioned as Eh,trackedArticlePaths as Nh}from"document360-engine";var bs=3;function $s(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 xs(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function vs(e,t){return t.map(n=>{let o=0;try{o=Sh(Ph(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function Cs(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:
|
|
322
322
|
- 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.
|
|
323
323
|
- 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.
|
|
324
324
|
- 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.
|
|
325
325
|
- Work only on these files:
|
|
326
326
|
`+e.paths.map(t=>`- ${t}`).join(`
|
|
327
|
-
`)}function
|
|
327
|
+
`)}function Rs(e,t,n){let o=e.reduce((p,g)=>p+g.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(p=>` \u2022 ${p.label} \u2014 ${p.paths.length} article${p.paths.length===1?"":"s"}`),"",`Estimated cost: ${$e(r)}\u2013${$e(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function Ss(e,t,n){let o=R=>t[R.index]?.paths.length??0,r=e.filter(R=>R.ok),s=e.filter(R=>!R.ok),a=e.reduce((R,E)=>R+o(E),0),p=r.reduce((R,E)=>R+o(E),0),g=e.reduce((R,E)=>R+E.costUsd,0),k=e.reduce((R,E)=>R+E.outputTokens,0),y=n==="api"?`${$e(g)} total`:it(k),S=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,v=R=>`${R} article${R===1?"":"s"}`,_=[];if(s.length===0)_.push(`Converted ${v(a)} (${S}) successfully \xB7 ${y}.`);else{_.push(`Converted ${p}/${v(a)} (${S}) \xB7 ${y}.`),_.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let R of s)_.push(` \u2717 ${R.label}${R.error?` \u2014 ${R.error}`:""}`)}return _}async function Ml(e,t){if(!Ah(t.cwd))return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=$s(e),r=Nh(t.cwd,t.profileName);if(r.length===0)return console.log(C("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let s=xs(r,n);if(s.length===0)return console.log(C(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let a=Dh(s),p=`/convert${n?` --scope ${n}`:""} --run`,{model:g,forced:k}=jh(t.cwd,"light");if(!o){let y=Th({files:vs(t.cwd,s),op:"convert",model:g});n&&console.log(m(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let S of Rs(a,y,bs))console.log(S);return console.log(m(`Model: ${g}${k?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(m(`Run ${p} to start.`)),console.log(""),{kind:"continue"}}console.log(m(`Converting ${s.length} articles across ${a.length} partitions (\u2264${bs} agents at once) on ${g}\u2026`)),console.log(m(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let y of Eh({cwd:t.cwd,partitions:a,promptFor:Cs,concurrency:bs,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:g}))if(y.type==="partition_status")y.status==="running"?console.log(m(` \u25B8 ${y.label} \u2014 converting\u2026`)):y.status==="done"?console.log(j(` \u2713 ${y.label}`)):console.log(C(` \u2717 ${y.label}`));else if(y.type==="run_done"){console.log("");let S=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let v of Ss(y.results,a,S))console.log(y.ok?j(v):O(v))}}catch(y){console.log(C(`Convert run failed: ${y.message}`))}return console.log(""),{kind:"continue"}}F();import{statSync as Fl}from"node:fs";import{resolve as Hl}from"node:path";import{estimateBulkCost as Hh,lintDocs as qh,planPartitions as Bh,readDocsPlan as Vh,readProjectConfig as ql,DEFAULT_DOCS_DIR as Gh,resolveModelForOperation as Yh,runPartitioned as zh,stampArticles as Kh,CONTENT_CAP_VERSION as Xh}from"document360-engine";import{readProjectConfig as Ih,loadProfileMap as _h,resolveActiveProfile as Lh,desiredCategoryOrder as Oh,desiredArticleOrder as Mh,DEFAULT_DOCS_DIR as Uh}from"document360-engine";var Ps=e=>e.replace(/\\/g,"/"),Wh=e=>Ps(e).split("/").pop()??e;function Fh(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}function En(e,t){try{let n=Ih(e);if(!n)return[];let o=Lh(e,t),r=_h(e,o.name);if(!r)return[];let s=Ps(n.docsDir??Uh).replace(/\/+$/,""),a=new Map;for(let g of Mh(r))a.set(g.categoryPath,(a.get(g.categoryPath)??0)+1);let p=[];for(let g of Oh(r)){let k=Ps(g.path),y=k.startsWith(`${s}/`)?k.slice(s.length+1):k===s?"":k;y&&p.push({token:y,label:Fh(Wh(k)),count:a.get(g.path)??0})}return p}catch{return[]}}function Ul(e,t){let n=En(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 at(e,t){return t.includes("--all")||t.some(n=>!n.startsWith("--"))?!1:e==="review"||e==="reorder"||e==="write"&&t.includes("--rewrite")}function on(e,t,n,o){let r=En(e,o);if(r.length<=1)return[];let s=n.filter(k=>k.startsWith("--")).join(" "),a=s?` ${s}`:"",p=`/${t}${a} --all`.replace(/\s+/g," "),g=k=>t==="write"?`/write --scope ${k}${a}`:`/${t} ${k}${a}`;return[`Bare /${t} covers the WHOLE knowledge base (${r.reduce((k,y)=>k+y.count,0)} articles). Pick a target:`,` ${p} (everything)`,...r.map(k=>` ${g(k.token)} (${k.label} \xB7 ${k.count} article${k.count===1?"":"s"})`)]}function Fo(e){let t=e.indexOf("--scope");if(t===-1)return!1;let n=e[t+1];return n===void 0||n.startsWith("-")}function Wl(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 Qh=3,Jh=8;function Ts(e){return e===void 0||!Number.isFinite(e)?Qh:Math.max(1,Math.min(Math.floor(e),Jh))}function Ds(e){let t,n,o=!1,r=!1,s,a=g=>{let k=Number(g);return g!==void 0&&Number.isFinite(k)?k:void 0};for(let g=0;g<e.length;g++){let k=e[g];if(k==="--preview"||k==="--dry-run")o=!0;else if(k==="--rewrite"||k==="--force")r=!0;else{if(k==="--run"||k==="--yes"||k==="--all")continue;k==="--scope"?t=e[++g]:k?.startsWith("--scope=")?t=k.slice(8):k==="--concurrency"?s=a(e[++g]):k?.startsWith("--concurrency=")?s=a(k.slice(14)):k&&!k.startsWith("--")&&(n=k)}}let p=g=>g?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:p(t),path:p(n),preview:o,concurrency:s,rewrite:r}}function Zh(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function ef(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function As(e,t,n){return n.filter(o=>{try{return Fl(Hl(e,t,o)).size===0}catch{return!0}})}function js(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+=Fl(Hl(e,a)).size}catch{}return{path:r,bytes:s}})}function Es(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.
|
|
328
328
|
`:"";return`Run the write-article skill to author EACH documentation article listed below. For each path:
|
|
329
329
|
- 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).
|
|
330
330
|
- 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).
|
|
@@ -334,90 +334,90 @@ ${s}${g}`).join("")}).join(`
|
|
|
334
334
|
- 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.
|
|
335
335
|
Articles:
|
|
336
336
|
`+e.paths.map(r=>`- ${r}`).join(`
|
|
337
|
-
`)}function
|
|
338
|
-
`)}var
|
|
339
|
-
`)}var Fs="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 Kl(e,t){let n=t?.cwd??process.cwd();if(!rf(n))return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=Us(e);if(!r&&Ms(n)===0)return console.log(m(Fs)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:Ws(r,o),display:s}}W();import{search as sf}from"@inquirer/prompts";import{findByName as af,getSession as lf,listSessions as cf,relativeTime as Ql}from"document360-engine";async function Jl(e,t){let n=cf(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=af(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(C(`No session matches "${o}".`)),Xl(n),{kind:"continue"})}if(!process.stdin.isTTY)return Xl(n),console.log(m("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>sf({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let a=(s??"").toLowerCase();return n.filter(p=>!a||p.name.toLowerCase().includes(a)||p.firstPrompt.toLowerCase().includes(a)).map(p=>({name:`${p.name} ${Ql(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=lf(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function Xl(e){console.log("");for(let t of e.slice(0,15))console.log(` ${_(t.name)} ${m(Ql(t.updatedAt))}`),console.log(` ${m(t.firstPrompt.slice(0,80))}`);console.log("")}W();import{renameSession as df}from"document360-engine";function Hs(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 Zl(e,t){let n=Hs(e.join(" "));if(!n)return console.log(C("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(df(o,n)?console.log(E(`\u2713 Session renamed to "${n}"`)):console.log(C("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(E(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as ec,readProjectConfig as uf,writeProjectConfig as pf}from"document360-engine";W();function qs(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=uf(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 ec().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},pf(o,e),null):`Unknown environment "${r}". Known: ${ec().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function tc(e,t){let n=e[0];if(!n)return xo(t.cwd),{kind:"continue"};if(n==="add"){let o=qs(t.cwd,e[1],e[2]);return o?(console.log(C(o)),{kind:"continue"}):(console.log(E(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${_(`/profile ${e[1]}`)} then ${_("/login")}`),{kind:"continue"})}return vo(t.cwd,n),Co(t.cwd,n),console.log(m(" Restarting agent for the new profile\u2026")),{kind:"clear"}}W();import{select as hf}from"@inquirer/prompts";import{readProjectConfig as ff,readUserConfig as nc,resolveModelSetting as Bs,writeUserConfig as oc}from"document360-engine";var Fe=[{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 qo(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=Fe.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function mf(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 Nn(e,t){let n=()=>Bs(e).model;if(t==="default"){let s=nc();return s.defaultModel?(delete s.defaultModel,oc(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${Bs(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}}oc({...nc(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=ff(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 rc(e,t){let n=e[0]?.trim();if(!n){let a=Bs(t.cwd);if(!process.stdin.isTTY)return console.log(`${be("Model:")} ${_(a.model)}${a.source==="auto"?m(" (auto)"):""}`),console.log(m(` source: ${mf(a)}`)),console.log(m(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let p=qo(a),g;try{g=await t.withPausedInput(()=>hf({message:`Select model (current: ${a.model}${a.source==="auto"?" \xB7 auto":""})`,default:Fe[p].value,choices:Fe.map((v,I)=>({name:`${v.label}${I===p?" \u2714":""}`,value:v.value,description:v.desc}))}))}catch{return console.log(m("Cancelled.")),{kind:"continue"}}let{lines:k,changed:y,effective:S}=Nn(t.cwd,g??"default");for(let v of k)console.log(v.startsWith("\u26A0")?O(v):v.startsWith("\u2713")?E(v):m(v));return y&&await t.setModel(S),{kind:"continue"}}let{lines:o,changed:r,effective:s}=Nn(t.cwd,n);for(let a of o)console.log(a.startsWith("\u26A0")?O(a):a.startsWith("\u2713")?E(a):m(a));return r&&await t.setModel(s),{kind:"continue"}}Bo();async function dc(e,t){return await t.withPausedInput(()=>Kt(t.cwd)),{kind:"clear"}}async function uc(e,t){return await t.withPausedInput(()=>yo(t.cwd,t.profileName)),{kind:"clear"}}W();import{resolveActiveProfile as Nf}from"document360-engine";async function pc(e,t){let n=!1;try{n=Nf(t.cwd).production}catch{}return n?(console.log(O("\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"})}W();var hc=async(e,t)=>{try{await t.withPausedInput(()=>$o({}))}catch(n){console.log(C(`Login failed: ${n.message}`))}return{kind:"continue"}};W();import{resolveActiveProfile as If,clearTokens as _f,clearProfileProject as Of}from"document360-engine";async function fc(e,t){let n;try{n=If(t.cwd,t.profileName).name}catch(r){return console.log(C(r.message)),{kind:"continue"}}let o=_f(n);return Of(t.cwd,n),console.log(o?E(`\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{existsSync as Gs}from"node:fs";import{isAbsolute as gc,join as wc,resolve as yc}from"node:path";import{readProjectConfig as kc,screenshotPlaceholderIds as Lf,DEFAULT_CAPTURE_DIR as bc,DEFAULT_OUTPUT_DIR as Mf}from"document360-engine";var mc=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Ys(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?mc(n[1]):void 0};let o=n[0];return o?o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:mc(o),setup:t}:{mode:"single",id:o}:{mode:"list",picker:!0}}function St(e,t){let n=kc(e),o=n?.captureDir??bc,r=n?.outputDir??Mf,s=(a,p)=>gc(a)?wc(a,p):yc(e,a,p);return Lf(e,{scope:t}).map(({id:a,file:p})=>{let g=Gs(s(r,`${a}.png`))?"captured":Gs(s(o,`${a}.spec.ts`))?"spec":"placeholder";return{id:a,file:p,state:g}})}function $c(e,t){let n=kc(e)?.captureDir??bc;return Gs(gc(n)?wc(n,`${t}.spec.ts`):yc(e,n,`${t}.spec.ts`))}var Uf={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},Wf={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function Vo(e,t){if(e.length===0)return[t?`No screenshot placeholders under ${t}.`:"No screenshot placeholders found in the docs."];let n=[...new Set(e.map(s=>s.file))].sort(),o=e.filter(s=>s.state==="captured").length,r=[`Screenshots: ${e.length} placeholder${e.length===1?"":"s"} across ${n.length} article${n.length===1?"":"s"} \xB7 ${o} captured${t?` \xB7 scope ${t}`:""}`,""];for(let s of n){r.push(s);for(let a of e.filter(p=>p.file===s))r.push(` ${Uf[a.state]} ${a.id.padEnd(34)} ${Wf[a.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function xc(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),indent:!1});let r=new Map;for(let s of t){let a=r.get(s.file);a?a.push(s):r.set(s.file,[s])}for(let s of[...r.keys()].sort()){let a=r.get(s);if(a.length===1){o.push({kind:"shot",action:"author",label:a[0].id,ids:[a[0].id],indent:!1,note:` ${s}`});continue}o.push({kind:"article",action:"author",label:`${s} (${a.length})`,ids:a.map(p=>p.id),indent:!1});for(let p of a)o.push({kind:"shot",action:"author",label:p.id,ids:[p.id],indent:!0})}n.length>1&&o.push({kind:"all",action:"capture",label:`Capture all ${n.length} ready specs`,ids:n.map(s=>s.id),indent:!1});for(let s of n)o.push({kind:"shot",action:"capture",label:s.id,ids:[s.id],indent:n.length>1,note:" \u25D0 ready \u2014 enter captures"});return o}function vc(e){return["Run the emit-screenshot-spec skill to author the document360-capture spec for EACH of these","SCREENSHOT placeholder ids:",e.paths.map(t=>`- ${t}`).join(`
|
|
337
|
+
`)}function Ns(e,t,n){let o=e.reduce((a,p)=>a+p.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: ${$e(r)}\u2013${$e(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function Is(e,t,n){let o=R=>t[R.index]?.paths.length??0,r=e.filter(R=>R.ok),s=e.filter(R=>!R.ok),a=e.reduce((R,E)=>R+o(E),0),p=r.reduce((R,E)=>R+o(E),0),g=e.reduce((R,E)=>R+E.costUsd,0),k=e.reduce((R,E)=>R+E.outputTokens,0),y=n==="api"?`${$e(g)} total`:it(k),S=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,v=R=>`${R} article${R===1?"":"s"}`,_=[];if(s.length===0)_.push(`Wrote ${v(a)} (${S}) successfully \xB7 ${y}.`),_.push("Next \u2014 push them to Document360:"),_.push("/publish --all"),_.push("Or add screenshots first with /screenshot --all. Drafts are reviewable in the portal after publishing.");else{_.push(`Wrote ${p}/${v(a)} (${S}) \xB7 ${y}.`),_.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let R of s)_.push(` \u2717 ${R.label}${R.error?` \u2014 ${R.error}`:""}`)}return _}function _s(e,t,n){try{let o=qh({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 Ls(e,t,n){let o=(ql(e)?.docsDir??Gh).replace(/\/+$/,""),r=t.map(p=>p.path);if(n.path){let p=Zh(n.path,o);return r.includes(p)?{docsDir:o,targets:[p],planCount:r.length}:{docsDir:o,targets:[],planCount:r.length,reason:`"${p}" isn't in the docs plan (.d360-writer/plan.json).`}}let s=ef(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=As(e,o,s);if(a.length===0){let p=n.scope?` under "${n.scope}"`:"",g=n.scope?` --scope ${n.scope}`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${p} are already written. Use /write <path> to rewrite one, or /write${g} --rewrite to regenerate them all.`}}return{docsDir:o,targets:a,planCount:r.length}}async function Bl(e,t){if(!ql(t.cwd))return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};if(Fo(e)){for(let U of Ul(t.cwd,t.profileName))console.log(m(U));return{kind:"continue"}}if(at("write",e)){let U=on(t.cwd,"write",e,t.profileName);if(U.length>0){for(let G of U)console.log(m(G));return{kind:"continue"}}}let n=Vh(t.cwd);if(n.length===0)return console.log(C("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:p}=Ds(e),{docsDir:g,targets:k,reason:y,rewriting:S}=Ls(t.cwd,n,{scope:o,path:r,rewrite:p});if(k.length===0)return console.log(y?O(y):O("Nothing to write.")),{kind:"continue"};S&&console.log(O(`--rewrite: regenerating ${k.length} already-written article${k.length===1?"":"s"} (overwrites them; git has your baseline).`));let v=Bh(k),_=Ts(a),{model:R,forced:E}=Yh(t.cwd,"standard"),T=!!r;if(s&&!T){let U=Hh({files:js(t.cwd,n,k),op:"write",model:R});o&&console.log(m(`Scope: ${o} (${k.length} pending).`));for(let G of Ns(v,U,_))console.log(G);return console.log(m(`Model: ${R}${E?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(m(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}console.log(m(`Writing ${k.length} article${k.length===1?"":"s"} across ${v.length} partition${v.length===1?"":"s"} (\u2264${_} agents at once) on ${R}\u2026`)),console.log(m(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let U of zh({cwd:t.cwd,partitions:v,promptFor:G=>Es(G,g,{rewrite:S||T}),concurrency:_,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:R}))if(U.type==="partition_status")U.status==="running"?console.log(m(` \u25B8 ${U.label} \u2014 writing\u2026`)):U.status==="done"?console.log(j(` \u2713 ${U.label}`)):console.log(C(` \u2717 ${U.label}`));else if(U.type==="run_done"){console.log("");let G=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let z of Is(U.results,v,G))console.log(U.ok?j(z):O(z));if(U.ok)try{Kh(t.cwd,k.map(z=>`${g}/${z}`),{writtenCap:Xh})}catch{}let Y=_s(t.cwd,g,k);Y&&console.log(O(Y))}}catch(U){console.log(C(`Write run failed: ${U.message}`))}return console.log(""),{kind:"continue"}}F();import{existsSync as tf,readdirSync as Vl,statSync as Gl}from"node:fs";import{join as Yl}from"node:path";import{inputDir as nf,readProjectConfig as of}from"document360-engine";var zl=/\.(md|markdown|pdf|txt)$/i;function Os(e){let t=nf(e);if(!tf(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of Vl(t)){let s=Yl(t,r),a=!1;try{a=Gl(s).isDirectory()}catch{continue}if(a){if(r.startsWith("."))continue;let p=rf(s);p>0&&n.push({name:r,docCount:p})}else zl.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function rf(e){let t=0;for(let n of Vl(e))try{Gl(Yl(e,n)).isFile()&&zl.test(n)&&t++}catch{}return t}function Ms(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 Ho(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(`
|
|
338
|
+
`)}var Us="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function Kl(e,t){let n=t?.cwd??process.cwd();if(!of(n))return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=Os(n);if(o.length===0&&r===0)return console.log(m(Us)),{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 g of o)console.log(` ${g.name} ${m(`(${g.docCount} doc${g.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let p=o[0]?.name??"";return{kind:"forward-to-agent",prompt:Ho(p),display:p?`/draft ${p}`:"/draft"}}let a=Ms(o,s);return{kind:"forward-to-agent",prompt:Ho(a??"",a?void 0:s),display:`/draft ${s}`}}F();import{listOpenForDocs as sf,readProjectConfig as af}from"document360-engine";function Ws(e){try{return sf(e).filter(t=>t.kind==="request").length}catch{return 0}}function Fs(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function Hs(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(`
|
|
339
|
+
`)}var qs="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 Xl(e,t){let n=t?.cwd??process.cwd();if(!af(n))return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=Fs(e);if(!r&&Ws(n)===0)return console.log(m(qs)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:Hs(r,o),display:s}}F();import{search as lf}from"@inquirer/prompts";import{findByName as cf,getSession as df,listSessions as uf,relativeTime as Jl}from"document360-engine";async function Zl(e,t){let n=uf(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=cf(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(C(`No session matches "${o}".`)),Ql(n),{kind:"continue"})}if(!process.stdin.isTTY)return Ql(n),console.log(m("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>lf({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let a=(s??"").toLowerCase();return n.filter(p=>!a||p.name.toLowerCase().includes(a)||p.firstPrompt.toLowerCase().includes(a)).map(p=>({name:`${p.name} ${Jl(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=df(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function Ql(e){console.log("");for(let t of e.slice(0,15))console.log(` ${L(t.name)} ${m(Jl(t.updatedAt))}`),console.log(` ${m(t.firstPrompt.slice(0,80))}`);console.log("")}F();import{renameSession as pf}from"document360-engine";function Bs(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 ec(e,t){let n=Bs(e.join(" "));if(!n)return console.log(C("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(pf(o,n)?console.log(j(`\u2713 Session renamed to "${n}"`)):console.log(C("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(j(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as tc,readProjectConfig as hf,writeProjectConfig as ff}from"document360-engine";F();function Vs(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=hf(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 tc().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},ff(o,e),null):`Unknown environment "${r}". Known: ${tc().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function nc(e,t){let n=e[0];if(!n)return xo(t.cwd),{kind:"continue"};if(n==="add"){let o=Vs(t.cwd,e[1],e[2]);return o?(console.log(C(o)),{kind:"continue"}):(console.log(j(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${L(`/profile ${e[1]}`)} then ${L("/login")}`),{kind:"continue"})}return vo(t.cwd,n),Co(t.cwd,n),console.log(m(" Restarting agent for the new profile\u2026")),{kind:"clear"}}F();import{select as mf}from"@inquirer/prompts";import{readProjectConfig as gf,readUserConfig as oc,resolveModelSetting as Gs,writeUserConfig as rc}from"document360-engine";var Fe=[{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 qo(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=Fe.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function wf(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 Nn(e,t){let n=()=>Gs(e).model;if(t==="default"){let s=oc();return s.defaultModel?(delete s.defaultModel,rc(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${Gs(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}}rc({...oc(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=gf(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 sc(e,t){let n=e[0]?.trim();if(!n){let a=Gs(t.cwd);if(!process.stdin.isTTY)return console.log(`${be("Model:")} ${L(a.model)}${a.source==="auto"?m(" (auto)"):""}`),console.log(m(` source: ${wf(a)}`)),console.log(m(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let p=qo(a),g;try{g=await t.withPausedInput(()=>mf({message:`Select model (current: ${a.model}${a.source==="auto"?" \xB7 auto":""})`,default:Fe[p].value,choices:Fe.map((v,_)=>({name:`${v.label}${_===p?" \u2714":""}`,value:v.value,description:v.desc}))}))}catch{return console.log(m("Cancelled.")),{kind:"continue"}}let{lines:k,changed:y,effective:S}=Nn(t.cwd,g??"default");for(let v of k)console.log(v.startsWith("\u26A0")?O(v):v.startsWith("\u2713")?j(v):m(v));return y&&await t.setModel(S),{kind:"continue"}}let{lines:o,changed:r,effective:s}=Nn(t.cwd,n);for(let a of o)console.log(a.startsWith("\u26A0")?O(a):a.startsWith("\u2713")?j(a):m(a));return r&&await t.setModel(s),{kind:"continue"}}Bo();async function uc(e,t){return await t.withPausedInput(()=>Kt(t.cwd)),{kind:"clear"}}async function pc(e,t){return await t.withPausedInput(()=>yo(t.cwd,t.profileName)),{kind:"clear"}}F();import{resolveActiveProfile as _f}from"document360-engine";async function hc(e,t){let n=!1;try{n=_f(t.cwd).production}catch{}return n?(console.log(O("\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"})}F();var fc=async(e,t)=>{try{await t.withPausedInput(()=>$o({}))}catch(n){console.log(C(`Login failed: ${n.message}`))}return{kind:"continue"}};F();import{resolveActiveProfile as Lf,clearTokens as Of,clearProfileProject as Mf}from"document360-engine";async function mc(e,t){let n;try{n=Lf(t.cwd,t.profileName).name}catch(r){return console.log(C(r.message)),{kind:"continue"}}let o=Of(n);return Mf(t.cwd,n),console.log(o?j(`\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{existsSync as zs}from"node:fs";import{isAbsolute as wc,join as yc,resolve as kc}from"node:path";import{readProjectConfig as bc,screenshotPlaceholderIds as Uf,DEFAULT_CAPTURE_DIR as $c,DEFAULT_OUTPUT_DIR as Wf}from"document360-engine";var gc=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Ks(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?gc(n[1]):void 0};let o=n[0];return o?o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:gc(o),setup:t}:{mode:"single",id:o}:{mode:"list",picker:!0}}function St(e,t){let n=bc(e),o=n?.captureDir??$c,r=n?.outputDir??Wf,s=(a,p)=>wc(a)?yc(a,p):kc(e,a,p);return Uf(e,{scope:t}).map(({id:a,file:p})=>{let g=zs(s(r,`${a}.png`))?"captured":zs(s(o,`${a}.spec.ts`))?"spec":"placeholder";return{id:a,file:p,state:g}})}function xc(e,t){let n=bc(e)?.captureDir??$c;return zs(wc(n)?yc(n,`${t}.spec.ts`):kc(e,n,`${t}.spec.ts`))}var Ff={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},Hf={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function Vo(e,t){if(e.length===0)return[t?`No screenshot placeholders under ${t}.`:"No screenshot placeholders found in the docs."];let n=[...new Set(e.map(s=>s.file))].sort(),o=e.filter(s=>s.state==="captured").length,r=[`Screenshots: ${e.length} placeholder${e.length===1?"":"s"} across ${n.length} article${n.length===1?"":"s"} \xB7 ${o} captured${t?` \xB7 scope ${t}`:""}`,""];for(let s of n){r.push(s);for(let a of e.filter(p=>p.file===s))r.push(` ${Ff[a.state]} ${a.id.padEnd(34)} ${Hf[a.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function vc(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),indent:!1});let r=new Map;for(let s of t){let a=r.get(s.file);a?a.push(s):r.set(s.file,[s])}for(let s of[...r.keys()].sort()){let a=r.get(s);if(a.length===1){o.push({kind:"shot",action:"author",label:a[0].id,ids:[a[0].id],indent:!1,note:` ${s}`});continue}o.push({kind:"article",action:"author",label:`${s} (${a.length})`,ids:a.map(p=>p.id),indent:!1});for(let p of a)o.push({kind:"shot",action:"author",label:p.id,ids:[p.id],indent:!0})}n.length>1&&o.push({kind:"all",action:"capture",label:`Capture all ${n.length} ready specs`,ids:n.map(s=>s.id),indent:!1});for(let s of n)o.push({kind:"shot",action:"capture",label:s.id,ids:[s.id],indent:n.length>1,note:" \u25D0 ready \u2014 enter captures"});return o}function Cc(e){return["Run the emit-screenshot-spec skill to author the document360-capture spec for EACH of these","SCREENSHOT placeholder ids:",e.paths.map(t=>`- ${t}`).join(`
|
|
340
340
|
`),"","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."].join(`
|
|
341
|
-
`)}async function Go(e,t){let n=
|
|
341
|
+
`)}async function Go(e,t){let n=Ks(e);if(n.mode==="list"){let a=t?.cwd??process.cwd(),p=St(a,n.scope);for(let k of Vo(p,n.scope))console.log(k);let g=p.filter(k=>k.state==="placeholder").length;return g>0&&(console.log(""),console.log(`Author specs: /screenshot <id> (one shot) \xB7 /screenshot <path> (a folder) \xB7 /screenshot --all (all ${g} unauthored)`)),{kind:"continue"}}if(n.mode==="single")return{kind:"forward-to-agent",prompt:[`Run the emit-screenshot-spec skill for the SCREENSHOT placeholder with id \`${n.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>/${n.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."].join(`
|
|
342
342
|
`),display:`/screenshot ${n.id}`};let r=[`Run the emit-screenshot-spec skill to (re)generate the document360-capture spec for ${n.mode==="scope"?`every <!-- SCREENSHOT --> placeholder in articles under ${n.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.${n.setup?" When done, run capture-setup-checklist to refresh CAPTURE-SETUP.md.":""} Report specs written, TODO data-testids, and data to stage.`].join(`
|
|
343
|
-
`),s=n.mode==="scope"?`/screenshot ${n.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:r,display:s}}import{spawn as
|
|
344
|
-
`)}var
|
|
345
|
-
`),display:"/capture-setup"}}var
|
|
346
|
-
`)}async function
|
|
347
|
-
`)}var
|
|
348
|
-
`).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function
|
|
343
|
+
`),s=n.mode==="scope"?`/screenshot ${n.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:r,display:s}}import{spawn as qf}from"node:child_process";import{existsSync as Rc,statSync as Bf}from"node:fs";import{isAbsolute as Vf,join as Sc,resolve as Gf}from"node:path";import{readProjectConfig as Yf,DEFAULT_OUTPUT_DIR as zf}from"document360-engine";var Kf=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Xs(e){let t=e.find(n=>!n.startsWith("--"));return e.includes("--all")?{mode:"all"}:t?/[\\/]/.test(t)||t.endsWith(".md")?{mode:"scope",scope:Kf(t)}:{mode:"single",id:t}:{mode:"picker"}}function Qs(e,t){let n=St(e,t);return{ready:n.filter(o=>o.state==="spec").map(o=>o.id),captured:n.filter(o=>o.state==="captured").map(o=>o.id)}}function Pc(e){let t=e.filter(s=>s.state==="spec"),n=e.filter(s=>s.state==="captured"),o=[];t.length>1&&o.push({kind:"all",action:"capture",label:`Capture all ${t.length} ready specs`,ids:t.map(s=>s.id),indent:!1});let r=new Map;for(let s of t){let a=r.get(s.file);a?a.push(s):r.set(s.file,[s])}for(let s of[...r.keys()].sort()){let a=r.get(s);if(a.length===1){o.push({kind:"shot",action:"capture",label:a[0].id,ids:[a[0].id],indent:!1,note:` ${s}`});continue}o.push({kind:"article",action:"capture",label:`${s} (${a.length})`,ids:a.map(p=>p.id),indent:!1});for(let p of a)o.push({kind:"shot",action:"capture",label:p.id,ids:[p.id],indent:!0})}for(let s of[...n].sort((a,p)=>a.id.localeCompare(p.id)))o.push({kind:"shot",action:"capture",label:s.id,ids:[s.id],indent:!1,note:" \u25CF captured \u2014 re-capture"});return o}function Xf(e,t){let n=Yf(e)?.outputDir??zf;return Vf(n)?Sc(n,`${t}.png`):Gf(e,n,`${t}.png`)}function Js(e,t,n,o){let r=Xf(e,t);return Rc(r)&&Bf(r).mtimeMs>=o?"captured":n===0?"skipped":"failed"}function Tc(e){let t=/⊘[^\n—]*—\s*(.+)/.exec(e);return t?t[1].trim():null}function Dc(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(`
|
|
344
|
+
`)}var Qf=/^[A-Za-z0-9._-]+$/;function Zs(e){return new Promise((t,n)=>{if(!Qf.test(e.id)){n(new Error(`Not a valid spec id: "${e.id}"`));return}let o=qf(`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 Ac(e,t){return e===127||/is not recognized as an internal or external command|command not found/i.test(t)}function Yo(e){return Rc(Sc(e,".d360-writer","capture.json"))}function jc(e,t){let n=new Map(St(e).map(o=>[o.id,o.file]));return[...new Set(t.map(o=>n.get(o)).filter(o=>!!o))].sort()}async function Ec(e,t){let n=t?.cwd??process.cwd(),o=Xs(e);if(!Yo(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}=Qs(n,o.mode==="scope"?o.scope:void 0),a=o.mode==="single"?[o.id]:o.mode==="picker"?r:[...r,...s];if(a.length===0)return console.log("No authored specs to capture yet \u2014 author them first: /screenshot"),{kind:"continue"};let p=Date.now(),g=[];for(let y of a){console.log(`\u25B6 ${y}`);try{let{exitCode:S}=await Zs({cwd:n,id:y,stdio:"inherit"});g.push({id:y,outcome:Js(n,y,S,p)})}catch(S){if(S.code==="ENOENT")return console.log("d360-capture is not installed. Run: npm i -g document360-capture"),{kind:"continue"};g.push({id:y,outcome:"failed",detail:S.message})}}let k=y=>g.filter(S=>S.outcome===y).length;return console.log(`\u2713 ${k("captured")} captured \xB7 \u2298 ${k("skipped")} skipped \xB7 \u2717 ${k("failed")} failed`),{kind:"continue"}}import{existsSync as Jf,readFileSync as Zf}from"node:fs";import{isAbsolute as em,join as tm,resolve as nm}from"node:path";import{readProjectConfig as om,DEFAULT_CAPTURE_DIR as rm}from"document360-engine";async function _n(){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-capture.json, then synthesize a deduped, grouped","\u201Cstage this data\u201D checklist and write it to <captureDir>/CAPTURE-SETUP.md. Separate transient/manual","states, flag any spec whose prerequisites are vague, and report the path when done."].join(`
|
|
345
|
+
`),display:"/capture-setup"}}var Nc="-".repeat(64);function ei(e){let t=rm;try{let y=om(e);y?.captureDir&&(t=y.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=em(t)?tm(t,"CAPTURE-TESTID-REQUESTS.json"):nm(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!Jf(n))return null;let o;try{let y=JSON.parse(Zf(n,"utf8").replace(/^/,""));o=Array.isArray(y?.requests)?y.requests:[]}catch{return null}if(o.length===0)return null;let r=new Set(o.map(y=>y.file).filter(Boolean)).size,s=o.length,a=`${s} data-testid attribute${s===1?"":"s"}`,p=`${r} source file${r===1?"":"s"}`,g=`${t}/CAPTURE-TESTID-REQUESTS.md`,k=`${t}/CAPTURE-TESTID-REQUESTS.json`;return[`\u{1F4CB} Developer hand-off \u2014 ${a} requested across ${p}.`,"\u26A0 Do NOT run this prompt here. d360-writer documents code; it does not change it \u2014"," these edits belong in your code repo. Open a SEPARATE terminal in:",` ${e}`," start Claude Code (or your coding agent), and paste everything between the lines."," Tip: run it in plan mode first \u2014 these are a hypothesis to verify, not a verified patch.","",Nc,`Read ${g} and ${k}. 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.",Nc]}rt();F();import{listOpenForDocs as sm,readProjectConfig as im}from"document360-engine";function ti(e){try{return sm(e).length}catch{return 0}}function ni(){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(`
|
|
346
|
+
`)}async function Ic(e,t){let n=t?.cwd??process.cwd();return im(n)?ti(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:ni(),display:"/inbox"}:(console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"})}F();import{listOpenHints as am,listOpenForDocs as lm,listOpenDirectives as cm,readProjectConfig as dm,computeSyncStatus as um,planPull as pm,applyPull as hm,planImport as fm,applyImport as mm}from"document360-engine";function Ln(e){let t=0,n=0,o=0,r=0;try{t=am(e).length}catch{}try{let s=lm(e);n=s.filter(a=>a.kind==="request").length,o=s.filter(a=>a.kind==="answer").length}catch{}try{r=cm(e).length}catch{}return{hints:t,requests:n,answers:o,directives:r}}function On(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 ri(e){return{publish:e.includes("--publish")}}function si({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(`
|
|
347
|
+
`)}var gm={status:um,plan:pm,apply:hm,planImport:fm,applyImport:mm};async function ii(e,t=gm){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 oi=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,zo=e=>e===1?"":"s";function ai(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${zo(e.pulled.length)} into local: ${oi(e.pulled)}`),e.imported.length&&t.push(`\u2713 Imported ${e.imported.length} new portal article${zo(e.imported.length)} into local drafts: ${oi(e.imported)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${zo(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${oi(e.conflicts)}`),e.failed.length&&t.push(`\u26A0 ${e.failed.length} pull/import${zo(e.failed.length)} failed \u2014 left for /pull.`),t}async function _c(e,t){let n=t?.cwd??process.cwd();if(!dm(n))return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=_e(n,t?.profileName);if(!o.ok)return console.log(C(o.reason)),{kind:"continue"};let{publish:r}=ri(e);console.log(m("Reconciling with Document360 (pulling any portal changes)\u2026"));let s=await ii({cwd:n,profileName:t?.profileName});for(let p of ai(s))console.log(p.startsWith("\u2713")?j(p):p.startsWith("\u2139")?m(p):O(p));let a=On(Ln(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:si({publish:r}),display:`/catch-up${r?" --publish":""}`}}F();import{spawn as wm}from"node:child_process";var Pt="document360-writer",Ko=`npm i -g ${Pt}@latest`;async function Xo(){let e=process.platform==="win32";return new Promise(t=>{try{let n=wm(`npm i -g ${Pt}@latest`,{stdio:"ignore",shell:!0,detached:!e,windowsHide:!0});n.on("error",o=>t({ok:!1,output:String(o)})),n.on("close",o=>t({ok:o===0,output:""})),e||n.unref()}catch(n){t({ok:!1,output:String(n)})}})}async function Lc(){return console.log(m(`Updating ${Pt}\u2026`)),(await Xo()).ok?console.log(j("\u2713 Updated. Exit (/exit) and relaunch d360-writer to apply.")):console.log(C(`Update failed \u2014 run manually: ${Ko}`)),{kind:"continue"}}F();rt();import{existsSync as li,rmSync as ym}from"node:fs";import{basename as Oc,resolve as ci}from"node:path";import{execFileSync as km}from"node:child_process";import{input as bm}from"@inquirer/prompts";import{readProjectConfig as $m,devHintsGuidePath as xm}from"document360-engine";var vm=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],Cm=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),Qo=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),Mc=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function Uc(e){let t=Qo(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:Mc(t)?!0:Cm.has(t)}function di(e){let t=null;try{t=$m(e)}catch{t=null}let n=new Set(vm);for(let o of[Qo(t?.docsDir),Qo(t?.captureDir),Qo(t?.outputDir)])o&&Mc(o)&&n.add(o);return[...n].filter(o=>Uc(o)&&li(ci(e,o)))}function ui(e,t){let n=[],o=[];for(let r of t){if(!Uc(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{ym(ci(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function Wc(e,t){try{return km("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
|
|
348
|
+
`).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function Rm(e){return Wc(e,".d360-writer/hints")}function Sm(e){return Wc(e,".d360-writer/messages")}function pi(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=Rm(e),o=Sm(e),r=li(ci(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: ${Oc(e)}`]}async function Fc(e,t){let n=di(t.cwd);for(let g of pi(t.cwd,n))console.log(n.length===0?m(g):g);if(n.length===0)return{kind:"continue"};let o=Oc(t.cwd);if((await t.withPausedInput(()=>bm({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(O("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=li(xm(t.cwd)),{removed:a,failed:p}=ui(t.cwd,n);console.log(j(`\u2713 Reset complete \u2014 removed ${a.length} item${a.length===1?"":"s"}. The repo is back to its original state.`));for(let g of p)console.log(C(` \u2717 ${g.path}: ${g.error}`));if(s){for(let g of To())console.log(g);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"}}F();import{lintDocs as Pm}from"document360-engine";function Jo(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 hi(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(`
|
|
349
349
|
`)).join(`
|
|
350
350
|
`)].join(`
|
|
351
|
-
`)}async function
|
|
352
|
-
`);return{prompt:
|
|
353
|
-
`),display:`/reorder${n?` ${n}`:""}`}}async function
|
|
351
|
+
`)}async function Hc(e,t){let n=e.includes("--fix"),o=e.find(a=>!a.startsWith("--")),r=o?` ${o}`:"",s=Pm({cwd:t.cwd,scope:o});if(n)return s.length===0?(console.log(j("\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:hi(s),display:`/check${r} --fix`});console.log(m("Linting the docs (engine internals, unknown commands, stale facts, AI-tells)\u2026"));for(let a of Jo(s))console.log(s.length===0?j(a):O(a));return s.length>0&&console.log(m("Run /check --fix to have the agent correct these.")),console.log(""),{kind:"continue"}}F();import{lintDocs as Nm,loadStyleGuide as Im,buildReviewPrompt as _m,readProjectConfig as Lm,DEFAULT_DOCS_DIR as Om}from"document360-engine";F();import{readProjectConfig as Tm,loadProfileMap as Dm,resolveActiveProfile as Am,desiredCategoryOrder as jm,desiredArticleOrder as Em}from"document360-engine";function qc(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}var Bc=e=>e.replace(/\\/g,"/").split("/").pop()??e;function Mn(e,t){try{if(!Tm(e))return[];let n=Am(e,t),o=Dm(e,n.name);if(!o)return[];let r=new Map;for(let a of Em(o)){let p=r.get(a.categoryPath);p?p.push(a):r.set(a.categoryPath,[a])}let s=[];for(let a of jm(o)){s.push(qc(Bc(a.path)));for(let p of(r.get(a.path)??[]).sort((g,k)=>g.order-k.order))s.push(` ${qc(Bc(p.path))}`)}return s}catch{return[]}}async function Vc(e,t){let n=Mn(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(L("Documentation order (categories \u2192 articles):"));for(let o of n)console.log(o);return console.log(""),{kind:"continue"}}function fi(e,t){let n=Lm(e);if(!n)return null;let o=(n.docsDir??Om).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),s=t.find(y=>!y.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),a=Nm({cwd:e}),p=s?a.filter(y=>y.path===`${o}/${s}`||y.path.startsWith(`${o}/${s}/`)):a,g=s?"":Mn(e).join(`
|
|
352
|
+
`);return{prompt:_m({docsRoot:o,scope:s,styleGuide:Im(e),deterministicFindings:p,fix:r,structure:g||void 0}),display:`/review${s?` ${s}`:""}${r?" --fix":""}`}}async function Gc(e,t){if(at("review",e)){let o=on(t.cwd,"review",e,t.profileName);if(o.length>0){for(let r of o)console.log(m(r));return{kind:"continue"}}}let n=fi(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"})}F();import{readProjectConfig as Mm}from"document360-engine";function mi(e,t){if(!Mm(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(`
|
|
353
|
+
`),display:`/reorder${n?` ${n}`:""}`}}async function Yc(e,t){if(at("reorder",e)){let o=on(t.cwd,"reorder",e,t.profileName);if(o.length>0){for(let r of o)console.log(m(r));return{kind:"continue"}}}let n=mi(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"})}F();import{readProjectConfig as Um,writeProjectConfig as zc,isAppType as Wm,playbookSkillName as Fm,detectAppType as Kc}from"document360-engine";var Xc=["web","cli","service","library"],Hm=new Set(["web","cli"]);function gi(e){return Hm.has(e)?`${Fm(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function Zo(e,t){let n=t.cwd,o=Um(n);if(!o)return console.log(C("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let s=o.appType??Kc(n);if(s){let a=o.appType?"set in config":"auto-detected";console.log(`${L("Genre:")} ${s} (${a}) \u2014 ${gi(s)}`)}else console.log(O("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(m(`Set it: /genre <${Xc.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;zc(a,n);let p=Kc(n);return console.log(j(`\u2713 Genre reset to auto-detect \u2014 now: ${p?`${p} (${gi(p)})`:"unclassified (no playbook)"} (applies from your next command).`)),{kind:"continue"}}return Wm(r)?(zc({...o,appType:r},n),console.log(j(`\u2713 Genre set to ${r} \u2014 ${gi(r)} (applies from your next command).`)),{kind:"continue"}):(console.log(C(`Unknown genre "${r}". Choose one of: ${Xc.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}F();import{listRoadmap as er,roadmapProgress as Qc,stampRoadmapDone as qm}from"document360-engine";function wi(e){let t=er(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=Qc(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=er(e).filter(k=>k.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=k=>k.trim().toLowerCase(),s=n.find(k=>r(k.title)===r(o)),a=o?s?[s]:n.filter(k=>r(k.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:
|
|
354
354
|
${a.map(k=>` \u25CB ${k.title}`).join(`
|
|
355
355
|
`)}`};if(a.length===0)return{ok:!1,line:`No open step matches "${o}". Open steps:
|
|
356
356
|
${n.map(k=>` \u25CB ${k.title}`).join(`
|
|
357
|
-
`)}`};let p=a[0].title;
|
|
357
|
+
`)}`};let p=a[0].title;qm(e,p,{doneAt:new Date().toISOString()});let g=Qc(e)?.next;return{ok:!0,line:`\u2713 Marked done: ${p}${g?` \u2014 next up: ${g.title}${g.run?` (${g.run})`:""}`:" \u2014 that was the last step: campaign complete."}`}}function Jc(e,t){let n=r=>r.trim().replace(/\s+/g," ").toLowerCase(),o=n(t);return o.startsWith("/")?er(e).find(r=>r.status==="open"&&!!r.run&&n(r.run)===o)??null:null}function Zc(e,t){let n=t.trim().toLowerCase();if(!n)return null;let o=er(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:
|
|
358
358
|
${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(`
|
|
359
|
-
`):null}async function
|
|
360
|
-
\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${de(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${de(n)}.`})}if(e.localAhead>0){let n=e.localAhead;t.push({key:"publish",bullet:`${n} article${de(n)} changed locally \u2014 ready to publish`,lead:{kind:"cmd",cmd:"/publish",reason:`it pushes your ${n} local edit${de(n)} up to Document360`},picker:null,follow:`Then /publish pushes your ${n} local edit${de(n)} up.`})}if(e.conflicts>0){let n=e.conflicts;t.push({key:"resolve",bullet:`${n} article${de(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${de(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${de(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${de(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${de(n)}.`})}if(e.uncommittedDocs>0){let n=e.uncommittedDocs;t.push({key:"commit",bullet:`\u26A0 ${n} uncommitted change${de(n)} under .d360-writer/ \u2014 a commit request is standing in your builder's mailbox (the sync bookkeeping in there protects against duplicate publishes)`,lead:null,picker:null,follow:null})}return t}function
|
|
361
|
-
`)];return r.length&&s.push(r.join(" ")),s.push(
|
|
362
|
-
|
|
363
|
-
`)}function Wn(e){if(!e.ready)return{kind:"idle"};let t=
|
|
364
|
-
`).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let a=
|
|
365
|
-
`);return{lines:s.slice(0,t).map(a=>Pe(a,Ri)),hidden:Math.max(0,s.length-t)}}function
|
|
366
|
-
`))console.log(a(` ${p}`));s.rec.picker&&console.log(
|
|
367
|
-
|
|
368
|
-
`),console.log(`${
|
|
369
|
-
`);let s=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(m(` (${Tn(s)}\u2192${Tn(e.outputTokens)} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(
|
|
370
|
-
`),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){
|
|
371
|
-
`)}import{existsSync as
|
|
372
|
-
\u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close \xB7 d360-writer v${n} \xB7 engine v${o}`})]})}var
|
|
373
|
-
`)){let a=s.trim().replace(
|
|
374
|
-
`)}function
|
|
375
|
-
`)||e.length>200}function
|
|
376
|
-
`).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function
|
|
377
|
-
`)){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
|
|
359
|
+
`):null}async function ed(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?j(r.line):O(r.line)),{kind:"continue"}}let o=wi(n);console.log(L(o[0]??""));for(let r of o.slice(1))console.log(r.startsWith("(")?m(r):r);return{kind:"continue"}}var td={help:Gr,"?":Gr,clear:Ia,exit:Yr,quit:Yr,init:Jr,mcp:jo,publish:vl,audit:jn,discover:Cl,scope:Sl,pull:Ol,resolve:Il,convert:Ml,write:Bl,draft:Kl,document:Xl,resume:Zl,rename:ec,profile:nc,model:sc,doctor:In,workspace:uc,project:pc,"allow-prod":hc,login:fc,logout:mc,screenshot:Go,capture:Ec,"capture-setup":_n,devhints:Va,inbox:Ic,"catch-up":_c,update:Lc,reset:Fc,check:Hc,review:Gc,reorder:Yc,structure:Vc,genre:Zo,roadmap:ed};function nd(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}rt();var Bm="Or just tell me what to write or update.",Vm='\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 de(e){return e===1?"":"s"}function nr(e){return e.kind==="cmd"?`\u21E5 tab to run ${e.cmd} \xB7 or just ask me anything\u2026`:null}function Un(e){return e.kind==="cmd"?`I\u2019d start with ${e.cmd} \u2014 ${e.reason}.`:`Just tell me: \u201C${e.text}\u201D.`}var Gm={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 Ym(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:Gm,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${de(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${de(e.directives)} waiting`),e.pendingText&&o.push(`your builder left ${e.pendingText}`),t.push({key:"catchup",bullet:o.join(`
|
|
360
|
+
\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${de(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${de(n)}.`})}if(e.localAhead>0){let n=e.localAhead;t.push({key:"publish",bullet:`${n} article${de(n)} changed locally \u2014 ready to publish`,lead:{kind:"cmd",cmd:"/publish",reason:`it pushes your ${n} local edit${de(n)} up to Document360`},picker:null,follow:`Then /publish pushes your ${n} local edit${de(n)} up.`})}if(e.conflicts>0){let n=e.conflicts;t.push({key:"resolve",bullet:`${n} article${de(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${de(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${de(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${de(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${de(n)}.`})}if(e.uncommittedDocs>0){let n=e.uncommittedDocs;t.push({key:"commit",bullet:`\u26A0 ${n} uncommitted change${de(n)} under .d360-writer/ \u2014 a commit request is standing in your builder's mailbox (the sync bookkeeping in there protects against duplicate publishes)`,lead:null,picker:null,follow:null})}return t}function od(e){return e.find(t=>t.lead||t.picker)??null}function yi(e,t){let n=t.filter(a=>a.bullet).map(a=>` \u2022 ${a.bullet}`),o=od(t),r=[];o?.lead?r.push(Un(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(p=>p!==o).slice(0,2))a.follow&&r.push(a.follow);let s=[[e,...n].join(`
|
|
361
|
+
`)];return r.length&&s.push(r.join(" ")),s.push(Bm),s.join(`
|
|
362
|
+
|
|
363
|
+
`)}function Wn(e){if(!e.ready)return{kind:"idle"};let t=Ym(e);if(!e.hasDocs){let s=od(t);return s&&(s.lead?.kind==="cmd"||s.picker)?{kind:"recommend",rec:{note:yi("\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:Vm,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${de(e.roadmap.total)} done (/roadmap).`:"";return{kind:"recommend",rec:{note:`Welcome back. Your ${e.tracked} tracked article${de(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${de(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`}:{kind:"recommend",rec:{note:yi("Welcome back \u2014 where your docs stand:",t),tone:o.tone??"info",lead:o.lead,picker:o.picker}}:{kind:"recommend",rec:{note:yi("Welcome back \u2014 where your docs stand:",t),tone:"info",lead:null,picker:null}}}import{existsSync as ki,readdirSync as $i}from"node:fs";import{spawnSync as zm}from"node:child_process";import{join as or}from"node:path";import{readProjectConfig as sd,resolveActiveProfile as id,loadTokens as Km,isExpired as Xm,loadProfileMap as ad,localAheadPaths as Qm,loadKnownConflicts as Jm,readDocsPlan as Zm,devHintsGuidePath as eg,DEFAULT_DOCS_DIR as bi,roadmapProgress as tg,listRoadmap as ng,readProductBriefState as og,reconcileCommitRequest as rg}from"document360-engine";rt();function rd(e){try{return $i(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function xi(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>rd(or(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&rd(or(e,o)))}function vi(e,t){try{let n=sd(e);if(!n)return!1;let o=id(e,t),r=ad(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=or(e,(n.docsDir??bi).replace(/\/+$/,""));return!!(ki(s)&&$i(s).length>0||ki(eg(e)))}catch{return!1}}function Fn(e,t,n){try{let o=sd(e);if(!o)return null;let r=id(e,t),s=Km(r.name),a=!!s&&(!Xm(s)||!!s.refreshToken),p=vi(e,t)||!xi(e,o.authoritativeSourceFiles),g=ad(e,r.name),k=g?Object.keys(g.articles).length:0,y=or(e,(o.docsDir??bi).replace(/\/+$/,"")),S=!1;try{S=ki(y)&&$i(y).length>0}catch{}let v=0;if(g?.lastAnalyzedCommit)try{let xe=zm("git",["rev-list","--count",`${g.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});xe.status===0&&(v=parseInt((xe.stdout||"").trim(),10)||0)}catch{}let _=0;try{let xe=Zm(e);if(xe.length>0){let dt=(o.docsDir??bi).replace(/\/+$/,"");_=As(e,dt,xe.map(He=>He.path)).length}}catch{}let R=Ln(e),E=On({...R,directives:0}),T=Qm(e,t),U=new Set(Jm(e,r.name)),G=T.filter(xe=>U.has(xe)).length,Y=T.length-G,z=Ie(e),pe=tg(e),Xe=rg(e,new Date().toISOString()),fe=og(e),At=fe?{status:fe.status,openQuestions:fe.openQuestions}:null;return!At&&S&&ng(e).some(dt=>dt.status==="open"&&(dt.run??"").trim()==="/discover")&&(At={status:"pending",openQuestions:0}),{ready:a&&p&&!n.claudeMissing,hasDocs:S,tracked:k,pendingText:E,directives:R.directives,behind:v,pendingWrites:_,localAhead:Y,conflicts:G,autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:z.status,devhintsCompletedVersion:z.completedVersion,devhintsToVersion:ae,builderStarted:ze(e),genreUnknown:n.genreUnknown,roadmap:pe,discovery:At,uncommittedDocs:Xe.dirty.length}}catch{return null}}function ld(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 rr(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 p of ld(`${a+1}. ${s.feature}`,76))o.push(n(p));o.push(n());for(let p of ld(s.why,73))o.push(n(` ${p}`));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}F();var sg={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"},dd=160,Ri=200,ud=40;function Pe(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function cd(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}: ${Pe(typeof r=="string"?r:JSON.stringify(r),ud)}`);return t.length>4&&n.push("\u2026"),Pe(n.join(", "),dd)}var lt=e=>typeof e=="string"&&e?e:null,Ci=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function ig(e){let t=lt(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 ag(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=lt(t.title);if(!o)return null;let r=ig(t.local_path);return n("Create article",`"${Pe(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=lt(t.title),r=Ci(t.article_id);return n("Update article",o?`"${Pe(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",Ci(t.article_id)?`id ${Ci(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",lt(t.name)?`"${Pe(lt(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=lt(t.file_path);return n("Upload image",o?Pe(o.replace(/\\/g,"/").split("/").pop()??o,60):null)}case"d360_sync_status":return n("Check sync status",null);default:return null}}function sr(e,t){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,r="",...s]=e.split("__"),a=s.join("__");if(r==="document360"){let k=ag(a,t);if(k)return k}let p=a.replace(/^d360_/,"").replace(/_/g," ");return{title:`${r==="document360"?"Document360":r.charAt(0).toUpperCase()+r.slice(1)}: ${p}`,sep:" ",arg:cd(t)}}let n=sg[e],o=n?t[n]:void 0;return typeof o=="string"&&o?{title:e,sep:"",arg:Pe(o,dd)}:{title:e,sep:"",arg:cd(t)}}function lg(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 cg(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(lg).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>Pe(r,Ri))]}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}: ${Pe(String(r),ud)}`);return n.length>0?[Pe(n.join(" \xB7 "),Ri)]:null}return null}function dg(e){let t=lt(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function ug(e,t,n){switch(e){case"d360_create_article":{let o=dg(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=lt(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 ${Pe(o[0],120)}`:""}`]}default:return null}}function ir(e,t=4,n,o){let r=e.replace(/\r\n/g,`
|
|
364
|
+
`).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let a=ug(n.slice(18),o,r);if(a)return{lines:a,hidden:0}}let s=cg(r)??r.split(`
|
|
365
|
+
`);return{lines:s.slice(0,t).map(a=>Pe(a,Ri)),hidden:Math.max(0,s.length-t)}}function ar(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function lr(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 pd(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 cr(e){return pd(e,"url")}function dr(e){return pd(e,"preview_url")}var jg=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Eg(e,t,n,o){if(jg.test(e))try{let r=md(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,a=lr(t,n),p=cr(n);e.endsWith("publish_article")&&p&&console.log(L(` \u2B95 Live: ${p}`));let g=dr(n);g?console.log(L(` \u2B95 Preview: ${g}`)):a&&s&&console.log(L(` \u2B95 Preview: ${ar(r.connection.portalUrl,s,a,r.project.languageCode??"en")}`))}catch{}}async function gd(e=process.cwd(),t="auto",n,o){let r=hg(t);r.kind==="none"&&(console.error(""),console.error(C("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${L("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${L('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${L("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${L("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),Ng(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=Si({cwd:e,profileName:n,allowProdWrites:s}),p={uuid:null,firstPrompt:null,titleFired:!1},g=pg({input:process.stdin,output:process.stdout}),k=[],y=null,S=!1;g.on("line",R=>{if(y){let E=y;y=null,E(R)}else k.push(R)}),g.on("close",()=>{if(S=!0,y){let R=y;y=null,R(null)}});function v(){return k.length>0?Promise.resolve(k.shift()):S?Promise.resolve(null):(process.stdout.write(L("> ")),new Promise(R=>{y=R}))}let _={cwd:e,version:o,profileName:n,allowProdWrites:()=>s,restartAgent:()=>{a.close(),a=Si({cwd:e,profileName:n,allowProdWrites:s}),p={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>p.uuid,setPendingName:R=>{p.pendingName=R},setModel:async R=>a.setModel(R),withPausedInput:async R=>{g.pause();try{return await R()}finally{g.resume()}}};try{for(;;){let R=await v();if(R===null)break;let E=R.trim();if(E){if(E.startsWith("/")){let T=nd(E);if(!T)continue;let U=td[T.name];if(!U){console.log(C(`Unknown command: /${T.name}`)),console.log(m("Type /help for the list."));continue}let G=await U(T.args,_);if(G.kind==="exit")break;if(G.kind==="clear"){_.restartAgent();continue}if(G.kind==="allow-prod"){s=!0,_.restartAgent(),console.log(j("\u2713 Production writes authorized for this session.")),console.log("");continue}if(G.kind==="resume"){a.close(),a=Si({cwd:e,resume:G.uuid,profileName:n,allowProdWrites:s});let Y=fg(G.uuid);p={uuid:G.uuid,firstPrompt:Y?.firstPrompt??null,titleFired:!0},fd(G.uuid),console.log(j(`\u2713 Resumed "${G.name}"`)),console.log("");continue}if(G.kind==="forward-to-agent"){p.firstPrompt||(p.firstPrompt=G.display??G.prompt);let Y=(G.display??"").trim().split(/\s+/),z=(Y[0]==="/check"||Y[0]==="/review")&&Y.includes("--fix"),pe=Y.slice(1).find(fe=>!fe.startsWith("--")),Xe=z?Dg(e,pe):[];if(await Pi(a,G.prompt,r,p,e),z)try{Tg(e,Xe,{reviewedCap:Ag})}catch{}}else Ig(e,n);continue}if(Cg(E)){let T=Rg(E);if(T){try{Sg(e,{title:T,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}p.firstPrompt||(p.firstPrompt=E),await Pi(a,`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${T}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${T}" and the article path(s) you wrote.`,r,p,e);continue}}p.firstPrompt||(p.firstPrompt=E),await Pi(a,E,r,p,e)}}}finally{a.close(),g.close()}}function Ng(e,t){console.log(""),console.log(xn("document360-writer")),console.log(m(` cwd: ${e}`));let n=kg(e);if(console.log(m(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(_g(e,t)),!bg(e))console.log(O(" 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(So(e),!ze(e))for(let r of Po(e))console.log(O(` ${r}`))}catch{}try{let r=$g(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=Pg(e);for(let s of rr(r.applied))console.log(O(` ${s}`))}catch{}try{let r=Fn(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:o}),s=r?Wn(r):null;if(s?.kind==="recommend"&&s.rec.note){let a=s.rec.tone==="warn"?O:m;for(let p of is(s.rec.note).split(`
|
|
366
|
+
`))console.log(a(` ${p}`));s.rec.picker&&console.log(L(` Pick one: ${s.rec.picker.options.map(p=>p.cmd).join(" \xB7 ")}`))}}catch{}}console.log(m(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function Ig(e,t){try{let n=Fn(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:!1}),o=n?Wn(n):null;o?.kind==="recommend"&&o.rec.lead&&console.log(m(` Next: ${Un(o.rec.lead)}`))}catch{}}function _g(e,t){try{let n=md(e,t),o=n.production?O(" \u26A0 PRODUCTION"):"",r=vg(n.name);if(!r)return m(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...hd(r.idToken)??{},...hd(r.accessToken)??{}},a=s.email??s.preferred_username??"signed in";return xg(r)&&!r.refreshToken?O(` 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 Lg(){console.error(""),console.error(`Sign in with your Claude subscription: run ${L("claude")} once, then retry.`),console.error(` (No Claude Code? ${L("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${L("https://console.anthropic.com/settings/keys")}`)}function Og(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;wg({uuid:t,name:r??gg(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function Mg(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||yg(o,t).then(r=>{r&&mg(n,r)}).catch(()=>{})}async function Pi(e,t,n,o,r){let s=new Map;for await(let a of e.send(t))Ug(a,o,r,n,s)}function Ug(e,t,n,o,r){switch(e.type){case"session":t.uuid||Og(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let s=sr(e.name,e.input);s&&(process.stdout.write(`
|
|
367
|
+
|
|
368
|
+
`),console.log(`${j("\u25CF")} ${be(s.title)}${s.arg!==null?ie(`${s.sep}(${s.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let s=Ke(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!s)break;let a=p=>p===1?"":"s";console.log(ie(` \u23BF Added ${s.added} line${a(s.added)}, removed ${s.removed} line${a(s.removed)}`));for(let p of s.lines)console.log(p);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=ir(e.output,4,e.isError?void 0:s.name,s.input),p=e.isError?C:ie;a.lines.forEach((g,k)=>console.log(p((k===0?" \u23BF ":" ")+g))),a.hidden>0&&console.log(m(` \u2026 +${a.hidden} lines`)),e.isError||Eg(s.name,s.input,e.output,n);break}case"result":{process.stdout.write(`
|
|
369
|
+
`);let s=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(m(` (${Tn(s)}\u2192${Tn(e.outputTokens)} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(fd(t.uuid),t.titleFired||Mg(t,n));break}case"error":console.error(""),console.error(C(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&Lg();break}}import{render as ey}from"ink";import{resolveAuth as ty}from"document360-engine";import{useCallback as B,useEffect as De,useMemo as Ni,useRef as Z,useState as H}from"react";import{Box as re,Text as D,useApp as ew,useInput as tw,useStdout as nw}from"ink";import{existsSync as sn,readFileSync as yr,readdirSync as ow}from"node:fs";import{basename as qn,isAbsolute as rw,join as Ii}from"node:path";import{createSession as Fd,classifyClaudeAuth as Wi,CLAUDE_CODE_SETUP_HINT as sw,loginPkce as iw,toStoredTokens as aw,saveTokens as lw,getAccessToken as cw,resolveActiveProfile as Te,resolveProjectId as dw,getArticle as uw,decodeJwtClaims as ln,isExpired as ct,loadTokens as Dt,clearTokens as pw,clearProfileProject as hw,setTitle as fw,slugify as mw,touchSession as _i,upsertSession as gw,generateTitle as Hd,findByName as ww,listSessions as yw,renameSession as kw,suggestNextAction as bw,readProjectConfig as oe,writeProjectConfig as qd,resolveAndPersistAppType as $w,detectAppType as xw,resolveModelSetting as Fi,loadProfileMap as Bd,applyPull as Vd,computeSyncStatus as Li,lintDocs as Gd,compareRemoteSources as vw,planPull as Yd,establishBaselines as Cw,rebaselineServerMeta as Rw,inventoryRepo as Sw,knownEnvironments as Pw,resolveEnvironment as Tw,planPartitions as Oi,partitionEvenly as Dw,screenshotPlaceholderIds as Aw,trackedArticlePaths as jw,runPartitioned as kr,estimateBulkCost as zd,resolveModelForOperation as br,readDocsPlan as Ew,checkForUpdate as Nw,detectInstallKind as Iw,isSelfUpdatable as _w,devHintsGuidePath as Kd,toolFeedbackPath as Xd,reconcileToolFeedback as Lw,reconcileUpgradeActions as Ow,stampArticles as Mi,listArticleFiles as Qd,CONTENT_CAP_VERSION as Ui,ENGINE_VERSION as su,DEFAULT_DOCS_DIR as iu,setProfileProject as Mw,writeCrashLog as Uw,applyStructureOrder as Jd,orderSyncLine as Zd,applyRelatedArticles as eu,relatedSyncLine as tu}from"document360-engine";rt();import{spawn as wd}from"node:child_process";function Wg(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function Fg(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?wd([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):wd(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 Ti(e){for(let[t,n]of Wg())if(await Fg(t,n,e))return!0;return!1}var Hg=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function Di(e,t){if(t.closed)return e;let n=e.split(`
|
|
370
|
+
`),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){Hg.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(`
|
|
371
|
+
`)}import{existsSync as qg,mkdirSync as Bg,readFileSync as Vg,writeFileSync as Gg}from"node:fs";import{join as yd}from"node:path";import{writerDir as Yg}from"document360-engine";function kd(e){return yd(Yg(e),".sessions")}function bd(e,t){return yd(kd(e),`${t}.json`)}function $d(e,t,n){try{Bg(kd(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");Gg(bd(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function Ai(e,t){try{let n=bd(e,t);if(!qg(n))return[];let o=JSON.parse(Vg(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var zg=e=>`\x1B]0;${e}\x07`,Kg=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function xd(e){process.stdout.isTTY&&process.stdout.write(e)}function rn(e){xd(zg(e))}function ur(e){xd(Kg(e))}var pr=["\xB7 "," \xB7"],hr="\u{1F7E3}";Bo();Ao();F();import{Box as vd,Text as ce}from"ink";import{jsx as ue,jsxs as fr}from"react/jsx-runtime";function Xg({row:e}){switch(e.t){case"head":return ue(ce,{color:q,bold:!0,children:e.s});case"text":return ue(ce,{children:e.s});case"dim":return ue(ce,{dimColor:!0,children:e.s});case"sub":return ue(ce,{bold:!0,dimColor:!0,children:e.s});case"good":return ue(ce,{color:"green",children:e.s});case"step":return fr(ce,{children:[ue(ce,{color:q,children:`${e.n}. `}),e.s]});case"cmd":return fr(ce,{children:[" ",ue(ce,{color:q,children:e.name.padEnd(20)}),ue(ce,{dimColor:!0,children:e.s})]});case"gap":return ue(ce,{children:" "})}}function Cd({tab:e,width:t,version:n,engineVersion:o}){let r=Ne[e]??Ne[0],s=6+Ne.reduce((p,g)=>p+g.label.length+4,0),a="\u2500".repeat(Math.min(s,Math.max(t-1,20)));return fr(vd,{flexDirection:"column",paddingX:1,children:[fr(ce,{children:[ue(ce,{color:q,bold:!0,children:"Help "}),Ne.map((p,g)=>g===e?ue(ce,{color:"white",backgroundColor:q,bold:!0,children:` ${p.label} `},p.key):ue(ce,{dimColor:!0,children:` ${p.label} `},p.key))]}),ue(ce,{color:q,children:a}),ue(vd,{flexDirection:"column",marginTop:1,children:r.rows.map((p,g)=>ue(Xg,{row:p},g))}),ue(ce,{dimColor:!0,children:`
|
|
372
|
+
\u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close \xB7 d360-writer v${n} \xB7 engine v${o}`})]})}var Qg=/^(?:\d+[.)]|[-*•])\s+/;function Rd(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
|
|
373
|
+
`)){let a=s.trim().replace(Qg,""),p=a.match(/^`([^`]+)`$/);p&&(a=p[1].trim());let g=a.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!g||!o.has(g[1].toLowerCase()))continue;let k=`/${g[1].toLowerCase()}${g[2]?` ${g[2]}`:""}`;if(r.includes(k)||r.push(k),r.length>=n)break}return r}F();function Hn(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function Le(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function Sd(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var Jg=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function Pd(e,t,n){if(!Jg.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 ji(e){return e.replace(/^[\w.-]+\//,"")}var mr=16,Td={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function Tt(e){return typeof e=="string"?e:e.cmd}function Dd(e){return typeof e=="string"?void 0:e.desc}function Ei(e){return e.trim().split(/\s+/).slice(1).join(" ")}function Ad(e,t){let n=Ei(t);return e.some(r=>Tt(r).trim()===t.trim()||!!n&&Ei(Tt(r))===n)?e.filter(r=>Tt(r).trim()!==t.trim()&&!(n&&Ei(Tt(r))===n)):[]}import{isDirectiveMention as Ww,stripDirectiveMention as Fw,appendDirective as Hw}from"document360-engine";var Zg=/\[Pasted text #\d+ \+\d+ lines?\]/g;function jd(e){return e.replace(/\r\n?/g,`
|
|
374
|
+
`)}function Ed(e){return e.includes(`
|
|
375
|
+
`)||e.length>200}function Nd(e,t){let n=t.split(`
|
|
376
|
+
`).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function Id(e,t){return e.replace(Zg,n=>t.get(n)??n)}function _d(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function gr(e,t){let n=Math.max(1,t),o=[],r=0;for(let s of e.split(`
|
|
377
|
+
`)){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 wr(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function Ld(e,t,n){let o=wr(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 Od(e,t,n){let o=e[wr(e,t)];return n==="start"?o.start:o.end}function Md(e,t,n){let o=Math.max(1,n),r=e.split(`
|
|
378
378
|
`),s=0;for(let a=r.length-1;a>=0;a--){let p=r[a];if(s+=Math.max(1,Math.ceil(p.length/o)),s>=t){let g=s-t;return{text:[g>0?p.slice(g*o):p,...r.slice(a+1)].join(`
|
|
379
|
-
`),truncated:a>0||g>0}}}return{text:e,truncated:!1}}function
|
|
380
|
-
`)){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 Bn,jsx as A,jsxs as V}from"react/jsx-runtime";var
|
|
379
|
+
`),truncated:a>0||g>0}}}return{text:e,truncated:!1}}function Ud(e,t){if(t||e.length===0||/\s$/.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 Wd(e){let t=!1,n=0,o=0;for(let r of e.split(`
|
|
380
|
+
`)){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 Bn,jsx as A,jsxs as V}from"react/jsx-runtime";var qw={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL",auto:"auto \u2014 right-sized for docs \xB7 /model to change"},nu=` 1. /init \u2014 pick your Document360 environment & scaffold config
|
|
381
381
|
2. /login \u2014 sign in & pick your Document360 project (workspace auto-selected)
|
|
382
|
-
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function
|
|
383
|
-
${
|
|
382
|
+
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function Bw(e,t,n,o){let r=Wi(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=Fi(e),p=oe(e),g=(p?.docsDir??iu).replace(/\/+$/,""),k=p?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${g}/ + config`,y={version:t,engineVersion:su,claude:s,model:a.model,modelSource:qw[a.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:p!==null,mode:k};if(p===null)return y;try{let S=Te(e,o);y.profile=S.name,y.apiUrl=S.connection.apiUrl,y.prod=S.production,y.project=S.project.projectName??S.project.projectId??"(chosen at login)";let v=Dt(S.name);if(v){let _={...ln(v.idToken)??{},...ln(v.accessToken)??{}},R=_.email??_.preferred_username??"signed in";ct(v)?v.refreshToken&&(y.who=R,y.loggedOut=!1,y.sessionHint="session expired \u2014 refreshing\u2026"):(y.who=R,y.loggedOut=!1,y.sessionHint=`session valid until ${new Date(v.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return y}function Vw(e,t){try{let n=Te(e,t),o=Dt(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...ln(o.idToken)??{},...ln(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return ct(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 ou=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],cn=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Gw="Ask me to write or update an article\u2026";function an({ch:e,dim:t}){let[n,o]=H(!0);return De(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),A(D,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var Yw=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function ru(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var zw=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Kw({startTime:e,chars:t}){let[n,o]=H(0);De(()=>{let g=setInterval(()=>o(k=>k+1),120);return()=>clearInterval(g)},[]);let r=cn[n%cn.length],s=ou[Math.floor(n/16)%ou.length],a=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return V(re,{children:[A(D,{color:q,children:` ${r} ${s}\u2026 `}),A(D,{color:"gray",children:`(${Dn(a)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}function Xw({text:e}){let[t,n]=H(0);return De(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),A(re,{paddingX:1,children:A(D,{color:q,children:`${cn[t%cn.length]} ${e}`})})}var Qw=12e4;function Jw({p:e}){let[t,n]=H(0);De(()=>{let T=setInterval(()=>n(U=>U+1),150);return()=>clearInterval(T)},[]);let o=cn[t%cn.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),a=Math.round(e.chars/4),p=Date.now()-e.lastAt>=Qw,g=e.verb??"Converting",k=e.unit??"article",y=e.rows.reduce((T,U)=>T+U.items,0),S=g.toLowerCase(),v=e.rows,_=0;if(v.length>mr){let T=v.findIndex(G=>G.status==="active"||G.status==="pending"),U=Math.max(0,Math.min(T-2,v.length-mr));_=v.slice(0,U).filter(G=>G.status==="done").length,v=v.slice(U,U+mr)}let R=Math.min(40,Math.max(...v.map(T=>ji(T.label).length),0)),E=T=>T==="failed"?"red":T==="active"?q:void 0;return V(re,{flexDirection:"column",children:[V(re,{children:[A(D,{color:q,children:` ${o} ${g} ${y} ${k}${y===1?"":"s"} `}),A(D,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${a} tokens \xB7 ${Dn(r)} \xB7 esc to stop`})]}),_>0&&A(D,{dimColor:!0,children:` \u2714 +${_} done`}),v.map(T=>V(D,{color:E(T.status),dimColor:T.status==="done"||T.status==="pending",children:[` ${Td[T.status]} ${ji(T.label).padEnd(R)}`,T.status==="active"&&T.itemsDone!==void 0?` (${T.itemsDone}/${T.items} ${k}${T.items===1?"":"s"})`:T.status!=="pending"?` (${T.items} ${k}${T.items===1?"":"s"})`:"",T.status==="active"?` \u2190 ${S}\u2026`:""]},T.label)),p&&A(D,{color:"yellow",children:` \u26A0 no activity for ${Dn(s)} \u2014 press esc to stop if it's wedged`})]})}var Zw=10800*1e3;function au({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=ew(),[s,a]=H(n),[p,g]=H(null),[k,y]=H({text:"",pos:0}),S=k.text,v=B(c=>{y(l=>{let i=typeof c=="function"?c(l.text):c;return{text:i,pos:i.length}})},[]),_=B(c=>{y(l=>({text:l.text.slice(0,l.pos)+c+l.text.slice(l.pos),pos:l.pos+c.length}))},[]),R=B(()=>{y(c=>{if(c.pos===0)return c;let l=c.text.slice(0,c.pos),i=_d(l)??l.slice(0,-1);return{text:i+c.text.slice(c.pos),pos:i.length}})},[]),[E,T]=H(!1),[U,G]=H(!1),[Y,z]=H(0),[pe,Xe]=H(!1),[fe,At]=H(null),[xe,dt]=H(null),[He,ut]=H([]),Vn=Z(!1),xr=Z(!1),[vr,Vi]=H(!1),Gn=Z(0),[fu,Yn]=H(!1),[mu,zn]=H(!1),[Cr,Gi]=H(null),[gu,jt]=H(0),pt=Z(0),[dn,Et]=H(0),[Nt,Kn]=H(null),Yi=Z(new Map),wu=Z(0),It=Z([]),Ae=Z(null);Ae.current===null&&(Ae.current=Fd({cwd:e,profileName:s,allowProdWrites:!1}));let qe=Z({uuid:null,firstPrompt:null,titleFired:!1}),Xn=Z(new Map),_t=Z(!1),Rr=Z([]),le=Z([]),Lt=Z([]),Qn=Z(null),[zi,ht]=H(null),Sr=Z(null),[ft,mt]=H(null),[Be,Ot]=H(null),[Ve,Mt]=H(null),[me,Ut]=H(null),[ve,gt]=H(null),[Qe,Wt]=H(null),[Je,wt]=H(null),[Ge,yt]=H(null),[Ki,un]=H(null),[Ce,kt]=H(null),[we,Ft]=H(null),[Xi,Pr]=H([]),bt=Z([]),pn=Z(!1),ye=Z(null),[Jn,te]=H(null),[Qi,Ji]=H(null),Zn=Z(!1),hn=Z(null),fn=Z(null),[Re,$t]=H(null),[eo,mn]=H(null),Tr=!!(Ve||me||ve||Qe||Je||Ge||Ce||we||Re||eo),[Zi,Ht]=H(0),[ea,qt]=H(0),[yu,ta]=H(0),Dr=Ni(()=>{try{let c=Fi(e);return c.source==="auto"?`${c.model} (auto)`:c.model}catch{return null}},[e,yu]),{stdout:Me}=nw(),[,ku]=H(0),na=Z(`${Me.columns??80}x${Me.rows??24}`),Ze=B(()=>Math.max(20,(Me.columns??80)-1),[Me]),u=B(c=>{It.current.push(c),console.log(as(c,Ze()))},[Ze]),ge=B((c,l)=>{Gn.current++,At(c),dt(l??null)},[]),Ue=B(()=>{Gn.current++,At(null),dt(null)},[]),X=B(c=>ge(c,nr({kind:"cmd",cmd:c,reason:""})),[ge]),to=B((c,l)=>{!l?.silent&&c.note&&u({kind:"note",tone:c.tone,text:c.note}),c.picker&&(ut(c.picker.options.map(i=>({cmd:i.cmd,desc:i.desc}))),un(c.picker.title)),c.lead&&ge(c.lead.kind==="cmd"?c.lead.cmd:c.lead.text,nr(c.lead))},[u,ge]),ke=B((c,l,i="info")=>{c&&u({kind:"note",tone:i,text:c}),l&&ge(l.kind==="cmd"?l.cmd:l.text,nr(l))},[u,ge]),[gn,Ar]=H(null),[bu,oa]=H(!1),Bt=B(c=>{Ar(c),oa(!1),u({kind:"note",tone:"info",text:"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[u]),jr=Z(!1),Er=B(async()=>{try{if(jr.current||!_w(Iw())||oe(e)?.mode==="engineer")return;let c=await Nw({pkg:Pt,currentVersion:o,force:!0});if(!c.updateAvailable||!c.latest)return;jr.current=!0,u({kind:"note",tone:"info",text:`\u2B06 Updating ${Pt} ${c.current} \u2192 ${c.latest}\u2026 (wait for the \u2713 before you /exit)`}),zn(!0),(await Xo().finally(()=>zn(!1))).ok?(u({kind:"note",tone:"ok",text:`\u2713 Updated to v${c.latest} \u2014 run /exit, then relaunch to apply.`}),X("/exit"),Gi(c.latest)):u({kind:"note",tone:"warn",text:`Update available (v${c.latest}) but auto-update failed \u2014 run: ${Ko}`})}catch{}},[e,o,u,X]),no=B(c=>{let l=_e(e,s);return l.ok?!0:(u({kind:"note",tone:"warn",text:l.reason}),fn.current=c,X("/login"),!1)},[e,s,u,X]),[oo,Nr]=H(null),xt=B(c=>{let l=Fn(e,s,{claudeMissing:Wi(t).state==="missing",allowAutoAudit:c,genreUnknown:xr.current});return l?Wn(l):{kind:"idle"}},[e,s,t]),wn=Z(!0),Vt=Z(!1),ro=Z(0),yn=Z(0);De(()=>{let c=setInterval(()=>{if(wn.current){ro.current=0,yn.current=0;return}if(!E)try{if(!sn(Kd(e)))return;if(Ie(e).status==="current"){wn.current=!0,ro.current=0,yn.current=0;let i=xt(!1),f=i.kind==="recommend"?i.rec:null,d=Vt.current?`\u2713 Your builder finished the protocol update (v${ae}) \u2014 the dev\u2194docs hand-off is current again.`:"\u2713 Your builder finished the hand-off \u2014 the architecture brief is in. I can read this repo now and write accurate docs.";u({kind:"note",tone:"ok",text:`${d}${f?.lead?` ${Un(f.lead)}`:""}`}),Ar(null),f&&(f.lead||f.picker)?to(f,{silent:!0}):Vt.current||ge("write the docs for this repo"),z(w=>w+1);return}if(Vt.current)return;ro.current+=1;let l=ro.current;if((l===4||l%15===0)&&yn.current<3){yn.current+=1;let i=yn.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";u({kind:"note",tone:"info",text:ze(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,E,u,xt,to,ge]),De(()=>{let c=zi??qn(e);if(!E){ur(0),rn(`${hr} ${c}`);return}ur(3);let l=0;rn(`${pr[0]} ${c}`);let i=setInterval(()=>{l=(l+1)%pr.length,rn(`${pr[l]} ${c}`)},400);return()=>clearInterval(i)},[E,e,zi]),De(()=>()=>ur(0),[]),De(()=>{let c=performance.now(),l=[],i=(h,$)=>{let x=performance.now();try{return $()}finally{let N=Math.round(performance.now()-x);N>=80&&l.push(`${h}: ${N}ms`)}};u({kind:"banner",info:i("banner",()=>Bw(e,o,t,s))});let f=Wi(t).state==="missing";if(f&&u({kind:"note",tone:"warn",text:`\u26A0 Set up Claude first \u2014 d360-writer's agent runs on Claude Code, and it's not signed in on this machine yet.
|
|
383
|
+
${sw}
|
|
384
384
|
Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!oe(e)){u({kind:"note",tone:"info",text:`Welcome! This repo isn't set up for d360-writer yet \u2014 three steps and you're writing docs:
|
|
385
|
-
${
|
|
386
|
-
`)}),Bt(vt()),wn.current=!1,Vt.current=!1)}}catch{}try{let h=i("reconcile-feedback",()=>
|
|
387
|
-
`)})}catch{}let w=i("ready-decision",()=>xt(!0));w.kind==="autoAudit"?(u({kind:"note",tone:"info",text:w.note}),jn().then(h=>{h.kind==="forward-to-agent"&&h.prompt&&ne(h.prompt,{display:h.display,quietUser:!0})})):w.kind==="recommend"&&to(w.rec);let
|
|
385
|
+
${nu}`}),X(f?"/doctor":"/init");return}f&&X("/doctor");try{let h=Te(e,s),$=Dt(h.name);$&&ct($)&&$.refreshToken?cw({profile:h.name,connection:h.connection}).then(()=>{u({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),z(x=>x+1)}).catch(()=>{u({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 sign in again with /login."}),X("/login")}):(!$||ct($))&&(u({kind:"note",tone:"warn",text:`Profile "${h.name}" is not signed in \u2014 sign in with /login.`}),X("/login"))}catch{}try{let h=oe(e),$=Te(e,s),x=Dt($.name);h&&x&&!ct(x)&&xi(e,h.authoritativeSourceFiles)&&!vi(e,s)&&(u({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),X("/scope"))}catch{}try{let h=i("resolve-genre",()=>$w(e));h.persisted&&h.appType?u({kind:"note",tone:"ok",text:`\u2713 Detected a ${h.appType} app \u2014 enabled the ${h.appType}-doc-playbook (change with /genre, or edit .d360-writer/config.json).`}):h.source==="unknown"&&oe(e)&&(xr.current=!0)}catch{}let d=Ie(e);try{if(i("reconcile-devhints",()=>So(e)),d.status!=="current"&&!ze(e)){let h=Po(e);h.length&&(u({kind:"note",tone:"warn",text:h.join(`
|
|
386
|
+
`)}),Bt(vt()),wn.current=!1,Vt.current=!1)}}catch{}try{let h=i("reconcile-feedback",()=>Lw(e));h.archived>0&&u({kind:"note",tone:"ok",text:`\u2713 Tidied ${h.archived} resolved item${h.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${h.open>0?`; ${h.open} still open`:""}.`})}catch{}try{let h=i("upgrade-actions",()=>Ow(e));h.applied.length>0&&u({kind:"note",tone:"warn",text:rr(h.applied).join(`
|
|
387
|
+
`)})}catch{}let w=i("ready-decision",()=>xt(!0));w.kind==="autoAudit"?(u({kind:"note",tone:"info",text:w.note}),jn().then(h=>{h.kind==="forward-to-agent"&&h.prompt&&ne(h.prompt,{display:h.display,quietUser:!0})})):w.kind==="recommend"&&to(w.rec);let b=Math.round(performance.now()-c);b>=800&&Uw({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${b}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${l.length?l.join(`
|
|
388
388
|
`):"no single phase \u226580ms"}
|
|
389
|
-
cwd: ${e}`}),
|
|
390
|
-
`)});let
|
|
391
|
-
`)})}},[e,s,u,ne]),
|
|
392
|
-
${
|
|
393
|
-
`)}),Bt(vt()),wn.current=Ie(e).status==="current",Vt.current=ze(e),u({kind:"note",tone:"info",text:`No separate builder agent? Then just ask me now: "write the docs for this repo" \u2014 I'll read the code directly.`}))},[e,u,Se,Bt]),lo=B(async c=>{let l;try{l=await vn(e,c)}catch{u({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),X("/workspace");return}if(l.workspaces.length===0){u({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let i=l.workspaces.filter(d=>(d.workspace_type??"").toLowerCase()!=="apidocumentation"),f=i.length>0?i:l.workspaces;if(f.length===1){let d=f[0],w=l.workspaces.length-f.length;u({kind:"note",tone:"ok",text:`Selected the "${d.name??d.id}" workspace${w>0?" (skipped the API-documentation workspace)":""}.`}),ao(l.profile,l.projectId,d);return}u({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${f.length} available).`}),X("/workspace")},[e,u,ao,X]),co=B((c,l)=>{wo(e,c,l.id,l.name),u({kind:"note",tone:"ok",text:`Project set to "${l.name??l.id}" (agent restarted).`}),Se(),lo(c)},[e,u,Se,lo]),
|
|
394
|
-
`)}),Bt(
|
|
395
|
-
${
|
|
396
|
-
`)});return}case"mcp":await jo(f);return;case"init":{if(oe(e)){u({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer/config.json directly (or d360-writer init for the CLI wizard)."});return}let d=
|
|
397
|
-
`:"",
|
|
398
|
-
Model: ${
|
|
399
|
-
`)+
|
|
400
|
-
`)})}}catch(P){u({kind:"note",tone:"error",text:`Convert run failed: ${P.message}`})}finally{ye.current=null,te(null),T(!1),z(P=>P+1)}return}case"write":{if(!oe(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let d=
|
|
389
|
+
cwd: ${e}`}),Er()},[]),De(()=>{let c=setInterval(()=>{Er()},Zw);return()=>clearInterval(c)},[Er]),De(()=>{if(E||pe||vr||Vn.current||fe!==null||He.length>0||S!==""||gn!==null||le.current.length>0||Qn.current||Tr)return;let c=xt(!1);c.kind==="recommend"&&(c.rec.lead||c.rec.picker)&&to(c.rec,{silent:!0})},[E,pe,fe,He,S,gn,Tr,Y,xt,vr]),De(()=>{let c=null,l=null,i=()=>{c&&clearTimeout(c),c=setTimeout(()=>{c=null;let f=`${Me.columns??80}x${Me.rows??24}`;f!==na.current&&(na.current=f,ku(d=>d+1),l&&clearTimeout(l),l=setTimeout(()=>{l=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+ml(It.current,Ze())+"\x1B[?2026l")},80))},400)};return Me.on("resize",i),()=>{c&&clearTimeout(c),l&&clearTimeout(l),Me.off("resize",i)}},[Me,Ze]);let je=Math.max(20,(Me.columns??80)-1),ra=Ni(()=>Vw(e,s),[e,s,Y]),Ir=(()=>{if(mu)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(Cr!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${Cr?` v${Cr}`:""}\u2026`,isSetup:!0};if(oo)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(gn)return bu?{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(le.current.length>0)return le.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=oe(e);if(!c)return{text:"Run /init to set up this repo (or /help)\u2026",isSetup:!0};let l=Ii(e,(c.docsDir??iu).replace(/\/+$/,"")),i=(()=>{try{return sn(l)&&ow(l).length>0}catch{return!1}})();try{let f=Te(e,s),d=Dt(f.name);if(!(!!d&&!(ct(d)&&!d.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:Gw,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),kn=il(S),sa=kn.length>0&&!E,_r=p!==null?Md(p,8,je):null,so=Ce?Ce.paths.filter(c=>!Ce.query||c.toLowerCase().includes(Ce.query.toLowerCase())).slice(0,8):[],io=Re?Re.sessions.filter(c=>{let l=Re.query.toLowerCase();return!l||c.name.toLowerCase().includes(l)||c.firstPrompt.toLowerCase().includes(l)}).slice(0,8):[],Se=B((c,l)=>{Ae.current?.close(),Ae.current=Fd({cwd:e,resume:c,profileName:l??s,allowProdWrites:_t.current}),c||(qe.current={uuid:null,firstPrompt:null,titleFired:!1},ht(null)),Ht(0),qt(0)},[e,s]),ia=B((c,l,i)=>{if(Yw.test(c))try{let f=Te(e,s),d=typeof l.project_id=="string"&&l.project_id||f.project.projectId,w=lr(l,i),b=[],h=cr(i);c.endsWith("publish_article")&&h&&b.push(`Live: ${h}`);let $=dr(i);$?b.push(`Preview: ${$}`):w&&d&&b.push(`Preview: ${ar(f.connection.portalUrl,d,w,f.project.languageCode??"en")}`),b.length>0&&u({kind:"link",lines:b})}catch{}},[e,s,u]),ne=B(async(c,l)=>{Yn(!0),Vn.current=!1,Ue(),ut([]),un(null),Ar(null);let i=Gn.current;l?.quietUser||u({kind:"user",text:l?.echoDisplay&&l.display?l.display:c});let f=qe.current;f.firstPrompt||(f.firstPrompt=l?.display??c),pt.current=Date.now(),jt(0),T(!0),Xn.current.clear();let d="",w=!1,b=!1,h="",$={num:0,closed:!1,cueSeen:!1},x=null,N=()=>{x||(x=setTimeout(()=>{x=null,g(h.length>0?h:null)},60))},W=()=>{x&&clearTimeout(x),x=null,g(null)},K=(P=!1)=>{let{head:I,keep:M}=Ud(h,P);I.trim()&&u({kind:"assistant",text:Di(I.trimEnd(),$)}),h=M,W()};try{for await(let P of Ae.current.send(c))if(P.type==="session"){if(!f.uuid){f.uuid=P.sessionId;let I=new Date().toISOString(),M=Sr.current,ee=M??mw(f.firstPrompt??"session");gw({uuid:P.sessionId,name:ee,renamed:!!M,titled:!1,cwd:e,firstPrompt:f.firstPrompt??"",createdAt:I,updatedAt:I}),ht(ee),Sr.current=null}}else if(P.type==="text"){h+=P.delta,d+=P.delta;let I=Wd(h);if(I>0){let M=h.slice(0,I).trimEnd();M&&u({kind:"assistant",text:Di(M,$)}),h=h.slice(I)}N(),jt(M=>M+P.delta.length)}else if(P.type==="tool"){w=!0;let I=sr(P.name,P.input);I&&(K(),u({kind:"tool",title:I.title,sep:I.sep,arg:I.arg}),Xn.current.set(P.id,{name:P.name,input:P.input}))}else if(P.type==="article_diff"){let I=Ke(P.oldContent,P.newContent,Ze());I&&(K(),u({kind:"diff",added:I.added,removed:I.removed,lines:I.lines,hidden:I.hidden}))}else if(P.type==="tool_result"){P.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(P.output)&&(Zn.current=!0);let I=Xn.current.get(P.id);if(I){Xn.current.delete(P.id),K();let M=ir(P.output,4,P.isError?void 0:I.name,I.input);u({kind:"tool-result",lines:M.lines,hidden:M.hidden,isError:P.isError}),P.isError||ia(I.name,I.input,P.output)}}else if(P.type==="result"){K(!0),Ht(M=>M+P.outputTokens),qt(M=>M+P.costUsd);let I=P.inputTokens+P.cacheReadTokens+P.cacheCreationTokens;if(u({kind:"done",seconds:Math.round((Date.now()-pt.current)/1e3),tokens:P.outputTokens,costUsd:P.costUsd,ok:P.ok,...I>0?{inTokens:I,cachedPct:Math.round(P.cacheReadTokens/I*100)}:{}}),!b&&!w&&!d.trim()&&!pn.current&&u({kind:"note",tone:"warn",text:"The agent produced no output. This usually means the Claude model/runtime did not start \u2014 check sign-in and model with /doctor (on a subscription, make sure Claude Code is logged in on this machine)."}),P.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(d))try{let M=Xd(e);if(sn(M)){let ee=yr(M,"utf8").trim();ee&&(Nr(ee),u({kind:"note",tone:"info",text:"\u{1F6E0} Press c to copy this feedback \u2014 send it to the d360-writer team (Teams / Slack / email)."}))}}catch{}if(P.ok&&$.cueSeen)Vi(!0),ut([]);else{let M=P.ok?Rd(d,tn.map(ee=>ee.name)):[];if(M.length>0)X(M[0]);else if(P.ok&&d.trim()){let ee=xt(!1);ee.kind==="recommend"&&(ee.rec.lead||ee.rec.picker)||bw(c,d,e).then(Ee=>{Ee&&Gn.current===i&&ge(Ee)}).catch(()=>{})}}if(f.uuid&&(_i(f.uuid),!f.titleFired)){f.titleFired=!0;let M=f.uuid,ee=f.firstPrompt;ee&&Hd(ee,e).then(Ee=>{Ee&&(fw(M,Ee),ht(Ee))}).catch(()=>{})}}else P.type==="error"&&(K(!0),b=!0,P.kind==="auth"&&(Zn.current=!0),u({kind:"note",text:`agent error: ${P.message}`,tone:"error"}))}finally{T(!1),W(),z(P=>P+1),qe.current.uuid&&$d(e,qe.current.uuid,It.current),Zn.current?(Zn.current=!1,hn.current=l?.display??c,ge("/login","\u21E5 tab to run /login \u2014 then I\u2019ll re-send your last prompt\u2026")):hn.current=null,pn.current&&(pn.current=!1,bt.current.length>0&&(u({kind:"note",tone:"info",text:`(${bt.current.length} queued message(s) discarded)`}),bt.current=[],Pr([])),u({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,u,ia,Ze,ge,X,Ue,xt]),Gt=B(async c=>{let l=br(e,"standard");pt.current=Date.now(),jt(0),T(!0);let i=new AbortController;ye.current=i;let f=async(d,w)=>{let b=Oi(d);te({verb:"Publishing",total:b.length,done:0,active:[],rows:Hn(b),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:w?`Resolving cross-links in ${d.length} article${d.length===1?"":"s"} whose targets published this run (second pass)\u2026 (esc to stop)`:`Publishing ${d.length} article${d.length===1?"":"s"} across ${b.length} partition${b.length===1?"":"s"} (\u2264${An} agents at once) on ${l.model}\u2026 (esc to stop)`});let h=!1;for await(let $ of kr({cwd:e,partitions:b,promptFor:x=>Lo(x.paths),concurrency:An,profileName:s,allowProdWrites:_t.current,model:l.model,signal:i.signal}))if($.type==="partition_status")$.status==="running"?te(x=>x&&{...x,active:[...x.active,$.label],rows:Le(x.rows,$.label,"active"),lastAt:Date.now()}):te(x=>x&&{...x,active:x.active.filter(N=>N!==$.label),done:x.done+1,rows:Le(x.rows,$.label,$.status==="done"?"done":"failed"),lastAt:Date.now()});else if($.type==="partition_event")te(x=>{if(!x)return x;let N={...x,lastAt:Date.now()};return $.event.type==="tool"?N.tools=x.tools+1:$.event.type==="text"&&(N.chars=x.chars+$.event.delta.length),N});else if($.type==="run_done"){h=$.aborted,qt(K=>K+$.totalCostUsd),Ht(K=>K+$.results.reduce((P,I)=>P+I.outputTokens,0));let x=$.aborted?"Stopped. ":"",N=t.kind==="api"?"api":"subscription";u({kind:"note",tone:$.aborted?"warn":$.ok?"ok":"warn",text:x+us($.results,b,N).join(`
|
|
390
|
+
`)});let W=ds(e,s);if(W&&u({kind:"note",tone:"info",text:W}),!$.aborted){try{let K=await Jd({cwd:e,profileName:s}),P=Zd(K);P?u({kind:"note",tone:"info",text:P}):K.skipped&&u({kind:"note",tone:"warn",text:`Order sync skipped: ${K.skipped}`})}catch(K){u({kind:"note",tone:"warn",text:`Order sync failed: ${K.message}`})}try{let K=tu(await eu({cwd:e,profileName:s}));K&&u({kind:"note",tone:"info",text:K})}catch(K){u({kind:"note",tone:"warn",text:`Related-articles sync failed: ${K.message}`})}}}return h};try{if(!await f(c,!1)){let w=await ps(e,s,c);w.length>0&&await f(w,!0)}}catch(d){u({kind:"note",tone:"error",text:`Publish run failed: ${d.message}`})}finally{ye.current=null,te(null),T(!1),z(d=>d+1)}},[e,s,u,t]),Lr=B(async c=>{await ne(ls(c),{display:`/publish ${c}`,quietUser:!0});try{let l=await Oo(e,s,c.replace(/\\/g,"/"));l.length>0&&(un(`Related articles not yet published (${l.length}):`),ut([`/publish --related ${c}`,...l.map(i=>`/publish ${i}`)]))}catch{}},[e,s,ne]),aa=B(c=>{if(c)try{let l=Jc(e,c);if(!l)return;tr(e,l.title).ok&&u({kind:"note",tone:"ok",text:`\u2713 That completed a docs-campaign step \u2014 marked done: ${l.title}`})}catch{}},[e,u]),la=B(async(c,l)=>{let f=Dw(c,3),d=br(e,"standard");pt.current=Date.now(),jt(0),T(!0);let w=new AbortController;ye.current=w,te({verb:"Authoring",unit:"spec",total:f.length,done:0,active:[],rows:Hn(f),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({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 ${d.model}${d.forced?" (forced)":""}\u2026 (esc to stop)`});let b=!1;try{for await(let h of kr({cwd:e,partitions:f,promptFor:Cc,concurrency:6,profileName:s,allowProdWrites:_t.current,model:d.model,signal:w.signal}))if(h.type==="partition_status")h.status==="running"?te($=>$&&{...$,active:[...$.active,h.label],rows:Le($.rows,h.label,"active"),lastAt:Date.now()}):te($=>$&&{...$,active:$.active.filter(x=>x!==h.label),done:$.done+1,rows:Le($.rows,h.label,h.status==="done"?"done":"failed"),lastAt:Date.now()});else if(h.type==="partition_event")te($=>{if(!$)return $;let x={...$,lastAt:Date.now()};return h.event.type==="tool"?x.tools=$.tools+1:h.event.type==="text"&&(x.chars=$.chars+h.event.delta.length),x});else if(h.type==="run_done"){qt(W=>W+h.totalCostUsd),Ht(W=>W+h.results.reduce((K,P)=>K+P.outputTokens,0));let $=h.results.filter(W=>W.ok).length,x=h.aborted?"Stopped. ":"";b=!h.aborted&&l.setup;let N=h.aborted?"":b?" Refreshing the capture-setup checklist\u2026":" Next: /capture --all (or /capture-setup first for the staging checklist).";u({kind:"note",tone:h.aborted?"warn":h.ok?"ok":"warn",text:`${x}Authored specs \u2014 ${$}/${h.results.length} batches ok.${N}`}),!h.aborted&&h.ok&&aa(l.runLine)}}catch(h){u({kind:"note",tone:"error",text:`Spec authoring failed: ${h.message}`})}finally{ye.current=null,te(null),T(!1),z(h=>h+1)}if(b){let h=await _n();h.kind==="forward-to-agent"&&h.prompt&&await ne(h.prompt,{display:h.display,quietUser:!0});let $=ei(e);$&&u({kind:"note",tone:"info",text:$.join(`
|
|
391
|
+
`)})}},[e,s,u,ne]),ca=B(async c=>{let l=await Go([c]);l.kind==="forward-to-agent"&&l.prompt&&await ne(l.prompt,{display:l.display,quietUser:!0}),xc(e,c)&&ke(`Spec ready \u2014 /capture ${c} takes the screenshot; /screenshot picks the next shot.`,{kind:"cmd",cmd:`/capture ${c}`,reason:""})},[e,ne,ke]),Or=B(async(c,l)=>{if(!Yo(e)){u({kind:"note",tone:"warn",text:"Screenshot capture is not set up in this repo yet \u2014 run d360-capture init in this repo's terminal, then d360-capture auth (once per machine)."});return}T(!0);let i=new AbortController;ye.current=i;let f=c.map(N=>({label:N,items:1,status:"pending"}));te({verb:"Capturing",unit:"screenshot",total:c.length,done:0,active:[],rows:f,tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({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)`});let d=Date.now(),w=[];try{for(let N of c){if(i.signal.aborted)break;te(M=>M&&{...M,active:[N],rows:Le(M.rows,N,"active"),lastAt:Date.now()});let{exitCode:W,output:K}=await Zs({cwd:e,id:N,signal:i.signal,stdio:"pipe"});if(Ac(W,K)){u({kind:"note",tone:"error",text:"d360-capture is not installed on this machine. Run: npm i -g document360-capture \u2014 then /capture again."});return}let P=i.signal.aborted&&W!==0?"failed":Js(e,N,W,d),I=P==="captured"?void 0:P==="skipped"?Tc(K)??"a data prerequisite isn't met \u2014 the spec's skip reason names what to stage":Dc(K);w.push({id:N,outcome:P,detail:I}),te(M=>M&&{...M,active:[],done:M.done+1,rows:Le(M.rows,N,P==="captured"?"done":"failed"),lastAt:Date.now()})}}catch(N){u({kind:"note",tone:"error",text:`Capture run failed: ${N.message}`})}finally{ye.current=null,te(null),T(!1),z(N=>N+1)}if(w.length===0)return;let b=w.filter(N=>N.outcome==="captured"),h=w.filter(N=>N.outcome==="skipped"),$=w.filter(N=>N.outcome==="failed"),x=c.length-w.length;u({kind:"note",tone:$.length?"warn":b.length?"ok":"info",text:`\u2713 ${b.length} captured`+(h.length?` \xB7 \u2298 ${h.length} skipped`:"")+($.length?` \xB7 \u2717 ${$.length} failed`:"")+(x?` \xB7 ${x} not run (stopped)`:"")});for(let N of h)u({kind:"note",tone:"info",text:`\u2298 ${N.id} \u2014 ${N.detail}`});for(let N of $)N.detail&&u({kind:"note",tone:"error",text:`\u2717 ${N.id}
|
|
392
|
+
${N.detail}`});if(b.length>0){let N=jc(e,b.map(K=>K.id)),W=N.length===1?`/publish ${N[0]}`:"/publish";ke(`PNG${b.length===1?"":"s"} saved to the screenshots folder \u2014 publish to put ${b.length===1?"it":"them"} in the article${N.length===1?"":"s"}: ${W}`,{kind:"cmd",cmd:W,reason:""})}else if(h.length>0){let N=c.length===1?`/capture ${c[0]}`:"/capture";ke(null,{kind:"cmd",cmd:N,reason:""})}w.length===c.length&&$.length===0&&h.length===0&&aa(l?.runLine)},[e,u,ke]),Mr=B(c=>{let l=Dt(c);if(!l||ct(l)&&!l.refreshToken)return null;let i={...ln(l.idToken)??{},...ln(l.accessToken)??{}};return i.email??i.preferred_username??"signed in"},[]),Ur=B((c,l)=>{if(l){let i=oe(e);i&&(i.defaultProfile=c,qd(i,e))}a(c),Se(void 0,c),u({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${c}"${l?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),Mr(c)||(u({kind:"note",tone:"warn",text:`Profile "${c}" is not signed in \u2014 sign in with /login.`}),X("/login")),z(i=>i+1)},[e,u,Se,Mr,X]),ao=B((c,l,i)=>{go(e,c,l,i.id,i.name),u({kind:"note",tone:"ok",text:`Switched to workspace "${i.name??i.id}" (agent restarted).`}),Se(),Bd(e,c)||(u({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),u({kind:"note",tone:"warn",text:"\u26A0 Before I write the docs, hand the prompt below to your builder (your repo's coding agent). It gives me the architecture brief that makes the docs accurate:"}),u({kind:"note",tone:"info",text:Zt(Jt(e)).join(`
|
|
393
|
+
`)}),Bt(vt()),wn.current=Ie(e).status==="current",Vt.current=ze(e),u({kind:"note",tone:"info",text:`No separate builder agent? Then just ask me now: "write the docs for this repo" \u2014 I'll read the code directly.`}))},[e,u,Se,Bt]),lo=B(async c=>{let l;try{l=await vn(e,c)}catch{u({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),X("/workspace");return}if(l.workspaces.length===0){u({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let i=l.workspaces.filter(d=>(d.workspace_type??"").toLowerCase()!=="apidocumentation"),f=i.length>0?i:l.workspaces;if(f.length===1){let d=f[0],w=l.workspaces.length-f.length;u({kind:"note",tone:"ok",text:`Selected the "${d.name??d.id}" workspace${w>0?" (skipped the API-documentation workspace)":""}.`}),ao(l.profile,l.projectId,d);return}u({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${f.length} available).`}),X("/workspace")},[e,u,ao,X]),co=B((c,l)=>{wo(e,c,l.id,l.name),u({kind:"note",tone:"ok",text:`Project set to "${l.name??l.id}" (agent restarted).`}),Se(),lo(c)},[e,u,Se,lo]),da=B(async c=>{let l;try{l=Te(e,c)}catch{return}if(!l.project.workspaceId){if(l.project.projectId){if(!l.project.projectName)try{let{projects:i}=await nt(e,l.name),f=i.find(d=>d.id===l.project.projectId);f?.name&&Mw(e,l.name,{projectName:f.name})}catch{}await lo(l.name);return}try{let{projects:i}=await nt(e,l.name);if(i.length===1){let f=i[0];u({kind:"note",tone:"ok",text:`Using your Document360 project "${f.name??f.id}".`}),co(l.name,{id:f.id,name:f.name});return}if(i.length>1){let f=i.map(d=>({id:d.id,name:d.name??d.id,sub:d.sub_domain}));u({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),gt({cursor:0,current:-1,rows:f,profile:l.name,environment:l.connection.name});return}}catch{}u({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),X("/project")}},[e,u,lo,co,X]),Yt=B(()=>{let c=le.current[0];if(!c)return;Ue();let{plan:l,mode:i}=c;u({kind:"note",tone:"info",text:`\u25CF ${l.title} (${l.path})`});for(let d of l.notes)u({kind:"note",tone:"warn",text:`\u26A0 ${d}`});l.overwritesLocalChanges&&i==="pull"&&u({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let f=Ke(l.oldContent,l.newContent,Ze());u(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"?(u({kind:"note",tone:"warn",text:"Conflict \u2014 edited both here and on the portal (diff shows local \u2192 portal)."}),u({kind:"note",tone:"info",text:"Keep local (publish, overwrites portal) \xB7 take Portal (overwrites local) \xB7 Skip? (l/p/s \u2014 anything else cancels)"})):u({kind:"note",tone:"info",text:`Write ${l.path}? (y/n \u2014 anything else cancels)`})},[u,Ze,Ue]),Wr=B(()=>{if(le.current.length>0){Yt();return}let c=Lt.current;Lt.current=[],c.length>0?(u({kind:"note",tone:"info",text:`Publishing ${c.length} kept-local article${c.length===1?"":"s"} over the portal\u2026`}),Gt(c)):X("/pull")},[Yt,u,Gt,X]),ua=B(c=>{if(le.current.length===0)return!1;let l=c.trim().toLowerCase(),i=le.current[0];if(i.mode==="conflict"){if(l==="l"||l==="local")le.current.shift(),Lt.current.push(i.plan.path),u({kind:"note",tone:"info",text:`Keeping local ${i.plan.path} \u2014 will publish over the portal.`});else if(l==="p"||l==="portal"){le.current.shift();try{Vd({cwd:e,profileName:s},i.plan),u({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${i.plan.path} (local overwritten, sync base advanced).`})}catch(f){u({kind:"note",tone:"error",text:`Take-portal failed: ${f.message}`})}}else if(l==="s"||l==="skip"||l==="n")le.current.shift(),u({kind:"note",tone:"info",text:`Skipped ${i.plan.path} \u2014 still a conflict.`});else{let f=le.current.length;return le.current=[],Lt.current=[],u({kind:"note",tone:"info",text:`Resolve cancelled (${f} conflict${f===1?"":"s"} left untouched).`}),!0}return Wr(),!0}if(l==="y"||l==="yes"){let f=le.current.shift().plan;try{Vd({cwd:e,profileName:s},f),u({kind:"note",tone:"ok",text:`\u2713 Pulled ${f.path} (sync base advanced).`})}catch(d){u({kind:"note",tone:"error",text:`Pull failed: ${d.message}`})}}else if(l==="n"||l==="no"){let f=le.current.shift().plan;u({kind:"note",tone:"info",text:`Skipped ${f.path}.`})}else{let f=le.current.length;return le.current=[],u({kind:"note",tone:"info",text:`Pull cancelled (${f} article(s) left untouched).`}),!0}return Wr(),!0},[e,s,Wr,u]),Fr=B(async c=>{u({kind:"note",tone:"info",text:"Checking Document360 for conflicts\u2026"});try{let l=await Li({cwd:e,profileName:s}),i=c?.replace(/\\/g,"/"),f=l.entries.filter(w=>w.status==="conflict"&&w.path).map(w=>w.path);if(i){if(!f.includes(i)){u({kind:"note",tone:"ok",text:`${i} isn\u2019t in conflict \u2014 nothing to resolve.`});return}f=[i]}if(f.length===0){u({kind:"note",tone:"ok",text:"\u2713 No conflicts \u2014 local and Document360 agree on every tracked article."});return}let d=[];for(let w of f)try{d.push({plan:await Yd({cwd:e,profileName:s,relPath:w}),mode:"conflict"})}catch(b){u({kind:"note",tone:"error",text:`Could not load ${w} from Document360: ${b.message}`})}if(d.length===0)return;u({kind:"note",tone:"info",text:`Resolving ${d.length} conflict${d.length===1?"":"s"} \u2014 for each: keep local, take portal, or skip.`}),le.current=d,Lt.current=[],Yt()}catch(l){u({kind:"note",tone:"error",text:`Could not compute sync status: ${l.message}`})}},[e,s,u,Yt]),pa=B(c=>{let l=Qn.current;if(!l)return!1;if(Qn.current=null,Ue(),c.trim()!==l.repoName)return u({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:i,failed:f}=ui(e,l.targets);u({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 d of f)u({kind:"note",tone:"error",text:` \u2717 ${d.path}: ${d.error}`});return l.hadDevhints&&(u({kind:"note",tone:"warn",text:To().join(`
|
|
394
|
+
`)}),Bt(Xr())),u({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
|
|
395
|
+
${nu}`}),X("/init"),Yn(!1),!0},[e,u,Bt,Ue,X]),bn=B(async c=>{let l=c.slice(1).trim().split(/\s+/),i=(l[0]??"").toLowerCase(),f=l.slice(1);if(Yn(!0),Fo(f)&&["write","check","review","reorder"].includes(i)){let d=En(e,s);if(d.length===0){u({kind:"note",tone:"warn",text:"No categories yet \u2014 author some articles first, then scope to one."});return}let w=b=>i==="write"?`/write ${Wl(f,b).join(" ")}`.trim():`/${i} ${[b,...f.filter(h=>h!=="--scope")].join(" ")}`.trim();if(d.length===1){bn(w(d[0].token));return}yt({cursor:0,rows:d,run:b=>{bn(w(b))}});return}if(at(i,f)){let d=En(e,s);if(d.length>1){let w=f.filter(x=>x.startsWith("--")).join(" "),b=x=>`/${i}${x?` ${i==="write"?`--scope ${x}`:x}`:""}${w?` ${w}`:""} ${x?"":"--all"}`.replace(/\s+/g," ").trim(),h=d.reduce((x,N)=>x+N.count,0),$={token:"",label:i==="review"?`Everything \u2014 all ${h} articles + structure (IA) review`:i==="reorder"?`Everything \u2014 reorder all ${d.length} categories`:`Everything \u2014 rewrite all ${h} planned articles`,count:h};yt({cursor:0,rows:[$,...d],run:x=>{bn(b(x))}});return}}switch(i){case"help":mn({tab:0});return;case"exit":case"quit":Ae.current?.close(),r();return;case"clear":Se(),It.current=[],Yn(!1),Ue(),console.log("\x1B[?2026h\x1B[H\x1B[2J\x1B[3J\x1B[?2026l"),u({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let d;try{d=Te(e,s)}catch(w){u({kind:"note",tone:"error",text:w.message});return}u({kind:"note",tone:"info",text:`Profile "${d.name}" \u2192 ${d.connection.name} (${d.connection.apiUrl})${d.production?" \u26A0 PRODUCTION":""}`}),G(!0);try{let w=await iw(d.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},h=>u({kind:"note",tone:"info",text:h})),b=aw(d.name,w);if(lw(b),await Vr(b,d.name,h=>u({kind:"note",tone:"info",text:h})),u({kind:"note",tone:"ok",text:`\u2713 Logged in to "${d.name}" as ${bo(b)}`}),await da(s),fn.current){let h=fn.current;fn.current=null;let $=_e(e,s);$.ok?(u({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 tab to run ${h}.`}),X(h)):(u({kind:"note",tone:"warn",text:`${$.reason} (then ${h}.)`}),X("/login"),fn.current=h)}else hn.current&&(ge(hn.current,"\u21E5 tab to re-send your last prompt\u2026"),hn.current=null)}catch(w){u({kind:"note",tone:"error",text:`Login failed: ${w.message}`})}finally{G(!1),z(w=>w+1)}return}case"allow-prod":{let d=!1;try{d=Te(e,s).production}catch{}if(!d){u({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}_t.current=!0,Se(),u({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let d=Bs(f.join(" ")),w=qe.current.uuid;if(!w){if(!d){u({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}Sr.current=d,ht(d),rn(`${hr} ${d}`),u({kind:"note",tone:"ok",text:`Session will be named "${d}" once it starts.`});return}if(!d){u({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let b=qe.current.firstPrompt??"";Hd(b,e).then(h=>{h?(ge(`/rename ${h}`),u({kind:"note",tone:"info",text:`Suggestion: "${h}" \u2014 press tab to accept, or type /rename <your name>.`})):u({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>u({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}kw(w,d),ht(d),rn(`${hr} ${d}`),u({kind:"note",tone:"ok",text:`Session renamed to "${d}".`});return}case"profile":{let d=f[0],w=oe(e);if(!d){let b=Object.entries(w?.profiles??{});if(b.length===0){u({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let h=b.map(([N,W])=>({name:N,env:W.connection?.environment??"custom",prod:W.production===!0,who:Mr(N)})),$=s??w?.defaultProfile,x=Math.max(0,h.findIndex(N=>N.name===$));Ot({cursor:x,current:x,rows:h});return}if(d==="add"){let b=Vs(e,f[1],f[2]);if(b){u({kind:"note",tone:"error",text:b});return}u({kind:"note",tone:"ok",text:`\u2713 Profile "${f[1]}" created (environment: ${f[2]??f[1]}).`}),Ur(f[1],!1);return}if(!w?.profiles?.[d]){u({kind:"note",tone:"error",text:`Unknown profile "${d}". Create it: /profile add ${d} <environment>`});return}Ur(d,!0);return}case"doctor":await In(f,{cwd:e,version:o});return;case"genre":{await Zo(f,{cwd:e});try{xr.current=!(oe(e)?.appType??xw(e))}catch{}z(d=>d+1);return}case"roadmap":{if(f[0]?.toLowerCase()==="done"){let d=tr(e,f.slice(1).join(" ").trim());u({kind:"note",tone:d.ok?"ok":"warn",text:d.line}),z(w=>w+1);return}u({kind:"note",tone:"info",text:wi(e).join(`
|
|
396
|
+
`)});return}case"mcp":await jo(f);return;case"init":{if(oe(e)){u({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer/config.json directly (or d360-writer init for the CLI wizard)."});return}let d=Pw().map(w=>({name:w,apiUrl:Tw(w).apiUrl}));Mt({cursor:0,rows:d});return}case"resume":{let d=f.join(" ").trim(),w=yw(e).filter($=>$.uuid!==qe.current.uuid);if(!d){if(!w.length){u({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}$t({query:"",cursor:0,sessions:w});return}let b=ww(e,d);if(!b){u({kind:"note",tone:"error",text:`No session matches "${d}".`});return}Se(b.uuid),qe.current={uuid:b.uuid,firstPrompt:b.firstPrompt,titleFired:!0},ht(b.name),_i(b.uuid),It.current=[];let h=Ai(e,b.uuid);for(let $ of h)u($);u({kind:"note",tone:"ok",text:h.length?`Resumed "${b.name}" \u2014 restored ${h.length} message(s); continue where you left off.`:`Resumed "${b.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let d=f.join(" ").trim(),w;try{w=await vn(e,s)}catch(h){u({kind:"note",tone:"error",text:`Could not list workspaces: ${h.message}`});return}if(!d){let h=w.workspaces.map(x=>({id:x.id,name:x.name??x.id,type:x.workspace_type}));if(h.length===0){u({kind:"note",tone:"info",text:"No workspaces in this project."});return}let $=Math.max(0,h.findIndex(x=>x.id===w.current));Ut({cursor:$,current:$,rows:h,profile:w.profile,projectId:w.projectId,projectName:w.projectName,environment:w.environment});return}let b=qr(w.workspaces,d);if(!b){u({kind:"note",tone:"error",text:`No workspace matches "${d}".`});return}ao(w.profile,w.projectId,b);return}case"project":{let d=f.join(" ").trim(),w;try{w=await nt(e,s)}catch(h){u({kind:"note",tone:"error",text:`Could not list projects: ${h.message} (signed in? try /login)`});return}if(!d){let h=w.projects.map(x=>({id:x.id,name:x.name??x.id,sub:x.sub_domain}));if(h.length===0){u({kind:"note",tone:"info",text:"No projects found for this identity."});return}let $=h.findIndex(x=>x.id===w.current);gt({cursor:Math.max(0,$),current:$,rows:h,profile:w.profile,environment:w.environment});return}let b=Br(w.projects,d);if(!b){u({kind:"note",tone:"error",text:`No project matches "${d}". Available: ${w.projects.map(h=>h.name??h.id).join(", ")}`});return}co(w.profile,b);return}case"logout":{let d;try{d=Te(e,s).name}catch(b){u({kind:"note",tone:"error",text:b.message});return}let w=pw(d);hw(e,d),Se(),z(b=>b+1),u({kind:"note",tone:w?"ok":"info",text:w?`\u2713 Signed out of "${d}" and cleared its project/workspace selection.`:`Profile "${d}" was not signed in. Cleared any project/workspace selection.`}),u({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),X("/login");return}case"publish":{if(!no(c.trim()))return;if(f[0]==="--related"&&f[1]){let h=await Oo(e,s,f[1].replace(/\\/g,"/"));if(h.length===0){u({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await Gt(h);return}let d=f.filter(h=>!h.startsWith("--"));if(d[0]){await Lr(d[0]);return}let w=f.includes("--all"),b=f.includes("--force");u({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let h=await Li({cwd:e,profileName:s}),{clean:$,conflicts:x}=No(h.entries),N=w&&b&&x.length>0,W=_o(h.entries);if(W>0&&u({kind:"note",tone:"warn",text:`\u26A0 ${W} article${W===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.`}),x.length>0&&!N&&u({kind:"note",tone:"warn",text:Io(x.length)}),$.length===0&&!N){if(x.length>0){X("/resolve");return}u({kind:"note",tone:"ok",text:W>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let K=h.counts["unknown-base"]??0;K>0&&u({kind:"note",tone:"info",text:`(${K} article(s) have no sync base yet \u2014 publish those by path if needed.)`}),Ji("Reconciling structure on Document360 (order + related articles)\u2026");try{let P=await Jd({cwd:e,profileName:s}),I=tu(await eu({cwd:e,profileName:s})),M=Zd(P);M?u({kind:"note",tone:"info",text:M}):P.skipped&&u({kind:"note",tone:"warn",text:`Order sync skipped: ${P.skipped}`}),I&&u({kind:"note",tone:"info",text:I}),u({kind:"note",tone:"ok",text:M||I?"\u2713 Structure synced to Document360 \u2014 /structure shows the new category + article order.":"\u2713 Already in order \u2014 nothing to change."}),(M||I)&&X("/structure")}catch(P){u({kind:"note",tone:"warn",text:`Structure sync failed: ${P.message}`})}finally{Ji(null)}return}if(w){let K=(N?[...$,...x]:$).map(P=>P.path);await Gt(K),x.length>0&&!N&&X("/resolve");return}Wt({cursor:0,rows:xl($,x)})}catch(h){u({kind:"note",tone:"error",text:`Could not compute sync status: ${h.message}`}),u({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"resolve":{if(!no(c.trim()))return;await Fr(f.find(d=>!d.startsWith("--")));return}case"preview":{let d=f.join(" ").trim();if(!d){let b=[];try{b=Object.keys(Bd(e,Te(e,s).name)?.articles??{})}catch{}if(b.length===0){u({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}kt({query:"",cursor:0,paths:b});return}let w=rw(d)?d:Ii(e,d);if(sn(w)){try{u({kind:"preview",name:qn(w),text:ru(yr(w,"utf8"))})}catch(b){u({kind:"note",tone:"error",text:`Could not read ${w}: ${b.message}`})}return}if(zw.test(d)){try{let b=Te(e,s),h={profile:b.name,connection:b.connection},$=b.project.projectId??dw(h),x=await uw(h,$,d);u({kind:"preview",name:x.title??d,text:x.content??"*(article has no content)*"})}catch(b){u({kind:"note",tone:"error",text:`Could not fetch article: ${b.message}`})}return}u({kind:"note",tone:"error",text:`"${d}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let d=f[0]?.trim();if(!d){let $=qo(Fi(e));mt({cursor:$,current:$});return}let{lines:w,changed:b,effective:h}=Nn(e,d);for(let $ of w)u({kind:"note",tone:$.startsWith("\u26A0")?"warn":$.startsWith("\u2713")?"ok":"info",text:$});b&&(ta($=>$+1),Ae.current?.setModel(h));return}case"convert":{if(!oe(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:d,run:w}=$s(f),b=jw(e,s);if(b.length===0){u({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let h=xs(b,d);if(h.length===0){u({kind:"note",tone:"error",text:`No tracked articles under "${d}". (${b.length} are tracked overall.)`});return}let $=Oi(h),x=3,N=`/convert${d?` --scope ${d}`:""} --run`,W=br(e,"light");if(!w){let P=zd({files:vs(e,h),op:"convert",model:W.model}),I=d?`Scope: ${d} (${h.length} of ${b.length} tracked)
|
|
397
|
+
`:"",M=`
|
|
398
|
+
Model: ${W.model}${W.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;u({kind:"note",tone:"info",text:I+Rs($,P,x).join(`
|
|
399
|
+
`)+M}),X(N);return}pt.current=Date.now(),jt(0),T(!0);let K=new AbortController;ye.current=K,te({verb:"Converting",total:$.length,done:0,active:[],rows:Hn($),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Converting ${h.length} articles across ${$.length} partitions (\u2264${x} agents at once) on ${W.model}\u2026 (esc to stop)`});try{for await(let P of kr({cwd:e,partitions:$,promptFor:Cs,concurrency:x,profileName:s,allowProdWrites:_t.current,model:W.model,signal:K.signal}))if(P.type==="partition_status")P.status==="running"?te(I=>I&&{...I,active:[...I.active,P.label],rows:Le(I.rows,P.label,"active"),lastAt:Date.now()}):te(I=>I&&{...I,active:I.active.filter(M=>M!==P.label),done:I.done+1,rows:Le(I.rows,P.label,P.status==="done"?"done":"failed"),lastAt:Date.now()});else if(P.type==="partition_event")te(I=>{if(!I)return I;let M={...I,lastAt:Date.now()};return P.event.type==="tool"?M.tools=I.tools+1:P.event.type==="text"&&(M.chars=I.chars+P.event.delta.length),M});else if(P.type==="run_done"){qt(ee=>ee+P.totalCostUsd),Ht(ee=>ee+P.results.reduce((Ee,ho)=>Ee+ho.outputTokens,0));let I=P.aborted?"Stopped. ":"",M=t.kind==="api"?"api":"subscription";u({kind:"note",tone:P.aborted?"warn":P.ok?"ok":"warn",text:I+Ss(P.results,$,M).join(`
|
|
400
|
+
`)})}}catch(P){u({kind:"note",tone:"error",text:`Convert run failed: ${P.message}`})}finally{ye.current=null,te(null),T(!1),z(P=>P+1)}return}case"write":{if(!oe(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let d=Ew(e);if(d.length===0){u({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:w,path:b,preview:h,concurrency:$,rewrite:x}=Ds(f),{docsDir:N,targets:W,reason:K,rewriting:P}=Ls(e,d,{scope:w,path:b,rewrite:x});if(W.length===0){u({kind:"note",tone:"warn",text:K??"Nothing to write."});return}P&&u({kind:"note",tone:"warn",text:`--rewrite: regenerating ${W.length} already-written article${W.length===1?"":"s"} (overwrites them; git has your baseline).`});let I=Oi(W),M=Ts($),ee=br(e,"standard"),Ee=!!b;if(h&&!Ee){let Q=zd({files:js(e,d,W),op:"write",model:ee.model}),se=w?`Scope: ${w} (${W.length} pending)
|
|
401
401
|
`:"",he=`
|
|
402
|
-
Model: ${ee.model}${ee.forced?" (forced)":" \u2014 authoring; /model to override"}`;u({kind:"note",tone:"info",text:se+
|
|
403
|
-
`)+he}),X(`/write${w?` --scope ${w}`:""}`);return}pt.current=Date.now(),jt(0),T(!0);let ho=new AbortController;ye.current=ho,te({verb:"Writing",total:
|
|
404
|
-
`)}),!Q.aborted&&Q.ok)try{let et=(fo.size>0?[...fo]:
|
|
405
|
-
${d.map(
|
|
406
|
-
`)}`}),ut(d.map(
|
|
407
|
-
`)});return}if(d==="--baseline"){let h=f.find(
|
|
408
|
-
${
|
|
409
|
-
`)}`}),z(
|
|
410
|
-
`)});return}if(d){u({kind:"note",tone:"error",text:`Unknown option: ${d} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let w=f[0];if(w){let h=await
|
|
411
|
-
`)}),ke(
|
|
412
|
-
`)})
|
|
413
|
-
`)});return}case"reorder":{let d=
|
|
402
|
+
Model: ${ee.model}${ee.forced?" (forced)":" \u2014 authoring; /model to override"}`;u({kind:"note",tone:"info",text:se+Ns(I,Q,M).join(`
|
|
403
|
+
`)+he}),X(`/write${w?` --scope ${w}`:""}`);return}pt.current=Date.now(),jt(0),T(!0);let ho=new AbortController;ye.current=ho,te({verb:"Writing",total:I.length,done:0,active:[],rows:Hn(I),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Writing ${W.length} article${W.length===1?"":"s"} across ${I.length} partition${I.length===1?"":"s"} (\u2264${M} agents at once) on ${ee.model}${ee.forced?" (forced)":""}\u2026 (esc to stop)`});let fo=new Set;try{for await(let Q of kr({cwd:e,partitions:I,promptFor:se=>Es(se,N,{rewrite:P||Ee}),concurrency:M,profileName:s,allowProdWrites:_t.current,model:ee.model,signal:ho.signal}))if(Q.type==="partition_status")Q.status==="running"?te(se=>se&&{...se,active:[...se.active,Q.label],rows:Le(se.rows,Q.label,"active"),lastAt:Date.now()}):te(se=>se&&{...se,active:se.active.filter(he=>he!==Q.label),done:se.done+1,rows:Le(se.rows,Q.label,Q.status==="done"?"done":"failed"),lastAt:Date.now()});else if(Q.type==="partition_event"){let se=null;if(Q.event.type==="tool"){let he=Pd(Q.event.name,Q.event.input,I[Q.index]?.paths??[]);he&&!fo.has(he)&&(fo.add(he),se=Q.label)}te(he=>{if(!he)return he;let We={...he,lastAt:Date.now()};return Q.event.type==="tool"?We.tools=he.tools+1:Q.event.type==="text"&&(We.chars=he.chars+Q.event.delta.length),se&&(We.rows=Sd(We.rows,se)),We})}else if(Q.type==="run_done"){qt(et=>et+Q.totalCostUsd),Ht(et=>et+Q.results.reduce((Ye,vu)=>Ye+vu.outputTokens,0));let se=Q.aborted?"Stopped. ":"",he=t.kind==="api"?"api":"subscription";if(u({kind:"note",tone:Q.aborted?"warn":Q.ok?"ok":"warn",text:se+Is(Q.results,I,he).join(`
|
|
404
|
+
`)}),!Q.aborted&&Q.ok)try{let et=(fo.size>0?[...fo]:W).map(Ye=>`${N}/${Ye}`);Mi(e,et,{writtenCap:Ui})}catch{}let We=Q.aborted?null:_s(e,N,W);if(We&&u({kind:"note",tone:"warn",text:We}),!Q.aborted&&Q.ok){let et=w??b??"",Ye=et?` ${et}`:"";ke(We?`Written \u2014 but the checker flagged issues. I\u2019d fix those first with /check${Ye} --fix, then /review${Ye} --fix for editorial quality, then /publish --all (add /screenshot --all first if you want images).`:`Written. I\u2019d run /review${Ye} --fix next \u2014 editorial review that applies its fixes \u2014 then /publish --all pushes the drafts up (add /screenshot --all first if you want images).`,{kind:"cmd",cmd:We?`/check${Ye} --fix`:`/review${Ye} --fix`,reason:""})}}}catch(Q){u({kind:"note",tone:"error",text:`Write run failed: ${Q.message}`})}finally{ye.current=null,te(null),T(!1),z(Q=>Q+1)}return}case"draft":{if(!oe(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:d,looseDocs:w}=Os(e);if(d.length===0&&w===0){u({kind:"note",tone:"info",text:Us});return}let b=f.join(" ").trim();if(!b&&d.length>1){u({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
|
|
405
|
+
${d.map(x=>` \u2022 ${x.name} (${x.docCount} doc${x.docCount===1?"":"s"})`).join(`
|
|
406
|
+
`)}`}),ut(d.map(x=>`/draft ${x.name}`));return}let h="",$;if(b){let x=Ms(d,b);x?h=x:$=b}else h=d[0]?.name??"";await ne(Ho(h,$),{display:b?`/draft ${b}`:"/draft",quietUser:!0});return}case"pull":{if(!no(c.trim()))return;let d=f.find(w=>w.startsWith("--"));try{if(d==="--status"){u({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let h=Date.now(),$=await Li({cwd:e,profileName:s});u({kind:"note",tone:"info",text:Uo($,Date.now()-h).join(`
|
|
407
|
+
`)});return}if(d==="--baseline"){let h=f.find(W=>!W.startsWith("--")),$=h?h.replace(/\\/g,"/"):void 0;u({kind:"note",tone:"info",text:$?`Setting the sync baseline for ${$}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let x=await Cw({cwd:e,profileName:s,relPaths:$?[$]:void 0}),N=$?{rebaselined:[],skipped:[]}:await Rw({cwd:e,profileName:s});if(x.baselined.length===0&&x.skipped.length===0&&N.rebaselined.length===0){u({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}x.baselined.length>0&&u({kind:"note",tone:"ok",text:`\u2713 Baselined ${x.baselined.length} article${x.baselined.length===1?"":"s"} \u2014 they now read in-sync until either side changes.`}),N.rebaselined.length>0&&u({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${N.rebaselined.length} article${N.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),x.skipped.length>0&&u({kind:"note",tone:"warn",text:`${x.skipped.length} skipped:
|
|
408
|
+
${x.skipped.map(W=>` - ${W.path} (${W.reason})`).join(`
|
|
409
|
+
`)}`}),z(W=>W+1);return}if(d==="--compare"){u({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let h=await vw({cwd:e,profileName:s}),$=h.onlyInLegacy.length===0&&h.onlyInManifest.length===0&&h.mappedMissingFromManifest.length===0,x=[`Legacy listing: ${h.legacyCount} \xB7 Manifest: ${h.manifestCount} \xB7 in both: ${h.inBoth}`];$?x.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(h.mappedMissingFromManifest.length&&x.push(`\u2717 ${h.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${h.mappedMissingFromManifest.slice(0,5).join(", ")}`),h.onlyInLegacy.length&&x.push(`\u26A0 ${h.onlyInLegacy.length} only in the legacy listing: ${h.onlyInLegacy.slice(0,5).join(", ")}`),h.onlyInManifest.length&&x.push(`\u26A0 ${h.onlyInManifest.length} only in the manifest: ${h.onlyInManifest.slice(0,5).join(", ")}`),x.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),u({kind:"note",tone:$?"ok":"warn",text:x.join(`
|
|
410
|
+
`)});return}if(d){u({kind:"note",tone:"error",text:`Unknown option: ${d} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let w=f[0];if(w){let h=await Yd({cwd:e,profileName:s,relPath:w.replace(/\\/g,"/")});le.current=[{plan:h,mode:h.overwritesLocalChanges?"conflict":"pull"}],Lt.current=[],Yt();return}u({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let b=await ys({cwd:e,profileName:s});for(let h of ks(b))u({kind:"note",tone:h.tone,text:h.text});z(h=>h+1)}catch(w){u({kind:"note",tone:"error",text:`Pull failed: ${w.message}`})}return}case"scope":{if(!oe(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let d=Sw(e);if(d.length===0){u({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.'});return}Ft({cursor:0,rows:d.map(w=>({...w,checked:w.recommended}))});return}case"audit":{if(f[0]==="--auto"){let w=oe(e);if(!w){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let b=f[1]!=="off";qd({...w,autoAudit:b},e),u({kind:"note",tone:"ok",text:b?"\u2713 Auto-audit ON \u2014 when you launch with code changes since the last audit, I\u2019ll run /audit automatically. (/audit --auto off to disable.)":"\u2713 Auto-audit OFF \u2014 I\u2019ll just nudge you to run /audit when code changed."});return}let d=await jn();d.kind==="forward-to-agent"&&d.prompt&&await ne(d.prompt,{display:d.display,quietUser:!0});return}case"check":{let d=f.find(h=>!h.startsWith("--")),w=d?` ${d}`:"",b=Gd({cwd:e,scope:d});if(f.includes("--fix")){if(b.length===0){u({kind:"note",tone:"ok",text:"\u2713 Nothing to fix \u2014 the docs are already clean."});return}u({kind:"note",tone:"info",text:`Fixing ${b.length} doc issue${b.length===1?"":"s"}\u2026`});let h=Qd(e,d);await ne(hi(b),{display:`/check${w} --fix`,quietUser:!0});try{Mi(e,h,{reviewedCap:Ui})}catch{}let $=Gd({cwd:e,scope:d});u({kind:"note",tone:$.length===0?"ok":"warn",text:$.length===0?"\u2713 Doc-checker: all issues resolved.":Jo($).join(`
|
|
411
|
+
`)}),ke($.length===0?`Deterministic issues fixed. Next: /review${w} --fix for editorial quality (style, grammar, structure), then /publish --all.`:`Some issues remain \u2014 /review${w} --fix runs the editorial review + fixes, then /publish --all.`,{kind:"cmd",cmd:`/review${w} --fix`,reason:""});return}u({kind:"note",tone:b.length===0?"ok":"warn",text:Jo(b).join(`
|
|
412
|
+
`)}),b.length>0&&ke(`Found ${b.length} doc issue${b.length===1?"":"s"} above. /check${w} --fix has the agent fix them in place (or /review${w} --fix for the full editorial pass; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/check${w} --fix`,reason:""});return}case"structure":{let d=Mn(e,s);if(d.length===0){u({kind:"note",tone:"info",text:"No documentation structure yet \u2014 run /init and author some articles first."});return}u({kind:"note",tone:"info",text:["Documentation order (categories \u2192 articles):","",...d].join(`
|
|
413
|
+
`)});return}case"reorder":{let d=mi(e,f);if(!d){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await ne(d.prompt,{display:d.display,quietUser:!0}),ke("Reordered locally \u2014 /publish --all syncs the new order to Document360.",{kind:"cmd",cmd:"/publish --all",reason:""});return}case"review":{let d=fi(e,f);if(!d){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let w=f.includes("--fix"),b=f.find($=>!$.startsWith("--")),h=w?Qd(e,b):[];if(await ne(d.prompt,{display:d.display,quietUser:!0}),w)try{Mi(e,h,{reviewedCap:Ui})}catch{}if(w)ke("\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 $=f.filter(x=>x!=="--fix").join(" ");ke(`The review listed issues above. /review${$?` ${$}`:""} --fix lets the editor apply them all (or /check --fix for just the deterministic ones; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/review${$?` ${$}`:""} --fix`,reason:""})}return}case"capture-setup":{let d=await _n();d.kind==="forward-to-agent"&&d.prompt&&await ne(d.prompt,{display:d.display,quietUser:!0});let w=ei(e);w&&u({kind:"note",tone:"info",text:w.join(`
|
|
414
414
|
`)});return}case"devhints":{if(!oe(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}u({kind:"note",tone:"info",text:Zt(Jt(e)).join(`
|
|
415
|
-
`)}),Bt(vt()),wn.current=Ie(e).status==="current",Vt.current=ze(e);return}case"discover":{if(!oe(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await ne(
|
|
416
|
-
`)}),ke(`\u2713 All ${h.length} screenshots are captured. /publish puts them in the articles; /capture re-captures.`,{kind:"cmd",cmd:"/publish",reason:""});return}wt({cursor:0,rows:
|
|
417
|
-
`)});let
|
|
418
|
-
`)}),ge(qn(e));return}default:u({kind:"note",tone:"error",text:`Unknown command: /${i} \u2014 type /help.`})}},[e,r,s,Yt,Ur,u,Se,ne,Gt,Ir,ca]),uo=B(c=>{let l=(c??S).trim();if(v(""),Kn(null),Et(0),l.startsWith("/")&&(Vn.current=!1,Ue(),un(null),ut(f=>Td(f,l))),!l||(Vi(!1),ua(l))||da(l))return;vr.current.push(l);let i=Ed(l,Yi.current);if(l.startsWith("/"))u({kind:"user",text:l}),Xe(!0),bn(i).finally(()=>Xe(!1));else if(Mw(i)){u({kind:"user",text:l});let f=Uw(i);if(!f)ne(i,{display:l,quietUser:!0});else{try{Ww(e,{title:f,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}ne(`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=Qc(e,i);ne(f??i,{display:l})}},[S,ua,da,bn,ne]),pa=B(c=>{if(c.length>1){if(c.includes("\x1B"))return;let l=Dd(c);if(Ad(l)){let i=jd(++mu.current,l);Yi.current.set(i,l),I(i)}else I(l);return}I(c)},[I]),zt=Math.max(10,je-6),ha=Ni(()=>fr(k.text,zt),[k.text,zt]),Wr=B(c=>y(l=>({...l,pos:Math.max(0,Math.min(l.text.length,l.pos+c))})),[]),po=B(c=>y(l=>({...l,pos:Id(fr(l.text,zt),l.pos,c)})),[zt]),$n=B(c=>y(l=>({...l,pos:_d(fr(l.text,zt),l.pos,c)})),[zt]),ku=["\x1B[H","\x1B[1~","\x1BOH"],bu=["\x1B[F","\x1B[4~","\x1BOF"],fa=B((c,l)=>l.leftArrow?(Wr(-1),!0):l.rightArrow?(Wr(1),!0):c&&ku.includes(c)?($n("start"),!0):c&&bu.includes(c)?($n("end"),!0):l.ctrl&&c==="a"?($n("start"),!0):l.ctrl&&c==="e"?($n("end"),!0):!1,[Wr,$n]);return Zg((c,l)=>{if(l.ctrl&&c==="c"){Ae.current?.close(),r();return}if(!L){if(N){if(l.escape){if(ye.current){if(!ye.current.signal.aborted){let i=(Jn?.verb??"work").toLowerCase(),f=Jn?.unit??"article";u({kind:"note",tone:"warn",text:`\u238B Stopping the ${i} run (finishing in-flight ${f}s)\u2026`}),ye.current.abort()}return}pn.current||(pn.current=!0,u({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),Ae.current?.interrupt());return}if(l.return){let i=S.trim();if(!i)return;bt.current.push(i),Rr([...bt.current]),v("");return}if(fa(c,l))return;if(l.upArrow){po(-1);return}if(l.downArrow){po(1);return}if(l.backspace||l.delete){R();return}c&&!l.ctrl&&!l.meta&&pa(c);return}if(ft){if(l.upArrow){mt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){mt(i=>i&&{...i,cursor:Math.min(Fe.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Fe.length){mt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Fe[ft.cursor];mt(null);let{lines:f,changed:d,effective:w}=Nn(e,i.value??"default");for(let $ of f)u({kind:"note",tone:$.startsWith("\u26A0")?"warn":$.startsWith("\u2713")?"ok":"info",text:$});d&&(ta($=>$+1),Ae.current?.setModel(w));return}if(c==="s"){let i=Fe[ft.cursor];mt(null),Ae.current?.setModel(i.value??void 0),u({kind:"note",tone:"ok",text:`\u2713 Using ${i.label} for this session only (your saved default is unchanged).`});return}if(l.escape){mt(null);return}return}if(Be){if(l.upArrow){Lt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Lt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Be.rows.length){Lt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return||c==="s"){let i=Be.rows[Be.cursor];Lt(null),Lr(i.name,l.return===!0);return}if(l.escape){Lt(null);return}return}if(eo){if(l.escape){mn(null);return}if(l.leftArrow||l.tab&&l.shift){mn(i=>i&&{tab:(i.tab-1+Ne.length)%Ne.length});return}if(l.rightArrow||l.tab){mn(i=>i&&{tab:(i.tab+1)%Ne.length});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ne.length){mn({tab:Number(c)-1});return}return}if(Ve){if(l.upArrow){Mt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Mt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ve.rows.length){Mt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Ve.rows[Ve.cursor].name;if(Mt(null),!Kr(e,i).created){u({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}u({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${i}").`});let d=!1;try{let w=Dt(i);d=!!w&&!(ct(w)&&!w.refreshToken)}catch{d=!1}u({kind:"note",tone:"info",text:d?`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.`}),X("/login"),z(w=>w+1);return}if(l.escape){Mt(null);return}return}if(me){if(l.upArrow){Ut(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Ut(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=me.rows.length){Ut(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=me.rows[me.cursor],{profile:f,projectId:d}=me;Ut(null),ao(f,d,i);return}if(l.escape){Ut(null);return}return}if(ve){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)<=ve.rows.length){gt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=ve.rows[ve.cursor],{profile:f}=ve;gt(null),co(f,i);return}if(l.escape){gt(null);return}return}if(we){if(l.upArrow){Ft(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Ft(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c===" "){Ft(i=>i&&{...i,rows:i.rows.map((f,d)=>d===i.cursor?{...f,checked:!f.checked}:f)});return}if(l.return){let i=we.rows.filter(f=>f.checked).map(f=>f.path);if(Ft(null),i.length===0){u({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}ps(e,i),u({kind:"note",tone:"ok",text:`\u2713 Scoped to ${i.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let f of i)u({kind:"note",tone:"info",text:` ${f}`});u({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(l.escape){Ft(null);return}return}if(Ge){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)<=Ge.rows.length){yt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Ge.rows[Ge.cursor],f=Ge.run;yt(null),f(i.token);return}if(l.escape){yt(null);return}return}if(Qe){if(l.upArrow){Wt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Wt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Qe.rows.length){Wt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Qe.rows[Qe.cursor];Wt(null),i.conflict?Ur(i.paths[0]):i.kind==="article"?Ir(i.paths[0]):Gt(i.paths);return}if(l.escape){Wt(null);return}return}if(Je){if(l.upArrow){wt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){wt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Je.rows.length){wt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Je.rows[Je.cursor];wt(null),i.action==="capture"?_r(i.ids):i.kind==="shot"?la(i.ids[0]):aa(i.ids,{setup:!0});return}if(l.escape){wt(null);return}return}if(Ce){if(l.escape){kt(null);return}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(Math.max(0,so.length-1),i.cursor+1)});return}if(l.return){let i=so[Ce.cursor];if(i){kt(null);try{u({kind:"preview",name:qn(i),text:nu(gr(Ii(e,i),"utf8"))})}catch(f){u({kind:"note",tone:"error",text:`Could not read ${i}: ${f.message}`})}}return}if(l.backspace||l.delete){kt(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(c&&!l.ctrl&&!l.meta&&c.length===1){kt(i=>i&&{...i,query:i.query+c,cursor:0});return}return}if(Re){if(l.escape){$t(null);return}if(l.upArrow){$t(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){$t(i=>i&&{...i,cursor:Math.min(Math.max(0,io.length-1),i.cursor+1)});return}if(l.return){let i=io[Re.cursor];if(i){$t(null),Se(i.uuid),qe.current={uuid:i.uuid,firstPrompt:i.firstPrompt,titleFired:!0},ht(i.name),_i(i.uuid),It.current=[];let f=Ai(e,i.uuid);for(let d of f)u(d);u({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){$t(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(c&&!l.ctrl&&!l.meta&&c.length===1){$t(i=>i&&{...i,query:i.query+c,cursor:0});return}return}if(l.tab&&!S&&fe){v(fe),Ue();return}if(!S&&He.length>0&&!$r&&c&&/^[1-9]$/.test(c)){let i=He[Number(c)-1];if(i){v(Tt(i));return}}if(!S&&(oo||gn)&&c==="c"&&!l.ctrl&&!l.meta&&!l.return&&!l.tab){let i=oo!=null;Ti(oo??gn).then(d=>{u({kind:"note",tone:d?"ok":"warn",text:d?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."}),d&&i&&jr(null),d&&!i&&oa(!0)});return}if(!fa(c,l)){if(sa){if(l.upArrow){Et(i=>Math.max(0,i-1));return}if(l.downArrow){Et(i=>Math.min(kn.length-1,i+1));return}if(l.tab){v("/"+(kn[dn]?.name??"")+" "),Et(0);return}if(l.return){let i=kn[dn];if(i){let f=S.trim().slice(1).split(/\s+/).slice(1).join(" ");if(il(i.usage)&&!f){v("/"+i.name+" "),Et(0);return}uo("/"+i.name+(f?" "+f:""));return}}}else{if(l.upArrow){if(S!==""&&Nt===null){po(-1);return}let i=vr.current;if(!i.length)return;let f=Nt===null?i.length-1:Math.max(0,Nt-1);Kn(f),v(i[f]??"");return}if(l.downArrow){if(S!==""&&Nt===null){po(1);return}let i=vr.current;if(Nt===null)return;let f=Nt+1;f>=i.length?(Kn(null),v("")):(Kn(f),v(i[f]??""));return}}if(l.return){uo();return}if(l.backspace||l.delete){R();return}if(l.escape){v(""),Et(0),Ue(),ut([]),un(null),Vn.current=!0;return}c&&!l.ctrl&&!l.meta&&pa(c)}}}),De(()=>{if(N||L)return;let c=bt.current.shift();c!==void 0&&(Rr([...bt.current]),uo(c))},[N,L,uo]),V(re,{flexDirection:"column",width:je,children:[Nr!==null&&V(re,{marginTop:1,flexDirection:"column",children:[Nr.truncated&&A(D,{dimColor:!0,children:"\u2026"}),A(D,{children:Nr.text})]}),N&&(Jn?A(Xw,{p:Jn}):A(Yw,{startTime:pt.current,chars:fu})),!N&&Qi?A(zw,{text:Qi}):null,A(re,{borderStyle:"round",borderColor:ra.prod?"yellow":q,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:S?ha.map((c,l)=>{let i=k.text.slice(c.start,c.end),f=l===mr(ha,k.pos),d=Math.min(k.pos,c.end)-c.start;return V(D,{children:[A(D,{color:q,children:l===0?"> ":" "}),f?V(Bn,{children:[i.slice(0,d),A(an,{ch:i[d]??" "}),i.slice(d+1)]}):i||" "]},`${l}-${c.start}`)}):V(D,{children:[A(D,{color:q,children:"> "}),Sr?A(an,{ch:" "}):fe&&!N&&xe?V(Bn,{children:[A(an,{ch:xe[0],dim:!0}),A(D,{color:"gray",children:xe.slice(1)})]}):fe&&!N?V(Bn,{children:[A(an,{ch:fe[0],dim:!0}),A(D,{color:"gray",children:fe.slice(1)}),A(D,{dimColor:!0,children:" (tab)"})]}):(Er.isSetup||!pu)&&!N?V(Bn,{children:[A(an,{ch:Er.text[0],dim:!0}),A(D,{color:"gray",children:Er.text.slice(1)})]}):A(an,{ch:" "})]})}),Xi.length>0&&A(re,{flexDirection:"column",paddingX:1,children:Xi.map((c,l)=>A(D,{color:"gray",children:`\u29D7 queued: ${c}`},`${l}-${c.slice(0,24)}`))}),eo?A(xd,{tab:eo.tab,width:je,version:o,engineVersion:ou}):ft?V(re,{flexDirection:"column",paddingX:1,children:[A(D,{color:q,bold:!0,children:"Select model"}),A(D,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),Fe.map((c,l)=>V(D,{color:l===ft.cursor?q:void 0,children:[l===ft.cursor?"\u276F ":" ",`${l+1}. ${c.label}${l===ft.current?" \u2714":""}`.padEnd(16),A(D,{color:"gray",children:c.desc})]},c.label)),A(D,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Be?V(re,{flexDirection:"column",paddingX:1,children:[A(D,{color:q,bold:!0,children:"Switch connection profile"}),Be.rows.map((c,l)=>V(D,{color:l===Be.cursor?q:void 0,children:[l===Be.cursor?"\u276F ":" ",`${l+1}. ${c.name}${l===Be.current?" \u2714":""}`.padEnd(20),A(D,{color:"gray",children:`${c.env} \xB7 ${c.who??"not signed in"}`}),c.prod?A(D,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},c.name)),A(D,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Ve?V(re,{flexDirection:"column",paddingX:1,children:[A(D,{color:q,bold:!0,children:"Pick your Document360 environment"}),Ve.rows.map((c,l)=>V(D,{color:l===Ve.cursor?q:void 0,children:[l===Ve.cursor?"\u276F ":" ",`${l+1}. ${c.name}`.padEnd(16),A(D,{color:"gray",children:c.apiUrl})]},c.name)),A(D,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):me?V(re,{flexDirection:"column",paddingX:1,children:[A(D,{color:q,bold:!0,children:"Switch workspace"}),A(D,{dimColor:!0,children:`environment ${me.environment} \xB7 project ${me.projectName??`${me.projectId.slice(0,8)}\u2026`}`}),me.rows.map((c,l)=>V(D,{color:l===me.cursor?q:void 0,children:[l===me.cursor?"\u276F ":" ",`${l+1}. ${c.name}${l===me.current?" \u2714":""}`.padEnd(30),A(D,{color:"gray",children:c.type??""})]},c.id)),A(D,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):ve?V(re,{flexDirection:"column",paddingX:1,children:[A(D,{color:q,bold:!0,children:"Choose project"}),A(D,{dimColor:!0,children:`environment ${ve.environment}`}),ve.rows.map((c,l)=>V(D,{color:l===ve.cursor?q:void 0,children:[l===ve.cursor?"\u276F ":" ",`${l+1}. ${c.name}${l===ve.current?" \u2714":""}`.padEnd(30),A(D,{color:"gray",children:c.sub??""})]},c.id)),A(D,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):we?(()=>{let l=Math.min(Math.max(0,we.cursor-Math.floor(7)),Math.max(0,we.rows.length-14)),i=we.rows.slice(l,l+14),f=we.rows.filter(d=>d.checked).length;return V(re,{flexDirection:"column",paddingX:1,children:[A(D,{color:q,bold:!0,children:`Which folders back the user docs? (${f} selected of ${we.rows.length})`}),l>0?A(D,{dimColor:!0,children:` \u2191 ${l} more`}):null,i.map((d,w)=>{let $=l+w;return V(D,{color:$===we.cursor?q:void 0,children:[$===we.cursor?"\u276F ":" ",d.checked?"\u25C9 ":"\u25CB ",d.path.padEnd(Math.min(48,je-34)),A(D,{color:"gray",children:Mo(d)})]},d.path)}),l+14<we.rows.length?A(D,{dimColor:!0,children:` \u2193 ${we.rows.length-l-14} more`}):null,A(D,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():Ge?V(re,{flexDirection:"column",paddingX:1,children:[A(D,{color:q,bold:!0,children:"Which category? (pick one to scope to)"}),Ge.rows.map((c,l)=>{let i=l===Ge.cursor,f=`${l+1}.`.padEnd(3);return V(D,{color:i?q:void 0,children:[i?"\u276F ":" ",`${f} ${c.label} (${c.count})`.padEnd(Math.min(44,Math.max(20,je-24))),A(D,{color:"gray",children:` ${c.token}`})]},c.token)}),A(D,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):Qe?V(re,{flexDirection:"column",paddingX:1,children:[A(D,{color:q,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),Qe.rows.map((c,l)=>{let i=l===Qe.cursor,f=c.indent?" ":" ",d=`${l+1}.`.padEnd(3);return V(D,{color:i?q:void 0,bold:c.kind==="category"&&!i,children:[i?"\u276F ":" ",`${f}${d} ${c.label}`.padEnd(Math.min(56,je-24)),c.note?A(D,{color:"gray",children:c.note}):null]},`${c.kind}:${c.paths.join(",")}`)}),A(D,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):Je?V(re,{flexDirection:"column",paddingX:1,children:[A(D,{color:q,bold:!0,children:Je.title}),(()=>{let{rows:l,cursor:i}=Je,f=Math.max(0,Math.min(i-Math.floor(12/2),l.length-12)),d=l.slice(f,f+12);return V(Bn,{children:[f>0?A(D,{color:"gray",children:` \u2026 ${f} more above`}):null,d.map((w,$)=>{let h=f+$,x=h===i,b=w.indent?" ":" ",U=h<9?`${h+1}.`.padEnd(3):" ";return V(D,{color:x?q:void 0,bold:w.kind!=="shot"&&!x,children:[x?"\u276F ":" ",`${b}${U} ${w.label}`.padEnd(Math.min(56,je-24)),w.note?A(D,{color:"gray",children:w.note}):null]},`${w.kind}:${w.ids.join(",")}`)}),f+12<l.length?A(D,{color:"gray",children:` \u2026 ${l.length-f-12} more below`}):null]})})(),A(D,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter run \xB7 esc cancel"})]}):Ce?V(re,{flexDirection:"column",paddingX:1,children:[A(D,{color:q,bold:!0,children:`Preview article${Ce.query?` \u2014 filter: ${Ce.query}`:" (type to filter)"}`}),so.length===0?A(D,{color:"gray",children:"no articles match"}):so.map((c,l)=>V(D,{color:l===Ce.cursor?q:void 0,children:[l===Ce.cursor?"\u276F ":" ",c]},c)),A(D,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):Re?V(re,{flexDirection:"column",paddingX:1,children:[A(D,{color:q,bold:!0,children:`Resume session${Re.query?` \u2014 filter: ${Re.query}`:" (type to filter)"}`}),io.length===0?A(D,{color:"gray",children:"no sessions match"}):io.map((c,l)=>V(D,{color:l===Re.cursor?q:void 0,children:[l===Re.cursor?"\u276F ":" ",c.name.slice(0,28).padEnd(30),A(D,{color:l===Re.cursor?q:"gray",children:c.firstPrompt.slice(0,Math.max(10,je-40))})]},c.uuid)),A(D,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):sa?V(re,{flexDirection:"column",children:[kn.map((c,l)=>V(D,{color:l===dn?q:void 0,children:[l===dn?"\u276F ":" ",c.usage.padEnd(22)," ",A(D,{color:l===dn?q:"gray",children:c.name==="model"&&Pr?`${c.desc} (currently ${Pr})`:c.desc})]},c.name)),A(D,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!N&&!S&&He.length>0?V(re,{flexDirection:"column",paddingX:1,children:[Ki?A(D,{color:q,children:Ki}):null,He.map((c,l)=>{let i=Tt(c),f=i.slice(0,Math.max(20,je-5)),d=je-f.length-7,w=d>=12?(Pd(c)??rl(i)).slice(0,d):"";return V(D,{children:[A(D,{color:q,children:l+1})," ",f,w?A(D,{dimColor:!0,children:` \u2014 ${w}`}):null]},i)}),A(D,{dimColor:!0,children:`press 1-${He.length} to fill \xB7 esc cancel`})]}):A(re,{paddingX:1,children:V(D,{color:"gray",children:[ra.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${Pr??"model n/a"}${t.kind==="api"?ea>0?` \xB7 ${$e(ea)}`:"":Zi>0?` \xB7 ${it(Zi)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}W();import{jsx as ey}from"react/jsx-runtime";async function iu(e=process.cwd(),t="auto",n,o="0.0.0"){let r=Zw(t);r.kind==="none"&&(console.error(""),console.error(C("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${_("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${_("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=Jw(ey(su,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
|
|
419
|
-
`),process.exit(0)}
|
|
415
|
+
`)}),Bt(vt()),wn.current=Ie(e).status==="current",Vt.current=ze(e);return}case"discover":{if(!oe(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await ne(hs(),{display:"/discover",quietUser:!0});return}case"inbox":{if(!oe(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(ti(e)===0){u({kind:"note",tone:"info",text:"Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)"});return}await ne(ni(),{display:"/inbox",quietUser:!0});return}case"feedback":{let d=Xd(e),w="";try{w=sn(d)?yr(d,"utf8"):""}catch{w=""}if(!/^## /m.test(w)){u({kind:"note",tone:"info",text:"No open d360-writer feedback to copy \u2014 nothing logged in .d360-writer/tool-feedback.md yet."});return}let b=await Ti(w.trim());u({kind:"note",tone:b?"ok":"warn",text:b?"\u2713 Copied the d360-writer feedback to your clipboard \u2014 send it to the team (Teams / Slack / email).":`Couldn\u2019t reach your clipboard \u2014 open ${d} and copy it manually.`}),b&&Nr(null);return}case"document":{if(!oe(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:d,what:w}=Fs(f);if(!w&&Ws(e)===0){u({kind:"note",tone:"info",text:qs});return}let b=`/document${w?` ${w}`:""}${d?" --publish":""}`;await ne(Hs(w,d),{display:b,quietUser:!0});return}case"catch-up":{if(!oe(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!no(c.trim()))return;let{publish:d}=ri(f);u({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let w=await ii({cwd:e,profileName:s});for(let h of ai(w))u({kind:"note",tone:h.startsWith("\u2713")?"ok":h.startsWith("\u2139")?"info":"warn",text:h});let b=On(Ln(e));u({kind:"note",tone:"info",text:b?`Catching up on ${b}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"}),await ne(si({publish:d}),{display:`/catch-up${d?" --publish":""}`,quietUser:!0});return}case"update":{jr.current=!0,u({kind:"note",tone:"info",text:`Updating ${Pt}\u2026 (don\u2019t close this window)`}),zn(!0),(await Xo().finally(()=>zn(!1))).ok?(u({kind:"note",tone:"ok",text:"\u2713 Updated \u2014 run /exit, then relaunch to apply."}),X("/exit"),Gi("")):u({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${Ko}`});return}case"screenshot":{let d=Ks(f);if(d.mode==="list"){if(!oe(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let h=St(e,d.scope);if(d.picker){if(h.length===0){u({kind:"note",tone:"info",text:"No screenshot placeholders found in the docs."});return}let x=vc(h);if(x.length===0){u({kind:"note",tone:"info",text:Vo(h,d.scope).join(`
|
|
416
|
+
`)}),ke(`\u2713 All ${h.length} screenshots are captured. /publish puts them in the articles; /capture re-captures.`,{kind:"cmd",cmd:"/publish",reason:""});return}wt({cursor:0,rows:x,title:"Screenshots \u2014 pick what to author or capture:"});return}u({kind:"note",tone:"info",text:Vo(h,d.scope).join(`
|
|
417
|
+
`)});let $=h.filter(x=>x.state==="placeholder").length;if($>0){let x=d.scope?`/screenshot ${d.scope}`:"/screenshot --all";ke(`${$} of ${h.length} still need${$===1?"s":""} a spec \u2014 /screenshot <id> authors one, ${x} authors them all in parallel.`,{kind:"cmd",cmd:x,reason:""})}return}if(d.mode==="single"){await ca(d.id);return}if(!oe(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let w=d.mode==="scope"?d.scope:void 0,b=Aw(e,{scope:w}).map(h=>h.id);if(b.length===0){u({kind:"note",tone:"info",text:w?`No screenshot placeholders under ${w}.`:"No screenshot placeholders found in the docs."});return}await la(b,{setup:d.setup,runLine:d.mode==="scope"?`/screenshot ${d.scope}`:"/screenshot --all"});return}case"capture":{let d=Xs(f);if(!Yo(e)){u({kind:"note",tone:"warn",text:"Screenshot capture is not set up in this repo yet \u2014 run d360-capture init in this repo's terminal, then d360-capture auth (once per machine)."});return}if(d.mode==="single"){await Or([d.id],{runLine:`/capture ${d.id}`});return}if(d.mode==="all"||d.mode==="scope"){let{ready:b,captured:h}=Qs(e,d.mode==="scope"?d.scope:void 0),$=[...b,...h];if($.length===0){u({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),X("/screenshot");return}await Or($,{runLine:d.mode==="scope"?`/capture ${d.scope}`:"/capture --all"});return}let w=Pc(St(e));if(w.length===0){u({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),X("/screenshot");return}wt({cursor:0,rows:w,title:"Capture screenshots \u2014 pick what to shoot:"});return}case"reset":{let d=di(e);if(d.length===0){u({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}Qn.current={repoName:qn(e),targets:d,hadDevhints:sn(Kd(e))},u({kind:"note",tone:"warn",text:pi(e,d).join(`
|
|
418
|
+
`)}),ge(qn(e));return}default:u({kind:"note",tone:"error",text:`Unknown command: /${i} \u2014 type /help.`})}},[e,r,s,Yt,Fr,u,Se,ne,Gt,Lr,da]),uo=B(c=>{let l=(c??S).trim();if(v(""),Kn(null),Et(0),l.startsWith("/")&&(Vn.current=!1,Ue(),un(null),ut(f=>Ad(f,l))),!l||(Vi(!1),pa(l))||ua(l))return;Rr.current.push(l);let i=Id(l,Yi.current);if(l.startsWith("/"))u({kind:"user",text:l}),Xe(!0),bn(i).finally(()=>Xe(!1));else if(Ww(i)){u({kind:"user",text:l});let f=Fw(i);if(!f)ne(i,{display:l,quietUser:!0});else{try{Hw(e,{title:f,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}ne(`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=Zc(e,i);ne(f??i,{display:l})}},[S,pa,ua,bn,ne]),ha=B(c=>{if(c.length>1){if(c.includes("\x1B"))return;let l=jd(c);if(Ed(l)){let i=Nd(++wu.current,l);Yi.current.set(i,l),_(i)}else _(l);return}_(c)},[_]),zt=Math.max(10,je-6),fa=Ni(()=>gr(k.text,zt),[k.text,zt]),Hr=B(c=>y(l=>({...l,pos:Math.max(0,Math.min(l.text.length,l.pos+c))})),[]),po=B(c=>y(l=>({...l,pos:Ld(gr(l.text,zt),l.pos,c)})),[zt]),$n=B(c=>y(l=>({...l,pos:Od(gr(l.text,zt),l.pos,c)})),[zt]),$u=["\x1B[H","\x1B[1~","\x1BOH"],xu=["\x1B[F","\x1B[4~","\x1BOF"],ma=B((c,l)=>l.leftArrow?(Hr(-1),!0):l.rightArrow?(Hr(1),!0):c&&$u.includes(c)?($n("start"),!0):c&&xu.includes(c)?($n("end"),!0):l.ctrl&&c==="a"?($n("start"),!0):l.ctrl&&c==="e"?($n("end"),!0):!1,[Hr,$n]);return tw((c,l)=>{if(l.ctrl&&c==="c"){Ae.current?.close(),r();return}if(!U){if(E){if(l.escape){if(ye.current){if(!ye.current.signal.aborted){let i=(Jn?.verb??"work").toLowerCase(),f=Jn?.unit??"article";u({kind:"note",tone:"warn",text:`\u238B Stopping the ${i} run (finishing in-flight ${f}s)\u2026`}),ye.current.abort()}return}pn.current||(pn.current=!0,u({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),Ae.current?.interrupt());return}if(l.return){let i=S.trim();if(!i)return;bt.current.push(i),Pr([...bt.current]),v("");return}if(ma(c,l))return;if(l.upArrow){po(-1);return}if(l.downArrow){po(1);return}if(l.backspace||l.delete){R();return}c&&!l.ctrl&&!l.meta&&ha(c);return}if(ft){if(l.upArrow){mt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){mt(i=>i&&{...i,cursor:Math.min(Fe.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Fe.length){mt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Fe[ft.cursor];mt(null);let{lines:f,changed:d,effective:w}=Nn(e,i.value??"default");for(let b of f)u({kind:"note",tone:b.startsWith("\u26A0")?"warn":b.startsWith("\u2713")?"ok":"info",text:b});d&&(ta(b=>b+1),Ae.current?.setModel(w));return}if(c==="s"){let i=Fe[ft.cursor];mt(null),Ae.current?.setModel(i.value??void 0),u({kind:"note",tone:"ok",text:`\u2713 Using ${i.label} for this session only (your saved default is unchanged).`});return}if(l.escape){mt(null);return}return}if(Be){if(l.upArrow){Ot(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Ot(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Be.rows.length){Ot(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return||c==="s"){let i=Be.rows[Be.cursor];Ot(null),Ur(i.name,l.return===!0);return}if(l.escape){Ot(null);return}return}if(eo){if(l.escape){mn(null);return}if(l.leftArrow||l.tab&&l.shift){mn(i=>i&&{tab:(i.tab-1+Ne.length)%Ne.length});return}if(l.rightArrow||l.tab){mn(i=>i&&{tab:(i.tab+1)%Ne.length});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ne.length){mn({tab:Number(c)-1});return}return}if(Ve){if(l.upArrow){Mt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Mt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ve.rows.length){Mt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Ve.rows[Ve.cursor].name;if(Mt(null),!Qr(e,i).created){u({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}u({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${i}").`});let d=!1;try{let w=Dt(i);d=!!w&&!(ct(w)&&!w.refreshToken)}catch{d=!1}u({kind:"note",tone:"info",text:d?`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.`}),X("/login"),z(w=>w+1);return}if(l.escape){Mt(null);return}return}if(me){if(l.upArrow){Ut(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Ut(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=me.rows.length){Ut(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=me.rows[me.cursor],{profile:f,projectId:d}=me;Ut(null),ao(f,d,i);return}if(l.escape){Ut(null);return}return}if(ve){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)<=ve.rows.length){gt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=ve.rows[ve.cursor],{profile:f}=ve;gt(null),co(f,i);return}if(l.escape){gt(null);return}return}if(we){if(l.upArrow){Ft(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Ft(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c===" "){Ft(i=>i&&{...i,rows:i.rows.map((f,d)=>d===i.cursor?{...f,checked:!f.checked}:f)});return}if(l.return){let i=we.rows.filter(f=>f.checked).map(f=>f.path);if(Ft(null),i.length===0){u({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}fs(e,i),u({kind:"note",tone:"ok",text:`\u2713 Scoped to ${i.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let f of i)u({kind:"note",tone:"info",text:` ${f}`});u({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(l.escape){Ft(null);return}return}if(Ge){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)<=Ge.rows.length){yt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Ge.rows[Ge.cursor],f=Ge.run;yt(null),f(i.token);return}if(l.escape){yt(null);return}return}if(Qe){if(l.upArrow){Wt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Wt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Qe.rows.length){Wt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Qe.rows[Qe.cursor];Wt(null),i.conflict?Fr(i.paths[0]):i.kind==="article"?Lr(i.paths[0]):Gt(i.paths);return}if(l.escape){Wt(null);return}return}if(Je){if(l.upArrow){wt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){wt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Je.rows.length){wt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Je.rows[Je.cursor];wt(null),i.action==="capture"?Or(i.ids,{runLine:i.kind==="all"?"/capture --all":void 0}):i.kind==="shot"?ca(i.ids[0]):la(i.ids,{setup:!0,runLine:i.kind==="all"?"/screenshot --all":void 0});return}if(l.escape){wt(null);return}return}if(Ce){if(l.escape){kt(null);return}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(Math.max(0,so.length-1),i.cursor+1)});return}if(l.return){let i=so[Ce.cursor];if(i){kt(null);try{u({kind:"preview",name:qn(i),text:ru(yr(Ii(e,i),"utf8"))})}catch(f){u({kind:"note",tone:"error",text:`Could not read ${i}: ${f.message}`})}}return}if(l.backspace||l.delete){kt(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(c&&!l.ctrl&&!l.meta&&c.length===1){kt(i=>i&&{...i,query:i.query+c,cursor:0});return}return}if(Re){if(l.escape){$t(null);return}if(l.upArrow){$t(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){$t(i=>i&&{...i,cursor:Math.min(Math.max(0,io.length-1),i.cursor+1)});return}if(l.return){let i=io[Re.cursor];if(i){$t(null),Se(i.uuid),qe.current={uuid:i.uuid,firstPrompt:i.firstPrompt,titleFired:!0},ht(i.name),_i(i.uuid),It.current=[];let f=Ai(e,i.uuid);for(let d of f)u(d);u({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){$t(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(c&&!l.ctrl&&!l.meta&&c.length===1){$t(i=>i&&{...i,query:i.query+c,cursor:0});return}return}if(l.tab&&!S&&fe){v(fe),Ue();return}if(!S&&He.length>0&&!vr&&c&&/^[1-9]$/.test(c)){let i=He[Number(c)-1];if(i){v(Tt(i));return}}if(!S&&(oo||gn)&&c==="c"&&!l.ctrl&&!l.meta&&!l.return&&!l.tab){let i=oo!=null;Ti(oo??gn).then(d=>{u({kind:"note",tone:d?"ok":"warn",text:d?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."}),d&&i&&Nr(null),d&&!i&&oa(!0)});return}if(!ma(c,l)){if(sa){if(l.upArrow){Et(i=>Math.max(0,i-1));return}if(l.downArrow){Et(i=>Math.min(kn.length-1,i+1));return}if(l.tab){v("/"+(kn[dn]?.name??"")+" "),Et(0);return}if(l.return){let i=kn[dn];if(i){let f=S.trim().slice(1).split(/\s+/).slice(1).join(" ");if(al(i.usage)&&!f){v("/"+i.name+" "),Et(0);return}uo("/"+i.name+(f?" "+f:""));return}}}else{if(l.upArrow){if(S!==""&&Nt===null){po(-1);return}let i=Rr.current;if(!i.length)return;let f=Nt===null?i.length-1:Math.max(0,Nt-1);Kn(f),v(i[f]??"");return}if(l.downArrow){if(S!==""&&Nt===null){po(1);return}let i=Rr.current;if(Nt===null)return;let f=Nt+1;f>=i.length?(Kn(null),v("")):(Kn(f),v(i[f]??""));return}}if(l.return){uo();return}if(l.backspace||l.delete){R();return}if(l.escape){v(""),Et(0),Ue(),ut([]),un(null),Vn.current=!0;return}c&&!l.ctrl&&!l.meta&&ha(c)}}}),De(()=>{if(E||U)return;let c=bt.current.shift();c!==void 0&&(Pr([...bt.current]),uo(c))},[E,U,uo]),V(re,{flexDirection:"column",width:je,children:[_r!==null&&V(re,{marginTop:1,flexDirection:"column",children:[_r.truncated&&A(D,{dimColor:!0,children:"\u2026"}),A(D,{children:_r.text})]}),E&&(Jn?A(Jw,{p:Jn}):A(Kw,{startTime:pt.current,chars:gu})),!E&&Qi?A(Xw,{text:Qi}):null,A(re,{borderStyle:"round",borderColor:ra.prod?"yellow":q,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:S?fa.map((c,l)=>{let i=k.text.slice(c.start,c.end),f=l===wr(fa,k.pos),d=Math.min(k.pos,c.end)-c.start;return V(D,{children:[A(D,{color:q,children:l===0?"> ":" "}),f?V(Bn,{children:[i.slice(0,d),A(an,{ch:i[d]??" "}),i.slice(d+1)]}):i||" "]},`${l}-${c.start}`)}):V(D,{children:[A(D,{color:q,children:"> "}),Tr?A(an,{ch:" "}):fe&&!E&&xe?V(Bn,{children:[A(an,{ch:xe[0],dim:!0}),A(D,{color:"gray",children:xe.slice(1)})]}):fe&&!E?V(Bn,{children:[A(an,{ch:fe[0],dim:!0}),A(D,{color:"gray",children:fe.slice(1)}),A(D,{dimColor:!0,children:" (tab)"})]}):(Ir.isSetup||!fu)&&!E?V(Bn,{children:[A(an,{ch:Ir.text[0],dim:!0}),A(D,{color:"gray",children:Ir.text.slice(1)})]}):A(an,{ch:" "})]})}),Xi.length>0&&A(re,{flexDirection:"column",paddingX:1,children:Xi.map((c,l)=>A(D,{color:"gray",children:`\u29D7 queued: ${c}`},`${l}-${c.slice(0,24)}`))}),eo?A(Cd,{tab:eo.tab,width:je,version:o,engineVersion:su}):ft?V(re,{flexDirection:"column",paddingX:1,children:[A(D,{color:q,bold:!0,children:"Select model"}),A(D,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),Fe.map((c,l)=>V(D,{color:l===ft.cursor?q:void 0,children:[l===ft.cursor?"\u276F ":" ",`${l+1}. ${c.label}${l===ft.current?" \u2714":""}`.padEnd(16),A(D,{color:"gray",children:c.desc})]},c.label)),A(D,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Be?V(re,{flexDirection:"column",paddingX:1,children:[A(D,{color:q,bold:!0,children:"Switch connection profile"}),Be.rows.map((c,l)=>V(D,{color:l===Be.cursor?q:void 0,children:[l===Be.cursor?"\u276F ":" ",`${l+1}. ${c.name}${l===Be.current?" \u2714":""}`.padEnd(20),A(D,{color:"gray",children:`${c.env} \xB7 ${c.who??"not signed in"}`}),c.prod?A(D,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},c.name)),A(D,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Ve?V(re,{flexDirection:"column",paddingX:1,children:[A(D,{color:q,bold:!0,children:"Pick your Document360 environment"}),Ve.rows.map((c,l)=>V(D,{color:l===Ve.cursor?q:void 0,children:[l===Ve.cursor?"\u276F ":" ",`${l+1}. ${c.name}`.padEnd(16),A(D,{color:"gray",children:c.apiUrl})]},c.name)),A(D,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):me?V(re,{flexDirection:"column",paddingX:1,children:[A(D,{color:q,bold:!0,children:"Switch workspace"}),A(D,{dimColor:!0,children:`environment ${me.environment} \xB7 project ${me.projectName??`${me.projectId.slice(0,8)}\u2026`}`}),me.rows.map((c,l)=>V(D,{color:l===me.cursor?q:void 0,children:[l===me.cursor?"\u276F ":" ",`${l+1}. ${c.name}${l===me.current?" \u2714":""}`.padEnd(30),A(D,{color:"gray",children:c.type??""})]},c.id)),A(D,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):ve?V(re,{flexDirection:"column",paddingX:1,children:[A(D,{color:q,bold:!0,children:"Choose project"}),A(D,{dimColor:!0,children:`environment ${ve.environment}`}),ve.rows.map((c,l)=>V(D,{color:l===ve.cursor?q:void 0,children:[l===ve.cursor?"\u276F ":" ",`${l+1}. ${c.name}${l===ve.current?" \u2714":""}`.padEnd(30),A(D,{color:"gray",children:c.sub??""})]},c.id)),A(D,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):we?(()=>{let l=Math.min(Math.max(0,we.cursor-Math.floor(7)),Math.max(0,we.rows.length-14)),i=we.rows.slice(l,l+14),f=we.rows.filter(d=>d.checked).length;return V(re,{flexDirection:"column",paddingX:1,children:[A(D,{color:q,bold:!0,children:`Which folders back the user docs? (${f} selected of ${we.rows.length})`}),l>0?A(D,{dimColor:!0,children:` \u2191 ${l} more`}):null,i.map((d,w)=>{let b=l+w;return V(D,{color:b===we.cursor?q:void 0,children:[b===we.cursor?"\u276F ":" ",d.checked?"\u25C9 ":"\u25CB ",d.path.padEnd(Math.min(48,je-34)),A(D,{color:"gray",children:Mo(d)})]},d.path)}),l+14<we.rows.length?A(D,{dimColor:!0,children:` \u2193 ${we.rows.length-l-14} more`}):null,A(D,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():Ge?V(re,{flexDirection:"column",paddingX:1,children:[A(D,{color:q,bold:!0,children:"Which category? (pick one to scope to)"}),Ge.rows.map((c,l)=>{let i=l===Ge.cursor,f=`${l+1}.`.padEnd(3);return V(D,{color:i?q:void 0,children:[i?"\u276F ":" ",`${f} ${c.label} (${c.count})`.padEnd(Math.min(44,Math.max(20,je-24))),A(D,{color:"gray",children:` ${c.token}`})]},c.token)}),A(D,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):Qe?V(re,{flexDirection:"column",paddingX:1,children:[A(D,{color:q,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),Qe.rows.map((c,l)=>{let i=l===Qe.cursor,f=c.indent?" ":" ",d=`${l+1}.`.padEnd(3);return V(D,{color:i?q:void 0,bold:c.kind==="category"&&!i,children:[i?"\u276F ":" ",`${f}${d} ${c.label}`.padEnd(Math.min(56,je-24)),c.note?A(D,{color:"gray",children:c.note}):null]},`${c.kind}:${c.paths.join(",")}`)}),A(D,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):Je?V(re,{flexDirection:"column",paddingX:1,children:[A(D,{color:q,bold:!0,children:Je.title}),(()=>{let{rows:l,cursor:i}=Je,f=Math.max(0,Math.min(i-Math.floor(12/2),l.length-12)),d=l.slice(f,f+12);return V(Bn,{children:[f>0?A(D,{color:"gray",children:` \u2026 ${f} more above`}):null,d.map((w,b)=>{let h=f+b,$=h===i,x=w.indent?" ":" ",N=h<9?`${h+1}.`.padEnd(3):" ";return V(D,{color:$?q:void 0,bold:w.kind!=="shot"&&!$,children:[$?"\u276F ":" ",`${x}${N} ${w.label}`.padEnd(Math.min(56,je-24)),w.note?A(D,{color:"gray",children:w.note}):null]},`${w.kind}:${w.ids.join(",")}`)}),f+12<l.length?A(D,{color:"gray",children:` \u2026 ${l.length-f-12} more below`}):null]})})(),A(D,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter run \xB7 esc cancel"})]}):Ce?V(re,{flexDirection:"column",paddingX:1,children:[A(D,{color:q,bold:!0,children:`Preview article${Ce.query?` \u2014 filter: ${Ce.query}`:" (type to filter)"}`}),so.length===0?A(D,{color:"gray",children:"no articles match"}):so.map((c,l)=>V(D,{color:l===Ce.cursor?q:void 0,children:[l===Ce.cursor?"\u276F ":" ",c]},c)),A(D,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):Re?V(re,{flexDirection:"column",paddingX:1,children:[A(D,{color:q,bold:!0,children:`Resume session${Re.query?` \u2014 filter: ${Re.query}`:" (type to filter)"}`}),io.length===0?A(D,{color:"gray",children:"no sessions match"}):io.map((c,l)=>V(D,{color:l===Re.cursor?q:void 0,children:[l===Re.cursor?"\u276F ":" ",c.name.slice(0,28).padEnd(30),A(D,{color:l===Re.cursor?q:"gray",children:c.firstPrompt.slice(0,Math.max(10,je-40))})]},c.uuid)),A(D,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):sa?V(re,{flexDirection:"column",children:[kn.map((c,l)=>V(D,{color:l===dn?q:void 0,children:[l===dn?"\u276F ":" ",c.usage.padEnd(22)," ",A(D,{color:l===dn?q:"gray",children:c.name==="model"&&Dr?`${c.desc} (currently ${Dr})`:c.desc})]},c.name)),A(D,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!E&&!S&&He.length>0?V(re,{flexDirection:"column",paddingX:1,children:[Ki?A(D,{color:q,children:Ki}):null,He.map((c,l)=>{let i=Tt(c),f=i.slice(0,Math.max(20,je-5)),d=je-f.length-7,w=d>=12?(Dd(c)??sl(i)).slice(0,d):"";return V(D,{children:[A(D,{color:q,children:l+1})," ",f,w?A(D,{dimColor:!0,children:` \u2014 ${w}`}):null]},i)}),A(D,{dimColor:!0,children:`press 1-${He.length} to fill \xB7 esc cancel`})]}):A(re,{paddingX:1,children:V(D,{color:"gray",children:[ra.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${Dr??"model n/a"}${t.kind==="api"?ea>0?` \xB7 ${$e(ea)}`:"":Zi>0?` \xB7 ${it(Zi)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}F();import{jsx as ny}from"react/jsx-runtime";async function lu(e=process.cwd(),t="auto",n,o="0.0.0"){let r=ty(t);r.kind==="none"&&(console.error(""),console.error(C("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${L("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${L("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=ey(ny(au,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
|
|
419
|
+
`),process.exit(0)}F();import{writeCrashLog as cu,isBenignTransportError as oy}from"document360-engine";var du=!1;function Hi(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function uu(e){if(du)return;du=!0;let t=(n,o)=>{if(oy(o)){cu({kind:n,level:"transport",message:Hi(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=cu({kind:n,level:"fatal",message:Hi(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
|
|
420
420
|
`+C(`\u2717 d360-writer crashed: ${Hi(o)}`)+`
|
|
421
421
|
`),r&&process.stderr.write(m(` Crash details: ${r}`)+`
|
|
422
422
|
`+m(" Run: d360-writer logs")+`
|
|
423
|
-
`),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var sy
|
|
423
|
+
`),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var ay=sy(import.meta.url),$r=ay("../package.json");uu("d360-writer");var Oe=new ry;function qi(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}Oe.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=>{qi(e),await $o({profile:e.profile,manual:e.manual})});Oe.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{qi(e),await Pa({profile:e.profile})});Oe.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{qi(e),await Sa({profile:e.profile})});var Bi=Oe.command("profile").description("Manage connection profiles for the current repo");Bi.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>xo(process.cwd()));Bi.command("use <name>").description("Set the default profile for this repo").action(e=>vo(process.cwd(),e));Bi.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>Co(process.cwd(),e));var pu=Oe.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");pu.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>Kt(process.cwd(),e.profile));pu.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await ka(process.cwd(),e,t.profile)});var hu=Oe.command("project").description("Choose the Document360 project for this repo (active profile's identity)");hu.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>yo(process.cwd(),e.profile));hu.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await $a(process.cwd(),e,t.profile)});Oe.command("init").description("Scaffold .d360-writer/config.json for this repo (interactive)").action(async()=>{let{initCommand:e}=await Promise.resolve().then(()=>(Ao(),nl));await e()});Oe.command("logs").description("Show the API + crash log files (send these to support when reporting a problem)").action(()=>ja());Oe.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(()=>(Bo(),dc)),n=await t(process.cwd(),$r.version);for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});Oe.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version($r.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(iy.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 Ea(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 gd(e.cwd,e.auth,e.profile,$r.version):await lu(e.cwd,e.auth,e.profile,$r.version)});Oe.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
|