document360-writer 0.5.159 → 0.5.160

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.
Files changed (2) hide show
  1. package/dist/cli.js +38 -38
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -284,7 +284,7 @@ try {
284
284
  `)),{kind:"clear"}}async function bs(){return{kind:"exit"}}Yo();z();import{readMcpConfig as Ss,writeMcpConfig as Xl}from"document360-engine";async function zo(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(Wh(),{kind:"continue"}):t==="add"?(Fh(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(Bh(e.slice(1)),{kind:"continue"}):(console.log(S(`Unknown /mcp subcommand: ${t}`)),console.log(m("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function Wh(){let e=Ss(),t=Object.keys(e.servers);if(t.length===0){console.log(m(`
285
285
  No MCP servers registered. Add one with /mcp add <name> <type> <ref>
286
286
  `));return}console.log(""),console.log("Registered MCP servers (~/.document360-writer/mcp.json):");for(let n of t){let o=e.servers[n];if(o.type==="stdio")console.log(` ${W(n)} ${m("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?m(` [headers: ${r.join(", ")}]`):"";console.log(` ${W(n)} ${m(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function Fh(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(S("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(S(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=Ss(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let a={};for(let u=1;u<o.length;u++)if(o[u]==="-H"||o[u]==="--header"){let p=o[++u],b=p?.match(/^([^:=]+)[:=](.+)$/);if(!b){console.log(S(`-H expects key:value (no spaces). Got: ${p??"(nothing)"}`));return}a[b[1].trim()]=b[2].trim()}else{console.log(S(`Unexpected argument: ${o[u]}. After the URL, only -H key:value is allowed.`));return}s={type:n,url:o[0],headers:Object.keys(a).length>0?a:void 0}}r.servers[t]=s,Xl(r),console.log(""),console.log(_(`\u2713 Registered "${t}" (${n})`)),console.log(B(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(m(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function Bh(e){let t=e[0];if(!t){console.log(S("Usage: /mcp remove <name>"));return}let n=Ss();if(!n.servers[t]){console.log(S(`No server named "${t}".`));return}delete n.servers[t],Xl(n),console.log(_(`\u2713 Removed "${t}".`)),console.log(m(" Run /clear to drop it from the current session immediately."))}z();import{readFileSync as Cf}from"node:fs";import{join as Rf}from"node:path";import{select as Sf}from"@inquirer/prompts";import{computeSyncStatus as ir,planPartitions as Pf,relatedArticlePaths as Tf,resolveModelForOperation as Df,runPartitioned as Af,loadProfileMap as Ef,resolveActiveProfile as jf,resolveCrossLinks as Nf,applyStructureOrder as Ic,orderSyncLine as Oc,applyRelatedArticles as _c,relatedSyncLine as Lc}from"document360-engine";import ne from"picocolors";import ac from"wrap-ansi";import js from"string-width";z();import mt from"picocolors";import Ps from"wrap-ansi";import Ts from"string-width";var dn=[{name:"init",usage:"/init",desc:"Pick an environment, scaffold .d360-writer/config.json, and set up the builder hand-off (prints the one-paste prompt)",group:"start"},{name:"login",usage:"/login",desc:"Sign in to Document360 (browser)",group:"start"},{name:"project",usage:"/project [name]",desc:"Choose the Document360 project (picker; lists all you can access)",group:"start"},{name:"devhints",usage:"/devhints",desc:"Re-show/refresh the builder hand-off prompt (set up by /init; run anytime to hand your repo agent the latest)",group:"start"},{name:"scope",usage:"/scope",desc:"Choose which repo folders back the docs (monorepos)",group:"start"},{name:"genre",usage:"/genre [web|cli|service|library|auto]",desc:"Set/show the product genre \u2014 picks the docs craft playbook (usually auto-detected; set it if it guessed wrong)",group:"start"},{name:"mcp",usage:"/mcp [list|add|remove]",desc:"Connect MCP servers (Notion, Linear, \u2026)",group:"start"},{name:"discover",usage:"/discover",desc:"Interview your builder to understand the product (identity, mental model, misconceptions, positioning) \u2192 pins a product brief that grounds the docs; asks focused questions and loops until confident",group:"docs"},{name:"draft",usage:"/draft [<feature>]",desc:"Draft a feature's articles from its PRDs/specs in .d360-writer/input/ + the code",group:"docs"},{name:"document",usage:"/document [<what>] [--publish]",desc:"Document a shipped change \u2014 the agent picks the action (new section/article/update); bare: act on builder requests",group:"docs"},{name:"write",usage:"/write [--preview|--scope <cat>|<path>] [--rewrite] [--concurrency N]",desc:"Write the planned articles in parallel (starts immediately; --preview shows plan + cost first; --rewrite regenerates already-written articles; --concurrency default 3)",group:"docs"},{name:"screenshot",usage:"/screenshot [author|capture|checklist|list] [id|path|--all|--failed|--retry-blocked]",desc:"Screenshots, one family \u2014 bare: pick what to do; author: write capture specs; capture: take the shots (--failed re-runs broken ones; --retry-blocked re-tries shots waiting on data); checklist: what to stage + dev test-id requests; list: status + what to stage",group:"docs"},{name:"preview",usage:"/preview [path|id]",desc:"Render an article (no arg: pick from tracked)",group:"docs"},{name:"publish",usage:"/publish [path|--all|--screenshots]",desc:"Publish to Document360 (no arg: pick; --all: every candidate; --screenshots: re-save articles with captured shots so images embed)",group:"publish"},{name:"check",usage:"/check [<category|path>] [--fix]",desc:"Check docs for leaked internals, invented commands, and stale facts (deterministic, no tokens). Scope to a category/path; --fix has the agent correct the findings in place",group:"docs"},{name:"review",usage:"/review [<category|path> | --all] [--fix]",desc:"Independent senior-editor review: style guide, terminology/voice, grammar/clarity, structure, improvement suggestions. Bare: pick a category or everything; --all reviews the whole KB; --fix applies the corrections in place",group:"docs"},{name:"reorder",usage:"/reorder [<category> | --all]",desc:"Reorder articles within a category to the best reading order (renumbers NN- prefixes, fixes references + map); bare: pick a category or everything; new order syncs to Document360 on next /publish",group:"docs"},{name:"structure",usage:"/structure",desc:"Show the documentation reading order (categories \u2192 articles) as it will appear on Document360",group:"docs"},{name:"roadmap",usage:"/roadmap [done [step]]",desc:"Show the docs campaign (the multi-session plan the agent maintains) \u2014 progress + next step; `done` marks the next open step finished (add words from a title to pick another)",group:"docs"},{name:"audit",usage:"/audit [--auto on|off]",desc:"Gap analysis: code vs docs vs Document360 (what changed); --auto runs it at launch when code changed",group:"publish"},{name:"inbox",usage:"/inbox",desc:"Act on messages from the repo's coding agent (requests to document, answers to your questions)",group:"publish"},{name:"catch-up",usage:"/catch-up [--publish]",desc:"Process ALL pending work (hints + requests + drift) \u2192 write \u2192 push to Document360 (bare = drafts; --publish goes live)",group:"publish"},{name:"pull",usage:"/pull [<path> | --status | --baseline]",desc:"Bring Document360 down: pull portal edits + import NEW portal articles. --status: drift report only \xB7 --baseline: set a sync base \xB7 <path>: one article / resolve a conflict",group:"publish"},{name:"resolve",usage:"/resolve [<path>]",desc:"Resolve conflicts (edited both here and on the portal): shows the diff, then keep local (publish), take portal (pull), or skip \u2014 for each. Bare: walk them all",group:"publish"},{name:"convert",usage:"/convert [--scope <folder>] [--run]",desc:"Convert tracked articles to DFM (one-off legacy migration)",group:"publish"},{name:"profile",usage:"/profile [name|add <name> [env]]",desc:"Switch/create a Document360 connection (picker; s = session)",group:"setup"},{name:"workspace",usage:"/workspace [name]",desc:"Switch the Document360 workspace (picker)",group:"setup"},{name:"model",usage:"/model [name|default]",desc:"Set the Claude model for d360-writer",group:"setup"},{name:"logout",usage:"/logout",desc:"Sign out + clear project/workspace selection (then /login to re-pick)",group:"setup"},{name:"allow-prod",usage:"/allow-prod",desc:"Authorize writes to a production profile",group:"setup"},{name:"doctor",usage:"/doctor",desc:"Health-check: auth, profile, workspace, map, API",group:"setup"},{name:"update",usage:"/update",desc:"Update d360-writer \u2014 and d360-capture when installed \u2014 to the latest versions (then relaunch)",group:"setup"},{name:"feedback",usage:"/feedback",desc:"Copy the repo's open d360-writer tool-feedback to your clipboard, to relay to the d360-writer team",group:"setup"},{name:"reset",usage:"/reset",desc:"[DANGER] Delete all d360-writer files (docs, config, screenshots); types repo name to confirm",group:"setup"},{name:"resume",usage:"/resume [name]",desc:"Resume a session (no arg lists them)",group:"session"},{name:"rename",usage:"/rename [name]",desc:"Name the session (no arg: suggest one)",group:"session"},{name:"clear",usage:"/clear",desc:"Clear the screen + reset the conversation (resumable)",group:"session"},{name:"help",usage:"/help",desc:"Show this help",group:"session"},{name:"exit",usage:"/exit",desc:"Quit",group:"session"}],Ql={"/catch-up":"write up everything your builder flagged","/audit":"check the code for anything new or missing in the docs","/discover":"interview your builder so the docs are grounded in the real product","/pull":"pull edits + new articles from Document360","/publish":"publish your drafts to Document360","/write":"author the planned articles","/draft":"plan articles from PRDs + the code","/login":"sign in to Document360","/workspace":"choose the Document360 workspace","/project":"choose the Document360 project","/scope":"choose which folders back the docs","/genre":"set this repo's product type (picks the docs playbook)","/init":"set up this repo","/screenshot":"work the screenshot pipeline (author specs, take shots)","/doctor":"run a health check"};function Jl(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(Ql[n])return Ql[n];let o=dn.find(r=>r.name===t);return o?o.desc:""}function Zl(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return dn.filter(n=>n.name.startsWith(t))}function ec(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}var qh=new RegExp(`^\\s*/(?:${dn.map(e=>e.name).join("|")})(?:\\s|$)`),tc=e=>qh.test(e),nc=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),oc=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),rc=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function Hh(e){let t=e.replace(/\r/g,"").split(`
287
- `),n=[],o=0;for(;o<t.length;){let r=t[o];if(/^\s*```/.test(r)){let u=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)u.push(t[o++]);o++,n.push({kind:"code",lines:u});continue}if(nc(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&oc(t[o+1])){let u=rc(r);o+=2;let p=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)p.push(rc(t[o++]));n.push({kind:"table",header:u,rows:p});continue}let s=r.match(/^(#{1,6})\s+(.*)$/);if(s){n.push({kind:"heading",level:s[1].length,text:s[2]}),o++;continue}if(/^\s*([-*]|\d+\.)\s+/.test(r)){let u=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);){let p=t[o++];u.push({ordered:/^\s*\d+\.\s+/.test(p),text:p.replace(/^\s*([-*]|\d+\.)\s+/,"")})}n.push({kind:"list",items:u});continue}if(r.trim()===""){o++;continue}if(tc(r)){n.push({kind:"para",text:r.trim()}),o++;continue}let a=[];for(;o<t.length&&t[o].trim()!==""&&!/^\s*```/.test(t[o])&&!/^(#{1,6})\s/.test(t[o])&&!/^\s*([-*]|\d+\.)\s+/.test(t[o])&&!tc(t[o])&&!nc(t[o])&&!(t[o].includes("|")&&o+1<t.length&&oc(t[o+1]));)a.push(t[o++]);n.push({kind:"para",text:a.join(" ")})}return n}function Ds(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?mt.bold(t.slice(2,-2)):t.startsWith("`")?W(t.slice(1,-1)):mt.italic(t.slice(1,-1)))}var Vh=(e,t)=>e+" ".repeat(Math.max(0,t-Ts(e)));function Gh(e,t,n){let o=e.length,r=e.map((v,D)=>Math.max(Ts(v),...t.map(E=>Ts(E[D]??"")))),s=Math.max(24,n),a=3*o+1,u=[...r],p=()=>u.reduce((v,D)=>v+D,0)+a,b=0;for(;p()>s&&b++<1e4;){let v=-1,D=6;for(let E=0;E<o;E++)u[E]>D&&(D=u[E],v=E);if(v===-1)break;u[v]-=1}let k=(v,D,E)=>mt.gray(v+u.map(U=>"\u2500".repeat(U+2)).join(D)+E),$=mt.gray("\u2502"),x=(v,D)=>{let E=u.map((G,H)=>{let se=v[H]??"",qe=D?mt.bold(se):Ds(se);return Ps(qe,G,{hard:!0}).split(`
287
+ `),n=[],o=0;for(;o<t.length;){let r=t[o];if(/^\s*```/.test(r)){let u=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)u.push(t[o++]);o++,n.push({kind:"code",lines:u});continue}if(nc(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&oc(t[o+1])){let u=rc(r);o+=2;let p=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)p.push(rc(t[o++]));n.push({kind:"table",header:u,rows:p});continue}let s=r.match(/^(#{1,6})\s+(.*)$/);if(s){n.push({kind:"heading",level:s[1].length,text:s[2]}),o++;continue}if(/^\s*([-*]|\d+\.)\s+/.test(r)){let u=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);){let p=t[o++];u.push({ordered:/^\s*\d+\.\s+/.test(p),text:p.replace(/^\s*([-*]|\d+\.)\s+/,"")})}n.push({kind:"list",items:u});continue}if(r.trim()===""){o++;continue}if(tc(r)){n.push({kind:"para",text:r.trim()}),o++;continue}let a=[];for(;o<t.length&&t[o].trim()!==""&&!/^\s*```/.test(t[o])&&!/^(#{1,6})\s/.test(t[o])&&!/^\s*([-*]|\d+\.)\s+/.test(t[o])&&!tc(t[o])&&!nc(t[o])&&!(t[o].includes("|")&&o+1<t.length&&oc(t[o+1]));)a.push(t[o++]);n.push({kind:"para",text:a.join(" ")})}return n}function Ds(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?mt.bold(t.slice(2,-2)):t.startsWith("`")?W(t.slice(1,-1)):mt.italic(t.slice(1,-1)))}var Vh=(e,t)=>e+" ".repeat(Math.max(0,t-Ts(e)));function Gh(e,t,n){let o=e.length,r=e.map((v,D)=>Math.max(Ts(v),...t.map(E=>Ts(E[D]??"")))),s=Math.max(24,n),a=3*o+1,u=[...r],p=()=>u.reduce((v,D)=>v+D,0)+a,b=0;for(;p()>s&&b++<1e4;){let v=-1,D=6;for(let E=0;E<o;E++)u[E]>D&&(D=u[E],v=E);if(v===-1)break;u[v]-=1}let k=(v,D,E)=>mt.gray(v+u.map(U=>"\u2500".repeat(U+2)).join(D)+E),$=mt.gray("\u2502"),x=(v,D)=>{let E=u.map((G,H)=>{let se=v[H]??"",Be=D?mt.bold(se):Ds(se);return Ps(Be,G,{hard:!0}).split(`
288
288
  `)}),U=Math.max(...E.map(G=>G.length)),L=[];for(let G=0;G<U;G++)L.push(u.map((H,se)=>`${$} ${Vh(E[se][G]??"",H)} `).join("")+$);return L.join(`
289
289
  `)},j=[k("\u250C","\u252C","\u2510"),x(e,!0)];return j.push(t.length===0?k("\u2514","\u2534","\u2518"):k("\u251C","\u253C","\u2524")),t.forEach((v,D)=>{j.push(x(v,!1)),j.push(D===t.length-1?k("\u2514","\u2534","\u2518"):k("\u251C","\u253C","\u2524"))}),j.join(`
290
290
  `)}function Yh(e,t){switch(e.kind){case"heading":return mt.bold(e.text);case"hr":return mt.gray("\u2500".repeat(t));case"para":return Ps(Ds(e.text),t);case"list":{let n=0;return e.items.map(o=>{let r=o.ordered?`${++n}.`:"\u2022",s=" ".repeat(2+r.length+1),[a="",...u]=Ps(Ds(o.text),Math.max(10,t-s.length)).split(`
@@ -312,14 +312,14 @@ ${s}${p}`).join("")}).join(`
312
312
  `+Zh[e.tone](Ln(Ns(e.text)));case"done":{let o=e.inTokens&&e.inTokens>0?` \xB7 ${Fn(e.inTokens)} in${e.cachedPct!=null?` (${e.cachedPct}% cached)`:""}`:"";return`
313
313
  `+(e.ok?ne.magenta("\u2736 "):ne.red("\u2736 "))+ne.gray(`Cooked for ${Bn(e.seconds)} \xB7 ${Fn(e.tokens)} tokens out${o}`+(e.costUsd>0?` \xB7 ${Pe(e.costUsd)}`:""))}}}function lc(e,t){return e.map(n=>Is(n,t)).join(`
314
314
  `)}import{resolveActiveProfile as ef,loadTokens as tf,isExpired as nf,decodeJwtClaims as cc}from"document360-engine";function of(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function Ue(e,t){try{let n=ef(e,t),o=tf(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(nf(o)&&!o.refreshToken)return{ok:!1,reason:`Your Document360 session expired (profile "${n.name}"). Run /login.`};let r=n.project.projectId;if(r){let a={...cc(o.idToken)??{},...cc(o.accessToken)??{}}.doc360_project_id;if(typeof a=="string"&&a&&a!==r)return{ok:!1,reason:`Your Document360 session is signed into a different project than profile "${n.name}" (this profile's project is ${of(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}import{existsSync as Ms,readFileSync as Bs}from"node:fs";import{isAbsolute as Jo,join as Zo,resolve as er}from"node:path";import O from"picocolors";function qn(e,t){let n=[],o="";for(let r of e.split(/\s+/).filter(Boolean))for(o.length?o.length+1+r.length<=t?o+=` ${r}`:(n.push(o),o=r):o=r;o.length>t;)n.push(o.slice(0,t)),o=o.slice(t);return o&&n.push(o),n}function Ko(e){if(e.length===0)return[];let t=(s,a)=>`${s}${"\u2500".repeat(78)}${a}`,n=(s="")=>`\u2502 ${s.padEnd(76)} \u2502`,o=[`\u2B06 d360-writer upgraded \u2014 ${e.length===1?"one improvement affects":`${e.length} improvements affect`} the docs you've already written:`,"",t("\u250C","\u2510")];e.forEach((s,a)=>{a>0&&o.push(t("\u251C","\u2524")),o.push(n());for(let u of qn(`${a+1}. ${s.feature}`,76))o.push(n(u));o.push(n());for(let u of qn(s.why,73))o.push(n(` ${u}`));o.push(n())}),o.push(t("\u2514","\u2518")),o.push("");let r=e.length>1;return o.push(`\u2713 ${r?"These are":"This is"} now on your docs roadmap \u2014 each launch shows your next step below (/roadmap shows the full campaign).`),o}import{readProjectConfig as hn,screenshotPlaceholderIds as kc,DEFAULT_CAPTURE_DIR as tr,DEFAULT_OUTPUT_DIR as cf,DEFAULT_DOCS_DIR as qs}from"document360-engine";import{createHash as rf}from"node:crypto";import{readFileSync as sf,writeFileSync as af}from"node:fs";import{captureStatePath as dc}from"document360-engine";var uc={version:1,shots:{}};function pc(e){return rf("sha1").update(e).digest("hex").slice(0,12)}function _t(e){try{let t=JSON.parse(sf(dc(e),"utf8").replace(/^/,""));return!t||typeof t!="object"||t.version!==1||!t.shots?{...uc,shots:{}}:{version:1,shots:t.shots}}catch{return{...uc,shots:{}}}}function lf(e,t){af(dc(e),`${JSON.stringify(t,null,2)}
315
- `,"utf8")}function Os(e){return e&&/data-testid|\btest-?id\b|has(?:n't| not) landed/i.test(e)?"testid":"data"}function hc(e,t,n){if(t.length===0)return;let o=_t(e);for(let r of t){let s=r.specSource?pc(r.specSource):void 0;o.shots[r.id]={outcome:r.outcome,at:n,...r.reason?{reason:r.reason}:{},...r.outcome==="skipped"?{blockedBy:Os(r.reason)}:{},...s?{specHash:s}:{}}}lf(e,o)}function _s(e,t,n){let o=e.shots[t];return!o||n===null||!o.specHash||o.specHash!==pc(n)?null:o}function fc(e){let t=_t(e).shots;return Object.keys(t).filter(n=>t[n].outcome==="failed").sort()}function Ls(e,t,n){let o=_s(_t(e),t,n);return o?.outcome==="failed"?o.reason??null:null}var bc=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function mc(e){let t=e.includes("--detail")||e.includes("-d"),n=e.find(o=>o!=="--detail"&&o!=="-d");return{mode:"list",scope:n?bc(n):void 0,...t?{detail:!0}:{}}}function Hn(e){let t=(e[0]??"").toLowerCase();if(t==="capture")return{mode:"capture",rest:e.slice(1)};if(t==="checklist"||t==="setup")return{mode:"checklist"};if(t==="list")return mc(e.slice(1));t==="author"&&(e=e.slice(1));let n=!e.includes("--no-setup"),o=e.filter(s=>s!=="--no-setup");if(o[0]==="--list")return mc(o.slice(1));let r=o[0];return r?r==="--all"?{mode:"all",setup:n}:/[\\/]/.test(r)||r.endsWith(".md")?{mode:"scope",scope:bc(r),setup:n}:{mode:"single",id:r}:{mode:"list",picker:!0}}function We(e,t){let n=hn(e),o=n?.captureDir??tr,r=n?.outputDir??cf,s=(u,p)=>Jo(u)?Zo(u,p):er(e,u,p),a=_t(e);return kc(e,{scope:t}).map(({id:u,file:p})=>{let b=s(o,`${u}.spec.ts`),k=null;if(Ms(b))try{k=Bs(b,"utf8")}catch{}let $=Ms(s(r,`${u}.png`)),x=k===null?null:_s(a,u,k),j=k!==null&&df(k),v=$?"captured":k===null?"placeholder":j||x?.outcome==="skipped"?"blocked":x?.outcome==="failed"?"broken":"spec",D=k===null?void 0:xc(k),E=j?pf(k):x?.reason,U=j?"testid":x?.outcome==="skipped"?Os(x.reason):void 0;return{id:u,file:p,state:v,...D?{mutates:D.mutates,...D.declared?{}:{undeclared:!0}}:{},...k!==null&&gc(k).length>0?{unguardedWaits:gc(k)}:{},...v==="blocked"||v==="broken"?{...E?{reason:E}:{},...U?{blockedBy:U}:{}}:{}}})}function nr(e,t){let n=hn(e)?.captureDir??tr,o=Jo(n)?Zo(n,`${t}.spec.ts`):er(e,n,`${t}.spec.ts`);try{return Bs(o,"utf8")}catch{return null}}function $c(e,t){let n=hn(e)?.captureDir??tr;return Ms(Jo(n)?Zo(n,`${t}.spec.ts`):er(e,n,`${t}.spec.ts`))}function uf(e,t,n){let o=[n.trim()];for(let r=t+1;r<e.length;r++){let s=/^\s*\/\/\s?(.*)$/.exec(e[r]);if(!s)break;let a=s[1].trim();if(!a||/^(CAPTURE-[A-Z]+:|TODO\b|NOTE\b|Grounding\b|\d+\.\s)/.test(a)||(o.push(a),o.join(" ").length>400))break}return o.join(" ")}function xc(e){let t=e.split(/\r?\n/),n=t.findIndex(u=>/^\s*\/\/\s*CAPTURE-SAFETY:\s*(readonly|mutates)\b/i.test(u)),o=n>=0?/^\s*\/\/\s*CAPTURE-SAFETY:\s*(readonly|mutates)\b[\s—:–-]*(.*)$/i.exec(t[n]):null;if(o){let u=uf(t,n,o[2]??"");return{mutates:o[1].toLowerCase()==="mutates",declared:!0,what:u||void 0}}let r=/setInputFiles/.test(e),s=/\{\s*name:\s*['"][^'"]*\b(create|import|save|apply|confirm|delete|submit|send|mint)\b[^'"]*['"][^}]*\}\s*\)\s*\.click\(/i.test(e),a=/\.fill\(/.test(e);return{mutates:r||a&&s,declared:!1}}function df(e){return/(^|\n)\s*test\.skip\s*\(\s*['"`]/.test(e)}function pf(e){let t=/\/\/\s*CAPTURE-TODO:\s*(\{.*\})\s*$/m.exec(e),n,o;if(t)try{let s=JSON.parse(t[1]);n=s.testid,o=s.file}catch{}return`Inert until your developers add ${n?`data-testid="${n}"${o?` in ${o}`:""}`:"a stable data-testid"} \u2014 the spec is skipped at compile time, so no capture run can produce this shot. /screenshot checklist builds the hand-off.`}function gc(e){let t=r=>{if(/^\s*\*/.test(r))return"";let s=/(?<!:)\/\//.exec(r);return s?r.slice(0,s.index):r},n=[],o=e.split(/\r?\n/).map(t);for(let[r,s]of o.entries()){if(!/\.waitFor\s*\(/.test(s))continue;let a=s;for(let u=r+1;u<o.length&&!/;\s*$/.test(a.trim())&&u<r+4;u++)a+=o[u];/\.catch\s*\(/.test(a)||n.push(r+1)}return n}function vc(e){return(e??"").trim().replace(/[.\s]+$/,"")}function Cc(e,t){let n=hn(e)?.captureDir??tr,o=Jo(n)?Zo(n,`${t}.spec.ts`):er(e,n,`${t}.spec.ts`);try{return xc(Bs(o,"utf8"))}catch{return{mutates:!1,declared:!1}}}function or(e){return[...new Set(e.filter(t=>t.state==="captured").map(t=>t.file))].sort()}var hf={placeholder:"\u25CB",spec:"\u25D0",blocked:"\u2298",broken:"\u2717",captured:"\u25CF"},ff={placeholder:O.gray,spec:O.yellow,blocked:O.cyan,broken:O.red,captured:O.green},Rc=` ${O.green("\u25CF captured")} ${O.yellow("\u25D0 ready")} ${O.cyan("\u2298 blocked")} ${O.red("\u2717 broken")} ${O.gray("\u25CB to spec")}`;function st(e,t=n=>n){return`${t(e)} `}function mf(e){let t=e.replace(/\s+/g," ").trim().replace(/^Prerequisite not met:\s*/i,""),n=/^(.*?[a-z0-9)"'”’])\.(?:\s|$)/i.exec(t);return(n?n[1]:t).trim()}function Hs(e){let t=new Map;for(let n of e){if(n.state!=="blocked")continue;let o=(n.reason??"No reason recorded \u2014 re-run this capture to find out why.").replace(/\s+/g," ").trim(),r=n.blockedBy??"data",s=mf(o),a=`${r} ${s.toLowerCase()}`,u=t.get(a)??{reason:s,blockedBy:r,ids:[]};t.has(a)||t.set(a,u),u.ids.push(n.id)}return[...t.values()].sort((n,o)=>o.ids.length-n.ids.length||n.reason.localeCompare(o.reason))}function Sc(e){let t=Hs(e);if(t.length===0)return[];let n=t.filter(s=>s.blockedBy==="data"),o=t.filter(s=>s.blockedBy==="testid"),r=[""];if(n.length>0){let s=n.reduce((u,p)=>u+p.ids.length,0);r.push(` ${O.bold("Stage this data")} ${O.gray(`\u2014 unblocks ${s} shot${s===1?"":"s"} in ${n.length} action${n.length===1?"":"s"}`)}`);let a=8;for(let u of n.slice(0,a)){let p=qn(u.reason,86);r.push(` ${O.cyan(yt(`${u.ids.length}\xD7`,4))} ${p[0]??""}`);for(let k of p.slice(1))r.push(` ${k}`);let b=u.ids.slice(0,4).join(" \xB7 ");r.push(O.gray(` ${b}${u.ids.length>4?` \xB7 +${u.ids.length-4} more`:""}`))}n.length>a&&r.push(O.gray(` \u2026 ${n.length-a} more staging action${n.length-a===1?"":"s"} \u2014 /screenshot list --detail`))}if(o.length>0){let s=o.reduce((a,u)=>a+u.ids.length,0);r.push(` ${st("\u2298",O.cyan)}${s} shot${s===1?"":"s"} need${s===1?"s":""} a data-testid from your developers \u2014 ${O.bold("/screenshot checklist")} builds the hand-off.`)}return r}function Pc(e){let t=e.filter(o=>(o.unguardedWaits?.length??0)>0);if(t.length===0)return[];let n=t.reduce((o,r)=>o+(r.unguardedWaits?.length??0),0);return["",` ${st("\u26A0",O.yellow)}${t.length} spec${t.length===1?"":"s"} ${t.length===1?"has":"have"} ${n} unguarded wait${n===1?"":"s"}`+O.gray(" \u2014 on missing data these fail with a stack trace instead of telling you what to stage"),O.gray(` ${t.slice(0,6).map(o=>`${o.id}:${o.unguardedWaits.join(",")}`).join(" \xB7 ")}${t.length>6?` \xB7 +${t.length-6} more`:""}`),O.gray(` Re-author to guard them: ${O.bold("/screenshot author <id>")}`)]}function Tc(e){let t=e.filter(o=>o.undeclared);if(t.length===0)return[];let n=t.filter(o=>o.mutates);return["",` ${st("\u26A0",O.yellow)}${t.length} spec${t.length===1?"":"s"} carr${t.length===1?"ies":"y"} no CAPTURE-SAFETY declaration`+(n.length>0?O.gray(` \u2014 ${n.length} of them read as "writes real data" by heuristic, so bulk capture benches ${n.length===1?"it":"them"}`):""),O.gray(` ${t.slice(0,6).map(o=>o.id).join(" \xB7 ")}${t.length>6?` \xB7 +${t.length-6} more`:""}`),O.gray(` Re-author them to declare it: ${O.bold("/screenshot author <id>")}`)]}var Xo=(e,t)=>e.length>=t?e:e+" ".repeat(t-e.length),yt=(e,t)=>e.length>=t?e:" ".repeat(t-e.length)+e;function Dc(e,t){let n=e.replace(/\\/g,"/"),o=t.replace(/\\/g,"/").replace(/\/+$/,"");o&&(n===o||n.startsWith(`${o}/`))&&(n=n.slice(o.length+1));let r=n.split("/").filter(Boolean);return r.length>1?r[0]:""}var gf=new Set(["and","or","of","the","to","a","an","in","on","for","with","vs"]),yf=new Set(["ai","api","cli","ui","ux","url","id","http","https","json","xml","sdk","csv","pdf","oauth","sso","mfa","io","faq"]);function wf(e){return e.replace(/[-_]+/g," ").trim().split(/\s+/).filter(Boolean).map((n,o)=>{let r=n.toLowerCase();return yf.has(r)?r.toUpperCase():o>0&&gf.has(r)?r:r.charAt(0).toUpperCase()+r.slice(1)}).join(" ")}function Us(e){if(!e)return{num:"",name:"(docs root)"};let t=/^(\d+)[-_](.+)$/.exec(e);return{num:t?t[1]:"",name:wf(t?t[2]:e)}}function kf(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).pop()??e}function yc(e,t,n){let o=t>0?Math.round(e/t*n):0;return O.green("\u2588".repeat(o))+O.gray("\u2591".repeat(Math.max(0,n-o)))}function bf(e,t){let n=t>0?Math.round(e/t*100):0,o=yt(`${n}%`,4);return n===100?O.green(o):n>0?O.yellow(o):O.gray(o)}function Ac(e,t){let n=new Map;for(let o of e){let r=Dc(o.file,t),s=n.get(r)??[];n.has(r)||n.set(r,s),s.push(o)}return[...n.keys()].sort().map(o=>[o,n.get(o)])}function $f(e,t){let n=(L,G)=>L.filter(H=>H.state===G).length,o=e.length,r=n(e,"captured"),s=n(e,"spec"),a=n(e,"blocked"),u=n(e,"broken"),p=n(e,"placeholder"),b=new Set(e.map(L=>L.file)).size,k=Ac(e,t),$=[];$.push(` ${O.bold("Screenshots")} ${O.green(`${r}/${o} captured`)} ${O.gray("\xB7")} ${s>0?O.yellow(`${s} ready`):O.gray("0 ready")}`+(a>0?` ${O.gray("\xB7")} ${O.cyan(`${a} blocked`)}`:"")+(u>0?` ${O.gray("\xB7")} ${O.red(`${u} broken`)}`:"")+` ${O.gray("\xB7")} ${p>0?O.red(`${p} to spec`):O.gray("0 to spec")} `+O.gray(`across ${b} article${b===1?"":"s"}`));let x=o>0?Math.round(r/o*100):0;$.push(` [${yc(r,o,32)}] ${O.bold(`${x}%`)}`),$.push("");let j=k.map(([L])=>Us(L)),v=Math.min(32,Math.max(7,...j.map(L=>L.name.length))),D=L=>L.length>v?`${L.slice(0,v-1)}\u2026`:Xo(L,v),E=[{head:"Ready",w:5,state:"spec",color:O.yellow},...a>0?[{head:"Blocked",w:7,state:"blocked",color:O.cyan}]:[],...u>0?[{head:"Broken",w:6,state:"broken",color:O.red}]:[],{head:"To spec",w:7,state:"placeholder",color:O.red}];$.push(O.gray(` ${Xo("#",2)} ${Xo("Chapter",v)} ${yt("Captured",8)} ${E.map(L=>yt(L.head,L.w)).join(" ")} Progress`));for(let[L,[,G]]of k.entries()){let H=n(G,"captured"),se=G.length,{num:qe,name:fe}=j[L],Xe=H===se,me=D(fe),Qe=E.map(be=>{let He=n(G,be.state);return He>0?be.color(yt(String(He),be.w)):O.gray(yt("\u2014",be.w))}).join(" ");$.push(` ${O.cyan(Xo(qe,2))} ${Xe?O.green(me):H>0?me:O.gray(me)} ${Xe?O.green(yt(`${H}/${se}`,8)):yt(`${H}/${se}`,8)} ${Qe} ${yc(H,se,10)} ${bf(H,se)}`)}$.push("");let U=u>0?` ${O.gray("\xB7")} ${u} spec${u===1?"":"s"} broken \u2014 ${O.bold(`/screenshot ${e.find(L=>L.state==="broken").id}`)} re-authors ${u===1?"it":"the first"}`:"";if(p>0)$.push(` ${st("\u2192",O.yellow)}${p} placeholder${p===1?"":"s"} still need a spec \u2014 run ${O.bold("/screenshot author --all")}${U}`);else if(s>0){let L=e.filter(H=>H.state==="spec"&&H.mutates).length,G=L>0?O.gray(` \u2014 ${s-L} in one go; ${L} write${L===1?"s":""} real data and run${L===1?"s":""} one at a time`):"";$.push(` ${st("\u2192",O.yellow)}${s} spec${s===1?"":"s"} ready to capture \u2014 run ${O.bold("/screenshot capture")}${G}${U}`)}else a>0?$.push(` ${st("\u2192",O.cyan)}${a} shot${a===1?"":"s"} blocked \u2014 stage the data below, then ${O.bold("/screenshot capture --all --retry-blocked")}${U}`):u>0?$.push(` ${st("\u2192",O.red)}${u} spec${u===1?"":"s"} broken \u2014 ${O.bold(`/screenshot ${e.find(L=>L.state==="broken").id}`)} re-authors ${u===1?"it":"the first"} (re-capturing fails the same way)`):$.push(` ${st("\u2713",O.green)}all ${o} captured \u2014 ${O.bold("/publish")} embeds them in the articles`);if(r>0&&r<o){let L=k.filter(([,G])=>G.every(H=>H.state!=="captured")).map(([G])=>{let{num:H,name:se}=Us(G);return H?`${H} ${se}`:se});L.length>0&&$.push(O.gray(` Furthest behind: ${L.slice(0,5).join(" \xB7 ")}${L.length>5?" \u2026":""} (0% captured)`))}return $.push(...Sc(e),...Pc(e),...Tc(e)),$.push(""),$.push(Rc),$.push(O.gray(" Drill in: /screenshot list <chapter#> \xB7 /screenshot list --detail (all)")),$}function xf(e,t,n){let o=new Set(e.map(a=>a.file)),r=e.filter(a=>a.state==="captured").length,s=[` ${O.bold("Screenshots")}: ${e.length} placeholder${e.length===1?"":"s"} across ${o.size} article${o.size===1?"":"s"} \xB7 ${O.green(`${r} captured`)}${n?O.gray(` \xB7 scope ${n}`):""}`,""];for(let[a,u]of Ac(e,t)){let p=u.filter(j=>j.state==="captured").length,{num:b,name:k}=Us(a),$=b?`${b} \xB7 ${k}`:k;s.push(` ${O.bold($)} ${O.gray(`(${p}/${u.length})`)}`);let x=new Map;for(let j of u){let v=kf(j.file),D=x.get(v)??[];x.has(v)||x.set(v,D),D.push(j)}for(let j of[...x.keys()].sort()){s.push(O.gray(` ${j}`));for(let v of x.get(j)){let D=ff[v.state];if(s.push(` ${st(hf[v.state],D)}${D(v.id)}`),(v.state==="blocked"||v.state==="broken")&&v.reason)for(let E of qn(v.reason,84))s.push(O.gray(` ${E}`))}}}return s.push(...Sc(e),...Pc(e),...Tc(e)),s.push("",Rc),s}function rr(e,t){let n=t?.scope;if(e.length===0)return[n?`No screenshot placeholders under ${n}.`:"No screenshot placeholders found in the docs."];let o=t?.docsDir??qs;return t?.detail||n?xf(e,o,n):$f(e,o)}function Vs(e,t){if(!t||!/^\d+$/.test(t))return t;let n=hn(e)?.docsDir??qs,o=String(Number(t));for(let{file:r}of kc(e)){let s=Dc(r,n),a=/^(\d+)/.exec(s);if(a&&String(Number(a[1]))===o)return s}return t}function vf(e){let t=e.replace(/\\/g,"/").split("/").filter(Boolean),n=t.pop()??e;return{category:t.pop()??"(docs root)",article:n}}function Qo(e,t,n){let o=new Map;for(let s of t){let{category:a,article:u}=vf(s.file),p=o.get(a)??new Map;o.set(a,p);let b=p.get(u)??[];p.set(u,b),b.push(s)}let r=s=>n==="author"||!s.mutates;for(let s of[...o.keys()].sort()){let a=o.get(s),u=[...a.values()].flat().filter(r).map(p=>p.id);u.length>0&&e.push({kind:"category",action:n,label:`${s} (${u.length})`,ids:u,depth:1});for(let p of[...a.keys()].sort()){let b=a.get(p),k=b.filter(r).map($=>$.id);k.length>0&&e.push({kind:"article",action:n,label:`${p} (${k.length})`,ids:k,depth:2});for(let $ of b){let x=n==="capture"&&$.mutates?" \u26A0 creates real data \u2014 runs only alone":void 0;e.push({kind:"shot",action:n,label:$.id,ids:[$.id],depth:3,...x?{note:x}:{}})}}}}function wc(e,t=58){if(!e)return"";let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n}function Gs(e,t,n){let o=t.filter(r=>!r.mutates);o.length>1&&e.push({kind:"all",action:"capture",label:`Retry ${o.length} blocked shots (stage the data first)`,ids:o.map(r=>r.id),depth:0});for(let r of[...t].sort((s,a)=>s.id.localeCompare(a.id)))e.push({kind:"shot",action:"capture",label:r.id,ids:[r.id],depth:1,note:` \u2298 ${wc(r.reason)}`});n.length>1&&e.push({kind:"all",action:"author",label:`Re-author ${n.length} broken specs`,ids:n.map(r=>r.id),depth:0});for(let r of[...n].sort((s,a)=>s.id.localeCompare(a.id)))e.push({kind:"shot",action:"author",label:r.id,ids:[r.id],depth:1,note:` \u2717 ${wc(r.reason)} \u2014 re-authors`})}function Ec(e){let t=e.filter(s=>s.state==="placeholder"),n=e.filter(s=>s.state==="spec"),o=[];t.length>1&&o.push({kind:"all",action:"author",label:`Author all ${t.length} remaining specs`,ids:t.map(s=>s.id),depth:0}),Qo(o,t,"author");let r=n.filter(s=>!s.mutates);return r.length>1&&o.push({kind:"all",action:"capture",label:`Capture all ${r.length} ready specs`,ids:r.map(s=>s.id),depth:0}),Qo(o,n,"capture"),Gs(o,e.filter(s=>s.state==="blocked"),e.filter(s=>s.state==="broken")),o}var Ws=["MANDATORY \u2014 a missing prerequisite must SKIP, never time out. Two rules, applied to EVERY locator","in the spec, not just the first one or the one shown in the skill's example:","1. A bare `await x.waitFor(...)` is itself the bug: on a missing element it THROWS and the run"," reports a hard failure with a stack trace instead of a staging instruction. Every wait must be",' `await x.waitFor({ state: "visible", timeout: 10_000 }).catch(() => {});` followed by',' `if ((await x.count()) === 0) test.skip(true, "Prerequisite not met: \u2026")`. That applies to each'," element you wait on or click IN TURN \u2014 tabs, toggles, rows, buttons reached after the first"," guard \u2014 because any of them can be absent for the same reason the data is.",' And when a wait DOES time out, diagnose before you guard: a skip asserts "your app lacks this',' data", so if the real cause is a locator matching a node you did not intend (a rollup row, a'," sibling with the same testid), that assertion is a lie and sends the user to stage what they"," already have. Narrow the selector first, THEN guard.","2. Never reason about whether a role/text locator is unique; you cannot verify that by reading"," source, and Playwright fails the whole spec on 2+ matches. Every `getByRole`/`getByText`/"," `:has-text` without a unique data-testid gets `.first()` or a container scope"," (`page.locator('[data-testid=\"\u2026\"]').getByRole(\u2026)`). If you catch yourself writing a comment"," ARGUING a selector is unique, scope it instead \u2014 that argument is what fails.","3. Every skip reason opens with the SHARED staging action, worded identically across every shot",' that needs the same thing, naming where in the product to do it ("Create an API key in Settings',' \u2192 API Keys."); shot-specific detail (counts, which record, which state) goes in LATER sentences.'," The dashboard groups blocked shots by that first sentence, so a near-duplicate wording splits one"," chore into two. Grep sibling specs and reuse their exact opening sentence.","Before you finish, re-read each spec you wrote and check all three rules line by line."].join(`
315
+ `,"utf8")}function Os(e){return e&&/data-testid|\btest-?id\b|has(?:n't| not) landed/i.test(e)?"testid":"data"}function hc(e,t,n){if(t.length===0)return;let o=_t(e);for(let r of t){let s=r.specSource?pc(r.specSource):void 0;o.shots[r.id]={outcome:r.outcome,at:n,...r.reason?{reason:r.reason}:{},...r.outcome==="skipped"?{blockedBy:Os(r.reason)}:{},...s?{specHash:s}:{}}}lf(e,o)}function _s(e,t,n){let o=e.shots[t];return!o||n===null||!o.specHash||o.specHash!==pc(n)?null:o}function fc(e){let t=_t(e).shots;return Object.keys(t).filter(n=>t[n].outcome==="failed").sort()}function Ls(e,t,n){let o=_s(_t(e),t,n);return o?.outcome==="failed"?o.reason??null:null}var bc=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function mc(e){let t=e.includes("--detail")||e.includes("-d"),n=e.find(o=>o!=="--detail"&&o!=="-d");return{mode:"list",scope:n?bc(n):void 0,...t?{detail:!0}:{}}}function Hn(e){let t=(e[0]??"").toLowerCase();if(t==="capture")return{mode:"capture",rest:e.slice(1)};if(t==="checklist"||t==="setup")return{mode:"checklist"};if(t==="list")return mc(e.slice(1));t==="author"&&(e=e.slice(1));let n=!e.includes("--no-setup"),o=e.filter(s=>s!=="--no-setup");if(o[0]==="--list")return mc(o.slice(1));let r=o[0];return r?r==="--all"?{mode:"all",setup:n}:/[\\/]/.test(r)||r.endsWith(".md")?{mode:"scope",scope:bc(r),setup:n}:{mode:"single",id:r}:{mode:"list",picker:!0}}function ze(e,t){let n=hn(e),o=n?.captureDir??tr,r=n?.outputDir??cf,s=(u,p)=>Jo(u)?Zo(u,p):er(e,u,p),a=_t(e);return kc(e,{scope:t}).map(({id:u,file:p})=>{let b=s(o,`${u}.spec.ts`),k=null;if(Ms(b))try{k=Bs(b,"utf8")}catch{}let $=Ms(s(r,`${u}.png`)),x=k===null?null:_s(a,u,k),j=k!==null&&df(k),v=$?"captured":k===null?"placeholder":j||x?.outcome==="skipped"?"blocked":x?.outcome==="failed"?"broken":"spec",D=k===null?void 0:xc(k),E=j?pf(k):x?.reason,U=j?"testid":x?.outcome==="skipped"?Os(x.reason):void 0;return{id:u,file:p,state:v,...D?{mutates:D.mutates,...D.declared?{}:{undeclared:!0}}:{},...k!==null&&gc(k).length>0?{unguardedWaits:gc(k)}:{},...v==="blocked"||v==="broken"?{...E?{reason:E}:{},...U?{blockedBy:U}:{}}:{}}})}function nr(e,t){let n=hn(e)?.captureDir??tr,o=Jo(n)?Zo(n,`${t}.spec.ts`):er(e,n,`${t}.spec.ts`);try{return Bs(o,"utf8")}catch{return null}}function $c(e,t){let n=hn(e)?.captureDir??tr;return Ms(Jo(n)?Zo(n,`${t}.spec.ts`):er(e,n,`${t}.spec.ts`))}function uf(e,t,n){let o=[n.trim()];for(let r=t+1;r<e.length;r++){let s=/^\s*\/\/\s?(.*)$/.exec(e[r]);if(!s)break;let a=s[1].trim();if(!a||/^(CAPTURE-[A-Z]+:|TODO\b|NOTE\b|Grounding\b|\d+\.\s)/.test(a)||(o.push(a),o.join(" ").length>400))break}return o.join(" ")}function xc(e){let t=e.split(/\r?\n/),n=t.findIndex(u=>/^\s*\/\/\s*CAPTURE-SAFETY:\s*(readonly|mutates)\b/i.test(u)),o=n>=0?/^\s*\/\/\s*CAPTURE-SAFETY:\s*(readonly|mutates)\b[\s—:–-]*(.*)$/i.exec(t[n]):null;if(o){let u=uf(t,n,o[2]??"");return{mutates:o[1].toLowerCase()==="mutates",declared:!0,what:u||void 0}}let r=/setInputFiles/.test(e),s=/\{\s*name:\s*['"][^'"]*\b(create|import|save|apply|confirm|delete|submit|send|mint)\b[^'"]*['"][^}]*\}\s*\)\s*\.click\(/i.test(e),a=/\.fill\(/.test(e);return{mutates:r||a&&s,declared:!1}}function df(e){return/(^|\n)\s*test\.skip\s*\(\s*['"`]/.test(e)}function pf(e){let t=/\/\/\s*CAPTURE-TODO:\s*(\{.*\})\s*$/m.exec(e),n,o;if(t)try{let s=JSON.parse(t[1]);n=s.testid,o=s.file}catch{}return`Inert until your developers add ${n?`data-testid="${n}"${o?` in ${o}`:""}`:"a stable data-testid"} \u2014 the spec is skipped at compile time, so no capture run can produce this shot. /screenshot checklist builds the hand-off.`}function gc(e){let t=r=>{if(/^\s*\*/.test(r))return"";let s=/(?<!:)\/\//.exec(r);return s?r.slice(0,s.index):r},n=[],o=e.split(/\r?\n/).map(t);for(let[r,s]of o.entries()){if(!/\.waitFor\s*\(/.test(s))continue;let a=s;for(let u=r+1;u<o.length&&!/;\s*$/.test(a.trim())&&u<r+4;u++)a+=o[u];/\.catch\s*\(/.test(a)||n.push(r+1)}return n}function vc(e){return(e??"").trim().replace(/[.\s]+$/,"")}function Cc(e,t){let n=hn(e)?.captureDir??tr,o=Jo(n)?Zo(n,`${t}.spec.ts`):er(e,n,`${t}.spec.ts`);try{return xc(Bs(o,"utf8"))}catch{return{mutates:!1,declared:!1}}}function or(e){return[...new Set(e.filter(t=>t.state==="captured").map(t=>t.file))].sort()}var hf={placeholder:"\u25CB",spec:"\u25D0",blocked:"\u2298",broken:"\u2717",captured:"\u25CF"},ff={placeholder:O.gray,spec:O.yellow,blocked:O.cyan,broken:O.red,captured:O.green},Rc=` ${O.green("\u25CF captured")} ${O.yellow("\u25D0 ready")} ${O.cyan("\u2298 blocked")} ${O.red("\u2717 broken")} ${O.gray("\u25CB to spec")}`;function st(e,t=n=>n){return`${t(e)} `}function mf(e){let t=e.replace(/\s+/g," ").trim().replace(/^Prerequisite not met:\s*/i,""),n=/^(.*?[a-z0-9)"'”’])\.(?:\s|$)/i.exec(t);return(n?n[1]:t).trim()}function Hs(e){let t=new Map;for(let n of e){if(n.state!=="blocked")continue;let o=(n.reason??"No reason recorded \u2014 re-run this capture to find out why.").replace(/\s+/g," ").trim(),r=n.blockedBy??"data",s=mf(o),a=`${r} ${s.toLowerCase()}`,u=t.get(a)??{reason:s,blockedBy:r,ids:[]};t.has(a)||t.set(a,u),u.ids.push(n.id)}return[...t.values()].sort((n,o)=>o.ids.length-n.ids.length||n.reason.localeCompare(o.reason))}function Sc(e){let t=Hs(e);if(t.length===0)return[];let n=t.filter(s=>s.blockedBy==="data"),o=t.filter(s=>s.blockedBy==="testid"),r=[""];if(n.length>0){let s=n.reduce((u,p)=>u+p.ids.length,0);r.push(` ${O.bold("Stage this data")} ${O.gray(`\u2014 unblocks ${s} shot${s===1?"":"s"} in ${n.length} action${n.length===1?"":"s"}`)}`);let a=8;for(let u of n.slice(0,a)){let p=qn(u.reason,86);r.push(` ${O.cyan(yt(`${u.ids.length}\xD7`,4))} ${p[0]??""}`);for(let k of p.slice(1))r.push(` ${k}`);let b=u.ids.slice(0,4).join(" \xB7 ");r.push(O.gray(` ${b}${u.ids.length>4?` \xB7 +${u.ids.length-4} more`:""}`))}n.length>a&&r.push(O.gray(` \u2026 ${n.length-a} more staging action${n.length-a===1?"":"s"} \u2014 /screenshot list --detail`))}if(o.length>0){let s=o.reduce((a,u)=>a+u.ids.length,0);r.push(` ${st("\u2298",O.cyan)}${s} shot${s===1?"":"s"} need${s===1?"s":""} a data-testid from your developers \u2014 ${O.bold("/screenshot checklist")} builds the hand-off.`)}return r}function Pc(e){let t=e.filter(o=>(o.unguardedWaits?.length??0)>0);if(t.length===0)return[];let n=t.reduce((o,r)=>o+(r.unguardedWaits?.length??0),0);return["",` ${st("\u26A0",O.yellow)}${t.length} spec${t.length===1?"":"s"} ${t.length===1?"has":"have"} ${n} unguarded wait${n===1?"":"s"}`+O.gray(" \u2014 on missing data these fail with a stack trace instead of telling you what to stage"),O.gray(` ${t.slice(0,6).map(o=>`${o.id}:${o.unguardedWaits.join(",")}`).join(" \xB7 ")}${t.length>6?` \xB7 +${t.length-6} more`:""}`),O.gray(` Re-author to guard them: ${O.bold("/screenshot author <id>")}`)]}function Tc(e){let t=e.filter(o=>o.undeclared);if(t.length===0)return[];let n=t.filter(o=>o.mutates);return["",` ${st("\u26A0",O.yellow)}${t.length} spec${t.length===1?"":"s"} carr${t.length===1?"ies":"y"} no CAPTURE-SAFETY declaration`+(n.length>0?O.gray(` \u2014 ${n.length} of them read as "writes real data" by heuristic, so bulk capture benches ${n.length===1?"it":"them"}`):""),O.gray(` ${t.slice(0,6).map(o=>o.id).join(" \xB7 ")}${t.length>6?` \xB7 +${t.length-6} more`:""}`),O.gray(` Re-author them to declare it: ${O.bold("/screenshot author <id>")}`)]}var Xo=(e,t)=>e.length>=t?e:e+" ".repeat(t-e.length),yt=(e,t)=>e.length>=t?e:" ".repeat(t-e.length)+e;function Dc(e,t){let n=e.replace(/\\/g,"/"),o=t.replace(/\\/g,"/").replace(/\/+$/,"");o&&(n===o||n.startsWith(`${o}/`))&&(n=n.slice(o.length+1));let r=n.split("/").filter(Boolean);return r.length>1?r[0]:""}var gf=new Set(["and","or","of","the","to","a","an","in","on","for","with","vs"]),yf=new Set(["ai","api","cli","ui","ux","url","id","http","https","json","xml","sdk","csv","pdf","oauth","sso","mfa","io","faq"]);function wf(e){return e.replace(/[-_]+/g," ").trim().split(/\s+/).filter(Boolean).map((n,o)=>{let r=n.toLowerCase();return yf.has(r)?r.toUpperCase():o>0&&gf.has(r)?r:r.charAt(0).toUpperCase()+r.slice(1)}).join(" ")}function Us(e){if(!e)return{num:"",name:"(docs root)"};let t=/^(\d+)[-_](.+)$/.exec(e);return{num:t?t[1]:"",name:wf(t?t[2]:e)}}function kf(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).pop()??e}function yc(e,t,n){let o=t>0?Math.round(e/t*n):0;return O.green("\u2588".repeat(o))+O.gray("\u2591".repeat(Math.max(0,n-o)))}function bf(e,t){let n=t>0?Math.round(e/t*100):0,o=yt(`${n}%`,4);return n===100?O.green(o):n>0?O.yellow(o):O.gray(o)}function Ac(e,t){let n=new Map;for(let o of e){let r=Dc(o.file,t),s=n.get(r)??[];n.has(r)||n.set(r,s),s.push(o)}return[...n.keys()].sort().map(o=>[o,n.get(o)])}function $f(e,t){let n=(L,G)=>L.filter(H=>H.state===G).length,o=e.length,r=n(e,"captured"),s=n(e,"spec"),a=n(e,"blocked"),u=n(e,"broken"),p=n(e,"placeholder"),b=new Set(e.map(L=>L.file)).size,k=Ac(e,t),$=[];$.push(` ${O.bold("Screenshots")} ${O.green(`${r}/${o} captured`)} ${O.gray("\xB7")} ${s>0?O.yellow(`${s} ready`):O.gray("0 ready")}`+(a>0?` ${O.gray("\xB7")} ${O.cyan(`${a} blocked`)}`:"")+(u>0?` ${O.gray("\xB7")} ${O.red(`${u} broken`)}`:"")+` ${O.gray("\xB7")} ${p>0?O.red(`${p} to spec`):O.gray("0 to spec")} `+O.gray(`across ${b} article${b===1?"":"s"}`));let x=o>0?Math.round(r/o*100):0;$.push(` [${yc(r,o,32)}] ${O.bold(`${x}%`)}`),$.push("");let j=k.map(([L])=>Us(L)),v=Math.min(32,Math.max(7,...j.map(L=>L.name.length))),D=L=>L.length>v?`${L.slice(0,v-1)}\u2026`:Xo(L,v),E=[{head:"Ready",w:5,state:"spec",color:O.yellow},...a>0?[{head:"Blocked",w:7,state:"blocked",color:O.cyan}]:[],...u>0?[{head:"Broken",w:6,state:"broken",color:O.red}]:[],{head:"To spec",w:7,state:"placeholder",color:O.red}];$.push(O.gray(` ${Xo("#",2)} ${Xo("Chapter",v)} ${yt("Captured",8)} ${E.map(L=>yt(L.head,L.w)).join(" ")} Progress`));for(let[L,[,G]]of k.entries()){let H=n(G,"captured"),se=G.length,{num:Be,name:fe}=j[L],Xe=H===se,me=D(fe),Qe=E.map(be=>{let qe=n(G,be.state);return qe>0?be.color(yt(String(qe),be.w)):O.gray(yt("\u2014",be.w))}).join(" ");$.push(` ${O.cyan(Xo(Be,2))} ${Xe?O.green(me):H>0?me:O.gray(me)} ${Xe?O.green(yt(`${H}/${se}`,8)):yt(`${H}/${se}`,8)} ${Qe} ${yc(H,se,10)} ${bf(H,se)}`)}$.push("");let U=u>0?` ${O.gray("\xB7")} ${u} spec${u===1?"":"s"} broken \u2014 ${O.bold(`/screenshot ${e.find(L=>L.state==="broken").id}`)} re-authors ${u===1?"it":"the first"}`:"";if(p>0)$.push(` ${st("\u2192",O.yellow)}${p} placeholder${p===1?"":"s"} still need a spec \u2014 run ${O.bold("/screenshot author --all")}${U}`);else if(s>0){let L=e.filter(H=>H.state==="spec"&&H.mutates).length,G=L>0?O.gray(` \u2014 ${s-L} in one go; ${L} write${L===1?"s":""} real data and run${L===1?"s":""} one at a time`):"";$.push(` ${st("\u2192",O.yellow)}${s} spec${s===1?"":"s"} ready to capture \u2014 run ${O.bold("/screenshot capture")}${G}${U}`)}else a>0?$.push(` ${st("\u2192",O.cyan)}${a} shot${a===1?"":"s"} blocked \u2014 stage the data below, then ${O.bold("/screenshot capture --all --retry-blocked")}${U}`):u>0?$.push(` ${st("\u2192",O.red)}${u} spec${u===1?"":"s"} broken \u2014 ${O.bold(`/screenshot ${e.find(L=>L.state==="broken").id}`)} re-authors ${u===1?"it":"the first"} (re-capturing fails the same way)`):$.push(` ${st("\u2713",O.green)}all ${o} captured \u2014 ${O.bold("/publish")} embeds them in the articles`);if(r>0&&r<o){let L=k.filter(([,G])=>G.every(H=>H.state!=="captured")).map(([G])=>{let{num:H,name:se}=Us(G);return H?`${H} ${se}`:se});L.length>0&&$.push(O.gray(` Furthest behind: ${L.slice(0,5).join(" \xB7 ")}${L.length>5?" \u2026":""} (0% captured)`))}return $.push(...Sc(e),...Pc(e),...Tc(e)),$.push(""),$.push(Rc),$.push(O.gray(" Drill in: /screenshot list <chapter#> \xB7 /screenshot list --detail (all)")),$}function xf(e,t,n){let o=new Set(e.map(a=>a.file)),r=e.filter(a=>a.state==="captured").length,s=[` ${O.bold("Screenshots")}: ${e.length} placeholder${e.length===1?"":"s"} across ${o.size} article${o.size===1?"":"s"} \xB7 ${O.green(`${r} captured`)}${n?O.gray(` \xB7 scope ${n}`):""}`,""];for(let[a,u]of Ac(e,t)){let p=u.filter(j=>j.state==="captured").length,{num:b,name:k}=Us(a),$=b?`${b} \xB7 ${k}`:k;s.push(` ${O.bold($)} ${O.gray(`(${p}/${u.length})`)}`);let x=new Map;for(let j of u){let v=kf(j.file),D=x.get(v)??[];x.has(v)||x.set(v,D),D.push(j)}for(let j of[...x.keys()].sort()){s.push(O.gray(` ${j}`));for(let v of x.get(j)){let D=ff[v.state];if(s.push(` ${st(hf[v.state],D)}${D(v.id)}`),(v.state==="blocked"||v.state==="broken")&&v.reason)for(let E of qn(v.reason,84))s.push(O.gray(` ${E}`))}}}return s.push(...Sc(e),...Pc(e),...Tc(e)),s.push("",Rc),s}function rr(e,t){let n=t?.scope;if(e.length===0)return[n?`No screenshot placeholders under ${n}.`:"No screenshot placeholders found in the docs."];let o=t?.docsDir??qs;return t?.detail||n?xf(e,o,n):$f(e,o)}function Vs(e,t){if(!t||!/^\d+$/.test(t))return t;let n=hn(e)?.docsDir??qs,o=String(Number(t));for(let{file:r}of kc(e)){let s=Dc(r,n),a=/^(\d+)/.exec(s);if(a&&String(Number(a[1]))===o)return s}return t}function vf(e){let t=e.replace(/\\/g,"/").split("/").filter(Boolean),n=t.pop()??e;return{category:t.pop()??"(docs root)",article:n}}function Qo(e,t,n){let o=new Map;for(let s of t){let{category:a,article:u}=vf(s.file),p=o.get(a)??new Map;o.set(a,p);let b=p.get(u)??[];p.set(u,b),b.push(s)}let r=s=>n==="author"||!s.mutates;for(let s of[...o.keys()].sort()){let a=o.get(s),u=[...a.values()].flat().filter(r).map(p=>p.id);u.length>0&&e.push({kind:"category",action:n,label:`${s} (${u.length})`,ids:u,depth:1});for(let p of[...a.keys()].sort()){let b=a.get(p),k=b.filter(r).map($=>$.id);k.length>0&&e.push({kind:"article",action:n,label:`${p} (${k.length})`,ids:k,depth:2});for(let $ of b){let x=n==="capture"&&$.mutates?" \u26A0 creates real data \u2014 runs only alone":void 0;e.push({kind:"shot",action:n,label:$.id,ids:[$.id],depth:3,...x?{note:x}:{}})}}}}function wc(e,t=58){if(!e)return"";let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n}function Gs(e,t,n){let o=t.filter(r=>!r.mutates);o.length>1&&e.push({kind:"all",action:"capture",label:`Retry ${o.length} blocked shots (stage the data first)`,ids:o.map(r=>r.id),depth:0});for(let r of[...t].sort((s,a)=>s.id.localeCompare(a.id)))e.push({kind:"shot",action:"capture",label:r.id,ids:[r.id],depth:1,note:` \u2298 ${wc(r.reason)}`});n.length>1&&e.push({kind:"all",action:"author",label:`Re-author ${n.length} broken specs`,ids:n.map(r=>r.id),depth:0});for(let r of[...n].sort((s,a)=>s.id.localeCompare(a.id)))e.push({kind:"shot",action:"author",label:r.id,ids:[r.id],depth:1,note:` \u2717 ${wc(r.reason)} \u2014 re-authors`})}function Ec(e){let t=e.filter(s=>s.state==="placeholder"),n=e.filter(s=>s.state==="spec"),o=[];t.length>1&&o.push({kind:"all",action:"author",label:`Author all ${t.length} remaining specs`,ids:t.map(s=>s.id),depth:0}),Qo(o,t,"author");let r=n.filter(s=>!s.mutates);return r.length>1&&o.push({kind:"all",action:"capture",label:`Capture all ${r.length} ready specs`,ids:r.map(s=>s.id),depth:0}),Qo(o,n,"capture"),Gs(o,e.filter(s=>s.state==="blocked"),e.filter(s=>s.state==="broken")),o}var Ws=["MANDATORY \u2014 a missing prerequisite must SKIP, never time out. Two rules, applied to EVERY locator","in the spec, not just the first one or the one shown in the skill's example:","1. A bare `await x.waitFor(...)` is itself the bug: on a missing element it THROWS and the run"," reports a hard failure with a stack trace instead of a staging instruction. Every wait must be",' `await x.waitFor({ state: "visible", timeout: 10_000 }).catch(() => {});` followed by',' `if ((await x.count()) === 0) test.skip(true, "Prerequisite not met: \u2026")`. That applies to each'," element you wait on or click IN TURN \u2014 tabs, toggles, rows, buttons reached after the first"," guard \u2014 because any of them can be absent for the same reason the data is.",' And when a wait DOES time out, diagnose before you guard: a skip asserts "your app lacks this',' data", so if the real cause is a locator matching a node you did not intend (a rollup row, a'," sibling with the same testid), that assertion is a lie and sends the user to stage what they"," already have. Narrow the selector first, THEN guard.","2. Never reason about whether a role/text locator is unique; you cannot verify that by reading"," source, and Playwright fails the whole spec on 2+ matches. Every `getByRole`/`getByText`/"," `:has-text` without a unique data-testid gets `.first()` or a container scope"," (`page.locator('[data-testid=\"\u2026\"]').getByRole(\u2026)`). If you catch yourself writing a comment"," ARGUING a selector is unique, scope it instead \u2014 that argument is what fails.","3. Every skip reason opens with the SHARED staging action, worded identically across every shot",' that needs the same thing, naming where in the product to do it ("Create an API key in Settings',' \u2192 API Keys."); shot-specific detail (counts, which record, which state) goes in LATER sentences.'," The dashboard groups blocked shots by that first sentence, so a near-duplicate wording splits one"," chore into two. Grep sibling specs and reuse their exact opening sentence.","Before you finish, re-read each spec you wrote and check all three rules line by line."].join(`
316
316
  `),Fs="MANDATORY, check before you finish: every spec you write or touch must carry exactly one `// CAPTURE-SAFETY: readonly` or `// CAPTURE-SAFETY: mutates \u2014 <what it creates>; cleanup: <how>` line at the top. Re-read each file you wrote and add it if missing \u2014 a spec without it is classified by guesswork. A fail-by-design spec (the app rejects the input) is `readonly`.";function jc(e,t){let n=e.paths.filter(o=>t?.get(o));return["Run the emit-screenshot-spec skill to author the document360-capture spec for EACH of these","SCREENSHOT placeholder ids:",e.paths.map(o=>`- ${o}`).join(`
317
317
  `),"",...n.length>0?["REPAIR \u2014 these already have a spec, and it FAILED its last capture. Read the existing spec","first and fix the named failure specifically; do not re-emit the same locator and hope. A",'"strict mode violation" means the locator matched 2+ elements (scope it to a stable container',"or take .first()); a click timeout means the element was absent or unreachable (if the data","simply is not staged, the spec must test.skip with a reason naming what to stage, not time out).",...n.map(o=>`- ${o}: ${t.get(o).replace(/\s+/g," ").trim()}`),""]:[],"For each: locate its <!-- SCREENSHOT --> block in the docs tree (the configured docsDir); read the product source for","EXACT routes + stable data-testid selectors (never guess); enter the prepared context via","captureScope(); guard data prerequisites with test.skip(reason); write <captureDir>/<id>.spec.ts","(skip-with-TODO if a stable selector is missing). Do NOT run other skills. Report the specs you","wrote and any TODO data-testids.",Ws,Fs].join(`
318
- `)}async function sr(e,t,n){let o=Hn(e);if(o.mode==="list"){let u=t?.cwd??process.cwd(),p=Vs(u,o.scope),b=hn(u)?.docsDir??qs,k=We(u,p);for(let $ of rr(k,{scope:p,detail:o.detail,docsDir:b}))console.log($);return{kind:"continue"}}if(o.mode==="single")return{kind:"forward-to-agent",prompt:[`Run the emit-screenshot-spec skill for the SCREENSHOT placeholder with id \`${o.id}\`.`,"Locate its <!-- SCREENSHOT --> block in the docs tree (the configured docsDir), then follow that skill exactly: read the","product source for EXACT routes + stable data-testid selectors (never guess); enter the prepared","context via captureScope(); guard data prerequisites with test.skip(reason); write",`<captureDir>/${o.id}.spec.ts. Report per the skill's writer-facing format \u2014 spec path, data to`,"stage, dev requests only if any, and the capture command; no grounding narration.",Ws,Fs,...n?.lastFailure?["","REPAIR \u2014 the existing spec FAILED its last capture with:",n.lastFailure,'Read the existing spec first and fix that failure specifically. A "strict mode violation" means the',"locator matched 2+ elements \u2014 scope it to a stable container or take .first(); a click timeout means","the element was absent or unreachable \u2014 if that's because the data isn't staged, the spec must","test.skip with a reason naming what to stage, not time out. Re-verify every selector you keep","against the product source; do not re-emit the same locator and hope."]:[]].join(`
318
+ `)}async function sr(e,t,n){let o=Hn(e);if(o.mode==="list"){let u=t?.cwd??process.cwd(),p=Vs(u,o.scope),b=hn(u)?.docsDir??qs,k=ze(u,p);for(let $ of rr(k,{scope:p,detail:o.detail,docsDir:b}))console.log($);return{kind:"continue"}}if(o.mode==="single")return{kind:"forward-to-agent",prompt:[`Run the emit-screenshot-spec skill for the SCREENSHOT placeholder with id \`${o.id}\`.`,"Locate its <!-- SCREENSHOT --> block in the docs tree (the configured docsDir), then follow that skill exactly: read the","product source for EXACT routes + stable data-testid selectors (never guess); enter the prepared","context via captureScope(); guard data prerequisites with test.skip(reason); write",`<captureDir>/${o.id}.spec.ts. Report per the skill's writer-facing format \u2014 spec path, data to`,"stage, dev requests only if any, and the capture command; no grounding narration.",Ws,Fs,...n?.lastFailure?["","REPAIR \u2014 the existing spec FAILED its last capture with:",n.lastFailure,'Read the existing spec first and fix that failure specifically. A "strict mode violation" means the',"locator matched 2+ elements \u2014 scope it to a stable container or take .first(); a click timeout means","the element was absent or unreachable \u2014 if that's because the data isn't staged, the spec must","test.skip with a reason naming what to stage, not time out. Re-verify every selector you keep","against the product source; do not re-emit the same locator and hope."]:[]].join(`
319
319
  `),display:`/screenshot ${o.id}`};if(o.mode==="capture"||o.mode==="checklist")return{kind:"continue"};let s=[`Run the emit-screenshot-spec skill to (re)generate the document360-capture spec for ${o.mode==="scope"?`every <!-- SCREENSHOT --> placeholder in articles under ${o.scope}`:"every <!-- SCREENSHOT --> placeholder across the docs tree (the configured docsDir)"}.`,"Follow that skill exactly for each: read the SCREENSHOT block; read the product source for EXACT routes","and stable data-testid selectors (never guess); enter the prepared context via captureScope(); guard data",`prerequisites with test.skip(reason); write <captureDir>/<id>.spec.ts.${o.setup?" When done, run capture-setup-checklist to refresh CAPTURE-SETUP.md.":""} Report specs written, TODO data-testids, and data to stage.`,Ws,Fs].join(`
320
320
  `),a=o.mode==="scope"?`/screenshot ${o.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:s,display:a}}var Vn=3;function Ys(e){return[`Run the publish-to-d360 skill for the article at: ${e}`,"","Steps you must follow:","1. Read the article markdown \u2014 use the repo-relative path exactly as given above (it resolves against the working directory; do not reconstruct an absolute path).","2. Compute the D360 publish form (strip the YAML frontmatter and the H1 title, normalize cross-article links). For each <!-- SCREENSHOT ... --> block, read its id BEFORE stripping the block: when <outputDir>/<id>.png exists (the annotated capture), upload it (d360_search_drive first to reuse, else d360_upload_drive_file) and replace the visible [Screenshot: ...] line with the image markdown; only when no PNG exists does the visible line stay as text.","3. Look up the article ID in <repo>/d360-category-map.json. If present, call the document360 MCP update-article tool. If absent, call create-article with local_path set to the repo-relative .md path (the tool records the new ID + sync base in the category map itself \u2014 do not edit the articles map by hand).","4. Report what changed and remind me to publish the draft manually in the Document360 portal."].join(`
321
321
  `)}var Nc={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function zs(e){return e.filter(t=>t.path!==null&&t.status in Nc&&!t.link).map(t=>({path:t.path,label:Nc[t.status]}))}function ar(e){let t=zs(e),n=new Set(e.filter(o=>o.status==="conflict"&&o.path).map(o=>o.path));return{clean:t.filter(o=>!n.has(o.path)),conflicts:t.filter(o=>n.has(o.path))}}function lr(e){let t=e!==1;return`\u26A0 ${e} conflict${t?"s":""} NOT published (portal edit${t?"s":""} kept safe) \u2014 ${t?"these were":"it was"} edited both here and on the portal, so ${t?"they are":"it is"} left untouched. Settle ${t?"them":"it"}: /resolve (or /publish <path> to keep yours, /pull <path> to take the portal's).`}function cr(e){return e.filter(t=>t.link).length}function Ks(e,t){try{let n=Ef(e,jf(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=Nf(Cf(Rf(e,r),"utf8"),r,n).unresolved}catch{}return o===0?null:`\u2139 ${o} cross-link${o===1?"":"s"} point to pages not published yet \u2014 they show as plain text for now and turn into live links once those pages are published.`}catch{return null}}function If(e){let t=e.replace(/\\/g,"/").split("/").pop()??e,n=t.replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return n?n.charAt(0).toUpperCase()+n.slice(1):t}function Mc(e,t=[]){let n=[];e.length>1&&n.push({kind:"all",label:`Publish all ${e.length} articles`,paths:e.map(r=>r.path),indent:!1});let o=new Map;for(let r of e){let s=r.path.replace(/\\/g,"/").split("/").slice(0,-1).join("/"),a=o.get(s);a?a.push(r):o.set(s,[r])}for(let r of[...o.keys()].sort()){let s=o.get(r).sort((a,u)=>a.path.localeCompare(u.path));n.push({kind:"category",label:`${If(r)} (${s.length})`,paths:s.map(a=>a.path),indent:!1});for(let a of s){let u=a.path.replace(/\\/g,"/").split("/").pop()??a.path;n.push({kind:"article",label:u,paths:[a.path],indent:!0,note:a.label})}}for(let r of[...t].sort((s,a)=>s.path.localeCompare(a.path))){let s=r.path.replace(/\\/g,"/").split("/").pop()??r.path;n.push({kind:"article",label:s,paths:[r.path],indent:!1,note:r.label,conflict:!0})}return n}function Gn(e){return[`Run the publish-to-d360 skill for ALL of these ${e.length} articles, one by one:`,"",...e.map(t=>`- ${t}`),"","Use the repo-relative paths exactly as listed (they resolve against the working directory; do not reconstruct absolute paths). Apply the normal per-article publish flow (frontmatter/H1/screenshot-comment strips, link normalization; update when mapped, create with local_path when not). Compute each publish form IN MEMORY and pass it straight to the tool \u2014 NEVER write it to disk (no *.publish.md siblings, no temp copies anywhere in the docs tree; the local .md files stay untouched). If one article fails, note it and continue. Finish with a summary table (article | created/updated | failures) and remind me drafts need review in the portal."].join(`
322
- `)}function Xs(e,t,n){let o=x=>t[x.index]?.paths.length??0,r=e.filter(x=>x.ok),s=e.filter(x=>!x.ok),a=e.reduce((x,j)=>x+o(j),0),u=r.reduce((x,j)=>x+o(j),0),p=n==="api"?`${Pe(e.reduce((x,j)=>x+j.costUsd,0))} total`:gt(e.reduce((x,j)=>x+j.outputTokens,0)),b=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,k=x=>`${x} article${x===1?"":"s"}`,$=[];if(s.length===0)$.push(`Published ${k(a)} (${b}) successfully \xB7 ${p}.`),$.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{$.push(`Published ${u}/${k(a)} (${b}) \xB7 ${p}.`),$.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /publish --all to retry just the rest (published articles are skipped):`);for(let x of s)$.push(` \u2717 ${x.label}${x.error?` \u2014 ${x.error}`:""}`)}return $}async function wt(e,t){let{model:n}=Df(e.cwd,"standard"),o=async(r,s)=>{let a=Pf(r);console.log(m(s?`Resolving cross-links in ${r.length} article${r.length===1?"":"s"} whose targets published this run (second pass)\u2026`:`Publishing ${r.length} article${r.length===1?"":"s"} across ${a.length} partition${a.length===1?"":"s"} (\u2264${Vn} agents at once) on ${n}\u2026`)),s||console.log(m(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let u=!1;for await(let p of Af({cwd:e.cwd,partitions:a,promptFor:b=>Gn(b.paths),concurrency:Vn,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:n}))if(p.type==="partition_status")p.status==="running"?console.log(m(` \u25B8 ${p.label} \u2014 publishing\u2026`)):p.status==="done"?console.log(_(` \u2713 ${p.label}`)):console.log(S(` \u2717 ${p.label}`));else if(p.type==="run_done"){u=p.aborted,console.log("");let b=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let $ of Xs(p.results,a,b))console.log(p.ok?_($):B($));let k=Ks(e.cwd,e.profileName);k&&console.log(m(k));try{let $=Oc(await Ic({cwd:e.cwd,profileName:e.profileName}));$&&console.log(m($))}catch{}try{let $=Lc(await _c({cwd:e.cwd,profileName:e.profileName}));$&&console.log(m($))}catch{}}return u};try{if(!await o(t,!1)){let s=await Qs(e.cwd,e.profileName,t);s.length>0&&await o(s,!0)}}catch(r){console.log(S(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function ur(e,t,n){let o=Tf(e,n);if(o.length===0)return[];let r=new Set(zs((await ir({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function Qs(e,t,n){try{let o=new Set(n),r=await ir({cwd:e,profileName:t});return zs(r.entries).map(s=>s.path).filter(s=>o.has(s))}catch{return[]}}async function Uc(e,t){let n=Ue(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(S(n.reason)),{kind:"continue"};let o=e[0];if(e.includes("--screenshots")||e.includes("--shots")){let r=t?.cwd??process.cwd(),s=or(We(r));return s.length===0?(console.log(m("No captured screenshots yet \u2014 /screenshot capture first.")),{kind:"continue"}):t?await wt(t,s):{kind:"forward-to-agent",prompt:Gn(s),display:"/publish --screenshots"}}if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await ur(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return r.length===0?(console.log(_("\u2713 All related articles are already published.")),{kind:"continue"}):await wt(t,r)}if(o==="--all"){console.log(m("Checking what needs publishing\u2026"));try{let r=await ir({cwd:t?.cwd??process.cwd()}),{clean:s,conflicts:a}=ar(r.entries),u=cr(r.entries),p=e.includes("--force")&&a.length>0;u>0&&console.log(B(`\u26A0 ${u} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),a.length>0&&!p&&console.log(B(lr(a.length)));let b=p?[...s,...a]:s;if(b.length===0){if(a.length>0)return console.log(m("Resolve the conflicts: /resolve")),{kind:"continue"};if(console.log(_(u>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),t)try{let k=Oc(await Ic({cwd:t.cwd,profileName:t.profileName}));k&&console.log(m(k));let $=Lc(await _c({cwd:t.cwd,profileName:t.profileName}));$&&console.log(m($))}catch{}return{kind:"continue"}}return t?await wt(t,b.map(k=>k.path)):{kind:"forward-to-agent",prompt:Gn(b.map(k=>k.path)),display:"/publish --all"}}catch(r){return console.log(S(`Could not compute sync status: ${r.message}`)),{kind:"continue"}}}if(o&&o.startsWith("--")&&(o=e.find(r=>!r.startsWith("--"))??""),!o){console.log(m("Checking what needs publishing\u2026"));let r;try{let s=await ir({cwd:t?.cwd??process.cwd()}),{clean:a,conflicts:u}=ar(s.entries);r=a;let p=cr(s.entries);if(p>0&&console.log(B(`\u26A0 ${p} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),u.length>0&&console.log(B(lr(u.length))),r.length===0&&u.length>0)return console.log(m("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(s){return console.log(S(`Could not compute sync status: ${s.message}`)),console.log(m("Publish a specific article: /publish <article-path>")),{kind:"continue"}}if(r.length===0)return console.log(_("\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),console.log(m(" (Articles without a sync base are unverified \u2014 publish those by path if needed.)")),{kind:"continue"};if(!process.stdin.isTTY||!t){for(let s of r)console.log(` ${s.path} ${m(`(${s.label})`)}`);return console.log(m("Run: /publish <article-path>")),{kind:"continue"}}try{o=await t.withPausedInput(()=>Sf({message:"Publish which article?",choices:[...r.length>1?[{name:`All ${r.length} candidates`,value:"--all",description:"one agent run over every candidate"}]:[],...r.map(s=>({name:s.path,value:s.path,description:s.label}))]}))}catch{return console.log(m("Cancelled.")),{kind:"continue"}}if(o==="--all")return await wt(t,r.map(s=>s.path))}return{kind:"forward-to-agent",prompt:Ys(o),display:`/publish ${o}`}}async function Yn(){return{kind:"forward-to-agent",prompt:["Run the gap-analysis skill against this repo.","","Follow its stages in order:","1. d360_sync_status first \u2014 stop and report if any article is in conflict or remote-ahead (the local copy cannot be trusted until resolved).","2. git diff since the lastAnalyzedCommit marker in d360-category-map.json (or last 30 days if no marker), filtered to the authoritativeSourceFiles paths.","2.5. d360_pending_hints \u2014 the source agent's own notes on what it shipped. Verify each (sources exist, commit is an ancestor of HEAD, source shows the surface) before trusting; fold verified ones into the table, flag the rest.","3. Map changes (diff + hints) to articles via their `sources:` frontmatter; read only implicated articles and changed source files. If articles are missing `sources:`, this is the one-time bootstrap pass \u2014 backfill them.","4. Output the proposal table: | Article (path or proposed title) | Action (create | update | retire | link) | Reason | Evidence | Scope |, then advance lastAnalyzedCommit and stamp consumed hints.","","Do not start writing or updating any article yet \u2014 the proposal table is the deliverable."].join(`
322
+ `)}function Xs(e,t,n){let o=x=>t[x.index]?.paths.length??0,r=e.filter(x=>x.ok),s=e.filter(x=>!x.ok),a=e.reduce((x,j)=>x+o(j),0),u=r.reduce((x,j)=>x+o(j),0),p=n==="api"?`${Pe(e.reduce((x,j)=>x+j.costUsd,0))} total`:gt(e.reduce((x,j)=>x+j.outputTokens,0)),b=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,k=x=>`${x} article${x===1?"":"s"}`,$=[];if(s.length===0)$.push(`Published ${k(a)} (${b}) successfully \xB7 ${p}.`),$.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{$.push(`Published ${u}/${k(a)} (${b}) \xB7 ${p}.`),$.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /publish --all to retry just the rest (published articles are skipped):`);for(let x of s)$.push(` \u2717 ${x.label}${x.error?` \u2014 ${x.error}`:""}`)}return $}async function wt(e,t){let{model:n}=Df(e.cwd,"standard"),o=async(r,s)=>{let a=Pf(r);console.log(m(s?`Resolving cross-links in ${r.length} article${r.length===1?"":"s"} whose targets published this run (second pass)\u2026`:`Publishing ${r.length} article${r.length===1?"":"s"} across ${a.length} partition${a.length===1?"":"s"} (\u2264${Vn} agents at once) on ${n}\u2026`)),s||console.log(m(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let u=!1;for await(let p of Af({cwd:e.cwd,partitions:a,promptFor:b=>Gn(b.paths),concurrency:Vn,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:n}))if(p.type==="partition_status")p.status==="running"?console.log(m(` \u25B8 ${p.label} \u2014 publishing\u2026`)):p.status==="done"?console.log(_(` \u2713 ${p.label}`)):console.log(S(` \u2717 ${p.label}`));else if(p.type==="run_done"){u=p.aborted,console.log("");let b=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let $ of Xs(p.results,a,b))console.log(p.ok?_($):B($));let k=Ks(e.cwd,e.profileName);k&&console.log(m(k));try{let $=Oc(await Ic({cwd:e.cwd,profileName:e.profileName}));$&&console.log(m($))}catch{}try{let $=Lc(await _c({cwd:e.cwd,profileName:e.profileName}));$&&console.log(m($))}catch{}}return u};try{if(!await o(t,!1)){let s=await Qs(e.cwd,e.profileName,t);s.length>0&&await o(s,!0)}}catch(r){console.log(S(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function ur(e,t,n){let o=Tf(e,n);if(o.length===0)return[];let r=new Set(zs((await ir({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function Qs(e,t,n){try{let o=new Set(n),r=await ir({cwd:e,profileName:t});return zs(r.entries).map(s=>s.path).filter(s=>o.has(s))}catch{return[]}}async function Uc(e,t){let n=Ue(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(S(n.reason)),{kind:"continue"};let o=e[0];if(e.includes("--screenshots")||e.includes("--shots")){let r=t?.cwd??process.cwd(),s=or(ze(r));return s.length===0?(console.log(m("No captured screenshots yet \u2014 /screenshot capture first.")),{kind:"continue"}):t?await wt(t,s):{kind:"forward-to-agent",prompt:Gn(s),display:"/publish --screenshots"}}if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await ur(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return r.length===0?(console.log(_("\u2713 All related articles are already published.")),{kind:"continue"}):await wt(t,r)}if(o==="--all"){console.log(m("Checking what needs publishing\u2026"));try{let r=await ir({cwd:t?.cwd??process.cwd()}),{clean:s,conflicts:a}=ar(r.entries),u=cr(r.entries),p=e.includes("--force")&&a.length>0;u>0&&console.log(B(`\u26A0 ${u} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),a.length>0&&!p&&console.log(B(lr(a.length)));let b=p?[...s,...a]:s;if(b.length===0){if(a.length>0)return console.log(m("Resolve the conflicts: /resolve")),{kind:"continue"};if(console.log(_(u>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),t)try{let k=Oc(await Ic({cwd:t.cwd,profileName:t.profileName}));k&&console.log(m(k));let $=Lc(await _c({cwd:t.cwd,profileName:t.profileName}));$&&console.log(m($))}catch{}return{kind:"continue"}}return t?await wt(t,b.map(k=>k.path)):{kind:"forward-to-agent",prompt:Gn(b.map(k=>k.path)),display:"/publish --all"}}catch(r){return console.log(S(`Could not compute sync status: ${r.message}`)),{kind:"continue"}}}if(o&&o.startsWith("--")&&(o=e.find(r=>!r.startsWith("--"))??""),!o){console.log(m("Checking what needs publishing\u2026"));let r;try{let s=await ir({cwd:t?.cwd??process.cwd()}),{clean:a,conflicts:u}=ar(s.entries);r=a;let p=cr(s.entries);if(p>0&&console.log(B(`\u26A0 ${p} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),u.length>0&&console.log(B(lr(u.length))),r.length===0&&u.length>0)return console.log(m("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(s){return console.log(S(`Could not compute sync status: ${s.message}`)),console.log(m("Publish a specific article: /publish <article-path>")),{kind:"continue"}}if(r.length===0)return console.log(_("\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),console.log(m(" (Articles without a sync base are unverified \u2014 publish those by path if needed.)")),{kind:"continue"};if(!process.stdin.isTTY||!t){for(let s of r)console.log(` ${s.path} ${m(`(${s.label})`)}`);return console.log(m("Run: /publish <article-path>")),{kind:"continue"}}try{o=await t.withPausedInput(()=>Sf({message:"Publish which article?",choices:[...r.length>1?[{name:`All ${r.length} candidates`,value:"--all",description:"one agent run over every candidate"}]:[],...r.map(s=>({name:s.path,value:s.path,description:s.label}))]}))}catch{return console.log(m("Cancelled.")),{kind:"continue"}}if(o==="--all")return await wt(t,r.map(s=>s.path))}return{kind:"forward-to-agent",prompt:Ys(o),display:`/publish ${o}`}}async function Yn(){return{kind:"forward-to-agent",prompt:["Run the gap-analysis skill against this repo.","","Follow its stages in order:","1. d360_sync_status first \u2014 stop and report if any article is in conflict or remote-ahead (the local copy cannot be trusted until resolved).","2. git diff since the lastAnalyzedCommit marker in d360-category-map.json (or last 30 days if no marker), filtered to the authoritativeSourceFiles paths.","2.5. d360_pending_hints \u2014 the source agent's own notes on what it shipped. Verify each (sources exist, commit is an ancestor of HEAD, source shows the surface) before trusting; fold verified ones into the table, flag the rest.","3. Map changes (diff + hints) to articles via their `sources:` frontmatter; read only implicated articles and changed source files. If articles are missing `sources:`, this is the one-time bootstrap pass \u2014 backfill them.","4. Output the proposal table: | Article (path or proposed title) | Action (create | update | retire | link) | Reason | Evidence | Scope |, then advance lastAnalyzedCommit and stamp consumed hints.","","Do not start writing or updating any article yet \u2014 the proposal table is the deliverable."].join(`
323
323
  `),display:"/audit"}}z();import{readProjectConfig as Of}from"document360-engine";function Js(){return["Run the discover-product skill against this repo.","","Build (or continue refining) the product brief at `.d360-writer/product-brief.md` by interviewing the","source repo's coding agent (the builder):","1. Gather all grounding \u2014 the code surface (analyze-codebase pass), `.d360-writer/architecture/`"," (+ CREATOR-NOTES), any specs under `.d360-writer/input/`, existing docs, git log, and the current"," product brief if one exists.","2. Self-assess against the 8-point readiness rubric (identity, audience, core mental model,"," misconceptions, positioning, key concepts & terminology, critical journeys, boundaries/non-goals).","3. Write/update the brief \u2014 every claim cited to its grounding \u2014 and keep its frontmatter current"," (status, rounds, open_questions, last_updated).","4. For the dimensions you cannot yet ground confidently, ask the builder a focused batch (\u22646) of pointed",' questions via d360_ask_builder, with the subject prefixed "[discovery] ". Then END the turn \u2014 the'," builder answers async; /catch-up will ingest the answers and continue the loop.","","Set status: confident and hand off to propose-structure ONLY when every rubric dimension passes. If the","builder stays silent across a few rounds, degrade gracefully per the skill (best-effort brief, flagged","open questions) rather than blocking the docs. Do NOT write or publish any articles in this turn."].join(`
324
324
  `)}async function Wc(e,t){let n=t?.cwd??process.cwd();return Of(n)?{kind:"forward-to-agent",prompt:Js(),display:"/discover"}:(console.log(S("No d360-writer config here. Run /init first.")),{kind:"continue"})}z();import{checkbox as _f}from"@inquirer/prompts";import{inventoryRepo as Lf,readProjectConfig as Fc,writeProjectConfig as Mf}from"document360-engine";function Zs(e,t){let n=Fc(e);n&&(n.authoritativeSourceFiles=t,Mf(n,e))}function dr(e){let t=[`${e.fileCount}${e.fileCount>=5e3?"+":""} files`];return e.stacks.length&&t.push(e.stacks.join("+")),t.push(e.reason),t.join(" \xB7 ")}async function Bc(e,t){let n=t?.cwd??process.cwd();if(!Fc(n))return console.log(S("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=Lf(n);if(o.length===0)return console.log(m('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(W("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${m(dr(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>_f({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${dr(s)})`,value:s.path,checked:s.recommended})),pageSize:20}))}catch{return console.log(m("Cancelled.")),{kind:"continue"}}if(r.length===0)return console.log(m("Nothing selected \u2014 scope unchanged.")),{kind:"continue"};Zs(n,r),console.log(_(`\u2713 Scoped to ${r.length} folder(s) \u2014 written to .d360-writer/config.json`));for(let s of r)console.log(` ${s}`);return console.log(""),{kind:"continue"}}z();import{confirm as zf}from"@inquirer/prompts";import{applyPull as ni,computeSyncStatus as Qc,compareRemoteSources as Kf,planPull as Jc,planImport as Xf,applyImport as Qf,establishBaselines as Jf,rebaselineServerMeta as Zf,D360AuthError as em}from"document360-engine";z();var qc=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /publish <path>):",paint:S,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /publish <path>:",paint:B,mark:"M"},{status:"remote-ahead",header:"Changed on Document360 \u2014 pull with /pull <path> (or just /pull):",paint:W,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:S,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:S,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint:ue,mark:"X"},{status:"untracked-local",header:"New here \u2014 not on Document360 yet (publish to add them):",paint:m,mark:"?"},{status:"untracked-remote",header:"On Document360 \u2014 not in your local docs yet (run /pull to import them):",paint:m,mark:"?"},{status:"unknown-base",header:"Tracked, not yet compared \u2014 run /pull --baseline to set a baseline (or the next publish/pull sets one):",paint:ue,mark:"\xB7"}];function Uf(e){return e.path?e.path:`${e.title??"(untitled)"} ${ue(`[${e.articleId}]`)}`}function Wf(e){let t=e/1e3;if(t<60)return`${t.toFixed(1)}s`;let n=Math.floor(t/60);return`${n}m ${Math.round(t-n*60)}s`}function pr(e,t){let n=[],o=e.entries.filter(k=>k.link);if(o.length>0){n.push(""),n.push(Se("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let k of o)n.push(` ${B("~")} ${B(k.path??"")} ${ue(`\u2192 "${k.link.title}"`)}`)}for(let k of qc){let $=e.entries.filter(x=>x.status===k.status&&!(k.status==="untracked-local"&&x.link));if($.length!==0){n.push(""),n.push(Se(k.header));for(let x of $)n.push(` ${k.paint(k.mark)} ${k.paint(Uf(x))}${x.detail?ue(` (${x.detail})`):""}`)}}let r=e.counts["in-sync"]??0,s=e.entries.length;n.push("");let a={"in-sync":"up to date","local-ahead":"changed here","remote-ahead":"changed on Document360",conflict:"changed both places","untracked-local":"new here","untracked-remote":"only on Document360","deleted-local":"removed locally","deleted-remote":"gone from Document360",orphaned:"gone both sides","unknown-base":"not yet compared"},u=o.length,p=s===r?_("\u2713 everything up to date"):[r>0?_(`\u2713 ${r} up to date`):null,u>0?`${u} to link`:null,...qc.map(k=>{let $=(e.counts[k.status]??0)-(k.status==="untracked-local"?u:0);return $>0?`${$} ${a[k.status]}`:null})].filter(Boolean).join(ue(" \xB7 ")),b=t!==void 0?` \xB7 synced in ${Wf(t)}`:"";return n.push(p+ue(` \xB7 ${s} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${b}`)),n}import{structuredPatch as Ff}from"diff";import Hc from"picocolors";var Vc=80,Bf="\x1B[48;2;74;28;28m",qf="\x1B[48;2;24;66;24m",Gc="\x1B[49m",ei=e=>String(e).padStart(5);function Yc(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}function zc(e,t,n){if(n===void 0||n<t-4)return e.slice(0,t);let o=Math.max(0,n-12);return`\u2026${e.slice(o).slice(0,Math.max(8,t-1))}`}function it(e,t,n){let o=x=>{let j=x.replace(/\r\n/g,`
325
325
  `);return j.endsWith(`
@@ -342,13 +342,13 @@ Articles:
342
342
  `+e.paths.map(r=>`- ${r}`).join(`
343
343
  `)}function wi(e,t,n){let o=e.reduce((a,u)=>a+u.paths.length,0),[r,s]=t.usd;return[`Write ${o} article${o===1?"":"s"} across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(a=>` \u2022 ${a.label} \u2014 ${a.paths.length} article${a.paths.length===1?"":"s"}`),"",`Estimated cost: ${Pe(r)}\u2013${Pe(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function ki(e,t,n){let o=v=>t[v.index]?.paths.length??0,r=e.filter(v=>v.ok),s=e.filter(v=>!v.ok),a=e.reduce((v,D)=>v+o(D),0),u=r.reduce((v,D)=>v+o(D),0),p=e.reduce((v,D)=>v+D.costUsd,0),b=e.reduce((v,D)=>v+D.outputTokens,0),k=n==="api"?`${Pe(p)} total`:gt(b),$=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,x=v=>`${v} article${v===1?"":"s"}`,j=[];if(s.length===0)j.push(`Wrote ${x(a)} (${$}) successfully \xB7 ${k}.`),j.push("Next \u2014 push them to Document360:"),j.push("/publish --all"),j.push("Or add screenshots first with /screenshot author --all. Drafts are reviewable in the portal after publishing.");else{j.push(`Wrote ${u}/${x(a)} (${$}) \xB7 ${k}.`),j.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let v of s)j.push(` \u2717 ${v.label}${v.error?` \u2014 ${v.error}`:""}`)}return j}function bi(e,t,n){try{let o=xm({cwd:e,paths:n.map(s=>`${t}/${s}`)});if(o.length===0)return null;let r=new Set(o.map(s=>s.path)).size;return`\u26A0 Doc-checker: ${o.length} issue${o.length===1?"":"s"} in ${r} of the new article${r===1?"":"s"} (leaked internals / unknown commands / stale facts) \u2014 /check --fix corrects them.`}catch{return null}}function $i(e,t,n){let o=(su(e)?.docsDir??Rm).replace(/\/+$/,""),r=t.map(u=>u.path);if(n.path){let u=jm(n.path,o);return r.includes(u)?{docsDir:o,targets:[u],planCount:r.length}:{docsDir:o,targets:[],planCount:r.length,reason:`"${u}" isn't in the docs plan (.d360-writer/plan.json).`}}let s=Nm(r,n.scope);if(n.scope&&s.length===0)return{docsDir:o,targets:[],planCount:r.length,reason:`No planned articles under "${n.scope}".`};if(n.rewrite)return{docsDir:o,targets:s,planCount:r.length,rewriting:!0};let a=mi(e,o,s);if(a.length===0){let u=n.scope?` under "${n.scope}"`:"",p=n.scope?` --scope ${n.scope}`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${u} are already written. Use /write <path> to rewrite one, or /write${p} --rewrite to regenerate them all.`}}return{docsDir:o,targets:a,planCount:r.length}}async function iu(e,t){if(!su(t.cwd))return console.log(S("No d360-writer config here. Run /init first.")),{kind:"continue"};if(fr(e)){for(let U of tu(t.cwd,t.profileName))console.log(m(U));return{kind:"continue"}}if(kt("write",e)){let U=fn(t.cwd,"write",e,t.profileName);if(U.length>0){for(let L of U)console.log(m(L));return{kind:"continue"}}}let n=Cm(t.cwd);if(n.length===0)return console.log(S("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};let{scope:o,path:r,preview:s,concurrency:a,rewrite:u}=fi(e),{docsDir:p,targets:b,reason:k,rewriting:$}=$i(t.cwd,n,{scope:o,path:r,rewrite:u});if(b.length===0)return console.log(k?B(k):B("Nothing to write.")),{kind:"continue"};$&&console.log(B(`--rewrite: regenerating ${b.length} already-written article${b.length===1?"":"s"} (overwrites them; git has your baseline).`));let x=vm(b),j=hi(a),{model:v,forced:D}=Sm(t.cwd,"standard"),E=!!r;if(s&&!E){let U=$m({files:gi(t.cwd,n,b),op:"write",model:v});o&&console.log(m(`Scope: ${o} (${b.length} pending).`));for(let L of wi(x,U,j))console.log(L);return console.log(m(`Model: ${v}${D?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(m(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}console.log(m(`Writing ${b.length} article${b.length===1?"":"s"} across ${x.length} partition${x.length===1?"":"s"} (\u2264${j} agents at once) on ${v}\u2026`)),console.log(m(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let U of Pm({cwd:t.cwd,partitions:x,promptFor:L=>yi(L,p,{rewrite:$||E}),concurrency:j,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:v}))if(U.type==="partition_status")U.status==="running"?console.log(m(` \u25B8 ${U.label} \u2014 writing\u2026`)):U.status==="done"?console.log(_(` \u2713 ${U.label}`)):console.log(S(` \u2717 ${U.label}`));else if(U.type==="run_done"){console.log("");let L=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let H of ki(U.results,x,L))console.log(U.ok?_(H):B(H));if(U.ok)try{Tm(t.cwd,b.map(H=>`${p}/${H}`),{writtenCap:Dm})}catch{}let G=bi(t.cwd,p,b);G&&console.log(B(G))}}catch(U){console.log(S(`Write run failed: ${U.message}`))}return console.log(""),{kind:"continue"}}z();import{existsSync as Im,readdirSync as au,statSync as lu}from"node:fs";import{join as cu}from"node:path";import{inputDir as Om,readProjectConfig as _m}from"document360-engine";var uu=/\.(md|markdown|pdf|txt)$/i;function xi(e){let t=Om(e);if(!Im(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of au(t)){let s=cu(t,r),a=!1;try{a=lu(s).isDirectory()}catch{continue}if(a){if(r.startsWith("."))continue;let u=Lm(s);u>0&&n.push({name:r,docCount:u})}else uu.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function Lm(e){let t=0;for(let n of au(e))try{lu(cu(e,n)).isFile()&&uu.test(n)&&t++}catch{}return t}function vi(e,t){let n=t.trim().toLowerCase();return n?e.find(o=>o.name.toLowerCase()===n)?.name??e.find(o=>o.name.toLowerCase().startsWith(n))?.name??e.find(o=>o.name.toLowerCase().includes(n))?.name??null:null}function mr(e,t){return["Run the draft-from-prd skill.","",`Target scope: ${e?`the feature documents in .d360-writer/input/${e}/`:t?`the input docs in .d360-writer/input/ relevant to: "${t}"`:"the input docs in .d360-writer/input/"}.`,t&&!e?`Use "${t}" as the feature framing.`:"","","Follow the skill: (1) read those PRDs/specs as the primary source (intent, user-facing surface,","terminology, user stories, prerequisites); (2) locate and read the CODE that implements that surface","to pin exact UI strings/routes/states \u2014 never fabricate; flag anything the PRD claims that you","cannot find in source; (3) propose a tight feature-scoped article set (\u22483\u20135) and pin it to",".d360-writer/plan.json + AGENT-PLAN.md, with each article's `sources` listing BOTH the PRD file(s)","AND the grounding code files; (4) flag overlaps with existing articles (do not merge). Then stop and","offer /write. Do NOT write the articles in this turn."].filter(Boolean).join(`
344
344
  `)}var Ci="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function du(e,t){let n=t?.cwd??process.cwd();if(!_m(n))return console.log(S("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=xi(n);if(o.length===0&&r===0)return console.log(m(Ci)),{kind:"continue"};let s=e.join(" ").trim();if(!s){if(o.length>1){console.log(m("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let p of o)console.log(` ${p.name} ${m(`(${p.docCount} doc${p.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let u=o[0]?.name??"";return{kind:"forward-to-agent",prompt:mr(u),display:u?`/draft ${u}`:"/draft"}}let a=vi(o,s);return{kind:"forward-to-agent",prompt:mr(a??"",a?void 0:s),display:`/draft ${s}`}}z();import{listOpenForDocs as Mm,readProjectConfig as Um}from"document360-engine";function Ri(e){try{return Mm(e).filter(t=>t.kind==="request").length}catch{return 0}}function Si(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function Pi(e,t=!1){let n=["Run the document-handoff skill.",""];return e?n.push(`The builder hand-off (what was shipped this session): "${e}".`,"Treat this as the Stage 1 hand-off: ground it in the cited/changed code + the architecture brief,","then decide and APPLY the right doc action \u2014 a new section, a new article, an update to existing","article(s), or a retirement, or a mix. No fixed shape; pick the smallest set that keeps the docs correct."):n.push("No description was given \u2014 call d360_inbox and act on the OPEN `request` messages the builder left:","for each, run the document-handoff flow (ground \u2192 decide \u2192 apply) and mark the request `status: done`","with `resulting_articles` when finished."),n.push("","Draft only \u2014 do not publish. If you would create multiple new articles (a section), call","d360_estimate_cost and present the count + cost band first, then wait for the go-ahead."),t&&n.push("","After the drafts exist and the user confirms any bulk gate, publish the new/updated articles to","Document360 (the publish-to-d360 skill). On a production profile, respect the write-guard."),n.join(`
345
- `)}var Ti="Nothing to document yet. Say what changed: /document <what you shipped> \u2014 or have the builder drop a request via their /devhints hand-off.";async function pu(e,t){let n=t?.cwd??process.cwd();if(!Um(n))return console.log(S("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=Si(e);if(!r&&Ri(n)===0)return console.log(m(Ti)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:Pi(r,o),display:s}}z();import{search as Wm}from"@inquirer/prompts";import{findByName as Fm,getSession as Bm,listSessions as qm,relativeTime as fu}from"document360-engine";async function mu(e,t){let n=qm(t.cwd).filter(o=>o.uuid!==t.currentUuid());if(n.length===0)return console.log(m("No saved sessions for this repo yet \u2014 sessions auto-save as you work.")),{kind:"continue"};if(e.length>0){let o=e.join(" "),r=Fm(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(S(`No session matches "${o}".`)),hu(n),{kind:"continue"})}if(!process.stdin.isTTY)return hu(n),console.log(m("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>Wm({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let a=(s??"").toLowerCase();return n.filter(u=>!a||u.name.toLowerCase().includes(a)||u.firstPrompt.toLowerCase().includes(a)).map(u=>({name:`${u.name} ${fu(u.updatedAt)}`,value:u.uuid,description:u.firstPrompt.slice(0,100)}))}})),r=Bm(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function hu(e){console.log("");for(let t of e.slice(0,15))console.log(` ${W(t.name)} ${m(fu(t.updatedAt))}`),console.log(` ${m(t.firstPrompt.slice(0,80))}`);console.log("")}z();import{renameSession as Hm}from"document360-engine";function Di(e){let t=e.trim();return t.length>=2&&(t[0]==='"'&&t.endsWith('"')||t[0]==="'"&&t.endsWith("'"))?t.slice(1,-1).trim():t}async function gu(e,t){let n=Di(e.join(" "));if(!n)return console.log(S("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(Hm(o,n)?console.log(_(`\u2713 Session renamed to "${n}"`)):console.log(S("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(_(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as yu,readProjectConfig as Vm,writeProjectConfig as Gm}from"document360-engine";z();function Ai(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=Vm(e);if(!o)return"No .d360-writer/config.json \u2014 run /init first.";if(o.profiles?.[t])return`Profile "${t}" already exists.`;let r=n??t;return yu().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},Gm(o,e),null):`Unknown environment "${r}". Known: ${yu().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function wu(e,t){let n=e[0];if(!n)return Uo(t.cwd),{kind:"continue"};if(n==="add"){let o=Ai(t.cwd,e[1],e[2]);return o?(console.log(S(o)),{kind:"continue"}):(console.log(_(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${W(`/profile ${e[1]}`)} then ${W("/login")}`),{kind:"continue"})}return Wo(t.cwd,n),Fo(t.cwd,n),console.log(m(" Restarting agent for the new profile\u2026")),{kind:"clear"}}z();import{select as Ym}from"@inquirer/prompts";import{readProjectConfig as zm,readUserConfig as ku,resolveModelSetting as Ei,writeUserConfig as bu}from"document360-engine";var Ke=[{value:null,label:"Auto",desc:"Sonnet (latest) \u2014 right-sized for docs work (recommended); heavier models only when you pin them"},{value:"claude-fable-5",label:"Fable",desc:"Fable 5 \xB7 most capable, for the hardest and longest-running tasks"},{value:"opus",label:"Opus",desc:"Opus (latest) \xB7 best for everyday complex tasks"},{value:"sonnet",label:"Sonnet",desc:"Sonnet (latest) \xB7 efficient for routine tasks"},{value:"haiku",label:"Haiku",desc:"Haiku (latest) \xB7 fastest for quick answers"}];function gr(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=Ke.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function Km(e){switch(e.source){case"project":return".d360-writer/config.json defaultModel (team setting)";case"user":return"~/.document360-writer/config.json (your /model setting)";case"env":return"ANTHROPIC_MODEL environment variable";case"auto":return"auto \u2014 the docs-right default (newest Sonnet); /model to pin another"}}function Kn(e,t){let n=()=>Ei(e).model;if(t==="default"){let s=ku();return s.defaultModel?(delete s.defaultModel,bu(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${Ei(e).model} (auto; applies from your next message)`],changed:!0,effective:n()}):{lines:["No personal model override set \u2014 nothing to clear."],changed:!1,effective:void 0}}bu({...ku(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=zm(e)?.defaultModel;return r&&o.push(`\u26A0 .d360-writer/config.json sets defaultModel "${r}" \u2014 the team setting overrides yours until it is removed.`),{lines:o,changed:!0,effective:n()}}async function $u(e,t){let n=e[0]?.trim();if(!n){let a=Ei(t.cwd);if(!process.stdin.isTTY)return console.log(`${Se("Model:")} ${W(a.model)}${a.source==="auto"?m(" (auto)"):""}`),console.log(m(` source: ${Km(a)}`)),console.log(m(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let u=gr(a),p;try{p=await t.withPausedInput(()=>Ym({message:`Select model (current: ${a.model}${a.source==="auto"?" \xB7 auto":""})`,default:Ke[u].value,choices:Ke.map((x,j)=>({name:`${x.label}${j===u?" \u2714":""}`,value:x.value,description:x.desc}))}))}catch{return console.log(m("Cancelled.")),{kind:"continue"}}let{lines:b,changed:k,effective:$}=Kn(t.cwd,p??"default");for(let x of b)console.log(x.startsWith("\u26A0")?B(x):x.startsWith("\u2713")?_(x):m(x));return k&&await t.setModel($),{kind:"continue"}}let{lines:o,changed:r,effective:s}=Kn(t.cwd,n);for(let a of o)console.log(a.startsWith("\u26A0")?B(a):a.startsWith("\u2713")?_(a):m(a));return r&&await t.setModel(s),{kind:"continue"}}wr();async function Du(e,t){return await t.withPausedInput(()=>rn(t.cwd)),{kind:"clear"}}async function Au(e,t){return await t.withPausedInput(()=>Oo(t.cwd,t.profileName)),{kind:"clear"}}z();import{resolveActiveProfile as yg}from"document360-engine";async function Eu(e,t){let n=!1;try{n=yg(t.cwd).production}catch{}return n?(console.log(B("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(m("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}z();var ju=async(e,t)=>{try{await t.withPausedInput(()=>Mo({}))}catch(n){console.log(S(`Login failed: ${n.message}`))}return{kind:"continue"}};z();import{resolveActiveProfile as wg,clearTokens as kg,clearProfileProject as bg}from"document360-engine";async function Nu(e,t){let n;try{n=wg(t.cwd,t.profileName).name}catch(r){return console.log(S(r.message)),{kind:"continue"}}let o=kg(n);return bg(t.cwd,n),console.log(o?_(`\u2713 Signed out of "${n}" and cleared its project/workspace selection.`):m(`Profile "${n}" was not signed in. Cleared any project/workspace selection.`)),console.log(m("Run /login to sign in and pick a project.")),{kind:"continue"}}import{spawn as Iu}from"node:child_process";import{existsSync as _i,readFileSync as Oi,statSync as $g}from"node:fs";import{homedir as xg}from"node:os";import{basename as vg,isAbsolute as Cg,join as mn,resolve as Rg}from"node:path";import{readProjectConfig as Sg,DEFAULT_OUTPUT_DIR as Pg}from"document360-engine";var Tg=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Li(e){let t=e.find(o=>!o.startsWith("--")),n=e.includes("--retry-blocked");return e.includes("--failed")?{mode:"failed"}:e.includes("--all")?{mode:"all",retryBlocked:n}:t?/[\\/]/.test(t)||t.endsWith(".md")?{mode:"scope",scope:Tg(t),retryBlocked:n}:{mode:"single",id:t}:{mode:"picker"}}function kr(e,t){let n=We(e,t),o=r=>n.filter(s=>s.state===r).map(s=>s.id);return{ready:o("spec"),captured:o("captured"),blocked:o("blocked"),broken:o("broken"),rows:n}}function Ou(e){let t=e.filter(s=>s.state==="spec"),n=e.filter(s=>s.state==="captured"),o=[],r=t.filter(s=>!s.mutates);r.length>1&&o.push({kind:"all",action:"capture",label:`Capture all ${r.length} ready specs`,ids:r.map(s=>s.id),depth:0}),Qo(o,t,"capture"),Gs(o,e.filter(s=>s.state==="blocked"),e.filter(s=>s.state==="broken"));for(let s of[...n].sort((a,u)=>a.id.localeCompare(u.id)))o.push({kind:"shot",action:"capture",label:s.id,ids:[s.id],depth:1,note:" \u25CF captured \u2014 re-capture"});return o}function Mi(e,t){let n=new Set(t.filter(o=>o.state!=="placeholder").map(o=>o.id));return fc(e).filter(o=>n.has(o))}function Ui(e,t){let n=e.length;if(n===0)return null;let o=Hs(e).length;return[`\u2298 ${n} shot${n===1?"":"s"} excluded \u2014 ${n===1?"its data prerequisite wasn't":"their data prerequisites weren't"} met last run. Stage the data, then:`,` ${t}`,` /screenshot list shows what to stage (${o} action${o===1?"":"s"}).`].join(`
345
+ `)}var Ti="Nothing to document yet. Say what changed: /document <what you shipped> \u2014 or have the builder drop a request via their /devhints hand-off.";async function pu(e,t){let n=t?.cwd??process.cwd();if(!Um(n))return console.log(S("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=Si(e);if(!r&&Ri(n)===0)return console.log(m(Ti)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:Pi(r,o),display:s}}z();import{search as Wm}from"@inquirer/prompts";import{findByName as Fm,getSession as Bm,listSessions as qm,relativeTime as fu}from"document360-engine";async function mu(e,t){let n=qm(t.cwd).filter(o=>o.uuid!==t.currentUuid());if(n.length===0)return console.log(m("No saved sessions for this repo yet \u2014 sessions auto-save as you work.")),{kind:"continue"};if(e.length>0){let o=e.join(" "),r=Fm(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(S(`No session matches "${o}".`)),hu(n),{kind:"continue"})}if(!process.stdin.isTTY)return hu(n),console.log(m("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>Wm({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let a=(s??"").toLowerCase();return n.filter(u=>!a||u.name.toLowerCase().includes(a)||u.firstPrompt.toLowerCase().includes(a)).map(u=>({name:`${u.name} ${fu(u.updatedAt)}`,value:u.uuid,description:u.firstPrompt.slice(0,100)}))}})),r=Bm(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function hu(e){console.log("");for(let t of e.slice(0,15))console.log(` ${W(t.name)} ${m(fu(t.updatedAt))}`),console.log(` ${m(t.firstPrompt.slice(0,80))}`);console.log("")}z();import{renameSession as Hm}from"document360-engine";function Di(e){let t=e.trim();return t.length>=2&&(t[0]==='"'&&t.endsWith('"')||t[0]==="'"&&t.endsWith("'"))?t.slice(1,-1).trim():t}async function gu(e,t){let n=Di(e.join(" "));if(!n)return console.log(S("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(Hm(o,n)?console.log(_(`\u2713 Session renamed to "${n}"`)):console.log(S("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(_(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as yu,readProjectConfig as Vm,writeProjectConfig as Gm}from"document360-engine";z();function Ai(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=Vm(e);if(!o)return"No .d360-writer/config.json \u2014 run /init first.";if(o.profiles?.[t])return`Profile "${t}" already exists.`;let r=n??t;return yu().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},Gm(o,e),null):`Unknown environment "${r}". Known: ${yu().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function wu(e,t){let n=e[0];if(!n)return Uo(t.cwd),{kind:"continue"};if(n==="add"){let o=Ai(t.cwd,e[1],e[2]);return o?(console.log(S(o)),{kind:"continue"}):(console.log(_(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${W(`/profile ${e[1]}`)} then ${W("/login")}`),{kind:"continue"})}return Wo(t.cwd,n),Fo(t.cwd,n),console.log(m(" Restarting agent for the new profile\u2026")),{kind:"clear"}}z();import{select as Ym}from"@inquirer/prompts";import{readProjectConfig as zm,readUserConfig as ku,resolveModelSetting as Ei,writeUserConfig as bu}from"document360-engine";var Ke=[{value:null,label:"Auto",desc:"Sonnet (latest) \u2014 right-sized for docs work (recommended); heavier models only when you pin them"},{value:"claude-fable-5",label:"Fable",desc:"Fable 5 \xB7 most capable, for the hardest and longest-running tasks"},{value:"opus",label:"Opus",desc:"Opus (latest) \xB7 best for everyday complex tasks"},{value:"sonnet",label:"Sonnet",desc:"Sonnet (latest) \xB7 efficient for routine tasks"},{value:"haiku",label:"Haiku",desc:"Haiku (latest) \xB7 fastest for quick answers"}];function gr(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=Ke.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function Km(e){switch(e.source){case"project":return".d360-writer/config.json defaultModel (team setting)";case"user":return"~/.document360-writer/config.json (your /model setting)";case"env":return"ANTHROPIC_MODEL environment variable";case"auto":return"auto \u2014 the docs-right default (newest Sonnet); /model to pin another"}}function Kn(e,t){let n=()=>Ei(e).model;if(t==="default"){let s=ku();return s.defaultModel?(delete s.defaultModel,bu(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${Ei(e).model} (auto; applies from your next message)`],changed:!0,effective:n()}):{lines:["No personal model override set \u2014 nothing to clear."],changed:!1,effective:void 0}}bu({...ku(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=zm(e)?.defaultModel;return r&&o.push(`\u26A0 .d360-writer/config.json sets defaultModel "${r}" \u2014 the team setting overrides yours until it is removed.`),{lines:o,changed:!0,effective:n()}}async function $u(e,t){let n=e[0]?.trim();if(!n){let a=Ei(t.cwd);if(!process.stdin.isTTY)return console.log(`${Se("Model:")} ${W(a.model)}${a.source==="auto"?m(" (auto)"):""}`),console.log(m(` source: ${Km(a)}`)),console.log(m(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let u=gr(a),p;try{p=await t.withPausedInput(()=>Ym({message:`Select model (current: ${a.model}${a.source==="auto"?" \xB7 auto":""})`,default:Ke[u].value,choices:Ke.map((x,j)=>({name:`${x.label}${j===u?" \u2714":""}`,value:x.value,description:x.desc}))}))}catch{return console.log(m("Cancelled.")),{kind:"continue"}}let{lines:b,changed:k,effective:$}=Kn(t.cwd,p??"default");for(let x of b)console.log(x.startsWith("\u26A0")?B(x):x.startsWith("\u2713")?_(x):m(x));return k&&await t.setModel($),{kind:"continue"}}let{lines:o,changed:r,effective:s}=Kn(t.cwd,n);for(let a of o)console.log(a.startsWith("\u26A0")?B(a):a.startsWith("\u2713")?_(a):m(a));return r&&await t.setModel(s),{kind:"continue"}}wr();async function Du(e,t){return await t.withPausedInput(()=>rn(t.cwd)),{kind:"clear"}}async function Au(e,t){return await t.withPausedInput(()=>Oo(t.cwd,t.profileName)),{kind:"clear"}}z();import{resolveActiveProfile as yg}from"document360-engine";async function Eu(e,t){let n=!1;try{n=yg(t.cwd).production}catch{}return n?(console.log(B("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(m("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}z();var ju=async(e,t)=>{try{await t.withPausedInput(()=>Mo({}))}catch(n){console.log(S(`Login failed: ${n.message}`))}return{kind:"continue"}};z();import{resolveActiveProfile as wg,clearTokens as kg,clearProfileProject as bg}from"document360-engine";async function Nu(e,t){let n;try{n=wg(t.cwd,t.profileName).name}catch(r){return console.log(S(r.message)),{kind:"continue"}}let o=kg(n);return bg(t.cwd,n),console.log(o?_(`\u2713 Signed out of "${n}" and cleared its project/workspace selection.`):m(`Profile "${n}" was not signed in. Cleared any project/workspace selection.`)),console.log(m("Run /login to sign in and pick a project.")),{kind:"continue"}}import{spawn as Iu}from"node:child_process";import{existsSync as _i,readFileSync as Oi,statSync as $g}from"node:fs";import{homedir as xg}from"node:os";import{basename as vg,isAbsolute as Cg,join as mn,resolve as Rg}from"node:path";import{readProjectConfig as Sg,DEFAULT_OUTPUT_DIR as Pg}from"document360-engine";var Tg=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Li(e){let t=e.find(o=>!o.startsWith("--")),n=e.includes("--retry-blocked");return e.includes("--failed")?{mode:"failed"}:e.includes("--all")?{mode:"all",retryBlocked:n}:t?/[\\/]/.test(t)||t.endsWith(".md")?{mode:"scope",scope:Tg(t),retryBlocked:n}:{mode:"single",id:t}:{mode:"picker"}}function kr(e,t){let n=ze(e,t),o=r=>n.filter(s=>s.state===r).map(s=>s.id);return{ready:o("spec"),captured:o("captured"),blocked:o("blocked"),broken:o("broken"),rows:n}}function Ou(e){let t=e.filter(s=>s.state==="spec"),n=e.filter(s=>s.state==="captured"),o=[],r=t.filter(s=>!s.mutates);r.length>1&&o.push({kind:"all",action:"capture",label:`Capture all ${r.length} ready specs`,ids:r.map(s=>s.id),depth:0}),Qo(o,t,"capture"),Gs(o,e.filter(s=>s.state==="blocked"),e.filter(s=>s.state==="broken"));for(let s of[...n].sort((a,u)=>a.id.localeCompare(u.id)))o.push({kind:"shot",action:"capture",label:s.id,ids:[s.id],depth:1,note:" \u25CF captured \u2014 re-capture"});return o}function Mi(e,t){let n=new Set(t.filter(o=>o.state!=="placeholder").map(o=>o.id));return fc(e).filter(o=>n.has(o))}function Ui(e,t){let n=e.length;if(n===0)return null;let o=Hs(e).length;return[`\u2298 ${n} shot${n===1?"":"s"} excluded \u2014 ${n===1?"its data prerequisite wasn't":"their data prerequisites weren't"} met last run. Stage the data, then:`,` ${t}`,` /screenshot list shows what to stage (${o} action${o===1?"":"s"}).`].join(`
346
346
  `)}function Dg(e,t){let n=Sg(e)?.outputDir??Pg;return Cg(n)?mn(n,`${t}.png`):Rg(e,n,`${t}.png`)}function Wi(e,t,n,o){let r=Dg(e,t);return _i(r)&&$g(r).mtimeMs>=o?"captured":n===0?"skipped":"failed"}function _u(e){let t=/⊘[^\n—]*—\s*(.+)/.exec(e);return t?t[1].trim():null}function Lu(e){let n=e.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).filter(o=>/\b\w*Error\b|Cannot navigate|Timeout \d+m?s (exceeded|waiting)|net::|browser has been closed/i.test(o)&&!/^Error Context:/i.test(o));return n.length>0?[...new Set(n)].slice(0,3).join(`
347
347
  `):Fi(e)}function Fi(e,t=4){let n=/captured\s+·|^▶ Annotating|^✓ \d+ captured|^\s*[⊘✗]\s+\S+\s*$|^▶ Running \d+ spec/;return e.split(/\r?\n/).map(r=>r.trimEnd()).filter(r=>r.trim().length>0&&!n.test(r.trim())).slice(-t).join(`
348
348
  `)}var Ag=/^[A-Za-z0-9._-]+$/;function Bi(e){return new Promise((t,n)=>{if(!Ag.test(e.id)){n(new Error(`Not a valid spec id: "${e.id}"`));return}let o=Iu(`d360-capture capture ${e.id}`,{cwd:e.cwd,shell:!0,stdio:e.stdio==="inherit"?"inherit":["ignore","pipe","pipe"],env:{...process.env,NO_UPDATE_NOTIFIER:"1"}}),r="";e.stdio==="pipe"&&(o.stdout?.on("data",a=>{r+=a.toString()}),o.stderr?.on("data",a=>{r+=a.toString()}));let s=()=>{o.kill()};e.signal?.addEventListener("abort",s,{once:!0}),o.on("error",a=>{e.signal?.removeEventListener("abort",s),n(a)}),o.on("close",a=>{e.signal?.removeEventListener("abort",s),t({exitCode:a??1,output:r})})})}function Mu(e,t=xg()){try{let n=JSON.parse(Oi(mn(e,".d360-writer","capture.json"),"utf8").replace(/^/,"")),o=n.projectId;if(!o)try{o=JSON.parse(Oi(mn(e,"package.json"),"utf8")).name}catch{}o||=vg(e);let r=Object.keys(n.profiles??{}),s=n.defaultProfile??(r.length===1?r[0]:r.includes("staging")?"staging":r[0]);return s?_i(mn(t,".document360-capture","auth-states",o,`${s}.json`)):!0}catch{return!0}}function Uu(e){return new Promise((t,n)=>{let o=Iu("d360-capture auth --auto",{cwd:e.cwd,shell:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,NO_UPDATE_NOTIFIER:"1"}}),r="";o.stdout?.on("data",a=>{r+=a.toString()}),o.stderr?.on("data",a=>{r+=a.toString()});let s=()=>{o.kill()};e.signal?.addEventListener("abort",s,{once:!0}),o.on("error",a=>{e.signal?.removeEventListener("abort",s),n(a)}),o.on("close",a=>{e.signal?.removeEventListener("abort",s),t({exitCode:a??1,output:r})})})}function qi(e,t){return e===127||/is not recognized as an internal or external command|command not found/i.test(t)}function Wu(e){try{let t=JSON.parse(Oi(mn(e,".d360-writer","capture.json"),"utf8").replace(/^/,"")),n=Object.keys(t.profiles??{}),o=t.defaultProfile??(n.length===1?n[0]:n.includes("staging")?"staging":n[0]),r=o?t.profiles?.[o]:void 0;return{production:!!r?.production,name:o,url:r?.connection?.startUrl}}catch{return{production:!1}}}function br(e){return _i(mn(e,".d360-writer","capture.json"))}function Hi(){return["Screenshot capture is not configured in this repo yet (no `.d360-writer/capture.json`). Set it up","conversationally \u2014 never tell the user to run `d360-capture init`:","","1. Find the live app URL yourself first: `.d360-writer/config.json` `appUrl`, the product brief, the"," architecture brief, the repo (README, deploy config). Present what you found for confirmation \u2014 or"," ask for it if unknown. In the SAME message also ask: (a) is that URL the production environment?"," (b) which prepared demo context should screenshots enter \u2014 the capture scope (read the product"," source to know what this product scopes by: project / workspace / org; a single-context product"," needs none). One short numbered message, then END YOUR TURN and wait for the answers.","2. On the answers, write `.d360-writer/capture.json` in exactly this shape (fill the values):","```json","{",' "projectId": "<projectId from .d360-writer/config.json>",',' "profiles": {',' "<production or staging, matching their answer>": {',' "connection": { "startUrl": "<the app URL>" },',' "production": <true when they said production>,',' "scope": { "<scopeKey>": "<their demo context>" }'," }"," },",' "defaultProfile": "<the same profile name>"',"}","```"," Omit `scope` for a single-context product. Do not add captureDir/outputDir (defaults apply).","3. Also record the app URL as `appUrl` in `.d360-writer/config.json` \u2014 add/update just that key,",' preserving everything else. It is the canonical "where the product lives" fact (you may use it to'," deep-link stable app screens from articles).","4. Close with the ONE remaining external step, then the retry:"," `d360-capture auth` (run in this repo's terminal; first time also `npm i -g document360-capture`)"," then `/screenshot capture`."].join(`
349
349
  `)}function Fu(e,t){let n=e.filter(a=>a.state==="blocked"&&a.blockedBy!=="testid").length,o=e.filter(a=>a.state==="blocked"&&a.blockedBy==="testid").length,r=t+n+o;if(r===0)return null;let s=[];return t>0&&s.push(`${t} write${t===1?"s":""} real data`),n>0&&s.push(`${n} blocked on data`),o>0&&s.push(`${o} wait${o===1?"s":""} on a developer`),` ${r} held back \u2014 ${s.join(", ")}
350
350
  /screenshot list --detail shows what each one needs`}function Bu(e,t){let n=r=>e.shots[r]?.outcome,o={newlyCaptured:[],newlyBlocked:[],stillBroken:[],newlyBroken:[],blockedAsBefore:[]};for(let r of t){let s=n(r.id);r.outcome==="captured"&&s!=="captured"?o.newlyCaptured.push(r.id):r.outcome==="skipped"?(s==="skipped"?o.blockedAsBefore:o.newlyBlocked).push(r.id):r.outcome==="failed"&&(s==="failed"?o.stillBroken:o.newlyBroken).push(r.id)}return o}function qu(e,t=72){let o=((e??"no error text captured").split(/\r?\n/).map(r=>r.trim()).find(Boolean)??"").replace(/^(Error|TimeoutError):\s*/i,"").replace(/\s+/g," ");return o.length>t?`${o.slice(0,t-1)}\u2026`:o}function Ii(e,t=2){return e.length<=t?e.join(" \xB7 "):`${e.slice(0,t).join(" \xB7 ")} \xB7 +${e.length-t}`}function Hu(e,t){if(!t)return[];let n=[],o=(r,s,a,u)=>{s>0&&n.push(` ${r} ${`${s} ${a}`.padEnd(22)}${u}`)};return o("\u2713",e.newlyCaptured.length,"newly captured",Ii(e.newlyCaptured)),o("\u2717",e.newlyBroken.length,"newly broken",Ii(e.newlyBroken)),o("\u2298",e.newlyBlocked.length,"newly blocked",Ii(e.newlyBlocked)),o("\u2717",e.stillBroken.length,"still broken","unchanged \u2014 these need re-authoring"),o("\xB7",e.blockedAsBefore.length,"blocked as before","nothing staged since last time"),n.length>0?[""," Since your last run",...n]:[]}function Vu(e){let t=e.results.filter($=>$.outcome==="captured"),n=e.results.filter($=>$.outcome==="skipped"),o=e.results.filter($=>$.outcome==="failed"),r=$=>$===1?"":"s";if(t.length+n.length+o.length===0)return null;let s=e.articles.length===1?`/publish ${e.articles[0]}`:"/publish --screenshots",a=e.ids.length===1?`/screenshot capture ${e.ids[0]}`:"/screenshot capture",u=o[0]?.id,p=[];o.length>0&&p.push({glyph:"\u2717",cmd:`/screenshot ${u}`,why:`re-author the ${o.length===1?"broken spec":`first of ${o.length} broken specs`} \u2014 re-running fails the same way`}),n.length>0&&p.push({glyph:"\u2298",cmd:"/screenshot list",why:`what to stage for the ${n.length} blocked shot${r(n.length)}`}),t.length>0&&p.push({glyph:"\u2713",cmd:s,why:`embed the ${t.length} new PNG${r(t.length)}`});let b=Math.max(...p.map($=>$.cmd.length));return{note:p.map($=>`${$.glyph} ${$.cmd.padEnd(b)} ${$.why}`).join(`
351
- `),cmd:o.length>0?`/screenshot ${u}`:t.length>0?s:a,tone:o.length>0?"warn":"info"}}function Gu(e,t){let n=new Map(We(e).map(o=>[o.id,o.file]));return[...new Set(t.map(o=>n.get(o)).filter(o=>!!o))].sort()}async function Vi(e,t){let n=t?.cwd??process.cwd(),o=Li(e);if(!br(n))return console.log("Screenshot capture is not set up in this repo yet. Run: d360-capture init"),{kind:"continue"};let{ready:r,captured:s,blocked:a,rows:u}=kr(n,o.mode==="scope"?o.scope:void 0),p=Mi(n,u),b=(o.mode==="all"||o.mode==="scope")&&o.retryBlocked,k=o.mode==="single"?[o.id]:o.mode==="failed"?p:o.mode==="picker"?r:[...r,...s,...b?a:[]];if(k.length===0)return o.mode==="failed"?console.log("No broken specs to re-run \u2014 /screenshot list shows where things stand."):console.log("No authored specs to capture yet \u2014 author them first: /screenshot"),{kind:"continue"};if(!b&&o.mode!=="single"&&o.mode!=="failed"){let v=Ui(u.filter(D=>D.state==="blocked"),"/screenshot capture --all --retry-blocked");v&&console.log(v)}let $=Date.now(),x=[];for(let v of k){console.log(`\u25B6 ${v}`);try{let{exitCode:D}=await Bi({cwd:n,id:v,stdio:"inherit"});x.push({id:v,outcome:Wi(n,v,D,$)})}catch(D){if(D.code==="ENOENT")return console.log("d360-capture is not installed. Run: npm i -g document360-capture"),{kind:"continue"};x.push({id:v,outcome:"failed",detail:D.message})}}let j=v=>x.filter(D=>D.outcome===v).length;return console.log(`\u2713 ${j("captured")} captured \xB7 \u2298 ${j("skipped")} skipped \xB7 \u2717 ${j("failed")} failed`),{kind:"continue"}}import{existsSync as Eg,readFileSync as jg}from"node:fs";import{isAbsolute as Ng,join as Ig,resolve as Og}from"node:path";import{readProjectConfig as _g,DEFAULT_CAPTURE_DIR as Lg}from"document360-engine";async function gn(){return{kind:"forward-to-agent",prompt:["Run the capture-setup-checklist skill.","","Scan every <!-- SCREENSHOT --> block across the docs tree (the configured docsDir), read each block\u2019s prerequisites,","anchor them to the capture scope keys in .d360-writer/capture.json, then synthesize a deduped, grouped","\u201Cstage this data\u201D checklist and write it to <captureDir>/CAPTURE-CHECKLIST.md. Separate transient/manual","states, flag any spec whose prerequisites are vague, and report the path when done."].join(`
351
+ `),cmd:o.length>0?`/screenshot ${u}`:t.length>0?s:a,tone:o.length>0?"warn":"info"}}function Gu(e,t){let n=new Map(ze(e).map(o=>[o.id,o.file]));return[...new Set(t.map(o=>n.get(o)).filter(o=>!!o))].sort()}async function Vi(e,t){let n=t?.cwd??process.cwd(),o=Li(e);if(!br(n))return console.log("Screenshot capture is not set up in this repo yet. Run: d360-capture init"),{kind:"continue"};let{ready:r,captured:s,blocked:a,rows:u}=kr(n,o.mode==="scope"?o.scope:void 0),p=Mi(n,u),b=(o.mode==="all"||o.mode==="scope")&&o.retryBlocked,k=o.mode==="single"?[o.id]:o.mode==="failed"?p:o.mode==="picker"?r:[...r,...s,...b?a:[]];if(k.length===0)return o.mode==="failed"?console.log("No broken specs to re-run \u2014 /screenshot list shows where things stand."):console.log("No authored specs to capture yet \u2014 author them first: /screenshot"),{kind:"continue"};if(!b&&o.mode!=="single"&&o.mode!=="failed"){let v=Ui(u.filter(D=>D.state==="blocked"),"/screenshot capture --all --retry-blocked");v&&console.log(v)}let $=Date.now(),x=[];for(let v of k){console.log(`\u25B6 ${v}`);try{let{exitCode:D}=await Bi({cwd:n,id:v,stdio:"inherit"});x.push({id:v,outcome:Wi(n,v,D,$)})}catch(D){if(D.code==="ENOENT")return console.log("d360-capture is not installed. Run: npm i -g document360-capture"),{kind:"continue"};x.push({id:v,outcome:"failed",detail:D.message})}}let j=v=>x.filter(D=>D.outcome===v).length;return console.log(`\u2713 ${j("captured")} captured \xB7 \u2298 ${j("skipped")} skipped \xB7 \u2717 ${j("failed")} failed`),{kind:"continue"}}import{existsSync as Eg,readFileSync as jg}from"node:fs";import{isAbsolute as Ng,join as Ig,resolve as Og}from"node:path";import{readProjectConfig as _g,DEFAULT_CAPTURE_DIR as Lg}from"document360-engine";async function gn(){return{kind:"forward-to-agent",prompt:["Run the capture-setup-checklist skill.","","Scan every <!-- SCREENSHOT --> block across the docs tree (the configured docsDir), read each block\u2019s prerequisites,","anchor them to the capture scope keys in .d360-writer/capture.json, then synthesize a deduped, grouped","\u201Cstage this data\u201D checklist and write it to <captureDir>/CAPTURE-CHECKLIST.md. Separate transient/manual","states, flag any spec whose prerequisites are vague, and report the path when done."].join(`
352
352
  `),display:"/screenshot checklist"}}var Yu="-".repeat(64);function Gi(e){let t=Lg;try{let k=_g(e);k?.captureDir&&(t=k.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=Ng(t)?Ig(t,"CAPTURE-TESTID-REQUESTS.json"):Og(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!Eg(n))return null;let o;try{let k=JSON.parse(jg(n,"utf8").replace(/^/,""));o=Array.isArray(k?.requests)?k.requests:[]}catch{return null}if(o.length===0)return null;let r=new Set(o.map(k=>k.file).filter(Boolean)).size,s=o.length,a=`${s} data-testid attribute${s===1?"":"s"}`,u=`${r} source file${r===1?"":"s"}`,p=`${t}/CAPTURE-TESTID-REQUESTS.md`,b=`${t}/CAPTURE-TESTID-REQUESTS.json`;return[`\u{1F4CB} Developer hand-off \u2014 ${a} requested across ${u}.`,"\u26A0 Do NOT run this prompt here. d360-writer documents code; it does not change it \u2014"," these edits belong in your code repo. Open a SEPARATE terminal in:",` ${e}`," start Claude Code (or your coding agent), and paste everything between the lines."," Tip: run it in plan mode first \u2014 these are a hypothesis to verify, not a verified patch.","",Yu,`Read ${p} and ${b}. They list ${a} that d360-writer THINKS this repo needs for screenshot automation. Treat them as a hypothesis to VERIFY against the source \u2014 not a verified patch list.`,"","For EACH request in the JSON:",'1. Locate the element in THIS repo. Trace it from the route/page, not the feature name. If "anchorVerified" is false, find it by the "element"/"reason" description; otherwise confirm the "anchor" snippet still exists in "file".',"2. If the element already has a data-testid, skip it and note the existing one.","3. Confirm the attribute will reach the DOM: the rendering component must forward unknown props (a {...rest} spread or explicit pass-through). If it is a shared wrapper (e.g. Modal, ContextMenu) that destructures a fixed prop list, a data-testid is silently dropped \u2014 thread it through the component, or report it as needing a code change instead of forcing it.",'4. Only then add data-testid="<testid>" to the verified element. Add nothing else; do not rename, restructure, reformat, or change behaviour.',"","When done, report: which testids you added (file + element), which were already present, which requests were wrong (wrong file/anchor/page) with the correction, and which need threading through a shared component. Never force a request that does not match the source \u2014 flag it instead.",Yu]}ft();z();import{listOpenForDocs as Mg,readProjectConfig as Ug}from"document360-engine";function Yi(e){try{return Mg(e).length}catch{return 0}}function zi(){return["Process the two-way message inbox from the source repo's coding agent (the builder).","","1. Call d360_inbox to list the OPEN messages addressed to you.","2. For each message, act by its kind:",' \u2022 request ("document the X we shipped") \u2192 treat it as a session hand-off: run the document-handoff'," skill \u2014 read what changed, ground it in the cited sources + the architecture brief, then decide and"," apply the RIGHT doc action (new section, new article, update existing, or retire). No fixed shape.",' \u2022 answer to a [discovery]-tagged question (subject starts "[discovery] ") \u2192 this is product-discovery,'," not an article edit: fold the fact into `.d360-writer/product-brief.md` (updating the cited grounding,"," clearing the matching OPEN marker), then RE-RUN the discover-product readiness assessment \u2014 set the"," brief's frontmatter status to `confident` and offer propose-structure if every rubric dimension now"," passes, else ask the next focused batch via d360_ask_builder. Do not touch articles for these.",' \u2022 answer to a [depth]-tagged question (subject starts "[depth] ") \u2192 this is per-feature depth-mining,'," not the brief and not an article edit: fold it into the DOCS PLAN per propose-structure's"," depth-reconcile \u2014 adjust that feature's article palette in plan.json/AGENT-PLAN.md (add rows citing"," the answer's .d360-writer/messages/ file in `sources`, never renumber existing rows), decrement"," open_depth_questions in AGENT-PLAN.md's frontmatter, and flip status to `pinned` at zero."," \u2022 answer (a reply to any other question you asked; `re` = your question id) \u2192 fold the fact into the"," affected article(s), and into `.d360-writer/architecture/` if it is durable product knowledge.","3. After acting on a message, mark it resolved: edit its file in `.d360-writer/messages/` and set the"," frontmatter `status: done` (add `done_at` with the current UTC time). Never delete the file.","4. Drafts only \u2014 do not publish unless explicitly asked. End with a one-line summary of what you did per"," message (and, for any request you could not fully ground, what you still need)."].join(`
353
353
  `)}async function zu(e,t){let n=t?.cwd??process.cwd();return Ug(n)?Yi(n)===0?(console.log(m("Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)")),{kind:"continue"}):{kind:"forward-to-agent",prompt:zi(),display:"/inbox"}:(console.log(S("No d360-writer config here. Run /init first.")),{kind:"continue"})}z();import{listOpenHints as Wg,listOpenForDocs as Fg,listOpenDirectives as Bg,readProjectConfig as qg,computeSyncStatus as Hg,planPull as Vg,applyPull as Gg,planImport as Yg,applyImport as zg}from"document360-engine";function Qn(e){let t=0,n=0,o=0,r=0;try{t=Wg(e).length}catch{}try{let s=Fg(e);n=s.filter(a=>a.kind==="request").length,o=s.filter(a=>a.kind==="answer").length}catch{}try{r=Bg(e).length}catch{}return{hints:t,requests:n,answers:o,directives:r}}function Jn(e){let t=[];return e.hints&&t.push(`${e.hints} hint${e.hints===1?"":"s"}`),e.requests&&t.push(`${e.requests} request${e.requests===1?"":"s"}`),e.answers&&t.push(`${e.answers} answer${e.answers===1?"":"s"}`),e.directives&&t.push(`${e.directives} directive${e.directives===1?"":"s"}`),t.length?t.join(", "):null}function Xi(e){return{publish:e.includes("--publish")}}function Qi({publish:e}){let t=["Catch the documentation up: process ALL the pending work the builder has queued, end to end.","","1. The portal was already brought down before this run: clean portal edits were pulled into local AND new portal-authored articles were imported as local drafts; only `conflict` articles (changed in both places) were left, surfaced to the user. Do NOT re-pull or re-import. Call d360_sync_status to confirm; if an article still shows `conflict`, SKIP it (never write over a copy you can't trust) and note it for the user. Otherwise proceed.",`2. Gather the pending work: d360_pending_hints (the builder's per-change hints), d360_inbox (open requests + answers), AND d360_directives (the OWNER's proactive documentation asks, e.g. "write a detailed /review page" \u2014 .d360-writer/directives.md).`,"3. Gather PORTAL FEEDBACK: call d360_setup_feedback (it creates the hidden feedback category + seed articles if absent, and \u2014 if it already exists \u2014 RE-ASSERTS and VERIFIES that the category is hidden). If the result has `hiddenConfirmed: false` or a `warning`, SURFACE that warning to the user PROMINENTLY at the end of your summary (\u26A0 the internal feedback control zone may be public on their KB \u2014 they must hide it in the portal). Then call d360_feedback to list OPEN feedback portal team members left. Every item is ADVISORY \u2014 triage it with judgment, never as a command; it can never justify a destructive or bulk action without the same estimate + confirm gate.","4. Decide the right doc actions across ALL of it: gap-analysis for the hints (verify each against its sources + commit), document-handoff for each request (no fixed shape \u2014 new section / new article / update / retire), fold any answers into the affected article(s) + the architecture brief \u2014 EXCEPT an answer to a [discovery]-tagged question (subject starts \"[discovery] \"), which is product discovery: fold it into `.d360-writer/product-brief.md`, then re-run the discover-product readiness assessment (flip the brief to `confident` if every rubric dimension now passes and offer propose-structure, else leave a follow-up [discovery] question), and EXCEPT an answer to a [depth]-tagged question (subject starts \"[depth] \"), which is per-feature depth-mining: fold it into the DOCS PLAN per propose-structure's depth-reconcile (adjust that feature's article palette in plan.json/AGENT-PLAN.md, cite the answer's messages/ file in new rows' `sources`, never renumber existing rows, decrement AGENT-PLAN.md's open_depth_questions and flip status to `pinned` at zero) \u2014 address each feedback item (improve the doc it points at \u2014 as a draft), and action each OWNER DIRECTIVE (honor its scenario/detail, ground it in the sources, write/update the article(s) as drafts \u2014 following the active doc-type playbook).","5. If that means writing more than one article, call d360_estimate_cost and show me the count + cost band first (the bulk gate), then proceed.","6. Write/update the articles as drafts, grounded in the cited sources.","7. Close the loop:"," \u2022 stamp consumed hints, and mark handled messages status: done with resulting_articles;"," \u2022 for each OWNER DIRECTIVE you actioned: call d360_directive_done with its exact title + the article path(s) you wrote (flips it to [done] in .d360-writer/directives.md);"," \u2022 reconcile the DOCS ROADMAP (d360_roadmap): flip any campaign step this run completed (d360_roadmap_done) \u2014 including a step whose work you can verify an EARLIER session already completed but left unstamped \u2014 and append a step (d360_roadmap_add, with its run: command) for real new campaign work this run revealed \u2014 never delete existing steps;"," \u2022 for each portal feedback item you actioned: append a short note at the BOTTOM of that feedback article via d360_update_article \u2014 `**d360-writer response:** \u2713 actioned in <article> \u2014 <date>` (or `declined \u2014 <reason>`) \u2014 NEVER overwriting the person's own text \u2014 then call d360_feedback_done(article_id, resulting_articles);"," \u2022 EXCEPT the Creator-notes item (is_creator_notes:true): do NOT reply in it \u2014 instead fold its content into `.d360-writer/architecture/CREATOR-NOTES.md` as an appended, dated `## From portal Creator notes (<date>)` section (preserve every existing note + human edit), then call d360_feedback_done for it.","8. Push the drafts to Document360.","9. Cross-link second pass: any article you wrote that links to ANOTHER article in this same batch had that inline link degrade to plain text (its target had no live URL yet when the source was written). Now that every target exists, re-update the affected articles so those inline links resolve to live URLs \u2014 only the ones that had such forward references need it. (The structured Related Articles sidebars are already two-way linked; this is just inline body links.)"];return t.push(e?"10. Then publish the new/updated articles live (publish-to-d360 skill), respecting the production write-guard.":"Leave everything as DRAFTS for review \u2014 do not publish live (run /publish when you want them live)."),t.push("","End with a one-line-per-item summary of what you wrote/updated, and anything you couldn't ground (plus the d360_ask_builder question you left for it)."),t.join(`
354
354
  `)}var Kg={status:Hg,plan:Vg,apply:Gg,planImport:Yg,applyImport:zg};async function Ji(e,t=Kg){let n={pulled:[],imported:[],conflicts:[],failed:[]},o;try{o=await t.status({cwd:e.cwd,profileName:e.profileName})}catch(r){return n.error=r.message,n}for(let r of o.entries)if(r.status==="conflict"&&r.path)n.conflicts.push(r.path);else if(r.status==="untracked-remote"&&r.articleId)try{let s=await t.planImport({cwd:e.cwd,profileName:e.profileName,articleId:r.articleId});t.applyImport({cwd:e.cwd,profileName:e.profileName},s),n.imported.push(s.path)}catch(s){n.failed.push({path:r.title??r.articleId,error:s.message})}else if(r.status==="remote-ahead"&&r.path)try{let s=await t.plan({cwd:e.cwd,profileName:e.profileName,relPath:r.path});t.apply({cwd:e.cwd,profileName:e.profileName},s),n.pulled.push(r.path)}catch(s){n.failed.push({path:r.path,error:s.message})}return n}var Ki=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,$r=e=>e===1?"":"s";function Zi(e){if(e.error)return[`\u26A0 Couldn't check Document360 for portal changes (${e.error.slice(0,100)}) \u2014 proceeding; the agent will re-check.`];let t=[];return e.pulled.length&&t.push(`\u2713 Pulled ${e.pulled.length} portal edit${$r(e.pulled.length)} into local: ${Ki(e.pulled)}`),e.imported.length&&t.push(`\u2713 Imported ${e.imported.length} new portal article${$r(e.imported.length)} into local drafts: ${Ki(e.imported)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${$r(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${Ki(e.conflicts)}`),e.failed.length&&t.push(`\u26A0 ${e.failed.length} pull/import${$r(e.failed.length)} failed \u2014 left for /pull.`),t}async function Ku(e,t){let n=t?.cwd??process.cwd();if(!qg(n))return console.log(S("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Ue(n,t?.profileName);if(!o.ok)return console.log(S(o.reason)),{kind:"continue"};let{publish:r}=Xi(e);console.log(m("Reconciling with Document360 (pulling any portal changes)\u2026"));let s=await Ji({cwd:n,profileName:t?.profileName});for(let u of Zi(s))console.log(u.startsWith("\u2713")?_(u):u.startsWith("\u2139")?m(u):B(u));let a=Jn(Qn(n));return console.log(m(a?`Catching up on ${a}\u2026`:"Checking for code changes the builder didn't hint\u2026")),{kind:"forward-to-agent",prompt:Qi({publish:r}),display:`/catch-up${r?" --publish":""}`}}z();import{spawn as Xu}from"node:child_process";var yn="document360-writer",xr=`npm i -g ${yn}@latest`,Xg="document360-capture";function Qg(){return new Promise(e=>{try{let t=Xu("d360-capture --version",{stdio:"ignore",shell:!0,windowsHide:!0});t.on("error",()=>e(!1)),t.on("close",n=>e(n===0))}catch{e(!1)}})}async function vr(){let e=process.platform==="win32",n=await Qg()?[yn,Xg]:[yn];return new Promise(o=>{try{let r=Xu(`npm i -g ${n.map(s=>`${s}@latest`).join(" ")}`,{stdio:"ignore",shell:!0,detached:!e,windowsHide:!0});r.on("error",s=>o({ok:!1,output:String(s),packages:n})),r.on("close",s=>o({ok:s===0,output:"",packages:n})),e||r.unref()}catch(r){o({ok:!1,output:String(r),packages:n})}})}async function Qu(){console.log(m("Updating the d360-writer toolchain\u2026"));let e=await vr();return e.ok?console.log(_(`\u2713 Updated ${e.packages.join(" + ")}. Exit (/exit) and relaunch d360-writer to apply.`)):console.log(S(`Update failed \u2014 run manually: ${xr}`)),{kind:"continue"}}z();ft();import{existsSync as ea,rmSync as Jg}from"node:fs";import{basename as Ju,resolve as ta}from"node:path";import{execFileSync as Zg}from"node:child_process";import{input as ey}from"@inquirer/prompts";import{readProjectConfig as ty,devHintsGuidePath as ny}from"document360-engine";var oy=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],ry=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),Cr=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),Zu=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function ed(e){let t=Cr(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:Zu(t)?!0:ry.has(t)}function na(e){let t=null;try{t=ty(e)}catch{t=null}let n=new Set(oy);for(let o of[Cr(t?.docsDir),Cr(t?.captureDir),Cr(t?.outputDir)])o&&Zu(o)&&n.add(o);return[...n].filter(o=>ed(o)&&ea(ta(e,o)))}function oa(e,t){let n=[],o=[];for(let r of t){if(!ed(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{Jg(ta(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function td(e,t){try{return Zg("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
@@ -368,9 +368,9 @@ ${o.body}`:"","",`Close the loop IN THE SAME TURN the step's goal state is reach
368
368
  \u2022 `),lead:{kind:"cmd",cmd:"/catch-up",reason:n},picker:null,follow:"Then /catch-up clears what\u2019s queued for the docs."})}if(e.hasDocs&&e.pendingWrites>0){let n=e.pendingWrites;t.push({key:"write",bullet:`${n} planned article${ge(n)} still unwritten`,lead:{kind:"cmd",cmd:"/write",reason:"it finishes the articles already planned"},picker:null,follow:`Then /write finishes the ${n} planned article${ge(n)}.`})}if(e.localAhead>0){let n=e.localAhead;t.push({key:"publish",bullet:`${n} article${ge(n)} changed locally \u2014 ready to publish`,lead:{kind:"cmd",cmd:"/publish",reason:`it pushes your ${n} local edit${ge(n)} up to Document360`},picker:null,follow:`Then /publish pushes your ${n} local edit${ge(n)} up.`})}if(e.conflicts>0){let n=e.conflicts;t.push({key:"resolve",bullet:`${n} article${ge(n)} changed both here and on Document360 (conflicts) \u2014 /publish skips these`,lead:{kind:"cmd",cmd:"/resolve",reason:"it walks each conflict \u2014 keep yours, take the portal's, or skip"},picker:null,follow:`Then /resolve settles the ${n} conflict${ge(n)} (keep yours / take the portal's / skip).`})}if(e.hasDocs&&e.roadmap?.next){let n=e.roadmap,o=n.next;t.push({key:"roadmap",bullet:`docs campaign: ${n.done} of ${n.total} step${ge(n.total)} done \u2014 next: ${o.title}`,lead:o.run?{kind:"cmd",cmd:o.run,reason:"it\u2019s the next step of your docs campaign"}:{kind:"prompt",text:o.title,reason:"it\u2019s the next step of your docs campaign"},picker:null,follow:`Then the campaign continues: ${o.title} (/roadmap shows all ${n.total} steps).`})}if(e.behind>0){let n=e.behind;t.push({key:"audit",bullet:`${n} code change${ge(n)} since your last docs check`,lead:{kind:"cmd",cmd:"/audit",reason:"it shows what the latest code changes touch (or /audit --auto on to run it for you)"},picker:null,follow:`After that, /audit covers the ${n} newer commit${ge(n)}.`})}if(e.uncommittedDocs>0){let n=e.uncommittedDocs;t.push({key:"commit",bullet:`\u26A0 ${n} uncommitted change${ge(n)} under .d360-writer/ \u2014 tell your coding agent: "commit d360-writer's work"`,lead:null,picker:null,follow:null})}return t}function wd(e){return e.find(t=>t.lead||t.picker)??null}function da(e,t){let n=t.filter(a=>a.bullet).map(a=>` \u2022 ${a.bullet}`),o=wd(t),r=[];o?.lead?r.push(eo(o.lead)):o?.picker&&r.push("Pick the genre below \u2014 one keypress, and it shapes everything I write.");for(let a of t.filter(u=>u!==o).slice(0,2))a.follow&&r.push(a.follow);let s=[[e,...n].join(`
369
369
  `)];return r.length&&s.push(r.join(" ")),s.push(Cy),s.join(`
370
370
 
371
- `)}function to(e){if(!e.ready)return{kind:"idle"};let t=Py(e);if(!e.hasDocs){let s=wd(t);return s&&(s.lead?.kind==="cmd"||s.picker)?{kind:"recommend",rec:{note:da("\u{1F4ED} No docs yet for this repo \u2014 here\u2019s where things stand:",t),tone:s.tone??"info",lead:s.lead,picker:s.picker}}:{kind:"recommend",rec:{note:Ry,tone:"info",lead:{kind:"prompt",text:"write the docs for this repo",reason:"I\u2019ll read the code and draft a structure"},picker:null}}}if(t.length===0){let s=e.roadmap&&!e.roadmap.next?` Docs campaign complete \u2014 all ${e.roadmap.total} step${ge(e.roadmap.total)} done (/roadmap).`:"";return{kind:"recommend",rec:{note:`Welcome back. Your ${e.tracked} tracked article${ge(e.tracked)} for \u201C${e.profileName}\u201D are all in sync \u2014 /audit re-checks the code, /pull brings down portal edits.${s}`,tone:"info",lead:null,picker:null}}}let n=t.filter(s=>s.lead||s.picker),o=n[0]??null;return o?(o.key==="audit"||o.key==="roadmap"&&n[1]?.key==="audit")&&e.behind>0&&e.autoAudit&&e.allowAutoAudit?{kind:"autoAudit",note:`\u{1F4CB} ${e.behind} code change${ge(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`}:{kind:"recommend",rec:{note:da("Welcome back \u2014 where your docs stand:",t),tone:o.tone??"info",lead:o.lead,picker:o.picker}}:{kind:"recommend",rec:{note:da("Welcome back \u2014 where your docs stand:",t),tone:"info",lead:null,picker:null}}}import{existsSync as pa,readdirSync as fa}from"node:fs";import{spawnSync as Ty}from"node:child_process";import{join as Ar}from"node:path";import{readProjectConfig as bd,resolveActiveProfile as $d,loadTokens as Dy,isExpired as Ay,loadProfileMap as xd,localAheadPaths as Ey,loadKnownConflicts as jy,readDocsPlan as Ny,devHintsGuidePath as Iy,DEFAULT_DOCS_DIR as ha,roadmapProgress as Oy,listRoadmap as _y,readProductBriefState as Ly,reconcileCommitRequest as My}from"document360-engine";ft();function kd(e){try{return fa(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function ma(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>kd(Ar(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&kd(Ar(e,o)))}function ga(e,t){try{let n=bd(e);if(!n)return!1;let o=$d(e,t),r=xd(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=Ar(e,(n.docsDir??ha).replace(/\/+$/,""));return!!(pa(s)&&fa(s).length>0||pa(Iy(e)))}catch{return!1}}function no(e,t,n){try{let o=bd(e);if(!o)return null;let r=$d(e,t),s=Dy(r.name),a=!!s&&(!Ay(s)||!!s.refreshToken),u=ga(e,t)||!ma(e,o.authoritativeSourceFiles),p=xd(e,r.name),b=p?Object.keys(p.articles).length:0,k=Ar(e,(o.docsDir??ha).replace(/\/+$/,"")),$=!1;try{$=pa(k)&&fa(k).length>0}catch{}let x=0;if(p?.lastAnalyzedCommit)try{let me=Ty("git",["rev-list","--count",`${p.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});me.status===0&&(x=parseInt((me.stdout||"").trim(),10)||0)}catch{}let j=0;try{let me=Ny(e);if(me.length>0){let Qe=(o.docsDir??ha).replace(/\/+$/,"");j=mi(e,Qe,me.map(be=>be.path)).length}}catch{}let v=Qn(e),D=Jn({...v,directives:0}),E=Ey(e,t),U=new Set(jy(e,r.name)),L=E.filter(me=>U.has(me)).length,G=E.length-L,H=Me(e),se=Oy(e),qe=My(e,new Date().toISOString()),fe=Ly(e),Xe=fe?{status:fe.status,openQuestions:fe.openQuestions}:null;return!Xe&&$&&_y(e).some(Qe=>Qe.status==="open"&&(Qe.run??"").trim()==="/discover")&&(Xe={status:"pending",openQuestions:0}),{ready:a&&u&&!n.claudeMissing,hasDocs:$,tracked:b,pendingText:D,directives:v.directives,behind:x,pendingWrites:j,localAhead:G,conflicts:L,autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:H.status,devhintsCompletedVersion:H.completedVersion,devhintsToVersion:de,builderStarted:rt(e),genreUnknown:n.genreUnknown,roadmap:se,discovery:Xe,uncommittedDocs:qe.dirty.length}}catch{return null}}z();var Uy={Bash:"command",PowerShell:"command",Read:"file_path",Write:"file_path",Edit:"file_path",NotebookEdit:"notebook_path",Glob:"pattern",Grep:"pattern",WebFetch:"url",WebSearch:"query",Agent:"description",Task:"description",Skill:"skill"},Cd=160,wa=200,Rd=40;function je(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function vd(e){let t=Object.entries(e).filter(([,o])=>o!=null&&o!=="");if(t.length===0)return null;let n=t.slice(0,4).map(([o,r])=>`${o}: ${je(typeof r=="string"?r:JSON.stringify(r),Rd)}`);return t.length>4&&n.push("\u2026"),je(n.join(", "),Cd)}var Wy=new Set(["file_path","notebook_path"]);function Fy(e,t){if(!t)return e;let n=a=>a.replace(/\\/g,"/").replace(/\/+$/,""),o=n(e),r=`${n(t)}/`;return(process.platform==="win32"?o.toLowerCase().startsWith(r.toLowerCase()):o.startsWith(r))?o.slice(r.length):e}var bt=e=>typeof e=="string"&&e?e:null,ya=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function By(e){let t=bt(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);if(n.length<2)return null;let o=n[n.length-2],r=o.replace(/^\d+[-_.]/,"").split(/[-_]/).filter(Boolean);return r.length===0?o:r.map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" ")}function qy(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=bt(t.title);if(!o)return null;let r=By(t.local_path);return n("Create article",`"${je(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=bt(t.title),r=ya(t.article_id);return n("Update article",o?`"${je(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",ya(t.article_id)?`id ${ya(t.article_id)}\u2026`:null);case"d360_publish_article":{let o=t.version_number;return n("Publish article LIVE",typeof o=="number"?`v${o}`:null)}case"d360_unpublish_article":return n("Unpublish article",null);case"d360_create_category":return n("Create category",bt(t.name)?`"${je(bt(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=bt(t.file_path);return n("Upload image",o?je(o.replace(/\\/g,"/").split("/").pop()??o,60):null)}case"d360_sync_status":return n("Check sync status",null);default:return null}}function Er(e,t,n){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,s="",...a]=e.split("__"),u=a.join("__");if(s==="document360"){let k=qy(u,t);if(k)return k}let p=u.replace(/^d360_/,"").replace(/_/g," ");return{title:`${s==="document360"?"Document360":s.charAt(0).toUpperCase()+s.slice(1)}: ${p}`,sep:" ",arg:vd(t)}}let o=Uy[e],r=o?t[o]:void 0;if(typeof r=="string"&&r){let s=o&&Wy.has(o)?Fy(r,n):r;return{title:e,sep:"",arg:je(s,Cd)}}return{title:e,sep:"",arg:vd(t)}}function Hy(e){if(e===null||typeof e!="object")return typeof e=="string"?e:null;let t=e;for(let n of["name","title","slug","id"])if(typeof t[n]=="string"&&t[n])return t[n];return null}function Vy(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(Hy).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>je(r,wa))]}if(t!==null&&typeof t=="object"){let n=Object.entries(t).filter(([,o])=>o!==null&&(typeof o=="string"||typeof o=="number"||typeof o=="boolean")).slice(0,6).map(([o,r])=>`${o}: ${je(String(r),Rd)}`);return n.length>0?[je(n.join(" \xB7 "),wa)]:null}return null}function Gy(e){let t=bt(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function Yy(e,t,n){switch(e){case"d360_create_article":{let o=Gy(t?.local_path);return[`\u2713 draft created${o?` \xB7 ${o}`:""}`]}case"d360_update_article":return["\u2713 draft updated"];case"d360_fork_article":return["\u2713 forked to a new draft"];case"d360_publish_article":return["\u2713 PUBLISHED LIVE \u2014 visible to readers"];case"d360_unpublish_article":return["\u2713 reverted to draft (removed from readers)"];case"d360_create_category":{let o=bt(t?.name);return[`\u2713 category created${o?` \xB7 "${o}"`:""}`]}case"d360_upload_drive_file":{let o=n.match(/https?:\/\/\S+/);return[`\u2713 uploaded${o?` \xB7 ${je(o[0],120)}`:""}`]}default:return null}}function jr(e,t=4,n,o){let r=e.replace(/\r\n/g,`
371
+ `)}function to(e){if(!e.ready)return{kind:"idle"};let t=Py(e);if(!e.hasDocs){let s=wd(t);return s&&(s.lead?.kind==="cmd"||s.picker)?{kind:"recommend",rec:{note:da("\u{1F4ED} No docs yet for this repo \u2014 here\u2019s where things stand:",t),tone:s.tone??"info",lead:s.lead,picker:s.picker}}:{kind:"recommend",rec:{note:Ry,tone:"info",lead:{kind:"prompt",text:"write the docs for this repo",reason:"I\u2019ll read the code and draft a structure"},picker:null}}}if(t.length===0){let s=e.roadmap&&!e.roadmap.next?` Docs campaign complete \u2014 all ${e.roadmap.total} step${ge(e.roadmap.total)} done (/roadmap).`:"";return{kind:"recommend",rec:{note:`Welcome back. Your ${e.tracked} tracked article${ge(e.tracked)} for \u201C${e.profileName}\u201D are all in sync \u2014 /audit re-checks the code, /pull brings down portal edits.${s}`,tone:"info",lead:null,picker:null}}}let n=t.filter(s=>s.lead||s.picker),o=n[0]??null;return o?(o.key==="audit"||o.key==="roadmap"&&n[1]?.key==="audit")&&e.behind>0&&e.autoAudit&&e.allowAutoAudit?{kind:"autoAudit",note:`\u{1F4CB} ${e.behind} code change${ge(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`}:{kind:"recommend",rec:{note:da("Welcome back \u2014 where your docs stand:",t),tone:o.tone??"info",lead:o.lead,picker:o.picker}}:{kind:"recommend",rec:{note:da("Welcome back \u2014 where your docs stand:",t),tone:"info",lead:null,picker:null}}}import{existsSync as pa,readdirSync as fa}from"node:fs";import{spawnSync as Ty}from"node:child_process";import{join as Ar}from"node:path";import{readProjectConfig as bd,resolveActiveProfile as $d,loadTokens as Dy,isExpired as Ay,loadProfileMap as xd,localAheadPaths as Ey,loadKnownConflicts as jy,readDocsPlan as Ny,devHintsGuidePath as Iy,DEFAULT_DOCS_DIR as ha,roadmapProgress as Oy,listRoadmap as _y,readProductBriefState as Ly,reconcileCommitRequest as My}from"document360-engine";ft();function kd(e){try{return fa(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function ma(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>kd(Ar(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&kd(Ar(e,o)))}function ga(e,t){try{let n=bd(e);if(!n)return!1;let o=$d(e,t),r=xd(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=Ar(e,(n.docsDir??ha).replace(/\/+$/,""));return!!(pa(s)&&fa(s).length>0||pa(Iy(e)))}catch{return!1}}function no(e,t,n){try{let o=bd(e);if(!o)return null;let r=$d(e,t),s=Dy(r.name),a=!!s&&(!Ay(s)||!!s.refreshToken),u=ga(e,t)||!ma(e,o.authoritativeSourceFiles),p=xd(e,r.name),b=p?Object.keys(p.articles).length:0,k=Ar(e,(o.docsDir??ha).replace(/\/+$/,"")),$=!1;try{$=pa(k)&&fa(k).length>0}catch{}let x=0;if(p?.lastAnalyzedCommit)try{let me=Ty("git",["rev-list","--count",`${p.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});me.status===0&&(x=parseInt((me.stdout||"").trim(),10)||0)}catch{}let j=0;try{let me=Ny(e);if(me.length>0){let Qe=(o.docsDir??ha).replace(/\/+$/,"");j=mi(e,Qe,me.map(be=>be.path)).length}}catch{}let v=Qn(e),D=Jn({...v,directives:0}),E=Ey(e,t),U=new Set(jy(e,r.name)),L=E.filter(me=>U.has(me)).length,G=E.length-L,H=Me(e),se=Oy(e),Be=My(e,new Date().toISOString()),fe=Ly(e),Xe=fe?{status:fe.status,openQuestions:fe.openQuestions}:null;return!Xe&&$&&_y(e).some(Qe=>Qe.status==="open"&&(Qe.run??"").trim()==="/discover")&&(Xe={status:"pending",openQuestions:0}),{ready:a&&u&&!n.claudeMissing,hasDocs:$,tracked:b,pendingText:D,directives:v.directives,behind:x,pendingWrites:j,localAhead:G,conflicts:L,autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:H.status,devhintsCompletedVersion:H.completedVersion,devhintsToVersion:de,builderStarted:rt(e),genreUnknown:n.genreUnknown,roadmap:se,discovery:Xe,uncommittedDocs:Be.dirty.length}}catch{return null}}z();var Uy={Bash:"command",PowerShell:"command",Read:"file_path",Write:"file_path",Edit:"file_path",NotebookEdit:"notebook_path",Glob:"pattern",Grep:"pattern",WebFetch:"url",WebSearch:"query",Agent:"description",Task:"description",Skill:"skill"},Cd=160,wa=200,Rd=40;function je(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function vd(e){let t=Object.entries(e).filter(([,o])=>o!=null&&o!=="");if(t.length===0)return null;let n=t.slice(0,4).map(([o,r])=>`${o}: ${je(typeof r=="string"?r:JSON.stringify(r),Rd)}`);return t.length>4&&n.push("\u2026"),je(n.join(", "),Cd)}var Wy=new Set(["file_path","notebook_path"]);function Fy(e,t){if(!t)return e;let n=a=>a.replace(/\\/g,"/").replace(/\/+$/,""),o=n(e),r=`${n(t)}/`;return(process.platform==="win32"?o.toLowerCase().startsWith(r.toLowerCase()):o.startsWith(r))?o.slice(r.length):e}var bt=e=>typeof e=="string"&&e?e:null,ya=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function By(e){let t=bt(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);if(n.length<2)return null;let o=n[n.length-2],r=o.replace(/^\d+[-_.]/,"").split(/[-_]/).filter(Boolean);return r.length===0?o:r.map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" ")}function qy(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=bt(t.title);if(!o)return null;let r=By(t.local_path);return n("Create article",`"${je(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=bt(t.title),r=ya(t.article_id);return n("Update article",o?`"${je(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",ya(t.article_id)?`id ${ya(t.article_id)}\u2026`:null);case"d360_publish_article":{let o=t.version_number;return n("Publish article LIVE",typeof o=="number"?`v${o}`:null)}case"d360_unpublish_article":return n("Unpublish article",null);case"d360_create_category":return n("Create category",bt(t.name)?`"${je(bt(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=bt(t.file_path);return n("Upload image",o?je(o.replace(/\\/g,"/").split("/").pop()??o,60):null)}case"d360_sync_status":return n("Check sync status",null);default:return null}}function Er(e,t,n){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,s="",...a]=e.split("__"),u=a.join("__");if(s==="document360"){let k=qy(u,t);if(k)return k}let p=u.replace(/^d360_/,"").replace(/_/g," ");return{title:`${s==="document360"?"Document360":s.charAt(0).toUpperCase()+s.slice(1)}: ${p}`,sep:" ",arg:vd(t)}}let o=Uy[e],r=o?t[o]:void 0;if(typeof r=="string"&&r){let s=o&&Wy.has(o)?Fy(r,n):r;return{title:e,sep:"",arg:je(s,Cd)}}return{title:e,sep:"",arg:vd(t)}}function Hy(e){if(e===null||typeof e!="object")return typeof e=="string"?e:null;let t=e;for(let n of["name","title","slug","id"])if(typeof t[n]=="string"&&t[n])return t[n];return null}function Vy(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(Hy).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>je(r,wa))]}if(t!==null&&typeof t=="object"){let n=Object.entries(t).filter(([,o])=>o!==null&&(typeof o=="string"||typeof o=="number"||typeof o=="boolean")).slice(0,6).map(([o,r])=>`${o}: ${je(String(r),Rd)}`);return n.length>0?[je(n.join(" \xB7 "),wa)]:null}return null}function Gy(e){let t=bt(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function Yy(e,t,n){switch(e){case"d360_create_article":{let o=Gy(t?.local_path);return[`\u2713 draft created${o?` \xB7 ${o}`:""}`]}case"d360_update_article":return["\u2713 draft updated"];case"d360_fork_article":return["\u2713 forked to a new draft"];case"d360_publish_article":return["\u2713 PUBLISHED LIVE \u2014 visible to readers"];case"d360_unpublish_article":return["\u2713 reverted to draft (removed from readers)"];case"d360_create_category":{let o=bt(t?.name);return[`\u2713 category created${o?` \xB7 "${o}"`:""}`]}case"d360_upload_drive_file":{let o=n.match(/https?:\/\/\S+/);return[`\u2713 uploaded${o?` \xB7 ${je(o[0],120)}`:""}`]}default:return null}}function jr(e,t=4,n,o){let r=e.replace(/\r\n/g,`
372
372
  `).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let a=Yy(n.slice(18),o,r);if(a)return{lines:a,hidden:0}}let s=Vy(r)??r.split(`
373
- `);return{lines:s.slice(0,t).map(a=>je(a,wa)),hidden:Math.max(0,s.length-t)}}function Nr(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function Ir(e,t){if(typeof e.article_id=="string"&&e.article_id)return e.article_id;try{let n=JSON.parse(t),r=(Array.isArray(n)?n[0]:n)?.id;return typeof r=="string"&&r?r:null}catch{return null}}function Sd(e,t){try{let n=JSON.parse(e),r=(Array.isArray(n)?n[0]:n)?.[t];return typeof r=="string"&&/^https?:\/\//.test(r)?r:null}catch{return null}}function Or(e){return Sd(e,"url")}function _r(e){return Sd(e,"preview_url")}var hw=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function fw(e,t,n,o){if(hw.test(e))try{let r=Dd(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,a=Ir(t,n),u=Or(n);e.endsWith("publish_article")&&u&&console.log(W(` \u2B95 Live: ${u}`));let p=_r(n);p?console.log(W(` \u2B95 Preview: ${p}`)):a&&s&&console.log(W(` \u2B95 Preview: ${Nr(r.connection.portalUrl,s,a,r.project.languageCode??"en")}`))}catch{}}async function Ad(e=process.cwd(),t="auto",n,o){let r=Ky(t);r.kind==="none"&&(console.error(""),console.error(S("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${W("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${W('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${W("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${W("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),mw(e,n),r.kind==="subscription"&&(r.stored?console.log(m(" Using your Claude subscription (no API key set).")):console.log(m(" No API key or stored Claude Code login found \u2014 trying your Claude session anyway.")),console.log(""));let s=!1,a=ka({cwd:e,profileName:n,allowProdWrites:s}),u={uuid:null,firstPrompt:null,titleFired:!1},p=zy({input:process.stdin,output:process.stdout}),b=[],k=null,$=!1;p.on("line",v=>{if(k){let D=k;k=null,D(v)}else b.push(v)}),p.on("close",()=>{if($=!0,k){let v=k;k=null,v(null)}});function x(){return b.length>0?Promise.resolve(b.shift()):$?Promise.resolve(null):(process.stdout.write(W("> ")),new Promise(v=>{k=v}))}let j={cwd:e,version:o,profileName:n,allowProdWrites:()=>s,restartAgent:()=>{a.close(),a=ka({cwd:e,profileName:n,allowProdWrites:s}),u={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>u.uuid,setPendingName:v=>{u.pendingName=v},setModel:async v=>a.setModel(v),withPausedInput:async v=>{p.pause();try{return await v()}finally{p.resume()}}};try{for(;;){let v=await x();if(v===null)break;let D=v.trim();if(D){if(D.startsWith("/")){let E=yd(D);if(!E)continue;let U=gd[E.name];if(!U){console.log(S(`Unknown command: /${E.name}`)),console.log(m("Type /help for the list."));continue}let L=await U(E.args,j);if(L.kind==="exit")break;if(L.kind==="clear"){j.restartAgent();continue}if(L.kind==="allow-prod"){s=!0,j.restartAgent(),console.log(_("\u2713 Production writes authorized for this session.")),console.log("");continue}if(L.kind==="resume"){a.close(),a=ka({cwd:e,resume:L.uuid,profileName:n,allowProdWrites:s});let G=Xy(L.uuid);u={uuid:L.uuid,firstPrompt:G?.firstPrompt??null,titleFired:!0},Td(L.uuid),console.log(_(`\u2713 Resumed "${L.name}"`)),console.log("");continue}if(L.kind==="forward-to-agent"){u.firstPrompt||(u.firstPrompt=L.display??L.prompt);let G=(L.display??"").trim().split(/\s+/),H=(G[0]==="/check"||G[0]==="/review")&&G.includes("--fix"),se=G.slice(1).find(fe=>!fe.startsWith("--")),qe=H?dw(e,se):[];if(await ba(a,L.prompt,r,u,e),H)try{uw(e,qe,{reviewedCap:pw})}catch{}}else gw(e,n);continue}if(iw(D)){let E=aw(D);if(E){try{lw(e,{title:E,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}u.firstPrompt||(u.firstPrompt=D),await ba(a,`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${E}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${E}" and the article path(s) you wrote.`,r,u,e);continue}}u.firstPrompt||(u.firstPrompt=D),await ba(a,D,r,u,e)}}}finally{a.close(),p.close()}}function mw(e,t){console.log(""),console.log(On("document360-writer")),console.log(m(` cwd: ${e}`));let n=tw(e);if(console.log(m(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(yw(e,t)),!nw(e))console.log(B(" First run: /init (scaffolds config + prints the builder hand-off prompt) \u2192 /login, then ask me to write the docs."));else{let o=!1;try{if(qo(e),!rt(e))for(let r of Ho(e))console.log(B(` ${r}`))}catch{}try{let r=ow(e);r.persisted&&r.appType?console.log(m(` \u2713 Detected a ${r.appType} app \u2014 enabled the ${r.appType}-doc-playbook (change with /genre).`)):r.source==="unknown"&&(o=!0)}catch{}try{let r=cw(e);for(let s of Ko(r.applied))console.log(B(` ${s}`))}catch{}try{let r=no(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:o}),s=r?to(r):null;if(s?.kind==="recommend"&&s.rec.note){let a=s.rec.tone==="warn"?B:m;for(let u of Ns(s.rec.note).split(`
373
+ `);return{lines:s.slice(0,t).map(a=>je(a,wa)),hidden:Math.max(0,s.length-t)}}function Nr(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function Ir(e,t){if(typeof e.article_id=="string"&&e.article_id)return e.article_id;try{let n=JSON.parse(t),r=(Array.isArray(n)?n[0]:n)?.id;return typeof r=="string"&&r?r:null}catch{return null}}function Sd(e,t){try{let n=JSON.parse(e),r=(Array.isArray(n)?n[0]:n)?.[t];return typeof r=="string"&&/^https?:\/\//.test(r)?r:null}catch{return null}}function Or(e){return Sd(e,"url")}function _r(e){return Sd(e,"preview_url")}var hw=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function fw(e,t,n,o){if(hw.test(e))try{let r=Dd(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,a=Ir(t,n),u=Or(n);e.endsWith("publish_article")&&u&&console.log(W(` \u2B95 Live: ${u}`));let p=_r(n);p?console.log(W(` \u2B95 Preview: ${p}`)):a&&s&&console.log(W(` \u2B95 Preview: ${Nr(r.connection.portalUrl,s,a,r.project.languageCode??"en")}`))}catch{}}async function Ad(e=process.cwd(),t="auto",n,o){let r=Ky(t);r.kind==="none"&&(console.error(""),console.error(S("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${W("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${W('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${W("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${W("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),mw(e,n),r.kind==="subscription"&&(r.stored?console.log(m(" Using your Claude subscription (no API key set).")):console.log(m(" No API key or stored Claude Code login found \u2014 trying your Claude session anyway.")),console.log(""));let s=!1,a=ka({cwd:e,profileName:n,allowProdWrites:s}),u={uuid:null,firstPrompt:null,titleFired:!1},p=zy({input:process.stdin,output:process.stdout}),b=[],k=null,$=!1;p.on("line",v=>{if(k){let D=k;k=null,D(v)}else b.push(v)}),p.on("close",()=>{if($=!0,k){let v=k;k=null,v(null)}});function x(){return b.length>0?Promise.resolve(b.shift()):$?Promise.resolve(null):(process.stdout.write(W("> ")),new Promise(v=>{k=v}))}let j={cwd:e,version:o,profileName:n,allowProdWrites:()=>s,restartAgent:()=>{a.close(),a=ka({cwd:e,profileName:n,allowProdWrites:s}),u={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>u.uuid,setPendingName:v=>{u.pendingName=v},setModel:async v=>a.setModel(v),withPausedInput:async v=>{p.pause();try{return await v()}finally{p.resume()}}};try{for(;;){let v=await x();if(v===null)break;let D=v.trim();if(D){if(D.startsWith("/")){let E=yd(D);if(!E)continue;let U=gd[E.name];if(!U){console.log(S(`Unknown command: /${E.name}`)),console.log(m("Type /help for the list."));continue}let L=await U(E.args,j);if(L.kind==="exit")break;if(L.kind==="clear"){j.restartAgent();continue}if(L.kind==="allow-prod"){s=!0,j.restartAgent(),console.log(_("\u2713 Production writes authorized for this session.")),console.log("");continue}if(L.kind==="resume"){a.close(),a=ka({cwd:e,resume:L.uuid,profileName:n,allowProdWrites:s});let G=Xy(L.uuid);u={uuid:L.uuid,firstPrompt:G?.firstPrompt??null,titleFired:!0},Td(L.uuid),console.log(_(`\u2713 Resumed "${L.name}"`)),console.log("");continue}if(L.kind==="forward-to-agent"){u.firstPrompt||(u.firstPrompt=L.display??L.prompt);let G=(L.display??"").trim().split(/\s+/),H=(G[0]==="/check"||G[0]==="/review")&&G.includes("--fix"),se=G.slice(1).find(fe=>!fe.startsWith("--")),Be=H?dw(e,se):[];if(await ba(a,L.prompt,r,u,e),H)try{uw(e,Be,{reviewedCap:pw})}catch{}}else gw(e,n);continue}if(iw(D)){let E=aw(D);if(E){try{lw(e,{title:E,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}u.firstPrompt||(u.firstPrompt=D),await ba(a,`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${E}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${E}" and the article path(s) you wrote.`,r,u,e);continue}}u.firstPrompt||(u.firstPrompt=D),await ba(a,D,r,u,e)}}}finally{a.close(),p.close()}}function mw(e,t){console.log(""),console.log(On("document360-writer")),console.log(m(` cwd: ${e}`));let n=tw(e);if(console.log(m(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(yw(e,t)),!nw(e))console.log(B(" First run: /init (scaffolds config + prints the builder hand-off prompt) \u2192 /login, then ask me to write the docs."));else{let o=!1;try{if(qo(e),!rt(e))for(let r of Ho(e))console.log(B(` ${r}`))}catch{}try{let r=ow(e);r.persisted&&r.appType?console.log(m(` \u2713 Detected a ${r.appType} app \u2014 enabled the ${r.appType}-doc-playbook (change with /genre).`)):r.source==="unknown"&&(o=!0)}catch{}try{let r=cw(e);for(let s of Ko(r.applied))console.log(B(` ${s}`))}catch{}try{let r=no(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:o}),s=r?to(r):null;if(s?.kind==="recommend"&&s.rec.note){let a=s.rec.tone==="warn"?B:m;for(let u of Ns(s.rec.note).split(`
374
374
  `))console.log(a(` ${u}`));s.rec.picker&&console.log(W(` Pick one: ${s.rec.picker.options.map(u=>u.cmd).join(" \xB7 ")}`))}}catch{}}console.log(m(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function gw(e,t){try{let n=no(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:!1}),o=n?to(n):null;o?.kind==="recommend"&&o.rec.lead&&console.log(m(` Next: ${eo(o.rec.lead)}`))}catch{}}function yw(e,t){try{let n=Dd(e,t),o=n.production?B(" \u26A0 PRODUCTION"):"",r=sw(n.name);if(!r)return m(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...Pd(r.idToken)??{},...Pd(r.accessToken)??{}},a=s.email??s.preferred_username??"signed in";return rw(r)&&!r.refreshToken?B(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):m(` Document360: ${a} \xB7 profile "${n.name}"${o}`)}catch(n){return m(` Document360: ${n.message.split(".")[0]}`)}}function ww(){console.error(""),console.error(`Sign in with your Claude subscription: run ${W("claude")} once, then retry.`),console.error(` (No Claude Code? ${W("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${W("https://console.anthropic.com/settings/keys")}`)}function kw(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;Zy({uuid:t,name:r??Jy(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function bw(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||ew(o,t).then(r=>{r&&Qy(n,r)}).catch(()=>{})}async function ba(e,t,n,o,r){let s=new Map;for await(let a of e.send(t))$w(a,o,r,n,s)}function $w(e,t,n,o,r){switch(e.type){case"session":t.uuid||kw(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let s=Er(e.name,e.input,process.cwd());s&&(process.stdout.write(`
375
375
 
376
376
  `),console.log(`${_("\u25CF")} ${Se(s.title)}${s.arg!==null?ue(`${s.sep}(${s.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let s=it(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!s)break;let a=u=>u===1?"":"s";console.log(ue(` \u23BF Added ${s.added} line${a(s.added)}, removed ${s.removed} line${a(s.removed)}`));for(let u of s.lines)console.log(u);s.hidden>0&&console.log(m(` \u2026 +${s.hidden} more diff lines`));break}case"tool_result":{let s=r.get(e.id);if(!s)break;r.delete(e.id);let a=jr(e.output,4,e.isError?void 0:s.name,s.input),u=e.isError?S:ue;a.lines.forEach((p,b)=>console.log(u((b===0?" \u23BF ":" ")+p))),a.hidden>0&&console.log(m(` \u2026 +${a.hidden} lines`)),e.isError||fw(s.name,s.input,e.output,n);break}case"result":{process.stdout.write(`
@@ -378,7 +378,7 @@ ${o.body}`:"","",`Close the loop IN THE SAME TURN the step's goal state is reach
378
378
  `),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){Cw.test(s)&&(t.cueSeen=!0);continue}let a=/^(\s{0,3})[-*•]\s+(.*)$/.exec(s);a?(n[r]=`${a[1]}${++t.num}. ${a[2]}`,o=!0):o&&s.trim()!==""&&/^\S/.test(s)&&(t.closed=!0)}return n.join(`
379
379
  `)}import{existsSync as Rw,mkdirSync as Sw,readFileSync as Pw,writeFileSync as Tw}from"node:fs";import{join as jd}from"node:path";import{writerDir as Dw}from"document360-engine";function Nd(e){return jd(Dw(e),".sessions")}function Id(e,t){return jd(Nd(e),`${t}.json`)}function Od(e,t,n){try{Sw(Nd(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");Tw(Id(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function va(e,t){try{let n=Id(e,t);if(!Rw(n))return[];let o=JSON.parse(Pw(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var Aw=e=>`\x1B]0;${e}\x07`,Ew=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function _d(e){process.stdout.isTTY&&process.stdout.write(e)}function wn(e){_d(Aw(e))}function Lr(e){_d(Ew(e))}var Mr=["\xB7 "," \xB7"],Ur="\u{1F7E3}";wr();Yo();z();import{Box as Ld,Text as he}from"ink";import{jsx as ye,jsxs as Wr}from"react/jsx-runtime";function jw({row:e}){switch(e.t){case"head":return ye(he,{color:X,bold:!0,children:e.s});case"text":return ye(he,{children:e.s});case"dim":return ye(he,{dimColor:!0,children:e.s});case"sub":return ye(he,{bold:!0,dimColor:!0,children:e.s});case"good":return ye(he,{color:"green",children:e.s});case"step":return Wr(he,{children:[ye(he,{color:X,children:`${e.n}. `}),e.s]});case"cmd":return Wr(he,{children:[" ",ye(he,{color:X,children:e.name.padEnd(20)}),ye(he,{dimColor:!0,children:e.s})]});case"gap":return ye(he,{children:" "})}}function Md({tab:e,width:t,version:n,engineVersion:o}){let r=Le[e]??Le[0],s=6+Le.reduce((u,p)=>u+p.label.length+4,0),a="\u2500".repeat(Math.min(s,Math.max(t-1,20)));return Wr(Ld,{flexDirection:"column",paddingX:1,children:[Wr(he,{children:[ye(he,{color:X,bold:!0,children:"Help "}),Le.map((u,p)=>p===e?ye(he,{color:"white",backgroundColor:X,bold:!0,children:` ${u.label} `},u.key):ye(he,{dimColor:!0,children:` ${u.label} `},u.key))]}),ye(he,{color:X,children:a}),ye(Ld,{flexDirection:"column",marginTop:1,children:r.rows.map((u,p)=>ye(jw,{row:u},p))}),ye(he,{dimColor:!0,children:`
380
380
  \u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close \xB7 d360-writer v${n} \xB7 engine v${o}`})]})}var Nw=/^(?:\d+[.)]|[-*•])\s+/;function Ud(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
381
- `)){let a=s.trim().replace(Nw,""),u=a.match(/^`([^`]+)`$/);u&&(a=u[1].trim());let p=a.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!p||!o.has(p[1].toLowerCase()))continue;let b=`/${p[1].toLowerCase()}${p[2]?` ${p[2]}`:""}`;if(r.includes(b)||r.push(b),r.length>=n)break}return r}z();function oo(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function Fe(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function Wd(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var Iw=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function Fd(e,t,n){if(!Iw.has(e))return null;let o=t?.file_path;if(typeof o!="string"||!o)return null;let r=o.replace(/\\/g,"/");return n.find(s=>{let a=s.replace(/\\/g,"/");return r===a||r.endsWith(`/${a}`)})??null}function Ca(e){return e.replace(/^[\w.-]+\//,"")}var Fr=16,Bd={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function Mt(e){return typeof e=="string"?e:e.cmd}function qd(e){return typeof e=="string"?void 0:e.desc}function Ra(e){return e.trim().split(/\s+/).slice(1).join(" ")}function Hd(e,t){let n=Ra(t);return e.some(r=>Mt(r).trim()===t.trim()||!!n&&Ra(Mt(r))===n)?e.filter(r=>Mt(r).trim()!==t.trim()&&!(n&&Ra(Mt(r))===n)):[]}import{isDirectiveMention as xk,stripDirectiveMention as vk,appendDirective as Ck}from"document360-engine";var Ow=/\[Pasted text #\d+ \+\d+ lines?\]/g;function Vd(e){return e.replace(/\r\n?/g,`
381
+ `)){let a=s.trim().replace(Nw,""),u=a.match(/^`([^`]+)`$/);u&&(a=u[1].trim());let p=a.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!p||!o.has(p[1].toLowerCase()))continue;let b=`/${p[1].toLowerCase()}${p[2]?` ${p[2]}`:""}`;if(r.includes(b)||r.push(b),r.length>=n)break}return r}z();function oo(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function We(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function Wd(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var Iw=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function Fd(e,t,n){if(!Iw.has(e))return null;let o=t?.file_path;if(typeof o!="string"||!o)return null;let r=o.replace(/\\/g,"/");return n.find(s=>{let a=s.replace(/\\/g,"/");return r===a||r.endsWith(`/${a}`)})??null}function Ca(e){return e.replace(/^[\w.-]+\//,"")}var Fr=16,Bd={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function Mt(e){return typeof e=="string"?e:e.cmd}function qd(e){return typeof e=="string"?void 0:e.desc}function Ra(e){return e.trim().split(/\s+/).slice(1).join(" ")}function Hd(e,t){let n=Ra(t);return e.some(r=>Mt(r).trim()===t.trim()||!!n&&Ra(Mt(r))===n)?e.filter(r=>Mt(r).trim()!==t.trim()&&!(n&&Ra(Mt(r))===n)):[]}import{isDirectiveMention as xk,stripDirectiveMention as vk,appendDirective as Ck}from"document360-engine";var Ow=/\[Pasted text #\d+ \+\d+ lines?\]/g;function Vd(e){return e.replace(/\r\n?/g,`
382
382
  `)}function Gd(e){return e.includes(`
383
383
  `)||e.length>200}function Yd(e,t){let n=t.split(`
384
384
  `).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function zd(e,t){return e.replace(Ow,n=>t.get(n)??n)}function Kd(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function Br(e,t){let n=Math.max(1,t),o=[],r=0;for(let s of e.split(`
@@ -387,50 +387,50 @@ ${o.body}`:"","",`Close the loop IN THE SAME TURN the step's goal state is reach
387
387
  `),truncated:a>0||p>0}}}return{text:e,truncated:!1}}function Zd(e,t){if(t||e.length===0||/\s$/.test(e)||/[.!?:…]["')\]]?$/.test(e))return{head:e,keep:""};let n=e.search(/\s\S*$/);return n<0?{head:"",keep:e}:{head:e.slice(0,n),keep:e.slice(n)}}function ep(e){let t=!1,n=0,o=0;for(let r of e.split(`
388
388
  `)){let s=o+r.length;/^\s*```/.test(r)?t=!t:!t&&r.trim()===""&&s<e.length&&(n=s+1),o=s+1}return n}import{Fragment as so,jsx as I,jsxs as J}from"react/jsx-runtime";var Rk={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL",auto:"auto \u2014 right-sized for docs \xB7 /model to change"},gp=` 1. /init \u2014 pick your Document360 environment & scaffold config
389
389
  2. /login \u2014 sign in & pick your Document360 project (workspace auto-selected)
390
- 3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function Sk(e,t,n,o){let r=Na(n),s=r.state==="ready"?r.kind==="api"?"API key":"subscription":r.state==="maybe"?"subscription":"not signed in \u2014 run /doctor (needs Claude Code, not Claude Desktop)",a=Ia(e),u=ae(e),p=(u?.docsDir??Oa).replace(/\/+$/,""),b=u?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${p}/ + config`,k={version:t,engineVersion:kp,captureVersion:yr(),claude:s,model:a.model,modelSource:Rk[a.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:u!==null,mode:b};if(u===null)return k;try{let $=Ne(e,o);k.profile=$.name,k.apiUrl=$.connection.apiUrl,k.prod=$.production,k.project=$.project.projectName??$.project.projectId??"(chosen at login)";let x=Ut($.name);if(x){let j={...$n(x.idToken)??{},...$n(x.accessToken)??{}},v=j.email??j.preferred_username??"signed in";$t(x)?x.refreshToken&&(k.who=v,k.loggedOut=!1,k.sessionHint="session expired \u2014 refreshing\u2026"):(k.who=v,k.loggedOut=!1,k.sessionHint=`session valid until ${new Date(x.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return k}function Pk(e,t){try{let n=Ne(e,t),o=Ut(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...$n(o.idToken)??{},...$n(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return $t(o)&&!o.refreshToken?{text:`profile "${n.name}" \u2014 session expired (/login)`,prod:n.production}:{text:`${s} \xB7 profile "${n.name}"`,prod:n.production}}catch(n){return{text:n.message.split(".")[0],prod:!1}}}var yp=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],xn=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Tk="Ask me to write or update an article\u2026";function bn({ch:e,dim:t}){let[n,o]=K(!0);return Ie(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),I(N,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var Dk=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function wp(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var Ak=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ek({startTime:e,chars:t}){let[n,o]=K(0);Ie(()=>{let p=setInterval(()=>o(b=>b+1),120);return()=>clearInterval(p)},[]);let r=xn[n%xn.length],s=yp[Math.floor(n/16)%yp.length],a=Math.floor((Date.now()-e)/1e3),u=Math.round(t/4);return J(le,{children:[I(N,{color:X,children:` ${r} ${s}\u2026 `}),I(N,{color:"gray",children:`(${Bn(a)} \xB7 ~${u} tokens \xB7 esc to interrupt)`})]})}function jk({text:e}){let[t,n]=K(0);return Ie(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),I(le,{paddingX:1,children:I(N,{color:X,children:`${xn[t%xn.length]} ${e}`})})}var Nk=12e4;function Ik({p:e}){let[t,n]=K(0);Ie(()=>{let E=setInterval(()=>n(U=>U+1),150);return()=>clearInterval(E)},[]);let o=xn[t%xn.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),a=Math.round(e.chars/4),u=Date.now()-e.lastAt>=Nk,p=e.verb??"Converting",b=e.unit??"article",k=e.rows.reduce((E,U)=>E+U.items,0),$=p.toLowerCase(),x=e.rows,j=0;if(x.length>Fr){let E=x.findIndex(L=>L.status==="active"||L.status==="pending"),U=Math.max(0,Math.min(E-2,x.length-Fr));j=x.slice(0,U).filter(L=>L.status==="done").length,x=x.slice(U,U+Fr)}let v=Math.min(40,Math.max(...x.map(E=>Ca(E.label).length),0)),D=E=>E==="failed"?"red":E==="active"?X:void 0;return J(le,{flexDirection:"column",children:[J(le,{children:[I(N,{color:X,children:` ${o} ${p} ${k} ${b}${k===1?"":"s"} `}),I(N,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${a} tokens \xB7 ${Bn(r)} \xB7 esc to stop`})]}),j>0&&I(N,{dimColor:!0,children:` \u2714 +${j} done`}),x.map(E=>J(N,{color:D(E.status),dimColor:E.status==="done"||E.status==="pending",children:[` ${Bd[E.status]} ${Ca(E.label).padEnd(v)}`,E.status==="active"&&E.itemsDone!==void 0?` (${E.itemsDone}/${E.items} ${b}${E.items===1?"":"s"})`:E.status!=="pending"?` (${E.items} ${b}${E.items===1?"":"s"})`:"",E.status==="active"?` \u2190 ${$}\u2026`:""]},E.label)),u&&I(N,{color:"yellow",children:` \u26A0 no activity for ${Bn(s)} \u2014 press esc to stop if it's wedged`})]})}var Ok=10800*1e3;function bp({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=_w(),[s,a]=K(n),[u,p]=K(null),[b,k]=K({text:"",pos:0}),$=b.text,x=Q(c=>{k(l=>{let i=typeof c=="function"?c(l.text):c;return{text:i,pos:i.length}})},[]),j=Q(c=>{k(l=>({text:l.text.slice(0,l.pos)+c+l.text.slice(l.pos),pos:l.pos+c.length}))},[]),v=Q(()=>{k(c=>{if(c.pos===0)return c;let l=c.text.slice(0,c.pos),i=Kd(l)??l.slice(0,-1);return{text:i+c.text.slice(c.pos),pos:i.length}})},[]),[D,E]=K(!1),[U,L]=K(!1),[G,H]=K(0),[se,qe]=K(!1),[fe,Xe]=K(null),[me,Qe]=K(null),[be,He]=K([]),io=te(!1),vn=te(!1),zr=te(!1),[Kr,Ua]=K(!1),ao=te(0),[Pp,lo]=K(!1),[Tp,co]=K(!1),[Xr,Wa]=K(null),[Dp,Wt]=K(0),xt=te(0),[Qr,Ft]=K(0),[Bt,uo]=K(null),Fa=te(new Map),Ap=te(0),qt=te([]),Oe=te(null);Oe.current===null&&(Oe.current=tp({cwd:e,profileName:s,allowProdWrites:!1}));let Je=te({uuid:null,firstPrompt:null,titleFired:!1}),po=te(new Map),Ba=te(null),Ht=te(!1),Jr=te([]),pe=te([]),Vt=te([]),ho=te(null),[qa,vt]=K(null),Zr=te(null),[Ct,Rt]=K(null),[Ze,Gt]=K(null),[et,Yt]=K(null),[$e,zt]=K(null),[Te,St]=K(null),[at,Kt]=K(null),[lt,Pt]=K(null),[tt,Tt]=K(null),[Ha,Cn]=K(null),[De,Dt]=K(null),[Ce,Xt]=K(null),[Va,es]=K([]),At=te([]),Rn=te(!1),we=te(null),[fo,ie]=K(null),[Ga,mo]=K(null),go=te(!1),Sn=te(null),Pn=te(null),[Ae,Et]=K(null),[yo,Tn]=K(null),ts=!!(et||$e||Te||at||lt||tt||De||Ce||Ae||yo),[Ya,Qt]=K(0),[za,Jt]=K(0),[Ep,Ka]=K(0),ns=Sa(()=>{try{let c=Ia(e);return c.source==="auto"?`${c.model} (auto)`:c.model}catch{return null}},[e,Ep]),{stdout:_e}=Mw(),[,jp]=K(0),Xa=te(`${_e.columns??80}x${_e.rows??24}`),ct=Q(()=>Math.max(20,(_e.columns??80)-1),[_e]),d=Q(c=>{qt.current.push(c),console.log(Is(c,ct()))},[ct]),xe=Q((c,l)=>{ao.current++,Xe(c),Qe(l??null)},[]),Ve=Q(()=>{ao.current++,Xe(null),Qe(null)},[]),Z=Q(c=>xe(c,Dr({kind:"cmd",cmd:c,reason:""})),[xe]),wo=Q((c,l)=>{!l?.silent&&c.note&&d({kind:"note",tone:c.tone,text:c.note}),c.picker&&(He(c.picker.options.map(i=>({cmd:i.cmd,desc:i.desc}))),Cn(c.picker.title)),c.lead&&xe(c.lead.kind==="cmd"?c.lead.cmd:c.lead.text,Dr(c.lead))},[d,xe]),ve=Q((c,l,i="info")=>{c&&d({kind:"note",tone:i,text:c}),l&&xe(l.kind==="cmd"?l.cmd:l.text,Dr(l))},[d,xe]),[Dn,os]=K(null),[Np,Qa]=K(!1),Zt=Q(c=>{os(c),Qa(!1),d({kind:"note",tone:"info",text:"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[d]),rs=te(!1),ss=Q(async()=>{try{if(rs.current||!yk(gk())||ae(e)?.mode==="engineer")return;let c=await mk({pkg:yn,currentVersion:o,force:!0});if(!c.updateAvailable||!c.latest)return;rs.current=!0,d({kind:"note",tone:"info",text:`\u2B06 Updating ${yn} ${c.current} \u2192 ${c.latest}\u2026 (wait for the \u2713 before you /exit)`}),co(!0),(await vr().finally(()=>co(!1))).ok?(d({kind:"note",tone:"ok",text:`\u2713 Updated to v${c.latest} \u2014 run /exit, then relaunch to apply.`}),Z("/exit"),Wa(c.latest)):d({kind:"note",tone:"warn",text:`Update available (v${c.latest}) but auto-update failed \u2014 run: ${xr}`})}catch{}},[e,o,d,Z]),ko=Q(c=>{let l=Ue(e,s);return l.ok?!0:(d({kind:"note",tone:"warn",text:l.reason}),Pn.current=c,Z("/login"),!1)},[e,s,d,Z]),[bo,is]=K(null),jt=Q(c=>{let l=no(e,s,{claudeMissing:Na(t).state==="missing",allowAutoAudit:c,genreUnknown:zr.current});return l?to(l):{kind:"idle"}},[e,s,t]),An=te(!0),en=te(!1),$o=te(0),En=te(0);Ie(()=>{let c=setInterval(()=>{if(An.current){$o.current=0,En.current=0;return}if(!D)try{if(!kn(cp(e)))return;if(Me(e).status==="current"){An.current=!0,$o.current=0,En.current=0;let i=jt(!1),f=i.kind==="recommend"?i.rec:null,P=en.current?`\u2713 Your builder finished the protocol update (v${de}) \u2014 the dev\u2194docs hand-off is current again.`:"\u2713 Your builder finished the hand-off \u2014 the architecture brief is in. I can read this repo now and write accurate docs.";d({kind:"note",tone:"ok",text:`${P}${f?.lead?` ${eo(f.lead)}`:""}`}),os(null),f&&(f.lead||f.picker)?wo(f,{silent:!0}):en.current||xe("write the docs for this repo"),H(Y=>Y+1);return}if(en.current)return;$o.current+=1;let l=$o.current;if((l===4||l%15===0)&&En.current<3){En.current+=1;let i=En.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";d({kind:"note",tone:"info",text:rt(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${i}`:`\u23F3 Waiting for your builder to run the prompt \u2014 paste it into your coding agent; I'll pick up automatically when it's done.${i}`})}}catch{}},4e3);return()=>clearInterval(c)},[e,D,d,jt,wo,xe]),Ie(()=>{let c=qa??ro(e);if(!D){Lr(0),wn(`${Ur} ${c}`);return}Lr(3);let l=0;wn(`${Mr[0]} ${c}`);let i=setInterval(()=>{l=(l+1)%Mr.length,wn(`${Mr[l]} ${c}`)},400);return()=>clearInterval(i)},[D,e,qa]),Ie(()=>()=>Lr(0),[]),Ie(()=>{let c=performance.now(),l=[],i=(y,w)=>{let g=performance.now();try{return w()}finally{let C=Math.round(performance.now()-g);C>=80&&l.push(`${y}: ${C}ms`)}};d({kind:"banner",info:i("banner",()=>Sk(e,o,t,s))});let f=Na(t).state==="missing";if(f&&d({kind:"note",tone:"warn",text:`\u26A0 Set up Claude first \u2014 d360-writer's agent runs on Claude Code, and it's not signed in on this machine yet.
390
+ 3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function Sk(e,t,n,o){let r=Na(n),s=r.state==="ready"?r.kind==="api"?"API key":"subscription":r.state==="maybe"?"subscription":"not signed in \u2014 run /doctor (needs Claude Code, not Claude Desktop)",a=Ia(e),u=ae(e),p=(u?.docsDir??Oa).replace(/\/+$/,""),b=u?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${p}/ + config`,k={version:t,engineVersion:kp,captureVersion:yr(),claude:s,model:a.model,modelSource:Rk[a.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:u!==null,mode:b};if(u===null)return k;try{let $=Ne(e,o);k.profile=$.name,k.apiUrl=$.connection.apiUrl,k.prod=$.production,k.project=$.project.projectName??$.project.projectId??"(chosen at login)";let x=Ut($.name);if(x){let j={...$n(x.idToken)??{},...$n(x.accessToken)??{}},v=j.email??j.preferred_username??"signed in";$t(x)?x.refreshToken&&(k.who=v,k.loggedOut=!1,k.sessionHint="session expired \u2014 refreshing\u2026"):(k.who=v,k.loggedOut=!1,k.sessionHint=`session valid until ${new Date(x.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return k}function Pk(e,t){try{let n=Ne(e,t),o=Ut(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...$n(o.idToken)??{},...$n(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return $t(o)&&!o.refreshToken?{text:`profile "${n.name}" \u2014 session expired (/login)`,prod:n.production}:{text:`${s} \xB7 profile "${n.name}"`,prod:n.production}}catch(n){return{text:n.message.split(".")[0],prod:!1}}}var yp=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],xn=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Tk="Ask me to write or update an article\u2026";function bn({ch:e,dim:t}){let[n,o]=K(!0);return Ie(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),I(N,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var Dk=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function wp(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var Ak=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ek({startTime:e,chars:t}){let[n,o]=K(0);Ie(()=>{let p=setInterval(()=>o(b=>b+1),120);return()=>clearInterval(p)},[]);let r=xn[n%xn.length],s=yp[Math.floor(n/16)%yp.length],a=Math.floor((Date.now()-e)/1e3),u=Math.round(t/4);return J(le,{children:[I(N,{color:X,children:` ${r} ${s}\u2026 `}),I(N,{color:"gray",children:`(${Bn(a)} \xB7 ~${u} tokens \xB7 esc to interrupt)`})]})}function jk({text:e}){let[t,n]=K(0);return Ie(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),I(le,{paddingX:1,children:I(N,{color:X,children:`${xn[t%xn.length]} ${e}`})})}var Nk=12e4;function Ik({p:e}){let[t,n]=K(0);Ie(()=>{let E=setInterval(()=>n(U=>U+1),150);return()=>clearInterval(E)},[]);let o=xn[t%xn.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),a=Math.round(e.chars/4),u=Date.now()-e.lastAt>=Nk,p=e.verb??"Converting",b=e.unit??"article",k=e.rows.reduce((E,U)=>E+U.items,0),$=p.toLowerCase(),x=e.rows,j=0;if(x.length>Fr){let E=x.findIndex(L=>L.status==="active"||L.status==="pending"),U=Math.max(0,Math.min(E-2,x.length-Fr));j=x.slice(0,U).filter(L=>L.status==="done").length,x=x.slice(U,U+Fr)}let v=Math.min(40,Math.max(...x.map(E=>Ca(E.label).length),0)),D=E=>E==="failed"?"red":E==="active"?X:void 0;return J(le,{flexDirection:"column",children:[J(le,{children:[I(N,{color:X,children:` ${o} ${p} ${k} ${b}${k===1?"":"s"} `}),I(N,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${a} tokens \xB7 ${Bn(r)} \xB7 esc to stop`})]}),j>0&&I(N,{dimColor:!0,children:` \u2714 +${j} done`}),x.map(E=>J(N,{color:D(E.status),dimColor:E.status==="done"||E.status==="pending",children:[` ${Bd[E.status]} ${Ca(E.label).padEnd(v)}`,E.status==="active"&&E.itemsDone!==void 0?` (${E.itemsDone}/${E.items} ${b}${E.items===1?"":"s"})`:E.status!=="pending"?` (${E.items} ${b}${E.items===1?"":"s"})`:"",E.status==="active"?` \u2190 ${$}\u2026`:""]},E.label)),u&&I(N,{color:"yellow",children:` \u26A0 no activity for ${Bn(s)} \u2014 press esc to stop if it's wedged`})]})}var Ok=10800*1e3;function bp({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=_w(),[s,a]=K(n),[u,p]=K(null),[b,k]=K({text:"",pos:0}),$=b.text,x=Q(c=>{k(l=>{let i=typeof c=="function"?c(l.text):c;return{text:i,pos:i.length}})},[]),j=Q(c=>{k(l=>({text:l.text.slice(0,l.pos)+c+l.text.slice(l.pos),pos:l.pos+c.length}))},[]),v=Q(()=>{k(c=>{if(c.pos===0)return c;let l=c.text.slice(0,c.pos),i=Kd(l)??l.slice(0,-1);return{text:i+c.text.slice(c.pos),pos:i.length}})},[]),[D,E]=K(!1),[U,L]=K(!1),[G,H]=K(0),[se,Be]=K(!1),[fe,Xe]=K(null),[me,Qe]=K(null),[be,qe]=K([]),io=te(!1),vn=te(!1),zr=te(!1),[Kr,Ua]=K(!1),ao=te(0),[Pp,lo]=K(!1),[Tp,co]=K(!1),[Xr,Wa]=K(null),[Dp,Wt]=K(0),xt=te(0),[Qr,Ft]=K(0),[Bt,uo]=K(null),Fa=te(new Map),Ap=te(0),qt=te([]),Oe=te(null);Oe.current===null&&(Oe.current=tp({cwd:e,profileName:s,allowProdWrites:!1}));let Je=te({uuid:null,firstPrompt:null,titleFired:!1}),po=te(new Map),Ba=te(null),Ht=te(!1),Jr=te([]),pe=te([]),Vt=te([]),ho=te(null),[qa,vt]=K(null),Zr=te(null),[Ct,Rt]=K(null),[Ze,Gt]=K(null),[et,Yt]=K(null),[$e,zt]=K(null),[Te,St]=K(null),[at,Kt]=K(null),[lt,Pt]=K(null),[tt,Tt]=K(null),[Ha,Cn]=K(null),[De,Dt]=K(null),[Ce,Xt]=K(null),[Va,es]=K([]),At=te([]),Rn=te(!1),we=te(null),[fo,ie]=K(null),[Ga,mo]=K(null),go=te(!1),Sn=te(null),Pn=te(null),[Ae,Et]=K(null),[yo,Tn]=K(null),ts=!!(et||$e||Te||at||lt||tt||De||Ce||Ae||yo),[Ya,Qt]=K(0),[za,Jt]=K(0),[Ep,Ka]=K(0),ns=Sa(()=>{try{let c=Ia(e);return c.source==="auto"?`${c.model} (auto)`:c.model}catch{return null}},[e,Ep]),{stdout:_e}=Mw(),[,jp]=K(0),Xa=te(`${_e.columns??80}x${_e.rows??24}`),ct=Q(()=>Math.max(20,(_e.columns??80)-1),[_e]),d=Q(c=>{qt.current.push(c),console.log(Is(c,ct()))},[ct]),xe=Q((c,l)=>{ao.current++,Xe(c),Qe(l??null)},[]),He=Q(()=>{ao.current++,Xe(null),Qe(null)},[]),Z=Q(c=>xe(c,Dr({kind:"cmd",cmd:c,reason:""})),[xe]),wo=Q((c,l)=>{!l?.silent&&c.note&&d({kind:"note",tone:c.tone,text:c.note}),c.picker&&(qe(c.picker.options.map(i=>({cmd:i.cmd,desc:i.desc}))),Cn(c.picker.title)),c.lead&&xe(c.lead.kind==="cmd"?c.lead.cmd:c.lead.text,Dr(c.lead))},[d,xe]),ve=Q((c,l,i="info")=>{c&&d({kind:"note",tone:i,text:c}),l&&xe(l.kind==="cmd"?l.cmd:l.text,Dr(l))},[d,xe]),[Dn,os]=K(null),[Np,Qa]=K(!1),Zt=Q(c=>{os(c),Qa(!1),d({kind:"note",tone:"info",text:"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[d]),rs=te(!1),ss=Q(async()=>{try{if(rs.current||!yk(gk())||ae(e)?.mode==="engineer")return;let c=await mk({pkg:yn,currentVersion:o,force:!0});if(!c.updateAvailable||!c.latest)return;rs.current=!0,d({kind:"note",tone:"info",text:`\u2B06 Updating ${yn} ${c.current} \u2192 ${c.latest}\u2026 (wait for the \u2713 before you /exit)`}),co(!0),(await vr().finally(()=>co(!1))).ok?(d({kind:"note",tone:"ok",text:`\u2713 Updated to v${c.latest} \u2014 run /exit, then relaunch to apply.`}),Z("/exit"),Wa(c.latest)):d({kind:"note",tone:"warn",text:`Update available (v${c.latest}) but auto-update failed \u2014 run: ${xr}`})}catch{}},[e,o,d,Z]),ko=Q(c=>{let l=Ue(e,s);return l.ok?!0:(d({kind:"note",tone:"warn",text:l.reason}),Pn.current=c,Z("/login"),!1)},[e,s,d,Z]),[bo,is]=K(null),jt=Q(c=>{let l=no(e,s,{claudeMissing:Na(t).state==="missing",allowAutoAudit:c,genreUnknown:zr.current});return l?to(l):{kind:"idle"}},[e,s,t]),An=te(!0),en=te(!1),$o=te(0),En=te(0);Ie(()=>{let c=setInterval(()=>{if(An.current){$o.current=0,En.current=0;return}if(!D)try{if(!kn(cp(e)))return;if(Me(e).status==="current"){An.current=!0,$o.current=0,En.current=0;let i=jt(!1),f=i.kind==="recommend"?i.rec:null,P=en.current?`\u2713 Your builder finished the protocol update (v${de}) \u2014 the dev\u2194docs hand-off is current again.`:"\u2713 Your builder finished the hand-off \u2014 the architecture brief is in. I can read this repo now and write accurate docs.";d({kind:"note",tone:"ok",text:`${P}${f?.lead?` ${eo(f.lead)}`:""}`}),os(null),f&&(f.lead||f.picker)?wo(f,{silent:!0}):en.current||xe("write the docs for this repo"),H(Y=>Y+1);return}if(en.current)return;$o.current+=1;let l=$o.current;if((l===4||l%15===0)&&En.current<3){En.current+=1;let i=En.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";d({kind:"note",tone:"info",text:rt(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${i}`:`\u23F3 Waiting for your builder to run the prompt \u2014 paste it into your coding agent; I'll pick up automatically when it's done.${i}`})}}catch{}},4e3);return()=>clearInterval(c)},[e,D,d,jt,wo,xe]),Ie(()=>{let c=qa??ro(e);if(!D){Lr(0),wn(`${Ur} ${c}`);return}Lr(3);let l=0;wn(`${Mr[0]} ${c}`);let i=setInterval(()=>{l=(l+1)%Mr.length,wn(`${Mr[l]} ${c}`)},400);return()=>clearInterval(i)},[D,e,qa]),Ie(()=>()=>Lr(0),[]),Ie(()=>{let c=performance.now(),l=[],i=(y,w)=>{let g=performance.now();try{return w()}finally{let R=Math.round(performance.now()-g);R>=80&&l.push(`${y}: ${R}ms`)}};d({kind:"banner",info:i("banner",()=>Sk(e,o,t,s))});let f=Na(t).state==="missing";if(f&&d({kind:"note",tone:"warn",text:`\u26A0 Set up Claude first \u2014 d360-writer's agent runs on Claude Code, and it's not signed in on this machine yet.
391
391
  ${Fw}
392
392
  Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!ae(e)){d({kind:"note",tone:"info",text:`Welcome! This repo isn't set up for d360-writer yet \u2014 three steps and you're writing docs:
393
393
  ${gp}`}),Z(f?"/doctor":"/init");return}f&&Z("/doctor");try{let y=Ne(e,s),w=Ut(y.name);w&&$t(w)&&w.refreshToken?Vw({profile:y.name,connection:y.connection}).then(()=>{d({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),H(g=>g+1)}).catch(()=>{d({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 sign in again with /login."}),Z("/login")}):(!w||$t(w))&&(d({kind:"note",tone:"warn",text:`Profile "${y.name}" is not signed in \u2014 sign in with /login.`}),Z("/login"))}catch{}try{let y=ae(e),w=Ne(e,s),g=Ut(w.name);y&&g&&!$t(g)&&ma(e,y.authoritativeSourceFiles)&&!ga(e,s)&&(d({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),Z("/scope"))}catch{}try{let y=i("resolve-genre",()=>ok(e));y.persisted&&y.appType?d({kind:"note",tone:"ok",text:`\u2713 Detected a ${y.appType} app \u2014 enabled the ${y.appType}-doc-playbook (change with /genre, or edit .d360-writer/config.json).`}):y.source==="unknown"&&ae(e)&&(zr.current=!0)}catch{}let P=Me(e);try{if(i("reconcile-devhints",()=>qo(e)),P.status!=="current"&&!rt(e)){let y=Ho(e);y.length&&(d({kind:"note",tone:"warn",text:y.join(`
394
394
  `)}),Zt(Ot()),An.current=!1,en.current=!1)}}catch{}try{let y=i("reconcile-feedback",()=>wk(e));y.archived>0&&d({kind:"note",tone:"ok",text:`\u2713 Tidied ${y.archived} resolved item${y.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${y.open>0?`; ${y.open} still open`:""}.`})}catch{}try{let y=i("upgrade-actions",()=>kk(e));y.applied.length>0&&d({kind:"note",tone:"warn",text:Ko(y.applied).join(`
395
395
  `)})}catch{}let Y=i("ready-decision",()=>jt(!0));Y.kind==="autoAudit"?(d({kind:"note",tone:"info",text:Y.note}),Yn().then(y=>{y.kind==="forward-to-agent"&&y.prompt&&re(y.prompt,{display:y.display,quietUser:!0})})):Y.kind==="recommend"&&wo(Y.rec);let h=Math.round(performance.now()-c);h>=800&&$k({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${h}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${l.length?l.join(`
396
396
  `):"no single phase \u226580ms"}
397
- cwd: ${e}`}),ss()},[]),Ie(()=>{let c=setInterval(()=>{ss()},Ok);return()=>clearInterval(c)},[ss]),Ie(()=>{if(D||se||Kr||io.current||vn.current||fe!==null||be.length>0||$!==""||Dn!==null||pe.current.length>0||ho.current||ts)return;let c=jt(!1);c.kind==="recommend"&&(c.rec.lead||c.rec.picker)&&wo(c.rec,{silent:!0})},[D,se,fe,be,$,Dn,ts,G,jt,Kr]),Ie(()=>{let c=null,l=null,i=()=>{c&&clearTimeout(c),c=setTimeout(()=>{c=null;let f=`${_e.columns??80}x${_e.rows??24}`;f!==Xa.current&&(Xa.current=f,jp(P=>P+1),l&&clearTimeout(l),l=setTimeout(()=>{l=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+lc(qt.current,ct())+"\x1B[?2026l")},80))},400)};return _e.on("resize",i),()=>{c&&clearTimeout(c),l&&clearTimeout(l),_e.off("resize",i)}},[_e,ct]);let Ge=Math.max(20,(_e.columns??80)-1),Ja=Sa(()=>Pk(e,s),[e,s,G]),as=(()=>{if(Tp)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(Xr!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${Xr?` v${Xr}`:""}\u2026`,isSetup:!0};if(bo)return{text:"\u{1F6E0} press c to copy the d360-writer feedback \u2014 then send it to the team (Teams / Slack / email)\u2026",isSetup:!0};if(Dn)return Np?{text:"\u2713 copied \u2014 paste it into your coding agent \xB7 I\u2019ll pick up automatically when it finishes\u2026",isSetup:!0}:{text:"\u2328 press c to copy the prompt above \u2014 then paste it into your coding agent\u2026",isSetup:!0};if(pe.current.length>0)return pe.current[0].mode==="conflict"?{text:"l keep local \xB7 p take portal \xB7 s skip \xB7 anything else cancels\u2026",isSetup:!0}:{text:"y to write \xB7 n to skip \xB7 anything else cancels\u2026",isSetup:!0};let c=ae(e);if(!c)return{text:"Run /init to set up this repo (or /help)\u2026",isSetup:!0};let l=Pa(e,(c.docsDir??Oa).replace(/\/+$/,"")),i=(()=>{try{return kn(l)&&Uw(l).length>0}catch{return!1}})();try{let f=Ne(e,s),P=Ut(f.name);if(!(!!P&&!($t(P)&&!P.refreshToken)))return{text:`Sign in with /login (profile "${f.name}")\u2026`,isSetup:!0};if(!f.project.projectId)return{text:"Sign in to Document360 to pick your project\u2026",isSetup:!0};if(!f.project.workspaceId&&!i)return{text:"Pick a workspace with /workspace\u2026",isSetup:!0}}catch{}return i?{text:Tk,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),Ye=Zl($),Za=Ye.length>0&&!D,xo=Math.max(3,Math.min(12,(_e.rows??24)-8)),vo=Math.min(Qr,Math.max(0,Ye.length-1)),Nt=Ye.length<=xo?0:Math.min(Math.max(0,vo-Math.floor(xo/2)),Ye.length-xo),ls=Ye.slice(Nt,Nt+xo),cs=u!==null?Jd(u,8,Ge):null,Co=De?De.paths.filter(c=>!De.query||c.toLowerCase().includes(De.query.toLowerCase())).slice(0,8):[],Ro=Ae?Ae.sessions.filter(c=>{let l=Ae.query.toLowerCase();return!l||c.name.toLowerCase().includes(l)||c.firstPrompt.toLowerCase().includes(l)}).slice(0,8):[],Ee=Q((c,l)=>{Oe.current?.close(),Oe.current=tp({cwd:e,resume:c,profileName:l??s,allowProdWrites:Ht.current}),c||(Je.current={uuid:null,firstPrompt:null,titleFired:!1},vt(null)),Qt(0),Jt(0)},[e,s]),el=Q((c,l,i)=>{if(Dk.test(c))try{let f=Ne(e,s),P=typeof l.project_id=="string"&&l.project_id||f.project.projectId,Y=Ir(l,i),h=[],y=Or(i);c.endsWith("publish_article")&&y&&h.push(`Live: ${y}`);let w=_r(i);w?h.push(`Preview: ${w}`):Y&&P&&h.push(`Preview: ${Nr(f.connection.portalUrl,P,Y,f.project.languageCode??"en")}`),h.length>0&&d({kind:"link",lines:h})}catch{}},[e,s,d]),re=Q(async(c,l)=>{lo(!0),io.current=!1,vn.current=!1,Ve(),He([]),Cn(null),os(null);let i=ao.current;if(l?.display?.startsWith("/"))try{let R=hd(e,l.display);R&&(c=`${c}
397
+ cwd: ${e}`}),ss()},[]),Ie(()=>{let c=setInterval(()=>{ss()},Ok);return()=>clearInterval(c)},[ss]),Ie(()=>{if(D||se||Kr||io.current||vn.current||fe!==null||be.length>0||$!==""||Dn!==null||pe.current.length>0||ho.current||ts)return;let c=jt(!1);c.kind==="recommend"&&(c.rec.lead||c.rec.picker)&&wo(c.rec,{silent:!0})},[D,se,fe,be,$,Dn,ts,G,jt,Kr]),Ie(()=>{let c=null,l=null,i=()=>{c&&clearTimeout(c),c=setTimeout(()=>{c=null;let f=`${_e.columns??80}x${_e.rows??24}`;f!==Xa.current&&(Xa.current=f,jp(P=>P+1),l&&clearTimeout(l),l=setTimeout(()=>{l=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+lc(qt.current,ct())+"\x1B[?2026l")},80))},400)};return _e.on("resize",i),()=>{c&&clearTimeout(c),l&&clearTimeout(l),_e.off("resize",i)}},[_e,ct]);let Ve=Math.max(20,(_e.columns??80)-1),Ja=Sa(()=>Pk(e,s),[e,s,G]),as=(()=>{if(Tp)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(Xr!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${Xr?` v${Xr}`:""}\u2026`,isSetup:!0};if(bo)return{text:"\u{1F6E0} press c to copy the d360-writer feedback \u2014 then send it to the team (Teams / Slack / email)\u2026",isSetup:!0};if(Dn)return Np?{text:"\u2713 copied \u2014 paste it into your coding agent \xB7 I\u2019ll pick up automatically when it finishes\u2026",isSetup:!0}:{text:"\u2328 press c to copy the prompt above \u2014 then paste it into your coding agent\u2026",isSetup:!0};if(pe.current.length>0)return pe.current[0].mode==="conflict"?{text:"l keep local \xB7 p take portal \xB7 s skip \xB7 anything else cancels\u2026",isSetup:!0}:{text:"y to write \xB7 n to skip \xB7 anything else cancels\u2026",isSetup:!0};let c=ae(e);if(!c)return{text:"Run /init to set up this repo (or /help)\u2026",isSetup:!0};let l=Pa(e,(c.docsDir??Oa).replace(/\/+$/,"")),i=(()=>{try{return kn(l)&&Uw(l).length>0}catch{return!1}})();try{let f=Ne(e,s),P=Ut(f.name);if(!(!!P&&!($t(P)&&!P.refreshToken)))return{text:`Sign in with /login (profile "${f.name}")\u2026`,isSetup:!0};if(!f.project.projectId)return{text:"Sign in to Document360 to pick your project\u2026",isSetup:!0};if(!f.project.workspaceId&&!i)return{text:"Pick a workspace with /workspace\u2026",isSetup:!0}}catch{}return i?{text:Tk,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),Ge=Zl($),Za=Ge.length>0&&!D,xo=Math.max(3,Math.min(12,(_e.rows??24)-8)),vo=Math.min(Qr,Math.max(0,Ge.length-1)),Nt=Ge.length<=xo?0:Math.min(Math.max(0,vo-Math.floor(xo/2)),Ge.length-xo),ls=Ge.slice(Nt,Nt+xo),cs=u!==null?Jd(u,8,Ve):null,Co=De?De.paths.filter(c=>!De.query||c.toLowerCase().includes(De.query.toLowerCase())).slice(0,8):[],Ro=Ae?Ae.sessions.filter(c=>{let l=Ae.query.toLowerCase();return!l||c.name.toLowerCase().includes(l)||c.firstPrompt.toLowerCase().includes(l)}).slice(0,8):[],Ee=Q((c,l)=>{Oe.current?.close(),Oe.current=tp({cwd:e,resume:c,profileName:l??s,allowProdWrites:Ht.current}),c||(Je.current={uuid:null,firstPrompt:null,titleFired:!1},vt(null)),Qt(0),Jt(0)},[e,s]),el=Q((c,l,i)=>{if(Dk.test(c))try{let f=Ne(e,s),P=typeof l.project_id=="string"&&l.project_id||f.project.projectId,Y=Ir(l,i),h=[],y=Or(i);c.endsWith("publish_article")&&y&&h.push(`Live: ${y}`);let w=_r(i);w?h.push(`Preview: ${w}`):Y&&P&&h.push(`Preview: ${Nr(f.connection.portalUrl,P,Y,f.project.languageCode??"en")}`),h.length>0&&d({kind:"link",lines:h})}catch{}},[e,s,d]),re=Q(async(c,l)=>{lo(!0),io.current=!1,vn.current=!1,He(),qe([]),Cn(null),os(null);let i=ao.current;if(l?.display?.startsWith("/"))try{let C=hd(e,l.display);C&&(c=`${c}
398
398
 
399
- ${R}`)}catch{}l?.quietUser||d({kind:"user",text:l?.echoDisplay&&l.display?l.display:c});let f=Je.current;f.firstPrompt||(f.firstPrompt=l?.display??c),xt.current=Date.now(),Wt(0),E(!0),po.current.clear();let P="",Y=!1,h=!1,y="",w={num:0,closed:!1,cueSeen:!1},g=null,C=()=>{g||(g=setTimeout(()=>{g=null,p(y.length>0?y:null)},60))},A=()=>{g&&clearTimeout(g),g=null,p(null)},F=(R=!1)=>{let{head:q,keep:M}=Zd(y,R);q.trim()&&d({kind:"assistant",text:xa(q.trimEnd(),w)}),y=M,A()};try{for await(let R of Oe.current.send(c))if(R.type==="session"){if(!f.uuid){f.uuid=R.sessionId;let q=new Date().toISOString(),M=Zr.current,T=M??Qw(f.firstPrompt??"session");Jw({uuid:R.sessionId,name:T,renamed:!!M,titled:!1,cwd:e,firstPrompt:f.firstPrompt??"",createdAt:q,updatedAt:q}),vt(T),Zr.current=null}}else if(R.type==="text"){y+=R.delta,P+=R.delta;let q=ep(y);if(q>0){let M=y.slice(0,q).trimEnd();M&&d({kind:"assistant",text:xa(M,w)}),y=y.slice(q)}C(),Wt(M=>M+R.delta.length)}else if(R.type==="tool"){Y=!0;let M=(oe=>typeof oe=="string"&&oe?oe.replace(/\\/g,"/").toLowerCase():null)(R.input.file_path??R.input.notebook_path),T=["Edit","Write","MultiEdit","NotebookEdit"].includes(R.name),V=R.name==="Read"&&M!==null&&M===Ba.current;if(Ba.current=T?M:null,V)F(),d({kind:"tool",title:"Read",sep:"",arg:"(re-checking the file it just edited)"});else{let oe=Er(R.name,R.input,e);oe&&(F(),d({kind:"tool",title:oe.title,sep:oe.sep,arg:oe.arg}),po.current.set(R.id,{name:R.name,input:R.input}))}}else if(R.type==="article_diff"){let q=it(R.oldContent,R.newContent,ct());q&&(F(),d({kind:"diff",added:q.added,removed:q.removed,lines:q.lines,hidden:q.hidden}))}else if(R.type==="tool_result"){R.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(R.output)&&(go.current=!0);let q=po.current.get(R.id);if(q){po.current.delete(R.id),F();let M=jr(R.output,4,R.isError?void 0:q.name,q.input);d({kind:"tool-result",lines:M.lines,hidden:M.hidden,isError:R.isError}),R.isError||el(q.name,q.input,R.output)}}else if(R.type==="result"){F(!0),Qt(M=>M+R.outputTokens),Jt(M=>M+R.costUsd);let q=R.inputTokens+R.cacheReadTokens+R.cacheCreationTokens;if(d({kind:"done",seconds:Math.round((Date.now()-xt.current)/1e3),tokens:R.outputTokens,costUsd:R.costUsd,ok:R.ok,...q>0?{inTokens:q,cachedPct:Math.round(R.cacheReadTokens/q*100)}:{}}),!h&&!Y&&!P.trim()&&!Rn.current&&d({kind:"note",tone:"warn",text:"The agent produced no output. This usually means the Claude model/runtime did not start \u2014 check sign-in and model with /doctor (on a subscription, make sure Claude Code is logged in on this machine)."}),R.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(P))try{let M=up(e);if(kn(M)){let T=Hr(M,"utf8").trim();T&&(is(T),d({kind:"note",tone:"info",text:"\u{1F6E0} Press c to copy this feedback \u2014 send it to the d360-writer team (Teams / Slack / email)."}))}}catch{}if(vn.current=R.ok&&/\?[\s*_"')\]]*$/.test(P.trimEnd()),R.ok&&w.cueSeen)Ua(!0),He([]);else{let M=R.ok?Ud(P,dn.map(T=>T.name)):[];if(M.length>0)Z(M[0]);else if(R.ok&&P.trim()&&!vn.current){let T=jt(!1);T.kind==="recommend"&&(T.rec.lead||T.rec.picker)||nk(c,P,e).then(V=>{V&&ao.current===i&&xe(V)}).catch(()=>{})}}if(f.uuid&&(Ta(f.uuid),!f.titleFired)){f.titleFired=!0;let M=f.uuid,T=f.firstPrompt;T&&np(T,e).then(V=>{V&&(Xw(M,V),vt(V))}).catch(()=>{})}}else R.type==="error"&&(F(!0),h=!0,R.kind==="auth"&&(go.current=!0),d({kind:"note",text:`agent error: ${R.message}`,tone:"error"}))}finally{E(!1),A(),H(R=>R+1),Je.current.uuid&&Od(e,Je.current.uuid,qt.current),go.current?(go.current=!1,Sn.current=l?.display??c,xe("/login","\u21E5 tab to run /login \u2014 then I\u2019ll re-send your last prompt\u2026")):Sn.current=null,Rn.current&&(Rn.current=!1,At.current.length>0&&(d({kind:"note",tone:"info",text:`(${At.current.length} queued message(s) discarded)`}),At.current=[],es([])),d({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,d,el,ct,xe,Z,Ve,jt]),It=Q(async c=>{let l=Gr(e,"standard");xt.current=Date.now(),Wt(0),E(!0);let i=new AbortController;we.current=i;let f=async(P,Y)=>{let h=Aa(P);ie({verb:"Publishing",total:h.length,done:0,active:[],rows:oo(h),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:Y?`Resolving cross-links in ${P.length} article${P.length===1?"":"s"} whose targets published this run (second pass)\u2026 (esc to stop)`:`Publishing ${P.length} article${P.length===1?"":"s"} across ${h.length} partition${h.length===1?"":"s"} (\u2264${Vn} agents at once) on ${l.model}\u2026 (esc to stop)`});let y=!1;for await(let w of Vr({cwd:e,partitions:h,promptFor:g=>Gn(g.paths),concurrency:Vn,profileName:s,allowProdWrites:Ht.current,model:l.model,signal:i.signal}))if(w.type==="partition_status")w.status==="running"?ie(g=>g&&{...g,active:[...g.active,w.label],rows:Fe(g.rows,w.label,"active"),lastAt:Date.now()}):ie(g=>g&&{...g,active:g.active.filter(C=>C!==w.label),done:g.done+1,rows:Fe(g.rows,w.label,w.status==="done"?"done":"failed"),lastAt:Date.now()});else if(w.type==="partition_event")ie(g=>{if(!g)return g;let C={...g,lastAt:Date.now()};return w.event.type==="tool"?C.tools=g.tools+1:w.event.type==="text"&&(C.chars=g.chars+w.event.delta.length),C});else if(w.type==="run_done"){y=w.aborted,Jt(F=>F+w.totalCostUsd),Qt(F=>F+w.results.reduce((R,q)=>R+q.outputTokens,0));let g=w.aborted?"Stopped. ":"",C=t.kind==="api"?"api":"subscription";d({kind:"note",tone:w.aborted?"warn":w.ok?"ok":"warn",text:g+Xs(w.results,h,C).join(`
400
- `)});let A=Ks(e,s);if(A&&d({kind:"note",tone:"info",text:A}),!w.aborted){try{let F=await pp({cwd:e,profileName:s}),R=hp(F);R?d({kind:"note",tone:"info",text:R}):F.skipped&&d({kind:"note",tone:"warn",text:`Order sync skipped: ${F.skipped}`})}catch(F){d({kind:"note",tone:"warn",text:`Order sync failed: ${F.message}`})}try{let F=mp(await fp({cwd:e,profileName:s}));F&&d({kind:"note",tone:"info",text:F})}catch(F){d({kind:"note",tone:"warn",text:`Related-articles sync failed: ${F.message}`})}}}return y};try{if(!await f(c,!1)){let Y=await Qs(e,s,c);Y.length>0&&await f(Y,!0)}}catch(P){d({kind:"note",tone:"error",text:`Publish run failed: ${P.message}`})}finally{we.current=null,ie(null),E(!1),H(P=>P+1)}},[e,s,d,t]),us=Q(async c=>{await re(Ys(c),{display:`/publish ${c}`,quietUser:!0});try{let l=await ur(e,s,c.replace(/\\/g,"/"));l.length>0&&(Cn(`Related articles not yet published (${l.length}):`),He([`/publish --related ${c}`,...l.map(i=>`/publish ${i}`)]))}catch{}},[e,s,re]),So=Q(c=>{if(c)try{for(let l of Array.isArray(c)?c:[c]){let i=ua(e,l);if(!i)continue;Tr(e,i.title).ok&&d({kind:"note",tone:"ok",text:`\u2713 That completed a docs-campaign step \u2014 marked done: ${i.title}`});return}}catch{}},[e,d]),tl=Q(async(c,l)=>{let f=dk(c,3),P=Gr(e,"standard"),Y=new Map;for(let w of c){let g=Ls(e,w,nr(e,w));g&&Y.set(w,g)}xt.current=Date.now(),Wt(0),E(!0);let h=new AbortController;we.current=h,ie({verb:"Authoring",unit:"spec",total:f.length,done:0,active:[],rows:oo(f),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Authoring ${c.length} screenshot spec${c.length===1?"":"s"} across ${f.length} partition${f.length===1?"":"s"} (\u22646 agents at once) on ${P.model}${P.forced?" (forced)":""}\u2026 (esc to stop)`});let y=!1;try{for await(let w of Vr({cwd:e,partitions:f,promptFor:g=>jc(g,Y),concurrency:6,profileName:s,allowProdWrites:Ht.current,model:P.model,signal:h.signal}))if(w.type==="partition_status")w.status==="running"?ie(g=>g&&{...g,active:[...g.active,w.label],rows:Fe(g.rows,w.label,"active"),lastAt:Date.now()}):ie(g=>g&&{...g,active:g.active.filter(C=>C!==w.label),done:g.done+1,rows:Fe(g.rows,w.label,w.status==="done"?"done":"failed"),lastAt:Date.now()});else if(w.type==="partition_event")ie(g=>{if(!g)return g;let C={...g,lastAt:Date.now()};return w.event.type==="tool"?C.tools=g.tools+1:w.event.type==="text"&&(C.chars=g.chars+w.event.delta.length),C});else if(w.type==="run_done"){Jt(F=>F+w.totalCostUsd),Qt(F=>F+w.results.reduce((R,q)=>R+q.outputTokens,0));let g=w.results.filter(F=>F.ok).length,C=w.aborted?"Stopped. ":"";y=!w.aborted&&l.setup;let A=w.aborted?"":y?" Refreshing the capture-setup checklist\u2026":" Next: /screenshot capture --all (or /screenshot checklist first for the staging checklist).";d({kind:"note",tone:w.aborted?"warn":w.ok?"ok":"warn",text:`${C}Authored specs \u2014 ${g}/${w.results.length} batches ok.${A}`}),!w.aborted&&w.ok&&So(l.runLine)}}catch(w){d({kind:"note",tone:"error",text:`Spec authoring failed: ${w.message}`})}finally{we.current=null,ie(null),E(!1),H(w=>w+1)}if(y){let w=await gn();w.kind==="forward-to-agent"&&w.prompt&&await re(w.prompt,{display:w.display,quietUser:!0});let g=Gi(e);g&&d({kind:"note",tone:"info",text:g.join(`
399
+ ${C}`)}catch{}l?.quietUser||d({kind:"user",text:l?.echoDisplay&&l.display?l.display:c});let f=Je.current;f.firstPrompt||(f.firstPrompt=l?.display??c),xt.current=Date.now(),Wt(0),E(!0),po.current.clear();let P="",Y=!1,h=!1,y="",w={num:0,closed:!1,cueSeen:!1},g=null,R=()=>{g||(g=setTimeout(()=>{g=null,p(y.length>0?y:null)},60))},A=()=>{g&&clearTimeout(g),g=null,p(null)},F=(C=!1)=>{let{head:q,keep:M}=Zd(y,C);q.trim()&&d({kind:"assistant",text:xa(q.trimEnd(),w)}),y=M,A()};try{for await(let C of Oe.current.send(c))if(C.type==="session"){if(!f.uuid){f.uuid=C.sessionId;let q=new Date().toISOString(),M=Zr.current,T=M??Qw(f.firstPrompt??"session");Jw({uuid:C.sessionId,name:T,renamed:!!M,titled:!1,cwd:e,firstPrompt:f.firstPrompt??"",createdAt:q,updatedAt:q}),vt(T),Zr.current=null}}else if(C.type==="text"){y+=C.delta,P+=C.delta;let q=ep(y);if(q>0){let M=y.slice(0,q).trimEnd();M&&d({kind:"assistant",text:xa(M,w)}),y=y.slice(q)}R(),Wt(M=>M+C.delta.length)}else if(C.type==="tool"){Y=!0;let M=(oe=>typeof oe=="string"&&oe?oe.replace(/\\/g,"/").toLowerCase():null)(C.input.file_path??C.input.notebook_path),T=["Edit","Write","MultiEdit","NotebookEdit"].includes(C.name),V=C.name==="Read"&&M!==null&&M===Ba.current;if(Ba.current=T?M:null,V)F(),d({kind:"tool",title:"Read",sep:"",arg:"(re-checking the file it just edited)"});else{let oe=Er(C.name,C.input,e);oe&&(F(),d({kind:"tool",title:oe.title,sep:oe.sep,arg:oe.arg}),po.current.set(C.id,{name:C.name,input:C.input}))}}else if(C.type==="article_diff"){let q=it(C.oldContent,C.newContent,ct());q&&(F(),d({kind:"diff",added:q.added,removed:q.removed,lines:q.lines,hidden:q.hidden}))}else if(C.type==="tool_result"){C.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(C.output)&&(go.current=!0);let q=po.current.get(C.id);if(q){po.current.delete(C.id),F();let M=jr(C.output,4,C.isError?void 0:q.name,q.input);d({kind:"tool-result",lines:M.lines,hidden:M.hidden,isError:C.isError}),C.isError||el(q.name,q.input,C.output)}}else if(C.type==="result"){F(!0),Qt(M=>M+C.outputTokens),Jt(M=>M+C.costUsd);let q=C.inputTokens+C.cacheReadTokens+C.cacheCreationTokens;if(d({kind:"done",seconds:Math.round((Date.now()-xt.current)/1e3),tokens:C.outputTokens,costUsd:C.costUsd,ok:C.ok,...q>0?{inTokens:q,cachedPct:Math.round(C.cacheReadTokens/q*100)}:{}}),!h&&!Y&&!P.trim()&&!Rn.current&&d({kind:"note",tone:"warn",text:"The agent produced no output. This usually means the Claude model/runtime did not start \u2014 check sign-in and model with /doctor (on a subscription, make sure Claude Code is logged in on this machine)."}),C.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(P))try{let M=up(e);if(kn(M)){let T=Hr(M,"utf8").trim();T&&(is(T),d({kind:"note",tone:"info",text:"\u{1F6E0} Press c to copy this feedback \u2014 send it to the d360-writer team (Teams / Slack / email)."}))}}catch{}if(vn.current=C.ok&&/\?[\s*_"')\]]*$/.test(P.trimEnd()),C.ok&&w.cueSeen)Ua(!0),qe([]);else{let M=C.ok?Ud(P,dn.map(T=>T.name)):[];if(M.length>0)Z(M[0]);else if(C.ok&&P.trim()&&!vn.current){let T=jt(!1);T.kind==="recommend"&&(T.rec.lead||T.rec.picker)||nk(c,P,e).then(V=>{V&&ao.current===i&&xe(V)}).catch(()=>{})}}if(f.uuid&&(Ta(f.uuid),!f.titleFired)){f.titleFired=!0;let M=f.uuid,T=f.firstPrompt;T&&np(T,e).then(V=>{V&&(Xw(M,V),vt(V))}).catch(()=>{})}}else C.type==="error"&&(F(!0),h=!0,C.kind==="auth"&&(go.current=!0),d({kind:"note",text:`agent error: ${C.message}`,tone:"error"}))}finally{E(!1),A(),H(C=>C+1),Je.current.uuid&&Od(e,Je.current.uuid,qt.current),go.current?(go.current=!1,Sn.current=l?.display??c,xe("/login","\u21E5 tab to run /login \u2014 then I\u2019ll re-send your last prompt\u2026")):Sn.current=null,Rn.current&&(Rn.current=!1,At.current.length>0&&(d({kind:"note",tone:"info",text:`(${At.current.length} queued message(s) discarded)`}),At.current=[],es([])),d({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,d,el,ct,xe,Z,He,jt]),It=Q(async c=>{let l=Gr(e,"standard");xt.current=Date.now(),Wt(0),E(!0);let i=new AbortController;we.current=i;let f=async(P,Y)=>{let h=Aa(P);ie({verb:"Publishing",total:h.length,done:0,active:[],rows:oo(h),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:Y?`Resolving cross-links in ${P.length} article${P.length===1?"":"s"} whose targets published this run (second pass)\u2026 (esc to stop)`:`Publishing ${P.length} article${P.length===1?"":"s"} across ${h.length} partition${h.length===1?"":"s"} (\u2264${Vn} agents at once) on ${l.model}\u2026 (esc to stop)`});let y=!1;for await(let w of Vr({cwd:e,partitions:h,promptFor:g=>Gn(g.paths),concurrency:Vn,profileName:s,allowProdWrites:Ht.current,model:l.model,signal:i.signal}))if(w.type==="partition_status")w.status==="running"?ie(g=>g&&{...g,active:[...g.active,w.label],rows:We(g.rows,w.label,"active"),lastAt:Date.now()}):ie(g=>g&&{...g,active:g.active.filter(R=>R!==w.label),done:g.done+1,rows:We(g.rows,w.label,w.status==="done"?"done":"failed"),lastAt:Date.now()});else if(w.type==="partition_event")ie(g=>{if(!g)return g;let R={...g,lastAt:Date.now()};return w.event.type==="tool"?R.tools=g.tools+1:w.event.type==="text"&&(R.chars=g.chars+w.event.delta.length),R});else if(w.type==="run_done"){y=w.aborted,Jt(F=>F+w.totalCostUsd),Qt(F=>F+w.results.reduce((C,q)=>C+q.outputTokens,0));let g=w.aborted?"Stopped. ":"",R=t.kind==="api"?"api":"subscription";d({kind:"note",tone:w.aborted?"warn":w.ok?"ok":"warn",text:g+Xs(w.results,h,R).join(`
400
+ `)});let A=Ks(e,s);if(A&&d({kind:"note",tone:"info",text:A}),!w.aborted){try{let F=await pp({cwd:e,profileName:s}),C=hp(F);C?d({kind:"note",tone:"info",text:C}):F.skipped&&d({kind:"note",tone:"warn",text:`Order sync skipped: ${F.skipped}`})}catch(F){d({kind:"note",tone:"warn",text:`Order sync failed: ${F.message}`})}try{let F=mp(await fp({cwd:e,profileName:s}));F&&d({kind:"note",tone:"info",text:F})}catch(F){d({kind:"note",tone:"warn",text:`Related-articles sync failed: ${F.message}`})}}}return y};try{if(!await f(c,!1)){let Y=await Qs(e,s,c);Y.length>0&&await f(Y,!0)}}catch(P){d({kind:"note",tone:"error",text:`Publish run failed: ${P.message}`})}finally{we.current=null,ie(null),E(!1),H(P=>P+1)}},[e,s,d,t]),us=Q(async c=>{await re(Ys(c),{display:`/publish ${c}`,quietUser:!0});try{let l=await ur(e,s,c.replace(/\\/g,"/"));l.length>0&&(Cn(`Related articles not yet published (${l.length}):`),qe([`/publish --related ${c}`,...l.map(i=>`/publish ${i}`)]))}catch{}},[e,s,re]),So=Q(c=>{if(c)try{for(let l of Array.isArray(c)?c:[c]){let i=ua(e,l);if(!i)continue;Tr(e,i.title).ok&&d({kind:"note",tone:"ok",text:`\u2713 That completed a docs-campaign step \u2014 marked done: ${i.title}`});return}}catch{}},[e,d]),tl=Q(async(c,l)=>{let f=dk(c,3),P=Gr(e,"standard"),Y=new Map;for(let w of c){let g=Ls(e,w,nr(e,w));g&&Y.set(w,g)}xt.current=Date.now(),Wt(0),E(!0);let h=new AbortController;we.current=h,ie({verb:"Authoring",unit:"spec",total:f.length,done:0,active:[],rows:oo(f),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Authoring ${c.length} screenshot spec${c.length===1?"":"s"} across ${f.length} partition${f.length===1?"":"s"} (\u22646 agents at once) on ${P.model}${P.forced?" (forced)":""}\u2026 (esc to stop)`});let y=!1;try{for await(let w of Vr({cwd:e,partitions:f,promptFor:g=>jc(g,Y),concurrency:6,profileName:s,allowProdWrites:Ht.current,model:P.model,signal:h.signal}))if(w.type==="partition_status")w.status==="running"?ie(g=>g&&{...g,active:[...g.active,w.label],rows:We(g.rows,w.label,"active"),lastAt:Date.now()}):ie(g=>g&&{...g,active:g.active.filter(R=>R!==w.label),done:g.done+1,rows:We(g.rows,w.label,w.status==="done"?"done":"failed"),lastAt:Date.now()});else if(w.type==="partition_event")ie(g=>{if(!g)return g;let R={...g,lastAt:Date.now()};return w.event.type==="tool"?R.tools=g.tools+1:w.event.type==="text"&&(R.chars=g.chars+w.event.delta.length),R});else if(w.type==="run_done"){Jt(F=>F+w.totalCostUsd),Qt(F=>F+w.results.reduce((C,q)=>C+q.outputTokens,0));let g=w.results.filter(F=>F.ok).length,R=w.aborted?"Stopped. ":"";y=!w.aborted&&l.setup;let A=w.aborted?"":y?" Refreshing the capture-setup checklist\u2026":" Next: /screenshot capture --all (or /screenshot checklist first for the staging checklist).";d({kind:"note",tone:w.aborted?"warn":w.ok?"ok":"warn",text:`${R}Authored specs \u2014 ${g}/${w.results.length} batches ok.${A}`}),!w.aborted&&w.ok&&So(l.runLine)}}catch(w){d({kind:"note",tone:"error",text:`Spec authoring failed: ${w.message}`})}finally{we.current=null,ie(null),E(!1),H(w=>w+1)}if(y){let w=await gn();w.kind==="forward-to-agent"&&w.prompt&&await re(w.prompt,{display:w.display,quietUser:!0});let g=Gi(e);g&&d({kind:"note",tone:"info",text:g.join(`
401
401
  `)})}},[e,s,d,re,So]),nl=Q(async c=>{let l=Ls(e,c,nr(e,c))??void 0,i=await sr([c],void 0,{lastFailure:l});i.kind==="forward-to-agent"&&i.prompt&&await re(i.prompt,{display:i.display,quietUser:!0}),$c(e,c)&&ve(`Spec ready \u2014 /screenshot capture ${c} takes the screenshot; bare /screenshot picks the next shot.`,{kind:"cmd",cmd:`/screenshot capture ${c}`,reason:""})},[e,re,ve]),Po=Q(async(c,l)=>{if(!br(e)){await re(Hi(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(!Mu(e)){d({kind:"note",tone:"info",text:"No saved login for screenshot capture yet \u2014 opening a browser window. Sign in to your app (MFA included); I'll continue automatically once the session saves. (esc cancels)"}),E(!0),mo("Waiting for you to finish logging in (browser window)\u2026");let T=new AbortController;we.current=T;let V;try{V=await Uu({cwd:e,signal:T.signal})}catch(oe){d({kind:"note",tone:"error",text:`Could not launch the login: ${oe.message}`});return}finally{we.current=null,mo(null),E(!1)}if(V.exitCode!==0){qi(V.exitCode,V.output)?d({kind:"note",tone:"error",text:"d360-capture is not installed on this machine. Run: npm i -g document360-capture \u2014 then /screenshot capture again."}):/unknown option/i.test(V.output)?d({kind:"note",tone:"warn",text:"Your d360-capture is older than this writer. Update it: npm i -g document360-capture \u2014 then /screenshot capture again."}):d({kind:"note",tone:T.signal.aborted?"warn":"error",text:T.signal.aborted?"Login cancelled \u2014 nothing saved.":`Login did not complete:
402
- ${Fi(V.output)}`});return}d({kind:"note",tone:"ok",text:"\u2713 Login saved \u2014 continuing with the capture."})}let i=new Map(c.map(T=>[T,Cc(e,T)])),f=0;if(c.length>1){let T=c.filter(V=>i.get(V).mutates);if(T.length>0&&(f=T.length,c=c.filter(V=>!i.get(V).mutates),c.length===0)){d({kind:"note",tone:"warn",text:`\u26A0 All ${T.length} spec${T.length===1?"":"s"} in scope write real data, so a bulk run has nothing to do. Run one deliberately: /screenshot capture ${T[0]}`});return}}else if(c.length===1&&i.get(c[0]).mutates){let T=i.get(c[0]),V=Wu(e);d({kind:"note",tone:"warn",text:`\u26A0 This capture performs a REAL write in your app${T.what?`: ${vc(T.what)}`:T.declared?"":" (detected from the spec: form fill + commit click / file upload)"}. Running because you named it explicitly \u2014 check the result and clean up what it created. `+(V.production?`This profile is PRODUCTION \u2014 the write lands in the LIVE tenant${V.url?` (${V.url})`:""}. If the spec cleans up after itself, confirm it did.`:"Tip: point the capture scope (.d360-writer/capture.json) at a demo/non-production context for shots like this.")})}E(!0);let P=new AbortController;we.current=P;let Y=c.map(T=>({label:T,items:1,status:"pending"}));ie({verb:"Capturing",unit:"screenshot",total:c.length,done:0,active:[],rows:Y,tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()});let h=_t(e),y=Object.keys(h.shots).length>0,w=Fu(We(e).filter(T=>!c.includes(T.id)),f);d({kind:"note",tone:"info",text:`Capturing ${c.length} screenshot${c.length===1?"":"s"} with d360-capture (a real browser drives your app)\u2026 (esc to stop)`+(w?`
403
- ${w}`:"")});let g=Date.now(),C=[];try{for(let T of c){if(P.signal.aborted)break;ie(Re=>Re&&{...Re,active:[T],rows:Fe(Re.rows,T,"active"),lastAt:Date.now()});let{exitCode:V,output:oe}=await Bi({cwd:e,id:T,signal:P.signal,stdio:"pipe"});if(qi(V,oe)){d({kind:"note",tone:"error",text:"d360-capture is not installed on this machine. Run: npm i -g document360-capture \u2014 then /screenshot capture again."});return}let nt=P.signal.aborted&&V!==0?"failed":Wi(e,T,V,g),on=nt==="captured"?void 0:nt==="skipped"?_u(oe)??"a data prerequisite isn't met \u2014 the spec's skip reason names what to stage":Lu(oe);C.push({id:T,outcome:nt,detail:on}),ie(Re=>Re&&{...Re,active:[],done:Re.done+1,rows:Fe(Re.rows,T,nt==="captured"?"done":"failed"),lastAt:Date.now()})}}catch(T){d({kind:"note",tone:"error",text:`Capture run failed: ${T.message}`})}finally{we.current=null,ie(null),E(!1),H(T=>T+1)}if(C.length===0)return;let A=C.filter(T=>T.outcome==="captured"),F=C.filter(T=>T.outcome==="skipped"),R=C.filter(T=>T.outcome==="failed"),q=c.length-C.length;if(d({kind:"note",tone:R.length?"warn":A.length?"ok":"info",text:[`\u2713 ${A.length} captured`,F.length?`\u2298 ${F.length} blocked`:"",R.length?`\u2717 ${R.length} broken`:"",q?`${q} not run (stopped)`:""].filter(Boolean).join(" ")+` ${C.length} run${f>0?` \xB7 ${f} held back`:""}`+Hu(Bu(h,C),y).map(T=>`
404
- ${T}`).join("")}),R.length>0){let T=Math.max(...R.map(V=>V.id.length));d({kind:"note",tone:"error",text:R.map(V=>`\u2717 ${V.id.padEnd(T)} ${qu(V.detail)}`).join(`
405
- `)})}hc(e,C.map(T=>({id:T.id,outcome:T.outcome,reason:T.detail,specSource:nr(e,T.id)})),new Date().toISOString());let M=Vu({results:C,ids:c,articles:Gu(e,A.map(T=>T.id))});M&&ve(M.note,{kind:"cmd",cmd:M.cmd,reason:""},M.tone),C.length===c.length&&R.length===0&&F.length===0&&So(l?.runLine)},[e,d,ve,re,So]),ds=Q(c=>{let l=Ut(c);if(!l||$t(l)&&!l.refreshToken)return null;let i={...$n(l.idToken)??{},...$n(l.accessToken)??{}};return i.email??i.preferred_username??"signed in"},[]),ps=Q((c,l)=>{if(l){let i=ae(e);i&&(i.defaultProfile=c,op(i,e))}a(c),Ee(void 0,c),d({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${c}"${l?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),ds(c)||(d({kind:"note",tone:"warn",text:`Profile "${c}" is not signed in \u2014 sign in with /login.`}),Z("/login")),H(i=>i+1)},[e,d,Ee,ds,Z]),To=Q((c,l,i)=>{No(e,c,l,i.id,i.name),d({kind:"note",tone:"ok",text:`Switched to workspace "${i.name??i.id}" (agent restarted).`}),Ee(),rp(e,c)||(d({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),d({kind:"note",tone:"warn",text:"\u26A0 Before I write the docs, hand the prompt below to your builder (your repo's coding agent). It gives me the architecture brief that makes the docs accurate:"}),d({kind:"note",tone:"info",text:cn(ln(e)).join(`
406
- `)}),Zt(Ot()),An.current=Me(e).status==="current",en.current=rt(e),d({kind:"note",tone:"info",text:`No separate builder agent? Then just ask me now: "write the docs for this repo" \u2014 I'll read the code directly.`}))},[e,d,Ee,Zt]),Do=Q(async c=>{let l;try{l=await _n(e,c)}catch{d({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),Z("/workspace");return}if(l.workspaces.length===0){d({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let i=l.workspaces.filter(P=>(P.workspace_type??"").toLowerCase()!=="apidocumentation"),f=i.length>0?i:l.workspaces;if(f.length===1){let P=f[0],Y=l.workspaces.length-f.length;d({kind:"note",tone:"ok",text:`Selected the "${P.name??P.id}" workspace${Y>0?" (skipped the API-documentation workspace)":""}.`}),To(l.profile,l.projectId,P);return}d({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${f.length} available).`}),Z("/workspace")},[e,d,To,Z]),Ao=Q((c,l)=>{Io(e,c,l.id,l.name),d({kind:"note",tone:"ok",text:`Project set to "${l.name??l.id}" (agent restarted).`}),Ee(),Do(c)},[e,d,Ee,Do]),ol=Q(async c=>{let l;try{l=Ne(e,c)}catch{return}if(!l.project.workspaceId){if(l.project.projectId){if(!l.project.projectName)try{let{projects:i}=await pt(e,l.name),f=i.find(P=>P.id===l.project.projectId);f?.name&&bk(e,l.name,{projectName:f.name})}catch{}await Do(l.name);return}try{let{projects:i}=await pt(e,l.name);if(i.length===1){let f=i[0];d({kind:"note",tone:"ok",text:`Using your Document360 project "${f.name??f.id}".`}),Ao(l.name,{id:f.id,name:f.name});return}if(i.length>1){let f=i.map(P=>({id:P.id,name:P.name??P.id,sub:P.sub_domain}));d({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),St({cursor:0,current:-1,rows:f,profile:l.name,environment:l.connection.name});return}}catch{}d({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),Z("/project")}},[e,d,Do,Ao,Z]),tn=Q(()=>{let c=pe.current[0];if(!c)return;Ve();let{plan:l,mode:i}=c;d({kind:"note",tone:"info",text:`\u25CF ${l.title} (${l.path})`});for(let P of l.notes)d({kind:"note",tone:"warn",text:`\u26A0 ${P}`});l.overwritesLocalChanges&&i==="pull"&&d({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let f=it(l.oldContent,l.newContent,ct());d(f?{kind:"diff",added:f.added,removed:f.removed,lines:f.lines,hidden:f.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."}),i==="conflict"?(d({kind:"note",tone:"warn",text:"Conflict \u2014 edited both here and on the portal (diff shows local \u2192 portal)."}),d({kind:"note",tone:"info",text:"Keep local (publish, overwrites portal) \xB7 take Portal (overwrites local) \xB7 Skip? (l/p/s \u2014 anything else cancels)"})):d({kind:"note",tone:"info",text:`Write ${l.path}? (y/n \u2014 anything else cancels)`})},[d,ct,Ve]),hs=Q(()=>{if(pe.current.length>0){tn();return}let c=Vt.current;Vt.current=[],c.length>0?(d({kind:"note",tone:"info",text:`Publishing ${c.length} kept-local article${c.length===1?"":"s"} over the portal\u2026`}),It(c)):Z("/pull")},[tn,d,It,Z]),rl=Q(c=>{if(pe.current.length===0)return!1;let l=c.trim().toLowerCase(),i=pe.current[0];if(i.mode==="conflict"){if(l==="l"||l==="local")pe.current.shift(),Vt.current.push(i.plan.path),d({kind:"note",tone:"info",text:`Keeping local ${i.plan.path} \u2014 will publish over the portal.`});else if(l==="p"||l==="portal"){pe.current.shift();try{sp({cwd:e,profileName:s},i.plan),d({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${i.plan.path} (local overwritten, sync base advanced).`})}catch(f){d({kind:"note",tone:"error",text:`Take-portal failed: ${f.message}`})}}else if(l==="s"||l==="skip"||l==="n")pe.current.shift(),d({kind:"note",tone:"info",text:`Skipped ${i.plan.path} \u2014 still a conflict.`});else{let f=pe.current.length;return pe.current=[],Vt.current=[],d({kind:"note",tone:"info",text:`Resolve cancelled (${f} conflict${f===1?"":"s"} left untouched).`}),!0}return hs(),!0}if(l==="y"||l==="yes"){let f=pe.current.shift().plan;try{sp({cwd:e,profileName:s},f),d({kind:"note",tone:"ok",text:`\u2713 Pulled ${f.path} (sync base advanced).`})}catch(P){d({kind:"note",tone:"error",text:`Pull failed: ${P.message}`})}}else if(l==="n"||l==="no"){let f=pe.current.shift().plan;d({kind:"note",tone:"info",text:`Skipped ${f.path}.`})}else{let f=pe.current.length;return pe.current=[],d({kind:"note",tone:"info",text:`Pull cancelled (${f} article(s) left untouched).`}),!0}return hs(),!0},[e,s,hs,d]),fs=Q(async c=>{d({kind:"note",tone:"info",text:"Checking Document360 for conflicts\u2026"});try{let l=await Da({cwd:e,profileName:s}),i=c?.replace(/\\/g,"/"),f=l.entries.filter(Y=>Y.status==="conflict"&&Y.path).map(Y=>Y.path);if(i){if(!f.includes(i)){d({kind:"note",tone:"ok",text:`${i} isn\u2019t in conflict \u2014 nothing to resolve.`});return}f=[i]}if(f.length===0){d({kind:"note",tone:"ok",text:"\u2713 No conflicts \u2014 local and Document360 agree on every tracked article."});return}let P=[];for(let Y of f)try{P.push({plan:await ap({cwd:e,profileName:s,relPath:Y}),mode:"conflict"})}catch(h){d({kind:"note",tone:"error",text:`Could not load ${Y} from Document360: ${h.message}`})}if(P.length===0)return;d({kind:"note",tone:"info",text:`Resolving ${P.length} conflict${P.length===1?"":"s"} \u2014 for each: keep local, take portal, or skip.`}),pe.current=P,Vt.current=[],tn()}catch(l){d({kind:"note",tone:"error",text:`Could not compute sync status: ${l.message}`})}},[e,s,d,tn]),sl=Q(c=>{let l=ho.current;if(!l)return!1;if(ho.current=null,Ve(),c.trim()!==l.repoName)return d({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:i,failed:f}=oa(e,l.targets);d({kind:"note",tone:f.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${i.length} item${i.length===1?"":"s"}. The repo is back to its original state.`});for(let P of f)d({kind:"note",tone:"error",text:` \u2717 ${P.path}: ${P.error}`});return l.hadDevhints&&(d({kind:"note",tone:"warn",text:Vo().join(`
402
+ ${Fi(V.output)}`});return}d({kind:"note",tone:"ok",text:"\u2713 Login saved \u2014 continuing with the capture."})}let i=new Map(c.map(T=>[T,Cc(e,T)])),f=0;if(c.length>1){let T=c.filter(V=>i.get(V).mutates);if(T.length>0&&(f=T.length,c=c.filter(V=>!i.get(V).mutates),c.length===0)){d({kind:"note",tone:"warn",text:`\u26A0 All ${T.length} spec${T.length===1?"":"s"} in scope write real data, so a bulk run has nothing to do. Run one deliberately: /screenshot capture ${T[0]}`});return}}else if(c.length===1&&i.get(c[0]).mutates){let T=i.get(c[0]),V=Wu(e);d({kind:"note",tone:"warn",text:`\u26A0 This capture performs a REAL write in your app${T.what?`: ${vc(T.what)}`:T.declared?"":" (detected from the spec: form fill + commit click / file upload)"}. Running because you named it explicitly \u2014 check the result and clean up what it created. `+(V.production?`This profile is PRODUCTION \u2014 the write lands in the LIVE tenant${V.url?` (${V.url})`:""}. If the spec cleans up after itself, confirm it did.`:"Tip: point the capture scope (.d360-writer/capture.json) at a demo/non-production context for shots like this.")})}E(!0);let P=new AbortController;we.current=P;let Y=c.map(T=>({label:T,items:1,status:"pending"}));ie({verb:"Capturing",unit:"screenshot",total:c.length,done:0,active:[],rows:Y,tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()});let h=_t(e),y=Object.keys(h.shots).length>0,w=Fu(l?.heldBackBlocked??[],f);d({kind:"note",tone:"info",text:`Capturing ${c.length} screenshot${c.length===1?"":"s"} with d360-capture (a real browser drives your app)\u2026 (esc to stop)`+(w?`
403
+ ${w}`:"")});let g=Date.now(),R=[];try{for(let T of c){if(P.signal.aborted)break;ie(Re=>Re&&{...Re,active:[T],rows:We(Re.rows,T,"active"),lastAt:Date.now()});let{exitCode:V,output:oe}=await Bi({cwd:e,id:T,signal:P.signal,stdio:"pipe"});if(qi(V,oe)){d({kind:"note",tone:"error",text:"d360-capture is not installed on this machine. Run: npm i -g document360-capture \u2014 then /screenshot capture again."});return}let nt=P.signal.aborted&&V!==0?"failed":Wi(e,T,V,g),on=nt==="captured"?void 0:nt==="skipped"?_u(oe)??"a data prerequisite isn't met \u2014 the spec's skip reason names what to stage":Lu(oe);R.push({id:T,outcome:nt,detail:on}),ie(Re=>Re&&{...Re,active:[],done:Re.done+1,rows:We(Re.rows,T,nt==="captured"?"done":"failed"),lastAt:Date.now()})}}catch(T){d({kind:"note",tone:"error",text:`Capture run failed: ${T.message}`})}finally{we.current=null,ie(null),E(!1),H(T=>T+1)}if(R.length===0)return;let A=R.filter(T=>T.outcome==="captured"),F=R.filter(T=>T.outcome==="skipped"),C=R.filter(T=>T.outcome==="failed"),q=c.length-R.length;if(d({kind:"note",tone:C.length?"warn":A.length?"ok":"info",text:[`\u2713 ${A.length} captured`,F.length?`\u2298 ${F.length} blocked`:"",C.length?`\u2717 ${C.length} broken`:"",q?`${q} not run (stopped)`:""].filter(Boolean).join(" ")+` ${R.length} run${f>0?` \xB7 ${f} held back`:""}`+Hu(Bu(h,R),y).map(T=>`
404
+ ${T}`).join("")}),C.length>0){let T=Math.max(...C.map(V=>V.id.length));d({kind:"note",tone:"error",text:C.map(V=>`\u2717 ${V.id.padEnd(T)} ${qu(V.detail)}`).join(`
405
+ `)})}hc(e,R.map(T=>({id:T.id,outcome:T.outcome,reason:T.detail,specSource:nr(e,T.id)})),new Date().toISOString());let M=Vu({results:R,ids:c,articles:Gu(e,A.map(T=>T.id))});M&&ve(M.note,{kind:"cmd",cmd:M.cmd,reason:""},M.tone),R.length===c.length&&C.length===0&&F.length===0&&So(l?.runLine)},[e,d,ve,re,So]),ds=Q(c=>{let l=Ut(c);if(!l||$t(l)&&!l.refreshToken)return null;let i={...$n(l.idToken)??{},...$n(l.accessToken)??{}};return i.email??i.preferred_username??"signed in"},[]),ps=Q((c,l)=>{if(l){let i=ae(e);i&&(i.defaultProfile=c,op(i,e))}a(c),Ee(void 0,c),d({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${c}"${l?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),ds(c)||(d({kind:"note",tone:"warn",text:`Profile "${c}" is not signed in \u2014 sign in with /login.`}),Z("/login")),H(i=>i+1)},[e,d,Ee,ds,Z]),To=Q((c,l,i)=>{No(e,c,l,i.id,i.name),d({kind:"note",tone:"ok",text:`Switched to workspace "${i.name??i.id}" (agent restarted).`}),Ee(),rp(e,c)||(d({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),d({kind:"note",tone:"warn",text:"\u26A0 Before I write the docs, hand the prompt below to your builder (your repo's coding agent). It gives me the architecture brief that makes the docs accurate:"}),d({kind:"note",tone:"info",text:cn(ln(e)).join(`
406
+ `)}),Zt(Ot()),An.current=Me(e).status==="current",en.current=rt(e),d({kind:"note",tone:"info",text:`No separate builder agent? Then just ask me now: "write the docs for this repo" \u2014 I'll read the code directly.`}))},[e,d,Ee,Zt]),Do=Q(async c=>{let l;try{l=await _n(e,c)}catch{d({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),Z("/workspace");return}if(l.workspaces.length===0){d({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let i=l.workspaces.filter(P=>(P.workspace_type??"").toLowerCase()!=="apidocumentation"),f=i.length>0?i:l.workspaces;if(f.length===1){let P=f[0],Y=l.workspaces.length-f.length;d({kind:"note",tone:"ok",text:`Selected the "${P.name??P.id}" workspace${Y>0?" (skipped the API-documentation workspace)":""}.`}),To(l.profile,l.projectId,P);return}d({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${f.length} available).`}),Z("/workspace")},[e,d,To,Z]),Ao=Q((c,l)=>{Io(e,c,l.id,l.name),d({kind:"note",tone:"ok",text:`Project set to "${l.name??l.id}" (agent restarted).`}),Ee(),Do(c)},[e,d,Ee,Do]),ol=Q(async c=>{let l;try{l=Ne(e,c)}catch{return}if(!l.project.workspaceId){if(l.project.projectId){if(!l.project.projectName)try{let{projects:i}=await pt(e,l.name),f=i.find(P=>P.id===l.project.projectId);f?.name&&bk(e,l.name,{projectName:f.name})}catch{}await Do(l.name);return}try{let{projects:i}=await pt(e,l.name);if(i.length===1){let f=i[0];d({kind:"note",tone:"ok",text:`Using your Document360 project "${f.name??f.id}".`}),Ao(l.name,{id:f.id,name:f.name});return}if(i.length>1){let f=i.map(P=>({id:P.id,name:P.name??P.id,sub:P.sub_domain}));d({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),St({cursor:0,current:-1,rows:f,profile:l.name,environment:l.connection.name});return}}catch{}d({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),Z("/project")}},[e,d,Do,Ao,Z]),tn=Q(()=>{let c=pe.current[0];if(!c)return;He();let{plan:l,mode:i}=c;d({kind:"note",tone:"info",text:`\u25CF ${l.title} (${l.path})`});for(let P of l.notes)d({kind:"note",tone:"warn",text:`\u26A0 ${P}`});l.overwritesLocalChanges&&i==="pull"&&d({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let f=it(l.oldContent,l.newContent,ct());d(f?{kind:"diff",added:f.added,removed:f.removed,lines:f.lines,hidden:f.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."}),i==="conflict"?(d({kind:"note",tone:"warn",text:"Conflict \u2014 edited both here and on the portal (diff shows local \u2192 portal)."}),d({kind:"note",tone:"info",text:"Keep local (publish, overwrites portal) \xB7 take Portal (overwrites local) \xB7 Skip? (l/p/s \u2014 anything else cancels)"})):d({kind:"note",tone:"info",text:`Write ${l.path}? (y/n \u2014 anything else cancels)`})},[d,ct,He]),hs=Q(()=>{if(pe.current.length>0){tn();return}let c=Vt.current;Vt.current=[],c.length>0?(d({kind:"note",tone:"info",text:`Publishing ${c.length} kept-local article${c.length===1?"":"s"} over the portal\u2026`}),It(c)):Z("/pull")},[tn,d,It,Z]),rl=Q(c=>{if(pe.current.length===0)return!1;let l=c.trim().toLowerCase(),i=pe.current[0];if(i.mode==="conflict"){if(l==="l"||l==="local")pe.current.shift(),Vt.current.push(i.plan.path),d({kind:"note",tone:"info",text:`Keeping local ${i.plan.path} \u2014 will publish over the portal.`});else if(l==="p"||l==="portal"){pe.current.shift();try{sp({cwd:e,profileName:s},i.plan),d({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${i.plan.path} (local overwritten, sync base advanced).`})}catch(f){d({kind:"note",tone:"error",text:`Take-portal failed: ${f.message}`})}}else if(l==="s"||l==="skip"||l==="n")pe.current.shift(),d({kind:"note",tone:"info",text:`Skipped ${i.plan.path} \u2014 still a conflict.`});else{let f=pe.current.length;return pe.current=[],Vt.current=[],d({kind:"note",tone:"info",text:`Resolve cancelled (${f} conflict${f===1?"":"s"} left untouched).`}),!0}return hs(),!0}if(l==="y"||l==="yes"){let f=pe.current.shift().plan;try{sp({cwd:e,profileName:s},f),d({kind:"note",tone:"ok",text:`\u2713 Pulled ${f.path} (sync base advanced).`})}catch(P){d({kind:"note",tone:"error",text:`Pull failed: ${P.message}`})}}else if(l==="n"||l==="no"){let f=pe.current.shift().plan;d({kind:"note",tone:"info",text:`Skipped ${f.path}.`})}else{let f=pe.current.length;return pe.current=[],d({kind:"note",tone:"info",text:`Pull cancelled (${f} article(s) left untouched).`}),!0}return hs(),!0},[e,s,hs,d]),fs=Q(async c=>{d({kind:"note",tone:"info",text:"Checking Document360 for conflicts\u2026"});try{let l=await Da({cwd:e,profileName:s}),i=c?.replace(/\\/g,"/"),f=l.entries.filter(Y=>Y.status==="conflict"&&Y.path).map(Y=>Y.path);if(i){if(!f.includes(i)){d({kind:"note",tone:"ok",text:`${i} isn\u2019t in conflict \u2014 nothing to resolve.`});return}f=[i]}if(f.length===0){d({kind:"note",tone:"ok",text:"\u2713 No conflicts \u2014 local and Document360 agree on every tracked article."});return}let P=[];for(let Y of f)try{P.push({plan:await ap({cwd:e,profileName:s,relPath:Y}),mode:"conflict"})}catch(h){d({kind:"note",tone:"error",text:`Could not load ${Y} from Document360: ${h.message}`})}if(P.length===0)return;d({kind:"note",tone:"info",text:`Resolving ${P.length} conflict${P.length===1?"":"s"} \u2014 for each: keep local, take portal, or skip.`}),pe.current=P,Vt.current=[],tn()}catch(l){d({kind:"note",tone:"error",text:`Could not compute sync status: ${l.message}`})}},[e,s,d,tn]),sl=Q(c=>{let l=ho.current;if(!l)return!1;if(ho.current=null,He(),c.trim()!==l.repoName)return d({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:i,failed:f}=oa(e,l.targets);d({kind:"note",tone:f.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${i.length} item${i.length===1?"":"s"}. The repo is back to its original state.`});for(let P of f)d({kind:"note",tone:"error",text:` \u2717 ${P.path}: ${P.error}`});return l.hadDevhints&&(d({kind:"note",tone:"warn",text:Vo().join(`
407
407
  `)}),Zt(vs())),d({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
408
- ${gp}`}),Z("/init"),lo(!1),!0},[e,d,Zt,Ve,Z]),jn=Q(async c=>{let l=c.slice(1).trim().split(/\s+/),i=(l[0]??"").toLowerCase(),f=l.slice(1);if(lo(!0),fr(f)&&["write","check","review","reorder"].includes(i)){let h=zn(e,s);if(h.length===0){d({kind:"note",tone:"warn",text:"No categories yet \u2014 author some articles first, then scope to one."});return}let y=w=>i==="write"?`/write ${nu(f,w).join(" ")}`.trim():`/${i} ${[w,...f.filter(g=>g!=="--scope")].join(" ")}`.trim();if(h.length===1){jn(y(h[0].token));return}Tt({cursor:0,rows:h,run:w=>{jn(y(w))}});return}if(kt(i,f)){let h=zn(e,s);if(h.length>1){let y=f.filter(A=>A.startsWith("--")).join(" "),w=A=>`/${i}${A?` ${i==="write"?`--scope ${A}`:A}`:""}${y?` ${y}`:""} ${A?"":"--all"}`.replace(/\s+/g," ").trim(),g=h.reduce((A,F)=>A+F.count,0),C={token:"",label:i==="review"?`Everything \u2014 all ${g} articles + structure (IA) review`:i==="reorder"?`Everything \u2014 reorder all ${h.length} categories`:`Everything \u2014 rewrite all ${g} planned articles`,count:g};Tt({cursor:0,rows:[C,...h],run:A=>{jn(w(A))}});return}}let P=async h=>{let y=Li(h);if(!br(e)){await re(Hi(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(y.mode==="single"){await Po([y.id],{runLine:[`/screenshot capture ${y.id}`,`/capture ${y.id}`]});return}if(y.mode==="failed"){let g=Mi(e,kr(e).rows);if(g.length===0){d({kind:"note",tone:"info",text:"No broken specs to re-run \u2014 /screenshot list shows where things stand."}),Z("/screenshot list");return}await Po(g);return}if(y.mode==="all"||y.mode==="scope"){let g=y.mode==="scope"?y.scope:void 0,{ready:C,captured:A,blocked:F,rows:R}=kr(e,g),q=[...C,...A,...y.retryBlocked?F:[]];if(q.length===0&&F.length>0&&!y.retryBlocked){let T=g?`/screenshot capture ${g} --retry-blocked`:"/screenshot capture --all --retry-blocked";ve(`All ${F.length} shot${F.length===1?"":"s"} in scope ${F.length===1?"is":"are"} blocked on data that wasn't staged last run \u2014 /screenshot list shows what to stage, then ${T}.`,{kind:"cmd",cmd:"/screenshot list",reason:""},"warn");return}if(q.length===0){d({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),Z("/screenshot");return}if(!y.retryBlocked){let T=g?`/screenshot capture ${g} --retry-blocked`:"/screenshot capture --all --retry-blocked",V=Ui(R.filter(oe=>oe.state==="blocked"),T);V&&d({kind:"note",tone:"info",text:V})}let M=y.mode==="scope"?[`/screenshot capture ${y.scope}`,`/capture ${y.scope}`]:["/screenshot capture --all","/capture --all"];await Po(q,{runLine:M});return}let w=Ou(We(e));if(w.length===0){d({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),Z("/screenshot");return}Pt({cursor:0,rows:w,title:"Capture screenshots \u2014 pick what to shoot:"})},Y=async()=>{let h=await gn();h.kind==="forward-to-agent"&&h.prompt&&await re(h.prompt,{display:h.display,quietUser:!0});let y=Gi(e);y&&d({kind:"note",tone:"info",text:y.join(`
409
- `)})};switch(i){case"help":Tn({tab:0});return;case"exit":case"quit":Oe.current?.close(),r();return;case"clear":Ee(),qt.current=[],lo(!1),Ve(),console.log("\x1B[?2026h\x1B[H\x1B[2J\x1B[3J\x1B[?2026l"),d({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let h;try{h=Ne(e,s)}catch(y){d({kind:"note",tone:"error",text:y.message});return}d({kind:"note",tone:"info",text:`Profile "${h.name}" \u2192 ${h.connection.name} (${h.connection.apiUrl})${h.production?" \u26A0 PRODUCTION":""}`}),L(!0);try{let y=await Bw(h.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},g=>d({kind:"note",tone:"info",text:g})),w=qw(h.name,y);if(Hw(w),await ws(w,h.name,g=>d({kind:"note",tone:"info",text:g})),d({kind:"note",tone:"ok",text:`\u2713 Logged in to "${h.name}" as ${Lo(w)}`}),await ol(s),Pn.current){let g=Pn.current;Pn.current=null;let C=Ue(e,s);C.ok?(d({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 tab to run ${g}.`}),Z(g)):(d({kind:"note",tone:"warn",text:`${C.reason} (then ${g}.)`}),Z("/login"),Pn.current=g)}else Sn.current&&(xe(Sn.current,"\u21E5 tab to re-send your last prompt\u2026"),Sn.current=null)}catch(y){d({kind:"note",tone:"error",text:`Login failed: ${y.message}`})}finally{L(!1),H(y=>y+1)}return}case"allow-prod":{let h=!1;try{h=Ne(e,s).production}catch{}if(!h){d({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}Ht.current=!0,Ee(),d({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let h=Di(f.join(" ")),y=Je.current.uuid;if(!y){if(!h){d({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}Zr.current=h,vt(h),wn(`${Ur} ${h}`),d({kind:"note",tone:"ok",text:`Session will be named "${h}" once it starts.`});return}if(!h){d({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let w=Je.current.firstPrompt??"";np(w,e).then(g=>{g?(xe(`/rename ${g}`),d({kind:"note",tone:"info",text:`Suggestion: "${g}" \u2014 press tab to accept, or type /rename <your name>.`})):d({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>d({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}tk(y,h),vt(h),wn(`${Ur} ${h}`),d({kind:"note",tone:"ok",text:`Session renamed to "${h}".`});return}case"profile":{let h=f[0],y=ae(e);if(!h){let w=Object.entries(y?.profiles??{});if(w.length===0){d({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let g=w.map(([F,R])=>({name:F,env:R.connection?.environment??"custom",prod:R.production===!0,who:ds(F)})),C=s??y?.defaultProfile,A=Math.max(0,g.findIndex(F=>F.name===C));Gt({cursor:A,current:A,rows:g});return}if(h==="add"){let w=Ai(e,f[1],f[2]);if(w){d({kind:"note",tone:"error",text:w});return}d({kind:"note",tone:"ok",text:`\u2713 Profile "${f[1]}" created (environment: ${f[2]??f[1]}).`}),ps(f[1],!1);return}if(!y?.profiles?.[h]){d({kind:"note",tone:"error",text:`Unknown profile "${h}". Create it: /profile add ${h} <environment>`});return}ps(h,!0);return}case"doctor":await Xn(f,{cwd:e,version:o});return;case"genre":{await Sr(f,{cwd:e});try{zr.current=!(ae(e)?.appType??rk(e))}catch{}H(h=>h+1);return}case"roadmap":{if(f[0]?.toLowerCase()==="done"){let h=Tr(e,f.slice(1).join(" ").trim());d({kind:"note",tone:h.ok?"ok":"warn",text:h.line}),H(y=>y+1);return}d({kind:"note",tone:"info",text:ca(e).join(`
410
- `)});return}case"mcp":await zo(f);return;case"init":{if(ae(e)){d({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer/config.json directly (or d360-writer init for the CLI wizard)."});return}let h=ck().map(y=>({name:y,apiUrl:uk(y).apiUrl}));Yt({cursor:0,rows:h});return}case"resume":{let h=f.join(" ").trim(),y=ek(e).filter(C=>C.uuid!==Je.current.uuid);if(!h){if(!y.length){d({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}Et({query:"",cursor:0,sessions:y});return}let w=Zw(e,h);if(!w){d({kind:"note",tone:"error",text:`No session matches "${h}".`});return}Ee(w.uuid),Je.current={uuid:w.uuid,firstPrompt:w.firstPrompt,titleFired:!0},vt(w.name),Ta(w.uuid),qt.current=[];let g=va(e,w.uuid);for(let C of g)d(C);d({kind:"note",tone:"ok",text:g.length?`Resumed "${w.name}" \u2014 restored ${g.length} message(s); continue where you left off.`:`Resumed "${w.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let h=f.join(" ").trim(),y;try{y=await _n(e,s)}catch(g){d({kind:"note",tone:"error",text:`Could not list workspaces: ${g.message}`});return}if(!h){let g=y.workspaces.map(A=>({id:A.id,name:A.name??A.id,type:A.workspace_type}));if(g.length===0){d({kind:"note",tone:"info",text:"No workspaces in this project."});return}let C=Math.max(0,g.findIndex(A=>A.id===y.current));zt({cursor:C,current:C,rows:g,profile:y.profile,projectId:y.projectId,projectName:y.projectName,environment:y.environment});return}let w=gs(y.workspaces,h);if(!w){d({kind:"note",tone:"error",text:`No workspace matches "${h}".`});return}To(y.profile,y.projectId,w);return}case"project":{let h=f.join(" ").trim(),y;try{y=await pt(e,s)}catch(g){d({kind:"note",tone:"error",text:`Could not list projects: ${g.message} (signed in? try /login)`});return}if(!h){let g=y.projects.map(A=>({id:A.id,name:A.name??A.id,sub:A.sub_domain}));if(g.length===0){d({kind:"note",tone:"info",text:"No projects found for this identity."});return}let C=g.findIndex(A=>A.id===y.current);St({cursor:Math.max(0,C),current:C,rows:g,profile:y.profile,environment:y.environment});return}let w=ys(y.projects,h);if(!w){d({kind:"note",tone:"error",text:`No project matches "${h}". Available: ${y.projects.map(g=>g.name??g.id).join(", ")}`});return}Ao(y.profile,w);return}case"logout":{let h;try{h=Ne(e,s).name}catch(w){d({kind:"note",tone:"error",text:w.message});return}let y=zw(h);Kw(e,h),Ee(),H(w=>w+1),d({kind:"note",tone:y?"ok":"info",text:y?`\u2713 Signed out of "${h}" and cleared its project/workspace selection.`:`Profile "${h}" was not signed in. Cleared any project/workspace selection.`}),d({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),Z("/login");return}case"publish":{if(!ko(c.trim()))return;if(f.includes("--screenshots")||f.includes("--shots")){let g=or(We(e));if(g.length===0){d({kind:"note",tone:"info",text:"No captured screenshots yet \u2014 /screenshot capture first."});return}d({kind:"note",tone:"info",text:`Re-saving ${g.length} article${g.length===1?"":"s"} with captured screenshots so the images embed\u2026`}),await It(g);return}if(f[0]==="--related"&&f[1]){let g=await ur(e,s,f[1].replace(/\\/g,"/"));if(g.length===0){d({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await It(g);return}let h=f.filter(g=>!g.startsWith("--"));if(h[0]){await us(h[0]);return}let y=f.includes("--all"),w=f.includes("--force");d({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let g=await Da({cwd:e,profileName:s}),{clean:C,conflicts:A}=ar(g.entries),F=y&&w&&A.length>0,R=cr(g.entries);if(R>0&&d({kind:"note",tone:"warn",text:`\u26A0 ${R} article${R===1?"":"s"} already exist on Document360 but aren\u2019t linked \u2014 left OUT of publish (publishing would duplicate them). Run /catch-up (or ask me to link them) first.`}),A.length>0&&!F&&d({kind:"note",tone:"warn",text:lr(A.length)}),C.length===0&&!F){if(A.length>0){Z("/resolve");return}d({kind:"note",tone:"ok",text:R>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let q=g.counts["unknown-base"]??0;q>0&&d({kind:"note",tone:"info",text:`(${q} article(s) have no sync base yet \u2014 publish those by path if needed.)`}),mo("Reconciling structure on Document360 (order + related articles)\u2026");try{let M=await pp({cwd:e,profileName:s}),T=mp(await fp({cwd:e,profileName:s})),V=hp(M);V?d({kind:"note",tone:"info",text:V}):M.skipped&&d({kind:"note",tone:"warn",text:`Order sync skipped: ${M.skipped}`}),T&&d({kind:"note",tone:"info",text:T}),d({kind:"note",tone:"ok",text:V||T?"\u2713 Structure synced to Document360 \u2014 /structure shows the new category + article order.":"\u2713 Already in order \u2014 nothing to change."}),(V||T)&&Z("/structure")}catch(M){d({kind:"note",tone:"warn",text:`Structure sync failed: ${M.message}`})}finally{mo(null)}return}if(y){let q=(F?[...C,...A]:C).map(M=>M.path);await It(q),A.length>0&&!F&&Z("/resolve");return}Kt({cursor:0,rows:Mc(C,A)})}catch(g){d({kind:"note",tone:"error",text:`Could not compute sync status: ${g.message}`}),d({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"resolve":{if(!ko(c.trim()))return;await fs(f.find(h=>!h.startsWith("--")));return}case"preview":{let h=f.join(" ").trim();if(!h){let w=[];try{w=Object.keys(rp(e,Ne(e,s).name)?.articles??{})}catch{}if(w.length===0){d({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}Dt({query:"",cursor:0,paths:w});return}let y=Ww(h)?h:Pa(e,h);if(kn(y)){try{d({kind:"preview",name:ro(y),text:wp(Hr(y,"utf8"))})}catch(w){d({kind:"note",tone:"error",text:`Could not read ${y}: ${w.message}`})}return}if(Ak.test(h)){try{let w=Ne(e,s),g={profile:w.name,connection:w.connection},C=w.project.projectId??Gw(g),A=await Yw(g,C,h);d({kind:"preview",name:A.title??h,text:A.content??"*(article has no content)*"})}catch(w){d({kind:"note",tone:"error",text:`Could not fetch article: ${w.message}`})}return}d({kind:"note",tone:"error",text:`"${h}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let h=f[0]?.trim();if(!h){let C=gr(Ia(e));Rt({cursor:C,current:C});return}let{lines:y,changed:w,effective:g}=Kn(e,h);for(let C of y)d({kind:"note",tone:C.startsWith("\u26A0")?"warn":C.startsWith("\u2713")?"ok":"info",text:C});w&&(Ka(C=>C+1),Oe.current?.setModel(g));return}case"convert":{if(!ae(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:h,run:y}=ii(f),w=hk(e,s);if(w.length===0){d({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let g=ai(w,h);if(g.length===0){d({kind:"note",tone:"error",text:`No tracked articles under "${h}". (${w.length} are tracked overall.)`});return}let C=Aa(g),A=3,F=`/convert${h?` --scope ${h}`:""} --run`,R=Gr(e,"light");if(!y){let M=lp({files:li(e,g),op:"convert",model:R.model}),T=h?`Scope: ${h} (${g.length} of ${w.length} tracked)
408
+ ${gp}`}),Z("/init"),lo(!1),!0},[e,d,Zt,He,Z]),jn=Q(async c=>{let l=c.slice(1).trim().split(/\s+/),i=(l[0]??"").toLowerCase(),f=l.slice(1);if(lo(!0),fr(f)&&["write","check","review","reorder"].includes(i)){let h=zn(e,s);if(h.length===0){d({kind:"note",tone:"warn",text:"No categories yet \u2014 author some articles first, then scope to one."});return}let y=w=>i==="write"?`/write ${nu(f,w).join(" ")}`.trim():`/${i} ${[w,...f.filter(g=>g!=="--scope")].join(" ")}`.trim();if(h.length===1){jn(y(h[0].token));return}Tt({cursor:0,rows:h,run:w=>{jn(y(w))}});return}if(kt(i,f)){let h=zn(e,s);if(h.length>1){let y=f.filter(A=>A.startsWith("--")).join(" "),w=A=>`/${i}${A?` ${i==="write"?`--scope ${A}`:A}`:""}${y?` ${y}`:""} ${A?"":"--all"}`.replace(/\s+/g," ").trim(),g=h.reduce((A,F)=>A+F.count,0),R={token:"",label:i==="review"?`Everything \u2014 all ${g} articles + structure (IA) review`:i==="reorder"?`Everything \u2014 reorder all ${h.length} categories`:`Everything \u2014 rewrite all ${g} planned articles`,count:g};Tt({cursor:0,rows:[R,...h],run:A=>{jn(w(A))}});return}}let P=async h=>{let y=Li(h);if(!br(e)){await re(Hi(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(y.mode==="single"){await Po([y.id],{runLine:[`/screenshot capture ${y.id}`,`/capture ${y.id}`]});return}if(y.mode==="failed"){let g=Mi(e,kr(e).rows);if(g.length===0){d({kind:"note",tone:"info",text:"No broken specs to re-run \u2014 /screenshot list shows where things stand."}),Z("/screenshot list");return}await Po(g);return}if(y.mode==="all"||y.mode==="scope"){let g=y.mode==="scope"?y.scope:void 0,{ready:R,captured:A,blocked:F,rows:C}=kr(e,g),q=[...R,...A,...y.retryBlocked?F:[]];if(q.length===0&&F.length>0&&!y.retryBlocked){let T=g?`/screenshot capture ${g} --retry-blocked`:"/screenshot capture --all --retry-blocked";ve(`All ${F.length} shot${F.length===1?"":"s"} in scope ${F.length===1?"is":"are"} blocked on data that wasn't staged last run \u2014 /screenshot list shows what to stage, then ${T}.`,{kind:"cmd",cmd:"/screenshot list",reason:""},"warn");return}if(q.length===0){d({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),Z("/screenshot");return}if(!y.retryBlocked){let T=g?`/screenshot capture ${g} --retry-blocked`:"/screenshot capture --all --retry-blocked",V=Ui(C.filter(oe=>oe.state==="blocked"),T);V&&d({kind:"note",tone:"info",text:V})}let M=y.mode==="scope"?[`/screenshot capture ${y.scope}`,`/capture ${y.scope}`]:["/screenshot capture --all","/capture --all"];await Po(q,{runLine:M,...y.retryBlocked?{}:{heldBackBlocked:C.filter(T=>T.state==="blocked")}});return}let w=Ou(ze(e));if(w.length===0){d({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),Z("/screenshot");return}Pt({cursor:0,rows:w,title:"Capture screenshots \u2014 pick what to shoot:"})},Y=async()=>{let h=await gn();h.kind==="forward-to-agent"&&h.prompt&&await re(h.prompt,{display:h.display,quietUser:!0});let y=Gi(e);y&&d({kind:"note",tone:"info",text:y.join(`
409
+ `)})};switch(i){case"help":Tn({tab:0});return;case"exit":case"quit":Oe.current?.close(),r();return;case"clear":Ee(),qt.current=[],lo(!1),He(),console.log("\x1B[?2026h\x1B[H\x1B[2J\x1B[3J\x1B[?2026l"),d({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let h;try{h=Ne(e,s)}catch(y){d({kind:"note",tone:"error",text:y.message});return}d({kind:"note",tone:"info",text:`Profile "${h.name}" \u2192 ${h.connection.name} (${h.connection.apiUrl})${h.production?" \u26A0 PRODUCTION":""}`}),L(!0);try{let y=await Bw(h.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},g=>d({kind:"note",tone:"info",text:g})),w=qw(h.name,y);if(Hw(w),await ws(w,h.name,g=>d({kind:"note",tone:"info",text:g})),d({kind:"note",tone:"ok",text:`\u2713 Logged in to "${h.name}" as ${Lo(w)}`}),await ol(s),Pn.current){let g=Pn.current;Pn.current=null;let R=Ue(e,s);R.ok?(d({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 tab to run ${g}.`}),Z(g)):(d({kind:"note",tone:"warn",text:`${R.reason} (then ${g}.)`}),Z("/login"),Pn.current=g)}else Sn.current&&(xe(Sn.current,"\u21E5 tab to re-send your last prompt\u2026"),Sn.current=null)}catch(y){d({kind:"note",tone:"error",text:`Login failed: ${y.message}`})}finally{L(!1),H(y=>y+1)}return}case"allow-prod":{let h=!1;try{h=Ne(e,s).production}catch{}if(!h){d({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}Ht.current=!0,Ee(),d({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let h=Di(f.join(" ")),y=Je.current.uuid;if(!y){if(!h){d({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}Zr.current=h,vt(h),wn(`${Ur} ${h}`),d({kind:"note",tone:"ok",text:`Session will be named "${h}" once it starts.`});return}if(!h){d({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let w=Je.current.firstPrompt??"";np(w,e).then(g=>{g?(xe(`/rename ${g}`),d({kind:"note",tone:"info",text:`Suggestion: "${g}" \u2014 press tab to accept, or type /rename <your name>.`})):d({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>d({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}tk(y,h),vt(h),wn(`${Ur} ${h}`),d({kind:"note",tone:"ok",text:`Session renamed to "${h}".`});return}case"profile":{let h=f[0],y=ae(e);if(!h){let w=Object.entries(y?.profiles??{});if(w.length===0){d({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let g=w.map(([F,C])=>({name:F,env:C.connection?.environment??"custom",prod:C.production===!0,who:ds(F)})),R=s??y?.defaultProfile,A=Math.max(0,g.findIndex(F=>F.name===R));Gt({cursor:A,current:A,rows:g});return}if(h==="add"){let w=Ai(e,f[1],f[2]);if(w){d({kind:"note",tone:"error",text:w});return}d({kind:"note",tone:"ok",text:`\u2713 Profile "${f[1]}" created (environment: ${f[2]??f[1]}).`}),ps(f[1],!1);return}if(!y?.profiles?.[h]){d({kind:"note",tone:"error",text:`Unknown profile "${h}". Create it: /profile add ${h} <environment>`});return}ps(h,!0);return}case"doctor":await Xn(f,{cwd:e,version:o});return;case"genre":{await Sr(f,{cwd:e});try{zr.current=!(ae(e)?.appType??rk(e))}catch{}H(h=>h+1);return}case"roadmap":{if(f[0]?.toLowerCase()==="done"){let h=Tr(e,f.slice(1).join(" ").trim());d({kind:"note",tone:h.ok?"ok":"warn",text:h.line}),H(y=>y+1);return}d({kind:"note",tone:"info",text:ca(e).join(`
410
+ `)});return}case"mcp":await zo(f);return;case"init":{if(ae(e)){d({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer/config.json directly (or d360-writer init for the CLI wizard)."});return}let h=ck().map(y=>({name:y,apiUrl:uk(y).apiUrl}));Yt({cursor:0,rows:h});return}case"resume":{let h=f.join(" ").trim(),y=ek(e).filter(R=>R.uuid!==Je.current.uuid);if(!h){if(!y.length){d({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}Et({query:"",cursor:0,sessions:y});return}let w=Zw(e,h);if(!w){d({kind:"note",tone:"error",text:`No session matches "${h}".`});return}Ee(w.uuid),Je.current={uuid:w.uuid,firstPrompt:w.firstPrompt,titleFired:!0},vt(w.name),Ta(w.uuid),qt.current=[];let g=va(e,w.uuid);for(let R of g)d(R);d({kind:"note",tone:"ok",text:g.length?`Resumed "${w.name}" \u2014 restored ${g.length} message(s); continue where you left off.`:`Resumed "${w.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let h=f.join(" ").trim(),y;try{y=await _n(e,s)}catch(g){d({kind:"note",tone:"error",text:`Could not list workspaces: ${g.message}`});return}if(!h){let g=y.workspaces.map(A=>({id:A.id,name:A.name??A.id,type:A.workspace_type}));if(g.length===0){d({kind:"note",tone:"info",text:"No workspaces in this project."});return}let R=Math.max(0,g.findIndex(A=>A.id===y.current));zt({cursor:R,current:R,rows:g,profile:y.profile,projectId:y.projectId,projectName:y.projectName,environment:y.environment});return}let w=gs(y.workspaces,h);if(!w){d({kind:"note",tone:"error",text:`No workspace matches "${h}".`});return}To(y.profile,y.projectId,w);return}case"project":{let h=f.join(" ").trim(),y;try{y=await pt(e,s)}catch(g){d({kind:"note",tone:"error",text:`Could not list projects: ${g.message} (signed in? try /login)`});return}if(!h){let g=y.projects.map(A=>({id:A.id,name:A.name??A.id,sub:A.sub_domain}));if(g.length===0){d({kind:"note",tone:"info",text:"No projects found for this identity."});return}let R=g.findIndex(A=>A.id===y.current);St({cursor:Math.max(0,R),current:R,rows:g,profile:y.profile,environment:y.environment});return}let w=ys(y.projects,h);if(!w){d({kind:"note",tone:"error",text:`No project matches "${h}". Available: ${y.projects.map(g=>g.name??g.id).join(", ")}`});return}Ao(y.profile,w);return}case"logout":{let h;try{h=Ne(e,s).name}catch(w){d({kind:"note",tone:"error",text:w.message});return}let y=zw(h);Kw(e,h),Ee(),H(w=>w+1),d({kind:"note",tone:y?"ok":"info",text:y?`\u2713 Signed out of "${h}" and cleared its project/workspace selection.`:`Profile "${h}" was not signed in. Cleared any project/workspace selection.`}),d({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),Z("/login");return}case"publish":{if(!ko(c.trim()))return;if(f.includes("--screenshots")||f.includes("--shots")){let g=or(ze(e));if(g.length===0){d({kind:"note",tone:"info",text:"No captured screenshots yet \u2014 /screenshot capture first."});return}d({kind:"note",tone:"info",text:`Re-saving ${g.length} article${g.length===1?"":"s"} with captured screenshots so the images embed\u2026`}),await It(g);return}if(f[0]==="--related"&&f[1]){let g=await ur(e,s,f[1].replace(/\\/g,"/"));if(g.length===0){d({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await It(g);return}let h=f.filter(g=>!g.startsWith("--"));if(h[0]){await us(h[0]);return}let y=f.includes("--all"),w=f.includes("--force");d({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let g=await Da({cwd:e,profileName:s}),{clean:R,conflicts:A}=ar(g.entries),F=y&&w&&A.length>0,C=cr(g.entries);if(C>0&&d({kind:"note",tone:"warn",text:`\u26A0 ${C} article${C===1?"":"s"} already exist on Document360 but aren\u2019t linked \u2014 left OUT of publish (publishing would duplicate them). Run /catch-up (or ask me to link them) first.`}),A.length>0&&!F&&d({kind:"note",tone:"warn",text:lr(A.length)}),R.length===0&&!F){if(A.length>0){Z("/resolve");return}d({kind:"note",tone:"ok",text:C>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let q=g.counts["unknown-base"]??0;q>0&&d({kind:"note",tone:"info",text:`(${q} article(s) have no sync base yet \u2014 publish those by path if needed.)`}),mo("Reconciling structure on Document360 (order + related articles)\u2026");try{let M=await pp({cwd:e,profileName:s}),T=mp(await fp({cwd:e,profileName:s})),V=hp(M);V?d({kind:"note",tone:"info",text:V}):M.skipped&&d({kind:"note",tone:"warn",text:`Order sync skipped: ${M.skipped}`}),T&&d({kind:"note",tone:"info",text:T}),d({kind:"note",tone:"ok",text:V||T?"\u2713 Structure synced to Document360 \u2014 /structure shows the new category + article order.":"\u2713 Already in order \u2014 nothing to change."}),(V||T)&&Z("/structure")}catch(M){d({kind:"note",tone:"warn",text:`Structure sync failed: ${M.message}`})}finally{mo(null)}return}if(y){let q=(F?[...R,...A]:R).map(M=>M.path);await It(q),A.length>0&&!F&&Z("/resolve");return}Kt({cursor:0,rows:Mc(R,A)})}catch(g){d({kind:"note",tone:"error",text:`Could not compute sync status: ${g.message}`}),d({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"resolve":{if(!ko(c.trim()))return;await fs(f.find(h=>!h.startsWith("--")));return}case"preview":{let h=f.join(" ").trim();if(!h){let w=[];try{w=Object.keys(rp(e,Ne(e,s).name)?.articles??{})}catch{}if(w.length===0){d({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}Dt({query:"",cursor:0,paths:w});return}let y=Ww(h)?h:Pa(e,h);if(kn(y)){try{d({kind:"preview",name:ro(y),text:wp(Hr(y,"utf8"))})}catch(w){d({kind:"note",tone:"error",text:`Could not read ${y}: ${w.message}`})}return}if(Ak.test(h)){try{let w=Ne(e,s),g={profile:w.name,connection:w.connection},R=w.project.projectId??Gw(g),A=await Yw(g,R,h);d({kind:"preview",name:A.title??h,text:A.content??"*(article has no content)*"})}catch(w){d({kind:"note",tone:"error",text:`Could not fetch article: ${w.message}`})}return}d({kind:"note",tone:"error",text:`"${h}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let h=f[0]?.trim();if(!h){let R=gr(Ia(e));Rt({cursor:R,current:R});return}let{lines:y,changed:w,effective:g}=Kn(e,h);for(let R of y)d({kind:"note",tone:R.startsWith("\u26A0")?"warn":R.startsWith("\u2713")?"ok":"info",text:R});w&&(Ka(R=>R+1),Oe.current?.setModel(g));return}case"convert":{if(!ae(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:h,run:y}=ii(f),w=hk(e,s);if(w.length===0){d({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let g=ai(w,h);if(g.length===0){d({kind:"note",tone:"error",text:`No tracked articles under "${h}". (${w.length} are tracked overall.)`});return}let R=Aa(g),A=3,F=`/convert${h?` --scope ${h}`:""} --run`,C=Gr(e,"light");if(!y){let M=lp({files:li(e,g),op:"convert",model:C.model}),T=h?`Scope: ${h} (${g.length} of ${w.length} tracked)
411
411
  `:"",V=`
412
- Model: ${R.model}${R.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;d({kind:"note",tone:"info",text:T+ui(C,M,A).join(`
413
- `)+V}),Z(F);return}xt.current=Date.now(),Wt(0),E(!0);let q=new AbortController;we.current=q,ie({verb:"Converting",total:C.length,done:0,active:[],rows:oo(C),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Converting ${g.length} articles across ${C.length} partitions (\u2264${A} agents at once) on ${R.model}\u2026 (esc to stop)`});try{for await(let M of Vr({cwd:e,partitions:C,promptFor:ci,concurrency:A,profileName:s,allowProdWrites:Ht.current,model:R.model,signal:q.signal}))if(M.type==="partition_status")M.status==="running"?ie(T=>T&&{...T,active:[...T.active,M.label],rows:Fe(T.rows,M.label,"active"),lastAt:Date.now()}):ie(T=>T&&{...T,active:T.active.filter(V=>V!==M.label),done:T.done+1,rows:Fe(T.rows,M.label,M.status==="done"?"done":"failed"),lastAt:Date.now()});else if(M.type==="partition_event")ie(T=>{if(!T)return T;let V={...T,lastAt:Date.now()};return M.event.type==="tool"?V.tools=T.tools+1:M.event.type==="text"&&(V.chars=T.chars+M.event.delta.length),V});else if(M.type==="run_done"){Jt(oe=>oe+M.totalCostUsd),Qt(oe=>oe+M.results.reduce((nt,on)=>nt+on.outputTokens,0));let T=M.aborted?"Stopped. ":"",V=t.kind==="api"?"api":"subscription";d({kind:"note",tone:M.aborted?"warn":M.ok?"ok":"warn",text:T+di(M.results,C,V).join(`
414
- `)})}}catch(M){d({kind:"note",tone:"error",text:`Convert run failed: ${M.message}`})}finally{we.current=null,ie(null),E(!1),H(M=>M+1)}return}case"write":{if(!ae(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let h=fk(e);if(h.length===0){d({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:y,path:w,preview:g,concurrency:C,rewrite:A}=fi(f),{docsDir:F,targets:R,reason:q,rewriting:M}=$i(e,h,{scope:y,path:w,rewrite:A});if(R.length===0){d({kind:"note",tone:"warn",text:q??"Nothing to write."});return}M&&d({kind:"note",tone:"warn",text:`--rewrite: regenerating ${R.length} already-written article${R.length===1?"":"s"} (overwrites them; git has your baseline).`});let T=Aa(R),V=hi(C),oe=Gr(e,"standard"),nt=!!w;if(g&&!nt){let ee=lp({files:gi(e,h,R),op:"write",model:oe.model}),ce=y?`Scope: ${y} (${R.length} pending)
412
+ Model: ${C.model}${C.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;d({kind:"note",tone:"info",text:T+ui(R,M,A).join(`
413
+ `)+V}),Z(F);return}xt.current=Date.now(),Wt(0),E(!0);let q=new AbortController;we.current=q,ie({verb:"Converting",total:R.length,done:0,active:[],rows:oo(R),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Converting ${g.length} articles across ${R.length} partitions (\u2264${A} agents at once) on ${C.model}\u2026 (esc to stop)`});try{for await(let M of Vr({cwd:e,partitions:R,promptFor:ci,concurrency:A,profileName:s,allowProdWrites:Ht.current,model:C.model,signal:q.signal}))if(M.type==="partition_status")M.status==="running"?ie(T=>T&&{...T,active:[...T.active,M.label],rows:We(T.rows,M.label,"active"),lastAt:Date.now()}):ie(T=>T&&{...T,active:T.active.filter(V=>V!==M.label),done:T.done+1,rows:We(T.rows,M.label,M.status==="done"?"done":"failed"),lastAt:Date.now()});else if(M.type==="partition_event")ie(T=>{if(!T)return T;let V={...T,lastAt:Date.now()};return M.event.type==="tool"?V.tools=T.tools+1:M.event.type==="text"&&(V.chars=T.chars+M.event.delta.length),V});else if(M.type==="run_done"){Jt(oe=>oe+M.totalCostUsd),Qt(oe=>oe+M.results.reduce((nt,on)=>nt+on.outputTokens,0));let T=M.aborted?"Stopped. ":"",V=t.kind==="api"?"api":"subscription";d({kind:"note",tone:M.aborted?"warn":M.ok?"ok":"warn",text:T+di(M.results,R,V).join(`
414
+ `)})}}catch(M){d({kind:"note",tone:"error",text:`Convert run failed: ${M.message}`})}finally{we.current=null,ie(null),E(!1),H(M=>M+1)}return}case"write":{if(!ae(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let h=fk(e);if(h.length===0){d({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:y,path:w,preview:g,concurrency:R,rewrite:A}=fi(f),{docsDir:F,targets:C,reason:q,rewriting:M}=$i(e,h,{scope:y,path:w,rewrite:A});if(C.length===0){d({kind:"note",tone:"warn",text:q??"Nothing to write."});return}M&&d({kind:"note",tone:"warn",text:`--rewrite: regenerating ${C.length} already-written article${C.length===1?"":"s"} (overwrites them; git has your baseline).`});let T=Aa(C),V=hi(R),oe=Gr(e,"standard"),nt=!!w;if(g&&!nt){let ee=lp({files:gi(e,h,C),op:"write",model:oe.model}),ce=y?`Scope: ${y} (${C.length} pending)
415
415
  `:"",ke=`
416
416
  Model: ${oe.model}${oe.forced?" (forced)":" \u2014 authoring; /model to override"}`;d({kind:"note",tone:"info",text:ce+wi(T,ee,V).join(`
417
- `)+ke}),Z(`/write${y?` --scope ${y}`:""}`);return}xt.current=Date.now(),Wt(0),E(!0);let on=new AbortController;we.current=on,ie({verb:"Writing",total:T.length,done:0,active:[],rows:oo(T),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Writing ${R.length} article${R.length===1?"":"s"} across ${T.length} partition${T.length===1?"":"s"} (\u2264${V} agents at once) on ${oe.model}${oe.forced?" (forced)":""}\u2026 (esc to stop)`});let Re=new Set;try{for await(let ee of Vr({cwd:e,partitions:T,promptFor:ce=>yi(ce,F,{rewrite:M||nt}),concurrency:V,profileName:s,allowProdWrites:Ht.current,model:oe.model,signal:on.signal}))if(ee.type==="partition_status")ee.status==="running"?ie(ce=>ce&&{...ce,active:[...ce.active,ee.label],rows:Fe(ce.rows,ee.label,"active"),lastAt:Date.now()}):ie(ce=>ce&&{...ce,active:ce.active.filter(ke=>ke!==ee.label),done:ce.done+1,rows:Fe(ce.rows,ee.label,ee.status==="done"?"done":"failed"),lastAt:Date.now()});else if(ee.type==="partition_event"){let ce=null;if(ee.event.type==="tool"){let ke=Fd(ee.event.name,ee.event.input,T[ee.index]?.paths??[]);ke&&!Re.has(ke)&&(Re.add(ke),ce=ee.label)}ie(ke=>{if(!ke)return ke;let ze={...ke,lastAt:Date.now()};return ee.event.type==="tool"?ze.tools=ke.tools+1:ee.event.type==="text"&&(ze.chars=ke.chars+ee.event.delta.length),ce&&(ze.rows=Wd(ze.rows,ce)),ze})}else if(ee.type==="run_done"){Jt(ut=>ut+ee.totalCostUsd),Qt(ut=>ut+ee.results.reduce((ot,_p)=>ot+_p.outputTokens,0));let ce=ee.aborted?"Stopped. ":"",ke=t.kind==="api"?"api":"subscription";if(d({kind:"note",tone:ee.aborted?"warn":ee.ok?"ok":"warn",text:ce+ki(ee.results,T,ke).join(`
418
- `)}),!ee.aborted&&ee.ok)try{let ut=(Re.size>0?[...Re]:R).map(ot=>`${F}/${ot}`);Ea(e,ut,{writtenCap:ja})}catch{}let ze=ee.aborted?null:bi(e,F,R);if(ze&&d({kind:"note",tone:"warn",text:ze}),!ee.aborted&&ee.ok){let ut=y??w??"",ot=ut?` ${ut}`:"";ve(ze?`Written \u2014 but the checker flagged issues. I\u2019d fix those first with /check${ot} --fix, then /review${ot} --fix for editorial quality, then /publish --all (add /screenshot author --all first if you want images).`:`Written. I\u2019d run /review${ot} --fix next \u2014 editorial review that applies its fixes \u2014 then /publish --all pushes the drafts up (add /screenshot author --all first if you want images).`,{kind:"cmd",cmd:ze?`/check${ot} --fix`:`/review${ot} --fix`,reason:""})}}}catch(ee){d({kind:"note",tone:"error",text:`Write run failed: ${ee.message}`})}finally{we.current=null,ie(null),E(!1),H(ee=>ee+1)}return}case"draft":{if(!ae(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:h,looseDocs:y}=xi(e);if(h.length===0&&y===0){d({kind:"note",tone:"info",text:Ci});return}let w=f.join(" ").trim();if(!w&&h.length>1){d({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
417
+ `)+ke}),Z(`/write${y?` --scope ${y}`:""}`);return}xt.current=Date.now(),Wt(0),E(!0);let on=new AbortController;we.current=on,ie({verb:"Writing",total:T.length,done:0,active:[],rows:oo(T),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Writing ${C.length} article${C.length===1?"":"s"} across ${T.length} partition${T.length===1?"":"s"} (\u2264${V} agents at once) on ${oe.model}${oe.forced?" (forced)":""}\u2026 (esc to stop)`});let Re=new Set;try{for await(let ee of Vr({cwd:e,partitions:T,promptFor:ce=>yi(ce,F,{rewrite:M||nt}),concurrency:V,profileName:s,allowProdWrites:Ht.current,model:oe.model,signal:on.signal}))if(ee.type==="partition_status")ee.status==="running"?ie(ce=>ce&&{...ce,active:[...ce.active,ee.label],rows:We(ce.rows,ee.label,"active"),lastAt:Date.now()}):ie(ce=>ce&&{...ce,active:ce.active.filter(ke=>ke!==ee.label),done:ce.done+1,rows:We(ce.rows,ee.label,ee.status==="done"?"done":"failed"),lastAt:Date.now()});else if(ee.type==="partition_event"){let ce=null;if(ee.event.type==="tool"){let ke=Fd(ee.event.name,ee.event.input,T[ee.index]?.paths??[]);ke&&!Re.has(ke)&&(Re.add(ke),ce=ee.label)}ie(ke=>{if(!ke)return ke;let Ye={...ke,lastAt:Date.now()};return ee.event.type==="tool"?Ye.tools=ke.tools+1:ee.event.type==="text"&&(Ye.chars=ke.chars+ee.event.delta.length),ce&&(Ye.rows=Wd(Ye.rows,ce)),Ye})}else if(ee.type==="run_done"){Jt(ut=>ut+ee.totalCostUsd),Qt(ut=>ut+ee.results.reduce((ot,_p)=>ot+_p.outputTokens,0));let ce=ee.aborted?"Stopped. ":"",ke=t.kind==="api"?"api":"subscription";if(d({kind:"note",tone:ee.aborted?"warn":ee.ok?"ok":"warn",text:ce+ki(ee.results,T,ke).join(`
418
+ `)}),!ee.aborted&&ee.ok)try{let ut=(Re.size>0?[...Re]:C).map(ot=>`${F}/${ot}`);Ea(e,ut,{writtenCap:ja})}catch{}let Ye=ee.aborted?null:bi(e,F,C);if(Ye&&d({kind:"note",tone:"warn",text:Ye}),!ee.aborted&&ee.ok){let ut=y??w??"",ot=ut?` ${ut}`:"";ve(Ye?`Written \u2014 but the checker flagged issues. I\u2019d fix those first with /check${ot} --fix, then /review${ot} --fix for editorial quality, then /publish --all (add /screenshot author --all first if you want images).`:`Written. I\u2019d run /review${ot} --fix next \u2014 editorial review that applies its fixes \u2014 then /publish --all pushes the drafts up (add /screenshot author --all first if you want images).`,{kind:"cmd",cmd:Ye?`/check${ot} --fix`:`/review${ot} --fix`,reason:""})}}}catch(ee){d({kind:"note",tone:"error",text:`Write run failed: ${ee.message}`})}finally{we.current=null,ie(null),E(!1),H(ee=>ee+1)}return}case"draft":{if(!ae(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:h,looseDocs:y}=xi(e);if(h.length===0&&y===0){d({kind:"note",tone:"info",text:Ci});return}let w=f.join(" ").trim();if(!w&&h.length>1){d({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
419
419
  ${h.map(A=>` \u2022 ${A.name} (${A.docCount} doc${A.docCount===1?"":"s"})`).join(`
420
- `)}`}),He(h.map(A=>`/draft ${A.name}`));return}let g="",C;if(w){let A=vi(h,w);A?g=A:C=w}else g=h[0]?.name??"";await re(mr(g,C),{display:w?`/draft ${w}`:"/draft",quietUser:!0});return}case"pull":{if(!ko(c.trim()))return;let h=f.find(y=>y.startsWith("--"));try{if(h==="--status"){d({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let g=Date.now(),C=await Da({cwd:e,profileName:s});d({kind:"note",tone:"info",text:pr(C,Date.now()-g).join(`
421
- `)});return}if(h==="--baseline"){let g=f.find(R=>!R.startsWith("--")),C=g?g.replace(/\\/g,"/"):void 0;d({kind:"note",tone:"info",text:C?`Setting the sync baseline for ${C}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let A=await ik({cwd:e,profileName:s,relPaths:C?[C]:void 0}),F=C?{rebaselined:[],skipped:[]}:await ak({cwd:e,profileName:s});if(A.baselined.length===0&&A.skipped.length===0&&F.rebaselined.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}A.baselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Baselined ${A.baselined.length} article${A.baselined.length===1?"":"s"} \u2014 they now read in-sync until either side changes.`}),F.rebaselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${F.rebaselined.length} article${F.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),A.skipped.length>0&&d({kind:"note",tone:"warn",text:`${A.skipped.length} skipped:
422
- ${A.skipped.map(R=>` - ${R.path} (${R.reason})`).join(`
423
- `)}`}),H(R=>R+1);return}if(h==="--compare"){d({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let g=await sk({cwd:e,profileName:s}),C=g.onlyInLegacy.length===0&&g.onlyInManifest.length===0&&g.mappedMissingFromManifest.length===0,A=[`Legacy listing: ${g.legacyCount} \xB7 Manifest: ${g.manifestCount} \xB7 in both: ${g.inBoth}`];C?A.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(g.mappedMissingFromManifest.length&&A.push(`\u2717 ${g.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${g.mappedMissingFromManifest.slice(0,5).join(", ")}`),g.onlyInLegacy.length&&A.push(`\u26A0 ${g.onlyInLegacy.length} only in the legacy listing: ${g.onlyInLegacy.slice(0,5).join(", ")}`),g.onlyInManifest.length&&A.push(`\u26A0 ${g.onlyInManifest.length} only in the manifest: ${g.onlyInManifest.slice(0,5).join(", ")}`),A.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),d({kind:"note",tone:C?"ok":"warn",text:A.join(`
424
- `)});return}if(h){d({kind:"note",tone:"error",text:`Unknown option: ${h} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let y=f[0];if(y){let g=await ap({cwd:e,profileName:s,relPath:y.replace(/\\/g,"/")});pe.current=[{plan:g,mode:g.overwritesLocalChanges?"conflict":"pull"}],Vt.current=[],tn();return}d({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let w=await oi({cwd:e,profileName:s});for(let g of ri(w))d({kind:"note",tone:g.tone,text:g.text});H(g=>g+1)}catch(y){d({kind:"note",tone:"error",text:`Pull failed: ${y.message}`})}return}case"scope":{if(!ae(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let h=lk(e);if(h.length===0){d({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.'});return}Xt({cursor:0,rows:h.map(y=>({...y,checked:y.recommended}))});return}case"audit":{if(f[0]==="--auto"){let y=ae(e);if(!y){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let w=f[1]!=="off";op({...y,autoAudit:w},e),d({kind:"note",tone:"ok",text:w?"\u2713 Auto-audit ON \u2014 when you launch with code changes since the last audit, I\u2019ll run /audit automatically. (/audit --auto off to disable.)":"\u2713 Auto-audit OFF \u2014 I\u2019ll just nudge you to run /audit when code changed."});return}let h=await Yn();h.kind==="forward-to-agent"&&h.prompt&&await re(h.prompt,{display:h.display,quietUser:!0});return}case"check":{let h=f.find(g=>!g.startsWith("--")),y=h?` ${h}`:"",w=ip({cwd:e,scope:h});if(f.includes("--fix")){if(w.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing to fix \u2014 the docs are already clean."});return}d({kind:"note",tone:"info",text:`Fixing ${w.length} doc issue${w.length===1?"":"s"}\u2026`});let g=dp(e,h);await re(sa(w),{display:`/check${y} --fix`,quietUser:!0});try{Ea(e,g,{reviewedCap:ja})}catch{}let C=ip({cwd:e,scope:h});d({kind:"note",tone:C.length===0?"ok":"warn",text:C.length===0?"\u2713 Doc-checker: all issues resolved.":Rr(C).join(`
425
- `)}),ve(C.length===0?`Deterministic issues fixed. Next: /review${y} --fix for editorial quality (style, grammar, structure), then /publish --all.`:`Some issues remain \u2014 /review${y} --fix runs the editorial review + fixes, then /publish --all.`,{kind:"cmd",cmd:`/review${y} --fix`,reason:""});return}d({kind:"note",tone:w.length===0?"ok":"warn",text:Rr(w).join(`
420
+ `)}`}),qe(h.map(A=>`/draft ${A.name}`));return}let g="",R;if(w){let A=vi(h,w);A?g=A:R=w}else g=h[0]?.name??"";await re(mr(g,R),{display:w?`/draft ${w}`:"/draft",quietUser:!0});return}case"pull":{if(!ko(c.trim()))return;let h=f.find(y=>y.startsWith("--"));try{if(h==="--status"){d({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let g=Date.now(),R=await Da({cwd:e,profileName:s});d({kind:"note",tone:"info",text:pr(R,Date.now()-g).join(`
421
+ `)});return}if(h==="--baseline"){let g=f.find(C=>!C.startsWith("--")),R=g?g.replace(/\\/g,"/"):void 0;d({kind:"note",tone:"info",text:R?`Setting the sync baseline for ${R}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let A=await ik({cwd:e,profileName:s,relPaths:R?[R]:void 0}),F=R?{rebaselined:[],skipped:[]}:await ak({cwd:e,profileName:s});if(A.baselined.length===0&&A.skipped.length===0&&F.rebaselined.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}A.baselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Baselined ${A.baselined.length} article${A.baselined.length===1?"":"s"} \u2014 they now read in-sync until either side changes.`}),F.rebaselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${F.rebaselined.length} article${F.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),A.skipped.length>0&&d({kind:"note",tone:"warn",text:`${A.skipped.length} skipped:
422
+ ${A.skipped.map(C=>` - ${C.path} (${C.reason})`).join(`
423
+ `)}`}),H(C=>C+1);return}if(h==="--compare"){d({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let g=await sk({cwd:e,profileName:s}),R=g.onlyInLegacy.length===0&&g.onlyInManifest.length===0&&g.mappedMissingFromManifest.length===0,A=[`Legacy listing: ${g.legacyCount} \xB7 Manifest: ${g.manifestCount} \xB7 in both: ${g.inBoth}`];R?A.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(g.mappedMissingFromManifest.length&&A.push(`\u2717 ${g.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${g.mappedMissingFromManifest.slice(0,5).join(", ")}`),g.onlyInLegacy.length&&A.push(`\u26A0 ${g.onlyInLegacy.length} only in the legacy listing: ${g.onlyInLegacy.slice(0,5).join(", ")}`),g.onlyInManifest.length&&A.push(`\u26A0 ${g.onlyInManifest.length} only in the manifest: ${g.onlyInManifest.slice(0,5).join(", ")}`),A.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),d({kind:"note",tone:R?"ok":"warn",text:A.join(`
424
+ `)});return}if(h){d({kind:"note",tone:"error",text:`Unknown option: ${h} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let y=f[0];if(y){let g=await ap({cwd:e,profileName:s,relPath:y.replace(/\\/g,"/")});pe.current=[{plan:g,mode:g.overwritesLocalChanges?"conflict":"pull"}],Vt.current=[],tn();return}d({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let w=await oi({cwd:e,profileName:s});for(let g of ri(w))d({kind:"note",tone:g.tone,text:g.text});H(g=>g+1)}catch(y){d({kind:"note",tone:"error",text:`Pull failed: ${y.message}`})}return}case"scope":{if(!ae(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let h=lk(e);if(h.length===0){d({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.'});return}Xt({cursor:0,rows:h.map(y=>({...y,checked:y.recommended}))});return}case"audit":{if(f[0]==="--auto"){let y=ae(e);if(!y){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let w=f[1]!=="off";op({...y,autoAudit:w},e),d({kind:"note",tone:"ok",text:w?"\u2713 Auto-audit ON \u2014 when you launch with code changes since the last audit, I\u2019ll run /audit automatically. (/audit --auto off to disable.)":"\u2713 Auto-audit OFF \u2014 I\u2019ll just nudge you to run /audit when code changed."});return}let h=await Yn();h.kind==="forward-to-agent"&&h.prompt&&await re(h.prompt,{display:h.display,quietUser:!0});return}case"check":{let h=f.find(g=>!g.startsWith("--")),y=h?` ${h}`:"",w=ip({cwd:e,scope:h});if(f.includes("--fix")){if(w.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing to fix \u2014 the docs are already clean."});return}d({kind:"note",tone:"info",text:`Fixing ${w.length} doc issue${w.length===1?"":"s"}\u2026`});let g=dp(e,h);await re(sa(w),{display:`/check${y} --fix`,quietUser:!0});try{Ea(e,g,{reviewedCap:ja})}catch{}let R=ip({cwd:e,scope:h});d({kind:"note",tone:R.length===0?"ok":"warn",text:R.length===0?"\u2713 Doc-checker: all issues resolved.":Rr(R).join(`
425
+ `)}),ve(R.length===0?`Deterministic issues fixed. Next: /review${y} --fix for editorial quality (style, grammar, structure), then /publish --all.`:`Some issues remain \u2014 /review${y} --fix runs the editorial review + fixes, then /publish --all.`,{kind:"cmd",cmd:`/review${y} --fix`,reason:""});return}d({kind:"note",tone:w.length===0?"ok":"warn",text:Rr(w).join(`
426
426
  `)}),w.length>0&&ve(`Found ${w.length} doc issue${w.length===1?"":"s"} above. /check${y} --fix has the agent fix them in place (or /review${y} --fix for the full editorial pass; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/check${y} --fix`,reason:""});return}case"structure":{let h=Zn(e,s);if(h.length===0){d({kind:"note",tone:"info",text:"No documentation structure yet \u2014 run /init and author some articles first."});return}d({kind:"note",tone:"info",text:["Documentation order (categories \u2192 articles):","",...h].join(`
427
- `)});return}case"reorder":{let h=aa(e,f);if(!h){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await re(h.prompt,{display:h.display,quietUser:!0}),ve("Reordered locally \u2014 /publish --all syncs the new order to Document360.",{kind:"cmd",cmd:"/publish --all",reason:""});return}case"review":{let h=ia(e,f);if(!h){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let y=f.includes("--fix"),w=f.find(C=>!C.startsWith("--")),g=y?dp(e,w):[];if(await re(h.prompt,{display:h.display,quietUser:!0}),y)try{Ea(e,g,{reviewedCap:ja})}catch{}if(y)ve("\u2713 Editor applied its fixes \u2014 your docs are corrected. /publish --all pushes them up (or /check for an instant no-token re-scan first).",{kind:"cmd",cmd:"/publish --all",reason:""});else{let C=f.filter(A=>A!=="--fix").join(" ");ve(`The review listed issues above. /review${C?` ${C}`:""} --fix lets the editor apply them all (or /check --fix for just the deterministic ones; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/review${C?` ${C}`:""} --fix`,reason:""})}return}case"capture-setup":{await Y();return}case"devhints":{if(!ae(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:cn(ln(e)).join(`
428
- `)}),Zt(Ot()),An.current=Me(e).status==="current",en.current=rt(e);return}case"discover":{if(!ae(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await re(Js(),{display:"/discover",quietUser:!0});return}case"inbox":{if(!ae(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(Yi(e)===0){d({kind:"note",tone:"info",text:"Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)"});return}await re(zi(),{display:"/inbox",quietUser:!0});return}case"feedback":{let h=up(e),y="";try{y=kn(h)?Hr(h,"utf8"):""}catch{y=""}if(!/^## /m.test(y)){d({kind:"note",tone:"info",text:"No open d360-writer feedback to copy \u2014 nothing logged in .d360-writer/tool-feedback.md yet."});return}let w=await $a(y.trim());d({kind:"note",tone:w?"ok":"warn",text:w?"\u2713 Copied the d360-writer feedback to your clipboard \u2014 send it to the team (Teams / Slack / email).":`Couldn\u2019t reach your clipboard \u2014 open ${h} and copy it manually.`}),w&&is(null);return}case"document":{if(!ae(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:h,what:y}=Si(f);if(!y&&Ri(e)===0){d({kind:"note",tone:"info",text:Ti});return}let w=`/document${y?` ${y}`:""}${h?" --publish":""}`;await re(Pi(y,h),{display:w,quietUser:!0});return}case"catch-up":{if(!ae(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!ko(c.trim()))return;let{publish:h}=Xi(f);d({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let y=await Ji({cwd:e,profileName:s});for(let g of Zi(y))d({kind:"note",tone:g.startsWith("\u2713")?"ok":g.startsWith("\u2139")?"info":"warn",text:g});let w=Jn(Qn(e));d({kind:"note",tone:"info",text:w?`Catching up on ${w}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"}),await re(Qi({publish:h}),{display:`/catch-up${h?" --publish":""}`,quietUser:!0});return}case"update":{rs.current=!0,d({kind:"note",tone:"info",text:"Updating the d360-writer toolchain\u2026 (don\u2019t close this window)"}),co(!0);let h=await vr().finally(()=>co(!1));h.ok?(d({kind:"note",tone:"ok",text:`\u2713 Updated ${h.packages.join(" + ")} \u2014 run /exit, then relaunch to apply.`}),Z("/exit"),Wa("")):d({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${xr}`});return}case"screenshot":{let h=Hn(f);if(h.mode==="capture"){await P(h.rest);return}if(h.mode==="checklist"){await Y();return}if(h.mode==="list"){if(!ae(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let g=ae(e)?.docsDir??Oa,C=Vs(e,h.scope),A=We(e,C);if(h.picker){if(A.length===0){d({kind:"note",tone:"info",text:"No screenshot placeholders found in the docs."});return}let q=Ec(A);if(q.length===0){d({kind:"note",tone:"info",text:rr(A,{docsDir:g}).join(`
429
- `)}),ve(`\u2713 All ${A.length} screenshots are captured. /publish puts them in the articles; /screenshot capture re-captures.`,{kind:"cmd",cmd:"/publish",reason:""});return}Pt({cursor:0,rows:q,title:"Screenshots \u2014 pick what to author or capture:"});return}d({kind:"note",tone:"info",text:rr(A,{scope:C,detail:h.detail,docsDir:g}).join(`
430
- `)});let F=A.filter(q=>q.state==="placeholder").length,R=A.filter(q=>q.state==="spec").length;if(F>0){let q=C?`/screenshot author ${C}`:"/screenshot author --all";ve(`${F} of ${A.length} still need${F===1?"s":""} a spec \u2014 /screenshot author <id> authors one, ${q} authors them all in parallel.`,{kind:"cmd",cmd:q,reason:""})}else if(R>0){let q=C?`/screenshot capture ${C}`:"/screenshot capture";ve(`${R} spec${R===1?"":"s"} ready to capture \u2014 ${q} takes ${R===1?"it":"them"} (a real browser drives your app).`,{kind:"cmd",cmd:q,reason:""})}return}if(h.mode==="single"){await nl(h.id);return}if(!ae(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let y=h.mode==="scope"?h.scope:void 0,w=pk(e,{scope:y}).map(g=>g.id);if(w.length===0){d({kind:"note",tone:"info",text:y?`No screenshot placeholders under ${y}.`:"No screenshot placeholders found in the docs."});return}await tl(w,{setup:h.setup,runLine:h.mode==="scope"?[`/screenshot author ${h.scope}`,`/screenshot ${h.scope}`]:["/screenshot author --all","/screenshot --all"]});return}case"capture":{await P(f);return}case"reset":{let h=na(e);if(h.length===0){d({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}ho.current={repoName:ro(e),targets:h,hadDevhints:kn(cp(e))},d({kind:"note",tone:"warn",text:ra(e,h).join(`
431
- `)}),xe(ro(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${i} \u2014 type /help.`})}},[e,r,s,tn,fs,d,Ee,re,It,us,ol]),Eo=Q(c=>{let l=(c??$).trim();if(x(""),uo(null),Ft(0),l.startsWith("/")&&(io.current=!1,vn.current=!1,Ve(),Cn(null),He(f=>Hd(f,l))),!l||(Ua(!1),sl(l))||rl(l))return;Jr.current.push(l);let i=zd(l,Fa.current);if(l.startsWith("/"))d({kind:"user",text:l}),qe(!0),jn(i).finally(()=>qe(!1));else if(xk(i)){d({kind:"user",text:l});let f=vk(i);if(!f)re(i,{display:l,quietUser:!0});else{try{Ck(e,{title:f,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}re(`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${f}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${f}" and the article path(s) you wrote.`,{display:l,quietUser:!0})}}else{let f=fd(e,i);re(f??i,{display:l})}},[$,sl,rl,jn,re]),il=Q(c=>{if(c.length>1){if(c.includes("\x1B"))return;let l=Vd(c);if(Gd(l)){let i=Yd(++Ap.current,l);Fa.current.set(i,l),j(i)}else j(l);return}j(c)},[j]),nn=Math.max(10,Ge-6),al=Sa(()=>Br(b.text,nn),[b.text,nn]),ms=Q(c=>k(l=>({...l,pos:Math.max(0,Math.min(l.text.length,l.pos+c))})),[]),jo=Q(c=>k(l=>({...l,pos:Xd(Br(l.text,nn),l.pos,c)})),[nn]),Nn=Q(c=>k(l=>({...l,pos:Qd(Br(l.text,nn),l.pos,c)})),[nn]),Ip=["\x1B[H","\x1B[1~","\x1BOH"],Op=["\x1B[F","\x1B[4~","\x1BOF"],ll=Q((c,l)=>l.leftArrow?(ms(-1),!0):l.rightArrow?(ms(1),!0):c&&Ip.includes(c)?(Nn("start"),!0):c&&Op.includes(c)?(Nn("end"),!0):l.ctrl&&c==="a"?(Nn("start"),!0):l.ctrl&&c==="e"?(Nn("end"),!0):!1,[ms,Nn]);return Lw((c,l)=>{if(l.ctrl&&c==="c"){Oe.current?.close(),r();return}if(!U){if(D){if(l.escape){if(we.current){if(!we.current.signal.aborted){let i=(fo?.verb??"work").toLowerCase(),f=fo?.unit??"article";d({kind:"note",tone:"warn",text:`\u238B Stopping the ${i} run (finishing in-flight ${f}s)\u2026`}),we.current.abort()}return}Rn.current||(Rn.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),Oe.current?.interrupt());return}if(l.return){let i=$.trim();if(!i)return;At.current.push(i),es([...At.current]),x("");return}if(ll(c,l))return;if(l.upArrow){jo(-1);return}if(l.downArrow){jo(1);return}if(l.backspace||l.delete){v();return}c&&!l.ctrl&&!l.meta&&il(c);return}if(Ct){if(l.upArrow){Rt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Rt(i=>i&&{...i,cursor:Math.min(Ke.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ke.length){Rt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Ke[Ct.cursor];Rt(null);let{lines:f,changed:P,effective:Y}=Kn(e,i.value??"default");for(let h of f)d({kind:"note",tone:h.startsWith("\u26A0")?"warn":h.startsWith("\u2713")?"ok":"info",text:h});P&&(Ka(h=>h+1),Oe.current?.setModel(Y));return}if(c==="s"){let i=Ke[Ct.cursor];Rt(null),Oe.current?.setModel(i.value??void 0),d({kind:"note",tone:"ok",text:`\u2713 Using ${i.label} for this session only (your saved default is unchanged).`});return}if(l.escape){Rt(null);return}return}if(Ze){if(l.upArrow){Gt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Gt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ze.rows.length){Gt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return||c==="s"){let i=Ze.rows[Ze.cursor];Gt(null),ps(i.name,l.return===!0);return}if(l.escape){Gt(null);return}return}if(yo){if(l.escape){Tn(null);return}if(l.leftArrow||l.tab&&l.shift){Tn(i=>i&&{tab:(i.tab-1+Le.length)%Le.length});return}if(l.rightArrow||l.tab){Tn(i=>i&&{tab:(i.tab+1)%Le.length});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Le.length){Tn({tab:Number(c)-1});return}return}if(et){if(l.upArrow){Yt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Yt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=et.rows.length){Yt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=et.rows[et.cursor].name;if(Yt(null),!Cs(e,i).created){d({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}d({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${i}").`});let P=!1;try{let Y=Ut(i);P=!!Y&&!($t(Y)&&!Y.refreshToken)}catch{P=!1}d({kind:"note",tone:"info",text:P?`Next: sign in to ${i} and pick your project \u2014 you're already signed in here, so it'll be quick.`:`Next: sign in to Document360 (${i}) and pick your project.`}),Z("/login"),H(Y=>Y+1);return}if(l.escape){Yt(null);return}return}if($e){if(l.upArrow){zt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){zt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=$e.rows.length){zt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=$e.rows[$e.cursor],{profile:f,projectId:P}=$e;zt(null),To(f,P,i);return}if(l.escape){zt(null);return}return}if(Te){if(l.upArrow){St(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){St(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Te.rows.length){St(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Te.rows[Te.cursor],{profile:f}=Te;St(null),Ao(f,i);return}if(l.escape){St(null);return}return}if(Ce){if(l.upArrow){Xt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Xt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c===" "){Xt(i=>i&&{...i,rows:i.rows.map((f,P)=>P===i.cursor?{...f,checked:!f.checked}:f)});return}if(l.return){let i=Ce.rows.filter(f=>f.checked).map(f=>f.path);if(Xt(null),i.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}Zs(e,i),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${i.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let f of i)d({kind:"note",tone:"info",text:` ${f}`});d({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(l.escape){Xt(null);return}return}if(tt){if(l.upArrow){Tt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Tt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=tt.rows.length){Tt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=tt.rows[tt.cursor],f=tt.run;Tt(null),f(i.token);return}if(l.escape){Tt(null);return}return}if(at){if(l.upArrow){Kt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Kt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=at.rows.length){Kt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=at.rows[at.cursor];Kt(null),i.conflict?fs(i.paths[0]):i.kind==="article"?us(i.paths[0]):It(i.paths);return}if(l.escape){Kt(null);return}return}if(lt){if(l.upArrow){Pt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Pt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=lt.rows.length){Pt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=lt.rows[lt.cursor];Pt(null),i.action==="capture"?Po(i.ids,{runLine:i.kind==="all"?["/screenshot capture --all","/capture --all"]:void 0}):i.kind==="shot"?nl(i.ids[0]):tl(i.ids,{setup:!0,runLine:i.kind==="all"?["/screenshot author --all","/screenshot --all"]:void 0});return}if(l.escape){Pt(null);return}return}if(De){if(l.escape){Dt(null);return}if(l.upArrow){Dt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Dt(i=>i&&{...i,cursor:Math.min(Math.max(0,Co.length-1),i.cursor+1)});return}if(l.return){let i=Co[De.cursor];if(i){Dt(null);try{d({kind:"preview",name:ro(i),text:wp(Hr(Pa(e,i),"utf8"))})}catch(f){d({kind:"note",tone:"error",text:`Could not read ${i}: ${f.message}`})}}return}if(l.backspace||l.delete){Dt(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(c&&!l.ctrl&&!l.meta&&c.length===1){Dt(i=>i&&{...i,query:i.query+c,cursor:0});return}return}if(Ae){if(l.escape){Et(null);return}if(l.upArrow){Et(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Et(i=>i&&{...i,cursor:Math.min(Math.max(0,Ro.length-1),i.cursor+1)});return}if(l.return){let i=Ro[Ae.cursor];if(i){Et(null),Ee(i.uuid),Je.current={uuid:i.uuid,firstPrompt:i.firstPrompt,titleFired:!0},vt(i.name),Ta(i.uuid),qt.current=[];let f=va(e,i.uuid);for(let P of f)d(P);d({kind:"note",tone:"ok",text:f.length?`Resumed "${i.name}" \u2014 restored ${f.length} message(s); continue where you left off.`:`Resumed "${i.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(l.backspace||l.delete){Et(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(c&&!l.ctrl&&!l.meta&&c.length===1){Et(i=>i&&{...i,query:i.query+c,cursor:0});return}return}if(l.tab&&!$&&fe){x(fe),Ve();return}if(!$&&be.length>0&&!Kr&&c&&/^[1-9]$/.test(c)){let i=be[Number(c)-1];if(i){x(Mt(i));return}}if(!$&&(bo||Dn)&&c==="c"&&!l.ctrl&&!l.meta&&!l.return&&!l.tab){let i=bo!=null;$a(bo??Dn).then(P=>{d({kind:"note",tone:P?"ok":"warn",text:P?i?"\u2713 Copied the feedback to your clipboard \u2014 send it to the d360-writer team (Teams / Slack / email).":"\u2713 Copied the prompt to your clipboard \u2014 paste it into your repo's coding agent.":i?"Couldn't reach your clipboard \u2014 select the feedback above and copy it manually.":"Couldn't reach your clipboard \u2014 select the prompt above and copy it manually."}),P&&i&&is(null),P&&!i&&Qa(!0)});return}if(!ll(c,l)){if(Za){if(l.upArrow){Ft(i=>Math.max(0,i-1));return}if(l.downArrow){Ft(i=>Math.min(Ye.length-1,i+1));return}if(l.tab){x("/"+(Ye[Qr]?.name??"")+" "),Ft(0);return}if(l.return){let i=Ye[Qr];if(i){let f=$.trim().slice(1).split(/\s+/).slice(1).join(" ");if(ec(i.usage)&&!f){x("/"+i.name+" "),Ft(0);return}Eo("/"+i.name+(f?" "+f:""));return}}}else{if(l.upArrow){if($!==""&&Bt===null){jo(-1);return}let i=Jr.current;if(!i.length)return;let f=Bt===null?i.length-1:Math.max(0,Bt-1);uo(f),x(i[f]??"");return}if(l.downArrow){if($!==""&&Bt===null){jo(1);return}let i=Jr.current;if(Bt===null)return;let f=Bt+1;f>=i.length?(uo(null),x("")):(uo(f),x(i[f]??""));return}}if(l.return){Eo();return}if(l.backspace||l.delete){v();return}if(l.escape){x(""),Ft(0),Ve(),He([]),Cn(null),io.current=!0;return}c&&!l.ctrl&&!l.meta&&il(c)}}}),Ie(()=>{if(D||U)return;let c=At.current.shift();c!==void 0&&(es([...At.current]),Eo(c))},[D,U,Eo]),J(le,{flexDirection:"column",width:Ge,children:[cs!==null&&J(le,{marginTop:1,flexDirection:"column",children:[cs.truncated&&I(N,{dimColor:!0,children:"\u2026"}),I(N,{children:cs.text})]}),D&&(fo?I(Ik,{p:fo}):I(Ek,{startTime:xt.current,chars:Dp})),!D&&Ga?I(jk,{text:Ga}):null,I(le,{borderStyle:"round",borderColor:Ja.prod?"yellow":X,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:$?al.map((c,l)=>{let i=b.text.slice(c.start,c.end),f=l===qr(al,b.pos),P=Math.min(b.pos,c.end)-c.start;return J(N,{children:[I(N,{color:X,children:l===0?"> ":" "}),f?J(so,{children:[i.slice(0,P),I(bn,{ch:i[P]??" "}),i.slice(P+1)]}):i||" "]},`${l}-${c.start}`)}):J(N,{children:[I(N,{color:X,children:"> "}),ts?I(bn,{ch:" "}):fe&&!D&&me?J(so,{children:[I(bn,{ch:me[0],dim:!0}),I(N,{color:"gray",children:me.slice(1)})]}):fe&&!D?J(so,{children:[I(bn,{ch:fe[0],dim:!0}),I(N,{color:"gray",children:fe.slice(1)}),I(N,{dimColor:!0,children:" (tab)"})]}):(as.isSetup||!Pp)&&!D?J(so,{children:[I(bn,{ch:as.text[0],dim:!0}),I(N,{color:"gray",children:as.text.slice(1)})]}):I(bn,{ch:" "})]})}),Va.length>0&&I(le,{flexDirection:"column",paddingX:1,children:Va.map((c,l)=>I(N,{color:"gray",children:`\u29D7 queued: ${c}`},`${l}-${c.slice(0,24)}`))}),yo?I(Md,{tab:yo.tab,width:Ge,version:o,engineVersion:kp}):Ct?J(le,{flexDirection:"column",paddingX:1,children:[I(N,{color:X,bold:!0,children:"Select model"}),I(N,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),Ke.map((c,l)=>J(N,{color:l===Ct.cursor?X:void 0,children:[l===Ct.cursor?"\u276F ":" ",`${l+1}. ${c.label}${l===Ct.current?" \u2714":""}`.padEnd(16),I(N,{color:"gray",children:c.desc})]},c.label)),I(N,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Ze?J(le,{flexDirection:"column",paddingX:1,children:[I(N,{color:X,bold:!0,children:"Switch connection profile"}),Ze.rows.map((c,l)=>J(N,{color:l===Ze.cursor?X:void 0,children:[l===Ze.cursor?"\u276F ":" ",`${l+1}. ${c.name}${l===Ze.current?" \u2714":""}`.padEnd(20),I(N,{color:"gray",children:`${c.env} \xB7 ${c.who??"not signed in"}`}),c.prod?I(N,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},c.name)),I(N,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):et?J(le,{flexDirection:"column",paddingX:1,children:[I(N,{color:X,bold:!0,children:"Pick your Document360 environment"}),et.rows.map((c,l)=>J(N,{color:l===et.cursor?X:void 0,children:[l===et.cursor?"\u276F ":" ",`${l+1}. ${c.name}`.padEnd(16),I(N,{color:"gray",children:c.apiUrl})]},c.name)),I(N,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):$e?J(le,{flexDirection:"column",paddingX:1,children:[I(N,{color:X,bold:!0,children:"Switch workspace"}),I(N,{dimColor:!0,children:`environment ${$e.environment} \xB7 project ${$e.projectName??`${$e.projectId.slice(0,8)}\u2026`}`}),$e.rows.map((c,l)=>J(N,{color:l===$e.cursor?X:void 0,children:[l===$e.cursor?"\u276F ":" ",`${l+1}. ${c.name}${l===$e.current?" \u2714":""}`.padEnd(30),I(N,{color:"gray",children:c.type??""})]},c.id)),I(N,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):Te?J(le,{flexDirection:"column",paddingX:1,children:[I(N,{color:X,bold:!0,children:"Choose project"}),I(N,{dimColor:!0,children:`environment ${Te.environment}`}),Te.rows.map((c,l)=>J(N,{color:l===Te.cursor?X:void 0,children:[l===Te.cursor?"\u276F ":" ",`${l+1}. ${c.name}${l===Te.current?" \u2714":""}`.padEnd(30),I(N,{color:"gray",children:c.sub??""})]},c.id)),I(N,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):Ce?(()=>{let l=Math.min(Math.max(0,Ce.cursor-Math.floor(7)),Math.max(0,Ce.rows.length-14)),i=Ce.rows.slice(l,l+14),f=Ce.rows.filter(P=>P.checked).length;return J(le,{flexDirection:"column",paddingX:1,children:[I(N,{color:X,bold:!0,children:`Which folders back the user docs? (${f} selected of ${Ce.rows.length})`}),l>0?I(N,{dimColor:!0,children:` \u2191 ${l} more`}):null,i.map((P,Y)=>{let h=l+Y;return J(N,{color:h===Ce.cursor?X:void 0,children:[h===Ce.cursor?"\u276F ":" ",P.checked?"\u25C9 ":"\u25CB ",P.path.padEnd(Math.min(48,Ge-34)),I(N,{color:"gray",children:dr(P)})]},P.path)}),l+14<Ce.rows.length?I(N,{dimColor:!0,children:` \u2193 ${Ce.rows.length-l-14} more`}):null,I(N,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():tt?J(le,{flexDirection:"column",paddingX:1,children:[I(N,{color:X,bold:!0,children:"Which category? (pick one to scope to)"}),tt.rows.map((c,l)=>{let i=l===tt.cursor,f=`${l+1}.`.padEnd(3);return J(N,{color:i?X:void 0,children:[i?"\u276F ":" ",`${f} ${c.label} (${c.count})`.padEnd(Math.min(44,Math.max(20,Ge-24))),I(N,{color:"gray",children:` ${c.token}`})]},c.token)}),I(N,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):at?J(le,{flexDirection:"column",paddingX:1,children:[I(N,{color:X,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),at.rows.map((c,l)=>{let i=l===at.cursor,f=c.indent?" ":" ",P=`${l+1}.`.padEnd(3);return J(N,{color:i?X:void 0,bold:c.kind==="category"&&!i,children:[i?"\u276F ":" ",`${f}${P} ${c.label}`.padEnd(Math.min(56,Ge-24)),c.note?I(N,{color:"gray",children:c.note}):null]},`${c.kind}:${c.paths.join(",")}`)}),I(N,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):lt?J(le,{flexDirection:"column",paddingX:1,children:[I(N,{color:X,bold:!0,children:lt.title}),(()=>{let{rows:l,cursor:i}=lt,f=Math.max(0,Math.min(i-Math.floor(12/2),l.length-12)),P=l.slice(f,f+12),Y=`${l.length}.`.length+1;return J(so,{children:[f>0?I(N,{color:"gray",children:` \u2026 ${f} more above`}):null,P.map((h,y)=>{let w=f+y,g=w===i;return J(N,{color:g?X:void 0,bold:(h.kind==="all"||h.kind==="category")&&!g,children:[g?"\u276F ":" ",`${w+1}.`.padEnd(Y)," ".repeat(h.depth),h.label,h.note?I(N,{color:"gray",children:h.note}):null]},`${h.action}:${h.kind}:${h.ids.join(",")}`)}),f+12<l.length?I(N,{color:"gray",children:` \u2026 ${l.length-f-12} more below`}):null]})})(),I(N,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter run \xB7 esc cancel"})]}):De?J(le,{flexDirection:"column",paddingX:1,children:[I(N,{color:X,bold:!0,children:`Preview article${De.query?` \u2014 filter: ${De.query}`:" (type to filter)"}`}),Co.length===0?I(N,{color:"gray",children:"no articles match"}):Co.map((c,l)=>J(N,{color:l===De.cursor?X:void 0,children:[l===De.cursor?"\u276F ":" ",c]},c)),I(N,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):Ae?J(le,{flexDirection:"column",paddingX:1,children:[I(N,{color:X,bold:!0,children:`Resume session${Ae.query?` \u2014 filter: ${Ae.query}`:" (type to filter)"}`}),Ro.length===0?I(N,{color:"gray",children:"no sessions match"}):Ro.map((c,l)=>J(N,{color:l===Ae.cursor?X:void 0,children:[l===Ae.cursor?"\u276F ":" ",c.name.slice(0,28).padEnd(30),I(N,{color:l===Ae.cursor?X:"gray",children:c.firstPrompt.slice(0,Math.max(10,Ge-40))})]},c.uuid)),I(N,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Za?J(le,{flexDirection:"column",children:[Nt>0?I(N,{dimColor:!0,children:` \u22EF ${Nt} more above`}):null,ls.map((c,l)=>{let i=Nt+l;return J(N,{color:i===vo?X:void 0,children:[i===vo?"\u276F ":" ",c.usage.padEnd(22)," ",I(N,{color:i===vo?X:"gray",children:c.name==="model"&&ns?`${c.desc} (currently ${ns})`:c.desc})]},c.name)}),Nt+ls.length<Ye.length?I(N,{dimColor:!0,children:` \u22EF ${Ye.length-Nt-ls.length} more below`}):null,I(N,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!D&&!$&&be.length>0?J(le,{flexDirection:"column",paddingX:1,children:[Ha?I(N,{color:X,children:Ha}):null,be.map((c,l)=>{let i=Mt(c),f=i.slice(0,Math.max(20,Ge-5)),P=Ge-f.length-7,Y=P>=12?(qd(c)??Jl(i)).slice(0,P):"";return J(N,{children:[I(N,{color:X,children:l+1})," ",f,Y?I(N,{dimColor:!0,children:` \u2014 ${Y}`}):null]},i)}),I(N,{dimColor:!0,children:`press 1-${be.length} to fill \xB7 esc cancel`})]}):I(le,{paddingX:1,children:J(N,{color:"gray",children:[Ja.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${ns??"model n/a"}${t.kind==="api"?za>0?` \xB7 ${Pe(za)}`:"":Ya>0?` \xB7 ${gt(Ya)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}z();import{jsx as Mk}from"react/jsx-runtime";async function $p(e=process.cwd(),t="auto",n,o="0.0.0"){let r=Lk(t);r.kind==="none"&&(console.error(""),console.error(S("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${W("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${W("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=_k(Mk(bp,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
427
+ `)});return}case"reorder":{let h=aa(e,f);if(!h){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await re(h.prompt,{display:h.display,quietUser:!0}),ve("Reordered locally \u2014 /publish --all syncs the new order to Document360.",{kind:"cmd",cmd:"/publish --all",reason:""});return}case"review":{let h=ia(e,f);if(!h){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let y=f.includes("--fix"),w=f.find(R=>!R.startsWith("--")),g=y?dp(e,w):[];if(await re(h.prompt,{display:h.display,quietUser:!0}),y)try{Ea(e,g,{reviewedCap:ja})}catch{}if(y)ve("\u2713 Editor applied its fixes \u2014 your docs are corrected. /publish --all pushes them up (or /check for an instant no-token re-scan first).",{kind:"cmd",cmd:"/publish --all",reason:""});else{let R=f.filter(A=>A!=="--fix").join(" ");ve(`The review listed issues above. /review${R?` ${R}`:""} --fix lets the editor apply them all (or /check --fix for just the deterministic ones; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/review${R?` ${R}`:""} --fix`,reason:""})}return}case"capture-setup":{await Y();return}case"devhints":{if(!ae(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:cn(ln(e)).join(`
428
+ `)}),Zt(Ot()),An.current=Me(e).status==="current",en.current=rt(e);return}case"discover":{if(!ae(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await re(Js(),{display:"/discover",quietUser:!0});return}case"inbox":{if(!ae(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(Yi(e)===0){d({kind:"note",tone:"info",text:"Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)"});return}await re(zi(),{display:"/inbox",quietUser:!0});return}case"feedback":{let h=up(e),y="";try{y=kn(h)?Hr(h,"utf8"):""}catch{y=""}if(!/^## /m.test(y)){d({kind:"note",tone:"info",text:"No open d360-writer feedback to copy \u2014 nothing logged in .d360-writer/tool-feedback.md yet."});return}let w=await $a(y.trim());d({kind:"note",tone:w?"ok":"warn",text:w?"\u2713 Copied the d360-writer feedback to your clipboard \u2014 send it to the team (Teams / Slack / email).":`Couldn\u2019t reach your clipboard \u2014 open ${h} and copy it manually.`}),w&&is(null);return}case"document":{if(!ae(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:h,what:y}=Si(f);if(!y&&Ri(e)===0){d({kind:"note",tone:"info",text:Ti});return}let w=`/document${y?` ${y}`:""}${h?" --publish":""}`;await re(Pi(y,h),{display:w,quietUser:!0});return}case"catch-up":{if(!ae(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!ko(c.trim()))return;let{publish:h}=Xi(f);d({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let y=await Ji({cwd:e,profileName:s});for(let g of Zi(y))d({kind:"note",tone:g.startsWith("\u2713")?"ok":g.startsWith("\u2139")?"info":"warn",text:g});let w=Jn(Qn(e));d({kind:"note",tone:"info",text:w?`Catching up on ${w}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"}),await re(Qi({publish:h}),{display:`/catch-up${h?" --publish":""}`,quietUser:!0});return}case"update":{rs.current=!0,d({kind:"note",tone:"info",text:"Updating the d360-writer toolchain\u2026 (don\u2019t close this window)"}),co(!0);let h=await vr().finally(()=>co(!1));h.ok?(d({kind:"note",tone:"ok",text:`\u2713 Updated ${h.packages.join(" + ")} \u2014 run /exit, then relaunch to apply.`}),Z("/exit"),Wa("")):d({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${xr}`});return}case"screenshot":{let h=Hn(f);if(h.mode==="capture"){await P(h.rest);return}if(h.mode==="checklist"){await Y();return}if(h.mode==="list"){if(!ae(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let g=ae(e)?.docsDir??Oa,R=Vs(e,h.scope),A=ze(e,R);if(h.picker){if(A.length===0){d({kind:"note",tone:"info",text:"No screenshot placeholders found in the docs."});return}let q=Ec(A);if(q.length===0){d({kind:"note",tone:"info",text:rr(A,{docsDir:g}).join(`
429
+ `)}),ve(`\u2713 All ${A.length} screenshots are captured. /publish puts them in the articles; /screenshot capture re-captures.`,{kind:"cmd",cmd:"/publish",reason:""});return}Pt({cursor:0,rows:q,title:"Screenshots \u2014 pick what to author or capture:"});return}d({kind:"note",tone:"info",text:rr(A,{scope:R,detail:h.detail,docsDir:g}).join(`
430
+ `)});let F=A.filter(q=>q.state==="placeholder").length,C=A.filter(q=>q.state==="spec").length;if(F>0){let q=R?`/screenshot author ${R}`:"/screenshot author --all";ve(`${F} of ${A.length} still need${F===1?"s":""} a spec \u2014 /screenshot author <id> authors one, ${q} authors them all in parallel.`,{kind:"cmd",cmd:q,reason:""})}else if(C>0){let q=R?`/screenshot capture ${R}`:"/screenshot capture";ve(`${C} spec${C===1?"":"s"} ready to capture \u2014 ${q} takes ${C===1?"it":"them"} (a real browser drives your app).`,{kind:"cmd",cmd:q,reason:""})}return}if(h.mode==="single"){await nl(h.id);return}if(!ae(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let y=h.mode==="scope"?h.scope:void 0,w=pk(e,{scope:y}).map(g=>g.id);if(w.length===0){d({kind:"note",tone:"info",text:y?`No screenshot placeholders under ${y}.`:"No screenshot placeholders found in the docs."});return}await tl(w,{setup:h.setup,runLine:h.mode==="scope"?[`/screenshot author ${h.scope}`,`/screenshot ${h.scope}`]:["/screenshot author --all","/screenshot --all"]});return}case"capture":{await P(f);return}case"reset":{let h=na(e);if(h.length===0){d({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}ho.current={repoName:ro(e),targets:h,hadDevhints:kn(cp(e))},d({kind:"note",tone:"warn",text:ra(e,h).join(`
431
+ `)}),xe(ro(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${i} \u2014 type /help.`})}},[e,r,s,tn,fs,d,Ee,re,It,us,ol]),Eo=Q(c=>{let l=(c??$).trim();if(x(""),uo(null),Ft(0),l.startsWith("/")&&(io.current=!1,vn.current=!1,He(),Cn(null),qe(f=>Hd(f,l))),!l||(Ua(!1),sl(l))||rl(l))return;Jr.current.push(l);let i=zd(l,Fa.current);if(l.startsWith("/"))d({kind:"user",text:l}),Be(!0),jn(i).finally(()=>Be(!1));else if(xk(i)){d({kind:"user",text:l});let f=vk(i);if(!f)re(i,{display:l,quietUser:!0});else{try{Ck(e,{title:f,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}re(`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${f}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${f}" and the article path(s) you wrote.`,{display:l,quietUser:!0})}}else{let f=fd(e,i);re(f??i,{display:l})}},[$,sl,rl,jn,re]),il=Q(c=>{if(c.length>1){if(c.includes("\x1B"))return;let l=Vd(c);if(Gd(l)){let i=Yd(++Ap.current,l);Fa.current.set(i,l),j(i)}else j(l);return}j(c)},[j]),nn=Math.max(10,Ve-6),al=Sa(()=>Br(b.text,nn),[b.text,nn]),ms=Q(c=>k(l=>({...l,pos:Math.max(0,Math.min(l.text.length,l.pos+c))})),[]),jo=Q(c=>k(l=>({...l,pos:Xd(Br(l.text,nn),l.pos,c)})),[nn]),Nn=Q(c=>k(l=>({...l,pos:Qd(Br(l.text,nn),l.pos,c)})),[nn]),Ip=["\x1B[H","\x1B[1~","\x1BOH"],Op=["\x1B[F","\x1B[4~","\x1BOF"],ll=Q((c,l)=>l.leftArrow?(ms(-1),!0):l.rightArrow?(ms(1),!0):c&&Ip.includes(c)?(Nn("start"),!0):c&&Op.includes(c)?(Nn("end"),!0):l.ctrl&&c==="a"?(Nn("start"),!0):l.ctrl&&c==="e"?(Nn("end"),!0):!1,[ms,Nn]);return Lw((c,l)=>{if(l.ctrl&&c==="c"){Oe.current?.close(),r();return}if(!U){if(D){if(l.escape){if(we.current){if(!we.current.signal.aborted){let i=(fo?.verb??"work").toLowerCase(),f=fo?.unit??"article";d({kind:"note",tone:"warn",text:`\u238B Stopping the ${i} run (finishing in-flight ${f}s)\u2026`}),we.current.abort()}return}Rn.current||(Rn.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),Oe.current?.interrupt());return}if(l.return){let i=$.trim();if(!i)return;At.current.push(i),es([...At.current]),x("");return}if(ll(c,l))return;if(l.upArrow){jo(-1);return}if(l.downArrow){jo(1);return}if(l.backspace||l.delete){v();return}c&&!l.ctrl&&!l.meta&&il(c);return}if(Ct){if(l.upArrow){Rt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Rt(i=>i&&{...i,cursor:Math.min(Ke.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ke.length){Rt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Ke[Ct.cursor];Rt(null);let{lines:f,changed:P,effective:Y}=Kn(e,i.value??"default");for(let h of f)d({kind:"note",tone:h.startsWith("\u26A0")?"warn":h.startsWith("\u2713")?"ok":"info",text:h});P&&(Ka(h=>h+1),Oe.current?.setModel(Y));return}if(c==="s"){let i=Ke[Ct.cursor];Rt(null),Oe.current?.setModel(i.value??void 0),d({kind:"note",tone:"ok",text:`\u2713 Using ${i.label} for this session only (your saved default is unchanged).`});return}if(l.escape){Rt(null);return}return}if(Ze){if(l.upArrow){Gt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Gt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ze.rows.length){Gt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return||c==="s"){let i=Ze.rows[Ze.cursor];Gt(null),ps(i.name,l.return===!0);return}if(l.escape){Gt(null);return}return}if(yo){if(l.escape){Tn(null);return}if(l.leftArrow||l.tab&&l.shift){Tn(i=>i&&{tab:(i.tab-1+Le.length)%Le.length});return}if(l.rightArrow||l.tab){Tn(i=>i&&{tab:(i.tab+1)%Le.length});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Le.length){Tn({tab:Number(c)-1});return}return}if(et){if(l.upArrow){Yt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Yt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=et.rows.length){Yt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=et.rows[et.cursor].name;if(Yt(null),!Cs(e,i).created){d({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}d({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${i}").`});let P=!1;try{let Y=Ut(i);P=!!Y&&!($t(Y)&&!Y.refreshToken)}catch{P=!1}d({kind:"note",tone:"info",text:P?`Next: sign in to ${i} and pick your project \u2014 you're already signed in here, so it'll be quick.`:`Next: sign in to Document360 (${i}) and pick your project.`}),Z("/login"),H(Y=>Y+1);return}if(l.escape){Yt(null);return}return}if($e){if(l.upArrow){zt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){zt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=$e.rows.length){zt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=$e.rows[$e.cursor],{profile:f,projectId:P}=$e;zt(null),To(f,P,i);return}if(l.escape){zt(null);return}return}if(Te){if(l.upArrow){St(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){St(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Te.rows.length){St(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=Te.rows[Te.cursor],{profile:f}=Te;St(null),Ao(f,i);return}if(l.escape){St(null);return}return}if(Ce){if(l.upArrow){Xt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Xt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c===" "){Xt(i=>i&&{...i,rows:i.rows.map((f,P)=>P===i.cursor?{...f,checked:!f.checked}:f)});return}if(l.return){let i=Ce.rows.filter(f=>f.checked).map(f=>f.path);if(Xt(null),i.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}Zs(e,i),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${i.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let f of i)d({kind:"note",tone:"info",text:` ${f}`});d({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(l.escape){Xt(null);return}return}if(tt){if(l.upArrow){Tt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Tt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=tt.rows.length){Tt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=tt.rows[tt.cursor],f=tt.run;Tt(null),f(i.token);return}if(l.escape){Tt(null);return}return}if(at){if(l.upArrow){Kt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Kt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=at.rows.length){Kt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=at.rows[at.cursor];Kt(null),i.conflict?fs(i.paths[0]):i.kind==="article"?us(i.paths[0]):It(i.paths);return}if(l.escape){Kt(null);return}return}if(lt){if(l.upArrow){Pt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Pt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=lt.rows.length){Pt(i=>i&&{...i,cursor:Number(c)-1});return}if(l.return){let i=lt.rows[lt.cursor];Pt(null),i.action==="capture"?Po(i.ids,{runLine:i.kind==="all"?["/screenshot capture --all","/capture --all"]:void 0}):i.kind==="shot"?nl(i.ids[0]):tl(i.ids,{setup:!0,runLine:i.kind==="all"?["/screenshot author --all","/screenshot --all"]:void 0});return}if(l.escape){Pt(null);return}return}if(De){if(l.escape){Dt(null);return}if(l.upArrow){Dt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Dt(i=>i&&{...i,cursor:Math.min(Math.max(0,Co.length-1),i.cursor+1)});return}if(l.return){let i=Co[De.cursor];if(i){Dt(null);try{d({kind:"preview",name:ro(i),text:wp(Hr(Pa(e,i),"utf8"))})}catch(f){d({kind:"note",tone:"error",text:`Could not read ${i}: ${f.message}`})}}return}if(l.backspace||l.delete){Dt(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(c&&!l.ctrl&&!l.meta&&c.length===1){Dt(i=>i&&{...i,query:i.query+c,cursor:0});return}return}if(Ae){if(l.escape){Et(null);return}if(l.upArrow){Et(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Et(i=>i&&{...i,cursor:Math.min(Math.max(0,Ro.length-1),i.cursor+1)});return}if(l.return){let i=Ro[Ae.cursor];if(i){Et(null),Ee(i.uuid),Je.current={uuid:i.uuid,firstPrompt:i.firstPrompt,titleFired:!0},vt(i.name),Ta(i.uuid),qt.current=[];let f=va(e,i.uuid);for(let P of f)d(P);d({kind:"note",tone:"ok",text:f.length?`Resumed "${i.name}" \u2014 restored ${f.length} message(s); continue where you left off.`:`Resumed "${i.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(l.backspace||l.delete){Et(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(c&&!l.ctrl&&!l.meta&&c.length===1){Et(i=>i&&{...i,query:i.query+c,cursor:0});return}return}if(l.tab&&!$&&fe){x(fe),He();return}if(!$&&be.length>0&&!Kr&&c&&/^[1-9]$/.test(c)){let i=be[Number(c)-1];if(i){x(Mt(i));return}}if(!$&&(bo||Dn)&&c==="c"&&!l.ctrl&&!l.meta&&!l.return&&!l.tab){let i=bo!=null;$a(bo??Dn).then(P=>{d({kind:"note",tone:P?"ok":"warn",text:P?i?"\u2713 Copied the feedback to your clipboard \u2014 send it to the d360-writer team (Teams / Slack / email).":"\u2713 Copied the prompt to your clipboard \u2014 paste it into your repo's coding agent.":i?"Couldn't reach your clipboard \u2014 select the feedback above and copy it manually.":"Couldn't reach your clipboard \u2014 select the prompt above and copy it manually."}),P&&i&&is(null),P&&!i&&Qa(!0)});return}if(!ll(c,l)){if(Za){if(l.upArrow){Ft(i=>Math.max(0,i-1));return}if(l.downArrow){Ft(i=>Math.min(Ge.length-1,i+1));return}if(l.tab){x("/"+(Ge[Qr]?.name??"")+" "),Ft(0);return}if(l.return){let i=Ge[Qr];if(i){let f=$.trim().slice(1).split(/\s+/).slice(1).join(" ");if(ec(i.usage)&&!f){x("/"+i.name+" "),Ft(0);return}Eo("/"+i.name+(f?" "+f:""));return}}}else{if(l.upArrow){if($!==""&&Bt===null){jo(-1);return}let i=Jr.current;if(!i.length)return;let f=Bt===null?i.length-1:Math.max(0,Bt-1);uo(f),x(i[f]??"");return}if(l.downArrow){if($!==""&&Bt===null){jo(1);return}let i=Jr.current;if(Bt===null)return;let f=Bt+1;f>=i.length?(uo(null),x("")):(uo(f),x(i[f]??""));return}}if(l.return){Eo();return}if(l.backspace||l.delete){v();return}if(l.escape){x(""),Ft(0),He(),qe([]),Cn(null),io.current=!0;return}c&&!l.ctrl&&!l.meta&&il(c)}}}),Ie(()=>{if(D||U)return;let c=At.current.shift();c!==void 0&&(es([...At.current]),Eo(c))},[D,U,Eo]),J(le,{flexDirection:"column",width:Ve,children:[cs!==null&&J(le,{marginTop:1,flexDirection:"column",children:[cs.truncated&&I(N,{dimColor:!0,children:"\u2026"}),I(N,{children:cs.text})]}),D&&(fo?I(Ik,{p:fo}):I(Ek,{startTime:xt.current,chars:Dp})),!D&&Ga?I(jk,{text:Ga}):null,I(le,{borderStyle:"round",borderColor:Ja.prod?"yellow":X,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:$?al.map((c,l)=>{let i=b.text.slice(c.start,c.end),f=l===qr(al,b.pos),P=Math.min(b.pos,c.end)-c.start;return J(N,{children:[I(N,{color:X,children:l===0?"> ":" "}),f?J(so,{children:[i.slice(0,P),I(bn,{ch:i[P]??" "}),i.slice(P+1)]}):i||" "]},`${l}-${c.start}`)}):J(N,{children:[I(N,{color:X,children:"> "}),ts?I(bn,{ch:" "}):fe&&!D&&me?J(so,{children:[I(bn,{ch:me[0],dim:!0}),I(N,{color:"gray",children:me.slice(1)})]}):fe&&!D?J(so,{children:[I(bn,{ch:fe[0],dim:!0}),I(N,{color:"gray",children:fe.slice(1)}),I(N,{dimColor:!0,children:" (tab)"})]}):(as.isSetup||!Pp)&&!D?J(so,{children:[I(bn,{ch:as.text[0],dim:!0}),I(N,{color:"gray",children:as.text.slice(1)})]}):I(bn,{ch:" "})]})}),Va.length>0&&I(le,{flexDirection:"column",paddingX:1,children:Va.map((c,l)=>I(N,{color:"gray",children:`\u29D7 queued: ${c}`},`${l}-${c.slice(0,24)}`))}),yo?I(Md,{tab:yo.tab,width:Ve,version:o,engineVersion:kp}):Ct?J(le,{flexDirection:"column",paddingX:1,children:[I(N,{color:X,bold:!0,children:"Select model"}),I(N,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),Ke.map((c,l)=>J(N,{color:l===Ct.cursor?X:void 0,children:[l===Ct.cursor?"\u276F ":" ",`${l+1}. ${c.label}${l===Ct.current?" \u2714":""}`.padEnd(16),I(N,{color:"gray",children:c.desc})]},c.label)),I(N,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Ze?J(le,{flexDirection:"column",paddingX:1,children:[I(N,{color:X,bold:!0,children:"Switch connection profile"}),Ze.rows.map((c,l)=>J(N,{color:l===Ze.cursor?X:void 0,children:[l===Ze.cursor?"\u276F ":" ",`${l+1}. ${c.name}${l===Ze.current?" \u2714":""}`.padEnd(20),I(N,{color:"gray",children:`${c.env} \xB7 ${c.who??"not signed in"}`}),c.prod?I(N,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},c.name)),I(N,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):et?J(le,{flexDirection:"column",paddingX:1,children:[I(N,{color:X,bold:!0,children:"Pick your Document360 environment"}),et.rows.map((c,l)=>J(N,{color:l===et.cursor?X:void 0,children:[l===et.cursor?"\u276F ":" ",`${l+1}. ${c.name}`.padEnd(16),I(N,{color:"gray",children:c.apiUrl})]},c.name)),I(N,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):$e?J(le,{flexDirection:"column",paddingX:1,children:[I(N,{color:X,bold:!0,children:"Switch workspace"}),I(N,{dimColor:!0,children:`environment ${$e.environment} \xB7 project ${$e.projectName??`${$e.projectId.slice(0,8)}\u2026`}`}),$e.rows.map((c,l)=>J(N,{color:l===$e.cursor?X:void 0,children:[l===$e.cursor?"\u276F ":" ",`${l+1}. ${c.name}${l===$e.current?" \u2714":""}`.padEnd(30),I(N,{color:"gray",children:c.type??""})]},c.id)),I(N,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):Te?J(le,{flexDirection:"column",paddingX:1,children:[I(N,{color:X,bold:!0,children:"Choose project"}),I(N,{dimColor:!0,children:`environment ${Te.environment}`}),Te.rows.map((c,l)=>J(N,{color:l===Te.cursor?X:void 0,children:[l===Te.cursor?"\u276F ":" ",`${l+1}. ${c.name}${l===Te.current?" \u2714":""}`.padEnd(30),I(N,{color:"gray",children:c.sub??""})]},c.id)),I(N,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):Ce?(()=>{let l=Math.min(Math.max(0,Ce.cursor-Math.floor(7)),Math.max(0,Ce.rows.length-14)),i=Ce.rows.slice(l,l+14),f=Ce.rows.filter(P=>P.checked).length;return J(le,{flexDirection:"column",paddingX:1,children:[I(N,{color:X,bold:!0,children:`Which folders back the user docs? (${f} selected of ${Ce.rows.length})`}),l>0?I(N,{dimColor:!0,children:` \u2191 ${l} more`}):null,i.map((P,Y)=>{let h=l+Y;return J(N,{color:h===Ce.cursor?X:void 0,children:[h===Ce.cursor?"\u276F ":" ",P.checked?"\u25C9 ":"\u25CB ",P.path.padEnd(Math.min(48,Ve-34)),I(N,{color:"gray",children:dr(P)})]},P.path)}),l+14<Ce.rows.length?I(N,{dimColor:!0,children:` \u2193 ${Ce.rows.length-l-14} more`}):null,I(N,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():tt?J(le,{flexDirection:"column",paddingX:1,children:[I(N,{color:X,bold:!0,children:"Which category? (pick one to scope to)"}),tt.rows.map((c,l)=>{let i=l===tt.cursor,f=`${l+1}.`.padEnd(3);return J(N,{color:i?X:void 0,children:[i?"\u276F ":" ",`${f} ${c.label} (${c.count})`.padEnd(Math.min(44,Math.max(20,Ve-24))),I(N,{color:"gray",children:` ${c.token}`})]},c.token)}),I(N,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):at?J(le,{flexDirection:"column",paddingX:1,children:[I(N,{color:X,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),at.rows.map((c,l)=>{let i=l===at.cursor,f=c.indent?" ":" ",P=`${l+1}.`.padEnd(3);return J(N,{color:i?X:void 0,bold:c.kind==="category"&&!i,children:[i?"\u276F ":" ",`${f}${P} ${c.label}`.padEnd(Math.min(56,Ve-24)),c.note?I(N,{color:"gray",children:c.note}):null]},`${c.kind}:${c.paths.join(",")}`)}),I(N,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):lt?J(le,{flexDirection:"column",paddingX:1,children:[I(N,{color:X,bold:!0,children:lt.title}),(()=>{let{rows:l,cursor:i}=lt,f=Math.max(0,Math.min(i-Math.floor(12/2),l.length-12)),P=l.slice(f,f+12),Y=`${l.length}.`.length+1;return J(so,{children:[f>0?I(N,{color:"gray",children:` \u2026 ${f} more above`}):null,P.map((h,y)=>{let w=f+y,g=w===i;return J(N,{color:g?X:void 0,bold:(h.kind==="all"||h.kind==="category")&&!g,children:[g?"\u276F ":" ",`${w+1}.`.padEnd(Y)," ".repeat(h.depth),h.label,h.note?I(N,{color:"gray",children:h.note}):null]},`${h.action}:${h.kind}:${h.ids.join(",")}`)}),f+12<l.length?I(N,{color:"gray",children:` \u2026 ${l.length-f-12} more below`}):null]})})(),I(N,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter run \xB7 esc cancel"})]}):De?J(le,{flexDirection:"column",paddingX:1,children:[I(N,{color:X,bold:!0,children:`Preview article${De.query?` \u2014 filter: ${De.query}`:" (type to filter)"}`}),Co.length===0?I(N,{color:"gray",children:"no articles match"}):Co.map((c,l)=>J(N,{color:l===De.cursor?X:void 0,children:[l===De.cursor?"\u276F ":" ",c]},c)),I(N,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):Ae?J(le,{flexDirection:"column",paddingX:1,children:[I(N,{color:X,bold:!0,children:`Resume session${Ae.query?` \u2014 filter: ${Ae.query}`:" (type to filter)"}`}),Ro.length===0?I(N,{color:"gray",children:"no sessions match"}):Ro.map((c,l)=>J(N,{color:l===Ae.cursor?X:void 0,children:[l===Ae.cursor?"\u276F ":" ",c.name.slice(0,28).padEnd(30),I(N,{color:l===Ae.cursor?X:"gray",children:c.firstPrompt.slice(0,Math.max(10,Ve-40))})]},c.uuid)),I(N,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Za?J(le,{flexDirection:"column",children:[Nt>0?I(N,{dimColor:!0,children:` \u22EF ${Nt} more above`}):null,ls.map((c,l)=>{let i=Nt+l;return J(N,{color:i===vo?X:void 0,children:[i===vo?"\u276F ":" ",c.usage.padEnd(22)," ",I(N,{color:i===vo?X:"gray",children:c.name==="model"&&ns?`${c.desc} (currently ${ns})`:c.desc})]},c.name)}),Nt+ls.length<Ge.length?I(N,{dimColor:!0,children:` \u22EF ${Ge.length-Nt-ls.length} more below`}):null,I(N,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!D&&!$&&be.length>0?J(le,{flexDirection:"column",paddingX:1,children:[Ha?I(N,{color:X,children:Ha}):null,be.map((c,l)=>{let i=Mt(c),f=i.slice(0,Math.max(20,Ve-5)),P=Ve-f.length-7,Y=P>=12?(qd(c)??Jl(i)).slice(0,P):"";return J(N,{children:[I(N,{color:X,children:l+1})," ",f,Y?I(N,{dimColor:!0,children:` \u2014 ${Y}`}):null]},i)}),I(N,{dimColor:!0,children:`press 1-${be.length} to fill \xB7 esc cancel`})]}):I(le,{paddingX:1,children:J(N,{color:"gray",children:[Ja.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${ns??"model n/a"}${t.kind==="api"?za>0?` \xB7 ${Pe(za)}`:"":Ya>0?` \xB7 ${gt(Ya)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}z();import{jsx as Mk}from"react/jsx-runtime";async function $p(e=process.cwd(),t="auto",n,o="0.0.0"){let r=Lk(t);r.kind==="none"&&(console.error(""),console.error(S("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${W("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${W("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=_k(Mk(bp,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
432
432
  `),process.exit(0)}z();import{writeCrashLog as xp,isBenignTransportError as Uk}from"document360-engine";var vp=!1;function _a(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function Cp(e){if(vp)return;vp=!0;let t=(n,o)=>{if(Uk(o)){xp({kind:n,level:"transport",message:_a(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=xp({kind:n,level:"fatal",message:_a(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
433
433
  `+S(`\u2717 d360-writer crashed: ${_a(o)}`)+`
434
434
  `),r&&process.stderr.write(m(` Crash details: ${r}`)+`
435
435
  `+m(" Run: d360-writer logs")+`
436
- `),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var qk=Fk(import.meta.url),Yr=qk("../package.json");Cp("d360-writer");var Be=new Wk;function La(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}Be.command("login").description("Sign in to Document360 (browser OAuth; project chosen during login)").option("--profile <name>","Connection profile (defaults to the repo's defaultProfile)").option("--env <name>",!1).option("--manual","No local listener \u2014 paste the redirect URL instead (SSH/locked-down setups)").action(async e=>{La(e),await Mo({profile:e.profile,manual:e.manual})});Be.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{La(e),await bl({profile:e.profile})});Be.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{La(e),await kl({profile:e.profile})});var Ma=Be.command("profile").description("Manage connection profiles for the current repo");Ma.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>Uo(process.cwd()));Ma.command("use <name>").description("Set the default profile for this repo").action(e=>Wo(process.cwd(),e));Ma.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>Fo(process.cwd(),e));var Rp=Be.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");Rp.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>rn(process.cwd(),e.profile));Rp.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await pl(process.cwd(),e,t.profile)});var Sp=Be.command("project").description("Choose the Document360 project for this repo (active profile's identity)");Sp.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>Oo(process.cwd(),e.profile));Sp.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await fl(process.cwd(),e,t.profile)});Be.command("init").description("Scaffold .d360-writer/config.json for this repo (interactive)").action(async()=>{let{initCommand:e}=await Promise.resolve().then(()=>(Yo(),Kl));await e()});Be.command("logs").description("Show the API + crash log files (send these to support when reporting a problem)").action(()=>Cl());Be.command("doctor").description("Health-check: node, Claude auth, Document360 login, profile/workspace, category map, API reachability").action(async()=>{let{renderDoctorChecks:e,runDoctorChecks:t}=await Promise.resolve().then(()=>(wr(),Tu)),n=await t(process.cwd(),Yr.version);for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});Be.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(Yr.version,"-v, --version").option("-p, --prompt <text>","One-shot prompt mode (non-interactive)").option("-r, --resume <name>","Resume a saved session (with --prompt; use /resume inside the REPL)").option("-C, --cwd <dir>","Working directory",process.cwd()).option("--auth <mode>","Auth mode: auto | api | subscription","auto").option("--profile <name>","Connection profile (defaults to the repo's defaultProfile)").option("--yes","Skip the production write confirmation (for one-shot/CI)").option("--classic","Use the plain readline REPL instead of the Ink TUI").action(async e=>{if(Bk.includes(e.auth)||(console.error(`\u2717 Invalid --auth mode: ${e.auth}`),console.error("Run: d360-writer --auth auto | api | subscription"),process.exit(2)),e.prompt){await Rl(e.cwd,e.prompt,e.auth,e.resume,e.profile,e.yes);return}e.resume&&(console.error("\u2717 --resume requires --prompt. In the interactive REPL, use /resume instead."),process.exit(2)),e.classic||!process.stdin.isTTY?await Ad(e.cwd,e.auth,e.profile,Yr.version):await $p(e.cwd,e.auth,e.profile,Yr.version)});Be.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
436
+ `),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var qk=Fk(import.meta.url),Yr=qk("../package.json");Cp("d360-writer");var Fe=new Wk;function La(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}Fe.command("login").description("Sign in to Document360 (browser OAuth; project chosen during login)").option("--profile <name>","Connection profile (defaults to the repo's defaultProfile)").option("--env <name>",!1).option("--manual","No local listener \u2014 paste the redirect URL instead (SSH/locked-down setups)").action(async e=>{La(e),await Mo({profile:e.profile,manual:e.manual})});Fe.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{La(e),await bl({profile:e.profile})});Fe.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{La(e),await kl({profile:e.profile})});var Ma=Fe.command("profile").description("Manage connection profiles for the current repo");Ma.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>Uo(process.cwd()));Ma.command("use <name>").description("Set the default profile for this repo").action(e=>Wo(process.cwd(),e));Ma.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>Fo(process.cwd(),e));var Rp=Fe.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");Rp.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>rn(process.cwd(),e.profile));Rp.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await pl(process.cwd(),e,t.profile)});var Sp=Fe.command("project").description("Choose the Document360 project for this repo (active profile's identity)");Sp.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>Oo(process.cwd(),e.profile));Sp.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await fl(process.cwd(),e,t.profile)});Fe.command("init").description("Scaffold .d360-writer/config.json for this repo (interactive)").action(async()=>{let{initCommand:e}=await Promise.resolve().then(()=>(Yo(),Kl));await e()});Fe.command("logs").description("Show the API + crash log files (send these to support when reporting a problem)").action(()=>Cl());Fe.command("doctor").description("Health-check: node, Claude auth, Document360 login, profile/workspace, category map, API reachability").action(async()=>{let{renderDoctorChecks:e,runDoctorChecks:t}=await Promise.resolve().then(()=>(wr(),Tu)),n=await t(process.cwd(),Yr.version);for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});Fe.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(Yr.version,"-v, --version").option("-p, --prompt <text>","One-shot prompt mode (non-interactive)").option("-r, --resume <name>","Resume a saved session (with --prompt; use /resume inside the REPL)").option("-C, --cwd <dir>","Working directory",process.cwd()).option("--auth <mode>","Auth mode: auto | api | subscription","auto").option("--profile <name>","Connection profile (defaults to the repo's defaultProfile)").option("--yes","Skip the production write confirmation (for one-shot/CI)").option("--classic","Use the plain readline REPL instead of the Ink TUI").action(async e=>{if(Bk.includes(e.auth)||(console.error(`\u2717 Invalid --auth mode: ${e.auth}`),console.error("Run: d360-writer --auth auto | api | subscription"),process.exit(2)),e.prompt){await Rl(e.cwd,e.prompt,e.auth,e.resume,e.profile,e.yes);return}e.resume&&(console.error("\u2717 --resume requires --prompt. In the interactive REPL, use /resume instead."),process.exit(2)),e.classic||!process.stdin.isTTY?await Ad(e.cwd,e.auth,e.profile,Yr.version):await $p(e.cwd,e.auth,e.profile,Yr.version)});Fe.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "document360-writer",
3
- "version": "0.5.159",
3
+ "version": "0.5.160",
4
4
  "description": "Standalone documentation agent CLI. Reads your code, writes your docs. Specialized for Document360 publishing.",
5
5
  "type": "module",
6
6
  "bin": {