document360-writer 0.5.320 → 0.5.322
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +250 -250
- package/package.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var H0=Object.defineProperty;var Rr=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var Nm=(e,t)=>{for(var n in t)H0(e,n,{get:t[n],enumerable:!0})};import Bn from"picocolors";var ue,G0,q0,V0,Dm,Ds,u,L,H,X,Z,Ae,Je,Ye,oe,ae=Rr(()=>{"use strict";ue="#7f56d9",[G0,q0,V0]=[127,86,217],Dm=e=>Bn.isColorSupported?`\x1B[38;2;${G0};${q0};${V0}m${e}\x1B[39m`:e,Ds=e=>Bn.bold(Dm(e)),u=e=>Bn.dim(e),L=e=>Bn.red(e),H=e=>Bn.yellow(e),X=e=>Bn.green(e),Z=Dm,Ae=e=>Bn.gray(e),Je=e=>Bn.bold(e),Ye="\u25CF production",oe=(e,t)=>`${e} ${t}`});import{CUSTOM_ENVIRONMENT_NAME as lx,currentEnvironments as cx,environmentIsAdded as ux,environmentIsInternal as _m,environmentIsProduction as Um,isExpired as dx,knownEnvironments as px,loadProfileMap as hx,loadTokens as fx,profileEnvironmentName as mx,readProjectConfig as fu,resolveActiveProfile as gx,resolveEnvironment as Fm,sunsetEnvironment as hu,unpushedArticlePaths as yx}from"document360-engine";function mu(e,t){let n=fu(e);return Object.entries(n?.profiles??{}).find(([,o])=>o.connection?.environment===t)?.[0]??null}function Hn(e,t){try{if(!fu(e))return null;let n=hu(mx(e,t));if(!n)return null;let o=mu(e,n.replacement);return{name:n.name,replacement:n.replacement,why:n.why,replacementProfile:o,cmd:o?`/profile ${o}`:`/profile add ${n.replacement}`}}catch{return null}}function wx(e){return e==="production-eu"?"Europe":e==="production-us"?"United States":e==="production-ca"?"Canada":null}function Gn(){return[...cx(),...px().filter(t=>hu(t))].map(t=>{let n=_m(t),o=Um(t),r=hu(t)!==null,s=ux(t),a=[r?"being retired":n?"Document360 internal staging":wx(t),s?"added on this machine":null].filter(Boolean).join(", ")||null;return{name:t,portalUrl:Fm(t).portalUrl,note:a,internal:n,production:o,added:s,retired:r}})}function gu(e){let t=fu(e);if(!t?.profiles)return[];let n=(()=>{try{return gx(e).name}catch{return t.defaultProfile??null}})();return Object.entries(t.profiles).map(([o,r])=>{let s=r.connection?.environment??lx,i=r.connection?.portalUrl??"";try{r.connection?.environment&&(i=Fm(r.connection.environment).portalUrl)}catch{i=""}let a=hx(e,o),l=r.project?.projectId,c=!1;try{let y=fx(o,l);c=!!y&&(!dx(y)||!!y.refreshToken)}catch{c=!1}let h=0;try{h=yx(e,o).length}catch{h=0}return{profile:o,environment:s,portalUrl:i,production:r.production??Um(r.connection?.environment),internal:_m(r.connection?.environment),project:r.project?.projectName??l??null,workspace:r.project?.workspaceName??r.project?.workspaceId??null,tracked:a?Object.keys(a.articles).length:0,unpushed:h,signedIn:c,active:o===n}})}function Wm(e){let t=new Map;for(let n of gu(e))n.project&&t.set(n.project,[...t.get(n.project)??[],n.profile]);return[...t.values()].filter(n=>n.length>1)}var qn=Rr(()=>{"use strict"});import{existsSync as Cr,writeFileSync as Yn,readFileSync as hR,readdirSync as fR}from"node:fs";import{join as yg}from"node:path";import{devHintsGuidePath as va,hintsDir as wg,hooksDir as bg,architectureDir as xg,messagesDir as Tu,creatorNotesPath as kg,devhintsStatePath as Rg,directivesPath as $g,DIRECTIVES_HEADER as mR,roadmapPath as vg,ROADMAP_HEADER as gR,ensureDir as Os,writeMessage as yR,listOpenForDev as wR,stampDone as bR,seedBriefConsumed as kR}from"document360-engine";function Sg(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
|
|
3
3
|
|
|
4
4
|
<!-- devhints script v${We} \xB7 maintained by document360-writer (/devhints). -->
|
|
5
5
|
|
|
@@ -242,7 +242,7 @@ do it**:
|
|
|
242
242
|
**Do NOT write or action the documentation yourself** \u2014 same boundary as Part 2. Writing the article is the
|
|
243
243
|
docs agent's job; it actions open directives on its next \`/catch-up\` (as drafts) and flips each to \`[done]\`
|
|
244
244
|
with the article it wrote. You are only the relay so the ask is captured durably and travels via git.
|
|
245
|
-
`}function
|
|
245
|
+
`}function vR(){return`# Creator notes (optional \u2014 for the docs agent and the builder)
|
|
246
246
|
|
|
247
247
|
<!-- The ORIGINAL CREATOR's context. Most repos leave this empty \u2014 that's fine.
|
|
248
248
|
The builder agent reads this FIRST and treats it as authoritative when writing the architecture
|
|
@@ -256,12 +256,12 @@ Anything only a human knows that would help document this product. For example:
|
|
|
256
256
|
- Gotchas or non-obvious behavior.
|
|
257
257
|
|
|
258
258
|
(Replace these examples with your notes, or leave the file as-is to skip \u2014 it's optional.)
|
|
259
|
-
`}function
|
|
260
|
-
`)}
|
|
261
|
-
`)}function
|
|
262
|
-
`)}function
|
|
263
|
-
`)}),n.notifiedBuilder=!0)}}catch{}return n}function
|
|
264
|
-
`)}function
|
|
259
|
+
`}function Tr(e){Os(wg(e)),Os(xg(e)),Os(Tu(e));for(let n of[wg(e),Tu(e)]){let o=yg(n,".gitkeep");Cr(o)||Yn(o,`# Keeps this document360-writer inbox tracked in git even when empty.
|
|
260
|
+
`)}Cr(kg(e))||Yn(kg(e),vR()),Cr($g(e))||Yn($g(e),mR),Cr(vg(e))||Yn(vg(e),gR),Yn(va(e),Sg()),Os(bg(e)),Yn(yg(bg(e),"open-questions.mjs"),$R);let t=en(e);return Pg(e,new Date().toISOString()),t}async function Cg(e,t){for(let n of Ar(Tr(t.cwd)))console.log(n);return{kind:"continue"}}function Oo(){return[`This is document360-writer's dev hand-off setup (v${We}).`,'Connect this repository to document360-writer (its "docs agent" \u2014 a separate tool that writes this',"product's user documentation from your code, but needs your intent). This prompt is SAFE TO RUN MORE","THAN ONCE \u2014 paste it again whenever the product changes. At each step: create what is missing, reconcile","what already exists, and never duplicate, clobber a refined file, or delete human-written notes. In order:","","1. Read `.d360-writer/DEV-HINTS-GUIDE.md` \u2014 the full dev\u2192docs hand-off protocol (Parts 1\u20136). Follow it.","2. Architecture brief in `.d360-writer/architecture/` (per the guide). First read"," `.d360-writer/architecture/CREATOR-NOTES.md` and treat it as authoritative (it may be empty; never"," modify it). Then:"," \u2022 If no brief exists yet, write it now \u2014 a USER-DOC-enabling brief: product intent, user-facing"," surfaces, features and why a user reaches for each, roles/permission gating, core workflows,"," terminology \u2014 every claim citing the source file(s) that prove it. Skip internals (services, data"," access, infra, build/CI, tests)."," \u2022 If a brief already exists, UPDATE it to match the current code: add new surfaces/features, correct"," what changed, remove what was deleted \u2014 but preserve accurate existing content and any human edits."," Do NOT rewrite it from scratch. If nothing changed, leave it as is.","3. Persist the ongoing rule so teammates' agents inherit it: this repo's agent-memory file (CLAUDE.md,"," or AGENTS.md \u2014 whichever this repo already uses; create CLAUDE.md if neither exists) should contain a",' short "Documentation hand-off" section saying: on every user-facing change, drop a hint file in'," `.d360-writer/hints/` and keep `.d360-writer/architecture/` current \u2014 and SURFACE each hint drop in"," your reply (name the file + the one-line surface), never silently; NEVER write or publish the"," user-facing articles yourself (that is the docs agent's job \u2014 you only hand off); each session,"," check `.d360-writer/messages/` for open questions from the docs agent and answer them promptly and"," in full \u2014 an open docs question BLOCKS the documentation, and `[discovery]` questions define the"," whole product brief, so answer those in depth; `git pull` at session start FIRST, because the docs"," agent may be on another machine and its questions only reach you when you pull; AND when the"," human types `@d360-writer <directive>` in your session, append it as an `## [open] <directive>` block"," to `.d360-writer/directives.md` (create if absent) and commit \u2014 do NOT action it yourself (the docs"," agent picks it up on its next /catch-up) \u2014 all per `.d360-writer/DEV-HINTS-GUIDE.md`. If that section"," is already there, leave it (refine in place only if"," wrong) \u2014 do NOT add a duplicate. Then commit `.d360-writer/` and the memory-file change ONLY if"," something actually changed.","4. Wire the SESSION-START QUESTION NUDGE so open docs questions surface every session \u2014 a memory rule"," alone (step 3) is easy to forget. d360-writer already scaffolded a portable, dependency-free checker"," at `.d360-writer/hooks/open-questions.mjs` (prints a one-line nudge when open `from: docs` questions"," exist; silent otherwise). Register it with YOUR coding agent's session-start mechanism:"," \u2022 Claude Code (this repo has a `.claude/` dir): add a `SessionStart` hook to `.claude/settings.json`"," (create the file if absent) that runs `node .d360-writer/hooks/open-questions.mjs` \u2014 its stdout is"," added to your context at session start. MERGE into any existing hooks, do NOT clobber other"," settings, and skip if that exact hook is already there. Shape:",' {"hooks":{"SessionStart":[{"hooks":[{"type":"command","command":"node .d360-writer/hooks/open-questions.mjs"}]}]}}'," \u2022 Codex / other agents: no stdout-injecting session hook yet \u2014 rely on the step-3 memory rule, and"," optionally run `node .d360-writer/hooks/open-questions.mjs` yourself when starting a docs-touching"," session. Wire the same command once your agent gains a session-start trigger."," Commit the hook config (`.claude/settings.json` or the equivalent) with the rest. Idempotent \u2014 leave"," an existing hook alone.","5. Two-way messages (Part 3). FIRST run `git pull` (fast-forward) if this repo has a remote \u2014 the docs"," agent may be a different person on a different machine, so their questions for you only EXIST in your",' checkout once you pull; skipping it makes an empty mailbox look like "no questions". If the pull'," cannot fast-forward, say so and continue rather than merging or rebasing to force it. Then check"," `.d360-writer/messages/` for open questions addressed to you"," (`from: docs`, `status: open`). Answer each IN FULL \u2014 an open docs question blocks the documentation,"," and `[discovery]`-tagged questions (what the product is, who it's for, its core mental model,"," misconceptions, positioning, terminology) define the whole product brief, so answer those in depth."," Fold durable facts into the architecture brief and drop a reply (`from: dev`, `kind: answer`,"," `re: <id>`) \u2014 then set the question's frontmatter `status: done`. If there are none, continue.","6. Then STOP and ask me for tribal knowledge \u2014 present it as a clearly-marked, standalone prompt on its"," own line (NOT buried in prose) and WAIT for my reply before doing anything else. Use this shape:",' "\u23F8 YOUR INPUT NEEDED \u2014 Any tribal knowledge that would help document this product? (folder map,',` terminology, what to prioritize or skip, gotchas.) Type it below, or reply 'none' / 'carry on' to skip."`," If I give you anything, phrase it clearly and append it to `.d360-writer/architecture/CREATOR-NOTES.md`"," (keep the existing header comment and every note already there; only add). If I say 'none'/'carry on', continue.",`7. Record completion: write/merge \`.d360-writer/devhints-state.json\` with {"completedVersion": ${We},`,' "completedAt": "<UTC now>", "completedCommit": "<current HEAD short sha>"} (preserve any other keys'," already in the file, e.g. emittedAt). Include this file in the commit from step 3.","8. Finish with a RECEIPT of what this run actually changed, then the right next step. Two parts.",""," (a) The receipt. A heading line, then one short bullet per thing that CHANGED \u2014 omit any bullet"," that did not happen, so a run that changed little stays three lines rather than ten. Report"," OUTCOMES, not the steps you took. Cover, where applicable: the protocol version you moved to; the"," architecture brief (created / N files updated / unchanged); how many docs questions you answered"," (and how many were `[discovery]`); how many hints you dropped \u2014 and when none, add one clause",' saying WHY, so "0 hints" reads as a judgement rather than an omission; whether you added to'," CREATOR-NOTES.md; whether you wired the session-start hook; and the commit you pushed. Shape:"," \u2705 Hand-off refreshed (protocol v11 \u2192 v12)"," \u2022 architecture brief: 2 files updated"," \u2022 answered 3 docs questions (1 [discovery])"," \u2022 dropped 0 hints \u2014 only internal test anchors changed"," \u2022 committed + pushed: <short sha>",' Say "\u2705 Setup complete" instead when this was the first-time setup (no brief existed before).',""," (b) The next step \u2014 chosen by what you are actually HANDING OVER. Do not print a command in every"," case, and never invent one to look helpful:"," \u2022 You answered a question, dropped a hint, or relayed an owner directive \u2192 the docs agent has a"," queue to fold in. Print, fenced on its own line so it copies cleanly:"," ```"," /catch-up"," ```"," \u2022 The docs folder configured in `.d360-writer/config.json` (default `.d360-writer/user-docs/`) is"," absent or empty \u2192 this repo has no docs yet, so it is a cold start:"," ```"," write the docs for this repo"," ```"," \u2022 You handed over NOTHING (no answers, no hints, no directives) and docs already exist \u2192 print NO",' command. Say: "Nothing new to hand over. Switch back to the document360-writer terminal \u2014 it',' will show you where things stand." The docs agent picks its own next action from the whole'," picture (its documentation campaign, coverage gaps, what is still unpublished); a command"," guessed from your side would override one it already knows to be better.",' When you DO print a block, precede it with "Back in the document360-writer terminal, paste this:"',' \u2014 or "Now switch to the document360-writer terminal and paste this:" on first-time setup.'].join(`
|
|
261
|
+
`)}function Eu(e){try{let t=hR(Rg(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function Pg(e,t){let o={...Eu(e)??{},emittedVersion:We,emittedAt:t};Yn(Rg(e),`${JSON.stringify(o,null,2)}
|
|
262
|
+
`)}function Pn(e){try{return fR(xg(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function en(e){let n=Eu(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<We?"stale":"current",completedVersion:n}}function xR(e){let t=new RegExp(`${Au.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(\\d+)\\)`).exec(e);return t?Number(t[1]):null}function xa(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,supersededRequests:[],toVersion:We};try{if(!Cr(va(e)))return n;kR(e);let o=Eu(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;if(We>r&&(Os(Tu(e)),Yn(va(e),Sg()),Pg(e,t),n.guideRefreshed=!0),We>s){let i=wR(e).filter(l=>l.kind==="request"&&l.subject.startsWith(Au)),a=i.filter(l=>(xR(l.subject)??We)>=We);for(let l of i.filter(c=>!a.includes(c)))bR(e,l.file,{doneAt:t,answeredBy:"docs"}),n.supersededRequests.push(l.subject);a.length===0&&(yR(e,{id:`onb${We}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${Au}${We})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${We}${s?` (you last completed v${s})`:""}.`,"Re-run the hand-off so the docs agent and this repo stay in step \u2014 run this prompt here:","",Oo()].join(`
|
|
263
|
+
`)}),n.notifiedBuilder=!0)}}catch{}return n}function Ra(e){if(!Cr(va(e)))return[];let t=en(e);return t.status==="current"?[]:[`\u{1F514} Your builder agent ${t.completedVersion?`is on v${t.completedVersion}`:"hasn't completed the hand-off yet"} \u2014 d360-writer's dev\u2194docs protocol is now v${We}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,Pr,Oo(),Pr,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function Nu(){return['document360-writer (its "docs agent") has been removed from this repository. Please undo its dev\u2192docs',"hand-off setup and restore this repo to how it was before \u2014 in order:","","1. In this repo's agent-memory file (CLAUDE.md, or AGENTS.md \u2014 whichever it edited), REMOVE the",' "Documentation hand-off" section that was added (the rule about dropping hint files in'," `.d360-writer/hints/`, keeping `.d360-writer/architecture/` current, checking"," `.d360-writer/messages/`, and relaying `@d360-writer` directives to `.d360-writer/directives.md`)."," Leave everything else in that file untouched.","2. The `.d360-writer/` folder is already deleted on disk. If it was committed, remove it from version"," control too \u2014 `git rm -r --cached .d360-writer` (if it still resolves) \u2014 and commit the deletions.","3. Do NOT recreate any of those files or follow the hand-off protocol anymore.","","That's it \u2014 this repo is back to its pre-docs-agent state."].join(`
|
|
264
|
+
`)}function Sa(){return['\u{1F9F9} One leftover: your builder still has the "Documentation hand-off" rule in its CLAUDE.md / AGENTS.md'," (reset only clears d360-writer's own .d360-writer/ folder \u2014 never your repo's files)."," To restore it, paste this prompt into your repo's coding agent (Claude Code / Codex / Cursor):",Pr,Nu(),Pr]}function Ar(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${We}.`," Have them run the prompt below again \u2014 it now sets up two-way messages + on-demand docs.",""]:[],"\u2713 Wrote .d360-writer/DEV-HINTS-GUIDE.md + the .d360-writer/architecture/ (brief), .d360-writer/hints/, and .d360-writer/messages/ inboxes.","","\u{1F4CB} Copy this one prompt and run it in your repo's coding agent (Claude Code / Codex / Cursor):",Pr,Oo(),Pr,"","That one run writes the architecture brief, adds the ongoing rule to your agent memory (CLAUDE.md / AGENTS.md)","and commits it so teammates inherit it, answers any open questions the writer left, and asks you for tribal","knowledge \u2014 no manual file edits. It also sets up the two-way channel: the writer can ask you questions","(`/inbox` on its side), and you can ask it to document a session on demand (Part 4 of the guide).","","When it finishes, come back to THIS terminal and run:"," write the docs for this repo"]}var Pr,We,$R,Au,Kn=Rr(()=>{"use strict";Pr="-".repeat(64),We=13,$R=`#!/usr/bin/env node
|
|
265
265
|
// d360-writer \u2014 session-start nudge for the builder ("John"). Surfaces open questions the docs agent
|
|
266
266
|
// ("Julie") left in .d360-writer/messages/ so they get answered, not forgotten. Self-contained (no deps);
|
|
267
267
|
// wired into your coding agent's session-start trigger by /devhints. See .d360-writer/DEV-HINTS-GUIDE.md.
|
|
@@ -299,96 +299,96 @@ try {
|
|
|
299
299
|
} catch {
|
|
300
300
|
/* a session-start nudge must never break the session */
|
|
301
301
|
}
|
|
302
|
-
`;
|
|
303
|
-
`),"utf8");return}let o;try{o=
|
|
302
|
+
`;Au="Re-run dev\u2194docs onboarding (protocol v"});var Ug={};Nm(Ug,{initCommand:()=>Iu,scaffoldInit:()=>Du,writeWriterGitignore:()=>ju});import{input as Ca,confirm as RR,select as SR}from"@inquirer/prompts";import{basename as Eg,join as Pa}from"node:path";import{existsSync as Er,readFileSync as Ng,readdirSync as CR,writeFileSync as Tg}from"node:fs";import{writeProjectConfig as Dg,readProjectConfig as PR,projectConfigPath as jg,writerDir as TR,DEFAULT_DOCS_DIR as Ig,DEFAULT_CAPTURE_DIR as Lg,DEFAULT_OUTPUT_DIR as Og,environmentIsProduction as AR,resolveEnvironment as ER}from"document360-engine";function Du(e,t){let n=jg(e);if(Er(n))return{created:!1,path:n,profileName:""};let o={projectId:Mg(e)??Eg(e),docsDir:Ig,captureDir:Lg,outputDir:Og,profiles:{[t]:{connection:{environment:t}}},defaultProfile:t,authoritativeSourceFiles:_g(e)};return Dg(o,e),ju(e),{created:!0,path:n,profileName:t}}function ju(e){let t=Pa(TR(e),".gitignore"),n="# Local/transient \u2014 the config files here ARE meant to be committed.";if(!Er(t)){Tg(t,[n,...Ag,""].join(`
|
|
303
|
+
`),"utf8");return}let o;try{o=Ng(t,"utf8")}catch{return}let r=new Set(o.split(/\r?\n/).map(l=>l.trim())),s=Ag.filter(l=>!r.has(l)&&!r.has(l.replace(/\/$/,"")));if(s.length===0)return;let i=/\r\n/.test(o)?`\r
|
|
304
304
|
`:`
|
|
305
305
|
`,a=o.endsWith(`
|
|
306
|
-
`)?"":i;Rg(t,`${o}${a}${s.join(i)}${i}`,"utf8")}async function ju(){let e=process.cwd(),t=Ag(e);if(Ar(t)&&!await gR({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(u("init canceled.")),{kind:"continue"};let n=jg(e)??Cg(e),o=await Sa({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await Sa({message:"Capture directory (where document360-capture .spec.ts files live):",default:Ng}),s=await Sa({message:"Screenshot output directory:",default:Dg}),i=Bn().filter(w=>!w.retired),a=Math.max(...i.map(w=>w.portalUrl.length))+3,l=await yR({message:"Which Document360 deployment do these docs publish to?",choices:i.map(w=>({name:`${w.name.padEnd(16)}${w.portalUrl.padEnd(a)}${w.note?`(${w.note})`:""}`.trimEnd(),value:w.name}))}),c=await Sa({message:"Name for this connection profile:",default:l}),h={projectId:o,docsDir:Eg,captureDir:r,outputDir:s,profiles:{[c]:{connection:{environment:l}}},defaultProfile:c,authoritativeSourceFiles:Ig(e)},y=bR(e);y?.terminologyGlossary&&(h.terminologyGlossary=y.terminologyGlossary),Tg(h,e),Du(e);let x=Pr(e);console.log(""),console.log(X(`\u2713 Wrote ${t}`)),$R(l)&&(console.log(""),console.log(`\u26A0 ${l} is a live deployment \u2014 ${vR(l).portalUrl}`),console.log(u(" Drafts save freely. Taking articles live needs --yes, or /allow-prod in the app."))),console.log(""),console.log(`Next: ${Z(`d360-writer login --profile ${c}`)} ${u("(sign in; project & workspace auto-selected)")}`),console.log("");for(let w of Tr(x))console.log(w);return console.log(""),console.log(`${u("Then ask:")} ${Z('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function jg(e){let t=Ca(e,"package.json");if(!Ar(t))return null;try{return JSON.parse(Pg(t,"utf8")).name??null}catch{return null}}function Ig(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Ar(Ca(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Ca(e,n);Ar(o)&&!xR(o)&&t.push(n)}return t}function xR(e){try{return wR(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var Sg,Pa=xr(()=>{"use strict";ie();Hn();Vn();Sg=[".sessions/","cache/"]});import{createRequire as _R}from"node:module";import{existsSync as UR,readFileSync as FR}from"node:fs";import{dirname as qg,join as Vg}from"node:path";function vt(){let e;try{e=WR.resolve("document360-capture/helpers")}catch{return null}let t=qg(e);for(let n=0;n<5&&!UR(Vg(t,"package.json"));n++)t=qg(t);try{let n=JSON.parse(FR(Vg(t,"package.json"),"utf8"));return n.name==="document360-capture"&&n.version?n.version:null}catch{return null}}var WR,Er=xr(()=>{"use strict";WR=_R(import.meta.url)});var hb={};Tm(hb,{doctorCommand:()=>ri,renderDoctorChecks:()=>pb,runDoctorChecks:()=>db});import{existsSync as ZT}from"node:fs";import{d360GetAll as eA,getAccessToken as tA,isExpired as Al,loadProfileMap as nA,loadCoverage as oA,profileIdentityDrift as rA,loadTokens as sA,listStoredSessions as iA,tokensProjectId as Cp,packageSkillsDir as ub,ENGINE_VERSION as aA,projectConfigPath as lA,readProjectConfig as cA,DEFAULT_DOCS_DIR as uA,fetchManifestSummary as dA,resolveActiveProfile as pA,loadAddedEnvironments as hA,addedEnvironmentsPath as fA,classifyClaudeAuth as mA,resolveAuthOrigin as gA,authOriginLine as yA,authOriginFix as wA,CLAUDE_CODE_SETUP_HINT as El,resolveModelSetting as bA,probeModel as kA,probeAgentTurn as $A,stderrHeadline as vA,detectAppType as xA,playbookSkillName as RA,D360AuthError as SA,applyStructureOrder as CA}from"document360-engine";async function db(e,t){let n=[],o=vt();n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${aA}${o?` \xB7 capture v${o}`:" \xB7 capture not installed"}`});let r=Number(process.versions.node.split(".")[0]);n.push(r>=20?{level:"ok",label:`Node ${process.versions.node}`}:{level:"fail",label:`Node ${process.versions.node} \u2014 20+ required`,fix:"Install Node 20 or later (nodejs.org)"});let s=mA();if(s.state==="ready"){let j=gA(),ne=wA(j);n.push({level:ne?"warn":"ok",label:`Claude auth: ${yA(j).replace(/^Claude: /,"")}`,...ne?{fix:ne}:{}})}else s.state==="maybe"?n.push({level:"warn",label:"Claude: no Claude Code login found (may be in the macOS Keychain)",fix:`If a docs turn ends with no output, sign in to Claude Code. ${El}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:El});let i=bA(e);if(n.push({level:"ok",label:`Model: ${i.model} (${i.source==="auto"?"auto \u2014 right-sized for docs; /model to change":i.source})`}),s.state==="ready"){let j=await kA(e,i.model??void 0);if(j.ok){n.push({level:"ok",label:`Model reachable \u2014 replied in ${(j.latencyMs/1e3).toFixed(1)}s`});let ne=await $A(e,i.model??void 0);if(ne.ok)n.push({level:"ok",label:`Agent turn works \u2014 ran with your skills and tools in ${(ne.latencyMs/1e3).toFixed(1)}s`});else{let te=vA(ne.stderr),ye=/auth|sign.?in|login|credential|token|401|expired/i.test(`${ne.error??""} ${ne.stderr??""}`);if(n.push({level:"fail",label:ne.timedOut?"Agent turn never finished \u2014 the model answers, but a real turn with your skills and tools hangs":ye?"Agent turn failed \u2014 your Claude sign-in has expired, so every /write, /review and /catch-up will do nothing":`Agent turn produced nothing \u2014 the model answers, but a real turn with your skills and tools ${ne.producedNothing?"ends instantly with no output":`fails: ${ne.error}`}`,fix:(te?`Claude Code said: "${te}". `:"")+(ye?`Sign in again, then re-run /doctor. ${El}`:"This is the failure behind an empty /write, /review or /catch-up. Run /logs for the whole thing \u2014 it offers to copy it so you can send it to the team.")}),ye){let $e=n.find(ge=>ge.label.startsWith("Claude auth:"));$e&&($e.level="warn",$e.label="Claude auth: a sign-in exists on this machine, but it is no longer valid",$e.fix=`Sign in again. ${El}`)}}}else j.timedOut?n.push({level:"fail",label:"Model unreachable \u2014 no response in 30s (a docs turn will hang, then end with 0 tokens / no output)",fix:`Usually a corporate proxy/firewall or org policy blocking the Claude model API. Check this machine's network access to the Claude endpoint; confirm with: claude -p "say hi"`}):n.push({level:"fail",label:`Model call failed \u2014 ${j.error??"no output"} (a docs turn will end with 0 tokens / no output)`,fix:'Check sign-in, the selected model (/model), and network access to the Claude endpoint; confirm with: claude -p "say hi"'})}let a=cA(e);if(!a)return n.push({level:"fail",label:`No ${lA(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${a.projectId}`});let l=(a.docsDir??uA).replace(/\/+$/,"");n.push(a.mode==="engineer"?{level:"warn",label:"Mode: engineer \u2014 agent may modify any source file (dogfooding)",fix:'Remove "mode" from .d360-writer/config.json for the writer-mode boundary'}:{level:"ok",label:`Mode: writer \u2014 edits limited to ${l}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let c=a.authoritativeSourceFiles??[];n.push(c.length>0?{level:"ok",label:`Sources: docs grounded in ${c.length} path(s) (${c.slice(0,3).join(", ")}${c.length>3?", \u2026":""})`}:{level:"warn",label:"Sources: not set \u2014 docs are grounded in the whole repo",fix:"Run: /scope to choose which files/folders the docs are written from"});let h=a.appType??xA(e);if(h){let j=a.appType?"from config":"auto-detected",ne=h==="web"||h==="cli";n.push({level:"ok",label:`Genre: ${h} (${j})${ne?` \u2192 ${RA(h)} loaded`:" \u2014 no doc-type playbook for this genre yet (generic skills)"}`})}else n.push({level:"warn",label:"Genre: unclassified \u2014 no doc-type playbook is loading (generic output)",fix:"Run /genre <web|cli|service|library> to pick \u2014 raises docs to that genre's craft bar"});let y=hA(),x=Object.keys(y.entries);x.length>0&&n.push({level:"ok",label:`Added deployments: ${x.join(", ")}`,detail:`Not shipped with d360-writer \u2014 read from ${fA()}`});for(let j of y.problems)n.push({level:"warn",label:`Added deployment refused: ${j}`,fix:"Run: d360-writer env list"});let w;try{w=pA(e),n.push({level:"ok",label:`Profile: ${w.name} (${w.connection.name})${w.production?" \u26A0 PRODUCTION":""}`})}catch(j){return n.push({level:"fail",label:`Profile config: ${j.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let S=sA(w.name,w.project.projectId),P=iA(w.name).filter(j=>{let ne=Cp(j);return!!ne&&ne!==w.project.projectId&&!(Al(j)&&!j.refreshToken)}),T=w.project.projectName?`"${w.project.projectName}"`:"this project";S?Al(S)&&!S.refreshToken?n.push({level:"fail",label:S.refreshRejectedAt?`Document360: session ended \u2014 Document360 refused to renew it (${new Date(S.refreshRejectedAt).toLocaleString()})`:"Document360: session expired (no refresh token)",fix:"/login"}):Al(S)?n.push({level:"ok",label:"Document360: logged in (access token expired \u2014 refreshes automatically on the next call)"}):n.push({level:"ok",label:`Document360: logged in to ${T} (until ${new Date(S.expiresAt).toLocaleString()})`}):n.push(P.length>0?{level:"fail",label:`Document360: not signed in to ${T} \u2014 signed in to ${P.map(j=>j.projectName?`"${j.projectName}"`:(Cp(j)??"").slice(0,8)+"\u2026").join(", ")} instead`,fix:`Run: /login and pick ${T} \u2014 each project needs its own sign-in, and both are then kept`}:{level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${w.name})`}),P.length>0&&n.push({level:"ok",label:`Other Document360 projects signed in on this machine: ${P.map(j=>j.projectName?`"${j.projectName}"`:(Cp(j)??"").slice(0,8)+"\u2026").join(", ")} (kept \u2014 each repo uses its own)`}),n.push(w.project.workspaceId?{level:"ok",label:`Workspace: ${w.project.workspaceName??w.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let R=mu(e);if(R.length>1)for(let j of R){let ne=[j.production?"\u26A0 PRODUCTION":null,j.internal?"\u26A0 internal":null].filter(Boolean).join(" ");n.push({level:"ok",label:`${j.active?"\u25CF ":" "}${j.profile} \u2192 ${j.portalUrl||j.environment}${j.project?` \xB7 ${j.project}`:" \xB7 no project"} \xB7 ${j.tracked} tracked${j.signedIn?"":" \xB7 not signed in"}${ne?` \xB7 ${ne}`:""}`,...j.active?{detail:"\u25CF is what /push and /publish act on. Switch with /profile."}:{}})}let N=R.find(j=>j.active);N&&N.unpushed>0&&n.push({level:"warn",label:`${N.unpushed} local article${N.unpushed===1?"":"s"} ${N.unpushed===1?"has":"have"} never been saved to "${N.profile}"`,fix:"Run: /push --all"});for(let j of _m(e))n.push({level:"warn",label:`Profiles ${j.map(ne=>`"${ne}"`).join(" and ")} point at the same Document360 project`,fix:"They track one portal in separate map sections \u2014 keep one, or point one at a different project with /project"});let B=nA(e,w.name),G=rA(e,w.name);if(!B)n.push({level:"ok",label:`Category map: none yet for "${w.name}" (created on first /push)`});else if(G.length>0)for(let j of G)n.push({level:"fail",label:`Category map ${j.field} (${j.recorded}) \u2260 profile ${j.field} (${j.current})`,fix:"This repo\u2019s records belong to a different Document360 project \u2014 to publish somewhere new, connect it as its own profile: /profile"});else{let j=oA(e,w.name),ne=`${Object.keys(B.articles).length} articles, ${Object.keys(B.categories).length} categories`;j?j.unmapped>0?n.push({level:"warn",label:`Category map covers ${j.mappedArticles} of ${j.portalArticles} Document360 articles and ${j.mappedCategories} of ${j.portalCategories} categories`+(j.declined>0?` (${j.declined} declined)`:""),fix:`/pull imports the ${j.unmapped} ${j.unmapped===1?"article":"articles"} this repo has no folder for`}):n.push({level:"ok",label:`Category map: ${ne} \u2014 every Document360 article is tracked here`}):n.push({level:"ok",label:`Category map: ${ne} (not yet compared with Document360)`,fix:"/pull --status compares this repo with Document360"});for(let te of j?.duplicateCategories??[])n.push({level:"warn",label:`Two Document360 categories named "${te.name}" in the same place (${te.ids.join(", ")})`,fix:"Merging or hiding one is your decision \u2014 /restructure moves articles; nothing here deletes"});for(let te of j?.sameNameCategories??[])(j?.duplicateCategories??[]).some(ye=>ye.name.toLowerCase()===te.name.toLowerCase())||n.push({level:"warn",label:`"${te.name}" is a Document360 category in ${te.entries.length} different places (${te.entries.map(ye=>ye.id).join(", ")})`,fix:"Readers see them all. Choose which one they keep: /restructure moves articles, /retire hides a page this repo owns, /untrack disowns one that was never ours"})}n.push(ZT(ub())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${ub()}`,fix:"Reinstall document360-writer (broken install)"});let Q=Qt(e);if(Q.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${We})`}):Q.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${Q.completedVersion}, current is v${We}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),S&&(!Al(S)||S.refreshToken)){let j={profile:w.name,connection:w.connection,projectId:w.project.projectId,projectName:w.project.projectName};try{await tA(j);let te=await eA(j,"/v3/projects");n.push({level:"ok",label:`API reachable (${w.connection.apiUrl}) \u2014 ${te.length} project(s) visible`})}catch(te){n.push({level:"fail",label:`API call failed: ${te.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let ne=B?.projectId??w.project.projectId;if(ne&&w.project.workspaceId){try{let te=await dA(j,ne,w.project.workspaceId);if(te){let ye=(te.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Your Document360 project: reachable on ${w.connection.name} (${te.languages?.length??0} language${(te.languages?.length??0)===1?"":"s"}) \xB7 version ${ye||"(none)"}`})}else n.push({level:"ok",label:`Workspace sync manifest: not live on ${w.connection.name} yet \u2014 sync uses the per-article path (nothing to do)`})}catch(te){te instanceof SA||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(te.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${w.project.projectName??ne})`,fix:"Run /login and pick this repo's project \u2014 your token is scoped to another project"}):n.push({level:"warn",label:`Workspace sync manifest: probe failed (${te.message.slice(0,80)})`})}try{let te=await CA({cwd:e,profileName:w.name,dryRun:!0}),ye=te.categoriesReordered+te.articlesReordered;if(te.skipped==="no category map")n.push({level:"ok",label:"Reading order: nothing to check yet (no articles published)"});else if(te.skipped)n.push({level:"warn",label:`Reading order: can't be checked (${te.skipped})`,fix:"Your article order on Document360 may not match your structure \u2014 /push syncs it once this resolves"});else if(te.unverified)n.push({level:"warn",label:`Reading order: ${te.unverified} of your articles aren't listed by Document360, so their order can't be set`,fix:"Usually means those articles are not live yet (the listing returns published articles). /publish takes them live, then /push re-syncs the order"});else if(ye>0){let $e=[te.categoriesReordered>0?`${te.categoriesReordered} categor${te.categoriesReordered===1?"y":"ies"}`:"",te.articlesReordered>0?`${te.articlesReordered} article${te.articlesReordered===1?"":"s"}`:""].filter(Boolean);n.push({level:"warn",label:`Reading order: ${$e.join(" + ")} out of order on Document360`,fix:"Run /push \u2014 it re-syncs the order from your NN- folder/file prefixes"})}else n.push({level:"ok",label:"Reading order: Document360 matches your structure"});if(te.orphans?.length){let $e=te.orphans;n.push({level:"warn",label:`${$e.length} article${$e.length===1?"":"s"} on Document360 ${$e.length===1?"is":"are"} not in your docs folder: ${$e.slice(0,3).map(ge=>ge.path).join(", ")}${$e.length>3?`, +${$e.length-3} more`:""}`,fix:"/retire <path> takes one off your readers \xB7 /pull <path> brings one back into your docs folder \u2014 until you choose, it stays live and d360-writer leaves it alone"})}}catch(te){n.push({level:"warn",label:`Reading order: check failed (${te.message.slice(0,80)})`})}}}return n}function pb(e){let t=[""];for(let r of e){let s=r.level==="ok"?X("\u2713"):r.level==="warn"?H("\u26A0"):L("\u2717");t.push(` ${s} ${r.label}${r.detail?u(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${u("fix:")} ${Z(r.fix)}`)}let n=e.filter(r=>r.level==="fail").length,o=e.filter(r=>r.level==="warn").length;return t.push(""),t.push(n===0?X(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):L(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function ri(e,t){console.log(u("Running checks\u2026"));for(let n of pb(await db(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var Nl=xr(()=>{"use strict";Vn();Hn();ie();Er()});import{Command as o6}from"commander";import{createRequire as r6}from"node:module";import{AUTH_MODES as s6}from"document360-engine";import{input as px}from"@inquirer/prompts";import{currentEnvironments as hx,loginPkce as fx,getAccessToken as mx,toStoredTokens as gx,clearTokens as yx,decodeJwtClaims as Um,isExpired as wx,loadTokens as gu,saveTokens as bx,listStoredSessions as yu,tokensProjectId as Gn,rememberSessionProject as Fm,resolveActiveProfile as js,setProfileProject as kx,readProjectConfig as $x}from"document360-engine";ie();import{select as F0}from"@inquirer/prompts";import{resolveActiveProfile as Nm,setProfileProject as W0,resolveProjectId as B0,listWorkspaces as H0,ensureSeededContentSwept as G0,seededSweepLines as q0}from"document360-engine";async function Ns(e,t){let n=Nm(e,t),o={profile:n.name,connection:n.connection,projectId:n.project.projectId,projectName:n.project.projectName},r=n.project.projectId??B0(o);return{workspaces:await H0(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var Em=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function uu(e,t){let n=t.toLowerCase();return e.find(o=>(o.name??"").toLowerCase()===n)??e.find(o=>(o.name??"").toLowerCase().startsWith(n))??e.find(o=>o.id.startsWith(t))}function aa(e,t,n,o,r){W0(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function Dm(e,t,n){let o;try{o=await Ns(e,n)}catch(s){return console.log(L(`Could not list workspaces: ${s.message}`)),1}let r=uu(o.workspaces,t);return r?(aa(e,o.profile,o.projectId,r.id,r.name),console.log(X(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(L(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function Rr(e,t){let n;try{n=await Ns(e,t)}catch(c){console.log(L(`Could not list workspaces: ${c.message}`));return}let{workspaces:o,projectId:r,profile:s,current:i}=n;if(o.length===0){console.log(u("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let c of o)console.log(` ${c.id===i?Z("\u25CF"):" "} ${Em(c)} ${u(c.id)}`);console.log(u("Run: d360-writer workspace use <name>"));return}let a=await F0({message:"Select the Document360 workspace for this repo:",choices:o.map(c=>({name:`${Em(c)}${c.id===i?" (current)":""}`,value:c.id}))}),l=o.find(c=>c.id===a);aa(e,s,r,a,l?.name),console.log(X(`\u2713 Workspace set to "${l?.name??a}" for profile "${s}".`)),await V0(e,s,r,a)}async function V0(e,t,n,o){try{let r=Nm(e,t),s=await G0({profile:r.name,connection:r.connection,projectId:n,projectName:r.project.projectName},{cwd:e,profile:r.name,projectId:n,workspaceId:o});for(let i of q0(s))console.log(i)}catch{}}ie();import{select as Y0}from"@inquirer/prompts";import{resolveActiveProfile as K0,setProfileProject as z0,listProjects as X0}from"document360-engine";async function Sn(e,t){let n=K0(e,t),o={profile:n.name,connection:n.connection};return{projects:await X0(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var jm=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function du(e,t){let n=t.toLowerCase();return e.find(o=>(o.name??"").toLowerCase()===n)??e.find(o=>(o.name??"").toLowerCase().startsWith(n))??e.find(o=>o.id.startsWith(t))}function la(e,t,n,o){z0(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function Im(e,t,n){let o;try{o=await Sn(e,n)}catch(s){return console.log(L(`Could not list projects: ${s.message}`)),1}let r=du(o.projects,t);return r?(la(e,o.profile,r.id,r.name),console.log(X(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log(L(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function ca(e,t){let n;try{n=await Sn(e,t)}catch(l){console.log(L(`Could not list projects: ${l.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(u("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let l of o)console.log(` ${l.id===s?Z("\u25CF"):" "} ${jm(l)} ${u(l.id)}`);console.log(u("Run: d360-writer project use <name>"));return}let i=await Y0({message:"Select the Document360 project for this repo:",choices:o.map(l=>({name:`${jm(l)}${l.id===s?" (current)":""}`,value:l.id}))}),a=o.find(l=>l.id===i);la(e,r,i,a?.name),console.log(X(`\u2713 Project set to "${a?.name??i}" for profile "${r}". Next: pick a workspace.`))}ie();import Q0 from"picocolors";function J0(e=process.env){return e.FORCE_HYPERLINK==="0"||!Q0.isColorSupported?!1:e.FORCE_HYPERLINK?!0:!!(e.WT_SESSION||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="WezTerm"||e.TERM_PROGRAM==="ghostty"||e.VTE_VERSION||e.KONSOLE_VERSION)}function Z0(e,t=e,n){return J0(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var ex=/https?:\/\/[^\s\x1b]+/g;function Ds(e,t){return e.replace(ex,n=>Z0(n,n,t))}Hn();function Wm(e){return{...Um(e.idToken)??{},...Um(e.accessToken)??{}}}function ua(e){let t=Wm(e),n=t.email??t.preferred_username??t.sub??"unknown",o=Gn(e),r=e.projectName?` \xB7 project "${e.projectName}"`:o?` \xB7 project ${o}`:"";return`${n}${r}`}async function wu(e,t,n){n&&Fm(e,t,n);try{let{projects:o}=await Sn(process.cwd(),e);for(let r of yu(e)){let s=Gn(r);s&&Fm(e,s,o.find(i=>i.id===s)?.name)}}catch{}}function vx(e,t,n){let o=Gn(e);if(!o||!t||o===t)return null;let r=n?`"${n}"`:t.slice(0,8)+"\u2026";return`\u26A0 You signed in to project ${e.projectName?`"${e.projectName}"`:o.slice(0,8)+"\u2026"}, but this repo's docs live in ${r}. Run /login again and pick ${r} (or /project to point this repo somewhere else).`}async function da(e){let t=js(process.cwd(),e.profile);if(!t.configured&&!e.profile){console.error(L("This repo is not set up yet, so there is no Document360 deployment to sign in to.")),console.error(`Run ${Z("/init")} to pick your region (or ${Z("d360-writer init")}), then sign in.`),console.error(u(`Signing in to one deployment directly: d360-writer login --profile <${hx().join("|")}>`)),process.exitCode=2;return}let n=t.connection;console.log(u(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=Wn(process.cwd(),e.profile);o&&(console.log(H(`\u26A0 ${o.why} \u2014 and signing in does NOT change it (the environment comes from the profile, not the login).`)),console.log(H(` To move: ${o.cmd}${o.replacementProfile?"":", then /login"}`)));let r=await fx(n,{manual:e.manual,promptForRedirect:h=>px({message:h})},h=>console.log(Ds(h))),s=gx(t.name,r);bx(s),await bu(s,t.name,h=>console.log(u(h)));let i=Gn(s),a=js(process.cwd(),e.profile).project;i&&await wu(t.name,i,a.projectId===i?a.projectName:void 0);let l=gu(t.name,i??void 0)??s;console.log(""),console.log(X(`\u2713 Logged in to "${t.name}" as ${ua(l)}`));let c=vx(l,a.projectId,a.projectName);if(c&&console.log(H(c)),console.log(u(` access token expires: ${s.expiresAt}`)),console.log(u(` refresh token: ${s.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{$x(process.cwd())?.profiles?.[t.name]&&(console.log(""),await Rr(process.cwd(),t.name))}catch{}}async function bu(e,t,n){let r=Wm(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(js(process.cwd(),t).project.projectId)return;let i;try{let{projects:a}=await Sn(process.cwd(),t);i=a.find(l=>l.id===r)?.name}catch{}kx(process.cwd(),t,{projectId:r,projectName:i}),n(` Project "${i??r}" written to profile "${t}".`)}catch{}}async function Bm(e){let t=js(process.cwd(),e.profile),n=t.connection,o=gu(t.name,t.project.projectId);if(!o){console.log(L(`Not logged in to Document360 (profile "${t.name}").`));let r=yu(t.name).filter(s=>Gn(s)&&Gn(s)!==t.project.projectId);r.length>0&&console.log(u(`This repo's project needs its own sign-in. Signed in on this machine: ${r.map(s=>s.projectName??Gn(s)).join(", ")}`)),console.log(u(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${Z(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${ua(o)}`),wx(o))if(o.refreshToken)try{await mx({profile:t.name,connection:n,projectId:t.project.projectId,projectName:t.project.projectName});let r=gu(t.name,t.project.projectId);console.log(X(`\u2713 Session refreshed${r?` \u2014 expires ${r.expiresAt}`:""}`))}catch(r){console.log(H(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(u(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(H("Session expired (no refresh token).")),console.log(u(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(u(` expires: ${o.expiresAt}`))}async function Hm(e){let t=js(process.cwd(),e.profile),n=e.allProjects?void 0:t.project.projectId,o=t.project.projectName?`"${t.project.projectName}"`:`profile "${t.name}"`;if(yx(t.name,n)){console.log(X(e.allProjects?`\u2713 Logged out of every Document360 project for profile "${t.name}".`:`\u2713 Logged out of ${o}.`));let r=yu(t.name).filter(s=>Gn(s)).length;r>0&&console.log(u(`Still signed in to ${r} other project${r===1?"":"s"} on this machine.`))}else console.log(u(`No Document360 session for ${o} \u2014 nothing to do.`))}ie();import{readProjectConfig as Gm,writeProjectConfig as xx,resolveActiveProfile as Rx,loadTokens as Sx,isExpired as Cx}from"document360-engine";function pa(e){let t=Gm(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(L("No profiles in .d360-writer/config.json. Run: d360-writer init")),process.exitCode=1;return}console.log("");for(let[n,o]of Object.entries(t.profiles)){let r=n===t.defaultProfile?Z("\u25CF "):" ",s=o.production?H(" \u26A0 PRODUCTION"):"",i=o.connection.environment??"(inline)",a=Sx(n,o.project?.projectId),l=a?Cx(a)&&!a.refreshToken?H("expired"):u("logged in"):u("not logged in");console.log(`${r}${Z(n)} \u2192 ${i}${s} [${l}]`)}console.log(""),console.log(u("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function ha(e,t){let n=Gm(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(L(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,xx(n,e);let o=n.profiles[t].production?H(" \u26A0 PRODUCTION"):"";console.log(X(`\u2713 Default profile is now "${t}"${o}`))}function fa(e,t){try{let n=Rx(e,t);console.log(""),console.log(`Profile ${Z(n.name)}${n.production?H(" \u26A0 PRODUCTION"):""}`),console.log(u(` api: ${n.connection.apiUrl}`)),console.log(u(` identity: ${n.connection.authorizationUrl}`)),console.log(u(` clientId: ${n.connection.clientId}`)),console.log(u(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(u(` project: ${n.project.projectId??"(set at login)"}`)),console.log(u(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(L(n.message)),process.exitCode=1}}ie();import{existsSync as Ym,readdirSync as Px,readFileSync as Tx,statSync as Ax}from"node:fs";import{join as Km}from"node:path";import{apiLogDir as Ex}from"document360-engine";var Nx=30,Dx=12e3;function jx(e){if(!Ym(e))return{api:[],crash:[]};try{let t=Px(e);return{api:t.filter(n=>n.endsWith(".jsonl")).sort().reverse(),crash:t.filter(n=>/^crash-\d{4}-\d{2}-\d{2}\.log$/.test(n)).sort().reverse()}}catch{return{api:[],crash:[]}}}var Ix=/·\s*(empty-turn|agent-subprocess|uncaught|unhandled)\s*===/i,Lx=/·\s*FATAL\s*·/i,Ox=e=>Lx.test(e)||Ix.test(e);function Mx(e){let n=e.split(/\n(?==== \d{4}-\d{2}-\d{2}T)/).map(s=>s.trim()).filter(Boolean).filter(s=>s.startsWith("==="));if(n.length===0)return null;let o=[...n].reverse().find(Ox),r=o??n[n.length-1];return{text:r,when:/^=== (\S+)/.exec(r)?.[1]??"",count:n.length,notable:!!o}}function _x(e,t){let n=t[0];if(!n)return null;try{return Mx(Tx(Km(e,n),"utf8"))}catch{return null}}function qm(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}var Vm=(e,t)=>{try{return`${(Ax(Km(e,t)).size/1024).toFixed(1)} KB`}catch{return""}};function ku(){let e=Ex(),{api:t,crash:n}=jx(e),o=_x(e,n),r=[];if(o){let s=o.text.split(/\r?\n/),i=s.slice(0,Nx);r.push(o.notable?oe("\u2717",`The last thing that went wrong \u2014 ${qm(o.when)}:`):oe("\u2139",`Nothing has failed. The most recent note d360-writer recorded \u2014 ${qm(o.when)}:`)),r.push("");for(let a of i)r.push(` ${a}`);s.length>i.length&&r.push(u(` \u2026${s.length-i.length} more line${s.length-i.length===1?"":"s"} \u2014 the whole thing is in ${n[0]}, and c copies all of it.`)),r.push(""),o.count>1&&r.push(u(` ${o.count} entries recorded today; this is the one worth reading.`)),o.notable&&r.push(u(" If this is not obviously your own doing, send it to the team \u2014 it names what failed.")),r.push("")}else n.length===0&&(r.push(oe("\u2713","Nothing has failed \u2014 d360-writer has recorded no problems.")),r.push(""));if(r.push(`Logs live in ${Z(e)}`),!Ym(e)||t.length===0&&n.length===0)return r.push(u(" Nothing here yet \u2014 logs appear after the first Document360 call.")),{lines:r,copyText:null,notable:!1};if(n.length>0){r.push(""),r.push(`Problem logs ${u("(send these if something crashed or a run did nothing)")}:`);for(let s of n.slice(0,14))r.push(` ${L(s)} ${u(Vm(e,s))}`)}if(t.length>0){r.push(""),r.push("Document360 call logs:");for(let s of t.slice(0,14))r.push(` ${s} ${u(Vm(e,s))}`)}return r.push(""),r.push(u("Failed calls include what was sent and returned (sign-in details removed, 4 KB cap).")),r.push(u("Set D360_LOG_BODIES=1 to record successful calls too.")),{lines:r,copyText:o?o.text.slice(0,Dx):null,notable:!!o?.notable}}async function zm(){return $u(),{kind:"continue"}}function $u(){let{lines:e,copyText:t}=ku();console.log("");for(let n of e)console.log(n);t&&console.log(u("Inside d360-writer, /logs offers to copy this for you.")),console.log("")}ie();Hn();import{existsSync as Ux,readFileSync as Xm}from"node:fs";import{homedir as Fx}from"node:os";import{EnvironmentConfigError as Qm,addedEnvironmentsPath as ma,loadAddedEnvironments as Jm,parseAddedEnvironments as Wx,profileEnvironmentName as Bx,readProjectConfig as Hx,removeAddedEnvironment as Gx,resolveEnvironment as qx,saveAddedEnvironment as Vx}from"document360-engine";function ga(e){let t=Fx();return e.startsWith(t)?`~${e.slice(t.length).replace(/\\/g,"/")}`:e}function Zm(e){let t=Bn(),n=Bx(e),o=Math.max(...t.map(c=>c.name.length)),r=Math.max(...t.map(c=>c.portalUrl.length)),s=["Document360 deployments",""];for(let c of t){let h=c.name===n?`${Z("\u25CF")} `:" ",y=c.note?u(` ${c.note}`):"";s.push(`${h}${Z(c.name.padEnd(o))} ${c.portalUrl.padEnd(r)}${y}`)}let{entries:i,problems:a}=Jm(),l=Object.keys(i);if(s.push(""),n&&s.push(u("\u25CF = where this repo publishes.")),l.length===0?s.push(u("Add a deployment this build does not ship: d360-writer env add <file.json>")):(s.push(u(`Added on this machine: ${ga(ma())}`)),s.push(u("Add another: d360-writer env add <file.json>")),s.push(u(`Remove one: d360-writer env remove ${l[0]}`))),a.length>0){s.push("");let c=a.length===1?"One added deployment could not be loaded:":`${a.length} added deployments could not be loaded:`;s.push(H(oe("\u26A0",c)));for(let h of a)s.push(H(` ${h}`))}return s}function Yx(e){if(e==="-")try{return{text:Xm(0,"utf8"),where:"standard input"}}catch{return null}if(!Ux(e))return null;try{return{text:Xm(e,"utf8"),where:e}}catch{return null}}function eg(e,t){let n=Yx(t);if(!n)return{ok:!1,lines:[L(`Cannot read ${t}.`),u("Pass a JSON file, or - to read the document from standard input.")]};let o;try{o=Wx(n.text,n.where)}catch(a){if(!(a instanceof Qm))throw a;return{ok:!1,lines:[L("That document has problems, so nothing was saved:"),...a.message.split(`
|
|
307
|
-
`).map(l=>L(` ${l}`))]}}let r=Object.keys(o);if(r.length===0)return{ok:!1,lines:[L(`${n.where} defines no deployments.`),u("The document is a JSON object of environment name \u2192 connection fields.")]};let s=[];for(let a of r){let l=
|
|
308
|
-
`).map(i=>L(` ${i}`))]}}if(!n){let s=Object.keys(
|
|
309
|
-
`),process.exit(y)}import{createInterface as
|
|
310
|
-
`)}var $t=[{key:"start",label:"Getting Started",rows:[{t:"text",s:"D360-Writer reads your codebase and writes your user documentation."},{t:"gap"},{t:"text",s:"It publishes to Document360 when you are ready."},{t:"gap"},{t:"text",s:"It needs Claude access \u2014 a subscription, or an ANTHROPIC_API_KEY."},{t:"gap"},{t:"sub",s:"Quick start"},{t:"step",n:1,s:"Run /init. Pick the Document360 deployment you publish to, sign in, choose your project."},{t:"step",n:2,s:"Paste the prompt it prints into your coding agent, and let it finish."},{t:"step",n:3,s:"Run /doctor to confirm every check is green."},{t:"step",n:4,s:'Type "write the docs for this repository".'},{t:"gap"},{t:"dim",s:"Claude Code, Codex and Cursor all work. /devhints re-shows that prompt."},{t:"dim",s:"That's it \u2014 D360-Writer drafts your docs without you writing a line."},{t:"gap"},{t:"sub",s:"Tips"},{t:"text",s:"Just talk to it. Anything not starting with / goes to the agent."},{t:"gap"},{t:"dim",s:"/ browse commands \xB7 \u2191 recall history \xB7 tab run the suggestion"},{t:"dim",s:"1-9 pick from a list \xB7 c copy whatever was offered"},{t:"dim",s:"esc interrupt a run \xB7 ctrl+c twice exit"},{t:"dim",s:"shift+tab switch auto / manual \u2014 see /auto"}]},{key:"agentic",label:"Agentic",rows:[{t:"text",s:"Agentic mode is for products built with an AI coding agent."},{t:"gap"},{t:"text",s:"Your coding agent ships features and leaves notes."},{t:"text",s:"D360-Writer turns those notes into user documentation."},{t:"gap"},{t:"dim",s:"Think of it as a Technical Writer dedicated to your project."},{t:"gap"},{t:"sub",s:"Auto or manual"},{t:"gap"},{t:"text",s:"In MANUAL mode I work out the next step and offer it. You press tab."},{t:"gap"},{t:"text",s:"In AUTO mode I run that step myself, then the one after it."},{t:"gap"},{t:"dim",s:" write \u2192 review \u2192 check the style \u2192 save \u2192 go live"},{t:"gap"},{t:"text",s:"Start a build, come back to a finished knowledge base."},{t:"gap"},{t:"cmd",name:"/auto on",s:"Let me run my own next step."},{t:"cmd",name:"/auto --budget",s:"Cap what one run may spend. The standard cap is $200."},{t:"gap"},{t:"dim",s:" shift+tab switches mode \xB7 esc stops a run"},{t:"dim",s:" Nothing already written, saved or published is undone."},{t:"gap"},{t:"text",s:"Auto changes who presses the key. It does not change what is checked."},{t:"gap"},{t:"text",s:"Every gate still runs."},{t:"text",s:"An article that fails one stays a draft, and the report names it."},{t:"gap"},{t:"text",s:"Screenshots are never automatic \u2014 they need your app on screen."},{t:"gap"},{t:"sub",s:"Every few days"},{t:"cmd",name:"/catch-up",s:"Write up everything pending. It all lands as a draft."},{t:"dim",s:" A note whose code your builder has not committed waits, and they get asked."},{t:"dim",s:" --include-unfinished write those pages anyway"},{t:"cmd",name:"/review --fix",s:"A senior editor reads every article and fixes it."},{t:"cmd",name:"/push --all",s:"Save the reviewed articles to Document360, as drafts."},{t:"cmd",name:"/publish --all",s:"Take those drafts live. It lists them and asks first."},{t:"gap"},{t:"dim",s:" An editorial read is required before anything goes live."},{t:"dim",s:" /review --blocked only the articles publishing is stuck on"},{t:"dim",s:" /review --stale only the ones this editor has not read yet"},{t:"gap"},{t:"sub",s:"Whenever you need"},{t:"cmd",name:"/discover",s:"Interview your builder. Pins a product brief for the docs."},{t:"cmd",name:"/audit",s:"What changed in the code, what is missing from the docs."},{t:"cmd",name:"/audit --decline <path>",s:"That folder or file needs no article. Stops it being reported. Bare: lists what you could decline."},{t:"cmd",name:"/pull",s:"Bring down portal edits and any new portal articles."},{t:"cmd",name:"/resolve",s:"Settle a conflict: keep yours, take the portal, or skip."},{t:"cmd",name:"/comments",s:"Reviewer comments on your articles. Read one, answer it."},{t:"cmd",name:"/inbox",s:"Act on your coding agent's messages."},{t:"cmd",name:"/ask",s:"Ask your developers what the code cannot answer."},{t:"gap"},{t:"dim",s:" An answer fixes the article, saves the draft and replies in the thread."}]},{key:"assistant",label:"Assistant",rows:[{t:"text",s:"D360-Writer is your writing assistant."},{t:"gap"},{t:"text",s:"It does the writing. You decide what gets written, and when."},{t:"gap"},{t:"text",s:"Best for large monorepos: point it at one feature or one set of folders."},{t:"gap"},{t:"sub",s:"Just ask"},{t:"good",s:'"Write the docs for the Multiple JWT feature we shipped last release."'},{t:"gap"},{t:"sub",s:"Or drive it yourself"},{t:"cmd",name:"/scope",s:"Focus on specific source folders."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from its PRDs and the code."},{t:"cmd",name:"/write",s:"Write the planned articles."},{t:"cmd",name:"/push",s:"Save them to Document360 as drafts."},{t:"cmd",name:"/publish",s:"Take the drafts live to your readers."},{t:"cmd",name:"/status",s:"What stands between your work and your readers. Free."},{t:"gap"},{t:"dim",s:" /write --preview shows the plan and the cost first."},{t:"dim",s:" /push --preview <path> shows exactly what Document360 would receive."},{t:"gap"},{t:"sub",s:"One place for what repeats"},{t:"gap"},{t:"text",s:"A variable holds a value \u2014 your product name, a URL \u2014 in one place."},{t:"text",s:"Change it there and every article changes."},{t:"gap"},{t:"text",s:"A snippet does the same for a whole block, like who to contact."},{t:"gap"},{t:"text",s:"A term is defined once, and every article is checked for explaining it."},{t:"gap"},{t:"cmd",name:"/reuse",s:"What your project already keeps on Document360."},{t:"cmd",name:"/reuse pull",s:"Refresh that list from Document360."},{t:"cmd",name:"/reuse add",s:'Create one there: /reuse add variable <name> "<value>".'},{t:"cmd",name:"/reuse audit",s:"Read every article and find what belongs in one place."},{t:"cmd",name:"/terms",s:"Is the same thing called the same name everywhere?"},{t:"cmd",name:"/eval",s:"How does the whole knowledge base score? Free."},{t:"gap"},{t:"dim",s:" Reading is free. Nothing is created until you pick it."},{t:"gap"},{t:"sub",s:"Taking a page back"},{t:"cmd",name:"/retire <path>",s:"Stop showing an article to readers. /push puts it back."},{t:"cmd",name:"/untrack <path>",s:"Disown an imported page that is not one of your docs."},{t:"gap"},{t:"dim",s:" Neither deletes anything. History and reviewer comments stay."}]},{key:"shots",label:"Screenshots",rows:[{t:"text",s:"Documenting a web app? D360-Writer marks where an image helps."},{t:"gap"},{t:"text",s:"The companion CLI d360-capture turns those marks into real,"},{t:"text",s:"annotated screenshots by driving your app in a browser."},{t:"gap"},{t:"sub",s:"Flow"},{t:"step",n:1,s:"Write your docs as usual. Placeholders go in where visuals help."},{t:"step",n:2,s:"Run /screenshot author --all to write the capture specs."},{t:"step",n:3,s:"Stage what the checklist asks for, then /screenshot capture."},{t:"step",n:4,s:"The callouts are drawn on straight after. No browser needed."},{t:"step",n:5,s:"Each finished picture is checked, then marked \u2714 verified."},{t:"step",n:6,s:"Run /push --screenshots so the images embed on Document360."},{t:"gap"},{t:"sub",s:"One command family"},{t:"cmd",name:"/screenshot",s:"Pick what to do next."},{t:"cmd",name:"/screenshot author",s:"Write the capture specs."},{t:"cmd",name:"/screenshot capture",s:"Take the shots."},{t:"cmd",name:"/screenshot annotate",s:"Draw the callouts on shots already taken."},{t:"cmd",name:"/screenshot verify",s:"Judge the finished pictures and mark them verified."},{t:"cmd",name:"/screenshot checklist",s:"What to stage, and the test-ids to ask your dev for."},{t:"cmd",name:"/screenshot list",s:"Progress by chapter, and the worklist."},{t:"gap"},{t:"dim",s:" Each takes an <id>, a path, or --all."},{t:"dim",s:" capture --failed re-runs what did not work \xB7 --blocked what waited on data"},{t:"dim",s:" annotate --force re-draws after a wording or style change"},{t:"gap"},{t:"sub",s:"What each state means"},{t:"text",s:"\u2714 verified finished \u2014 this is the finish line"},{t:"text",s:"\u25C8 to verify the picture is done, waiting to be looked at"},{t:"text",s:"\u25CF to annotate shot taken, callouts not drawn on yet"},{t:"text",s:"\u25D0 ready the spec is written, the shot not taken"},{t:"text",s:"\u2691 rejected the shot ran but the picture is wrong"},{t:"text",s:"\u2298 blocked your app lacked the data the shot needs"},{t:"text",s:"\u2717 broken the spec itself is out of date"},{t:"text",s:"\u25CB to-spec no spec written yet"},{t:"gap"},{t:"dim",s:" rejected \u2014 the spec is usually fixed for you, then capture --failed re-shoots"},{t:"dim",s:" blocked \u2014 /screenshot list groups every blocker into a few things to stage"},{t:"dim",s:" broken \u2014 re-author with /screenshot <id>; a re-capture would fail the same way"},{t:"gap"},{t:"dim",s:"One-time setup in your app repo:"},{t:"dim",s:" npm i -g document360-capture \xB7 d360-capture init \xB7 d360-capture auth"}]},{key:"cmds",label:"Commands",rows:[{t:"dim",s:"Every command, one line each \u2014 type / for the full usage."},{t:"dim",s:"The tabs above teach the ones worth more than a line."},{t:"gap"},{t:"sub",s:"Getting started"},{t:"cmd",name:"/init",s:"Set up Document360 and the coding-agent hand-off."},{t:"cmd",name:"/login",s:"Sign in \u2014 one sign-in per project, all kept."},{t:"cmd",name:"/project",s:"Choose the Document360 project."},{t:"cmd",name:"/workspace",s:"Switch the workspace."},{t:"cmd",name:"/scope",s:"Choose which repo folders back the docs."},{t:"cmd",name:"/genre",s:"What kind of product this is \u2014 picks the writing guide."},{t:"cmd",name:"/devhints",s:"Re-show the prompt to paste into your coding agent."},{t:"cmd",name:"/mcp",s:"Connect MCP servers (Notion, Linear, \u2026)."},{t:"gap"},{t:"sub",s:"Agentic \u2014 keep docs in sync"},{t:"cmd",name:"/roadmap",s:"The docs campaign: progress and the next step."},{t:"cmd",name:"/catch-up",s:"Do all pending work \u2192 drafts. --push also saves them."},{t:"cmd",name:"/auto",s:"Run the next step myself instead of waiting for you."},{t:"cmd",name:"/audit",s:"What changed in the code, what's missing from the docs."},{t:"cmd",name:"/inbox",s:"Act on your coding agent's messages."},{t:"cmd",name:"/ask",s:"Ask your developers what the code cannot answer."},{t:"cmd",name:"/share",s:"Get your builder's latest, send yours (automatic)."},{t:"gap"},{t:"sub",s:"Assistant \u2014 directed writing"},{t:"cmd",name:"/discover",s:"Interview your builder \u2192 a product brief for the docs."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from its PRDs and the code."},{t:"cmd",name:"/write",s:"Write the planned articles. --preview costs first."},{t:"cmd",name:"/preview",s:"Render an article locally."},{t:"cmd",name:"/reorder",s:"Put a category's articles in the best reading order."},{t:"cmd",name:"/restructure",s:"Move an article to another category, split one, merge two, rename one."},{t:"cmd",name:"/structure",s:"The reading order, as it will appear on Document360."},{t:"gap"},{t:"sub",s:"Quality \u2014 before you publish"},{t:"cmd",name:"/style-guide",s:"Choose the writing rules your docs are held to."},{t:"cmd",name:"/lint",s:"The machine pass over those rules. Free. --fix corrects."},{t:"cmd",name:"/review",s:"The editor pass. Required before anything goes live."},{t:"cmd",name:"/terms",s:"Is the same thing called the same name everywhere? Free."},{t:"cmd",name:"/eval",s:"Score the whole set: links, shape, naming. Free."},{t:"cmd",name:"/reuse",s:"The terms, values and blocks kept on Document360."},{t:"gap"},{t:"sub",s:"Publish & sync"},{t:"cmd",name:"/status",s:"What stands between your work and your readers. Free."},{t:"cmd",name:"/push",s:"Save your articles to Document360 as drafts."},{t:"cmd",name:"/publish",s:"Take the drafts live to your readers. Asks first."},{t:"cmd",name:"/pull",s:"Portal edits + new portal articles. --status: report only."},{t:"cmd",name:"/resolve",s:"Settle a local\u2194portal conflict: keep, take, or skip."},{t:"cmd",name:"/comments",s:"Reviewer comments on your articles \u2014 read and answer."},{t:"cmd",name:"/retire",s:"Take an article off your readers. Nothing is deleted."},{t:"cmd",name:"/untrack",s:"Disown an imported page that is not one of your docs."},{t:"gap"},{t:"sub",s:"Screenshots"},{t:"cmd",name:"/screenshot",s:"The screenshot pipeline. Bare: pick what to do next."},{t:"dim",s:" author \xB7 capture \xB7 annotate \xB7 verify \xB7 checklist \xB7 list"},{t:"gap"},{t:"sub",s:"Setup & health"},{t:"cmd",name:"/model",s:"Set the Claude model."},{t:"cmd",name:"/verbose",s:"Raw transcript: every tool call, path and result."},{t:"cmd",name:"/profile",s:"Where this repo publishes. Switch, or connect another environment."},{t:"cmd",name:"/allow-prod",s:"Authorize taking articles live on a production profile."},{t:"cmd",name:"/env",s:"The deployments this machine can reach. Add one from a JSON file."},{t:"cmd",name:"/doctor",s:"Health check \u2014 including a real agent turn."},{t:"cmd",name:"/logs",s:"The last problem, in full. Press `c` to copy it."},{t:"cmd",name:"/update",s:"Update D360-Writer, and d360-capture if installed."},{t:"cmd",name:"/feedback",s:"Copy this repo's open feedback, to relay to the team."},{t:"cmd",name:"/logout",s:"Sign out of this project. --all-projects: all of them."},{t:"cmd",name:"/reset",s:"Delete all D360-Writer files (confirms first)."},{t:"gap"},{t:"sub",s:"Session"},{t:"cmd",name:"/resume",s:"Resume a saved session."},{t:"cmd",name:"/rename",s:"Name the session."},{t:"cmd",name:"/clear",s:"Clear the screen and reset the conversation."},{t:"cmd",name:"/help",s:"Show this help."},{t:"cmd",name:"/exit",s:"Quit."}]}],ag=24;function xu(e){let t=e.filter(n=>n.t==="cmd").map(n=>n.name.length);return t.length===0?ag:Math.min(ag,Math.max(...t))}var lg=2;function ka(e,t,n,o){let r=" ".repeat(2+n+lg),s=Math.max(24,o-r.length-2),i=ln(t,s);return e.length>n?{nameCell:e,descLines:i,indent:r,nameOwnLine:!0}:{nameCell:e.padEnd(n+lg-1),descLines:i,indent:r,nameOwnLine:!1}}function tR(e,t,n){switch(e.t){case"head":return e.s;case"text":return` ${e.s}`;case"dim":return` ${e.s}`;case"sub":return e.s;case"good":return` ${e.s}`;case"step":return` ${e.n}. ${e.s}`;case"cmd":{let o=ka(e.name,e.s,t,n),r=o.descLines.slice(o.nameOwnLine?0:1).map(i=>`${o.indent}${i}`);return[o.nameOwnLine?` ${o.nameCell}`:` ${o.nameCell} ${o.descLines[0]??""}`,...r].join(`
|
|
311
|
-
`)}case"gap":return""}}function
|
|
306
|
+
`)?"":i;Tg(t,`${o}${a}${s.join(i)}${i}`,"utf8")}async function Iu(){let e=process.cwd(),t=jg(e);if(Er(t)&&!await RR({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(u("init canceled.")),{kind:"continue"};let n=Mg(e)??Eg(e),o=await Ca({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await Ca({message:"Capture directory (where document360-capture .spec.ts files live):",default:Lg}),s=await Ca({message:"Screenshot output directory:",default:Og}),i=Gn().filter(w=>!w.retired),a=Math.max(...i.map(w=>w.portalUrl.length))+3,l=await SR({message:"Which Document360 deployment do these docs publish to?",choices:i.map(w=>({name:`${w.name.padEnd(16)}${w.portalUrl.padEnd(a)}${w.note?`(${w.note})`:""}`.trimEnd(),value:w.name}))}),c=await Ca({message:"Name for this connection profile:",default:l}),h={projectId:o,docsDir:Ig,captureDir:r,outputDir:s,profiles:{[c]:{connection:{environment:l}}},defaultProfile:c,authoritativeSourceFiles:_g(e)},y=PR(e);y?.terminologyGlossary&&(h.terminologyGlossary=y.terminologyGlossary),Dg(h,e),ju(e);let x=Tr(e);console.log(""),console.log(X(`\u2713 Wrote ${t}`)),AR(l)&&(console.log(""),console.log(`\u26A0 ${l} is a live deployment \u2014 ${ER(l).portalUrl}`),console.log(u(" Drafts save freely. Taking articles live needs --yes, or /allow-prod in the app."))),console.log(""),console.log(`Next: ${Z(`d360-writer login --profile ${c}`)} ${u("(sign in; project & workspace auto-selected)")}`),console.log("");for(let w of Ar(x))console.log(w);return console.log(""),console.log(`${u("Then ask:")} ${Z('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function Mg(e){let t=Pa(e,"package.json");if(!Er(t))return null;try{return JSON.parse(Ng(t,"utf8")).name??null}catch{return null}}function _g(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Er(Pa(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Pa(e,n);Er(o)&&!NR(o)&&t.push(n)}return t}function NR(e){try{return CR(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var Ag,Ta=Rr(()=>{"use strict";ae();qn();Kn();Ag=[".sessions/","cache/"]});import{createRequire as VR}from"node:module";import{existsSync as YR,readFileSync as KR}from"node:fs";import{dirname as zg,join as Xg}from"node:path";function Rt(){let e;try{e=zR.resolve("document360-capture/helpers")}catch{return null}let t=zg(e);for(let n=0;n<5&&!YR(Xg(t,"package.json"));n++)t=zg(t);try{let n=JSON.parse(KR(Xg(t,"package.json"),"utf8"));return n.name==="document360-capture"&&n.version?n.version:null}catch{return null}}var zR,Nr=Rr(()=>{"use strict";zR=VR(import.meta.url)});var yb={};Nm(yb,{doctorCommand:()=>ii,renderDoctorChecks:()=>gb,runDoctorChecks:()=>mb});import{existsSync as aA}from"node:fs";import{d360GetAll as lA,getAccessToken as cA,isExpired as El,loadProfileMap as uA,loadCoverage as dA,danglingCount as pA,profileIdentityDrift as hA,loadTokens as fA,listStoredSessions as mA,tokensProjectId as Pp,packageSkillsDir as fb,ENGINE_VERSION as gA,projectConfigPath as yA,readProjectConfig as wA,DEFAULT_DOCS_DIR as bA,fetchManifestSummary as kA,resolveActiveProfile as $A,loadAddedEnvironments as vA,addedEnvironmentsPath as xA,classifyClaudeAuth as RA,resolveAuthOrigin as SA,authOriginLine as CA,authOriginFix as PA,CLAUDE_CODE_SETUP_HINT as Nl,resolveModelSetting as TA,probeModel as AA,probeAgentTurn as EA,stderrHeadline as NA,detectAppType as DA,playbookSkillName as jA,D360AuthError as IA,applyStructureOrder as LA}from"document360-engine";async function mb(e,t){let n=[],o=Rt();n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${gA}${o?` \xB7 capture v${o}`:" \xB7 capture not installed"}`});let r=Number(process.versions.node.split(".")[0]);n.push(r>=20?{level:"ok",label:`Node ${process.versions.node}`}:{level:"fail",label:`Node ${process.versions.node} \u2014 20+ required`,fix:"Install Node 20 or later (nodejs.org)"});let s=RA();if(s.state==="ready"){let N=SA(),ne=PA(N);n.push({level:ne?"warn":"ok",label:`Claude auth: ${CA(N).replace(/^Claude: /,"")}`,...ne?{fix:ne}:{}})}else s.state==="maybe"?n.push({level:"warn",label:"Claude: no Claude Code login found (may be in the macOS Keychain)",fix:`If a docs turn ends with no output, sign in to Claude Code. ${Nl}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:Nl});let i=TA(e);if(n.push({level:"ok",label:`Model: ${i.model} (${i.source==="auto"?"auto \u2014 right-sized for docs; /model to change":i.source})`}),s.state==="ready"){let N=await AA(e,i.model??void 0);if(N.ok){n.push({level:"ok",label:`Model reachable \u2014 replied in ${(N.latencyMs/1e3).toFixed(1)}s`});let ne=await EA(e,i.model??void 0);if(ne.ok)n.push({level:"ok",label:`Agent turn works \u2014 ran with your skills and tools in ${(ne.latencyMs/1e3).toFixed(1)}s`});else{let te=NA(ne.stderr),he=/auth|sign.?in|login|credential|token|401|expired/i.test(`${ne.error??""} ${ne.stderr??""}`);if(n.push({level:"fail",label:ne.timedOut?"Agent turn never finished \u2014 the model answers, but a real turn with your skills and tools hangs":he?"Agent turn failed \u2014 your Claude sign-in has expired, so every /write, /review and /catch-up will do nothing":`Agent turn produced nothing \u2014 the model answers, but a real turn with your skills and tools ${ne.producedNothing?"ends instantly with no output":`fails: ${ne.error}`}`,fix:(te?`Claude Code said: "${te}". `:"")+(he?`Sign in again, then re-run /doctor. ${Nl}`:"This is the failure behind an empty /write, /review or /catch-up. Run /logs for the whole thing \u2014 it offers to copy it so you can send it to the team.")}),he){let we=n.find(ye=>ye.label.startsWith("Claude auth:"));we&&(we.level="warn",we.label="Claude auth: a sign-in exists on this machine, but it is no longer valid",we.fix=`Sign in again. ${Nl}`)}}}else N.timedOut?n.push({level:"fail",label:"Model unreachable \u2014 no response in 30s (a docs turn will hang, then end with 0 tokens / no output)",fix:`Usually a corporate proxy/firewall or org policy blocking the Claude model API. Check this machine's network access to the Claude endpoint; confirm with: claude -p "say hi"`}):n.push({level:"fail",label:`Model call failed \u2014 ${N.error??"no output"} (a docs turn will end with 0 tokens / no output)`,fix:'Check sign-in, the selected model (/model), and network access to the Claude endpoint; confirm with: claude -p "say hi"'})}let a=wA(e);if(!a)return n.push({level:"fail",label:`No ${yA(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${a.projectId}`});let l=(a.docsDir??bA).replace(/\/+$/,"");n.push(a.mode==="engineer"?{level:"warn",label:"Mode: engineer \u2014 agent may modify any source file (dogfooding)",fix:'Remove "mode" from .d360-writer/config.json for the writer-mode boundary'}:{level:"ok",label:`Mode: writer \u2014 edits limited to ${l}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let c=a.authoritativeSourceFiles??[];n.push(c.length>0?{level:"ok",label:`Sources: docs grounded in ${c.length} path(s) (${c.slice(0,3).join(", ")}${c.length>3?", \u2026":""})`}:{level:"warn",label:"Sources: not set \u2014 docs are grounded in the whole repo",fix:"Run: /scope to choose which files/folders the docs are written from"});let h=a.appType??DA(e);if(h){let N=a.appType?"from config":"auto-detected",ne=h==="web"||h==="cli";n.push({level:"ok",label:`Genre: ${h} (${N})${ne?` \u2192 ${jA(h)} loaded`:" \u2014 no doc-type playbook for this genre yet (generic skills)"}`})}else n.push({level:"warn",label:"Genre: unclassified \u2014 no doc-type playbook is loading (generic output)",fix:"Run /genre <web|cli|service|library> to pick \u2014 raises docs to that genre's craft bar"});let y=vA(),x=Object.keys(y.entries);x.length>0&&n.push({level:"ok",label:`Added deployments: ${x.join(", ")}`,detail:`Not shipped with d360-writer \u2014 read from ${xA()}`});for(let N of y.problems)n.push({level:"warn",label:`Added deployment refused: ${N}`,fix:"Run: d360-writer env list"});let w;try{w=$A(e),n.push({level:"ok",label:`Profile: ${w.name} (${w.connection.name})${w.production?` ${Ye}`:""}`})}catch(N){return n.push({level:"fail",label:`Profile config: ${N.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let S=fA(w.name,w.project.projectId),P=mA(w.name).filter(N=>{let ne=Pp(N);return!!ne&&ne!==w.project.projectId&&!(El(N)&&!N.refreshToken)}),T=w.project.projectName?`"${w.project.projectName}"`:"this project";S?El(S)&&!S.refreshToken?n.push({level:"fail",label:S.refreshRejectedAt?`Document360: session ended \u2014 Document360 refused to renew it (${new Date(S.refreshRejectedAt).toLocaleString()})`:"Document360: session expired (no refresh token)",fix:"/login"}):El(S)?n.push({level:"ok",label:"Document360: logged in (access token expired \u2014 refreshes automatically on the next call)"}):n.push({level:"ok",label:`Document360: logged in to ${T} (until ${new Date(S.expiresAt).toLocaleString()})`}):n.push(P.length>0?{level:"fail",label:`Document360: not signed in to ${T} \u2014 signed in to ${P.map(N=>N.projectName?`"${N.projectName}"`:(Pp(N)??"").slice(0,8)+"\u2026").join(", ")} instead`,fix:`Run: /login and pick ${T} \u2014 each project needs its own sign-in, and both are then kept`}:{level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${w.name})`}),P.length>0&&n.push({level:"ok",label:`Other Document360 projects signed in on this machine: ${P.map(N=>N.projectName?`"${N.projectName}"`:(Pp(N)??"").slice(0,8)+"\u2026").join(", ")} (kept \u2014 each repo uses its own)`}),n.push(w.project.workspaceId?{level:"ok",label:`Workspace: ${w.project.workspaceName??w.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let R=gu(e);if(R.length>1)for(let N of R){let ne=[N.production?"production":null,N.internal?"internal":null].filter(Boolean).join(" \xB7 ");n.push({level:"ok",label:`${N.active?"\u25CF ":" "}${N.profile} \u2192 ${N.portalUrl||N.environment}${N.project?` \xB7 ${N.project}`:" \xB7 no project"} \xB7 ${N.tracked} tracked${N.signedIn?"":" \xB7 not signed in"}${ne?` \xB7 ${ne}`:""}`,...N.active?{detail:"\u25CF is what /push and /publish act on. Switch with /profile."}:{}})}let D=R.find(N=>N.active);D&&D.unpushed>0&&n.push({level:"warn",label:`${D.unpushed} local article${D.unpushed===1?"":"s"} ${D.unpushed===1?"has":"have"} never been saved to "${D.profile}"`,fix:"Run: /push --all"});for(let N of Wm(e))n.push({level:"warn",label:`Profiles ${N.map(ne=>`"${ne}"`).join(" and ")} point at the same Document360 project`,fix:"They track one portal in separate map sections \u2014 keep one, or point one at a different project with /project"});let B=uA(e,w.name),G=hA(e,w.name);if(!B)n.push({level:"ok",label:`Category map: none yet for "${w.name}" (created on first /push)`});else if(G.length>0)for(let N of G)n.push({level:"fail",label:`Category map ${N.field} (${N.recorded}) \u2260 profile ${N.field} (${N.current})`,fix:"This repo\u2019s records belong to a different Document360 project \u2014 to publish somewhere new, connect it as its own profile: /profile"});else{let N=dA(e,w.name),ne=`${Object.keys(B.articles).length} articles, ${Object.keys(B.categories).length} categories`;N?N.unmapped>0?n.push({level:"warn",label:`Category map covers ${N.mappedArticles} of ${N.portalArticles} Document360 articles and ${N.mappedCategories} of ${N.portalCategories} categories`+(N.declined>0?` (${N.declined} declined)`:""),fix:`/pull imports the ${N.unmapped} ${N.unmapped===1?"article":"articles"} this repo has no folder for`}):n.push({level:"ok",label:`Category map: ${ne} \u2014 every Document360 article is tracked here`}):n.push({level:"ok",label:`Category map: ${ne} (not yet compared with Document360)`,fix:"/pull --status compares this repo with Document360"});let te=pA(N);if(te!==null&&te>0){let he=N?.dangling?.articles.length??0,we=N?.dangling?.categories.length??0;n.push({level:"warn",label:`${te} map ${te===1?"entry points":"entries point"} at something Document360 no longer has`+(he>0&&we>0?` (${he} articles, ${we} categories)`:""),detail:(N?.dangling?.articles??[]).slice(0,3).join(", ")||void 0,fix:"/push saves them again for your readers, /untrack drops the ones you no longer want \u2014 /status lists them"})}for(let he of N?.duplicateCategories??[])n.push({level:"warn",label:`Two Document360 categories named "${he.name}" in the same place (${he.ids.join(", ")})`,fix:"Merging or hiding one is your decision \u2014 /restructure moves articles; nothing here deletes"});for(let he of N?.sameNameCategories??[])(N?.duplicateCategories??[]).some(we=>we.name.toLowerCase()===he.name.toLowerCase())||n.push({level:"warn",label:`"${he.name}" is a Document360 category in ${he.entries.length} different places (${he.entries.map(we=>we.id).join(", ")})`,fix:"Readers see them all. Choose which one they keep: /restructure moves articles, /retire hides a page this repo owns, /untrack disowns one that was never ours"})}n.push(aA(fb())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${fb()}`,fix:"Reinstall document360-writer (broken install)"});let Q=en(e);if(Q.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${We})`}):Q.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${Q.completedVersion}, current is v${We}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),S&&(!El(S)||S.refreshToken)){let N={profile:w.name,connection:w.connection,projectId:w.project.projectId,projectName:w.project.projectName};try{await cA(N);let te=await lA(N,"/v3/projects");n.push({level:"ok",label:`API reachable (${w.connection.apiUrl}) \u2014 ${te.length} project(s) visible`})}catch(te){n.push({level:"fail",label:`API call failed: ${te.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let ne=B?.projectId??w.project.projectId;if(ne&&w.project.workspaceId){try{let te=await kA(N,ne,w.project.workspaceId);if(te){let he=(te.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Your Document360 project: reachable on ${w.connection.name} (${te.languages?.length??0} language${(te.languages?.length??0)===1?"":"s"}) \xB7 version ${he||"(none)"}`})}else n.push({level:"ok",label:`Workspace sync manifest: not live on ${w.connection.name} yet \u2014 sync uses the per-article path (nothing to do)`})}catch(te){te instanceof IA||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(te.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${w.project.projectName??ne})`,fix:"Run /login and pick this repo's project \u2014 your token is scoped to another project"}):n.push({level:"warn",label:`Workspace sync manifest: probe failed (${te.message.slice(0,80)})`})}try{let te=await LA({cwd:e,profileName:w.name,dryRun:!0}),he=te.categoriesReordered+te.articlesReordered;if(te.skipped==="no category map")n.push({level:"ok",label:"Reading order: nothing to check yet (no articles published)"});else if(te.skipped)n.push({level:"warn",label:`Reading order: can't be checked (${te.skipped})`,fix:"Your article order on Document360 may not match your structure \u2014 /push syncs it once this resolves"});else if(te.unverified)n.push({level:"warn",label:`Reading order: ${te.unverified} of your articles aren't listed by Document360, so their order can't be set`,fix:"Usually means those articles are not live yet (the listing returns published articles). /publish takes them live, then /push re-syncs the order"});else if(he>0){let we=[te.categoriesReordered>0?`${te.categoriesReordered} categor${te.categoriesReordered===1?"y":"ies"}`:"",te.articlesReordered>0?`${te.articlesReordered} article${te.articlesReordered===1?"":"s"}`:""].filter(Boolean);n.push({level:"warn",label:`Reading order: ${we.join(" + ")} out of order on Document360`,fix:"Run /push \u2014 it re-syncs the order from your NN- folder/file prefixes"})}else n.push({level:"ok",label:"Reading order: Document360 matches your structure"});if(te.orphans?.length){let we=te.orphans;n.push({level:"warn",label:`${we.length} article${we.length===1?"":"s"} on Document360 ${we.length===1?"is":"are"} not in your docs folder: ${we.slice(0,3).map(ye=>ye.path).join(", ")}${we.length>3?`, +${we.length-3} more`:""}`,fix:"/retire <path> takes one off your readers \xB7 /pull <path> brings one back into your docs folder \u2014 until you choose, it stays live and d360-writer leaves it alone"})}}catch(te){n.push({level:"warn",label:`Reading order: check failed (${te.message.slice(0,80)})`})}}}return n}function gb(e){let t=[""];for(let r of e){let s=r.level==="ok"?X("\u2713"):r.level==="warn"?H("\u26A0"):L("\u2717");t.push(` ${s} ${r.label}${r.detail?u(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${u("fix:")} ${Z(r.fix)}`)}let n=e.filter(r=>r.level==="fail").length,o=e.filter(r=>r.level==="warn").length;return t.push(""),t.push(n===0?X(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):L(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function ii(e,t){console.log(u("Running checks\u2026"));for(let n of gb(await mb(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var Dl=Rr(()=>{"use strict";Kn();qn();ae();Nr()});import{Command as b6}from"commander";import{createRequire as k6}from"node:module";import{AUTH_MODES as $6}from"document360-engine";import{input as bx}from"@inquirer/prompts";import{currentEnvironments as kx,loginPkce as $x,getAccessToken as vx,toStoredTokens as xx,clearTokens as Rx,decodeJwtClaims as Bm,isExpired as Sx,loadTokens as yu,saveTokens as Cx,listStoredSessions as wu,tokensProjectId as Vn,rememberSessionProject as Hm,resolveActiveProfile as Ls,setProfileProject as Px,readProjectConfig as Tx}from"document360-engine";ae();import{select as Y0}from"@inquirer/prompts";import{resolveActiveProfile as Im,setProfileProject as K0,resolveProjectId as z0,listWorkspaces as X0,ensureSeededContentSwept as Q0,seededSweepLines as J0}from"document360-engine";async function js(e,t){let n=Im(e,t),o={profile:n.name,connection:n.connection,projectId:n.project.projectId,projectName:n.project.projectName},r=n.project.projectId??z0(o);return{workspaces:await X0(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var jm=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function du(e,t){let n=t.toLowerCase();return e.find(o=>(o.name??"").toLowerCase()===n)??e.find(o=>(o.name??"").toLowerCase().startsWith(n))??e.find(o=>o.id.startsWith(t))}function la(e,t,n,o,r){K0(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function Lm(e,t,n){let o;try{o=await js(e,n)}catch(s){return console.log(L(`Could not list workspaces: ${s.message}`)),1}let r=du(o.workspaces,t);return r?(la(e,o.profile,o.projectId,r.id,r.name),console.log(X(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(L(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function Sr(e,t){let n;try{n=await js(e,t)}catch(c){console.log(L(`Could not list workspaces: ${c.message}`));return}let{workspaces:o,projectId:r,profile:s,current:i}=n;if(o.length===0){console.log(u("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let c of o)console.log(` ${c.id===i?Z("\u25CF"):" "} ${jm(c)} ${u(c.id)}`);console.log(u("Run: d360-writer workspace use <name>"));return}let a=await Y0({message:"Select the Document360 workspace for this repo:",choices:o.map(c=>({name:`${jm(c)}${c.id===i?" (current)":""}`,value:c.id}))}),l=o.find(c=>c.id===a);la(e,s,r,a,l?.name),console.log(X(`\u2713 Workspace set to "${l?.name??a}" for profile "${s}".`)),await Z0(e,s,r,a)}async function Z0(e,t,n,o){try{let r=Im(e,t),s=await Q0({profile:r.name,connection:r.connection,projectId:n,projectName:r.project.projectName},{cwd:e,profile:r.name,projectId:n,workspaceId:o});for(let i of J0(s))console.log(i)}catch{}}ae();import{select as ex}from"@inquirer/prompts";import{resolveActiveProfile as tx,setProfileProject as nx,listProjects as ox}from"document360-engine";async function Cn(e,t){let n=tx(e,t),o={profile:n.name,connection:n.connection};return{projects:await ox(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var Om=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function pu(e,t){let n=t.toLowerCase();return e.find(o=>(o.name??"").toLowerCase()===n)??e.find(o=>(o.name??"").toLowerCase().startsWith(n))??e.find(o=>o.id.startsWith(t))}function ca(e,t,n,o){nx(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function Mm(e,t,n){let o;try{o=await Cn(e,n)}catch(s){return console.log(L(`Could not list projects: ${s.message}`)),1}let r=pu(o.projects,t);return r?(ca(e,o.profile,r.id,r.name),console.log(X(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log(L(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function ua(e,t){let n;try{n=await Cn(e,t)}catch(l){console.log(L(`Could not list projects: ${l.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(u("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let l of o)console.log(` ${l.id===s?Z("\u25CF"):" "} ${Om(l)} ${u(l.id)}`);console.log(u("Run: d360-writer project use <name>"));return}let i=await ex({message:"Select the Document360 project for this repo:",choices:o.map(l=>({name:`${Om(l)}${l.id===s?" (current)":""}`,value:l.id}))}),a=o.find(l=>l.id===i);ca(e,r,i,a?.name),console.log(X(`\u2713 Project set to "${a?.name??i}" for profile "${r}". Next: pick a workspace.`))}ae();import rx from"picocolors";function sx(e=process.env){return e.FORCE_HYPERLINK==="0"||!rx.isColorSupported?!1:e.FORCE_HYPERLINK?!0:!!(e.WT_SESSION||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="WezTerm"||e.TERM_PROGRAM==="ghostty"||e.VTE_VERSION||e.KONSOLE_VERSION)}function ix(e,t=e,n){return sx(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var ax=/https?:\/\/[^\s\x1b]+/g;function Is(e,t){return e.replace(ax,n=>ix(n,n,t))}qn();function Gm(e){return{...Bm(e.idToken)??{},...Bm(e.accessToken)??{}}}function da(e){let t=Gm(e),n=t.email??t.preferred_username??t.sub??"unknown",o=Vn(e),r=e.projectName?` \xB7 project "${e.projectName}"`:o?` \xB7 project ${o}`:"";return`${n}${r}`}async function bu(e,t,n){n&&Hm(e,t,n);try{let{projects:o}=await Cn(process.cwd(),e);for(let r of wu(e)){let s=Vn(r);s&&Hm(e,s,o.find(i=>i.id===s)?.name)}}catch{}}function Ax(e,t,n){let o=Vn(e);if(!o||!t||o===t)return null;let r=n?`"${n}"`:t.slice(0,8)+"\u2026";return`\u26A0 You signed in to project ${e.projectName?`"${e.projectName}"`:o.slice(0,8)+"\u2026"}, but this repo's docs live in ${r}. Run /login again and pick ${r} (or /project to point this repo somewhere else).`}async function pa(e){let t=Ls(process.cwd(),e.profile);if(!t.configured&&!e.profile){console.error(L("This repo is not set up yet, so there is no Document360 deployment to sign in to.")),console.error(`Run ${Z("/init")} to pick your region (or ${Z("d360-writer init")}), then sign in.`),console.error(u(`Signing in to one deployment directly: d360-writer login --profile <${kx().join("|")}>`)),process.exitCode=2;return}let n=t.connection;console.log(u(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})`)+(t.production?H(` ${Ye}`):""));let o=Hn(process.cwd(),e.profile);o&&(console.log(H(`\u26A0 ${o.why} \u2014 and signing in does NOT change it (the environment comes from the profile, not the login).`)),console.log(H(` To move: ${o.cmd}${o.replacementProfile?"":", then /login"}`)));let r=await $x(n,{manual:e.manual,promptForRedirect:h=>bx({message:h})},h=>console.log(Is(h))),s=xx(t.name,r);Cx(s),await ku(s,t.name,h=>console.log(u(h)));let i=Vn(s),a=Ls(process.cwd(),e.profile).project;i&&await bu(t.name,i,a.projectId===i?a.projectName:void 0);let l=yu(t.name,i??void 0)??s;console.log(""),console.log(X(`\u2713 Logged in to "${t.name}" as ${da(l)}`));let c=Ax(l,a.projectId,a.projectName);if(c&&console.log(H(c)),console.log(u(` access token expires: ${s.expiresAt}`)),console.log(u(` refresh token: ${s.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{Tx(process.cwd())?.profiles?.[t.name]&&(console.log(""),await Sr(process.cwd(),t.name))}catch{}}async function ku(e,t,n){let r=Gm(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Ls(process.cwd(),t).project.projectId)return;let i;try{let{projects:a}=await Cn(process.cwd(),t);i=a.find(l=>l.id===r)?.name}catch{}Px(process.cwd(),t,{projectId:r,projectName:i}),n(` Project "${i??r}" written to profile "${t}".`)}catch{}}async function qm(e){let t=Ls(process.cwd(),e.profile),n=t.connection,o=yu(t.name,t.project.projectId);if(!o){console.log(L(`Not logged in to Document360 (profile "${t.name}").`));let r=wu(t.name).filter(s=>Vn(s)&&Vn(s)!==t.project.projectId);r.length>0&&console.log(u(`This repo's project needs its own sign-in. Signed in on this machine: ${r.map(s=>s.projectName??Vn(s)).join(", ")}`)),console.log(u(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${Z(t.name)}${t.production?H(` ${Ye}`):""}: ${da(o)}`),Sx(o))if(o.refreshToken)try{await vx({profile:t.name,connection:n,projectId:t.project.projectId,projectName:t.project.projectName});let r=yu(t.name,t.project.projectId);console.log(X(`\u2713 Session refreshed${r?` \u2014 expires ${r.expiresAt}`:""}`))}catch(r){console.log(H(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(u(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(H("Session expired (no refresh token).")),console.log(u(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(u(` expires: ${o.expiresAt}`))}async function Vm(e){let t=Ls(process.cwd(),e.profile),n=e.allProjects?void 0:t.project.projectId,o=t.project.projectName?`"${t.project.projectName}"`:`profile "${t.name}"`;if(Rx(t.name,n)){console.log(X(e.allProjects?`\u2713 Logged out of every Document360 project for profile "${t.name}".`:`\u2713 Logged out of ${o}.`));let r=wu(t.name).filter(s=>Vn(s)).length;r>0&&console.log(u(`Still signed in to ${r} other project${r===1?"":"s"} on this machine.`))}else console.log(u(`No Document360 session for ${o} \u2014 nothing to do.`))}ae();import{readProjectConfig as Ym,writeProjectConfig as Ex,resolveActiveProfile as Nx,loadTokens as Dx,isExpired as jx,environmentIsProduction as Ix}from"document360-engine";function Km(e){return e.production??Ix(e.connection?.environment)}function ha(e){let t=Ym(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(L("No profiles in .d360-writer/config.json. Run: d360-writer init")),process.exitCode=1;return}console.log("");for(let[n,o]of Object.entries(t.profiles)){let r=n===t.defaultProfile?Z("\u25CF "):" ",s=Km(o)?H(` ${Ye}`):"",i=o.connection.environment??"(inline)",a=Dx(n,o.project?.projectId),l=a?jx(a)&&!a.refreshToken?H("expired"):u("logged in"):u("not logged in");console.log(`${r}${Z(n)} \u2192 ${i}${s} [${l}]`)}console.log(""),console.log(u("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function fa(e,t){let n=Ym(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(L(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,Ex(n,e);let o=Km(n.profiles[t])?H(` ${Ye}`):"";console.log(X(`\u2713 Default profile is now "${t}"${o}`))}function ma(e,t){try{let n=Nx(e,t);console.log(""),console.log(`Profile ${Z(n.name)}${n.production?H(` ${Ye}`):""}`),console.log(u(` api: ${n.connection.apiUrl}`)),console.log(u(` identity: ${n.connection.authorizationUrl}`)),console.log(u(` clientId: ${n.connection.clientId}`)),console.log(u(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(u(` project: ${n.project.projectId??"(set at login)"}`)),console.log(u(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(L(n.message)),process.exitCode=1}}ae();import{existsSync as Qm,readdirSync as Lx,readFileSync as Ox,statSync as Mx}from"node:fs";import{join as Jm}from"node:path";import{apiLogDir as _x}from"document360-engine";var Ux=30,Fx=12e3;function Wx(e){if(!Qm(e))return{api:[],crash:[]};try{let t=Lx(e);return{api:t.filter(n=>n.endsWith(".jsonl")).sort().reverse(),crash:t.filter(n=>/^crash-\d{4}-\d{2}-\d{2}\.log$/.test(n)).sort().reverse()}}catch{return{api:[],crash:[]}}}var Bx=/·\s*(empty-turn|agent-subprocess|uncaught|unhandled)\s*===/i,Hx=/·\s*FATAL\s*·/i,Gx=e=>Hx.test(e)||Bx.test(e);function qx(e){let n=e.split(/\n(?==== \d{4}-\d{2}-\d{2}T)/).map(s=>s.trim()).filter(Boolean).filter(s=>s.startsWith("==="));if(n.length===0)return null;let o=[...n].reverse().find(Gx),r=o??n[n.length-1];return{text:r,when:/^=== (\S+)/.exec(r)?.[1]??"",count:n.length,notable:!!o}}function Vx(e,t){let n=t[0];if(!n)return null;try{return qx(Ox(Jm(e,n),"utf8"))}catch{return null}}function zm(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}var Xm=(e,t)=>{try{return`${(Mx(Jm(e,t)).size/1024).toFixed(1)} KB`}catch{return""}};function $u(){let e=_x(),{api:t,crash:n}=Wx(e),o=Vx(e,n),r=[];if(o){let s=o.text.split(/\r?\n/),i=s.slice(0,Ux);r.push(o.notable?oe("\u2717",`The last thing that went wrong \u2014 ${zm(o.when)}:`):oe("\u2139",`Nothing has failed. The most recent note d360-writer recorded \u2014 ${zm(o.when)}:`)),r.push("");for(let a of i)r.push(` ${a}`);s.length>i.length&&r.push(u(` \u2026${s.length-i.length} more line${s.length-i.length===1?"":"s"} \u2014 the whole thing is in ${n[0]}, and c copies all of it.`)),r.push(""),o.count>1&&r.push(u(` ${o.count} entries recorded today; this is the one worth reading.`)),o.notable&&r.push(u(" If this is not obviously your own doing, send it to the team \u2014 it names what failed.")),r.push("")}else n.length===0&&(r.push(oe("\u2713","Nothing has failed \u2014 d360-writer has recorded no problems.")),r.push(""));if(r.push(`Logs live in ${Z(e)}`),!Qm(e)||t.length===0&&n.length===0)return r.push(u(" Nothing here yet \u2014 logs appear after the first Document360 call.")),{lines:r,copyText:null,notable:!1};if(n.length>0){r.push(""),r.push(`Problem logs ${u("(send these if something crashed or a run did nothing)")}:`);for(let s of n.slice(0,14))r.push(` ${L(s)} ${u(Xm(e,s))}`)}if(t.length>0){r.push(""),r.push("Document360 call logs:");for(let s of t.slice(0,14))r.push(` ${s} ${u(Xm(e,s))}`)}return r.push(""),r.push(u("Failed calls include what was sent and returned (sign-in details removed, 4 KB cap).")),r.push(u("Set D360_LOG_BODIES=1 to record successful calls too.")),{lines:r,copyText:o?o.text.slice(0,Fx):null,notable:!!o?.notable}}async function Zm(){return vu(),{kind:"continue"}}function vu(){let{lines:e,copyText:t}=$u();console.log("");for(let n of e)console.log(n);t&&console.log(u("Inside d360-writer, /logs offers to copy this for you.")),console.log("")}ae();qn();import{existsSync as Yx,readFileSync as eg}from"node:fs";import{homedir as Kx}from"node:os";import{EnvironmentConfigError as tg,addedEnvironmentsPath as ga,loadAddedEnvironments as ng,parseAddedEnvironments as zx,profileEnvironmentName as Xx,readProjectConfig as Qx,removeAddedEnvironment as Jx,resolveEnvironment as Zx,saveAddedEnvironment as eR}from"document360-engine";function ya(e){let t=Kx();return e.startsWith(t)?`~${e.slice(t.length).replace(/\\/g,"/")}`:e}function og(e){let t=Gn(),n=Xx(e),o=Math.max(...t.map(c=>c.name.length)),r=Math.max(...t.map(c=>c.portalUrl.length)),s=["Document360 deployments",""];for(let c of t){let h=c.name===n?`${Z("\u25CF")} `:" ",y=c.note?u(` ${c.note}`):"";s.push(`${h}${Z(c.name.padEnd(o))} ${c.portalUrl.padEnd(r)}${y}`)}let{entries:i,problems:a}=ng(),l=Object.keys(i);if(s.push(""),n&&s.push(u("\u25CF = where this repo publishes.")),l.length===0?s.push(u("Add a deployment this build does not ship: d360-writer env add <file.json>")):(s.push(u(`Added on this machine: ${ya(ga())}`)),s.push(u("Add another: d360-writer env add <file.json>")),s.push(u(`Remove one: d360-writer env remove ${l[0]}`))),a.length>0){s.push("");let c=a.length===1?"One added deployment could not be loaded:":`${a.length} added deployments could not be loaded:`;s.push(H(oe("\u26A0",c)));for(let h of a)s.push(H(` ${h}`))}return s}function tR(e){if(e==="-")try{return{text:eg(0,"utf8"),where:"standard input"}}catch{return null}if(!Yx(e))return null;try{return{text:eg(e,"utf8"),where:e}}catch{return null}}function rg(e,t){let n=tR(t);if(!n)return{ok:!1,lines:[L(`Cannot read ${t}.`),u("Pass a JSON file, or - to read the document from standard input.")]};let o;try{o=zx(n.text,n.where)}catch(a){if(!(a instanceof tg))throw a;return{ok:!1,lines:[L("That document has problems, so nothing was saved:"),...a.message.split(`
|
|
307
|
+
`).map(l=>L(` ${l}`))]}}let r=Object.keys(o);if(r.length===0)return{ok:!1,lines:[L(`${n.where} defines no deployments.`),u("The document is a JSON object of environment name \u2192 connection fields.")]};let s=[];for(let a of r){let l=eR(a,o[a]),c=Zx(a);s.push(X(oe("\u2713",`${l==="added"?"Added":"Updated"} ${a} \u2014 ${c.portalUrl}`))),c.isProduction?s.push(H(oe("\u26A0",`${a} is a live deployment. Drafts save freely; taking articles live needs /allow-prod.`))):s.push(u(' Treated as staging. Add "isProduction": true if it reaches real readers.'))}s.push(""),s.push(u(`Saved to ${ya(ga())}`)),s.push("");let i=r[0];return s.push(Qx(e)?`Next: ${Z(`/profile add ${i}`)} ${u("(then /login)")}`:`Next: ${Z("d360-writer init")} ${u(`(${i} is now in the deployment list)`)}`),{ok:!0,lines:s}}function sg(e,t){let n=!1;try{n=Jx(t)}catch(s){if(!(s instanceof tg))throw s;return{ok:!1,lines:[L(`${ya(ga())} cannot be read, so nothing was removed:`),...s.message.split(`
|
|
308
|
+
`).map(i=>L(` ${i}`))]}}if(!n){let s=Object.keys(ng().entries);return{ok:!1,lines:[L(`Nothing added on this machine is called "${t}".`),u(s.length>0?`Added here: ${s.join(", ")}`:"This machine has no added deployments.")]}}let o=[X(oe("\u2713",`Removed ${t} from ${ya(ga())}`))],r=mu(e,t);return r&&(o.push(H(oe("\u26A0",`Profile "${r}" in this repo still points at ${t} and can no longer reach it.`))),o.push(u(" Add it back with: d360-writer env add <file.json>"))),{ok:!0,lines:o}}function xu(e,t){let[n,o]=t;return!n||n==="list"?{ok:!0,lines:og(e)}:n==="add"?o?rg(e,o):{ok:!1,lines:[L("Usage: /env add <file.json>"),u("A JSON object of environment name \u2192 connection fields.")]}:n==="remove"?o?sg(e,o):{ok:!1,lines:[L("Usage: /env remove <name>")]}:{ok:!1,lines:[L(`Unknown: /env ${n}`),u("Try: /env, /env add <file.json>, /env remove <name>")]}}function wa(e){console.log("");for(let t of e.lines)console.log(t);console.log(""),e.ok||(process.exitCode=1)}function ig(e){wa({ok:!0,lines:og(e)})}function ag(e,t){wa(rg(e,t))}function lg(e,t){wa(sg(e,t))}async function cg(e,t){return wa(xu(t.cwd,e)),{kind:"continue"}}ae();import{createSession as nR,resolveAuth as oR,findByName as rR,slugify as sR,touchSession as iR,upsertSession as aR,resolveActiveProfile as lR}from"document360-engine";async function ug(e,t,n,o,r,s){let i=oR(n);i.kind==="none"&&(console.error(""),console.error(L("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${Z("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${Z("d360-writer --auth subscription")}`),process.exit(2)),i.kind==="subscription"&&console.error(u("Using your Claude subscription (no API key set)."));let a=null;try{a=lR(e,r)}catch(x){console.error(L(`Document360 profile error: ${x.message}`)),process.exit(2)}a.production&&(console.error(H(`${Ye} \u2014 profile "${a.name}" publishes to real readers.`)),console.error(s?u(" --yes given \u2014 this run may take articles live."):u(" Drafts will be saved. Taking articles live needs --yes.")));let l;if(o){let x=rR(e,o);x||(console.error(L(`No saved session matches "${o}" in this repo.`)),console.error(u("List sessions inside the REPL with /resume.")),process.exit(2)),l=x.uuid,console.error(u(`Resuming "${x.name}"`))}let c=nR({cwd:e,resume:l,profileName:r,allowProdWrites:s===!0}),h=l??null,y=1;for await(let x of c.send(t))switch(x.type){case"session":if(!h){h=x.sessionId;let w=new Date().toISOString();aR({uuid:h,name:sR(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:w,updatedAt:w})}break;case"text":process.stdout.write(x.delta);break;case"tool":console.error(Ae(` \u2699 ${x.name}`));break;case"result":y=x.ok?0:1,console.error(u(`(${x.inputTokens}\u2192${x.outputTokens} tokens`+(x.costUsd>0?`, $${x.costUsd<.01?x.costUsd.toFixed(4):x.costUsd.toFixed(2)}`:"")+")")),x.ok||console.error(L("agent finished with an error result"));break;case"error":console.error(""),console.error(L(`agent error: ${x.message}`)),process.exit(1)}h&&iR(h),process.stdout.write(`
|
|
309
|
+
`),process.exit(y)}import{createInterface as pL}from"node:readline/promises";import{createSession as wf,resolveAuth as hL,resolveAuthOrigin as fL,authOriginLine as B$,authOriginFix as mL,getSession as gL,setTitle as yL,slugify as wL,touchSession as Y$,upsertSession as bL,generateTitle as kL,resolveActiveProfile as K$,resolveModelSetting as $L,readProjectConfig as vL,readUserConfig as xL,resolveAndPersistAppType as RL,decodeJwtClaims as H$,isExpired as SL,loadTokens as CL,isDirectiveMention as PL,stripDirectiveMention as TL,appendDirective as AL,reconcileUpgradeActions as EL,stampArticles as NL,snapshotArticles as G$,listArticleFiles as DL,applyStructureOrder as jL,orderSyncLine as IL,computeSyncStatus as LL,recordBriefConsumed as OL}from"document360-engine";import{ENGINE_VERSION as dR}from"document360-engine";function cn(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 ba(e){if(e.length===0)return[];let t=(s,i)=>`${s}${"\u2500".repeat(78)}${i}`,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,i)=>{i>0&&o.push(t("\u251C","\u2524")),o.push(n());for(let a of cn(`${i+1}. ${s.feature}`,76))o.push(n(a));o.push(n());for(let a of cn(s.why,73))o.push(n(` ${a}`));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}function ka(e){return[`\u26A0 ${e} screenshot${e===1?"":"s"} that hide${e===1?"s":""} sensitive areas ${e===1?"is":"are"} back to needing a check.`," A blacked-out area only covered the first matching spot on the screen \u2014 so on a list or a table, the",` rows below it were still readable. Blackouts now cover every match, and ${e===1?"that picture needs":"those pictures need"} a fresh look.`].join(`
|
|
310
|
+
`)}var xt=[{key:"start",label:"Getting Started",rows:[{t:"text",s:"D360-Writer reads your codebase and writes your user documentation."},{t:"gap"},{t:"text",s:"It publishes to Document360 when you are ready."},{t:"gap"},{t:"text",s:"It needs Claude access \u2014 a subscription, or an ANTHROPIC_API_KEY."},{t:"gap"},{t:"sub",s:"Quick start"},{t:"step",n:1,s:"Run /init. Pick the Document360 deployment you publish to, sign in, choose your project."},{t:"step",n:2,s:"Paste the prompt it prints into your coding agent, and let it finish."},{t:"step",n:3,s:"Run /doctor to confirm every check is green."},{t:"step",n:4,s:'Type "write the docs for this repository".'},{t:"gap"},{t:"dim",s:"Claude Code, Codex and Cursor all work. /devhints re-shows that prompt."},{t:"dim",s:"That's it \u2014 D360-Writer drafts your docs without you writing a line."},{t:"gap"},{t:"sub",s:"Tips"},{t:"text",s:"Just talk to it. Anything not starting with / goes to the agent."},{t:"gap"},{t:"dim",s:"/ browse commands \xB7 \u2191 recall history \xB7 tab run the suggestion"},{t:"dim",s:"1-9 pick from a list \xB7 ctrl+y copy whatever was offered"},{t:"dim",s:"esc interrupt a run \xB7 ctrl+c twice exit"},{t:"dim",s:"shift+tab switch auto / manual \u2014 see /auto"}]},{key:"agentic",label:"Agentic",rows:[{t:"text",s:"Agentic mode is for products built with an AI coding agent."},{t:"gap"},{t:"text",s:"Your coding agent ships features and leaves notes."},{t:"text",s:"D360-Writer turns those notes into user documentation."},{t:"gap"},{t:"dim",s:"Think of it as a Technical Writer dedicated to your project."},{t:"gap"},{t:"sub",s:"Auto or manual"},{t:"gap"},{t:"text",s:"In MANUAL mode I work out the next step and offer it. You press tab."},{t:"gap"},{t:"text",s:"In AUTO mode I run that step myself, then the one after it."},{t:"gap"},{t:"dim",s:" write \u2192 review \u2192 check the style \u2192 save \u2192 go live"},{t:"gap"},{t:"text",s:"Start a build, come back to a finished knowledge base."},{t:"gap"},{t:"cmd",name:"/auto on",s:"Let me run my own next step."},{t:"cmd",name:"/auto --budget",s:"Cap what one run may spend. The standard cap is $200."},{t:"gap"},{t:"dim",s:" shift+tab switches mode \xB7 esc stops a run"},{t:"dim",s:" Nothing already written, saved or published is undone."},{t:"gap"},{t:"text",s:"Auto changes who presses the key. It does not change what is checked."},{t:"gap"},{t:"text",s:"Every gate still runs."},{t:"text",s:"An article that fails one stays a draft, and the report names it."},{t:"gap"},{t:"text",s:"Screenshots are never automatic \u2014 they need your app on screen."},{t:"gap"},{t:"sub",s:"Every few days"},{t:"cmd",name:"/catch-up",s:"Write up everything pending. It all lands as a draft."},{t:"dim",s:" A note whose code your builder has not committed waits, and they get asked."},{t:"dim",s:" --include-unfinished write those pages anyway"},{t:"cmd",name:"/review --fix",s:"A senior editor reads every article and fixes it."},{t:"cmd",name:"/push --all",s:"Save the reviewed articles to Document360, as drafts."},{t:"cmd",name:"/publish --all",s:"Take those drafts live. It lists them and asks first."},{t:"gap"},{t:"dim",s:" An editorial read is required before anything goes live."},{t:"dim",s:" /review --blocked only the articles publishing is stuck on"},{t:"dim",s:" /review --stale only the ones this editor has not read yet"},{t:"gap"},{t:"sub",s:"Whenever you need"},{t:"cmd",name:"/discover",s:"Interview your builder. Pins a product brief for the docs."},{t:"cmd",name:"/audit",s:"What changed in the code, what is missing from the docs."},{t:"cmd",name:"/audit --decline <path>",s:"That folder or file needs no article. Stops it being reported. Bare: lists what you could decline."},{t:"cmd",name:"/pull",s:"Bring down portal edits and any new portal articles."},{t:"cmd",name:"/resolve",s:"Settle a conflict: keep yours, take the portal, or skip."},{t:"cmd",name:"/comments",s:"Reviewer comments on your articles. Read one, answer it."},{t:"cmd",name:"/inbox",s:"Act on your coding agent's messages."},{t:"cmd",name:"/ask",s:"Ask your developers what the code cannot answer."},{t:"gap"},{t:"dim",s:" An answer fixes the article, saves the draft and replies in the thread."}]},{key:"assistant",label:"Assistant",rows:[{t:"text",s:"D360-Writer is your writing assistant."},{t:"gap"},{t:"text",s:"It does the writing. You decide what gets written, and when."},{t:"gap"},{t:"text",s:"Best for large monorepos: point it at one feature or one set of folders."},{t:"gap"},{t:"sub",s:"Just ask"},{t:"good",s:'"Write the docs for the Multiple JWT feature we shipped last release."'},{t:"gap"},{t:"sub",s:"Or drive it yourself"},{t:"cmd",name:"/scope",s:"Focus on specific source folders."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from its PRDs and the code."},{t:"cmd",name:"/write",s:"Write the planned articles."},{t:"cmd",name:"/push",s:"Save them to Document360 as drafts."},{t:"cmd",name:"/publish",s:"Take the drafts live to your readers."},{t:"cmd",name:"/status",s:"What stands between your work and your readers. Free."},{t:"gap"},{t:"dim",s:" /write --preview shows the plan and the cost first."},{t:"dim",s:" /push --preview <path> shows exactly what Document360 would receive."},{t:"gap"},{t:"sub",s:"One place for what repeats"},{t:"gap"},{t:"text",s:"A variable holds a value \u2014 your product name, a URL \u2014 in one place."},{t:"text",s:"Change it there and every article changes."},{t:"gap"},{t:"text",s:"A snippet does the same for a whole block, like who to contact."},{t:"gap"},{t:"text",s:"A term is defined once, and every article is checked for explaining it."},{t:"gap"},{t:"cmd",name:"/reuse",s:"What your project already keeps on Document360."},{t:"cmd",name:"/reuse pull",s:"Refresh that list from Document360."},{t:"cmd",name:"/reuse add",s:'Create one there: /reuse add variable <name> "<value>".'},{t:"cmd",name:"/reuse audit",s:"Read every article and find what belongs in one place."},{t:"cmd",name:"/terms",s:"Is the same thing called the same name everywhere?"},{t:"cmd",name:"/eval",s:"How does the whole knowledge base score? Free."},{t:"gap"},{t:"dim",s:" Reading is free. Nothing is created until you pick it."},{t:"gap"},{t:"sub",s:"Taking a page back"},{t:"cmd",name:"/retire <path>",s:"Stop showing an article to readers. /push puts it back."},{t:"cmd",name:"/untrack <path>",s:"Disown an imported page that is not one of your docs."},{t:"gap"},{t:"dim",s:" Neither deletes anything. History and reviewer comments stay."}]},{key:"shots",label:"Screenshots",rows:[{t:"text",s:"Documenting a web app? D360-Writer marks where an image helps."},{t:"gap"},{t:"text",s:"The companion CLI d360-capture turns those marks into real,"},{t:"text",s:"annotated screenshots by driving your app in a browser."},{t:"gap"},{t:"sub",s:"Flow"},{t:"step",n:1,s:"Write your docs as usual. Placeholders go in where visuals help."},{t:"step",n:2,s:"Run /screenshot author --all to write the capture specs."},{t:"step",n:3,s:"Stage what the checklist asks for, then /screenshot capture."},{t:"step",n:4,s:"The callouts are drawn on straight after. No browser needed."},{t:"step",n:5,s:"Each finished picture is checked, then marked \u2714 verified."},{t:"step",n:6,s:"Run /push --screenshots so the images embed on Document360."},{t:"gap"},{t:"sub",s:"One command family"},{t:"cmd",name:"/screenshot",s:"Pick what to do next."},{t:"cmd",name:"/screenshot author",s:"Write the capture specs."},{t:"cmd",name:"/screenshot capture",s:"Take the shots."},{t:"cmd",name:"/screenshot annotate",s:"Draw the callouts on shots already taken."},{t:"cmd",name:"/screenshot verify",s:"Judge the finished pictures and mark them verified."},{t:"cmd",name:"/screenshot checklist",s:"What to stage, and the test-ids to ask your dev for."},{t:"cmd",name:"/screenshot list",s:"Progress by chapter, and the worklist."},{t:"gap"},{t:"dim",s:" Each takes an <id>, a path, or --all."},{t:"dim",s:" capture --failed re-runs what did not work \xB7 --blocked what waited on data"},{t:"dim",s:" annotate --force re-draws after a wording or style change"},{t:"gap"},{t:"sub",s:"What each state means"},{t:"text",s:"\u2714 verified finished \u2014 this is the finish line"},{t:"text",s:"\u25C8 to verify the picture is done, waiting to be looked at"},{t:"text",s:"\u25CF to annotate shot taken, callouts not drawn on yet"},{t:"text",s:"\u25D0 ready the spec is written, the shot not taken"},{t:"text",s:"\u2691 rejected the shot ran but the picture is wrong"},{t:"text",s:"\u2298 blocked your app lacked the data the shot needs"},{t:"text",s:"\u2717 broken the spec itself is out of date"},{t:"text",s:"\u25CB to-spec no spec written yet"},{t:"gap"},{t:"dim",s:" rejected \u2014 the spec is usually fixed for you, then capture --failed re-shoots"},{t:"dim",s:" blocked \u2014 /screenshot list groups every blocker into a few things to stage"},{t:"dim",s:" broken \u2014 re-author with /screenshot <id>; a re-capture would fail the same way"},{t:"gap"},{t:"dim",s:"One-time setup in your app repo:"},{t:"dim",s:" npm i -g document360-capture \xB7 d360-capture init \xB7 d360-capture auth"}]},{key:"cmds",label:"Commands",rows:[{t:"dim",s:"Every command, one line each \u2014 type / for the full usage."},{t:"dim",s:"The tabs above teach the ones worth more than a line."},{t:"gap"},{t:"sub",s:"Getting started"},{t:"cmd",name:"/init",s:"Set up Document360 and the coding-agent hand-off."},{t:"cmd",name:"/login",s:"Sign in \u2014 one sign-in per project, all kept."},{t:"cmd",name:"/project",s:"Choose the Document360 project."},{t:"cmd",name:"/workspace",s:"Switch the workspace."},{t:"cmd",name:"/scope",s:"Choose which repo folders back the docs."},{t:"cmd",name:"/genre",s:"What kind of product this is \u2014 picks the writing guide."},{t:"cmd",name:"/devhints",s:"Re-show the prompt to paste into your coding agent."},{t:"cmd",name:"/mcp",s:"Connect MCP servers (Notion, Linear, \u2026)."},{t:"gap"},{t:"sub",s:"Agentic \u2014 keep docs in sync"},{t:"cmd",name:"/roadmap",s:"The docs campaign: progress and the next step."},{t:"cmd",name:"/catch-up",s:"Do all pending work \u2192 drafts. --push also saves them."},{t:"cmd",name:"/auto",s:"Run the next step myself instead of waiting for you."},{t:"cmd",name:"/audit",s:"What changed in the code, what's missing from the docs."},{t:"cmd",name:"/inbox",s:"Act on your coding agent's messages."},{t:"cmd",name:"/ask",s:"Ask your developers what the code cannot answer."},{t:"cmd",name:"/share",s:"Get your builder's latest, send yours (automatic)."},{t:"gap"},{t:"sub",s:"Assistant \u2014 directed writing"},{t:"cmd",name:"/discover",s:"Interview your builder \u2192 a product brief for the docs."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from its PRDs and the code."},{t:"cmd",name:"/write",s:"Write the planned articles. --preview costs first."},{t:"cmd",name:"/preview",s:"Render an article locally."},{t:"cmd",name:"/reorder",s:"Put a category's articles in the best reading order."},{t:"cmd",name:"/restructure",s:"Move an article to another category, split one, merge two, rename one."},{t:"cmd",name:"/structure",s:"The reading order, as it will appear on Document360."},{t:"gap"},{t:"sub",s:"Quality \u2014 before you publish"},{t:"cmd",name:"/style-guide",s:"Choose the writing rules your docs are held to."},{t:"cmd",name:"/lint",s:"The machine pass over those rules. Free. --fix corrects."},{t:"cmd",name:"/review",s:"The editor pass. Required before anything goes live."},{t:"cmd",name:"/terms",s:"Is the same thing called the same name everywhere? Free."},{t:"cmd",name:"/eval",s:"Score the whole set: links, shape, naming. Free."},{t:"cmd",name:"/reuse",s:"The terms, values and blocks kept on Document360."},{t:"gap"},{t:"sub",s:"Publish & sync"},{t:"cmd",name:"/status",s:"What stands between your work and your readers. Free."},{t:"cmd",name:"/push",s:"Save your articles to Document360 as drafts."},{t:"cmd",name:"/publish",s:"Take the drafts live to your readers. Asks first."},{t:"cmd",name:"/pull",s:"Portal edits + new portal articles. --status: report only."},{t:"cmd",name:"/resolve",s:"Settle a local\u2194portal conflict: keep, take, or skip."},{t:"cmd",name:"/comments",s:"Reviewer comments on your articles \u2014 read and answer."},{t:"cmd",name:"/retire",s:"Take an article off your readers. Nothing is deleted."},{t:"cmd",name:"/untrack",s:"Disown an imported page that is not one of your docs."},{t:"gap"},{t:"sub",s:"Screenshots"},{t:"cmd",name:"/screenshot",s:"The screenshot pipeline. Bare: pick what to do next."},{t:"dim",s:" author \xB7 capture \xB7 annotate \xB7 verify \xB7 checklist \xB7 list"},{t:"gap"},{t:"sub",s:"Setup & health"},{t:"cmd",name:"/model",s:"Set the Claude model."},{t:"cmd",name:"/verbose",s:"Raw transcript: every tool call, path and result."},{t:"cmd",name:"/profile",s:"Where this repo publishes. Switch, or connect another environment."},{t:"cmd",name:"/allow-prod",s:"Authorize taking articles live on a production profile."},{t:"cmd",name:"/env",s:"The deployments this machine can reach. Add one from a JSON file."},{t:"cmd",name:"/doctor",s:"Health check \u2014 including a real agent turn."},{t:"cmd",name:"/logs",s:"The last problem, in full. \u2303y copies it."},{t:"cmd",name:"/update",s:"Update D360-Writer, and d360-capture if installed."},{t:"cmd",name:"/feedback",s:"Copy this repo's open feedback, to relay to the team."},{t:"cmd",name:"/copy",s:"Copy what is waiting to be copied. \u2303y does the same."},{t:"cmd",name:"/logout",s:"Sign out of this project. --all-projects: all of them."},{t:"cmd",name:"/reset",s:"Delete all D360-Writer files (confirms first)."},{t:"gap"},{t:"sub",s:"Session"},{t:"cmd",name:"/resume",s:"Resume a saved session."},{t:"cmd",name:"/rename",s:"Name the session."},{t:"cmd",name:"/clear",s:"Clear the screen and reset the conversation."},{t:"cmd",name:"/help",s:"Show this help."},{t:"cmd",name:"/exit",s:"Quit."}]}],dg=24;function Ru(e){let t=e.filter(n=>n.t==="cmd").map(n=>n.name.length);return t.length===0?dg:Math.min(dg,Math.max(...t))}var pg=2;function $a(e,t,n,o){let r=" ".repeat(2+n+pg),s=Math.max(24,o-r.length-2),i=cn(t,s);return e.length>n?{nameCell:e,descLines:i,indent:r,nameOwnLine:!0}:{nameCell:e.padEnd(n+pg-1),descLines:i,indent:r,nameOwnLine:!1}}function cR(e,t,n){switch(e.t){case"head":return e.s;case"text":return` ${e.s}`;case"dim":return` ${e.s}`;case"sub":return e.s;case"good":return` ${e.s}`;case"step":return` ${e.n}. ${e.s}`;case"cmd":{let o=$a(e.name,e.s,t,n),r=o.descLines.slice(o.nameOwnLine?0:1).map(i=>`${o.indent}${i}`);return[o.nameOwnLine?` ${o.nameCell}`:` ${o.nameCell} ${o.descLines[0]??""}`,...r].join(`
|
|
311
|
+
`)}case"gap":return""}}function hg(e){let n=[e?`document360-writer \u2014 help \xB7 v${e.version} \xB7 engine v${e.engineVersion}`:"document360-writer \u2014 help",""];for(let o of xt){n.push(`\u2500\u2500 ${o.label} \u2500\u2500`,"");let r=Ru(o.rows);for(let s of o.rows)n.push(cR(s,r,100));n.push("")}return n.push("Tip: anything not starting with / goes to the agent."),n}function Su(e,t){return cn(e,Math.max(10,Math.max(20,t)-2))}function uR(e,t,n){let o=Math.max(20,n),r=s=>Math.max(1,Su(s,o).length);switch(e.t){case"gap":return 1;case"cmd":{let s=$a(e.name,e.s,t,o);return s.nameOwnLine?1+s.descLines.length:1+Math.max(0,s.descLines.length-1)}case"step":return r(`${e.n}. ${e.s}`);default:return r(e.s)}}function fg(e,t){let n=Math.min(Math.max(0,t.scroll),Math.max(0,e.length-1)),o=[],r=0;for(let s=n;s<e.length;s++){let i=uR(e[s],t.nameW,t.width);if(r+i>t.budget&&o.length>0)break;o.push(e[s]),r+=i}return{visible:o,above:n,below:e.length-n-o.length,start:n}}function mg(e){let n=r=>Math.max(1,Math.ceil(r/Math.max(10,e.inner))),o=n(e.barWidth)+n(e.barWidth)+1+1+n(e.footerWidth)+7;return Math.max(3,Math.min(22,(e.rows||24)-o))}async function Cu(e=[],t){console.log("");let n=t?.version?{version:t.version,engineVersion:dR}:void 0;for(let o of hg(n))console.log(o);return console.log(""),console.log("Reporting a problem? Run `/logs` \u2014 it shows the last problem and offers to copy it."),console.log(""),{kind:"continue"}}ae();import{getSession as pR}from"document360-engine";async function gg(e,t){let n=t.currentUuid(),o=n?pR(n):void 0;return console.log(o?u(`
|
|
312
312
|
(conversation reset \u2014 "${o.name}" is still available via /resume)
|
|
313
313
|
`):u(`
|
|
314
314
|
(conversation reset \u2014 agent will start fresh on the next prompt)
|
|
315
|
-
`)),{kind:"clear"}}async function
|
|
315
|
+
`)),{kind:"clear"}}async function Pu(){return{kind:"exit"}}Ta();ae();import{readMcpConfig as Lu,writeMcpConfig as Fg}from"document360-engine";async function Aa(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(DR(),{kind:"continue"}):t==="add"?(jR(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(IR(e.slice(1)),{kind:"continue"}):(console.log(L(`Unknown /mcp subcommand: ${t}`)),console.log(u("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function DR(){let e=Lu(),t=Object.keys(e.servers);if(t.length===0){console.log(u(`
|
|
316
316
|
No MCP servers registered. Add one with /mcp add <name> <type> <ref>
|
|
317
|
-
`));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(` ${Z(n)} ${u("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?u(` [headers: ${r.join(", ")}]`):"";console.log(` ${Z(n)} ${u(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function
|
|
317
|
+
`));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(` ${Z(n)} ${u("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?u(` [headers: ${r.join(", ")}]`):"";console.log(` ${Z(n)} ${u(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function jR(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(L("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(L(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=Lu(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let i={};for(let a=1;a<o.length;a++)if(o[a]==="-H"||o[a]==="--header"){let l=o[++a],c=l?.match(/^([^:=]+)[:=](.+)$/);if(!c){console.log(L(`-H expects key:value (no spaces). Got: ${l??"(nothing)"}`));return}i[c[1].trim()]=c[2].trim()}else{console.log(L(`Unexpected argument: ${o[a]}. After the URL, only -H key:value is allowed.`));return}s={type:n,url:o[0],headers:Object.keys(i).length>0?i:void 0}}r.servers[t]=s,Fg(r),console.log(""),console.log(X(`\u2713 Registered "${t}" (${n})`)),console.log(H(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(u(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function IR(e){let t=e[0];if(!t){console.log(L("Usage: /mcp remove <name>"));return}let n=Lu();if(!n.servers[t]){console.log(L(`No server named "${t}".`));return}delete n.servers[t],Fg(n),console.log(X(`\u2713 Removed "${t}".`)),console.log(u(" Run /clear to drop it from the current session immediately."))}ae();import{readFileSync as hC}from"node:fs";import{join as fC}from"node:path";import{select as mC}from"@inquirer/prompts";import{computeSyncStatus as Xa,planPartitions as gC,relatedArticlePaths as yC,loadProfileMap as By,draftPendingPaths as Hy,placeholderFindings as wC,resolveActiveProfile as Ja,listUnpullable as bC,unreviewedPaths as kC,styleErrorPaths as Gy,publishGateVerdict as $C,publishGateLines as vC,pushArticles as xC,pushArticle as RC,PUSH_POOL_SIZE as SC,SKIP_STYLE_FLAG as CC,listArticleFiles as qy,docsRootOf as PC,ensureFeedbackChannel as TC,FEEDBACK_CATEGORY_NAME as Fy,resolveCrossLinks as AC,applyStructureOrder as Vy,orderSyncLine as Yy,applyRelatedArticles as Ky,relatedSyncLine as zy}from"document360-engine";import{readFileSync as LR}from"node:fs";import{resolve as OR}from"node:path";import{prettyFolderName as Wg}from"document360-engine";var zn=Wg;function Ea(e){return e.replace(/\\/g,"/").split("/").slice(0,-1).join("/")}function Ms(e){let t=e.replace(/\\/g,"/").split("/").pop()??e;return Wg(t.replace(/\.md$/i,""))}function Na(e,t){try{return/^#\s+(.+)$/m.exec(LR(OR(e,t),"utf8"))?.[1]?.trim()??null}catch{return null}}import{resolveActiveProfile as Bg,loadTokens as Hg,isExpired as _u,listStoredSessions as MR,tokensProjectId as Mu,identityRefusal as _R}from"document360-engine";function Da(e,t){try{let n=Bg(e,t),o=Hg(n.name,n.project.projectId);return!o||_u(o)?!1:Ze(e,t).ok}catch{return!1}}function UR(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function Ou(e,t){return t?`"${t}"`:e?UR(e):"this project"}function FR(e,t){return t?MR(e).filter(n=>{let o=Mu(n);return!!o&&o!==t&&!(_u(n)&&!n.refreshToken)}):[]}function Ze(e,t){try{let n=Bg(e,t);try{n.connection}catch(l){return{ok:!1,reason:l instanceof Error?l.message:String(l)}}let o=_R(e,t);if(o)return{ok:!1,reason:o};let r=n.project.projectId,s=Ou(r,n.project.projectName),i=Hg(n.name,r);if(!i){let l=FR(n.name,r);return l.length>0?{ok:!1,reason:`You're signed in to Document360 project ${l.map(h=>Ou(Mu(h)??void 0,h.projectName)).join(", ")}, and this repo's docs live in ${s}. A sign-in covers one project, so ${s} needs its own \u2014 run /login and pick it. Both stay signed in after that, so switching between repos won't ask again.`}:{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`}}if(_u(i)&&!i.refreshToken)return{ok:!1,reason:`Your Document360 session for ${s} expired. Run /login.`};let a=Mu(i);return r&&a&&a!==r?{ok:!1,reason:`Your Document360 session is signed into a different project than this repo's ${s} (the session is for ${Ou(a,i.projectName)}). Run /login and pick ${s}.`}:{ok:!0}}catch{return{ok:!0}}}import{existsSync as ly,readFileSync as Ju}from"node:fs";import{isAbsolute as Ma,join as _a,resolve as Ua}from"node:path";import M from"picocolors";import La from"string-width";import{readProjectConfig as Qn,screenshotPlaceholderIds as cy,screenshotMarkerProblemsInDocs as uS,DEFAULT_CAPTURE_DIR as Fa,DEFAULT_OUTPUT_DIR as Zu,DEFAULT_DOCS_DIR as ed,resolveOutputDir as uy,migrateShotLayout as dS,reviewIsCurrent as pS,anchorPresent as hS,annotationCurrent as fS,captureLanded as mS,shotArtifacts as gS,RAW_SUBDIR as yS,ANNOTATED_SUBDIR as wS}from"document360-engine";import{createHash as Uu}from"node:crypto";import{readFileSync as qg,writeFileSync as WR}from"node:fs";import{join as BR}from"node:path";import{captureStatePath as Vg}from"document360-engine";var Gg={version:1,shots:{}};function HR(e){return e.replace(/^/,"").replace(/\r\n?/g,`
|
|
318
318
|
`).replace(/\n+$/,`
|
|
319
|
-
`)}function
|
|
320
|
-
`,"utf8")}function
|
|
321
|
-
${a[1]??" "}clipTo: ${l}${i.selector}${l},`);return c=c.replace(o,`${r}await captureShot(page, PLACEHOLDER);`),c=c.replace(
|
|
319
|
+
`)}function Yg(e){return Uu("sha1").update(HR(e)).digest("hex").slice(0,12)}function GR(e){return Uu("sha1").update(e).digest("hex").slice(0,12)}function ja(e){try{let t=JSON.parse(qg(BR(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]);if(!o)return null;let r=t.profiles?.[o],s=r?.scope??{},i=Object.keys(s).sort().map(a=>`${a}=${s[a]}`).join("&");return Uu("sha1").update(`${o}|${r?.connection?.startUrl??""}|${i}`).digest("hex").slice(0,12)}catch{return null}}function Tn(e){try{let t=JSON.parse(qg(Vg(e),"utf8").replace(/^/,""));return!t||typeof t!="object"||t.version!==1||!t.shots?{...Gg,shots:{}}:{version:1,shots:t.shots}}catch{return{...Gg,shots:{}}}}function qR(e,t){WR(Vg(e),`${JSON.stringify(t,null,2)}
|
|
320
|
+
`,"utf8")}function Fu(e){return e&&/data-testid|\btest-?id\b|has(?:n't| not) landed/i.test(e)?"testid":"data"}function Ia(e,t,n){if(t.length===0)return;let o=Tn(e),r=ja(e);for(let s of t){let i=s.specSource?Yg(s.specSource):void 0;o.shots[s.id]={outcome:s.outcome,at:n,...s.reason?{reason:s.reason}:{},...s.outcome==="skipped"?{blockedBy:Fu(s.reason)}:{},...i?{specHash:i}:{},...r?{envHash:r}:{}}}qR(e,o)}function Wu(e,t,n,o){let r=e.shots[t];return!r||n===null||!r.specHash||r.specHash!==Yg(n)&&r.specHash!==GR(n)||o&&r.envHash&&r.envHash!==o?null:r}function Kg(e){let t=Tn(e).shots;return Object.keys(t).filter(n=>t[n].outcome==="failed").sort()}function Bu(e,t,n){let o=Wu(Tn(e),t,n,ja(e));return!o||o.outcome==="captured"||!o.reason?null:{outcome:o.outcome,reason:o.reason}}Nr();import{existsSync as XR,readFileSync as Jg,readdirSync as Zg,writeFileSync as QR}from"node:fs";import{isAbsolute as JR,join as ey,resolve as ZR}from"node:path";import{readProjectConfig as eS,DEFAULT_CAPTURE_DIR as tS}from"document360-engine";var Qg="0.2.25";function Dr(e,t){if(!e)return!1;let n=s=>s.split("-")[0].split(".").map(i=>Number.parseInt(i,10)||0),o=n(e),r=n(t);for(let s=0;s<Math.max(o.length,r.length);s++){let i=(o[s]??0)-(r[s]??0);if(i!==0)return i>0}return!0}var nS=/^([ \t]*)await\s+([^\n;]+?)\.screenshot\(\{\s*path:\s*PLACEHOLDER\.saveTo\s*(?:,\s*fullPage:\s*(?:true|false)\s*)?,?\s*\}\)\s*;?[ \t]*$/m,oS=/^[ \t]*await\s+dumpAnnotations\(\s*page\s*,\s*PLACEHOLDER\s*\)\s*;?[ \t]*\r?\n?/m,ty="(?:'([^']+)'|\"([^\"]+)\"|`([^`]+)`)",rS=new RegExp(`^page\\s*\\.\\s*locator\\(\\s*${ty}\\s*\\)$`),ny=e=>e[1]??e[2]??e[3]??null,sS=/^[A-Za-z_$][\w$]*$/;function iS(e,t){let o=new RegExp(`\\bconst\\s+${t}\\s*=\\s*page\\s*\\.\\s*locator\\(\\s*${ty}\\s*\\)\\s*;`).exec(e);return o?ny(o):null}function aS(e,t){let n=t.trim();if(n==="page")return null;let o=rS.exec(n);if(o){let r=ny(o);return r?{selector:r}:{unresolved:!0}}if(sS.test(n)){let r=iS(e,n);return r?{selector:r}:{unresolved:!0}}return{unresolved:!0}}function oy(e){if(/\bcaptureShot\s*\(/.test(e))return null;let t=(e.match(/\.screenshot\(\{\s*path:\s*PLACEHOLDER\.saveTo/g)??[]).length;if(t>1)return{unresolved:`${t} conditional capture calls`};let n=nS.exec(e);if(!n)return null;let[o,r="",s=""]=n,i=aS(e,s);if(i===null)return null;if("unresolved"in i)return{unresolved:s.trim()};let a=/^([ \t]*)saveTo:\s*.+,[ \t]*$/m.exec(e);if(!a)return null;let l=i.selector.includes("'")?'"':"'",c=e.replace(a[0],`${a[0]}
|
|
321
|
+
${a[1]??" "}clipTo: ${l}${i.selector}${l},`);return c=c.replace(o,`${r}await captureShot(page, PLACEHOLDER);`),c=c.replace(oS,""),c=c.replace(/\bdumpAnnotations\b(?=[^\n]*from 'document360-capture\/helpers')/,"captureShot"),/from 'document360-capture\/helpers'/.test(c)&&!/\bcaptureShot\b[^\n]*from 'document360-capture\/helpers'/.test(c)&&(c=c.replace(/import \{([^}]*)\} from 'document360-capture\/helpers'/,(h,y)=>`import {${y.replace(/\s*$/,"")}, captureShot } from 'document360-capture/helpers'`)),{next:c,selector:i.selector}}function lS(e){try{return Zg(e).filter(t=>t.endsWith(".spec.ts")).some(t=>{try{let n=oy(Jg(ey(e,t),"utf8"));return n!==null&&!("unresolved"in n)}catch{return!1}})}catch{return!1}}function cS(e){let t=eS(e)?.captureDir??tS;return JR(t)?t:ZR(e,t)}function ry(e,t){let n={migrated:[],skipped:[]},o=cS(e);if(!XR(o))return n;let r=t?.captureVersion===void 0?Rt():t.captureVersion;if(!Dr(r,Qg))return lS(o)?{...n,heldBackForCapture:{installed:r,required:Qg}}:n;let s;try{s=Zg(o).filter(i=>i.endsWith(".spec.ts"))}catch{return n}for(let i of s.sort()){let a=i.slice(0,-8),l=ey(o,i);try{let c=Jg(l,"utf8"),h=oy(c);if(h===null)continue;if("unresolved"in h){n.skipped.push({id:a,receiver:h.unresolved});continue}QR(l,h.next,"utf8"),n.migrated.push(a)}catch{}}return n}function sy(e){if(e.heldBackForCapture){let{installed:n,required:o}=e.heldBackForCapture;return`\u26A0 Some capture specs need a fix that requires d360-capture ${o}+ (${n?`you have ${n}`:"not found on this machine"}). Until then their callouts may sit in the wrong place on cropped screenshots.
|
|
322
322
|
Run /update to bring the whole toolchain up, then /screenshot again.`}if(e.migrated.length===0&&e.skipped.length===0)return null;let t=[];return e.migrated.length>0&&t.push(`\u2195 Fixed ${e.migrated.length} capture spec${e.migrated.length===1?"":"s"} that cropped the screenshot without telling the annotator \u2014 their callouts were landing outside the image. Re-capture to pick up the fix.`),e.skipped.length>0&&t.push(`\u26A0 ${e.skipped.length} spec${e.skipped.length===1?"":"s"} crop${e.skipped.length===1?"s":""} to something that needs a human eye (${e.skipped.slice(0,3).map(n=>n.id).join(", ")}${e.skipped.length>3?"\u2026":""}) \u2014 /screenshot verify flags them if their callouts are off.`),t.join(`
|
|
323
|
-
`)}function Ce(e,t,n){return`${e}${n?` ${n}`:""}${t?` ${t}`:""}`}function
|
|
324
|
-
`):null}function
|
|
325
|
-
`))||o.push(r+1));return o}function
|
|
323
|
+
`)}function Ce(e,t,n){return`${e}${n?` ${n}`:""}${t?` ${t}`:""}`}function Mt(e){if(e.length===0)return;let t=e.map(r=>r.replace(/\\/g,"/"));if(t.length===1)return t[0];let n=r=>r.split("/").slice(0,-1).join("/"),o=n(t[0]);if(o!=="")return t.every(r=>n(r)===o)?o:void 0}Nr();var dy=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function iy(e){let t=e.includes("--detail")||e.includes("-d"),n=e.find(o=>o!=="--detail"&&o!=="-d");return{mode:"list",scope:n?dy(n):void 0,...t?{detail:!0}:{}}}function _s(e){let t=(e[0]??"").toLowerCase();if(t==="capture")return{mode:"capture",rest:e.slice(1)};if(t==="annotate")return{mode:"annotate",rest:e.slice(1)};if(t==="verify"||t==="review")return{mode:"verify",rest:e.slice(1)};if(t==="checklist"||t==="setup")return{mode:"checklist"};if(t==="list")return iy(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 iy(o.slice(1));let r=o[0];return r?r==="--all"?{mode:"all",setup:n}:/[\\/]/.test(r)||r.endsWith(".md")?{mode:"scope",scope:dy(r),setup:n}:{mode:"single",id:r}:{mode:"list",picker:!0}}function He(e,t,n){let o=Qn(e),r=o?.captureDir??Fa,s=o?.outputDir??Zu,i=(y,x)=>Ma(y)?_a(y,x):Ua(e,y,x),a=Tn(e),l=n?.captureVersion===void 0?Rt():n.captureVersion,c=Dr(l,my),h=ja(e);return cy(e,{scope:t}).map(({id:y,file:x})=>{let w=i(r,`${y}.spec.ts`),S=null;if(ly(w))try{S=Ju(w,"utf8")}catch{}let P=uy(e,s),T=gS(P,y),R=fS(T),D=mS(T),B=S===null?null:Wu(a,y,S,h),G=a.shots[y]?.review,Q=R&&pS(G,T.annotatedMtimeMs)?G:void 0,N=S!==null&&$S(S),ne=R&&Q?.verdict==="ok"?"verified":R&&Q?.verdict==="rejected"?"rejected":R?"annotated":D?"captured":S===null?"placeholder":N||B?.outcome==="skipped"?"blocked":B?.outcome==="failed"?"broken":"spec",te=S===null?void 0:hy(S),he=N?xS(S):B?.reason,we=N?"testid":B?.outcome==="skipped"?Fu(B.reason):void 0,ye=S===null?[]:vS(e,S);return{id:y,file:x,state:ne,...te?{mutates:te.mutates,...te.declared?{}:{undeclared:!0}}:{},...S!==null&&qu(S).length>0?{unguardedWaits:qu(S)}:{},...S!==null&&Gu(S).length>0?{unverifiedForce:Gu(S)}:{},...S!==null&&Vu(S).length>0?{handRolled:Vu(S)}:{},...S!==null&&Ku(S).length>0?{stalePause:Ku(S)}:{},...S!==null&&c&&Yu(S).length>0?{bareGoto:Yu(S)}:{},...ye.length>0?{staleAnchor:ye}:{},...ne==="blocked"||ne==="broken"?{...he?{reason:he}:{},...we?{blockedBy:we}:{}}:{},...ne==="rejected"?{...Q?.reason?{reason:Q.reason}:{},...Q?.repaired?{repaired:!0}:{}}:{}}})}function bS(e){let t=Qn(e)?.outputDir??Zu;return dS(uy(e,t))}function Mo(e){let t=bS(e),n=Qn(e)?.outputDir??Zu,o=[];t>0&&o.push(`\u2195 Tidied ${t} screenshot file${t===1?"":"s"} into ${n}/{${yS},${wS}} \u2014 annotated/ is what publishes, raw/ is the pre-annotation intermediate.`);let r=sy(ry(e));return r&&o.push(r),o.length>0?o.join(`
|
|
324
|
+
`):null}function _o(e,t){let n=Qn(e)?.captureDir??Fa,o=Ma(n)?_a(n,`${t}.spec.ts`):Ua(e,n,`${t}.spec.ts`);try{return Ju(o,"utf8")}catch{return null}}function py(e,t){let n=Qn(e)?.captureDir??Fa;return ly(Ma(n)?_a(n,`${t}.spec.ts`):Ua(e,n,`${t}.spec.ts`))}function kS(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 i=s[1].trim();if(!i||/^(CAPTURE-[A-Z]+:|TODO\b|NOTE\b|Grounding\b|\d+\.\s)/.test(i)||(o.push(i),o.join(" ").length>400))break}return o.join(" ")}function hy(e){let t=e.split(/\r?\n/),n=t.findIndex(a=>/^\s*\/\/\s*CAPTURE-SAFETY:\s*(readonly|mutates)\b/i.test(a)),o=n>=0?/^\s*\/\/\s*CAPTURE-SAFETY:\s*(readonly|mutates)\b[\s—:–-]*(.*)$/i.exec(t[n]):null;if(o){let a=kS(t,n,o[2]??"");return{mutates:o[1].toLowerCase()==="mutates",declared:!0,what:a||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),i=/\.fill\(/.test(e);return{mutates:r||i&&s,declared:!1}}function $S(e){return/(^|\n)\s*test\.skip\s*\(\s*['"`]/.test(e)}function fy(e){let t=[];for(let n of e.matchAll(/\/\/\s*CAPTURE-TODO:\s*(\{.*\})\s*$/gm))try{let o=JSON.parse(n[1]);o&&typeof o=="object"&&t.push(o)}catch{}return t}function vS(e,t){let n=[];for(let o of fy(t))hS(e,o.file,o.anchor)===!1&&n.push(o.testid??o.file??"unnamed request");return[...new Set(n)]}function xS(e){let{testid:t,file:n}=fy(e)[0]??{};return`Inert until your developers add ${t?`data-testid="${t}"${n?` in ${n}`:""}`:"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 Us(e){return e.split(/\r?\n/).map(t=>{if(/^\s*\*/.test(t))return"";let n=/(?<!:)\/\//.exec(t);return n?t.slice(0,n.index):t})}function Gu(e,t=10){let n=Us(e),o=[];for(let[r,s]of n.entries())/\.click\s*\([^)]*force\s*:\s*true/.test(s)&&(/test\.skip\s*\(/.test(n.slice(r+1,r+1+t).join(`
|
|
325
|
+
`))||o.push(r+1));return o}function qu(e){let t=[],n=Us(e);for(let[o,r]of n.entries()){if(!/\.waitFor\s*\(/.test(r))continue;let s=r;for(let i=o+1;i<n.length&&!/;\s*$/.test(s.trim())&&i<o+4;i++)s+=n[i];/\.catch\s*\(/.test(s)||t.push(o+1)}return t}function Vu(e){let t=[];for(let[n,o]of Us(e).entries())(/\.screenshot\s*\(/.test(o)||/\bdumpAnnotations\s*\(/.test(o))&&t.push(n+1);return t}var my="0.2.28";function Yu(e){let t=[];for(let[n,o]of Us(e).entries())/\.goto\s*\(/.test(o)&&t.push(n+1);return t}function Ku(e,t=6){let n=Us(e),o=[];for(let[r,s]of n.entries()){if(!/waitForTimeout\s*\(/.test(s))continue;let i=n.slice(r+1,r+1+t).join(`
|
|
326
326
|
`);if(!/test\.skip\s*\(/.test(i)||!/\.count\s*\(\s*\)/.test(i))continue;let a=n.slice(Math.max(0,r-t),r+1).join(`
|
|
327
|
-
`);/\.waitFor\s*\(|Promise\.race\s*\(|waitForFunction\s*\(|waitForSelector\s*\(/.test(a)||o.push(r+1)}return o}function
|
|
328
|
-
`)}function
|
|
329
|
-
`)}var bS={placeholder:"\u25CB",spec:"\u25D0",blocked:"\u2298",broken:"\u2717",captured:"\u25CF",annotated:"\u25C8",verified:"\u2714",rejected:"\u2691"},kS={placeholder:M.gray,spec:M.yellow,blocked:M.cyan,broken:M.red,captured:M.yellow,annotated:M.blue,verified:M.green,rejected:M.magenta},$S=` ${M.green("\u2714 verified")} ${M.blue("\u25C8 to verify")} ${M.yellow("\u25CF to annotate")} ${M.yellow("\u25D0 ready")} ${M.magenta("\u2691 rejected")} ${M.cyan("\u2298 blocked")} ${M.red("\u2717 broken")} ${M.gray("\u25CB to spec")}`;function V(e,t=n=>n){return`${t(e)} `}function jr(e){return e.replace(/\s+/g," ").trim().replace(/^Prerequisites? not met[:—-]?\s*/i,"")}function Ha(e){let t=jr(e),n=/^(.*?[a-z0-9)"'”’])\.(?:\s|$)/i.exec(t);return(n?n[1]:t).trim()}function _s(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=Ha(o),i=`${r} ${s.toLowerCase()}`,a=t.get(i)??{reason:s,blockedBy:r,ids:[]};t.has(i)||t.set(i,a),a.ids.push(n.id)}return[...t.values()].sort((n,o)=>o.ids.length-n.ids.length||n.reason.localeCompare(o.reason))}function my(e){let t=_s(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((a,l)=>a+l.ids.length,0);r.push(` ${M.bold("Stage this data")} ${M.gray(`\u2014 unblocks ${s} shot${s===1?"":"s"} in ${n.length} action${n.length===1?"":"s"}`)}`);let i=8;for(let a of n.slice(0,i)){let l=ln(a.reason,86);r.push(` ${M.cyan(Kn(`${a.ids.length}\xD7`,4))} ${l[0]??""}`);for(let h of l.slice(1))r.push(` ${h}`);let c=a.ids.slice(0,4).join(" \xB7 ");r.push(M.gray(` ${c}${a.ids.length>4?` \xB7 +${a.ids.length-4} more`:""}`))}n.length>i&&r.push(M.gray(` \u2026 ${n.length-i} more staging action${n.length-i===1?"":"s"} \u2014 /screenshot list --detail`))}if(o.length>0){let s=o.reduce((i,a)=>i+a.ids.length,0);r.push(` ${V("\u2298",M.cyan)}${s} shot${s===1?"":"s"} need${s===1?"s":""} a data-testid from your developers \u2014 ${M.bold("/screenshot checklist")} builds the hand-off.`)}return r}function td(e){if(e.length===0)return[];let t=e.slice(0,6),n=e.length;return["",` ${V("\u26A0",M.yellow)}${n} screenshot marker${n===1?"":"s"} will be ignored \u2014 ${n===1?"it is":"they are"} not shaped the way the publish step needs`+M.gray(`, so ${n===1?"that picture":"those pictures"} would never be taken`),...t.map(o=>M.gray(` ${o.file}:${o.line} \u2014 ${o.reason}`)),...n>t.length?[M.gray(` \u2026and ${n-t.length} more`)]:[],M.gray(" Usually a reviewer comment wrapped around it. A marker must start its own line and carry an id:.")]}function gy(e,t){let n=e.filter(i=>(i.staleAnchor?.length??0)>0);if(n.length===0)return[];let o=[...new Set(n.flatMap(i=>i.staleAnchor))],r=o.length,s=["",` ${V("\u26A0",M.yellow)}${r} selector request${r===1?"":"s"} quote${r===1?"s":""} source code that has since changed`+M.gray(" \u2014 your developers would go looking for something that isn't there any more"),M.gray(` Refresh the hand-off before sending it: ${M.bold("/screenshot checklist")}`)];return t&&s.push(M.gray(` ${o.slice(0,8).join(" \xB7 ")}${r>8?` \xB7 +${r-8} more`:""}`)),s}function yy(e,t,n){let o=e.filter(h=>(h.unguardedWaits?.length??0)>0),r=e.filter(h=>h.undeclared),s=e.filter(h=>(h.handRolled?.length??0)>0),i=e.filter(h=>(h.stalePause?.length??0)>0),a=e.filter(h=>(h.bareGoto?.length??0)>0);if(o.length===0&&r.length===0&&s.length===0&&i.length===0&&a.length===0)return[];let l=["",` ${V("\u26A0",M.yellow)}Some specs were written before later reliability fixes:`],c=(h,y)=>` ${h.slice(0,8).map(y).join(" \xB7 ")}${h.length>8?` \xB7 +${h.length-8} more`:""}`;if(o.length>0){let h=o.length;l.push(M.gray(` ${h} crash${h===1?"es":""} instead of telling you what to stage when the data ${h===1?"it needs":"they need"} is missing`)),t&&l.push(M.gray(c(o,y=>`${y.id}:${y.unguardedWaits.join(",")}`)))}if(a.length>0){let h=a.length;l.push(M.gray(` ${h} open${h===1?"s":""} pages the slow way, so ${h===1?"it stalls":"they stall"} for a minute and give up when several shots run at once`)),t&&l.push(M.gray(c(a,y=>`${y.id}:${y.bareGoto.join(",")}`)))}if(i.length>0){let h=i.length;l.push(M.gray(` ${h} decide${h===1?"s":""} "the data is missing" from a fixed pause, so data you HAVE staged can read as absent`)),t&&l.push(M.gray(c(i,y=>`${y.id}:${y.stalePause.join(",")}`)))}if(s.length>0){let h=s.length;l.push(M.gray(` ${h} take${h===1?"s":""} ${h===1?"its":"their"} own screenshot instead of the one call that positions the callouts too \u2014 on a cropped shot the numbers land in the wrong places, and nothing reports it`)),t&&l.push(M.gray(c(s,y=>`${y.id}:${y.handRolled.join(",")}`)))}if(r.length>0){let h=r.length,y=r.filter(x=>x.mutates).length;l.push(M.gray(` ${h} do${h===1?"es":""} not say whether ${h===1?"it changes":"they change"} data in your app`+(y>0?`, so ${y===1?"one is":`${y} are`} left out of bulk runs to be safe`:""))),t&&l.push(M.gray(c(r,x=>x.id)))}return n?.commandInLead||l.push(M.gray(` Re-write them all with the current rules: ${M.bold("/screenshot author --all")}`)),l}function wy(e){let t=e.filter(n=>(n.unverifiedForce?.length??0)>0);return t.length===0?[]:["",` ${V("\u26A0",M.red)}${t.length} spec${t.length===1?"":"s"} force-click past Playwright's safety checks without asserting the result`+M.gray(" \u2014 if the click lands on nothing, the shot photographs the unchanged screen"),M.gray(` ${t.slice(0,6).map(n=>`${n.id}:${n.unverifiedForce.join(",")}`).join(" \xB7 ")}${t.length>6?` \xB7 +${t.length-6} more`:""}`),M.gray(` Re-author to check what the click did: ${M.bold("/screenshot author <id>")}`)]}var La=(e,t)=>e.length>=t?e:e+" ".repeat(t-e.length),Kn=(e,t)=>e.length>=t?e:" ".repeat(t-e.length)+e;function by(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 vS=new Set(["and","or","of","the","to","a","an","in","on","for","with","vs"]),xS=new Set(["ai","api","cli","ui","ux","url","id","http","https","json","xml","sdk","csv","pdf","oauth","sso","mfa","io","faq"]);function RS(e){return e.replace(/[-_]+/g," ").trim().split(/\s+/).filter(Boolean).map((n,o)=>{let r=n.toLowerCase();return xS.has(r)?r.toUpperCase():o>0&&vS.has(r)?r:r.charAt(0).toUpperCase()+r.slice(1)}).join(" ")}function Ku(e){if(!e)return{num:"",name:"(docs root)"};let t=/^(\d+)[-_](.+)$/.exec(e);return{num:t?t[1]:"",name:RS(t?t[2]:e)}}function SS(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).pop()??e}function oy(e,t,n){let o=t>0?Math.round(e/t*n):0;return M.green("\u2588".repeat(o))+M.gray("\u2591".repeat(Math.max(0,n-o)))}function CS(e,t){let n=t>0?Math.round(e/t*100):0,o=Kn(`${n}%`,4);return n===100?M.green(o):n>0?M.yellow(o):M.gray(o)}function ky(e,t){let n=new Map;for(let o of e){let r=by(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 nd(e,t){let n=T=>e.filter(R=>R.state===T).length,o=n("captured"),r=n("placeholder"),s=n("spec"),i=n("annotated"),a=n("blocked"),l=n("broken"),c=n("rejected"),h=e.filter(T=>T.state==="spec"&&T.mutates).length,y=s>h,x=e.filter(T=>(T.unguardedWaits?.length??0)>0||(T.bareGoto?.length??0)>0).length,w=e.filter(T=>(T.stalePause?.length??0)>0||(T.handRolled?.length??0)>0).length,S=s>0||a>0||l>0,P=(T,R="")=>Ce(T,R,t);return o>0?{key:"annotate",cmd:P("/screenshot annotate")}:r>0?{key:"toSpec",cmd:t?`/screenshot author ${t}`:"/screenshot author --all"}:x>0&&S?{key:"crashy",cmd:t?`/screenshot author ${t}`:"/screenshot author --all"}:w>0&&S?{key:"wrongOutput",cmd:t?`/screenshot author ${t}`:"/screenshot author --all"}:s>0&&(y||i===0)?{key:"ready",cmd:P("/screenshot capture")}:i>0&&s>0?{key:"verify",cmd:P("/screenshot verify")}:a>0?{key:"blocked",cmd:P("/screenshot capture","--blocked")}:l>0?{key:"broken",cmd:`/screenshot ${e.find(T=>T.state==="broken").id}`}:i>0?{key:"verify",cmd:P("/screenshot verify")}:c>0?{key:"rejected",cmd:P("/screenshot capture","--failed")}:{key:"done",cmd:t?`/push ${t}`:"/push"}}function PS(e,t,n=[]){let o=(ee,Ee)=>ee.filter(_e=>_e.state===Ee).length,r=e.length,s=o(e,"verified"),i=o(e,"annotated"),a=o(e,"captured"),l=o(e,"rejected"),c=o(e,"spec"),h=o(e,"blocked"),y=o(e,"broken"),x=o(e,"placeholder"),w=new Set(e.map(ee=>ee.file)).size,S=ky(e,t),P=[];P.push(` ${M.bold("Screenshots")} ${M.green(`${s}/${r} verified`)} ${M.gray("\xB7")} ${i>0?M.blue(`${i} to verify`):M.gray("0 to verify")}`+(a>0?` ${M.gray("\xB7")} ${M.yellow(`${a} to annotate`)}`:"")+(l>0?` ${M.gray("\xB7")} ${M.magenta(`${l} rejected`)}`:"")+` ${M.gray("\xB7")} ${c>0?M.yellow(`${c} ready`):M.gray("0 ready")}`+(h>0?` ${M.gray("\xB7")} ${M.cyan(`${h} blocked`)}`:"")+(y>0?` ${M.gray("\xB7")} ${M.red(`${y} broken`)}`:"")+` ${M.gray("\xB7")} ${x>0?M.red(`${x} to spec`):M.gray("0 to spec")} `+M.gray(`across ${w} article${w===1?"":"s"}`));let T=r>0?Math.round(s/r*100):0;P.push(` [${oy(s,r,32)}] ${M.bold(`${T}%`)}`),P.push("");let R=S.map(([ee])=>Ku(ee)),N=Math.min(32,Math.max(7,...R.map(ee=>ee.name.length))),B=ee=>ee.length>N?`${ee.slice(0,N-1)}\u2026`:La(ee,N),G=[...a>0?[{head:"To annotate",w:11,state:"captured",color:M.yellow}]:[],...i>0?[{head:"To verify",w:9,state:"annotated",color:M.blue}]:[],...l>0?[{head:"Rejected",w:8,state:"rejected",color:M.magenta}]:[],{head:"Ready",w:5,state:"spec",color:M.yellow},...h>0?[{head:"Blocked",w:7,state:"blocked",color:M.cyan}]:[],...y>0?[{head:"Broken",w:6,state:"broken",color:M.red}]:[],{head:"To spec",w:7,state:"placeholder",color:M.red}];P.push(M.gray(` ${La("#",2)} ${La("Chapter",N)} ${Kn("Verified",8)} ${G.map(ee=>Kn(ee.head,ee.w)).join(" ")} Progress`));for(let[ee,[,Ee]]of S.entries()){let _e=o(Ee,"verified"),ze=Ee.length,{num:uo,name:Pe}=R[ee],Ne=_e===ze,Ze=B(Pe),sn=G.map(Ct=>{let po=o(Ee,Ct.state);return po>0?Ct.color(Kn(String(po),Ct.w)):M.gray(Kn("\u2014",Ct.w))}).join(" ");P.push(` ${M.cyan(La(uo,2))} ${Ne?M.green(Ze):_e>0?Ze:M.gray(Ze)} ${Ne?M.green(Kn(`${_e}/${ze}`,8)):Kn(`${_e}/${ze}`,8)} ${sn} ${oy(_e,ze,10)} ${CS(_e,ze)}`)}P.push("");let Q=y>0?` ${M.gray("\xB7")} ${y} spec${y===1?"":"s"} broken \u2014 ${M.bold(`/screenshot ${e.find(ee=>ee.state==="broken").id}`)} re-authors ${y===1?"it":"the first"}`:"",j=e.filter(ee=>ee.state==="spec"&&ee.mutates).length,ne=c>j,te=e.filter(ee=>(ee.unguardedWaits?.length??0)>0||(ee.bareGoto?.length??0)>0).length,ye=e.filter(ee=>(ee.stalePause?.length??0)>0||(ee.handRolled?.length??0)>0).length,$e=c>0||h>0||y>0,ge=!1,be=nd(e).key;if(be==="annotate")P.push(` ${V("\u25C8",M.blue)}${a} shot${a===1?"":"s"} taken but not drawn on \u2014 run ${M.bold("/screenshot annotate")}`+M.gray(` \u2014 no browser, seconds; the callouts are what make ${a===1?"it":"them"} publishable`)+Q);else if(be==="toSpec")P.push(` ${V("\u2192",M.yellow)}${x} placeholder${x===1?"":"s"} still need a spec \u2014 run ${M.bold("/screenshot author --all")}${Q}`);else if(be==="crashy")ge=!0,P.push(` ${V("\u2192",M.yellow)}${te} spec${te===1?"":"s"} would crash mid-run \u2014 re-write ${te===1?"it":"them"} first: ${M.bold("/screenshot author --all")}`+M.gray(` \xB7 then ${M.bold("/screenshot capture")} (no browser time wasted on ${te===1?"a shot":"shots"} that can't finish)`)+Q);else if(be==="wrongOutput")ge=!0,P.push(` ${V("\u2192",M.yellow)}${ye} spec${ye===1?"":"s"} would shoot the wrong thing \u2014 re-write ${ye===1?"it":"them"} first: ${M.bold("/screenshot author --all")}`+M.gray(` \xB7 then ${M.bold("/screenshot capture")} (a false skip or a misplaced callout costs the same browser time as a good shot)`)+Q);else if(be==="ready"){let ee=j>0?M.gray(` \u2014 ${c-j} in one go; ${j} write${j===1?"s":""} real data and run${j===1?"s":""} one at a time`):"";P.push(` ${V("\u2192",M.yellow)}${c} spec${c===1?"":"s"} ready to capture \u2014 run ${M.bold("/screenshot capture")}${ee}${Q}`)}else if(be==="verify"&&c>0)P.push(` ${V("\u2192",M.blue)}${i} shot${i===1?"":"s"} awaiting verification \u2014 run ${M.bold("/screenshot verify")}`+M.gray(" \u2014 no browser needed")+M.gray(` \xB7 ${c} ready spec${c===1?"":"s"} write real data, so ${c===1?"it runs":"each runs"} only when named: /screenshot capture <id>`)+Q);else if(be==="blocked")P.push(` ${V("\u2192",M.cyan)}${h} shot${h===1?"":"s"} blocked \u2014 stage the data below, then ${M.bold("/screenshot capture --blocked")}${Q}`);else if(be==="broken")P.push(` ${V("\u2192",M.red)}${y} spec${y===1?"":"s"} broken \u2014 ${M.bold(`/screenshot ${e.find(ee=>ee.state==="broken").id}`)} re-authors ${y===1?"it":"the first"} (re-capturing fails the same way)`);else if(be==="verify")P.push(` ${V("\u2192",M.blue)}${i} shot${i===1?"":"s"} awaiting verification \u2014 run ${M.bold("/screenshot verify")}`+M.gray(" \u2014 it checks each picture against what its article needs (no browser, no re-capture)"));else if(be==="rejected"){let ee=e.filter(Ee=>Ee.state==="rejected"&&Ee.repaired).length;P.push(` ${V("\u2691",M.magenta)}${l} shot${l===1?"":"s"} failed review \u2014 `+(ee>0?`${ee} spec${ee===1?"":"s"} already repaired; re-capture with ${M.bold("/screenshot capture --failed")}`:`see the reasons below, then ${M.bold("/screenshot capture --failed")}`))}else P.push(` ${V("\u2713",M.green)}all ${r} verified \u2014 ${M.bold("/push")} embeds them in the articles`);if(s>0&&s<r){let ee=S.filter(([,Ee])=>Ee.every(_e=>_e.state!=="verified")).map(([Ee])=>{let{num:_e,name:ze}=Ku(Ee);return _e?`${_e} ${ze}`:ze});ee.length>0&&P.push(M.gray(` Furthest behind: ${ee.slice(0,5).join(" \xB7 ")}${ee.length>5?" \u2026":""} (0% verified)`))}return P.push(...my(e),...wy(e),...yy(e,!1,{commandInLead:ge}),...gy(e,!1),...td(n)),P.push(""),P.push(M.gray(" Drill in: /screenshot list <chapter#> \xB7 /screenshot list --detail (all)")),P}function TS(e,t,n,o=[]){let r=new Set(e.map(c=>c.file)),s=e.filter(c=>c.state==="verified").length,i=e.filter(c=>c.state==="annotated").length,a=e.filter(c=>c.state==="captured").length,l=[` ${M.bold("Screenshots")}: ${e.length} placeholder${e.length===1?"":"s"} across ${r.size} article${r.size===1?"":"s"} \xB7 ${M.green(`${s} verified`)}${i>0?M.blue(` \xB7 ${i} to verify`):""}${a>0?M.yellow(` \xB7 ${a} to annotate`):""}${n?M.gray(` \xB7 scope ${n}`):""}`,""];for(let[c,h]of ky(e,t)){let y=h.filter(T=>T.state==="verified").length,{num:x,name:w}=Ku(c),S=x?`${x} \xB7 ${w}`:w;l.push(` ${M.bold(S)} ${M.gray(`(${y}/${h.length})`)}`);let P=new Map;for(let T of h){let R=SS(T.file),N=P.get(R)??[];P.has(R)||P.set(R,N),N.push(T)}for(let T of[...P.keys()].sort()){l.push(M.gray(` ${T}`));for(let R of P.get(T)){let N=kS[R.state];if(l.push(` ${V(bS[R.state],N)}${N(R.id)}`),(R.state==="blocked"||R.state==="broken"||R.state==="rejected")&&R.reason){for(let B of ln(jr(R.reason),84))l.push(M.gray(` ${B}`));R.state==="rejected"&&l.push(M.gray(` ${R.repaired?"spec repaired \u2014 re-capture to confirm":"spec not yet repaired"}`))}}}}return l.push(...my(e),...wy(e),...yy(e,!0),...gy(e,!0),...td(o)),l.push("",$S),l}function Ga(e,t){let n=t?.scope,o=t?.markerProblems??[];if(e.length===0)return[n?`No screenshot placeholders under ${n}.`:"No screenshot placeholders found in the docs.",...td(o)];let r=t?.docsDir??Zu;return t?.detail||n?TS(e,r,n,o):PS(e,r,o)}function od(e,t){if(!t||!/^\d+$/.test(t))return t;let n=zn(e)?.docsDir??Zu,o=String(Number(t));for(let{file:r}of sy(e)){let s=by(r,n),i=/^(\d+)/.exec(s);if(i&&String(Number(i[1]))===o)return s}return t}function $y(e,t){let r=e.map(a=>" ".repeat(a.depth)+a.label),s=Math.max(0,...e.map((a,l)=>a.note?Ia(r[l]):0)),i=Math.min(s,Math.max(0,t-2-24));return e.map((a,l)=>{let c=r[l];if(!a.note)return{head:c,note:""};let h=Math.max(2,i+2-Ia(c)),y=a.note.trim(),x=t-Ia(c)-h;return{head:c+" ".repeat(h),note:x>1&&Ia(y)>x?`${y.slice(0,x-1)}\u2026`:y}})}function AS(e){let t=e.replace(/\\/g,"/").split("/").filter(Boolean),n=t.pop()??e;return{category:t.pop()??"(docs root)",article:n}}function Dr(e,t,n){let o=new Map;for(let s of t){let{category:i,article:a}=AS(s.file),l=o.get(i)??new Map;o.set(i,l);let c=l.get(a)??[];l.set(a,c),c.push(s)}let r=s=>n!=="capture"||!s.mutates;for(let s of[...o.keys()].sort()){let i=o.get(s),a=[...i.values()].flat().filter(r).map(c=>c.id),l=a.length>0;l&&e.push({kind:"category",action:n,label:`${s} (${a.length})`,ids:a,depth:1});for(let c of[...i.keys()].sort()){let h=i.get(c),y=h.filter(r).map(S=>S.id),x=y.length>0;x&&e.push({kind:"article",action:n,label:`${c} (${y.length})`,ids:y,depth:l?2:1});let w=(l?1:0)+(x?1:0)+1;for(let S of h){let P=n==="capture"&&S.mutates?" \u26A0 creates real data \u2014 runs only alone":void 0;e.push({kind:"shot",action:n,label:S.id,ids:[S.id],depth:w,...P?{note:P}:{}})}}}}function Bu(e){return e?jr(e):""}function rd(e,t,n,o=[]){let r=t.filter(i=>!i.mutates);r.length>1&&e.push({kind:"all",action:"capture",label:`Retry ${r.length} blocked shots (Prerequisites not met \u2014 Stage the data first)`,ids:r.map(i=>i.id),depth:0});for(let i of[...t].sort((a,l)=>a.id.localeCompare(l.id)))e.push({kind:"shot",action:"capture",label:i.id,ids:[i.id],depth:1,note:` \u2298 ${Bu(i.reason)}`});n.length>1&&e.push({kind:"all",action:"author",label:`Re-author ${n.length} broken specs`,ids:n.map(i=>i.id),depth:0});for(let i of[...n].sort((a,l)=>a.id.localeCompare(l.id)))e.push({kind:"shot",action:"author",label:i.id,ids:[i.id],depth:1,note:` \u2717 re-authors \u2014 ${Bu(i.reason)}`});let s=o.filter(i=>!i.mutates);s.length>1&&e.push({kind:"all",action:"capture",label:`Re-capture ${s.length} shots that failed review`,ids:s.map(i=>i.id),depth:0});for(let i of[...o].sort((a,l)=>a.id.localeCompare(l.id))){let a=i.repaired?"re-captures":"re-captures (spec not yet repaired)";e.push({kind:"shot",action:"capture",label:i.id,ids:[i.id],depth:1,note:` \u2691 ${a} \u2014 ${Bu(i.reason)}`})}}function vy(e){let t=e.filter(i=>i.state==="placeholder"),n=e.filter(i=>i.state==="spec"),o=[];t.length>1&&o.push({kind:"all",action:"author",label:`Author all ${t.length} remaining specs`,ids:t.map(i=>i.id),depth:0}),Dr(o,t,"author");let r=n.filter(i=>!i.mutates);r.length>1&&o.push({kind:"all",action:"capture",label:`Capture all ${r.length} ready specs`,ids:r.map(i=>i.id),depth:0}),Dr(o,n,"capture");let s=e.filter(i=>i.state==="captured");return s.length>1&&o.push({kind:"all",action:"annotate",label:`Draw the callouts on all ${s.length} shots`,ids:s.map(i=>i.id),depth:0}),Dr(o,s,"annotate"),rd(o,e.filter(i=>i.state==="blocked"),e.filter(i=>i.state==="broken"),e.filter(i=>i.state==="rejected")),o}var zu=["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 guard on the SAME predicate the action needs: `.click()` requires visible AND ENABLED, so a",' DISABLED button passes both waitFor({state:"visible"}) and count()>0 and then times out at 15s'," (measured). Add `|| !(await x.isEnabled().catch(() => false))` to the condition, and put the"," control's own title/aria-disabled text in the skip reason \u2014 a disabled control is the product"," telling you the prerequisite is unmet, usually with the reason attached.",' 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."," Two corollaries, both of which have cost a wasted repair round:"," (a) An element that is not RENDERED is not absent. A collapsed tree node, an unopened accordion,"," an inactive tab, a virtualised list or page 2 of a table keeps its children out of the DOM."," EXPAND/scroll/switch to reach the target \u2014 that is a step to script, not data to stage."," (b) When you narrow past a decoy, count the UNNARROWED set too and put the number in the reason:",' "Found 6 folder roll-ups but no endpoint-level score \u2014 if one exists it may not be rendered".',' A bare "prerequisite not met" cannot tell absent data from an over-narrow selector. Put that'," evidence in a LATER sentence, never the first: grouping keys on the first sentence, so an",' interpolated count there makes every run its own "action" and the dedup stops working.'," (c) `click({ force: true })` is the ONE pattern that turns a failure into a silent WRONG"," SCREENSHOT rather than a crash or skip: it skips the actionability checks, so a click that"," lands on nothing photographs the unchanged screen and that image ships in the docs. It is"," sometimes right (a button nested inside a button reads as intercepted by its own ancestor)."," Never force blind: ground it in source, scrollIntoViewIfNeeded() first, and ASSERT THE"," CONSEQUENCE immediately after with a guarded wait + test.skip, so a no-op force skips."," Know its limit: force skips the CHECK but still hit-tests real screen coordinates, so the"," element that RECEIVES the event may not be the one your locator names (measured: a forced"," click on a pill nested in its section-header button never ran the pill's own handler).",' For a genuinely nested interactive node use `locator.dispatchEvent("click")`, which goes'," straight to that node with no hit-test \u2014 and still assert the consequence."," (d) Never bind a locator to an attribute your own interaction CHANGES. A locator is re-evaluated",' on every use, so `button[title="Multi-select scenarios"]` matches nothing once the click',' flips it to `title="Exit select mode"` \u2014 a 15s "not found" timeout on an element that is'," right there (measured). Toggling labels are normal (Play/Pause, Expand/Collapse, Select"," all/Deselect all): if the attribute is a ternary on state it is not an identity. Match both"," values in one locator, or use a testid."," (e) Cleanup after the screenshot is BEST-EFFORT and must never throw or test.skip. Anything"," after captureShot() runs with the image already on disk, so a throw there turns a successful"," capture into a reported failure and the shot is thrown away (measured: a valid .raw.png plus"," annotations, reported broken). Guard with isVisible()/isEnabled() and click best-effort \u2014 by"," then there is nothing left to skip."," (f) An element that is RENDERED can still be EMPTY. A component may mount an input/textarea/pane",' with no content and fill it when its fetch resolves, so waitFor({state:"visible"}) proves the'," node exists, not that the data arrived \u2014 reading inputValue()/textContent() right after can"," catch the pre-fetch empty state and false-skip data that IS there. When the decision rests on"," a VALUE rather than on presence, wait for the value: page.waitForFunction(sel => { const el =",' document.querySelector(sel); return !!el && (el.value ?? el.textContent ?? "").trim() !== ""; },',' "<selector>", { timeout: 10_000 }).catch(() => {}) \u2014 THEN read it and skip on empty.'," (g) NEVER take the screenshot yourself. `captureShot(page, PLACEHOLDER)` is the only capture call:"," it shoots AND resolves the callout positions in one pass, so they cannot disagree. A"," page.screenshot()/locator.screenshot() + dumpAnnotations() pair measures coordinates against"," the whole page while a cropped image starts at the crop corner, so every pin and highlight is"," offset \u2014 and nothing errors, so the spec reports success and the picture is wrong."," (h) EVERY navigation goes through `gotoResilient` (from document360-capture/helpers), never a bare",' page.goto(): `await gotoResilient(page)` for the start URL, `gotoResilient(page, "/route")`',` mid-spec. Under a bulk run, sibling specs saturate the network and goto's default "load" wait`," never fires \u2014 four specs died on that identical first line, each patched by hand.","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."," That consistency applies WITHIN one spec too, and a spec with 2+ test.skip calls needs two checks:"," (a) does a LATER branch's reason still HOLD, given what passing the earlier guard already proved?",` A later branch that reuses an earlier one's reason verbatim ("sign in as an owner\u2026") when`," reaching it proves that condition passed does not just read oddly \u2014 it misdiagnoses the cause"," and sends the reader to fix something that is already fine."," (b) do multiple branches for the SAME prerequisite (found 0 vs found fewer than N) open with one"," identical sentence? Divergent openings defeat the grouping even within a single spec.","Before you finish, re-read each spec you wrote and check every rule above line by line."].join(`
|
|
330
|
-
`);function
|
|
331
|
-
`),"",...r.length>0?["REPAIR: 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).",...r.map(i),""]:[],...s.length>0?["REPAIR: these already have a spec and it SKIPPED. Treat each reason as SUSPECT, not as proof","the spec is right: a FALSE skip is indistinguishable from a true one from inside the spec, and","you are being asked to re-author rather than to stage. Check TWO things before concluding a","spec needs no change. (1) Is the target RENDERED? A collapsed tree node, unopened accordion,","inactive tab, virtualised list or page 2 of a table keeps children out of the DOM, so the count","is zero for data one click away, so expanding is a step to SCRIPT. (2) Is the selector too narrow?","If you filtered past a decoy, count the unnarrowed set and put the number in the reason. A spec","that satisfies every rule and still cannot reach its target is NOT correct.",...s.map(i),""]:[],...a.flatMap(l=>
|
|
332
|
-
`)}async function
|
|
333
|
-
`),display:`/screenshot ${o.id}`}}if(o.mode==="capture"||o.mode==="annotate"||o.mode==="verify"||o.mode==="checklist")return{kind:"continue"};let i=[`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-CHECKLIST.md.":""} Report specs written, TODO data-testids, and data to stage.`,
|
|
334
|
-
`),a=o.mode==="scope"?`/screenshot ${o.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:i,display:a}}import{readDocsPlan as
|
|
327
|
+
`);/\.waitFor\s*\(|Promise\.race\s*\(|waitForFunction\s*\(|waitForSelector\s*\(/.test(a)||o.push(r+1)}return o}function td(e,t){let n=h=>`line${h.length===1?"":"s"} ${h.join(", ")}`,o=[],r=t?.captureVersion===void 0?Rt():t.captureVersion,s=Dr(r,my)?Yu(e):[];s.length>0&&o.push(`- ${n(s)}: navigates with a bare page.goto(). EVERY navigation must go through gotoResilient (from document360-capture/helpers) \u2014 \`await gotoResilient(page)\` for the start URL, \`await gotoResilient(page, "/route")\` mid-spec. Under a bulk run goto's default "load" wait never fires and the spec dies at 60s on that line.`);let i=qu(e);i.length>0&&o.push(`- ${n(i)}: a .waitFor() whose timeout is not swallowed, so a missing prerequisite hard-fails instead of skipping. Add .catch(() => {}), then read the element and test.skip with a reason.`);let a=Vu(e);a.length>0&&o.push(`- ${n(a)}: takes its own screenshot (or calls dumpAnnotations) instead of captureShot(page, PLACEHOLDER). On a cropped shot that misplaces every callout and nothing errors.`);let l=Ku(e);l.length>0&&o.push(`- ${n(l)}: the "data is missing" decision rests on a fixed waitForTimeout, so staged data can read as absent. Give the element a bounded chance to appear first, then count.`);let c=Gu(e);return c.length>0&&o.push(`- ${n(c)}: click({ force: true }) with no assertion that it worked, so a no-op click photographs the unchanged screen. Assert the expected result immediately after, guarded, and skip if it never arrives.`),/CAPTURE-SAFETY:/.test(e)||o.push("- no CAPTURE-SAFETY marker: add exactly one `// CAPTURE-SAFETY: readonly` or `// CAPTURE-SAFETY: mutates \u2014 <what>; cleanup: <how>` at the top."),o}function gy(e,t){return e.length===0?[]:[t,...e,"These are SEPARATE from whatever else you were asked to fix \u2014 clear them in the same pass. They were","found by scanning the file, so they are facts about it, not suggestions.",""]}function yy(e){return(e??"").trim().replace(/[.\s]+$/,"")}function wy(e,t){let n=Qn(e)?.captureDir??Fa,o=Ma(n)?_a(n,`${t}.spec.ts`):Ua(e,n,`${t}.spec.ts`);try{return hy(Ju(o,"utf8"))}catch{return{mutates:!1,declared:!1}}}var RS=["annotated","verified","rejected"],SS=e=>RS.includes(e);function CS(e){return[...new Set(e.filter(t=>SS(t.state)).map(t=>t.file))].sort()}function Wa(e,t){let n=CS(e);if(!t)return n;let o=t.replace(/\\/g,"/").replace(/\/+$/,"");return n.filter(r=>{let s=r.replace(/\\/g,"/");return s===o||s.startsWith(`${o}/`)||s.endsWith(`/${o}`)})}function Ba(e,t){let n=e.filter(s=>s.state==="captured");if(n.length===0)return null;let o=Math.max(...n.map(s=>s.id.length)),r=n.length===1;return[`${V("\u26A0",M.yellow)}${n.length} screenshot${r?" has":"s have"} been taken but the callouts aren't drawn on yet, so ${r?"it has":"they have"} no picture to publish:`,...n.map(s=>` ${M.yellow(s.id.padEnd(o))}`),` Publishing without ${r?"it":"them"}. Finish ${r?"it":"them"} first: ${M.bold(Ce("/screenshot annotate","",t))}`].join(`
|
|
328
|
+
`)}function Ha(e){let t=e.filter(o=>o.state==="rejected");if(t.length===0)return null;let n=Math.max(...t.map(o=>o.id.length));return[`${V("\u26A0",M.yellow)}${t.length} screenshot${t.length===1?"":"s"} failed verification:`,...t.map(o=>` ${M.magenta(o.id.padEnd(n))} ${M.gray(Ir(o.reason??"no reason recorded"))}`),` Publishing anyway. Fix + re-capture: ${M.bold("/screenshot capture --failed")}`].join(`
|
|
329
|
+
`)}var PS={placeholder:"\u25CB",spec:"\u25D0",blocked:"\u2298",broken:"\u2717",captured:"\u25CF",annotated:"\u25C8",verified:"\u2714",rejected:"\u2691"},TS={placeholder:M.gray,spec:M.yellow,blocked:M.cyan,broken:M.red,captured:M.yellow,annotated:M.blue,verified:M.green,rejected:M.magenta},AS=` ${M.green("\u2714 verified")} ${M.blue("\u25C8 to verify")} ${M.yellow("\u25CF to annotate")} ${M.yellow("\u25D0 ready")} ${M.magenta("\u2691 rejected")} ${M.cyan("\u2298 blocked")} ${M.red("\u2717 broken")} ${M.gray("\u25CB to spec")}`;function V(e,t=n=>n){return`${t(e)} `}function Ir(e){return e.replace(/\s+/g," ").trim().replace(/^Prerequisites? not met[:—-]?\s*/i,"")}function Ga(e){let t=Ir(e),n=/^(.*?[a-z0-9)"'”’])\.(?:\s|$)/i.exec(t);return(n?n[1]:t).trim()}function Fs(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=Ga(o),i=`${r} ${s.toLowerCase()}`,a=t.get(i)??{reason:s,blockedBy:r,ids:[]};t.has(i)||t.set(i,a),a.ids.push(n.id)}return[...t.values()].sort((n,o)=>o.ids.length-n.ids.length||n.reason.localeCompare(o.reason))}function by(e){let t=Fs(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((a,l)=>a+l.ids.length,0);r.push(` ${M.bold("Stage this data")} ${M.gray(`\u2014 unblocks ${s} shot${s===1?"":"s"} in ${n.length} action${n.length===1?"":"s"}`)}`);let i=8;for(let a of n.slice(0,i)){let l=cn(a.reason,86);r.push(` ${M.cyan(Xn(`${a.ids.length}\xD7`,4))} ${l[0]??""}`);for(let h of l.slice(1))r.push(` ${h}`);let c=a.ids.slice(0,4).join(" \xB7 ");r.push(M.gray(` ${c}${a.ids.length>4?` \xB7 +${a.ids.length-4} more`:""}`))}n.length>i&&r.push(M.gray(` \u2026 ${n.length-i} more staging action${n.length-i===1?"":"s"} \u2014 /screenshot list --detail`))}if(o.length>0){let s=o.reduce((i,a)=>i+a.ids.length,0);r.push(` ${V("\u2298",M.cyan)}${s} shot${s===1?"":"s"} need${s===1?"s":""} a data-testid from your developers \u2014 ${M.bold("/screenshot checklist")} builds the hand-off.`)}return r}function nd(e){if(e.length===0)return[];let t=e.slice(0,6),n=e.length;return["",` ${V("\u26A0",M.yellow)}${n} screenshot marker${n===1?"":"s"} will be ignored \u2014 ${n===1?"it is":"they are"} not shaped the way the publish step needs`+M.gray(`, so ${n===1?"that picture":"those pictures"} would never be taken`),...t.map(o=>M.gray(` ${o.file}:${o.line} \u2014 ${o.reason}`)),...n>t.length?[M.gray(` \u2026and ${n-t.length} more`)]:[],M.gray(" Usually a reviewer comment wrapped around it. A marker must start its own line and carry an id:.")]}function ky(e,t){let n=e.filter(i=>(i.staleAnchor?.length??0)>0);if(n.length===0)return[];let o=[...new Set(n.flatMap(i=>i.staleAnchor))],r=o.length,s=["",` ${V("\u26A0",M.yellow)}${r} selector request${r===1?"":"s"} quote${r===1?"s":""} source code that has since changed`+M.gray(" \u2014 your developers would go looking for something that isn't there any more"),M.gray(` Refresh the hand-off before sending it: ${M.bold("/screenshot checklist")}`)];return t&&s.push(M.gray(` ${o.slice(0,8).join(" \xB7 ")}${r>8?` \xB7 +${r-8} more`:""}`)),s}function $y(e,t,n){let o=e.filter(h=>(h.unguardedWaits?.length??0)>0),r=e.filter(h=>h.undeclared),s=e.filter(h=>(h.handRolled?.length??0)>0),i=e.filter(h=>(h.stalePause?.length??0)>0),a=e.filter(h=>(h.bareGoto?.length??0)>0);if(o.length===0&&r.length===0&&s.length===0&&i.length===0&&a.length===0)return[];let l=["",` ${V("\u26A0",M.yellow)}Some specs were written before later reliability fixes:`],c=(h,y)=>` ${h.slice(0,8).map(y).join(" \xB7 ")}${h.length>8?` \xB7 +${h.length-8} more`:""}`;if(o.length>0){let h=o.length;l.push(M.gray(` ${h} crash${h===1?"es":""} instead of telling you what to stage when the data ${h===1?"it needs":"they need"} is missing`)),t&&l.push(M.gray(c(o,y=>`${y.id}:${y.unguardedWaits.join(",")}`)))}if(a.length>0){let h=a.length;l.push(M.gray(` ${h} open${h===1?"s":""} pages the slow way, so ${h===1?"it stalls":"they stall"} for a minute and give up when several shots run at once`)),t&&l.push(M.gray(c(a,y=>`${y.id}:${y.bareGoto.join(",")}`)))}if(i.length>0){let h=i.length;l.push(M.gray(` ${h} decide${h===1?"s":""} "the data is missing" from a fixed pause, so data you HAVE staged can read as absent`)),t&&l.push(M.gray(c(i,y=>`${y.id}:${y.stalePause.join(",")}`)))}if(s.length>0){let h=s.length;l.push(M.gray(` ${h} take${h===1?"s":""} ${h===1?"its":"their"} own screenshot instead of the one call that positions the callouts too \u2014 on a cropped shot the numbers land in the wrong places, and nothing reports it`)),t&&l.push(M.gray(c(s,y=>`${y.id}:${y.handRolled.join(",")}`)))}if(r.length>0){let h=r.length,y=r.filter(x=>x.mutates).length;l.push(M.gray(` ${h} do${h===1?"es":""} not say whether ${h===1?"it changes":"they change"} data in your app`+(y>0?`, so ${y===1?"one is":`${y} are`} left out of bulk runs to be safe`:""))),t&&l.push(M.gray(c(r,x=>x.id)))}return n?.commandInLead||l.push(M.gray(` Re-write them all with the current rules: ${M.bold("/screenshot author --all")}`)),l}function vy(e){let t=e.filter(n=>(n.unverifiedForce?.length??0)>0);return t.length===0?[]:["",` ${V("\u26A0",M.red)}${t.length} spec${t.length===1?"":"s"} force-click past Playwright's safety checks without asserting the result`+M.gray(" \u2014 if the click lands on nothing, the shot photographs the unchanged screen"),M.gray(` ${t.slice(0,6).map(n=>`${n.id}:${n.unverifiedForce.join(",")}`).join(" \xB7 ")}${t.length>6?` \xB7 +${t.length-6} more`:""}`),M.gray(` Re-author to check what the click did: ${M.bold("/screenshot author <id>")}`)]}var Oa=(e,t)=>e.length>=t?e:e+" ".repeat(t-e.length),Xn=(e,t)=>e.length>=t?e:" ".repeat(t-e.length)+e;function xy(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 ES=new Set(["and","or","of","the","to","a","an","in","on","for","with","vs"]),NS=new Set(["ai","api","cli","ui","ux","url","id","http","https","json","xml","sdk","csv","pdf","oauth","sso","mfa","io","faq"]);function DS(e){return e.replace(/[-_]+/g," ").trim().split(/\s+/).filter(Boolean).map((n,o)=>{let r=n.toLowerCase();return NS.has(r)?r.toUpperCase():o>0&&ES.has(r)?r:r.charAt(0).toUpperCase()+r.slice(1)}).join(" ")}function zu(e){if(!e)return{num:"",name:"(docs root)"};let t=/^(\d+)[-_](.+)$/.exec(e);return{num:t?t[1]:"",name:DS(t?t[2]:e)}}function jS(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).pop()??e}function ay(e,t,n){let o=t>0?Math.round(e/t*n):0;return M.green("\u2588".repeat(o))+M.gray("\u2591".repeat(Math.max(0,n-o)))}function IS(e,t){let n=t>0?Math.round(e/t*100):0,o=Xn(`${n}%`,4);return n===100?M.green(o):n>0?M.yellow(o):M.gray(o)}function Ry(e,t){let n=new Map;for(let o of e){let r=xy(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 od(e,t){let n=T=>e.filter(R=>R.state===T).length,o=n("captured"),r=n("placeholder"),s=n("spec"),i=n("annotated"),a=n("blocked"),l=n("broken"),c=n("rejected"),h=e.filter(T=>T.state==="spec"&&T.mutates).length,y=s>h,x=e.filter(T=>(T.unguardedWaits?.length??0)>0||(T.bareGoto?.length??0)>0).length,w=e.filter(T=>(T.stalePause?.length??0)>0||(T.handRolled?.length??0)>0).length,S=s>0||a>0||l>0,P=(T,R="")=>Ce(T,R,t);return o>0?{key:"annotate",cmd:P("/screenshot annotate")}:r>0?{key:"toSpec",cmd:t?`/screenshot author ${t}`:"/screenshot author --all"}:x>0&&S?{key:"crashy",cmd:t?`/screenshot author ${t}`:"/screenshot author --all"}:w>0&&S?{key:"wrongOutput",cmd:t?`/screenshot author ${t}`:"/screenshot author --all"}:s>0&&(y||i===0)?{key:"ready",cmd:P("/screenshot capture")}:i>0&&s>0?{key:"verify",cmd:P("/screenshot verify")}:a>0?{key:"blocked",cmd:P("/screenshot capture","--blocked")}:l>0?{key:"broken",cmd:`/screenshot ${e.find(T=>T.state==="broken").id}`}:i>0?{key:"verify",cmd:P("/screenshot verify")}:c>0?{key:"rejected",cmd:P("/screenshot capture","--failed")}:{key:"done",cmd:t?`/push ${t}`:"/push"}}function LS(e,t,n=[]){let o=(ee,Ee)=>ee.filter(_e=>_e.state===Ee).length,r=e.length,s=o(e,"verified"),i=o(e,"annotated"),a=o(e,"captured"),l=o(e,"rejected"),c=o(e,"spec"),h=o(e,"blocked"),y=o(e,"broken"),x=o(e,"placeholder"),w=new Set(e.map(ee=>ee.file)).size,S=Ry(e,t),P=[];P.push(` ${M.bold("Screenshots")} ${M.green(`${s}/${r} verified`)} ${M.gray("\xB7")} ${i>0?M.blue(`${i} to verify`):M.gray("0 to verify")}`+(a>0?` ${M.gray("\xB7")} ${M.yellow(`${a} to annotate`)}`:"")+(l>0?` ${M.gray("\xB7")} ${M.magenta(`${l} rejected`)}`:"")+` ${M.gray("\xB7")} ${c>0?M.yellow(`${c} ready`):M.gray("0 ready")}`+(h>0?` ${M.gray("\xB7")} ${M.cyan(`${h} blocked`)}`:"")+(y>0?` ${M.gray("\xB7")} ${M.red(`${y} broken`)}`:"")+` ${M.gray("\xB7")} ${x>0?M.red(`${x} to spec`):M.gray("0 to spec")} `+M.gray(`across ${w} article${w===1?"":"s"}`));let T=r>0?Math.round(s/r*100):0;P.push(` [${ay(s,r,32)}] ${M.bold(`${T}%`)}`),P.push("");let R=S.map(([ee])=>zu(ee)),D=Math.min(32,Math.max(7,...R.map(ee=>ee.name.length))),B=ee=>ee.length>D?`${ee.slice(0,D-1)}\u2026`:Oa(ee,D),G=[...a>0?[{head:"To annotate",w:11,state:"captured",color:M.yellow}]:[],...i>0?[{head:"To verify",w:9,state:"annotated",color:M.blue}]:[],...l>0?[{head:"Rejected",w:8,state:"rejected",color:M.magenta}]:[],{head:"Ready",w:5,state:"spec",color:M.yellow},...h>0?[{head:"Blocked",w:7,state:"blocked",color:M.cyan}]:[],...y>0?[{head:"Broken",w:6,state:"broken",color:M.red}]:[],{head:"To spec",w:7,state:"placeholder",color:M.red}];P.push(M.gray(` ${Oa("#",2)} ${Oa("Chapter",D)} ${Xn("Verified",8)} ${G.map(ee=>Xn(ee.head,ee.w)).join(" ")} Progress`));for(let[ee,[,Ee]]of S.entries()){let _e=o(Ee,"verified"),Xe=Ee.length,{num:ho,name:Pe}=R[ee],Ne=_e===Xe,tt=B(Pe),an=G.map(At=>{let fo=o(Ee,At.state);return fo>0?At.color(Xn(String(fo),At.w)):M.gray(Xn("\u2014",At.w))}).join(" ");P.push(` ${M.cyan(Oa(ho,2))} ${Ne?M.green(tt):_e>0?tt:M.gray(tt)} ${Ne?M.green(Xn(`${_e}/${Xe}`,8)):Xn(`${_e}/${Xe}`,8)} ${an} ${ay(_e,Xe,10)} ${IS(_e,Xe)}`)}P.push("");let Q=y>0?` ${M.gray("\xB7")} ${y} spec${y===1?"":"s"} broken \u2014 ${M.bold(`/screenshot ${e.find(ee=>ee.state==="broken").id}`)} re-authors ${y===1?"it":"the first"}`:"",N=e.filter(ee=>ee.state==="spec"&&ee.mutates).length,ne=c>N,te=e.filter(ee=>(ee.unguardedWaits?.length??0)>0||(ee.bareGoto?.length??0)>0).length,he=e.filter(ee=>(ee.stalePause?.length??0)>0||(ee.handRolled?.length??0)>0).length,we=c>0||h>0||y>0,ye=!1,ke=od(e).key;if(ke==="annotate")P.push(` ${V("\u25C8",M.blue)}${a} shot${a===1?"":"s"} taken but not drawn on \u2014 run ${M.bold("/screenshot annotate")}`+M.gray(` \u2014 no browser, seconds; the callouts are what make ${a===1?"it":"them"} publishable`)+Q);else if(ke==="toSpec")P.push(` ${V("\u2192",M.yellow)}${x} placeholder${x===1?"":"s"} still need a spec \u2014 run ${M.bold("/screenshot author --all")}${Q}`);else if(ke==="crashy")ye=!0,P.push(` ${V("\u2192",M.yellow)}${te} spec${te===1?"":"s"} would crash mid-run \u2014 re-write ${te===1?"it":"them"} first: ${M.bold("/screenshot author --all")}`+M.gray(` \xB7 then ${M.bold("/screenshot capture")} (no browser time wasted on ${te===1?"a shot":"shots"} that can't finish)`)+Q);else if(ke==="wrongOutput")ye=!0,P.push(` ${V("\u2192",M.yellow)}${he} spec${he===1?"":"s"} would shoot the wrong thing \u2014 re-write ${he===1?"it":"them"} first: ${M.bold("/screenshot author --all")}`+M.gray(` \xB7 then ${M.bold("/screenshot capture")} (a false skip or a misplaced callout costs the same browser time as a good shot)`)+Q);else if(ke==="ready"){let ee=N>0?M.gray(` \u2014 ${c-N} in one go; ${N} write${N===1?"s":""} real data and run${N===1?"s":""} one at a time`):"";P.push(` ${V("\u2192",M.yellow)}${c} spec${c===1?"":"s"} ready to capture \u2014 run ${M.bold("/screenshot capture")}${ee}${Q}`)}else if(ke==="verify"&&c>0)P.push(` ${V("\u2192",M.blue)}${i} shot${i===1?"":"s"} awaiting verification \u2014 run ${M.bold("/screenshot verify")}`+M.gray(" \u2014 no browser needed")+M.gray(` \xB7 ${c} ready spec${c===1?"":"s"} write real data, so ${c===1?"it runs":"each runs"} only when named: /screenshot capture <id>`)+Q);else if(ke==="blocked")P.push(` ${V("\u2192",M.cyan)}${h} shot${h===1?"":"s"} blocked \u2014 stage the data below, then ${M.bold("/screenshot capture --blocked")}${Q}`);else if(ke==="broken")P.push(` ${V("\u2192",M.red)}${y} spec${y===1?"":"s"} broken \u2014 ${M.bold(`/screenshot ${e.find(ee=>ee.state==="broken").id}`)} re-authors ${y===1?"it":"the first"} (re-capturing fails the same way)`);else if(ke==="verify")P.push(` ${V("\u2192",M.blue)}${i} shot${i===1?"":"s"} awaiting verification \u2014 run ${M.bold("/screenshot verify")}`+M.gray(" \u2014 it checks each picture against what its article needs (no browser, no re-capture)"));else if(ke==="rejected"){let ee=e.filter(Ee=>Ee.state==="rejected"&&Ee.repaired).length;P.push(` ${V("\u2691",M.magenta)}${l} shot${l===1?"":"s"} failed review \u2014 `+(ee>0?`${ee} spec${ee===1?"":"s"} already repaired; re-capture with ${M.bold("/screenshot capture --failed")}`:`see the reasons below, then ${M.bold("/screenshot capture --failed")}`))}else P.push(` ${V("\u2713",M.green)}all ${r} verified \u2014 ${M.bold("/push")} embeds them in the articles`);if(s>0&&s<r){let ee=S.filter(([,Ee])=>Ee.every(_e=>_e.state!=="verified")).map(([Ee])=>{let{num:_e,name:Xe}=zu(Ee);return _e?`${_e} ${Xe}`:Xe});ee.length>0&&P.push(M.gray(` Furthest behind: ${ee.slice(0,5).join(" \xB7 ")}${ee.length>5?" \u2026":""} (0% verified)`))}return P.push(...by(e),...vy(e),...$y(e,!1,{commandInLead:ye}),...ky(e,!1),...nd(n)),P.push(""),P.push(M.gray(" Drill in: /screenshot list <chapter#> \xB7 /screenshot list --detail (all)")),P}function OS(e,t,n,o=[]){let r=new Set(e.map(c=>c.file)),s=e.filter(c=>c.state==="verified").length,i=e.filter(c=>c.state==="annotated").length,a=e.filter(c=>c.state==="captured").length,l=[` ${M.bold("Screenshots")}: ${e.length} placeholder${e.length===1?"":"s"} across ${r.size} article${r.size===1?"":"s"} \xB7 ${M.green(`${s} verified`)}${i>0?M.blue(` \xB7 ${i} to verify`):""}${a>0?M.yellow(` \xB7 ${a} to annotate`):""}${n?M.gray(` \xB7 scope ${n}`):""}`,""];for(let[c,h]of Ry(e,t)){let y=h.filter(T=>T.state==="verified").length,{num:x,name:w}=zu(c),S=x?`${x} \xB7 ${w}`:w;l.push(` ${M.bold(S)} ${M.gray(`(${y}/${h.length})`)}`);let P=new Map;for(let T of h){let R=jS(T.file),D=P.get(R)??[];P.has(R)||P.set(R,D),D.push(T)}for(let T of[...P.keys()].sort()){l.push(M.gray(` ${T}`));for(let R of P.get(T)){let D=TS[R.state];if(l.push(` ${V(PS[R.state],D)}${D(R.id)}`),(R.state==="blocked"||R.state==="broken"||R.state==="rejected")&&R.reason){for(let B of cn(Ir(R.reason),84))l.push(M.gray(` ${B}`));R.state==="rejected"&&l.push(M.gray(` ${R.repaired?"spec repaired \u2014 re-capture to confirm":"spec not yet repaired"}`))}}}}return l.push(...by(e),...vy(e),...$y(e,!0),...ky(e,!0),...nd(o)),l.push("",AS),l}function qa(e,t){let n=t?.scope,o=t?.markerProblems??[];if(e.length===0)return[n?`No screenshot placeholders under ${n}.`:"No screenshot placeholders found in the docs.",...nd(o)];let r=t?.docsDir??ed;return t?.detail||n?OS(e,r,n,o):LS(e,r,o)}function rd(e,t){if(!t||!/^\d+$/.test(t))return t;let n=Qn(e)?.docsDir??ed,o=String(Number(t));for(let{file:r}of cy(e)){let s=xy(r,n),i=/^(\d+)/.exec(s);if(i&&String(Number(i[1]))===o)return s}return t}function Sy(e,t){let r=e.map(a=>" ".repeat(a.depth)+a.label),s=Math.max(0,...e.map((a,l)=>a.note?La(r[l]):0)),i=Math.min(s,Math.max(0,t-2-24));return e.map((a,l)=>{let c=r[l];if(!a.note)return{head:c,note:""};let h=Math.max(2,i+2-La(c)),y=a.note.trim(),x=t-La(c)-h;return{head:c+" ".repeat(h),note:x>1&&La(y)>x?`${y.slice(0,x-1)}\u2026`:y}})}function MS(e){let t=e.replace(/\\/g,"/").split("/").filter(Boolean),n=t.pop()??e;return{category:t.pop()??"(docs root)",article:n}}function jr(e,t,n){let o=new Map;for(let s of t){let{category:i,article:a}=MS(s.file),l=o.get(i)??new Map;o.set(i,l);let c=l.get(a)??[];l.set(a,c),c.push(s)}let r=s=>n!=="capture"||!s.mutates;for(let s of[...o.keys()].sort()){let i=o.get(s),a=[...i.values()].flat().filter(r).map(c=>c.id),l=a.length>0;l&&e.push({kind:"category",action:n,label:`${s} (${a.length})`,ids:a,depth:1});for(let c of[...i.keys()].sort()){let h=i.get(c),y=h.filter(r).map(S=>S.id),x=y.length>0;x&&e.push({kind:"article",action:n,label:`${c} (${y.length})`,ids:y,depth:l?2:1});let w=(l?1:0)+(x?1:0)+1;for(let S of h){let P=n==="capture"&&S.mutates?" \u26A0 creates real data \u2014 runs only alone":void 0;e.push({kind:"shot",action:n,label:S.id,ids:[S.id],depth:w,...P?{note:P}:{}})}}}}function Hu(e){return e?Ir(e):""}function sd(e,t,n,o=[]){let r=t.filter(i=>!i.mutates);r.length>1&&e.push({kind:"all",action:"capture",label:`Retry ${r.length} blocked shots (Prerequisites not met \u2014 Stage the data first)`,ids:r.map(i=>i.id),depth:0});for(let i of[...t].sort((a,l)=>a.id.localeCompare(l.id)))e.push({kind:"shot",action:"capture",label:i.id,ids:[i.id],depth:1,note:` \u2298 ${Hu(i.reason)}`});n.length>1&&e.push({kind:"all",action:"author",label:`Re-author ${n.length} broken specs`,ids:n.map(i=>i.id),depth:0});for(let i of[...n].sort((a,l)=>a.id.localeCompare(l.id)))e.push({kind:"shot",action:"author",label:i.id,ids:[i.id],depth:1,note:` \u2717 re-authors \u2014 ${Hu(i.reason)}`});let s=o.filter(i=>!i.mutates);s.length>1&&e.push({kind:"all",action:"capture",label:`Re-capture ${s.length} shots that failed review`,ids:s.map(i=>i.id),depth:0});for(let i of[...o].sort((a,l)=>a.id.localeCompare(l.id))){let a=i.repaired?"re-captures":"re-captures (spec not yet repaired)";e.push({kind:"shot",action:"capture",label:i.id,ids:[i.id],depth:1,note:` \u2691 ${a} \u2014 ${Hu(i.reason)}`})}}function Cy(e){let t=e.filter(i=>i.state==="placeholder"),n=e.filter(i=>i.state==="spec"),o=[];t.length>1&&o.push({kind:"all",action:"author",label:`Author all ${t.length} remaining specs`,ids:t.map(i=>i.id),depth:0}),jr(o,t,"author");let r=n.filter(i=>!i.mutates);r.length>1&&o.push({kind:"all",action:"capture",label:`Capture all ${r.length} ready specs`,ids:r.map(i=>i.id),depth:0}),jr(o,n,"capture");let s=e.filter(i=>i.state==="captured");return s.length>1&&o.push({kind:"all",action:"annotate",label:`Draw the callouts on all ${s.length} shots`,ids:s.map(i=>i.id),depth:0}),jr(o,s,"annotate"),sd(o,e.filter(i=>i.state==="blocked"),e.filter(i=>i.state==="broken"),e.filter(i=>i.state==="rejected")),o}var Xu=["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 guard on the SAME predicate the action needs: `.click()` requires visible AND ENABLED, so a",' DISABLED button passes both waitFor({state:"visible"}) and count()>0 and then times out at 15s'," (measured). Add `|| !(await x.isEnabled().catch(() => false))` to the condition, and put the"," control's own title/aria-disabled text in the skip reason \u2014 a disabled control is the product"," telling you the prerequisite is unmet, usually with the reason attached.",' 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."," Two corollaries, both of which have cost a wasted repair round:"," (a) An element that is not RENDERED is not absent. A collapsed tree node, an unopened accordion,"," an inactive tab, a virtualised list or page 2 of a table keeps its children out of the DOM."," EXPAND/scroll/switch to reach the target \u2014 that is a step to script, not data to stage."," (b) When you narrow past a decoy, count the UNNARROWED set too and put the number in the reason:",' "Found 6 folder roll-ups but no endpoint-level score \u2014 if one exists it may not be rendered".',' A bare "prerequisite not met" cannot tell absent data from an over-narrow selector. Put that'," evidence in a LATER sentence, never the first: grouping keys on the first sentence, so an",' interpolated count there makes every run its own "action" and the dedup stops working.'," (c) `click({ force: true })` is the ONE pattern that turns a failure into a silent WRONG"," SCREENSHOT rather than a crash or skip: it skips the actionability checks, so a click that"," lands on nothing photographs the unchanged screen and that image ships in the docs. It is"," sometimes right (a button nested inside a button reads as intercepted by its own ancestor)."," Never force blind: ground it in source, scrollIntoViewIfNeeded() first, and ASSERT THE"," CONSEQUENCE immediately after with a guarded wait + test.skip, so a no-op force skips."," Know its limit: force skips the CHECK but still hit-tests real screen coordinates, so the"," element that RECEIVES the event may not be the one your locator names (measured: a forced"," click on a pill nested in its section-header button never ran the pill's own handler).",' For a genuinely nested interactive node use `locator.dispatchEvent("click")`, which goes'," straight to that node with no hit-test \u2014 and still assert the consequence."," (d) Never bind a locator to an attribute your own interaction CHANGES. A locator is re-evaluated",' on every use, so `button[title="Multi-select scenarios"]` matches nothing once the click',' flips it to `title="Exit select mode"` \u2014 a 15s "not found" timeout on an element that is'," right there (measured). Toggling labels are normal (Play/Pause, Expand/Collapse, Select"," all/Deselect all): if the attribute is a ternary on state it is not an identity. Match both"," values in one locator, or use a testid."," (e) Cleanup after the screenshot is BEST-EFFORT and must never throw or test.skip. Anything"," after captureShot() runs with the image already on disk, so a throw there turns a successful"," capture into a reported failure and the shot is thrown away (measured: a valid .raw.png plus"," annotations, reported broken). Guard with isVisible()/isEnabled() and click best-effort \u2014 by"," then there is nothing left to skip."," (f) An element that is RENDERED can still be EMPTY. A component may mount an input/textarea/pane",' with no content and fill it when its fetch resolves, so waitFor({state:"visible"}) proves the'," node exists, not that the data arrived \u2014 reading inputValue()/textContent() right after can"," catch the pre-fetch empty state and false-skip data that IS there. When the decision rests on"," a VALUE rather than on presence, wait for the value: page.waitForFunction(sel => { const el =",' document.querySelector(sel); return !!el && (el.value ?? el.textContent ?? "").trim() !== ""; },',' "<selector>", { timeout: 10_000 }).catch(() => {}) \u2014 THEN read it and skip on empty.'," (g) NEVER take the screenshot yourself. `captureShot(page, PLACEHOLDER)` is the only capture call:"," it shoots AND resolves the callout positions in one pass, so they cannot disagree. A"," page.screenshot()/locator.screenshot() + dumpAnnotations() pair measures coordinates against"," the whole page while a cropped image starts at the crop corner, so every pin and highlight is"," offset \u2014 and nothing errors, so the spec reports success and the picture is wrong."," (h) EVERY navigation goes through `gotoResilient` (from document360-capture/helpers), never a bare",' page.goto(): `await gotoResilient(page)` for the start URL, `gotoResilient(page, "/route")`',` mid-spec. Under a bulk run, sibling specs saturate the network and goto's default "load" wait`," never fires \u2014 four specs died on that identical first line, each patched by hand.","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."," That consistency applies WITHIN one spec too, and a spec with 2+ test.skip calls needs two checks:"," (a) does a LATER branch's reason still HOLD, given what passing the earlier guard already proved?",` A later branch that reuses an earlier one's reason verbatim ("sign in as an owner\u2026") when`," reaching it proves that condition passed does not just read oddly \u2014 it misdiagnoses the cause"," and sends the reader to fix something that is already fine."," (b) do multiple branches for the SAME prerequisite (found 0 vs found fewer than N) open with one"," identical sentence? Divergent openings defeat the grouping even within a single spec.","Before you finish, re-read each spec you wrote and check every rule above line by line."].join(`
|
|
330
|
+
`);function _S(e){return e.outcome==="failed"?["REPAIR \u2014 the existing spec FAILED its last capture with:",e.reason,'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."]:["REPAIR \u2014 the existing spec SKIPPED its last capture with:",e.reason,"You are being asked to re-author a shot that SKIPPED, and that is itself the signal: the normal","response to a blocked shot is to STAGE the data, not to rewrite the spec. So treat that reason as","SUSPECT \u2014 assume it is a FALSE skip until you have proved otherwise. Two things make a guard report",'"not staged" when the data exists:',"1. THE TARGET IS NOT RENDERED. Trace the path from the entry point to the element you finally need"," and confirm every intermediate container is OPENED. A collapsed tree node, an unopened accordion,"," an inactive tab, a virtualised list or page 2 of a table keeps its children out of the DOM, so the"," count is zero and the skip fires \u2014 for data sitting one click away. Expanding is a step to SCRIPT.","2. THE SELECTOR IS TOO NARROW. If you filtered past a decoy, count the UNNARROWED set and put the",' number in the reason ("Found 6 folder roll-ups but no endpoint-level score"), so the next reader'," can tell absent data from an over-narrow selector without opening the app.","A spec that satisfies every rule in this skill and still cannot reach its target is NOT correct.",'"No changes needed" is earned by tracing reachability end to end \u2014 not by checking conformance.']}var Qu="MANDATORY, check before you finish: every spec you write or touch must carry exactly one `// CAPTURE-SAFETY: readonly` or `// CAPTURE-SAFETY: mutates: <what it creates>; cleanup: <how>` line at the top. Re-read each file you wrote and add it if missing; a spec without it is classified by guesswork. A fail-by-design spec (the app rejects the input) is `readonly`.";function Py(e,t,n){let o=e.paths,r=o.filter(l=>t?.get(l)?.outcome==="failed"),s=o.filter(l=>t?.get(l)?.outcome==="skipped"),i=l=>`- ${l}: ${t.get(l).reason.replace(/\s+/g," ").trim()}`,a=o.filter(l=>(n?.get(l)?.length??0)>0);return["Run the emit-screenshot-spec skill to author the document360-capture spec for EACH of these","SCREENSHOT placeholder ids:",e.paths.map(l=>`- ${l}`).join(`
|
|
331
|
+
`),"",...r.length>0?["REPAIR: 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).",...r.map(i),""]:[],...s.length>0?["REPAIR: these already have a spec and it SKIPPED. Treat each reason as SUSPECT, not as proof","the spec is right: a FALSE skip is indistinguishable from a true one from inside the spec, and","you are being asked to re-author rather than to stage. Check TWO things before concluding a","spec needs no change. (1) Is the target RENDERED? A collapsed tree node, unopened accordion,","inactive tab, virtualised list or page 2 of a table keeps children out of the DOM, so the count","is zero for data one click away, so expanding is a step to SCRIPT. (2) Is the selector too narrow?","If you filtered past a decoy, count the unnarrowed set and put the number in the reason. A spec","that satisfies every rule and still cannot reach its target is NOT correct.",...s.map(i),""]:[],...a.flatMap(l=>gy(n.get(l),`RULE VIOLATIONS already in ${l}'s existing spec \u2014 fix every one:`)),"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.",Xu,Qu].join(`
|
|
332
|
+
`)}async function Va(e,t,n){let o=_s(e),r=Mo(t?.cwd??process.cwd());if(r&&console.log(M.gray(r)),o.mode==="list"){let l=t?.cwd??process.cwd(),c=rd(l,o.scope),h=Qn(l)?.docsDir??ed,y=He(l,c),x=uS(l,c?{scope:c}:{});for(let w of qa(y,{scope:c,detail:o.detail,docsDir:h,markerProblems:x}))console.log(w);return{kind:"continue"}}if(o.mode==="single"){let l=_o(t?.cwd??process.cwd(),o.id),c=l===null?[]:td(l);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: spec path, data to`,"stage, dev requests only if any, and the capture command; no grounding narration.",Xu,Qu,...n?.prior?["",..._S(n.prior)]:[],...c.length>0?["",...gy(c,"RULE VIOLATIONS already in the existing spec \u2014 fix every one:")]:[]].join(`
|
|
333
|
+
`),display:`/screenshot ${o.id}`}}if(o.mode==="capture"||o.mode==="annotate"||o.mode==="verify"||o.mode==="checklist")return{kind:"continue"};let i=[`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-CHECKLIST.md.":""} Report specs written, TODO data-testids, and data to stage.`,Xu,Qu].join(`
|
|
334
|
+
`),a=o.mode==="scope"?`/screenshot ${o.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:i,display:a}}import{readDocsPlan as WS,readProjectConfig as BS,listOpenHints as HS,partitionOpenHints as GS,listOpenForDocs as qS,listOpenDirectives as VS,loadOpenCommentCount as YS,resolveActiveProfile as KS,briefMoved as zS,DEFAULT_DOCS_DIR as XS}from"document360-engine";import{statSync as US}from"node:fs";import{resolve as FS}from"node:path";function Jn(e,t,n){return n.filter(o=>{try{return US(FS(e,t,o)).size===0}catch{return!0}})}var Uo=e=>e===1?"":"s";function QS(e){try{let t=(BS(e)?.docsDir??XS).replace(/\/+$/,""),n=WS(e,t);return n.length===0?0:Jn(e,t,n.map(o=>o.path)).length}catch{return 0}}function JS(e){try{return YS(e,KS(e).name)}catch{return 0}}function ZS(e){let t=i=>{try{return i().length}catch{return 0}},n=t(()=>GS(e,HS(e)).actionable),o=t(()=>qS(e)),r=t(()=>VS(e)),s=!1;try{s=zS(e)}catch{}return{hints:n,messages:o,directives:r,brief:s,total:n+o+r+(s?1:0)}}function Ty(e,t){let n=t?.just,o=ZS(e);if(o.total>0&&n!=="/catch-up"){let i=[];return o.hints>0&&i.push(`${o.hints} hint${Uo(o.hints)}`),o.messages>0&&i.push(`${o.messages} message${Uo(o.messages)}`),o.directives>0&&i.push(`${o.directives} request${Uo(o.directives)}`),o.brief&&i.push("an updated product brief"),{cmd:"/catch-up",short:`Your builder left ${i.join(" and ")} waiting`,text:`Your builder left ${i.join(" and ")} waiting. /catch-up clears that first \u2014 it rewrites articles, so reviewing or sending anything up before it runs is work you would do twice.`}}let r=JS(e);if(r>0&&n!=="/comments")return{cmd:"/comments",short:`${r} reviewer comment${Uo(r)} ${r===1?"is":"are"} waiting on your articles`,text:`${r} reviewer comment${Uo(r)} ${r===1?"is":"are"} waiting on your articles. /comments answers ${r===1?"it":"them"} first \u2014 answering rewrites the passages they marked up, so reviewing or sending anything up before it runs is work you would do twice.`};let s=QS(e);return s>0&&n!=="/write"?{cmd:"/write",short:`${s} planned article${Uo(s)} ${s===1?"is":"are"} still unwritten`,text:`${s} planned article${Uo(s)} ${s===1?"is":"are"} still unwritten. /write finish${s===1?"es it":"es them"} first, so one review pass and one save cover everything together instead of running twice.`}:null}import{modernizeLegacyCommandLine as eC}from"document360-engine";var tC=new Set(["--scope","--concurrency","--model"]),nC=new Set(["/screenshot","/style-guide","/reuse"]),oC=e=>e.trim().replace(/\s+/g," ").toLowerCase();function un(e){let t=oC(eC(e));if(!t.startsWith("/"))return null;let n=t.split(" ").filter(Boolean),o=n[0],r=1,s;nC.has(o)&&n[1]&&!n[1].startsWith("-")&&(s=n[1],r=2);let i=new Set,a;for(;r<n.length;r++){let l=n[r];if(l.startsWith("--")){let c=l.indexOf("=");if(c!==-1){let h=l.slice(0,c);i.add(h),h==="--scope"&&(a=l.slice(c+1)||void 0);continue}if(i.add(l),tC.has(l)){let h=n[r+1];h!==void 0&&!h.startsWith("-")&&(l==="--scope"&&(a=h),r++)}continue}if(l.startsWith("-")){i.add(l);continue}a??=l}return{cmd:o,...s?{sub:s}:{},flags:i,...a?{scope:a.replace(/\/+$/,"")}:{}}}function Lr(e){switch(e.cmd){case"/review":case"/lint":return e.flags.has("--fix");case"/write":return!e.flags.has("--preview")&&!e.flags.has("--dry-run");case"/comments":return e.flags.has("--answer");case"/screenshot":return e.sub==="author"||e.sub==="capture"||e.sub==="annotate"||e.sub==="verify";case"/style-guide":return e.sub==="use"||e.sub==="keep"||e.sub==="compile"||e.sub==="learn";case"/reuse":return e.sub==="pull"||e.sub==="add"||e.sub==="audit";case"/restructure":return e.scope!==void 0;case"/push":case"/publish":case"/convert":case"/catch-up":case"/discover":case"/document":case"/pull":case"/reorder":return!0;default:return!1}}var rC=new Set(["--all"]),sC=new Set(["--concurrency","--model","--verbose","--quiet"]),iC=new Set(["--scope"]);function Ay(e){return[...e.flags].filter(t=>!rC.has(t)&&!sC.has(t)&&!iC.has(t)).sort().join(" ")}function Ey(e,t){if(!t)return!1;let n=un(e),o=un(t);return!n||!o||n.cmd!==o.cmd||n.sub!==o.sub||!Lr(n)||Ay(n)!==Ay(o)?!1:n.scope===void 0||n.scope===o.scope}function tn(e){return e.aborted||e.blocked||e.allEmpty||e.bailedEmpty||e.producedNothing||(e.leftBehind??0)>0||e.failed>0||e.notRun>0?!1:e.verifiedComplete?!0:e.partitions>=1}import{listRoadmap as Ws,roadmapProgress as Oy,stampRoadmapDone as pC}from"document360-engine";ae();ae();import{ROADMAP_STAGES as Ny}from"document360-engine";var Dy=[...Ny,"other"],aC=[[/^\/screenshot\b/,"capture"],[/^\/style-guide\b/,"decide"],[/^\/genre\b/,"decide"],[/^\/scope\b/,"decide"],[/^\/discover\b/,"plan"],[/^\/plan\b/,"plan"],[/^\/audit\b/,"plan"],[/^\/write\b/,"write"],[/^\/catch-up\b/,"write"],[/^\/document\b/,"write"],[/^\/review\b/,"edit"],[/^\/comments\b/,"edit"],[/^\/lint\b/,"lint"],[/^\/push\b/,"save"],[/^\/pull\b/,"save"],[/^\/publish\b/,"golive"]];function id(e){let t=(e.stage??"").trim().toLowerCase();if(Ny.includes(t))return t;let n=(e.run??"").trim().toLowerCase();if(n.startsWith("/")){for(let[o,r]of aC)if(o.test(n))return r}return"other"}function Ya(e){return id(e)==="capture"}var lC={decide:"Decide",plan:"Plan",capture:"Screenshots",write:"Write",edit:"Edit",lint:"Style rules",save:"Save to Document360",golive:"Go live",other:"Other steps"};function jy(e){return e.status==="done"&&!!e.replacedBy}var ld=e=>(e.run??"").trim().replace(/\s+/g," ").toLowerCase();function cC(e){let t=[];for(let o of e){let r=ld(o);r&&!t.includes(r)&&t.push(r)}let n=o=>{let r=ld(o);return r?t.indexOf(r):t.length};return e.map((o,r)=>({s:o,i:r})).sort((o,r)=>n(o.s)-n(r.s)||o.i-r.i).map(o=>o.s)}function uC(e){let t=new Map;for(let o of e){let r=id(o),s=t.get(r);s?s.push(o):t.set(r,[o])}let n=[];for(let o of Dy){let r=t.get(o);!r||r.length===0||n.push({key:o,label:lC[o],steps:cC(r),done:r.filter(s=>s.status==="done").length})}return n}var ad=" ",Iy=e=>e.trim().toLowerCase();function dC(e,t){let n=Math.max(20,t.width-ad.length),o=e.status==="done"?X("\u2713"):Ae("\u25CB"),r=e.status==="done"?u:t.isNext?Z:h=>h,s=cn(e.title.trim(),n);s.length===0&&s.push("");let i=[];t.showRun&&e.run?.trim()&&i.push(e.run.trim()),t.showReplaced&&e.replacedBy&&i.push(`replaced by \u201C${e.replacedBy}\u201D`);let a=i.map(h=>` \xB7 ${h}`).join(""),l=s.map((h,y)=>y===0?` ${o} ${r(h)}`:`${ad}${r(h)}`);if(!a)return l;if((s[s.length-1]??"").length+a.length<=n)return l[l.length-1]+=Ae(a),l;for(let h of i)l.push(`${ad}${Ae(`\xB7 ${h}`)}`);return l}function Ly(e,t={}){let n=Math.max(40,t.width??80),o=t.all?e:e.filter(a=>!jy(a)),r=e.length-o.length,s=e.filter(a=>a.status==="done").length,i=[Z(`Docs roadmap \u2014 ${s} of ${e.length} step${e.length===1?"":"s"} done`)];for(let a of uC(o)){i.push(""),i.push(` ${Je(a.label)}${Ae(` \xB7 ${a.done} of ${a.steps.length}`)}`);let l="";for(let c of a.steps){let h=ld(c);i.push(...dC(c,{width:n,showRun:!!h&&h!==l,isNext:!!t.next&&Iy(c.title)===Iy(t.next.title),showReplaced:!!t.all&&jy(c)})),l=h}}return i.push(""),i.push(t.next?`Next: ${t.next.title}${t.next.run?` \u2014 ${t.next.run}`:""}`:"Campaign complete \u2014 the docs agent adds new steps as the app changes."),r>0&&i.push(u(`(+${r} step${r===1?"":"s"} closed because a later pass replaced ${r===1?"it":"them"} \u2014 /roadmap --all lists ${r===1?"it":"them"}.)`)),i}function cd(e,t={}){let n=Ws(e);if(n.length===0)return["No docs roadmap yet \u2014 the docs agent seeds .d360-writer/roadmap.md when it pins a structure,","and adds steps as the app changes. You can also write steps by hand (## [open] <step>), or ask:",'"propose the docs roadmap for this repo".'];let o=Oy(e),r=Ly(n,{width:t.width,all:t.all,next:o.next});return r.push(u("(Edit .d360-writer/roadmap.md freely \xB7 /roadmap done marks the next step you finished yourself \u2014 add words from a title to pick another.)")),n.some(s=>s.stepId)&&r.push(u('(d360-writer keeps the wording of its own steps current \u2014 add a "keep:" line to one to leave your version alone.)')),r}function Or(e,t){let n=Ws(e).filter(c=>c.status==="open"),o=t.trim();if(n.length===0)return{ok:!1,line:"The roadmap has no open steps \u2014 nothing to mark done."};let r=c=>c.trim().toLowerCase(),s=n.find(c=>r(c.title)===r(o)),i=o?s?[s]:n.filter(c=>r(c.title).includes(r(o))):[n[0]];if(i.length>1)return{ok:!1,line:`"${o}" matches ${i.length} open steps \u2014 add a distinguishing word:
|
|
335
335
|
${i.map(c=>` \u25CB ${c.title}`).join(`
|
|
336
336
|
`)}`};if(i.length===0)return{ok:!1,line:`No open step matches "${o}". Open steps:
|
|
337
337
|
${n.map(c=>` \u25CB ${c.title}`).join(`
|
|
338
|
-
`)}`};let a=i[0].title;
|
|
339
|
-
`)}function
|
|
338
|
+
`)}`};let a=i[0].title;pC(e,a,{doneAt:new Date().toISOString()});let l=Oy(e)?.next;return{ok:!0,line:`\u2713 Marked done: ${a}${l?` \u2014 next up: ${l.title}${l.run?` (${l.run})`:""}`:" \u2014 that was the last step: campaign complete."}`}}function My(e,t){let n=r=>r.trim().replace(/\s+/g," ").toLowerCase(),o=n(t);return o.startsWith("/")?Ws(e).find(r=>r.status==="open"&&!!r.run&&n(r.run)===o)??null:null}function Ka(e,t){let n=(Array.isArray(t)?t:[t]).filter(s=>s.trim().startsWith("/"));if(n.length===0)return[];let o=new Set,r=[];for(let s of Ws(e))s.status==="open"&&n.some(i=>Ey(i,s.run))&&(o.has(s.title)||(o.add(s.title),r.push(s.title)));return r}function Ke(e,t){if(!t)return[];try{let n=Ka(e,t).filter(o=>Or(e,o).ok);return n.length===0?[]:n.length===1?[`\u2713 That completed a docs-campaign step \u2014 marked done: ${n[0]}`]:[`\u2713 That completed ${n.length} docs-campaign steps \u2014 marked done:`,...n.map(o=>` \u2022 ${o}`)]}catch{return[]}}function za(e,t){let n=Ka(e,t);if(n.length===0)return null;let o=n.map(r=>`"${r}"`).join(", ");return[n.length===1?`Note: this command executes the open docs-roadmap step ${o}.`:`Note: this command executes ${n.length} open docs-roadmap steps: ${o}.`,`Close the loop IN THE SAME TURN the goal state is reached: call d360_roadmap_done with exactly the title of EACH step it completed (${o}), then tell the user they are marked done \u2014 including when you find the goal already holds ("no action needed" completes the STEP, not just the turn). Leave one open ONLY if its work is genuinely incomplete, and say exactly what remains.`].join(`
|
|
339
|
+
`)}function _y(e,t){let n=t.trim().toLowerCase();if(!n)return null;let o=Ws(e).find(r=>r.status==="open"&&r.title.trim().toLowerCase()===n);return o?[`Execute this open docs-roadmap step: "${o.title}".`,o.run?`Its run command: ${o.run}`:"",o.body?`Step detail:
|
|
340
340
|
${o.body}`:"","",`Close the loop IN THE SAME TURN the step's goal state is reached: call d360_roadmap_done with exactly the title "${o.title}", then tell the user it is marked done. This INCLUDES discovering the goal already holds \u2014 "no action needed" completes the STEP, not just the turn, so stamp it done then too. Leave it open ONLY if the work is genuinely incomplete (blocked, or background results not yet applied) \u2014 then say exactly what remains before it can be closed.`].filter(Boolean).join(`
|
|
341
|
-
`):null}async function Ly(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let o=Lr(n,e.slice(1).join(" ").trim());return console.log(o.ok?X(o.line):H(o.line)),{kind:"continue"}}for(let o of ld(n,{all:e.some(r=>r.toLowerCase()==="--all")}))console.log(o);return{kind:"continue"}}var ud={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 pushing overwrites the portal edit"},vC="\u26A0 held on Document360 in another editor \u2014 /resolve settles it";function Wo(e){return e.filter(t=>t.path!==null&&t.status in ud&&!t.link).map(t=>({path:t.path,label:ud[t.status]}))}function Uo(e,t=[]){let n=Wo(e),o=new Set(t),r=new Set([...e.filter(s=>s.status==="conflict"&&s.path).map(s=>s.path),...o]);return{clean:n.filter(s=>!r.has(s.path)),conflicts:n.filter(s=>r.has(s.path)).map(s=>o.has(s.path)&&s.label!==ud.conflict?{...s,label:vC}:s)}}function Fo(e,t){try{return dC(e,Qa(e,t).name).map(n=>n.path)}catch{return[]}}function Fs(e,t=0){let n=e!==1;if(t>=e)return`\u26A0 ${e} article${n?"s":""} NOT pushed (nothing on the portal overwritten) \u2014 Document360 holds ${n?"their bodies":"its body"} in another editor, so ${n?"they cannot be":"it cannot be"} read back. Settle ${n?"them":"it"}: /resolve (or ask your Document360 admin to move ${n?"them":"it"} to the Markdown editor).`;let o=t>0?` (${t} of ${n?"them are":"these is"} held in another editor and cannot be read back)`:"";return`\u26A0 ${e} conflict${n?"s":""} NOT pushed (portal edit${n?"s":""} kept safe) \u2014 ${n?"these were":"it was"} edited both here and on the portal, so ${n?"they are":"it is"} left untouched.${o} Settle ${n?"them":"it"}: /resolve (or /push <path> to keep yours, /pull <path> to take the portal's).`}function dd(e,t){let n=t.scope?.replace(/\\/g,"/").replace(/\/+$/,"");return!n||!n.endsWith(".md")||!Uy(e,t.profileName).map(r=>r.replace(/\\/g,"/")).some(r=>r===n||r.endsWith(`/${n}`)||n.endsWith(`/${r}`))?null:{cmd:Ce("/publish","",n),reason:"it takes this draft live \u2014 until it does, your readers still see the previous version"}}function Or(e,t){let n=Uy(e,t),o=n.length;if(o===0)return null;let r=o===1?"":"s",s=0;try{s=uC(e,n).length}catch{}if(s>0){let i=o-s,a=`${s===o?o===1?"It is":"All of them are":`${s} of them ${s===1?"is":"are"}`} waiting on a missing picture`;return`\u2139 ${o} article${r} ${o===1?"is":"are"} saved on Document360 as a draft and not live yet \u2014 readers still see the previous version. ${a}, so /publish holds ${s===1?"it":"them"} back${i>0?` and takes the other ${i} live once ${i===1?"it has":"they have"} been signed off.`:"."}`}return`\u2139 ${o} article${r} ${o===1?"is":"are"} saved on Document360 as a draft and not live yet \u2014 readers still see the previous version. /publish takes ${o===1?"it":"them"} live once ${o===1?"it has":"they have"} been signed off.`}function Xa(e){return e.filter(t=>t.link).length}function pd(e,t){try{let n=_y(e,Qa(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=$C(sC(iC(e,r),"utf8"),r,n).unresolved}catch{}return o===0?null:`\u2139 ${o} cross-link${o===1?"":"s"} point to pages that aren't on Document360 yet \u2014 they show as plain text for now and turn into links once those pages are pushed.`}catch{return null}}function Vy(e,t=[]){let n=[];e.length>1&&n.push({kind:"all",label:`Push 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("/"),i=o.get(s);i?i.push(r):o.set(s,[r])}for(let r of[...o.keys()].sort()){let s=o.get(r).sort((i,a)=>i.path.localeCompare(a.path));n.push({kind:"category",label:`${Yn(r)} (${s.length})`,paths:s.map(i=>i.path),indent:!1});for(let i of s){let a=i.path.replace(/\\/g,"/").split("/").pop()??i.path;n.push({kind:"article",label:a,paths:[i.path],indent:!0,note:i.label})}}for(let r of[...t].sort((s,i)=>s.path.localeCompare(i.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}async function Ws(e,t){try{let n=Qa(e,t),o=n.project.projectId,r=n.project.workspaceId;if(!o||!r)return null;let s=await kC({profile:n.name,connection:n.connection,projectId:o,projectName:n.project.projectName},{cwd:e,profile:n.name,projectPath:`/v3/projects/${o}`,workspaceId:r,verifyHidden:!1});if(s.kind!=="created")return null;if(s.hidden!=="confirmed"){let i=s.seeded.length===0?" Its internal articles were NOT created, because that would put docs-agent scaffolding in front of your readers.":"";return`\u26A0 Created the "${Oy}" folder on Document360 for reviewer feedback, but could NOT confirm it is hidden from readers.${i} Open its category settings in the portal and turn on "Hide from readers", then run /catch-up.`}return`\u2139 Created a hidden "${Oy}" folder on Document360 \u2014 it's where your reviewers leave feedback for d360-writer to action (confirmed hidden from readers; its README explains how). /catch-up picks up what they write.`}catch{return null}}var Lt="--skip-review";function Bs(e,t){return pC(e,t)}function Ja(e,t){try{return Bs(e,Wy(e,t)).length}catch{return 0}}function Ot(e,t,n="",o,r){let s=Ja(e,o),i=Za(e,o),a=o?` ${o}`:"",l=o?"/push":"/push --all",c=Ry(e,{just:r}),h=!!o&&o.endsWith(".md"),y=c&&h?` (${c.short} \u2014 ${c.cmd} once this page is delivered.)`:"";if(c&&!h){let S=s>0?` (${s} article${s===1?"":"s"}${o&&!o.endsWith(".md")?` in ${o}`:""} ${s===1?"carries":"carry"} text no editor has read, so ${s===1?"it cannot":"they cannot"} be sent up until /review${a} --blocked --fix runs \u2014 that can wait until the writing is done.)`:i>0?` (${i} article${i===1?"":"s"} break${i===1?"s":""} house style rules that block sending up \u2014 /lint${a} --blocked --fix clears that whenever you want.)`:"";return{text:`${n}${c.text}${S}`,cmd:c.cmd}}if(s===0&&i===0)return y?{...t,text:`${t.text}${y}`}:t;let x=o&&!o.endsWith(".md")?` in ${o}`:"";if(s>0){let S=s===1?"":"s",P=i>0?` ${i} also break house style rules \u2014 /lint${a} --blocked --fix clears those afterwards.`:"",T=`/review${a} --blocked --fix`;return{text:`${n}${s} article${S}${x} ${s===1?"carries":"carry"} text no editor has read, so pushing ${s===1?"it is":"them is"} blocked. ${T} reads ${s===1?"it":"just those"} and applies its fixes.${P} Then ${l}.${y}`,cmd:T}}return{text:`${n}${i} article${i===1?"":"s"}${x} break${i===1?"s":""} house style rules that block publishing. /lint${a} --blocked --fix corrects them in place \u2014 finding them costs nothing \u2014 then ${l}.${y}`,cmd:`/lint${a} --blocked --fix`}}function Za(e,t){try{return Fy(e,Wy(e,t)).length}catch{return 0}}function Yy(e,t){return Fy(e,t)}function hd(e,t,n){try{let o=_y(e,Qa(e,n).name);if(!o)return 0;let r=i=>i.replace(/\\/g,"/"),s=new Set(Object.keys(o.articles??{}).map(r));return t.filter(i=>s.has(r(i))).length}catch{return 0}}function fd(e,t){let n=`/push${t.scope?` ${t.scope}`:" --all"}`,o=l=>`${l} article${l===1?"":"s"}`,r=[],s=e.pushed.length,i=t.elapsedMs!==void 0?` \xB7 ${SC(t.elapsedMs)}`:"",a=e.screenshotsUploaded>0?` \xB7 ${e.screenshotsUploaded} screenshot${e.screenshotsUploaded===1?"":"s"} uploaded`:"";s===0&&e.failed.length===0?r.push("Nothing was pushed \u2014 no articles were sent."):t.recorded<s?(r.push(`Pushed ${t.recorded}/${o(s)}${a}${i}.`),r.push(`${s-t.recorded} article${s-t.recorded===1?"":"s"} reported success but ${s-t.recorded===1?"is":"are"} not recorded in the category map \u2014 re-run ${n}.`)):(r.push(`Pushed ${o(s)}${e.created>0?` (${e.created} new)`:""}${a}${i}.`),r.push(`Saved on Document360 as draft${s===1?"":"s"} \u2014 readers don't see ${s===1?"it":"them"} until /publish takes ${s===1?"it":"them"} live.`)),e.stopped?.reason==="unavailable"&&r.push(`Stopped: ${e.stopped.streak} articles in a row could not reach Document360${e.notRun.length>0?`, so the remaining ${e.notRun.length} ${e.notRun.length===1?"was":"were"} not attempted`:""}.`);for(let l of e.duplicateCategories??[])r.push(`\u26A0 Document360 now holds ${l.ids.length} categories called "${l.name}" \u2014 your articles are split between them.`);if((e.duplicateCategories??[]).length>0&&r.push(" Nothing here deletes a category. Remove the extra ones in the portal, then run /push --all again."),e.stopped?.reason==="identity"&&r.push(`Nothing was pushed. ${e.stopped.error}`),e.failed.length>0){let l=e.failed.filter(y=>y.refused),c=RC(e.failed,t.docsRoot),h=e.failed.length;if(c.length===1&&h>1)r.push(`${o(h)} could not be pushed \u2014 all with the same error: ${c[0].error}`),r.push(...My(c[0].paths," \u2717 "));else{r.push(`${o(h)} could not be pushed:`);for(let y of c)y.paths.length===1?r.push(` \u2717 ${y.paths[0]} \u2014 ${y.error}`):(r.push(` \u2717 ${o(y.paths.length)} \u2014 ${y.error}`),r.push(...My(y.paths," ")))}l.length<e.failed.length&&(e.stopped?r.push(`Nothing was lost \u2014 your articles are unchanged. Re-run ${n} when Document360 is back.`):r.push(`Re-run ${n} to retry the rest \u2014 articles already saved are sent again only if they changed.`))}if(e.notRun.length>0&&!e.stopped&&r.push(`\u26A0 ${o(e.notRun.length)} never started (the run was stopped): ${xC(e.notRun)}`),e.missingShots.length>0){let l=e.missingShots.flatMap(c=>c.ids);r.push(`\u26A0 ${l.length} screenshot${l.length===1?"":"s"} in ${o(e.missingShots.length)} ${l.length===1?"has":"have"} not been taken, so the description was published instead: /screenshot capture`)}if(e.categoryLookupFailed.length>0){let l=e.categoryLookupFailed.length;r.push(`\u26A0 Could not check Document360 for existing categories, so ${l===1?"a new one was":`${l} new ones were`} created. There may now be two with the same name: /doctor lists them.`),r.push(` Reason: ${e.categoryLookupFailed[0].reason}`)}return t.conflictsSkipped&&t.conflictsSkipped>0&&r.push(Fs(t.conflictsSkipped,t.unreadableSkipped??0)),r}var xC=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,cd=5;function My(e,t){let n=e.slice(0,cd).map(o=>`${t}${o}`);return e.length>cd&&n.push(`${" ".repeat(t.length)}\u2026 +${e.length-cd} more`),n}function RC(e,t){let n=t?`${t.replace(/\\/g,"/").replace(/\/+$/,"")}/`:null,o=s=>{let i=s.replace(/\\/g,"/");return n&&i.startsWith(n)?i.slice(n.length):i},r=new Map;for(let s of e){let i=r.get(s.error);i?i.push(o(s.path)):r.set(s.error,[o(s.path)])}return[...r.entries()].map(([s,i])=>({error:s,paths:i})).sort((s,i)=>i.paths.length-s.paths.length)}function SC(e){let t=Math.round(e/1e3);return t<60?`${t}s`:`${Math.floor(t/60)}m ${String(t%60).padStart(2,"0")}s`}async function Zt(e,t,n=0,o){let r=hC(e.cwd,t,{allowUnreviewed:o?.skipReview===!0,allowStyleErrors:o?.skipStyle===!0});if(!r.clear){for(let c of fC(r,t.length,{act:"push"}))console.log(H(c));return{kind:"continue"}}let s={aborted:!1,partitions:0,failed:0,notRun:0,producedNothing:!0},i={retryable:0,stopped:!1,paths:[]},a=async(c,h)=>{let y=Date.now();console.log(u(h?`Resolving cross-links in ${c.length} article${c.length===1?"":"s"} whose targets published this run (second pass)\u2026`:`Pushing ${c.length} article${c.length===1?"":"s"} to Document360 (${yC} at a time)\u2026`));let x=await mC({cwd:e.cwd,...e.profileName?{profileName:e.profileName}:{},paths:c,...o?.allowUnpullable===!0?{allowUnpullable:!0}:{},onEvent:B=>{B.type==="article_done"?console.log(X(` \u2713 ${B.result.path}${B.result.action==="created"?" (new)":""}`)):B.type==="article_failed"&&console.log(L(` \u2717 ${B.failure.path}`))}});console.log("");let w=hd(e.cwd,c,e.profileName);h||(i={retryable:x.failed.filter(B=>!B.refused).length,stopped:!!x.stopped,paths:x.failed.map(B=>B.path)},s={aborted:x.aborted||!!x.stopped,partitions:lC(c).length,failed:x.failed.length,notRun:x.notRun.length,producedNothing:x.pushed.length===0,verifiedComplete:w>=c.length,leftBehind:n});let S=x.pushed.length>0;for(let B of fd(x,{recorded:w,elapsedMs:Date.now()-y,docsRoot:bC(e.cwd),...h?{}:{conflictsSkipped:n,unreadableSkipped:o?.unreadableSkipped??0},...o?.scope?{scope:o.scope}:{}}))console.log(S&&x.failed.length===0?X(B):H(B));let P=x.aborted||!!x.stopped;if(!S)return P;let T=pd(e.cwd,e.profileName);T&&console.log(u(T));let R=Or(e.cwd,e.profileName);if(R&&console.log(u(R)),P)return P;try{let B=Hy(await By({cwd:e.cwd,profileName:e.profileName,onRateLimit:G=>console.log(u(` Document360 rate limit \u2014 waiting ${Math.ceil(G.waitMs/1e3)}s\u2026`))}));B&&console.log(B.startsWith("\u26A0")?H(B):u(B))}catch{}try{let B=qy(await Gy({cwd:e.cwd,profileName:e.profileName}));B&&console.log(u(B))}catch{}let N=await Ws(e.cwd,e.profileName);return N&&console.log(u(N)),P};try{if(!await a(t,!1)){let h=await md(e.cwd,e.profileName,t,i.paths);if(h.length>0&&await a(h,!0),Jt(s))for(let y of Ye(e.cwd,o?.scope?`/push ${o.scope}`:"/push --all"))console.log(X(y))}}catch(c){console.log(L(`Push run failed: ${c.message}`))}if(console.log(""),i.retryable>0){let c=Ce("/push",o?.scope?"":"--all",o?.scope);return console.log(u(i.stopped?`Next: ${c} \u2014 your articles are unchanged, so it picks up where the run left off.`:`Next: ${c} \u2014 retries the ${i.retryable} article${i.retryable===1?"":"s"} that could not be saved.`)),{kind:"continue",ownNext:!0}}let l=dd(e.cwd,{scope:o?.scope,profileName:e.profileName});return l?(console.log(u(`Next: ${l.cmd} \u2014 ${l.reason}.`)),{kind:"continue",ownNext:!0}):{kind:"continue"}}async function el(e,t,n){let o=cC(e,n);if(o.length===0)return[];let r=new Set(Wo((await za({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function md(e,t,n,o=[]){try{let r=new Set(n),s=new Set(o),i=await za({cwd:e,profileName:t});return Wo(i.entries).map(a=>a.path).filter(a=>r.has(a)&&!s.has(a))}catch{return[]}}async function CC(e,t,n){try{let o=await gC({cwd:e,...t?{profileName:t}:{},relPath:n.replace(/\\/g,"/"),preview:!0});console.log(""),console.log(X(`${o.title}`)),console.log(u(`${o.path} \xB7 ${o.articleId?`updates article ${o.articleId}`:"would be created as a new article"}`)),o.shots.length>0&&console.log(u(`${o.shots.length} screenshot${o.shots.length===1?"":"s"} embedded: ${o.shots.map(r=>r.id).join(", ")}`)),o.missingShots.length>0&&console.log(H(`\u26A0 ${o.missingShots.length} screenshot${o.missingShots.length===1?"":"s"} not taken yet \u2014 the description publishes instead: ${o.missingShots.join(", ")}`)),console.log(u("\u2500".repeat(Math.min(80,Math.max(20,(process.stdout.columns??80)-1))))),console.log(o.body),console.log(u("\u2500".repeat(Math.min(80,Math.max(20,(process.stdout.columns??80)-1))))),console.log(u(`Nothing was sent. Run /push ${o.path} to save it as a draft.`))}catch(o){console.log(L(o.message))}return{kind:"continue"}}async function tl(e,t){let n=Je(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(L(n.reason)),{kind:"continue"};let o=e.includes(Lt),r=e.includes(wC);if(e.includes("--preview")){let i=e.find(a=>!a.startsWith("--"));return i?await CC(t?.cwd??process.cwd(),t?.profileName,i):(console.log(L("Which article? Use /push --preview <path> \u2014 a preview is per article.")),{kind:"continue"})}let s=e[0];if(e.includes("--screenshots")||e.includes("--shots")){let i=t?.cwd??process.cwd(),a=e.find(w=>!w.startsWith("--")),l=He(i),c=Fa(l,a);if(c.length===0){let w=l.filter(S=>S.state==="captured").length;return console.log(u(w>0?`${w} screenshot${w===1?" has":"s have"} been taken but the callouts aren't drawn on yet, so there is nothing to embed \u2014 /screenshot annotate finishes ${w===1?"it":"them"}.`:a?`No captured screenshots in ${a} \u2014 /push --screenshots covers the whole knowledge base.`:"No captured screenshots yet \u2014 /screenshot capture first.")),{kind:"continue"}}let h=Wa(l,a);h&&console.log(h);let y=Ba(l);y&&console.log(y);let x=Ce("","--screenshots",a).trim();return await Zt(t??{cwd:process.cwd()},c,0,{skipReview:o,skipStyle:r,scope:x})}if(s==="--related"&&e[1]){if(!t)return{kind:"continue"};let i=await el(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return i.length===0?(console.log(X("\u2713 All related articles are already on Document360.")),{kind:"continue"}):await Zt(t,i,0,{skipReview:o,skipStyle:r,scope:`--related ${e[1]}`})}if(s==="--all"){console.log(u("Checking what needs pushing\u2026"));try{let i=await za({cwd:t?.cwd??process.cwd()}),a=new Set(Fo(t?.cwd??process.cwd(),t?.profileName)),{clean:l,conflicts:c}=Uo(i.entries,a),h=c.filter(P=>a.has(P.path)).length,y=Xa(i.entries),x=e.includes("--force"),w=x&&c.length>0;y>0&&console.log(H(`\u26A0 ${y} article(s) already exist on Document360 but aren't linked \u2014 left out (pushing would duplicate them). Run /catch-up or ask me to link them first.`)),c.length>0&&!w&&console.log(H(Fs(c.length,h)));let S=w?[...l,...c]:l;if(S.length===0){if(c.length>0){let T=Or(t?.cwd??process.cwd(),t?.profileName);return T&&console.log(u(T)),console.log(u("Resolve the conflicts: /resolve")),{kind:"continue"}}console.log(X(y>0?"\u2713 Nothing else is ahead of Document360 to push.":"\u2713 Nothing is ahead of Document360 \u2014 nothing to push."));let P=Or(t?.cwd??process.cwd(),t?.profileName);if(P&&console.log(u(P)),t)try{let T=Hy(await By({cwd:t.cwd,profileName:t.profileName,onRateLimit:N=>console.log(u(` Document360 rate limit \u2014 waiting ${Math.ceil(N.waitMs/1e3)}s\u2026`))}));T&&console.log(T.startsWith("\u26A0")?H(T):u(T));let R=qy(await Gy({cwd:t.cwd,profileName:t.profileName}));R&&console.log(u(R))}catch{}return{kind:"continue"}}return await Zt(t??{cwd:process.cwd()},S.map(P=>P.path),w?0:c.length,{skipReview:o,skipStyle:r,allowUnpullable:x,unreadableSkipped:w?0:h})}catch(i){return console.log(L(`Could not compute sync status: ${i.message}`)),{kind:"continue"}}}if(s&&s.startsWith("--")&&(s=e.find(i=>!i.startsWith("--"))??""),!s){console.log(u("Checking what needs pushing\u2026"));let i,a=0,l=0;try{let c=await za({cwd:t?.cwd??process.cwd()}),h=new Set(Fo(t?.cwd??process.cwd(),t?.profileName)),{clean:y,conflicts:x}=Uo(c.entries,h);l=x.filter(S=>h.has(S.path)).length,i=y,a=x.length;let w=Xa(c.entries);if(w>0&&console.log(H(`\u26A0 ${w} article(s) already exist on Document360 but aren't linked \u2014 left out (pushing would duplicate them). Run /catch-up or ask me to link them first.`)),x.length>0&&console.log(H(Fs(x.length,l))),i.length===0&&x.length>0)return console.log(u("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(c){return console.log(L(`Could not compute sync status: ${c.message}`)),console.log(u("Push a specific article: /push <article-path>")),{kind:"continue"}}if(i.length===0)return console.log(X("\u2713 Nothing is ahead of Document360 \u2014 nothing to push.")),console.log(u(" (Articles without a sync base are unverified \u2014 push those by path if needed.)")),{kind:"continue"};if(!process.stdin.isTTY||!t){for(let c of i)console.log(` ${c.path} ${u(`(${c.label})`)}`);return console.log(u("Run: /push <article-path>")),{kind:"continue"}}try{s=await t.withPausedInput(()=>aC({message:"Push which article?",choices:[...i.length>1?[{name:`All ${i.length} candidates`,value:"--all",description:"one agent run over every candidate"}]:[],...i.map(c=>({name:c.path,value:c.path,description:c.label}))]}))}catch{return console.log(u("Cancelled.")),{kind:"continue"}}if(s==="--all")return await Zt(t,i.map(c=>c.path),a,{skipReview:o,skipStyle:r,unreadableSkipped:l})}return await Zt(t??{cwd:process.cwd()},[s],0,{skipReview:o,skipStyle:r,scope:s})}ie();import{select as EC}from"@inquirer/prompts";import{computeSyncStatus as NC,localAheadPaths as DC,pendingDrafts as jC,publishArticleLive as IC,publishGateVerdict as LC,publishGateLines as OC,blockedPaths as MC,placeholderRemedy as _C,resolveActiveProfile as UC,SKIP_STYLE_FLAG as FC,SKIP_SHOTS_FLAG as WC}from"document360-engine";import{gateFixTarget as PC}from"document360-engine";var yd=e=>"ruleId"in e,nl=e=>yd(e)?e.severity:"warning",Qn=e=>e===1?"":"s";function Hs(e,t){let n=t??PC(e),o=n?` ${n}`:"";return e.unreviewed.length>0?`/review${o} --blocked --fix`:`/lint${o} --blocked --fix`}var gd=new Map;var TC=e=>yd(e)?e.fp||`${e.ruleId}:${e.path}:${e.line}:${e.term}`:`${e.kind}:${e.path}:${e.line}`;function Gs(e){let{cwd:t,after:n,scope:o,aborted:r,blocked:s}=e,i=n.filter(w=>nl(w)==="error").length,a=n.filter(w=>nl(w)==="warning").length,l=n.filter(w=>nl(w)==="suggestion").length,c=Ce("/lint","--blocked --fix",o);if(r){let w=Ce("/lint",s?"--blocked --fix":"--fix",o);return{text:`Stopped. Nothing else changed \u2014 ${w} picks up where this left off.`,cmd:w}}if(i>0){let w=n.filter(N=>nl(N)==="error"),S=new Set(w.map(N=>N.path)).size,P=`${t}::${o??""}`,T=w.map(TC).sort().join("|"),R=gd.get(P)===T;if(gd.set(P,T),R){let N=Ce("/lint","--blocked --full",o),B=[...new Set(w.filter(yd).map(G=>G.ruleId))];return{text:`The same ${i} error${Qn(i)} in ${S} article${Qn(S)} survived two ${c} passes, so a third would change nothing \u2014 ${i===1?"it needs":"they need"} a person. ${N} shows ${i===1?"it":"them"} in place. If ${B.length===1?`${B[0]} is`:"a rule is"} wrong for your product, switch it off in .d360-writer/config.json under "styleGuide": { "rules": { "<rule>": "off" } }.`,cmd:N}}return{text:`${i} error${Qn(i)} in ${S} article${Qn(S)} still block${i===1?"s":""} publishing. ${c} has another go at ${i===1?"it":"just those"} \u2014 if a second pass leaves the same ones, they need a human eye.`,cmd:c}}gd.delete(`${t}::${o??""}`);let h=a>0&&l>0?`${a} warning${Qn(a)} and ${l} suggestion${Qn(l)} remain (neither blocks publishing). `:a>0?`${a} warning${Qn(a)} remain${a===1?"s":""}, which ${a===1?"does":"do"} not block publishing. `:l>0?`${l} suggestion${Qn(l)} remain${l===1?"s":""} \u2014 ${l===1?"it is":"they are"} judgment calls and ${l===1?"does":"do"} not block publishing. `:"",y=h===""?"\u2713 Nothing left to fix. ":`\u2713 ${h}`,x=o?"/push":"/push --all";return Ot(t,{text:`${y}Nothing is blocking${o?` in ${o}`:""} \u2014 ${x} saves the articles to Document360 as drafts.`,cmd:x},y,o)}var AC={check:"/check is now /lint (same command)."};function ol(){return"That saves drafts rather than taking anything live, so running /push. (/publish takes saved drafts live.)"}var Ky=new Set;function qs(e){let t=AC[e.replace(/^\//,"")];return!t||Ky.has(e)?null:(Ky.add(e),t)}var BC=400,HC=3e3,GC=e=>e>0?new Promise(t=>setTimeout(t,e)):Promise.resolve(),bd=e=>e===1?"":"s",wd=e=>e.replace(/\\/g,"/").split("/").pop()??e;function kd(e){return e.includes("--screenshots")||e.includes("--shots")||e[0]==="--related"}async function $d(e,t,n){await NC({cwd:e,profileName:t});let o=n?n.replace(/\\/g,"/").replace(/\/+$/,""):null;return jC(e,t).filter(r=>!o||r.path===o||r.path.startsWith(`${o}/`)).map(r=>({...r,label:qC(e,r.path)}))}function qC(e,t){let n=Ea(e,t)??Ls(t),o=Aa(t),r=o?Yn(o):"";return r?`${r} \u203A ${n}`:n}function VC(e){let t=Math.min(58,Math.max(...e.map(n=>n.label.length),20));return e.map(n=>` ${n.label.padEnd(t)} ${n.version?`draft v${n.version} \u2192 live`:"draft \u2192 live"}`)}function vd(e,t,n){let r=[`\u2713 Nothing is waiting to go live${n?` in ${n}`:""} \u2014 readers are seeing the latest version of every article.`],s=n?n.replace(/\\/g,"/").replace(/\/+$/,""):null,i=DC(e,t).filter(a=>!s||a===s||a.startsWith(`${s}/`)).length;return i>0&&r.push(`${i} article${bd(i)} ${i===1?"has":"have"} local edits that aren't on Document360 yet \u2014 that's /push${n?` ${n}`:""}.`),{lines:r,ahead:i}}function rl(e,t,n){let o=null;try{o=_C(e,t.placeholders)?.cmd??null}catch{}return{cmd:t.unreviewed.length>0||t.styleErrors.length>0?Hs(t,n):o,shotFix:o}}function xd(e,t,n,o){if(n)return null;let r=!1;try{r=UC(e,t).production}catch{return null}if(!r)return null;let s=o;return[`\u26A0 ${s} draft${s===1?"":"s"} ${s===1?"is":"are"} ready, and this is a PRODUCTION deployment.`," Nothing is blocking them \u2014 taking articles live here just needs authorizing once per session."," Run /allow-prod, then /publish."]}async function Rd(e,t,n,o={}){let r={published:[],blocked:[],failed:[]},s=0,i=BC,a=0;for(let l of n){o.onProgress?.(s,n.length,l.label);let c=await IC({onRateLimit:()=>{a+=1,i=Math.min(i*2,HC)},articleId:l.articleId,cwd:e,profileName:t,allowUnreviewed:o.skipReview===!0,allowStyleErrors:o.skipStyle===!0,allowProduction:o.allowProduction===!0});c.ok?r.published.push({path:l.path,...c.url?{url:c.url}:{}}):c.blocked?r.blocked.push({path:l.path,message:c.message,...c.commands.length>0?{commands:c.commands}:{}}):r.failed.push({path:l.path,message:c.error.message}),s+=1,s<n.length&&await GC(i)}return a>0&&(r.throttled={times:a,finalPacingMs:i}),r}function Sd(e){let{published:t,blocked:n,failed:o}=e,r=[];if(t.length>0){r.push(`\u2713 ${t.length} article${bd(t.length)} ${t.length===1?"is":"are"} now live \u2014 readers see ${t.length===1?"it":"them"} now.`);let s=t.filter(i=>i.url);for(let i of s.slice(0,3))r.push(` \u2B95 ${i.url}`);s.length>3&&r.push(` \u2B95 \u2026and ${s.length-3} more`)}if(n.length>0){let s=n.length>0&&n.every(i=>(i.commands??[]).includes("/allow-prod"));r.push(s?`\u2717 ${n.length} not published \u2014 this is a PRODUCTION deployment and this session is not authorized. Still ${n.length===1?"a draft":"drafts"}:`:`\u2717 ${n.length} refused by the publish gates \u2014 still ${n.length===1?"a draft":"drafts"}, nothing was lost:`);for(let i of n.slice(0,3))r.push(` \xB7 ${wd(i.path)}`);n.length>3&&r.push(` \xB7 \u2026and ${n.length-3} more`),r.push(s?" Run /allow-prod, then /publish.":" /status names what is blocking each one, and the command that clears it. It costs nothing.")}if(e.throttled){let s=(e.throttled.finalPacingMs/1e3).toFixed(1);r.push(`\u2139 Document360 asked us to slow down ${e.throttled.times} time${e.throttled.times===1?"":"s"}, so this run eased to ${s}s between articles.`)}if(o.length>0){r.push(`\u2717 ${o.length} failed \u2014 ${o.length===1?"it is":"they are"} still a draft, so re-running /publish retries ${o.length===1?"it":"them"}:`);for(let s of o.slice(0,3))r.push(` \xB7 ${wd(s.path)} \u2014 ${s.message}`);o.length>3&&r.push(` \xB7 \u2026and ${o.length-3} more`)}return r.length===0&&r.push("Nothing was published."),r}async function zy(e,t){let n=t?.cwd??process.cwd();if(kd(e))return console.log(u(`\u2192 ${ol()}`)),tl(e,t);let o=Je(n,t?.profileName);if(!o.ok)return console.log(L(o.reason)),{kind:"continue"};let r=e.includes(Lt),s=e.includes(FC),i=e.includes(WC),a=e.includes("--all"),l=e.find(R=>!R.startsWith("--"));console.log(u("Checking what is waiting to go live\u2026"));let c;try{c=await $d(n,t?.profileName,l)}catch(R){return console.log(L(`Could not check Document360: ${R.message}`)),{kind:"continue"}}if(c.length===0){for(let R of vd(n,t?.profileName,l).lines)console.log(R.startsWith("\u2713")?X(R):u(R));return{kind:"continue"}}let h=LC(n,c.map(R=>R.path),{allowUnreviewed:r,allowStyleErrors:s,checkScreenshots:!0,allowPlaceholders:i}),y=new Set(MC(h)),x=c.filter(R=>!y.has(R.path)),w=rl(n,h,l);if(y.size>0)for(let R of OC(h,c.length,{scope:l,act:"publish",going:x.length,shotFix:w.shotFix}))console.log(H(R));if(x.length===0)return w.cmd&&console.log(u(`Run: ${w.cmd}`)),{kind:"continue"};c=x,console.log(""),console.log(`${c.length} draft${bd(c.length)} ${c.length===1?"is":"are"} ahead of what readers see:`);for(let R of VC(c.slice(0,12)))console.log(u(R));c.length>12&&console.log(u(` \u2026and ${c.length-12} more`)),console.log("");let S=c;if(!a){let R=await EC({message:"Publish live to your readers?",choices:[{name:`Yes \u2014 publish all ${c.length} live`,value:"all"},...c.slice(0,8).map(N=>({name:`Just ${N.label}`,value:N.path})),{name:"No \u2014 leave them as drafts",value:"none"}]});if(R==="none")return console.log(u("Left as drafts. Nothing changed.")),{kind:"continue"};R!=="all"&&(S=c.filter(N=>N.path===R))}let P=xd(n,t?.profileName,t?.allowProdWrites?.()===!0,S.length);if(P){for(let R of P)console.log(R.startsWith("\u26A0")?H(R):u(R));return{kind:"continue"}}let T=await Rd(n,t?.profileName,S,{skipReview:r,skipStyle:s,allowProduction:t?.allowProdWrites?.()===!0,onProgress:(R,N,B)=>console.log(u(` \u25B8 ${R+1}/${N} ${wd(B)}\u2026`))});console.log("");for(let R of Sd(T))console.log(R.startsWith("\u2713")?X(R):R.startsWith("\u2717")?H(R):u(R));return{kind:"continue"}}import{loadKnownConflicts as YC,localArticleTitle as KC,resolveActiveProfile as zC,surfaceCoverageSafe as Xy,readProjectConfig as Qy,recordDeclinedSurface as XC,areaExists as QC,declineTargets as Jy}from"document360-engine";function JC(e,t){let n=KC(e,t);return n||(t.split(/[\\/]/).pop()??t).replace(/\.md$/,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ")}function sl(e,t){let n=[];try{n=YC(e,zC(e,t).name)}catch{return null}if(n.length===0)return null;let o=n.length,r=n.slice(0,3).map(i=>JC(e,i)),s=o>3?`${r.join(", ")} and ${o-3} more`:r.join(", ");return{paths:n,note:`\u26A0 ${o} article${o===1?"":"s"} ${o===1?"has":"have"} been changed both here and on Document360 (${s}), so your local copy is not a reliable picture of what your readers have. An audit over it could tell you to write an article that already exists, or miss one that needs your decision \u2014 so it needs ${o===1?"that":"those"} settled first.`}}var Mr={cmd:"/resolve",reason:"it walks each one with you \u2014 keep yours, take the portal's, or skip"};function il(e,t){let n=t.indexOf("--decline");if(n<0)return null;let o=t[n+1];if(!o||o.startsWith("--")){let a=Xy(e,Qy(e)),l=a.recognised?a.areas.slice(0,5).flatMap(c=>Jy(c).map(h=>` /audit --decline ${h}`)):[];return["Name the path to decline \u2014 a folder, or a single file.",...l.length?["","No article covers these right now. Run one of these to settle it for good:",...l]:["","For example:"," /audit --decline src/internal-admin"]]}let r=o.replace(/\\/g,"/").replace(/\/+$/,"");if(!QC(e,r))return[`There is nothing at ${r}, so there is nothing to decline. Copy the path from /eval or /audit.`];let s=t.slice(n+2).filter(a=>!a.startsWith("--")).join(" ")||void 0;return XC(e,r,s)?[`\u2713 ${r} will not be reported as needing an article. /audit and /eval leave it out from now on, and say how many you have declined.`]:[`Could not write .d360-writer/declined-surfaces.json, so ${r} was not declined.`]}async function Vs(e){if(e?.cwd){let r=sl(e.cwd,e.profileName);if(r)return{kind:"audit-blocked",note:r.note,lead:Mr}}let t=e?.cwd?Xy(e.cwd,Qy(e.cwd)):null,n=[];if(t?.recognised&&t.areas.length>0){let r=t.areas.slice(0,15);n.push("","2.7. These parts of the product are cited by NO article's `sources:` frontmatter. This list is DETERMINISTIC and complete as of now \u2014 it does not depend on the diff window above, so treat it as authoritative rather than re-deriving it:",...r.map(s=>` - ${s.folder} (${s.files} of ${s.total} file${s.total===1?"":"s"} uncited, e.g. ${s.sample.join(", ")}) \u2014 to decline: ${Jy(s).map(i=>`/audit --decline ${i}`).join(" \xB7 ")}`),...t.areas.length>r.length?[` \u2026and ${t.areas.length-r.length} more areas.`]:[]," EVERY row above must leave this run accounted for: a `create` row, or a stated reason it needs no article (internal-only, unreachable by a reader, already covered by an existing article's prose). Do NOT silently drop one \u2014 if you list fewer paths than this section handed you, say which you left out and why."," A `decline` verdict is not a record. For EVERY row you decline, print its exact /audit --decline line (copied from above \u2014 it already picks folder-or-file correctly) in the closing block, each on its own line so the terminal makes it a button. A judgement that leaves the turn as prose changes nothing and will be re-derived, at this price, on every future audit.",...t.declined>0?[` (${t.declined} more ${t.declined===1?"is":"are"} already declined and left out of that list.)`]:[])}return{kind:"forward-to-agent",prompt:["Run the gap-analysis skill against this repo.","","Follow its stages in order:","1. d360_sync_status first; stop if any article is changed in both places, or changed on Document360 and not yet pulled down (the local copy cannot be trusted until that is resolved). Say which articles, in plain words, never the internal status word \u2014 and tell the user to run /resolve, which walks the affected articles one at a time (keep the local copy, take the portal's, or skip). Do NOT ask them to report back to you: they will run /resolve and then /audit again.","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: the source agent's own notes on what it shipped. Verify each against the CURRENT code (its `sources` exist, and the code as it stands shows the surface it claims) before trusting it; never judge it by its `branch` or `commit`. Fold verified ones into the table, flag the rest.","2.6. Anything d360_pending_hints returns under `held` is NOT a proposal. Its cited code has uncommitted changes, so the builder is still writing that surface and has already been asked whether it is done. List each held item at the END of the table as a `waiting` row (Reason: the code behind it is not finished), do NOT propose create/update/retire for it, and do NOT stamp it consumed.",...n,"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, so backfill them.","4. Output the proposal table: | Article (path or proposed title) | Action (create | update | retire | link) | Reason | Evidence | Scope |. Leave every hint OPEN \u2014 this run proposes, it does not write articles, so nothing has been acted on yet.","5. End with the skill's closing block, and put NOTHING below it \u2014 no receipts, no roadmap confirmations, no feedback marker line, no summary. It ends in a question, and a question the user has to scroll back to find is one you did not really ask.","","Do not start writing or updating any article yet; the proposal table is the deliverable.","The audited-up-to marker is recorded for you when this command finishes. Read it to size the diff window; never write it, and never report it as a missing capability."].join(`
|
|
342
|
-
`),display:"/audit"}}
|
|
343
|
-
`)}async function
|
|
341
|
+
`):null}async function Uy(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let o=Or(n,e.slice(1).join(" ").trim());return console.log(o.ok?X(o.line):H(o.line)),{kind:"continue"}}for(let o of cd(n,{all:e.some(r=>r.toLowerCase()==="--all")}))console.log(o);return{kind:"continue"}}var dd={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 pushing overwrites the portal edit"},EC="\u26A0 held on Document360 in another editor \u2014 /resolve settles it";function Bo(e){return e.filter(t=>t.path!==null&&t.status in dd&&!t.link).map(t=>({path:t.path,label:dd[t.status]}))}function Fo(e,t=[]){let n=Bo(e),o=new Set(t),r=new Set([...e.filter(s=>s.status==="conflict"&&s.path).map(s=>s.path),...o]);return{clean:n.filter(s=>!r.has(s.path)),conflicts:n.filter(s=>r.has(s.path)).map(s=>o.has(s.path)&&s.label!==dd.conflict?{...s,label:EC}:s)}}function Wo(e,t){try{return bC(e,Ja(e,t).name).map(n=>n.path)}catch{return[]}}function Bs(e,t=0){let n=e!==1;if(t>=e)return`\u26A0 ${e} article${n?"s":""} NOT pushed (nothing on the portal overwritten) \u2014 Document360 holds ${n?"their bodies":"its body"} in another editor, so ${n?"they cannot be":"it cannot be"} read back. Settle ${n?"them":"it"}: /resolve (or ask your Document360 admin to move ${n?"them":"it"} to the Markdown editor).`;let o=t>0?` (${t} of ${n?"them are":"these is"} held in another editor and cannot be read back)`:"";return`\u26A0 ${e} conflict${n?"s":""} NOT pushed (portal edit${n?"s":""} kept safe) \u2014 ${n?"these were":"it was"} edited both here and on the portal, so ${n?"they are":"it is"} left untouched.${o} Settle ${n?"them":"it"}: /resolve (or /push <path> to keep yours, /pull <path> to take the portal's).`}function pd(e,t){let n=t.scope?.replace(/\\/g,"/").replace(/\/+$/,"");return!n||!n.endsWith(".md")||!Hy(e,t.profileName).map(r=>r.replace(/\\/g,"/")).some(r=>r===n||r.endsWith(`/${n}`)||n.endsWith(`/${r}`))?null:{cmd:Ce("/publish","",n),reason:"it takes this draft live \u2014 until it does, your readers still see the previous version"}}function Mr(e,t){let n=Hy(e,t),o=n.length;if(o===0)return null;let r=o===1?"":"s",s=0;try{s=wC(e,n).length}catch{}if(s>0){let i=o-s,a=`${s===o?o===1?"It is":"All of them are":`${s} of them ${s===1?"is":"are"}`} waiting on a missing picture`;return`\u2139 ${o} article${r} ${o===1?"is":"are"} saved on Document360 as a draft and not live yet \u2014 readers still see the previous version. ${a}, so /publish holds ${s===1?"it":"them"} back${i>0?` and takes the other ${i} live once ${i===1?"it has":"they have"} been signed off.`:"."}`}return`\u2139 ${o} article${r} ${o===1?"is":"are"} saved on Document360 as a draft and not live yet \u2014 readers still see the previous version. /publish takes ${o===1?"it":"them"} live once ${o===1?"it has":"they have"} been signed off.`}function Qa(e){return e.filter(t=>t.link).length}function hd(e,t){try{let n=By(e,Ja(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=AC(hC(fC(e,r),"utf8"),r,n).unresolved}catch{}return o===0?null:`\u2139 ${o} cross-link${o===1?"":"s"} point to pages that aren't on Document360 yet \u2014 they show as plain text for now and turn into links once those pages are pushed.`}catch{return null}}function Xy(e,t=[]){let n=[];e.length>1&&n.push({kind:"all",label:`Push 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("/"),i=o.get(s);i?i.push(r):o.set(s,[r])}for(let r of[...o.keys()].sort()){let s=o.get(r).sort((i,a)=>i.path.localeCompare(a.path));n.push({kind:"category",label:`${zn(r)} (${s.length})`,paths:s.map(i=>i.path),indent:!1});for(let i of s){let a=i.path.replace(/\\/g,"/").split("/").pop()??i.path;n.push({kind:"article",label:a,paths:[i.path],indent:!0,note:i.label})}}for(let r of[...t].sort((s,i)=>s.path.localeCompare(i.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}async function Hs(e,t){try{let n=Ja(e,t),o=n.project.projectId,r=n.project.workspaceId;if(!o||!r)return null;let s=await TC({profile:n.name,connection:n.connection,projectId:o,projectName:n.project.projectName},{cwd:e,profile:n.name,projectPath:`/v3/projects/${o}`,workspaceId:r,verifyHidden:!1});if(s.kind!=="created")return null;if(s.hidden!=="confirmed"){let i=s.seeded.length===0?" Its internal articles were NOT created, because that would put docs-agent scaffolding in front of your readers.":"";return`\u26A0 Created the "${Fy}" folder on Document360 for reviewer feedback, but could NOT confirm it is hidden from readers.${i} Open its category settings in the portal and turn on "Hide from readers", then run /catch-up.`}return`\u2139 Created a hidden "${Fy}" folder on Document360 \u2014 it's where your reviewers leave feedback for d360-writer to action (confirmed hidden from readers; its README explains how). /catch-up picks up what they write.`}catch{return null}}var _t="--skip-review";function Gs(e,t){return kC(e,t)}function Za(e,t){try{return Gs(e,qy(e,t)).length}catch{return 0}}function Ut(e,t,n="",o,r){let s=Za(e,o),i=el(e,o),a=o?` ${o}`:"",l=o?"/push":"/push --all",c=Ty(e,{just:r}),h=!!o&&o.endsWith(".md"),y=c&&h?` (${c.short} \u2014 ${c.cmd} once this page is delivered.)`:"";if(c&&!h){let S=s>0?` (${s} article${s===1?"":"s"}${o&&!o.endsWith(".md")?` in ${o}`:""} ${s===1?"carries":"carry"} text no editor has read, so ${s===1?"it cannot":"they cannot"} be sent up until /review${a} --blocked --fix runs \u2014 that can wait until the writing is done.)`:i>0?` (${i} article${i===1?"":"s"} break${i===1?"s":""} house style rules that block sending up \u2014 /lint${a} --blocked --fix clears that whenever you want.)`:"";return{text:`${n}${c.text}${S}`,cmd:c.cmd}}if(s===0&&i===0)return y?{...t,text:`${t.text}${y}`}:t;let x=o&&!o.endsWith(".md")?` in ${o}`:"";if(s>0){let S=s===1?"":"s",P=i>0?` ${i} also break house style rules \u2014 /lint${a} --blocked --fix clears those afterwards.`:"",T=`/review${a} --blocked --fix`;return{text:`${n}${s} article${S}${x} ${s===1?"carries":"carry"} text no editor has read, so pushing ${s===1?"it is":"them is"} blocked. ${T} reads ${s===1?"it":"just those"} and applies its fixes.${P} Then ${l}.${y}`,cmd:T}}return{text:`${n}${i} article${i===1?"":"s"}${x} break${i===1?"s":""} house style rules that block publishing. /lint${a} --blocked --fix corrects them in place \u2014 finding them costs nothing \u2014 then ${l}.${y}`,cmd:`/lint${a} --blocked --fix`}}function el(e,t){try{return Gy(e,qy(e,t)).length}catch{return 0}}function Qy(e,t){return Gy(e,t)}function fd(e,t,n){try{let o=By(e,Ja(e,n).name);if(!o)return 0;let r=i=>i.replace(/\\/g,"/"),s=new Set(Object.keys(o.articles??{}).map(r));return t.filter(i=>s.has(r(i))).length}catch{return 0}}function md(e,t){let n=`/push${t.scope?` ${t.scope}`:" --all"}`,o=l=>`${l} article${l===1?"":"s"}`,r=[],s=e.pushed.length,i=t.elapsedMs!==void 0?` \xB7 ${jC(t.elapsedMs)}`:"",a=e.screenshotsUploaded>0?` \xB7 ${e.screenshotsUploaded} screenshot${e.screenshotsUploaded===1?"":"s"} uploaded`:"";s===0&&e.failed.length===0?r.push("Nothing was pushed \u2014 no articles were sent."):t.recorded<s?(r.push(`Pushed ${t.recorded}/${o(s)}${a}${i}.`),r.push(`${s-t.recorded} article${s-t.recorded===1?"":"s"} reported success but ${s-t.recorded===1?"is":"are"} not recorded in the category map \u2014 re-run ${n}.`)):(r.push(`Pushed ${o(s)}${e.created>0?` (${e.created} new)`:""}${a}${i}.`),r.push(`Saved on Document360 as draft${s===1?"":"s"} \u2014 readers don't see ${s===1?"it":"them"} until /publish takes ${s===1?"it":"them"} live.`)),e.stopped?.reason==="unavailable"&&r.push(`Stopped: ${e.stopped.streak} articles in a row could not reach Document360${e.notRun.length>0?`, so the remaining ${e.notRun.length} ${e.notRun.length===1?"was":"were"} not attempted`:""}.`);for(let l of e.duplicateCategories??[])r.push(`\u26A0 Document360 now holds ${l.ids.length} categories called "${l.name}" \u2014 your articles are split between them.`);if((e.duplicateCategories??[]).length>0&&r.push(" Nothing here deletes a category. Remove the extra ones in the portal, then run /push --all again."),e.stopped?.reason==="identity"&&r.push(`Nothing was pushed. ${e.stopped.error}`),e.failed.length>0){let l=e.failed.filter(y=>y.refused),c=DC(e.failed,t.docsRoot),h=e.failed.length;if(c.length===1&&h>1)r.push(`${o(h)} could not be pushed \u2014 all with the same error: ${c[0].error}`),r.push(...Wy(c[0].paths," \u2717 "));else{r.push(`${o(h)} could not be pushed:`);for(let y of c)y.paths.length===1?r.push(` \u2717 ${y.paths[0]} \u2014 ${y.error}`):(r.push(` \u2717 ${o(y.paths.length)} \u2014 ${y.error}`),r.push(...Wy(y.paths," ")))}l.length<e.failed.length&&(e.stopped?r.push(`Nothing was lost \u2014 your articles are unchanged. Re-run ${n} when Document360 is back.`):r.push(`Re-run ${n} to retry the rest \u2014 articles already saved are sent again only if they changed.`))}if(e.notRun.length>0&&!e.stopped&&r.push(`\u26A0 ${o(e.notRun.length)} never started (the run was stopped): ${NC(e.notRun)}`),e.missingShots.length>0){let l=e.missingShots.flatMap(c=>c.ids);r.push(`\u26A0 ${l.length} screenshot${l.length===1?"":"s"} in ${o(e.missingShots.length)} ${l.length===1?"has":"have"} not been taken, so the description was published instead: /screenshot capture`)}if(e.categoryLookupFailed.length>0){let l=e.categoryLookupFailed.length;r.push(`\u26A0 Could not check Document360 for existing categories, so ${l===1?"a new one was":`${l} new ones were`} created. There may now be two with the same name: /doctor lists them.`),r.push(` Reason: ${e.categoryLookupFailed[0].reason}`)}return t.conflictsSkipped&&t.conflictsSkipped>0&&r.push(Bs(t.conflictsSkipped,t.unreadableSkipped??0)),r}var NC=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,ud=5;function Wy(e,t){let n=e.slice(0,ud).map(o=>`${t}${o}`);return e.length>ud&&n.push(`${" ".repeat(t.length)}\u2026 +${e.length-ud} more`),n}function DC(e,t){let n=t?`${t.replace(/\\/g,"/").replace(/\/+$/,"")}/`:null,o=s=>{let i=s.replace(/\\/g,"/");return n&&i.startsWith(n)?i.slice(n.length):i},r=new Map;for(let s of e){let i=r.get(s.error);i?i.push(o(s.path)):r.set(s.error,[o(s.path)])}return[...r.entries()].map(([s,i])=>({error:s,paths:i})).sort((s,i)=>i.paths.length-s.paths.length)}function jC(e){let t=Math.round(e/1e3);return t<60?`${t}s`:`${Math.floor(t/60)}m ${String(t%60).padStart(2,"0")}s`}async function nn(e,t,n=0,o){let r=$C(e.cwd,t,{allowUnreviewed:o?.skipReview===!0,allowStyleErrors:o?.skipStyle===!0});if(!r.clear){for(let c of vC(r,t.length,{act:"push"}))console.log(H(c));return{kind:"continue"}}let s={aborted:!1,partitions:0,failed:0,notRun:0,producedNothing:!0},i={retryable:0,stopped:!1,paths:[]},a=async(c,h)=>{let y=Date.now();console.log(u(h?`Resolving cross-links in ${c.length} article${c.length===1?"":"s"} whose targets published this run (second pass)\u2026`:`Pushing ${c.length} article${c.length===1?"":"s"} to Document360 (${SC} at a time)\u2026`));let x=await xC({cwd:e.cwd,...e.profileName?{profileName:e.profileName}:{},paths:c,...o?.allowUnpullable===!0?{allowUnpullable:!0}:{},onEvent:B=>{B.type==="article_done"?console.log(X(` \u2713 ${B.result.path}${B.result.action==="created"?" (new)":""}`)):B.type==="article_failed"&&console.log(L(` \u2717 ${B.failure.path}`))}});console.log("");let w=fd(e.cwd,c,e.profileName);h||(i={retryable:x.failed.filter(B=>!B.refused).length,stopped:!!x.stopped,paths:x.failed.map(B=>B.path)},s={aborted:x.aborted||!!x.stopped,partitions:gC(c).length,failed:x.failed.length,notRun:x.notRun.length,producedNothing:x.pushed.length===0,verifiedComplete:w>=c.length,leftBehind:n});let S=x.pushed.length>0;for(let B of md(x,{recorded:w,elapsedMs:Date.now()-y,docsRoot:PC(e.cwd),...h?{}:{conflictsSkipped:n,unreadableSkipped:o?.unreadableSkipped??0},...o?.scope?{scope:o.scope}:{}}))console.log(S&&x.failed.length===0?X(B):H(B));let P=x.aborted||!!x.stopped;if(!S)return P;let T=hd(e.cwd,e.profileName);T&&console.log(u(T));let R=Mr(e.cwd,e.profileName);if(R&&console.log(u(R)),P)return P;try{let B=Yy(await Vy({cwd:e.cwd,profileName:e.profileName,onRateLimit:G=>console.log(u(` Document360 rate limit \u2014 waiting ${Math.ceil(G.waitMs/1e3)}s\u2026`))}));B&&console.log(B.startsWith("\u26A0")?H(B):u(B))}catch{}try{let B=zy(await Ky({cwd:e.cwd,profileName:e.profileName}));B&&console.log(u(B))}catch{}let D=await Hs(e.cwd,e.profileName);return D&&console.log(u(D)),P};try{if(!await a(t,!1)){let h=await gd(e.cwd,e.profileName,t,i.paths);if(h.length>0&&await a(h,!0),tn(s))for(let y of Ke(e.cwd,o?.scope?`/push ${o.scope}`:"/push --all"))console.log(X(y))}}catch(c){console.log(L(`Push run failed: ${c.message}`))}if(console.log(""),i.retryable>0){let c=Ce("/push",o?.scope?"":"--all",o?.scope);return console.log(u(i.stopped?`Next: ${c} \u2014 your articles are unchanged, so it picks up where the run left off.`:`Next: ${c} \u2014 retries the ${i.retryable} article${i.retryable===1?"":"s"} that could not be saved.`)),{kind:"continue",ownNext:!0}}let l=pd(e.cwd,{scope:o?.scope,profileName:e.profileName});return l?(console.log(u(`Next: ${l.cmd} \u2014 ${l.reason}.`)),{kind:"continue",ownNext:!0}):{kind:"continue"}}async function tl(e,t,n){let o=yC(e,n);if(o.length===0)return[];let r=new Set(Bo((await Xa({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function gd(e,t,n,o=[]){try{let r=new Set(n),s=new Set(o),i=await Xa({cwd:e,profileName:t});return Bo(i.entries).map(a=>a.path).filter(a=>r.has(a)&&!s.has(a))}catch{return[]}}async function IC(e,t,n){try{let o=await RC({cwd:e,...t?{profileName:t}:{},relPath:n.replace(/\\/g,"/"),preview:!0});console.log(""),console.log(X(`${o.title}`)),console.log(u(`${o.path} \xB7 ${o.articleId?`updates article ${o.articleId}`:"would be created as a new article"}`)),o.shots.length>0&&console.log(u(`${o.shots.length} screenshot${o.shots.length===1?"":"s"} embedded: ${o.shots.map(r=>r.id).join(", ")}`)),o.missingShots.length>0&&console.log(H(`\u26A0 ${o.missingShots.length} screenshot${o.missingShots.length===1?"":"s"} not taken yet \u2014 the description publishes instead: ${o.missingShots.join(", ")}`)),console.log(u("\u2500".repeat(Math.min(80,Math.max(20,(process.stdout.columns??80)-1))))),console.log(o.body),console.log(u("\u2500".repeat(Math.min(80,Math.max(20,(process.stdout.columns??80)-1))))),console.log(u(`Nothing was sent. Run /push ${o.path} to save it as a draft.`))}catch(o){console.log(L(o.message))}return{kind:"continue"}}async function nl(e,t){let n=Ze(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(L(n.reason)),{kind:"continue"};let o=e.includes(_t),r=e.includes(CC);if(e.includes("--preview")){let i=e.find(a=>!a.startsWith("--"));return i?await IC(t?.cwd??process.cwd(),t?.profileName,i):(console.log(L("Which article? Use /push --preview <path> \u2014 a preview is per article.")),{kind:"continue"})}let s=e[0];if(e.includes("--screenshots")||e.includes("--shots")){let i=t?.cwd??process.cwd(),a=e.find(w=>!w.startsWith("--")),l=He(i),c=Wa(l,a);if(c.length===0){let w=l.filter(S=>S.state==="captured").length;return console.log(u(w>0?`${w} screenshot${w===1?" has":"s have"} been taken but the callouts aren't drawn on yet, so there is nothing to embed \u2014 /screenshot annotate finishes ${w===1?"it":"them"}.`:a?`No captured screenshots in ${a} \u2014 /push --screenshots covers the whole knowledge base.`:"No captured screenshots yet \u2014 /screenshot capture first.")),{kind:"continue"}}let h=Ba(l,a);h&&console.log(h);let y=Ha(l);y&&console.log(y);let x=Ce("","--screenshots",a).trim();return await nn(t??{cwd:process.cwd()},c,0,{skipReview:o,skipStyle:r,scope:x})}if(s==="--related"&&e[1]){if(!t)return{kind:"continue"};let i=await tl(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return i.length===0?(console.log(X("\u2713 All related articles are already on Document360.")),{kind:"continue"}):await nn(t,i,0,{skipReview:o,skipStyle:r,scope:`--related ${e[1]}`})}if(s==="--all"){console.log(u("Checking what needs pushing\u2026"));try{let i=await Xa({cwd:t?.cwd??process.cwd()}),a=new Set(Wo(t?.cwd??process.cwd(),t?.profileName)),{clean:l,conflicts:c}=Fo(i.entries,a),h=c.filter(P=>a.has(P.path)).length,y=Qa(i.entries),x=e.includes("--force"),w=x&&c.length>0;y>0&&console.log(H(`\u26A0 ${y} article(s) already exist on Document360 but aren't linked \u2014 left out (pushing would duplicate them). Run /catch-up or ask me to link them first.`)),c.length>0&&!w&&console.log(H(Bs(c.length,h)));let S=w?[...l,...c]:l;if(S.length===0){if(c.length>0){let T=Mr(t?.cwd??process.cwd(),t?.profileName);return T&&console.log(u(T)),console.log(u("Resolve the conflicts: /resolve")),{kind:"continue"}}console.log(X(y>0?"\u2713 Nothing else is ahead of Document360 to push.":"\u2713 Nothing is ahead of Document360 \u2014 nothing to push."));let P=Mr(t?.cwd??process.cwd(),t?.profileName);if(P&&console.log(u(P)),t)try{let T=Yy(await Vy({cwd:t.cwd,profileName:t.profileName,onRateLimit:D=>console.log(u(` Document360 rate limit \u2014 waiting ${Math.ceil(D.waitMs/1e3)}s\u2026`))}));T&&console.log(T.startsWith("\u26A0")?H(T):u(T));let R=zy(await Ky({cwd:t.cwd,profileName:t.profileName}));R&&console.log(u(R))}catch{}return{kind:"continue"}}return await nn(t??{cwd:process.cwd()},S.map(P=>P.path),w?0:c.length,{skipReview:o,skipStyle:r,allowUnpullable:x,unreadableSkipped:w?0:h})}catch(i){return console.log(L(`Could not compute sync status: ${i.message}`)),{kind:"continue"}}}if(s&&s.startsWith("--")&&(s=e.find(i=>!i.startsWith("--"))??""),!s){console.log(u("Checking what needs pushing\u2026"));let i,a=0,l=0;try{let c=await Xa({cwd:t?.cwd??process.cwd()}),h=new Set(Wo(t?.cwd??process.cwd(),t?.profileName)),{clean:y,conflicts:x}=Fo(c.entries,h);l=x.filter(S=>h.has(S.path)).length,i=y,a=x.length;let w=Qa(c.entries);if(w>0&&console.log(H(`\u26A0 ${w} article(s) already exist on Document360 but aren't linked \u2014 left out (pushing would duplicate them). Run /catch-up or ask me to link them first.`)),x.length>0&&console.log(H(Bs(x.length,l))),i.length===0&&x.length>0)return console.log(u("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(c){return console.log(L(`Could not compute sync status: ${c.message}`)),console.log(u("Push a specific article: /push <article-path>")),{kind:"continue"}}if(i.length===0)return console.log(X("\u2713 Nothing is ahead of Document360 \u2014 nothing to push.")),console.log(u(" (Articles without a sync base are unverified \u2014 push those by path if needed.)")),{kind:"continue"};if(!process.stdin.isTTY||!t){for(let c of i)console.log(` ${c.path} ${u(`(${c.label})`)}`);return console.log(u("Run: /push <article-path>")),{kind:"continue"}}try{s=await t.withPausedInput(()=>mC({message:"Push which article?",choices:[...i.length>1?[{name:`All ${i.length} candidates`,value:"--all",description:"one agent run over every candidate"}]:[],...i.map(c=>({name:c.path,value:c.path,description:c.label}))]}))}catch{return console.log(u("Cancelled.")),{kind:"continue"}}if(s==="--all")return await nn(t,i.map(c=>c.path),a,{skipReview:o,skipStyle:r,unreadableSkipped:l})}return await nn(t??{cwd:process.cwd()},[s],0,{skipReview:o,skipStyle:r,scope:s})}ae();import{select as _C}from"@inquirer/prompts";import{computeSyncStatus as UC,localAheadPaths as FC,pendingDrafts as WC,publishArticleLive as BC,publishGateVerdict as HC,publishGateLines as GC,blockedPaths as qC,placeholderRemedy as VC,resolveActiveProfile as YC,SKIP_STYLE_FLAG as KC,SKIP_SHOTS_FLAG as zC}from"document360-engine";import{gateFixTarget as LC}from"document360-engine";var wd=e=>"ruleId"in e,ol=e=>wd(e)?e.severity:"warning",Zn=e=>e===1?"":"s";function qs(e,t){let n=t??LC(e),o=n?` ${n}`:"";return e.unreviewed.length>0?`/review${o} --blocked --fix`:`/lint${o} --blocked --fix`}var yd=new Map;var OC=e=>wd(e)?e.fp||`${e.ruleId}:${e.path}:${e.line}:${e.term}`:`${e.kind}:${e.path}:${e.line}`;function Vs(e){let{cwd:t,after:n,scope:o,aborted:r,blocked:s}=e,i=n.filter(w=>ol(w)==="error").length,a=n.filter(w=>ol(w)==="warning").length,l=n.filter(w=>ol(w)==="suggestion").length,c=Ce("/lint","--blocked --fix",o);if(r){let w=Ce("/lint",s?"--blocked --fix":"--fix",o);return{text:`Stopped. Nothing else changed \u2014 ${w} picks up where this left off.`,cmd:w}}if(i>0){let w=n.filter(D=>ol(D)==="error"),S=new Set(w.map(D=>D.path)).size,P=`${t}::${o??""}`,T=w.map(OC).sort().join("|"),R=yd.get(P)===T;if(yd.set(P,T),R){let D=Ce("/lint","--blocked --full",o),B=[...new Set(w.filter(wd).map(G=>G.ruleId))];return{text:`The same ${i} error${Zn(i)} in ${S} article${Zn(S)} survived two ${c} passes, so a third would change nothing \u2014 ${i===1?"it needs":"they need"} a person. ${D} shows ${i===1?"it":"them"} in place. If ${B.length===1?`${B[0]} is`:"a rule is"} wrong for your product, switch it off in .d360-writer/config.json under "styleGuide": { "rules": { "<rule>": "off" } }.`,cmd:D}}return{text:`${i} error${Zn(i)} in ${S} article${Zn(S)} still block${i===1?"s":""} publishing. ${c} has another go at ${i===1?"it":"just those"} \u2014 if a second pass leaves the same ones, they need a human eye.`,cmd:c}}yd.delete(`${t}::${o??""}`);let h=a>0&&l>0?`${a} warning${Zn(a)} and ${l} suggestion${Zn(l)} remain (neither blocks publishing). `:a>0?`${a} warning${Zn(a)} remain${a===1?"s":""}, which ${a===1?"does":"do"} not block publishing. `:l>0?`${l} suggestion${Zn(l)} remain${l===1?"s":""} \u2014 ${l===1?"it is":"they are"} judgment calls and ${l===1?"does":"do"} not block publishing. `:"",y=h===""?"\u2713 Nothing left to fix. ":`\u2713 ${h}`,x=o?"/push":"/push --all";return Ut(t,{text:`${y}Nothing is blocking${o?` in ${o}`:""} \u2014 ${x} saves the articles to Document360 as drafts.`,cmd:x},y,o)}var MC={check:"/check is now /lint (same command)."};function rl(){return"That saves drafts rather than taking anything live, so running /push. (/publish takes saved drafts live.)"}var Jy=new Set;function Ys(e){let t=MC[e.replace(/^\//,"")];return!t||Jy.has(e)?null:(Jy.add(e),t)}var XC=400,QC=3e3,JC=e=>e>0?new Promise(t=>setTimeout(t,e)):Promise.resolve(),kd=e=>e===1?"":"s",bd=e=>e.replace(/\\/g,"/").split("/").pop()??e;function $d(e){return e.includes("--screenshots")||e.includes("--shots")||e[0]==="--related"}async function vd(e,t,n){await UC({cwd:e,profileName:t});let o=n?n.replace(/\\/g,"/").replace(/\/+$/,""):null;return WC(e,t).filter(r=>!o||r.path===o||r.path.startsWith(`${o}/`)).map(r=>({...r,label:ZC(e,r.path)}))}function ZC(e,t){let n=Na(e,t)??Ms(t),o=Ea(t),r=o?zn(o):"";return r?`${r} \u203A ${n}`:n}function eP(e){let t=Math.min(58,Math.max(...e.map(n=>n.label.length),20));return e.map(n=>` ${n.label.padEnd(t)} ${n.version?`draft v${n.version} \u2192 live`:"draft \u2192 live"}`)}function xd(e,t,n){let r=[`\u2713 Nothing is waiting to go live${n?` in ${n}`:""} \u2014 readers are seeing the latest version of every article.`],s=n?n.replace(/\\/g,"/").replace(/\/+$/,""):null,i=FC(e,t).filter(a=>!s||a===s||a.startsWith(`${s}/`)).length;return i>0&&r.push(`${i} article${kd(i)} ${i===1?"has":"have"} local edits that aren't on Document360 yet \u2014 that's /push${n?` ${n}`:""}.`),{lines:r,ahead:i}}function sl(e,t,n){let o=null;try{o=VC(e,t.placeholders)?.cmd??null}catch{}return{cmd:t.unreviewed.length>0||t.styleErrors.length>0?qs(t,n):o,shotFix:o}}function Rd(e,t,n,o){if(n)return null;let r=!1;try{r=YC(e,t).production}catch{return null}if(!r)return null;let s=o;return[`\u26A0 ${s} draft${s===1?"":"s"} ${s===1?"is":"are"} ready, and this is a PRODUCTION deployment.`," Nothing is blocking them \u2014 taking articles live here just needs authorizing once per session."," Run /allow-prod, then /publish."]}async function Sd(e,t,n,o={}){let r={published:[],blocked:[],failed:[]},s=0,i=XC,a=0;for(let l of n){o.onProgress?.(s,n.length,l.label);let c=await BC({onRateLimit:()=>{a+=1,i=Math.min(i*2,QC)},articleId:l.articleId,cwd:e,profileName:t,allowUnreviewed:o.skipReview===!0,allowStyleErrors:o.skipStyle===!0,allowProduction:o.allowProduction===!0});c.ok?r.published.push({path:l.path,...c.url?{url:c.url}:{}}):c.blocked?r.blocked.push({path:l.path,message:c.message,...c.commands.length>0?{commands:c.commands}:{}}):r.failed.push({path:l.path,message:c.error.message}),s+=1,s<n.length&&await JC(i)}return a>0&&(r.throttled={times:a,finalPacingMs:i}),r}function Cd(e){let{published:t,blocked:n,failed:o}=e,r=[];if(t.length>0){r.push(`\u2713 ${t.length} article${kd(t.length)} ${t.length===1?"is":"are"} now live \u2014 readers see ${t.length===1?"it":"them"} now.`);let s=t.filter(i=>i.url);for(let i of s.slice(0,3))r.push(` \u2B95 ${i.url}`);s.length>3&&r.push(` \u2B95 \u2026and ${s.length-3} more`)}if(n.length>0){let s=n.length>0&&n.every(i=>(i.commands??[]).includes("/allow-prod"));r.push(s?`\u2717 ${n.length} not published \u2014 this is a PRODUCTION deployment and this session is not authorized. Still ${n.length===1?"a draft":"drafts"}:`:`\u2717 ${n.length} refused by the publish gates \u2014 still ${n.length===1?"a draft":"drafts"}, nothing was lost:`);for(let i of n.slice(0,3))r.push(` \xB7 ${bd(i.path)}`);n.length>3&&r.push(` \xB7 \u2026and ${n.length-3} more`),r.push(s?" Run /allow-prod, then /publish.":" /status names what is blocking each one, and the command that clears it. It costs nothing.")}if(e.throttled){let s=(e.throttled.finalPacingMs/1e3).toFixed(1);r.push(`\u2139 Document360 asked us to slow down ${e.throttled.times} time${e.throttled.times===1?"":"s"}, so this run eased to ${s}s between articles.`)}if(o.length>0){r.push(`\u2717 ${o.length} failed \u2014 ${o.length===1?"it is":"they are"} still a draft, so re-running /publish retries ${o.length===1?"it":"them"}:`);for(let s of o.slice(0,3))r.push(` \xB7 ${bd(s.path)} \u2014 ${s.message}`);o.length>3&&r.push(` \xB7 \u2026and ${o.length-3} more`)}return r.length===0&&r.push("Nothing was published."),r}async function Zy(e,t){let n=t?.cwd??process.cwd();if($d(e))return console.log(u(`\u2192 ${rl()}`)),nl(e,t);let o=Ze(n,t?.profileName);if(!o.ok)return console.log(L(o.reason)),{kind:"continue"};let r=e.includes(_t),s=e.includes(KC),i=e.includes(zC),a=e.includes("--all"),l=e.find(R=>!R.startsWith("--"));console.log(u("Checking what is waiting to go live\u2026"));let c;try{c=await vd(n,t?.profileName,l)}catch(R){return console.log(L(`Could not check Document360: ${R.message}`)),{kind:"continue"}}if(c.length===0){for(let R of xd(n,t?.profileName,l).lines)console.log(R.startsWith("\u2713")?X(R):u(R));return{kind:"continue"}}let h=HC(n,c.map(R=>R.path),{allowUnreviewed:r,allowStyleErrors:s,checkScreenshots:!0,allowPlaceholders:i}),y=new Set(qC(h)),x=c.filter(R=>!y.has(R.path)),w=sl(n,h,l);if(y.size>0)for(let R of GC(h,c.length,{scope:l,act:"publish",going:x.length,shotFix:w.shotFix}))console.log(H(R));if(x.length===0)return w.cmd&&console.log(u(`Run: ${w.cmd}`)),{kind:"continue"};c=x,console.log(""),console.log(`${c.length} draft${kd(c.length)} ${c.length===1?"is":"are"} ahead of what readers see:`);for(let R of eP(c.slice(0,12)))console.log(u(R));c.length>12&&console.log(u(` \u2026and ${c.length-12} more`)),console.log("");let S=c;if(!a){let R=await _C({message:"Publish live to your readers?",choices:[{name:`Yes \u2014 publish all ${c.length} live`,value:"all"},...c.slice(0,8).map(D=>({name:`Just ${D.label}`,value:D.path})),{name:"No \u2014 leave them as drafts",value:"none"}]});if(R==="none")return console.log(u("Left as drafts. Nothing changed.")),{kind:"continue"};R!=="all"&&(S=c.filter(D=>D.path===R))}let P=Rd(n,t?.profileName,t?.allowProdWrites?.()===!0,S.length);if(P){for(let R of P)console.log(R.startsWith("\u26A0")?H(R):u(R));return{kind:"continue"}}let T=await Sd(n,t?.profileName,S,{skipReview:r,skipStyle:s,allowProduction:t?.allowProdWrites?.()===!0,onProgress:(R,D,B)=>console.log(u(` \u25B8 ${R+1}/${D} ${bd(B)}\u2026`))});console.log("");for(let R of Cd(T))console.log(R.startsWith("\u2713")?X(R):R.startsWith("\u2717")?H(R):u(R));return{kind:"continue"}}import{loadKnownConflicts as tP,localArticleTitle as nP,resolveActiveProfile as oP,surfaceCoverageSafe as ew,readProjectConfig as tw,recordDeclinedSurface as rP,areaExists as sP,declineTargets as nw}from"document360-engine";function iP(e,t){let n=nP(e,t);return n||(t.split(/[\\/]/).pop()??t).replace(/\.md$/,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ")}function il(e,t){let n=[];try{n=tP(e,oP(e,t).name)}catch{return null}if(n.length===0)return null;let o=n.length,r=n.slice(0,3).map(i=>iP(e,i)),s=o>3?`${r.join(", ")} and ${o-3} more`:r.join(", ");return{paths:n,note:`\u26A0 ${o} article${o===1?"":"s"} ${o===1?"has":"have"} been changed both here and on Document360 (${s}), so your local copy is not a reliable picture of what your readers have. An audit over it could tell you to write an article that already exists, or miss one that needs your decision \u2014 so it needs ${o===1?"that":"those"} settled first.`}}var _r={cmd:"/resolve",reason:"it walks each one with you \u2014 keep yours, take the portal's, or skip"};function al(e,t){let n=t.indexOf("--decline");if(n<0)return null;let o=t[n+1];if(!o||o.startsWith("--")){let a=ew(e,tw(e)),l=a.recognised?a.areas.slice(0,5).flatMap(c=>nw(c).map(h=>` /audit --decline ${h}`)):[];return["Name the path to decline \u2014 a folder, or a single file.",...l.length?["","No article covers these right now. Run one of these to settle it for good:",...l]:["","For example:"," /audit --decline src/internal-admin"]]}let r=o.replace(/\\/g,"/").replace(/\/+$/,"");if(!sP(e,r))return[`There is nothing at ${r}, so there is nothing to decline. Copy the path from /eval or /audit.`];let s=t.slice(n+2).filter(a=>!a.startsWith("--")).join(" ")||void 0;return rP(e,r,s)?[`\u2713 ${r} will not be reported as needing an article. /audit and /eval leave it out from now on, and say how many you have declined.`]:[`Could not write .d360-writer/declined-surfaces.json, so ${r} was not declined.`]}async function Ks(e){if(e?.cwd){let r=il(e.cwd,e.profileName);if(r)return{kind:"audit-blocked",note:r.note,lead:_r}}let t=e?.cwd?ew(e.cwd,tw(e.cwd)):null,n=[];if(t?.recognised&&t.areas.length>0){let r=t.areas.slice(0,15);n.push("","2.7. These parts of the product are cited by NO article's `sources:` frontmatter. This list is DETERMINISTIC and complete as of now \u2014 it does not depend on the diff window above, so treat it as authoritative rather than re-deriving it:",...r.map(s=>` - ${s.folder} (${s.files} of ${s.total} file${s.total===1?"":"s"} uncited, e.g. ${s.sample.join(", ")}) \u2014 to decline: ${nw(s).map(i=>`/audit --decline ${i}`).join(" \xB7 ")}`),...t.areas.length>r.length?[` \u2026and ${t.areas.length-r.length} more areas.`]:[]," EVERY row above must leave this run accounted for: a `create` row, or a stated reason it needs no article (internal-only, unreachable by a reader, already covered by an existing article's prose). Do NOT silently drop one \u2014 if you list fewer paths than this section handed you, say which you left out and why."," A `decline` verdict is not a record. For EVERY row you decline, print its exact /audit --decline line (copied from above \u2014 it already picks folder-or-file correctly) in the closing block, each on its own line so the terminal makes it a button. A judgement that leaves the turn as prose changes nothing and will be re-derived, at this price, on every future audit.",...t.declined>0?[` (${t.declined} more ${t.declined===1?"is":"are"} already declined and left out of that list.)`]:[])}return{kind:"forward-to-agent",prompt:["Run the gap-analysis skill against this repo.","","Follow its stages in order:","1. d360_sync_status first; stop if any article is changed in both places, or changed on Document360 and not yet pulled down (the local copy cannot be trusted until that is resolved). Say which articles, in plain words, never the internal status word \u2014 and tell the user to run /resolve, which walks the affected articles one at a time (keep the local copy, take the portal's, or skip). Do NOT ask them to report back to you: they will run /resolve and then /audit again.","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: the source agent's own notes on what it shipped. Verify each against the CURRENT code (its `sources` exist, and the code as it stands shows the surface it claims) before trusting it; never judge it by its `branch` or `commit`. Fold verified ones into the table, flag the rest.","2.6. Anything d360_pending_hints returns under `held` is NOT a proposal. Its cited code has uncommitted changes, so the builder is still writing that surface and has already been asked whether it is done. List each held item at the END of the table as a `waiting` row (Reason: the code behind it is not finished), do NOT propose create/update/retire for it, and do NOT stamp it consumed.",...n,"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, so backfill them.","4. Output the proposal table: | Article (path or proposed title) | Action (create | update | retire | link) | Reason | Evidence | Scope |. Leave every hint OPEN \u2014 this run proposes, it does not write articles, so nothing has been acted on yet.","5. End with the skill's closing block, and put NOTHING below it \u2014 no receipts, no roadmap confirmations, no feedback marker line, no summary. It ends in a question, and a question the user has to scroll back to find is one you did not really ask.","","Do not start writing or updating any article yet; the proposal table is the deliverable.","The audited-up-to marker is recorded for you when this command finishes. Read it to size the diff window; never write it, and never report it as a missing capability."].join(`
|
|
342
|
+
`),display:"/audit"}}ae();import{readProjectConfig as aP,writeProjectConfig as ow,autoBudgetUsd as lP,autoModeEnabled as cP,DEFAULT_AUTO_BUDGET_USD as uP}from"document360-engine";function ze(e){return`$${e%1===0?e.toFixed(0):e.toFixed(2)}`}function zs(e){return e?"I run the next step myself instead of waiting for you \u2014 writing, reviewing, checking style, saving and going live.":"I suggest the next step and wait for you to run it."}function Xs(e){let t=cP(e),n=lP(e),o=e.auto?.budgetUsd===void 0?" (the standard limit \u2014 nothing set for this repo)":"",r=[{tone:"info",text:`Mode: ${t?"auto":"manual"} \u2014 ${zs(t)}`}];return t?(r.push({tone:"info",text:`Spending limit: ${ze(n)} a run${o}. I stop and report when it is reached.`}),r.push({tone:"info",text:"Screenshots are never part of an automatic run \u2014 they need your product running."}),r.push({tone:"info",text:"Stop a run at any time: esc. Switch back to manual: shift+tab, or /auto off."})):r.push({tone:"info",text:`Turn it on: /auto on \xB7 or shift+tab. Spending limit if you do: ${ze(n)} a run.`}),r}function ll(e,t,n,o=new Date){let r={...t,auto:{...t.auto,enabled:n,decidedAt:o.toISOString()}};return ow(r,e),[n?{tone:"ok",text:V("\u2713")+"Auto mode ON \u2014 "+zs(!0)}:{tone:"ok",text:V("\u2713")+"Manual mode \u2014 "+zs(!1)},...Xs(r)]}function Td(e,t,n){if(!Number.isFinite(n)||n<=0)return null;let o={...t,auto:{...t.auto,enabled:t.auto?.enabled===!0,budgetUsd:n}};return ow(o,e),[{tone:"ok",text:V("\u2713")+`Spending limit set to ${ze(n)} a run.`},...Xs(o)]}function Ad(e){let t=e.findIndex(r=>r==="--budget"||r.startsWith("--budget="));if(t===-1)return{malformed:!1};let n=e[t].includes("=")?e[t].split("=").slice(1).join("="):e[t+1];if(n===void 0)return{malformed:!0};let o=Number(String(n).replace(/^\$/,"").replace(/,/g,""));return!Number.isFinite(o)||o<=0?{malformed:!0}:{usd:o,malformed:!1}}function Ed(e,t){let n=e.findIndex(o=>o==="--budget");return e.filter((o,r)=>!o.startsWith("--")&&!(n!==-1&&r===n+1)&&o!==String(t)).map(o=>o.trim().toLowerCase()).find(o=>o.length>0)}var Pd=e=>{for(let t of e)console.log(t.tone==="ok"?X(t.text):t.tone==="warn"?H(t.text):t.tone==="error"?L(t.text):u(t.text))};async function rw(e,t){let n=t.cwd,o=aP(n);if(!o)return console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=Ad(e);if(r.malformed)return console.log(L(`I could not read that spending limit. Give it as an amount, like: /auto --budget 150 (the standard limit is ${ze(uP)}).`)),{kind:"continue"};let s=Ed(e,r.usd);if(r.usd!==void 0&&!s){let i=Td(n,o,r.usd);return i&&Pd(i),{kind:"continue"}}if(!s||s==="status")return Pd(Xs(o)),{kind:"continue"};if(s==="on"||s==="off"){let i=r.usd!==void 0?{...o,auto:{...o.auto,enabled:o.auto?.enabled===!0,budgetUsd:r.usd}}:o;return Pd(ll(n,i,s==="on")),{kind:"continue"}}return console.log(L(`I don't know "${s}". Use: /auto on \xB7 /auto off \xB7 /auto status \xB7 /auto --budget <amount>`)),{kind:"continue"}}ae();import{readProjectConfig as dP}from"document360-engine";function Nd(){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: 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, with every claim cited to its grounding, 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;'," 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(`
|
|
343
|
+
`)}async function sw(e,t){let n=t?.cwd??process.cwd();return dP(n)?{kind:"forward-to-agent",prompt:Nd(),display:"/discover"}:(console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"})}ae();import{checkbox as pP}from"@inquirer/prompts";import{inventoryRepo as hP,readProjectConfig as iw,writeProjectConfig as fP}from"document360-engine";function Dd(e,t){let n=iw(e);n&&(n.authoritativeSourceFiles=t,fP(n,e))}function cl(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 aw(e,t){let n=t?.cwd??process.cwd();if(!iw(n))return console.log(L("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=hP(n);if(o.length===0)return console.log(u('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(Z("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${u(cl(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>pP({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${cl(s)})`,value:s.path,checked:s.recommended})),pageSize:20}))}catch{return console.log(u("Cancelled.")),{kind:"continue"}}if(r.length===0)return console.log(u("Nothing selected \u2014 scope unchanged.")),{kind:"continue"};Dd(n,r),console.log(X(`\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"}}ae();import{confirm as CP}from"@inquirer/prompts";import{applyPull as Od,computeSyncStatus as bw,compareRemoteSources as PP,planPull as kw,planImport as TP,applyImport as AP,establishBaselines as EP,rebaselineServerMeta as NP,D360AuthError as DP}from"document360-engine";ae();var lw=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /push <path>):",paint:L,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /push <path>:",paint:H,mark:"M"},{status:"remote-ahead",header:"Changed on Document360 \u2014 pull with /pull <path> (or just /pull):",paint:Z,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:L,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:L,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint:Ae,mark:"X"},{status:"untracked-local",header:"New here \u2014 not on Document360 yet (publish to add them):",paint:u,mark:"?"},{status:"untracked-remote",header:"On Document360 \u2014 not in your local docs yet (run /pull to import them):",paint:u,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:Ae,mark:"\xB7"}];function mP(e){return e.path?e.path:`${e.title??"(untitled)"} ${Ae(`[${e.articleId}]`)}`}function gP(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 ul(e,t){let n=[],o=e.entries.filter(h=>h.link);if(o.length>0){n.push(""),n.push(Je("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let h of o)n.push(` ${H("~")} ${H(h.path??"")} ${Ae(`\u2192 "${h.link.title}"`)}`)}for(let h of lw){let y=e.entries.filter(x=>x.status===h.status&&!(h.status==="untracked-local"&&x.link));if(y.length!==0){n.push(""),n.push(Je(h.header));for(let x of y)n.push(` ${h.paint(h.mark)} ${h.paint(mP(x))}${x.detail?Ae(` (${x.detail})`):""}`)}}let r=e.counts["in-sync"]??0,s=e.entries.length;n.push("");let i={"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"},a=o.length,l=s===r?X("\u2713 everything up to date"):[r>0?X(`\u2713 ${r} up to date`):null,a>0?`${a} to link`:null,...lw.map(h=>{let y=(e.counts[h.status]??0)-(h.status==="untracked-local"?a:0);return y>0?`${y} ${i[h.status]}`:null})].filter(Boolean).join(Ae(" \xB7 ")),c=t!==void 0?` \xB7 synced in ${gP(t)}`:"";return n.push(l+Ae(` \xB7 ${s} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${c}`)),n}import{structuredPatch as yP}from"diff";import cw from"picocolors";var wP=80,Ur=400,bP="\x1B[48;2;74;28;28m",kP="\x1B[48;2;24;66;24m",uw="\x1B[49m",jd=e=>String(e).padStart(5);function dw(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}function pw(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 Ft(e,t,n,o=wP){let r=S=>{let P=S.replace(/\r\n/g,`
|
|
344
344
|
`);return P.endsWith(`
|
|
345
345
|
`)||P===""?P:P+`
|
|
346
|
-
`},s=r(e),i=r(t);if(s===i)return null;let a=Math.max(20,n-10),l=cP("a","b",s,i,"","",{context:3}),c=0,h=0,y=[];l.hunks.forEach((S,P)=>{P>0&&y.push(sw.gray(" \u2026"));let T=S.oldStart,R=S.newStart,N=[],B=[],G=()=>{for(let Q=0;Q<N.length;Q++){let j=Q<B.length?aw(N[Q],B[Q]):void 0;h++,y.push(`${dP}${Dd(T++)} - ${lw(N[Q],a,j)}${iw}`)}for(let Q=0;Q<B.length;Q++){let j=Q<N.length?aw(N[Q],B[Q]):void 0;c++,y.push(`${pP}${Dd(R++)} + ${lw(B[Q],a,j)}${iw}`)}N=[],B=[]};for(let Q of S.lines){let j=Q[0],ne=Q.slice(1);j==="-"?N.push(ne):j==="+"?B.push(ne):(G(),y.push(sw.gray(Dd(R))+" "+ne.slice(0,a)),T++,R++)}G()});let x=Math.max(1,o),w=y.slice(0,x);return{added:c,removed:h,lines:w,hidden:Math.max(0,y.length-x)}}import{select as pw}from"@inquirer/prompts";import{applyPull as hw,computeSyncStatus as mP,isPullWouldBlankError as uw,localArticleTitle as gP,planPull as dw}from"document360-engine";import{listUnpullable as hP,resolveActiveProfile as fP}from"document360-engine";function ul(e,t,n,o){let r=n.filter(a=>a.status==="conflict"&&a.path).map(a=>a.path),s=new Set(o),i=[];try{i=hP(e,fP(e,t).name).map(a=>a.path).filter(a=>s.has(a))}catch{}return[...new Set([...r,...i])].sort()}function dl(){return["Document360 will not give this article back as markdown \u2014 it is not on the Markdown (Editor 3.0) editor, so there is no portal copy to show you or to take.","Your local copy is intact, and publishing it over the portal settles this. Skipping leaves the article flagged, and it will be waiting again next time."]}function pl(){return"Publish your copy over the portal (settles it) \xB7 Skip?"}function cw(){return"(l publish yours \xB7 s skip \u2014 anything else stops, keeping your answers so far)"}function hl(e){if(e.length===0)return[];let t=e.length,n=e.slice(0,3).join(", ")+(t>3?`, +${t-3} more`:"");return[`${t} article${t===1?"":"s"} stay${t===1?"s":""} flagged \u2014 Document360 cannot hand ${t===1?"its":"their"} markdown back: ${n}`,"Two ways out: run /resolve and press l to publish your copy over the portal, or ask your Document360 admin to move the article back to the Markdown (Editor 3.0) editor, then run /resolve again."]}function jd(e){return`Cannot take the portal copy of ${e} \u2014 Document360 will not return it as markdown. Left as it was.`}ie();var fl=e=>e===1?"":"s";async function Id(e,t,n=1){console.log(""),console.log(`${Z("\u25CF")} ${Qe(t.title)} ${Ae(`(${t.path})`)}`);for(let i of t.notes)console.log(H(` \u26A0 ${i}`));let o=Mt(t.oldContent,t.newContent,Math.max(40,(process.stdout.columns??80)-1),_r);if(o){console.log(Ae(` \u23BF local \u2192 portal: +${o.added} / -${o.removed} line${fl(o.added+o.removed)}`));for(let i of o.lines)console.log(i);o.hidden>0&&console.log(u(` \u2026 +${o.hidden} more diff lines`))}else console.log(u(" Local already matches the portal content \u2014 resolving just advances the sync base."));let r=n>1,s=await e.withPausedInput(()=>pw({message:`Conflict \u2014 ${t.path}${r?` (${n} left)`:""}`,choices:[{name:"Keep local (publish \u2014 overwrites the portal edit)",value:"local"},{name:"Take portal (overwrites your local edits)",value:"portal"},{name:"Skip (leave it a conflict)",value:"skip"},...r?[{name:`Keep local for ALL ${n} remaining`,value:"local-all"},{name:`Take portal for ALL ${n} remaining`,value:"portal-all"},{name:`Skip ALL ${n} remaining`,value:"skip-all"}]:[]]})).catch(()=>"skip");return s==="portal"?(hw({cwd:e.cwd,profileName:e.profileName},t),console.log(X(" \u2713 Took the portal copy (local overwritten, sync base advanced).")),"took-portal"):s==="local"?"keep-local":s==="skip"?(console.log(u(" Skipped \u2014 still a conflict.")),"skipped"):s==="local-all"?"keep-local-all":s==="portal-all"?"took-portal-all":"skipped-all"}async function yP(e,t){console.log(""),console.log(`${Z("\u25CF")} ${Qe(gP(e.cwd,t)??t)} ${Ae(`(${t})`)}`);for(let o of dl())console.log(H(` \u26A0 ${o}`));return await e.withPausedInput(()=>pw({message:pl(),choices:[{name:"Publish your copy over the portal (settles it)",value:"local"},{name:"Skip (leave it a conflict)",value:"skip"}]})).catch(()=>"skip")==="local"?"keep-local":(console.log(u(" Skipped \u2014 still a conflict.")),"skipped")}async function fw(e,t){let n=Je(t.cwd,t.profileName);if(!n.ok)return console.log(L(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let r=await mP({cwd:t.cwd,profileName:t.profileName}),s=ul(t.cwd,t.profileName,r.entries,Wo(r.entries).map(l=>l.path));if(o){if(!s.includes(o))return console.log(X(`${o} isn't waiting on a decision \u2014 nothing to resolve.`)),{kind:"continue"};s=[o]}if(s.length===0)return console.log(X("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let i=[],a=[];for(let[l,c]of s.entries()){let h;try{h=await dw({cwd:t.cwd,profileName:t.profileName,relPath:c})}catch(w){if(!uw(w))throw w;await yP(t,c)==="keep-local"?i.push(c):a.push(c);continue}let y=await Id(t,h,s.length-l);if(y==="keep-local"&&i.push(c),!y.endsWith("-all"))continue;let x=s.slice(l);if(y==="keep-local-all")i.push(...x),console.log(u(` Keeping local for all ${x.length} \u2014 publishing them over the portal.`));else if(y==="took-portal-all"){let w=0;for(let S of x)try{hw({cwd:t.cwd,profileName:t.profileName},await dw({cwd:t.cwd,profileName:t.profileName,relPath:S})),w++}catch(P){console.log(L(` \u2717 ${S}: ${P.message}`)),uw(P)&&a.push(S)}console.log(X(` \u2713 Took the portal copy of ${w} article${fl(w)} (local overwritten, sync base advanced).`))}else console.log(u(` Skipped all ${x.length} \u2014 still conflict${fl(x.length)}.`));break}for(let l of hl(a))console.log(H(`\u26A0 ${l}`));if(i.length>0)return console.log(u(`Publishing ${i.length} kept-local article${fl(i.length)} over the portal\u2026`)),await Zt(t,i,0,{allowUnpullable:!0})}catch(r){console.log(L(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function yw(e,t){let n=Je(t.cwd,t.profileName);if(!n.ok)return console.log(L(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await SP(t),{kind:"continue"};if(o==="--baseline")return await CP(t,e.filter(i=>i!=="--baseline")),{kind:"continue"};if(o==="--compare")return await PP(t),{kind:"continue"};if(o)return console.log(L(`Unknown option: ${o}`)),console.log(u("Usage: /pull pull portal edits + import new portal articles")),console.log(u(" /pull <path> pull one article (or resolve a conflict)")),console.log(u(" /pull --status drift report only (no writes)")),console.log(u(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await TP(t,r),{kind:"continue"};console.log(u("Pulling changes from Document360\u2026"));let s=await Od({cwd:t.cwd,profileName:t.profileName});for(let i of Md(s))console.log(i.tone==="ok"?X(i.text):i.tone==="warn"?H(i.text):u(i.text));console.log("")}catch(r){r instanceof RP?console.log(L(r.message)):console.log(L(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function Od(e){let t=await mw({cwd:e.cwd,profileName:e.profileName}),n={pulled:[],imported:[],conflicts:[],toPublish:0,failed:[]};for(let o of t.entries)if(o.status==="remote-ahead"&&o.path)try{let r=await gw({cwd:e.cwd,profileName:e.profileName,relPath:o.path});Ld({cwd:e.cwd,profileName:e.profileName},r),n.pulled.push(o.path)}catch(r){n.failed.push({ref:o.path,error:r.message})}else if(o.status==="untracked-remote"&&o.articleId)try{let r=await kP({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId,...o.remoteCategory?{categoryPath:o.remoteCategory.path}:{}});$P({cwd:e.cwd,profileName:e.profileName},r),n.imported.push({title:r.title,path:r.path})}catch(r){n.failed.push({ref:o.title??o.articleId,error:r.message})}else o.status==="conflict"&&o.path?n.conflicts.push(o.path):(o.status==="local-ahead"||o.status==="untracked-local"&&!o.link)&&o.path&&n.toPublish++;return n}var ml=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Bo=e=>e===1?"":"s";function Md(e){let t=[];if(e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${Bo(e.pulled.length)} into local: ${ml(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${Bo(e.imported.length)}: ${ml(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${Bo(e.toPublish)} changed locally \u2014 /push saves them to Document360.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${Bo(e.conflicts.length)} changed both here and on Document360 \u2014 left untouched. Resolve them: /resolve (or /push <path> to keep yours, /pull <path> to take the portal's). (${ml(e.conflicts)})`}),e.failed.length){t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${Bo(e.failed.length)} could not be imported.`});let n=new Map;for(let o of e.failed){let r=o.error.replace(/^"[^"]*" could not be imported: /,"");n.set(r,[...n.get(r)??[],o.ref])}for(let[o,r]of n)t.push({tone:"warn",text:` ${o}`}),t.push({tone:"warn",text:` ${ml(r)}`})}return t.length===0&&t.push({tone:"ok",text:"\u2713 Already in sync with Document360 \u2014 nothing to pull."}),t}async function SP(e){console.log(u("Checking Document360 for drift\u2026"));let t=Date.now(),n=await mw({cwd:e.cwd,profileName:e.profileName});for(let o of cl(n,Date.now()-t))console.log(o);console.log("")}async function CP(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(u(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await vP({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await xP({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(X("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(X(`\u2713 Recorded ${o.baselined.length} article(s) as matching Document360 \u2014 they read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(X(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(H(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(u(` - ${s.path} (${s.reason})`))}}async function PP(e){console.log(u("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await bP({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${Qe(String(t.legacyCount))} \xB7 Manifest: ${Qe(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(X("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(L(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(H(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(H(` ${t.onlyInManifest.length} only in the manifest: ${t.onlyInManifest.slice(0,5).join(", ")}`)),console.log(u(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function TP(e,t){let n=t.replace(/\\/g,"/"),o=await gw({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await Id(e,o)==="keep-local"&&(console.log(u(`Publishing ${o.path} over the portal\u2026`)),await Zt(e,[o.path]));return}console.log(""),console.log(`${Z("\u25CF")} ${Qe(o.title)} ${Ae(`(${o.path})`)}`);for(let i of o.notes)console.log(H(` \u26A0 ${i}`));let r=Mt(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1),_r);if(!r){console.log(u(" Local file already matches the remote content \u2014 advancing the sync base only.")),Ld({cwd:e.cwd,profileName:e.profileName},o);return}console.log(Ae(` \u23BF Added ${r.added} line${Bo(r.added)}, removed ${r.removed} line${Bo(r.removed)}`));for(let i of r.lines)console.log(i);if(r.hidden>0&&console.log(u(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>wP({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(u(" Skipped."));return}Ld({cwd:e.cwd,profileName:e.profileName},o),console.log(X(` \u2713 Pulled ${o.path} (sync base advanced).`))}ie();import{statSync as UP}from"node:fs";import{resolve as FP}from"node:path";import{estimateBulkCost as WP,planPartitions as BP,readProjectConfig as HP,resolveModelForOperation as GP,runPartitioned as qP,trackedArticlePaths as VP}from"document360-engine";function Jn(e,t){return e.aborted?null:e.blocked?[`\u2717 ${t} didn\u2019t start \u2014 ${e.blocked}.`,"Nothing was changed. Fix that, then re-run."]:e.allEmpty?[`\u2717 ${t} did nothing \u2014 every batch produced no output, so no agent actually ran.`,"Run /doctor \u2014 it runs a real turn with your skills and tools and reports what failed. /logs shows Claude Code\u2019s own error, which was recorded either way, and offers to copy it.","A Claude usage or session limit also does this, and it ends every turn instantly \u2014 if you have just hit one, wait for the reset and re-run."]:null}function ww(e){return!e.bailedEmpty||!e.notRun?null:`\u26A0 Stopped early \u2014 ${e.notRun} batch${e.notRun===1?" was":"es were"} not attempted, because two in a row produced no output (that is systemic, not this work: usually a Claude usage limit). Re-run to finish the rest; anything already done is skipped.`}var Ur=class{activeMs=0;last=0;timer=null;startedAt=0;stopped=null;start(t=Date.now()){this.timer||(this.startedAt=t,this.last=t,this.timer=setInterval(()=>this.tick(),1e3),this.timer.unref?.())}tick(t=Date.now()){let n=t-this.last;this.last=t,!(n<=0)&&(this.activeMs+=Math.min(n,5e3))}stop(t=Date.now()){return this.stopped?this.stopped:(this.timer&&(clearInterval(this.timer),this.timer=null),this.tick(t),this.stopped={activeSeconds:Math.max(0,Math.round(this.activeMs/1e3)),elapsedSeconds:Math.max(0,Math.round((t-this.startedAt)/1e3))},this.stopped)}};function gl(e,t){let n=t-e;return n>=300&&n>=t*.2}function _t(e,t,n,o=Date.now(),r){let s=t.reduce((a,l)=>a+(l.inputTokens??0),0),i=t.reduce((a,l)=>a+(l.cacheReadTokens??0),0);return{seconds:Math.max(0,Math.round((o-e)/1e3)),outputTokens:t.reduce((a,l)=>a+l.outputTokens,0),inputTokens:s,...s>0?{cachedPct:Math.round(i/s*100)}:{},...r!==void 0?{activeSeconds:r}:{},costUsd:n}}function yl(e){return e.activeSeconds!==void 0&&gl(e.activeSeconds,e.seconds)?`${_d(e.seconds)} elapsed \xB7 ${_d(e.activeSeconds)} working`:_d(e.seconds)}var bw=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:`${e}`,_d=e=>{if(e<60)return`${e}s`;let t=Math.floor(e/60);return t<60?`${t}m ${e%60}s`:`${Math.floor(t/60)}h ${t%60}m`};function un(e){let t=e.cachedPct!==void 0?`, ${e.cachedPct}% cached`:"",n=e.costUsd>0?`, this turn ${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"";return` (took ${yl(e)}, ${bw(e.inputTokens)}\u2192${bw(e.outputTokens)} tokens${t}${n})`}import xe from"picocolors";import Bd from"wrap-ansi";import Hd from"string-width";ie();import Zn from"picocolors";import bl from"wrap-ansi";import wl from"string-width";var Ho=[{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>] [--push]",desc:"Document a shipped change \u2014 the agent picks the action (new section/article/update); bare: act on builder requests. --push then saves the result to Document360 as drafts, which still needs an editorial review first",group:"docs"},{name:"write",usage:"/write [--preview|--scope <cat>|<path>] [--rewrite] [--concurrency N] [--skip-style]",desc:"Write the planned articles in parallel (starts immediately; --preview shows plan + cost first; --rewrite regenerates already-written articles; --concurrency default 3). Anything that would block publishing is corrected in one automatic pass before the run finishes; --skip-style leaves it to /lint",group:"docs"},{name:"screenshot",usage:"/screenshot [author|capture|annotate|verify|checklist|list] [id|path|--all|--failed|--blocked]",desc:"Screenshots, one family \u2014 bare: pick what to do; author: write capture specs; capture: take the shots (--all re-shoots everything; --failed re-runs the ones that did not work; --blocked re-runs the ones waiting on app data); annotate: draw the callouts on shots already taken, no browser needed (--all --force re-draws after a wording or style change); verify: judge the finished pictures and mark them verified (both run automatically after a capture); 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:"push",usage:"/push [path|--all|--related <path>|[<category>] --screenshots] [--preview] [--skip-review]",desc:"Save your articles to Document360 as drafts \u2014 readers don't see them until /publish (no arg: pick; --all: every candidate; --screenshots: re-save articles with captured shots so images embed, optionally narrowed to one category; --related <path>: also save that article's related articles that were never saved; --preview <path>: show exactly what would be sent, and send nothing). Blocked until each article has had /review --fix \u2014 AI-written text gets an editor first; --skip-review overrides deliberately",group:"publish"},{name:"publish",usage:"/publish [path|<category>|--all] [--skip-review]",desc:"Take the drafts on Document360 LIVE to your readers (the portal's own Publish). Always lists what would become visible and asks first; no arg or a category narrows it. Needs an editorial review \u2014 /review --blocked --fix",group:"publish"},{name:"style-guide",usage:"/style-guide [list | use [<preset>] | keep | sweep [skip] | pull [<n>] | learn | compile | explain <rule>]",desc:"Choose the writing rules your docs are held to. Bare: what is active now; list: every pack you can turn on; use: switch packs, hold every article to them and apply the free text swaps (bare: pick from a list); keep: settle on the rules you have today; sweep: how much of your knowledge base still needs reading against a guide you switched to (skip stops me raising it); pull: bring your Document360 project's own style guide down; learn: turn what your reviewers keep asking for into standing rules; compile: turn its mechanical statements into checks; explain: what one rule means and how to silence it",group:"docs"},{name:"lint",usage:"/lint [<category|path>] [--blocked] [--fix] [--full] [--baselined]",desc:"Lint the docs against the house rules: leaked internals, invented commands, stale facts, AI-tells, em dashes, callout shape (deterministic, no tokens). Every finding names the rule that produced it. Scope to a category/path; --blocked narrows to the errors that block publishing and leaves warnings and suggestions alone; --fix has the agent correct them in place; --full lists every finding instead of a capped summary; --baselined shows the issues that were already in your articles when you chose this style guide, which never block publishing",group:"docs"},{name:"review",usage:"/review [<category|path> | --all | --blocked | --stale] [--fix]",desc:"Independent senior-editor review: style guide, terminology/voice, grammar/clarity, page structure, improvement suggestions. A whole-knowledge-base run also gets one editor on the SHAPE of the docs \u2014 reading order, categories that have grown too big, articles filed in the wrong place, names that no longer fit. Bare: pick a category or everything; --blocked reads only the articles publishing is blocked on; --stale reads the ones the current editor has not read yet, so running it twice costs nothing; --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 /push",group:"docs"},{name:"restructure",usage:"/restructure [<what to change>]",desc:"Reshape the knowledge base: move an article to a different category, split one that has grown too big, merge two, rename one, or nest one inside another. A category left empty by a merge is hidden from readers, never deleted. Bare: reviews how the docs are organized and reports what should change, without touching anything; the changes reach Document360 on the next /push",group:"docs"},{name:"structure",usage:"/structure",desc:"Show the documentation reading order (categories \u2192 articles) as it will appear on Document360",group:"docs"},{name:"status",usage:"/status [--all]",desc:'What stands between your work and your readers, before you spend anything: which articles no editor has read, which break a style rule your config makes blocking, which would show "[Screenshot: \u2026]" text to a reader, which are in conflict with the portal, and which are saved as drafts readers cannot see yet. Each group names the one command that clears it. Reads local files and the last sync \u2014 no network, no tokens. --all lists every article gate by gate',group:"publish"},{name:"retire",usage:"/retire [<path>] [--yes]",desc:"Take an article off your readers on Document360 \u2014 it stops being visible, and nothing offers to publish it again. Nothing is deleted: the article, its version history and every reviewer comment stay. Bare: lists what is worth retiring (articles on Document360 that are no longer in your docs folder). /push puts one back \u2014 reviving is a publish like any other",group:"publish"},{name:"untrack",usage:"/untrack [<path>] [--undo] [--list] [--yes]",desc:"Disown a page that was imported from Document360 but is not one of your docs. /catch-up and /pull import every article they find in your categories; this records the ones you do not want, so they are never imported again \u2014 and the decision travels with the repo, so a teammate\u2019s clone inherits it. Nothing on Document360 changes and nothing is deleted: the markdown moves to .d360-writer/declined/. Bare: lists what this repo has declined. --undo puts one back",group:"publish"},{name:"reuse",usage:'/reuse [pull | add <variable|snippet> <name> "<value>" | audit [<category>] [--create <n\u2026>]]',desc:"The terms, values and blocks your project already maintains on Document360, so your articles reference them instead of repeating them. A variable holds a value like your product name in one place \u2014 change it there and every article changes; type it out by hand and /lint flags it. A snippet does the same for a whole block, and the writer references yours by name instead of writing its own version. A term is defined once and every article is checked for explaining it the first time it appears. Reading is free; pull refreshes from Document360, add creates a new one there, and audit reads every article to work out what belongs in one place",group:"docs"},{name:"eval",usage:"/eval [<category>] [--all]",desc:"How does your whole knowledge base score? Reads every article and reports what no single-article check can see: internal links written as portal URLs, links pointing at headings that no longer exist, link text that names a different article, the command summary line appearing in several shapes, two names for the same section, and how many style findings were accepted as exempt when you chose your style guide. Costs nothing and calls nothing",group:"docs"},{name:"terms",usage:'/terms [<category>] [--all] [--approve "<term>"]',desc:"Is your knowledge base calling the same thing by the same name? Reads every article and reports terms spelled more than one way, short names that may be the long name abbreviated, and article titles out of step with the rest of their kind \u2014 the consistency an editor reading three articles at a time cannot see. Costs nothing and calls nothing. --approve records a spelling as the approved one, so every later run enforces it",group:"docs"},{name:"roadmap",usage:"/roadmap [--all | done [step]]",desc:"Show the docs campaign (the multi-session plan the agent maintains), grouped by the part of the job \u2014 progress + next step; `--all` also lists the steps a later pass replaced; `done` marks the next open step finished (add words from a title to pick another)",group:"docs"},{name:"audit",usage:"/audit [--auto on|off] [--decline <path>]",desc:"Gap analysis: code vs docs vs Document360 (what changed); --auto runs it at launch when code changed; --decline settles a folder or file that needs no article",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:"ask",usage:"/ask <question>",desc:"Ask your developers something the code cannot tell you: why a feature exists, when to use it, whether it can be undone",group:"publish"},{name:"share",usage:"/share [status|on|off]",desc:"Share your docs work with the team: get your builder's latest, then save + send yours (runs automatically; `off` leaves it to your coding agent)",group:"publish"},{name:"catch-up",usage:"/catch-up [--push] [--include-unfinished]",desc:"Process ALL pending work (builder hints + requests + Document360 portal drift) \u2192 write \u2192 save to Document360 as drafts. --push does that last step for you, which still needs an editorial review first. A note whose code your builder has not committed is left for later, and they are asked whether it is done; --include-unfinished writes those pages anyway. For code changes, that's /audit",group:"publish"},{name:"comments",usage:"/comments [<article>] [--scope <category>] [--answer] [--all] [--resolve] [--answered] [--full]",desc:"Reviewer comments left on passages of your articles in the Document360 portal \u2014 bare: a table by article, pick a number to read its comments in full, then answer or go back; --answer: fix, push the draft, reply (threads stay open unless you add --resolve); --full re-reads every article",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 (push), take portal (pull), or skip \u2014 per article, or one answer for all remaining. 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:"Where this repo publishes \u2014 switch, or connect another environment (picker; s = session)",group:"setup"},{name:"workspace",usage:"/workspace [name]",desc:"Switch the Document360 workspace (picker)",group:"setup"},{name:"auto",usage:"/auto [on|off|status] [--budget <amount>]",desc:"Auto or manual: in auto I run the next step myself \u2014 write, review, check style, save, go live \u2014 instead of waiting for you (shift+tab cycles it; esc stops a run)",group:"setup"},{name:"model",usage:"/model [name|default]",desc:"Set the Claude model for d360-writer",group:"setup"},{name:"verbose",usage:"/verbose [on|off]",desc:"Show the raw transcript \u2014 every tool call with its file path and full result, instead of article-shaped cards with my bookkeeping collapsed (bare: toggle)",group:"setup"},{name:"logout",usage:"/logout [--all-projects]",desc:"Sign out of this project + clear its workspace selection (then /login to re-pick)",group:"setup"},{name:"allow-prod",usage:"/allow-prod",desc:"Authorize taking articles live on a production profile",group:"setup"},{name:"env",usage:"/env [add <file.json>|remove <name>]",desc:"The Document360 deployments this machine can reach \u2014 and add one this build does not ship",group:"setup"},{name:"doctor",usage:"/doctor",desc:"Health-check: auth, profile, workspace, map, API, and a real agent turn",group:"setup"},{name:"logs",usage:"/logs",desc:"Show the most recent problem d360-writer recorded, and where the logs are \u2014 press c to copy it for the team",group:"setup"},{name:"update",usage:"/update",desc:"Update d360-writer \u2014 and d360-capture when installed \u2014 to the latest versions",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"}],kw={"/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","/push":"save your articles to Document360 as drafts","/publish":"take the signed-off drafts live to your readers","/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, draw the callouts)","/doctor":"run a health check","/logs":"show the last problem, and copy it for the team","/auto":"choose whether I run the next step myself or wait for you","/style-guide":"choose the writing rules your docs are held to","/lint":"check the docs against those rules (costs nothing)"};function $w(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(kw[n])return kw[n];let o=Ho.find(r=>r.name===t);return o?o.desc:""}function vw(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return Ho.filter(n=>n.name.startsWith(t))}function xw(e){let t=0,n="";for(let o of e){if(o==="["){t++;continue}if(o==="]"){t=Math.max(0,t-1);continue}t===0&&(n+=o)}return/<[^>]+>/.test(n)}var AP=new RegExp(`^\\s*/(?:${Ho.map(e=>e.name).join("|")})(?:\\s|$)`),Rw=e=>AP.test(e),Sw=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Cw=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),Pw=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function EP(e){let t=e.replace(/\r/g,"").split(`
|
|
347
|
-
`),n=[],o=0;for(;o<t.length;){let r=t[o];if(/^\s*```/.test(r)){let a=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)a.push(t[o++]);o++,n.push({kind:"code",lines:a});continue}if(
|
|
348
|
-
`).map(R=>
|
|
349
|
-
`)?
|
|
350
|
-
`).flatMap(
|
|
351
|
-
`)):
|
|
352
|
-
`)}),B=Math.max(...
|
|
346
|
+
`},s=r(e),i=r(t);if(s===i)return null;let a=Math.max(20,n-10),l=yP("a","b",s,i,"","",{context:3}),c=0,h=0,y=[];l.hunks.forEach((S,P)=>{P>0&&y.push(cw.gray(" \u2026"));let T=S.oldStart,R=S.newStart,D=[],B=[],G=()=>{for(let Q=0;Q<D.length;Q++){let N=Q<B.length?dw(D[Q],B[Q]):void 0;h++,y.push(`${bP}${jd(T++)} - ${pw(D[Q],a,N)}${uw}`)}for(let Q=0;Q<B.length;Q++){let N=Q<D.length?dw(D[Q],B[Q]):void 0;c++,y.push(`${kP}${jd(R++)} + ${pw(B[Q],a,N)}${uw}`)}D=[],B=[]};for(let Q of S.lines){let N=Q[0],ne=Q.slice(1);N==="-"?D.push(ne):N==="+"?B.push(ne):(G(),y.push(cw.gray(jd(R))+" "+ne.slice(0,a)),T++,R++)}G()});let x=Math.max(1,o),w=y.slice(0,x);return{added:c,removed:h,lines:w,hidden:Math.max(0,y.length-x)}}import{select as gw}from"@inquirer/prompts";import{applyPull as yw,computeSyncStatus as xP,isPullWouldBlankError as fw,localArticleTitle as RP,planPull as mw}from"document360-engine";import{listUnpullable as $P,resolveActiveProfile as vP}from"document360-engine";function dl(e,t,n,o){let r=n.filter(a=>a.status==="conflict"&&a.path).map(a=>a.path),s=new Set(o),i=[];try{i=$P(e,vP(e,t).name).map(a=>a.path).filter(a=>s.has(a))}catch{}return[...new Set([...r,...i])].sort()}function pl(){return["Document360 will not give this article back as markdown \u2014 it is not on the Markdown (Editor 3.0) editor, so there is no portal copy to show you or to take.","Your local copy is intact, and publishing it over the portal settles this. Skipping leaves the article flagged, and it will be waiting again next time."]}function hl(){return"Publish your copy over the portal (settles it) \xB7 Skip?"}function hw(){return"(l publish yours \xB7 s skip \u2014 anything else stops, keeping your answers so far)"}function fl(e){if(e.length===0)return[];let t=e.length,n=e.slice(0,3).join(", ")+(t>3?`, +${t-3} more`:"");return[`${t} article${t===1?"":"s"} stay${t===1?"s":""} flagged \u2014 Document360 cannot hand ${t===1?"its":"their"} markdown back: ${n}`,"Two ways out: run /resolve and press l to publish your copy over the portal, or ask your Document360 admin to move the article back to the Markdown (Editor 3.0) editor, then run /resolve again."]}function Id(e){return`Cannot take the portal copy of ${e} \u2014 Document360 will not return it as markdown. Left as it was.`}ae();var ml=e=>e===1?"":"s";async function Ld(e,t,n=1){console.log(""),console.log(`${Z("\u25CF")} ${Je(t.title)} ${Ae(`(${t.path})`)}`);for(let i of t.notes)console.log(H(` \u26A0 ${i}`));let o=Ft(t.oldContent,t.newContent,Math.max(40,(process.stdout.columns??80)-1),Ur);if(o){console.log(Ae(` \u23BF local \u2192 portal: +${o.added} / -${o.removed} line${ml(o.added+o.removed)}`));for(let i of o.lines)console.log(i);o.hidden>0&&console.log(u(` \u2026 +${o.hidden} more diff lines`))}else console.log(u(" Local already matches the portal content \u2014 resolving just advances the sync base."));let r=n>1,s=await e.withPausedInput(()=>gw({message:`Conflict \u2014 ${t.path}${r?` (${n} left)`:""}`,choices:[{name:"Keep local (publish \u2014 overwrites the portal edit)",value:"local"},{name:"Take portal (overwrites your local edits)",value:"portal"},{name:"Skip (leave it a conflict)",value:"skip"},...r?[{name:`Keep local for ALL ${n} remaining`,value:"local-all"},{name:`Take portal for ALL ${n} remaining`,value:"portal-all"},{name:`Skip ALL ${n} remaining`,value:"skip-all"}]:[]]})).catch(()=>"skip");return s==="portal"?(yw({cwd:e.cwd,profileName:e.profileName},t),console.log(X(" \u2713 Took the portal copy (local overwritten, sync base advanced).")),"took-portal"):s==="local"?"keep-local":s==="skip"?(console.log(u(" Skipped \u2014 still a conflict.")),"skipped"):s==="local-all"?"keep-local-all":s==="portal-all"?"took-portal-all":"skipped-all"}async function SP(e,t){console.log(""),console.log(`${Z("\u25CF")} ${Je(RP(e.cwd,t)??t)} ${Ae(`(${t})`)}`);for(let o of pl())console.log(H(` \u26A0 ${o}`));return await e.withPausedInput(()=>gw({message:hl(),choices:[{name:"Publish your copy over the portal (settles it)",value:"local"},{name:"Skip (leave it a conflict)",value:"skip"}]})).catch(()=>"skip")==="local"?"keep-local":(console.log(u(" Skipped \u2014 still a conflict.")),"skipped")}async function ww(e,t){let n=Ze(t.cwd,t.profileName);if(!n.ok)return console.log(L(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let r=await xP({cwd:t.cwd,profileName:t.profileName}),s=dl(t.cwd,t.profileName,r.entries,Bo(r.entries).map(l=>l.path));if(o){if(!s.includes(o))return console.log(X(`${o} isn't waiting on a decision \u2014 nothing to resolve.`)),{kind:"continue"};s=[o]}if(s.length===0)return console.log(X("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let i=[],a=[];for(let[l,c]of s.entries()){let h;try{h=await mw({cwd:t.cwd,profileName:t.profileName,relPath:c})}catch(w){if(!fw(w))throw w;await SP(t,c)==="keep-local"?i.push(c):a.push(c);continue}let y=await Ld(t,h,s.length-l);if(y==="keep-local"&&i.push(c),!y.endsWith("-all"))continue;let x=s.slice(l);if(y==="keep-local-all")i.push(...x),console.log(u(` Keeping local for all ${x.length} \u2014 publishing them over the portal.`));else if(y==="took-portal-all"){let w=0;for(let S of x)try{yw({cwd:t.cwd,profileName:t.profileName},await mw({cwd:t.cwd,profileName:t.profileName,relPath:S})),w++}catch(P){console.log(L(` \u2717 ${S}: ${P.message}`)),fw(P)&&a.push(S)}console.log(X(` \u2713 Took the portal copy of ${w} article${ml(w)} (local overwritten, sync base advanced).`))}else console.log(u(` Skipped all ${x.length} \u2014 still conflict${ml(x.length)}.`));break}for(let l of fl(a))console.log(H(`\u26A0 ${l}`));if(i.length>0)return console.log(u(`Publishing ${i.length} kept-local article${ml(i.length)} over the portal\u2026`)),await nn(t,i,0,{allowUnpullable:!0})}catch(r){console.log(L(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function $w(e,t){let n=Ze(t.cwd,t.profileName);if(!n.ok)return console.log(L(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await jP(t),{kind:"continue"};if(o==="--baseline")return await IP(t,e.filter(i=>i!=="--baseline")),{kind:"continue"};if(o==="--compare")return await LP(t),{kind:"continue"};if(o)return console.log(L(`Unknown option: ${o}`)),console.log(u("Usage: /pull pull portal edits + import new portal articles")),console.log(u(" /pull <path> pull one article (or resolve a conflict)")),console.log(u(" /pull --status drift report only (no writes)")),console.log(u(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await OP(t,r),{kind:"continue"};console.log(u("Pulling changes from Document360\u2026"));let s=await Md({cwd:t.cwd,profileName:t.profileName});for(let i of _d(s))console.log(i.tone==="ok"?X(i.text):i.tone==="warn"?H(i.text):u(i.text));console.log("")}catch(r){r instanceof DP?console.log(L(r.message)):console.log(L(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function Md(e){let t=await bw({cwd:e.cwd,profileName:e.profileName}),n={pulled:[],imported:[],conflicts:[],toPublish:0,failed:[]};for(let o of t.entries)if(o.status==="remote-ahead"&&o.path)try{let r=await kw({cwd:e.cwd,profileName:e.profileName,relPath:o.path});Od({cwd:e.cwd,profileName:e.profileName},r),n.pulled.push(o.path)}catch(r){n.failed.push({ref:o.path,error:r.message})}else if(o.status==="untracked-remote"&&o.articleId)try{let r=await TP({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId,...o.remoteCategory?{categoryPath:o.remoteCategory.path}:{}});AP({cwd:e.cwd,profileName:e.profileName},r),n.imported.push({title:r.title,path:r.path})}catch(r){n.failed.push({ref:o.title??o.articleId,error:r.message})}else o.status==="conflict"&&o.path?n.conflicts.push(o.path):(o.status==="local-ahead"||o.status==="untracked-local"&&!o.link)&&o.path&&n.toPublish++;return n}var gl=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Ho=e=>e===1?"":"s";function _d(e){let t=[];if(e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${Ho(e.pulled.length)} into local: ${gl(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${Ho(e.imported.length)}: ${gl(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${Ho(e.toPublish)} changed locally \u2014 /push saves them to Document360.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${Ho(e.conflicts.length)} changed both here and on Document360 \u2014 left untouched. Resolve them: /resolve (or /push <path> to keep yours, /pull <path> to take the portal's). (${gl(e.conflicts)})`}),e.failed.length){t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${Ho(e.failed.length)} could not be imported.`});let n=new Map;for(let o of e.failed){let r=o.error.replace(/^"[^"]*" could not be imported: /,"");n.set(r,[...n.get(r)??[],o.ref])}for(let[o,r]of n)t.push({tone:"warn",text:` ${o}`}),t.push({tone:"warn",text:` ${gl(r)}`})}return t.length===0&&t.push({tone:"ok",text:"\u2713 Already in sync with Document360 \u2014 nothing to pull."}),t}async function jP(e){console.log(u("Checking Document360 for drift\u2026"));let t=Date.now(),n=await bw({cwd:e.cwd,profileName:e.profileName});for(let o of ul(n,Date.now()-t))console.log(o);console.log("")}async function IP(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(u(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await EP({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await NP({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(X("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(X(`\u2713 Recorded ${o.baselined.length} article(s) as matching Document360 \u2014 they read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(X(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(H(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(u(` - ${s.path} (${s.reason})`))}}async function LP(e){console.log(u("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await PP({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${Je(String(t.legacyCount))} \xB7 Manifest: ${Je(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(X("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(L(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(H(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(H(` ${t.onlyInManifest.length} only in the manifest: ${t.onlyInManifest.slice(0,5).join(", ")}`)),console.log(u(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function OP(e,t){let n=t.replace(/\\/g,"/"),o=await kw({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await Ld(e,o)==="keep-local"&&(console.log(u(`Publishing ${o.path} over the portal\u2026`)),await nn(e,[o.path]));return}console.log(""),console.log(`${Z("\u25CF")} ${Je(o.title)} ${Ae(`(${o.path})`)}`);for(let i of o.notes)console.log(H(` \u26A0 ${i}`));let r=Ft(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1),Ur);if(!r){console.log(u(" Local file already matches the remote content \u2014 advancing the sync base only.")),Od({cwd:e.cwd,profileName:e.profileName},o);return}console.log(Ae(` \u23BF Added ${r.added} line${Ho(r.added)}, removed ${r.removed} line${Ho(r.removed)}`));for(let i of r.lines)console.log(i);if(r.hidden>0&&console.log(u(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>CP({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(u(" Skipped."));return}Od({cwd:e.cwd,profileName:e.profileName},o),console.log(X(` \u2713 Pulled ${o.path} (sync base advanced).`))}ae();import{statSync as YP}from"node:fs";import{resolve as KP}from"node:path";import{estimateBulkCost as zP,planPartitions as XP,readProjectConfig as QP,resolveModelForOperation as JP,runPartitioned as ZP,trackedArticlePaths as eT}from"document360-engine";function eo(e,t){return e.aborted?null:e.blocked?[`\u2717 ${t} didn\u2019t start \u2014 ${e.blocked}.`,"Nothing was changed. Fix that, then re-run."]:e.allEmpty?[`\u2717 ${t} did nothing \u2014 every batch produced no output, so no agent actually ran.`,"Run /doctor \u2014 it runs a real turn with your skills and tools and reports what failed. /logs shows Claude Code\u2019s own error, which was recorded either way, and offers to copy it.","A Claude usage or session limit also does this, and it ends every turn instantly \u2014 if you have just hit one, wait for the reset and re-run."]:null}function vw(e){return!e.bailedEmpty||!e.notRun?null:`\u26A0 Stopped early \u2014 ${e.notRun} batch${e.notRun===1?" was":"es were"} not attempted, because two in a row produced no output (that is systemic, not this work: usually a Claude usage limit). Re-run to finish the rest; anything already done is skipped.`}var Fr=class{activeMs=0;last=0;timer=null;startedAt=0;stopped=null;start(t=Date.now()){this.timer||(this.startedAt=t,this.last=t,this.timer=setInterval(()=>this.tick(),1e3),this.timer.unref?.())}tick(t=Date.now()){let n=t-this.last;this.last=t,!(n<=0)&&(this.activeMs+=Math.min(n,5e3))}stop(t=Date.now()){return this.stopped?this.stopped:(this.timer&&(clearInterval(this.timer),this.timer=null),this.tick(t),this.stopped={activeSeconds:Math.max(0,Math.round(this.activeMs/1e3)),elapsedSeconds:Math.max(0,Math.round((t-this.startedAt)/1e3))},this.stopped)}};function yl(e,t){let n=t-e;return n>=300&&n>=t*.2}function Wt(e,t,n,o=Date.now(),r){let s=t.reduce((a,l)=>a+(l.inputTokens??0),0),i=t.reduce((a,l)=>a+(l.cacheReadTokens??0),0);return{seconds:Math.max(0,Math.round((o-e)/1e3)),outputTokens:t.reduce((a,l)=>a+l.outputTokens,0),inputTokens:s,...s>0?{cachedPct:Math.round(i/s*100)}:{},...r!==void 0?{activeSeconds:r}:{},costUsd:n}}function wl(e){return e.activeSeconds!==void 0&&yl(e.activeSeconds,e.seconds)?`${Ud(e.seconds)} elapsed \xB7 ${Ud(e.activeSeconds)} working`:Ud(e.seconds)}var xw=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:`${e}`,Ud=e=>{if(e<60)return`${e}s`;let t=Math.floor(e/60);return t<60?`${t}m ${e%60}s`:`${Math.floor(t/60)}h ${t%60}m`};function dn(e){let t=e.cachedPct!==void 0?`, ${e.cachedPct}% cached`:"",n=e.costUsd>0?`, this turn ${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"";return` (took ${wl(e)}, ${xw(e.inputTokens)}\u2192${xw(e.outputTokens)} tokens${t}${n})`}import Re from"picocolors";import Hd from"wrap-ansi";import Gd from"string-width";ae();import to from"picocolors";import kl from"wrap-ansi";import bl from"string-width";var Go=[{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>] [--push]",desc:"Document a shipped change \u2014 the agent picks the action (new section/article/update); bare: act on builder requests. --push then saves the result to Document360 as drafts, which still needs an editorial review first",group:"docs"},{name:"write",usage:"/write [--preview|--scope <cat>|<path>] [--rewrite] [--concurrency N] [--skip-style]",desc:"Write the planned articles in parallel (starts immediately; --preview shows plan + cost first; --rewrite regenerates already-written articles; --concurrency default 3). Anything that would block publishing is corrected in one automatic pass before the run finishes; --skip-style leaves it to /lint",group:"docs"},{name:"screenshot",usage:"/screenshot [author|capture|annotate|verify|checklist|list] [id|path|--all|--failed|--blocked]",desc:"Screenshots, one family \u2014 bare: pick what to do; author: write capture specs; capture: take the shots (--all re-shoots everything; --failed re-runs the ones that did not work; --blocked re-runs the ones waiting on app data); annotate: draw the callouts on shots already taken, no browser needed (--all --force re-draws after a wording or style change); verify: judge the finished pictures and mark them verified (both run automatically after a capture); 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:"push",usage:"/push [path|--all|--related <path>|[<category>] --screenshots] [--preview] [--skip-review]",desc:"Save your articles to Document360 as drafts \u2014 readers don't see them until /publish (no arg: pick; --all: every candidate; --screenshots: re-save articles with captured shots so images embed, optionally narrowed to one category; --related <path>: also save that article's related articles that were never saved; --preview <path>: show exactly what would be sent, and send nothing). Blocked until each article has had /review --fix \u2014 AI-written text gets an editor first; --skip-review overrides deliberately",group:"publish"},{name:"publish",usage:"/publish [path|<category>|--all] [--skip-review]",desc:"Take the drafts on Document360 LIVE to your readers (the portal's own Publish). Always lists what would become visible and asks first; no arg or a category narrows it. Needs an editorial review \u2014 /review --blocked --fix",group:"publish"},{name:"style-guide",usage:"/style-guide [list | use [<preset>] | keep | sweep [skip] | pull [<n>] | learn | compile | explain <rule>]",desc:"Choose the writing rules your docs are held to. Bare: what is active now; list: every pack you can turn on; use: switch packs, hold every article to them and apply the free text swaps (bare: pick from a list); keep: settle on the rules you have today; sweep: how much of your knowledge base still needs reading against a guide you switched to (skip stops me raising it); pull: bring your Document360 project's own style guide down; learn: turn what your reviewers keep asking for into standing rules; compile: turn its mechanical statements into checks; explain: what one rule means and how to silence it",group:"docs"},{name:"lint",usage:"/lint [<category|path>] [--blocked] [--fix] [--full] [--baselined]",desc:"Lint the docs against the house rules: leaked internals, invented commands, stale facts, AI-tells, em dashes, callout shape (deterministic, no tokens). Every finding names the rule that produced it. Scope to a category/path; --blocked narrows to the errors that block publishing and leaves warnings and suggestions alone; --fix has the agent correct them in place; --full lists every finding instead of a capped summary; --baselined shows the issues that were already in your articles when you chose this style guide, which never block publishing",group:"docs"},{name:"review",usage:"/review [<category|path> | --all | --blocked | --stale] [--fix]",desc:"Independent senior-editor review: style guide, terminology/voice, grammar/clarity, page structure, improvement suggestions. A whole-knowledge-base run also gets one editor on the SHAPE of the docs \u2014 reading order, categories that have grown too big, articles filed in the wrong place, names that no longer fit. Bare: pick a category or everything; --blocked reads only the articles publishing is blocked on; --stale reads the ones the current editor has not read yet, so running it twice costs nothing; --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 /push",group:"docs"},{name:"restructure",usage:"/restructure [<what to change>]",desc:"Reshape the knowledge base: move an article to a different category, split one that has grown too big, merge two, rename one, or nest one inside another. A category left empty by a merge is hidden from readers, never deleted. Bare: reviews how the docs are organized and reports what should change, without touching anything; the changes reach Document360 on the next /push",group:"docs"},{name:"structure",usage:"/structure",desc:"Show the documentation reading order (categories \u2192 articles) as it will appear on Document360",group:"docs"},{name:"status",usage:"/status [--all]",desc:'What stands between your work and your readers, before you spend anything: which articles no editor has read, which break a style rule your config makes blocking, which would show "[Screenshot: \u2026]" text to a reader, which are in conflict with the portal, and which are saved as drafts readers cannot see yet. Each group names the one command that clears it. Reads local files and the last sync \u2014 no network, no tokens. --all lists every article gate by gate',group:"publish"},{name:"retire",usage:"/retire [<path>] [--yes]",desc:"Take an article off your readers on Document360 \u2014 it stops being visible, and nothing offers to publish it again. Nothing is deleted: the article, its version history and every reviewer comment stay. Bare: lists what is worth retiring (articles on Document360 that are no longer in your docs folder). /push puts one back \u2014 reviving is a publish like any other",group:"publish"},{name:"untrack",usage:"/untrack [<path>] [--undo] [--list] [--yes]",desc:"Disown a page that was imported from Document360 but is not one of your docs. /catch-up and /pull import every article they find in your categories; this records the ones you do not want, so they are never imported again \u2014 and the decision travels with the repo, so a teammate\u2019s clone inherits it. Nothing on Document360 changes and nothing is deleted: the markdown moves to .d360-writer/declined/. Bare: lists what this repo has declined. --undo puts one back",group:"publish"},{name:"reuse",usage:'/reuse [pull | add <variable|snippet> <name> "<value>" | audit [<category>] [--create <n\u2026>]]',desc:"The terms, values and blocks your project already maintains on Document360, so your articles reference them instead of repeating them. A variable holds a value like your product name in one place \u2014 change it there and every article changes; type it out by hand and /lint flags it. A snippet does the same for a whole block, and the writer references yours by name instead of writing its own version. A term is defined once and every article is checked for explaining it the first time it appears. Reading is free; pull refreshes from Document360, add creates a new one there, and audit reads every article to work out what belongs in one place",group:"docs"},{name:"eval",usage:"/eval [<category>] [--all]",desc:"How does your whole knowledge base score? Reads every article and reports what no single-article check can see: internal links written as portal URLs, links pointing at headings that no longer exist, link text that names a different article, the command summary line appearing in several shapes, two names for the same section, and how many style findings were accepted as exempt when you chose your style guide. Costs nothing and calls nothing",group:"docs"},{name:"terms",usage:'/terms [<category>] [--all] [--approve "<term>"]',desc:"Is your knowledge base calling the same thing by the same name? Reads every article and reports terms spelled more than one way, short names that may be the long name abbreviated, and article titles out of step with the rest of their kind \u2014 the consistency an editor reading three articles at a time cannot see. Costs nothing and calls nothing. --approve records a spelling as the approved one, so every later run enforces it",group:"docs"},{name:"roadmap",usage:"/roadmap [--all | done [step]]",desc:"Show the docs campaign (the multi-session plan the agent maintains), grouped by the part of the job \u2014 progress + next step; `--all` also lists the steps a later pass replaced; `done` marks the next open step finished (add words from a title to pick another)",group:"docs"},{name:"audit",usage:"/audit [--auto on|off] [--decline <path>]",desc:"Gap analysis: code vs docs vs Document360 (what changed); --auto runs it at launch when code changed; --decline settles a folder or file that needs no article",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:"ask",usage:"/ask <question>",desc:"Ask your developers something the code cannot tell you: why a feature exists, when to use it, whether it can be undone",group:"publish"},{name:"share",usage:"/share [status|on|off]",desc:"Share your docs work with the team: get your builder's latest, then save + send yours (runs automatically; `off` leaves it to your coding agent)",group:"publish"},{name:"catch-up",usage:"/catch-up [--push] [--include-unfinished]",desc:"Process ALL pending work (builder hints + requests + Document360 portal drift) \u2192 write \u2192 save to Document360 as drafts. --push does that last step for you, which still needs an editorial review first. A note whose code your builder has not committed is left for later, and they are asked whether it is done; --include-unfinished writes those pages anyway. For code changes, that's /audit",group:"publish"},{name:"comments",usage:"/comments [<article>] [--scope <category>] [--answer] [--all] [--resolve] [--answered] [--full]",desc:"Reviewer comments left on passages of your articles in the Document360 portal \u2014 bare: a table by article, pick a number to read its comments in full, then answer or go back; --answer: fix, push the draft, reply (threads stay open unless you add --resolve); --full re-reads every article",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 (push), take portal (pull), or skip \u2014 per article, or one answer for all remaining. 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:"Where this repo publishes \u2014 switch, or connect another environment (picker; s = session)",group:"setup"},{name:"workspace",usage:"/workspace [name]",desc:"Switch the Document360 workspace (picker)",group:"setup"},{name:"auto",usage:"/auto [on|off|status] [--budget <amount>]",desc:"Auto or manual: in auto I run the next step myself \u2014 write, review, check style, save, go live \u2014 instead of waiting for you (shift+tab cycles it; esc stops a run)",group:"setup"},{name:"model",usage:"/model [name|default]",desc:"Set the Claude model for d360-writer",group:"setup"},{name:"verbose",usage:"/verbose [on|off]",desc:"Show the raw transcript \u2014 every tool call with its file path and full result, instead of article-shaped cards with my bookkeeping collapsed (bare: toggle)",group:"setup"},{name:"logout",usage:"/logout [--all-projects]",desc:"Sign out of this project + clear its workspace selection (then /login to re-pick)",group:"setup"},{name:"allow-prod",usage:"/allow-prod",desc:"Authorize taking articles live on a production profile",group:"setup"},{name:"env",usage:"/env [add <file.json>|remove <name>]",desc:"The Document360 deployments this machine can reach \u2014 and add one this build does not ship",group:"setup"},{name:"doctor",usage:"/doctor",desc:"Health-check: auth, profile, workspace, map, API, and a real agent turn",group:"setup"},{name:"logs",usage:"/logs",desc:"Show the most recent problem d360-writer recorded, and where the logs are \u2014 \u2303y copies it for the team",group:"setup"},{name:"update",usage:"/update",desc:"Update d360-writer \u2014 and d360-capture when installed \u2014 to the latest versions",group:"setup"},{name:"copy",usage:"/copy",desc:"Copy what is waiting \u2014 the feedback to relay, or the builder prompt to paste (\u2303y does the same)",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"}],Rw={"/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","/push":"save your articles to Document360 as drafts","/publish":"take the signed-off drafts live to your readers","/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, draw the callouts)","/doctor":"run a health check","/logs":"show the last problem, and copy it for the team","/auto":"choose whether I run the next step myself or wait for you","/style-guide":"choose the writing rules your docs are held to","/lint":"check the docs against those rules (costs nothing)"};function Sw(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(Rw[n])return Rw[n];let o=Go.find(r=>r.name===t);return o?o.desc:""}function Cw(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return Go.filter(n=>n.name.startsWith(t))}function Pw(e){let t=0,n="";for(let o of e){if(o==="["){t++;continue}if(o==="]"){t=Math.max(0,t-1);continue}t===0&&(n+=o)}return/<[^>]+>/.test(n)}var MP=new RegExp(`^\\s*/(?:${Go.map(e=>e.name).join("|")})(?:\\s|$)`),Tw=e=>MP.test(e),Aw=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Ew=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),Nw=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function _P(e){let t=e.replace(/\r/g,"").split(`
|
|
347
|
+
`),n=[],o=0;for(;o<t.length;){let r=t[o];if(/^\s*```/.test(r)){let a=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)a.push(t[o++]);o++,n.push({kind:"code",lines:a});continue}if(Aw(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&Ew(t[o+1])){let a=Nw(r);o+=2;let l=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)l.push(Nw(t[o++]));n.push({kind:"table",header:a,rows:l});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 a=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);){let l=t[o++];a.push({ordered:/^\s*\d+\.\s+/.test(l),text:l.replace(/^\s*([-*]|\d+\.)\s+/,"")})}n.push({kind:"list",items:a});continue}if(r.trim()===""){o++;continue}if(Tw(r)){n.push({kind:"para",text:r.trim()}),o++;continue}let i=[];for(;o<t.length&&t[o].trim()!==""&&!/^\s*```/.test(t[o])&&!/^(#{1,6})\s/.test(t[o])&&!/^\s*([-*]|\d+\.)\s+/.test(t[o])&&!Tw(t[o])&&!Aw(t[o])&&!(t[o].includes("|")&&o+1<t.length&&Ew(t[o+1]));)i.push(t[o++]);n.push({kind:"para",text:i.join(" ")})}return n}function Fd(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?to.bold(t.slice(2,-2)):t.startsWith("`")?Z(t.slice(1,-1)):to.italic(t.slice(1,-1)))}var UP=(e,t)=>e+" ".repeat(Math.max(0,t-bl(e)));function Qs(e,t,n,o={}){return Dw(e,t,n,o)}function Dw(e,t,n,o={}){let r=e.length,s=T=>Math.max(0,...T.split(`
|
|
348
|
+
`).map(R=>bl(R))),i=e.map((T,R)=>Math.max(bl(T),...t.map(D=>s(D[R]??"")))),a=Math.max(24,n),l=3*r+1,c=[...i],h=()=>c.reduce((T,R)=>T+R,0)+l,y=0;for(;h()>a&&y++<1e4;){let T=-1,R=6;for(let D=0;D<r;D++)c[D]>R&&(R=c[D],T=D);if(T===-1)break;c[T]-=1}let x=(T,R,D)=>to.gray(T+c.map(B=>"\u2500".repeat(B+2)).join(R)+D),w=to.gray("\u2502"),S=(T,R)=>{let D=c.map((N,ne)=>{let te=T[ne]??"",he=R?to.bold(te):o.plain?te:Fd(te);return te.includes(`
|
|
349
|
+
`)?he.split(`
|
|
350
|
+
`).flatMap(we=>kl(we,N,{hard:!0}).split(`
|
|
351
|
+
`)):kl(he,N,{hard:!0}).split(`
|
|
352
|
+
`)}),B=Math.max(...D.map(N=>N.length)),G=[],Q=(N,ne,te)=>o.align?.[te]==="right"?" ".repeat(Math.max(0,ne-bl(N)))+N:UP(N,ne);for(let N=0;N<B;N++)G.push(c.map((ne,te)=>`${w} ${Q(D[te][N]??"",ne,te)} `).join("")+w);return G.join(`
|
|
353
353
|
`)},P=[x("\u250C","\u252C","\u2510"),S(e,!0)];return P.push(t.length===0?x("\u2514","\u2534","\u2518"):x("\u251C","\u253C","\u2524")),t.forEach((T,R)=>{P.push(S(T,!1)),P.push(R===t.length-1?x("\u2514","\u2534","\u2518"):x("\u251C","\u253C","\u2524"))}),P.join(`
|
|
354
|
-
`)}function
|
|
354
|
+
`)}function FP(e,t){switch(e.kind){case"heading":return to.bold(e.text);case"hr":return to.gray("\u2500".repeat(t));case"para":return kl(Fd(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),[i="",...a]=kl(Fd(o.text),Math.max(10,t-s.length)).split(`
|
|
355
355
|
`);return` ${r} ${i}`+a.map(l=>`
|
|
356
356
|
${s}${l}`).join("")}).join(`
|
|
357
|
-
`)}case"code":return e.lines.map(n=>
|
|
358
|
-
`);case"table":return
|
|
357
|
+
`)}case"code":return e.lines.map(n=>to.gray(" "+n)).join(`
|
|
358
|
+
`);case"table":return Dw(e.header,e.rows,t)}}function Wd(e,t){let n=Math.max(20,t);return _P(e).map(o=>FP(o,n)).join(`
|
|
359
359
|
|
|
360
|
-
`)}
|
|
361
|
-
`);let r=2,s=3,i=
|
|
360
|
+
`)}ae();import WP from"picocolors";var BP=[127,86,217],HP=[22,38,43],jw={T:BP,E:HP},Js=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],Bd=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,GP=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function Iw(){if(!WP.isColorSupported)return[];let e=Js[0].length,t=[];for(let n=0;n<Js.length;n+=2){let o="";for(let r=0;r<e;r++){let s=jw[Js[n][r]],i=n+1<Js.length?jw[Js[n+1][r]]:void 0;s&&i?o+=`${Bd(s)}${GP(i)}\u2580\x1B[49m\x1B[39m`:s?o+=`${Bd(s)}\u2580\x1B[39m`:i?o+=`${Bd(i)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function Zs(e){let t=n=>n.toFixed(1).endsWith(".0")?n.toFixed(0):n.toFixed(1);return e<1e3?String(e):e<1e6?`${t(e/1e3)}k`:`${t(e/1e6)}M`}function An(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function Ow(e,t,n){let o=e>0&&e<=n?e:t;return Math.max(0,Math.floor((n-o)/1e3))}function St(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function Br(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var Wr=(e,t)=>` ${e.padEnd(13)}${t}`;function qP(e,t){let n=[Ds("\u270E document360-writer")+Re.gray(` v${e.version} \xB7 engine v${e.engineVersion}${e.captureVersion?` \xB7 capture v${e.captureVersion}`:""}`),Re.gray(" Reads your code, writes your docs."),"",Wr("Claude:",`${e.claude}${Re.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),Wr("Document360:",e.configured?e.loggedOut?Re.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?Re.gray(` (${e.sessionHint})`):""}`:Re.yellow("not set up \u2014 run /init")),Wr("Profile:",e.configured?`${e.profile}${Re.gray(` (${e.apiUrl})`)}${e.prod?Re.yellow(` ${Ye}`):""}`:Re.gray("\u2014 (run /init)")),Wr("Project:",e.configured&&e.workspace===null?`${e.project}${Re.yellow(" \xB7 no workspace yet")}`:`${e.project}${e.workspace?Re.gray(` \xB7 ${e.workspace}`):""}`),Wr("Mode:",Re.gray(e.mode)),Wr("cwd:",Re.gray(e.cwd))],o=Iw();if(o.length===0)return n.join(`
|
|
361
|
+
`);let r=2,s=3,i=Gd(o[0]);if(!(t>=r+i+s+Math.max(...n.map(h=>Gd(h)))))return[...o.map(h=>" "+h),...n].join(`
|
|
362
362
|
`);let l=Math.max(0,Math.floor((n.length-o.length)/2)),c=[];for(let h=0;h<Math.max(o.length+l,n.length);h++){let y=o[h-l]??" ".repeat(i);c.push((" ".repeat(r)+y+" ".repeat(s)+(n[h]??"")).trimEnd())}return c.join(`
|
|
363
|
-
`)}var
|
|
364
|
-
`).flatMap(c=>
|
|
365
|
-
`)),l=Math.max(0,a.length-i);return l>0&&(a=[...a.slice(0,i),
|
|
366
|
-
`+a.map((c,h)=>o+(h===0?Z(" \u276F "):" ")+c+" ".repeat(Math.max(0,s-
|
|
363
|
+
`)}var VP={error:Re.red,warn:Re.yellow,ok:Re.green,info:Re.gray},Lw=9;function qd(e){return e.length>=Lw?`${e} `:e.padEnd(Lw)}function $l(e){return e.replace(/^(\s*• |)([^\x00-\x7F][\u{1F000}-\u{1FAFF}️]*) (?=\S)/gmu,"$1$2 ")}function Vd(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return qP(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",s=Math.max(10,n-4),i=50,a=e.text.split(`
|
|
364
|
+
`).flatMap(c=>Hd(c,s,{hard:!0}).split(`
|
|
365
|
+
`)),l=Math.max(0,a.length-i);return l>0&&(a=[...a.slice(0,i),Re.dim(`\u2026 +${l} more lines`)]),`
|
|
366
|
+
`+a.map((c,h)=>o+(h===0?Z(" \u276F "):" ")+c+" ".repeat(Math.max(0,s-Gd(c))+1)+r).join(`
|
|
367
367
|
`)}case"assistant":return`
|
|
368
|
-
`+
|
|
369
|
-
`+
|
|
370
|
-
`+
|
|
371
|
-
`)}case"diff":{let o=i=>i===1?"":"s",s=[
|
|
372
|
-
`)}case"link":return e.lines.map(o=>Z(
|
|
368
|
+
`+Wd(e.text,n);case"tool":{let o=e.arg!==null?Re.gray(`${e.sep}(${e.arg})`):"";return`
|
|
369
|
+
`+Hd(Re.gray("\u25CF ")+e.title+o,n)}case"doc":{let o=[e.category,e.note].filter(s=>!!s).map(s=>Re.gray(` \xB7 ${s}`)),r=e.loud?Re.gray(" \xB7 ")+Re.bold(Re.yellow(e.loud)):"";return`
|
|
370
|
+
`+Hd(Re.green("\u25CF ")+Z(Re.bold(qd(e.verb)))+Re.bold(e.title)+o.join("")+r,n)}case"tool-result":{let o=e.isError?Re.red:Re.gray,r=e.lines.map((s,i)=>o((i===0?" \u23BF ":" ")+s));return e.hidden>0&&r.push(Re.dim(` \u2026 +${e.hidden} lines`)),r.join(`
|
|
371
|
+
`)}case"diff":{let o=i=>i===1?"":"s",s=[Re.gray(` \u23BF Added ${e.added} line${o(e.added)}, removed ${e.removed} line${o(e.removed)}`),...e.lines];return e.hidden>0&&s.push(Re.dim(` \u2026 +${e.hidden} more diff lines`)),s.join(`
|
|
372
|
+
`)}case"link":return e.lines.map(o=>Z(Is(` \u2B95 ${o}`))).join(`
|
|
373
373
|
`);case"preview":return`
|
|
374
|
-
`+
|
|
374
|
+
`+Ds(`\u25A3 Preview \u2014 ${e.name}`)+`
|
|
375
375
|
|
|
376
|
-
`+
|
|
377
|
-
`+
|
|
378
|
-
`+e.text;case"done":{let o=e.inTokens&&e.inTokens>0?` \xB7 ${
|
|
379
|
-
`+(e.ok?
|
|
376
|
+
`+Wd(e.text,n);case"note":return`
|
|
377
|
+
`+VP[e.tone](Is($l(e.text)));case"block":return`
|
|
378
|
+
`+e.text;case"done":{let o=e.inTokens&&e.inTokens>0?` \xB7 ${Zs(e.inTokens)} in${e.cachedPct!=null?` (${e.cachedPct}% cached)`:""}`:"",r=e.activeSeconds!==void 0&&yl(e.activeSeconds,e.seconds)?`${An(e.seconds)} elapsed \xB7 ${An(e.activeSeconds)} working`:An(e.seconds),s=e.costUsd>0?` \xB7 this turn ${St(e.costUsd)}`+(e.sessionCostUsd!==void 0&&e.sessionCostUsd>e.costUsd?` \xB7 session ${St(e.sessionCostUsd)}`:""):"";return`
|
|
379
|
+
`+(e.ok?Re.magenta("\u2736 "):Re.red("\u2736 "))+Re.gray(`Cooked for ${r} \xB7 ${Zs(e.tokens)} tokens out${o}${s}`)}}}function Mw(e,t,n){let o=e.map(i=>Vd(i,t));if(n===void 0||n<=0)return o.join(`
|
|
380
380
|
`);let r=[],s=0;for(let i=o.length-1;i>=0;i--){let a=o[i].split(`
|
|
381
381
|
`).length;if(r.length>0&&s+a>n)break;r.unshift(o[i]),s+=a}return r.join(`
|
|
382
|
-
`)}var
|
|
382
|
+
`)}var Yd=3;function Kd(e){let t,n=!1;for(let r=0;r<e.length;r++){let s=e[r];s==="--run"||s==="--yes"?n=!0:s==="--scope"?t=e[++r]:s?.startsWith("--scope=")&&(t=s.slice(8))}return{scope:t?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0,run:n}}function zd(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Xd(e,t){return t.map(n=>{let o=0;try{o=YP(KP(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function Qd(e){return`Convert each of these articles to canonical Document360 Flavored Markdown (DFM) and re-publish each as a DRAFT. This is a mechanical syntax conversion, not a rewrite, so be efficient:
|
|
383
383
|
- Read ONLY the article files listed below. Do NOT read source code, other articles, or fetch the live portal; you already have everything you need.
|
|
384
384
|
- Convert in place: wrap callouts, FAQs, tabs, accordions, and media embeds per the d360-markdown skill. Preserve all wording, headings, and structure; change only GFM\u2192DFM syntax.
|
|
385
385
|
- Publish each as a draft with a single update call. Do NOT re-read, re-verify, or polish after converting, and skip articles already in DFM.
|
|
386
386
|
- Work only on these files:
|
|
387
387
|
`+e.paths.map(t=>`- ${t}`).join(`
|
|
388
|
-
`)}function
|
|
388
|
+
`)}function Jd(e,t,n){let o=e.reduce((a,l)=>a+l.paths.length,0),[r,s]=t.usd;return[`Convert ${o} article${o===1?"":"s"} to DFM in ${e.length} batch${e.length===1?"":"es"} (\u2264${n} agents at once):`,...e.map(a=>` \u2022 ${a.label} \u2014 ${a.paths.length} article${a.paths.length===1?"":"s"}`),"",`Estimated cost: ${St(r)}\u2013${St(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function Zd(e,t,n){let o=S=>t[S.index]?.paths.length??0,r=e.filter(S=>S.ok),s=e.filter(S=>!S.ok),i=e.reduce((S,P)=>S+o(P),0),a=r.reduce((S,P)=>S+o(P),0),l=e.reduce((S,P)=>S+P.costUsd,0),c=e.reduce((S,P)=>S+P.outputTokens,0),h=n==="api"?`${St(l)} total`:Br(c),y=`${r.length}/${e.length} batch${e.length===1?"":"es"} completed`,x=S=>`${S} article${S===1?"":"s"}`,w=[];if(s.length===0)w.push(`Converted ${x(i)} (${y}) successfully \xB7 ${h}.`);else{w.push(`Converted ${a}/${x(i)} (${y}) \xB7 ${h}.`),w.push(`${s.length} batch${s.length===1?"":"es"} failed \u2014 re-run /convert to retry:`);for(let S of s)w.push(` \u2717 ${S.label}${S.error?` \u2014 ${S.error}`:""}`)}return w}async function _w(e,t){if(!QP(t.cwd))return console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=Kd(e),r=eT(t.cwd,t.profileName);if(r.length===0)return console.log(L("No tracked articles in d360-category-map.json. Save some to Document360 first (/push), then /convert.")),{kind:"continue"};let s=zd(r,n);if(s.length===0)return console.log(L(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let i=XP(s),a=`/convert${n?` --scope ${n}`:""} --run`,{model:l,forced:c}=JP(t.cwd,"light");if(!o){let y=zP({files:Xd(t.cwd,s),op:"convert",model:l});n&&console.log(u(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let x of Jd(i,y,Yd))console.log(x);return console.log(u(`Model: ${l}${c?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(u(`Run ${a} to start.`)),console.log(""),{kind:"continue"}}console.log(u(`Converting ${s.length} articles in ${i.length} batches (\u2264${Yd} agents at once) on ${l}\u2026`)),console.log(u(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let h=Date.now();try{for await(let y of ZP({cwd:t.cwd,partitions:i,promptFor:Qd,concurrency:Yd,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:l}))if(y.type==="partition_status")y.status==="running"?console.log(u(` \u25B8 ${y.label} \u2014 converting\u2026`)):y.status==="done"?console.log(X(` \u2713 ${y.label}`)):console.log(L(` \u2717 ${y.label}`));else if(y.type==="run_done"){console.log("");let x=process.env.ANTHROPIC_API_KEY?"api":"subscription",w=eo(y,"The conversion");for(let S of w??Zd(y.results,i,x))console.log(w||!y.ok?H(S):X(S));console.log(u(dn(Wt(h,y.results,y.totalCostUsd))))}}catch(y){console.log(L(`Convert run failed: ${y.message}`))}return console.log(""),{kind:"continue"}}import{statSync as xT}from"node:fs";import{resolve as RT}from"node:path";import{CLAUDE_ACCOUNT_MISMATCH_HINT as ST,estimateBulkCost as CT,lintDocs as PT,planFindingPartitions as TT,planPartitions as AT,readDocsPlan as ET,readProjectConfig as lp,DEFAULT_DOCS_DIR as Jw,resolveModelForOperation as Kw,runPartitioned as zw,partitionCoverage as Xw,stampArticles as Qw,readReviewerNotes as NT,renderNotesForPrompt as DT,readReaderContract as jT,renderGapsForPrompt as IT,notesForPath as LT,CONTENT_CAP_VERSION as OT}from"document360-engine";ae();import{lintDocs as tp,guidanceForRules as tT,planFindingPartitions as nT,runPartitioned as oT,partitionCoverage as rT,resolveModelForOperation as sT,stampArticles as iT,applyDeterministicFixes as aT,isMechanical as lT}from"document360-engine";import{CONTENT_CAP_VERSION as Uw}from"document360-engine";function Fw(e){let t=e.trim().split(/\s+/);return t.includes("--fix")?t[0]==="/review"?"review":t[0]==="/lint"||t[0]==="/check"?"lint":null:null}function Ww(e){return e.trim().split(/\s+/).slice(1).find(t=>!t.startsWith("--"))}function wt(e){return e==="review"?{reviewedCap:Uw}:{checkedCap:Uw}}var xl={error:0,warning:1,suggestion:2},cT={error:"\u2717",warning:"\u26A0",suggestion:"\xB7"},uT=10,dT=8,pT=96,Bw=34,pn=e=>"ruleId"in e,no=e=>pn(e)?e.severity:"warning",np=e=>pn(e)?e.ruleId:e.kind,qo=e=>e.fileLine??e.line;function En(e){return e.includes("--blocked")}function Nn(e,t){return En(t)?e.filter(n=>no(n)==="error"):e}function ei(e,t){return`/lint${t?` ${t}`:""}${En(e)?" --blocked":""} --fix`}function ep(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function vl(e){let t={error:0,warning:0,suggestion:0};for(let n of e)t[no(n)]++;return t}function Hw(e){let t=[];for(let n of["error","warning","suggestion"])e[n]>0&&t.push(`${e[n]} ${n}${e[n]===1?"":"s"}`);return t.join(" \xB7 ")}function ti(e,t={}){let n=t.baselined?[]:e.filter(y=>pn(y)&&y.baselined),o=t.baselined?e:e.filter(y=>!(pn(y)&&y.baselined)),r=n.length>0?[oe("\u2139",`${n.length} issue${n.length===1?"":"s"} ${n.length===1?"was":"were"} already in your articles when you chose this style guide, so ${n.length===1?"it never blocks":"they never block"} publishing. /lint --baselined shows ${n.length===1?"it":"them"}.`)]:[];if(o.length===0)return[oe("\u2713","No issues found \u2014 no leaked internals, unknown commands, stale version facts, AI-tells, em dashes, or broken callouts in the docs."),...r];let s=new Map;for(let y of o){let x=s.get(y.path)??[];x.push(y),s.set(y.path,x)}let i=vl(o),a=[oe("\u26A0",`${o.length} issue${o.length===1?"":"s"} in ${s.size} article${s.size===1?"":"s"} \u2014 ${Hw(i)}.`),""],l=[...s.entries()].sort((y,x)=>{let w=vl(y[1]);return vl(x[1]).error-w.error||x[1].length-y[1].length||y[0].localeCompare(x[0])}),c=t.full?l:l.slice(0,uT);for(let[y,x]of c){a.push(` ${y} ${u(Hw(vl(x)))}`);let w=new Map;for(let R of x){let D=np(R),B=w.get(D)??[];B.push(R),w.set(D,B)}let S=[...w.entries()].sort((R,D)=>xl[no(R[1][0])]-xl[no(D[1][0])]||D[1].length-R[1].length||R[0].localeCompare(D[0])),P=t.full?S:S.slice(0,dT);for(let[R,D]of P){let B=[...D].sort((ke,ee)=>qo(ke)-qo(ee)),G=cT[no(B[0])],N=new Set(B.map(ke=>ke.term)).size===1?` ${ep(`"${B[0].term}"`,Bw)}`:"",ne=B.length>1?u(` \xD7${B.length}`):"",te=t.full?B[0].message:ep(B[0].message,pT);a.push(` ${G} ${R}${ne}${N}`),a.push(` ${u(te)}`);let he=B.map(ke=>N?`L${qo(ke)}`:`L${qo(ke)} ${ep(`"${ke.term}"`,Bw)}`),we=t.full?he:he.slice(0,12),ye=he.length-we.length;a.push(` ${u(we.join(", ")+(ye>0?` \u2026+${ye}`:""))}`)}let T=S.length-P.length;T>0&&a.push(u(` \u2026${T} more rule${T===1?"":"s"} fired here (/lint ${y} --full)`)),a.push("")}let h=l.length-c.length;return h>0&&(a.push(u(` \u2026and ${h} more article${h===1?"":"s"} (/lint <category> narrows \xB7 /lint --full lists every one)`)),a.push("")),a.push(...r),a}var hT=200;function Rl(e){let n=[...e.filter(l=>!(pn(l)&&l.baselined))].sort((l,c)=>xl[no(l)]-xl[no(c)]||l.path.localeCompare(c.path)||qo(l)-qo(c)),o=n.slice(0,hT),r=n.length-o.length,s=new Map;for(let l of o){let c=s.get(l.path)??[];c.push(l),s.set(l.path,c)}let i=[...s.entries()].map(([l,c])=>[l,...c.map(h=>` - L${qo(h)} [${np(h)}] (${no(h)}): "${h.term}": ${h.message}`)].join(`
|
|
389
389
|
`)).join(`
|
|
390
|
-
`),a=
|
|
391
|
-
`)}var
|
|
390
|
+
`),a=tT(o.map(l=>({id:np(l),message:l.message,link:pn(l)?l.link:void 0})));return["The documentation linter found issues in already-written articles. FIX each one by EDITING the","article in place. Do not rewrite whole articles; just resolve the flagged problems. Ground every change","in the actual product source (the authoritativeSourceFiles); never invent.","","Errors are listed first: those are defects of fact or structure, and they matter most.","",...a.length>0?["How to fix, by rule:",...a,""]:[],"Rules: edit ONLY the listed articles; do not touch others; do not publish; introduce no new internal","nouns, invented commands, or wrong facts. When done, every listed issue should be gone.","",...r>0?[`Note: ${r} further finding${r===1?"":"s"} were left out of this batch to keep it actionable. Run /lint --fix again afterwards to pick them up.`,""]:[],"Issues:",i].join(`
|
|
391
|
+
`)}var Hr=3;function oo(e,t,n){let o=n.filter(a=>!(pn(a)&&a.baselined)),r=Nn(o,t).filter(a=>pn(a)&&lT(a));if(r.length===0)return{fixed:0,skipped:0,lines:[],paths:[]};let s=aT(e,r),i=[];if(s.fixed.length>0){let a=new Set(s.fixed.map(l=>l.path)).size;i.push(X(oe("\u2713",`Fixed ${s.fixed.length} ${s.fixed.length===1?"issue":"issues"} in ${a} ${a===1?"article":"articles"} \u2014 a straight swap, so no model and no cost.`)))}return s.skipped.length>0&&i.push(u(` ${s.skipped.length} could not be applied automatically (${s.skipped[0].reason}) \u2014 left for the editor pass.`)),{fixed:s.fixed.length,skipped:s.skipped.length,lines:i,paths:s.paths}}function op(e,t,n){let o=Nn(n.filter(a=>!(pn(a)&&a.baselined)),t);if(o.length===0)return null;let r=t.find(a=>!a.startsWith("--")),s=ei(t,r),i=nT(o);return i.length<=1?{kind:"single",prompt:Rl(o),display:s,findings:o.length}:{kind:"partitioned",partitions:i,display:s,articles:new Set(o.map(a=>a.path)).size,findings:o.length,promptFor:a=>{let l=new Set(a.paths);return Rl(o.filter(c=>l.has(c.path)))}}}function rp(e,t,n){let o=t.find(l=>!l.startsWith("--")),r=o?` in ${o}`:"",s=n.filter(l=>!(pn(l)&&l.baselined)),i=new Set(s.map(l=>l.path)).size;return{lines:En(t)?s.length===0?[`\u2713 Nothing is blocking publishing${r} \u2014 no style errors at all.`]:[`\u2713 Nothing is blocking publishing${r}. The ${s.length} issue${s.length===1?"":"s"} left ${s.length===1?"is a warning or a suggestion":"are warnings and suggestions"}, which never block it.`,` /lint${o?` ${o}`:""} --fix clears ${s.length===1?"it":"those"} too \u2014 ${s.length} issue${s.length===1?"":"s"} across ${i} article${i===1?"":"s"}.`]:[`\u2713 Nothing to fix${r} \u2014 the docs are already clean.`],closed:Ke(e,ei(t,o))}}async function fT(e,t,n,o=[]){let{model:r}=sT(e.cwd,"standard");console.log(u(`Fixing ${t.findings} issue${t.findings===1?"":"s"} across ${t.articles} article${t.articles===1?"":"s"} in ${t.partitions.length} batches (\u2264${Hr} at once) on ${r}\u2026`));let s=[],i=Date.now(),a={aborted:!1,partitions:0,failed:0,notRun:0,producedNothing:!0};try{for await(let y of oT({cwd:e.cwd,partitions:t.partitions,promptFor:t.promptFor,concurrency:Hr,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:r}))if(y.type==="partition_status")y.status==="running"?console.log(u(` \u25B8 ${y.label} \u2014 fixing\u2026`)):y.status==="done"?console.log(X(` \u2713 ${y.label}`)):console.log(L(` \u2717 ${y.label}`));else if(y.type==="run_done"){let x=rT(t.partitions,y.results);a={aborted:!!y.aborted,partitions:t.partitions.length,failed:x.failed.length,notRun:x.notRun.length,...y.blocked?{blocked:y.blocked}:{},...y.allEmpty?{allEmpty:!0}:{},...y.bailedEmpty?{bailedEmpty:!0}:{}},console.log(u(dn(Wt(i,y.results,y.totalCostUsd)))),x.failed.length&&console.log(H(`\u26A0 ${x.failed.length} batch${x.failed.length===1?"":"es"} not fixed: ${x.failed.map(w=>w.label).join(", ")}`)),x.notRun.length&&console.log(H(`\u26A0 ${x.notRun.length} batch${x.notRun.length===1?"":"es"} never started \u2014 their articles are untouched.`)),y.blocked&&console.log(H(`\u26A0 ${y.blocked}`)),y.allEmpty&&console.log(H("\u26A0 No turn produced any work this run \u2014 nothing was changed.")),!y.allEmpty&&!y.blocked&&s.push(...x.covered)}}catch(y){return console.log(L(`Fix run failed: ${y.message}`)),{kind:"continue"}}if(s.length>0)try{iT(e.cwd,s,wt("lint"))}catch{}let l=tp({cwd:e.cwd,scope:n}).filter(y=>!y.baselined),c=Nn(l,o);console.log("");for(let y of ti(c))console.log(c.length===0?X(y):H(y));if(tn(a))for(let y of Ke(e.cwd,ei(o,n)))console.log(X(y));let h=Vs({cwd:e.cwd,after:c,before:t.findings,scope:n,blocked:En(o)});return console.log(""),console.log(u(h.text)),{kind:"continue",ownNext:!0}}async function sp(e,t){let n=e.includes("--fix"),o=e.find(a=>!a.startsWith("--")),r=o?` ${o}`:"",s=tp({cwd:t.cwd,scope:o});if(n){let a=oo(t.cwd,e,s);for(let h of a.lines)console.log(h);let l=a.fixed>0?tp({cwd:t.cwd,scope:o}):s,c=op(t.cwd,e,l);if(!c){let h=rp(t.cwd,e,l);console.log(X(h.lines[0]));for(let y of h.lines.slice(1))console.log(u(y));for(let y of h.closed)console.log(X(y));return{kind:"continue",ownNext:!0}}return c.kind==="partitioned"?fT(t,c,o,e):(console.log(u(`Fixing ${c.findings} doc issue${c.findings===1?"":"s"} (run /lint again after to confirm)\u2026`)),{kind:"forward-to-agent",prompt:c.prompt,display:c.display})}let i=Nn(s,e);console.log(u("Linting the docs (engine internals, unknown commands, stale facts, AI-tells, em dashes, callout shape)\u2026"));for(let a of ti(i,{full:e.includes("--full"),baselined:e.includes("--baselined")}))console.log(i.length===0?X(a):H(a));return i.length>0&&console.log(u(`Run /lint${r}${En(e)?" --blocked":""} --fix to have the agent correct these.`)),console.log(""),{kind:"continue",ownNext:i.length>0}}var Gw=async(e,t)=>{let n=Ys("check");return n&&console.log(u(`\u2192 ${n}`)),sp(e,t)};ae();import{readProjectConfig as mT,loadProfileMap as gT,resolveActiveProfile as yT,desiredCategoryOrder as wT,desiredArticleOrder as bT,DEFAULT_DOCS_DIR as kT}from"document360-engine";var ip=e=>e.replace(/\\/g,"/"),qw=e=>ip(e).split("/").pop()??e;function ap(e){let t=qw(e),n=t.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return n?n.charAt(0).toUpperCase()+n.slice(1):t}var $T=ap;function ni(e,t){try{let n=mT(e);if(!n)return[];let o=yT(e,t),r=gT(e,o.name);if(!r)return[];let s=ip(n.docsDir??kT).replace(/\/+$/,""),i=new Map;for(let l of bT(r))i.set(l.categoryPath,(i.get(l.categoryPath)??0)+1);let a=[];for(let l of wT(r)){let c=ip(l.path),h=c.startsWith(`${s}/`)?c.slice(s.length+1):c===s?"":c;h&&a.push({token:h,label:$T(qw(c)),count:i.get(l.path)??0})}return a}catch{return[]}}function Vw(e,t){let n=ni(e,t);return n.length===0?["No categories yet \u2014 author some articles first, then scope to one."]:["Which category? Re-run with one of:",...n.map(o=>` --scope ${o.token} (${o.label} \xB7 ${o.count} article${o.count===1?"":"s"})`)]}function ro(e,t){if(t.includes("--all")||t.includes("--blocked")||t.includes("--stale")||t.some(n=>n.startsWith("--scope="))||t.includes("--scope")&&!oi(t))return!1;for(let n=0;n<t.length;n++){let o=t[n];if(o.startsWith("--")){vT.has(o)&&n++;continue}return!1}return e==="write"?!t.includes("--preview")&&!t.includes("--dry-run"):e==="review"||e==="reorder"}var vT=new Set(["--scope","--concurrency"]);function Gr(e,t,n,o,r){if(r=r??ni(e,o),r.length<=1)return[];let s=n.filter(c=>c.startsWith("--")).join(" "),i=s?` ${s}`:"",a=`/${t}${i} --all`.replace(/\s+/g," "),l=c=>t==="write"?`/write --scope ${c}${i}`:`/${t} ${c}${i}`;return[`Bare /${t} covers the WHOLE knowledge base (${r.reduce((c,h)=>c+h.count,0)} articles). Pick a target:`,` ${a} (everything)`,...r.map(c=>` ${l(c.token)} (${c.label} \xB7 ${c.count} article${c.count===1?"":"s"})`)]}function oi(e){let t=e.indexOf("--scope");if(t===-1)return!1;let n=e[t+1];return n===void 0||n.startsWith("-")}function Yw(e,t){let n=e.indexOf("--scope");if(n===-1)return["--scope",t,...e];let o=e[n+1],r=[...e];return o===void 0||o.startsWith("-")?r.splice(n+1,0,t):r[n+1]=t,r}var MT=3,_T=8;function cp(e){return e===void 0||!Number.isFinite(e)?MT:Math.max(1,Math.min(Math.floor(e),_T))}function ri(e){let t,n,o=!1,r=!1,s,i=l=>{let c=Number(l);return l!==void 0&&Number.isFinite(c)?c:void 0};for(let l=0;l<e.length;l++){let c=e[l];if(c==="--preview"||c==="--dry-run")o=!0;else if(c==="--rewrite"||c==="--force")r=!0;else{if(c==="--run"||c==="--yes"||c==="--all")continue;c==="--scope"?t=e[++l]:c?.startsWith("--scope=")?t=c.slice(8):c==="--concurrency"?s=i(e[++l]):c?.startsWith("--concurrency=")?s=i(c.slice(14)):c&&!c.startsWith("--")&&(n=c)}}let a=l=>l?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:a(t),path:a(n),preview:o,concurrency:s,rewrite:r}}function UT(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function FT(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function up(e,t,n){let o=new Map(t.map(r=>[r.path,r]));return n.map(r=>{let s=1;for(let i of o.get(r)?.sources??[])try{s+=xT(RT(e,i)).size}catch{}return{path:r,bytes:s}})}function dp(e,t,n={}){let o=n.rewrite?"- Some or all of these articles ALREADY EXIST on disk \u2014 this is a re-author (rewrite/upgrade), NOT a first draft. For any that exist, do NOT preserve or lightly-edit the current file: RE-AUTHOR it from scratch against the plan + sources + the active doc-type playbook standard. The existing file is what you're replacing, and its structure is NOT the target; match only the project's voice/terminology.\n- PRESERVE REVIEWER ANCHORS. If the existing file contains `:comment[some text]{id=\"\u2026\"}` markers, each one is where a reviewer left a comment. Carry every marker into your new text, wrapping whatever passage now makes the point the old one made, and keep its `id` exactly. Dropping a marker silently detaches that reviewer's comment from the article \u2014 they keep the note and lose the place.\n":"",r=n.reviewerNotes?.trim()?`
|
|
392
392
|
WHAT REVIEWERS HAVE ASKED FOR ON THESE ARTICLES \u2014 apply each one as you write. These are real comments from the people who own these docs, so an article that ignores them will simply come back:
|
|
393
393
|
`+n.reviewerNotes.trim()+`
|
|
394
394
|
`:"",s=n.openGaps?.trim()?`
|
|
@@ -406,209 +406,209 @@ QUESTIONS ALREADY RAISED ABOUT THESE ARTICLES (waiting on a person). Someone has
|
|
|
406
406
|
- Each article is independent. Do NOT write, edit, or publish any article not in this list, and do NOT publish to Document360; these are local drafts.
|
|
407
407
|
Articles:
|
|
408
408
|
`+e.paths.map(a=>`- ${a}`).join(`
|
|
409
|
-
`)+r+s}function dp(e,t,n){let o=e.reduce((i,a)=>i+a.paths.length,0),[r,s]=t.usd;return[`Write ${o} article${o===1?"":"s"} in ${e.length} batch${e.length===1?"":"es"} (\u2264${n} agents at once):`,...e.map(i=>` \u2022 ${i.label} \u2014 ${i.paths.length} article${i.paths.length===1?"":"s"}`),"",`Estimated cost: ${xt(r)}\u2013${xt(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function pp(e,t,n,o){let r=P=>t[P.index]?.paths.length??0,s=e.filter(P=>P.ok),i=e.filter(P=>!P.ok),a=e.reduce((P,T)=>P+r(T),0),l=s.reduce((P,T)=>P+r(T),0),c=e.reduce((P,T)=>P+T.costUsd,0),h=e.reduce((P,T)=>P+T.outputTokens,0),y=n==="api"?`${xt(c)} total`:Wr(h),x=`${s.length}/${e.length} batch${e.length===1?"":"es"} completed`,w=P=>`${P} article${P===1?"":"s"}`,S=[];if(i.length===0){S.push(`Wrote ${w(a)} (${x}) successfully \xB7 ${y}.`);let P=o?` ${o}`:"",T=o?"/push":"/push --all",R=o?`/screenshot author ${o}`:"/screenshot author --all";S.push("Next \u2014 an editorial review, because these were written by an AI:"),S.push(`/review${P} --fix`),S.push(`It reads every article and applies its fixes; ${T} then pushes them up (add screenshots first with ${R} if you want them).`)}else{S.push(`Wrote ${l}/${w(a)} (${x}) \xB7 ${y}.`),S.push(`${i.length} batch${i.length===1?"":"es"} failed \u2014 re-run /write${o?` --scope ${o}`:""} to retry the rest:`);for(let P of i)S.push(` \u2717 ${P.label}${P.error?` \u2014 ${P.error}`:""}`);i.some(P=>/rate-limited/i.test(P.error??""))&&(S.push("Claude rate-limited this run, not your usage allowance. Retry one batch at a time:"),S.push(`/write${o?` --scope ${o}`:""} --concurrency 1`)),i.some(P=>/usage limit has been reached/i.test(P.error??""))&&S.push(yT)}return S}function Gr(e,t,n){try{return bT({cwd:e,paths:n.map(o=>`${t}/${o}`)}).filter(o=>!o.baselined)}catch{return[]}}function hp(e){if(e.length===0)return null;let t=new Set(e.map(r=>r.path)).size,n=e.filter(r=>r.severity==="error").length,o=n>0?`${n} of them error${n===1?"":"s"} \u2014 `:"";return`\u26A0 Lint: ${e.length} issue${e.length===1?"":"s"} in ${t} of the new article${t===1?"":"s"} (${o}/lint --fix corrects them).`}function fp(e){let t=e.filter(o=>o.severity==="error");if(t.length===0)return null;let n=kT(t);return n.length===0?null:{errors:t,partitions:n,articles:new Set(t.map(o=>o.path)).size,promptFor:o=>{let r=new Set(o.paths);return xl(t.filter(s=>r.has(s.path)))}}}function mp(e,t){let n=t.filter(r=>r.severity==="error").length,o=t.length-n;return n===0?[`\u2713 Style: all ${e} error${e===1?"":"s"} fixed.${o>0?` ${o} warning${o===1?"":"s"}/suggestion${o===1?"":"s"} remain \u2014 /lint lists them.`:""}`]:[`\u26A0 Style: ${n} of ${e} error${e===1?"":"s"} remain, in ${new Set(t.filter(r=>r.severity==="error").map(r=>r.path)).size} article(s).`," /lint --blocked --fix retries them. Exactly one automatic pass runs, so a loop can never spin here."]}function Rl(e,t,n){let o=(ap(e)?.docsDir??Kw).replace(/\/+$/,""),r=t.map(a=>a.path);if(n.path){let a=NT(n.path,o);return r.includes(a)?{docsDir:o,targets:[a],planCount:r.length}:{docsDir:o,targets:[],planCount:r.length,reason:`"${a}" isn't in the docs plan (.d360-writer/plan.json).`}}let s=DT(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 i=Xn(e,o,s);if(i.length===0){let a=n.scope?` under "${n.scope}"`:"",l=n.scope?` --scope ${n.scope}`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${a} are already written. Use /write <path> to rewrite one, or /write${l} --rewrite to regenerate them all.`}}return{docsDir:o,targets:i,planCount:r.length}}function gp(e,t,n){let{targets:o}=Rl(e,t,{rewrite:n?.rewrite}),r=new Map;for(let s of o){let i=s.split("/");if(i.length<2)continue;let a=i[0];r.set(a,(r.get(a)??0)+1)}return[...r].map(([s,i])=>({token:s,label:ip(s),count:i}))}async function zw(e,t){if(!ap(t.cwd))return console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"};if(ti(e)){for(let Q of Bw(t.cwd,t.profileName))console.log(u(Q));return{kind:"continue"}}let n=vT(t.cwd,(ap(t.cwd)?.docsDir??Kw).replace(/\/+$/,""));if(n.length===0)return console.log(L("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};if(no("write",e)){let Q=gp(t.cwd,n,{rewrite:ni(e).rewrite}),j=Hr(t.cwd,"write",e,t.profileName,Q);if(j.length>0){for(let ne of j)console.log(u(ne));return{kind:"continue"}}}let{scope:o,path:r,preview:s,concurrency:i,rewrite:a}=ni(e),{docsDir:l,targets:c,reason:h,rewriting:y}=Rl(t.cwd,n,{scope:o,path:r,rewrite:a});if(c.length===0)return console.log(h?H(h):H("Nothing to write.")),{kind:"continue"};y&&console.log(H(`--rewrite: regenerating ${c.length} already-written article${c.length===1?"":"s"} (overwrites them; git has your baseline).`));let x=$T(c),w=lp(i),{model:S,forced:P}=Gw(t.cwd,"standard"),T=!!r;if(s&&!T){let Q=wT({files:cp(t.cwd,n,c),op:"write",model:S});o&&console.log(u(`Scope: ${o} (${c.length} pending).`));for(let j of dp(x,Q,w))console.log(j);return console.log(u(`Model: ${S}${P?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(u(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}let R=xT(t.cwd),N=ST(t.cwd),B=c.filter(Q=>PT(R,Q).length>0).length;B>0&&console.log(u(` ${B} of these ${B===1?"has":"have"} reviewer comments \u2014 the writer gets them.`)),console.log(u(`Writing ${c.length} article${c.length===1?"":"s"} in ${x.length} batch${x.length===1?"":"es"} (\u2264${w} agents at once) on ${S}\u2026`)),console.log(u(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let G=Date.now();try{for await(let Q of qw({cwd:t.cwd,partitions:x,promptFor:j=>up(j,l,{rewrite:y||T,reviewerNotes:RT(R,j.paths),openGaps:CT(t.cwd,j.paths),readerContract:N}),concurrency:w,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:S}))if(Q.type==="partition_status")Q.status==="running"?console.log(u(` \u25B8 ${Q.label} \u2014 writing\u2026`)):Q.status==="done"?console.log(X(` \u2713 ${Q.label}`)):console.log(L(` \u2717 ${Q.label}`));else if(Q.type==="run_done"){console.log("");let j=process.env.ANTHROPIC_API_KEY?"api":"subscription",ne=Jn(Q,"The write");if(ne){for(let ge of ne)console.log(H(ge));continue}for(let ge of pp(Q.results,x,j,o??r))console.log(Q.ok?X(ge):H(ge));if(console.log(u(un(_t(G,Q.results,Q.totalCostUsd)))),Q.ok)try{Yw(t.cwd,c.map(ge=>`${l}/${ge}`),{writtenCap:TT,reviewedCap:0,checkedCap:0})}catch{}let te=Gr(t.cwd,l,c),ye=hp(te);ye&&console.log(H(ye));let $e=e.includes("--skip-style")?null:fp(te);if($e){console.log(u(`Fixing ${$e.errors.length} style error(s) in ${$e.articles} article(s) \u2014 one pass\u2026`));let{model:ge}=Gw(t.cwd,"standard"),be=[];try{for await(let ee of qw({cwd:t.cwd,partitions:$e.partitions,promptFor:$e.promptFor,concurrency:3,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:ge}))if(ee.type==="partition_status"&&ee.status!=="running")console.log(ee.status==="done"?X(` \u2713 ${ee.label}`):L(` \u2717 ${ee.label}`));else if(ee.type==="run_done"&&!ee.allEmpty&&!ee.blocked){let Ee=Vw($e.partitions,ee.results);Ee.notRun.length&&console.log(H(`\u26A0 ${Ee.notRun.length} style-fix batch${Ee.notRun.length===1?"":"es"} never started \u2014 their articles are untouched.`)),be.push(...Ee.covered)}}catch(ee){console.log(H(`Style fix pass failed: ${ee.message}`))}if(be.length>0)try{Yw(t.cwd,be,yt("lint"))}catch{}for(let ee of mp($e.errors.length,Gr(t.cwd,l,c)))console.log(ee.startsWith("\u2713")?X(ee):H(ee))}{let ge=Vw(x,Q.results),be={aborted:!!Q.aborted,partitions:x.length,failed:ge.failed.length,notRun:ge.notRun.length,leftBehind:Gr(t.cwd,l,c).filter(ee=>ee.severity==="error").length,...Q.blocked?{blocked:Q.blocked}:{},...Q.allEmpty?{allEmpty:!0}:{},...Q.bailedEmpty?{bailedEmpty:!0}:{}};if(Jt(be)){let ee=`/write${o?` --scope ${o}`:""}${e.includes("--rewrite")?" --rewrite":""}`;for(let Ee of Ye(t.cwd,ee))console.log(X(Ee))}}}}catch(Q){console.log(L(`Write run failed: ${Q.message}`))}return console.log(""),{kind:"continue"}}ie();import{existsSync as jT,readdirSync as Xw,statSync as Qw}from"node:fs";import{join as Jw}from"node:path";import{inputDir as IT,readProjectConfig as LT}from"document360-engine";var Zw=/\.(md|markdown|pdf|txt)$/i;function yp(e){let t=IT(e);if(!jT(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of Xw(t)){let s=Jw(t,r),i=!1;try{i=Qw(s).isDirectory()}catch{continue}if(i){if(r.startsWith("."))continue;let a=OT(s);a>0&&n.push({name:r,docCount:a})}else Zw.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function OT(e){let t=0;for(let n of Xw(e))try{Qw(Jw(e,n)).isFile()&&Zw.test(n)&&t++}catch{}return t}function wp(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 Sl(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, and 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(`
|
|
410
|
-
`)}var
|
|
411
|
-
`)}var
|
|
412
|
-
`)}function
|
|
409
|
+
`)+r+s}function pp(e,t,n){let o=e.reduce((i,a)=>i+a.paths.length,0),[r,s]=t.usd;return[`Write ${o} article${o===1?"":"s"} in ${e.length} batch${e.length===1?"":"es"} (\u2264${n} agents at once):`,...e.map(i=>` \u2022 ${i.label} \u2014 ${i.paths.length} article${i.paths.length===1?"":"s"}`),"",`Estimated cost: ${St(r)}\u2013${St(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function hp(e,t,n,o){let r=P=>t[P.index]?.paths.length??0,s=e.filter(P=>P.ok),i=e.filter(P=>!P.ok),a=e.reduce((P,T)=>P+r(T),0),l=s.reduce((P,T)=>P+r(T),0),c=e.reduce((P,T)=>P+T.costUsd,0),h=e.reduce((P,T)=>P+T.outputTokens,0),y=n==="api"?`${St(c)} total`:Br(h),x=`${s.length}/${e.length} batch${e.length===1?"":"es"} completed`,w=P=>`${P} article${P===1?"":"s"}`,S=[];if(i.length===0){S.push(`Wrote ${w(a)} (${x}) successfully \xB7 ${y}.`);let P=o?` ${o}`:"",T=o?"/push":"/push --all",R=o?`/screenshot author ${o}`:"/screenshot author --all";S.push("Next \u2014 an editorial review, because these were written by an AI:"),S.push(`/review${P} --fix`),S.push(`It reads every article and applies its fixes; ${T} then pushes them up (add screenshots first with ${R} if you want them).`)}else{S.push(`Wrote ${l}/${w(a)} (${x}) \xB7 ${y}.`),S.push(`${i.length} batch${i.length===1?"":"es"} failed \u2014 re-run /write${o?` --scope ${o}`:""} to retry the rest:`);for(let P of i)S.push(` \u2717 ${P.label}${P.error?` \u2014 ${P.error}`:""}`);i.some(P=>/rate-limited/i.test(P.error??""))&&(S.push("Claude rate-limited this run, not your usage allowance. Retry one batch at a time:"),S.push(`/write${o?` --scope ${o}`:""} --concurrency 1`)),i.some(P=>/usage limit has been reached/i.test(P.error??""))&&S.push(ST)}return S}function qr(e,t,n){try{return PT({cwd:e,paths:n.map(o=>`${t}/${o}`)}).filter(o=>!o.baselined)}catch{return[]}}function fp(e){if(e.length===0)return null;let t=new Set(e.map(r=>r.path)).size,n=e.filter(r=>r.severity==="error").length,o=n>0?`${n} of them error${n===1?"":"s"} \u2014 `:"";return`\u26A0 Lint: ${e.length} issue${e.length===1?"":"s"} in ${t} of the new article${t===1?"":"s"} (${o}/lint --fix corrects them).`}function mp(e){let t=e.filter(o=>o.severity==="error");if(t.length===0)return null;let n=TT(t);return n.length===0?null:{errors:t,partitions:n,articles:new Set(t.map(o=>o.path)).size,promptFor:o=>{let r=new Set(o.paths);return Rl(t.filter(s=>r.has(s.path)))}}}function gp(e,t){let n=t.filter(r=>r.severity==="error").length,o=t.length-n;return n===0?[`\u2713 Style: all ${e} error${e===1?"":"s"} fixed.${o>0?` ${o} warning${o===1?"":"s"}/suggestion${o===1?"":"s"} remain \u2014 /lint lists them.`:""}`]:[`\u26A0 Style: ${n} of ${e} error${e===1?"":"s"} remain, in ${new Set(t.filter(r=>r.severity==="error").map(r=>r.path)).size} article(s).`," /lint --blocked --fix retries them. Exactly one automatic pass runs, so a loop can never spin here."]}function Sl(e,t,n){let o=(lp(e)?.docsDir??Jw).replace(/\/+$/,""),r=t.map(a=>a.path);if(n.path){let a=UT(n.path,o);return r.includes(a)?{docsDir:o,targets:[a],planCount:r.length}:{docsDir:o,targets:[],planCount:r.length,reason:`"${a}" isn't in the docs plan (.d360-writer/plan.json).`}}let s=FT(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 i=Jn(e,o,s);if(i.length===0){let a=n.scope?` under "${n.scope}"`:"",l=n.scope?` --scope ${n.scope}`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${a} are already written. Use /write <path> to rewrite one, or /write${l} --rewrite to regenerate them all.`}}return{docsDir:o,targets:i,planCount:r.length}}function yp(e,t,n){let{targets:o}=Sl(e,t,{rewrite:n?.rewrite}),r=new Map;for(let s of o){let i=s.split("/");if(i.length<2)continue;let a=i[0];r.set(a,(r.get(a)??0)+1)}return[...r].map(([s,i])=>({token:s,label:ap(s),count:i}))}async function Zw(e,t){if(!lp(t.cwd))return console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"};if(oi(e)){for(let Q of Vw(t.cwd,t.profileName))console.log(u(Q));return{kind:"continue"}}let n=ET(t.cwd,(lp(t.cwd)?.docsDir??Jw).replace(/\/+$/,""));if(n.length===0)return console.log(L("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};if(ro("write",e)){let Q=yp(t.cwd,n,{rewrite:ri(e).rewrite}),N=Gr(t.cwd,"write",e,t.profileName,Q);if(N.length>0){for(let ne of N)console.log(u(ne));return{kind:"continue"}}}let{scope:o,path:r,preview:s,concurrency:i,rewrite:a}=ri(e),{docsDir:l,targets:c,reason:h,rewriting:y}=Sl(t.cwd,n,{scope:o,path:r,rewrite:a});if(c.length===0)return console.log(h?H(h):H("Nothing to write.")),{kind:"continue"};y&&console.log(H(`--rewrite: regenerating ${c.length} already-written article${c.length===1?"":"s"} (overwrites them; git has your baseline).`));let x=AT(c),w=cp(i),{model:S,forced:P}=Kw(t.cwd,"standard"),T=!!r;if(s&&!T){let Q=CT({files:up(t.cwd,n,c),op:"write",model:S});o&&console.log(u(`Scope: ${o} (${c.length} pending).`));for(let N of pp(x,Q,w))console.log(N);return console.log(u(`Model: ${S}${P?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(u(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}let R=NT(t.cwd),D=jT(t.cwd),B=c.filter(Q=>LT(R,Q).length>0).length;B>0&&console.log(u(` ${B} of these ${B===1?"has":"have"} reviewer comments \u2014 the writer gets them.`)),console.log(u(`Writing ${c.length} article${c.length===1?"":"s"} in ${x.length} batch${x.length===1?"":"es"} (\u2264${w} agents at once) on ${S}\u2026`)),console.log(u(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let G=Date.now();try{for await(let Q of zw({cwd:t.cwd,partitions:x,promptFor:N=>dp(N,l,{rewrite:y||T,reviewerNotes:DT(R,N.paths),openGaps:IT(t.cwd,N.paths),readerContract:D}),concurrency:w,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:S}))if(Q.type==="partition_status")Q.status==="running"?console.log(u(` \u25B8 ${Q.label} \u2014 writing\u2026`)):Q.status==="done"?console.log(X(` \u2713 ${Q.label}`)):console.log(L(` \u2717 ${Q.label}`));else if(Q.type==="run_done"){console.log("");let N=process.env.ANTHROPIC_API_KEY?"api":"subscription",ne=eo(Q,"The write");if(ne){for(let ye of ne)console.log(H(ye));continue}for(let ye of hp(Q.results,x,N,o??r))console.log(Q.ok?X(ye):H(ye));if(console.log(u(dn(Wt(G,Q.results,Q.totalCostUsd)))),Q.ok)try{Qw(t.cwd,c.map(ye=>`${l}/${ye}`),{writtenCap:OT,reviewedCap:0,checkedCap:0})}catch{}let te=qr(t.cwd,l,c),he=fp(te);he&&console.log(H(he));let we=e.includes("--skip-style")?null:mp(te);if(we){console.log(u(`Fixing ${we.errors.length} style error(s) in ${we.articles} article(s) \u2014 one pass\u2026`));let{model:ye}=Kw(t.cwd,"standard"),ke=[];try{for await(let ee of zw({cwd:t.cwd,partitions:we.partitions,promptFor:we.promptFor,concurrency:3,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:ye}))if(ee.type==="partition_status"&&ee.status!=="running")console.log(ee.status==="done"?X(` \u2713 ${ee.label}`):L(` \u2717 ${ee.label}`));else if(ee.type==="run_done"&&!ee.allEmpty&&!ee.blocked){let Ee=Xw(we.partitions,ee.results);Ee.notRun.length&&console.log(H(`\u26A0 ${Ee.notRun.length} style-fix batch${Ee.notRun.length===1?"":"es"} never started \u2014 their articles are untouched.`)),ke.push(...Ee.covered)}}catch(ee){console.log(H(`Style fix pass failed: ${ee.message}`))}if(ke.length>0)try{Qw(t.cwd,ke,wt("lint"))}catch{}for(let ee of gp(we.errors.length,qr(t.cwd,l,c)))console.log(ee.startsWith("\u2713")?X(ee):H(ee))}{let ye=Xw(x,Q.results),ke={aborted:!!Q.aborted,partitions:x.length,failed:ye.failed.length,notRun:ye.notRun.length,leftBehind:qr(t.cwd,l,c).filter(ee=>ee.severity==="error").length,...Q.blocked?{blocked:Q.blocked}:{},...Q.allEmpty?{allEmpty:!0}:{},...Q.bailedEmpty?{bailedEmpty:!0}:{}};if(tn(ke)){let ee=`/write${o?` --scope ${o}`:""}${e.includes("--rewrite")?" --rewrite":""}`;for(let Ee of Ke(t.cwd,ee))console.log(X(Ee))}}}}catch(Q){console.log(L(`Write run failed: ${Q.message}`))}return console.log(""),{kind:"continue"}}ae();import{existsSync as WT,readdirSync as eb,statSync as tb}from"node:fs";import{join as nb}from"node:path";import{inputDir as BT,readProjectConfig as HT}from"document360-engine";var ob=/\.(md|markdown|pdf|txt)$/i;function wp(e){let t=BT(e);if(!WT(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of eb(t)){let s=nb(t,r),i=!1;try{i=tb(s).isDirectory()}catch{continue}if(i){if(r.startsWith("."))continue;let a=GT(s);a>0&&n.push({name:r,docCount:a})}else ob.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function GT(e){let t=0;for(let n of eb(e))try{tb(nb(e,n)).isFile()&&ob.test(n)&&t++}catch{}return t}function bp(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 Cl(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, and 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(`
|
|
410
|
+
`)}var kp="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function rb(e,t){let n=t?.cwd??process.cwd();if(!HT(n))return console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=wp(n);if(o.length===0&&r===0)return console.log(u(kp)),{kind:"continue"};let s=e.join(" ").trim();if(!s){if(o.length>1){console.log(u("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let l of o)console.log(` ${l.name} ${u(`(${l.docCount} doc${l.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let a=o[0]?.name??"";return{kind:"forward-to-agent",prompt:Cl(a),display:a?`/draft ${a}`:"/draft"}}let i=bp(o,s);return{kind:"forward-to-agent",prompt:Cl(i??"",i?void 0:s),display:`/draft ${s}`}}ae();import{listOpenForDocs as qT,readProjectConfig as VT}from"document360-engine";function $p(e){try{return qT(e).filter(t=>t.kind==="request").length}catch{return 0}}function vp(e){let t=e.includes("--push")||e.includes("--publish"),n=e.includes(_t),o=e.filter(r=>!r.startsWith("--")).join(" ").trim();return{push:t,skipReview:n,what:o}}function xp(e){let t=["Run the document-handoff skill.",""];return e?t.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: 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."):t.push("No description was given, so 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."),t.push("","Draft only; 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.join(`
|
|
411
|
+
`)}var Rp="Nothing to document yet. Say what changed: /document <what you shipped>, or have the builder drop a request via their /devhints hand-off.";async function sb(e,t){let n=t?.cwd??process.cwd();if(!VT(n))return console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"};let{push:o,what:r}=vp(e);if(!r&&$p(n)===0)return console.log(u(Rp)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --push":""}`;return{kind:"forward-to-agent",prompt:xp(r),display:s}}ae();import{search as YT}from"@inquirer/prompts";import{findByName as KT,getSession as zT,listSessions as XT,relativeTime as ab}from"document360-engine";async function lb(e,t){let n=XT(t.cwd).filter(o=>o.uuid!==t.currentUuid());if(n.length===0)return console.log(u("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=KT(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(L(`No session matches "${o}".`)),ib(n),{kind:"continue"})}if(!process.stdin.isTTY)return ib(n),console.log(u("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>YT({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let i=(s??"").toLowerCase();return n.filter(a=>!i||a.name.toLowerCase().includes(i)||a.firstPrompt.toLowerCase().includes(i)).map(a=>({name:`${a.name} ${ab(a.updatedAt)}`,value:a.uuid,description:a.firstPrompt.slice(0,100)}))}})),r=zT(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function ib(e){console.log("");for(let t of e.slice(0,15))console.log(` ${Z(t.name)} ${u(ab(t.updatedAt))}`),console.log(` ${u(t.firstPrompt.slice(0,80))}`);console.log("")}ae();import{renameSession as QT}from"document360-engine";function Sp(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 cb(e,t){let n=Sp(e.join(" "));if(!n)return console.log(L("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(QT(o,n)?console.log(X(`\u2713 Session renamed to "${n}"`)):console.log(L("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(X(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{currentEnvironments as JT,environmentIsProduction as ZT,isKnownEnvironment as eA,readProjectConfig as tA,resolveEnvironment as nA,writeProjectConfig as oA}from"document360-engine";ae();function Pl(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=tA(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 eA(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r}}},oA(o,e),null):[`Unknown environment "${r}". Known: ${JT().join(", ")}`,"Add a deployment this build does not ship: d360-writer env add <file.json>","Or give this profile explicit URLs in .d360-writer/config.json."].join(`
|
|
412
|
+
`)}function Tl(e,t){let n=[`\u2713 Profile "${e}" created \u2014 ${nA(t).portalUrl}`];return ZT(t)&&n.push(`\u26A0 ${t} is a live deployment. Drafts save freely; taking articles live needs /allow-prod.`),n}async function ub(e,t){let n=e[0];if(!n)return ha(t.cwd),{kind:"continue"};if(n==="add"){let o=Pl(t.cwd,e[1],e[2]);if(o)return console.log(L(o)),{kind:"continue"};let r=e[1],s=e[2]??r,[i,...a]=Tl(r,s);console.log(X(i));for(let l of a)console.log(H(l));return console.log(` Switch + sign in: ${Z(`/profile ${r}`)} then ${Z("/login")}`),console.log(u(" Until you switch, this repo keeps using the current profile\u2019s environment.")),{kind:"continue"}}return fa(t.cwd,n),ma(t.cwd,n),console.log(u(" Restarting agent for the new profile\u2026")),{kind:"clear"}}ae();import{select as rA}from"@inquirer/prompts";import{readProjectConfig as sA,readUserConfig as db,resolveModelSetting as Cp,writeUserConfig as pb}from"document360-engine";var Bt=[{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 Al(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=Bt.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function iA(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 si(e,t){let n=()=>Cp(e).model;if(t==="default"){let s=db();return s.defaultModel?(delete s.defaultModel,pb(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${Cp(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}}pb({...db(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=sA(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 hb(e,t){let n=e[0]?.trim();if(!n){let i=Cp(t.cwd);if(!process.stdin.isTTY)return console.log(`${Je("Model:")} ${Z(i.model)}${i.source==="auto"?u(" (auto)"):""}`),console.log(u(` source: ${iA(i)}`)),console.log(u(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let a=Al(i),l;try{l=await t.withPausedInput(()=>rA({message:`Select model (current: ${i.model}${i.source==="auto"?" \xB7 auto":""})`,default:Bt[a].value,choices:Bt.map((x,w)=>({name:`${x.label}${w===a?" \u2714":""}`,value:x.value,description:x.desc}))}))}catch{return console.log(u("Cancelled.")),{kind:"continue"}}let{lines:c,changed:h,effective:y}=si(t.cwd,l??"default");for(let x of c)console.log(x.startsWith("\u26A0")?H(x):x.startsWith("\u2713")?X(x):u(x));return h&&await t.setModel(y),{kind:"continue"}}let{lines:o,changed:r,effective:s}=si(t.cwd,n);for(let i of o)console.log(i.startsWith("\u26A0")?H(i):i.startsWith("\u2713")?X(i):u(i));return r&&await t.setModel(s),{kind:"continue"}}Dl();async function wb(e,t){return await t.withPausedInput(()=>Sr(t.cwd)),{kind:"clear"}}async function bb(e,t){return await t.withPausedInput(()=>ua(t.cwd,t.profileName)),{kind:"clear"}}ae();import{resolveActiveProfile as OA}from"document360-engine";async function kb(e,t){let n=!1;try{n=OA(t.cwd).production}catch{}return n?(console.log(H("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(u("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}ae();var $b=async(e,t)=>{try{await t.withPausedInput(()=>pa({}))}catch(n){if(console.log(L(`Login failed: ${n.message}`)),!Da(t.cwd,t.profileName))return console.log(u("Your Document360 session still isn't working \u2014 run /login to try again.")),{kind:"continue",ownNext:!0}}return{kind:"continue"}};qn();ae();import{resolveActiveProfile as MA,clearTokens as _A,clearProfileProject as UA,listStoredSessions as FA,tokensProjectId as WA}from"document360-engine";async function vb(e,t){let n,o,r,s;try{let y=MA(t.cwd,t.profileName);n=y.name,o=y.connection.name,r=y.project.projectId,s=y.project.projectName}catch(y){return console.log(L(y.message)),{kind:"continue"}}let i=e.includes("--all-projects"),a=FA(n).filter(y=>{let x=WA(y);return!!x&&x!==r}).length,l=_A(n,i?void 0:r);UA(t.cwd,n);let c=i||a===0?"":` Your sign-in for ${a} other project${a===1?"":"s"} is untouched (/logout --all-projects clears those too).`;console.log(l?i?X(`\u2713 Signed out of every Document360 project for "${n}" and cleared this repo's project/workspace selection.`):X(`\u2713 Signed out of ${s?`"${s}"`:`"${n}"`} and cleared its project/workspace selection.${c}`):u(`Profile "${n}" was not signed in. Cleared any project/workspace selection.${c}`)),console.log(u(`Run /login to sign back in to "${n}" (the ${o} environment) and pick a project.`));let h=Hn(t.cwd,t.profileName);return console.log(h?H(`\u26A0 ${h.why}. Signing out doesn\u2019t change the environment \u2014 ${h.cmd} does.`):u(" Different environment? That comes from the profile, not the login \u2014 /profile add <environment>.")),{kind:"continue"}}import{existsSync as Sb,readFileSync as Ap}from"node:fs";import{homedir as XA}from"node:os";import{basename as QA,join as ci}from"node:path";import{readProjectConfig as JA,DEFAULT_OUTPUT_DIR as ZA,existingAnnotatedShotPath as ZW,resolveOutputDir as eE,shotArtifacts as tE}from"document360-engine";import Ct from"picocolors";import{annotationsPath as BA,resolveOutputDir as HA,readProjectConfig as GA,DEFAULT_OUTPUT_DIR as qA,existingAnnotatedShotPath as VA}from"document360-engine";function YA(e){let n=e.filter(o=>o!=="--all"&&o!=="-a").find(o=>!o.startsWith("-"));return n?{mode:"single",id:n}:{mode:"all"}}function ai(e){return e.filter(t=>t.state==="annotated").map(t=>t.id)}function hn(e,t){let n=HA(e,GA(e)?.outputDir??qA),o=new Map(He(e).map(i=>[i.id,i])),r=i=>i.replace(`${e}\\`,"").replace(`${e}/`,"").replace(/\\/g,"/"),s=t.map(i=>{let a=o.get(i)?.file??"(unknown article)";return[`- ${i}`,` image: ${r(VA(n,i))}`,` facts: ${r(BA(n,i))}`,` article: ${a}`].join(`
|
|
413
413
|
`)}).join(`
|
|
414
414
|
`);return[`Run the review-screenshots skill over ${t.length} newly captured screenshot${t.length===1?"":"s"}.`,"","For EACH shot below:","1. READ THE IMAGE FILE. Actually look at the picture; this judgment cannot be made from the spec"," source or the JSON alone.","2. Read its facts JSON (the `capture` block records what the capture observed: image dimensions,"," crop origin, whether the origin was inferred rather than declared, selectors that never resolved,"," boxes that fell outside the frame, how many elements each highlight/redaction selector covered,"," and whether the page was still loading when the shutter fired).","3. Read the article to see what the placeholder promises the reader at that point.","4. Record a verdict with d360_verify_screenshot; every shot gets exactly one call.",' On "rejected": give a one-line plain-language reason, then FIX THE SPEC that produced it and pass'," repaired: true. Do not re-run the capture yourself; the user does that.","",s,"","Then report to the user briefly: ONE line per rejected shot naming the defect in plain words and what","you changed. Do NOT state counts, totals, or the re-capture command; an exact receipt is printed from","your recorded verdicts right after your report, so any number you state can only contradict it."].join(`
|
|
415
|
-
`)}function
|
|
416
|
-
${
|
|
417
|
-
`)}function
|
|
418
|
-
`):
|
|
419
|
-
`)}var
|
|
420
|
-
`)}function
|
|
421
|
-
/screenshot list --detail shows what each one needs`}function
|
|
422
|
-
`),cmd:o.length>0?`/screenshot ${l}`:r.length>0?h:t.length>0?i:a,tone:o.length>0||r.length>0?"warn":"info"}}function
|
|
423
|
-
Check them when you're ready: ${Ce("/screenshot verify","",i)}`),{kind:"continue"};let
|
|
424
|
-
`),display:"/screenshot checklist"}}function
|
|
425
|
-
`)}async function
|
|
426
|
-
`).map(s=>s.trim()).filter(Boolean).slice(-1)[0];return r?` \u2014 ${r}`:""};switch(e){case"no-git":return"This folder is not a git repository, so there is nowhere to share to. Your docs are still saved on this machine.";case"detached-head":return"This repo is not on a branch right now. Ask your builder to check out a branch, then run /share.";case"mid-operation":return"A merge or rebase is in progress here. Finish or cancel it first, then run /share.";case"no-upstream":return"This branch has no remote yet, so there is nowhere to send your work. Ask your builder to run: git push -u origin HEAD";case"disabled":return"Sharing is switched off for this repo. Turn it on: /share on";case"diverged":return"Your work and your builder's have both moved on, so they can't be combined automatically. Your work is committed and safe \u2014 ask your builder to merge the branch.";case"rejected":return"Someone pushed to this branch first, so your work could not be sent. It IS committed and safe \u2014 try /share again in a moment, or ask your builder to merge the branch.";case"auth":return"Git could not sign in to the remote. Ask your builder to set up your git credentials, then run /share.";case"network":return"Could not reach the remote. Check your connection, then run /share again.";case"hook-failed":return`This repo's own commit checks rejected the change${n(t)}. Ask your builder to take a look \u2014 your docs are safe on this machine.`;case"failed":return`Git could not finish the share${n(t)}. Your docs are safe on this machine \u2014 run /share to try again, or show this line to your builder.`}}function Il(e,t){let n=Bb(t);if(!n.commit)return[{tone:"info",text:"Sharing: off \u2014 d360-writer leaves its work for your coding agent to commit."},{tone:"info",text:"Turn it on: /share on"}];let o=vE(e);if(!o)return[{tone:"info",text:"Sharing: unavailable \u2014 this folder is not a git repository."}];if(!o.upstream)return[{tone:"warn",text:V("\u26A0")+`This branch (${o.branch??"detached"}) has no remote, so your work can't reach your team yet.`},{tone:"info",text:"Ask your builder to run: git push -u origin HEAD"}];let r=n.push===!0?"on":n.push==="unconfirmed"?"not set up yet":"off",s=[{tone:"info",text:`Sharing: ${o.branch} \u2192 ${o.upstream} \xB7 saving: on \xB7 sending: ${r}`}];return o.ahead>0?s.push({tone:"warn",text:V("\u26A0")+`${o.ahead} change${di(o.ahead)} not shared yet \u2014 run /share`}):s.push({tone:"ok",text:V("\u2713")+"Everything is shared with your team."}),s}function Yp(e,t,n){Wb({...t,gitHandoff:{commit:n,push:n}},e);let o=n?{tone:"ok",text:V("\u2713")+"Sharing on \u2014 d360-writer will save and send its own work from now on."}:{tone:"ok",text:V("\u2713")+"Sharing off \u2014 d360-writer will leave its work for your coding agent to commit."};return n?[o,...Il(e,{...t,gitHandoff:{commit:!0,push:!0}})]:[o]}async function Ll(e,t){let n=[],o=Bb(t);if(!o.commit)return{lines:[{tone:"info",text:ro("disabled")}],changed:!1};let r=t;o.push==="unconfirmed"&&xE(e,t)&&(r={...t,gitHandoff:{commit:!0,push:!0}},Wb(r,e),n.push({tone:"info",text:"Sharing is now set up for this repo \u2014 d360-writer will keep doing this automatically."}));let s=await $E(e);if(s.ok&&s.pulled>0){let c=[s.newHints>0?`${s.newHints} new hint${di(s.newHints)}`:null,s.newMessages>0?`${s.newMessages} new message${di(s.newMessages)}`:null].filter(Boolean);n.push({tone:"ok",text:V("\u2B07")+`Got your builder's latest${c.length?` \u2014 ${c.join(", ")}`:""}.`})}else!s.ok&&s.reason!=="no-upstream"&&s.reason!=="no-git"&&n.push({tone:"warn",text:V("\u26A0")+ro(s.reason,s.detail)});let i=await kE(e,r);if(i.commit&&!i.commit.ok)return n.push({tone:"warn",text:V("\u26A0")+ro(i.commit.reason,i.commit.detail)}),{lines:n,changed:!1};let a=i.commit?.ok?i.commit.committed.length:0;if(a>0&&n.push({tone:"ok",text:V("\u2713")+`Saved ${a} change${di(a)} to the docs folder.`}),i.push&&!i.push.ok)return n.push({tone:"warn",text:V("\u26A0")+ro(i.push.reason,i.push.detail)}),{lines:n,changed:a>0};let l=i.push?.ok?i.push.pushed:0;return l>0?n.push({tone:"ok",text:V("\u2B06")+`Shared ${l} change set${di(l)} with your team.`}):a===0&&(s.ok&&s.pulled===0)?n.push({tone:"ok",text:V("\u2713")+"Everything is already shared with your team."}):a>0&&!i.push&&n.push({tone:"info",text:"Saved on this machine only. /share on lets d360-writer send it to your team too."}),{lines:n,changed:a>0||l>0||s.ok&&s.pulled>0}}var RE={ok:X,info:Ae,warn:H,error:L};async function Hb(e,t){let n=t.cwd,o=bE(n);if(!o)return console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase(),s=a=>{for(let l of a)console.log(RE[l.tone](l.text))};if(r==="status")return s(Il(n,o)),{kind:"continue"};if(r==="on"||r==="off")return s(Yp(n,o,r==="on")),{kind:"continue"};if(r)return console.log(L(`Unknown option "${r}". Use /share, /share status, /share on, or /share off.`)),{kind:"continue"};console.log(u("Exchanging work with your team\u2026"));let{lines:i}=await Ll(n,o);return s(i),{kind:"continue"}}function en(e){let t=0,n=0,o=0,r=0,s=0,i=0;try{let l=Vb(e,Gb(e));t=l.actionable.length,n=l.held.length,o=l.held.filter(c=>c.asked).length}catch{}try{let l=SE(e);r=l.filter(c=>c.kind==="request").length,s=l.filter(c=>c.kind==="answer").length}catch{}try{i=CE(e).length}catch{}let a=!1;try{a=ME(e)}catch{}return{hints:t,requests:r,answers:s,directives:i,held:n,heldAsked:o,briefMoved:a}}async function zp(e){let t=qb(e);if(!t)return[];if(!jE(e,t))return[];let n=await DE(e);if(n.ok){if(n.pulled===0)return[];let o=[n.newHints>0?`${n.newHints} new hint${n.newHints===1?"":"s"}`:null,n.newMessages>0?`${n.newMessages} new message${n.newMessages===1?"":"s"}`:null].filter(Boolean);return[{tone:"ok",text:`\u2B07 Got your builder's latest${o.length?` \u2014 ${o.join(", ")}`:""}.`}]}return n.reason==="no-upstream"||n.reason==="no-git"?[]:[{tone:"warn",text:`\u26A0 Couldn't get your builder's latest first \u2014 ${ro(n.reason,n.detail)}`}]}function Kr(e){let t=[];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"}`);let n=t.join(", ");return e.briefMoved?n?`${n} and an updated product brief`:"an updated product brief":n||null}function Xp(e){let t=Kr(e);return t?`Catching up on ${t}\u2026`:"Nothing queued from your builder \u2014 checking Document360 for reviewer comments and feedback\u2026"}function Ml(e){let t={...e.queued,briefMoved:!1},n=Kr(t);if(n)return{tone:"warn",note:`${V("\u26A0")}That run finished without writing anything, and ${n} ${t.hints+t.requests+t.answers+t.directives===1?"is":"are"} still queued \u2014 nothing was lost.`,lead:{cmd:"/catch-up",reason:"the queue is untouched, so running it again picks up the same work"}};if(e.queued.held>0){let o=e.queued.held;return{tone:"info",note:`${V("\u2139")}Nothing to write yet \u2014 your builder's ${o} note${hn(o)} ${o===1?"is":"are"} waiting on code that isn't finished. ${o===1?"It stays":"They stay"} queued.`,lead:null}}return e.hold?{tone:"info",note:`${V("\u2139")}No articles changed \u2014 product discovery is still open, so new overview and concept pages are on hold.`,lead:null}:{tone:"info",note:`${V("\u2713")}Nothing needed writing \u2014 no articles changed.`,lead:null}}function Qp(e){return{push:e.includes("--push")||e.includes("--publish"),skipReview:e.includes(Lt),includeUnfinished:e.includes(_l)}}var _l="--include-unfinished";function pi(e){let t={hold:!1,openQuestions:0,answersPending:0};try{let n=IE(e);return!n||n.status==="confident"?t:{hold:!0,...LE(e)}}catch{return t}}function Jp(e){if(!e.hold)return[];let t="I'll update the reference pages, and hold new overview and concept pages";if(e.answersPending>0){let n=e.answersPending;return[{tone:"info",text:`${V("\u2139")}Product discovery is still open \u2014 ${n} answer${hn(n)} just arrived from your builder.`},{tone:"info",text:` I'll fold ${n===1?"it":"those"} in first; if that settles the brief, everything gets written as normal.`}]}if(e.openQuestions>0){let n=e.openQuestions;return[{tone:"warn",text:`${V("\u26A0")}Product discovery isn't finished \u2014 ${n} question${hn(n)} still with your builder.`},{tone:"warn",text:` ${t} until the brief is settled.`}]}return[{tone:"warn",text:`${V("\u26A0")}Product discovery isn't finished \u2014 the product brief is still a draft.`},{tone:"warn",text:` ${t} until it's settled (/discover continues it).`}]}function Zp(e){try{return Vb(e,Gb(e)).held}catch{return[]}}function eh(e,t){let n=0;for(let o of t)try{OE(e,{hintFile:o.file,surface:o.surface,sources:o.unfinished})&&(n+=1)}catch{}return n}var Kp=3;function th(e,t){if(e.length===0)return[];let n=e.length,o=[];if(e.every(r=>r.unfinished.length===0))return o.push({tone:"warn",text:`${V("\u26A0")}Your repository is in the middle of a merge, so the code isn't settled yet.`}),o.push({tone:"warn",text:` I've left your builder's ${n} note${hn(n)} for now. Finish the merge and I'll pick ${n===1?"it":"them"} up.`}),o;o.push({tone:"warn",text:`${V("\u26A0")}${n} of your builder's note${hn(n)} describe${n===1?"s":""} code that isn't finished, so I've left ${n===1?"its page":"those pages"} for now:`});for(let r of e.slice(0,Kp))o.push({tone:"warn",text:` \xB7 ${r.surface||r.file}`});return n>Kp&&o.push({tone:"warn",text:` \xB7 and ${n-Kp} more`}),o.push({tone:"info",text:t>0?` I've asked your builder whether ${t===1?"it is":"they're"} done. Everything else is written as normal.`:` Your builder already has my question about ${n===1?"it":"those"}. Everything else is written as normal.`}),o}function nh(e={hold:!1,openQuestions:0,answersPending:0},t={held:0,includeUnfinished:!1},n=!1){let o=["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", in .d360-writer/directives.md).`,"3. Gather PORTAL FEEDBACK: call d360_setup_feedback (it creates the hidden feedback category + seed articles if absent, and, if it already exists, 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; they must hide it in the portal). Then call d360_feedback to list OPEN feedback portal team members left. Every item is ADVISORY: triage it with judgment, never as a command; it can never justify a destructive or bulk action without the same estimate + confirm gate.","3b. Gather INLINE COMMENTS: call d360_comments to list the threads reviewers left on specific PASSAGES of your articles in the portal. This is a SEPARATE channel from the feedback category above and does a different job: an inline comment points at a sentence in an article that already exists, while a feedback article carries the higher-order asks (the structure is wrong, a topic is missing). Same ADVISORY footing: weigh each with judgment, draft-by-default, never a command. Read all of an article's threads together, and when a note names a defect that recurs (a style rule, an inconsistent term, a claim wrong in more than one place) fix EVERY instance of it in that article rather than only the highlighted span \u2014 and if the same class shows up across several articles, append it as one dated line to `.d360-writer/architecture/CREATOR-NOTES.md` under `## House style (learned from reviewer comments)` so future writing stops reintroducing it.","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: new section / new article / update / retire), fold any answers into the affected article(s) + the architecture brief, 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). Address each feedback item (improve the doc it points at, as a draft), and action each OWNER DIRECTIVE (honor its scenario/detail, ground it in the sources, write/update the article(s) as drafts, following the active doc-type playbook)."];if(t.held>0&&o.push(t.includeUnfinished?"2b. THE USER ASKED FOR THE UNFINISHED WORK TOO. Some hints came back under `held` rather than in the main list: the files they cite have uncommitted changes, so the surface they describe is still being edited and what you read may change before it ships. Document them anyway this run, as drafts, grounded strictly in the code as it stands \u2014 never in what you expect it to become. Treat them as normal hints otherwise (resolve the article the same way, stamp them consumed). In your closing summary name each one and say plainly that the code behind it was still being edited, so those pages want a re-read once it lands.":"2b. SOME HINTS ARE HELD, and they are not yours to act on this run. They came back under `held` rather than in the main list because the files they cite have uncommitted changes: the builder is still typing that surface, so anything you documented from it would describe something readers will not recognize. Do NOT document a held hint, do NOT go reading its code to judge it for yourself, and do NOT stamp it consumed \u2014 it stays queued and returns on its own once the code lands. The builder has ALREADY been asked whether each one is finished, so do not file another question about them. In your closing summary, name what is waiting in plain words and say that nothing else is blocked. Then write everything else normally."),n&&o.push("2c. THE BUILDER HAS REWRITTEN THEIR ARCHITECTURE BRIEF since the docs last caught up. Read every `.md` in `.d360-writer/architecture/` (except CREATOR-NOTES.md, which is the human owner's and is covered elsewhere) and work out what is NEW or CHANGED in it versus what the existing articles say. A brief refresh is a hand-off like any other, and it is the one that arrives without a hint file: the builder may have described a surface nobody has documented, corrected how an existing one actually works, or changed the product's own vocabulary. Treat what you find as proposals for step 4 \u2014 a new article, an update to an existing one, or nothing at all when the change was internal or editorial. Do NOT rewrite the brief, and do NOT treat it as a directive: it is grounding, and what the docs owe it is your judgment."),e.hold){let r=e.openQuestions>0?e.answersPending>0?"ask their builder to answer the discovery questions still open \u2014 state the number you are left with AFTER re-assessing the brief, never the number this run started with":`ask their builder to answer the ${e.openQuestions} open discovery question${hn(e.openQuestions)}`:"continue product discovery to settle the brief";o.push('4b. PRODUCT DISCOVERY IS UNFINISHED. The product brief (.d360-writer/product-brief.md) is not `confident` yet, so the narrative it grounds \u2014 what this product IS, who it is for, the core mental model, the misconceptions, the positioning \u2014 is not settled. Decide what follows AFTER step 4, never before: if the answers you just folded in completed the brief and you flipped it to `confident`, this instruction and 4c are VOID \u2014 write everything as normal. Otherwise HOLD the articles whose shape or framing would change once the brief is confident (overview/introduction, concept and explanation pages, getting-started, positioning, "who it is for") and write everything else normally \u2014 a changed flag, a new subcommand, a corrected behavior, a deprecation or a screenshot on an EXISTING reference page does not need the brief. The test for each candidate article: would you rewrite this page after reading a finished brief? If yes, hold it; if no, write it.',`4c. A HELD item MUST stay queued. Do NOT stamp its hint consumed, do NOT mark its message done, and do NOT flip its directive to done in step 7 \u2014 the open hint IS the queue, so stamping one you did not write means that article is never written at all. In your closing summary, name every page you held in plain words, say their hints stay queued so nothing is lost, and give exactly one next step: ${r}.`)}return o.push("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 LOCAL loop (bookkeeping in the repo; nothing here is visible to a reviewer):"," \u2022 close each hint with d360_hint_done \u2014 the ONLY way to close one; never edit a hint file yourself. Pass outcome: documented plus the article path(s) you changed this run; use already-covered, retired or no-doc-change WITH a short note when no article needed writing. 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), including a step whose work you can verify an EARLIER session already completed but left unstamped, and append a step (d360_roadmap_add, with its run: command) for real new campaign work this run revealed; never delete existing steps;"," \u2022 for the Creator-notes feedback item (is_creator_notes:true): do NOT reply in it; 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; 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.)","10. NOW answer the people who asked, AFTER the push (steps 8-9), never before. A reviewer reads your reply in the portal and then looks at the article to check it, so replying first promises a change they cannot see. For anything whose push failed, do NOT reply on it; leave it outstanding and report it."," \u2022 for each INLINE COMMENT you actioned: call d360_comment_respond with its comment_id + article_id and a `reply` saying in plain words what you changed \u2014 in the reviewer's terms, mentioning where you applied the same fix more widely. Do NOT pass `resolve`: replying is your job, closing the thread is theirs, and they can only decide it is settled after seeing the change (your answer is recorded either way, so it will not come back at you). NEVER edit the reviewer's own comment text;"," \u2022 for each portal feedback item you actioned: append a short note at the BOTTOM of that feedback article via d360_update_article: `**d360-writer response:** \u2713 actioned in <article> (<date>)` (or `declined: <reason>`), NEVER overwriting the person's own text, then call d360_feedback_done(article_id, resulting_articles)."),o.push("Leave everything as DRAFTS for review; do not publish live. Publishing is a separate, reviewed step: articles you write here have not been read by an editor yet, so making them visible to readers is never part of this run. Tell the user what is waiting as a draft.",'Do NOT end with slash commands or a "what to do next" line. The tool prints the next step itself, scoped to what this run changed, and a second suggestion from you competes with it (yours will be the broader, more expensive one, because you cannot see how much was touched). Report what you did and stop.'),o.push("","End with a one-line-per-item summary of what you wrote/updated, and anything you couldn't ground (say plainly that you left a question for their engineers). Write the whole summary for a technical writer: no tool names, no internal file names, no raw status words, no hint ids, just plain sentences about what changed and what is worth their attention."),o.join(`
|
|
427
|
-
`)}var
|
|
428
|
-
(Document360 sends the first 500 characters of a highlight)`:`\u201C${n}\u201D`;let o=n.slice(0,
|
|
429
|
-
(+${r} more character${r===1?"":"s"}${e.comment.commented_text_truncated?", and Document360 caps a highlight at 500":""})`}function
|
|
430
|
-
`)]});return o.push(
|
|
431
|
-
`)}function
|
|
432
|
-
`)}async function
|
|
433
|
-
${s()}`.trim(),packages:n})),a.on("close",l=>i({ok:l===0,output:l===0?"":s(),packages:n})),e||a.unref()}catch(a){i({ok:!1,output:String(a),packages:n})}})}var
|
|
434
|
-
`).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function
|
|
435
|
-
|
|
436
|
-
`;
|
|
437
|
-
`,"utf8");let S=Nn(e)??{projectId:""};return vh({...S,styleGuide:{...S.styleGuide,pulledFrom:{styleGuideId:a.id,name:a.name??a.id,pulledAt:new Date().toISOString(),contentHash:aD("sha1").update(x).digest("hex").slice(0,16)}}},e),{lines:[oe("\u2713",`Pulled "${a.name??a.id}" into .d360-writer/style-guide.md (${x.length.toLocaleString()} characters).`),...y,u(" This is PROSE, not rules \u2014 /review judges against it, and the writer now writes to it."),u(" Turn its mechanical parts into checks: /style-guide compile"),u(" Restarting the agent so it writes to the new guide\u2026")],restart:!0}}function dD(e){let t=kh(e).rules.filter(n=>n.pack.toLowerCase()===wi.toLowerCase()).map(n=>n.id);return{prompt:zN({guide:XN(e),packName:wi,existingRuleIds:t}),display:"/style-guide compile"}}function pD(e){let t=ZN(e),n=Rh(t)?dk(t,"utf8").trim():"";return!n||!/^## /m.test(n)?{kind:"nothing",lines:[oe("\u2139","No reviewer comments have been read yet, so there is nothing to learn from."),u(" Reviewers comment on your drafts in Document360; /comments reads them, and every read"),u(" keeps a copy in .d360-writer/reviewer-notes.md. Run /comments first.")]}:{kind:"run",prompt:JN({notes:n,existingRules:QN(e),houseRulesFile:".d360-writer/house-rules.md"}),display:"/style-guide learn"}}function hk(){return[u(" Read what it wrote: git diff .d360-writer/house-rules.md"),u(" These rules apply from now on \u2014 the writer follows them and /review judges against them."),u(" Disagree with one? Delete the line. It is your file, and nothing regenerates it."),u(" Restarting the agent so it writes to the new rules\u2026")]}function fk(){return[u(` Review what it wrote: git diff .d360-writer/styles/${wi}/`),u(` Anything it could not check mechanically is listed in .d360-writer/styles/${wi}/UNCHECKABLE.md \u2014 /review judges those.`),u(` Turn them on when you are happy: /style-guide use ${wi.toLowerCase()} (they start as warnings, never blocking)`)]}var rt=(e,t)=>`${e} ${t}${e===1?"":"s"}`,bh=e=>/^v\d/i.test(e)?e:`v${e}`;function hD(e){let t=(e.description??`${e.name} style guide`).trim().replace(/\s+/g," "),n=/^(.{0,72})(?:[.,:;—]|$)/.exec(t)?.[1]?.replace(/[.,:;—\s]+$/,"").trim();if(n&&n.length>0)return n;let o=t.slice(0,72),r=o.lastIndexOf(" ");return`${r>20?o.slice(0,r):o}\u2026`}function mk(e){let t={error:0,warning:0,suggestion:0};for(let n of e)t[n.severity]=(t[n.severity]??0)+1;return["error","warning","suggestion"].filter(n=>t[n]>0).map(n=>`${t[n]} ${n}`).join(" \xB7 ")}function fD(e){let n=Nn(e)?.styleGuide?.pulledFrom;return n?`.d360-writer/style-guide.md \u2014 pulled ${n.pulledAt.slice(0,10)} from "${n.name}"`:Rh(ck(e))?".d360-writer/style-guide.md (yours)":"the built-in default"}function mD(e){let t=Nn(e),n=kh(e),o=(t?.styleGuide?.packs??[]).filter(Boolean),r=n.packs.filter(c=>c.name.toLowerCase()===so),s=n.packs.filter(c=>{let h=c.name.toLowerCase();return h!==so&&h!=="d360"}),i=t?.styleGuide?.packs===void 0&&s.length>0,a=[`Style guide: ${fD(e)}`,`Rule packs: ${s.length>0?s.map(c=>`${c.name.toLowerCase()} ${bh(c.version)}`).join(", ")+(i?u(" (the default \u2014 nobody has chosen yet)"):""):u("none chosen")}`,`Always on: ${u(`d360 (correctness, built in \u2014 ${rt(Yl.filter(c=>c.id.startsWith("D360.")).length,"rule")})`)}`];for(let c of r)a.push(` ${u(`${c.name.toLowerCase()} ${bh(c.version)} (anti-slop \u2014 ${rt(c.ruleCount,"rule")})`)}`);r.length>0&&(a.push(u(" Every article here is machine-written, so these cannot be switched off by")),a.push(u(" choosing another pack. styleGuide.humanise: false turns them off deliberately.")));let l=[...Yl.map(c=>({severity:c.severity})),...n.rules.map(c=>({severity:c.severity}))];a.push("",`${rt(l.length,"rule")} active \xB7 ${mk(l)}`);try{let c=Vl({cwd:e}),h=c.findings.filter(x=>!x.baselined),y=h.filter(x=>x.severity==="error").length;a.push(""),a.push(y===0?oe("\u2713",`No style errors across the docs${h.length>0?`, though ${rt(h.length,"other issue")} ${h.length===1?"is":"are"} reported`:""}.`):oe("\u2717",`${rt(y,"style error")} \u2014 /lint --blocked shows them, /lint --blocked --fix corrects them.`)),c.baselinedCount>0&&a.push(oe("\u2139",`${rt(c.baselinedCount,"issue")} ${c.baselinedCount===1?"was":"were"} already in your articles when this style guide was chosen, so ${c.baselinedCount===1?"it never blocks":"they never block"} publishing.`)),c.ruleErrors.length>0&&a.push(oe("\u26A0",`${rt(c.ruleErrors.length,"rule")} could not be loaded: ${c.ruleErrors.slice(0,2).map(x=>`${x.ruleId} (${x.reason})`).join("; ")}`))}catch{}return a.push(""),a.push(u(" See them all: /style-guide list \xB7 change: /style-guide use \xB7 one rule: /style-guide explain <rule>")),uk(Nn(e)?.styleGuide)&&(a.push(""),a.push("A guide built for software documentation is installed, and these docs are not on it:"),a.push(` Move to it /style-guide use ${xh}`),a.push(" Stay as you are /style-guide keep"),a.push(u(" Several rules in a general-prose guide are wrong for software documentation. This one was")),a.push(u(" measured on real knowledge bases, rule by rule, and nothing in it can block a publish."))),Sh(e)&&(a.push(""),a.push("Nobody has settled this yet, and it is a decision \u2014 nothing above changed anything:"),a.push(" Happy with these rules? /style-guide keep"),a.push(" Want a stricter standard? /style-guide use microsoft (or google)"),a.push(u(" Worth settling now rather than later: it shapes every article written from here, and")),a.push(u(" changing it once a knowledge base exists means going back over what is already written."))),a}function gk(e){let t=Nn(e),n=new Set($h(t?.styleGuide)),o=yh(e),r=["Rule packs you can turn on:",""],s=Math.max(12,...o.map(i=>i.name.length));for(let i of o){let a=i.name.toLowerCase(),l=n.has(a),c=a===so,h=l?"\u2713":"\xB7",y=c?u("(always on)"):l?u("(active)"):"",x=i.local?u(" [yours]"):"";r.push(` ${h} ${a.padEnd(s)}${x} ${i.description??""}`),r.push(` ${u(`${rt(i.rules.length,"rule")} \xB7 ${mk(i.rules)} \xB7 ${bh(i.version)}`)} ${y}`),i.errors.length>0&&r.push(oe("\u26A0",`${rt(i.errors.length,"rule")} in this pack could not be loaded \u2014 /style-guide explain names them.`))}return o.every(i=>i.name.toLowerCase()===so)&&(r.push(""),r.push(u(" The Microsoft and Google style guides are not installed in this build yet."))),r.push(""),r.push(u(" Turn one on: /style-guide use <name> (this replaces the chosen set, it does not add to it)")),r.push(u(" Several: /style-guide use microsoft,google")),r.push(u(" Back to none: /style-guide use none")),r}function gD(e,t){if(!t)return[oe("\u26A0","Name a rule: /style-guide explain Humanise.EmDash")];let n=kh(e),o=Yl.find(c=>c.id.toLowerCase()===t.toLowerCase()),r=n.rules.find(c=>c.id.toLowerCase()===t.toLowerCase());if(!o&&!r){let c=[...Yl.map(h=>h.id),...n.rules.map(h=>h.id)].filter(h=>h.toLowerCase().includes(t.toLowerCase())).slice(0,5);return[oe("\u26A0",`No active rule called "${t}".`),...c.length>0?[u(` Did you mean: ${c.join(", ")}`)]:[u(" /style-guide list shows the active packs.")]]}let s=o?.id??r.id,i=o?.severity??r.severity,a=o?"built in (correctness \u2014 always on)":`pack: ${r.pack.toLowerCase()}`,l=[`${s} ${i} \xB7 ${a}`,""];l.push(` ${o?.summary??r.message}`),r?.link&&l.push(u(` ${r.link}`)),r?.degraded&&(l.push(""),l.push(oe("\u26A0",`This rule is translated approximately: ${r.degraded}. It may match slightly more than the original does.`)));try{let c=Vl({cwd:e}).findings.filter(y=>y.ruleId===s),h=c.filter(y=>!y.baselined);l.push(""),l.push(c.length===0?" Currently: no findings.":` Currently: ${rt(h.length,"finding")}${c.length!==h.length?`, plus ${c.length-h.length} baselined and hidden`:""}.`)}catch{}return l.push(""),o?(l.push(u(" Built-in checks are grounded in your product's own source and cannot be switched off \u2014 they")),l.push(u(" catch defects of fact, not matters of taste."))):(l.push(i==="error"?u(' This one BLOCKS publishing \u2014 your config sets it to "error" deliberately.'):u(" Style rules never block publishing. Fix it when you want to; it will not hold a page back.")),l.push(u(` Silence it everywhere: add "${s}": "off" to styleGuide.rules in .d360-writer/config.json`)),i!=="error"&&l.push(u(" Silence one passage: <!-- vale "+s+" = NO --> \u2026 <!-- vale "+s+" = YES -->"))),l}function Ch(e,t){let n=(t??"").trim();if(!n){let w=yh(e).filter(R=>R.name.toLowerCase()!==so),S=new Set($h(Nn(e)?.styleGuide).map(R=>R.toLowerCase())),P=R=>R.toLowerCase()===xh?0:1,T=w.sort((R,N)=>P(R.name)-P(N.name)||R.name.localeCompare(N.name)).map(R=>({cmd:`/style-guide use ${R.name.toLowerCase()}`,desc:`${hD(R)} \u2014 ${R.rules.length} rules${S.has(R.name.toLowerCase())?" (active now)":""}`}));return{lines:[],restart:!1,pick:{title:"Which writing rules should these docs follow?",lead:"Pick below. Whichever you choose, every article here is held to it \u2014 nothing stays exempt.",options:[...T,{cmd:"/style-guide use none",desc:"the built-in checks only \u2014 correctness and anti-slop"}]}}}let o=n.toLowerCase()==="none"?[]:n.split(/[,\s]+/).map(w=>w.trim().toLowerCase()).filter(Boolean),r=new Map(yh(e).map(w=>[w.name.toLowerCase(),w])),s=o.filter(w=>!r.has(w));if(s.length>0)return{lines:[oe("\u2717",`No rule pack named ${s.map(w=>`"${w}"`).join(", ")}.`),"",...gk(e)],restart:!1};let i=Nn(e)??{projectId:""},{declinedUpgrade:a,...l}=i.styleGuide??{},c=(i.styleGuide?.packs??[]).map(w=>w.trim().toLowerCase()).filter(Boolean);vh({...i,styleGuide:{...l,packs:o,decidedAt:new Date().toISOString()}},e),BN();let h=[oe("\u2192",`Switching to: ${o.length>0?o.join(", "):"the built-in checks only"}${o.includes(so)?"":` (+ ${so}, always on)`}\u2026`)],y,x=[];try{let w=HN(e),S=w?Object.values(w.entries).reduce((R,N)=>R+N.count,0):0;if(w){try{wh(`${qN(e)}.bak`,JSON.stringify(w,null,2),"utf8")}catch{}GN(e)}let P=Vl({cwd:e}),T=new Set(P.findings.map(R=>R.path)).size;if(P.findings.length===0)h.push(oe("\u2713",T===0?"No articles yet \u2014 everything you write from here is held to the full set.":"Your articles are already clean against these rules."));else{h.push(oe("\u26A0","Every article is held to the new rules. Nothing stays exempt."),"",u(` ${rt(P.findings.length,"finding")} across ${rt(T,"article")} ${P.findings.length===1?"is":"are"} now live.`)),S>0&&(h.push(u(` ${rt(S,"finding")} accepted under your previous guide ${S===1?"is":"are"} not carried over.`)),h.push(u(" Your previous record is at .d360-writer/style-baseline.json.bak"))),h.push(""),h.push(oe("\u2713","Nothing blocks publishing \u2014 no style-pack rule can."));let R=to(e,["--fix"],P.findings);R.lines.length>0&&h.push("",...R.lines);let N=R.fixed>0?Vl({cwd:e}):P,B=N.findings.length,G=new Set(N.findings.map(Q=>Q.path)).size;B===0?h.push(oe("\u2713","That was all of them \u2014 your articles now match the new guide.")):y={findings:B,articles:G,cmd:"/review --all --fix",...R.fixed>0?{outOf:P.findings.length}:{}},x=[...new Set(N.findings.map(Q=>Q.path))]}VN(e,{packs:o,from:c,articlesWithFindings:x})}catch(w){h.push(oe("\u26A0",`The packs are active, but reading your articles failed: ${w instanceof Error?w.message:String(w)}`)),h.push(u(" Run /lint to see the current state before publishing."))}return h.push(...pk(e,`/style-guide use ${n}`)),h.push(u(" Restarting the agent so it writes to the new rules\u2026")),{lines:h,restart:!0,...y?{editorial:y}:{}}}function yD(e){return[e.title,u(` ${e.lead}`),"",...e.options.map(t=>` ${t.cmd}`.padEnd(38)+u(t.desc))]}function Ph(e){let t=e.outOf?`${e.findings} of the ${e.outOf} findings`:rt(e.findings,"finding");return[oe("\u2192",`${t} across ${rt(e.articles,"article")} ${e.findings===1?"needs":"need"} a read, not a swap.`),u(` ${e.cmd} reads each one and rewrites it. Nothing is blocking your publishing in the meantime.`)]}function wD(e,t){let n=(t??"").trim().toLowerCase()==="skip",o=KN(e);if(!o)return[oe("\u2713","No sweep is owed \u2014 your articles have been read against the guide they follow.")];let r=o.packs.length>0?o.packs.join(", "):"the built-in checks";if(n)return YN(e),[oe("\u2713",`Fine \u2014 I won't raise the ${r} sweep again.`),"",u(` ${rt(o.pending,"article")} still ${o.pending===1?"has":"have"} not been read against it.`),u(" /review --all --fix does the sweep whenever you want it.")];let s=o.total-o.pending;return[oe("\u2192",`${o.pending} of your ${rt(o.total,"article")} still ${o.pending===1?"needs":"need"} a read against ${r}.`),"",...s>0?[u(` ${s} read so far.`)]:[],u(" /review --all --fix reads the rest and rewrites them."),u(" /style-guide sweep skip stops me raising it.")]}async function Kl(e,t){let{sub:n,value:o}=Xr(e),r=s=>{for(let i of s)console.log(i);console.log("")};switch(n){case"list":return r(gk(t.cwd)),{kind:"continue"};case"explain":return r(gD(t.cwd,o)),{kind:"continue"};case"use":{let s=Ch(t.cwd,o);return r(s.pick?yD(s.pick):s.lines),s.editorial&&r(Ph(s.editorial)),s.restart?{kind:"clear"}:{kind:"continue"}}case"keep":return r(cD(t.cwd)),{kind:"continue"};case"sweep":return r(wD(t.cwd,o)),{kind:"continue"};case"pull":{let s=await uD(t.cwd,o,t.profileName);return r(s.lines),s.restart?{kind:"clear"}:{kind:"continue"}}case"compile":{let s=dD(t.cwd);return{kind:"forward-to-agent",prompt:s.prompt,display:s.display}}case"learn":{let s=pD(t.cwd);return s.kind==="nothing"?(r(s.lines),{kind:"continue"}):{kind:"forward-to-agent",prompt:s.prompt,display:s.display}}default:return r(mD(t.cwd)),{kind:"continue"}}}ie();import{lintDocs as Xl,loadStyleGuide as Ck,buildReviewPrompt as Pk,buildStructureReviewPrompt as FD,structureReviewDue as WD,structureFingerprint as BD,recordStructureReview as HD,hasCaptureArtifacts as Tk,readProjectConfig as Ih,DEFAULT_DOCS_DIR as Lh,listArticleFiles as Qo,normalizeScope as GD,planPartitions as qD,runPartitioned as Ak,partitionCoverage as VD,resolveModelForOperation as Ek,stampArticles as YD,snapshotArticles as KD,reviewStalePaths as zD,readReviewerNotes as Nk,renderNotesForPrompt as Dk,readDocsPlan as XD,CONTENT_CAP_VERSION as jh}from"document360-engine";import{articlesChangedSince as bD,isUnadoptedArticle as kD,docsRootOf as $D}from"document360-engine";function zo(e,t,n,o){let r=t.map(c=>c.replace(/\\/g,"/"));if(!n)return{changed:[],earned:r,unadopted:[]};let s=[];try{s=bD(e,n).map(c=>c.replace(/\\/g,"/"))}catch{return{changed:[],earned:r,unadopted:[]}}let i=new Set(s),a=r.filter(c=>!i.has(c)&&kD(e,c,o)),l=new Set(a);return{changed:s.filter(c=>r.includes(c)),earned:r.filter(c=>!l.has(c)),unadopted:a}}function vD(e,t){let n=t.replace(/\\/g,"/");try{let o=$D(e).replace(/\\/g,"/").replace(/\/+$/,"");return o&&n.startsWith(`${o}/`)?n.slice(o.length+1):n}catch{return n}}function Qr(e,t,n){if(t.length===0)return null;let o=t.length===1,r=[];r.push(o?`\u26A0 The editor changed nothing in ${vD(e,t[0])}, so it is not recorded as reviewed.`:`\u26A0 The editor changed nothing in ${t.length} pages, so they are not recorded as reviewed.`),r.push(o?" Nothing here has adopted this page: it came from Document360, it is not in your docs plan, and":" Nothing here has adopted them: they came from Document360, they are not in your docs plan, and"),r.push(o?" nothing records what it was written from. There was nothing for an editor to check it against.":" nothing records what they were written from. There was nothing for an editor to check them against.");for(let i of t)r.push(`/untrack ${i}`);r.push(o?" That disowns it \u2014 the page, its history and its comments stay on Document360, readers see no":" That disowns one \u2014 the page, its history and its comments stay on Document360, readers see no"),r.push(" change, and the markdown is kept. Nothing is deleted.");let s=n.lead&&o?{text:r.join(`
|
|
438
|
-
`),cmd:`/untrack ${t[0]}`}:null;return{lines:r,cta:s}}function
|
|
439
|
-
`),w=
|
|
440
|
-
`);return
|
|
441
|
-
`),readerContract:
|
|
442
|
-
`),display:`/reorder${n?` ${n}`:""}`}}async function
|
|
415
|
+
`)}function so(e){return`${V("\u2192",Ct.blue)}Verifying ${e} new screenshot${e===1?"":"s"} (reading each image)\u2026`}var KA=(e,t=88)=>{let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n};function Vr(e,t){if(t.length===0)return[];let n=Tn(e).shots,o=[],r=[],s=[];for(let a of t){let l=n[a]?.review;l?l.verdict==="ok"?o.push(a):r.push({id:a,reason:l.reason??"no reason recorded",repaired:!!l.repaired}):s.push(a)}let i=[""];if(i.push(`${V("\u2714",Ct.green)}${Ct.green(`${o.length} verified`)}`+(r.length>0?` ${Ct.magenta(`\u2691 ${r.length} flagged`)}`:"")+(s.length>0?` ${Ct.yellow(`? ${s.length} not verified`)}`:"")+Ct.gray(` ${t.length} shot${t.length===1?"":"s"} in this pass`)),r.length>0){let a=Math.max(...r.map(c=>c.id.length));for(let c of r)i.push(` ${Ct.magenta(c.id.padEnd(a))} ${Ct.gray(KA(c.reason))}`);let l=r.filter(c=>c.repaired).length;i.push(`${V("\u2192",Ct.magenta)}Re-capture the ${r.length} flagged: ${Ct.bold("/screenshot capture --failed")}`+(l<r.length?Ct.gray(` (${r.length-l} still need${r.length-l===1?"s":""} a spec fix first)`):""))}return s.length>0&&i.push(`${V("\u26A0",Ct.yellow)}No verdict recorded for ${s.slice(0,3).join(", ")}${s.length>3?`, +${s.length-3}`:""} \u2014 still awaiting verification. Run ${Ct.bold("/screenshot verify")} again.`),i}async function xb(e,t){let n=t?.cwd??process.cwd(),o=Mo(n);o&&console.log(o);let r=He(n),s=YA(e);if(s.mode==="single"){let a=r.find(l=>l.id===s.id);return a?a.state==="captured"?(console.log(`"${s.id}" has been taken but the callouts aren't drawn on yet \u2014 /screenshot annotate ${s.id} finishes it.`),{kind:"continue"}):["annotated","verified","rejected"].includes(a.state)?{kind:"forward-to-agent",prompt:hn(n,[s.id]),display:`/screenshot verify ${s.id}`}:(console.log(`"${s.id}" has no captured image yet \u2014 /screenshot capture ${s.id} takes the shot first.`),{kind:"continue"}):(console.log(`No screenshot placeholder called "${s.id}". /screenshot list shows them all.`),{kind:"continue"})}let i=ai(r);if(i.length===0){let a=r.filter(h=>h.state==="verified").length,l=r.filter(h=>h.state==="rejected").length,c=r.filter(h=>h.state==="captured").length;return console.log(c>0?`${c} shot${c===1?" is":"s are"} taken but not drawn on yet \u2014 /screenshot annotate finishes ${c===1?"it":"them"}, then there'll be something to verify.`:l>0?`Nothing left to verify. ${l} shot${l===1?"":"s"} failed verification \u2014 re-capture with: /screenshot capture --failed`:a>0?`All ${a} captured shot${a===1?" is":"s are"} already verified.`:"No captured screenshots to verify yet \u2014 /screenshot capture takes the shots first."),{kind:"continue"}}return{kind:"forward-to-agent",prompt:hn(n,i),display:"/screenshot verify"}}import{spawn as Rb}from"node:child_process";var Tp="d360-capture";function zA(e,t){if(t&&typeof e.pid=="number")try{process.kill(-e.pid,"SIGTERM");return}catch{}try{e.kill()}catch{}}function li(e){let t=process.platform==="win32",n=!t&&e.stdio==="pipe";return new Promise((o,r)=>{let s=t?Rb(`${Tp} ${e.args.join(" ")}`,{cwd:e.cwd,shell:!0,stdio:e.stdio==="inherit"?"inherit":["ignore","pipe","pipe"],env:{...process.env,NO_UPDATE_NOTIFIER:"1"}}):Rb(Tp,e.args,{cwd:e.cwd,shell:!1,detached:e.stdio==="pipe",stdio:e.stdio==="inherit"?"inherit":["ignore","pipe","pipe"],env:{...process.env,NO_UPDATE_NOTIFIER:"1"}}),i="";e.stdio==="pipe"&&(s.stdout?.on("data",l=>{i+=l.toString()}),s.stderr?.on("data",l=>{i+=l.toString()}));let a=()=>zA(s,n);e.signal?.addEventListener("abort",a,{once:!0}),s.on("error",l=>{if(e.signal?.removeEventListener("abort",a),l.code==="ENOENT"){o({exitCode:127,output:`${i}
|
|
416
|
+
${Tp}: command not found`.trim()});return}r(l)}),s.on("close",l=>{e.signal?.removeEventListener("abort",a),o({exitCode:l??1,output:i})})})}var nE=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Ep(e){let t=e.find(o=>!o.startsWith("--")),n=e.includes("--blocked")||e.includes("--retry-blocked");return e.includes("--failed")?{mode:"failed"}:e.includes("--all")?{mode:"all",retryBlocked:n}:!t&&n?{mode:"blocked"}:t?/[\\/]/.test(t)||t.endsWith(".md")?{mode:"scope",scope:nE(t),retryBlocked:n}:{mode:"single",id:t}:{mode:"picker"}}function di(e,t){let n=He(e,t),o=r=>n.filter(s=>s.state===r).map(s=>s.id);return{ready:o("spec"),captured:[...o("captured"),...o("annotated"),...o("verified"),...o("rejected")].sort(),blocked:o("blocked"),broken:o("broken"),rejected:o("rejected"),rows:n}}function Cb(e){let t=e.filter(s=>s.state==="spec"),n=e.filter(s=>s.state==="annotated"||s.state==="verified"),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}),jr(o,t,"capture"),sd(o,e.filter(s=>s.state==="blocked"),e.filter(s=>s.state==="broken"),e.filter(s=>s.state==="rejected"));for(let s of[...n].sort((i,a)=>i.id.localeCompare(a.id))){let i=s.state==="verified"?" \u2714 verified \u2014 re-capture":" \u25C8 to verify \u2014 re-capture";o.push({kind:"shot",action:"capture",label:s.id,ids:[s.id],depth:1,note:i})}return o}function Np(e,t){let n=new Set(t.filter(r=>r.state!=="placeholder").map(r=>r.id)),o=t.filter(r=>r.state==="rejected").map(r=>r.id);return[...new Set([...Kg(e).filter(r=>n.has(r)),...o])].sort()}function Dp(e,t){let n=e.length;if(n===0)return null;let o=Fs(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(`
|
|
417
|
+
`)}function oE(e,t){let n=JA(e)?.outputDir??ZA;return tE(eE(e,n),t)}function jp(e,t,n,o){let r=oE(e,t);return(r.annotationsMtimeMs??0)>=o&&r.rawMtimeMs!==void 0?"captured":n===0?"skipped":"failed"}function Pb(e){let t=/⊘[^\n—]*—\s*(.+)/.exec(e);return t?t[1].trim():null}var rE=/element is not (?:enabled|visible|stable|editable)|intercepts pointer events|outside of the viewport|element is not attached/i;function Tb(e){let t=e.split(/\r?\n/).map(s=>s.trim()).filter(Boolean),n=t.filter(s=>/\b\w*Error\b|Cannot navigate|Timeout \d+m?s (exceeded|waiting)|net::|browser has been closed/i.test(s)&&!/^Error Context:/i.test(s)),o=[...new Set(t.filter(s=>rE.test(s)).map(s=>s.replace(/^-\s*/,"")))].slice(0,2),r=t.find(s=>/locator resolved to/i.test(s))?.replace(/^-\s*/,"");return n.length>0||o.length>0?[...new Set([...n].slice(0,2)),...o,...r&&o.length>0?[r.length>120?`${r.slice(0,119)}\u2026`:r]:[]].join(`
|
|
418
|
+
`):Ip(e)}function Ip(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(`
|
|
419
|
+
`)}var sE=/^[A-Za-z0-9._-]+$/;function Lp(e){return sE.test(e.id)?li({args:["capture",e.id],cwd:e.cwd,stdio:e.stdio,signal:e.signal}):Promise.reject(new Error(`Not a valid spec id: "${e.id}"`))}function Ab(e,t=XA()){try{let n=JSON.parse(Ap(ci(e,".d360-writer","capture.json"),"utf8").replace(/^/,"")),o=n.projectId;if(!o)try{o=JSON.parse(Ap(ci(e,"package.json"),"utf8")).name}catch{}o||=QA(e);let r=Object.keys(n.profiles??{}),s=n.defaultProfile??(r.length===1?r[0]:r.includes("staging")?"staging":r[0]);return s?Sb(ci(t,".document360-capture","auth-states",o,`${s}.json`)):!0}catch{return!0}}function Eb(e){return li({args:["auth","--auto"],cwd:e.cwd,stdio:"pipe",signal:e.signal})}function Op(e,t){return e===127||/is not recognized as an internal or external command|command not found/i.test(t)}function Nb(e){try{let t=JSON.parse(Ap(ci(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 Vo(e){return Sb(ci(e,".d360-writer","capture.json"))}function Mp(){return["Screenshot capture is not configured in this repo yet (no `.d360-writer/capture.json`). Set it up","conversationally, and 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, 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: 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`, adding/updating 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(`
|
|
420
|
+
`)}function Db(e,t){let n=e.filter(i=>i.state==="blocked"&&i.blockedBy!=="testid").length,o=e.filter(i=>i.state==="blocked"&&i.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(", ")}
|
|
421
|
+
/screenshot list --detail shows what each one needs`}function jb(e,t){let n={newlyCaptured:[],newlyBlocked:[],stillBroken:[],newlyBroken:[],brokeDifferently:[],repairedNowBlocked:[],blockedAsBefore:[],blockedNewReason:[]};for(let o of t){let r=e.shots[o.id],s=r?.outcome;o.outcome==="captured"&&s!=="captured"?n.newlyCaptured.push(o.id):o.outcome==="failed"?s!=="failed"?n.newlyBroken.push(o.id):ui(r?.reason)!==ui(o.detail)?n.brokeDifferently.push(o.id):n.stillBroken.push(o.id):o.outcome==="skipped"&&(s==="failed"?n.repairedNowBlocked.push(o.id):s!=="skipped"?n.newlyBlocked.push(o.id):Ga(r?.reason??"")!==Ga(o.detail??"")?n.blockedNewReason.push(o.id):n.blockedAsBefore.push(o.id))}return n}function ui(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 Ib(e,t=3){if(e.length===0||e.length>t)return[];let n=Math.max(...e.map(o=>o.id.length));return e.map(o=>`\u2298 ${o.id.padEnd(n)} ${o.detail?Ir(o.detail):"no reason recorded"}`)}function Yr(e,t=2){return e.length<=t?e.join(" \xB7 "):`${e.slice(0,t).join(" \xB7 ")} \xB7 +${e.length-t}`}function Lb(e,t){if(!t)return[];let n=[],o=(i,a,l,c)=>{a>0&&n.push({glyph:i,label:`${a} ${l}`,tail:c})};if(o("\u2713",e.newlyCaptured.length,"newly captured",Yr(e.newlyCaptured)),o("\u2717",e.newlyBroken.length,"newly broken",Yr(e.newlyBroken)),o("\u2192",e.repairedNowBlocked.length,"repaired",`no longer broken \u2014 only data stands in the way \xB7 ${Yr(e.repairedNowBlocked)}`),o("\u2298",e.newlyBlocked.length,"newly blocked",Yr(e.newlyBlocked)),o("\u2192",e.blockedNewReason.length,"blocked on something new",`an earlier step now passes \xB7 ${Yr(e.blockedNewReason)}`),o("\u2192",e.brokeDifferently.length,"broken differently",`the previous cause is fixed \xB7 ${Yr(e.brokeDifferently)}`),o("\u2717",e.stillBroken.length,"still broken","same error \u2014 these need re-authoring"),o("\xB7",e.blockedAsBefore.length,"blocked as before","nothing staged since last time"),n.length===0)return[];let r=Math.max(...n.map(i=>i.label.length));return[""," Since your last run",...n.map(i=>` ${i.glyph} ${i.label.padEnd(r)} ${i.tail}`)]}function Ob(e){let t=e.results.filter(w=>w.outcome==="captured"),n=e.results.filter(w=>w.outcome==="skipped"),o=e.results.filter(w=>w.outcome==="failed"),r=e.unannotated??[],s=w=>w===1?"":"s";if(t.length+n.length+o.length===0)return null;let i=e.articles.length===1?`/push ${e.articles[0]}`:Ce("/push","--screenshots",Mt(e.articles)),a=e.ids.length===1?`/screenshot capture ${e.ids[0]}`:"/screenshot capture",l=o[0]?.id,c=[];o.length>0&&c.push({glyph:"\u2717",cmd:`/screenshot ${l}`,why:`re-author the ${o.length===1?"broken spec":`first of ${o.length} broken specs`} \u2014 re-running fails the same way`});let h=Ce("/screenshot annotate","",r.length===1?r[0]:void 0);r.length>0&&c.push({glyph:"\u25C8",cmd:h,why:`draw the callouts on ${r.length} shot${s(r.length)} \u2014 no browser, seconds; ${r.length===1?"it cannot":"they cannot"} publish until drawn`}),n.length>0&&c.push({glyph:"\u2298",cmd:"/screenshot list",why:`what to stage for the ${n.length} blocked shot${s(n.length)}`}),t.length>0&&r.length<t.length&&c.push({glyph:"\u2713",cmd:i,why:`embed the ${t.length-r.length} new PNG${s(t.length-r.length)}`});let y=Math.max(...c.map(w=>w.cmd.length));return{note:c.map(w=>`${w.glyph} ${w.cmd.padEnd(y)} ${w.why}`).join(`
|
|
422
|
+
`),cmd:o.length>0?`/screenshot ${l}`:r.length>0?h:t.length>0?i:a,tone:o.length>0||r.length>0?"warn":"info"}}function Mb(e,t){let n=new Map(He(e).map(o=>[o.id,o.file]));return[...new Set(t.map(o=>n.get(o)).filter(o=>!!o))].sort()}async function _p(e,t){let n=t?.cwd??process.cwd(),o=Ep(e);if(!Vo(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:i,rows:a}=di(n,o.mode==="scope"?o.scope:void 0),l=Np(n,a),c=(o.mode==="all"||o.mode==="scope")&&o.retryBlocked,h=o.mode==="single"?[o.id]:o.mode==="failed"?l:o.mode==="blocked"?i:o.mode==="picker"?r:[...r,...s,...c?i:[]];if(h.length===0)return o.mode==="failed"?console.log("No broken specs to re-run \u2014 /screenshot list shows where things stand."):o.mode==="blocked"?console.log("No shots are waiting on app data \u2014 /screenshot list shows where things stand."):console.log("No authored specs to capture yet \u2014 author them first: /screenshot"),{kind:"continue"};if(!c&&o.mode!=="single"&&o.mode!=="failed"&&o.mode!=="blocked"){let P=Dp(a.filter(T=>T.state==="blocked"),"/screenshot capture --blocked");P&&console.log(P)}let y=Date.now(),x=[];for(let P of h){console.log(`\u25B6 ${P}`);try{let{exitCode:T}=await Lp({cwd:n,id:P,stdio:"inherit"});x.push({id:P,outcome:jp(n,P,T,y)})}catch(T){if(T.code==="ENOENT")return console.log("d360-capture is not installed. Run: npm i -g document360-capture"),{kind:"continue"};x.push({id:P,outcome:"failed",detail:T.message})}}let w=P=>x.filter(T=>T.outcome===P).length;console.log(`\u2713 ${w("captured")} captured \xB7 \u2298 ${w("skipped")} skipped \xB7 \u2717 ${w("failed")} failed`);let S=x.filter(P=>P.outcome==="captured");return Ia(n,x.map(P=>({id:P.id,outcome:P.outcome,reason:P.detail,specSource:_o(n,P.id)})),new Date().toISOString()),S.length>0?(console.log(so(S.length)),{kind:"forward-to-agent",prompt:hn(n,S.map(P=>P.id)),display:"/screenshot verify"}):{kind:"continue"}}import{readProjectConfig as iE,DEFAULT_OUTPUT_DIR as aE,resolveOutputDir as lE,shotArtifacts as cE,annotationCurrent as uE}from"document360-engine";Nr();var _b="0.2.29";function jl(e=Rt()){return Dr(e,_b)}function Up(e){let t=e.includes("--force")||e.includes("-f"),n=e.includes("--all")||e.includes("-a"),o=e.find(r=>!r.startsWith("-"));return n?{mode:"all",force:t}:o?o.includes("/")||o.includes("\\")||o.endsWith(".md")?{mode:"scope",scope:o.replace(/\\/g,"/").replace(/\/+$/,""),force:t}:{mode:"single",id:o}:{mode:"pending"}}function Fp(e,t){let n=He(e,t);return{pending:n.filter(o=>o.state==="captured").map(o=>o.id),done:n.filter(o=>o.state==="annotated"||o.state==="verified"||o.state==="rejected").map(o=>o.id),rows:n}}var dE=/^[A-Za-z0-9._-]+$/;function pE(e){if(!dE.test(e.id))return Promise.reject(new Error(`Not a valid spec id: "${e.id}"`));let t=["annotate",e.id,...e.force?["--force"]:[]];return li({args:t,cwd:e.cwd,stdio:e.stdio,signal:e.signal})}function hE(e,t,n,o){let r=lE(e,iE(e)?.outputDir??aE),s=cE(r,t);return(s.annotatedMtimeMs??0)>=o?"annotated":n===0&&uE(s)?"skipped":"failed"}function Wp(e){return e===null?"d360-capture is not installed, so there is nothing to draw with. Install it, then run /screenshot annotate again.":`The installed d360-capture (${e}) draws the callouts during the capture itself, so there is no separate step to run. Run /update to move to ${_b} or later, then /screenshot annotate becomes available.`}var Il=8;function Ub(e){let t=e.results.filter(o=>o.outcome==="failed"),n=e.results.filter(o=>o.outcome==="annotated");return t.length>0?{glyph:"\u2717",cmd:Ce("/screenshot capture","",t.length===1?t[0].id:void 0),why:`${t.length} could not be drawn \u2014 taking ${t.length===1?"it":"them"} again rebuilds the boxes`}:n.length===0?null:e.voidedVerdicts>Il?{glyph:"\u25C8",cmd:Ce("/screenshot verify","",e.scope),why:`${e.voidedVerdicts} verified shots were re-drawn, so their verdicts no longer describe the picture on disk`}:{glyph:"\u25C8",cmd:Ce("/screenshot verify","",e.scope),why:`${n.length} picture${n.length===1?"":"s"} ready to check \u2014 no browser needed`}}async function Bp(e){let t=Date.now(),n=[];for(let o of e.ids){if(e.signal?.aborted)break;e.onStart?.(o);try{let{exitCode:r,output:s}=await pE({cwd:e.cwd,id:o,...e.force?{force:!0}:{},...e.signal?{signal:e.signal}:{},stdio:"pipe"}),i=hE(e.cwd,o,r,t);n.push({id:o,outcome:i,...i==="failed"?{detail:fE(s)}:{}}),e.onDone?.(o,i)}catch(r){if(r.code==="ENOENT")return{results:n,cliMissing:!0};n.push({id:o,outcome:"failed",detail:r.message}),e.onDone?.(o,"failed")}}return{results:n}}async function Hp(e,t){let n=t?.cwd??process.cwd(),o=Up(e);if(!Vo(n))return console.log("Screenshot capture is not set up in this repo yet. Run: d360-capture init"),{kind:"continue"};let r=Rt();if(!jl(r))return console.log(Wp(r)),{kind:"continue"};let s=Mo(n);s&&console.log(s);let i=o.mode==="scope"?o.scope:void 0,{pending:a,done:l,rows:c}=Fp(n,i),h=o.mode==="all"||o.mode==="scope"?o.force:!1,y=o.mode==="single"?[o.id]:h?[...a,...l]:a;if(y.length===0){let B=l.length>0;return console.log(B?`Every shot${i?` under ${i}`:""} is already drawn. Re-draw them anyway: /screenshot annotate --all --force`:"No shots have been taken yet \u2014 /screenshot capture takes them first."),{kind:"continue"}}let x=new Set(c.filter(B=>B.state==="verified").map(B=>B.id)),{results:w,cliMissing:S}=await Bp({cwd:n,ids:y,force:h});if(S)return console.log("d360-capture is not installed. Run: npm i -g document360-capture"),{kind:"continue"};let P=B=>w.filter(G=>G.outcome===B).length;console.log(`\u2713 ${P("annotated")} annotated`+(P("skipped")?` \xB7 ${P("skipped")} already current`:"")+(P("failed")?` \xB7 \u2717 ${P("failed")} failed`:""));for(let B of w.filter(G=>G.outcome==="failed"))console.log(` \u2717 ${B.id}${B.detail?` \u2014 ${B.detail}`:""}`);let T=w.filter(B=>B.outcome==="annotated").map(B=>B.id);if(T.length===0)return{kind:"continue"};let R=T.filter(B=>x.has(B)).length;if(R>Il)return console.log(`\u26A0 ${R} verified shots were re-drawn, so their verdicts no longer describe the picture on disk.
|
|
423
|
+
Check them when you're ready: ${Ce("/screenshot verify","",i)}`),{kind:"continue"};let D=T.filter(B=>!x.has(B)||R>0);return D.length===0?{kind:"continue"}:(console.log(so(D.length)),{kind:"forward-to-agent",prompt:hn(n,D),display:"/screenshot verify"})}function fE(e){return e.split(/\r?\n/).map(n=>n.trim()).filter(n=>n.length>0&&!/^[▶✓↕]/.test(n)).at(-1)}ae();import{existsSync as mE}from"node:fs";import{join as gE}from"node:path";import{builderChannelWired as yE,driftedAnchors as wE,readTestidRequests as bE,testidHandoffPrompt as kE,testidRequestPaths as $E,writerDir as vE}from"document360-engine";async function Kr(e,t){let n=t?.cwd;if(n){let r=xE(n);if(r){for(let s of r)console.log(s);return{kind:"continue",ownNext:!0}}}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.","","This run is also the RE-VERIFY pass for open selector requests: for every CAPTURE-TODO anchor, check the","snippet is still in its named file (an unrelated refactor can invalidate it with nobody touching the spec).","Where it is gone, re-locate the element and rewrite that CAPTURE-TODO with a current anchor and line.","or set anchorVerified:false when you cannot confirm it. /screenshot list --detail names the drifted ones."].join(`
|
|
424
|
+
`),display:"/screenshot checklist"}}function xE(e){let t;try{t=He(e)}catch{return null}let n=mE(gE(vE(e),"capture.json")),o=t.some(i=>i.state!=="placeholder");if(n||o)return null;let r=t.length,s=new Set(t.map(i=>i.file)).size;return r===0?[`${V("\u25CB",u)}No screenshots are planned yet, so there is nothing to stage.`,u(" A screenshot is planned by the article that needs it. /write adds the placeholders as it writes.")]:[`${V("\u25CB",u)}${r} screenshot${r===1?"":"s"} planned across ${s} article${s===1?"":"s"} \u2014 none captured, none with a spec, and no capture setup yet.`,u(" There is nothing to stage from yet: a checklist is built from what each spec needs, and no specs exist."),u(" /screenshot author writes the specs. Come back to /screenshot checklist once they exist and it will"),u(" tell you what data to stage and which test ids your developers still owe you."),"",u(" Free \u2014 this read your files and called nothing.")]}var Fb="-".repeat(64);function Wb(e){let t=bE(e);if(t.length===0)return null;let{mdRel:n}=$E(e),o=t.length,r=new Set(t.map(h=>h.file).filter(Boolean)).size,s=`${o} data-testid attribute${o===1?"":"s"}`,i=`${r} source file${r===1?"":"s"}`,a=kE(e,o),l=wE(t).length,c=l>0?[` \u26A0 ${l} of ${l===1?"them quotes":"them quote"} code that has changed since \u2014 still likely right,`,` but ${l===1?"it says":"they say"} so, and ${l===1?"asks":"ask"} to be found by description instead.`]:[];return yE(e)?{prompt:a,lines:[`\u{1F4CB} Developer hand-off \u2014 ${s} requested across ${i}.`,...c," Left in your builder's inbox: their coding agent is told about it at its next session, so",` there is nothing for you to relay. Detail: ${n}`]}:{prompt:a,lines:[`\u{1F4CB} Developer hand-off \u2014 ${s} requested across ${i}.`,...c,"\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."," (Run /devhints once and requests like this reach your builder on their own.)","",Fb,a,Fb]}}Kn();ae();import{listOpenForDocs as RE,readProjectConfig as SE}from"document360-engine";function Gp(e){try{return RE(e).length}catch{return 0}}function qp(){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: 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, setting 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: 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; 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(`
|
|
425
|
+
`)}async function Bb(e,t){let n=t?.cwd??process.cwd();return SE(n)?Gp(n)===0?(console.log(u("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:qp(),display:"/inbox"}:(console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"})}ae();import{askBuilder as CE,openGapQuestions as Hb,readProjectConfig as PE}from"document360-engine";function pi(e){try{return Hb(e).length}catch{return 0}}function Vp(e,t){let n=[`\u2713 Question filed for your developers: .d360-writer/messages/${e}`," It is committed and pushed with your docs, so it reaches them wherever they work. Their answer comes"," back the same way, and /inbox folds it into the article for you."];return t>1&&n.push(` ${t} of your questions are now waiting for an answer.`),n}function Yp(e){let t=["Ask your developers something the code cannot tell you: why a feature exists, when to use it, what it","affects, or whether it can be undone.",""," /ask I can document how a refund works, but not whether it can be reversed or who should approve it","","The question is written to your docs folder and travels to them with your next save. You do not have to","stop working: keep writing what you can ground, and /inbox folds the answer in when it arrives."];if(e.length>0){t.push("",`Still waiting on ${e.length} question${e.length===1?"":"s"}:`);for(let n of e.slice(0,5))t.push(` \xB7 ${n.subject.replace(/^\[gap\]\s*/,"")}`);e.length>5&&t.push(` \xB7 \u2026and ${e.length-5} more`)}return t}async function Gb(e,t,n){let o=t?.cwd??process.cwd();if(!PE(o))return console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e.join(" ").trim();if(r===""){for(let s of Yp(Hb(o)))console.log(s.startsWith(" \xB7")?u(s):s);return{kind:"continue",ownNext:!0}}try{let s=CE(o,{question:r,...n?{article:n}:{}}),i=pi(o);for(let a of Vp(s.file,i))console.log(a.startsWith("\u2713")?X(a):u(a))}catch(s){console.log(H(`Could not file the question: ${s.message}`))}return{kind:"continue",ownNext:!0}}ae();import{listOpenHints as Kb,listOpenForDocs as IE,listOpenDirectives as LE,readProjectConfig as zb,computeSyncStatus as OE,planPull as ME,applyPull as _E,planImport as UE,applyImport as FE,pullDocsUpdates as WE,handoffAvailable as BE,readProductBriefState as HE,readDiscoveryQueue as GE,partitionOpenHints as Xb,askAboutUnfinishedHint as qE,briefMoved as VE}from"document360-engine";ae();import{readProjectConfig as TE,writeProjectConfig as qb,reconcileDocsGit as AE,pullDocsUpdates as EE,probeGitState as NE,resolveGitHandoff as Vb,handoffAvailable as DE}from"document360-engine";var hi=e=>e===1?"":"s";function io(e,t){let n=o=>{let r=(o??"").split(`
|
|
426
|
+
`).map(s=>s.trim()).filter(Boolean).slice(-1)[0];return r?` \u2014 ${r}`:""};switch(e){case"no-git":return"This folder is not a git repository, so there is nowhere to share to. Your docs are still saved on this machine.";case"detached-head":return"This repo is not on a branch right now. Ask your builder to check out a branch, then run /share.";case"mid-operation":return"A merge or rebase is in progress here. Finish or cancel it first, then run /share.";case"no-upstream":return"This branch has no remote yet, so there is nowhere to send your work. Ask your builder to run: git push -u origin HEAD";case"disabled":return"Sharing is switched off for this repo. Turn it on: /share on";case"diverged":return"Your work and your builder's have both moved on, so they can't be combined automatically. Your work is committed and safe \u2014 ask your builder to merge the branch.";case"rejected":return"Someone pushed to this branch first, so your work could not be sent. It IS committed and safe \u2014 try /share again in a moment, or ask your builder to merge the branch.";case"auth":return"Git could not sign in to the remote. Ask your builder to set up your git credentials, then run /share.";case"network":return"Could not reach the remote. Check your connection, then run /share again.";case"hook-failed":return`This repo's own commit checks rejected the change${n(t)}. Ask your builder to take a look \u2014 your docs are safe on this machine.`;case"failed":return`Git could not finish the share${n(t)}. Your docs are safe on this machine \u2014 run /share to try again, or show this line to your builder.`}}function Ll(e,t){let n=Vb(t);if(!n.commit)return[{tone:"info",text:"Sharing: off \u2014 d360-writer leaves its work for your coding agent to commit."},{tone:"info",text:"Turn it on: /share on"}];let o=NE(e);if(!o)return[{tone:"info",text:"Sharing: unavailable \u2014 this folder is not a git repository."}];if(!o.upstream)return[{tone:"warn",text:V("\u26A0")+`This branch (${o.branch??"detached"}) has no remote, so your work can't reach your team yet.`},{tone:"info",text:"Ask your builder to run: git push -u origin HEAD"}];let r=n.push===!0?"on":n.push==="unconfirmed"?"not set up yet":"off",s=[{tone:"info",text:`Sharing: ${o.branch} \u2192 ${o.upstream} \xB7 saving: on \xB7 sending: ${r}`}];return o.ahead>0?s.push({tone:"warn",text:V("\u26A0")+`${o.ahead} change${hi(o.ahead)} not shared yet \u2014 run /share`}):s.push({tone:"ok",text:V("\u2713")+"Everything is shared with your team."}),s}function Kp(e,t,n){qb({...t,gitHandoff:{commit:n,push:n}},e);let o=n?{tone:"ok",text:V("\u2713")+"Sharing on \u2014 d360-writer will save and send its own work from now on."}:{tone:"ok",text:V("\u2713")+"Sharing off \u2014 d360-writer will leave its work for your coding agent to commit."};return n?[o,...Ll(e,{...t,gitHandoff:{commit:!0,push:!0}})]:[o]}async function Ol(e,t){let n=[],o=Vb(t);if(!o.commit)return{lines:[{tone:"info",text:io("disabled")}],changed:!1};let r=t;o.push==="unconfirmed"&&DE(e,t)&&(r={...t,gitHandoff:{commit:!0,push:!0}},qb(r,e),n.push({tone:"info",text:"Sharing is now set up for this repo \u2014 d360-writer will keep doing this automatically."}));let s=await EE(e);if(s.ok&&s.pulled>0){let c=[s.newHints>0?`${s.newHints} new hint${hi(s.newHints)}`:null,s.newMessages>0?`${s.newMessages} new message${hi(s.newMessages)}`:null].filter(Boolean);n.push({tone:"ok",text:V("\u2B07")+`Got your builder's latest${c.length?` \u2014 ${c.join(", ")}`:""}.`})}else!s.ok&&s.reason!=="no-upstream"&&s.reason!=="no-git"&&n.push({tone:"warn",text:V("\u26A0")+io(s.reason,s.detail)});let i=await AE(e,r);if(i.commit&&!i.commit.ok)return n.push({tone:"warn",text:V("\u26A0")+io(i.commit.reason,i.commit.detail)}),{lines:n,changed:!1};let a=i.commit?.ok?i.commit.committed.length:0;if(a>0&&n.push({tone:"ok",text:V("\u2713")+`Saved ${a} change${hi(a)} to the docs folder.`}),i.push&&!i.push.ok)return n.push({tone:"warn",text:V("\u26A0")+io(i.push.reason,i.push.detail)}),{lines:n,changed:a>0};let l=i.push?.ok?i.push.pushed:0;return l>0?n.push({tone:"ok",text:V("\u2B06")+`Shared ${l} change set${hi(l)} with your team.`}):a===0&&(s.ok&&s.pulled===0)?n.push({tone:"ok",text:V("\u2713")+"Everything is already shared with your team."}):a>0&&!i.push&&n.push({tone:"info",text:"Saved on this machine only. /share on lets d360-writer send it to your team too."}),{lines:n,changed:a>0||l>0||s.ok&&s.pulled>0}}var jE={ok:X,info:Ae,warn:H,error:L};async function Yb(e,t){let n=t.cwd,o=TE(n);if(!o)return console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase(),s=a=>{for(let l of a)console.log(jE[l.tone](l.text))};if(r==="status")return s(Ll(n,o)),{kind:"continue"};if(r==="on"||r==="off")return s(Kp(n,o,r==="on")),{kind:"continue"};if(r)return console.log(L(`Unknown option "${r}". Use /share, /share status, /share on, or /share off.`)),{kind:"continue"};console.log(u("Exchanging work with your team\u2026"));let{lines:i}=await Ol(n,o);return s(i),{kind:"continue"}}function on(e){let t=0,n=0,o=0,r=0,s=0,i=0;try{let l=Xb(e,Kb(e));t=l.actionable.length,n=l.held.length,o=l.held.filter(c=>c.asked).length}catch{}try{let l=IE(e);r=l.filter(c=>c.kind==="request").length,s=l.filter(c=>c.kind==="answer").length}catch{}try{i=LE(e).length}catch{}let a=!1;try{a=VE(e)}catch{}return{hints:t,requests:r,answers:s,directives:i,held:n,heldAsked:o,briefMoved:a}}async function Xp(e){let t=zb(e);if(!t)return[];if(!BE(e,t))return[];let n=await WE(e);if(n.ok){if(n.pulled===0)return[];let o=[n.newHints>0?`${n.newHints} new hint${n.newHints===1?"":"s"}`:null,n.newMessages>0?`${n.newMessages} new message${n.newMessages===1?"":"s"}`:null].filter(Boolean);return[{tone:"ok",text:`\u2B07 Got your builder's latest${o.length?` \u2014 ${o.join(", ")}`:""}.`}]}return n.reason==="no-upstream"||n.reason==="no-git"?[]:[{tone:"warn",text:`\u26A0 Couldn't get your builder's latest first \u2014 ${io(n.reason,n.detail)}`}]}function zr(e){let t=[];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"}`);let n=t.join(", ");return e.briefMoved?n?`${n} and an updated product brief`:"an updated product brief":n||null}function Qp(e){let t=zr(e);return t?`Catching up on ${t}\u2026`:"Nothing queued from your builder \u2014 checking Document360 for reviewer comments and feedback\u2026"}function _l(e){let t={...e.queued,briefMoved:!1},n=zr(t);if(n)return{tone:"warn",note:`${V("\u26A0")}That run finished without writing anything, and ${n} ${t.hints+t.requests+t.answers+t.directives===1?"is":"are"} still queued \u2014 nothing was lost.`,lead:{cmd:"/catch-up",reason:"the queue is untouched, so running it again picks up the same work"}};if(e.queued.held>0){let o=e.queued.held;return{tone:"info",note:`${V("\u2139")}Nothing to write yet \u2014 your builder's ${o} note${fn(o)} ${o===1?"is":"are"} waiting on code that isn't finished. ${o===1?"It stays":"They stay"} queued.`,lead:null}}return e.hold?{tone:"info",note:`${V("\u2139")}No articles changed \u2014 product discovery is still open, so new overview and concept pages are on hold.`,lead:null}:{tone:"info",note:`${V("\u2713")}Nothing needed writing \u2014 no articles changed.`,lead:null}}function Jp(e){return{push:e.includes("--push")||e.includes("--publish"),skipReview:e.includes(_t),includeUnfinished:e.includes(Ul)}}var Ul="--include-unfinished";function fi(e){let t={hold:!1,openQuestions:0,answersPending:0};try{let n=HE(e);return!n||n.status==="confident"?t:{hold:!0,...GE(e)}}catch{return t}}function Zp(e){if(!e.hold)return[];let t="I'll update the reference pages, and hold new overview and concept pages";if(e.answersPending>0){let n=e.answersPending;return[{tone:"info",text:`${V("\u2139")}Product discovery is still open \u2014 ${n} answer${fn(n)} just arrived from your builder.`},{tone:"info",text:` I'll fold ${n===1?"it":"those"} in first; if that settles the brief, everything gets written as normal.`}]}if(e.openQuestions>0){let n=e.openQuestions;return[{tone:"warn",text:`${V("\u26A0")}Product discovery isn't finished \u2014 ${n} question${fn(n)} still with your builder.`},{tone:"warn",text:` ${t} until the brief is settled.`}]}return[{tone:"warn",text:`${V("\u26A0")}Product discovery isn't finished \u2014 the product brief is still a draft.`},{tone:"warn",text:` ${t} until it's settled (/discover continues it).`}]}function eh(e){try{return Xb(e,Kb(e)).held}catch{return[]}}function th(e,t){let n=0;for(let o of t)try{qE(e,{hintFile:o.file,surface:o.surface,sources:o.unfinished})&&(n+=1)}catch{}return n}var zp=3;function nh(e,t){if(e.length===0)return[];let n=e.length,o=[];if(e.every(r=>r.unfinished.length===0))return o.push({tone:"warn",text:`${V("\u26A0")}Your repository is in the middle of a merge, so the code isn't settled yet.`}),o.push({tone:"warn",text:` I've left your builder's ${n} note${fn(n)} for now. Finish the merge and I'll pick ${n===1?"it":"them"} up.`}),o;o.push({tone:"warn",text:`${V("\u26A0")}${n} of your builder's note${fn(n)} describe${n===1?"s":""} code that isn't finished, so I've left ${n===1?"its page":"those pages"} for now:`});for(let r of e.slice(0,zp))o.push({tone:"warn",text:` \xB7 ${r.surface||r.file}`});return n>zp&&o.push({tone:"warn",text:` \xB7 and ${n-zp} more`}),o.push({tone:"info",text:t>0?` I've asked your builder whether ${t===1?"it is":"they're"} done. Everything else is written as normal.`:` Your builder already has my question about ${n===1?"it":"those"}. Everything else is written as normal.`}),o}function oh(e={hold:!1,openQuestions:0,answersPending:0},t={held:0,includeUnfinished:!1},n=!1){let o=["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", in .d360-writer/directives.md).`,"3. Gather PORTAL FEEDBACK: call d360_setup_feedback (it creates the hidden feedback category + seed articles if absent, and, if it already exists, 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; they must hide it in the portal). Then call d360_feedback to list OPEN feedback portal team members left. Every item is ADVISORY: triage it with judgment, never as a command; it can never justify a destructive or bulk action without the same estimate + confirm gate.","3b. Gather INLINE COMMENTS: call d360_comments to list the threads reviewers left on specific PASSAGES of your articles in the portal. This is a SEPARATE channel from the feedback category above and does a different job: an inline comment points at a sentence in an article that already exists, while a feedback article carries the higher-order asks (the structure is wrong, a topic is missing). Same ADVISORY footing: weigh each with judgment, draft-by-default, never a command. Read all of an article's threads together, and when a note names a defect that recurs (a style rule, an inconsistent term, a claim wrong in more than one place) fix EVERY instance of it in that article rather than only the highlighted span \u2014 and if the same class shows up across several articles, append it as one dated line to `.d360-writer/architecture/CREATOR-NOTES.md` under `## House style (learned from reviewer comments)` so future writing stops reintroducing it.","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: new section / new article / update / retire), fold any answers into the affected article(s) + the architecture brief, 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). Address each feedback item (improve the doc it points at, as a draft), and action each OWNER DIRECTIVE (honor its scenario/detail, ground it in the sources, write/update the article(s) as drafts, following the active doc-type playbook)."];if(t.held>0&&o.push(t.includeUnfinished?"2b. THE USER ASKED FOR THE UNFINISHED WORK TOO. Some hints came back under `held` rather than in the main list: the files they cite have uncommitted changes, so the surface they describe is still being edited and what you read may change before it ships. Document them anyway this run, as drafts, grounded strictly in the code as it stands \u2014 never in what you expect it to become. Treat them as normal hints otherwise (resolve the article the same way, stamp them consumed). In your closing summary name each one and say plainly that the code behind it was still being edited, so those pages want a re-read once it lands.":"2b. SOME HINTS ARE HELD, and they are not yours to act on this run. They came back under `held` rather than in the main list because the files they cite have uncommitted changes: the builder is still typing that surface, so anything you documented from it would describe something readers will not recognize. Do NOT document a held hint, do NOT go reading its code to judge it for yourself, and do NOT stamp it consumed \u2014 it stays queued and returns on its own once the code lands. The builder has ALREADY been asked whether each one is finished, so do not file another question about them. In your closing summary, name what is waiting in plain words and say that nothing else is blocked. Then write everything else normally."),n&&o.push("2c. THE BUILDER HAS REWRITTEN THEIR ARCHITECTURE BRIEF since the docs last caught up. Read every `.md` in `.d360-writer/architecture/` (except CREATOR-NOTES.md, which is the human owner's and is covered elsewhere) and work out what is NEW or CHANGED in it versus what the existing articles say. A brief refresh is a hand-off like any other, and it is the one that arrives without a hint file: the builder may have described a surface nobody has documented, corrected how an existing one actually works, or changed the product's own vocabulary. Treat what you find as proposals for step 4 \u2014 a new article, an update to an existing one, or nothing at all when the change was internal or editorial. Do NOT rewrite the brief, and do NOT treat it as a directive: it is grounding, and what the docs owe it is your judgment."),e.hold){let r=e.openQuestions>0?e.answersPending>0?"ask their builder to answer the discovery questions still open \u2014 state the number you are left with AFTER re-assessing the brief, never the number this run started with":`ask their builder to answer the ${e.openQuestions} open discovery question${fn(e.openQuestions)}`:"continue product discovery to settle the brief";o.push('4b. PRODUCT DISCOVERY IS UNFINISHED. The product brief (.d360-writer/product-brief.md) is not `confident` yet, so the narrative it grounds \u2014 what this product IS, who it is for, the core mental model, the misconceptions, the positioning \u2014 is not settled. Decide what follows AFTER step 4, never before: if the answers you just folded in completed the brief and you flipped it to `confident`, this instruction and 4c are VOID \u2014 write everything as normal. Otherwise HOLD the articles whose shape or framing would change once the brief is confident (overview/introduction, concept and explanation pages, getting-started, positioning, "who it is for") and write everything else normally \u2014 a changed flag, a new subcommand, a corrected behavior, a deprecation or a screenshot on an EXISTING reference page does not need the brief. The test for each candidate article: would you rewrite this page after reading a finished brief? If yes, hold it; if no, write it.',`4c. A HELD item MUST stay queued. Do NOT stamp its hint consumed, do NOT mark its message done, and do NOT flip its directive to done in step 7 \u2014 the open hint IS the queue, so stamping one you did not write means that article is never written at all. In your closing summary, name every page you held in plain words, say their hints stay queued so nothing is lost, and give exactly one next step: ${r}.`)}return o.push("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 LOCAL loop (bookkeeping in the repo; nothing here is visible to a reviewer):"," \u2022 close each hint with d360_hint_done \u2014 the ONLY way to close one; never edit a hint file yourself. Pass outcome: documented plus the article path(s) you changed this run; use already-covered, retired or no-doc-change WITH a short note when no article needed writing \u2014 already-covered also needs the ONE article and `quote`: the passage in it that already says the thing, copied from the article (it is checked against the file). 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), including a step whose work you can verify an EARLIER session already completed but left unstamped, and append a step (d360_roadmap_add, with its run: command) for real new campaign work this run revealed; never delete existing steps;"," \u2022 for the Creator-notes feedback item (is_creator_notes:true): do NOT reply in it; 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; 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.)","10. NOW answer the people who asked, AFTER the push (steps 8-9), never before. A reviewer reads your reply in the portal and then looks at the article to check it, so replying first promises a change they cannot see. For anything whose push failed, do NOT reply on it; leave it outstanding and report it."," \u2022 for each INLINE COMMENT you actioned: call d360_comment_respond with its comment_id + article_id and a `reply` saying in plain words what you changed \u2014 in the reviewer's terms, mentioning where you applied the same fix more widely. Do NOT pass `resolve`: replying is your job, closing the thread is theirs, and they can only decide it is settled after seeing the change (your answer is recorded either way, so it will not come back at you). NEVER edit the reviewer's own comment text;"," \u2022 for each portal feedback item you actioned: append a short note at the BOTTOM of that feedback article via d360_update_article: `**d360-writer response:** \u2713 actioned in <article> (<date>)` (or `declined: <reason>`), NEVER overwriting the person's own text, then call d360_feedback_done(article_id, resulting_articles)."),o.push("Leave everything as DRAFTS for review; do not publish live. Publishing is a separate, reviewed step: articles you write here have not been read by an editor yet, so making them visible to readers is never part of this run. Tell the user what is waiting as a draft.",'Do NOT end with slash commands or a "what to do next" line. The tool prints the next step itself, scoped to what this run changed, and a second suggestion from you competes with it (yours will be the broader, more expensive one, because you cannot see how much was touched). Report what you did and stop.'),o.push("","End with a one-line-per-item summary of what you wrote/updated, and anything you couldn't ground (say plainly that you left a question for their engineers). Write the whole summary for a technical writer: no tool names, no internal file names, no raw status words, no hint ids, just plain sentences about what changed and what is worth their attention."),o.join(`
|
|
427
|
+
`)}var YE={status:OE,plan:ME,apply:_E,planImport:UE,applyImport:FE};async function rh(e,t=YE){let n={pulled:[],imported:[],conflicts:[],failed:[],needFolders:[]},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){if(r.remoteCategory&&!r.remoteCategory.hasLocalFolder){n.needFolders.push(r.title??r.articleId);continue}try{let s=await t.planImport({cwd:e.cwd,profileName:e.profileName,articleId:r.articleId,...r.remoteCategory?{categoryPath:r.remoteCategory.path}:{}});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 Ml=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,fn=e=>e===1?"":"s";function sh(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=[];e.pulled.length&&t.push(`\u2713 Pulled ${e.pulled.length} portal edit${fn(e.pulled.length)} into local: ${Ml(e.pulled)}`),e.imported.length&&t.push(`\u2713 Imported ${e.imported.length} new portal article${fn(e.imported.length)} into local drafts: ${Ml(e.imported)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${fn(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${Ml(e.conflicts)}`);for(let n of e.failed.slice(0,3))t.push(`\u26A0 ${n.path}: ${n.error}`);return e.failed.length>3&&t.push(`\u26A0 \u2026and ${e.failed.length-3} more left for /pull.`),e.needFolders.length&&t.push(`\u2139 ${e.needFolders.length} portal article${fn(e.needFolders.length)} ${e.needFolders.length===1?"is":"are"} in a category with no folder here \u2014 /pull creates ${e.needFolders.length===1?"it":"them"} and imports ${e.needFolders.length===1?"the article":"the articles"}: ${Ml(e.needFolders)}`),t}async function Qb(e,t){let n=t?.cwd??process.cwd();if(!zb(n))return console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Ze(n,t?.profileName);if(!o.ok)return console.log(L(o.reason)),{kind:"continue"};let{push:r,includeUnfinished:s}=Jp(e);for(let x of await Xp(n))console.log(x.tone==="ok"?X(x.text):H(x.text));console.log(u("Reconciling with Document360 (pulling any portal changes)\u2026"));let i=await rh({cwd:n,profileName:t?.profileName});for(let x of sh(i))console.log(x.startsWith("\u2713")?X(x):x.startsWith("\u2139")?u(x):H(x));let a=fi(n);for(let x of Zp(a))console.log(x.tone==="warn"?H(x.text):u(x.text));let l=eh(n),c=s?[]:l,h=th(n,c);for(let x of nh(c,h))console.log(x.tone==="warn"?H(x.text):u(x.text));let y=on(n);return console.log(u(Qp(y))),{kind:"forward-to-agent",prompt:oh(a,{held:l.length,includeUnfinished:s},y.briefMoved),display:`/catch-up${r?" --push":""}${s?` ${Ul}`:""}`}}ae();import{resolveActiveProfile as JE,resolveProjectId as ZE,loadProfileMap as eN,readCommentLedger as tN,isCommentOpen as nN,saveOpenCommentCount as oN,loadCommentSweepMemory as rN,recordCommentSweep as sN,planCommentSweep as iN,sweepOpenComments as aN,loadUserNames as lN,writeReviewerNotes as cN,sweptFromResult as uN,needsFullArchivePass as dN,reviewerNotesPath as pN,commentHtmlToText as Jb,annotatedText as hN,readProjectConfig as fN,loadPortalLabels as mN,portalBreadcrumb as ah,portalCategoryPath as gN,resolveModelForOperation as yN,runPartitioned as wN,snapshotArticles as bN,EMPTY_PORTAL_LABELS as kN}from"document360-engine";import je from"picocolors";import{CONTENT_CAP_VERSION as KE,stampArticles as zE,articlesChangedSince as XE,docsRootOf as QE}from"document360-engine";function Yo(e,t,n="",o){let r=[];try{r=XE(e,t)}catch{return{changed:[],cta:null}}if(r.length===0)return{changed:[],cta:null};try{zE(e,r,{writtenCap:KE,reviewedCap:0,checkedCap:0})}catch{}let s=QE(e),i=h=>{let y=h.replace(/\\/g,"/");return y.startsWith(`${s}/`)?y.slice(s.length+1):y},a=Mt(r.map(i)),l=r.length,c=a?"/push":"/push --all";try{return{changed:r,cta:Ut(e,{text:`${n}${l} article${l===1?"":"s"} updated \u2014 ${c} saves ${l===1?"it":"them"} to Document360 as ${l===1?"a draft":"drafts"}.`,cmd:c},n,a,o)}}catch{return{changed:r,cta:null}}}var ek=300,mi=3;function $N(e,t){let n=Ea(e).toLowerCase(),o=t.trim().replace(/\\/g,"/").replace(/^\/+|\/+$/g,"").toLowerCase();if(!o||n===o||n.endsWith(`/${o}`))return!0;let r=n.split("/").pop()??n;return r.startsWith(`${o}-`)||r===o||zn(n).toLowerCase()===o}async function Fl(e,t,n={}){let o=JE(e,t),r={profile:o.name,connection:o.connection,projectId:o.project.projectId,projectName:o.project.projectName},s=ZE(r,o.project.projectId),i=eN(e,o.name);if(!i)return{threads:[],answered:[],labels:kN,scanned:0,failed:[],truncated:0,skipped:0,archived:!1};let a=tN(e,o.name),l=new Set(Object.values(a).map(N=>N.articlePath).filter(N=>!!N)),c=Object.keys(a).length===0||l.size>0,h=n.articleIds?.length?new Set(n.articleIds):null,y=!!(h||n.path||n.scope),x=Object.entries(i.articles).filter(([,N])=>!!N.id).filter(([N,ne])=>h?h.has(ne.id):n.path?N.replace(/\\/g,"/")===n.path.replace(/\\/g,"/"):n.scope?$N(N,n.scope):!0).map(([N,ne])=>({articleId:ne.id,path:N,title:Na(e,N),answered:y||(c?l.has(N):!0)})),w=x.slice(0,ek),S=await mN(r,s,o.project.workspaceId,{cwd:e,profile:o.name}),P=y||n.full?{read:w,skipped:[]}:iN(w,{live:S.live,stateOf:N=>S.articles.get(N),memory:rN(e,o.name),alwaysRead:new Set(x.filter(N=>l.has(N.path)).map(N=>N.articleId))}),T=o.project.languageCode,R=dN(e)||!!n.full,D=await aN(r,s,P.read,{isOpen:(N,ne)=>nN(a,N.id??"",ne,N),...T?{langCode:T}:{},...n.onProgress?{onProgress:n.onProgress}:{},...R?{includeResolved:R}:{}}),B=D.threads.length>0||D.answered.length>0?await lN(r,s):new Map,G=cN(e,uN(D.threads,D.answered,N=>ah(S,N)),{userNames:B,ourReplyIds:Object.values(a).flatMap(N=>N.replyIds??[]),...R?{completeFor:P.read.filter(N=>!D.failed.some(ne=>ne.articleId===N.articleId)).map(N=>N.articleId)}:{}});y||oN(e,o.name,D.threads.length);let Q=new Map;for(let N of[...D.threads,...D.answered])Q.set(N.articleId,(Q.get(N.articleId)??0)+1);return sN(e,o.name,{live:S.live,read:P.read.map(N=>N.articleId),failedIds:D.failed.map(N=>N.articleId),threadCounts:Q,latestVersionOf:N=>S.articles.get(N)?.latestVersion}),{threads:D.threads,answered:D.answered,labels:S,scanned:D.scanned,failed:D.failed,truncated:Math.max(0,x.length-w.length),skipped:P.skipped.length,archived:G}}function vN(e,t=96){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n}var Zb=500;function xN(e){let t=hN(e.comment);if(!t)return"a passage";let n=t.replace(/\s+/g," ").trim();if(n.length<=Zb)return e.comment.commented_text_truncated?`\u201C${n}\u2026\u201D
|
|
428
|
+
(Document360 sends the first 500 characters of a highlight)`:`\u201C${n}\u201D`;let o=n.slice(0,Zb).trimEnd(),r=n.length-o.length;return`\u201C${o}\u2026\u201D
|
|
429
|
+
(+${r} more character${r===1?"":"s"}${e.comment.commented_text_truncated?", and Document360 caps a highlight at 500":""})`}function RN(e,t){let n=gN(t,e.articleId);return n.length>0?n.join(" \u203A "):e.path?zn(e.path):""}function SN(e,t){return t.articles.get(e.articleId)?.title?.trim()||e.title||(e.path?Ms(e.path):e.articleId)}function CN(e,t){return ah(t,e.articleId,{category:e.path?zn(e.path):null,title:e.title??(e.path?Ms(e.path):null)})??e.path??e.articleId}function Ko(e,t){let n=new Map;for(let o of e){let r=n.get(o.articleId);r||(r={articleId:o.articleId,path:o.path,category:RN(o,t),title:SN(o,t),label:CN(o,t),threads:[]},n.set(o.articleId,r)),r.threads.push(o)}return[...n.values()].sort((o,r)=>o.category.localeCompare(r.category)||o.title.localeCompare(r.title))}var PN=100,TN=120,tk=(e,t)=>Math.max(40,Math.min(e??96,t));function nk(e){let t=s=>s===1?"":"s",n=new Set(e.threads.map(s=>s.articleId)).size,o=e.answered.length,r=[`${e.threads.length} open`,`${n} article${t(n)}`];return o>0&&r.push(`${o} answered, awaiting reviewer`),r.push(e.skipped>0?`${e.scanned} of ${e.scanned+e.skipped} articles re-read`:`${e.scanned} checked`),`${je.bold("Reviewer comments")} ${r.join(` ${je.gray("\xB7")} `)}`}function ih(e){let t=[],n=o=>o===1?"":"s";if(e.skipped>0&&t.push(je.gray(` ${e.skipped} article${n(e.skipped)} weren\u2019t re-read \u2014 nobody has drafted or commented on them since your last check, so they can\u2019t have new comments. /comments --full reads every one.`)),e.failed.length){t.push(`${V("\u26A0",je.yellow)}${e.failed.length} article${n(e.failed.length)} couldn\u2019t be checked this time \u2014 they may have comments too:`);for(let o of e.failed.slice(0,5)){let r=ah(e.labels,o.articleId,{title:o.title})??o.title??o.articleId;t.push(` ${je.gray(`${r} \u2014 ${vN(o.error,60)}`)}`)}e.failed.length>5&&t.push(` ${je.gray(`+${e.failed.length-5} more`)}`),t.push(je.gray(" Run /comments again to retry them."))}return e.truncated&&t.push(`${V("\u26A0",je.yellow)}Checked the first ${ek} articles; ${e.truncated} not checked this run.`),e.archived&&(e.threads.length>0||e.answered.length>0)?t.push(je.gray(` Everything reviewers have written is kept in ${pN(".").replace(/\\/g,"/").replace(/^\.\//,"")} \u2014 it outlives a rewrite.`)):!e.archived&&(e.threads.length>0||e.answered.length>0)&&t.push(`${V("\u26A0",je.yellow)}Couldn\u2019t write the reviewer-notes file, so Document360 is still the only copy of these notes.`),t}function gi(e,t={}){let n=[],o=a=>a===1?"":"s",r=e.answered.length,s=()=>{if(!(!t.showAnswered||r===0)){n.push(` ${je.gray(`Answered, waiting on the reviewer (${r})`)}`);for(let a of Ko(e.answered,e.labels))n.push(` ${je.gray(`${a.label} \u2014 ${a.threads.length} thread${o(a.threads.length)}`)}`);n.push("")}};if(e.threads.length===0){let a=r>0?` ${je.gray("\xB7")} ${r} answered, awaiting reviewer`:"",l=e.scanned+e.skipped;return n.push(e.skipped>0?`${V("\u2713",je.green)}No open reviewer comments in the ${e.scanned} article${o(e.scanned)} checked ${je.gray("\xB7")} ${e.skipped} of ${l} not checked${a}`:`${V("\u2713",je.green)}No open reviewer comments across ${e.scanned} article${o(e.scanned)}.${a}`),r>0?(n.push(je.gray(` Those ${r} are answered and left open on purpose \u2014 the reviewer closes them once they\u2019ve checked the change.`)),t.showAnswered||n.push(je.gray(" /comments --answered lists them."))):n.push(je.gray(" Reviewers leave these by highlighting text in a draft in the Document360 portal and commenting on it.")),n.push(""),s(),n.push(...ih(e)),n}let i=Ko(e.threads,e.labels);return n.push(nk(e)),n.push(""),n.push(Qs(["#","Category","Article","Comments"],i.map((a,l)=>[`${l+1}`,a.category||"(root)",a.title,`${a.threads.length}`]),tk(t.width,PN),{plain:!0,align:["left","left","left","right"]})),n.push(""),s(),n.push(...ih(e)),n}function Wl(e,t={}){let n=s=>s===1?"":"s",o=[`${je.gray("Category:")} ${e.category||"(root)"}`,`${je.gray("Article: ")} ${je.bold(e.title)}`,je.gray(`${e.threads.length} comment${n(e.threads.length)} from your reviewers`),""],r=e.threads.map(s=>{let i=[Jb(s.comment.comment)||"(empty comment)"];for(let a of s.comment.replies??[])i.push(`\u21B3 ${Jb(a.comment)}`);return s.comment.status==="reopened"&&i.push("(reopened \u2014 you answered this once and the reviewer came back)"),s.canResolve||i.push("(you can reply to this one, but your role can\u2019t resolve it)"),[xN(s),i.join(`
|
|
430
|
+
`)]});return o.push(Qs(["Annotated text","Comment"],r,tk(t.width,TN),{plain:!0})),o.push(""),o}function Bl(e){let t=e.reduce((r,s)=>r+s.threads.length,0),n=r=>r===1?"":"s",o=[{kind:"all",label:`All articles \u2014 answer all ${t} comment${n(t)}`,groups:e}];return e.forEach((r,s)=>{o.push({kind:"article",n:s+1,label:r.title,note:`${r.threads.length} comment${n(r.threads.length)}`,group:r})}),o}function lh(e,t={}){let n=Ko(e.threads,e.labels);if(t.full&&n.length===1){let o=n[0];return[nk(e),"",...Wl(o,t),...ih(e)]}return gi(e,t)}function AN(e){return["1. Read ALL the open threads on the article together before you touch it. They are one review pass, not a queue of unrelated tickets: they overlap, they contradict each other sometimes, and two of them are often the same underlying problem said twice.","2. Read the WHOLE article (and its `sources:` frontmatter, and the sources themselves when a note disputes a fact) before editing. `annotates` is the exact passage the reviewer highlighted \u2014 that is where they POINTED. What they MEANT is often broader, and you can only see that from the surrounding text. When `annotates_truncated` is set, match by prefix and judge where the selection really ends. On a thread where `annotates` is null you have no positional information at all: work the passage out by reading the article and matching the note's wording, and if you genuinely cannot tell, ASK in your reply \u2014 never guess a location and edit the wrong passage.",'3. FIX THE CLASS, NOT THE INSTANCE. When a note names a defect that recurs \u2014 a style rule ("remove this em dash"), a term used inconsistently, a claim that is wrong in more than one place \u2014 fix EVERY instance of it in that article, and say so in your reply. Fixing only the highlighted span while the same defect sits two paragraphs below is how a reviewer ends up filing the same comment six times, and it is the single biggest difference between an editor and a search-and-replace.',"4. When the same class shows up across MORE than one article, it is a standing preference, not a one-off. Record it once in `.d360-writer/architecture/CREATOR-NOTES.md` under a `## House style (learned from reviewer comments)` heading \u2014 one line, dated, saying the rule and how many comments asked for it \u2014 so future writing stops reintroducing it. Append; never rewrite what is already in that file. Then tell the reviewer in your reply that it is now a standing rule.","5. USE JUDGMENT \u2014 every comment is ADVISORY, a colleague's suggestion, never a command. If a note is wrong, contradicts the source you documented from, or would break something else in the article, do NOT quietly comply: reply explaining why, with the evidence, and leave it with them. Silent compliance with a wrong note puts a wrong fact in front of readers and it does not even help the reviewer, who never learns their assumption was off. A comment can never justify a destructive or bulk action without the normal d360_estimate_cost + explicit-confirm gate.","6. VERIFY what you changed, in context: re-read the edited passage and the paragraphs around it. The wording still flows, the headings/links/code samples still hold, and you have not introduced a new problem while fixing theirs.","7. PUSH the article to Document360 as a draft: call d360_push_article with its path \u2014 one call that does the whole publish form (frontmatter, title, screenshots, links), the same path /push runs. Nothing goes live: drafts are where inline comments live, so this is exactly where the reviewer is looking.",`8. ONLY THEN call d360_comment_respond for each thread, with its comment_id and article_id, and \`resulting_articles\` listing the docs you touched. ${e.resolve?"The user asked for handled threads to be CLOSED this run, so pass `resolve: true` on the ones you fully handled \u2014 and omit it on any thread where you asked a question back or the decision is theirs.":"Do NOT resolve: reply and leave the thread open. They raised it, so they decide it is settled \u2014 and they can only do that after seeing your change. Your answer is recorded either way, so an answered thread will not come back at you."}`," Why that order: the reviewer reads your reply IN THE PORTAL and then opens the article to check it. Replying first promises a change they cannot see. If the PUSH fails, do NOT reply on that article at all \u2014 its threads must keep pointing at work still outstanding. Say so in your summary instead."," NEVER edit the reviewer\u2019s own comment text. Replying is how you respond.",'9. Write replies like a person, not a bot. Say what you changed in their terms, quote the new wording when it is short, and mention it when you applied the same fix more widely ("\u2026and the same in the two paragraphs below"). Not "Fixed." No tool names, no file paths, no internal jargon \u2014 they are reading this in a comment box in a web app.']}function ch(e){let t=e.count===1?"":"s";return[`Answer the ${e.count} reviewer comment${t} on one article: \u201C${e.label}\u201D${e.path?` (local file: ${e.path})`:""}.`,"",`Call d360_comments with article_id "${e.articleId}" to read its open threads \u2014 scope it to that id, never sweep the whole knowledge base, which costs one API read per article. A thread whose status is \`reopened\` is one you already answered and the reviewer was NOT satisfied with, so read its replies \u2014 yours included \u2014 before touching the article, and do not simply repeat the previous fix.`,"",...AN({resolve:e.resolve}),"","End with one line per thread: what the reviewer asked, what you changed, and whether you left it with them. Plain sentences for a technical writer \u2014 no tool names, no internal file names. Then say the updated article is now a draft in Document360, so the reviewers can see the changes where they left their comments, and that it stays a draft \u2014 readers keep seeing the previous version \u2014 until someone asks for it to be published live."].join(`
|
|
431
|
+
`)}function uh(e){let t={answer:!1,resolve:!1,all:!1,showAnswered:!1,scope:{}};for(let n=0;n<e.length;n++){let o=e[n];o==="--answer"?t.answer=!0:o==="--resolve"?t.resolve=!0:o==="--all"?t.all=!0:o==="--full"?t.scope.full=!0:o==="--answered"||o==="--waiting"?t.showAnswered=!0:o==="--scope"?t.scope.scope=e[++n]:o.startsWith("--scope=")?t.scope.scope=o.slice(8):o.startsWith("-")||(t.scope.path=o)}return t.all&&(t.answer=!0),t.scope.scope===void 0&&delete t.scope.scope,t.scope.path===void 0&&delete t.scope.path,t}async function EN(e,t,n){if(t.length===0)return{kind:"continue"};let o=t.reduce((y,x)=>y+x.threads.length,0),{model:r}=yN(e.cwd,"standard"),s=new Map(t.map(y=>[y.label,y])),i=t.map(y=>({label:y.label,paths:y.path?[y.path]:[]}));console.log(u(`Answering ${o} comment${o===1?"":"s"} across ${i.length} article${i.length===1?"":"s"} (\u2264${mi} agents at once) on ${r}. Each article is fixed, pushed to Document360 as a draft, then answered${n.resolve?" and resolved":" \u2014 the threads stay open for your reviewers to close"}\u2026`));let a=Date.now(),l=bN(e.cwd);try{for await(let y of wN({cwd:e.cwd,partitions:i,promptFor:x=>{let w=s.get(x.label);return ch({articleId:w.articleId,label:w.label,path:w.path,count:w.threads.length,resolve:n.resolve})},concurrency:mi,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),allowCommentResolve:n.resolve,model:r}))if(y.type==="partition_status")y.status==="running"?console.log(u(` \u25B8 ${y.label} \u2014 answering\u2026`)):y.status==="done"?console.log(X(` \u2713 ${y.label}`)):console.log(L(` \u2717 ${y.label}`));else if(y.type==="run_done"){let x=y.results.filter(w=>!w.ok);console.log(""),console.log(`${y.results.length-x.length}/${i.length} article${i.length===1?"":"s"} answered.`),x.length&&console.log(H(`\u26A0 ${x.length} left untouched (their comments are still open, so nothing was promised to those reviewers): ${x.map(w=>w.label).join(", ")}`)),y.blocked&&console.log(H(`\u26A0 ${y.blocked}`)),y.allEmpty&&console.log(H("\u26A0 No agent produced any work this run \u2014 nothing was changed or answered.")),console.log(u(dn(Wt(a,y.results,y.totalCostUsd))))}}catch(y){console.log(L(`Answering comments failed: ${y.message}`))}let h=Yo(e.cwd,l,"","/comments").changed.length;return h>0&&console.log(`${h} article${h===1?"":"s"} changed, and that new text has not been read by an editor \u2014 ${h===1?"it":"they"} can go live once /review has been over ${h===1?"it":"them"}.`),{kind:"continue"}}async function ok(e,t){let n=t?.cwd??process.cwd();if(!fN(n))return console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Ze(n,t?.profileName);if(!o.ok)return console.log(L(o.reason)),{kind:"continue"};let r=uh(e);console.log(u("Checking Document360 for reviewer comments\u2026"));let s;try{s=await Fl(n,t?.profileName,r.scope)}catch(a){return console.log(L(`Couldn\u2019t read comments from Document360: ${a.message}`)),{kind:"continue"}}for(let a of lh(s,{full:!!r.scope.path,showAnswered:r.showAnswered}))console.log(a);if(s.threads.length===0)return{kind:"continue"};if(r.answer&&t)return EN(t,Ko(s.threads,s.labels),{resolve:r.resolve});let i=Ko(s.threads,s.labels)[0];return console.log(`${V("\u2192",je.yellow)}${je.bold("/comments <article>")} shows one article\u2019s comments in full `+je.gray(i?.path?`(e.g. /comments ${i.path})`:"(by its local path)")),console.log(`${V("\u2192",je.yellow)}${je.bold("/comments --answer")} fixes each one, updates the draft in Document360, then replies in the thread `+je.gray("(one article at a time: /comments --answer <article>, or --scope <category>)")),{kind:"continue"}}ae();import{spawn as sk}from"node:child_process";import{mkdirSync as NN,openSync as DN,readFileSync as jN}from"node:fs";import{dirname as IN,join as LN}from"node:path";import{logsDir as ON}from"document360-engine";var zo="document360-writer",Xr=`npm i -g ${zo}@latest`,MN="document360-capture";function _N(){return new Promise(e=>{try{let t=sk("d360-capture --version",{stdio:"ignore",shell:!0,windowsHide:!0});t.on("error",()=>e(!1)),t.on("close",n=>e(n===0))}catch{e(!1)}})}function yi(){return LN(ON(),"self-update.log")}function dh(e){return/\bEBUSY\b|\bETXTBSY\b|resource busy or locked|text file busy/i.test(e)}function Hl(){return process.platform==="win32"}var ph=null;function Gl(e){ph=e}function wi(e){return dh(e)?`Another d360-writer is still running and holding its files open. Close every d360-writer window, then run: ${Xr}`:/\bEACCES\b|permission denied|EPERM|operation not permitted/i.test(e)?process.platform==="win32"?`Permission denied. Run ${Xr} from an Administrator terminal.`:`Permission denied \u2014 your global npm folder isn't writable. Either run sudo ${Xr} , or (better) switch to a Node version manager such as nvm or fnm so global installs need no sudo.`:/ENOTFOUND|EAI_AGAIN|ETIMEDOUT|ECONNRESET|network/i.test(e)?`Couldn't reach the npm registry. Check your connection or proxy, then run: ${Xr}`:/EBADENGINE|Unsupported engine/i.test(e)?`Your Node version is too old for this release. Install Node 20 or later, then run: ${Xr}`:`Run manually: ${Xr}`}function UN(e,t=6){return e.split(/\r?\n/).map(n=>n.trimEnd()).filter(Boolean).slice(-t).join(`
|
|
432
|
+
`)}async function bi(){let e=process.platform==="win32",n=await _N()?[zo,MN]:[zo],o=yi(),r=null;try{NN(IN(o),{recursive:!0}),r=DN(o,"w")}catch{r=null}let s=()=>{try{return UN(jN(o,"utf8"))}catch{return""}};return new Promise(i=>{try{let a=sk(`npm i -g ${n.map(l=>`${l}@latest`).join(" ")}`,{stdio:r===null?"ignore":["ignore",r,r],shell:!0,detached:!e,windowsHide:!0});a.on("error",l=>i({ok:!1,output:`${String(l)}
|
|
433
|
+
${s()}`.trim(),packages:n})),a.on("close",l=>i({ok:l===0,output:l===0?"":s(),packages:n})),e||a.unref()}catch(a){i({ok:!1,output:String(a),packages:n})}})}var rk=[1500,2e3,2500],FN=e=>new Promise(t=>setTimeout(t,e));async function ql(e={}){let t=ph;if(t===null)return"none";ph=null;let n=e.run??bi,o=e.wait??FN,r=e.write??(a=>console.log(a)),s=t?`v${t}`:"the update";r(""),r(u(oe("\u2B06",`Installing ${s}\u2026 (don\u2019t close this window)`)));let i=e.spinner===!1?null:WN();try{let a={ok:!1,output:"",packages:[]};for(let l=0;a=await n(),!(a.ok||!dh(a.output)||l>=rk.length);l++)await o(rk[l]);return i?.(),a.ok?(r(X(oe("\u2713",`Updated to ${s} \u2014 it\u2019s live next time you start d360-writer.`))),"installed"):dh(a.output)?(r(H(oe("\u26A0",`Couldn\u2019t install ${s} \u2014 another d360-writer window is still open.`))),r(u(" It installs when the last one closes.")),"busy"):(r(H(oe("\u26A0",`Couldn\u2019t install ${s}. ${wi(a.output)}`))),r(u(` Full output: ${yi()}`)),"failed")}catch{return i?.(),"failed"}}function WN(){if(!process.stdout.isTTY)return null;let e=0,t=setInterval(()=>{e=e%3+1,process.stdout.write(`\r ${".".repeat(e)}${" ".repeat(3-e)}`)},1e3);return()=>{clearInterval(t),process.stdout.write("\r \r")}}async function ik(){if(Hl())return Gl(""),console.log(u("\u2B06 Windows can\u2019t replace the files while d360-writer is running.")),console.log(u(" I\u2019ll install the update the moment you /exit.")),{kind:"continue"};console.log(u("Updating the d360-writer toolchain\u2026"));let e=await bi();return e.ok?(console.log(X(`\u2713 Updated ${e.packages.join(" + ")}. Exit (/exit) and relaunch d360-writer to apply.`)),{kind:"continue"}):(console.log(L(`Update failed. ${wi(e.output)}`)),e.output&&console.log(u(e.output)),console.log(u(`Full output: ${yi()}`)),{kind:"continue"})}ae();Kn();import{existsSync as hh,rmSync as BN}from"node:fs";import{basename as ak,resolve as fh}from"node:path";import{execFileSync as HN}from"node:child_process";import{input as GN}from"@inquirer/prompts";import{readProjectConfig as qN,devHintsGuidePath as VN}from"document360-engine";var YN=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],KN=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),Vl=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),lk=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function ck(e){let t=Vl(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:lk(t)?!0:KN.has(t)}function mh(e){let t=null;try{t=qN(e)}catch{t=null}let n=new Set(YN);for(let o of[Vl(t?.docsDir),Vl(t?.captureDir),Vl(t?.outputDir)])o&&lk(o)&&n.add(o);return[...n].filter(o=>ck(o)&&hh(fh(e,o)))}function gh(e,t){let n=[],o=[];for(let r of t){if(!ck(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{BN(fh(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function uk(e,t){try{return HN("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
|
|
434
|
+
`).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function zN(e){return uk(e,".d360-writer/hints")}function XN(e){return uk(e,".d360-writer/messages")}function yh(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=zN(e),o=XN(e),r=hh(fh(e,"user-docs"));return["\u26A0 This permanently DELETES everything d360-writer created here:",...t.map(s=>` \u2022 ${s}`),"",...n>0?[`\u26A0 ${n} doc hint(s) under .d360-writer/hints/ are not committed \u2014 commit them first or they're gone.`]:[],...o>0?[`\u26A0 ${o} message(s) under .d360-writer/messages/ are not committed \u2014 commit them first or they're gone.`]:[],...r?["Note: a repo-root user-docs/ is NOT touched (only .d360-writer/ is removed)."]:[],"Undo = git: committed files are restorable; untracked ones (most screenshots) are gone.",`To confirm, type the repo name: ${ak(e)}`]}async function dk(e,t){let n=mh(t.cwd);for(let l of yh(t.cwd,n))console.log(n.length===0?u(l):l);if(n.length===0)return{kind:"continue"};let o=ak(t.cwd);if((await t.withPausedInput(()=>GN({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(H("Reset canceled \u2014 nothing deleted.")),{kind:"continue"};let s=hh(VN(t.cwd)),{removed:i,failed:a}=gh(t.cwd,n);console.log(X(`\u2713 Reset complete \u2014 removed ${i.length} item${i.length===1?"":"s"}. The repo is back to its original state.`));for(let l of a)console.log(L(` \u2717 ${l.path}: ${l.error}`));if(s){for(let l of Sa())console.log(l);console.log(u("(Select and copy the prompt above to paste into your coding agent.)"))}return console.log(u("Set up d360-writer again with /init (then /login, /workspace).")),{kind:"continue"}}ae();import{buildRegistry as $h,clearRegistryCache as QN,lintArticles as Yl,listAvailablePacks as wh,readProjectConfig as Dn,readStyleBaseline as JN,clearStyleBaseline as ZN,styleBaselinePath as eD,recordStyleSwitch as tD,declineStyleSweep as nD,styleSweepOutstanding as oD,resolveActivePacks as vh,styleGuidePath as hk,writeProjectConfig as xh,buildStyleCompilePrompt as rD,loadStyleGuide as sD,loadHouseRules as iD,buildStyleLearnPrompt as aD,reviewerNotesPath as lD,listStyleGuides as cD,getStyleGuide as uD,resolveActiveProfile as dD,resolveProjectId as pD,styleGuideSettled as hD,styleGuideUpgradeOffered as fk,DEFAULT_PACK as Rh,STYLE_GUIDE_MAX_CHARS as pk,BUILTIN_RULES as Kl,ALWAYS_ON_PACK as ao}from"document360-engine";import{existsSync as Sh,mkdirSync as fD,readFileSync as mk,writeFileSync as bh}from"node:fs";import{dirname as mD}from"node:path";import{createHash as gD}from"node:crypto";function Qr(e){let t=e.filter(o=>!o.startsWith("--")),n=(t[0]??"").toLowerCase();return n==="list"?{sub:"list"}:n==="use"?{sub:"use",value:t.slice(1).join(" ")}:n==="keep"?{sub:"keep"}:n==="sweep"?{sub:"sweep",value:t[1]}:n==="explain"?{sub:"explain",value:t[1]}:n==="pull"?{sub:"pull",value:t[1]}:n==="compile"?{sub:"compile"}:n==="learn"?{sub:"learn"}:{sub:"show"}}function yD(e){try{return My(e,"/style-guide")?.title??null}catch{return null}}function Ch(e){try{return!hD(Dn(e)?.styleGuide)}catch{return!1}}function gk(e,t){let n=[],o=new Set,r=s=>{if(o.has(s))return;o.add(s),Or(e,s).ok&&n.push(oe("\u2713",`That settles a docs-campaign step \u2014 marked done: ${s}`))};try{let s=yD(e);if(s&&r(s),t)for(let i of Ka(e,t))r(i)}catch{}return n}function wD(e){let t=Dn(e)??{projectId:""},n=vh(t.styleGuide).filter(s=>s!==ao),o=fk(t.styleGuide);xh({...t,styleGuide:{...t.styleGuide,decidedAt:new Date().toISOString(),...o?{declinedUpgrade:Rh}:{}}},e);let r=[oe("\u2713",n.length>0?`Keeping ${n.join(", ")} \u2014 plus the built-in checks, which are always on.`:"Keeping the built-in checks only \u2014 the correctness rules and the anti-slop rules, both always on."),u(" Change your mind any time: /style-guide use \xB7 see the options: /style-guide list")];return r.push(...gk(e)),r}var ki="House";async function bD(e,t,n){let o,r;try{let P=dD(e,n);o={profile:P.name,connection:P.connection,projectId:P.project.projectId,projectName:P.project.projectName},r=await pD(o,P.project?.projectId)}catch(P){return{lines:[oe("\u2717",`Not signed in to Document360: ${P instanceof Error?P.message:String(P)}`),u(" Run /login first.")],restart:!1}}let s=await cD(o,r);if(s.kind!=="ok")return{lines:[oe("\u26A0",`Document360 didn't return your style guides \u2014 ${s.reason}.`),u(" Nothing is blocked. Your house style guide lives at .d360-writer/style-guide.md \u2014 write or paste"),u(" it there directly, and /review and the writer both read it. /style-guide compile then turns its"),u(" mechanical parts into checks.")],restart:!1};if(s.guides.length===0)return{lines:[oe("\u2139","This Document360 project has no style guides yet."),u(" Admins create them in the portal, or write your own at .d360-writer/style-guide.md.")],restart:!1};if(!t)return{lines:["Style guides in this Document360 project:","",...s.guides.map((T,R)=>{let D=[T.language_code,T.created_by_name,T.created_at?.slice(0,10)].filter(Boolean).join(" \xB7 ");return` ${R+1} ${T.name??T.id}${T.is_default?u(" (default)"):""}${D?u(` ${D}`):""}`}),"",u(" Pull one: /style-guide pull 1 (or paste its id)")],restart:!1};let i=Number(t),a=Number.isInteger(i)&&i>=1&&i<=s.guides.length?s.guides[i-1]:s.guides.find(P=>P.id===t);if(!a)return{lines:[oe("\u2717",`No style guide numbered or identified by "${t}". Run /style-guide pull to list them.`)],restart:!1};let l=await uD(o,r,a.id,{langCode:a.language_code});if(l.kind!=="ok"){let P=l.kind==="notFound"?"Document360 could not find it (style guides are per language)":l.reason;return{lines:[oe("\u2717",`Could not read "${a.name??a.id}" \u2014 ${P}.`)],restart:!1}}let c=(l.guide.content??"").trim();if(!c)return{lines:[oe("\u26A0",`"${a.name??a.id}" has no content yet \u2014 nothing to pull.`)],restart:!1};let h=hk(e),y=[];if(Sh(h))try{bh(`${h}.bak`,mk(h,"utf8"),"utf8"),y.push(u(" Your previous guide is at .d360-writer/style-guide.md.bak"))}catch{}let x=c.length>pk?c.slice(0,pk):c,w=`<!-- Pulled from Document360: "${a.name??a.id}" (${new Date().toISOString().slice(0,10)}). Edit freely \u2014 /style-guide pull overwrites this file. -->
|
|
435
|
+
|
|
436
|
+
`;fD(mD(h),{recursive:!0}),bh(h,`${w}${x}
|
|
437
|
+
`,"utf8");let S=Dn(e)??{projectId:""};return xh({...S,styleGuide:{...S.styleGuide,pulledFrom:{styleGuideId:a.id,name:a.name??a.id,pulledAt:new Date().toISOString(),contentHash:gD("sha1").update(x).digest("hex").slice(0,16)}}},e),{lines:[oe("\u2713",`Pulled "${a.name??a.id}" into .d360-writer/style-guide.md (${x.length.toLocaleString()} characters).`),...y,u(" This is PROSE, not rules \u2014 /review judges against it, and the writer now writes to it."),u(" Turn its mechanical parts into checks: /style-guide compile"),u(" Restarting the agent so it writes to the new guide\u2026")],restart:!0}}function kD(e){let t=$h(e).rules.filter(n=>n.pack.toLowerCase()===ki.toLowerCase()).map(n=>n.id);return{prompt:rD({guide:sD(e),packName:ki,existingRuleIds:t}),display:"/style-guide compile"}}function $D(e){let t=lD(e),n=Sh(t)?mk(t,"utf8").trim():"";return!n||!/^## /m.test(n)?{kind:"nothing",lines:[oe("\u2139","No reviewer comments have been read yet, so there is nothing to learn from."),u(" Reviewers comment on your drafts in Document360; /comments reads them, and every read"),u(" keeps a copy in .d360-writer/reviewer-notes.md. Run /comments first.")]}:{kind:"run",prompt:aD({notes:n,existingRules:iD(e),houseRulesFile:".d360-writer/house-rules.md"}),display:"/style-guide learn"}}function yk(){return[u(" Read what it wrote: git diff .d360-writer/house-rules.md"),u(" These rules apply from now on \u2014 the writer follows them and /review judges against them."),u(" Disagree with one? Delete the line. It is your file, and nothing regenerates it."),u(" Restarting the agent so it writes to the new rules\u2026")]}function wk(){return[u(` Review what it wrote: git diff .d360-writer/styles/${ki}/`),u(` Anything it could not check mechanically is listed in .d360-writer/styles/${ki}/UNCHECKABLE.md \u2014 /review judges those.`),u(` Turn them on when you are happy: /style-guide use ${ki.toLowerCase()} (they start as warnings, never blocking)`)]}var it=(e,t)=>`${e} ${t}${e===1?"":"s"}`,kh=e=>/^v\d/i.test(e)?e:`v${e}`;function vD(e){let t=(e.description??`${e.name} style guide`).trim().replace(/\s+/g," "),n=/^(.{0,72})(?:[.,:;—]|$)/.exec(t)?.[1]?.replace(/[.,:;—\s]+$/,"").trim();if(n&&n.length>0)return n;let o=t.slice(0,72),r=o.lastIndexOf(" ");return`${r>20?o.slice(0,r):o}\u2026`}function bk(e){let t={error:0,warning:0,suggestion:0};for(let n of e)t[n.severity]=(t[n.severity]??0)+1;return["error","warning","suggestion"].filter(n=>t[n]>0).map(n=>`${t[n]} ${n}`).join(" \xB7 ")}function xD(e){let n=Dn(e)?.styleGuide?.pulledFrom;return n?`.d360-writer/style-guide.md \u2014 pulled ${n.pulledAt.slice(0,10)} from "${n.name}"`:Sh(hk(e))?".d360-writer/style-guide.md (yours)":"the built-in default"}function RD(e){let t=Dn(e),n=$h(e),o=(t?.styleGuide?.packs??[]).filter(Boolean),r=n.packs.filter(c=>c.name.toLowerCase()===ao),s=n.packs.filter(c=>{let h=c.name.toLowerCase();return h!==ao&&h!=="d360"}),i=t?.styleGuide?.packs===void 0&&s.length>0,a=[`Style guide: ${xD(e)}`,`Rule packs: ${s.length>0?s.map(c=>`${c.name.toLowerCase()} ${kh(c.version)}`).join(", ")+(i?u(" (the default \u2014 nobody has chosen yet)"):""):u("none chosen")}`,`Always on: ${u(`d360 (correctness, built in \u2014 ${it(Kl.filter(c=>c.id.startsWith("D360.")).length,"rule")})`)}`];for(let c of r)a.push(` ${u(`${c.name.toLowerCase()} ${kh(c.version)} (anti-slop \u2014 ${it(c.ruleCount,"rule")})`)}`);r.length>0&&(a.push(u(" Every article here is machine-written, so these cannot be switched off by")),a.push(u(" choosing another pack. styleGuide.humanise: false turns them off deliberately.")));let l=[...Kl.map(c=>({severity:c.severity})),...n.rules.map(c=>({severity:c.severity}))];a.push("",`${it(l.length,"rule")} active \xB7 ${bk(l)}`);try{let c=Yl({cwd:e}),h=c.findings.filter(x=>!x.baselined),y=h.filter(x=>x.severity==="error").length;a.push(""),a.push(y===0?oe("\u2713",`No style errors across the docs${h.length>0?`, though ${it(h.length,"other issue")} ${h.length===1?"is":"are"} reported`:""}.`):oe("\u2717",`${it(y,"style error")} \u2014 /lint --blocked shows them, /lint --blocked --fix corrects them.`)),c.baselinedCount>0&&a.push(oe("\u2139",`${it(c.baselinedCount,"issue")} ${c.baselinedCount===1?"was":"were"} already in your articles when this style guide was chosen, so ${c.baselinedCount===1?"it never blocks":"they never block"} publishing.`)),c.ruleErrors.length>0&&a.push(oe("\u26A0",`${it(c.ruleErrors.length,"rule")} could not be loaded: ${c.ruleErrors.slice(0,2).map(x=>`${x.ruleId} (${x.reason})`).join("; ")}`))}catch{}return a.push(""),a.push(u(" See them all: /style-guide list \xB7 change: /style-guide use \xB7 one rule: /style-guide explain <rule>")),fk(Dn(e)?.styleGuide)&&(a.push(""),a.push("A guide built for software documentation is installed, and these docs are not on it:"),a.push(` Move to it /style-guide use ${Rh}`),a.push(" Stay as you are /style-guide keep"),a.push(u(" Several rules in a general-prose guide are wrong for software documentation. This one was")),a.push(u(" measured on real knowledge bases, rule by rule, and nothing in it can block a publish."))),Ch(e)&&(a.push(""),a.push("Nobody has settled this yet, and it is a decision \u2014 nothing above changed anything:"),a.push(" Happy with these rules? /style-guide keep"),a.push(" Want a stricter standard? /style-guide use microsoft (or google)"),a.push(u(" Worth settling now rather than later: it shapes every article written from here, and")),a.push(u(" changing it once a knowledge base exists means going back over what is already written."))),a}function kk(e){let t=Dn(e),n=new Set(vh(t?.styleGuide)),o=wh(e),r=["Rule packs you can turn on:",""],s=Math.max(12,...o.map(i=>i.name.length));for(let i of o){let a=i.name.toLowerCase(),l=n.has(a),c=a===ao,h=l?"\u2713":"\xB7",y=c?u("(always on)"):l?u("(active)"):"",x=i.local?u(" [yours]"):"";r.push(` ${h} ${a.padEnd(s)}${x} ${i.description??""}`),r.push(` ${u(`${it(i.rules.length,"rule")} \xB7 ${bk(i.rules)} \xB7 ${kh(i.version)}`)} ${y}`),i.errors.length>0&&r.push(oe("\u26A0",`${it(i.errors.length,"rule")} in this pack could not be loaded \u2014 /style-guide explain names them.`))}return o.every(i=>i.name.toLowerCase()===ao)&&(r.push(""),r.push(u(" The Microsoft and Google style guides are not installed in this build yet."))),r.push(""),r.push(u(" Turn one on: /style-guide use <name> (this replaces the chosen set, it does not add to it)")),r.push(u(" Several: /style-guide use microsoft,google")),r.push(u(" Back to none: /style-guide use none")),r}function SD(e,t){if(!t)return[oe("\u26A0","Name a rule: /style-guide explain Humanise.EmDash")];let n=$h(e),o=Kl.find(c=>c.id.toLowerCase()===t.toLowerCase()),r=n.rules.find(c=>c.id.toLowerCase()===t.toLowerCase());if(!o&&!r){let c=[...Kl.map(h=>h.id),...n.rules.map(h=>h.id)].filter(h=>h.toLowerCase().includes(t.toLowerCase())).slice(0,5);return[oe("\u26A0",`No active rule called "${t}".`),...c.length>0?[u(` Did you mean: ${c.join(", ")}`)]:[u(" /style-guide list shows the active packs.")]]}let s=o?.id??r.id,i=o?.severity??r.severity,a=o?"built in (correctness \u2014 always on)":`pack: ${r.pack.toLowerCase()}`,l=[`${s} ${i} \xB7 ${a}`,""];l.push(` ${o?.summary??r.message}`),r?.link&&l.push(u(` ${r.link}`)),r?.degraded&&(l.push(""),l.push(oe("\u26A0",`This rule is translated approximately: ${r.degraded}. It may match slightly more than the original does.`)));try{let c=Yl({cwd:e}).findings.filter(y=>y.ruleId===s),h=c.filter(y=>!y.baselined);l.push(""),l.push(c.length===0?" Currently: no findings.":` Currently: ${it(h.length,"finding")}${c.length!==h.length?`, plus ${c.length-h.length} baselined and hidden`:""}.`)}catch{}return l.push(""),o?(l.push(u(" Built-in checks are grounded in your product's own source and cannot be switched off \u2014 they")),l.push(u(" catch defects of fact, not matters of taste."))):(l.push(i==="error"?u(' This one BLOCKS publishing \u2014 your config sets it to "error" deliberately.'):u(" Style rules never block publishing. Fix it when you want to; it will not hold a page back.")),l.push(u(` Silence it everywhere: add "${s}": "off" to styleGuide.rules in .d360-writer/config.json`)),i!=="error"&&l.push(u(" Silence one passage: <!-- vale "+s+" = NO --> \u2026 <!-- vale "+s+" = YES -->"))),l}function Ph(e,t){let n=(t??"").trim();if(!n){let w=wh(e).filter(R=>R.name.toLowerCase()!==ao),S=new Set(vh(Dn(e)?.styleGuide).map(R=>R.toLowerCase())),P=R=>R.toLowerCase()===Rh?0:1,T=w.sort((R,D)=>P(R.name)-P(D.name)||R.name.localeCompare(D.name)).map(R=>({cmd:`/style-guide use ${R.name.toLowerCase()}`,desc:`${vD(R)} \u2014 ${R.rules.length} rules${S.has(R.name.toLowerCase())?" (active now)":""}`}));return{lines:[],restart:!1,pick:{title:"Which writing rules should these docs follow?",lead:"Pick below. Whichever you choose, every article here is held to it \u2014 nothing stays exempt.",options:[...T,{cmd:"/style-guide use none",desc:"the built-in checks only \u2014 correctness and anti-slop"}]}}}let o=n.toLowerCase()==="none"?[]:n.split(/[,\s]+/).map(w=>w.trim().toLowerCase()).filter(Boolean),r=new Map(wh(e).map(w=>[w.name.toLowerCase(),w])),s=o.filter(w=>!r.has(w));if(s.length>0)return{lines:[oe("\u2717",`No rule pack named ${s.map(w=>`"${w}"`).join(", ")}.`),"",...kk(e)],restart:!1};let i=Dn(e)??{projectId:""},{declinedUpgrade:a,...l}=i.styleGuide??{},c=(i.styleGuide?.packs??[]).map(w=>w.trim().toLowerCase()).filter(Boolean);xh({...i,styleGuide:{...l,packs:o,decidedAt:new Date().toISOString()}},e),QN();let h=[oe("\u2192",`Switching to: ${o.length>0?o.join(", "):"the built-in checks only"}${o.includes(ao)?"":` (+ ${ao}, always on)`}\u2026`)],y,x=[];try{let w=JN(e),S=w?Object.values(w.entries).reduce((R,D)=>R+D.count,0):0;if(w){try{bh(`${eD(e)}.bak`,JSON.stringify(w,null,2),"utf8")}catch{}ZN(e)}let P=Yl({cwd:e}),T=new Set(P.findings.map(R=>R.path)).size;if(P.findings.length===0)h.push(oe("\u2713",T===0?"No articles yet \u2014 everything you write from here is held to the full set.":"Your articles are already clean against these rules."));else{h.push(oe("\u26A0","Every article is held to the new rules. Nothing stays exempt."),"",u(` ${it(P.findings.length,"finding")} across ${it(T,"article")} ${P.findings.length===1?"is":"are"} now live.`)),S>0&&(h.push(u(` ${it(S,"finding")} accepted under your previous guide ${S===1?"is":"are"} not carried over.`)),h.push(u(" Your previous record is at .d360-writer/style-baseline.json.bak"))),h.push(""),h.push(oe("\u2713","Nothing blocks publishing \u2014 no style-pack rule can."));let R=oo(e,["--fix"],P.findings);R.lines.length>0&&h.push("",...R.lines);let D=R.fixed>0?Yl({cwd:e}):P,B=D.findings.length,G=new Set(D.findings.map(Q=>Q.path)).size;B===0?h.push(oe("\u2713","That was all of them \u2014 your articles now match the new guide.")):y={findings:B,articles:G,cmd:"/review --all --fix",...R.fixed>0?{outOf:P.findings.length}:{}},x=[...new Set(D.findings.map(Q=>Q.path))]}tD(e,{packs:o,from:c,articlesWithFindings:x})}catch(w){h.push(oe("\u26A0",`The packs are active, but reading your articles failed: ${w instanceof Error?w.message:String(w)}`)),h.push(u(" Run /lint to see the current state before publishing."))}return h.push(...gk(e,`/style-guide use ${n}`)),h.push(u(" Restarting the agent so it writes to the new rules\u2026")),{lines:h,restart:!0,...y?{editorial:y}:{}}}function CD(e){return[e.title,u(` ${e.lead}`),"",...e.options.map(t=>` ${t.cmd}`.padEnd(38)+u(t.desc))]}function Th(e){let t=e.outOf?`${e.findings} of the ${e.outOf} findings`:it(e.findings,"finding");return[oe("\u2192",`${t} across ${it(e.articles,"article")} ${e.findings===1?"needs":"need"} a read, not a swap.`),u(` ${e.cmd} reads each one and rewrites it. Nothing is blocking your publishing in the meantime.`)]}function PD(e,t){let n=(t??"").trim().toLowerCase()==="skip",o=oD(e);if(!o)return[oe("\u2713","No sweep is owed \u2014 your articles have been read against the guide they follow.")];let r=o.packs.length>0?o.packs.join(", "):"the built-in checks";if(n)return nD(e),[oe("\u2713",`Fine \u2014 I won't raise the ${r} sweep again.`),"",u(` ${it(o.pending,"article")} still ${o.pending===1?"has":"have"} not been read against it.`),u(" /review --all --fix does the sweep whenever you want it.")];let s=o.total-o.pending;return[oe("\u2192",`${o.pending} of your ${it(o.total,"article")} still ${o.pending===1?"needs":"need"} a read against ${r}.`),"",...s>0?[u(` ${s} read so far.`)]:[],u(" /review --all --fix reads the rest and rewrites them."),u(" /style-guide sweep skip stops me raising it.")]}async function zl(e,t){let{sub:n,value:o}=Qr(e),r=s=>{for(let i of s)console.log(i);console.log("")};switch(n){case"list":return r(kk(t.cwd)),{kind:"continue"};case"explain":return r(SD(t.cwd,o)),{kind:"continue"};case"use":{let s=Ph(t.cwd,o);return r(s.pick?CD(s.pick):s.lines),s.editorial&&r(Th(s.editorial)),s.restart?{kind:"clear"}:{kind:"continue"}}case"keep":return r(wD(t.cwd)),{kind:"continue"};case"sweep":return r(PD(t.cwd,o)),{kind:"continue"};case"pull":{let s=await bD(t.cwd,o,t.profileName);return r(s.lines),s.restart?{kind:"clear"}:{kind:"continue"}}case"compile":{let s=kD(t.cwd);return{kind:"forward-to-agent",prompt:s.prompt,display:s.display}}case"learn":{let s=$D(t.cwd);return s.kind==="nothing"?(r(s.lines),{kind:"continue"}):{kind:"forward-to-agent",prompt:s.prompt,display:s.display}}default:return r(RD(t.cwd)),{kind:"continue"}}}ae();import{lintDocs as Ql,loadStyleGuide as Ek,buildReviewPrompt as Nk,buildStructureReviewPrompt as zD,structureReviewDue as XD,structureFingerprint as QD,recordStructureReview as JD,hasCaptureArtifacts as Dk,readProjectConfig as Lh,DEFAULT_DOCS_DIR as Oh,listArticleFiles as Jo,normalizeScope as ZD,planPartitions as e1,runPartitioned as jk,partitionCoverage as t1,resolveModelForOperation as Ik,stampArticles as n1,snapshotArticles as o1,reviewStalePaths as r1,readReviewerNotes as Lk,renderNotesForPrompt as Ok,readDocsPlan as s1,CONTENT_CAP_VERSION as Ih}from"document360-engine";import{articlesChangedSince as TD,isUnadoptedArticle as AD,docsRootOf as ED}from"document360-engine";function Xo(e,t,n,o){let r=t.map(c=>c.replace(/\\/g,"/"));if(!n)return{changed:[],earned:r,unadopted:[]};let s=[];try{s=TD(e,n).map(c=>c.replace(/\\/g,"/"))}catch{return{changed:[],earned:r,unadopted:[]}}let i=new Set(s),a=r.filter(c=>!i.has(c)&&AD(e,c,o)),l=new Set(a);return{changed:s.filter(c=>r.includes(c)),earned:r.filter(c=>!l.has(c)),unadopted:a}}function ND(e,t){let n=t.replace(/\\/g,"/");try{let o=ED(e).replace(/\\/g,"/").replace(/\/+$/,"");return o&&n.startsWith(`${o}/`)?n.slice(o.length+1):n}catch{return n}}function Jr(e,t,n){if(t.length===0)return null;let o=t.length===1,r=[];r.push(o?`\u26A0 The editor changed nothing in ${ND(e,t[0])}, so it is not recorded as reviewed.`:`\u26A0 The editor changed nothing in ${t.length} pages, so they are not recorded as reviewed.`),r.push(o?" Nothing here has adopted this page: it came from Document360, it is not in your docs plan, and":" Nothing here has adopted them: they came from Document360, they are not in your docs plan, and"),r.push(o?" nothing records what it was written from. There was nothing for an editor to check it against.":" nothing records what they were written from. There was nothing for an editor to check them against.");for(let i of t)r.push(`/untrack ${i}`);r.push(o?" That disowns it \u2014 the page, its history and its comments stay on Document360, readers see no":" That disowns one \u2014 the page, its history and its comments stay on Document360, readers see no"),r.push(" change, and the markdown is kept. Nothing is deleted.");let s=n.lead&&o?{text:r.join(`
|
|
438
|
+
`),cmd:`/untrack ${t[0]}`}:null;return{lines:r,cta:s}}function $i(e){return e===0?"The editor found nothing to change":"Editor applied its fixes"}import{listArticleFiles as $k,lintDocs as DD,planFindingPartitions as jD,planPartitions as ID,readDocsPlan as LD,readProjectConfig as OD,runRate as Eh,loadCoverage as MD,coverageGap as _D,resolveActiveProfile as UD,DEFAULT_DOCS_DIR as FD}from"document360-engine";function Nh(e){switch(e.cmd){case"/review":return{concurrency:lo,maxPerPartition:jh,minutesPerBatch:5};case"/write":return{concurrency:3,minutesPerBatch:4};case"/lint":return{concurrency:3,minutesPerBatch:2};default:return{concurrency:3,minutesPerBatch:2}}}function WD(e,t){let n=DD({cwd:e,scope:t.scope}).filter(s=>!s.baselined),o=t.flags.has("--blocked")?n.filter(s=>s.severity==="error"):n;if(o.length===0)return null;let r=new Set(o.map(s=>s.path)).size;return{lead:`${o.length} issue${o.length===1?"":"s"} \xB7 ${r} article${r===1?"":"s"}`,articles:r,batches:jD(o).length}}var BD=new Set(["/push","/publish"]);function vk(e,t){if(t.cmd==="/lint"){let r=jn(()=>WD(e,t));return r?{lead:r.lead,billable:r.articles,batches:r.batches}:null}if(t.cmd==="/catch-up"){let r=jn(()=>on(e));if(!r)return null;let s=r.hints+r.requests+r.answers+r.directives;if(s===0)return null;let i=jn(()=>zr(r));return i?{lead:i,billable:0,batches:null}:{lead:`${s} queued item${s===1?"":"s"}`,billable:0,batches:null}}if(t.cmd==="/reuse"){if(t.sub!=="audit")return null;let r=jn(()=>$k(e,t.scope))?.length??0;return r<4?null:{lead:`${r} article${r===1?"":"s"} read \xB7 one editorial turn`,billable:0,batches:null}}if(t.cmd==="/pull"){let r=jn(()=>_D(MD(e,UD(e).name)))??0;return r<4?null:{lead:`${r} article${r===1?"":"s"} to import`,billable:0,batches:null}}if(BD.has(t.cmd)){let r=jn(()=>$k(e,t.scope))?.length??0;return r<4?null:{lead:`${r} article${r===1?"":"s"}`,billable:0,batches:null}}let n=HD(e,t);if(!n||n.length<4)return null;let o=Nh(t);return{lead:`${n.length} article${n.length===1?"":"s"}`,billable:n.length,batches:ID(n,o.maxPerPartition?{maxPerPartition:o.maxPerPartition}:void 0).length}}function HD(e,t){try{if(t.cmd==="/write"){let n=(OD(e)?.docsDir??FD).replace(/\/+$/,""),o=LD(e,n).map(s=>s.path);if(o.length===0)return null;let r=t.scope?o.filter(s=>s===t.scope||s.startsWith(`${t.scope}/`)):o;return t.flags.has("--rewrite")?r:Jn(e,n,r)}return t.cmd==="/review"?Qo(e,[...t.flags],t.scope):null}catch{return null}}function xk(e,t){let n=rn(e,t);if(!n)return null;let o=n.indexOf(" batch");if(o<0)return null;let r=n.lastIndexOf("\xB7 ",o);return r<0?n:n.slice(r+2)}function rn(e,t){let n=un(t);if(!n||!Lr(n))return null;let o=vk(e,n);if(!o)return null;let r=jn(()=>Eh(e,n.cmd));if(o.batches===null){let c=r?.minutesPerWave!==void 0?` \xB7 ~${Ah(r.minutesPerWave)}`:"";return`${o.lead}${c}`}let s=Nh(n),a=Math.ceil(o.batches/s.concurrency)*(r?.minutesPerWave??s.minutesPerBatch),l=r?.usdPerArticle!==void 0&&o.billable>0?` \xB7 ~${Ck(o.billable*r.usdPerArticle)}`:"";return`${o.lead} \xB7 ${o.batches} batch${o.batches===1?"":"es"} \xB7 ~${Ah(a)}${l}`}function Rk(e,t){let n=un(t);if(!n||!Lr(n))return null;let o=jn(()=>Eh(e,n.cmd));if(o?.usdPerArticle===void 0)return null;let r=vk(e,n);return!r||r.billable===0?null:r.billable*o.usdPerArticle*Dh}var Sk=.7,Dh=1.4;function Ah(e){let t=Math.max(1,Math.round(e*Sk)),n=Math.max(t,Math.round(e*Dh));if(n<90)return`${t}\u2013${n} min`;let o=r=>r<60?`0h ${r}m`:`${Math.floor(r/60)}h ${r%60}m`;return`${o(t)}\u2013${o(n)}`}function Ck(e){let t=e*Sk,n=e*Dh;return n>=10?`$${Math.round(t)}\u2013${Math.round(n)}`:`$${t.toFixed(2)}\u2013${n.toFixed(2)}`}function jn(e){try{return e()}catch{return null}}function Xl(e,t,n,o){if(n<4||o<1)return null;let r=Nh({cmd:t,scope:void 0,flags:new Set,args:[]}),s=Math.ceil(o/r.concurrency),i=jn(()=>Eh(e,t)),a=s*(i?.minutesPerWave??r.minutesPerBatch),l=i?.usdPerArticle!==void 0?` \xB7 ~${Ck(n*i.usdPerArticle)}`:"";return`~${Ah(a)}${l}`}import{loadProfileMap as i1,resolveActiveProfile as a1}from"document360-engine";import{renderGapsForPrompt as Mk,readReaderContract as Mh,renderCorpusTermsForPrompt as _k,scanTerminology as Uk,renderReuseForPrompt as Fk,scanReuse as Wk}from"document360-engine";import{recordRunSample as l1}from"document360-engine";ae();import{readProjectConfig as GD,loadProfileMap as qD,resolveActiveProfile as VD,desiredCategoryOrder as YD,desiredArticleOrder as KD}from"document360-engine";function Pk(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}var Tk=e=>e.replace(/\\/g,"/").split("/").pop()??e;function Zr(e,t){try{if(!GD(e))return[];let n=VD(e,t),o=qD(e,n.name);if(!o)return[];let r=new Map;for(let y of KD(o)){let x=r.get(y.categoryPath);x?x.push(y):r.set(y.categoryPath,[y])}let s=YD(o),i=Math.min(...s.map(y=>y.path.split("/").length),Number.MAX_SAFE_INTEGER),a=new Map;for(let y of s){let x=y.path.split("/").slice(0,-1).join("/"),w=a.get(x);w?w.push(y):a.set(x,[y])}let l=[],c=(y,x)=>{for(let w of(a.get(y)??[]).sort((S,P)=>S.order-P.order)){let S=" ".repeat(x);l.push(`${S}${Pk(Tk(w.path))}`);for(let P of(r.get(w.path)??[]).sort((T,R)=>T.order-R.order))l.push(`${S} ${Pk(Tk(P.path))}`);c(w.path,x+1)}},h=s.find(y=>y.path.split("/").length===i);return c(h?h.path.split("/").slice(0,-1).join("/"):"",0),l}catch{return[]}}async function Ak(e,t){let n=Zr(t.cwd,t.profileName);if(n.length===0)return console.log(u("No documentation structure yet \u2014 run /init and author some articles first.")),{kind:"continue"};console.log(Z("Documentation order (categories \u2192 articles):"));for(let o of n)console.log(o);return console.log(""),{kind:"continue"}}function _h(e,t){return Gs(e,Jo(e,t))}function Uh(e,t){return r1(e,Jo(e,t),Ih)}function es(e){return e.includes("--blocked")||e.includes("--stale")}function Qo(e,t,n){return t.includes("--blocked")?_h(e,n):t.includes("--stale")?Uh(e,n):Jo(e,n)}function Fh(e,t,n){let o;try{o=s1(e)}catch{return[]}let r=new Map(o.map(i=>[i.path.replace(/\\/g,"/"),i])),s=[];for(let i of n){let a=i.replace(/\\/g,"/").replace(`${t}/`,""),l=r.get(a);l&&s.push({path:i,type:l.type,...l.purpose?{purpose:l.purpose}:{}})}return s}function Bk(e,t){let n=Lh(e);if(!n)return null;let o=(n.docsDir??Oh).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),s=es(t),i=t.find(T=>!T.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),a=Ql({cwd:e}),l=i?ZD(o,i):"",c=l?a.filter(T=>T.path===`${o}/${l}`||T.path.startsWith(`${o}/${l}/`)):a,h=s?Qo(e,t,i):void 0,y=h?c.filter(T=>h.includes(T.path)):c,x=i||s?"":Zr(e).join(`
|
|
439
|
+
`),w=Dk(e,n),S=Nk({docsRoot:o,scope:i,styleGuide:Ek(e),deterministicFindings:y,fix:r,structure:x||void 0,screenshots:w,...h?{paths:h}:{},reviewerNotes:Ok(Lk(e),h??Jo(e,i)),openGaps:Mk(e,h??Jo(e,i)),readerContract:Mh(e),corpusTerms:_k(Uk(e)),corpusReuse:Fk(Wk(e)),planRows:Fh(e,o,h??Jo(e,i))}),P=t.includes("--blocked")?" --blocked":t.includes("--stale")?" --stale":"";return{prompt:S,display:`/review${i?` ${i}`:""}${P}${r?" --fix":""}`}}var c1=e=>"ruleId"in e,lo=3,jh=3;function Wh(e,t){let n=Bk(e,t);if(!n)return null;let o=t.find(T=>!T.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),r=Qo(e,t,o),s=e1(r,{maxPerPartition:jh});if(s.length<=1)return{kind:"single",...n};let i=Lh(e),a=(i?.docsDir??Oh).replace(/\\/g,"/").replace(/\/+$/,""),l=t.includes("--fix"),c=Ek(e),h=Ql({cwd:e}),y=Lk(e),x=Dk(e,i),w=Mh(e),S=_k(Uk(e)),P=Fk(Wk(e));return{kind:"partitioned",partitions:s,articles:r.length,wholeKb:!o&&!es(t),display:n.display,promptFor:T=>{let R=new Set(T.paths);return Nk({docsRoot:a,styleGuide:c,deterministicFindings:h.filter(D=>R.has(D.path)),fix:l,screenshots:x,paths:T.paths,reviewerNotes:Ok(y,T.paths),openGaps:Mk(e,T.paths),readerContract:w,corpusTerms:S,corpusReuse:P,planRows:Fh(e,a,T.paths)})}}}function vi(e,t,n){let o=Lh(e);if(!o||t.find(l=>!l.startsWith("--"))||n?.kind==="single"&&!es(t))return null;let s=(o.docsDir??Oh).replace(/\\/g,"/").replace(/\/+$/,""),i=Zr(e);if(Object.keys(i1(e,a1(e).name)?.categories??{}).length<2)return null;let a=i.join(`
|
|
440
|
+
`);return XD(e,a,Ih)?{prompt:zD({docsRoot:s,structure:a,planRows:Fh(e,s,Jo(e)).map(l=>`${l.path} ${l.type}`).join(`
|
|
441
|
+
`),readerContract:Mh(e)}),display:"/review \u2014 the shape of your knowledge base",fingerprint:QD(a,Ih)}:null}function Bh(e,t){if(!es(t))return null;let n=t.find(y=>!y.startsWith("--"));if(Qo(e,t,n).length>0)return null;let o=t.includes("--blocked"),r=!!n&&n.endsWith(".md"),s=n?r?" here":` in ${n}`:"",a=o?`\u2713 Nothing is blocked${s} \u2014 ${n&&r?"it has":"every article has"} been through an editorial read.`:`\u2713 ${r?"This article has":`Every article${s} has`} already been read by the current editor \u2014 nothing to re-read.`,l=`/push${n?` ${n}`:" --all"}`,c=Ut(e,{text:`${l} saves ${r?"it":"what has changed"} to Document360 as ${r?"a draft":"drafts"}.`,cmd:l},"",n,"/review"),h=Ke(e,Bk(e,t)?.display??"");return{lines:[a,` ${c.text}`],closed:h,cta:c}}async function Hk(e,t){let n=Bh(t.cwd,e);if(n){console.log(X(n.lines[0]));for(let s of n.lines.slice(1))console.log(u(s));for(let s of n.closed)console.log(X(s));let r=vi(t.cwd,e,null);return r&&(console.log(u("One thing left: no editor has looked at how your docs are organized since it last changed.")),await Gk(t,r)),{kind:"continue",ownNext:!0}}if(ro("review",e)){let r=Gr(t.cwd,"review",e,t.profileName);if(r.length>0){for(let s of r)console.log(u(s));return{kind:"continue"}}}let o=Wh(t.cwd,e);return o?o.kind==="single"?{kind:"forward-to-agent",prompt:o.prompt,display:o.display}:await u1(t,o,e.includes("--fix"),e.find(r=>!r.startsWith("--")),e):(console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"})}async function Gk(e,t){console.log(""),console.log(u(`Reviewing ${t.display.replace(/^\/review — /,"")}\u2026`));let n=!1;try{for await(let o of jk({cwd:e.cwd,partitions:[{label:"the shape of your knowledge base",paths:[]}],promptFor:()=>t.prompt,concurrency:1,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:Ik(e.cwd,"standard").model,scope:"review"}))o.type==="run_done"&&(n=o.results.some(r=>r.ok))}catch{return}n&&JD(e.cwd,t.fingerprint)}async function u1(e,t,n,o,r=[]){let{model:s}=Ik(e.cwd,"standard"),i=vi(e.cwd,r,t),a=Xl(e.cwd,"/review",t.articles,t.partitions.length);console.log(u(`Reviewing ${t.articles} article${t.articles===1?"":"s"} in ${t.partitions.length} batches (\u2264${lo} editors at once) on ${s}${n?", applying fixes":", report only"}${a?` \xB7 ${a}`:""}\u2026`));let l=Date.now(),c=n?o1(e.cwd):null,h=[],y=0,x=new Fr;x.start();let w={aborted:!1,partitions:0,failed:0,notRun:0,producedNothing:!0};try{for await(let R of jk({cwd:e.cwd,partitions:t.partitions,promptFor:t.promptFor,concurrency:lo,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:s,scope:"review"}))if(R.type==="partition_status")R.status==="running"?console.log(u(` \u25B8 ${R.label} \u2014 reviewing\u2026`)):R.status==="done"?console.log(X(` \u2713 ${R.label}`)):console.log(L(` \u2717 ${R.label}`));else if(R.type==="run_done"){let D=t1(t.partitions,R.results);w={aborted:!!R.aborted,partitions:t.partitions.length,failed:D.failed.length,notRun:D.notRun.length,...R.blocked?{blocked:R.blocked}:{},...R.allEmpty?{allEmpty:!0}:{},...R.bailedEmpty?{bailedEmpty:!0}:{}},console.log(""),console.log(`${R.results.length-D.failed.length}/${t.partitions.length} batches reviewed.`),D.failed.length&&console.log(H(`\u26A0 ${D.failed.length} not reviewed: ${D.failed.map(G=>G.label).join(", ")}`)),D.notRun.length&&console.log(H(`\u26A0 ${D.notRun.length} batch${D.notRun.length===1?"":"es"} never started \u2014 their articles are untouched.`)),R.blocked&&console.log(H(`\u26A0 ${R.blocked}`)),R.allEmpty&&console.log(H("\u26A0 No editor produced any work this run \u2014 nothing was reviewed or changed."));for(let G of Hh(t,!!i))console.log(u(G));if(n&&!R.allEmpty&&!R.blocked){let G=Xo(e.cwd,D.covered,c,e.profileName);if(h.push(...G.unadopted),y=G.changed.length,G.earned.length>0)try{n1(e.cwd,G.earned,wt("review"))}catch{}}let B=x.stop();if(console.log(u(dn(Wt(l,R.results,R.totalCostUsd,Date.now(),B.activeSeconds)))),!R.allEmpty&&!R.blocked){let G=R.results.filter(Q=>Q.ok).length;l1(e.cwd,"review",{articles:D.covered.length,waves:Math.ceil(G/Math.max(1,lo)),seconds:B.activeSeconds,costUsd:R.totalCostUsd})}}}catch(R){return x.stop(),console.log(L(`Review failed: ${R.message}`)),{kind:"continue"}}if(x.stop(),i&&!w.aborted&&await Gk(e,i),n&&tn(w))for(let R of Ke(e.cwd,t.display))console.log(X(R));if(!n)return{kind:"continue"};let S=oo(e.cwd,["--fix"],Ql({cwd:e.cwd,scope:o}));for(let R of S.lines)console.log(R);let T=Ql({cwd:e.cwd,scope:o}).filter(R=>!R.baselined).filter(R=>c1(R)&&R.severity==="error");if(console.log(""),T.length>0){let R=Ce("/lint","--blocked --fix",o);console.log(u(`${$i(y)}, but ${T.length} style error${T.length===1?"":"s"} remain \u2014 ${R} clears them (finding them costs nothing, one pass corrects them). It is the last paid pass before publishing: anything still standing after a second attempt is reported for a person rather than run again.`))}else{let R=Jr(e.cwd,h,{lead:y===0});if(R)for(let D of R.lines)console.log(H(D));if(R?.cta)return{kind:"continue",ownNext:!0};console.log(u(Ut(e.cwd,{text:`\u2713 ${y===0?"Reviewed \u2014 nothing needed changing":"Reviewed and fixed"}. /push --all saves the articles to Document360 as drafts.`,cmd:"/push --all"},"",o).text))}return{kind:"continue",ownNext:!0}}function Hh(e,t=!1){return e.partitions.length<2?[]:t?["Each editor saw one slice of the docs, so no one of them judged the set as a whole.","They did all see how the whole set spells its terms; two different WORDS for one thing still need a person."]:[`Each editor saw one slice of the docs, so reading order ${e.wholeKb?"ACROSS categories":"ACROSS the rest of the knowledge base"} was not judged.`,"They did all see how the whole set spells its terms; two different WORDS for one thing still need a person.","/structure shows the reading order if you want to check it yourself."]}ae();import{readProjectConfig as d1}from"document360-engine";function Gh(e,t){if(!d1(e))return null;let n=t.find(r=>!r.startsWith("--"));return{prompt:[`Reorder the articles within ${n?`the "${n}" category`:"each category"} to the best reading order.`,"Follow the manage-structure skill: decide the ideal order with senior-editor judgment per the doc-genre","playbook (overview / mental-model first; reference and troubleshooting/FAQ last), then APPLY it with the","d360_reorder_articles tool: one category at a time, all paths in the same category folder.",n?"":"If the CATEGORY order itself reads wrong too, fix that first with the d360_reorder_categories tool (folder paths under one parent, in the desired order).","Do not rename files or folders or edit the map by hand; the tools handle it. Report the new order, and","remind me it reaches Document360 on the next /push."].filter(Boolean).join(`
|
|
442
|
+
`),display:`/reorder${n?` ${n}`:""}`}}async function qk(e,t){if(ro("reorder",e)){let o=Gr(t.cwd,"reorder",e,t.profileName);if(o.length>0){for(let r of o)console.log(u(r));return{kind:"continue"}}}let n=Gh(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"})}ae();import{readProjectConfig as p1}from"document360-engine";function qh(e,t){if(!p1(e))return null;let n=t.filter(r=>!r.startsWith("--")).join(" ").trim();return{prompt:[n?`Restructure the docs: ${n}`:"Review how the docs are organised and tell me what should change.","","Follow the manage-structure skill.",n?"Apply the change with the right tool: d360_move_articles to refile, split or merge; d360_rename_category to rename; d360_nest_category to put a category inside another or lift one back out; d360_reorder_articles or d360_reorder_categories if only the order is wrong.":["Read the current structure first, then judge it as a senior technical writer would: is every article","filed where a reader would look for it, has any category grown past one topic and want splitting, are","two categories really the same one, does any name still describe what is in it, and does any nesting","earn the click it costs the reader?","","Report what you would change and why, as a short numbered list, and STOP THERE. Do not apply anything","yet: reshaping a knowledge base is my call, not yours. If nothing needs changing, say so plainly."].join(`
|
|
443
443
|
`),"","Do not rename files or folders or edit the map by hand; the tools handle the whole refactor.","Moving an article does not change its public URL, so say so rather than warning me about broken links.","A category a merge leaves empty is handled for me: it goes locally and is hidden from readers on the","next push, never deleted. Say that in those words rather than telling me to tidy it up myself.","When you have applied something, remind me it reaches Document360 on the next /push."].filter(Boolean).join(`
|
|
444
|
-
`),display:`/restructure${n?` ${n}`:""}`}}async function
|
|
445
|
-
`)}function qh(e,t={}){let n=r1(e,t.profileName),o=[];if(n.rows.length===0){o.push(Z("Publish readiness")),o.push("");let h=i1(n.coverage),y=n.neverPushed.length;return o.push(n.tracked===0?y>0?`${V("\u25CB",Ue.gray)}Nothing here is on Document360 yet.`:`${V("\u25CB",Ue.gray)}No articles are tracked yet. /write authors them, /push saves them to Document360.`:h>0||y>0?`${V("\u2713",Ue.green)}All ${n.tracked} tracked articles are live and unchanged.`:`${V("\u2713",Ue.green)}All ${n.tracked} articles are live and unchanged \u2014 nothing is waiting on you.`),o.push(...u1(n)),n.neverPushed.length>0&&(o.push(""),o.push(...Hk(n))),n.orphans.length>0&&o.push(...qk(n)),n.unadopted.length>0&&(o.push(""),o.push(...Gk(n))),o.push(""),o.push(u(" Free \u2014 /status reads your local files and the last sync. It calls nothing.")),o}let r=n.rows.length,s=n.blocked.length;o.push(Z("Publish readiness")+u(` ${r} article${r===1?"":"s"} not yet settled with readers \xB7 ${s===0?"nothing blocked":`${s} blocked`}`)),o.push(""),t.all&&(o.push(...c1(n,t.width??100)),o.push(""));for(let h of a1(n)){o.push(` ${V(h.glyph,h.paint)}${h.title}${h.fix?u(` ${h.fix}`):""}`);for(let y of h.items.slice(0,jn))o.push(u(` ${y}`));h.items.length>jn&&o.push(u(` \u2026and ${h.items.length-jn} more`)),o.push("")}let i=Hk(n);i.length>0&&(o.push(...i),o.push(""));let a=Gk(n);a.length>0&&(o.push(...a),o.push(""));let l=l1(n);if(l.length>0){for(let h of l)o.push(` ${h}`);o.push("")}let c=n.rows.filter(h=>h.localAhead).length;return c>0&&o.push(u(` ${c} changed here \u2014 /push saves ${c===1?"it":"them"} to Document360 as ${c===1?"a draft":"drafts"}. Readers see nothing until then.`)),n.draftPending.length>0&&(o.push(u(` ${n.draftPending.length} saved on Document360 as ${n.draftPending.length===1?"a draft":"drafts"} and not live \u2014 /publish takes ${n.draftPending.length===1?"it":"them"} to your readers.`)),o.push(u(" That is from your last sync. /pull re-checks what is live."))),n.orphans.length>0&&o.push(...qk(n)),!t.all&&n.rows.length>0&&o.push(u(" /status --all shows every article, gate by gate.")),o.push(""),o.push(u(" Free \u2014 /status reads your local files and the last sync. It calls nothing.")),o}function Hk(e){let t=e.neverPushed.length;if(t===0)return[];let n=[` ${V("\u25CB",Ue.gray)}${t===1?"One article is":`${t} articles are`} written here and ${t===1?"has":"have"} never been saved to Document360`,u(` Your readers cannot see ${t===1?"it":"them"} at all yet \u2014 not even as a draft.`)];for(let o of e.neverPushed.slice(0,jn))n.push(` ${Me(o)}`);return t>jn&&n.push(u(` \u2026and ${t-jn} more`)),n.push(u(" /push --all saves them as drafts; /publish then takes them live.")),n}function Gk(e){let t=e.unadopted.length;if(t===0)return[];let n=[` ${V("\u25CB",Ue.gray)}${t===1?"One page here came from Document360 and nothing has adopted it":`${t} pages here came from Document360 and nothing has adopted them`}`,u(` Not in your docs plan, not written by d360-writer, and nothing records what ${t===1?"it says":"they say"}.`),u(` So no editor can check ${t===1?"it":"them"}: a review pass over ${t===1?"it":"them"} comes back having changed nothing.`)];for(let o of e.unadopted.slice(0,jn))n.push(` /untrack ${o.path}`);return t>jn&&n.push(u(` \u2026and ${t-jn} more`)),n.push(u(" Disowning one leaves Document360 untouched \u2014 the page, its history and its comments all stay.")),n}function qk(e){let t=e.orphans.length;return[u(` ${t} article${t===1?"":"s"} on Document360 ${t===1?"is":"are"} not in your docs folder (${Me(e.orphans[0].path,40)}${t>1?`, +${t-1} more`:""}) \u2014 /doctor lists ${t===1?"it":"them"}.`)]}function Vk(e){let t=Date.now()-Date.parse(e);if(!Number.isFinite(t)||t<0)return"just now";let n=Math.floor(t/6e4);if(n<2)return"just now";if(n<60)return`${n} minutes ago`;let o=Math.floor(n/60);if(o<24)return`${o} hour${o===1?"":"s"} ago`;let r=Math.floor(o/24);return`${r} day${r===1?"":"s"} ago`}function u1(e){let t=e.coverage;if(!t)return e.tracked===0?[]:["",u(" Nothing has compared this repo with Document360 yet."),"",u(" /pull --status counts what is there.")];if(t.unmapped===0)return[u(` Every Document360 article is tracked here (${t.mappedArticles} of ${t.portalArticles}, checked ${Vk(t.at)}).`)];let n=t.portalOnlyCategories.filter(r=>r.articles>0).length,o=["",H(` ${V("\u26A0",Ue.yellow)}Document360 holds ${t.portalArticles} articles in ${t.portalCategories} categories.`),"",u(` This repo tracks ${t.mappedArticles} of them.`)];return n>0&&(o.push(""),o.push(u(` ${t.unmapped} articles sit in ${n} ${n===1?"category":"categories"} with no folder here.`))),t.declined>0&&(o.push(""),o.push(u(` ${t.declined} more ${t.declined===1?"is one you":"are ones you"} declined with /untrack.`))),o.push(""),o.push(u(` /pull imports them. Checked ${Vk(t.at)}.`)),o}async function Yk(e,t){let n=e.some(o=>o==="--all"||o==="--full");for(let o of qh(t.cwd,{profileName:t.profileName,all:n}))console.log(o);return{kind:"continue",ownNext:!0}}ie();import{computeReadiness as d1,retireArticle as p1,retiredPaths as h1,normalizeScope as f1}from"document360-engine";import{select as m1}from"@inquirer/prompts";function Vh(e,t){let n=d1(e,t),o=h1(e,t),r=[Z("Take an article off your readers"),""];if(n.orphans.length>0){r.push(` ${V("\u25CB",u)}On Document360, but not in your docs folder \u2014 the usual reason to retire:`);for(let s of n.orphans.slice(0,8))r.push(u(` ${Me(s.path)}`));n.orphans.length>8&&r.push(u(` \u2026and ${n.orphans.length-8} more`)),r.push("")}if(o.length>0){r.push(` ${V("\u2713",u)}Already retired \u2014 readers do not see ${o.length===1?"it":"these"}:`);for(let s of o.slice(0,5))r.push(u(` ${Me(s)}`));o.length>5&&r.push(u(` \u2026and ${o.length-5} more`)),r.push("")}return n.orphans.length===0&&o.length===0&&(r.push(u(" Nothing obvious to retire \u2014 every tracked article is still in your docs folder.")),r.push("")),r.push(u(" /retire <path> takes one off your readers. Any tracked article can be named, not just these.")),r.push(u(" Nothing is deleted: the article, its history and every reviewer comment stay on Document360.")),r.push(u(" /push puts one back \u2014 reviving is a publish like any other, with the same review.")),r}async function Kk(e,t){let n=t.cwd,o=e.find(a=>!a.startsWith("-"));if(!o){for(let a of Vh(n,t.profileName))console.log(a);return{kind:"continue",ownNext:!0}}let r=f1(n,o)||o;if(!(e.includes("--yes")||e.includes("-y"))&&(console.log(""),console.log(H(`This takes "${Me(r)}" off your readers on Document360.`)),console.log(u(" The article, its history and every reviewer comment stay \u2014 nothing is deleted.")),console.log(u(" /push puts it back later if you change your mind.")),console.log(""),await m1({message:"Take it off your readers?",choices:[{name:"No \u2014 leave it as it is",value:"no"},{name:"Yes \u2014 readers stop seeing it",value:"yes"}]})!=="yes"))return console.log(u("Nothing changed.")),{kind:"continue",ownNext:!0};let i=await p1({cwd:n,path:r,profileName:t.profileName,now:new Date().toISOString()});return i.ok?(console.log(i.alreadyHidden?`${V("\u2713")}"${Me(r)}" was already invisible to readers. Recorded as retired, so nothing will offer to publish it again.`:`${V("\u2713")}"${Me(r)}" is no longer visible to your readers.`),console.log(u(" It is still on Document360 with its history and comments intact. /push puts it back.")),{kind:"continue",ownNext:!0}):(console.log(L(`${V("\u2717")}Could not retire "${Me(r)}" \u2014 ${i.error.message}`)),{kind:"continue",ownNext:!0})}ie();import{declineImport as g1,loadDeclinedImports as y1,undoDecline as w1,normalizeScope as b1,resolveActiveProfile as k1}from"document360-engine";import{select as $1}from"@inquirer/prompts";function Yh(e,t){let n={};try{n=y1(e,k1(e,t).name)}catch{}let o=Object.keys(n),r=[Z("Pages on Document360 that are not part of these docs"),""];if(o.length===0)r.push(u(" Nothing is declined. Every article on Document360 in one of your categories is")),r.push(u(" imported into your docs folder when you run /catch-up or /pull."));else{for(let s of o.slice(0,10)){let i=n[s];r.push(` ${V("\u25CB",u)}${i.title??i.path??s}`),i.path&&r.push(u(` was ${Me(i.path)}`)),i.keptAt&&r.push(u(` kept at ${i.keptAt}`))}o.length>10&&r.push(u(` \u2026and ${o.length-10} more`))}return r.push(""),r.push(u(" /untrack <path> disowns an imported page \u2014 nothing on Document360 changes.")),r.push(u(" /untrack --undo <path> puts it back and lets the next /catch-up import it again.")),r}async function zk(e,t){let n=t.cwd,o=e.find(c=>!c.startsWith("-")),r=e.includes("--list")||e.includes("-l"),s=e.includes("--undo");if(r||!o&&!s){for(let c of Yh(n,t.profileName))console.log(c);return{kind:"continue",ownNext:!0}}if(!o)return console.log(L(`${V("\u2717")}Name what to put back: /untrack --undo <path>`)),{kind:"continue",ownNext:!0};let i=b1(n,o)||o;if(s){let c=w1(n,t.profileName,i);return c.ok?(console.log(c.restoredTo?`${V("\u2713")}Put "${Me(c.restoredTo)}" back in your docs folder.`:`${V("\u2713")}No longer declined. /catch-up imports it again on the next run.`),{kind:"continue",ownNext:!0}):(console.log(L(`${V("\u2717")}${c.error.message}`)),{kind:"continue",ownNext:!0})}if(!(e.includes("--yes")||e.includes("-y"))&&(console.log(""),console.log(H(`This stops tracking "${Me(i)}" as one of your docs.`)),console.log(u(" Nothing on Document360 changes \u2014 the page, its history and its comments all stay,")),console.log(u(" and your readers see no difference.")),console.log(u(" The markdown moves to .d360-writer/declined/, so nothing is deleted.")),console.log(u(" /untrack --undo puts it back if you change your mind.")),console.log(""),await $1({message:"Stop tracking it?",choices:[{name:"No \u2014 leave it as it is",value:"no"},{name:"Yes \u2014 it is not one of my docs",value:"yes"}]})!=="yes"))return console.log(u("Nothing changed.")),{kind:"continue",ownNext:!0};let l=g1({cwd:n,path:i,profileName:t.profileName,now:new Date().toISOString()});return l.ok?(console.log(`${V("\u2713")}"${l.title??Me(l.path)}" is no longer one of your docs.`),l.keptAt&&console.log(u(` The markdown is kept at ${l.keptAt} \u2014 nothing was deleted.`)),console.log(u(" It is untouched on Document360. /catch-up will not import it again.")),{kind:"continue",ownNext:!0}):(console.log(L(`${V("\u2717")}Could not untrack "${Me(i)}" \u2014 ${l.error.message}`)),{kind:"continue",ownNext:!0})}ie();import{scanTerminology as Xk,approvalBlockedReason as Qk,readProjectConfig as v1,writeProjectConfig as x1,termKey as Kh,HEAD_NOUN_CAP as R1}from"document360-engine";import nn from"picocolors";var S1=3,C1=e=>e.uses.map(t=>`${nn.bold(t.form)} ${u(`${t.files.length} article${t.files.length===1?"":"s"}`)}`).join(u(" \xB7 "));function zh(e,t={}){let n=Xk(e,t.scope?{scope:t.scope}:{}),o=[];if(n.scanned===0)return[Z("Terminology"),"",`${V("\u25CB",u)}No articles to read yet.`,""];let r=n.variance.length+n.headings.length;if(o.push(Z("Terminology")+u(` ${n.scanned} article${n.scanned===1?"":"s"} read \xB7 ${r===0?"nothing inconsistent":`${r} to look at`}`)),o.push(""),n.variance.length>0){o.push(` ${V("\u2717",nn.red)}The same term, spelled more than one way`);for(let s of n.variance){o.push(` ${C1(s)}`);let i=s.uses[s.uses.length-1],a=i.files.slice(0,S1);o.push(u(` "${i.form}" is in ${a.map(c=>Me(c,40)).join(", ")}${i.files.length>a.length?`, +${i.files.length-a.length} more`:""}`));let l=Qk(s);l?o.push(u(` ${l}`)):o.push(u(` /terms --approve "${s.uses[0].form}" makes that the approved spelling`))}o.push("")}if(n.headNouns.length>0){let s=t.all?n.headNouns:n.headNouns.slice(0,R1);o.push(` ${V("\u25CB",u)}Possibly the same thing under a short name \u2014 ${nn.italic("your call")}`);for(let i of s)o.push(u(` ${i.uses.map(a=>a.form).join(" \xB7 ")}`));n.headNouns.length>s.length&&o.push(u(` \u2026and ${n.headNouns.length-s.length} more \u2014 /terms --all lists them`)),o.push(u(' A shared word is not proof of a shared meaning: "billing history" and "history" are')),o.push(u(" different things. Nothing is flagged as wrong here.")),o.push("")}if(n.headings.length>0){o.push(` ${V("\u26A0",nn.yellow)}Titles out of step with the rest of their kind`);for(let s of n.headings)o.push(` ${nn.bold(s.title)} ${u(`\u2014 ${Me(s.path,40)}`)}`),o.push(u(` the other ${s.peers} ${s.type} article${s.peers===1?"":"s"} look like "${s.example}"; this one starts ${P1(s.shape)}`));o.push("")}return r===0&&n.headNouns.length===0&&(o.push(` ${V("\u2713",nn.green)}Every term is spelled one way, and every title matches its kind.`),o.push("")),o.push(u(' This compares spellings, not meanings: two different words for one thing (say "nav" and')),o.push(u(' "rail") look unrelated to it. Add the pair to your approved terms and every run enforces it.')),o.push(u(" Free \u2014 this read your articles and called nothing.")),o}function P1(e){return e==="gerund"?"with an -ing word":e==="how-to"?'with "How to"':"differently"}function Xh(e,t,n){let o=n??Xk(e),r=Kh(t),s=o.variance.find(y=>y.uses.some(x=>Kh(x.form)===r));if(!s)return{wrote:!1,lines:[`${V("\u2717",nn.red)}"${t}" is not one of the terms with competing spellings. /terms lists them.`]};let i=Qk(s);if(i)return{wrote:!1,lines:[`${V("\u2717",nn.red)}That one cannot be recorded: ${i}.`,u(` The spellings in play are ${s.uses.map(y=>`"${y.form}"`).join(" and ")}.`)]};let a=s.uses.find(y=>Kh(y.form)===r).form,l=s.uses.filter(y=>y.form!==a).map(y=>y.form),c=v1(e);if(!c)return{wrote:!1,lines:[`${V("\u2717",nn.red)}No project configuration here \u2014 run /init first.`]};let h={...c.terminologyGlossary??{}};for(let y of l)h[y]=a;return x1({...c,terminologyGlossary:h},e),{wrote:!0,lines:[`${V("\u2713",nn.green)}"${a}" is now the approved spelling.`,u(` Added to your approved terms: ${l.map(y=>`"${y}" \u2192 "${a}"`).join(", ")}`),u(" Every run enforces it from now on, and /lint --fix corrects the others for free.")]}}async function Jk(e,t){let n=e.findIndex(s=>s==="--approve");if(n!==-1){let s=e[n+1];if(!s)return console.log(`${V("\u2717",nn.red)}Name the spelling to approve, e.g. /terms --approve "drop-down".`),{kind:"continue",ownNext:!0};for(let i of Xh(t.cwd,s.replace(/^["']|["']$/g,"")).lines)console.log(i);return{kind:"continue",ownNext:!0}}let o=e.includes("--all"),r=e.find(s=>!s.startsWith("--"));for(let s of zh(t.cwd,{...r?{scope:r}:{},all:o}))console.log(s);return{kind:"continue",ownNext:!0}}ie();import{evaluateCorpus as T1,buildRegistry as A1,lintArticles as E1,scanTerminology as N1,BUILTIN_RULES as D1,surfaceCoverageSafe as j1,readProjectConfig as I1}from"document360-engine";import on from"picocolors";var rn=3,st=(e,t)=>`${e} ${t}${e===1?"":"s"}`,e$=e=>`${Me(e.path)}:${e.line}`,Qh=e=>e.split("/").pop()?.split("\\").pop()??e;function Zk(e,t,n,o,r,s,i){if(r.length===0)return;e.push(` ${V(t,n)}${o}`);let a=i?r:r.slice(0,rn);for(let l of a)e.push(u(` ${e$(l)} ${l.detail}`));r.length>a.length&&e.push(u(` \u2026and ${r.length-a.length} more \u2014 /eval --all`)),e.push(u(` ${s}`)),e.push("")}function Jh(e,t={}){let n=A1(e),o=new Set([...D1.map(h=>h.id),...n.rules.map(h=>h.id)]),r=T1(e,o,{...t.scope?{scope:t.scope}:{},...t.profile?{profile:t.profile}:{}}),s=t.all===!0,i=[];if(r.articles===0)return[Z("Knowledge-base score"),"",`${V("\u25CB",u)}No articles to read yet.`,""];let a=j1(e,I1(e)),l=r.links.absolute.length+r.links.deadAnchors.length+r.links.staleLabels.length+r.shapes.typeTemplates.filter(h=>h.deviations.length>0).length+(r.shapes.synopsisForms.length>1?1:0)+(a.recognised?a.areas.length:0);if(i.push(Z("Knowledge-base score")+u(` ${st(r.articles,"article")} read \xB7 ${l===0?"nothing to look at":`${l} to look at`}`)),i.push(""),Zk(i,"\u2717",on.red,"Internal links written as portal URLs",r.links.absolute,"These break the day the site moves. Write them as relative .md links instead.",s),Zk(i,"\u2717",on.red,"Links pointing at headings that do not exist",r.links.deadAnchors,"The heading was renamed after the link was written. Point it at the current heading.",s),r.links.staleLabels.length>0){let h=r.links.staleLabels.reduce((y,x)=>y+x.sites.length,0);i.push(` ${V("\u26A0",on.yellow)}${st(r.links.staleLabels.length,"link label")} name an article something it is not called${h>r.links.staleLabels.length?u(`, in ${st(h,"place")}`):""}`);for(let y of s?r.links.staleLabels:r.links.staleLabels.slice(0,rn))if(i.push(u(` "${y.label}" \u2192 the article is titled "${y.title}"${y.sites.length>1?` (${y.sites.length}\xD7)`:""}`)),s)for(let x of y.sites)i.push(u(` ${e$(x)}`));!s&&r.links.staleLabels.length>rn&&i.push(u(` \u2026and ${r.links.staleLabels.length-rn} more \u2014 /eval --all`)),i.push(u(" A reader clicks expecting one page and lands on another name.")),i.push("")}if(s&&r.links.shortenedLabels.length>0){i.push(` ${V("\u25CB",u)}${st(r.links.shortenedLabels.length,"link label")} shorten the title they point at`);for(let h of r.links.shortenedLabels.slice(0,10))i.push(u(` "${h.label}" \u2192 "${h.title}"`));i.push(u(" Usually fine. Listed separately because it is a judgment call, not a defect.")),i.push("")}if(s&&r.links.sidebarLabelMismatch>0&&(i.push(` ${V("\u25CB",u)}${st(r.links.sidebarLabelMismatch,"Related-articles link")} not counted above`),i.push(u(" Those labels are dropped when the article is saved. Document360 builds that list from")),i.push(u(" the real titles, so a reader never sees the label written here.")),i.push("")),r.shapes.synopsisForms.length>1){i.push(` ${V("\u26A0",on.yellow)}The command summary line appears in ${st(r.shapes.synopsisForms.length,"shape")}`);for(let h of r.shapes.synopsisForms)i.push(u(` ${String(h.count).padStart(3)} ${h.form.padEnd(14)} ${h.examples.map(Qh).join(", ")}`));r.shapes.noSynopsis.length>0&&i.push(u(` ${st(r.shapes.noSynopsis.length,"article")} carry none at all`)),i.push(u(" Same information, different labels. Pick one and use it everywhere.")),i.push("")}for(let h of r.shapes.typeTemplates)if(h.deviations.length!==0){i.push(` ${V("\u26A0",on.yellow)}${h.deviations.length} of ${st(h.articles,`${h.type} article`)} skip a section the rest of them carry`),i.push(u(` Most ${h.type} articles have: ${h.expected.map(y=>`## ${y.heading} (${y.count})`).join(" \xB7 ")}`));for(let y of s?h.deviations:h.deviations.slice(0,rn))i.push(u(` ${Qh(y.path)} \u2014 missing ${y.missing.map(x=>`## ${x}`).join(", ")}`));!s&&h.deviations.length>rn&&i.push(u(` \u2026and ${h.deviations.length-rn} more \u2014 /eval --all`)),i.push(u(" A deviation may be deliberate. This counts them; it does not say the template is right.")),i.push("")}try{let h=N1(e,t.scope?{scope:t.scope}:{});if(h.variance.length>0){i.push(` ${V("\u26A0",on.yellow)}${st(h.variance.length,"term")} spelled more than one way across the set`);for(let y of h.variance.slice(0,s?99:rn))i.push(u(` ${y.uses.map(x=>`"${x.form}" \xD7${x.count}`).join(" \xB7 ")}`));h.headNouns.length>0&&i.push(u(` ${st(h.headNouns.length,"short name")} may be a longer one abbreviated \u2014 /terms lists them`)),i.push(u(' Settle one and every later run enforces it: /terms --approve "<term>"')),i.push("")}}catch{}let c=0;try{let y=E1({cwd:e,...t.scope?{scope:t.scope}:{}}).findings.filter(w=>!w.baselined);c=y.filter(w=>w.ruleId==="Document360.Changelog").length;let x=y.filter(w=>w.severity==="error").length;if(i.push(` ${V(x>0?"\u2717":y.length>0?"\u26A0":"\u2713",x>0?on.red:y.length>0?on.yellow:on.green)}`+(y.length===0?"Style rules: nothing reported":`Style rules: ${st(y.length,"finding")}${x>0?`, ${x} blocking publish`:", none blocking publish"}`)),y.length>0){let w=new Map;for(let S of y)w.set(S.ruleId,(w.get(S.ruleId)??0)+1);for(let[S,P]of[...w.entries()].sort((T,R)=>R[1]-T[1]).slice(0,s?99:5))i.push(u(` ${String(P).padStart(4)} ${S}`));i.push(u(" Fix what can be fixed mechanically: /lint --fix"))}i.push("")}catch{}if(r.debt&&r.debt.total>0){let h=r.debt.liveRules.reduce((w,S)=>w+S.count,0),y=r.debt.inertRules.reduce((w,S)=>w+S.count,0),x=r.debt.createdAt.slice(0,10);if(h>0){i.push(` ${V("\u2139",u)}${st(h,"style finding")} accepted as exempt on ${x}, from rules that are still on`);for(let w of r.debt.liveRules.slice(0,s?99:4))i.push(u(` ${String(w.count).padStart(4)} ${w.rule}`));i.push(u(" Nothing reports these, so the articles read as compliant. They are exempt, not compliant.")),i.push(u(" Work them down with /review --all --fix, then /lint --all --fix."))}else y>0&&(i.push(` ${V("\u25CB",u)}${st(y,"finding")} accepted on ${x} under a style guide no longer in use`),i.push(u(" They match no active rule, so they suppress nothing. Only weight in the file.")));i.push("")}if(a.recognised&&a.areas.length>0){i.push(` ${V("\u26A0",on.yellow)}${st(a.areas.length,"part")} of the product no article says it documents`);for(let h of a.areas.slice(0,s?99:5))i.push(u(` ${String(h.files).padStart(4)} ${h.folder}`));!s&&a.areas.length>5&&i.push(u(` \u2026and ${a.areas.length-5} more \u2014 /eval --all lists them.`)),i.push(u(` ${a.documented} of ${a.filesScanned} source files are cited by an article.`)),a.declined>0&&i.push(u(` ${a.declined} you declined, left out of that count.`)),i.push(u(" /audit proposes the articles. /audit --decline <path> settles a folder or file for good.")),i.push("")}else a.recognised||(i.push(` ${V("\u25CB",u)}Product coverage was not measured`),i.push(u(` ${a.reason}`)),i.push(""));if(i.push(` ${V("\u25CB",u)}Length: ${r.length.words.toLocaleString()} words, median ${r.length.median.toLocaleString()} an article`),r.length.longest.length>0){i.push(u(` ${st(r.length.longest.length,"article")} past 2,500 words:`));for(let h of s?r.length.longest:r.length.longest.slice(0,rn))i.push(u(` ${h.words.toLocaleString()} ${Qh(h.path)}`));!s&&r.length.longest.length>rn&&i.push(u(` \u2026and ${r.length.longest.length-rn} more \u2014 /eval --all`))}return c>0&&(i.push(u(` ${st(c,"sentence")} tell the reader what the product used to do.`)),i.push(u(" Those are the longest sentences in a corpus, and the cheapest words to take out."))),i.push(u(" No previous measurement to compare against, so this is a reading, not a trend.")),i.push(""),l===0&&(r.debt?.total??0)===0&&(i.push(` ${V("\u2713",on.green)}Links resolve, one template shape, one name per thing.`),i.push("")),i.push(u(` Free \u2014 this read your ${st(r.articles,"article")} and called nothing.`)),i}async function t$(e,t){let n=e.includes("--all"),o=e.find(r=>!r.startsWith("--"));for(let r of Jh(t.cwd,{...o?{scope:o}:{},...t.profileName?{profile:t.profileName}:{},all:n}))console.log(r);return{kind:"continue",ownNext:!0}}import{fetchPortalReuse as J1,readReuseCache as Z1,writeReuseCache as ej,resolveActiveProfile as tf,resolveProjectId as nf,createVariable as i$,createSnippet as a$,reuseNameProblem as tj,variableRule as nj,VARIABLE_MAX_CHARS as r$}from"document360-engine";ie();import{scanReuse as n$,scanValueCandidates as o$,buildReuseAuditPrompt as L1,reuseAuditProposalPath as O1,readReuseProposal as M1,readReuseCache as _1,listArticleFiles as U1,normalizeScope as F1,docsRootOf as W1,variableRule as B1}from"document360-engine";import{rmSync as H1}from"node:fs";import G1 from"picocolors";var Ql=6,q1=20;function V1(e,t){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}\u2026`:n}function Y1(e,t=52){let n=e.replace(/\s+/g," ").trim(),o=[],r="";for(let s of n.split(" "))r===""?r=s:`${r} ${s}`.length<=t?r+=` ${s}`:(o.push(r),r=s);return r!==""&&o.push(r),o}function Jl(e,t,n,o){let r=[Z("Content reuse audit"),""];return r.push(`${e} article${e===1?"":"s"} read${u(" \xB7 free to look")}`,""),r.push(` ${String(n).padStart(3)} value${n===1?"":"s"} written out by hand in more than one article`),r.push(` ${String(t).padStart(3)} block${t===1?"":"s"} written more than once, in different words`),o>0&&r.push(u(` ${o} more families were left out of this pass \u2014 the longest ones are shown first.`)),r}function Zl(e,t){let n=W1(e),o=t.filter(x=>x!=="audit"&&!x.startsWith("--")).find(x=>x!==void 0),r=o?F1(n,o.replace(/\\/g,"/").replace(/\/+$/,"")):void 0,s=U1(e,r).length;if(s===0)return{lines:[oe("\u25CB",r?`No articles under ${r} to audit.`:"No articles to audit yet."),u(" Reuse is about text that repeats, so there has to be some text first.")]};let i=n$(e,{...r?{scope:r}:{},groups:!0}),a=o$(e,r?{scope:r}:void 0),l=i.groups??[],c=a.candidates;if(l.length===0&&c.length===0)return{lines:[oe("\u2713",`Nothing repeats across ${s} article${s===1?"":"s"} \u2014 there is nothing to keep in one place.`),u(" That is a good answer, not an empty one. Run this again after a few more articles.")]};let h=_1(e),y=O1(e);try{H1(y,{force:!0})}catch{}return{prompt:L1({cwd:e,families:l,values:c,snippets:h?.snippets??[],variables:h?.variables??[],terms:h?.terms??[],proposalPath:y,articles:s}),display:r?`/reuse audit ${r}`:"/reuse audit",articles:s,families:l.length,values:c.length}}function K1(e,t){let n=[],o=` ${String(t).padStart(2)} ${e.kind.padEnd(9)}${G1.bold(e.name.padEnd(q1))}`,r=e.kind==="variable"?[`"${V1(e.value,52)}"`]:Y1(`"${e.value}"`);n.push(`${o}${r[0]??""}`);for(let a of r.slice(1))n.push(`${" ".repeat(o.length-10)}${a}`);let s=e.uses>0?`${e.uses} use${e.uses===1?"":"s"} across ${e.files} article${e.files===1?"":"s"}`:"",i=e.why?s?` \u2014 ${e.why}`:e.why:"";return(s||i)&&n.push(u(` ${s}${i}`)),n}function z1(e,t,n){let o=[],r=e.proposals.length;if(o.push(r===0?oe("\u2713",`An editor read ${t} famil${t===1?"y":"ies"} and ${n} value${n===1?"":"s"}. None of it has to stay identical everywhere.`):oe("\u2713",`An editor read ${t} famil${t===1?"y":"ies"} and ${n} value${n===1?"":"s"}. ${r} ${r===1?"is":"are"} worth keeping in one place.`),""),e.proposals.forEach((s,i)=>{o.push(...K1(s,i+1),"")}),e.rejected.length>0){o.push(" Not proposed, and why:");for(let s of e.rejected.slice(0,Ql))o.push(u(` \xB7 ${s.what} \u2014 ${s.why}`));e.rejected.length>Ql&&o.push(u(` \xB7 \u2026and ${e.rejected.length-Ql} more.`)),o.push("")}if(e.dropped.length>0){o.push(oe("\u26A0",`${e.dropped.length} proposal${e.dropped.length===1?"":"s"} could not be used:`));for(let s of e.dropped.slice(0,Ql))o.push(u(` \xB7 ${s}`));o.push("")}return o}function X1(){return[u(" Nothing to create. The knowledge base repeats itself, but not in ways that have to stay"),u(" identical everywhere \u2014 which is the answer an editor is for."),""]}function ec(e,t){let n=[],o=t.created.map(a=>a.name);o.length>0&&(n.push(oe("\u2713",`Created ${o.length} on Document360: ${o.join(", ")}.`)),n.push(u(" Your local copy is in step and the agent has been restarted, so it writes with them from now on.")));for(let a of t.failed)n.push(oe("\u2717",`Document360 refused "${a.name}" \u2014 ${a.why}`));t.failed.length>0&&n.push(u(" Nothing else was changed. A name already in use is the usual cause; /reuse lists what exists."));let r=t.created.some(a=>a.kind==="variable"),s=t.created.filter(a=>a.kind==="snippet"),i=null;if(r){let a=B1(e).rule!==null;n.push(""),n.push(a?oe("\u2139","Those values are still typed out by hand across your articles."):oe("\u2139","Those values are created, but nothing checks them yet.")),a&&(n.push(u(" /lint --all --fix swaps every one of them \u2014 it costs no agent time, and nothing else in")),n.push(u(" your articles changes.")),i="/lint --all --fix")}return s.length>0&&(n.push(""),n.push(oe("\u2139",`${s.length===1?"The snippet exists":`The ${s.length} snippets exist`} on Document360, but no article references ${s.length===1?"it":"them"} yet.`)),n.push(u(` Ask me to use ${s.length===1?"it":"them"} in an article, or run /review --all --fix and the editor will replace the`)),n.push(u(" passages it finds. Replacing a passage changes the words a reader sees, so it goes through")),n.push(u(" an editorial read rather than a mechanical swap.")),i||(i="/review --all --fix")),i&&n.push("",i,""),{lines:n,cta:i}}function tc(e,t){let n=e.indexOf("--create");if(n===-1)return{picks:[],bad:[]};let o=e.slice(n+1).filter(i=>!i.startsWith("--"));if(o.length===1&&(o[0]==="a"||o[0]==="all"))return{picks:Array.from({length:t},(i,a)=>a),bad:[]};let r=[],s=[];for(let i of o){let a=Number(i);if(!Number.isInteger(a)||a<1||a>t){s.push(i);continue}r.includes(a-1)||r.push(a-1)}return{picks:r,bad:s}}function Q1(e){if(e===0)return[];let t=Array.from({length:e},(n,o)=>o+1).join(" ");return[u(` Pick what to create. Run the line below for all ${e}, or edit the numbers to take some.`),"",`/reuse audit --create ${t}`,""]}function nc(){return[oe("\u2717","There is no reuse proposal to create from."),u(" Run /reuse audit first \u2014 it reads your articles and works out what belongs in one place."),"","/reuse audit",""]}function oc(e,t){let n=M1(e);if(!n)return[oe("\u26A0","The editor did not leave a proposal, so there is nothing to create."),u(" Nothing was changed. This is usually a turn that stopped early \u2014 running it again is safe,"),u(" and the scan it starts from costs nothing."),"",t?`/reuse audit ${t}`:"/reuse audit",""];let o=n$(e,{...t?{scope:t}:{},groups:!0}),r=o$(e,t?{scope:t}:void 0),s=z1(n,(o.groups??[]).length,r.candidates.length);return s.push(...n.proposals.length===0?X1():Q1(n.proposals.length)),s}ie();import{readReuseProposal as oj}from"document360-engine";import es from"picocolors";var Zh=8,In=6,ef=14,rj=52;function sj(e){if(!e)return"";let t=new Date(e);return Number.isNaN(t.getTime())?"":t.toLocaleDateString(void 0,{day:"numeric",month:"short"})}function s$(e,t=rj){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}\u2026`:n}function of(e){let t=Z1(e),n=[Z("Reusable content"),""];if(!t||t.terms.length===0&&t.snippets.length===0&&t.variables.length===0)return n.push(`${V("\u25CB",u)}Nothing pulled from Document360 yet.`,"",u(" A variable holds a value like your product name in one place, so changing it changes every"),u(" article at once. A snippet does the same for a whole block, like who to contact when"),u(" something goes wrong. A term is defined once and explained everywhere it first appears."),"","/reuse pull",""),n;let o=sj(t.pulledAt);if(t.terms.length===0)n.push(`${V("\u25CB",u)}No glossary terms in this Document360 project${o?u(` (checked ${o})`):""}.`);else{n.push(`${t.terms.length} term${t.terms.length===1?"":"s"} from Document360${o?u(`, pulled ${o}`):""}.`,"");for(let r of t.terms.slice(0,Zh)){let s=" ".repeat(Math.max(1,ef-r.term.length));n.push(` ${es.bold(r.term)}${s}${u(r.definition||"(no definition)")}`)}t.terms.length>Zh&&n.push(u(` \u2026and ${t.terms.length-Zh} more.`))}if(t.variables.length>0){n.push("",`${t.variables.length} value${t.variables.length===1?"":"s"} kept in one place.`,"");for(let s of t.variables.slice(0,In)){let i=" ".repeat(Math.max(1,ef-s.name.length));n.push(` ${es.bold(s.name)}${i}${u(s.value?`"${s$(s.value)}"`:"(no value recorded)")}`)}t.variables.length>In&&n.push(u(` \u2026and ${t.variables.length-In} more.`));let{skipped:r}=nj(e);if(r.length>0){let s=t.variables.length-r.length;n.push("",u(` ${s} of ${t.variables.length} are checked in your articles. ${r.length===1?"This one is":"These are"} not:`));for(let i of r.slice(0,In))n.push(u(` ${i.name} \u2014 ${i.why}.`));r.length>In&&n.push(u(` \u2026and ${r.length-In} more.`))}}if(t.snippets.length>0){n.push("",`${t.snippets.length} maintained block${t.snippets.length===1?"":"s"}.`,"");for(let r of t.snippets.slice(0,In)){let s=" ".repeat(Math.max(1,ef-r.name.length)),i=r.usedBy>0?u(` (in ${r.usedBy} article${r.usedBy===1?"":"s"})`):"";n.push(` ${es.bold(r.name)}${s}${u(r.description||s$(r.value??"")||"(no content recorded)")}${i}`)}t.snippets.length>In&&n.push(u(` \u2026and ${t.snippets.length-In} more.`))}return n.push("",u(" Terms are checked at first use in every article, a value you typed out by hand is flagged,"),u(" and the writer reuses your blocks by name instead of writing its own version of them."),"","/reuse pull","/lint --all",""),n}async function $i(e,t){let n,o;try{let c=tf(e,t);n={profile:c.name,connection:c.connection,projectId:c.project.projectId,projectName:c.project.projectName},o=await nf(n,c.project?.projectId)}catch(c){return{lines:[oe("\u2717",`Not signed in to Document360: ${c instanceof Error?c.message:String(c)}`),u(" Run /login first.")],restart:!1}}let r;try{r=await J1(n,o)}catch(c){return{lines:[oe("\u26A0",`Document360 didn't return your reusable content \u2014 ${c instanceof Error?c.message:String(c)}.`),u(" Nothing is blocked. Everything else works exactly as it did; you just do not get the"),u(" first-use check on your terms, or the reuse checks, until this succeeds.")],restart:!1}}let s={pulledAt:new Date().toISOString(),profile:n.profile,projectId:o,terms:r.terms,snippets:r.snippets,variables:r.variables};if(ej(e,s),s.terms.length+s.snippets.length+s.variables.length===0)return{lines:[oe("\u2139","This Document360 project has no terms, snippets or variables yet."),u(" Someone with portal access adds them under Content tools. A good first one is your product"),u(" name as a variable: it is the string most likely to change, and the hardest to change late.")],restart:!1};let a=[`${s.terms.length} term${s.terms.length===1?"":"s"}`,`${s.snippets.length} snippet${s.snippets.length===1?"":"s"}`,`${s.variables.length} variable${s.variables.length===1?"":"s"}`],l=[oe("\u2713",`Pulled ${a.join(" \xB7 ")} from Document360.`)];return r.droppedTerms.length>0&&l.push(u(` ${r.droppedTerms.length} term${r.droppedTerms.length===1?" has":"s have"} no wording recorded in Document360, so ${r.droppedTerms.length===1?"it is":"they are"} not checked:`),u(` ${r.droppedTerms.slice(0,6).join(", ")}${r.droppedTerms.length>6?`, and ${r.droppedTerms.length-6} more`:""}.`)),r.contentlessBlocks.length>0&&l.push(u(` ${r.contentlessBlocks.length} block${r.contentlessBlocks.length===1?"":"s"} came back without content, so ${r.contentlessBlocks.length===1?"it is":"they are"} not matched against your articles:`),u(` ${r.contentlessBlocks.slice(0,6).join(", ")}${r.contentlessBlocks.length>6?`, and ${r.contentlessBlocks.length-6} more`:""}.`)),l.push("",u(" Your terms are now checked at first use in every article, a value you typed out by hand is"),u(" flagged, and the writer reuses your blocks by name instead of writing its own version."),"","/lint --all",""),{lines:l,restart:!0}}async function rf(e,t,n,o,r){let s=tj(n);if(s)return{lines:[oe("\u2717",`That name will not work: ${s}.`),u(' Try something like "product-name".')],restart:!1};if(o.trim()==="")return{lines:[oe("\u2717","A value is required \u2014 that is the text this will stand for in your articles.")],restart:!1};if(t==="variable"&&o.length>r$)return{lines:[oe("\u2717",`A variable holds at most ${r$} characters and this is ${o.length}.`),u(' Longer text belongs in a snippet: /reuse add snippet <name> "<text>"')],restart:!1};let i,a;try{let l=tf(e);i={profile:l.name,connection:l.connection,projectId:l.project.projectId,projectName:l.project.projectName},a=await nf(i,l.project?.projectId)}catch(l){return{lines:[oe("\u2717",`Not signed in to Document360: ${l instanceof Error?l.message:String(l)}`),u(" Run /login first.")],restart:!1}}try{let l=t==="variable"?await i$(i,a,{name:n,value:o}):await a$(i,a,{name:n,value:o,...r?{description:r}:{}}),c=await $i(e);return{lines:[oe("\u2713",`Created the ${t} "${l.name}" on Document360.`),u(` Write ${t==="variable"?`:variable[]{name="${l.name}"}`:`::snippet{name="${l.name}"}`} and Document360 puts your text there.`),"",...c.lines],restart:!0}}catch(l){let c=l instanceof Error?l.message:String(l);return{lines:[oe("\u2717",`Document360 refused to create that ${t} \u2014 ${c}`),u(" Nothing was changed. A name already in use is the usual cause; /reuse lists what exists.")],restart:!1}}}function l$(e){let t=e.trim();return t.length>=2&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))?t.slice(1,-1):t}function ij(e){let t=e.indexOf("--desc");if(t===-1)return{rest:e};let n=l$(e.slice(t+1).join(" "));return{rest:e.slice(0,t),...n?{description:n}:{}}}function sf(e){let{rest:t,description:n}=ij(e),o=t.filter(l=>!l.startsWith("--")),[,r,s,...i]=o;if(r!=="variable"&&r!=="snippet")return{error:'Say which one: /reuse add variable <name> "<value>", or /reuse add snippet <name> "<text>".'};if(!s)return{error:`Give it a name: /reuse add ${r} <name> "<value>".`};if(r==="variable"&&n)return{error:"Only a snippet takes --desc; a variable is just its value. Drop the flag, or add it as a snippet."};let a=l$(i.join(" "));return a===""?{error:`Give it a value: /reuse add ${r} ${s} "<the text it stands for>".`}:{kind:r,name:s,value:a,...n?{description:n}:{}}}async function c$(e,t){let n=e.find(o=>!o.startsWith("--"));if(n==="add"){let o=sf(e);if("error"in o)return console.log(`${V("\u2717",es.red)}${o.error}`),{kind:"continue",ownNext:!0};let r=await rf(t.cwd,o.kind,o.name,o.value,o.description);for(let s of r.lines)console.log(s);return r.restart?{kind:"clear"}:{kind:"continue",ownNext:!0}}if(n==="pull"){let o=await $i(t.cwd);for(let r of o.lines)console.log(r);for(let r of Ye(t.cwd,"/reuse pull"))console.log(r);return o.restart?{kind:"clear"}:{kind:"continue",ownNext:!0}}if(n==="audit"){if(e.includes("--create")){let r=oj(t.cwd);if(!r||r.proposals.length===0){for(let h of nc())console.log(h);return{kind:"continue",ownNext:!0}}let{picks:s,bad:i}=tc(e,r.proposals.length);for(let h of i)console.log(`${V("\u26A0",es.yellow)}There is no proposal ${h} \u2014 the list has ${r.proposals.length}.`);if(s.length===0)return console.log(`${V("\u25CB",u)}Nothing picked, so nothing was created.`),{kind:"continue",ownNext:!0};let{outcome:a,pullLines:l}=await af(t.cwd,s.map(h=>r.proposals[h]));for(let h of l)console.log(h);let{lines:c}=ec(t.cwd,a);for(let h of c)console.log(h);for(let h of Ye(t.cwd,"/reuse audit"))console.log(h);return a.created.length>0?{kind:"clear"}:{kind:"continue",ownNext:!0}}let o=Zl(t.cwd,e);if("lines"in o){for(let r of o.lines)console.log(r);for(let r of Ye(t.cwd,"/reuse audit"))console.log(r);return{kind:"continue",ownNext:!0}}for(let r of Jl(o.articles,o.families,o.values,0))console.log(r);return{kind:"forward-to-agent",prompt:o.prompt,display:o.display}}if(n&&n!=="show")return console.log(`${V("\u2717",es.red)}I don't know "/reuse ${n}". Use /reuse to see what this project maintains, /reuse pull to refresh it, /reuse audit to find what belongs in one place, or /reuse add variable <name> "<value>".`),{kind:"continue",ownNext:!0};for(let o of of(t.cwd))console.log(o);return{kind:"continue",ownNext:!0}}async function af(e,t){let n=[],o=[],r,s;try{let a=tf(e);r={profile:a.name,connection:a.connection,projectId:a.project.projectId,projectName:a.project.projectName},s=await nf(r,a.project?.projectId)}catch(a){return{outcome:{created:[],failed:t.map(l=>({name:l.name,why:`not signed in to Document360: ${a instanceof Error?a.message:String(a)}`}))},pullLines:[u(" Run /login first.")]}}for(let a of t)try{a.kind==="variable"?await i$(r,s,{name:a.name,value:a.value}):await a$(r,s,{name:a.name,value:a.value,...a.description?{description:a.description}:{}}),n.push(a)}catch(l){o.push({name:a.name,why:l instanceof Error?l.message:String(l)})}if(n.length===0)return{outcome:{created:n,failed:o},pullLines:[]};let i=await $i(e);return{outcome:{created:n,failed:o},pullLines:i.restart?[]:i.lines}}ie();import{readProjectConfig as aj,writeProjectConfig as u$,isAppType as lj,playbookSkillName as cj,detectAppType as d$}from"document360-engine";var p$=["web","cli","service","library"],uj=new Set(["web","cli"]);function lf(e){return uj.has(e)?`${cj(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function rc(e,t){let n=t.cwd,o=aj(n);if(!o)return console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let s=o.appType??d$(n);if(s){let i=o.appType?"set in config":"auto-detected";console.log(`${Z("Genre:")} ${s} (${i}) \u2014 ${lf(s)}`)}else console.log(H("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(u(`Set it: /genre <${p$.join("|")}> \xB7 revert to auto-detect: /genre auto`)),{kind:"continue"}}if(r==="auto"||r==="clear"){if(!o.appType)return console.log(u("Already on auto-detect (no genre set in config).")),{kind:"continue"};let{appType:s,...i}=o;u$(i,n);let a=d$(n);return console.log(X(`\u2713 Genre reset to auto-detect \u2014 now: ${a?`${a} (${lf(a)})`:"unclassified (no playbook)"}.`)),console.log(u(" Restarting the agent so the loaded playbook matches\u2026")),{kind:"clear"}}return lj(r)?(u$({...o,appType:r},n),console.log(X(`\u2713 Genre set to ${r} \u2014 ${lf(r)}.`)),console.log(u(" Restarting the agent so the playbook loads\u2026")),{kind:"clear"}):(console.log(L(`Unknown genre "${r}". Choose one of: ${p$.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}var h$={help:Su,"?":Su,clear:pg,exit:Cu,quit:Cu,init:ju,mcp:Ta,push:tl,publish:zy,audit:(e,t)=>{let n=il(t.cwd,e);if(n){for(let o of n)console.log(o);return Promise.resolve({kind:"continue",ownNext:!0})}return Vs({cwd:t.cwd,profileName:t.profileName})},discover:tw,scope:ow,pull:yw,resolve:fw,convert:Iw,write:zw,draft:eb,document:tb,resume:rb,rename:sb,profile:ib,model:cb,doctor:ri,env:sg,logs:zm,workspace:fb,project:mb,"allow-prod":gb,login:yb,logout:wb,screenshot:async(e,t)=>{let n=Os(e);return n.mode==="capture"?Mp(n.rest,t):n.mode==="annotate"?Bp(n.rest,t):n.mode==="verify"?bb(n.rest,t):n.mode==="checklist"?Yr(e,t):qa(e,t)},capture:Mp,annotate:Bp,"capture-setup":Yr,devhints:vg,inbox:_b,ask:Fb,"catch-up":Yb,comments:Zb,update:nk,reset:ak,lint:rp,check:Fw,"style-guide":Kl,review:Uk,reorder:Wk,restructure:Bk,structure:Sk,status:Yk,retire:Kk,untrack:zk,terms:Jk,eval:t$,reuse:c$,genre:rc,roadmap:Ly,share:Hb,auto:ew};function f$(e){let t=e.trim();if(!t.startsWith("/"))return null;let n=t.slice(1).split(/\s+/),o=(n[0]??"").toLowerCase();return o?{name:o,args:n.slice(1)}:null}import{spawnSync as dj}from"node:child_process";import{readProjectConfig as pj,recordAnalyzedCommit as hj,recordReportedAreas as fj,resolveActiveProfile as mj,surfaceCoverageSafe as gj}from"document360-engine";function yj(e){try{let t=dj("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8",timeout:1200}),n=(t.stdout||"").trim();return t.status===0&&n?n:null}catch{return null}}function vi(e,t){try{let n=mj(e,t),o=gj(e,pj(e));o.recognised&&fj(e,n.name,o.areas.map(s=>s.folder));let r=yj(e);return r&&hj(e,n.name,r)?r:null}catch{return null}}Vn();var m$="Or just tell me what to write or update.";function y$(e,t=0){if(!(e>0))return null;let n=e===1?"the page":"those pages",o=`${e} note${se(e)} from your builder ${e===1?"is":"are"} waiting on code they haven't finished.`,r=t>=e?`I've asked whether ${e===1?"it's":"they're"} done, and I'll write ${n} once the code lands.`:`I'll write ${n} once the code lands, and /catch-up asks your builder whether ${e===1?"it's":"they're"} done.`;return`${o} ${r} Nothing else is blocked.`}function wj(e,t,n={}){let o=n.onlyScreenshots?"\u2713 Your writing is done \u2014 nothing is waiting to be written, reviewed, saved or taken live. Readers are seeing every article you have.":"\u2713 That\u2019s the full round trip \u2014 nothing is waiting to be written, reviewed, saved or taken live. Readers are seeing every article you have.";return n.listed?o:`${o}
|
|
444
|
+
`),display:`/restructure${n?` ${n}`:""}`}}async function Vk(e,t){let n=qh(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"})}ae();import{computeReadiness as h1,readinessPlaceholderPlaces as f1,coverageGap as m1,danglingCount as g1}from"document360-engine";import Ue from"picocolors";var In=5;function Me(e,t=58){let n=e.replace(/\\/g,"/");return n.length<=t?n:`\u2026${n.slice(n.length-t+1)}`}function y1(e){let t=[],n=e.verdict;if(e.conflicts.length>0&&t.push({glyph:"\u2717",paint:Ue.red,title:`Changed here and on Document360 (${e.conflicts.length})`,fix:"/resolve",items:e.conflicts.map(o=>Me(o))}),n.unreviewed.length>0&&t.push({glyph:"\u2717",paint:Ue.red,title:`Never read by an editor (${n.unreviewed.length})`,fix:"/review --blocked --fix",items:n.unreviewed.map(o=>Me(o))}),n.styleErrors.length>0){let o=n.styleErrors.reduce((r,s)=>r+s.errors,0);t.push({glyph:"\u2717",paint:Ue.red,title:`Break house style rules your config makes blocking (${o} error${o===1?"":"s"})`,fix:"/lint --blocked --fix",items:n.styleErrors.map(r=>`${Me(r.path)} (${r.errors})`)})}if(n.placeholders.length>0){let o=f1(e);t.push({glyph:"\u2717",paint:Ue.red,title:`Would show "[Screenshot: \u2026]" to your readers (${n.placeholders.length} article${n.placeholders.length===1?"":"s"}, ${o} place${o===1?"":"s"})`,fix:"/screenshot",items:n.placeholders.map(r=>`${Me(r.path)} (${r.missingShots.length+r.orphans})`)})}return t}function w1(e){let t=e.verdict,n=[];return e.conflicts.length===0&&n.push(`${V("\u2713",Ue.green)}Nothing is in conflict with Document360`),t.unreviewed.length===0&&n.push(`${V("\u2713",Ue.green)}Every article has been read by an editor`),t.styleErrors.length===0&&n.push(`${V("\u2713",Ue.green)}House style: nothing blocking`),t.placeholders.length===0&&n.push(`${V("\u2713",Ue.green)}No placeholder text would reach a reader`),n}function b1(e,t){if(e.rows.length===0)return[];let n=r=>r?Ue.green("\u2713"):Ue.red("\u2717"),o=e.rows.map((r,s)=>[String(s+1),Me(r.path,46),n(r.reviewed),r.styleErrors===0?Ue.green("\u2713"):Ue.red(`\u2717 ${r.styleErrors}`),r.placeholders===0?Ue.green("\u2713"):Ue.red(`\u2717 ${r.placeholders}`),r.conflict?Ue.red("conflict"):r.draftPending?Ue.yellow("draft"):r.localAhead?u("not saved"):u("\u2014")]);return Qs(["#","Article","Read","Style","Pictures","Document360 (last sync)"],o,t).split(`
|
|
445
|
+
`)}function Vh(e,t={}){let n=h1(e,t.profileName),o=[];if(n.rows.length===0){o.push(Z("Publish readiness")),o.push("");let h=m1(n.coverage),y=n.neverPushed.length;return o.push(n.tracked===0?y>0?`${V("\u25CB",Ue.gray)}Nothing here is on Document360 yet.`:`${V("\u25CB",Ue.gray)}No articles are tracked yet. /write authors them, /push saves them to Document360.`:h>0||y>0?`${V("\u2713",Ue.green)}All ${n.tracked} tracked articles are live and unchanged.`:`${V("\u2713",Ue.green)}All ${n.tracked} articles are live and unchanged \u2014 nothing is waiting on you.`),o.push(...k1(n)),n.neverPushed.length>0&&(o.push(""),o.push(...Yk(n))),n.orphans.length>0&&o.push(...zk(n)),n.unadopted.length>0&&(o.push(""),o.push(...Kk(n))),o.push(""),o.push(u(" Free \u2014 /status reads your local files and the last sync. It calls nothing.")),o}let r=n.rows.length,s=n.blocked.length;o.push(Z("Publish readiness")+u(` ${r} article${r===1?"":"s"} not yet settled with readers \xB7 ${s===0?"nothing blocked":`${s} blocked`}`)),o.push(""),t.all&&(o.push(...b1(n,t.width??100)),o.push(""));for(let h of y1(n)){o.push(` ${V(h.glyph,h.paint)}${h.title}${h.fix?u(` ${h.fix}`):""}`);for(let y of h.items.slice(0,In))o.push(u(` ${y}`));h.items.length>In&&o.push(u(` \u2026and ${h.items.length-In} more`)),o.push("")}let i=Yk(n);i.length>0&&(o.push(...i),o.push(""));let a=Kk(n);a.length>0&&(o.push(...a),o.push(""));let l=w1(n);if(l.length>0){for(let h of l)o.push(` ${h}`);o.push("")}let c=n.rows.filter(h=>h.localAhead).length;return c>0&&o.push(u(` ${c} changed here \u2014 /push saves ${c===1?"it":"them"} to Document360 as ${c===1?"a draft":"drafts"}. Readers see nothing until then.`)),n.draftPending.length>0&&(o.push(u(` ${n.draftPending.length} saved on Document360 as ${n.draftPending.length===1?"a draft":"drafts"} and not live \u2014 /publish takes ${n.draftPending.length===1?"it":"them"} to your readers.`)),o.push(u(" That is from your last sync. /pull re-checks what is live."))),n.orphans.length>0&&o.push(...zk(n)),!t.all&&n.rows.length>0&&o.push(u(" /status --all shows every article, gate by gate.")),o.push(""),o.push(u(" Free \u2014 /status reads your local files and the last sync. It calls nothing.")),o}function Yk(e){let t=e.neverPushed.length;if(t===0)return[];let n=[` ${V("\u25CB",Ue.gray)}${t===1?"One article is":`${t} articles are`} written here and ${t===1?"has":"have"} never been saved to Document360`,u(` Your readers cannot see ${t===1?"it":"them"} at all yet \u2014 not even as a draft.`)];for(let o of e.neverPushed.slice(0,In))n.push(` ${Me(o)}`);return t>In&&n.push(u(` \u2026and ${t-In} more`)),n.push(u(" /push --all saves them as drafts; /publish then takes them live.")),n}function Kk(e){let t=e.unadopted.length;if(t===0)return[];let n=[` ${V("\u25CB",Ue.gray)}${t===1?"One page here came from Document360 and nothing has adopted it":`${t} pages here came from Document360 and nothing has adopted them`}`,u(` Not in your docs plan, not written by d360-writer, and nothing records what ${t===1?"it says":"they say"}.`),u(` So no editor can check ${t===1?"it":"them"}: a review pass over ${t===1?"it":"them"} comes back having changed nothing.`)];for(let o of e.unadopted.slice(0,In))n.push(` /untrack ${o.path}`);return t>In&&n.push(u(` \u2026and ${t-In} more`)),n.push(u(" Disowning one leaves Document360 untouched \u2014 the page, its history and its comments all stay.")),n}function zk(e){let t=e.orphans.length;return[u(` ${t} article${t===1?"":"s"} on Document360 ${t===1?"is":"are"} not in your docs folder (${Me(e.orphans[0].path,40)}${t>1?`, +${t-1} more`:""}) \u2014 /doctor lists ${t===1?"it":"them"}.`)]}function Xk(e){let t=Date.now()-Date.parse(e);if(!Number.isFinite(t)||t<0)return"just now";let n=Math.floor(t/6e4);if(n<2)return"just now";if(n<60)return`${n} minutes ago`;let o=Math.floor(n/60);if(o<24)return`${o} hour${o===1?"":"s"} ago`;let r=Math.floor(o/24);return`${r} day${r===1?"":"s"} ago`}function k1(e){let t=e.coverage;if(!t)return e.tracked===0?[]:["",u(" Nothing has compared this repo with Document360 yet."),"",u(" /pull --status counts what is there.")];if(t.unmapped===0)return[u(` Every Document360 article is tracked here (${t.mappedArticles} of ${t.portalArticles}, checked ${Xk(t.at)}).`),...Qk(t)];let n=t.portalOnlyCategories.filter(r=>r.articles>0).length,o=["",H(` ${V("\u26A0",Ue.yellow)}Document360 holds ${t.portalArticles} articles in ${t.portalCategories} categories.`),"",u(` This repo tracks ${t.mappedArticles} of them.`)];return n>0&&(o.push(""),o.push(u(` ${t.unmapped} articles sit in ${n} ${n===1?"category":"categories"} with no folder here.`))),t.declined>0&&(o.push(""),o.push(u(` ${t.declined} more ${t.declined===1?"is one you":"are ones you"} declined with /untrack.`))),o.push(""),o.push(u(` /pull imports them. Checked ${Xk(t.at)}.`)),o.push(...Qk(t)),o}function Qk(e){let t=g1(e);if(t===null||t===0)return[];let n=e.dangling?.articles??[],o=e.dangling?.categories??[],r=["",H(` ${V("\u26A0",Ue.yellow)}${n.length>0?`${n.length} ${n.length===1?"article":"articles"} here point`:""}${n.length>0&&o.length>0?" \u2014 and ":""}${o.length>0?`${o.length} ${o.length===1?"folder points":"folders point"}`:""} at something Document360 no longer has.`)];r.push("");for(let s of n.slice(0,5))r.push(u(` ${s}`));return n.length>5&&r.push(u(` \u2026and ${n.length-5} more.`)),r.push(""),r.push(u(" Someone deleted them on the portal, or they were replaced by newer articles.")),r.push(""),r.push(u(" /push saves them again for your readers. /untrack drops the ones you no longer want.")),r}async function Jk(e,t){let n=e.some(o=>o==="--all"||o==="--full");for(let o of Vh(t.cwd,{profileName:t.profileName,all:n}))console.log(o);return{kind:"continue",ownNext:!0}}ae();import{computeReadiness as $1,retireArticle as v1,retiredPaths as x1,normalizeScope as R1}from"document360-engine";import{select as S1}from"@inquirer/prompts";function Yh(e,t){let n=$1(e,t),o=x1(e,t),r=[Z("Take an article off your readers"),""];if(n.orphans.length>0){r.push(` ${V("\u25CB",u)}On Document360, but not in your docs folder \u2014 the usual reason to retire:`);for(let s of n.orphans.slice(0,8))r.push(u(` ${Me(s.path)}`));n.orphans.length>8&&r.push(u(` \u2026and ${n.orphans.length-8} more`)),r.push("")}if(o.length>0){r.push(` ${V("\u2713",u)}Already retired \u2014 readers do not see ${o.length===1?"it":"these"}:`);for(let s of o.slice(0,5))r.push(u(` ${Me(s)}`));o.length>5&&r.push(u(` \u2026and ${o.length-5} more`)),r.push("")}return n.orphans.length===0&&o.length===0&&(r.push(u(" Nothing obvious to retire \u2014 every tracked article is still in your docs folder.")),r.push("")),r.push(u(" /retire <path> takes one off your readers. Any tracked article can be named, not just these.")),r.push(u(" Nothing is deleted: the article, its history and every reviewer comment stay on Document360.")),r.push(u(" /push puts one back \u2014 reviving is a publish like any other, with the same review.")),r}async function Zk(e,t){let n=t.cwd,o=e.find(a=>!a.startsWith("-"));if(!o){for(let a of Yh(n,t.profileName))console.log(a);return{kind:"continue",ownNext:!0}}let r=R1(n,o)||o;if(!(e.includes("--yes")||e.includes("-y"))&&(console.log(""),console.log(H(`This takes "${Me(r)}" off your readers on Document360.`)),console.log(u(" The article, its history and every reviewer comment stay \u2014 nothing is deleted.")),console.log(u(" /push puts it back later if you change your mind.")),console.log(""),await S1({message:"Take it off your readers?",choices:[{name:"No \u2014 leave it as it is",value:"no"},{name:"Yes \u2014 readers stop seeing it",value:"yes"}]})!=="yes"))return console.log(u("Nothing changed.")),{kind:"continue",ownNext:!0};let i=await v1({cwd:n,path:r,profileName:t.profileName,now:new Date().toISOString()});return i.ok?(console.log(i.alreadyHidden?`${V("\u2713")}"${Me(r)}" was already invisible to readers. Recorded as retired, so nothing will offer to publish it again.`:`${V("\u2713")}"${Me(r)}" is no longer visible to your readers.`),console.log(u(" It is still on Document360 with its history and comments intact. /push puts it back.")),{kind:"continue",ownNext:!0}):(console.log(L(`${V("\u2717")}Could not retire "${Me(r)}" \u2014 ${i.error.message}`)),{kind:"continue",ownNext:!0})}ae();import{declineImport as C1,loadDeclinedImports as P1,undoDecline as T1,normalizeScope as A1,resolveActiveProfile as E1}from"document360-engine";import{select as N1}from"@inquirer/prompts";function Kh(e,t){let n={};try{n=P1(e,E1(e,t).name)}catch{}let o=Object.keys(n),r=[Z("Pages on Document360 that are not part of these docs"),""];if(o.length===0)r.push(u(" Nothing is declined. Every article on Document360 in one of your categories is")),r.push(u(" imported into your docs folder when you run /catch-up or /pull."));else{for(let s of o.slice(0,10)){let i=n[s];r.push(` ${V("\u25CB",u)}${i.title??i.path??s}`),i.path&&r.push(u(` was ${Me(i.path)}`)),i.keptAt&&r.push(u(` kept at ${i.keptAt}`))}o.length>10&&r.push(u(` \u2026and ${o.length-10} more`))}return r.push(""),r.push(u(" /untrack <path> disowns an imported page \u2014 nothing on Document360 changes.")),r.push(u(" /untrack --undo <path> puts it back and lets the next /catch-up import it again.")),r}async function e$(e,t){let n=t.cwd,o=e.find(c=>!c.startsWith("-")),r=e.includes("--list")||e.includes("-l"),s=e.includes("--undo");if(r||!o&&!s){for(let c of Kh(n,t.profileName))console.log(c);return{kind:"continue",ownNext:!0}}if(!o)return console.log(L(`${V("\u2717")}Name what to put back: /untrack --undo <path>`)),{kind:"continue",ownNext:!0};let i=A1(n,o)||o;if(s){let c=T1(n,t.profileName,i);return c.ok?(console.log(c.restoredTo?`${V("\u2713")}Put "${Me(c.restoredTo)}" back in your docs folder.`:`${V("\u2713")}No longer declined. /catch-up imports it again on the next run.`),{kind:"continue",ownNext:!0}):(console.log(L(`${V("\u2717")}${c.error.message}`)),{kind:"continue",ownNext:!0})}if(!(e.includes("--yes")||e.includes("-y"))&&(console.log(""),console.log(H(`This stops tracking "${Me(i)}" as one of your docs.`)),console.log(u(" Nothing on Document360 changes \u2014 the page, its history and its comments all stay,")),console.log(u(" and your readers see no difference.")),console.log(u(" The markdown moves to .d360-writer/declined/, so nothing is deleted.")),console.log(u(" /untrack --undo puts it back if you change your mind.")),console.log(""),await N1({message:"Stop tracking it?",choices:[{name:"No \u2014 leave it as it is",value:"no"},{name:"Yes \u2014 it is not one of my docs",value:"yes"}]})!=="yes"))return console.log(u("Nothing changed.")),{kind:"continue",ownNext:!0};let l=C1({cwd:n,path:i,profileName:t.profileName,now:new Date().toISOString()});return l.ok?(console.log(`${V("\u2713")}"${l.title??Me(l.path)}" is no longer one of your docs.`),l.keptAt&&console.log(u(` The markdown is kept at ${l.keptAt} \u2014 nothing was deleted.`)),console.log(u(" It is untouched on Document360. /catch-up will not import it again.")),{kind:"continue",ownNext:!0}):(console.log(L(`${V("\u2717")}Could not untrack "${Me(i)}" \u2014 ${l.error.message}`)),{kind:"continue",ownNext:!0})}ae();import{scanTerminology as t$,approvalBlockedReason as n$,readProjectConfig as D1,writeProjectConfig as j1,termKey as zh,HEAD_NOUN_CAP as I1}from"document360-engine";import sn from"picocolors";var L1=3,O1=e=>e.uses.map(t=>`${sn.bold(t.form)} ${u(`${t.files.length} article${t.files.length===1?"":"s"}`)}`).join(u(" \xB7 "));function Xh(e,t={}){let n=t$(e,t.scope?{scope:t.scope}:{}),o=[];if(n.scanned===0)return[Z("Terminology"),"",`${V("\u25CB",u)}No articles to read yet.`,""];let r=n.variance.length+n.headings.length;if(o.push(Z("Terminology")+u(` ${n.scanned} article${n.scanned===1?"":"s"} read \xB7 ${r===0?"nothing inconsistent":`${r} to look at`}`)),o.push(""),n.variance.length>0){o.push(` ${V("\u2717",sn.red)}The same term, spelled more than one way`);for(let s of n.variance){o.push(` ${O1(s)}`);let i=s.uses[s.uses.length-1],a=i.files.slice(0,L1);o.push(u(` "${i.form}" is in ${a.map(c=>Me(c,40)).join(", ")}${i.files.length>a.length?`, +${i.files.length-a.length} more`:""}`));let l=n$(s);l?o.push(u(` ${l}`)):o.push(u(` /terms --approve "${s.uses[0].form}" makes that the approved spelling`))}o.push("")}if(n.headNouns.length>0){let s=t.all?n.headNouns:n.headNouns.slice(0,I1);o.push(` ${V("\u25CB",u)}Possibly the same thing under a short name \u2014 ${sn.italic("your call")}`);for(let i of s)o.push(u(` ${i.uses.map(a=>a.form).join(" \xB7 ")}`));n.headNouns.length>s.length&&o.push(u(` \u2026and ${n.headNouns.length-s.length} more \u2014 /terms --all lists them`)),o.push(u(' A shared word is not proof of a shared meaning: "billing history" and "history" are')),o.push(u(" different things. Nothing is flagged as wrong here.")),o.push("")}if(n.headings.length>0){o.push(` ${V("\u26A0",sn.yellow)}Titles out of step with the rest of their kind`);for(let s of n.headings)o.push(` ${sn.bold(s.title)} ${u(`\u2014 ${Me(s.path,40)}`)}`),o.push(u(` the other ${s.peers} ${s.type} article${s.peers===1?"":"s"} look like "${s.example}"; this one starts ${M1(s.shape)}`));o.push("")}return r===0&&n.headNouns.length===0&&(o.push(` ${V("\u2713",sn.green)}Every term is spelled one way, and every title matches its kind.`),o.push("")),o.push(u(' This compares spellings, not meanings: two different words for one thing (say "nav" and')),o.push(u(' "rail") look unrelated to it. Add the pair to your approved terms and every run enforces it.')),o.push(u(" Free \u2014 this read your articles and called nothing.")),o}function M1(e){return e==="gerund"?"with an -ing word":e==="how-to"?'with "How to"':"differently"}function Qh(e,t,n){let o=n??t$(e),r=zh(t),s=o.variance.find(y=>y.uses.some(x=>zh(x.form)===r));if(!s)return{wrote:!1,lines:[`${V("\u2717",sn.red)}"${t}" is not one of the terms with competing spellings. /terms lists them.`]};let i=n$(s);if(i)return{wrote:!1,lines:[`${V("\u2717",sn.red)}That one cannot be recorded: ${i}.`,u(` The spellings in play are ${s.uses.map(y=>`"${y.form}"`).join(" and ")}.`)]};let a=s.uses.find(y=>zh(y.form)===r).form,l=s.uses.filter(y=>y.form!==a).map(y=>y.form),c=D1(e);if(!c)return{wrote:!1,lines:[`${V("\u2717",sn.red)}No project configuration here \u2014 run /init first.`]};let h={...c.terminologyGlossary??{}};for(let y of l)h[y]=a;return j1({...c,terminologyGlossary:h},e),{wrote:!0,lines:[`${V("\u2713",sn.green)}"${a}" is now the approved spelling.`,u(` Added to your approved terms: ${l.map(y=>`"${y}" \u2192 "${a}"`).join(", ")}`),u(" Every run enforces it from now on, and /lint --fix corrects the others for free.")]}}async function o$(e,t){let n=e.findIndex(s=>s==="--approve");if(n!==-1){let s=e[n+1];if(!s)return console.log(`${V("\u2717",sn.red)}Name the spelling to approve, e.g. /terms --approve "drop-down".`),{kind:"continue",ownNext:!0};for(let i of Qh(t.cwd,s.replace(/^["']|["']$/g,"")).lines)console.log(i);return{kind:"continue",ownNext:!0}}let o=e.includes("--all"),r=e.find(s=>!s.startsWith("--"));for(let s of Xh(t.cwd,{...r?{scope:r}:{},all:o}))console.log(s);return{kind:"continue",ownNext:!0}}ae();import{evaluateCorpus as _1,buildRegistry as U1,lintArticles as F1,scanTerminology as W1,BUILTIN_RULES as B1,surfaceCoverageSafe as H1,readProjectConfig as G1}from"document360-engine";import Pt from"picocolors";var bt=3,et=(e,t)=>`${e} ${t}${e===1?"":"s"}`,r$=e=>`${Me(e.path)}:${e.line}`,Jh=e=>e.split("/").pop()?.split("\\").pop()??e;function Zh(e,t,n,o,r,s,i){if(r.length===0)return;e.push(` ${V(t,n)}${o}`);let a=i?r:r.slice(0,bt);for(let l of a)e.push(u(` ${r$(l)} ${l.detail}`));r.length>a.length&&e.push(u(` \u2026and ${r.length-a.length} more \u2014 /eval --all`)),e.push(u(` ${s}`)),e.push("")}function ef(e,t={}){let n=U1(e),o=new Set([...B1.map(h=>h.id),...n.rules.map(h=>h.id)]),r=_1(e,o,{...t.scope?{scope:t.scope}:{},...t.profile?{profile:t.profile}:{}}),s=t.all===!0,i=[];if(r.articles===0)return[Z("Knowledge-base score"),"",`${V("\u25CB",u)}No articles to read yet.`,""];let a=H1(e,G1(e)),l=r.links.absolute.length+r.links.deadTargets.length+r.links.deadAnchors.length+r.links.staleLabels.length+r.sources.missing.length+r.shapes.typeTemplates.filter(h=>h.deviations.length>0).length+(r.shapes.synopsisForms.length>1?1:0)+(a.recognised?a.areas.length:0);if(i.push(Z("Knowledge-base score")+u(` ${et(r.articles,"article")} read \xB7 ${l===0?"nothing to look at":`${l} to look at`}`)),i.push(""),Zh(i,"\u2717",Pt.red,"Links pointing at articles that do not exist",r.links.deadTargets,"The article was renamed or retired after the link was written. Point it at the one that replaced it.",s),r.links.deadTargets.length===0&&r.links.sidebarDeadTargets>0&&(i.push(u(` ${r.links.sidebarDeadTargets} dead link${r.links.sidebarDeadTargets===1?"":"s"} in a Related articles list \u2014 excluded, the portal rebuilds that list itself`)),i.push("")),Zh(i,"\u2717",Pt.red,"Internal links written as portal URLs",r.links.absolute,"These break the day the site moves. Write them as relative .md links instead.",s),Zh(i,"\u2717",Pt.red,"Links pointing at headings that do not exist",r.links.deadAnchors,"The heading was renamed after the link was written. Point it at the current heading.",s),r.links.staleLabels.length>0){let h=r.links.staleLabels.reduce((y,x)=>y+x.sites.length,0);i.push(` ${V("\u26A0",Pt.yellow)}${et(r.links.staleLabels.length,"link label")} name an article something it is not called${h>r.links.staleLabels.length?u(`, in ${et(h,"place")}`):""}`);for(let y of s?r.links.staleLabels:r.links.staleLabels.slice(0,bt))if(i.push(u(` "${y.label}" \u2192 the article is titled "${y.title}"${y.sites.length>1?` (${y.sites.length}\xD7)`:""}`)),s)for(let x of y.sites)i.push(u(` ${r$(x)}`));!s&&r.links.staleLabels.length>bt&&i.push(u(` \u2026and ${r.links.staleLabels.length-bt} more \u2014 /eval --all`)),i.push(u(" A reader clicks expecting one page and lands on another name.")),i.push("")}if(s&&r.links.shortenedLabels.length>0){i.push(` ${V("\u25CB",u)}${et(r.links.shortenedLabels.length,"link label")} shorten the title they point at`);for(let h of r.links.shortenedLabels.slice(0,10))i.push(u(` "${h.label}" \u2192 "${h.title}"`));i.push(u(" Usually fine. Listed separately because it is a judgment call, not a defect.")),i.push("")}if(s&&r.links.sidebarLabelMismatch>0&&(i.push(` ${V("\u25CB",u)}${et(r.links.sidebarLabelMismatch,"Related-articles link")} not counted above`),i.push(u(" Those labels are dropped when the article is saved. Document360 builds that list from")),i.push(u(" the real titles, so a reader never sees the label written here.")),i.push("")),r.shapes.synopsisForms.length>1){i.push(` ${V("\u26A0",Pt.yellow)}The command summary line appears in ${et(r.shapes.synopsisForms.length,"shape")}`);for(let h of r.shapes.synopsisForms)i.push(u(` ${String(h.count).padStart(3)} ${h.form.padEnd(14)} ${h.examples.map(Jh).join(", ")}`));r.shapes.noSynopsis.length>0&&i.push(u(` ${et(r.shapes.noSynopsis.length,"article")} carry none at all`)),i.push(u(" Same information, different labels. Pick one and use it everywhere.")),i.push("")}for(let h of r.shapes.typeTemplates)if(h.deviations.length!==0){i.push(` ${V("\u26A0",Pt.yellow)}${h.deviations.length} of ${et(h.articles,`${h.type} article`)} skip a section the rest of them carry`),i.push(u(` Most ${h.type} articles have: ${h.expected.map(y=>`## ${y.heading} (${y.count})`).join(" \xB7 ")}`));for(let y of s?h.deviations:h.deviations.slice(0,bt))i.push(u(` ${Jh(y.path)} \u2014 missing ${y.missing.map(x=>`## ${x}`).join(", ")}`));!s&&h.deviations.length>bt&&i.push(u(` \u2026and ${h.deviations.length-bt} more \u2014 /eval --all`)),i.push(u(" A deviation may be deliberate. This counts them; it does not say the template is right.")),i.push("")}try{let h=W1(e,t.scope?{scope:t.scope}:{});if(h.variance.length>0){i.push(` ${V("\u26A0",Pt.yellow)}${et(h.variance.length,"term")} spelled more than one way across the set`);for(let y of h.variance.slice(0,s?99:bt))i.push(u(` ${y.uses.map(x=>`"${x.form}" \xD7${x.count}`).join(" \xB7 ")}`));h.headNouns.length>0&&i.push(u(` ${et(h.headNouns.length,"short name")} may be a longer one abbreviated \u2014 /terms lists them`)),i.push(u(' Settle one and every later run enforces it: /terms --approve "<term>"')),i.push("")}}catch{}let c=0;try{let y=F1({cwd:e,...t.scope?{scope:t.scope}:{}}).findings.filter(w=>!w.baselined);c=y.filter(w=>w.ruleId==="Document360.Changelog").length;let x=y.filter(w=>w.severity==="error").length;if(i.push(` ${V(x>0?"\u2717":y.length>0?"\u26A0":"\u2713",x>0?Pt.red:y.length>0?Pt.yellow:Pt.green)}`+(y.length===0?"Style rules: nothing reported":`Style rules: ${et(y.length,"finding")}${x>0?`, ${x} blocking publish`:", none blocking publish"}`)),y.length>0){let w=new Map;for(let S of y)w.set(S.ruleId,(w.get(S.ruleId)??0)+1);for(let[S,P]of[...w.entries()].sort((T,R)=>R[1]-T[1]).slice(0,s?99:5))i.push(u(` ${String(P).padStart(4)} ${S}`));i.push(u(" Fix what can be fixed mechanically: /lint --fix"))}i.push("")}catch{}if(r.debt&&r.debt.total>0){let h=r.debt.liveRules.reduce((w,S)=>w+S.count,0),y=r.debt.inertRules.reduce((w,S)=>w+S.count,0),x=r.debt.createdAt.slice(0,10);if(h>0){i.push(` ${V("\u2139",u)}${et(h,"style finding")} accepted as exempt on ${x}, from rules that are still on`);for(let w of r.debt.liveRules.slice(0,s?99:4))i.push(u(` ${String(w.count).padStart(4)} ${w.rule}`));i.push(u(" Nothing reports these, so the articles read as compliant. They are exempt, not compliant.")),i.push(u(" Work them down with /review --all --fix, then /lint --all --fix."))}else y>0&&(i.push(` ${V("\u25CB",u)}${et(y,"finding")} accepted on ${x} under a style guide no longer in use`),i.push(u(" They match no active rule, so they suppress nothing. Only weight in the file.")));i.push("")}if(r.sources.missing.length>0){i.push(` ${V("\u26A0",Pt.yellow)}${et(r.sources.missing.length,"article")} cite a file that is not in the repository`);for(let h of s?r.sources.missing:r.sources.missing.slice(0,bt))i.push(u(` ${h.source}${u(" \u2190 ")}${h.path}`));!s&&r.sources.missing.length>bt&&i.push(u(` \u2026and ${r.sources.missing.length-bt} more \u2014 /eval --all`)),i.push(u(" Renamed or deleted since the article was written. /audit points it at the file that replaced it.")),i.push("")}if(a.recognised&&a.areas.length>0){i.push(` ${V("\u26A0",Pt.yellow)}${et(a.areas.length,"part")} of the product no article says it documents`);for(let h of a.areas.slice(0,s?99:5))i.push(u(` ${String(h.files).padStart(4)} ${h.folder}`));!s&&a.areas.length>5&&i.push(u(` \u2026and ${a.areas.length-5} more \u2014 /eval --all lists them.`)),i.push(u(` ${a.documented} of ${a.filesScanned} source files are cited by an article.`)),a.declined>0&&i.push(u(` ${a.declined} you declined, left out of that count.`)),i.push(u(" /audit proposes the articles. /audit --decline <path> settles a folder or file for good.")),i.push("")}else a.recognised||(i.push(` ${V("\u25CB",u)}Product coverage was not measured`),i.push(u(` ${a.reason}`)),i.push(""));if(i.push(` ${V("\u25CB",u)}Length: ${r.length.words.toLocaleString()} words, median ${r.length.median.toLocaleString()} an article`),r.length.longest.length>0){i.push(u(` ${et(r.length.longest.length,"article")} past 2,500 words:`));for(let h of s?r.length.longest:r.length.longest.slice(0,bt))i.push(u(` ${h.words.toLocaleString()} ${Jh(h.path)}`));!s&&r.length.longest.length>bt&&i.push(u(` \u2026and ${r.length.longest.length-bt} more \u2014 /eval --all`))}return c>0&&(i.push(u(` ${et(c,"sentence")} tell the reader what the product used to do.`)),i.push(u(" Those are the longest sentences in a corpus, and the cheapest words to take out."))),i.push(u(" No previous measurement to compare against, so this is a reading, not a trend.")),i.push(""),l===0&&(r.debt?.total??0)===0&&(i.push(` ${V("\u2713",Pt.green)}Links resolve, one template shape, one name per thing.`),i.push("")),i.push(u(` Free \u2014 this read your ${et(r.articles,"article")} and called nothing.`)),i}async function s$(e,t){let n=e.includes("--all"),o=e.find(r=>!r.startsWith("--"));for(let r of ef(t.cwd,{...o?{scope:o}:{},...t.profileName?{profile:t.profileName}:{},all:n}))console.log(r);return{kind:"continue",ownNext:!0}}import{fetchPortalReuse as lj,readReuseCache as cj,writeReuseCache as uj,resolveActiveProfile as of,resolveProjectId as rf,createVariable as u$,createSnippet as d$,reuseNameProblem as dj,variableRule as pj,VARIABLE_MAX_CHARS as l$}from"document360-engine";ae();import{scanReuse as i$,scanValueCandidates as a$,buildReuseAuditPrompt as q1,reuseAuditProposalPath as V1,readReuseProposal as Y1,readReuseCache as K1,listArticleFiles as z1,normalizeScope as X1,docsRootOf as Q1,variableRule as J1}from"document360-engine";import{rmSync as Z1}from"node:fs";import ej from"picocolors";var Jl=6,tj=20;function nj(e,t){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}\u2026`:n}function oj(e,t=52){let n=e.replace(/\s+/g," ").trim(),o=[],r="";for(let s of n.split(" "))r===""?r=s:`${r} ${s}`.length<=t?r+=` ${s}`:(o.push(r),r=s);return r!==""&&o.push(r),o}function Zl(e,t,n,o){let r=[Z("Content reuse audit"),""];return r.push(`${e} article${e===1?"":"s"} read${u(" \xB7 free to look")}`,""),r.push(` ${String(n).padStart(3)} value${n===1?"":"s"} written out by hand in more than one article`),r.push(` ${String(t).padStart(3)} block${t===1?"":"s"} written more than once, in different words`),o>0&&r.push(u(` ${o} more families were left out of this pass \u2014 the longest ones are shown first.`)),r}function ec(e,t){let n=Q1(e),o=t.filter(x=>x!=="audit"&&!x.startsWith("--")).find(x=>x!==void 0),r=o?X1(n,o.replace(/\\/g,"/").replace(/\/+$/,"")):void 0,s=z1(e,r).length;if(s===0)return{lines:[oe("\u25CB",r?`No articles under ${r} to audit.`:"No articles to audit yet."),u(" Reuse is about text that repeats, so there has to be some text first.")]};let i=i$(e,{...r?{scope:r}:{},groups:!0}),a=a$(e,r?{scope:r}:void 0),l=i.groups??[],c=a.candidates;if(l.length===0&&c.length===0)return{lines:[oe("\u2713",`Nothing repeats across ${s} article${s===1?"":"s"} \u2014 there is nothing to keep in one place.`),u(" That is a good answer, not an empty one. Run this again after a few more articles.")]};let h=K1(e),y=V1(e);try{Z1(y,{force:!0})}catch{}return{prompt:q1({cwd:e,families:l,values:c,snippets:h?.snippets??[],variables:h?.variables??[],terms:h?.terms??[],proposalPath:y,articles:s}),display:r?`/reuse audit ${r}`:"/reuse audit",articles:s,families:l.length,values:c.length}}function rj(e,t){let n=[],o=` ${String(t).padStart(2)} ${e.kind.padEnd(9)}${ej.bold(e.name.padEnd(tj))}`,r=e.kind==="variable"?[`"${nj(e.value,52)}"`]:oj(`"${e.value}"`);n.push(`${o}${r[0]??""}`);for(let a of r.slice(1))n.push(`${" ".repeat(o.length-10)}${a}`);let s=e.uses>0?`${e.uses} use${e.uses===1?"":"s"} across ${e.files} article${e.files===1?"":"s"}`:"",i=e.why?s?` \u2014 ${e.why}`:e.why:"";return(s||i)&&n.push(u(` ${s}${i}`)),n}function sj(e,t,n){let o=[],r=e.proposals.length;if(o.push(r===0?oe("\u2713",`An editor read ${t} famil${t===1?"y":"ies"} and ${n} value${n===1?"":"s"}. None of it has to stay identical everywhere.`):oe("\u2713",`An editor read ${t} famil${t===1?"y":"ies"} and ${n} value${n===1?"":"s"}. ${r} ${r===1?"is":"are"} worth keeping in one place.`),""),e.proposals.forEach((s,i)=>{o.push(...rj(s,i+1),"")}),e.rejected.length>0){o.push(" Not proposed, and why:");for(let s of e.rejected.slice(0,Jl))o.push(u(` \xB7 ${s.what} \u2014 ${s.why}`));e.rejected.length>Jl&&o.push(u(` \xB7 \u2026and ${e.rejected.length-Jl} more.`)),o.push("")}if(e.dropped.length>0){o.push(oe("\u26A0",`${e.dropped.length} proposal${e.dropped.length===1?"":"s"} could not be used:`));for(let s of e.dropped.slice(0,Jl))o.push(u(` \xB7 ${s}`));o.push("")}return o}function ij(){return[u(" Nothing to create. The knowledge base repeats itself, but not in ways that have to stay"),u(" identical everywhere \u2014 which is the answer an editor is for."),""]}function tc(e,t){let n=[],o=t.created.map(a=>a.name);o.length>0&&(n.push(oe("\u2713",`Created ${o.length} on Document360: ${o.join(", ")}.`)),n.push(u(" Your local copy is in step and the agent has been restarted, so it writes with them from now on.")));for(let a of t.failed)n.push(oe("\u2717",`Document360 refused "${a.name}" \u2014 ${a.why}`));t.failed.length>0&&n.push(u(" Nothing else was changed. A name already in use is the usual cause; /reuse lists what exists."));let r=t.created.some(a=>a.kind==="variable"),s=t.created.filter(a=>a.kind==="snippet"),i=null;if(r){let a=J1(e).rule!==null;n.push(""),n.push(a?oe("\u2139","Those values are still typed out by hand across your articles."):oe("\u2139","Those values are created, but nothing checks them yet.")),a&&(n.push(u(" /lint --all --fix swaps every one of them \u2014 it costs no agent time, and nothing else in")),n.push(u(" your articles changes.")),i="/lint --all --fix")}return s.length>0&&(n.push(""),n.push(oe("\u2139",`${s.length===1?"The snippet exists":`The ${s.length} snippets exist`} on Document360, but no article references ${s.length===1?"it":"them"} yet.`)),n.push(u(` Ask me to use ${s.length===1?"it":"them"} in an article, or run /review --all --fix and the editor will replace the`)),n.push(u(" passages it finds. Replacing a passage changes the words a reader sees, so it goes through")),n.push(u(" an editorial read rather than a mechanical swap.")),i||(i="/review --all --fix")),i&&n.push("",i,""),{lines:n,cta:i}}function nc(e,t){let n=e.indexOf("--create");if(n===-1)return{picks:[],bad:[]};let o=e.slice(n+1).filter(i=>!i.startsWith("--"));if(o.length===1&&(o[0]==="a"||o[0]==="all"))return{picks:Array.from({length:t},(i,a)=>a),bad:[]};let r=[],s=[];for(let i of o){let a=Number(i);if(!Number.isInteger(a)||a<1||a>t){s.push(i);continue}r.includes(a-1)||r.push(a-1)}return{picks:r,bad:s}}function aj(e){if(e===0)return[];let t=Array.from({length:e},(n,o)=>o+1).join(" ");return[u(` Pick what to create. Run the line below for all ${e}, or edit the numbers to take some.`),"",`/reuse audit --create ${t}`,""]}function oc(){return[oe("\u2717","There is no reuse proposal to create from."),u(" Run /reuse audit first \u2014 it reads your articles and works out what belongs in one place."),"","/reuse audit",""]}function rc(e,t){let n=Y1(e);if(!n)return[oe("\u26A0","The editor did not leave a proposal, so there is nothing to create."),u(" Nothing was changed. This is usually a turn that stopped early \u2014 running it again is safe,"),u(" and the scan it starts from costs nothing."),"",t?`/reuse audit ${t}`:"/reuse audit",""];let o=i$(e,{...t?{scope:t}:{},groups:!0}),r=a$(e,t?{scope:t}:void 0),s=sj(n,(o.groups??[]).length,r.candidates.length);return s.push(...n.proposals.length===0?ij():aj(n.proposals.length)),s}ae();import{readReuseProposal as hj}from"document360-engine";import ts from"picocolors";var tf=8,Ln=6,nf=14,fj=52;function mj(e){if(!e)return"";let t=new Date(e);return Number.isNaN(t.getTime())?"":t.toLocaleDateString(void 0,{day:"numeric",month:"short"})}function c$(e,t=fj){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}\u2026`:n}function sf(e){let t=cj(e),n=[Z("Reusable content"),""];if(!t||t.terms.length===0&&t.snippets.length===0&&t.variables.length===0)return n.push(`${V("\u25CB",u)}Nothing pulled from Document360 yet.`,"",u(" A variable holds a value like your product name in one place, so changing it changes every"),u(" article at once. A snippet does the same for a whole block, like who to contact when"),u(" something goes wrong. A term is defined once and explained everywhere it first appears."),"","/reuse pull",""),n;let o=mj(t.pulledAt);if(t.terms.length===0)n.push(`${V("\u25CB",u)}No glossary terms in this Document360 project${o?u(` (checked ${o})`):""}.`);else{n.push(`${t.terms.length} term${t.terms.length===1?"":"s"} from Document360${o?u(`, pulled ${o}`):""}.`,"");for(let r of t.terms.slice(0,tf)){let s=" ".repeat(Math.max(1,nf-r.term.length));n.push(` ${ts.bold(r.term)}${s}${u(r.definition||"(no definition)")}`)}t.terms.length>tf&&n.push(u(` \u2026and ${t.terms.length-tf} more.`))}if(t.variables.length>0){n.push("",`${t.variables.length} value${t.variables.length===1?"":"s"} kept in one place.`,"");for(let s of t.variables.slice(0,Ln)){let i=" ".repeat(Math.max(1,nf-s.name.length));n.push(` ${ts.bold(s.name)}${i}${u(s.value?`"${c$(s.value)}"`:"(no value recorded)")}`)}t.variables.length>Ln&&n.push(u(` \u2026and ${t.variables.length-Ln} more.`));let{skipped:r}=pj(e);if(r.length>0){let s=t.variables.length-r.length;n.push("",u(` ${s} of ${t.variables.length} are checked in your articles. ${r.length===1?"This one is":"These are"} not:`));for(let i of r.slice(0,Ln))n.push(u(` ${i.name} \u2014 ${i.why}.`));r.length>Ln&&n.push(u(` \u2026and ${r.length-Ln} more.`))}}if(t.snippets.length>0){n.push("",`${t.snippets.length} maintained block${t.snippets.length===1?"":"s"}.`,"");for(let r of t.snippets.slice(0,Ln)){let s=" ".repeat(Math.max(1,nf-r.name.length)),i=r.usedBy>0?u(` (in ${r.usedBy} article${r.usedBy===1?"":"s"})`):"";n.push(` ${ts.bold(r.name)}${s}${u(r.description||c$(r.value??"")||"(no content recorded)")}${i}`)}t.snippets.length>Ln&&n.push(u(` \u2026and ${t.snippets.length-Ln} more.`))}return n.push("",u(" Terms are checked at first use in every article, a value you typed out by hand is flagged,"),u(" and the writer reuses your blocks by name instead of writing its own version of them."),"","/reuse pull","/lint --all",""),n}async function xi(e,t){let n,o;try{let c=of(e,t);n={profile:c.name,connection:c.connection,projectId:c.project.projectId,projectName:c.project.projectName},o=await rf(n,c.project?.projectId)}catch(c){return{lines:[oe("\u2717",`Not signed in to Document360: ${c instanceof Error?c.message:String(c)}`),u(" Run /login first.")],restart:!1}}let r;try{r=await lj(n,o)}catch(c){return{lines:[oe("\u26A0",`Document360 didn't return your reusable content \u2014 ${c instanceof Error?c.message:String(c)}.`),u(" Nothing is blocked. Everything else works exactly as it did; you just do not get the"),u(" first-use check on your terms, or the reuse checks, until this succeeds.")],restart:!1}}let s={pulledAt:new Date().toISOString(),profile:n.profile,projectId:o,terms:r.terms,snippets:r.snippets,variables:r.variables};if(uj(e,s),s.terms.length+s.snippets.length+s.variables.length===0)return{lines:[oe("\u2139","This Document360 project has no terms, snippets or variables yet."),u(" Someone with portal access adds them under Content tools. A good first one is your product"),u(" name as a variable: it is the string most likely to change, and the hardest to change late.")],restart:!1};let a=[`${s.terms.length} term${s.terms.length===1?"":"s"}`,`${s.snippets.length} snippet${s.snippets.length===1?"":"s"}`,`${s.variables.length} variable${s.variables.length===1?"":"s"}`],l=[oe("\u2713",`Pulled ${a.join(" \xB7 ")} from Document360.`)];return r.droppedTerms.length>0&&l.push(u(` ${r.droppedTerms.length} term${r.droppedTerms.length===1?" has":"s have"} no wording recorded in Document360, so ${r.droppedTerms.length===1?"it is":"they are"} not checked:`),u(` ${r.droppedTerms.slice(0,6).join(", ")}${r.droppedTerms.length>6?`, and ${r.droppedTerms.length-6} more`:""}.`)),r.contentlessBlocks.length>0&&l.push(u(` ${r.contentlessBlocks.length} block${r.contentlessBlocks.length===1?"":"s"} came back without content, so ${r.contentlessBlocks.length===1?"it is":"they are"} not matched against your articles:`),u(` ${r.contentlessBlocks.slice(0,6).join(", ")}${r.contentlessBlocks.length>6?`, and ${r.contentlessBlocks.length-6} more`:""}.`)),l.push("",u(" Your terms are now checked at first use in every article, a value you typed out by hand is"),u(" flagged, and the writer reuses your blocks by name instead of writing its own version."),"","/lint --all",""),{lines:l,restart:!0}}async function af(e,t,n,o,r){let s=dj(n);if(s)return{lines:[oe("\u2717",`That name will not work: ${s}.`),u(' Try something like "product-name".')],restart:!1};if(o.trim()==="")return{lines:[oe("\u2717","A value is required \u2014 that is the text this will stand for in your articles.")],restart:!1};if(t==="variable"&&o.length>l$)return{lines:[oe("\u2717",`A variable holds at most ${l$} characters and this is ${o.length}.`),u(' Longer text belongs in a snippet: /reuse add snippet <name> "<text>"')],restart:!1};let i,a;try{let l=of(e);i={profile:l.name,connection:l.connection,projectId:l.project.projectId,projectName:l.project.projectName},a=await rf(i,l.project?.projectId)}catch(l){return{lines:[oe("\u2717",`Not signed in to Document360: ${l instanceof Error?l.message:String(l)}`),u(" Run /login first.")],restart:!1}}try{let l=t==="variable"?await u$(i,a,{name:n,value:o}):await d$(i,a,{name:n,value:o,...r?{description:r}:{}}),c=await xi(e);return{lines:[oe("\u2713",`Created the ${t} "${l.name}" on Document360.`),u(` Write ${t==="variable"?`:variable[]{name="${l.name}"}`:`::snippet{name="${l.name}"}`} and Document360 puts your text there.`),"",...c.lines],restart:!0}}catch(l){let c=l instanceof Error?l.message:String(l);return{lines:[oe("\u2717",`Document360 refused to create that ${t} \u2014 ${c}`),u(" Nothing was changed. A name already in use is the usual cause; /reuse lists what exists.")],restart:!1}}}function p$(e){let t=e.trim();return t.length>=2&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))?t.slice(1,-1):t}function gj(e){let t=e.indexOf("--desc");if(t===-1)return{rest:e};let n=p$(e.slice(t+1).join(" "));return{rest:e.slice(0,t),...n?{description:n}:{}}}function lf(e){let{rest:t,description:n}=gj(e),o=t.filter(l=>!l.startsWith("--")),[,r,s,...i]=o;if(r!=="variable"&&r!=="snippet")return{error:'Say which one: /reuse add variable <name> "<value>", or /reuse add snippet <name> "<text>".'};if(!s)return{error:`Give it a name: /reuse add ${r} <name> "<value>".`};if(r==="variable"&&n)return{error:"Only a snippet takes --desc; a variable is just its value. Drop the flag, or add it as a snippet."};let a=p$(i.join(" "));return a===""?{error:`Give it a value: /reuse add ${r} ${s} "<the text it stands for>".`}:{kind:r,name:s,value:a,...n?{description:n}:{}}}async function h$(e,t){let n=e.find(o=>!o.startsWith("--"));if(n==="add"){let o=lf(e);if("error"in o)return console.log(`${V("\u2717",ts.red)}${o.error}`),{kind:"continue",ownNext:!0};let r=await af(t.cwd,o.kind,o.name,o.value,o.description);for(let s of r.lines)console.log(s);return r.restart?{kind:"clear"}:{kind:"continue",ownNext:!0}}if(n==="pull"){let o=await xi(t.cwd);for(let r of o.lines)console.log(r);for(let r of Ke(t.cwd,"/reuse pull"))console.log(r);return o.restart?{kind:"clear"}:{kind:"continue",ownNext:!0}}if(n==="audit"){if(e.includes("--create")){let r=hj(t.cwd);if(!r||r.proposals.length===0){for(let h of oc())console.log(h);return{kind:"continue",ownNext:!0}}let{picks:s,bad:i}=nc(e,r.proposals.length);for(let h of i)console.log(`${V("\u26A0",ts.yellow)}There is no proposal ${h} \u2014 the list has ${r.proposals.length}.`);if(s.length===0)return console.log(`${V("\u25CB",u)}Nothing picked, so nothing was created.`),{kind:"continue",ownNext:!0};let{outcome:a,pullLines:l}=await cf(t.cwd,s.map(h=>r.proposals[h]));for(let h of l)console.log(h);let{lines:c}=tc(t.cwd,a);for(let h of c)console.log(h);for(let h of Ke(t.cwd,"/reuse audit"))console.log(h);return a.created.length>0?{kind:"clear"}:{kind:"continue",ownNext:!0}}let o=ec(t.cwd,e);if("lines"in o){for(let r of o.lines)console.log(r);for(let r of Ke(t.cwd,"/reuse audit"))console.log(r);return{kind:"continue",ownNext:!0}}for(let r of Zl(o.articles,o.families,o.values,0))console.log(r);return{kind:"forward-to-agent",prompt:o.prompt,display:o.display}}if(n&&n!=="show")return console.log(`${V("\u2717",ts.red)}I don't know "/reuse ${n}". Use /reuse to see what this project maintains, /reuse pull to refresh it, /reuse audit to find what belongs in one place, or /reuse add variable <name> "<value>".`),{kind:"continue",ownNext:!0};for(let o of sf(t.cwd))console.log(o);return{kind:"continue",ownNext:!0}}async function cf(e,t){let n=[],o=[],r,s;try{let a=of(e);r={profile:a.name,connection:a.connection,projectId:a.project.projectId,projectName:a.project.projectName},s=await rf(r,a.project?.projectId)}catch(a){return{outcome:{created:[],failed:t.map(l=>({name:l.name,why:`not signed in to Document360: ${a instanceof Error?a.message:String(a)}`}))},pullLines:[u(" Run /login first.")]}}for(let a of t)try{a.kind==="variable"?await u$(r,s,{name:a.name,value:a.value}):await d$(r,s,{name:a.name,value:a.value,...a.description?{description:a.description}:{}}),n.push(a)}catch(l){o.push({name:a.name,why:l instanceof Error?l.message:String(l)})}if(n.length===0)return{outcome:{created:n,failed:o},pullLines:[]};let i=await xi(e);return{outcome:{created:n,failed:o},pullLines:i.restart?[]:i.lines}}ae();import{readProjectConfig as yj,writeProjectConfig as f$,isAppType as wj,playbookSkillName as bj,detectAppType as m$}from"document360-engine";var g$=["web","cli","service","library"],kj=new Set(["web","cli"]);function uf(e){return kj.has(e)?`${bj(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function sc(e,t){let n=t.cwd,o=yj(n);if(!o)return console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let s=o.appType??m$(n);if(s){let i=o.appType?"set in config":"auto-detected";console.log(`${Z("Genre:")} ${s} (${i}) \u2014 ${uf(s)}`)}else console.log(H("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(u(`Set it: /genre <${g$.join("|")}> \xB7 revert to auto-detect: /genre auto`)),{kind:"continue"}}if(r==="auto"||r==="clear"){if(!o.appType)return console.log(u("Already on auto-detect (no genre set in config).")),{kind:"continue"};let{appType:s,...i}=o;f$(i,n);let a=m$(n);return console.log(X(`\u2713 Genre reset to auto-detect \u2014 now: ${a?`${a} (${uf(a)})`:"unclassified (no playbook)"}.`)),console.log(u(" Restarting the agent so the loaded playbook matches\u2026")),{kind:"clear"}}return wj(r)?(f$({...o,appType:r},n),console.log(X(`\u2713 Genre set to ${r} \u2014 ${uf(r)}.`)),console.log(u(" Restarting the agent so the playbook loads\u2026")),{kind:"clear"}):(console.log(L(`Unknown genre "${r}". Choose one of: ${g$.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}var y$={help:Cu,"?":Cu,clear:gg,exit:Pu,quit:Pu,init:Iu,mcp:Aa,push:nl,publish:Zy,audit:(e,t)=>{let n=al(t.cwd,e);if(n){for(let o of n)console.log(o);return Promise.resolve({kind:"continue",ownNext:!0})}return Ks({cwd:t.cwd,profileName:t.profileName})},discover:sw,scope:aw,pull:$w,resolve:ww,convert:_w,write:Zw,draft:rb,document:sb,resume:lb,rename:cb,profile:ub,model:hb,doctor:ii,env:cg,logs:Zm,workspace:wb,project:bb,"allow-prod":kb,login:$b,logout:vb,screenshot:async(e,t)=>{let n=_s(e);return n.mode==="capture"?_p(n.rest,t):n.mode==="annotate"?Hp(n.rest,t):n.mode==="verify"?xb(n.rest,t):n.mode==="checklist"?Kr(e,t):Va(e,t)},capture:_p,annotate:Hp,"capture-setup":Kr,devhints:Cg,inbox:Bb,ask:Gb,"catch-up":Qb,comments:ok,update:ik,reset:dk,lint:sp,check:Gw,"style-guide":zl,review:Hk,reorder:qk,restructure:Vk,structure:Ak,status:Jk,retire:Zk,untrack:e$,terms:o$,eval:s$,reuse:h$,genre:sc,roadmap:Uy,share:Yb,auto:rw};function w$(e){let t=e.trim();if(!t.startsWith("/"))return null;let n=t.slice(1).split(/\s+/),o=(n[0]??"").toLowerCase();return o?{name:o,args:n.slice(1)}:null}import{spawnSync as $j}from"node:child_process";import{readProjectConfig as vj,recordAnalyzedCommit as xj,recordReportedAreas as Rj,resolveActiveProfile as Sj,surfaceCoverageSafe as Cj}from"document360-engine";function Pj(e){try{let t=$j("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8",timeout:1200}),n=(t.stdout||"").trim();return t.status===0&&n?n:null}catch{return null}}function Ri(e,t){try{let n=Sj(e,t),o=Cj(e,vj(e));o.recognised&&Rj(e,n.name,o.areas.map(s=>s.folder));let r=Pj(e);return r&&xj(e,n.name,r)?r:null}catch{return null}}Kn();var b$="Or just tell me what to write or update.";function $$(e,t=0){if(!(e>0))return null;let n=e===1?"the page":"those pages",o=`${e} note${se(e)} from your builder ${e===1?"is":"are"} waiting on code they haven't finished.`,r=t>=e?`I've asked whether ${e===1?"it's":"they're"} done, and I'll write ${n} once the code lands.`:`I'll write ${n} once the code lands, and /catch-up asks your builder whether ${e===1?"it's":"they're"} done.`;return`${o} ${r} Nothing else is blocked.`}function Tj(e,t,n={}){let o=n.onlyScreenshots?"\u2713 Your writing is done \u2014 nothing is waiting to be written, reviewed, saved or taken live. Readers are seeing every article you have.":"\u2713 That\u2019s the full round trip \u2014 nothing is waiting to be written, reviewed, saved or taken live. Readers are seeing every article you have.";return n.listed?o:`${o}
|
|
446
446
|
|
|
447
|
-
Optional from here: ${e} of your ${t} docs campaign step${se(t)} ${e===1?"is":"are"} still open (/roadmap shows them).`}function
|
|
448
|
-
\u2022 `),lead:{kind:"cmd",cmd:"/catch-up",reason:w},picker:null,follow:"Then /catch-up clears what\u2019s queued for the docs.",dependsOn:["discovery"]})}if(e.openComments>0){let w=e.openComments;n.push({key:"comments",bullet:`${w} reviewer comment${se(w)} waiting on your articles`,lead:{kind:"cmd",cmd:"/comments",reason:"it shows what reviewers marked up in the portal, then lets you take it an article at a time"},picker:null,follow:`Then /comments shows the ${w} reviewer comment${se(w)} waiting on your articles.`})}if(e.conflicts>0){let w=e.conflicts,S=w===1?"it":"these",P=e.unreadable===w,T=P?`${w} article${se(w)} ${w===1?"is":"are"} held on Document360 in a form I can't read back`:e.unreadable>0?`${w} article${se(w)} ${w===1?"is":"are"} waiting on your decision \u2014 changed both here and on Document360, or held there in a form I can't read back`:`${w} article${se(w)} changed both here and on Document360`;n.push({key:"resolve",bullet:`${T} \u2014 /push skips ${S}, and an audit can't trust your local copy until ${w===1?"it is":"they are"} settled`,lead:{kind:"cmd",cmd:"/resolve",reason:P?"it walks each one with you \u2014 publish your copy over the portal, or skip":"it walks each one with you \u2014 keep yours, take the portal's, or skip"},picker:null,follow:P?`Then /resolve settles the ${w} article${se(w)} Document360 won't hand back (publish yours over the portal / skip).`:`Then /resolve settles the ${w} article${se(w)} waiting on your decision (keep yours / take the portal's / skip).`})}let o=e.firstPublish,r=(()=>{if(!o||o.unpushed===0)return null;let w=o.unpushed,S=e.profileName?` on ${e.profileName}`:"";if(o.portalArticles===null)return{key:"firstPublish",bullet:`${w} article${se(w)} ${w===1?"is":"are"} written here, and this connection has never been compared with Document360`,lead:{kind:"cmd",cmd:"/pull --status",reason:"it asks Document360 what is already there. No tokens, and it changes nothing"},picker:null,follow:"Then /pull --status shows what this portal already holds."};if(o.twins===0){let P="/push --all",T=t?.scaleFor?.(P)??null;return{key:"firstPublish",bullet:w===o.total?`${w} article${se(w)} ${w===1?"is":"are"} written here and none of them are${S} yet \u2014 your readers see nothing`:`${w} of your ${o.total} article${se(o.total)} ${w===1?"has":"have"} not reached ${e.profileName} yet \u2014 the rest are saved as drafts`,lead:{kind:"cmd",cmd:P,reason:w===o.total?`it saves all ${w} to Document360 as draft${se(w)}`:`it retries the ${w} that did not land`,...T&&w===o.total?{detail:T}:{}},picker:null,follow:w===o.total?`Then ${P} saves all ${w} to Document360, and /publish takes them live.`:`Then ${P} retries the ${w} that did not land, and /publish takes them live.`,...T&&w===o.total?{detail:T}:{},dependsOn:["catchup","comments"],blockedBy:["review","styleguide"]}}return{key:"firstPublish",bullet:`${w} article${se(w)} ${w===1?"is":"are"} written here, and this portal holds ${o.twins} page${o.twins===1?"":"s"} nothing here tracks`,lead:null,picker:null,follow:"/pull --status compares them article by article, so nothing is pushed until you decide."}})(),s=r!==null&&e.unreviewed===0&&e.styleErrors===0,i=e.draftAhead,a=i>0?{key:"golive",bullet:`${i} article${se(i)} ${i===1?"is":"are"} saved on Document360 but not live \u2014 your readers still see the previous version`,lead:{kind:"cmd",cmd:"/publish",reason:`it takes the ${i} draft${se(i)} live to your readers \u2014 it lists them and asks first`},picker:null,follow:`Then /publish takes the ${i} draft${se(i)} live \u2014 until it does, readers see the previous version.`,dependsOn:["comments"],blockedBy:["review","styleguide"]}:null,l=e.localAhead===0&&(e.firstPublish?.unpushed??0)===0,c=a!==null&&l&&e.unreviewed===0&&e.styleErrors===0;if(a&&c&&n.push(a),r&&s&&n.push(r),e.portalUntracked>0){let w=e.portalUntracked,S=e.portalOnlyCategories;n.push({key:"coverage",bullet:`${w} article${se(w)} on Document360 ${w===1?"is":"are"} not in your docs folder \u2014 a plan or an audit built now would miss ${w===1?"it":"them"}`,lead:{kind:"cmd",cmd:"/pull",reason:S>0?`it imports ${w===1?"it":"them"} and creates the ${S} ${S===1?"folder":"folders"} they need`:`it imports ${w===1?"it":"them"} into your docs folder`},picker:null,follow:`Then /pull brings the ${w} Document360 article${se(w)} this repo is not tracking.`})}if(e.behind>0||e.undocumentedAreas>0){let w=e.behind,S=e.undocumentedAreas,P=w>0||e.unreportedAreas>0,T=e.declineTarget?`/audit --decline ${e.declineTarget}`:"/audit --decline",R=w>0&&S>0?`${w} code change${se(w)} since your last docs check, and ${S} part${se(S)} of the product no article covers`:w>0?`${w} code change${se(w)} since your last docs check`:P?`${S} part${se(S)} of the product no article covers`:`${S} part${se(S)} of the product no article covers \u2014 proposed already, still open. Settle one for good: ${T}`;n.push({key:"audit",bullet:R,lead:P?{kind:"cmd",cmd:"/audit",reason:w>0?"it shows what the latest code changes touch (or /audit --auto on to run it for you)":`it proposes the articles those parts need \u2014 or settle one with ${T}`}:null,picker:null,follow:P?w>0?`After that, /audit covers the ${w} newer commit${se(w)}.`:`After that, /audit proposes what the ${S} uncovered part${se(S)} need.`:null,blockedBy:["resolve"],dependsOn:["coverage"],opensRound:!0})}if(e.hasDocs&&e.pendingWrites>0){let w=e.pendingWrites;n.push({key:"write",bullet:`${w} planned article${se(w)} still unwritten`,lead:{kind:"cmd",cmd:"/write",reason:"it finishes the articles already planned"},picker:null,follow:`Then /write finishes the ${w} planned article${se(w)}.`,dependsOn:["genre","discovery","catchup","audit","coverage"]})}if(e.styleSweep){let w=e.styleSweep.pending,S=e.styleSweep.packs.length>0?e.styleSweep.packs.join(", "):"the built-in checks",P=e.styleSweep.scope?Ce("/review","--fix",e.styleSweep.scope):"/review --all --fix";n.push({key:"styleSweep",bullet:`your writing rules changed to ${S} \u2014 ${w<e.styleSweep.total?`${w} of ${e.styleSweep.total}`:`${w}`} article${se(w)} ${w===1?"has":"have"} not been read against them yet`,lead:{kind:"cmd",cmd:P,reason:"it reads each one against the new rules and rewrites it",detail:[t?.scaleFor?.(P),"/style-guide sweep skip stops me raising it."].filter(Boolean).map(T=>T.replace(/([^.!?…])$/,"$1.")).join(" ")},picker:null,follow:`Then ${P} reads the ${w} article${se(w)} the new rules have never been applied to.`,dependsOn:["catchup","comments","audit"]})}if(e.unreviewed>0){let w=e.unreviewed,S=Ce("/review","--blocked --fix",e.unreviewedScope);n.push({key:"review",bullet:`${w} article${se(w)} not yet live ${w===1?"carries":"carry"} text no editor has read`,lead:{kind:"cmd",cmd:S,reason:"these were written by an AI \u2014 it reads each one and applies its fixes, and nothing can be sent up or taken live until it has"},picker:null,follow:`Then ${S} reviews the ${w} unreviewed article${se(w)} \u2014 nothing reaches your readers until it has.`,dependsOn:["catchup","comments"]})}if(e.styleErrors>0){let w=e.styleErrors,S=Ce("/lint","--blocked --fix",e.styleErrorScope);n.push({key:"styleguide",bullet:`${w} article${se(w)} not yet live break${w===1?"s":""} house style rules that block publishing`,lead:{kind:"cmd",cmd:S,reason:"finding them costs nothing and one pass corrects them in place \u2014 nothing can be sent up or taken live until it has"},picker:null,follow:`Then ${S} clears the style errors on ${w} article${se(w)} \u2014 nothing reaches your readers until it has.`,dependsOn:["catchup","comments","review"]})}let h=e.draftBlockedShots??null,y=h&&h.articles>0?{key:"annotate",bullet:`${h.articles} article${se(h.articles)} ${h.articles===1?"is":"are"} saved on Document360 and cannot go live \u2014 ${h.places} picture${se(h.places)} ${h.places===1?"is":"are"} missing, so your readers would see "[Screenshot: \u2026]" on the page`,lead:h.cmd?{kind:"cmd",cmd:h.cmd,reason:Tj(h.stage,h.places)}:{kind:"prompt",text:`fix the ${h.places} bare "[Screenshot: \u2026]" line${se(h.places)} \u2014 either give each one a proper screenshot block or take the line out`,reason:"these lines belong to no screenshot, so no command can finish them"},picker:null,follow:h.cmd?`Then ${h.cmd} deals with the ${h.places} missing picture${se(h.places)}, and /push and /publish take the ${h.articles} article${se(h.articles)} live.`:`Then the ${h.places} bare "[Screenshot: \u2026]" line${se(h.places)} can be sorted out, and /push and /publish take the ${h.articles} article${se(h.articles)} live.`,...h.stage==="spec"||h.stage==="capture"?{opensRound:!0}:{}}:e.shotsToAnnotate>0?{key:"annotate",bullet:`${e.shotsToAnnotate} screenshot${se(e.shotsToAnnotate)} ${e.shotsToAnnotate===1?"has":"have"} been taken but ${e.shotsToAnnotate===1?"is":"are"} not finished \u2014 the callouts aren't drawn on, so ${e.shotsToAnnotate===1?"it cannot":"they cannot"} be published`,lead:{kind:"cmd",cmd:"/screenshot annotate",reason:"it draws the callouts on \u2014 no browser, about a second per picture"},picker:null,follow:`Then /screenshot annotate finishes the ${e.shotsToAnnotate} screenshot${se(e.shotsToAnnotate)} already taken.`}:e.shotsToRecapture>0?{key:"annotate",bullet:`${e.shotsToRecapture} screenshot${se(e.shotsToRecapture)} ${e.shotsToRecapture===1?"has":"have"} a plan for what to point at but no picture \u2014 the picture has to be taken again before anything can be drawn on it`,lead:{kind:"cmd",cmd:"/screenshot capture",reason:"it takes the picture again in a browser, and the callouts are drawn on straight after"},picker:null,follow:`Then /screenshot capture re-takes the ${e.shotsToRecapture} missing picture${se(e.shotsToRecapture)}.`,opensRound:!0}:null,x=y!==null&&h!==null&&h.articles>0;if(y&&!x&&e.localAhead>0&&n.push(y),r&&!s&&n.push(r),e.localAhead>0){let w=e.localAhead;n.push({key:"publish",bullet:`${w} article${se(w)} changed locally \u2014 ready to send to Document360`,lead:{kind:"cmd",cmd:"/push",reason:`it saves your ${w} local edit${se(w)} to Document360 as drafts`},picker:null,follow:`Then /push saves your ${w} local edit${se(w)} to Document360.`,dependsOn:["discovery","comments","audit","annotate"],blockedBy:["review","styleguide"]})}if(a&&!c&&n.push(a),y&&(x||e.localAhead===0)&&n.push(y),e.hasDocs&&e.roadmap?.next){let w=e.roadmap,S=w.next,P=S.run?t?.scaleFor?.(S.run)??null:null,T=S.run?P:g$(S.body),R=S.run?P??void 0:g$(S.body,340,2)??void 0,N=`docs campaign: ${w.done} of ${w.total} step${se(w.total)} done`,B=!!S.run&&Aj(S.run,e.lastCommand);n.push(B?{key:"roadmap",bullet:`${N} \u2014 \u201C${S.title}\u201D is waiting on you
|
|
449
|
-
\u2022 You just ran ${S.run}. It showed you where things stand; the step stays open until you act on what it showed, or close it with /roadmap done.`,lead:null,picker:null,follow:null}:{key:"roadmap",bullet:`${
|
|
450
|
-
\u2022 ${T}`:""}`,lead:S.run?{kind:"cmd",cmd:S.run,reason:"it\u2019s the next step of your docs campaign",...R?{detail:R}:{}}:{kind:"prompt",text:S.title,reason:"it\u2019s the next step of your docs campaign",...R?{detail:R}:{}},picker:null,follow:`Then the campaign continues: ${S.title} (/roadmap shows all ${w.total} steps).`,dependsOn:["genre","discovery","audit"],rowBullet:`${
|
|
447
|
+
Optional from here: ${e} of your ${t} docs campaign step${se(t)} ${e===1?"is":"are"} still open (/roadmap shows them).`}function Aj(e){let{heldDrafts:t,behind:n}=e,o=t>0?"every draft that was ready is live, and readers have it":"everything you have written is live, and readers are seeing it",r=[];return t>0&&r.push(`${t} article${se(t)} ${t===1?"is":"are"} still saved as a draft, waiting on a picture.`),n>0&&r.push(`${n} code change${se(n)} ${n===1?"has":"have"} landed since your last docs check.`),[`\u2713 That\u2019s this round done \u2014 ${o}.`,...r].join(" ")}var Ej="Still open, whenever you want it:";function Nj(e,t){let n=t?`Press 1\u2013${e} when you want one \u2014 nothing runs on its own.`:"Run one of the commands above when you want to.";return`Nothing is armed. ${e>0?`${n} `:""}Whatever you leave, I\u2019ll raise again next time you\u2019re in.`}var Dj="Screenshots are the only thing still open \u2014 a separate job, and none of it changes your text:",jj="Optional depth, when you want it:",Ij="Writing",Lj="Screenshots \u2014 a separate job from the writing";function Oj(e,t){let n=t?`Press 1\u2013${e} to fill one in \u2014 nothing runs on its own.`:"Run one of the commands above when you want to.";return`Nothing is waiting${e>0?", and none of the above is owed":""}. ${e>0?`${n} `:""}I\u2019ll pick up new hints from your builder, or code that moved, next time you\u2019re in.`}var Mj='\u{1F4ED} No docs yet for this repo. Tell me "write the docs for this repo" and I\u2019ll read the code and draft a structure \u2014 or /audit to see what the docs should cover.';function se(e){return e===1?"":"s"}function _j(e,t){let n=`${t} missing picture${se(t)}`;switch(e){case"spec":return`it writes the capture instructions for the ${n} \u2014 reading your code for the exact screens and buttons`;case"capture":return`it takes the ${n} in a browser and draws the callouts on straight after \u2014 your app needs to be running`;default:return`it draws the callouts on the ${n} already taken \u2014 no browser, about a second each`}}function Uj(e,t){if(!e||!t)return!1;let n=o=>o.trim().replace(/\s+/g," ").toLowerCase();return n(e)===n(t)}function ns(e,t=0){let n=t>=2?` \xB7 1\u2013${t} to pick another`:"";return e.kind==="cmd"?`\u21E5 tab to run ${e.cmd}${n} \xB7 or just ask me anything\u2026`:e.kind==="answer"&&e.options>=2?`1\u2013${e.options} to answer \xB7 or just ask me anything\u2026`:null}function v$(e,t){return e.length===t.length&&e.every((n,o)=>n===t[o])}function k$(e,t=150,n=1){let o=(e??"").replace(/\s+/g," ").trim();if(!o)return null;let r=/[.!?]\s+(?=["“'(A-Z])/g,s=o;for(let l=0;l<n;l++){let c=r.exec(o);if(!c)break;s=o.slice(0,c.index+1)}if(s.length<=t)return s;let i=s.slice(0,t),a=i.lastIndexOf(" ");return`${(a>t*.6?i.slice(0,a):i).replace(/[,;:]$/,"")}\u2026`}function os(e){if(e.kind==="answer")return e.options>=2?`Answer above (1\u2013${e.options}), or say what you want instead.`:"Answer above, or say what you want instead.";let t=e.detail?` ${e.detail.replace(/\s*$/,"").replace(/([^.!?…])$/,"$1.")}`:"";return e.kind==="cmd"?`I\u2019d start with ${e.cmd} \u2014 ${e.reason}.${t}`:`Just tell me: \u201C${e.text}\u201D \u2014 ${e.reason}.${t}`}var Zo="write the docs for this repo",ic={title:"What kind of product is this repo? (sets the doc-craft playbook \u2014 otherwise the docs stay generic)",lead:"Pick the genre below \u2014 one keypress, and it shapes everything I write.",exclusive:!0,options:[{cmd:"/genre web",desc:"web app / SaaS UI"},{cmd:"/genre cli",desc:"command-line tool"},{cmd:"/genre service",desc:"API / backend service"},{cmd:"/genre library",desc:"SDK / library"}]};function Fj(e,t){let n=[];if(e.sunsetEnv){let w=e.sunsetEnv,S=w.replacementProfile?`/profile ${w.replacementProfile}`:`/profile add ${w.replacement}`;n.push({key:"environment",bullet:`this repo publishes to the ${w.name} environment, which is being retired (${w.replacement} is the current one)`,lead:{kind:"cmd",cmd:S,reason:w.replacementProfile?`it switches to your ${w.replacement} profile (then /login if it asks)`:`it creates a ${w.replacement} profile and switches to it (then /login picks the project)`},picker:null,follow:null,tone:"warn"})}if(e.devhints!=="current"&&e.builderStarted){let w=e.devhintsToVersion?`v${e.devhintsToVersion}`:"a newer version",S=e.devhints==="stale"&&e.devhintsCompletedVersion?` (your builder is on v${e.devhintsCompletedVersion})`:"";n.push({key:"devhints",bullet:`dev\u2194docs protocol moved to ${w}${S} \u2014 your docs aren\u2019t blocked`,lead:{kind:"cmd",cmd:"/devhints",reason:`one paste updates your builder to ${w}`},picker:null,follow:"Also run /devhints when you get a second \u2014 your builder\u2019s protocol is behind.",tone:"warn"})}if(e.genreUnknown&&n.push({key:"genre",bullet:"the doc genre isn\u2019t set \u2014 I can\u2019t load the right doc-craft playbook yet",lead:null,picker:ic,follow:"Then pick the doc genre below (it sets the playbook I write with)."}),e.styleRules){let w=e.styleRules.articles;n.push({key:"styleRules",bullet:w>0?`the writing rules for these docs were never settled \u2014 and ${w} article${se(w)} ${w===1?"is":"are"} already written to them`:"the writing rules for these docs aren\u2019t settled yet \u2014 worth answering before I write anything",lead:null,picker:{title:w>0?`Which writing rules should these docs follow? (${w} article${se(w)} already written \u2014 changing this later means rewriting them)`:"Which writing rules should these docs follow? (this shapes every article I write)",lead:w>0?"Settle the writing rules below \u2014 one keypress. Keeping what you have is the usual answer once articles exist.":"Settle the writing rules below \u2014 one keypress, before I write anything to them.",exclusive:!0,options:e.styleRules.presets},follow:"Then settle the writing rules below \u2014 it shapes every article, and it gets dearer to change the longer it waits."})}if(e.styleUpgrade){let w=e.styleUpgrade,S=w.articles,P=w.from.length>0?w.from.join(", "):"the built-in checks only";n.push({key:"styleUpgrade",bullet:`you\u2019re on ${P} \u2014 several of its rules are wrong for software documentation, and the guide measured on real knowledge bases is ready`,lead:null,picker:{title:`Move these docs to the Document360 style guide? (you\u2019re on ${P})`,lead:S>0?`Pick below \u2014 one keypress. Switching is instant; I then run the free text swaps over your ${S} article${se(S)} and stop before the editorial pass.`:"Pick below \u2014 one keypress, before I write anything to it.",exclusive:!0,options:[{cmd:`/style-guide use ${w.to}`,desc:S>0?`switch, then bring your ${S} article${se(S)} up to it \u2014 ${w.rules} rules, none of which can block a publish`:`Microsoft style corrected for software docs \u2014 ${w.rules} rules, none of which can block a publish`},{cmd:"/style-guide keep",desc:`stay on ${P} \u2014 I won\u2019t ask again`}]},follow:"Then decide whether these docs move to the Document360 style guide \u2014 it gets dearer to change the longer it waits."})}if(e.autoChoice){let w=e.autoChoice.articles;n.push({key:"autoMode",bullet:w>0?`you haven\u2019t said whether I should run each step myself or wait for you \u2014 with ${w} article${se(w)} here, that is the difference between a night\u2019s work and an afternoon of key presses`:"you haven\u2019t said whether I should run each step myself or wait for you to press the key each time",lead:null,picker:{title:"Should I run each step myself, or wait for you?",lead:"Pick how I should work below \u2014 one keypress, and shift+tab changes it again whenever you like.",exclusive:!0,options:e.autoChoice.presets},follow:"Then say whether I should run each step myself or wait for you \u2014 shift+tab changes it later."})}if(e.discovery&&e.discovery.status!=="confident"){let w=e.discovery.openQuestions;e.discovery.status==="pending"?n.push({key:"discovery",bullet:"your existing docs aren\u2019t grounded in a product brief yet",lead:{kind:"cmd",cmd:"/discover",reason:"it interviews your builder and grounds the docs before you rewrite or publish them"},picker:null,follow:"Then /discover grounds your docs in a product brief (do this before the rewrite/push steps)."}):w>0?n.push({key:"discovery",bullet:`product discovery is waiting on ${w} answer${se(w)} from your builder \u2014 nudge them`,lead:null,picker:null,follow:"Discovery is waiting on your builder\u2019s answers \u2014 nudge them, then /catch-up folds the answers in once they reply."}):e.discovery.answersPending===0&&n.push({key:"discovery",bullet:"product discovery is ready to continue",lead:{kind:"cmd",cmd:"/discover",reason:"it continues interviewing your builder to ground the docs"},picker:null,follow:"Then /discover continues building the product brief."})}if(e.directives>0||e.pendingText){let w=e.directives>0&&e.pendingText?"it actions your directives and clears the builder\u2019s queue":e.directives>0?"it actions the directives you left":"it clears everything your builder queued",S=[];e.directives>0&&S.push(`${e.directives} owner directive${se(e.directives)} waiting`);let P=e.discovery&&e.discovery.status!=="confident"?e.discovery.answersPending:0,T=P>0?` (${P} settle${P===1?"s":""} the product brief)`:"";e.pendingText&&S.push(`your builder left ${e.pendingText}${T}`),n.push({key:"catchup",bullet:S.join(`
|
|
448
|
+
\u2022 `),lead:{kind:"cmd",cmd:"/catch-up",reason:w},picker:null,follow:"Then /catch-up clears what\u2019s queued for the docs.",dependsOn:["discovery"]})}if(e.openComments>0){let w=e.openComments;n.push({key:"comments",bullet:`${w} reviewer comment${se(w)} waiting on your articles`,lead:{kind:"cmd",cmd:"/comments",reason:"it shows what reviewers marked up in the portal, then lets you take it an article at a time"},picker:null,follow:`Then /comments shows the ${w} reviewer comment${se(w)} waiting on your articles.`})}if(e.conflicts>0){let w=e.conflicts,S=w===1?"it":"these",P=e.unreadable===w,T=P?`${w} article${se(w)} ${w===1?"is":"are"} held on Document360 in a form I can't read back`:e.unreadable>0?`${w} article${se(w)} ${w===1?"is":"are"} waiting on your decision \u2014 changed both here and on Document360, or held there in a form I can't read back`:`${w} article${se(w)} changed both here and on Document360`;n.push({key:"resolve",bullet:`${T} \u2014 /push skips ${S}, and an audit can't trust your local copy until ${w===1?"it is":"they are"} settled`,lead:{kind:"cmd",cmd:"/resolve",reason:P?"it walks each one with you \u2014 publish your copy over the portal, or skip":"it walks each one with you \u2014 keep yours, take the portal's, or skip"},picker:null,follow:P?`Then /resolve settles the ${w} article${se(w)} Document360 won't hand back (publish yours over the portal / skip).`:`Then /resolve settles the ${w} article${se(w)} waiting on your decision (keep yours / take the portal's / skip).`})}let o=e.firstPublish,r=(()=>{if(!o||o.unpushed===0)return null;let w=o.unpushed,S=e.profileName?` on ${e.profileName}`:"";if(o.portalArticles===null)return{key:"firstPublish",bullet:`${w} article${se(w)} ${w===1?"is":"are"} written here, and this connection has never been compared with Document360`,lead:{kind:"cmd",cmd:"/pull --status",reason:"it asks Document360 what is already there. No tokens, and it changes nothing"},picker:null,follow:"Then /pull --status shows what this portal already holds."};if(o.twins===0){let P="/push --all",T=t?.scaleFor?.(P)??null;return{key:"firstPublish",bullet:w===o.total?`${w} article${se(w)} ${w===1?"is":"are"} written here and none of them are${S} yet \u2014 your readers see nothing`:`${w} of your ${o.total} article${se(o.total)} ${w===1?"has":"have"} not reached ${e.profileName} yet \u2014 the rest are saved as drafts`,lead:{kind:"cmd",cmd:P,reason:w===o.total?`it saves all ${w} to Document360 as draft${se(w)}`:`it retries the ${w} that did not land`,...T&&w===o.total?{detail:T}:{}},picker:null,follow:w===o.total?`Then ${P} saves all ${w} to Document360, and /publish takes them live.`:`Then ${P} retries the ${w} that did not land, and /publish takes them live.`,...T&&w===o.total?{detail:T}:{},dependsOn:["catchup","comments"],blockedBy:["review","styleguide"]}}return{key:"firstPublish",bullet:`${w} article${se(w)} ${w===1?"is":"are"} written here, and this portal holds ${o.twins} page${o.twins===1?"":"s"} nothing here tracks`,lead:null,picker:null,follow:"/pull --status compares them article by article, so nothing is pushed until you decide."}})(),s=r!==null&&e.unreviewed===0&&e.styleErrors===0,i=e.draftAhead,a=i>0?{key:"golive",bullet:`${i} article${se(i)} ${i===1?"is":"are"} saved on Document360 but not live \u2014 your readers still see the previous version`,lead:{kind:"cmd",cmd:"/publish",reason:`it takes the ${i} draft${se(i)} live to your readers \u2014 it lists them and asks first`},picker:null,follow:`Then /publish takes the ${i} draft${se(i)} live \u2014 until it does, readers see the previous version.`,dependsOn:["comments"],blockedBy:["review","styleguide"]}:null,l=e.localAhead===0&&(e.firstPublish?.unpushed??0)===0,c=a!==null&&l&&e.unreviewed===0&&e.styleErrors===0;if(a&&c&&n.push(a),r&&s&&n.push(r),e.portalUntracked>0){let w=e.portalUntracked,S=e.portalOnlyCategories;n.push({key:"coverage",bullet:`${w} article${se(w)} on Document360 ${w===1?"is":"are"} not in your docs folder \u2014 a plan or an audit built now would miss ${w===1?"it":"them"}`,lead:{kind:"cmd",cmd:"/pull",reason:S>0?`it imports ${w===1?"it":"them"} and creates the ${S} ${S===1?"folder":"folders"} they need`:`it imports ${w===1?"it":"them"} into your docs folder`},picker:null,follow:`Then /pull brings the ${w} Document360 article${se(w)} this repo is not tracking.`})}if(e.behind>0||e.undocumentedAreas>0){let w=e.behind,S=e.undocumentedAreas,P=w>0||e.unreportedAreas>0,T=e.declineTarget?`/audit --decline ${e.declineTarget}`:"/audit --decline",R=w>0&&S>0?`${w} code change${se(w)} since your last docs check, and ${S} part${se(S)} of the product no article covers`:w>0?`${w} code change${se(w)} since your last docs check`:P?`${S} part${se(S)} of the product no article covers`:`${S} part${se(S)} of the product no article covers \u2014 proposed already, still open. Settle one for good: ${T}`;n.push({key:"audit",bullet:R,lead:P?{kind:"cmd",cmd:"/audit",reason:w>0?"it shows what the latest code changes touch (or /audit --auto on to run it for you)":`it proposes the articles those parts need \u2014 or settle one with ${T}`}:null,picker:null,follow:P?w>0?`After that, /audit covers the ${w} newer commit${se(w)}.`:`After that, /audit proposes what the ${S} uncovered part${se(S)} need.`:null,blockedBy:["resolve"],dependsOn:["coverage"],opensRound:!0})}if(e.hasDocs&&e.pendingWrites>0){let w=e.pendingWrites;n.push({key:"write",bullet:`${w} planned article${se(w)} still unwritten`,lead:{kind:"cmd",cmd:"/write",reason:"it finishes the articles already planned"},picker:null,follow:`Then /write finishes the ${w} planned article${se(w)}.`,dependsOn:["genre","discovery","catchup","audit","coverage"]})}if(e.styleSweep){let w=e.styleSweep.pending,S=e.styleSweep.packs.length>0?e.styleSweep.packs.join(", "):"the built-in checks",P=e.styleSweep.scope?Ce("/review","--fix",e.styleSweep.scope):"/review --all --fix";n.push({key:"styleSweep",bullet:`your writing rules changed to ${S} \u2014 ${w<e.styleSweep.total?`${w} of ${e.styleSweep.total}`:`${w}`} article${se(w)} ${w===1?"has":"have"} not been read against them yet`,lead:{kind:"cmd",cmd:P,reason:"it reads each one against the new rules and rewrites it",detail:[t?.scaleFor?.(P),"/style-guide sweep skip stops me raising it."].filter(Boolean).map(T=>T.replace(/([^.!?…])$/,"$1.")).join(" ")},picker:null,follow:`Then ${P} reads the ${w} article${se(w)} the new rules have never been applied to.`,dependsOn:["catchup","comments","audit"]})}if(e.unreviewed>0){let w=e.unreviewed,S=Ce("/review","--blocked --fix",e.unreviewedScope);n.push({key:"review",bullet:`${w} article${se(w)} not yet live ${w===1?"carries":"carry"} text no editor has read`,lead:{kind:"cmd",cmd:S,reason:"these were written by an AI \u2014 it reads each one and applies its fixes, and nothing can be sent up or taken live until it has"},picker:null,follow:`Then ${S} reviews the ${w} unreviewed article${se(w)} \u2014 nothing reaches your readers until it has.`,dependsOn:["catchup","comments"]})}if(e.styleErrors>0){let w=e.styleErrors,S=Ce("/lint","--blocked --fix",e.styleErrorScope);n.push({key:"styleguide",bullet:`${w} article${se(w)} not yet live break${w===1?"s":""} house style rules that block publishing`,lead:{kind:"cmd",cmd:S,reason:"finding them costs nothing and one pass corrects them in place \u2014 nothing can be sent up or taken live until it has"},picker:null,follow:`Then ${S} clears the style errors on ${w} article${se(w)} \u2014 nothing reaches your readers until it has.`,dependsOn:["catchup","comments","review"]})}let h=e.draftBlockedShots??null,y=h&&h.articles>0?{key:"annotate",bullet:`${h.articles} article${se(h.articles)} ${h.articles===1?"is":"are"} saved on Document360 and cannot go live \u2014 ${h.places} picture${se(h.places)} ${h.places===1?"is":"are"} missing, so your readers would see "[Screenshot: \u2026]" on the page`,lead:h.cmd?{kind:"cmd",cmd:h.cmd,reason:_j(h.stage,h.places)}:{kind:"prompt",text:`fix the ${h.places} bare "[Screenshot: \u2026]" line${se(h.places)} \u2014 either give each one a proper screenshot block or take the line out`,reason:"these lines belong to no screenshot, so no command can finish them"},picker:null,follow:h.cmd?`Then ${h.cmd} deals with the ${h.places} missing picture${se(h.places)}, and /push and /publish take the ${h.articles} article${se(h.articles)} live.`:`Then the ${h.places} bare "[Screenshot: \u2026]" line${se(h.places)} can be sorted out, and /push and /publish take the ${h.articles} article${se(h.articles)} live.`,...h.stage==="spec"||h.stage==="capture"?{opensRound:!0}:{}}:e.shotsToAnnotate>0?{key:"annotate",bullet:`${e.shotsToAnnotate} screenshot${se(e.shotsToAnnotate)} ${e.shotsToAnnotate===1?"has":"have"} been taken but ${e.shotsToAnnotate===1?"is":"are"} not finished \u2014 the callouts aren't drawn on, so ${e.shotsToAnnotate===1?"it cannot":"they cannot"} be published`,lead:{kind:"cmd",cmd:"/screenshot annotate",reason:"it draws the callouts on \u2014 no browser, about a second per picture"},picker:null,follow:`Then /screenshot annotate finishes the ${e.shotsToAnnotate} screenshot${se(e.shotsToAnnotate)} already taken.`}:e.shotsToRecapture>0?{key:"annotate",bullet:`${e.shotsToRecapture} screenshot${se(e.shotsToRecapture)} ${e.shotsToRecapture===1?"has":"have"} a plan for what to point at but no picture \u2014 the picture has to be taken again before anything can be drawn on it`,lead:{kind:"cmd",cmd:"/screenshot capture",reason:"it takes the picture again in a browser, and the callouts are drawn on straight after"},picker:null,follow:`Then /screenshot capture re-takes the ${e.shotsToRecapture} missing picture${se(e.shotsToRecapture)}.`,opensRound:!0}:null,x=y!==null&&h!==null&&h.articles>0;if(y&&!x&&e.localAhead>0&&n.push(y),r&&!s&&n.push(r),e.localAhead>0){let w=e.localAhead;n.push({key:"publish",bullet:`${w} article${se(w)} changed locally \u2014 ready to send to Document360`,lead:{kind:"cmd",cmd:"/push",reason:`it saves your ${w} local edit${se(w)} to Document360 as drafts`},picker:null,follow:`Then /push saves your ${w} local edit${se(w)} to Document360.`,dependsOn:["discovery","comments","audit","annotate"],blockedBy:["review","styleguide"]})}if(a&&!c&&n.push(a),y&&(x||e.localAhead===0)&&n.push(y),e.hasDocs&&e.roadmap?.next){let w=e.roadmap,S=w.next,P=S.run?t?.scaleFor?.(S.run)??null:null,T=S.run?P:k$(S.body),R=S.run?P??void 0:k$(S.body,340,2)??void 0,D=`docs campaign: ${w.done} of ${w.total} step${se(w.total)} done`,B=!!S.run&&Uj(S.run,e.lastCommand);n.push(B?{key:"roadmap",bullet:`${D} \u2014 \u201C${S.title}\u201D is waiting on you
|
|
449
|
+
\u2022 You just ran ${S.run}. It showed you where things stand; the step stays open until you act on what it showed, or close it with /roadmap done.`,lead:null,picker:null,follow:null}:{key:"roadmap",bullet:`${D} \u2014 next: ${S.title}${T?`
|
|
450
|
+
\u2022 ${T}`:""}`,lead:S.run?{kind:"cmd",cmd:S.run,reason:"it\u2019s the next step of your docs campaign",...R?{detail:R}:{}}:{kind:"prompt",text:S.title,reason:"it\u2019s the next step of your docs campaign",...R?{detail:R}:{}},picker:null,follow:`Then the campaign continues: ${S.title} (/roadmap shows all ${w.total} steps).`,dependsOn:["genre","discovery","audit"],rowBullet:`${D} \u2014 this is next${T?`
|
|
451
451
|
\u2022 ${T}`:""}`,opensRound:!0})}if(e.handoff){let w=Math.max(e.handoff.unpushed,e.handoff.uncommitted>0?1:0),S=e.handoff.unpushed;w>0&&e.handoff.pushConsent==="unconfirmed"?n.push({key:"share",bullet:e.shareExplained?"your docs work is saved on this machine only \u2014 your team can't see it yet":["your docs work is saved on this machine only \u2014 your team can't see it yet","d360-writer keeps everything it produces in .d360-writer/ \u2014 your articles, the map linking","them to Document360, and the channel your builder leaves hints and answers in. It saves that","to git for you automatically, but it won't send anything to your team until you say so."].join(`
|
|
452
|
-
`),lead:{kind:"cmd",cmd:"/share",reason:"it sends your saved work to your team and brings back your builder's latest; after this once, I keep doing it for you"},picker:null,follow:null}):S>0&&n.push({key:"share",bullet:`\u26A0 ${S} docs change set${se(S)} saved but not sent \u2014 someone else pushed to this branch first (your work is safe)`,lead:{kind:"cmd",cmd:"/share",reason:"it retries sending your saved work; if it keeps failing, your builder can merge the branch"},picker:null,follow:null})}else if(e.uncommittedDocs>0){let w=e.uncommittedDocs;n.push({key:"commit",bullet:`\u26A0 ${w} uncommitted change${se(w)} under .d360-writer/ \u2014 tell your coding agent: "commit d360-writer's work"`,lead:null,picker:null,follow:null})}return n}function
|
|
453
|
-
`):
|
|
454
|
-
`),{note:[...o?[o]:[],
|
|
452
|
+
`),lead:{kind:"cmd",cmd:"/share",reason:"it sends your saved work to your team and brings back your builder's latest; after this once, I keep doing it for you"},picker:null,follow:null}):S>0&&n.push({key:"share",bullet:`\u26A0 ${S} docs change set${se(S)} saved but not sent \u2014 someone else pushed to this branch first (your work is safe)`,lead:{kind:"cmd",cmd:"/share",reason:"it retries sending your saved work; if it keeps failing, your builder can merge the branch"},picker:null,follow:null})}else if(e.uncommittedDocs>0){let w=e.uncommittedDocs;n.push({key:"commit",bullet:`\u26A0 ${w} uncommitted change${se(w)} under .d360-writer/ \u2014 tell your coding agent: "commit d360-writer's work"`,lead:null,picker:null,follow:null})}return n}function x$(e){return e.find(t=>t.lead||t.picker)??null}function Wj(e){return e.kind==="cmd"?e.cmd:e.kind==="prompt"?`\u201C${e.text}\u201D`:""}function rs(e){return e.kind==="cmd"?e.cmd:e.kind==="prompt"?e.text:null}function Bj(e){return rs(e)??""}function Hj(e,t,n){let o=a=>(a??[]).map(l=>t.get(l)).filter(l=>l!==void 0&&l<n),r=a=>a.length===1?`${a[0]}`:`${a.slice(0,-1).join(", ")} and ${a[a.length-1]}`,s=o(e.blockedBy);if(s.length>0)return` (needs ${r(s)} first)`;let i=o(e.dependsOn);return i.length>0?` (better after ${r(i)})`:""}function Si(e,t,n,o=null,r,s=0,i=0,a=0,l=!1){if(r&&r.length>0){let D=r.filter(Ya),B=r.filter(te=>!Ya(te)),G=[...B,...D],Q=(te,he)=>` ${he+1}. ${te.title}${te.run?` \xB7 ${te.run}`:""}`,N;return D.length===0||B.length===0?N=[e,...G.map(Q)].join(`
|
|
453
|
+
`):N=[e,"",` ${Ij}`,...B.map((te,he)=>Q(te,he)),"",` ${Lj}`,...D.map((te,he)=>Q(te,B.length+he))].join(`
|
|
454
|
+
`),{note:[...o?[o]:[],N,Oj(G.length,n),b$].join(`
|
|
455
455
|
|
|
456
|
-
`),menu:G.map(te=>te.run??te.title)}}let c=l?null:
|
|
457
|
-
\u2022 `),
|
|
458
|
-
`)}let ne=
|
|
456
|
+
`),menu:G.map(te=>te.run??te.title)}}let c=l?null:x$(t),h=c?.picker?[]:t.filter(D=>D.lead),y=l||h.length>=2?h:[],x=new Map(y.map((D,B)=>[D.key,B+1])),w=[];c?.lead?w.push(os(c.lead)):c?.picker&&w.push(c.picker.lead);for(let D of t.filter(B=>B!==c&&!B.lead).slice(0,2))D.follow&&w.push(D.follow);l?w.push(Nj(y.length,n)):y.length>=2&&n&&w.push(`Press 1\u2013${y.length} to pick a different one \u2014 the number fills the box, enter runs it.`);let S=w.join(" "),P=t.filter(D=>D.bullet).map(D=>{let B=x.get(D.key),[G="",...Q]=(B&&D.lead?.kind==="prompt"&&D.rowBullet?D.rowBullet:D.bullet).split(`
|
|
457
|
+
\u2022 `),N=D===c&&D.lead?.kind!=="answer"&&D.lead?.detail?[]:Q;if(B&&D.lead){let he=G.replace(/^→\s+/,"");return[` ${B}. ${Wj(D.lead)} \u2014 ${he}${Hj(D,x,B)}`,...N.map(ye=>` ${ye}`)].join(`
|
|
458
|
+
`)}let ne=D.lead?.kind==="cmd"?D.lead.cmd:null;return` \u2022 ${[G,...N].join(`
|
|
459
459
|
\u2022 `)}${ne&&!S.includes(ne)?` \u2014 ${ne}`:""}`}),T=o?[o,[e,...P].join(`
|
|
460
460
|
`)]:[[e,...P].join(`
|
|
461
|
-
`)];if(w.length&&T.push(w.join(" ")),s>0){let
|
|
462
|
-
|
|
463
|
-
`),menu:y.map(
|
|
464
|
-
|
|
465
|
-
${R}`:R;if(!e.ready)return{kind:"idle"};if(e.pendingAnswer)return{kind:"recommend",rec:{note:null,settled:null,restKind:null,tone:"info",lead:e.pendingAnswer.options>=2?{kind:"answer",options:e.pendingAnswer.options,reason:"the agent is waiting on your pick"}:null,picker:null,menu:[],heldHints:e.heldHints}};let r=
|
|
466
|
-
|
|
467
|
-
${
|
|
468
|
-
`)){let o=n.trimEnd();if(/^\s*(```|~~~)/.test(o)){t=!t;continue}if(t)continue;let r=/^#\s+(\S.*)$/.exec(o);if(r)return
|
|
469
|
-
`)){if(n>t)break;let i=s.trimEnd();if(/^\s*(```|~~~)/.test(i))o=!o;else if(!o){let a=/^(#{2,6})\s+(\S.*)$/.exec(i);a&&(r=
|
|
470
|
-
`)){let n=t.replace(/^\s*(#{1,6}\s+|[-*+]\s+|>\s+|\d+[.)]\s+)/,"").replace(/^\s*\|/,"").trim();if(n)return
|
|
471
|
-
`).length;return{verb:"Draft",title:Q,category:l,note:`new, ${
|
|
472
|
-
`)),category:l,note:w,articleKey:s,...B?{repeat:B}:{}}}function
|
|
473
|
-
`);if(e==="Read"){let o=n.length,r=
|
|
474
|
-
`));return[`${o} line${o===1?"":"s"}${r?` \xB7 ${r}`:""}`]}if(e==="Glob"){if(/^no files found/i.test(t))return null;let o=n.filter(r=>r.trim()).length;return[`${o} file${o===1?"":"s"}`]}return e==="Grep"&&/^Found \d+/.test(n[0]??"")?[n[0]]:null}function
|
|
475
|
-
`).trimEnd();if(n&&
|
|
476
|
-
`);return{lines:s.slice(0,t).map(i=>
|
|
477
|
-
|
|
478
|
-
${Pe}`)}catch{}let
|
|
479
|
-
`))console.log(i(` ${a}`));s.rec.picker&&console.log(Z(` Pick one: ${s.rec.picker.options.map(a=>a.cmd).join(" \xB7 ")}`))}}catch{}}console.log(u(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}var
|
|
480
|
-
`))console.log(X(` ${r}`))}else o.rec.settled&&!o.rec.lead&&console.log(u(" Nothing is waiting. /roadmap lists the optional campaign steps."));o.rec.lead&&console.log(u(` Next: ${
|
|
481
|
-
|
|
482
|
-
`);let l=[i.category,i.note].filter(h=>!!h).map(h=>Ae(` \xB7 ${h}`)),c=i.loud?Ae(" \xB7 ")+
|
|
483
|
-
|
|
484
|
-
`),console.log(`${Ae("\u25CF")} ${a.title}${a.arg!==null?Ae(`${a.sep}(${a.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let i=
|
|
485
|
-
`);let i=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(u(` (${
|
|
486
|
-
`),n=0;for(let s=t.length-1;s>=0;s--){let i=t[s];if(/^\s{0,3}\d{1,2}[.)]\s+\S/.test(i)){n++;continue}if(!(n>0&&/^\s+\S/.test(i)))break}return n<2?0:t.filter(s=>/^\s{0,3}\d{1,2}[.)]\s+\S/.test(s)).slice(-n).every((s,i)=>Number(/^\s{0,3}(\d{1,2})/.exec(s)[1])===i+1)?n:0}var
|
|
487
|
-
`),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){
|
|
488
|
-
`)}var
|
|
489
|
-
`).filter(s=>/^\s{0,3}\d{1,2}[.)]\s+\S/.test(s)).slice(-n).map(s=>{let i=s.replace(/^\s{0,3}\d{1,2}[.)]\s+/,"").trim(),a=
|
|
490
|
-
`).map(o=>o.trim()).filter(o=>o.length>3),n=t[t.length-1];return n?n.length>160?`${n.slice(0,157)}\u2026`:n:null}function
|
|
491
|
-
`)}var
|
|
492
|
-
\u2190/\u2192 or tab switch \xB7 1-5 jump${S+P>0?" \xB7 \u2191\u2193 scroll":""} \xB7 esc close \xB7 d360-writer v${r} \xB7 engine v${s}`})]})}var
|
|
493
|
-
`)){let i=s.trim().replace(
|
|
494
|
-
`)}function
|
|
495
|
-
`)||e.length>200}function
|
|
496
|
-
`).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function
|
|
497
|
-
`)){if(s.length===0)o.push({start:r,end:r});else for(let i=0;i<s.length;i+=n)o.push({start:r+i,end:r+Math.min(i+n,s.length)});r+=s.length+1}return o.length>0?o:[{start:0,end:0}]}function
|
|
461
|
+
`)];if(w.length&&T.push(w.join(" ")),s>0){let D=s;T.push(`${D} question${se(D)} you asked your developers ${D===1?"is":"are"} still unanswered. Their reply arrives with your docs the next time either of you shares, and /inbox folds it in. Nothing is blocked meanwhile.`)}let R=$$(i,a);return R&&T.push(R),T.push(b$),{note:T.join(`
|
|
462
|
+
|
|
463
|
+
`),menu:y.map(D=>Bj(D.lead))}}function Ci(e,t){let n=t?.pickable===!0,o=R=>t?.header?`${t.header}
|
|
464
|
+
|
|
465
|
+
${R}`:R;if(!e.ready)return{kind:"idle"};if(e.pendingAnswer)return{kind:"recommend",rec:{note:null,settled:null,restKind:null,tone:"info",lead:e.pendingAnswer.options>=2?{kind:"answer",options:e.pendingAnswer.options,reason:"the agent is waiting on your pick"}:null,picker:null,menu:[],heldHints:e.heldHints}};let r=Fj(e,t),s=r.length===1&&r[0].key==="roadmap"&&!!r[0].lead&&!!e.roadmap&&!!e.roadmap.next,i=s?e.roadmap.open?.length?e.roadmap.open:[e.roadmap.next]:[],a=i.length>0&&i.every(Ya)&&e.roadmap.total-e.roadmap.done===i.length,l=s?Tj(e.roadmap.total-e.roadmap.done,e.roadmap.total,{listed:i.length>0,onlyScreenshots:a}):null,c=r.filter(R=>R.lead||R.picker),h=!s&&c.length>0&&c.every(R=>R.opensRound===!0),y=h?Aj({heldDrafts:e.draftBlockedShots?.articles??0,behind:e.behind}):l,x=s?"complete":h?"delivered":null;if(!e.hasDocs){let R=x$(r);if(R&&(R.lead?.kind==="cmd"||R.picker)){let D=Si(t?.header??"\u{1F4ED} No docs yet for this repo \u2014 here\u2019s where things stand:",r,n,null,void 0,e.outboundQuestions,e.heldHints,e.heldHintsAsked);return{kind:"recommend",rec:{note:D.note,settled:null,restKind:null,tone:R.tone??"info",lead:R.lead,picker:R.picker,menu:D.menu,heldHints:e.heldHints}}}return{kind:"recommend",rec:{note:o(Mj),settled:null,restKind:null,tone:"info",lead:{kind:"prompt",text:Zo,reason:"I\u2019ll read the code and draft a structure"},picker:null,menu:[],heldHints:e.heldHints}}}if(r.length===0){let R=e.roadmap&&!e.roadmap.next?` Docs campaign complete \u2014 all ${e.roadmap.total} step${se(e.roadmap.total)} done (/roadmap).`:"",D=$$(e.heldHints,e.heldHintsAsked);return{kind:"recommend",rec:{note:o(`Welcome back. Your ${e.tracked} tracked article${se(e.tracked)} for \u201C${e.profileName}\u201D are all in sync \u2014 /audit re-checks the code, /pull brings down portal edits.${R}`+(D?`
|
|
466
|
+
|
|
467
|
+
${D}`:"")),settled:null,restKind:null,tone:"info",lead:null,picker:null,menu:[],heldHints:e.heldHints}}}let w=c,S=w[0]??null;if(!S){let R=Si(t?.header??"Welcome back \u2014 where your docs stand:",r,n,null,void 0,e.outboundQuestions,e.heldHints,e.heldHintsAsked);return{kind:"recommend",rec:{note:R.note,settled:null,restKind:null,tone:"info",lead:null,picker:null,menu:R.menu,heldHints:e.heldHints}}}if((S.key==="audit"||w[1]?.key==="audit")&&e.behind>0&&e.autoAudit&&e.allowAutoAudit)return{kind:"autoAudit",note:o(`\u{1F4CB} ${e.behind} code change${se(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`)};if(s){let R=Si(a?Dj:jj,r,n,y,i,e.outboundQuestions,e.heldHints,e.heldHintsAsked);return{kind:"recommend",rec:{note:R.note,settled:y,restKind:x,tone:"info",lead:null,picker:null,menu:R.menu,heldHints:e.heldHints}}}if(h){let R=Si(Ej,r,n,y,void 0,e.outboundQuestions,e.heldHints,e.heldHintsAsked,!0);return{kind:"recommend",rec:{note:R.note,settled:y,restKind:x,tone:"info",lead:null,picker:null,menu:R.menu,heldHints:e.heldHints}}}let T=Si(t?.header??"Welcome back \u2014 where your docs stand:",r,n,y,void 0,e.outboundQuestions,e.heldHints,e.heldHintsAsked);return{kind:"recommend",rec:{note:T.note,settled:y,restKind:x,tone:S.tone??"info",lead:S.lead,picker:S.picker,menu:T.menu,heldHints:e.heldHints}}}qn();import{existsSync as ac,readdirSync as hf}from"node:fs";import{spawnSync as Gj}from"node:child_process";import{join as lc}from"node:path";import{readProjectConfig as pf,resolveActiveProfile as ff,loadTokens as qj,isExpired as Vj,loadProfileMap as T$,localAheadPaths as Yj,unpushedArticlePaths as A$,loadKnownConflicts as Kj,loadCoverage as zj,surfaceCoverageSafe as Xj,undocumentedAreaCount as Qj,declineTargets as Jj,listUnpullable as Zj,draftPendingPaths as eI,loadOpenCommentCount as tI,readDocsPlan as nI,devHintsGuidePath as oI,DEFAULT_DOCS_DIR as cc,roadmapProgress as rI,listRoadmap as R$,readProductBriefState as sI,readDiscoveryQueue as iI,reconcileCommitRequest as aI,reconcileTestidRequest as lI,snapshotHandoff as cI,shareExplainedPath as uI,unannotatedShotIds as dI,shotsNeedingRecapture as pI,resolveOutputDir as hI,DEFAULT_OUTPUT_DIR as fI,WRITER_DIRNAME as df,styleGuideSettled as mI,styleGuideUpgradeOffered as gI,styleSweepOutstanding as yI,styleSweepSeedNeeded as wI,recordStyleSwitch as bI,lintArticles as kI,DEFAULT_PACK as $I,autoModeSettled as vI,autoBudgetUsd as xI,listAvailablePacks as S$,listArticleFiles as Pi,placeholderFindings as RI,placeholderRemedy as SI}from"document360-engine";Kn();var C$=new Set,CI=5;function P$(e){try{return hf(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function mf(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>P$(lc(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&P$(lc(e,o)))}function gf(e,t){try{let n=pf(e);if(!n)return!1;let o=ff(e,t),r=T$(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=lc(e,(n.docsDir??cc).replace(/\/+$/,""));return!!(ac(s)&&hf(s).length>0||ac(oI(e)))}catch{return!1}}function E$(e,t){try{let n=ff(e,t);return A$(e,n.name).length>0?"unpushed":Pi(e).length>0?"tracked":"fresh"}catch{return"tracked"}}function PI(e){let t=[`:(exclude)${df}`],n=(e.docsDir??cc).replace(/\\/g,"/").replace(/\/+$/,"");return n&&!n.startsWith(`${df}/`)&&n!==df&&t.push(`:(exclude)${n}`),t}function TI(e,t){if(!e.recognised)return 0;if(!t||t.length===0)return e.areas.length;let n=new Set(t);return e.areas.filter(o=>!n.has(o.folder)).length}function AI(e){return!e.recognised||e.areas.length===0?null:Jj(e.areas[0])[0]??null}function EI(e,t,n){try{let o=Gj("git",["rev-list","--count",`${t}..HEAD`,"--",".",...PI(n)],{cwd:e,encoding:"utf8",timeout:1200});return o.status===0&&parseInt((o.stdout||"").trim(),10)||0}catch{return 0}}function Ti(e,t,n){try{let o=pf(e);if(!o)return null;let r=ff(e,t),s=qj(r.name,r.project.projectId),i=!!s&&(!Vj(s)||!!s.refreshToken),a=gf(e,t)||!mf(e,o.authoritativeSourceFiles),l=T$(e,r.name),c=l?Object.keys(l.articles).length:0,h=lc(e,(o.docsDir??cc).replace(/\/+$/,"")),y=!1;try{y=ac(h)&&hf(h).length>0}catch{}let x=l?.lastAnalyzedCommit?EI(e,l.lastAnalyzedCommit,o):0,w=0;try{let de=(o.docsDir??cc).replace(/\/+$/,""),De=nI(e,de);De.length>0&&(w=Jn(e,de,De.map(nt=>nt.path)).length)}catch{}let S=on(e),P=zr({...S,directives:0}),T=Yj(e,t),R=new Set(Kj(e,r.name)),D=new Set(Zj(e,r.name).map(de=>de.path)),B=zj(e,r.name),G=Xj(e,o),Q=T.filter(de=>R.has(de)||D.has(de)),N=Q.length,ne=T.length-N,te=new Set(T),he=eI(e,t).filter(de=>!te.has(de)),we=RI(e,he),ye=new Set(we.map(de=>de.path)),ke=he.filter(de=>!ye.has(de)).length,ee=null;try{ee=SI(e,we)}catch{}let Ee=[...T.filter(de=>!R.has(de)),...he],_e=Gs(e,Ee),Xe=_e.length,ho=Mt(_e),Pe=null;try{if(!mI(o.styleGuide)){let de=S$(e).filter(De=>De.name.toLowerCase()!=="humanise");Pe={articles:Pi(e).length,presets:[{cmd:"/style-guide keep",desc:"the built-in rules only \u2014 correctness and anti-slop checks (nothing changes)"},...de.map(De=>({cmd:`/style-guide use ${De.name.toLowerCase()}`,desc:`${De.name} style guide \u2014 ${De.rules.length} more rules`}))]}}}catch{}let Ne=null;try{if(gI(o.styleGuide)){let De=S$(e).find(nt=>nt.name.toLowerCase()===$I);De&&(Ne={to:De.name.toLowerCase(),rules:De.rules.length,from:(o.styleGuide?.packs??[]).map(nt=>nt.trim().toLowerCase()).filter(Boolean),articles:Pi(e).length})}}catch{}let tt=null;try{if(wI(e,o?.styleGuide?.packs,o?.styleGuide?.decidedAt)&&!C$.has(e)){C$.add(e);let De=kI({cwd:e}).findings;bI(e,{packs:o?.styleGuide?.packs??[],from:[],articlesWithFindings:[...new Set(De.map(nt=>nt.path))]})}let de=yI(e);de&&(tt={pending:de.pending,total:de.total,packs:de.packs,...Mt(de.paths)?{scope:Mt(de.paths)}:{}})}catch{}let an=null;try{vI(o)||(an={articles:Pi(e).length,presets:[{cmd:"/auto off",desc:"manual \u2014 I suggest the next step and wait for you to run it"},{cmd:"/auto on",desc:`auto \u2014 I run the next step myself, all the way to live (up to ${ze(xI(o))} a run)`}]})}catch{}let At=0,fo;try{let de=Qy(e,Ee);At=de.length,fo=Mt(de)}catch{}let mo=0,rr=0;try{let de=hI(e,pf(e)?.outputDir??fI);mo=dI(de).length,rr=pI(de).length}catch{}let Mi=tI(e,r.name),_i=en(e),qt=rI(e),Vt=qt?{...qt,open:R$(e).filter(de=>de.status==="open").slice(0,CI).map(de=>({title:de.title,...de.run?{run:de.run}:{},...de.stage?{stage:de.stage}:{}}))}:null,sr=cI(e,o),Mn=aI(e,new Date().toISOString(),{supersededByHandoff:sr!==null});lI(e,new Date().toISOString());let Yt=Hn(e,t),ir=Yt?{name:Yt.name,replacement:Yt.replacement,replacementProfile:Yt.replacementProfile}:null,mn=sI(e),_n=iI(e),ar=mn?{status:mn.status,openQuestions:_n.openQuestions,answersPending:_n.answersPending}:null;!ar&&y&&R$(e).some(De=>De.status==="open"&&(De.run??"").trim()==="/discover")&&(ar={status:"pending",openQuestions:0,answersPending:0});let Ui=null;if(r.project.projectId&&r.project.workspaceId)try{let de=A$(e,r.name).length;de>0&&(Ui={unpushed:de,total:Pi(e).length,portalArticles:B?B.portalArticles:null,twins:B?.unmapped??0})}catch{}return{ready:i&&a&&!n.claudeMissing,hasDocs:y,tracked:c,firstPublish:Ui,pendingText:P,directives:S.directives,behind:x,pendingWrites:w,localAhead:ne,unreviewed:Xe,unreviewedScope:ho,styleErrors:At,shotsToAnnotate:mo,shotsToRecapture:rr,styleErrorScope:fo,draftAhead:ke,draftBlockedShots:ee,conflicts:N,unreadable:Q.filter(de=>D.has(de)).length,portalUntracked:B?.unmapped??0,portalOnlyCategories:B?.portalOnlyCategories.filter(de=>de.articles>0).length??0,undocumentedAreas:Qj(G),unreportedAreas:TI(G,l?.lastReportedAreas),declineTarget:AI(G),openComments:Mi,outboundQuestions:pi(e),heldHints:S.held,heldHintsAsked:S.heldAsked,autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:_i.status,devhintsCompletedVersion:_i.completedVersion,devhintsToVersion:We,builderStarted:Pn(e),genreUnknown:n.genreUnknown,pendingAnswer:n.pendingAnswer??null,lastCommand:n.lastCommand??null,styleRules:Pe,styleUpgrade:Ne,styleSweep:tt,autoChoice:an,roadmap:Vt,discovery:ar,uncommittedDocs:Mn.dirty.length,handoff:sr,shareExplained:ac(uI(e)),sunsetEnv:ir}}catch{return null}}ae();import{existsSync as jI,readFileSync as II}from"node:fs";import{isAbsolute as LI,join as OI}from"node:path";import{DEFAULT_DOCS_DIR as MI,findPathByArticleId as _I,isArticleDocPath as UI,loadProfileMap as FI,readProjectConfig as WI,resolveActiveProfile as BI}from"document360-engine";function NI(){return process.platform==="win32"||process.platform==="darwin"}var DI=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function uc(e,t){let n=e.replace(/\\/g,"/"),o=`${DI(t)}/`,[r,s]=NI()?[n.toLowerCase(),o.toLowerCase()]:[n,o];return r.startsWith(s)?n.slice(o.length):null}var D$=70;function HI(e,t){return{docsRoot:()=>(WI(e)?.docsDir??MI).replace(/\\/g,"/").replace(/\/+$/,""),read:n=>{try{let o=LI(n)?n:OI(e,n);return jI(o)?II(o,"utf8"):null}catch{return null}},pathForArticleId:n=>{try{let o=FI(e,BI(e,t).name);return o?_I(o,n):null}catch{return null}}}}var er=(e,t=D$)=>{let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"};function Ai(e){if(!e)return null;let t=!1;for(let n of e.split(`
|
|
468
|
+
`)){let o=n.trimEnd();if(/^\s*(```|~~~)/.test(o)){t=!t;continue}if(t)continue;let r=/^#\s+(\S.*)$/.exec(o);if(r)return er(r[1])}return null}var GI=new Set(["a","an","and","as","at","but","by","for","in","of","on","or","the","to","vs","with"]),qI=new Set(["ai","api","cli","css","csv","dfm","faq","html","http","https","id","json","mcp","pdf","sdk","sso","ui","url","ux","yaml","ado","qa"]);function j$(e,t,n){let o=e.toLowerCase();return qI.has(o)?e.toUpperCase():!t&&GI.has(o)?o:!t&&!n?e:e.charAt(0).toUpperCase()+e.slice(1)}var I$=e=>e.replace(/^\d+[-_.]/,"").split(/[-_]/).filter(Boolean);function VI(e){let t=I$(e);return t.length===0?e:t.map((n,o)=>j$(n,o===0,!0)).join(" ")}function L$(e){let t=typeof e=="string"&&e?e.replace(/\\/g,"/"):null;if(!t)return null;let n=t.split("/").filter(Boolean);return n.length<2?null:VI(n[n.length-2])}function O$(e){let t=e.replace(/\\/g,"/").split("/").pop()??e,n=I$(t.replace(/\.(md|markdown)$/i,""));return n.length===0?t:n.map((o,r)=>j$(o,r===0,!1)).join(" ")}var YI=46;function KI(e,t){let n=0,o=!1,r=null;for(let s of e.split(`
|
|
469
|
+
`)){if(n>t)break;let i=s.trimEnd();if(/^\s*(```|~~~)/.test(i))o=!o;else if(!o){let a=/^(#{2,6})\s+(\S.*)$/.exec(i);a&&(r=er(a[2],D$))}n+=s.length+1}return r}function N$(e){for(let t of e.split(`
|
|
470
|
+
`)){let n=t.replace(/^\s*(#{1,6}\s+|[-*+]\s+|>\s+|\d+[.)]\s+)/,"").replace(/^\s*\|/,"").trim();if(n)return er(n,YI)}return null}var Ht=e=>typeof e=="string"&&e?e:null,zI=e=>typeof e=="string"&&e.length>=8?`id ${e.slice(0,8)}\u2026`:null;function XI(e,t){return uc(e,t)??e.replace(/\\/g,"/")}function QI(e,t){let n=Ft(e,t,200);return n?`+${n.added} \u2212${n.removed}`:"no change"}var JI=new Set(["Edit","MultiEdit","Write"]);function ZI(e,t,n,o){if(!JI.has(e))return null;let r=Ht(t.file_path);if(!r)return null;let s=XI(r,n),i=o.docsRoot();if(!(s===i||s.startsWith(`${i}/`)))return null;let a=s.slice(i.length+1);if(!a||!UI(a))return null;let l=L$(a),c=o.read(s),h=G=>Ai(G)??Ai(c)??O$(a);if(e==="Write"){let G=Ht(t.content)??"",Q=h(G);if(c===null){let N=G.replace(/\n$/,"").split(`
|
|
471
|
+
`).length;return{verb:"Draft",title:Q,category:l,note:`new, ${N} lines`,articleKey:s}}return{verb:"Rewrite",title:Q,category:l,note:QI(c,G),articleKey:s}}let y=Array.isArray(t.edits)?t.edits.map(G=>({from:Ht(G.old_string)??"",to:Ht(G.new_string)??""})):[{from:Ht(t.old_string)??"",to:Ht(t.new_string)??""}],x=y.reduce((G,Q)=>{let N=Ft(Q.from,Q.to,200);return N?{added:G.added+N.added,removed:G.removed+N.removed}:G},{added:0,removed:0}),w=x.added===0&&x.removed===0?"no change":`+${x.added} \u2212${x.removed}`,S=y[0],P=S&&c?KI(c,c.indexOf(S.from)):null,T=S?N$(S.to)??N$(S.from):null,R=y.length>1?` +${y.length-1} more`:"",D=T?`\u201C${T}\u201D${R}`:R.trim()||null,B=P?{title:`\u21B3 ${P}`,category:D,note:w}:D?{title:`\u21B3 ${D}`,category:null,note:w}:null;return{verb:"Update",title:h(y.map(G=>G.to).join(`
|
|
472
|
+
`)),category:l,note:w,articleKey:s,...B?{repeat:B}:{}}}function eL(e,t,n){let o=()=>{let r=Ht(t.article_id),s=r?n.pathForArticleId(r):null;return(s?Ai(n.read(s)):null)??(s?O$(s):zI(r)??"article")};switch(e){case"d360_create_article":{let r=Ht(t.title);return r?{verb:"Create",title:er(r),category:L$(t.local_path),note:"Document360 draft"}:null}case"d360_update_article":return{verb:"Update",title:Ht(t.title)?er(Ht(t.title)):o(),category:null,note:"Document360 draft"};case"d360_fork_article":return{verb:"Fork",title:o(),category:null,note:"new Document360 draft"};case"d360_publish_article":{let r=t.version_number;return{verb:"Publish",title:o(),category:null,note:typeof r=="number"?`v${r}`:null,loud:"LIVE"}}case"d360_unpublish_article":return{verb:"Unpublish",title:o(),category:null,note:"back to draft, removed from readers"};case"d360_create_category":{let r=Ht(t.name);return r?{verb:"Create",title:er(r),category:null,note:"Document360 category"}:null}case"d360_upload_drive_file":{let r=Ht(t.file_path);if(!r)return null;let s=r.replace(/\\/g,"/").split("/").pop()??r;return{verb:"Upload",title:er(s),category:null,note:"Document360 Drive",keepResult:!0}}default:return null}}function dc(e,t,n,o,r=HI(n,o)){try{let s="mcp__document360__";return e.startsWith(s)?eL(e.slice(s.length),t,r):ZI(e,t,n,r)}catch{return null}}var tL={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"},_$=160,yf=200,U$=40;function co(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:nL(n)?"\u2026"+n.slice(n.length-(t-1)):n.slice(0,t-1)+"\u2026"}function nL(e){return!e.includes(" ")&&/[/\\]/.test(e)}function M$(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}: ${co(typeof r=="string"?r:JSON.stringify(r),U$)}`);return t.length>4&&n.push("\u2026"),co(n.join(", "),_$)}var oL=new Set(["file_path","notebook_path"]);function rL(e,t){return t?uc(e.replace(/\\/g,"/").replace(/\/+$/,""),t)??e:e}var pc=e=>typeof e=="string"&&e?e:null;function sL(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});return e==="d360_sync_status"?n("Check sync status",null):null}function hc(e,t,n){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,s="",...i]=e.split("__"),a=i.join("__");if(s==="document360"){let h=sL(a,t);if(h)return h}let l=a.replace(/^d360_/,"").replace(/_/g," ");return{title:`${s==="document360"?"Document360":s.charAt(0).toUpperCase()+s.slice(1)}: ${l}`,sep:" ",arg:M$(t)}}let o=tL[e],r=o?t[o]:void 0;if(typeof r=="string"&&r){let s=o&&oL.has(o)?rL(r,n):r;return{title:e,sep:"",arg:co(s,_$)}}return{title:e,sep:"",arg:M$(t)}}function iL(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 aL(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(iL).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>co(r,yf))]}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}: ${co(String(r),U$)}`);return n.length>0?[co(n.join(" \xB7 "),yf)]:null}return null}function lL(e){let t=pc(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function cL(e,t,n){switch(e){case"d360_create_article":{let o=lL(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=pc(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 ${co(o[0],120)}`:""}`]}case"d360_create_variable":{let o=pc(t?.name);return[`\u2713 variable created${o?` \xB7 :variable[]{name="${o}"}`:""}`]}case"d360_create_snippet":{let o=pc(t?.name);return[`\u2713 snippet created${o?` \xB7 ::snippet{name="${o}"}`:""}`]}default:return null}}var F$=new Set(["Edit","Write","MultiEdit","NotebookEdit"]);function uL(e){return e.replace(/^\s*\d+\t/,"")}function dL(e,t){if(F$.has(e))return[];let n=t.split(`
|
|
473
|
+
`);if(e==="Read"){let o=n.length,r=Ai(n.map(uL).join(`
|
|
474
|
+
`));return[`${o} line${o===1?"":"s"}${r?` \xB7 ${r}`:""}`]}if(e==="Glob"){if(/^no files found/i.test(t))return null;let o=n.filter(r=>r.trim()).length;return[`${o} file${o===1?"":"s"}`]}return e==="Grep"&&/^Found \d+/.test(n[0]??"")?[n[0]]:null}function fc(e,t=4,n,o){let r=e.replace(/\r\n/g,`
|
|
475
|
+
`).trimEnd();if(n&&F$.has(n))return{lines:[],hidden:0};if(!r)return{lines:["(no output)"],hidden:0};if(n&&!n.startsWith("mcp__")){let i=dL(n,r);if(i)return{lines:i,hidden:0}}if(n?.startsWith("mcp__document360__")){let i=cL(n.slice(18),o,r);if(i)return{lines:i,hidden:0}}let s=aL(r)??r.split(`
|
|
476
|
+
`);return{lines:s.slice(0,t).map(i=>co(i,yf)),hidden:Math.max(0,s.length-t)}}function mc(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function gc(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 W$(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 yc(e){return W$(e,"url")}function wc(e){return W$(e,"preview_url")}function bc(e,t){try{let o=JSON.parse(t),s=(Array.isArray(o)?o[0]:o)?.title;if(typeof s=="string"&&s.trim())return s.trim()}catch{}if(typeof e.title=="string"&&e.title.trim())return e.title.trim();let n=e.local_path;return typeof n=="string"&&n.trim()?(n.replace(/\\/g,"/").split("/").pop()??n).replace(/\.(md|markdown)$/i,""):null}var z$=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/,bf=null;function q$(){return bf===null&&(bf=xL().verboseTranscript===!0),bf}function ML(e,t,n,o){if(z$.test(e))try{let r=K$(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,i=gc(t,n),a=bc(t,n),l=a?`${a} \u2014 `:"",c=yc(n);e.endsWith("publish_article")&&c&&console.log(Z(` \u2B95 ${l}Live: ${c}`));let h=wc(n);h?console.log(Z(` \u2B95 ${l}Preview: ${h}`)):i&&s&&console.log(Z(` \u2B95 ${l}Preview: ${mc(r.connection.portalUrl,s,i,r.project.languageCode??"en")}`))}catch{}}async function X$(e=process.cwd(),t="auto",n,o){let r=hL(t);r.kind==="none"&&(console.error(""),console.error(L("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${Z("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${Z('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${Z("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${Z("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),_L(e,n);let s=fL(t),i=mL(s);console.log(i?H(` ${B$(s)}`):u(` ${B$(s)}`)),i?console.log(u(` ${i}`)):r.kind==="subscription"&&!r.stored&&console.log(u(" No sign-in found on this machine \u2014 trying your Claude session anyway.")),console.log("");let a=!1,l=wf({cwd:e,profileName:n,allowProdWrites:a}),c={uuid:null,firstPrompt:null,titleFired:!1},h=pL({input:process.stdin,output:process.stdout}),y=[],x=null,w=!1;h.on("line",T=>{if(x){let R=x;x=null,R(T)}else y.push(T)}),h.on("close",()=>{if(w=!0,x){let T=x;x=null,T(null)}});function S(){return y.length>0?Promise.resolve(y.shift()):w?Promise.resolve(null):(process.stdout.write(Z("> ")),new Promise(T=>{x=T}))}let P={cwd:e,version:o,profileName:n,allowProdWrites:()=>a,restartAgent:()=>{l.close(),l=wf({cwd:e,profileName:n,allowProdWrites:a}),c={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>c.uuid,setPendingName:T=>{c.pendingName=T},setModel:async T=>l.setModel(T),withPausedInput:async T=>{h.pause();try{return await T()}finally{h.resume()}}};try{for(;;){let T=await S();if(T===null)break;let R=T.trim();if(R){if(R.startsWith("/")){let D=w$(R);if(!D)continue;let B=y$[D.name];if(!B){console.log(L(`Unknown command: /${D.name}`)),console.log(u("Type /help for the list."));continue}let G=await B(D.args,P);if(G.kind==="exit")break;if(G.kind==="clear"){P.restartAgent();continue}if(G.kind==="allow-prod"){a=!0,P.restartAgent(),console.log(X("\u2713 Production writes authorized for this session.")),console.log("");continue}if(G.kind==="resume"){l.close(),l=wf({cwd:e,resume:G.uuid,profileName:n,allowProdWrites:a});let Q=gL(G.uuid);c={uuid:G.uuid,firstPrompt:Q?.firstPrompt??null,titleFired:!0},Y$(G.uuid),console.log(X(`\u2713 Resumed "${G.name}"`)),console.log("");continue}if(G.kind==="audit-blocked"){console.log(H(G.note)),console.log(u(` Run: ${G.lead.cmd} \u2014 ${G.lead.reason}.`)),console.log("");continue}if(G.kind==="forward-to-agent"){c.firstPrompt||(c.firstPrompt=G.display??G.prompt);let Q=G.display??"",N=Q.trim().split(/\s+/),ne=Fw(Q),te=ne?DL(e,Ww(Q)):[],he=ne==="review"?G$(e):null,we=N[0]==="/screenshot"&&(N[1]==="verify"||N[1]==="review"),ye=we?N[2]&&!N[2].startsWith("--")?[N[2]]:ai(He(e)):[],ke=N[0]==="/catch-up"&&!ne,ee=ke?G$(e):null;l.beginTurn({baseline:ee,allowUnfinishedHints:N.includes("--include-unfinished")});let Ee=ke?on(e):null,_e=ke?fi(e).hold:!1,Xe=G.prompt;if(Q.startsWith("/"))try{let Pe=za(e,Q);Pe&&(Xe=`${Xe}
|
|
477
|
+
|
|
478
|
+
${Pe}`)}catch{}let ho=await kf(l,Xe,r,c,e,n);if(ne){let Pe=ne==="review"?Xo(e,te,he,n):null,Ne=Pe?Pe.earned:te;if(Ne.length>0)try{NL(e,Ne,wt(ne))}catch{}let tt=Pe?Jr(e,Pe.unadopted,{lead:Pe.changed.length===0}):null;if(tt)for(let an of tt.lines)console.log(u(an))}if(ee){ho.produced&&OL(e);let Pe=Yo(e,ee,"",N[0]);if(Pe.cta)console.log(u(Pe.cta.text));else if(Ee){let Ne=_l({queued:Ee,hold:_e});Ne.note&&console.log(Ne.tone==="warn"?H(Ne.note):u(Ne.note)),Ne.lead&&console.log(u(` Run ${Ne.lead.cmd} \u2014 ${Ne.lead.reason}.`))}}if(N[0]==="/reuse"&&N[1]==="audit"){let Pe=N.slice(2).find(Ne=>!Ne.startsWith("--"));for(let Ne of rc(e,Pe))console.log(Ne)}if(N[0]==="/audit"&&!N.includes("--auto")&&Ri(e,n),we&&ye.length>0)try{for(let Pe of Vr(e,ye))console.log(Pe)}catch{}if(N[0]==="/push"){let Pe=await Hs(e,n);Pe&&console.log(u(Pe))}if((N[0]==="/catch-up"||N[0]==="/document")&&(N.includes("--push")||N.includes("--publish")))try{let Pe=await LL({cwd:e,profileName:n}),{clean:Ne,conflicts:tt}=Fo(Pe.entries,Wo(e,n));Ne.length===0?console.log(u("Nothing new to push \u2014 everything is already up to date on Document360.")):await nn(P,Ne.map(an=>an.path),tt.length,{skipReview:N.includes(_t)})}catch(Pe){console.log(H(`Couldn't check what to push (${Pe.message}) \u2014 your drafts are saved; run /push when ready.`))}}else G.kind==="continue"&&G.ownNext||UL(e,n);continue}if(PL(R)){let D=TL(R);if(D){try{AL(e,{title:D,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}c.firstPrompt||(c.firstPrompt=R),await kf(l,`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${D}". 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 "${D}" and the article path(s) you wrote.`,r,c,e,n);continue}}c.firstPrompt||(c.firstPrompt=R),await kf(l,R,r,c,e,n)}}}finally{l.close(),h.close(),await ql()}}function _L(e,t){console.log(""),console.log(Ds("document360-writer")),console.log(u(` cwd: ${e}`));let n=$L(e);if(console.log(u(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(FL(e,t)),!vL(e))console.log(H(" 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(xa(e),!Pn(e))for(let r of Ra(e))console.log(H(` ${r}`))}catch{}try{let r=RL(e);r.persisted&&r.appType?console.log(u(` \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=EL(e);for(let s of ba(r.applied))console.log(H(` ${s}`));if(r.reopenedForRedaction)for(let s of ka(r.reopenedForRedaction).split(/\r?\n/))console.log(H(` ${s}`))}catch{}try{let r=Ti(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:o}),s=r?Ci(r,{pickable:!1,scaleFor:i=>rn(e,i)}):null;if(s?.kind==="recommend"&&s.rec.note){let i=s.rec.tone==="warn"?H:u;for(let a of $l(s.rec.note).split(`
|
|
479
|
+
`))console.log(i(` ${a}`));s.rec.picker&&console.log(Z(` Pick one: ${s.rec.picker.options.map(a=>a.cmd).join(" \xB7 ")}`))}}catch{}}console.log(u(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}var V$=!1;function UL(e,t){try{let n=Ti(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:!1}),o=n?Ci(n,{scaleFor:r=>rn(e,r)}):null;if(o?.kind!=="recommend")return;if(o.rec.settled&&!V$){V$=!0;for(let r of $l(o.rec.settled).split(`
|
|
480
|
+
`))console.log(X(` ${r}`))}else o.rec.settled&&!o.rec.lead&&console.log(u(" Nothing is waiting. /roadmap lists the optional campaign steps."));o.rec.lead&&console.log(u(` Next: ${os(o.rec.lead)}`))}catch{}}function FL(e,t){try{let n=K$(e,t),o=n.production?H(` ${Ye}`):"",r=CL(n.name,n.project.projectId);if(!r)return u(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...H$(r.idToken)??{},...H$(r.accessToken)??{}},i=s.email??s.preferred_username??"signed in";return SL(r)&&!r.refreshToken?H(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):u(` Document360: ${i} \xB7 profile "${n.name}"${o}`)}catch(n){return u(` Document360: ${n.message.split(".")[0]}`)}}function WL(){console.error(""),console.error(`Sign in with your Claude subscription: run ${Z("claude")} once, then retry.`),console.error(` (No Claude Code? ${Z("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${Z("https://console.anthropic.com/settings/keys")}`)}function BL(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;bL({uuid:t,name:r??wL(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function HL(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||kL(o,t).then(r=>{r&&yL(n,r)}).catch(()=>{})}async function kf(e,t,n,o,r,s){let i=new Map,a=!1,l=!1;for await(let c of e.send(t))c.type==="tool"&&(l=!0),c.type==="text"&&c.delta.trim()&&(l=!0),c.type==="tool"&&z$.test(c.name)&&(a=!0),GL(c,o,r,n,i,s);if(a)try{let c=IL(await jL({cwd:r,profileName:s}));c&&console.log(c.startsWith("\u26A0")?H(c):c)}catch{}return{produced:l}}function GL(e,t,n,o,r,s){switch(e.type){case"session":t.uuid||BL(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let i=q$()?null:dc(e.name,e.input,n,s);if(i){process.stdout.write(`
|
|
481
|
+
|
|
482
|
+
`);let l=[i.category,i.note].filter(h=>!!h).map(h=>Ae(` \xB7 ${h}`)),c=i.loud?Ae(" \xB7 ")+Je(H(i.loud)):"";console.log(`${X("\u25CF")} ${Z(Je(qd(i.verb)))}${Je(i.title)}${l.join("")}${c}`),r.set(e.id,{name:e.name,input:e.input,doc:!0,keepResult:i.keepResult});break}let a=hc(e.name,e.input,process.cwd());a&&(process.stdout.write(`
|
|
483
|
+
|
|
484
|
+
`),console.log(`${Ae("\u25CF")} ${a.title}${a.arg!==null?Ae(`${a.sep}(${a.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let i=Ft(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!i)break;let a=l=>l===1?"":"s";console.log(Ae(` \u23BF Added ${i.added} line${a(i.added)}, removed ${i.removed} line${a(i.removed)}`));for(let l of i.lines)console.log(l);i.hidden>0&&console.log(u(` \u2026 +${i.hidden} more diff lines`));break}case"tool_result":{let i=r.get(e.id);if(!i)break;r.delete(e.id);let l=i.doc&&!i.keepResult&&!e.isError?{lines:[],hidden:0}:fc(e.output,4,e.isError||q$()?void 0:i.name,i.input),c=e.isError?L:Ae;l.lines.forEach((h,y)=>console.log(c((y===0?" \u23BF ":" ")+h))),l.hidden>0&&console.log(u(` \u2026 +${l.hidden} lines`)),e.isError||ML(i.name,i.input,e.output,n);break}case"result":{process.stdout.write(`
|
|
485
|
+
`);let i=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(u(` (${Zs(i)}\u2192${Zs(e.outputTokens)} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(Y$(t.uuid),t.titleFired||HL(t,n));break}case"error":console.error(""),e.kind==="limit"?console.log(H(`\u23F3 ${e.message}`)):console.error(L(`agent error: ${e.message}`)),e.note&&console.log(u(` ${e.note}`)),o.kind==="subscription"&&e.kind==="auth"&&WL();break}}import{render as f6}from"ink";import{resolveAuth as m6}from"document360-engine";import{useCallback as ie,useEffect as ct,useMemo as Nc,useRef as ce,useState as pe}from"react";import{Box as Le,Text as K,useApp as IO,useInput as LO,useStdout as OO}from"ink";import{existsSync as ls,readFileSync as Dc,readdirSync as MO,writeFileSync as Zv,mkdirSync as _O}from"node:fs";import{basename as Di,dirname as UO,isAbsolute as FO,join as ji}from"node:path";import{createSession as e0,classifyClaudeAuth as Uf,CLAUDE_CODE_SETUP_HINT as WO,loginPkce as BO,toStoredTokens as HO,saveTokens as GO,getAccessToken as qO,D360AuthError as VO,resolveActiveProfile as pt,resolveProjectId as YO,getArticle as KO,decodeJwtClaims as ps,isExpired as or,loadTokens as po,clearTokens as zO,rememberSessionProject as XO,listStoredSessions as QO,tokensProjectId as t0,clearProfileProject as JO,setTitle as ZO,slugify as e3,touchSession as Df,upsertSession as t3,generateTitle as n0,findByName as n3,listSessions as o3,renameSession as r3,suggestNextAction as s3,readProjectConfig as ve,writeProjectConfig as o0,autoModeEnabled as r0,autoBudgetUsd as jc,DEFAULT_AUTO_BUDGET_USD as i3,WRITER_DIRNAME as a3,readUserConfig as s0,writeUserConfig as l3,resolveAndPersistAppType as c3,detectAppType as i0,resolveModelSetting as Ff,loadProfileMap as u3,applyPull as Ic,computeSyncStatus as Ii,unpushedArticlePaths as d3,ensureSeededContentSwept as p3,seededSweepLines as h3,lintDocs as cs,compareRemoteSources as f3,planPull as a0,recordRunSample as m3,pushArticles as g3,pushArticle as y3,PUSH_POOL_SIZE as w3,isPullWouldBlankError as l0,localArticleTitle as c0,establishBaselines as b3,rebaselineServerMeta as k3,inventoryRepo as $3,resolveEnvironment as v3,environmentIsProduction as x3,environmentIsInternal as R3,planPartitions as jf,partitionEvenly as S3,screenshotPlaceholderIds as C3,trackedArticlePaths as P3,runPartitioned as Li,partitionCoverage as If,estimateBulkCost as u0,resolveModelForOperation as Oi,readDocsPlan as d0,checkForUpdate as p0,detectInstallKind as T3,isSelfUpdatable as A3,devHintsGuidePath as h0,toolFeedbackPath as f0,reconcileToolFeedback as E3,reconcileUpgradeActions as N3,stampArticles as us,snapshotArticles as Lf,listArticleFiles as D3,CONTENT_CAP_VERSION as j3,ENGINE_VERSION as S0,DEFAULT_DOCS_DIR as Wf,docsRootOf as I3,setProfileProject as L3,writeCrashLog as O3,applyStructureOrder as Of,orderSyncLine as Mf,applyRelatedArticles as m0,relatedSyncLine as g0,reconcileDocsGit as M3,shareExplainedPath as _3,ensureDir as U3}from"document360-engine";Nr();Kn();import{spawn as Q$}from"node:child_process";import{existsSync as qL,mkdirSync as VL,readFileSync as YL,writeFileSync as KL}from"node:fs";import{join as J$}from"node:path";import{userDir as Z$}from"document360-engine";function zL(){if(process.env.WSL_DISTRO_NAME||process.env.WSL_INTEROP)return!0;try{return/microsoft/i.test(YL("/proc/version","utf8"))}catch{return!1}}function XL(e=process.platform,t=zL()){if(e==="win32")return[{cmd:"clip",args:[],encoding:"utf16le"}];if(e==="darwin")return[{cmd:"pbcopy",args:[],encoding:"utf8"}];let n=[{cmd:"wl-copy",args:[],encoding:"utf8"},{cmd:"xclip",args:["-selection","clipboard"],encoding:"utf8"},{cmd:"xsel",args:["--clipboard","--input"],encoding:"utf8"}];return t&&n.push({cmd:"clip.exe",args:[],encoding:"utf16le"}),n}function QL(e,t){return new Promise(n=>{try{let o=process.platform==="win32"?Q$([e.cmd,...e.args].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):Q$(e.cmd,e.args,{stdio:["pipe","ignore","ignore"]});o.on("error",()=>n(!1)),o.on("close",s=>n(s===0)),o.stdin?.on("error",()=>n(!1));let r=e.encoding==="utf16le"?Buffer.from("\uFEFF"+t,"utf16le"):Buffer.from(t,"utf8");o.stdin?.end(r)}catch{n(!1)}})}async function $f(e){for(let t of XL())if(await QL(t,e))return!0;return!1}function JL(e){return J$(Z$(),"copy",`${e}.txt`)}async function ev(e,t){if(await $f(e))return{copied:!0,path:null};let n=JL(t);try{let o=J$(Z$(),"copy");return qL(o)||VL(o,{recursive:!0}),KL(n,e,"utf8"),{copied:!1,path:n}}catch{return{copied:!1,path:null}}}var tv=/\b(?:reply|respond|answer)\s+with\s+(?:the\s+|a\s+)?(?:number|option|\d+)\b|\bpick one\b|\bpress the number\b|\b(?:tell me|let me know)\s+which\b|\bsay the number\b/i;function nv(e){let t=e.replace(/\s+$/,"").split(`
|
|
486
|
+
`),n=0;for(let s=t.length-1;s>=0;s--){let i=t[s];if(/^\s{0,3}\d{1,2}[.)]\s+\S/.test(i)){n++;continue}if(!(n>0&&/^\s+\S/.test(i)))break}return n<2?0:t.filter(s=>/^\s{0,3}\d{1,2}[.)]\s+\S/.test(s)).slice(-n).every((s,i)=>Number(/^\s{0,3}(\d{1,2})/.exec(s)[1])===i+1)?n:0}var ZL=/\b(?:once|after|when)\s+(?:you|you've|you have|they|those|these|that)\b[^.!?]{0,80}\b(?:tell me|let me know|come back|ask me|say the word|run\s+\/|then\s+\/)|\b(?:tell me|let me know)\s+(?:when|once|and)\b|\bi'?ll\s+(?:wait|stand by|pick (?:it|this) up)\b|\bcome back to me\b|\bthen\s+(?:ask|tell)\s+me\b/i;function ov(e){let t=e.trimEnd();if(!t)return null;let n=nv(t);return n>=2?{options:n}:/\?[\s*_"')\]]*$/.test(t)||tv.test(t)||ZL.test(t)?{options:0}:null}function vf(e,t){if(t.closed)return e;let n=e.split(`
|
|
487
|
+
`),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){tv.test(s)&&(t.cueSeen=!0);continue}let i=/^(\s{0,3})[-*•]\s+(.*)$/.exec(s);i?(n[r]=`${i[1]}${++t.num}. ${i[2]}`,o=!0):o&&s.trim()!==""&&/^\S/.test(s)&&(t.closed=!0)}return n.join(`
|
|
488
|
+
`)}var eO=/^(?:(?:run|use|try|execute)\s+)?['"`*]?(\/[a-z][a-z-]*)['"`*]?((?:\s+(?:--?[a-z][\w-]*|\S*[/\\]\S*|\d{1,3}[-_][\w.-]*|[\w.-]+\.(?:md|markdown)))*)/i;function tO(e,t){let n=nv(e);return n<2?[]:e.replace(/\s+$/,"").split(`
|
|
489
|
+
`).filter(s=>/^\s{0,3}\d{1,2}[.)]\s+\S/.test(s)).slice(-n).map(s=>{let i=s.replace(/^\s{0,3}\d{1,2}[.)]\s+/,"").trim(),a=eO.exec(i);if(!a)return null;let l=a[1].slice(1).toLowerCase();return t.has(l)?`${a[1]}${(a[2]??"").replace(/\s+/g," ").trimEnd()}`:null})}function rv(e,t){let n=tO(e,t);return n.length<2||n.some(o=>o===null)?null:n}function nO(e){let t=e.split(`
|
|
490
|
+
`).map(o=>o.trim()).filter(o=>o.length>3),n=t[t.length-1];return n?n.length>160?`${n.slice(0,157)}\u2026`:n:null}function ss(e){if(e.usageLimit)return`${e.label}: ${e.usageLimit}`;let t=e.stderrTail?nO(e.stderrTail):null;return t?`${e.label} last said: ${t}`:`${e.label} has said nothing since. Whatever it is, it is recorded: d360-writer logs. Stopping keeps every batch already finished.`}var oO={la:"local","l all":"local","local all":"local",pa:"portal","p all":"portal","portal all":"portal",sa:"skip","s all":"skip","skip all":"skip"},rO={L:"local",P:"portal",S:"skip"},sO={ya:"write","y all":"write","yes all":"write",na:"skip","n all":"skip","no all":"skip"},iO={Y:"write",N:"skip"};function sv(e,t,n){let o=e.trim(),r=o.toLowerCase().replace(/\s+/g," ");return t[r]??(o.length===1?n[o]??null:null)}function kc(e){return sv(e,oO,rO)}function iv(e){return sv(e,sO,iO)}function xf(e,t){let n=t?.max??12,o=t?.chrome??8;return Math.max(3,Math.min(n,(e??24)-o))}function $c(e,t,n){if(e<=n)return{start:0,end:e,above:0,below:0};let o=Math.min(Math.max(0,t),e-1),r=Math.min(Math.max(0,o-Math.floor(n/2)),e-n),s=r+n;return{start:r,end:s,above:r,below:e-s}}function Rf(e,t,n,o=Date.now()){let s=e.value>0&&o-e.at<900?e.value*10+t:0,i=s>=1&&s<=n?s:t>=1&&t<=n?t:0;return i===0?{index:null,memory:{value:0,at:o}}:{index:i-1,memory:{value:i,at:o}}}function av(e){return e<2?null:`1-${e}`}function Tt(e){let t=[];if(e.multi)t.push("\u2191\u2193 move","space toggle");else{t.push("\u2191\u2193 move");let n=e.rows===void 0?null:av(e.rows);n&&t.push(`${n} jump to a row`)}return t.push(...e.extra??[]),t.push(`enter ${e.verb}`),t.push(`esc ${e.cancel??"cancel"}`),t.join(" \xB7 ")}function lv(e){if(e.multi)return"pick with space, then enter to save \xB7 esc to cancel\u2026";let t=e.rows===void 0?null:av(e.rows);return`choose one below \u2014 \u2191\u2193 then enter to ${e.verb}${t?", or type its number":""} \xB7 esc to ${e.cancel??"cancel"}\u2026`}var aO=[/\bfile does not exist\b/i,/\bno such file or directory\b/i,/\bENOENT\b/,/\bno (files? )?(were )?found\b/i,/\bfound 0 (files?|matches|results)\b/i,/\bno matches\b/i,/\bdid not match any\b/i,/\bno results?\b/i],lO=[/\bpermission denied\b/i,/\bEACCES\b/,/\bEPERM\b/,/\bnot authori[sz]ed\b/i,/\bunauthori[sz]ed\b/i,/\bforbidden\b/i,/\brefus(ed|ing)\b/i,/\bblocked\b/i,/\bwriter mode\b/i,/\bHTTP [45]\d\d\b/],cO=/^(read|glob|grep|ls|search|notebookread)$/i;function cv(e,t){return!e||!cO.test(e.trim())||lO.some(n=>n.test(t))?!1:aO.some(n=>n.test(t))}import{existsSync as uO,mkdirSync as dO,readFileSync as pO,writeFileSync as hO}from"node:fs";import{join as uv}from"node:path";import{writerDir as fO}from"document360-engine";function dv(e){return uv(fO(e),".sessions")}function pv(e,t){return uv(dv(e),`${t}.json`)}function hv(e,t,n){try{dO(dv(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");hO(pv(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function Sf(e,t){try{let n=pv(e,t);if(!uO(n))return[];let o=JSON.parse(pO(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var mO=e=>`\x1B]0;${e}\x07`,gO=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function fv(e){process.stdout.isTTY&&process.stdout.write(e)}function is(e){fv(mO(e))}function vc(e){fv(gO(e))}var xc=["\xB7 "," \xB7"],Rc="\u{1F7E3}";Dl();var mv=e=>e===1?"":"s";function gv(e){let t=e.ran.length,n=t===0?"nothing to do":`${t} step${mv(t)} done`;switch(e.reason.kind){case"settled":return{tone:"ok",text:`Auto mode finished \u2014 that is the full round trip. ${n}.`};case"delivered":return{tone:"ok",text:`Auto mode finished \u2014 this round is delivered and your readers have it. ${n}.`};case"nothingToDo":return t===0?e.parked.length>0?{tone:"ok",text:"Auto mode had nothing it could run on its own \u2014 everything else is already written, saved and live."}:{tone:"ok",text:"Auto mode had nothing to do \u2014 everything is already written, saved and live."}:e.parked.length>0?{tone:"ok",text:`Auto mode finished what it could. ${n}.`}:{tone:"ok",text:`Auto mode finished \u2014 nothing left waiting. ${n}.`};case"onlyBlocked":return t===0?{tone:"warn",text:"Auto mode did not start anything \u2014 everything waiting needs a decision from you."}:{tone:"warn",text:`Auto mode went as far as it could on its own. ${n}, and the rest needs you.`};case"budget":return{tone:"warn",text:`Auto mode stopped at its spending limit \u2014 ${ze(e.reason.spentUsd)} of ${ze(e.reason.limitUsd)}. ${n}.`};case"stopped":return{tone:"warn",text:`Auto mode stopped \u2014 you asked it to. ${n}.`};case"repeat":case"noProgress":return{tone:"warn",text:`Auto mode stopped \u2014 ${e.reason.cmd} came back unfinished, and running it again would not have changed that. ${n}.`};case"maxSteps":return{tone:"warn",text:`Auto mode stopped after ${e.reason.steps} steps without reaching a finished state. ${n}.`}}}function yv(e){switch(e.reason.kind){case"settled":case"nothingToDo":return e.parked.length>0?{tone:"info",text:"What is left is with someone else. I am still in auto mode, so I will pick it up as soon as it lands."}:{tone:"info",text:"Nothing is waiting. I am still in auto mode, so the next time there is work I will pick it up."};case"delivered":return{tone:"info",text:"What is left needs you or a browser \u2014 /status lists it, and it costs nothing. I am still in auto mode for the next round."};case"budget":return{tone:"info",text:`/auto --budget <amount> raises the limit, then ${e.reason.next} is where it picks up.`};case"stopped":return{tone:"info",text:"/auto on picks the round trip back up from here. Nothing was undone."};case"onlyBlocked":return{tone:"info",text:"Clear the items above and I will carry on \u2014 /auto on starts me again."};case"repeat":case"noProgress":case"maxSteps":return{tone:"info",text:"This one needs a person. /status shows what stands between your work and your readers, and it costs nothing."}}}function wv(e){let t=[gv(e)],n=e.spentUsd>0?` \xB7 ${ze(e.spentUsd)} of ${ze(e.budgetUsd)}`:"";if(t.push({tone:"info",text:` ${wl({seconds:e.seconds,...e.activeSeconds!==void 0?{activeSeconds:e.activeSeconds}:{}})}${n}`}),e.ran.length>0){t.push({tone:"info",text:""}),t.push({tone:"info",text:" What I ran:"});for(let o of e.ran)t.push({tone:"info",text:` \xB7 ${o}`})}if(e.parked.length>0){t.push({tone:"info",text:""}),t.push({tone:"warn",text:` ${e.parked.length} thing${mv(e.parked.length)} need${e.parked.length===1?"s":""} you:`});for(let o of e.parked)t.push({tone:"warn",text:` \xB7 ${o.what}${o.cmd?` \u2192 ${o.cmd}`:""}`})}return e.reason.kind!=="settled"&&e.reason.kind!=="nothingToDo"&&e.reason.kind!=="delivered"&&e.ran.length>0&&(t.push({tone:"info",text:""}),t.push({tone:"info",text:" Everything already written, saved and published is kept \u2014 stopping never undoes work."})),t.push({tone:"info",text:""}),t.push(yv(e)),t}function bv(e,t){let n=gv(e).text,o=[`# Automatic run \u2014 ${t}`,"",n,""];if(o.push(`- Time: ${wl({seconds:e.seconds,...e.activeSeconds!==void 0?{activeSeconds:e.activeSeconds}:{}})}`),o.push(`- Spent: ${ze(e.spentUsd)} of a ${ze(e.budgetUsd)} limit`),o.push(""),o.push("## What ran"),o.push(""),e.ran.length===0)o.push("Nothing \u2014 see above for why.");else for(let r of e.ran)o.push(`- \`${r}\``);if(o.push(""),o.push("## What needs you"),o.push(""),e.parked.length===0)o.push("Nothing.");else for(let r of e.parked)o.push(`- ${r.what}${r.cmd?` Run \`${r.cmd}\`.`:""}`);return o.push(""),o.push(yv(e).text),o.push(""),o.join(`
|
|
491
|
+
`)}var kv=new Set(["/resolve","/pull","/screenshot","/login","/logout","/init","/reset","/discover","/genre","/style-guide","/scope","/profile","/project","/workspace","/model","/mcp","/share","/auto","/allow-prod"]),yO=new Set(["--skip-review","--skip-style","--skip-screenshots","--force"]),wO=40,bO=2,kO=(e,t)=>e.what===t.what&&e.cmd===t.cmd;function Sc(e,t){return e.some(n=>kO(n,t))?e:[...e,t]}function $v(e){let t=un(e);if(!t||kv.has(t.cmd)||!Lr(t))return!1;for(let n of t.flags)if(yO.has(n))return!1;return!$O(t)}function $O(e){return e.cmd!=="/review"&&e.cmd!=="/write"&&e.cmd!=="/reorder"||e.flags.has("--all")||e.flags.has("--blocked")||e.flags.has("--stale")?!1:e.scope===void 0}function vv(e){let t=un(e);return!t||t.cmd!=="/push"||t.scope!==void 0||t.flags.has("--all")||t.flags.size>0?e:"/push --all"}function xv(e){return!e||e.kind!=="cmd"?null:e.cmd}function vO(e){return e.kind==="answer"?{what:"I asked you a question and stopped to wait for the answer.",cmd:null}:e.kind==="prompt"?{what:`A step needs you to tell me what you want: \u201C${e.text}\u201D.`,cmd:null}:Rv(e.cmd)}function Rv(e){switch(un(e)?.cmd??e.split(/\s+/)[0]??e){case"/resolve":return{what:"Some articles were changed both here and in Document360, and only you can say which copy survives.",cmd:"/resolve"};case"/pull":return{what:"Document360 has articles this repo has no folder for, and importing them changes your docs tree.",cmd:"/pull"};case"/screenshot":return{what:"Some screenshots are still to be taken \u2014 that needs your product running, so I never do it automatically.",cmd:"/screenshot"};case"/login":return{what:"The Document360 session needs signing in again, which happens in your browser.",cmd:"/login"};case"/discover":return{what:"The product questions are still out with your builder, so there is nothing I can answer tonight.",cmd:"/discover"};default:return{what:`${e} is a step I leave to you.`,cmd:e}}}var xO=(e,t)=>e.ran.filter(n=>n===t).length;function Sv(e,t,n){let o=t.parked,r=n.maxSteps??wO;if(t.ran.length>=r)return{kind:"stop",reason:{kind:"maxSteps",steps:t.ran.length},parked:o};if(e.heldHints>0){let a=e.heldHints;o=Sc(o,{what:`${a} note${a===1?"":"s"} from your builder ${a===1?"is":"are"} waiting on code they haven't finished \u2014 I've asked whether ${a===1?"it's":"they're"} done.`,cmd:null})}if(e.restKind==="complete")return{kind:"stop",reason:{kind:"settled"},parked:o};if(e.restKind==="delivered"&&t.ran.length>0)return{kind:"stop",reason:{kind:"delivered"},parked:o};if(!e.lead&&!e.picker&&e.menu.length===0)return{kind:"stop",reason:{kind:"nothingToDo"},parked:o};e.picker&&(o=Sc(o,{what:`${e.picker.title} \u2014 that one is yours to answer.`,cmd:null}));let s=[{cmd:xv(e.lead),lead:e.lead},...e.menu.map(a=>({cmd:a.startsWith("/")?a:null,lead:null}))],i=new Set;for(let a of s){if(!a.cmd){if(a.lead?.kind==="prompt"&&a.lead.text===Zo)return t.ran.includes(Zo)?{kind:"stop",reason:{kind:"noProgress",cmd:Zo},parked:o}:t.spentUsd>=n.budgetUsd?{kind:"stop",reason:{kind:"budget",spentUsd:t.spentUsd,limitUsd:n.budgetUsd,next:Zo},parked:o}:{kind:"prompt",text:Zo,parked:o};a.lead&&(o=Sc(o,vO(a.lead)));continue}let l=vv(a.cmd);if(i.has(l))continue;if(i.add(l),!$v(a.cmd)){let h=un(a.cmd);h&&kv.has(h.cmd)&&(o=Sc(o,Rv(a.cmd)));continue}if(t.ran[t.ran.length-1]===l)return{kind:"stop",reason:{kind:"repeat",cmd:l},parked:o};if(xO(t,l)>=bO)return{kind:"stop",reason:{kind:"repeat",cmd:l},parked:o};if(t.lastClosedItsTarget===!1&&t.lastLeadKey&&t.lastLeadKey===l)return{kind:"stop",reason:{kind:"noProgress",cmd:l},parked:o};let c=t.spentUsd+(n.nextCostUsd??0);return t.spentUsd>=n.budgetUsd||c>n.budgetUsd?{kind:"stop",reason:{kind:"budget",spentUsd:t.spentUsd,limitUsd:n.budgetUsd,next:l},parked:o}:{kind:"run",cmd:l,parked:o}}return{kind:"stop",reason:{kind:"onlyBlocked"},parked:o}}function Cv(e,t,n){let o=[],r=new Set([t]),s=[xv(e.lead),...e.menu.map(i=>i.startsWith("/")?i:null)];for(let i of s){if(!i||!$v(i))continue;let a=vv(i);if(r.has(a))continue;r.add(a);let l=null;try{l=n(a)}catch{l=null}o.push({cmd:a,scale:l})}return o}var Pv=()=>({fingerprint:null,counts:null,settled:0,spokenBaseline:null,lastSpokeAt:null,awaySince:null}),RO={hints:0,requests:0,answers:0,directives:0,held:0,heldAsked:0,briefMoved:!1};function Cf(e,t){let n=e??RO;return{hints:Math.max(0,t.hints-n.hints),requests:Math.max(0,t.requests-n.requests),answers:Math.max(0,t.answers-n.answers),directives:Math.max(0,t.directives-n.directives),held:Math.max(0,t.held-n.held),heldAsked:Math.max(0,t.heldAsked-n.heldAsked),briefMoved:t.briefMoved&&!n.briefMoved}}var Cc=e=>e.hints===0&&e.requests===0&&e.answers===0&&e.directives===0&&!e.briefMoved,Tv=e=>e.hints+e.requests+e.answers+e.directives+(e.briefMoved?1:0),Pf=(e,t)=>e-t>=6e5;function Av(e){let{now:t,lastInputAt:n,fingerprint:o,counts:r,occupied:s,prev:i}=e,a=Pf(t,n),c=i.fingerprint!==null&&i.fingerprint!==o?0:i.settled+1,h={...i,fingerprint:o,counts:r,settled:c,awaySince:a?i.awaySince??t:null,spokenBaseline:i.spokenBaseline??r};if(a){let x=Cf(h.spokenBaseline,r);return{memory:h,speak:null,waiting:Cc(x)?null:x}}if(s)return{memory:h,speak:null,waiting:null};if(c<2)return{memory:h,speak:null,waiting:null};let y=Cf(i.spokenBaseline,r);return Cc(y)?{memory:h,speak:null,waiting:null}:i.lastSpokeAt!==null&&t-i.lastSpokeAt<6e5?{memory:h,speak:null,waiting:null}:{memory:{...h,spokenBaseline:r,lastSpokeAt:t,settled:c},speak:y,waiting:null}}function Ev(e,t,n){if(e.awaySince===null)return{kind:"none",memory:e};let o=t-e.awaySince,r=Cf(e.spokenBaseline,n),s={...e,awaySince:null,counts:n,spokenBaseline:n,lastSpokeAt:Cc(r)?e.lastSpokeAt:t};return Cc(r)?{kind:"none",memory:s}:{kind:o>=36e5?"briefing":"delta",memory:s,delta:r,awayMs:o}}function Ei(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"}`),e.briefMoved&&t.push("an updated product brief"),t.length===0?"":t.length===1?t[0]:`${t.slice(0,-1).join(", ")} and ${t.at(-1)}`}function Tf(e){let t=Math.round(e/6e4);if(t<45)return`${t} minutes`;let n=Math.round(e/36e5);if(n<20)return`${n} hour${n===1?"":"s"}`;let o=Math.round(n/24);return o<=1?"a day":`${o} days`}function Nv(e){return`\u{1F4E5} ${Ei(e)} just arrived from your builder \u2014 /catch-up folds ${Tv(e)===1?"it":"them"} into the docs.`}function Dv(e,t){return`\u{1F4E5} While you were away (${Tf(t)}): ${Ei(e)} from your builder \u2014 /catch-up folds ${Tv(e)===1?"it":"them"} into the docs.`}function jv(e){return`\u{1F4E5} ${Ei(e)} waiting from your builder \xB7 tab to run /catch-up\u2026`}Ta();import{publishGateVerdict as Lc,publishGateLines as _f,blockedPaths as F3,SKIP_STYLE_FLAG as y0,SKIP_SHOTS_FLAG as W3}from"document360-engine";import{askBuilder as B3,openGapQuestions as H3}from"document360-engine";import{recordStructureReview as w0}from"document360-engine";import{recordBriefConsumed as G3}from"document360-engine";import{retireArticle as q3,normalizeScope as b0,declineImport as V3,undoDecline as Y3}from"document360-engine";import{readReuseProposal as K3}from"document360-engine";ae();import{Box as Ni,Text as Ge}from"ink";import{jsx as qe,jsxs as as}from"react/jsx-runtime";function SO({row:e,nameW:t,width:n}){let o=s=>Su(s,n),r=(s,i)=>qe(Ni,{flexDirection:"column",children:s.map(i)});switch(e.t){case"head":return r(o(e.s),(s,i)=>qe(Ge,{color:ue,bold:!0,children:s},i));case"text":return r(o(e.s),(s,i)=>qe(Ge,{children:s},i));case"dim":return r(o(e.s),(s,i)=>qe(Ge,{dimColor:!0,children:s},i));case"sub":return r(o(e.s),(s,i)=>qe(Ge,{bold:!0,dimColor:!0,children:s},i));case"good":return r(o(e.s),(s,i)=>qe(Ge,{color:"green",children:s},i));case"step":{let s=o(`${e.n}. ${e.s}`);return qe(Ni,{flexDirection:"column",children:s.map((i,a)=>a===0?as(Ge,{children:[qe(Ge,{color:ue,children:`${e.n}. `}),i.slice(`${e.n}. `.length)]},a):qe(Ge,{children:i},a))})}case"cmd":{let s=$a(e.name,e.s,t,n),i=s.descLines.slice(s.nameOwnLine?0:1);return as(Ni,{flexDirection:"column",children:[as(Ge,{children:[" ",qe(Ge,{color:ue,children:s.nameCell}),!s.nameOwnLine&&qe(Ge,{dimColor:!0,children:` ${s.descLines[0]??""}`})]}),i.map((a,l)=>qe(Ge,{dimColor:!0,children:`${s.indent}${a}`},l))]})}case"gap":return qe(Ge,{children:" "})}}function Iv({tab:e,scroll:t,rows:n,width:o,version:r,engineVersion:s}){let i=xt[e]??xt[0],a=Ru(i.rows),l=Math.max(20,o-2),c=6+xt.reduce((T,R)=>T+R.label.length+4,0),h="\u2500".repeat(Math.min(c,l)),y=`\u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 \u2191\u2193 scroll \xB7 esc close \xB7 d360-writer v${r} \xB7 engine v${s}`,x=mg({rows:n,inner:l,barWidth:c,footerWidth:y.length}),{visible:w,above:S,below:P}=fg(i.rows,{width:o,budget:x,scroll:t,nameW:a});return as(Ni,{flexDirection:"column",paddingX:1,children:[as(Ge,{children:[qe(Ge,{color:ue,bold:!0,children:"Help "}),xt.map((T,R)=>R===e?qe(Ge,{color:"white",backgroundColor:ue,bold:!0,children:` ${T.label} `},T.key):qe(Ge,{children:` ${T.label} `},T.key))]}),qe(Ge,{color:ue,children:h}),as(Ni,{flexDirection:"column",marginTop:1,children:[S>0?qe(Ge,{dimColor:!0,children:`\u22EF ${S} more above`}):null,w.map((T,R)=>qe(SO,{row:T,nameW:a,width:o},S+R)),P>0?qe(Ge,{dimColor:!0,children:`\u22EF ${P} more below`}):null]}),qe(Ge,{dimColor:!0,children:`
|
|
492
|
+
\u2190/\u2192 or tab switch \xB7 1-5 jump${S+P>0?" \xB7 \u2191\u2193 scroll":""} \xB7 esc close \xB7 d360-writer v${r} \xB7 engine v${s}`})]})}var CO=/^(?:\d+[.)]|[-*•])\s+/;function Lv(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
|
|
493
|
+
`)){let i=s.trim().replace(CO,""),a=i.match(/^`([^`]+)`$/);a&&(i=a[1].trim());let l=i.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!l||!o.has(l[1].toLowerCase()))continue;let c=`/${l[1].toLowerCase()}${l[2]?` ${l[2]}`:""}`;if(r.includes(c)||r.push(c),r.length>=n)break}return r}ae();function tr(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function at(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function Pc(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var PO=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function Af(e,t,n){if(!PO.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 i=s.replace(/\\/g,"/");return r===i||r.endsWith(`/${i}`)})??null}function Ef(e){return e.replace(/^[\w.-]+\//,"")}var Tc=16,Ov={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function uo(e){return typeof e=="string"?e:e.cmd}function Mv(e){return typeof e=="string"?void 0:e.desc}function Nf(e){return e.trim().split(/\s+/).slice(1).join(" ")}function _v(e,t){let n=Nf(t);return e.some(r=>uo(r).trim()===t.trim()||!!n&&Nf(uo(r))===n)?e.filter(r=>uo(r).trim()!==t.trim()&&!(n&&Nf(uo(r))===n)):[]}import{isDirectiveMention as z3,stripDirectiveMention as X3,appendDirective as Q3,reconcileTestidRequest as J3,builderChannelWired as Z3,pendingFingerprint as e6}from"document360-engine";qn();var TO=/\[Pasted text #\d+ \+\d+ lines?\]/g;function Uv(e){return e.replace(/\r\n?/g,`
|
|
494
|
+
`)}function Fv(e){return e.includes(`
|
|
495
|
+
`)||e.length>200}function Wv(e,t){let n=t.split(`
|
|
496
|
+
`).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function Bv(e,t){return e.replace(TO,n=>t.get(n)??n)}function Hv(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function Ac(e,t){let n=Math.max(1,t),o=[],r=0;for(let s of e.split(`
|
|
497
|
+
`)){if(s.length===0)o.push({start:r,end:r});else for(let i=0;i<s.length;i+=n)o.push({start:r+i,end:r+Math.min(i+n,s.length)});r+=s.length+1}return o.length>0?o:[{start:0,end:0}]}function Ec(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function Gv(e,t,n){let o=Ec(e,t),r=o+n;if(r<0||r>=e.length)return t;let s=Math.min(t,e[o].end)-e[o].start;return Math.min(e[r].start+s,e[r].end)}function qv(e,t,n){let o=e[Ec(e,t)];return n==="start"?o.start:o.end}var AO=new Set(["Edit","Write","MultiEdit","NotebookEdit"]),Vv={hint:"hint",message:"message",state:"state file",roadmap:"roadmap",directive:"directives",feedback:"tool-feedback"},EO=new Set(["hint","message","state"]),NO=["hint","message","roadmap","directive","feedback","state"];function DO(e){return e.startsWith("hints/")?"hint":e.startsWith("messages/")?"message":e==="roadmap.md"?"roadmap":e==="directives.md"?"directive":/^tool-feedback(-archived)?\.md$/.test(e)?"feedback":e.startsWith("cache/")||e.startsWith(".sessions/")||/^(plan|devhints-state|upgrade-state|category-map)\.json$/.test(e)?"state":null}function Yv(e,t){let n=e==="Read"?"read":AO.has(e)?"updated":null;if(!n)return null;let o=t.file_path??t.notebook_path;if(typeof o!="string"||!o)return null;let r=o.replace(/\\/g,"/").toLowerCase(),s=".d360-writer/",i=r.lastIndexOf(s);if(i<0)return null;let a=DO(r.slice(i+s.length));return a?{category:a,verb:n,path:r}:null}function Kv(e){let t=new Map,n=new Set;for(let r of e)r.verb==="updated"&&n.add(r.path);for(let r of e){if(r.verb==="read"&&n.has(r.path))continue;let s=`${r.category}:${r.verb}`,i=t.get(s);i||t.set(s,i=new Set),i.add(r.path)}let o=[];for(let r of NO)for(let s of["updated","read"]){let i=t.get(`${r}:${s}`)?.size??0;i!==0&&o.push(EO.has(r)?`${i} ${Vv[r]}${i===1?"":"s"} ${s}`:`${Vv[r]} ${s}`)}return o.length>0?o.join(" \xB7 "):null}function zv(e,t,n){let o=Math.max(1,n),r=e.split(`
|
|
498
498
|
`),s=0;for(let i=r.length-1;i>=0;i--){let a=r[i];if(s+=Math.max(1,Math.ceil(a.length/o)),s>=t){let l=s-t;return{text:[l>0?a.slice(l*o):a,...r.slice(i+1)].join(`
|
|
499
|
-
`),truncated:i>0||l>0}}}return{text:e,truncated:!1}}function
|
|
500
|
-
`)){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
|
|
499
|
+
`),truncated:i>0||l>0}}}return{text:e,truncated:!1}}function Xv(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 Qv(e){let t=!1,n=0,o=0;for(let r of e.split(`
|
|
500
|
+
`)){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 nr,jsx as Y,jsxs as ge}from"react/jsx-runtime";var t6={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL",auto:"auto \u2014 right-sized for docs \xB7 /model to change"},k0=` 1. /init \u2014 pick your Document360 environment & scaffold config
|
|
501
501
|
2. /login \u2014 sign in & pick your Document360 project (workspace auto-selected)
|
|
502
|
-
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function
|
|
503
|
-
`).length+1,console.log(m)},[
|
|
504
|
-
`)}catch{}p.picker&&(
|
|
505
|
-
`)}),
|
|
506
|
-
I'll install it when you /exit \u2014 your next launch runs it.`});return}f({kind:"note",tone:"info",text:`\u2B06 Updating ${
|
|
507
|
-
${
|
|
502
|
+
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function n6(e,t,n,o){let r=Uf(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)",i=Ff(e),a=ve(e),l=(a?.docsDir??Wf).replace(/\/+$/,""),c=a?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${l}/ + config`,h={version:t,engineVersion:S0,captureVersion:Rt(),claude:s,model:i.model,modelSource:t6[i.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",workspace:null,cwd:e,prod:!1,loggedOut:!0,configured:a!==null,mode:c};if(a===null)return h;try{let y=pt(e,o);h.profile=y.name,h.apiUrl=y.connection.apiUrl,h.prod=y.production,h.project=y.project.projectName??y.project.projectId??"(chosen at login)",h.workspace=y.project.workspaceName??y.project.workspaceId??null;let x=po(y.name,y.project.projectId);if(x){let w={...ps(x.idToken)??{},...ps(x.accessToken)??{}},S=w.email??w.preferred_username??"signed in";or(x)?x.refreshToken&&(h.who=S,h.loggedOut=!1,h.sessionHint="session expired \u2014 refreshing\u2026"):(h.who=S,h.loggedOut=!1,h.sessionHint=`session valid until ${new Date(x.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return h}var o6=e=>e.mode==="local-only"?e.path:e.plan.path;function r6(e,t){try{let n=pt(e,t),o=po(n.name,n.project.projectId);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...ps(o.idToken)??{},...ps(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return or(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 $0=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],hs=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],s6="Ask me to write or update an article\u2026",v0=2e3,i6=new Set(Go.map(e=>e.name));function ds({ch:e,dim:t}){let[n,o]=pe(!0);return ct(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),Y(K,{inverse:n,color:t&&!n?"gray":void 0,children:e})}function On({rows:e,cursor:t,cap:n,render:o}){let r=$c(e.length,t,n);return ge(nr,{children:[r.above>0?Y(K,{color:"gray",children:` \u22EF ${r.above} more above`}):null,e.slice(r.start,r.end).map((s,i)=>o(s,r.start+i,r.start+i===t)),r.below>0?Y(K,{color:"gray",children:` \u22EF ${r.below} more below`}):null]})}var x0=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function R0(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var a6=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function l6({startTime:e,chars:t}){let[n,o]=pe(0),r=ce(Date.now());ct(()=>{let c=setInterval(()=>o(h=>h+1),120);return()=>clearInterval(c)},[]);let s=hs[n%hs.length],i=$0[Math.floor(n/16)%$0.length],a=Ow(e,r.current,Date.now()),l=Math.round(t/4);return ge(Le,{children:[Y(K,{color:ue,children:` ${s} ${i}\u2026 `}),Y(K,{color:"gray",children:`(${An(a)} \xB7 ~${l} tokens \xB7 esc to interrupt)`})]})}function c6({step:e,cmd:t,startedAt:n,spentUsd:o,budgetUsd:r}){let[,s]=pe(0);ct(()=>{let l=setInterval(()=>s(c=>c+1),1e3);return()=>clearInterval(l)},[]);let i=Math.max(0,Math.round((Date.now()-n)/1e3)),a=o>0?` \xB7 ${St(o)} of ${ze(r)}`:` \xB7 limit ${ze(r)}`;return ge(Le,{flexDirection:"column",children:[ge(Le,{children:[Y(K,{color:ue,children:` \u23F5\u23F5 auto \xB7 step ${e} \xB7 `}),Y(K,{color:ue,bold:!0,children:t})]}),Y(K,{color:"gray",children:` ${An(i)}${a} \xB7 esc stops`})]})}function u6({text:e}){let[t,n]=pe(0);return ct(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),Y(Le,{paddingX:1,children:Y(K,{color:ue,children:`${hs[t%hs.length]} ${e}`})})}var d6=12e4;function p6({p:e}){let[t,n]=pe(0);ct(()=>{let R=setInterval(()=>n(D=>D+1),150);return()=>clearInterval(R)},[]);let o=hs[t%hs.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),i=Math.round(e.chars/4),a=Date.now()-e.lastAt>=d6,l=e.verb??"Converting",c=e.unit??"article",h=e.rows.reduce((R,D)=>R+D.items,0),y=e.rows.reduce((R,D)=>R+(D.status==="done"?D.items:D.itemsDone??0),0),x=l.toLowerCase(),w=e.rows,S=0;if(w.length>Tc){let R=w.findIndex(B=>B.status==="active"||B.status==="pending"),D=Math.max(0,Math.min(R-2,w.length-Tc));S=w.slice(0,D).filter(B=>B.status==="done").length,w=w.slice(D,D+Tc)}let P=Math.min(40,Math.max(...w.map(R=>Ef(R.label).length),0)),T=R=>R==="failed"?"red":R==="active"?ue:void 0;return ge(Le,{flexDirection:"column",children:[ge(Le,{children:[Y(K,{color:ue,children:` ${o} ${l} ${h} ${c}${h===1?"":"s"} `}),Y(K,{color:"gray",children:e.agentless?`\xB7 ${y}/${h} ${c}${h===1?"":"s"} \xB7 ${An(r)} \xB7 esc to stop`:`\xB7 ${y}/${h} ${c}${h===1?"":"s"} \xB7 ${e.done}/${e.total} batch${e.total===1?"":"es"} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${i} tokens \xB7 ${An(r)} \xB7 esc to stop`})]}),S>0&&Y(K,{dimColor:!0,children:` \u2714 +${S} done`}),w.map(R=>ge(K,{color:T(R.status),dimColor:R.status==="done"||R.status==="pending",children:[` ${Ov[R.status]} ${Ef(R.label).padEnd(P)}`,R.status==="active"&&R.itemsDone!==void 0?` (${R.itemsDone}/${R.items} ${c}${R.items===1?"":"s"})`:R.status!=="pending"?` (${R.items} ${c}${R.items===1?"":"s"})`:"",R.status==="active"?` \u2190 ${x}\u2026`:""]},R.label)),a&&Y(K,{color:"yellow",children:` \u26A0 no activity for ${An(s)} \u2014 press esc to stop if it's wedged`}),a&&e.stalledNote?Y(K,{color:"yellow",children:` ${e.stalledNote}`}):null]})}var h6=10800*1e3;function C0({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=IO(),[s,i]=pe(n),[a,l]=pe(null),[c,h]=pe({text:"",pos:0}),y=c.text,x=ie(p=>{h(m=>{let d=typeof p=="function"?p(m.text):p;return{text:d,pos:d.length}})},[]),w=ie(p=>{h(m=>({text:m.text.slice(0,m.pos)+p+m.text.slice(m.pos),pos:m.pos+p.length}))},[]),S=ie(()=>{h(p=>{if(p.pos===0)return p;let m=p.text.slice(0,p.pos),d=Hv(m)??m.slice(0,-1);return{text:d+p.text.slice(p.pos),pos:d.length}})},[]),[P,T]=pe(!1),[R,D]=pe(!1),[B,G]=pe(0),[Q,N]=pe(!1),[ne,te]=pe(null),[he,we]=pe(null),[ye,ke]=pe([]),ee=ce(!1),Ee=ce(!1),_e=ce(null),Xe=ce(!1),[ho,Pe]=pe(!1),Ne=ce(!1),tt=ce(0),[an,At]=pe(!1),[fo,mo]=pe(!1),[rr,Mi]=pe(null),[_i,qt]=pe(0),Vt=ce(0),[sr,Mn]=pe(0),[Yt,ir]=pe(null),[mn,_n]=pe(null),ar=ce(new Map),Ui=ce(0),de=ce([]),De=ce(null);De.current===null&&(De.current=e0({cwd:e,profileName:s,allowProdWrites:!1}));let nt=ce({uuid:null,firstPrompt:null,titleFired:!1}),fs=ce(new Map),Yf=ce(null),Mc=ce(null),Fi=ce(s0().verboseTranscript===!0),gn=ce(!1),_c=ce([]),Ie=ce([]),yn=ce([]),Kt=ce([]),lr=ce(null),[Kf,go]=pe(null),Uc=ce(null),[wn,yo]=pe(null),[zt,cr]=pe(null),[Et,Un]=pe(null),[lt,ur]=pe(null),[ht,wo]=pe(null),[Nt,dr]=pe(null),[Xt,pr]=pe(null),[Qt,bo]=pe(null),[Dt,bn]=pe(null),[ut,ms]=pe(null),zf=ce({value:0,at:0}),Xf=ce({value:0,at:0}),kn=ie((p,m)=>{let{index:d,memory:g}=Rf(Xf.current,Number(p),m);return Xf.current=g,d},[]),[kt,ko]=pe(null),[Qf,$o]=pe(null);ct(()=>_n(null),[ye]);let[jt,vo]=pe(null),[ft,hr]=pe(null),[Jf,Fc]=pe([]),xo=ce([]),gs=ce(!1),ys=ce(null),Wc=ce(null),[D0,Zf]=pe(!1),Qe=ce(null),[mt,Wi]=pe(null),Bi=ce(!1),Ro=ce(!1),Hi=ce(!1),Bc=ce(null),[fr,em]=pe(null),Hc=ce(null),Be=ce(null),[mr,$e]=pe(null),[tm,Fe]=pe(null),ws=ce(!1),bs=ce(null),Gc=ce(null),So=ce(null),[It,Co]=pe(null),[ks,Po]=pe(null),Fn=!!(mt||Et||lt||ht||Nt||Xt||Qt||Dt||ut||kt||jt||ft||It||ks),$s=Nc(()=>{try{return r0(ve(e))}catch{return!1}},[e,B]),nm=Xt?{verb:"publish live",cancel:"leave as drafts",rows:Xt.rows.length+1}:Nt?{verb:"push as drafts",rows:Nt.rows.length}:kt?{verb:"choose it",rows:kt.rows.length}:Qt?{verb:"run it",rows:Qt.rows.length}:Dt?{verb:"open it",cancel:"close",rows:Dt.rows.length-1}:lt?{verb:"switch",rows:lt.rows.length}:ht?{verb:"switch",rows:ht.rows.length}:Et?{verb:"use it",rows:Et.rows.length}:zt?{verb:"switch",rows:zt.rows.length,extra:["s this session only"]}:wn?{verb:"use it",rows:Bt.length}:ft?{verb:"save",multi:!0}:null,[om,To]=pe(0),[Lt,Ao]=pe(0),[j0,rm]=pe(0),qc=Nc(()=>{try{let p=Ff(e);return p.source==="auto"?`${p.model} (auto)`:p.model}catch{return null}},[e,j0]),{stdout:ot}=OO(),[,I0]=pe(0),sm=ce(`${ot.columns??80}x${ot.rows??24}`),im=ce(ot.columns??80),rt=ie(()=>Math.max(20,(ot.columns??80)-1),[ot]),Gi=ie(p=>{de.current.push(p);let m=Vd(p,rt());gr.current+=m.split(`
|
|
503
|
+
`).length+1,console.log(m)},[rt]),Vc=ce([]),qi=ie(()=>{let p=Vc.current;if(p.length===0)return;Vc.current=[];let m=Kv(p);m&&Gi({kind:"note",tone:"info",text:`\u25CF Housekeeping ${m}`})},[Gi]),f=ie(p=>{qi(),Gi(p)},[Gi,qi]),gt=ce({printed:[],armed:[],printedAt:0}),Vi=ce(null),Yi=ce([]),gr=ce(0),Ki=ie(()=>Qe.current!==null,[]),st=ie((p,m)=>{Ki()||(tt.current++,gt.current.armed=[],te(p),we(m??null))},[Ki]),Jt=ie(()=>{tt.current++,gt.current.armed=[],te(null),we(null)},[]),vs=ie(p=>{Ki()||(tt.current++,gt.current.armed=[],te(null),we(p))},[Ki]),le=ie(p=>st(p,ns({kind:"cmd",cmd:p,reason:""})),[st]),$n=ie((p,m)=>{if(!m?.silent&&p.note&&f({kind:"note",tone:m?.tone??p.tone,text:p.note}),!m?.silent&&p.note?.includes(".d360-writer/ \u2014 your articles"))try{let A=_3(e);U3(UO(A)),Zv(A,`${new Date().toISOString()}
|
|
504
|
+
`)}catch{}p.picker&&(ke(p.picker.options.map(A=>({cmd:A.cmd,desc:A.desc}))),$o(p.picker.title),Yi.current=p.picker.exclusive?p.picker.options.map(A=>A.cmd.trim()):[]),!m?.silent&&p.note&&(gt.current.printed=p.menu,gt.current.printedAt=gr.current);let g=gr.current-gt.current.printedAt<Math.max(8,(ot.rows??24)-4)&&v$(gt.current.printed,p.menu)?p.menu:[];p.lead?(p.lead.kind==="answer"?vs(ns(p.lead,g.length)):st(p.lead.kind==="cmd"?p.lead.cmd:p.lead.text,ns(p.lead,g.length)),!m?.silent&&p.note&&(Vi.current=rs(p.lead))):!p.picker&&(!m?.silent||p.restKind!==null)&&(Jt(),g.length>0&&vs(p.restKind==="delivered"?`1\u2013${g.length} when you want one \xB7 nothing is owed \xB7 or just ask me anything\u2026`:`1\u2013${g.length} to pick a campaign step \xB7 nothing is waiting \xB7 or just ask me anything\u2026`)),gt.current.armed=g},[f,st,vs,e,ot]),Te=ie((p,m,d="info")=>{gt.current.armed=[],p&&f({kind:"note",tone:d,text:p}),m&&(m.kind==="answer"?vs(ns(m)):st(m.kind==="cmd"?m.cmd:m.text,ns(m)),Vi.current=p?rs(m):null)},[f,st,vs]),vn=ie((p,m,d,g="info")=>{if(p.producedNothing){Te("Nothing was changed \u2014 the agent produced no output, so this command did nothing at all.",{kind:"cmd",cmd:"/doctor",reason:"it checks Claude sign-in + whether the model is reachable from this machine"},"warn");return}p.handedBack||Te(m,d,g)},[Te]),[Wn,Yc]=pe(null),[L0,am]=pe(!1),xn=ie((p,m)=>{Yc(p),am(!1),f({kind:"note",tone:"info",text:m?.hint??"\u2328 Press \u2303y to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[f]),Kc=ie(()=>{J3(e,new Date().toISOString());let p=Wb(e);p&&(f({kind:"note",tone:"info",text:p.lines.join(`
|
|
505
|
+
`)}),xn(p.prompt,Z3(e)?{hint:"\u2328 Press \u2303y to copy the request \u2014 only if you want to hand it over now; your builder already has it."}:void 0))},[e,f,xn]),zi=ce(!1),zc=ie(async()=>{try{if(zi.current||!A3(T3())||ve(e)?.mode==="engineer")return;let p=await p0({pkg:zo,currentVersion:o,force:!0});if(!p.updateAvailable||!p.latest)return;if(zi.current=!0,Hl()){Gl(p.latest),f({kind:"note",tone:"info",text:`\u2B06 Update v${p.latest} is ready to install.
|
|
506
|
+
I'll install it when you /exit \u2014 your next launch runs it.`});return}f({kind:"note",tone:"info",text:`\u2B06 Updating ${zo} ${p.current} \u2192 ${p.latest}\u2026 (wait for the \u2713 before you /exit)`}),mo(!0);let m=await bi().finally(()=>mo(!1));m.ok?(f({kind:"note",tone:"ok",text:`\u2713 Updated to v${p.latest} \u2014 run /exit, then relaunch to apply.`}),le("/exit"),Mi(p.latest)):f({kind:"note",tone:"warn",text:`Update available (v${p.latest}) but auto-update failed. ${wi(m.output)}`})}catch{}},[e,o,f,le]),xs=ce(!1),Xc=ce(null),lm=ie(async p=>{if(!xs.current)try{let m=ve(e);if(!m)return;let d=cm.current;if(!d)return;if(d.pushConsent!=="on"){if(d.uncommitted===0)return;xs.current=!0;try{let A=await M3(e,m);if(A.commit?.ok)Xc.current=null;else if(A.commit&&!A.commit.ok){let U=`${A.commit.reason}:${A.commit.detail??""}`;Xc.current!==U&&(Xc.current=U,f({kind:"note",tone:"warn",text:`\u26A0 Couldn't save your docs work to git \u2014 ${io(A.commit.reason,A.commit.detail)}`}))}}finally{xs.current=!1}return}if(d.uncommitted===0&&d.unpushed===0&&!p.pull)return;xs.current=!0;try{let{lines:A,changed:U}=await Ol(e,m);for(let O of A)O.tone==="warn"||O.tone==="error"?f({kind:"note",tone:O.tone,text:O.text}):O.text.includes("\u2B07")&&f({kind:"note",tone:O.tone,text:O.text});U&&G(O=>O+1)}finally{xs.current=!1}}catch{}},[e,f]),Eo=ie(p=>{let m=Ze(e,s);return m.ok?!0:(f({kind:"note",tone:"warn",text:m.reason}),So.current=p,le("/login"),!1)},[e,s,f,le]),[Rs,Qc]=pe(null),cm=ce(null),um=ce(null),$t=ie((p,m)=>{let d=Ti(e,s,{claudeMissing:Uf(t).state==="missing",allowAutoAudit:p,genreUnknown:Xe.current,pendingAnswer:_e.current,lastCommand:um.current});return cm.current=d?.handoff??null,d?Ci(d,{header:m,pickable:!0,scaleFor:g=>rn(e,g)}):{kind:"idle"}},[e,s,t]),Jc=ce(Date.now()),Ss=ce(Pv()),dm=ce(0),[pm,hm]=pe(null),Cs=ce(!0),yr=ce(!1),Xi=ce(0),Ps=ce(0);ct(()=>{let p=setInterval(()=>{if(Cs.current){Xi.current=0,Ps.current=0;return}if(!P)try{if(!ls(h0(e)))return;if(en(e).status==="current"){Cs.current=!0,Xi.current=0,Ps.current=0;let d=yr.current?`\u2713 Your builder finished the protocol update (v${We}) \u2014 the dev\u2194docs hand-off is current again. Here\u2019s where your docs stand:`:"\u2713 Your builder finished the hand-off \u2014 the architecture brief is in. I can read this repo now and write accurate docs. Here\u2019s where things stand:",g=$t(!1,d),A=g.kind==="recommend"?g.rec:null;Yc(null),A?.note?$n(A,{tone:"ok"}):(f({kind:"note",tone:"ok",text:`${d}${A?.lead?` ${os(A.lead)}`:""}`}),A?.lead||A?.picker?$n(A,{silent:!0}):yr.current||st("write the docs for this repo")),G(U=>U+1);return}if(yr.current)return;Xi.current+=1;let m=Xi.current;if((m===4||m%15===0)&&Ps.current<3){Ps.current+=1;let d=Ps.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";f({kind:"note",tone:"info",text:Pn(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${d}`:`\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.${d}`})}}catch{}},4e3);return()=>clearInterval(p)},[e,P,f,$t,$n,st]),ct(()=>{let p=Kf??Di(e);if(!P){vc(0),is(`${Rc} ${p}`);return}vc(3);let m=0;is(`${xc[0]} ${p}`);let d=setInterval(()=>{m=(m+1)%xc.length,is(`${xc[m]} ${p}`)},400);return()=>clearInterval(d)},[P,e,Kf]),ct(()=>()=>vc(0),[]),ct(()=>{let p=performance.now(),m=[],d=(b,$)=>{let v=performance.now();try{return $()}finally{let k=Math.round(performance.now()-v);k>=80&&m.push(`${b}: ${k}ms`)}};f({kind:"banner",info:d("banner",()=>n6(e,o,t,s))});let g=Uf(t).state==="missing";if(g&&f({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.
|
|
507
|
+
${WO}
|
|
508
508
|
Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!ve(e)){f({kind:"note",tone:"info",text:`Welcome! This repo isn't set up for d360-writer yet \u2014 three steps and you're writing docs:
|
|
509
|
-
${
|
|
510
|
-
`)}),
|
|
511
|
-
`)}),b.reopenedForRedaction&&f({kind:"note",tone:"warn",text:
|
|
509
|
+
${k0}`}),le(g?"/doctor":"/init");return}g&&le("/doctor");try{let b=pt(e,s);b.project.projectId&&XO(b.name,b.project.projectId,b.project.projectName);let $=po(b.name,b.project.projectId),v=Ze(e,s);$&&or($)&&$.refreshToken?qO({profile:b.name,connection:b.connection,projectId:b.project.projectId,projectName:b.project.projectName}).then(()=>{f({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),G(k=>k+1)}).catch(k=>{if(k instanceof VO&&k.transient){f({kind:"note",tone:"warn",text:"Couldn't reach Document360 to renew your session \u2014 your sign-in is intact, and I'll try again on your next command."});return}f({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 sign in again with /login."}),le("/login"),G(C=>C+1)}):v.ok||(f({kind:"note",tone:"warn",text:v.reason}),le("/login"))}catch{}try{let b=ve(e),$=pt(e,s),v=po($.name,$.project.projectId);b&&v&&!or(v)&&mf(e,b.authoritativeSourceFiles)&&!gf(e,s)&&(f({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),le("/scope"))}catch{}try{let b=d("resolve-genre",()=>c3(e));b.persisted&&b.appType?f({kind:"note",tone:"ok",text:`\u2713 Detected a ${b.appType} app \u2014 enabled the ${b.appType}-doc-playbook (change with /genre, or edit .d360-writer/config.json).`}):b.source==="unknown"&&ve(e)&&(Xe.current=!0)}catch{}let A=en(e);try{if(d("reconcile-devhints",()=>xa(e)),A.status!=="current"&&!Pn(e)){let b=Ra(e);b.length&&(f({kind:"note",tone:"warn",text:b.join(`
|
|
510
|
+
`)}),xn(Oo()),Cs.current=!1,yr.current=!1)}}catch{}try{let b=d("reconcile-feedback",()=>E3(e));b.archived>0&&f({kind:"note",tone:"ok",text:`\u2713 Tidied ${b.archived} resolved item${b.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${b.open>0?`; ${b.open} still open`:""}.`})}catch{}try{let b=d("upgrade-actions",()=>N3(e));b.applied.length>0&&f({kind:"note",tone:"warn",text:ba(b.applied).join(`
|
|
511
|
+
`)}),b.reopenedForRedaction&&f({kind:"note",tone:"warn",text:ka(b.reopenedForRedaction)})}catch{}let U=d("ready-decision",()=>$t(!0));U.kind==="autoAudit"?(f({kind:"note",tone:"info",text:U.note}),Ks({cwd:e,profileName:s}).then(b=>{if(b.kind==="audit-blocked"){Te(b.note,{kind:"cmd",cmd:b.lead.cmd,reason:b.lead.reason},"warn");return}b.kind!=="forward-to-agent"||!b.prompt||Se(b.prompt,{display:b.display,quietUser:!0}).then($=>{if($.producedNothing)return;let v=il(e,s);if(v){Te(v.note,{kind:"cmd",cmd:_r.cmd,reason:_r.reason},"warn"),G(k=>k+1);return}Ri(e,s),G(k=>k+1)})})):U.kind==="recommend"&&$n(U.rec);let O=Math.round(performance.now()-p);O>=800&&O3({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${O}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${m.length?m.join(`
|
|
512
512
|
`):"no single phase \u226580ms"}
|
|
513
|
-
cwd: ${e}`}),
|
|
514
|
-
|
|
515
|
-
${
|
|
516
|
-
`)}),le(
|
|
517
|
-
`)}),v||(O={retryable:
|
|
518
|
-
`)}),[f]),
|
|
519
|
-
`)});let F=A.stop();if(
|
|
520
|
-
`)}),
|
|
521
|
-
`)}),le(
|
|
522
|
-
`)}),le("/allow-prod");return}T(!0);try{let g=await
|
|
523
|
-
`)}),g.blocked.length>0){let U=
|
|
524
|
-
`):`${E}Authored specs \u2014 ${C}/${k.results.length} batches ok.${F}`}),
|
|
513
|
+
cwd: ${e}`}),zc(),lm({pull:!0})},[]),ct(()=>{let p=setInterval(()=>{zc()},h6);return()=>clearInterval(p)},[zc]),ct(()=>{let p=setInterval(()=>{try{let m=Date.now(),d=Pf(m,Jc.current);if(dm.current+=1,d&&dm.current%Math.round(3e5/6e4)!==0)return;let g=e6(e),A=Ss.current,U=g===A.fingerprint&&A.counts?A.counts:on(e),O=Av({now:m,lastInputAt:Jc.current,fingerprint:g,counts:U,occupied:P||Q||ye.length>0||y!==""||Fn||Ie.current.length>0,prev:A});if(Ss.current=O.memory,hm(O.waiting),O.speak&&Qe.current===null){f({kind:"note",tone:"info",text:Nv(O.speak)});let b=$t(!1);b.kind==="recommend"&&$n(b.rec,{silent:!0})}}catch{}},6e4);return()=>clearInterval(p)},[e,P,Q,ye.length,y,Fn,f,$t,$n]),ct(()=>{if(P||Q||ee.current||$s&&!Ro.current||ne!==null||ye.length>0||y!==""||Wn!==null||Ie.current.length>0||lr.current||Fn)return;let p=$t(!1);if(p.kind==="recommend"&&(p.rec.lead||p.rec.picker||p.rec.menu.length>0)){$n(p.rec,{silent:!0});let m=p.rec.lead,d=m?rs(m):p.rec.restKind?`rest:${p.rec.restKind}`:null;d&&d!==Vi.current&&(Vi.current=d,p.rec.settled&&f({kind:"note",tone:"ok",text:p.rec.settled}),m&&f({kind:"note",tone:"info",text:os(m)}))}lm({pull:!1})},[P,Q,ne,ye,y,Wn,Fn,B,$t,ho]);let Ts=ie((p,m)=>{let d=Qe.current;if(Qe.current=null,Bi.current=!1,Hi.current=!1,!d)return;let g=Math.max(0,Math.round((Date.now()-d.startedAt)/1e3)),A={ran:d.ran,parked:m,spentUsd:Math.max(0,Lt-d.stepStartedSpend),budgetUsd:jc(ve(e)),seconds:g,reason:p};for(let O of wv(A))f({kind:"note",tone:O.tone,text:O.text});try{let O=new Date().toISOString().replace(/[:.]/g,"-"),b=ji(e,a3,"auto-runs");_O(b,{recursive:!0}),Zv(ji(b,`${O}.md`),bv(A,new Date().toISOString()),"utf8")}catch{}let U=m.find(O=>O.cmd)?.cmd;U&&le(U),em(null),G(O=>O+1)},[e,f,Lt,le]);ct(()=>{if(!$s||Ro.current||Hi.current||P||Q||ye.length>0||y!==""||Wn!==null||Ie.current.length>0||lr.current||Fn)return;let p=Qe.current;if(p?.stopping){Ts({kind:"stopped",how:"manual"},p.parked);return}let m=$t(!1);if(m.kind!=="recommend")return;let d=p??{ran:[],parked:[],spentUsd:0,startedAt:Date.now(),stopping:!1,stepStartedSpend:Lt},g=Hc.current,A=Sv(m.rec,{ran:d.ran,parked:d.parked,spentUsd:Math.max(0,Lt-d.stepStartedSpend),...d.ran.length>0?{lastLeadKey:d.ran[d.ran.length-1]??null}:{},...g?{lastClosedItsTarget:tn(g)}:{}},{budgetUsd:jc(ve(e))});if(A.kind==="stop"){if(!p&&A.reason.kind!=="onlyBlocked")return;if(!p){let b=m.rec.lead?rs(m.rec.lead):"blocked";if(Bc.current===b)return;Bc.current=b}Qe.current=d,Ts(A.reason,A.parked);return}if(!Bi.current){let b=jc(ve(e)),$=E=>{try{return E()}catch{return null}},v=A.kind==="run"?A.cmd:`\u201C${A.text}\u201D`,k=A.kind==="run"?$(()=>Rk(e,A.cmd)):null,C=A.kind==="run"?$(()=>Cv(m.rec,A.cmd,E=>rn(e,E)))??[]:[];Wi({firstCmd:v,scale:A.kind==="run"?$(()=>rn(e,A.cmd)):null,upcoming:C,budgetUsd:b,overBudget:k!==null&&k>b});return}let U=A.kind==="run"?A.cmd:A.text;d.parked=A.parked,d.ran=[...d.ran,U],Qe.current=d,Hc.current=null,f({kind:"block",text:Z(oe("\u25B6",`Auto mode, step ${d.ran.length}: ${U}`))}),em({step:d.ran.length,cmd:U,startedAt:d.startedAt,spentUsd:Math.max(0,Lt-d.stepStartedSpend),budgetUsd:jc(ve(e))}),Bc.current=null,Hi.current=!0,N(!0),(A.kind==="run"?jo(A.cmd):Se(A.text,{display:A.text,quietUser:!0}).then(()=>{})).finally(()=>{Hi.current=!1,N(!1)})},[$s,P,Q,ye,y,Wn,Fn,B,$t,Ts]),ct(()=>{let p=null,m=null,d=()=>{p&&clearTimeout(p),p=setTimeout(()=>{p=null;let g=ot.columns??80,A=`${g}x${ot.rows??24}`;if(A===sm.current)return;let U=g<(im.current??g);sm.current=A,im.current=g,I0(O=>O+1),U&&(m&&clearTimeout(m),m=setTimeout(()=>{m=null;let O=Math.max(8,(ot.rows??24)-2);console.log("\x1B[?2026h\x1B[H\x1B[2J"+Mw(de.current,rt(),O)+"\x1B[?2026l")},80))},400)};return ot.on("resize",d),()=>{p&&clearTimeout(p),m&&clearTimeout(m),ot.off("resize",d)}},[ot,rt]);let yt=Math.max(20,(ot.columns??80)-1),fm=Nc(()=>r6(e,s),[e,s,B]),Zc=(()=>{if(fo)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(rr!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${rr?` v${rr}`:""}\u2026`,isSetup:!0};if(nm)return{text:lv(nm),isSetup:!0};if(Rs)return{text:"\u{1F6E0} press \u2303y to copy the d360-writer feedback \u2014 then send it to the team (Teams / Slack / email)\u2026",isSetup:!0};if(Wn)return L0?{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 \u2303y to copy the prompt \u2014 then paste it into your coding agent\u2026",isSetup:!0};if(pm)return{text:jv(pm),isSetup:!0};if(Ie.current.length>0){let g=Ie.current.length,A=Ie.current[0].mode;return A==="local-only"?{text:"l publish yours over the portal \xB7 s skip \xB7 anything else cancels\u2026",isSetup:!0}:A==="conflict"?{text:g>1?`l keep local \xB7 p take portal \xB7 s skip \xB7 la/pa/sa for all ${g}\u2026`:"l keep local \xB7 p take portal \xB7 s skip \xB7 anything else cancels\u2026",isSetup:!0}:{text:g>1?`y to write \xB7 n to skip \xB7 ya/na for all ${g}\u2026`:"y to write \xB7 n to skip \xB7 anything else cancels\u2026",isSetup:!0}}let p=ve(e);if(!p)return{text:"Run /init to set up this repo (or /help)\u2026",isSetup:!0};let m=ji(e,(p.docsDir??Wf).replace(/\/+$/,"")),d=(()=>{try{return ls(m)&&MO(m).length>0}catch{return!1}})();try{let g=pt(e,s),A=po(g.name,g.project.projectId);if(!(!!A&&!(or(A)&&!A.refreshToken)))return{text:`Sign in with /login (profile "${g.name}")\u2026`,isSetup:!0};if(!g.project.projectId)return{text:"Sign in to Document360 to pick your project\u2026",isSetup:!0};if(!g.project.workspaceId&&!d)return{text:"Pick a workspace with /workspace\u2026",isSetup:!0}}catch{}return d?{text:s6,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),Rn=Cw(y),eu=Rn.length>0&&!P,O0=12,ln=xf(ot.rows),M0=ot.rows??24,mm=xf(ot.rows,{max:O0}),Qi=Math.min(sr,Math.max(0,Rn.length-1)),No=$c(Rn.length,Qi,mm).start,tu=Rn.slice(No,No+mm),nu=a!==null?zv(a,8,yt):null,Ji=jt?jt.paths.filter(p=>!jt.query||p.toLowerCase().includes(jt.query.toLowerCase())).slice(0,8):[],Zi=It?It.sessions.filter(p=>{let m=It.query.toLowerCase();return!m||p.name.toLowerCase().includes(m)||p.firstPrompt.toLowerCase().includes(m)}).slice(0,8):[],Ve=ie((p,m)=>{De.current?.close(),De.current=e0({cwd:e,resume:p,profileName:m??s,allowProdWrites:gn.current}),p||(nt.current={uuid:null,firstPrompt:null,titleFired:!1},go(null)),To(0),Ao(0)},[e,s]),gm=ie((p,m,d)=>{if(x0.test(p))try{let g=pt(e,s),A=typeof m.project_id=="string"&&m.project_id||g.project.projectId,U=gc(m,d),O=[],b=bc(m,d),$=b?`${b} \u2014 `:"",v=yc(d);p.endsWith("publish_article")&&v&&O.push(`${$}Live: ${v}`);let k=wc(d);k?O.push(`${$}Preview: ${k}`):U&&A&&O.push(`${$}Preview: ${mc(g.connection.portalUrl,A,U,g.project.languageCode??"en")}`),O.length>0&&f({kind:"link",lines:O})}catch{}},[e,s,f]),Se=ie(async(p,m)=>{At(!0),ee.current=!1,Ee.current=!1,_e.current=null,Jt(),ke([]),$o(null),Yc(null);let d=tt.current;if(m?.display?.startsWith("/"))try{let j=za(e,m.display);j&&(p=`${p}
|
|
514
|
+
|
|
515
|
+
${j}`)}catch{}m?.quietUser||f({kind:"user",text:m?.echoDisplay&&m.display?m.display:p});let g=nt.current;g.firstPrompt||(g.firstPrompt=m?.display??p),Vt.current=Date.now(),qt(0),T(!0),fs.current.clear(),Mc.current=null;let A="",U=!1,O=!1,b=!1,$=!1,v="",k={num:0,closed:!1,cueSeen:!1},C=null,E=()=>{C||(C=setTimeout(()=>{C=null,l(v.length>0?v:null)},60))},F=()=>{C&&clearTimeout(C),C=null,l(null)},_=(j=!1)=>{let{head:z,keep:I}=Xv(v,j);z.trim()&&f({kind:"assistant",text:vf(z.trimEnd(),k)}),v=I,F()};try{for await(let j of De.current.send(p))if(j.type==="session"){if(!g.uuid){g.uuid=j.sessionId;let z=new Date().toISOString(),I=Uc.current,W=I??e3(g.firstPrompt??"session");t3({uuid:j.sessionId,name:W,renamed:!!I,titled:!1,cwd:e,firstPrompt:g.firstPrompt??"",createdAt:z,updatedAt:z}),go(W),Uc.current=null}}else if(j.type==="text"){v+=j.delta,A+=j.delta;let z=Qv(v);if(z>0){let I=v.slice(0,z).trimEnd();I&&f({kind:"assistant",text:vf(I,k)}),v=v.slice(z)}E(),qt(I=>I+j.delta.length)}else if(j.type==="tool"){U=!0,x0.test(j.name)&&(O=!0);let I=(be=>typeof be=="string"&&be?be.replace(/\\/g,"/").toLowerCase():null)(j.input.file_path??j.input.notebook_path),W=["Edit","Write","MultiEdit","NotebookEdit"].includes(j.name),q=j.name==="Read"&&I!==null&&I===Yf.current;Yf.current=W?I:null;let re=Fi.current,fe=re?null:Yv(j.name,j.input),me=re?null:dc(j.name,j.input,e,s);if(fe)Vc.current.push(fe);else if(me){_();let be=me.repeat&&me.articleKey&&me.articleKey===Mc.current?me.repeat:me;Mc.current=me.articleKey??null,f({kind:"doc",verb:me.verb,title:be.title,category:be.category,note:be.note,...me.loud?{loud:me.loud}:{}}),fs.current.set(j.id,{name:j.name,input:j.input,doc:!0,keepResult:me.keepResult})}else if(q)_(),f({kind:"tool",title:"Read",sep:"",arg:"re-checking the file it just edited"});else{let be=hc(j.name,j.input,e);be&&(_(),f({kind:"tool",title:be.title,sep:be.sep,arg:be.arg}),fs.current.set(j.id,{name:j.name,input:j.input}))}}else if(j.type==="article_diff"){let z=Ft(j.oldContent,j.newContent,rt());z&&(_(),f({kind:"diff",added:z.added,removed:z.removed,lines:z.lines,hidden:z.hidden}))}else if(j.type==="gate_blocked")Gc.current={path:j.path,commands:j.commands};else if(j.type==="tool_result"){j.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(j.output)&&(ws.current=!0);let z=fs.current.get(j.id);if(z){fs.current.delete(j.id),_();let W=z.doc&&!z.keepResult&&!j.isError?{lines:[],hidden:0}:fc(j.output,4,j.isError||Fi.current?void 0:z.name,z.input),q=j.isError&&cv(z.name,j.output);W.lines.length>0&&f({kind:"tool-result",lines:W.lines,hidden:W.hidden,isError:j.isError&&!q}),j.isError||gm(z.name,z.input,j.output)}}else if(j.type==="result"){_(!0),To(q=>q+j.outputTokens),Ao(q=>Math.max(q,j.sessionCostUsd));let z=j.inputTokens+j.cacheReadTokens+j.cacheCreationTokens;if(f({kind:"done",seconds:Math.round((Date.now()-Vt.current)/1e3),tokens:j.outputTokens,costUsd:j.costUsd,sessionCostUsd:Math.max(Lt,j.sessionCostUsd),ok:j.ok,...z>0?{inTokens:z,cachedPct:Math.round(j.cacheReadTokens/z*100)}:{}}),!b&&!U&&!A.trim()&&!gs.current&&($=!0,f({kind:"note",tone:"warn",text:"The agent produced no output \u2014 nothing ran this turn. Run /doctor: it runs a real turn with your skills and tools and reports what failed. Claude Code\u2019s own error was written either way \u2014 /logs shows it, and offers to copy it for the team."})),j.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(A))try{let q=f0(e);if(ls(q)){let re=Dc(q,"utf8").trim();re&&(Qc(re),f({kind:"note",tone:"info",text:"\u{1F6E0} Press \u2303y to copy this feedback \u2014 send it to the d360-writer team (Teams / Slack / email)."}))}}catch{}let I=j.ok?ov(A):null;Ee.current=I!==null,_e.current=I;let W=j.ok?rv(A,i6):null;if(W)Pe(!1),Ne.current=!1,ke(W);else if(j.ok&&(k.cueSeen||(I?.options??0)>=2))Pe(!0),Ne.current=!0,ke([]);else if(I)ke([]);else{let q=j.ok?Lv(A,Go.map(re=>re.name)):[];if(q.length>0)le(q[0]);else if(j.ok&&A.trim()&&!Ee.current){let re=$t(!1);re.kind==="recommend"&&(re.rec.lead||re.rec.picker)||s3(p,A,e).then(fe=>{fe&&tt.current===d&&st(fe)}).catch(()=>{})}}if(g.uuid&&(Df(g.uuid),!g.titleFired)){g.titleFired=!0;let q=g.uuid,re=g.firstPrompt;re&&n0(re,e).then(fe=>{fe&&(ZO(q,fe),go(fe))}).catch(()=>{})}}else j.type==="error"&&(_(!0),b=!0,j.kind==="auth"&&(ws.current=!0),f(j.kind==="limit"?{kind:"note",text:`\u23F3 ${j.message}`,tone:"warn"}:{kind:"note",text:`agent error: ${j.message}`,tone:"error"}),j.note&&f({kind:"note",text:j.note,tone:"info"}))}finally{if(T(!1),F(),qi(),O)try{let z=Mf(await Of({cwd:e,profileName:s,onRateLimit:I=>Fe(`Document360 rate limit \u2014 waiting ${Math.ceil(I.waitMs/1e3)}s\u2026`)}));z&&f({kind:"note",tone:z.startsWith("\u26A0")?"warn":"info",text:z})}catch{}finally{Fe(null)}G(z=>z+1),nt.current.uuid&&hv(e,nt.current.uuid,de.current),ws.current?(ws.current=!1,bs.current=m?.display??p,st("/login","\u21E5 tab to run /login \u2014 then I\u2019ll re-send your last prompt\u2026")):bs.current=null;let j=Gc.current;if(Gc.current=null,j&&!ws.current&&j.commands.length>0){let z=j.commands[0],I=j.commands.length>1?` \u2014 then ${j.commands[1].split(" ")[0]} for the style errors`:"";st(z,`\u21E5 tab to run ${z.split(" ")[0]}${I}`)}gs.current&&(gs.current=!1,xo.current.length>0&&(f({kind:"note",tone:"info",text:`(${xo.current.length} queued message(s) discarded)`}),xo.current=[],Fc([])),f({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}return{producedNothing:$,handedBack:_e.current!==null}},[e,f,gm,rt,st,le,Jt,$t,qi]),ea=ie(async()=>{try{Fe("Checking Document360 for new reviewer comments\u2026"),await Fl(e,s,{onProgress:(p,m)=>Fe(`Checking Document360 for new reviewer comments\u2026 ${p}/${m}`)})}catch{}finally{Fe(null)}},[e,s]),vt=ie(async(p,m=0,d)=>{let g=Lc(e,p,{allowUnreviewed:d?.skipReview===!0,allowStyleErrors:d?.skipStyle===!0});if(!g.clear){f({kind:"note",tone:"warn",text:_f(g,p.length,{act:"push"}).join(`
|
|
516
|
+
`)}),le(qs(g));return}Vt.current=Date.now(),qt(0),T(!0);let A=new AbortController;Be.current=A;let U={aborted:!1,partitions:0,failed:0,notRun:0,producedNothing:!0},O={retryable:0,stopped:!1,paths:[]},b=async($,v)=>{let k=jf($),C=new Map;for(let re of k)for(let fe of re.paths)C.set(fe,re.label);let E=new Map(k.map(re=>[re.label,re.paths.length])),F=new Set,_=Date.now();$e({verb:"Pushing",unit:"article",total:$.length,done:0,active:[],rows:tr(k),tools:0,chars:0,lastAt:Date.now(),startedAt:_,agentless:!0}),f({kind:"note",tone:"info",text:v?`Resolving cross-links in ${$.length} article${$.length===1?"":"s"} whose targets were saved this run (second pass)\u2026 (esc to stop)`:`Pushing ${$.length} article${$.length===1?"":"s"} to Document360 (${w3} at a time)\u2026 (esc to stop)`});let j=await g3({cwd:e,profileName:s,paths:$,...d?.allowUnpullable===!0?{allowUnpullable:!0}:{},signal:A.signal,onEvent:re=>{let fe=re.type==="article_done"?re.result.path:re.type==="article_failed"?re.failure.path:re.path,me=C.get(fe);if(!me)return;if(re.type==="article_start"){$e(J=>J&&!J.active.includes(me)?{...J,active:[...J.active,me],rows:at(J.rows,me,"active"),lastAt:Date.now()}:J&&{...J,lastAt:Date.now()});return}re.type==="article_failed"&&F.add(me);let be=(E.get(me)??1)-1;E.set(me,be),$e(J=>{if(!J)return J;let xe={...J,done:J.done+1,rows:Pc(J.rows,me),lastAt:Date.now()};return be>0?xe:{...xe,active:xe.active.filter(Oe=>Oe!==me),rows:at(xe.rows,me,F.has(me)?"failed":"done")}})}}),z=j.aborted||!!j.stopped,I=fd(e,$,s);v||(U={aborted:z,partitions:k.length,failed:j.failed.length,notRun:j.notRun.length,producedNothing:j.pushed.length===0,verifiedComplete:I>=$.length,leftBehind:m});let W=j.pushed.length>0;f({kind:"note",tone:z||j.failed.length>0||!W?"warn":"ok",text:(z?"Stopped. ":"")+md(j,{recorded:I,elapsedMs:Date.now()-_,docsRoot:I3(e),...v?{}:{conflictsSkipped:m,unreadableSkipped:d?.unreadableSkipped??0},...d?.scope?{scope:d.scope}:{}}).join(`
|
|
517
|
+
`)}),v||(O={retryable:j.failed.filter(re=>!re.refused).length,stopped:!!j.stopped,paths:j.failed.map(re=>re.path)});let q=hd(e,s);if(q&&f({kind:"note",tone:"info",text:q}),W){let re=Mr(e,s);re&&f({kind:"note",tone:"info",text:re})}if(!z&&W){try{let fe=await Of({cwd:e,profileName:s,onRateLimit:be=>Fe(`Document360 rate limit \u2014 waiting ${Math.ceil(be.waitMs/1e3)}s\u2026`)}),me=Mf(fe);me?f({kind:"note",tone:me.startsWith("\u26A0")?"warn":"info",text:me}):fe.skipped&&f({kind:"note",tone:"warn",text:`Order sync skipped: ${fe.skipped}`})}catch(fe){f({kind:"note",tone:"warn",text:`Order sync failed: ${fe.message}`})}finally{Fe(null)}try{let fe=g0(await m0({cwd:e,profileName:s}));fe&&f({kind:"note",tone:"info",text:fe})}catch(fe){f({kind:"note",tone:"warn",text:`Related-articles sync failed: ${fe.message}`})}let re=await Hs(e,s);re&&f({kind:"note",tone:"info",text:re})}return z};try{let $=await b(p,!1);if(!$){let k=await gd(e,s,p,O.paths);k.length>0&&await b(k,!0),Sn(d?.scope?`/push ${d.scope}`:"/push --all",U)}let v=Ce("/push",d?.scope?"":"--all",d?.scope);if(O.retryable>0)Te(null,{kind:"cmd",cmd:v,reason:O.stopped?"Document360 stopped answering \u2014 your articles are unchanged, so this picks up where the run left off":`${O.retryable} article${O.retryable===1?"":"s"} could not be saved \u2014 this retries them`},"warn");else if(!$&&m>0)Te(null,{kind:"cmd",cmd:"/resolve",reason:`${m} conflict${m===1?"":"s"} still need settling \u2014 they were left untouched`},"warn");else if(!$){let k=pd(e,{scope:d?.scope,profileName:s});k&&Te(null,{kind:"cmd",...k})}}catch($){f({kind:"note",tone:"error",text:`Publish run failed: ${$.message}`})}finally{Be.current=null,$e(null),await ea(),T(!1),G($=>$+1)}},[e,s,f,t,Te,ea]),wr=ie(p=>f({kind:"block",text:p.join(`
|
|
518
|
+
`)}),[f]),ym=ie(async()=>{let p=Rs!=null,m=Rs??Wn;if(!m){f({kind:"note",tone:"info",text:"Nothing is waiting to be copied. /feedback copies this repo\u2019s open d360-writer feedback anytime."});return}let d=await ev(m,p?"feedback":"handoff-prompt");f({kind:"note",tone:d.copied?"ok":"warn",text:d.copied?p?"\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.":d.path?`Couldn\u2019t reach your clipboard, so the text is in ${d.path} \u2014 open that and copy it from there.`:"Couldn\u2019t reach your clipboard, and could not save the text either. /logs has the details."}),d.copied&&p&&Qc(null),d.copied&&!p&&am(!0)},[Rs,Wn,f]),br=ie((p,m,d,g,A)=>{let U=Wt(p,m,d,Date.now(),A);f({kind:"done",seconds:U.seconds,tokens:U.outputTokens,costUsd:U.costUsd,ok:g,...U.activeSeconds!==void 0?{activeSeconds:U.activeSeconds}:{},sessionCostUsd:Lt+d,...U.inputTokens>0?{inTokens:U.inputTokens,...U.cachedPct!==void 0?{cachedPct:U.cachedPct}:{}}:{}})},[f,Lt]),ta=ie(async p=>{let m=Oi(e,"standard");Vt.current=Date.now(),qt(0),T(!0);let d=new AbortController;Be.current=d;let g=Date.now(),A=new Fr;A.start(),$e({verb:p.verb,unit:"article",total:p.partitions.length,done:0,active:[],rows:tr(p.partitions),tools:0,chars:0,lastAt:Date.now(),startedAt:g}),f({kind:"note",tone:"info",text:`${p.headline} on ${m.model}\u2026 (esc to stop)`});let U=!0,O=[],b=!1,$={aborted:!1,partitions:0,failed:0,notRun:0,producedNothing:!0},v=new Set;try{for await(let k of Li({cwd:e,partitions:p.partitions,promptFor:p.promptFor,concurrency:p.concurrency,profileName:s,allowProdWrites:gn.current,model:m.model,signal:d.signal,scope:p.scope}))if(k.type==="partition_status")k.status==="running"?$e(C=>C&&{...C,active:[...C.active,k.label],rows:at(C.rows,k.label,"active"),lastAt:Date.now()}):$e(C=>C&&{...C,active:C.active.filter(E=>E!==k.label),done:C.done+1,rows:at(C.rows,k.label,k.status==="done"?"done":"failed"),lastAt:Date.now()});else if(k.type==="partition_stalled"){let C=ss(k);$e(E=>E&&C?{...E,stalledNote:C}:E)}else if(k.type==="partition_event"){let C=null;if(k.event.type==="tool"){let E=Af(k.event.name,k.event.input,p.partitions[k.index]?.paths??[]);E&&!v.has(E)&&(v.add(E),C=k.label)}$e(E=>{if(!E)return E;let F={...E,lastAt:Date.now()};return k.event.type==="tool"?F.tools=E.tools+1:k.event.type==="text"&&(F.chars=E.chars+k.event.delta.length),C&&(F.rows=Pc(F.rows,C)),F})}else if(k.type==="run_done"){Ao(_=>_+k.totalCostUsd),To(_=>_+k.results.reduce((j,z)=>j+z.outputTokens,0));let C=If(p.partitions,k.results);U=!!k.allEmpty||!!k.blocked,b=!!k.aborted,$={aborted:!!k.aborted,partitions:p.partitions.length,failed:C.failed.length,notRun:C.notRun.length,...k.blocked?{blocked:k.blocked}:{},...k.allEmpty?{allEmpty:!0}:{},...k.bailedEmpty?{bailedEmpty:!0}:{}};let E=[`${k.aborted?"Stopped. ":""}${k.results.length-C.failed.length}/${p.partitions.length} batches ${p.doneNoun}.`,...C.failed.length?[`\u26A0 ${C.failed.length} not ${p.doneNoun} \u2014 their articles are unchanged: ${C.failed.map(_=>_.label).join(", ")}`]:[],...C.notRun.length?[`\u26A0 ${C.notRun.length} batch${C.notRun.length===1?"":"es"} never started \u2014 their articles are untouched.`]:[],...k.blocked?[`\u26A0 ${k.blocked}`]:[],...k.allEmpty?[p.emptyNote??"\u26A0 No turn produced any work this run \u2014 nothing was changed."]:[],...p.caveatLines??[]];f({kind:"note",tone:k.aborted||C.failed.length||C.notRun.length||k.blocked||k.allEmpty?"warn":"ok",text:E.join(`
|
|
519
|
+
`)});let F=A.stop();if(br(g,k.results,k.totalCostUsd,!b&&!U&&!C.failed.length,F.activeSeconds),p.calibrateAs){let _=k.results.filter(j=>j.ok).length;m3(e,p.calibrateAs,{articles:C.covered.length,waves:Math.ceil(_/Math.max(1,p.concurrency)),seconds:F.activeSeconds,costUsd:k.totalCostUsd})}U||(O=C.covered)}}catch(k){f({kind:"note",tone:"error",text:`${p.verb} failed: ${k.message}`})}finally{A.stop(),Be.current=null,$e(null),T(!1),G(k=>k+1)}return{producedNothing:U,covered:O,aborted:b,outcome:$}},[e,s,f,br]),_0=ie(async(p,m,d,g=!1)=>{let A=await ta({partitions:p.partitions,promptFor:p.promptFor,concurrency:lo,verb:"Reviewing",doneNoun:"reviewed",headline:`Reviewing ${p.articles} article${p.articles===1?"":"s"} in ${p.partitions.length} batches (\u2264${lo} editors at once)${m?", applying fixes as they go":", report only"}`+(()=>{let O=Xl(e,"/review",p.articles,p.partitions.length);return O?` \xB7 ${O}`:""})(),caveatLines:Hh(p,g),emptyNote:"\u26A0 No editor produced any work this run \u2014 nothing was reviewed or changed.",calibrateAs:"/review",scope:"review"}),U=null;if(m&&A.covered.length>0&&(U=Xo(e,A.covered,d,s),U.earned.length>0))try{us(e,U.earned,wt("review"))}catch{}return{producedNothing:A.producedNothing,aborted:A.aborted,outcome:A.outcome,evidence:U}},[e,ta]),ou=ie(async(p,m)=>{if(p.length===0)return;let d=p.reduce((v,k)=>v+k.threads.length,0),g=new Map,A=p.map(v=>(g.set(v.label,v),{label:v.label,paths:v.path?[v.path]:[]})),U=Oi(e,"standard");Vt.current=Date.now(),qt(0),T(!0);let O=new AbortController;Be.current=O;let b=Date.now(),$=Lf(e);$e({verb:"Answering",unit:"article",total:A.length,done:0,active:[],rows:tr(A),tools:0,chars:0,lastAt:Date.now(),startedAt:b}),f({kind:"note",tone:"info",text:`Answering ${d} comment${d===1?"":"s"} across ${A.length} article${A.length===1?"":"s"} (\u2264${mi} agents at once) on ${U.model}. Each article is fixed, pushed to Document360 as a draft, then answered in the thread${m.resolve?" and resolved":" \u2014 the threads stay open for your reviewers to close"}\u2026 (esc to stop)`});try{for await(let v of Li({cwd:e,partitions:A,promptFor:k=>{let C=g.get(k.label);return ch({articleId:C.articleId,label:C.label,path:C.path,count:C.threads.length,resolve:m.resolve})},concurrency:mi,profileName:s,allowProdWrites:gn.current,allowCommentResolve:m.resolve,model:U.model,signal:O.signal}))if(v.type==="partition_status")v.status==="running"?$e(k=>k&&{...k,active:[...k.active,v.label],rows:at(k.rows,v.label,"active"),lastAt:Date.now()}):$e(k=>k&&{...k,active:k.active.filter(C=>C!==v.label),done:k.done+1,rows:at(k.rows,v.label,v.status==="done"?"done":"failed"),lastAt:Date.now()});else if(v.type==="partition_stalled"){let k=ss(v);$e(C=>C&&k?{...C,stalledNote:k}:C)}else if(v.type==="partition_event")$e(k=>{if(!k)return k;let C={...k,lastAt:Date.now()};return v.event.type==="tool"?C.tools=k.tools+1:v.event.type==="text"&&(C.chars=k.chars+v.event.delta.length),C});else if(v.type==="run_done"){Ao(I=>I+v.totalCostUsd),To(I=>I+v.results.reduce((W,q)=>W+q.outputTokens,0));let k=If(A,v.results),C=v.results.length-k.failed.length,E=v.aborted?"Stopped. ":"",F=[...k.failed.map(I=>I.label),...k.notRun.map(I=>I.label)],_=[`${E}${C}/${A.length} article${A.length===1?"":"s"} answered.`,...F.length?[`\u26A0 ${F.length} left untouched (their threads are still open, which is correct \u2014 nothing was promised to those reviewers): ${F.join(", ")}`]:[],...v.blocked?[`\u26A0 ${v.blocked}`]:[],...v.allEmpty?["\u26A0 No agent produced any work this run \u2014 nothing was changed or answered."]:[]];f({kind:"note",tone:v.aborted||F.length||v.blocked||v.allEmpty?"warn":"ok",text:_.join(`
|
|
520
|
+
`)}),br(b,v.results,v.totalCostUsd,!v.aborted&&!F.length&&!v.blocked&&!v.allEmpty);let j=new Set(F),z=[...m.rest??[],...p.filter(I=>j.has(I.label))];if(z.length>0&&!v.aborted&&m.report){let I=z.reduce((q,re)=>q+re.threads.length,0);f({kind:"note",tone:"info",text:`${I} comment${I===1?"":"s"} on ${z.length} other article${z.length===1?"":"s"} still open \u2014 pick the next one, or esc to stop here.`});let W={...m.report,threads:z.flatMap(q=>q.threads)};wr(gi(W,{width:rt()})),bn({cursor:0,rows:Bl(z),groups:z,resolve:m.resolve,report:W})}else if(z.length>0&&!v.aborted){let I=z.map(q=>q.path).filter(q=>!!q),W=I.length===z.length?Mt(I):void 0;le(W?I.length===1?`/comments ${W}`:`/comments --scope ${W}`:"/comments")}Sn("/comments --answer",{aborted:v.aborted,partitions:A.length,failed:k.failed.length,notRun:k.notRun.length,...v.blocked?{blocked:v.blocked}:{},...v.allEmpty?{allEmpty:!0}:{},leftBehind:(m.rest??[]).length})}}catch(v){f({kind:"note",tone:"error",text:`Answering comments failed: ${v.message}`})}finally{let k=Yo(e,$,"","/comments").changed.length;k>0&&f({kind:"note",tone:"info",text:`${k} article${k===1?"":"s"} changed, and that new text has not been read by an editor \u2014 ${k===1?"it":"they"} can go live once /review has been over ${k===1?"it":"them"}.`}),Be.current=null,$e(null),T(!1),G(C=>C+1)}},[e,s,f,Te,le,wr,rt]),ru=ie(async(p,m)=>{if(!(m?.skipReview===!0||m?.skipStyle===!0)){let g=Lc(e,[p],{});if(!g.clear){f({kind:"note",tone:"warn",text:_f(g,1,{act:"push"}).join(`
|
|
521
|
+
`)}),le(qs(g,p));return}}await vt([p],0,{skipReview:m?.skipReview,skipStyle:m?.skipStyle,scope:p});try{let g=await tl(e,s,p.replace(/\\/g,"/"));g.length>0&&($o(`Related articles not yet saved to Document360 (${g.length}):`),ke([`/push --related ${p}`,...g.map(A=>`/push ${A}`)]))}catch{}},[e,s,Se,vt]),wm=ie(async(p,m)=>{let d=Rd(e,s,gn.current,p.length);if(d){f({kind:"note",tone:"warn",text:d.join(`
|
|
522
|
+
`)}),le("/allow-prod");return}T(!0);try{let g=await Sd(e,s,p,{skipReview:m.skipReview,skipStyle:m.skipStyle,allowProduction:gn.current,onProgress:(U,O,b)=>Fe(`Publishing ${U+1}/${O} \u2014 ${b}\u2026`)}),A=g.blocked.length+g.failed.length;if(f({kind:"note",tone:A>0?"warn":"ok",text:Cd(g).join(`
|
|
523
|
+
`)}),g.blocked.length>0){let U=Lc(e,g.blocked.map(b=>b.path),{allowUnreviewed:m.skipReview,allowStyleErrors:m.skipStyle,checkScreenshots:!0}),O=sl(e,U,m.scope);O.cmd?le(O.cmd):Te(null,null)}else Te(null,null)}catch(g){f({kind:"note",tone:"error",text:`Publishing failed: ${g.message}`})}finally{Fe(null),await ea(),T(!1),G(g=>g+1)}},[e,s,f,le,Te,ea]),bm=ie(async p=>{try{let m=await Ii({cwd:e,profileName:s}),d=new Set(Wo(e,s)),{clean:g,conflicts:A}=Fo(m.entries,d);if(g.length===0){f({kind:"note",tone:"info",text:"Nothing new to save \u2014 everything is already up to date on Document360."});return}await vt(g.map(U=>U.path),A.length,{skipReview:p?.skipReview,skipStyle:p?.skipStyle,unreadableSkipped:A.filter(U=>d.has(U.path)).length})}catch(m){f({kind:"note",tone:"warn",text:`Couldn\u2019t check what to save (${m.message}) \u2014 your articles are written; run /push when ready.`})}},[e,s,vt]),Sn=ie((p,m)=>{if(m&&(Hc.current=m),!(m&&!tn(m)))for(let d of Ke(e,p))f({kind:"note",tone:"ok",text:d})},[e,f]),km=ie(async(p,m)=>{let g=S3(p,3),A=Oi(e,"standard"),U=new Map,O=new Map;for(let k of p){let C=_o(e,k),E=Bu(e,k,C);if(E&&U.set(k,E),C!==null){let F=td(C);F.length>0&&O.set(k,F)}}Vt.current=Date.now(),qt(0),T(!0);let b=new AbortController;Be.current=b;let $=Date.now();$e({verb:"Authoring",unit:"spec",total:g.length,done:0,active:[],rows:tr(g),tools:0,chars:0,lastAt:Date.now(),startedAt:$}),f({kind:"note",tone:"info",text:`Authoring ${p.length} screenshot spec${p.length===1?"":"s"} in ${g.length} batch${g.length===1?"":"es"} (\u22646 agents at once) on ${A.model}${A.forced?" (forced)":""}\u2026 (esc to stop)`});let v=!1;try{for await(let k of Li({cwd:e,partitions:g,promptFor:C=>Py(C,U,O),concurrency:6,profileName:s,allowProdWrites:gn.current,model:A.model,signal:b.signal}))if(k.type==="partition_status")k.status==="running"?$e(C=>C&&{...C,active:[...C.active,k.label],rows:at(C.rows,k.label,"active"),lastAt:Date.now()}):$e(C=>C&&{...C,active:C.active.filter(E=>E!==k.label),done:C.done+1,rows:at(C.rows,k.label,k.status==="done"?"done":"failed"),lastAt:Date.now()});else if(k.type==="partition_stalled"){let C=ss(k);$e(E=>E&&C?{...E,stalledNote:C}:E)}else if(k.type==="partition_event")$e(C=>{if(!C)return C;let E={...C,lastAt:Date.now()};return k.event.type==="tool"?E.tools=C.tools+1:k.event.type==="text"&&(E.chars=C.chars+k.event.delta.length),E});else if(k.type==="run_done"){Ao(j=>j+k.totalCostUsd),To(j=>j+k.results.reduce((z,I)=>z+I.outputTokens,0));let C=k.results.filter(j=>j.ok).length,E=k.aborted?"Stopped. ":"";v=!k.aborted&&m.setup;let F=k.aborted?"":v?" Refreshing the staging checklist\u2026":` Next: /screenshot capture${m.scope?` ${m.scope}`:" --all"} (or /screenshot checklist first for the staging checklist).`,_=eo(k,"Spec authoring");f({kind:"note",tone:_||k.aborted?"warn":k.ok?"ok":"warn",text:_?_.join(`
|
|
524
|
+
`):`${E}Authored specs \u2014 ${C}/${k.results.length} batches ok.${F}`}),br($,k.results,k.totalCostUsd,!_&&!k.aborted&&k.ok),_&&(le("/doctor"),v=!1),!k.aborted&&k.ok&&!_&&Sn(m.runLine)}}catch(k){f({kind:"note",tone:"error",text:`Spec authoring failed: ${k.message}`})}finally{Be.current=null,$e(null),T(!1),G(k=>k+1)}if(v){let k=await Kr();k.kind==="forward-to-agent"&&k.prompt&&await Se(k.prompt,{display:k.display,quietUser:!0}),Kc()}},[e,s,f,Se,Sn,Kc]),$m=ie(async p=>{let m=Bu(e,p,_o(e,p))??void 0,d=await Va([p],void 0,{prior:m});d.kind==="forward-to-agent"&&d.prompt&&await Se(d.prompt,{display:d.display,quietUser:!0}),py(e,p)&&Te(`Spec ready \u2014 /screenshot capture ${p} takes the screenshot; bare /screenshot picks the next shot.`,{kind:"cmd",cmd:`/screenshot capture ${p}`,reason:""})},[e,Se,Te]),na=ie(async(p,m)=>{if(p.length===0)return{drawn:[],undrawn:[],cliMissing:!1};T(!0);let d=new AbortController;Be.current=d,$e({verb:"Drawing callouts",unit:"screenshot",total:p.length,done:0,active:[],rows:p.map(C=>({label:C,items:1,status:"pending"})),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()});let g=[],A=!1;try{let C=await Bp({cwd:e,ids:p,...m.force?{force:!0}:{},signal:d.signal,onStart:E=>$e(F=>F&&{...F,active:[E],rows:at(F.rows,E,"active"),lastAt:Date.now()}),onDone:(E,F)=>$e(_=>_&&{..._,active:[],done:_.done+1,rows:at(_.rows,E,F==="failed"?"failed":"done"),lastAt:Date.now()})});g=C.results,A=C.cliMissing??!1}catch(C){f({kind:"note",tone:"error",text:`Drawing the callouts failed: ${C.message}`})}finally{Be.current=null,$e(null),T(!1),G(C=>C+1)}if(A)return f({kind:"note",tone:"error",text:"d360-capture is not installed on this machine. Run: npm i -g document360-capture \u2014 then /screenshot annotate."}),{drawn:[],undrawn:p,cliMissing:!0};let U=g.filter(C=>C.outcome==="annotated").map(C=>C.id),O=g.filter(C=>C.outcome==="skipped").map(C=>C.id),b=p.filter(C=>!U.includes(C)&&!O.includes(C));if(f({kind:"note",tone:b.length?"warn":"ok",text:[`\u25C8 ${U.length} drawn`,O.length?`${O.length} already current`:"",b.length?`\u2717 ${b.length} not drawn`:""].filter(Boolean).join(" ")}),b.length>0){let C=Math.max(...b.map(E=>E.length));f({kind:"note",tone:"warn",text:b.map(E=>`\u2717 ${E.padEnd(C)} ${ui(g.find(F=>F.id===E)?.detail)||"no picture was produced"}`).join(`
|
|
525
525
|
`)+`
|
|
526
|
-
${b.length===1?"It has":"They have"} no publishable picture yet. Re-take the shot: /screenshot capture`})}if(m.chainVerify===!1||U.length===0)return{drawn:U,undrawn:b,cliMissing:!1};let $=U.filter(C=>m.verifiedBefore.has(C)).length;if($>
|
|
527
|
-
`)}),{drawn:U,undrawn:b,cliMissing:!1}},[e,f,Te,Se]),
|
|
528
|
-
${
|
|
529
|
-
${$}`:"")});let v=Date.now(),k=[];try{for(let W of p){if(A.signal.aborted)break
|
|
530
|
-
${W}`).join("")});let
|
|
531
|
-
`)}),F.length>0){let W=Math.max(...F.map(q=>q.id.length));f({kind:"note",tone:"error",text:F.map(q=>`\u2717 ${q.id.padEnd(W)} ${
|
|
532
|
-
`)})}
|
|
533
|
-
`)});return}let I=
|
|
534
|
-
`)})}catch{}},U=
|
|
535
|
-
`)}),
|
|
526
|
+
${b.length===1?"It has":"They have"} no publishable picture yet. Re-take the shot: /screenshot capture`})}if(m.chainVerify===!1||U.length===0)return{drawn:U,undrawn:b,cliMissing:!1};let $=U.filter(C=>m.verifiedBefore.has(C)).length;if($>Il){let C=Ub({results:g,voidedVerdicts:$,...m.scope?{scope:m.scope}:{}});return C&&Te(`${C.glyph} ${C.cmd} ${C.why}`,{kind:"cmd",cmd:C.cmd,reason:""},"warn"),{drawn:U,undrawn:b,cliMissing:!1}}let v=U.filter(C=>!m.verifiedBefore.has(C)||$>0);if(v.length===0)return{drawn:U,undrawn:b,cliMissing:!1};f({kind:"note",tone:"info",text:so(v.length)}),await Se(hn(e,v),{display:"/screenshot verify",quietUser:!0});let k=Vr(e,v);return k.length>0&&f({kind:"note",tone:"info",text:k.join(`
|
|
527
|
+
`)}),{drawn:U,undrawn:b,cliMissing:!1}},[e,f,Te,Se]),As=ie(async(p,m)=>{if(!Vo(e)){await Se(Mp(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(!Ab(e)){f({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)"}),T(!0),Fe("Waiting for you to finish logging in (browser window)\u2026");let W=new AbortController;Be.current=W;let q;try{q=await Eb({cwd:e,signal:W.signal})}catch(re){f({kind:"note",tone:"error",text:`Could not launch the login: ${re.message}`});return}finally{Be.current=null,Fe(null),T(!1)}if(q.exitCode!==0){Op(q.exitCode,q.output)?f({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(q.output)?f({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."}):f({kind:"note",tone:W.signal.aborted?"warn":"error",text:W.signal.aborted?"Login cancelled \u2014 nothing saved.":`Login did not complete:
|
|
528
|
+
${Ip(q.output)}`});return}f({kind:"note",tone:"ok",text:"\u2713 Login saved \u2014 continuing with the capture."})}let d=new Map(p.map(W=>[W,wy(e,W)])),g=0;if(p.length>1){let W=p.filter(q=>d.get(q).mutates);if(W.length>0&&(g=W.length,p=p.filter(q=>!d.get(q).mutates),p.length===0)){f({kind:"note",tone:"warn",text:`\u26A0 All ${W.length} spec${W.length===1?"":"s"} in scope write real data, so a bulk run has nothing to do. Run one deliberately: /screenshot capture ${W[0]}`});return}}else if(p.length===1&&d.get(p[0]).mutates){let W=d.get(p[0]),q=Nb(e);f({kind:"note",tone:"warn",text:`\u26A0 This capture performs a REAL write in your app${W.what?`: ${yy(W.what)}`:W.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. `+(q.production?`This profile is PRODUCTION \u2014 the write lands in the LIVE tenant${q.url?` (${q.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.")})}T(!0);let A=new AbortController;Be.current=A;let U=p.map(W=>({label:W,items:1,status:"pending"}));$e({verb:"Capturing",unit:"screenshot",total:p.length,done:0,active:[],rows:U,tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()});let O=Tn(e),b=Object.keys(O.shots).length>0,$=Db(m?.heldBackBlocked??[],g);f({kind:"note",tone:"info",text:`Capturing ${p.length} screenshot${p.length===1?"":"s"} with d360-capture (a real browser drives your app)\u2026 (esc to stop)`+($?`
|
|
529
|
+
${$}`:"")});let v=Date.now(),k=[];try{for(let W of p){if(A.signal.aborted)break;$e(be=>be&&{...be,active:[W],rows:at(be.rows,W,"active"),lastAt:Date.now()});let{exitCode:q,output:re}=await Lp({cwd:e,id:W,signal:A.signal,stdio:"pipe"});if(Op(q,re)){f({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 fe=A.signal.aborted&&q!==0?"failed":jp(e,W,q,v),me=fe==="captured"?void 0:fe==="skipped"?Pb(re)??"a data prerequisite isn't met \u2014 the spec's skip reason names what to stage":Tb(re);k.push({id:W,outcome:fe,detail:me}),$e(be=>be&&{...be,active:[],done:be.done+1,rows:at(be.rows,W,fe==="captured"?"done":"failed"),lastAt:Date.now()})}}catch(W){f({kind:"note",tone:"error",text:`Capture run failed: ${W.message}`})}finally{Be.current=null,$e(null),T(!1),G(W=>W+1)}if(k.length===0)return;let C=k.filter(W=>W.outcome==="captured"),E=k.filter(W=>W.outcome==="skipped"),F=k.filter(W=>W.outcome==="failed"),_=p.length-k.length;f({kind:"note",tone:F.length?"warn":C.length?"ok":"info",text:[`\u2713 ${C.length} captured`,E.length?`\u2298 ${E.length} blocked`:"",F.length?`\u2717 ${F.length} broken`:"",_?`${_} not run (stopped)`:""].filter(Boolean).join(" ")+` ${k.length} run${g>0?` \xB7 ${g} held back`:""}`+Lb(jb(O,k),b).map(W=>`
|
|
530
|
+
${W}`).join("")});let j=Ib(E);if(j.length>0&&f({kind:"note",tone:"info",text:j.join(`
|
|
531
|
+
`)}),F.length>0){let W=Math.max(...F.map(q=>q.id.length));f({kind:"note",tone:"error",text:F.map(q=>`\u2717 ${q.id.padEnd(W)} ${ui(q.detail)}`).join(`
|
|
532
|
+
`)})}Ia(e,k.map(W=>({id:W.id,outcome:W.outcome,reason:W.detail,specSource:_o(e,W.id)})),new Date().toISOString()),k.length===p.length&&F.length===0&&E.length===0&&Sn(m?.runLine);let z=[];if(C.length>0&&jl()){let W=await na(C.map(q=>q.id),{verifiedBefore:new Set});if(W.cliMissing||(z=W.undrawn,W.drawn.length>0))return}else if(C.length>0){f({kind:"note",tone:"info",text:so(C.length)}),await Se(hn(e,C.map(q=>q.id)),{display:"/screenshot verify",quietUser:!0});let W=Vr(e,C.map(q=>q.id));W.length>0&&f({kind:"note",tone:"info",text:W.join(`
|
|
533
|
+
`)});return}let I=Ob({results:k,ids:p,articles:Mb(e,C.map(W=>W.id)),...z.length>0?{unannotated:z}:{}});I&&Te(I.note,{kind:"cmd",cmd:I.cmd,reason:""},I.tone)},[e,f,Te,Se,Sn,na]),su=ie(p=>{let m=po(p);if(!m||or(m)&&!m.refreshToken)return null;let d={...ps(m.idToken)??{},...ps(m.accessToken)??{}};return d.email??d.preferred_username??"signed in"},[]),oa=ie((p,m)=>{if(m){let d=ve(e);d&&(d.defaultProfile=p,o0(d,e))}i(p),Ve(void 0,p),f({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${p}"${m?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),su(p)||(f({kind:"note",tone:"warn",text:`Profile "${p}" is not signed in \u2014 sign in with /login.`}),le("/login")),G(d=>d+1)},[e,f,Ve,su,le]),iu=ie(async(p,m,d,g)=>{let A=async()=>{try{let O=pt(e,p),b=await p3({profile:O.name,connection:O.connection,projectId:m,projectName:O.project.projectName},{cwd:e,profile:O.name,projectId:m,workspaceId:d}),$=h3(b);$.length>0&&f({kind:"note",tone:b.kind==="swept"&&b.hidden==="confirmed"?"ok":"warn",text:$.join(`
|
|
534
|
+
`)})}catch{}},U=E$(e,p);if(U==="fresh"){A(),f({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),f({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:"}),f({kind:"note",tone:"info",text:Ar(Tr(e)).join(`
|
|
535
|
+
`)}),xn(Oo()),Cs.current=en(e).status==="current",yr.current=Pn(e),f({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.`});return}if(U==="unpushed"){let O=p;try{O=pt(e,p).connection.portalUrl}catch{}f({kind:"note",tone:"ok",text:`\u2713 Connected. ${p} \xB7 ${g} \xB7 ${O}`}),Fe("Checking what this portal already holds\u2026"),await A(),Fe("Comparing your articles with this portal\u2026");try{let b=await Ii({cwd:e,profileName:p}),$=d3(e,p).length,v=b.counts["untracked-remote"]??0;f({kind:"note",tone:"ok",text:v===0?`\u2713 This portal has no articles yet.
|
|
536
536
|
Your ${$} ${$===1?"is":"are"} written here and none of them are on it.`:`\u2713 This portal already holds ${v} article${v===1?"":"s"}.
|
|
537
537
|
Nothing is pushed until you decide which of yours are already there.
|
|
538
|
-
/pull --status shows the comparison article by article.`})}catch{}finally{Fe(null),G(b=>b+1)}return}G(O=>O+1)},[e,f,
|
|
539
|
-
`)}),
|
|
540
|
-
${
|
|
541
|
-
`)}),b.copyText&&
|
|
542
|
-
${v.pick.lead}`}),
|
|
543
|
-
`)}),v.restart&&(Ve(),f({kind:"note",tone:"ok",text:"\u2713 Agent restarted \u2014 it now writes to the new rules."})),v.editorial){let k=
|
|
544
|
-
`),{kind:"cmd",cmd:v.editorial.cmd,reason:"it reads every article the new guide flagged and rewrites it",...k?{detail:k}:{}})}G(k=>k+1);return}let $=await
|
|
545
|
-
`)}),v&&(Ve(),f({kind:"note",tone:"ok",text:"\u2713 Agent restarted \u2014 it now writes to your house rules."})))}G(v=>v+1);return}case"genre":{let b=ve(e)?.appType??null;(await
|
|
546
|
-
`)});return}case"mcp":await
|
|
547
|
-
`)}),b&&f({kind:"note",tone:"warn",text:`\u26A0 ${b.why} \u2014 ${b.cmd} moves this repo.`});return}
|
|
548
|
-
${F.path} \xB7 ${F.articleId?`updates article ${F.articleId}`:"would be created as a new article"}${_}`}),F.missingShots.length>0&&f({kind:"note",tone:"warn",text:`\u26A0 ${F.missingShots.length} screenshot${F.missingShots.length===1?"":"s"} not taken yet \u2014 the description publishes instead: ${F.missingShots.join(", ")}`}),f({kind:"note",tone:"info",text:F.body}),f({kind:"note",tone:"info",text:`Nothing was sent. /push ${F.path} saves it as a draft.`}),le(`/push ${F.path}`)}catch(F){f({kind:"note",tone:"error",text:F.message})}return}if(g.includes("--screenshots")||g.includes("--shots")){let E=g.find(I=>!I.startsWith("--")),F=He(e),_=
|
|
538
|
+
/pull --status shows the comparison article by article.`})}catch{}finally{Fe(null),G(b=>b+1)}return}G(O=>O+1)},[e,f,xn]),ra=ie((p,m,d)=>{la(e,p,m,d.id,d.name),f({kind:"note",tone:"ok",text:`Switched to workspace "${d.name??d.id}" (agent restarted).`}),Ve(),iu(p,m,d.id,d.name??d.id)},[e,f,Ve,iu]),sa=ie(async p=>{let m;try{m=await js(e,p)}catch{f({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),le("/workspace");return}if(m.workspaces.length===0){f({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let d=m.workspaces.filter(A=>(A.workspace_type??"").toLowerCase()!=="apidocumentation"),g=d.length>0?d:m.workspaces;if(g.length===1){let A=g[0],U=m.workspaces.length-g.length;f({kind:"note",tone:"ok",text:`Selected the "${A.name??A.id}" workspace${U>0?" (skipped the API-documentation workspace)":""}.`}),ra(m.profile,m.projectId,A);return}f({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${g.length} available).`}),le("/workspace")},[e,f,ra,le]),ia=ie((p,m)=>{ca(e,p,m.id,m.name),f({kind:"note",tone:"ok",text:`Project set to "${m.name??m.id}" (agent restarted).`}),Ve(),sa(p)},[e,f,Ve,sa]),vm=ie(async p=>{let m;try{m=pt(e,p)}catch{return}if(m.project.workspaceId){let d=m.project.workspaceName??m.project.workspaceId;m.project.projectId&&await iu(m.name,m.project.projectId,m.project.workspaceId,d);return}if(m.project.projectId){if(!m.project.projectName)try{let{projects:d}=await Cn(e,m.name),g=d.find(A=>A.id===m.project.projectId);g?.name&&L3(e,m.name,{projectName:g.name})}catch{}await sa(m.name);return}try{let{projects:d}=await Cn(e,m.name);if(d.length===1){let g=d[0];f({kind:"note",tone:"ok",text:`Using your Document360 project "${g.name??g.id}".`}),ia(m.name,{id:g.id,name:g.name});return}if(d.length>1){let g=d.map(A=>({id:A.id,name:A.name??A.id,sub:A.sub_domain}));f({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),wo({cursor:0,current:-1,rows:g,profile:m.name,environment:m.connection.name});return}}catch{}f({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),le("/project")},[e,f,sa,ia,le]),kr=ie(()=>{let p=Ie.current[0];if(!p)return;if(Jt(),p.mode==="local-only"){f({kind:"note",tone:"info",text:`\u25CF ${p.title??p.path} (${p.path})`});for(let U of pl())f({kind:"note",tone:"warn",text:`\u26A0 ${U}`});f({kind:"note",tone:"info",text:hl()}),f({kind:"note",tone:"info",text:hw()});return}let{plan:m,mode:d}=p;f({kind:"note",tone:"info",text:`\u25CF ${m.title} (${m.path})`});for(let U of m.notes)f({kind:"note",tone:"warn",text:`\u26A0 ${U}`});m.overwritesLocalChanges&&d==="pull"&&f({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let g=Ft(m.oldContent,m.newContent,rt(),Ur);f(g?{kind:"diff",added:g.added,removed:g.removed,lines:g.lines,hidden:g.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."});let A=Ie.current.length;d==="conflict"?(f({kind:"note",tone:"warn",text:"Conflict \u2014 edited both here and on the portal (diff shows local \u2192 portal)."}),f({kind:"note",tone:"info",text:"Keep local (publish, overwrites portal) \xB7 take Portal (overwrites local) \xB7 Skip?"}),f({kind:"note",tone:"info",text:A>1?`(l/p/s \xB7 la/pa/sa for all ${A} \u2014 anything else stops, keeping your answers so far)`:"(l/p/s \u2014 anything else stops, keeping your answers so far)"})):f({kind:"note",tone:"info",text:A>1?`Write ${m.path}? (y/n \xB7 ya/na for all ${A} \u2014 anything else cancels)`:`Write ${m.path}? (y/n \u2014 anything else cancels)`})},[f,rt,Jt]),Do=ie(()=>{if(Ie.current.length>0){kr();return}let p=Kt.current;Kt.current=[];let m=yn.current;yn.current=[];for(let d of fl(m))f({kind:"note",tone:"warn",text:`\u26A0 ${d}`});p.length>0?(f({kind:"note",tone:"info",text:`Saving ${p.length} kept-local article${p.length===1?"":"s"} over the portal\u2026`}),vt(p,0,{allowUnpullable:!0})):m.length>0||le("/pull")},[kr,f,vt,le]),au=ie(p=>{let m=kc(p);if(!m)return!1;let d=Ie.current.splice(0),g=d.length;if(m==="local"){for(let A of d)Kt.current.push(o6(A));f({kind:"note",tone:"info",text:`Keeping local for all ${g} \u2014 will publish ${g===1?"it":"them"} over the portal.`})}else if(m==="portal"){let A=0;for(let U of d){if(U.mode==="local-only"){f({kind:"note",tone:"warn",text:`\u26A0 ${Id(U.path)}`}),yn.current.push(U.path);continue}try{Ic({cwd:e,profileName:s},U.plan),A++}catch(O){f({kind:"note",tone:"error",text:`Take-portal failed for ${U.plan.path}: ${O.message}`})}}f({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${A} article${A===1?"":"s"} (local overwritten, sync base advanced).`})}else{for(let A of d)A.mode==="local-only"&&yn.current.push(A.path);f({kind:"note",tone:"info",text:`Skipped all ${g} \u2014 still conflict${g===1?"":"s"}.`})}return Do(),!0},[e,s,Do,f]),xm=ie(p=>{if(Ie.current.length===0)return!1;let m=p.trim(),d=m.toLowerCase(),g=Ie.current[0];if(g.mode==="local-only"){if(kc(m))return au(m);if(d==="l"||d==="local"||d==="publish")Ie.current.shift(),Kt.current.push(g.path),f({kind:"note",tone:"info",text:`Publishing your copy of ${g.path} over the portal.`});else if(d==="s"||d==="skip")Ie.current.shift(),yn.current.push(g.path),f({kind:"note",tone:"info",text:`Skipped ${g.path} \u2014 still a conflict.`});else{let U=Ie.current.splice(0),O=Kt.current;return Kt.current=[],yn.current=[],f({kind:"note",tone:"info",text:`Resolve canceled. ${U.length} conflict${U.length===1?"":"s"} left untouched.`+(O.length>0?` Saving the ${O.length} article${O.length===1?"":"s"} you already chose to keep - an answer you gave is not undone by stopping.`:"")}),O.length>0&&vt(O,0,{allowUnpullable:!0}),!0}return Do(),!0}if(g.mode==="conflict"){if(kc(m))return au(m);if(d==="l"||d==="local")Ie.current.shift(),Kt.current.push(g.plan.path),f({kind:"note",tone:"info",text:`Keeping local ${g.plan.path} \u2014 will publish over the portal.`});else if(d==="p"||d==="portal"){Ie.current.shift();try{Ic({cwd:e,profileName:s},g.plan),f({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${g.plan.path} (local overwritten, sync base advanced).`})}catch(U){f({kind:"note",tone:"error",text:`Take-portal failed: ${U.message}`})}}else if(d==="s"||d==="skip"||d==="n")Ie.current.shift(),f({kind:"note",tone:"info",text:`Skipped ${g.plan.path} \u2014 still a conflict.`});else{let U=Ie.current.length;Ie.current=[];let O=Kt.current;return Kt.current=[],yn.current=[],f({kind:"note",tone:"info",text:`Resolve canceled. ${U} conflict${U===1?"":"s"} left untouched.`+(O.length>0?` Saving the ${O.length} article${O.length===1?"":"s"} you already chose to keep - an answer you gave is not undone by stopping.`:"")}),O.length>0&&vt(O,0,{allowUnpullable:!0}),!0}return Do(),!0}let A=iv(m);if(A){let U=Ie.current.splice(0);if(A==="skip")f({kind:"note",tone:"info",text:`Skipped all ${U.length} article${U.length===1?"":"s"}.`});else{let O=0;for(let b of U){if(b.mode==="local-only"){f({kind:"note",tone:"warn",text:`\u26A0 ${Id(b.path)}`});continue}try{Ic({cwd:e,profileName:s},b.plan),O++}catch($){f({kind:"note",tone:"error",text:`Pull failed for ${b.plan.path}: ${$.message}`})}}f({kind:"note",tone:"ok",text:`\u2713 Pulled ${O} article${O===1?"":"s"} (sync base advanced).`})}return Do(),!0}if(d==="y"||d==="yes"){let{plan:U}=g;Ie.current.shift();try{Ic({cwd:e,profileName:s},U),f({kind:"note",tone:"ok",text:`\u2713 Pulled ${U.path} (sync base advanced).`})}catch(O){f({kind:"note",tone:"error",text:`Pull failed: ${O.message}`})}}else if(d==="n"||d==="no")Ie.current.shift(),f({kind:"note",tone:"info",text:`Skipped ${g.plan.path}.`});else{let U=Ie.current.length;return Ie.current=[],f({kind:"note",tone:"info",text:`Pull cancelled (${U} article(s) left untouched).`}),!0}return Do(),!0},[e,s,Do,f,au]),lu=ie(async p=>{f({kind:"note",tone:"info",text:"Checking Document360 for conflicts\u2026"});try{let m=await Ii({cwd:e,profileName:s}),d=p?.replace(/\\/g,"/"),g=dl(e,s,m.entries,Bo(m.entries).map(O=>O.path));if(d){if(!g.includes(d)){f({kind:"note",tone:"ok",text:`${d} isn\u2019t waiting on a decision \u2014 nothing to resolve.`});return}g=[d]}if(g.length===0){f({kind:"note",tone:"ok",text:"\u2713 No conflicts \u2014 local and Document360 agree on every tracked article."});return}let A=[];for(let O of g)try{A.push({plan:await a0({cwd:e,profileName:s,relPath:O}),mode:"conflict"})}catch(b){l0(b)?A.push({mode:"local-only",path:O,title:c0(e,O)}):f({kind:"note",tone:"error",text:`Could not load ${O} from Document360: ${b.message}`})}if(A.length===0)return;let U=A.some(O=>O.mode!=="local-only");f({kind:"note",tone:"info",text:U?`Resolving ${A.length} conflict${A.length===1?"":"s"} \u2014 for each: keep local, take portal, or skip.`:`Resolving ${A.length} conflict${A.length===1?"":"s"} \u2014 for each: publish your copy over the portal, or skip.`}),Ie.current=A,Kt.current=[],yn.current=[],kr()}catch(m){f({kind:"note",tone:"error",text:`Could not compute sync status: ${m.message}`})}},[e,s,f,kr]),Rm=ie(p=>{let m=lr.current;if(!m)return!1;if(lr.current=null,Jt(),p.trim()!==m.repoName)return f({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:d,failed:g}=gh(e,m.targets);f({kind:"note",tone:g.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${d.length} item${d.length===1?"":"s"}. The repo is back to its original state.`});for(let A of g)f({kind:"note",tone:"error",text:` \u2717 ${A.path}: ${A.error}`});return m.hadDevhints&&(f({kind:"note",tone:"warn",text:Sa().join(`
|
|
539
|
+
`)}),xn(Nu())),f({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
|
|
540
|
+
${k0}`}),le("/init"),At(!1),!0},[e,f,xn,Jt,le]),jo=ie(async p=>{let m=p.slice(1).trim().split(/\s+/),d=(m[0]??"").toLowerCase(),g=m.slice(1);if(um.current=p.trim(),At(!0),oi(g)&&["write","lint","check","review","reorder"].includes(d)){let b=ni(e,s);if(b.length===0){f({kind:"note",tone:"warn",text:"No categories yet \u2014 author some articles first, then scope to one."});return}let $=v=>d==="write"?`/write ${Yw(g,v).join(" ")}`.trim():`/${d} ${[v,...g.filter(k=>k!=="--scope")].join(" ")}`.trim();if(b.length===1){jo($(b[0].token));return}ko({cursor:0,rows:b,run:v=>{jo($(v))}});return}if(ro(d,g)){let b=d==="write"&&ri(g).rewrite,$=d==="write"?yp(e,d0(e),{rewrite:b}):ni(e,s);if($.length>1){let v=g.filter(q=>q.startsWith("--")).join(" "),k=q=>q==="--blocked"?`/${d} --blocked${v?` ${v}`:""}`.trim():`/${d}${q?` ${d==="write"?`--scope ${q}`:q}`:""}${v?` ${v}`:""} ${q?"":"--all"}`.replace(/\s+/g," ").trim(),C=$.reduce((q,re)=>q+re.count,0),E={token:"",label:d==="review"?`Everything \u2014 all ${C} articles + structure (IA) review`:d==="reorder"?`Everything \u2014 reorder all ${$.length} categories`:b?`Everything \u2014 rewrite all ${C} planned articles`:`Everything \u2014 write all ${C} pending article${C===1?"":"s"}`,count:C},F=d==="review"?_h(e):[],_=F.length>0&&F.length<C?[{token:"--blocked",label:`Only what needs review \u2014 ${F.length} article${F.length===1?"":"s"} publishing is blocked on`,count:F.length}]:[],j=d==="review"?Uh(e):[],z=j.length>F.length&&j.length<C?[{token:"--stale",label:`Everything the current editor hasn\u2019t read \u2014 ${j.length} article${j.length===1?"":"s"}`,count:j.length}]:[],I=d==="write"?`Write which articles? (counts = ${b?"articles to regenerate":"still to write"})`:d==="review"?"Review what? (counts = articles)":"Reorder what?";ko({cursor:0,rows:(q=>d==="review"||d==="write"?q.map(re=>{let fe=(()=>{try{return xk(e,k(re.token))}catch{return null}})();return fe?{...re,label:`${re.label} \xB7 ${fe}`}:re}):q)([..._,...z,E,...$]),run:q=>{jo(k(q))},title:I});return}}let A=async b=>{let $=Ep(b);if(!Vo(e)){await Se(Mp(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if($.mode==="single"){await As([$.id],{runLine:[`/screenshot capture ${$.id}`,`/capture ${$.id}`]});return}if($.mode==="failed"){let k=Np(e,di(e).rows);if(k.length===0){f({kind:"note",tone:"info",text:"No broken specs to re-run \u2014 /screenshot list shows where things stand."}),le("/screenshot list");return}await As(k);return}if($.mode==="blocked"){let{blocked:k,rows:C}=di(e);if(k.length===0){f({kind:"note",tone:"info",text:"No shots are waiting on app data \u2014 /screenshot list shows where things stand."}),le("/screenshot list");return}let E=Fs(C.filter(F=>F.state==="blocked")).length;f({kind:"note",tone:"info",text:`Re-running ${k.length} shot${k.length===1?"":"s"} that skipped on missing data last run.`+(E>0?` If you haven't staged ${E===1?"it":"those "+E+" things"} yet, ${k.length===1?"it":"they"} will skip again \u2014 /screenshot list has the worklist.`:"")}),await As(k,{runLine:["/screenshot capture --blocked","/screenshot capture --all --retry-blocked"]});return}if($.mode==="all"||$.mode==="scope"){let k=$.mode==="scope"?$.scope:void 0,{ready:C,captured:E,blocked:F,rows:_}=di(e,k),j=[...C,...E,...$.retryBlocked?F:[]];if(j.length===0&&F.length>0&&!$.retryBlocked){let I=k?`/screenshot capture ${k} --retry-blocked`:"/screenshot capture --blocked";Te(`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 ${I}.`,{kind:"cmd",cmd:"/screenshot list",reason:""},"warn");return}if(j.length===0){f({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),le("/screenshot");return}if(!$.retryBlocked){let I=k?`/screenshot capture ${k} --retry-blocked`:"/screenshot capture --blocked",W=Dp(_.filter(q=>q.state==="blocked"),I);W&&f({kind:"note",tone:"info",text:W})}let z=$.mode==="scope"?[`/screenshot capture ${$.scope}`,`/capture ${$.scope}`]:["/screenshot capture --all","/capture --all"];await As(j,{runLine:z,...$.retryBlocked?{}:{heldBackBlocked:_.filter(I=>I.state==="blocked")}});return}let v=Cb(He(e));if(v.length===0){f({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),le("/screenshot");return}bo({cursor:0,rows:v,title:"Capture screenshots \u2014 pick what to shoot:"})},U=async b=>{let $=Up(b);if(!Vo(e)){f({kind:"note",tone:"info",text:"Screenshot capture is not set up in this repo yet. Run /screenshot capture and it will walk you through it."}),le("/screenshot capture");return}let v=Rt();if(!jl(v)){f({kind:"note",tone:"info",text:Wp(v)}),le("/update");return}let k=$.mode==="scope"?$.scope:void 0,{pending:C,done:E,rows:F}=Fp(e,k),_=$.mode==="all"||$.mode==="scope"?$.force:!1,j=$.mode==="single"?[$.id]:_?[...C,...E]:C;if(j.length===0){f({kind:"note",tone:"info",text:E.length>0?`Every shot${k?` under ${k}`:""} is already drawn on. To re-draw them anyway (after a wording or style change): /screenshot annotate --all --force`:"No shots have been taken yet \u2014 /screenshot capture takes them first."}),le(E.length>0?"/screenshot annotate --all --force":"/screenshot capture");return}await na(j,{force:_,scope:k,verifiedBefore:new Set(F.filter(z=>z.state==="verified").map(z=>z.id))})},O=async()=>{let b=await Kr(g,{cwd:e,profileName:s});b.kind==="forward-to-agent"&&b.prompt&&await Se(b.prompt,{display:b.display,quietUser:!0}),Kc()};switch(d){case"help":Po({tab:0,scroll:0});return;case"exit":case"quit":De.current?.close(),r();return;case"clear":Ve(),de.current=[],gt.current={printed:[],armed:[],printedAt:gr.current},At(!1),Jt(),console.log("\x1B[?2026h\x1B[H\x1B[2J\x1B[3J\x1B[?2026l"),f({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let b;try{b=pt(e,s)}catch($){f({kind:"note",tone:"error",text:$.message});return}f({kind:"note",tone:"info",text:`Profile "${b.name}" \u2192 ${b.connection.name} (${b.connection.apiUrl})${b.production?` ${Ye}`:""}`}),D(!0);try{let $=await BO(b.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},C=>f({kind:"note",tone:"info",text:C})),v=HO(b.name,$);GO(v),await ku(v,b.name,C=>f({kind:"note",tone:"info",text:C}));let k=t0(v);if(k){let C=pt(e,s).project;await bu(b.name,k,C.projectId===k?C.projectName:void 0)}if(f({kind:"note",tone:"ok",text:`\u2713 Logged in to "${b.name}" as ${da(po(b.name,k??void 0)??v)}`}),await vm(s),!So.current){let C=Ze(e,s);C.ok||(f({kind:"note",tone:"warn",text:C.reason}),le("/login"))}if(So.current){let C=So.current;So.current=null;let E=Ze(e,s);E.ok?(f({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 tab to run ${C}.`}),le(C)):(f({kind:"note",tone:"warn",text:`${E.reason} (then ${C}.)`}),le("/login"),So.current=C)}else bs.current&&(st(bs.current,"\u21E5 tab to re-send your last prompt\u2026"),bs.current=null)}catch($){if(f({kind:"note",tone:"error",text:`Login failed: ${$.message}`}),!Da(e,s)){let v=So.current;f({kind:"note",tone:"warn",text:`Your Document360 session still isn't working, so nothing here can reach your portal${v?` \u2014 ${v} is still waiting`:""}. Run /login to try again.`}),le("/login")}}finally{D(!1),G($=>$+1)}return}case"allow-prod":{let b=!1;try{b=pt(e,s).production}catch{}if(!b){f({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}gn.current=!0,Ve(),f({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let b=Sp(g.join(" ")),$=nt.current.uuid;if(!$){if(!b){f({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}Uc.current=b,go(b),is(`${Rc} ${b}`),f({kind:"note",tone:"ok",text:`Session will be named "${b}" once it starts.`});return}if(!b){f({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let v=nt.current.firstPrompt??"";n0(v,e).then(k=>{k?(st(`/rename ${k}`),f({kind:"note",tone:"info",text:`Suggestion: "${k}" \u2014 press tab to accept, or type /rename <your name>.`})):f({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>f({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}r3($,b),go(b),is(`${Rc} ${b}`),f({kind:"note",tone:"ok",text:`Session renamed to "${b}".`});return}case"profile":{let b=g[0],$=ve(e);if(!b){let v=Object.entries($?.profiles??{});if(v.length===0){f({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let k=v.map(([_,j])=>{let z=j.connection?.environment,I="";try{I=z?v3(z).portalUrl:j.connection?.portalUrl??""}catch{I=""}return{name:_,env:z??"custom",portalUrl:I,project:j.project?.projectName??j.project?.projectId??null,prod:j.production??x3(z),internal:R3(z),who:su(_)}}),C=s??$?.defaultProfile,E=Math.max(0,k.findIndex(_=>_.name===C)),F={name:"\uFF0B Connect another Document360 environment",env:"",portalUrl:"",project:null,prod:!1,internal:!1,who:null,connect:!0};cr({cursor:E,current:E,rows:[...k,F]});return}if(b==="add"){if(!g[1]){Un({cursor:0,mode:"connect",rows:Gn()});return}let v=Pl(e,g[1],g[2]);if(v){f({kind:"note",tone:"error",text:v});return}let[k,...C]=Tl(g[1],g[2]??g[1]);f({kind:"note",tone:"ok",text:k});for(let E of C)f({kind:"note",tone:"warn",text:E});oa(g[1],!0);return}if(!$?.profiles?.[b]){f({kind:"note",tone:"error",text:`Unknown profile "${b}". Create it: /profile add ${b} <environment>`});return}oa(b,!0);return}case"doctor":await ii(g,{cwd:e,version:o});return;case"logs":{let b=$u();f({kind:"note",tone:"info",text:b.lines.join(`
|
|
541
|
+
`)}),b.copyText&&xn(b.copyText,{hint:b.notable?"\u2328 Press \u2303y to copy this problem report \u2014 then send it to the team (Teams / Slack / email).":"\u2328 Press \u2303y to copy this entry, if you want to send it to the team."});return}case"style-guide":{let b=Ch(e);if(Qr(g).sub==="use"){let v=Ph(e,Qr(g).value);if(v.pick){f({kind:"note",tone:"info",text:`${v.pick.title}
|
|
542
|
+
${v.pick.lead}`}),ke(v.pick.options.map(k=>({cmd:k.cmd,desc:k.desc}))),$o(v.pick.title),Yi.current=v.pick.options.map(k=>k.cmd.trim()),G(k=>k+1);return}if(v.lines.length>0&&f({kind:"note",tone:"info",text:v.lines.join(`
|
|
543
|
+
`)}),v.restart&&(Ve(),f({kind:"note",tone:"ok",text:"\u2713 Agent restarted \u2014 it now writes to the new rules."})),v.editorial){let k=rn(e,v.editorial.cmd);Te(Th(v.editorial).join(`
|
|
544
|
+
`),{kind:"cmd",cmd:v.editorial.cmd,reason:"it reads every article the new guide flagged and rewrites it",...k?{detail:k}:{}})}G(k=>k+1);return}let $=await zl(g,{cwd:e,profileName:s});if(b&&Qr(g).sub==="show"&&Te(null,{kind:"cmd",cmd:"/style-guide keep",reason:""}),$.kind==="clear")Ve(),f({kind:"note",tone:"ok",text:"\u2713 Agent restarted \u2014 it now writes to the new rules."});else if($.kind==="forward-to-agent"){let v=Qr(g).sub==="learn";(await Se($.prompt,{display:$.display,quietUser:!0})).producedNothing||(f({kind:"note",tone:"info",text:(v?yk():wk()).join(`
|
|
545
|
+
`)}),v&&(Ve(),f({kind:"note",tone:"ok",text:"\u2713 Agent restarted \u2014 it now writes to your house rules."})))}G(v=>v+1);return}case"genre":{let b=ve(e)?.appType??null;(await sc(g,{cwd:e})).kind==="clear"&&(ve(e)?.appType??null)!==b&&(Ve(),f({kind:"note",tone:"ok",text:"\u2713 Agent restarted \u2014 the doc-craft playbook for this genre is now loaded."}));try{Xe.current=!(ve(e)?.appType??i0(e))}catch{}G(v=>v+1);return}case"roadmap":{if(g[0]?.toLowerCase()==="done"){let b=Or(e,g.slice(1).join(" ").trim());f({kind:"note",tone:b.ok?"ok":"warn",text:b.line}),G($=>$+1);return}f({kind:"block",text:cd(e,{width:rt(),all:g.some(b=>b.toLowerCase()==="--all")}).join(`
|
|
546
|
+
`)});return}case"mcp":await Aa(g);return;case"init":{if(ve(e)){let b=Hn(e,s);f({kind:"note",tone:"info",text:["This repo is already set up \u2014 /init won\u2019t overwrite it."," Publish somewhere else: /profile, then pick \u201CConnect another Document360 environment\u201D."," The environment lives on the profile, not on your login \u2014 so signing in again never changes it."," Anything else: edit .d360-writer/config.json, or run d360-writer init for the CLI wizard."].join(`
|
|
547
|
+
`)}),b&&f({kind:"note",tone:"warn",text:`\u26A0 ${b.why} \u2014 ${b.cmd} moves this repo.`});return}Un({cursor:0,mode:"init",rows:Gn()});return}case"resume":{let b=g.join(" ").trim(),$=o3(e).filter(C=>C.uuid!==nt.current.uuid);if(!b){if(!$.length){f({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}Co({query:"",cursor:0,sessions:$});return}let v=n3(e,b);if(!v){f({kind:"note",tone:"error",text:`No session matches "${b}".`});return}Ve(v.uuid),nt.current={uuid:v.uuid,firstPrompt:v.firstPrompt,titleFired:!0},go(v.name),Df(v.uuid),de.current=[],gt.current={printed:[],armed:[],printedAt:gr.current};let k=Sf(e,v.uuid);for(let C of k)f(C);f({kind:"note",tone:"ok",text:k.length?`Resumed "${v.name}" \u2014 restored ${k.length} message(s); continue where you left off.`:`Resumed "${v.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let b=g.join(" ").trim(),$;try{$=await js(e,s)}catch(k){f({kind:"note",tone:"error",text:`Could not list workspaces: ${k.message}`});return}if(!b){let k=$.workspaces.map(E=>({id:E.id,name:E.name??E.id,type:E.workspace_type}));if(k.length===0){f({kind:"note",tone:"info",text:"No workspaces in this project."});return}let C=Math.max(0,k.findIndex(E=>E.id===$.current));ur({cursor:C,current:C,rows:k,profile:$.profile,projectId:$.projectId,projectName:$.projectName,environment:$.environment});return}let v=du($.workspaces,b);if(!v){f({kind:"note",tone:"error",text:`No workspace matches "${b}".`});return}ra($.profile,$.projectId,v);return}case"project":{let b=g.join(" ").trim(),$;try{$=await Cn(e,s)}catch(k){f({kind:"note",tone:"error",text:`Could not list projects: ${k.message} (signed in? try /login)`});return}if(!b){let k=$.projects.map(E=>({id:E.id,name:E.name??E.id,sub:E.sub_domain}));if(k.length===0){f({kind:"note",tone:"info",text:"No projects found for this identity."});return}let C=k.findIndex(E=>E.id===$.current);wo({cursor:Math.max(0,C),current:C,rows:k,profile:$.profile,environment:$.environment});return}let v=pu($.projects,b);if(!v){f({kind:"note",tone:"error",text:`No project matches "${b}". Available: ${$.projects.map(k=>k.name??k.id).join(", ")}`});return}ia($.profile,v);return}case"logout":{let b,$,v;try{let _=pt(e,s);b=_.name,$=_.project.projectId,v=_.project.projectName}catch(_){f({kind:"note",tone:"error",text:_.message});return}let k=g.includes("--all-projects"),C=QO(b).filter(_=>{let j=t0(_);return!!j&&j!==$}).length,E=zO(b,k?void 0:$);JO(e,b),Ve(),G(_=>_+1);let F=k||C===0?"":` Your sign-in for ${C} other project${C===1?"":"s"} is untouched (/logout --all-projects clears those too).`;f({kind:"note",tone:E?"ok":"info",text:E?k?`\u2713 Signed out of every Document360 project for "${b}" and cleared this repo's project/workspace selection.`:`\u2713 Signed out of ${v?`"${v}"`:`"${b}"`} and cleared its project/workspace selection.${F}`:`Profile "${b}" was not signed in. Cleared any project/workspace selection.${F}`}),f({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),le("/login");return}case"publish":{if($d(g)){f({kind:"note",tone:"info",text:rl()}),await jo(`/push ${g.join(" ")}`.trim());return}if(!Eo(p.trim()))return;let b=g.find(j=>!j.startsWith("--")),$={skipReview:g.includes(_t),skipStyle:g.includes(y0),...b?{scope:b}:{}};Fe("Checking what is waiting to go live\u2026");let v;try{v=await vd(e,s,b)}catch(j){f({kind:"note",tone:"error",text:`Could not check Document360: ${j.message}`});return}finally{Fe(null)}if(v.length===0){let j=xd(e,s,b);for(let z of j.lines)f({kind:"note",tone:z.startsWith("\u2713")?"ok":"info",text:z});j.ahead>0&&le(Ce("/push","",b));return}let k=Lc(e,v.map(j=>j.path),{allowUnreviewed:$.skipReview,allowStyleErrors:$.skipStyle,checkScreenshots:!0,allowPlaceholders:g.includes(W3)}),C=F3(k),E=v.filter(j=>C.has(j.path)),F=v.filter(j=>!C.has(j.path)),_=sl(e,k,b);if(E.length>0)for(let j of _f(k,v.length,{scope:b,act:"publish",going:F.length,shotFix:_.shotFix}))f({kind:"note",tone:"warn",text:j});if(F.length===0){_.cmd&&le(_.cmd);return}if(v=F,Qe.current&&Bi.current){f({kind:"note",tone:"info",text:`Taking ${v.length} draft${v.length===1?"":"s"} live \u2014 you approved this run when it started.`}),await wm(v,$);return}f({kind:"note",tone:"info",text:`${v.length} draft${v.length===1?" is":"s are"} ahead of what readers see. Pick what goes live:`}),pr({cursor:0,rows:v,opts:$});return}case"push":{if(!Eo(p.trim()))return;let b=g.includes(_t),$=g.includes(y0);if(g.includes("--preview")){let E=g.find(F=>!F.startsWith("--"));if(!E){f({kind:"note",tone:"error",text:"Which article? Use /push --preview <path> \u2014 a preview is per article."});return}try{let F=await y3({cwd:e,profileName:s,relPath:E.replace(/\\/g,"/"),preview:!0}),_=F.shots.length>0?` \xB7 ${F.shots.length} screenshot${F.shots.length===1?"":"s"} embedded`:"";f({kind:"note",tone:"info",text:`${F.title}
|
|
548
|
+
${F.path} \xB7 ${F.articleId?`updates article ${F.articleId}`:"would be created as a new article"}${_}`}),F.missingShots.length>0&&f({kind:"note",tone:"warn",text:`\u26A0 ${F.missingShots.length} screenshot${F.missingShots.length===1?"":"s"} not taken yet \u2014 the description publishes instead: ${F.missingShots.join(", ")}`}),f({kind:"note",tone:"info",text:F.body}),f({kind:"note",tone:"info",text:`Nothing was sent. /push ${F.path} saves it as a draft.`}),le(`/push ${F.path}`)}catch(F){f({kind:"note",tone:"error",text:F.message})}return}if(g.includes("--screenshots")||g.includes("--shots")){let E=g.find(I=>!I.startsWith("--")),F=He(e),_=Wa(F,E);if(_.length===0){let I=F.filter(W=>W.state==="captured").length;f({kind:"note",tone:"info",text:I>0?`${I} screenshot${I===1?" has":"s have"} been taken but the callouts aren't drawn on yet, so there is nothing to embed \u2014 /screenshot annotate finishes ${I===1?"it":"them"}.`:E?`No captured screenshots in ${E} \u2014 /push --screenshots covers the whole knowledge base.`:"No captured screenshots yet \u2014 /screenshot capture first."}),I>0&&le("/screenshot annotate");return}let j=Ba(F,E);j&&f({kind:"note",tone:"warn",text:j});let z=Ha(F);z&&f({kind:"note",tone:"warn",text:z}),f({kind:"note",tone:"info",text:`Re-saving ${_.length} article${_.length===1?"":"s"} with captured screenshots so the images embed\u2026`}),await vt(_,0,{skipReview:b,skipStyle:$,scope:Ce("","--screenshots",E).trim()});return}if(g[0]==="--related"&&g[1]){let E=await tl(e,s,g[1].replace(/\\/g,"/"));if(E.length===0){f({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await vt(E,0,{skipReview:b,skipStyle:$,scope:`--related ${g[1]}`});return}let v=g.filter(E=>!E.startsWith("--"));if(v[0]){await ru(v[0],{skipReview:b,skipStyle:$});return}let k=g.includes("--all"),C=g.includes("--force");f({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let E=await Ii({cwd:e,profileName:s}),F=new Set(Wo(e,s)),{clean:_,conflicts:j}=Fo(E.entries,F),z=j.filter(q=>F.has(q.path)).length,I=k&&C&&j.length>0,W=Qa(E.entries);if(W>0&&f({kind:"note",tone:"warn",text:`\u26A0 ${W} article${W===1?"":"s"} already exist on Document360 but aren\u2019t linked \u2014 left OUT of publish (publishing would duplicate them). Run /catch-up (or ask me to link them) first.`}),j.length>0&&!I&&f({kind:"note",tone:"warn",text:Bs(j.length,z)}),_.length===0&&!I){let q=Mr(e,s);if(q&&f({kind:"note",tone:"info",text:q}),j.length>0){le("/resolve");return}f({kind:"note",tone:"ok",text:W>0?"\u2713 Nothing else is ahead of Document360 to save.":"\u2713 Nothing is ahead of Document360 \u2014 nothing to save."});let re=E.counts["unknown-base"]??0;re>0&&f({kind:"note",tone:"info",text:`(${re} article(s) have no sync base yet \u2014 /push <path> saves one anyway if you need it.)`}),Fe("Reconciling structure on Document360 (order + related articles)\u2026");try{let fe=await Of({cwd:e,profileName:s,onRateLimit:J=>Fe(`Document360 rate limit \u2014 waiting ${Math.ceil(J.waitMs/1e3)}s\u2026`)}),me=g0(await m0({cwd:e,profileName:s})),be=Mf(fe);be?f({kind:"note",tone:be.startsWith("\u26A0")?"warn":"info",text:be}):fe.skipped&&f({kind:"note",tone:"warn",text:`Order sync skipped: ${fe.skipped}`}),me&&f({kind:"note",tone:"info",text:me}),fe.failures?.length?le("/structure"):(f({kind:"note",tone:"ok",text:be||me?"\u2713 Structure synced to Document360 \u2014 /structure shows the new category + article order.":"\u2713 Already in order \u2014 nothing to change."}),(be||me)&&le("/structure"))}catch(fe){f({kind:"note",tone:"warn",text:`Structure sync failed: ${fe.message}`})}finally{Fe(null)}return}if(k){let q=(I?[..._,...j]:_).map(re=>re.path);await vt(q,I?0:j.length,{skipReview:b,skipStyle:$,allowUnpullable:C,unreadableSkipped:I?0:z});return}dr({cursor:0,rows:Xy(_,j),conflicts:j.length})}catch(E){f({kind:"note",tone:"error",text:`Could not compute sync status: ${E.message}`}),f({kind:"note",tone:"info",text:"Save one article on its own: /push <article-path>"})}return}case"resolve":{if(!Eo(p.trim()))return;await lu(g.find(b=>!b.startsWith("--")));return}case"preview":{let b=g.join(" ").trim();if(!b){let v=[];try{v=Object.keys(u3(e,pt(e,s).name)?.articles??{})}catch{}if(v.length===0){f({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}vo({query:"",cursor:0,paths:v});return}let $=FO(b)?b:ji(e,b);if(ls($)){try{f({kind:"preview",name:Di($),text:R0(Dc($,"utf8"))})}catch(v){f({kind:"note",tone:"error",text:`Could not read ${$}: ${v.message}`})}return}if(a6.test(b)){try{let v=pt(e,s),k={profile:v.name,connection:v.connection},C=v.project.projectId??YO(k),E=await KO(k,C,b);f({kind:"preview",name:E.title??b,text:E.content??"*(article has no content)*"})}catch(v){f({kind:"note",tone:"error",text:`Could not fetch article: ${v.message}`})}return}f({kind:"note",tone:"error",text:`"${b}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let b=g[0]?.trim();if(!b){let C=Al(Ff(e));yo({cursor:C,current:C});return}let{lines:$,changed:v,effective:k}=si(e,b);for(let C of $)f({kind:"note",tone:C.startsWith("\u26A0")?"warn":C.startsWith("\u2713")?"ok":"info",text:C});v&&(rm(C=>C+1),De.current?.setModel(k));return}case"verbose":{let b=g[0]?.trim().toLowerCase(),$=b==="on"?!0:b==="off"?!1:!Fi.current;Fi.current=$;try{l3({...s0(),verboseTranscript:$})}catch{f({kind:"note",tone:"warn",text:"\u26A0 Applied for this session, but the setting could not be saved."})}f({kind:"note",tone:"ok",text:$?"\u2713 Verbose transcript ON \u2014 every tool call with its file path and full result.":"\u2713 Verbose transcript OFF \u2014 doc work shown by article; my bookkeeping collapsed to one line."});return}case"convert":{if(!ve(e)){f({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:b,run:$}=Kd(g),v=P3(e,s);if(v.length===0){f({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Save some to Document360 first (/push), then /convert."});return}let k=zd(v,b);if(k.length===0){f({kind:"note",tone:"error",text:`No tracked articles under "${b}". (${v.length} are tracked overall.)`});return}let C=jf(k),E=3,F=`/convert${b?` --scope ${b}`:""} --run`,_=Oi(e,"light");if(!$){let I=u0({files:Xd(e,k),op:"convert",model:_.model}),W=b?`Scope: ${b} (${k.length} of ${v.length} tracked)
|
|
549
549
|
`:"",q=`
|
|
550
|
-
Model: ${_.model}${_.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;f({kind:"note",tone:"info",text:W+
|
|
551
|
-
`)+q}),le(F);return}
|
|
552
|
-
`):W+
|
|
553
|
-
`)}),
|
|
550
|
+
Model: ${_.model}${_.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;f({kind:"note",tone:"info",text:W+Jd(C,I,E).join(`
|
|
551
|
+
`)+q}),le(F);return}Vt.current=Date.now(),qt(0),T(!0);let j=new AbortController;Be.current=j;let z=Date.now();$e({verb:"Converting",total:C.length,done:0,active:[],rows:tr(C),tools:0,chars:0,lastAt:Date.now(),startedAt:z}),f({kind:"note",tone:"info",text:`Converting ${k.length} articles in ${C.length} batches (\u2264${E} agents at once) on ${_.model}\u2026 (esc to stop)`});try{for await(let I of Li({cwd:e,partitions:C,promptFor:Qd,concurrency:E,profileName:s,allowProdWrites:gn.current,model:_.model,signal:j.signal}))if(I.type==="partition_status")I.status==="running"?$e(W=>W&&{...W,active:[...W.active,I.label],rows:at(W.rows,I.label,"active"),lastAt:Date.now()}):$e(W=>W&&{...W,active:W.active.filter(q=>q!==I.label),done:W.done+1,rows:at(W.rows,I.label,I.status==="done"?"done":"failed"),lastAt:Date.now()});else if(I.type==="partition_stalled"){let W=ss(I);$e(q=>q&&W?{...q,stalledNote:W}:q)}else if(I.type==="partition_event")$e(W=>{if(!W)return W;let q={...W,lastAt:Date.now()};return I.event.type==="tool"?q.tools=W.tools+1:I.event.type==="text"&&(q.chars=W.chars+I.event.delta.length),q});else if(I.type==="run_done"){Ao(fe=>fe+I.totalCostUsd),To(fe=>fe+I.results.reduce((me,be)=>me+be.outputTokens,0));let W=I.aborted?"Stopped. ":"",q=t.kind==="api"?"api":"subscription",re=eo(I,"The conversion");f({kind:"note",tone:re||I.aborted?"warn":I.ok?"ok":"warn",text:re?re.join(`
|
|
552
|
+
`):W+Zd(I.results,C,q).join(`
|
|
553
|
+
`)}),br(z,I.results,I.totalCostUsd,!re&&!I.aborted&&I.ok),re&&le("/doctor")}}catch(I){f({kind:"note",tone:"error",text:`Convert run failed: ${I.message}`})}finally{Be.current=null,$e(null),T(!1),G(I=>I+1)}return}case"write":{if(!ve(e)){f({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let b=d0(e);if(b.length===0){f({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:$,path:v,preview:k,concurrency:C,rewrite:E}=ri(g);if(!v&&!k&&!(ve(e)?.appType??i0(e))){f({kind:"note",tone:"warn",text:`\u26A0 No doc genre is set, so no doc-craft playbook would load \u2014 all ${b.length} articles would be written generically.
|
|
554
554
|
Pick the genre below (one keypress), then run /write again \u2014 it changes structure, titles and depth for every article.
|
|
555
|
-
Not blocked: /write <path> still authors a single article, and /write --preview costs nothing.`}),
|
|
555
|
+
Not blocked: /write <path> still authors a single article, and /write --preview costs nothing.`}),ke(ic.options.map(J=>({cmd:J.cmd,desc:J.desc}))),$o(ic.title);return}let{docsDir:F,targets:_,reason:j,rewriting:z}=Sl(e,b,{scope:$,path:v,rewrite:E});if(_.length===0){f({kind:"note",tone:"warn",text:j??"Nothing to write."});return}z&&f({kind:"note",tone:"warn",text:`--rewrite: regenerating ${_.length} already-written article${_.length===1?"":"s"} (overwrites them; git has your baseline).`});let I=jf(_),W=cp(C),q=Oi(e,"standard"),re=!!v;if(k&&!re){let J=u0({files:up(e,b,_),op:"write",model:q.model}),xe=$?`Scope: ${$} (${_.length} pending)
|
|
556
556
|
`:"",Oe=`
|
|
557
|
-
Model: ${q.model}${q.forced?" (forced)":" \u2014 authoring; /model to override"}`;f({kind:"note",tone:"info",text:
|
|
558
|
-
`)+Oe}),le(`/write${$?` --scope ${$}`:""}`);return}
|
|
559
|
-
`):
|
|
560
|
-
`)}),
|
|
561
|
-
`)})}if(!J.aborted&&J.ok){let
|
|
557
|
+
Model: ${q.model}${q.forced?" (forced)":" \u2014 authoring; /model to override"}`;f({kind:"note",tone:"info",text:xe+pp(I,J,W).join(`
|
|
558
|
+
`)+Oe}),le(`/write${$?` --scope ${$}`:""}`);return}Vt.current=Date.now(),qt(0),T(!0);let fe=new AbortController;Be.current=fe;let me=Date.now();$e({verb:"Writing",total:I.length,done:0,active:[],rows:tr(I),tools:0,chars:0,lastAt:Date.now(),startedAt:me}),f({kind:"note",tone:"info",text:`Writing ${_.length} article${_.length===1?"":"s"} in ${I.length} batch${I.length===1?"":"es"} (\u2264${W} agents at once) on ${q.model}${q.forced?" (forced)":""}\u2026 (esc to stop)`});let be=new Set;try{for await(let J of Li({cwd:e,partitions:I,promptFor:xe=>dp(xe,F,{rewrite:z||re}),concurrency:W,profileName:s,allowProdWrites:gn.current,model:q.model,signal:fe.signal}))if(J.type==="partition_status")J.status==="running"?$e(xe=>xe&&{...xe,active:[...xe.active,J.label],rows:at(xe.rows,J.label,"active"),lastAt:Date.now()}):$e(xe=>xe&&{...xe,active:xe.active.filter(Oe=>Oe!==J.label),done:xe.done+1,rows:at(xe.rows,J.label,J.status==="done"?"done":"failed"),lastAt:Date.now()});else if(J.type==="partition_stalled"){let xe=ss(J);$e(Oe=>Oe&&xe?{...Oe,stalledNote:xe}:Oe)}else if(J.type==="partition_event"){let xe=null;if(J.event.type==="tool"){let Oe=Af(J.event.name,J.event.input,I[J.index]?.paths??[]);Oe&&!be.has(Oe)&&(be.add(Oe),xe=J.label)}$e(Oe=>{if(!Oe)return Oe;let Zt={...Oe,lastAt:Date.now()};return J.event.type==="tool"?Zt.tools=Oe.tools+1:J.event.type==="text"&&(Zt.chars=Oe.chars+J.event.delta.length),xe&&(Zt.rows=Pc(Zt.rows,xe)),Zt})}else if(J.type==="run_done"){Ao(dt=>dt+J.totalCostUsd),To(dt=>dt+J.results.reduce((Ot,Lo)=>Ot+Lo.outputTokens,0));let xe=J.aborted?"Stopped. ":"",Oe=t.kind==="api"?"api":"subscription",Zt=eo(J,"The write");if(f({kind:"note",tone:Zt||J.aborted?"warn":J.ok?"ok":"warn",text:Zt?Zt.join(`
|
|
559
|
+
`):xe+hp(J.results,I,Oe,$??v).join(`
|
|
560
|
+
`)}),br(me,J.results,J.totalCostUsd,!Zt&&!J.aborted&&J.ok),Zt){le("/doctor");continue}let Tm=vw(J);if(Tm&&f({kind:"note",tone:"warn",text:Tm}),!J.aborted&&J.ok)try{let dt=(be.size>0?[...be]:_).map(Ot=>`${F}/${Ot}`);us(e,dt,{writtenCap:j3,reviewedCap:0,checkedCap:0})}catch{}let Io=J.aborted?[]:qr(e,F,_),Am=fp(Io);Am&&f({kind:"note",tone:"warn",text:Am});let vr=J.aborted||g.includes("--skip-style")?null:mp(Io);if(vr){let dt=vr.errors.length,Ot=await ta({partitions:vr.partitions,promptFor:vr.promptFor,concurrency:Hr,verb:"Fixing",doneNoun:"fixed",headline:`${dt} style error${dt===1?"":"s"} in ${vr.articles} of the new article${vr.articles===1?"":"s"} \u2014 fixing now, one pass`});if(Ot.covered.length>0)try{us(e,Ot.covered,wt("lint"))}catch{}Io=qr(e,F,_);let Lo=gp(dt,Io);f({kind:"note",tone:Lo[0].startsWith("\u2713")?"ok":"warn",text:Lo.join(`
|
|
561
|
+
`)})}if(!J.aborted&&J.ok){let dt=$??v??"",Ot=dt?` ${dt}`:"",Lo=Io.some(xr=>xr.severity==="error");{let xr=If(I,J.results);Sn(`/write${$?` --scope ${$}`:""}${g.includes("--rewrite")?" --rewrite":""}`,{aborted:J.aborted,partitions:I.length,failed:xr.failed.length,notRun:xr.notRun.length,leftBehind:Io.filter(B0=>B0.severity==="error").length,...J.blocked?{blocked:J.blocked}:{},...J.allEmpty?{allEmpty:!0}:{},...J.bailedEmpty?{bailedEmpty:!0}:{}})}let Em=dt?"/push":"/push --all",W0=dt?`/screenshot author ${dt}`:"/screenshot author --all";Te(Lo?`Written, but ${Io.filter(xr=>xr.severity==="error").length} style error(s) are still unfixed. /lint${Ot} --blocked --fix retries them, then /review${Ot} --fix for editorial quality, then ${Em}.`:`Written. I\u2019d run /review${Ot} --fix next \u2014 editorial review that applies its fixes \u2014 then ${Em} saves them to Document360 as drafts (add ${W0} first if you want images).`,{kind:"cmd",cmd:Lo?`/lint${Ot} --blocked --fix`:`/review${Ot} --fix`,reason:""})}}}catch(J){f({kind:"note",tone:"error",text:`Write run failed: ${J.message}`})}finally{Be.current=null,$e(null),T(!1),G(J=>J+1)}return}case"draft":{if(!ve(e)){f({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:b,looseDocs:$}=wp(e);if(b.length===0&&$===0){f({kind:"note",tone:"info",text:kp});return}let v=g.join(" ").trim();if(!v&&b.length>1){f({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
|
|
562
562
|
${b.map(E=>` \u2022 ${E.name} (${E.docCount} doc${E.docCount===1?"":"s"})`).join(`
|
|
563
|
-
`)}`}),
|
|
564
|
-
`)});return}if(b==="--baseline"){let k=g.find(_=>!_.startsWith("--")),C=k?k.replace(/\\/g,"/"):void 0;f({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 E=await
|
|
563
|
+
`)}`}),ke(b.map(E=>`/draft ${E.name}`));return}let k="",C;if(v){let E=bp(b,v);E?k=E:C=v}else k=b[0]?.name??"";await Se(Cl(k,C),{display:v?`/draft ${v}`:"/draft",quietUser:!0});return}case"pull":{if(!Eo(p.trim()))return;let b=g.find($=>$.startsWith("--"));try{if(b==="--status"){f({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let k=Date.now(),C=await Ii({cwd:e,profileName:s});f({kind:"note",tone:"info",text:ul(C,Date.now()-k).join(`
|
|
564
|
+
`)});return}if(b==="--baseline"){let k=g.find(_=>!_.startsWith("--")),C=k?k.replace(/\\/g,"/"):void 0;f({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 E=await b3({cwd:e,profileName:s,relPaths:C?[C]:void 0}),F=C?{rebaselined:[],skipped:[]}:await k3({cwd:e,profileName:s});if(E.baselined.length===0&&E.skipped.length===0&&F.rebaselined.length===0){f({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}E.baselined.length>0&&f({kind:"note",tone:"ok",text:`\u2713 Recorded ${E.baselined.length} article${E.baselined.length===1?"":"s"} as matching Document360 \u2014 they read in-sync until either side changes.`}),F.rebaselined.length>0&&f({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.`}),E.skipped.length>0&&f({kind:"note",tone:"warn",text:`${E.skipped.length} skipped:
|
|
565
565
|
${E.skipped.map(_=>` - ${_.path} (${_.reason})`).join(`
|
|
566
|
-
`)}`}),G(_=>_+1);return}if(b==="--compare"){f({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let k=await
|
|
567
|
-
`)});return}if(b){f({kind:"note",tone:"error",text:`Unknown option: ${b} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let $=g[0];if($){let k=$.replace(/\\/g,"/"),C;try{let E=await
|
|
568
|
-
`)});return}}if(g[0]==="--auto"){let $=ve(e);if(!$){f({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let v=g[1]!=="off";
|
|
569
|
-
`)});let F=E.fixed>0?
|
|
570
|
-
`)});for(let
|
|
571
|
-
\u26A0 ${
|
|
572
|
-
`)}),
|
|
573
|
-
`)}),C.length>0){let E=
|
|
574
|
-
`)});return}case"status":{let b=g.some($=>$==="--all"||$==="--full");f({kind:"block",text:
|
|
575
|
-
`)}),ee.current=!0;return}case"env":{let b=
|
|
576
|
-
`)});return}case"retire":{let b=g.find(v=>!v.startsWith("-"));if(!b){f({kind:"block",text:
|
|
577
|
-
`)}),ee.current=!0;return}let $=
|
|
578
|
-
`)}),
|
|
566
|
+
`)}`}),G(_=>_+1);return}if(b==="--compare"){f({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let k=await f3({cwd:e,profileName:s}),C=k.onlyInLegacy.length===0&&k.onlyInManifest.length===0&&k.mappedMissingFromManifest.length===0,E=[`Legacy listing: ${k.legacyCount} \xB7 Manifest: ${k.manifestCount} \xB7 in both: ${k.inBoth}`];C?E.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(k.mappedMissingFromManifest.length&&E.push(`\u2717 ${k.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${k.mappedMissingFromManifest.slice(0,5).join(", ")}`),k.onlyInLegacy.length&&E.push(`\u26A0 ${k.onlyInLegacy.length} only in the legacy listing: ${k.onlyInLegacy.slice(0,5).join(", ")}`),k.onlyInManifest.length&&E.push(`\u26A0 ${k.onlyInManifest.length} only in the manifest: ${k.onlyInManifest.slice(0,5).join(", ")}`),E.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),f({kind:"note",tone:C?"ok":"warn",text:E.join(`
|
|
567
|
+
`)});return}if(b){f({kind:"note",tone:"error",text:`Unknown option: ${b} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let $=g[0];if($){let k=$.replace(/\\/g,"/"),C;try{let E=await a0({cwd:e,profileName:s,relPath:k});C={plan:E,mode:E.overwritesLocalChanges?"conflict":"pull"}}catch(E){if(!l0(E))throw E;C={mode:"local-only",path:k,title:c0(e,k)}}Ie.current=[C],Kt.current=[],yn.current=[],kr();return}f({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let v=await Md({cwd:e,profileName:s});for(let k of _d(v))f({kind:"note",tone:k.tone,text:k.text});G(k=>k+1)}catch($){f({kind:"note",tone:"error",text:`Pull failed: ${$.message}`})}return}case"scope":{if(!ve(e)){f({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let b=$3(e);if(b.length===0){f({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.'});return}hr({cursor:0,rows:b.map($=>({...$,checked:$.recommended}))});return}case"audit":{{let $=al(e,g);if($){f({kind:"note",tone:$[0].startsWith("\u2713")?"ok":"info",text:$.join(`
|
|
568
|
+
`)});return}}if(g[0]==="--auto"){let $=ve(e);if(!$){f({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let v=g[1]!=="off";o0({...$,autoAudit:v},e),f({kind:"note",tone:"ok",text:v?"\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}if(!Eo(p.trim()))return;let b=await Ks({cwd:e,profileName:s});if(b.kind==="audit-blocked"){Te(b.note,{kind:"cmd",cmd:b.lead.cmd,reason:b.lead.reason},"warn");return}if(b.kind==="forward-to-agent"&&b.prompt){let $=await Se(b.prompt,{display:b.display,quietUser:!0}),v=il(e,s);if(v){Te(v.note,{kind:"cmd",cmd:_r.cmd,reason:_r.reason},"warn"),G(k=>k+1);return}$.producedNothing||(Ri(e,s),G(k=>k+1))}return}case"lint":case"check":{let b=Ys(d);b&&f({kind:"note",tone:"info",text:`\u2192 ${b}`});let $=g.find(E=>!E.startsWith("--")),v=$?` ${$}`:"",k=cs({cwd:e,scope:$}),C=Nn(k,g);if(g.includes("--fix")){let E=oo(e,g,k);E.lines.length>0&&f({kind:"note",tone:"ok",text:E.lines.join(`
|
|
569
|
+
`)});let F=E.fixed>0?cs({cwd:e,scope:$}):k,_=op(e,g,F);if(!_){let J=rp(e,g,F);f({kind:"note",tone:"ok",text:J.lines.join(`
|
|
570
|
+
`)});for(let xe of J.closed)f({kind:"note",tone:"ok",text:xe});return}let j={aborted:!1,partitions:0,failed:0,notRun:0};if(_.kind==="partitioned"){let J=await ta({partitions:_.partitions,promptFor:_.promptFor,concurrency:Hr,verb:"Fixing",doneNoun:"fixed",headline:`Fixing ${_.findings} issue${_.findings===1?"":"s"} across ${_.articles} article${_.articles===1?"":"s"} in ${_.partitions.length} batches (\u2264${Hr} at once)`,calibrateAs:"/lint"});if(j=J.outcome,J.covered.length>0)try{us(e,J.covered,wt("lint"))}catch{}if(J.aborted){let xe=Vs({cwd:e,after:Nn(cs({cwd:e,scope:$}).filter(Oe=>!Oe.baselined),g),scope:$,aborted:!0,blocked:En(g)});Te(xe.text,{kind:"cmd",cmd:xe.cmd,reason:""},"warn");return}}else{f({kind:"note",tone:"info",text:`Fixing ${_.findings} doc issue${_.findings===1?"":"s"}\u2026`});let J=D3(e,$);await Se(_.prompt,{display:_.display,quietUser:!0});try{us(e,J,wt("lint"))}catch{}}let z=Nn(cs({cwd:e,scope:$}).filter(J=>!J.baselined),g),I=Nn(F.filter(J=>!J.baselined),g),W=new Set(z.map(J=>J.fp)),q=new Set(I.map(J=>J.fp)),re=I.filter(J=>!W.has(J.fp)).length,fe=z.filter(J=>!q.has(J.fp)).length,me=fe>0?`
|
|
571
|
+
\u26A0 ${fe} new ${fe===1?"issue":"issues"} appeared in the rewrites \u2014 recasting a sentence is where these come from.`:"";f({kind:"note",tone:z.some(J=>J.severity==="error")?"warn":"ok",text:z.length===0?`\u2713 Lint: all ${I.length} issue${I.length===1?"":"s"} resolved.`:[`\u2713 Lint: fixed ${re} of ${I.length}.${me}`,"",...ti(z)].join(`
|
|
572
|
+
`)}),Sn(ei(g,$),_.kind==="partitioned"?j:{aborted:!1,partitions:0,failed:0,notRun:0,verifiedComplete:z.length===0});let be=Vs({cwd:e,after:z,before:_.findings,scope:$,blocked:En(g)});Te(be.text,{kind:"cmd",cmd:be.cmd,reason:""});return}if(f({kind:"note",tone:C.length===0?"ok":"warn",text:ti(C,{full:g.includes("--full"),baselined:g.includes("--baselined")}).join(`
|
|
573
|
+
`)}),C.length>0){let E=Za(e,$)===0&&el(e,$)===0?"; /push --all saves them to Document360 as-is":"",F=`/lint${v}${En(g)?" --blocked":""} --fix`,_=rn(e,F);Te(`Found ${C.length} doc issue${C.length===1?"":"s"} above. ${F} has the agent fix them in place${_?` (${_})`:""} \u2014 or /review${v} --fix for the full editorial pass${E}.`,{kind:"cmd",cmd:F,reason:""})}return}case"structure":{let b=Zr(e,s);if(b.length===0){f({kind:"note",tone:"info",text:"No documentation structure yet \u2014 run /init and author some articles first."});return}f({kind:"note",tone:"info",text:["Documentation order (categories \u2192 articles):","",...b].join(`
|
|
574
|
+
`)});return}case"status":{let b=g.some($=>$==="--all"||$==="--full");f({kind:"block",text:Vh(e,{profileName:s,all:b,width:rt()}).join(`
|
|
575
|
+
`)}),ee.current=!0;return}case"env":{let b=xu(e,g);f({kind:"block",text:b.lines.join(`
|
|
576
|
+
`)});return}case"retire":{let b=g.find(v=>!v.startsWith("-"));if(!b){f({kind:"block",text:Yh(e,s).join(`
|
|
577
|
+
`)}),ee.current=!0;return}let $=b0(e,b)||b;if(!g.includes("--yes")&&!g.includes("-y")){f({kind:"note",tone:"warn",text:[`\u26A0 This takes "${$}" off your readers on Document360.`," The article, its history and every reviewer comment stay \u2014 nothing is deleted."," /push puts it back later if you change your mind."].join(`
|
|
578
|
+
`)}),st(`/retire ${$} --yes`,"tab to take it off your readers \xB7 or keep typing");return}T(!0);try{let v=await q3({cwd:e,path:$,profileName:s,now:new Date().toISOString()});f(v.ok?{kind:"note",tone:"ok",text:v.alreadyHidden?`\u2713 "${$}" was already invisible to readers. Recorded as retired, so nothing will offer to publish it again.
|
|
579
579
|
It stays on Document360 with its history and comments intact. /push puts it back.`:`\u2713 "${$}" is no longer visible to your readers.
|
|
580
|
-
It stays on Document360 with its history and comments intact. /push puts it back.`}:{kind:"note",tone:"error",text:`\u2717 Could not retire "${$}" \u2014 ${v.error.message}`})}finally{T(!1)}return}case"untrack":{let b=g.find(k=>!k.startsWith("-"));if(g.includes("--list")||!b&&!g.includes("--undo")){f({kind:"block",text:
|
|
581
|
-
`)}),ee.current=!0;return}if(!b){f({kind:"note",tone:"warn",text:"\u2717 Name what to put back: /untrack --undo <path>"});return}let $=
|
|
582
|
-
`)}),
|
|
583
|
-
`)}:{kind:"note",tone:"error",text:`\u2717 Could not untrack "${$}" \u2014 ${v.error.message}`});return}case"eval":{f({kind:"block",text:
|
|
584
|
-
`)}),ee.current=!0;return}case"terms":{let b=g.findIndex($=>$==="--approve");if(b!==-1){let $=g[b+1];f($?{kind:"block",text:
|
|
585
|
-
`)}:{kind:"note",tone:"warn",text:'\u2717 Name the spelling to approve, e.g. /terms --approve "drop-down".'}),ee.current=!0;return}f({kind:"block",text:
|
|
586
|
-
`)}),ee.current=!0;return}case"reuse":{let b=g.find($=>!$.startsWith("--"));if(b==="pull"){(async()=>{let $=await
|
|
587
|
-
`)});for(let v of
|
|
588
|
-
`)}),ee.current=!0;return}let{picks:k,bad:C}=
|
|
589
|
-
`)}),f({kind:"block",text:
|
|
590
|
-
`)});for(let _ of
|
|
591
|
-
`)});for(let v of
|
|
592
|
-
`)}),(async()=>(await Se($.prompt,{display:$.display,quietUser:!0}),f({kind:"block",text:
|
|
593
|
-
`)})))(),ee.current=!0;return}if(b==="add"){let $=
|
|
594
|
-
`)}),v.restart&&Ve()})(),ee.current=!0;return}if(b&&b!=="show"){f({kind:"note",tone:"warn",text:`\u2717 I don't know "/reuse ${b}". Use /reuse to see what this project maintains, /reuse pull to refresh it, or /reuse add variable <name> "<value>".`}),ee.current=!0;return}f({kind:"block",text:
|
|
595
|
-
`)}),ee.current=!0;return}case"reorder":{let b=
|
|
596
|
-
`)})}let I=v&&!_.producedNothing?
|
|
597
|
-
`)}),I.length>0){let
|
|
598
|
-
`)}),
|
|
599
|
-
`)});return}try{let $=
|
|
600
|
-
`)})}catch($){f({kind:"note",tone:"warn",text:`Could not file the question: ${$.message}`})}return}case"inbox":{if(!ve(e)){f({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(
|
|
601
|
-
`)});return}if(b.answer&&(b.all||b.scope.path||b.scope.scope||v.length===1)){
|
|
602
|
-
Windows can't replace the files while d360-writer is running, so I'll install it the moment you /exit.`}),le("/exit");return}
|
|
603
|
-
|
|
604
|
-
Full output: ${
|
|
605
|
-
`)});return}if(b.mode==="list"){if(!ve(e)){f({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let C=ve(e)?.docsDir??
|
|
606
|
-
`)});let z=Ce("/push","--screenshots",E),I=
|
|
607
|
-
`)}),$&&f({kind:"note",tone:"info",text:$});let _=
|
|
608
|
-
`)}),
|
|
609
|
-
Press s in /profile to use a profile for one session only.`});for(let C of k)f({kind:"note",tone:"warn",text:C});na(b,!0);return}if(!Nu(e,d).created){f({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}f({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${d}").`});let U=!1;try{let O=co(d);U=!!O&&!(nr(O)&&!O.refreshToken)}catch{U=!1}f({kind:"note",tone:"info",text:U?`Next: sign in to ${d} and pick your project \u2014 you're already signed in here, so it'll be quick.`:`Next: sign in to Document360 (${d}) and pick your project.`}),le("/login"),G(O=>O+1);return}if(m.escape){_n(null);return}return}if(at){if(m.upArrow){cr(d=>d&&{...d,cursor:Math.max(0,d.cursor-1)});return}if(m.downArrow){cr(d=>d&&{...d,cursor:Math.min(d.rows.length-1,d.cursor+1)});return}if(p&&/^[0-9]$/.test(p)){let d=bn(p,at.rows.length);d!==null&&cr(g=>g&&{...g,cursor:d});return}if(m.return){let d=at.rows[at.cursor],{profile:g,projectId:A}=at;cr(null),oa(g,A,d);return}if(m.escape){cr(null);return}return}if(pt){if(m.upArrow){go(d=>d&&{...d,cursor:Math.max(0,d.cursor-1)});return}if(m.downArrow){go(d=>d&&{...d,cursor:Math.min(d.rows.length-1,d.cursor+1)});return}if(p&&/^[0-9]$/.test(p)){let d=bn(p,pt.rows.length);d!==null&&go(g=>g&&{...g,cursor:d});return}if(m.return){let d=pt.rows[pt.cursor],{profile:g}=pt;go(null),sa(g,d);return}if(m.escape){go(null);return}return}if(ht){if(m.upArrow){pr(d=>d&&{...d,cursor:Math.max(0,d.cursor-1)});return}if(m.downArrow){pr(d=>d&&{...d,cursor:Math.min(d.rows.length-1,d.cursor+1)});return}if(p===" "){pr(d=>d&&{...d,rows:d.rows.map((g,A)=>A===d.cursor?{...g,checked:!g.checked}:g)});return}if(m.return){let d=ht.rows.filter(g=>g.checked).map(g=>g.path);if(pr(null),d.length===0){f({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}Nd(e,d),f({kind:"note",tone:"ok",text:`\u2713 Scoped to ${d.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let g of d)f({kind:"note",tone:"info",text:` ${g}`});f({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(m.escape){pr(null);return}return}if(wt){if(m.upArrow){wo(d=>d&&{...d,cursor:Math.max(0,d.cursor-1)});return}if(m.downArrow){wo(d=>d&&{...d,cursor:Math.min(d.rows.length-1,d.cursor+1)});return}if(p&&/^[0-9]$/.test(p)){let d=bn(p,wt.rows.length);d!==null&&wo(g=>g&&{...g,cursor:d});return}if(m.return){let d=wt.rows[wt.cursor],g=wt.run;wo(null),g(d.token);return}if(m.escape){wo(null);return}return}if(Tt){if(m.upArrow){ur(d=>d&&{...d,cursor:Math.max(0,d.cursor-1)});return}if(m.downArrow){ur(d=>d&&{...d,cursor:Math.min(d.rows.length-1,d.cursor+1)});return}if(p&&/^[0-9]$/.test(p)){let d=bn(p,Tt.rows.length);d!==null&&ur(g=>g&&{...g,cursor:d});return}if(m.return){let d=Tt.rows[Tt.cursor],g=Tt.conflicts;ur(null),d.conflict?au(d.paths[0]):d.kind==="article"?ou(d.paths[0]):kt(d.paths,d.kind==="all"?g:0);return}if(m.escape){ur(null);return}return}if(Yt){if(m.upArrow){dr(d=>d&&{...d,cursor:Math.max(0,d.cursor-1)});return}if(m.downArrow){dr(d=>d&&{...d,cursor:Math.min(d.rows.length,d.cursor+1)});return}if(p&&/^[0-9]$/.test(p)){let d=bn(p,Yt.rows.length+1);d!==null&&dr(g=>g&&{...g,cursor:d});return}if(m.return){let{cursor:d,rows:g,opts:A}=Yt;dr(null);let U=d===0?g:[g[d-1]];mm(U,A);return}if(m.escape){dr(null),f({kind:"note",tone:"info",text:"Left as drafts \u2014 nothing changed. /publish when they have been signed off."});return}return}if(At){let{rows:d}=At;if(m.upArrow){wn(g=>g&&{...g,cursor:Math.max(0,g.cursor-1)});return}if(m.downArrow){wn(g=>g&&{...g,cursor:Math.min(d.length-1,g.cursor+1)});return}if(p&&/^[0-9]$/.test(p)){let g=vf(Yf.current,Number(p),d.length-1);Yf.current=g.memory,g.index!==null&&wn(A=>A&&{...A,cursor:g.index+1});return}if(p==="a"||p==="A"){wn(g=>g&&{...g,cursor:0});return}if(m.return){let g=d[At.cursor],{groups:A,resolve:U,report:O}=At;if(wn(null),g.kind==="all"){nu(A,{resolve:U,report:O});return}yr(Fl(g.group,{width:nt()})),fs({group:g.group,cursor:0,fromList:!0,resolve:U,rest:A.filter(b=>b.articleId!==g.group.articleId),report:O});return}if(m.escape){wn(null),le("/comments");return}return}if(ct){let d=()=>{let{rest:g,group:A,fromList:U,resolve:O,report:b}=ct;if(fs(null),!U||!b){le("/comments");return}let $=[A,...g].sort((v,k)=>v.category.localeCompare(k.category)||v.title.localeCompare(k.title));wn({cursor:0,rows:Wl($),groups:$,resolve:O,report:b})};if(m.upArrow||m.downArrow){fs(g=>g&&{...g,cursor:g.cursor===0?1:0});return}if(p==="y"||p==="Y"||m.return&&ct.cursor===0){let{group:g,resolve:A,rest:U,report:O}=ct;fs(null),nu([g],{resolve:A,rest:U,...O?{report:O}:{}});return}if(p==="b"||p==="B"||m.escape||m.return){d();return}return}if(Kt){if(m.upArrow){yo(d=>d&&{...d,cursor:Math.max(0,d.cursor-1)});return}if(m.downArrow){yo(d=>d&&{...d,cursor:Math.min(d.rows.length-1,d.cursor+1)});return}if(p&&/^[0-9]$/.test(p)){let d=bn(p,Kt.rows.length);d!==null&&yo(g=>g&&{...g,cursor:d});return}if(m.return){let d=Kt.rows[Kt.cursor];yo(null),d.action==="capture"?Ps(d.ids,{runLine:d.kind==="all"?["/screenshot capture --all","/capture --all"]:void 0}):d.action==="annotate"?ta(d.ids,{verifiedBefore:new Set(He(e).filter(g=>g.state==="verified").map(g=>g.id))}):d.kind==="shot"?wm(d.ids[0]):ym(d.ids,{setup:!0,runLine:d.kind==="all"?["/screenshot author --all","/screenshot --all"]:void 0});return}if(m.escape){yo(null);return}return}if(Et){if(m.escape){ko(null);return}if(m.upArrow){ko(d=>d&&{...d,cursor:Math.max(0,d.cursor-1)});return}if(m.downArrow){ko(d=>d&&{...d,cursor:Math.min(Math.max(0,Qi.length-1),d.cursor+1)});return}if(m.return){let d=Qi[Et.cursor];if(d){ko(null);try{f({kind:"preview",name:Ei(d),text:y0(Nc(Ni(e,d),"utf8"))})}catch(g){f({kind:"note",tone:"error",text:`Could not read ${d}: ${g.message}`})}}return}if(m.backspace||m.delete){ko(d=>d&&{...d,query:d.query.slice(0,-1),cursor:0});return}if(p&&!m.ctrl&&!m.meta&&p.length===1){ko(d=>d&&{...d,query:d.query+p,cursor:0});return}return}if(Nt){if(m.escape){Ro(null);return}if(m.upArrow){Ro(d=>d&&{...d,cursor:Math.max(0,d.cursor-1)});return}if(m.downArrow){Ro(d=>d&&{...d,cursor:Math.min(Math.max(0,Ji.length-1),d.cursor+1)});return}if(m.return){let d=Ji[Nt.cursor];if(d){Ro(null),Ve(d.uuid),et.current={uuid:d.uuid,firstPrompt:d.firstPrompt,titleFired:!0},fo(d.name),Ef(d.uuid),de.current=[],mt.current={printed:[],armed:[],printedAt:mr.current};let g=xf(e,d.uuid);for(let A of g)f(A);f({kind:"note",tone:"ok",text:g.length?`Resumed "${d.name}" \u2014 restored ${g.length} message(s); continue where you left off.`:`Resumed "${d.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(m.backspace||m.delete){Ro(d=>d&&{...d,query:d.query.slice(0,-1),cursor:0});return}if(p&&!m.ctrl&&!m.meta&&p.length===1){Ro(d=>d&&{...d,query:d.query+p,cursor:0});return}return}if(m.tab&&!y&&ne){x(ne),zt();return}if(!y&&ge.length>0&&!Ne.current&&p&&/^[1-9]$/.test(p)){let d=ge[Number(p)-1];if(d){x(lo(d));return}}if(!y&&ge.length===0&&!Ne.current&&mt.current.armed.length>0&&p&&/^[1-9]$/.test(p)){let d=mt.current.armed[Number(p)-1];if(d){x(d);return}}if(!y&&(Ki||To)&&p==="c"&&!m.ctrl&&!m.meta&&!m.return&&!m.tab){let d=Ki!=null;bf(Ki??To).then(A=>{f({kind:"note",tone:A?"ok":"warn",text:A?d?"\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.":d?"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."}),A&&d&&Xc(null),A&&!d&&sm(!0)});return}if(!Rm(p,m)){if(Zc){if(m.upArrow){On(d=>Math.max(0,d-1));return}if(m.downArrow){On(d=>Math.min(xn.length-1,d+1));return}if(m.tab){x("/"+(xn[rr]?.name??"")+" "),On(0);return}if(m.return){let d=xn[rr];if(d){let g=y.trim().slice(1).split(/\s+/).slice(1).join(" ");if(xw(d.usage)&&!g){x("/"+d.name+" "),On(0);return}Ts("/"+d.name+(g?" "+g:""));return}}}else{if(!y&&ge.length>0&&!Ne.current&&(m.upArrow||m.downArrow)){if(m.downArrow){Mn(d=>d===null?0:Math.min(ge.length-1,d+1));return}if(fn!==null){Mn(d=>d===null||d===0?null:d-1);return}}if(m.upArrow){if(y!==""&&Gt===null){ia(-1);return}let d=Mc.current;if(!d.length)return;let g=Gt===null?d.length-1:Math.max(0,Gt-1);sr(g),x(d[g]??"");return}if(m.downArrow){if(y!==""&&Gt===null){ia(1);return}let d=Mc.current;if(Gt===null)return;let g=Gt+1;g>=d.length?(sr(null),x("")):(sr(g),x(d[g]??""));return}}if(m.return){if(fn!==null&&!y&&ge[fn]){let d=lo(ge[fn]);Mn(null),Ts(d);return}Ts();return}if(m.backspace||m.delete){S();return}if(m.escape){Xe.current&&(vo.current=!0,Cs({kind:"stopped",how:"esc"},Xe.current.parked)),x(""),On(0),zt(),be([]),bo(null),Mn(null),ee.current=!0;return}p&&!m.ctrl&&!m.meta&&vm(p)}}}),lt(()=>{if(P||R)return;let p=$o.current.shift();p!==void 0&&(Uc([...$o.current]),Ts(p))},[P,R,Ts]),me(Le,{flexDirection:"column",width:gt,children:[tu!==null&&me(Le,{marginTop:1,flexDirection:"column",children:[tu.truncated&&Y(K,{dimColor:!0,children:"\u2026"}),Y(K,{children:tu.text})]}),hr?Y(Y3,{step:hr.step,cmd:hr.cmd,startedAt:hr.startedAt,spentUsd:Math.max(hr.spentUsd,Dt-(Xe.current?.stepStartedSpend??Dt)),budgetUsd:hr.budgetUsd}):null,P&&fr?Y(X3,{p:fr}):null,Zf?Y(K3,{text:Zf}):P&&!fr?Y(V3,{startTime:Ht.current,chars:Oi}):null,Y(Le,{borderStyle:"round",borderColor:pm.prod?"yellow":ue,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:y?xm.map((p,m)=>{let d=c.text.slice(p.start,p.end),g=m===Ac(xm,c.pos),A=Math.min(c.pos,p.end)-p.start;return me(K,{children:[Y(K,{color:ue,children:m===0?"> ":" "}),g?me(tr,{children:[d.slice(0,A),Y(us,{ch:d[A]??" "}),d.slice(A+1)]}):d||" "]},`${m}-${p.start}`)}):me(K,{children:[Y(K,{color:ue,children:"> "}),Un?Y(us,{ch:" "}):ye&&!P?me(tr,{children:[Y(us,{ch:ye[0],dim:!0}),Y(K,{color:"gray",children:ye.slice(1)})]}):ne&&!P?me(tr,{children:[Y(us,{ch:ne[0],dim:!0}),Y(K,{color:"gray",children:ne.slice(1)}),Y(K,{dimColor:!0,children:" (tab)"})]}):(Jc.isSetup||!sn)&&!P?me(tr,{children:[Y(us,{ch:Jc.text[0],dim:!0}),Y(K,{color:"gray",children:Jc.text.slice(1)})]}):Y(us,{ch:" "})]})}),Xf.length>0&&Y(Le,{flexDirection:"column",paddingX:1,children:Xf.map((p,m)=>Y(K,{color:"gray",children:`\u29D7 queued: ${p}`},`${m}-${p.slice(0,24)}`))}),ft?me(Le,{flexDirection:"column",paddingX:1,children:[Y(K,{color:ue,bold:!0,children:"Auto mode \u2014 I run each step myself"}),Y(K,{color:"gray",children:` first step ${ft.firstCmd}${ft.scale?` \u2014 ${ft.scale}`:""}`}),ft.upcoming.length>0?me(tr,{children:[Y(K,{color:"gray",children:" as things stand, after that:"}),ft.upcoming.map(p=>Y(K,{color:"gray",children:` ${p.cmd}${p.scale?` ${p.scale}`:""}`},p.cmd)),Y(K,{color:"gray",children:" each step changes what the next one finds, so this is not a total"})]}):Y(K,{color:"gray",children:" I work down the ladder from there \u2014 reviewing, checking style, saving and going live"}),[ft.scale,...ft.upcoming.map(p=>p.scale)].every(p=>!p?.includes("$"))?Y(K,{color:"gray",children:" no cost estimate yet \u2014 this repo has not finished a run for me to measure"}):null,Y(K,{color:"gray",children:` spending limit ${Ke(ft.budgetUsd)} \xB7 I stop and report if it is reached`}),Y(K,{color:"gray",children:" screenshots are not part of an automatic run"}),ft.overBudget?Y(K,{color:"yellow",children:`\u26A0 That is more than your ${Ke(ft.budgetUsd)} limit. I will stop partway and report what is left.`}):null,Y(K,{dimColor:!0,children:ft.overBudget?"b raise the limit \xB7 enter start anyway \xB7 esc stay in manual for now":"enter start \xB7 b change the limit \xB7 esc stay in manual for now"})]}):bs?Y(Pv,{tab:bs.tab,scroll:bs.scroll,rows:E0,width:gt,version:o,engineVersion:w0}):yn?me(Le,{flexDirection:"column",paddingX:1,children:[Y(K,{color:ue,bold:!0,children:"Select model"}),Y(K,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),Ut.map((p,m)=>me(K,{color:m===yn.cursor?ue:void 0,children:[m===yn.cursor?"\u276F ":" ",`${m+1}. ${p.label}${m===yn.current?" \u2714":""}`.padEnd(16),Y(K,{color:"gray",children:` ${p.desc}`})]},p.label)),Y(K,{dimColor:!0,children:St({verb:"set as default",rows:Ut.length,extra:["s this session only"]})})]}):Vt?me(Le,{flexDirection:"column",paddingX:1,children:[Y(K,{color:ue,bold:!0,children:"Switch connection profile"}),Y(K,{color:"gray",children:"Where this repo publishes. The environment lives on the profile, not on your login."}),Y(Ln,{rows:Vt.rows,cursor:Vt.cursor,cap:an,render:(p,m,d)=>me(K,{color:d?ue:void 0,children:[d?"\u276F ":" ",`${m+1}. ${p.name}${m===Vt.current?" \u2714":""}`.padEnd(20),p.connect?null:Y(K,{color:"gray",children:` ${p.portalUrl||p.env}${p.project?` \xB7 ${p.project}`:""} \xB7 ${p.who??"not signed in"}`}),p.prod?Y(K,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null,p.internal?Y(K,{color:"yellow",children:" \u26A0 internal"}):null]},p.name)}),Y(K,{dimColor:!0,children:St({verb:"switch (saved as default)",rows:Vt.rows.length,extra:["s this session only"]})})]}):Pt?me(Le,{flexDirection:"column",paddingX:1,children:[Y(K,{color:ue,bold:!0,children:"Pick your Document360 environment"}),Y(K,{color:"gray",children:"This is the portal your readers see. Rows marked internal are ours, not a customer's."}),Y(Ln,{rows:Pt.rows,cursor:Pt.cursor,cap:an,render:(p,m,d)=>me(K,{color:d?ue:void 0,children:[d?"\u276F ":" ",`${m+1}. ${p.name}`.padEnd(18),Y(K,{color:"gray",children:` ${p.portalUrl.replace(/^https:\/\//,"")}`}),p.note?p.internal||!p.production?Y(K,{color:"yellow",children:` \u26A0 ${p.note}`}):Y(K,{color:"gray",children:` ${p.note}`}):null]},p.name)}),Y(K,{dimColor:!0,children:St({verb:"use it",rows:Pt.rows.length})})]}):at?me(Le,{flexDirection:"column",paddingX:1,children:[Y(K,{color:ue,bold:!0,children:"Switch workspace"}),Y(K,{dimColor:!0,children:`environment ${at.environment} \xB7 project ${at.projectName??`${at.projectId.slice(0,8)}\u2026`}`}),Y(Ln,{rows:at.rows,cursor:at.cursor,cap:an,render:(p,m,d)=>me(K,{color:d?ue:void 0,children:[d?"\u276F ":" ",`${m+1}. ${p.name}${m===at.current?" \u2714":""}`.padEnd(30),Y(K,{color:"gray",children:p.type?` ${p.type}`:""})]},p.id)}),Y(K,{dimColor:!0,children:St({verb:"switch",rows:at.rows.length})})]}):pt?me(Le,{flexDirection:"column",paddingX:1,children:[Y(K,{color:ue,bold:!0,children:"Choose project"}),Y(K,{dimColor:!0,children:`environment ${pt.environment}`}),Y(Ln,{rows:pt.rows,cursor:pt.cursor,cap:an,render:(p,m,d)=>me(K,{color:d?ue:void 0,children:[d?"\u276F ":" ",`${m+1}. ${p.name}${m===pt.current?" \u2714":""}`.padEnd(30),Y(K,{color:"gray",children:p.sub?` ${p.sub}`:""})]},p.id)}),Y(K,{dimColor:!0,children:St({verb:"switch",rows:pt.rows.length})})]}):ht?(()=>{let m=Math.min(Math.max(0,ht.cursor-Math.floor(7)),Math.max(0,ht.rows.length-14)),d=ht.rows.slice(m,m+14),g=ht.rows.filter(A=>A.checked).length;return me(Le,{flexDirection:"column",paddingX:1,children:[Y(K,{color:ue,bold:!0,children:`Which folders back the user docs? (${g} selected of ${ht.rows.length})`}),m>0?Y(K,{dimColor:!0,children:` \u2191 ${m} more`}):null,d.map((A,U)=>{let O=m+U;return me(K,{color:O===ht.cursor?ue:void 0,children:[O===ht.cursor?"\u276F ":" ",A.checked?"\u25C9 ":"\u25CB ",A.path.padEnd(Math.min(48,gt-34)),Y(K,{color:"gray",children:ll(A)})]},A.path)}),m+14<ht.rows.length?Y(K,{dimColor:!0,children:` \u2193 ${ht.rows.length-m-14} more`}):null,Y(K,{dimColor:!0,children:St({verb:"save",multi:!0})})]})})():wt?me(Le,{flexDirection:"column",paddingX:1,children:[Y(K,{color:ue,bold:!0,children:wt.title??"Which category? (pick one to scope to)"}),Y(Ln,{rows:wt.rows,cursor:wt.cursor,cap:an,render:(p,m,d)=>me(K,{color:d?ue:void 0,children:[d?"\u276F ":" ",`${`${m+1}.`.padEnd(3)} ${p.label} (${p.count})`.padEnd(Math.min(44,Math.max(20,gt-24))),Y(K,{color:"gray",children:` ${p.token}`})]},p.token)}),Y(K,{dimColor:!0,children:St({verb:"choose it",rows:wt.rows.length})})]}):Tt?me(Le,{flexDirection:"column",paddingX:1,children:[Y(K,{color:ue,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),Y(Ln,{rows:Tt.rows,cursor:Tt.cursor,cap:an,render:(p,m,d)=>me(K,{color:d?ue:void 0,bold:p.kind==="category"&&!d,children:[d?"\u276F ":" ",`${p.indent?" ":" "}${`${m+1}.`.padEnd(3)} ${p.label}`.padEnd(Math.min(56,gt-24)),p.note?Y(K,{color:"gray",children:` ${p.note}`}):null]},`${p.kind}:${p.paths.join(",")}`)}),Y(K,{dimColor:!0,children:St({verb:"push as drafts",rows:Tt.rows.length})})]}):Yt?me(Le,{flexDirection:"column",paddingX:1,children:[Y(K,{color:ue,bold:!0,children:"Publish live to your readers \u2014 this is what they will see:"}),Y(Ln,{rows:[{path:"",articleId:"",label:`Publish all ${Yt.rows.length} live`,version:void 0},...Yt.rows],cursor:Yt.cursor,cap:an,render:(p,m,d)=>me(K,{color:d?ue:void 0,bold:m===0&&!d,children:[d?"\u276F ":" ",` ${`${m+1}.`.padEnd(3)} ${p.label}`.padEnd(Math.min(56,gt-24)),m>0?Y(K,{color:"gray",children:` ${p.version?`draft v${p.version} \u2192 live`:"draft \u2192 live"}`}):null]},`${m}:${p.path||"all"}`)}),Y(K,{dimColor:!0,children:St({verb:"publish live",cancel:"leave as drafts",rows:Yt.rows.length+1})})]}):At?me(Le,{flexDirection:"column",paddingX:1,children:[Y(K,{color:ue,bold:!0,children:"Which comments do you want to look at?"}),Y(Ln,{rows:At.rows,cursor:At.cursor,cap:an,render:(p,m,d)=>me(K,{color:d?ue:void 0,bold:p.kind==="all"&&!d,children:[d?"\u276F ":" ",`${(p.kind==="all"?"":`${p.n}.`).padEnd(4)}${p.label}`.padEnd(Math.min(56,Math.max(20,gt-24))),p.kind==="article"?Y(K,{color:"gray",children:p.note}):null]},p.kind==="all"?"all":p.group.articleId)}),Y(K,{dimColor:!0,children:St({verb:"open it",cancel:"close",rows:At.rows.length-1})}),At.resolve?Y(K,{dimColor:!0,children:"--resolve is on: threads you answer will be closed as well as replied to"}):null]}):ct?me(Le,{flexDirection:"column",paddingX:1,children:[Y(K,{color:ue,bold:!0,children:`${ct.group.title} \u2014 ${ct.group.threads.length} comment${ct.group.threads.length===1?"":"s"}`}),me(K,{color:ct.cursor===0?ue:void 0,children:[ct.cursor===0?"\u276F ":" ",ct.resolve?"Yes \u2014 fix them, push the draft, reply and resolve":"Yes \u2014 fix them, push the draft to Document360, then reply"]}),me(K,{color:ct.cursor===1?ue:void 0,children:[ct.cursor===1?"\u276F ":" ",ct.fromList?"No \u2014 back to the list":"No \u2014 leave them for now"]}),Y(K,{dimColor:!0,children:St({verb:"open it",cancel:"go back",extra:["y answer"]})})]}):Kt?me(Le,{flexDirection:"column",paddingX:1,children:[Y(K,{color:ue,bold:!0,children:Kt.title}),(()=>{let{rows:p,cursor:m}=Kt,d=kc(p.length,m,an),g=d.start,A=p.slice(d.start,d.end),U=`${p.length}.`.length+1,O=$y(p,Math.max(20,gt-4-U));return me(tr,{children:[g>0?Y(K,{color:"gray",children:` \u2026 ${g} more above`}):null,A.map((b,$)=>{let v=g+$,k=v===m,C=O[v];return me(K,{color:k?ue:void 0,bold:(b.kind==="all"||b.kind==="category")&&!k,children:[k?"\u276F ":" ",`${v+1}.`.padEnd(U),C.head,C.note?Y(K,{color:"gray",children:C.note}):null]},`${b.action}:${b.kind}:${b.ids.join(",")}`)}),d.below>0?Y(K,{color:"gray",children:` \u2026 ${d.below} more below`}):null]})})(),Y(K,{dimColor:!0,children:St({verb:"run it",rows:Kt.rows.length})})]}):Et?me(Le,{flexDirection:"column",paddingX:1,children:[Y(K,{color:ue,bold:!0,children:`Preview article${Et.query?` \u2014 filter: ${Et.query}`:" (type to filter)"}`}),Qi.length===0?Y(K,{color:"gray",children:"no articles match"}):Qi.map((p,m)=>me(K,{color:m===Et.cursor?ue:void 0,children:[m===Et.cursor?"\u276F ":" ",p]},p)),Y(K,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):Nt?me(Le,{flexDirection:"column",paddingX:1,children:[Y(K,{color:ue,bold:!0,children:`Resume session${Nt.query?` \u2014 filter: ${Nt.query}`:" (type to filter)"}`}),Ji.length===0?Y(K,{color:"gray",children:"no sessions match"}):Ji.map((p,m)=>me(K,{color:m===Nt.cursor?ue:void 0,children:[m===Nt.cursor?"\u276F ":" ",p.name.slice(0,28).padEnd(30),Y(K,{color:m===Nt.cursor?ue:"gray",children:p.firstPrompt.slice(0,Math.max(10,gt-40))})]},p.uuid)),Y(K,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Zc?me(Le,{flexDirection:"column",children:[Eo>0?Y(K,{dimColor:!0,children:` \u22EF ${Eo} more above`}):null,eu.map((p,m)=>{let d=Eo+m,g=p.name==="model"&&Gc?`${p.desc} (currently ${Gc})`:p.desc,A=Math.max(20,gt-4),U=p.usage.length>A?`${p.usage.slice(0,A-1)}\u2026`:p.usage,O=A-Math.max(U.length,22)-1,b=O<=1?"":g.length>O?`${g.slice(0,O-1)}\u2026`:g;return me(K,{color:d===Xi?ue:void 0,children:[d===Xi?"\u276F ":" ",U.padEnd(22)," ",Y(K,{color:d===Xi?ue:"gray",children:b})]},p.name)}),Eo+eu.length<xn.length?Y(K,{dimColor:!0,children:` \u22EF ${xn.length-Eo-eu.length} more below`}):null,Y(K,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!P&&!y&&ge.length>0?me(Le,{flexDirection:"column",paddingX:1,children:[zf?Y(K,{color:ue,children:zf}):null,Y(Ln,{rows:ge,cursor:fn??0,cap:an,render:(p,m)=>{let d=m===fn,g=lo(p),A=g.slice(0,Math.max(20,gt-7)),U=gt-A.length-9,O=U>=12?(Ev(p)??$w(g)).slice(0,U):"";return me(K,{color:d?ue:void 0,children:[d?"\u276F ":" ",Y(K,{color:ue,children:m+1})," ",A,O?Y(K,{color:d?ue:void 0,dimColor:!d,children:` \u2014 ${O}`}):null]},g)}}),Y(K,{dimColor:!0,children:`\u2191\u2193 choose \xB7 enter run \xB7 1-${ge.length} fill \xB7 esc cancel`})]}):Y(Le,{paddingX:1,children:me(K,{color:"gray",children:[pm.prod?"\u26A0 PRODUCTION \xB7 ":"",Y(K,{color:ks?ue:void 0,children:ks?"\u23F5\u23F5 auto":"\u23F5 manual"}),` \xB7 /help \xB7 ${Gc??"model n/a"}${t.kind==="api"?Dt>0?` \xB7 session ${xt(Dt)}`:"":tm>0?` \xB7 ${Wr(tm)}`:""} \xB7 \u2191 history \xB7 shift+tab mode \xB7 ${S0?"press ctrl+c again to exit":"ctrl+c twice to exit"}`]})})]})}ie();import{jsx as e6}from"react/jsx-runtime";async function k0(e=process.cwd(),t="auto",n,o="0.0.0"){let r=Z3(t);r.kind==="none"&&(console.error(""),console.error(L("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${Z("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${Z("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=J3(e6(b0,{cwd:e,auth:r,profileName:n,version:o}),{exitOnCtrlC:!1});await s(),await Gl(),process.stdout.write(`
|
|
610
|
-
`),process.exit(0)}
|
|
611
|
-
`+L(`\u2717 d360-writer crashed: ${
|
|
580
|
+
It stays on Document360 with its history and comments intact. /push puts it back.`}:{kind:"note",tone:"error",text:`\u2717 Could not retire "${$}" \u2014 ${v.error.message}`})}finally{T(!1)}return}case"untrack":{let b=g.find(k=>!k.startsWith("-"));if(g.includes("--list")||!b&&!g.includes("--undo")){f({kind:"block",text:Kh(e,s).join(`
|
|
581
|
+
`)}),ee.current=!0;return}if(!b){f({kind:"note",tone:"warn",text:"\u2717 Name what to put back: /untrack --undo <path>"});return}let $=b0(e,b)||b;if(g.includes("--undo")){let k=Y3(e,s,$);f(k.ok?{kind:"note",tone:"ok",text:k.restoredTo?`\u2713 Put "${k.restoredTo}" back in your docs folder.`:"\u2713 No longer declined. /catch-up imports it again on the next run."}:{kind:"note",tone:"error",text:`\u2717 ${k.error.message}`});return}if(!g.includes("--yes")&&!g.includes("-y")){f({kind:"note",tone:"warn",text:[`\u26A0 This stops tracking "${$}" as one of your docs.`," Nothing on Document360 changes \u2014 the page, its history and its comments all stay,"," and your readers see no difference."," The markdown moves to .d360-writer/declined/, so nothing is deleted."," /untrack --undo puts it back if you change your mind."].join(`
|
|
582
|
+
`)}),st(`/untrack ${$} --yes`,"tab to stop tracking it \xB7 or keep typing");return}let v=V3({cwd:e,path:$,profileName:s,now:new Date().toISOString()});f(v.ok?{kind:"note",tone:"ok",text:[`\u2713 "${v.title??v.path}" is no longer one of your docs.`,...v.keptAt?[` The markdown is kept at ${v.keptAt} \u2014 nothing was deleted.`]:[]," It is untouched on Document360. /catch-up will not import it again."].join(`
|
|
583
|
+
`)}:{kind:"note",tone:"error",text:`\u2717 Could not untrack "${$}" \u2014 ${v.error.message}`});return}case"eval":{f({kind:"block",text:ef(e,{...g.find(b=>!b.startsWith("--"))?{scope:g.find(b=>!b.startsWith("--"))}:{},...s?{profile:s}:{},all:g.includes("--all")}).join(`
|
|
584
|
+
`)}),ee.current=!0;return}case"terms":{let b=g.findIndex($=>$==="--approve");if(b!==-1){let $=g[b+1];f($?{kind:"block",text:Qh(e,$.replace(/^["']|["']$/g,"")).lines.join(`
|
|
585
|
+
`)}:{kind:"note",tone:"warn",text:'\u2717 Name the spelling to approve, e.g. /terms --approve "drop-down".'}),ee.current=!0;return}f({kind:"block",text:Xh(e,{...g.find($=>!$.startsWith("--"))?{scope:g.find($=>!$.startsWith("--"))}:{},all:g.includes("--all")}).join(`
|
|
586
|
+
`)}),ee.current=!0;return}case"reuse":{let b=g.find($=>!$.startsWith("--"));if(b==="pull"){(async()=>{let $=await xi(e);f({kind:"block",text:$.lines.join(`
|
|
587
|
+
`)});for(let v of Ke(e,"/reuse pull"))f({kind:"note",tone:"ok",text:v});$.restart&&Ve()})(),ee.current=!0;return}if(b==="audit"){if(g.includes("--create")){let v=K3(e);if(!v||v.proposals.length===0){f({kind:"block",text:oc().join(`
|
|
588
|
+
`)}),ee.current=!0;return}let{picks:k,bad:C}=nc(g,v.proposals.length);for(let E of C)f({kind:"note",tone:"warn",text:`\u26A0 There is no proposal ${E} \u2014 the list has ${v.proposals.length}.`});if(k.length===0){f({kind:"note",tone:"info",text:"\u25CB Nothing picked, so nothing was created."}),ee.current=!0;return}(async()=>{let{outcome:E,pullLines:F}=await cf(e,k.map(_=>v.proposals[_]));F.length>0&&f({kind:"block",text:F.join(`
|
|
589
|
+
`)}),f({kind:"block",text:tc(e,E).lines.join(`
|
|
590
|
+
`)});for(let _ of Ke(e,"/reuse audit"))f({kind:"note",tone:"ok",text:_});E.created.length>0&&Ve()})(),ee.current=!0;return}let $=ec(e,g);if("lines"in $){f({kind:"block",text:$.lines.join(`
|
|
591
|
+
`)});for(let v of Ke(e,"/reuse audit"))f({kind:"note",tone:"ok",text:v});ee.current=!0;return}f({kind:"block",text:Zl($.articles,$.families,$.values,0).join(`
|
|
592
|
+
`)}),(async()=>(await Se($.prompt,{display:$.display,quietUser:!0}),f({kind:"block",text:rc(e,$.display.split(/\s+/)[2]).join(`
|
|
593
|
+
`)})))(),ee.current=!0;return}if(b==="add"){let $=lf(g);if("error"in $){f({kind:"note",tone:"warn",text:`\u2717 ${$.error}`}),ee.current=!0;return}(async()=>{let v=await af(e,$.kind,$.name,$.value,$.description);f({kind:"block",text:v.lines.join(`
|
|
594
|
+
`)}),v.restart&&Ve()})(),ee.current=!0;return}if(b&&b!=="show"){f({kind:"note",tone:"warn",text:`\u2717 I don't know "/reuse ${b}". Use /reuse to see what this project maintains, /reuse pull to refresh it, or /reuse add variable <name> "<value>".`}),ee.current=!0;return}f({kind:"block",text:sf(e).join(`
|
|
595
|
+
`)}),ee.current=!0;return}case"reorder":{let b=Gh(e,g);if(!b){f({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let $=await Se(b.prompt,{display:b.display,quietUser:!0}),v=Ut(e,{text:"Reordered locally \u2014 /push --all syncs the new order to Document360.",cmd:"/push --all"},"Reordered locally. ");vn($,v.text,{kind:"cmd",cmd:v.cmd,reason:""});return}case"restructure":{let b=qh(e,g);if(!b){f({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let $=await Se(b.prompt,{display:b.display,quietUser:!0});if(g.filter(k=>!k.startsWith("--")).length===0){vn($,null,null);return}let v=Ut(e,{text:"Restructured locally \u2014 /push --all moves it on Document360.",cmd:"/push --all"},"Restructured locally. ");vn($,v.text,{kind:"cmd",cmd:v.cmd,reason:""});return}case"review":{let b=Bh(e,g);if(b){f({kind:"note",tone:"ok",text:b.lines[0]});for(let W of b.closed)f({kind:"note",tone:"ok",text:W});let I=vi(e,g,null);I&&(f({kind:"note",tone:"info",text:"One thing left: no editor has looked at how your docs are organised since it last changed. Checking that now \u2014 it reads the shape, not the articles, so it is one quick pass."}),(await Se(I.prompt,{display:I.display,quietUser:!0})).producedNothing||w0(e,I.fingerprint)),Te(b.cta.text,{kind:"cmd",cmd:b.cta.cmd,reason:""});return}let $=Wh(e,g);if(!$){f({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let v=g.includes("--fix"),k=g.find(I=>!I.startsWith("--")),C=v?Qo(e,g,k):[],E=v?Lf(e):null,F={aborted:!1,partitions:0,failed:0,notRun:0},_,j=null,z=vi(e,g,$);if($.kind==="partitioned"){let I=await _0($,v,E,!!z);F=I.outcome,_=I,j=I.evidence}else _=await Se($.prompt,{display:$.display,quietUser:!0}),F={...F,producedNothing:_.producedNothing};if("aborted"in _&&_.aborted){let I=g.includes("--blocked")?"--blocked --fix":g.includes("--stale")?"--stale --fix":"--fix",W=Ce("/review",I,k);Te(`Stopped \u2014 the batches that finished are saved. ${W} picks up the rest${k||es(g)?"":", or narrow it with /review <category> --fix"}.`,{kind:"cmd",cmd:W,reason:""},"warn");return}if(z&&((await Se(z.prompt,{display:z.display,quietUser:!0})).producedNothing||w0(e,z.fingerprint)),$.kind!=="partitioned"&&v&&!_.producedNothing&&(j=Xo(e,C,E,s),j.earned.length>0))try{us(e,j.earned,wt("review"))}catch{}if(v&&Sn(`/review${k?` ${k}`:""}${g.includes("--all")?" --all":""}${g.includes("--blocked")?" --blocked":g.includes("--stale")?" --stale":""} --fix`,F),v){if(v&&!_.producedNothing){let me=oo(e,["--fix"],cs({cwd:e,scope:k}));me.lines.length>0&&f({kind:"note",tone:"ok",text:me.lines.join(`
|
|
596
|
+
`)})}let I=v&&!_.producedNothing?cs({cwd:e,scope:k}).filter(me=>!me.baselined&&me.severity==="error"):[],W=j?j.changed.length:-1,q=W<0?"Editor applied its fixes":$i(W),re=Jr(e,j?.unadopted??[],{lead:W===0&&I.length===0});if(re&&f({kind:"note",tone:"warn",text:re.lines.join(`
|
|
597
|
+
`)}),I.length>0){let me=new Set(I.map(Oe=>Oe.path)).size,be=`/lint${k?` ${k}`:""} --blocked --fix`,J=rn(e,be),xe=!j||j.changed.length>0;f({kind:"note",tone:"warn",text:xe?`\u26A0 The editor's rewrites left ${I.length} style error${I.length===1?"":"s"} in ${me} article${me===1?"":"s"} \u2014 recasting a sentence is where these appear.`:`\u26A0 ${I.length} style error${I.length===1?"":"s"} in ${me} article${me===1?"":"s"} still block${I.length===1?"s":""} publishing \u2014 the editor changed nothing, so these were already there.`}),vn(_,`${j?$i(j.changed.length):"Editor applied its fixes"}, but ${I.length} style error${I.length===1?"":"s"} remain. ${be} clears ${I.length===1?"it":"just those"} \u2014 it costs nothing to find them and one pass to correct${J?` (${J})`:""}. It is the last paid pass before publishing: anything still standing after a second attempt is reported for a person rather than run again.`,{kind:"cmd",cmd:be,reason:""});return}if(re?.cta){vn(_,re.cta.text,{kind:"cmd",cmd:re.cta.cmd,reason:""});return}let fe=Ut(e,{text:`\u2713 ${q} \u2014 your docs are ready. /push${k?"":" --all"} saves them to Document360 as drafts (or /lint${k?` ${k}`:""} for an instant no-token re-scan first).`,cmd:k?"/push":"/push --all"},`\u2713 ${q} in this scope. `,k);vn(_,fe.text,{kind:"cmd",cmd:fe.cmd,reason:""})}else{let I=k?` ${k}`:"",W=Za(e,k)===0&&el(e,k)===0?`; /push${k?"":" --all"} saves them to Document360 as-is`:"";vn(_,`The review listed issues above. /review${I} --fix lets the editor apply them all (or /lint${I} --fix for just the deterministic ones${W}).`,{kind:"cmd",cmd:`/review${I} --fix`,reason:""})}return}case"capture-setup":{await O();return}case"devhints":{if(!ve(e)){f({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}f({kind:"note",tone:"info",text:Ar(Tr(e)).join(`
|
|
598
|
+
`)}),xn(Oo()),Cs.current=en(e).status==="current",yr.current=Pn(e);return}case"discover":{if(!ve(e)){f({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await Se(Nd(),{display:"/discover",quietUser:!0});return}case"ask":{if(!ve(e)){f({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let b=g.join(" ").trim();if(b===""){f({kind:"block",text:Yp(H3(e)).join(`
|
|
599
|
+
`)});return}try{let $=B3(e,{question:b});f({kind:"note",tone:"ok",text:Vp($.file,pi(e)).join(`
|
|
600
|
+
`)})}catch($){f({kind:"note",tone:"warn",text:`Could not file the question: ${$.message}`})}return}case"inbox":{if(!ve(e)){f({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(Gp(e)===0){f({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 Se(qp(),{display:"/inbox",quietUser:!0});return}case"auto":{let b=ve(e);if(!b){f({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let $=Ad(g);if($.malformed){f({kind:"note",tone:"error",text:`I could not read that spending limit. Give it as an amount, like: /auto --budget 150 (the standard limit is ${ze(i3)}).`});return}let v=Ed(g,$.usd),k=C=>{for(let E of C)f({kind:"note",tone:E.tone,text:E.text});G(E=>E+1)};if($.usd!==void 0&&!v){let C=Td(e,b,$.usd);C&&k(C);return}if(!v||v==="status"){for(let C of Xs(b))f({kind:"note",tone:C.tone,text:C.text});return}if(v==="on"||v==="off"){v==="on"&&(Ro.current=!1);let C=$.usd!==void 0?{...b,auto:{...b.auto,enabled:b.auto?.enabled===!0,budgetUsd:$.usd}}:b;k(ll(e,C,v==="on"));return}f({kind:"note",tone:"error",text:`I don't know "${v}". Use: /auto on \xB7 /auto off \xB7 /auto status \xB7 /auto --budget <amount>`});return}case"share":{let b=ve(e);if(!b){f({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let $=g[0]?.trim().toLowerCase();if($==="status"){for(let k of Ll(e,b))f({kind:"note",tone:k.tone,text:k.text});return}if($==="on"||$==="off"){for(let k of Kp(e,b,$==="on"))f({kind:"note",tone:k.tone,text:k.text});G(k=>k+1);return}if($){f({kind:"note",tone:"error",text:`Unknown option: ${$} \u2014 use /share, /share status, /share on, or /share off.`});return}f({kind:"note",tone:"info",text:"Exchanging work with your team\u2026"});let v=await Ol(e,b);for(let k of v.lines)f({kind:"note",tone:k.tone,text:k.text});v.changed&&G(k=>k+1);return}case"feedback":{let b=f0(e),$="";try{$=ls(b)?Dc(b,"utf8"):""}catch{$=""}if(!/^## /m.test($)){f({kind:"note",tone:"info",text:"No open d360-writer feedback to copy \u2014 nothing logged in .d360-writer/tool-feedback.md yet."});return}let v=await $f($.trim());f({kind:"note",tone:v?"ok":"warn",text:v?"\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 ${b} and copy it manually.`}),v&&Qc(null);return}case"copy":{ym();return}case"document":{if(!ve(e)){f({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{push:b,skipReview:$,what:v}=vp(g);if(!v&&$p(e)===0){f({kind:"note",tone:"info",text:Rp});return}let k=`/document${v?` ${v}`:""}${b?" --push":""}`,C=await Se(xp(v),{display:k,quietUser:!0});b&&!C.producedNothing&&await bm({skipReview:$});return}case"catch-up":{if(!ve(e)){f({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!Eo(p.trim()))return;let{push:b,skipReview:$,includeUnfinished:v}=Jp(g);for(let q of await Xp(e))f({kind:"note",tone:q.tone,text:q.text});f({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let k=await rh({cwd:e,profileName:s});for(let q of sh(k))f({kind:"note",tone:q.startsWith("\u2713")?"ok":q.startsWith("\u2139")?"info":"warn",text:q});let C=fi(e);for(let q of Zp(C))f({kind:"note",tone:q.tone,text:q.text});let E=eh(e),F=v?[]:E,_=th(e,F);for(let q of nh(F,_))f({kind:"note",tone:q.tone,text:q.text});let j=on(e);f({kind:"note",tone:"info",text:Qp(j)});let z=Lf(e);De.current?.beginTurn({baseline:z,allowUnfinishedHints:v});let I=await Se(oh(C,{held:E.length,includeUnfinished:v},j.briefMoved),{display:`/catch-up${b?" --push":""}${v?` ${Ul}`:""}`,quietUser:!0});I.producedNothing||G3(e);let W=Yo(e,z,"","/catch-up");if(b&&!I.producedNothing)await bm({skipReview:$});else if(W.cta)vn(I,W.cta.text,{kind:"cmd",cmd:W.cta.cmd,reason:""});else{let q=_l({queued:j,hold:C.hold});vn(I,q.note,q.lead?{kind:"cmd",cmd:q.lead.cmd,reason:q.lead.reason}:null,q.tone)}return}case"comments":{if(!ve(e)){f({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!Eo(p.trim()))return;let b=uh(g);Fe("Checking Document360 for reviewer comments\u2026"),T(!0);let $=null;try{$=await Fl(e,s,{...b.scope,onProgress:(k,C)=>Fe(`Checking Document360 for reviewer comments\u2026 ${k}/${C}`)})}catch(k){f({kind:"note",tone:"error",text:`Couldn\u2019t read comments from Document360: ${k.message}`})}finally{T(!1),Fe(null)}if(!$)return;G(k=>k+1);let v=Ko($.threads,$.labels);if($.threads.length===0){f({kind:"note",tone:"ok",text:gi($,{showAnswered:b.showAnswered,width:rt()}).join(`
|
|
601
|
+
`)});return}if(b.answer&&(b.all||b.scope.path||b.scope.scope||v.length===1)){wr(lh($,{full:!0,showAnswered:b.showAnswered,width:rt()})),await ou(v,{resolve:b.resolve});return}if(v.length===1){wr(Wl(v[0],{width:rt()})),ms({group:v[0],cursor:0,fromList:!1,resolve:b.resolve,rest:[]});return}wr(gi($,{showAnswered:b.showAnswered,width:rt()})),bn({cursor:0,rows:Bl(v),groups:v,resolve:b.resolve,report:$});return}case"update":{if(Hl()){f({kind:"note",tone:"info",text:"Checking for a newer version\u2026"});let $=await p0({pkg:zo,currentVersion:o,force:!0}).catch(()=>null);if(!$?.updateAvailable||!$.latest){f({kind:"note",tone:"ok",text:`\u2713 You're on the latest version (v${o}).`});return}zi.current=!0,Gl($.latest),f({kind:"note",tone:"info",text:`\u2B06 Update v${$.latest} is ready.
|
|
602
|
+
Windows can't replace the files while d360-writer is running, so I'll install it the moment you /exit.`}),le("/exit");return}zi.current=!0,f({kind:"note",tone:"info",text:"Updating the d360-writer toolchain\u2026 (don\u2019t close this window)"}),mo(!0);let b=await bi().finally(()=>mo(!1));b.ok?(f({kind:"note",tone:"ok",text:`\u2713 Updated ${b.packages.join(" + ")} \u2014 run /exit, then relaunch to apply.`}),le("/exit"),Mi("")):(f({kind:"note",tone:"warn",text:`Update failed. ${wi(b.output)}`}),b.output&&f({kind:"note",tone:"info",text:`${b.output}
|
|
603
|
+
|
|
604
|
+
Full output: ${yi()}`}));return}case"screenshot":{let b=_s(g),$=Mo(e);if($&&b.mode!=="list"&&f({kind:"note",tone:"info",text:$}),b.mode==="capture"){await A(b.rest);return}if(b.mode==="annotate"){await U(b.rest);return}if(b.mode==="checklist"){await O();return}if(b.mode==="verify"){let C=He(e),E=b.rest.find(j=>!j.startsWith("-")),F=E?[E]:ai(C);if(E&&!C.some(j=>j.id===E)){f({kind:"note",tone:"error",text:`No screenshot placeholder called "${E}". /screenshot list shows them all.`});return}if(F.length===0){let j=C.filter(I=>I.state==="rejected").length,z=C.filter(I=>I.state==="verified").length;f({kind:"note",tone:"info",text:j>0?`Nothing left to verify. ${j} shot${j===1?"":"s"} failed verification \u2014 re-capture with /screenshot capture --failed.`:z>0?`All ${z} captured shot${z===1?" is":"s are"} already verified.`:"No captured screenshots to verify yet \u2014 /screenshot capture takes the shots first."});return}f({kind:"note",tone:"info",text:so(F.length)}),await Se(hn(e,F),{display:E?`/screenshot verify ${E}`:"/screenshot verify",quietUser:!0});let _=Vr(e,F);_.length>0&&f({kind:"note",tone:"info",text:_.join(`
|
|
605
|
+
`)});return}if(b.mode==="list"){if(!ve(e)){f({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let C=ve(e)?.docsDir??Wf,E=rd(e,b.scope),F=He(e,E);if(b.picker){if(F.length===0){f({kind:"note",tone:"info",text:"No screenshot placeholders found in the docs."});return}let j=Cy(F);if(j.length===0){f({kind:"note",tone:"info",text:qa(F,{docsDir:C}).join(`
|
|
606
|
+
`)});let z=Ce("/push","--screenshots",E),I=Ut(e,{text:`\u2713 All ${F.length} screenshots are captured. ${z} saves them into the articles on Document360; /screenshot capture${E?` ${E}`:""} re-captures.`,cmd:z},`\u2713 All ${F.length} screenshots are captured. `,E);Te(I.text,{kind:"cmd",cmd:I.cmd,reason:""});return}bo({cursor:0,rows:j,title:"Screenshots \u2014 pick what to author or capture:"});return}f({kind:"note",tone:"info",text:qa(F,{scope:E,detail:b.detail,docsDir:C}).join(`
|
|
607
|
+
`)}),$&&f({kind:"note",tone:"info",text:$});let _=od(F,E);_.key!=="done"&&le(_.cmd);return}if(b.mode==="single"){await $m(b.id);return}if(!ve(e)){f({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let v=b.mode==="scope"?b.scope:void 0,k=C3(e,{scope:v}).map(C=>C.id);if(k.length===0){f({kind:"note",tone:"info",text:v?`No screenshot placeholders under ${v}.`:"No screenshot placeholders found in the docs."});return}await km(k,{setup:b.setup,scope:b.mode==="scope"?b.scope:void 0,runLine:b.mode==="scope"?[`/screenshot author ${b.scope}`,`/screenshot ${b.scope}`]:["/screenshot author --all","/screenshot --all"]});return}case"capture":{await A(g);return}case"reset":{let b=mh(e);if(b.length===0){f({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}lr.current={repoName:Di(e),targets:b,hadDevhints:ls(h0(e))},f({kind:"note",tone:"warn",text:yh(e,b).join(`
|
|
608
|
+
`)}),st(Di(e));return}default:f({kind:"note",tone:"error",text:`Unknown command: /${d} \u2014 type /help.`})}},[e,r,s,kr,lu,f,Ve,Se,vt,ru,vm]),Es=ie(p=>{let m=(p??y).trim();if(x(""),ir(null),Mn(0),m.startsWith("/")){ee.current=!1,Ee.current=!1,_e.current=null,Jt(),$o(null);let g=Yi.current.includes(m);g&&(Yi.current=[]),ke(A=>g?[]:_v(A,m))}if(!m||(Pe(!1),Ne.current=!1,(lr.current||Ie.current.length>0)&&f({kind:"user",text:m}),Rm(m))||xm(m))return;_c.current.push(m);let d=Bv(m,ar.current);if(m.startsWith("/"))f({kind:"user",text:m}),N(!0),jo(d).finally(()=>N(!1));else if(z3(d)){f({kind:"user",text:m});let g=X3(d);if(!g)Se(d,{display:m,quietUser:!0});else{try{Q3(e,{title:g,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}Se(`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${g}". 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 "${g}" and the article path(s) you wrote.`,{display:m,quietUser:!0})}}else{let g=_y(e,d);Se(g??d,{display:m})}},[y,Rm,xm,jo,Se]),Sm=ie(p=>{if(p.length>1){if(p.includes("\x1B"))return;let m=Uv(p);if(Fv(m)){let d=Wv(++Ui.current,m);ar.current.set(d,m),w(d)}else w(m);return}w(p)},[w]),$r=Math.max(10,yt-6),Cm=Nc(()=>Ac(c.text,$r),[c.text,$r]),cu=ie(p=>h(m=>({...m,pos:Math.max(0,Math.min(m.text.length,m.pos+p))})),[]),aa=ie(p=>h(m=>({...m,pos:Gv(Ac(m.text,$r),m.pos,p)})),[$r]),Ns=ie(p=>h(m=>({...m,pos:qv(Ac(m.text,$r),m.pos,p)})),[$r]),U0=["\x1B[H","\x1B[1~","\x1BOH"],F0=["\x1B[F","\x1B[4~","\x1BOF"],Pm=ie((p,m)=>m.leftArrow?(cu(-1),!0):m.rightArrow?(cu(1),!0):p&&U0.includes(p)?(Ns("start"),!0):p&&F0.includes(p)?(Ns("end"),!0):m.ctrl&&p==="a"?(Ns("start"),!0):m.ctrl&&p==="e"?(Ns("end"),!0):!1,[cu,Ns]),uu=ie(()=>{if(Be.current){if(!Be.current.signal.aborted){let p=(mr?.verb??"work").toLowerCase(),m=mr?.unit??"article";f({kind:"note",tone:"warn",text:`\u238B Stopping the ${p} run (finishing in-flight ${m}s)\u2026`}),Be.current.abort()}return!0}return gs.current?!1:(gs.current=!0,f({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),De.current?.interrupt(),!0)},[mr]);return LO((p,m)=>{if(m.ctrl&&p==="c"){if(ys.current!==null&&Date.now()-ys.current<v0){ys.current=null,De.current?.close(),r();return}ys.current=Date.now(),Zf(!0),Wc.current&&clearTimeout(Wc.current),Wc.current=setTimeout(()=>{ys.current=null,Zf(!1)},v0),P?uu():y&&x("");return}if(Ss.current.awaySince!==null&&Qe.current===null)try{let d=Ev(Ss.current,Date.now(),on(e));if(Ss.current=d.memory,hm(null),d.kind==="delta"){f({kind:"note",tone:"info",text:Dv(d.delta,d.awayMs)});let g=$t(!1);g.kind==="recommend"&&$n(g.rec,{silent:!0})}else if(d.kind==="briefing"){f({kind:"note",tone:"info",text:`\u{1F4E5} ${Ei(d.delta)} arrived while you were away (${Tf(d.awayMs)}).`});let g=$t(!1);g.kind==="recommend"&&$n(g.rec)}}catch{}if(Jc.current=Date.now(),!R){if(mt){if(m.return){Wi(null),Bi.current=!0,G(d=>d+1),f({kind:"note",tone:"info",text:"\u25B6 Auto mode starting \u2014 esc stops it at any point, and nothing already done is undone."});return}if(p==="b"||p==="B"){Wi(null),x("/auto --budget ");return}if(m.escape){Wi(null),Ro.current=!0,Qe.current=null,f({kind:"note",tone:"info",text:"Left in manual for now \u2014 nothing started. Auto mode is still on: /auto on begins the round trip when you are ready, or /auto off switches it off."}),G(d=>d+1);return}return}if(m.tab&&m.shift&&!Fn&&!wn&&!eu){let d=ve(e);if(!d){f({kind:"note",tone:"info",text:"Set this repo up first with /init \u2014 then shift+tab switches between auto and manual."});return}let g=!r0(d);ll(e,d,g),g&&(Ro.current=!1);let A=!g&&Qe.current!==null;A&&(Qe.current={...Qe.current,stopping:!0}),f({kind:"note",tone:"ok",text:A?"Manual mode \u2014 I'll finish what is running and stop there, then hand back. (shift+tab to change it back.)":`${g?"Auto mode ON":"Manual mode"} \u2014 ${zs(g)} (shift+tab to change it back.)`}),G(U=>U+1);return}if(P){if(m.escape){if(Qe.current){Ro.current=!0;let d=Qe.current;uu(),Ts({kind:"stopped",how:"esc"},d.parked);return}uu();return}if(m.return){let d=y.trim();if(!d)return;xo.current.push(d),Fc([...xo.current]),x("");return}if(Pm(p,m))return;if(m.upArrow){aa(-1);return}if(m.downArrow){aa(1);return}if(m.backspace||m.delete){S();return}p&&!m.ctrl&&!m.meta&&Sm(p);return}if(wn){if(m.upArrow){yo(d=>d&&{...d,cursor:Math.max(0,d.cursor-1)});return}if(m.downArrow){yo(d=>d&&{...d,cursor:Math.min(Bt.length-1,d.cursor+1)});return}if(p&&/^[0-9]$/.test(p)){let d=kn(p,Bt.length);d!==null&&yo(g=>g&&{...g,cursor:d});return}if(m.return){let d=Bt[wn.cursor];yo(null);let{lines:g,changed:A,effective:U}=si(e,d.value??"default");for(let O of g)f({kind:"note",tone:O.startsWith("\u26A0")?"warn":O.startsWith("\u2713")?"ok":"info",text:O});A&&(rm(O=>O+1),De.current?.setModel(U));return}if(p==="s"){let d=Bt[wn.cursor];yo(null),De.current?.setModel(d.value??void 0),f({kind:"note",tone:"ok",text:`\u2713 Using ${d.label} for this session only (your saved default is unchanged).`});return}if(m.escape){yo(null);return}return}if(zt){if(m.upArrow){cr(d=>d&&{...d,cursor:Math.max(0,d.cursor-1)});return}if(m.downArrow){cr(d=>d&&{...d,cursor:Math.min(d.rows.length-1,d.cursor+1)});return}if(p&&/^[0-9]$/.test(p)){let d=kn(p,zt.rows.length);d!==null&&cr(g=>g&&{...g,cursor:d});return}if(m.return||p==="s"){let d=zt.rows[zt.cursor];if(cr(null),d.connect){Un({cursor:0,mode:"connect",rows:Gn()});return}oa(d.name,m.return===!0);return}if(m.escape){cr(null);return}return}if(ks){if(m.escape){Po(null);return}if(m.leftArrow||m.tab&&m.shift){Po(d=>d&&{tab:(d.tab-1+xt.length)%xt.length,scroll:0});return}if(m.rightArrow||m.tab){Po(d=>d&&{tab:(d.tab+1)%xt.length,scroll:0});return}if(p&&/^[1-9]$/.test(p)&&Number(p)<=xt.length){Po({tab:Number(p)-1,scroll:0});return}if(m.upArrow){Po(d=>d&&{...d,scroll:Math.max(0,d.scroll-1)});return}if(m.downArrow){Po(d=>{if(!d)return d;let g=(xt[d.tab]??xt[0]).rows.length;return{...d,scroll:Math.min(Math.max(0,g-1),d.scroll+1)}});return}return}if(Et){if(m.upArrow){Un(d=>d&&{...d,cursor:Math.max(0,d.cursor-1)});return}if(m.downArrow){Un(d=>d&&{...d,cursor:Math.min(d.rows.length-1,d.cursor+1)});return}if(p&&/^[0-9]$/.test(p)){let d=kn(p,Et.rows.length);d!==null&&Un(g=>g&&{...g,cursor:d});return}if(m.return){let d=Et.rows[Et.cursor].name,g=Et.mode;if(Un(null),g==="connect"){let O=new Set(Object.keys(ve(e)?.profiles??{})),b=d;for(let C=2;O.has(b);C++)b=`${d}-${C}`;let $=Pl(e,b,d);if($){f({kind:"note",tone:"error",text:$});return}let[v,...k]=Tl(b,d);f({kind:"note",tone:"ok",text:v}),f({kind:"note",tone:"info",text:`Saved as this repo\u2019s default, so everyone who pulls this repo publishes here.
|
|
609
|
+
Press s in /profile to use a profile for one session only.`});for(let C of k)f({kind:"note",tone:"warn",text:C});oa(b,!0);return}if(!Du(e,d).created){f({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}f({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${d}").`});let U=!1;try{let O=po(d);U=!!O&&!(or(O)&&!O.refreshToken)}catch{U=!1}f({kind:"note",tone:"info",text:U?`Next: sign in to ${d} and pick your project \u2014 you're already signed in here, so it'll be quick.`:`Next: sign in to Document360 (${d}) and pick your project.`}),le("/login"),G(O=>O+1);return}if(m.escape){Un(null);return}return}if(lt){if(m.upArrow){ur(d=>d&&{...d,cursor:Math.max(0,d.cursor-1)});return}if(m.downArrow){ur(d=>d&&{...d,cursor:Math.min(d.rows.length-1,d.cursor+1)});return}if(p&&/^[0-9]$/.test(p)){let d=kn(p,lt.rows.length);d!==null&&ur(g=>g&&{...g,cursor:d});return}if(m.return){let d=lt.rows[lt.cursor],{profile:g,projectId:A}=lt;ur(null),ra(g,A,d);return}if(m.escape){ur(null);return}return}if(ht){if(m.upArrow){wo(d=>d&&{...d,cursor:Math.max(0,d.cursor-1)});return}if(m.downArrow){wo(d=>d&&{...d,cursor:Math.min(d.rows.length-1,d.cursor+1)});return}if(p&&/^[0-9]$/.test(p)){let d=kn(p,ht.rows.length);d!==null&&wo(g=>g&&{...g,cursor:d});return}if(m.return){let d=ht.rows[ht.cursor],{profile:g}=ht;wo(null),ia(g,d);return}if(m.escape){wo(null);return}return}if(ft){if(m.upArrow){hr(d=>d&&{...d,cursor:Math.max(0,d.cursor-1)});return}if(m.downArrow){hr(d=>d&&{...d,cursor:Math.min(d.rows.length-1,d.cursor+1)});return}if(p===" "){hr(d=>d&&{...d,rows:d.rows.map((g,A)=>A===d.cursor?{...g,checked:!g.checked}:g)});return}if(m.return){let d=ft.rows.filter(g=>g.checked).map(g=>g.path);if(hr(null),d.length===0){f({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}Dd(e,d),f({kind:"note",tone:"ok",text:`\u2713 Scoped to ${d.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let g of d)f({kind:"note",tone:"info",text:` ${g}`});f({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(m.escape){hr(null);return}return}if(kt){if(m.upArrow){ko(d=>d&&{...d,cursor:Math.max(0,d.cursor-1)});return}if(m.downArrow){ko(d=>d&&{...d,cursor:Math.min(d.rows.length-1,d.cursor+1)});return}if(p&&/^[0-9]$/.test(p)){let d=kn(p,kt.rows.length);d!==null&&ko(g=>g&&{...g,cursor:d});return}if(m.return){let d=kt.rows[kt.cursor],g=kt.run;ko(null),g(d.token);return}if(m.escape){ko(null);return}return}if(Nt){if(m.upArrow){dr(d=>d&&{...d,cursor:Math.max(0,d.cursor-1)});return}if(m.downArrow){dr(d=>d&&{...d,cursor:Math.min(d.rows.length-1,d.cursor+1)});return}if(p&&/^[0-9]$/.test(p)){let d=kn(p,Nt.rows.length);d!==null&&dr(g=>g&&{...g,cursor:d});return}if(m.return){let d=Nt.rows[Nt.cursor],g=Nt.conflicts;dr(null),d.conflict?lu(d.paths[0]):d.kind==="article"?ru(d.paths[0]):vt(d.paths,d.kind==="all"?g:0);return}if(m.escape){dr(null);return}return}if(Xt){if(m.upArrow){pr(d=>d&&{...d,cursor:Math.max(0,d.cursor-1)});return}if(m.downArrow){pr(d=>d&&{...d,cursor:Math.min(d.rows.length,d.cursor+1)});return}if(p&&/^[0-9]$/.test(p)){let d=kn(p,Xt.rows.length+1);d!==null&&pr(g=>g&&{...g,cursor:d});return}if(m.return){let{cursor:d,rows:g,opts:A}=Xt;pr(null);let U=d===0?g:[g[d-1]];wm(U,A);return}if(m.escape){pr(null),f({kind:"note",tone:"info",text:"Left as drafts \u2014 nothing changed. /publish when they have been signed off."});return}return}if(Dt){let{rows:d}=Dt;if(m.upArrow){bn(g=>g&&{...g,cursor:Math.max(0,g.cursor-1)});return}if(m.downArrow){bn(g=>g&&{...g,cursor:Math.min(d.length-1,g.cursor+1)});return}if(p&&/^[0-9]$/.test(p)){let g=Rf(zf.current,Number(p),d.length-1);zf.current=g.memory,g.index!==null&&bn(A=>A&&{...A,cursor:g.index+1});return}if(p==="a"||p==="A"){bn(g=>g&&{...g,cursor:0});return}if(m.return){let g=d[Dt.cursor],{groups:A,resolve:U,report:O}=Dt;if(bn(null),g.kind==="all"){ou(A,{resolve:U,report:O});return}wr(Wl(g.group,{width:rt()})),ms({group:g.group,cursor:0,fromList:!0,resolve:U,rest:A.filter(b=>b.articleId!==g.group.articleId),report:O});return}if(m.escape){bn(null),le("/comments");return}return}if(ut){let d=()=>{let{rest:g,group:A,fromList:U,resolve:O,report:b}=ut;if(ms(null),!U||!b){le("/comments");return}let $=[A,...g].sort((v,k)=>v.category.localeCompare(k.category)||v.title.localeCompare(k.title));bn({cursor:0,rows:Bl($),groups:$,resolve:O,report:b})};if(m.upArrow||m.downArrow){ms(g=>g&&{...g,cursor:g.cursor===0?1:0});return}if(p==="y"||p==="Y"||m.return&&ut.cursor===0){let{group:g,resolve:A,rest:U,report:O}=ut;ms(null),ou([g],{resolve:A,rest:U,...O?{report:O}:{}});return}if(p==="b"||p==="B"||m.escape||m.return){d();return}return}if(Qt){if(m.upArrow){bo(d=>d&&{...d,cursor:Math.max(0,d.cursor-1)});return}if(m.downArrow){bo(d=>d&&{...d,cursor:Math.min(d.rows.length-1,d.cursor+1)});return}if(p&&/^[0-9]$/.test(p)){let d=kn(p,Qt.rows.length);d!==null&&bo(g=>g&&{...g,cursor:d});return}if(m.return){let d=Qt.rows[Qt.cursor];bo(null),d.action==="capture"?As(d.ids,{runLine:d.kind==="all"?["/screenshot capture --all","/capture --all"]:void 0}):d.action==="annotate"?na(d.ids,{verifiedBefore:new Set(He(e).filter(g=>g.state==="verified").map(g=>g.id))}):d.kind==="shot"?$m(d.ids[0]):km(d.ids,{setup:!0,runLine:d.kind==="all"?["/screenshot author --all","/screenshot --all"]:void 0});return}if(m.escape){bo(null);return}return}if(jt){if(m.escape){vo(null);return}if(m.upArrow){vo(d=>d&&{...d,cursor:Math.max(0,d.cursor-1)});return}if(m.downArrow){vo(d=>d&&{...d,cursor:Math.min(Math.max(0,Ji.length-1),d.cursor+1)});return}if(m.return){let d=Ji[jt.cursor];if(d){vo(null);try{f({kind:"preview",name:Di(d),text:R0(Dc(ji(e,d),"utf8"))})}catch(g){f({kind:"note",tone:"error",text:`Could not read ${d}: ${g.message}`})}}return}if(m.backspace||m.delete){vo(d=>d&&{...d,query:d.query.slice(0,-1),cursor:0});return}if(p&&!m.ctrl&&!m.meta&&p.length===1){vo(d=>d&&{...d,query:d.query+p,cursor:0});return}return}if(It){if(m.escape){Co(null);return}if(m.upArrow){Co(d=>d&&{...d,cursor:Math.max(0,d.cursor-1)});return}if(m.downArrow){Co(d=>d&&{...d,cursor:Math.min(Math.max(0,Zi.length-1),d.cursor+1)});return}if(m.return){let d=Zi[It.cursor];if(d){Co(null),Ve(d.uuid),nt.current={uuid:d.uuid,firstPrompt:d.firstPrompt,titleFired:!0},go(d.name),Df(d.uuid),de.current=[],gt.current={printed:[],armed:[],printedAt:gr.current};let g=Sf(e,d.uuid);for(let A of g)f(A);f({kind:"note",tone:"ok",text:g.length?`Resumed "${d.name}" \u2014 restored ${g.length} message(s); continue where you left off.`:`Resumed "${d.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(m.backspace||m.delete){Co(d=>d&&{...d,query:d.query.slice(0,-1),cursor:0});return}if(p&&!m.ctrl&&!m.meta&&p.length===1){Co(d=>d&&{...d,query:d.query+p,cursor:0});return}return}if(m.tab&&!y&&ne){x(ne),Jt();return}if(!y&&ye.length>0&&!Ne.current&&p&&/^[1-9]$/.test(p)){let d=ye[Number(p)-1];if(d){x(uo(d));return}}if(!y&&ye.length===0&&!Ne.current&>.current.armed.length>0&&p&&/^[1-9]$/.test(p)){let d=gt.current.armed[Number(p)-1];if(d){x(d);return}}if(!y&&(Rs||Wn)&&m.ctrl&&p==="y"){ym();return}if(!Pm(p,m)){if(eu){if(m.upArrow){Mn(d=>Math.max(0,d-1));return}if(m.downArrow){Mn(d=>Math.min(Rn.length-1,d+1));return}if(m.tab){x("/"+(Rn[sr]?.name??"")+" "),Mn(0);return}if(m.return){let d=Rn[sr];if(d){let g=y.trim().slice(1).split(/\s+/).slice(1).join(" ");if(Pw(d.usage)&&!g){x("/"+d.name+" "),Mn(0);return}Es("/"+d.name+(g?" "+g:""));return}}}else{if(!y&&ye.length>0&&!Ne.current&&(m.upArrow||m.downArrow)){if(m.downArrow){_n(d=>d===null?0:Math.min(ye.length-1,d+1));return}if(mn!==null){_n(d=>d===null||d===0?null:d-1);return}}if(m.upArrow){if(y!==""&&Yt===null){aa(-1);return}let d=_c.current;if(!d.length)return;let g=Yt===null?d.length-1:Math.max(0,Yt-1);ir(g),x(d[g]??"");return}if(m.downArrow){if(y!==""&&Yt===null){aa(1);return}let d=_c.current;if(Yt===null)return;let g=Yt+1;g>=d.length?(ir(null),x("")):(ir(g),x(d[g]??""));return}}if(m.return){if(mn!==null&&!y&&ye[mn]){let d=uo(ye[mn]);_n(null),Es(d);return}Es();return}if(m.backspace||m.delete){S();return}if(m.escape){Qe.current&&(Ro.current=!0,Ts({kind:"stopped",how:"esc"},Qe.current.parked)),x(""),Mn(0),Jt(),ke([]),$o(null),_n(null),ee.current=!0;return}p&&!m.ctrl&&!m.meta&&Sm(p)}}}),ct(()=>{if(P||R)return;let p=xo.current.shift();p!==void 0&&(Fc([...xo.current]),Es(p))},[P,R,Es]),ge(Le,{flexDirection:"column",width:yt,children:[nu!==null&&ge(Le,{marginTop:1,flexDirection:"column",children:[nu.truncated&&Y(K,{dimColor:!0,children:"\u2026"}),Y(K,{children:nu.text})]}),fr?Y(c6,{step:fr.step,cmd:fr.cmd,startedAt:fr.startedAt,spentUsd:Math.max(fr.spentUsd,Lt-(Qe.current?.stepStartedSpend??Lt)),budgetUsd:fr.budgetUsd}):null,P&&mr?Y(p6,{p:mr}):null,tm?Y(u6,{text:tm}):P&&!mr?Y(l6,{startTime:Vt.current,chars:_i}):null,Y(Le,{borderStyle:"round",borderColor:fm.prod?"yellow":ue,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:y?Cm.map((p,m)=>{let d=c.text.slice(p.start,p.end),g=m===Ec(Cm,c.pos),A=Math.min(c.pos,p.end)-p.start;return ge(K,{children:[Y(K,{color:ue,children:m===0?"> ":" "}),g?ge(nr,{children:[d.slice(0,A),Y(ds,{ch:d[A]??" "}),d.slice(A+1)]}):d||" "]},`${m}-${p.start}`)}):ge(K,{children:[Y(K,{color:ue,children:"> "}),Fn?Y(ds,{ch:" "}):he&&!P?ge(nr,{children:[Y(ds,{ch:he[0],dim:!0}),Y(K,{color:"gray",children:he.slice(1)})]}):ne&&!P?ge(nr,{children:[Y(ds,{ch:ne[0],dim:!0}),Y(K,{color:"gray",children:ne.slice(1)}),Y(K,{dimColor:!0,children:" (tab)"})]}):(Zc.isSetup||!an)&&!P?ge(nr,{children:[Y(ds,{ch:Zc.text[0],dim:!0}),Y(K,{color:"gray",children:Zc.text.slice(1)})]}):Y(ds,{ch:" "})]})}),Jf.length>0&&Y(Le,{flexDirection:"column",paddingX:1,children:Jf.map((p,m)=>Y(K,{color:"gray",children:`\u29D7 queued: ${p}`},`${m}-${p.slice(0,24)}`))}),mt?ge(Le,{flexDirection:"column",paddingX:1,children:[Y(K,{color:ue,bold:!0,children:"Auto mode \u2014 I run each step myself"}),Y(K,{color:"gray",children:` first step ${mt.firstCmd}${mt.scale?` \u2014 ${mt.scale}`:""}`}),mt.upcoming.length>0?ge(nr,{children:[Y(K,{color:"gray",children:" as things stand, after that:"}),mt.upcoming.map(p=>Y(K,{color:"gray",children:` ${p.cmd}${p.scale?` ${p.scale}`:""}`},p.cmd)),Y(K,{color:"gray",children:" each step changes what the next one finds, so this is not a total"})]}):Y(K,{color:"gray",children:" I work down the ladder from there \u2014 reviewing, checking style, saving and going live"}),[mt.scale,...mt.upcoming.map(p=>p.scale)].every(p=>!p?.includes("$"))?Y(K,{color:"gray",children:" no cost estimate yet \u2014 this repo has not finished a run for me to measure"}):null,Y(K,{color:"gray",children:` spending limit ${ze(mt.budgetUsd)} \xB7 I stop and report if it is reached`}),Y(K,{color:"gray",children:" screenshots are not part of an automatic run"}),mt.overBudget?Y(K,{color:"yellow",children:`\u26A0 That is more than your ${ze(mt.budgetUsd)} limit. I will stop partway and report what is left.`}):null,Y(K,{dimColor:!0,children:mt.overBudget?"b raise the limit \xB7 enter start anyway \xB7 esc stay in manual for now":"enter start \xB7 b change the limit \xB7 esc stay in manual for now"})]}):ks?Y(Iv,{tab:ks.tab,scroll:ks.scroll,rows:M0,width:yt,version:o,engineVersion:S0}):wn?ge(Le,{flexDirection:"column",paddingX:1,children:[Y(K,{color:ue,bold:!0,children:"Select model"}),Y(K,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),Bt.map((p,m)=>ge(K,{color:m===wn.cursor?ue:void 0,children:[m===wn.cursor?"\u276F ":" ",`${m+1}. ${p.label}${m===wn.current?" \u2714":""}`.padEnd(16),Y(K,{color:"gray",children:` ${p.desc}`})]},p.label)),Y(K,{dimColor:!0,children:Tt({verb:"set as default",rows:Bt.length,extra:["s this session only"]})})]}):zt?ge(Le,{flexDirection:"column",paddingX:1,children:[Y(K,{color:ue,bold:!0,children:"Switch connection profile"}),Y(K,{color:"gray",children:"Where this repo publishes. The environment lives on the profile, not on your login."}),Y(On,{rows:zt.rows,cursor:zt.cursor,cap:ln,render:(p,m,d)=>ge(K,{color:d?ue:void 0,children:[d?"\u276F ":" ",`${m+1}. ${p.name}${m===zt.current?" \u2714":""}`.padEnd(20),p.connect?null:Y(K,{color:"gray",children:` ${p.portalUrl||p.env}${p.project?` \xB7 ${p.project}`:""} \xB7 ${p.who??"not signed in"}`}),p.prod?Y(K,{color:"yellow",children:` ${Ye}`}):null,p.internal?Y(K,{color:"gray",children:" internal"}):null]},p.name)}),Y(K,{dimColor:!0,children:Tt({verb:"switch (saved as default)",rows:zt.rows.length,extra:["s this session only"]})})]}):Et?ge(Le,{flexDirection:"column",paddingX:1,children:[Y(K,{color:ue,bold:!0,children:"Pick your Document360 environment"}),Y(K,{color:"gray",children:"This is the portal your readers see. Rows marked internal are ours, not a customer's."}),Y(On,{rows:Et.rows,cursor:Et.cursor,cap:ln,render:(p,m,d)=>ge(K,{color:d?ue:void 0,children:[d?"\u276F ":" ",`${m+1}. ${p.name}`.padEnd(18),Y(K,{color:"gray",children:` ${p.portalUrl.replace(/^https:\/\//,"")}`}),p.note?p.internal||!p.production?Y(K,{color:"yellow",children:` \u26A0 ${p.note}`}):Y(K,{color:"gray",children:` ${p.note}`}):null]},p.name)}),Y(K,{dimColor:!0,children:Tt({verb:"use it",rows:Et.rows.length})})]}):lt?ge(Le,{flexDirection:"column",paddingX:1,children:[Y(K,{color:ue,bold:!0,children:"Switch workspace"}),Y(K,{dimColor:!0,children:`environment ${lt.environment} \xB7 project ${lt.projectName??`${lt.projectId.slice(0,8)}\u2026`}`}),Y(On,{rows:lt.rows,cursor:lt.cursor,cap:ln,render:(p,m,d)=>ge(K,{color:d?ue:void 0,children:[d?"\u276F ":" ",`${m+1}. ${p.name}${m===lt.current?" \u2714":""}`.padEnd(30),Y(K,{color:"gray",children:p.type?` ${p.type}`:""})]},p.id)}),Y(K,{dimColor:!0,children:Tt({verb:"switch",rows:lt.rows.length})})]}):ht?ge(Le,{flexDirection:"column",paddingX:1,children:[Y(K,{color:ue,bold:!0,children:"Choose project"}),Y(K,{dimColor:!0,children:`environment ${ht.environment}`}),Y(On,{rows:ht.rows,cursor:ht.cursor,cap:ln,render:(p,m,d)=>ge(K,{color:d?ue:void 0,children:[d?"\u276F ":" ",`${m+1}. ${p.name}${m===ht.current?" \u2714":""}`.padEnd(30),Y(K,{color:"gray",children:p.sub?` ${p.sub}`:""})]},p.id)}),Y(K,{dimColor:!0,children:Tt({verb:"switch",rows:ht.rows.length})})]}):ft?(()=>{let m=Math.min(Math.max(0,ft.cursor-Math.floor(7)),Math.max(0,ft.rows.length-14)),d=ft.rows.slice(m,m+14),g=ft.rows.filter(A=>A.checked).length;return ge(Le,{flexDirection:"column",paddingX:1,children:[Y(K,{color:ue,bold:!0,children:`Which folders back the user docs? (${g} selected of ${ft.rows.length})`}),m>0?Y(K,{dimColor:!0,children:` \u2191 ${m} more`}):null,d.map((A,U)=>{let O=m+U;return ge(K,{color:O===ft.cursor?ue:void 0,children:[O===ft.cursor?"\u276F ":" ",A.checked?"\u25C9 ":"\u25CB ",A.path.padEnd(Math.min(48,yt-34)),Y(K,{color:"gray",children:cl(A)})]},A.path)}),m+14<ft.rows.length?Y(K,{dimColor:!0,children:` \u2193 ${ft.rows.length-m-14} more`}):null,Y(K,{dimColor:!0,children:Tt({verb:"save",multi:!0})})]})})():kt?ge(Le,{flexDirection:"column",paddingX:1,children:[Y(K,{color:ue,bold:!0,children:kt.title??"Which category? (pick one to scope to)"}),Y(On,{rows:kt.rows,cursor:kt.cursor,cap:ln,render:(p,m,d)=>ge(K,{color:d?ue:void 0,children:[d?"\u276F ":" ",`${`${m+1}.`.padEnd(3)} ${p.label} (${p.count})`.padEnd(Math.min(44,Math.max(20,yt-24))),Y(K,{color:"gray",children:` ${p.token}`})]},p.token)}),Y(K,{dimColor:!0,children:Tt({verb:"choose it",rows:kt.rows.length})})]}):Nt?ge(Le,{flexDirection:"column",paddingX:1,children:[Y(K,{color:ue,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),Y(On,{rows:Nt.rows,cursor:Nt.cursor,cap:ln,render:(p,m,d)=>ge(K,{color:d?ue:void 0,bold:p.kind==="category"&&!d,children:[d?"\u276F ":" ",`${p.indent?" ":" "}${`${m+1}.`.padEnd(3)} ${p.label}`.padEnd(Math.min(56,yt-24)),p.note?Y(K,{color:"gray",children:` ${p.note}`}):null]},`${p.kind}:${p.paths.join(",")}`)}),Y(K,{dimColor:!0,children:Tt({verb:"push as drafts",rows:Nt.rows.length})})]}):Xt?ge(Le,{flexDirection:"column",paddingX:1,children:[Y(K,{color:ue,bold:!0,children:"Publish live to your readers \u2014 this is what they will see:"}),Y(On,{rows:[{path:"",articleId:"",label:`Publish all ${Xt.rows.length} live`,version:void 0},...Xt.rows],cursor:Xt.cursor,cap:ln,render:(p,m,d)=>ge(K,{color:d?ue:void 0,bold:m===0&&!d,children:[d?"\u276F ":" ",` ${`${m+1}.`.padEnd(3)} ${p.label}`.padEnd(Math.min(56,yt-24)),m>0?Y(K,{color:"gray",children:` ${p.version?`draft v${p.version} \u2192 live`:"draft \u2192 live"}`}):null]},`${m}:${p.path||"all"}`)}),Y(K,{dimColor:!0,children:Tt({verb:"publish live",cancel:"leave as drafts",rows:Xt.rows.length+1})})]}):Dt?ge(Le,{flexDirection:"column",paddingX:1,children:[Y(K,{color:ue,bold:!0,children:"Which comments do you want to look at?"}),Y(On,{rows:Dt.rows,cursor:Dt.cursor,cap:ln,render:(p,m,d)=>ge(K,{color:d?ue:void 0,bold:p.kind==="all"&&!d,children:[d?"\u276F ":" ",`${(p.kind==="all"?"":`${p.n}.`).padEnd(4)}${p.label}`.padEnd(Math.min(56,Math.max(20,yt-24))),p.kind==="article"?Y(K,{color:"gray",children:p.note}):null]},p.kind==="all"?"all":p.group.articleId)}),Y(K,{dimColor:!0,children:Tt({verb:"open it",cancel:"close",rows:Dt.rows.length-1})}),Dt.resolve?Y(K,{dimColor:!0,children:"--resolve is on: threads you answer will be closed as well as replied to"}):null]}):ut?ge(Le,{flexDirection:"column",paddingX:1,children:[Y(K,{color:ue,bold:!0,children:`${ut.group.title} \u2014 ${ut.group.threads.length} comment${ut.group.threads.length===1?"":"s"}`}),ge(K,{color:ut.cursor===0?ue:void 0,children:[ut.cursor===0?"\u276F ":" ",ut.resolve?"Yes \u2014 fix them, push the draft, reply and resolve":"Yes \u2014 fix them, push the draft to Document360, then reply"]}),ge(K,{color:ut.cursor===1?ue:void 0,children:[ut.cursor===1?"\u276F ":" ",ut.fromList?"No \u2014 back to the list":"No \u2014 leave them for now"]}),Y(K,{dimColor:!0,children:Tt({verb:"open it",cancel:"go back",extra:["y answer"]})})]}):Qt?ge(Le,{flexDirection:"column",paddingX:1,children:[Y(K,{color:ue,bold:!0,children:Qt.title}),(()=>{let{rows:p,cursor:m}=Qt,d=$c(p.length,m,ln),g=d.start,A=p.slice(d.start,d.end),U=`${p.length}.`.length+1,O=Sy(p,Math.max(20,yt-4-U));return ge(nr,{children:[g>0?Y(K,{color:"gray",children:` \u2026 ${g} more above`}):null,A.map((b,$)=>{let v=g+$,k=v===m,C=O[v];return ge(K,{color:k?ue:void 0,bold:(b.kind==="all"||b.kind==="category")&&!k,children:[k?"\u276F ":" ",`${v+1}.`.padEnd(U),C.head,C.note?Y(K,{color:"gray",children:C.note}):null]},`${b.action}:${b.kind}:${b.ids.join(",")}`)}),d.below>0?Y(K,{color:"gray",children:` \u2026 ${d.below} more below`}):null]})})(),Y(K,{dimColor:!0,children:Tt({verb:"run it",rows:Qt.rows.length})})]}):jt?ge(Le,{flexDirection:"column",paddingX:1,children:[Y(K,{color:ue,bold:!0,children:`Preview article${jt.query?` \u2014 filter: ${jt.query}`:" (type to filter)"}`}),Ji.length===0?Y(K,{color:"gray",children:"no articles match"}):Ji.map((p,m)=>ge(K,{color:m===jt.cursor?ue:void 0,children:[m===jt.cursor?"\u276F ":" ",p]},p)),Y(K,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):It?ge(Le,{flexDirection:"column",paddingX:1,children:[Y(K,{color:ue,bold:!0,children:`Resume session${It.query?` \u2014 filter: ${It.query}`:" (type to filter)"}`}),Zi.length===0?Y(K,{color:"gray",children:"no sessions match"}):Zi.map((p,m)=>ge(K,{color:m===It.cursor?ue:void 0,children:[m===It.cursor?"\u276F ":" ",p.name.slice(0,28).padEnd(30),Y(K,{color:m===It.cursor?ue:"gray",children:p.firstPrompt.slice(0,Math.max(10,yt-40))})]},p.uuid)),Y(K,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):eu?ge(Le,{flexDirection:"column",children:[No>0?Y(K,{dimColor:!0,children:` \u22EF ${No} more above`}):null,tu.map((p,m)=>{let d=No+m,g=p.name==="model"&&qc?`${p.desc} (currently ${qc})`:p.desc,A=Math.max(20,yt-4),U=p.usage.length>A?`${p.usage.slice(0,A-1)}\u2026`:p.usage,O=A-Math.max(U.length,22)-1,b=O<=1?"":g.length>O?`${g.slice(0,O-1)}\u2026`:g;return ge(K,{color:d===Qi?ue:void 0,children:[d===Qi?"\u276F ":" ",U.padEnd(22)," ",Y(K,{color:d===Qi?ue:"gray",children:b})]},p.name)}),No+tu.length<Rn.length?Y(K,{dimColor:!0,children:` \u22EF ${Rn.length-No-tu.length} more below`}):null,Y(K,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!P&&!y&&ye.length>0?ge(Le,{flexDirection:"column",paddingX:1,children:[Qf?Y(K,{color:ue,children:Qf}):null,Y(On,{rows:ye,cursor:mn??0,cap:ln,render:(p,m)=>{let d=m===mn,g=uo(p),A=g.slice(0,Math.max(20,yt-7)),U=yt-A.length-9,O=U>=12?(Mv(p)??Sw(g)).slice(0,U):"";return ge(K,{color:d?ue:void 0,children:[d?"\u276F ":" ",Y(K,{color:ue,children:m+1})," ",A,O?Y(K,{color:d?ue:void 0,dimColor:!d,children:` \u2014 ${O}`}):null]},g)}}),Y(K,{dimColor:!0,children:`\u2191\u2193 choose \xB7 enter run \xB7 1-${ye.length} fill \xB7 esc cancel`})]}):Y(Le,{paddingX:1,children:ge(K,{color:"gray",children:[fm.prod?Y(K,{color:"yellow",children:`${Ye} \xB7 `}):null,Y(K,{color:$s?ue:void 0,children:$s?"\u23F5\u23F5 auto":"\u23F5 manual"}),` \xB7 /help \xB7 ${qc??"model n/a"}${t.kind==="api"?Lt>0?` \xB7 session ${St(Lt)}`:"":om>0?` \xB7 ${Br(om)}`:""} \xB7 \u2191 history \xB7 shift+tab mode \xB7 ${D0?"press ctrl+c again to exit":"ctrl+c twice to exit"}`]})})]})}ae();import{jsx as g6}from"react/jsx-runtime";async function P0(e=process.cwd(),t="auto",n,o="0.0.0"){let r=m6(t);r.kind==="none"&&(console.error(""),console.error(L("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${Z("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${Z("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=f6(g6(C0,{cwd:e,auth:r,profileName:n,version:o}),{exitOnCtrlC:!1});await s(),await ql(),process.stdout.write(`
|
|
610
|
+
`),process.exit(0)}ae();import{writeCrashLog as Bf,isBenignTransportError as y6}from"document360-engine";var T0=!1;function w6(e=process.stdout){return e.destroyed===!0||e.writable===!1}function Hf(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function A0(e){if(T0)return;T0=!0;let t=(n,o)=>{if(y6(o)){Bf({kind:n,level:"transport",message:Hf(o),stack:o instanceof Error?o.stack:void 0,detail:e}),w6()&&(Bf({kind:"terminal-gone",level:"transport",message:"stdout is closed \u2014 the terminal this session was rendering to is gone, so it exited rather than spin.",detail:e}),process.exit(0));return}let r=Bf({kind:n,level:"fatal",message:Hf(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
|
|
611
|
+
`+L(`\u2717 d360-writer crashed: ${Hf(o)}`)+`
|
|
612
612
|
`),r&&process.stderr.write(u(` Crash details: ${r}`)+`
|
|
613
613
|
`+u(" Run: d360-writer logs")+`
|
|
614
|
-
`),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var
|
|
614
|
+
`),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var v6=k6(import.meta.url),Oc=v6("../package.json");A0("d360-writer");var Gt=new b6;function Gf(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}Gt.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=>{Gf(e),await pa({profile:e.profile,manual:e.manual})});Gt.command("logout").description("Remove the stored Document360 session for this repo's project").option("--profile <name>","Connection profile").option("--all-projects","Sign out of every Document360 project on this machine, not just this repo's").option("--env <name>",!1).action(async e=>{Gf(e),await Vm({profile:e.profile,allProjects:e.allProjects})});Gt.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Gf(e),await qm({profile:e.profile})});var qf=Gt.command("profile").description("Manage connection profiles for the current repo");qf.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>ha(process.cwd()));qf.command("use <name>").description("Set the default profile for this repo").action(e=>fa(process.cwd(),e));qf.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>ma(process.cwd(),e));var Vf=Gt.command("env").description("Document360 deployments this machine can connect to");Vf.command("list",{isDefault:!0}).description("List deployments (\u25CF = where this repo publishes)").action(()=>ig(process.cwd()));Vf.command("add <file>").description("Add deployments from a JSON file (- reads standard input)").action(e=>ag(process.cwd(),e));Vf.command("remove <name>").description("Remove a deployment added on this machine").action(e=>lg(process.cwd(),e));var E0=Gt.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");E0.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>Sr(process.cwd(),e.profile));E0.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await Lm(process.cwd(),e,t.profile)});var N0=Gt.command("project").description("Choose the Document360 project for this repo (active profile's identity)");N0.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>ua(process.cwd(),e.profile));N0.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await Mm(process.cwd(),e,t.profile)});Gt.command("init").description("Scaffold .d360-writer/config.json for this repo (interactive)").action(async()=>{let{initCommand:e}=await Promise.resolve().then(()=>(Ta(),Ug));await e()});Gt.command("logs").description("Show the last thing that went wrong, and where the logs are kept (/logs does the same inside the app, and offers to copy it)").action(()=>vu());Gt.command("doctor").description("Health-check: node, Claude auth, Document360 login, profile/workspace, category map, API reachability, and a real agent turn").action(async()=>{let{renderDoctorChecks:e,runDoctorChecks:t}=await Promise.resolve().then(()=>(Dl(),yb)),n=await t(process.cwd(),Oc.version);for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});Gt.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(Oc.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($6.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 ug(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 X$(e.cwd,e.auth,e.profile,Oc.version):await P0(e.cwd,e.auth,e.profile,Oc.version)});Gt.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
|