document360-writer 0.5.37 → 0.5.39
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 +79 -77
- package/dist/commands/lint.d.ts +6 -0
- package/dist/commands/write.d.ts +7 -2
- package/package.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var Kl=Object.defineProperty;var qo=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var Xl=(e,t)=>{for(var n in t)Kl(e,n,{get:t[n],enumerable:!0})};import He from"picocolors";var F,Jl,Ql,Zl,Bs,Gt,f,v,M,A,N,re,ve,W=qo(()=>{"use strict";F="#7f56d9",[Jl,Ql,Zl]=[127,86,217],Bs=e=>He.isColorSupported?`\x1B[38;2;${Jl};${Ql};${Zl}m${e}\x1B[39m`:e,Gt=e=>He.bold(Bs(e)),f=e=>He.dim(e),v=e=>He.red(e),M=e=>He.yellow(e),A=e=>He.green(e),N=Bs,re=e=>He.gray(e),ve=e=>He.bold(e)});import{existsSync as Nn,writeFileSync as Kt,readFileSync as Oc,readdirSync as Lc}from"node:fs";import{join as Uc}from"node:path";import{devHintsGuidePath as _n,hintsDir as ci,architectureDir as pi,messagesDir as Ko,creatorNotesPath as ui,devhintsStatePath as fi,ensureDir as In,writeMessage as Wc,listOpenForDev as Fc}from"document360-engine";function mi(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
|
|
3
3
|
|
|
4
4
|
<!-- devhints script v${oe} \xB7 maintained by document360-writer (/devhints). -->
|
|
5
5
|
|
|
@@ -159,7 +159,7 @@ whenever \`git status\` shows changes under \`.d360-writer/\`, commit them (e.g.
|
|
|
159
159
|
\`git add .d360-writer && git commit -m "docs: sync d360-writer output"\`) before you push. The docs agent
|
|
160
160
|
will remind you when it leaves changes, but it's your call to commit them. Without this, the team's docs
|
|
161
161
|
and \u2014 critically \u2014 the sync map are stranded on one machine.
|
|
162
|
-
`}function
|
|
162
|
+
`}function Hc(){return`# Creator notes (optional \u2014 for the docs agent and the builder)
|
|
163
163
|
|
|
164
164
|
<!-- The ORIGINAL CREATOR's context. Most repos leave this empty \u2014 that's fine.
|
|
165
165
|
The builder agent reads this FIRST and treats it as authoritative when writing the architecture
|
|
@@ -173,128 +173,130 @@ Anything only a human knows that would help document this product. For example:
|
|
|
173
173
|
- Gotchas or non-obvious behavior.
|
|
174
174
|
|
|
175
175
|
(Replace these examples with your notes, or leave the file as-is to skip \u2014 it's optional.)
|
|
176
|
-
`}function jt(e){In(
|
|
177
|
-
`)}Nn(
|
|
178
|
-
`)}function Xo(e){try{let t=
|
|
179
|
-
`)}function Xt(e){try{return
|
|
176
|
+
`}function jt(e){In(ci(e)),In(pi(e)),In(Ko(e));for(let n of[ci(e),Ko(e)]){let o=Uc(n,".gitkeep");Nn(o)||Kt(o,`# Keeps this document360-writer inbox tracked in git even when empty.
|
|
177
|
+
`)}Nn(ui(e))||Kt(ui(e),Hc()),Kt(_n(e),mi());let t=Ie(e);return gi(e,new Date().toISOString()),t}async function hi(e,t){for(let n of At(jt(t.cwd)))console.log(n);return{kind:"continue"}}function it(){return[`This is document360-writer's dev hand-off setup (v${oe}).`,'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\u20134). 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; AND each session, check"," `.d360-writer/messages/` for open questions from the docs agent and answer them \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. Two-way messages (Part 3): check `.d360-writer/messages/` for open questions addressed to you"," (`from: docs`, `status: open`). Answer each \u2014 fold durable facts into the architecture brief and/or drop"," a reply (`from: dev`, `kind: answer`, `re: <id>`) \u2014 then set the question's frontmatter `status: done`."," If there are none, continue.","5. 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.",`6. Record completion: write/merge \`.d360-writer/devhints-state.json\` with {"completedVersion": ${oe},`,' "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.","7. 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(`
|
|
178
|
+
`)}function Xo(e){try{let t=Oc(fi(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function gi(e,t){let o={...Xo(e)??{},emittedVersion:oe,emittedAt:t};Kt(fi(e),`${JSON.stringify(o,null,2)}
|
|
179
|
+
`)}function Xt(e){try{return Lc(pi(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function Ie(e){let n=Xo(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<oe?"stale":"current",completedVersion:n}}function Mn(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:oe};try{if(!Nn(_n(e)))return n;let o=Xo(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;oe>r&&(In(Ko(e)),Kt(_n(e),mi()),gi(e,t),n.guideRefreshed=!0),oe>s&&(Fc(e).some(p=>p.kind==="request"&&p.subject.startsWith(di))||(Wc(e,{id:`onb${oe}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${di}${oe})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${oe}${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:","",it()].join(`
|
|
180
180
|
`)}),n.notifiedBuilder=!0))}catch{}return n}function On(e){if(!Nn(_n(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${oe}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,Dt,it(),Dt,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function Jo(){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, and checking"," `.d360-writer/messages/`). 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(`
|
|
181
|
-
`)}function Ln(){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):",Dt,Jo(),Dt]}function At(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${oe}.`," 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):",Dt,it(),Dt,"","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 Dt,oe,ui,at=qo(()=>{"use strict";Dt="-".repeat(64),oe=5;ui="Re-run dev\u2194docs onboarding (protocol v"});var ya={};zl(ya,{doctorCommand:()=>rn,renderDoctorChecks:()=>wa,runDoctorChecks:()=>ga});import{existsSync as xd}from"node:fs";import{d360GetAll as $d,getAccessToken as vd,isExpired as Fr,loadProfileMap as Cd,loadTokens as Pd,packageSkillsDir as ma,projectConfigPath as Rd,readProjectConfig as Td,DEFAULT_DOCS_DIR as Sd,fetchManifestSummary as Dd,resolveActiveProfile as jd,classifyClaudeAuth as Ad,CLAUDE_CODE_SETUP_HINT as ha,resolveModelSetting as Ed,probeModel as Id,D360AuthError as Nd}from"document360-engine";async function ga(e){let t=[],n=Number(process.versions.node.split(".")[0]);t.push(n>=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 o=Ad();o.state==="ready"?t.push({level:"ok",label:`Claude auth: ${o.kind==="api"?"API key":"subscription (Claude Code login found)"}`}):o.state==="maybe"?t.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. ${ha}`}):t.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:ha});let r=Ed(e);if(t.push({level:"ok",label:`Model: ${r.model??"Claude Code default"} (${r.source})`}),o.state==="ready"){let y=await Id(e,r.model??void 0);y.ok?t.push({level:"ok",label:`Model reachable \u2014 replied in ${(y.latencyMs/1e3).toFixed(1)}s`}):y.timedOut?t.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"`}):t.push({level:"fail",label:`Model call failed \u2014 ${y.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 s=Td(e);if(!s)return t.push({level:"fail",label:`No ${Rd(e)}`,fix:"Run: /init (or d360-writer init)"}),t;t.push({level:"ok",label:`Project config: ${s.projectId}`});let c=(s.docsDir??Sd).replace(/\/+$/,"");t.push(s.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 ${c}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let p=s.authoritativeSourceFiles??[];t.push(p.length>0?{level:"ok",label:`Sources: docs grounded in ${p.length} path(s) (${p.slice(0,3).join(", ")}${p.length>3?", \u2026":""})`}:{level:"warn",label:"Sources: not set \u2014 docs are grounded in the whole repo",fix:"Run: /scope to choose which files/folders the docs are written from"});let h;try{h=jd(e),t.push({level:"ok",label:`Profile: ${h.name} (${h.connection.name})${h.production?" \u26A0 PRODUCTION":""}`})}catch(y){return t.push({level:"fail",label:`Profile config: ${y.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),t}let b=Pd(h.name);b?Fr(b)&&!b.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):Fr(b)?t.push({level:"warn",label:"Document360: token expired \u2014 will auto-refresh on next call"}):t.push({level:"ok",label:`Document360: logged in (until ${new Date(b.expiresAt).toLocaleString()})`}):t.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${h.name})`}),t.push(h.project.workspaceId?{level:"ok",label:`Workspace: ${h.project.workspaceName??h.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let x=Cd(e,h.name);x?x.projectId&&h.project.projectId&&x.projectId!==h.project.projectId?t.push({level:"fail",label:`Category map projectId (${x.projectId}) \u2260 profile projectId (${h.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):t.push({level:"ok",label:`Category map: ${Object.keys(x.articles).length} articles, ${Object.keys(x.categories).length} categories`}):t.push({level:"ok",label:`Category map: none yet for "${h.name}" (created on first /publish)`}),t.push(xd(ma())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${ma()}`,fix:"Reinstall document360-writer (broken install)"});let D=Ie(e);if(D.status==="current"?t.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${oe})`}):D.status==="stale"&&t.push({level:"warn",label:`Dev hand-off: builder on devhints v${D.completedVersion}, current is v${oe}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),b&&(!Fr(b)||b.refreshToken)){let y={profile:h.name,connection:h.connection};try{await vd(y);let C=await $d(y,"/v3/projects");t.push({level:"ok",label:`API reachable (${h.connection.apiUrl}) \u2014 ${C.length} project(s) visible`})}catch(C){t.push({level:"fail",label:`API call failed: ${C.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let P=x?.projectId??h.project.projectId;if(P&&h.project.workspaceId)try{let C=await Dd(y,P,h.project.workspaceId);if(C){let I=(C.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);t.push({level:"ok",label:`Workspace sync manifest: available on ${h.connection.name} (${C.languages?.length??0} language${(C.languages?.length??0)===1?"":"s"}) \xB7 hash ${I||"(none)"}`})}else t.push({level:"warn",label:`Workspace sync manifest: not live on ${h.connection.name} yet`,fix:"No action needed \u2014 sync uses the per-article path until the manifest ships on this environment"})}catch(C){C instanceof Nd||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(C.message)?t.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${h.project.projectName??P})`,fix:"Run /login and pick this repo's project \u2014 your token is scoped to another project"}):t.push({level:"warn",label:`Workspace sync manifest: probe failed (${C.message.slice(0,80)})`})}}return t}function wa(e){let t=[""];for(let r of e){let s=r.level==="ok"?E("\u2713"):r.level==="warn"?O("\u26A0"):$("\u2717");t.push(` ${s} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("fix:")} ${N(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"})`}`):$(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function rn(e,t){console.log(f("Running checks\u2026"));for(let n of wa(await ga(t.cwd)))console.log(n);return{kind:"continue"}}var Kn=qo(()=>{"use strict";at();F()});import{Command as cm}from"commander";import{createRequire as um}from"node:module";import{AUTH_MODES as dm}from"document360-engine";import{input as dc}from"@inquirer/prompts";import{loginPkce as pc,refreshTokens as fc,toStoredTokens as Xs,clearTokens as mc,decodeJwtClaims as Ks,isExpired as hc,loadTokens as gc,saveTokens as Js,resolveActiveProfile as Tn,setProfileProject as wc,readProjectConfig as yc}from"document360-engine";F();import{select as Ql}from"@inquirer/prompts";import{resolveActiveProfile as Zl,setProfileProject as ec,resolveProjectId as tc,listWorkspaces as nc}from"document360-engine";async function Vt(e,t){let n=Zl(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??tc(o);return{workspaces:await nc(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var Bs=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function Bo(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 Rn(e,t,n,o,r){ec(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function Ys(e,t,n){let o;try{o=await Vt(e,n)}catch(s){return console.log($(`Could not list workspaces: ${s.message}`)),1}let r=Bo(o.workspaces,t);return r?(Rn(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($(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function St(e,t){let n;try{n=await Vt(e,t)}catch(b){console.log($(`Could not list workspaces: ${b.message}`));return}let{workspaces:o,projectId:r,profile:s,current:c}=n;if(o.length===0){console.log(f("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let b of o)console.log(` ${b.id===c?N("\u25CF"):" "} ${Bs(b)} ${f(b.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let p=await Ql({message:"Select the Document360 workspace for this repo:",choices:o.map(b=>({name:`${Bs(b)}${b.id===c?" (current)":""}`,value:b.id}))}),h=o.find(b=>b.id===p);Rn(e,s,r,p,h?.name),console.log(E(`\u2713 Workspace set to "${h?.name??p}" for profile "${s}".`))}F();import{select as oc}from"@inquirer/prompts";import{resolveActiveProfile as rc,setProfileProject as sc,listProjects as ic}from"document360-engine";async function st(e,t){let n=rc(e,t),o={profile:n.name,connection:n.connection};return{projects:await ic(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var Gs=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Vs(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 Yo(e,t,n,o){sc(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function zs(e,t){let n;try{n=await st(e,t)}catch(h){console.log($(`Could not list projects: ${h.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(f("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let h of o)console.log(` ${h.id===s?N("\u25CF"):" "} ${Gs(h)} ${f(h.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let c=await oc({message:"Select the Document360 project for this repo:",choices:o.map(h=>({name:`${Gs(h)}${h.id===s?" (current)":""}`,value:h.id}))}),p=o.find(h=>h.id===c);Yo(e,r,c,p?.name),console.log(E(`\u2713 Project set to "${p?.name??c}" for profile "${r}". Next: pick a workspace.`))}F();import ac from"picocolors";function lc(e=process.env){return e.FORCE_HYPERLINK==="0"||!ac.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 cc(e,t=e,n){return lc(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var uc=/https?:\/\/[^\s\x1b]+/g;function zt(e,t){return e.replace(uc,n=>cc(n,n,t))}function Qs(e){return{...Ks(e.idToken)??{},...Ks(e.accessToken)??{}}}function Sn(e){let t=Qs(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 Dn(e){let t=Tn(process.cwd(),e.profile),n=t.connection;console.log(f(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=await pc(n,{manual:e.manual,promptForRedirect:s=>dc({message:s})},s=>console.log(zt(s))),r=Xs(t.name,o);if(Js(r),await Go(r,t.name,s=>console.log(f(s))),console.log(""),console.log(E(`\u2713 Logged in to "${t.name}" as ${Sn(r)}`)),console.log(f(` access token expires: ${r.expiresAt}`)),console.log(f(` refresh token: ${r.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{yc(process.cwd())?.profiles?.[t.name]&&(console.log(""),await St(process.cwd(),t.name))}catch{}}async function Go(e,t,n){let r=Qs(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Tn(process.cwd(),t).project.projectId)return;let c;try{let{projects:p}=await st(process.cwd(),t);c=p.find(h=>h.id===r)?.name}catch{}wc(process.cwd(),t,{projectId:r,projectName:c}),n(` Project "${c??r}" written to profile "${t}".`)}catch{}}async function Zs(e){let t=Tn(process.cwd(),e.profile),n=t.connection,o=gc(t.name);if(!o){console.log($(`Not logged in to Document360 (profile "${t.name}").`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${N(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Sn(o)}`),hc(o))if(o.refreshToken)try{let r=Xs(t.name,await fc(n,o.refreshToken));Js(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(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(O("Session expired (no refresh token).")),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(f(` expires: ${o.expiresAt}`))}async function ei(e){let t=Tn(process.cwd(),e.profile);mc(t.name)?console.log(E(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(f(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}F();import{readProjectConfig as ti,writeProjectConfig as kc,resolveActiveProfile as bc,loadTokens as xc,isExpired as $c}from"document360-engine";function jn(e){let t=ti(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log($("No profiles in .d360-writer.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?N("\u25CF "):" ",s=o.production?O(" \u26A0 PRODUCTION"):"",c=o.connection.environment??"(inline)",p=xc(n),h=p?$c(p)&&!p.refreshToken?O("expired"):f("logged in"):f("not logged in");console.log(`${r}${N(n)} \u2192 ${c}${s} [${h}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function An(e,t){let n=ti(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log($(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,kc(n,e);let o=n.profiles[t].production?O(" \u26A0 PRODUCTION"):"";console.log(E(`\u2713 Default profile is now "${t}"${o}`))}function En(e,t){try{let n=bc(e,t);console.log(""),console.log(`Profile ${N(n.name)}${n.production?O(" \u26A0 PRODUCTION"):""}`),console.log(f(` api: ${n.connection.apiUrl}`)),console.log(f(` identity: ${n.connection.authorizationUrl}`)),console.log(f(` clientId: ${n.connection.clientId}`)),console.log(f(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(f(` project: ${n.project.projectId??"(set at login)"}`)),console.log(f(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log($(n.message)),process.exitCode=1}}F();import{existsSync as vc,readdirSync as Cc,statSync as ni}from"node:fs";import{join as oi}from"node:path";import{apiLogDir as Pc}from"document360-engine";function ri(){let e=Pc();if(console.log(""),console.log(`Document360 API logs: ${N(e)}`),!vc(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Cc(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(f(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let s=(ni(oi(e,r)).size/1024).toFixed(1);console.log(` ${r} ${f(`${s} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${f("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let s=(ni(oi(e,r)).size/1024).toFixed(1);console.log(` ${$(r)} ${f(`${s} KB`)}`)}}console.log(""),console.log(f("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(f("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}F();import{createSession as Rc,resolveAuth as Tc,findByName as Sc,slugify as Dc,touchSession as jc,upsertSession as Ac,resolveActiveProfile as Ec}from"document360-engine";async function si(e,t,n,o,r,s){let c=Tc(n);c.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${N("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${N("d360-writer --auth subscription")}`),process.exit(2)),c.kind==="subscription"&&console.error(f("Using your Claude subscription (no API key set)."));let p=null;try{p=Ec(e,r)}catch(y){console.error($(`Document360 profile error: ${y.message}`)),process.exit(2)}p.production&&(console.error(O(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),s||(console.error($("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(f(" --yes given \u2014 proceeding against production.")));let h;if(o){let y=Sc(e,o);y||(console.error($(`No saved session matches "${o}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),h=y.uuid,console.error(f(`Resuming "${y.name}"`))}let b=Rc({cwd:e,resume:h,profileName:r,allowProdWrites:s===!0}),x=h??null,D=1;for await(let y of b.send(t))switch(y.type){case"session":if(!x){x=y.sessionId;let P=new Date().toISOString();Ac({uuid:x,name:Dc(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:P,updatedAt:P})}break;case"text":process.stdout.write(y.delta);break;case"tool":console.error(re(` \u2699 ${y.name}`));break;case"result":D=y.ok?0:1,console.error(f(`(${y.inputTokens}\u2192${y.outputTokens} tokens`+(y.costUsd>0?`, $${y.costUsd<.01?y.costUsd.toFixed(4):y.costUsd.toFixed(2)}`:"")+")")),y.ok||console.error($("agent finished with an error result"));break;case"error":console.error(""),console.error($(`agent error: ${y.message}`)),process.exit(1)}x&&jc(x),process.stdout.write(`
|
|
182
|
-
`),process.exit(D)}import{createInterface as
|
|
181
|
+
`)}function Ln(){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):",Dt,Jo(),Dt]}function At(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${oe}.`," 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):",Dt,it(),Dt,"","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 Dt,oe,di,at=qo(()=>{"use strict";Dt="-".repeat(64),oe=5;di="Re-run dev\u2194docs onboarding (protocol v"});var ka={};Xl(ka,{doctorCommand:()=>rn,renderDoctorChecks:()=>ya,runDoctorChecks:()=>wa});import{existsSync as vd}from"node:fs";import{d360GetAll as Cd,getAccessToken as Pd,isExpired as Fr,loadProfileMap as Rd,loadTokens as Td,packageSkillsDir as ha,projectConfigPath as Sd,readProjectConfig as Dd,DEFAULT_DOCS_DIR as jd,fetchManifestSummary as Ad,resolveActiveProfile as Ed,classifyClaudeAuth as Id,CLAUDE_CODE_SETUP_HINT as ga,resolveModelSetting as Nd,probeModel as _d,D360AuthError as Md}from"document360-engine";async function wa(e){let t=[],n=Number(process.versions.node.split(".")[0]);t.push(n>=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 o=Id();o.state==="ready"?t.push({level:"ok",label:`Claude auth: ${o.kind==="api"?"API key":"subscription (Claude Code login found)"}`}):o.state==="maybe"?t.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. ${ga}`}):t.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:ga});let r=Nd(e);if(t.push({level:"ok",label:`Model: ${r.model??"Claude Code default"} (${r.source})`}),o.state==="ready"){let y=await _d(e,r.model??void 0);y.ok?t.push({level:"ok",label:`Model reachable \u2014 replied in ${(y.latencyMs/1e3).toFixed(1)}s`}):y.timedOut?t.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"`}):t.push({level:"fail",label:`Model call failed \u2014 ${y.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 s=Dd(e);if(!s)return t.push({level:"fail",label:`No ${Sd(e)}`,fix:"Run: /init (or d360-writer init)"}),t;t.push({level:"ok",label:`Project config: ${s.projectId}`});let c=(s.docsDir??jd).replace(/\/+$/,"");t.push(s.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 ${c}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let p=s.authoritativeSourceFiles??[];t.push(p.length>0?{level:"ok",label:`Sources: docs grounded in ${p.length} path(s) (${p.slice(0,3).join(", ")}${p.length>3?", \u2026":""})`}:{level:"warn",label:"Sources: not set \u2014 docs are grounded in the whole repo",fix:"Run: /scope to choose which files/folders the docs are written from"});let h;try{h=Ed(e),t.push({level:"ok",label:`Profile: ${h.name} (${h.connection.name})${h.production?" \u26A0 PRODUCTION":""}`})}catch(y){return t.push({level:"fail",label:`Profile config: ${y.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),t}let b=Td(h.name);b?Fr(b)&&!b.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):Fr(b)?t.push({level:"warn",label:"Document360: token expired \u2014 will auto-refresh on next call"}):t.push({level:"ok",label:`Document360: logged in (until ${new Date(b.expiresAt).toLocaleString()})`}):t.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${h.name})`}),t.push(h.project.workspaceId?{level:"ok",label:`Workspace: ${h.project.workspaceName??h.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let x=Rd(e,h.name);x?x.projectId&&h.project.projectId&&x.projectId!==h.project.projectId?t.push({level:"fail",label:`Category map projectId (${x.projectId}) \u2260 profile projectId (${h.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):t.push({level:"ok",label:`Category map: ${Object.keys(x.articles).length} articles, ${Object.keys(x.categories).length} categories`}):t.push({level:"ok",label:`Category map: none yet for "${h.name}" (created on first /publish)`}),t.push(vd(ha())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${ha()}`,fix:"Reinstall document360-writer (broken install)"});let D=Ie(e);if(D.status==="current"?t.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${oe})`}):D.status==="stale"&&t.push({level:"warn",label:`Dev hand-off: builder on devhints v${D.completedVersion}, current is v${oe}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),b&&(!Fr(b)||b.refreshToken)){let y={profile:h.name,connection:h.connection};try{await Pd(y);let C=await Cd(y,"/v3/projects");t.push({level:"ok",label:`API reachable (${h.connection.apiUrl}) \u2014 ${C.length} project(s) visible`})}catch(C){t.push({level:"fail",label:`API call failed: ${C.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let P=x?.projectId??h.project.projectId;if(P&&h.project.workspaceId)try{let C=await Ad(y,P,h.project.workspaceId);if(C){let I=(C.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);t.push({level:"ok",label:`Workspace sync manifest: available on ${h.connection.name} (${C.languages?.length??0} language${(C.languages?.length??0)===1?"":"s"}) \xB7 hash ${I||"(none)"}`})}else t.push({level:"warn",label:`Workspace sync manifest: not live on ${h.connection.name} yet`,fix:"No action needed \u2014 sync uses the per-article path until the manifest ships on this environment"})}catch(C){C instanceof Md||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(C.message)?t.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${h.project.projectName??P})`,fix:"Run /login and pick this repo's project \u2014 your token is scoped to another project"}):t.push({level:"warn",label:`Workspace sync manifest: probe failed (${C.message.slice(0,80)})`})}}return t}function ya(e){let t=[""];for(let r of e){let s=r.level==="ok"?A("\u2713"):r.level==="warn"?M("\u26A0"):v("\u2717");t.push(` ${s} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("fix:")} ${N(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?A(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):v(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function rn(e,t){console.log(f("Running checks\u2026"));for(let n of ya(await wa(t.cwd)))console.log(n);return{kind:"continue"}}var Kn=qo(()=>{"use strict";at();W()});import{Command as fm}from"commander";import{createRequire as mm}from"node:module";import{AUTH_MODES as hm}from"document360-engine";import{input as fc}from"@inquirer/prompts";import{loginPkce as mc,refreshTokens as hc,toStoredTokens as Js,clearTokens as gc,decodeJwtClaims as Xs,isExpired as wc,loadTokens as yc,saveTokens as Qs,resolveActiveProfile as Tn,setProfileProject as kc,readProjectConfig as bc}from"document360-engine";W();import{select as ec}from"@inquirer/prompts";import{resolveActiveProfile as tc,setProfileProject as nc,resolveProjectId as oc,listWorkspaces as rc}from"document360-engine";async function Vt(e,t){let n=tc(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??oc(o);return{workspaces:await rc(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var Ys=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function Bo(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 Rn(e,t,n,o,r){nc(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function Gs(e,t,n){let o;try{o=await Vt(e,n)}catch(s){return console.log(v(`Could not list workspaces: ${s.message}`)),1}let r=Bo(o.workspaces,t);return r?(Rn(e,o.profile,o.projectId,r.id,r.name),console.log(A(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(v(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function St(e,t){let n;try{n=await Vt(e,t)}catch(b){console.log(v(`Could not list workspaces: ${b.message}`));return}let{workspaces:o,projectId:r,profile:s,current:c}=n;if(o.length===0){console.log(f("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let b of o)console.log(` ${b.id===c?N("\u25CF"):" "} ${Ys(b)} ${f(b.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let p=await ec({message:"Select the Document360 workspace for this repo:",choices:o.map(b=>({name:`${Ys(b)}${b.id===c?" (current)":""}`,value:b.id}))}),h=o.find(b=>b.id===p);Rn(e,s,r,p,h?.name),console.log(A(`\u2713 Workspace set to "${h?.name??p}" for profile "${s}".`))}W();import{select as sc}from"@inquirer/prompts";import{resolveActiveProfile as ic,setProfileProject as ac,listProjects as lc}from"document360-engine";async function st(e,t){let n=ic(e,t),o={profile:n.name,connection:n.connection};return{projects:await lc(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var Vs=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function zs(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 Yo(e,t,n,o){ac(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function Ks(e,t){let n;try{n=await st(e,t)}catch(h){console.log(v(`Could not list projects: ${h.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(f("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let h of o)console.log(` ${h.id===s?N("\u25CF"):" "} ${Vs(h)} ${f(h.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let c=await sc({message:"Select the Document360 project for this repo:",choices:o.map(h=>({name:`${Vs(h)}${h.id===s?" (current)":""}`,value:h.id}))}),p=o.find(h=>h.id===c);Yo(e,r,c,p?.name),console.log(A(`\u2713 Project set to "${p?.name??c}" for profile "${r}". Next: pick a workspace.`))}W();import cc from"picocolors";function uc(e=process.env){return e.FORCE_HYPERLINK==="0"||!cc.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 dc(e,t=e,n){return uc(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var pc=/https?:\/\/[^\s\x1b]+/g;function zt(e,t){return e.replace(pc,n=>dc(n,n,t))}function Zs(e){return{...Xs(e.idToken)??{},...Xs(e.accessToken)??{}}}function Sn(e){let t=Zs(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 Dn(e){let t=Tn(process.cwd(),e.profile),n=t.connection;console.log(f(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=await mc(n,{manual:e.manual,promptForRedirect:s=>fc({message:s})},s=>console.log(zt(s))),r=Js(t.name,o);if(Qs(r),await Go(r,t.name,s=>console.log(f(s))),console.log(""),console.log(A(`\u2713 Logged in to "${t.name}" as ${Sn(r)}`)),console.log(f(` access token expires: ${r.expiresAt}`)),console.log(f(` refresh token: ${r.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{bc(process.cwd())?.profiles?.[t.name]&&(console.log(""),await St(process.cwd(),t.name))}catch{}}async function Go(e,t,n){let r=Zs(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Tn(process.cwd(),t).project.projectId)return;let c;try{let{projects:p}=await st(process.cwd(),t);c=p.find(h=>h.id===r)?.name}catch{}kc(process.cwd(),t,{projectId:r,projectName:c}),n(` Project "${c??r}" written to profile "${t}".`)}catch{}}async function ei(e){let t=Tn(process.cwd(),e.profile),n=t.connection,o=yc(t.name);if(!o){console.log(v(`Not logged in to Document360 (profile "${t.name}").`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${N(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Sn(o)}`),wc(o))if(o.refreshToken)try{let r=Js(t.name,await hc(n,o.refreshToken));Qs(r),console.log(A(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(M(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(M("Session expired (no refresh token).")),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(f(` expires: ${o.expiresAt}`))}async function ti(e){let t=Tn(process.cwd(),e.profile);gc(t.name)?console.log(A(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(f(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}W();import{readProjectConfig as ni,writeProjectConfig as xc,resolveActiveProfile as $c,loadTokens as vc,isExpired as Cc}from"document360-engine";function jn(e){let t=ni(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(v("No profiles in .d360-writer.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?N("\u25CF "):" ",s=o.production?M(" \u26A0 PRODUCTION"):"",c=o.connection.environment??"(inline)",p=vc(n),h=p?Cc(p)&&!p.refreshToken?M("expired"):f("logged in"):f("not logged in");console.log(`${r}${N(n)} \u2192 ${c}${s} [${h}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function An(e,t){let n=ni(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(v(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,xc(n,e);let o=n.profiles[t].production?M(" \u26A0 PRODUCTION"):"";console.log(A(`\u2713 Default profile is now "${t}"${o}`))}function En(e,t){try{let n=$c(e,t);console.log(""),console.log(`Profile ${N(n.name)}${n.production?M(" \u26A0 PRODUCTION"):""}`),console.log(f(` api: ${n.connection.apiUrl}`)),console.log(f(` identity: ${n.connection.authorizationUrl}`)),console.log(f(` clientId: ${n.connection.clientId}`)),console.log(f(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(f(` project: ${n.project.projectId??"(set at login)"}`)),console.log(f(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(v(n.message)),process.exitCode=1}}W();import{existsSync as Pc,readdirSync as Rc,statSync as oi}from"node:fs";import{join as ri}from"node:path";import{apiLogDir as Tc}from"document360-engine";function si(){let e=Tc();if(console.log(""),console.log(`Document360 API logs: ${N(e)}`),!Pc(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Rc(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(f(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let s=(oi(ri(e,r)).size/1024).toFixed(1);console.log(` ${r} ${f(`${s} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${f("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let s=(oi(ri(e,r)).size/1024).toFixed(1);console.log(` ${v(r)} ${f(`${s} KB`)}`)}}console.log(""),console.log(f("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(f("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}W();import{createSession as Sc,resolveAuth as Dc,findByName as jc,slugify as Ac,touchSession as Ec,upsertSession as Ic,resolveActiveProfile as Nc}from"document360-engine";async function ii(e,t,n,o,r,s){let c=Dc(n);c.kind==="none"&&(console.error(""),console.error(v("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${N("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${N("d360-writer --auth subscription")}`),process.exit(2)),c.kind==="subscription"&&console.error(f("Using your Claude subscription (no API key set)."));let p=null;try{p=Nc(e,r)}catch(y){console.error(v(`Document360 profile error: ${y.message}`)),process.exit(2)}p.production&&(console.error(M(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),s||(console.error(v("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(f(" --yes given \u2014 proceeding against production.")));let h;if(o){let y=jc(e,o);y||(console.error(v(`No saved session matches "${o}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),h=y.uuid,console.error(f(`Resuming "${y.name}"`))}let b=Sc({cwd:e,resume:h,profileName:r,allowProdWrites:s===!0}),x=h??null,D=1;for await(let y of b.send(t))switch(y.type){case"session":if(!x){x=y.sessionId;let P=new Date().toISOString();Ic({uuid:x,name:Ac(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:P,updatedAt:P})}break;case"text":process.stdout.write(y.delta);break;case"tool":console.error(re(` \u2699 ${y.name}`));break;case"result":D=y.ok?0:1,console.error(f(`(${y.inputTokens}\u2192${y.outputTokens} tokens`+(y.costUsd>0?`, $${y.costUsd<.01?y.costUsd.toFixed(4):y.costUsd.toFixed(2)}`:"")+")")),y.ok||console.error(v("agent finished with an error result"));break;case"error":console.error(""),console.error(v(`agent error: ${y.message}`)),process.exit(1)}x&&Ec(x),process.stdout.write(`
|
|
182
|
+
`),process.exit(D)}import{createInterface as jp}from"node:readline/promises";import{createSession as as,resolveAuth as Ap,getSession as Ep,setTitle as Ip,slugify as Np,touchSession as Ya,upsertSession as _p,generateTitle as Mp,resolveActiveProfile as Ga,resolveModelSetting as Op,readProjectConfig as Lp,decodeJwtClaims as qa,isExpired as Up,loadTokens as Wp}from"document360-engine";var Ce=[{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:"/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:"/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 run d360-capture in your app's repo \u2014 it 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 --list",s:"See capture status \u2014 which specs exist and which are done."},{t:"cmd",name:"/capture-setup",s:"Re-show the data-staging + test-id checklist (auto-runs after /screenshot --all)."},{t:"gap"},{t:"dim",s:"d360-capture is a separate Playwright CLI \u2014 run it in the app's repo (needs its URL + a login)."}]},{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:"/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:"/inbox",s:"Act on your coding agent's messages."},{t:"gap"},{t:"sub",s:"Assistant \u2014 directed writing"},{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 capture specs (--all / --list)."},{t:"gap"},{t:"sub",s:"Setup & health"},{t:"cmd",name:"/model",s:"Set the Claude model."},{t:"cmd",name:"/profile",s:"Switch/create a Document360 connection."},{t:"cmd",name:"/mcp",s:"Connect MCP servers (Notion, Linear, \u2026)."},{t:"cmd",name:"/allow-prod",s:"Authorize writes to a production profile."},{t:"cmd",name:"/doctor",s:"Health check: auth, profile, workspace, API."},{t:"cmd",name:"/update",s:"Update D360-Writer."},{t:"cmd",name:"/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:"Reset the conversation (resumable)."},{t:"cmd",name:"/help",s:"Show this help."},{t:"cmd",name:"/exit",s:"Quit."}]}];function _c(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 ai(){let e=["document360-writer \u2014 help",""];for(let t of Ce){e.push(`\u2500\u2500 ${t.label} \u2500\u2500`,"");for(let n of t.rows)e.push(_c(n));e.push("")}return e.push("Tip: anything not starting with / goes to the agent."),e}async function Vo(){console.log("");for(let e of ai())console.log(e);return console.log(""),console.log("Reporting a problem? Run `d360-writer logs` for the API log files."),console.log(""),{kind:"continue"}}W();import{getSession as Mc}from"document360-engine";async function li(e,t){let n=t.currentUuid(),o=n?Mc(n):void 0;return console.log(o?f(`
|
|
183
183
|
(conversation reset \u2014 "${o.name}" is still available via /resume)
|
|
184
184
|
`):f(`
|
|
185
185
|
(conversation reset \u2014 agent will start fresh on the next prompt)
|
|
186
|
-
`)),{kind:"clear"}}async function zo(){return{kind:"exit"}}
|
|
187
|
-
`),"utf8")}async function
|
|
186
|
+
`)),{kind:"clear"}}async function zo(){return{kind:"exit"}}W();at();import{input as Jt,confirm as qc}from"@inquirer/prompts";import{basename as wi,join as Un}from"node:path";import{existsSync as Et,readFileSync as Bc,readdirSync as Yc,writeFileSync as Gc}from"node:fs";import{writeProjectConfig as yi,readProjectConfig as Vc,projectConfigPath as ki,writerDir as zc,DEFAULT_DOCS_DIR as bi,DEFAULT_CAPTURE_DIR as xi,DEFAULT_OUTPUT_DIR as $i}from"document360-engine";function vi(e,t="berlin"){let n=ki(e);if(Et(n))return{created:!1,path:n,profileName:""};let o={projectId:Ri(e)??wi(e),docsDir:bi,captureDir:xi,outputDir:$i,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:Ti(e)};return yi(o,e),Ci(e),{created:!0,path:n,profileName:t}}function Ci(e){let t=Un(zc(e),".gitignore");Et(t)||Gc(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
|
|
187
|
+
`),"utf8")}async function Pi(){let e=process.cwd(),t=ki(e);if(Et(t)&&!await qc({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let n=Ri(e)??wi(e),o=await Jt({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await Jt({message:"Capture directory (where document360-capture .spec.ts files live):",default:xi}),s=await Jt({message:"Screenshot output directory:",default:$i}),c=await Jt({message:"Default connection profile name:",default:"berlin"}),p=await Jt({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),h={projectId:o,docsDir:bi,captureDir:r,outputDir:s,profiles:{[c]:{connection:{environment:p},production:!1}},defaultProfile:c,authoritativeSourceFiles:Ti(e)},b=Vc(e);b?.terminologyGlossary&&(h.terminologyGlossary=b.terminologyGlossary),yi(h,e),Ci(e);let x=jt(e);console.log(""),console.log(A(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${N(`d360-writer login --profile ${c}`)} ${f("(sign in; project & workspace auto-selected)")}`),console.log("");for(let D of At(x))console.log(D);return console.log(""),console.log(`${f("Then ask:")} ${N('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function Ri(e){let t=Un(e,"package.json");if(!Et(t))return null;try{return JSON.parse(Bc(t,"utf8")).name??null}catch{return null}}function Ti(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Et(Un(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Un(e,n);Et(o)&&!Kc(o)&&t.push(n)}return t}function Kc(e){try{return Yc(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}W();import{readMcpConfig as Qo,writeMcpConfig as Si}from"document360-engine";async function Wn(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(Xc(),{kind:"continue"}):t==="add"?(Jc(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(Qc(e.slice(1)),{kind:"continue"}):(console.log(v(`Unknown /mcp subcommand: ${t}`)),console.log(f("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function Xc(){let e=Qo(),t=Object.keys(e.servers);if(t.length===0){console.log(f(`
|
|
188
188
|
No MCP servers registered. Add one with /mcp add <name> <type> <ref>
|
|
189
|
-
`));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(n)} ${f("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?f(` [headers: ${r.join(", ")}]`):"";console.log(` ${N(n)} ${f(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function
|
|
190
|
-
`),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(
|
|
191
|
-
`)}),L=Math.max(..._.map(de=>de.length)),Q=[];for(let de=0;de<L;de++)Q.push(p.map((ie,
|
|
189
|
+
`));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(n)} ${f("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?f(` [headers: ${r.join(", ")}]`):"";console.log(` ${N(n)} ${f(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function Jc(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(v("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(v(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=Qo(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let c={};for(let p=1;p<o.length;p++)if(o[p]==="-H"||o[p]==="--header"){let h=o[++p],b=h?.match(/^([^:=]+)[:=](.+)$/);if(!b){console.log(v(`-H expects key:value (no spaces). Got: ${h??"(nothing)"}`));return}c[b[1].trim()]=b[2].trim()}else{console.log(v(`Unexpected argument: ${o[p]}. After the URL, only -H key:value is allowed.`));return}s={type:n,url:o[0],headers:Object.keys(c).length>0?c:void 0}}r.servers[t]=s,Si(r),console.log(""),console.log(A(`\u2713 Registered "${t}" (${n})`)),console.log(M(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(f(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function Qc(e){let t=e[0];if(!t){console.log(v("Usage: /mcp remove <name>"));return}let n=Qo();if(!n.servers[t]){console.log(v(`No server named "${t}".`));return}delete n.servers[t],Si(n),console.log(A(`\u2713 Removed "${t}".`)),console.log(f(" Run /clear to drop it from the current session immediately."))}W();import{readFileSync as fu}from"node:fs";import{join as mu}from"node:path";import{select as hu}from"@inquirer/prompts";import{computeSyncStatus as ar,planPartitions as gu,relatedArticlePaths as wu,resolveModelForOperation as yu,runPartitioned as ku,loadProfileMap as bu,resolveActiveProfile as xu,resolveCrossLinks as $u}from"document360-engine";import V from"picocolors";import Ni from"wrap-ansi";import rr from"string-width";W();import qe from"picocolors";import Zo from"wrap-ansi";import er from"string-width";var Di=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),ji=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),Ai=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function Zc(e){let t=e.replace(/\r/g,"").split(`
|
|
190
|
+
`),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(Di(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&ji(t[o+1])){let p=Ai(r);o+=2;let h=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)h.push(Ai(t[o++]));n.push({kind:"table",header:p,rows:h});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]);)p.push(t[o++].replace(/^\s*([-*]|\d+\.)\s+/,""));n.push({kind:"list",items:p});continue}if(r.trim()===""){o++;continue}let c=[];for(;o<t.length&&t[o].trim()!==""&&!/^\s*```/.test(t[o])&&!/^(#{1,6})\s/.test(t[o])&&!/^\s*([-*]|\d+\.)\s+/.test(t[o])&&!Di(t[o])&&!(t[o].includes("|")&&o+1<t.length&&ji(t[o+1]));)c.push(t[o++]);n.push({kind:"para",text:c.join(" ")})}return n}function tr(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?qe.bold(t.slice(2,-2)):t.startsWith("`")?N(t.slice(1,-1)):qe.italic(t.slice(1,-1)))}var eu=(e,t)=>e+" ".repeat(Math.max(0,t-er(e)));function tu(e,t,n){let o=e.length,r=e.map((C,I)=>Math.max(er(C),...t.map(_=>er(_[I]??"")))),s=Math.max(24,n),c=3*o+1,p=[...r],h=()=>p.reduce((C,I)=>C+I,0)+c,b=0;for(;h()>s&&b++<1e4;){let C=-1,I=6;for(let _=0;_<o;_++)p[_]>I&&(I=p[_],C=_);if(C===-1)break;p[C]-=1}let x=(C,I,_)=>qe.gray(C+p.map(L=>"\u2500".repeat(L+2)).join(I)+_),D=qe.gray("\u2502"),y=(C,I)=>{let _=p.map((de,ie)=>{let Re=C[ie]??"",le=I?qe.bold(Re):tr(Re);return Zo(le,de,{hard:!0}).split(`
|
|
191
|
+
`)}),L=Math.max(..._.map(de=>de.length)),Q=[];for(let de=0;de<L;de++)Q.push(p.map((ie,Re)=>`${D} ${eu(_[Re][de]??"",ie)} `).join("")+D);return Q.join(`
|
|
192
192
|
`)},P=[x("\u250C","\u252C","\u2510"),y(e,!0)];return P.push(t.length===0?x("\u2514","\u2534","\u2518"):x("\u251C","\u253C","\u2524")),t.forEach((C,I)=>{P.push(y(C,!1)),P.push(I===t.length-1?x("\u2514","\u2534","\u2518"):x("\u251C","\u253C","\u2524"))}),P.join(`
|
|
193
|
-
`)}function
|
|
193
|
+
`)}function nu(e,t){switch(e.kind){case"heading":return qe.bold(e.text);case"hr":return qe.gray("\u2500".repeat(t));case"para":return Zo(tr(e.text),t);case"list":return e.items.map(n=>{let[o="",...r]=Zo(tr(n),Math.max(10,t-4)).split(`
|
|
194
194
|
`);return" \u2022 "+o+r.map(s=>`
|
|
195
195
|
`+s).join("")}).join(`
|
|
196
196
|
`);case"code":return e.lines.map(n=>qe.gray(" "+n)).join(`
|
|
197
|
-
`);case"table":return
|
|
197
|
+
`);case"table":return tu(e.header,e.rows,t)}}function nr(e,t){let n=Math.max(20,t);return Zc(e).map(o=>nu(o,n)).join(`
|
|
198
198
|
|
|
199
|
-
`)}
|
|
199
|
+
`)}W();import ou from"picocolors";var ru=[127,86,217],su=[22,38,43],Ei={T:ru,E:su},Qt=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],or=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,iu=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function Ii(){if(!ou.isColorSupported)return[];let e=Qt[0].length,t=[];for(let n=0;n<Qt.length;n+=2){let o="";for(let r=0;r<e;r++){let s=Ei[Qt[n][r]],c=n+1<Qt.length?Ei[Qt[n+1][r]]:void 0;s&&c?o+=`${or(s)}${iu(c)}\u2580\x1B[49m\x1B[39m`:s?o+=`${or(s)}\u2580\x1B[39m`:c?o+=`${or(c)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function Zt(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function fe(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function Be(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var It=(e,t)=>` ${e.padEnd(13)}${t}`;function au(e,t){let n=[Gt("\u270E document360-writer")+V.gray(` v${e.version}`),V.gray(" Reads your code, writes your docs."),"",It("Claude:",`${e.claude}${V.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),It("Document360:",e.configured?e.loggedOut?V.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?V.gray(` (${e.sessionHint})`):""}`:V.yellow("not set up \u2014 run /init")),It("Profile:",e.configured?`${e.profile}${V.gray(` (${e.apiUrl})`)}${e.prod?V.bold(V.yellow(" \u26A0 PRODUCTION")):""}`:V.gray("\u2014 (run /init)")),It("Project:",e.project),It("Mode:",V.gray(e.mode)),It("cwd:",V.gray(e.cwd))],o=Ii();if(o.length===0)return n.join(`
|
|
200
200
|
`);let r=2,s=3,c=rr(o[0]);if(!(t>=r+c+s+Math.max(...n.map(x=>rr(x)))))return[...o.map(x=>" "+x),...n].join(`
|
|
201
201
|
`);let h=Math.max(0,Math.floor((n.length-o.length)/2)),b=[];for(let x=0;x<Math.max(o.length+h,n.length);x++){let D=o[x-h]??" ".repeat(c);b.push((" ".repeat(r)+D+" ".repeat(s)+(n[x]??"")).trimEnd())}return b.join(`
|
|
202
|
-
`)}var
|
|
203
|
-
`).flatMap(b=>
|
|
202
|
+
`)}var lu={error:V.red,warn:V.yellow,ok:V.green,info:V.gray};function sr(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return au(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",s=Math.max(10,n-4),c=50,p=e.text.split(`
|
|
203
|
+
`).flatMap(b=>Ni(b,s,{hard:!0}).split(`
|
|
204
204
|
`)),h=Math.max(0,p.length-c);return h>0&&(p=[...p.slice(0,c),V.dim(`\u2026 +${h} more lines`)]),`
|
|
205
205
|
`+p.map((b,x)=>o+(x===0?N(" \u276F "):" ")+b+" ".repeat(Math.max(0,s-rr(b))+1)+r).join(`
|
|
206
206
|
`)}case"assistant":return`
|
|
207
207
|
`+nr(e.text,n);case"tool":{let o=e.arg!==null?V.gray(`${e.sep}(${e.arg})`):"";return`
|
|
208
|
-
`+
|
|
208
|
+
`+Ni(V.green("\u25CF ")+V.bold(e.title)+o,n)}case"tool-result":{let o=e.isError?V.red:V.gray,r=e.lines.map((s,c)=>o((c===0?" \u23BF ":" ")+s));return e.hidden>0&&r.push(V.dim(` \u2026 +${e.hidden} lines`)),r.join(`
|
|
209
209
|
`)}case"diff":{let o=c=>c===1?"":"s",s=[V.gray(` \u23BF Added ${e.added} line${o(e.added)}, removed ${e.removed} line${o(e.removed)}`),...e.lines];return e.hidden>0&&s.push(V.dim(` \u2026 +${e.hidden} more diff lines`)),s.join(`
|
|
210
210
|
`)}case"link":return e.lines.map(o=>N(zt(` \u2B95 ${o}`))).join(`
|
|
211
211
|
`);case"preview":return`
|
|
212
212
|
`+Gt(`\u25A3 Preview \u2014 ${e.name}`)+`
|
|
213
213
|
|
|
214
214
|
`+nr(e.text,n);case"note":return`
|
|
215
|
-
`+
|
|
216
|
-
`+(e.ok?V.magenta("\u2736 "):V.red("\u2736 "))+V.gray(`Cooked for ${Zt(e.seconds)} \xB7 ${e.tokens} tokens`+(e.costUsd>0?` \xB7 ${fe(e.costUsd)}`:""))}}function
|
|
217
|
-
`)}import{resolveActiveProfile as
|
|
218
|
-
`)}var
|
|
219
|
-
`)}function ur(e,t,n){let o=y=>t[y.index]?.paths.length??0,r=e.filter(y=>y.ok),s=e.filter(y=>!y.ok),c=e.reduce((y,P)=>y+o(P),0),p=r.reduce((y,P)=>y+o(P),0),h=n==="api"?`${fe(e.reduce((y,P)=>y+P.costUsd,0))} total`:Be(e.reduce((y,P)=>y+P.outputTokens,0)),b=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,x=y=>`${y} article${y===1?"":"s"}`,D=[];if(s.length===0)D.push(`Published ${x(c)} (${b}) successfully \xB7 ${h}.`),D.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{D.push(`Published ${p}/${x(c)} (${b}) \xB7 ${h}.`),D.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 y of s)D.push(` \u2717 ${y.label}${y.error?` \u2014 ${y.error}`:""}`)}return D}async function ir(e,t){let n=
|
|
220
|
-
`),display:"/audit"}}
|
|
215
|
+
`+lu[e.tone](zt(e.text));case"done":return`
|
|
216
|
+
`+(e.ok?V.magenta("\u2736 "):V.red("\u2736 "))+V.gray(`Cooked for ${Zt(e.seconds)} \xB7 ${e.tokens} tokens`+(e.costUsd>0?` \xB7 ${fe(e.costUsd)}`:""))}}function _i(e,t){return e.map(n=>sr(n,t)).join(`
|
|
217
|
+
`)}import{resolveActiveProfile as cu,loadTokens as uu,isExpired as du,decodeJwtClaims as Mi}from"document360-engine";function pu(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function Ne(e,t){try{let n=cu(e,t),o=uu(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(du(o)&&!o.refreshToken)return{ok:!1,reason:`Your Document360 session expired (profile "${n.name}"). Run /login.`};let r=n.project.projectId;if(r){let c={...Mi(o.idToken)??{},...Mi(o.accessToken)??{}}.doc360_project_id;if(typeof c=="string"&&c&&c!==r)return{ok:!1,reason:`Your Document360 session is signed into a different project than profile "${n.name}" (this profile's project is ${pu(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}var en=3;function lr(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(`
|
|
218
|
+
`)}var Oi={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function tn(e){return e.filter(t=>t.path!==null&&t.status in Oi&&!t.link).map(t=>({path:t.path,label:Oi[t.status]}))}function Fn(e){return e.filter(t=>t.link).length}function cr(e,t){try{let n=bu(e,xu(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=$u(fu(mu(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 vu(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 Li(e){let t=[];e.length>1&&t.push({kind:"all",label:`Publish all ${e.length} articles`,paths:e.map(o=>o.path),indent:!1});let n=new Map;for(let o of e){let r=o.path.replace(/\\/g,"/").split("/").slice(0,-1).join("/"),s=n.get(r);s?s.push(o):n.set(r,[o])}for(let o of[...n.keys()].sort()){let r=n.get(o).sort((s,c)=>s.path.localeCompare(c.path));t.push({kind:"category",label:`${vu(o)} (${r.length})`,paths:r.map(s=>s.path),indent:!1});for(let s of r){let c=s.path.replace(/\\/g,"/").split("/").pop()??s.path;t.push({kind:"article",label:c,paths:[s.path],indent:!0,note:s.label})}}return t}function Hn(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). 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(`
|
|
219
|
+
`)}function ur(e,t,n){let o=y=>t[y.index]?.paths.length??0,r=e.filter(y=>y.ok),s=e.filter(y=>!y.ok),c=e.reduce((y,P)=>y+o(P),0),p=r.reduce((y,P)=>y+o(P),0),h=n==="api"?`${fe(e.reduce((y,P)=>y+P.costUsd,0))} total`:Be(e.reduce((y,P)=>y+P.outputTokens,0)),b=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,x=y=>`${y} article${y===1?"":"s"}`,D=[];if(s.length===0)D.push(`Published ${x(c)} (${b}) successfully \xB7 ${h}.`),D.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{D.push(`Published ${p}/${x(c)} (${b}) \xB7 ${h}.`),D.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 y of s)D.push(` \u2717 ${y.label}${y.error?` \u2014 ${y.error}`:""}`)}return D}async function ir(e,t){let n=gu(t),{model:o}=yu(e.cwd,"standard");console.log(f(`Publishing ${t.length} article${t.length===1?"":"s"} across ${n.length} partition${n.length===1?"":"s"} (\u2264${en} agents at once) on ${o}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let r of ku({cwd:e.cwd,partitions:n,promptFor:s=>Hn(s.paths),concurrency:en,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:o}))if(r.type==="partition_status")r.status==="running"?console.log(f(` \u25B8 ${r.label} \u2014 publishing\u2026`)):r.status==="done"?console.log(A(` \u2713 ${r.label}`)):console.log(v(` \u2717 ${r.label}`));else if(r.type==="run_done"){console.log("");let s=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let p of ur(r.results,n,s))console.log(r.ok?A(p):M(p));let c=cr(e.cwd,e.profileName);c&&console.log(f(c))}}catch(r){console.log(v(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function qn(e,t,n){let o=wu(e,n);if(o.length===0)return[];let r=new Set(tn((await ar({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function Ui(e,t){let n=Ne(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(v(n.reason)),{kind:"continue"};let o=e[0];if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await qn(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return r.length===0?(console.log(A("\u2713 All related articles are already published.")),{kind:"continue"}):await ir(t,r)}if(o==="--all"){console.log(f("Checking what needs publishing\u2026"));try{let r=await ar({cwd:t?.cwd??process.cwd()}),s=tn(r.entries),c=Fn(r.entries);return c>0&&console.log(M(`\u26A0 ${c} 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.`)),s.length===0?(console.log(A(c>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),{kind:"continue"}):t?await ir(t,s.map(p=>p.path)):{kind:"forward-to-agent",prompt:Hn(s.map(p=>p.path)),display:"/publish --all"}}catch(r){return console.log(v(`Could not compute sync status: ${r.message}`)),{kind:"continue"}}}if(!o){console.log(f("Checking what needs publishing\u2026"));let r;try{let s=await ar({cwd:t?.cwd??process.cwd()});r=tn(s.entries);let c=Fn(s.entries);c>0&&console.log(M(`\u26A0 ${c} 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.`))}catch(s){return console.log(v(`Could not compute sync status: ${s.message}`)),console.log(f("Publish a specific article: /publish <article-path>")),{kind:"continue"}}if(r.length===0)return console.log(A("\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),console.log(f(" (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} ${f(`(${s.label})`)}`);return console.log(f("Run: /publish <article-path>")),{kind:"continue"}}try{o=await t.withPausedInput(()=>hu({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(f("Cancelled.")),{kind:"continue"}}if(o==="--all")return await ir(t,r.map(s=>s.path))}return{kind:"forward-to-agent",prompt:lr(o),display:`/publish ${o}`}}async function nn(){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(`
|
|
220
|
+
`),display:"/audit"}}W();import{checkbox as Cu}from"@inquirer/prompts";import{inventoryRepo as Pu,readProjectConfig as Wi,writeProjectConfig as Ru}from"document360-engine";function dr(e,t){let n=Wi(e);n&&(n.authoritativeSourceFiles=t,Ru(n,e))}function Bn(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 Fi(e,t){let n=t?.cwd??process.cwd();if(!Wi(n))return console.log(v("No .d360-writer.json here. Run /init first.")),{kind:"continue"};let o=Pu(n);if(o.length===0)return console.log(f('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(N("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${f(Bn(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>Cu({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${Bn(s)})`,value:s.path,checked:s.recommended})),pageSize:20}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}if(r.length===0)return console.log(f("Nothing selected \u2014 scope unchanged.")),{kind:"continue"};dr(n,r),console.log(A(`\u2713 Scoped to ${r.length} folder(s) \u2014 written to .d360-writer.json`));for(let s of r)console.log(` ${s}`);return console.log(""),{kind:"continue"}}W();import{confirm as Eu}from"@inquirer/prompts";import{applyPull as fr,computeSyncStatus as Gi,compareRemoteSources as Iu,planPull as Vi,planImport as Nu,applyImport as _u,establishBaselines as Mu,rebaselineServerMeta as Ou,D360AuthError as Lu}from"document360-engine";W();var Hi=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /publish <path>):",paint:v,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /publish <path>:",paint:M,mark:"M"},{status:"remote-ahead",header:"Changed on Document360 \u2014 pull with /pull <path> (or just /pull):",paint:N,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:v,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:v,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint:re,mark:"X"},{status:"untracked-local",header:"New here \u2014 not on Document360 yet (publish to add them):",paint:f,mark:"?"},{status:"untracked-remote",header:"On Document360 \u2014 not in your local docs yet (run /pull to import them):",paint:f,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:re,mark:"\xB7"}];function Tu(e){return e.path?e.path:`${e.title??"(untitled)"} ${re(`[${e.articleId}]`)}`}function Su(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 Yn(e,t){let n=[],o=e.entries.filter(x=>x.link);if(o.length>0){n.push(""),n.push(ve("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let x of o)n.push(` ${M("~")} ${M(x.path??"")} ${re(`\u2192 "${x.link.title}"`)}`)}for(let x of Hi){let D=e.entries.filter(y=>y.status===x.status&&!(x.status==="untracked-local"&&y.link));if(D.length!==0){n.push(""),n.push(ve(x.header));for(let y of D)n.push(` ${x.paint(x.mark)} ${x.paint(Tu(y))}${y.detail?re(` (${y.detail})`):""}`)}}let r=e.counts["in-sync"]??0,s=e.entries.length;n.push("");let c={"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,h=s===r?A("\u2713 everything up to date"):[r>0?A(`\u2713 ${r} up to date`):null,p>0?`${p} to link`:null,...Hi.map(x=>{let D=(e.counts[x.status]??0)-(x.status==="untracked-local"?p:0);return D>0?`${D} ${c[x.status]}`:null})].filter(Boolean).join(re(" \xB7 ")),b=t!==void 0?` \xB7 synced in ${Su(t)}`:"";return n.push(h+re(` \xB7 ${s} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${b}`)),n}import{structuredPatch as Du}from"diff";import qi from"picocolors";var Bi=80,ju="\x1B[48;2;74;28;28m",Au="\x1B[48;2;24;66;24m",Yi="\x1B[49m",pr=e=>String(e).padStart(5);function lt(e,t,n){let o=y=>{let P=y.replace(/\r\n/g,`
|
|
221
221
|
`);return P.endsWith(`
|
|
222
222
|
`)||P===""?P:P+`
|
|
223
|
-
`},r=o(e),s=o(t);if(r===s)return null;let c=Math.max(20,n-10),p=
|
|
223
|
+
`},r=o(e),s=o(t);if(r===s)return null;let c=Math.max(20,n-10),p=Du("a","b",r,s,"","",{context:3}),h=0,b=0,x=[];p.hunks.forEach((y,P)=>{P>0&&x.push(qi.gray(" \u2026"));let C=y.oldStart,I=y.newStart;for(let _ of y.lines){let L=_[0],Q=_.slice(1).slice(0,c);L==="-"?(b++,x.push(`${ju}${pr(C++)} - ${Q}${Yi}`)):L==="+"?(h++,x.push(`${Au}${pr(I++)} + ${Q}${Yi}`)):(x.push(qi.gray(pr(I))+" "+Q),C++,I++)}});let D=x.slice(0,Bi);return{added:h,removed:b,lines:D,hidden:Math.max(0,x.length-Bi)}}async function zi(e,t){let n=Ne(t.cwd,t.profileName);if(!n.ok)return console.log(v(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await Uu(t),{kind:"continue"};if(o==="--baseline")return await Wu(t,e.filter(c=>c!=="--baseline")),{kind:"continue"};if(o==="--compare")return await Fu(t),{kind:"continue"};if(o)return console.log(v(`Unknown option: ${o}`)),console.log(f("Usage: /pull pull portal edits + import new portal articles")),console.log(f(" /pull <path> pull one article (or resolve a conflict)")),console.log(f(" /pull --status drift report only (no writes)")),console.log(f(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await Hu(t,r),{kind:"continue"};console.log(f("Pulling changes from Document360\u2026"));let s=await mr({cwd:t.cwd,profileName:t.profileName});for(let c of hr(s))console.log(c.tone==="ok"?A(c.text):c.tone==="warn"?M(c.text):f(c.text));console.log("")}catch(r){r instanceof Lu?console.log(v(r.message)):console.log(v(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function mr(e){let t=await Gi({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 Vi({cwd:e.cwd,profileName:e.profileName,relPath:o.path});fr({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 Nu({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});_u({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 Gn=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,ct=e=>e===1?"":"s";function hr(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${ct(e.pulled.length)} into local: ${Gn(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${ct(e.imported.length)}: ${Gn(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${ct(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${ct(e.conflicts.length)} changed both here and on Document360 \u2014 left untouched. Take the portal copy: /pull <path> \xB7 keep yours: /publish <path>. (${Gn(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${ct(e.failed.length)} failed: ${Gn(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 Uu(e){console.log(f("Checking Document360 for drift\u2026"));let t=Date.now(),n=await Gi({cwd:e.cwd,profileName:e.profileName});for(let o of Yn(n,Date.now()-t))console.log(o);console.log("")}async function Wu(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(f(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await Mu({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await Ou({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(A("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(A(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(A(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(M(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(f(` - ${s.path} (${s.reason})`))}}async function Fu(e){console.log(f("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await Iu({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${ve(String(t.legacyCount))} \xB7 Manifest: ${ve(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(A("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(v(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(M(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(M(` ${t.onlyInManifest.length} only in the manifest: ${t.onlyInManifest.slice(0,5).join(", ")}`)),console.log(f(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function Hu(e,t){let n=t.replace(/\\/g,"/"),o=await Vi({cwd:e.cwd,profileName:e.profileName,relPath:n});console.log(""),console.log(`${N("\u25CF")} ${ve(o.title)} ${re(`(${o.path})`)}`);for(let c of o.notes)console.log(M(` \u26A0 ${c}`));o.overwritesLocalChanges&&console.log(M(" \u26A0 This OVERWRITES local edits made since the last sync."));let r=lt(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!r){console.log(f(" Local file already matches the remote content \u2014 advancing the sync base only.")),fr({cwd:e.cwd,profileName:e.profileName},o);return}console.log(re(` \u23BF Added ${r.added} line${ct(r.added)}, removed ${r.removed} line${ct(r.removed)}`));for(let c of r.lines)console.log(c);if(r.hidden>0&&console.log(f(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>Eu({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(f(" Skipped."));return}fr({cwd:e.cwd,profileName:e.profileName},o),console.log(A(` \u2713 Pulled ${o.path} (sync base advanced).`))}W();import{statSync as qu}from"node:fs";import{resolve as Bu}from"node:path";import{estimateBulkCost as Yu,planPartitions as Gu,readProjectConfig as Vu,resolveModelForOperation as zu,runPartitioned as Ku,trackedArticlePaths as Xu}from"document360-engine";var gr=3;function wr(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 yr(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function kr(e,t){return t.map(n=>{let o=0;try{o=qu(Bu(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function br(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:
|
|
224
224
|
- 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.
|
|
225
225
|
- 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.
|
|
226
226
|
- 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.
|
|
227
227
|
- Work only on these files:
|
|
228
228
|
`+e.paths.map(t=>`- ${t}`).join(`
|
|
229
|
-
`)}function xr(e,t,n){let o=e.reduce((p,h)=>p+h.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: ${fe(r)}\u2013${fe(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function $r(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),c=e.reduce((C,I)=>C+o(I),0),p=r.reduce((C,I)=>C+o(I),0),h=e.reduce((C,I)=>C+I.costUsd,0),b=e.reduce((C,I)=>C+I.outputTokens,0),x=n==="api"?`${fe(h)} total`:Be(b),D=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,y=C=>`${C} article${C===1?"":"s"}`,P=[];if(s.length===0)P.push(`Converted ${y(c)} (${D}) successfully \xB7 ${x}.`);else{P.push(`Converted ${p}/${y(c)} (${D}) \xB7 ${x}.`),P.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let C of s)P.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return P}async function
|
|
229
|
+
`)}function xr(e,t,n){let o=e.reduce((p,h)=>p+h.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: ${fe(r)}\u2013${fe(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function $r(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),c=e.reduce((C,I)=>C+o(I),0),p=r.reduce((C,I)=>C+o(I),0),h=e.reduce((C,I)=>C+I.costUsd,0),b=e.reduce((C,I)=>C+I.outputTokens,0),x=n==="api"?`${fe(h)} total`:Be(b),D=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,y=C=>`${C} article${C===1?"":"s"}`,P=[];if(s.length===0)P.push(`Converted ${y(c)} (${D}) successfully \xB7 ${x}.`);else{P.push(`Converted ${p}/${y(c)} (${D}) \xB7 ${x}.`),P.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let C of s)P.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return P}async function Ki(e,t){if(!Vu(t.cwd))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=wr(e),r=Xu(t.cwd,t.profileName);if(r.length===0)return console.log(v("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let s=yr(r,n);if(s.length===0)return console.log(v(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let c=Gu(s),p=`/convert${n?` --scope ${n}`:""} --run`,{model:h,forced:b}=zu(t.cwd,"light");if(!o){let x=Yu({files:kr(t.cwd,s),op:"convert",model:h});n&&console.log(f(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let D of xr(c,x,gr))console.log(D);return console.log(f(`Model: ${h}${b?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(f(`Run ${p} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Converting ${s.length} articles across ${c.length} partitions (\u2264${gr} agents at once) on ${h}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let x of Ku({cwd:t.cwd,partitions:c,promptFor:br,concurrency:gr,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:h}))if(x.type==="partition_status")x.status==="running"?console.log(f(` \u25B8 ${x.label} \u2014 converting\u2026`)):x.status==="done"?console.log(A(` \u2713 ${x.label}`)):console.log(v(` \u2717 ${x.label}`));else if(x.type==="run_done"){console.log("");let D=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let y of $r(x.results,c,D))console.log(x.ok?A(y):M(y))}}catch(x){console.log(v(`Convert run failed: ${x.message}`))}return console.log(""),{kind:"continue"}}W();import{statSync as Xi}from"node:fs";import{resolve as Ji}from"node:path";import{estimateBulkCost as Ju,planPartitions as Qu,readDocsPlan as Zu,readProjectConfig as Qi,DEFAULT_DOCS_DIR as ed,resolveModelForOperation as td,runPartitioned as nd}from"document360-engine";var od=3,rd=8;function vr(e){return e===void 0||!Number.isFinite(e)?od:Math.max(1,Math.min(Math.floor(e),rd))}function Cr(e){let t,n,o=!1,r=!1,s,c=h=>{let b=Number(h);return h!==void 0&&Number.isFinite(b)?b:void 0};for(let h=0;h<e.length;h++){let b=e[h];if(b==="--preview"||b==="--dry-run")o=!0;else if(b==="--rewrite"||b==="--force")r=!0;else{if(b==="--run"||b==="--yes"||b==="--all")continue;b==="--scope"?t=e[++h]:b?.startsWith("--scope=")?t=b.slice(8):b==="--concurrency"?s=c(e[++h]):b?.startsWith("--concurrency=")?s=c(b.slice(14)):b&&!b.startsWith("--")&&(n=b)}}let p=h=>h?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:p(t),path:p(n),preview:o,concurrency:s,rewrite:r}}function sd(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function id(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Pr(e,t,n){return n.filter(o=>{try{return Xi(Ji(e,t,o)).size===0}catch{return!0}})}function Rr(e,t,n){let o=new Map(t.map(r=>[r.path,r]));return n.map(r=>{let s=1;for(let c of o.get(r)?.sources??[])try{s+=Xi(Ji(e,c)).size}catch{}return{path:r,bytes:s}})}function Tr(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.
|
|
230
|
+
`:"";return`Run the write-article skill to author EACH documentation article listed below. For each path:
|
|
230
231
|
- It is relative to ${t}/. Look up its entry (matching "path") in .d360-writer/plan.json for its purpose and the source files it draws from (AGENT-PLAN.md has the same table).
|
|
231
232
|
- Read ONLY those source files plus any shared context you genuinely need, and ground every statement in them. Never invent UI labels, routes, or behaviour \u2014 if the source does not say it, omit it.
|
|
232
|
-
|
|
233
|
+
`+o+`- Write the finished article to ${t}/<path>, following the write-article structure and the project terminologyGlossary. Add the \`sources:\` frontmatter listing the files you actually read.
|
|
233
234
|
- Emit \`<!-- SCREENSHOT -->\` placeholders where a visual helps, but do NOT author capture specs now.
|
|
234
235
|
- 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.
|
|
235
236
|
Articles:
|
|
236
|
-
`+e.paths.map(
|
|
237
|
-
`)}function Sr(e,t,n){let o=e.reduce((c,p)=>c+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(c=>` \u2022 ${c.label} \u2014 ${c.paths.length} article${c.paths.length===1?"":"s"}`),"",`Estimated cost: ${fe(r)}\u2013${fe(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function Dr(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),c=e.reduce((C,I)=>C+o(I),0),p=r.reduce((C,I)=>C+o(I),0),h=e.reduce((C,I)=>C+I.costUsd,0),b=e.reduce((C,I)=>C+I.outputTokens,0),x=n==="api"?`${fe(h)} total`:Be(b),D=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,y=C=>`${C} article${C===1?"":"s"}`,P=[];if(s.length===0)P.push(`Wrote ${y(c)} (${D}) successfully \xB7 ${x}.`),P.push("Next \u2014 push them to Document360:"),P.push("/publish --all"),P.push("Or add screenshots first with /screenshot --all. Drafts are reviewable in the portal after publishing.");else{P.push(`Wrote ${p}/${y(c)} (${D}) \xB7 ${x}.`),P.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let C of s)P.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return P}function jr(e,t,n){let o=(
|
|
238
|
-
`)}var Ir="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function
|
|
239
|
-
`)}var Or="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
|
|
237
|
+
`+e.paths.map(r=>`- ${r}`).join(`
|
|
238
|
+
`)}function Sr(e,t,n){let o=e.reduce((c,p)=>c+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(c=>` \u2022 ${c.label} \u2014 ${c.paths.length} article${c.paths.length===1?"":"s"}`),"",`Estimated cost: ${fe(r)}\u2013${fe(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function Dr(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),c=e.reduce((C,I)=>C+o(I),0),p=r.reduce((C,I)=>C+o(I),0),h=e.reduce((C,I)=>C+I.costUsd,0),b=e.reduce((C,I)=>C+I.outputTokens,0),x=n==="api"?`${fe(h)} total`:Be(b),D=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,y=C=>`${C} article${C===1?"":"s"}`,P=[];if(s.length===0)P.push(`Wrote ${y(c)} (${D}) successfully \xB7 ${x}.`),P.push("Next \u2014 push them to Document360:"),P.push("/publish --all"),P.push("Or add screenshots first with /screenshot --all. Drafts are reviewable in the portal after publishing.");else{P.push(`Wrote ${p}/${y(c)} (${D}) \xB7 ${x}.`),P.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let C of s)P.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return P}function jr(e,t,n){let o=(Qi(e)?.docsDir??ed).replace(/\/+$/,""),r=t.map(p=>p.path);if(n.path){let p=sd(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=id(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 c=Pr(e,o,s);if(c.length===0){let p=n.scope?` under "${n.scope}"`:"",h=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${h} --rewrite to regenerate them all.`}}return{docsDir:o,targets:c,planCount:r.length}}async function Zi(e,t){if(!Qi(t.cwd))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let n=Zu(t.cwd);if(n.length===0)return console.log(v("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:c,rewrite:p}=Cr(e),{docsDir:h,targets:b,reason:x,rewriting:D}=jr(t.cwd,n,{scope:o,path:r,rewrite:p});if(b.length===0)return console.log(x?M(x):M("Nothing to write.")),{kind:"continue"};D&&console.log(M(`--rewrite: regenerating ${b.length} already-written article${b.length===1?"":"s"} (overwrites them; git has your baseline).`));let y=Qu(b),P=vr(c),{model:C,forced:I}=td(t.cwd,"standard"),_=!!r;if(s&&!_){let L=Ju({files:Rr(t.cwd,n,b),op:"write",model:C});o&&console.log(f(`Scope: ${o} (${b.length} pending).`));for(let Q of Sr(y,L,P))console.log(Q);return console.log(f(`Model: ${C}${I?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(f(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Writing ${b.length} article${b.length===1?"":"s"} across ${y.length} partition${y.length===1?"":"s"} (\u2264${P} agents at once) on ${C}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let L of nd({cwd:t.cwd,partitions:y,promptFor:Q=>Tr(Q,h,{rewrite:D||_}),concurrency:P,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:C}))if(L.type==="partition_status")L.status==="running"?console.log(f(` \u25B8 ${L.label} \u2014 writing\u2026`)):L.status==="done"?console.log(A(` \u2713 ${L.label}`)):console.log(v(` \u2717 ${L.label}`));else if(L.type==="run_done"){console.log("");let Q=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let de of Dr(L.results,y,Q))console.log(L.ok?A(de):M(de))}}catch(L){console.log(v(`Write run failed: ${L.message}`))}return console.log(""),{kind:"continue"}}W();import{existsSync as ad,readdirSync as ea,statSync as ta}from"node:fs";import{join as na}from"node:path";import{inputDir as ld,readProjectConfig as cd}from"document360-engine";var oa=/\.(md|markdown|pdf|txt)$/i;function Ar(e){let t=ld(e);if(!ad(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of ea(t)){let s=na(t,r),c=!1;try{c=ta(s).isDirectory()}catch{continue}if(c){if(r.startsWith("."))continue;let p=ud(s);p>0&&n.push({name:r,docCount:p})}else oa.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function ud(e){let t=0;for(let n of ea(e))try{ta(na(e,n)).isFile()&&oa.test(n)&&t++}catch{}return t}function Er(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 Vn(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(`
|
|
239
|
+
`)}var Ir="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function ra(e,t){let n=t?.cwd??process.cwd();if(!cd(n))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=Ar(n);if(o.length===0&&r===0)return console.log(f(Ir)),{kind:"continue"};let s=e.join(" ").trim();if(!s){if(o.length>1){console.log(f("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let h of o)console.log(` ${h.name} ${f(`(${h.docCount} doc${h.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let p=o[0]?.name??"";return{kind:"forward-to-agent",prompt:Vn(p),display:p?`/draft ${p}`:"/draft"}}let c=Er(o,s);return{kind:"forward-to-agent",prompt:Vn(c??"",c?void 0:s),display:`/draft ${s}`}}W();import{listOpenForDocs as dd,readProjectConfig as pd}from"document360-engine";function Nr(e){try{return dd(e).filter(t=>t.kind==="request").length}catch{return 0}}function _r(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function Mr(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(`
|
|
240
|
+
`)}var Or="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 sa(e,t){let n=t?.cwd??process.cwd();if(!pd(n))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=_r(e);if(!r&&Nr(n)===0)return console.log(f(Or)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:Mr(r,o),display:s}}W();import{search as fd}from"@inquirer/prompts";import{findByName as md,getSession as hd,listSessions as gd,relativeTime as aa}from"document360-engine";async function la(e,t){let n=gd(t.cwd).filter(o=>o.uuid!==t.currentUuid());if(n.length===0)return console.log(f("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=md(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(v(`No session matches "${o}".`)),ia(n),{kind:"continue"})}if(!process.stdin.isTTY)return ia(n),console.log(f("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>fd({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let c=(s??"").toLowerCase();return n.filter(p=>!c||p.name.toLowerCase().includes(c)||p.firstPrompt.toLowerCase().includes(c)).map(p=>({name:`${p.name} ${aa(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=hd(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function ia(e){console.log("");for(let t of e.slice(0,15))console.log(` ${N(t.name)} ${f(aa(t.updatedAt))}`),console.log(` ${f(t.firstPrompt.slice(0,80))}`);console.log("")}W();import{renameSession as wd}from"document360-engine";function Lr(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 ca(e,t){let n=Lr(e.join(" "));if(!n)return console.log(v("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(wd(o,n)?console.log(A(`\u2713 Session renamed to "${n}"`)):console.log(v("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(A(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as ua,readProjectConfig as yd,writeProjectConfig as kd}from"document360-engine";W();function Ur(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=yd(e);if(!o)return"No .d360-writer.json \u2014 run /init first.";if(o.profiles?.[t])return`Profile "${t}" already exists.`;let r=n??t;return ua().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},kd(o,e),null):`Unknown environment "${r}". Known: ${ua().join(", ")} (or add the profile with explicit URLs in .d360-writer.json).`}async function da(e,t){let n=e[0];if(!n)return jn(t.cwd),{kind:"continue"};if(n==="add"){let o=Ur(t.cwd,e[1],e[2]);return o?(console.log(v(o)),{kind:"continue"}):(console.log(A(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${N(`/profile ${e[1]}`)} then ${N("/login")}`),{kind:"continue"})}return An(t.cwd,n),En(t.cwd,n),console.log(f(" Restarting agent for the new profile\u2026")),{kind:"clear"}}W();import{select as bd}from"@inquirer/prompts";import{readProjectConfig as xd,readUserConfig as pa,resolveModelSetting as Wr,writeUserConfig as fa}from"document360-engine";var Se=[{value:null,label:"Auto",desc:"Engine right-sizes per task \u2014 Sonnet for routine work, Opus for analysis (recommended)"},{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 4.8 \xB7 best for everyday complex tasks"},{value:"sonnet",label:"Sonnet",desc:"Sonnet 4.6 \xB7 efficient for routine tasks"},{value:"haiku",label:"Haiku",desc:"Haiku 4.5 \xB7 fastest for quick answers"}];function zn(e){if(e.model===null||e.source==="claude-settings")return 0;let t=e.model.toLowerCase(),n=Se.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function $d(e){switch(e.source){case"project":return".d360-writer.json defaultModel (team setting)";case"user":return"~/.document360-writer/config.json (your /model setting)";case"env":return"ANTHROPIC_MODEL environment variable";case"claude-settings":return"Claude Code's own settings (~/.claude/settings.json)";case"claude-default":return"Claude Code default (no override configured)"}}function on(e,t){let n=()=>{let s=Wr(e);return s.source==="project"||s.source==="user"||s.source==="env"?s.model??void 0:void 0};if(t==="default"){let s=pa();return s.defaultModel?(delete s.defaultModel,fa(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${Wr(e).model??"Claude Code default"} (applies from your next message)`],changed:!0,effective:n()}):{lines:["No personal model override set \u2014 nothing to clear."],changed:!1,effective:void 0}}fa({...pa(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=xd(e)?.defaultModel;return r&&o.push(`\u26A0 .d360-writer.json sets defaultModel "${r}" \u2014 the team setting overrides yours until it is removed.`),{lines:o,changed:!0,effective:n()}}async function ma(e,t){let n=e[0]?.trim();if(!n){let c=Wr(t.cwd);if(!process.stdin.isTTY)return console.log(`${ve("Model:")} ${N(c.model??"Claude Code default")}`),console.log(f(` source: ${$d(c)}`)),console.log(f(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let p=zn(c),h;try{h=await t.withPausedInput(()=>bd({message:`Select model (current: ${c.model??"Claude Code default"})`,default:Se[p].value,choices:Se.map((y,P)=>({name:`${y.label}${P===p?" \u2714":""}`,value:y.value,description:y.desc}))}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}let{lines:b,changed:x,effective:D}=on(t.cwd,h??"default");for(let y of b)console.log(y.startsWith("\u26A0")?M(y):y.startsWith("\u2713")?A(y):f(y));return x&&await t.setModel(D),{kind:"continue"}}let{lines:o,changed:r,effective:s}=on(t.cwd,n);for(let c of o)console.log(c.startsWith("\u26A0")?M(c):c.startsWith("\u2713")?A(c):f(c));return r&&await t.setModel(s),{kind:"continue"}}Kn();async function ba(e,t){return await t.withPausedInput(()=>St(t.cwd)),{kind:"clear"}}async function xa(e,t){return await t.withPausedInput(()=>Ks(t.cwd,t.profileName)),{kind:"clear"}}W();import{resolveActiveProfile as Od}from"document360-engine";async function $a(e,t){let n=!1;try{n=Od(t.cwd).production}catch{}return n?(console.log(M("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(f("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}W();var va=async(e,t)=>{try{await t.withPausedInput(()=>Dn({}))}catch(n){console.log(v(`Login failed: ${n.message}`))}return{kind:"continue"}};W();import{resolveActiveProfile as Ld,clearTokens as Ud,clearProfileProject as Wd}from"document360-engine";async function Ca(e,t){let n;try{n=Ld(t.cwd,t.profileName).name}catch(r){return console.log(v(r.message)),{kind:"continue"}}let o=Ud(n);return Wd(t.cwd,n),console.log(o?A(`\u2713 Signed out of "${n}" and cleared its project/workspace selection.`):f(`Profile "${n}" was not signed in. Cleared any project/workspace selection.`)),console.log(f("Run /login to sign in and pick a project.")),{kind:"continue"}}import{existsSync as Pa}from"node:fs";import{isAbsolute as Fd,join as Hd,resolve as qd}from"node:path";import{readProjectConfig as Bd,screenshotPlaceholderIds as Yd,DEFAULT_CAPTURE_DIR as Gd,DEFAULT_OUTPUT_DIR as Vd}from"document360-engine";var Ra=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Hr(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?Ra(n[1]):void 0};let o=n[0];return!o||o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:Ra(o),setup:t}:{mode:"single",id:o}}function qr(e,t){let n=Bd(e),o=n?.captureDir??Gd,r=n?.outputDir??Vd,s=(c,p)=>Fd(c)?Hd(c,p):qd(e,c,p);return Yd(e,{scope:t}).map(({id:c,file:p})=>{let h=Pa(s(r,`${c}.png`))?"captured":Pa(s(o,`${c}.spec.ts`))?"spec":"placeholder";return{id:c,file:p,state:h}})}var zd={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},Kd={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function Br(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 c of e.filter(p=>p.file===s))r.push(` ${zd[c.state]} ${c.id.padEnd(34)} ${Kd[c.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function Ta(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(`
|
|
240
241
|
`),"","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(`
|
|
241
242
|
`)}async function Xn(e,t){let n=Hr(e);if(n.mode==="list"){let c=t?.cwd??process.cwd();for(let p of Br(qr(c,n.scope),n.scope))console.log(p);return{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 the spec path and any TODO data-testids or data to stage.`].join(`
|
|
242
243
|
`),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(`
|
|
243
|
-
`),s=n.mode==="scope"?`/screenshot ${n.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:r,display:s}}import{existsSync as
|
|
244
|
-
`),display:"/capture-setup"}}var
|
|
245
|
-
`)}async function
|
|
246
|
-
`)}var
|
|
247
|
-
`).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function
|
|
248
|
-
`).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let c=
|
|
249
|
-
`);return{lines:s.slice(0,t).map(c=>
|
|
250
|
-
|
|
251
|
-
`),console.log(`${
|
|
252
|
-
`),console.log(f(` (${e.inputTokens}\u2192${e.outputTokens} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(
|
|
253
|
-
`),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){
|
|
254
|
-
`)}import{existsSync as
|
|
255
|
-
\u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close`})]})}var
|
|
256
|
-
`)){let c=s.trim().replace(
|
|
257
|
-
`)}function
|
|
258
|
-
`)}function
|
|
259
|
-
`)||e.length>200}function
|
|
260
|
-
`).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function
|
|
261
|
-
`)){if(s.length===0)o.push({start:r,end:r});else for(let c=0;c<s.length;c+=n)o.push({start:r+c,end:r+Math.min(c+n,s.length)});r+=s.length+1}return o.length>0?o:[{start:0,end:0}]}function mo(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function
|
|
244
|
+
`),s=n.mode==="scope"?`/screenshot ${n.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:r,display:s}}import{existsSync as Xd,readFileSync as Jd}from"node:fs";import{isAbsolute as Qd,join as Zd,resolve as ep}from"node:path";import{readProjectConfig as tp,DEFAULT_CAPTURE_DIR as np}from"document360-engine";async function sn(){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(`
|
|
245
|
+
`),display:"/capture-setup"}}var Sa="-".repeat(64);function Yr(e){let t=np;try{let x=tp(e);x?.captureDir&&(t=x.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=Qd(t)?Zd(t,"CAPTURE-TESTID-REQUESTS.json"):ep(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!Xd(n))return null;let o;try{let x=JSON.parse(Jd(n,"utf8").replace(/^/,""));o=Array.isArray(x?.requests)?x.requests:[]}catch{return null}if(o.length===0)return null;let r=new Set(o.map(x=>x.file).filter(Boolean)).size,s=o.length,c=`${s} data-testid attribute${s===1?"":"s"}`,p=`${r} source file${r===1?"":"s"}`,h=`${t}/CAPTURE-TESTID-REQUESTS.md`,b=`${t}/CAPTURE-TESTID-REQUESTS.json`;return[`\u{1F4CB} Developer hand-off \u2014 ${c} 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.","",Sa,`Read ${h} and ${b}. They list ${c} 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.",Sa]}at();W();import{listOpenForDocs as op,readProjectConfig as rp}from"document360-engine";function Gr(e){try{return op(e).length}catch{return 0}}function Vr(){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 (a reply to a 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(`
|
|
246
|
+
`)}async function Da(e,t){let n=t?.cwd??process.cwd();return rp(n)?Gr(n)===0?(console.log(f("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:Vr(),display:"/inbox"}:(console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{listOpenHints as sp,listOpenForDocs as ip,readProjectConfig as ap,computeSyncStatus as lp,planPull as cp,applyPull as up}from"document360-engine";function Nt(e){let t=0,n=0,o=0;try{t=sp(e).length}catch{}try{let r=ip(e);n=r.filter(s=>s.kind==="request").length,o=r.filter(s=>s.kind==="answer").length}catch{}return{hints:t,requests:n,answers:o}}function _t(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"}`),t.length?t.join(", "):null}function Kr(e){return{publish:e.includes("--publish")}}function Xr({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 reconciled before this run: clean portal edits were pulled into local, and any conflicts / new-portal-articles were surfaced to the user. Do NOT re-pull. 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) AND d360_inbox (open requests + answers).","3. 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), and fold any answers into the affected article(s) + the architecture brief.","4. 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.","5. Write/update the articles as drafts, grounded in the cited sources.","6. Close the loop: stamp consumed hints, and mark handled messages status: done with resulting_articles.","7. Push the drafts to Document360.","8. 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?"9. 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(`
|
|
247
|
+
`)}var dp={status:lp,plan:cp,apply:up};async function Jr(e,t=dp){let n={pulled:[],conflicts:[],untrackedRemote:[],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")n.untrackedRemote.push(r.title??r.articleId??"(untitled)");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 zr=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Jn=e=>e===1?"":"s";function Qr(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${Jn(e.pulled.length)} into local: ${zr(e.pulled)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${Jn(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${zr(e.conflicts)}`),e.untrackedRemote.length&&t.push(`\u2139 ${e.untrackedRemote.length} new article${Jn(e.untrackedRemote.length)} in the portal aren't local yet \u2014 run /pull to bring them in: ${zr(e.untrackedRemote)}`),e.failed.length&&t.push(`\u26A0 ${e.failed.length} pull${Jn(e.failed.length)} failed \u2014 left for /pull.`),t}async function ja(e,t){let n=t?.cwd??process.cwd();if(!ap(n))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Ne(n,t?.profileName);if(!o.ok)return console.log(v(o.reason)),{kind:"continue"};let{publish:r}=Kr(e);console.log(f("Reconciling with Document360 (pulling any portal changes)\u2026"));let s=await Jr({cwd:n,profileName:t?.profileName});for(let p of Qr(s))console.log(p.startsWith("\u2713")?A(p):p.startsWith("\u2139")?f(p):M(p));let c=_t(Nt(n));return console.log(f(c?`Catching up on ${c}\u2026`:"Checking for code changes the builder didn't hint\u2026")),{kind:"forward-to-agent",prompt:Xr({publish:r}),display:`/catch-up${r?" --publish":""}`}}W();import{spawn as pp}from"node:child_process";var ut="document360-writer",Qn=`npm i -g ${ut}@latest`;async function Zn(){let e=process.platform==="win32";return new Promise(t=>{try{let n=pp(`npm i -g ${ut}@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 Aa(){return console.log(f(`Updating ${ut}\u2026`)),(await Zn()).ok?console.log(A("\u2713 Updated. Exit (/exit) and relaunch d360-writer to apply.")):console.log(v(`Update failed \u2014 run manually: ${Qn}`)),{kind:"continue"}}W();at();import{existsSync as Zr,rmSync as fp}from"node:fs";import{basename as Ea,resolve as es}from"node:path";import{execFileSync as mp}from"node:child_process";import{input as hp}from"@inquirer/prompts";import{readProjectConfig as gp,devHintsGuidePath as wp}from"document360-engine";var yp=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],kp=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),eo=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),Ia=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function Na(e){let t=eo(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:Ia(t)?!0:kp.has(t)}function ts(e){let t=null;try{t=gp(e)}catch{t=null}let n=new Set(yp);for(let o of[eo(t?.docsDir),eo(t?.captureDir),eo(t?.outputDir)])o&&Ia(o)&&n.add(o);return[...n].filter(o=>Na(o)&&Zr(es(e,o)))}function ns(e,t){let n=[],o=[];for(let r of t){if(!Na(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{fp(es(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function _a(e,t){try{return mp("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
|
|
248
|
+
`).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function bp(e){return _a(e,".d360-writer/hints")}function xp(e){return _a(e,".d360-writer/messages")}function os(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=bp(e),o=xp(e),r=Zr(es(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: ${Ea(e)}`]}async function Ma(e,t){let n=ts(t.cwd);for(let h of os(t.cwd,n))console.log(n.length===0?f(h):h);if(n.length===0)return{kind:"continue"};let o=Ea(t.cwd);if((await t.withPausedInput(()=>hp({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(M("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=Zr(wp(t.cwd)),{removed:c,failed:p}=ns(t.cwd,n);console.log(A(`\u2713 Reset complete \u2014 removed ${c.length} item${c.length===1?"":"s"}. The repo is back to its original state.`));for(let h of p)console.log(v(` \u2717 ${h.path}: ${h.error}`));if(s){for(let h of Ln())console.log(h);console.log(f("(Select and copy the prompt above to paste into your coding agent.)"))}return console.log(f("Set up d360-writer again with /init (then /login, /workspace).")),{kind:"continue"}}W();import{lintDocs as $p}from"document360-engine";function rs(e){if(e.length===0)return["\u2713 No internal-noun leaks \u2014 no codenames, skill names, or tool names found 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} internal-noun leak${e.length===1?"":"s"} in ${t.size} article${t.size===1?"":"s"} \u2014 engine internals that shouldn't reach readers:`];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}async function Oa(e,t){console.log(f("Linting the docs for leaked engine internals\u2026"));let n=$p({cwd:t.cwd}),o=rs(n);for(let r of o)console.log(n.length===0?A(r):M(r));return console.log(""),{kind:"continue"}}var La={help:Vo,"?":Vo,clear:li,exit:zo,quit:zo,init:Pi,mcp:Wn,publish:Ui,audit:nn,scope:Fi,pull:zi,convert:Ki,write:Zi,draft:ra,document:sa,resume:la,rename:ca,profile:da,model:ma,doctor:rn,workspace:ba,project:xa,"allow-prod":$a,login:va,logout:Ca,screenshot:Xn,"capture-setup":sn,devhints:hi,inbox:Da,"catch-up":ja,update:Aa,reset:Ma,lint:Oa};function Ua(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}at();W();var vp={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"},Fa=160,is=200,Ha=40;function we(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function Wa(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}: ${we(typeof r=="string"?r:JSON.stringify(r),Ha)}`);return t.length>4&&n.push("\u2026"),we(n.join(", "),Fa)}var Ye=e=>typeof e=="string"&&e?e:null,ss=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function Cp(e){let t=Ye(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 Pp(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=Ye(t.title);if(!o)return null;let r=Cp(t.local_path);return n("Create article",`"${we(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=Ye(t.title),r=ss(t.article_id);return n("Update article",o?`"${we(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",ss(t.article_id)?`id ${ss(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",Ye(t.name)?`"${we(Ye(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=Ye(t.file_path);return n("Upload image",o?we(o.replace(/\\/g,"/").split("/").pop()??o,60):null)}case"d360_sync_status":return n("Check sync status",null);default:return null}}function to(e,t){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,r="",...s]=e.split("__"),c=s.join("__");if(r==="document360"){let b=Pp(c,t);if(b)return b}let p=c.replace(/^d360_/,"").replace(/_/g," ");return{title:`${r==="document360"?"Document360":r.charAt(0).toUpperCase()+r.slice(1)}: ${p}`,sep:" ",arg:Wa(t)}}let n=vp[e],o=n?t[n]:void 0;return typeof o=="string"&&o?{title:e,sep:"",arg:we(o,Fa)}:{title:e,sep:"",arg:Wa(t)}}function Rp(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 Tp(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(Rp).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>we(r,is))]}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}: ${we(String(r),Ha)}`);return n.length>0?[we(n.join(" \xB7 "),is)]:null}return null}function Sp(e){let t=Ye(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function Dp(e,t,n){switch(e){case"d360_create_article":{let o=Sp(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=Ye(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 ${we(o[0],120)}`:""}`]}default:return null}}function no(e,t=4,n,o){let r=e.replace(/\r\n/g,`
|
|
249
|
+
`).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let c=Dp(n.slice(18),o,r);if(c)return{lines:c,hidden:0}}let s=Tp(r)??r.split(`
|
|
250
|
+
`);return{lines:s.slice(0,t).map(c=>we(c,is)),hidden:Math.max(0,s.length-t)}}function oo(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function ro(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 so(e){try{let t=JSON.parse(e),o=(Array.isArray(t)?t[0]:t)?.url;return typeof o=="string"&&/^https?:\/\//.test(o)?o:null}catch{return null}}var Fp=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Hp(e,t,n,o){if(Fp.test(e))try{let r=Ga(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,c=ro(t,n),p=so(n);e.endsWith("publish_article")&&p&&console.log(N(` \u2B95 Live: ${p}`)),c&&s&&console.log(N(` \u2B95 Preview: ${oo(r.connection.portalUrl,s,c,r.project.languageCode??"en")}`))}catch{}}async function Va(e=process.cwd(),t="auto",n){let o=Ap(t);o.kind==="none"&&(console.error(""),console.error(v("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${N("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${N('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${N("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${N("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),qp(e,n),o.kind==="subscription"&&(o.stored?console.log(f(" Using your Claude subscription (no API key set).")):console.log(f(" No API key or stored Claude Code login found \u2014 trying your Claude session anyway.")),console.log(""));let r=!1,s=as({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1},p=jp({input:process.stdin,output:process.stdout}),h=[],b=null,x=!1;p.on("line",P=>{if(b){let C=b;b=null,C(P)}else h.push(P)}),p.on("close",()=>{if(x=!0,b){let P=b;b=null,P(null)}});function D(){return h.length>0?Promise.resolve(h.shift()):x?Promise.resolve(null):(process.stdout.write(N("> ")),new Promise(P=>{b=P}))}let y={cwd:e,profileName:n,allowProdWrites:()=>r,restartAgent:()=>{s.close(),s=as({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>c.uuid,setPendingName:P=>{c.pendingName=P},setModel:async P=>s.setModel(P),withPausedInput:async P=>{p.pause();try{return await P()}finally{p.resume()}}};try{for(;;){let P=await D();if(P===null)break;let C=P.trim();if(C){if(C.startsWith("/")){let I=Ua(C);if(!I)continue;let _=La[I.name];if(!_){console.log(v(`Unknown command: /${I.name}`)),console.log(f("Type /help for the list."));continue}let L=await _(I.args,y);if(L.kind==="exit")break;if(L.kind==="clear"){y.restartAgent();continue}if(L.kind==="allow-prod"){r=!0,y.restartAgent(),console.log(A("\u2713 Production writes authorized for this session.")),console.log("");continue}if(L.kind==="resume"){s.close(),s=as({cwd:e,resume:L.uuid,profileName:n,allowProdWrites:r});let Q=Ep(L.uuid);c={uuid:L.uuid,firstPrompt:Q?.firstPrompt??null,titleFired:!0},Ya(L.uuid),console.log(A(`\u2713 Resumed "${L.name}"`)),console.log("");continue}L.kind==="forward-to-agent"&&(c.firstPrompt||(c.firstPrompt=L.display??L.prompt),await Ba(s,L.prompt,o,c,e));continue}c.firstPrompt||(c.firstPrompt=C),await Ba(s,C,o,c,e)}}}finally{s.close(),p.close()}}function qp(e,t){console.log(""),console.log(Gt("document360-writer")),console.log(f(` cwd: ${e}`));let n=Op(e);if(console.log(f(` model: ${n.model??"auto (engine right-sizes per task)"}${n.model?` (${n.source})`:""}`)),console.log(Bp(e,t)),!Lp(e))console.log(M(" First run: /init (scaffolds config + prints the builder hand-off prompt) \u2192 /login, then ask me to write the docs."));else{try{Mn(e);for(let o of On(e))console.log(M(` ${o}`))}catch{}try{let o=_t(Nt(e));o&&console.log(M(` \u{1F4CB} ${o} from the repo's coding agent \u2014 run /catch-up.`))}catch{}}console.log(f(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function Bp(e,t){try{let n=Ga(e,t),o=n.production?M(" \u26A0 PRODUCTION"):"",r=Wp(n.name);if(!r)return f(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...qa(r.idToken)??{},...qa(r.accessToken)??{}},c=s.email??s.preferred_username??"signed in";return Up(r)&&!r.refreshToken?M(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):f(` Document360: ${c} \xB7 profile "${n.name}"${o}`)}catch(n){return f(` Document360: ${n.message.split(".")[0]}`)}}function Yp(){console.error(""),console.error(`Sign in with your Claude subscription: run ${N("claude")} once, then retry.`),console.error(` (No Claude Code? ${N("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${N("https://console.anthropic.com/settings/keys")}`)}function Gp(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;_p({uuid:t,name:r??Np(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function Vp(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||Mp(o,t).then(r=>{r&&Ip(n,r)}).catch(()=>{})}async function Ba(e,t,n,o,r){let s=new Map;for await(let c of e.send(t))zp(c,o,r,n,s)}function zp(e,t,n,o,r){switch(e.type){case"session":t.uuid||Gp(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let s=to(e.name,e.input);s&&(process.stdout.write(`
|
|
251
|
+
|
|
252
|
+
`),console.log(`${A("\u25CF")} ${ve(s.title)}${s.arg!==null?re(`${s.sep}(${s.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let s=lt(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!s)break;let c=p=>p===1?"":"s";console.log(re(` \u23BF Added ${s.added} line${c(s.added)}, removed ${s.removed} line${c(s.removed)}`));for(let p of s.lines)console.log(p);s.hidden>0&&console.log(f(` \u2026 +${s.hidden} more diff lines`));break}case"tool_result":{let s=r.get(e.id);if(!s)break;r.delete(e.id);let c=no(e.output,4,e.isError?void 0:s.name,s.input),p=e.isError?v:re;c.lines.forEach((h,b)=>console.log(p((b===0?" \u23BF ":" ")+h))),c.hidden>0&&console.log(f(` \u2026 +${c.hidden} lines`)),e.isError||Hp(s.name,s.input,e.output,n);break}case"result":process.stdout.write(`
|
|
253
|
+
`),console.log(f(` (${e.inputTokens}\u2192${e.outputTokens} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(Ya(t.uuid),t.titleFired||Vp(t,n));break;case"error":console.error(""),console.error(v(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&Yp();break}}import{render as cm}from"ink";import{resolveAuth as um}from"document360-engine";import{useCallback as G,useEffect as Pe,useMemo as fs,useRef as X,useState as H}from"react";import{Box as ne,Text as T,useApp as pf,useInput as ff,useStdout as mf}from"ink";import{existsSync as Ge,readFileSync as ms,readdirSync as ko}from"node:fs";import{spawnSync as hf}from"node:child_process";import{basename as ln,isAbsolute as gf,join as dt}from"node:path";import{createSession as bl,classifyClaudeAuth as ys,CLAUDE_CODE_SETUP_HINT as wf,loginPkce as yf,toStoredTokens as kf,saveTokens as bf,getAccessToken as xf,resolveActiveProfile as ue,resolveProjectId as $f,getArticle as vf,decodeJwtClaims as Ot,isExpired as Oe,loadTokens as Ve,clearTokens as Cf,clearProfileProject as Pf,setTitle as Rf,slugify as Tf,touchSession as hs,upsertSession as Sf,generateTitle as xl,findByName as Df,listSessions as jf,renameSession as Af,suggestNextAction as Ef,readProjectConfig as ee,writeProjectConfig as $l,resolveModelSetting as ks,loadProfileMap as yo,applyPull as If,computeSyncStatus as vl,countLocalAhead as Nf,lintDocs as _f,compareRemoteSources as Mf,planPull as Of,establishBaselines as Lf,rebaselineServerMeta as Uf,inventoryRepo as Wf,knownEnvironments as Ff,resolveEnvironment as Hf,planPartitions as gs,partitionEvenly as qf,screenshotPlaceholderIds as Bf,trackedArticlePaths as Yf,runPartitioned as ho,estimateBulkCost as Cl,resolveModelForOperation as go,readDocsPlan as Pl,checkForUpdate as Gf,detectInstallKind as Vf,isSelfUpdatable as zf,devHintsGuidePath as bs,toolFeedbackPath as Kf,reconcileToolFeedback as Xf,DEFAULT_DOCS_DIR as cn,setProfileProject as Jf,writeCrashLog as Qf}from"document360-engine";at();import{spawn as za}from"node:child_process";function Kp(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function Xp(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?za([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):za(e,t,{stdio:["pipe","ignore","ignore"]});r.on("error",()=>o(!1)),r.on("close",c=>o(c===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 Ka(e){for(let[t,n]of Kp())if(await Xp(t,n,e))return!0;return!1}var Jp=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function ls(e,t){if(t.closed)return e;let n=e.split(`
|
|
254
|
+
`),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){Jp.test(s)&&(t.cueSeen=!0);continue}let c=/^(\s{0,3})[-*•]\s+(.*)$/.exec(s);c?(n[r]=`${c[1]}${++t.num}. ${c[2]}`,o=!0):o&&s.trim()!==""&&/^\S/.test(s)&&(t.closed=!0)}return n.join(`
|
|
255
|
+
`)}import{existsSync as Qp,mkdirSync as Zp,readFileSync as ef,writeFileSync as tf}from"node:fs";import{join as Xa}from"node:path";import{writerDir as nf}from"document360-engine";function Ja(e){return Xa(nf(e),".sessions")}function Qa(e,t){return Xa(Ja(e),`${t}.json`)}function Za(e,t,n){try{Zp(Ja(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");tf(Qa(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function cs(e,t){try{let n=Qa(e,t);if(!Qp(n))return[];let o=JSON.parse(ef(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var of=e=>`\x1B]0;${e}\x07`,rf=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function el(e){process.stdout.isTTY&&process.stdout.write(e)}function Mt(e){el(of(e))}function io(e){el(rf(e))}var ao=["\xB7 "," \xB7"],lo="\u{1F7E3}";Kn();var co=[{name:"init",usage:"/init",desc:"Pick an environment, scaffold .d360-writer.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:"mcp",usage:"/mcp [list|add|remove]",desc:"Connect MCP servers (Notion, Linear, \u2026)",group:"start"},{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 [--list|id|--all|path]",desc:"--list: status; else author capture specs (bulk also refreshes the capture checklist; --no-setup skips)",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:"lint",usage:"/lint",desc:"Check generated docs for leaked engine internals (agent codename, skill names, d360_* tool names) \u2014 deterministic, no tokens",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:"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:"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:"Reset the conversation (resumable)",group:"session"},{name:"help",usage:"/help",desc:"Show this help",group:"session"},{name:"exit",usage:"/exit",desc:"Quit",group:"session"}],tl={"/catch-up":"write up everything your builder flagged","/audit":"check the code for anything new or missing in the docs","/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","/init":"set up this repo","/screenshot":"generate screenshots","/doctor":"run a health check"};function nl(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(tl[n])return tl[n];let o=co.find(r=>r.name===t);return o?o.desc:""}function ol(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return co.filter(n=>n.name.startsWith(t))}function rl(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}W();import{Box as sl,Text as se}from"ink";import{jsx as ae,jsxs as uo}from"react/jsx-runtime";function sf({row:e}){switch(e.t){case"head":return ae(se,{color:F,bold:!0,children:e.s});case"text":return ae(se,{children:e.s});case"dim":return ae(se,{dimColor:!0,children:e.s});case"sub":return ae(se,{bold:!0,dimColor:!0,children:e.s});case"good":return ae(se,{color:"green",children:e.s});case"step":return uo(se,{children:[ae(se,{color:F,children:`${e.n}. `}),e.s]});case"cmd":return uo(se,{children:[" ",ae(se,{color:F,children:e.name.padEnd(20)}),ae(se,{dimColor:!0,children:e.s})]});case"gap":return ae(se,{children:" "})}}function il({tab:e,width:t}){let n=Ce[e]??Ce[0],o=6+Ce.reduce((s,c)=>s+c.label.length+4,0),r="\u2500".repeat(Math.min(o,Math.max(t-1,20)));return uo(sl,{flexDirection:"column",paddingX:1,children:[uo(se,{children:[ae(se,{color:F,bold:!0,children:"Help "}),Ce.map((s,c)=>c===e?ae(se,{color:"white",backgroundColor:F,bold:!0,children:` ${s.label} `},s.key):ae(se,{dimColor:!0,children:` ${s.label} `},s.key))]}),ae(se,{color:F,children:r}),ae(sl,{flexDirection:"column",marginTop:1,children:n.rows.map((s,c)=>ae(sf,{row:s},c))}),ae(se,{dimColor:!0,children:`
|
|
256
|
+
\u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close`})]})}var af=/^(?:\d+[.)]|[-*•])\s+/;function al(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
|
|
257
|
+
`)){let c=s.trim().replace(af,""),p=c.match(/^`([^`]+)`$/);p&&(c=p[1].trim());let h=c.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!h||!o.has(h[1].toLowerCase()))continue;let b=`/${h[1].toLowerCase()}${h[2]?` ${h[2]}`:""}`;if(r.includes(b)||r.push(b),r.length>=n)break}return r}W();function an(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function _e(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function us(e){return e.replace(/^[\w.-]+\//,"")}var po=16,ll={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function ds(e){return e.trim().split(/\s+/).slice(1).join(" ")}function cl(e,t){let n=ds(t);return e.some(r=>r.trim()===t.trim()||!!n&&ds(r)===n)?e.filter(r=>r.trim()!==t.trim()&&!(n&&ds(r)===n)):[]}var lf='\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 cf(e,t){switch(e){case"/write":return"finish the planned articles that aren\u2019t written yet";case"/catch-up":return"write up everything your builder flagged";case"/audit":return t?"also scan the code for other changes":"check the code for anything new or missing in the docs";case"/pull":return"pull edits + new articles from Document360";case"/publish":return"push your local changes up to Document360";default:return""}}function Me(e){return e===1?"":"s"}function uf(e){switch(e){case"/write":return"it finishes the articles already planned";case"/catch-up":return"it clears everything your builder queued";case"/audit":return"it shows what the latest code changes touch";case"/pull":return"it reconciles anything changed on Document360";case"/publish":return"it pushes your local edits up to Document360";default:return"it\u2019s the most useful next step"}}function ps(e,t,n){let o=[];e.pendingWrites>0&&o.push(` \u2022 ${e.pendingWrites} planned article${Me(e.pendingWrites)} still unwritten`),e.localAhead>0&&o.push(` \u2022 ${e.localAhead} article${Me(e.localAhead)} changed locally \u2014 ready to publish`),e.pendingText&&o.push(` \u2022 your builder left ${e.pendingText}`),e.behind>0&&o.push(` \u2022 ${e.behind} code change${Me(e.behind)} since your last docs check`);let r=o.length>0?["Welcome back \u2014 where your docs stand:",...o,`I\u2019d start with ${t[0]} \u2014 ${uf(t[0])}.`]:[`Welcome back. Your ${e.tracked} tracked article${Me(e.tracked)} are all in sync.`];return r.push("",...t.map((s,c)=>` ${c+1} ${s.padEnd(9)} ${cf(s,n)}`),"Or just tell me what to write or update."),r.join(`
|
|
258
|
+
`)}function ul(e){if(!e.ready)return{kind:"idle"};let t=!!e.pendingText;if(!e.hasDocs)return{kind:"noDocs",note:lf,ghost:"write the docs for this repo",title:t?`\u{1F4CB} Your builder left ${e.pendingText} for the docs:`:null,options:t?["/catch-up","/audit"]:["/audit"]};if(e.pendingWrites>0){let r=t?["/write","/catch-up"]:["/write","/audit"],s=`\u{1F4DD} ${e.pendingWrites} planned article${Me(e.pendingWrites)} not written yet \u2014 pick up where you left off:`;return{kind:"actions",note:ps(e,r,t),title:s,options:r}}if(e.localAhead>0){let r=t?["/publish","/catch-up"]:["/publish","/audit"],s=`\u{1F4E4} ${e.localAhead} article${Me(e.localAhead)} changed locally \u2014 ready to publish to Document360:`;return{kind:"actions",note:ps(e,r,t),title:s,options:r}}if(!t&&e.behind>0&&e.autoAudit&&e.allowAutoAudit)return{kind:"autoAudit",note:`\u{1F4CB} ${e.behind} code change${Me(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`};let n=t?["/catch-up","/audit"]:["/audit","/pull"],o=t?`\u{1F4CB} Your builder left ${e.pendingText} for the docs:`:e.behind>0?`\u{1F4CB} ${e.behind} code change${Me(e.behind)} since your last docs check \u2014 /audit to see what needs updating (or /audit --auto on to run it for you):`:`\u{1F4DA} ${e.tracked} article${Me(e.tracked)} tracked for "${e.profileName}". What next?`;return{kind:"actions",note:ps(e,n,t),title:o,options:n}}var df=/\[Pasted text #\d+ \+\d+ lines?\]/g;function dl(e){return e.replace(/\r\n?/g,`
|
|
259
|
+
`)}function pl(e){return e.includes(`
|
|
260
|
+
`)||e.length>200}function fl(e,t){let n=t.split(`
|
|
261
|
+
`).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function ml(e,t){return e.replace(df,n=>t.get(n)??n)}function hl(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function fo(e,t){let n=Math.max(1,t),o=[],r=0;for(let s of e.split(`
|
|
262
|
+
`)){if(s.length===0)o.push({start:r,end:r});else for(let c=0;c<s.length;c+=n)o.push({start:r+c,end:r+Math.min(c+n,s.length)});r+=s.length+1}return o.length>0?o:[{start:0,end:0}]}function mo(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function gl(e,t,n){let o=mo(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 wl(e,t,n){let o=e[mo(e,t)];return n==="start"?o.start:o.end}function yl(e,t,n){let o=Math.max(1,n),r=e.split(`
|
|
262
263
|
`),s=0;for(let c=r.length-1;c>=0;c--){let p=r[c];if(s+=Math.max(1,Math.ceil(p.length/o)),s>=t){let h=s-t;return{text:[h>0?p.slice(h*o):p,...r.slice(c+1)].join(`
|
|
263
|
-
`),truncated:c>0||h>0}}}return{text:e,truncated:!1}}function
|
|
264
|
-
`)){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
|
|
264
|
+
`),truncated:c>0||h>0}}}return{text:e,truncated:!1}}function kl(e){let t=!1,n=0,o=0;for(let r of e.split(`
|
|
265
|
+
`)){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 ws,jsx as E,jsxs as B}from"react/jsx-runtime";var Zf={project:".d360-writer.json",user:"/model",env:"ANTHROPIC_MODEL","claude-settings":"Claude Code settings","claude-default":""},Rl=` 1. /init \u2014 pick your Document360 environment & scaffold config
|
|
265
266
|
2. /login \u2014 sign in & pick your Document360 project (workspace auto-selected)
|
|
266
|
-
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function
|
|
267
|
-
${
|
|
267
|
+
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function em(e,t,n,o){let r=ys(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)",c=ks(e),p=ee(e),h=(p?.docsDir??cn).replace(/\/+$/,""),b=p?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${h}/ + config`,x={version:t,claude:s,model:c.model??"Claude Code default model",modelSource:Zf[c.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:p!==null,mode:b};if(p===null)return x;try{let D=ue(e,o);x.profile=D.name,x.apiUrl=D.connection.apiUrl,x.prod=D.production,x.project=D.project.projectName??D.project.projectId??"(chosen at login)";let y=Ve(D.name);if(y){let P={...Ot(y.idToken)??{},...Ot(y.accessToken)??{}},C=P.email??P.preferred_username??"signed in";Oe(y)?y.refreshToken&&(x.who=C,x.loggedOut=!1,x.sessionHint="session expired \u2014 refreshing\u2026"):(x.who=C,x.loggedOut=!1,x.sessionHint=`session valid until ${new Date(y.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return x}function tm(e,t){try{let n=ue(e,t),o=Ve(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...Ot(o.idToken)??{},...Ot(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return Oe(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 Tl=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],bo=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],nm="Ask me to write or update an article\u2026";function wo({ch:e,dim:t}){let[n,o]=H(!0);return Pe(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),E(T,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var om=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Sl(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var rm=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Dl(e){try{return ko(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function jl(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>Dl(dt(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&Dl(dt(e,o)))}function Al(e,t){try{let n=ee(e);if(!n)return!1;let o=ue(e,t),r=yo(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=dt(e,(n.docsDir??cn).replace(/\/+$/,""));return!!(Ge(s)&&ko(s).length>0||Ge(bs(e)))}catch{return!1}}function sm({startTime:e,chars:t}){let[n,o]=H(0);Pe(()=>{let h=setInterval(()=>o(b=>b+1),120);return()=>clearInterval(h)},[]);let r=bo[n%bo.length],s=Tl[Math.floor(n/16)%Tl.length],c=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return B(ne,{children:[E(T,{color:F,children:` ${r} ${s}\u2026 `}),E(T,{color:"gray",children:`(${Zt(c)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}var im=12e4;function am({p:e}){let[t,n]=H(0);Pe(()=>{let _=setInterval(()=>n(L=>L+1),150);return()=>clearInterval(_)},[]);let o=bo[t%bo.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),c=Math.round(e.chars/4),p=Date.now()-e.lastAt>=im,h=e.verb??"Converting",b=e.unit??"article",x=e.rows.reduce((_,L)=>_+L.items,0),D=h.toLowerCase(),y=e.rows,P=0;if(y.length>po){let _=y.findIndex(Q=>Q.status==="active"||Q.status==="pending"),L=Math.max(0,Math.min(_-2,y.length-po));P=y.slice(0,L).filter(Q=>Q.status==="done").length,y=y.slice(L,L+po)}let C=Math.min(40,Math.max(...y.map(_=>us(_.label).length),0)),I=_=>_==="failed"?"red":_==="active"?F:void 0;return B(ne,{flexDirection:"column",children:[B(ne,{children:[E(T,{color:F,children:` ${o} ${h} ${x} ${b}${x===1?"":"s"} `}),E(T,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${c} tokens \xB7 ${Zt(r)} \xB7 esc to stop`})]}),P>0&&E(T,{dimColor:!0,children:` \u2714 +${P} done`}),y.map(_=>B(T,{color:I(_.status),dimColor:_.status==="done"||_.status==="pending",children:[` ${ll[_.status]} ${us(_.label).padEnd(C)}`,_.status!=="pending"?` (${_.items} ${b}${_.items===1?"":"s"})`:"",_.status==="active"?` \u2190 ${D}\u2026`:""]},_.label)),p&&E(T,{color:"yellow",children:` \u26A0 no activity for ${Zt(s)} \u2014 press esc to stop if it's wedged`})]})}var lm=10800*1e3;function El({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=pf(),[s,c]=H(n),[p,h]=H(null),[b,x]=H({text:"",pos:0}),D=b.text,y=G(l=>{x(i=>{let a=typeof l=="function"?l(i.text):l;return{text:a,pos:a.length}})},[]),P=G(l=>{x(i=>({text:i.text.slice(0,i.pos)+l+i.text.slice(i.pos),pos:i.pos+l.length}))},[]),C=G(()=>{x(l=>{if(l.pos===0)return l;let i=l.text.slice(0,l.pos),a=hl(i)??i.slice(0,-1);return{text:a+l.text.slice(l.pos),pos:a.length}})},[]),[I,_]=H(!1),[L,Q]=H(!1),[de,ie]=H(0),[Re,le]=H(null),[ze,Y]=H([]),pt=X(0),[Ul,un]=H(!1),[Wl,dn]=H(!1),[xo,Cs]=H(null),[Fl,ft]=H(0),Ke=X(0),[Lt,mt]=H(0),[ht,pn]=H(null),Ps=X(new Map),Hl=X(0),gt=X([]),ye=X(null);ye.current===null&&(ye.current=bl({cwd:e,profileName:s,allowProdWrites:!1}));let De=X({uuid:null,firstPrompt:null,titleFired:!1}),fn=X(new Map),wt=X(!1),$o=X([]),Ue=X([]),vo=X(null),[Rs,Xe]=H(null),Co=X(null),[Je,Qe]=H(null),[je,yt]=H(null),[We,kt]=H(null),[pe,bt]=H(null),[ke,Ze]=H(null),[et,xt]=H(null),[Ts,tt]=H(null),[be,nt]=H(null),[me,$t]=H(null),[Ss,Po]=H([]),ot=X([]),Ut=X(!1),xe=X(null),[Ds,te]=H(null),mn=X(!1),hn=X(null),Wt=X(null),[$e,rt]=H(null),[Ro,Ft]=H(null),[js,vt]=H(0),[As,Ct]=H(0),[ql,Es]=H(0),To=fs(()=>{try{return ks(e).model??"auto"}catch{return null}},[e,ql]),{stdout:Te}=mf(),[,Bl]=H(0),Is=X(`${Te.columns??80}x${Te.rows??24}`),Fe=G(()=>Math.max(20,(Te.columns??80)-1),[Te]),d=G(l=>{gt.current.push(l),console.log(sr(l,Fe()))},[Fe]),[So,Do]=H(null),Pt=G(l=>{Do(l),d({kind:"note",tone:"info",text:"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[d]),jo=X(!1),Ao=G(async()=>{try{if(jo.current||!zf(Vf())||ee(e)?.mode==="engineer")return;let l=await Gf({pkg:ut,currentVersion:o,force:!0});if(!l.updateAvailable||!l.latest)return;jo.current=!0,d({kind:"note",tone:"info",text:`\u2B06 Updating ${ut} ${l.current} \u2192 ${l.latest}\u2026 (wait for the \u2713 before you /exit)`}),dn(!0),(await Zn().finally(()=>dn(!1))).ok?(d({kind:"note",tone:"ok",text:`\u2713 Updated to v${l.latest} \u2014 run /exit, then relaunch to apply.`}),Y(a=>a.includes("/exit")?a:[...a,"/exit"]),Cs(l.latest)):d({kind:"note",tone:"warn",text:`Update available (v${l.latest}) but auto-update failed \u2014 run: ${Qn}`})}catch{}},[e,o,d]),Eo=G(l=>{let i=Ne(e,s);return i.ok?!0:(d({kind:"note",tone:"warn",text:i.reason}),Wt.current=l,Y(["/login"]),!1)},[e,s,d]),[Io,No]=H(null),Ht=X(!0),gn=X(0),qt=X(0);Pe(()=>{let l=setInterval(()=>{if(Ht.current){gn.current=0,qt.current=0;return}if(!I)try{if(!Ge(bs(e)))return;if(Ie(e).status==="current"){Ht.current=!0,gn.current=0,qt.current=0,d({kind:"note",tone:"ok",text:"\u2713 Your builder finished the hand-off \u2014 the architecture brief is in. I can read this repo now and write accurate docs."}),Do(null),le("write the docs for this repo");return}gn.current+=1;let i=gn.current;if((i===4||i%15===0)&&qt.current<3){qt.current+=1;let a=qt.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";d({kind:"note",tone:"info",text:Xt(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${a}`:`\u23F3 Waiting for your builder to run the prompt \u2014 paste it into your coding agent; I'll pick up automatically when it's done.${a}`})}}catch{}},4e3);return()=>clearInterval(l)},[e,I,d]),Pe(()=>{let l=Rs??ln(e);if(!I){io(0),Mt(`${lo} ${l}`);return}io(3);let i=0;Mt(`${ao[0]} ${l}`);let a=setInterval(()=>{i=(i+1)%ao.length,Mt(`${ao[i]} ${l}`)},400);return()=>clearInterval(a)},[I,e,Rs]),Pe(()=>()=>io(0),[]);let _o=G(l=>{try{let i=ee(e);if(!i)return{kind:"idle"};let a=ue(e,s),g=Ve(a.name),u=!!g&&(!Oe(g)||!!g.refreshToken),m=Al(e,s)||!jl(e,i.authoritativeSourceFiles),w=ys(t).state==="missing",k=yo(e,a.name),R=k?Object.keys(k.articles).length:0,S=dt(e,(i.docsDir??cn).replace(/\/+$/,"")),J=!1;try{J=Ge(S)&&ko(S).length>0}catch{}let q=0;if(k?.lastAnalyzedCommit)try{let U=hf("git",["rev-list","--count",`${k.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});U.status===0&&(q=parseInt((U.stdout||"").trim(),10)||0)}catch{}let O=0;try{let U=Pl(e);if(U.length>0){let z=(i.docsDir??cn).replace(/\/+$/,"");O=Pr(e,z,U.map(ge=>ge.path)).length}}catch{}let $=Nf(e,s),j={ready:u&&m&&!w,hasDocs:J,tracked:R,pendingText:_t(Nt(e)),behind:q,pendingWrites:O,localAhead:$,autoAudit:!!i.autoAudit,profileName:a.name,allowAutoAudit:l};return ul(j)}catch{return{kind:"idle"}}},[e,s,t]);Pe(()=>{let l=performance.now(),i=[],a=(w,k)=>{let R=performance.now();try{return k()}finally{let S=Math.round(performance.now()-R);S>=80&&i.push(`${w}: ${S}ms`)}};d({kind:"banner",info:a("banner",()=>em(e,o,t,s))});let g=ys(t).state==="missing";if(g&&d({kind:"note",tone:"warn",text:`\u26A0 Set up Claude first \u2014 d360-writer's agent runs on Claude Code, and it's not signed in on this machine yet.
|
|
268
|
+
${wf}
|
|
268
269
|
Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!ee(e)){d({kind:"note",tone:"info",text:`Welcome! This repo isn't set up for d360-writer yet \u2014 three steps and you're writing docs:
|
|
269
|
-
${
|
|
270
|
-
`)}),Pt(it()),Ht.current=!1)}}catch{}try{let w=a("reconcile-feedback",()=>
|
|
270
|
+
${Rl}`}),Y(g?["/doctor","/init"]:["/init"]);return}g&&Y(["/doctor"]);try{let w=ue(e,s),k=Ve(w.name);k&&Oe(k)&&k.refreshToken?xf({profile:w.name,connection:w.connection}).then(()=>{d({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),ie(R=>R+1)}).catch(()=>{d({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 do you want to log in now? (press 1)"}),Y(["/login"])}):(!k||Oe(k))&&(d({kind:"note",tone:"warn",text:`Profile "${w.name}" is not signed in \u2014 do you want to log in now? (press 1)`}),Y(["/login"]))}catch{}try{let w=ee(e),k=ue(e,s),R=Ve(k.name);w&&R&&!Oe(R)&&jl(e,w.authoritativeSourceFiles)&&!Al(e,s)&&(d({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),Y(["/scope"]))}catch{}try{if(a("reconcile-devhints",()=>Mn(e)),Ie(e).status!=="current")if(Xt(e))d({kind:"note",tone:"info",text:`\u{1F514} A newer dev\u2194docs protocol (v${oe}) is available \u2014 your builder can re-run /devhints when convenient. Your docs aren't blocked.`});else{let w=On(e);w.length&&(d({kind:"note",tone:"warn",text:w.join(`
|
|
271
|
+
`)}),Pt(it()),Ht.current=!1)}}catch{}try{let w=a("reconcile-feedback",()=>Xf(e));w.archived>0&&d({kind:"note",tone:"ok",text:`\u2713 Tidied ${w.archived} resolved item${w.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${w.open>0?`; ${w.open} still open`:""}.`})}catch{}let u=a("ready-decision",()=>_o(!0));u.kind==="autoAudit"?(d({kind:"note",tone:"info",text:u.note}),nn().then(w=>{w.kind==="forward-to-agent"&&w.prompt&&ce(w.prompt,{display:w.display,quietUser:!0})})):u.kind==="noDocs"?(d({kind:"note",tone:"info",text:u.note}),le(u.ghost),Y(u.options),u.title&&tt(u.title)):u.kind==="actions"&&(d({kind:"note",tone:"info",text:u.note}),Y(u.options),tt(u.title));let m=Math.round(performance.now()-l);m>=800&&Qf({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${m}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${i.length?i.join(`
|
|
271
272
|
`):"no single phase \u226580ms"}
|
|
272
|
-
cwd: ${e}`}),Ao()},[]),
|
|
273
|
-
`)});let k=cr(e,s);k&&d({kind:"note",tone:"info",text:k})}}catch(u){d({kind:"note",tone:"error",text:`Publish run failed: ${u.message}`})}finally{
|
|
274
|
-
`)}),Pt(it()),Ht.current=Ie(e).status==="current"||Xt(e),d({kind:"note",tone:"info",text:`No separate builder agent? Then just ask me now: "write the docs for this repo" \u2014 I'll read the code directly.`}))},[e,d,he,Pt]),xn=G(async l=>{let i;try{i=await Vt(e,l)}catch{d({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),Y(["/workspace"]);return}if(i.workspaces.length===0){d({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let a=i.workspaces.filter(u=>(u.workspace_type??"").toLowerCase()!=="apidocumentation"),g=a.length>0?a:i.workspaces;if(g.length===1){let u=g[0],m=i.workspaces.length-g.length;d({kind:"note",tone:"ok",text:`Selected the "${u.name??u.id}" workspace${m>0?" (skipped the API-documentation workspace)":""}.`}),bn(i.profile,i.projectId,u);return}d({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${g.length} available).`}),Y(["/workspace"])},[e,d,bn]),$n=G((l,i)=>{Yo(e,l,i.id,i.name),d({kind:"note",tone:"ok",text:`Project set to "${i.name??i.id}" (agent restarted).`}),he(),xn(l)},[e,d,he,xn]),
|
|
273
|
+
cwd: ${e}`}),Ao()},[]),Pe(()=>{let l=setInterval(()=>{Ao()},lm);return()=>clearInterval(l)},[Ao]),Pe(()=>{if(I||ze.length>0)return;let l=_o(!1);(l.kind==="actions"||l.kind==="noDocs")&&(Y(l.options),tt(l.title??null))},[I,ze,de,_o]),Pe(()=>{let l=null,i=null,a=()=>{l&&clearTimeout(l),l=setTimeout(()=>{l=null;let g=`${Te.columns??80}x${Te.rows??24}`;g!==Is.current&&(Is.current=g,Bl(u=>u+1),i&&clearTimeout(i),i=setTimeout(()=>{i=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+_i(gt.current,Fe())+"\x1B[?2026l")},80))},400)};return Te.on("resize",a),()=>{l&&clearTimeout(l),i&&clearTimeout(i),Te.off("resize",a)}},[Te,Fe]);let Ae=Math.max(20,(Te.columns??80)-1),Ns=fs(()=>tm(e,s),[e,s,de]),Mo=(()=>{if(Wl)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(xo!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${xo?` v${xo}`:""}\u2026`,isSetup:!0};let l=ee(e);if(!l)return{text:"Press 1 to set up this repo, or /help\u2026",isSetup:!0};let i=dt(e,(l.docsDir??cn).replace(/\/+$/,"")),a=(()=>{try{return Ge(i)&&ko(i).length>0}catch{return!1}})();try{let g=ue(e,s),u=Ve(g.name);if(!(!!u&&!(Oe(u)&&!u.refreshToken)))return{text:`Press 1 to sign in to Document360 (profile "${g.name}")\u2026`,isSetup:!0};if(!g.project.projectId)return{text:"Sign in to Document360 to pick your project\u2026",isSetup:!0};if(!g.project.workspaceId&&!a)return{text:"Press 1 to pick a workspace\u2026",isSetup:!0}}catch{}return a?{text:nm,isSetup:!1}:So?{text:"Press c to copy the prompt above, run it in your coding agent \u2014 then ask me to write the docs",isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),Bt=ol(D),_s=Bt.length>0&&!I,Oo=p!==null?yl(p,8,Ae):null,wn=be?be.paths.filter(l=>!be.query||l.toLowerCase().includes(be.query.toLowerCase())).slice(0,8):[],yn=$e?$e.sessions.filter(l=>{let i=$e.query.toLowerCase();return!i||l.name.toLowerCase().includes(i)||l.firstPrompt.toLowerCase().includes(i)}).slice(0,8):[],he=G((l,i)=>{ye.current?.close(),ye.current=bl({cwd:e,resume:l,profileName:i??s,allowProdWrites:wt.current}),l||(De.current={uuid:null,firstPrompt:null,titleFired:!1},Xe(null)),vt(0),Ct(0)},[e,s]),Ms=G((l,i,a)=>{if(om.test(l))try{let g=ue(e,s),u=typeof i.project_id=="string"&&i.project_id||g.project.projectId,m=ro(i,a),w=[],k=so(a);l.endsWith("publish_article")&&k&&w.push(`Live: ${k}`),m&&u&&w.push(`Preview: ${oo(g.connection.portalUrl,u,m,g.project.languageCode??"en")}`),w.length>0&&d({kind:"link",lines:w})}catch{}},[e,s,d]),ce=G(async(l,i)=>{un(!0),le(null),Y([]),tt(null),Do(null),No(null);let a=++pt.current;i?.quietUser||d({kind:"user",text:i?.echoDisplay&&i.display?i.display:l});let g=De.current;g.firstPrompt||(g.firstPrompt=i?.display??l),Ke.current=Date.now(),ft(0),_(!0),fn.current.clear();let u="",m=!1,w=!1,k="",R={num:0,closed:!1,cueSeen:!1},S=null,J=()=>{S||(S=setTimeout(()=>{S=null,h(k.length>0?k:null)},60))},q=()=>{S&&clearTimeout(S),S=null,h(null)},O=()=>{if(k.trim()){let $=ls(k.trimEnd(),R);d({kind:"assistant",text:$})}k="",q()};try{for await(let $ of ye.current.send(l))if($.type==="session"){if(!g.uuid){g.uuid=$.sessionId;let j=new Date().toISOString(),U=Co.current,z=U??Tf(g.firstPrompt??"session");Sf({uuid:$.sessionId,name:z,renamed:!!U,titled:!1,cwd:e,firstPrompt:g.firstPrompt??"",createdAt:j,updatedAt:j}),Xe(z),Co.current=null}}else if($.type==="text"){k+=$.delta,u+=$.delta;let j=kl(k);if(j>0){let U=k.slice(0,j).trimEnd();U&&d({kind:"assistant",text:ls(U,R)}),k=k.slice(j)}J(),ft(U=>U+$.delta.length)}else if($.type==="tool"){m=!0;let j=to($.name,$.input);j&&(O(),d({kind:"tool",title:j.title,sep:j.sep,arg:j.arg}),fn.current.set($.id,{name:$.name,input:$.input}))}else if($.type==="article_diff"){let j=lt($.oldContent,$.newContent,Fe());j&&(O(),d({kind:"diff",added:j.added,removed:j.removed,lines:j.lines,hidden:j.hidden}))}else if($.type==="tool_result"){$.isError&&/run \/login|not logged in|session expired|rejected the token/i.test($.output)&&(mn.current=!0);let j=fn.current.get($.id);if(j){fn.current.delete($.id),O();let U=no($.output,4,$.isError?void 0:j.name,j.input);d({kind:"tool-result",lines:U.lines,hidden:U.hidden,isError:$.isError}),$.isError||Ms(j.name,j.input,$.output)}}else if($.type==="result"){if(O(),vt(U=>U+$.outputTokens),Ct(U=>U+$.costUsd),d({kind:"done",seconds:Math.round((Date.now()-Ke.current)/1e3),tokens:$.outputTokens,costUsd:$.costUsd,ok:$.ok}),!w&&!m&&!u.trim()&&!Ut.current&&d({kind:"note",tone:"warn",text:"The agent produced no output. This usually means the Claude model/runtime did not start \u2014 check sign-in and model with /doctor (on a subscription, make sure Claude Code is logged in on this machine)."}),$.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(u))try{let U=Kf(e);if(Ge(U)){let z=ms(U,"utf8").trim();z&&(No(z),d({kind:"note",tone:"info",text:"\u{1F6E0} Press c to copy this feedback \u2014 send it to the d360-writer team (Teams / Slack / email)."}))}}catch{}let j=$.ok?al(u,co.map(U=>U.name)):[];if(j.length>0?Y(j):$.ok&&u.trim()&&Ef(l,u,e).then(U=>{U&&pt.current===a&&le(U)}).catch(()=>{}),g.uuid&&(hs(g.uuid),!g.titleFired)){g.titleFired=!0;let U=g.uuid,z=g.firstPrompt;z&&xl(z,e).then(ge=>{ge&&(Rf(U,ge),Xe(ge))}).catch(()=>{})}}else $.type==="error"&&(O(),w=!0,$.kind==="auth"&&(mn.current=!0),d({kind:"note",text:`agent error: ${$.message}`,tone:"error"}))}finally{_(!1),q(),ie($=>$+1),De.current.uuid&&Za(e,De.current.uuid,gt.current),mn.current&&(mn.current=!1,hn.current=i?.display??l,Y(["/login"])),Ut.current&&(Ut.current=!1,ot.current.length>0&&(d({kind:"note",tone:"info",text:`(${ot.current.length} queued message(s) discarded)`}),ot.current=[],Po([])),d({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,d,Ms,Fe]),kn=G(async l=>{let i=gs(l),a=go(e,"standard");Ke.current=Date.now(),ft(0),_(!0);let g=new AbortController;xe.current=g,te({verb:"Publishing",total:i.length,done:0,active:[],rows:an(i),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Publishing ${l.length} article${l.length===1?"":"s"} across ${i.length} partition${i.length===1?"":"s"} (\u2264${en} agents at once) on ${a.model}\u2026 (esc to stop)`});try{for await(let u of ho({cwd:e,partitions:i,promptFor:m=>Hn(m.paths),concurrency:en,profileName:s,allowProdWrites:wt.current,model:a.model,signal:g.signal}))if(u.type==="partition_status")u.status==="running"?te(m=>m&&{...m,active:[...m.active,u.label],rows:_e(m.rows,u.label,"active"),lastAt:Date.now()}):te(m=>m&&{...m,active:m.active.filter(w=>w!==u.label),done:m.done+1,rows:_e(m.rows,u.label,u.status==="done"?"done":"failed"),lastAt:Date.now()});else if(u.type==="partition_event")te(m=>{if(!m)return m;let w={...m,lastAt:Date.now()};return u.event.type==="tool"?w.tools=m.tools+1:u.event.type==="text"&&(w.chars=m.chars+u.event.delta.length),w});else if(u.type==="run_done"){Ct(R=>R+u.totalCostUsd),vt(R=>R+u.results.reduce((S,J)=>S+J.outputTokens,0));let m=u.aborted?"Stopped. ":"",w=t.kind==="api"?"api":"subscription";d({kind:"note",tone:u.aborted?"warn":u.ok?"ok":"warn",text:m+ur(u.results,i,w).join(`
|
|
274
|
+
`)});let k=cr(e,s);k&&d({kind:"note",tone:"info",text:k})}}catch(u){d({kind:"note",tone:"error",text:`Publish run failed: ${u.message}`})}finally{xe.current=null,te(null),_(!1),ie(u=>u+1)}},[e,s,d,t]),Lo=G(async l=>{await ce(lr(l),{display:`/publish ${l}`,quietUser:!0});try{let i=await qn(e,s,l.replace(/\\/g,"/"));i.length>0&&(tt(`Related articles not yet published (${i.length}):`),Y([`/publish --related ${l}`,...i.map(a=>`/publish ${a}`)]))}catch{}},[e,s,ce]),Uo=G(l=>{let i=Ve(l);if(!i||Oe(i)&&!i.refreshToken)return null;let a={...Ot(i.idToken)??{},...Ot(i.accessToken)??{}};return a.email??a.preferred_username??"signed in"},[]),Wo=G((l,i)=>{if(i){let a=ee(e);a&&(a.defaultProfile=l,$l(a,e))}c(l),he(void 0,l),d({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${l}"${i?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),Uo(l)||(d({kind:"note",tone:"warn",text:`Profile "${l}" is not signed in \u2014 do you want to log in now? (press 1)`}),Y(["/login"])),ie(a=>a+1)},[e,d,he,Uo]),bn=G((l,i,a)=>{Rn(e,l,i,a.id,a.name),d({kind:"note",tone:"ok",text:`Switched to workspace "${a.name??a.id}" (agent restarted).`}),he(),yo(e,l)||(d({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),d({kind:"note",tone:"warn",text:"\u26A0 Before I write the docs, hand the prompt below to your builder (your repo's coding agent). It gives me the architecture brief that makes the docs accurate:"}),d({kind:"note",tone:"info",text:At(jt(e)).join(`
|
|
275
|
+
`)}),Pt(it()),Ht.current=Ie(e).status==="current"||Xt(e),d({kind:"note",tone:"info",text:`No separate builder agent? Then just ask me now: "write the docs for this repo" \u2014 I'll read the code directly.`}))},[e,d,he,Pt]),xn=G(async l=>{let i;try{i=await Vt(e,l)}catch{d({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),Y(["/workspace"]);return}if(i.workspaces.length===0){d({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let a=i.workspaces.filter(u=>(u.workspace_type??"").toLowerCase()!=="apidocumentation"),g=a.length>0?a:i.workspaces;if(g.length===1){let u=g[0],m=i.workspaces.length-g.length;d({kind:"note",tone:"ok",text:`Selected the "${u.name??u.id}" workspace${m>0?" (skipped the API-documentation workspace)":""}.`}),bn(i.profile,i.projectId,u);return}d({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${g.length} available).`}),Y(["/workspace"])},[e,d,bn]),$n=G((l,i)=>{Yo(e,l,i.id,i.name),d({kind:"note",tone:"ok",text:`Project set to "${i.name??i.id}" (agent restarted).`}),he(),xn(l)},[e,d,he,xn]),Os=G(async l=>{let i;try{i=ue(e,l)}catch{return}if(!i.project.workspaceId){if(i.project.projectId){if(!i.project.projectName)try{let{projects:a}=await st(e,i.name),g=a.find(u=>u.id===i.project.projectId);g?.name&&Jf(e,i.name,{projectName:g.name})}catch{}await xn(i.name);return}try{let{projects:a}=await st(e,i.name);if(a.length===1){let g=a[0];d({kind:"note",tone:"ok",text:`Using your Document360 project "${g.name??g.id}".`}),$n(i.name,{id:g.id,name:g.name});return}if(a.length>1){let g=a.map(u=>({id:u.id,name:u.name??u.id,sub:u.sub_domain}));d({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),Ze({cursor:0,current:-1,rows:g,profile:i.name,environment:i.connection.name});return}}catch{}d({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),Y(["/project"])}},[e,d,xn,$n]),vn=G(()=>{let l=Ue.current[0];if(!l)return;d({kind:"note",tone:"info",text:`\u25CF ${l.title} (${l.path})`});for(let a of l.notes)d({kind:"note",tone:"warn",text:`\u26A0 ${a}`});l.overwritesLocalChanges&&d({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let i=lt(l.oldContent,l.newContent,Fe());d(i?{kind:"diff",added:i.added,removed:i.removed,lines:i.lines,hidden:i.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."}),d({kind:"note",tone:"info",text:`Write ${l.path}? (y/n \u2014 anything else cancels)`})},[d,Fe]),Ls=G(l=>{if(Ue.current.length===0)return!1;let i=l.trim().toLowerCase();if(i==="y"||i==="yes"){let a=Ue.current.shift();try{If({cwd:e,profileName:s},a),d({kind:"note",tone:"ok",text:`\u2713 Pulled ${a.path} (sync base advanced).`}),Ue.current.length===0&&Y(g=>g.length>0?g:["/pull"])}catch(g){d({kind:"note",tone:"error",text:`Pull failed: ${g.message}`})}}else if(i==="n"||i==="no"){let a=Ue.current.shift();d({kind:"note",tone:"info",text:`Skipped ${a.path}.`})}else{let a=Ue.current.length;return Ue.current=[],d({kind:"note",tone:"info",text:`Pull cancelled (${a} article(s) left untouched).`}),!0}return vn(),!0},[e,s,vn,d]),Us=G(l=>{let i=vo.current;if(!i)return!1;if(vo.current=null,le(null),pt.current++,l.trim()!==i.repoName)return d({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:a,failed:g}=ns(e,i.targets);d({kind:"note",tone:g.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${a.length} item${a.length===1?"":"s"}. The repo is back to its original state.`});for(let u of g)d({kind:"note",tone:"error",text:` \u2717 ${u.path}: ${u.error}`});return i.hadDevhints&&(d({kind:"note",tone:"warn",text:Ln().join(`
|
|
275
276
|
`)}),Pt(Jo())),d({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
|
|
276
|
-
${
|
|
277
|
+
${Rl}`}),Y(["/init"]),un(!1),!0},[e,d,Pt]),Ws=G(async l=>{let i=l.slice(1).trim().split(/\s+/),a=(i[0]??"").toLowerCase(),g=i.slice(1);switch(un(!0),a){case"help":Ft({tab:0});return;case"exit":case"quit":ye.current?.close(),r();return;case"clear":he(),gt.current=[],un(!1),le(null),pt.current++,d({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let u;try{u=ue(e,s)}catch(m){d({kind:"note",tone:"error",text:m.message});return}d({kind:"note",tone:"info",text:`Profile "${u.name}" \u2192 ${u.connection.name} (${u.connection.apiUrl})${u.production?" \u26A0 PRODUCTION":""}`}),Q(!0);try{let m=await yf(u.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},k=>d({kind:"note",tone:"info",text:k})),w=kf(u.name,m);if(bf(w),await Go(w,u.name,k=>d({kind:"note",tone:"info",text:k})),d({kind:"note",tone:"ok",text:`\u2713 Logged in to "${u.name}" as ${Sn(w)}`}),await Os(s),Wt.current){let k=Wt.current;Wt.current=null;let R=Ne(e,s);R.ok?(d({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 press 1 to run ${k}.`}),Y([k])):(d({kind:"note",tone:"warn",text:`${R.reason} (then ${k}.)`}),Y(["/login"]),Wt.current=k)}else hn.current&&(le(hn.current),hn.current=null,d({kind:"note",tone:"info",text:"Press tab to re-send your last prompt."}))}catch(m){d({kind:"note",tone:"error",text:`Login failed: ${m.message}`})}finally{Q(!1),ie(m=>m+1)}return}case"allow-prod":{let u=!1;try{u=ue(e,s).production}catch{}if(!u){d({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}wt.current=!0,he(),d({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let u=Lr(g.join(" ")),m=De.current.uuid;if(!m){if(!u){d({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}Co.current=u,Xe(u),Mt(`${lo} ${u}`),d({kind:"note",tone:"ok",text:`Session will be named "${u}" once it starts.`});return}if(!u){d({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let w=De.current.firstPrompt??"";xl(w,e).then(k=>{k?(le(`/rename ${k}`),d({kind:"note",tone:"info",text:`Suggestion: "${k}" \u2014 press tab to accept, or type /rename <your name>.`})):d({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>d({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}Af(m,u),Xe(u),Mt(`${lo} ${u}`),d({kind:"note",tone:"ok",text:`Session renamed to "${u}".`});return}case"profile":{let u=g[0],m=ee(e);if(!u){let w=Object.entries(m?.profiles??{});if(w.length===0){d({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let k=w.map(([J,q])=>({name:J,env:q.connection?.environment??"custom",prod:q.production===!0,who:Uo(J)})),R=s??m?.defaultProfile,S=Math.max(0,k.findIndex(J=>J.name===R));yt({cursor:S,current:S,rows:k});return}if(u==="add"){let w=Ur(e,g[1],g[2]);if(w){d({kind:"note",tone:"error",text:w});return}d({kind:"note",tone:"ok",text:`\u2713 Profile "${g[1]}" created (environment: ${g[2]??g[1]}).`}),Wo(g[1],!1);return}if(!m?.profiles?.[u]){d({kind:"note",tone:"error",text:`Unknown profile "${u}". Create it: /profile add ${u} <environment>`});return}Wo(u,!0);return}case"doctor":await rn(g,{cwd:e});return;case"mcp":await Wn(g);return;case"init":{if(ee(e)){d({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer.json directly (or d360-writer init for the CLI wizard)."});return}let u=Ff().map(m=>({name:m,apiUrl:Hf(m).apiUrl}));kt({cursor:0,rows:u});return}case"resume":{let u=g.join(" ").trim(),m=jf(e).filter(R=>R.uuid!==De.current.uuid);if(!u){if(!m.length){d({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}rt({query:"",cursor:0,sessions:m});return}let w=Df(e,u);if(!w){d({kind:"note",tone:"error",text:`No session matches "${u}".`});return}he(w.uuid),De.current={uuid:w.uuid,firstPrompt:w.firstPrompt,titleFired:!0},Xe(w.name),hs(w.uuid),gt.current=[];let k=cs(e,w.uuid);for(let R of k)d(R);d({kind:"note",tone:"ok",text:k.length?`Resumed "${w.name}" \u2014 restored ${k.length} message(s); continue where you left off.`:`Resumed "${w.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let u=g.join(" ").trim(),m;try{m=await Vt(e,s)}catch(k){d({kind:"note",tone:"error",text:`Could not list workspaces: ${k.message}`});return}if(!u){let k=m.workspaces.map(S=>({id:S.id,name:S.name??S.id,type:S.workspace_type}));if(k.length===0){d({kind:"note",tone:"info",text:"No workspaces in this project."});return}let R=Math.max(0,k.findIndex(S=>S.id===m.current));bt({cursor:R,current:R,rows:k,profile:m.profile,projectId:m.projectId,projectName:m.projectName,environment:m.environment});return}let w=Bo(m.workspaces,u);if(!w){d({kind:"note",tone:"error",text:`No workspace matches "${u}".`});return}bn(m.profile,m.projectId,w);return}case"project":{let u=g.join(" ").trim(),m;try{m=await st(e,s)}catch(k){d({kind:"note",tone:"error",text:`Could not list projects: ${k.message} (signed in? try /login)`});return}if(!u){let k=m.projects.map(S=>({id:S.id,name:S.name??S.id,sub:S.sub_domain}));if(k.length===0){d({kind:"note",tone:"info",text:"No projects found for this identity."});return}let R=k.findIndex(S=>S.id===m.current);Ze({cursor:Math.max(0,R),current:R,rows:k,profile:m.profile,environment:m.environment});return}let w=zs(m.projects,u);if(!w){d({kind:"note",tone:"error",text:`No project matches "${u}". Available: ${m.projects.map(k=>k.name??k.id).join(", ")}`});return}$n(m.profile,w);return}case"logout":{let u;try{u=ue(e,s).name}catch(w){d({kind:"note",tone:"error",text:w.message});return}let m=Cf(u);Pf(e,u),he(),ie(w=>w+1),d({kind:"note",tone:m?"ok":"info",text:m?`\u2713 Signed out of "${u}" and cleared its project/workspace selection.`:`Profile "${u}" was not signed in. Cleared any project/workspace selection.`}),d({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),Y(["/login"]);return}case"publish":{if(!Eo(l.trim()))return;if(g[0]==="--related"&&g[1]){let m=await qn(e,s,g[1].replace(/\\/g,"/"));if(m.length===0){d({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await kn(m);return}if(g[0]&&g[0]!=="--all"){await Lo(g[0]);return}let u=g[0]==="--all";d({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let m=await vl({cwd:e,profileName:s}),w=tn(m.entries),k=Fn(m.entries);if(k>0&&d({kind:"note",tone:"warn",text:`\u26A0 ${k} article${k===1?"":"s"} already exist on Document360 but aren\u2019t linked \u2014 left OUT of publish (publishing would duplicate them). Run /catch-up (or ask me to link them) first.`}),w.length===0){d({kind:"note",tone:"ok",text:k>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let R=m.counts["unknown-base"]??0;R>0&&d({kind:"note",tone:"info",text:`(${R} article(s) have no sync base yet \u2014 publish those by path if needed.)`});return}if(u){await kn(w.map(R=>R.path));return}xt({cursor:0,rows:Li(w)})}catch(m){d({kind:"note",tone:"error",text:`Could not compute sync status: ${m.message}`}),d({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"preview":{let u=g.join(" ").trim();if(!u){let w=[];try{w=Object.keys(yo(e,ue(e,s).name)?.articles??{})}catch{}if(w.length===0){d({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}nt({query:"",cursor:0,paths:w});return}let m=gf(u)?u:dt(e,u);if(Ge(m)){try{d({kind:"preview",name:ln(m),text:Sl(ms(m,"utf8"))})}catch(w){d({kind:"note",tone:"error",text:`Could not read ${m}: ${w.message}`})}return}if(rm.test(u)){try{let w=ue(e,s),k={profile:w.name,connection:w.connection},R=w.project.projectId??$f(k),S=await vf(k,R,u);d({kind:"preview",name:S.title??u,text:S.content??"*(article has no content)*"})}catch(w){d({kind:"note",tone:"error",text:`Could not fetch article: ${w.message}`})}return}d({kind:"note",tone:"error",text:`"${u}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let u=g[0]?.trim();if(!u){let R=zn(ks(e));Qe({cursor:R,current:R});return}let{lines:m,changed:w,effective:k}=on(e,u);for(let R of m)d({kind:"note",tone:R.startsWith("\u26A0")?"warn":R.startsWith("\u2713")?"ok":"info",text:R});w&&(Es(R=>R+1),ye.current?.setModel(k));return}case"convert":{if(!ee(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:u,run:m}=wr(g),w=Yf(e,s);if(w.length===0){d({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let k=yr(w,u);if(k.length===0){d({kind:"note",tone:"error",text:`No tracked articles under "${u}". (${w.length} are tracked overall.)`});return}let R=gs(k),S=3,J=`/convert${u?` --scope ${u}`:""} --run`,q=go(e,"light");if(!m){let $=Cl({files:kr(e,k),op:"convert",model:q.model}),j=u?`Scope: ${u} (${k.length} of ${w.length} tracked)
|
|
277
278
|
`:"",U=`
|
|
278
|
-
Model: ${q.model}${q.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;d({kind:"note",tone:"info",text:j+xr(R
|
|
279
|
-
`)+U}),Y([J]);return}Ke.current=Date.now(),ft(0),_(!0);let
|
|
280
|
-
`)})}}catch(
|
|
279
|
+
Model: ${q.model}${q.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;d({kind:"note",tone:"info",text:j+xr(R,$,S).join(`
|
|
280
|
+
`)+U}),Y([J]);return}Ke.current=Date.now(),ft(0),_(!0);let O=new AbortController;xe.current=O,te({verb:"Converting",total:R.length,done:0,active:[],rows:an(R),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Converting ${k.length} articles across ${R.length} partitions (\u2264${S} agents at once) on ${q.model}\u2026 (esc to stop)`});try{for await(let $ of ho({cwd:e,partitions:R,promptFor:br,concurrency:S,profileName:s,allowProdWrites:wt.current,model:q.model,signal:O.signal}))if($.type==="partition_status")$.status==="running"?te(j=>j&&{...j,active:[...j.active,$.label],rows:_e(j.rows,$.label,"active"),lastAt:Date.now()}):te(j=>j&&{...j,active:j.active.filter(U=>U!==$.label),done:j.done+1,rows:_e(j.rows,$.label,$.status==="done"?"done":"failed"),lastAt:Date.now()});else if($.type==="partition_event")te(j=>{if(!j)return j;let U={...j,lastAt:Date.now()};return $.event.type==="tool"?U.tools=j.tools+1:$.event.type==="text"&&(U.chars=j.chars+$.event.delta.length),U});else if($.type==="run_done"){Ct(z=>z+$.totalCostUsd),vt(z=>z+$.results.reduce((ge,Tt)=>ge+Tt.outputTokens,0));let j=$.aborted?"Stopped. ":"",U=t.kind==="api"?"api":"subscription";d({kind:"note",tone:$.aborted?"warn":$.ok?"ok":"warn",text:j+$r($.results,R,U).join(`
|
|
281
|
+
`)})}}catch($){d({kind:"note",tone:"error",text:`Convert run failed: ${$.message}`})}finally{xe.current=null,te(null),_(!1),ie($=>$+1)}return}case"write":{if(!ee(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=Pl(e);if(u.length===0){d({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:m,path:w,preview:k,concurrency:R,rewrite:S}=Cr(g),{docsDir:J,targets:q,reason:O,rewriting:$}=jr(e,u,{scope:m,path:w,rewrite:S});if(q.length===0){d({kind:"note",tone:"warn",text:O??"Nothing to write."});return}$&&d({kind:"note",tone:"warn",text:`--rewrite: regenerating ${q.length} already-written article${q.length===1?"":"s"} (overwrites them; git has your baseline).`});let j=gs(q),U=vr(R),z=go(e,"standard"),ge=!!w;if(k&&!ge){let K=Cl({files:Rr(e,u,q),op:"write",model:z.model}),Z=m?`Scope: ${m} (${q.length} pending)
|
|
281
282
|
`:"",Ee=`
|
|
282
283
|
Model: ${z.model}${z.forced?" (forced)":" \u2014 authoring; /model to override"}`;d({kind:"note",tone:"info",text:Z+Sr(j,K,U).join(`
|
|
283
|
-
`)+Ee}),Y([`/write${m?` --scope ${m}`:""}`]);return}Ke.current=Date.now(),ft(0),_(!0);let Tt=new AbortController;
|
|
284
|
-
`)}),!K.aborted&&K.ok&&Y(["/publish --all","/screenshot --all"])}}catch(K){d({kind:"note",tone:"error",text:`Write run failed: ${K.message}`})}finally{
|
|
284
|
+
`)+Ee}),Y([`/write${m?` --scope ${m}`:""}`]);return}Ke.current=Date.now(),ft(0),_(!0);let Tt=new AbortController;xe.current=Tt,te({verb:"Writing",total:j.length,done:0,active:[],rows:an(j),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Writing ${q.length} article${q.length===1?"":"s"} across ${j.length} partition${j.length===1?"":"s"} (\u2264${U} agents at once) on ${z.model}${z.forced?" (forced)":""}\u2026 (esc to stop)`});try{for await(let K of ho({cwd:e,partitions:j,promptFor:Z=>Tr(Z,J,{rewrite:$||ge}),concurrency:U,profileName:s,allowProdWrites:wt.current,model:z.model,signal:Tt.signal}))if(K.type==="partition_status")K.status==="running"?te(Z=>Z&&{...Z,active:[...Z.active,K.label],rows:_e(Z.rows,K.label,"active"),lastAt:Date.now()}):te(Z=>Z&&{...Z,active:Z.active.filter(Ee=>Ee!==K.label),done:Z.done+1,rows:_e(Z.rows,K.label,K.status==="done"?"done":"failed"),lastAt:Date.now()});else if(K.type==="partition_event")te(Z=>{if(!Z)return Z;let Ee={...Z,lastAt:Date.now()};return K.event.type==="tool"?Ee.tools=Z.tools+1:K.event.type==="text"&&(Ee.chars=Z.chars+K.event.delta.length),Ee});else if(K.type==="run_done"){Ct(Ho=>Ho+K.totalCostUsd),vt(Ho=>Ho+K.results.reduce((Vl,zl)=>Vl+zl.outputTokens,0));let Z=K.aborted?"Stopped. ":"",Ee=t.kind==="api"?"api":"subscription";d({kind:"note",tone:K.aborted?"warn":K.ok?"ok":"warn",text:Z+Dr(K.results,j,Ee).join(`
|
|
285
|
+
`)}),!K.aborted&&K.ok&&Y(["/publish --all","/screenshot --all"])}}catch(K){d({kind:"note",tone:"error",text:`Write run failed: ${K.message}`})}finally{xe.current=null,te(null),_(!1),ie(K=>K+1)}return}case"draft":{if(!ee(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:u,looseDocs:m}=Ar(e);if(u.length===0&&m===0){d({kind:"note",tone:"info",text:Ir});return}let w=g.join(" ").trim();if(!w&&u.length>1){d({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
|
|
285
286
|
${u.map(S=>` \u2022 ${S.name} (${S.docCount} doc${S.docCount===1?"":"s"})`).join(`
|
|
286
|
-
`)}`}),Y(u.map(S=>`/draft ${S.name}`));return}let k="",R;if(w){let S=Er(u,w);S?k=S:R=w}else k=u[0]?.name??"";await ce(Vn(k,R),{display:w?`/draft ${w}`:"/draft",quietUser:!0});return}case"pull":{if(!Eo(l.trim()))return;let u=g.find(m=>m.startsWith("--"));try{if(u==="--status"){d({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let k=Date.now(),R=await
|
|
287
|
-
`)});return}if(u==="--baseline"){let k=g.find(q=>!q.startsWith("--")),R=k?k.replace(/\\/g,"/"):void 0;d({kind:"note",tone:"info",text:R?`Setting the sync baseline for ${R}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let S=await
|
|
287
|
+
`)}`}),Y(u.map(S=>`/draft ${S.name}`));return}let k="",R;if(w){let S=Er(u,w);S?k=S:R=w}else k=u[0]?.name??"";await ce(Vn(k,R),{display:w?`/draft ${w}`:"/draft",quietUser:!0});return}case"pull":{if(!Eo(l.trim()))return;let u=g.find(m=>m.startsWith("--"));try{if(u==="--status"){d({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let k=Date.now(),R=await vl({cwd:e,profileName:s});d({kind:"note",tone:"info",text:Yn(R,Date.now()-k).join(`
|
|
288
|
+
`)});return}if(u==="--baseline"){let k=g.find(q=>!q.startsWith("--")),R=k?k.replace(/\\/g,"/"):void 0;d({kind:"note",tone:"info",text:R?`Setting the sync baseline for ${R}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let S=await Lf({cwd:e,profileName:s,relPaths:R?[R]:void 0}),J=R?{rebaselined:[],skipped:[]}:await Uf({cwd:e,profileName:s});if(S.baselined.length===0&&S.skipped.length===0&&J.rebaselined.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}S.baselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Baselined ${S.baselined.length} article${S.baselined.length===1?"":"s"} \u2014 they now read in-sync until either side changes.`}),J.rebaselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${J.rebaselined.length} article${J.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),S.skipped.length>0&&d({kind:"note",tone:"warn",text:`${S.skipped.length} skipped:
|
|
288
289
|
${S.skipped.map(q=>` - ${q.path} (${q.reason})`).join(`
|
|
289
|
-
`)}`}),ie(q=>q+1);return}if(u==="--compare"){d({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let k=await
|
|
290
|
-
`)});return}if(u){d({kind:"note",tone:"error",text:`Unknown option: ${u} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let m=g[0];if(m){let k=await
|
|
290
|
+
`)}`}),ie(q=>q+1);return}if(u==="--compare"){d({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let k=await Mf({cwd:e,profileName:s}),R=k.onlyInLegacy.length===0&&k.onlyInManifest.length===0&&k.mappedMissingFromManifest.length===0,S=[`Legacy listing: ${k.legacyCount} \xB7 Manifest: ${k.manifestCount} \xB7 in both: ${k.inBoth}`];R?S.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(k.mappedMissingFromManifest.length&&S.push(`\u2717 ${k.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${k.mappedMissingFromManifest.slice(0,5).join(", ")}`),k.onlyInLegacy.length&&S.push(`\u26A0 ${k.onlyInLegacy.length} only in the legacy listing: ${k.onlyInLegacy.slice(0,5).join(", ")}`),k.onlyInManifest.length&&S.push(`\u26A0 ${k.onlyInManifest.length} only in the manifest: ${k.onlyInManifest.slice(0,5).join(", ")}`),S.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),d({kind:"note",tone:R?"ok":"warn",text:S.join(`
|
|
291
|
+
`)});return}if(u){d({kind:"note",tone:"error",text:`Unknown option: ${u} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let m=g[0];if(m){let k=await Of({cwd:e,profileName:s,relPath:m.replace(/\\/g,"/")});Ue.current=[k],vn();return}d({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let w=await mr({cwd:e,profileName:s});for(let k of hr(w))d({kind:"note",tone:k.tone,text:k.text});ie(k=>k+1)}catch(m){d({kind:"note",tone:"error",text:`Pull failed: ${m.message}`})}return}case"scope":{if(!ee(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=Wf(e);if(u.length===0){d({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer.json manually.'});return}$t({cursor:0,rows:u.map(m=>({...m,checked:m.recommended}))});return}case"audit":{if(g[0]==="--auto"){let m=ee(e);if(!m){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let w=g[1]!=="off";$l({...m,autoAudit:w},e),d({kind:"note",tone:"ok",text:w?"\u2713 Auto-audit ON \u2014 when you launch with code changes since the last audit, I\u2019ll run /audit automatically. (/audit --auto off to disable.)":"\u2713 Auto-audit OFF \u2014 I\u2019ll just nudge you to run /audit when code changed."});return}let u=await nn();u.kind==="forward-to-agent"&&u.prompt&&await ce(u.prompt,{display:u.display,quietUser:!0});return}case"lint":{let u=_f({cwd:e});d({kind:"note",tone:u.length===0?"ok":"warn",text:rs(u).join(`
|
|
292
|
+
`)});return}case"capture-setup":{let u=await sn();u.kind==="forward-to-agent"&&u.prompt&&await ce(u.prompt,{display:u.display,quietUser:!0});let m=Yr(e);m&&d({kind:"note",tone:"info",text:m.join(`
|
|
291
293
|
`)});return}case"devhints":{if(!ee(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:At(jt(e)).join(`
|
|
292
|
-
`)}),Pt(it()),Ht.current=Ie(e).status==="current"||Xt(e);return}case"inbox":{if(!ee(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(Gr(e)===0){d({kind:"note",tone:"info",text:"Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)"});return}await ce(Vr(),{display:"/inbox",quietUser:!0});return}case"document":{if(!ee(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:u,what:m}=_r(g);if(!m&&Nr(e)===0){d({kind:"note",tone:"info",text:Or});return}let w=`/document${m?` ${m}`:""}${u?" --publish":""}`;await ce(Mr(m,u),{display:w,quietUser:!0});return}case"catch-up":{if(!ee(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!Eo(l.trim()))return;let{publish:u}=Kr(g);d({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let m=await Jr({cwd:e,profileName:s});for(let k of Qr(m))d({kind:"note",tone:k.startsWith("\u2713")?"ok":k.startsWith("\u2139")?"info":"warn",text:k});let w=_t(Nt(e));d({kind:"note",tone:"info",text:w?`Catching up on ${w}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"}),await ce(Xr({publish:u}),{display:`/catch-up${u?" --publish":""}`,quietUser:!0});return}case"update":{jo.current=!0,d({kind:"note",tone:"info",text:`Updating ${ut}\u2026 (don\u2019t close this window)`}),dn(!0),(await Zn().finally(()=>dn(!1))).ok?(d({kind:"note",tone:"ok",text:"\u2713 Updated \u2014 run /exit, then relaunch to apply."}),Y(m=>m.includes("/exit")?m:[...m,"/exit"]),
|
|
293
|
-
`)});return}if(u.mode==="single"){let
|
|
294
|
-
`)})}return}case"reset":{let u=ts(e);if(u.length===0){d({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}vo.current={repoName:ln(e),targets:u,hadDevhints:Ge(
|
|
295
|
-
`)}),le(ln(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${a} \u2014 type /help.`})}},[e,r,s,vn,d,he,ce,kn,Lo,Ms]),Cn=G(l=>{let i=(l??D).trim();if(y(""),pn(null),mt(0),i.startsWith("/")&&(le(null),pt.current++,tt(null),Y(g=>al(g,i))),!i||Ls(i)||Os(i))return;$o.current.push(i);let a=pl(i,Cs.current);i.startsWith("/")?(d({kind:"user",text:i}),Us(a)):ce(a,{display:i})},[D,Ls,Os,Us,ce]),Ws=G(l=>{if(l.length>1){if(l.includes("\x1B"))return;let i=cl(l);if(ul(i)){let a=dl(++Wl.current,i);Cs.current.set(a,i),P(a)}else P(i);return}P(l)},[P]),Rt=Math.max(10,Ae-6),Fs=ps(()=>fo(b.text,Rt),[b.text,Rt]),Fo=G(l=>x(i=>({...i,pos:Math.max(0,Math.min(i.text.length,i.pos+l))})),[]),Pn=G(l=>x(i=>({...i,pos:ml(fo(i.text,Rt),i.pos,l)})),[Rt]),Yt=G(l=>x(i=>({...i,pos:hl(fo(i.text,Rt),i.pos,l)})),[Rt]),ql=["\x1B[H","\x1B[1~","\x1BOH"],Bl=["\x1B[F","\x1B[4~","\x1BOF"],Hs=G((l,i)=>i.leftArrow?(Fo(-1),!0):i.rightArrow?(Fo(1),!0):l&&ql.includes(l)?(Yt("start"),!0):l&&Bl.includes(l)?(Yt("end"),!0):i.ctrl&&l==="a"?(Yt("start"),!0):i.ctrl&&l==="e"?(Yt("end"),!0):!1,[Fo,Yt]);return uf((l,i)=>{if(i.ctrl&&l==="c"){we.current?.close(),r();return}if(!L){if(I){if(i.escape){if(be.current){be.current.signal.aborted||(d({kind:"note",tone:"warn",text:"\u238B Stopping the convert run (finishing in-flight articles)\u2026"}),be.current.abort());return}Ut.current||(Ut.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),we.current?.interrupt());return}if(i.return){let a=D.trim();if(!a)return;ot.current.push(a),Po([...ot.current]),y("");return}if(Hs(l,i))return;if(i.upArrow){Pn(-1);return}if(i.downArrow){Pn(1);return}if(i.backspace||i.delete){C();return}l&&!i.ctrl&&!i.meta&&Ws(l);return}if(Je){if(i.upArrow){Qe(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Qe(a=>a&&{...a,cursor:Math.min(Se.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Se.length){Qe(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=Se[Je.cursor];Qe(null);let{lines:g,changed:u,effective:m}=on(e,a.value??"default");for(let w of g)d({kind:"note",tone:w.startsWith("\u26A0")?"warn":w.startsWith("\u2713")?"ok":"info",text:w});u&&(As(w=>w+1),we.current?.setModel(m));return}if(l==="s"){let a=Se[Je.cursor];Qe(null),we.current?.setModel(a.value??void 0),d({kind:"note",tone:"ok",text:`\u2713 Using ${a.label} for this session only (your saved default is unchanged).`});return}if(i.escape){Qe(null);return}return}if(je){if(i.upArrow){yt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){yt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=je.rows.length){yt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return||l==="s"){let a=je.rows[je.cursor];yt(null),Wo(a.name,i.return===!0);return}if(i.escape){yt(null);return}return}if(Ro){if(i.escape){Ft(null);return}if(i.leftArrow||i.tab&&i.shift){Ft(a=>a&&{tab:(a.tab-1+ve.length)%ve.length});return}if(i.rightArrow||i.tab){Ft(a=>a&&{tab:(a.tab+1)%ve.length});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=ve.length){Ft({tab:Number(l)-1});return}return}if(We){if(i.upArrow){kt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){kt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=We.rows.length){kt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=We.rows[We.cursor].name;if(kt(null),!$i(e,a).created){d({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer.json already exists."});return}d({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer.json (environment "${a}").`});let u=!1;try{let m=Ve(a);u=!!m&&!(Oe(m)&&!m.refreshToken)}catch{u=!1}d({kind:"note",tone:"info",text:u?`Next: sign in to ${a} and pick your project \u2014 you're already signed in here, so it'll be quick. (press 1)`:`Next: sign in to Document360 (${a}) and pick your project. (press 1)`}),Y(["/login"]),ie(m=>m+1);return}if(i.escape){kt(null);return}return}if(pe){if(i.upArrow){bt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){bt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=pe.rows.length){bt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=pe.rows[pe.cursor],{profile:g,projectId:u}=pe;bt(null),bn(g,u,a);return}if(i.escape){bt(null);return}return}if(ye){if(i.upArrow){Ze(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Ze(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=ye.rows.length){Ze(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=ye.rows[ye.cursor],{profile:g}=ye;Ze(null),$n(g,a);return}if(i.escape){Ze(null);return}return}if(me){if(i.upArrow){$t(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){$t(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l===" "){$t(a=>a&&{...a,rows:a.rows.map((g,u)=>u===a.cursor?{...g,checked:!g.checked}:g)});return}if(i.return){let a=me.rows.filter(g=>g.checked).map(g=>g.path);if($t(null),a.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}dr(e,a),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${a.length} folder(s) \u2014 written to .d360-writer.json`});for(let g of a)d({kind:"note",tone:"info",text:` ${g}`});d({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(i.escape){$t(null);return}return}if(et){if(i.upArrow){xt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){xt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=et.rows.length){xt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=et.rows[et.cursor];xt(null),a.kind==="article"?Lo(a.paths[0]):kn(a.paths);return}if(i.escape){xt(null);return}return}if(ke){if(i.escape){nt(null);return}if(i.upArrow){nt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){nt(a=>a&&{...a,cursor:Math.min(Math.max(0,wn.length-1),a.cursor+1)});return}if(i.return){let a=wn[ke.cursor];if(a){nt(null);try{d({kind:"preview",name:ln(a),text:Rl(fs(dt(e,a),"utf8"))})}catch(g){d({kind:"note",tone:"error",text:`Could not read ${a}: ${g.message}`})}}return}if(i.backspace||i.delete){nt(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){nt(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(xe){if(i.escape){rt(null);return}if(i.upArrow){rt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){rt(a=>a&&{...a,cursor:Math.min(Math.max(0,yn.length-1),a.cursor+1)});return}if(i.return){let a=yn[xe.cursor];if(a){rt(null),he(a.uuid),De.current={uuid:a.uuid,firstPrompt:a.firstPrompt,titleFired:!0},Xe(a.name),ms(a.uuid),gt.current=[];let g=ls(e,a.uuid);for(let u of g)d(u);d({kind:"note",tone:"ok",text:g.length?`Resumed "${a.name}" \u2014 restored ${g.length} message(s); continue where you left off.`:`Resumed "${a.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(i.backspace||i.delete){rt(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){rt(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(i.tab&&!D&&Pe){y(Pe),le(null),pt.current++;return}if(!D&&ze.length>0&&l&&/^[1-9]$/.test(l)){let a=ze[Number(l)-1];if(a){y(a);return}}if(!D&&(Io||So)&&l==="c"&&!i.ctrl&&!i.meta&&!i.return&&!i.tab){let a=Io!=null;Va(Io??So).then(u=>{d({kind:"note",tone:u?"ok":"warn",text:u?a?"\u2713 Copied the feedback to your clipboard \u2014 send it to the d360-writer team (Teams / Slack / email).":"\u2713 Copied the prompt to your clipboard \u2014 paste it into your repo's coding agent.":a?"Couldn't reach your clipboard \u2014 select the feedback above and copy it manually.":"Couldn't reach your clipboard \u2014 select the prompt above and copy it manually."}),u&&a&&No(null)});return}if(!Hs(l,i)){if(Ns){if(i.upArrow){mt(a=>Math.max(0,a-1));return}if(i.downArrow){mt(a=>Math.min(Bt.length-1,a+1));return}if(i.tab){y("/"+(Bt[Lt]?.name??"")+" "),mt(0);return}if(i.return){let a=Bt[Lt];if(a){let g=D.trim().slice(1).split(/\s+/).slice(1).join(" ");if(nl(a.usage)&&!g){y("/"+a.name+" "),mt(0);return}Cn("/"+a.name+(g?" "+g:""));return}}}else{if(i.upArrow){if(D!==""&&ht===null){Pn(-1);return}let a=$o.current;if(!a.length)return;let g=ht===null?a.length-1:Math.max(0,ht-1);pn(g),y(a[g]??"");return}if(i.downArrow){if(D!==""&&ht===null){Pn(1);return}let a=$o.current;if(ht===null)return;let g=ht+1;g>=a.length?(pn(null),y("")):(pn(g),y(a[g]??""));return}}if(i.return){Cn();return}if(i.backspace||i.delete){C();return}if(i.escape){y(""),mt(0),le(null),Y([]),tt(null);return}l&&!i.ctrl&&!i.meta&&Ws(l)}}}),Ce(()=>{if(I||L)return;let l=ot.current.shift();l!==void 0&&(Po([...ot.current]),Cn(l))},[I,L,Cn]),B(ne,{flexDirection:"column",width:Ae,children:[Oo!==null&&B(ne,{marginTop:1,flexDirection:"column",children:[Oo.truncated&&A(T,{dimColor:!0,children:"\u2026"}),A(T,{children:Oo.text})]}),I&&(Ss?A(om,{p:Ss}):A(tm,{startTime:Ke.current,chars:Ul})),A(ne,{borderStyle:"round",borderColor:Is.prod?"yellow":W,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:D?Fs.map((l,i)=>{let a=b.text.slice(l.start,l.end),g=i===mo(Fs,b.pos),u=Math.min(b.pos,l.end)-l.start;return B(T,{children:[A(T,{color:W,children:i===0?"> ":" "}),g?B(gs,{children:[a.slice(0,u),A(wo,{ch:a[u]??" "}),a.slice(u+1)]}):a||" "]},`${i}-${l.start}`)}):B(T,{children:[A(T,{color:W,children:"> "}),Pe&&!I?B(gs,{children:[A(wo,{ch:Pe[0],dim:!0}),A(T,{color:"gray",children:Pe.slice(1)}),A(T,{dimColor:!0,children:" (tab)"})]}):(Mo.isSetup||!Ol)&&!I?B(gs,{children:[A(wo,{ch:Mo.text[0],dim:!0}),A(T,{color:"gray",children:Mo.text.slice(1)})]}):A(wo,{ch:" "})]})}),Ts.length>0&&A(ne,{flexDirection:"column",paddingX:1,children:Ts.map((l,i)=>A(T,{color:"gray",children:`\u29D7 queued: ${l}`},`${i}-${l.slice(0,24)}`))}),Ro?A(rl,{tab:Ro.tab,width:Ae}):Je?B(ne,{flexDirection:"column",paddingX:1,children:[A(T,{color:W,bold:!0,children:"Select model"}),A(T,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer.json still wins)."}),Se.map((l,i)=>B(T,{color:i===Je.cursor?W:void 0,children:[i===Je.cursor?"\u276F ":" ",`${i+1}. ${l.label}${i===Je.current?" \u2714":""}`.padEnd(16),A(T,{color:"gray",children:l.desc})]},l.label)),A(T,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):je?B(ne,{flexDirection:"column",paddingX:1,children:[A(T,{color:W,bold:!0,children:"Switch connection profile"}),je.rows.map((l,i)=>B(T,{color:i===je.cursor?W:void 0,children:[i===je.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===je.current?" \u2714":""}`.padEnd(20),A(T,{color:"gray",children:`${l.env} \xB7 ${l.who??"not signed in"}`}),l.prod?A(T,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},l.name)),A(T,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):We?B(ne,{flexDirection:"column",paddingX:1,children:[A(T,{color:W,bold:!0,children:"Pick your Document360 environment"}),We.rows.map((l,i)=>B(T,{color:i===We.cursor?W:void 0,children:[i===We.cursor?"\u276F ":" ",`${i+1}. ${l.name}`.padEnd(16),A(T,{color:"gray",children:l.apiUrl})]},l.name)),A(T,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):pe?B(ne,{flexDirection:"column",paddingX:1,children:[A(T,{color:W,bold:!0,children:"Switch workspace"}),A(T,{dimColor:!0,children:`environment ${pe.environment} \xB7 project ${pe.projectName??`${pe.projectId.slice(0,8)}\u2026`}`}),pe.rows.map((l,i)=>B(T,{color:i===pe.cursor?W:void 0,children:[i===pe.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===pe.current?" \u2714":""}`.padEnd(30),A(T,{color:"gray",children:l.type??""})]},l.id)),A(T,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):ye?B(ne,{flexDirection:"column",paddingX:1,children:[A(T,{color:W,bold:!0,children:"Choose project"}),A(T,{dimColor:!0,children:`environment ${ye.environment}`}),ye.rows.map((l,i)=>B(T,{color:i===ye.cursor?W:void 0,children:[i===ye.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===ye.current?" \u2714":""}`.padEnd(30),A(T,{color:"gray",children:l.sub??""})]},l.id)),A(T,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):me?(()=>{let i=Math.min(Math.max(0,me.cursor-Math.floor(7)),Math.max(0,me.rows.length-14)),a=me.rows.slice(i,i+14),g=me.rows.filter(u=>u.checked).length;return B(ne,{flexDirection:"column",paddingX:1,children:[A(T,{color:W,bold:!0,children:`Which folders back the user docs? (${g} selected of ${me.rows.length})`}),i>0?A(T,{dimColor:!0,children:` \u2191 ${i} more`}):null,a.map((u,m)=>{let w=i+m;return B(T,{color:w===me.cursor?W:void 0,children:[w===me.cursor?"\u276F ":" ",u.checked?"\u25C9 ":"\u25CB ",u.path.padEnd(Math.min(48,Ae-34)),A(T,{color:"gray",children:Bn(u)})]},u.path)}),i+14<me.rows.length?A(T,{dimColor:!0,children:` \u2193 ${me.rows.length-i-14} more`}):null,A(T,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():et?B(ne,{flexDirection:"column",paddingX:1,children:[A(T,{color:W,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),et.rows.map((l,i)=>{let a=i===et.cursor,g=l.indent?" ":" ",u=`${i+1}.`.padEnd(3);return B(T,{color:a?W:void 0,bold:l.kind==="category"&&!a,children:[a?"\u276F ":" ",`${g}${u} ${l.label}`.padEnd(Math.min(56,Ae-24)),l.note?A(T,{color:"gray",children:l.note}):null]},`${l.kind}:${l.paths.join(",")}`)}),A(T,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):ke?B(ne,{flexDirection:"column",paddingX:1,children:[A(T,{color:W,bold:!0,children:`Preview article${ke.query?` \u2014 filter: ${ke.query}`:" (type to filter)"}`}),wn.length===0?A(T,{color:"gray",children:"no articles match"}):wn.map((l,i)=>B(T,{color:i===ke.cursor?W:void 0,children:[i===ke.cursor?"\u276F ":" ",l]},l)),A(T,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):xe?B(ne,{flexDirection:"column",paddingX:1,children:[A(T,{color:W,bold:!0,children:`Resume session${xe.query?` \u2014 filter: ${xe.query}`:" (type to filter)"}`}),yn.length===0?A(T,{color:"gray",children:"no sessions match"}):yn.map((l,i)=>B(T,{color:i===xe.cursor?W:void 0,children:[i===xe.cursor?"\u276F ":" ",l.name.slice(0,28).padEnd(30),A(T,{color:i===xe.cursor?W:"gray",children:l.firstPrompt.slice(0,Math.max(10,Ae-40))})]},l.uuid)),A(T,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Ns?B(ne,{flexDirection:"column",children:[Bt.map((l,i)=>B(T,{color:i===Lt?W:void 0,children:[i===Lt?"\u276F ":" ",l.usage.padEnd(22)," ",A(T,{color:i===Lt?W:"gray",children:l.name==="model"&&To?`${l.desc} (currently ${To})`:l.desc})]},l.name)),A(T,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!I&&!D&&ze.length>0?B(ne,{flexDirection:"column",paddingX:1,children:[Rs?A(T,{color:W,children:Rs}):null,ze.map((l,i)=>{let a=l.slice(0,Math.max(20,Ae-5)),g=Ae-a.length-7,u=g>=12?el(l).slice(0,g):"";return B(T,{children:[A(T,{color:W,children:i+1})," ",a,u?A(T,{dimColor:!0,children:` \u2014 ${u}`}):null]},l)}),A(T,{dimColor:!0,children:`press 1-${ze.length} to fill the command \xB7 esc dismiss`})]}):A(ne,{paddingX:1,children:B(T,{color:"gray",children:[Is.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${To??"model n/a"}${t.kind==="api"?js>0?` \xB7 ${fe(js)}`:"":Ds>0?` \xB7 ${Be(Ds)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}F();import{jsx as am}from"react/jsx-runtime";async function Al(e=process.cwd(),t="auto",n,o="0.0.0"){let r=im(t);r.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${N("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${N("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=sm(am(jl,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
|
|
296
|
-
`),process.exit(0)}
|
|
297
|
-
|
|
294
|
+
`)}),Pt(it()),Ht.current=Ie(e).status==="current"||Xt(e);return}case"inbox":{if(!ee(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(Gr(e)===0){d({kind:"note",tone:"info",text:"Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)"});return}await ce(Vr(),{display:"/inbox",quietUser:!0});return}case"document":{if(!ee(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:u,what:m}=_r(g);if(!m&&Nr(e)===0){d({kind:"note",tone:"info",text:Or});return}let w=`/document${m?` ${m}`:""}${u?" --publish":""}`;await ce(Mr(m,u),{display:w,quietUser:!0});return}case"catch-up":{if(!ee(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!Eo(l.trim()))return;let{publish:u}=Kr(g);d({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let m=await Jr({cwd:e,profileName:s});for(let k of Qr(m))d({kind:"note",tone:k.startsWith("\u2713")?"ok":k.startsWith("\u2139")?"info":"warn",text:k});let w=_t(Nt(e));d({kind:"note",tone:"info",text:w?`Catching up on ${w}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"}),await ce(Xr({publish:u}),{display:`/catch-up${u?" --publish":""}`,quietUser:!0});return}case"update":{jo.current=!0,d({kind:"note",tone:"info",text:`Updating ${ut}\u2026 (don\u2019t close this window)`}),dn(!0),(await Zn().finally(()=>dn(!1))).ok?(d({kind:"note",tone:"ok",text:"\u2713 Updated \u2014 run /exit, then relaunch to apply."}),Y(m=>m.includes("/exit")?m:[...m,"/exit"]),Cs("")):d({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${Qn}`});return}case"screenshot":{let u=Hr(g);if(u.mode==="list"){if(!ee(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:Br(qr(e,u.scope),u.scope).join(`
|
|
295
|
+
`)});return}if(u.mode==="single"){let O=await Xn(g);O.kind==="forward-to-agent"&&O.prompt&&await ce(O.prompt,{display:O.display,quietUser:!0});return}if(!ee(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=u.mode==="scope"?u.scope:void 0,w=Bf(e,{scope:m}).map(O=>O.id);if(w.length===0){d({kind:"note",tone:"info",text:m?`No screenshot placeholders under ${m}.`:"No screenshot placeholders found in the docs."});return}let k=6,R=qf(w,3),S=go(e,"standard");Ke.current=Date.now(),ft(0),_(!0);let J=new AbortController;xe.current=J,te({verb:"Authoring",unit:"spec",total:R.length,done:0,active:[],rows:an(R),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Authoring ${w.length} screenshot spec${w.length===1?"":"s"} across ${R.length} partition${R.length===1?"":"s"} (\u2264${k} agents at once) on ${S.model}${S.forced?" (forced)":""}\u2026 (esc to stop)`});let q=!1;try{for await(let O of ho({cwd:e,partitions:R,promptFor:Ta,concurrency:k,profileName:s,allowProdWrites:wt.current,model:S.model,signal:J.signal}))if(O.type==="partition_status")O.status==="running"?te($=>$&&{...$,active:[...$.active,O.label],rows:_e($.rows,O.label,"active"),lastAt:Date.now()}):te($=>$&&{...$,active:$.active.filter(j=>j!==O.label),done:$.done+1,rows:_e($.rows,O.label,O.status==="done"?"done":"failed"),lastAt:Date.now()});else if(O.type==="partition_event")te($=>{if(!$)return $;let j={...$,lastAt:Date.now()};return O.event.type==="tool"?j.tools=$.tools+1:O.event.type==="text"&&(j.chars=$.chars+O.event.delta.length),j});else if(O.type==="run_done"){Ct(z=>z+O.totalCostUsd),vt(z=>z+O.results.reduce((ge,Tt)=>ge+Tt.outputTokens,0));let $=O.results.filter(z=>z.ok).length,j=O.aborted?"Stopped. ":"";q=!O.aborted&&u.setup;let U=O.aborted?"":q?" Refreshing the capture-setup checklist\u2026":" Next: /capture-setup, then d360-capture capture.";d({kind:"note",tone:O.aborted?"warn":O.ok?"ok":"warn",text:`${j}Authored specs \u2014 ${$}/${O.results.length} batches ok.${U}`})}}catch(O){d({kind:"note",tone:"error",text:`Spec authoring failed: ${O.message}`})}finally{xe.current=null,te(null),_(!1),ie(O=>O+1)}if(q){let O=await sn();O.kind==="forward-to-agent"&&O.prompt&&await ce(O.prompt,{display:O.display,quietUser:!0});let $=Yr(e);$&&d({kind:"note",tone:"info",text:$.join(`
|
|
296
|
+
`)})}return}case"reset":{let u=ts(e);if(u.length===0){d({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}vo.current={repoName:ln(e),targets:u,hadDevhints:Ge(bs(e))},d({kind:"note",tone:"warn",text:os(e,u).join(`
|
|
297
|
+
`)}),le(ln(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${a} \u2014 type /help.`})}},[e,r,s,vn,d,he,ce,kn,Lo,Os]),Cn=G(l=>{let i=(l??D).trim();if(y(""),pn(null),mt(0),i.startsWith("/")&&(le(null),pt.current++,tt(null),Y(g=>cl(g,i))),!i||Us(i)||Ls(i))return;$o.current.push(i);let a=ml(i,Ps.current);i.startsWith("/")?(d({kind:"user",text:i}),Ws(a)):ce(a,{display:i})},[D,Us,Ls,Ws,ce]),Fs=G(l=>{if(l.length>1){if(l.includes("\x1B"))return;let i=dl(l);if(pl(i)){let a=fl(++Hl.current,i);Ps.current.set(a,i),P(a)}else P(i);return}P(l)},[P]),Rt=Math.max(10,Ae-6),Hs=fs(()=>fo(b.text,Rt),[b.text,Rt]),Fo=G(l=>x(i=>({...i,pos:Math.max(0,Math.min(i.text.length,i.pos+l))})),[]),Pn=G(l=>x(i=>({...i,pos:gl(fo(i.text,Rt),i.pos,l)})),[Rt]),Yt=G(l=>x(i=>({...i,pos:wl(fo(i.text,Rt),i.pos,l)})),[Rt]),Yl=["\x1B[H","\x1B[1~","\x1BOH"],Gl=["\x1B[F","\x1B[4~","\x1BOF"],qs=G((l,i)=>i.leftArrow?(Fo(-1),!0):i.rightArrow?(Fo(1),!0):l&&Yl.includes(l)?(Yt("start"),!0):l&&Gl.includes(l)?(Yt("end"),!0):i.ctrl&&l==="a"?(Yt("start"),!0):i.ctrl&&l==="e"?(Yt("end"),!0):!1,[Fo,Yt]);return ff((l,i)=>{if(i.ctrl&&l==="c"){ye.current?.close(),r();return}if(!L){if(I){if(i.escape){if(xe.current){xe.current.signal.aborted||(d({kind:"note",tone:"warn",text:"\u238B Stopping the convert run (finishing in-flight articles)\u2026"}),xe.current.abort());return}Ut.current||(Ut.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),ye.current?.interrupt());return}if(i.return){let a=D.trim();if(!a)return;ot.current.push(a),Po([...ot.current]),y("");return}if(qs(l,i))return;if(i.upArrow){Pn(-1);return}if(i.downArrow){Pn(1);return}if(i.backspace||i.delete){C();return}l&&!i.ctrl&&!i.meta&&Fs(l);return}if(Je){if(i.upArrow){Qe(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Qe(a=>a&&{...a,cursor:Math.min(Se.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Se.length){Qe(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=Se[Je.cursor];Qe(null);let{lines:g,changed:u,effective:m}=on(e,a.value??"default");for(let w of g)d({kind:"note",tone:w.startsWith("\u26A0")?"warn":w.startsWith("\u2713")?"ok":"info",text:w});u&&(Es(w=>w+1),ye.current?.setModel(m));return}if(l==="s"){let a=Se[Je.cursor];Qe(null),ye.current?.setModel(a.value??void 0),d({kind:"note",tone:"ok",text:`\u2713 Using ${a.label} for this session only (your saved default is unchanged).`});return}if(i.escape){Qe(null);return}return}if(je){if(i.upArrow){yt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){yt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=je.rows.length){yt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return||l==="s"){let a=je.rows[je.cursor];yt(null),Wo(a.name,i.return===!0);return}if(i.escape){yt(null);return}return}if(Ro){if(i.escape){Ft(null);return}if(i.leftArrow||i.tab&&i.shift){Ft(a=>a&&{tab:(a.tab-1+Ce.length)%Ce.length});return}if(i.rightArrow||i.tab){Ft(a=>a&&{tab:(a.tab+1)%Ce.length});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Ce.length){Ft({tab:Number(l)-1});return}return}if(We){if(i.upArrow){kt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){kt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=We.rows.length){kt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=We.rows[We.cursor].name;if(kt(null),!vi(e,a).created){d({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer.json already exists."});return}d({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer.json (environment "${a}").`});let u=!1;try{let m=Ve(a);u=!!m&&!(Oe(m)&&!m.refreshToken)}catch{u=!1}d({kind:"note",tone:"info",text:u?`Next: sign in to ${a} and pick your project \u2014 you're already signed in here, so it'll be quick. (press 1)`:`Next: sign in to Document360 (${a}) and pick your project. (press 1)`}),Y(["/login"]),ie(m=>m+1);return}if(i.escape){kt(null);return}return}if(pe){if(i.upArrow){bt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){bt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=pe.rows.length){bt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=pe.rows[pe.cursor],{profile:g,projectId:u}=pe;bt(null),bn(g,u,a);return}if(i.escape){bt(null);return}return}if(ke){if(i.upArrow){Ze(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Ze(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=ke.rows.length){Ze(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=ke.rows[ke.cursor],{profile:g}=ke;Ze(null),$n(g,a);return}if(i.escape){Ze(null);return}return}if(me){if(i.upArrow){$t(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){$t(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l===" "){$t(a=>a&&{...a,rows:a.rows.map((g,u)=>u===a.cursor?{...g,checked:!g.checked}:g)});return}if(i.return){let a=me.rows.filter(g=>g.checked).map(g=>g.path);if($t(null),a.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}dr(e,a),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${a.length} folder(s) \u2014 written to .d360-writer.json`});for(let g of a)d({kind:"note",tone:"info",text:` ${g}`});d({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(i.escape){$t(null);return}return}if(et){if(i.upArrow){xt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){xt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=et.rows.length){xt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=et.rows[et.cursor];xt(null),a.kind==="article"?Lo(a.paths[0]):kn(a.paths);return}if(i.escape){xt(null);return}return}if(be){if(i.escape){nt(null);return}if(i.upArrow){nt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){nt(a=>a&&{...a,cursor:Math.min(Math.max(0,wn.length-1),a.cursor+1)});return}if(i.return){let a=wn[be.cursor];if(a){nt(null);try{d({kind:"preview",name:ln(a),text:Sl(ms(dt(e,a),"utf8"))})}catch(g){d({kind:"note",tone:"error",text:`Could not read ${a}: ${g.message}`})}}return}if(i.backspace||i.delete){nt(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){nt(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if($e){if(i.escape){rt(null);return}if(i.upArrow){rt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){rt(a=>a&&{...a,cursor:Math.min(Math.max(0,yn.length-1),a.cursor+1)});return}if(i.return){let a=yn[$e.cursor];if(a){rt(null),he(a.uuid),De.current={uuid:a.uuid,firstPrompt:a.firstPrompt,titleFired:!0},Xe(a.name),hs(a.uuid),gt.current=[];let g=cs(e,a.uuid);for(let u of g)d(u);d({kind:"note",tone:"ok",text:g.length?`Resumed "${a.name}" \u2014 restored ${g.length} message(s); continue where you left off.`:`Resumed "${a.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(i.backspace||i.delete){rt(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){rt(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(i.tab&&!D&&Re){y(Re),le(null),pt.current++;return}if(!D&&ze.length>0&&l&&/^[1-9]$/.test(l)){let a=ze[Number(l)-1];if(a){y(a);return}}if(!D&&(Io||So)&&l==="c"&&!i.ctrl&&!i.meta&&!i.return&&!i.tab){let a=Io!=null;Ka(Io??So).then(u=>{d({kind:"note",tone:u?"ok":"warn",text:u?a?"\u2713 Copied the feedback to your clipboard \u2014 send it to the d360-writer team (Teams / Slack / email).":"\u2713 Copied the prompt to your clipboard \u2014 paste it into your repo's coding agent.":a?"Couldn't reach your clipboard \u2014 select the feedback above and copy it manually.":"Couldn't reach your clipboard \u2014 select the prompt above and copy it manually."}),u&&a&&No(null)});return}if(!qs(l,i)){if(_s){if(i.upArrow){mt(a=>Math.max(0,a-1));return}if(i.downArrow){mt(a=>Math.min(Bt.length-1,a+1));return}if(i.tab){y("/"+(Bt[Lt]?.name??"")+" "),mt(0);return}if(i.return){let a=Bt[Lt];if(a){let g=D.trim().slice(1).split(/\s+/).slice(1).join(" ");if(rl(a.usage)&&!g){y("/"+a.name+" "),mt(0);return}Cn("/"+a.name+(g?" "+g:""));return}}}else{if(i.upArrow){if(D!==""&&ht===null){Pn(-1);return}let a=$o.current;if(!a.length)return;let g=ht===null?a.length-1:Math.max(0,ht-1);pn(g),y(a[g]??"");return}if(i.downArrow){if(D!==""&&ht===null){Pn(1);return}let a=$o.current;if(ht===null)return;let g=ht+1;g>=a.length?(pn(null),y("")):(pn(g),y(a[g]??""));return}}if(i.return){Cn();return}if(i.backspace||i.delete){C();return}if(i.escape){y(""),mt(0),le(null),Y([]),tt(null);return}l&&!i.ctrl&&!i.meta&&Fs(l)}}}),Pe(()=>{if(I||L)return;let l=ot.current.shift();l!==void 0&&(Po([...ot.current]),Cn(l))},[I,L,Cn]),B(ne,{flexDirection:"column",width:Ae,children:[Oo!==null&&B(ne,{marginTop:1,flexDirection:"column",children:[Oo.truncated&&E(T,{dimColor:!0,children:"\u2026"}),E(T,{children:Oo.text})]}),I&&(Ds?E(am,{p:Ds}):E(sm,{startTime:Ke.current,chars:Fl})),E(ne,{borderStyle:"round",borderColor:Ns.prod?"yellow":F,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:D?Hs.map((l,i)=>{let a=b.text.slice(l.start,l.end),g=i===mo(Hs,b.pos),u=Math.min(b.pos,l.end)-l.start;return B(T,{children:[E(T,{color:F,children:i===0?"> ":" "}),g?B(ws,{children:[a.slice(0,u),E(wo,{ch:a[u]??" "}),a.slice(u+1)]}):a||" "]},`${i}-${l.start}`)}):B(T,{children:[E(T,{color:F,children:"> "}),Re&&!I?B(ws,{children:[E(wo,{ch:Re[0],dim:!0}),E(T,{color:"gray",children:Re.slice(1)}),E(T,{dimColor:!0,children:" (tab)"})]}):(Mo.isSetup||!Ul)&&!I?B(ws,{children:[E(wo,{ch:Mo.text[0],dim:!0}),E(T,{color:"gray",children:Mo.text.slice(1)})]}):E(wo,{ch:" "})]})}),Ss.length>0&&E(ne,{flexDirection:"column",paddingX:1,children:Ss.map((l,i)=>E(T,{color:"gray",children:`\u29D7 queued: ${l}`},`${i}-${l.slice(0,24)}`))}),Ro?E(il,{tab:Ro.tab,width:Ae}):Je?B(ne,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:"Select model"}),E(T,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer.json still wins)."}),Se.map((l,i)=>B(T,{color:i===Je.cursor?F:void 0,children:[i===Je.cursor?"\u276F ":" ",`${i+1}. ${l.label}${i===Je.current?" \u2714":""}`.padEnd(16),E(T,{color:"gray",children:l.desc})]},l.label)),E(T,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):je?B(ne,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:"Switch connection profile"}),je.rows.map((l,i)=>B(T,{color:i===je.cursor?F:void 0,children:[i===je.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===je.current?" \u2714":""}`.padEnd(20),E(T,{color:"gray",children:`${l.env} \xB7 ${l.who??"not signed in"}`}),l.prod?E(T,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},l.name)),E(T,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):We?B(ne,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:"Pick your Document360 environment"}),We.rows.map((l,i)=>B(T,{color:i===We.cursor?F:void 0,children:[i===We.cursor?"\u276F ":" ",`${i+1}. ${l.name}`.padEnd(16),E(T,{color:"gray",children:l.apiUrl})]},l.name)),E(T,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):pe?B(ne,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:"Switch workspace"}),E(T,{dimColor:!0,children:`environment ${pe.environment} \xB7 project ${pe.projectName??`${pe.projectId.slice(0,8)}\u2026`}`}),pe.rows.map((l,i)=>B(T,{color:i===pe.cursor?F:void 0,children:[i===pe.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===pe.current?" \u2714":""}`.padEnd(30),E(T,{color:"gray",children:l.type??""})]},l.id)),E(T,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):ke?B(ne,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:"Choose project"}),E(T,{dimColor:!0,children:`environment ${ke.environment}`}),ke.rows.map((l,i)=>B(T,{color:i===ke.cursor?F:void 0,children:[i===ke.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===ke.current?" \u2714":""}`.padEnd(30),E(T,{color:"gray",children:l.sub??""})]},l.id)),E(T,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):me?(()=>{let i=Math.min(Math.max(0,me.cursor-Math.floor(7)),Math.max(0,me.rows.length-14)),a=me.rows.slice(i,i+14),g=me.rows.filter(u=>u.checked).length;return B(ne,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:`Which folders back the user docs? (${g} selected of ${me.rows.length})`}),i>0?E(T,{dimColor:!0,children:` \u2191 ${i} more`}):null,a.map((u,m)=>{let w=i+m;return B(T,{color:w===me.cursor?F:void 0,children:[w===me.cursor?"\u276F ":" ",u.checked?"\u25C9 ":"\u25CB ",u.path.padEnd(Math.min(48,Ae-34)),E(T,{color:"gray",children:Bn(u)})]},u.path)}),i+14<me.rows.length?E(T,{dimColor:!0,children:` \u2193 ${me.rows.length-i-14} more`}):null,E(T,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():et?B(ne,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),et.rows.map((l,i)=>{let a=i===et.cursor,g=l.indent?" ":" ",u=`${i+1}.`.padEnd(3);return B(T,{color:a?F:void 0,bold:l.kind==="category"&&!a,children:[a?"\u276F ":" ",`${g}${u} ${l.label}`.padEnd(Math.min(56,Ae-24)),l.note?E(T,{color:"gray",children:l.note}):null]},`${l.kind}:${l.paths.join(",")}`)}),E(T,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):be?B(ne,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:`Preview article${be.query?` \u2014 filter: ${be.query}`:" (type to filter)"}`}),wn.length===0?E(T,{color:"gray",children:"no articles match"}):wn.map((l,i)=>B(T,{color:i===be.cursor?F:void 0,children:[i===be.cursor?"\u276F ":" ",l]},l)),E(T,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):$e?B(ne,{flexDirection:"column",paddingX:1,children:[E(T,{color:F,bold:!0,children:`Resume session${$e.query?` \u2014 filter: ${$e.query}`:" (type to filter)"}`}),yn.length===0?E(T,{color:"gray",children:"no sessions match"}):yn.map((l,i)=>B(T,{color:i===$e.cursor?F:void 0,children:[i===$e.cursor?"\u276F ":" ",l.name.slice(0,28).padEnd(30),E(T,{color:i===$e.cursor?F:"gray",children:l.firstPrompt.slice(0,Math.max(10,Ae-40))})]},l.uuid)),E(T,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):_s?B(ne,{flexDirection:"column",children:[Bt.map((l,i)=>B(T,{color:i===Lt?F:void 0,children:[i===Lt?"\u276F ":" ",l.usage.padEnd(22)," ",E(T,{color:i===Lt?F:"gray",children:l.name==="model"&&To?`${l.desc} (currently ${To})`:l.desc})]},l.name)),E(T,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!I&&!D&&ze.length>0?B(ne,{flexDirection:"column",paddingX:1,children:[Ts?E(T,{color:F,children:Ts}):null,ze.map((l,i)=>{let a=l.slice(0,Math.max(20,Ae-5)),g=Ae-a.length-7,u=g>=12?nl(l).slice(0,g):"";return B(T,{children:[E(T,{color:F,children:i+1})," ",a,u?E(T,{dimColor:!0,children:` \u2014 ${u}`}):null]},l)}),E(T,{dimColor:!0,children:`press 1-${ze.length} to fill the command \xB7 esc dismiss`})]}):E(ne,{paddingX:1,children:B(T,{color:"gray",children:[Ns.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${To??"model n/a"}${t.kind==="api"?As>0?` \xB7 ${fe(As)}`:"":js>0?` \xB7 ${Be(js)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}W();import{jsx as dm}from"react/jsx-runtime";async function Il(e=process.cwd(),t="auto",n,o="0.0.0"){let r=um(t);r.kind==="none"&&(console.error(""),console.error(v("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${N("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${N("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=cm(dm(El,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
|
|
298
|
+
`),process.exit(0)}W();import{writeCrashLog as Nl,isBenignTransportError as pm}from"document360-engine";var _l=!1;function xs(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function Ml(e){if(_l)return;_l=!0;let t=(n,o)=>{if(pm(o)){Nl({kind:n,level:"transport",message:xs(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=Nl({kind:n,level:"fatal",message:xs(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
|
|
299
|
+
`+v(`\u2717 d360-writer crashed: ${xs(o)}`)+`
|
|
298
300
|
`),r&&process.stderr.write(f(` Crash details: ${r}`)+`
|
|
299
301
|
`+f(" Run: d360-writer logs")+`
|
|
300
|
-
`),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var
|
|
302
|
+
`),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var gm=mm(import.meta.url),Ol=gm("../package.json");Ml("d360-writer");var Le=new fm;function $s(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}Le.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=>{$s(e),await Dn({profile:e.profile,manual:e.manual})});Le.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{$s(e),await ti({profile:e.profile})});Le.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{$s(e),await ei({profile:e.profile})});var vs=Le.command("profile").description("Manage connection profiles for the current repo");vs.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>jn(process.cwd()));vs.command("use <name>").description("Set the default profile for this repo").action(e=>An(process.cwd(),e));vs.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>En(process.cwd(),e));var Ll=Le.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");Ll.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>St(process.cwd(),e.profile));Ll.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await Gs(process.cwd(),e,t.profile)});Le.command("logs").description("Show the API + crash log files (send these to support when reporting a problem)").action(()=>si());Le.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(()=>(Kn(),ka)),n=await t(process.cwd());for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});Le.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(Ol.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(hm.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 ii(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 Va(e.cwd,e.auth,e.profile):await Il(e.cwd,e.auth,e.profile,Ol.version)});Le.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
|