document360-writer 0.5.217 → 0.5.219
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 +179 -179
- package/package.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var Sm=Object.defineProperty;var ko=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var Kc=(e,t)=>{for(var n in t)Sm(e,n,{get:t[n],enumerable:!0})};import At from"picocolors";var te,Pm,Tm,Em,zc,bo,k,j,W,U,G,he,je,Q=ko(()=>{"use strict";te="#7f56d9",[Pm,Tm,Em]=[127,86,217],zc=e=>At.isColorSupported?`\x1B[38;2;${Pm};${Tm};${Em}m${e}\x1B[39m`:e,bo=e=>At.bold(zc(e)),k=e=>At.dim(e),j=e=>At.red(e),W=e=>At.yellow(e),U=e=>At.green(e),G=zc,he=e=>At.gray(e),je=e=>At.bold(e)});import{existsSync as Nn,writeFileSync as It,readFileSync as wg,readdirSync as kg}from"node:fs";import{join as yu}from"node:path";import{devHintsGuidePath as Fr,hintsDir as wu,hooksDir as ku,architectureDir as Ru,messagesDir as ji,creatorNotesPath as bu,devhintsStatePath as Cu,directivesPath as $u,DIRECTIVES_HEADER as bg,roadmapPath as vu,ROADMAP_HEADER as $g,ensureDir as xo,writeMessage as vg,listOpenForDev as xg}from"document360-engine";function Su(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
|
|
3
3
|
|
|
4
|
-
<!-- devhints script v${
|
|
4
|
+
<!-- devhints script v${ve} \xB7 maintained by document360-writer (/devhints). -->
|
|
5
5
|
|
|
6
6
|
This repo's user documentation is written by **document360-writer** ("the docs agent"), a separate agent.
|
|
7
7
|
It can read your code, but code alone can't tell it the *intent* \u2014 WHY a feature exists, which of a
|
|
@@ -235,7 +235,7 @@ do it**:
|
|
|
235
235
|
**Do NOT write or action the documentation yourself** \u2014 same boundary as Part 2. Writing the article is the
|
|
236
236
|
docs agent's job; it actions open directives on its next \`/catch-up\` (as drafts) and flips each to \`[done]\`
|
|
237
237
|
with the article it wrote. You are only the relay so the ask is captured durably and travels via git.
|
|
238
|
-
`}function
|
|
238
|
+
`}function Cg(){return`# Creator notes (optional \u2014 for the docs agent and the builder)
|
|
239
239
|
|
|
240
240
|
<!-- The ORIGINAL CREATOR's context. Most repos leave this empty \u2014 that's fine.
|
|
241
241
|
The builder agent reads this FIRST and treats it as authoritative when writing the architecture
|
|
@@ -249,12 +249,12 @@ Anything only a human knows that would help document this product. For example:
|
|
|
249
249
|
- Gotchas or non-obvious behavior.
|
|
250
250
|
|
|
251
251
|
(Replace these examples with your notes, or leave the file as-is to skip \u2014 it's optional.)
|
|
252
|
-
`}function
|
|
253
|
-
`)}
|
|
254
|
-
`)}function
|
|
255
|
-
`)}function
|
|
256
|
-
`)}),n.notifiedBuilder=!0))}catch{}return n}function
|
|
257
|
-
`)}function
|
|
252
|
+
`}function On(e){xo(wu(e)),xo(Ru(e)),xo(ji(e));for(let n of[wu(e),ji(e)]){let o=yu(n,".gitkeep");Nn(o)||It(o,`# Keeps this document360-writer inbox tracked in git even when empty.
|
|
253
|
+
`)}Nn(bu(e))||It(bu(e),Cg()),Nn($u(e))||It($u(e),bg),Nn(vu(e))||It(vu(e),$g),It(Fr(e),Su()),xo(ku(e)),It(yu(ku(e),"open-questions.mjs"),Rg);let t=ot(e);return Tu(e,new Date().toISOString()),t}async function Pu(e,t){for(let n of Ln(On(t.cwd)))console.log(n);return{kind:"continue"}}function sn(){return[`This is document360-writer's dev hand-off setup (v${ve}).`,'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": ${ve},`,' "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(`
|
|
254
|
+
`)}function Ni(e){try{let t=wg(Cu(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function Tu(e,t){let o={...Ni(e)??{},emittedVersion:ve,emittedAt:t};It(Cu(e),`${JSON.stringify(o,null,2)}
|
|
255
|
+
`)}function bt(e){try{return kg(Ru(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function ot(e){let n=Ni(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<ve?"stale":"current",completedVersion:n}}function Br(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:ve};try{if(!Nn(Fr(e)))return n;let o=Ni(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;ve>r&&(xo(ji(e)),It(Fr(e),Su()),Tu(e,t),n.guideRefreshed=!0),ve>s&&(xg(e).some(l=>l.kind==="request"&&l.subject.startsWith(xu))||(vg(e,{id:`onb${ve}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${xu}${ve})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${ve}${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:","",sn()].join(`
|
|
256
|
+
`)}),n.notifiedBuilder=!0))}catch{}return n}function Hr(e){if(!Nn(Fr(e)))return[];let t=ot(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${ve}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,In,sn(),In,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function Ii(){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(`
|
|
257
|
+
`)}function qr(){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):",In,Ii(),In]}function Ln(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${ve}.`," 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):",In,sn(),In,"","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 In,ve,Rg,xu,Ot=ko(()=>{"use strict";In="-".repeat(64),ve=12,Rg=`#!/usr/bin/env node
|
|
258
258
|
// d360-writer \u2014 session-start nudge for the builder ("John"). Surfaces open questions the docs agent
|
|
259
259
|
// ("Julie") left in .d360-writer/messages/ so they get answered, not forgotten. Self-contained (no deps);
|
|
260
260
|
// wired into your coding agent's session-start trigger by /devhints. See .d360-writer/DEV-HINTS-GUIDE.md.
|
|
@@ -292,203 +292,203 @@ try {
|
|
|
292
292
|
} catch {
|
|
293
293
|
/* a session-start nudge must never break the session */
|
|
294
294
|
}
|
|
295
|
-
`;
|
|
296
|
-
`),"utf8")}async function ji(){let e=process.cwd(),t=Su(e);if(In(t)&&!await bg({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(w("init cancelled.")),{kind:"continue"};let n=Du(e)??Cu(e),o=await bo({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await bo({message:"Capture directory (where document360-capture .spec.ts files live):",default:Tu}),s=await bo({message:"Screenshot output directory:",default:Eu}),i=await bo({message:"Default connection profile name:",default:"berlin"}),a=await bo({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),d={projectId:o,docsDir:Pu,captureDir:r,outputDir:s,profiles:{[i]:{connection:{environment:a},production:!1}},defaultProfile:i,authoritativeSourceFiles:ju(e)},h=Cg(e);h?.terminologyGlossary&&(d.terminologyGlossary=h.terminologyGlossary),Ru(d,e),Au(e);let m=jn(e);console.log(""),console.log(U(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${H(`d360-writer login --profile ${i}`)} ${w("(sign in; project & workspace auto-selected)")}`),console.log("");for(let k of Nn(m))console.log(k);return console.log(""),console.log(`${w("Then ask:")} ${H('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function Du(e){let t=Wr(e,"package.json");if(!In(t))return null;try{return JSON.parse($g(t,"utf8")).name??null}catch{return null}}function ju(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])In(Wr(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Wr(e,n);In(o)&&!Sg(o)&&t.push(n)}return t}function Sg(e){try{return vg(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var Br=mo(()=>{"use strict";X();jt()});import{createRequire as Kg}from"node:module";import{existsSync as zg,readFileSync as Xg}from"node:fs";import{dirname as ed,join as td}from"node:path";function kt(){let e;try{e=Qg.resolve("document360-capture/helpers")}catch{return null}let t=ed(e);for(let n=0;n<5&&!zg(td(t,"package.json"));n++)t=ed(t);try{let n=JSON.parse(Xg(td(t,"package.json"),"utf8"));return n.name==="document360-capture"&&n.version?n.version:null}catch{return null}}var Qg,Co=mo(()=>{"use strict";Qg=Kg(import.meta.url)});var Ep={};Hc(Ep,{doctorCommand:()=>Lo,renderDoctorChecks:()=>Tp,runDoctorChecks:()=>Pp});import{existsSync as ck}from"node:fs";import{d360GetAll as uk,getAccessToken as dk,isExpired as Xa,loadProfileMap as pk,loadTokens as hk,packageSkillsDir as Rp,ENGINE_VERSION as fk,projectConfigPath as mk,readProjectConfig as gk,DEFAULT_DOCS_DIR as yk,fetchManifestSummary as wk,resolveActiveProfile as kk,classifyClaudeAuth as bk,CLAUDE_CODE_SETUP_HINT as Sp,resolveModelSetting as $k,probeModel as vk,detectAppType as xk,playbookSkillName as Ck,D360AuthError as Rk,applyStructureOrder as Sk}from"document360-engine";async function Pp(e,t){let n=[],o=kt();n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${fk}${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=bk();s.state==="ready"?n.push({level:"ok",label:`Claude auth: ${s.kind==="api"?"API key":"subscription (Claude Code login found)"}`}):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. ${Sp}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:Sp});let i=$k(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 S=await vk(e,i.model??void 0);S.ok?n.push({level:"ok",label:`Model reachable \u2014 replied in ${(S.latencyMs/1e3).toFixed(1)}s`}):S.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 ${S.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=gk(e);if(!a)return n.push({level:"fail",label:`No ${mk(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${a.projectId}`});let d=(a.docsDir??yk).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 ${d}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let h=a.authoritativeSourceFiles??[];n.push(h.length>0?{level:"ok",label:`Sources: docs grounded in ${h.length} path(s) (${h.slice(0,3).join(", ")}${h.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 m=a.appType??xk(e);if(m){let S=a.appType?"from config":"auto-detected",C=m==="web"||m==="cli";n.push({level:"ok",label:`Genre: ${m} (${S})${C?` \u2192 ${Ck(m)} 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 k;try{k=kk(e),n.push({level:"ok",label:`Profile: ${k.name} (${k.connection.name})${k.production?" \u26A0 PRODUCTION":""}`})}catch(S){return n.push({level:"fail",label:`Profile config: ${S.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let v=hk(k.name);v?Xa(v)&&!v.refreshToken?n.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):Xa(v)?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 (until ${new Date(v.expiresAt).toLocaleString()})`}):n.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${k.name})`}),n.push(k.project.workspaceId?{level:"ok",label:`Workspace: ${k.project.workspaceName??k.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let R=pk(e,k.name);R?R.projectId&&k.project.projectId&&R.projectId!==k.project.projectId?n.push({level:"fail",label:`Category map projectId (${R.projectId}) \u2260 profile projectId (${k.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):n.push({level:"ok",label:`Category map: ${Object.keys(R.articles).length} articles, ${Object.keys(R.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${k.name}" (created on first /publish)`}),n.push(ck(Rp())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${Rp()}`,fix:"Reinstall document360-writer (broken install)"});let $=nt(e);if($.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${be})`}):$.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${$.completedVersion}, current is v${be}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),v&&(!Xa(v)||v.refreshToken)){let S={profile:k.name,connection:k.connection};try{await dk(S);let I=await uk(S,"/v3/projects");n.push({level:"ok",label:`API reachable (${k.connection.apiUrl}) \u2014 ${I.length} project(s) visible`})}catch(I){n.push({level:"fail",label:`API call failed: ${I.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let C=R?.projectId??k.project.projectId;if(C&&k.project.workspaceId){try{let I=await wk(S,C,k.project.workspaceId);if(I){let Y=(I.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Workspace sync manifest: available on ${k.connection.name} (${I.languages?.length??0} language${(I.languages?.length??0)===1?"":"s"}) \xB7 hash ${Y||"(none)"}`})}else n.push({level:"ok",label:`Workspace sync manifest: not live on ${k.connection.name} yet \u2014 sync uses the per-article path (nothing to do)`})}catch(I){I instanceof Rk||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(I.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${k.project.projectName??C})`,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 (${I.message.slice(0,80)})`})}try{let I=await Sk({cwd:e,profileName:k.name,dryRun:!0}),Y=I.categoriesReordered+I.articlesReordered;if(I.skipped==="no category map")n.push({level:"ok",label:"Reading order: nothing to check yet (no articles published)"});else if(I.skipped)n.push({level:"warn",label:`Reading order: can't be checked (${I.skipped})`,fix:"Your article order on Document360 may not match your structure \u2014 /publish syncs it once this resolves"});else if(I.unverified)n.push({level:"warn",label:`Reading order: ${I.unverified} of your articles aren't listed by Document360, so their order can't be set`,fix:"Usually means those articles are not published (the listing returns published articles). Publish them, then /publish re-syncs the order"});else if(Y>0){let q=[I.categoriesReordered>0?`${I.categoriesReordered} categor${I.categoriesReordered===1?"y":"ies"}`:"",I.articlesReordered>0?`${I.articlesReordered} article${I.articlesReordered===1?"":"s"}`:""].filter(Boolean);n.push({level:"warn",label:`Reading order: ${q.join(" + ")} out of order on Document360`,fix:"Run /publish \u2014 it re-syncs the order from your NN- folder/file prefixes"})}else n.push({level:"ok",label:"Reading order: Document360 matches your structure"})}catch(I){n.push({level:"warn",label:`Reading order: check failed (${I.message.slice(0,80)})`})}}}return n}function Tp(e){let t=[""];for(let r of e){let s=r.level==="ok"?U("\u2713"):r.level==="warn"?W("\u26A0"):j("\u2717");t.push(` ${s} ${r.label}${r.detail?w(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${w("fix:")} ${H(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?U(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):j(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function Lo(e,t){console.log(w("Running checks\u2026"));for(let n of Tp(await Pp(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var ws=mo(()=>{"use strict";jt();X();Co()});import{Command as u0}from"commander";import{createRequire as d0}from"node:module";import{AUTH_MODES as p0}from"document360-engine";import{input as Fm}from"@inquirer/prompts";import{loginPkce as Wm,refreshTokens as Bm,toStoredTokens as Qc,clearTokens as Hm,decodeJwtClaims as Xc,isExpired as qm,loadTokens as Gm,saveTokens as Jc,resolveActiveProfile as Tr,setProfileProject as Vm,readProjectConfig as Ym}from"document360-engine";X();import{select as Cm}from"@inquirer/prompts";import{resolveActiveProfile as Rm,setProfileProject as Sm,resolveProjectId as Pm,listWorkspaces as Tm}from"document360-engine";async function yo(e,t){let n=Rm(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Pm(o);return{workspaces:await Tm(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var Gc=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function $i(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 Rr(e,t,n,o,r){Sm(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function Vc(e,t,n){let o;try{o=await yo(e,n)}catch(s){return console.log(j(`Could not list workspaces: ${s.message}`)),1}let r=$i(o.workspaces,t);return r?(Rr(e,o.profile,o.projectId,r.id,r.name),console.log(U(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(j(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function En(e,t){let n;try{n=await yo(e,t)}catch(h){console.log(j(`Could not list workspaces: ${h.message}`));return}let{workspaces:o,projectId:r,profile:s,current:i}=n;if(o.length===0){console.log(w("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let h of o)console.log(` ${h.id===i?H("\u25CF"):" "} ${Gc(h)} ${w(h.id)}`);console.log(w("Run: d360-writer workspace use <name>"));return}let a=await Cm({message:"Select the Document360 workspace for this repo:",choices:o.map(h=>({name:`${Gc(h)}${h.id===i?" (current)":""}`,value:h.id}))}),d=o.find(h=>h.id===a);Rr(e,s,r,a,d?.name),console.log(U(`\u2713 Workspace set to "${d?.name??a}" for profile "${s}".`))}X();import{select as Em}from"@inquirer/prompts";import{resolveActiveProfile as Am,setProfileProject as Dm,listProjects as jm}from"document360-engine";async function Tt(e,t){let n=Am(e,t),o={profile:n.name,connection:n.connection};return{projects:await jm(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var Yc=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function vi(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 Sr(e,t,n,o){Dm(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function Kc(e,t,n){let o;try{o=await Tt(e,n)}catch(s){return console.log(j(`Could not list projects: ${s.message}`)),1}let r=vi(o.projects,t);return r?(Sr(e,o.profile,r.id,r.name),console.log(U(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log(j(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function Pr(e,t){let n;try{n=await Tt(e,t)}catch(d){console.log(j(`Could not list projects: ${d.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(w("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let d of o)console.log(` ${d.id===s?H("\u25CF"):" "} ${Yc(d)} ${w(d.id)}`);console.log(w("Run: d360-writer project use <name>"));return}let i=await Em({message:"Select the Document360 project for this repo:",choices:o.map(d=>({name:`${Yc(d)}${d.id===s?" (current)":""}`,value:d.id}))}),a=o.find(d=>d.id===i);Sr(e,r,i,a?.name),console.log(U(`\u2713 Project set to "${a?.name??i}" for profile "${r}". Next: pick a workspace.`))}X();import Nm from"picocolors";function Im(e=process.env){return e.FORCE_HYPERLINK==="0"||!Nm.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 Om(e,t=e,n){return Im(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Lm=/https?:\/\/[^\s\x1b]+/g;function wo(e,t){return e.replace(Lm,n=>Om(n,n,t))}import{readProjectConfig as zc,sunsetEnvironment as _m,resolveActiveProfile as Mm}from"document360-engine";function Um(e,t){let n=zc(e);return Object.entries(n?.profiles??{}).find(([,o])=>(o.connection?.environment??"berlin")===t)?.[0]??null}function Et(e,t){try{if(!zc(e))return null;let n=Mm(e,t),o=_m(n.connection.name);if(!o)return null;let r=Um(e,o.replacement);return{name:o.name,replacement:o.replacement,why:o.why,replacementProfile:r,cmd:r?`/profile ${r}`:`/profile add ${o.replacement}`}}catch{return null}}function Zc(e){return{...Xc(e.idToken)??{},...Xc(e.accessToken)??{}}}function Er(e){let t=Zc(e),n=t.email??t.preferred_username??t.sub??"unknown",o=t.doc360_project_id?` \xB7 project ${t.doc360_project_id}`:"";return`${n}${o}`}async function Ar(e){let t=Tr(process.cwd(),e.profile),n=t.connection;console.log(w(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=Et(process.cwd(),e.profile);o&&(console.log(W(`\u26A0 ${o.why} \u2014 and signing in does NOT change it (the environment comes from the profile, not the login).`)),console.log(W(` To move: ${o.cmd}${o.replacementProfile?"":", then /login"}`)));let r=await Wm(n,{manual:e.manual,promptForRedirect:i=>Fm({message:i})},i=>console.log(wo(i))),s=Qc(t.name,r);if(Jc(s),await xi(s,t.name,i=>console.log(w(i))),console.log(""),console.log(U(`\u2713 Logged in to "${t.name}" as ${Er(s)}`)),console.log(w(` access token expires: ${s.expiresAt}`)),console.log(w(` refresh token: ${s.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{Ym(process.cwd())?.profiles?.[t.name]&&(console.log(""),await En(process.cwd(),t.name))}catch{}}async function xi(e,t,n){let r=Zc(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Tr(process.cwd(),t).project.projectId)return;let i;try{let{projects:a}=await Tt(process.cwd(),t);i=a.find(d=>d.id===r)?.name}catch{}Vm(process.cwd(),t,{projectId:r,projectName:i}),n(` Project "${i??r}" written to profile "${t}".`)}catch{}}async function eu(e){let t=Tr(process.cwd(),e.profile),n=t.connection,o=Gm(t.name);if(!o){console.log(j(`Not logged in to Document360 (profile "${t.name}").`)),console.log(w(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${H(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Er(o)}`),qm(o))if(o.refreshToken)try{let r=Qc(t.name,await Bm(n,o.refreshToken));Jc(r),console.log(U(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(W(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(w(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(W("Session expired (no refresh token).")),console.log(w(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(w(` expires: ${o.expiresAt}`))}async function tu(e){let t=Tr(process.cwd(),e.profile);Hm(t.name)?console.log(U(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(w(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}X();import{readProjectConfig as nu,writeProjectConfig as Km,resolveActiveProfile as zm,loadTokens as Xm,isExpired as Qm}from"document360-engine";function Dr(e){let t=nu(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(j("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?H("\u25CF "):" ",s=o.production?W(" \u26A0 PRODUCTION"):"",i=o.connection.environment??"(inline)",a=Xm(n),d=a?Qm(a)&&!a.refreshToken?W("expired"):w("logged in"):w("not logged in");console.log(`${r}${H(n)} \u2192 ${i}${s} [${d}]`)}console.log(""),console.log(w("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function jr(e,t){let n=nu(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(j(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,Km(n,e);let o=n.profiles[t].production?W(" \u26A0 PRODUCTION"):"";console.log(U(`\u2713 Default profile is now "${t}"${o}`))}function Nr(e,t){try{let n=zm(e,t);console.log(""),console.log(`Profile ${H(n.name)}${n.production?W(" \u26A0 PRODUCTION"):""}`),console.log(w(` api: ${n.connection.apiUrl}`)),console.log(w(` identity: ${n.connection.authorizationUrl}`)),console.log(w(` clientId: ${n.connection.clientId}`)),console.log(w(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(w(` project: ${n.project.projectId??"(set at login)"}`)),console.log(w(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(j(n.message)),process.exitCode=1}}X();import{existsSync as Jm,readdirSync as Zm,statSync as ou}from"node:fs";import{join as ru}from"node:path";import{apiLogDir as eg}from"document360-engine";function su(){let e=eg();if(console.log(""),console.log(`Document360 API logs: ${H(e)}`),!Jm(e)){console.log(w(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Zm(e),n=t.filter(r=>r.endsWith(".jsonl")).sort().reverse(),o=t.filter(r=>/^crash-\d{4}-\d{2}-\d{2}\.log$/.test(r)).sort().reverse();n.length===0&&o.length===0&&console.log(w(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let s=(ou(ru(e,r)).size/1024).toFixed(1);console.log(` ${r} ${w(`${s} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${w("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let s=(ou(ru(e,r)).size/1024).toFixed(1);console.log(` ${j(r)} ${w(`${s} KB`)}`)}}console.log(""),console.log(w("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(w("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}X();import{createSession as tg,resolveAuth as ng,findByName as og,slugify as rg,touchSession as sg,upsertSession as ig,resolveActiveProfile as ag}from"document360-engine";async function iu(e,t,n,o,r,s){let i=ng(n);i.kind==="none"&&(console.error(""),console.error(j("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${H("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${H("d360-writer --auth subscription")}`),process.exit(2)),i.kind==="subscription"&&console.error(w("Using your Claude subscription (no API key set)."));let a=null;try{a=ag(e,r)}catch(v){console.error(j(`Document360 profile error: ${v.message}`)),process.exit(2)}a.production&&(console.error(W(`\u26A0 Profile "${a.name}" is PRODUCTION.`)),s||(console.error(j("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(w(" --yes given \u2014 proceeding against production.")));let d;if(o){let v=og(e,o);v||(console.error(j(`No saved session matches "${o}" in this repo.`)),console.error(w("List sessions inside the REPL with /resume.")),process.exit(2)),d=v.uuid,console.error(w(`Resuming "${v.name}"`))}let h=tg({cwd:e,resume:d,profileName:r,allowProdWrites:s===!0}),m=d??null,k=1;for await(let v of h.send(t))switch(v.type){case"session":if(!m){m=v.sessionId;let R=new Date().toISOString();ig({uuid:m,name:rg(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:R,updatedAt:R})}break;case"text":process.stdout.write(v.delta);break;case"tool":console.error(he(` \u2699 ${v.name}`));break;case"result":k=v.ok?0:1,console.error(w(`(${v.inputTokens}\u2192${v.outputTokens} tokens`+(v.costUsd>0?`, $${v.costUsd<.01?v.costUsd.toFixed(4):v.costUsd.toFixed(2)}`:"")+")")),v.ok||console.error(j("agent finished with an error result"));break;case"error":console.error(""),console.error(j(`agent error: ${v.message}`)),process.exit(1)}m&&sg(m),process.stdout.write(`
|
|
297
|
-
`),process.exit(
|
|
298
|
-
`)}var Ue=[{key:"start",label:"Getting Started",rows:[{t:"text",s:"D360-Writer reads your codebase, generates end-user documentation, and publishes it to Document360."},{t:"text",s:"It needs Claude access \u2014 a Claude subscription (default) or an ANTHROPIC_API_KEY."},{t:"gap"},{t:"sub",s:"Quick start"},{t:"step",n:1,s:"Run /init \u2014 pick your environment, sign in, choose your project & workspace. It ends by printing a one-paste hand-off prompt."},{t:"step",n:2,s:"Paste that prompt into your repo's coding agent (Claude Code / Codex / Cursor). Let it finish, then follow its closing line. (Re-show it: /devhints)"},{t:"step",n:3,s:"Run /doctor to confirm every check is green."},{t:"step",n:4,s:'Type "write the docs for this repository" and follow the prompts.'},{t:"gap"},{t:"dim",s:"That's it \u2014 D360-Writer drafts your docs without you writing a line."},{t:"gap"},{t:"sub",s:"Tips"},{t:"text",s:"Just talk to it \u2014 anything not starting with / goes to the agent."},{t:"dim",s:"/ browses commands \xB7 \u2191 recalls history \xB7 esc interrupts a run \xB7 ctrl+c exits"},{t:"dim",s:"tab runs the suggestion \xB7 1-9 pick from a list \xB7 c copies whatever was offered for copying"}]},{key:"agentic",label:"Agentic",rows:[{t:"text",s:"Agentic Mode is designed for applications built using AI coding agents. D360-Writer works alongside your coding agent to continuously create and maintain your user documentation. Think of it as hiring a Technical Writer dedicated to your project."},{t:"gap"},{t:"text",s:"As your coding agent ships new features, it leaves documentation notes for D360-Writer. All you need to do is run the documentation loop."},{t:"gap"},{t:"sub",s:"Every few days"},{t:"cmd",name:"/catch-up --publish",s:"Analyze the latest code changes, read the notes left by your coding agent, update the documentation, and publish the changes."},{t:"dim",s:" (or run /catch-up to review drafts first, then /publish when you're ready)"},{t:"gap"},{t:"sub",s:"Whenever you need"},{t:"cmd",name:"/discover",s:"Interview your coding agent to understand the product (what it is, who it's for, the core idea, common misconceptions) \u2014 pins a product brief that grounds every article. Runs before writing a repo's docs; loops until confident."},{t:"cmd",name:"/audit",s:"Preview what has changed and identify missing documentation, without writing or publishing anything."},{t:"cmd",name:"/pull",s:"Bring Document360 down \u2014 pull edits made in the portal and import any new portal articles."},{t:"cmd",name:"/resolve",s:"Resolve conflicts when an article was edited both here and in the portal \u2014 review the diff, then keep yours, take the portal's, or skip."},{t:"cmd",name:"/comments",s:"See the comments reviewers left on passages of your articles in the Document360 portal. Add --answer and D360-Writer makes each change and replies in the thread, resolving the ones it fully handled."},{t:"cmd",name:"/inbox",s:"Review and act on messages left by your coding agent."}]},{key:"assistant",label:"Assistant",rows:[{t:"text",s:"D360-Writer is your writing assistant \u2014 it does the writing, you decide what gets written and when."},{t:"text",s:"Best for large or complex monorepos: focus it on one feature, component, or set of source folders."},{t:"gap"},{t:"sub",s:"Just ask"},{t:"good",s:'"Write the documentation for the Multiple JWT feature we shipped in the latest release."'},{t:"gap"},{t:"sub",s:"Or use the pipeline"},{t:"cmd",name:"/scope",s:"Focus D360-Writer on specific source folders (monorepos)."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from its PRDs in .d360-writer/input/ + the code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview shows the plan + cost first)."},{t:"cmd",name:"/publish",s:"Publish the articles to Document360. Requires an editorial review first \u2014 /review --fix."}]},{key:"shots",label:"Screenshots",rows:[{t:"text",s:"Documenting a web app? D360-Writer marks where an image helps with a <!-- SCREENSHOT --> placeholder."},{t:"text",s:"The companion CLI d360-capture turns those into real, annotated screenshots by driving your app in a browser."},{t:"gap"},{t:"sub",s:"Flow"},{t:"step",n:1,s:"Write your docs as usual \u2014 placeholders are added where visuals help."},{t:"step",n:2,s:"Run /screenshot author --all to write the capture specs and refresh the capture checklist (data + test-ids the shots need)."},{t:"step",n:3,s:"Stage what the checklist asks for, then /screenshot capture \u2014 the writer drives a real browser that signs in, navigates, captures, annotates."},{t:"step",n:4,s:"Each new shot is then checked automatically: D360-Writer looks at the picture and marks it \u2714 verified, or flags what is wrong and fixes the spec for you."},{t:"step",n:5,s:"Run /publish --screenshots \u2014 it re-saves the articles with captured shots so the images embed on Document360."},{t:"gap"},{t:"sub",s:"One command family"},{t:"cmd",name:"/screenshot",s:"Bare: pick what to do next (author or capture, per shot)."},{t:"cmd",name:"/screenshot author",s:"Write capture specs (<id>, a path, or --all)."},{t:"cmd",name:"/screenshot capture",s:"Take the screenshots (<id>, a path, or --all; bare = pick ready specs)."},{t:"cmd",name:"/screenshot capture --failed",s:"Re-run just the shots that did not work \u2014 a failed run, or one that failed verification."},{t:"cmd",name:"/screenshot capture --blocked",s:"Re-run the shots waiting on app data, once you have staged it (a bulk run leaves them out by default)."},{t:"cmd",name:"/screenshot verify",s:"Look at the captured pictures and mark them verified (<id> for one). Runs automatically after a capture \u2014 run it yourself for shots taken before this existed, or after an interrupted run. No browser needed."},{t:"cmd",name:"/screenshot checklist",s:"What to stage + dev test-id requests (a report; auto-runs after bulk authoring)."},{t:"cmd",name:"/screenshot list",s:'Progress by chapter (\u2714 verified \xB7 \u25CF to verify \xB7 \u25D0 ready \xB7 \u2691 rejected \xB7 \u2298 blocked \xB7 \u2717 broken \xB7 \u25CB to-spec) plus the grouped "stage this data" worklist; list <chapter#> or --detail drills in.'},{t:"gap"},{t:"sub",s:"What done means"},{t:"text",s:"\u2714 verified is the finish line, not \u25CF captured. A captured shot only means a file exists; it counts as done once the picture has been looked at and judged fit for the article."},{t:"gap"},{t:"sub",s:"When a shot does not produce a usable image"},{t:"text",s:"\u2298 blocked means your app lacked the data the shot needs \u2014 /screenshot list groups every blocker into the handful of things to go and stage."},{t:"text",s:"\u2717 broken means the spec itself is out of date. Re-author it with /screenshot <id> (which carries the error into the fix); re-running the capture would fail the same way."},{t:"text",s:"\u2691 rejected means the shot ran but the picture is wrong \u2014 an empty placeholder where content should be, a callout on the wrong element, the subject unreadable. The spec is usually fixed for you; /screenshot capture --failed re-shoots. /screenshot list --detail shows each reason."},{t:"gap"},{t:"dim",s:"One-time setup in the app repo: npm i -g document360-capture \xB7 d360-capture init \xB7 d360-capture auth (real login, once per machine)."}]},{key:"cmds",label:"Commands",rows:[{t:"dim",s:"Grouped by job. Type any command, or just talk to the agent."},{t:"gap"},{t:"sub",s:"Getting started"},{t:"cmd",name:"/init",s:"Set up Document360 (environment, sign-in, project, hand-off prompt)."},{t:"cmd",name:"/login",s:"Sign in to Document360."},{t:"cmd",name:"/project",s:"Choose the Document360 project."},{t:"cmd",name:"/workspace",s:"Switch the workspace."},{t:"cmd",name:"/scope",s:"Choose which repo folders back the docs (monorepos)."},{t:"cmd",name:"/devhints",s:"Re-show the builder hand-off prompt."},{t:"gap"},{t:"sub",s:"Agentic \u2014 keep docs in sync"},{t:"cmd",name:"/roadmap",s:"The docs campaign: progress + the next step (`done` marks the next step finished)."},{t:"cmd",name:"/catch-up",s:"Do all pending work \u2192 drafts (--publish goes live)."},{t:"cmd",name:"/share",s:"Exchange work with your team: get your builder's latest, send yours (automatic; `off` to stop)."},{t:"cmd",name:"/publish",s:"Publish to Document360 (--all or a path). Needs /review --fix first."},{t:"cmd",name:"/audit",s:"Preview what changed / what's missing."},{t:"cmd",name:"/pull",s:"Pull portal edits + new articles (--status: report only)."},{t:"cmd",name:"/resolve",s:"Resolve local\u2194portal conflicts (diff \u2192 keep local / take portal / skip)."},{t:"cmd",name:"/comments",s:"Reviewer comments on your articles (--answer fixes them + replies)."},{t:"cmd",name:"/inbox",s:"Act on your coding agent's messages."},{t:"gap"},{t:"sub",s:"Assistant \u2014 directed writing"},{t:"cmd",name:"/discover",s:"Interview your builder \u2192 product brief that grounds the docs."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from PRDs + code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview first)."},{t:"cmd",name:"/preview",s:"Render an article locally."},{t:"gap"},{t:"sub",s:"Screenshots"},{t:"cmd",name:"/screenshot",s:"The screenshot pipeline: bare = pick; author / capture / checklist / 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 full result (bare: toggle)."},{t:"cmd",name:"/profile",s:"Switch/create a Document360 connection."},{t:"cmd",name:"/mcp",s:"Connect MCP servers (Notion, Linear, \u2026)."},{t:"cmd",name:"/allow-prod",s:"Authorize writes to a production profile."},{t:"cmd",name:"/doctor",s:"Health check: auth, profile, workspace, API."},{t:"cmd",name:"/update",s:"Update D360-Writer."},{t:"cmd",name:"/feedback",s:"Copy logged D360-Writer feedback to your clipboard (relay it to the team)."},{t:"cmd",name:"/reset",s:"Delete all D360-Writer files (confirms first)."},{t:"gap"},{t:"sub",s:"Session"},{t:"cmd",name:"/resume",s:"Resume a saved session."},{t:"cmd",name:"/rename",s:"Name the session."},{t:"cmd",name:"/clear",s:"Clear the screen and reset the conversation (resumable)."},{t:"cmd",name:"/help",s:"Show this help."},{t:"cmd",name:"/exit",s:"Quit."}]}],au=24;function Ci(e){let t=e.filter(n=>n.t==="cmd").map(n=>n.name.length);return t.length===0?au:Math.min(au,Math.max(...t))}function Lr(e,t,n,o){let r=" ".repeat(2+n+1),s=Math.max(24,o-r.length-2),i=At(t,s);return e.length>n?{nameCell:e,descLines:i,indent:r,nameOwnLine:!0}:{nameCell:e.padEnd(n),descLines:i,indent:r,nameOwnLine:!1}}function lg(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=Lr(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(`
|
|
299
|
-
`)}case"gap":return""}}function
|
|
295
|
+
`;xu="Re-run dev\u2194docs onboarding (protocol v"});var Mu={};Kc(Mu,{initCommand:()=>Li,scaffoldInit:()=>Oi});import{input as Ro,confirm as Sg}from"@inquirer/prompts";import{basename as Eu,join as Gr}from"node:path";import{existsSync as _n,readFileSync as Pg,readdirSync as Tg,writeFileSync as Eg}from"node:fs";import{writeProjectConfig as Au,readProjectConfig as Ag,projectConfigPath as Du,writerDir as Dg,DEFAULT_DOCS_DIR as ju,DEFAULT_CAPTURE_DIR as Nu,DEFAULT_OUTPUT_DIR as Iu}from"document360-engine";function Oi(e,t="berlin"){let n=Du(e);if(_n(n))return{created:!1,path:n,profileName:""};let o={projectId:Lu(e)??Eu(e),docsDir:ju,captureDir:Nu,outputDir:Iu,profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:_u(e)};return Au(o,e),Ou(e),{created:!0,path:n,profileName:t}}function Ou(e){let t=Gr(Dg(e),".gitignore");_n(t)||Eg(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
|
|
296
|
+
`),"utf8")}async function Li(){let e=process.cwd(),t=Du(e);if(_n(t)&&!await Sg({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(k("init cancelled.")),{kind:"continue"};let n=Lu(e)??Eu(e),o=await Ro({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await Ro({message:"Capture directory (where document360-capture .spec.ts files live):",default:Nu}),s=await Ro({message:"Screenshot output directory:",default:Iu}),i=await Ro({message:"Default connection profile name:",default:"berlin"}),l=await Ro({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),d={projectId:o,docsDir:ju,captureDir:r,outputDir:s,profiles:{[i]:{connection:{environment:l},production:!1}},defaultProfile:i,authoritativeSourceFiles:_u(e)},h=Ag(e);h?.terminologyGlossary&&(d.terminologyGlossary=h.terminologyGlossary),Au(d,e),Ou(e);let m=On(e);console.log(""),console.log(U(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${G(`d360-writer login --profile ${i}`)} ${k("(sign in; project & workspace auto-selected)")}`),console.log("");for(let w of Ln(m))console.log(w);return console.log(""),console.log(`${k("Then ask:")} ${G('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function Lu(e){let t=Gr(e,"package.json");if(!_n(t))return null;try{return JSON.parse(Pg(t,"utf8")).name??null}catch{return null}}function _u(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])_n(Gr(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Gr(e,n);_n(o)&&!jg(o)&&t.push(n)}return t}function jg(e){try{return Tg(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var Vr=ko(()=>{"use strict";Q();Ot()});import{createRequire as ey}from"node:module";import{existsSync as ty,readFileSync as ny}from"node:fs";import{dirname as sd,join as id}from"node:path";function vt(){let e;try{e=oy.resolve("document360-capture/helpers")}catch{return null}let t=sd(e);for(let n=0;n<5&&!ty(id(t,"package.json"));n++)t=sd(t);try{let n=JSON.parse(ny(id(t,"package.json"),"utf8"));return n.name==="document360-capture"&&n.version?n.version:null}catch{return null}}var oy,To=ko(()=>{"use strict";oy=ey(import.meta.url)});var Np={};Kc(Np,{doctorCommand:()=>Fo,renderDoctorChecks:()=>jp,runDoctorChecks:()=>Dp});import{existsSync as gk}from"node:fs";import{d360GetAll as yk,getAccessToken as wk,isExpired as tl,loadProfileMap as kk,loadTokens as bk,packageSkillsDir as Ep,ENGINE_VERSION as $k,projectConfigPath as vk,readProjectConfig as xk,DEFAULT_DOCS_DIR as Rk,fetchManifestSummary as Ck,resolveActiveProfile as Sk,classifyClaudeAuth as Pk,CLAUDE_CODE_SETUP_HINT as Ap,resolveModelSetting as Tk,probeModel as Ek,detectAppType as Ak,playbookSkillName as Dk,D360AuthError as jk,applyStructureOrder as Nk}from"document360-engine";async function Dp(e,t){let n=[],o=vt();n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${$k}${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=Pk();s.state==="ready"?n.push({level:"ok",label:`Claude auth: ${s.kind==="api"?"API key":"subscription (Claude Code login found)"}`}):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. ${Ap}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:Ap});let i=Tk(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 T=await Ek(e,i.model??void 0);T.ok?n.push({level:"ok",label:`Model reachable \u2014 replied in ${(T.latencyMs/1e3).toFixed(1)}s`}):T.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 ${T.error??"no output"} (a docs turn will end with 0 tokens / no output)`,fix:'Check sign-in, the selected model (/model), and network access to the Claude endpoint; confirm with: claude -p "say hi"'})}let l=xk(e);if(!l)return n.push({level:"fail",label:`No ${vk(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${l.projectId}`});let d=(l.docsDir??Rk).replace(/\/+$/,"");n.push(l.mode==="engineer"?{level:"warn",label:"Mode: engineer \u2014 agent may modify any source file (dogfooding)",fix:'Remove "mode" from .d360-writer/config.json for the writer-mode boundary'}:{level:"ok",label:`Mode: writer \u2014 edits limited to ${d}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let h=l.authoritativeSourceFiles??[];n.push(h.length>0?{level:"ok",label:`Sources: docs grounded in ${h.length} path(s) (${h.slice(0,3).join(", ")}${h.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 m=l.appType??Ak(e);if(m){let T=l.appType?"from config":"auto-detected",R=m==="web"||m==="cli";n.push({level:"ok",label:`Genre: ${m} (${T})${R?` \u2192 ${Dk(m)} 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 w;try{w=Sk(e),n.push({level:"ok",label:`Profile: ${w.name} (${w.connection.name})${w.production?" \u26A0 PRODUCTION":""}`})}catch(T){return n.push({level:"fail",label:`Profile config: ${T.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),n}let x=bk(w.name);x?tl(x)&&!x.refreshToken?n.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):tl(x)?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 (until ${new Date(x.expiresAt).toLocaleString()})`}):n.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${w.name})`}),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 S=kk(e,w.name);S?S.projectId&&w.project.projectId&&S.projectId!==w.project.projectId?n.push({level:"fail",label:`Category map projectId (${S.projectId}) \u2260 profile projectId (${w.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):n.push({level:"ok",label:`Category map: ${Object.keys(S.articles).length} articles, ${Object.keys(S.categories).length} categories`}):n.push({level:"ok",label:`Category map: none yet for "${w.name}" (created on first /publish)`}),n.push(gk(Ep())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${Ep()}`,fix:"Reinstall document360-writer (broken install)"});let $=ot(e);if($.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${ve})`}):$.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${$.completedVersion}, current is v${ve}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),x&&(!tl(x)||x.refreshToken)){let T={profile:w.name,connection:w.connection};try{await wk(T);let I=await yk(T,"/v3/projects");n.push({level:"ok",label:`API reachable (${w.connection.apiUrl}) \u2014 ${I.length} project(s) visible`})}catch(I){n.push({level:"fail",label:`API call failed: ${I.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let R=S?.projectId??w.project.projectId;if(R&&w.project.workspaceId){try{let I=await Ck(T,R,w.project.workspaceId);if(I){let Y=(I.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Workspace sync manifest: available on ${w.connection.name} (${I.languages?.length??0} language${(I.languages?.length??0)===1?"":"s"}) \xB7 hash ${Y||"(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(I){I instanceof jk||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(I.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${w.project.projectName??R})`,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 (${I.message.slice(0,80)})`})}try{let I=await Nk({cwd:e,profileName:w.name,dryRun:!0}),Y=I.categoriesReordered+I.articlesReordered;if(I.skipped==="no category map")n.push({level:"ok",label:"Reading order: nothing to check yet (no articles published)"});else if(I.skipped)n.push({level:"warn",label:`Reading order: can't be checked (${I.skipped})`,fix:"Your article order on Document360 may not match your structure \u2014 /publish syncs it once this resolves"});else if(I.unverified)n.push({level:"warn",label:`Reading order: ${I.unverified} of your articles aren't listed by Document360, so their order can't be set`,fix:"Usually means those articles are not published (the listing returns published articles). Publish them, then /publish re-syncs the order"});else if(Y>0){let q=[I.categoriesReordered>0?`${I.categoriesReordered} categor${I.categoriesReordered===1?"y":"ies"}`:"",I.articlesReordered>0?`${I.articlesReordered} article${I.articlesReordered===1?"":"s"}`:""].filter(Boolean);n.push({level:"warn",label:`Reading order: ${q.join(" + ")} out of order on Document360`,fix:"Run /publish \u2014 it re-syncs the order from your NN- folder/file prefixes"})}else n.push({level:"ok",label:"Reading order: Document360 matches your structure"})}catch(I){n.push({level:"warn",label:`Reading order: check failed (${I.message.slice(0,80)})`})}}}return n}function jp(e){let t=[""];for(let r of e){let s=r.level==="ok"?U("\u2713"):r.level==="warn"?W("\u26A0"):j("\u2717");t.push(` ${s} ${r.label}${r.detail?k(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${k("fix:")} ${G(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?U(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):j(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function Fo(e,t){console.log(k("Running checks\u2026"));for(let n of jp(await Dp(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var $s=ko(()=>{"use strict";Ot();Q();To()});import{Command as v0}from"commander";import{createRequire as x0}from"node:module";import{AUTH_MODES as R0}from"document360-engine";import{input as Vm}from"@inquirer/prompts";import{loginPkce as Ym,refreshTokens as Km,toStoredTokens as nu,clearTokens as zm,decodeJwtClaims as tu,isExpired as Xm,loadTokens as Qm,saveTokens as ou,resolveActiveProfile as jr,setProfileProject as Jm,readProjectConfig as Zm}from"document360-engine";Q();import{select as Am}from"@inquirer/prompts";import{resolveActiveProfile as Dm,setProfileProject as jm,resolveProjectId as Nm,listWorkspaces as Im}from"document360-engine";async function $o(e,t){let n=Dm(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Nm(o);return{workspaces:await Im(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var Xc=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function Ci(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 Er(e,t,n,o,r){jm(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function Qc(e,t,n){let o;try{o=await $o(e,n)}catch(s){return console.log(j(`Could not list workspaces: ${s.message}`)),1}let r=Ci(o.workspaces,t);return r?(Er(e,o.profile,o.projectId,r.id,r.name),console.log(U(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(j(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function jn(e,t){let n;try{n=await $o(e,t)}catch(h){console.log(j(`Could not list workspaces: ${h.message}`));return}let{workspaces:o,projectId:r,profile:s,current:i}=n;if(o.length===0){console.log(k("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let h of o)console.log(` ${h.id===i?G("\u25CF"):" "} ${Xc(h)} ${k(h.id)}`);console.log(k("Run: d360-writer workspace use <name>"));return}let l=await Am({message:"Select the Document360 workspace for this repo:",choices:o.map(h=>({name:`${Xc(h)}${h.id===i?" (current)":""}`,value:h.id}))}),d=o.find(h=>h.id===l);Er(e,s,r,l,d?.name),console.log(U(`\u2713 Workspace set to "${d?.name??l}" for profile "${s}".`))}Q();import{select as Om}from"@inquirer/prompts";import{resolveActiveProfile as Lm,setProfileProject as _m,listProjects as Mm}from"document360-engine";async function Dt(e,t){let n=Lm(e,t),o={profile:n.name,connection:n.connection};return{projects:await Mm(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var Jc=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Si(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 Ar(e,t,n,o){_m(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function Zc(e,t,n){let o;try{o=await Dt(e,n)}catch(s){return console.log(j(`Could not list projects: ${s.message}`)),1}let r=Si(o.projects,t);return r?(Ar(e,o.profile,r.id,r.name),console.log(U(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log(j(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function Dr(e,t){let n;try{n=await Dt(e,t)}catch(d){console.log(j(`Could not list projects: ${d.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(k("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let d of o)console.log(` ${d.id===s?G("\u25CF"):" "} ${Jc(d)} ${k(d.id)}`);console.log(k("Run: d360-writer project use <name>"));return}let i=await Om({message:"Select the Document360 project for this repo:",choices:o.map(d=>({name:`${Jc(d)}${d.id===s?" (current)":""}`,value:d.id}))}),l=o.find(d=>d.id===i);Ar(e,r,i,l?.name),console.log(U(`\u2713 Project set to "${l?.name??i}" for profile "${r}". Next: pick a workspace.`))}Q();import Um from"picocolors";function Wm(e=process.env){return e.FORCE_HYPERLINK==="0"||!Um.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 Fm(e,t=e,n){return Wm(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Bm=/https?:\/\/[^\s\x1b]+/g;function vo(e,t){return e.replace(Bm,n=>Fm(n,n,t))}import{readProjectConfig as eu,sunsetEnvironment as Hm,resolveActiveProfile as qm}from"document360-engine";function Gm(e,t){let n=eu(e);return Object.entries(n?.profiles??{}).find(([,o])=>(o.connection?.environment??"berlin")===t)?.[0]??null}function jt(e,t){try{if(!eu(e))return null;let n=qm(e,t),o=Hm(n.connection.name);if(!o)return null;let r=Gm(e,o.replacement);return{name:o.name,replacement:o.replacement,why:o.why,replacementProfile:r,cmd:r?`/profile ${r}`:`/profile add ${o.replacement}`}}catch{return null}}function ru(e){return{...tu(e.idToken)??{},...tu(e.accessToken)??{}}}function Nr(e){let t=ru(e),n=t.email??t.preferred_username??t.sub??"unknown",o=t.doc360_project_id?` \xB7 project ${t.doc360_project_id}`:"";return`${n}${o}`}async function Ir(e){let t=jr(process.cwd(),e.profile),n=t.connection;console.log(k(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=jt(process.cwd(),e.profile);o&&(console.log(W(`\u26A0 ${o.why} \u2014 and signing in does NOT change it (the environment comes from the profile, not the login).`)),console.log(W(` To move: ${o.cmd}${o.replacementProfile?"":", then /login"}`)));let r=await Ym(n,{manual:e.manual,promptForRedirect:i=>Vm({message:i})},i=>console.log(vo(i))),s=nu(t.name,r);if(ou(s),await Pi(s,t.name,i=>console.log(k(i))),console.log(""),console.log(U(`\u2713 Logged in to "${t.name}" as ${Nr(s)}`)),console.log(k(` access token expires: ${s.expiresAt}`)),console.log(k(` refresh token: ${s.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{Zm(process.cwd())?.profiles?.[t.name]&&(console.log(""),await jn(process.cwd(),t.name))}catch{}}async function Pi(e,t,n){let r=ru(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(jr(process.cwd(),t).project.projectId)return;let i;try{let{projects:l}=await Dt(process.cwd(),t);i=l.find(d=>d.id===r)?.name}catch{}Jm(process.cwd(),t,{projectId:r,projectName:i}),n(` Project "${i??r}" written to profile "${t}".`)}catch{}}async function su(e){let t=jr(process.cwd(),e.profile),n=t.connection,o=Qm(t.name);if(!o){console.log(j(`Not logged in to Document360 (profile "${t.name}").`)),console.log(k(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${G(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Nr(o)}`),Xm(o))if(o.refreshToken)try{let r=nu(t.name,await Km(n,o.refreshToken));ou(r),console.log(U(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(W(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(k(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(W("Session expired (no refresh token).")),console.log(k(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(k(` expires: ${o.expiresAt}`))}async function iu(e){let t=jr(process.cwd(),e.profile);zm(t.name)?console.log(U(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(k(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}Q();import{readProjectConfig as au,writeProjectConfig as eg,resolveActiveProfile as tg,loadTokens as ng,isExpired as og}from"document360-engine";function Or(e){let t=au(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(j("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?G("\u25CF "):" ",s=o.production?W(" \u26A0 PRODUCTION"):"",i=o.connection.environment??"(inline)",l=ng(n),d=l?og(l)&&!l.refreshToken?W("expired"):k("logged in"):k("not logged in");console.log(`${r}${G(n)} \u2192 ${i}${s} [${d}]`)}console.log(""),console.log(k("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function Lr(e,t){let n=au(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(j(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,eg(n,e);let o=n.profiles[t].production?W(" \u26A0 PRODUCTION"):"";console.log(U(`\u2713 Default profile is now "${t}"${o}`))}function _r(e,t){try{let n=tg(e,t);console.log(""),console.log(`Profile ${G(n.name)}${n.production?W(" \u26A0 PRODUCTION"):""}`),console.log(k(` api: ${n.connection.apiUrl}`)),console.log(k(` identity: ${n.connection.authorizationUrl}`)),console.log(k(` clientId: ${n.connection.clientId}`)),console.log(k(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(k(` project: ${n.project.projectId??"(set at login)"}`)),console.log(k(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(j(n.message)),process.exitCode=1}}Q();import{existsSync as rg,readdirSync as sg,statSync as lu}from"node:fs";import{join as cu}from"node:path";import{apiLogDir as ig}from"document360-engine";function uu(){let e=ig();if(console.log(""),console.log(`Document360 API logs: ${G(e)}`),!rg(e)){console.log(k(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=sg(e),n=t.filter(r=>r.endsWith(".jsonl")).sort().reverse(),o=t.filter(r=>/^crash-\d{4}-\d{2}-\d{2}\.log$/.test(r)).sort().reverse();n.length===0&&o.length===0&&console.log(k(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let s=(lu(cu(e,r)).size/1024).toFixed(1);console.log(` ${r} ${k(`${s} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${k("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let s=(lu(cu(e,r)).size/1024).toFixed(1);console.log(` ${j(r)} ${k(`${s} KB`)}`)}}console.log(""),console.log(k("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(k("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}Q();import{createSession as ag,resolveAuth as lg,findByName as cg,slugify as ug,touchSession as dg,upsertSession as pg,resolveActiveProfile as hg}from"document360-engine";async function du(e,t,n,o,r,s){let i=lg(n);i.kind==="none"&&(console.error(""),console.error(j("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${G("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${G("d360-writer --auth subscription")}`),process.exit(2)),i.kind==="subscription"&&console.error(k("Using your Claude subscription (no API key set)."));let l=null;try{l=hg(e,r)}catch(x){console.error(j(`Document360 profile error: ${x.message}`)),process.exit(2)}l.production&&(console.error(W(`\u26A0 Profile "${l.name}" is PRODUCTION.`)),s||(console.error(j("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(k(" --yes given \u2014 proceeding against production.")));let d;if(o){let x=cg(e,o);x||(console.error(j(`No saved session matches "${o}" in this repo.`)),console.error(k("List sessions inside the REPL with /resume.")),process.exit(2)),d=x.uuid,console.error(k(`Resuming "${x.name}"`))}let h=ag({cwd:e,resume:d,profileName:r,allowProdWrites:s===!0}),m=d??null,w=1;for await(let x of h.send(t))switch(x.type){case"session":if(!m){m=x.sessionId;let S=new Date().toISOString();pg({uuid:m,name:ug(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:S,updatedAt:S})}break;case"text":process.stdout.write(x.delta);break;case"tool":console.error(he(` \u2699 ${x.name}`));break;case"result":w=x.ok?0:1,console.error(k(`(${x.inputTokens}\u2192${x.outputTokens} tokens`+(x.costUsd>0?`, $${x.costUsd<.01?x.costUsd.toFixed(4):x.costUsd.toFixed(2)}`:"")+")")),x.ok||console.error(j("agent finished with an error result"));break;case"error":console.error(""),console.error(j(`agent error: ${x.message}`)),process.exit(1)}m&&dg(m),process.stdout.write(`
|
|
297
|
+
`),process.exit(w)}import{createInterface as dv}from"node:readline/promises";import{createSession as Gl,resolveAuth as pv,getSession as hv,setTitle as fv,slugify as mv,touchSession as Xh,upsertSession as gv,generateTitle as yv,resolveActiveProfile as Qh,resolveModelSetting as wv,readProjectConfig as kv,readUserConfig as bv,resolveAndPersistAppType as $v,decodeJwtClaims as Kh,isExpired as vv,loadTokens as xv,isDirectiveMention as Rv,stripDirectiveMention as Cv,appendDirective as Sv,reconcileUpgradeActions as Pv,stampArticles as Tv,listArticleFiles as Ev,CONTENT_CAP_VERSION as Av,applyStructureOrder as Dv,orderSyncLine as jv,computeSyncStatus as Nv}from"document360-engine";import{ENGINE_VERSION as gg}from"document360-engine";function Nt(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 Mr(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 l of Nt(`${i+1}. ${s.feature}`,76))o.push(n(l));o.push(n());for(let l of Nt(s.why,73))o.push(n(` ${l}`));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 Ur(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(`
|
|
298
|
+
`)}var Ue=[{key:"start",label:"Getting Started",rows:[{t:"text",s:"D360-Writer reads your codebase, generates end-user documentation, and publishes it to Document360."},{t:"text",s:"It needs Claude access \u2014 a Claude subscription (default) or an ANTHROPIC_API_KEY."},{t:"gap"},{t:"sub",s:"Quick start"},{t:"step",n:1,s:"Run /init \u2014 pick your environment, sign in, choose your project & workspace. It ends by printing a one-paste hand-off prompt."},{t:"step",n:2,s:"Paste that prompt into your repo's coding agent (Claude Code / Codex / Cursor). Let it finish, then follow its closing line. (Re-show it: /devhints)"},{t:"step",n:3,s:"Run /doctor to confirm every check is green."},{t:"step",n:4,s:'Type "write the docs for this repository" and follow the prompts.'},{t:"gap"},{t:"dim",s:"That's it \u2014 D360-Writer drafts your docs without you writing a line."},{t:"gap"},{t:"sub",s:"Tips"},{t:"text",s:"Just talk to it \u2014 anything not starting with / goes to the agent."},{t:"dim",s:"/ browses commands \xB7 \u2191 recalls history \xB7 esc interrupts a run \xB7 ctrl+c exits"},{t:"dim",s:"tab runs the suggestion \xB7 1-9 pick from a list \xB7 c copies whatever was offered for copying"}]},{key:"agentic",label:"Agentic",rows:[{t:"text",s:"Agentic Mode is designed for applications built using AI coding agents. D360-Writer works alongside your coding agent to continuously create and maintain your user documentation. Think of it as hiring a Technical Writer dedicated to your project."},{t:"gap"},{t:"text",s:"As your coding agent ships new features, it leaves documentation notes for D360-Writer. All you need to do is run the documentation loop."},{t:"gap"},{t:"sub",s:"Every few days"},{t:"cmd",name:"/catch-up",s:"Analyze the latest code changes, read the notes left by your coding agent, and update the documentation. Everything lands as a draft."},{t:"cmd",name:"/review --fix",s:"A senior editor reads every article and applies its fixes. Required before anything goes live \u2014 these were written by an AI."},{t:"cmd",name:"/publish --all",s:"Push the reviewed articles live to your readers."},{t:"dim",s:" (/catch-up --publish runs the first and last steps back-to-back, once the review is done)"},{t:"gap"},{t:"sub",s:"Whenever you need"},{t:"cmd",name:"/discover",s:"Interview your coding agent to understand the product (what it is, who it's for, the core idea, common misconceptions) \u2014 pins a product brief that grounds every article. Runs before writing a repo's docs; loops until confident."},{t:"cmd",name:"/audit",s:"Preview what has changed and identify missing documentation, without writing or publishing anything."},{t:"cmd",name:"/pull",s:"Bring Document360 down \u2014 pull edits made in the portal and import any new portal articles."},{t:"cmd",name:"/resolve",s:"Resolve conflicts when an article was edited both here and in the portal \u2014 review the diff, then keep yours, take the portal's, or skip."},{t:"cmd",name:"/comments",s:"See the comments reviewers left on passages of your articles in the Document360 portal. Add --answer and D360-Writer makes each change and replies in the thread, resolving the ones it fully handled."},{t:"cmd",name:"/inbox",s:"Review and act on messages left by your coding agent."}]},{key:"assistant",label:"Assistant",rows:[{t:"text",s:"D360-Writer is your writing assistant \u2014 it does the writing, you decide what gets written and when."},{t:"text",s:"Best for large or complex monorepos: focus it on one feature, component, or set of source folders."},{t:"gap"},{t:"sub",s:"Just ask"},{t:"good",s:'"Write the documentation for the Multiple JWT feature we shipped in the latest release."'},{t:"gap"},{t:"sub",s:"Or use the pipeline"},{t:"cmd",name:"/scope",s:"Focus D360-Writer on specific source folders (monorepos)."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from its PRDs in .d360-writer/input/ + the code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview shows the plan + cost first)."},{t:"cmd",name:"/publish",s:"Publish the articles to Document360. Requires an editorial review first \u2014 /review --fix."}]},{key:"shots",label:"Screenshots",rows:[{t:"text",s:"Documenting a web app? D360-Writer marks where an image helps with a <!-- SCREENSHOT --> placeholder."},{t:"text",s:"The companion CLI d360-capture turns those into real, annotated screenshots by driving your app in a browser."},{t:"gap"},{t:"sub",s:"Flow"},{t:"step",n:1,s:"Write your docs as usual \u2014 placeholders are added where visuals help."},{t:"step",n:2,s:"Run /screenshot author --all to write the capture specs and refresh the capture checklist (data + test-ids the shots need)."},{t:"step",n:3,s:"Stage what the checklist asks for, then /screenshot capture \u2014 the writer drives a real browser that signs in, navigates, captures, annotates."},{t:"step",n:4,s:"Each new shot is then checked automatically: D360-Writer looks at the picture and marks it \u2714 verified, or flags what is wrong and fixes the spec for you."},{t:"step",n:5,s:"Run /publish --screenshots \u2014 it re-saves the articles with captured shots so the images embed on Document360."},{t:"gap"},{t:"sub",s:"One command family"},{t:"cmd",name:"/screenshot",s:"Bare: pick what to do next (author or capture, per shot)."},{t:"cmd",name:"/screenshot author",s:"Write capture specs (<id>, a path, or --all)."},{t:"cmd",name:"/screenshot capture",s:"Take the screenshots (<id>, a path, or --all; bare = pick ready specs)."},{t:"cmd",name:"/screenshot capture --failed",s:"Re-run just the shots that did not work \u2014 a failed run, or one that failed verification."},{t:"cmd",name:"/screenshot capture --blocked",s:"Re-run the shots waiting on app data, once you have staged it (a bulk run leaves them out by default)."},{t:"cmd",name:"/screenshot verify",s:"Look at the captured pictures and mark them verified (<id> for one). Runs automatically after a capture \u2014 run it yourself for shots taken before this existed, or after an interrupted run. No browser needed."},{t:"cmd",name:"/screenshot checklist",s:"What to stage + dev test-id requests (a report; auto-runs after bulk authoring)."},{t:"cmd",name:"/screenshot list",s:'Progress by chapter (\u2714 verified \xB7 \u25CF to verify \xB7 \u25D0 ready \xB7 \u2691 rejected \xB7 \u2298 blocked \xB7 \u2717 broken \xB7 \u25CB to-spec) plus the grouped "stage this data" worklist; list <chapter#> or --detail drills in.'},{t:"gap"},{t:"sub",s:"What done means"},{t:"text",s:"\u2714 verified is the finish line, not \u25CF captured. A captured shot only means a file exists; it counts as done once the picture has been looked at and judged fit for the article."},{t:"gap"},{t:"sub",s:"When a shot does not produce a usable image"},{t:"text",s:"\u2298 blocked means your app lacked the data the shot needs \u2014 /screenshot list groups every blocker into the handful of things to go and stage."},{t:"text",s:"\u2717 broken means the spec itself is out of date. Re-author it with /screenshot <id> (which carries the error into the fix); re-running the capture would fail the same way."},{t:"text",s:"\u2691 rejected means the shot ran but the picture is wrong \u2014 an empty placeholder where content should be, a callout on the wrong element, the subject unreadable. The spec is usually fixed for you; /screenshot capture --failed re-shoots. /screenshot list --detail shows each reason."},{t:"gap"},{t:"dim",s:"One-time setup in the app repo: npm i -g document360-capture \xB7 d360-capture init \xB7 d360-capture auth (real login, once per machine)."}]},{key:"cmds",label:"Commands",rows:[{t:"dim",s:"Grouped by job. Type any command, or just talk to the agent."},{t:"gap"},{t:"sub",s:"Getting started"},{t:"cmd",name:"/init",s:"Set up Document360 (environment, sign-in, project, hand-off prompt)."},{t:"cmd",name:"/login",s:"Sign in to Document360."},{t:"cmd",name:"/project",s:"Choose the Document360 project."},{t:"cmd",name:"/workspace",s:"Switch the workspace."},{t:"cmd",name:"/scope",s:"Choose which repo folders back the docs (monorepos)."},{t:"cmd",name:"/devhints",s:"Re-show the builder hand-off prompt."},{t:"gap"},{t:"sub",s:"Agentic \u2014 keep docs in sync"},{t:"cmd",name:"/roadmap",s:"The docs campaign: progress + the next step (`done` marks the next step finished)."},{t:"cmd",name:"/catch-up",s:"Do all pending work \u2192 drafts (--publish then runs the gated publish)."},{t:"cmd",name:"/share",s:"Exchange work with your team: get your builder's latest, send yours (automatic; `off` to stop)."},{t:"cmd",name:"/publish",s:"Publish to Document360 (--all or a path). Needs /review --fix first."},{t:"cmd",name:"/audit",s:"Preview what changed / what's missing."},{t:"cmd",name:"/pull",s:"Pull portal edits + new articles (--status: report only)."},{t:"cmd",name:"/resolve",s:"Resolve local\u2194portal conflicts (diff \u2192 keep local / take portal / skip \u2014 one at a time, or all at once)."},{t:"cmd",name:"/comments",s:"Reviewer comments on your articles (--answer fixes them + replies)."},{t:"cmd",name:"/inbox",s:"Act on your coding agent's messages."},{t:"gap"},{t:"sub",s:"Assistant \u2014 directed writing"},{t:"cmd",name:"/discover",s:"Interview your builder \u2192 product brief that grounds the docs."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from PRDs + code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview first)."},{t:"cmd",name:"/preview",s:"Render an article locally."},{t:"gap"},{t:"sub",s:"Screenshots"},{t:"cmd",name:"/screenshot",s:"The screenshot pipeline: bare = pick; author / capture / checklist / 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 full result (bare: toggle)."},{t:"cmd",name:"/profile",s:"Switch/create a Document360 connection."},{t:"cmd",name:"/mcp",s:"Connect MCP servers (Notion, Linear, \u2026)."},{t:"cmd",name:"/allow-prod",s:"Authorize writes to a production profile."},{t:"cmd",name:"/doctor",s:"Health check: auth, profile, workspace, API."},{t:"cmd",name:"/update",s:"Update D360-Writer."},{t:"cmd",name:"/feedback",s:"Copy logged D360-Writer feedback to your clipboard (relay it to the team)."},{t:"cmd",name:"/reset",s:"Delete all D360-Writer files (confirms first)."},{t:"gap"},{t:"sub",s:"Session"},{t:"cmd",name:"/resume",s:"Resume a saved session."},{t:"cmd",name:"/rename",s:"Name the session."},{t:"cmd",name:"/clear",s:"Clear the screen and reset the conversation (resumable)."},{t:"cmd",name:"/help",s:"Show this help."},{t:"cmd",name:"/exit",s:"Quit."}]}],pu=24;function Ti(e){let t=e.filter(n=>n.t==="cmd").map(n=>n.name.length);return t.length===0?pu:Math.min(pu,Math.max(...t))}function Wr(e,t,n,o){let r=" ".repeat(2+n+1),s=Math.max(24,o-r.length-2),i=Nt(t,s);return e.length>n?{nameCell:e,descLines:i,indent:r,nameOwnLine:!0}:{nameCell:e.padEnd(n),descLines:i,indent:r,nameOwnLine:!1}}function fg(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=Wr(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(`
|
|
299
|
+
`)}case"gap":return""}}function hu(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 Ue){n.push(`\u2500\u2500 ${o.label} \u2500\u2500`,"");let r=Ti(o.rows);for(let s of o.rows)n.push(fg(s,r,100));n.push("")}return n.push("Tip: anything not starting with / goes to the agent."),n}function Ei(e,t){return Nt(e,Math.max(10,Math.max(20,t)-2))}function mg(e,t,n){let o=Math.max(20,n),r=s=>Math.max(1,Ei(s,o).length);switch(e.t){case"gap":return 1;case"cmd":{let s=Wr(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 fu(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=mg(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 mu(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 Ai(e=[],t){console.log("");let n=t?.version?{version:t.version,engineVersion:gg}:void 0;for(let o of hu(n))console.log(o);return console.log(""),console.log("Reporting a problem? Run `d360-writer logs` for the API log files."),console.log(""),{kind:"continue"}}Q();import{getSession as yg}from"document360-engine";async function gu(e,t){let n=t.currentUuid(),o=n?yg(n):void 0;return console.log(o?k(`
|
|
300
300
|
(conversation reset \u2014 "${o.name}" is still available via /resume)
|
|
301
|
-
`):
|
|
301
|
+
`):k(`
|
|
302
302
|
(conversation reset \u2014 agent will start fresh on the next prompt)
|
|
303
|
-
`)),{kind:"clear"}}async function
|
|
303
|
+
`)),{kind:"clear"}}async function Di(){return{kind:"exit"}}Vr();Q();import{readMcpConfig as _i,writeMcpConfig as Uu}from"document360-engine";async function Yr(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(Ng(),{kind:"continue"}):t==="add"?(Ig(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(Og(e.slice(1)),{kind:"continue"}):(console.log(j(`Unknown /mcp subcommand: ${t}`)),console.log(k("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function Ng(){let e=_i(),t=Object.keys(e.servers);if(t.length===0){console.log(k(`
|
|
304
304
|
No MCP servers registered. Add one with /mcp add <name> <type> <ref>
|
|
305
|
-
`));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(` ${H(n)} ${w("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?w(` [headers: ${r.join(", ")}]`):"";console.log(` ${H(n)} ${w(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function Tg(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(j("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(j(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=Ni(),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 d=o[++a],h=d?.match(/^([^:=]+)[:=](.+)$/);if(!h){console.log(j(`-H expects key:value (no spaces). Got: ${d??"(nothing)"}`));return}i[h[1].trim()]=h[2].trim()}else{console.log(j(`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,Iu(r),console.log(""),console.log(U(`\u2713 Registered "${t}" (${n})`)),console.log(W(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(w(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function Eg(e){let t=e[0];if(!t){console.log(j("Usage: /mcp remove <name>"));return}let n=Ni();if(!n.servers[t]){console.log(j(`No server named "${t}".`));return}delete n.servers[t],Iu(n),console.log(U(`\u2713 Removed "${t}".`)),console.log(w(" Run /clear to drop it from the current session immediately."))}X();import{readFileSync as Nd}from"node:fs";import{join as Id}from"node:path";import{select as My}from"@inquirer/prompts";import{computeSyncStatus as is,planPartitions as Uy,relatedArticlePaths as Fy,resolveModelForOperation as Wy,runPartitioned as By,loadProfileMap as Od,resolveActiveProfile as ca,articleCaps as Hy,ensureFeedbackChannel as qy,FEEDBACK_CATEGORY_NAME as Gy,resolveCrossLinks as Vy,applyStructureOrder as Ld,orderSyncLine as _d,applyRelatedArticles as Md,relatedSyncLine as Ud}from"document360-engine";import se from"picocolors";import Ui from"wrap-ansi";import Fi from"string-width";X();import Nt from"picocolors";import Ii from"wrap-ansi";import Oi from"string-width";var On=[{name:"init",usage:"/init",desc:"Pick an environment, scaffold .d360-writer/config.json, and set up the builder hand-off (prints the one-paste prompt)",group:"start"},{name:"login",usage:"/login",desc:"Sign in to Document360 (browser)",group:"start"},{name:"project",usage:"/project [name]",desc:"Choose the Document360 project (picker; lists all you can access)",group:"start"},{name:"devhints",usage:"/devhints",desc:"Re-show/refresh the builder hand-off prompt (set up by /init; run anytime to hand your repo agent the latest)",group:"start"},{name:"scope",usage:"/scope",desc:"Choose which repo folders back the docs (monorepos)",group:"start"},{name:"genre",usage:"/genre [web|cli|service|library|auto]",desc:"Set/show the product genre \u2014 picks the docs craft playbook (usually auto-detected; set it if it guessed wrong)",group:"start"},{name:"mcp",usage:"/mcp [list|add|remove]",desc:"Connect MCP servers (Notion, Linear, \u2026)",group:"start"},{name:"discover",usage:"/discover",desc:"Interview your builder to understand the product (identity, mental model, misconceptions, positioning) \u2192 pins a product brief that grounds the docs; asks focused questions and loops until confident",group:"docs"},{name:"draft",usage:"/draft [<feature>]",desc:"Draft a feature's articles from its PRDs/specs in .d360-writer/input/ + the code",group:"docs"},{name:"document",usage:"/document [<what>] [--publish]",desc:"Document a shipped change \u2014 the agent picks the action (new section/article/update); bare: act on builder requests",group:"docs"},{name:"write",usage:"/write [--preview|--scope <cat>|<path>] [--rewrite] [--concurrency N]",desc:"Write the planned articles in parallel (starts immediately; --preview shows plan + cost first; --rewrite regenerates already-written articles; --concurrency default 3)",group:"docs"},{name:"screenshot",usage:"/screenshot [author|capture|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); verify: judge the captured pictures and mark them verified (runs 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:"publish",usage:"/publish [path|--all|--screenshots] [--skip-review]",desc:"Publish to Document360 (no arg: pick; --all: every candidate; --screenshots: re-save articles with captured shots so images embed). Blocked until each article has had /review --fix \u2014 AI-written text gets an editor first; --skip-review overrides deliberately",group:"publish"},{name:"check",usage:"/check [<category|path>] [--fix]",desc:"Check docs for leaked internals, invented commands, and stale facts (deterministic, no tokens). Scope to a category/path; --fix has the agent correct the findings in place",group:"docs"},{name:"review",usage:"/review [<category|path> | --all] [--fix]",desc:"Independent senior-editor review: style guide, terminology/voice, grammar/clarity, structure, improvement suggestions. Bare: pick a category or everything; --all reviews the whole KB; --fix applies the corrections in place",group:"docs"},{name:"reorder",usage:"/reorder [<category> | --all]",desc:"Reorder articles within a category to the best reading order (renumbers NN- prefixes, fixes references + map); bare: pick a category or everything; new order syncs to Document360 on next /publish",group:"docs"},{name:"structure",usage:"/structure",desc:"Show the documentation reading order (categories \u2192 articles) as it will appear on Document360",group:"docs"},{name:"roadmap",usage:"/roadmap [done [step]]",desc:"Show the docs campaign (the multi-session plan the agent maintains) \u2014 progress + next step; `done` marks the next open step finished (add words from a title to pick another)",group:"docs"},{name:"audit",usage:"/audit [--auto on|off]",desc:"Gap analysis: code vs docs vs Document360 (what changed); --auto runs it at launch when code changed",group:"publish"},{name:"inbox",usage:"/inbox",desc:"Act on messages from the repo's coding agent (requests to document, answers to your questions)",group:"publish"},{name:"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 [--publish]",desc:"Process ALL pending work (builder hints + requests + Document360 portal drift) \u2192 write \u2192 push to Document360 (bare = drafts; --publish goes live). For code changes, that's /audit",group:"publish"},{name:"comments",usage:"/comments [--answer]",desc:"Reviewer comments left on passages of your articles in the Document360 portal \u2014 bare: show what's open; --answer: fix each one and reply in the thread",group:"publish"},{name:"pull",usage:"/pull [<path> | --status | --baseline]",desc:"Bring Document360 down: pull portal edits + import NEW portal articles. --status: drift report only \xB7 --baseline: set a sync base \xB7 <path>: one article / resolve a conflict",group:"publish"},{name:"resolve",usage:"/resolve [<path>]",desc:"Resolve conflicts (edited both here and on the portal): shows the diff, then keep local (publish), take portal (pull), or skip \u2014 for each. Bare: walk them all",group:"publish"},{name:"convert",usage:"/convert [--scope <folder>] [--run]",desc:"Convert tracked articles to DFM (one-off legacy migration)",group:"publish"},{name:"profile",usage:"/profile [name|add <name> [env]]",desc:"Switch/create a Document360 connection (picker; s = session)",group:"setup"},{name:"workspace",usage:"/workspace [name]",desc:"Switch the Document360 workspace (picker)",group:"setup"},{name:"model",usage:"/model [name|default]",desc:"Set the Claude model for d360-writer",group:"setup"},{name:"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",desc:"Sign out + clear project/workspace selection (then /login to re-pick)",group:"setup"},{name:"allow-prod",usage:"/allow-prod",desc:"Authorize writes to a production profile",group:"setup"},{name:"doctor",usage:"/doctor",desc:"Health-check: auth, profile, workspace, map, API",group:"setup"},{name:"update",usage:"/update",desc:"Update d360-writer \u2014 and d360-capture when installed \u2014 to the latest versions (then relaunch)",group:"setup"},{name:"feedback",usage:"/feedback",desc:"Copy the repo's open d360-writer tool-feedback to your clipboard, to relay to the d360-writer team",group:"setup"},{name:"reset",usage:"/reset",desc:"[DANGER] Delete all d360-writer files (docs, config, screenshots); types repo name to confirm",group:"setup"},{name:"resume",usage:"/resume [name]",desc:"Resume a session (no arg lists them)",group:"session"},{name:"rename",usage:"/rename [name]",desc:"Name the session (no arg: suggest one)",group:"session"},{name:"clear",usage:"/clear",desc:"Clear the screen + reset the conversation (resumable)",group:"session"},{name:"help",usage:"/help",desc:"Show this help",group:"session"},{name:"exit",usage:"/exit",desc:"Quit",group:"session"}],Ou={"/catch-up":"write up everything your builder flagged","/audit":"check the code for anything new or missing in the docs","/discover":"interview your builder so the docs are grounded in the real product","/pull":"pull edits + new articles from Document360","/publish":"publish your drafts to Document360","/write":"author the planned articles","/draft":"plan articles from PRDs + the code","/login":"sign in to Document360","/workspace":"choose the Document360 workspace","/project":"choose the Document360 project","/scope":"choose which folders back the docs","/genre":"set this repo's product type (picks the docs playbook)","/init":"set up this repo","/screenshot":"work the screenshot pipeline (author specs, take shots)","/doctor":"run a health check"};function Lu(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(Ou[n])return Ou[n];let o=On.find(r=>r.name===t);return o?o.desc:""}function _u(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return On.filter(n=>n.name.startsWith(t))}function Mu(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}var Ag=new RegExp(`^\\s*/(?:${On.map(e=>e.name).join("|")})(?:\\s|$)`),Uu=e=>Ag.test(e),Fu=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Wu=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),Bu=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function Dg(e){let t=e.replace(/\r/g,"").split(`
|
|
306
|
-
`),n=[],o=0;for(;o<t.length;){let r=t[o];if(/^\s*```/.test(r)){let
|
|
307
|
-
`)}),I=Math.max(...
|
|
308
|
-
`)},
|
|
309
|
-
`)}function
|
|
310
|
-
`);return` ${r} ${i}`+
|
|
305
|
+
`));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(` ${G(n)} ${k("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?k(` [headers: ${r.join(", ")}]`):"";console.log(` ${G(n)} ${k(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function Ig(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(j("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(j(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=_i(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let i={};for(let l=1;l<o.length;l++)if(o[l]==="-H"||o[l]==="--header"){let d=o[++l],h=d?.match(/^([^:=]+)[:=](.+)$/);if(!h){console.log(j(`-H expects key:value (no spaces). Got: ${d??"(nothing)"}`));return}i[h[1].trim()]=h[2].trim()}else{console.log(j(`Unexpected argument: ${o[l]}. 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,Uu(r),console.log(""),console.log(U(`\u2713 Registered "${t}" (${n})`)),console.log(W(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(k(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function Og(e){let t=e[0];if(!t){console.log(j("Usage: /mcp remove <name>"));return}let n=_i();if(!n.servers[t]){console.log(j(`No server named "${t}".`));return}delete n.servers[t],Uu(n),console.log(U(`\u2713 Removed "${t}".`)),console.log(k(" Run /clear to drop it from the current session immediately."))}Q();import{readFileSync as qy}from"node:fs";import{join as Gy}from"node:path";import{select as Vy}from"@inquirer/prompts";import{computeSyncStatus as us,planPartitions as Yy,relatedArticlePaths as Ky,resolveModelForOperation as zy,runPartitioned as Xy,loadProfileMap as Md,resolveActiveProfile as ha,unreviewedPaths as Qy,listArticleFiles as Jy,ensureFeedbackChannel as Zy,FEEDBACK_CATEGORY_NAME as ew,resolveCrossLinks as tw,applyStructureOrder as Ud,orderSyncLine as Wd,applyRelatedArticles as Fd,relatedSyncLine as Bd}from"document360-engine";import ie from"picocolors";import Hi from"wrap-ansi";import qi from"string-width";Q();import Lt from"picocolors";import Mi from"wrap-ansi";import Ui from"string-width";var Mn=[{name:"init",usage:"/init",desc:"Pick an environment, scaffold .d360-writer/config.json, and set up the builder hand-off (prints the one-paste prompt)",group:"start"},{name:"login",usage:"/login",desc:"Sign in to Document360 (browser)",group:"start"},{name:"project",usage:"/project [name]",desc:"Choose the Document360 project (picker; lists all you can access)",group:"start"},{name:"devhints",usage:"/devhints",desc:"Re-show/refresh the builder hand-off prompt (set up by /init; run anytime to hand your repo agent the latest)",group:"start"},{name:"scope",usage:"/scope",desc:"Choose which repo folders back the docs (monorepos)",group:"start"},{name:"genre",usage:"/genre [web|cli|service|library|auto]",desc:"Set/show the product genre \u2014 picks the docs craft playbook (usually auto-detected; set it if it guessed wrong)",group:"start"},{name:"mcp",usage:"/mcp [list|add|remove]",desc:"Connect MCP servers (Notion, Linear, \u2026)",group:"start"},{name:"discover",usage:"/discover",desc:"Interview your builder to understand the product (identity, mental model, misconceptions, positioning) \u2192 pins a product brief that grounds the docs; asks focused questions and loops until confident",group:"docs"},{name:"draft",usage:"/draft [<feature>]",desc:"Draft a feature's articles from its PRDs/specs in .d360-writer/input/ + the code",group:"docs"},{name:"document",usage:"/document [<what>] [--publish]",desc:"Document a shipped change \u2014 the agent picks the action (new section/article/update); bare: act on builder requests. --publish then runs the normal publish, which still needs an editorial review first",group:"docs"},{name:"write",usage:"/write [--preview|--scope <cat>|<path>] [--rewrite] [--concurrency N]",desc:"Write the planned articles in parallel (starts immediately; --preview shows plan + cost first; --rewrite regenerates already-written articles; --concurrency default 3)",group:"docs"},{name:"screenshot",usage:"/screenshot [author|capture|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); verify: judge the captured pictures and mark them verified (runs 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:"publish",usage:"/publish [path|--all|--screenshots] [--skip-review]",desc:"Publish to Document360 (no arg: pick; --all: every candidate; --screenshots: re-save articles with captured shots so images embed). Blocked until each article has had /review --fix \u2014 AI-written text gets an editor first; --skip-review overrides deliberately",group:"publish"},{name:"check",usage:"/check [<category|path>] [--fix]",desc:"Check docs for leaked internals, invented commands, and stale facts (deterministic, no tokens). Scope to a category/path; --fix has the agent correct the findings in place",group:"docs"},{name:"review",usage:"/review [<category|path> | --all] [--fix]",desc:"Independent senior-editor review: style guide, terminology/voice, grammar/clarity, structure, improvement suggestions. Bare: pick a category or everything; --all reviews the whole KB; --fix applies the corrections in place",group:"docs"},{name:"reorder",usage:"/reorder [<category> | --all]",desc:"Reorder articles within a category to the best reading order (renumbers NN- prefixes, fixes references + map); bare: pick a category or everything; new order syncs to Document360 on next /publish",group:"docs"},{name:"structure",usage:"/structure",desc:"Show the documentation reading order (categories \u2192 articles) as it will appear on Document360",group:"docs"},{name:"roadmap",usage:"/roadmap [done [step]]",desc:"Show the docs campaign (the multi-session plan the agent maintains) \u2014 progress + next step; `done` marks the next open step finished (add words from a title to pick another)",group:"docs"},{name:"audit",usage:"/audit [--auto on|off]",desc:"Gap analysis: code vs docs vs Document360 (what changed); --auto runs it at launch when code changed",group:"publish"},{name:"inbox",usage:"/inbox",desc:"Act on messages from the repo's coding agent (requests to document, answers to your questions)",group:"publish"},{name:"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 [--publish]",desc:"Process ALL pending work (builder hints + requests + Document360 portal drift) \u2192 write \u2192 push to Document360 as drafts. --publish then runs the normal publish, which still needs an editorial review first. For code changes, that's /audit",group:"publish"},{name:"comments",usage:"/comments [--answer]",desc:"Reviewer comments left on passages of your articles in the Document360 portal \u2014 bare: show what's open; --answer: fix each one and reply in the thread",group:"publish"},{name:"pull",usage:"/pull [<path> | --status | --baseline]",desc:"Bring Document360 down: pull portal edits + import NEW portal articles. --status: drift report only \xB7 --baseline: set a sync base \xB7 <path>: one article / resolve a conflict",group:"publish"},{name:"resolve",usage:"/resolve [<path>]",desc:"Resolve conflicts (edited both here and on the portal): shows the diff, then keep local (publish), take portal (pull), or skip \u2014 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:"Switch/create a Document360 connection (picker; s = session)",group:"setup"},{name:"workspace",usage:"/workspace [name]",desc:"Switch the Document360 workspace (picker)",group:"setup"},{name:"model",usage:"/model [name|default]",desc:"Set the Claude model for d360-writer",group:"setup"},{name:"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",desc:"Sign out + clear project/workspace selection (then /login to re-pick)",group:"setup"},{name:"allow-prod",usage:"/allow-prod",desc:"Authorize writes to a production profile",group:"setup"},{name:"doctor",usage:"/doctor",desc:"Health-check: auth, profile, workspace, map, API",group:"setup"},{name:"update",usage:"/update",desc:"Update d360-writer \u2014 and d360-capture when installed \u2014 to the latest versions (then relaunch)",group:"setup"},{name:"feedback",usage:"/feedback",desc:"Copy the repo's open d360-writer tool-feedback to your clipboard, to relay to the d360-writer team",group:"setup"},{name:"reset",usage:"/reset",desc:"[DANGER] Delete all d360-writer files (docs, config, screenshots); types repo name to confirm",group:"setup"},{name:"resume",usage:"/resume [name]",desc:"Resume a session (no arg lists them)",group:"session"},{name:"rename",usage:"/rename [name]",desc:"Name the session (no arg: suggest one)",group:"session"},{name:"clear",usage:"/clear",desc:"Clear the screen + reset the conversation (resumable)",group:"session"},{name:"help",usage:"/help",desc:"Show this help",group:"session"},{name:"exit",usage:"/exit",desc:"Quit",group:"session"}],Wu={"/catch-up":"write up everything your builder flagged","/audit":"check the code for anything new or missing in the docs","/discover":"interview your builder so the docs are grounded in the real product","/pull":"pull edits + new articles from Document360","/publish":"publish your drafts to Document360","/write":"author the planned articles","/draft":"plan articles from PRDs + the code","/login":"sign in to Document360","/workspace":"choose the Document360 workspace","/project":"choose the Document360 project","/scope":"choose which folders back the docs","/genre":"set this repo's product type (picks the docs playbook)","/init":"set up this repo","/screenshot":"work the screenshot pipeline (author specs, take shots)","/doctor":"run a health check"};function Fu(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(Wu[n])return Wu[n];let o=Mn.find(r=>r.name===t);return o?o.desc:""}function Bu(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return Mn.filter(n=>n.name.startsWith(t))}function Hu(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}var Lg=new RegExp(`^\\s*/(?:${Mn.map(e=>e.name).join("|")})(?:\\s|$)`),qu=e=>Lg.test(e),Gu=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Vu=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),Yu=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function _g(e){let t=e.replace(/\r/g,"").split(`
|
|
306
|
+
`),n=[],o=0;for(;o<t.length;){let r=t[o];if(/^\s*```/.test(r)){let l=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)l.push(t[o++]);o++,n.push({kind:"code",lines:l});continue}if(Gu(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&Vu(t[o+1])){let l=Yu(r);o+=2;let d=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)d.push(Yu(t[o++]));n.push({kind:"table",header:l,rows:d});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 l=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);){let d=t[o++];l.push({ordered:/^\s*\d+\.\s+/.test(d),text:d.replace(/^\s*([-*]|\d+\.)\s+/,"")})}n.push({kind:"list",items:l});continue}if(r.trim()===""){o++;continue}if(qu(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])&&!qu(t[o])&&!Gu(t[o])&&!(t[o].includes("|")&&o+1<t.length&&Vu(t[o+1]));)i.push(t[o++]);n.push({kind:"para",text:i.join(" ")})}return n}function Wi(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?Lt.bold(t.slice(2,-2)):t.startsWith("`")?G(t.slice(1,-1)):Lt.italic(t.slice(1,-1)))}var Mg=(e,t)=>e+" ".repeat(Math.max(0,t-Ui(e)));function Ug(e,t,n){let o=e.length,r=e.map(($,T)=>Math.max(Ui($),...t.map(R=>Ui(R[T]??"")))),s=Math.max(24,n),i=3*o+1,l=[...r],d=()=>l.reduce(($,T)=>$+T,0)+i,h=0;for(;d()>s&&h++<1e4;){let $=-1,T=6;for(let R=0;R<o;R++)l[R]>T&&(T=l[R],$=R);if($===-1)break;l[$]-=1}let m=($,T,R)=>Lt.gray($+l.map(I=>"\u2500".repeat(I+2)).join(T)+R),w=Lt.gray("\u2502"),x=($,T)=>{let R=l.map((q,z)=>{let ae=$[z]??"",xe=T?Lt.bold(ae):Wi(ae);return Mi(xe,q,{hard:!0}).split(`
|
|
307
|
+
`)}),I=Math.max(...R.map(q=>q.length)),Y=[];for(let q=0;q<I;q++)Y.push(l.map((z,ae)=>`${w} ${Mg(R[ae][q]??"",z)} `).join("")+w);return Y.join(`
|
|
308
|
+
`)},S=[m("\u250C","\u252C","\u2510"),x(e,!0)];return S.push(t.length===0?m("\u2514","\u2534","\u2518"):m("\u251C","\u253C","\u2524")),t.forEach(($,T)=>{S.push(x($,!1)),S.push(T===t.length-1?m("\u2514","\u2534","\u2518"):m("\u251C","\u253C","\u2524"))}),S.join(`
|
|
309
|
+
`)}function Wg(e,t){switch(e.kind){case"heading":return Lt.bold(e.text);case"hr":return Lt.gray("\u2500".repeat(t));case"para":return Mi(Wi(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="",...l]=Mi(Wi(o.text),Math.max(10,t-s.length)).split(`
|
|
310
|
+
`);return` ${r} ${i}`+l.map(d=>`
|
|
311
311
|
${s}${d}`).join("")}).join(`
|
|
312
|
-
`)}case"code":return e.lines.map(n=>
|
|
313
|
-
`);case"table":return
|
|
314
|
-
|
|
315
|
-
`)}
|
|
316
|
-
`);let r=2,s=3,i=
|
|
317
|
-
`);let d=Math.max(0,Math.floor((n.length-o.length)/2)),h=[];for(let m=0;m<Math.max(o.length+d,n.length);m++){let
|
|
318
|
-
`)}var
|
|
319
|
-
`).flatMap(h=>
|
|
320
|
-
`)),d=Math.max(0,
|
|
321
|
-
`+
|
|
312
|
+
`)}case"code":return e.lines.map(n=>Lt.gray(" "+n)).join(`
|
|
313
|
+
`);case"table":return Ug(e.header,e.rows,t)}}function Fi(e,t){let n=Math.max(20,t);return _g(e).map(o=>Wg(o,n)).join(`
|
|
314
|
+
|
|
315
|
+
`)}Q();import Fg from"picocolors";var Bg=[127,86,217],Hg=[22,38,43],Ku={T:Bg,E:Hg},Co=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],Bi=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,qg=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function zu(){if(!Fg.isColorSupported)return[];let e=Co[0].length,t=[];for(let n=0;n<Co.length;n+=2){let o="";for(let r=0;r<e;r++){let s=Ku[Co[n][r]],i=n+1<Co.length?Ku[Co[n+1][r]]:void 0;s&&i?o+=`${Bi(s)}${qg(i)}\u2580\x1B[49m\x1B[39m`:s?o+=`${Bi(s)}\u2580\x1B[39m`:i?o+=`${Bi(i)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function So(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 Po(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function We(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function _t(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var Un=(e,t)=>` ${e.padEnd(13)}${t}`;function Gg(e,t){let n=[bo("\u270E document360-writer")+ie.gray(` v${e.version} \xB7 engine v${e.engineVersion}${e.captureVersion?` \xB7 capture v${e.captureVersion}`:""}`),ie.gray(" Reads your code, writes your docs."),"",Un("Claude:",`${e.claude}${ie.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),Un("Document360:",e.configured?e.loggedOut?ie.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?ie.gray(` (${e.sessionHint})`):""}`:ie.yellow("not set up \u2014 run /init")),Un("Profile:",e.configured?`${e.profile}${ie.gray(` (${e.apiUrl})`)}${e.prod?ie.bold(ie.yellow(" \u26A0 PRODUCTION")):""}`:ie.gray("\u2014 (run /init)")),Un("Project:",e.project),Un("Mode:",ie.gray(e.mode)),Un("cwd:",ie.gray(e.cwd))],o=zu();if(o.length===0)return n.join(`
|
|
316
|
+
`);let r=2,s=3,i=qi(o[0]);if(!(t>=r+i+s+Math.max(...n.map(m=>qi(m)))))return[...o.map(m=>" "+m),...n].join(`
|
|
317
|
+
`);let d=Math.max(0,Math.floor((n.length-o.length)/2)),h=[];for(let m=0;m<Math.max(o.length+d,n.length);m++){let w=o[m-d]??" ".repeat(i);h.push((" ".repeat(r)+w+" ".repeat(s)+(n[m]??"")).trimEnd())}return h.join(`
|
|
318
|
+
`)}var Vg={error:ie.red,warn:ie.yellow,ok:ie.green,info:ie.gray},Xu=9;function Gi(e){return e.length>=Xu?`${e} `:e.padEnd(Xu)}function Vi(e){return e.replace(/^(\s*• |)([^\x00-\x7F][\u{1F000}-\u{1FAFF}️]*) (?=\S)/gmu,"$1$2 ")}function Yi(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return Gg(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",s=Math.max(10,n-4),i=50,l=e.text.split(`
|
|
319
|
+
`).flatMap(h=>Hi(h,s,{hard:!0}).split(`
|
|
320
|
+
`)),d=Math.max(0,l.length-i);return d>0&&(l=[...l.slice(0,i),ie.dim(`\u2026 +${d} more lines`)]),`
|
|
321
|
+
`+l.map((h,m)=>o+(m===0?G(" \u276F "):" ")+h+" ".repeat(Math.max(0,s-qi(h))+1)+r).join(`
|
|
322
322
|
`)}case"assistant":return`
|
|
323
|
-
`+
|
|
324
|
-
`+
|
|
325
|
-
`+
|
|
326
|
-
`)}case"diff":{let o=i=>i===1?"":"s",s=[
|
|
327
|
-
`)}case"link":return e.lines.map(o=>
|
|
323
|
+
`+Fi(e.text,n);case"tool":{let o=e.arg!==null?ie.gray(`${e.sep}(${e.arg})`):"";return`
|
|
324
|
+
`+Hi(ie.gray("\u25CF ")+e.title+o,n)}case"doc":{let o=[e.category,e.note].filter(s=>!!s).map(s=>ie.gray(` \xB7 ${s}`)),r=e.loud?ie.gray(" \xB7 ")+ie.bold(ie.yellow(e.loud)):"";return`
|
|
325
|
+
`+Hi(ie.green("\u25CF ")+G(ie.bold(Gi(e.verb)))+ie.bold(e.title)+o.join("")+r,n)}case"tool-result":{let o=e.isError?ie.red:ie.gray,r=e.lines.map((s,i)=>o((i===0?" \u23BF ":" ")+s));return e.hidden>0&&r.push(ie.dim(` \u2026 +${e.hidden} lines`)),r.join(`
|
|
326
|
+
`)}case"diff":{let o=i=>i===1?"":"s",s=[ie.gray(` \u23BF Added ${e.added} line${o(e.added)}, removed ${e.removed} line${o(e.removed)}`),...e.lines];return e.hidden>0&&s.push(ie.dim(` \u2026 +${e.hidden} more diff lines`)),s.join(`
|
|
327
|
+
`)}case"link":return e.lines.map(o=>G(vo(` \u2B95 ${o}`))).join(`
|
|
328
328
|
`);case"preview":return`
|
|
329
|
-
`+
|
|
330
|
-
|
|
331
|
-
`+
|
|
332
|
-
`+
|
|
333
|
-
`+(e.ok?
|
|
334
|
-
`)}import{resolveActiveProfile as
|
|
335
|
-
`,"utf8")}function
|
|
336
|
-
${
|
|
329
|
+
`+bo(`\u25A3 Preview \u2014 ${e.name}`)+`
|
|
330
|
+
|
|
331
|
+
`+Fi(e.text,n);case"note":return`
|
|
332
|
+
`+Vg[e.tone](vo(Vi(e.text)));case"done":{let o=e.inTokens&&e.inTokens>0?` \xB7 ${So(e.inTokens)} in${e.cachedPct!=null?` (${e.cachedPct}% cached)`:""}`:"";return`
|
|
333
|
+
`+(e.ok?ie.magenta("\u2736 "):ie.red("\u2736 "))+ie.gray(`Cooked for ${Po(e.seconds)} \xB7 ${So(e.tokens)} tokens out${o}`+(e.costUsd>0?` \xB7 ${We(e.costUsd)}`:""))}}}function Qu(e,t){return e.map(n=>Yi(n,t)).join(`
|
|
334
|
+
`)}import{resolveActiveProfile as Yg,loadTokens as Kg,isExpired as zg,decodeJwtClaims as Ju}from"document360-engine";function Xg(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function Fe(e,t){try{let n=Yg(e,t),o=Kg(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(zg(o)&&!o.refreshToken)return{ok:!1,reason:`Your Document360 session expired (profile "${n.name}"). Run /login.`};let r=n.project.projectId;if(r){let i={...Ju(o.idToken)??{},...Ju(o.accessToken)??{}}.doc360_project_id;if(typeof i=="string"&&i&&i!==r)return{ok:!1,reason:`Your Document360 session is signed into a different project than profile "${n.name}" (this profile's project is ${Xg(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}function ut(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 partition produced no output, so no agent actually ran.`,"Most likely a Claude usage/session limit \u2014 it ends every turn instantly and leaves /doctor clean, so wait for the reset and re-run. If you have plenty of quota left, /doctor checks sign-in + model reachability."]:null}function Kr(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.`}import{existsSync as Ji,readFileSync as aa}from"node:fs";import{isAbsolute as ts,join as ns,resolve as os}from"node:path";import A from"picocolors";import Jr from"string-width";import{readProjectConfig as Ut,screenshotPlaceholderIds as wd,DEFAULT_CAPTURE_DIR as rs,DEFAULT_OUTPUT_DIR as la,DEFAULT_DOCS_DIR as ca,existingAnnotatedShotPath as wy,resolveOutputDir as kd,migrateShotLayout as ky,reviewIsCurrent as by,shotImageMtimeMs as $y,anchorPresent as vy,RAW_SUBDIR as xy,ANNOTATED_SUBDIR as Ry}from"document360-engine";import{createHash as ed}from"node:crypto";import{readFileSync as td,writeFileSync as Qg}from"node:fs";import{join as Jg}from"node:path";import{captureStatePath as nd}from"document360-engine";var Zu={version:1,shots:{}};function od(e){return ed("sha1").update(e).digest("hex").slice(0,12)}function zr(e){try{let t=JSON.parse(td(Jg(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(l=>`${l}=${s[l]}`).join("&");return ed("sha1").update(`${o}|${r?.connection?.startUrl??""}|${i}`).digest("hex").slice(0,12)}catch{return null}}function $t(e){try{let t=JSON.parse(td(nd(e),"utf8").replace(/^/,""));return!t||typeof t!="object"||t.version!==1||!t.shots?{...Zu,shots:{}}:{version:1,shots:t.shots}}catch{return{...Zu,shots:{}}}}function Zg(e,t){Qg(nd(e),`${JSON.stringify(t,null,2)}
|
|
335
|
+
`,"utf8")}function Ki(e){return e&&/data-testid|\btest-?id\b|has(?:n't| not) landed/i.test(e)?"testid":"data"}function Xr(e,t,n){if(t.length===0)return;let o=$t(e),r=zr(e);for(let s of t){let i=s.specSource?od(s.specSource):void 0;o.shots[s.id]={outcome:s.outcome,at:n,...s.reason?{reason:s.reason}:{},...s.outcome==="skipped"?{blockedBy:Ki(s.reason)}:{},...i?{specHash:i}:{},...r?{envHash:r}:{}}}Zg(e,o)}function zi(e,t,n,o){let r=e.shots[t];return!r||n===null||!r.specHash||r.specHash!==od(n)||o&&r.envHash&&r.envHash!==o?null:r}function rd(e){let t=$t(e).shots;return Object.keys(t).filter(n=>t[n].outcome==="failed").sort()}function Xi(e,t,n){let o=zi($t(e),t,n,zr(e));return!o||o.outcome==="captured"||!o.reason?null:{outcome:o.outcome,reason:o.reason}}To();import{existsSync as ry,readFileSync as ld,readdirSync as cd,writeFileSync as sy}from"node:fs";import{isAbsolute as iy,join as ud,resolve as ay}from"node:path";import{readProjectConfig as ly,DEFAULT_CAPTURE_DIR as cy}from"document360-engine";var ad="0.2.25";function Qr(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 uy=/^([ \t]*)await\s+([^\n;]+?)\.screenshot\(\{\s*path:\s*PLACEHOLDER\.saveTo\s*(?:,\s*fullPage:\s*(?:true|false)\s*)?,?\s*\}\)\s*;?[ \t]*$/m,dy=/^[ \t]*await\s+dumpAnnotations\(\s*page\s*,\s*PLACEHOLDER\s*\)\s*;?[ \t]*\r?\n?/m,dd="(?:'([^']+)'|\"([^\"]+)\"|`([^`]+)`)",py=new RegExp(`^page\\s*\\.\\s*locator\\(\\s*${dd}\\s*\\)$`),pd=e=>e[1]??e[2]??e[3]??null,hy=/^[A-Za-z_$][\w$]*$/;function fy(e,t){let o=new RegExp(`\\bconst\\s+${t}\\s*=\\s*page\\s*\\.\\s*locator\\(\\s*${dd}\\s*\\)\\s*;`).exec(e);return o?pd(o):null}function my(e,t){let n=t.trim();if(n==="page")return null;let o=py.exec(n);if(o){let r=pd(o);return r?{selector:r}:{unresolved:!0}}if(hy.test(n)){let r=fy(e,n);return r?{selector:r}:{unresolved:!0}}return{unresolved:!0}}function hd(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=uy.exec(e);if(!n)return null;let[o,r="",s=""]=n,i=my(e,s);if(i===null)return null;if("unresolved"in i)return{unresolved:s.trim()};let l=/^([ \t]*)saveTo:\s*.+,[ \t]*$/m.exec(e);if(!l)return null;let d=i.selector.includes("'")?'"':"'",h=e.replace(l[0],`${l[0]}
|
|
336
|
+
${l[1]??" "}clipTo: ${d}${i.selector}${d},`);return h=h.replace(o,`${r}await captureShot(page, PLACEHOLDER);`),h=h.replace(dy,""),h=h.replace(/\bdumpAnnotations\b(?=[^\n]*from 'document360-capture\/helpers')/,"captureShot"),/from 'document360-capture\/helpers'/.test(h)&&!/\bcaptureShot\b[^\n]*from 'document360-capture\/helpers'/.test(h)&&(h=h.replace(/import \{([^}]*)\} from 'document360-capture\/helpers'/,(m,w)=>`import {${w.replace(/\s*$/,"")}, captureShot } from 'document360-capture/helpers'`)),{next:h,selector:i.selector}}function gy(e){try{return cd(e).filter(t=>t.endsWith(".spec.ts")).some(t=>{try{let n=hd(ld(ud(e,t),"utf8"));return n!==null&&!("unresolved"in n)}catch{return!1}})}catch{return!1}}function yy(e){let t=ly(e)?.captureDir??cy;return iy(t)?t:ay(e,t)}function fd(e,t){let n={migrated:[],skipped:[]},o=yy(e);if(!ry(o))return n;let r=t?.captureVersion===void 0?vt():t.captureVersion;if(!Qr(r,ad))return gy(o)?{...n,heldBackForCapture:{installed:r,required:ad}}:n;let s;try{s=cd(o).filter(i=>i.endsWith(".spec.ts"))}catch{return n}for(let i of s.sort()){let l=i.slice(0,-8),d=ud(o,i);try{let h=ld(d,"utf8"),m=hd(h);if(m===null)continue;if("unresolved"in m){n.skipped.push({id:l,receiver:m.unresolved});continue}sy(d,m.next,"utf8"),n.migrated.push(l)}catch{}}return n}function md(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.
|
|
337
337
|
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(`
|
|
338
|
-
`)}
|
|
339
|
-
`):null}function
|
|
340
|
-
`))||o.push(r+1));return o}function
|
|
341
|
-
`);if(!/test\.skip\s*\(/.test(i)||!/\.count\s*\(\s*\)/.test(i))continue;let
|
|
342
|
-
`);/\.waitFor\s*\(|Promise\.race\s*\(|waitForFunction\s*\(|waitForSelector\s*\(/.test(
|
|
343
|
-
`)}var Sy={placeholder:"\u25CB",spec:"\u25D0",blocked:"\u2298",broken:"\u2717",captured:"\u25CF",verified:"\u2714",rejected:"\u2691"},Py={placeholder:E.gray,spec:E.yellow,blocked:E.cyan,broken:E.red,captured:E.blue,verified:E.green,rejected:E.magenta},Ty=` ${E.green("\u2714 verified")} ${E.blue("\u25CF to verify")} ${E.yellow("\u25D0 ready")} ${E.magenta("\u2691 rejected")} ${E.cyan("\u2298 blocked")} ${E.red("\u2717 broken")} ${E.gray("\u25CB to spec")}`;function ne(e,t=n=>n){return`${t(e)} `}function _n(e){return e.replace(/\s+/g," ").trim().replace(/^Prerequisites? not met[:—-]?\s*/i,"")}function os(e){let t=_n(e),n=/^(.*?[a-z0-9)"'”’])\.(?:\s|$)/i.exec(t);return(n?n[1]:t).trim()}function To(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=os(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 xd(e){let t=To(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,d)=>a+d.ids.length,0);r.push(` ${E.bold("Stage this data")} ${E.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 d=At(a.reason,86);r.push(` ${E.cyan(Ot(`${a.ids.length}\xD7`,4))} ${d[0]??""}`);for(let m of d.slice(1))r.push(` ${m}`);let h=a.ids.slice(0,4).join(" \xB7 ");r.push(E.gray(` ${h}${a.ids.length>4?` \xB7 +${a.ids.length-4} more`:""}`))}n.length>i&&r.push(E.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(` ${ne("\u2298",E.cyan)}${s} shot${s===1?"":"s"} need${s===1?"s":""} a data-testid from your developers \u2014 ${E.bold("/screenshot checklist")} builds the hand-off.`)}return r}function Cd(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=["",` ${ne("\u26A0",E.yellow)}${r} selector request${r===1?"":"s"} quote${r===1?"s":""} source code that has since changed`+E.gray(" \u2014 your developers would go looking for something that isn't there any more"),E.gray(` Refresh the hand-off before sending it: ${E.bold("/screenshot checklist")}`)];return t&&s.push(E.gray(` ${o.slice(0,8).join(" \xB7 ")}${r>8?` \xB7 +${r-8} more`:""}`)),s}function Rd(e,t,n){let o=e.filter(m=>(m.unguardedWaits?.length??0)>0),r=e.filter(m=>m.undeclared),s=e.filter(m=>(m.handRolled?.length??0)>0),i=e.filter(m=>(m.stalePause?.length??0)>0),a=e.filter(m=>(m.bareGoto?.length??0)>0);if(o.length===0&&r.length===0&&s.length===0&&i.length===0&&a.length===0)return[];let d=["",` ${ne("\u26A0",E.yellow)}Some specs were written before later reliability fixes:`],h=(m,k)=>` ${m.slice(0,8).map(k).join(" \xB7 ")}${m.length>8?` \xB7 +${m.length-8} more`:""}`;if(o.length>0){let m=o.length;d.push(E.gray(` ${m} crash${m===1?"es":""} instead of telling you what to stage when the data ${m===1?"it needs":"they need"} is missing`)),t&&d.push(E.gray(h(o,k=>`${k.id}:${k.unguardedWaits.join(",")}`)))}if(a.length>0){let m=a.length;d.push(E.gray(` ${m} open${m===1?"s":""} pages the slow way, so ${m===1?"it stalls":"they stall"} for a minute and give up when several shots run at once`)),t&&d.push(E.gray(h(a,k=>`${k.id}:${k.bareGoto.join(",")}`)))}if(i.length>0){let m=i.length;d.push(E.gray(` ${m} decide${m===1?"s":""} "the data is missing" from a fixed pause, so data you HAVE staged can read as absent`)),t&&d.push(E.gray(h(i,k=>`${k.id}:${k.stalePause.join(",")}`)))}if(s.length>0){let m=s.length;d.push(E.gray(` ${m} take${m===1?"s":""} ${m===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&&d.push(E.gray(h(s,k=>`${k.id}:${k.handRolled.join(",")}`)))}if(r.length>0){let m=r.length,k=r.filter(v=>v.mutates).length;d.push(E.gray(` ${m} do${m===1?"es":""} not say whether ${m===1?"it changes":"they change"} data in your app`+(k>0?`, so ${k===1?"one is":`${k} are`} left out of bulk runs to be safe`:""))),t&&d.push(E.gray(h(r,v=>v.id)))}return n?.commandInLead||d.push(E.gray(` Re-write them all with the current rules: ${E.bold("/screenshot author --all")}`)),d}function Sd(e){let t=e.filter(n=>(n.unverifiedForce?.length??0)>0);return t.length===0?[]:["",` ${ne("\u26A0",E.red)}${t.length} spec${t.length===1?"":"s"} force-click past Playwright's safety checks without asserting the result`+E.gray(" \u2014 if the click lands on nothing, the shot photographs the unchanged screen"),E.gray(` ${t.slice(0,6).map(n=>`${n.id}:${n.unverifiedForce.join(",")}`).join(" \xB7 ")}${t.length>6?` \xB7 +${t.length-6} more`:""}`),E.gray(` Re-author to check what the click did: ${E.bold("/screenshot author <id>")}`)]}var zr=(e,t)=>e.length>=t?e:e+" ".repeat(t-e.length),Ot=(e,t)=>e.length>=t?e:" ".repeat(t-e.length)+e;function Pd(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 Ey=new Set(["and","or","of","the","to","a","an","in","on","for","with","vs"]),Ay=new Set(["ai","api","cli","ui","ux","url","id","http","https","json","xml","sdk","csv","pdf","oauth","sso","mfa","io","faq"]);function Dy(e){return e.replace(/[-_]+/g," ").trim().split(/\s+/).filter(Boolean).map((n,o)=>{let r=n.toLowerCase();return Ay.has(r)?r.toUpperCase():o>0&&Ey.has(r)?r:r.charAt(0).toUpperCase()+r.slice(1)}).join(" ")}function ea(e){if(!e)return{num:"",name:"(docs root)"};let t=/^(\d+)[-_](.+)$/.exec(e);return{num:t?t[1]:"",name:Dy(t?t[2]:e)}}function jy(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).pop()??e}function pd(e,t,n){let o=t>0?Math.round(e/t*n):0;return E.green("\u2588".repeat(o))+E.gray("\u2591".repeat(Math.max(0,n-o)))}function Ny(e,t){let n=t>0?Math.round(e/t*100):0,o=Ot(`${n}%`,4);return n===100?E.green(o):n>0?E.yellow(o):E.gray(o)}function Td(e,t){let n=new Map;for(let o of e){let r=Pd(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 Iy(e,t){let n=(z,pe)=>z.filter(de=>de.state===pe).length,o=e.length,r=n(e,"verified"),s=n(e,"captured"),i=n(e,"rejected"),a=n(e,"spec"),d=n(e,"blocked"),h=n(e,"broken"),m=n(e,"placeholder"),k=new Set(e.map(z=>z.file)).size,v=Td(e,t),R=[];R.push(` ${E.bold("Screenshots")} ${E.green(`${r}/${o} verified`)} ${E.gray("\xB7")} ${s>0?E.blue(`${s} to verify`):E.gray("0 to verify")}`+(i>0?` ${E.gray("\xB7")} ${E.magenta(`${i} rejected`)}`:"")+` ${E.gray("\xB7")} ${a>0?E.yellow(`${a} ready`):E.gray("0 ready")}`+(d>0?` ${E.gray("\xB7")} ${E.cyan(`${d} blocked`)}`:"")+(h>0?` ${E.gray("\xB7")} ${E.red(`${h} broken`)}`:"")+` ${E.gray("\xB7")} ${m>0?E.red(`${m} to spec`):E.gray("0 to spec")} `+E.gray(`across ${k} article${k===1?"":"s"}`));let $=o>0?Math.round(r/o*100):0;R.push(` [${pd(r,o,32)}] ${E.bold(`${$}%`)}`),R.push("");let S=v.map(([z])=>ea(z)),C=Math.min(32,Math.max(7,...S.map(z=>z.name.length))),I=z=>z.length>C?`${z.slice(0,C-1)}\u2026`:zr(z,C),Y=[...s>0?[{head:"To verify",w:9,state:"captured",color:E.blue}]:[],...i>0?[{head:"Rejected",w:8,state:"rejected",color:E.magenta}]:[],{head:"Ready",w:5,state:"spec",color:E.yellow},...d>0?[{head:"Blocked",w:7,state:"blocked",color:E.cyan}]:[],...h>0?[{head:"Broken",w:6,state:"broken",color:E.red}]:[],{head:"To spec",w:7,state:"placeholder",color:E.red}];R.push(E.gray(` ${zr("#",2)} ${zr("Chapter",C)} ${Ot("Verified",8)} ${Y.map(z=>Ot(z.head,z.w)).join(" ")} Progress`));for(let[z,[,pe]]of v.entries()){let de=n(pe,"verified"),Re=pe.length,{num:Se,name:Qe}=S[z],bt=de===Re,Bt=I(Qe),er=Y.map(st=>{let tr=n(pe,st.state);return tr>0?st.color(Ot(String(tr),st.w)):E.gray(Ot("\u2014",st.w))}).join(" ");R.push(` ${E.cyan(zr(Se,2))} ${bt?E.green(Bt):de>0?Bt:E.gray(Bt)} ${bt?E.green(Ot(`${de}/${Re}`,8)):Ot(`${de}/${Re}`,8)} ${er} ${pd(de,Re,10)} ${Ny(de,Re)}`)}R.push("");let q=h>0?` ${E.gray("\xB7")} ${h} spec${h===1?"":"s"} broken \u2014 ${E.bold(`/screenshot ${e.find(z=>z.state==="broken").id}`)} re-authors ${h===1?"it":"the first"}`:"",K=e.filter(z=>z.state==="spec"&&z.mutates).length,ae=a>K,$e=e.filter(z=>(z.unguardedWaits?.length??0)>0||(z.bareGoto?.length??0)>0).length,ye=e.filter(z=>(z.stalePause?.length??0)>0||(z.handRolled?.length??0)>0).length,Ee=a>0||d>0||h>0,ve=!1;if(m>0)R.push(` ${ne("\u2192",E.yellow)}${m} placeholder${m===1?"":"s"} still need a spec \u2014 run ${E.bold("/screenshot author --all")}${q}`);else if($e>0&&Ee)ve=!0,R.push(` ${ne("\u2192",E.yellow)}${$e} spec${$e===1?"":"s"} would crash mid-run \u2014 re-write ${$e===1?"it":"them"} first: ${E.bold("/screenshot author --all")}`+E.gray(` \xB7 then ${E.bold("/screenshot capture")} (no browser time wasted on ${$e===1?"a shot":"shots"} that can't finish)`)+q);else if(ye>0&&Ee)ve=!0,R.push(` ${ne("\u2192",E.yellow)}${ye} spec${ye===1?"":"s"} would shoot the wrong thing \u2014 re-write ${ye===1?"it":"them"} first: ${E.bold("/screenshot author --all")}`+E.gray(` \xB7 then ${E.bold("/screenshot capture")} (a false skip or a misplaced callout costs the same browser time as a good shot)`)+q);else if(a>0&&(ae||s===0)){let z=K>0?E.gray(` \u2014 ${a-K} in one go; ${K} write${K===1?"s":""} real data and run${K===1?"s":""} one at a time`):"";R.push(` ${ne("\u2192",E.yellow)}${a} spec${a===1?"":"s"} ready to capture \u2014 run ${E.bold("/screenshot capture")}${z}${q}`)}else if(s>0&&a>0)R.push(` ${ne("\u2192",E.blue)}${s} shot${s===1?"":"s"} awaiting verification \u2014 run ${E.bold("/screenshot verify")}`+E.gray(" \u2014 no browser needed")+E.gray(` \xB7 ${a} ready spec${a===1?"":"s"} write real data, so ${a===1?"it runs":"each runs"} only when named: /screenshot capture <id>`)+q);else if(d>0)R.push(` ${ne("\u2192",E.cyan)}${d} shot${d===1?"":"s"} blocked \u2014 stage the data below, then ${E.bold("/screenshot capture --blocked")}${q}`);else if(h>0)R.push(` ${ne("\u2192",E.red)}${h} spec${h===1?"":"s"} broken \u2014 ${E.bold(`/screenshot ${e.find(z=>z.state==="broken").id}`)} re-authors ${h===1?"it":"the first"} (re-capturing fails the same way)`);else if(s>0)R.push(` ${ne("\u2192",E.blue)}${s} shot${s===1?"":"s"} awaiting verification \u2014 run ${E.bold("/screenshot verify")}`+E.gray(" \u2014 it checks each picture against what its article needs (no browser, no re-capture)"));else if(i>0){let z=e.filter(pe=>pe.state==="rejected"&&pe.repaired).length;R.push(` ${ne("\u2691",E.magenta)}${i} shot${i===1?"":"s"} failed review \u2014 `+(z>0?`${z} spec${z===1?"":"s"} already repaired; re-capture with ${E.bold("/screenshot capture --failed")}`:`see the reasons below, then ${E.bold("/screenshot capture --failed")}`))}else R.push(` ${ne("\u2713",E.green)}all ${o} verified \u2014 ${E.bold("/publish")} embeds them in the articles`);if(r>0&&r<o){let z=v.filter(([,pe])=>pe.every(de=>de.state!=="verified")).map(([pe])=>{let{num:de,name:Re}=ea(pe);return de?`${de} ${Re}`:Re});z.length>0&&R.push(E.gray(` Furthest behind: ${z.slice(0,5).join(" \xB7 ")}${z.length>5?" \u2026":""} (0% verified)`))}return R.push(...xd(e),...Sd(e),...Rd(e,!1,{commandInLead:ve}),...Cd(e,!1)),R.push(""),R.push(E.gray(" Drill in: /screenshot list <chapter#> \xB7 /screenshot list --detail (all)")),R}function Oy(e,t,n){let o=new Set(e.map(a=>a.file)),r=e.filter(a=>a.state==="verified").length,s=e.filter(a=>a.state==="captured").length,i=[` ${E.bold("Screenshots")}: ${e.length} placeholder${e.length===1?"":"s"} across ${o.size} article${o.size===1?"":"s"} \xB7 ${E.green(`${r} verified`)}${s>0?E.blue(` \xB7 ${s} to verify`):""}${n?E.gray(` \xB7 scope ${n}`):""}`,""];for(let[a,d]of Td(e,t)){let h=d.filter($=>$.state==="verified").length,{num:m,name:k}=ea(a),v=m?`${m} \xB7 ${k}`:k;i.push(` ${E.bold(v)} ${E.gray(`(${h}/${d.length})`)}`);let R=new Map;for(let $ of d){let S=jy($.file),C=R.get(S)??[];R.has(S)||R.set(S,C),C.push($)}for(let $ of[...R.keys()].sort()){i.push(E.gray(` ${$}`));for(let S of R.get($)){let C=Py[S.state];if(i.push(` ${ne(Sy[S.state],C)}${C(S.id)}`),(S.state==="blocked"||S.state==="broken"||S.state==="rejected")&&S.reason){for(let I of At(_n(S.reason),84))i.push(E.gray(` ${I}`));S.state==="rejected"&&i.push(E.gray(` ${S.repaired?"spec repaired \u2014 re-capture to confirm":"spec not yet repaired"}`))}}}}return i.push(...xd(e),...Sd(e),...Rd(e,!0),...Cd(e,!0)),i.push("",Ty),i}function rs(e,t){let n=t?.scope;if(e.length===0)return[n?`No screenshot placeholders under ${n}.`:"No screenshot placeholders found in the docs."];let o=t?.docsDir??sa;return t?.detail||n?Oy(e,o,n):Iy(e,o)}function aa(e,t){if(!t||!/^\d+$/.test(t))return t;let n=Lt(e)?.docsDir??sa,o=String(Number(t));for(let{file:r}of hd(e)){let s=Pd(r,n),i=/^(\d+)/.exec(s);if(i&&String(Number(i[1]))===o)return s}return t}function Ed(e,t){let r=e.map(a=>" ".repeat(a.depth)+a.label),s=Math.max(0,...e.map((a,d)=>a.note?Kr(r[d]):0)),i=Math.min(s,Math.max(0,t-2-24));return e.map((a,d)=>{let h=r[d];if(!a.note)return{head:h,note:""};let m=Math.max(2,i+2-Kr(h)),k=a.note.trim(),v=t-Kr(h)-m;return{head:h+" ".repeat(m),note:v>1&&Kr(k)>v?`${k.slice(0,v-1)}\u2026`:k}})}function Ly(e){let t=e.replace(/\\/g,"/").split("/").filter(Boolean),n=t.pop()??e;return{category:t.pop()??"(docs root)",article:n}}function Xr(e,t,n){let o=new Map;for(let s of t){let{category:i,article:a}=Ly(s.file),d=o.get(i)??new Map;o.set(i,d);let h=d.get(a)??[];d.set(a,h),h.push(s)}let r=s=>n==="author"||!s.mutates;for(let s of[...o.keys()].sort()){let i=o.get(s),a=[...i.values()].flat().filter(r).map(h=>h.id),d=a.length>0;d&&e.push({kind:"category",action:n,label:`${s} (${a.length})`,ids:a,depth:1});for(let h of[...i.keys()].sort()){let m=i.get(h),k=m.filter(r).map($=>$.id),v=k.length>0;v&&e.push({kind:"article",action:n,label:`${h} (${k.length})`,ids:k,depth:d?2:1});let R=(d?1:0)+(v?1:0)+1;for(let $ of m){let S=n==="capture"&&$.mutates?" \u26A0 creates real data \u2014 runs only alone":void 0;e.push({kind:"shot",action:n,label:$.id,ids:[$.id],depth:R,...S?{note:S}:{}})}}}}function Yi(e){return e?_n(e):""}function la(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,d)=>a.id.localeCompare(d.id)))e.push({kind:"shot",action:"capture",label:i.id,ids:[i.id],depth:1,note:` \u2298 ${Yi(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,d)=>a.id.localeCompare(d.id)))e.push({kind:"shot",action:"author",label:i.id,ids:[i.id],depth:1,note:` \u2717 re-authors \u2014 ${Yi(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,d)=>a.id.localeCompare(d.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 ${Yi(i.reason)}`})}}function Ad(e){let t=e.filter(s=>s.state==="placeholder"),n=e.filter(s=>s.state==="spec"),o=[];t.length>1&&o.push({kind:"all",action:"author",label:`Author all ${t.length} remaining specs`,ids:t.map(s=>s.id),depth:0}),Xr(o,t,"author");let r=n.filter(s=>!s.mutates);return r.length>1&&o.push({kind:"all",action:"capture",label:`Capture all ${r.length} ready specs`,ids:r.map(s=>s.id),depth:0}),Xr(o,n,"capture"),la(o,e.filter(s=>s.state==="blocked"),e.filter(s=>s.state==="broken"),e.filter(s=>s.state==="rejected")),o}var ta=["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(`
|
|
344
|
-
`);function
|
|
345
|
-
`),"",...r.length>0?["REPAIR
|
|
346
|
-
`)}async function
|
|
347
|
-
`),display:`/screenshot ${o.id}`}}if(o.mode==="capture"||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.`,
|
|
348
|
-
`),
|
|
349
|
-
`)}var
|
|
350
|
-
`)}async function Mn(e,t){try{let n=ca(e,t),o=n.project.projectId,r=n.project.workspaceId;return!o||!r||(await qy({profile:n.name,connection:n.connection},{cwd:e,profile:n.name,projectPath:`/v3/projects/${o}`,workspaceId:r,verifyHidden:!1})).kind!=="created"?null:`\u2139 Created a hidden "${Gy}" folder on Document360 \u2014 it's where your reviewers leave feedback for d360-writer to action (hidden from readers; its README explains how). /catch-up picks up what they write.`}catch{return null}}var cs="--skip-review";function Un(e,t){let n=[];for(let o of t)try{Hy(Nd(Id(e,o),"utf8")).reviewed===0&&n.push(o)}catch{}return n}function us(e,t,n){let o=e.length,r=o===t?`all ${t} article${t===1?"":"s"}`:`${o} of the ${t} articles`,s=e.slice(0,3).map(i=>` \xB7 ${i.split("/").pop()}`);return[`\u2717 Not published \u2014 ${r} in this run ${o===1?"has":"have"} never been through an editorial review.`,...s,...o>s.length?[` \xB7 \u2026and ${o-s.length} more`]:[],"",`These were written by an AI. Run /review${n?` ${n}`:""} --fix first \u2014 a senior-editor pass that reads every article and applies its fixes \u2014 then publish.`,`(Deliberately publishing without a review: add ${cs}.)`]}function ha(e,t,n){try{let o=Od(e,ca(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 fa(e,t,n,o=0,r){let s=C=>t[C.index]?.paths.length??0,i=e.filter(C=>C.ok),a=e.filter(C=>!C.ok),d=e.reduce((C,I)=>C+s(I),0),h=i.reduce((C,I)=>C+s(I),0),m=n==="api"?`${Fe(e.reduce((C,I)=>C+I.costUsd,0))} total`:It(e.reduce((C,I)=>C+I.outputTokens,0)),k=`${i.length}/${e.length} partition${e.length===1?"":"s"}`,v=C=>`${C} article${C===1?"":"s"}`,R=[],$=r?ct({blocked:r.blocked,allEmpty:r.allEmpty,aborted:!1},"The publish"):null;if($)return R.push(...$),R.push("Nothing reached Document360. Re-run /publish --all once that is fixed."),o>0&&R.push(sn(o)),R;if(r&&d>0&&r.recorded===0){R.push(`\u2717 Nothing was published \u2014 the ${v(d)} in this run are not recorded in the category map, so none of them reached Document360.`),R.push("Run /doctor (this is usually the agent runtime not running), then re-run /publish --all.");for(let C of a)C.error&&R.push(` \u2717 ${C.label} \u2014 ${C.error}`);return o>0&&R.push(sn(o)),R}if(a.length===0&&(!r||r.recorded>=d))R.push(`Published ${v(d)} (${k}) successfully \xB7 ${m}.`),R.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else if(a.length===0&&r)R.push(`Published ${r.recorded}/${v(d)} (${k}) \xB7 ${m}.`),R.push(`${d-r.recorded} article${d-r.recorded===1?"":"s"} reported no error but ${d-r.recorded===1?"is":"are"} not recorded as published \u2014 re-run /publish --all to retry just those.`);else{R.push(`Published ${r?r.recorded:h}/${v(d)} (${k}) \xB7 ${m}.`),R.push(`${a.length} partition${a.length===1?"":"s"} failed \u2014 re-run /publish --all to retry just the rest (published articles are skipped):`);for(let C of a)R.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}let S=r?qr(r):null;return S&&R.push(S),o>0&&R.push(sn(o)),R}async function _t(e,t,n=0,o){if(!o?.skipReview){let i=Un(e.cwd,t);if(i.length>0){for(let a of us(i,t.length))console.log(W(a));return{kind:"continue"}}}let{model:r}=Wy(e.cwd,"standard"),s=async(i,a)=>{let d=Uy(i);console.log(w(a?`Resolving cross-links in ${i.length} article${i.length===1?"":"s"} whose targets published this run (second pass)\u2026`:`Publishing ${i.length} article${i.length===1?"":"s"} across ${d.length} partition${d.length===1?"":"s"} (\u2264${Eo} agents at once) on ${r}\u2026`)),a||console.log(w(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let h=!1;for await(let m of By({cwd:e.cwd,partitions:d,promptFor:k=>Ao(k.paths),concurrency:Eo,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:r}))if(m.type==="partition_status")m.status==="running"?console.log(w(` \u25B8 ${m.label} \u2014 publishing\u2026`)):m.status==="done"?console.log(U(` \u2713 ${m.label}`)):console.log(j(` \u2717 ${m.label}`));else if(m.type==="run_done"){h=m.aborted,console.log("");let k=process.env.ANTHROPIC_API_KEY?"api":"subscription",v=ha(e.cwd,i,e.profileName),R=!m.aborted&&(!!m.blocked||!!m.allEmpty||i.length>0&&v===0);for(let C of fa(m.results,d,k,a?0:n,{recorded:v,...m.blocked?{blocked:m.blocked}:{},...m.allEmpty?{allEmpty:!0}:{}}))console.log(m.ok&&!R?U(C):W(C));if(R)continue;let $=pa(e.cwd,e.profileName);$&&console.log(w($));try{let C=_d(await Ld({cwd:e.cwd,profileName:e.profileName,onRateLimit:I=>console.log(w(` Document360 rate limit \u2014 waiting ${Math.ceil(I.waitMs/1e3)}s\u2026`))}));C&&console.log(w(C))}catch{}try{let C=Ud(await Md({cwd:e.cwd,profileName:e.profileName}));C&&console.log(w(C))}catch{}let S=await Mn(e.cwd,e.profileName);S&&console.log(w(S))}return h};try{if(!await s(t,!1)){let a=await ma(e.cwd,e.profileName,t);a.length>0&&await s(a,!0)}}catch(i){console.log(j(`Publish run failed: ${i.message}`))}return console.log(""),{kind:"continue"}}async function ds(e,t,n){let o=Fy(e,n);if(o.length===0)return[];let r=new Set(da((await is({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function ma(e,t,n){try{let o=new Set(n),r=await is({cwd:e,profileName:t});return da(r.entries).map(s=>s.path).filter(s=>o.has(s))}catch{return[]}}async function Wd(e,t){let n=We(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(j(n.reason)),{kind:"continue"};let o=e.includes(cs),r=e[0];if(e.includes("--screenshots")||e.includes("--shots")){let s=t?.cwd??process.cwd(),i=Pe(s),a=ts(i);if(a.length===0)return console.log(w("No captured screenshots yet \u2014 /screenshot capture first.")),{kind:"continue"};let d=ns(i);return d&&console.log(d),t?await _t(t,a,0,{skipReview:o}):{kind:"forward-to-agent",prompt:Ao(a),display:"/publish --screenshots"}}if(r==="--related"&&e[1]){if(!t)return{kind:"continue"};let s=await ds(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return s.length===0?(console.log(U("\u2713 All related articles are already published.")),{kind:"continue"}):await _t(t,s,0,{skipReview:o})}if(r==="--all"){console.log(w("Checking what needs publishing\u2026"));try{let s=await is({cwd:t?.cwd??process.cwd()}),{clean:i,conflicts:a}=as(s.entries),d=ls(s.entries),h=e.includes("--force")&&a.length>0;d>0&&console.log(W(`\u26A0 ${d} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),a.length>0&&!h&&console.log(W(sn(a.length)));let m=h?[...i,...a]:i;if(m.length===0){if(a.length>0)return console.log(w("Resolve the conflicts: /resolve")),{kind:"continue"};if(console.log(U(d>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),t)try{let k=_d(await Ld({cwd:t.cwd,profileName:t.profileName,onRateLimit:R=>console.log(w(` Document360 rate limit \u2014 waiting ${Math.ceil(R.waitMs/1e3)}s\u2026`))}));k&&console.log(w(k));let v=Ud(await Md({cwd:t.cwd,profileName:t.profileName}));v&&console.log(w(v))}catch{}return{kind:"continue"}}return t?await _t(t,m.map(k=>k.path),h?0:a.length,{skipReview:o}):{kind:"forward-to-agent",prompt:Ao(m.map(k=>k.path)),display:"/publish --all"}}catch(s){return console.log(j(`Could not compute sync status: ${s.message}`)),{kind:"continue"}}}if(r&&r.startsWith("--")&&(r=e.find(s=>!s.startsWith("--"))??""),!r){console.log(w("Checking what needs publishing\u2026"));let s,i=0;try{let a=await is({cwd:t?.cwd??process.cwd()}),{clean:d,conflicts:h}=as(a.entries);s=d,i=h.length;let m=ls(a.entries);if(m>0&&console.log(W(`\u26A0 ${m} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),h.length>0&&console.log(W(sn(h.length))),s.length===0&&h.length>0)return console.log(w("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(a){return console.log(j(`Could not compute sync status: ${a.message}`)),console.log(w("Publish a specific article: /publish <article-path>")),{kind:"continue"}}if(s.length===0)return console.log(U("\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),console.log(w(" (Articles without a sync base are unverified \u2014 publish those by path if needed.)")),{kind:"continue"};if(!process.stdin.isTTY||!t){for(let a of s)console.log(` ${a.path} ${w(`(${a.label})`)}`);return console.log(w("Run: /publish <article-path>")),{kind:"continue"}}try{r=await t.withPausedInput(()=>My({message:"Publish which article?",choices:[...s.length>1?[{name:`All ${s.length} candidates`,value:"--all",description:"one agent run over every candidate"}]:[],...s.map(a=>({name:a.path,value:a.path,description:a.label}))]}))}catch{return console.log(w("Cancelled.")),{kind:"continue"}}if(r==="--all")return await _t(t,s.map(a=>a.path),i,{skipReview:o})}return{kind:"forward-to-agent",prompt:ua(r),display:`/publish ${r}`}}async function Do(){return{kind:"forward-to-agent",prompt:["Run the gap-analysis skill against this repo.","","Follow its stages in order:","1. d360_sync_status first \u2014 stop 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 and what to do about them, in plain words \u2014 never the internal status word.","2. git diff since the lastAnalyzedCommit marker in d360-category-map.json (or last 30 days if no marker), filtered to the authoritativeSourceFiles paths.","2.5. d360_pending_hints \u2014 the source agent's own notes on what it shipped. Verify each (sources exist, commit is an ancestor of HEAD, source shows the surface) before trusting; fold verified ones into the table, flag the rest.","3. Map changes (diff + hints) to articles via their `sources:` frontmatter; read only implicated articles and changed source files. If articles are missing `sources:`, this is the one-time bootstrap pass \u2014 backfill them.","4. Output the proposal table: | Article (path or proposed title) | Action (create | update | retire | link) | Reason | Evidence | Scope |, then advance lastAnalyzedCommit and stamp consumed hints.","","Do not start writing or updating any article yet \u2014 the proposal table is the deliverable."].join(`
|
|
351
|
-
`),display:"/audit"}}
|
|
352
|
-
`)}async function
|
|
353
|
-
`);return
|
|
354
|
-
`)||
|
|
355
|
-
`},r=o(e),s=o(t);if(r===s)return null;let i=Math.max(20,n-10),a=ew("a","b",r,s,"","",{context:3}),d=0,h=0,m=[];a.hunks.forEach((v,R)=>{R>0&&m.push(Vd.gray(" \u2026"));let $=v.oldStart,S=v.newStart,C=[],I=[],Y=()=>{for(let q=0;q<C.length;q++){let K=q<I.length?zd(C[q],I[q]):void 0;h++,m.push(`${tw}${wa($++)} - ${Xd(C[q],i,K)}${Kd}`)}for(let q=0;q<I.length;q++){let K=q<C.length?zd(C[q],I[q]):void 0;d++,m.push(`${nw}${wa(S++)} + ${Xd(I[q],i,K)}${Kd}`)}C=[],I=[]};for(let q of v.lines){let K=q[0],ae=q.slice(1);K==="-"?C.push(ae):K==="+"?I.push(ae):(Y(),m.push(Vd.gray(wa(S))+" "+ae.slice(0,i)),$++,S++)}Y()});let k=m.slice(0,Yd);return{added:d,removed:h,lines:k,hidden:Math.max(0,m.length-Yd)}}X();import{select as ow}from"@inquirer/prompts";import{applyPull as rw,computeSyncStatus as sw,planPull as iw}from"document360-engine";var Qd=e=>e===1?"":"s";async function ka(e,t){console.log(""),console.log(`${H("\u25CF")} ${je(t.title)} ${he(`(${t.path})`)}`);for(let r of t.notes)console.log(W(` \u26A0 ${r}`));let n=Ke(t.oldContent,t.newContent,Math.max(40,(process.stdout.columns??80)-1));if(n){console.log(he(` \u23BF local \u2192 portal: +${n.added} / -${n.removed} line${Qd(n.added+n.removed)}`));for(let r of n.lines)console.log(r);n.hidden>0&&console.log(w(` \u2026 +${n.hidden} more diff lines`))}else console.log(w(" Local already matches the portal content \u2014 resolving just advances the sync base."));let o=await e.withPausedInput(()=>ow({message:`Conflict \u2014 ${t.path}`,choices:[{name:"Keep local (publish \u2014 overwrites the portal edit)",value:"local"},{name:"Take portal (overwrites your local edits)",value:"portal"},{name:"Skip (leave it a conflict)",value:"skip"}]})).catch(()=>"skip");return o==="portal"?(rw({cwd:e.cwd,profileName:e.profileName},t),console.log(U(" \u2713 Took the portal copy (local overwritten, sync base advanced).")),"took-portal"):o==="local"?"keep-local":(console.log(w(" Skipped \u2014 still a conflict.")),"skipped")}async function Jd(e,t){let n=We(t.cwd,t.profileName);if(!n.ok)return console.log(j(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let s=(await sw({cwd:t.cwd,profileName:t.profileName})).entries.filter(a=>a.status==="conflict"&&a.path).map(a=>a.path);if(o){if(!s.includes(o))return console.log(U(`${o} isn't in conflict \u2014 nothing to resolve.`)),{kind:"continue"};s=[o]}if(s.length===0)return console.log(U("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let i=[];for(let a of s){let d=await iw({cwd:t.cwd,profileName:t.profileName,relPath:a});await ka(t,d)==="keep-local"&&i.push(a)}if(i.length>0)return console.log(w(`Publishing ${i.length} kept-local article${Qd(i.length)} over the portal\u2026`)),await _t(t,i)}catch(r){console.log(j(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function tp(e,t){let n=We(t.cwd,t.profileName);if(!n.ok)return console.log(j(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await fw(t),{kind:"continue"};if(o==="--baseline")return await mw(t,e.filter(i=>i!=="--baseline")),{kind:"continue"};if(o==="--compare")return await gw(t),{kind:"continue"};if(o)return console.log(j(`Unknown option: ${o}`)),console.log(w("Usage: /pull pull portal edits + import new portal articles")),console.log(w(" /pull <path> pull one article (or resolve a conflict)")),console.log(w(" /pull --status drift report only (no writes)")),console.log(w(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await yw(t,r),{kind:"continue"};console.log(w("Pulling changes from Document360\u2026"));let s=await $a({cwd:t.cwd,profileName:t.profileName});for(let i of va(s))console.log(i.tone==="ok"?U(i.text):i.tone==="warn"?W(i.text):w(i.text));console.log("")}catch(r){r instanceof hw?console.log(j(r.message)):console.log(j(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function $a(e){let t=await Zd({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 ep({cwd:e.cwd,profileName:e.profileName,relPath:o.path});ba({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 cw({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});uw({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 fs=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,an=e=>e===1?"":"s";function va(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${an(e.pulled.length)} into local: ${fs(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${an(e.imported.length)}: ${fs(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${an(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${an(e.conflicts.length)} changed both here and on Document360 \u2014 left untouched. Resolve them: /resolve (or /publish <path> to keep yours, /pull <path> to take the portal's). (${fs(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${an(e.failed.length)} failed: ${fs(e.failed.map(n=>n.ref))}`}),t.length===0&&t.push({tone:"ok",text:"\u2713 Already in sync with Document360 \u2014 nothing to pull."}),t}async function fw(e){console.log(w("Checking Document360 for drift\u2026"));let t=Date.now(),n=await Zd({cwd:e.cwd,profileName:e.profileName});for(let o of hs(n,Date.now()-t))console.log(o);console.log("")}async function mw(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(w(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await dw({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await pw({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(U("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(U(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(U(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(W(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(w(` - ${s.path} (${s.reason})`))}}async function gw(e){console.log(w("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await lw({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(U("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(j(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(W(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(W(` ${t.onlyInManifest.length} only in the manifest: ${t.onlyInManifest.slice(0,5).join(", ")}`)),console.log(w(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function yw(e,t){let n=t.replace(/\\/g,"/"),o=await ep({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await ka(e,o)==="keep-local"&&(console.log(w(`Publishing ${o.path} over the portal\u2026`)),await _t(e,[o.path]));return}console.log(""),console.log(`${H("\u25CF")} ${je(o.title)} ${he(`(${o.path})`)}`);for(let i of o.notes)console.log(W(` \u26A0 ${i}`));let r=Ke(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!r){console.log(w(" Local file already matches the remote content \u2014 advancing the sync base only.")),ba({cwd:e.cwd,profileName:e.profileName},o);return}console.log(he(` \u23BF Added ${r.added} line${an(r.added)}, removed ${r.removed} line${an(r.removed)}`));for(let i of r.lines)console.log(i);if(r.hidden>0&&console.log(w(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>aw({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(w(" Skipped."));return}ba({cwd:e.cwd,profileName:e.profileName},o),console.log(U(` \u2713 Pulled ${o.path} (sync base advanced).`))}X();import{statSync as ww}from"node:fs";import{resolve as kw}from"node:path";import{estimateBulkCost as bw,planPartitions as $w,readProjectConfig as vw,resolveModelForOperation as xw,runPartitioned as Cw,trackedArticlePaths as Rw}from"document360-engine";var xa=3;function Ca(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 Ra(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Sa(e,t){return t.map(n=>{let o=0;try{o=ww(kw(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function Pa(e){return`Convert each of these articles to canonical Document360 Flavored Markdown (DFM) and re-publish each as a DRAFT. This is a mechanical syntax conversion, not a rewrite \u2014 be efficient:
|
|
356
|
-
- Read ONLY the article files listed below. Do NOT read source code, other articles, or fetch the live portal
|
|
338
|
+
`)}To();var bd=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function gd(e){let t=e.includes("--detail")||e.includes("-d"),n=e.find(o=>o!=="--detail"&&o!=="-d");return{mode:"list",scope:n?bd(n):void 0,...t?{detail:!0}:{}}}function Eo(e){let t=(e[0]??"").toLowerCase();if(t==="capture")return{mode:"capture",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 gd(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 gd(o.slice(1));let r=o[0];return r?r==="--all"?{mode:"all",setup:n}:/[\\/]/.test(r)||r.endsWith(".md")?{mode:"scope",scope:bd(r),setup:n}:{mode:"single",id:r}:{mode:"list",picker:!0}}function Pe(e,t,n){let o=Ut(e),r=o?.captureDir??rs,s=o?.outputDir??la,i=(w,x)=>ts(w)?ns(w,x):os(e,w,x),l=$t(e),d=n?.captureVersion===void 0?vt():n.captureVersion,h=Qr(d,Rd),m=zr(e);return wd(e,{scope:t}).map(({id:w,file:x})=>{let S=i(r,`${w}.spec.ts`),$=null;if(Ji(S))try{$=aa(S,"utf8")}catch{}let T=kd(e,s),R=Ji(wy(T,w)),I=$===null?null:zi(l,w,$,m),Y=l.shots[w]?.review,q=R&&by(Y,$y(T,w))?Y:void 0,z=$!==null&&Py($),ae=R&&q?.verdict==="ok"?"verified":R&&q?.verdict==="rejected"?"rejected":R?"captured":$===null?"placeholder":z||I?.outcome==="skipped"?"blocked":I?.outcome==="failed"?"broken":"spec",xe=$===null?void 0:vd($),ke=z?Ey($):I?.reason,Ee=z?"testid":I?.outcome==="skipped"?Ki(I.reason):void 0,ge=$===null?[]:Ty(e,$);return{id:w,file:x,state:ae,...xe?{mutates:xe.mutates,...xe.declared?{}:{undeclared:!0}}:{},...$!==null&&ea($).length>0?{unguardedWaits:ea($)}:{},...$!==null&&Zi($).length>0?{unverifiedForce:Zi($)}:{},...$!==null&&ta($).length>0?{handRolled:ta($)}:{},...$!==null&&oa($).length>0?{stalePause:oa($)}:{},...$!==null&&h&&na($).length>0?{bareGoto:na($)}:{},...ge.length>0?{staleAnchor:ge}:{},...ae==="blocked"||ae==="broken"?{...ke?{reason:ke}:{},...Ee?{blockedBy:Ee}:{}}:{},...ae==="rejected"?{...q?.reason?{reason:q.reason}:{},...q?.repaired?{repaired:!0}:{}}:{}}})}function Cy(e){let t=Ut(e)?.outputDir??la;return ky(kd(e,t))}function Ao(e){let t=Cy(e),n=Ut(e)?.outputDir??la,o=[];t>0&&o.push(`\u2195 Tidied ${t} screenshot file${t===1?"":"s"} into ${n}/{${xy},${Ry}} \u2014 annotated/ is what publishes, raw/ is the pre-annotation intermediate.`);let r=md(fd(e));return r&&o.push(r),o.length>0?o.join(`
|
|
339
|
+
`):null}function an(e,t){let n=Ut(e)?.captureDir??rs,o=ts(n)?ns(n,`${t}.spec.ts`):os(e,n,`${t}.spec.ts`);try{return aa(o,"utf8")}catch{return null}}function $d(e,t){let n=Ut(e)?.captureDir??rs;return Ji(ts(n)?ns(n,`${t}.spec.ts`):os(e,n,`${t}.spec.ts`))}function Sy(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 vd(e){let t=e.split(/\r?\n/),n=t.findIndex(l=>/^\s*\/\/\s*CAPTURE-SAFETY:\s*(readonly|mutates)\b/i.test(l)),o=n>=0?/^\s*\/\/\s*CAPTURE-SAFETY:\s*(readonly|mutates)\b[\s—:–-]*(.*)$/i.exec(t[n]):null;if(o){let l=Sy(t,n,o[2]??"");return{mutates:o[1].toLowerCase()==="mutates",declared:!0,what:l||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 Py(e){return/(^|\n)\s*test\.skip\s*\(\s*['"`]/.test(e)}function xd(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 Ty(e,t){let n=[];for(let o of xd(t))vy(e,o.file,o.anchor)===!1&&n.push(o.testid??o.file??"unnamed request");return[...new Set(n)]}function Ey(e){let{testid:t,file:n}=xd(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 Do(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 Zi(e,t=10){let n=Do(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(`
|
|
340
|
+
`))||o.push(r+1));return o}function ea(e){let t=[],n=Do(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 ta(e){let t=[];for(let[n,o]of Do(e).entries())(/\.screenshot\s*\(/.test(o)||/\bdumpAnnotations\s*\(/.test(o))&&t.push(n+1);return t}var Rd="0.2.28";function na(e){let t=[];for(let[n,o]of Do(e).entries())/\.goto\s*\(/.test(o)&&t.push(n+1);return t}function oa(e,t=6){let n=Do(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(`
|
|
341
|
+
`);if(!/test\.skip\s*\(/.test(i)||!/\.count\s*\(\s*\)/.test(i))continue;let l=n.slice(Math.max(0,r-t),r+1).join(`
|
|
342
|
+
`);/\.waitFor\s*\(|Promise\.race\s*\(|waitForFunction\s*\(|waitForSelector\s*\(/.test(l)||o.push(r+1)}return o}function ua(e,t){let n=m=>`line${m.length===1?"":"s"} ${m.join(", ")}`,o=[],r=t?.captureVersion===void 0?vt():t.captureVersion,s=Qr(r,Rd)?na(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=ea(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 l=ta(e);l.length>0&&o.push(`- ${n(l)}: takes its own screenshot (or calls dumpAnnotations) instead of captureShot(page, PLACEHOLDER). On a cropped shot that misplaces every callout and nothing errors.`);let d=oa(e);d.length>0&&o.push(`- ${n(d)}: 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 h=Zi(e);return h.length>0&&o.push(`- ${n(h)}: 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 Cd(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 Sd(e){return(e??"").trim().replace(/[.\s]+$/,"")}function Pd(e,t){let n=Ut(e)?.captureDir??rs,o=ts(n)?ns(n,`${t}.spec.ts`):os(e,n,`${t}.spec.ts`);try{return vd(aa(o,"utf8"))}catch{return{mutates:!1,declared:!1}}}var Ay=["captured","verified","rejected"],Dy=e=>Ay.includes(e);function ss(e){return[...new Set(e.filter(t=>Dy(t.state)).map(t=>t.file))].sort()}function is(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[`${ne("\u26A0",A.yellow)}${t.length} screenshot${t.length===1?"":"s"} failed verification:`,...t.map(o=>` ${A.magenta(o.id.padEnd(n))} ${A.gray(Wn(o.reason??"no reason recorded"))}`),` Publishing anyway. Fix + re-capture: ${A.bold("/screenshot capture --failed")}`].join(`
|
|
343
|
+
`)}var jy={placeholder:"\u25CB",spec:"\u25D0",blocked:"\u2298",broken:"\u2717",captured:"\u25CF",verified:"\u2714",rejected:"\u2691"},Ny={placeholder:A.gray,spec:A.yellow,blocked:A.cyan,broken:A.red,captured:A.blue,verified:A.green,rejected:A.magenta},Iy=` ${A.green("\u2714 verified")} ${A.blue("\u25CF to verify")} ${A.yellow("\u25D0 ready")} ${A.magenta("\u2691 rejected")} ${A.cyan("\u2298 blocked")} ${A.red("\u2717 broken")} ${A.gray("\u25CB to spec")}`;function ne(e,t=n=>n){return`${t(e)} `}function Wn(e){return e.replace(/\s+/g," ").trim().replace(/^Prerequisites? not met[:—-]?\s*/i,"")}function as(e){let t=Wn(e),n=/^(.*?[a-z0-9)"'”’])\.(?:\s|$)/i.exec(t);return(n?n[1]:t).trim()}function jo(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=as(o),i=`${r} ${s.toLowerCase()}`,l=t.get(i)??{reason:s,blockedBy:r,ids:[]};t.has(i)||t.set(i,l),l.ids.push(n.id)}return[...t.values()].sort((n,o)=>o.ids.length-n.ids.length||n.reason.localeCompare(o.reason))}function Td(e){let t=jo(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((l,d)=>l+d.ids.length,0);r.push(` ${A.bold("Stage this data")} ${A.gray(`\u2014 unblocks ${s} shot${s===1?"":"s"} in ${n.length} action${n.length===1?"":"s"}`)}`);let i=8;for(let l of n.slice(0,i)){let d=Nt(l.reason,86);r.push(` ${A.cyan(Mt(`${l.ids.length}\xD7`,4))} ${d[0]??""}`);for(let m of d.slice(1))r.push(` ${m}`);let h=l.ids.slice(0,4).join(" \xB7 ");r.push(A.gray(` ${h}${l.ids.length>4?` \xB7 +${l.ids.length-4} more`:""}`))}n.length>i&&r.push(A.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,l)=>i+l.ids.length,0);r.push(` ${ne("\u2298",A.cyan)}${s} shot${s===1?"":"s"} need${s===1?"s":""} a data-testid from your developers \u2014 ${A.bold("/screenshot checklist")} builds the hand-off.`)}return r}function Ed(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=["",` ${ne("\u26A0",A.yellow)}${r} selector request${r===1?"":"s"} quote${r===1?"s":""} source code that has since changed`+A.gray(" \u2014 your developers would go looking for something that isn't there any more"),A.gray(` Refresh the hand-off before sending it: ${A.bold("/screenshot checklist")}`)];return t&&s.push(A.gray(` ${o.slice(0,8).join(" \xB7 ")}${r>8?` \xB7 +${r-8} more`:""}`)),s}function Ad(e,t,n){let o=e.filter(m=>(m.unguardedWaits?.length??0)>0),r=e.filter(m=>m.undeclared),s=e.filter(m=>(m.handRolled?.length??0)>0),i=e.filter(m=>(m.stalePause?.length??0)>0),l=e.filter(m=>(m.bareGoto?.length??0)>0);if(o.length===0&&r.length===0&&s.length===0&&i.length===0&&l.length===0)return[];let d=["",` ${ne("\u26A0",A.yellow)}Some specs were written before later reliability fixes:`],h=(m,w)=>` ${m.slice(0,8).map(w).join(" \xB7 ")}${m.length>8?` \xB7 +${m.length-8} more`:""}`;if(o.length>0){let m=o.length;d.push(A.gray(` ${m} crash${m===1?"es":""} instead of telling you what to stage when the data ${m===1?"it needs":"they need"} is missing`)),t&&d.push(A.gray(h(o,w=>`${w.id}:${w.unguardedWaits.join(",")}`)))}if(l.length>0){let m=l.length;d.push(A.gray(` ${m} open${m===1?"s":""} pages the slow way, so ${m===1?"it stalls":"they stall"} for a minute and give up when several shots run at once`)),t&&d.push(A.gray(h(l,w=>`${w.id}:${w.bareGoto.join(",")}`)))}if(i.length>0){let m=i.length;d.push(A.gray(` ${m} decide${m===1?"s":""} "the data is missing" from a fixed pause, so data you HAVE staged can read as absent`)),t&&d.push(A.gray(h(i,w=>`${w.id}:${w.stalePause.join(",")}`)))}if(s.length>0){let m=s.length;d.push(A.gray(` ${m} take${m===1?"s":""} ${m===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&&d.push(A.gray(h(s,w=>`${w.id}:${w.handRolled.join(",")}`)))}if(r.length>0){let m=r.length,w=r.filter(x=>x.mutates).length;d.push(A.gray(` ${m} do${m===1?"es":""} not say whether ${m===1?"it changes":"they change"} data in your app`+(w>0?`, so ${w===1?"one is":`${w} are`} left out of bulk runs to be safe`:""))),t&&d.push(A.gray(h(r,x=>x.id)))}return n?.commandInLead||d.push(A.gray(` Re-write them all with the current rules: ${A.bold("/screenshot author --all")}`)),d}function Dd(e){let t=e.filter(n=>(n.unverifiedForce?.length??0)>0);return t.length===0?[]:["",` ${ne("\u26A0",A.red)}${t.length} spec${t.length===1?"":"s"} force-click past Playwright's safety checks without asserting the result`+A.gray(" \u2014 if the click lands on nothing, the shot photographs the unchanged screen"),A.gray(` ${t.slice(0,6).map(n=>`${n.id}:${n.unverifiedForce.join(",")}`).join(" \xB7 ")}${t.length>6?` \xB7 +${t.length-6} more`:""}`),A.gray(` Re-author to check what the click did: ${A.bold("/screenshot author <id>")}`)]}var Zr=(e,t)=>e.length>=t?e:e+" ".repeat(t-e.length),Mt=(e,t)=>e.length>=t?e:" ".repeat(t-e.length)+e;function jd(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 Oy=new Set(["and","or","of","the","to","a","an","in","on","for","with","vs"]),Ly=new Set(["ai","api","cli","ui","ux","url","id","http","https","json","xml","sdk","csv","pdf","oauth","sso","mfa","io","faq"]);function _y(e){return e.replace(/[-_]+/g," ").trim().split(/\s+/).filter(Boolean).map((n,o)=>{let r=n.toLowerCase();return Ly.has(r)?r.toUpperCase():o>0&&Oy.has(r)?r:r.charAt(0).toUpperCase()+r.slice(1)}).join(" ")}function ra(e){if(!e)return{num:"",name:"(docs root)"};let t=/^(\d+)[-_](.+)$/.exec(e);return{num:t?t[1]:"",name:_y(t?t[2]:e)}}function My(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).pop()??e}function yd(e,t,n){let o=t>0?Math.round(e/t*n):0;return A.green("\u2588".repeat(o))+A.gray("\u2591".repeat(Math.max(0,n-o)))}function Uy(e,t){let n=t>0?Math.round(e/t*100):0,o=Mt(`${n}%`,4);return n===100?A.green(o):n>0?A.yellow(o):A.gray(o)}function Nd(e,t){let n=new Map;for(let o of e){let r=jd(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 Wy(e,t){let n=(K,pe)=>K.filter(le=>le.state===pe).length,o=e.length,r=n(e,"verified"),s=n(e,"captured"),i=n(e,"rejected"),l=n(e,"spec"),d=n(e,"blocked"),h=n(e,"broken"),m=n(e,"placeholder"),w=new Set(e.map(K=>K.file)).size,x=Nd(e,t),S=[];S.push(` ${A.bold("Screenshots")} ${A.green(`${r}/${o} verified`)} ${A.gray("\xB7")} ${s>0?A.blue(`${s} to verify`):A.gray("0 to verify")}`+(i>0?` ${A.gray("\xB7")} ${A.magenta(`${i} rejected`)}`:"")+` ${A.gray("\xB7")} ${l>0?A.yellow(`${l} ready`):A.gray("0 ready")}`+(d>0?` ${A.gray("\xB7")} ${A.cyan(`${d} blocked`)}`:"")+(h>0?` ${A.gray("\xB7")} ${A.red(`${h} broken`)}`:"")+` ${A.gray("\xB7")} ${m>0?A.red(`${m} to spec`):A.gray("0 to spec")} `+A.gray(`across ${w} article${w===1?"":"s"}`));let $=o>0?Math.round(r/o*100):0;S.push(` [${yd(r,o,32)}] ${A.bold(`${$}%`)}`),S.push("");let T=x.map(([K])=>ra(K)),R=Math.min(32,Math.max(7,...T.map(K=>K.name.length))),I=K=>K.length>R?`${K.slice(0,R-1)}\u2026`:Zr(K,R),Y=[...s>0?[{head:"To verify",w:9,state:"captured",color:A.blue}]:[],...i>0?[{head:"Rejected",w:8,state:"rejected",color:A.magenta}]:[],{head:"Ready",w:5,state:"spec",color:A.yellow},...d>0?[{head:"Blocked",w:7,state:"blocked",color:A.cyan}]:[],...h>0?[{head:"Broken",w:6,state:"broken",color:A.red}]:[],{head:"To spec",w:7,state:"placeholder",color:A.red}];S.push(A.gray(` ${Zr("#",2)} ${Zr("Chapter",R)} ${Mt("Verified",8)} ${Y.map(K=>Mt(K.head,K.w)).join(" ")} Progress`));for(let[K,[,pe]]of x.entries()){let le=n(pe,"verified"),Ce=pe.length,{num:Se,name:Qe}=T[K],xt=le===Ce,qt=I(Qe),sr=Y.map(it=>{let ir=n(pe,it.state);return ir>0?it.color(Mt(String(ir),it.w)):A.gray(Mt("\u2014",it.w))}).join(" ");S.push(` ${A.cyan(Zr(Se,2))} ${xt?A.green(qt):le>0?qt:A.gray(qt)} ${xt?A.green(Mt(`${le}/${Ce}`,8)):Mt(`${le}/${Ce}`,8)} ${sr} ${yd(le,Ce,10)} ${Uy(le,Ce)}`)}S.push("");let q=h>0?` ${A.gray("\xB7")} ${h} spec${h===1?"":"s"} broken \u2014 ${A.bold(`/screenshot ${e.find(K=>K.state==="broken").id}`)} re-authors ${h===1?"it":"the first"}`:"",z=e.filter(K=>K.state==="spec"&&K.mutates).length,ae=l>z,xe=e.filter(K=>(K.unguardedWaits?.length??0)>0||(K.bareGoto?.length??0)>0).length,ke=e.filter(K=>(K.stalePause?.length??0)>0||(K.handRolled?.length??0)>0).length,Ee=l>0||d>0||h>0,ge=!1;if(m>0)S.push(` ${ne("\u2192",A.yellow)}${m} placeholder${m===1?"":"s"} still need a spec \u2014 run ${A.bold("/screenshot author --all")}${q}`);else if(xe>0&&Ee)ge=!0,S.push(` ${ne("\u2192",A.yellow)}${xe} spec${xe===1?"":"s"} would crash mid-run \u2014 re-write ${xe===1?"it":"them"} first: ${A.bold("/screenshot author --all")}`+A.gray(` \xB7 then ${A.bold("/screenshot capture")} (no browser time wasted on ${xe===1?"a shot":"shots"} that can't finish)`)+q);else if(ke>0&&Ee)ge=!0,S.push(` ${ne("\u2192",A.yellow)}${ke} spec${ke===1?"":"s"} would shoot the wrong thing \u2014 re-write ${ke===1?"it":"them"} first: ${A.bold("/screenshot author --all")}`+A.gray(` \xB7 then ${A.bold("/screenshot capture")} (a false skip or a misplaced callout costs the same browser time as a good shot)`)+q);else if(l>0&&(ae||s===0)){let K=z>0?A.gray(` \u2014 ${l-z} in one go; ${z} write${z===1?"s":""} real data and run${z===1?"s":""} one at a time`):"";S.push(` ${ne("\u2192",A.yellow)}${l} spec${l===1?"":"s"} ready to capture \u2014 run ${A.bold("/screenshot capture")}${K}${q}`)}else if(s>0&&l>0)S.push(` ${ne("\u2192",A.blue)}${s} shot${s===1?"":"s"} awaiting verification \u2014 run ${A.bold("/screenshot verify")}`+A.gray(" \u2014 no browser needed")+A.gray(` \xB7 ${l} ready spec${l===1?"":"s"} write real data, so ${l===1?"it runs":"each runs"} only when named: /screenshot capture <id>`)+q);else if(d>0)S.push(` ${ne("\u2192",A.cyan)}${d} shot${d===1?"":"s"} blocked \u2014 stage the data below, then ${A.bold("/screenshot capture --blocked")}${q}`);else if(h>0)S.push(` ${ne("\u2192",A.red)}${h} spec${h===1?"":"s"} broken \u2014 ${A.bold(`/screenshot ${e.find(K=>K.state==="broken").id}`)} re-authors ${h===1?"it":"the first"} (re-capturing fails the same way)`);else if(s>0)S.push(` ${ne("\u2192",A.blue)}${s} shot${s===1?"":"s"} awaiting verification \u2014 run ${A.bold("/screenshot verify")}`+A.gray(" \u2014 it checks each picture against what its article needs (no browser, no re-capture)"));else if(i>0){let K=e.filter(pe=>pe.state==="rejected"&&pe.repaired).length;S.push(` ${ne("\u2691",A.magenta)}${i} shot${i===1?"":"s"} failed review \u2014 `+(K>0?`${K} spec${K===1?"":"s"} already repaired; re-capture with ${A.bold("/screenshot capture --failed")}`:`see the reasons below, then ${A.bold("/screenshot capture --failed")}`))}else S.push(` ${ne("\u2713",A.green)}all ${o} verified \u2014 ${A.bold("/publish")} embeds them in the articles`);if(r>0&&r<o){let K=x.filter(([,pe])=>pe.every(le=>le.state!=="verified")).map(([pe])=>{let{num:le,name:Ce}=ra(pe);return le?`${le} ${Ce}`:Ce});K.length>0&&S.push(A.gray(` Furthest behind: ${K.slice(0,5).join(" \xB7 ")}${K.length>5?" \u2026":""} (0% verified)`))}return S.push(...Td(e),...Dd(e),...Ad(e,!1,{commandInLead:ge}),...Ed(e,!1)),S.push(""),S.push(A.gray(" Drill in: /screenshot list <chapter#> \xB7 /screenshot list --detail (all)")),S}function Fy(e,t,n){let o=new Set(e.map(l=>l.file)),r=e.filter(l=>l.state==="verified").length,s=e.filter(l=>l.state==="captured").length,i=[` ${A.bold("Screenshots")}: ${e.length} placeholder${e.length===1?"":"s"} across ${o.size} article${o.size===1?"":"s"} \xB7 ${A.green(`${r} verified`)}${s>0?A.blue(` \xB7 ${s} to verify`):""}${n?A.gray(` \xB7 scope ${n}`):""}`,""];for(let[l,d]of Nd(e,t)){let h=d.filter($=>$.state==="verified").length,{num:m,name:w}=ra(l),x=m?`${m} \xB7 ${w}`:w;i.push(` ${A.bold(x)} ${A.gray(`(${h}/${d.length})`)}`);let S=new Map;for(let $ of d){let T=My($.file),R=S.get(T)??[];S.has(T)||S.set(T,R),R.push($)}for(let $ of[...S.keys()].sort()){i.push(A.gray(` ${$}`));for(let T of S.get($)){let R=Ny[T.state];if(i.push(` ${ne(jy[T.state],R)}${R(T.id)}`),(T.state==="blocked"||T.state==="broken"||T.state==="rejected")&&T.reason){for(let I of Nt(Wn(T.reason),84))i.push(A.gray(` ${I}`));T.state==="rejected"&&i.push(A.gray(` ${T.repaired?"spec repaired \u2014 re-capture to confirm":"spec not yet repaired"}`))}}}}return i.push(...Td(e),...Dd(e),...Ad(e,!0),...Ed(e,!0)),i.push("",Iy),i}function ls(e,t){let n=t?.scope;if(e.length===0)return[n?`No screenshot placeholders under ${n}.`:"No screenshot placeholders found in the docs."];let o=t?.docsDir??ca;return t?.detail||n?Fy(e,o,n):Wy(e,o)}function da(e,t){if(!t||!/^\d+$/.test(t))return t;let n=Ut(e)?.docsDir??ca,o=String(Number(t));for(let{file:r}of wd(e)){let s=jd(r,n),i=/^(\d+)/.exec(s);if(i&&String(Number(i[1]))===o)return s}return t}function Id(e,t){let r=e.map(l=>" ".repeat(l.depth)+l.label),s=Math.max(0,...e.map((l,d)=>l.note?Jr(r[d]):0)),i=Math.min(s,Math.max(0,t-2-24));return e.map((l,d)=>{let h=r[d];if(!l.note)return{head:h,note:""};let m=Math.max(2,i+2-Jr(h)),w=l.note.trim(),x=t-Jr(h)-m;return{head:h+" ".repeat(m),note:x>1&&Jr(w)>x?`${w.slice(0,x-1)}\u2026`:w}})}function By(e){let t=e.replace(/\\/g,"/").split("/").filter(Boolean),n=t.pop()??e;return{category:t.pop()??"(docs root)",article:n}}function es(e,t,n){let o=new Map;for(let s of t){let{category:i,article:l}=By(s.file),d=o.get(i)??new Map;o.set(i,d);let h=d.get(l)??[];d.set(l,h),h.push(s)}let r=s=>n==="author"||!s.mutates;for(let s of[...o.keys()].sort()){let i=o.get(s),l=[...i.values()].flat().filter(r).map(h=>h.id),d=l.length>0;d&&e.push({kind:"category",action:n,label:`${s} (${l.length})`,ids:l,depth:1});for(let h of[...i.keys()].sort()){let m=i.get(h),w=m.filter(r).map($=>$.id),x=w.length>0;x&&e.push({kind:"article",action:n,label:`${h} (${w.length})`,ids:w,depth:d?2:1});let S=(d?1:0)+(x?1:0)+1;for(let $ of m){let T=n==="capture"&&$.mutates?" \u26A0 creates real data \u2014 runs only alone":void 0;e.push({kind:"shot",action:n,label:$.id,ids:[$.id],depth:S,...T?{note:T}:{}})}}}}function Qi(e){return e?Wn(e):""}function pa(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((l,d)=>l.id.localeCompare(d.id)))e.push({kind:"shot",action:"capture",label:i.id,ids:[i.id],depth:1,note:` \u2298 ${Qi(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((l,d)=>l.id.localeCompare(d.id)))e.push({kind:"shot",action:"author",label:i.id,ids:[i.id],depth:1,note:` \u2717 re-authors \u2014 ${Qi(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((l,d)=>l.id.localeCompare(d.id))){let l=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 ${l} \u2014 ${Qi(i.reason)}`})}}function Od(e){let t=e.filter(s=>s.state==="placeholder"),n=e.filter(s=>s.state==="spec"),o=[];t.length>1&&o.push({kind:"all",action:"author",label:`Author all ${t.length} remaining specs`,ids:t.map(s=>s.id),depth:0}),es(o,t,"author");let r=n.filter(s=>!s.mutates);return r.length>1&&o.push({kind:"all",action:"capture",label:`Capture all ${r.length} ready specs`,ids:r.map(s=>s.id),depth:0}),es(o,n,"capture"),pa(o,e.filter(s=>s.state==="blocked"),e.filter(s=>s.state==="broken"),e.filter(s=>s.state==="rejected")),o}var sa=["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(`
|
|
344
|
+
`);function Hy(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 ia="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 Ld(e,t,n){let o=e.paths,r=o.filter(d=>t?.get(d)?.outcome==="failed"),s=o.filter(d=>t?.get(d)?.outcome==="skipped"),i=d=>`- ${d}: ${t.get(d).reason.replace(/\s+/g," ").trim()}`,l=o.filter(d=>(n?.get(d)?.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(d=>`- ${d}`).join(`
|
|
345
|
+
`),"",...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),""]:[],...l.flatMap(d=>Cd(n.get(d),`RULE VIOLATIONS already in ${d}'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.",sa,ia].join(`
|
|
346
|
+
`)}async function cs(e,t,n){let o=Eo(e),r=Ao(t?.cwd??process.cwd());if(r&&console.log(A.gray(r)),o.mode==="list"){let d=t?.cwd??process.cwd(),h=da(d,o.scope),m=Ut(d)?.docsDir??ca,w=Pe(d,h);for(let x of ls(w,{scope:h,detail:o.detail,docsDir:m}))console.log(x);return{kind:"continue"}}if(o.mode==="single"){let d=an(t?.cwd??process.cwd(),o.id),h=d===null?[]:ua(d);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.",sa,ia,...n?.prior?["",...Hy(n.prior)]:[],...h.length>0?["",...Cd(h,"RULE VIOLATIONS already in the existing spec \u2014 fix every one:")]:[]].join(`
|
|
347
|
+
`),display:`/screenshot ${o.id}`}}if(o.mode==="capture"||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.`,sa,ia].join(`
|
|
348
|
+
`),l=o.mode==="scope"?`/screenshot ${o.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:i,display:l}}var No=3;function fa(e){return[`Run the publish-to-d360 skill for the article at: ${e}`,"","Steps you must follow:","1. Read the article markdown, using the repo-relative path exactly as given above (it resolves against the working directory; do not reconstruct an absolute path).","2. Compute the D360 publish form (strip the YAML frontmatter and the H1 title, normalize cross-article links). For each <!-- SCREENSHOT ... --> block, read its id BEFORE stripping the block: when <outputDir>/<id>.png exists (the annotated capture), upload it (d360_search_drive first to reuse, else d360_upload_drive_file) and replace the visible [Screenshot: ...] line with the image markdown; only when no PNG exists does the visible line stay as text.","3. Look up the article ID in <repo>/d360-category-map.json. If present, call the document360 MCP update-article tool. If absent, call create-article with local_path set to the repo-relative .md path (the tool records the new ID + sync base in the category map itself; do not edit the articles map by hand).","4. Report what changed and remind me to publish the draft manually in the Document360 portal."].join(`
|
|
349
|
+
`)}var _d={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function ma(e){return e.filter(t=>t.path!==null&&t.status in _d&&!t.link).map(t=>({path:t.path,label:_d[t.status]}))}function cn(e){let t=ma(e),n=new Set(e.filter(o=>o.status==="conflict"&&o.path).map(o=>o.path));return{clean:t.filter(o=>!n.has(o.path)),conflicts:t.filter(o=>n.has(o.path))}}function ln(e){let t=e!==1;return`\u26A0 ${e} conflict${t?"s":""} NOT published (portal edit${t?"s":""} kept safe) \u2014 ${t?"these were":"it was"} edited both here and on the portal, so ${t?"they are":"it is"} left untouched. Settle ${t?"them":"it"}: /resolve (or /publish <path> to keep yours, /pull <path> to take the portal's).`}function ds(e){return e.filter(t=>t.link).length}function ga(e,t){try{let n=Md(e,ha(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=tw(qy(Gy(e,r),"utf8"),r,n).unresolved}catch{}return o===0?null:`\u2139 ${o} cross-link${o===1?"":"s"} point to pages not published yet \u2014 they show as plain text for now and turn into live links once those pages are published.`}catch{return null}}function nw(e){let t=e.replace(/\\/g,"/").split("/").pop()??e,n=t.replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return n?n.charAt(0).toUpperCase()+n.slice(1):t}function Hd(e,t=[]){let n=[];e.length>1&&n.push({kind:"all",label:`Publish all ${e.length} articles`,paths:e.map(r=>r.path),indent:!1});let o=new Map;for(let r of e){let s=r.path.replace(/\\/g,"/").split("/").slice(0,-1).join("/"),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,l)=>i.path.localeCompare(l.path));n.push({kind:"category",label:`${nw(r)} (${s.length})`,paths:s.map(i=>i.path),indent:!1});for(let i of s){let l=i.path.replace(/\\/g,"/").split("/").pop()??i.path;n.push({kind:"article",label:l,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}function Io(e){return[`Run the publish-to-d360 skill for ALL of these ${e.length} articles, one by one:`,"",...e.map(t=>`- ${t}`),"","Use the repo-relative paths exactly as listed (they resolve against the working directory; do not reconstruct absolute paths). Apply the normal per-article publish flow (frontmatter/H1/screenshot-comment strips, link normalization; update when mapped, create with local_path when not). Compute each publish form IN MEMORY and pass it straight to the tool, and NEVER write it to disk (no *.publish.md siblings, no temp copies anywhere in the docs tree; the local .md files stay untouched). If one article fails, note it and continue. Finish with a summary table (article | created/updated | failures) and remind me drafts need review in the portal."].join(`
|
|
350
|
+
`)}async function Fn(e,t){try{let n=ha(e,t),o=n.project.projectId,r=n.project.workspaceId;return!o||!r||(await Zy({profile:n.name,connection:n.connection},{cwd:e,profile:n.name,projectPath:`/v3/projects/${o}`,workspaceId:r,verifyHidden:!1})).kind!=="created"?null:`\u2139 Created a hidden "${ew}" folder on Document360 \u2014 it's where your reviewers leave feedback for d360-writer to action (hidden from readers; its README explains how). /catch-up picks up what they write.`}catch{return null}}var pt="--skip-review";function un(e,t){return Qy(e,t)}function ya(e,t){try{return un(e,Jy(e,t)).length}catch{return 0}}function Oo(e,t,n=""){let o=ya(e);return o===0?t:{text:`${n}${o} article${o===1?"":"s"} ${o===1?"has":"have"} never been editorially reviewed, so publishing is blocked until then. /review --fix reads each one and applies its fixes \u2014 then /publish --all.`,cmd:"/review --fix"}}function ps(e,t,n){let o=e.length,r=o===t?`all ${t} article${t===1?"":"s"}`:`${o} of the ${t} articles`,s=e.slice(0,3).map(i=>` \xB7 ${i.split("/").pop()}`);return[`\u2717 Not published \u2014 ${r} in this run ${o===1?"has":"have"} never been through an editorial review.`,...s,...o>s.length?[` \xB7 \u2026and ${o-s.length} more`]:[],"",`These were written by an AI. Run /review${n?` ${n}`:""} --fix first \u2014 a senior-editor pass that reads every article and applies its fixes \u2014 then publish.`,`(Deliberately publishing without a review: add ${pt}.)`]}function wa(e,t,n){try{let o=Md(e,ha(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 ka(e,t,n,o=0,r){let s=R=>t[R.index]?.paths.length??0,i=e.filter(R=>R.ok),l=e.filter(R=>!R.ok),d=e.reduce((R,I)=>R+s(I),0),h=i.reduce((R,I)=>R+s(I),0),m=n==="api"?`${We(e.reduce((R,I)=>R+I.costUsd,0))} total`:_t(e.reduce((R,I)=>R+I.outputTokens,0)),w=`${i.length}/${e.length} partition${e.length===1?"":"s"}`,x=R=>`${R} article${R===1?"":"s"}`,S=[],$=r?ut({blocked:r.blocked,allEmpty:r.allEmpty,aborted:!1},"The publish"):null;if($)return S.push(...$),S.push("Nothing reached Document360. Re-run /publish --all once that is fixed."),o>0&&S.push(ln(o)),S;if(r&&d>0&&r.recorded===0){S.push(`\u2717 Nothing was published \u2014 the ${x(d)} in this run are not recorded in the category map, so none of them reached Document360.`),S.push("Run /doctor (this is usually the agent runtime not running), then re-run /publish --all.");for(let R of l)R.error&&S.push(` \u2717 ${R.label} \u2014 ${R.error}`);return o>0&&S.push(ln(o)),S}if(l.length===0&&(!r||r.recorded>=d))S.push(`Published ${x(d)} (${w}) successfully \xB7 ${m}.`),S.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else if(l.length===0&&r)S.push(`Published ${r.recorded}/${x(d)} (${w}) \xB7 ${m}.`),S.push(`${d-r.recorded} article${d-r.recorded===1?"":"s"} reported no error but ${d-r.recorded===1?"is":"are"} not recorded as published \u2014 re-run /publish --all to retry just those.`);else{S.push(`Published ${r?r.recorded:h}/${x(d)} (${w}) \xB7 ${m}.`),S.push(`${l.length} partition${l.length===1?"":"s"} failed \u2014 re-run /publish --all to retry just the rest (published articles are skipped):`);for(let R of l)S.push(` \u2717 ${R.label}${R.error?` \u2014 ${R.error}`:""}`)}let T=r?Kr(r):null;return T&&S.push(T),o>0&&S.push(ln(o)),S}async function dt(e,t,n=0,o){if(!o?.skipReview){let i=un(e.cwd,t);if(i.length>0){for(let l of ps(i,t.length))console.log(W(l));return{kind:"continue"}}}let{model:r}=zy(e.cwd,"standard"),s=async(i,l)=>{let d=Yy(i);console.log(k(l?`Resolving cross-links in ${i.length} article${i.length===1?"":"s"} whose targets published this run (second pass)\u2026`:`Publishing ${i.length} article${i.length===1?"":"s"} across ${d.length} partition${d.length===1?"":"s"} (\u2264${No} agents at once) on ${r}\u2026`)),l||console.log(k(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let h=!1;for await(let m of Xy({cwd:e.cwd,partitions:d,promptFor:w=>Io(w.paths),concurrency:No,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),allowUnreviewedPublish:o?.skipReview===!0,model:r}))if(m.type==="partition_status")m.status==="running"?console.log(k(` \u25B8 ${m.label} \u2014 publishing\u2026`)):m.status==="done"?console.log(U(` \u2713 ${m.label}`)):console.log(j(` \u2717 ${m.label}`));else if(m.type==="run_done"){h=m.aborted,console.log("");let w=process.env.ANTHROPIC_API_KEY?"api":"subscription",x=wa(e.cwd,i,e.profileName),S=!m.aborted&&(!!m.blocked||!!m.allEmpty||i.length>0&&x===0);for(let R of ka(m.results,d,w,l?0:n,{recorded:x,...m.blocked?{blocked:m.blocked}:{},...m.allEmpty?{allEmpty:!0}:{}}))console.log(m.ok&&!S?U(R):W(R));if(S)continue;let $=ga(e.cwd,e.profileName);$&&console.log(k($));try{let R=Wd(await Ud({cwd:e.cwd,profileName:e.profileName,onRateLimit:I=>console.log(k(` Document360 rate limit \u2014 waiting ${Math.ceil(I.waitMs/1e3)}s\u2026`))}));R&&console.log(R.startsWith("\u26A0")?W(R):k(R))}catch{}try{let R=Bd(await Fd({cwd:e.cwd,profileName:e.profileName}));R&&console.log(k(R))}catch{}let T=await Fn(e.cwd,e.profileName);T&&console.log(k(T))}return h};try{if(!await s(t,!1)){let l=await ba(e.cwd,e.profileName,t);l.length>0&&await s(l,!0)}}catch(i){console.log(j(`Publish run failed: ${i.message}`))}return console.log(""),{kind:"continue"}}async function hs(e,t,n){let o=Ky(e,n);if(o.length===0)return[];let r=new Set(ma((await us({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function ba(e,t,n){try{let o=new Set(n),r=await us({cwd:e,profileName:t});return ma(r.entries).map(s=>s.path).filter(s=>o.has(s))}catch{return[]}}async function qd(e,t){let n=Fe(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log(j(n.reason)),{kind:"continue"};let o=e.includes(pt),r=e[0];if(e.includes("--screenshots")||e.includes("--shots")){let s=t?.cwd??process.cwd(),i=Pe(s),l=ss(i);if(l.length===0)return console.log(k("No captured screenshots yet \u2014 /screenshot capture first.")),{kind:"continue"};let d=is(i);return d&&console.log(d),t?await dt(t,l,0,{skipReview:o}):{kind:"forward-to-agent",prompt:Io(l),display:"/publish --screenshots"}}if(r==="--related"&&e[1]){if(!t)return{kind:"continue"};let s=await hs(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return s.length===0?(console.log(U("\u2713 All related articles are already published.")),{kind:"continue"}):await dt(t,s,0,{skipReview:o})}if(r==="--all"){console.log(k("Checking what needs publishing\u2026"));try{let s=await us({cwd:t?.cwd??process.cwd()}),{clean:i,conflicts:l}=cn(s.entries),d=ds(s.entries),h=e.includes("--force")&&l.length>0;d>0&&console.log(W(`\u26A0 ${d} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),l.length>0&&!h&&console.log(W(ln(l.length)));let m=h?[...i,...l]:i;if(m.length===0){if(l.length>0)return console.log(k("Resolve the conflicts: /resolve")),{kind:"continue"};if(console.log(U(d>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),t)try{let w=Wd(await Ud({cwd:t.cwd,profileName:t.profileName,onRateLimit:S=>console.log(k(` Document360 rate limit \u2014 waiting ${Math.ceil(S.waitMs/1e3)}s\u2026`))}));w&&console.log(w.startsWith("\u26A0")?W(w):k(w));let x=Bd(await Fd({cwd:t.cwd,profileName:t.profileName}));x&&console.log(k(x))}catch{}return{kind:"continue"}}return t?await dt(t,m.map(w=>w.path),h?0:l.length,{skipReview:o}):{kind:"forward-to-agent",prompt:Io(m.map(w=>w.path)),display:"/publish --all"}}catch(s){return console.log(j(`Could not compute sync status: ${s.message}`)),{kind:"continue"}}}if(r&&r.startsWith("--")&&(r=e.find(s=>!s.startsWith("--"))??""),!r){console.log(k("Checking what needs publishing\u2026"));let s,i=0;try{let l=await us({cwd:t?.cwd??process.cwd()}),{clean:d,conflicts:h}=cn(l.entries);s=d,i=h.length;let m=ds(l.entries);if(m>0&&console.log(W(`\u26A0 ${m} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),h.length>0&&console.log(W(ln(h.length))),s.length===0&&h.length>0)return console.log(k("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(l){return console.log(j(`Could not compute sync status: ${l.message}`)),console.log(k("Publish a specific article: /publish <article-path>")),{kind:"continue"}}if(s.length===0)return console.log(U("\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),console.log(k(" (Articles without a sync base are unverified \u2014 publish those by path if needed.)")),{kind:"continue"};if(!process.stdin.isTTY||!t){for(let l of s)console.log(` ${l.path} ${k(`(${l.label})`)}`);return console.log(k("Run: /publish <article-path>")),{kind:"continue"}}try{r=await t.withPausedInput(()=>Vy({message:"Publish which article?",choices:[...s.length>1?[{name:`All ${s.length} candidates`,value:"--all",description:"one agent run over every candidate"}]:[],...s.map(l=>({name:l.path,value:l.path,description:l.label}))]}))}catch{return console.log(k("Cancelled.")),{kind:"continue"}}if(r==="--all")return await dt(t,s.map(l=>l.path),i,{skipReview:o})}return{kind:"forward-to-agent",prompt:fa(r),display:`/publish ${r}`}}async function Lo(){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 and what to do about them, in plain words, never the internal status word.","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 (sources exist, commit is an ancestor of HEAD, source shows the surface) before trusting; fold verified ones into the table, flag the rest.","3. Map changes (diff + hints) to articles via their `sources:` frontmatter; read only implicated articles and changed source files. If articles are missing `sources:`, this is the one-time bootstrap pass, so backfill them.","4. Output the proposal table: | Article (path or proposed title) | Action (create | update | retire | link) | Reason | Evidence | Scope |, then advance lastAnalyzedCommit and stamp consumed hints.","","Do not start writing or updating any article yet; the proposal table is the deliverable."].join(`
|
|
351
|
+
`),display:"/audit"}}Q();import{readProjectConfig as ow}from"document360-engine";function $a(){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(`
|
|
352
|
+
`)}async function Gd(e,t){let n=t?.cwd??process.cwd();return ow(n)?{kind:"forward-to-agent",prompt:$a(),display:"/discover"}:(console.log(j("No d360-writer config here. Run /init first.")),{kind:"continue"})}Q();import{checkbox as rw}from"@inquirer/prompts";import{inventoryRepo as sw,readProjectConfig as Vd,writeProjectConfig as iw}from"document360-engine";function va(e,t){let n=Vd(e);n&&(n.authoritativeSourceFiles=t,iw(n,e))}function fs(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 Yd(e,t){let n=t?.cwd??process.cwd();if(!Vd(n))return console.log(j("No .d360-writer/config.json here. Run /init first.")),{kind:"continue"};let o=sw(n);if(o.length===0)return console.log(k('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(G("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${k(fs(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>rw({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${fs(s)})`,value:s.path,checked:s.recommended})),pageSize:20}))}catch{return console.log(k("Cancelled.")),{kind:"continue"}}if(r.length===0)return console.log(k("Nothing selected \u2014 scope unchanged.")),{kind:"continue"};va(n,r),console.log(U(`\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"}}Q();import{confirm as fw}from"@inquirer/prompts";import{applyPull as Ca,computeSyncStatus as op,compareRemoteSources as mw,planPull as rp,planImport as gw,applyImport as yw,establishBaselines as ww,rebaselineServerMeta as kw,D360AuthError as bw}from"document360-engine";Q();var Kd=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /publish <path>):",paint:j,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /publish <path>:",paint:W,mark:"M"},{status:"remote-ahead",header:"Changed on Document360 \u2014 pull with /pull <path> (or just /pull):",paint:G,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:j,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:j,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint:he,mark:"X"},{status:"untracked-local",header:"New here \u2014 not on Document360 yet (publish to add them):",paint:k,mark:"?"},{status:"untracked-remote",header:"On Document360 \u2014 not in your local docs yet (run /pull to import them):",paint:k,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:he,mark:"\xB7"}];function aw(e){return e.path?e.path:`${e.title??"(untitled)"} ${he(`[${e.articleId}]`)}`}function lw(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 ms(e,t){let n=[],o=e.entries.filter(m=>m.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 m of o)n.push(` ${W("~")} ${W(m.path??"")} ${he(`\u2192 "${m.link.title}"`)}`)}for(let m of Kd){let w=e.entries.filter(x=>x.status===m.status&&!(m.status==="untracked-local"&&x.link));if(w.length!==0){n.push(""),n.push(je(m.header));for(let x of w)n.push(` ${m.paint(m.mark)} ${m.paint(aw(x))}${x.detail?he(` (${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"},l=o.length,d=s===r?U("\u2713 everything up to date"):[r>0?U(`\u2713 ${r} up to date`):null,l>0?`${l} to link`:null,...Kd.map(m=>{let w=(e.counts[m.status]??0)-(m.status==="untracked-local"?l:0);return w>0?`${w} ${i[m.status]}`:null})].filter(Boolean).join(he(" \xB7 ")),h=t!==void 0?` \xB7 synced in ${lw(t)}`:"";return n.push(d+he(` \xB7 ${s} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${h}`)),n}import{structuredPatch as cw}from"diff";import zd from"picocolors";var Xd=80,uw="\x1B[48;2;74;28;28m",dw="\x1B[48;2;24;66;24m",Qd="\x1B[49m",xa=e=>String(e).padStart(5);function Jd(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}function Zd(e,t,n){if(n===void 0||n<t-4)return e.slice(0,t);let o=Math.max(0,n-12);return`\u2026${e.slice(o).slice(0,Math.max(8,t-1))}`}function Ke(e,t,n){let o=x=>{let S=x.replace(/\r\n/g,`
|
|
353
|
+
`);return S.endsWith(`
|
|
354
|
+
`)||S===""?S:S+`
|
|
355
|
+
`},r=o(e),s=o(t);if(r===s)return null;let i=Math.max(20,n-10),l=cw("a","b",r,s,"","",{context:3}),d=0,h=0,m=[];l.hunks.forEach((x,S)=>{S>0&&m.push(zd.gray(" \u2026"));let $=x.oldStart,T=x.newStart,R=[],I=[],Y=()=>{for(let q=0;q<R.length;q++){let z=q<I.length?Jd(R[q],I[q]):void 0;h++,m.push(`${uw}${xa($++)} - ${Zd(R[q],i,z)}${Qd}`)}for(let q=0;q<I.length;q++){let z=q<R.length?Jd(R[q],I[q]):void 0;d++,m.push(`${dw}${xa(T++)} + ${Zd(I[q],i,z)}${Qd}`)}R=[],I=[]};for(let q of x.lines){let z=q[0],ae=q.slice(1);z==="-"?R.push(ae):z==="+"?I.push(ae):(Y(),m.push(zd.gray(xa(T))+" "+ae.slice(0,i)),$++,T++)}Y()});let w=m.slice(0,Xd);return{added:d,removed:h,lines:w,hidden:Math.max(0,m.length-Xd)}}Q();import{select as pw}from"@inquirer/prompts";import{applyPull as tp,computeSyncStatus as hw,planPull as ep}from"document360-engine";var gs=e=>e===1?"":"s";async function Ra(e,t,n=1){console.log(""),console.log(`${G("\u25CF")} ${je(t.title)} ${he(`(${t.path})`)}`);for(let i of t.notes)console.log(W(` \u26A0 ${i}`));let o=Ke(t.oldContent,t.newContent,Math.max(40,(process.stdout.columns??80)-1));if(o){console.log(he(` \u23BF local \u2192 portal: +${o.added} / -${o.removed} line${gs(o.added+o.removed)}`));for(let i of o.lines)console.log(i);o.hidden>0&&console.log(k(` \u2026 +${o.hidden} more diff lines`))}else console.log(k(" 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"?(tp({cwd:e.cwd,profileName:e.profileName},t),console.log(U(" \u2713 Took the portal copy (local overwritten, sync base advanced).")),"took-portal"):s==="local"?"keep-local":s==="skip"?(console.log(k(" Skipped \u2014 still a conflict.")),"skipped"):s==="local-all"?"keep-local-all":s==="portal-all"?"took-portal-all":"skipped-all"}async function np(e,t){let n=Fe(t.cwd,t.profileName);if(!n.ok)return console.log(j(n.reason)),{kind:"continue"};let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let s=(await hw({cwd:t.cwd,profileName:t.profileName})).entries.filter(l=>l.status==="conflict"&&l.path).map(l=>l.path);if(o){if(!s.includes(o))return console.log(U(`${o} isn't in conflict \u2014 nothing to resolve.`)),{kind:"continue"};s=[o]}if(s.length===0)return console.log(U("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let i=[];for(let[l,d]of s.entries()){let h=await ep({cwd:t.cwd,profileName:t.profileName,relPath:d}),m=await Ra(t,h,s.length-l);if(m==="keep-local"&&i.push(d),!m.endsWith("-all"))continue;let w=s.slice(l);if(m==="keep-local-all")i.push(...w),console.log(k(` Keeping local for all ${w.length} \u2014 publishing them over the portal.`));else if(m==="took-portal-all"){let x=0;for(let S of w)try{tp({cwd:t.cwd,profileName:t.profileName},await ep({cwd:t.cwd,profileName:t.profileName,relPath:S})),x++}catch($){console.log(j(` \u2717 ${S}: ${$.message}`))}console.log(U(` \u2713 Took the portal copy of ${x} article${gs(x)} (local overwritten, sync base advanced).`))}else console.log(k(` Skipped all ${w.length} \u2014 still conflict${gs(w.length)}.`));break}if(i.length>0)return console.log(k(`Publishing ${i.length} kept-local article${gs(i.length)} over the portal\u2026`)),await dt(t,i)}catch(r){console.log(j(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function sp(e,t){let n=Fe(t.cwd,t.profileName);if(!n.ok)return console.log(j(n.reason)),{kind:"continue"};let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await $w(t),{kind:"continue"};if(o==="--baseline")return await vw(t,e.filter(i=>i!=="--baseline")),{kind:"continue"};if(o==="--compare")return await xw(t),{kind:"continue"};if(o)return console.log(j(`Unknown option: ${o}`)),console.log(k("Usage: /pull pull portal edits + import new portal articles")),console.log(k(" /pull <path> pull one article (or resolve a conflict)")),console.log(k(" /pull --status drift report only (no writes)")),console.log(k(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await Rw(t,r),{kind:"continue"};console.log(k("Pulling changes from Document360\u2026"));let s=await Sa({cwd:t.cwd,profileName:t.profileName});for(let i of Pa(s))console.log(i.tone==="ok"?U(i.text):i.tone==="warn"?W(i.text):k(i.text));console.log("")}catch(r){r instanceof bw?console.log(j(r.message)):console.log(j(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function Sa(e){let t=await op({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 rp({cwd:e.cwd,profileName:e.profileName,relPath:o.path});Ca({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 gw({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId});yw({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 ys=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,dn=e=>e===1?"":"s";function Pa(e){let t=[];return e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${dn(e.pulled.length)} into local: ${ys(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${dn(e.imported.length)}: ${ys(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${dn(e.toPublish)} changed locally \u2014 /publish to push them up.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${dn(e.conflicts.length)} changed both here and on Document360 \u2014 left untouched. Resolve them: /resolve (or /publish <path> to keep yours, /pull <path> to take the portal's). (${ys(e.conflicts)})`}),e.failed.length&&t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${dn(e.failed.length)} failed: ${ys(e.failed.map(n=>n.ref))}`}),t.length===0&&t.push({tone:"ok",text:"\u2713 Already in sync with Document360 \u2014 nothing to pull."}),t}async function $w(e){console.log(k("Checking Document360 for drift\u2026"));let t=Date.now(),n=await op({cwd:e.cwd,profileName:e.profileName});for(let o of ms(n,Date.now()-t))console.log(o);console.log("")}async function vw(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(k(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await ww({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await kw({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(U("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(U(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(U(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(W(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(k(` - ${s.path} (${s.reason})`))}}async function xw(e){console.log(k("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await mw({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(U("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(j(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(W(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(W(` ${t.onlyInManifest.length} only in the manifest: ${t.onlyInManifest.slice(0,5).join(", ")}`)),console.log(k(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function Rw(e,t){let n=t.replace(/\\/g,"/"),o=await rp({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await Ra(e,o)==="keep-local"&&(console.log(k(`Publishing ${o.path} over the portal\u2026`)),await dt(e,[o.path]));return}console.log(""),console.log(`${G("\u25CF")} ${je(o.title)} ${he(`(${o.path})`)}`);for(let i of o.notes)console.log(W(` \u26A0 ${i}`));let r=Ke(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!r){console.log(k(" Local file already matches the remote content \u2014 advancing the sync base only.")),Ca({cwd:e.cwd,profileName:e.profileName},o);return}console.log(he(` \u23BF Added ${r.added} line${dn(r.added)}, removed ${r.removed} line${dn(r.removed)}`));for(let i of r.lines)console.log(i);if(r.hidden>0&&console.log(k(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>fw({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(k(" Skipped."));return}Ca({cwd:e.cwd,profileName:e.profileName},o),console.log(U(` \u2713 Pulled ${o.path} (sync base advanced).`))}Q();import{statSync as Cw}from"node:fs";import{resolve as Sw}from"node:path";import{estimateBulkCost as Pw,planPartitions as Tw,readProjectConfig as Ew,resolveModelForOperation as Aw,runPartitioned as Dw,trackedArticlePaths as jw}from"document360-engine";var Ta=3;function Ea(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 Aa(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Da(e,t){return t.map(n=>{let o=0;try{o=Cw(Sw(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function ja(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:
|
|
356
|
+
- 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.
|
|
357
357
|
- 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.
|
|
358
358
|
- 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.
|
|
359
359
|
- Work only on these files:
|
|
360
360
|
`+e.paths.map(t=>`- ${t}`).join(`
|
|
361
|
-
`)}function
|
|
361
|
+
`)}function Na(e,t,n){let o=e.reduce((l,d)=>l+d.paths.length,0),[r,s]=t.usd;return[`Convert ${o} article${o===1?"":"s"} to DFM across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(l=>` \u2022 ${l.label} \u2014 ${l.paths.length} article${l.paths.length===1?"":"s"}`),"",`Estimated cost: ${We(r)}\u2013${We(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function Ia(e,t,n){let o=$=>t[$.index]?.paths.length??0,r=e.filter($=>$.ok),s=e.filter($=>!$.ok),i=e.reduce(($,T)=>$+o(T),0),l=r.reduce(($,T)=>$+o(T),0),d=e.reduce(($,T)=>$+T.costUsd,0),h=e.reduce(($,T)=>$+T.outputTokens,0),m=n==="api"?`${We(d)} total`:_t(h),w=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,x=$=>`${$} article${$===1?"":"s"}`,S=[];if(s.length===0)S.push(`Converted ${x(i)} (${w}) successfully \xB7 ${m}.`);else{S.push(`Converted ${l}/${x(i)} (${w}) \xB7 ${m}.`),S.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let $ of s)S.push(` \u2717 ${$.label}${$.error?` \u2014 ${$.error}`:""}`)}return S}async function ip(e,t){if(!Ew(t.cwd))return console.log(j("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=Ea(e),r=jw(t.cwd,t.profileName);if(r.length===0)return console.log(j("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let s=Aa(r,n);if(s.length===0)return console.log(j(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let i=Tw(s),l=`/convert${n?` --scope ${n}`:""} --run`,{model:d,forced:h}=Aw(t.cwd,"light");if(!o){let m=Pw({files:Da(t.cwd,s),op:"convert",model:d});n&&console.log(k(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let w of Na(i,m,Ta))console.log(w);return console.log(k(`Model: ${d}${h?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(k(`Run ${l} to start.`)),console.log(""),{kind:"continue"}}console.log(k(`Converting ${s.length} articles across ${i.length} partitions (\u2264${Ta} agents at once) on ${d}\u2026`)),console.log(k(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let m of Dw({cwd:t.cwd,partitions:i,promptFor:ja,concurrency:Ta,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:d}))if(m.type==="partition_status")m.status==="running"?console.log(k(` \u25B8 ${m.label} \u2014 converting\u2026`)):m.status==="done"?console.log(U(` \u2713 ${m.label}`)):console.log(j(` \u2717 ${m.label}`));else if(m.type==="run_done"){console.log("");let w=process.env.ANTHROPIC_API_KEY?"api":"subscription",x=ut(m,"The conversion");for(let S of x??Ia(m.results,i,w))console.log(x||!m.ok?W(S):U(S))}}catch(m){console.log(j(`Convert run failed: ${m.message}`))}return console.log(""),{kind:"continue"}}Q();import{statSync as up}from"node:fs";import{resolve as dp}from"node:path";import{estimateBulkCost as Fw,lintDocs as Bw,planPartitions as Hw,readDocsPlan as qw,readProjectConfig as pp,DEFAULT_DOCS_DIR as Gw,resolveModelForOperation as Vw,runPartitioned as Yw,stampArticles as Kw,CONTENT_CAP_VERSION as zw}from"document360-engine";import{readProjectConfig as Nw,loadProfileMap as Iw,resolveActiveProfile as Ow,desiredCategoryOrder as Lw,desiredArticleOrder as _w,DEFAULT_DOCS_DIR as Mw}from"document360-engine";var Oa=e=>e.replace(/\\/g,"/"),ap=e=>Oa(e).split("/").pop()??e;function La(e){let t=ap(e),n=t.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return n?n.charAt(0).toUpperCase()+n.slice(1):t}var Uw=La;function _o(e,t){try{let n=Nw(e);if(!n)return[];let o=Ow(e,t),r=Iw(e,o.name);if(!r)return[];let s=Oa(n.docsDir??Mw).replace(/\/+$/,""),i=new Map;for(let d of _w(r))i.set(d.categoryPath,(i.get(d.categoryPath)??0)+1);let l=[];for(let d of Lw(r)){let h=Oa(d.path),m=h.startsWith(`${s}/`)?h.slice(s.length+1):h===s?"":h;m&&l.push({token:m,label:Uw(ap(h)),count:i.get(d.path)??0})}return l}catch{return[]}}function lp(e,t){let n=_o(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 Wt(e,t){if(t.includes("--all")||t.some(n=>n.startsWith("--scope="))||t.includes("--scope")&&!Mo(t))return!1;for(let n=0;n<t.length;n++){let o=t[n];if(o.startsWith("--")){Ww.has(o)&&n++;continue}return!1}return e==="write"?!t.includes("--preview")&&!t.includes("--dry-run"):e==="review"||e==="reorder"}var Ww=new Set(["--scope","--concurrency"]);function Bn(e,t,n,o,r){if(r=r??_o(e,o),r.length<=1)return[];let s=n.filter(h=>h.startsWith("--")).join(" "),i=s?` ${s}`:"",l=`/${t}${i} --all`.replace(/\s+/g," "),d=h=>t==="write"?`/write --scope ${h}${i}`:`/${t} ${h}${i}`;return[`Bare /${t} covers the WHOLE knowledge base (${r.reduce((h,m)=>h+m.count,0)} articles). Pick a target:`,` ${l} (everything)`,...r.map(h=>` ${d(h.token)} (${h.label} \xB7 ${h.count} article${h.count===1?"":"s"})`)]}function Mo(e){let t=e.indexOf("--scope");if(t===-1)return!1;let n=e[t+1];return n===void 0||n.startsWith("-")}function cp(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 Xw=3,Qw=8;function _a(e){return e===void 0||!Number.isFinite(e)?Xw:Math.max(1,Math.min(Math.floor(e),Qw))}function Uo(e){let t,n,o=!1,r=!1,s,i=d=>{let h=Number(d);return d!==void 0&&Number.isFinite(h)?h:void 0};for(let d=0;d<e.length;d++){let h=e[d];if(h==="--preview"||h==="--dry-run")o=!0;else if(h==="--rewrite"||h==="--force")r=!0;else{if(h==="--run"||h==="--yes"||h==="--all")continue;h==="--scope"?t=e[++d]:h?.startsWith("--scope=")?t=h.slice(8):h==="--concurrency"?s=i(e[++d]):h?.startsWith("--concurrency=")?s=i(h.slice(14)):h&&!h.startsWith("--")&&(n=h)}}let l=d=>d?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:l(t),path:l(n),preview:o,concurrency:s,rewrite:r}}function Jw(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function Zw(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Ma(e,t,n){return n.filter(o=>{try{return up(dp(e,t,o)).size===0}catch{return!0}})}function Ua(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+=up(dp(e,i)).size}catch{}return{path:r,bytes:s}})}function Wa(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.
|
|
362
362
|
`:"";return`Run the write-article skill to author EACH documentation article listed below. For each path:
|
|
363
363
|
- It is relative to ${t}/. Look up its entry (matching "path") in .d360-writer/plan.json for its purpose, its \`type\` (concept | task | reference | faq | tutorial | troubleshooting | best-practices | use-case; missing \u21D2 task), and the source files it draws from (AGENT-PLAN.md has the same table).
|
|
364
364
|
- Use the skeleton for that \`type\` (see write-article): a \`concept\`/overview page opens with what the product IS + its mental model and takes NO Prerequisites/Steps; only a \`task\` or \`tutorial\` page gets numbered steps (a tutorial ends every stage with a visible checkpoint); a \`troubleshooting\` page is symptom \u2192 cause \u2192 fix. Titles follow the type grammar (task: "How to <verb> <object>"; concept: "Understanding <X>"; troubleshooting: the symptom the user sees).
|
|
365
|
-
- Read ONLY those source files plus any shared context you genuinely need, and ground every statement in them. Never invent UI labels, routes, or behaviour
|
|
365
|
+
- Read ONLY those source files plus any shared context you genuinely need, and ground every statement in them. Never invent UI labels, routes, or behaviour; if the source does not say it, omit it.
|
|
366
366
|
`+o+`- Write the finished article to ${t}/<path>, following the write-article structure and the project terminologyGlossary. Add the \`sources:\` frontmatter listing the files you actually read.
|
|
367
367
|
- Emit \`<!-- SCREENSHOT -->\` placeholders where a visual helps, but do NOT author capture specs now.
|
|
368
|
-
- Each article is independent. Do NOT write, edit, or publish any article not in this list, and do NOT publish to Document360
|
|
368
|
+
- 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.
|
|
369
369
|
Articles:
|
|
370
370
|
`+e.paths.map(r=>`- ${r}`).join(`
|
|
371
|
-
`)}function
|
|
372
|
-
`)}var
|
|
373
|
-
`)}var
|
|
371
|
+
`)}function Fa(e,t,n){let o=e.reduce((i,l)=>i+l.paths.length,0),[r,s]=t.usd;return[`Write ${o} article${o===1?"":"s"} across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(i=>` \u2022 ${i.label} \u2014 ${i.paths.length} article${i.paths.length===1?"":"s"}`),"",`Estimated cost: ${We(r)}\u2013${We(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function Ba(e,t,n){let o=$=>t[$.index]?.paths.length??0,r=e.filter($=>$.ok),s=e.filter($=>!$.ok),i=e.reduce(($,T)=>$+o(T),0),l=r.reduce(($,T)=>$+o(T),0),d=e.reduce(($,T)=>$+T.costUsd,0),h=e.reduce(($,T)=>$+T.outputTokens,0),m=n==="api"?`${We(d)} total`:_t(h),w=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,x=$=>`${$} article${$===1?"":"s"}`,S=[];if(s.length===0)S.push(`Wrote ${x(i)} (${w}) successfully \xB7 ${m}.`),S.push("Next \u2014 an editorial review, because these were written by an AI:"),S.push("/review --fix"),S.push("It reads every article and applies its fixes; /publish --all then pushes them up (add screenshots first with /screenshot author --all if you want them).");else{S.push(`Wrote ${l}/${x(i)} (${w}) \xB7 ${m}.`),S.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let $ of s)S.push(` \u2717 ${$.label}${$.error?` \u2014 ${$.error}`:""}`)}return S}function Ha(e,t,n){try{let o=Bw({cwd:e,paths:n.map(s=>`${t}/${s}`)});if(o.length===0)return null;let r=new Set(o.map(s=>s.path)).size;return`\u26A0 Doc-checker: ${o.length} issue${o.length===1?"":"s"} in ${r} of the new article${r===1?"":"s"} (leaked internals / unknown commands / stale facts / AI-tells / em dashes) \u2014 /check --fix corrects them.`}catch{return null}}function ws(e,t,n){let o=(pp(e)?.docsDir??Gw).replace(/\/+$/,""),r=t.map(l=>l.path);if(n.path){let l=Jw(n.path,o);return r.includes(l)?{docsDir:o,targets:[l],planCount:r.length}:{docsDir:o,targets:[],planCount:r.length,reason:`"${l}" isn't in the docs plan (.d360-writer/plan.json).`}}let s=Zw(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=Ma(e,o,s);if(i.length===0){let l=n.scope?` under "${n.scope}"`:"",d=n.scope?` --scope ${n.scope}`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${l} are already written. Use /write <path> to rewrite one, or /write${d} --rewrite to regenerate them all.`}}return{docsDir:o,targets:i,planCount:r.length}}function qa(e,t,n){let{targets:o}=ws(e,t,{rewrite:n?.rewrite}),r=new Map;for(let s of o){let i=s.split("/");if(i.length<2)continue;let l=i[0];r.set(l,(r.get(l)??0)+1)}return[...r].map(([s,i])=>({token:s,label:La(s),count:i}))}async function hp(e,t){if(!pp(t.cwd))return console.log(j("No d360-writer config here. Run /init first.")),{kind:"continue"};if(Mo(e)){for(let I of lp(t.cwd,t.profileName))console.log(k(I));return{kind:"continue"}}let n=qw(t.cwd);if(n.length===0)return console.log(j("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};if(Wt("write",e)){let I=qa(t.cwd,n,{rewrite:Uo(e).rewrite}),Y=Bn(t.cwd,"write",e,t.profileName,I);if(Y.length>0){for(let q of Y)console.log(k(q));return{kind:"continue"}}}let{scope:o,path:r,preview:s,concurrency:i,rewrite:l}=Uo(e),{docsDir:d,targets:h,reason:m,rewriting:w}=ws(t.cwd,n,{scope:o,path:r,rewrite:l});if(h.length===0)return console.log(m?W(m):W("Nothing to write.")),{kind:"continue"};w&&console.log(W(`--rewrite: regenerating ${h.length} already-written article${h.length===1?"":"s"} (overwrites them; git has your baseline).`));let x=Hw(h),S=_a(i),{model:$,forced:T}=Vw(t.cwd,"standard"),R=!!r;if(s&&!R){let I=Fw({files:Ua(t.cwd,n,h),op:"write",model:$});o&&console.log(k(`Scope: ${o} (${h.length} pending).`));for(let Y of Fa(x,I,S))console.log(Y);return console.log(k(`Model: ${$}${T?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(k(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}console.log(k(`Writing ${h.length} article${h.length===1?"":"s"} across ${x.length} partition${x.length===1?"":"s"} (\u2264${S} agents at once) on ${$}\u2026`)),console.log(k(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let I of Yw({cwd:t.cwd,partitions:x,promptFor:Y=>Wa(Y,d,{rewrite:w||R}),concurrency:S,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:$}))if(I.type==="partition_status")I.status==="running"?console.log(k(` \u25B8 ${I.label} \u2014 writing\u2026`)):I.status==="done"?console.log(U(` \u2713 ${I.label}`)):console.log(j(` \u2717 ${I.label}`));else if(I.type==="run_done"){console.log("");let Y=process.env.ANTHROPIC_API_KEY?"api":"subscription",q=ut(I,"The write");if(q){for(let ae of q)console.log(W(ae));continue}for(let ae of Ba(I.results,x,Y))console.log(I.ok?U(ae):W(ae));if(I.ok)try{Kw(t.cwd,h.map(ae=>`${d}/${ae}`),{writtenCap:zw,reviewedCap:0,checkedCap:0})}catch{}let z=Ha(t.cwd,d,h);z&&console.log(W(z))}}catch(I){console.log(j(`Write run failed: ${I.message}`))}return console.log(""),{kind:"continue"}}Q();import{existsSync as ek,readdirSync as fp,statSync as mp}from"node:fs";import{join as gp}from"node:path";import{inputDir as tk,readProjectConfig as nk}from"document360-engine";var yp=/\.(md|markdown|pdf|txt)$/i;function Ga(e){let t=tk(e);if(!ek(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of fp(t)){let s=gp(t,r),i=!1;try{i=mp(s).isDirectory()}catch{continue}if(i){if(r.startsWith("."))continue;let l=ok(s);l>0&&n.push({name:r,docCount:l})}else yp.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function ok(e){let t=0;for(let n of fp(e))try{mp(gp(e,n)).isFile()&&yp.test(n)&&t++}catch{}return t}function Va(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 ks(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(`
|
|
372
|
+
`)}var Ya="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function wp(e,t){let n=t?.cwd??process.cwd();if(!nk(n))return console.log(j("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=Ga(n);if(o.length===0&&r===0)return console.log(k(Ya)),{kind:"continue"};let s=e.join(" ").trim();if(!s){if(o.length>1){console.log(k("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let d of o)console.log(` ${d.name} ${k(`(${d.docCount} doc${d.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let l=o[0]?.name??"";return{kind:"forward-to-agent",prompt:ks(l),display:l?`/draft ${l}`:"/draft"}}let i=Va(o,s);return{kind:"forward-to-agent",prompt:ks(i??"",i?void 0:s),display:`/draft ${s}`}}Q();import{listOpenForDocs as rk,readProjectConfig as sk}from"document360-engine";function Ka(e){try{return rk(e).filter(t=>t.kind==="request").length}catch{return 0}}function za(e){let t=e.includes("--publish"),n=e.includes(pt),o=e.filter(r=>!r.startsWith("--")).join(" ").trim();return{publish:t,skipReview:n,what:o}}function Xa(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(`
|
|
373
|
+
`)}var Qa="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 kp(e,t){let n=t?.cwd??process.cwd();if(!sk(n))return console.log(j("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=za(e);if(!r&&Ka(n)===0)return console.log(k(Qa)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:Xa(r),display:s}}Q();import{search as ik}from"@inquirer/prompts";import{findByName as ak,getSession as lk,listSessions as ck,relativeTime as $p}from"document360-engine";async function vp(e,t){let n=ck(t.cwd).filter(o=>o.uuid!==t.currentUuid());if(n.length===0)return console.log(k("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=ak(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(j(`No session matches "${o}".`)),bp(n),{kind:"continue"})}if(!process.stdin.isTTY)return bp(n),console.log(k("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>ik({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let i=(s??"").toLowerCase();return n.filter(l=>!i||l.name.toLowerCase().includes(i)||l.firstPrompt.toLowerCase().includes(i)).map(l=>({name:`${l.name} ${$p(l.updatedAt)}`,value:l.uuid,description:l.firstPrompt.slice(0,100)}))}})),r=lk(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function bp(e){console.log("");for(let t of e.slice(0,15))console.log(` ${G(t.name)} ${k($p(t.updatedAt))}`),console.log(` ${k(t.firstPrompt.slice(0,80))}`);console.log("")}Q();import{renameSession as uk}from"document360-engine";function Ja(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 xp(e,t){let n=Ja(e.join(" "));if(!n)return console.log(j("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(uk(o,n)?console.log(U(`\u2713 Session renamed to "${n}"`)):console.log(j("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(U(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}import{knownEnvironments as Rp,readProjectConfig as dk,writeProjectConfig as pk}from"document360-engine";Q();function Za(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=dk(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 Rp().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},pk(o,e),null):`Unknown environment "${r}". Known: ${Rp().join(", ")} (or add the profile with explicit URLs in .d360-writer/config.json).`}async function Cp(e,t){let n=e[0];if(!n)return Or(t.cwd),{kind:"continue"};if(n==="add"){let o=Za(t.cwd,e[1],e[2]);return o?(console.log(j(o)),{kind:"continue"}):(console.log(U(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${G(`/profile ${e[1]}`)} then ${G("/login")}`),console.log(k(" Until you switch, this repo keeps using the current profile\u2019s environment.")),{kind:"continue"})}return Lr(t.cwd,n),_r(t.cwd,n),console.log(k(" Restarting agent for the new profile\u2026")),{kind:"clear"}}Q();import{select as hk}from"@inquirer/prompts";import{readProjectConfig as fk,readUserConfig as Sp,resolveModelSetting as el,writeUserConfig as Pp}from"document360-engine";var ht=[{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 bs(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=ht.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function mk(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 Wo(e,t){let n=()=>el(e).model;if(t==="default"){let s=Sp();return s.defaultModel?(delete s.defaultModel,Pp(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${el(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}}Pp({...Sp(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=fk(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 Tp(e,t){let n=e[0]?.trim();if(!n){let i=el(t.cwd);if(!process.stdin.isTTY)return console.log(`${je("Model:")} ${G(i.model)}${i.source==="auto"?k(" (auto)"):""}`),console.log(k(` source: ${mk(i)}`)),console.log(k(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let l=bs(i),d;try{d=await t.withPausedInput(()=>hk({message:`Select model (current: ${i.model}${i.source==="auto"?" \xB7 auto":""})`,default:ht[l].value,choices:ht.map((x,S)=>({name:`${x.label}${S===l?" \u2714":""}`,value:x.value,description:x.desc}))}))}catch{return console.log(k("Cancelled.")),{kind:"continue"}}let{lines:h,changed:m,effective:w}=Wo(t.cwd,d??"default");for(let x of h)console.log(x.startsWith("\u26A0")?W(x):x.startsWith("\u2713")?U(x):k(x));return m&&await t.setModel(w),{kind:"continue"}}let{lines:o,changed:r,effective:s}=Wo(t.cwd,n);for(let i of o)console.log(i.startsWith("\u26A0")?W(i):i.startsWith("\u2713")?U(i):k(i));return r&&await t.setModel(s),{kind:"continue"}}$s();async function Ip(e,t){return await t.withPausedInput(()=>jn(t.cwd)),{kind:"clear"}}async function Op(e,t){return await t.withPausedInput(()=>Dr(t.cwd,t.profileName)),{kind:"clear"}}Q();import{resolveActiveProfile as Ik}from"document360-engine";async function Lp(e,t){let n=!1;try{n=Ik(t.cwd).production}catch{}return n?(console.log(W("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(k("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}Q();var _p=async(e,t)=>{try{await t.withPausedInput(()=>Ir({}))}catch(n){console.log(j(`Login failed: ${n.message}`))}return{kind:"continue"}};import{resolveActiveProfile as Ok,clearTokens as Lk,clearProfileProject as _k}from"document360-engine";Q();async function Mp(e,t){let n,o;try{let i=Ok(t.cwd,t.profileName);n=i.name,o=i.connection.name}catch(i){return console.log(j(i.message)),{kind:"continue"}}let r=Lk(n);_k(t.cwd,n),console.log(r?U(`\u2713 Signed out of "${n}" and cleared its project/workspace selection.`):k(`Profile "${n}" was not signed in. Cleared any project/workspace selection.`)),console.log(k(`Run /login to sign back in to "${n}" (the ${o} environment) and pick a project.`));let s=jt(t.cwd,t.profileName);return console.log(s?W(`\u26A0 ${s.why}. Signing out doesn\u2019t change the environment \u2014 ${s.cmd} does.`):k(" Different environment? That comes from the profile, not the login \u2014 /profile add <environment>.")),{kind:"continue"}}import{spawn as Wp}from"node:child_process";import{existsSync as ol,readFileSync as nl,statSync as Gk}from"node:fs";import{homedir as Vk}from"node:os";import{basename as Yk,join as Go}from"node:path";import{readProjectConfig as Kk,DEFAULT_OUTPUT_DIR as zk,existingAnnotatedShotPath as Xk,resolveOutputDir as Qk}from"document360-engine";import Be from"picocolors";import{annotationsPath as Mk,resolveOutputDir as Uk,readProjectConfig as Wk,DEFAULT_OUTPUT_DIR as Fk,existingAnnotatedShotPath as Bk}from"document360-engine";function Hk(e){let n=e.filter(o=>o!=="--all"&&o!=="-a").find(o=>!o.startsWith("-"));return n?{mode:"single",id:n}:{mode:"all"}}function Bo(e){return e.filter(t=>t.state==="captured").map(t=>t.id)}function pn(e,t){let n=Uk(e,Wk(e)?.outputDir??Fk),o=new Map(Pe(e).map(i=>[i.id,i])),r=i=>i.replace(`${e}\\`,"").replace(`${e}/`,"").replace(/\\/g,"/"),s=t.map(i=>{let l=o.get(i)?.file??"(unknown article)";return[`- ${i}`,` image: ${r(Bk(n,i))}`,` facts: ${r(Mk(n,i))}`,` article: ${l}`].join(`
|
|
374
374
|
`)}).join(`
|
|
375
|
-
`);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
|
|
376
|
-
`)}function
|
|
377
|
-
`)}function
|
|
378
|
-
`):
|
|
379
|
-
`)}var
|
|
380
|
-
`)}function
|
|
381
|
-
/screenshot list --detail shows what each one needs`}function
|
|
382
|
-
`),cmd:o.length>0?`/screenshot ${
|
|
383
|
-
`),display:"/screenshot checklist"}}var
|
|
384
|
-
`)}async function
|
|
385
|
-
`).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 $s(e,t){let n=Zp(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=sb(e);if(!o)return[{tone:"info",text:"Sharing: unavailable \u2014 this folder is not a git repository."}];if(!o.upstream)return[{tone:"warn",text:ne("\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:ne("\u26A0")+`${o.ahead} change${Bo(o.ahead)} not shared yet \u2014 run /share`}):s.push({tone:"ok",text:ne("\u2713")+"Everything is shared with your team."}),s}function ul(e,t,n){Jp({...t,gitHandoff:{commit:n,push:n}},e);let o=n?{tone:"ok",text:ne("\u2713")+"Sharing on \u2014 d360-writer will save and send its own work from now on."}:{tone:"ok",text:ne("\u2713")+"Sharing off \u2014 d360-writer will leave its work for your coding agent to commit."};return n?[o,...$s(e,{...t,gitHandoff:{commit:!0,push:!0}})]:[o]}async function vs(e,t){let n=[],o=Zp(t);if(!o.commit)return{lines:[{tone:"info",text:Ut("disabled")}],changed:!1};let r=t;o.push==="unconfirmed"&&ib(e,t)&&(r={...t,gitHandoff:{commit:!0,push:!0}},Jp(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 rb(e);if(s.ok&&s.pulled>0){let h=[s.newHints>0?`${s.newHints} new hint${Bo(s.newHints)}`:null,s.newMessages>0?`${s.newMessages} new message${Bo(s.newMessages)}`:null].filter(Boolean);n.push({tone:"ok",text:ne("\u2B07")+`Got your builder's latest${h.length?` \u2014 ${h.join(", ")}`:""}.`})}else!s.ok&&s.reason!=="no-upstream"&&s.reason!=="no-git"&&n.push({tone:"warn",text:ne("\u26A0")+Ut(s.reason,s.detail)});let i=await ob(e,r);if(i.commit&&!i.commit.ok)return n.push({tone:"warn",text:ne("\u26A0")+Ut(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:ne("\u2713")+`Saved ${a} change${Bo(a)} to the docs folder.`}),i.push&&!i.push.ok)return n.push({tone:"warn",text:ne("\u26A0")+Ut(i.push.reason,i.push.detail)}),{lines:n,changed:a>0};let d=i.push?.ok?i.push.pushed:0;return d>0?n.push({tone:"ok",text:ne("\u2B06")+`Shared ${d} change set${Bo(d)} with your team.`}):a===0&&(s.ok&&s.pulled===0)?n.push({tone:"ok",text:ne("\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||d>0||s.ok&&s.pulled>0}}var ab={ok:U,info:he,warn:W,error:j};async function eh(e,t){let n=t.cwd,o=nb(n);if(!o)return console.log(j("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase(),s=a=>{for(let d of a)console.log(ab[d.tone](d.text))};if(r==="status")return s($s(n,o)),{kind:"continue"};if(r==="on"||r==="off")return s(ul(n,o,r==="on")),{kind:"continue"};if(r)return console.log(j(`Unknown option "${r}". Use /share, /share status, /share on, or /share off.`)),{kind:"continue"};console.log(w("Exchanging work with your team\u2026"));let{lines:i}=await vs(n,o);return s(i),{kind:"continue"}}function cn(e){let t=0,n=0,o=0,r=0;try{t=lb(e).length}catch{}try{let s=cb(e);n=s.filter(i=>i.kind==="request").length,o=s.filter(i=>i.kind==="answer").length}catch{}try{r=ub(e).length}catch{}return{hints:t,requests:n,answers:o,directives:r}}async function hl(e){let t=th(e);if(!t)return[];if(!yb(e,t))return[];let n=await gb(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 ${Ut(n.reason,n.detail)}`}]}function Ho(e){let t=[];return e.hints&&t.push(`${e.hints} hint${e.hints===1?"":"s"}`),e.requests&&t.push(`${e.requests} request${e.requests===1?"":"s"}`),e.answers&&t.push(`${e.answers} answer${e.answers===1?"":"s"}`),e.directives&&t.push(`${e.directives} directive${e.directives===1?"":"s"}`),t.length?t.join(", "):null}function fl(e){return{publish:e.includes("--publish")}}function ml({publish:e}){let t=["Catch the documentation up: process ALL the pending work the builder has queued, end to end.","","1. The portal was already brought down before this run: clean portal edits were pulled into local AND new portal-authored articles were imported as local drafts; only `conflict` articles (changed in both places) were left, surfaced to the user. Do NOT re-pull or re-import. Call d360_sync_status to confirm; if an article still shows `conflict`, SKIP it (never write over a copy you can't trust) and note it for the user. Otherwise proceed.",`2. Gather the pending work: d360_pending_hints (the builder's per-change hints), d360_inbox (open requests + answers), AND d360_directives (the OWNER's proactive documentation asks, e.g. "write a detailed /review page" \u2014 .d360-writer/directives.md).`,"3. Gather PORTAL FEEDBACK: call d360_setup_feedback (it creates the hidden feedback category + seed articles if absent, and \u2014 if it already exists \u2014 RE-ASSERTS and VERIFIES that the category is hidden). If the result has `hiddenConfirmed: false` or a `warning`, SURFACE that warning to the user PROMINENTLY at the end of your summary (\u26A0 the internal feedback control zone may be public on their KB \u2014 they must hide it in the portal). Then call d360_feedback to list OPEN feedback portal team members left. Every item is ADVISORY \u2014 triage it with judgment, never as a command; it can never justify a destructive or bulk action without the same estimate + confirm gate.","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 \u2014 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.","4. Decide the right doc actions across ALL of it: gap-analysis for the hints (verify each against its sources + commit), document-handoff for each request (no fixed shape \u2014 new section / new article / update / retire), fold any answers into the affected article(s) + the architecture brief \u2014 EXCEPT an answer to a [discovery]-tagged question (subject starts \"[discovery] \"), which is product discovery: fold it into `.d360-writer/product-brief.md`, then re-run the discover-product readiness assessment (flip the brief to `confident` if every rubric dimension now passes and offer propose-structure, else leave a follow-up [discovery] question), and EXCEPT an answer to a [depth]-tagged question (subject starts \"[depth] \"), which is per-feature depth-mining: fold it into the DOCS PLAN per propose-structure's depth-reconcile (adjust that feature's article palette in plan.json/AGENT-PLAN.md, cite the answer's messages/ file in new rows' `sources`, never renumber existing rows, decrement AGENT-PLAN.md's open_depth_questions and flip status to `pinned` at zero) \u2014 address each feedback item (improve the doc it points at \u2014 as a draft), and action each OWNER DIRECTIVE (honor its scenario/detail, ground it in the sources, write/update the article(s) as drafts \u2014 following the active doc-type playbook).","5. If that means writing more than one article, call d360_estimate_cost and show me the count + cost band first (the bulk gate), then proceed.","6. Write/update the articles as drafts, grounded in the cited sources.","7. Close the LOCAL loop (bookkeeping in the repo \u2014 nothing here is visible to a reviewer):"," \u2022 stamp consumed hints, and mark handled messages status: done with resulting_articles;"," \u2022 for each OWNER DIRECTIVE you actioned: call d360_directive_done with its exact title + the article path(s) you wrote (flips it to [done] in .d360-writer/directives.md);"," \u2022 reconcile the DOCS ROADMAP (d360_roadmap): flip any campaign step this run completed (d360_roadmap_done) \u2014 including a step whose work you can verify an EARLIER session already completed but left unstamped \u2014 and append a step (d360_roadmap_add, with its run: command) for real new campaign work this run revealed \u2014 never delete existing steps;"," \u2022 for the Creator-notes feedback item (is_creator_notes:true): do NOT reply in it \u2014 fold its content into `.d360-writer/architecture/CREATOR-NOTES.md` as an appended, dated `## From portal Creator notes (<date>)` section (preserve every existing note + human edit), then call d360_feedback_done for it.","8. Push the drafts to Document360.","9. Cross-link second pass: any article you wrote that links to ANOTHER article in this same batch had that inline link degrade to plain text (its target had no live URL yet when the source was written). Now that every target exists, re-update the affected articles so those inline links resolve to live URLs \u2014 only the ones that had such forward references need it. (The structured Related Articles sidebars are already two-way linked; this is just inline body links.)","10. NOW answer the people who asked \u2014 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, and closing the thread takes away the one thing they could do about it (tell you it is still wrong). For anything whose push failed, do NOT reply or close it \u2014 leave it outstanding and report it."," \u2022 for each INLINE COMMENT you actioned: call d360_comment_respond with its comment_id + article_id \u2014 `reply` saying in plain words what you changed, plus `resolve: true` when the ask is fully handled; when it needs a decision only they can make (or you disagree), reply explaining or asking and OMIT resolve so the thread stays open for them. 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 \u2014 `**d360-writer response:** \u2713 actioned in <article> \u2014 <date>` (or `declined \u2014 <reason>`) \u2014 NEVER overwriting the person's own text \u2014 then call d360_feedback_done(article_id, resulting_articles)."];return t.push(e?"11. Then publish the new/updated articles live (publish-to-d360 skill), respecting the production write-guard.":"Leave everything as DRAFTS for review \u2014 do not publish live (run /publish when you want them live)."),t.push("","End with a one-line-per-item summary of what you wrote/updated, and anything you couldn't ground (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 \u2014 plain sentences about what changed and what is worth their attention."),t.join(`
|
|
386
|
-
`)}var
|
|
387
|
-
`)}function
|
|
388
|
-
`).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function
|
|
375
|
+
`);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(`
|
|
376
|
+
`)}function Ho(e){return`${ne("\u2192",Be.blue)}Verifying ${e} new screenshot${e===1?"":"s"} (reading each image)\u2026`}var qk=(e,t=88)=>{let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n};function qo(e,t){if(t.length===0)return[];let n=$t(e).shots,o=[],r=[],s=[];for(let l of t){let d=n[l]?.review;d?d.verdict==="ok"?o.push(l):r.push({id:l,reason:d.reason??"no reason recorded",repaired:!!d.repaired}):s.push(l)}let i=[""];if(i.push(`${ne("\u2714",Be.green)}${Be.green(`${o.length} verified`)}`+(r.length>0?` ${Be.magenta(`\u2691 ${r.length} flagged`)}`:"")+(s.length>0?` ${Be.yellow(`? ${s.length} not verified`)}`:"")+Be.gray(` ${t.length} shot${t.length===1?"":"s"} in this pass`)),r.length>0){let l=Math.max(...r.map(h=>h.id.length));for(let h of r)i.push(` ${Be.magenta(h.id.padEnd(l))} ${Be.gray(qk(h.reason))}`);let d=r.filter(h=>h.repaired).length;i.push(`${ne("\u2192",Be.magenta)}Re-capture the ${r.length} flagged: ${Be.bold("/screenshot capture --failed")}`+(d<r.length?Be.gray(` (${r.length-d} still need${r.length-d===1?"s":""} a spec fix first)`):""))}return s.length>0&&i.push(`${ne("\u26A0",Be.yellow)}No verdict recorded for ${s.slice(0,3).join(", ")}${s.length>3?`, +${s.length-3}`:""} \u2014 still awaiting verification. Run ${Be.bold("/screenshot verify")} again.`),i}async function Up(e,t){let n=t?.cwd??process.cwd(),o=Ao(n);o&&console.log(o);let r=Pe(n),s=Hk(e);if(s.mode==="single"){let l=r.find(d=>d.id===s.id);return l?["captured","verified","rejected"].includes(l.state)?{kind:"forward-to-agent",prompt:pn(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=Bo(r);if(i.length===0){let l=r.filter(h=>h.state==="verified").length,d=r.filter(h=>h.state==="rejected").length;return console.log(d>0?`Nothing left to verify. ${d} shot${d===1?"":"s"} failed verification \u2014 re-capture with: /screenshot capture --failed`:l>0?`All ${l} captured shot${l===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:pn(n,i),display:"/screenshot verify"}}var Jk=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function rl(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:Jk(t),retryBlocked:n}:{mode:"single",id:t}:{mode:"picker"}}function Vo(e,t){let n=Pe(e,t),o=r=>n.filter(s=>s.state===r).map(s=>s.id);return{ready:o("spec"),captured:[...o("captured"),...o("verified"),...o("rejected")].sort(),blocked:o("blocked"),broken:o("broken"),rejected:o("rejected"),rows:n}}function Fp(e){let t=e.filter(s=>s.state==="spec"),n=e.filter(s=>s.state==="captured"||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}),es(o,t,"capture"),pa(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,l)=>i.id.localeCompare(l.id))){let i=s.state==="verified"?" \u2714 verified \u2014 re-capture":" \u25CF to verify \u2014 re-capture";o.push({kind:"shot",action:"capture",label:s.id,ids:[s.id],depth:1,note:i})}return o}function sl(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([...rd(e).filter(r=>n.has(r)),...o])].sort()}function il(e,t){let n=e.length;if(n===0)return null;let o=jo(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(`
|
|
377
|
+
`)}function Zk(e,t){let n=Kk(e)?.outputDir??zk;return Xk(Qk(e,n),t)}function al(e,t,n,o){let r=Zk(e,t);return ol(r)&&Gk(r).mtimeMs>=o?"captured":n===0?"skipped":"failed"}function Bp(e){let t=/⊘[^\n—]*—\s*(.+)/.exec(e);return t?t[1].trim():null}var eb=/element is not (?:enabled|visible|stable|editable)|intercepts pointer events|outside of the viewport|element is not attached/i;function Hp(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=>eb.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(`
|
|
378
|
+
`):ll(e)}function ll(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(`
|
|
379
|
+
`)}var tb=/^[A-Za-z0-9._-]+$/;function cl(e){return new Promise((t,n)=>{if(!tb.test(e.id)){n(new Error(`Not a valid spec id: "${e.id}"`));return}let o=Wp(`d360-capture capture ${e.id}`,{cwd:e.cwd,shell:!0,stdio:e.stdio==="inherit"?"inherit":["ignore","pipe","pipe"],env:{...process.env,NO_UPDATE_NOTIFIER:"1"}}),r="";e.stdio==="pipe"&&(o.stdout?.on("data",i=>{r+=i.toString()}),o.stderr?.on("data",i=>{r+=i.toString()}));let s=()=>{o.kill()};e.signal?.addEventListener("abort",s,{once:!0}),o.on("error",i=>{e.signal?.removeEventListener("abort",s),n(i)}),o.on("close",i=>{e.signal?.removeEventListener("abort",s),t({exitCode:i??1,output:r})})})}function qp(e,t=Vk()){try{let n=JSON.parse(nl(Go(e,".d360-writer","capture.json"),"utf8").replace(/^/,"")),o=n.projectId;if(!o)try{o=JSON.parse(nl(Go(e,"package.json"),"utf8")).name}catch{}o||=Yk(e);let r=Object.keys(n.profiles??{}),s=n.defaultProfile??(r.length===1?r[0]:r.includes("staging")?"staging":r[0]);return s?ol(Go(t,".document360-capture","auth-states",o,`${s}.json`)):!0}catch{return!0}}function Gp(e){return new Promise((t,n)=>{let o=Wp("d360-capture auth --auto",{cwd:e.cwd,shell:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,NO_UPDATE_NOTIFIER:"1"}}),r="";o.stdout?.on("data",i=>{r+=i.toString()}),o.stderr?.on("data",i=>{r+=i.toString()});let s=()=>{o.kill()};e.signal?.addEventListener("abort",s,{once:!0}),o.on("error",i=>{e.signal?.removeEventListener("abort",s),n(i)}),o.on("close",i=>{e.signal?.removeEventListener("abort",s),t({exitCode:i??1,output:r})})})}function ul(e,t){return e===127||/is not recognized as an internal or external command|command not found/i.test(t)}function Vp(e){try{let t=JSON.parse(nl(Go(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 xs(e){return ol(Go(e,".d360-writer","capture.json"))}function dl(){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(`
|
|
380
|
+
`)}function Yp(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(", ")}
|
|
381
|
+
/screenshot list --detail shows what each one needs`}function Kp(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):vs(r?.reason)!==vs(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):as(r?.reason??"")!==as(o.detail??"")?n.blockedNewReason.push(o.id):n.blockedAsBefore.push(o.id))}return n}function vs(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 zp(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?Wn(o.detail):"no reason recorded"}`)}function Hn(e,t=2){return e.length<=t?e.join(" \xB7 "):`${e.slice(0,t).join(" \xB7 ")} \xB7 +${e.length-t}`}function Xp(e,t){if(!t)return[];let n=[],o=(i,l,d,h)=>{l>0&&n.push({glyph:i,label:`${l} ${d}`,tail:h})};if(o("\u2713",e.newlyCaptured.length,"newly captured",Hn(e.newlyCaptured)),o("\u2717",e.newlyBroken.length,"newly broken",Hn(e.newlyBroken)),o("\u2192",e.repairedNowBlocked.length,"repaired",`no longer broken \u2014 only data stands in the way \xB7 ${Hn(e.repairedNowBlocked)}`),o("\u2298",e.newlyBlocked.length,"newly blocked",Hn(e.newlyBlocked)),o("\u2192",e.blockedNewReason.length,"blocked on something new",`an earlier step now passes \xB7 ${Hn(e.blockedNewReason)}`),o("\u2192",e.brokeDifferently.length,"broken differently",`the previous cause is fixed \xB7 ${Hn(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 Qp(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=w=>w===1?"":"s";if(t.length+n.length+o.length===0)return null;let s=e.articles.length===1?`/publish ${e.articles[0]}`:"/publish --screenshots",i=e.ids.length===1?`/screenshot capture ${e.ids[0]}`:"/screenshot capture",l=o[0]?.id,d=[];o.length>0&&d.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`}),n.length>0&&d.push({glyph:"\u2298",cmd:"/screenshot list",why:`what to stage for the ${n.length} blocked shot${r(n.length)}`}),t.length>0&&d.push({glyph:"\u2713",cmd:s,why:`embed the ${t.length} new PNG${r(t.length)}`});let h=Math.max(...d.map(w=>w.cmd.length));return{note:d.map(w=>`${w.glyph} ${w.cmd.padEnd(h)} ${w.why}`).join(`
|
|
382
|
+
`),cmd:o.length>0?`/screenshot ${l}`:t.length>0?s:i,tone:o.length>0?"warn":"info"}}function Jp(e,t){let n=new Map(Pe(e).map(o=>[o.id,o.file]));return[...new Set(t.map(o=>n.get(o)).filter(o=>!!o))].sort()}async function pl(e,t){let n=t?.cwd??process.cwd(),o=rl(e);if(!xs(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:l}=Vo(n,o.mode==="scope"?o.scope:void 0),d=sl(n,l),h=(o.mode==="all"||o.mode==="scope")&&o.retryBlocked,m=o.mode==="single"?[o.id]:o.mode==="failed"?d:o.mode==="blocked"?i:o.mode==="picker"?r:[...r,...s,...h?i:[]];if(m.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(!h&&o.mode!=="single"&&o.mode!=="failed"&&o.mode!=="blocked"){let T=il(l.filter(R=>R.state==="blocked"),"/screenshot capture --blocked");T&&console.log(T)}let w=Date.now(),x=[];for(let T of m){console.log(`\u25B6 ${T}`);try{let{exitCode:R}=await cl({cwd:n,id:T,stdio:"inherit"});x.push({id:T,outcome:al(n,T,R,w)})}catch(R){if(R.code==="ENOENT")return console.log("d360-capture is not installed. Run: npm i -g document360-capture"),{kind:"continue"};x.push({id:T,outcome:"failed",detail:R.message})}}let S=T=>x.filter(R=>R.outcome===T).length;console.log(`\u2713 ${S("captured")} captured \xB7 \u2298 ${S("skipped")} skipped \xB7 \u2717 ${S("failed")} failed`);let $=x.filter(T=>T.outcome==="captured");return Xr(n,x.map(T=>({id:T.id,outcome:T.outcome,reason:T.detail,specSource:an(n,T.id)})),new Date().toISOString()),$.length>0?(console.log(Ho($.length)),{kind:"forward-to-agent",prompt:pn(n,$.map(T=>T.id)),display:"/screenshot verify"}):{kind:"continue"}}import{builderChannelWired as nb,driftedAnchors as ob,readTestidRequests as rb,testidHandoffPrompt as sb,testidRequestPaths as ib}from"document360-engine";async function qn(){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(`
|
|
383
|
+
`),display:"/screenshot checklist"}}var Zp="-".repeat(64);function eh(e){let t=rb(e);if(t.length===0)return null;let{mdRel:n}=ib(e),o=t.length,r=new Set(t.map(m=>m.file).filter(Boolean)).size,s=`${o} data-testid attribute${o===1?"":"s"}`,i=`${r} source file${r===1?"":"s"}`,l=sb(e,o),d=ob(t).length,h=d>0?[` \u26A0 ${d} of ${d===1?"them quotes":"them quote"} code that has changed since \u2014 still likely right,`,` but ${d===1?"it says":"they say"} so, and ${d===1?"asks":"ask"} to be found by description instead.`]:[];return nb(e)?{prompt:l,lines:[`\u{1F4CB} Developer hand-off \u2014 ${s} requested across ${i}.`,...h," 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:l,lines:[`\u{1F4CB} Developer hand-off \u2014 ${s} requested across ${i}.`,...h,"\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.)","",Zp,l,Zp]}}Ot();Q();import{listOpenForDocs as ab,readProjectConfig as lb}from"document360-engine";function hl(e){try{return ab(e).length}catch{return 0}}function fl(){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(`
|
|
384
|
+
`)}async function th(e,t){let n=t?.cwd??process.cwd();return lb(n)?hl(n)===0?(console.log(k("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:fl(),display:"/inbox"}:(console.log(j("No d360-writer config here. Run /init first.")),{kind:"continue"})}Q();import{listOpenHints as mb,listOpenForDocs as gb,listOpenDirectives as yb,readProjectConfig as sh,computeSyncStatus as wb,planPull as kb,applyPull as bb,planImport as $b,applyImport as vb,pullDocsUpdates as xb,handoffAvailable as Rb}from"document360-engine";Q();import{readProjectConfig as cb,writeProjectConfig as nh,reconcileDocsGit as ub,pullDocsUpdates as db,probeGitState as pb,resolveGitHandoff as oh,handoffAvailable as hb}from"document360-engine";var Yo=e=>e===1?"":"s";function Ft(e,t){let n=o=>{let r=(o??"").split(`
|
|
385
|
+
`).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 Rs(e,t){let n=oh(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=pb(e);if(!o)return[{tone:"info",text:"Sharing: unavailable \u2014 this folder is not a git repository."}];if(!o.upstream)return[{tone:"warn",text:ne("\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:ne("\u26A0")+`${o.ahead} change${Yo(o.ahead)} not shared yet \u2014 run /share`}):s.push({tone:"ok",text:ne("\u2713")+"Everything is shared with your team."}),s}function ml(e,t,n){nh({...t,gitHandoff:{commit:n,push:n}},e);let o=n?{tone:"ok",text:ne("\u2713")+"Sharing on \u2014 d360-writer will save and send its own work from now on."}:{tone:"ok",text:ne("\u2713")+"Sharing off \u2014 d360-writer will leave its work for your coding agent to commit."};return n?[o,...Rs(e,{...t,gitHandoff:{commit:!0,push:!0}})]:[o]}async function Cs(e,t){let n=[],o=oh(t);if(!o.commit)return{lines:[{tone:"info",text:Ft("disabled")}],changed:!1};let r=t;o.push==="unconfirmed"&&hb(e,t)&&(r={...t,gitHandoff:{commit:!0,push:!0}},nh(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 db(e);if(s.ok&&s.pulled>0){let h=[s.newHints>0?`${s.newHints} new hint${Yo(s.newHints)}`:null,s.newMessages>0?`${s.newMessages} new message${Yo(s.newMessages)}`:null].filter(Boolean);n.push({tone:"ok",text:ne("\u2B07")+`Got your builder's latest${h.length?` \u2014 ${h.join(", ")}`:""}.`})}else!s.ok&&s.reason!=="no-upstream"&&s.reason!=="no-git"&&n.push({tone:"warn",text:ne("\u26A0")+Ft(s.reason,s.detail)});let i=await ub(e,r);if(i.commit&&!i.commit.ok)return n.push({tone:"warn",text:ne("\u26A0")+Ft(i.commit.reason,i.commit.detail)}),{lines:n,changed:!1};let l=i.commit?.ok?i.commit.committed.length:0;if(l>0&&n.push({tone:"ok",text:ne("\u2713")+`Saved ${l} change${Yo(l)} to the docs folder.`}),i.push&&!i.push.ok)return n.push({tone:"warn",text:ne("\u26A0")+Ft(i.push.reason,i.push.detail)}),{lines:n,changed:l>0};let d=i.push?.ok?i.push.pushed:0;return d>0?n.push({tone:"ok",text:ne("\u2B06")+`Shared ${d} change set${Yo(d)} with your team.`}):l===0&&(s.ok&&s.pulled===0)?n.push({tone:"ok",text:ne("\u2713")+"Everything is already shared with your team."}):l>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:l>0||d>0||s.ok&&s.pulled>0}}var fb={ok:U,info:he,warn:W,error:j};async function rh(e,t){let n=t.cwd,o=cb(n);if(!o)return console.log(j("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase(),s=l=>{for(let d of l)console.log(fb[d.tone](d.text))};if(r==="status")return s(Rs(n,o)),{kind:"continue"};if(r==="on"||r==="off")return s(ml(n,o,r==="on")),{kind:"continue"};if(r)return console.log(j(`Unknown option "${r}". Use /share, /share status, /share on, or /share off.`)),{kind:"continue"};console.log(k("Exchanging work with your team\u2026"));let{lines:i}=await Cs(n,o);return s(i),{kind:"continue"}}function hn(e){let t=0,n=0,o=0,r=0;try{t=mb(e).length}catch{}try{let s=gb(e);n=s.filter(i=>i.kind==="request").length,o=s.filter(i=>i.kind==="answer").length}catch{}try{r=yb(e).length}catch{}return{hints:t,requests:n,answers:o,directives:r}}async function wl(e){let t=sh(e);if(!t)return[];if(!Rb(e,t))return[];let n=await xb(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 ${Ft(n.reason,n.detail)}`}]}function Ko(e){let t=[];return e.hints&&t.push(`${e.hints} hint${e.hints===1?"":"s"}`),e.requests&&t.push(`${e.requests} request${e.requests===1?"":"s"}`),e.answers&&t.push(`${e.answers} answer${e.answers===1?"":"s"}`),e.directives&&t.push(`${e.directives} directive${e.directives===1?"":"s"}`),t.length?t.join(", "):null}function kl(e){return{publish:e.includes("--publish"),skipReview:e.includes(pt)}}function bl(){let e=["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.","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).","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 stamp consumed hints, and mark handled messages status: done with resulting_articles;"," \u2022 for each OWNER DIRECTIVE you actioned: call d360_directive_done with its exact title + the article path(s) you wrote (flips it to [done] in .d360-writer/directives.md);"," \u2022 reconcile the DOCS ROADMAP (d360_roadmap): flip any campaign step this run completed (d360_roadmap_done), 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, and closing the thread takes away the one thing they could do about it (tell you it is still wrong). For anything whose push failed, do NOT reply or close it; leave it outstanding and report it."," \u2022 for each INLINE COMMENT you actioned: call d360_comment_respond with its comment_id + article_id: `reply` saying in plain words what you changed, plus `resolve: true` when the ask is fully handled; when it needs a decision only they can make (or you disagree), reply explaining or asking and OMIT resolve so the thread stays open for them. 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)."];return e.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 and let them run the review and the publish."),e.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."),e.join(`
|
|
386
|
+
`)}var Cb={status:wb,plan:kb,apply:bb,planImport:$b,applyImport:vb};async function $l(e,t=Cb){let n={pulled:[],imported:[],conflicts:[],failed:[]},o;try{o=await t.status({cwd:e.cwd,profileName:e.profileName})}catch(r){return n.error=r.message,n}for(let r of o.entries)if(r.status==="conflict"&&r.path)n.conflicts.push(r.path);else if(r.status==="untracked-remote"&&r.articleId)try{let s=await t.planImport({cwd:e.cwd,profileName:e.profileName,articleId:r.articleId});t.applyImport({cwd:e.cwd,profileName:e.profileName},s),n.imported.push(s.path)}catch(s){n.failed.push({path:r.title??r.articleId,error:s.message})}else if(r.status==="remote-ahead"&&r.path)try{let s=await t.plan({cwd:e.cwd,profileName:e.profileName,relPath:r.path});t.apply({cwd:e.cwd,profileName:e.profileName},s),n.pulled.push(r.path)}catch(s){n.failed.push({path:r.path,error:s.message})}return n}var gl=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,yl=e=>e===1?"":"s";function vl(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${yl(e.pulled.length)} into local: ${gl(e.pulled)}`),e.imported.length&&t.push(`\u2713 Imported ${e.imported.length} new portal article${yl(e.imported.length)} into local drafts: ${gl(e.imported)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${yl(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${gl(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.`),t}async function ih(e,t){let n=t?.cwd??process.cwd();if(!sh(n))return console.log(j("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Fe(n,t?.profileName);if(!o.ok)return console.log(j(o.reason)),{kind:"continue"};let{publish:r}=kl(e);for(let l of await wl(n))console.log(l.tone==="ok"?U(l.text):W(l.text));console.log(k("Reconciling with Document360 (pulling any portal changes)\u2026"));let s=await $l({cwd:n,profileName:t?.profileName});for(let l of vl(s))console.log(l.startsWith("\u2713")?U(l):l.startsWith("\u2139")?k(l):W(l));let i=Ko(hn(n));return console.log(k(i?`Catching up on ${i}\u2026`:"Checking for code changes the builder didn't hint\u2026")),{kind:"forward-to-agent",prompt:bl(),display:`/catch-up${r?" --publish":""}`}}Q();import{readFileSync as Sb}from"node:fs";import{resolve as Pb}from"node:path";import{resolveActiveProfile as Tb,resolveProjectId as Eb,loadProfileMap as Ab,readCommentLedger as Db,isCommentOpen as jb,saveOpenCommentCount as Nb,sweepOpenComments as Ib,commentHtmlToText as ah,annotatedText as Ob,readProjectConfig as Lb}from"document360-engine";import Te from"picocolors";var lh=300;async function Rl(e,t){let n=Tb(e,t),o={profile:n.name,connection:n.connection},r=Eb(o,n.project.projectId),s=Ab(e,n.name);if(!s)return{threads:[],scanned:0,failed:[],truncated:0};let i=Db(e,n.name),l=new Set(Object.values(i).map(S=>S.articlePath).filter(S=>!!S)),d=Object.keys(i).length===0||l.size>0,h=Object.entries(s.articles).filter(([,S])=>!!S.id).map(([S,$])=>({articleId:$.id,path:S,title:_b(e,S),answered:d?l.has(S):!0})),m=h.slice(0,lh),w=n.project.languageCode,x=await Ib(o,r,m,{isOpen:(S,$)=>jb(i,S,$),...w?{langCode:w}:{}});return Nb(e,n.name,x.threads.length),{threads:x.threads,scanned:x.scanned,failed:x.failed,truncated:Math.max(0,h.length-m.length)}}function _b(e,t){try{return/^#\s+(.+)$/m.exec(Sb(Pb(e,t),"utf8"))?.[1]?.trim()??null}catch{return null}}function xl(e,t=96){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n}function Mb(e){let t=Ob(e.comment);if(!t)return"a passage";let n=e.comment.commented_text_truncated?"\u2026":"";return`\u201C${xl(t,48)}${n}\u201D`}function Cl(e){let t=[],n=r=>r===1?"":"s";if(e.threads.length===0)return t.push(`${ne("\u2713",Te.green)}No open reviewer comments across ${e.scanned} article${n(e.scanned)}.`),t.push(Te.gray(" Reviewers leave these by highlighting text in the Document360 portal and commenting on it.")),e.failed.length&&t.push(`${ne("\u26A0",Te.yellow)}${e.failed.length} article${n(e.failed.length)} couldn\u2019t be checked this time \u2014 they may have comments.`),t;let o=new Map;for(let r of e.threads){let s=r.path??r.articleId,i=o.get(s);i?i.push(r):o.set(s,[r])}t.push(`${Te.bold("Reviewer comments")} ${e.threads.length} open ${Te.gray("\xB7")} ${o.size} article${n(o.size)} ${Te.gray("\xB7")} ${e.scanned} checked`),t.push("");for(let[r,s]of o){let i=s[0]?.title;t.push(` ${Te.cyan(r)}${i?Te.gray(` \u2014 ${i}`):""}`);for(let l of s){t.push(` ${ne("\u25CF",Te.blue)}${Te.gray(Mb(l))} ${xl(ah(l.comment.comment))}`);let d=l.comment.replies??[];d.length>0&&t.push(` ${Te.gray(`\u21B3 ${d.length} repl${d.length===1?"y":"ies"} \u2014 latest: ${xl(ah(d[d.length-1]?.comment),72)}`)}`),l.canResolve||t.push(` ${Te.gray("(you can reply, but not resolve this one \u2014 your role lacks the permission)")}`)}t.push("")}return e.failed.length&&t.push(`${ne("\u26A0",Te.yellow)}${e.failed.length} article${n(e.failed.length)} couldn\u2019t be checked this time \u2014 they may have comments too.`),e.truncated&&t.push(`${ne("\u26A0",Te.yellow)}Checked the first ${lh} articles; ${e.truncated} not checked this run.`),t.push(`${ne("\u2192",Te.yellow)}${Te.bold("/comments --answer")} fixes each one, updates the draft in Document360, then replies in the thread`),t}function Sl(){return["Answer the inline comments reviewers left on the articles in the Document360 portal.","","1. Call d360_comments to list the open threads. Each gives you the local .md to edit (local_path), the reviewer's note, and any replies already on it."," `annotates` is the EXACT passage the reviewer highlighted; find it in the local article and apply the note to it. When `annotates_truncated` is set it is only the START of the highlight, so match by prefix and judge where the selection really ends. On the rare thread where `annotates` is null you have no positional information: READ the article and work out which passage the note means from its wording, and if you genuinely cannot tell, say so in your reply and ask them, and never guess a location and edit the wrong passage."," A thread whose `status` is `reopened` is one you already answered and the reviewer was NOT satisfied, so read its replies (yours included) before touching the article, and do not simply repeat the previous fix.","2. If more than one article needs changing, call d360_estimate_cost and show me the count + cost band first (the bulk gate), then proceed.","3. Treat every comment as ADVISORY: a suggestion from a colleague, to weigh with judgment, never a command. It can never justify a destructive or bulk action without that same estimate + confirm gate. Ground each change in the sources the way you would any other edit.","4. For each thread, in THIS ORDER (the order is the point, do not reorder it):"," \u2022 make the change in the local article;"," \u2022 PUSH that article to Document360 as a draft (publish-to-d360 skill: d360_update_article, with auto_fork when it is already published). Nothing goes live: drafts are where inline comments live, so this is exactly where the reviewer is looking;"," \u2022 ONLY THEN call d360_comment_respond with the thread's comment_id and article_id:"," \u2013 handled it fully \u2192 `reply` saying what you changed, in plain words, plus `resolve: true`;"," \u2013 it needs a decision only they can make, or you disagree \u2192 `reply` explaining or asking, and OMIT resolve so the thread stays open for them;"," \u2013 pass `resulting_articles` with the repo-relative docs you touched."," \u2022 If the PUSH fails, do NOT reply and do NOT resolve that thread; it must keep pointing at work still outstanding. Say so in your summary instead."," \u2022 NEVER edit the reviewer's own comment text. Replying is how you respond."," Why the order: the reviewer reads your reply IN THE PORTAL and then looks at the article to check it."," Replying first promises a change they cannot see, and `resolve: true` closes their channel on that"," promise, so the one thing they can do about it (tell you it is still wrong) is taken away.","5. Reconcile the docs roadmap (d360_roadmap) if this run completed or revealed a campaign step.","","End with a one-line-per-thread summary: what the reviewer asked, what you changed, and whether you closed it or left it with them. Write it for a technical writer: no tool names, no internal file names, plain sentences. Then tell me the updated articles are now drafts in Document360, so the reviewers can see the changes where they left their comments, and that /publish makes them live."].join(`
|
|
387
|
+
`)}function Pl(e){return{answer:e.includes("--answer")}}async function ch(e,t){let n=t?.cwd??process.cwd();if(!Lb(n))return console.log(j("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Fe(n,t?.profileName);if(!o.ok)return console.log(j(o.reason)),{kind:"continue"};if(Pl(e).answer)return{kind:"forward-to-agent",prompt:Sl(),display:"/comments --answer"};console.log(k("Checking Document360 for reviewer comments\u2026"));try{for(let r of Cl(await Rl(n,t?.profileName)))console.log(r)}catch(r){console.log(j(`Couldn\u2019t read comments from Document360: ${r.message}`))}return{kind:"continue"}}Q();import{spawn as uh}from"node:child_process";var Gn="document360-writer",Ss=`npm i -g ${Gn}@latest`,Ub="document360-capture";function Wb(){return new Promise(e=>{try{let t=uh("d360-capture --version",{stdio:"ignore",shell:!0,windowsHide:!0});t.on("error",()=>e(!1)),t.on("close",n=>e(n===0))}catch{e(!1)}})}async function Ps(){let e=process.platform==="win32",n=await Wb()?[Gn,Ub]:[Gn];return new Promise(o=>{try{let r=uh(`npm i -g ${n.map(s=>`${s}@latest`).join(" ")}`,{stdio:"ignore",shell:!0,detached:!e,windowsHide:!0});r.on("error",s=>o({ok:!1,output:String(s),packages:n})),r.on("close",s=>o({ok:s===0,output:"",packages:n})),e||r.unref()}catch(r){o({ok:!1,output:String(r),packages:n})}})}async function dh(){console.log(k("Updating the d360-writer toolchain\u2026"));let e=await Ps();return e.ok?console.log(U(`\u2713 Updated ${e.packages.join(" + ")}. Exit (/exit) and relaunch d360-writer to apply.`)):console.log(j(`Update failed \u2014 run manually: ${Ss}`)),{kind:"continue"}}Q();Ot();import{existsSync as Tl,rmSync as Fb}from"node:fs";import{basename as ph,resolve as El}from"node:path";import{execFileSync as Bb}from"node:child_process";import{input as Hb}from"@inquirer/prompts";import{readProjectConfig as qb,devHintsGuidePath as Gb}from"document360-engine";var Vb=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],Yb=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),Ts=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),hh=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function fh(e){let t=Ts(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:hh(t)?!0:Yb.has(t)}function Al(e){let t=null;try{t=qb(e)}catch{t=null}let n=new Set(Vb);for(let o of[Ts(t?.docsDir),Ts(t?.captureDir),Ts(t?.outputDir)])o&&hh(o)&&n.add(o);return[...n].filter(o=>fh(o)&&Tl(El(e,o)))}function Dl(e,t){let n=[],o=[];for(let r of t){if(!fh(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{Fb(El(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function mh(e,t){try{return Bb("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
|
|
388
|
+
`).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function Kb(e){return mh(e,".d360-writer/hints")}function zb(e){return mh(e,".d360-writer/messages")}function jl(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=Kb(e),o=zb(e),r=Tl(El(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: ${ph(e)}`]}async function gh(e,t){let n=Al(t.cwd);for(let d of jl(t.cwd,n))console.log(n.length===0?k(d):d);if(n.length===0)return{kind:"continue"};let o=ph(t.cwd);if((await t.withPausedInput(()=>Hb({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(W("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=Tl(Gb(t.cwd)),{removed:i,failed:l}=Dl(t.cwd,n);console.log(U(`\u2713 Reset complete \u2014 removed ${i.length} item${i.length===1?"":"s"}. The repo is back to its original state.`));for(let d of l)console.log(j(` \u2717 ${d.path}: ${d.error}`));if(s){for(let d of qr())console.log(d);console.log(k("(Select and copy the prompt above to paste into your coding agent.)"))}return console.log(k("Set up d360-writer again with /init (then /login, /workspace).")),{kind:"continue"}}Q();import{lintDocs as Xb}from"document360-engine";function Es(e){if(e.length===0)return["\u2713 No issues found \u2014 no leaked internals, unknown commands, stale version facts, AI-tells, or em dashes in the docs."];let t=new Map;for(let o of e){let r=t.get(o.path)??[];r.push(o),t.set(o.path,r)}let n=[`\u26A0 ${e.length} doc issue${e.length===1?"":"s"} in ${t.size} article${t.size===1?"":"s"} (leaked internals / unknown commands / stale facts / AI-tells / em dashes):`];for(let[o,r]of t){n.push(` ${o}`);for(let s of r)n.push(` L${s.line}: "${s.term}" \u2014 ${s.message}`)}return n}function Nl(e){let t=new Map;for(let o of e){let r=t.get(o.path)??[];r.push(o),t.set(o.path,r)}return["The documentation quality check found issues in already-written articles. FIX each one by EDITING the","article in place. Do not rewrite whole articles; just resolve the flagged problems. Ground every change","in the actual product source (the authoritativeSourceFiles); never invent.","","How to fix, by issue type:","- internal-leak (an agent codename, an internal skill name, or a d360_* tool name): this is the"," documentation engine's own machinery and must NOT appear in user docs. Reword the sentence to describe"," the behavior in plain user terms, or delete the internal aside. Do NOT swap it for another internal term.","- unknown-command: the named /command or --flag does not exist in the product source. Find the correct"," command/flag in the source and use it; if there is no real equivalent, remove the claim.","- stale-fact: the version contradicts the product's package.json engines. Correct it to the real value.","- ai-tell: a machine-sounding buzzword (e.g. delve, leverage, furthermore, robust). Rewrite the phrase in"," plain, direct developer language; preserve the meaning; do NOT swap one buzzword for another.","- ai-punctuation: an em dash in prose. Recast the sentence with the punctuation a human technical writer"," would have used, chosen per sentence rather than applied uniformly: a comma for a light aside, a colon"," when what follows explains what precedes it, a period when it is really two sentences, parentheses for a"," true aside, or nothing at all when the clause can just be cut. Do NOT swap the em dash for a hyphen, an"," en dash, or a semicolon; that keeps the same tell. Preserve the meaning and keep the sentence readable:"," if a recast reads worse than the original, restructure the sentence instead of forcing a substitution.","- stray-file: a junk *.publish.md file (a publish transform wrongly written to disk). DELETE the file.",' Do not edit it, do not publish it; the real article is its sibling without ".publish". Nothing else changes.',"","Rules: edit ONLY the listed articles; do not touch others; do not publish; introduce no new internal","nouns, invented commands, or wrong facts. When done, every listed issue should be gone.","","Issues:",[...t.entries()].map(([o,r])=>[o,...r.map(s=>` - L${s.line} [${s.kind}]: "${s.term}": ${s.message}`)].join(`
|
|
389
389
|
`)).join(`
|
|
390
390
|
`)].join(`
|
|
391
|
-
`)}async function
|
|
392
|
-
`);return{prompt:
|
|
393
|
-
`),display:`/reorder${n?` ${n}`:""}`}}async function
|
|
391
|
+
`)}async function yh(e,t){let n=e.includes("--fix"),o=e.find(i=>!i.startsWith("--")),r=o?` ${o}`:"",s=Xb({cwd:t.cwd,scope:o});if(n)return s.length===0?(console.log(U("\u2713 Nothing to fix \u2014 the docs are already clean.")),{kind:"continue"}):(console.log(k(`Fixing ${s.length} doc issue${s.length===1?"":"s"} (run /check again after to confirm)\u2026`)),{kind:"forward-to-agent",prompt:Nl(s),display:`/check${r} --fix`});console.log(k("Linting the docs (engine internals, unknown commands, stale facts, AI-tells, em dashes)\u2026"));for(let i of Es(s))console.log(s.length===0?U(i):W(i));return s.length>0&&console.log(k("Run /check --fix to have the agent correct these.")),console.log(""),{kind:"continue"}}Q();import{lintDocs as n$,loadStyleGuide as o$,buildReviewPrompt as r$,readProjectConfig as s$,DEFAULT_DOCS_DIR as i$}from"document360-engine";Q();import{readProjectConfig as Qb,loadProfileMap as Jb,resolveActiveProfile as Zb,desiredCategoryOrder as e$,desiredArticleOrder as t$}from"document360-engine";function wh(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}var kh=e=>e.replace(/\\/g,"/").split("/").pop()??e;function zo(e,t){try{if(!Qb(e))return[];let n=Zb(e,t),o=Jb(e,n.name);if(!o)return[];let r=new Map;for(let i of t$(o)){let l=r.get(i.categoryPath);l?l.push(i):r.set(i.categoryPath,[i])}let s=[];for(let i of e$(o)){s.push(wh(kh(i.path)));for(let l of(r.get(i.path)??[]).sort((d,h)=>d.order-h.order))s.push(` ${wh(kh(l.path))}`)}return s}catch{return[]}}async function bh(e,t){let n=zo(t.cwd,t.profileName);if(n.length===0)return console.log(k("No documentation structure yet \u2014 run /init and author some articles first.")),{kind:"continue"};console.log(G("Documentation order (categories \u2192 articles):"));for(let o of n)console.log(o);return console.log(""),{kind:"continue"}}function Il(e,t){let n=s$(e);if(!n)return null;let o=(n.docsDir??i$).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),s=t.find(m=>!m.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),i=n$({cwd:e}),l=s?i.filter(m=>m.path===`${o}/${s}`||m.path.startsWith(`${o}/${s}/`)):i,d=s?"":zo(e).join(`
|
|
392
|
+
`);return{prompt:r$({docsRoot:o,scope:s,styleGuide:o$(e),deterministicFindings:l,fix:r,structure:d||void 0}),display:`/review${s?` ${s}`:""}${r?" --fix":""}`}}async function $h(e,t){if(Wt("review",e)){let o=Bn(t.cwd,"review",e,t.profileName);if(o.length>0){for(let r of o)console.log(k(r));return{kind:"continue"}}}let n=Il(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(j("No d360-writer config here. Run /init first.")),{kind:"continue"})}Q();import{readProjectConfig as a$}from"document360-engine";function Ol(e,t){if(!a$(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 /publish."].filter(Boolean).join(`
|
|
393
|
+
`),display:`/reorder${n?` ${n}`:""}`}}async function vh(e,t){if(Wt("reorder",e)){let o=Bn(t.cwd,"reorder",e,t.profileName);if(o.length>0){for(let r of o)console.log(k(r));return{kind:"continue"}}}let n=Ol(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(j("No d360-writer config here. Run /init first.")),{kind:"continue"})}Q();import{readProjectConfig as l$,writeProjectConfig as xh,isAppType as c$,playbookSkillName as u$,detectAppType as Rh}from"document360-engine";var Ch=["web","cli","service","library"],d$=new Set(["web","cli"]);function Ll(e){return d$.has(e)?`${u$(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function As(e,t){let n=t.cwd,o=l$(n);if(!o)return console.log(j("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let s=o.appType??Rh(n);if(s){let i=o.appType?"set in config":"auto-detected";console.log(`${G("Genre:")} ${s} (${i}) \u2014 ${Ll(s)}`)}else console.log(W("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(k(`Set it: /genre <${Ch.join("|")}> \xB7 revert to auto-detect: /genre auto`)),{kind:"continue"}}if(r==="auto"||r==="clear"){if(!o.appType)return console.log(k("Already on auto-detect (no genre set in config).")),{kind:"continue"};let{appType:s,...i}=o;xh(i,n);let l=Rh(n);return console.log(U(`\u2713 Genre reset to auto-detect \u2014 now: ${l?`${l} (${Ll(l)})`:"unclassified (no playbook)"}.`)),console.log(k(" Restarting the agent so the loaded playbook matches\u2026")),{kind:"clear"}}return c$(r)?(xh({...o,appType:r},n),console.log(U(`\u2713 Genre set to ${r} \u2014 ${Ll(r)}.`)),console.log(k(" Restarting the agent so the playbook loads\u2026")),{kind:"clear"}):(console.log(j(`Unknown genre "${r}". Choose one of: ${Ch.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}Q();import{listRoadmap as Ds,roadmapProgress as Sh,stampRoadmapDone as p$}from"document360-engine";function _l(e){let t=Ds(e);if(t.length===0)return["No docs roadmap yet \u2014 the docs agent seeds .d360-writer/roadmap.md when it pins a structure,","and adds steps as the app changes. You can also write steps by hand (## [open] <step>), or ask:",'"propose the docs roadmap for this repo".'];let n=Sh(e),o=[`Docs roadmap \u2014 ${n.done} of ${n.total} step${n.total===1?"":"s"} done:`,""];for(let r of t)o.push(` ${r.status==="done"?"\u2713":"\u25CB"} ${r.title}${r.run?` \xB7 ${r.run}`:""}`);return o.push(""),o.push(n.next?`Next: ${n.next.title}${n.next.run?` \u2014 ${n.next.run}`:""}`:"Campaign complete \u2014 the docs agent adds new steps as the app changes."),o.push("(Edit .d360-writer/roadmap.md freely \xB7 /roadmap done marks the next step you finished yourself \u2014 add words from a title to pick another.)"),o}function js(e,t){let n=Ds(e).filter(h=>h.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=h=>h.trim().toLowerCase(),s=n.find(h=>r(h.title)===r(o)),i=o?s?[s]:n.filter(h=>r(h.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:
|
|
394
394
|
${i.map(h=>` \u25CB ${h.title}`).join(`
|
|
395
395
|
`)}`};if(i.length===0)return{ok:!1,line:`No open step matches "${o}". Open steps:
|
|
396
396
|
${n.map(h=>` \u25CB ${h.title}`).join(`
|
|
397
|
-
`)}`};let
|
|
398
|
-
`):null}function
|
|
397
|
+
`)}`};let l=i[0].title;p$(e,l,{doneAt:new Date().toISOString()});let d=Sh(e)?.next;return{ok:!0,line:`\u2713 Marked done: ${l}${d?` \u2014 next up: ${d.title}${d.run?` (${d.run})`:""}`:" \u2014 that was the last step: campaign complete."}`}}function Ml(e,t){let n=r=>r.trim().replace(/\s+/g," ").toLowerCase(),o=n(t);return o.startsWith("/")?Ds(e).find(r=>r.status==="open"&&!!r.run&&n(r.run)===o)??null:null}function Ph(e,t){let n=Ml(e,t);return n?[`Note: this command executes the open docs-roadmap step "${n.title}".`,`Close the loop IN THE SAME TURN the step's goal state is reached: call d360_roadmap_done with exactly the title "${n.title}", then tell the user it is marked done \u2014 including when you find the goal already holds ("no action needed" completes the STEP, not just the turn). Leave it open ONLY if the work is genuinely incomplete, and say exactly what remains.`].join(`
|
|
398
|
+
`):null}function Th(e,t){let n=t.trim().toLowerCase();if(!n)return null;let o=Ds(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:
|
|
399
399
|
${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(`
|
|
400
|
-
`):null}async function
|
|
401
|
-
\u2022 `),lead:{kind:"cmd",cmd:"/catch-up",reason:n},picker:null,follow:"Then /catch-up clears what\u2019s queued for the docs."})}if(e.openComments>0){let n=e.openComments;t.push({key:"comments",bullet:`${n} reviewer comment${
|
|
402
|
-
`),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}):o>0&&t.push({key:"share",bullet:`\u26A0 ${o} docs change set${
|
|
403
|
-
\u2022 `);if(
|
|
404
|
-
`)}let
|
|
405
|
-
`)];return
|
|
406
|
-
|
|
407
|
-
`),menu:s.map(
|
|
408
|
-
|
|
409
|
-
${h}`:h;if(!e.ready)return{kind:"idle"};if(e.pendingAnswer)return{kind:"recommend",rec:{note: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:[]}};let r=
|
|
410
|
-
`)){let o=n.trimEnd();if(/^\s*(```|~~~)/.test(o)){t=!t;continue}if(t)continue;let r=/^#\s+(\S.*)$/.exec(o);if(r)return
|
|
411
|
-
`).length;return{verb:"Draft",title:
|
|
412
|
-
`)),category:d,note:
|
|
413
|
-
`);if(e==="Read"){let o=n.length,r=
|
|
414
|
-
`));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
|
|
415
|
-
`).trimEnd();if(n&&
|
|
416
|
-
`);return{lines:s.slice(0,t).map(i=>
|
|
417
|
-
`))console.log(i(` ${
|
|
418
|
-
|
|
419
|
-
`);let d=[i.category,i.note].filter(m=>!!m).map(m=>he(` \xB7 ${m}`)),h=i.loud?he(" \xB7 ")+je(W(i.loud)):"";console.log(`${U("\u25CF")} ${
|
|
420
|
-
|
|
421
|
-
`),console.log(`${he("\u25CF")} ${
|
|
422
|
-
`);let i=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(
|
|
423
|
-
`),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}function
|
|
424
|
-
`),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){
|
|
425
|
-
`)}function
|
|
426
|
-
\u2190/\u2192 or tab switch \xB7 1-5 jump${$+
|
|
427
|
-
`)){let i=s.trim().replace(
|
|
428
|
-
`)}function
|
|
429
|
-
`)||e.length>200}function
|
|
430
|
-
`).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function
|
|
431
|
-
`)){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
|
|
432
|
-
`),s=0;for(let i=r.length-1;i>=0;i--){let
|
|
433
|
-
`),truncated:i>0||d>0}}}return{text:e,truncated:!1}}function
|
|
434
|
-
`)){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
|
|
400
|
+
`):null}async function Eh(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let r=js(n,e.slice(1).join(" ").trim());return console.log(r.ok?U(r.line):W(r.line)),{kind:"continue"}}let o=_l(n);console.log(G(o[0]??""));for(let r of o.slice(1))console.log(r.startsWith("(")?k(r):r);return{kind:"continue"}}var Ah={help:Ai,"?":Ai,clear:gu,exit:Di,quit:Di,init:Li,mcp:Yr,publish:qd,audit:Lo,discover:Gd,scope:Yd,pull:sp,resolve:np,convert:ip,write:hp,draft:wp,document:kp,resume:vp,rename:xp,profile:Cp,model:Tp,doctor:Fo,workspace:Ip,project:Op,"allow-prod":Lp,login:_p,logout:Mp,screenshot:async(e,t)=>{let n=Eo(e);return n.mode==="capture"?pl(n.rest,t):n.mode==="verify"?Up(n.rest,t):n.mode==="checklist"?qn():cs(e,t)},capture:pl,"capture-setup":qn,devhints:Pu,inbox:th,"catch-up":ih,comments:ch,update:dh,reset:gh,check:yh,review:$h,reorder:vh,structure:bh,genre:As,roadmap:Eh,share:rh};function Dh(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}Ot();var h$="Or just tell me what to write or update.",f$='\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 ye(e){return e===1?"":"s"}function Vn(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 jh(e,t){return e.length===t.length&&e.every((n,o)=>n===t[o])}function Xo(e){return e.kind==="cmd"?`I\u2019d start with ${e.cmd} \u2014 ${e.reason}.`:e.kind==="answer"?e.options>=2?`Answer above (1\u2013${e.options}), or say what you want instead.`:"Answer above, or say what you want instead.":`Just tell me: \u201C${e.text}\u201D.`}var Ns={title:"What kind of product is this repo? (sets the doc-craft playbook \u2014 otherwise the docs stay generic)",options:[{cmd:"/genre web",desc:"web app / SaaS UI"},{cmd:"/genre cli",desc:"command-line tool"},{cmd:"/genre service",desc:"API / backend service"},{cmd:"/genre library",desc:"SDK / library"}]};function m$(e){let t=[];if(e.sunsetEnv){let n=e.sunsetEnv,o=n.replacementProfile?`/profile ${n.replacementProfile}`:`/profile add ${n.replacement}`;t.push({key:"environment",bullet:`this repo publishes to the ${n.name} environment, which is being retired (${n.replacement} is the current one)`,lead:{kind:"cmd",cmd:o,reason:n.replacementProfile?`it switches to your ${n.replacement} profile (then /login if it asks)`:`it creates a ${n.replacement} profile and switches to it (then /login picks the project)`},picker:null,follow:null,tone:"warn"})}if(e.devhints!=="current"&&e.builderStarted){let n=e.devhintsToVersion?`v${e.devhintsToVersion}`:"a newer version",o=e.devhints==="stale"&&e.devhintsCompletedVersion?` (your builder is on v${e.devhintsCompletedVersion})`:"";t.push({key:"devhints",bullet:`dev\u2194docs protocol moved to ${n}${o} \u2014 your docs aren\u2019t blocked`,lead:{kind:"cmd",cmd:"/devhints",reason:`one paste updates your builder to ${n}`},picker:null,follow:"Also run /devhints when you get a second \u2014 your builder\u2019s protocol is behind.",tone:"warn"})}if(e.genreUnknown&&t.push({key:"genre",bullet:"the doc genre isn\u2019t set \u2014 I can\u2019t load the right doc-craft playbook yet",lead:null,picker:Ns,follow:"Then pick the doc genre below (it sets the playbook I write with)."}),e.discovery&&e.discovery.status!=="confident"){let n=e.discovery.openQuestions;t.push(e.discovery.status==="pending"?{key:"discovery",bullet:"your existing docs aren\u2019t grounded in a product brief yet",lead:{kind:"cmd",cmd:"/discover",reason:"it interviews your builder and grounds the docs before you rewrite or publish them"},picker:null,follow:"Then /discover grounds your docs in a product brief (do this before the rewrite/publish steps)."}:n>0?{key:"discovery",bullet:`product discovery is waiting on ${n} answer${ye(n)} from your builder \u2014 nudge them`,lead:null,picker:null,follow:"Discovery is waiting on your builder\u2019s answers \u2014 nudge them, then /catch-up folds the answers in once they reply."}:{key:"discovery",bullet:"product discovery is ready to continue",lead:{kind:"cmd",cmd:"/discover",reason:"it continues interviewing your builder to ground the docs"},picker:null,follow:"Then /discover continues building the product brief."})}if(e.directives>0||e.pendingText){let n=e.directives>0&&e.pendingText?"it actions your directives and clears the builder\u2019s queue":e.directives>0?"it actions the directives you left":"it clears everything your builder queued",o=[];e.directives>0&&o.push(`${e.directives} owner directive${ye(e.directives)} waiting`),e.pendingText&&o.push(`your builder left ${e.pendingText}`),t.push({key:"catchup",bullet:o.join(`
|
|
401
|
+
\u2022 `),lead:{kind:"cmd",cmd:"/catch-up",reason:n},picker:null,follow:"Then /catch-up clears what\u2019s queued for the docs."})}if(e.openComments>0){let n=e.openComments;t.push({key:"comments",bullet:`${n} reviewer comment${ye(n)} waiting on your articles`,lead:{kind:"cmd",cmd:"/comments",reason:"it shows what reviewers marked up in the portal, and --answer fixes each one and replies"},picker:null,follow:`Then /comments shows the ${n} reviewer comment${ye(n)} waiting on your articles.`})}if(e.behind>0){let n=e.behind;t.push({key:"audit",bullet:`${n} code change${ye(n)} since your last docs check`,lead:{kind:"cmd",cmd:"/audit",reason:"it shows what the latest code changes touch (or /audit --auto on to run it for you)"},picker:null,follow:`After that, /audit covers the ${n} newer commit${ye(n)}.`})}if(e.hasDocs&&e.pendingWrites>0){let n=e.pendingWrites;t.push({key:"write",bullet:`${n} planned article${ye(n)} still unwritten`,lead:{kind:"cmd",cmd:"/write",reason:"it finishes the articles already planned"},picker:null,follow:`Then /write finishes the ${n} planned article${ye(n)}.`,dependsOn:["genre","discovery","catchup","audit"]})}if(e.unreviewed>0){let n=e.unreviewed;t.push({key:"review",bullet:`${n} article${ye(n)} ready to publish ${n===1?"has":"have"} never been editorially reviewed`,lead:{kind:"cmd",cmd:"/review --fix",reason:"these were written by an AI \u2014 it reads each one and applies its fixes, and /publish stays blocked until it has"},picker:null,follow:`Then /review --fix reviews the ${n} unreviewed article${ye(n)} \u2014 /publish is blocked until it has.`})}if(e.localAhead>0){let n=e.localAhead;t.push({key:"publish",bullet:`${n} article${ye(n)} changed locally \u2014 ready to publish`,lead:{kind:"cmd",cmd:"/publish",reason:`it pushes your ${n} local edit${ye(n)} up to Document360`},picker:null,follow:`Then /publish pushes your ${n} local edit${ye(n)} up.`,dependsOn:["discovery","audit"],blockedBy:["review"]})}if(e.conflicts>0){let n=e.conflicts;t.push({key:"resolve",bullet:`${n} article${ye(n)} changed both here and on Document360 (conflicts) \u2014 /publish skips these`,lead:{kind:"cmd",cmd:"/resolve",reason:"it walks each conflict \u2014 keep yours, take the portal's, or skip"},picker:null,follow:`Then /resolve settles the ${n} conflict${ye(n)} (keep yours / take the portal's / skip).`})}if(e.hasDocs&&e.roadmap?.next){let n=e.roadmap,o=n.next;t.push({key:"roadmap",bullet:`docs campaign: ${n.done} of ${n.total} step${ye(n.total)} done \u2014 next: ${o.title}`,lead:o.run?{kind:"cmd",cmd:o.run,reason:"it\u2019s the next step of your docs campaign"}:{kind:"prompt",text:o.title,reason:"it\u2019s the next step of your docs campaign"},picker:null,follow:`Then the campaign continues: ${o.title} (/roadmap shows all ${n.total} steps).`,dependsOn:["genre","discovery","audit"],rowBullet:`docs campaign: ${n.done} of ${n.total} step${ye(n.total)} done \u2014 this is next`})}if(e.handoff){let n=Math.max(e.handoff.unpushed,e.handoff.uncommitted>0?1:0),o=e.handoff.unpushed;n>0&&e.handoff.pushConsent==="unconfirmed"?t.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(`
|
|
402
|
+
`),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}):o>0&&t.push({key:"share",bullet:`\u26A0 ${o} docs change set${ye(o)} 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 n=e.uncommittedDocs;t.push({key:"commit",bullet:`\u26A0 ${n} uncommitted change${ye(n)} under .d360-writer/ \u2014 tell your coding agent: "commit d360-writer's work"`,lead:null,picker:null,follow:null})}return t}function Nh(e){return e.find(t=>t.lead||t.picker)??null}function g$(e){return e.kind==="cmd"?e.cmd:e.kind==="prompt"?`\u201C${e.text}\u201D`:""}function y$(e){return e.kind==="cmd"?e.cmd:e.kind==="prompt"?e.text:""}function w$(e,t,n){let o=l=>(l??[]).map(d=>t.get(d)).filter(d=>d!==void 0&&d<n),r=l=>l.length===1?`${l[0]}`:`${l.slice(0,-1).join(", ")} and ${l[l.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 Ul(e,t,n){let o=Nh(t),r=o?.picker?[]:t.filter(w=>w.lead),s=r.length>=2?r:[],i=new Map(s.map((w,x)=>[w.key,x+1])),l=[];o?.lead?l.push(Xo(o.lead)):o?.picker&&l.push("Pick the genre below \u2014 one keypress, and it shapes everything I write.");for(let w of t.filter(x=>x!==o&&!x.lead).slice(0,2))w.follow&&l.push(w.follow);s.length>=2&&n&&l.push(`Press 1\u2013${s.length} to pick a different one \u2014 the number fills the box, enter runs it.`);let d=l.join(" "),h=t.filter(w=>w.bullet).map(w=>{let x=i.get(w.key),[S="",...$]=(x&&w.lead?.kind==="prompt"&&w.rowBullet?w.rowBullet:w.bullet).split(`
|
|
403
|
+
\u2022 `);if(x&&w.lead){let R=S.replace(/^→\s+/,"");return[` ${x}. ${g$(w.lead)} \u2014 ${R}${w$(w,i,x)}`,...$.map(Y=>` ${Y}`)].join(`
|
|
404
|
+
`)}let T=w.lead?.kind==="cmd"?w.lead.cmd:null;return` \u2022 ${w.bullet}${T&&!d.includes(T)?` \u2014 ${T}`:""}`}),m=[[e,...h].join(`
|
|
405
|
+
`)];return l.length&&m.push(l.join(" ")),m.push(h$),{note:m.join(`
|
|
406
|
+
|
|
407
|
+
`),menu:s.map(w=>y$(w.lead))}}function Qo(e,t){let n=t?.pickable===!0,o=h=>t?.header?`${t.header}
|
|
408
|
+
|
|
409
|
+
${h}`:h;if(!e.ready)return{kind:"idle"};if(e.pendingAnswer)return{kind:"recommend",rec:{note: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:[]}};let r=m$(e);if(!e.hasDocs){let h=Nh(r);if(h&&(h.lead?.kind==="cmd"||h.picker)){let m=Ul(t?.header??"\u{1F4ED} No docs yet for this repo \u2014 here\u2019s where things stand:",r,n);return{kind:"recommend",rec:{note:m.note,tone:h.tone??"info",lead:h.lead,picker:h.picker,menu:m.menu}}}return{kind:"recommend",rec:{note:o(f$),tone:"info",lead:{kind:"prompt",text:"write the docs for this repo",reason:"I\u2019ll read the code and draft a structure"},picker:null,menu:[]}}}if(r.length===0){let h=e.roadmap&&!e.roadmap.next?` Docs campaign complete \u2014 all ${e.roadmap.total} step${ye(e.roadmap.total)} done (/roadmap).`:"";return{kind:"recommend",rec:{note:o(`Welcome back. Your ${e.tracked} tracked article${ye(e.tracked)} for \u201C${e.profileName}\u201D are all in sync \u2014 /audit re-checks the code, /pull brings down portal edits.${h}`),tone:"info",lead:null,picker:null,menu:[]}}}let s=r.filter(h=>h.lead||h.picker),i=s[0]??null;if(!i){let h=Ul(t?.header??"Welcome back \u2014 where your docs stand:",r,n);return{kind:"recommend",rec:{note:h.note,tone:"info",lead:null,picker:null,menu:h.menu}}}if((i.key==="audit"||s[1]?.key==="audit")&&e.behind>0&&e.autoAudit&&e.allowAutoAudit)return{kind:"autoAudit",note:o(`\u{1F4CB} ${e.behind} code change${ye(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`)};let d=Ul(t?.header??"Welcome back \u2014 where your docs stand:",r,n);return{kind:"recommend",rec:{note:d.note,tone:i.tone??"info",lead:i.lead,picker:i.picker,menu:d.menu}}}import{existsSync as Is,readdirSync as Fl}from"node:fs";import{spawnSync as k$}from"node:child_process";import{join as Os}from"node:path";import{readProjectConfig as Oh,resolveActiveProfile as Lh,loadTokens as b$,isExpired as $$,loadProfileMap as _h,localAheadPaths as v$,loadKnownConflicts as x$,loadOpenCommentCount as R$,readDocsPlan as C$,devHintsGuidePath as S$,DEFAULT_DOCS_DIR as Wl,roadmapProgress as P$,listRoadmap as T$,readProductBriefState as E$,reconcileCommitRequest as A$,reconcileTestidRequest as D$,snapshotHandoff as j$,shareExplainedPath as N$}from"document360-engine";Ot();function Ih(e){try{return Fl(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function Bl(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>Ih(Os(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&Ih(Os(e,o)))}function Hl(e,t){try{let n=Oh(e);if(!n)return!1;let o=Lh(e,t),r=_h(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=Os(e,(n.docsDir??Wl).replace(/\/+$/,""));return!!(Is(s)&&Fl(s).length>0||Is(S$(e)))}catch{return!1}}function Jo(e,t,n){try{let o=Oh(e);if(!o)return null;let r=Lh(e,t),s=b$(r.name),i=!!s&&(!$$(s)||!!s.refreshToken),l=Hl(e,t)||!Bl(e,o.authoritativeSourceFiles),d=_h(e,r.name),h=d?Object.keys(d.articles).length:0,m=Os(e,(o.docsDir??Wl).replace(/\/+$/,"")),w=!1;try{w=Is(m)&&Fl(m).length>0}catch{}let x=0;if(d?.lastAnalyzedCommit)try{let Se=k$("git",["rev-list","--count",`${d.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});Se.status===0&&(x=parseInt((Se.stdout||"").trim(),10)||0)}catch{}let S=0;try{let Se=C$(e);if(Se.length>0){let Qe=(o.docsDir??Wl).replace(/\/+$/,"");S=Ma(e,Qe,Se.map(xt=>xt.path)).length}}catch{}let $=hn(e),T=Ko({...$,directives:0}),R=v$(e,t),I=new Set(x$(e,r.name)),Y=R.filter(Se=>I.has(Se)).length,q=R.length-Y,z=un(e,R.filter(Se=>!I.has(Se))).length,ae=R$(e,r.name),xe=ot(e),ke=P$(e),Ee=j$(e,o),ge=A$(e,new Date().toISOString(),{supersededByHandoff:Ee!==null});D$(e,new Date().toISOString());let K=jt(e,t),pe=K?{name:K.name,replacement:K.replacement,replacementProfile:K.replacementProfile}:null,le=E$(e),Ce=le?{status:le.status,openQuestions:le.openQuestions}:null;return!Ce&&w&&T$(e).some(Qe=>Qe.status==="open"&&(Qe.run??"").trim()==="/discover")&&(Ce={status:"pending",openQuestions:0}),{ready:i&&l&&!n.claudeMissing,hasDocs:w,tracked:h,pendingText:T,directives:$.directives,behind:x,pendingWrites:S,localAhead:q,unreviewed:z,conflicts:Y,openComments:ae,autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:xe.status,devhintsCompletedVersion:xe.completedVersion,devhintsToVersion:ve,builderStarted:bt(e),genreUnknown:n.genreUnknown,pendingAnswer:n.pendingAnswer??null,roadmap:ke,discovery:Ce,uncommittedDocs:ge.dirty.length,handoff:Ee,shareExplained:Is(N$(e)),sunsetEnv:pe}}catch{return null}}Q();import{existsSync as I$,readFileSync as O$}from"node:fs";import{isAbsolute as L$,join as _$}from"node:path";import{DEFAULT_DOCS_DIR as M$,findPathByArticleId as U$,isArticleDocPath as W$,loadProfileMap as F$,readProjectConfig as B$,resolveActiveProfile as H$}from"document360-engine";var q$=70;function G$(e,t){return{docsRoot:()=>(B$(e)?.docsDir??M$).replace(/\\/g,"/").replace(/\/+$/,""),read:n=>{try{let o=L$(n)?n:_$(e,n);return I$(o)?O$(o,"utf8"):null}catch{return null}},pathForArticleId:n=>{try{let o=F$(e,H$(e,t).name);return o?U$(o,n):null}catch{return null}}}}var Zo=(e,t=q$)=>{let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"};function er(e){if(!e)return null;let t=!1;for(let n of e.split(`
|
|
410
|
+
`)){let o=n.trimEnd();if(/^\s*(```|~~~)/.test(o)){t=!t;continue}if(t)continue;let r=/^#\s+(\S.*)$/.exec(o);if(r)return Zo(r[1])}return null}var V$=new Set(["a","an","and","as","at","but","by","for","in","of","on","or","the","to","vs","with"]),Y$=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 Mh(e,t,n){let o=e.toLowerCase();return Y$.has(o)?e.toUpperCase():!t&&V$.has(o)?o:!t&&!n?e:e.charAt(0).toUpperCase()+e.slice(1)}var Uh=e=>e.replace(/^\d+[-_.]/,"").split(/[-_]/).filter(Boolean);function K$(e){let t=Uh(e);return t.length===0?e:t.map((n,o)=>Mh(n,o===0,!0)).join(" ")}function Wh(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:K$(n[n.length-2])}function Fh(e){let t=e.replace(/\\/g,"/").split("/").pop()??e,n=Uh(t.replace(/\.(md|markdown)$/i,""));return n.length===0?t:n.map((o,r)=>Mh(o,r===0,!1)).join(" ")}var ze=e=>typeof e=="string"&&e?e:null,z$=e=>typeof e=="string"&&e.length>=8?`id ${e.slice(0,8)}\u2026`:null;function X$(e,t){let n=i=>i.replace(/\\/g,"/").replace(/\/+$/,""),o=e.replace(/\\/g,"/"),r=`${n(t)}/`;return(process.platform==="win32"?o.toLowerCase().startsWith(r.toLowerCase()):o.startsWith(r))?o.slice(r.length):o}function Q$(e,t){let n=Ke(e,t,200);return n?`+${n.added} \u2212${n.removed}`:"no change"}var J$=new Set(["Edit","MultiEdit","Write"]);function Z$(e,t,n,o){if(!J$.has(e))return null;let r=ze(t.file_path);if(!r)return null;let s=X$(r,n),i=o.docsRoot();if(!(s===i||s.startsWith(`${i}/`)))return null;let l=s.slice(i.length+1);if(!l||!W$(l))return null;let d=Wh(l),h=o.read(s),m=$=>er($)??er(h)??Fh(l);if(e==="Write"){let $=ze(t.content)??"",T=m($);if(h===null){let R=$.replace(/\n$/,"").split(`
|
|
411
|
+
`).length;return{verb:"Draft",title:T,category:d,note:`new, ${R} lines`}}return{verb:"Rewrite",title:T,category:d,note:Q$(h,$)}}let w=Array.isArray(t.edits)?t.edits.map($=>({from:ze($.old_string)??"",to:ze($.new_string)??""})):[{from:ze(t.old_string)??"",to:ze(t.new_string)??""}],x=w.reduce(($,T)=>{let R=Ke(T.from,T.to,200);return R?{added:$.added+R.added,removed:$.removed+R.removed}:$},{added:0,removed:0}),S=x.added===0&&x.removed===0?"no change":`+${x.added} \u2212${x.removed}`;return{verb:"Update",title:m(w.map($=>$.to).join(`
|
|
412
|
+
`)),category:d,note:S}}function ev(e,t,n){let o=()=>{let r=ze(t.article_id),s=r?n.pathForArticleId(r):null;return(s?er(n.read(s)):null)??(s?Fh(s):z$(r)??"article")};switch(e){case"d360_create_article":{let r=ze(t.title);return r?{verb:"Create",title:Zo(r),category:Wh(t.local_path),note:"Document360 draft"}:null}case"d360_update_article":return{verb:"Update",title:ze(t.title)?Zo(ze(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=ze(t.name);return r?{verb:"Create",title:Zo(r),category:null,note:"Document360 category"}:null}case"d360_upload_drive_file":{let r=ze(t.file_path);if(!r)return null;let s=r.replace(/\\/g,"/").split("/").pop()??r;return{verb:"Upload",title:Zo(s),category:null,note:"Document360 Drive",keepResult:!0}}default:return null}}function Ls(e,t,n,o,r=G$(n,o)){try{let s="mcp__document360__";return e.startsWith(s)?ev(e.slice(s.length),t,r):Z$(e,t,n,r)}catch{return null}}var tv={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"},Hh=160,ql=200,qh=40;function Bt(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function Bh(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}: ${Bt(typeof r=="string"?r:JSON.stringify(r),qh)}`);return t.length>4&&n.push("\u2026"),Bt(n.join(", "),Hh)}var nv=new Set(["file_path","notebook_path"]);function ov(e,t){if(!t)return e;let n=i=>i.replace(/\\/g,"/").replace(/\/+$/,""),o=n(e),r=`${n(t)}/`;return(process.platform==="win32"?o.toLowerCase().startsWith(r.toLowerCase()):o.startsWith(r))?o.slice(r.length):e}var Gh=e=>typeof e=="string"&&e?e:null;function rv(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});return e==="d360_sync_status"?n("Check sync status",null):null}function _s(e,t,n){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,s="",...i]=e.split("__"),l=i.join("__");if(s==="document360"){let m=rv(l,t);if(m)return m}let d=l.replace(/^d360_/,"").replace(/_/g," ");return{title:`${s==="document360"?"Document360":s.charAt(0).toUpperCase()+s.slice(1)}: ${d}`,sep:" ",arg:Bh(t)}}let o=tv[e],r=o?t[o]:void 0;if(typeof r=="string"&&r){let s=o&&nv.has(o)?ov(r,n):r;return{title:e,sep:"",arg:Bt(s,Hh)}}return{title:e,sep:"",arg:Bh(t)}}function sv(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 iv(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(sv).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>Bt(r,ql))]}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}: ${Bt(String(r),qh)}`);return n.length>0?[Bt(n.join(" \xB7 "),ql)]:null}return null}function av(e){let t=Gh(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function lv(e,t,n){switch(e){case"d360_create_article":{let o=av(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=Gh(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 ${Bt(o[0],120)}`:""}`]}default:return null}}var Vh=new Set(["Edit","Write","MultiEdit","NotebookEdit"]);function cv(e){return e.replace(/^\s*\d+\t/,"")}function uv(e,t){if(Vh.has(e))return[];let n=t.split(`
|
|
413
|
+
`);if(e==="Read"){let o=n.length,r=er(n.map(cv).join(`
|
|
414
|
+
`));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 Ms(e,t=4,n,o){let r=e.replace(/\r\n/g,`
|
|
415
|
+
`).trimEnd();if(n&&Vh.has(n))return{lines:[],hidden:0};if(!r)return{lines:["(no output)"],hidden:0};if(n&&!n.startsWith("mcp__")){let i=uv(n,r);if(i)return{lines:i,hidden:0}}if(n?.startsWith("mcp__document360__")){let i=lv(n.slice(18),o,r);if(i)return{lines:i,hidden:0}}let s=iv(r)??r.split(`
|
|
416
|
+
`);return{lines:s.slice(0,t).map(i=>Bt(i,ql)),hidden:Math.max(0,s.length-t)}}function Us(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function Ws(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 Yh(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 Fs(e){return Yh(e,"url")}function Bs(e){return Yh(e,"preview_url")}var Jh=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/,Vl=null;function zh(){return Vl===null&&(Vl=bv().verboseTranscript===!0),Vl}function Iv(e,t,n,o){if(Jh.test(e))try{let r=Qh(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,i=Ws(t,n),l=Fs(n);e.endsWith("publish_article")&&l&&console.log(G(` \u2B95 Live: ${l}`));let d=Bs(n);d?console.log(G(` \u2B95 Preview: ${d}`)):i&&s&&console.log(G(` \u2B95 Preview: ${Us(r.connection.portalUrl,s,i,r.project.languageCode??"en")}`))}catch{}}async function Zh(e=process.cwd(),t="auto",n,o){let r=pv(t);r.kind==="none"&&(console.error(""),console.error(j("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${G("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${G('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${G("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${G("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),Ov(e,n),r.kind==="subscription"&&(r.stored?console.log(k(" Using your Claude subscription (no API key set).")):console.log(k(" No API key or stored Claude Code login found \u2014 trying your Claude session anyway.")),console.log(""));let s=!1,i=Gl({cwd:e,profileName:n,allowProdWrites:s}),l={uuid:null,firstPrompt:null,titleFired:!1},d=dv({input:process.stdin,output:process.stdout}),h=[],m=null,w=!1;d.on("line",$=>{if(m){let T=m;m=null,T($)}else h.push($)}),d.on("close",()=>{if(w=!0,m){let $=m;m=null,$(null)}});function x(){return h.length>0?Promise.resolve(h.shift()):w?Promise.resolve(null):(process.stdout.write(G("> ")),new Promise($=>{m=$}))}let S={cwd:e,version:o,profileName:n,allowProdWrites:()=>s,restartAgent:()=>{i.close(),i=Gl({cwd:e,profileName:n,allowProdWrites:s}),l={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>l.uuid,setPendingName:$=>{l.pendingName=$},setModel:async $=>i.setModel($),withPausedInput:async $=>{d.pause();try{return await $()}finally{d.resume()}}};try{for(;;){let $=await x();if($===null)break;let T=$.trim();if(T){if(T.startsWith("/")){let R=Dh(T);if(!R)continue;let I=Ah[R.name];if(!I){console.log(j(`Unknown command: /${R.name}`)),console.log(k("Type /help for the list."));continue}let Y=await I(R.args,S);if(Y.kind==="exit")break;if(Y.kind==="clear"){S.restartAgent();continue}if(Y.kind==="allow-prod"){s=!0,S.restartAgent(),console.log(U("\u2713 Production writes authorized for this session.")),console.log("");continue}if(Y.kind==="resume"){i.close(),i=Gl({cwd:e,resume:Y.uuid,profileName:n,allowProdWrites:s});let q=hv(Y.uuid);l={uuid:Y.uuid,firstPrompt:q?.firstPrompt??null,titleFired:!0},Xh(Y.uuid),console.log(U(`\u2713 Resumed "${Y.name}"`)),console.log("");continue}if(Y.kind==="forward-to-agent"){l.firstPrompt||(l.firstPrompt=Y.display??Y.prompt);let q=(Y.display??"").trim().split(/\s+/),z=(q[0]==="/check"||q[0]==="/review")&&q.includes("--fix"),ae=q.slice(1).find(ge=>!ge.startsWith("--")),xe=z?Ev(e,ae):[],ke=q[0]==="/screenshot"&&(q[1]==="verify"||q[1]==="review"),Ee=ke?q[2]&&!q[2].startsWith("--")?[q[2]]:Bo(Pe(e)):[];if(await Yl(i,Y.prompt,r,l,e,n),z)try{Tv(e,xe,{reviewedCap:Av})}catch{}if(ke&&Ee.length>0)try{for(let ge of qo(e,Ee))console.log(ge)}catch{}if(q[0]==="/publish"){let ge=await Fn(e,n);ge&&console.log(k(ge))}if((q[0]==="/catch-up"||q[0]==="/document")&&q.includes("--publish"))try{let ge=await Nv({cwd:e,profileName:n}),{clean:K,conflicts:pe}=cn(ge.entries);K.length===0?console.log(k("Nothing new to publish \u2014 everything is already up to date on Document360.")):await dt(S,K.map(le=>le.path),pe.length,{skipReview:q.includes(pt)})}catch(ge){console.log(W(`Couldn't check what to publish (${ge.message}) \u2014 your drafts are saved; run /publish when ready.`))}}else Lv(e,n);continue}if(Rv(T)){let R=Cv(T);if(R){try{Sv(e,{title:R,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}l.firstPrompt||(l.firstPrompt=T),await Yl(i,`The owner left this documentation directive (already recorded in .d360-writer/directives.md): "${R}". 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 "${R}" and the article path(s) you wrote.`,r,l,e,n);continue}}l.firstPrompt||(l.firstPrompt=T),await Yl(i,T,r,l,e,n)}}}finally{i.close(),d.close()}}function Ov(e,t){console.log(""),console.log(bo("document360-writer")),console.log(k(` cwd: ${e}`));let n=wv(e);if(console.log(k(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(_v(e,t)),!kv(e))console.log(W(" 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(Br(e),!bt(e))for(let r of Hr(e))console.log(W(` ${r}`))}catch{}try{let r=$v(e);r.persisted&&r.appType?console.log(k(` \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=Pv(e);for(let s of Mr(r.applied))console.log(W(` ${s}`));if(r.reopenedForRedaction)for(let s of Ur(r.reopenedForRedaction).split(/\r?\n/))console.log(W(` ${s}`))}catch{}try{let r=Jo(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:o}),s=r?Qo(r,{pickable:!1}):null;if(s?.kind==="recommend"&&s.rec.note){let i=s.rec.tone==="warn"?W:k;for(let l of Vi(s.rec.note).split(`
|
|
417
|
+
`))console.log(i(` ${l}`));s.rec.picker&&console.log(G(` Pick one: ${s.rec.picker.options.map(l=>l.cmd).join(" \xB7 ")}`))}}catch{}}console.log(k(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function Lv(e,t){try{let n=Jo(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:!1}),o=n?Qo(n):null;o?.kind==="recommend"&&o.rec.lead&&console.log(k(` Next: ${Xo(o.rec.lead)}`))}catch{}}function _v(e,t){try{let n=Qh(e,t),o=n.production?W(" \u26A0 PRODUCTION"):"",r=xv(n.name);if(!r)return k(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...Kh(r.idToken)??{},...Kh(r.accessToken)??{}},i=s.email??s.preferred_username??"signed in";return vv(r)&&!r.refreshToken?W(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):k(` Document360: ${i} \xB7 profile "${n.name}"${o}`)}catch(n){return k(` Document360: ${n.message.split(".")[0]}`)}}function Mv(){console.error(""),console.error(`Sign in with your Claude subscription: run ${G("claude")} once, then retry.`),console.error(` (No Claude Code? ${G("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${G("https://console.anthropic.com/settings/keys")}`)}function Uv(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;gv({uuid:t,name:r??mv(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function Wv(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||yv(o,t).then(r=>{r&&fv(n,r)}).catch(()=>{})}async function Yl(e,t,n,o,r,s){let i=new Map,l=!1;for await(let d of e.send(t))d.type==="tool"&&Jh.test(d.name)&&(l=!0),Fv(d,o,r,n,i,s);if(l)try{let d=jv(await Dv({cwd:r,profileName:s}));d&&console.log(d.startsWith("\u26A0")?W(d):d)}catch{}}function Fv(e,t,n,o,r,s){switch(e.type){case"session":t.uuid||Uv(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let i=zh()?null:Ls(e.name,e.input,n,s);if(i){process.stdout.write(`
|
|
418
|
+
|
|
419
|
+
`);let d=[i.category,i.note].filter(m=>!!m).map(m=>he(` \xB7 ${m}`)),h=i.loud?he(" \xB7 ")+je(W(i.loud)):"";console.log(`${U("\u25CF")} ${G(je(Gi(i.verb)))}${je(i.title)}${d.join("")}${h}`),r.set(e.id,{name:e.name,input:e.input,doc:!0,keepResult:i.keepResult});break}let l=_s(e.name,e.input,process.cwd());l&&(process.stdout.write(`
|
|
420
|
+
|
|
421
|
+
`),console.log(`${he("\u25CF")} ${l.title}${l.arg!==null?he(`${l.sep}(${l.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let i=Ke(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!i)break;let l=d=>d===1?"":"s";console.log(he(` \u23BF Added ${i.added} line${l(i.added)}, removed ${i.removed} line${l(i.removed)}`));for(let d of i.lines)console.log(d);i.hidden>0&&console.log(k(` \u2026 +${i.hidden} more diff lines`));break}case"tool_result":{let i=r.get(e.id);if(!i)break;r.delete(e.id);let d=i.doc&&!i.keepResult&&!e.isError?{lines:[],hidden:0}:Ms(e.output,4,e.isError||zh()?void 0:i.name,i.input),h=e.isError?j:he;d.lines.forEach((m,w)=>console.log(h((w===0?" \u23BF ":" ")+m))),d.hidden>0&&console.log(k(` \u2026 +${d.hidden} lines`)),e.isError||Iv(i.name,i.input,e.output,n);break}case"result":{process.stdout.write(`
|
|
422
|
+
`);let i=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(k(` (${So(i)}\u2192${So(e.outputTokens)} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(Xh(t.uuid),t.titleFired||Wv(t,n));break}case"error":console.error(""),e.kind==="limit"?console.log(W(`\u23F3 ${e.message}`)):console.error(j(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&Mv();break}}import{render as w0}from"ink";import{resolveAuth as k0}from"document360-engine";import{useCallback as X,useEffect as He,useMemo as oc,useRef as re,useState as Z}from"react";import{Box as we,Text as M,useApp as px,useInput as hx,useStdout as fx}from"ink";import{existsSync as zn,readFileSync as Qs,readdirSync as mx,writeFileSync as gx}from"node:fs";import{basename as rr,dirname as yx,isAbsolute as wx,join as rc}from"node:path";import{createSession as Wf,classifyClaudeAuth as dc,CLAUDE_CODE_SETUP_HINT as kx,loginPkce as bx,toStoredTokens as $x,saveTokens as vx,getAccessToken as xx,resolveActiveProfile as Xe,resolveProjectId as Rx,getArticle as Cx,decodeJwtClaims as Zn,isExpired as Ht,loadTokens as mn,clearTokens as Sx,clearProfileProject as Px,setTitle as Tx,slugify as Ex,touchSession as sc,upsertSession as Ax,generateTitle as Ff,findByName as Dx,listSessions as jx,renameSession as Nx,suggestNextAction as Ix,readProjectConfig as ue,writeProjectConfig as Bf,readUserConfig as Hf,writeUserConfig as Ox,resolveAndPersistAppType as Lx,detectAppType as qf,resolveModelSetting as pc,loadProfileMap as Gf,applyPull as Js,computeSyncStatus as Zs,lintDocs as Vf,compareRemoteSources as _x,planPull as Yf,establishBaselines as Mx,rebaselineServerMeta as Ux,inventoryRepo as Wx,knownEnvironments as Fx,currentEnvironments as Kf,sunsetEnvironment as zf,resolveEnvironment as Bx,planPartitions as ic,partitionEvenly as Hx,screenshotPlaceholderIds as qx,trackedArticlePaths as Gx,runPartitioned as ei,estimateBulkCost as Xf,resolveModelForOperation as ti,readDocsPlan as Qf,checkForUpdate as Vx,detectInstallKind as Yx,isSelfUpdatable as Kx,devHintsGuidePath as Jf,toolFeedbackPath as Zf,reconcileToolFeedback as zx,reconcileUpgradeActions as Xx,stampArticles as ac,listArticleFiles as em,CONTENT_CAP_VERSION as lc,ENGINE_VERSION as am,DEFAULT_DOCS_DIR as hc,setProfileProject as Qx,writeCrashLog as Jx,applyStructureOrder as cc,orderSyncLine as uc,applyRelatedArticles as tm,relatedSyncLine as nm,reconcileDocsGit as Zx,shareExplainedPath as e0,ensureDir as t0}from"document360-engine";To();Ot();import{spawn as ef}from"node:child_process";function Bv(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function Hv(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?ef([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):ef(e,t,{stdio:["pipe","ignore","ignore"]});r.on("error",()=>o(!1)),r.on("close",i=>o(i===0)),r.stdin?.on("error",()=>o(!1));let s=process.platform==="win32"?Buffer.from("\uFEFF"+n,"utf16le"):Buffer.from(n,"utf8");r.stdin?.end(s)}catch{o(!1)}})}async function Kl(e){for(let[t,n]of Bv())if(await Hv(t,n,e))return!0;return!1}var tf=/\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 qv(e){let t=e.replace(/\s+$/,"").split(`
|
|
423
|
+
`),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}function nf(e){let t=e.trimEnd();if(!t)return null;let n=qv(t);return n>=2?{options:n}:/\?[\s*_"')\]]*$/.test(t)||tf.test(t)?{options:0}:null}function zl(e,t){if(t.closed)return e;let n=e.split(`
|
|
424
|
+
`),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){tf.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(`
|
|
425
|
+
`)}var Gv={la:"local","l all":"local","local all":"local",pa:"portal","p all":"portal","portal all":"portal",sa:"skip","s all":"skip","skip all":"skip"},Vv={L:"local",P:"portal",S:"skip"},Yv={ya:"write","y all":"write","yes all":"write",na:"skip","n all":"skip","no all":"skip"},Kv={Y:"write",N:"skip"};function of(e,t,n){let o=e.trim(),r=o.toLowerCase().replace(/\s+/g," ");return t[r]??(o.length===1?n[o]??null:null)}function rf(e){return of(e,Gv,Vv)}function sf(e){return of(e,Yv,Kv)}function Xl(e,t){let n=t?.max??12,o=t?.chrome??8;return Math.max(3,Math.min(n,(e??24)-o))}function Hs(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}}import{existsSync as zv,mkdirSync as Xv,readFileSync as Qv,writeFileSync as Jv}from"node:fs";import{join as af}from"node:path";import{writerDir as Zv}from"document360-engine";function lf(e){return af(Zv(e),".sessions")}function cf(e,t){return af(lf(e),`${t}.json`)}function uf(e,t,n){try{Xv(lf(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");Jv(cf(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function Ql(e,t){try{let n=cf(e,t);if(!zv(n))return[];let o=JSON.parse(Qv(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var ex=e=>`\x1B]0;${e}\x07`,tx=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function df(e){process.stdout.isTTY&&process.stdout.write(e)}function Yn(e){df(ex(e))}function qs(e){df(tx(e))}var Gs=["\xB7 "," \xB7"],Vs="\u{1F7E3}";$s();var pf=()=>({fingerprint:null,counts:null,settled:0,spokenBaseline:null,lastSpokeAt:null,awaySince:null}),nx={hints:0,requests:0,answers:0,directives:0};function Jl(e,t){let n=e??nx;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)}}var Ys=e=>e.hints===0&&e.requests===0&&e.answers===0&&e.directives===0,hf=e=>e.hints+e.requests+e.answers+e.directives,Zl=(e,t)=>e-t>=6e5;function ff(e){let{now:t,lastInputAt:n,fingerprint:o,counts:r,occupied:s,prev:i}=e,l=Zl(t,n),h=i.fingerprint!==null&&i.fingerprint!==o?0:i.settled+1,m={...i,fingerprint:o,counts:r,settled:h,awaySince:l?i.awaySince??t:null,spokenBaseline:i.spokenBaseline??r};if(l){let x=Jl(m.spokenBaseline,r);return{memory:m,speak:null,waiting:Ys(x)?null:x}}if(s)return{memory:m,speak:null,waiting:null};if(h<2)return{memory:m,speak:null,waiting:null};let w=Jl(i.spokenBaseline,r);return Ys(w)?{memory:m,speak:null,waiting:null}:i.lastSpokeAt!==null&&t-i.lastSpokeAt<6e5?{memory:m,speak:null,waiting:null}:{memory:{...m,spokenBaseline:r,lastSpokeAt:t,settled:h},speak:w,waiting:null}}function mf(e,t,n){if(e.awaySince===null)return{kind:"none",memory:e};let o=t-e.awaySince,r=Jl(e.spokenBaseline,n),s={...e,awaySince:null,counts:n,spokenBaseline:n,lastSpokeAt:Ys(r)?e.lastSpokeAt:t};return Ys(r)?{kind:"none",memory:s}:{kind:o>=36e5?"briefing":"delta",memory:s,delta:r,awayMs:o}}function tr(e){let t=[];return e.hints&&t.push(`${e.hints} hint${e.hints===1?"":"s"}`),e.requests&&t.push(`${e.requests} request${e.requests===1?"":"s"}`),e.answers&&t.push(`${e.answers} answer${e.answers===1?"":"s"}`),e.directives&&t.push(`${e.directives} directive${e.directives===1?"":"s"}`),t.length===0?"":t.length===1?t[0]:`${t.slice(0,-1).join(", ")} and ${t.at(-1)}`}function ec(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 gf(e){return`\u{1F4E5} ${tr(e)} just arrived from your builder \u2014 /catch-up folds ${hf(e)===1?"it":"them"} into the docs.`}function yf(e,t){return`\u{1F4E5} While you were away (${ec(t)}): ${tr(e)} from your builder \u2014 /catch-up folds ${hf(e)===1?"it":"them"} into the docs.`}function wf(e){return`\u{1F4E5} ${tr(e)} waiting from your builder \xB7 tab to run /catch-up\u2026`}Vr();Q();import{Box as nr,Text as be}from"ink";import{jsx as $e,jsxs as Kn}from"react/jsx-runtime";function ox({row:e,nameW:t,width:n}){let o=s=>Ei(s,n),r=(s,i)=>$e(nr,{flexDirection:"column",children:s.map(i)});switch(e.t){case"head":return r(o(e.s),(s,i)=>$e(be,{color:te,bold:!0,children:s},i));case"text":return r(o(e.s),(s,i)=>$e(be,{children:s},i));case"dim":return r(o(e.s),(s,i)=>$e(be,{dimColor:!0,children:s},i));case"sub":return r(o(e.s),(s,i)=>$e(be,{bold:!0,dimColor:!0,children:s},i));case"good":return r(o(e.s),(s,i)=>$e(be,{color:"green",children:s},i));case"step":{let s=o(`${e.n}. ${e.s}`);return $e(nr,{flexDirection:"column",children:s.map((i,l)=>l===0?Kn(be,{children:[$e(be,{color:te,children:`${e.n}. `}),i.slice(`${e.n}. `.length)]},l):$e(be,{children:i},l))})}case"cmd":{let s=Wr(e.name,e.s,t,n),i=s.descLines.slice(s.nameOwnLine?0:1);return Kn(nr,{flexDirection:"column",children:[Kn(be,{children:[" ",$e(be,{color:te,children:s.nameCell}),!s.nameOwnLine&&$e(be,{dimColor:!0,children:` ${s.descLines[0]??""}`})]}),i.map((l,d)=>$e(be,{dimColor:!0,children:`${s.indent}${l}`},d))]})}case"gap":return $e(be,{children:" "})}}function kf({tab:e,scroll:t,rows:n,width:o,version:r,engineVersion:s}){let i=Ue[e]??Ue[0],l=Ti(i.rows),d=Math.max(20,o-2),h=6+Ue.reduce((R,I)=>R+I.label.length+4,0),m="\u2500".repeat(Math.min(h,d)),w=`\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=mu({rows:n,inner:d,barWidth:h,footerWidth:w.length}),{visible:S,above:$,below:T}=fu(i.rows,{width:o,budget:x,scroll:t,nameW:l});return Kn(nr,{flexDirection:"column",paddingX:1,children:[Kn(be,{children:[$e(be,{color:te,bold:!0,children:"Help "}),Ue.map((R,I)=>I===e?$e(be,{color:"white",backgroundColor:te,bold:!0,children:` ${R.label} `},R.key):$e(be,{dimColor:!0,children:` ${R.label} `},R.key))]}),$e(be,{color:te,children:m}),Kn(nr,{flexDirection:"column",marginTop:1,children:[$>0?$e(be,{dimColor:!0,children:`\u22EF ${$} more above`}):null,S.map((R,I)=>$e(ox,{row:R,nameW:l,width:o},$+I)),T>0?$e(be,{dimColor:!0,children:`\u22EF ${T} more below`}):null]}),$e(be,{dimColor:!0,children:`
|
|
426
|
+
\u2190/\u2192 or tab switch \xB7 1-5 jump${$+T>0?" \xB7 \u2191\u2193 scroll":""} \xB7 esc close \xB7 d360-writer v${r} \xB7 engine v${s}`})]})}var rx=/^(?:\d+[.)]|[-*•])\s+/;function bf(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
|
|
427
|
+
`)){let i=s.trim().replace(rx,""),l=i.match(/^`([^`]+)`$/);l&&(i=l[1].trim());let d=i.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!d||!o.has(d[1].toLowerCase()))continue;let h=`/${d[1].toLowerCase()}${d[2]?` ${d[2]}`:""}`;if(r.includes(h)||r.push(h),r.length>=n)break}return r}Q();function or(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function rt(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function $f(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var sx=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function vf(e,t,n){if(!sx.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 tc(e){return e.replace(/^[\w.-]+\//,"")}var Ks=16,xf={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function fn(e){return typeof e=="string"?e:e.cmd}function Rf(e){return typeof e=="string"?void 0:e.desc}function nc(e){return e.trim().split(/\s+/).slice(1).join(" ")}function Cf(e,t){let n=nc(t);return e.some(r=>fn(r).trim()===t.trim()||!!n&&nc(fn(r))===n)?e.filter(r=>fn(r).trim()!==t.trim()&&!(n&&nc(fn(r))===n)):[]}import{isDirectiveMention as n0,stripDirectiveMention as o0,appendDirective as r0,reconcileTestidRequest as s0,builderChannelWired as i0,pendingFingerprint as a0}from"document360-engine";var ix=/\[Pasted text #\d+ \+\d+ lines?\]/g;function Sf(e){return e.replace(/\r\n?/g,`
|
|
428
|
+
`)}function Pf(e){return e.includes(`
|
|
429
|
+
`)||e.length>200}function Tf(e,t){let n=t.split(`
|
|
430
|
+
`).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function Ef(e,t){return e.replace(ix,n=>t.get(n)??n)}function Af(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function zs(e,t){let n=Math.max(1,t),o=[],r=0;for(let s of e.split(`
|
|
431
|
+
`)){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 Xs(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function Df(e,t,n){let o=Xs(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 jf(e,t,n){let o=e[Xs(e,t)];return n==="start"?o.start:o.end}var ax=new Set(["Edit","Write","MultiEdit","NotebookEdit"]),Nf={hint:"hint",message:"message",state:"state file",roadmap:"roadmap",directive:"directives",feedback:"tool-feedback"},lx=new Set(["hint","message","state"]),cx=["hint","message","roadmap","directive","feedback","state"];function ux(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 If(e,t){let n=e==="Read"?"read":ax.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 l=ux(r.slice(i+s.length));return l?{category:l,verb:n,path:r}:null}function Of(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 cx)for(let s of["updated","read"]){let i=t.get(`${r}:${s}`)?.size??0;i!==0&&o.push(lx.has(r)?`${i} ${Nf[r]}${i===1?"":"s"} ${s}`:`${Nf[r]} ${s}`)}return o.length>0?o.join(" \xB7 "):null}function Lf(e,t,n){let o=Math.max(1,n),r=e.split(`
|
|
432
|
+
`),s=0;for(let i=r.length-1;i>=0;i--){let l=r[i];if(s+=Math.max(1,Math.ceil(l.length/o)),s>=t){let d=s-t;return{text:[d>0?l.slice(d*o):l,...r.slice(i+1)].join(`
|
|
433
|
+
`),truncated:i>0||d>0}}}return{text:e,truncated:!1}}function _f(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 Mf(e){let t=!1,n=0,o=0;for(let r of e.split(`
|
|
434
|
+
`)){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 Jn,jsx as L,jsxs as oe}from"react/jsx-runtime";var l0={project:".d360-writer/config.json",user:"/model",env:"ANTHROPIC_MODEL",auto:"auto \u2014 right-sized for docs \xB7 /model to change"},om=` 1. /init \u2014 pick your Document360 environment & scaffold config
|
|
435
435
|
2. /login \u2014 sign in & pick your Document360 project (workspace auto-selected)
|
|
436
|
-
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function
|
|
437
|
-
`)}catch{}c.picker&&(
|
|
438
|
-
`)}),
|
|
439
|
-
${
|
|
440
|
-
Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!
|
|
441
|
-
${
|
|
442
|
-
`)}),
|
|
443
|
-
`)}),y.reopenedForRedaction&&p({kind:"note",tone:"warn",text:
|
|
436
|
+
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function c0(e,t,n,o){let r=dc(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=pc(e),l=ue(e),d=(l?.docsDir??hc).replace(/\/+$/,""),h=l?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${d}/ + config`,m={version:t,engineVersion:am,captureVersion:vt(),claude:s,model:i.model,modelSource:l0[i.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:l!==null,mode:h};if(l===null)return m;try{let w=Xe(e,o);m.profile=w.name,m.apiUrl=w.connection.apiUrl,m.prod=w.production,m.project=w.project.projectName??w.project.projectId??"(chosen at login)";let x=mn(w.name);if(x){let S={...Zn(x.idToken)??{},...Zn(x.accessToken)??{}},$=S.email??S.preferred_username??"signed in";Ht(x)?x.refreshToken&&(m.who=$,m.loggedOut=!1,m.sessionHint="session expired \u2014 refreshing\u2026"):(m.who=$,m.loggedOut=!1,m.sessionHint=`session valid until ${new Date(x.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return m}function u0(e,t){try{let n=Xe(e,t),o=mn(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...Zn(o.idToken)??{},...Zn(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return Ht(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 rm=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],eo=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],d0="Ask me to write or update an article\u2026";function Xn({ch:e,dim:t}){let[n,o]=Z(!0);return He(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),L(M,{inverse:n,color:t&&!n?"gray":void 0,children:e})}function Qn({rows:e,cursor:t,cap:n,render:o}){let r=Hs(e.length,t,n);return oe(Jn,{children:[r.above>0?L(M,{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?L(M,{color:"gray",children:` \u22EF ${r.below} more below`}):null]})}var sm=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function im(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var p0=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function h0({startTime:e,chars:t}){let[n,o]=Z(0);He(()=>{let d=setInterval(()=>o(h=>h+1),120);return()=>clearInterval(d)},[]);let r=eo[n%eo.length],s=rm[Math.floor(n/16)%rm.length],i=Math.floor((Date.now()-e)/1e3),l=Math.round(t/4);return oe(we,{children:[L(M,{color:te,children:` ${r} ${s}\u2026 `}),L(M,{color:"gray",children:`(${Po(i)} \xB7 ~${l} tokens \xB7 esc to interrupt)`})]})}function f0({text:e}){let[t,n]=Z(0);return He(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),L(we,{paddingX:1,children:L(M,{color:te,children:`${eo[t%eo.length]} ${e}`})})}var m0=12e4;function g0({p:e}){let[t,n]=Z(0);He(()=>{let R=setInterval(()=>n(I=>I+1),150);return()=>clearInterval(R)},[]);let o=eo[t%eo.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),i=Math.round(e.chars/4),l=Date.now()-e.lastAt>=m0,d=e.verb??"Converting",h=e.unit??"article",m=e.rows.reduce((R,I)=>R+I.items,0),w=d.toLowerCase(),x=e.rows,S=0;if(x.length>Ks){let R=x.findIndex(Y=>Y.status==="active"||Y.status==="pending"),I=Math.max(0,Math.min(R-2,x.length-Ks));S=x.slice(0,I).filter(Y=>Y.status==="done").length,x=x.slice(I,I+Ks)}let $=Math.min(40,Math.max(...x.map(R=>tc(R.label).length),0)),T=R=>R==="failed"?"red":R==="active"?te:void 0;return oe(we,{flexDirection:"column",children:[oe(we,{children:[L(M,{color:te,children:` ${o} ${d} ${m} ${h}${m===1?"":"s"} `}),L(M,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${i} tokens \xB7 ${Po(r)} \xB7 esc to stop`})]}),S>0&&L(M,{dimColor:!0,children:` \u2714 +${S} done`}),x.map(R=>oe(M,{color:T(R.status),dimColor:R.status==="done"||R.status==="pending",children:[` ${xf[R.status]} ${tc(R.label).padEnd($)}`,R.status==="active"&&R.itemsDone!==void 0?` (${R.itemsDone}/${R.items} ${h}${R.items===1?"":"s"})`:R.status!=="pending"?` (${R.items} ${h}${R.items===1?"":"s"})`:"",R.status==="active"?` \u2190 ${w}\u2026`:""]},R.label)),l&&L(M,{color:"yellow",children:` \u26A0 no activity for ${Po(s)} \u2014 press esc to stop if it's wedged`})]})}var y0=10800*1e3;function lm({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=px(),[s,i]=Z(n),[l,d]=Z(null),[h,m]=Z({text:"",pos:0}),w=h.text,x=X(c=>{m(u=>{let a=typeof c=="function"?c(u.text):c;return{text:a,pos:a.length}})},[]),S=X(c=>{m(u=>({text:u.text.slice(0,u.pos)+c+u.text.slice(u.pos),pos:u.pos+c.length}))},[]),$=X(()=>{m(c=>{if(c.pos===0)return c;let u=c.text.slice(0,c.pos),a=Af(u)??u.slice(0,-1);return{text:a+c.text.slice(c.pos),pos:a.length}})},[]),[T,R]=Z(!1),[I,Y]=Z(!1),[q,z]=Z(0),[ae,xe]=Z(!1),[ke,Ee]=Z(null),[ge,K]=Z(null),[pe,le]=Z([]),Ce=re(!1),Se=re(!1),Qe=re(null),xt=re(!1),[qt,sr]=Z(!1),it=re(0),[ir,ar]=Z(!1),[mm,lr]=Z(!1),[oi,yc]=Z(null),[gm,gn]=Z(0),Gt=re(0),[ri,yn]=Z(0),[wn,cr]=Z(null),wc=re(new Map),ym=re(0),kn=re([]),Je=re(null);Je.current===null&&(Je.current=Wf({cwd:e,profileName:s,allowProdWrites:!1}));let ft=re({uuid:null,firstPrompt:null,titleFired:!1}),to=re(new Map),kc=re(null),ur=re(Hf().verboseTranscript===!0),bn=re(!1),si=re([]),fe=re([]),Vt=re([]),no=re(null),[bc,Yt]=Z(null),ii=re(null),[Kt,zt]=Z(null),[Rt,$n]=Z(null),[Ct,vn]=Z(null),[Oe,xn]=Z(null),[Ze,Xt]=Z(null),[mt,Rn]=Z(null),[St,Qt]=Z(null),[at,Jt]=Z(null),[$c,Cn]=Z(null),[qe,Zt]=Z(null),[Le,Sn]=Z(null),[vc,ai]=Z([]),en=re([]),oo=re(!1),Ae=re(null),[dr,me]=Z(null),[xc,gt]=Z(null),pr=re(!1),ro=re(null),so=re(null),[Ge,tn]=Z(null),[io,nn]=Z(null),ao=!!(Ct||Oe||Ze||mt||St||at||qe||Le||Ge||io),[Rc,Pn]=Z(0),[Cc,Tn]=Z(0),[wm,Sc]=Z(0),li=oc(()=>{try{let c=pc(e);return c.source==="auto"?`${c.model} (auto)`:c.model}catch{return null}},[e,wm]),{stdout:_e}=fx(),[,km]=Z(0),Pc=re(`${_e.columns??80}x${_e.rows??24}`),Pt=X(()=>Math.max(20,(_e.columns??80)-1),[_e]),hr=X(c=>{kn.current.push(c),console.log(Yi(c,Pt()))},[Pt]),ci=re([]),fr=X(()=>{let c=ci.current;if(c.length===0)return;ci.current=[];let u=Of(c);u&&hr({kind:"note",tone:"info",text:`\u25CF Housekeeping ${u}`})},[hr]),p=X(c=>{fr(),hr(c)},[hr,fr]),Ve=re({printed:[],armed:[]}),Ne=X((c,u)=>{it.current++,Ve.current.armed=[],Ee(c),K(u??null)},[]),lt=X(()=>{it.current++,Ve.current.armed=[],Ee(null),K(null)},[]),mr=X(c=>{it.current++,Ve.current.armed=[],Ee(null),K(c)},[]),J=X(c=>Ne(c,Vn({kind:"cmd",cmd:c,reason:""})),[Ne]),yt=X((c,u)=>{if(!u?.silent&&c.note&&p({kind:"note",tone:u?.tone??c.tone,text:c.note}),!u?.silent&&c.note?.includes(".d360-writer/ \u2014 your articles"))try{let g=e0(e);t0(yx(g)),gx(g,`${new Date().toISOString()}
|
|
437
|
+
`)}catch{}c.picker&&(le(c.picker.options.map(g=>({cmd:g.cmd,desc:g.desc}))),Cn(c.picker.title)),!u?.silent&&c.note&&(Ve.current.printed=c.menu);let a=jh(Ve.current.printed,c.menu)?c.menu:[];c.lead&&(c.lead.kind==="answer"?mr(Vn(c.lead,a.length)):Ne(c.lead.kind==="cmd"?c.lead.cmd:c.lead.text,Vn(c.lead,a.length))),Ve.current.armed=a},[p,Ne,mr]),Ie=X((c,u,a="info")=>{Ve.current.armed=[],c&&p({kind:"note",tone:a,text:c}),u&&(u.kind==="answer"?mr(Vn(u)):Ne(u.kind==="cmd"?u.cmd:u.text,Vn(u)))},[p,Ne,mr]),gr=X((c,u,a,g="info")=>{if(c.producedNothing){Ie("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}Ie(u,a,g)},[Ie]),[lo,ui]=Z(null),[bm,Tc]=Z(!1),Tt=X((c,u)=>{ui(c),Tc(!1),p({kind:"note",tone:"info",text:u?.hint??"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[p]),di=X(()=>{s0(e,new Date().toISOString());let c=eh(e);c&&(p({kind:"note",tone:"info",text:c.lines.join(`
|
|
438
|
+
`)}),Tt(c.prompt,i0(e)?{hint:"\u2328 Press c to copy the request \u2014 only if you want to hand it over now; your builder already has it."}:void 0))},[e,p,Tt]),pi=re(!1),hi=X(async()=>{try{if(pi.current||!Kx(Yx())||ue(e)?.mode==="engineer")return;let c=await Vx({pkg:Gn,currentVersion:o,force:!0});if(!c.updateAvailable||!c.latest)return;pi.current=!0,p({kind:"note",tone:"info",text:`\u2B06 Updating ${Gn} ${c.current} \u2192 ${c.latest}\u2026 (wait for the \u2713 before you /exit)`}),lr(!0),(await Ps().finally(()=>lr(!1))).ok?(p({kind:"note",tone:"ok",text:`\u2713 Updated to v${c.latest} \u2014 run /exit, then relaunch to apply.`}),J("/exit"),yc(c.latest)):p({kind:"note",tone:"warn",text:`Update available (v${c.latest}) but auto-update failed \u2014 run: ${Ss}`})}catch{}},[e,o,p,J]),co=re(!1),fi=re(null),Ec=X(async c=>{if(!co.current)try{let u=ue(e);if(!u)return;let a=Ac.current;if(!a)return;if(a.pushConsent!=="on"){if(a.uncommitted===0)return;co.current=!0;try{let E=await Zx(e,u);if(E.commit?.ok)fi.current=null;else if(E.commit&&!E.commit.ok){let F=`${E.commit.reason}:${E.commit.detail??""}`;fi.current!==F&&(fi.current=F,p({kind:"note",tone:"warn",text:`\u26A0 Couldn't save your docs work to git \u2014 ${Ft(E.commit.reason,E.commit.detail)}`}))}}finally{co.current=!1}return}if(a.uncommitted===0&&a.unpushed===0&&!c.pull)return;co.current=!0;try{let{lines:E,changed:F}=await Cs(e,u);for(let f of E)f.tone==="warn"||f.tone==="error"?p({kind:"note",tone:f.tone,text:f.text}):f.text.includes("\u2B07")&&p({kind:"note",tone:f.tone,text:f.text});F&&z(f=>f+1)}finally{co.current=!1}}catch{}},[e,p]),uo=X(c=>{let u=Fe(e,s);return u.ok?!0:(p({kind:"note",tone:"warn",text:u.reason}),so.current=c,J("/login"),!1)},[e,s,p,J]),[yr,mi]=Z(null),Ac=re(null),et=X((c,u)=>{let a=Jo(e,s,{claudeMissing:dc(t).state==="missing",allowAutoAudit:c,genreUnknown:xt.current,pendingAnswer:Qe.current});return Ac.current=a?.handoff??null,a?Qo(a,{header:u,pickable:!0}):{kind:"idle"}},[e,s,t]),gi=re(Date.now()),po=re(pf()),Dc=re(0),[jc,Nc]=Z(null),ho=re(!0),En=re(!1),wr=re(0),fo=re(0);He(()=>{let c=setInterval(()=>{if(ho.current){wr.current=0,fo.current=0;return}if(!T)try{if(!zn(Jf(e)))return;if(ot(e).status==="current"){ho.current=!0,wr.current=0,fo.current=0;let a=En.current?`\u2713 Your builder finished the protocol update (v${ve}) \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=et(!1,a),E=g.kind==="recommend"?g.rec:null;ui(null),E?.note?yt(E,{tone:"ok"}):(p({kind:"note",tone:"ok",text:`${a}${E?.lead?` ${Xo(E.lead)}`:""}`}),E?.lead||E?.picker?yt(E,{silent:!0}):En.current||Ne("write the docs for this repo")),z(F=>F+1);return}if(En.current)return;wr.current+=1;let u=wr.current;if((u===4||u%15===0)&&fo.current<3){fo.current+=1;let a=fo.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";p({kind:"note",tone:"info",text:bt(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${a}`:`\u23F3 Waiting for your builder to run the prompt \u2014 paste it into your coding agent; I'll pick up automatically when it's done.${a}`})}}catch{}},4e3);return()=>clearInterval(c)},[e,T,p,et,yt,Ne]),He(()=>{let c=bc??rr(e);if(!T){qs(0),Yn(`${Vs} ${c}`);return}qs(3);let u=0;Yn(`${Gs[0]} ${c}`);let a=setInterval(()=>{u=(u+1)%Gs.length,Yn(`${Gs[u]} ${c}`)},400);return()=>clearInterval(a)},[T,e,bc]),He(()=>()=>qs(0),[]),He(()=>{let c=performance.now(),u=[],a=(y,C)=>{let b=performance.now();try{return C()}finally{let v=Math.round(performance.now()-b);v>=80&&u.push(`${y}: ${v}ms`)}};p({kind:"banner",info:a("banner",()=>c0(e,o,t,s))});let g=dc(t).state==="missing";if(g&&p({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.
|
|
439
|
+
${kx}
|
|
440
|
+
Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!ue(e)){p({kind:"note",tone:"info",text:`Welcome! This repo isn't set up for d360-writer yet \u2014 three steps and you're writing docs:
|
|
441
|
+
${om}`}),J(g?"/doctor":"/init");return}g&&J("/doctor");try{let y=Xe(e,s),C=mn(y.name);C&&Ht(C)&&C.refreshToken?xx({profile:y.name,connection:y.connection}).then(()=>{p({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),z(b=>b+1)}).catch(()=>{p({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 sign in again with /login."}),J("/login")}):(!C||Ht(C))&&(p({kind:"note",tone:"warn",text:`Profile "${y.name}" is not signed in \u2014 sign in with /login.`}),J("/login"))}catch{}try{let y=ue(e),C=Xe(e,s),b=mn(C.name);y&&b&&!Ht(b)&&Bl(e,y.authoritativeSourceFiles)&&!Hl(e,s)&&(p({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),J("/scope"))}catch{}try{let y=a("resolve-genre",()=>Lx(e));y.persisted&&y.appType?p({kind:"note",tone:"ok",text:`\u2713 Detected a ${y.appType} app \u2014 enabled the ${y.appType}-doc-playbook (change with /genre, or edit .d360-writer/config.json).`}):y.source==="unknown"&&ue(e)&&(xt.current=!0)}catch{}let E=ot(e);try{if(a("reconcile-devhints",()=>Br(e)),E.status!=="current"&&!bt(e)){let y=Hr(e);y.length&&(p({kind:"note",tone:"warn",text:y.join(`
|
|
442
|
+
`)}),Tt(sn()),ho.current=!1,En.current=!1)}}catch{}try{let y=a("reconcile-feedback",()=>zx(e));y.archived>0&&p({kind:"note",tone:"ok",text:`\u2713 Tidied ${y.archived} resolved item${y.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${y.open>0?`; ${y.open} still open`:""}.`})}catch{}try{let y=a("upgrade-actions",()=>Xx(e));y.applied.length>0&&p({kind:"note",tone:"warn",text:Mr(y.applied).join(`
|
|
443
|
+
`)}),y.reopenedForRedaction&&p({kind:"note",tone:"warn",text:Ur(y.reopenedForRedaction)})}catch{}let F=a("ready-decision",()=>et(!0));F.kind==="autoAudit"?(p({kind:"note",tone:"info",text:F.note}),Lo().then(y=>{y.kind==="forward-to-agent"&&y.prompt&&de(y.prompt,{display:y.display,quietUser:!0})})):F.kind==="recommend"&&yt(F.rec);let f=Math.round(performance.now()-c);f>=800&&Jx({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${f}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${u.length?u.join(`
|
|
444
444
|
`):"no single phase \u226580ms"}
|
|
445
|
-
cwd: ${e}`}),
|
|
446
|
-
|
|
447
|
-
${D}`)}catch{}u?.quietUser||p({kind:"user",text:u?.echoDisplay&&u.display?u.display:c});let g=
|
|
448
|
-
`)}),
|
|
449
|
-
`)});let D=
|
|
450
|
-
`)}),
|
|
451
|
-
`):`${
|
|
452
|
-
${
|
|
453
|
-
${
|
|
454
|
-
${N}`).join("")});let D=
|
|
455
|
-
`)}),
|
|
456
|
-
`)})}if(
|
|
457
|
-
`)});return}let O=
|
|
458
|
-
`)}),
|
|
459
|
-
`)}),
|
|
460
|
-
${
|
|
461
|
-
`)});return}case"mcp":await
|
|
462
|
-
`)}),y&&p({kind:"note",tone:"warn",text:`\u26A0 ${y.why} \u2014 ${y.cmd} moves this repo.`});return}let f=[...
|
|
445
|
+
cwd: ${e}`}),hi(),Ec({pull:!0})},[]),He(()=>{let c=setInterval(()=>{hi()},y0);return()=>clearInterval(c)},[hi]),He(()=>{let c=setInterval(()=>{try{let u=Date.now(),a=Zl(u,gi.current);if(Dc.current+=1,a&&Dc.current%Math.round(3e5/6e4)!==0)return;let g=a0(e),E=po.current,F=g===E.fingerprint&&E.counts?E.counts:hn(e),f=ff({now:u,lastInputAt:gi.current,fingerprint:g,counts:F,occupied:T||ae||pe.length>0||w!==""||ao||fe.current.length>0,prev:E});if(po.current=f.memory,Nc(f.waiting),f.speak){p({kind:"note",tone:"info",text:gf(f.speak)});let y=et(!1);y.kind==="recommend"&&yt(y.rec,{silent:!0})}}catch{}},6e4);return()=>clearInterval(c)},[e,T,ae,pe.length,w,ao,p,et,yt]),He(()=>{if(T||ae||Ce.current||ke!==null||pe.length>0||w!==""||lo!==null||fe.current.length>0||no.current||ao)return;let c=et(!1);c.kind==="recommend"&&(c.rec.lead||c.rec.picker)&&yt(c.rec,{silent:!0}),Ec({pull:!1})},[T,ae,ke,pe,w,lo,ao,q,et,qt]),He(()=>{let c=null,u=null,a=()=>{c&&clearTimeout(c),c=setTimeout(()=>{c=null;let g=`${_e.columns??80}x${_e.rows??24}`;g!==Pc.current&&(Pc.current=g,km(E=>E+1),u&&clearTimeout(u),u=setTimeout(()=>{u=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+Qu(kn.current,Pt())+"\x1B[?2026l")},80))},400)};return _e.on("resize",a),()=>{c&&clearTimeout(c),u&&clearTimeout(u),_e.off("resize",a)}},[_e,Pt]);let Ye=Math.max(20,(_e.columns??80)-1),Ic=oc(()=>u0(e,s),[e,s,q]),yi=(()=>{if(mm)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(oi!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${oi?` v${oi}`:""}\u2026`,isSetup:!0};if(yr)return{text:"\u{1F6E0} press c to copy the d360-writer feedback \u2014 then send it to the team (Teams / Slack / email)\u2026",isSetup:!0};if(lo)return bm?{text:"\u2713 copied \u2014 paste it into your coding agent \xB7 I\u2019ll pick up automatically when it finishes\u2026",isSetup:!0}:{text:"\u2328 press c to copy the prompt \u2014 then paste it into your coding agent\u2026",isSetup:!0};if(jc)return{text:wf(jc),isSetup:!0};if(fe.current.length>0){let g=fe.current.length;return fe.current[0].mode==="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 c=ue(e);if(!c)return{text:"Run /init to set up this repo (or /help)\u2026",isSetup:!0};let u=rc(e,(c.docsDir??hc).replace(/\/+$/,"")),a=(()=>{try{return zn(u)&&mx(u).length>0}catch{return!1}})();try{let g=Xe(e,s),E=mn(g.name);if(!(!!E&&!(Ht(E)&&!E.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&&!a)return{text:"Pick a workspace with /workspace\u2026",isSetup:!0}}catch{}return a?{text:d0,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),wt=Bu(w),Oc=wt.length>0&&!T,$m=12,on=Xl(_e.rows),vm=_e.rows??24,Lc=Xl(_e.rows,{max:$m}),kr=Math.min(ri,Math.max(0,wt.length-1)),rn=Hs(wt.length,kr,Lc).start,wi=wt.slice(rn,rn+Lc),ki=l!==null?Lf(l,8,Ye):null,br=qe?qe.paths.filter(c=>!qe.query||c.toLowerCase().includes(qe.query.toLowerCase())).slice(0,8):[],$r=Ge?Ge.sessions.filter(c=>{let u=Ge.query.toLowerCase();return!u||c.name.toLowerCase().includes(u)||c.firstPrompt.toLowerCase().includes(u)}).slice(0,8):[],Me=X((c,u)=>{Je.current?.close(),Je.current=Wf({cwd:e,resume:c,profileName:u??s,allowProdWrites:bn.current}),c||(ft.current={uuid:null,firstPrompt:null,titleFired:!1},Yt(null)),Pn(0),Tn(0)},[e,s]),_c=X((c,u,a)=>{if(sm.test(c))try{let g=Xe(e,s),E=typeof u.project_id=="string"&&u.project_id||g.project.projectId,F=Ws(u,a),f=[],y=Fs(a);c.endsWith("publish_article")&&y&&f.push(`Live: ${y}`);let C=Bs(a);C?f.push(`Preview: ${C}`):F&&E&&f.push(`Preview: ${Us(g.connection.portalUrl,E,F,g.project.languageCode??"en")}`),f.length>0&&p({kind:"link",lines:f})}catch{}},[e,s,p]),de=X(async(c,u)=>{ar(!0),Ce.current=!1,Se.current=!1,Qe.current=null,lt(),le([]),Cn(null),ui(null);let a=it.current;if(u?.display?.startsWith("/"))try{let D=Ph(e,u.display);D&&(c=`${c}
|
|
446
|
+
|
|
447
|
+
${D}`)}catch{}u?.quietUser||p({kind:"user",text:u?.echoDisplay&&u.display?u.display:c});let g=ft.current;g.firstPrompt||(g.firstPrompt=u?.display??c),Gt.current=Date.now(),gn(0),R(!0),to.current.clear();let E="",F=!1,f=!1,y=!1,C=!1,b="",v={num:0,closed:!1,cueSeen:!1},P=null,B=()=>{P||(P=setTimeout(()=>{P=null,d(b.length>0?b:null)},60))},H=()=>{P&&clearTimeout(P),P=null,d(null)},ee=(D=!1)=>{let{head:O,keep:N}=_f(b,D);O.trim()&&p({kind:"assistant",text:zl(O.trimEnd(),v)}),b=N,H()};try{for await(let D of Je.current.send(c))if(D.type==="session"){if(!g.uuid){g.uuid=D.sessionId;let O=new Date().toISOString(),N=ii.current,_=N??Ex(g.firstPrompt??"session");Ax({uuid:D.sessionId,name:_,renamed:!!N,titled:!1,cwd:e,firstPrompt:g.firstPrompt??"",createdAt:O,updatedAt:O}),Yt(_),ii.current=null}}else if(D.type==="text"){b+=D.delta,E+=D.delta;let O=Mf(b);if(O>0){let N=b.slice(0,O).trimEnd();N&&p({kind:"assistant",text:zl(N,v)}),b=b.slice(O)}B(),gn(N=>N+D.delta.length)}else if(D.type==="tool"){F=!0,sm.test(D.name)&&(f=!0);let N=(ce=>typeof ce=="string"&&ce?ce.replace(/\\/g,"/").toLowerCase():null)(D.input.file_path??D.input.notebook_path),_=["Edit","Write","MultiEdit","NotebookEdit"].includes(D.name),se=D.name==="Read"&&N!==null&&N===kc.current;kc.current=_?N:null;let Re=ur.current,nt=Re?null:If(D.name,D.input),V=Re?null:Ls(D.name,D.input,e,s);if(nt)ci.current.push(nt);else if(V)ee(),p({kind:"doc",verb:V.verb,title:V.title,category:V.category,note:V.note,...V.loud?{loud:V.loud}:{}}),to.current.set(D.id,{name:D.name,input:D.input,doc:!0,keepResult:V.keepResult});else if(se)ee(),p({kind:"tool",title:"Read",sep:"",arg:"re-checking the file it just edited"});else{let ce=_s(D.name,D.input,e);ce&&(ee(),p({kind:"tool",title:ce.title,sep:ce.sep,arg:ce.arg}),to.current.set(D.id,{name:D.name,input:D.input}))}}else if(D.type==="article_diff"){let O=Ke(D.oldContent,D.newContent,Pt());O&&(ee(),p({kind:"diff",added:O.added,removed:O.removed,lines:O.lines,hidden:O.hidden}))}else if(D.type==="tool_result"){D.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(D.output)&&(pr.current=!0);let O=to.current.get(D.id);if(O){to.current.delete(D.id),ee();let _=O.doc&&!O.keepResult&&!D.isError?{lines:[],hidden:0}:Ms(D.output,4,D.isError||ur.current?void 0:O.name,O.input);_.lines.length>0&&p({kind:"tool-result",lines:_.lines,hidden:_.hidden,isError:D.isError}),D.isError||_c(O.name,O.input,D.output)}}else if(D.type==="result"){ee(!0),Pn(_=>_+D.outputTokens),Tn(_=>_+D.costUsd);let O=D.inputTokens+D.cacheReadTokens+D.cacheCreationTokens;if(p({kind:"done",seconds:Math.round((Date.now()-Gt.current)/1e3),tokens:D.outputTokens,costUsd:D.costUsd,ok:D.ok,...O>0?{inTokens:O,cachedPct:Math.round(D.cacheReadTokens/O*100)}:{}}),!y&&!F&&!E.trim()&&!oo.current&&(C=!0,p({kind:"note",tone:"warn",text:"The agent produced no output \u2014 nothing ran this turn. Two usual causes: the Claude model/runtime (check /doctor \u2014 sign-in + reachability), or a Claude usage limit reached mid-session, which ends every turn instantly and leaves /doctor completely clean."})),D.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(E))try{let _=Zf(e);if(zn(_)){let se=Qs(_,"utf8").trim();se&&(mi(se),p({kind:"note",tone:"info",text:"\u{1F6E0} Press c to copy this feedback \u2014 send it to the d360-writer team (Teams / Slack / email)."}))}}catch{}let N=D.ok?nf(E):null;if(Se.current=N!==null,Qe.current=N,D.ok&&(v.cueSeen||(N?.options??0)>=2))sr(!0),le([]);else if(N)le([]);else{let _=D.ok?bf(E,Mn.map(se=>se.name)):[];if(_.length>0)J(_[0]);else if(D.ok&&E.trim()&&!Se.current){let se=et(!1);se.kind==="recommend"&&(se.rec.lead||se.rec.picker)||Ix(c,E,e).then(Re=>{Re&&it.current===a&&Ne(Re)}).catch(()=>{})}}if(g.uuid&&(sc(g.uuid),!g.titleFired)){g.titleFired=!0;let _=g.uuid,se=g.firstPrompt;se&&Ff(se,e).then(Re=>{Re&&(Tx(_,Re),Yt(Re))}).catch(()=>{})}}else D.type==="error"&&(ee(!0),y=!0,D.kind==="auth"&&(pr.current=!0),p(D.kind==="limit"?{kind:"note",text:`\u23F3 ${D.message}`,tone:"warn"}:{kind:"note",text:`agent error: ${D.message}`,tone:"error"}))}finally{if(R(!1),H(),fr(),f)try{let D=uc(await cc({cwd:e,profileName:s,onRateLimit:O=>gt(`Document360 rate limit \u2014 waiting ${Math.ceil(O.waitMs/1e3)}s\u2026`)}));D&&p({kind:"note",tone:D.startsWith("\u26A0")?"warn":"info",text:D})}catch{}z(D=>D+1),ft.current.uuid&&uf(e,ft.current.uuid,kn.current),pr.current?(pr.current=!1,ro.current=u?.display??c,Ne("/login","\u21E5 tab to run /login \u2014 then I\u2019ll re-send your last prompt\u2026")):ro.current=null,oo.current&&(oo.current=!1,en.current.length>0&&(p({kind:"note",tone:"info",text:`(${en.current.length} queued message(s) discarded)`}),en.current=[],ai([])),p({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}return{producedNothing:C}},[e,p,_c,Pt,Ne,J,lt,et,fr]),tt=X(async(c,u=0,a)=>{if(!a?.skipReview){let f=un(e,c);if(f.length>0){p({kind:"note",tone:"warn",text:ps(f,c.length).join(`
|
|
448
|
+
`)}),J("/review --fix");return}}let g=ti(e,"standard");Gt.current=Date.now(),gn(0),R(!0);let E=new AbortController;Ae.current=E;let F=async(f,y)=>{let C=ic(f);me({verb:"Publishing",total:C.length,done:0,active:[],rows:or(C),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),p({kind:"note",tone:"info",text:y?`Resolving cross-links in ${f.length} article${f.length===1?"":"s"} whose targets published this run (second pass)\u2026 (esc to stop)`:`Publishing ${f.length} article${f.length===1?"":"s"} across ${C.length} partition${C.length===1?"":"s"} (\u2264${No} agents at once) on ${g.model}\u2026 (esc to stop)`});let b=!1;for await(let v of ei({cwd:e,partitions:C,promptFor:P=>Io(P.paths),concurrency:No,profileName:s,allowProdWrites:bn.current,allowUnreviewedPublish:a?.skipReview===!0,model:g.model,signal:E.signal}))if(v.type==="partition_status")v.status==="running"?me(P=>P&&{...P,active:[...P.active,v.label],rows:rt(P.rows,v.label,"active"),lastAt:Date.now()}):me(P=>P&&{...P,active:P.active.filter(B=>B!==v.label),done:P.done+1,rows:rt(P.rows,v.label,v.status==="done"?"done":"failed"),lastAt:Date.now()});else if(v.type==="partition_event")me(P=>{if(!P)return P;let B={...P,lastAt:Date.now()};return v.event.type==="tool"?B.tools=P.tools+1:v.event.type==="text"&&(B.chars=P.chars+v.event.delta.length),B});else if(v.type==="run_done"){b=v.aborted,Tn(O=>O+v.totalCostUsd),Pn(O=>O+v.results.reduce((N,_)=>N+_.outputTokens,0));let P=v.aborted?"Stopped. ":"",B=t.kind==="api"?"api":"subscription",H=wa(e,c,s),ee=!v.aborted&&(!!v.blocked||!!v.allEmpty||c.length>0&&H===0);p({kind:"note",tone:v.aborted?"warn":v.ok&&!ee?"ok":"warn",text:P+ka(v.results,C,B,y?0:u,{recorded:H,...v.blocked?{blocked:v.blocked}:{},...v.allEmpty?{allEmpty:!0}:{},...v.bailedEmpty?{bailedEmpty:!0,notRun:v.notRun??0}:{}}).join(`
|
|
449
|
+
`)});let D=ga(e,s);if(D&&p({kind:"note",tone:"info",text:D}),!v.aborted&&!ee){try{let N=await cc({cwd:e,profileName:s,onRateLimit:se=>gt(`Document360 rate limit \u2014 waiting ${Math.ceil(se.waitMs/1e3)}s\u2026`)}),_=uc(N);_?p({kind:"note",tone:_.startsWith("\u26A0")?"warn":"info",text:_}):N.skipped&&p({kind:"note",tone:"warn",text:`Order sync skipped: ${N.skipped}`})}catch(N){p({kind:"note",tone:"warn",text:`Order sync failed: ${N.message}`})}try{let N=nm(await tm({cwd:e,profileName:s}));N&&p({kind:"note",tone:"info",text:N})}catch(N){p({kind:"note",tone:"warn",text:`Related-articles sync failed: ${N.message}`})}let O=await Fn(e,s);O&&p({kind:"note",tone:"info",text:O})}}return b};try{if(!await F(c,!1)){let y=await ba(e,s,c);y.length>0&&await F(y,!0),u>0&&Ie(null,{kind:"cmd",cmd:"/resolve",reason:`${u} conflict${u===1?"":"s"} still need settling \u2014 they were left untouched`},"warn")}}catch(f){p({kind:"note",tone:"error",text:`Publish run failed: ${f.message}`})}finally{Ae.current=null,me(null),R(!1),z(f=>f+1)}},[e,s,p,t,Ie]),bi=X(async(c,u)=>{if(u?.skipReview)await tt([c],0,{skipReview:!0});else{let g=un(e,[c]);if(g.length>0){p({kind:"note",tone:"warn",text:ps(g,1).join(`
|
|
450
|
+
`)}),J("/review --fix");return}await de(fa(c),{display:`/publish ${c}`,quietUser:!0})}let a=u?.skipReview?null:await Fn(e,s);a&&p({kind:"note",tone:"info",text:a});try{let g=await hs(e,s,c.replace(/\\/g,"/"));g.length>0&&(Cn(`Related articles not yet published (${g.length}):`),le([`/publish --related ${c}`,...g.map(E=>`/publish ${E}`)]))}catch{}},[e,s,de,tt]),Mc=X(async c=>{try{let u=await Zs({cwd:e,profileName:s}),{clean:a,conflicts:g}=cn(u.entries);if(a.length===0){p({kind:"note",tone:"info",text:"Nothing new to publish \u2014 everything is already up to date on Document360."});return}await tt(a.map(E=>E.path),g.length,{skipReview:c?.skipReview})}catch(u){p({kind:"note",tone:"warn",text:`Couldn\u2019t check what to publish (${u.message}) \u2014 your drafts are saved; run /publish when ready.`})}},[e,s,tt]),vr=X(c=>{if(c)try{for(let u of Array.isArray(c)?c:[c]){let a=Ml(e,u);if(!a)continue;js(e,a.title).ok&&p({kind:"note",tone:"ok",text:`\u2713 That completed a docs-campaign step \u2014 marked done: ${a.title}`});return}}catch{}},[e,p]),Uc=X(async(c,u)=>{let g=Hx(c,3),E=ti(e,"standard"),F=new Map,f=new Map;for(let b of c){let v=an(e,b),P=Xi(e,b,v);if(P&&F.set(b,P),v!==null){let B=ua(v);B.length>0&&f.set(b,B)}}Gt.current=Date.now(),gn(0),R(!0);let y=new AbortController;Ae.current=y,me({verb:"Authoring",unit:"spec",total:g.length,done:0,active:[],rows:or(g),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),p({kind:"note",tone:"info",text:`Authoring ${c.length} screenshot spec${c.length===1?"":"s"} across ${g.length} partition${g.length===1?"":"s"} (\u22646 agents at once) on ${E.model}${E.forced?" (forced)":""}\u2026 (esc to stop)`});let C=!1;try{for await(let b of ei({cwd:e,partitions:g,promptFor:v=>Ld(v,F,f),concurrency:6,profileName:s,allowProdWrites:bn.current,model:E.model,signal:y.signal}))if(b.type==="partition_status")b.status==="running"?me(v=>v&&{...v,active:[...v.active,b.label],rows:rt(v.rows,b.label,"active"),lastAt:Date.now()}):me(v=>v&&{...v,active:v.active.filter(P=>P!==b.label),done:v.done+1,rows:rt(v.rows,b.label,b.status==="done"?"done":"failed"),lastAt:Date.now()});else if(b.type==="partition_event")me(v=>{if(!v)return v;let P={...v,lastAt:Date.now()};return b.event.type==="tool"?P.tools=v.tools+1:b.event.type==="text"&&(P.chars=v.chars+b.event.delta.length),P});else if(b.type==="run_done"){Tn(ee=>ee+b.totalCostUsd),Pn(ee=>ee+b.results.reduce((D,O)=>D+O.outputTokens,0));let v=b.results.filter(ee=>ee.ok).length,P=b.aborted?"Stopped. ":"";C=!b.aborted&&u.setup;let B=b.aborted?"":C?" Refreshing the staging checklist\u2026":" Next: /screenshot capture --all (or /screenshot checklist first for the staging checklist).",H=ut(b,"Spec authoring");p({kind:"note",tone:H||b.aborted?"warn":b.ok?"ok":"warn",text:H?H.join(`
|
|
451
|
+
`):`${P}Authored specs \u2014 ${v}/${b.results.length} batches ok.${B}`}),H&&(J("/doctor"),C=!1),!b.aborted&&b.ok&&!H&&vr(u.runLine)}}catch(b){p({kind:"note",tone:"error",text:`Spec authoring failed: ${b.message}`})}finally{Ae.current=null,me(null),R(!1),z(b=>b+1)}if(C){let b=await qn();b.kind==="forward-to-agent"&&b.prompt&&await de(b.prompt,{display:b.display,quietUser:!0}),di()}},[e,s,p,de,vr,di]),Wc=X(async c=>{let u=Xi(e,c,an(e,c))??void 0,a=await cs([c],void 0,{prior:u});a.kind==="forward-to-agent"&&a.prompt&&await de(a.prompt,{display:a.display,quietUser:!0}),$d(e,c)&&Ie(`Spec ready \u2014 /screenshot capture ${c} takes the screenshot; bare /screenshot picks the next shot.`,{kind:"cmd",cmd:`/screenshot capture ${c}`,reason:""})},[e,de,Ie]),mo=X(async(c,u)=>{if(!xs(e)){await de(dl(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(!qp(e)){p({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)"}),R(!0),gt("Waiting for you to finish logging in (browser window)\u2026");let N=new AbortController;Ae.current=N;let _;try{_=await Gp({cwd:e,signal:N.signal})}catch(se){p({kind:"note",tone:"error",text:`Could not launch the login: ${se.message}`});return}finally{Ae.current=null,gt(null),R(!1)}if(_.exitCode!==0){ul(_.exitCode,_.output)?p({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(_.output)?p({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."}):p({kind:"note",tone:N.signal.aborted?"warn":"error",text:N.signal.aborted?"Login cancelled \u2014 nothing saved.":`Login did not complete:
|
|
452
|
+
${ll(_.output)}`});return}p({kind:"note",tone:"ok",text:"\u2713 Login saved \u2014 continuing with the capture."})}let a=new Map(c.map(N=>[N,Pd(e,N)])),g=0;if(c.length>1){let N=c.filter(_=>a.get(_).mutates);if(N.length>0&&(g=N.length,c=c.filter(_=>!a.get(_).mutates),c.length===0)){p({kind:"note",tone:"warn",text:`\u26A0 All ${N.length} spec${N.length===1?"":"s"} in scope write real data, so a bulk run has nothing to do. Run one deliberately: /screenshot capture ${N[0]}`});return}}else if(c.length===1&&a.get(c[0]).mutates){let N=a.get(c[0]),_=Vp(e);p({kind:"note",tone:"warn",text:`\u26A0 This capture performs a REAL write in your app${N.what?`: ${Sd(N.what)}`:N.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. `+(_.production?`This profile is PRODUCTION \u2014 the write lands in the LIVE tenant${_.url?` (${_.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.")})}R(!0);let E=new AbortController;Ae.current=E;let F=c.map(N=>({label:N,items:1,status:"pending"}));me({verb:"Capturing",unit:"screenshot",total:c.length,done:0,active:[],rows:F,tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()});let f=$t(e),y=Object.keys(f.shots).length>0,C=Yp(u?.heldBackBlocked??[],g);p({kind:"note",tone:"info",text:`Capturing ${c.length} screenshot${c.length===1?"":"s"} with d360-capture (a real browser drives your app)\u2026 (esc to stop)`+(C?`
|
|
453
|
+
${C}`:"")});let b=Date.now(),v=[];try{for(let N of c){if(E.signal.aborted)break;me(V=>V&&{...V,active:[N],rows:rt(V.rows,N,"active"),lastAt:Date.now()});let{exitCode:_,output:se}=await cl({cwd:e,id:N,signal:E.signal,stdio:"pipe"});if(ul(_,se)){p({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 Re=E.signal.aborted&&_!==0?"failed":al(e,N,_,b),nt=Re==="captured"?void 0:Re==="skipped"?Bp(se)??"a data prerequisite isn't met \u2014 the spec's skip reason names what to stage":Hp(se);v.push({id:N,outcome:Re,detail:nt}),me(V=>V&&{...V,active:[],done:V.done+1,rows:rt(V.rows,N,Re==="captured"?"done":"failed"),lastAt:Date.now()})}}catch(N){p({kind:"note",tone:"error",text:`Capture run failed: ${N.message}`})}finally{Ae.current=null,me(null),R(!1),z(N=>N+1)}if(v.length===0)return;let P=v.filter(N=>N.outcome==="captured"),B=v.filter(N=>N.outcome==="skipped"),H=v.filter(N=>N.outcome==="failed"),ee=c.length-v.length;p({kind:"note",tone:H.length?"warn":P.length?"ok":"info",text:[`\u2713 ${P.length} captured`,B.length?`\u2298 ${B.length} blocked`:"",H.length?`\u2717 ${H.length} broken`:"",ee?`${ee} not run (stopped)`:""].filter(Boolean).join(" ")+` ${v.length} run${g>0?` \xB7 ${g} held back`:""}`+Xp(Kp(f,v),y).map(N=>`
|
|
454
|
+
${N}`).join("")});let D=zp(B);if(D.length>0&&p({kind:"note",tone:"info",text:D.join(`
|
|
455
|
+
`)}),H.length>0){let N=Math.max(...H.map(_=>_.id.length));p({kind:"note",tone:"error",text:H.map(_=>`\u2717 ${_.id.padEnd(N)} ${vs(_.detail)}`).join(`
|
|
456
|
+
`)})}if(Xr(e,v.map(N=>({id:N.id,outcome:N.outcome,reason:N.detail,specSource:an(e,N.id)})),new Date().toISOString()),v.length===c.length&&H.length===0&&B.length===0&&vr(u?.runLine),P.length>0){let N=P.map(se=>se.id);p({kind:"note",tone:"info",text:Ho(N.length)}),await de(pn(e,N),{display:"/screenshot verify",quietUser:!0});let _=qo(e,N);_.length>0&&p({kind:"note",tone:"info",text:_.join(`
|
|
457
|
+
`)});return}let O=Qp({results:v,ids:c,articles:Jp(e,P.map(N=>N.id))});O&&Ie(O.note,{kind:"cmd",cmd:O.cmd,reason:""},O.tone)},[e,p,Ie,de,vr]),$i=X(c=>{let u=mn(c);if(!u||Ht(u)&&!u.refreshToken)return null;let a={...Zn(u.idToken)??{},...Zn(u.accessToken)??{}};return a.email??a.preferred_username??"signed in"},[]),vi=X((c,u)=>{if(u){let a=ue(e);a&&(a.defaultProfile=c,Bf(a,e))}i(c),Me(void 0,c),p({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${c}"${u?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),$i(c)||(p({kind:"note",tone:"warn",text:`Profile "${c}" is not signed in \u2014 sign in with /login.`}),J("/login")),z(a=>a+1)},[e,p,Me,$i,J]),xr=X((c,u,a)=>{Er(e,c,u,a.id,a.name),p({kind:"note",tone:"ok",text:`Switched to workspace "${a.name??a.id}" (agent restarted).`}),Me(),Gf(e,c)||(p({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),p({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:"}),p({kind:"note",tone:"info",text:Ln(On(e)).join(`
|
|
458
|
+
`)}),Tt(sn()),ho.current=ot(e).status==="current",En.current=bt(e),p({kind:"note",tone:"info",text:`No separate builder agent? Then just ask me now: "write the docs for this repo" \u2014 I'll read the code directly.`}))},[e,p,Me,Tt]),Rr=X(async c=>{let u;try{u=await $o(e,c)}catch{p({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),J("/workspace");return}if(u.workspaces.length===0){p({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let a=u.workspaces.filter(E=>(E.workspace_type??"").toLowerCase()!=="apidocumentation"),g=a.length>0?a:u.workspaces;if(g.length===1){let E=g[0],F=u.workspaces.length-g.length;p({kind:"note",tone:"ok",text:`Selected the "${E.name??E.id}" workspace${F>0?" (skipped the API-documentation workspace)":""}.`}),xr(u.profile,u.projectId,E);return}p({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${g.length} available).`}),J("/workspace")},[e,p,xr,J]),Cr=X((c,u)=>{Ar(e,c,u.id,u.name),p({kind:"note",tone:"ok",text:`Project set to "${u.name??u.id}" (agent restarted).`}),Me(),Rr(c)},[e,p,Me,Rr]),Fc=X(async c=>{let u;try{u=Xe(e,c)}catch{return}if(!u.project.workspaceId){if(u.project.projectId){if(!u.project.projectName)try{let{projects:a}=await Dt(e,u.name),g=a.find(E=>E.id===u.project.projectId);g?.name&&Qx(e,u.name,{projectName:g.name})}catch{}await Rr(u.name);return}try{let{projects:a}=await Dt(e,u.name);if(a.length===1){let g=a[0];p({kind:"note",tone:"ok",text:`Using your Document360 project "${g.name??g.id}".`}),Cr(u.name,{id:g.id,name:g.name});return}if(a.length>1){let g=a.map(E=>({id:E.id,name:E.name??E.id,sub:E.sub_domain}));p({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),Xt({cursor:0,current:-1,rows:g,profile:u.name,environment:u.connection.name});return}}catch{}p({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),J("/project")}},[e,p,Rr,Cr,J]),An=X(()=>{let c=fe.current[0];if(!c)return;lt();let{plan:u,mode:a}=c;p({kind:"note",tone:"info",text:`\u25CF ${u.title} (${u.path})`});for(let F of u.notes)p({kind:"note",tone:"warn",text:`\u26A0 ${F}`});u.overwritesLocalChanges&&a==="pull"&&p({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let g=Ke(u.oldContent,u.newContent,Pt());p(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 E=fe.current.length;a==="conflict"?(p({kind:"note",tone:"warn",text:"Conflict \u2014 edited both here and on the portal (diff shows local \u2192 portal)."}),p({kind:"note",tone:"info",text:"Keep local (publish, overwrites portal) \xB7 take Portal (overwrites local) \xB7 Skip?"}),p({kind:"note",tone:"info",text:E>1?`(l/p/s \xB7 la/pa/sa for all ${E} \u2014 anything else cancels)`:"(l/p/s \u2014 anything else cancels)"})):p({kind:"note",tone:"info",text:E>1?`Write ${u.path}? (y/n \xB7 ya/na for all ${E} \u2014 anything else cancels)`:`Write ${u.path}? (y/n \u2014 anything else cancels)`})},[p,Pt,lt]),go=X(()=>{if(fe.current.length>0){An();return}let c=Vt.current;Vt.current=[],c.length>0?(p({kind:"note",tone:"info",text:`Publishing ${c.length} kept-local article${c.length===1?"":"s"} over the portal\u2026`}),tt(c)):J("/pull")},[An,p,tt,J]),Bc=X(c=>{if(fe.current.length===0)return!1;let u=c.trim(),a=u.toLowerCase(),g=fe.current[0];if(g.mode==="conflict"){let F=rf(u);if(F){let f=fe.current.splice(0),y=f.length;if(F==="local"){for(let C of f)Vt.current.push(C.plan.path);p({kind:"note",tone:"info",text:`Keeping local for all ${y} \u2014 will publish ${y===1?"it":"them"} over the portal.`})}else if(F==="portal"){let C=0;for(let b of f)try{Js({cwd:e,profileName:s},b.plan),C++}catch(v){p({kind:"note",tone:"error",text:`Take-portal failed for ${b.plan.path}: ${v.message}`})}p({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${C} article${C===1?"":"s"} (local overwritten, sync base advanced).`})}else p({kind:"note",tone:"info",text:`Skipped all ${y} \u2014 still conflict${y===1?"":"s"}.`});return go(),!0}if(a==="l"||a==="local")fe.current.shift(),Vt.current.push(g.plan.path),p({kind:"note",tone:"info",text:`Keeping local ${g.plan.path} \u2014 will publish over the portal.`});else if(a==="p"||a==="portal"){fe.current.shift();try{Js({cwd:e,profileName:s},g.plan),p({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${g.plan.path} (local overwritten, sync base advanced).`})}catch(f){p({kind:"note",tone:"error",text:`Take-portal failed: ${f.message}`})}}else if(a==="s"||a==="skip"||a==="n")fe.current.shift(),p({kind:"note",tone:"info",text:`Skipped ${g.plan.path} \u2014 still a conflict.`});else{let f=fe.current.length;return fe.current=[],Vt.current=[],p({kind:"note",tone:"info",text:`Resolve cancelled (${f} conflict${f===1?"":"s"} left untouched).`}),!0}return go(),!0}let E=sf(u);if(E){let F=fe.current.splice(0);if(E==="skip")p({kind:"note",tone:"info",text:`Skipped all ${F.length} article${F.length===1?"":"s"}.`});else{let f=0;for(let y of F)try{Js({cwd:e,profileName:s},y.plan),f++}catch(C){p({kind:"note",tone:"error",text:`Pull failed for ${y.plan.path}: ${C.message}`})}p({kind:"note",tone:"ok",text:`\u2713 Pulled ${f} article${f===1?"":"s"} (sync base advanced).`})}return go(),!0}if(a==="y"||a==="yes"){let F=fe.current.shift().plan;try{Js({cwd:e,profileName:s},F),p({kind:"note",tone:"ok",text:`\u2713 Pulled ${F.path} (sync base advanced).`})}catch(f){p({kind:"note",tone:"error",text:`Pull failed: ${f.message}`})}}else if(a==="n"||a==="no"){let F=fe.current.shift().plan;p({kind:"note",tone:"info",text:`Skipped ${F.path}.`})}else{let F=fe.current.length;return fe.current=[],p({kind:"note",tone:"info",text:`Pull cancelled (${F} article(s) left untouched).`}),!0}return go(),!0},[e,s,go,p]),xi=X(async c=>{p({kind:"note",tone:"info",text:"Checking Document360 for conflicts\u2026"});try{let u=await Zs({cwd:e,profileName:s}),a=c?.replace(/\\/g,"/"),g=u.entries.filter(F=>F.status==="conflict"&&F.path).map(F=>F.path);if(a){if(!g.includes(a)){p({kind:"note",tone:"ok",text:`${a} isn\u2019t in conflict \u2014 nothing to resolve.`});return}g=[a]}if(g.length===0){p({kind:"note",tone:"ok",text:"\u2713 No conflicts \u2014 local and Document360 agree on every tracked article."});return}let E=[];for(let F of g)try{E.push({plan:await Yf({cwd:e,profileName:s,relPath:F}),mode:"conflict"})}catch(f){p({kind:"note",tone:"error",text:`Could not load ${F} from Document360: ${f.message}`})}if(E.length===0)return;p({kind:"note",tone:"info",text:`Resolving ${E.length} conflict${E.length===1?"":"s"} \u2014 for each: keep local, take portal, or skip.`}),fe.current=E,Vt.current=[],An()}catch(u){p({kind:"note",tone:"error",text:`Could not compute sync status: ${u.message}`})}},[e,s,p,An]),Hc=X(c=>{let u=no.current;if(!u)return!1;if(no.current=null,lt(),c.trim()!==u.repoName)return p({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:a,failed:g}=Dl(e,u.targets);p({kind:"note",tone:g.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${a.length} item${a.length===1?"":"s"}. The repo is back to its original state.`});for(let E of g)p({kind:"note",tone:"error",text:` \u2717 ${E.path}: ${E.error}`});return u.hadDevhints&&(p({kind:"note",tone:"warn",text:qr().join(`
|
|
459
|
+
`)}),Tt(Ii())),p({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
|
|
460
|
+
${om}`}),J("/init"),ar(!1),!0},[e,p,Tt,lt,J]),yo=X(async c=>{let u=c.slice(1).trim().split(/\s+/),a=(u[0]??"").toLowerCase(),g=u.slice(1);if(ar(!0),Mo(g)&&["write","check","review","reorder"].includes(a)){let f=_o(e,s);if(f.length===0){p({kind:"note",tone:"warn",text:"No categories yet \u2014 author some articles first, then scope to one."});return}let y=C=>a==="write"?`/write ${cp(g,C).join(" ")}`.trim():`/${a} ${[C,...g.filter(b=>b!=="--scope")].join(" ")}`.trim();if(f.length===1){yo(y(f[0].token));return}Jt({cursor:0,rows:f,run:C=>{yo(y(C))}});return}if(Wt(a,g)){let f=a==="write"&&Uo(g).rewrite,y=a==="write"?qa(e,Qf(e),{rewrite:f}):_o(e,s);if(y.length>1){let C=g.filter(H=>H.startsWith("--")).join(" "),b=H=>`/${a}${H?` ${a==="write"?`--scope ${H}`:H}`:""}${C?` ${C}`:""} ${H?"":"--all"}`.replace(/\s+/g," ").trim(),v=y.reduce((H,ee)=>H+ee.count,0),P={token:"",label:a==="review"?`Everything \u2014 all ${v} articles + structure (IA) review`:a==="reorder"?`Everything \u2014 reorder all ${y.length} categories`:f?`Everything \u2014 rewrite all ${v} planned articles`:`Everything \u2014 write all ${v} pending article${v===1?"":"s"}`,count:v},B=a==="write"?`Write which articles? (counts = ${f?"articles to regenerate":"still to write"})`:a==="review"?"Review what? (counts = articles)":"Reorder what?";Jt({cursor:0,rows:[P,...y],run:H=>{yo(b(H))},title:B});return}}let E=async f=>{let y=rl(f);if(!xs(e)){await de(dl(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(y.mode==="single"){await mo([y.id],{runLine:[`/screenshot capture ${y.id}`,`/capture ${y.id}`]});return}if(y.mode==="failed"){let b=sl(e,Vo(e).rows);if(b.length===0){p({kind:"note",tone:"info",text:"No broken specs to re-run \u2014 /screenshot list shows where things stand."}),J("/screenshot list");return}await mo(b);return}if(y.mode==="blocked"){let{blocked:b,rows:v}=Vo(e);if(b.length===0){p({kind:"note",tone:"info",text:"No shots are waiting on app data \u2014 /screenshot list shows where things stand."}),J("/screenshot list");return}let P=jo(v.filter(B=>B.state==="blocked")).length;p({kind:"note",tone:"info",text:`Re-running ${b.length} shot${b.length===1?"":"s"} that skipped on missing data last run.`+(P>0?` If you haven't staged ${P===1?"it":"those "+P+" things"} yet, ${b.length===1?"it":"they"} will skip again \u2014 /screenshot list has the worklist.`:"")}),await mo(b,{runLine:["/screenshot capture --blocked","/screenshot capture --all --retry-blocked"]});return}if(y.mode==="all"||y.mode==="scope"){let b=y.mode==="scope"?y.scope:void 0,{ready:v,captured:P,blocked:B,rows:H}=Vo(e,b),ee=[...v,...P,...y.retryBlocked?B:[]];if(ee.length===0&&B.length>0&&!y.retryBlocked){let O=b?`/screenshot capture ${b} --retry-blocked`:"/screenshot capture --blocked";Ie(`All ${B.length} shot${B.length===1?"":"s"} in scope ${B.length===1?"is":"are"} blocked on data that wasn't staged last run \u2014 /screenshot list shows what to stage, then ${O}.`,{kind:"cmd",cmd:"/screenshot list",reason:""},"warn");return}if(ee.length===0){p({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),J("/screenshot");return}if(!y.retryBlocked){let O=b?`/screenshot capture ${b} --retry-blocked`:"/screenshot capture --blocked",N=il(H.filter(_=>_.state==="blocked"),O);N&&p({kind:"note",tone:"info",text:N})}let D=y.mode==="scope"?[`/screenshot capture ${y.scope}`,`/capture ${y.scope}`]:["/screenshot capture --all","/capture --all"];await mo(ee,{runLine:D,...y.retryBlocked?{}:{heldBackBlocked:H.filter(O=>O.state==="blocked")}});return}let C=Fp(Pe(e));if(C.length===0){p({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),J("/screenshot");return}Qt({cursor:0,rows:C,title:"Capture screenshots \u2014 pick what to shoot:"})},F=async()=>{let f=await qn();f.kind==="forward-to-agent"&&f.prompt&&await de(f.prompt,{display:f.display,quietUser:!0}),di()};switch(a){case"help":nn({tab:0,scroll:0});return;case"exit":case"quit":Je.current?.close(),r();return;case"clear":Me(),kn.current=[],Ve.current={printed:[],armed:[]},ar(!1),lt(),console.log("\x1B[?2026h\x1B[H\x1B[2J\x1B[3J\x1B[?2026l"),p({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let f;try{f=Xe(e,s)}catch(y){p({kind:"note",tone:"error",text:y.message});return}p({kind:"note",tone:"info",text:`Profile "${f.name}" \u2192 ${f.connection.name} (${f.connection.apiUrl})${f.production?" \u26A0 PRODUCTION":""}`}),Y(!0);try{let y=await bx(f.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},b=>p({kind:"note",tone:"info",text:b})),C=$x(f.name,y);if(vx(C),await Pi(C,f.name,b=>p({kind:"note",tone:"info",text:b})),p({kind:"note",tone:"ok",text:`\u2713 Logged in to "${f.name}" as ${Nr(C)}`}),await Fc(s),so.current){let b=so.current;so.current=null;let v=Fe(e,s);v.ok?(p({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 tab to run ${b}.`}),J(b)):(p({kind:"note",tone:"warn",text:`${v.reason} (then ${b}.)`}),J("/login"),so.current=b)}else ro.current&&(Ne(ro.current,"\u21E5 tab to re-send your last prompt\u2026"),ro.current=null)}catch(y){p({kind:"note",tone:"error",text:`Login failed: ${y.message}`})}finally{Y(!1),z(y=>y+1)}return}case"allow-prod":{let f=!1;try{f=Xe(e,s).production}catch{}if(!f){p({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}bn.current=!0,Me(),p({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let f=Ja(g.join(" ")),y=ft.current.uuid;if(!y){if(!f){p({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}ii.current=f,Yt(f),Yn(`${Vs} ${f}`),p({kind:"note",tone:"ok",text:`Session will be named "${f}" once it starts.`});return}if(!f){p({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let C=ft.current.firstPrompt??"";Ff(C,e).then(b=>{b?(Ne(`/rename ${b}`),p({kind:"note",tone:"info",text:`Suggestion: "${b}" \u2014 press tab to accept, or type /rename <your name>.`})):p({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>p({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}Nx(y,f),Yt(f),Yn(`${Vs} ${f}`),p({kind:"note",tone:"ok",text:`Session renamed to "${f}".`});return}case"profile":{let f=g[0],y=ue(e);if(!f){let C=Object.entries(y?.profiles??{});if(C.length===0){p({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let b=C.map(([B,H])=>({name:B,env:H.connection?.environment??"custom",prod:H.production===!0,who:$i(B)})),v=s??y?.defaultProfile,P=Math.max(0,b.findIndex(B=>B.name===v));$n({cursor:P,current:P,rows:b});return}if(f==="add"){let C=Za(e,g[1],g[2]);if(C){p({kind:"note",tone:"error",text:C});return}p({kind:"note",tone:"ok",text:`\u2713 Profile "${g[1]}" created (environment: ${g[2]??g[1]}).`}),vi(g[1],!0);return}if(!y?.profiles?.[f]){p({kind:"note",tone:"error",text:`Unknown profile "${f}". Create it: /profile add ${f} <environment>`});return}vi(f,!0);return}case"doctor":await Fo(g,{cwd:e,version:o});return;case"genre":{let f=ue(e)?.appType??null;(await As(g,{cwd:e})).kind==="clear"&&(ue(e)?.appType??null)!==f&&(Me(),p({kind:"note",tone:"ok",text:"\u2713 Agent restarted \u2014 the doc-craft playbook for this genre is now loaded."}));try{xt.current=!(ue(e)?.appType??qf(e))}catch{}z(C=>C+1);return}case"roadmap":{if(g[0]?.toLowerCase()==="done"){let f=js(e,g.slice(1).join(" ").trim());p({kind:"note",tone:f.ok?"ok":"warn",text:f.line}),z(y=>y+1);return}p({kind:"note",tone:"info",text:_l(e).join(`
|
|
461
|
+
`)});return}case"mcp":await Yr(g);return;case"init":{if(ue(e)){let y=jt(e,s);p({kind:"note",tone:"info",text:["This repo is already set up \u2014 /init won\u2019t overwrite it.",` Change environment: /profile add <${Kf().join("|")}> then /profile <name> (the environment lives on the profile, not the login).`," Anything else: edit .d360-writer/config.json, or run d360-writer init for the CLI wizard."].join(`
|
|
462
|
+
`)}),y&&p({kind:"note",tone:"warn",text:`\u26A0 ${y.why} \u2014 ${y.cmd} moves this repo.`});return}let f=[...Kf(),...Fx().filter(y=>zf(y))].map(y=>({name:y,apiUrl:Bx(y).apiUrl,note:zf(y)?"being retired":null}));vn({cursor:0,rows:f});return}case"resume":{let f=g.join(" ").trim(),y=jx(e).filter(v=>v.uuid!==ft.current.uuid);if(!f){if(!y.length){p({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}tn({query:"",cursor:0,sessions:y});return}let C=Dx(e,f);if(!C){p({kind:"note",tone:"error",text:`No session matches "${f}".`});return}Me(C.uuid),ft.current={uuid:C.uuid,firstPrompt:C.firstPrompt,titleFired:!0},Yt(C.name),sc(C.uuid),kn.current=[],Ve.current={printed:[],armed:[]};let b=Ql(e,C.uuid);for(let v of b)p(v);p({kind:"note",tone:"ok",text:b.length?`Resumed "${C.name}" \u2014 restored ${b.length} message(s); continue where you left off.`:`Resumed "${C.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let f=g.join(" ").trim(),y;try{y=await $o(e,s)}catch(b){p({kind:"note",tone:"error",text:`Could not list workspaces: ${b.message}`});return}if(!f){let b=y.workspaces.map(P=>({id:P.id,name:P.name??P.id,type:P.workspace_type}));if(b.length===0){p({kind:"note",tone:"info",text:"No workspaces in this project."});return}let v=Math.max(0,b.findIndex(P=>P.id===y.current));xn({cursor:v,current:v,rows:b,profile:y.profile,projectId:y.projectId,projectName:y.projectName,environment:y.environment});return}let C=Ci(y.workspaces,f);if(!C){p({kind:"note",tone:"error",text:`No workspace matches "${f}".`});return}xr(y.profile,y.projectId,C);return}case"project":{let f=g.join(" ").trim(),y;try{y=await Dt(e,s)}catch(b){p({kind:"note",tone:"error",text:`Could not list projects: ${b.message} (signed in? try /login)`});return}if(!f){let b=y.projects.map(P=>({id:P.id,name:P.name??P.id,sub:P.sub_domain}));if(b.length===0){p({kind:"note",tone:"info",text:"No projects found for this identity."});return}let v=b.findIndex(P=>P.id===y.current);Xt({cursor:Math.max(0,v),current:v,rows:b,profile:y.profile,environment:y.environment});return}let C=Si(y.projects,f);if(!C){p({kind:"note",tone:"error",text:`No project matches "${f}". Available: ${y.projects.map(b=>b.name??b.id).join(", ")}`});return}Cr(y.profile,C);return}case"logout":{let f;try{f=Xe(e,s).name}catch(C){p({kind:"note",tone:"error",text:C.message});return}let y=Sx(f);Px(e,f),Me(),z(C=>C+1),p({kind:"note",tone:y?"ok":"info",text:y?`\u2713 Signed out of "${f}" and cleared its project/workspace selection.`:`Profile "${f}" was not signed in. Cleared any project/workspace selection.`}),p({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),J("/login");return}case"publish":{if(!uo(c.trim()))return;let f=g.includes(pt);if(g.includes("--screenshots")||g.includes("--shots")){let v=Pe(e),P=ss(v);if(P.length===0){p({kind:"note",tone:"info",text:"No captured screenshots yet \u2014 /screenshot capture first."});return}let B=is(v);B&&p({kind:"note",tone:"warn",text:B}),p({kind:"note",tone:"info",text:`Re-saving ${P.length} article${P.length===1?"":"s"} with captured screenshots so the images embed\u2026`}),await tt(P,0,{skipReview:f});return}if(g[0]==="--related"&&g[1]){let v=await hs(e,s,g[1].replace(/\\/g,"/"));if(v.length===0){p({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await tt(v,0,{skipReview:f});return}let y=g.filter(v=>!v.startsWith("--"));if(y[0]){await bi(y[0],{skipReview:f});return}let C=g.includes("--all"),b=g.includes("--force");p({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let v=await Zs({cwd:e,profileName:s}),{clean:P,conflicts:B}=cn(v.entries),H=C&&b&&B.length>0,ee=ds(v.entries);if(ee>0&&p({kind:"note",tone:"warn",text:`\u26A0 ${ee} article${ee===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.`}),B.length>0&&!H&&p({kind:"note",tone:"warn",text:ln(B.length)}),P.length===0&&!H){if(B.length>0){J("/resolve");return}p({kind:"note",tone:"ok",text:ee>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let D=v.counts["unknown-base"]??0;D>0&&p({kind:"note",tone:"info",text:`(${D} article(s) have no sync base yet \u2014 publish those by path if needed.)`}),gt("Reconciling structure on Document360 (order + related articles)\u2026");try{let O=await cc({cwd:e,profileName:s,onRateLimit:se=>gt(`Document360 rate limit \u2014 waiting ${Math.ceil(se.waitMs/1e3)}s\u2026`)}),N=nm(await tm({cwd:e,profileName:s})),_=uc(O);_?p({kind:"note",tone:_.startsWith("\u26A0")?"warn":"info",text:_}):O.skipped&&p({kind:"note",tone:"warn",text:`Order sync skipped: ${O.skipped}`}),N&&p({kind:"note",tone:"info",text:N}),O.failures?.length?J("/structure"):(p({kind:"note",tone:"ok",text:_||N?"\u2713 Structure synced to Document360 \u2014 /structure shows the new category + article order.":"\u2713 Already in order \u2014 nothing to change."}),(_||N)&&J("/structure"))}catch(O){p({kind:"note",tone:"warn",text:`Structure sync failed: ${O.message}`})}finally{gt(null)}return}if(C){let D=(H?[...P,...B]:P).map(O=>O.path);await tt(D,H?0:B.length,{skipReview:f});return}Rn({cursor:0,rows:Hd(P,B),conflicts:B.length})}catch(v){p({kind:"note",tone:"error",text:`Could not compute sync status: ${v.message}`}),p({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"resolve":{if(!uo(c.trim()))return;await xi(g.find(f=>!f.startsWith("--")));return}case"preview":{let f=g.join(" ").trim();if(!f){let C=[];try{C=Object.keys(Gf(e,Xe(e,s).name)?.articles??{})}catch{}if(C.length===0){p({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}Zt({query:"",cursor:0,paths:C});return}let y=wx(f)?f:rc(e,f);if(zn(y)){try{p({kind:"preview",name:rr(y),text:im(Qs(y,"utf8"))})}catch(C){p({kind:"note",tone:"error",text:`Could not read ${y}: ${C.message}`})}return}if(p0.test(f)){try{let C=Xe(e,s),b={profile:C.name,connection:C.connection},v=C.project.projectId??Rx(b),P=await Cx(b,v,f);p({kind:"preview",name:P.title??f,text:P.content??"*(article has no content)*"})}catch(C){p({kind:"note",tone:"error",text:`Could not fetch article: ${C.message}`})}return}p({kind:"note",tone:"error",text:`"${f}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let f=g[0]?.trim();if(!f){let v=bs(pc(e));zt({cursor:v,current:v});return}let{lines:y,changed:C,effective:b}=Wo(e,f);for(let v of y)p({kind:"note",tone:v.startsWith("\u26A0")?"warn":v.startsWith("\u2713")?"ok":"info",text:v});C&&(Sc(v=>v+1),Je.current?.setModel(b));return}case"verbose":{let f=g[0]?.trim().toLowerCase(),y=f==="on"?!0:f==="off"?!1:!ur.current;ur.current=y;try{Ox({...Hf(),verboseTranscript:y})}catch{p({kind:"note",tone:"warn",text:"\u26A0 Applied for this session, but the setting could not be saved."})}p({kind:"note",tone:"ok",text:y?"\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(!ue(e)){p({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:f,run:y}=Ea(g),C=Gx(e,s);if(C.length===0){p({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let b=Aa(C,f);if(b.length===0){p({kind:"note",tone:"error",text:`No tracked articles under "${f}". (${C.length} are tracked overall.)`});return}let v=ic(b),P=3,B=`/convert${f?` --scope ${f}`:""} --run`,H=ti(e,"light");if(!y){let D=Xf({files:Da(e,b),op:"convert",model:H.model}),O=f?`Scope: ${f} (${b.length} of ${C.length} tracked)
|
|
463
463
|
`:"",N=`
|
|
464
|
-
Model: ${
|
|
465
|
-
`)+N}),
|
|
466
|
-
`):O+
|
|
467
|
-
`)}),
|
|
464
|
+
Model: ${H.model}${H.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;p({kind:"note",tone:"info",text:O+Na(v,D,P).join(`
|
|
465
|
+
`)+N}),J(B);return}Gt.current=Date.now(),gn(0),R(!0);let ee=new AbortController;Ae.current=ee,me({verb:"Converting",total:v.length,done:0,active:[],rows:or(v),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),p({kind:"note",tone:"info",text:`Converting ${b.length} articles across ${v.length} partitions (\u2264${P} agents at once) on ${H.model}\u2026 (esc to stop)`});try{for await(let D of ei({cwd:e,partitions:v,promptFor:ja,concurrency:P,profileName:s,allowProdWrites:bn.current,model:H.model,signal:ee.signal}))if(D.type==="partition_status")D.status==="running"?me(O=>O&&{...O,active:[...O.active,D.label],rows:rt(O.rows,D.label,"active"),lastAt:Date.now()}):me(O=>O&&{...O,active:O.active.filter(N=>N!==D.label),done:O.done+1,rows:rt(O.rows,D.label,D.status==="done"?"done":"failed"),lastAt:Date.now()});else if(D.type==="partition_event")me(O=>{if(!O)return O;let N={...O,lastAt:Date.now()};return D.event.type==="tool"?N.tools=O.tools+1:D.event.type==="text"&&(N.chars=O.chars+D.event.delta.length),N});else if(D.type==="run_done"){Tn(se=>se+D.totalCostUsd),Pn(se=>se+D.results.reduce((Re,nt)=>Re+nt.outputTokens,0));let O=D.aborted?"Stopped. ":"",N=t.kind==="api"?"api":"subscription",_=ut(D,"The conversion");p({kind:"note",tone:_||D.aborted?"warn":D.ok?"ok":"warn",text:_?_.join(`
|
|
466
|
+
`):O+Ia(D.results,v,N).join(`
|
|
467
|
+
`)}),_&&J("/doctor")}}catch(D){p({kind:"note",tone:"error",text:`Convert run failed: ${D.message}`})}finally{Ae.current=null,me(null),R(!1),z(D=>D+1)}return}case"write":{if(!ue(e)){p({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let f=Qf(e);if(f.length===0){p({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:y,path:C,preview:b,concurrency:v,rewrite:P}=Uo(g);if(!C&&!b&&!(ue(e)?.appType??qf(e))){p({kind:"note",tone:"warn",text:`\u26A0 No doc genre is set, so no doc-craft playbook would load \u2014 all ${f.length} articles would be written generically.
|
|
468
468
|
Pick the genre below (one keypress), then run /write again \u2014 it changes structure, titles and depth for every article.
|
|
469
|
-
Not blocked: /write <path> still authors a single article, and /write --preview costs nothing.`}),
|
|
469
|
+
Not blocked: /write <path> still authors a single article, and /write --preview costs nothing.`}),le(Ns.options.map(V=>({cmd:V.cmd,desc:V.desc}))),Cn(Ns.title);return}let{docsDir:B,targets:H,reason:ee,rewriting:D}=ws(e,f,{scope:y,path:C,rewrite:P});if(H.length===0){p({kind:"note",tone:"warn",text:ee??"Nothing to write."});return}D&&p({kind:"note",tone:"warn",text:`--rewrite: regenerating ${H.length} already-written article${H.length===1?"":"s"} (overwrites them; git has your baseline).`});let O=ic(H),N=_a(v),_=ti(e,"standard"),se=!!C;if(b&&!se){let V=Xf({files:Ua(e,f,H),op:"write",model:_.model}),ce=y?`Scope: ${y} (${H.length} pending)
|
|
470
470
|
`:"",De=`
|
|
471
|
-
Model: ${
|
|
472
|
-
`)+De}),
|
|
473
|
-
`):
|
|
474
|
-
`)}),
|
|
475
|
-
${f.map(
|
|
476
|
-
`)}`}),
|
|
477
|
-
`)});return}if(f==="--baseline"){let b=g.find(
|
|
478
|
-
${
|
|
479
|
-
`)}`}),
|
|
480
|
-
`)});return}if(f){p({kind:"note",tone:"error",text:`Unknown option: ${f} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let y=g[0];if(y){let b=await
|
|
481
|
-
`)}),Ie(
|
|
482
|
-
`)}),
|
|
483
|
-
`)});return}case"reorder":{let f=
|
|
484
|
-
`)}),
|
|
485
|
-
`)}),f.threads.length>0&&
|
|
486
|
-
`)});return}if(f.mode==="list"){if(!
|
|
487
|
-
`)}),
|
|
488
|
-
`)}),y&&p({kind:"note",tone:"info",text:y});let B
|
|
489
|
-
`)}),Ne(Zo(e));return}default:p({kind:"note",tone:"error",text:`Unknown command: /${l} \u2014 type /help.`})}},[e,r,s,Pn,ki,p,Me,ue,nn,mi,Lc]),vr=Q(c=>{let u=(c??k).trim();if(v(""),rr(null),hn(0),u.startsWith("/")&&(Re.current=!1,Se.current=!1,Qe.current=null,at(),vn(null),de(g=>wf(g,u))),!u||(er(!1),Mc(u))||_c(u))return;ei.current.push(u);let l=vf(u,fc.current);if(u.startsWith("/"))p({kind:"user",text:u}),$e(!0),ho(l).finally(()=>$e(!1));else if(qx(l)){p({kind:"user",text:u});let g=Gx(l);if(!g)ue(l,{display:u,quietUser:!0});else{try{Vx(e,{title:g,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}ue(`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:u,quietUser:!0})}}else{let g=Ch(e,l);ue(g??l,{display:u})}},[k,Mc,_c,ho,ue]),Uc=Q(c=>{if(c.length>1){if(c.includes("\x1B"))return;let u=kf(c);if(bf(u)){let l=$f(++dm.current,u);fc.current.set(l,u),R(l)}else R(u);return}R(c)},[R]),Tn=Math.max(10,Ye-6),Fc=Jl(()=>Vs(h.text,Tn),[h.text,Tn]),bi=Q(c=>m(u=>({...u,pos:Math.max(0,Math.min(u.text.length,u.pos+c))})),[]),xr=Q(c=>m(u=>({...u,pos:Cf(Vs(u.text,Tn),u.pos,c)})),[Tn]),fo=Q(c=>m(u=>({...u,pos:Rf(Vs(u.text,Tn),u.pos,c)})),[Tn]),ym=["\x1B[H","\x1B[1~","\x1BOH"],wm=["\x1B[F","\x1B[4~","\x1BOF"],Wc=Q((c,u)=>u.leftArrow?(bi(-1),!0):u.rightArrow?(bi(1),!0):c&&ym.includes(c)?(fo("start"),!0):c&&wm.includes(c)?(fo("end"),!0):u.ctrl&&c==="a"?(fo("start"),!0):u.ctrl&&c==="e"?(fo("end"),!0):!1,[bi,fo]);return tx((c,u)=>{if(u.ctrl&&c==="c"){Je.current?.close(),r();return}if(lo.current.awaySince!==null)try{let l=lf(lo.current,Date.now(),cn(e));if(lo.current=l.memory,Ec(null),l.kind==="delta"){p({kind:"note",tone:"info",text:uf(l.delta,l.awayMs)});let g=et(!1);g.kind==="recommend"&&ft(g.rec,{silent:!0})}else if(l.kind==="briefing"){p({kind:"note",tone:"info",text:`\u{1F4E5} ${Xo(l.delta)} arrived while you were away (${zl(l.awayMs)}).`});let g=et(!1);g.kind==="recommend"&&ft(g.rec)}}catch{}if(di.current=Date.now(),!I){if(S){if(u.escape){if(Ae.current){if(!Ae.current.signal.aborted){let l=(ar?.verb??"work").toLowerCase(),g=ar?.unit??"article";p({kind:"note",tone:"warn",text:`\u238B Stopping the ${l} run (finishing in-flight ${g}s)\u2026`}),Ae.current.abort()}return}eo.current||(eo.current=!0,p({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),Je.current?.interrupt());return}if(u.return){let l=k.trim();if(!l)return;Qt.current.push(l),ni([...Qt.current]),v("");return}if(Wc(c,u))return;if(u.upArrow){xr(-1);return}if(u.downArrow){xr(1);return}if(u.backspace||u.delete){$();return}c&&!u.ctrl&&!u.meta&&Uc(c);return}if(Gt){if(u.upArrow){Vt(l=>l&&{...l,cursor:Math.max(0,l.cursor-1)});return}if(u.downArrow){Vt(l=>l&&{...l,cursor:Math.min(ut.length-1,l.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=ut.length){Vt(l=>l&&{...l,cursor:Number(c)-1});return}if(u.return){let l=ut[Gt.cursor];Vt(null);let{lines:g,changed:A,effective:G}=Oo(e,l.value??"default");for(let f of g)p({kind:"note",tone:f.startsWith("\u26A0")?"warn":f.startsWith("\u2713")?"ok":"info",text:f});A&&(vc(f=>f+1),Je.current?.setModel(G));return}if(c==="s"){let l=ut[Gt.cursor];Vt(null),Je.current?.setModel(l.value??void 0),p({kind:"note",tone:"ok",text:`\u2713 Using ${l.label} for this session only (your saved default is unchanged).`});return}if(u.escape){Vt(null);return}return}if($t){if(u.upArrow){wn(l=>l&&{...l,cursor:Math.max(0,l.cursor-1)});return}if(u.downArrow){wn(l=>l&&{...l,cursor:Math.min(l.rows.length-1,l.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=$t.rows.length){wn(l=>l&&{...l,cursor:Number(c)-1});return}if(u.return||c==="s"){let l=$t.rows[$t.cursor];wn(null),yi(l.name,u.return===!0);return}if(u.escape){wn(null);return}return}if(oo){if(u.escape){Zt(null);return}if(u.leftArrow||u.tab&&u.shift){Zt(l=>l&&{tab:(l.tab-1+Ue.length)%Ue.length,scroll:0});return}if(u.rightArrow||u.tab){Zt(l=>l&&{tab:(l.tab+1)%Ue.length,scroll:0});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ue.length){Zt({tab:Number(c)-1,scroll:0});return}if(u.upArrow){Zt(l=>l&&{...l,scroll:Math.max(0,l.scroll-1)});return}if(u.downArrow){Zt(l=>{if(!l)return l;let g=(Ue[l.tab]??Ue[0]).rows.length;return{...l,scroll:Math.min(Math.max(0,g-1),l.scroll+1)}});return}return}if(vt){if(u.upArrow){kn(l=>l&&{...l,cursor:Math.max(0,l.cursor-1)});return}if(u.downArrow){kn(l=>l&&{...l,cursor:Math.min(l.rows.length-1,l.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=vt.rows.length){kn(l=>l&&{...l,cursor:Number(c)-1});return}if(u.return){let l=vt.rows[vt.cursor].name;if(kn(null),!Di(e,l).created){p({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}p({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${l}").`});let A=!1;try{let G=dn(l);A=!!G&&!(Wt(G)&&!G.refreshToken)}catch{A=!1}p({kind:"note",tone:"info",text:A?`Next: sign in to ${l} and pick your project \u2014 you're already signed in here, so it'll be quick.`:`Next: sign in to Document360 (${l}) and pick your project.`}),Z("/login"),K(G=>G+1);return}if(u.escape){kn(null);return}return}if(Oe){if(u.upArrow){bn(l=>l&&{...l,cursor:Math.max(0,l.cursor-1)});return}if(u.downArrow){bn(l=>l&&{...l,cursor:Math.min(l.rows.length-1,l.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Oe.rows.length){bn(l=>l&&{...l,cursor:Number(c)-1});return}if(u.return){let l=Oe.rows[Oe.cursor],{profile:g,projectId:A}=Oe;bn(null),kr(g,A,l);return}if(u.escape){bn(null);return}return}if(Ze){if(u.upArrow){Yt(l=>l&&{...l,cursor:Math.max(0,l.cursor-1)});return}if(u.downArrow){Yt(l=>l&&{...l,cursor:Math.min(l.rows.length-1,l.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ze.rows.length){Yt(l=>l&&{...l,cursor:Number(c)-1});return}if(u.return){let l=Ze.rows[Ze.cursor],{profile:g}=Ze;Yt(null),$r(g,l);return}if(u.escape){Yt(null);return}return}if(Le){if(u.upArrow){xn(l=>l&&{...l,cursor:Math.max(0,l.cursor-1)});return}if(u.downArrow){xn(l=>l&&{...l,cursor:Math.min(l.rows.length-1,l.cursor+1)});return}if(c===" "){xn(l=>l&&{...l,rows:l.rows.map((g,A)=>A===l.cursor?{...g,checked:!g.checked}:g)});return}if(u.return){let l=Le.rows.filter(g=>g.checked).map(g=>g.path);if(xn(null),l.length===0){p({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}ya(e,l),p({kind:"note",tone:"ok",text:`\u2713 Scoped to ${l.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let g of l)p({kind:"note",tone:"info",text:` ${g}`});p({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(u.escape){xn(null);return}return}if(it){if(u.upArrow){zt(l=>l&&{...l,cursor:Math.max(0,l.cursor-1)});return}if(u.downArrow){zt(l=>l&&{...l,cursor:Math.min(l.rows.length-1,l.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=it.rows.length){zt(l=>l&&{...l,cursor:Number(c)-1});return}if(u.return){let l=it.rows[it.cursor],g=it.run;zt(null),g(l.token);return}if(u.escape){zt(null);return}return}if(pt){if(u.upArrow){$n(l=>l&&{...l,cursor:Math.max(0,l.cursor-1)});return}if(u.downArrow){$n(l=>l&&{...l,cursor:Math.min(l.rows.length-1,l.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=pt.rows.length){$n(l=>l&&{...l,cursor:Number(c)-1});return}if(u.return){let l=pt.rows[pt.cursor],g=pt.conflicts;$n(null),l.conflict?ki(l.paths[0]):l.kind==="article"?mi(l.paths[0]):nn(l.paths,l.kind==="all"?g:0);return}if(u.escape){$n(null);return}return}if(xt){if(u.upArrow){Kt(l=>l&&{...l,cursor:Math.max(0,l.cursor-1)});return}if(u.downArrow){Kt(l=>l&&{...l,cursor:Math.min(l.rows.length-1,l.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=xt.rows.length){Kt(l=>l&&{...l,cursor:Number(c)-1});return}if(u.return){let l=xt.rows[xt.cursor];Kt(null),l.action==="capture"?po(l.ids,{runLine:l.kind==="all"?["/screenshot capture --all","/capture --all"]:void 0}):l.kind==="shot"?Oc(l.ids[0]):Ic(l.ids,{setup:!0,runLine:l.kind==="all"?["/screenshot author --all","/screenshot --all"]:void 0});return}if(u.escape){Kt(null);return}return}if(qe){if(u.escape){Xt(null);return}if(u.upArrow){Xt(l=>l&&{...l,cursor:Math.max(0,l.cursor-1)});return}if(u.downArrow){Xt(l=>l&&{...l,cursor:Math.min(Math.max(0,gr.length-1),l.cursor+1)});return}if(u.return){let l=gr[qe.cursor];if(l){Xt(null);try{p({kind:"preview",name:Zo(l),text:em(Ks(Zl(e,l),"utf8"))})}catch(g){p({kind:"note",tone:"error",text:`Could not read ${l}: ${g.message}`})}}return}if(u.backspace||u.delete){Xt(l=>l&&{...l,query:l.query.slice(0,-1),cursor:0});return}if(c&&!u.ctrl&&!u.meta&&c.length===1){Xt(l=>l&&{...l,query:l.query+c,cursor:0});return}return}if(Ge){if(u.escape){Jt(null);return}if(u.upArrow){Jt(l=>l&&{...l,cursor:Math.max(0,l.cursor-1)});return}if(u.downArrow){Jt(l=>l&&{...l,cursor:Math.min(Math.max(0,yr.length-1),l.cursor+1)});return}if(u.return){let l=yr[Ge.cursor];if(l){Jt(null),Me(l.uuid),dt.current={uuid:l.uuid,firstPrompt:l.firstPrompt,titleFired:!0},qt(l.name),ec(l.uuid),mn.current=[],Ve.current={printed:[],armed:[]};let g=Vl(e,l.uuid);for(let A of g)p(A);p({kind:"note",tone:"ok",text:g.length?`Resumed "${l.name}" \u2014 restored ${g.length} message(s); continue where you left off.`:`Resumed "${l.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(u.backspace||u.delete){Jt(l=>l&&{...l,query:l.query.slice(0,-1),cursor:0});return}if(c&&!u.ctrl&&!u.meta&&c.length===1){Jt(l=>l&&{...l,query:l.query+c,cursor:0});return}return}if(u.tab&&!k&&ye){v(ye),at();return}if(!k&&pe.length>0&&!Bt&&c&&/^[1-9]$/.test(c)){let l=pe[Number(c)-1];if(l){v(un(l));return}}if(!k&&pe.length===0&&!Bt&&Ve.current.armed.length>0&&c&&/^[1-9]$/.test(c)){let l=Ve.current.armed[Number(c)-1];if(l){v(l);return}}if(!k&&(hr||so)&&c==="c"&&!u.ctrl&&!u.meta&&!u.return&&!u.tab){let l=hr!=null;Hl(hr??so).then(A=>{p({kind:"note",tone:A?"ok":"warn",text:A?l?"\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.":l?"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&&l&&ui(null),A&&!l&&Cc(!0)});return}if(!Wc(c,u)){if(Dc){if(u.upArrow){hn(l=>Math.max(0,l-1));return}if(u.downArrow){hn(l=>Math.min(mt.length-1,l+1));return}if(u.tab){v("/"+(mt[Zs]?.name??"")+" "),hn(0);return}if(u.return){let l=mt[Zs];if(l){let g=k.trim().slice(1).split(/\s+/).slice(1).join(" ");if(Mu(l.usage)&&!g){v("/"+l.name+" "),hn(0);return}vr("/"+l.name+(g?" "+g:""));return}}}else{if(u.upArrow){if(k!==""&&fn===null){xr(-1);return}let l=ei.current;if(!l.length)return;let g=fn===null?l.length-1:Math.max(0,fn-1);rr(g),v(l[g]??"");return}if(u.downArrow){if(k!==""&&fn===null){xr(1);return}let l=ei.current;if(fn===null)return;let g=fn+1;g>=l.length?(rr(null),v("")):(rr(g),v(l[g]??""));return}}if(u.return){vr();return}if(u.backspace||u.delete){$();return}if(u.escape){v(""),hn(0),at(),de([]),vn(null),Re.current=!0;return}c&&!u.ctrl&&!u.meta&&Uc(c)}}}),He(()=>{if(S||I)return;let c=Qt.current.shift();c!==void 0&&(ni([...Qt.current]),vr(c))},[S,I,vr]),oe(ge,{flexDirection:"column",width:Ye,children:[fi!==null&&oe(ge,{marginTop:1,flexDirection:"column",children:[fi.truncated&&L(_,{dimColor:!0,children:"\u2026"}),L(_,{children:fi.text})]}),S&&(ar?L(r0,{p:ar}):L(t0,{startTime:Ht.current,chars:um})),!S&&kc?L(n0,{text:kc}):null,L(ge,{borderStyle:"round",borderColor:Ac.prod?"yellow":te,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:k?Fc.map((c,u)=>{let l=h.text.slice(c.start,c.end),g=u===Ys(Fc,h.pos),A=Math.min(h.pos,c.end)-c.start;return oe(_,{children:[L(_,{color:te,children:u===0?"> ":" "}),g?oe(Xn,{children:[l.slice(0,A),L(Kn,{ch:l[A]??" "}),l.slice(A+1)]}):l||" "]},`${u}-${c.start}`)}):oe(_,{children:[L(_,{color:te,children:"> "}),ro?L(Kn,{ch:" "}):ye&&!S&&ve?oe(Xn,{children:[L(Kn,{ch:ve[0],dim:!0}),L(_,{color:"gray",children:ve.slice(1)})]}):ye&&!S?oe(Xn,{children:[L(Kn,{ch:ye[0],dim:!0}),L(_,{color:"gray",children:ye.slice(1)}),L(_,{dimColor:!0,children:" (tab)"})]}):(pi.isSetup||!tr)&&!S?oe(Xn,{children:[L(Kn,{ch:pi.text[0],dim:!0}),L(_,{color:"gray",children:pi.text.slice(1)})]}):L(Kn,{ch:" "})]})}),wc.length>0&&L(ge,{flexDirection:"column",paddingX:1,children:wc.map((c,u)=>L(_,{color:"gray",children:`\u29D7 queued: ${c}`},`${u}-${c.slice(0,24)}`))}),oo?L(pf,{tab:oo.tab,scroll:oo.scroll,rows:gm,width:Ye,version:o,engineVersion:tm}):Gt?oe(ge,{flexDirection:"column",paddingX:1,children:[L(_,{color:te,bold:!0,children:"Select model"}),L(_,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),ut.map((c,u)=>oe(_,{color:u===Gt.cursor?te:void 0,children:[u===Gt.cursor?"\u276F ":" ",`${u+1}. ${c.label}${u===Gt.current?" \u2714":""}`.padEnd(16),L(_,{color:"gray",children:c.desc})]},c.label)),L(_,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):$t?oe(ge,{flexDirection:"column",paddingX:1,children:[L(_,{color:te,bold:!0,children:"Switch connection profile"}),L(zn,{rows:$t.rows,cursor:$t.cursor,cap:en,render:(c,u,l)=>oe(_,{color:l?te:void 0,children:[l?"\u276F ":" ",`${u+1}. ${c.name}${u===$t.current?" \u2714":""}`.padEnd(20),L(_,{color:"gray",children:`${c.env} \xB7 ${c.who??"not signed in"}`}),c.prod?L(_,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},c.name)}),L(_,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):vt?oe(ge,{flexDirection:"column",paddingX:1,children:[L(_,{color:te,bold:!0,children:"Pick your Document360 environment"}),L(zn,{rows:vt.rows,cursor:vt.cursor,cap:en,render:(c,u,l)=>oe(_,{color:l?te:void 0,children:[l?"\u276F ":" ",`${u+1}. ${c.name}`.padEnd(16),L(_,{color:"gray",children:c.apiUrl}),c.note?L(_,{color:"yellow",children:` \u26A0 ${c.note}`}):null]},c.name)}),L(_,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):Oe?oe(ge,{flexDirection:"column",paddingX:1,children:[L(_,{color:te,bold:!0,children:"Switch workspace"}),L(_,{dimColor:!0,children:`environment ${Oe.environment} \xB7 project ${Oe.projectName??`${Oe.projectId.slice(0,8)}\u2026`}`}),L(zn,{rows:Oe.rows,cursor:Oe.cursor,cap:en,render:(c,u,l)=>oe(_,{color:l?te:void 0,children:[l?"\u276F ":" ",`${u+1}. ${c.name}${u===Oe.current?" \u2714":""}`.padEnd(30),L(_,{color:"gray",children:c.type??""})]},c.id)}),L(_,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):Ze?oe(ge,{flexDirection:"column",paddingX:1,children:[L(_,{color:te,bold:!0,children:"Choose project"}),L(_,{dimColor:!0,children:`environment ${Ze.environment}`}),L(zn,{rows:Ze.rows,cursor:Ze.cursor,cap:en,render:(c,u,l)=>oe(_,{color:l?te:void 0,children:[l?"\u276F ":" ",`${u+1}. ${c.name}${u===Ze.current?" \u2714":""}`.padEnd(30),L(_,{color:"gray",children:c.sub??""})]},c.id)}),L(_,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):Le?(()=>{let u=Math.min(Math.max(0,Le.cursor-Math.floor(7)),Math.max(0,Le.rows.length-14)),l=Le.rows.slice(u,u+14),g=Le.rows.filter(A=>A.checked).length;return oe(ge,{flexDirection:"column",paddingX:1,children:[L(_,{color:te,bold:!0,children:`Which folders back the user docs? (${g} selected of ${Le.rows.length})`}),u>0?L(_,{dimColor:!0,children:` \u2191 ${u} more`}):null,l.map((A,G)=>{let f=u+G;return oe(_,{color:f===Le.cursor?te:void 0,children:[f===Le.cursor?"\u276F ":" ",A.checked?"\u25C9 ":"\u25CB ",A.path.padEnd(Math.min(48,Ye-34)),L(_,{color:"gray",children:ps(A)})]},A.path)}),u+14<Le.rows.length?L(_,{dimColor:!0,children:` \u2193 ${Le.rows.length-u-14} more`}):null,L(_,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():it?oe(ge,{flexDirection:"column",paddingX:1,children:[L(_,{color:te,bold:!0,children:it.title??"Which category? (pick one to scope to)"}),L(zn,{rows:it.rows,cursor:it.cursor,cap:en,render:(c,u,l)=>oe(_,{color:l?te:void 0,children:[l?"\u276F ":" ",`${`${u+1}.`.padEnd(3)} ${c.label} (${c.count})`.padEnd(Math.min(44,Math.max(20,Ye-24))),L(_,{color:"gray",children:` ${c.token}`})]},c.token)}),L(_,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):pt?oe(ge,{flexDirection:"column",paddingX:1,children:[L(_,{color:te,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),L(zn,{rows:pt.rows,cursor:pt.cursor,cap:en,render:(c,u,l)=>oe(_,{color:l?te:void 0,bold:c.kind==="category"&&!l,children:[l?"\u276F ":" ",`${c.indent?" ":" "}${`${u+1}.`.padEnd(3)} ${c.label}`.padEnd(Math.min(56,Ye-24)),c.note?L(_,{color:"gray",children:c.note}):null]},`${c.kind}:${c.paths.join(",")}`)}),L(_,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):xt?oe(ge,{flexDirection:"column",paddingX:1,children:[L(_,{color:te,bold:!0,children:xt.title}),(()=>{let{rows:c,cursor:u}=xt,l=Fs(c.length,u,en),g=l.start,A=c.slice(l.start,l.end),G=`${c.length}.`.length+1,f=Ed(c,Math.max(20,Ye-4-G));return oe(Xn,{children:[g>0?L(_,{color:"gray",children:` \u2026 ${g} more above`}):null,A.map((y,P)=>{let b=g+P,x=b===u,T=f[b];return oe(_,{color:x?te:void 0,bold:(y.kind==="all"||y.kind==="category")&&!x,children:[x?"\u276F ":" ",`${b+1}.`.padEnd(G),T.head,T.note?L(_,{color:"gray",children:T.note}):null]},`${y.action}:${y.kind}:${y.ids.join(",")}`)}),l.below>0?L(_,{color:"gray",children:` \u2026 ${l.below} more below`}):null]})})(),L(_,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter run \xB7 esc cancel"})]}):qe?oe(ge,{flexDirection:"column",paddingX:1,children:[L(_,{color:te,bold:!0,children:`Preview article${qe.query?` \u2014 filter: ${qe.query}`:" (type to filter)"}`}),gr.length===0?L(_,{color:"gray",children:"no articles match"}):gr.map((c,u)=>oe(_,{color:u===qe.cursor?te:void 0,children:[u===qe.cursor?"\u276F ":" ",c]},c)),L(_,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):Ge?oe(ge,{flexDirection:"column",paddingX:1,children:[L(_,{color:te,bold:!0,children:`Resume session${Ge.query?` \u2014 filter: ${Ge.query}`:" (type to filter)"}`}),yr.length===0?L(_,{color:"gray",children:"no sessions match"}):yr.map((c,u)=>oe(_,{color:u===Ge.cursor?te:void 0,children:[u===Ge.cursor?"\u276F ":" ",c.name.slice(0,28).padEnd(30),L(_,{color:u===Ge.cursor?te:"gray",children:c.firstPrompt.slice(0,Math.max(10,Ye-40))})]},c.uuid)),L(_,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Dc?oe(ge,{flexDirection:"column",children:[tn>0?L(_,{dimColor:!0,children:` \u22EF ${tn} more above`}):null,hi.map((c,u)=>{let l=tn+u,g=c.name==="model"&&oi?`${c.desc} (currently ${oi})`:c.desc,A=Math.max(20,Ye-4),G=c.usage.length>A?`${c.usage.slice(0,A-1)}\u2026`:c.usage,f=A-Math.max(G.length,22)-1,y=f<=1?"":g.length>f?`${g.slice(0,f-1)}\u2026`:g;return oe(_,{color:l===mr?te:void 0,children:[l===mr?"\u276F ":" ",G.padEnd(22)," ",L(_,{color:l===mr?te:"gray",children:y})]},c.name)}),tn+hi.length<mt.length?L(_,{dimColor:!0,children:` \u22EF ${mt.length-tn-hi.length} more below`}):null,L(_,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!S&&!k&&pe.length>0?oe(ge,{flexDirection:"column",paddingX:1,children:[yc?L(_,{color:te,children:yc}):null,pe.map((c,u)=>{let l=un(c),g=l.slice(0,Math.max(20,Ye-5)),A=Ye-g.length-7,G=A>=12?(yf(c)??Lu(l)).slice(0,A):"";return oe(_,{children:[L(_,{color:te,children:u+1})," ",g,G?L(_,{dimColor:!0,children:` \u2014 ${G}`}):null]},l)}),L(_,{dimColor:!0,children:`press 1-${pe.length} to fill \xB7 esc cancel`})]}):L(ge,{paddingX:1,children:oe(_,{color:"gray",children:[Ac.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${oi??"model n/a"}${t.kind==="api"?$c>0?` \xB7 ${Fe($c)}`:"":bc>0?` \xB7 ${It(bc)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}X();import{jsx as l0}from"react/jsx-runtime";async function om(e=process.cwd(),t="auto",n,o="0.0.0"){let r=a0(t);r.kind==="none"&&(console.error(""),console.error(j("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${H("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${H("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=i0(l0(nm,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
|
|
490
|
-
`),process.exit(0)}
|
|
491
|
-
`+j(`\u2717 d360-writer crashed: ${
|
|
492
|
-
`),r&&process.stderr.write(
|
|
493
|
-
`+
|
|
494
|
-
`),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var
|
|
471
|
+
Model: ${_.model}${_.forced?" (forced)":" \u2014 authoring; /model to override"}`;p({kind:"note",tone:"info",text:ce+Fa(O,V,N).join(`
|
|
472
|
+
`)+De}),J(`/write${y?` --scope ${y}`:""}`);return}Gt.current=Date.now(),gn(0),R(!0);let Re=new AbortController;Ae.current=Re,me({verb:"Writing",total:O.length,done:0,active:[],rows:or(O),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),p({kind:"note",tone:"info",text:`Writing ${H.length} article${H.length===1?"":"s"} across ${O.length} partition${O.length===1?"":"s"} (\u2264${N} agents at once) on ${_.model}${_.forced?" (forced)":""}\u2026 (esc to stop)`});let nt=new Set;try{for await(let V of ei({cwd:e,partitions:O,promptFor:ce=>Wa(ce,B,{rewrite:D||se}),concurrency:N,profileName:s,allowProdWrites:bn.current,model:_.model,signal:Re.signal}))if(V.type==="partition_status")V.status==="running"?me(ce=>ce&&{...ce,active:[...ce.active,V.label],rows:rt(ce.rows,V.label,"active"),lastAt:Date.now()}):me(ce=>ce&&{...ce,active:ce.active.filter(De=>De!==V.label),done:ce.done+1,rows:rt(ce.rows,V.label,V.status==="done"?"done":"failed"),lastAt:Date.now()});else if(V.type==="partition_event"){let ce=null;if(V.event.type==="tool"){let De=vf(V.event.name,V.event.input,O[V.index]?.paths??[]);De&&!nt.has(De)&&(nt.add(De),ce=V.label)}me(De=>{if(!De)return De;let ct={...De,lastAt:Date.now()};return V.event.type==="tool"?ct.tools=De.tools+1:V.event.type==="text"&&(ct.chars=De.chars+V.event.delta.length),ce&&(ct.rows=$f(ct.rows,ce)),ct})}else if(V.type==="run_done"){Tn(Et=>Et+V.totalCostUsd),Pn(Et=>Et+V.results.reduce((kt,Cm)=>kt+Cm.outputTokens,0));let ce=V.aborted?"Stopped. ":"",De=t.kind==="api"?"api":"subscription",ct=ut(V,"The write");if(p({kind:"note",tone:ct||V.aborted?"warn":V.ok?"ok":"warn",text:ct?ct.join(`
|
|
473
|
+
`):ce+Ba(V.results,O,De).join(`
|
|
474
|
+
`)}),ct){J("/doctor");continue}let Yc=Kr(V);if(Yc&&p({kind:"note",tone:"warn",text:Yc}),!V.aborted&&V.ok)try{let Et=(nt.size>0?[...nt]:H).map(kt=>`${B}/${kt}`);ac(e,Et,{writtenCap:lc,reviewedCap:0,checkedCap:0})}catch{}let Tr=V.aborted?null:Ha(e,B,H);if(Tr&&p({kind:"note",tone:"warn",text:Tr}),!V.aborted&&V.ok){let Et=y??C??"",kt=Et?` ${Et}`:"";Ie(Tr?`Written \u2014 but the checker flagged issues. I\u2019d fix those first with /check${kt} --fix, then /review${kt} --fix for editorial quality, then /publish --all (add /screenshot author --all first if you want images).`:`Written. I\u2019d run /review${kt} --fix next \u2014 editorial review that applies its fixes \u2014 then /publish --all pushes the drafts up (add /screenshot author --all first if you want images).`,{kind:"cmd",cmd:Tr?`/check${kt} --fix`:`/review${kt} --fix`,reason:""})}}}catch(V){p({kind:"note",tone:"error",text:`Write run failed: ${V.message}`})}finally{Ae.current=null,me(null),R(!1),z(V=>V+1)}return}case"draft":{if(!ue(e)){p({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:f,looseDocs:y}=Ga(e);if(f.length===0&&y===0){p({kind:"note",tone:"info",text:Ya});return}let C=g.join(" ").trim();if(!C&&f.length>1){p({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
|
|
475
|
+
${f.map(P=>` \u2022 ${P.name} (${P.docCount} doc${P.docCount===1?"":"s"})`).join(`
|
|
476
|
+
`)}`}),le(f.map(P=>`/draft ${P.name}`));return}let b="",v;if(C){let P=Va(f,C);P?b=P:v=C}else b=f[0]?.name??"";await de(ks(b,v),{display:C?`/draft ${C}`:"/draft",quietUser:!0});return}case"pull":{if(!uo(c.trim()))return;let f=g.find(y=>y.startsWith("--"));try{if(f==="--status"){p({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let b=Date.now(),v=await Zs({cwd:e,profileName:s});p({kind:"note",tone:"info",text:ms(v,Date.now()-b).join(`
|
|
477
|
+
`)});return}if(f==="--baseline"){let b=g.find(H=>!H.startsWith("--")),v=b?b.replace(/\\/g,"/"):void 0;p({kind:"note",tone:"info",text:v?`Setting the sync baseline for ${v}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let P=await Mx({cwd:e,profileName:s,relPaths:v?[v]:void 0}),B=v?{rebaselined:[],skipped:[]}:await Ux({cwd:e,profileName:s});if(P.baselined.length===0&&P.skipped.length===0&&B.rebaselined.length===0){p({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}P.baselined.length>0&&p({kind:"note",tone:"ok",text:`\u2713 Baselined ${P.baselined.length} article${P.baselined.length===1?"":"s"} \u2014 they now read in-sync until either side changes.`}),B.rebaselined.length>0&&p({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${B.rebaselined.length} article${B.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),P.skipped.length>0&&p({kind:"note",tone:"warn",text:`${P.skipped.length} skipped:
|
|
478
|
+
${P.skipped.map(H=>` - ${H.path} (${H.reason})`).join(`
|
|
479
|
+
`)}`}),z(H=>H+1);return}if(f==="--compare"){p({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let b=await _x({cwd:e,profileName:s}),v=b.onlyInLegacy.length===0&&b.onlyInManifest.length===0&&b.mappedMissingFromManifest.length===0,P=[`Legacy listing: ${b.legacyCount} \xB7 Manifest: ${b.manifestCount} \xB7 in both: ${b.inBoth}`];v?P.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(b.mappedMissingFromManifest.length&&P.push(`\u2717 ${b.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${b.mappedMissingFromManifest.slice(0,5).join(", ")}`),b.onlyInLegacy.length&&P.push(`\u26A0 ${b.onlyInLegacy.length} only in the legacy listing: ${b.onlyInLegacy.slice(0,5).join(", ")}`),b.onlyInManifest.length&&P.push(`\u26A0 ${b.onlyInManifest.length} only in the manifest: ${b.onlyInManifest.slice(0,5).join(", ")}`),P.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),p({kind:"note",tone:v?"ok":"warn",text:P.join(`
|
|
480
|
+
`)});return}if(f){p({kind:"note",tone:"error",text:`Unknown option: ${f} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let y=g[0];if(y){let b=await Yf({cwd:e,profileName:s,relPath:y.replace(/\\/g,"/")});fe.current=[{plan:b,mode:b.overwritesLocalChanges?"conflict":"pull"}],Vt.current=[],An();return}p({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let C=await Sa({cwd:e,profileName:s});for(let b of Pa(C))p({kind:"note",tone:b.tone,text:b.text});z(b=>b+1)}catch(y){p({kind:"note",tone:"error",text:`Pull failed: ${y.message}`})}return}case"scope":{if(!ue(e)){p({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let f=Wx(e);if(f.length===0){p({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer/config.json manually.'});return}Sn({cursor:0,rows:f.map(y=>({...y,checked:y.recommended}))});return}case"audit":{if(g[0]==="--auto"){let y=ue(e);if(!y){p({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let C=g[1]!=="off";Bf({...y,autoAudit:C},e),p({kind:"note",tone:"ok",text:C?"\u2713 Auto-audit ON \u2014 when you launch with code changes since the last audit, I\u2019ll run /audit automatically. (/audit --auto off to disable.)":"\u2713 Auto-audit OFF \u2014 I\u2019ll just nudge you to run /audit when code changed."});return}let f=await Lo();f.kind==="forward-to-agent"&&f.prompt&&await de(f.prompt,{display:f.display,quietUser:!0});return}case"check":{let f=g.find(b=>!b.startsWith("--")),y=f?` ${f}`:"",C=Vf({cwd:e,scope:f});if(g.includes("--fix")){if(C.length===0){p({kind:"note",tone:"ok",text:"\u2713 Nothing to fix \u2014 the docs are already clean."});return}p({kind:"note",tone:"info",text:`Fixing ${C.length} doc issue${C.length===1?"":"s"}\u2026`});let b=em(e,f);await de(Nl(C),{display:`/check${y} --fix`,quietUser:!0});try{ac(e,b,{checkedCap:lc})}catch{}let v=Vf({cwd:e,scope:f});p({kind:"note",tone:v.length===0?"ok":"warn",text:v.length===0?"\u2713 Doc-checker: all issues resolved.":Es(v).join(`
|
|
481
|
+
`)}),Ie(v.length===0?`Deterministic issues fixed. Next: /review${y} --fix for editorial quality (style, grammar, structure), then /publish --all.`:`Some issues remain \u2014 /review${y} --fix runs the editorial review + fixes, then /publish --all.`,{kind:"cmd",cmd:`/review${y} --fix`,reason:""});return}if(p({kind:"note",tone:C.length===0?"ok":"warn",text:Es(C).join(`
|
|
482
|
+
`)}),C.length>0){let b=ya(e,f)===0?"; /publish --all publishes as-is":"";Ie(`Found ${C.length} doc issue${C.length===1?"":"s"} above. /check${y} --fix has the agent fix them in place (or /review${y} --fix for the full editorial pass${b}).`,{kind:"cmd",cmd:`/check${y} --fix`,reason:""})}return}case"structure":{let f=zo(e,s);if(f.length===0){p({kind:"note",tone:"info",text:"No documentation structure yet \u2014 run /init and author some articles first."});return}p({kind:"note",tone:"info",text:["Documentation order (categories \u2192 articles):","",...f].join(`
|
|
483
|
+
`)});return}case"reorder":{let f=Ol(e,g);if(!f){p({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let y=await de(f.prompt,{display:f.display,quietUser:!0}),C=Oo(e,{text:"Reordered locally \u2014 /publish --all syncs the new order to Document360.",cmd:"/publish --all"},"Reordered locally. ");gr(y,C.text,{kind:"cmd",cmd:C.cmd,reason:""});return}case"review":{let f=Il(e,g);if(!f){p({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let y=g.includes("--fix"),C=g.find(P=>!P.startsWith("--")),b=y?em(e,C):[],v=await de(f.prompt,{display:f.display,quietUser:!0});if(y&&!v.producedNothing)try{ac(e,b,{reviewedCap:lc})}catch{}if(y){let P=Oo(e,{text:"\u2713 Editor applied its fixes \u2014 your docs are corrected. /publish --all pushes them up (or /check for an instant no-token re-scan first).",cmd:"/publish --all"},"\u2713 Editor applied its fixes to this scope. ");gr(v,P.text,{kind:"cmd",cmd:P.cmd,reason:""})}else{let P=g.filter(B=>B!=="--fix").join(" ");gr(v,`The review listed issues above. /review${P?` ${P}`:""} --fix lets the editor apply them all (or /check --fix for just the deterministic ones; /publish --all publishes as-is).`,{kind:"cmd",cmd:`/review${P?` ${P}`:""} --fix`,reason:""})}return}case"capture-setup":{await F();return}case"devhints":{if(!ue(e)){p({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}p({kind:"note",tone:"info",text:Ln(On(e)).join(`
|
|
484
|
+
`)}),Tt(sn()),ho.current=ot(e).status==="current",En.current=bt(e);return}case"discover":{if(!ue(e)){p({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}await de($a(),{display:"/discover",quietUser:!0});return}case"inbox":{if(!ue(e)){p({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(hl(e)===0){p({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 de(fl(),{display:"/inbox",quietUser:!0});return}case"share":{let f=ue(e);if(!f){p({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let y=g[0]?.trim().toLowerCase();if(y==="status"){for(let b of Rs(e,f))p({kind:"note",tone:b.tone,text:b.text});return}if(y==="on"||y==="off"){for(let b of ml(e,f,y==="on"))p({kind:"note",tone:b.tone,text:b.text});z(b=>b+1);return}if(y){p({kind:"note",tone:"error",text:`Unknown option: ${y} \u2014 use /share, /share status, /share on, or /share off.`});return}p({kind:"note",tone:"info",text:"Exchanging work with your team\u2026"});let C=await Cs(e,f);for(let b of C.lines)p({kind:"note",tone:b.tone,text:b.text});C.changed&&z(b=>b+1);return}case"feedback":{let f=Zf(e),y="";try{y=zn(f)?Qs(f,"utf8"):""}catch{y=""}if(!/^## /m.test(y)){p({kind:"note",tone:"info",text:"No open d360-writer feedback to copy \u2014 nothing logged in .d360-writer/tool-feedback.md yet."});return}let C=await Kl(y.trim());p({kind:"note",tone:C?"ok":"warn",text:C?"\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 ${f} and copy it manually.`}),C&&mi(null);return}case"document":{if(!ue(e)){p({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:f,skipReview:y,what:C}=za(g);if(!C&&Ka(e)===0){p({kind:"note",tone:"info",text:Qa});return}let b=`/document${C?` ${C}`:""}${f?" --publish":""}`,v=await de(Xa(C),{display:b,quietUser:!0});f&&!v.producedNothing&&await Mc({skipReview:y});return}case"catch-up":{if(!ue(e)){p({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!uo(c.trim()))return;let{publish:f,skipReview:y}=kl(g);for(let P of await wl(e))p({kind:"note",tone:P.tone,text:P.text});p({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let C=await $l({cwd:e,profileName:s});for(let P of vl(C))p({kind:"note",tone:P.startsWith("\u2713")?"ok":P.startsWith("\u2139")?"info":"warn",text:P});let b=Ko(hn(e));p({kind:"note",tone:"info",text:b?`Catching up on ${b}\u2026`:"Checking for code changes the builder didn\u2019t hint\u2026"});let v=await de(bl(),{display:`/catch-up${f?" --publish":""}`,quietUser:!0});f&&!v.producedNothing&&await Mc({skipReview:y});return}case"comments":{if(!ue(e)){p({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!uo(c.trim()))return;if(Pl(g).answer){let f=await de(Sl(),{display:"/comments --answer",quietUser:!0}),y=Oo(e,{text:"",cmd:"/publish --all"});gr(f,y.cmd==="/publish --all"?null:y.text,{kind:"cmd",cmd:y.cmd,reason:y.cmd==="/publish --all"?"it pushes the articles you just fixed up to Document360":""});return}gt("Checking Document360 for reviewer comments\u2026"),R(!0);try{let f=await Rl(e,s);p({kind:"note",tone:f.threads.length>0?"info":"ok",text:Cl(f).join(`
|
|
485
|
+
`)}),f.threads.length>0&&J("/comments --answer"),z(y=>y+1)}catch(f){p({kind:"note",tone:"error",text:`Couldn\u2019t read comments from Document360: ${f.message}`})}finally{R(!1),gt(null)}return}case"update":{pi.current=!0,p({kind:"note",tone:"info",text:"Updating the d360-writer toolchain\u2026 (don\u2019t close this window)"}),lr(!0);let f=await Ps().finally(()=>lr(!1));f.ok?(p({kind:"note",tone:"ok",text:`\u2713 Updated ${f.packages.join(" + ")} \u2014 run /exit, then relaunch to apply.`}),J("/exit"),yc("")):p({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${Ss}`});return}case"screenshot":{let f=Eo(g),y=Ao(e);if(y&&f.mode!=="list"&&p({kind:"note",tone:"info",text:y}),f.mode==="capture"){await E(f.rest);return}if(f.mode==="checklist"){await F();return}if(f.mode==="verify"){let v=Pe(e),P=f.rest.find(ee=>!ee.startsWith("-")),B=P?[P]:Bo(v);if(P&&!v.some(ee=>ee.id===P)){p({kind:"note",tone:"error",text:`No screenshot placeholder called "${P}". /screenshot list shows them all.`});return}if(B.length===0){let ee=v.filter(O=>O.state==="rejected").length,D=v.filter(O=>O.state==="verified").length;p({kind:"note",tone:"info",text:ee>0?`Nothing left to verify. ${ee} shot${ee===1?"":"s"} failed verification \u2014 re-capture with /screenshot capture --failed.`:D>0?`All ${D} captured shot${D===1?" is":"s are"} already verified.`:"No captured screenshots to verify yet \u2014 /screenshot capture takes the shots first."});return}p({kind:"note",tone:"info",text:Ho(B.length)}),await de(pn(e,B),{display:P?`/screenshot verify ${P}`:"/screenshot verify",quietUser:!0});let H=qo(e,B);H.length>0&&p({kind:"note",tone:"info",text:H.join(`
|
|
486
|
+
`)});return}if(f.mode==="list"){if(!ue(e)){p({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let v=ue(e)?.docsDir??hc,P=da(e,f.scope),B=Pe(e,P);if(f.picker){if(B.length===0){p({kind:"note",tone:"info",text:"No screenshot placeholders found in the docs."});return}let _=Od(B);if(_.length===0){p({kind:"note",tone:"info",text:ls(B,{docsDir:v}).join(`
|
|
487
|
+
`)});let se=Oo(e,{text:`\u2713 All ${B.length} screenshots are captured. /publish puts them in the articles; /screenshot capture re-captures.`,cmd:"/publish"},`\u2713 All ${B.length} screenshots are captured. `);Ie(se.text,{kind:"cmd",cmd:se.cmd,reason:""});return}Qt({cursor:0,rows:_,title:"Screenshots \u2014 pick what to author or capture:"});return}p({kind:"note",tone:"info",text:ls(B,{scope:P,detail:f.detail,docsDir:v}).join(`
|
|
488
|
+
`)}),y&&p({kind:"note",tone:"info",text:y});let H=B.filter(_=>_.state==="placeholder").length,ee=B.filter(_=>_.state==="spec").length,D=B.filter(_=>_.state==="captured").length,O=B.filter(_=>_.state==="rejected").length,N=B.filter(_=>_.state==="spec"&&!_.mutates).length;H>0?J(P?`/screenshot author ${P}`:"/screenshot author --all"):ee>0&&(N>0||D===0)?J(P?`/screenshot capture ${P}`:"/screenshot capture"):D>0?J("/screenshot verify"):O>0&&J("/screenshot capture --failed");return}if(f.mode==="single"){await Wc(f.id);return}if(!ue(e)){p({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let C=f.mode==="scope"?f.scope:void 0,b=qx(e,{scope:C}).map(v=>v.id);if(b.length===0){p({kind:"note",tone:"info",text:C?`No screenshot placeholders under ${C}.`:"No screenshot placeholders found in the docs."});return}await Uc(b,{setup:f.setup,runLine:f.mode==="scope"?[`/screenshot author ${f.scope}`,`/screenshot ${f.scope}`]:["/screenshot author --all","/screenshot --all"]});return}case"capture":{await E(g);return}case"reset":{let f=Al(e);if(f.length===0){p({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}no.current={repoName:rr(e),targets:f,hadDevhints:zn(Jf(e))},p({kind:"note",tone:"warn",text:jl(e,f).join(`
|
|
489
|
+
`)}),Ne(rr(e));return}default:p({kind:"note",tone:"error",text:`Unknown command: /${a} \u2014 type /help.`})}},[e,r,s,An,xi,p,Me,de,tt,bi,Fc]),Sr=X(c=>{let u=(c??w).trim();if(x(""),cr(null),yn(0),u.startsWith("/")&&(Ce.current=!1,Se.current=!1,Qe.current=null,lt(),Cn(null),le(g=>Cf(g,u))),!u||(sr(!1),(no.current||fe.current.length>0)&&p({kind:"user",text:u}),Hc(u))||Bc(u))return;si.current.push(u);let a=Ef(u,wc.current);if(u.startsWith("/"))p({kind:"user",text:u}),xe(!0),yo(a).finally(()=>xe(!1));else if(n0(a)){p({kind:"user",text:u});let g=o0(a);if(!g)de(a,{display:u,quietUser:!0});else{try{r0(e,{title:g,by:"owner (d360-writer terminal)",at:new Date().toISOString()})}catch{}de(`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:u,quietUser:!0})}}else{let g=Th(e,a);de(g??a,{display:u})}},[w,Hc,Bc,yo,de]),qc=X(c=>{if(c.length>1){if(c.includes("\x1B"))return;let u=Sf(c);if(Pf(u)){let a=Tf(++ym.current,u);wc.current.set(a,u),S(a)}else S(u);return}S(c)},[S]),Dn=Math.max(10,Ye-6),Gc=oc(()=>zs(h.text,Dn),[h.text,Dn]),Ri=X(c=>m(u=>({...u,pos:Math.max(0,Math.min(u.text.length,u.pos+c))})),[]),Pr=X(c=>m(u=>({...u,pos:Df(zs(u.text,Dn),u.pos,c)})),[Dn]),wo=X(c=>m(u=>({...u,pos:jf(zs(u.text,Dn),u.pos,c)})),[Dn]),xm=["\x1B[H","\x1B[1~","\x1BOH"],Rm=["\x1B[F","\x1B[4~","\x1BOF"],Vc=X((c,u)=>u.leftArrow?(Ri(-1),!0):u.rightArrow?(Ri(1),!0):c&&xm.includes(c)?(wo("start"),!0):c&&Rm.includes(c)?(wo("end"),!0):u.ctrl&&c==="a"?(wo("start"),!0):u.ctrl&&c==="e"?(wo("end"),!0):!1,[Ri,wo]);return hx((c,u)=>{if(u.ctrl&&c==="c"){Je.current?.close(),r();return}if(po.current.awaySince!==null)try{let a=mf(po.current,Date.now(),hn(e));if(po.current=a.memory,Nc(null),a.kind==="delta"){p({kind:"note",tone:"info",text:yf(a.delta,a.awayMs)});let g=et(!1);g.kind==="recommend"&&yt(g.rec,{silent:!0})}else if(a.kind==="briefing"){p({kind:"note",tone:"info",text:`\u{1F4E5} ${tr(a.delta)} arrived while you were away (${ec(a.awayMs)}).`});let g=et(!1);g.kind==="recommend"&&yt(g.rec)}}catch{}if(gi.current=Date.now(),!I){if(T){if(u.escape){if(Ae.current){if(!Ae.current.signal.aborted){let a=(dr?.verb??"work").toLowerCase(),g=dr?.unit??"article";p({kind:"note",tone:"warn",text:`\u238B Stopping the ${a} run (finishing in-flight ${g}s)\u2026`}),Ae.current.abort()}return}oo.current||(oo.current=!0,p({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),Je.current?.interrupt());return}if(u.return){let a=w.trim();if(!a)return;en.current.push(a),ai([...en.current]),x("");return}if(Vc(c,u))return;if(u.upArrow){Pr(-1);return}if(u.downArrow){Pr(1);return}if(u.backspace||u.delete){$();return}c&&!u.ctrl&&!u.meta&&qc(c);return}if(Kt){if(u.upArrow){zt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(u.downArrow){zt(a=>a&&{...a,cursor:Math.min(ht.length-1,a.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=ht.length){zt(a=>a&&{...a,cursor:Number(c)-1});return}if(u.return){let a=ht[Kt.cursor];zt(null);let{lines:g,changed:E,effective:F}=Wo(e,a.value??"default");for(let f of g)p({kind:"note",tone:f.startsWith("\u26A0")?"warn":f.startsWith("\u2713")?"ok":"info",text:f});E&&(Sc(f=>f+1),Je.current?.setModel(F));return}if(c==="s"){let a=ht[Kt.cursor];zt(null),Je.current?.setModel(a.value??void 0),p({kind:"note",tone:"ok",text:`\u2713 Using ${a.label} for this session only (your saved default is unchanged).`});return}if(u.escape){zt(null);return}return}if(Rt){if(u.upArrow){$n(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(u.downArrow){$n(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Rt.rows.length){$n(a=>a&&{...a,cursor:Number(c)-1});return}if(u.return||c==="s"){let a=Rt.rows[Rt.cursor];$n(null),vi(a.name,u.return===!0);return}if(u.escape){$n(null);return}return}if(io){if(u.escape){nn(null);return}if(u.leftArrow||u.tab&&u.shift){nn(a=>a&&{tab:(a.tab-1+Ue.length)%Ue.length,scroll:0});return}if(u.rightArrow||u.tab){nn(a=>a&&{tab:(a.tab+1)%Ue.length,scroll:0});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ue.length){nn({tab:Number(c)-1,scroll:0});return}if(u.upArrow){nn(a=>a&&{...a,scroll:Math.max(0,a.scroll-1)});return}if(u.downArrow){nn(a=>{if(!a)return a;let g=(Ue[a.tab]??Ue[0]).rows.length;return{...a,scroll:Math.min(Math.max(0,g-1),a.scroll+1)}});return}return}if(Ct){if(u.upArrow){vn(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(u.downArrow){vn(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ct.rows.length){vn(a=>a&&{...a,cursor:Number(c)-1});return}if(u.return){let a=Ct.rows[Ct.cursor].name;if(vn(null),!Oi(e,a).created){p({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}p({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${a}").`});let E=!1;try{let F=mn(a);E=!!F&&!(Ht(F)&&!F.refreshToken)}catch{E=!1}p({kind:"note",tone:"info",text:E?`Next: sign in to ${a} and pick your project \u2014 you're already signed in here, so it'll be quick.`:`Next: sign in to Document360 (${a}) and pick your project.`}),J("/login"),z(F=>F+1);return}if(u.escape){vn(null);return}return}if(Oe){if(u.upArrow){xn(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(u.downArrow){xn(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Oe.rows.length){xn(a=>a&&{...a,cursor:Number(c)-1});return}if(u.return){let a=Oe.rows[Oe.cursor],{profile:g,projectId:E}=Oe;xn(null),xr(g,E,a);return}if(u.escape){xn(null);return}return}if(Ze){if(u.upArrow){Xt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(u.downArrow){Xt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=Ze.rows.length){Xt(a=>a&&{...a,cursor:Number(c)-1});return}if(u.return){let a=Ze.rows[Ze.cursor],{profile:g}=Ze;Xt(null),Cr(g,a);return}if(u.escape){Xt(null);return}return}if(Le){if(u.upArrow){Sn(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(u.downArrow){Sn(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(c===" "){Sn(a=>a&&{...a,rows:a.rows.map((g,E)=>E===a.cursor?{...g,checked:!g.checked}:g)});return}if(u.return){let a=Le.rows.filter(g=>g.checked).map(g=>g.path);if(Sn(null),a.length===0){p({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}va(e,a),p({kind:"note",tone:"ok",text:`\u2713 Scoped to ${a.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let g of a)p({kind:"note",tone:"info",text:` ${g}`});p({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(u.escape){Sn(null);return}return}if(at){if(u.upArrow){Jt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(u.downArrow){Jt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=at.rows.length){Jt(a=>a&&{...a,cursor:Number(c)-1});return}if(u.return){let a=at.rows[at.cursor],g=at.run;Jt(null),g(a.token);return}if(u.escape){Jt(null);return}return}if(mt){if(u.upArrow){Rn(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(u.downArrow){Rn(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=mt.rows.length){Rn(a=>a&&{...a,cursor:Number(c)-1});return}if(u.return){let a=mt.rows[mt.cursor],g=mt.conflicts;Rn(null),a.conflict?xi(a.paths[0]):a.kind==="article"?bi(a.paths[0]):tt(a.paths,a.kind==="all"?g:0);return}if(u.escape){Rn(null);return}return}if(St){if(u.upArrow){Qt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(u.downArrow){Qt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(c&&/^[1-9]$/.test(c)&&Number(c)<=St.rows.length){Qt(a=>a&&{...a,cursor:Number(c)-1});return}if(u.return){let a=St.rows[St.cursor];Qt(null),a.action==="capture"?mo(a.ids,{runLine:a.kind==="all"?["/screenshot capture --all","/capture --all"]:void 0}):a.kind==="shot"?Wc(a.ids[0]):Uc(a.ids,{setup:!0,runLine:a.kind==="all"?["/screenshot author --all","/screenshot --all"]:void 0});return}if(u.escape){Qt(null);return}return}if(qe){if(u.escape){Zt(null);return}if(u.upArrow){Zt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(u.downArrow){Zt(a=>a&&{...a,cursor:Math.min(Math.max(0,br.length-1),a.cursor+1)});return}if(u.return){let a=br[qe.cursor];if(a){Zt(null);try{p({kind:"preview",name:rr(a),text:im(Qs(rc(e,a),"utf8"))})}catch(g){p({kind:"note",tone:"error",text:`Could not read ${a}: ${g.message}`})}}return}if(u.backspace||u.delete){Zt(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(c&&!u.ctrl&&!u.meta&&c.length===1){Zt(a=>a&&{...a,query:a.query+c,cursor:0});return}return}if(Ge){if(u.escape){tn(null);return}if(u.upArrow){tn(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(u.downArrow){tn(a=>a&&{...a,cursor:Math.min(Math.max(0,$r.length-1),a.cursor+1)});return}if(u.return){let a=$r[Ge.cursor];if(a){tn(null),Me(a.uuid),ft.current={uuid:a.uuid,firstPrompt:a.firstPrompt,titleFired:!0},Yt(a.name),sc(a.uuid),kn.current=[],Ve.current={printed:[],armed:[]};let g=Ql(e,a.uuid);for(let E of g)p(E);p({kind:"note",tone:"ok",text:g.length?`Resumed "${a.name}" \u2014 restored ${g.length} message(s); continue where you left off.`:`Resumed "${a.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(u.backspace||u.delete){tn(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(c&&!u.ctrl&&!u.meta&&c.length===1){tn(a=>a&&{...a,query:a.query+c,cursor:0});return}return}if(u.tab&&!w&&ke){x(ke),lt();return}if(!w&&pe.length>0&&!qt&&c&&/^[1-9]$/.test(c)){let a=pe[Number(c)-1];if(a){x(fn(a));return}}if(!w&&pe.length===0&&!qt&&Ve.current.armed.length>0&&c&&/^[1-9]$/.test(c)){let a=Ve.current.armed[Number(c)-1];if(a){x(a);return}}if(!w&&(yr||lo)&&c==="c"&&!u.ctrl&&!u.meta&&!u.return&&!u.tab){let a=yr!=null;Kl(yr??lo).then(E=>{p({kind:"note",tone:E?"ok":"warn",text:E?a?"\u2713 Copied the feedback to your clipboard \u2014 send it to the d360-writer team (Teams / Slack / email).":"\u2713 Copied the prompt to your clipboard \u2014 paste it into your repo's coding agent.":a?"Couldn't reach your clipboard \u2014 select the feedback above and copy it manually.":"Couldn't reach your clipboard \u2014 select the prompt above and copy it manually."}),E&&a&&mi(null),E&&!a&&Tc(!0)});return}if(!Vc(c,u)){if(Oc){if(u.upArrow){yn(a=>Math.max(0,a-1));return}if(u.downArrow){yn(a=>Math.min(wt.length-1,a+1));return}if(u.tab){x("/"+(wt[ri]?.name??"")+" "),yn(0);return}if(u.return){let a=wt[ri];if(a){let g=w.trim().slice(1).split(/\s+/).slice(1).join(" ");if(Hu(a.usage)&&!g){x("/"+a.name+" "),yn(0);return}Sr("/"+a.name+(g?" "+g:""));return}}}else{if(u.upArrow){if(w!==""&&wn===null){Pr(-1);return}let a=si.current;if(!a.length)return;let g=wn===null?a.length-1:Math.max(0,wn-1);cr(g),x(a[g]??"");return}if(u.downArrow){if(w!==""&&wn===null){Pr(1);return}let a=si.current;if(wn===null)return;let g=wn+1;g>=a.length?(cr(null),x("")):(cr(g),x(a[g]??""));return}}if(u.return){Sr();return}if(u.backspace||u.delete){$();return}if(u.escape){x(""),yn(0),lt(),le([]),Cn(null),Ce.current=!0;return}c&&!u.ctrl&&!u.meta&&qc(c)}}}),He(()=>{if(T||I)return;let c=en.current.shift();c!==void 0&&(ai([...en.current]),Sr(c))},[T,I,Sr]),oe(we,{flexDirection:"column",width:Ye,children:[ki!==null&&oe(we,{marginTop:1,flexDirection:"column",children:[ki.truncated&&L(M,{dimColor:!0,children:"\u2026"}),L(M,{children:ki.text})]}),T&&(dr?L(g0,{p:dr}):L(h0,{startTime:Gt.current,chars:gm})),!T&&xc?L(f0,{text:xc}):null,L(we,{borderStyle:"round",borderColor:Ic.prod?"yellow":te,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:w?Gc.map((c,u)=>{let a=h.text.slice(c.start,c.end),g=u===Xs(Gc,h.pos),E=Math.min(h.pos,c.end)-c.start;return oe(M,{children:[L(M,{color:te,children:u===0?"> ":" "}),g?oe(Jn,{children:[a.slice(0,E),L(Xn,{ch:a[E]??" "}),a.slice(E+1)]}):a||" "]},`${u}-${c.start}`)}):oe(M,{children:[L(M,{color:te,children:"> "}),ao?L(Xn,{ch:" "}):ke&&!T&&ge?oe(Jn,{children:[L(Xn,{ch:ge[0],dim:!0}),L(M,{color:"gray",children:ge.slice(1)})]}):ke&&!T?oe(Jn,{children:[L(Xn,{ch:ke[0],dim:!0}),L(M,{color:"gray",children:ke.slice(1)}),L(M,{dimColor:!0,children:" (tab)"})]}):(yi.isSetup||!ir)&&!T?oe(Jn,{children:[L(Xn,{ch:yi.text[0],dim:!0}),L(M,{color:"gray",children:yi.text.slice(1)})]}):L(Xn,{ch:" "})]})}),vc.length>0&&L(we,{flexDirection:"column",paddingX:1,children:vc.map((c,u)=>L(M,{color:"gray",children:`\u29D7 queued: ${c}`},`${u}-${c.slice(0,24)}`))}),io?L(kf,{tab:io.tab,scroll:io.scroll,rows:vm,width:Ye,version:o,engineVersion:am}):Kt?oe(we,{flexDirection:"column",paddingX:1,children:[L(M,{color:te,bold:!0,children:"Select model"}),L(M,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),ht.map((c,u)=>oe(M,{color:u===Kt.cursor?te:void 0,children:[u===Kt.cursor?"\u276F ":" ",`${u+1}. ${c.label}${u===Kt.current?" \u2714":""}`.padEnd(16),L(M,{color:"gray",children:c.desc})]},c.label)),L(M,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Rt?oe(we,{flexDirection:"column",paddingX:1,children:[L(M,{color:te,bold:!0,children:"Switch connection profile"}),L(Qn,{rows:Rt.rows,cursor:Rt.cursor,cap:on,render:(c,u,a)=>oe(M,{color:a?te:void 0,children:[a?"\u276F ":" ",`${u+1}. ${c.name}${u===Rt.current?" \u2714":""}`.padEnd(20),L(M,{color:"gray",children:`${c.env} \xB7 ${c.who??"not signed in"}`}),c.prod?L(M,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},c.name)}),L(M,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Ct?oe(we,{flexDirection:"column",paddingX:1,children:[L(M,{color:te,bold:!0,children:"Pick your Document360 environment"}),L(Qn,{rows:Ct.rows,cursor:Ct.cursor,cap:on,render:(c,u,a)=>oe(M,{color:a?te:void 0,children:[a?"\u276F ":" ",`${u+1}. ${c.name}`.padEnd(16),L(M,{color:"gray",children:c.apiUrl}),c.note?L(M,{color:"yellow",children:` \u26A0 ${c.note}`}):null]},c.name)}),L(M,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):Oe?oe(we,{flexDirection:"column",paddingX:1,children:[L(M,{color:te,bold:!0,children:"Switch workspace"}),L(M,{dimColor:!0,children:`environment ${Oe.environment} \xB7 project ${Oe.projectName??`${Oe.projectId.slice(0,8)}\u2026`}`}),L(Qn,{rows:Oe.rows,cursor:Oe.cursor,cap:on,render:(c,u,a)=>oe(M,{color:a?te:void 0,children:[a?"\u276F ":" ",`${u+1}. ${c.name}${u===Oe.current?" \u2714":""}`.padEnd(30),L(M,{color:"gray",children:c.type??""})]},c.id)}),L(M,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):Ze?oe(we,{flexDirection:"column",paddingX:1,children:[L(M,{color:te,bold:!0,children:"Choose project"}),L(M,{dimColor:!0,children:`environment ${Ze.environment}`}),L(Qn,{rows:Ze.rows,cursor:Ze.cursor,cap:on,render:(c,u,a)=>oe(M,{color:a?te:void 0,children:[a?"\u276F ":" ",`${u+1}. ${c.name}${u===Ze.current?" \u2714":""}`.padEnd(30),L(M,{color:"gray",children:c.sub??""})]},c.id)}),L(M,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):Le?(()=>{let u=Math.min(Math.max(0,Le.cursor-Math.floor(7)),Math.max(0,Le.rows.length-14)),a=Le.rows.slice(u,u+14),g=Le.rows.filter(E=>E.checked).length;return oe(we,{flexDirection:"column",paddingX:1,children:[L(M,{color:te,bold:!0,children:`Which folders back the user docs? (${g} selected of ${Le.rows.length})`}),u>0?L(M,{dimColor:!0,children:` \u2191 ${u} more`}):null,a.map((E,F)=>{let f=u+F;return oe(M,{color:f===Le.cursor?te:void 0,children:[f===Le.cursor?"\u276F ":" ",E.checked?"\u25C9 ":"\u25CB ",E.path.padEnd(Math.min(48,Ye-34)),L(M,{color:"gray",children:fs(E)})]},E.path)}),u+14<Le.rows.length?L(M,{dimColor:!0,children:` \u2193 ${Le.rows.length-u-14} more`}):null,L(M,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():at?oe(we,{flexDirection:"column",paddingX:1,children:[L(M,{color:te,bold:!0,children:at.title??"Which category? (pick one to scope to)"}),L(Qn,{rows:at.rows,cursor:at.cursor,cap:on,render:(c,u,a)=>oe(M,{color:a?te:void 0,children:[a?"\u276F ":" ",`${`${u+1}.`.padEnd(3)} ${c.label} (${c.count})`.padEnd(Math.min(44,Math.max(20,Ye-24))),L(M,{color:"gray",children:` ${c.token}`})]},c.token)}),L(M,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter select \xB7 esc cancel"})]}):mt?oe(we,{flexDirection:"column",paddingX:1,children:[L(M,{color:te,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),L(Qn,{rows:mt.rows,cursor:mt.cursor,cap:on,render:(c,u,a)=>oe(M,{color:a?te:void 0,bold:c.kind==="category"&&!a,children:[a?"\u276F ":" ",`${c.indent?" ":" "}${`${u+1}.`.padEnd(3)} ${c.label}`.padEnd(Math.min(56,Ye-24)),c.note?L(M,{color:"gray",children:c.note}):null]},`${c.kind}:${c.paths.join(",")}`)}),L(M,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):St?oe(we,{flexDirection:"column",paddingX:1,children:[L(M,{color:te,bold:!0,children:St.title}),(()=>{let{rows:c,cursor:u}=St,a=Hs(c.length,u,on),g=a.start,E=c.slice(a.start,a.end),F=`${c.length}.`.length+1,f=Id(c,Math.max(20,Ye-4-F));return oe(Jn,{children:[g>0?L(M,{color:"gray",children:` \u2026 ${g} more above`}):null,E.map((y,C)=>{let b=g+C,v=b===u,P=f[b];return oe(M,{color:v?te:void 0,bold:(y.kind==="all"||y.kind==="category")&&!v,children:[v?"\u276F ":" ",`${b+1}.`.padEnd(F),P.head,P.note?L(M,{color:"gray",children:P.note}):null]},`${y.action}:${y.kind}:${y.ids.join(",")}`)}),a.below>0?L(M,{color:"gray",children:` \u2026 ${a.below} more below`}):null]})})(),L(M,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter run \xB7 esc cancel"})]}):qe?oe(we,{flexDirection:"column",paddingX:1,children:[L(M,{color:te,bold:!0,children:`Preview article${qe.query?` \u2014 filter: ${qe.query}`:" (type to filter)"}`}),br.length===0?L(M,{color:"gray",children:"no articles match"}):br.map((c,u)=>oe(M,{color:u===qe.cursor?te:void 0,children:[u===qe.cursor?"\u276F ":" ",c]},c)),L(M,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):Ge?oe(we,{flexDirection:"column",paddingX:1,children:[L(M,{color:te,bold:!0,children:`Resume session${Ge.query?` \u2014 filter: ${Ge.query}`:" (type to filter)"}`}),$r.length===0?L(M,{color:"gray",children:"no sessions match"}):$r.map((c,u)=>oe(M,{color:u===Ge.cursor?te:void 0,children:[u===Ge.cursor?"\u276F ":" ",c.name.slice(0,28).padEnd(30),L(M,{color:u===Ge.cursor?te:"gray",children:c.firstPrompt.slice(0,Math.max(10,Ye-40))})]},c.uuid)),L(M,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Oc?oe(we,{flexDirection:"column",children:[rn>0?L(M,{dimColor:!0,children:` \u22EF ${rn} more above`}):null,wi.map((c,u)=>{let a=rn+u,g=c.name==="model"&&li?`${c.desc} (currently ${li})`:c.desc,E=Math.max(20,Ye-4),F=c.usage.length>E?`${c.usage.slice(0,E-1)}\u2026`:c.usage,f=E-Math.max(F.length,22)-1,y=f<=1?"":g.length>f?`${g.slice(0,f-1)}\u2026`:g;return oe(M,{color:a===kr?te:void 0,children:[a===kr?"\u276F ":" ",F.padEnd(22)," ",L(M,{color:a===kr?te:"gray",children:y})]},c.name)}),rn+wi.length<wt.length?L(M,{dimColor:!0,children:` \u22EF ${wt.length-rn-wi.length} more below`}):null,L(M,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!T&&!w&&pe.length>0?oe(we,{flexDirection:"column",paddingX:1,children:[$c?L(M,{color:te,children:$c}):null,pe.map((c,u)=>{let a=fn(c),g=a.slice(0,Math.max(20,Ye-5)),E=Ye-g.length-7,F=E>=12?(Rf(c)??Fu(a)).slice(0,E):"";return oe(M,{children:[L(M,{color:te,children:u+1})," ",g,F?L(M,{dimColor:!0,children:` \u2014 ${F}`}):null]},a)}),L(M,{dimColor:!0,children:`press 1-${pe.length} to fill \xB7 esc cancel`})]}):L(we,{paddingX:1,children:oe(M,{color:"gray",children:[Ic.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${li??"model n/a"}${t.kind==="api"?Cc>0?` \xB7 ${We(Cc)}`:"":Rc>0?` \xB7 ${_t(Rc)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}Q();import{jsx as b0}from"react/jsx-runtime";async function cm(e=process.cwd(),t="auto",n,o="0.0.0"){let r=k0(t);r.kind==="none"&&(console.error(""),console.error(j("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${G("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${G("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=w0(b0(lm,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
|
|
490
|
+
`),process.exit(0)}Q();import{writeCrashLog as um,isBenignTransportError as $0}from"document360-engine";var dm=!1;function fc(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function pm(e){if(dm)return;dm=!0;let t=(n,o)=>{if($0(o)){um({kind:n,level:"transport",message:fc(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=um({kind:n,level:"fatal",message:fc(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
|
|
491
|
+
`+j(`\u2717 d360-writer crashed: ${fc(o)}`)+`
|
|
492
|
+
`),r&&process.stderr.write(k(` Crash details: ${r}`)+`
|
|
493
|
+
`+k(" Run: d360-writer logs")+`
|
|
494
|
+
`),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var C0=x0(import.meta.url),ni=C0("../package.json");pm("d360-writer");var st=new v0;function mc(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}st.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=>{mc(e),await Ir({profile:e.profile,manual:e.manual})});st.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{mc(e),await iu({profile:e.profile})});st.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{mc(e),await su({profile:e.profile})});var gc=st.command("profile").description("Manage connection profiles for the current repo");gc.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>Or(process.cwd()));gc.command("use <name>").description("Set the default profile for this repo").action(e=>Lr(process.cwd(),e));gc.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>_r(process.cwd(),e));var hm=st.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");hm.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>jn(process.cwd(),e.profile));hm.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await Qc(process.cwd(),e,t.profile)});var fm=st.command("project").description("Choose the Document360 project for this repo (active profile's identity)");fm.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>Dr(process.cwd(),e.profile));fm.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await Zc(process.cwd(),e,t.profile)});st.command("init").description("Scaffold .d360-writer/config.json for this repo (interactive)").action(async()=>{let{initCommand:e}=await Promise.resolve().then(()=>(Vr(),Mu));await e()});st.command("logs").description("Show the API + crash log files (send these to support when reporting a problem)").action(()=>uu());st.command("doctor").description("Health-check: node, Claude auth, Document360 login, profile/workspace, category map, API reachability").action(async()=>{let{renderDoctorChecks:e,runDoctorChecks:t}=await Promise.resolve().then(()=>($s(),Np)),n=await t(process.cwd(),ni.version);for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});st.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(ni.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(R0.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 du(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 Zh(e.cwd,e.auth,e.profile,ni.version):await cm(e.cwd,e.auth,e.profile,ni.version)});st.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
|