document360-writer 0.5.113 → 0.5.115
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 +103 -103
- package/package.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var zd=Object.defineProperty;var co=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var na=(e,t)=>{for(var n in t)zd(e,n,{get:t[n],enumerable:!0})};import Ze from"picocolors";var q,Kd,Xd,Qd,oa,yn,f,R,L,D,O,ie,ke,W=co(()=>{"use strict";q="#7f56d9",[Kd,Xd,Qd]=[127,86,217],oa=e=>Ze.isColorSupported?`\x1B[38;2;${Kd};${Xd};${Qd}m${e}\x1B[39m`:e,yn=e=>Ze.bold(oa(e)),f=e=>Ze.dim(e),R=e=>Ze.red(e),L=e=>Ze.yellow(e),D=e=>Ze.green(e),O=oa,ie=e=>Ze.gray(e),ke=e=>Ze.bold(e)});import{existsSync as Yt,writeFileSync as tt,readFileSync as Ou,readdirSync as Lu}from"node:fs";import{join as va}from"node:path";import{devHintsGuidePath as bo,hintsDir as $a,hooksDir as xa,architectureDir as Sa,messagesDir as Wr,creatorNotesPath as Ca,devhintsStatePath as Da,directivesPath as Ra,DIRECTIVES_HEADER as Mu,roadmapPath as Pa,ROADMAP_HEADER as Uu,ensureDir as vn,writeMessage as Wu,listOpenForDev as Fu}from"document360-engine";function ja(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
|
|
3
3
|
|
|
4
|
-
<!-- devhints script v${
|
|
4
|
+
<!-- devhints script v${ae} \xB7 maintained by document360-writer (/devhints). -->
|
|
5
5
|
|
|
6
6
|
This repo's user documentation is written by **document360-writer** ("the docs agent"), a separate agent.
|
|
7
7
|
It can read your code, but code alone can't tell it the *intent* \u2014 WHY a feature exists, which of a
|
|
@@ -218,7 +218,7 @@ do it**:
|
|
|
218
218
|
**Do NOT write or action the documentation yourself** \u2014 same boundary as Part 2. Writing the article is the
|
|
219
219
|
docs agent's job; it actions open directives on its next \`/catch-up\` (as drafts) and flips each to \`[done]\`
|
|
220
220
|
with the article it wrote. You are only the relay so the ask is captured durably and travels via git.
|
|
221
|
-
`}function
|
|
221
|
+
`}function qu(){return`# Creator notes (optional \u2014 for the docs agent and the builder)
|
|
222
222
|
|
|
223
223
|
<!-- The ORIGINAL CREATOR's context. Most repos leave this empty \u2014 that's fine.
|
|
224
224
|
The builder agent reads this FIRST and treats it as authoritative when writing the architecture
|
|
@@ -232,12 +232,12 @@ Anything only a human knows that would help document this product. For example:
|
|
|
232
232
|
- Gotchas or non-obvious behavior.
|
|
233
233
|
|
|
234
234
|
(Replace these examples with your notes, or leave the file as-is to skip \u2014 it's optional.)
|
|
235
|
-
`}function
|
|
236
|
-
`)}
|
|
237
|
-
`)}function
|
|
238
|
-
`)}function
|
|
239
|
-
`)}),n.notifiedBuilder=!0))}catch{}return n}function
|
|
240
|
-
`)}function
|
|
235
|
+
`}function Kt(e){vn($a(e)),vn(Sa(e)),vn(Wr(e));for(let n of[$a(e),Wr(e)]){let o=va(n,".gitkeep");Yt(o)||tt(o,`# Keeps this document360-writer inbox tracked in git even when empty.
|
|
236
|
+
`)}Yt(Ca(e))||tt(Ca(e),qu()),Yt(Ra(e))||tt(Ra(e),Mu),Yt(Pa(e))||tt(Pa(e),Uu),tt(bo(e),ja()),vn(xa(e)),tt(va(xa(e),"open-questions.mjs"),Hu);let t=Ee(e);return Ea(e,new Date().toISOString()),t}async function Aa(e,t){for(let n of Xt(Kt(t.cwd)))console.log(n);return{kind:"continue"}}function bt(){return[`This is document360-writer's dev hand-off setup (v${ae}).`,'Connect this repository to document360-writer (its "docs agent" \u2014 a separate tool that writes this',"product's user documentation from your code, but needs your intent). This prompt is SAFE TO RUN MORE","THAN ONCE \u2014 paste it again whenever the product changes. At each step: create what is missing, reconcile","what already exists, and never duplicate, clobber a refined file, or delete human-written notes. In order:","","1. Read `.d360-writer/DEV-HINTS-GUIDE.md` \u2014 the full dev\u2192docs hand-off protocol (Parts 1\u20136). Follow it.","2. Architecture brief in `.d360-writer/architecture/` (per the guide). First read"," `.d360-writer/architecture/CREATOR-NOTES.md` and treat it as authoritative (it may be empty; never"," modify it). Then:"," \u2022 If no brief exists yet, write it now \u2014 a USER-DOC-enabling brief: product intent, user-facing"," surfaces, features and why a user reaches for each, roles/permission gating, core workflows,"," terminology \u2014 every claim citing the source file(s) that prove it. Skip internals (services, data"," access, infra, build/CI, tests)."," \u2022 If a brief already exists, UPDATE it to match the current code: add new surfaces/features, correct"," what changed, remove what was deleted \u2014 but preserve accurate existing content and any human edits."," Do NOT rewrite it from scratch. If nothing changed, leave it as is.","3. Persist the ongoing rule so teammates' agents inherit it: this repo's agent-memory file (CLAUDE.md,"," or AGENTS.md \u2014 whichever this repo already uses; create CLAUDE.md if neither exists) should contain a",' short "Documentation hand-off" section saying: on every user-facing change, drop a hint file in'," `.d360-writer/hints/` and keep `.d360-writer/architecture/` current \u2014 and SURFACE each hint drop in"," your reply (name the file + the one-line surface), never silently; NEVER write or publish the"," user-facing articles yourself (that is the docs agent's job \u2014 you only hand off); each session,"," check `.d360-writer/messages/` for open questions from the docs agent and answer them promptly and"," in full \u2014 an open docs question BLOCKS the documentation, and `[discovery]` questions define the"," whole product brief, so answer those in depth; AND when the"," human types `@d360-writer <directive>` in your session, append it as an `## [open] <directive>` block"," to `.d360-writer/directives.md` (create if absent) and commit \u2014 do NOT action it yourself (the docs"," agent picks it up on its next /catch-up) \u2014 all per `.d360-writer/DEV-HINTS-GUIDE.md`. If that section"," is already there, leave it (refine in place only if"," wrong) \u2014 do NOT add a duplicate. Then commit `.d360-writer/` and the memory-file change ONLY if"," something actually changed.","4. Wire the SESSION-START QUESTION NUDGE so open docs questions surface every session \u2014 a memory rule"," alone (step 3) is easy to forget. d360-writer already scaffolded a portable, dependency-free checker"," at `.d360-writer/hooks/open-questions.mjs` (prints a one-line nudge when open `from: docs` questions"," exist; silent otherwise). Register it with YOUR coding agent's session-start mechanism:"," \u2022 Claude Code (this repo has a `.claude/` dir): add a `SessionStart` hook to `.claude/settings.json`"," (create the file if absent) that runs `node .d360-writer/hooks/open-questions.mjs` \u2014 its stdout is"," added to your context at session start. MERGE into any existing hooks, do NOT clobber other"," settings, and skip if that exact hook is already there. Shape:",' {"hooks":{"SessionStart":[{"hooks":[{"type":"command","command":"node .d360-writer/hooks/open-questions.mjs"}]}]}}'," \u2022 Codex / other agents: no stdout-injecting session hook yet \u2014 rely on the step-3 memory rule, and"," optionally run `node .d360-writer/hooks/open-questions.mjs` yourself when starting a docs-touching"," session. Wire the same command once your agent gains a session-start trigger."," Commit the hook config (`.claude/settings.json` or the equivalent) with the rest. Idempotent \u2014 leave"," an existing hook alone.","5. Two-way messages (Part 3): check `.d360-writer/messages/` for open questions addressed to you"," (`from: docs`, `status: open`). Answer each IN FULL \u2014 an open docs question blocks the documentation,"," and `[discovery]`-tagged questions (what the product is, who it's for, its core mental model,"," misconceptions, positioning, terminology) define the whole product brief, so answer those in depth."," Fold durable facts into the architecture brief and drop a reply (`from: dev`, `kind: answer`,"," `re: <id>`) \u2014 then set the question's frontmatter `status: done`. If there are none, continue.","6. Then STOP and ask me for tribal knowledge \u2014 present it as a clearly-marked, standalone prompt on its"," own line (NOT buried in prose) and WAIT for my reply before doing anything else. Use this shape:",' "\u23F8 YOUR INPUT NEEDED \u2014 Any tribal knowledge that would help document this product? (folder map,',` terminology, what to prioritize or skip, gotchas.) Type it below, or reply 'none' / 'carry on' to skip."`," If I give you anything, phrase it clearly and append it to `.d360-writer/architecture/CREATOR-NOTES.md`"," (keep the existing header comment and every note already there; only add). If I say 'none'/'carry on', continue.",`7. Record completion: write/merge \`.d360-writer/devhints-state.json\` with {"completedVersion": ${ae},`,' "completedAt": "<UTC now>", "completedCommit": "<current HEAD short sha>"} (preserve any other keys'," already in the file, e.g. emittedAt). Include this file in the commit from step 3.","8. When everything is done, print the completion line, THEN the next command as its own copy-paste"," block so it is unmistakable. Pick the matching first line:",' \u2022 first-time setup: "\u2705 Setup complete. Now switch to the document360-writer terminal and paste this:"',' \u2022 a refresh (brief/notes already existed): "\u2705 Hand-off refreshed. Back in the document360-writer terminal, paste this:"'," Then, on its OWN line, fenced as a code block so it copies cleanly:"," ```"," write the docs for this repo"," ```"].join(`
|
|
237
|
+
`)}function Fr(e){try{let t=Ou(Da(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function Ea(e,t){let o={...Fr(e)??{},emittedVersion:ae,emittedAt:t};tt(Da(e),`${JSON.stringify(o,null,2)}
|
|
238
|
+
`)}function Ge(e){try{return Lu(Sa(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function Ee(e){let n=Fr(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<ae?"stale":"current",completedVersion:n}}function vo(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:ae};try{if(!Yt(bo(e)))return n;let o=Fr(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;ae>r&&(vn(Wr(e)),tt(bo(e),ja()),Ea(e,t),n.guideRefreshed=!0),ae>s&&(Fu(e).some(p=>p.kind==="request"&&p.subject.startsWith(Ta))||(Wu(e,{id:`onb${ae}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${Ta}${ae})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${ae}${s?` (you last completed v${s})`:""}.`,"Re-run the hand-off so the docs agent and this repo stay in step \u2014 run this prompt here:","",bt()].join(`
|
|
239
|
+
`)}),n.notifiedBuilder=!0))}catch{}return n}function $o(e){if(!Yt(bo(e)))return[];let t=Ee(e);return t.status==="current"?[]:[`\u{1F514} Your builder agent ${t.completedVersion?`is on v${t.completedVersion}`:"hasn't completed the hand-off yet"} \u2014 d360-writer's dev\u2194docs protocol is now v${ae}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,zt,bt(),zt,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function Hr(){return['document360-writer (its "docs agent") has been removed from this repository. Please undo its dev\u2192docs',"hand-off setup and restore this repo to how it was before \u2014 in order:","","1. In this repo's agent-memory file (CLAUDE.md, or AGENTS.md \u2014 whichever it edited), REMOVE the",' "Documentation hand-off" section that was added (the rule about dropping hint files in'," `.d360-writer/hints/`, keeping `.d360-writer/architecture/` current, checking"," `.d360-writer/messages/`, and relaying `@d360-writer` directives to `.d360-writer/directives.md`)."," Leave everything else in that file untouched.","2. The `.d360-writer/` folder is already deleted on disk. If it was committed, remove it from version"," control too \u2014 `git rm -r --cached .d360-writer` (if it still resolves) \u2014 and commit the deletions.","3. Do NOT recreate any of those files or follow the hand-off protocol anymore.","","That's it \u2014 this repo is back to its pre-docs-agent state."].join(`
|
|
240
|
+
`)}function xo(){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):",zt,Hr(),zt]}function Xt(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${ae}.`," Have them run the prompt below again \u2014 it now sets up two-way messages + on-demand docs.",""]:[],"\u2713 Wrote .d360-writer/DEV-HINTS-GUIDE.md + the .d360-writer/architecture/ (brief), .d360-writer/hints/, and .d360-writer/messages/ inboxes.","","\u{1F4CB} Copy this one prompt and run it in your repo's coding agent (Claude Code / Codex / Cursor):",zt,bt(),zt,"","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 zt,ae,Hu,Ta,nt=co(()=>{"use strict";zt="-".repeat(64),ae=10,Hu=`#!/usr/bin/env node
|
|
241
241
|
// d360-writer \u2014 session-start nudge for the builder ("John"). Surfaces open questions the docs agent
|
|
242
242
|
// ("Julie") left in .d360-writer/messages/ so they get answered, not forgotten. Self-contained (no deps);
|
|
243
243
|
// wired into your coding agent's session-start trigger by /devhints. See .d360-writer/DEV-HINTS-GUIDE.md.
|
|
@@ -275,56 +275,56 @@ try {
|
|
|
275
275
|
} catch {
|
|
276
276
|
/* a session-start nudge must never break the session */
|
|
277
277
|
}
|
|
278
|
-
`;
|
|
279
|
-
`),"utf8")}async function Hr(){let e=process.cwd(),t=Na(e);if(Xt(t)&&!await Hu({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let n=Ma(e)??Aa(e),o=await vn({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await vn({message:"Capture directory (where document360-capture .spec.ts files live):",default:_a}),s=await vn({message:"Screenshot output directory:",default:Oa}),l=await vn({message:"Default connection profile name:",default:"berlin"}),p=await vn({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),m={projectId:o,docsDir:Ia,captureDir:r,outputDir:s,profiles:{[l]:{connection:{environment:p},production:!1}},defaultProfile:l,authoritativeSourceFiles:Ua(e)},k=Gu(e);k?.terminologyGlossary&&(m.terminologyGlossary=k.terminologyGlossary),Ea(m,e),La(e);let g=zt(e);console.log(""),console.log(D(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${O(`d360-writer login --profile ${l}`)} ${f("(sign in; project & workspace auto-selected)")}`),console.log("");for(let T of Kt(g))console.log(T);return console.log(""),console.log(`${f("Then ask:")} ${O('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function Ma(e){let t=$o(e,"package.json");if(!Xt(t))return null;try{return JSON.parse(qu(t,"utf8")).name??null}catch{return null}}function Ua(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Xt($o(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=$o(e,n);Xt(o)&&!zu(o)&&t.push(n)}return t}function zu(e){try{return Bu(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var xo=ao(()=>{"use strict";W();ot()});var ql={};ea(ql,{doctorCommand:()=>Dn,renderDoctorChecks:()=>Hl,runDoctorChecks:()=>Fl});import{existsSync as Wf}from"node:fs";import{d360GetAll as Ff,getAccessToken as Hf,isExpired as Os,loadProfileMap as qf,loadTokens as Bf,packageSkillsDir as Ul,ENGINE_VERSION as Vf,projectConfigPath as Gf,readProjectConfig as Yf,DEFAULT_DOCS_DIR as zf,fetchManifestSummary as Kf,resolveActiveProfile as Xf,classifyClaudeAuth as Qf,CLAUDE_CODE_SETUP_HINT as Wl,resolveModelSetting as Jf,probeModel as Zf,detectAppType as eh,playbookSkillName as th,D360AuthError as nh}from"document360-engine";async function Fl(e,t){let n=[];n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${Vf}`});let o=Number(process.versions.node.split(".")[0]);n.push(o>=20?{level:"ok",label:`Node ${process.versions.node}`}:{level:"fail",label:`Node ${process.versions.node} \u2014 20+ required`,fix:"Install Node 20 or later (nodejs.org)"});let r=Qf();r.state==="ready"?n.push({level:"ok",label:`Claude auth: ${r.kind==="api"?"API key":"subscription (Claude Code login found)"}`}):r.state==="maybe"?n.push({level:"warn",label:"Claude: no Claude Code login found (may be in the macOS Keychain)",fix:`If a docs turn ends with no output, sign in to Claude Code. ${Wl}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:Wl});let s=Jf(e);if(n.push({level:"ok",label:`Model: ${s.model} (${s.source==="auto"?"auto \u2014 right-sized for docs; /model to change":s.source})`}),r.state==="ready"){let P=await Zf(e,s.model??void 0);P.ok?n.push({level:"ok",label:`Model reachable \u2014 replied in ${(P.latencyMs/1e3).toFixed(1)}s`}):P.timedOut?n.push({level:"fail",label:"Model unreachable \u2014 no response in 30s (a docs turn will hang, then end with 0 tokens / no output)",fix:`Usually a corporate proxy/firewall or org policy blocking the Claude model API. Check this machine's network access to the Claude endpoint; confirm with: claude -p "say hi"`}):n.push({level:"fail",label:`Model call failed \u2014 ${P.error??"no output"} (a docs turn will end with 0 tokens / no output)`,fix:'Check sign-in, the selected model (/model), and network access to the Claude endpoint; confirm with: claude -p "say hi"'})}let l=Yf(e);if(!l)return n.push({level:"fail",label:`No ${Gf(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${l.projectId}`});let p=(l.docsDir??zf).replace(/\/+$/,"");n.push(l.mode==="engineer"?{level:"warn",label:"Mode: engineer \u2014 agent may modify any source file (dogfooding)",fix:'Remove "mode" from .d360-writer/config.json for the writer-mode boundary'}:{level:"ok",label:`Mode: writer \u2014 edits limited to ${p}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let m=l.authoritativeSourceFiles??[];n.push(m.length>0?{level:"ok",label:`Sources: docs grounded in ${m.length} path(s) (${m.slice(0,3).join(", ")}${m.length>3?", \u2026":""})`}:{level:"warn",label:"Sources: not set \u2014 docs are grounded in the whole repo",fix:"Run: /scope to choose which files/folders the docs are written from"});let k=l.appType??eh(e);if(k){let P=l.appType?"from config":"auto-detected",N=k==="web"||k==="cli";n.push({level:"ok",label:`Genre: ${k} (${P})${N?` \u2192 ${th(k)} loaded`:" \u2014 no doc-type playbook for this genre yet (generic skills)"}`})}else n.push({level:"warn",label:"Genre: unclassified \u2014 no doc-type playbook is loading (generic output)",fix:"Run /genre <web|cli|service|library> to pick \u2014 raises docs to that genre's craft bar"});let g;try{g=Xf(e),n.push({level:"ok",label:`Profile: ${g.name} (${g.connection.name})${g.production?" \u26A0 PRODUCTION":""}`})}catch(P){return n.push({level:"fail",label:`Profile config: ${P.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let T=Bf(g.name);T?Os(T)&&!T.refreshToken?n.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):Os(T)?n.push({level:"warn",label:"Document360: token expired \u2014 will auto-refresh on next call"}):n.push({level:"ok",label:`Document360: logged in (until ${new Date(T.expiresAt).toLocaleString()})`}):n.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${g.name})`}),n.push(g.project.workspaceId?{level:"ok",label:`Workspace: ${g.project.workspaceName??g.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let v=qf(e,g.name);v?v.projectId&&g.project.projectId&&v.projectId!==g.project.projectId?n.push({level:"fail",label:`Category map projectId (${v.projectId}) \u2260 profile projectId (${g.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):n.push({level:"ok",label:`Category map: ${Object.keys(v.articles).length} articles, ${Object.keys(v.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${g.name}" (created on first /publish)`}),n.push(Wf(Ul())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${Ul()}`,fix:"Reinstall document360-writer (broken install)"});let _=Ee(e);if(_.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${le})`}):_.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${_.completedVersion}, current is v${le}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),T&&(!Os(T)||T.refreshToken)){let P={profile:g.name,connection:g.connection};try{await Hf(P);let S=await Ff(P,"/v3/projects");n.push({level:"ok",label:`API reachable (${g.connection.apiUrl}) \u2014 ${S.length} project(s) visible`})}catch(S){n.push({level:"fail",label:`API call failed: ${S.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let N=v?.projectId??g.project.projectId;if(N&&g.project.workspaceId)try{let S=await Kf(P,N,g.project.workspaceId);if(S){let M=(S.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Workspace sync manifest: available on ${g.connection.name} (${S.languages?.length??0} language${(S.languages?.length??0)===1?"":"s"}) \xB7 hash ${M||"(none)"}`})}else n.push({level:"warn",label:`Workspace sync manifest: not live on ${g.connection.name} yet`,fix:"No action needed \u2014 sync uses the per-article path until the manifest ships on this environment"})}catch(S){S instanceof nh||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(S.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${g.project.projectName??N})`,fix:"Run /login and pick this repo's project \u2014 your token is scoped to another project"}):n.push({level:"warn",label:`Workspace sync manifest: probe failed (${S.message.slice(0,80)})`})}}return n}function Hl(e){let t=[""];for(let r of e){let s=r.level==="ok"?D("\u2713"):r.level==="warn"?L("\u26A0"):R("\u2717");t.push(` ${s} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("fix:")} ${O(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?D(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):R(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function Dn(e,t){console.log(f("Running checks\u2026"));for(let n of Hl(await Fl(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var Lo=ao(()=>{"use strict";ot();W()});import{Command as vw}from"commander";import{createRequire as $w}from"node:module";import{AUTH_MODES as xw}from"document360-engine";import{input as cu}from"@inquirer/prompts";import{loginPkce as du,refreshTokens as uu,toStoredTokens as aa,clearTokens as pu,decodeJwtClaims as ia,isExpired as fu,loadTokens as hu,saveTokens as la,resolveActiveProfile as po,setProfileProject as mu,readProjectConfig as gu}from"document360-engine";W();import{select as Xd}from"@inquirer/prompts";import{resolveActiveProfile as Qd,setProfileProject as Jd,resolveProjectId as Zd,listWorkspaces as eu}from"document360-engine";async function yn(e,t){let n=Qd(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Zd(o);return{workspaces:await eu(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var na=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function Nr(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 lo(e,t,n,o,r){Jd(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function oa(e,t,n){let o;try{o=await yn(e,n)}catch(s){return console.log(R(`Could not list workspaces: ${s.message}`)),1}let r=Nr(o.workspaces,t);return r?(lo(e,o.profile,o.projectId,r.id,r.name),console.log(D(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(R(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function Vt(e,t){let n;try{n=await yn(e,t)}catch(k){console.log(R(`Could not list workspaces: ${k.message}`));return}let{workspaces:o,projectId:r,profile:s,current:l}=n;if(o.length===0){console.log(f("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let k of o)console.log(` ${k.id===l?O("\u25CF"):" "} ${na(k)} ${f(k.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let p=await Xd({message:"Select the Document360 workspace for this repo:",choices:o.map(k=>({name:`${na(k)}${k.id===l?" (current)":""}`,value:k.id}))}),m=o.find(k=>k.id===p);lo(e,s,r,p,m?.name),console.log(D(`\u2713 Workspace set to "${m?.name??p}" for profile "${s}".`))}W();import{select as tu}from"@inquirer/prompts";import{resolveActiveProfile as nu,setProfileProject as ou,listProjects as ru}from"document360-engine";async function tt(e,t){let n=nu(e,t),o={profile:n.name,connection:n.connection};return{projects:await ru(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var ra=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Ir(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 co(e,t,n,o){ou(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function sa(e,t,n){let o;try{o=await tt(e,n)}catch(s){return console.log(R(`Could not list projects: ${s.message}`)),1}let r=Ir(o.projects,t);return r?(co(e,o.profile,r.id,r.name),console.log(D(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log(R(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function uo(e,t){let n;try{n=await tt(e,t)}catch(m){console.log(R(`Could not list projects: ${m.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 m of o)console.log(` ${m.id===s?O("\u25CF"):" "} ${ra(m)} ${f(m.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let l=await tu({message:"Select the Document360 project for this repo:",choices:o.map(m=>({name:`${ra(m)}${m.id===s?" (current)":""}`,value:m.id}))}),p=o.find(m=>m.id===l);co(e,r,l,p?.name),console.log(D(`\u2713 Project set to "${p?.name??l}" for profile "${r}". Next: pick a workspace.`))}W();import su from"picocolors";function iu(e=process.env){return e.FORCE_HYPERLINK==="0"||!su.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 au(e,t=e,n){return iu(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var lu=/https?:\/\/[^\s\x1b]+/g;function kn(e,t){return e.replace(lu,n=>au(n,n,t))}function ca(e){return{...ia(e.idToken)??{},...ia(e.accessToken)??{}}}function fo(e){let t=ca(e),n=t.email??t.preferred_username??t.sub??"unknown",o=t.doc360_project_id?` \xB7 project ${t.doc360_project_id}`:"";return`${n}${o}`}async function ho(e){let t=po(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 du(n,{manual:e.manual,promptForRedirect:s=>cu({message:s})},s=>console.log(kn(s))),r=aa(t.name,o);if(la(r),await _r(r,t.name,s=>console.log(f(s))),console.log(""),console.log(D(`\u2713 Logged in to "${t.name}" as ${fo(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{gu(process.cwd())?.profiles?.[t.name]&&(console.log(""),await Vt(process.cwd(),t.name))}catch{}}async function _r(e,t,n){let r=ca(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(po(process.cwd(),t).project.projectId)return;let l;try{let{projects:p}=await tt(process.cwd(),t);l=p.find(m=>m.id===r)?.name}catch{}mu(process.cwd(),t,{projectId:r,projectName:l}),n(` Project "${l??r}" written to profile "${t}".`)}catch{}}async function da(e){let t=po(process.cwd(),e.profile),n=t.connection,o=hu(t.name);if(!o){console.log(R(`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 ${O(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${fo(o)}`),fu(o))if(o.refreshToken)try{let r=aa(t.name,await uu(n,o.refreshToken));la(r),console.log(D(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(L(`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(L("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 ua(e){let t=po(process.cwd(),e.profile);pu(t.name)?console.log(D(`\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 pa,writeProjectConfig as wu,resolveActiveProfile as yu,loadTokens as ku,isExpired as bu}from"document360-engine";function mo(e){let t=pa(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(R("No profiles in .d360-writer/config.json. Run: d360-writer init")),process.exitCode=1;return}console.log("");for(let[n,o]of Object.entries(t.profiles)){let r=n===t.defaultProfile?O("\u25CF "):" ",s=o.production?L(" \u26A0 PRODUCTION"):"",l=o.connection.environment??"(inline)",p=ku(n),m=p?bu(p)&&!p.refreshToken?L("expired"):f("logged in"):f("not logged in");console.log(`${r}${O(n)} \u2192 ${l}${s} [${m}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function go(e,t){let n=pa(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(R(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,wu(n,e);let o=n.profiles[t].production?L(" \u26A0 PRODUCTION"):"";console.log(D(`\u2713 Default profile is now "${t}"${o}`))}function wo(e,t){try{let n=yu(e,t);console.log(""),console.log(`Profile ${O(n.name)}${n.production?L(" \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(R(n.message)),process.exitCode=1}}W();import{existsSync as vu,readdirSync as $u,statSync as fa}from"node:fs";import{join as ha}from"node:path";import{apiLogDir as xu}from"document360-engine";function ma(){let e=xu();if(console.log(""),console.log(`Document360 API logs: ${O(e)}`),!vu(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=$u(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=(fa(ha(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=(fa(ha(e,r)).size/1024).toFixed(1);console.log(` ${R(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 Cu,resolveAuth as Ru,findByName as Pu,slugify as Tu,touchSession as Su,upsertSession as Du,resolveActiveProfile as ju}from"document360-engine";async function ga(e,t,n,o,r,s){let l=Ru(n);l.kind==="none"&&(console.error(""),console.error(R("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${O("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${O("d360-writer --auth subscription")}`),process.exit(2)),l.kind==="subscription"&&console.error(f("Using your Claude subscription (no API key set)."));let p=null;try{p=ju(e,r)}catch(v){console.error(R(`Document360 profile error: ${v.message}`)),process.exit(2)}p.production&&(console.error(L(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),s||(console.error(R("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(f(" --yes given \u2014 proceeding against production.")));let m;if(o){let v=Pu(e,o);v||(console.error(R(`No saved session matches "${o}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),m=v.uuid,console.error(f(`Resuming "${v.name}"`))}let k=Cu({cwd:e,resume:m,profileName:r,allowProdWrites:s===!0}),g=m??null,T=1;for await(let v of k.send(t))switch(v.type){case"session":if(!g){g=v.sessionId;let _=new Date().toISOString();Du({uuid:g,name:Tu(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:_,updatedAt:_})}break;case"text":process.stdout.write(v.delta);break;case"tool":console.error(ae(` \u2699 ${v.name}`));break;case"result":T=v.ok?0:1,console.error(f(`(${v.inputTokens}\u2192${v.outputTokens} tokens`+(v.costUsd>0?`, $${v.costUsd<.01?v.costUsd.toFixed(4):v.costUsd.toFixed(2)}`:"")+")")),v.ok||console.error(R("agent finished with an error result"));break;case"error":console.error(""),console.error(R(`agent error: ${v.message}`)),process.exit(1)}g&&Su(g),process.stdout.write(`
|
|
280
|
-
`),process.exit(T)}import{createInterface as
|
|
278
|
+
`;Ta="Re-run dev\u2194docs onboarding (protocol v"});var Ha={};na(Ha,{initCommand:()=>Br,scaffoldInit:()=>qr});import{input as $n,confirm as Bu}from"@inquirer/prompts";import{basename as Na,join as Co}from"node:path";import{existsSync as Qt,readFileSync as Vu,readdirSync as Gu,writeFileSync as Yu}from"node:fs";import{writeProjectConfig as Ia,readProjectConfig as zu,projectConfigPath as _a,writerDir as Ku,DEFAULT_DOCS_DIR as Oa,DEFAULT_CAPTURE_DIR as La,DEFAULT_OUTPUT_DIR as Ma}from"document360-engine";function qr(e,t="berlin"){let n=_a(e);if(Qt(n))return{created:!1,path:n,profileName:""};let o={projectId:Wa(e)??Na(e),docsDir:Oa,captureDir:La,outputDir:Ma,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:Fa(e)};return Ia(o,e),Ua(e),{created:!0,path:n,profileName:t}}function Ua(e){let t=Co(Ku(e),".gitignore");Qt(t)||Yu(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
|
|
279
|
+
`),"utf8")}async function Br(){let e=process.cwd(),t=_a(e);if(Qt(t)&&!await Bu({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let n=Wa(e)??Na(e),o=await $n({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await $n({message:"Capture directory (where document360-capture .spec.ts files live):",default:La}),s=await $n({message:"Screenshot output directory:",default:Ma}),l=await $n({message:"Default connection profile name:",default:"berlin"}),p=await $n({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),m={projectId:o,docsDir:Oa,captureDir:r,outputDir:s,profiles:{[l]:{connection:{environment:p},production:!1}},defaultProfile:l,authoritativeSourceFiles:Fa(e)},k=zu(e);k?.terminologyGlossary&&(m.terminologyGlossary=k.terminologyGlossary),Ia(m,e),Ua(e);let g=Kt(e);console.log(""),console.log(D(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${O(`d360-writer login --profile ${l}`)} ${f("(sign in; project & workspace auto-selected)")}`),console.log("");for(let T of Xt(g))console.log(T);return console.log(""),console.log(`${f("Then ask:")} ${O('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function Wa(e){let t=Co(e,"package.json");if(!Qt(t))return null;try{return JSON.parse(Vu(t,"utf8")).name??null}catch{return null}}function Fa(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Qt(Co(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Co(e,n);Qt(o)&&!Xu(o)&&t.push(n)}return t}function Xu(e){try{return Gu(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var Ro=co(()=>{"use strict";W();nt()});var Vl={};na(Vl,{doctorCommand:()=>jn,renderDoctorChecks:()=>Bl,runDoctorChecks:()=>ql});import{existsSync as Hf}from"node:fs";import{d360GetAll as qf,getAccessToken as Bf,isExpired as Ms,loadProfileMap as Vf,loadTokens as Gf,packageSkillsDir as Fl,ENGINE_VERSION as Yf,projectConfigPath as zf,readProjectConfig as Kf,DEFAULT_DOCS_DIR as Xf,fetchManifestSummary as Qf,resolveActiveProfile as Jf,classifyClaudeAuth as Zf,CLAUDE_CODE_SETUP_HINT as Hl,resolveModelSetting as eh,probeModel as th,detectAppType as nh,playbookSkillName as oh,D360AuthError as rh}from"document360-engine";async function ql(e,t){let n=[];n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${Yf}`});let o=Number(process.versions.node.split(".")[0]);n.push(o>=20?{level:"ok",label:`Node ${process.versions.node}`}:{level:"fail",label:`Node ${process.versions.node} \u2014 20+ required`,fix:"Install Node 20 or later (nodejs.org)"});let r=Zf();r.state==="ready"?n.push({level:"ok",label:`Claude auth: ${r.kind==="api"?"API key":"subscription (Claude Code login found)"}`}):r.state==="maybe"?n.push({level:"warn",label:"Claude: no Claude Code login found (may be in the macOS Keychain)",fix:`If a docs turn ends with no output, sign in to Claude Code. ${Hl}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:Hl});let s=eh(e);if(n.push({level:"ok",label:`Model: ${s.model} (${s.source==="auto"?"auto \u2014 right-sized for docs; /model to change":s.source})`}),r.state==="ready"){let P=await th(e,s.model??void 0);P.ok?n.push({level:"ok",label:`Model reachable \u2014 replied in ${(P.latencyMs/1e3).toFixed(1)}s`}):P.timedOut?n.push({level:"fail",label:"Model unreachable \u2014 no response in 30s (a docs turn will hang, then end with 0 tokens / no output)",fix:`Usually a corporate proxy/firewall or org policy blocking the Claude model API. Check this machine's network access to the Claude endpoint; confirm with: claude -p "say hi"`}):n.push({level:"fail",label:`Model call failed \u2014 ${P.error??"no output"} (a docs turn will end with 0 tokens / no output)`,fix:'Check sign-in, the selected model (/model), and network access to the Claude endpoint; confirm with: claude -p "say hi"'})}let l=Kf(e);if(!l)return n.push({level:"fail",label:`No ${zf(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${l.projectId}`});let p=(l.docsDir??Xf).replace(/\/+$/,"");n.push(l.mode==="engineer"?{level:"warn",label:"Mode: engineer \u2014 agent may modify any source file (dogfooding)",fix:'Remove "mode" from .d360-writer/config.json for the writer-mode boundary'}:{level:"ok",label:`Mode: writer \u2014 edits limited to ${p}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let m=l.authoritativeSourceFiles??[];n.push(m.length>0?{level:"ok",label:`Sources: docs grounded in ${m.length} path(s) (${m.slice(0,3).join(", ")}${m.length>3?", \u2026":""})`}:{level:"warn",label:"Sources: not set \u2014 docs are grounded in the whole repo",fix:"Run: /scope to choose which files/folders the docs are written from"});let k=l.appType??nh(e);if(k){let P=l.appType?"from config":"auto-detected",N=k==="web"||k==="cli";n.push({level:"ok",label:`Genre: ${k} (${P})${N?` \u2192 ${oh(k)} loaded`:" \u2014 no doc-type playbook for this genre yet (generic skills)"}`})}else n.push({level:"warn",label:"Genre: unclassified \u2014 no doc-type playbook is loading (generic output)",fix:"Run /genre <web|cli|service|library> to pick \u2014 raises docs to that genre's craft bar"});let g;try{g=Jf(e),n.push({level:"ok",label:`Profile: ${g.name} (${g.connection.name})${g.production?" \u26A0 PRODUCTION":""}`})}catch(P){return n.push({level:"fail",label:`Profile config: ${P.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let T=Gf(g.name);T?Ms(T)&&!T.refreshToken?n.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):Ms(T)?n.push({level:"warn",label:"Document360: token expired \u2014 will auto-refresh on next call"}):n.push({level:"ok",label:`Document360: logged in (until ${new Date(T.expiresAt).toLocaleString()})`}):n.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${g.name})`}),n.push(g.project.workspaceId?{level:"ok",label:`Workspace: ${g.project.workspaceName??g.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let v=Vf(e,g.name);v?v.projectId&&g.project.projectId&&v.projectId!==g.project.projectId?n.push({level:"fail",label:`Category map projectId (${v.projectId}) \u2260 profile projectId (${g.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):n.push({level:"ok",label:`Category map: ${Object.keys(v.articles).length} articles, ${Object.keys(v.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${g.name}" (created on first /publish)`}),n.push(Hf(Fl())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${Fl()}`,fix:"Reinstall document360-writer (broken install)"});let _=Ee(e);if(_.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${ae})`}):_.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${_.completedVersion}, current is v${ae}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),T&&(!Ms(T)||T.refreshToken)){let P={profile:g.name,connection:g.connection};try{await Bf(P);let S=await qf(P,"/v3/projects");n.push({level:"ok",label:`API reachable (${g.connection.apiUrl}) \u2014 ${S.length} project(s) visible`})}catch(S){n.push({level:"fail",label:`API call failed: ${S.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let N=v?.projectId??g.project.projectId;if(N&&g.project.workspaceId)try{let S=await Qf(P,N,g.project.workspaceId);if(S){let M=(S.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Workspace sync manifest: available on ${g.connection.name} (${S.languages?.length??0} language${(S.languages?.length??0)===1?"":"s"}) \xB7 hash ${M||"(none)"}`})}else n.push({level:"warn",label:`Workspace sync manifest: not live on ${g.connection.name} yet`,fix:"No action needed \u2014 sync uses the per-article path until the manifest ships on this environment"})}catch(S){S instanceof rh||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(S.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${g.project.projectName??N})`,fix:"Run /login and pick this repo's project \u2014 your token is scoped to another project"}):n.push({level:"warn",label:`Workspace sync manifest: probe failed (${S.message.slice(0,80)})`})}}return n}function Bl(e){let t=[""];for(let r of e){let s=r.level==="ok"?D("\u2713"):r.level==="warn"?L("\u26A0"):R("\u2717");t.push(` ${s} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("fix:")} ${O(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?D(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):R(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function jn(e,t){console.log(f("Running checks\u2026"));for(let n of Bl(await ql(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var Uo=co(()=>{"use strict";nt();W()});import{Command as xw}from"commander";import{createRequire as Cw}from"node:module";import{AUTH_MODES as Rw}from"document360-engine";import{input as uu}from"@inquirer/prompts";import{loginPkce as pu,refreshTokens as fu,toStoredTokens as ca,clearTokens as hu,decodeJwtClaims as la,isExpired as mu,loadTokens as gu,saveTokens as da,resolveActiveProfile as ho,setProfileProject as wu,readProjectConfig as yu}from"document360-engine";W();import{select as Jd}from"@inquirer/prompts";import{resolveActiveProfile as Zd,setProfileProject as eu,resolveProjectId as tu,listWorkspaces as nu}from"document360-engine";async function kn(e,t){let n=Zd(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??tu(o);return{workspaces:await nu(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var ra=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function _r(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 uo(e,t,n,o,r){eu(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function sa(e,t,n){let o;try{o=await kn(e,n)}catch(s){return console.log(R(`Could not list workspaces: ${s.message}`)),1}let r=_r(o.workspaces,t);return r?(uo(e,o.profile,o.projectId,r.id,r.name),console.log(D(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(R(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function Gt(e,t){let n;try{n=await kn(e,t)}catch(k){console.log(R(`Could not list workspaces: ${k.message}`));return}let{workspaces:o,projectId:r,profile:s,current:l}=n;if(o.length===0){console.log(f("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let k of o)console.log(` ${k.id===l?O("\u25CF"):" "} ${ra(k)} ${f(k.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let p=await Jd({message:"Select the Document360 workspace for this repo:",choices:o.map(k=>({name:`${ra(k)}${k.id===l?" (current)":""}`,value:k.id}))}),m=o.find(k=>k.id===p);uo(e,s,r,p,m?.name),console.log(D(`\u2713 Workspace set to "${m?.name??p}" for profile "${s}".`))}W();import{select as ou}from"@inquirer/prompts";import{resolveActiveProfile as ru,setProfileProject as su,listProjects as iu}from"document360-engine";async function et(e,t){let n=ru(e,t),o={profile:n.name,connection:n.connection};return{projects:await iu(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var ia=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Or(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 po(e,t,n,o){su(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function aa(e,t,n){let o;try{o=await et(e,n)}catch(s){return console.log(R(`Could not list projects: ${s.message}`)),1}let r=Or(o.projects,t);return r?(po(e,o.profile,r.id,r.name),console.log(D(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log(R(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function fo(e,t){let n;try{n=await et(e,t)}catch(m){console.log(R(`Could not list projects: ${m.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 m of o)console.log(` ${m.id===s?O("\u25CF"):" "} ${ia(m)} ${f(m.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let l=await ou({message:"Select the Document360 project for this repo:",choices:o.map(m=>({name:`${ia(m)}${m.id===s?" (current)":""}`,value:m.id}))}),p=o.find(m=>m.id===l);po(e,r,l,p?.name),console.log(D(`\u2713 Project set to "${p?.name??l}" for profile "${r}". Next: pick a workspace.`))}W();import au from"picocolors";function lu(e=process.env){return e.FORCE_HYPERLINK==="0"||!au.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 cu(e,t=e,n){return lu(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var du=/https?:\/\/[^\s\x1b]+/g;function bn(e,t){return e.replace(du,n=>cu(n,n,t))}function ua(e){return{...la(e.idToken)??{},...la(e.accessToken)??{}}}function mo(e){let t=ua(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 go(e){let t=ho(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 pu(n,{manual:e.manual,promptForRedirect:s=>uu({message:s})},s=>console.log(bn(s))),r=ca(t.name,o);if(da(r),await Lr(r,t.name,s=>console.log(f(s))),console.log(""),console.log(D(`\u2713 Logged in to "${t.name}" as ${mo(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{yu(process.cwd())?.profiles?.[t.name]&&(console.log(""),await Gt(process.cwd(),t.name))}catch{}}async function Lr(e,t,n){let r=ua(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(ho(process.cwd(),t).project.projectId)return;let l;try{let{projects:p}=await et(process.cwd(),t);l=p.find(m=>m.id===r)?.name}catch{}wu(process.cwd(),t,{projectId:r,projectName:l}),n(` Project "${l??r}" written to profile "${t}".`)}catch{}}async function pa(e){let t=ho(process.cwd(),e.profile),n=t.connection,o=gu(t.name);if(!o){console.log(R(`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 ${O(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${mo(o)}`),mu(o))if(o.refreshToken)try{let r=ca(t.name,await fu(n,o.refreshToken));da(r),console.log(D(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(L(`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(L("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 fa(e){let t=ho(process.cwd(),e.profile);hu(t.name)?console.log(D(`\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 ha,writeProjectConfig as ku,resolveActiveProfile as bu,loadTokens as vu,isExpired as $u}from"document360-engine";function wo(e){let t=ha(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(R("No profiles in .d360-writer/config.json. Run: d360-writer init")),process.exitCode=1;return}console.log("");for(let[n,o]of Object.entries(t.profiles)){let r=n===t.defaultProfile?O("\u25CF "):" ",s=o.production?L(" \u26A0 PRODUCTION"):"",l=o.connection.environment??"(inline)",p=vu(n),m=p?$u(p)&&!p.refreshToken?L("expired"):f("logged in"):f("not logged in");console.log(`${r}${O(n)} \u2192 ${l}${s} [${m}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function yo(e,t){let n=ha(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(R(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,ku(n,e);let o=n.profiles[t].production?L(" \u26A0 PRODUCTION"):"";console.log(D(`\u2713 Default profile is now "${t}"${o}`))}function ko(e,t){try{let n=bu(e,t);console.log(""),console.log(`Profile ${O(n.name)}${n.production?L(" \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(R(n.message)),process.exitCode=1}}W();import{existsSync as xu,readdirSync as Cu,statSync as ma}from"node:fs";import{join as ga}from"node:path";import{apiLogDir as Ru}from"document360-engine";function wa(){let e=Ru();if(console.log(""),console.log(`Document360 API logs: ${O(e)}`),!xu(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Cu(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=(ma(ga(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=(ma(ga(e,r)).size/1024).toFixed(1);console.log(` ${R(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 Pu,resolveAuth as Tu,findByName as Su,slugify as Du,touchSession as ju,upsertSession as Au,resolveActiveProfile as Eu}from"document360-engine";async function ya(e,t,n,o,r,s){let l=Tu(n);l.kind==="none"&&(console.error(""),console.error(R("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${O("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${O("d360-writer --auth subscription")}`),process.exit(2)),l.kind==="subscription"&&console.error(f("Using your Claude subscription (no API key set)."));let p=null;try{p=Eu(e,r)}catch(v){console.error(R(`Document360 profile error: ${v.message}`)),process.exit(2)}p.production&&(console.error(L(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),s||(console.error(R("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(f(" --yes given \u2014 proceeding against production.")));let m;if(o){let v=Su(e,o);v||(console.error(R(`No saved session matches "${o}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),m=v.uuid,console.error(f(`Resuming "${v.name}"`))}let k=Pu({cwd:e,resume:m,profileName:r,allowProdWrites:s===!0}),g=m??null,T=1;for await(let v of k.send(t))switch(v.type){case"session":if(!g){g=v.sessionId;let _=new Date().toISOString();Au({uuid:g,name:Du(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:_,updatedAt:_})}break;case"text":process.stdout.write(v.delta);break;case"tool":console.error(ie(` \u2699 ${v.name}`));break;case"result":T=v.ok?0:1,console.error(f(`(${v.inputTokens}\u2192${v.outputTokens} tokens`+(v.costUsd>0?`, $${v.costUsd<.01?v.costUsd.toFixed(4):v.costUsd.toFixed(2)}`:"")+")")),v.ok||console.error(R("agent finished with an error result"));break;case"error":console.error(""),console.error(R(`agent error: ${v.message}`)),process.exit(1)}g&&ju(g),process.stdout.write(`
|
|
280
|
+
`),process.exit(T)}import{createInterface as Am}from"node:readline/promises";import{createSession as mi,resolveAuth as Em,getSession as Nm,setTitle as Im,slugify as _m,touchSession as Ic,upsertSession as Om,generateTitle as Lm,resolveActiveProfile as _c,resolveModelSetting as Mm,readProjectConfig as Um,resolveAndPersistAppType as Wm,decodeJwtClaims as Nc,isExpired as Fm,loadTokens as Hm,isDirectiveMention as qm,stripDirectiveMention as Bm,appendDirective as Vm,reconcileUpgradeActions as Gm,stampArticles as Ym,listArticleFiles as zm,CONTENT_CAP_VERSION as Km}from"document360-engine";import{ENGINE_VERSION as Iu}from"document360-engine";var Ae=[{key:"start",label:"Getting Started",rows:[{t:"text",s:"D360-Writer reads your codebase, generates end-user documentation, and publishes it to Document360."},{t:"text",s:"It needs Claude access \u2014 a Claude subscription (default) or an ANTHROPIC_API_KEY."},{t:"gap"},{t:"sub",s:"Quick start"},{t:"step",n:1,s:"Run /init \u2014 pick your environment, sign in, choose your project & workspace. It ends by printing a one-paste hand-off prompt."},{t:"step",n:2,s:"Paste that prompt into your repo's coding agent (Claude Code / Codex / Cursor). Let it finish, then follow its closing line. (Re-show it: /devhints)"},{t:"step",n:3,s:"Run /doctor to confirm every check is green."},{t:"step",n:4,s:'Type "write the docs for this repository" and follow the prompts.'},{t:"gap"},{t:"dim",s:"That's it \u2014 D360-Writer drafts your docs without you writing a line."},{t:"gap"},{t:"sub",s:"Tips"},{t:"text",s:"Just talk to it \u2014 anything not starting with / goes to the agent."},{t:"dim",s:"/ browses commands \xB7 \u2191 recalls history \xB7 esc interrupts a run \xB7 ctrl+c exits"}]},{key:"agentic",label:"Agentic",rows:[{t:"text",s:"Agentic Mode is designed for applications built using AI coding agents. D360-Writer works alongside your coding agent to continuously create and maintain your user documentation. Think of it as hiring a Technical Writer dedicated to your project."},{t:"gap"},{t:"text",s:"As your coding agent ships new features, it leaves documentation notes for D360-Writer. All you need to do is run the documentation loop."},{t:"gap"},{t:"sub",s:"Every few days"},{t:"cmd",name:"/catch-up --publish",s:"Analyze the latest code changes, read the notes left by your coding agent, update the documentation, and publish the changes."},{t:"dim",s:" (or run /catch-up to review drafts first, then /publish when you're ready)"},{t:"gap"},{t:"sub",s:"Whenever you need"},{t:"cmd",name:"/discover",s:"Interview your coding agent to understand the product (what it is, who it's for, the core idea, common misconceptions) \u2014 pins a product brief that grounds every article. Runs before writing a repo's docs; loops until confident."},{t:"cmd",name:"/audit",s:"Preview what has changed and identify missing documentation, without writing or publishing anything."},{t:"cmd",name:"/pull",s:"Bring Document360 down \u2014 pull edits made in the portal and import any new portal articles."},{t:"cmd",name:"/resolve",s:"Resolve conflicts when an article was edited both here and in the portal \u2014 review the diff, then keep yours, take the portal's, or skip."},{t:"cmd",name:"/inbox",s:"Review and act on messages left by your coding agent."}]},{key:"assistant",label:"Assistant",rows:[{t:"text",s:"D360-Writer is your writing assistant \u2014 it does the writing, you decide what gets written and when."},{t:"text",s:"Best for large or complex monorepos: focus it on one feature, component, or set of source folders."},{t:"gap"},{t:"sub",s:"Just ask"},{t:"good",s:'"Write the documentation for the Multiple JWT feature we shipped in the latest release."'},{t:"gap"},{t:"sub",s:"Or use the pipeline"},{t:"cmd",name:"/scope",s:"Focus D360-Writer on specific source folders (monorepos)."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from its PRDs in .d360-writer/input/ + the code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview shows the plan + cost first)."},{t:"cmd",name:"/publish",s:"Publish the articles to Document360."}]},{key:"shots",label:"Screenshots",rows:[{t:"text",s:"Documenting a web app? D360-Writer marks where an image helps with a <!-- SCREENSHOT --> placeholder."},{t:"text",s:"The companion CLI d360-capture turns those into real, annotated screenshots by driving your app in a browser."},{t:"gap"},{t:"sub",s:"Flow"},{t:"step",n:1,s:"Write your docs as usual \u2014 placeholders are added where visuals help."},{t:"step",n:2,s:"Run /screenshot --all to author capture specs and refresh the capture checklist (data + test-ids the shots need)."},{t:"step",n:3,s:"Stage what the checklist asks for, then 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:"/roadmap",s:"The docs campaign: progress + the next step."},{t:"cmd",name:"/catch-up",s:"Do all pending work \u2192 drafts (--publish goes live)."},{t:"cmd",name:"/publish",s:"Publish to Document360 (--all or a path)."},{t:"cmd",name:"/audit",s:"Preview what changed / what's missing."},{t:"cmd",name:"/pull",s:"Pull portal edits + new articles (--status: report only)."},{t:"cmd",name:"/resolve",s:"Resolve local\u2194portal conflicts (diff \u2192 keep local / take portal / skip)."},{t:"cmd",name:"/inbox",s:"Act on your coding agent's messages."},{t:"gap"},{t:"sub",s:"Assistant \u2014 directed writing"},{t:"cmd",name:"/discover",s:"Interview your builder \u2192 product brief that grounds the docs."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from PRDs + code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview first)."},{t:"cmd",name:"/preview",s:"Render an article locally."},{t:"gap"},{t:"sub",s:"Screenshots"},{t:"cmd",name:"/screenshot",s:"Author 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:"/feedback",s:"Copy logged D360-Writer feedback to your clipboard (relay it to the team)."},{t:"cmd",name:"/reset",s:"Delete all D360-Writer files (confirms first)."},{t:"gap"},{t:"sub",s:"Session"},{t:"cmd",name:"/resume",s:"Resume a saved session."},{t:"cmd",name:"/rename",s:"Name the session."},{t:"cmd",name:"/clear",s:"Clear the screen and reset the conversation (resumable)."},{t:"cmd",name:"/help",s:"Show this help."},{t:"cmd",name:"/exit",s:"Quit."}]}];function Nu(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 ka(e){let n=[e?`document360-writer \u2014 help \xB7 v${e.version} \xB7 engine v${e.engineVersion}`:"document360-writer \u2014 help",""];for(let o of Ae){n.push(`\u2500\u2500 ${o.label} \u2500\u2500`,"");for(let r of o.rows)n.push(Nu(r));n.push("")}return n.push("Tip: anything not starting with / goes to the agent."),n}async function Mr(e=[],t){console.log("");let n=t?.version?{version:t.version,engineVersion:Iu}:void 0;for(let o of ka(n))console.log(o);return console.log(""),console.log("Reporting a problem? Run `d360-writer logs` for the API log files."),console.log(""),{kind:"continue"}}W();import{getSession as _u}from"document360-engine";async function ba(e,t){let n=t.currentUuid(),o=n?_u(n):void 0;return console.log(o?f(`
|
|
281
281
|
(conversation reset \u2014 "${o.name}" is still available via /resume)
|
|
282
282
|
`):f(`
|
|
283
283
|
(conversation reset \u2014 agent will start fresh on the next prompt)
|
|
284
|
-
`)),{kind:"clear"}}async function
|
|
284
|
+
`)),{kind:"clear"}}async function Ur(){return{kind:"exit"}}Ro();W();import{readMcpConfig as Vr,writeMcpConfig as qa}from"document360-engine";async function Po(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(Qu(),{kind:"continue"}):t==="add"?(Ju(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(Zu(e.slice(1)),{kind:"continue"}):(console.log(R(`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 Qu(){let e=Vr(),t=Object.keys(e.servers);if(t.length===0){console.log(f(`
|
|
285
285
|
No MCP servers registered. Add one with /mcp add <name> <type> <ref>
|
|
286
|
-
`));return}console.log(""),console.log("Registered MCP servers (~/.document360-writer/mcp.json):");for(let n of t){let o=e.servers[n];if(o.type==="stdio")console.log(` ${O(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(` ${O(n)} ${f(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function
|
|
287
|
-
`),n=[],o=0;for(;o<t.length;){let r=t[o];if(/^\s*```/.test(r)){let p=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)p.push(t[o++]);o++,n.push({kind:"code",lines:p});continue}if(
|
|
288
|
-
`)}),M=Math.max(...S.map(V=>V.length)),B=[];for(let V=0;V<M;V++)B.push(p.map((Y,
|
|
286
|
+
`));return}console.log(""),console.log("Registered MCP servers (~/.document360-writer/mcp.json):");for(let n of t){let o=e.servers[n];if(o.type==="stdio")console.log(` ${O(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(` ${O(n)} ${f(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function Ju(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(R("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(R(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=Vr(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let l={};for(let p=1;p<o.length;p++)if(o[p]==="-H"||o[p]==="--header"){let m=o[++p],k=m?.match(/^([^:=]+)[:=](.+)$/);if(!k){console.log(R(`-H expects key:value (no spaces). Got: ${m??"(nothing)"}`));return}l[k[1].trim()]=k[2].trim()}else{console.log(R(`Unexpected argument: ${o[p]}. After the URL, only -H key:value is allowed.`));return}s={type:n,url:o[0],headers:Object.keys(l).length>0?l:void 0}}r.servers[t]=s,qa(r),console.log(""),console.log(D(`\u2713 Registered "${t}" (${n})`)),console.log(L(" 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 Zu(e){let t=e[0];if(!t){console.log(R("Usage: /mcp remove <name>"));return}let n=Vr();if(!n.servers[t]){console.log(R(`No server named "${t}".`));return}delete n.servers[t],qa(n),console.log(D(`\u2713 Removed "${t}".`)),console.log(f(" Run /clear to drop it from the current session immediately."))}W();import{readFileSync as mp}from"node:fs";import{join as gp}from"node:path";import{select as wp}from"@inquirer/prompts";import{computeSyncStatus as To,planPartitions as yp,relatedArticlePaths as kp,resolveModelForOperation as bp,runPartitioned as vp,loadProfileMap as $p,resolveActiveProfile as xp,resolveCrossLinks as Cp,applyStructureOrder as Za,orderSyncLine as el,applyRelatedArticles as tl,relatedSyncLine as nl}from"document360-engine";import Z from"picocolors";import Ka from"wrap-ansi";import Qr from"string-width";W();import ot from"picocolors";import Gr from"wrap-ansi";import Yr from"string-width";var Ba=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Va=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),Ga=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function ep(e){let t=e.replace(/\r/g,"").split(`
|
|
287
|
+
`),n=[],o=0;for(;o<t.length;){let r=t[o];if(/^\s*```/.test(r)){let p=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)p.push(t[o++]);o++,n.push({kind:"code",lines:p});continue}if(Ba(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&Va(t[o+1])){let p=Ga(r);o+=2;let m=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)m.push(Ga(t[o++]));n.push({kind:"table",header:p,rows:m});continue}let s=r.match(/^(#{1,6})\s+(.*)$/);if(s){n.push({kind:"heading",level:s[1].length,text:s[2]}),o++;continue}if(/^\s*([-*]|\d+\.)\s+/.test(r)){let p=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);){let m=t[o++];p.push({ordered:/^\s*\d+\.\s+/.test(m),text:m.replace(/^\s*([-*]|\d+\.)\s+/,"")})}n.push({kind:"list",items:p});continue}if(r.trim()===""){o++;continue}let l=[];for(;o<t.length&&t[o].trim()!==""&&!/^\s*```/.test(t[o])&&!/^(#{1,6})\s/.test(t[o])&&!/^\s*([-*]|\d+\.)\s+/.test(t[o])&&!Ba(t[o])&&!(t[o].includes("|")&&o+1<t.length&&Va(t[o+1]));)l.push(t[o++]);n.push({kind:"para",text:l.join(" ")})}return n}function zr(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?ot.bold(t.slice(2,-2)):t.startsWith("`")?O(t.slice(1,-1)):ot.italic(t.slice(1,-1)))}var tp=(e,t)=>e+" ".repeat(Math.max(0,t-Yr(e)));function np(e,t,n){let o=e.length,r=e.map((P,N)=>Math.max(Yr(P),...t.map(S=>Yr(S[N]??"")))),s=Math.max(24,n),l=3*o+1,p=[...r],m=()=>p.reduce((P,N)=>P+N,0)+l,k=0;for(;m()>s&&k++<1e4;){let P=-1,N=6;for(let S=0;S<o;S++)p[S]>N&&(N=p[S],P=S);if(P===-1)break;p[P]-=1}let g=(P,N,S)=>ot.gray(P+p.map(M=>"\u2500".repeat(M+2)).join(N)+S),T=ot.gray("\u2502"),v=(P,N)=>{let S=p.map((V,Y)=>{let ue=P[Y]??"",_e=N?ot.bold(ue):zr(ue);return Gr(_e,V,{hard:!0}).split(`
|
|
288
|
+
`)}),M=Math.max(...S.map(V=>V.length)),B=[];for(let V=0;V<M;V++)B.push(p.map((Y,ue)=>`${T} ${tp(S[ue][V]??"",Y)} `).join("")+T);return B.join(`
|
|
289
289
|
`)},_=[g("\u250C","\u252C","\u2510"),v(e,!0)];return _.push(t.length===0?g("\u2514","\u2534","\u2518"):g("\u251C","\u253C","\u2524")),t.forEach((P,N)=>{_.push(v(P,!1)),_.push(N===t.length-1?g("\u2514","\u2534","\u2518"):g("\u251C","\u253C","\u2524"))}),_.join(`
|
|
290
|
-
`)}function
|
|
290
|
+
`)}function op(e,t){switch(e.kind){case"heading":return ot.bold(e.text);case"hr":return ot.gray("\u2500".repeat(t));case"para":return Gr(zr(e.text),t);case"list":{let n=0;return e.items.map(o=>{let r=o.ordered?`${++n}.`:"\u2022",s=" ".repeat(2+r.length+1),[l="",...p]=Gr(zr(o.text),Math.max(10,t-s.length)).split(`
|
|
291
291
|
`);return` ${r} ${l}`+p.map(m=>`
|
|
292
292
|
${s}${m}`).join("")}).join(`
|
|
293
|
-
`)}case"code":return e.lines.map(n=>
|
|
294
|
-
`);case"table":return
|
|
293
|
+
`)}case"code":return e.lines.map(n=>ot.gray(" "+n)).join(`
|
|
294
|
+
`);case"table":return np(e.header,e.rows,t)}}function Kr(e,t){let n=Math.max(20,t);return ep(e).map(o=>op(o,n)).join(`
|
|
295
295
|
|
|
296
|
-
`)}W();import
|
|
297
|
-
`);let r=2,s=3,l=
|
|
296
|
+
`)}W();import rp from"picocolors";var sp=[127,86,217],ip=[22,38,43],Ya={T:sp,E:ip},xn=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],Xr=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,ap=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function za(){if(!rp.isColorSupported)return[];let e=xn[0].length,t=[];for(let n=0;n<xn.length;n+=2){let o="";for(let r=0;r<e;r++){let s=Ya[xn[n][r]],l=n+1<xn.length?Ya[xn[n+1][r]]:void 0;s&&l?o+=`${Xr(s)}${ap(l)}\u2580\x1B[49m\x1B[39m`:s?o+=`${Xr(s)}\u2580\x1B[39m`:l?o+=`${Xr(l)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function Cn(e){let t=n=>n.toFixed(1).endsWith(".0")?n.toFixed(0):n.toFixed(1);return e<1e3?String(e):e<1e6?`${t(e/1e3)}k`:`${t(e/1e6)}M`}function Rn(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function be(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function rt(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var Jt=(e,t)=>` ${e.padEnd(13)}${t}`;function lp(e,t){let n=[yn("\u270E document360-writer")+Z.gray(` v${e.version} \xB7 engine v${e.engineVersion}`),Z.gray(" Reads your code, writes your docs."),"",Jt("Claude:",`${e.claude}${Z.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),Jt("Document360:",e.configured?e.loggedOut?Z.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?Z.gray(` (${e.sessionHint})`):""}`:Z.yellow("not set up \u2014 run /init")),Jt("Profile:",e.configured?`${e.profile}${Z.gray(` (${e.apiUrl})`)}${e.prod?Z.bold(Z.yellow(" \u26A0 PRODUCTION")):""}`:Z.gray("\u2014 (run /init)")),Jt("Project:",e.project),Jt("Mode:",Z.gray(e.mode)),Jt("cwd:",Z.gray(e.cwd))],o=za();if(o.length===0)return n.join(`
|
|
297
|
+
`);let r=2,s=3,l=Qr(o[0]);if(!(t>=r+l+s+Math.max(...n.map(g=>Qr(g)))))return[...o.map(g=>" "+g),...n].join(`
|
|
298
298
|
`);let m=Math.max(0,Math.floor((n.length-o.length)/2)),k=[];for(let g=0;g<Math.max(o.length+m,n.length);g++){let T=o[g-m]??" ".repeat(l);k.push((" ".repeat(r)+T+" ".repeat(s)+(n[g]??"")).trimEnd())}return k.join(`
|
|
299
|
-
`)}var
|
|
300
|
-
`).flatMap(k=>
|
|
299
|
+
`)}var cp={error:Z.red,warn:Z.yellow,ok:Z.green,info:Z.gray};function dp(e){return e.replace(/^([^\x00-\x7F][\u{1F000}-\u{1FAFF}️]*) (?=\S)/gmu,"$1 ")}function Jr(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return lp(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",s=Math.max(10,n-4),l=50,p=e.text.split(`
|
|
300
|
+
`).flatMap(k=>Ka(k,s,{hard:!0}).split(`
|
|
301
301
|
`)),m=Math.max(0,p.length-l);return m>0&&(p=[...p.slice(0,l),Z.dim(`\u2026 +${m} more lines`)]),`
|
|
302
|
-
`+p.map((k,g)=>o+(g===0?O(" \u276F "):" ")+k+" ".repeat(Math.max(0,s-
|
|
302
|
+
`+p.map((k,g)=>o+(g===0?O(" \u276F "):" ")+k+" ".repeat(Math.max(0,s-Qr(k))+1)+r).join(`
|
|
303
303
|
`)}case"assistant":return`
|
|
304
|
-
`+
|
|
305
|
-
`+
|
|
304
|
+
`+Kr(e.text,n);case"tool":{let o=e.arg!==null?Z.gray(`${e.sep}(${e.arg})`):"";return`
|
|
305
|
+
`+Ka(Z.green("\u25CF ")+Z.bold(e.title)+o,n)}case"tool-result":{let o=e.isError?Z.red:Z.gray,r=e.lines.map((s,l)=>o((l===0?" \u23BF ":" ")+s));return e.hidden>0&&r.push(Z.dim(` \u2026 +${e.hidden} lines`)),r.join(`
|
|
306
306
|
`)}case"diff":{let o=l=>l===1?"":"s",s=[Z.gray(` \u23BF Added ${e.added} line${o(e.added)}, removed ${e.removed} line${o(e.removed)}`),...e.lines];return e.hidden>0&&s.push(Z.dim(` \u2026 +${e.hidden} more diff lines`)),s.join(`
|
|
307
|
-
`)}case"link":return e.lines.map(o=>O(
|
|
307
|
+
`)}case"link":return e.lines.map(o=>O(bn(` \u2B95 ${o}`))).join(`
|
|
308
308
|
`);case"preview":return`
|
|
309
|
-
`+
|
|
310
|
-
|
|
311
|
-
`+
|
|
312
|
-
`+
|
|
313
|
-
`+(e.ok?Z.magenta("\u2736 "):Z.red("\u2736 "))+Z.gray(`Cooked for ${
|
|
314
|
-
`)}import{resolveActiveProfile as
|
|
315
|
-
`)}var
|
|
316
|
-
`)}function
|
|
317
|
-
`),display:"/audit"}}W();import{readProjectConfig as
|
|
318
|
-
`)}async function
|
|
309
|
+
`+yn(`\u25A3 Preview \u2014 ${e.name}`)+`
|
|
310
|
+
|
|
311
|
+
`+Kr(e.text,n);case"note":return`
|
|
312
|
+
`+cp[e.tone](bn(dp(e.text)));case"done":{let o=e.inTokens&&e.inTokens>0?` \xB7 ${Cn(e.inTokens)} in${e.cachedPct!=null?` (${e.cachedPct}% cached)`:""}`:"";return`
|
|
313
|
+
`+(e.ok?Z.magenta("\u2736 "):Z.red("\u2736 "))+Z.gray(`Cooked for ${Rn(e.seconds)} \xB7 ${Cn(e.tokens)} tokens out${o}`+(e.costUsd>0?` \xB7 ${be(e.costUsd)}`:""))}}}function Xa(e,t){return e.map(n=>Jr(n,t)).join(`
|
|
314
|
+
`)}import{resolveActiveProfile as up,loadTokens as pp,isExpired as fp,decodeJwtClaims as Qa}from"document360-engine";function hp(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function Ne(e,t){try{let n=up(e,t),o=pp(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(fp(o)&&!o.refreshToken)return{ok:!1,reason:`Your Document360 session expired (profile "${n.name}"). Run /login.`};let r=n.project.projectId;if(r){let l={...Qa(o.idToken)??{},...Qa(o.accessToken)??{}}.doc360_project_id;if(typeof l=="string"&&l&&l!==r)return{ok:!1,reason:`Your Document360 session is signed into a different project than profile "${n.name}" (this profile's project is ${hp(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}var Pn=3;function Zr(e){return[`Run the publish-to-d360 skill for the article at: ${e}`,"","Steps you must follow:","1. Read the article markdown \u2014 use the repo-relative path exactly as given above (it resolves against the working directory; do not reconstruct an absolute path).","2. Compute the D360 publish form (strip the YAML frontmatter and the H1 title, strip every <!-- SCREENSHOT ... --> block while keeping the visible [Screenshot: ...] line, normalize cross-article links).","3. Look up the article ID in <repo>/d360-category-map.json. If present, call the document360 MCP update-article tool. If absent, call create-article with local_path set to the repo-relative .md path (the tool records the new ID + sync base in the category map itself \u2014 do not edit the articles map by hand).","4. Report what changed and remind me to publish the draft manually in the Document360 portal."].join(`
|
|
315
|
+
`)}var Ja={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function es(e){return e.filter(t=>t.path!==null&&t.status in Ja&&!t.link).map(t=>({path:t.path,label:Ja[t.status]}))}function So(e){let t=es(e),n=new Set(e.filter(o=>o.status==="conflict"&&o.path).map(o=>o.path));return{clean:t.filter(o=>!n.has(o.path)),conflicts:t.filter(o=>n.has(o.path))}}function Do(e){let t=e!==1;return`\u26A0 ${e} conflict${t?"s":""} NOT published (portal edit${t?"s":""} kept safe) \u2014 ${t?"these were":"it was"} edited both here and on the portal, so ${t?"they are":"it is"} left untouched. Settle ${t?"them":"it"}: /resolve (or /publish <path> to keep yours, /pull <path> to take the portal's).`}function jo(e){return e.filter(t=>t.link).length}function ts(e,t){try{let n=$p(e,xp(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=Cp(mp(gp(e,r),"utf8"),r,n).unresolved}catch{}return o===0?null:`\u2139 ${o} cross-link${o===1?"":"s"} point to pages not published yet \u2014 they show as plain text for now and turn into live links once those pages are published.`}catch{return null}}function Rp(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 ol(e,t=[]){let n=[];e.length>1&&n.push({kind:"all",label:`Publish all ${e.length} articles`,paths:e.map(r=>r.path),indent:!1});let o=new Map;for(let r of e){let s=r.path.replace(/\\/g,"/").split("/").slice(0,-1).join("/"),l=o.get(s);l?l.push(r):o.set(s,[r])}for(let r of[...o.keys()].sort()){let s=o.get(r).sort((l,p)=>l.path.localeCompare(p.path));n.push({kind:"category",label:`${Rp(r)} (${s.length})`,paths:s.map(l=>l.path),indent:!1});for(let l of s){let p=l.path.replace(/\\/g,"/").split("/").pop()??l.path;n.push({kind:"article",label:p,paths:[l.path],indent:!0,note:l.label})}}for(let r of[...t].sort((s,l)=>s.path.localeCompare(l.path))){let s=r.path.replace(/\\/g,"/").split("/").pop()??r.path;n.push({kind:"article",label:s,paths:[r.path],indent:!1,note:r.label,conflict:!0})}return n}function Ao(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(`
|
|
316
|
+
`)}function ns(e,t,n){let o=v=>t[v.index]?.paths.length??0,r=e.filter(v=>v.ok),s=e.filter(v=>!v.ok),l=e.reduce((v,_)=>v+o(_),0),p=r.reduce((v,_)=>v+o(_),0),m=n==="api"?`${be(e.reduce((v,_)=>v+_.costUsd,0))} total`:rt(e.reduce((v,_)=>v+_.outputTokens,0)),k=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,g=v=>`${v} article${v===1?"":"s"}`,T=[];if(s.length===0)T.push(`Published ${g(l)} (${k}) successfully \xB7 ${m}.`),T.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{T.push(`Published ${p}/${g(l)} (${k}) \xB7 ${m}.`),T.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /publish --all to retry just the rest (published articles are skipped):`);for(let v of s)T.push(` \u2717 ${v.label}${v.error?` \u2014 ${v.error}`:""}`)}return T}async function vt(e,t){let{model:n}=bp(e.cwd,"standard"),o=async(r,s)=>{let l=yp(r);console.log(f(s?`Resolving cross-links in ${r.length} article${r.length===1?"":"s"} whose targets published this run (second pass)\u2026`:`Publishing ${r.length} article${r.length===1?"":"s"} across ${l.length} partition${l.length===1?"":"s"} (\u2264${Pn} agents at once) on ${n}\u2026`)),s||console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let p=!1;for await(let m of vp({cwd:e.cwd,partitions:l,promptFor:k=>Ao(k.paths),concurrency:Pn,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:n}))if(m.type==="partition_status")m.status==="running"?console.log(f(` \u25B8 ${m.label} \u2014 publishing\u2026`)):m.status==="done"?console.log(D(` \u2713 ${m.label}`)):console.log(R(` \u2717 ${m.label}`));else if(m.type==="run_done"){p=m.aborted,console.log("");let k=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let T of ns(m.results,l,k))console.log(m.ok?D(T):L(T));let g=ts(e.cwd,e.profileName);g&&console.log(f(g));try{let T=el(await Za({cwd:e.cwd,profileName:e.profileName}));T&&console.log(f(T))}catch{}try{let T=nl(await tl({cwd:e.cwd,profileName:e.profileName}));T&&console.log(f(T))}catch{}}return p};try{if(!await o(t,!1)){let s=await os(e.cwd,e.profileName,t);s.length>0&&await o(s,!0)}}catch(r){console.log(R(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function Eo(e,t,n){let o=kp(e,n);if(o.length===0)return[];let r=new Set(es((await To({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function os(e,t,n){try{let o=new Set(n),r=await To({cwd:e,profileName:t});return es(r.entries).map(s=>s.path).filter(s=>o.has(s))}catch{return[]}}async function rl(e,t){let n=Ne(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(R(n.reason)),{kind:"continue"};let o=e[0];if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await Eo(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return r.length===0?(console.log(D("\u2713 All related articles are already published.")),{kind:"continue"}):await vt(t,r)}if(o==="--all"){console.log(f("Checking what needs publishing\u2026"));try{let r=await To({cwd:t?.cwd??process.cwd()}),{clean:s,conflicts:l}=So(r.entries),p=jo(r.entries),m=e.includes("--force")&&l.length>0;p>0&&console.log(L(`\u26A0 ${p} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),l.length>0&&!m&&console.log(L(Do(l.length)));let k=m?[...s,...l]:s;if(k.length===0){if(l.length>0)return console.log(f("Resolve the conflicts: /resolve")),{kind:"continue"};if(console.log(D(p>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),t)try{let g=el(await Za({cwd:t.cwd,profileName:t.profileName}));g&&console.log(f(g));let T=nl(await tl({cwd:t.cwd,profileName:t.profileName}));T&&console.log(f(T))}catch{}return{kind:"continue"}}return t?await vt(t,k.map(g=>g.path)):{kind:"forward-to-agent",prompt:Ao(k.map(g=>g.path)),display:"/publish --all"}}catch(r){return console.log(R(`Could not compute sync status: ${r.message}`)),{kind:"continue"}}}if(o&&o.startsWith("--")&&(o=e.find(r=>!r.startsWith("--"))??""),!o){console.log(f("Checking what needs publishing\u2026"));let r;try{let s=await To({cwd:t?.cwd??process.cwd()}),{clean:l,conflicts:p}=So(s.entries);r=l;let m=jo(s.entries);if(m>0&&console.log(L(`\u26A0 ${m} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),p.length>0&&console.log(L(Do(p.length))),r.length===0&&p.length>0)return console.log(f("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(s){return console.log(R(`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(D("\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(()=>wp({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 vt(t,r.map(s=>s.path))}return{kind:"forward-to-agent",prompt:Zr(o),display:`/publish ${o}`}}async function Tn(){return{kind:"forward-to-agent",prompt:["Run the gap-analysis skill against this repo.","","Follow its stages in order:","1. d360_sync_status first \u2014 stop and report if any article is in conflict or remote-ahead (the local copy cannot be trusted until resolved).","2. git diff since the lastAnalyzedCommit marker in d360-category-map.json (or last 30 days if no marker), filtered to the authoritativeSourceFiles paths.","2.5. d360_pending_hints \u2014 the source agent's own notes on what it shipped. Verify each (sources exist, commit is an ancestor of HEAD, source shows the surface) before trusting; fold verified ones into the table, flag the rest.","3. Map changes (diff + hints) to articles via their `sources:` frontmatter; read only implicated articles and changed source files. If articles are missing `sources:`, this is the one-time bootstrap pass \u2014 backfill them.","4. Output the proposal table: | Article (path or proposed title) | Action (create | update | retire | link) | Reason | Evidence | Scope |, then advance lastAnalyzedCommit and stamp consumed hints.","","Do not start writing or updating any article yet \u2014 the proposal table is the deliverable."].join(`
|
|
317
|
+
`),display:"/audit"}}W();import{readProjectConfig as Pp}from"document360-engine";function rs(){return["Run the discover-product skill against this repo.","","Build (or continue refining) the product brief at `.d360-writer/product-brief.md` by interviewing the","source repo's coding agent (the builder):","1. Gather all grounding \u2014 the code surface (analyze-codebase pass), `.d360-writer/architecture/`"," (+ CREATOR-NOTES), any specs under `.d360-writer/input/`, existing docs, git log, and the current"," product brief if one exists.","2. Self-assess against the 8-point readiness rubric (identity, audience, core mental model,"," misconceptions, positioning, key concepts & terminology, critical journeys, boundaries/non-goals).","3. Write/update the brief \u2014 every claim cited to its grounding \u2014 and keep its frontmatter current"," (status, rounds, open_questions, last_updated).","4. For the dimensions you cannot yet ground confidently, ask the builder a focused batch (\u22646) of pointed",' questions via d360_ask_builder, with the subject prefixed "[discovery] ". Then END the turn \u2014 the'," builder answers async; /catch-up will ingest the answers and continue the loop.","","Set status: confident and hand off to propose-structure ONLY when every rubric dimension passes. If the","builder stays silent across a few rounds, degrade gracefully per the skill (best-effort brief, flagged","open questions) rather than blocking the docs. Do NOT write or publish any articles in this turn."].join(`
|
|
318
|
+
`)}async function sl(e,t){let n=t?.cwd??process.cwd();return Pp(n)?{kind:"forward-to-agent",prompt:rs(),display:"/discover"}:(console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{checkbox as Tp}from"@inquirer/prompts";import{inventoryRepo as Sp,readProjectConfig as il,writeProjectConfig as Dp}from"document360-engine";function ss(e,t){let n=il(e);n&&(n.authoritativeSourceFiles=t,Dp(n,e))}function No(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 al(e,t){let n=t?.cwd??process.cwd();if(!il(n))return console.log(R("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=Sp(n);if(o.length===0)return console.log(f('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(O("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${f(No(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>Tp({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${No(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"};ss(n,r),console.log(D(`\u2713 Scoped to ${r.length} folder(s) \u2014 written to .d360-writer/config.json`));for(let s of r)console.log(` ${s}`);return console.log(""),{kind:"continue"}}W();import{confirm as Up}from"@inquirer/prompts";import{applyPull as ls,computeSyncStatus as gl,compareRemoteSources as Wp,planPull as wl,planImport as Fp,applyImport as Hp,establishBaselines as qp,rebaselineServerMeta as Bp,D360AuthError as Vp}from"document360-engine";W();var ll=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /publish <path>):",paint:R,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /publish <path>:",paint:L,mark:"M"},{status:"remote-ahead",header:"Changed on Document360 \u2014 pull with /pull <path> (or just /pull):",paint:O,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:R,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:R,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint:ie,mark:"X"},{status:"untracked-local",header:"New here \u2014 not on Document360 yet (publish to add them):",paint: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:ie,mark:"\xB7"}];function jp(e){return e.path?e.path:`${e.title??"(untitled)"} ${ie(`[${e.articleId}]`)}`}function Ap(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 Io(e,t){let n=[],o=e.entries.filter(g=>g.link);if(o.length>0){n.push(""),n.push(ke("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let g of o)n.push(` ${L("~")} ${L(g.path??"")} ${ie(`\u2192 "${g.link.title}"`)}`)}for(let g of ll){let T=e.entries.filter(v=>v.status===g.status&&!(g.status==="untracked-local"&&v.link));if(T.length!==0){n.push(""),n.push(ke(g.header));for(let v of T)n.push(` ${g.paint(g.mark)} ${g.paint(jp(v))}${v.detail?ie(` (${v.detail})`):""}`)}}let r=e.counts["in-sync"]??0,s=e.entries.length;n.push("");let l={"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,m=s===r?D("\u2713 everything up to date"):[r>0?D(`\u2713 ${r} up to date`):null,p>0?`${p} to link`:null,...ll.map(g=>{let T=(e.counts[g.status]??0)-(g.status==="untracked-local"?p:0);return T>0?`${T} ${l[g.status]}`:null})].filter(Boolean).join(ie(" \xB7 ")),k=t!==void 0?` \xB7 synced in ${Ap(t)}`:"";return n.push(m+ie(` \xB7 ${s} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${k}`)),n}import{structuredPatch as Ep}from"diff";import cl from"picocolors";var dl=80,Np="\x1B[48;2;74;28;28m",Ip="\x1B[48;2;24;66;24m",ul="\x1B[49m",is=e=>String(e).padStart(5);function pl(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}function fl(e,t,n){if(n===void 0||n<t-4)return e.slice(0,t);let o=Math.max(0,n-12);return`\u2026${e.slice(o).slice(0,Math.max(8,t-1))}`}function Ye(e,t,n){let o=v=>{let _=v.replace(/\r\n/g,`
|
|
319
319
|
`);return _.endsWith(`
|
|
320
320
|
`)||_===""?_:_+`
|
|
321
|
-
`},r=o(e),s=o(t);if(r===s)return null;let l=Math.max(20,n-10),p=jp("a","b",r,s,"","",{context:3}),m=0,k=0,g=[];p.hunks.forEach((v,_)=>{_>0&&g.push(al.gray(" \u2026"));let P=v.oldStart,N=v.newStart,S=[],M=[],B=()=>{for(let V=0;V<S.length;V++){let Y=V<M.length?dl(S[V],M[V]):void 0;k++,g.push(`${Ap}${rs(P++)} - ${ul(S[V],l,Y)}${cl}`)}for(let V=0;V<M.length;V++){let Y=V<S.length?dl(S[V],M[V]):void 0;m++,g.push(`${Ep}${rs(N++)} + ${ul(M[V],l,Y)}${cl}`)}S=[],M=[]};for(let V of v.lines){let Y=V[0],ne=V.slice(1);Y==="-"?S.push(ne):Y==="+"?M.push(ne):(B(),g.push(al.gray(rs(N))+" "+ne.slice(0,l)),P++,N++)}B()});let T=g.slice(0,ll);return{added:m,removed:k,lines:T,hidden:Math.max(0,g.length-ll)}}W();import{select as Np}from"@inquirer/prompts";import{applyPull as Ip,computeSyncStatus as _p,planPull as Op}from"document360-engine";var pl=e=>e===1?"":"s";async function ss(e,t){console.log(""),console.log(`${O("\u25CF")} ${ye(t.title)} ${ae(`(${t.path})`)}`);for(let r of t.notes)console.log(L(` \u26A0 ${r}`));let n=Ke(t.oldContent,t.newContent,Math.max(40,(process.stdout.columns??80)-1));if(n){console.log(ae(` \u23BF local \u2192 portal: +${n.added} / -${n.removed} line${pl(n.added+n.removed)}`));for(let r of n.lines)console.log(r);n.hidden>0&&console.log(f(` \u2026 +${n.hidden} more diff lines`))}else console.log(f(" Local already matches the portal content \u2014 resolving just advances the sync base."));let o=await e.withPausedInput(()=>Np({message:`Conflict \u2014 ${t.path}`,choices:[{name:"Keep local (publish \u2014 overwrites the portal edit)",value:"local"},{name:"Take portal (overwrites your local edits)",value:"portal"},{name:"Skip (leave it a conflict)",value:"skip"}]})).catch(()=>"skip");return o==="portal"?(Ip({cwd:e.cwd,profileName:e.profileName},t),console.log(D(" \u2713 Took the portal copy (local overwritten, sync base advanced).")),"took-portal"):o==="local"?"keep-local":(console.log(f(" Skipped \u2014 still a conflict.")),"skipped")}async function fl(e,t){let n=Ne(t.cwd,t.profileName);if(!n.ok)return console.log(R(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let s=(await _p({cwd:t.cwd,profileName:t.profileName})).entries.filter(p=>p.status==="conflict"&&p.path).map(p=>p.path);if(o){if(!s.includes(o))return console.log(D(`${o} isn't in conflict \u2014 nothing to resolve.`)),{kind:"continue"};s=[o]}if(s.length===0)return console.log(D("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let l=[];for(let p of s){let m=await Op({cwd:t.cwd,profileName:t.profileName,relPath:p});await ss(t,m)==="keep-local"&&l.push(p)}if(l.length>0)return console.log(f(`Publishing ${l.length} kept-local article${pl(l.length)} over the portal\u2026`)),await bt(t,l)}catch(r){console.log(R(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function gl(e,t){let n=Ne(t.cwd,t.profileName);if(!n.ok)return console.log(R(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await Bp(t),{kind:"continue"};if(o==="--baseline")return await Vp(t,e.filter(l=>l!=="--baseline")),{kind:"continue"};if(o==="--compare")return await Gp(t),{kind:"continue"};if(o)return console.log(R(`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 Yp(t,r),{kind:"continue"};console.log(f("Pulling changes from Document360\u2026"));let s=await as({cwd:t.cwd,profileName:t.profileName});for(let l of ls(s))console.log(l.tone==="ok"?D(l.text):l.tone==="warn"?L(l.text):f(l.text));console.log("")}catch(r){r instanceof qp?console.log(R(r.message)):console.log(R(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function as(e){let t=await hl({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 ml({cwd:e.cwd,profileName:e.profileName,relPath:o.path});is({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 Up({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});Wp({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 No=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,vt=e=>e===1?"":"s";function ls(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${vt(e.pulled.length)} into local: ${No(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${vt(e.imported.length)}: ${No(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${vt(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${vt(e.conflicts.length)} changed both here and on Document360 \u2014 left untouched. Resolve them: /resolve (or /publish <path> to keep yours, /pull <path> to take the portal's). (${No(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${vt(e.failed.length)} failed: ${No(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 Bp(e){console.log(f("Checking Document360 for drift\u2026"));let t=Date.now(),n=await hl({cwd:e.cwd,profileName:e.profileName});for(let o of Eo(n,Date.now()-t))console.log(o);console.log("")}async function Vp(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 Fp({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await Hp({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(D("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(D(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(D(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(L(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(f(` - ${s.path} (${s.reason})`))}}async function Gp(e){console.log(f("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await Mp({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${ye(String(t.legacyCount))} \xB7 Manifest: ${ye(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(D("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(R(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(L(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(L(` ${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 Yp(e,t){let n=t.replace(/\\/g,"/"),o=await ml({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await ss(e,o)==="keep-local"&&(console.log(f(`Publishing ${o.path} over the portal\u2026`)),await bt(e,[o.path]));return}console.log(""),console.log(`${O("\u25CF")} ${ye(o.title)} ${ae(`(${o.path})`)}`);for(let l of o.notes)console.log(L(` \u26A0 ${l}`));let r=Ke(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.")),is({cwd:e.cwd,profileName:e.profileName},o);return}console.log(ae(` \u23BF Added ${r.added} line${vt(r.added)}, removed ${r.removed} line${vt(r.removed)}`));for(let l of r.lines)console.log(l);if(r.hidden>0&&console.log(f(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>Lp({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(f(" Skipped."));return}is({cwd:e.cwd,profileName:e.profileName},o),console.log(D(` \u2713 Pulled ${o.path} (sync base advanced).`))}W();import{statSync as zp}from"node:fs";import{resolve as Kp}from"node:path";import{estimateBulkCost as Xp,planPartitions as Qp,readProjectConfig as Jp,resolveModelForOperation as Zp,runPartitioned as ef,trackedArticlePaths as tf}from"document360-engine";var cs=3;function ds(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 us(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function ps(e,t){return t.map(n=>{let o=0;try{o=zp(Kp(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function fs(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:
|
|
321
|
+
`},r=o(e),s=o(t);if(r===s)return null;let l=Math.max(20,n-10),p=Ep("a","b",r,s,"","",{context:3}),m=0,k=0,g=[];p.hunks.forEach((v,_)=>{_>0&&g.push(cl.gray(" \u2026"));let P=v.oldStart,N=v.newStart,S=[],M=[],B=()=>{for(let V=0;V<S.length;V++){let Y=V<M.length?pl(S[V],M[V]):void 0;k++,g.push(`${Np}${is(P++)} - ${fl(S[V],l,Y)}${ul}`)}for(let V=0;V<M.length;V++){let Y=V<S.length?pl(S[V],M[V]):void 0;m++,g.push(`${Ip}${is(N++)} + ${fl(M[V],l,Y)}${ul}`)}S=[],M=[]};for(let V of v.lines){let Y=V[0],ue=V.slice(1);Y==="-"?S.push(ue):Y==="+"?M.push(ue):(B(),g.push(cl.gray(is(N))+" "+ue.slice(0,l)),P++,N++)}B()});let T=g.slice(0,dl);return{added:m,removed:k,lines:T,hidden:Math.max(0,g.length-dl)}}W();import{select as _p}from"@inquirer/prompts";import{applyPull as Op,computeSyncStatus as Lp,planPull as Mp}from"document360-engine";var hl=e=>e===1?"":"s";async function as(e,t){console.log(""),console.log(`${O("\u25CF")} ${ke(t.title)} ${ie(`(${t.path})`)}`);for(let r of t.notes)console.log(L(` \u26A0 ${r}`));let n=Ye(t.oldContent,t.newContent,Math.max(40,(process.stdout.columns??80)-1));if(n){console.log(ie(` \u23BF local \u2192 portal: +${n.added} / -${n.removed} line${hl(n.added+n.removed)}`));for(let r of n.lines)console.log(r);n.hidden>0&&console.log(f(` \u2026 +${n.hidden} more diff lines`))}else console.log(f(" Local already matches the portal content \u2014 resolving just advances the sync base."));let o=await e.withPausedInput(()=>_p({message:`Conflict \u2014 ${t.path}`,choices:[{name:"Keep local (publish \u2014 overwrites the portal edit)",value:"local"},{name:"Take portal (overwrites your local edits)",value:"portal"},{name:"Skip (leave it a conflict)",value:"skip"}]})).catch(()=>"skip");return o==="portal"?(Op({cwd:e.cwd,profileName:e.profileName},t),console.log(D(" \u2713 Took the portal copy (local overwritten, sync base advanced).")),"took-portal"):o==="local"?"keep-local":(console.log(f(" Skipped \u2014 still a conflict.")),"skipped")}async function ml(e,t){let n=Ne(t.cwd,t.profileName);if(!n.ok)return console.log(R(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let s=(await Lp({cwd:t.cwd,profileName:t.profileName})).entries.filter(p=>p.status==="conflict"&&p.path).map(p=>p.path);if(o){if(!s.includes(o))return console.log(D(`${o} isn't in conflict \u2014 nothing to resolve.`)),{kind:"continue"};s=[o]}if(s.length===0)return console.log(D("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let l=[];for(let p of s){let m=await Mp({cwd:t.cwd,profileName:t.profileName,relPath:p});await as(t,m)==="keep-local"&&l.push(p)}if(l.length>0)return console.log(f(`Publishing ${l.length} kept-local article${hl(l.length)} over the portal\u2026`)),await vt(t,l)}catch(r){console.log(R(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function yl(e,t){let n=Ne(t.cwd,t.profileName);if(!n.ok)return console.log(R(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await Gp(t),{kind:"continue"};if(o==="--baseline")return await Yp(t,e.filter(l=>l!=="--baseline")),{kind:"continue"};if(o==="--compare")return await zp(t),{kind:"continue"};if(o)return console.log(R(`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 Kp(t,r),{kind:"continue"};console.log(f("Pulling changes from Document360\u2026"));let s=await cs({cwd:t.cwd,profileName:t.profileName});for(let l of ds(s))console.log(l.tone==="ok"?D(l.text):l.tone==="warn"?L(l.text):f(l.text));console.log("")}catch(r){r instanceof Vp?console.log(R(r.message)):console.log(R(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function cs(e){let t=await gl({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 wl({cwd:e.cwd,profileName:e.profileName,relPath:o.path});ls({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 Fp({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});Hp({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 _o=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,$t=e=>e===1?"":"s";function ds(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${$t(e.pulled.length)} into local: ${_o(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${$t(e.imported.length)}: ${_o(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${$t(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${$t(e.conflicts.length)} changed both here and on Document360 \u2014 left untouched. Resolve them: /resolve (or /publish <path> to keep yours, /pull <path> to take the portal's). (${_o(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${$t(e.failed.length)} failed: ${_o(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 Gp(e){console.log(f("Checking Document360 for drift\u2026"));let t=Date.now(),n=await gl({cwd:e.cwd,profileName:e.profileName});for(let o of Io(n,Date.now()-t))console.log(o);console.log("")}async function Yp(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 qp({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await Bp({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(D("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(D(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(D(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(L(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(f(` - ${s.path} (${s.reason})`))}}async function zp(e){console.log(f("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await Wp({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${ke(String(t.legacyCount))} \xB7 Manifest: ${ke(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(D("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(R(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(L(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(L(` ${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 Kp(e,t){let n=t.replace(/\\/g,"/"),o=await wl({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await as(e,o)==="keep-local"&&(console.log(f(`Publishing ${o.path} over the portal\u2026`)),await vt(e,[o.path]));return}console.log(""),console.log(`${O("\u25CF")} ${ke(o.title)} ${ie(`(${o.path})`)}`);for(let l of o.notes)console.log(L(` \u26A0 ${l}`));let r=Ye(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.")),ls({cwd:e.cwd,profileName:e.profileName},o);return}console.log(ie(` \u23BF Added ${r.added} line${$t(r.added)}, removed ${r.removed} line${$t(r.removed)}`));for(let l of r.lines)console.log(l);if(r.hidden>0&&console.log(f(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>Up({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(f(" Skipped."));return}ls({cwd:e.cwd,profileName:e.profileName},o),console.log(D(` \u2713 Pulled ${o.path} (sync base advanced).`))}W();import{statSync as Xp}from"node:fs";import{resolve as Qp}from"node:path";import{estimateBulkCost as Jp,planPartitions as Zp,readProjectConfig as ef,resolveModelForOperation as tf,runPartitioned as nf,trackedArticlePaths as of}from"document360-engine";var us=3;function ps(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 fs(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function hs(e,t){return t.map(n=>{let o=0;try{o=Xp(Qp(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function ms(e){return`Convert each of these articles to canonical Document360 Flavored Markdown (DFM) and re-publish each as a DRAFT. This is a mechanical syntax conversion, not a rewrite \u2014 be efficient:
|
|
322
322
|
- Read ONLY the article files listed below. Do NOT read source code, other articles, or fetch the live portal \u2014 you already have everything you need.
|
|
323
323
|
- Convert in place: wrap callouts, FAQs, tabs, accordions, and media embeds per the d360-markdown skill. Preserve all wording, headings, and structure; change only GFM\u2192DFM syntax.
|
|
324
324
|
- Publish each as a draft with a single update call. Do NOT re-read, re-verify, or polish after converting, and skip articles already in DFM.
|
|
325
325
|
- Work only on these files:
|
|
326
326
|
`+e.paths.map(t=>`- ${t}`).join(`
|
|
327
|
-
`)}function
|
|
327
|
+
`)}function gs(e,t,n){let o=e.reduce((p,m)=>p+m.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: ${be(r)}\u2013${be(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function ws(e,t,n){let o=P=>t[P.index]?.paths.length??0,r=e.filter(P=>P.ok),s=e.filter(P=>!P.ok),l=e.reduce((P,N)=>P+o(N),0),p=r.reduce((P,N)=>P+o(N),0),m=e.reduce((P,N)=>P+N.costUsd,0),k=e.reduce((P,N)=>P+N.outputTokens,0),g=n==="api"?`${be(m)} total`:rt(k),T=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,v=P=>`${P} article${P===1?"":"s"}`,_=[];if(s.length===0)_.push(`Converted ${v(l)} (${T}) successfully \xB7 ${g}.`);else{_.push(`Converted ${p}/${v(l)} (${T}) \xB7 ${g}.`),_.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let P of s)_.push(` \u2717 ${P.label}${P.error?` \u2014 ${P.error}`:""}`)}return _}async function kl(e,t){if(!ef(t.cwd))return console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=ps(e),r=of(t.cwd,t.profileName);if(r.length===0)return console.log(R("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let s=fs(r,n);if(s.length===0)return console.log(R(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let l=Zp(s),p=`/convert${n?` --scope ${n}`:""} --run`,{model:m,forced:k}=tf(t.cwd,"light");if(!o){let g=Jp({files:hs(t.cwd,s),op:"convert",model:m});n&&console.log(f(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let T of gs(l,g,us))console.log(T);return console.log(f(`Model: ${m}${k?" (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 ${l.length} partitions (\u2264${us} agents at once) on ${m}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let g of nf({cwd:t.cwd,partitions:l,promptFor:ms,concurrency:us,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:m}))if(g.type==="partition_status")g.status==="running"?console.log(f(` \u25B8 ${g.label} \u2014 converting\u2026`)):g.status==="done"?console.log(D(` \u2713 ${g.label}`)):console.log(R(` \u2717 ${g.label}`));else if(g.type==="run_done"){console.log("");let T=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let v of ws(g.results,l,T))console.log(g.ok?D(v):L(v))}}catch(g){console.log(R(`Convert run failed: ${g.message}`))}return console.log(""),{kind:"continue"}}W();import{statSync as $l}from"node:fs";import{resolve as xl}from"node:path";import{estimateBulkCost as ff,lintDocs as hf,planPartitions as mf,readDocsPlan as gf,readProjectConfig as Cl,DEFAULT_DOCS_DIR as wf,resolveModelForOperation as yf,runPartitioned as kf,stampArticles as bf,CONTENT_CAP_VERSION as vf}from"document360-engine";import{readProjectConfig as rf,loadProfileMap as sf,resolveActiveProfile as af,desiredCategoryOrder as lf,desiredArticleOrder as cf,DEFAULT_DOCS_DIR as df}from"document360-engine";var ys=e=>e.replace(/\\/g,"/"),uf=e=>ys(e).split("/").pop()??e;function pf(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}function Sn(e,t){try{let n=rf(e);if(!n)return[];let o=af(e,t),r=sf(e,o.name);if(!r)return[];let s=ys(n.docsDir??df).replace(/\/+$/,""),l=new Map;for(let m of cf(r))l.set(m.categoryPath,(l.get(m.categoryPath)??0)+1);let p=[];for(let m of lf(r)){let k=ys(m.path),g=k.startsWith(`${s}/`)?k.slice(s.length+1):k===s?"":k;g&&p.push({token:g,label:pf(uf(k)),count:l.get(m.path)??0})}return p}catch{return[]}}function bl(e,t){let n=Sn(e,t);return n.length===0?["No categories yet \u2014 author some articles first, then scope to one."]:["Which category? Re-run with one of:",...n.map(o=>` --scope ${o.token} (${o.label} \xB7 ${o.count} article${o.count===1?"":"s"})`)]}function st(e,t){return t.includes("--all")||t.some(n=>!n.startsWith("--"))?!1:e==="review"||e==="reorder"||e==="write"&&t.includes("--rewrite")}function Zt(e,t,n,o){let r=Sn(e,o);if(r.length<=1)return[];let s=n.filter(k=>k.startsWith("--")).join(" "),l=s?` ${s}`:"",p=`/${t}${l} --all`.replace(/\s+/g," "),m=k=>t==="write"?`/write --scope ${k}${l}`:`/${t} ${k}${l}`;return[`Bare /${t} covers the WHOLE knowledge base (${r.reduce((k,g)=>k+g.count,0)} articles). Pick a target:`,` ${p} (everything)`,...r.map(k=>` ${m(k.token)} (${k.label} \xB7 ${k.count} article${k.count===1?"":"s"})`)]}function Oo(e){let t=e.indexOf("--scope");if(t===-1)return!1;let n=e[t+1];return n===void 0||n.startsWith("-")}function vl(e,t){let n=e.indexOf("--scope");if(n===-1)return["--scope",t,...e];let o=e[n+1],r=[...e];return o===void 0||o.startsWith("-")?r.splice(n+1,0,t):r[n+1]=t,r}var $f=3,xf=8;function ks(e){return e===void 0||!Number.isFinite(e)?$f:Math.max(1,Math.min(Math.floor(e),xf))}function bs(e){let t,n,o=!1,r=!1,s,l=m=>{let k=Number(m);return m!==void 0&&Number.isFinite(k)?k:void 0};for(let m=0;m<e.length;m++){let k=e[m];if(k==="--preview"||k==="--dry-run")o=!0;else if(k==="--rewrite"||k==="--force")r=!0;else{if(k==="--run"||k==="--yes"||k==="--all")continue;k==="--scope"?t=e[++m]:k?.startsWith("--scope=")?t=k.slice(8):k==="--concurrency"?s=l(e[++m]):k?.startsWith("--concurrency=")?s=l(k.slice(14)):k&&!k.startsWith("--")&&(n=k)}}let p=m=>m?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:p(t),path:p(n),preview:o,concurrency:s,rewrite:r}}function Cf(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function Rf(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function vs(e,t,n){return n.filter(o=>{try{return $l(xl(e,t,o)).size===0}catch{return!0}})}function $s(e,t,n){let o=new Map(t.map(r=>[r.path,r]));return n.map(r=>{let s=1;for(let l of o.get(r)?.sources??[])try{s+=$l(xl(e,l)).size}catch{}return{path:r,bytes:s}})}function xs(e,t,n={}){let o=n.rewrite?`- Some or all of these articles ALREADY EXIST on disk \u2014 this is a re-author (rewrite/upgrade), NOT a first draft. For any that exist, do NOT preserve or lightly-edit the current file: RE-AUTHOR it from scratch against the plan + sources + the active doc-type playbook standard. The existing file is what you're replacing \u2014 its structure is NOT the target; match only the project's voice/terminology.
|
|
328
328
|
`:"";return`Run the write-article skill to author EACH documentation article listed below. For each path:
|
|
329
329
|
- It is relative to ${t}/. Look up its entry (matching "path") in .d360-writer/plan.json for its purpose, its \`type\` (concept | task | reference | faq | tutorial | troubleshooting | best-practices | use-case; missing \u21D2 task), and the source files it draws from (AGENT-PLAN.md has the same table).
|
|
330
330
|
- Use the skeleton for that \`type\` (see write-article): a \`concept\`/overview page opens with what the product IS + its mental model and takes NO Prerequisites/Steps; only a \`task\` or \`tutorial\` page gets numbered steps (a tutorial ends every stage with a visible checkpoint); a \`troubleshooting\` page is symptom \u2192 cause \u2192 fix. Titles follow the type grammar (task: "How to <verb> <object>"; concept: "Understanding <X>"; troubleshooting: the symptom the user sees).
|
|
@@ -334,81 +334,81 @@ ${s}${m}`).join("")}).join(`
|
|
|
334
334
|
- Each article is independent. Do NOT write, edit, or publish any article not in this list, and do NOT publish to Document360 \u2014 these are local drafts.
|
|
335
335
|
Articles:
|
|
336
336
|
`+e.paths.map(r=>`- ${r}`).join(`
|
|
337
|
-
`)}function
|
|
338
|
-
`)}var
|
|
339
|
-
`)}var
|
|
337
|
+
`)}function Cs(e,t,n){let o=e.reduce((l,p)=>l+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(l=>` \u2022 ${l.label} \u2014 ${l.paths.length} article${l.paths.length===1?"":"s"}`),"",`Estimated cost: ${be(r)}\u2013${be(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function Rs(e,t,n){let o=P=>t[P.index]?.paths.length??0,r=e.filter(P=>P.ok),s=e.filter(P=>!P.ok),l=e.reduce((P,N)=>P+o(N),0),p=r.reduce((P,N)=>P+o(N),0),m=e.reduce((P,N)=>P+N.costUsd,0),k=e.reduce((P,N)=>P+N.outputTokens,0),g=n==="api"?`${be(m)} total`:rt(k),T=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,v=P=>`${P} article${P===1?"":"s"}`,_=[];if(s.length===0)_.push(`Wrote ${v(l)} (${T}) successfully \xB7 ${g}.`),_.push("Next \u2014 push them to Document360:"),_.push("/publish --all"),_.push("Or add screenshots first with /screenshot --all. Drafts are reviewable in the portal after publishing.");else{_.push(`Wrote ${p}/${v(l)} (${T}) \xB7 ${g}.`),_.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let P of s)_.push(` \u2717 ${P.label}${P.error?` \u2014 ${P.error}`:""}`)}return _}function Ps(e,t,n){try{let o=hf({cwd:e,paths:n.map(s=>`${t}/${s}`)});if(o.length===0)return null;let r=new Set(o.map(s=>s.path)).size;return`\u26A0 Doc-checker: ${o.length} issue${o.length===1?"":"s"} in ${r} of the new article${r===1?"":"s"} (leaked internals / unknown commands / stale facts) \u2014 /check --fix corrects them.`}catch{return null}}function Ts(e,t,n){let o=(Cl(e)?.docsDir??wf).replace(/\/+$/,""),r=t.map(p=>p.path);if(n.path){let p=Cf(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=Rf(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 l=vs(e,o,s);if(l.length===0){let p=n.scope?` under "${n.scope}"`:"",m=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${m} --rewrite to regenerate them all.`}}return{docsDir:o,targets:l,planCount:r.length}}async function Rl(e,t){if(!Cl(t.cwd))return console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"};if(Oo(e)){for(let M of bl(t.cwd,t.profileName))console.log(f(M));return{kind:"continue"}}if(st("write",e)){let M=Zt(t.cwd,"write",e,t.profileName);if(M.length>0){for(let B of M)console.log(f(B));return{kind:"continue"}}}let n=gf(t.cwd);if(n.length===0)return console.log(R("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:l,rewrite:p}=bs(e),{docsDir:m,targets:k,reason:g,rewriting:T}=Ts(t.cwd,n,{scope:o,path:r,rewrite:p});if(k.length===0)return console.log(g?L(g):L("Nothing to write.")),{kind:"continue"};T&&console.log(L(`--rewrite: regenerating ${k.length} already-written article${k.length===1?"":"s"} (overwrites them; git has your baseline).`));let v=mf(k),_=ks(l),{model:P,forced:N}=yf(t.cwd,"standard"),S=!!r;if(s&&!S){let M=ff({files:$s(t.cwd,n,k),op:"write",model:P});o&&console.log(f(`Scope: ${o} (${k.length} pending).`));for(let B of Cs(v,M,_))console.log(B);return console.log(f(`Model: ${P}${N?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(f(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Writing ${k.length} article${k.length===1?"":"s"} across ${v.length} partition${v.length===1?"":"s"} (\u2264${_} agents at once) on ${P}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let M of kf({cwd:t.cwd,partitions:v,promptFor:B=>xs(B,m,{rewrite:T||S}),concurrency:_,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:P}))if(M.type==="partition_status")M.status==="running"?console.log(f(` \u25B8 ${M.label} \u2014 writing\u2026`)):M.status==="done"?console.log(D(` \u2713 ${M.label}`)):console.log(R(` \u2717 ${M.label}`));else if(M.type==="run_done"){console.log("");let B=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let Y of Rs(M.results,v,B))console.log(M.ok?D(Y):L(Y));if(M.ok)try{bf(t.cwd,k.map(Y=>`${m}/${Y}`),{writtenCap:vf})}catch{}let V=Ps(t.cwd,m,k);V&&console.log(L(V))}}catch(M){console.log(R(`Write run failed: ${M.message}`))}return console.log(""),{kind:"continue"}}W();import{existsSync as Pf,readdirSync as Pl,statSync as Tl}from"node:fs";import{join as Sl}from"node:path";import{inputDir as Tf,readProjectConfig as Sf}from"document360-engine";var Dl=/\.(md|markdown|pdf|txt)$/i;function Ss(e){let t=Tf(e);if(!Pf(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of Pl(t)){let s=Sl(t,r),l=!1;try{l=Tl(s).isDirectory()}catch{continue}if(l){if(r.startsWith("."))continue;let p=Df(s);p>0&&n.push({name:r,docCount:p})}else Dl.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function Df(e){let t=0;for(let n of Pl(e))try{Tl(Sl(e,n)).isFile()&&Dl.test(n)&&t++}catch{}return t}function Ds(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 Lo(e,t){return["Run the draft-from-prd skill.","",`Target scope: ${e?`the feature documents in .d360-writer/input/${e}/`:t?`the input docs in .d360-writer/input/ relevant to: "${t}"`:"the input docs in .d360-writer/input/"}.`,t&&!e?`Use "${t}" as the feature framing.`:"","","Follow the skill: (1) read those PRDs/specs as the primary source (intent, user-facing surface,","terminology, user stories, prerequisites); (2) locate and read the CODE that implements that surface","to pin exact UI strings/routes/states \u2014 never fabricate; flag anything the PRD claims that you","cannot find in source; (3) propose a tight feature-scoped article set (\u22483\u20135) and pin it to",".d360-writer/plan.json + AGENT-PLAN.md, with each article's `sources` listing BOTH the PRD file(s)","AND the grounding code files; (4) flag overlaps with existing articles (do not merge). Then stop and","offer /write. Do NOT write the articles in this turn."].filter(Boolean).join(`
|
|
338
|
+
`)}var js="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function jl(e,t){let n=t?.cwd??process.cwd();if(!Sf(n))return console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=Ss(n);if(o.length===0&&r===0)return console.log(f(js)),{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 m of o)console.log(` ${m.name} ${f(`(${m.docCount} doc${m.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let p=o[0]?.name??"";return{kind:"forward-to-agent",prompt:Lo(p),display:p?`/draft ${p}`:"/draft"}}let l=Ds(o,s);return{kind:"forward-to-agent",prompt:Lo(l??"",l?void 0:s),display:`/draft ${s}`}}W();import{listOpenForDocs as jf,readProjectConfig as Af}from"document360-engine";function As(e){try{return jf(e).filter(t=>t.kind==="request").length}catch{return 0}}function Es(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function Ns(e,t=!1){let n=["Run the document-handoff skill.",""];return e?n.push(`The builder hand-off (what was shipped this session): "${e}".`,"Treat this as the Stage 1 hand-off: ground it in the cited/changed code + the architecture brief,","then decide and APPLY the right doc action \u2014 a new section, a new article, an update to existing","article(s), or a retirement, or a mix. No fixed shape; pick the smallest set that keeps the docs correct."):n.push("No description was given \u2014 call d360_inbox and act on the OPEN `request` messages the builder left:","for each, run the document-handoff flow (ground \u2192 decide \u2192 apply) and mark the request `status: done`","with `resulting_articles` when finished."),n.push("","Draft only \u2014 do not publish. If you would create multiple new articles (a section), call","d360_estimate_cost and present the count + cost band first, then wait for the go-ahead."),t&&n.push("","After the drafts exist and the user confirms any bulk gate, publish the new/updated articles to","Document360 (the publish-to-d360 skill). On a production profile, respect the write-guard."),n.join(`
|
|
339
|
+
`)}var Is="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 Al(e,t){let n=t?.cwd??process.cwd();if(!Af(n))return console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=Es(e);if(!r&&As(n)===0)return console.log(f(Is)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:Ns(r,o),display:s}}W();import{search as Ef}from"@inquirer/prompts";import{findByName as Nf,getSession as If,listSessions as _f,relativeTime as Nl}from"document360-engine";async function Il(e,t){let n=_f(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=Nf(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(R(`No session matches "${o}".`)),El(n),{kind:"continue"})}if(!process.stdin.isTTY)return El(n),console.log(f("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>Ef({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let l=(s??"").toLowerCase();return n.filter(p=>!l||p.name.toLowerCase().includes(l)||p.firstPrompt.toLowerCase().includes(l)).map(p=>({name:`${p.name} ${Nl(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=If(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function El(e){console.log("");for(let t of e.slice(0,15))console.log(` ${O(t.name)} ${f(Nl(t.updatedAt))}`),console.log(` ${f(t.firstPrompt.slice(0,80))}`);console.log("")}W();import{renameSession as Of}from"document360-engine";function _s(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 _l(e,t){let n=_s(e.join(" "));if(!n)return console.log(R("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(Of(o,n)?console.log(D(`\u2713 Session renamed to "${n}"`)):console.log(R("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(D(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as Ol,readProjectConfig as Lf,writeProjectConfig as Mf}from"document360-engine";W();function Os(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=Lf(e);if(!o)return"No .d360-writer/config.json \u2014 run /init first.";if(o.profiles?.[t])return`Profile "${t}" already exists.`;let r=n??t;return Ol().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},Mf(o,e),null):`Unknown environment "${r}". Known: ${Ol().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function Ll(e,t){let n=e[0];if(!n)return wo(t.cwd),{kind:"continue"};if(n==="add"){let o=Os(t.cwd,e[1],e[2]);return o?(console.log(R(o)),{kind:"continue"}):(console.log(D(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${O(`/profile ${e[1]}`)} then ${O("/login")}`),{kind:"continue"})}return yo(t.cwd,n),ko(t.cwd,n),console.log(f(" Restarting agent for the new profile\u2026")),{kind:"clear"}}W();import{select as Uf}from"@inquirer/prompts";import{readProjectConfig as Wf,readUserConfig as Ml,resolveModelSetting as Ls,writeUserConfig as Ul}from"document360-engine";var We=[{value:null,label:"Auto",desc:"Sonnet (latest) \u2014 right-sized for docs work (recommended); heavier models only when you pin them"},{value:"claude-fable-5",label:"Fable",desc:"Fable 5 \xB7 most capable, for the hardest and longest-running tasks"},{value:"opus",label:"Opus",desc:"Opus (latest) \xB7 best for everyday complex tasks"},{value:"sonnet",label:"Sonnet",desc:"Sonnet (latest) \xB7 efficient for routine tasks"},{value:"haiku",label:"Haiku",desc:"Haiku (latest) \xB7 fastest for quick answers"}];function Mo(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=We.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function Ff(e){switch(e.source){case"project":return".d360-writer/config.json defaultModel (team setting)";case"user":return"~/.document360-writer/config.json (your /model setting)";case"env":return"ANTHROPIC_MODEL environment variable";case"auto":return"auto \u2014 the docs-right default (newest Sonnet); /model to pin another"}}function Dn(e,t){let n=()=>Ls(e).model;if(t==="default"){let s=Ml();return s.defaultModel?(delete s.defaultModel,Ul(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${Ls(e).model} (auto; applies from your next message)`],changed:!0,effective:n()}):{lines:["No personal model override set \u2014 nothing to clear."],changed:!1,effective:void 0}}Ul({...Ml(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=Wf(e)?.defaultModel;return r&&o.push(`\u26A0 .d360-writer/config.json sets defaultModel "${r}" \u2014 the team setting overrides yours until it is removed.`),{lines:o,changed:!0,effective:n()}}async function Wl(e,t){let n=e[0]?.trim();if(!n){let l=Ls(t.cwd);if(!process.stdin.isTTY)return console.log(`${ke("Model:")} ${O(l.model)}${l.source==="auto"?f(" (auto)"):""}`),console.log(f(` source: ${Ff(l)}`)),console.log(f(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let p=Mo(l),m;try{m=await t.withPausedInput(()=>Uf({message:`Select model (current: ${l.model}${l.source==="auto"?" \xB7 auto":""})`,default:We[p].value,choices:We.map((v,_)=>({name:`${v.label}${_===p?" \u2714":""}`,value:v.value,description:v.desc}))}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}let{lines:k,changed:g,effective:T}=Dn(t.cwd,m??"default");for(let v of k)console.log(v.startsWith("\u26A0")?L(v):v.startsWith("\u2713")?D(v):f(v));return g&&await t.setModel(T),{kind:"continue"}}let{lines:o,changed:r,effective:s}=Dn(t.cwd,n);for(let l of o)console.log(l.startsWith("\u26A0")?L(l):l.startsWith("\u2713")?D(l):f(l));return r&&await t.setModel(s),{kind:"continue"}}Uo();async function Gl(e,t){return await t.withPausedInput(()=>Gt(t.cwd)),{kind:"clear"}}async function Yl(e,t){return await t.withPausedInput(()=>fo(t.cwd,t.profileName)),{kind:"clear"}}W();import{resolveActiveProfile as sh}from"document360-engine";async function zl(e,t){let n=!1;try{n=sh(t.cwd).production}catch{}return n?(console.log(L("\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 Kl=async(e,t)=>{try{await t.withPausedInput(()=>go({}))}catch(n){console.log(R(`Login failed: ${n.message}`))}return{kind:"continue"}};W();import{resolveActiveProfile as ih,clearTokens as ah,clearProfileProject as lh}from"document360-engine";async function Xl(e,t){let n;try{n=ih(t.cwd,t.profileName).name}catch(r){return console.log(R(r.message)),{kind:"continue"}}let o=ah(n);return lh(t.cwd,n),console.log(o?D(`\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 Ql}from"node:fs";import{isAbsolute as ch,join as dh,resolve as uh}from"node:path";import{readProjectConfig as ph,screenshotPlaceholderIds as fh,DEFAULT_CAPTURE_DIR as hh,DEFAULT_OUTPUT_DIR as mh}from"document360-engine";var Jl=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Us(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?Jl(n[1]):void 0};let o=n[0];return!o||o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:Jl(o),setup:t}:{mode:"single",id:o}}function Ws(e,t){let n=ph(e),o=n?.captureDir??hh,r=n?.outputDir??mh,s=(l,p)=>ch(l)?dh(l,p):uh(e,l,p);return fh(e,{scope:t}).map(({id:l,file:p})=>{let m=Ql(s(r,`${l}.png`))?"captured":Ql(s(o,`${l}.spec.ts`))?"spec":"placeholder";return{id:l,file:p,state:m}})}var gh={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},wh={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function Fs(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 l of e.filter(p=>p.file===s))r.push(` ${gh[l.state]} ${l.id.padEnd(34)} ${wh[l.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function Zl(e){return["Run the emit-screenshot-spec skill to author the document360-capture spec for EACH of these","SCREENSHOT placeholder ids:",e.paths.map(t=>`- ${t}`).join(`
|
|
340
340
|
`),"","For each: locate its <!-- SCREENSHOT --> block in the docs tree (the configured docsDir); read the product source for","EXACT routes + stable data-testid selectors (never guess); enter the prepared context via","captureScope(); guard data prerequisites with test.skip(reason); write <captureDir>/<id>.spec.ts","(skip-with-TODO if a stable selector is missing). Do NOT run other skills. Report the specs you","wrote and any TODO data-testids."].join(`
|
|
341
|
-
`)}async function
|
|
341
|
+
`)}async function Wo(e,t){let n=Us(e);if(n.mode==="list"){let l=t?.cwd??process.cwd();for(let p of Fs(Ws(l,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(`
|
|
342
342
|
`),display:`/screenshot ${n.id}`};let r=[`Run the emit-screenshot-spec skill to (re)generate the document360-capture spec for ${n.mode==="scope"?`every <!-- SCREENSHOT --> placeholder in articles under ${n.scope}`:"every <!-- SCREENSHOT --> placeholder across the docs tree (the configured docsDir)"}.`,"Follow that skill exactly for each: read the SCREENSHOT block; read the product source for EXACT routes","and stable data-testid selectors (never guess); enter the prepared context via captureScope(); guard data",`prerequisites with test.skip(reason); write <captureDir>/<id>.spec.ts.${n.setup?" When done, run capture-setup-checklist to refresh CAPTURE-SETUP.md.":""} Report specs written, TODO data-testids, and data to stage.`].join(`
|
|
343
|
-
`),s=n.mode==="scope"?`/screenshot ${n.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:r,display:s}}import{existsSync as
|
|
344
|
-
`),display:"/capture-setup"}}var
|
|
345
|
-
`)}async function
|
|
346
|
-
`)}var
|
|
347
|
-
`).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function
|
|
343
|
+
`),s=n.mode==="scope"?`/screenshot ${n.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:r,display:s}}import{existsSync as yh,readFileSync as kh}from"node:fs";import{isAbsolute as bh,join as vh,resolve as $h}from"node:path";import{readProjectConfig as xh,DEFAULT_CAPTURE_DIR as Ch}from"document360-engine";async function An(){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(`
|
|
344
|
+
`),display:"/capture-setup"}}var ec="-".repeat(64);function Hs(e){let t=Ch;try{let g=xh(e);g?.captureDir&&(t=g.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=bh(t)?vh(t,"CAPTURE-TESTID-REQUESTS.json"):$h(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!yh(n))return null;let o;try{let g=JSON.parse(kh(n,"utf8").replace(/^/,""));o=Array.isArray(g?.requests)?g.requests:[]}catch{return null}if(o.length===0)return null;let r=new Set(o.map(g=>g.file).filter(Boolean)).size,s=o.length,l=`${s} data-testid attribute${s===1?"":"s"}`,p=`${r} source file${r===1?"":"s"}`,m=`${t}/CAPTURE-TESTID-REQUESTS.md`,k=`${t}/CAPTURE-TESTID-REQUESTS.json`;return[`\u{1F4CB} Developer hand-off \u2014 ${l} 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.","",ec,`Read ${m} and ${k}. They list ${l} 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.",ec]}nt();W();import{listOpenForDocs as Rh,readProjectConfig as Ph}from"document360-engine";function qs(e){try{return Rh(e).length}catch{return 0}}function Bs(){return["Process the two-way message inbox from the source repo's coding agent (the builder).","","1. Call d360_inbox to list the OPEN messages addressed to you.","2. For each message, act by its kind:",' \u2022 request ("document the X we shipped") \u2192 treat it as a session hand-off: run the document-handoff'," skill \u2014 read what changed, ground it in the cited sources + the architecture brief, then decide and"," apply the RIGHT doc action (new section, new article, update existing, or retire). No fixed shape.",' \u2022 answer to a [discovery]-tagged question (subject starts "[discovery] ") \u2192 this is product-discovery,'," not an article edit: fold the fact into `.d360-writer/product-brief.md` (updating the cited grounding,"," clearing the matching OPEN marker), then RE-RUN the discover-product readiness assessment \u2014 set the"," brief's frontmatter status to `confident` and offer propose-structure if every rubric dimension now"," passes, else ask the next focused batch via d360_ask_builder. Do not touch articles for these.",' \u2022 answer to a [depth]-tagged question (subject starts "[depth] ") \u2192 this is per-feature depth-mining,'," not the brief and not an article edit: fold it into the DOCS PLAN per propose-structure's"," depth-reconcile \u2014 adjust that feature's article palette in plan.json/AGENT-PLAN.md (add rows citing"," the answer's .d360-writer/messages/ file in `sources`, never renumber existing rows), decrement"," open_depth_questions in AGENT-PLAN.md's frontmatter, and flip status to `pinned` at zero."," \u2022 answer (a reply to any other question you asked; `re` = your question id) \u2192 fold the fact into the"," affected article(s), and into `.d360-writer/architecture/` if it is durable product knowledge.","3. After acting on a message, mark it resolved: edit its file in `.d360-writer/messages/` and set the"," frontmatter `status: done` (add `done_at` with the current UTC time). Never delete the file.","4. Drafts only \u2014 do not publish unless explicitly asked. End with a one-line summary of what you did per"," message (and, for any request you could not fully ground, what you still need)."].join(`
|
|
345
|
+
`)}async function tc(e,t){let n=t?.cwd??process.cwd();return Ph(n)?qs(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:Bs(),display:"/inbox"}:(console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{listOpenHints as Th,listOpenForDocs as Sh,listOpenDirectives as Dh,readProjectConfig as jh,computeSyncStatus as Ah,planPull as Eh,applyPull as Nh,planImport as Ih,applyImport as _h}from"document360-engine";function En(e){let t=0,n=0,o=0,r=0;try{t=Th(e).length}catch{}try{let s=Sh(e);n=s.filter(l=>l.kind==="request").length,o=s.filter(l=>l.kind==="answer").length}catch{}try{r=Dh(e).length}catch{}return{hints:t,requests:n,answers:o,directives:r}}function Nn(e){let t=[];return e.hints&&t.push(`${e.hints} hint${e.hints===1?"":"s"}`),e.requests&&t.push(`${e.requests} request${e.requests===1?"":"s"}`),e.answers&&t.push(`${e.answers} answer${e.answers===1?"":"s"}`),e.directives&&t.push(`${e.directives} directive${e.directives===1?"":"s"}`),t.length?t.join(", "):null}function Gs(e){return{publish:e.includes("--publish")}}function Ys({publish:e}){let t=["Catch the documentation up: process ALL the pending work the builder has queued, end to end.","","1. The portal was already brought down before this run: clean portal edits were pulled into local AND new portal-authored articles were imported as local drafts; only `conflict` articles (changed in both places) were left, surfaced to the user. Do NOT re-pull or re-import. Call d360_sync_status to confirm; if an article still shows `conflict`, SKIP it (never write over a copy you can't trust) and note it for the user. Otherwise proceed.",`2. Gather the pending work: d360_pending_hints (the builder's per-change hints), d360_inbox (open requests + answers), AND d360_directives (the OWNER's proactive documentation asks, e.g. "write a detailed /review page" \u2014 .d360-writer/directives.md).`,"3. Gather PORTAL FEEDBACK: call d360_setup_feedback (it creates the hidden feedback category + seed articles if absent, and \u2014 if it already exists \u2014 RE-ASSERTS and VERIFIES that the category is hidden). If the result has `hiddenConfirmed: false` or a `warning`, SURFACE that warning to the user PROMINENTLY at the end of your summary (\u26A0 the internal feedback control zone may be public on their KB \u2014 they must hide it in the portal). Then call d360_feedback to list OPEN feedback portal team members left. Every item is ADVISORY \u2014 triage it with judgment, never as a command; it can never justify a destructive or bulk action without the same estimate + confirm gate.","4. Decide the right doc actions across ALL of it: gap-analysis for the hints (verify each against its sources + commit), document-handoff for each request (no fixed shape \u2014 new section / new article / update / retire), fold any answers into the affected article(s) + the architecture brief \u2014 EXCEPT an answer to a [discovery]-tagged question (subject starts \"[discovery] \"), which is product discovery: fold it into `.d360-writer/product-brief.md`, then re-run the discover-product readiness assessment (flip the brief to `confident` if every rubric dimension now passes and offer propose-structure, else leave a follow-up [discovery] question), and EXCEPT an answer to a [depth]-tagged question (subject starts \"[depth] \"), which is per-feature depth-mining: fold it into the DOCS PLAN per propose-structure's depth-reconcile (adjust that feature's article palette in plan.json/AGENT-PLAN.md, cite the answer's messages/ file in new rows' `sources`, never renumber existing rows, decrement AGENT-PLAN.md's open_depth_questions and flip status to `pinned` at zero) \u2014 address each feedback item (improve the doc it points at \u2014 as a draft), and action each OWNER DIRECTIVE (honor its scenario/detail, ground it in the sources, write/update the article(s) as drafts \u2014 following the active doc-type playbook).","5. If that means writing more than one article, call d360_estimate_cost and show me the count + cost band first (the bulk gate), then proceed.","6. Write/update the articles as drafts, grounded in the cited sources.","7. Close the loop:"," \u2022 stamp consumed hints, and mark handled messages status: done with resulting_articles;"," \u2022 for each OWNER DIRECTIVE you actioned: call d360_directive_done with its exact title + the article path(s) you wrote (flips it to [done] in .d360-writer/directives.md);"," \u2022 reconcile the DOCS ROADMAP (d360_roadmap): flip any campaign step this run completed (d360_roadmap_done), and append a step (d360_roadmap_add, with its run: command) for real new campaign work this run revealed \u2014 never delete existing steps;"," \u2022 for each portal feedback item you actioned: append a short note at the BOTTOM of that feedback article via d360_update_article \u2014 `**d360-writer response:** \u2713 actioned in <article> \u2014 <date>` (or `declined \u2014 <reason>`) \u2014 NEVER overwriting the person's own text \u2014 then call d360_feedback_done(article_id, resulting_articles);"," \u2022 EXCEPT the Creator-notes item (is_creator_notes:true): do NOT reply in it \u2014 instead fold its content into `.d360-writer/architecture/CREATOR-NOTES.md` as an appended, dated `## From portal Creator notes (<date>)` section (preserve every existing note + human edit), then call d360_feedback_done for it.","8. Push the drafts to Document360.","9. Cross-link second pass: any article you wrote that links to ANOTHER article in this same batch had that inline link degrade to plain text (its target had no live URL yet when the source was written). Now that every target exists, re-update the affected articles so those inline links resolve to live URLs \u2014 only the ones that had such forward references need it. (The structured Related Articles sidebars are already two-way linked; this is just inline body links.)"];return t.push(e?"10. Then publish the new/updated articles live (publish-to-d360 skill), respecting the production write-guard.":"Leave everything as DRAFTS for review \u2014 do not publish live (run /publish when you want them live)."),t.push("","End with a one-line-per-item summary of what you wrote/updated, and anything you couldn't ground (plus the d360_ask_builder question you left for it)."),t.join(`
|
|
346
|
+
`)}var Oh={status:Ah,plan:Eh,apply:Nh,planImport:Ih,applyImport:_h};async function zs(e,t=Oh){let n={pulled:[],imported:[],conflicts:[],failed:[]},o;try{o=await t.status({cwd:e.cwd,profileName:e.profileName})}catch(r){return n.error=r.message,n}for(let r of o.entries)if(r.status==="conflict"&&r.path)n.conflicts.push(r.path);else if(r.status==="untracked-remote"&&r.articleId)try{let s=await t.planImport({cwd:e.cwd,profileName:e.profileName,articleId:r.articleId});t.applyImport({cwd:e.cwd,profileName:e.profileName},s),n.imported.push(s.path)}catch(s){n.failed.push({path:r.title??r.articleId,error:s.message})}else if(r.status==="remote-ahead"&&r.path)try{let s=await t.plan({cwd:e.cwd,profileName:e.profileName,relPath:r.path});t.apply({cwd:e.cwd,profileName:e.profileName},s),n.pulled.push(r.path)}catch(s){n.failed.push({path:r.path,error:s.message})}return n}var Vs=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Fo=e=>e===1?"":"s";function Ks(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${Fo(e.pulled.length)} into local: ${Vs(e.pulled)}`),e.imported.length&&t.push(`\u2713 Imported ${e.imported.length} new portal article${Fo(e.imported.length)} into local drafts: ${Vs(e.imported)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${Fo(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${Vs(e.conflicts)}`),e.failed.length&&t.push(`\u26A0 ${e.failed.length} pull/import${Fo(e.failed.length)} failed \u2014 left for /pull.`),t}async function nc(e,t){let n=t?.cwd??process.cwd();if(!jh(n))return console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Ne(n,t?.profileName);if(!o.ok)return console.log(R(o.reason)),{kind:"continue"};let{publish:r}=Gs(e);console.log(f("Reconciling with Document360 (pulling any portal changes)\u2026"));let s=await zs({cwd:n,profileName:t?.profileName});for(let p of Ks(s))console.log(p.startsWith("\u2713")?D(p):p.startsWith("\u2139")?f(p):L(p));let l=Nn(En(n));return console.log(f(l?`Catching up on ${l}\u2026`:"Checking for code changes the builder didn't hint\u2026")),{kind:"forward-to-agent",prompt:Ys({publish:r}),display:`/catch-up${r?" --publish":""}`}}W();import{spawn as Lh}from"node:child_process";var xt="document360-writer",Ho=`npm i -g ${xt}@latest`;async function qo(){let e=process.platform==="win32";return new Promise(t=>{try{let n=Lh(`npm i -g ${xt}@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 oc(){return console.log(f(`Updating ${xt}\u2026`)),(await qo()).ok?console.log(D("\u2713 Updated. Exit (/exit) and relaunch d360-writer to apply.")):console.log(R(`Update failed \u2014 run manually: ${Ho}`)),{kind:"continue"}}W();nt();import{existsSync as Xs,rmSync as Mh}from"node:fs";import{basename as rc,resolve as Qs}from"node:path";import{execFileSync as Uh}from"node:child_process";import{input as Wh}from"@inquirer/prompts";import{readProjectConfig as Fh,devHintsGuidePath as Hh}from"document360-engine";var qh=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],Bh=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),Bo=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),sc=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function ic(e){let t=Bo(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:sc(t)?!0:Bh.has(t)}function Js(e){let t=null;try{t=Fh(e)}catch{t=null}let n=new Set(qh);for(let o of[Bo(t?.docsDir),Bo(t?.captureDir),Bo(t?.outputDir)])o&&sc(o)&&n.add(o);return[...n].filter(o=>ic(o)&&Xs(Qs(e,o)))}function Zs(e,t){let n=[],o=[];for(let r of t){if(!ic(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{Mh(Qs(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function ac(e,t){try{return Uh("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
|
|
347
|
+
`).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function Vh(e){return ac(e,".d360-writer/hints")}function Gh(e){return ac(e,".d360-writer/messages")}function ei(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=Vh(e),o=Gh(e),r=Xs(Qs(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: ${rc(e)}`]}async function lc(e,t){let n=Js(t.cwd);for(let m of ei(t.cwd,n))console.log(n.length===0?f(m):m);if(n.length===0)return{kind:"continue"};let o=rc(t.cwd);if((await t.withPausedInput(()=>Wh({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(L("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=Xs(Hh(t.cwd)),{removed:l,failed:p}=Zs(t.cwd,n);console.log(D(`\u2713 Reset complete \u2014 removed ${l.length} item${l.length===1?"":"s"}. The repo is back to its original state.`));for(let m of p)console.log(R(` \u2717 ${m.path}: ${m.error}`));if(s){for(let m of xo())console.log(m);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 Yh}from"document360-engine";function Vo(e){if(e.length===0)return["\u2713 No issues found \u2014 no leaked internals, unknown commands, stale version facts, or AI-tells in the docs."];let t=new Map;for(let o of e){let r=t.get(o.path)??[];r.push(o),t.set(o.path,r)}let n=[`\u26A0 ${e.length} doc issue${e.length===1?"":"s"} in ${t.size} article${t.size===1?"":"s"} (leaked internals / unknown commands / stale facts / AI-tells):`];for(let[o,r]of t){n.push(` ${o}`);for(let s of r)n.push(` L${s.line}: "${s.term}" \u2014 ${s.message}`)}return n}function ti(e){let t=new Map;for(let o of e){let r=t.get(o.path)??[];r.push(o),t.set(o.path,r)}return["The documentation quality check found issues in already-written articles. FIX each one by EDITING the","article in place \u2014 do not rewrite whole articles, just resolve the flagged problems. Ground every change","in the actual product source (the authoritativeSourceFiles); never invent.","","How to fix, by issue type:","- internal-leak (an agent codename, an internal skill name, or a d360_* tool name): this is the"," documentation engine's own machinery and must NOT appear in user docs. Reword the sentence to describe"," the behavior in plain user terms, or delete the internal aside. Do NOT swap it for another internal term.","- unknown-command: the named /command or --flag does not exist in the product source. Find the correct"," command/flag in the source and use it; if there is no real equivalent, remove the claim.","- stale-fact: the version contradicts the product's package.json engines \u2014 correct it to the real value.","- ai-tell: a machine-sounding buzzword (e.g. delve, leverage, furthermore, robust). Rewrite the phrase in"," plain, direct developer language; preserve the meaning; do NOT swap one buzzword for another.","","Rules: edit ONLY the listed articles; do not touch others; do not publish; introduce no new internal","nouns, invented commands, or wrong facts. When done, every listed issue should be gone.","","Issues:",[...t.entries()].map(([o,r])=>[o,...r.map(s=>` - L${s.line} [${s.kind}]: "${s.term}" \u2014 ${s.message}`)].join(`
|
|
348
348
|
`)).join(`
|
|
349
349
|
`)].join(`
|
|
350
|
-
`)}async function
|
|
351
|
-
`);return{prompt:
|
|
352
|
-
`),display:`/reorder${n?` ${n}`:""}`}}async function
|
|
353
|
-
\u2022 `),lead:{kind:"cmd",cmd:"/catch-up",reason:n},picker:null,follow:"Then /catch-up clears what\u2019s queued for the docs."})}if(e.hasDocs&&e.pendingWrites>0){let n=e.pendingWrites;t.push({key:"write",bullet:`${n} planned article${fe(n)} still unwritten`,lead:{kind:"cmd",cmd:"/write",reason:"it finishes the articles already planned"},picker:null,follow:`Then /write finishes the ${n} planned article${fe(n)}.`})}if(e.localAhead>0){let n=e.localAhead;t.push({key:"publish",bullet:`${n} article${fe(n)} changed locally \u2014 ready to publish`,lead:{kind:"cmd",cmd:"/publish",reason:`it pushes your ${n} local edit${fe(n)} up to Document360`},picker:null,follow:`Then /publish pushes your ${n} local edit${fe(n)} up.`})}if(e.conflicts>0){let n=e.conflicts;t.push({key:"resolve",bullet:`${n} article${fe(n)} changed both here and on Document360 (conflicts) \u2014 /publish skips these`,lead:{kind:"cmd",cmd:"/resolve",reason:"it walks each conflict \u2014 keep yours, take the portal's, or skip"},picker:null,follow:`Then /resolve settles the ${n} conflict${fe(n)} (keep yours / take the portal's / skip).`})}if(e.hasDocs&&e.roadmap?.next){let n=e.roadmap,o=n.next;t.push({key:"roadmap",bullet:`docs campaign: ${n.done} of ${n.total} step${fe(n.total)} done \u2014 next: ${o.title}`,lead:o.run?{kind:"cmd",cmd:o.run,reason:"it\u2019s the next step of your docs campaign"}:{kind:"prompt",text:o.title,reason:"it\u2019s the next step of your docs campaign"},picker:null,follow:`Then the campaign continues: ${o.title} (/roadmap shows all ${n.total} steps).`})}if(e.behind>0){let n=e.behind;t.push({key:"audit",bullet:`${n} code change${fe(n)} since your last docs check`,lead:{kind:"cmd",cmd:"/audit",reason:"it shows what the latest code changes touch (or /audit --auto on to run it for you)"},picker:null,follow:`After that, /audit covers the ${n} newer commit${fe(n)}.`})}return t}function
|
|
354
|
-
`)];return r.length&&s.push(r.join(" ")),s.push(
|
|
355
|
-
|
|
356
|
-
`)}function
|
|
357
|
-
`).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let l=
|
|
358
|
-
`);return{lines:s.slice(0,t).map(l=>Re(l,
|
|
359
|
-
`))console.log(l(` ${p}`));s.rec.picker&&console.log(O(` Pick one: ${s.rec.picker.options.map(p=>p.cmd).join(" \xB7 ")}`))}}catch{}}console.log(f(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function
|
|
360
|
-
|
|
361
|
-
`),console.log(`${D("\u25CF")} ${
|
|
362
|
-
`);let s=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(f(` (${
|
|
363
|
-
`),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){
|
|
364
|
-
`)}import{existsSync as
|
|
365
|
-
\u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close \xB7 d360-writer v${n} \xB7 engine v${o}`})]})}var
|
|
366
|
-
`)){let l=s.trim().replace(
|
|
367
|
-
`)}function
|
|
368
|
-
`)||e.length>200}function
|
|
369
|
-
`).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function
|
|
370
|
-
`)){if(s.length===0)o.push({start:r,end:r});else for(let l=0;l<s.length;l+=n)o.push({start:r+l,end:r+Math.min(l+n,s.length)});r+=s.length+1}return o.length>0?o:[{start:0,end:0}]}function
|
|
350
|
+
`)}async function cc(e,t){let n=e.includes("--fix"),o=e.find(l=>!l.startsWith("--")),r=o?` ${o}`:"",s=Yh({cwd:t.cwd,scope:o});if(n)return s.length===0?(console.log(D("\u2713 Nothing to fix \u2014 the docs are already clean.")),{kind:"continue"}):(console.log(f(`Fixing ${s.length} doc issue${s.length===1?"":"s"} (run /check again after to confirm)\u2026`)),{kind:"forward-to-agent",prompt:ti(s),display:`/check${r} --fix`});console.log(f("Linting the docs (engine internals, unknown commands, stale facts, AI-tells)\u2026"));for(let l of Vo(s))console.log(s.length===0?D(l):L(l));return s.length>0&&console.log(f("Run /check --fix to have the agent correct these.")),console.log(""),{kind:"continue"}}W();import{lintDocs as Zh,loadStyleGuide as em,buildReviewPrompt as tm,readProjectConfig as nm,DEFAULT_DOCS_DIR as om}from"document360-engine";W();import{readProjectConfig as zh,loadProfileMap as Kh,resolveActiveProfile as Xh,desiredCategoryOrder as Qh,desiredArticleOrder as Jh}from"document360-engine";function dc(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}var uc=e=>e.replace(/\\/g,"/").split("/").pop()??e;function In(e,t){try{if(!zh(e))return[];let n=Xh(e,t),o=Kh(e,n.name);if(!o)return[];let r=new Map;for(let l of Jh(o)){let p=r.get(l.categoryPath);p?p.push(l):r.set(l.categoryPath,[l])}let s=[];for(let l of Qh(o)){s.push(dc(uc(l.path)));for(let p of(r.get(l.path)??[]).sort((m,k)=>m.order-k.order))s.push(` ${dc(uc(p.path))}`)}return s}catch{return[]}}async function pc(e,t){let n=In(t.cwd,t.profileName);if(n.length===0)return console.log(f("No documentation structure yet \u2014 run /init and author some articles first.")),{kind:"continue"};console.log(O("Documentation order (categories \u2192 articles):"));for(let o of n)console.log(o);return console.log(""),{kind:"continue"}}function ni(e,t){let n=nm(e);if(!n)return null;let o=(n.docsDir??om).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),s=t.find(g=>!g.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),l=Zh({cwd:e}),p=s?l.filter(g=>g.path===`${o}/${s}`||g.path.startsWith(`${o}/${s}/`)):l,m=s?"":In(e).join(`
|
|
351
|
+
`);return{prompt:tm({docsRoot:o,scope:s,styleGuide:em(e),deterministicFindings:p,fix:r,structure:m||void 0}),display:`/review${s?` ${s}`:""}${r?" --fix":""}`}}async function fc(e,t){if(st("review",e)){let o=Zt(t.cwd,"review",e,t.profileName);if(o.length>0){for(let r of o)console.log(f(r));return{kind:"continue"}}}let n=ni(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{readProjectConfig as rm}from"document360-engine";function oi(e,t){if(!rm(e))return null;let n=t.find(r=>!r.startsWith("--"));return{prompt:[`Reorder the articles within ${n?`the "${n}" category`:"each category"} to the best reading order.`,"Follow the manage-structure skill: decide the ideal order with senior-editor judgment per the doc-genre","playbook (overview / mental-model first; reference and troubleshooting/FAQ last), then APPLY it with the","d360_reorder_articles tool \u2014 one category at a time, all paths in the same category folder.",n?"":"If the CATEGORY order itself reads wrong too, fix that first with the d360_reorder_categories tool (folder paths under one parent, in the desired order).","Do not rename files or folders or edit the map by hand; the tools handle it. Report the new order, and","remind me it reaches Document360 on the next /publish."].filter(Boolean).join(`
|
|
352
|
+
`),display:`/reorder${n?` ${n}`:""}`}}async function hc(e,t){if(st("reorder",e)){let o=Zt(t.cwd,"reorder",e,t.profileName);if(o.length>0){for(let r of o)console.log(f(r));return{kind:"continue"}}}let n=oi(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{readProjectConfig as sm,writeProjectConfig as mc,isAppType as im,playbookSkillName as am,detectAppType as gc}from"document360-engine";var wc=["web","cli","service","library"],lm=new Set(["web","cli"]);function ri(e){return lm.has(e)?`${am(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function Go(e,t){let n=t.cwd,o=sm(n);if(!o)return console.log(R("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let s=o.appType??gc(n);if(s){let l=o.appType?"set in config":"auto-detected";console.log(`${O("Genre:")} ${s} (${l}) \u2014 ${ri(s)}`)}else console.log(L("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(f(`Set it: /genre <${wc.join("|")}> \xB7 revert to auto-detect: /genre auto`)),{kind:"continue"}}if(r==="auto"||r==="clear"){if(!o.appType)return console.log(f("Already on auto-detect (no genre set in config).")),{kind:"continue"};let{appType:s,...l}=o;mc(l,n);let p=gc(n);return console.log(D(`\u2713 Genre reset to auto-detect \u2014 now: ${p?`${p} (${ri(p)})`:"unclassified (no playbook)"} (applies from your next command).`)),{kind:"continue"}}return im(r)?(mc({...o,appType:r},n),console.log(D(`\u2713 Genre set to ${r} \u2014 ${ri(r)} (applies from your next command).`)),{kind:"continue"}):(console.log(R(`Unknown genre "${r}". Choose one of: ${wc.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}W();import{listRoadmap as yc,roadmapProgress as kc,stampRoadmapDone as cm}from"document360-engine";function si(e){let t=yc(e);if(t.length===0)return["No docs roadmap yet \u2014 the docs agent seeds .d360-writer/roadmap.md when it pins a structure,","and adds steps as the app changes. You can also write steps by hand (## [open] <step>), or ask:",'"propose the docs roadmap for this repo".'];let n=kc(e),o=[`Docs roadmap \u2014 ${n.done} of ${n.total} step${n.total===1?"":"s"} done:`,""];for(let r of t)o.push(` ${r.status==="done"?"\u2713":"\u25CB"} ${r.title}${r.run?` \xB7 ${r.run}`:""}`);return o.push(""),o.push(n.next?`Next: ${n.next.title}${n.next.run?` \u2014 ${n.next.run}`:""}`:"Campaign complete \u2014 the docs agent adds new steps as the app changes."),o.push("(Edit .d360-writer/roadmap.md freely \xB7 /roadmap done <step> marks one you finished yourself.)"),o}function ii(e,t){if(!t.trim())return{ok:!1,line:"Usage: /roadmap done <step title>"};if(!cm(e,t,{doneAt:new Date().toISOString()})){let r=yc(e).filter(s=>s.status==="open");return{ok:!1,line:r.length?`No open step titled "${t}". Open steps: ${r.map(s=>`"${s.title}"`).join(", ")}`:`No open step titled "${t}" \u2014 the roadmap has no open steps.`}}let o=kc(e)?.next;return{ok:!0,line:`\u2713 Marked done: ${t}${o?` \u2014 next up: ${o.title}${o.run?` (${o.run})`:""}`:" \u2014 that was the last step: campaign complete."}`}}async function bc(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let r=ii(n,e.slice(1).join(" ").trim());return console.log(r.ok?D(r.line):L(r.line)),{kind:"continue"}}let o=si(n);console.log(O(o[0]??""));for(let r of o.slice(1))console.log(r.startsWith("(")?f(r):r);return{kind:"continue"}}var vc={help:Mr,"?":Mr,clear:ba,exit:Ur,quit:Ur,init:Br,mcp:Po,publish:rl,audit:Tn,discover:sl,scope:al,pull:yl,resolve:ml,convert:kl,write:Rl,draft:jl,document:Al,resume:Il,rename:_l,profile:Ll,model:Wl,doctor:jn,workspace:Gl,project:Yl,"allow-prod":zl,login:Kl,logout:Xl,screenshot:Wo,"capture-setup":An,devhints:Aa,inbox:tc,"catch-up":nc,update:oc,reset:lc,check:cc,review:fc,reorder:hc,structure:pc,genre:Go,roadmap:bc};function $c(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}nt();var dm="Or just tell me what to write or update.",um='\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 fe(e){return e===1?"":"s"}function Yo(e){return e.kind==="cmd"?`\u21E5 tab to run ${e.cmd} \xB7 or just ask me anything\u2026`:null}function _n(e){return e.kind==="cmd"?`I\u2019d start with ${e.cmd} \u2014 ${e.reason}.`:`Just tell me: \u201C${e.text}\u201D.`}var pm={title:"What kind of product is this repo? (sets the doc-craft playbook \u2014 otherwise the docs stay generic)",options:[{cmd:"/genre web",desc:"web app / SaaS UI"},{cmd:"/genre cli",desc:"command-line tool"},{cmd:"/genre service",desc:"API / backend service"},{cmd:"/genre library",desc:"SDK / library"}]};function fm(e){let t=[];if(e.devhints!=="current"&&e.builderStarted){let n=e.devhintsToVersion?`v${e.devhintsToVersion}`:"a newer version",o=e.devhints==="stale"&&e.devhintsCompletedVersion?` (your builder is on v${e.devhintsCompletedVersion})`:"";t.push({key:"devhints",bullet:`dev\u2194docs protocol moved to ${n}${o} \u2014 your docs aren\u2019t blocked`,lead:{kind:"cmd",cmd:"/devhints",reason:`one paste updates your builder to ${n}`},picker:null,follow:"Also run /devhints when you get a second \u2014 your builder\u2019s protocol is behind.",tone:"warn"})}if(e.genreUnknown&&t.push({key:"genre",bullet:"the doc genre isn\u2019t set \u2014 I can\u2019t load the right doc-craft playbook yet",lead:null,picker:pm,follow:"Then pick the doc genre below (it sets the playbook I write with)."}),e.discovery&&e.discovery.status!=="confident"){let n=e.discovery.openQuestions;t.push(e.discovery.status==="pending"?{key:"discovery",bullet:"your existing docs aren\u2019t grounded in a product brief yet",lead:{kind:"cmd",cmd:"/discover",reason:"it interviews your builder and grounds the docs before you rewrite or publish them"},picker:null,follow:"Then /discover grounds your docs in a product brief (do this before the rewrite/publish steps)."}:n>0?{key:"discovery",bullet:`product discovery is waiting on ${n} answer${fe(n)} from your builder \u2014 nudge them`,lead:null,picker:null,follow:"Discovery is waiting on your builder\u2019s answers \u2014 nudge them, then /catch-up folds the answers in once they reply."}:{key:"discovery",bullet:"product discovery is ready to continue",lead:{kind:"cmd",cmd:"/discover",reason:"it continues interviewing your builder to ground the docs"},picker:null,follow:"Then /discover continues building the product brief."})}if(e.directives>0||e.pendingText){let n=e.directives>0&&e.pendingText?"it actions your directives and clears the builder\u2019s queue":e.directives>0?"it actions the directives you left":"it clears everything your builder queued",o=[];e.directives>0&&o.push(`${e.directives} owner directive${fe(e.directives)} waiting`),e.pendingText&&o.push(`your builder left ${e.pendingText}`),t.push({key:"catchup",bullet:o.join(`
|
|
353
|
+
\u2022 `),lead:{kind:"cmd",cmd:"/catch-up",reason:n},picker:null,follow:"Then /catch-up clears what\u2019s queued for the docs."})}if(e.hasDocs&&e.pendingWrites>0){let n=e.pendingWrites;t.push({key:"write",bullet:`${n} planned article${fe(n)} still unwritten`,lead:{kind:"cmd",cmd:"/write",reason:"it finishes the articles already planned"},picker:null,follow:`Then /write finishes the ${n} planned article${fe(n)}.`})}if(e.localAhead>0){let n=e.localAhead;t.push({key:"publish",bullet:`${n} article${fe(n)} changed locally \u2014 ready to publish`,lead:{kind:"cmd",cmd:"/publish",reason:`it pushes your ${n} local edit${fe(n)} up to Document360`},picker:null,follow:`Then /publish pushes your ${n} local edit${fe(n)} up.`})}if(e.conflicts>0){let n=e.conflicts;t.push({key:"resolve",bullet:`${n} article${fe(n)} changed both here and on Document360 (conflicts) \u2014 /publish skips these`,lead:{kind:"cmd",cmd:"/resolve",reason:"it walks each conflict \u2014 keep yours, take the portal's, or skip"},picker:null,follow:`Then /resolve settles the ${n} conflict${fe(n)} (keep yours / take the portal's / skip).`})}if(e.hasDocs&&e.roadmap?.next){let n=e.roadmap,o=n.next;t.push({key:"roadmap",bullet:`docs campaign: ${n.done} of ${n.total} step${fe(n.total)} done \u2014 next: ${o.title}`,lead:o.run?{kind:"cmd",cmd:o.run,reason:"it\u2019s the next step of your docs campaign"}:{kind:"prompt",text:o.title,reason:"it\u2019s the next step of your docs campaign"},picker:null,follow:`Then the campaign continues: ${o.title} (/roadmap shows all ${n.total} steps).`})}if(e.behind>0){let n=e.behind;t.push({key:"audit",bullet:`${n} code change${fe(n)} since your last docs check`,lead:{kind:"cmd",cmd:"/audit",reason:"it shows what the latest code changes touch (or /audit --auto on to run it for you)"},picker:null,follow:`After that, /audit covers the ${n} newer commit${fe(n)}.`})}return t}function xc(e){return e.find(t=>t.lead||t.picker)??null}function ai(e,t){let n=t.filter(l=>l.bullet).map(l=>` \u2022 ${l.bullet}`),o=xc(t),r=[];o?.lead?r.push(_n(o.lead)):o?.picker&&r.push("Pick the genre below \u2014 one keypress, and it shapes everything I write.");for(let l of t.filter(p=>p!==o).slice(0,2))l.follow&&r.push(l.follow);let s=[[e,...n].join(`
|
|
354
|
+
`)];return r.length&&s.push(r.join(" ")),s.push(dm),s.join(`
|
|
355
|
+
|
|
356
|
+
`)}function On(e){if(!e.ready)return{kind:"idle"};let t=fm(e);if(!e.hasDocs){let s=xc(t);return s&&(s.lead?.kind==="cmd"||s.picker)?{kind:"recommend",rec:{note:ai("\u{1F4ED} No docs yet for this repo \u2014 here\u2019s where things stand:",t),tone:s.tone??"info",lead:s.lead,picker:s.picker}}:{kind:"recommend",rec:{note:um,tone:"info",lead:{kind:"prompt",text:"write the docs for this repo",reason:"I\u2019ll read the code and draft a structure"},picker:null}}}if(t.length===0){let s=e.roadmap&&!e.roadmap.next?` Docs campaign complete \u2014 all ${e.roadmap.total} step${fe(e.roadmap.total)} done (/roadmap).`:"";return{kind:"recommend",rec:{note:`Welcome back. Your ${e.tracked} tracked article${fe(e.tracked)} for \u201C${e.profileName}\u201D are all in sync \u2014 /audit re-checks the code, /pull brings down portal edits.${s}`,tone:"info",lead:null,picker:null}}}let n=t.filter(s=>s.lead||s.picker),o=n[0]??null;return o?(o.key==="audit"||o.key==="roadmap"&&n[1]?.key==="audit")&&e.behind>0&&e.autoAudit&&e.allowAutoAudit?{kind:"autoAudit",note:`\u{1F4CB} ${e.behind} code change${fe(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`}:{kind:"recommend",rec:{note:ai("Welcome back \u2014 where your docs stand:",t),tone:o.tone??"info",lead:o.lead,picker:o.picker}}:{kind:"recommend",rec:{note:ai("Welcome back \u2014 where your docs stand:",t),tone:"info",lead:null,picker:null}}}import{existsSync as li,readdirSync as di}from"node:fs";import{spawnSync as hm}from"node:child_process";import{join as zo}from"node:path";import{readProjectConfig as Rc,resolveActiveProfile as Pc,loadTokens as mm,isExpired as gm,loadProfileMap as Tc,localAheadPaths as wm,loadKnownConflicts as ym,readDocsPlan as km,devHintsGuidePath as bm,DEFAULT_DOCS_DIR as ci,roadmapProgress as vm,listRoadmap as $m,readProductBriefState as xm}from"document360-engine";nt();function Cc(e){try{return di(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function ui(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>Cc(zo(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&Cc(zo(e,o)))}function pi(e,t){try{let n=Rc(e);if(!n)return!1;let o=Pc(e,t),r=Tc(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=zo(e,(n.docsDir??ci).replace(/\/+$/,""));return!!(li(s)&&di(s).length>0||li(bm(e)))}catch{return!1}}function Ln(e,t,n){try{let o=Rc(e);if(!o)return null;let r=Pc(e,t),s=mm(r.name),l=!!s&&(!gm(s)||!!s.refreshToken),p=pi(e,t)||!ui(e,o.authoritativeSourceFiles),m=Tc(e,r.name),k=m?Object.keys(m.articles).length:0,g=zo(e,(o.docsDir??ci).replace(/\/+$/,"")),T=!1;try{T=li(g)&&di(g).length>0}catch{}let v=0;if(m?.lastAnalyzedCommit)try{let Se=hm("git",["rev-list","--count",`${m.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});Se.status===0&&(v=parseInt((Se.stdout||"").trim(),10)||0)}catch{}let _=0;try{let Se=km(e);if(Se.length>0){let Ke=(o.docsDir??ci).replace(/\/+$/,"");_=vs(e,Ke,Se.map(Wn=>Wn.path)).length}}catch{}let P=En(e),N=Nn({...P,directives:0}),S=wm(e,t),M=new Set(ym(e,r.name)),B=S.filter(Se=>M.has(Se)).length,V=S.length-B,Y=Ee(e),ue=vm(e),_e=xm(e),he=_e?{status:_e.status,openQuestions:_e.openQuestions}:null;return!he&&T&&$m(e).some(Ke=>Ke.status==="open"&&(Ke.run??"").trim()==="/discover")&&(he={status:"pending",openQuestions:0}),{ready:l&&p&&!n.claudeMissing,hasDocs:T,tracked:k,pendingText:N,directives:P.directives,behind:v,pendingWrites:_,localAhead:V,conflicts:B,autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:Y.status,devhintsCompletedVersion:Y.completedVersion,devhintsToVersion:ae,builderStarted:Ge(e),genreUnknown:n.genreUnknown,roadmap:ue,discovery:he}}catch{return null}}function Sc(e,t){let n=[],o="";for(let r of e.split(/\s+/).filter(Boolean))for(o.length?o.length+1+r.length<=t?o+=` ${r}`:(n.push(o),o=r):o=r;o.length>t;)n.push(o.slice(0,t)),o=o.slice(t);return o&&n.push(o),n}function Ko(e){if(e.length===0)return[];let t=(s,l)=>`${s}${"\u2500".repeat(78)}${l}`,n=(s="")=>`\u2502 ${s.padEnd(76)} \u2502`,o=[`\u2B06 d360-writer upgraded \u2014 ${e.length===1?"one improvement affects":`${e.length} improvements affect`} the docs you've already written:`,"",t("\u250C","\u2510")];e.forEach((s,l)=>{l>0&&o.push(t("\u251C","\u2524")),o.push(n());for(let p of Sc(`${l+1}. ${s.feature}`,76))o.push(n(p));o.push(n());for(let p of Sc(s.why,73))o.push(n(` ${p}`));o.push(n())}),o.push(t("\u2514","\u2518")),o.push("");let r=e.length>1;return o.push(`\u2713 ${r?"These are":"This is"} now on your docs roadmap \u2014 each launch shows your next step below (/roadmap shows the full campaign).`),o}W();var Cm={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"},jc=160,hi=200,Ac=40;function Re(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function Dc(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}: ${Re(typeof r=="string"?r:JSON.stringify(r),Ac)}`);return t.length>4&&n.push("\u2026"),Re(n.join(", "),jc)}var it=e=>typeof e=="string"&&e?e:null,fi=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function Rm(e){let t=it(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 Pm(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=it(t.title);if(!o)return null;let r=Rm(t.local_path);return n("Create article",`"${Re(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=it(t.title),r=fi(t.article_id);return n("Update article",o?`"${Re(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",fi(t.article_id)?`id ${fi(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",it(t.name)?`"${Re(it(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=it(t.file_path);return n("Upload image",o?Re(o.replace(/\\/g,"/").split("/").pop()??o,60):null)}case"d360_sync_status":return n("Check sync status",null);default:return null}}function Xo(e,t){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,r="",...s]=e.split("__"),l=s.join("__");if(r==="document360"){let k=Pm(l,t);if(k)return k}let p=l.replace(/^d360_/,"").replace(/_/g," ");return{title:`${r==="document360"?"Document360":r.charAt(0).toUpperCase()+r.slice(1)}: ${p}`,sep:" ",arg:Dc(t)}}let n=Cm[e],o=n?t[n]:void 0;return typeof o=="string"&&o?{title:e,sep:"",arg:Re(o,jc)}:{title:e,sep:"",arg:Dc(t)}}function Tm(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 Sm(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(Tm).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>Re(r,hi))]}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}: ${Re(String(r),Ac)}`);return n.length>0?[Re(n.join(" \xB7 "),hi)]:null}return null}function Dm(e){let t=it(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function jm(e,t,n){switch(e){case"d360_create_article":{let o=Dm(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=it(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 ${Re(o[0],120)}`:""}`]}default:return null}}function Qo(e,t=4,n,o){let r=e.replace(/\r\n/g,`
|
|
357
|
+
`).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let l=jm(n.slice(18),o,r);if(l)return{lines:l,hidden:0}}let s=Sm(r)??r.split(`
|
|
358
|
+
`);return{lines:s.slice(0,t).map(l=>Re(l,hi)),hidden:Math.max(0,s.length-t)}}function Jo(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function Zo(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 Ec(e,t){try{let n=JSON.parse(e),r=(Array.isArray(n)?n[0]:n)?.[t];return typeof r=="string"&&/^https?:\/\//.test(r)?r:null}catch{return null}}function er(e){return Ec(e,"url")}function tr(e){return Ec(e,"preview_url")}var Xm=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Qm(e,t,n,o){if(Xm.test(e))try{let r=_c(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,l=Zo(t,n),p=er(n);e.endsWith("publish_article")&&p&&console.log(O(` \u2B95 Live: ${p}`));let m=tr(n);m?console.log(O(` \u2B95 Preview: ${m}`)):l&&s&&console.log(O(` \u2B95 Preview: ${Jo(r.connection.portalUrl,s,l,r.project.languageCode??"en")}`))}catch{}}async function Oc(e=process.cwd(),t="auto",n,o){let r=Em(t);r.kind==="none"&&(console.error(""),console.error(R("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${O("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${O('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${O("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${O("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),Jm(e,n),r.kind==="subscription"&&(r.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 s=!1,l=mi({cwd:e,profileName:n,allowProdWrites:s}),p={uuid:null,firstPrompt:null,titleFired:!1},m=Am({input:process.stdin,output:process.stdout}),k=[],g=null,T=!1;m.on("line",P=>{if(g){let N=g;g=null,N(P)}else k.push(P)}),m.on("close",()=>{if(T=!0,g){let P=g;g=null,P(null)}});function v(){return k.length>0?Promise.resolve(k.shift()):T?Promise.resolve(null):(process.stdout.write(O("> ")),new Promise(P=>{g=P}))}let _={cwd:e,version:o,profileName:n,allowProdWrites:()=>s,restartAgent:()=>{l.close(),l=mi({cwd:e,profileName:n,allowProdWrites:s}),p={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>p.uuid,setPendingName:P=>{p.pendingName=P},setModel:async P=>l.setModel(P),withPausedInput:async P=>{m.pause();try{return await P()}finally{m.resume()}}};try{for(;;){let P=await v();if(P===null)break;let N=P.trim();if(N){if(N.startsWith("/")){let S=$c(N);if(!S)continue;let M=vc[S.name];if(!M){console.log(R(`Unknown command: /${S.name}`)),console.log(f("Type /help for the list."));continue}let B=await M(S.args,_);if(B.kind==="exit")break;if(B.kind==="clear"){_.restartAgent();continue}if(B.kind==="allow-prod"){s=!0,_.restartAgent(),console.log(D("\u2713 Production writes authorized for this session.")),console.log("");continue}if(B.kind==="resume"){l.close(),l=mi({cwd:e,resume:B.uuid,profileName:n,allowProdWrites:s});let V=Nm(B.uuid);p={uuid:B.uuid,firstPrompt:V?.firstPrompt??null,titleFired:!0},Ic(B.uuid),console.log(D(`\u2713 Resumed "${B.name}"`)),console.log("");continue}if(B.kind==="forward-to-agent"){p.firstPrompt||(p.firstPrompt=B.display??B.prompt);let V=(B.display??"").trim().split(/\s+/),Y=(V[0]==="/check"||V[0]==="/review")&&V.includes("--fix"),ue=V.slice(1).find(he=>!he.startsWith("--")),_e=Y?zm(e,ue):[];if(await gi(l,B.prompt,r,p,e),Y)try{Ym(e,_e,{reviewedCap:Km})}catch{}}else Zm(e,n);continue}if(qm(N)){let S=Bm(N);if(S){try{Vm(e,{title:S,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}p.firstPrompt||(p.firstPrompt=N),await gi(l,`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${S}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${S}" and the article path(s) you wrote.`,r,p,e);continue}}p.firstPrompt||(p.firstPrompt=N),await gi(l,N,r,p,e)}}}finally{l.close(),m.close()}}function Jm(e,t){console.log(""),console.log(yn("document360-writer")),console.log(f(` cwd: ${e}`));let n=Mm(e);if(console.log(f(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(eg(e,t)),!Um(e))console.log(L(" First run: /init (scaffolds config + prints the builder hand-off prompt) \u2192 /login, then ask me to write the docs."));else{let o=!1;try{if(vo(e),!Ge(e))for(let r of $o(e))console.log(L(` ${r}`))}catch{}try{let r=Wm(e);r.persisted&&r.appType?console.log(f(` \u2713 Detected a ${r.appType} app \u2014 enabled the ${r.appType}-doc-playbook (change with /genre).`)):r.source==="unknown"&&(o=!0)}catch{}try{let r=Gm(e);for(let s of Ko(r.applied))console.log(L(` ${s}`))}catch{}try{let r=Ln(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:o}),s=r?On(r):null;if(s?.kind==="recommend"&&s.rec.note){let l=s.rec.tone==="warn"?L:f;for(let p of s.rec.note.split(`
|
|
359
|
+
`))console.log(l(` ${p}`));s.rec.picker&&console.log(O(` Pick one: ${s.rec.picker.options.map(p=>p.cmd).join(" \xB7 ")}`))}}catch{}}console.log(f(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function Zm(e,t){try{let n=Ln(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:!1}),o=n?On(n):null;o?.kind==="recommend"&&o.rec.lead&&console.log(f(` Next: ${_n(o.rec.lead)}`))}catch{}}function eg(e,t){try{let n=_c(e,t),o=n.production?L(" \u26A0 PRODUCTION"):"",r=Hm(n.name);if(!r)return f(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...Nc(r.idToken)??{},...Nc(r.accessToken)??{}},l=s.email??s.preferred_username??"signed in";return Fm(r)&&!r.refreshToken?L(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):f(` Document360: ${l} \xB7 profile "${n.name}"${o}`)}catch(n){return f(` Document360: ${n.message.split(".")[0]}`)}}function tg(){console.error(""),console.error(`Sign in with your Claude subscription: run ${O("claude")} once, then retry.`),console.error(` (No Claude Code? ${O("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${O("https://console.anthropic.com/settings/keys")}`)}function ng(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;Om({uuid:t,name:r??_m(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function og(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||Lm(o,t).then(r=>{r&&Im(n,r)}).catch(()=>{})}async function gi(e,t,n,o,r){let s=new Map;for await(let l of e.send(t))rg(l,o,r,n,s)}function rg(e,t,n,o,r){switch(e.type){case"session":t.uuid||ng(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let s=Xo(e.name,e.input);s&&(process.stdout.write(`
|
|
360
|
+
|
|
361
|
+
`),console.log(`${D("\u25CF")} ${ke(s.title)}${s.arg!==null?ie(`${s.sep}(${s.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let s=Ye(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!s)break;let l=p=>p===1?"":"s";console.log(ie(` \u23BF Added ${s.added} line${l(s.added)}, removed ${s.removed} line${l(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 l=Qo(e.output,4,e.isError?void 0:s.name,s.input),p=e.isError?R:ie;l.lines.forEach((m,k)=>console.log(p((k===0?" \u23BF ":" ")+m))),l.hidden>0&&console.log(f(` \u2026 +${l.hidden} lines`)),e.isError||Qm(s.name,s.input,e.output,n);break}case"result":{process.stdout.write(`
|
|
362
|
+
`);let s=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(f(` (${Cn(s)}\u2192${Cn(e.outputTokens)} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(Ic(t.uuid),t.titleFired||og(t,n));break}case"error":console.error(""),console.error(R(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&tg();break}}import{render as kw}from"ink";import{resolveAuth as bw}from"document360-engine";import{useCallback as z,useEffect as Te,useMemo as $i,useRef as ee,useState as F}from"react";import{Box as ne,Text as j,useApp as kg,useInput as bg,useStdout as vg}from"ink";import{existsSync as tn,readFileSync as dr,readdirSync as $g}from"node:fs";import{basename as Un,isAbsolute as xg,join as xi}from"node:path";import{createSession as ud,classifyClaudeAuth as Di,CLAUDE_CODE_SETUP_HINT as Cg,loginPkce as Rg,toStoredTokens as Pg,saveTokens as Tg,getAccessToken as Sg,resolveActiveProfile as Pe,resolveProjectId as Dg,getArticle as jg,decodeJwtClaims as on,isExpired as at,loadTokens as Rt,clearTokens as Ag,clearProfileProject as Eg,setTitle as Ng,slugify as Ig,touchSession as Ci,upsertSession as _g,generateTitle as pd,findByName as Og,listSessions as Lg,renameSession as Mg,suggestNextAction as Ug,readProjectConfig as te,writeProjectConfig as fd,resolveAndPersistAppType as Wg,detectAppType as Fg,resolveModelSetting as ji,loadProfileMap as hd,applyPull as md,computeSyncStatus as Ri,lintDocs as gd,compareRemoteSources as Hg,planPull as wd,establishBaselines as qg,rebaselineServerMeta as Bg,inventoryRepo as Vg,knownEnvironments as Gg,resolveEnvironment as Yg,planPartitions as Pi,partitionEvenly as zg,screenshotPlaceholderIds as Kg,trackedArticlePaths as Xg,runPartitioned as ur,estimateBulkCost as yd,resolveModelForOperation as pr,readDocsPlan as Qg,checkForUpdate as Jg,detectInstallKind as Zg,isSelfUpdatable as ew,devHintsGuidePath as kd,toolFeedbackPath as bd,reconcileToolFeedback as tw,reconcileUpgradeActions as nw,stampArticles as Ti,listArticleFiles as vd,CONTENT_CAP_VERSION as Si,ENGINE_VERSION as Dd,DEFAULT_DOCS_DIR as jd,setProfileProject as ow,writeCrashLog as rw,applyStructureOrder as $d,orderSyncLine as xd,applyRelatedArticles as Cd,relatedSyncLine as Rd}from"document360-engine";nt();import{spawn as Lc}from"node:child_process";function sg(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function ig(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?Lc([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):Lc(e,t,{stdio:["pipe","ignore","ignore"]});r.on("error",()=>o(!1)),r.on("close",l=>o(l===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 wi(e){for(let[t,n]of sg())if(await ig(t,n,e))return!0;return!1}var ag=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function yi(e,t){if(t.closed)return e;let n=e.split(`
|
|
363
|
+
`),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){ag.test(s)&&(t.cueSeen=!0);continue}let l=/^(\s{0,3})[-*•]\s+(.*)$/.exec(s);l?(n[r]=`${l[1]}${++t.num}. ${l[2]}`,o=!0):o&&s.trim()!==""&&/^\S/.test(s)&&(t.closed=!0)}return n.join(`
|
|
364
|
+
`)}import{existsSync as lg,mkdirSync as cg,readFileSync as dg,writeFileSync as ug}from"node:fs";import{join as Mc}from"node:path";import{writerDir as pg}from"document360-engine";function Uc(e){return Mc(pg(e),".sessions")}function Wc(e,t){return Mc(Uc(e),`${t}.json`)}function Fc(e,t,n){try{cg(Uc(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");ug(Wc(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function ki(e,t){try{let n=Wc(e,t);if(!lg(n))return[];let o=JSON.parse(dg(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var fg=e=>`\x1B]0;${e}\x07`,hg=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function Hc(e){process.stdout.isTTY&&process.stdout.write(e)}function en(e){Hc(fg(e))}function nr(e){Hc(hg(e))}var or=["\xB7 "," \xB7"],rr="\u{1F7E3}";Uo();Ro();var sr=[{name:"init",usage:"/init",desc:"Pick an environment, scaffold .d360-writer/config.json, and set up the builder hand-off (prints the one-paste prompt)",group:"start"},{name:"login",usage:"/login",desc:"Sign in to Document360 (browser)",group:"start"},{name:"project",usage:"/project [name]",desc:"Choose the Document360 project (picker; lists all you can access)",group:"start"},{name:"devhints",usage:"/devhints",desc:"Re-show/refresh the builder hand-off prompt (set up by /init; run anytime to hand your repo agent the latest)",group:"start"},{name:"scope",usage:"/scope",desc:"Choose which repo folders back the docs (monorepos)",group:"start"},{name:"genre",usage:"/genre [web|cli|service|library|auto]",desc:"Set/show the product genre \u2014 picks the docs craft playbook (usually auto-detected; set it if it guessed wrong)",group:"start"},{name:"mcp",usage:"/mcp [list|add|remove]",desc:"Connect MCP servers (Notion, Linear, \u2026)",group:"start"},{name:"discover",usage:"/discover",desc:"Interview your builder to understand the product (identity, mental model, misconceptions, positioning) \u2192 pins a product brief that grounds the docs; asks focused questions and loops until confident",group:"docs"},{name:"draft",usage:"/draft [<feature>]",desc:"Draft a feature's articles from its PRDs/specs in .d360-writer/input/ + the code",group:"docs"},{name:"document",usage:"/document [<what>] [--publish]",desc:"Document a shipped change \u2014 the agent picks the action (new section/article/update); bare: act on builder requests",group:"docs"},{name:"write",usage:"/write [--preview|--scope <cat>|<path>] [--rewrite] [--concurrency N]",desc:"Write the planned articles in parallel (starts immediately; --preview shows plan + cost first; --rewrite regenerates already-written articles; --concurrency default 3)",group:"docs"},{name:"screenshot",usage:"/screenshot [--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:"check",usage:"/check [<category|path>] [--fix]",desc:"Check docs for leaked internals, invented commands, and stale facts (deterministic, no tokens). Scope to a category/path; --fix has the agent correct the findings in place",group:"docs"},{name:"review",usage:"/review [<category|path> | --all] [--fix]",desc:"Independent senior-editor review: style guide, terminology/voice, grammar/clarity, structure, improvement suggestions. Bare: pick a category or everything; --all reviews the whole KB; --fix applies the corrections in place",group:"docs"},{name:"reorder",usage:"/reorder [<category> | --all]",desc:"Reorder articles within a category to the best reading order (renumbers NN- prefixes, fixes references + map); bare: pick a category or everything; new order syncs to Document360 on next /publish",group:"docs"},{name:"structure",usage:"/structure",desc:"Show the documentation reading order (categories \u2192 articles) as it will appear on Document360",group:"docs"},{name:"roadmap",usage:"/roadmap [done <step>]",desc:"Show the docs campaign (the multi-session plan the agent maintains) \u2014 progress + next step; `done <step>` marks one you finished yourself",group:"docs"},{name:"audit",usage:"/audit [--auto on|off]",desc:"Gap analysis: code vs docs vs Document360 (what changed); --auto runs it at launch when code changed",group:"publish"},{name:"inbox",usage:"/inbox",desc:"Act on messages from the repo's coding agent (requests to document, answers to your questions)",group:"publish"},{name:"catch-up",usage:"/catch-up [--publish]",desc:"Process ALL pending work (hints + requests + drift) \u2192 write \u2192 push to Document360 (bare = drafts; --publish goes live)",group:"publish"},{name:"pull",usage:"/pull [<path> | --status | --baseline]",desc:"Bring Document360 down: pull portal edits + import NEW portal articles. --status: drift report only \xB7 --baseline: set a sync base \xB7 <path>: one article / resolve a conflict",group:"publish"},{name:"resolve",usage:"/resolve [<path>]",desc:"Resolve conflicts (edited both here and on the portal): shows the diff, then keep local (publish), take portal (pull), or skip \u2014 for each. Bare: walk them all",group:"publish"},{name:"convert",usage:"/convert [--scope <folder>] [--run]",desc:"Convert tracked articles to DFM (one-off legacy migration)",group:"publish"},{name:"profile",usage:"/profile [name|add <name> [env]]",desc:"Switch/create a Document360 connection (picker; s = session)",group:"setup"},{name:"workspace",usage:"/workspace [name]",desc:"Switch the Document360 workspace (picker)",group:"setup"},{name:"model",usage:"/model [name|default]",desc:"Set the Claude model for d360-writer",group:"setup"},{name:"logout",usage:"/logout",desc:"Sign out + clear project/workspace selection (then /login to re-pick)",group:"setup"},{name:"allow-prod",usage:"/allow-prod",desc:"Authorize writes to a production profile",group:"setup"},{name:"doctor",usage:"/doctor",desc:"Health-check: auth, profile, workspace, map, API",group:"setup"},{name:"update",usage:"/update",desc:"Update d360-writer to the latest version (then relaunch)",group:"setup"},{name:"feedback",usage:"/feedback",desc:"Copy the repo's open d360-writer tool-feedback to your clipboard, to relay to the d360-writer team",group:"setup"},{name:"reset",usage:"/reset",desc:"[DANGER] Delete all d360-writer files (docs, config, screenshots); types repo name to confirm",group:"setup"},{name:"resume",usage:"/resume [name]",desc:"Resume a session (no arg lists them)",group:"session"},{name:"rename",usage:"/rename [name]",desc:"Name the session (no arg: suggest one)",group:"session"},{name:"clear",usage:"/clear",desc:"Clear the screen + reset the conversation (resumable)",group:"session"},{name:"help",usage:"/help",desc:"Show this help",group:"session"},{name:"exit",usage:"/exit",desc:"Quit",group:"session"}],qc={"/catch-up":"write up everything your builder flagged","/audit":"check the code for anything new or missing in the docs","/discover":"interview your builder so the docs are grounded in the real product","/pull":"pull edits + new articles from Document360","/publish":"publish your drafts to Document360","/write":"author the planned articles","/draft":"plan articles from PRDs + the code","/login":"sign in to Document360","/workspace":"choose the Document360 workspace","/project":"choose the Document360 project","/scope":"choose which folders back the docs","/genre":"set this repo's product type (picks the docs playbook)","/init":"set up this repo","/screenshot":"generate screenshots","/doctor":"run a health check"};function Bc(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(qc[n])return qc[n];let o=sr.find(r=>r.name===t);return o?o.desc:""}function Vc(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return sr.filter(n=>n.name.startsWith(t))}function Gc(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}W();import{Box as Yc,Text as ce}from"ink";import{jsx as de,jsxs as ir}from"react/jsx-runtime";function mg({row:e}){switch(e.t){case"head":return de(ce,{color:q,bold:!0,children:e.s});case"text":return de(ce,{children:e.s});case"dim":return de(ce,{dimColor:!0,children:e.s});case"sub":return de(ce,{bold:!0,dimColor:!0,children:e.s});case"good":return de(ce,{color:"green",children:e.s});case"step":return ir(ce,{children:[de(ce,{color:q,children:`${e.n}. `}),e.s]});case"cmd":return ir(ce,{children:[" ",de(ce,{color:q,children:e.name.padEnd(20)}),de(ce,{dimColor:!0,children:e.s})]});case"gap":return de(ce,{children:" "})}}function zc({tab:e,width:t,version:n,engineVersion:o}){let r=Ae[e]??Ae[0],s=6+Ae.reduce((p,m)=>p+m.label.length+4,0),l="\u2500".repeat(Math.min(s,Math.max(t-1,20)));return ir(Yc,{flexDirection:"column",paddingX:1,children:[ir(ce,{children:[de(ce,{color:q,bold:!0,children:"Help "}),Ae.map((p,m)=>m===e?de(ce,{color:"white",backgroundColor:q,bold:!0,children:` ${p.label} `},p.key):de(ce,{dimColor:!0,children:` ${p.label} `},p.key))]}),de(ce,{color:q,children:l}),de(Yc,{flexDirection:"column",marginTop:1,children:r.rows.map((p,m)=>de(mg,{row:p},m))}),de(ce,{dimColor:!0,children:`
|
|
365
|
+
\u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close \xB7 d360-writer v${n} \xB7 engine v${o}`})]})}var gg=/^(?:\d+[.)]|[-*•])\s+/;function Kc(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
|
|
366
|
+
`)){let l=s.trim().replace(gg,""),p=l.match(/^`([^`]+)`$/);p&&(l=p[1].trim());let m=l.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!m||!o.has(m[1].toLowerCase()))continue;let k=`/${m[1].toLowerCase()}${m[2]?` ${m[2]}`:""}`;if(r.includes(k)||r.push(k),r.length>=n)break}return r}W();function Mn(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function ze(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function Xc(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var wg=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function Qc(e,t,n){if(!wg.has(e))return null;let o=t?.file_path;if(typeof o!="string"||!o)return null;let r=o.replace(/\\/g,"/");return n.find(s=>{let l=s.replace(/\\/g,"/");return r===l||r.endsWith(`/${l}`)})??null}function bi(e){return e.replace(/^[\w.-]+\//,"")}var ar=16,Jc={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function Ct(e){return typeof e=="string"?e:e.cmd}function Zc(e){return typeof e=="string"?void 0:e.desc}function vi(e){return e.trim().split(/\s+/).slice(1).join(" ")}function ed(e,t){let n=vi(t);return e.some(r=>Ct(r).trim()===t.trim()||!!n&&vi(Ct(r))===n)?e.filter(r=>Ct(r).trim()!==t.trim()&&!(n&&vi(Ct(r))===n)):[]}import{isDirectiveMention as sw,stripDirectiveMention as iw,appendDirective as aw}from"document360-engine";var yg=/\[Pasted text #\d+ \+\d+ lines?\]/g;function td(e){return e.replace(/\r\n?/g,`
|
|
367
|
+
`)}function nd(e){return e.includes(`
|
|
368
|
+
`)||e.length>200}function od(e,t){let n=t.split(`
|
|
369
|
+
`).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function rd(e,t){return e.replace(yg,n=>t.get(n)??n)}function sd(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function lr(e,t){let n=Math.max(1,t),o=[],r=0;for(let s of e.split(`
|
|
370
|
+
`)){if(s.length===0)o.push({start:r,end:r});else for(let l=0;l<s.length;l+=n)o.push({start:r+l,end:r+Math.min(l+n,s.length)});r+=s.length+1}return o.length>0?o:[{start:0,end:0}]}function cr(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function id(e,t,n){let o=cr(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 ad(e,t,n){let o=e[cr(e,t)];return n==="start"?o.start:o.end}function ld(e,t,n){let o=Math.max(1,n),r=e.split(`
|
|
371
371
|
`),s=0;for(let l=r.length-1;l>=0;l--){let p=r[l];if(s+=Math.max(1,Math.ceil(p.length/o)),s>=t){let m=s-t;return{text:[m>0?p.slice(m*o):p,...r.slice(l+1)].join(`
|
|
372
|
-
`),truncated:l>0||m>0}}}return{text:e,truncated:!1}}function
|
|
373
|
-
`)){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
|
|
372
|
+
`),truncated:l>0||m>0}}}return{text:e,truncated:!1}}function cd(e,t){if(t||e.length===0||/\s$/.test(e))return{head:e,keep:""};let n=e.search(/\s\S*$/);return n<0?{head:"",keep:e}:{head:e.slice(0,n),keep:e.slice(n)}}function dd(e){let t=!1,n=0,o=0;for(let r of e.split(`
|
|
373
|
+
`)){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 fr,jsx as E,jsxs as K}from"react/jsx-runtime";var lw={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL",auto:"auto \u2014 right-sized for docs \xB7 /model to change"},Pd=` 1. /init \u2014 pick your Document360 environment & scaffold config
|
|
374
374
|
2. /login \u2014 sign in & pick your Document360 project (workspace auto-selected)
|
|
375
|
-
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function
|
|
376
|
-
${
|
|
375
|
+
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function cw(e,t,n,o){let r=Di(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)",l=ji(e),p=te(e),m=(p?.docsDir??jd).replace(/\/+$/,""),k=p?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${m}/ + config`,g={version:t,engineVersion:Dd,claude:s,model:l.model,modelSource:lw[l.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:p!==null,mode:k};if(p===null)return g;try{let T=Pe(e,o);g.profile=T.name,g.apiUrl=T.connection.apiUrl,g.prod=T.production,g.project=T.project.projectName??T.project.projectId??"(chosen at login)";let v=Rt(T.name);if(v){let _={...on(v.idToken)??{},...on(v.accessToken)??{}},P=_.email??_.preferred_username??"signed in";at(v)?v.refreshToken&&(g.who=P,g.loggedOut=!1,g.sessionHint="session expired \u2014 refreshing\u2026"):(g.who=P,g.loggedOut=!1,g.sessionHint=`session valid until ${new Date(v.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return g}function dw(e,t){try{let n=Pe(e,t),o=Rt(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...on(o.idToken)??{},...on(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return at(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 Td=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],rn=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],uw="Ask me to write or update an article\u2026";function nn({ch:e,dim:t}){let[n,o]=F(!0);return Te(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),E(j,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var pw=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Sd(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var fw=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function hw({startTime:e,chars:t}){let[n,o]=F(0);Te(()=>{let m=setInterval(()=>o(k=>k+1),120);return()=>clearInterval(m)},[]);let r=rn[n%rn.length],s=Td[Math.floor(n/16)%Td.length],l=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return K(ne,{children:[E(j,{color:q,children:` ${r} ${s}\u2026 `}),E(j,{color:"gray",children:`(${Rn(l)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}function mw({text:e}){let[t,n]=F(0);return Te(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),E(ne,{paddingX:1,children:E(j,{color:q,children:`${rn[t%rn.length]} ${e}`})})}var gw=12e4;function ww({p:e}){let[t,n]=F(0);Te(()=>{let S=setInterval(()=>n(M=>M+1),150);return()=>clearInterval(S)},[]);let o=rn[t%rn.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),l=Math.round(e.chars/4),p=Date.now()-e.lastAt>=gw,m=e.verb??"Converting",k=e.unit??"article",g=e.rows.reduce((S,M)=>S+M.items,0),T=m.toLowerCase(),v=e.rows,_=0;if(v.length>ar){let S=v.findIndex(B=>B.status==="active"||B.status==="pending"),M=Math.max(0,Math.min(S-2,v.length-ar));_=v.slice(0,M).filter(B=>B.status==="done").length,v=v.slice(M,M+ar)}let P=Math.min(40,Math.max(...v.map(S=>bi(S.label).length),0)),N=S=>S==="failed"?"red":S==="active"?q:void 0;return K(ne,{flexDirection:"column",children:[K(ne,{children:[E(j,{color:q,children:` ${o} ${m} ${g} ${k}${g===1?"":"s"} `}),E(j,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${l} tokens \xB7 ${Rn(r)} \xB7 esc to stop`})]}),_>0&&E(j,{dimColor:!0,children:` \u2714 +${_} done`}),v.map(S=>K(j,{color:N(S.status),dimColor:S.status==="done"||S.status==="pending",children:[` ${Jc[S.status]} ${bi(S.label).padEnd(P)}`,S.status==="active"&&S.itemsDone!==void 0?` (${S.itemsDone}/${S.items} ${k}${S.items===1?"":"s"})`:S.status!=="pending"?` (${S.items} ${k}${S.items===1?"":"s"})`:"",S.status==="active"?` \u2190 ${T}\u2026`:""]},S.label)),p&&E(j,{color:"yellow",children:` \u26A0 no activity for ${Rn(s)} \u2014 press esc to stop if it's wedged`})]})}var yw=10800*1e3;function Ad({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=kg(),[s,l]=F(n),[p,m]=F(null),[k,g]=F({text:"",pos:0}),T=k.text,v=z(c=>{g(a=>{let i=typeof c=="function"?c(a.text):c;return{text:i,pos:i.length}})},[]),_=z(c=>{g(a=>({text:a.text.slice(0,a.pos)+c+a.text.slice(a.pos),pos:a.pos+c.length}))},[]),P=z(()=>{g(c=>{if(c.pos===0)return c;let a=c.text.slice(0,c.pos),i=sd(a)??a.slice(0,-1);return{text:i+c.text.slice(c.pos),pos:i.length}})},[]),[N,S]=F(!1),[M,B]=F(!1),[V,Y]=F(0),[ue,_e]=F(!1),[he,Se]=F(null),[Ke,Wn]=F(null),[lt,ct]=F([]),Fn=ee(!1),mr=ee(!1),[gr,Ii]=F(!1),Hn=ee(0),[Md,qn]=F(!1),[Ud,Bn]=F(!1),[wr,_i]=F(null),[Wd,Pt]=F(0),dt=ee(0),[sn,Tt]=F(0),[St,Vn]=F(null),Oi=ee(new Map),Fd=ee(0),Dt=ee([]),De=ee(null);De.current===null&&(De.current=ud({cwd:e,profileName:s,allowProdWrites:!1}));let Fe=ee({uuid:null,firstPrompt:null,titleFired:!1}),Gn=ee(new Map),jt=ee(!1),yr=ee([]),le=ee([]),At=ee([]),Yn=ee(null),[Li,ut]=F(null),kr=ee(null),[pt,ft]=F(null),[He,Et]=F(null),[qe,Nt]=F(null),[me,It]=F(null),[ve,ht]=F(null),[Xe,_t]=F(null),[Be,mt]=F(null),[Mi,an]=F(null),[$e,gt]=F(null),[we,Ot]=F(null),[Ui,br]=F([]),wt=ee([]),ln=ee(!1),je=ee(null),[zn,oe]=F(null),[Wi,Fi]=F(null),Kn=ee(!1),cn=ee(null),dn=ee(null),[xe,yt]=F(null),[Xn,un]=F(null),vr=!!(qe||me||ve||Xe||Be||$e||we||xe||Xn),[Hi,Lt]=F(0),[qi,Mt]=F(0),[Hd,Bi]=F(0),$r=$i(()=>{try{let c=ji(e);return c.source==="auto"?`${c.model} (auto)`:c.model}catch{return null}},[e,Hd]),{stdout:Oe}=vg(),[,qd]=F(0),Vi=ee(`${Oe.columns??80}x${Oe.rows??24}`),Qe=z(()=>Math.max(20,(Oe.columns??80)-1),[Oe]),d=z(c=>{Dt.current.push(c),console.log(Jr(c,Qe()))},[Qe]),ge=z((c,a)=>{Hn.current++,Se(c),Wn(a??null)},[]),Le=z(()=>{Hn.current++,Se(null),Wn(null)},[]),Q=z(c=>ge(c,Yo({kind:"cmd",cmd:c,reason:""})),[ge]),Qn=z((c,a)=>{!a?.silent&&c.note&&d({kind:"note",tone:c.tone,text:c.note}),c.picker&&(ct(c.picker.options.map(i=>({cmd:i.cmd,desc:i.desc}))),an(c.picker.title)),c.lead&&ge(c.lead.kind==="cmd"?c.lead.cmd:c.lead.text,Yo(c.lead))},[d,ge]),Ut=z((c,a,i="info")=>{c&&d({kind:"note",tone:i,text:c}),a&&ge(a.kind==="cmd"?a.cmd:a.text,Yo(a))},[d,ge]),[pn,xr]=F(null),[Bd,Gi]=F(!1),Wt=z(c=>{xr(c),Gi(!1),d({kind:"note",tone:"info",text:"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[d]),Cr=ee(!1),Rr=z(async()=>{try{if(Cr.current||!ew(Zg())||te(e)?.mode==="engineer")return;let c=await Jg({pkg:xt,currentVersion:o,force:!0});if(!c.updateAvailable||!c.latest)return;Cr.current=!0,d({kind:"note",tone:"info",text:`\u2B06 Updating ${xt} ${c.current} \u2192 ${c.latest}\u2026 (wait for the \u2713 before you /exit)`}),Bn(!0),(await qo().finally(()=>Bn(!1))).ok?(d({kind:"note",tone:"ok",text:`\u2713 Updated to v${c.latest} \u2014 run /exit, then relaunch to apply.`}),Q("/exit"),_i(c.latest)):d({kind:"note",tone:"warn",text:`Update available (v${c.latest}) but auto-update failed \u2014 run: ${Ho}`})}catch{}},[e,o,d,Q]),Jn=z(c=>{let a=Ne(e,s);return a.ok?!0:(d({kind:"note",tone:"warn",text:a.reason}),dn.current=c,Q("/login"),!1)},[e,s,d,Q]),[Zn,Pr]=F(null),kt=z(c=>{let a=Ln(e,s,{claudeMissing:Di(t).state==="missing",allowAutoAudit:c,genreUnknown:mr.current});return a?On(a):{kind:"idle"}},[e,s,t]),fn=ee(!0),Ft=ee(!1),eo=ee(0),hn=ee(0);Te(()=>{let c=setInterval(()=>{if(fn.current){eo.current=0,hn.current=0;return}if(!N)try{if(!tn(kd(e)))return;if(Ee(e).status==="current"){fn.current=!0,eo.current=0,hn.current=0;let i=kt(!1),h=i.kind==="recommend"?i.rec:null,u=Ft.current?`\u2713 Your builder finished the protocol update (v${ae}) \u2014 the dev\u2194docs hand-off is current again.`:"\u2713 Your builder finished the hand-off \u2014 the architecture brief is in. I can read this repo now and write accurate docs.";d({kind:"note",tone:"ok",text:`${u}${h?.lead?` ${_n(h.lead)}`:""}`}),xr(null),h&&(h.lead||h.picker)?Qn(h,{silent:!0}):Ft.current||ge("write the docs for this repo"),Y(y=>y+1);return}if(Ft.current)return;eo.current+=1;let a=eo.current;if((a===4||a%15===0)&&hn.current<3){hn.current+=1;let i=hn.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";d({kind:"note",tone:"info",text:Ge(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${i}`:`\u23F3 Waiting for your builder to run the prompt \u2014 paste it into your coding agent; I'll pick up automatically when it's done.${i}`})}}catch{}},4e3);return()=>clearInterval(c)},[e,N,d,kt,Qn,ge]),Te(()=>{let c=Li??Un(e);if(!N){nr(0),en(`${rr} ${c}`);return}nr(3);let a=0;en(`${or[0]} ${c}`);let i=setInterval(()=>{a=(a+1)%or.length,en(`${or[a]} ${c}`)},400);return()=>clearInterval(i)},[N,e,Li]),Te(()=>()=>nr(0),[]),Te(()=>{let c=performance.now(),a=[],i=(w,$)=>{let x=performance.now();try{return $()}finally{let G=Math.round(performance.now()-x);G>=80&&a.push(`${w}: ${G}ms`)}};d({kind:"banner",info:i("banner",()=>cw(e,o,t,s))});let h=Di(t).state==="missing";if(h&&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.
|
|
376
|
+
${Cg}
|
|
377
377
|
Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!te(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:
|
|
378
|
-
${
|
|
379
|
-
`)}),
|
|
380
|
-
`)})}catch{}let y=i("ready-decision",()=>
|
|
378
|
+
${Pd}`}),Q(h?"/doctor":"/init");return}h&&Q("/doctor");try{let w=Pe(e,s),$=Rt(w.name);$&&at($)&&$.refreshToken?Sg({profile:w.name,connection:w.connection}).then(()=>{d({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),Y(x=>x+1)}).catch(()=>{d({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 sign in again with /login."}),Q("/login")}):(!$||at($))&&(d({kind:"note",tone:"warn",text:`Profile "${w.name}" is not signed in \u2014 sign in with /login.`}),Q("/login"))}catch{}try{let w=te(e),$=Pe(e,s),x=Rt($.name);w&&x&&!at(x)&&ui(e,w.authoritativeSourceFiles)&&!pi(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."}),Q("/scope"))}catch{}try{let w=i("resolve-genre",()=>Wg(e));w.persisted&&w.appType?d({kind:"note",tone:"ok",text:`\u2713 Detected a ${w.appType} app \u2014 enabled the ${w.appType}-doc-playbook (change with /genre, or edit .d360-writer/config.json).`}):w.source==="unknown"&&te(e)&&(mr.current=!0)}catch{}let u=Ee(e);try{if(i("reconcile-devhints",()=>vo(e)),u.status!=="current"&&!Ge(e)){let w=$o(e);w.length&&(d({kind:"note",tone:"warn",text:w.join(`
|
|
379
|
+
`)}),Wt(bt()),fn.current=!1,Ft.current=!1)}}catch{}try{let w=i("reconcile-feedback",()=>tw(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{}try{let w=i("upgrade-actions",()=>nw(e));w.applied.length>0&&d({kind:"note",tone:"warn",text:Ko(w.applied).join(`
|
|
380
|
+
`)})}catch{}let y=i("ready-decision",()=>kt(!0));y.kind==="autoAudit"?(d({kind:"note",tone:"info",text:y.note}),Tn().then(w=>{w.kind==="forward-to-agent"&&w.prompt&&re(w.prompt,{display:w.display,quietUser:!0})})):y.kind==="recommend"&&Qn(y.rec);let b=Math.round(performance.now()-c);b>=800&&rw({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${b}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${a.length?a.join(`
|
|
381
381
|
`):"no single phase \u226580ms"}
|
|
382
|
-
cwd: ${e}`}),
|
|
383
|
-
`)});let H=
|
|
384
|
-
`)}),
|
|
385
|
-
`)}),
|
|
386
|
-
${
|
|
387
|
-
`)});return}case"mcp":await
|
|
382
|
+
cwd: ${e}`}),Rr()},[]),Te(()=>{let c=setInterval(()=>{Rr()},yw);return()=>clearInterval(c)},[Rr]),Te(()=>{if(N||ue||gr||Fn.current||he!==null||lt.length>0||T!==""||pn!==null||le.current.length>0||Yn.current||vr)return;let c=kt(!1);c.kind==="recommend"&&(c.rec.lead||c.rec.picker)&&Qn(c.rec,{silent:!0})},[N,ue,he,lt,T,pn,vr,V,kt,gr]),Te(()=>{let c=null,a=null,i=()=>{c&&clearTimeout(c),c=setTimeout(()=>{c=null;let h=`${Oe.columns??80}x${Oe.rows??24}`;h!==Vi.current&&(Vi.current=h,qd(u=>u+1),a&&clearTimeout(a),a=setTimeout(()=>{a=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+Xa(Dt.current,Qe())+"\x1B[?2026l")},80))},400)};return Oe.on("resize",i),()=>{c&&clearTimeout(c),a&&clearTimeout(a),Oe.off("resize",i)}},[Oe,Qe]);let Me=Math.max(20,(Oe.columns??80)-1),Yi=$i(()=>dw(e,s),[e,s,V]),Tr=(()=>{if(Ud)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(wr!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${wr?` v${wr}`:""}\u2026`,isSetup:!0};if(Zn)return{text:"\u{1F6E0} press c to copy the d360-writer feedback \u2014 then send it to the team (Teams / Slack / email)\u2026",isSetup:!0};if(pn)return Bd?{text:"\u2713 copied \u2014 paste it into your coding agent \xB7 I\u2019ll pick up automatically when it finishes\u2026",isSetup:!0}:{text:"\u2328 press c to copy the prompt above \u2014 then paste it into your coding agent\u2026",isSetup:!0};if(le.current.length>0)return le.current[0].mode==="conflict"?{text:"l keep local \xB7 p take portal \xB7 s skip \xB7 anything else cancels\u2026",isSetup:!0}:{text:"y to write \xB7 n to skip \xB7 anything else cancels\u2026",isSetup:!0};let c=te(e);if(!c)return{text:"Run /init to set up this repo (or /help)\u2026",isSetup:!0};let a=xi(e,(c.docsDir??jd).replace(/\/+$/,"")),i=(()=>{try{return tn(a)&&$g(a).length>0}catch{return!1}})();try{let h=Pe(e,s),u=Rt(h.name);if(!(!!u&&!(at(u)&&!u.refreshToken)))return{text:`Sign in with /login (profile "${h.name}")\u2026`,isSetup:!0};if(!h.project.projectId)return{text:"Sign in to Document360 to pick your project\u2026",isSetup:!0};if(!h.project.workspaceId&&!i)return{text:"Pick a workspace with /workspace\u2026",isSetup:!0}}catch{}return i?{text:uw,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),mn=Vc(T),zi=mn.length>0&&!N,Sr=p!==null?ld(p,8,Me):null,to=$e?$e.paths.filter(c=>!$e.query||c.toLowerCase().includes($e.query.toLowerCase())).slice(0,8):[],no=xe?xe.sessions.filter(c=>{let a=xe.query.toLowerCase();return!a||c.name.toLowerCase().includes(a)||c.firstPrompt.toLowerCase().includes(a)}).slice(0,8):[],Ce=z((c,a)=>{De.current?.close(),De.current=ud({cwd:e,resume:c,profileName:a??s,allowProdWrites:jt.current}),c||(Fe.current={uuid:null,firstPrompt:null,titleFired:!1},ut(null)),Lt(0),Mt(0)},[e,s]),Ki=z((c,a,i)=>{if(pw.test(c))try{let h=Pe(e,s),u=typeof a.project_id=="string"&&a.project_id||h.project.projectId,y=Zo(a,i),b=[],w=er(i);c.endsWith("publish_article")&&w&&b.push(`Live: ${w}`);let $=tr(i);$?b.push(`Preview: ${$}`):y&&u&&b.push(`Preview: ${Jo(h.connection.portalUrl,u,y,h.project.languageCode??"en")}`),b.length>0&&d({kind:"link",lines:b})}catch{}},[e,s,d]),re=z(async(c,a)=>{qn(!0),Fn.current=!1,Le(),ct([]),an(null),xr(null);let i=Hn.current;a?.quietUser||d({kind:"user",text:a?.echoDisplay&&a.display?a.display:c});let h=Fe.current;h.firstPrompt||(h.firstPrompt=a?.display??c),dt.current=Date.now(),Pt(0),S(!0),Gn.current.clear();let u="",y=!1,b=!1,w="",$={num:0,closed:!1,cueSeen:!1},x=null,G=()=>{x||(x=setTimeout(()=>{x=null,m(w.length>0?w:null)},60))},H=()=>{x&&clearTimeout(x),x=null,m(null)},I=(C=!1)=>{let{head:A,keep:U}=cd(w,C);A.trim()&&d({kind:"assistant",text:yi(A.trimEnd(),$)}),w=U,H()};try{for await(let C of De.current.send(c))if(C.type==="session"){if(!h.uuid){h.uuid=C.sessionId;let A=new Date().toISOString(),U=kr.current,J=U??Ig(h.firstPrompt??"session");_g({uuid:C.sessionId,name:J,renamed:!!U,titled:!1,cwd:e,firstPrompt:h.firstPrompt??"",createdAt:A,updatedAt:A}),ut(J),kr.current=null}}else if(C.type==="text"){w+=C.delta,u+=C.delta;let A=dd(w);if(A>0){let U=w.slice(0,A).trimEnd();U&&d({kind:"assistant",text:yi(U,$)}),w=w.slice(A)}G(),Pt(U=>U+C.delta.length)}else if(C.type==="tool"){y=!0;let A=Xo(C.name,C.input);A&&(I(),d({kind:"tool",title:A.title,sep:A.sep,arg:A.arg}),Gn.current.set(C.id,{name:C.name,input:C.input}))}else if(C.type==="article_diff"){let A=Ye(C.oldContent,C.newContent,Qe());A&&(I(),d({kind:"diff",added:A.added,removed:A.removed,lines:A.lines,hidden:A.hidden}))}else if(C.type==="tool_result"){C.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(C.output)&&(Kn.current=!0);let A=Gn.current.get(C.id);if(A){Gn.current.delete(C.id),I();let U=Qo(C.output,4,C.isError?void 0:A.name,A.input);d({kind:"tool-result",lines:U.lines,hidden:U.hidden,isError:C.isError}),C.isError||Ki(A.name,A.input,C.output)}}else if(C.type==="result"){I(!0),Lt(U=>U+C.outputTokens),Mt(U=>U+C.costUsd);let A=C.inputTokens+C.cacheReadTokens+C.cacheCreationTokens;if(d({kind:"done",seconds:Math.round((Date.now()-dt.current)/1e3),tokens:C.outputTokens,costUsd:C.costUsd,ok:C.ok,...A>0?{inTokens:A,cachedPct:Math.round(C.cacheReadTokens/A*100)}:{}}),!b&&!y&&!u.trim()&&!ln.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)."}),C.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(u))try{let U=bd(e);if(tn(U)){let J=dr(U,"utf8").trim();J&&(Pr(J),d({kind:"note",tone:"info",text:"\u{1F6E0} Press c to copy this feedback \u2014 send it to the d360-writer team (Teams / Slack / email)."}))}}catch{}if(C.ok&&$.cueSeen)Ii(!0),ct([]);else{let U=C.ok?Kc(u,sr.map(J=>J.name)):[];if(U.length>0)Q(U[0]);else if(C.ok&&u.trim()){let J=kt(!1);J.kind==="recommend"&&(J.rec.lead||J.rec.picker)||Ug(c,u,e).then(ye=>{ye&&Hn.current===i&&ge(ye)}).catch(()=>{})}}if(h.uuid&&(Ci(h.uuid),!h.titleFired)){h.titleFired=!0;let U=h.uuid,J=h.firstPrompt;J&&pd(J,e).then(ye=>{ye&&(Ng(U,ye),ut(ye))}).catch(()=>{})}}else C.type==="error"&&(I(!0),b=!0,C.kind==="auth"&&(Kn.current=!0),d({kind:"note",text:`agent error: ${C.message}`,tone:"error"}))}finally{S(!1),H(),Y(C=>C+1),Fe.current.uuid&&Fc(e,Fe.current.uuid,Dt.current),Kn.current?(Kn.current=!1,cn.current=a?.display??c,ge("/login","\u21E5 tab to run /login \u2014 then I\u2019ll re-send your last prompt\u2026")):cn.current=null,ln.current&&(ln.current=!1,wt.current.length>0&&(d({kind:"note",tone:"info",text:`(${wt.current.length} queued message(s) discarded)`}),wt.current=[],br([])),d({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,d,Ki,Qe,ge,Q,Le,kt]),Ht=z(async c=>{let a=pr(e,"standard");dt.current=Date.now(),Pt(0),S(!0);let i=new AbortController;je.current=i;let h=async(u,y)=>{let b=Pi(u);oe({verb:"Publishing",total:b.length,done:0,active:[],rows:Mn(b),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:y?`Resolving cross-links in ${u.length} article${u.length===1?"":"s"} whose targets published this run (second pass)\u2026 (esc to stop)`:`Publishing ${u.length} article${u.length===1?"":"s"} across ${b.length} partition${b.length===1?"":"s"} (\u2264${Pn} agents at once) on ${a.model}\u2026 (esc to stop)`});let w=!1;for await(let $ of ur({cwd:e,partitions:b,promptFor:x=>Ao(x.paths),concurrency:Pn,profileName:s,allowProdWrites:jt.current,model:a.model,signal:i.signal}))if($.type==="partition_status")$.status==="running"?oe(x=>x&&{...x,active:[...x.active,$.label],rows:ze(x.rows,$.label,"active"),lastAt:Date.now()}):oe(x=>x&&{...x,active:x.active.filter(G=>G!==$.label),done:x.done+1,rows:ze(x.rows,$.label,$.status==="done"?"done":"failed"),lastAt:Date.now()});else if($.type==="partition_event")oe(x=>{if(!x)return x;let G={...x,lastAt:Date.now()};return $.event.type==="tool"?G.tools=x.tools+1:$.event.type==="text"&&(G.chars=x.chars+$.event.delta.length),G});else if($.type==="run_done"){w=$.aborted,Mt(I=>I+$.totalCostUsd),Lt(I=>I+$.results.reduce((C,A)=>C+A.outputTokens,0));let x=$.aborted?"Stopped. ":"",G=t.kind==="api"?"api":"subscription";d({kind:"note",tone:$.aborted?"warn":$.ok?"ok":"warn",text:x+ns($.results,b,G).join(`
|
|
383
|
+
`)});let H=ts(e,s);if(H&&d({kind:"note",tone:"info",text:H}),!$.aborted){try{let I=await $d({cwd:e,profileName:s}),C=xd(I);C?d({kind:"note",tone:"info",text:C}):I.skipped&&d({kind:"note",tone:"warn",text:`Order sync skipped: ${I.skipped}`})}catch(I){d({kind:"note",tone:"warn",text:`Order sync failed: ${I.message}`})}try{let I=Rd(await Cd({cwd:e,profileName:s}));I&&d({kind:"note",tone:"info",text:I})}catch(I){d({kind:"note",tone:"warn",text:`Related-articles sync failed: ${I.message}`})}}}return w};try{if(!await h(c,!1)){let y=await os(e,s,c);y.length>0&&await h(y,!0)}}catch(u){d({kind:"note",tone:"error",text:`Publish run failed: ${u.message}`})}finally{je.current=null,oe(null),S(!1),Y(u=>u+1)}},[e,s,d,t]),Dr=z(async c=>{await re(Zr(c),{display:`/publish ${c}`,quietUser:!0});try{let a=await Eo(e,s,c.replace(/\\/g,"/"));a.length>0&&(an(`Related articles not yet published (${a.length}):`),ct([`/publish --related ${c}`,...a.map(i=>`/publish ${i}`)]))}catch{}},[e,s,re]),jr=z(c=>{let a=Rt(c);if(!a||at(a)&&!a.refreshToken)return null;let i={...on(a.idToken)??{},...on(a.accessToken)??{}};return i.email??i.preferred_username??"signed in"},[]),Ar=z((c,a)=>{if(a){let i=te(e);i&&(i.defaultProfile=c,fd(i,e))}l(c),Ce(void 0,c),d({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${c}"${a?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),jr(c)||(d({kind:"note",tone:"warn",text:`Profile "${c}" is not signed in \u2014 sign in with /login.`}),Q("/login")),Y(i=>i+1)},[e,d,Ce,jr,Q]),oo=z((c,a,i)=>{uo(e,c,a,i.id,i.name),d({kind:"note",tone:"ok",text:`Switched to workspace "${i.name??i.id}" (agent restarted).`}),Ce(),hd(e,c)||(d({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),d({kind:"note",tone:"warn",text:"\u26A0 Before I write the docs, hand the prompt below to your builder (your repo's coding agent). It gives me the architecture brief that makes the docs accurate:"}),d({kind:"note",tone:"info",text:Xt(Kt(e)).join(`
|
|
384
|
+
`)}),Wt(bt()),fn.current=Ee(e).status==="current",Ft.current=Ge(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,Ce,Wt]),ro=z(async c=>{let a;try{a=await kn(e,c)}catch{d({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),Q("/workspace");return}if(a.workspaces.length===0){d({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let i=a.workspaces.filter(u=>(u.workspace_type??"").toLowerCase()!=="apidocumentation"),h=i.length>0?i:a.workspaces;if(h.length===1){let u=h[0],y=a.workspaces.length-h.length;d({kind:"note",tone:"ok",text:`Selected the "${u.name??u.id}" workspace${y>0?" (skipped the API-documentation workspace)":""}.`}),oo(a.profile,a.projectId,u);return}d({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${h.length} available).`}),Q("/workspace")},[e,d,oo,Q]),so=z((c,a)=>{po(e,c,a.id,a.name),d({kind:"note",tone:"ok",text:`Project set to "${a.name??a.id}" (agent restarted).`}),Ce(),ro(c)},[e,d,Ce,ro]),Xi=z(async c=>{let a;try{a=Pe(e,c)}catch{return}if(!a.project.workspaceId){if(a.project.projectId){if(!a.project.projectName)try{let{projects:i}=await et(e,a.name),h=i.find(u=>u.id===a.project.projectId);h?.name&&ow(e,a.name,{projectName:h.name})}catch{}await ro(a.name);return}try{let{projects:i}=await et(e,a.name);if(i.length===1){let h=i[0];d({kind:"note",tone:"ok",text:`Using your Document360 project "${h.name??h.id}".`}),so(a.name,{id:h.id,name:h.name});return}if(i.length>1){let h=i.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?"}),ht({cursor:0,current:-1,rows:h,profile:a.name,environment:a.connection.name});return}}catch{}d({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),Q("/project")}},[e,d,ro,so,Q]),qt=z(()=>{let c=le.current[0];if(!c)return;Le();let{plan:a,mode:i}=c;d({kind:"note",tone:"info",text:`\u25CF ${a.title} (${a.path})`});for(let u of a.notes)d({kind:"note",tone:"warn",text:`\u26A0 ${u}`});a.overwritesLocalChanges&&i==="pull"&&d({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let h=Ye(a.oldContent,a.newContent,Qe());d(h?{kind:"diff",added:h.added,removed:h.removed,lines:h.lines,hidden:h.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."}),i==="conflict"?(d({kind:"note",tone:"warn",text:"Conflict \u2014 edited both here and on the portal (diff shows local \u2192 portal)."}),d({kind:"note",tone:"info",text:"Keep local (publish, overwrites portal) \xB7 take Portal (overwrites local) \xB7 Skip? (l/p/s \u2014 anything else cancels)"})):d({kind:"note",tone:"info",text:`Write ${a.path}? (y/n \u2014 anything else cancels)`})},[d,Qe,Le]),Er=z(()=>{if(le.current.length>0){qt();return}let c=At.current;At.current=[],c.length>0?(d({kind:"note",tone:"info",text:`Publishing ${c.length} kept-local article${c.length===1?"":"s"} over the portal\u2026`}),Ht(c)):Q("/pull")},[qt,d,Ht,Q]),Qi=z(c=>{if(le.current.length===0)return!1;let a=c.trim().toLowerCase(),i=le.current[0];if(i.mode==="conflict"){if(a==="l"||a==="local")le.current.shift(),At.current.push(i.plan.path),d({kind:"note",tone:"info",text:`Keeping local ${i.plan.path} \u2014 will publish over the portal.`});else if(a==="p"||a==="portal"){le.current.shift();try{md({cwd:e,profileName:s},i.plan),d({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${i.plan.path} (local overwritten, sync base advanced).`})}catch(h){d({kind:"note",tone:"error",text:`Take-portal failed: ${h.message}`})}}else if(a==="s"||a==="skip"||a==="n")le.current.shift(),d({kind:"note",tone:"info",text:`Skipped ${i.plan.path} \u2014 still a conflict.`});else{let h=le.current.length;return le.current=[],At.current=[],d({kind:"note",tone:"info",text:`Resolve cancelled (${h} conflict${h===1?"":"s"} left untouched).`}),!0}return Er(),!0}if(a==="y"||a==="yes"){let h=le.current.shift().plan;try{md({cwd:e,profileName:s},h),d({kind:"note",tone:"ok",text:`\u2713 Pulled ${h.path} (sync base advanced).`})}catch(u){d({kind:"note",tone:"error",text:`Pull failed: ${u.message}`})}}else if(a==="n"||a==="no"){let h=le.current.shift().plan;d({kind:"note",tone:"info",text:`Skipped ${h.path}.`})}else{let h=le.current.length;return le.current=[],d({kind:"note",tone:"info",text:`Pull cancelled (${h} article(s) left untouched).`}),!0}return Er(),!0},[e,s,Er,d]),Nr=z(async c=>{d({kind:"note",tone:"info",text:"Checking Document360 for conflicts\u2026"});try{let a=await Ri({cwd:e,profileName:s}),i=c?.replace(/\\/g,"/"),h=a.entries.filter(y=>y.status==="conflict"&&y.path).map(y=>y.path);if(i){if(!h.includes(i)){d({kind:"note",tone:"ok",text:`${i} isn\u2019t in conflict \u2014 nothing to resolve.`});return}h=[i]}if(h.length===0){d({kind:"note",tone:"ok",text:"\u2713 No conflicts \u2014 local and Document360 agree on every tracked article."});return}let u=[];for(let y of h)try{u.push({plan:await wd({cwd:e,profileName:s,relPath:y}),mode:"conflict"})}catch(b){d({kind:"note",tone:"error",text:`Could not load ${y} from Document360: ${b.message}`})}if(u.length===0)return;d({kind:"note",tone:"info",text:`Resolving ${u.length} conflict${u.length===1?"":"s"} \u2014 for each: keep local, take portal, or skip.`}),le.current=u,At.current=[],qt()}catch(a){d({kind:"note",tone:"error",text:`Could not compute sync status: ${a.message}`})}},[e,s,d,qt]),Ji=z(c=>{let a=Yn.current;if(!a)return!1;if(Yn.current=null,Le(),c.trim()!==a.repoName)return d({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:i,failed:h}=Zs(e,a.targets);d({kind:"note",tone:h.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${i.length} item${i.length===1?"":"s"}. The repo is back to its original state.`});for(let u of h)d({kind:"note",tone:"error",text:` \u2717 ${u.path}: ${u.error}`});return a.hadDevhints&&(d({kind:"note",tone:"warn",text:xo().join(`
|
|
385
|
+
`)}),Wt(Hr())),d({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
|
|
386
|
+
${Pd}`}),Q("/init"),qn(!1),!0},[e,d,Wt,Le,Q]),gn=z(async c=>{let a=c.slice(1).trim().split(/\s+/),i=(a[0]??"").toLowerCase(),h=a.slice(1);if(qn(!0),Oo(h)&&["write","check","review","reorder"].includes(i)){let u=Sn(e,s);if(u.length===0){d({kind:"note",tone:"warn",text:"No categories yet \u2014 author some articles first, then scope to one."});return}let y=b=>i==="write"?`/write ${vl(h,b).join(" ")}`.trim():`/${i} ${[b,...h.filter(w=>w!=="--scope")].join(" ")}`.trim();if(u.length===1){gn(y(u[0].token));return}mt({cursor:0,rows:u,run:b=>{gn(y(b))}});return}if(st(i,h)){let u=Sn(e,s);if(u.length>1){let y=h.filter(x=>x.startsWith("--")).join(" "),b=x=>`/${i}${x?` ${i==="write"?`--scope ${x}`:x}`:""}${y?` ${y}`:""} ${x?"":"--all"}`.replace(/\s+/g," ").trim(),w=u.reduce((x,G)=>x+G.count,0),$={token:"",label:i==="review"?`Everything \u2014 all ${w} articles + structure (IA) review`:i==="reorder"?`Everything \u2014 reorder all ${u.length} categories`:`Everything \u2014 rewrite all ${w} planned articles`,count:w};mt({cursor:0,rows:[$,...u],run:x=>{gn(b(x))}});return}}switch(i){case"help":un({tab:0});return;case"exit":case"quit":De.current?.close(),r();return;case"clear":Ce(),Dt.current=[],qn(!1),Le(),console.log("\x1B[?2026h\x1B[H\x1B[2J\x1B[3J\x1B[?2026l"),d({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let u;try{u=Pe(e,s)}catch(y){d({kind:"note",tone:"error",text:y.message});return}d({kind:"note",tone:"info",text:`Profile "${u.name}" \u2192 ${u.connection.name} (${u.connection.apiUrl})${u.production?" \u26A0 PRODUCTION":""}`}),B(!0);try{let y=await Rg(u.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},w=>d({kind:"note",tone:"info",text:w})),b=Pg(u.name,y);if(Tg(b),await Lr(b,u.name,w=>d({kind:"note",tone:"info",text:w})),d({kind:"note",tone:"ok",text:`\u2713 Logged in to "${u.name}" as ${mo(b)}`}),await Xi(s),dn.current){let w=dn.current;dn.current=null;let $=Ne(e,s);$.ok?(d({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 tab to run ${w}.`}),Q(w)):(d({kind:"note",tone:"warn",text:`${$.reason} (then ${w}.)`}),Q("/login"),dn.current=w)}else cn.current&&(ge(cn.current,"\u21E5 tab to re-send your last prompt\u2026"),cn.current=null)}catch(y){d({kind:"note",tone:"error",text:`Login failed: ${y.message}`})}finally{B(!1),Y(y=>y+1)}return}case"allow-prod":{let u=!1;try{u=Pe(e,s).production}catch{}if(!u){d({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}jt.current=!0,Ce(),d({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let u=_s(h.join(" ")),y=Fe.current.uuid;if(!y){if(!u){d({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}kr.current=u,ut(u),en(`${rr} ${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 b=Fe.current.firstPrompt??"";pd(b,e).then(w=>{w?(ge(`/rename ${w}`),d({kind:"note",tone:"info",text:`Suggestion: "${w}" \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}Mg(y,u),ut(u),en(`${rr} ${u}`),d({kind:"note",tone:"ok",text:`Session renamed to "${u}".`});return}case"profile":{let u=h[0],y=te(e);if(!u){let b=Object.entries(y?.profiles??{});if(b.length===0){d({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let w=b.map(([G,H])=>({name:G,env:H.connection?.environment??"custom",prod:H.production===!0,who:jr(G)})),$=s??y?.defaultProfile,x=Math.max(0,w.findIndex(G=>G.name===$));Et({cursor:x,current:x,rows:w});return}if(u==="add"){let b=Os(e,h[1],h[2]);if(b){d({kind:"note",tone:"error",text:b});return}d({kind:"note",tone:"ok",text:`\u2713 Profile "${h[1]}" created (environment: ${h[2]??h[1]}).`}),Ar(h[1],!1);return}if(!y?.profiles?.[u]){d({kind:"note",tone:"error",text:`Unknown profile "${u}". Create it: /profile add ${u} <environment>`});return}Ar(u,!0);return}case"doctor":await jn(h,{cwd:e,version:o});return;case"genre":{await Go(h,{cwd:e});try{mr.current=!(te(e)?.appType??Fg(e))}catch{}Y(u=>u+1);return}case"roadmap":{if(h[0]?.toLowerCase()==="done"){let u=ii(e,h.slice(1).join(" ").trim());d({kind:"note",tone:u.ok?"ok":"warn",text:u.line}),Y(y=>y+1);return}d({kind:"note",tone:"info",text:si(e).join(`
|
|
387
|
+
`)});return}case"mcp":await Po(h);return;case"init":{if(te(e)){d({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer/config.json directly (or d360-writer init for the CLI wizard)."});return}let u=Gg().map(y=>({name:y,apiUrl:Yg(y).apiUrl}));Nt({cursor:0,rows:u});return}case"resume":{let u=h.join(" ").trim(),y=Lg(e).filter($=>$.uuid!==Fe.current.uuid);if(!u){if(!y.length){d({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}yt({query:"",cursor:0,sessions:y});return}let b=Og(e,u);if(!b){d({kind:"note",tone:"error",text:`No session matches "${u}".`});return}Ce(b.uuid),Fe.current={uuid:b.uuid,firstPrompt:b.firstPrompt,titleFired:!0},ut(b.name),Ci(b.uuid),Dt.current=[];let w=ki(e,b.uuid);for(let $ of w)d($);d({kind:"note",tone:"ok",text:w.length?`Resumed "${b.name}" \u2014 restored ${w.length} message(s); continue where you left off.`:`Resumed "${b.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let u=h.join(" ").trim(),y;try{y=await kn(e,s)}catch(w){d({kind:"note",tone:"error",text:`Could not list workspaces: ${w.message}`});return}if(!u){let w=y.workspaces.map(x=>({id:x.id,name:x.name??x.id,type:x.workspace_type}));if(w.length===0){d({kind:"note",tone:"info",text:"No workspaces in this project."});return}let $=Math.max(0,w.findIndex(x=>x.id===y.current));It({cursor:$,current:$,rows:w,profile:y.profile,projectId:y.projectId,projectName:y.projectName,environment:y.environment});return}let b=_r(y.workspaces,u);if(!b){d({kind:"note",tone:"error",text:`No workspace matches "${u}".`});return}oo(y.profile,y.projectId,b);return}case"project":{let u=h.join(" ").trim(),y;try{y=await et(e,s)}catch(w){d({kind:"note",tone:"error",text:`Could not list projects: ${w.message} (signed in? try /login)`});return}if(!u){let w=y.projects.map(x=>({id:x.id,name:x.name??x.id,sub:x.sub_domain}));if(w.length===0){d({kind:"note",tone:"info",text:"No projects found for this identity."});return}let $=w.findIndex(x=>x.id===y.current);ht({cursor:Math.max(0,$),current:$,rows:w,profile:y.profile,environment:y.environment});return}let b=Or(y.projects,u);if(!b){d({kind:"note",tone:"error",text:`No project matches "${u}". Available: ${y.projects.map(w=>w.name??w.id).join(", ")}`});return}so(y.profile,b);return}case"logout":{let u;try{u=Pe(e,s).name}catch(b){d({kind:"note",tone:"error",text:b.message});return}let y=Ag(u);Eg(e,u),Ce(),Y(b=>b+1),d({kind:"note",tone:y?"ok":"info",text:y?`\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."}),Q("/login");return}case"publish":{if(!Jn(c.trim()))return;if(h[0]==="--related"&&h[1]){let w=await Eo(e,s,h[1].replace(/\\/g,"/"));if(w.length===0){d({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await Ht(w);return}let u=h.filter(w=>!w.startsWith("--"));if(u[0]){await Dr(u[0]);return}let y=h.includes("--all"),b=h.includes("--force");d({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let w=await Ri({cwd:e,profileName:s}),{clean:$,conflicts:x}=So(w.entries),G=y&&b&&x.length>0,H=jo(w.entries);if(H>0&&d({kind:"note",tone:"warn",text:`\u26A0 ${H} article${H===1?"":"s"} already exist on Document360 but aren\u2019t linked \u2014 left OUT of publish (publishing would duplicate them). Run /catch-up (or ask me to link them) first.`}),x.length>0&&!G&&d({kind:"note",tone:"warn",text:Do(x.length)}),$.length===0&&!G){if(x.length>0){Q("/resolve");return}d({kind:"note",tone:"ok",text:H>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let I=w.counts["unknown-base"]??0;I>0&&d({kind:"note",tone:"info",text:`(${I} article(s) have no sync base yet \u2014 publish those by path if needed.)`}),Fi("Reconciling structure on Document360 (order + related articles)\u2026");try{let C=await $d({cwd:e,profileName:s}),A=Rd(await Cd({cwd:e,profileName:s})),U=xd(C);U?d({kind:"note",tone:"info",text:U}):C.skipped&&d({kind:"note",tone:"warn",text:`Order sync skipped: ${C.skipped}`}),A&&d({kind:"note",tone:"info",text:A}),d({kind:"note",tone:"ok",text:U||A?"\u2713 Structure synced to Document360 \u2014 /structure shows the new category + article order.":"\u2713 Already in order \u2014 nothing to change."}),(U||A)&&Q("/structure")}catch(C){d({kind:"note",tone:"warn",text:`Structure sync failed: ${C.message}`})}finally{Fi(null)}return}if(y){let I=(G?[...$,...x]:$).map(C=>C.path);await Ht(I),x.length>0&&!G&&Q("/resolve");return}_t({cursor:0,rows:ol($,x)})}catch(w){d({kind:"note",tone:"error",text:`Could not compute sync status: ${w.message}`}),d({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"resolve":{if(!Jn(c.trim()))return;await Nr(h.find(u=>!u.startsWith("--")));return}case"preview":{let u=h.join(" ").trim();if(!u){let b=[];try{b=Object.keys(hd(e,Pe(e,s).name)?.articles??{})}catch{}if(b.length===0){d({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}gt({query:"",cursor:0,paths:b});return}let y=xg(u)?u:xi(e,u);if(tn(y)){try{d({kind:"preview",name:Un(y),text:Sd(dr(y,"utf8"))})}catch(b){d({kind:"note",tone:"error",text:`Could not read ${y}: ${b.message}`})}return}if(fw.test(u)){try{let b=Pe(e,s),w={profile:b.name,connection:b.connection},$=b.project.projectId??Dg(w),x=await jg(w,$,u);d({kind:"preview",name:x.title??u,text:x.content??"*(article has no content)*"})}catch(b){d({kind:"note",tone:"error",text:`Could not fetch article: ${b.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=h[0]?.trim();if(!u){let $=Mo(ji(e));ft({cursor:$,current:$});return}let{lines:y,changed:b,effective:w}=Dn(e,u);for(let $ of y)d({kind:"note",tone:$.startsWith("\u26A0")?"warn":$.startsWith("\u2713")?"ok":"info",text:$});b&&(Bi($=>$+1),De.current?.setModel(w));return}case"convert":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:u,run:y}=ps(h),b=Xg(e,s);if(b.length===0){d({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let w=fs(b,u);if(w.length===0){d({kind:"note",tone:"error",text:`No tracked articles under "${u}". (${b.length} are tracked overall.)`});return}let $=Pi(w),x=3,G=`/convert${u?` --scope ${u}`:""} --run`,H=pr(e,"light");if(!y){let C=yd({files:hs(e,w),op:"convert",model:H.model}),A=u?`Scope: ${u} (${w.length} of ${b.length} tracked)
|
|
388
388
|
`:"",U=`
|
|
389
|
-
Model: ${H.model}${H.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;d({kind:"note",tone:"info",text:A+
|
|
390
|
-
`)+U}),Q(G);return}
|
|
391
|
-
`)})}}catch(C){d({kind:"note",tone:"error",text:`Convert run failed: ${C.message}`})}finally{je.current=null,
|
|
389
|
+
Model: ${H.model}${H.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;d({kind:"note",tone:"info",text:A+gs($,C,x).join(`
|
|
390
|
+
`)+U}),Q(G);return}dt.current=Date.now(),Pt(0),S(!0);let I=new AbortController;je.current=I,oe({verb:"Converting",total:$.length,done:0,active:[],rows:Mn($),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Converting ${w.length} articles across ${$.length} partitions (\u2264${x} agents at once) on ${H.model}\u2026 (esc to stop)`});try{for await(let C of ur({cwd:e,partitions:$,promptFor:ms,concurrency:x,profileName:s,allowProdWrites:jt.current,model:H.model,signal:I.signal}))if(C.type==="partition_status")C.status==="running"?oe(A=>A&&{...A,active:[...A.active,C.label],rows:ze(A.rows,C.label,"active"),lastAt:Date.now()}):oe(A=>A&&{...A,active:A.active.filter(U=>U!==C.label),done:A.done+1,rows:ze(A.rows,C.label,C.status==="done"?"done":"failed"),lastAt:Date.now()});else if(C.type==="partition_event")oe(A=>{if(!A)return A;let U={...A,lastAt:Date.now()};return C.event.type==="tool"?U.tools=A.tools+1:C.event.type==="text"&&(U.chars=A.chars+C.event.delta.length),U});else if(C.type==="run_done"){Mt(J=>J+C.totalCostUsd),Lt(J=>J+C.results.reduce((ye,Vt)=>ye+Vt.outputTokens,0));let A=C.aborted?"Stopped. ":"",U=t.kind==="api"?"api":"subscription";d({kind:"note",tone:C.aborted?"warn":C.ok?"ok":"warn",text:A+ws(C.results,$,U).join(`
|
|
391
|
+
`)})}}catch(C){d({kind:"note",tone:"error",text:`Convert run failed: ${C.message}`})}finally{je.current=null,oe(null),S(!1),Y(C=>C+1)}return}case"write":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=Qg(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:y,path:b,preview:w,concurrency:$,rewrite:x}=bs(h),{docsDir:G,targets:H,reason:I,rewriting:C}=Ts(e,u,{scope:y,path:b,rewrite:x});if(H.length===0){d({kind:"note",tone:"warn",text:I??"Nothing to write."});return}C&&d({kind:"note",tone:"warn",text:`--rewrite: regenerating ${H.length} already-written article${H.length===1?"":"s"} (overwrites them; git has your baseline).`});let A=Pi(H),U=ks($),J=pr(e,"standard"),ye=!!b;if(w&&!ye){let X=yd({files:$s(e,u,H),op:"write",model:J.model}),se=y?`Scope: ${y} (${H.length} pending)
|
|
392
392
|
`:"",pe=`
|
|
393
|
-
Model: ${J.model}${J.forced?" (forced)":" \u2014 authoring; /model to override"}`;d({kind:"note",tone:"info",text:
|
|
394
|
-
`)+pe}),Q(`/write${y?` --scope ${y}`:""}`);return}
|
|
395
|
-
`)}),!X.aborted&&X.ok)try{let
|
|
393
|
+
Model: ${J.model}${J.forced?" (forced)":" \u2014 authoring; /model to override"}`;d({kind:"note",tone:"info",text:se+Cs(A,X,U).join(`
|
|
394
|
+
`)+pe}),Q(`/write${y?` --scope ${y}`:""}`);return}dt.current=Date.now(),Pt(0),S(!0);let Vt=new AbortController;je.current=Vt,oe({verb:"Writing",total:A.length,done:0,active:[],rows:Mn(A),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Writing ${H.length} article${H.length===1?"":"s"} across ${A.length} partition${A.length===1?"":"s"} (\u2264${U} agents at once) on ${J.model}${J.forced?" (forced)":""}\u2026 (esc to stop)`});let lo=new Set;try{for await(let X of ur({cwd:e,partitions:A,promptFor:se=>xs(se,G,{rewrite:C||ye}),concurrency:U,profileName:s,allowProdWrites:jt.current,model:J.model,signal:Vt.signal}))if(X.type==="partition_status")X.status==="running"?oe(se=>se&&{...se,active:[...se.active,X.label],rows:ze(se.rows,X.label,"active"),lastAt:Date.now()}):oe(se=>se&&{...se,active:se.active.filter(pe=>pe!==X.label),done:se.done+1,rows:ze(se.rows,X.label,X.status==="done"?"done":"failed"),lastAt:Date.now()});else if(X.type==="partition_event"){let se=null;if(X.event.type==="tool"){let pe=Qc(X.event.name,X.event.input,A[X.index]?.paths??[]);pe&&!lo.has(pe)&&(lo.add(pe),se=X.label)}oe(pe=>{if(!pe)return pe;let Ue={...pe,lastAt:Date.now()};return X.event.type==="tool"?Ue.tools=pe.tools+1:X.event.type==="text"&&(Ue.chars=pe.chars+X.event.delta.length),se&&(Ue.rows=Xc(Ue.rows,se)),Ue})}else if(X.type==="run_done"){Mt(Je=>Je+X.totalCostUsd),Lt(Je=>Je+X.results.reduce((Ve,Yd)=>Ve+Yd.outputTokens,0));let se=X.aborted?"Stopped. ":"",pe=t.kind==="api"?"api":"subscription";if(d({kind:"note",tone:X.aborted?"warn":X.ok?"ok":"warn",text:se+Rs(X.results,A,pe).join(`
|
|
395
|
+
`)}),!X.aborted&&X.ok)try{let Je=(lo.size>0?[...lo]:H).map(Ve=>`${G}/${Ve}`);Ti(e,Je,{writtenCap:Si})}catch{}let Ue=X.aborted?null:Ps(e,G,H);if(Ue&&d({kind:"note",tone:"warn",text:Ue}),!X.aborted&&X.ok){let Je=y??b??"",Ve=Je?` ${Je}`:"";Ut(Ue?`Written \u2014 but the checker flagged issues. I\u2019d fix those first with /check${Ve} --fix, then /review${Ve} --fix for editorial quality, then /publish --all (add /screenshot --all first if you want images).`:`Written. I\u2019d run /review${Ve} --fix next \u2014 editorial review that applies its fixes \u2014 then /publish --all pushes the drafts up (add /screenshot --all first if you want images).`,{kind:"cmd",cmd:Ue?`/check${Ve} --fix`:`/review${Ve} --fix`,reason:""})}}}catch(X){d({kind:"note",tone:"error",text:`Write run failed: ${X.message}`})}finally{je.current=null,oe(null),S(!1),Y(X=>X+1)}return}case"draft":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:u,looseDocs:y}=Ss(e);if(u.length===0&&y===0){d({kind:"note",tone:"info",text:js});return}let b=h.join(" ").trim();if(!b&&u.length>1){d({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
|
|
396
396
|
${u.map(x=>` \u2022 ${x.name} (${x.docCount} doc${x.docCount===1?"":"s"})`).join(`
|
|
397
|
-
`)}`}),
|
|
398
|
-
`)});return}if(u==="--baseline"){let w=h.find(H=>!H.startsWith("--")),$=w?w.replace(/\\/g,"/"):void 0;d({kind:"note",tone:"info",text:$?`Setting the sync baseline for ${$}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let x=await
|
|
397
|
+
`)}`}),ct(u.map(x=>`/draft ${x.name}`));return}let w="",$;if(b){let x=Ds(u,b);x?w=x:$=b}else w=u[0]?.name??"";await re(Lo(w,$),{display:b?`/draft ${b}`:"/draft",quietUser:!0});return}case"pull":{if(!Jn(c.trim()))return;let u=h.find(y=>y.startsWith("--"));try{if(u==="--status"){d({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let w=Date.now(),$=await Ri({cwd:e,profileName:s});d({kind:"note",tone:"info",text:Io($,Date.now()-w).join(`
|
|
398
|
+
`)});return}if(u==="--baseline"){let w=h.find(H=>!H.startsWith("--")),$=w?w.replace(/\\/g,"/"):void 0;d({kind:"note",tone:"info",text:$?`Setting the sync baseline for ${$}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let x=await qg({cwd:e,profileName:s,relPaths:$?[$]:void 0}),G=$?{rebaselined:[],skipped:[]}:await Bg({cwd:e,profileName:s});if(x.baselined.length===0&&x.skipped.length===0&&G.rebaselined.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}x.baselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Baselined ${x.baselined.length} article${x.baselined.length===1?"":"s"} \u2014 they now read in-sync until either side changes.`}),G.rebaselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${G.rebaselined.length} article${G.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),x.skipped.length>0&&d({kind:"note",tone:"warn",text:`${x.skipped.length} skipped:
|
|
399
399
|
${x.skipped.map(H=>` - ${H.path} (${H.reason})`).join(`
|
|
400
|
-
`)}`}),Y(H=>H+1);return}if(u==="--compare"){d({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let w=await
|
|
401
|
-
`)});return}if(u){d({kind:"note",tone:"error",text:`Unknown option: ${u} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let y=h[0];if(y){let w=await
|
|
402
|
-
`)}),
|
|
403
|
-
`)}),b.length>0&&
|
|
404
|
-
`)});return}case"reorder":{let u=
|
|
405
|
-
`)});return}case"devhints":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:Kt(
|
|
406
|
-
`)}),
|
|
407
|
-
`)});return}if(u.mode==="single"){let I=await
|
|
408
|
-
`)})}return}case"reset":{let u=
|
|
409
|
-
`)}),me(Mn(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${i} \u2014 type /help.`})}},[e,r,s,Ht,Ar,d,Ce,se,Ft,Tr,zi]),ro=z(c=>{let a=(c??T).trim();if(v(""),qn(null),Pt(0),a.startsWith("/")&&(Un.current=!1,Le(),sn(null),He(h=>Jc(h,a))),!a||(Ei(!1),Xi(a))||Ki(a))return;gr.current.push(a);let i=nd(a,Ii.current);if(a.startsWith("/"))d({kind:"user",text:a}),mn(i);else if(ow(i)){d({kind:"user",text:a});let h=rw(i);if(!h)se(i,{display:a,quietUser:!0});else{try{sw(e,{title:h,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}se(`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${h}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${h}" and the article path(s) you wrote.`,{display:a,quietUser:!0})}}else se(i,{display:a})},[T,Xi,Ki,mn,se]),Qi=z(c=>{if(c.length>1){if(c.includes("\x1B"))return;let a=Zc(c);if(ed(a)){let i=td(++Ud.current,a);Ii.current.set(i,a),_(i)}else _(a);return}_(c)},[_]),qt=Math.max(10,Me-6),Ji=bi(()=>ir(k.text,qt),[k.text,qt]),Er=z(c=>g(a=>({...a,pos:Math.max(0,Math.min(a.text.length,a.pos+c))})),[]),so=z(c=>g(a=>({...a,pos:rd(ir(a.text,qt),a.pos,c)})),[qt]),gn=z(c=>g(a=>({...a,pos:sd(ir(a.text,qt),a.pos,c)})),[qt]),qd=["\x1B[H","\x1B[1~","\x1BOH"],Bd=["\x1B[F","\x1B[4~","\x1BOF"],Zi=z((c,a)=>a.leftArrow?(Er(-1),!0):a.rightArrow?(Er(1),!0):c&&qd.includes(c)?(gn("start"),!0):c&&Bd.includes(c)?(gn("end"),!0):a.ctrl&&c==="a"?(gn("start"),!0):a.ctrl&&c==="e"?(gn("end"),!0):!1,[Er,gn]);return yg((c,a)=>{if(a.ctrl&&c==="c"){De.current?.close(),r();return}if(!M){if(N){if(a.escape){if(je.current){if(!je.current.signal.aborted){let i=(Gn?.verb??"work").toLowerCase(),h=Gn?.unit??"article";d({kind:"note",tone:"warn",text:`\u238B Stopping the ${i} run (finishing in-flight ${h}s)\u2026`}),je.current.abort()}return}an.current||(an.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),De.current?.interrupt());return}if(a.return){let i=T.trim();if(!i)return;gt.current.push(i),yr([...gt.current]),v("");return}if(Zi(c,a))return;if(a.upArrow){so(-1);return}if(a.downArrow){so(1);return}if(a.backspace||a.delete){P();return}c&&!a.ctrl&&!a.meta&&Qi(c);return}if(ut){if(a.upArrow){pt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){pt(i=>i&&{...i,cursor:Math.min(We.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=We.length){pt(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=We[ut.cursor];pt(null);let{lines:h,changed:u,effective:y}=Sn(e,i.value??"default");for(let b of h)d({kind:"note",tone:b.startsWith("\u26A0")?"warn":b.startsWith("\u2713")?"ok":"info",text:b});u&&(Hi(b=>b+1),De.current?.setModel(y));return}if(c==="s"){let i=We[ut.cursor];pt(null),De.current?.setModel(i.value??void 0),d({kind:"note",tone:"ok",text:`\u2713 Using ${i.label} for this session only (your saved default is unchanged).`});return}if(a.escape){pt(null);return}return}if(Be){if(a.upArrow){At(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){At(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Be.rows.length){At(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return||c==="s"){let i=Be.rows[Be.cursor];At(null),Dr(i.name,a.return===!0);return}if(a.escape){At(null);return}return}if(zn){if(a.escape){dn(null);return}if(a.leftArrow||a.tab&&a.shift){dn(i=>i&&{tab:(i.tab-1+Ae.length)%Ae.length});return}if(a.rightArrow||a.tab){dn(i=>i&&{tab:(i.tab+1)%Ae.length});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ae.length){dn({tab:Number(c)-1});return}return}if(Ve){if(a.upArrow){Et(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Et(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ve.rows.length){Et(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=Ve.rows[Ve.cursor].name;if(Et(null),!Fr(e,i).created){d({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}d({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${i}").`});let u=!1;try{let y=Ct(i);u=!!y&&!(lt(y)&&!y.refreshToken)}catch{u=!1}d({kind:"note",tone:"info",text:u?`Next: sign in to ${i} and pick your project \u2014 you're already signed in here, so it'll be quick.`:`Next: sign in to Document360 (${i}) and pick your project.`}),Q("/login"),Y(y=>y+1);return}if(a.escape){Et(null);return}return}if(he){if(a.upArrow){Nt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Nt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=he.rows.length){Nt(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=he.rows[he.cursor],{profile:h,projectId:u}=he;Nt(null),to(h,u,i);return}if(a.escape){Nt(null);return}return}if(ve){if(a.upArrow){ft(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){ft(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=ve.rows.length){ft(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=ve.rows[ve.cursor],{profile:h}=ve;ft(null),oo(h,i);return}if(a.escape){ft(null);return}return}if(ge){if(a.upArrow){_t(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){_t(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c===" "){_t(i=>i&&{...i,rows:i.rows.map((h,u)=>u===i.cursor?{...h,checked:!h.checked}:h)});return}if(a.return){let i=ge.rows.filter(h=>h.checked).map(h=>h.path);if(_t(null),i.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}os(e,i),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${i.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let h of i)d({kind:"note",tone:"info",text:` ${h}`});d({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(a.escape){_t(null);return}return}if(Ge){if(a.upArrow){ht(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){ht(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ge.rows.length){ht(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=Ge.rows[Ge.cursor],h=Ge.run;ht(null),h(i.token);return}if(a.escape){ht(null);return}return}if(Qe){if(a.upArrow){It(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){It(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Qe.rows.length){It(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=Qe.rows[Qe.cursor];It(null),i.conflict?Ar(i.paths[0]):i.kind==="article"?Tr(i.paths[0]):Ft(i.paths);return}if(a.escape){It(null);return}return}if($e){if(a.escape){mt(null);return}if(a.upArrow){mt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){mt(i=>i&&{...i,cursor:Math.min(Math.max(0,Zn.length-1),i.cursor+1)});return}if(a.return){let i=Zn[$e.cursor];if(i){mt(null);try{d({kind:"preview",name:Mn(i),text:Pd(lr(vi(e,i),"utf8"))})}catch(h){d({kind:"note",tone:"error",text:`Could not read ${i}: ${h.message}`})}}return}if(a.backspace||a.delete){mt(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(c&&!a.ctrl&&!a.meta&&c.length===1){mt(i=>i&&{...i,query:i.query+c,cursor:0});return}return}if(xe){if(a.escape){wt(null);return}if(a.upArrow){wt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){wt(i=>i&&{...i,cursor:Math.min(Math.max(0,eo.length-1),i.cursor+1)});return}if(a.return){let i=eo[xe.cursor];if(i){wt(null),Ce(i.uuid),qe.current={uuid:i.uuid,firstPrompt:i.firstPrompt,titleFired:!0},dt(i.name),$i(i.uuid),St.current=[];let h=wi(e,i.uuid);for(let u of h)d(u);d({kind:"note",tone:"ok",text:h.length?`Resumed "${i.name}" \u2014 restored ${h.length} message(s); continue where you left off.`:`Resumed "${i.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(a.backspace||a.delete){wt(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(c&&!a.ctrl&&!a.meta&&c.length===1){wt(i=>i&&{...i,query:i.query+c,cursor:0});return}return}if(a.tab&&!T&&ne){v(ne),Le();return}if(!T&&be.length>0&&!hr&&c&&/^[1-9]$/.test(c)){let i=be[Number(c)-1];if(i){v(xt(i));return}}if(!T&&(Qn||un)&&c==="c"&&!a.ctrl&&!a.meta&&!a.return&&!a.tab){let i=Qn!=null;mi(Qn??un).then(u=>{d({kind:"note",tone:u?"ok":"warn",text:u?i?"\u2713 Copied the feedback to your clipboard \u2014 send it to the d360-writer team (Teams / Slack / email).":"\u2713 Copied the prompt to your clipboard \u2014 paste it into your repo's coding agent.":i?"Couldn't reach your clipboard \u2014 select the feedback above and copy it manually.":"Couldn't reach your clipboard \u2014 select the prompt above and copy it manually."}),u&&i&&Cr(null),u&&!i&&Bi(!0)});return}if(!Zi(c,a)){if(Gi){if(a.upArrow){Pt(i=>Math.max(0,i-1));return}if(a.downArrow){Pt(i=>Math.min(hn.length-1,i+1));return}if(a.tab){v("/"+(hn[rn]?.name??"")+" "),Pt(0);return}if(a.return){let i=hn[rn];if(i){let h=T.trim().slice(1).split(/\s+/).slice(1).join(" ");if(Bc(i.usage)&&!h){v("/"+i.name+" "),Pt(0);return}ro("/"+i.name+(h?" "+h:""));return}}}else{if(a.upArrow){if(T!==""&&Tt===null){so(-1);return}let i=gr.current;if(!i.length)return;let h=Tt===null?i.length-1:Math.max(0,Tt-1);qn(h),v(i[h]??"");return}if(a.downArrow){if(T!==""&&Tt===null){so(1);return}let i=gr.current;if(Tt===null)return;let h=Tt+1;h>=i.length?(qn(null),v("")):(qn(h),v(i[h]??""));return}}if(a.return){ro();return}if(a.backspace||a.delete){P();return}if(a.escape){v(""),Pt(0),Le(),He([]),sn(null),Un.current=!0;return}c&&!a.ctrl&&!a.meta&&Qi(c)}}}),Te(()=>{if(N||M)return;let c=gt.current.shift();c!==void 0&&(yr([...gt.current]),ro(c))},[N,M,ro]),K(oe,{flexDirection:"column",width:Me,children:[Pr!==null&&K(oe,{marginTop:1,flexDirection:"column",children:[Pr.truncated&&E(j,{dimColor:!0,children:"\u2026"}),E(j,{children:Pr.text})]}),N&&(Gn?E(mw,{p:Gn}):E(pw,{startTime:ct.current,chars:Md})),!N&&Mi?E(fw,{text:Mi}):null,E(oe,{borderStyle:"round",borderColor:Vi.prod?"yellow":q,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:T?Ji.map((c,a)=>{let i=k.text.slice(c.start,c.end),h=a===ar(Ji,k.pos),u=Math.min(k.pos,c.end)-c.start;return K(j,{children:[E(j,{color:q,children:a===0?"> ":" "}),h?K(ur,{children:[i.slice(0,u),E(tn,{ch:i[u]??" "}),i.slice(u+1)]}):i||" "]},`${a}-${c.start}`)}):K(j,{children:[E(j,{color:q,children:"> "}),kr?E(tn,{ch:" "}):ne&&!N&&Fe?K(ur,{children:[E(tn,{ch:Fe[0],dim:!0}),E(j,{color:"gray",children:Fe.slice(1)})]}):ne&&!N?K(ur,{children:[E(tn,{ch:ne[0],dim:!0}),E(j,{color:"gray",children:ne.slice(1)}),E(j,{dimColor:!0,children:" (tab)"})]}):(Rr.isSetup||!Od)&&!N?K(ur,{children:[E(tn,{ch:Rr.text[0],dim:!0}),E(j,{color:"gray",children:Rr.text.slice(1)})]}):E(tn,{ch:" "})]})}),Li.length>0&&E(oe,{flexDirection:"column",paddingX:1,children:Li.map((c,a)=>E(j,{color:"gray",children:`\u29D7 queued: ${c}`},`${a}-${c.slice(0,24)}`))}),zn?E(Gc,{tab:zn.tab,width:Me,version:o,engineVersion:Td}):ut?K(oe,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:"Select model"}),E(j,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),We.map((c,a)=>K(j,{color:a===ut.cursor?q:void 0,children:[a===ut.cursor?"\u276F ":" ",`${a+1}. ${c.label}${a===ut.current?" \u2714":""}`.padEnd(16),E(j,{color:"gray",children:c.desc})]},c.label)),E(j,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Be?K(oe,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:"Switch connection profile"}),Be.rows.map((c,a)=>K(j,{color:a===Be.cursor?q:void 0,children:[a===Be.cursor?"\u276F ":" ",`${a+1}. ${c.name}${a===Be.current?" \u2714":""}`.padEnd(20),E(j,{color:"gray",children:`${c.env} \xB7 ${c.who??"not signed in"}`}),c.prod?E(j,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},c.name)),E(j,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Ve?K(oe,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:"Pick your Document360 environment"}),Ve.rows.map((c,a)=>K(j,{color:a===Ve.cursor?q:void 0,children:[a===Ve.cursor?"\u276F ":" ",`${a+1}. ${c.name}`.padEnd(16),E(j,{color:"gray",children:c.apiUrl})]},c.name)),E(j,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):he?K(oe,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:"Switch workspace"}),E(j,{dimColor:!0,children:`environment ${he.environment} \xB7 project ${he.projectName??`${he.projectId.slice(0,8)}\u2026`}`}),he.rows.map((c,a)=>K(j,{color:a===he.cursor?q:void 0,children:[a===he.cursor?"\u276F ":" ",`${a+1}. ${c.name}${a===he.current?" \u2714":""}`.padEnd(30),E(j,{color:"gray",children:c.type??""})]},c.id)),E(j,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):ve?K(oe,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:"Choose project"}),E(j,{dimColor:!0,children:`environment ${ve.environment}`}),ve.rows.map((c,a)=>K(j,{color:a===ve.cursor?q:void 0,children:[a===ve.cursor?"\u276F ":" ",`${a+1}. ${c.name}${a===ve.current?" \u2714":""}`.padEnd(30),E(j,{color:"gray",children:c.sub??""})]},c.id)),E(j,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):ge?(()=>{let a=Math.min(Math.max(0,ge.cursor-Math.floor(7)),Math.max(0,ge.rows.length-14)),i=ge.rows.slice(a,a+14),h=ge.rows.filter(u=>u.checked).length;return K(oe,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:`Which folders back the user docs? (${h} selected of ${ge.rows.length})`}),a>0?E(j,{dimColor:!0,children:` \u2191 ${a} more`}):null,i.map((u,y)=>{let b=a+y;return K(j,{color:b===ge.cursor?q:void 0,children:[b===ge.cursor?"\u276F ":" ",u.checked?"\u25C9 ":"\u25CB ",u.path.padEnd(Math.min(48,Me-34)),E(j,{color:"gray",children:Ao(u)})]},u.path)}),a+14<ge.rows.length?E(j,{dimColor:!0,children:` \u2193 ${ge.rows.length-a-14} more`}):null,E(j,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():Ge?K(oe,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:"Which category? (pick one to scope to)"}),Ge.rows.map((c,a)=>{let i=a===Ge.cursor,h=`${a+1}.`.padEnd(3);return K(j,{color:i?q:void 0,children:[i?"\u276F ":" ",`${h} ${c.label} (${c.count})`.padEnd(Math.min(44,Math.max(20,Me-24))),E(j,{color:"gray",children:` ${c.token}`})]},c.token)}),E(j,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):Qe?K(oe,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),Qe.rows.map((c,a)=>{let i=a===Qe.cursor,h=c.indent?" ":" ",u=`${a+1}.`.padEnd(3);return K(j,{color:i?q:void 0,bold:c.kind==="category"&&!i,children:[i?"\u276F ":" ",`${h}${u} ${c.label}`.padEnd(Math.min(56,Me-24)),c.note?E(j,{color:"gray",children:c.note}):null]},`${c.kind}:${c.paths.join(",")}`)}),E(j,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):$e?K(oe,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:`Preview article${$e.query?` \u2014 filter: ${$e.query}`:" (type to filter)"}`}),Zn.length===0?E(j,{color:"gray",children:"no articles match"}):Zn.map((c,a)=>K(j,{color:a===$e.cursor?q:void 0,children:[a===$e.cursor?"\u276F ":" ",c]},c)),E(j,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):xe?K(oe,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:`Resume session${xe.query?` \u2014 filter: ${xe.query}`:" (type to filter)"}`}),eo.length===0?E(j,{color:"gray",children:"no sessions match"}):eo.map((c,a)=>K(j,{color:a===xe.cursor?q:void 0,children:[a===xe.cursor?"\u276F ":" ",c.name.slice(0,28).padEnd(30),E(j,{color:a===xe.cursor?q:"gray",children:c.firstPrompt.slice(0,Math.max(10,Me-40))})]},c.uuid)),E(j,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Gi?K(oe,{flexDirection:"column",children:[hn.map((c,a)=>K(j,{color:a===rn?q:void 0,children:[a===rn?"\u276F ":" ",c.usage.padEnd(22)," ",E(j,{color:a===rn?q:"gray",children:c.name==="model"&&br?`${c.desc} (currently ${br})`:c.desc})]},c.name)),E(j,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!N&&!T&&be.length>0?K(oe,{flexDirection:"column",paddingX:1,children:[Oi?E(j,{color:q,children:Oi}):null,be.map((c,a)=>{let i=xt(c),h=i.slice(0,Math.max(20,Me-5)),u=Me-h.length-7,y=u>=12?(Qc(c)??Hc(i)).slice(0,u):"";return K(j,{children:[E(j,{color:q,children:a+1})," ",h,y?E(j,{dimColor:!0,children:` \u2014 ${y}`}):null]},i)}),E(j,{dimColor:!0,children:`press 1-${be.length} to fill \xB7 esc cancel`})]}):E(oe,{paddingX:1,children:K(j,{color:"gray",children:[Vi.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${br??"model n/a"}${t.kind==="api"?Fi>0?` \xB7 ${ke(Fi)}`:"":Wi>0?` \xB7 ${st(Wi)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}W();import{jsx as kw}from"react/jsx-runtime";async function jd(e=process.cwd(),t="auto",n,o="0.0.0"){let r=yw(t);r.kind==="none"&&(console.error(""),console.error(R("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${O("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${O("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=ww(kw(Dd,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
|
|
410
|
-
`),process.exit(0)}W();import{writeCrashLog as
|
|
411
|
-
`+R(`\u2717 d360-writer crashed: ${
|
|
400
|
+
`)}`}),Y(H=>H+1);return}if(u==="--compare"){d({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let w=await Hg({cwd:e,profileName:s}),$=w.onlyInLegacy.length===0&&w.onlyInManifest.length===0&&w.mappedMissingFromManifest.length===0,x=[`Legacy listing: ${w.legacyCount} \xB7 Manifest: ${w.manifestCount} \xB7 in both: ${w.inBoth}`];$?x.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(w.mappedMissingFromManifest.length&&x.push(`\u2717 ${w.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${w.mappedMissingFromManifest.slice(0,5).join(", ")}`),w.onlyInLegacy.length&&x.push(`\u26A0 ${w.onlyInLegacy.length} only in the legacy listing: ${w.onlyInLegacy.slice(0,5).join(", ")}`),w.onlyInManifest.length&&x.push(`\u26A0 ${w.onlyInManifest.length} only in the manifest: ${w.onlyInManifest.slice(0,5).join(", ")}`),x.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),d({kind:"note",tone:$?"ok":"warn",text:x.join(`
|
|
401
|
+
`)});return}if(u){d({kind:"note",tone:"error",text:`Unknown option: ${u} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let y=h[0];if(y){let w=await wd({cwd:e,profileName:s,relPath:y.replace(/\\/g,"/")});le.current=[{plan:w,mode:w.overwritesLocalChanges?"conflict":"pull"}],At.current=[],qt();return}d({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let b=await cs({cwd:e,profileName:s});for(let w of ds(b))d({kind:"note",tone:w.tone,text:w.text});Y(w=>w+1)}catch(y){d({kind:"note",tone:"error",text:`Pull failed: ${y.message}`})}return}case"scope":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=Vg(e);if(u.length===0){d({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.'});return}Ot({cursor:0,rows:u.map(y=>({...y,checked:y.recommended}))});return}case"audit":{if(h[0]==="--auto"){let y=te(e);if(!y){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let b=h[1]!=="off";fd({...y,autoAudit:b},e),d({kind:"note",tone:"ok",text:b?"\u2713 Auto-audit ON \u2014 when you launch with code changes since the last audit, I\u2019ll run /audit automatically. (/audit --auto off to disable.)":"\u2713 Auto-audit OFF \u2014 I\u2019ll just nudge you to run /audit when code changed."});return}let u=await Tn();u.kind==="forward-to-agent"&&u.prompt&&await re(u.prompt,{display:u.display,quietUser:!0});return}case"check":{let u=h.find(w=>!w.startsWith("--")),y=u?` ${u}`:"",b=gd({cwd:e,scope:u});if(h.includes("--fix")){if(b.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing to fix \u2014 the docs are already clean."});return}d({kind:"note",tone:"info",text:`Fixing ${b.length} doc issue${b.length===1?"":"s"}\u2026`});let w=vd(e,u);await re(ti(b),{display:`/check${y} --fix`,quietUser:!0});try{Ti(e,w,{reviewedCap:Si})}catch{}let $=gd({cwd:e,scope:u});d({kind:"note",tone:$.length===0?"ok":"warn",text:$.length===0?"\u2713 Doc-checker: all issues resolved.":Vo($).join(`
|
|
402
|
+
`)}),Ut($.length===0?`Deterministic issues fixed. Next: /review${y} --fix for editorial quality (style, grammar, structure), then /publish --all.`:`Some issues remain \u2014 /review${y} --fix runs the editorial review + fixes, then /publish --all.`,{kind:"cmd",cmd:`/review${y} --fix`,reason:""});return}d({kind:"note",tone:b.length===0?"ok":"warn",text:Vo(b).join(`
|
|
403
|
+
`)}),b.length>0&&Ut(`Found ${b.length} doc issue${b.length===1?"":"s"} above. /check${y} --fix has the agent fix them in place (or /review${y} --fix for the full editorial pass; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/check${y} --fix`,reason:""});return}case"structure":{let u=In(e,s);if(u.length===0){d({kind:"note",tone:"info",text:"No documentation structure yet \u2014 run /init and author some articles first."});return}d({kind:"note",tone:"info",text:["Documentation order (categories \u2192 articles):","",...u].join(`
|
|
404
|
+
`)});return}case"reorder":{let u=oi(e,h);if(!u){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await re(u.prompt,{display:u.display,quietUser:!0}),Ut("Reordered locally \u2014 /publish --all syncs the new order to Document360.",{kind:"cmd",cmd:"/publish --all",reason:""});return}case"review":{let u=ni(e,h);if(!u){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let y=h.includes("--fix"),b=h.find($=>!$.startsWith("--")),w=y?vd(e,b):[];if(await re(u.prompt,{display:u.display,quietUser:!0}),y)try{Ti(e,w,{reviewedCap:Si})}catch{}if(y)Ut("\u2713 Editor applied its fixes \u2014 your docs are corrected. /publish --all pushes them up (or /check for an instant no-token re-scan first).",{kind:"cmd",cmd:"/publish --all",reason:""});else{let $=h.filter(x=>x!=="--fix").join(" ");Ut(`The review listed issues above. /review${$?` ${$}`:""} --fix lets the editor apply them all (or /check --fix for just the deterministic ones; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/review${$?` ${$}`:""} --fix`,reason:""})}return}case"capture-setup":{let u=await An();u.kind==="forward-to-agent"&&u.prompt&&await re(u.prompt,{display:u.display,quietUser:!0});let y=Hs(e);y&&d({kind:"note",tone:"info",text:y.join(`
|
|
405
|
+
`)});return}case"devhints":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:Xt(Kt(e)).join(`
|
|
406
|
+
`)}),Wt(bt()),fn.current=Ee(e).status==="current",Ft.current=Ge(e);return}case"discover":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await re(rs(),{display:"/discover",quietUser:!0});return}case"inbox":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(qs(e)===0){d({kind:"note",tone:"info",text:"Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)"});return}await re(Bs(),{display:"/inbox",quietUser:!0});return}case"feedback":{let u=bd(e),y="";try{y=tn(u)?dr(u,"utf8"):""}catch{y=""}if(!/^## /m.test(y)){d({kind:"note",tone:"info",text:"No open d360-writer feedback to copy \u2014 nothing logged in .d360-writer/tool-feedback.md yet."});return}let b=await wi(y.trim());d({kind:"note",tone:b?"ok":"warn",text:b?"\u2713 Copied the d360-writer feedback to your clipboard \u2014 send it to the team (Teams / Slack / email).":`Couldn\u2019t reach your clipboard \u2014 open ${u} and copy it manually.`}),b&&Pr(null);return}case"document":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:u,what:y}=Es(h);if(!y&&As(e)===0){d({kind:"note",tone:"info",text:Is});return}let b=`/document${y?` ${y}`:""}${u?" --publish":""}`;await re(Ns(y,u),{display:b,quietUser:!0});return}case"catch-up":{if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!Jn(c.trim()))return;let{publish:u}=Gs(h);d({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let y=await zs({cwd:e,profileName:s});for(let w of Ks(y))d({kind:"note",tone:w.startsWith("\u2713")?"ok":w.startsWith("\u2139")?"info":"warn",text:w});let b=Nn(En(e));d({kind:"note",tone:"info",text:b?`Catching up on ${b}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"}),await re(Ys({publish:u}),{display:`/catch-up${u?" --publish":""}`,quietUser:!0});return}case"update":{Cr.current=!0,d({kind:"note",tone:"info",text:`Updating ${xt}\u2026 (don\u2019t close this window)`}),Bn(!0),(await qo().finally(()=>Bn(!1))).ok?(d({kind:"note",tone:"ok",text:"\u2713 Updated \u2014 run /exit, then relaunch to apply."}),Q("/exit"),_i("")):d({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${Ho}`});return}case"screenshot":{let u=Us(h);if(u.mode==="list"){if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:Fs(Ws(e,u.scope),u.scope).join(`
|
|
407
|
+
`)});return}if(u.mode==="single"){let I=await Wo(h);I.kind==="forward-to-agent"&&I.prompt&&await re(I.prompt,{display:I.display,quietUser:!0});return}if(!te(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let y=u.mode==="scope"?u.scope:void 0,b=Kg(e,{scope:y}).map(I=>I.id);if(b.length===0){d({kind:"note",tone:"info",text:y?`No screenshot placeholders under ${y}.`:"No screenshot placeholders found in the docs."});return}let w=6,$=zg(b,3),x=pr(e,"standard");dt.current=Date.now(),Pt(0),S(!0);let G=new AbortController;je.current=G,oe({verb:"Authoring",unit:"spec",total:$.length,done:0,active:[],rows:Mn($),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Authoring ${b.length} screenshot spec${b.length===1?"":"s"} across ${$.length} partition${$.length===1?"":"s"} (\u2264${w} agents at once) on ${x.model}${x.forced?" (forced)":""}\u2026 (esc to stop)`});let H=!1;try{for await(let I of ur({cwd:e,partitions:$,promptFor:Zl,concurrency:w,profileName:s,allowProdWrites:jt.current,model:x.model,signal:G.signal}))if(I.type==="partition_status")I.status==="running"?oe(C=>C&&{...C,active:[...C.active,I.label],rows:ze(C.rows,I.label,"active"),lastAt:Date.now()}):oe(C=>C&&{...C,active:C.active.filter(A=>A!==I.label),done:C.done+1,rows:ze(C.rows,I.label,I.status==="done"?"done":"failed"),lastAt:Date.now()});else if(I.type==="partition_event")oe(C=>{if(!C)return C;let A={...C,lastAt:Date.now()};return I.event.type==="tool"?A.tools=C.tools+1:I.event.type==="text"&&(A.chars=C.chars+I.event.delta.length),A});else if(I.type==="run_done"){Mt(J=>J+I.totalCostUsd),Lt(J=>J+I.results.reduce((ye,Vt)=>ye+Vt.outputTokens,0));let C=I.results.filter(J=>J.ok).length,A=I.aborted?"Stopped. ":"";H=!I.aborted&&u.setup;let U=I.aborted?"":H?" Refreshing the capture-setup checklist\u2026":" Next: /capture-setup, then d360-capture capture.";d({kind:"note",tone:I.aborted?"warn":I.ok?"ok":"warn",text:`${A}Authored specs \u2014 ${C}/${I.results.length} batches ok.${U}`})}}catch(I){d({kind:"note",tone:"error",text:`Spec authoring failed: ${I.message}`})}finally{je.current=null,oe(null),S(!1),Y(I=>I+1)}if(H){let I=await An();I.kind==="forward-to-agent"&&I.prompt&&await re(I.prompt,{display:I.display,quietUser:!0});let C=Hs(e);C&&d({kind:"note",tone:"info",text:C.join(`
|
|
408
|
+
`)})}return}case"reset":{let u=Js(e);if(u.length===0){d({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}Yn.current={repoName:Un(e),targets:u,hadDevhints:tn(kd(e))},d({kind:"note",tone:"warn",text:ei(e,u).join(`
|
|
409
|
+
`)}),ge(Un(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${i} \u2014 type /help.`})}},[e,r,s,qt,Nr,d,Ce,re,Ht,Dr,Xi]),io=z(c=>{let a=(c??T).trim();if(v(""),Vn(null),Tt(0),a.startsWith("/")&&(Fn.current=!1,Le(),an(null),ct(h=>ed(h,a))),!a||(Ii(!1),Ji(a))||Qi(a))return;yr.current.push(a);let i=rd(a,Oi.current);if(a.startsWith("/"))d({kind:"user",text:a}),_e(!0),gn(i).finally(()=>_e(!1));else if(sw(i)){d({kind:"user",text:a});let h=iw(i);if(!h)re(i,{display:a,quietUser:!0});else{try{aw(e,{title:h,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}re(`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${h}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${h}" and the article path(s) you wrote.`,{display:a,quietUser:!0})}}else re(i,{display:a})},[T,Ji,Qi,gn,re]),Zi=z(c=>{if(c.length>1){if(c.includes("\x1B"))return;let a=td(c);if(nd(a)){let i=od(++Fd.current,a);Oi.current.set(i,a),_(i)}else _(a);return}_(c)},[_]),Bt=Math.max(10,Me-6),ea=$i(()=>lr(k.text,Bt),[k.text,Bt]),Ir=z(c=>g(a=>({...a,pos:Math.max(0,Math.min(a.text.length,a.pos+c))})),[]),ao=z(c=>g(a=>({...a,pos:id(lr(a.text,Bt),a.pos,c)})),[Bt]),wn=z(c=>g(a=>({...a,pos:ad(lr(a.text,Bt),a.pos,c)})),[Bt]),Vd=["\x1B[H","\x1B[1~","\x1BOH"],Gd=["\x1B[F","\x1B[4~","\x1BOF"],ta=z((c,a)=>a.leftArrow?(Ir(-1),!0):a.rightArrow?(Ir(1),!0):c&&Vd.includes(c)?(wn("start"),!0):c&&Gd.includes(c)?(wn("end"),!0):a.ctrl&&c==="a"?(wn("start"),!0):a.ctrl&&c==="e"?(wn("end"),!0):!1,[Ir,wn]);return bg((c,a)=>{if(a.ctrl&&c==="c"){De.current?.close(),r();return}if(!M){if(N){if(a.escape){if(je.current){if(!je.current.signal.aborted){let i=(zn?.verb??"work").toLowerCase(),h=zn?.unit??"article";d({kind:"note",tone:"warn",text:`\u238B Stopping the ${i} run (finishing in-flight ${h}s)\u2026`}),je.current.abort()}return}ln.current||(ln.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),De.current?.interrupt());return}if(a.return){let i=T.trim();if(!i)return;wt.current.push(i),br([...wt.current]),v("");return}if(ta(c,a))return;if(a.upArrow){ao(-1);return}if(a.downArrow){ao(1);return}if(a.backspace||a.delete){P();return}c&&!a.ctrl&&!a.meta&&Zi(c);return}if(pt){if(a.upArrow){ft(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){ft(i=>i&&{...i,cursor:Math.min(We.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=We.length){ft(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=We[pt.cursor];ft(null);let{lines:h,changed:u,effective:y}=Dn(e,i.value??"default");for(let b of h)d({kind:"note",tone:b.startsWith("\u26A0")?"warn":b.startsWith("\u2713")?"ok":"info",text:b});u&&(Bi(b=>b+1),De.current?.setModel(y));return}if(c==="s"){let i=We[pt.cursor];ft(null),De.current?.setModel(i.value??void 0),d({kind:"note",tone:"ok",text:`\u2713 Using ${i.label} for this session only (your saved default is unchanged).`});return}if(a.escape){ft(null);return}return}if(He){if(a.upArrow){Et(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Et(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=He.rows.length){Et(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return||c==="s"){let i=He.rows[He.cursor];Et(null),Ar(i.name,a.return===!0);return}if(a.escape){Et(null);return}return}if(Xn){if(a.escape){un(null);return}if(a.leftArrow||a.tab&&a.shift){un(i=>i&&{tab:(i.tab-1+Ae.length)%Ae.length});return}if(a.rightArrow||a.tab){un(i=>i&&{tab:(i.tab+1)%Ae.length});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ae.length){un({tab:Number(c)-1});return}return}if(qe){if(a.upArrow){Nt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Nt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=qe.rows.length){Nt(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=qe.rows[qe.cursor].name;if(Nt(null),!qr(e,i).created){d({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}d({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${i}").`});let u=!1;try{let y=Rt(i);u=!!y&&!(at(y)&&!y.refreshToken)}catch{u=!1}d({kind:"note",tone:"info",text:u?`Next: sign in to ${i} and pick your project \u2014 you're already signed in here, so it'll be quick.`:`Next: sign in to Document360 (${i}) and pick your project.`}),Q("/login"),Y(y=>y+1);return}if(a.escape){Nt(null);return}return}if(me){if(a.upArrow){It(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){It(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=me.rows.length){It(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=me.rows[me.cursor],{profile:h,projectId:u}=me;It(null),oo(h,u,i);return}if(a.escape){It(null);return}return}if(ve){if(a.upArrow){ht(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){ht(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=ve.rows.length){ht(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=ve.rows[ve.cursor],{profile:h}=ve;ht(null),so(h,i);return}if(a.escape){ht(null);return}return}if(we){if(a.upArrow){Ot(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Ot(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c===" "){Ot(i=>i&&{...i,rows:i.rows.map((h,u)=>u===i.cursor?{...h,checked:!h.checked}:h)});return}if(a.return){let i=we.rows.filter(h=>h.checked).map(h=>h.path);if(Ot(null),i.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}ss(e,i),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${i.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let h of i)d({kind:"note",tone:"info",text:` ${h}`});d({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(a.escape){Ot(null);return}return}if(Be){if(a.upArrow){mt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){mt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Be.rows.length){mt(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=Be.rows[Be.cursor],h=Be.run;mt(null),h(i.token);return}if(a.escape){mt(null);return}return}if(Xe){if(a.upArrow){_t(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){_t(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Xe.rows.length){_t(i=>i&&{...i,cursor:Number(c)-1});return}if(a.return){let i=Xe.rows[Xe.cursor];_t(null),i.conflict?Nr(i.paths[0]):i.kind==="article"?Dr(i.paths[0]):Ht(i.paths);return}if(a.escape){_t(null);return}return}if($e){if(a.escape){gt(null);return}if(a.upArrow){gt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){gt(i=>i&&{...i,cursor:Math.min(Math.max(0,to.length-1),i.cursor+1)});return}if(a.return){let i=to[$e.cursor];if(i){gt(null);try{d({kind:"preview",name:Un(i),text:Sd(dr(xi(e,i),"utf8"))})}catch(h){d({kind:"note",tone:"error",text:`Could not read ${i}: ${h.message}`})}}return}if(a.backspace||a.delete){gt(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(c&&!a.ctrl&&!a.meta&&c.length===1){gt(i=>i&&{...i,query:i.query+c,cursor:0});return}return}if(xe){if(a.escape){yt(null);return}if(a.upArrow){yt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){yt(i=>i&&{...i,cursor:Math.min(Math.max(0,no.length-1),i.cursor+1)});return}if(a.return){let i=no[xe.cursor];if(i){yt(null),Ce(i.uuid),Fe.current={uuid:i.uuid,firstPrompt:i.firstPrompt,titleFired:!0},ut(i.name),Ci(i.uuid),Dt.current=[];let h=ki(e,i.uuid);for(let u of h)d(u);d({kind:"note",tone:"ok",text:h.length?`Resumed "${i.name}" \u2014 restored ${h.length} message(s); continue where you left off.`:`Resumed "${i.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(a.backspace||a.delete){yt(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(c&&!a.ctrl&&!a.meta&&c.length===1){yt(i=>i&&{...i,query:i.query+c,cursor:0});return}return}if(a.tab&&!T&&he){v(he),Le();return}if(!T&<.length>0&&!gr&&c&&/^[1-9]$/.test(c)){let i=lt[Number(c)-1];if(i){v(Ct(i));return}}if(!T&&(Zn||pn)&&c==="c"&&!a.ctrl&&!a.meta&&!a.return&&!a.tab){let i=Zn!=null;wi(Zn??pn).then(u=>{d({kind:"note",tone:u?"ok":"warn",text:u?i?"\u2713 Copied the feedback to your clipboard \u2014 send it to the d360-writer team (Teams / Slack / email).":"\u2713 Copied the prompt to your clipboard \u2014 paste it into your repo's coding agent.":i?"Couldn't reach your clipboard \u2014 select the feedback above and copy it manually.":"Couldn't reach your clipboard \u2014 select the prompt above and copy it manually."}),u&&i&&Pr(null),u&&!i&&Gi(!0)});return}if(!ta(c,a)){if(zi){if(a.upArrow){Tt(i=>Math.max(0,i-1));return}if(a.downArrow){Tt(i=>Math.min(mn.length-1,i+1));return}if(a.tab){v("/"+(mn[sn]?.name??"")+" "),Tt(0);return}if(a.return){let i=mn[sn];if(i){let h=T.trim().slice(1).split(/\s+/).slice(1).join(" ");if(Gc(i.usage)&&!h){v("/"+i.name+" "),Tt(0);return}io("/"+i.name+(h?" "+h:""));return}}}else{if(a.upArrow){if(T!==""&&St===null){ao(-1);return}let i=yr.current;if(!i.length)return;let h=St===null?i.length-1:Math.max(0,St-1);Vn(h),v(i[h]??"");return}if(a.downArrow){if(T!==""&&St===null){ao(1);return}let i=yr.current;if(St===null)return;let h=St+1;h>=i.length?(Vn(null),v("")):(Vn(h),v(i[h]??""));return}}if(a.return){io();return}if(a.backspace||a.delete){P();return}if(a.escape){v(""),Tt(0),Le(),ct([]),an(null),Fn.current=!0;return}c&&!a.ctrl&&!a.meta&&Zi(c)}}}),Te(()=>{if(N||M)return;let c=wt.current.shift();c!==void 0&&(br([...wt.current]),io(c))},[N,M,io]),K(ne,{flexDirection:"column",width:Me,children:[Sr!==null&&K(ne,{marginTop:1,flexDirection:"column",children:[Sr.truncated&&E(j,{dimColor:!0,children:"\u2026"}),E(j,{children:Sr.text})]}),N&&(zn?E(ww,{p:zn}):E(hw,{startTime:dt.current,chars:Wd})),!N&&Wi?E(mw,{text:Wi}):null,E(ne,{borderStyle:"round",borderColor:Yi.prod?"yellow":q,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:T?ea.map((c,a)=>{let i=k.text.slice(c.start,c.end),h=a===cr(ea,k.pos),u=Math.min(k.pos,c.end)-c.start;return K(j,{children:[E(j,{color:q,children:a===0?"> ":" "}),h?K(fr,{children:[i.slice(0,u),E(nn,{ch:i[u]??" "}),i.slice(u+1)]}):i||" "]},`${a}-${c.start}`)}):K(j,{children:[E(j,{color:q,children:"> "}),vr?E(nn,{ch:" "}):he&&!N&&Ke?K(fr,{children:[E(nn,{ch:Ke[0],dim:!0}),E(j,{color:"gray",children:Ke.slice(1)})]}):he&&!N?K(fr,{children:[E(nn,{ch:he[0],dim:!0}),E(j,{color:"gray",children:he.slice(1)}),E(j,{dimColor:!0,children:" (tab)"})]}):(Tr.isSetup||!Md)&&!N?K(fr,{children:[E(nn,{ch:Tr.text[0],dim:!0}),E(j,{color:"gray",children:Tr.text.slice(1)})]}):E(nn,{ch:" "})]})}),Ui.length>0&&E(ne,{flexDirection:"column",paddingX:1,children:Ui.map((c,a)=>E(j,{color:"gray",children:`\u29D7 queued: ${c}`},`${a}-${c.slice(0,24)}`))}),Xn?E(zc,{tab:Xn.tab,width:Me,version:o,engineVersion:Dd}):pt?K(ne,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:"Select model"}),E(j,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),We.map((c,a)=>K(j,{color:a===pt.cursor?q:void 0,children:[a===pt.cursor?"\u276F ":" ",`${a+1}. ${c.label}${a===pt.current?" \u2714":""}`.padEnd(16),E(j,{color:"gray",children:c.desc})]},c.label)),E(j,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):He?K(ne,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:"Switch connection profile"}),He.rows.map((c,a)=>K(j,{color:a===He.cursor?q:void 0,children:[a===He.cursor?"\u276F ":" ",`${a+1}. ${c.name}${a===He.current?" \u2714":""}`.padEnd(20),E(j,{color:"gray",children:`${c.env} \xB7 ${c.who??"not signed in"}`}),c.prod?E(j,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},c.name)),E(j,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):qe?K(ne,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:"Pick your Document360 environment"}),qe.rows.map((c,a)=>K(j,{color:a===qe.cursor?q:void 0,children:[a===qe.cursor?"\u276F ":" ",`${a+1}. ${c.name}`.padEnd(16),E(j,{color:"gray",children:c.apiUrl})]},c.name)),E(j,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):me?K(ne,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:"Switch workspace"}),E(j,{dimColor:!0,children:`environment ${me.environment} \xB7 project ${me.projectName??`${me.projectId.slice(0,8)}\u2026`}`}),me.rows.map((c,a)=>K(j,{color:a===me.cursor?q:void 0,children:[a===me.cursor?"\u276F ":" ",`${a+1}. ${c.name}${a===me.current?" \u2714":""}`.padEnd(30),E(j,{color:"gray",children:c.type??""})]},c.id)),E(j,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):ve?K(ne,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:"Choose project"}),E(j,{dimColor:!0,children:`environment ${ve.environment}`}),ve.rows.map((c,a)=>K(j,{color:a===ve.cursor?q:void 0,children:[a===ve.cursor?"\u276F ":" ",`${a+1}. ${c.name}${a===ve.current?" \u2714":""}`.padEnd(30),E(j,{color:"gray",children:c.sub??""})]},c.id)),E(j,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):we?(()=>{let a=Math.min(Math.max(0,we.cursor-Math.floor(7)),Math.max(0,we.rows.length-14)),i=we.rows.slice(a,a+14),h=we.rows.filter(u=>u.checked).length;return K(ne,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:`Which folders back the user docs? (${h} selected of ${we.rows.length})`}),a>0?E(j,{dimColor:!0,children:` \u2191 ${a} more`}):null,i.map((u,y)=>{let b=a+y;return K(j,{color:b===we.cursor?q:void 0,children:[b===we.cursor?"\u276F ":" ",u.checked?"\u25C9 ":"\u25CB ",u.path.padEnd(Math.min(48,Me-34)),E(j,{color:"gray",children:No(u)})]},u.path)}),a+14<we.rows.length?E(j,{dimColor:!0,children:` \u2193 ${we.rows.length-a-14} more`}):null,E(j,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():Be?K(ne,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:"Which category? (pick one to scope to)"}),Be.rows.map((c,a)=>{let i=a===Be.cursor,h=`${a+1}.`.padEnd(3);return K(j,{color:i?q:void 0,children:[i?"\u276F ":" ",`${h} ${c.label} (${c.count})`.padEnd(Math.min(44,Math.max(20,Me-24))),E(j,{color:"gray",children:` ${c.token}`})]},c.token)}),E(j,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):Xe?K(ne,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),Xe.rows.map((c,a)=>{let i=a===Xe.cursor,h=c.indent?" ":" ",u=`${a+1}.`.padEnd(3);return K(j,{color:i?q:void 0,bold:c.kind==="category"&&!i,children:[i?"\u276F ":" ",`${h}${u} ${c.label}`.padEnd(Math.min(56,Me-24)),c.note?E(j,{color:"gray",children:c.note}):null]},`${c.kind}:${c.paths.join(",")}`)}),E(j,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):$e?K(ne,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:`Preview article${$e.query?` \u2014 filter: ${$e.query}`:" (type to filter)"}`}),to.length===0?E(j,{color:"gray",children:"no articles match"}):to.map((c,a)=>K(j,{color:a===$e.cursor?q:void 0,children:[a===$e.cursor?"\u276F ":" ",c]},c)),E(j,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):xe?K(ne,{flexDirection:"column",paddingX:1,children:[E(j,{color:q,bold:!0,children:`Resume session${xe.query?` \u2014 filter: ${xe.query}`:" (type to filter)"}`}),no.length===0?E(j,{color:"gray",children:"no sessions match"}):no.map((c,a)=>K(j,{color:a===xe.cursor?q:void 0,children:[a===xe.cursor?"\u276F ":" ",c.name.slice(0,28).padEnd(30),E(j,{color:a===xe.cursor?q:"gray",children:c.firstPrompt.slice(0,Math.max(10,Me-40))})]},c.uuid)),E(j,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):zi?K(ne,{flexDirection:"column",children:[mn.map((c,a)=>K(j,{color:a===sn?q:void 0,children:[a===sn?"\u276F ":" ",c.usage.padEnd(22)," ",E(j,{color:a===sn?q:"gray",children:c.name==="model"&&$r?`${c.desc} (currently ${$r})`:c.desc})]},c.name)),E(j,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!N&&!T&<.length>0?K(ne,{flexDirection:"column",paddingX:1,children:[Mi?E(j,{color:q,children:Mi}):null,lt.map((c,a)=>{let i=Ct(c),h=i.slice(0,Math.max(20,Me-5)),u=Me-h.length-7,y=u>=12?(Zc(c)??Bc(i)).slice(0,u):"";return K(j,{children:[E(j,{color:q,children:a+1})," ",h,y?E(j,{dimColor:!0,children:` \u2014 ${y}`}):null]},i)}),E(j,{dimColor:!0,children:`press 1-${lt.length} to fill \xB7 esc cancel`})]}):E(ne,{paddingX:1,children:K(j,{color:"gray",children:[Yi.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${$r??"model n/a"}${t.kind==="api"?qi>0?` \xB7 ${be(qi)}`:"":Hi>0?` \xB7 ${rt(Hi)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}W();import{jsx as vw}from"react/jsx-runtime";async function Ed(e=process.cwd(),t="auto",n,o="0.0.0"){let r=bw(t);r.kind==="none"&&(console.error(""),console.error(R("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${O("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${O("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=kw(vw(Ad,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
|
|
410
|
+
`),process.exit(0)}W();import{writeCrashLog as Nd,isBenignTransportError as $w}from"document360-engine";var Id=!1;function Ai(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function _d(e){if(Id)return;Id=!0;let t=(n,o)=>{if($w(o)){Nd({kind:n,level:"transport",message:Ai(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=Nd({kind:n,level:"fatal",message:Ai(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
|
|
411
|
+
`+R(`\u2717 d360-writer crashed: ${Ai(o)}`)+`
|
|
412
412
|
`),r&&process.stderr.write(f(` Crash details: ${r}`)+`
|
|
413
413
|
`+f(" Run: d360-writer logs")+`
|
|
414
|
-
`),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var Cw
|
|
414
|
+
`),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var Pw=Cw(import.meta.url),hr=Pw("../package.json");_d("d360-writer");var Ie=new xw;function Ei(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}Ie.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=>{Ei(e),await go({profile:e.profile,manual:e.manual})});Ie.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Ei(e),await fa({profile:e.profile})});Ie.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Ei(e),await pa({profile:e.profile})});var Ni=Ie.command("profile").description("Manage connection profiles for the current repo");Ni.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>wo(process.cwd()));Ni.command("use <name>").description("Set the default profile for this repo").action(e=>yo(process.cwd(),e));Ni.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>ko(process.cwd(),e));var Od=Ie.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");Od.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>Gt(process.cwd(),e.profile));Od.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await sa(process.cwd(),e,t.profile)});var Ld=Ie.command("project").description("Choose the Document360 project for this repo (active profile's identity)");Ld.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>fo(process.cwd(),e.profile));Ld.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await aa(process.cwd(),e,t.profile)});Ie.command("init").description("Scaffold .d360-writer/config.json for this repo (interactive)").action(async()=>{let{initCommand:e}=await Promise.resolve().then(()=>(Ro(),Ha));await e()});Ie.command("logs").description("Show the API + crash log files (send these to support when reporting a problem)").action(()=>wa());Ie.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(()=>(Uo(),Vl)),n=await t(process.cwd(),hr.version);for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});Ie.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(hr.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(Rw.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 ya(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 Oc(e.cwd,e.auth,e.profile,hr.version):await Ed(e.cwd,e.auth,e.profile,hr.version)});Ie.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
|