document360-writer 0.5.326 → 0.5.327
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 +296 -295
- package/package.json +3 -3
package/dist/cli.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var sR=Object.defineProperty;var Fr=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var Rg=(e,t)=>{for(var n in t)sR(e,n,{get:t[n],enumerable:!0})};import no from"picocolors";import{BRAND as iR}from"document360-engine";var pe,Ku,Yu,aR,lR,cR,Sg,Qs,u,L,F,Q,Z,Ie,rt,Je,qo,te,ae=Fr(()=>{"use strict";pe=iR.brandHex,Ku=e=>parseInt(pe.slice(e,e+2),16),Yu=[Ku(1),Ku(3),Ku(5)],[aR,lR,cR]=Yu,Sg=e=>no.isColorSupported?`\x1B[38;2;${aR};${lR};${cR}m${e}\x1B[39m`:e,Qs=e=>no.bold(Sg(e)),u=e=>no.dim(e),L=e=>no.red(e),F=e=>no.yellow(e),Q=e=>no.green(e),Z=Sg,Ie=e=>no.gray(e),rt=e=>no.bold(e),Je="\u25CF production",qo="\u25CF",te=(e,t)=>`${e} ${t}`});import{CUSTOM_ENVIRONMENT_NAME as CR,currentEnvironments as PR,environmentIsAdded as AR,environmentIsInternal as Dg,environmentIsProduction as jg,isExpired as TR,isKnownEnvironment as ER,knownEnvironments as NR,loadProfileMap as DR,loadTokens as jR,profileEnvironmentName as IR,readProjectConfig as Ju,resolveActiveProfile as LR,resolveEnvironment as Ig,sunsetEnvironment as Qu,unpushedArticlePaths as OR,unshippedEnvironment as _R,PRODUCT_NAME as MR}from"document360-engine";function Zu(e,t){let n=Ju(e);return Object.entries(n?.profiles??{}).find(([,o])=>o.connection?.environment===t)?.[0]??null}function Ve(e,t){try{if(!Ju(e))return null;let n=IR(e,t);if(!n)return null;let o=Qu(n);if(o){let s=Zu(e,o.replacement);return{name:o.name,kind:"retired",replacement:o.replacement,why:o.why,replacementProfile:s,cmd:s?`/profile ${s}`:`/profile add ${o.replacement}`}}if(ER(n))return null;let r=_R(n);return r?{name:r.name,kind:"unshipped",replacement:null,why:`${r.why}, so this machine needs its connection file`,replacementProfile:null,cmd:"/profile"}:{name:n,kind:"unknown",why:`no Document360 deployment by that name is shipped with ${MR} or added on this machine`,replacement:null,replacementProfile:null,cmd:"/profile"}}catch{return null}}function UR(e){return e==="production-eu"?"Europe":e==="production-us"?"United States":e==="production-ca"?"Canada":null}function oo(){return[...PR(),...NR().filter(t=>Qu(t))].map(t=>{let n=Dg(t),o=jg(t),r=Qu(t)!==null,s=AR(t),a=[r?"being retired":n?"Document360 internal staging":UR(t),s?"added on this machine":null].filter(Boolean).join(", ")||null;return{name:t,portalUrl:Ig(t).portalUrl,note:a,internal:n,production:o,added:s,retired:r}})}function ed(e){let t=Ju(e);if(!t?.profiles)return[];let n=(()=>{try{return LR(e).name}catch{return t.defaultProfile??null}})();return Object.entries(t.profiles).map(([o,r])=>{let s=r.connection?.environment??CR,i=r.connection?.portalUrl??"";try{r.connection?.environment&&(i=Ig(r.connection.environment).portalUrl)}catch{i=""}let a=DR(e,o),l=r.project?.projectId,c=!1;try{let m=jR(o,l);c=!!m&&(!TR(m)||!!m.refreshToken)}catch{c=!1}let p=0;try{p=OR(e,o).length}catch{p=0}return{profile:o,environment:s,portalUrl:i,production:r.production??jg(r.connection?.environment),internal:Dg(r.connection?.environment),project:r.project?.projectName??l??null,workspace:r.project?.workspaceName??r.project?.workspaceId??null,tracked:a?Object.keys(a.articles).length:0,unpushed:p,signedIn:c,active:o===n}})}function Lg(e){let t=new Map;for(let n of ed(e))n.project&&t.set(n.project,[...t.get(n.project)??[],n.profile]);return[...t.values()].filter(n=>n.length>1)}var mn=Fr(()=>{"use strict"});import{existsSync as Br,writeFileSync as so,readFileSync as qS,readdirSync as VS}from"node:fs";import{join as my}from"node:path";import{devHintsGuidePath as Za,hintsDir as gy,hooksDir as yy,architectureDir as vy,messagesDir as fd,creatorNotesPath as wy,devhintsStatePath as xy,directivesPath as ky,DIRECTIVES_HEADER as KS,roadmapPath as by,ROADMAP_HEADER as YS,ensureDir as ri,writeMessage as zS,listOpenForDev as XS,stampDone as QS,seedBriefConsumed as JS,PRODUCT_NAME as Yo,PRODUCT_DISPLAY_NAME as yn,WRITER_COMMAND as $y,WRITER_DIRNAME as fe,DIRECTIVE_MENTION as Hr}from"document360-engine";function Ry(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
|
|
3
3
|
|
|
4
|
-
<!-- devhints script v${
|
|
4
|
+
<!-- devhints script v${Ge} \xB7 maintained by ${yn} (/devhints). -->
|
|
5
5
|
|
|
6
|
-
This repo's user documentation is written by **
|
|
6
|
+
This repo's user documentation is written by **${yn}** ("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
|
|
8
8
|
thousand code paths is the one a user touches, the conceptual model, the terminology, what's new. You
|
|
9
9
|
(the coding agent that built this product) hold that context. This guide is how you hand it over.
|
|
@@ -15,7 +15,7 @@ you keep them in the loop as you ship (Part 2).
|
|
|
15
15
|
|
|
16
16
|
## Part 1 \u2014 Architecture brief (create it, then keep it current)
|
|
17
17
|
|
|
18
|
-
Write a **user-doc-enabling brief** into
|
|
18
|
+
Write a **user-doc-enabling brief** into \`${fe}/architecture/\` \u2014 one or more \`.md\` files. This
|
|
19
19
|
is NOT an engineering design doc. It is everything a *technical writer* needs to document the product for
|
|
20
20
|
END USERS. Steer hard toward the user-facing story; deprioritize internals.
|
|
21
21
|
|
|
@@ -23,7 +23,7 @@ END USERS. Steer hard toward the user-facing story; deprioritize internals.
|
|
|
23
23
|
it to match the current code: add new surfaces/features, correct what changed, remove what was deleted,
|
|
24
24
|
and preserve accurate existing content and human edits. Leave it untouched if nothing changed.
|
|
25
25
|
|
|
26
|
-
**0. First, read
|
|
26
|
+
**0. First, read \`${fe}/architecture/CREATOR-NOTES.md\`** \u2014 the original human creator's notes.
|
|
27
27
|
Treat anything there as **authoritative** (a human's "folder X is the admin UI; skip src/Services" beats
|
|
28
28
|
any inference). It may be empty \u2014 that's fine. **Never modify CREATOR-NOTES.md** (it's human-owned);
|
|
29
29
|
write your brief to OTHER files in the folder.
|
|
@@ -62,7 +62,7 @@ finished. Nothing is lost either way, but a hint dropped after the commit is wri
|
|
|
62
62
|
If you hand one off early on purpose, say so in the body and answer that question when it arrives.
|
|
63
63
|
|
|
64
64
|
### How to write a hint
|
|
65
|
-
Create **one new file** under
|
|
65
|
+
Create **one new file** under \`${fe}/hints/\` named \`<YYYY-MM-DD>-<short-slug>-<random>.md\`
|
|
66
66
|
(e.g. \`2026-06-17-export-csv-button-a1b2c3.md\`). One file per hint \u2014 never append (distinct files merge
|
|
67
67
|
cleanly across branches). Markdown with a YAML frontmatter header:
|
|
68
68
|
|
|
@@ -93,7 +93,7 @@ Prose: what you built and the gotchas a code diff would miss \u2014 e.g. "the bu
|
|
|
93
93
|
- Keep the body about user-facing intent, not implementation.
|
|
94
94
|
|
|
95
95
|
**Surface every hint \u2014 never silently.** When you drop a hint, say so in your reply: name the file and the
|
|
96
|
-
one-line surface (e.g. \`\u{1F4E8} Handed off to the docs agent:
|
|
96
|
+
one-line surface (e.g. \`\u{1F4E8} Handed off to the docs agent: ${fe}/hints/<file> \u2014 "<surface>"\`). The
|
|
97
97
|
human should be able to SEE the hand-off happened, not assume it.
|
|
98
98
|
|
|
99
99
|
**Stay in your lane \u2014 you hand off, you don't write the docs.** Your job ends at the hint + a current
|
|
@@ -110,10 +110,10 @@ That's it \u2014 drop the file and keep building. The docs agent picks it up on
|
|
|
110
110
|
Parts 1\u20132 are you \u2192 the writer. The writer can also reach **you**, two ways: a **question**
|
|
111
111
|
(\`kind: question\` \u2014 it can't ground a fact in the code or this brief and needs your answer) or a
|
|
112
112
|
**request** (\`kind: request\` \u2014 it needs you to *do* something, e.g. "the dev\u2194docs onboarding protocol
|
|
113
|
-
upgraded to a new version \u2014 re-run it"). Both arrive as files in
|
|
113
|
+
upgraded to a new version \u2014 re-run it"). Both arrive as files in \`${fe}/messages/\`
|
|
114
114
|
(\`from: docs\`, \`status: open\`).
|
|
115
115
|
|
|
116
|
-
**Each session \u2014 and every time you run this prompt \u2014 check
|
|
116
|
+
**Each session \u2014 and every time you run this prompt \u2014 check \`${fe}/messages/\` for open messages
|
|
117
117
|
addressed to you** (\`from: docs\`, \`status: open\`). **An open docs question BLOCKS the documentation \u2014
|
|
118
118
|
treat answering it as a task you own THIS session, not optional and not "eventually".** The writer can't
|
|
119
119
|
ground what only you know, and it will not ask the human \u2014 so if you don't answer, that part of the docs
|
|
@@ -138,11 +138,11 @@ the "what"), and fold the durable facts into the architecture brief. The writer
|
|
|
138
138
|
the product; the faster you answer, the faster the docs get good.
|
|
139
139
|
|
|
140
140
|
**Session-start nudge (so you never miss an open question).** Because a "check each session" rule is easy
|
|
141
|
-
to forget, onboarding wires a session-start TRIGGER.
|
|
142
|
-
at
|
|
141
|
+
to forget, onboarding wires a session-start TRIGGER. ${Yo} ships a portable, dependency-free checker
|
|
142
|
+
at \`${fe}/hooks/open-questions.mjs\` that prints a one-line nudge when open \`from: docs\` questions
|
|
143
143
|
exist (silent otherwise). You register it with your coding agent's session-start mechanism (the onboarding
|
|
144
144
|
prompt walks you through it): **Claude Code** \u2192 a \`SessionStart\` hook in \`.claude/settings.json\` running
|
|
145
|
-
\`node
|
|
145
|
+
\`node ${fe}/hooks/open-questions.mjs\` (its stdout joins your context at session start); **Codex or
|
|
146
146
|
other agents** \u2192 rely on this memory rule for now (and run the checker yourself when starting a docs
|
|
147
147
|
session) until the agent gains a native session-start trigger. The checker is agent-agnostic; only the
|
|
148
148
|
wiring differs per agent.
|
|
@@ -151,7 +151,7 @@ You can also **initiate**: to ask the writer to document something, drop a **req
|
|
|
151
151
|
\`from: dev\`, \`kind: request\`, \`sources: [the files you changed]\`, a \`subject\`, and a body describing
|
|
152
152
|
what you shipped. The writer picks requests up via its \`/inbox\`.
|
|
153
153
|
|
|
154
|
-
Message file shape (one file per message, under
|
|
154
|
+
Message file shape (one file per message, under \`${fe}/messages/\`):
|
|
155
155
|
\`\`\`markdown
|
|
156
156
|
---
|
|
157
157
|
id: <short token>
|
|
@@ -177,8 +177,8 @@ new section, one new article, an update to existing articles, or retiring what's
|
|
|
177
177
|
output shape; the writer judges it like a technical writer would. Two ways:
|
|
178
178
|
|
|
179
179
|
- **Now (synchronous)** \u2014 run from this repo:
|
|
180
|
-
|
|
181
|
-
Prerequisites:
|
|
180
|
+
\`${$y} -p "document the <feature> we added today: <what changed and why, in a paragraph>"\`
|
|
181
|
+
Prerequisites: ${Yo} installed, logged in (\`${$y} login\`), and a project selected. Add
|
|
182
182
|
\`--yes\` if the target profile is production.
|
|
183
183
|
- **Queued (async)** \u2014 drop a \`request\` message (Part 3); the writer documents it on its next session or
|
|
184
184
|
via CI. Use this when a human should review before publishing.
|
|
@@ -189,64 +189,64 @@ output shape; the writer judges it like a technical writer would. Two ways:
|
|
|
189
189
|
|
|
190
190
|
**This changed.** The docs agent used to be unable to run git, so committing ITS output was your chore.
|
|
191
191
|
It now **commits and pushes its own output** \u2014 the articles, the category map, its message status flips.
|
|
192
|
-
You no longer babysit that, and the old "please commit
|
|
192
|
+
You no longer babysit that, and the old "please commit \`${fe}/\`" request is gone. What you owe
|
|
193
193
|
instead is the other half of the exchange:
|
|
194
194
|
|
|
195
195
|
- **\`git pull\` when you start a session.** This is the important one. The writer may be a different
|
|
196
196
|
person on a different machine, and **their questions for you arrive only when you pull**. An open docs
|
|
197
197
|
question BLOCKS the documentation (Part 3) \u2014 if you don't pull, you never see it, and that part of the
|
|
198
|
-
docs ships thin or stalls. Pull *before* you check
|
|
199
|
-
- **Commit and push YOUR OWN writes under
|
|
198
|
+
docs ships thin or stalls. Pull *before* you check \`${fe}/messages/\`.
|
|
199
|
+
- **Commit and push YOUR OWN writes under \`${fe}/\`** \u2014 hints (Part 2), the architecture brief
|
|
200
200
|
(Part 1), your answer messages (Part 3), relayed owner directives (Part 6). The docs agent commits *its*
|
|
201
201
|
work, not yours, and unpushed hints reach nobody. In your clone this is simple: the writer's output
|
|
202
|
-
arrives already committed, so anything still uncommitted under
|
|
203
|
-
\`git add
|
|
202
|
+
arrives already committed, so anything still uncommitted under \`${fe}/\` is yours to commit.
|
|
203
|
+
\`git add ${fe} && git commit -m "docs: hand-off" && git push\` remains exactly right.
|
|
204
204
|
|
|
205
205
|
Two notes on what the docs agent's own commits look like, so they don't surprise you in \`git log\`:
|
|
206
206
|
|
|
207
|
-
- They are scoped to the docs footprint by pathspec (\`git commit --
|
|
207
|
+
- They are scoped to the docs footprint by pathspec (\`git commit -- ${fe} \u2026\`), so a docs commit
|
|
208
208
|
can **never** pick up your in-progress source changes, staged or unstaged.
|
|
209
209
|
- They land on the current branch and are pushed to its remote. Nothing is ever force-pushed, and if your
|
|
210
210
|
push and theirs collide, the docs agent **stops and reports** rather than rebasing or merging \u2014 the
|
|
211
211
|
writer is told to ask you to sort it out.
|
|
212
212
|
|
|
213
|
-
Still true, and the reason this matters:
|
|
213
|
+
Still true, and the reason this matters: **\`${fe}/category-map.json\`** links each local file to its
|
|
214
214
|
Document360 article id **plus the sync baseline**. If it's lost, the docs agent can't tell which local file
|
|
215
215
|
maps to which portal article, and a later publish can **create duplicates**. Treat it like a lockfile \u2014 it
|
|
216
216
|
is now committed automatically, which is exactly the point.
|
|
217
217
|
|
|
218
218
|
*(If a repo has this turned off \u2014 \`/share off\` on the writer's side, or no git remote \u2014 the docs agent
|
|
219
|
-
falls back to leaving you a standing "please commit
|
|
219
|
+
falls back to leaving you a standing "please commit \`${fe}/\`" request in your mailbox, as before.)*
|
|
220
220
|
|
|
221
221
|
---
|
|
222
222
|
|
|
223
|
-
## Part 6 \u2014 Relay the owner's
|
|
223
|
+
## Part 6 \u2014 Relay the owner's \`${Hr}\` directives (do NOT action them)
|
|
224
224
|
|
|
225
225
|
The human directing the work has a channel to the docs agent for **proactive** documentation asks \u2014 not
|
|
226
226
|
tied to a code change (Part 2) or a portal review \u2014 e.g. *"write a detailed page for /review"* or *"here's a
|
|
227
|
-
scenario, document it"*. They express it by typing a message that starts with
|
|
227
|
+
scenario, document it"*. They express it by typing a message that starts with **\`${Hr}\`** in YOUR
|
|
228
228
|
session:
|
|
229
229
|
|
|
230
|
-
>
|
|
230
|
+
> \`${Hr} write a detailed page for the /review command\`
|
|
231
231
|
|
|
232
|
-
When you see an
|
|
232
|
+
When you see an \`${Hr} <directive>\` message from the human, do exactly two things \u2014 **relay it, don't
|
|
233
233
|
do it**:
|
|
234
|
-
1. **Append** it as a new block to
|
|
234
|
+
1. **Append** it as a new block to \`${fe}/directives.md\` (create the file if absent):
|
|
235
235
|
\`\`\`markdown
|
|
236
236
|
## [open] <the directive, one line>
|
|
237
237
|
by: <the human / owner> \xB7 <YYYY-MM-DD>
|
|
238
238
|
<any scenario or detail they gave, verbatim, to ground the doc>
|
|
239
239
|
\`\`\`
|
|
240
|
-
2. **Commit**
|
|
240
|
+
2. **Commit** \`${fe}/directives.md\`, and confirm in your reply (e.g. \`\u{1F4E5} Recorded owner directive \u2192 ${fe}/directives.md: "<directive>"\`).
|
|
241
241
|
|
|
242
242
|
**Do NOT write or action the documentation yourself** \u2014 same boundary as Part 2. Writing the article is the
|
|
243
243
|
docs agent's job; it actions open directives on its next \`/catch-up\` (as drafts) and flips each to \`[done]\`
|
|
244
244
|
with the article it wrote. You are only the relay so the ask is captured durably and travels via git.
|
|
245
|
-
`}function
|
|
245
|
+
`}function eC(){return`# Creator notes (optional \u2014 for the docs agent and the builder)
|
|
246
246
|
|
|
247
247
|
<!-- The ORIGINAL CREATOR's context. Most repos leave this empty \u2014 that's fine.
|
|
248
248
|
The builder agent reads this FIRST and treats it as authoritative when writing the architecture
|
|
249
|
-
brief.
|
|
249
|
+
brief. ${yn} (the docs agent) also reads it as authoritative intent.
|
|
250
250
|
This file is HUMAN-OWNED: the builder never overwrites it. -->
|
|
251
251
|
|
|
252
252
|
Anything only a human knows that would help document this product. For example:
|
|
@@ -256,20 +256,20 @@ Anything only a human knows that would help document this product. For example:
|
|
|
256
256
|
- Gotchas or non-obvious behavior.
|
|
257
257
|
|
|
258
258
|
(Replace these examples with your notes, or leave the file as-is to skip \u2014 it's optional.)
|
|
259
|
-
`}function
|
|
260
|
-
`)}
|
|
261
|
-
`)}function
|
|
262
|
-
`)}function
|
|
263
|
-
`)}),n.notifiedBuilder=!0)}}catch{}return n}function
|
|
264
|
-
`)}function
|
|
265
|
-
//
|
|
266
|
-
// ("Julie") left in
|
|
267
|
-
// wired into your coding agent's session-start trigger by /devhints. See
|
|
259
|
+
`}function qr(e){ri(gy(e)),ri(vy(e)),ri(fd(e));for(let n of[gy(e),fd(e)]){let o=my(n,".gitkeep");Br(o)||so(o,`# Keeps this ${yn} inbox tracked in git even when empty.
|
|
260
|
+
`)}Br(wy(e))||so(wy(e),eC()),Br(ky(e))||so(ky(e),KS),Br(by(e))||so(by(e),YS),so(Za(e),Ry()),ri(yy(e)),so(my(yy(e),"open-questions.mjs"),ZS);let t=an(e);return Cy(e,new Date().toISOString()),t}async function Sy(e,t){for(let n of Vr(qr(t.cwd)))console.log(n);return{kind:"continue"}}function zo(){return[`This is ${yn}'s dev hand-off setup (v${Ge}).`,`Connect this repository to ${yn} (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 \`${fe}/DEV-HINTS-GUIDE.md\` \u2014 the full dev\u2192docs hand-off protocol (Parts 1\u20136). Follow it.`,`2. Architecture brief in \`${fe}/architecture/\` (per the guide). First read`,` \`${fe}/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',` \`${fe}/hints/\` and keep \`${fe}/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 \`${fe}/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 \`${Hr} <directive>\` in your session, append it as an \`## [open] <directive>\` block`,` to \`${fe}/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 \`${fe}/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 \`${fe}/\` 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. ${Yo} already scaffolded a portable, dependency-free checker`,` at \`${fe}/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 ${fe}/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 ${fe}/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 ${fe}/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",` \`${fe}/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 \`${fe}/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 \`${fe}/devhints-state.json\` with {"completedVersion": ${Ge},`,' "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 \`${fe}/config.json\` (default \`${fe}/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 ${yn} 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 ${yn} terminal, paste this:"`,` \u2014 or "Now switch to the ${yn} terminal and paste this:" on first-time setup.`].join(`
|
|
261
|
+
`)}function gd(e){try{let t=qS(xy(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function Cy(e,t){let o={...gd(e)??{},emittedVersion:Ge,emittedAt:t};so(xy(e),`${JSON.stringify(o,null,2)}
|
|
262
|
+
`)}function Un(e){try{return VS(vy(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function an(e){let n=gd(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<Ge?"stale":"current",completedVersion:n}}function tC(e){let t=new RegExp(`${md.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(\\d+)\\)`).exec(e);return t?Number(t[1]):null}function el(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,supersededRequests:[],toVersion:Ge};try{if(!Br(Za(e)))return n;JS(e);let o=gd(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;if(Ge>r&&(ri(fd(e)),so(Za(e),Ry()),Cy(e,t),n.guideRefreshed=!0),Ge>s){let i=XS(e).filter(l=>l.kind==="request"&&l.subject.startsWith(md)),a=i.filter(l=>(tC(l.subject)??Ge)>=Ge);for(let l of i.filter(c=>!a.includes(c)))QS(e,l.file,{doneAt:t,answeredBy:"docs"}),n.supersededRequests.push(l.subject);a.length===0&&(zS(e,{id:`onb${Ge}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${md}${Ge})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${Ge}${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:","",zo()].join(`
|
|
263
|
+
`)}),n.notifiedBuilder=!0)}}catch{}return n}function tl(e){if(!Br(Za(e)))return[];let t=an(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 ${Yo}'s dev\u2194docs protocol is now v${Ge}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,Gr,zo(),Gr,`(Also saved in ${fe}/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)`]}function yd(){return[`${yn} (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',` \`${fe}/hints/\`, keeping \`${fe}/architecture/\` current, checking`,` \`${fe}/messages/\`, and relaying \`${Hr}\` directives to \`${fe}/directives.md\`).`," Leave everything else in that file untouched.",`2. The \`${fe}/\` folder is already deleted on disk. If it was committed, remove it from version`,` control too \u2014 \`git rm -r --cached ${fe}\` (if it still resolves) \u2014 and commit the deletions.`,"3. Do NOT recreate any of those files or follow the hand-off protocol anymore.","","That's it \u2014 this repo is back to its pre-docs-agent state."].join(`
|
|
264
|
+
`)}function nl(){return['\u{1F9F9} One leftover: your builder still has the "Documentation hand-off" rule in its CLAUDE.md / AGENTS.md',` (reset only clears ${Yo}'s own ${fe}/ folder \u2014 never your repo's files).`," To restore it, paste this prompt into your repo's coding agent (Claude Code / Codex / Cursor):",Gr,yd(),Gr]}function Vr(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${Ge}.`," Have them run the prompt below again \u2014 it now sets up two-way messages + on-demand docs.",""]:[],`\u2713 Wrote ${fe}/DEV-HINTS-GUIDE.md + the ${fe}/architecture/ (brief), ${fe}/hints/, and ${fe}/messages/ inboxes.`,"","\u{1F4CB} Copy this one prompt and run it in your repo's coding agent (Claude Code / Codex / Cursor):",Gr,zo(),Gr,"","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 Gr,Ge,ZS,md,io=Fr(()=>{"use strict";Gr="-".repeat(64),Ge=13,ZS=`#!/usr/bin/env node
|
|
265
|
+
// ${Yo} \u2014 session-start nudge for the builder ("John"). Surfaces open questions the docs agent
|
|
266
|
+
// ("Julie") left in ${fe}/messages/ so they get answered, not forgotten. Self-contained (no deps);
|
|
267
|
+
// wired into your coding agent's session-start trigger by /devhints. See ${fe}/DEV-HINTS-GUIDE.md.
|
|
268
268
|
import { readdirSync, readFileSync } from 'node:fs';
|
|
269
269
|
import { join } from 'node:path';
|
|
270
270
|
|
|
271
271
|
try {
|
|
272
|
-
const dir = join(process.cwd(), '
|
|
272
|
+
const dir = join(process.cwd(), '${fe}', 'messages');
|
|
273
273
|
let open = 0;
|
|
274
274
|
let discovery = 0;
|
|
275
275
|
for (const f of readdirSync(dir)) {
|
|
@@ -292,105 +292,105 @@ try {
|
|
|
292
292
|
? ' (' + discovery + ' are [discovery] questions that define the product brief \u2014 answer those in depth)'
|
|
293
293
|
: '';
|
|
294
294
|
process.stdout.write(
|
|
295
|
-
'\u{1F4CB}
|
|
296
|
-
'. Reply with an answer file (kind: answer, status: open \u2014 the writer closes it after folding), flip only the QUESTION to status: done. An open docs question blocks the documentation. See
|
|
295
|
+
'\u{1F4CB} ${Yo}: ' + open + ' open question' + (open === 1 ? '' : 's') + ' from the docs agent await your answer' + d +
|
|
296
|
+
'. Reply with an answer file (kind: answer, status: open \u2014 the writer closes it after folding), flip only the QUESTION to status: done. An open docs question blocks the documentation. See ${fe}/DEV-HINTS-GUIDE.md.\\n',
|
|
297
297
|
);
|
|
298
298
|
}
|
|
299
299
|
} catch {
|
|
300
300
|
/* a session-start nudge must never break the session */
|
|
301
301
|
}
|
|
302
|
-
`;
|
|
303
|
-
`),"utf8");return}let o;try{o=
|
|
302
|
+
`;md="Re-run dev\u2194docs onboarding (protocol v"});var My={};Rg(My,{initCommand:()=>bd,scaffoldInit:()=>wd,writeWriterGitignore:()=>kd});import{input as ol,confirm as nC,select as oC}from"@inquirer/prompts";import{basename as Ty,join as rl}from"node:path";import{existsSync as Kr,readFileSync as Ey,readdirSync as rC,writeFileSync as Py}from"node:fs";import{writeProjectConfig as Ny,readProjectConfig as sC,projectConfigPath as Dy,writerDir as iC,DEFAULT_DOCS_DIR as jy,DEFAULT_CAPTURE_DIR as Iy,DEFAULT_OUTPUT_DIR as Ly,environmentIsProduction as aC,resolveEnvironment as lC,WRITER_COMMAND as cC,CAPTURE_PACKAGE as uC}from"document360-engine";function wd(e,t){let n=Dy(e);if(Kr(n))return{created:!1,path:n,profileName:""};let o={projectId:Oy(e)??Ty(e),docsDir:jy,captureDir:Iy,outputDir:Ly,profiles:{[t]:{connection:{environment:t}}},defaultProfile:t,authoritativeSourceFiles:_y(e)};return Ny(o,e),kd(e),{created:!0,path:n,profileName:t}}function kd(e){let t=rl(iC(e),".gitignore"),n="# Local/transient \u2014 the config files here ARE meant to be committed.";if(!Kr(t)){Py(t,[n,...Ay,""].join(`
|
|
303
|
+
`),"utf8");return}let o;try{o=Ey(t,"utf8")}catch{return}let r=new Set(o.split(/\r?\n/).map(l=>l.trim())),s=Ay.filter(l=>!r.has(l)&&!r.has(l.replace(/\/$/,"")));if(s.length===0)return;let i=/\r\n/.test(o)?`\r
|
|
304
304
|
`:`
|
|
305
305
|
`,a=o.endsWith(`
|
|
306
|
-
`)?"":i;Ig(t,`${o}${a}${s.join(i)}${i}`,"utf8")}async function Fu(){let e=process.cwd(),t=Fg(e);if(Ir(t)&&!await UR({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(u("init canceled.")),{kind:"continue"};let n=Hg(e)??Og(e),o=await ja({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await ja({message:"Capture directory (where document360-capture .spec.ts files live):",default:Wg}),s=await ja({message:"Screenshot output directory:",default:Bg}),i=Xn().filter(w=>!w.retired),a=Math.max(...i.map(w=>w.portalUrl.length))+3,l=await WR({message:"Which Document360 deployment do these docs publish to?",choices:i.map(w=>({name:`${w.name.padEnd(16)}${w.portalUrl.padEnd(a)}${w.note?`(${w.note})`:""}`.trimEnd(),value:w.name}))}),c=await ja({message:"Name for this connection profile:",default:l}),p={projectId:o,docsDir:Ug,captureDir:r,outputDir:s,profiles:{[c]:{connection:{environment:l}}},defaultProfile:c,authoritativeSourceFiles:Gg(e)},m=HR(e);m?.terminologyGlossary&&(p.terminologyGlossary=m.terminologyGlossary),Mg(p,e),Mu(e);let $=Dr(e);console.log(""),console.log(Q(`\u2713 Wrote ${t}`)),qR(l)&&(console.log(""),console.log(`\u26A0 ${l} is a live deployment \u2014 ${VR(l).portalUrl}`),console.log(u(" Drafts save freely. Taking articles live needs --yes, or /allow-prod in the app."))),console.log(""),console.log(`Next: ${Z(`d360-writer login --profile ${c}`)} ${u("(sign in; project & workspace auto-selected)")}`),console.log("");for(let w of jr($))console.log(w);return console.log(""),console.log(`${u("Then ask:")} ${Z('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function Hg(e){let t=Ia(e,"package.json");if(!Ir(t))return null;try{return JSON.parse(_g(t,"utf8")).name??null}catch{return null}}function Gg(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Ir(Ia(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Ia(e,n);Ir(o)&&!KR(o)&&t.push(n)}return t}function KR(e){try{return BR(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var Lg,La=Tr(()=>{"use strict";ue();un();Zn();Lg=[".sessions/","cache/"]});import{createRequire as lS}from"node:module";import{existsSync as cS,readFileSync as uS}from"node:fs";import{dirname as ty,join as ny}from"node:path";function Ct(){let e;try{e=dS.resolve("document360-capture/helpers")}catch{return null}let t=ty(e);for(let n=0;n<5&&!cS(ny(t,"package.json"));n++)t=ty(t);try{let n=JSON.parse(uS(ny(t,"package.json"),"utf8"));return n.name==="document360-capture"&&n.version?n.version:null}catch{return null}}var dS,Lr=Tr(()=>{"use strict";dS=lS(import.meta.url)});var vk={};Lm(vk,{doctorCommand:()=>di,renderDoctorChecks:()=>$k,runDoctorChecks:()=>bk});import{existsSync as yA}from"node:fs";import{d360GetAll as wA,getAccessToken as kA,isExpired as Ll,loadProfileMap as bA,loadCoverage as $A,danglingCount as vA,profileIdentityDrift as xA,loadTokens as RA,listStoredSessions as SA,tokensProjectId as jp,packageSkillsDir as kk,ENGINE_VERSION as CA,projectConfigPath as PA,readProjectConfig as TA,DEFAULT_DOCS_DIR as AA,fetchManifestSummary as EA,resolveActiveProfile as NA,loadAddedEnvironments as DA,addedEnvironmentsPath as jA,classifyClaudeAuth as IA,resolveAuthOrigin as LA,authOriginLine as OA,authOriginFix as _A,CLAUDE_CODE_SETUP_HINT as Ol,resolveModelSetting as MA,probeModel as FA,probeAgentTurn as UA,stderrHeadline as WA,detectAppType as BA,playbookSkillName as HA,D360AuthError as GA,applyStructureOrder as qA}from"document360-engine";async function bk(e,t){let n=[],o=Ct();n.push({level:"ok",label:`d360-writer ${t?`v${t}`:"(version unknown)"} \xB7 engine v${CA}${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=IA();if(s.state==="ready"){let K=LA(),ne=_A(K);n.push({level:ne?"warn":"ok",label:`Claude auth: ${OA(K).replace(/^Claude: /,"")}`,...ne?{fix:ne}:{}})}else s.state==="maybe"?n.push({level:"warn",label:"Claude: no Claude Code login found (may be in the macOS Keychain)",fix:`If a docs turn ends with no output, sign in to Claude Code. ${Ol}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:Ol});let i=MA(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 K=await FA(e,i.model??void 0);if(K.ok){n.push({level:"ok",label:`Model reachable \u2014 replied in ${(K.latencyMs/1e3).toFixed(1)}s`});let ne=await UA(e,i.model??void 0);if(ne.ok)n.push({level:"ok",label:`Agent turn works \u2014 ran with your skills and tools in ${(ne.latencyMs/1e3).toFixed(1)}s`});else{let oe=WA(ne.stderr),ve=/auth|sign.?in|login|credential|token|401|expired/i.test(`${ne.error??""} ${ne.stderr??""}`);if(n.push({level:"fail",label:ne.timedOut?"Agent turn never finished \u2014 the model answers, but a real turn with your skills and tools hangs":ve?"Agent turn failed \u2014 your Claude sign-in has expired, so every /write, /review and /catch-up will do nothing":`Agent turn produced nothing \u2014 the model answers, but a real turn with your skills and tools ${ne.producedNothing?"ends instantly with no output":`fails: ${ne.error}`}`,fix:(oe?`Claude Code said: "${oe}". `:"")+(ve?`Sign in again, then re-run /doctor. ${Ol}`:"This is the failure behind an empty /write, /review or /catch-up. Run /logs for the whole thing \u2014 it offers to copy it so you can send it to the team.")}),ve){let ae=n.find(pe=>pe.label.startsWith("Claude auth:"));ae&&(ae.level="warn",ae.label="Claude auth: a sign-in exists on this machine, but it is no longer valid",ae.fix=`Sign in again. ${Ol}`)}}}else K.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 ${K.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=TA(e);if(!a)return n.push({level:"fail",label:`No ${PA(e)}`,fix:"Run: /init (or d360-writer init)"}),n;n.push({level:"ok",label:`Project config: ${a.projectId}`});let l=(a.docsDir??AA).replace(/\/+$/,"");n.push(a.mode==="engineer"?{level:"warn",label:"Mode: engineer \u2014 agent may modify any source file (dogfooding)",fix:'Remove "mode" from .d360-writer/config.json for the writer-mode boundary'}:{level:"ok",label:`Mode: writer \u2014 edits limited to ${l}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let c=a.authoritativeSourceFiles??[];n.push(c.length>0?{level:"ok",label:`Sources: docs grounded in ${c.length} path(s) (${c.slice(0,3).join(", ")}${c.length>3?", \u2026":""})`}:{level:"warn",label:"Sources: not set \u2014 docs are grounded in the whole repo",fix:"Run: /scope to choose which files/folders the docs are written from"});let p=a.appType??BA(e);if(p){let K=a.appType?"from config":"auto-detected",ne=p==="web"||p==="cli";n.push({level:"ok",label:`Genre: ${p} (${K})${ne?` \u2192 ${HA(p)} 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 m=DA(),$=Object.keys(m.entries);$.length>0&&n.push({level:"ok",label:`Added deployments: ${$.join(", ")}`,detail:`Not shipped with d360-writer \u2014 read from ${jA()}`});for(let K of m.problems)n.push({level:"warn",label:`Added deployment refused: ${K}`,fix:"Run: d360-writer env list"});let w;try{w=NA(e)}catch(K){return n.push({level:"fail",label:`Profile config: ${K.message}`,fix:"Scaffold the profiles map: d360-writer init"}),n}let C=!1;try{n.push({level:"ok",label:`Profile: ${w.name} (${w.connection.name})${w.production?` ${Xe}`:""}`})}catch(K){C=!0;let ne=Ge(e);n.push({level:"fail",label:`Profile "${w.name}" cannot reach a Document360 deployment`,detail:K.message,fix:ne?.kind==="unshipped"?`To publish to a customer region instead, run ${ne.cmd}. To keep this deployment, add it on this machine: d360-writer env add <file.json>`:`Run: ${ne?.cmd??"/profile"}`})}let S=RA(w.name,w.project.projectId),T=SA(w.name).filter(K=>{let ne=jp(K);return!!ne&&ne!==w.project.projectId&&!(Ll(K)&&!K.refreshToken)}),R=w.project.projectName?`"${w.project.projectName}"`:"this project";C?n.push({level:"fail",label:"Document360: cannot sign in until this repo has a deployment it can reach",fix:"Fix the profile above first \u2014 signing in cannot change which deployment a profile names"}):S?Ll(S)&&!S.refreshToken?n.push({level:"fail",label:S.refreshRejectedAt?`Document360: session ended \u2014 Document360 refused to renew it (${new Date(S.refreshRejectedAt).toLocaleString()})`:"Document360: session expired (no refresh token)",fix:"/login"}):Ll(S)?n.push({level:"ok",label:"Document360: logged in (access token expired \u2014 refreshes automatically on the next call)"}):n.push({level:"ok",label:`Document360: logged in to ${R} (until ${new Date(S.expiresAt).toLocaleString()})`}):n.push(T.length>0?{level:"fail",label:`Document360: not signed in to ${R} \u2014 signed in to ${T.map(K=>K.projectName?`"${K.projectName}"`:(jp(K)??"").slice(0,8)+"\u2026").join(", ")} instead`,fix:`Run: /login and pick ${R} \u2014 each project needs its own sign-in, and both are then kept`}:{level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${w.name})`}),T.length>0&&n.push({level:"ok",label:`Other Document360 projects signed in on this machine: ${T.map(K=>K.projectName?`"${K.projectName}"`:(jp(K)??"").slice(0,8)+"\u2026").join(", ")} (kept \u2014 each repo uses its own)`}),n.push(w.project.workspaceId?{level:"ok",label:`Workspace: ${w.project.workspaceName??w.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let D=$u(e);if(D.length>1)for(let K of[...D].sort((ne,oe)=>Number(oe.active)-Number(ne.active))){let ne=[K.production?"production":null,K.internal?"internal":null].filter(Boolean).join(" \xB7 ");n.push({level:"ok",label:`${K.profile}${K.active?" (active)":""} \u2192 ${K.portalUrl||K.environment}${K.project?` \xB7 ${K.project}`:" \xB7 no project"} \xB7 ${K.tracked} tracked${K.signedIn?"":" \xB7 not signed in"}${ne?` \xB7 ${ne}`:""}`,...K.active?{detail:"/push and /publish act on this profile. Switch with /profile."}:{}})}let U=D.find(K=>K.active);U&&U.unpushed>0&&n.push({level:"warn",label:`${U.unpushed} local article${U.unpushed===1?"":"s"} ${U.unpushed===1?"has":"have"} never been saved to "${U.profile}"`,fix:"Run: /push --all"});for(let K of qm(e))n.push({level:"warn",label:`Profiles ${K.map(ne=>`"${ne}"`).join(" and ")} point at the same Document360 project`,fix:"They track one portal in separate map sections \u2014 keep one, or point one at a different project with /project"});let H=bA(e,w.name),J=xA(e,w.name);if(!H)n.push({level:"ok",label:`Category map: none yet for "${w.name}" (created on first /push)`});else if(J.length>0)for(let K of J)n.push({level:"fail",label:`Category map ${K.field} (${K.recorded}) \u2260 profile ${K.field} (${K.current})`,fix:"This repo\u2019s records belong to a different Document360 project \u2014 to publish somewhere new, connect it as its own profile: /profile"});else{let K=$A(e,w.name),ne=`${Object.keys(H.articles).length} articles, ${Object.keys(H.categories).length} categories`;K?K.unmapped>0?n.push({level:"warn",label:`Category map covers ${K.mappedArticles} of ${K.portalArticles} Document360 articles and ${K.mappedCategories} of ${K.portalCategories} categories`+(K.declined>0?` (${K.declined} declined)`:""),fix:`/pull imports the ${K.unmapped} ${K.unmapped===1?"article":"articles"} this repo has no folder for`}):n.push({level:"ok",label:`Category map: ${ne} \u2014 every Document360 article is tracked here`}):n.push({level:"ok",label:`Category map: ${ne} (not yet compared with Document360)`,fix:"/pull --status compares this repo with Document360"});let oe=vA(K);if(oe!==null&&oe>0){let ve=K?.dangling?.articles.length??0,ae=K?.dangling?.categories.length??0;n.push({level:"warn",label:`${oe} map ${oe===1?"entry points":"entries point"} at something Document360 no longer has`+(ve>0&&ae>0?` (${ve} articles, ${ae} categories)`:""),detail:(K?.dangling?.articles??[]).slice(0,3).join(", ")||void 0,fix:"/push saves them again for your readers, /untrack drops the ones you no longer want \u2014 /status lists them"})}for(let ve of K?.duplicateCategories??[])n.push({level:"warn",label:`Two Document360 categories named "${ve.name}" in the same place (${ve.ids.join(", ")})`,fix:"Merging or hiding one is your decision \u2014 /restructure moves articles; nothing here deletes"});for(let ve of K?.sameNameCategories??[])(K?.duplicateCategories??[]).some(ae=>ae.name.toLowerCase()===ve.name.toLowerCase())||n.push({level:"warn",label:`"${ve.name}" is a Document360 category in ${ve.entries.length} different places (${ve.entries.map(ae=>ae.id).join(", ")})`,fix:"Readers see them all. Choose which one they keep: /restructure moves articles, /retire hides a page this repo owns, /untrack disowns one that was never ours"})}n.push(yA(kk())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${kk()}`,fix:"Reinstall document360-writer (broken install)"});let G=tn(e);if(G.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${Be})`}):G.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${G.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)"}),S&&(!Ll(S)||S.refreshToken)&&!C){let K={profile:w.name,connection:w.connection,projectId:w.project.projectId,projectName:w.project.projectName};try{await kA(K);let oe=await wA(K,"/v3/projects");n.push({level:"ok",label:`API reachable (${w.connection.apiUrl}) \u2014 ${oe.length} project(s) visible`})}catch(oe){n.push({level:"fail",label:`API call failed: ${oe.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let ne=H?.projectId??w.project.projectId;if(ne&&w.project.workspaceId){try{let oe=await EA(K,ne,w.project.workspaceId);if(oe){let ve=(oe.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Your Document360 project: reachable on ${w.connection.name} (${oe.languages?.length??0} language${(oe.languages?.length??0)===1?"":"s"}) \xB7 version ${ve||"(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(oe){oe instanceof GA||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(oe.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${w.project.projectName??ne})`,fix:"Run /login and pick this repo's project \u2014 your token is scoped to another project"}):n.push({level:"warn",label:`Workspace sync manifest: probe failed (${oe.message.slice(0,80)})`})}try{let oe=await qA({cwd:e,profileName:w.name,dryRun:!0}),ve=oe.categoriesReordered+oe.articlesReordered;if(oe.skipped==="no category map")n.push({level:"ok",label:"Reading order: nothing to check yet (no articles published)"});else if(oe.skipped)n.push({level:"warn",label:`Reading order: can't be checked (${oe.skipped})`,fix:"Your article order on Document360 may not match your structure \u2014 /push syncs it once this resolves"});else if(oe.unverified)n.push({level:"warn",label:`Reading order: ${oe.unverified} of your articles aren't listed by Document360, so their order can't be set`,fix:"Usually means those articles are not live yet (the listing returns published articles). /publish takes them live, then /push re-syncs the order"});else if(ve>0){let ae=[oe.categoriesReordered>0?`${oe.categoriesReordered} categor${oe.categoriesReordered===1?"y":"ies"}`:"",oe.articlesReordered>0?`${oe.articlesReordered} article${oe.articlesReordered===1?"":"s"}`:""].filter(Boolean);n.push({level:"warn",label:`Reading order: ${ae.join(" + ")} out of order on Document360`,fix:"Run /push \u2014 it re-syncs the order from your NN- folder/file prefixes"})}else n.push({level:"ok",label:"Reading order: Document360 matches your structure"});if(oe.orphans?.length){let ae=oe.orphans;n.push({level:"warn",label:`${ae.length} article${ae.length===1?"":"s"} on Document360 ${ae.length===1?"is":"are"} not in your docs folder: ${ae.slice(0,3).map(pe=>pe.path).join(", ")}${ae.length>3?`, +${ae.length-3} more`:""}`,fix:"/retire <path> takes one off your readers \xB7 /pull <path> brings one back into your docs folder \u2014 until you choose, it stays live and d360-writer leaves it alone"})}}catch(oe){n.push({level:"warn",label:`Reading order: check failed (${oe.message.slice(0,80)})`})}}}return n}function $k(e){let t=[""];for(let r of e){let s=r.level==="ok"?Q("\u2713"):r.level==="warn"?W(Mo):L("\u2717"),i=(r.detail??"").split(`
|
|
307
|
-
`).filter(a=>a.trim());if(t.push(` ${s} ${r.label}${i.length===1?u(` \u2014 ${i[0]}`):""}`),i.length>1)for(let a of i)t.push(` ${u(a)}`);r.fix&&t.push(` ${u("fix:")} ${Z(r.fix)}`)}let n=e.filter(r=>r.level==="fail").length,o=e.filter(r=>r.level==="warn").length;return t.push(""),t.push(n===0?Q(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):L(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function di(e,t){console.log(u("Running checks\u2026"));for(let n of $k(await bk(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var _l=Tr(()=>{"use strict";Zn();un();ue();Lr()});import{createRequire as O6}from"node:module";import{Command as E6}from"commander";import{AUTH_MODES as N6}from"document360-engine";import{input as Tx}from"@inquirer/prompts";import{currentEnvironments as Ax,loginPkce as Ex,getAccessToken as Nx,toStoredTokens as Dx,clearTokens as jx,decodeJwtClaims as Vm,isExpired as Ix,loadTokens as vu,saveTokens as Lx,listStoredSessions as xu,tokensProjectId as Qn,rememberSessionProject as Km,resolveActiveProfile as Ms,setProfileProject as Ox,readProjectConfig as _x}from"document360-engine";ue();import{select as ex}from"@inquirer/prompts";import{resolveActiveProfile as Mm,setProfileProject as tx,resolveProjectId as nx,listWorkspaces as ox,ensureSeededContentSwept as rx,seededSweepLines as sx}from"document360-engine";async function Os(e,t){let n=Mm(e,t),o={profile:n.name,connection:n.connection,projectId:n.project.projectId,projectName:n.project.projectName},r=n.project.projectId??nx(o);return{workspaces:await ox(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var _m=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function gu(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 ma(e,t,n,o,r){tx(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function Fm(e,t,n){let o;try{o=await Os(e,n)}catch(s){return console.log(L(`Could not list workspaces: ${s.message}`)),1}let r=gu(o.workspaces,t);return r?(ma(e,o.profile,o.projectId,r.id,r.name),console.log(Q(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(L(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function Ar(e,t){let n;try{n=await Os(e,t)}catch(c){console.log(L(`Could not list workspaces: ${c.message}`));return}let{workspaces:o,projectId:r,profile:s,current:i}=n;if(o.length===0){console.log(u("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let c of o)console.log(` ${c.id===i?Z("\u25CF"):" "} ${_m(c)} ${u(c.id)}`);console.log(u("Run: d360-writer workspace use <name>"));return}let a=await ex({message:"Select the Document360 workspace for this repo:",choices:o.map(c=>({name:`${_m(c)}${c.id===i?" (current)":""}`,value:c.id}))}),l=o.find(c=>c.id===a);ma(e,s,r,a,l?.name),console.log(Q(`\u2713 Workspace set to "${l?.name??a}" for profile "${s}".`)),await ix(e,s,r,a)}async function ix(e,t,n,o){try{let r=Mm(e,t),s=await rx({profile:r.name,connection:r.connection,projectId:n,projectName:r.project.projectName},{cwd:e,profile:r.name,projectId:n,workspaceId:o});for(let i of sx(s))console.log(i)}catch{}}ue();import{select as ax}from"@inquirer/prompts";import{resolveActiveProfile as lx,setProfileProject as cx,listProjects as ux}from"document360-engine";async function Dn(e,t){let n=lx(e,t),o={profile:n.name,connection:n.connection};return{projects:await ux(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var Um=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function yu(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 ga(e,t,n,o){cx(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function Wm(e,t,n){let o;try{o=await Dn(e,n)}catch(s){return console.log(L(`Could not list projects: ${s.message}`)),1}let r=yu(o.projects,t);return r?(ga(e,o.profile,r.id,r.name),console.log(Q(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (d360-writer workspace).`)),0):(console.log(L(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function ya(e,t){let n;try{n=await Dn(e,t)}catch(l){console.log(L(`Could not list projects: ${l.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(u("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let l of o)console.log(` ${l.id===s?Z("\u25CF"):" "} ${Um(l)} ${u(l.id)}`);console.log(u("Run: d360-writer project use <name>"));return}let i=await ax({message:"Select the Document360 project for this repo:",choices:o.map(l=>({name:`${Um(l)}${l.id===s?" (current)":""}`,value:l.id}))}),a=o.find(l=>l.id===i);ga(e,r,i,a?.name),console.log(Q(`\u2713 Project set to "${a?.name??i}" for profile "${r}". Next: pick a workspace.`))}ue();import dx from"picocolors";function px(e=process.env){return e.FORCE_HYPERLINK==="0"||!dx.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 hx(e,t=e,n){return px(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var fx=/https?:\/\/[^\s\x1b]+/g;function _s(e,t){return e.replace(fx,n=>hx(n,n,t))}un();function Ym(e){return{...Vm(e.idToken)??{},...Vm(e.accessToken)??{}}}function wa(e){let t=Ym(e),n=t.email??t.preferred_username??t.sub??"unknown",o=Qn(e),r=e.projectName?` \xB7 project "${e.projectName}"`:o?` \xB7 project ${o}`:"";return`${n}${r}`}async function Ru(e,t,n){n&&Km(e,t,n);try{let{projects:o}=await Dn(process.cwd(),e);for(let r of xu(e)){let s=Qn(r);s&&Km(e,s,o.find(i=>i.id===s)?.name)}}catch{}}function Mx(e,t,n){let o=Qn(e);if(!o||!t||o===t)return null;let r=n?`"${n}"`:t.slice(0,8)+"\u2026";return`\u26A0 You signed in to project ${e.projectName?`"${e.projectName}"`:o.slice(0,8)+"\u2026"}, but this repo's docs live in ${r}. Run /login again and pick ${r} (or /project to point this repo somewhere else).`}async function ka(e){let t=Ms(process.cwd(),e.profile);if(!t.configured&&!e.profile){console.error(L("This repo is not set up yet, so there is no Document360 deployment to sign in to.")),console.error(`Run ${Z("/init")} to pick your region (or ${Z("d360-writer init")}), then sign in.`),console.error(u(`Signing in to one deployment directly: d360-writer login --profile <${Ax().join("|")}>`)),process.exitCode=2;return}let n=t.connection;console.log(u(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})`)+(t.production?W(` ${Xe}`):""));let o=Ge(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 Ex(n,{manual:e.manual,promptForRedirect:p=>Tx({message:p})},p=>console.log(_s(p))),s=Dx(t.name,r);Lx(s),await Su(s,t.name,p=>console.log(u(p)));let i=Qn(s),a=Ms(process.cwd(),e.profile).project;i&&await Ru(t.name,i,a.projectId===i?a.projectName:void 0);let l=vu(t.name,i??void 0)??s;console.log(""),console.log(Q(`\u2713 Logged in to "${t.name}" as ${wa(l)}`));let c=Mx(l,a.projectId,a.projectName);if(c&&console.log(W(c)),console.log(u(` access token expires: ${s.expiresAt}`)),console.log(u(` refresh token: ${s.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{_x(process.cwd())?.profiles?.[t.name]&&(console.log(""),await Ar(process.cwd(),t.name))}catch{}}async function Su(e,t,n){let r=Ym(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Ms(process.cwd(),t).project.projectId)return;let i;try{let{projects:a}=await Dn(process.cwd(),t);i=a.find(l=>l.id===r)?.name}catch{}Ox(process.cwd(),t,{projectId:r,projectName:i}),n(` Project "${i??r}" written to profile "${t}".`)}catch{}}async function zm(e){let t=Ms(process.cwd(),e.profile),n=t.connection,o=vu(t.name,t.project.projectId);if(!o){console.log(L(`Not logged in to Document360 (profile "${t.name}").`));let r=xu(t.name).filter(s=>Qn(s)&&Qn(s)!==t.project.projectId);r.length>0&&console.log(u(`This repo's project needs its own sign-in. Signed in on this machine: ${r.map(s=>s.projectName??Qn(s)).join(", ")}`)),console.log(u(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${Z(t.name)}${t.production?W(` ${Xe}`):""}: ${wa(o)}`),Ix(o))if(o.refreshToken)try{await Nx({profile:t.name,connection:n,projectId:t.project.projectId,projectName:t.project.projectName});let r=vu(t.name,t.project.projectId);console.log(Q(`\u2713 Session refreshed${r?` \u2014 expires ${r.expiresAt}`:""}`))}catch(r){console.log(W(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(u(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(W("Session expired (no refresh token).")),console.log(u(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(u(` expires: ${o.expiresAt}`))}async function Xm(e){let t=Ms(process.cwd(),e.profile),n=e.allProjects?void 0:t.project.projectId,o=t.project.projectName?`"${t.project.projectName}"`:`profile "${t.name}"`;if(jx(t.name,n)){console.log(Q(e.allProjects?`\u2713 Logged out of every Document360 project for profile "${t.name}".`:`\u2713 Logged out of ${o}.`));let r=xu(t.name).filter(s=>Qn(s)).length;r>0&&console.log(u(`Still signed in to ${r} other project${r===1?"":"s"} on this machine.`))}else console.log(u(`No Document360 session for ${o} \u2014 nothing to do.`))}ue();import{readProjectConfig as Qm,writeProjectConfig as Fx,resolveActiveProfile as Ux,loadTokens as Wx,isExpired as Bx,environmentIsProduction as Hx,isKnownEnvironment as Gx}from"document360-engine";function Jm(e){return e.production??Hx(e.connection?.environment)}function ba(e){let t=Qm(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(L("No profiles in .d360-writer/config.json. Run: d360-writer init")),process.exitCode=1;return}console.log("");let n=new Set;for(let[o,r]of Object.entries(t.profiles)){let s=o===t.defaultProfile?Z(" (active)"):"",i=Jm(r)?W(` ${Xe}`):"",a=r.connection.environment??"(inline)";a!=="(inline)"&&!Gx(a)&&n.add(o);let l=Wx(o,r.project?.projectId),c=l?Bx(l)&&!l.refreshToken?W("expired"):u("logged in"):u("not logged in"),p=n.has(o)?W("cannot be reached"):c;console.log(` ${Z(o)}${s} \u2192 ${a}${i} [${p}]`)}if(console.log(""),console.log(u("Switch with: d360-writer profile use <name>")),n.size>0){console.log("");let o=[...n].map(r=>`"${r}"`).join(", ");console.log(W(te(Mo,`${n.size===1?"Profile":"Profiles"} ${o} cannot reach a Document360 deployment.`))),console.log(u(" Point this repo at a customer region: d360-writer profile add <name> <environment>")),console.log(u(" Add a deployment this build does not ship: d360-writer env add <file.json>"))}console.log("")}function $a(e,t){let n=Qm(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(L(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,Fx(n,e);let o=Jm(n.profiles[t])?W(` ${Xe}`):"";console.log(Q(`\u2713 Default profile is now "${t}"${o}`))}function va(e,t){try{let n=Ux(e,t);console.log(""),console.log(`Profile ${Z(n.name)}${n.production?W(` ${Xe}`):""}`),console.log(u(` api: ${n.connection.apiUrl}`)),console.log(u(` identity: ${n.connection.authorizationUrl}`)),console.log(u(` clientId: ${n.connection.clientId}`)),console.log(u(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(u(` project: ${n.project.projectId??"(set at login)"}`)),console.log(u(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(L(n.message)),process.exitCode=1}}import{currentEnvironments as qx,environmentIsProduction as Vx,isKnownEnvironment as Kx,readProjectConfig as Yx,resolveEnvironment as zx,writeProjectConfig as Xx}from"document360-engine";ue();function Fs(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=Yx(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 Kx(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r}}},Xx(o,e),null):[`Unknown environment "${r}". Known: ${qx().join(", ")}`,"Add a deployment this build does not ship: d360-writer env add <file.json>","Or give this profile explicit URLs in .d360-writer/config.json."].join(`
|
|
308
|
-
`)}function
|
|
309
|
-
`).map(l=>L(` ${l}`))]}}let r=Object.keys(o);if(r.length===0)return{ok:!1,lines:[L(`${n.where} defines no deployments.`),u("The document is a JSON object of environment name \u2192 connection fields.")]};let s=[];for(let a of r){let l=
|
|
310
|
-
`).map(i=>L(` ${i}`))]}}if(!n){let s=Object.keys(
|
|
311
|
-
`),process.exit(m)}import{createInterface as
|
|
312
|
-
`)}var St=[{key:"start",label:"Getting Started",rows:[{t:"text",s:"D360-Writer reads your codebase and writes your user documentation."},{t:"gap"},{t:"text",s:"It publishes to Document360 when you are ready."},{t:"gap"},{t:"text",s:"It needs Claude access \u2014 a subscription, or an ANTHROPIC_API_KEY."},{t:"gap"},{t:"sub",s:"Quick start"},{t:"step",n:1,s:"Run /init. Pick the Document360 deployment you publish to, sign in, choose your project."},{t:"step",n:2,s:"Paste the prompt it prints into your coding agent, and let it finish."},{t:"step",n:3,s:"Run /doctor to confirm every check is green."},{t:"step",n:4,s:'Type "write the docs for this repository".'},{t:"gap"},{t:"dim",s:"Claude Code, Codex and Cursor all work. /devhints re-shows that prompt."},{t:"dim",s:"That's it \u2014 D360-Writer drafts your docs without you writing a line."},{t:"gap"},{t:"sub",s:"Tips"},{t:"text",s:"Just talk to it. Anything not starting with / goes to the agent."},{t:"gap"},{t:"dim",s:"/ browse commands \xB7 \u2191 recall history \xB7 tab run the suggestion"},{t:"dim",s:"1-9 pick from a list \xB7 ctrl+y copy whatever was offered"},{t:"dim",s:"esc interrupt a run \xB7 ctrl+c twice exit"},{t:"dim",s:"shift+tab switch auto / manual \u2014 see /auto"}]},{key:"agentic",label:"Agentic",rows:[{t:"text",s:"Agentic mode is for products built with an AI coding agent."},{t:"gap"},{t:"text",s:"Your coding agent ships features and leaves notes."},{t:"text",s:"D360-Writer turns those notes into user documentation."},{t:"gap"},{t:"dim",s:"Think of it as a Technical Writer dedicated to your project."},{t:"gap"},{t:"sub",s:"Auto or manual"},{t:"gap"},{t:"text",s:"In MANUAL mode I work out the next step and offer it. You press tab."},{t:"gap"},{t:"text",s:"In AUTO mode I run that step myself, then the one after it."},{t:"gap"},{t:"dim",s:" write \u2192 review \u2192 check the style \u2192 save \u2192 go live"},{t:"gap"},{t:"text",s:"Start a build, come back to a finished knowledge base."},{t:"gap"},{t:"cmd",name:"/auto on",s:"Let me run my own next step."},{t:"cmd",name:"/auto --budget",s:"Cap what one run may spend. The standard cap is $200."},{t:"gap"},{t:"dim",s:" shift+tab switches mode \xB7 esc stops a run"},{t:"dim",s:" Nothing already written, saved or published is undone."},{t:"gap"},{t:"text",s:"Auto changes who presses the key. It does not change what is checked."},{t:"gap"},{t:"text",s:"Every gate still runs."},{t:"text",s:"An article that fails one stays a draft, and the report names it."},{t:"gap"},{t:"text",s:"Screenshots are never automatic \u2014 they need your app on screen."},{t:"gap"},{t:"sub",s:"Every few days"},{t:"cmd",name:"/catch-up",s:"Write up everything pending. It all lands as a draft."},{t:"dim",s:" A note whose code your builder has not committed waits, and they get asked."},{t:"dim",s:" --include-unfinished write those pages anyway"},{t:"cmd",name:"/review --fix",s:"A senior editor reads every article and fixes it."},{t:"cmd",name:"/push --all",s:"Save the reviewed articles to Document360, as drafts."},{t:"cmd",name:"/publish --all",s:"Take those drafts live. It lists them and asks first."},{t:"gap"},{t:"dim",s:" An editorial read is required before anything goes live."},{t:"dim",s:" /review --blocked only the articles publishing is stuck on"},{t:"dim",s:" /review --stale only the ones this editor has not read yet"},{t:"gap"},{t:"sub",s:"Whenever you need"},{t:"cmd",name:"/discover",s:"Interview your builder. Pins a product brief for the docs."},{t:"cmd",name:"/audit",s:"What changed in the code, what is missing from the docs."},{t:"cmd",name:"/audit --decline <path>",s:"That folder or file needs no article. Stops it being reported. Bare: lists what you could decline."},{t:"cmd",name:"/pull",s:"Bring down portal edits and any new portal articles."},{t:"cmd",name:"/resolve",s:"Settle a conflict: keep yours, take the portal, or skip."},{t:"cmd",name:"/comments",s:"Reviewer comments on your articles. Read one, answer it."},{t:"cmd",name:"/inbox",s:"Act on your coding agent's messages."},{t:"cmd",name:"/ask",s:"Ask your developers what the code cannot answer."},{t:"gap"},{t:"dim",s:" An answer fixes the article, saves the draft and replies in the thread."}]},{key:"assistant",label:"Assistant",rows:[{t:"text",s:"D360-Writer is your writing assistant."},{t:"gap"},{t:"text",s:"It does the writing. You decide what gets written, and when."},{t:"gap"},{t:"text",s:"Best for large monorepos: point it at one feature or one set of folders."},{t:"gap"},{t:"sub",s:"Just ask"},{t:"good",s:'"Write the docs for the Multiple JWT feature we shipped last release."'},{t:"gap"},{t:"sub",s:"Or drive it yourself"},{t:"cmd",name:"/scope",s:"Focus on specific source folders."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from its PRDs and the code."},{t:"cmd",name:"/write",s:"Write the planned articles."},{t:"cmd",name:"/push",s:"Save them to Document360 as drafts."},{t:"cmd",name:"/publish",s:"Take the drafts live to your readers."},{t:"cmd",name:"/status",s:"What stands between your work and your readers. Free."},{t:"gap"},{t:"dim",s:" /write --preview shows the plan and the cost first."},{t:"dim",s:" /push --preview <path> shows exactly what Document360 would receive."},{t:"gap"},{t:"sub",s:"One place for what repeats"},{t:"gap"},{t:"text",s:"A variable holds a value \u2014 your product name, a URL \u2014 in one place."},{t:"text",s:"Change it there and every article changes."},{t:"gap"},{t:"text",s:"A snippet does the same for a whole block, like who to contact."},{t:"gap"},{t:"text",s:"A term is defined once, and every article is checked for explaining it."},{t:"gap"},{t:"cmd",name:"/reuse",s:"What your project already keeps on Document360."},{t:"cmd",name:"/reuse pull",s:"Refresh that list from Document360."},{t:"cmd",name:"/reuse add",s:'Create one there: /reuse add variable <name> "<value>".'},{t:"cmd",name:"/reuse audit",s:"Read every article and find what belongs in one place."},{t:"cmd",name:"/terms",s:"Is the same thing called the same name everywhere?"},{t:"cmd",name:"/eval",s:"How does the whole knowledge base score? Free."},{t:"gap"},{t:"dim",s:" Reading is free. Nothing is created until you pick it."},{t:"gap"},{t:"sub",s:"Taking a page back"},{t:"cmd",name:"/retire <path>",s:"Stop showing an article to readers. /push puts it back."},{t:"cmd",name:"/untrack <path>",s:"Disown an imported page that is not one of your docs."},{t:"gap"},{t:"dim",s:" Neither deletes anything. History and reviewer comments stay."}]},{key:"shots",label:"Screenshots",rows:[{t:"text",s:"Documenting a web app? D360-Writer marks where an image helps."},{t:"gap"},{t:"text",s:"The companion CLI d360-capture turns those marks into real,"},{t:"text",s:"annotated screenshots by driving your app in a browser."},{t:"gap"},{t:"sub",s:"Flow"},{t:"step",n:1,s:"Write your docs as usual. Placeholders go in where visuals help."},{t:"step",n:2,s:"Run /screenshot author --all to write the capture specs."},{t:"step",n:3,s:"Stage what the checklist asks for, then /screenshot capture."},{t:"step",n:4,s:"The callouts are drawn on straight after. No browser needed."},{t:"step",n:5,s:"Each finished picture is checked, then marked \u2714 verified."},{t:"step",n:6,s:"Run /push --screenshots so the images embed on Document360."},{t:"gap"},{t:"sub",s:"One command family"},{t:"cmd",name:"/screenshot",s:"Pick what to do next."},{t:"cmd",name:"/screenshot author",s:"Write the capture specs."},{t:"cmd",name:"/screenshot capture",s:"Take the shots."},{t:"cmd",name:"/screenshot annotate",s:"Draw the callouts on shots already taken."},{t:"cmd",name:"/screenshot verify",s:"Judge the finished pictures and mark them verified."},{t:"cmd",name:"/screenshot checklist",s:"What to stage, and the test-ids to ask your dev for."},{t:"cmd",name:"/screenshot list",s:"Progress by chapter, and the worklist."},{t:"gap"},{t:"dim",s:" Each takes an <id>, a path, or --all."},{t:"dim",s:" capture --failed re-runs what did not work \xB7 --blocked what waited on data"},{t:"dim",s:" annotate --force re-draws after a wording or style change"},{t:"gap"},{t:"sub",s:"What each state means"},{t:"text",s:"\u2714 verified finished \u2014 this is the finish line"},{t:"text",s:"\u25C8 to verify the picture is done, waiting to be looked at"},{t:"text",s:"\u25CF to annotate shot taken, callouts not drawn on yet"},{t:"text",s:"\u25D0 ready the spec is written, the shot not taken"},{t:"text",s:"\u2691 rejected the shot ran but the picture is wrong"},{t:"text",s:"\u2298 blocked your app lacked the data the shot needs"},{t:"text",s:"\u2717 broken the spec itself is out of date"},{t:"text",s:"\u25CB to-spec no spec written yet"},{t:"gap"},{t:"dim",s:" rejected \u2014 the spec is usually fixed for you, then capture --failed re-shoots"},{t:"dim",s:" blocked \u2014 /screenshot list groups every blocker into a few things to stage"},{t:"dim",s:" broken \u2014 re-author with /screenshot <id>; a re-capture would fail the same way"},{t:"gap"},{t:"dim",s:"One-time setup in your app repo:"},{t:"dim",s:" npm i -g document360-capture \xB7 d360-capture init \xB7 d360-capture auth"}]},{key:"cmds",label:"Commands",rows:[{t:"dim",s:"Every command, one line each \u2014 type / for the full usage."},{t:"dim",s:"The tabs above teach the ones worth more than a line."},{t:"gap"},{t:"sub",s:"Getting started"},{t:"cmd",name:"/init",s:"Set up Document360 and the coding-agent hand-off."},{t:"cmd",name:"/login",s:"Sign in \u2014 one sign-in per project, all kept."},{t:"cmd",name:"/project",s:"Choose the Document360 project."},{t:"cmd",name:"/workspace",s:"Switch the workspace."},{t:"cmd",name:"/scope",s:"Choose which repo folders back the docs."},{t:"cmd",name:"/genre",s:"What kind of product this is \u2014 picks the writing guide."},{t:"cmd",name:"/devhints",s:"Re-show the prompt to paste into your coding agent."},{t:"cmd",name:"/mcp",s:"Connect MCP servers (Notion, Linear, \u2026)."},{t:"gap"},{t:"sub",s:"Agentic \u2014 keep docs in sync"},{t:"cmd",name:"/roadmap",s:"The docs campaign: progress and the next step."},{t:"cmd",name:"/catch-up",s:"Do all pending work \u2192 drafts. --push also saves them."},{t:"cmd",name:"/auto",s:"Run the next step myself instead of waiting for you."},{t:"cmd",name:"/audit",s:"What changed in the code, what's missing from the docs."},{t:"cmd",name:"/inbox",s:"Act on your coding agent's messages."},{t:"cmd",name:"/ask",s:"Ask your developers what the code cannot answer."},{t:"cmd",name:"/share",s:"Get your builder's latest, send yours (automatic)."},{t:"gap"},{t:"sub",s:"Assistant \u2014 directed writing"},{t:"cmd",name:"/discover",s:"Interview your builder \u2192 a product brief for the docs."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from its PRDs and the code."},{t:"cmd",name:"/write",s:"Write the planned articles. --preview costs first."},{t:"cmd",name:"/preview",s:"Render an article locally."},{t:"cmd",name:"/reorder",s:"Put a category's articles in the best reading order."},{t:"cmd",name:"/restructure",s:"Move an article to another category, split one, merge two, rename one."},{t:"cmd",name:"/structure",s:"The reading order, as it will appear on Document360."},{t:"gap"},{t:"sub",s:"Quality \u2014 before you publish"},{t:"cmd",name:"/style-guide",s:"Choose the writing rules your docs are held to."},{t:"cmd",name:"/lint",s:"The machine pass over those rules. Free. --fix corrects."},{t:"cmd",name:"/review",s:"The editor pass. Required before anything goes live."},{t:"cmd",name:"/terms",s:"Is the same thing called the same name everywhere? Free."},{t:"cmd",name:"/eval",s:"Score the whole set: links, shape, naming. Free."},{t:"cmd",name:"/reuse",s:"The terms, values and blocks kept on Document360."},{t:"gap"},{t:"sub",s:"Publish & sync"},{t:"cmd",name:"/status",s:"What stands between your work and your readers. Free."},{t:"cmd",name:"/push",s:"Save your articles to Document360 as drafts."},{t:"cmd",name:"/publish",s:"Take the drafts live to your readers. Asks first."},{t:"cmd",name:"/pull",s:"Portal edits + new portal articles. --status: report only."},{t:"cmd",name:"/resolve",s:"Settle a local\u2194portal conflict: keep, take, or skip."},{t:"cmd",name:"/comments",s:"Reviewer comments on your articles \u2014 read and answer."},{t:"cmd",name:"/retire",s:"Take an article off your readers. Nothing is deleted."},{t:"cmd",name:"/untrack",s:"Disown an imported page that is not one of your docs."},{t:"gap"},{t:"sub",s:"Screenshots"},{t:"cmd",name:"/screenshot",s:"The screenshot pipeline. Bare: pick what to do next."},{t:"dim",s:" author \xB7 capture \xB7 annotate \xB7 verify \xB7 checklist \xB7 list"},{t:"gap"},{t:"sub",s:"Setup & health"},{t:"cmd",name:"/model",s:"Set the Claude model."},{t:"cmd",name:"/verbose",s:"Raw transcript: every tool call, path and result."},{t:"cmd",name:"/profile",s:"Where this repo publishes. Switch, or connect another environment."},{t:"cmd",name:"/allow-prod",s:"Authorize taking articles live on a production profile."},{t:"cmd",name:"/env",s:"The deployments this machine can reach. Add one from a JSON file."},{t:"cmd",name:"/doctor",s:"Health check \u2014 including a real agent turn."},{t:"cmd",name:"/logs",s:"The last problem, in full. \u2303y copies it."},{t:"cmd",name:"/update",s:"Update D360-Writer, and d360-capture if installed."},{t:"cmd",name:"/feedback",s:"Copy this repo's open feedback, to relay to the team."},{t:"cmd",name:"/copy",s:"Copy what is waiting to be copied. \u2303y does the same."},{t:"cmd",name:"/logout",s:"Sign out of this project. --all-projects: all of them."},{t:"cmd",name:"/reset",s:"Delete all D360-Writer files (confirms first)."},{t:"gap"},{t:"sub",s:"Session"},{t:"cmd",name:"/resume",s:"Resume a saved session."},{t:"cmd",name:"/rename",s:"Name the session."},{t:"cmd",name:"/clear",s:"Clear the screen and reset the conversation."},{t:"cmd",name:"/help",s:"Show this help."},{t:"cmd",name:"/exit",s:"Quit."}]}],yg=24;function Au(e){let t=e.filter(n=>n.t==="cmd").map(n=>n.name.length);return t.length===0?yg:Math.min(yg,Math.max(...t))}var wg=2;function Ta(e,t,n,o){let r=" ".repeat(2+n+wg),s=Math.max(24,o-r.length-2),i=dn(t,s);return e.length>n?{nameCell:e,descLines:i,indent:r,nameOwnLine:!0}:{nameCell:e.padEnd(n+wg-1),descLines:i,indent:r,nameOwnLine:!1}}function SR(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=Ta(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(`
|
|
313
|
-
`)}case"gap":return""}}function
|
|
306
|
+
`)?"":i;Py(t,`${o}${a}${s.join(i)}${i}`,"utf8")}async function bd(){let e=process.cwd(),t=Dy(e);if(Kr(t)&&!await nC({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(u("init canceled.")),{kind:"continue"};let n=Oy(e)??Ty(e),o=await ol({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await ol({message:`Capture directory (where ${uC} .spec.ts files live):`,default:Iy}),s=await ol({message:"Screenshot output directory:",default:Ly}),i=oo().filter(w=>!w.retired),a=Math.max(...i.map(w=>w.portalUrl.length))+3,l=await oC({message:"Which Document360 deployment do these docs publish to?",choices:i.map(w=>({name:`${w.name.padEnd(16)}${w.portalUrl.padEnd(a)}${w.note?`(${w.note})`:""}`.trimEnd(),value:w.name}))}),c=await ol({message:"Name for this connection profile:",default:l}),p={projectId:o,docsDir:jy,captureDir:r,outputDir:s,profiles:{[c]:{connection:{environment:l}}},defaultProfile:c,authoritativeSourceFiles:_y(e)},m=sC(e);m?.terminologyGlossary&&(p.terminologyGlossary=m.terminologyGlossary),Ny(p,e),kd(e);let $=qr(e);console.log(""),console.log(Q(`\u2713 Wrote ${t}`)),aC(l)&&(console.log(""),console.log(`\u26A0 ${l} is a live deployment \u2014 ${lC(l).portalUrl}`),console.log(u(" Drafts save freely. Taking articles live needs --yes, or /allow-prod in the app."))),console.log(""),console.log(`Next: ${Z(`${cC} login --profile ${c}`)} ${u("(sign in; project & workspace auto-selected)")}`),console.log("");for(let w of Vr($))console.log(w);return console.log(""),console.log(`${u("Then ask:")} ${Z('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function Oy(e){let t=rl(e,"package.json");if(!Kr(t))return null;try{return JSON.parse(Ey(t,"utf8")).name??null}catch{return null}}function _y(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Kr(rl(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=rl(e,n);Kr(o)&&!dC(o)&&t.push(n)}return t}function dC(e){try{return rC(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}var Ay,sl=Fr(()=>{"use strict";ae();mn();io();Ay=[".sessions/","cache/"]});import{createRequire as AC}from"node:module";import{existsSync as TC,readFileSync as EC}from"node:fs";import{dirname as Yy,join as zy}from"node:path";import{CAPTURE_HELPERS_SPECIFIER as NC,CAPTURE_PACKAGE as DC}from"document360-engine";function Nt(){let e;try{e=jC.resolve(NC)}catch{return null}let t=Yy(e);for(let n=0;n<5&&!TC(zy(t,"package.json"));n++)t=Yy(t);try{let n=JSON.parse(EC(zy(t,"package.json"),"utf8"));return n.name===DC&&n.version?n.version:null}catch{return null}}var jC,Yr=Fr(()=>{"use strict";jC=AC(import.meta.url)});var $b={};Rg($b,{doctorCommand:()=>Ti,renderDoctorChecks:()=>bb,runDoctorChecks:()=>kb});import{existsSync as YE}from"node:fs";import{d360GetAll as zE,getAccessToken as XE,isExpired as ic,loadProfileMap as QE,loadCoverage as JE,danglingCount as ZE,profileIdentityDrift as eN,loadTokens as tN,listStoredSessions as nN,tokensProjectId as wh,packageSkillsDir as yb,ENGINE_VERSION as oN,projectConfigPath as rN,readProjectConfig as sN,DEFAULT_DOCS_DIR as iN,fetchManifestSummary as aN,resolveActiveProfile as lN,loadAddedEnvironments as cN,addedEnvironmentsPath as uN,classifyClaudeAuth as dN,resolveAuthOrigin as pN,authOriginLine as hN,authOriginFix as fN,CLAUDE_CODE_SETUP_HINT as ac,resolveModelSetting as mN,probeModel as gN,probeAgentTurn as yN,stderrHeadline as wN,detectAppType as kN,playbookSkillName as bN,D360AuthError as $N,applyStructureOrder as vN,PRODUCT_NAME as kh,WRITER_COMMAND as Ai,WRITER_PACKAGE as xN,WRITER_DIRNAME as wb}from"document360-engine";async function kb(e,t){let n=[],o=Nt();n.push({level:"ok",label:`${kh} ${t?`v${t}`:"(version unknown)"} \xB7 engine v${oN}${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=dN();if(s.state==="ready"){let K=pN(),ne=fN(K);n.push({level:ne?"warn":"ok",label:`Claude auth: ${hN(K).replace(/^Claude: /,"")}`,...ne?{fix:ne}:{}})}else s.state==="maybe"?n.push({level:"warn",label:"Claude: no Claude Code login found (may be in the macOS Keychain)",fix:`If a docs turn ends with no output, sign in to Claude Code. ${ac}`}):n.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:ac});let i=mN(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 K=await gN(e,i.model??void 0);if(K.ok){n.push({level:"ok",label:`Model reachable \u2014 replied in ${(K.latencyMs/1e3).toFixed(1)}s`});let ne=await yN(e,i.model??void 0);if(ne.ok)n.push({level:"ok",label:`Agent turn works \u2014 ran with your skills and tools in ${(ne.latencyMs/1e3).toFixed(1)}s`});else{let oe=wN(ne.stderr),Re=/auth|sign.?in|login|credential|token|401|expired/i.test(`${ne.error??""} ${ne.stderr??""}`);if(n.push({level:"fail",label:ne.timedOut?"Agent turn never finished \u2014 the model answers, but a real turn with your skills and tools hangs":Re?"Agent turn failed \u2014 your Claude sign-in has expired, so every /write, /review and /catch-up will do nothing":`Agent turn produced nothing \u2014 the model answers, but a real turn with your skills and tools ${ne.producedNothing?"ends instantly with no output":`fails: ${ne.error}`}`,fix:(oe?`Claude Code said: "${oe}". `:"")+(Re?`Sign in again, then re-run /doctor. ${ac}`:"This is the failure behind an empty /write, /review or /catch-up. Run /logs for the whole thing \u2014 it offers to copy it so you can send it to the team.")}),Re){let le=n.find(he=>he.label.startsWith("Claude auth:"));le&&(le.level="warn",le.label="Claude auth: a sign-in exists on this machine, but it is no longer valid",le.fix=`Sign in again. ${ac}`)}}}else K.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 ${K.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=sN(e);if(!a)return n.push({level:"fail",label:`No ${rN(e)}`,fix:`Run: /init (or ${Ai} init)`}),n;n.push({level:"ok",label:`Project config: ${a.projectId}`});let l=(a.docsDir??iN).replace(/\/+$/,"");n.push(a.mode==="engineer"?{level:"warn",label:"Mode: engineer \u2014 agent may modify any source file (dogfooding)",fix:`Remove "mode" from ${wb}/config.json for the writer-mode boundary`}:{level:"ok",label:`Mode: writer \u2014 edits limited to ${l}/ and ${wb}/ (docs, capture specs, config); product source is read-only`});let c=a.authoritativeSourceFiles??[];n.push(c.length>0?{level:"ok",label:`Sources: docs grounded in ${c.length} path(s) (${c.slice(0,3).join(", ")}${c.length>3?", \u2026":""})`}:{level:"warn",label:"Sources: not set \u2014 docs are grounded in the whole repo",fix:"Run: /scope to choose which files/folders the docs are written from"});let p=a.appType??kN(e);if(p){let K=a.appType?"from config":"auto-detected",ne=p==="web"||p==="cli";n.push({level:"ok",label:`Genre: ${p} (${K})${ne?` \u2192 ${bN(p)} 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 m=cN(),$=Object.keys(m.entries);$.length>0&&n.push({level:"ok",label:`Added deployments: ${$.join(", ")}`,detail:`Not shipped with ${kh} \u2014 read from ${uN()}`});for(let K of m.problems)n.push({level:"warn",label:`Added deployment refused: ${K}`,fix:`Run: ${Ai} env list`});let w;try{w=lN(e)}catch(K){return n.push({level:"fail",label:`Profile config: ${K.message}`,fix:`Scaffold the profiles map: ${Ai} init`}),n}let C=!1;try{n.push({level:"ok",label:`Profile: ${w.name} (${w.connection.name})${w.production?` ${Je}`:""}`})}catch(K){C=!0;let ne=Ve(e);n.push({level:"fail",label:`Profile "${w.name}" cannot reach a Document360 deployment`,detail:K.message,fix:ne?.kind==="unshipped"?`To publish to a customer region instead, run ${ne.cmd}. To keep this deployment, add it on this machine: ${Ai} env add <file.json>`:`Run: ${ne?.cmd??"/profile"}`})}let S=tN(w.name,w.project.projectId),A=nN(w.name).filter(K=>{let ne=wh(K);return!!ne&&ne!==w.project.projectId&&!(ic(K)&&!K.refreshToken)}),R=w.project.projectName?`"${w.project.projectName}"`:"this project";C?n.push({level:"fail",label:"Document360: cannot sign in until this repo has a deployment it can reach",fix:"Fix the profile above first \u2014 signing in cannot change which deployment a profile names"}):S?ic(S)&&!S.refreshToken?n.push({level:"fail",label:S.refreshRejectedAt?`Document360: session ended \u2014 Document360 refused to renew it (${new Date(S.refreshRejectedAt).toLocaleString()})`:"Document360: session expired (no refresh token)",fix:"/login"}):ic(S)?n.push({level:"ok",label:"Document360: logged in (access token expired \u2014 refreshes automatically on the next call)"}):n.push({level:"ok",label:`Document360: logged in to ${R} (until ${new Date(S.expiresAt).toLocaleString()})`}):n.push(A.length>0?{level:"fail",label:`Document360: not signed in to ${R} \u2014 signed in to ${A.map(K=>K.projectName?`"${K.projectName}"`:(wh(K)??"").slice(0,8)+"\u2026").join(", ")} instead`,fix:`Run: /login and pick ${R} \u2014 each project needs its own sign-in, and both are then kept`}:{level:"fail",label:"Document360: not logged in",fix:`Run: /login (or ${Ai} login --profile ${w.name})`}),A.length>0&&n.push({level:"ok",label:`Other Document360 projects signed in on this machine: ${A.map(K=>K.projectName?`"${K.projectName}"`:(wh(K)??"").slice(0,8)+"\u2026").join(", ")} (kept \u2014 each repo uses its own)`}),n.push(w.project.workspaceId?{level:"ok",label:`Workspace: ${w.project.workspaceName??w.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let D=ed(e);if(D.length>1)for(let K of[...D].sort((ne,oe)=>Number(oe.active)-Number(ne.active))){let ne=[K.production?"production":null,K.internal?"internal":null].filter(Boolean).join(" \xB7 ");n.push({level:"ok",label:`${K.profile}${K.active?" (active)":""} \u2192 ${K.portalUrl||K.environment}${K.project?` \xB7 ${K.project}`:" \xB7 no project"} \xB7 ${K.tracked} tracked${K.signedIn?"":" \xB7 not signed in"}${ne?` \xB7 ${ne}`:""}`,...K.active?{detail:"/push and /publish act on this profile. Switch with /profile."}:{}})}let W=D.find(K=>K.active);W&&W.unpushed>0&&n.push({level:"warn",label:`${W.unpushed} local article${W.unpushed===1?"":"s"} ${W.unpushed===1?"has":"have"} never been saved to "${W.profile}"`,fix:"Run: /push --all"});for(let K of Lg(e))n.push({level:"warn",label:`Profiles ${K.map(ne=>`"${ne}"`).join(" and ")} point at the same Document360 project`,fix:"They track one portal in separate map sections \u2014 keep one, or point one at a different project with /project"});let H=QE(e,w.name),J=eN(e,w.name);if(!H)n.push({level:"ok",label:`Category map: none yet for "${w.name}" (created on first /push)`});else if(J.length>0)for(let K of J)n.push({level:"fail",label:`Category map ${K.field} (${K.recorded}) \u2260 profile ${K.field} (${K.current})`,fix:"This repo\u2019s records belong to a different Document360 project \u2014 to publish somewhere new, connect it as its own profile: /profile"});else{let K=JE(e,w.name),ne=`${Object.keys(H.articles).length} articles, ${Object.keys(H.categories).length} categories`;K?K.unmapped>0?n.push({level:"warn",label:`Category map covers ${K.mappedArticles} of ${K.portalArticles} Document360 articles and ${K.mappedCategories} of ${K.portalCategories} categories`+(K.declined>0?` (${K.declined} declined)`:""),fix:`/pull imports the ${K.unmapped} ${K.unmapped===1?"article":"articles"} this repo has no folder for`}):n.push({level:"ok",label:`Category map: ${ne} \u2014 every Document360 article is tracked here`}):n.push({level:"ok",label:`Category map: ${ne} (not yet compared with Document360)`,fix:"/pull --status compares this repo with Document360"});let oe=ZE(K);if(oe!==null&&oe>0){let Re=K?.dangling?.articles.length??0,le=K?.dangling?.categories.length??0;n.push({level:"warn",label:`${oe} map ${oe===1?"entry points":"entries point"} at something Document360 no longer has`+(Re>0&&le>0?` (${Re} articles, ${le} categories)`:""),detail:(K?.dangling?.articles??[]).slice(0,3).join(", ")||void 0,fix:"/push saves them again for your readers, /untrack drops the ones you no longer want \u2014 /status lists them"})}for(let Re of K?.duplicateCategories??[])n.push({level:"warn",label:`Two Document360 categories named "${Re.name}" in the same place (${Re.ids.join(", ")})`,fix:"Merging or hiding one is your decision \u2014 /restructure moves articles; nothing here deletes"});for(let Re of K?.sameNameCategories??[])(K?.duplicateCategories??[]).some(le=>le.name.toLowerCase()===Re.name.toLowerCase())||n.push({level:"warn",label:`"${Re.name}" is a Document360 category in ${Re.entries.length} different places (${Re.entries.map(le=>le.id).join(", ")})`,fix:"Readers see them all. Choose which one they keep: /restructure moves articles, /retire hides a page this repo owns, /untrack disowns one that was never ours"})}n.push(YE(yb())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${yb()}`,fix:`Reinstall ${xN} (broken install)`});let G=an(e);if(G.status==="current"?n.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${Ge})`}):G.status==="stale"&&n.push({level:"warn",label:`Dev hand-off: builder on devhints v${G.completedVersion}, current is v${Ge}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}),S&&(!ic(S)||S.refreshToken)&&!C){let K={profile:w.name,connection:w.connection,projectId:w.project.projectId,projectName:w.project.projectName};try{await XE(K);let oe=await zE(K,"/v3/projects");n.push({level:"ok",label:`API reachable (${w.connection.apiUrl}) \u2014 ${oe.length} project(s) visible`})}catch(oe){n.push({level:"fail",label:`API call failed: ${oe.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let ne=H?.projectId??w.project.projectId;if(ne&&w.project.workspaceId){try{let oe=await aN(K,ne,w.project.workspaceId);if(oe){let Re=(oe.workspace_hash??"").replace(/^sha256:/,"").slice(0,12);n.push({level:"ok",label:`Your Document360 project: reachable on ${w.connection.name} (${oe.languages?.length??0} language${(oe.languages?.length??0)===1?"":"s"}) \xB7 version ${Re||"(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(oe){oe instanceof $N||/scoped to a (?:specific|different) project|cannot access the requested project/i.test(oe.message)?n.push({level:"fail",label:`Project scope: your Document360 session is signed into a different project than this repo expects (${w.project.projectName??ne})`,fix:"Run /login and pick this repo's project \u2014 your token is scoped to another project"}):n.push({level:"warn",label:`Workspace sync manifest: probe failed (${oe.message.slice(0,80)})`})}try{let oe=await vN({cwd:e,profileName:w.name,dryRun:!0}),Re=oe.categoriesReordered+oe.articlesReordered;if(oe.skipped==="no category map")n.push({level:"ok",label:"Reading order: nothing to check yet (no articles published)"});else if(oe.skipped)n.push({level:"warn",label:`Reading order: can't be checked (${oe.skipped})`,fix:"Your article order on Document360 may not match your structure \u2014 /push syncs it once this resolves"});else if(oe.unverified)n.push({level:"warn",label:`Reading order: ${oe.unverified} of your articles aren't listed by Document360, so their order can't be set`,fix:"Usually means those articles are not live yet (the listing returns published articles). /publish takes them live, then /push re-syncs the order"});else if(Re>0){let le=[oe.categoriesReordered>0?`${oe.categoriesReordered} categor${oe.categoriesReordered===1?"y":"ies"}`:"",oe.articlesReordered>0?`${oe.articlesReordered} article${oe.articlesReordered===1?"":"s"}`:""].filter(Boolean);n.push({level:"warn",label:`Reading order: ${le.join(" + ")} out of order on Document360`,fix:"Run /push \u2014 it re-syncs the order from your NN- folder/file prefixes"})}else n.push({level:"ok",label:"Reading order: Document360 matches your structure"});if(oe.orphans?.length){let le=oe.orphans;n.push({level:"warn",label:`${le.length} article${le.length===1?"":"s"} on Document360 ${le.length===1?"is":"are"} not in your docs folder: ${le.slice(0,3).map(he=>he.path).join(", ")}${le.length>3?`, +${le.length-3} more`:""}`,fix:`/retire <path> takes one off your readers \xB7 /pull <path> brings one back into your docs folder \u2014 until you choose, it stays live and ${kh} leaves it alone`})}}catch(oe){n.push({level:"warn",label:`Reading order: check failed (${oe.message.slice(0,80)})`})}}}return n}function bb(e){let t=[""];for(let r of e){let s=r.level==="ok"?Q("\u2713"):r.level==="warn"?F(qo):L("\u2717"),i=(r.detail??"").split(`
|
|
307
|
+
`).filter(a=>a.trim());if(t.push(` ${s} ${r.label}${i.length===1?u(` \u2014 ${i[0]}`):""}`),i.length>1)for(let a of i)t.push(` ${u(a)}`);r.fix&&t.push(` ${u("fix:")} ${Z(r.fix)}`)}let n=e.filter(r=>r.level==="fail").length,o=e.filter(r=>r.level==="warn").length;return t.push(""),t.push(n===0?Q(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):L(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function Ti(e,t){console.log(u("Running checks\u2026"));for(let n of bb(await kb(t.cwd,t.version)))console.log(n);return{kind:"continue"}}var lc=Fr(()=>{"use strict";io();mn();ae();Yr()});import{createRequire as qF}from"node:module";import{WRITER_COMMAND as VF}from"document360-engine";import{Command as AF}from"commander";import{AUTH_MODES as TF,PRODUCT_NAME as EF,WRITER_COMMAND as gu,WRITER_DIRNAME as NF,WRITER_PACKAGE as DF}from"document360-engine";import{input as FR}from"@inquirer/prompts";import{currentEnvironments as WR,loginPkce as BR,getAccessToken as HR,toStoredTokens as GR,clearTokens as qR,decodeJwtClaims as Og,isExpired as VR,loadTokens as td,saveTokens as KR,listStoredSessions as nd,tokensProjectId as ro,rememberSessionProject as _g,resolveActiveProfile as ti,setProfileProject as YR,readProjectConfig as zR,WRITER_COMMAND as ei}from"document360-engine";ae();import{select as uR}from"@inquirer/prompts";import{resolveActiveProfile as Pg,setProfileProject as dR,resolveProjectId as pR,listWorkspaces as hR,ensureSeededContentSwept as fR,seededSweepLines as mR,WRITER_COMMAND as gR}from"document360-engine";async function Js(e,t){let n=Pg(e,t),o={profile:n.name,connection:n.connection,projectId:n.project.projectId,projectName:n.project.projectName},r=n.project.projectId??pR(o);return{workspaces:await hR(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var Cg=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function zu(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 Oa(e,t,n,o,r){dR(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function Ag(e,t,n){let o;try{o=await Js(e,n)}catch(s){return console.log(L(`Could not list workspaces: ${s.message}`)),1}let r=zu(o.workspaces,t);return r?(Oa(e,o.profile,o.projectId,r.id,r.name),console.log(Q(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(L(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function Wr(e,t){let n;try{n=await Js(e,t)}catch(c){console.log(L(`Could not list workspaces: ${c.message}`));return}let{workspaces:o,projectId:r,profile:s,current:i}=n;if(o.length===0){console.log(u("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let c of o)console.log(` ${c.id===i?Z("\u25CF"):" "} ${Cg(c)} ${u(c.id)}`);console.log(u(`Run: ${gR} workspace use <name>`));return}let a=await uR({message:"Select the Document360 workspace for this repo:",choices:o.map(c=>({name:`${Cg(c)}${c.id===i?" (current)":""}`,value:c.id}))}),l=o.find(c=>c.id===a);Oa(e,s,r,a,l?.name),console.log(Q(`\u2713 Workspace set to "${l?.name??a}" for profile "${s}".`)),await yR(e,s,r,a)}async function yR(e,t,n,o){try{let r=Pg(e,t),s=await fR({profile:r.name,connection:r.connection,projectId:n,projectName:r.project.projectName},{cwd:e,profile:r.name,projectId:n,workspaceId:o});for(let i of mR(s))console.log(i)}catch{}}ae();import{select as wR}from"@inquirer/prompts";import{resolveActiveProfile as kR,setProfileProject as bR,listProjects as $R,WRITER_COMMAND as Eg}from"document360-engine";async function Mn(e,t){let n=kR(e,t),o={profile:n.name,connection:n.connection};return{projects:await $R(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var Tg=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Xu(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 _a(e,t,n,o){bR(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function Ng(e,t,n){let o;try{o=await Mn(e,n)}catch(s){return console.log(L(`Could not list projects: ${s.message}`)),1}let r=Xu(o.projects,t);return r?(_a(e,o.profile,r.id,r.name),console.log(Q(`\u2713 Project set to "${r.name??r.id}" for profile "${o.profile}". Next: pick a workspace (${Eg} workspace).`)),0):(console.log(L(`No project matches "${t}". Available: ${o.projects.map(s=>s.name??s.id).join(", ")}`)),1)}async function Ma(e,t){let n;try{n=await Mn(e,t)}catch(l){console.log(L(`Could not list projects: ${l.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(u("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let l of o)console.log(` ${l.id===s?Z("\u25CF"):" "} ${Tg(l)} ${u(l.id)}`);console.log(u(`Run: ${Eg} project use <name>`));return}let i=await wR({message:"Select the Document360 project for this repo:",choices:o.map(l=>({name:`${Tg(l)}${l.id===s?" (current)":""}`,value:l.id}))}),a=o.find(l=>l.id===i);_a(e,r,i,a?.name),console.log(Q(`\u2713 Project set to "${a?.name??i}" for profile "${r}". Next: pick a workspace.`))}ae();import vR from"picocolors";function xR(e=process.env){return e.FORCE_HYPERLINK==="0"||!vR.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 RR(e,t=e,n){return xR(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var SR=/https?:\/\/[^\s\x1b]+/g;function Zs(e,t){return e.replace(SR,n=>RR(n,n,t))}mn();function Mg(e){return{...Og(e.idToken)??{},...Og(e.accessToken)??{}}}function Ua(e){let t=Mg(e),n=t.email??t.preferred_username??t.sub??"unknown",o=ro(e),r=e.projectName?` \xB7 project "${e.projectName}"`:o?` \xB7 project ${o}`:"";return`${n}${r}`}async function od(e,t,n){n&&_g(e,t,n);try{let{projects:o}=await Mn(process.cwd(),e);for(let r of nd(e)){let s=ro(r);s&&_g(e,s,o.find(i=>i.id===s)?.name)}}catch{}}function XR(e,t,n){let o=ro(e);if(!o||!t||o===t)return null;let r=n?`"${n}"`:t.slice(0,8)+"\u2026";return`\u26A0 You signed in to project ${e.projectName?`"${e.projectName}"`:o.slice(0,8)+"\u2026"}, but this repo's docs live in ${r}. Run /login again and pick ${r} (or /project to point this repo somewhere else).`}async function Fa(e){let t=ti(process.cwd(),e.profile);if(!t.configured&&!e.profile){console.error(L("This repo is not set up yet, so there is no Document360 deployment to sign in to.")),console.error(`Run ${Z("/init")} to pick your region (or ${Z(`${ei} init`)}), then sign in.`),console.error(u(`Signing in to one deployment directly: ${ei} login --profile <${WR().join("|")}>`)),process.exitCode=2;return}let n=t.connection;console.log(u(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})`)+(t.production?F(` ${Je}`):""));let o=Ve(process.cwd(),e.profile);o&&(console.log(F(`\u26A0 ${o.why} \u2014 and signing in does NOT change it (the environment comes from the profile, not the login).`)),console.log(F(` To move: ${o.cmd}${o.replacementProfile?"":", then /login"}`)));let r=await BR(n,{manual:e.manual,promptForRedirect:p=>FR({message:p})},p=>console.log(Zs(p))),s=GR(t.name,r);KR(s),await rd(s,t.name,p=>console.log(u(p)));let i=ro(s),a=ti(process.cwd(),e.profile).project;i&&await od(t.name,i,a.projectId===i?a.projectName:void 0);let l=td(t.name,i??void 0)??s;console.log(""),console.log(Q(`\u2713 Logged in to "${t.name}" as ${Ua(l)}`));let c=XR(l,a.projectId,a.projectName);if(c&&console.log(F(c)),console.log(u(` access token expires: ${s.expiresAt}`)),console.log(u(` refresh token: ${s.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{zR(process.cwd())?.profiles?.[t.name]&&(console.log(""),await Wr(process.cwd(),t.name))}catch{}}async function rd(e,t,n){let r=Mg(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(ti(process.cwd(),t).project.projectId)return;let i;try{let{projects:a}=await Mn(process.cwd(),t);i=a.find(l=>l.id===r)?.name}catch{}YR(process.cwd(),t,{projectId:r,projectName:i}),n(` Project "${i??r}" written to profile "${t}".`)}catch{}}async function Ug(e){let t=ti(process.cwd(),e.profile),n=t.connection,o=td(t.name,t.project.projectId);if(!o){console.log(L(`Not logged in to Document360 (profile "${t.name}").`));let r=nd(t.name).filter(s=>ro(s)&&ro(s)!==t.project.projectId);r.length>0&&console.log(u(`This repo's project needs its own sign-in. Signed in on this machine: ${r.map(s=>s.projectName??ro(s)).join(", ")}`)),console.log(u(`Run: ${ei} login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${Z(t.name)}${t.production?F(` ${Je}`):""}: ${Ua(o)}`),VR(o))if(o.refreshToken)try{await HR({profile:t.name,connection:n,projectId:t.project.projectId,projectName:t.project.projectName});let r=td(t.name,t.project.projectId);console.log(Q(`\u2713 Session refreshed${r?` \u2014 expires ${r.expiresAt}`:""}`))}catch(r){console.log(F(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(u(`Run: ${ei} login --profile ${t.name}`)),process.exitCode=1}else console.log(F("Session expired (no refresh token).")),console.log(u(`Run: ${ei} login --profile ${t.name}`)),process.exitCode=1;else console.log(u(` expires: ${o.expiresAt}`))}async function Fg(e){let t=ti(process.cwd(),e.profile),n=e.allProjects?void 0:t.project.projectId,o=t.project.projectName?`"${t.project.projectName}"`:`profile "${t.name}"`;if(qR(t.name,n)){console.log(Q(e.allProjects?`\u2713 Logged out of every Document360 project for profile "${t.name}".`:`\u2713 Logged out of ${o}.`));let r=nd(t.name).filter(s=>ro(s)).length;r>0&&console.log(u(`Still signed in to ${r} other project${r===1?"":"s"} on this machine.`))}else console.log(u(`No Document360 session for ${o} \u2014 nothing to do.`))}ae();import{readProjectConfig as Wg,writeProjectConfig as QR,resolveActiveProfile as JR,loadTokens as ZR,isExpired as eS,environmentIsProduction as tS,isKnownEnvironment as nS,WRITER_COMMAND as Wa,WRITER_DIRNAME as oS}from"document360-engine";function Bg(e){return e.production??tS(e.connection?.environment)}function Ba(e){let t=Wg(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(L(`No profiles in ${oS}/config.json. Run: ${Wa} init`)),process.exitCode=1;return}console.log("");let n=new Set;for(let[o,r]of Object.entries(t.profiles)){let s=o===t.defaultProfile?Z(" (active)"):"",i=Bg(r)?F(` ${Je}`):"",a=r.connection.environment??"(inline)";a!=="(inline)"&&!nS(a)&&n.add(o);let l=ZR(o,r.project?.projectId),c=l?eS(l)&&!l.refreshToken?F("expired"):u("logged in"):u("not logged in"),p=n.has(o)?F("cannot be reached"):c;console.log(` ${Z(o)}${s} \u2192 ${a}${i} [${p}]`)}if(console.log(""),console.log(u(`Switch with: ${Wa} profile use <name>`)),n.size>0){console.log("");let o=[...n].map(r=>`"${r}"`).join(", ");console.log(F(te(qo,`${n.size===1?"Profile":"Profiles"} ${o} cannot reach a Document360 deployment.`))),console.log(u(` Point this repo at a customer region: ${Wa} profile add <name> <environment>`)),console.log(u(` Add a deployment this build does not ship: ${Wa} env add <file.json>`))}console.log("")}function Ha(e,t){let n=Wg(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(L(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,QR(n,e);let o=Bg(n.profiles[t])?F(` ${Je}`):"";console.log(Q(`\u2713 Default profile is now "${t}"${o}`))}function Ga(e,t){try{let n=JR(e,t);console.log(""),console.log(`Profile ${Z(n.name)}${n.production?F(` ${Je}`):""}`),console.log(u(` api: ${n.connection.apiUrl}`)),console.log(u(` identity: ${n.connection.authorizationUrl}`)),console.log(u(` clientId: ${n.connection.clientId}`)),console.log(u(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(u(` project: ${n.project.projectId??"(set at login)"}`)),console.log(u(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(L(n.message)),process.exitCode=1}}import{currentEnvironments as rS,environmentIsProduction as sS,isKnownEnvironment as iS,readProjectConfig as aS,resolveEnvironment as lS,writeProjectConfig as cS,WRITER_COMMAND as sd,WRITER_DIRNAME as Hg}from"document360-engine";ae();function ni(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=aS(e);if(!o)return`No ${Hg}/config.json \u2014 run /init first.`;if(o.profiles?.[t])return`Profile "${t}" already exists.`;let r=n??t;return iS(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r}}},cS(o,e),null):[`Unknown environment "${r}". Known: ${rS().join(", ")}`,`Add a deployment this build does not ship: ${sd} env add <file.json>`,`Or give this profile explicit URLs in ${Hg}/config.json.`].join(`
|
|
308
|
+
`)}function oi(e,t){let n=[`\u2713 Profile "${e}" created \u2014 ${lS(t).portalUrl}`];return sS(t)&&n.push(`\u26A0 ${t} is a live deployment. Drafts save freely; taking articles live needs /allow-prod.`),n}function Gg(e,t,n){let o=ni(e,t,n);if(o){console.log(L(o)),process.exitCode=1;return}let[r,...s]=oi(t,n??t);console.log(Q(r));for(let i of s)console.log(F(i));console.log(` Switch + sign in: ${Z(`${sd} profile use ${t}`)} then ${Z(`${sd} login --profile ${t}`)}`),console.log(u(" Until you switch, this repo keeps using the current profile\u2019s environment."))}async function qg(e,t){let n=e[0];if(!n)return Ba(t.cwd),{kind:"continue"};if(n==="add"){let o=ni(t.cwd,e[1],e[2]);if(o)return console.log(L(o)),{kind:"continue"};let r=e[1],s=e[2]??r,[i,...a]=oi(r,s);console.log(Q(i));for(let l of a)console.log(F(l));return console.log(` Switch + sign in: ${Z(`/profile ${r}`)} then ${Z("/login")}`),console.log(u(" Until you switch, this repo keeps using the current profile\u2019s environment.")),{kind:"continue"}}return Ha(t.cwd,n),Ga(t.cwd,n),console.log(u(" Restarting agent for the new profile\u2026")),{kind:"clear"}}ae();import{existsSync as Yg,readdirSync as uS,readFileSync as dS,statSync as pS}from"node:fs";import{join as zg}from"node:path";import{apiLogDir as hS,PRODUCT_NAME as id}from"document360-engine";var fS=30,mS=12e3;function gS(e){if(!Yg(e))return{api:[],crash:[]};try{let t=uS(e);return{api:t.filter(n=>n.endsWith(".jsonl")).sort().reverse(),crash:t.filter(n=>/^crash-\d{4}-\d{2}-\d{2}\.log$/.test(n)).sort().reverse()}}catch{return{api:[],crash:[]}}}var yS=/·\s*(empty-turn|agent-subprocess|uncaught|unhandled)\s*===/i,wS=/·\s*FATAL\s*·/i,kS=e=>wS.test(e)||yS.test(e);function bS(e){let n=e.split(/\n(?==== \d{4}-\d{2}-\d{2}T)/).map(s=>s.trim()).filter(Boolean).filter(s=>s.startsWith("==="));if(n.length===0)return null;let o=[...n].reverse().find(kS),r=o??n[n.length-1];return{text:r,when:/^=== (\S+)/.exec(r)?.[1]??"",count:n.length,notable:!!o}}function $S(e,t){let n=t[0];if(!n)return null;try{return bS(dS(zg(e,n),"utf8"))}catch{return null}}function Vg(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}var Kg=(e,t)=>{try{return`${(pS(zg(e,t)).size/1024).toFixed(1)} KB`}catch{return""}};function ad(){let e=hS(),{api:t,crash:n}=gS(e),o=$S(e,n),r=[];if(o){let s=o.text.split(/\r?\n/),i=s.slice(0,fS);r.push(o.notable?te("\u2717",`The last thing that went wrong \u2014 ${Vg(o.when)}:`):te("\u2139",`Nothing has failed. The most recent note ${id} recorded \u2014 ${Vg(o.when)}:`)),r.push("");for(let a of i)r.push(` ${a}`);s.length>i.length&&r.push(u(` \u2026${s.length-i.length} more line${s.length-i.length===1?"":"s"} \u2014 the whole thing is in ${n[0]}, and c copies all of it.`)),r.push(""),o.count>1&&r.push(u(` ${o.count} entries recorded today; this is the one worth reading.`)),o.notable&&r.push(u(" If this is not obviously your own doing, send it to the team \u2014 it names what failed.")),r.push("")}else n.length===0&&(r.push(te("\u2713",`Nothing has failed \u2014 ${id} has recorded no problems.`)),r.push(""));if(r.push(`Logs live in ${Z(e)}`),!Yg(e)||t.length===0&&n.length===0)return r.push(u(" Nothing here yet \u2014 logs appear after the first Document360 call.")),{lines:r,copyText:null,notable:!1};if(n.length>0){r.push(""),r.push(`Problem logs ${u("(send these if something crashed or a run did nothing)")}:`);for(let s of n.slice(0,14))r.push(` ${L(s)} ${u(Kg(e,s))}`)}if(t.length>0){r.push(""),r.push("Document360 call logs:");for(let s of t.slice(0,14))r.push(` ${s} ${u(Kg(e,s))}`)}return r.push(""),r.push(u("Failed calls include what was sent and returned (sign-in details removed, 4 KB cap).")),r.push(u("Set D360_LOG_BODIES=1 to record successful calls too.")),{lines:r,copyText:o?o.text.slice(0,mS):null,notable:!!o?.notable}}async function Xg(){return ld(),{kind:"continue"}}function ld(){let{lines:e,copyText:t}=ad();console.log("");for(let n of e)console.log(n);t&&console.log(u(`Inside ${id}, /logs offers to copy this for you.`)),console.log("")}ae();mn();import{existsSync as vS,readFileSync as Qg}from"node:fs";import{homedir as xS}from"node:os";import{EnvironmentConfigError as Jg,addedEnvironmentsPath as qa,loadAddedEnvironments as Zg,parseAddedEnvironments as RS,profileEnvironmentName as SS,readProjectConfig as CS,removeAddedEnvironment as PS,resolveEnvironment as AS,saveAddedEnvironment as TS,WRITER_COMMAND as Vo}from"document360-engine";function Va(e){let t=xS();return e.startsWith(t)?`~${e.slice(t.length).replace(/\\/g,"/")}`:e}function ey(e){let t=oo(),n=SS(e),o=n&&!t.some(m=>m.name===n);if(o){let m=Ve(e);t.push({name:n,portalUrl:"\u2014",note:m?`cannot be reached \u2014 ${m.why}`:"cannot be reached from this machine",internal:!1,production:!1,added:!1,retired:!1})}let r=m=>m===n?`${m} (active)`:m,s=Math.max(...t.map(m=>r(m.name).length)),i=Math.max(...t.map(m=>m.portalUrl.length)),a=["Document360 deployments",""];for(let m of t){let $=m.note?u(` ${m.note}`):"";a.push(` ${Z(r(m.name).padEnd(s))} ${m.portalUrl.padEnd(i)}${$}`)}let{entries:l,problems:c}=Zg(),p=Object.keys(l);if(a.push(""),n&&a.push(u("(active) = where this repo publishes.")),p.length===0&&!o?a.push(u(`Add a deployment this build does not ship: ${Vo} env add <file.json>`)):p.length>0&&(a.push(u(`Added on this machine: ${Va(qa())}`)),a.push(u(`Add another: ${Vo} env add <file.json>`)),a.push(u(`Remove one: ${Vo} env remove ${p[0]}`))),c.length>0){a.push("");let m=c.length===1?"One added deployment could not be loaded:":`${c.length} added deployments could not be loaded:`;a.push(F(te("\u26A0",m)));for(let $ of c)a.push(F(` ${$}`))}if(o){let m=Ve(e);a.push(""),a.push(F(te("\u26A0",`This repo cannot reach "${n}", so nothing here can publish.`))),m?.kind==="unshipped"?(a.push(u(` Add it on this machine: ${Vo} env add <file.json>`)),a.push(u(" Or publish to a customer region instead: /profile"))):a.push(u(` Pick where this repo publishes: ${m?.cmd??"/profile"}`))}return a}function ES(e){if(e==="-")try{return{text:Qg(0,"utf8"),where:"standard input"}}catch{return null}if(!vS(e))return null;try{return{text:Qg(e,"utf8"),where:e}}catch{return null}}function ty(e,t){let n=ES(t);if(!n)return{ok:!1,lines:[L(`Cannot read ${t}.`),u("Pass a JSON file, or - to read the document from standard input.")]};let o;try{o=RS(n.text,n.where)}catch(a){if(!(a instanceof Jg))throw a;return{ok:!1,lines:[L("That document has problems, so nothing was saved:"),...a.message.split(`
|
|
309
|
+
`).map(l=>L(` ${l}`))]}}let r=Object.keys(o);if(r.length===0)return{ok:!1,lines:[L(`${n.where} defines no deployments.`),u("The document is a JSON object of environment name \u2192 connection fields.")]};let s=[];for(let a of r){let l=TS(a,o[a]),c=AS(a);s.push(Q(te("\u2713",`${l==="added"?"Added":"Updated"} ${a} \u2014 ${c.portalUrl}`))),c.isProduction?s.push(F(te("\u26A0",`${a} is a live deployment. Drafts save freely; taking articles live needs /allow-prod.`))):s.push(u(' Treated as staging. Add "isProduction": true if it reaches real readers.'))}s.push(""),s.push(u(`Saved to ${Va(qa())}`)),s.push("");let i=r[0];return s.push(CS(e)?`Next: ${Z(`${Vo} profile add ${i} ${i}`)} ${u("(or /profile in the app \u2014 then sign in)")}`:`Next: ${Z(`${Vo} init`)} ${u(`(${i} is now in the deployment list)`)}`),{ok:!0,lines:s}}function ny(e,t){let n=!1;try{n=PS(t)}catch(s){if(!(s instanceof Jg))throw s;return{ok:!1,lines:[L(`${Va(qa())} cannot be read, so nothing was removed:`),...s.message.split(`
|
|
310
|
+
`).map(i=>L(` ${i}`))]}}if(!n){let s=Object.keys(Zg().entries);return{ok:!1,lines:[L(`Nothing added on this machine is called "${t}".`),u(s.length>0?`Added here: ${s.join(", ")}`:"This machine has no added deployments.")]}}let o=[Q(te("\u2713",`Removed ${t} from ${Va(qa())}`))],r=Zu(e,t);return r&&(o.push(F(te("\u26A0",`Profile "${r}" in this repo still points at ${t} and can no longer reach it.`))),o.push(u(` Add it back with: ${Vo} env add <file.json>`))),{ok:!0,lines:o}}function cd(e,t){let[n,o]=t;return!n||n==="list"?{ok:!0,lines:ey(e)}:n==="add"?o?ty(e,o):{ok:!1,lines:[L("Usage: /env add <file.json>"),u("A JSON object of environment name \u2192 connection fields.")]}:n==="remove"?o?ny(e,o):{ok:!1,lines:[L("Usage: /env remove <name>")]}:{ok:!1,lines:[L(`Unknown: /env ${n}`),u("Try: /env, /env add <file.json>, /env remove <name>")]}}function Ka(e){console.log("");for(let t of e.lines)console.log(t);console.log(""),e.ok||(process.exitCode=1)}function oy(e){Ka({ok:!0,lines:ey(e)})}function ry(e,t){Ka(ty(e,t))}function sy(e,t){Ka(ny(e,t))}async function iy(e,t){return Ka(cd(t.cwd,e)),{kind:"continue"}}ae();import{createSession as NS,resolveAuth as DS,findByName as jS,slugify as IS,touchSession as LS,upsertSession as OS,resolveActiveProfile as _S,WRITER_COMMAND as MS}from"document360-engine";async function ay(e,t,n,o,r,s){let i=DS(n);i.kind==="none"&&(console.error(""),console.error(L("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${Z("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${Z(`${MS} --auth subscription`)}`),process.exit(2)),i.kind==="subscription"&&console.error(u("Using your Claude subscription (no API key set)."));let a=null;try{a=_S(e,r)}catch($){console.error(L(`Document360 profile error: ${$.message}`)),process.exit(2)}a.production&&(console.error(F(`${Je} \u2014 profile "${a.name}" publishes to real readers.`)),console.error(s?u(" --yes given \u2014 this run may take articles live."):u(" Drafts will be saved. Taking articles live needs --yes.")));let l;if(o){let $=jS(e,o);$||(console.error(L(`No saved session matches "${o}" in this repo.`)),console.error(u("List sessions inside the REPL with /resume.")),process.exit(2)),l=$.uuid,console.error(u(`Resuming "${$.name}"`))}let c=NS({cwd:e,resume:l,profileName:r,allowProdWrites:s===!0}),p=l??null,m=1;for await(let $ of c.send(t))switch($.type){case"session":if(!p){p=$.sessionId;let w=new Date().toISOString();OS({uuid:p,name:IS(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:w,updatedAt:w})}break;case"text":process.stdout.write($.delta);break;case"tool":console.error(Ie(` \u2699 ${$.name}`));break;case"result":m=$.ok?0:1,console.error(u(`(${$.inputTokens}\u2192${$.outputTokens} tokens`+($.costUsd>0?`, $${$.costUsd<.01?$.costUsd.toFixed(4):$.costUsd.toFixed(2)}`:"")+")")),$.ok||console.error(L("agent finished with an error result"));break;case"error":console.error(""),console.error(L(`agent error: ${$.message}`)),process.exit(1)}p&&LS(p),process.stdout.write(`
|
|
311
|
+
`),process.exit(m)}import{createInterface as w_}from"node:readline/promises";import{createSession as um,resolveAuth as k_,resolveAuthOrigin as b_,authOriginLine as Jv,authOriginFix as $_,getSession as v_,setTitle as x_,slugify as R_,touchSession as ox,upsertSession as S_,generateTitle as C_,resolveActiveProfile as rx,resolveModelSetting as P_,readProjectConfig as A_,readUserConfig as T_,resolveAndPersistAppType as E_,decodeJwtClaims as Zv,isExpired as N_,loadTokens as D_,isDirectiveMention as j_,stripDirectiveMention as I_,appendDirective as L_,reconcileUpgradeActions as O_,stampArticles as __,snapshotArticles as ex,listArticleFiles as M_,applyStructureOrder as U_,orderSyncLine as F_,computeSyncStatus as W_,recordBriefConsumed as B_,PRODUCT_DISPLAY_NAME as H_,PRODUCT_NAME as G_,WRITER_COMMAND as hm,WRITER_DIRNAME as q_}from"document360-engine";import{ENGINE_VERSION as HS}from"document360-engine";import{CAPTURE_COMMAND as Qa,CAPTURE_PACKAGE as FS,PRODUCT_DISPLAY_NAME as ly,PRODUCT_NAME as Ko}from"document360-engine";import{PRODUCT_NAME as US}from"document360-engine";var Ya=76;function gn(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 za(e){if(e.length===0)return[];let t=(s,i)=>`${s}${"\u2500".repeat(Ya+2)}${i}`,n=(s="")=>`\u2502 ${s.padEnd(Ya)} \u2502`,o=[`\u2B06 ${US} upgraded \u2014${e.length===1?"one improvement affects":`${e.length} improvements affect`} the docs you've already written:`,"",t("\u250C","\u2510")];e.forEach((s,i)=>{i>0&&o.push(t("\u251C","\u2524")),o.push(n());for(let a of gn(`${i+1}. ${s.feature}`,Ya))o.push(n(a));o.push(n());for(let a of gn(s.why,Ya-3))o.push(n(` ${a}`));o.push(n())}),o.push(t("\u2514","\u2518")),o.push("");let r=e.length>1;return o.push(`\u2713 ${r?"These are":"This is"} now on your docs roadmap \u2014 each launch shows your next step below (/roadmap shows the full campaign).`),o}function Xa(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(`
|
|
312
|
+
`)}var Et=[{key:"start",label:"Getting Started",rows:[{t:"text",s:`${Ko} reads your codebase and writes your user documentation.`},{t:"gap"},{t:"text",s:"It publishes to Document360 when you are ready."},{t:"gap"},{t:"text",s:"It needs Claude access \u2014 a subscription, or an ANTHROPIC_API_KEY."},{t:"gap"},{t:"sub",s:"Quick start"},{t:"step",n:1,s:"Run /init. Pick the Document360 deployment you publish to, sign in, choose your project."},{t:"step",n:2,s:"Paste the prompt it prints into your coding agent, and let it finish."},{t:"step",n:3,s:"Run /doctor to confirm every check is green."},{t:"step",n:4,s:'Type "write the docs for this repository".'},{t:"gap"},{t:"dim",s:"Claude Code, Codex and Cursor all work. /devhints re-shows that prompt."},{t:"dim",s:`That's it \u2014 ${Ko} drafts your docs without you writing a line.`},{t:"gap"},{t:"sub",s:"Tips"},{t:"text",s:"Just talk to it. Anything not starting with / goes to the agent."},{t:"gap"},{t:"dim",s:"/ browse commands \xB7 \u2191 recall history \xB7 tab run the suggestion"},{t:"dim",s:"1-9 pick from a list \xB7 ctrl+y copy whatever was offered"},{t:"dim",s:"esc interrupt a run \xB7 ctrl+c twice exit"},{t:"dim",s:"shift+tab switch auto / manual \u2014 see /auto"}]},{key:"agentic",label:"Agentic",rows:[{t:"text",s:"Agentic mode is for products built with an AI coding agent."},{t:"gap"},{t:"text",s:"Your coding agent ships features and leaves notes."},{t:"text",s:`${Ko} turns those notes into user documentation.`},{t:"gap"},{t:"dim",s:"Think of it as a Technical Writer dedicated to your project."},{t:"gap"},{t:"sub",s:"Auto or manual"},{t:"gap"},{t:"text",s:"In MANUAL mode I work out the next step and offer it. You press tab."},{t:"gap"},{t:"text",s:"In AUTO mode I run that step myself, then the one after it."},{t:"gap"},{t:"dim",s:" write \u2192 review \u2192 check the style \u2192 save \u2192 go live"},{t:"gap"},{t:"text",s:"Start a build, come back to a finished knowledge base."},{t:"gap"},{t:"cmd",name:"/auto on",s:"Let me run my own next step."},{t:"cmd",name:"/auto --budget",s:"Cap what one run may spend. The standard cap is $200."},{t:"gap"},{t:"dim",s:" shift+tab switches mode \xB7 esc stops a run"},{t:"dim",s:" Nothing already written, saved or published is undone."},{t:"gap"},{t:"text",s:"Auto changes who presses the key. It does not change what is checked."},{t:"gap"},{t:"text",s:"Every gate still runs."},{t:"text",s:"An article that fails one stays a draft, and the report names it."},{t:"gap"},{t:"text",s:"Screenshots are never automatic \u2014 they need your app on screen."},{t:"gap"},{t:"sub",s:"Every few days"},{t:"cmd",name:"/catch-up",s:"Write up everything pending. It all lands as a draft."},{t:"dim",s:" A note whose code your builder has not committed waits, and they get asked."},{t:"dim",s:" --include-unfinished write those pages anyway"},{t:"cmd",name:"/review --fix",s:"A senior editor reads every article and fixes it."},{t:"cmd",name:"/push --all",s:"Save the reviewed articles to Document360, as drafts."},{t:"cmd",name:"/publish --all",s:"Take those drafts live. It lists them and asks first."},{t:"gap"},{t:"dim",s:" An editorial read is required before anything goes live."},{t:"dim",s:" /review --blocked only the articles publishing is stuck on"},{t:"dim",s:" /review --stale only the ones this editor has not read yet"},{t:"gap"},{t:"sub",s:"Whenever you need"},{t:"cmd",name:"/discover",s:"Interview your builder. Pins a product brief for the docs."},{t:"cmd",name:"/audit",s:"What changed in the code, what is missing from the docs."},{t:"cmd",name:"/audit --decline <path>",s:"That folder or file needs no article. Stops it being reported. Bare: lists what you could decline."},{t:"cmd",name:"/pull",s:"Bring down portal edits and any new portal articles."},{t:"cmd",name:"/resolve",s:"Settle a conflict: keep yours, take the portal, or skip."},{t:"cmd",name:"/comments",s:"Reviewer comments on your articles. Read one, answer it."},{t:"cmd",name:"/inbox",s:"Act on your coding agent's messages."},{t:"cmd",name:"/ask",s:"Ask your developers what the code cannot answer."},{t:"gap"},{t:"dim",s:" An answer fixes the article, saves the draft and replies in the thread."}]},{key:"assistant",label:"Assistant",rows:[{t:"text",s:`${Ko} is your writing assistant.`},{t:"gap"},{t:"text",s:"It does the writing. You decide what gets written, and when."},{t:"gap"},{t:"text",s:"Best for large monorepos: point it at one feature or one set of folders."},{t:"gap"},{t:"sub",s:"Just ask"},{t:"good",s:'"Write the docs for the Multiple JWT feature we shipped last release."'},{t:"gap"},{t:"sub",s:"Or drive it yourself"},{t:"cmd",name:"/scope",s:"Focus on specific source folders."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from its PRDs and the code."},{t:"cmd",name:"/write",s:"Write the planned articles."},{t:"cmd",name:"/push",s:"Save them to Document360 as drafts."},{t:"cmd",name:"/publish",s:"Take the drafts live to your readers."},{t:"cmd",name:"/status",s:"What stands between your work and your readers. Free."},{t:"gap"},{t:"dim",s:" /write --preview shows the plan and the cost first."},{t:"dim",s:" /push --preview <path> shows exactly what Document360 would receive."},{t:"gap"},{t:"sub",s:"One place for what repeats"},{t:"gap"},{t:"text",s:"A variable holds a value \u2014 your product name, a URL \u2014 in one place."},{t:"text",s:"Change it there and every article changes."},{t:"gap"},{t:"text",s:"A snippet does the same for a whole block, like who to contact."},{t:"gap"},{t:"text",s:"A term is defined once, and every article is checked for explaining it."},{t:"gap"},{t:"cmd",name:"/reuse",s:"What your project already keeps on Document360."},{t:"cmd",name:"/reuse pull",s:"Refresh that list from Document360."},{t:"cmd",name:"/reuse add",s:'Create one there: /reuse add variable <name> "<value>".'},{t:"cmd",name:"/reuse audit",s:"Read every article and find what belongs in one place."},{t:"cmd",name:"/terms",s:"Is the same thing called the same name everywhere?"},{t:"cmd",name:"/eval",s:"How does the whole knowledge base score? Free."},{t:"gap"},{t:"dim",s:" Reading is free. Nothing is created until you pick it."},{t:"gap"},{t:"sub",s:"Taking a page back"},{t:"cmd",name:"/retire <path>",s:"Stop showing an article to readers. /push puts it back."},{t:"cmd",name:"/untrack <path>",s:"Disown an imported page that is not one of your docs."},{t:"gap"},{t:"dim",s:" Neither deletes anything. History and reviewer comments stay."}]},{key:"shots",label:"Screenshots",rows:[{t:"text",s:`Documenting a web app? ${Ko} marks where an image helps.`},{t:"gap"},{t:"text",s:`The companion CLI ${Qa} turns those marks into real,`},{t:"text",s:"annotated screenshots by driving your app in a browser."},{t:"gap"},{t:"sub",s:"Flow"},{t:"step",n:1,s:"Write your docs as usual. Placeholders go in where visuals help."},{t:"step",n:2,s:"Run /screenshot author --all to write the capture specs."},{t:"step",n:3,s:"Stage what the checklist asks for, then /screenshot capture."},{t:"step",n:4,s:"The callouts are drawn on straight after. No browser needed."},{t:"step",n:5,s:"Each finished picture is checked, then marked \u2714 verified."},{t:"step",n:6,s:"Run /push --screenshots so the images embed on Document360."},{t:"gap"},{t:"sub",s:"One command family"},{t:"cmd",name:"/screenshot",s:"Pick what to do next."},{t:"cmd",name:"/screenshot author",s:"Write the capture specs."},{t:"cmd",name:"/screenshot capture",s:"Take the shots."},{t:"cmd",name:"/screenshot annotate",s:"Draw the callouts on shots already taken."},{t:"cmd",name:"/screenshot verify",s:"Judge the finished pictures and mark them verified."},{t:"cmd",name:"/screenshot checklist",s:"What to stage, and the test-ids to ask your dev for."},{t:"cmd",name:"/screenshot list",s:"Progress by chapter, and the worklist."},{t:"gap"},{t:"dim",s:" Each takes an <id>, a path, or --all."},{t:"dim",s:" capture --failed re-runs what did not work \xB7 --blocked what waited on data"},{t:"dim",s:" annotate --force re-draws after a wording or style change"},{t:"gap"},{t:"sub",s:"What each state means"},{t:"text",s:"\u2714 verified finished \u2014 this is the finish line"},{t:"text",s:"\u25C8 to verify the picture is done, waiting to be looked at"},{t:"text",s:"\u25CF to annotate shot taken, callouts not drawn on yet"},{t:"text",s:"\u25D0 ready the spec is written, the shot not taken"},{t:"text",s:"\u2691 rejected the shot ran but the picture is wrong"},{t:"text",s:"\u2298 blocked your app lacked the data the shot needs"},{t:"text",s:"\u2717 broken the spec itself is out of date"},{t:"text",s:"\u25CB to-spec no spec written yet"},{t:"gap"},{t:"dim",s:" rejected \u2014 the spec is usually fixed for you, then capture --failed re-shoots"},{t:"dim",s:" blocked \u2014 /screenshot list groups every blocker into a few things to stage"},{t:"dim",s:" broken \u2014 re-author with /screenshot <id>; a re-capture would fail the same way"},{t:"gap"},{t:"dim",s:"One-time setup in your app repo:"},{t:"dim",s:` npm i -g ${FS} \xB7 ${Qa} init \xB7 ${Qa} auth`}]},{key:"cmds",label:"Commands",rows:[{t:"dim",s:"Every command, one line each \u2014 type / for the full usage."},{t:"dim",s:"The tabs above teach the ones worth more than a line."},{t:"gap"},{t:"sub",s:"Getting started"},{t:"cmd",name:"/init",s:"Set up Document360 and the coding-agent hand-off."},{t:"cmd",name:"/login",s:"Sign in \u2014 one sign-in per project, all kept."},{t:"cmd",name:"/project",s:"Choose the Document360 project."},{t:"cmd",name:"/workspace",s:"Switch the workspace."},{t:"cmd",name:"/scope",s:"Choose which repo folders back the docs."},{t:"cmd",name:"/genre",s:"What kind of product this is \u2014 picks the writing guide."},{t:"cmd",name:"/devhints",s:"Re-show the prompt to paste into your coding agent."},{t:"cmd",name:"/mcp",s:"Connect MCP servers (Notion, Linear, \u2026)."},{t:"gap"},{t:"sub",s:"Agentic \u2014 keep docs in sync"},{t:"cmd",name:"/roadmap",s:"The docs campaign: progress and the next step."},{t:"cmd",name:"/catch-up",s:"Do all pending work \u2192 drafts. --push also saves them."},{t:"cmd",name:"/auto",s:"Run the next step myself instead of waiting for you."},{t:"cmd",name:"/audit",s:"What changed in the code, what's missing from the docs."},{t:"cmd",name:"/inbox",s:"Act on your coding agent's messages."},{t:"cmd",name:"/ask",s:"Ask your developers what the code cannot answer."},{t:"cmd",name:"/share",s:"Get your builder's latest, send yours (automatic)."},{t:"gap"},{t:"sub",s:"Assistant \u2014 directed writing"},{t:"cmd",name:"/discover",s:"Interview your builder \u2192 a product brief for the docs."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from its PRDs and the code."},{t:"cmd",name:"/write",s:"Write the planned articles. --preview costs first."},{t:"cmd",name:"/preview",s:"Render an article locally."},{t:"cmd",name:"/reorder",s:"Put a category's articles in the best reading order."},{t:"cmd",name:"/restructure",s:"Move an article to another category, split one, merge two, rename one."},{t:"cmd",name:"/structure",s:"The reading order, as it will appear on Document360."},{t:"gap"},{t:"sub",s:"Quality \u2014 before you publish"},{t:"cmd",name:"/style-guide",s:"Choose the writing rules your docs are held to."},{t:"cmd",name:"/lint",s:"The machine pass over those rules. Free. --fix corrects."},{t:"cmd",name:"/review",s:"The editor pass. Required before anything goes live."},{t:"cmd",name:"/terms",s:"Is the same thing called the same name everywhere? Free."},{t:"cmd",name:"/eval",s:"Score the whole set: links, shape, naming. Free."},{t:"cmd",name:"/reuse",s:"The terms, values and blocks kept on Document360."},{t:"gap"},{t:"sub",s:"Publish & sync"},{t:"cmd",name:"/status",s:"What stands between your work and your readers. Free."},{t:"cmd",name:"/push",s:"Save your articles to Document360 as drafts."},{t:"cmd",name:"/publish",s:"Take the drafts live to your readers. Asks first."},{t:"cmd",name:"/pull",s:"Portal edits + new portal articles. --status: report only."},{t:"cmd",name:"/resolve",s:"Settle a local\u2194portal conflict: keep, take, or skip."},{t:"cmd",name:"/comments",s:"Reviewer comments on your articles \u2014 read and answer."},{t:"cmd",name:"/retire",s:"Take an article off your readers. Nothing is deleted."},{t:"cmd",name:"/untrack",s:"Disown an imported page that is not one of your docs."},{t:"gap"},{t:"sub",s:"Screenshots"},{t:"cmd",name:"/screenshot",s:"The screenshot pipeline. Bare: pick what to do next."},{t:"dim",s:" author \xB7 capture \xB7 annotate \xB7 verify \xB7 checklist \xB7 list"},{t:"gap"},{t:"sub",s:"Setup & health"},{t:"cmd",name:"/model",s:"Set the Claude model."},{t:"cmd",name:"/verbose",s:"Raw transcript: every tool call, path and result."},{t:"cmd",name:"/profile",s:"Where this repo publishes. Switch, or connect another environment."},{t:"cmd",name:"/allow-prod",s:"Authorize taking articles live on a production profile."},{t:"cmd",name:"/env",s:"The deployments this machine can reach. Add one from a JSON file."},{t:"cmd",name:"/doctor",s:"Health check \u2014 including a real agent turn."},{t:"cmd",name:"/logs",s:"The last problem, in full. \u2303y copies it."},{t:"cmd",name:"/update",s:`Update ${Ko}, and ${Qa} if installed.`},{t:"cmd",name:"/feedback",s:"Copy this repo's open feedback, to relay to the team."},{t:"cmd",name:"/copy",s:"Copy what is waiting to be copied. \u2303y does the same."},{t:"cmd",name:"/logout",s:"Sign out of this project. --all-projects: all of them."},{t:"cmd",name:"/reset",s:`Delete all ${Ko} files (confirms first).`},{t:"gap"},{t:"sub",s:"Session"},{t:"cmd",name:"/resume",s:"Resume a saved session."},{t:"cmd",name:"/rename",s:"Name the session."},{t:"cmd",name:"/clear",s:"Clear the screen and reset the conversation."},{t:"cmd",name:"/help",s:"Show this help."},{t:"cmd",name:"/exit",s:"Quit."}]}],cy=24;function ud(e){let t=e.filter(n=>n.t==="cmd").map(n=>n.name.length);return t.length===0?cy:Math.min(cy,Math.max(...t))}var uy=2;function Ja(e,t,n,o){let r=" ".repeat(2+n+uy),s=Math.max(24,o-r.length-2),i=gn(t,s);return e.length>n?{nameCell:e,descLines:i,indent:r,nameOwnLine:!0}:{nameCell:e.padEnd(n+uy-1),descLines:i,indent:r,nameOwnLine:!1}}function WS(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=Ja(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(`
|
|
313
|
+
`)}case"gap":return""}}function dy(e){let n=[e?`${ly} \u2014 help \xB7 v${e.version} \xB7 engine v${e.engineVersion}`:`${ly} \u2014 help`,""];for(let o of Et){n.push(`\u2500\u2500 ${o.label} \u2500\u2500`,"");let r=ud(o.rows);for(let s of o.rows)n.push(WS(s,r,100));n.push("")}return n.push("Tip: anything not starting with / goes to the agent."),n}function dd(e,t){return gn(e,Math.max(10,Math.max(20,t)-2))}function BS(e,t,n){let o=Math.max(20,n),r=s=>Math.max(1,dd(s,o).length);switch(e.t){case"gap":return 1;case"cmd":{let s=Ja(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 py(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=BS(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 hy(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 pd(e=[],t){console.log("");let n=t?.version?{version:t.version,engineVersion:HS}:void 0;for(let o of dy(n))console.log(o);return console.log(""),console.log("Reporting a problem? Run `/logs` \u2014 it shows the last problem and offers to copy it."),console.log(""),{kind:"continue"}}ae();import{getSession as GS}from"document360-engine";async function fy(e,t){let n=t.currentUuid(),o=n?GS(n):void 0;return console.log(o?u(`
|
|
314
314
|
(conversation reset \u2014 "${o.name}" is still available via /resume)
|
|
315
315
|
`):u(`
|
|
316
316
|
(conversation reset \u2014 agent will start fresh on the next prompt)
|
|
317
|
-
`)),{kind:"clear"}}async function
|
|
317
|
+
`)),{kind:"clear"}}async function hd(){return{kind:"exit"}}sl();ae();import{readMcpConfig as $d,writeMcpConfig as Uy,HOME_DIRNAME as pC}from"document360-engine";async function il(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(hC(),{kind:"continue"}):t==="add"?(fC(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(mC(e.slice(1)),{kind:"continue"}):(console.log(L(`Unknown /mcp subcommand: ${t}`)),console.log(u("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function hC(){let e=$d(),t=Object.keys(e.servers);if(t.length===0){console.log(u(`
|
|
318
318
|
No MCP servers registered. Add one with /mcp add <name> <type> <ref>
|
|
319
|
-
`));return}console.log(""),console.log(
|
|
319
|
+
`));return}console.log(""),console.log(`Registered MCP servers (~/${pC}/mcp.json):`);for(let n of t){let o=e.servers[n];if(o.type==="stdio")console.log(` ${Z(n)} ${u("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?u(` [headers: ${r.join(", ")}]`):"";console.log(` ${Z(n)} ${u(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function fC(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(L("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(L(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=$d(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let i={};for(let a=1;a<o.length;a++)if(o[a]==="-H"||o[a]==="--header"){let l=o[++a],c=l?.match(/^([^:=]+)[:=](.+)$/);if(!c){console.log(L(`-H expects key:value (no spaces). Got: ${l??"(nothing)"}`));return}i[c[1].trim()]=c[2].trim()}else{console.log(L(`Unexpected argument: ${o[a]}. After the URL, only -H key:value is allowed.`));return}s={type:n,url:o[0],headers:Object.keys(i).length>0?i:void 0}}r.servers[t]=s,Uy(r),console.log(""),console.log(Q(`\u2713 Registered "${t}" (${n})`)),console.log(F(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(u(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function mC(e){let t=e[0];if(!t){console.log(L("Usage: /mcp remove <name>"));return}let n=$d();if(!n.servers[t]){console.log(L(`No server named "${t}".`));return}delete n.servers[t],Uy(n),console.log(Q(`\u2713 Removed "${t}".`)),console.log(u(" Run /clear to drop it from the current session immediately."))}ae();import{readFileSync as ZP}from"node:fs";import{join as eA}from"node:path";import{select as tA}from"@inquirer/prompts";import{computeSyncStatus as Al,planPartitions as nA,relatedArticlePaths as oA,loadProfileMap as qw,draftPendingPaths as Vw,placeholderFindings as rA,resolveActiveProfile as El,listUnpullable as sA,unreviewedPaths as iA,styleErrorPaths as Kw,publishGateVerdict as aA,publishGateLines as lA,pushArticles as cA,pushArticle as uA,PUSH_POOL_SIZE as dA,SKIP_STYLE_FLAG as pA,listArticleFiles as Yw,docsRootOf as hA,ensureFeedbackChannel as fA,FEEDBACK_CATEGORY_NAME as Hw,resolveCrossLinks as mA,applyStructureOrder as zw,orderSyncLine as Xw,applyRelatedArticles as Qw,relatedSyncLine as Jw,PRODUCT_NAME as gA}from"document360-engine";import{readFileSync as gC}from"node:fs";import{resolve as yC}from"node:path";import{prettyFolderName as Fy}from"document360-engine";var ao=Fy;function al(e){return e.replace(/\\/g,"/").split("/").slice(0,-1).join("/")}function si(e){let t=e.replace(/\\/g,"/").split("/").pop()??e;return Fy(t.replace(/\.md$/i,""))}function ll(e,t){try{return/^#\s+(.+)$/m.exec(gC(yC(e,t),"utf8"))?.[1]?.trim()??null}catch{return null}}mn();import{resolveActiveProfile as Wy,loadTokens as By,isExpired as Rd,listStoredSessions as wC,tokensProjectId as xd,identityRefusal as kC}from"document360-engine";function Gt(e){return[e.reason,`Run: ${e.fix}`]}function cl(e,t){try{let n=Wy(e,t),o=By(n.name,n.project.projectId);return!o||Rd(o)?!1:st(e,t).ok}catch{return!1}}function bC(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function vd(e,t){return t?`"${t}"`:e?bC(e):"this project"}function $C(e,t){return t?wC(e).filter(n=>{let o=xd(n);return!!o&&o!==t&&!(Rd(n)&&!n.refreshToken)}):[]}function st(e,t){try{let n=Wy(e,t);try{n.connection}catch(l){let c=Ve(e,t);return{ok:!1,reason:l instanceof Error?l.message:String(l),fix:c?.cmd??"/profile"}}let o=kC(e,t);if(o)return{ok:!1,reason:o,fix:"/profile"};let r=n.project.projectId,s=vd(r,n.project.projectName),i=By(n.name,r);if(!i){let l=$C(n.name,r);return l.length>0?{ok:!1,reason:`You're signed in to Document360 project ${l.map(p=>vd(xd(p)??void 0,p.projectName)).join(", ")}, and this repo's docs live in ${s}. A sign-in covers one project, so ${s} needs its own \u2014 run /login and pick it. Both stay signed in after that, so switching between repos won't ask again.`,fix:"/login"}:{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`,fix:"/login"}}if(Rd(i)&&!i.refreshToken)return{ok:!1,reason:`Your Document360 session for ${s} expired. Run /login.`,fix:"/login"};let a=xd(i);return r&&a&&a!==r?{ok:!1,reason:`Your Document360 session is signed into a different project than this repo's ${s} (the session is for ${vd(a,i.projectName)}). Run /login and pick ${s}.`,fix:"/login"}:{ok:!0}}catch{return{ok:!0}}}import{existsSync as lw,readFileSync as Md}from"node:fs";import{isAbsolute as ml,join as gl,resolve as yl}from"node:path";import U from"picocolors";import hl from"string-width";import{readProjectConfig as co,screenshotPlaceholderIds as cw,screenshotMarkerProblemsInDocs as zC,DEFAULT_CAPTURE_DIR as wl,DEFAULT_OUTPUT_DIR as Ud,DEFAULT_DOCS_DIR as Fd,resolveOutputDir as uw,migrateShotLayout as XC,reviewIsCurrent as QC,anchorPresent as JC,annotationCurrent as ZC,captureLanded as eP,shotArtifacts as tP,RAW_SUBDIR as nP,ANNOTATED_SUBDIR as oP,CAPTURE_HELPERS_SPECIFIER as dw,CAPTURE_PACKAGE as pw}from"document360-engine";import{createHash as Sd}from"node:crypto";import{readFileSync as Gy,writeFileSync as vC}from"node:fs";import{join as xC}from"node:path";import{captureStatePath as qy,writerDir as RC}from"document360-engine";var Hy={version:1,shots:{}};function SC(e){return e.replace(/^/,"").replace(/\r\n?/g,`
|
|
320
320
|
`).replace(/\n+$/,`
|
|
321
|
-
`)}function
|
|
322
|
-
`,"utf8")}function
|
|
323
|
-
${a[1]??" "}clipTo: ${l}${i.selector}${l},`);return c=c.replace(o,`${r}await captureShot(page, PLACEHOLDER);`),c=c.replace(
|
|
321
|
+
`)}function Vy(e){return Sd("sha1").update(SC(e)).digest("hex").slice(0,12)}function CC(e){return Sd("sha1").update(e).digest("hex").slice(0,12)}function ul(e){try{let t=JSON.parse(Gy(xC(RC(e),"capture.json"),"utf8").replace(/^/,"")),n=Object.keys(t.profiles??{}),o=t.defaultProfile??(n.length===1?n[0]:n.includes("staging")?"staging":n[0]);if(!o)return null;let r=t.profiles?.[o],s=r?.scope??{},i=Object.keys(s).sort().map(a=>`${a}=${s[a]}`).join("&");return Sd("sha1").update(`${o}|${r?.connection?.startUrl??""}|${i}`).digest("hex").slice(0,12)}catch{return null}}function Fn(e){try{let t=JSON.parse(Gy(qy(e),"utf8").replace(/^/,""));return!t||typeof t!="object"||t.version!==1||!t.shots?{...Hy,shots:{}}:{version:1,shots:t.shots}}catch{return{...Hy,shots:{}}}}function PC(e,t){vC(qy(e),`${JSON.stringify(t,null,2)}
|
|
322
|
+
`,"utf8")}function Cd(e){return e&&/data-testid|\btest-?id\b|has(?:n't| not) landed/i.test(e)?"testid":"data"}function dl(e,t,n){if(t.length===0)return;let o=Fn(e),r=ul(e);for(let s of t){let i=s.specSource?Vy(s.specSource):void 0;o.shots[s.id]={outcome:s.outcome,at:n,...s.reason?{reason:s.reason}:{},...s.outcome==="skipped"?{blockedBy:Cd(s.reason)}:{},...i?{specHash:i}:{},...r?{envHash:r}:{}}}PC(e,o)}function Pd(e,t,n,o){let r=e.shots[t];return!r||n===null||!r.specHash||r.specHash!==Vy(n)&&r.specHash!==CC(n)||o&&r.envHash&&r.envHash!==o?null:r}function Ky(e){let t=Fn(e).shots;return Object.keys(t).filter(n=>t[n].outcome==="failed").sort()}function Ad(e,t,n){let o=Pd(Fn(e),t,n,ul(e));return!o||o.outcome==="captured"||!o.reason?null:{outcome:o.outcome,reason:o.reason}}Yr();import{existsSync as IC,readFileSync as Qy,readdirSync as Jy,writeFileSync as LC}from"node:fs";import{isAbsolute as OC,join as Zy,resolve as _C}from"node:path";import{readProjectConfig as MC,DEFAULT_CAPTURE_DIR as UC,CAPTURE_COMMAND as FC,CAPTURE_HELPERS_SPECIFIER as ew}from"document360-engine";var pl=`from '${ew.replace(/[.*+?^${}()|[\]\\/]/g,"\\$&")}'`,Xy="0.2.25";function zr(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 WC=/^([ \t]*)await\s+([^\n;]+?)\.screenshot\(\{\s*path:\s*PLACEHOLDER\.saveTo\s*(?:,\s*fullPage:\s*(?:true|false)\s*)?,?\s*\}\)\s*;?[ \t]*$/m,BC=/^[ \t]*await\s+dumpAnnotations\(\s*page\s*,\s*PLACEHOLDER\s*\)\s*;?[ \t]*\r?\n?/m,tw="(?:'([^']+)'|\"([^\"]+)\"|`([^`]+)`)",HC=new RegExp(`^page\\s*\\.\\s*locator\\(\\s*${tw}\\s*\\)$`),nw=e=>e[1]??e[2]??e[3]??null,GC=/^[A-Za-z_$][\w$]*$/;function qC(e,t){let o=new RegExp(`\\bconst\\s+${t}\\s*=\\s*page\\s*\\.\\s*locator\\(\\s*${tw}\\s*\\)\\s*;`).exec(e);return o?nw(o):null}function VC(e,t){let n=t.trim();if(n==="page")return null;let o=HC.exec(n);if(o){let r=nw(o);return r?{selector:r}:{unresolved:!0}}if(GC.test(n)){let r=qC(e,n);return r?{selector:r}:{unresolved:!0}}return{unresolved:!0}}function ow(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=WC.exec(e);if(!n)return null;let[o,r="",s=""]=n,i=VC(e,s);if(i===null)return null;if("unresolved"in i)return{unresolved:s.trim()};let a=/^([ \t]*)saveTo:\s*.+,[ \t]*$/m.exec(e);if(!a)return null;let l=i.selector.includes("'")?'"':"'",c=e.replace(a[0],`${a[0]}
|
|
323
|
+
${a[1]??" "}clipTo: ${l}${i.selector}${l},`);return c=c.replace(o,`${r}await captureShot(page, PLACEHOLDER);`),c=c.replace(BC,""),c=c.replace(new RegExp(`\\bdumpAnnotations\\b(?=[^\\n]*${pl})`),"captureShot"),new RegExp(pl).test(c)&&!new RegExp(`\\bcaptureShot\\b[^\\n]*${pl}`).test(c)&&(c=c.replace(new RegExp(`import \\{([^}]*)\\} ${pl}`),(p,m)=>`import {${m.replace(/\s*$/,"")}, captureShot } from '${ew}'`)),{next:c,selector:i.selector}}function KC(e){try{return Jy(e).filter(t=>t.endsWith(".spec.ts")).some(t=>{try{let n=ow(Qy(Zy(e,t),"utf8"));return n!==null&&!("unresolved"in n)}catch{return!1}})}catch{return!1}}function YC(e){let t=MC(e)?.captureDir??UC;return OC(t)?t:_C(e,t)}function rw(e,t){let n={migrated:[],skipped:[]},o=YC(e);if(!IC(o))return n;let r=t?.captureVersion===void 0?Nt():t.captureVersion;if(!zr(r,Xy))return KC(o)?{...n,heldBackForCapture:{installed:r,required:Xy}}:n;let s;try{s=Jy(o).filter(i=>i.endsWith(".spec.ts"))}catch{return n}for(let i of s.sort()){let a=i.slice(0,-8),l=Zy(o,i);try{let c=Qy(l,"utf8"),p=ow(c);if(p===null)continue;if("unresolved"in p){n.skipped.push({id:a,receiver:p.unresolved});continue}LC(l,p.next,"utf8"),n.migrated.push(a)}catch{}}return n}function sw(e){if(e.heldBackForCapture){let{installed:n,required:o}=e.heldBackForCapture;return`\u26A0 Some capture specs need a fix that requires ${FC} ${o}+ (${n?`you have ${n}`:"not found on this machine"}). Until then their callouts may sit in the wrong place on cropped screenshots.
|
|
324
324
|
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(`
|
|
325
|
-
`)}function
|
|
326
|
-
`):null}function
|
|
327
|
-
`))||o.push(r+1));return o}function
|
|
325
|
+
`)}function Ee(e,t,n){return`${e}${n?` ${n}`:""}${t?` ${t}`:""}`}function qt(e){if(e.length===0)return;let t=e.map(r=>r.replace(/\\/g,"/"));if(t.length===1)return t[0];let n=r=>r.split("/").slice(0,-1).join("/"),o=n(t[0]);if(o!=="")return t.every(r=>n(r)===o)?o:void 0}Yr();var hw=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function iw(e){let t=e.includes("--detail")||e.includes("-d"),n=e.find(o=>o!=="--detail"&&o!=="-d");return{mode:"list",scope:n?hw(n):void 0,...t?{detail:!0}:{}}}function ii(e){let t=(e[0]??"").toLowerCase();if(t==="capture")return{mode:"capture",rest:e.slice(1)};if(t==="annotate")return{mode:"annotate",rest:e.slice(1)};if(t==="verify"||t==="review")return{mode:"verify",rest:e.slice(1)};if(t==="checklist"||t==="setup")return{mode:"checklist"};if(t==="list")return iw(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 iw(o.slice(1));let r=o[0];return r?r==="--all"?{mode:"all",setup:n}:/[\\/]/.test(r)||r.endsWith(".md")?{mode:"scope",scope:hw(r),setup:n}:{mode:"single",id:r}:{mode:"list",picker:!0}}function Ke(e,t,n){let o=co(e),r=o?.captureDir??wl,s=o?.outputDir??Ud,i=(m,$)=>ml(m)?gl(m,$):yl(e,m,$),a=Fn(e),l=n?.captureVersion===void 0?Nt():n.captureVersion,c=zr(l,yw),p=ul(e);return cw(e,{scope:t}).map(({id:m,file:$})=>{let w=i(r,`${m}.spec.ts`),C=null;if(lw(w))try{C=Md(w,"utf8")}catch{}let S=uw(e,s),A=tP(S,m),R=ZC(A),D=eP(A),W=C===null?null:Pd(a,m,C,p),H=a.shots[m]?.review,J=R&&QC(H,A.annotatedMtimeMs)?H:void 0,G=C!==null&&iP(C),K=R&&J?.verdict==="ok"?"verified":R&&J?.verdict==="rejected"?"rejected":R?"annotated":D?"captured":C===null?"placeholder":G||W?.outcome==="skipped"?"blocked":W?.outcome==="failed"?"broken":"spec",ne=C===null?void 0:mw(C),oe=G?lP(C):W?.reason,Re=G?"testid":W?.outcome==="skipped"?Cd(W.reason):void 0,le=C===null?[]:aP(e,C);return{id:m,file:$,state:K,...ne?{mutates:ne.mutates,...ne.declared?{}:{undeclared:!0}}:{},...C!==null&&Nd(C).length>0?{unguardedWaits:Nd(C)}:{},...C!==null&&Ed(C).length>0?{unverifiedForce:Ed(C)}:{},...C!==null&&Dd(C).length>0?{handRolled:Dd(C)}:{},...C!==null&&Id(C).length>0?{stalePause:Id(C)}:{},...C!==null&&c&&jd(C).length>0?{bareGoto:jd(C)}:{},...le.length>0?{staleAnchor:le}:{},...K==="blocked"||K==="broken"?{...oe?{reason:oe}:{},...Re?{blockedBy:Re}:{}}:{},...K==="rejected"?{...J?.reason?{reason:J.reason}:{},...J?.repaired?{repaired:!0}:{}}:{}}})}function rP(e){let t=co(e)?.outputDir??Ud;return XC(uw(e,t))}function Xo(e){let t=rP(e),n=co(e)?.outputDir??Ud,o=[];t>0&&o.push(`\u2195 Tidied ${t} screenshot file${t===1?"":"s"} into ${n}/{${nP},${oP}} \u2014 annotated/ is what publishes, raw/ is the pre-annotation intermediate.`);let r=sw(rw(e));return r&&o.push(r),o.length>0?o.join(`
|
|
326
|
+
`):null}function Qo(e,t){let n=co(e)?.captureDir??wl,o=ml(n)?gl(n,`${t}.spec.ts`):yl(e,n,`${t}.spec.ts`);try{return Md(o,"utf8")}catch{return null}}function fw(e,t){let n=co(e)?.captureDir??wl;return lw(ml(n)?gl(n,`${t}.spec.ts`):yl(e,n,`${t}.spec.ts`))}function sP(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 mw(e){let t=e.split(/\r?\n/),n=t.findIndex(a=>/^\s*\/\/\s*CAPTURE-SAFETY:\s*(readonly|mutates)\b/i.test(a)),o=n>=0?/^\s*\/\/\s*CAPTURE-SAFETY:\s*(readonly|mutates)\b[\s—:–-]*(.*)$/i.exec(t[n]):null;if(o){let a=sP(t,n,o[2]??"");return{mutates:o[1].toLowerCase()==="mutates",declared:!0,what:a||void 0}}let r=/setInputFiles/.test(e),s=/\{\s*name:\s*['"][^'"]*\b(create|import|save|apply|confirm|delete|submit|send|mint)\b[^'"]*['"][^}]*\}\s*\)\s*\.click\(/i.test(e),i=/\.fill\(/.test(e);return{mutates:r||i&&s,declared:!1}}function iP(e){return/(^|\n)\s*test\.skip\s*\(\s*['"`]/.test(e)}function gw(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 aP(e,t){let n=[];for(let o of gw(t))JC(e,o.file,o.anchor)===!1&&n.push(o.testid??o.file??"unnamed request");return[...new Set(n)]}function lP(e){let{testid:t,file:n}=gw(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 ai(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 Ed(e,t=10){let n=ai(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(`
|
|
327
|
+
`))||o.push(r+1));return o}function Nd(e){let t=[],n=ai(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 Dd(e){let t=[];for(let[n,o]of ai(e).entries())(/\.screenshot\s*\(/.test(o)||/\bdumpAnnotations\s*\(/.test(o))&&t.push(n+1);return t}var yw="0.2.28";function jd(e){let t=[];for(let[n,o]of ai(e).entries())/\.goto\s*\(/.test(o)&&t.push(n+1);return t}function Id(e,t=6){let n=ai(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(`
|
|
328
328
|
`);if(!/test\.skip\s*\(/.test(i)||!/\.count\s*\(\s*\)/.test(i))continue;let a=n.slice(Math.max(0,r-t),r+1).join(`
|
|
329
|
-
`);/\.waitFor\s*\(|Promise\.race\s*\(|waitForFunction\s*\(|waitForSelector\s*\(/.test(a)||o.push(r+1)}return o}function
|
|
330
|
-
`)}function
|
|
331
|
-
`)}var HS={placeholder:"\u25CB",spec:"\u25D0",blocked:"\u2298",broken:"\u2717",captured:"\u25CF",annotated:"\u25C8",verified:"\u2714",rejected:"\u2691"},GS={placeholder:F.gray,spec:F.yellow,blocked:F.cyan,broken:F.red,captured:F.yellow,annotated:F.blue,verified:F.green,rejected:F.magenta},qS=` ${F.green("\u2714 verified")} ${F.blue("\u25C8 to verify")} ${F.yellow("\u25CF to annotate")} ${F.yellow("\u25D0 ready")} ${F.magenta("\u2691 rejected")} ${F.cyan("\u2298 blocked")} ${F.red("\u2717 broken")} ${F.gray("\u25CB to spec")}`;function V(e,t=n=>n){return`${t(e)} `}function Mr(e){return e.replace(/\s+/g," ").trim().replace(/^Prerequisites? not met[:—-]?\s*/i,"")}function Qa(e){let t=Mr(e),n=/^(.*?[a-z0-9)"'”’])\.(?:\s|$)/i.exec(t);return(n?n[1]:t).trim()}function qs(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=Qa(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 Sy(e){let t=qs(e);if(t.length===0)return[];let n=t.filter(s=>s.blockedBy==="data"),o=t.filter(s=>s.blockedBy==="testid"),r=[""];if(n.length>0){let s=n.reduce((a,l)=>a+l.ids.length,0);r.push(` ${F.bold("Stage this data")} ${F.gray(`\u2014 unblocks ${s} shot${s===1?"":"s"} in ${n.length} action${n.length===1?"":"s"}`)}`);let i=8;for(let a of n.slice(0,i)){let l=dn(a.reason,86);r.push(` ${F.cyan(to(`${a.ids.length}\xD7`,4))} ${l[0]??""}`);for(let p of l.slice(1))r.push(` ${p}`);let c=a.ids.slice(0,4).join(" \xB7 ");r.push(F.gray(` ${c}${a.ids.length>4?` \xB7 +${a.ids.length-4} more`:""}`))}n.length>i&&r.push(F.gray(` \u2026 ${n.length-i} more staging action${n.length-i===1?"":"s"} \u2014 /screenshot list --detail`))}if(o.length>0){let s=o.reduce((i,a)=>i+a.ids.length,0);r.push(` ${V("\u2298",F.cyan)}${s} shot${s===1?"":"s"} need${s===1?"s":""} a data-testid from your developers \u2014 ${F.bold("/screenshot checklist")} builds the hand-off.`)}return r}function ad(e){if(e.length===0)return[];let t=e.slice(0,6),n=e.length;return["",` ${V("\u26A0",F.yellow)}${n} screenshot marker${n===1?"":"s"} will be ignored \u2014 ${n===1?"it is":"they are"} not shaped the way the publish step needs`+F.gray(`, so ${n===1?"that picture":"those pictures"} would never be taken`),...t.map(o=>F.gray(` ${o.file}:${o.line} \u2014 ${o.reason}`)),...n>t.length?[F.gray(` \u2026and ${n-t.length} more`)]:[],F.gray(" Usually a reviewer comment wrapped around it. A marker must start its own line and carry an id:.")]}function Cy(e,t){let n=e.filter(i=>(i.staleAnchor?.length??0)>0);if(n.length===0)return[];let o=[...new Set(n.flatMap(i=>i.staleAnchor))],r=o.length,s=["",` ${V("\u26A0",F.yellow)}${r} selector request${r===1?"":"s"} quote${r===1?"s":""} source code that has since changed`+F.gray(" \u2014 your developers would go looking for something that isn't there any more"),F.gray(` Refresh the hand-off before sending it: ${F.bold("/screenshot checklist")}`)];return t&&s.push(F.gray(` ${o.slice(0,8).join(" \xB7 ")}${r>8?` \xB7 +${r-8} more`:""}`)),s}function Py(e,t,n){let o=e.filter(p=>(p.unguardedWaits?.length??0)>0),r=e.filter(p=>p.undeclared),s=e.filter(p=>(p.handRolled?.length??0)>0),i=e.filter(p=>(p.stalePause?.length??0)>0),a=e.filter(p=>(p.bareGoto?.length??0)>0);if(o.length===0&&r.length===0&&s.length===0&&i.length===0&&a.length===0)return[];let l=["",` ${V("\u26A0",F.yellow)}Some specs were written before later reliability fixes:`],c=(p,m)=>` ${p.slice(0,8).map(m).join(" \xB7 ")}${p.length>8?` \xB7 +${p.length-8} more`:""}`;if(o.length>0){let p=o.length;l.push(F.gray(` ${p} crash${p===1?"es":""} instead of telling you what to stage when the data ${p===1?"it needs":"they need"} is missing`)),t&&l.push(F.gray(c(o,m=>`${m.id}:${m.unguardedWaits.join(",")}`)))}if(a.length>0){let p=a.length;l.push(F.gray(` ${p} open${p===1?"s":""} pages the slow way, so ${p===1?"it stalls":"they stall"} for a minute and give up when several shots run at once`)),t&&l.push(F.gray(c(a,m=>`${m.id}:${m.bareGoto.join(",")}`)))}if(i.length>0){let p=i.length;l.push(F.gray(` ${p} decide${p===1?"s":""} "the data is missing" from a fixed pause, so data you HAVE staged can read as absent`)),t&&l.push(F.gray(c(i,m=>`${m.id}:${m.stalePause.join(",")}`)))}if(s.length>0){let p=s.length;l.push(F.gray(` ${p} take${p===1?"s":""} ${p===1?"its":"their"} own screenshot instead of the one call that positions the callouts too \u2014 on a cropped shot the numbers land in the wrong places, and nothing reports it`)),t&&l.push(F.gray(c(s,m=>`${m.id}:${m.handRolled.join(",")}`)))}if(r.length>0){let p=r.length,m=r.filter($=>$.mutates).length;l.push(F.gray(` ${p} do${p===1?"es":""} not say whether ${p===1?"it changes":"they change"} data in your app`+(m>0?`, so ${m===1?"one is":`${m} are`} left out of bulk runs to be safe`:""))),t&&l.push(F.gray(c(r,$=>$.id)))}return n?.commandInLead||l.push(F.gray(` Re-write them all with the current rules: ${F.bold("/screenshot author --all")}`)),l}function Ty(e){let t=e.filter(n=>(n.unverifiedForce?.length??0)>0);return t.length===0?[]:["",` ${V("\u26A0",F.red)}${t.length} spec${t.length===1?"":"s"} force-click past Playwright's safety checks without asserting the result`+F.gray(" \u2014 if the click lands on nothing, the shot photographs the unchanged screen"),F.gray(` ${t.slice(0,6).map(n=>`${n.id}:${n.unverifiedForce.join(",")}`).join(" \xB7 ")}${t.length>6?` \xB7 +${t.length-6} more`:""}`),F.gray(` Re-author to check what the click did: ${F.bold("/screenshot author <id>")}`)]}var Ha=(e,t)=>e.length>=t?e:e+" ".repeat(t-e.length),to=(e,t)=>e.length>=t?e:" ".repeat(t-e.length)+e;function Ay(e,t){let n=e.replace(/\\/g,"/"),o=t.replace(/\\/g,"/").replace(/\/+$/,"");o&&(n===o||n.startsWith(`${o}/`))&&(n=n.slice(o.length+1));let r=n.split("/").filter(Boolean);return r.length>1?r[0]:""}var VS=new Set(["and","or","of","the","to","a","an","in","on","for","with","vs"]),KS=new Set(["ai","api","cli","ui","ux","url","id","http","https","json","xml","sdk","csv","pdf","oauth","sso","mfa","io","faq"]);function YS(e){return e.replace(/[-_]+/g," ").trim().split(/\s+/).filter(Boolean).map((n,o)=>{let r=n.toLowerCase();return KS.has(r)?r.toUpperCase():o>0&&VS.has(r)?r:r.charAt(0).toUpperCase()+r.slice(1)}).join(" ")}function ed(e){if(!e)return{num:"",name:"(docs root)"};let t=/^(\d+)[-_](.+)$/.exec(e);return{num:t?t[1]:"",name:YS(t?t[2]:e)}}function zS(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).pop()??e}function hy(e,t,n){let o=t>0?Math.round(e/t*n):0;return F.green("\u2588".repeat(o))+F.gray("\u2591".repeat(Math.max(0,n-o)))}function XS(e,t){let n=t>0?Math.round(e/t*100):0,o=to(`${n}%`,4);return n===100?F.green(o):n>0?F.yellow(o):F.gray(o)}function Ey(e,t){let n=new Map;for(let o of e){let r=Ay(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 ld(e,t){let n=T=>e.filter(R=>R.state===T).length,o=n("captured"),r=n("placeholder"),s=n("spec"),i=n("annotated"),a=n("blocked"),l=n("broken"),c=n("rejected"),p=e.filter(T=>T.state==="spec"&&T.mutates).length,m=s>p,$=e.filter(T=>(T.unguardedWaits?.length??0)>0||(T.bareGoto?.length??0)>0).length,w=e.filter(T=>(T.stalePause?.length??0)>0||(T.handRolled?.length??0)>0).length,C=s>0||a>0||l>0,S=(T,R="")=>Te(T,R,t);return o>0?{key:"annotate",cmd:S("/screenshot annotate")}:r>0?{key:"toSpec",cmd:t?`/screenshot author ${t}`:"/screenshot author --all"}:$>0&&C?{key:"crashy",cmd:t?`/screenshot author ${t}`:"/screenshot author --all"}:w>0&&C?{key:"wrongOutput",cmd:t?`/screenshot author ${t}`:"/screenshot author --all"}:s>0&&(m||i===0)?{key:"ready",cmd:S("/screenshot capture")}:i>0&&s>0?{key:"verify",cmd:S("/screenshot verify")}:a>0?{key:"blocked",cmd:S("/screenshot capture","--blocked")}:l>0?{key:"broken",cmd:`/screenshot ${e.find(T=>T.state==="broken").id}`}:i>0?{key:"verify",cmd:S("/screenshot verify")}:c>0?{key:"rejected",cmd:S("/screenshot capture","--failed")}:{key:"done",cmd:t?`/push ${t}`:"/push"}}function QS(e,t,n=[]){let o=(re,be)=>re.filter(Ae=>Ae.state===be).length,r=e.length,s=o(e,"verified"),i=o(e,"annotated"),a=o(e,"captured"),l=o(e,"rejected"),c=o(e,"spec"),p=o(e,"blocked"),m=o(e,"broken"),$=o(e,"placeholder"),w=new Set(e.map(re=>re.file)).size,C=Ey(e,t),S=[];S.push(` ${F.bold("Screenshots")} ${F.green(`${s}/${r} verified`)} ${F.gray("\xB7")} ${i>0?F.blue(`${i} to verify`):F.gray("0 to verify")}`+(a>0?` ${F.gray("\xB7")} ${F.yellow(`${a} to annotate`)}`:"")+(l>0?` ${F.gray("\xB7")} ${F.magenta(`${l} rejected`)}`:"")+` ${F.gray("\xB7")} ${c>0?F.yellow(`${c} ready`):F.gray("0 ready")}`+(p>0?` ${F.gray("\xB7")} ${F.cyan(`${p} blocked`)}`:"")+(m>0?` ${F.gray("\xB7")} ${F.red(`${m} broken`)}`:"")+` ${F.gray("\xB7")} ${$>0?F.red(`${$} to spec`):F.gray("0 to spec")} `+F.gray(`across ${w} article${w===1?"":"s"}`));let T=r>0?Math.round(s/r*100):0;S.push(` [${hy(s,r,32)}] ${F.bold(`${T}%`)}`),S.push("");let R=C.map(([re])=>ed(re)),D=Math.min(32,Math.max(7,...R.map(re=>re.name.length))),U=re=>re.length>D?`${re.slice(0,D-1)}\u2026`:Ha(re,D),H=[...a>0?[{head:"To annotate",w:11,state:"captured",color:F.yellow}]:[],...i>0?[{head:"To verify",w:9,state:"annotated",color:F.blue}]:[],...l>0?[{head:"Rejected",w:8,state:"rejected",color:F.magenta}]:[],{head:"Ready",w:5,state:"spec",color:F.yellow},...p>0?[{head:"Blocked",w:7,state:"blocked",color:F.cyan}]:[],...m>0?[{head:"Broken",w:6,state:"broken",color:F.red}]:[],{head:"To spec",w:7,state:"placeholder",color:F.red}];S.push(F.gray(` ${Ha("#",2)} ${Ha("Chapter",D)} ${to("Verified",8)} ${H.map(re=>to(re.head,re.w)).join(" ")} Progress`));for(let[re,[,be]]of C.entries()){let Ae=o(be,"verified"),Ze=be.length,{num:go,name:Ee}=R[re],je=Ae===Ze,st=U(Ee),ln=H.map(Nt=>{let yo=o(be,Nt.state);return yo>0?Nt.color(to(String(yo),Nt.w)):F.gray(to("\u2014",Nt.w))}).join(" ");S.push(` ${F.cyan(Ha(go,2))} ${je?F.green(st):Ae>0?st:F.gray(st)} ${je?F.green(to(`${Ae}/${Ze}`,8)):to(`${Ae}/${Ze}`,8)} ${ln} ${hy(Ae,Ze,10)} ${XS(Ae,Ze)}`)}S.push("");let J=m>0?` ${F.gray("\xB7")} ${m} spec${m===1?"":"s"} broken \u2014 ${F.bold(`/screenshot ${e.find(re=>re.state==="broken").id}`)} re-authors ${m===1?"it":"the first"}`:"",G=e.filter(re=>re.state==="spec"&&re.mutates).length,K=c>G,ne=e.filter(re=>(re.unguardedWaits?.length??0)>0||(re.bareGoto?.length??0)>0).length,oe=e.filter(re=>(re.stalePause?.length??0)>0||(re.handRolled?.length??0)>0).length,ve=c>0||p>0||m>0,ae=!1,pe=ld(e).key;if(pe==="annotate")S.push(` ${V("\u25C8",F.blue)}${a} shot${a===1?"":"s"} taken but not drawn on \u2014 run ${F.bold("/screenshot annotate")}`+F.gray(` \u2014 no browser, seconds; the callouts are what make ${a===1?"it":"them"} publishable`)+J);else if(pe==="toSpec")S.push(` ${V("\u2192",F.yellow)}${$} placeholder${$===1?"":"s"} still need a spec \u2014 run ${F.bold("/screenshot author --all")}${J}`);else if(pe==="crashy")ae=!0,S.push(` ${V("\u2192",F.yellow)}${ne} spec${ne===1?"":"s"} would crash mid-run \u2014 re-write ${ne===1?"it":"them"} first: ${F.bold("/screenshot author --all")}`+F.gray(` \xB7 then ${F.bold("/screenshot capture")} (no browser time wasted on ${ne===1?"a shot":"shots"} that can't finish)`)+J);else if(pe==="wrongOutput")ae=!0,S.push(` ${V("\u2192",F.yellow)}${oe} spec${oe===1?"":"s"} would shoot the wrong thing \u2014 re-write ${oe===1?"it":"them"} first: ${F.bold("/screenshot author --all")}`+F.gray(` \xB7 then ${F.bold("/screenshot capture")} (a false skip or a misplaced callout costs the same browser time as a good shot)`)+J);else if(pe==="ready"){let re=G>0?F.gray(` \u2014 ${c-G} in one go; ${G} write${G===1?"s":""} real data and run${G===1?"s":""} one at a time`):"";S.push(` ${V("\u2192",F.yellow)}${c} spec${c===1?"":"s"} ready to capture \u2014 run ${F.bold("/screenshot capture")}${re}${J}`)}else if(pe==="verify"&&c>0)S.push(` ${V("\u2192",F.blue)}${i} shot${i===1?"":"s"} awaiting verification \u2014 run ${F.bold("/screenshot verify")}`+F.gray(" \u2014 no browser needed")+F.gray(` \xB7 ${c} ready spec${c===1?"":"s"} write real data, so ${c===1?"it runs":"each runs"} only when named: /screenshot capture <id>`)+J);else if(pe==="blocked")S.push(` ${V("\u2192",F.cyan)}${p} shot${p===1?"":"s"} blocked \u2014 stage the data below, then ${F.bold("/screenshot capture --blocked")}${J}`);else if(pe==="broken")S.push(` ${V("\u2192",F.red)}${m} spec${m===1?"":"s"} broken \u2014 ${F.bold(`/screenshot ${e.find(re=>re.state==="broken").id}`)} re-authors ${m===1?"it":"the first"} (re-capturing fails the same way)`);else if(pe==="verify")S.push(` ${V("\u2192",F.blue)}${i} shot${i===1?"":"s"} awaiting verification \u2014 run ${F.bold("/screenshot verify")}`+F.gray(" \u2014 it checks each picture against what its article needs (no browser, no re-capture)"));else if(pe==="rejected"){let re=e.filter(be=>be.state==="rejected"&&be.repaired).length;S.push(` ${V("\u2691",F.magenta)}${l} shot${l===1?"":"s"} failed review \u2014 `+(re>0?`${re} spec${re===1?"":"s"} already repaired; re-capture with ${F.bold("/screenshot capture --failed")}`:`see the reasons below, then ${F.bold("/screenshot capture --failed")}`))}else S.push(` ${V("\u2713",F.green)}all ${r} verified \u2014 ${F.bold("/push")} embeds them in the articles`);if(s>0&&s<r){let re=C.filter(([,be])=>be.every(Ae=>Ae.state!=="verified")).map(([be])=>{let{num:Ae,name:Ze}=ed(be);return Ae?`${Ae} ${Ze}`:Ze});re.length>0&&S.push(F.gray(` Furthest behind: ${re.slice(0,5).join(" \xB7 ")}${re.length>5?" \u2026":""} (0% verified)`))}return S.push(...Sy(e),...Ty(e),...Py(e,!1,{commandInLead:ae}),...Cy(e,!1),...ad(n)),S.push(""),S.push(F.gray(" Drill in: /screenshot list <chapter#> \xB7 /screenshot list --detail (all)")),S}function JS(e,t,n,o=[]){let r=new Set(e.map(c=>c.file)),s=e.filter(c=>c.state==="verified").length,i=e.filter(c=>c.state==="annotated").length,a=e.filter(c=>c.state==="captured").length,l=[` ${F.bold("Screenshots")}: ${e.length} placeholder${e.length===1?"":"s"} across ${r.size} article${r.size===1?"":"s"} \xB7 ${F.green(`${s} verified`)}${i>0?F.blue(` \xB7 ${i} to verify`):""}${a>0?F.yellow(` \xB7 ${a} to annotate`):""}${n?F.gray(` \xB7 scope ${n}`):""}`,""];for(let[c,p]of Ey(e,t)){let m=p.filter(T=>T.state==="verified").length,{num:$,name:w}=ed(c),C=$?`${$} \xB7 ${w}`:w;l.push(` ${F.bold(C)} ${F.gray(`(${m}/${p.length})`)}`);let S=new Map;for(let T of p){let R=zS(T.file),D=S.get(R)??[];S.has(R)||S.set(R,D),D.push(T)}for(let T of[...S.keys()].sort()){l.push(F.gray(` ${T}`));for(let R of S.get(T)){let D=GS[R.state];if(l.push(` ${V(HS[R.state],D)}${D(R.id)}`),(R.state==="blocked"||R.state==="broken"||R.state==="rejected")&&R.reason){for(let U of dn(Mr(R.reason),84))l.push(F.gray(` ${U}`));R.state==="rejected"&&l.push(F.gray(` ${R.repaired?"spec repaired \u2014 re-capture to confirm":"spec not yet repaired"}`))}}}}return l.push(...Sy(e),...Ty(e),...Py(e,!0),...Cy(e,!0),...ad(o)),l.push("",qS),l}function Ja(e,t){let n=t?.scope,o=t?.markerProblems??[];if(e.length===0)return[n?`No screenshot placeholders under ${n}.`:"No screenshot placeholders found in the docs.",...ad(o)];let r=t?.docsDir??sd;return t?.detail||n?JS(e,r,n,o):QS(e,r,o)}function cd(e,t){if(!t||!/^\d+$/.test(t))return t;let n=no(e)?.docsDir??sd,o=String(Number(t));for(let{file:r}of my(e)){let s=Ay(r,n),i=/^(\d+)/.exec(s);if(i&&String(Number(i[1]))===o)return s}return t}function Ny(e,t){let r=e.map(a=>" ".repeat(a.depth)+a.label),s=Math.max(0,...e.map((a,l)=>a.note?Ba(r[l]):0)),i=Math.min(s,Math.max(0,t-2-24));return e.map((a,l)=>{let c=r[l];if(!a.note)return{head:c,note:""};let p=Math.max(2,i+2-Ba(c)),m=a.note.trim(),$=t-Ba(c)-p;return{head:c+" ".repeat(p),note:$>1&&Ba(m)>$?`${m.slice(0,$-1)}\u2026`:m}})}function ZS(e){let t=e.replace(/\\/g,"/").split("/").filter(Boolean),n=t.pop()??e;return{category:t.pop()??"(docs root)",article:n}}function _r(e,t,n){let o=new Map;for(let s of t){let{category:i,article:a}=ZS(s.file),l=o.get(i)??new Map;o.set(i,l);let c=l.get(a)??[];l.set(a,c),c.push(s)}let r=s=>n!=="capture"||!s.mutates;for(let s of[...o.keys()].sort()){let i=o.get(s),a=[...i.values()].flat().filter(r).map(c=>c.id),l=a.length>0;l&&e.push({kind:"category",action:n,label:`${s} (${a.length})`,ids:a,depth:1});for(let c of[...i.keys()].sort()){let p=i.get(c),m=p.filter(r).map(C=>C.id),$=m.length>0;$&&e.push({kind:"article",action:n,label:`${c} (${m.length})`,ids:m,depth:l?2:1});let w=(l?1:0)+($?1:0)+1;for(let C of p){let S=n==="capture"&&C.mutates?" \u26A0 creates real data \u2014 runs only alone":void 0;e.push({kind:"shot",action:n,label:C.id,ids:[C.id],depth:w,...S?{note:S}:{}})}}}}function Yu(e){return e?Mr(e):""}function ud(e,t,n,o=[]){let r=t.filter(i=>!i.mutates);r.length>1&&e.push({kind:"all",action:"capture",label:`Retry ${r.length} blocked shots (Prerequisites not met \u2014 Stage the data first)`,ids:r.map(i=>i.id),depth:0});for(let i of[...t].sort((a,l)=>a.id.localeCompare(l.id)))e.push({kind:"shot",action:"capture",label:i.id,ids:[i.id],depth:1,note:` \u2298 ${Yu(i.reason)}`});n.length>1&&e.push({kind:"all",action:"author",label:`Re-author ${n.length} broken specs`,ids:n.map(i=>i.id),depth:0});for(let i of[...n].sort((a,l)=>a.id.localeCompare(l.id)))e.push({kind:"shot",action:"author",label:i.id,ids:[i.id],depth:1,note:` \u2717 re-authors \u2014 ${Yu(i.reason)}`});let s=o.filter(i=>!i.mutates);s.length>1&&e.push({kind:"all",action:"capture",label:`Re-capture ${s.length} shots that failed review`,ids:s.map(i=>i.id),depth:0});for(let i of[...o].sort((a,l)=>a.id.localeCompare(l.id))){let a=i.repaired?"re-captures":"re-captures (spec not yet repaired)";e.push({kind:"shot",action:"capture",label:i.id,ids:[i.id],depth:1,note:` \u2691 ${a} \u2014 ${Yu(i.reason)}`})}}function Dy(e){let t=e.filter(i=>i.state==="placeholder"),n=e.filter(i=>i.state==="spec"),o=[];t.length>1&&o.push({kind:"all",action:"author",label:`Author all ${t.length} remaining specs`,ids:t.map(i=>i.id),depth:0}),_r(o,t,"author");let r=n.filter(i=>!i.mutates);r.length>1&&o.push({kind:"all",action:"capture",label:`Capture all ${r.length} ready specs`,ids:r.map(i=>i.id),depth:0}),_r(o,n,"capture");let s=e.filter(i=>i.state==="captured");return s.length>1&&o.push({kind:"all",action:"annotate",label:`Draw the callouts on all ${s.length} shots`,ids:s.map(i=>i.id),depth:0}),_r(o,s,"annotate"),ud(o,e.filter(i=>i.state==="blocked"),e.filter(i=>i.state==="broken"),e.filter(i=>i.state==="rejected")),o}var td=["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(`
|
|
332
|
-
`);function
|
|
333
|
-
`),"",...r.length>0?["REPAIR: these already have a spec, and it FAILED its last capture. Read the existing spec","first and fix the named failure specifically; do not re-emit the same locator and hope. A",'"strict mode violation" means the locator matched 2+ elements (scope it to a stable container',"or take .first()); a click timeout means the element was absent or unreachable (if the data","simply is not staged, the spec must test.skip with a reason naming what to stage, not time out).",...r.map(i),""]:[],...s.length>0?["REPAIR: these already have a spec and it SKIPPED. Treat each reason as SUSPECT, not as proof","the spec is right: a FALSE skip is indistinguishable from a true one from inside the spec, and","you are being asked to re-author rather than to stage. Check TWO things before concluding a","spec needs no change. (1) Is the target RENDERED? A collapsed tree node, unopened accordion,","inactive tab, virtualised list or page 2 of a table keeps children out of the DOM, so the count","is zero for data one click away, so expanding is a step to SCRIPT. (2) Is the selector too narrow?","If you filtered past a decoy, count the unnarrowed set and put the number in the reason. A spec","that satisfies every rule and still cannot reach its target is NOT correct.",...s.map(i),""]:[],...a.flatMap(l=>
|
|
334
|
-
`)}async function
|
|
335
|
-
`),display:`/screenshot ${o.id}`}}if(o.mode==="capture"||o.mode==="annotate"||o.mode==="verify"||o.mode==="checklist")return{kind:"continue"};let
|
|
336
|
-
`),a=o.mode==="scope"?`/screenshot ${o.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:i,display:a}}import{readDocsPlan as
|
|
329
|
+
`);/\.waitFor\s*\(|Promise\.race\s*\(|waitForFunction\s*\(|waitForSelector\s*\(/.test(a)||o.push(r+1)}return o}function Wd(e,t){let n=p=>`line${p.length===1?"":"s"} ${p.join(", ")}`,o=[],r=t?.captureVersion===void 0?Nt():t.captureVersion,s=zr(r,yw)?jd(e):[];s.length>0&&o.push(`- ${n(s)}: navigates with a bare page.goto(). EVERY navigation must go through gotoResilient (from ${dw}) \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=Nd(e);i.length>0&&o.push(`- ${n(i)}: a .waitFor() whose timeout is not swallowed, so a missing prerequisite hard-fails instead of skipping. Add .catch(() => {}), then read the element and test.skip with a reason.`);let a=Dd(e);a.length>0&&o.push(`- ${n(a)}: takes its own screenshot (or calls dumpAnnotations) instead of captureShot(page, PLACEHOLDER). On a cropped shot that misplaces every callout and nothing errors.`);let l=Id(e);l.length>0&&o.push(`- ${n(l)}: the "data is missing" decision rests on a fixed waitForTimeout, so staged data can read as absent. Give the element a bounded chance to appear first, then count.`);let c=Ed(e);return c.length>0&&o.push(`- ${n(c)}: click({ force: true }) with no assertion that it worked, so a no-op click photographs the unchanged screen. Assert the expected result immediately after, guarded, and skip if it never arrives.`),/CAPTURE-SAFETY:/.test(e)||o.push("- no CAPTURE-SAFETY marker: add exactly one `// CAPTURE-SAFETY: readonly` or `// CAPTURE-SAFETY: mutates \u2014 <what>; cleanup: <how>` at the top."),o}function ww(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 kw(e){return(e??"").trim().replace(/[.\s]+$/,"")}function bw(e,t){let n=co(e)?.captureDir??wl,o=ml(n)?gl(n,`${t}.spec.ts`):yl(e,n,`${t}.spec.ts`);try{return mw(Md(o,"utf8"))}catch{return{mutates:!1,declared:!1}}}var cP=["annotated","verified","rejected"],uP=e=>cP.includes(e);function dP(e){return[...new Set(e.filter(t=>uP(t.state)).map(t=>t.file))].sort()}function kl(e,t){let n=dP(e);if(!t)return n;let o=t.replace(/\\/g,"/").replace(/\/+$/,"");return n.filter(r=>{let s=r.replace(/\\/g,"/");return s===o||s.startsWith(`${o}/`)||s.endsWith(`/${o}`)})}function bl(e,t){let n=e.filter(s=>s.state==="captured");if(n.length===0)return null;let o=Math.max(...n.map(s=>s.id.length)),r=n.length===1;return[`${V("\u26A0",U.yellow)}${n.length} screenshot${r?" has":"s have"} been taken but the callouts aren't drawn on yet, so ${r?"it has":"they have"} no picture to publish:`,...n.map(s=>` ${U.yellow(s.id.padEnd(o))}`),` Publishing without ${r?"it":"them"}. Finish ${r?"it":"them"} first: ${U.bold(Ee("/screenshot annotate","",t))}`].join(`
|
|
330
|
+
`)}function $l(e){let t=e.filter(o=>o.state==="rejected");if(t.length===0)return null;let n=Math.max(...t.map(o=>o.id.length));return[`${V("\u26A0",U.yellow)}${t.length} screenshot${t.length===1?"":"s"} failed verification:`,...t.map(o=>` ${U.magenta(o.id.padEnd(n))} ${U.gray(Qr(o.reason??"no reason recorded"))}`),` Publishing anyway. Fix + re-capture: ${U.bold("/screenshot capture --failed")}`].join(`
|
|
331
|
+
`)}var pP={placeholder:"\u25CB",spec:"\u25D0",blocked:"\u2298",broken:"\u2717",captured:"\u25CF",annotated:"\u25C8",verified:"\u2714",rejected:"\u2691"},hP={placeholder:U.gray,spec:U.yellow,blocked:U.cyan,broken:U.red,captured:U.yellow,annotated:U.blue,verified:U.green,rejected:U.magenta},fP=` ${U.green("\u2714 verified")} ${U.blue("\u25C8 to verify")} ${U.yellow("\u25CF to annotate")} ${U.yellow("\u25D0 ready")} ${U.magenta("\u2691 rejected")} ${U.cyan("\u2298 blocked")} ${U.red("\u2717 broken")} ${U.gray("\u25CB to spec")}`;function V(e,t=n=>n){return`${t(e)} `}function Qr(e){return e.replace(/\s+/g," ").trim().replace(/^Prerequisites? not met[:—-]?\s*/i,"")}function vl(e){let t=Qr(e),n=/^(.*?[a-z0-9)"'”’])\.(?:\s|$)/i.exec(t);return(n?n[1]:t).trim()}function li(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=vl(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 $w(e){let t=li(e);if(t.length===0)return[];let n=t.filter(s=>s.blockedBy==="data"),o=t.filter(s=>s.blockedBy==="testid"),r=[""];if(n.length>0){let s=n.reduce((a,l)=>a+l.ids.length,0);r.push(` ${U.bold("Stage this data")} ${U.gray(`\u2014 unblocks ${s} shot${s===1?"":"s"} in ${n.length} action${n.length===1?"":"s"}`)}`);let i=8;for(let a of n.slice(0,i)){let l=gn(a.reason,86);r.push(` ${U.cyan(lo(`${a.ids.length}\xD7`,4))} ${l[0]??""}`);for(let p of l.slice(1))r.push(` ${p}`);let c=a.ids.slice(0,4).join(" \xB7 ");r.push(U.gray(` ${c}${a.ids.length>4?` \xB7 +${a.ids.length-4} more`:""}`))}n.length>i&&r.push(U.gray(` \u2026 ${n.length-i} more staging action${n.length-i===1?"":"s"} \u2014 /screenshot list --detail`))}if(o.length>0){let s=o.reduce((i,a)=>i+a.ids.length,0);r.push(` ${V("\u2298",U.cyan)}${s} shot${s===1?"":"s"} need${s===1?"s":""} a data-testid from your developers \u2014 ${U.bold("/screenshot checklist")} builds the hand-off.`)}return r}function Bd(e){if(e.length===0)return[];let t=e.slice(0,6),n=e.length;return["",` ${V("\u26A0",U.yellow)}${n} screenshot marker${n===1?"":"s"} will be ignored \u2014 ${n===1?"it is":"they are"} not shaped the way the publish step needs`+U.gray(`, so ${n===1?"that picture":"those pictures"} would never be taken`),...t.map(o=>U.gray(` ${o.file}:${o.line} \u2014 ${o.reason}`)),...n>t.length?[U.gray(` \u2026and ${n-t.length} more`)]:[],U.gray(" Usually a reviewer comment wrapped around it. A marker must start its own line and carry an id:.")]}function vw(e,t){let n=e.filter(i=>(i.staleAnchor?.length??0)>0);if(n.length===0)return[];let o=[...new Set(n.flatMap(i=>i.staleAnchor))],r=o.length,s=["",` ${V("\u26A0",U.yellow)}${r} selector request${r===1?"":"s"} quote${r===1?"s":""} source code that has since changed`+U.gray(" \u2014 your developers would go looking for something that isn't there any more"),U.gray(` Refresh the hand-off before sending it: ${U.bold("/screenshot checklist")}`)];return t&&s.push(U.gray(` ${o.slice(0,8).join(" \xB7 ")}${r>8?` \xB7 +${r-8} more`:""}`)),s}function xw(e,t,n){let o=e.filter(p=>(p.unguardedWaits?.length??0)>0),r=e.filter(p=>p.undeclared),s=e.filter(p=>(p.handRolled?.length??0)>0),i=e.filter(p=>(p.stalePause?.length??0)>0),a=e.filter(p=>(p.bareGoto?.length??0)>0);if(o.length===0&&r.length===0&&s.length===0&&i.length===0&&a.length===0)return[];let l=["",` ${V("\u26A0",U.yellow)}Some specs were written before later reliability fixes:`],c=(p,m)=>` ${p.slice(0,8).map(m).join(" \xB7 ")}${p.length>8?` \xB7 +${p.length-8} more`:""}`;if(o.length>0){let p=o.length;l.push(U.gray(` ${p} crash${p===1?"es":""} instead of telling you what to stage when the data ${p===1?"it needs":"they need"} is missing`)),t&&l.push(U.gray(c(o,m=>`${m.id}:${m.unguardedWaits.join(",")}`)))}if(a.length>0){let p=a.length;l.push(U.gray(` ${p} open${p===1?"s":""} pages the slow way, so ${p===1?"it stalls":"they stall"} for a minute and give up when several shots run at once`)),t&&l.push(U.gray(c(a,m=>`${m.id}:${m.bareGoto.join(",")}`)))}if(i.length>0){let p=i.length;l.push(U.gray(` ${p} decide${p===1?"s":""} "the data is missing" from a fixed pause, so data you HAVE staged can read as absent`)),t&&l.push(U.gray(c(i,m=>`${m.id}:${m.stalePause.join(",")}`)))}if(s.length>0){let p=s.length;l.push(U.gray(` ${p} take${p===1?"s":""} ${p===1?"its":"their"} own screenshot instead of the one call that positions the callouts too \u2014 on a cropped shot the numbers land in the wrong places, and nothing reports it`)),t&&l.push(U.gray(c(s,m=>`${m.id}:${m.handRolled.join(",")}`)))}if(r.length>0){let p=r.length,m=r.filter($=>$.mutates).length;l.push(U.gray(` ${p} do${p===1?"es":""} not say whether ${p===1?"it changes":"they change"} data in your app`+(m>0?`, so ${m===1?"one is":`${m} are`} left out of bulk runs to be safe`:""))),t&&l.push(U.gray(c(r,$=>$.id)))}return n?.commandInLead||l.push(U.gray(` Re-write them all with the current rules: ${U.bold("/screenshot author --all")}`)),l}function Rw(e){let t=e.filter(n=>(n.unverifiedForce?.length??0)>0);return t.length===0?[]:["",` ${V("\u26A0",U.red)}${t.length} spec${t.length===1?"":"s"} force-click past Playwright's safety checks without asserting the result`+U.gray(" \u2014 if the click lands on nothing, the shot photographs the unchanged screen"),U.gray(` ${t.slice(0,6).map(n=>`${n.id}:${n.unverifiedForce.join(",")}`).join(" \xB7 ")}${t.length>6?` \xB7 +${t.length-6} more`:""}`),U.gray(` Re-author to check what the click did: ${U.bold("/screenshot author <id>")}`)]}var fl=(e,t)=>e.length>=t?e:e+" ".repeat(t-e.length),lo=(e,t)=>e.length>=t?e:" ".repeat(t-e.length)+e;function Sw(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 mP=new Set(["and","or","of","the","to","a","an","in","on","for","with","vs"]),gP=new Set(["ai","api","cli","ui","ux","url","id","http","https","json","xml","sdk","csv","pdf","oauth","sso","mfa","io","faq"]);function yP(e){return e.replace(/[-_]+/g," ").trim().split(/\s+/).filter(Boolean).map((n,o)=>{let r=n.toLowerCase();return gP.has(r)?r.toUpperCase():o>0&&mP.has(r)?r:r.charAt(0).toUpperCase()+r.slice(1)}).join(" ")}function Ld(e){if(!e)return{num:"",name:"(docs root)"};let t=/^(\d+)[-_](.+)$/.exec(e);return{num:t?t[1]:"",name:yP(t?t[2]:e)}}function wP(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).pop()??e}function aw(e,t,n){let o=t>0?Math.round(e/t*n):0;return U.green("\u2588".repeat(o))+U.gray("\u2591".repeat(Math.max(0,n-o)))}function kP(e,t){let n=t>0?Math.round(e/t*100):0,o=lo(`${n}%`,4);return n===100?U.green(o):n>0?U.yellow(o):U.gray(o)}function Cw(e,t){let n=new Map;for(let o of e){let r=Sw(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 Hd(e,t){let n=A=>e.filter(R=>R.state===A).length,o=n("captured"),r=n("placeholder"),s=n("spec"),i=n("annotated"),a=n("blocked"),l=n("broken"),c=n("rejected"),p=e.filter(A=>A.state==="spec"&&A.mutates).length,m=s>p,$=e.filter(A=>(A.unguardedWaits?.length??0)>0||(A.bareGoto?.length??0)>0).length,w=e.filter(A=>(A.stalePause?.length??0)>0||(A.handRolled?.length??0)>0).length,C=s>0||a>0||l>0,S=(A,R="")=>Ee(A,R,t);return o>0?{key:"annotate",cmd:S("/screenshot annotate")}:r>0?{key:"toSpec",cmd:t?`/screenshot author ${t}`:"/screenshot author --all"}:$>0&&C?{key:"crashy",cmd:t?`/screenshot author ${t}`:"/screenshot author --all"}:w>0&&C?{key:"wrongOutput",cmd:t?`/screenshot author ${t}`:"/screenshot author --all"}:s>0&&(m||i===0)?{key:"ready",cmd:S("/screenshot capture")}:i>0&&s>0?{key:"verify",cmd:S("/screenshot verify")}:a>0?{key:"blocked",cmd:S("/screenshot capture","--blocked")}:l>0?{key:"broken",cmd:`/screenshot ${e.find(A=>A.state==="broken").id}`}:i>0?{key:"verify",cmd:S("/screenshot verify")}:c>0?{key:"rejected",cmd:S("/screenshot capture","--failed")}:{key:"done",cmd:t?`/push ${t}`:"/push"}}function bP(e,t,n=[]){let o=(re,ve)=>re.filter(Ne=>Ne.state===ve).length,r=e.length,s=o(e,"verified"),i=o(e,"annotated"),a=o(e,"captured"),l=o(e,"rejected"),c=o(e,"spec"),p=o(e,"blocked"),m=o(e,"broken"),$=o(e,"placeholder"),w=new Set(e.map(re=>re.file)).size,C=Cw(e,t),S=[];S.push(` ${U.bold("Screenshots")} ${U.green(`${s}/${r} verified`)} ${U.gray("\xB7")} ${i>0?U.blue(`${i} to verify`):U.gray("0 to verify")}`+(a>0?` ${U.gray("\xB7")} ${U.yellow(`${a} to annotate`)}`:"")+(l>0?` ${U.gray("\xB7")} ${U.magenta(`${l} rejected`)}`:"")+` ${U.gray("\xB7")} ${c>0?U.yellow(`${c} ready`):U.gray("0 ready")}`+(p>0?` ${U.gray("\xB7")} ${U.cyan(`${p} blocked`)}`:"")+(m>0?` ${U.gray("\xB7")} ${U.red(`${m} broken`)}`:"")+` ${U.gray("\xB7")} ${$>0?U.red(`${$} to spec`):U.gray("0 to spec")} `+U.gray(`across ${w} article${w===1?"":"s"}`));let A=r>0?Math.round(s/r*100):0;S.push(` [${aw(s,r,32)}] ${U.bold(`${A}%`)}`),S.push("");let R=C.map(([re])=>Ld(re)),D=Math.min(32,Math.max(7,...R.map(re=>re.name.length))),W=re=>re.length>D?`${re.slice(0,D-1)}\u2026`:fl(re,D),H=[...a>0?[{head:"To annotate",w:11,state:"captured",color:U.yellow}]:[],...i>0?[{head:"To verify",w:9,state:"annotated",color:U.blue}]:[],...l>0?[{head:"Rejected",w:8,state:"rejected",color:U.magenta}]:[],{head:"Ready",w:5,state:"spec",color:U.yellow},...p>0?[{head:"Blocked",w:7,state:"blocked",color:U.cyan}]:[],...m>0?[{head:"Broken",w:6,state:"broken",color:U.red}]:[],{head:"To spec",w:7,state:"placeholder",color:U.red}];S.push(U.gray(` ${fl("#",2)} ${fl("Chapter",D)} ${lo("Verified",8)} ${H.map(re=>lo(re.head,re.w)).join(" ")} Progress`));for(let[re,[,ve]]of C.entries()){let Ne=o(ve,"verified"),tt=ve.length,{num:xo,name:De}=R[re],Le=Ne===tt,at=W(De),hn=H.map(Ot=>{let Ro=o(ve,Ot.state);return Ro>0?Ot.color(lo(String(Ro),Ot.w)):U.gray(lo("\u2014",Ot.w))}).join(" ");S.push(` ${U.cyan(fl(xo,2))} ${Le?U.green(at):Ne>0?at:U.gray(at)} ${Le?U.green(lo(`${Ne}/${tt}`,8)):lo(`${Ne}/${tt}`,8)} ${hn} ${aw(Ne,tt,10)} ${kP(Ne,tt)}`)}S.push("");let J=m>0?` ${U.gray("\xB7")} ${m} spec${m===1?"":"s"} broken \u2014 ${U.bold(`/screenshot ${e.find(re=>re.state==="broken").id}`)} re-authors ${m===1?"it":"the first"}`:"",G=e.filter(re=>re.state==="spec"&&re.mutates).length,K=c>G,ne=e.filter(re=>(re.unguardedWaits?.length??0)>0||(re.bareGoto?.length??0)>0).length,oe=e.filter(re=>(re.stalePause?.length??0)>0||(re.handRolled?.length??0)>0).length,Re=c>0||p>0||m>0,le=!1,he=Hd(e).key;if(he==="annotate")S.push(` ${V("\u25C8",U.blue)}${a} shot${a===1?"":"s"} taken but not drawn on \u2014 run ${U.bold("/screenshot annotate")}`+U.gray(` \u2014 no browser, seconds; the callouts are what make ${a===1?"it":"them"} publishable`)+J);else if(he==="toSpec")S.push(` ${V("\u2192",U.yellow)}${$} placeholder${$===1?"":"s"} still need a spec \u2014 run ${U.bold("/screenshot author --all")}${J}`);else if(he==="crashy")le=!0,S.push(` ${V("\u2192",U.yellow)}${ne} spec${ne===1?"":"s"} would crash mid-run \u2014 re-write ${ne===1?"it":"them"} first: ${U.bold("/screenshot author --all")}`+U.gray(` \xB7 then ${U.bold("/screenshot capture")} (no browser time wasted on ${ne===1?"a shot":"shots"} that can't finish)`)+J);else if(he==="wrongOutput")le=!0,S.push(` ${V("\u2192",U.yellow)}${oe} spec${oe===1?"":"s"} would shoot the wrong thing \u2014 re-write ${oe===1?"it":"them"} first: ${U.bold("/screenshot author --all")}`+U.gray(` \xB7 then ${U.bold("/screenshot capture")} (a false skip or a misplaced callout costs the same browser time as a good shot)`)+J);else if(he==="ready"){let re=G>0?U.gray(` \u2014 ${c-G} in one go; ${G} write${G===1?"s":""} real data and run${G===1?"s":""} one at a time`):"";S.push(` ${V("\u2192",U.yellow)}${c} spec${c===1?"":"s"} ready to capture \u2014 run ${U.bold("/screenshot capture")}${re}${J}`)}else if(he==="verify"&&c>0)S.push(` ${V("\u2192",U.blue)}${i} shot${i===1?"":"s"} awaiting verification \u2014 run ${U.bold("/screenshot verify")}`+U.gray(" \u2014 no browser needed")+U.gray(` \xB7 ${c} ready spec${c===1?"":"s"} write real data, so ${c===1?"it runs":"each runs"} only when named: /screenshot capture <id>`)+J);else if(he==="blocked")S.push(` ${V("\u2192",U.cyan)}${p} shot${p===1?"":"s"} blocked \u2014 stage the data below, then ${U.bold("/screenshot capture --blocked")}${J}`);else if(he==="broken")S.push(` ${V("\u2192",U.red)}${m} spec${m===1?"":"s"} broken \u2014 ${U.bold(`/screenshot ${e.find(re=>re.state==="broken").id}`)} re-authors ${m===1?"it":"the first"} (re-capturing fails the same way)`);else if(he==="verify")S.push(` ${V("\u2192",U.blue)}${i} shot${i===1?"":"s"} awaiting verification \u2014 run ${U.bold("/screenshot verify")}`+U.gray(" \u2014 it checks each picture against what its article needs (no browser, no re-capture)"));else if(he==="rejected"){let re=e.filter(ve=>ve.state==="rejected"&&ve.repaired).length;S.push(` ${V("\u2691",U.magenta)}${l} shot${l===1?"":"s"} failed review \u2014 `+(re>0?`${re} spec${re===1?"":"s"} already repaired; re-capture with ${U.bold("/screenshot capture --failed")}`:`see the reasons below, then ${U.bold("/screenshot capture --failed")}`))}else S.push(` ${V("\u2713",U.green)}all ${r} verified \u2014 ${U.bold("/push")} embeds them in the articles`);if(s>0&&s<r){let re=C.filter(([,ve])=>ve.every(Ne=>Ne.state!=="verified")).map(([ve])=>{let{num:Ne,name:tt}=Ld(ve);return Ne?`${Ne} ${tt}`:tt});re.length>0&&S.push(U.gray(` Furthest behind: ${re.slice(0,5).join(" \xB7 ")}${re.length>5?" \u2026":""} (0% verified)`))}return S.push(...$w(e),...Rw(e),...xw(e,!1,{commandInLead:le}),...vw(e,!1),...Bd(n)),S.push(""),S.push(U.gray(" Drill in: /screenshot list <chapter#> \xB7 /screenshot list --detail (all)")),S}function $P(e,t,n,o=[]){let r=new Set(e.map(c=>c.file)),s=e.filter(c=>c.state==="verified").length,i=e.filter(c=>c.state==="annotated").length,a=e.filter(c=>c.state==="captured").length,l=[` ${U.bold("Screenshots")}: ${e.length} placeholder${e.length===1?"":"s"} across ${r.size} article${r.size===1?"":"s"} \xB7 ${U.green(`${s} verified`)}${i>0?U.blue(` \xB7 ${i} to verify`):""}${a>0?U.yellow(` \xB7 ${a} to annotate`):""}${n?U.gray(` \xB7 scope ${n}`):""}`,""];for(let[c,p]of Cw(e,t)){let m=p.filter(A=>A.state==="verified").length,{num:$,name:w}=Ld(c),C=$?`${$} \xB7 ${w}`:w;l.push(` ${U.bold(C)} ${U.gray(`(${m}/${p.length})`)}`);let S=new Map;for(let A of p){let R=wP(A.file),D=S.get(R)??[];S.has(R)||S.set(R,D),D.push(A)}for(let A of[...S.keys()].sort()){l.push(U.gray(` ${A}`));for(let R of S.get(A)){let D=hP[R.state];if(l.push(` ${V(pP[R.state],D)}${D(R.id)}`),(R.state==="blocked"||R.state==="broken"||R.state==="rejected")&&R.reason){for(let W of gn(Qr(R.reason),84))l.push(U.gray(` ${W}`));R.state==="rejected"&&l.push(U.gray(` ${R.repaired?"spec repaired \u2014 re-capture to confirm":"spec not yet repaired"}`))}}}}return l.push(...$w(e),...Rw(e),...xw(e,!0),...vw(e,!0),...Bd(o)),l.push("",fP),l}function xl(e,t){let n=t?.scope,o=t?.markerProblems??[];if(e.length===0)return[n?`No screenshot placeholders under ${n}.`:"No screenshot placeholders found in the docs.",...Bd(o)];let r=t?.docsDir??Fd;return t?.detail||n?$P(e,r,n,o):bP(e,r,o)}function Gd(e,t){if(!t||!/^\d+$/.test(t))return t;let n=co(e)?.docsDir??Fd,o=String(Number(t));for(let{file:r}of cw(e)){let s=Sw(r,n),i=/^(\d+)/.exec(s);if(i&&String(Number(i[1]))===o)return s}return t}function Pw(e,t){let r=e.map(a=>" ".repeat(a.depth)+a.label),s=Math.max(0,...e.map((a,l)=>a.note?hl(r[l]):0)),i=Math.min(s,Math.max(0,t-2-24));return e.map((a,l)=>{let c=r[l];if(!a.note)return{head:c,note:""};let p=Math.max(2,i+2-hl(c)),m=a.note.trim(),$=t-hl(c)-p;return{head:c+" ".repeat(p),note:$>1&&hl(m)>$?`${m.slice(0,$-1)}\u2026`:m}})}function vP(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}=vP(s.file),l=o.get(i)??new Map;o.set(i,l);let c=l.get(a)??[];l.set(a,c),c.push(s)}let r=s=>n!=="capture"||!s.mutates;for(let s of[...o.keys()].sort()){let i=o.get(s),a=[...i.values()].flat().filter(r).map(c=>c.id),l=a.length>0;l&&e.push({kind:"category",action:n,label:`${s} (${a.length})`,ids:a,depth:1});for(let c of[...i.keys()].sort()){let p=i.get(c),m=p.filter(r).map(C=>C.id),$=m.length>0;$&&e.push({kind:"article",action:n,label:`${c} (${m.length})`,ids:m,depth:l?2:1});let w=(l?1:0)+($?1:0)+1;for(let C of p){let S=n==="capture"&&C.mutates?" \u26A0 creates real data \u2014 runs only alone":void 0;e.push({kind:"shot",action:n,label:C.id,ids:[C.id],depth:w,...S?{note:S}:{}})}}}}function Td(e){return e?Qr(e):""}function qd(e,t,n,o=[]){let r=t.filter(i=>!i.mutates);r.length>1&&e.push({kind:"all",action:"capture",label:`Retry ${r.length} blocked shots (Prerequisites not met \u2014 Stage the data first)`,ids:r.map(i=>i.id),depth:0});for(let i of[...t].sort((a,l)=>a.id.localeCompare(l.id)))e.push({kind:"shot",action:"capture",label:i.id,ids:[i.id],depth:1,note:` \u2298 ${Td(i.reason)}`});n.length>1&&e.push({kind:"all",action:"author",label:`Re-author ${n.length} broken specs`,ids:n.map(i=>i.id),depth:0});for(let i of[...n].sort((a,l)=>a.id.localeCompare(l.id)))e.push({kind:"shot",action:"author",label:i.id,ids:[i.id],depth:1,note:` \u2717 re-authors \u2014 ${Td(i.reason)}`});let s=o.filter(i=>!i.mutates);s.length>1&&e.push({kind:"all",action:"capture",label:`Re-capture ${s.length} shots that failed review`,ids:s.map(i=>i.id),depth:0});for(let i of[...o].sort((a,l)=>a.id.localeCompare(l.id))){let a=i.repaired?"re-captures":"re-captures (spec not yet repaired)";e.push({kind:"shot",action:"capture",label:i.id,ids:[i.id],depth:1,note:` \u2691 ${a} \u2014 ${Td(i.reason)}`})}}function Aw(e){let t=e.filter(i=>i.state==="placeholder"),n=e.filter(i=>i.state==="spec"),o=[];t.length>1&&o.push({kind:"all",action:"author",label:`Author all ${t.length} remaining specs`,ids:t.map(i=>i.id),depth:0}),Xr(o,t,"author");let r=n.filter(i=>!i.mutates);r.length>1&&o.push({kind:"all",action:"capture",label:`Capture all ${r.length} ready specs`,ids:r.map(i=>i.id),depth:0}),Xr(o,n,"capture");let s=e.filter(i=>i.state==="captured");return s.length>1&&o.push({kind:"all",action:"annotate",label:`Draw the callouts on all ${s.length} shots`,ids:s.map(i=>i.id),depth:0}),Xr(o,s,"annotate"),qd(o,e.filter(i=>i.state==="blocked"),e.filter(i=>i.state==="broken"),e.filter(i=>i.state==="rejected")),o}var Od=["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 ${dw}), 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(`
|
|
332
|
+
`);function xP(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 _d="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 Tw(e,t,n){let o=e.paths,r=o.filter(l=>t?.get(l)?.outcome==="failed"),s=o.filter(l=>t?.get(l)?.outcome==="skipped"),i=l=>`- ${l}: ${t.get(l).reason.replace(/\s+/g," ").trim()}`,a=o.filter(l=>(n?.get(l)?.length??0)>0);return[`Run the emit-screenshot-spec skill to author the ${pw} spec for EACH of these`,"SCREENSHOT placeholder ids:",e.paths.map(l=>`- ${l}`).join(`
|
|
333
|
+
`),"",...r.length>0?["REPAIR: these already have a spec, and it FAILED its last capture. Read the existing spec","first and fix the named failure specifically; do not re-emit the same locator and hope. A",'"strict mode violation" means the locator matched 2+ elements (scope it to a stable container',"or take .first()); a click timeout means the element was absent or unreachable (if the data","simply is not staged, the spec must test.skip with a reason naming what to stage, not time out).",...r.map(i),""]:[],...s.length>0?["REPAIR: these already have a spec and it SKIPPED. Treat each reason as SUSPECT, not as proof","the spec is right: a FALSE skip is indistinguishable from a true one from inside the spec, and","you are being asked to re-author rather than to stage. Check TWO things before concluding a","spec needs no change. (1) Is the target RENDERED? A collapsed tree node, unopened accordion,","inactive tab, virtualised list or page 2 of a table keeps children out of the DOM, so the count","is zero for data one click away, so expanding is a step to SCRIPT. (2) Is the selector too narrow?","If you filtered past a decoy, count the unnarrowed set and put the number in the reason. A spec","that satisfies every rule and still cannot reach its target is NOT correct.",...s.map(i),""]:[],...a.flatMap(l=>ww(n.get(l),`RULE VIOLATIONS already in ${l}'s existing spec \u2014 fix every one:`)),"For each: locate its <!-- SCREENSHOT --> block in the docs tree (the configured docsDir); read the product source for","EXACT routes + stable data-testid selectors (never guess); enter the prepared context via","captureScope(); guard data prerequisites with test.skip(reason); write <captureDir>/<id>.spec.ts","(skip-with-TODO if a stable selector is missing). Do NOT run other skills. Report the specs you","wrote and any TODO data-testids.",Od,_d].join(`
|
|
334
|
+
`)}async function Rl(e,t,n){let o=ii(e),r=Xo(t?.cwd??process.cwd());if(r&&console.log(U.gray(r)),o.mode==="list"){let l=t?.cwd??process.cwd(),c=Gd(l,o.scope),p=co(l)?.docsDir??Fd,m=Ke(l,c),$=zC(l,c?{scope:c}:{});for(let w of xl(m,{scope:c,detail:o.detail,docsDir:p,markerProblems:$}))console.log(w);return{kind:"continue"}}if(o.mode==="single"){let l=Qo(t?.cwd??process.cwd(),o.id),c=l===null?[]:Wd(l);return{kind:"forward-to-agent",prompt:[`Run the emit-screenshot-spec skill for the SCREENSHOT placeholder with id \`${o.id}\`.`,"Locate its <!-- SCREENSHOT --> block in the docs tree (the configured docsDir), then follow that skill exactly: read the","product source for EXACT routes + stable data-testid selectors (never guess); enter the prepared","context via captureScope(); guard data prerequisites with test.skip(reason); write",`<captureDir>/${o.id}.spec.ts. Report per the skill's writer-facing format: spec path, data to`,"stage, dev requests only if any, and the capture command; no grounding narration.",Od,_d,...n?.prior?["",...xP(n.prior)]:[],...c.length>0?["",...ww(c,"RULE VIOLATIONS already in the existing spec \u2014 fix every one:")]:[]].join(`
|
|
335
|
+
`),display:`/screenshot ${o.id}`}}if(o.mode==="capture"||o.mode==="annotate"||o.mode==="verify"||o.mode==="checklist")return{kind:"continue"};let s=o.mode==="scope"?`every <!-- SCREENSHOT --> placeholder in articles under ${o.scope}`:"every <!-- SCREENSHOT --> placeholder across the docs tree (the configured docsDir)",i=[`Run the emit-screenshot-spec skill to (re)generate the ${pw} spec for ${s}.`,"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.`,Od,_d].join(`
|
|
336
|
+
`),a=o.mode==="scope"?`/screenshot ${o.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:i,display:a}}import{readDocsPlan as CP,readProjectConfig as PP,listOpenHints as AP,partitionOpenHints as TP,listOpenForDocs as EP,listOpenDirectives as NP,loadOpenCommentCount as DP,resolveActiveProfile as jP,briefMoved as IP,DEFAULT_DOCS_DIR as LP}from"document360-engine";import{statSync as RP}from"node:fs";import{resolve as SP}from"node:path";function uo(e,t,n){return n.filter(o=>{try{return RP(SP(e,t,o)).size===0}catch{return!0}})}var Jo=e=>e===1?"":"s";function OP(e){try{let t=(PP(e)?.docsDir??LP).replace(/\/+$/,""),n=CP(e,t);return n.length===0?0:uo(e,t,n.map(o=>o.path)).length}catch{return 0}}function _P(e){try{return DP(e,jP(e).name)}catch{return 0}}function MP(e){let t=i=>{try{return i().length}catch{return 0}},n=t(()=>TP(e,AP(e)).actionable),o=t(()=>EP(e)),r=t(()=>NP(e)),s=!1;try{s=IP(e)}catch{}return{hints:n,messages:o,directives:r,brief:s,total:n+o+r+(s?1:0)}}function Ew(e,t){let n=t?.just,o=MP(e);if(o.total>0&&n!=="/catch-up"){let i=[];return o.hints>0&&i.push(`${o.hints} hint${Jo(o.hints)}`),o.messages>0&&i.push(`${o.messages} message${Jo(o.messages)}`),o.directives>0&&i.push(`${o.directives} request${Jo(o.directives)}`),o.brief&&i.push("an updated product brief"),{cmd:"/catch-up",short:`Your builder left ${i.join(" and ")} waiting`,text:`Your builder left ${i.join(" and ")} waiting. /catch-up clears that first \u2014 it rewrites articles, so reviewing or sending anything up before it runs is work you would do twice.`}}let r=_P(e);if(r>0&&n!=="/comments")return{cmd:"/comments",short:`${r} reviewer comment${Jo(r)} ${r===1?"is":"are"} waiting on your articles`,text:`${r} reviewer comment${Jo(r)} ${r===1?"is":"are"} waiting on your articles. /comments answers ${r===1?"it":"them"} first \u2014 answering rewrites the passages they marked up, so reviewing or sending anything up before it runs is work you would do twice.`};let s=OP(e);return s>0&&n!=="/write"?{cmd:"/write",short:`${s} planned article${Jo(s)} ${s===1?"is":"are"} still unwritten`,text:`${s} planned article${Jo(s)} ${s===1?"is":"are"} still unwritten. /write finish${s===1?"es it":"es them"} first, so one review pass and one save cover everything together instead of running twice.`}:null}import{modernizeLegacyCommandLine as UP}from"document360-engine";var FP=new Set(["--scope","--concurrency","--model"]),WP=new Set(["/screenshot","/style-guide","/reuse"]),BP=e=>e.trim().replace(/\s+/g," ").toLowerCase();function wn(e){let t=BP(UP(e));if(!t.startsWith("/"))return null;let n=t.split(" ").filter(Boolean),o=n[0],r=1,s;WP.has(o)&&n[1]&&!n[1].startsWith("-")&&(s=n[1],r=2);let i=new Set,a;for(;r<n.length;r++){let l=n[r];if(l.startsWith("--")){let c=l.indexOf("=");if(c!==-1){let p=l.slice(0,c);i.add(p),p==="--scope"&&(a=l.slice(c+1)||void 0);continue}if(i.add(l),FP.has(l)){let p=n[r+1];p!==void 0&&!p.startsWith("-")&&(l==="--scope"&&(a=p),r++)}continue}if(l.startsWith("-")){i.add(l);continue}a??=l}return{cmd:o,...s?{sub:s}:{},flags:i,...a?{scope:a.replace(/\/+$/,"")}:{}}}function Jr(e){switch(e.cmd){case"/review":case"/lint":return e.flags.has("--fix");case"/write":return!e.flags.has("--preview")&&!e.flags.has("--dry-run");case"/comments":return e.flags.has("--answer");case"/screenshot":return e.sub==="author"||e.sub==="capture"||e.sub==="annotate"||e.sub==="verify";case"/style-guide":return e.sub==="use"||e.sub==="keep"||e.sub==="compile"||e.sub==="learn";case"/reuse":return e.sub==="pull"||e.sub==="add"||e.sub==="audit";case"/restructure":return e.scope!==void 0;case"/push":case"/publish":case"/convert":case"/catch-up":case"/discover":case"/document":case"/pull":case"/reorder":return!0;default:return!1}}var HP=new Set(["--all"]),GP=new Set(["--concurrency","--model","--verbose","--quiet"]),qP=new Set(["--scope"]);function Nw(e){return[...e.flags].filter(t=>!HP.has(t)&&!GP.has(t)&&!qP.has(t)).sort().join(" ")}function Dw(e,t){if(!t)return!1;let n=wn(e),o=wn(t);return!n||!o||n.cmd!==o.cmd||n.sub!==o.sub||!Jr(n)||Nw(n)!==Nw(o)?!1:n.scope===void 0||n.scope===o.scope}function ln(e){return e.aborted||e.blocked||e.allEmpty||e.bailedEmpty||e.producedNothing||(e.leftBehind??0)>0||e.failed>0||e.notRun>0?!1:e.verifiedComplete?!0:e.partitions>=1}import{listRoadmap as ci,roadmapProgress as Uw,stampRoadmapDone as QP,PRODUCT_NAME as JP,WRITER_DIRNAME as Mw}from"document360-engine";ae();ae();import{ROADMAP_STAGES as jw}from"document360-engine";var Iw=[...jw,"other"],VP=[[/^\/screenshot\b/,"capture"],[/^\/style-guide\b/,"decide"],[/^\/genre\b/,"decide"],[/^\/scope\b/,"decide"],[/^\/discover\b/,"plan"],[/^\/plan\b/,"plan"],[/^\/audit\b/,"plan"],[/^\/write\b/,"write"],[/^\/catch-up\b/,"write"],[/^\/document\b/,"write"],[/^\/review\b/,"edit"],[/^\/comments\b/,"edit"],[/^\/lint\b/,"lint"],[/^\/push\b/,"save"],[/^\/pull\b/,"save"],[/^\/publish\b/,"golive"]];function Vd(e){let t=(e.stage??"").trim().toLowerCase();if(jw.includes(t))return t;let n=(e.run??"").trim().toLowerCase();if(n.startsWith("/")){for(let[o,r]of VP)if(o.test(n))return r}return"other"}function Sl(e){return Vd(e)==="capture"}var KP={decide:"Decide",plan:"Plan",capture:"Screenshots",write:"Write",edit:"Edit",lint:"Style rules",save:"Save to Document360",golive:"Go live",other:"Other steps"};function Lw(e){return e.status==="done"&&!!e.replacedBy}var Yd=e=>(e.run??"").trim().replace(/\s+/g," ").toLowerCase();function YP(e){let t=[];for(let o of e){let r=Yd(o);r&&!t.includes(r)&&t.push(r)}let n=o=>{let r=Yd(o);return r?t.indexOf(r):t.length};return e.map((o,r)=>({s:o,i:r})).sort((o,r)=>n(o.s)-n(r.s)||o.i-r.i).map(o=>o.s)}function zP(e){let t=new Map;for(let o of e){let r=Vd(o),s=t.get(r);s?s.push(o):t.set(r,[o])}let n=[];for(let o of Iw){let r=t.get(o);!r||r.length===0||n.push({key:o,label:KP[o],steps:YP(r),done:r.filter(s=>s.status==="done").length})}return n}var Kd=" ",Ow=e=>e.trim().toLowerCase();function XP(e,t){let n=Math.max(20,t.width-Kd.length),o=e.status==="done"?Q("\u2713"):Ie("\u25CB"),r=e.status==="done"?u:t.isNext?Z:p=>p,s=gn(e.title.trim(),n);s.length===0&&s.push("");let i=[];t.showRun&&e.run?.trim()&&i.push(e.run.trim()),t.showReplaced&&e.replacedBy&&i.push(`replaced by \u201C${e.replacedBy}\u201D`);let a=i.map(p=>` \xB7 ${p}`).join(""),l=s.map((p,m)=>m===0?` ${o} ${r(p)}`:`${Kd}${r(p)}`);if(!a)return l;if((s[s.length-1]??"").length+a.length<=n)return l[l.length-1]+=Ie(a),l;for(let p of i)l.push(`${Kd}${Ie(`\xB7 ${p}`)}`);return l}function _w(e,t={}){let n=Math.max(40,t.width??80),o=t.all?e:e.filter(a=>!Lw(a)),r=e.length-o.length,s=e.filter(a=>a.status==="done").length,i=[Z(`Docs roadmap \u2014 ${s} of ${e.length} step${e.length===1?"":"s"} done`)];for(let a of zP(o)){i.push(""),i.push(` ${rt(a.label)}${Ie(` \xB7 ${a.done} of ${a.steps.length}`)}`);let l="";for(let c of a.steps){let p=Yd(c);i.push(...XP(c,{width:n,showRun:!!p&&p!==l,isNext:!!t.next&&Ow(c.title)===Ow(t.next.title),showReplaced:!!t.all&&Lw(c)})),l=p}}return i.push(""),i.push(t.next?`Next: ${t.next.title}${t.next.run?` \u2014 ${t.next.run}`:""}`:"Campaign complete \u2014 the docs agent adds new steps as the app changes."),r>0&&i.push(u(`(+${r} step${r===1?"":"s"} closed because a later pass replaced ${r===1?"it":"them"} \u2014 /roadmap --all lists ${r===1?"it":"them"}.)`)),i}function zd(e,t={}){let n=ci(e);if(n.length===0)return[`No docs roadmap yet \u2014 the docs agent seeds ${Mw}/roadmap.md when it pins a structure,`,"and adds steps as the app changes. You can also write steps by hand (## [open] <step>), or ask:",'"propose the docs roadmap for this repo".'];let o=Uw(e),r=_w(n,{width:t.width,all:t.all,next:o.next});return r.push(u(`(Edit ${Mw}/roadmap.md freely \xB7 /roadmap done marks the next step you finished yourself \u2014 add words from a title to pick another.)`)),n.some(s=>s.stepId)&&r.push(u(`(${JP} keeps the wording of its own steps current \u2014 add a "keep:" line to one to leave your version alone.)`)),r}function Zr(e,t){let n=ci(e).filter(c=>c.status==="open"),o=t.trim();if(n.length===0)return{ok:!1,line:"The roadmap has no open steps \u2014 nothing to mark done."};let r=c=>c.trim().toLowerCase(),s=n.find(c=>r(c.title)===r(o)),i=o?s?[s]:n.filter(c=>r(c.title).includes(r(o))):[n[0]];if(i.length>1)return{ok:!1,line:`"${o}" matches ${i.length} open steps \u2014 add a distinguishing word:
|
|
337
337
|
${i.map(c=>` \u25CB ${c.title}`).join(`
|
|
338
338
|
`)}`};if(i.length===0)return{ok:!1,line:`No open step matches "${o}". Open steps:
|
|
339
339
|
${n.map(c=>` \u25CB ${c.title}`).join(`
|
|
340
|
-
`)}`};let a=i[0].title;
|
|
341
|
-
`)}function
|
|
340
|
+
`)}`};let a=i[0].title;QP(e,a,{doneAt:new Date().toISOString()});let l=Uw(e)?.next;return{ok:!0,line:`\u2713 Marked done: ${a}${l?` \u2014 next up: ${l.title}${l.run?` (${l.run})`:""}`:" \u2014 that was the last step: campaign complete."}`}}function Fw(e,t){let n=r=>r.trim().replace(/\s+/g," ").toLowerCase(),o=n(t);return o.startsWith("/")?ci(e).find(r=>r.status==="open"&&!!r.run&&n(r.run)===o)??null:null}function Cl(e,t){let n=(Array.isArray(t)?t:[t]).filter(s=>s.trim().startsWith("/"));if(n.length===0)return[];let o=new Set,r=[];for(let s of ci(e))s.status==="open"&&n.some(i=>Dw(i,s.run))&&(o.has(s.title)||(o.add(s.title),r.push(s.title)));return r}function Ze(e,t){if(!t)return[];try{let n=Cl(e,t).filter(o=>Zr(e,o).ok);return n.length===0?[]:n.length===1?[`\u2713 That completed a docs-campaign step \u2014 marked done: ${n[0]}`]:[`\u2713 That completed ${n.length} docs-campaign steps \u2014 marked done:`,...n.map(o=>` \u2022 ${o}`)]}catch{return[]}}function Pl(e,t){let n=Cl(e,t);if(n.length===0)return null;let o=n.map(r=>`"${r}"`).join(", ");return[n.length===1?`Note: this command executes the open docs-roadmap step ${o}.`:`Note: this command executes ${n.length} open docs-roadmap steps: ${o}.`,`Close the loop IN THE SAME TURN the goal state is reached: call d360_roadmap_done with exactly the title of EACH step it completed (${o}), then tell the user they are marked done \u2014 including when you find the goal already holds ("no action needed" completes the STEP, not just the turn). Leave one open ONLY if its work is genuinely incomplete, and say exactly what remains.`].join(`
|
|
341
|
+
`)}function Ww(e,t){let n=t.trim().toLowerCase();if(!n)return null;let o=ci(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:
|
|
342
342
|
${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(`
|
|
343
|
-
`):null}async function qy(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let o=Ur(n,e.slice(1).join(" ").trim());return console.log(o.ok?Q(o.line):W(o.line)),{kind:"continue"}}for(let o of fd(n,{all:e.some(r=>r.toLowerCase()==="--all")}))console.log(o);return{kind:"continue"}}var gd={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 pushing overwrites the portal edit"},VC="\u26A0 held on Document360 in another editor \u2014 /resolve settles it";function qo(e){return e.filter(t=>t.path!==null&&t.status in gd&&!t.link).map(t=>({path:t.path,label:gd[t.status]}))}function Ho(e,t=[]){let n=qo(e),o=new Set(t),r=new Set([...e.filter(s=>s.status==="conflict"&&s.path).map(s=>s.path),...o]);return{clean:n.filter(s=>!r.has(s.path)),conflicts:n.filter(s=>r.has(s.path)).map(s=>o.has(s.path)&&s.label!==gd.conflict?{...s,label:VC}:s)}}function Go(e,t){try{return LC(e,sl(e,t).name).map(n=>n.path)}catch{return[]}}function Ks(e,t=0){let n=e!==1;if(t>=e)return`\u26A0 ${e} article${n?"s":""} NOT pushed (nothing on the portal overwritten) \u2014 Document360 holds ${n?"their bodies":"its body"} in another editor, so ${n?"they cannot be":"it cannot be"} read back. Settle ${n?"them":"it"}: /resolve (or ask your Document360 admin to move ${n?"them":"it"} to the Markdown editor).`;let o=t>0?` (${t} of ${n?"them are":"these is"} held in another editor and cannot be read back)`:"";return`\u26A0 ${e} conflict${n?"s":""} NOT pushed (portal edit${n?"s":""} kept safe) \u2014 ${n?"these were":"it was"} edited both here and on the portal, so ${n?"they are":"it is"} left untouched.${o} Settle ${n?"them":"it"}: /resolve (or /push <path> to keep yours, /pull <path> to take the portal's).`}function yd(e,t){let n=t.scope?.replace(/\\/g,"/").replace(/\/+$/,"");return!n||!n.endsWith(".md")||!zy(e,t.profileName).map(r=>r.replace(/\\/g,"/")).some(r=>r===n||r.endsWith(`/${n}`)||n.endsWith(`/${r}`))?null:{cmd:Te("/publish","",n),reason:"it takes this draft live \u2014 until it does, your readers still see the previous version"}}function Wr(e,t){let n=zy(e,t),o=n.length;if(o===0)return null;let r=o===1?"":"s",s=0;try{s=IC(e,n).length}catch{}if(s>0){let i=o-s,a=`${s===o?o===1?"It is":"All of them are":`${s} of them ${s===1?"is":"are"}`} waiting on a missing picture`;return`\u2139 ${o} article${r} ${o===1?"is":"are"} saved on Document360 as a draft and not live yet \u2014 readers still see the previous version. ${a}, so /publish holds ${s===1?"it":"them"} back${i>0?` and takes the other ${i} live once ${i===1?"it has":"they have"} been signed off.`:"."}`}return`\u2139 ${o} article${r} ${o===1?"is":"are"} saved on Document360 as a draft and not live yet \u2014 readers still see the previous version. /publish takes ${o===1?"it":"them"} live once ${o===1?"it has":"they have"} been signed off.`}function rl(e){return e.filter(t=>t.link).length}function wd(e,t){try{let n=Yy(e,sl(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=qC(AC(EC(e,r),"utf8"),r,n).unresolved}catch{}return o===0?null:`\u2139 ${o} cross-link${o===1?"":"s"} point to pages that aren't on Document360 yet \u2014 they show as plain text for now and turn into links once those pages are pushed.`}catch{return null}}function nw(e,t=[]){let n=[];e.length>1&&n.push({kind:"all",label:`Push all ${e.length} articles`,paths:e.map(r=>r.path),indent:!1});let o=new Map;for(let r of e){let s=r.path.replace(/\\/g,"/").split("/").slice(0,-1).join("/"),i=o.get(s);i?i.push(r):o.set(s,[r])}for(let r of[...o.keys()].sort()){let s=o.get(r).sort((i,a)=>i.path.localeCompare(a.path));n.push({kind:"category",label:`${eo(r)} (${s.length})`,paths:s.map(i=>i.path),indent:!1});for(let i of s){let a=i.path.replace(/\\/g,"/").split("/").pop()??i.path;n.push({kind:"article",label:a,paths:[i.path],indent:!0,note:i.label})}}for(let r of[...t].sort((s,i)=>s.path.localeCompare(i.path))){let s=r.path.replace(/\\/g,"/").split("/").pop()??r.path;n.push({kind:"article",label:s,paths:[r.path],indent:!1,note:r.label,conflict:!0})}return n}async function Ys(e,t){try{let n=sl(e,t),o=n.project.projectId,r=n.project.workspaceId;if(!o||!r)return null;let s=await GC({profile:n.name,connection:n.connection,projectId:o,projectName:n.project.projectName},{cwd:e,profile:n.name,projectPath:`/v3/projects/${o}`,workspaceId:r,verifyHidden:!1});if(s.kind!=="created")return null;if(s.hidden!=="confirmed"){let i=s.seeded.length===0?" Its internal articles were NOT created, because that would put docs-agent scaffolding in front of your readers.":"";return`\u26A0 Created the "${Vy}" folder on Document360 for reviewer feedback, but could NOT confirm it is hidden from readers.${i} Open its category settings in the portal and turn on "Hide from readers", then run /catch-up.`}return`\u2139 Created a hidden "${Vy}" folder on Document360 \u2014 it's where your reviewers leave feedback for d360-writer to action (confirmed hidden from readers; its README explains how). /catch-up picks up what they write.`}catch{return null}}var Wt="--skip-review";function zs(e,t){return OC(e,t)}function il(e,t){try{return zs(e,Qy(e,t)).length}catch{return 0}}function Bt(e,t,n="",o,r){let s=il(e,o),i=al(e,o),a=o?` ${o}`:"",l=o?"/push":"/push --all",c=Iy(e,{just:r}),p=!!o&&o.endsWith(".md"),m=c&&p?` (${c.short} \u2014 ${c.cmd} once this page is delivered.)`:"";if(c&&!p){let C=s>0?` (${s} article${s===1?"":"s"}${o&&!o.endsWith(".md")?` in ${o}`:""} ${s===1?"carries":"carry"} text no editor has read, so ${s===1?"it cannot":"they cannot"} be sent up until /review${a} --blocked --fix runs \u2014 that can wait until the writing is done.)`:i>0?` (${i} article${i===1?"":"s"} break${i===1?"s":""} house style rules that block sending up \u2014 /lint${a} --blocked --fix clears that whenever you want.)`:"";return{text:`${n}${c.text}${C}`,cmd:c.cmd}}if(s===0&&i===0)return m?{...t,text:`${t.text}${m}`}:t;let $=o&&!o.endsWith(".md")?` in ${o}`:"";if(s>0){let C=s===1?"":"s",S=i>0?` ${i} also break house style rules \u2014 /lint${a} --blocked --fix clears those afterwards.`:"",T=`/review${a} --blocked --fix`;return{text:`${n}${s} article${C}${$} ${s===1?"carries":"carry"} text no editor has read, so pushing ${s===1?"it is":"them is"} blocked. ${T} reads ${s===1?"it":"just those"} and applies its fixes.${S} Then ${l}.${m}`,cmd:T}}return{text:`${n}${i} article${i===1?"":"s"}${$} break${i===1?"s":""} house style rules that block publishing. /lint${a} --blocked --fix corrects them in place \u2014 finding them costs nothing \u2014 then ${l}.${m}`,cmd:`/lint${a} --blocked --fix`}}function al(e,t){try{return Xy(e,Qy(e,t)).length}catch{return 0}}function ow(e,t){return Xy(e,t)}function kd(e,t,n){try{let o=Yy(e,sl(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 bd(e,t){let n=`/push${t.scope?` ${t.scope}`:" --all"}`,o=l=>`${l} article${l===1?"":"s"}`,r=[],s=e.pushed.length,i=t.elapsedMs!==void 0?` \xB7 ${zC(t.elapsedMs)}`:"",a=e.screenshotsUploaded>0?` \xB7 ${e.screenshotsUploaded} screenshot${e.screenshotsUploaded===1?"":"s"} uploaded`:"";s===0&&e.failed.length===0?r.push("Nothing was pushed \u2014 no articles were sent."):t.recorded<s?(r.push(`Pushed ${t.recorded}/${o(s)}${a}${i}.`),r.push(`${s-t.recorded} article${s-t.recorded===1?"":"s"} reported success but ${s-t.recorded===1?"is":"are"} not recorded in the category map \u2014 re-run ${n}.`)):(r.push(`Pushed ${o(s)}${e.created>0?` (${e.created} new)`:""}${a}${i}.`),r.push(`Saved on Document360 as draft${s===1?"":"s"} \u2014 readers don't see ${s===1?"it":"them"} until /publish takes ${s===1?"it":"them"} live.`)),e.stopped?.reason==="unavailable"&&r.push(`Stopped: ${e.stopped.streak} articles in a row could not reach Document360${e.notRun.length>0?`, so the remaining ${e.notRun.length} ${e.notRun.length===1?"was":"were"} not attempted`:""}.`);for(let l of e.duplicateCategories??[])r.push(`\u26A0 Document360 now holds ${l.ids.length} categories called "${l.name}" \u2014 your articles are split between them.`);if((e.duplicateCategories??[]).length>0&&r.push(" Nothing here deletes a category. Remove the extra ones in the portal, then run /push --all again."),e.stopped?.reason==="identity"&&r.push(`Nothing was pushed. ${e.stopped.error}`),e.failed.length>0){let l=e.failed.filter(m=>m.refused),c=YC(e.failed,t.docsRoot),p=e.failed.length;if(c.length===1&&p>1)r.push(`${o(p)} could not be pushed \u2014 all with the same error: ${c[0].error}`),r.push(...Ky(c[0].paths," \u2717 "));else{r.push(`${o(p)} could not be pushed:`);for(let m of c)m.paths.length===1?r.push(` \u2717 ${m.paths[0]} \u2014 ${m.error}`):(r.push(` \u2717 ${o(m.paths.length)} \u2014 ${m.error}`),r.push(...Ky(m.paths," ")))}l.length<e.failed.length&&(e.stopped?r.push(`Nothing was lost \u2014 your articles are unchanged. Re-run ${n} when Document360 is back.`):r.push(`Re-run ${n} to retry the rest \u2014 articles already saved are sent again only if they changed.`))}if(e.notRun.length>0&&!e.stopped&&r.push(`\u26A0 ${o(e.notRun.length)} never started (the run was stopped): ${KC(e.notRun)}`),e.missingShots.length>0){let l=e.missingShots.flatMap(c=>c.ids);r.push(`\u26A0 ${l.length} screenshot${l.length===1?"":"s"} in ${o(e.missingShots.length)} ${l.length===1?"has":"have"} not been taken, so the description was published instead: /screenshot capture`)}if(e.categoryLookupFailed.length>0){let l=e.categoryLookupFailed.length;r.push(`\u26A0 Could not check Document360 for existing categories, so ${l===1?"a new one was":`${l} new ones were`} created. There may now be two with the same name: /doctor lists them.`),r.push(` Reason: ${e.categoryLookupFailed[0].reason}`)}return t.conflictsSkipped&&t.conflictsSkipped>0&&r.push(Ks(t.conflictsSkipped,t.unreadableSkipped??0)),r}var KC=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,md=5;function Ky(e,t){let n=e.slice(0,md).map(o=>`${t}${o}`);return e.length>md&&n.push(`${" ".repeat(t.length)}\u2026 +${e.length-md} more`),n}function YC(e,t){let n=t?`${t.replace(/\\/g,"/").replace(/\/+$/,"")}/`:null,o=s=>{let i=s.replace(/\\/g,"/");return n&&i.startsWith(n)?i.slice(n.length):i},r=new Map;for(let s of e){let i=r.get(s.error);i?i.push(o(s.path)):r.set(s.error,[o(s.path)])}return[...r.entries()].map(([s,i])=>({error:s,paths:i})).sort((s,i)=>i.paths.length-s.paths.length)}function zC(e){let t=Math.round(e/1e3);return t<60?`${t}s`:`${Math.floor(t/60)}m ${String(t%60).padStart(2,"0")}s`}async function on(e,t,n=0,o){let r=_C(e.cwd,t,{allowUnreviewed:o?.skipReview===!0,allowStyleErrors:o?.skipStyle===!0});if(!r.clear){for(let c of MC(r,t.length,{act:"push"}))console.log(W(c));return{kind:"continue"}}let s={aborted:!1,partitions:0,failed:0,notRun:0,producedNothing:!0},i={retryable:0,stopped:!1,paths:[]},a=async(c,p)=>{let m=Date.now();console.log(u(p?`Resolving cross-links in ${c.length} article${c.length===1?"":"s"} whose targets published this run (second pass)\u2026`:`Pushing ${c.length} article${c.length===1?"":"s"} to Document360 (${WC} at a time)\u2026`));let $=await FC({cwd:e.cwd,...e.profileName?{profileName:e.profileName}:{},paths:c,...o?.allowUnpullable===!0?{allowUnpullable:!0}:{},onEvent:U=>{U.type==="article_done"?console.log(Q(` \u2713 ${U.result.path}${U.result.action==="created"?" (new)":""}`)):U.type==="article_failed"&&console.log(L(` \u2717 ${U.failure.path}`))}});console.log("");let w=kd(e.cwd,c,e.profileName);p||(i={retryable:$.failed.filter(U=>!U.refused).length,stopped:!!$.stopped,paths:$.failed.map(U=>U.path)},s={aborted:$.aborted||!!$.stopped,partitions:DC(c).length,failed:$.failed.length,notRun:$.notRun.length,producedNothing:$.pushed.length===0,verifiedComplete:w>=c.length,leftBehind:n});let C=$.pushed.length>0;for(let U of bd($,{recorded:w,elapsedMs:Date.now()-m,docsRoot:HC(e.cwd),...p?{}:{conflictsSkipped:n,unreadableSkipped:o?.unreadableSkipped??0},...o?.scope?{scope:o.scope}:{}}))console.log(C&&$.failed.length===0?Q(U):W(U));let S=$.aborted||!!$.stopped;if(!C)return S;let T=wd(e.cwd,e.profileName);T&&console.log(u(T));let R=Wr(e.cwd,e.profileName);if(R&&console.log(u(R)),S)return S;try{let U=Zy(await Jy({cwd:e.cwd,profileName:e.profileName,onRateLimit:H=>console.log(u(` Document360 rate limit \u2014 waiting ${Math.ceil(H.waitMs/1e3)}s\u2026`))}));U&&console.log(U.startsWith("\u26A0")?W(U):u(U))}catch{}try{let U=tw(await ew({cwd:e.cwd,profileName:e.profileName}));U&&console.log(u(U))}catch{}let D=await Ys(e.cwd,e.profileName);return D&&console.log(u(D)),S};try{if(!await a(t,!1)){let p=await $d(e.cwd,e.profileName,t,i.paths);if(p.length>0&&await a(p,!0),nn(s))for(let m of Qe(e.cwd,o?.scope?`/push ${o.scope}`:"/push --all"))console.log(Q(m))}}catch(c){console.log(L(`Push run failed: ${c.message}`))}if(console.log(""),i.retryable>0){let c=Te("/push",o?.scope?"":"--all",o?.scope);return console.log(u(i.stopped?`Next: ${c} \u2014 your articles are unchanged, so it picks up where the run left off.`:`Next: ${c} \u2014 retries the ${i.retryable} article${i.retryable===1?"":"s"} that could not be saved.`)),{kind:"continue",ownNext:!0}}let l=yd(e.cwd,{scope:o?.scope,profileName:e.profileName});return l?(console.log(u(`Next: ${l.cmd} \u2014 ${l.reason}.`)),{kind:"continue",ownNext:!0}):{kind:"continue"}}async function ll(e,t,n){let o=jC(e,n);if(o.length===0)return[];let r=new Set(qo((await ol({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function $d(e,t,n,o=[]){try{let r=new Set(n),s=new Set(o),i=await ol({cwd:e,profileName:t});return qo(i.entries).map(a=>a.path).filter(a=>r.has(a)&&!s.has(a))}catch{return[]}}async function XC(e,t,n){try{let o=await UC({cwd:e,...t?{profileName:t}:{},relPath:n.replace(/\\/g,"/"),preview:!0});console.log(""),console.log(Q(`${o.title}`)),console.log(u(`${o.path} \xB7 ${o.articleId?`updates article ${o.articleId}`:"would be created as a new article"}`)),o.shots.length>0&&console.log(u(`${o.shots.length} screenshot${o.shots.length===1?"":"s"} embedded: ${o.shots.map(r=>r.id).join(", ")}`)),o.missingShots.length>0&&console.log(W(`\u26A0 ${o.missingShots.length} screenshot${o.missingShots.length===1?"":"s"} not taken yet \u2014 the description publishes instead: ${o.missingShots.join(", ")}`)),console.log(u("\u2500".repeat(Math.min(80,Math.max(20,(process.stdout.columns??80)-1))))),console.log(o.body),console.log(u("\u2500".repeat(Math.min(80,Math.max(20,(process.stdout.columns??80)-1))))),console.log(u(`Nothing was sent. Run /push ${o.path} to save it as a draft.`))}catch(o){console.log(L(o.message))}return{kind:"continue"}}async function cl(e,t){let n=ot(t?.cwd??process.cwd(),t?.profileName);if(!n.ok){let[i,a]=Ft(n);return console.log(L(i)),console.log(u(a)),{kind:"continue"}}let o=e.includes(Wt),r=e.includes(BC);if(e.includes("--preview")){let i=e.find(a=>!a.startsWith("--"));return i?await XC(t?.cwd??process.cwd(),t?.profileName,i):(console.log(L("Which article? Use /push --preview <path> \u2014 a preview is per article.")),{kind:"continue"})}let s=e[0];if(e.includes("--screenshots")||e.includes("--shots")){let i=t?.cwd??process.cwd(),a=e.find(w=>!w.startsWith("--")),l=qe(i),c=Ya(l,a);if(c.length===0){let w=l.filter(C=>C.state==="captured").length;return console.log(u(w>0?`${w} screenshot${w===1?" has":"s have"} been taken but the callouts aren't drawn on yet, so there is nothing to embed \u2014 /screenshot annotate finishes ${w===1?"it":"them"}.`:a?`No captured screenshots in ${a} \u2014 /push --screenshots covers the whole knowledge base.`:"No captured screenshots yet \u2014 /screenshot capture first.")),{kind:"continue"}}let p=za(l,a);p&&console.log(p);let m=Xa(l);m&&console.log(m);let $=Te("","--screenshots",a).trim();return await on(t??{cwd:process.cwd()},c,0,{skipReview:o,skipStyle:r,scope:$})}if(s==="--related"&&e[1]){if(!t)return{kind:"continue"};let i=await ll(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return i.length===0?(console.log(Q("\u2713 All related articles are already on Document360.")),{kind:"continue"}):await on(t,i,0,{skipReview:o,skipStyle:r,scope:`--related ${e[1]}`})}if(s==="--all"){console.log(u("Checking what needs pushing\u2026"));try{let i=await ol({cwd:t?.cwd??process.cwd()}),a=new Set(Go(t?.cwd??process.cwd(),t?.profileName)),{clean:l,conflicts:c}=Ho(i.entries,a),p=c.filter(S=>a.has(S.path)).length,m=rl(i.entries),$=e.includes("--force"),w=$&&c.length>0;m>0&&console.log(W(`\u26A0 ${m} article(s) already exist on Document360 but aren't linked \u2014 left out (pushing would duplicate them). Run /catch-up or ask me to link them first.`)),c.length>0&&!w&&console.log(W(Ks(c.length,p)));let C=w?[...l,...c]:l;if(C.length===0){if(c.length>0){let T=Wr(t?.cwd??process.cwd(),t?.profileName);return T&&console.log(u(T)),console.log(u("Resolve the conflicts: /resolve")),{kind:"continue"}}console.log(Q(m>0?"\u2713 Nothing else is ahead of Document360 to push.":"\u2713 Nothing is ahead of Document360 \u2014 nothing to push."));let S=Wr(t?.cwd??process.cwd(),t?.profileName);if(S&&console.log(u(S)),t)try{let T=Zy(await Jy({cwd:t.cwd,profileName:t.profileName,onRateLimit:D=>console.log(u(` Document360 rate limit \u2014 waiting ${Math.ceil(D.waitMs/1e3)}s\u2026`))}));T&&console.log(T.startsWith("\u26A0")?W(T):u(T));let R=tw(await ew({cwd:t.cwd,profileName:t.profileName}));R&&console.log(u(R))}catch{}return{kind:"continue"}}return await on(t??{cwd:process.cwd()},C.map(S=>S.path),w?0:c.length,{skipReview:o,skipStyle:r,allowUnpullable:$,unreadableSkipped:w?0:p})}catch(i){return console.log(L(`Could not compute sync status: ${i.message}`)),{kind:"continue"}}}if(s&&s.startsWith("--")&&(s=e.find(i=>!i.startsWith("--"))??""),!s){console.log(u("Checking what needs pushing\u2026"));let i,a=0,l=0;try{let c=await ol({cwd:t?.cwd??process.cwd()}),p=new Set(Go(t?.cwd??process.cwd(),t?.profileName)),{clean:m,conflicts:$}=Ho(c.entries,p);l=$.filter(C=>p.has(C.path)).length,i=m,a=$.length;let w=rl(c.entries);if(w>0&&console.log(W(`\u26A0 ${w} article(s) already exist on Document360 but aren't linked \u2014 left out (pushing would duplicate them). Run /catch-up or ask me to link them first.`)),$.length>0&&console.log(W(Ks($.length,l))),i.length===0&&$.length>0)return console.log(u("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(c){return console.log(L(`Could not compute sync status: ${c.message}`)),console.log(u("Push a specific article: /push <article-path>")),{kind:"continue"}}if(i.length===0)return console.log(Q("\u2713 Nothing is ahead of Document360 \u2014 nothing to push.")),console.log(u(" (Articles without a sync base are unverified \u2014 push those by path if needed.)")),{kind:"continue"};if(!process.stdin.isTTY||!t){for(let c of i)console.log(` ${c.path} ${u(`(${c.label})`)}`);return console.log(u("Run: /push <article-path>")),{kind:"continue"}}try{s=await t.withPausedInput(()=>NC({message:"Push which article?",choices:[...i.length>1?[{name:`All ${i.length} candidates`,value:"--all",description:"one agent run over every candidate"}]:[],...i.map(c=>({name:c.path,value:c.path,description:c.label}))]}))}catch{return console.log(u("Cancelled.")),{kind:"continue"}}if(s==="--all")return await on(t,i.map(c=>c.path),a,{skipReview:o,skipStyle:r,unreadableSkipped:l})}return await on(t??{cwd:process.cwd()},[s],0,{skipReview:o,skipStyle:r,scope:s})}ue();import{select as eP}from"@inquirer/prompts";import{computeSyncStatus as tP,localAheadPaths as nP,pendingDrafts as oP,publishArticleLive as rP,publishGateVerdict as sP,publishGateLines as iP,blockedPaths as aP,placeholderRemedy as lP,resolveActiveProfile as cP,SKIP_STYLE_FLAG as uP,SKIP_SHOTS_FLAG as dP}from"document360-engine";import{gateFixTarget as QC}from"document360-engine";var xd=e=>"ruleId"in e,ul=e=>xd(e)?e.severity:"warning",ro=e=>e===1?"":"s";function Xs(e,t){let n=t??QC(e),o=n?` ${n}`:"";return e.unreviewed.length>0?`/review${o} --blocked --fix`:`/lint${o} --blocked --fix`}var vd=new Map;var JC=e=>xd(e)?e.fp||`${e.ruleId}:${e.path}:${e.line}:${e.term}`:`${e.kind}:${e.path}:${e.line}`;function Qs(e){let{cwd:t,after:n,scope:o,aborted:r,blocked:s}=e,i=n.filter(w=>ul(w)==="error").length,a=n.filter(w=>ul(w)==="warning").length,l=n.filter(w=>ul(w)==="suggestion").length,c=Te("/lint","--blocked --fix",o);if(r){let w=Te("/lint",s?"--blocked --fix":"--fix",o);return{text:`Stopped. Nothing else changed \u2014 ${w} picks up where this left off.`,cmd:w}}if(i>0){let w=n.filter(D=>ul(D)==="error"),C=new Set(w.map(D=>D.path)).size,S=`${t}::${o??""}`,T=w.map(JC).sort().join("|"),R=vd.get(S)===T;if(vd.set(S,T),R){let D=Te("/lint","--blocked --full",o),U=[...new Set(w.filter(xd).map(H=>H.ruleId))];return{text:`The same ${i} error${ro(i)} in ${C} article${ro(C)} survived two ${c} passes, so a third would change nothing \u2014 ${i===1?"it needs":"they need"} a person. ${D} shows ${i===1?"it":"them"} in place. If ${U.length===1?`${U[0]} is`:"a rule is"} wrong for your product, switch it off in .d360-writer/config.json under "styleGuide": { "rules": { "<rule>": "off" } }.`,cmd:D}}return{text:`${i} error${ro(i)} in ${C} article${ro(C)} still block${i===1?"s":""} publishing. ${c} has another go at ${i===1?"it":"just those"} \u2014 if a second pass leaves the same ones, they need a human eye.`,cmd:c}}vd.delete(`${t}::${o??""}`);let p=a>0&&l>0?`${a} warning${ro(a)} and ${l} suggestion${ro(l)} remain (neither blocks publishing). `:a>0?`${a} warning${ro(a)} remain${a===1?"s":""}, which ${a===1?"does":"do"} not block publishing. `:l>0?`${l} suggestion${ro(l)} remain${l===1?"s":""} \u2014 ${l===1?"it is":"they are"} judgment calls and ${l===1?"does":"do"} not block publishing. `:"",m=p===""?"\u2713 Nothing left to fix. ":`\u2713 ${p}`,$=o?"/push":"/push --all";return Bt(t,{text:`${m}Nothing is blocking${o?` in ${o}`:""} \u2014 ${$} saves the articles to Document360 as drafts.`,cmd:$},m,o)}var ZC={check:"/check is now /lint (same command)."};function dl(){return"That saves drafts rather than taking anything live, so running /push. (/publish takes saved drafts live.)"}var rw=new Set;function Js(e){let t=ZC[e.replace(/^\//,"")];return!t||rw.has(e)?null:(rw.add(e),t)}var pP=400,hP=3e3,fP=e=>e>0?new Promise(t=>setTimeout(t,e)):Promise.resolve(),Sd=e=>e===1?"":"s",Rd=e=>e.replace(/\\/g,"/").split("/").pop()??e;function Cd(e){return e.includes("--screenshots")||e.includes("--shots")||e[0]==="--related"}async function Pd(e,t,n){await tP({cwd:e,profileName:t});let o=n?n.replace(/\\/g,"/").replace(/\/+$/,""):null;return oP(e,t).filter(r=>!o||r.path===o||r.path.startsWith(`${o}/`)).map(r=>({...r,label:mP(e,r.path)}))}function mP(e,t){let n=Ma(e,t)??Bs(t),o=_a(t),r=o?eo(o):"";return r?`${r} \u203A ${n}`:n}function gP(e){let t=Math.min(58,Math.max(...e.map(n=>n.label.length),20));return e.map(n=>` ${n.label.padEnd(t)} ${n.version?`draft v${n.version} \u2192 live`:"draft \u2192 live"}`)}function Td(e,t,n){let r=[`\u2713 Nothing is waiting to go live${n?` in ${n}`:""} \u2014 readers are seeing the latest version of every article.`],s=n?n.replace(/\\/g,"/").replace(/\/+$/,""):null,i=nP(e,t).filter(a=>!s||a===s||a.startsWith(`${s}/`)).length;return i>0&&r.push(`${i} article${Sd(i)} ${i===1?"has":"have"} local edits that aren't on Document360 yet \u2014 that's /push${n?` ${n}`:""}.`),{lines:r,ahead:i}}function pl(e,t,n){let o=null;try{o=lP(e,t.placeholders)?.cmd??null}catch{}return{cmd:t.unreviewed.length>0||t.styleErrors.length>0?Xs(t,n):o,shotFix:o}}function Ad(e,t,n,o){if(n)return null;let r=!1;try{r=cP(e,t).production}catch{return null}if(!r)return null;let s=o;return[`\u26A0 ${s} draft${s===1?"":"s"} ${s===1?"is":"are"} ready, and this is a PRODUCTION deployment.`," Nothing is blocking them \u2014 taking articles live here just needs authorizing once per session."," Run /allow-prod, then /publish."]}async function Ed(e,t,n,o={}){let r={published:[],blocked:[],failed:[]},s=0,i=pP,a=0;for(let l of n){o.onProgress?.(s,n.length,l.label);let c=await rP({onRateLimit:()=>{a+=1,i=Math.min(i*2,hP)},articleId:l.articleId,cwd:e,profileName:t,allowUnreviewed:o.skipReview===!0,allowStyleErrors:o.skipStyle===!0,allowProduction:o.allowProduction===!0});c.ok?r.published.push({path:l.path,...c.url?{url:c.url}:{}}):c.blocked?r.blocked.push({path:l.path,message:c.message,...c.commands.length>0?{commands:c.commands}:{}}):r.failed.push({path:l.path,message:c.error.message}),s+=1,s<n.length&&await fP(i)}return a>0&&(r.throttled={times:a,finalPacingMs:i}),r}function Nd(e){let{published:t,blocked:n,failed:o}=e,r=[];if(t.length>0){r.push(`\u2713 ${t.length} article${Sd(t.length)} ${t.length===1?"is":"are"} now live \u2014 readers see ${t.length===1?"it":"them"} now.`);let s=t.filter(i=>i.url);for(let i of s.slice(0,3))r.push(` \u2B95 ${i.url}`);s.length>3&&r.push(` \u2B95 \u2026and ${s.length-3} more`)}if(n.length>0){let s=n.length>0&&n.every(i=>(i.commands??[]).includes("/allow-prod"));r.push(s?`\u2717 ${n.length} not published \u2014 this is a PRODUCTION deployment and this session is not authorized. Still ${n.length===1?"a draft":"drafts"}:`:`\u2717 ${n.length} refused by the publish gates \u2014 still ${n.length===1?"a draft":"drafts"}, nothing was lost:`);for(let i of n.slice(0,3))r.push(` \xB7 ${Rd(i.path)}`);n.length>3&&r.push(` \xB7 \u2026and ${n.length-3} more`),r.push(s?" Run /allow-prod, then /publish.":" /status names what is blocking each one, and the command that clears it. It costs nothing.")}if(e.throttled){let s=(e.throttled.finalPacingMs/1e3).toFixed(1);r.push(`\u2139 Document360 asked us to slow down ${e.throttled.times} time${e.throttled.times===1?"":"s"}, so this run eased to ${s}s between articles.`)}if(o.length>0){r.push(`\u2717 ${o.length} failed \u2014 ${o.length===1?"it is":"they are"} still a draft, so re-running /publish retries ${o.length===1?"it":"them"}:`);for(let s of o.slice(0,3))r.push(` \xB7 ${Rd(s.path)} \u2014 ${s.message}`);o.length>3&&r.push(` \xB7 \u2026and ${o.length-3} more`)}return r.length===0&&r.push("Nothing was published."),r}async function sw(e,t){let n=t?.cwd??process.cwd();if(Cd(e))return console.log(u(`\u2192 ${dl()}`)),cl(e,t);let o=ot(n,t?.profileName);if(!o.ok){let[R,D]=Ft(o);return console.log(L(R)),console.log(u(D)),{kind:"continue"}}let r=e.includes(Wt),s=e.includes(uP),i=e.includes(dP),a=e.includes("--all"),l=e.find(R=>!R.startsWith("--"));console.log(u("Checking what is waiting to go live\u2026"));let c;try{c=await Pd(n,t?.profileName,l)}catch(R){return console.log(L(`Could not check Document360: ${R.message}`)),{kind:"continue"}}if(c.length===0){for(let R of Td(n,t?.profileName,l).lines)console.log(R.startsWith("\u2713")?Q(R):u(R));return{kind:"continue"}}let p=sP(n,c.map(R=>R.path),{allowUnreviewed:r,allowStyleErrors:s,checkScreenshots:!0,allowPlaceholders:i}),m=new Set(aP(p)),$=c.filter(R=>!m.has(R.path)),w=pl(n,p,l);if(m.size>0)for(let R of iP(p,c.length,{scope:l,act:"publish",going:$.length,shotFix:w.shotFix}))console.log(W(R));if($.length===0)return w.cmd&&console.log(u(`Run: ${w.cmd}`)),{kind:"continue"};c=$,console.log(""),console.log(`${c.length} draft${Sd(c.length)} ${c.length===1?"is":"are"} ahead of what readers see:`);for(let R of gP(c.slice(0,12)))console.log(u(R));c.length>12&&console.log(u(` \u2026and ${c.length-12} more`)),console.log("");let C=c;if(!a){let R=await eP({message:"Publish live to your readers?",choices:[{name:`Yes \u2014 publish all ${c.length} live`,value:"all"},...c.slice(0,8).map(D=>({name:`Just ${D.label}`,value:D.path})),{name:"No \u2014 leave them as drafts",value:"none"}]});if(R==="none")return console.log(u("Left as drafts. Nothing changed.")),{kind:"continue"};R!=="all"&&(C=c.filter(D=>D.path===R))}let S=Ad(n,t?.profileName,t?.allowProdWrites?.()===!0,C.length);if(S){for(let R of S)console.log(R.startsWith("\u26A0")?W(R):u(R));return{kind:"continue"}}let T=await Ed(n,t?.profileName,C,{skipReview:r,skipStyle:s,allowProduction:t?.allowProdWrites?.()===!0,onProgress:(R,D,U)=>console.log(u(` \u25B8 ${R+1}/${D} ${Rd(U)}\u2026`))});console.log("");for(let R of Nd(T))console.log(R.startsWith("\u2713")?Q(R):R.startsWith("\u2717")?W(R):u(R));return{kind:"continue"}}import{loadKnownConflicts as yP,localArticleTitle as wP,resolveActiveProfile as kP,surfaceCoverageSafe as iw,readProjectConfig as aw,recordDeclinedSurface as bP,areaExists as $P,declineTargets as lw}from"document360-engine";function vP(e,t){let n=wP(e,t);return n||(t.split(/[\\/]/).pop()??t).replace(/\.md$/,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ")}function hl(e,t){let n=[];try{n=yP(e,kP(e,t).name)}catch{return null}if(n.length===0)return null;let o=n.length,r=n.slice(0,3).map(i=>vP(e,i)),s=o>3?`${r.join(", ")} and ${o-3} more`:r.join(", ");return{paths:n,note:`\u26A0 ${o} article${o===1?"":"s"} ${o===1?"has":"have"} been changed both here and on Document360 (${s}), so your local copy is not a reliable picture of what your readers have. An audit over it could tell you to write an article that already exists, or miss one that needs your decision \u2014 so it needs ${o===1?"that":"those"} settled first.`}}var Br={cmd:"/resolve",reason:"it walks each one with you \u2014 keep yours, take the portal's, or skip"};function fl(e,t){let n=t.indexOf("--decline");if(n<0)return null;let o=t[n+1];if(!o||o.startsWith("--")){let a=iw(e,aw(e)),l=a.recognised?a.areas.slice(0,5).flatMap(c=>lw(c).map(p=>` /audit --decline ${p}`)):[];return["Name the path to decline \u2014 a folder, or a single file.",...l.length?["","No article covers these right now. Run one of these to settle it for good:",...l]:["","For example:"," /audit --decline src/internal-admin"]]}let r=o.replace(/\\/g,"/").replace(/\/+$/,"");if(!$P(e,r))return[`There is nothing at ${r}, so there is nothing to decline. Copy the path from /eval or /audit.`];let s=t.slice(n+2).filter(a=>!a.startsWith("--")).join(" ")||void 0;return bP(e,r,s)?[`\u2713 ${r} will not be reported as needing an article. /audit and /eval leave it out from now on, and say how many you have declined.`]:[`Could not write .d360-writer/declined-surfaces.json, so ${r} was not declined.`]}async function Zs(e){if(e?.cwd){let r=hl(e.cwd,e.profileName);if(r)return{kind:"audit-blocked",note:r.note,lead:Br}}let t=e?.cwd?iw(e.cwd,aw(e.cwd)):null,n=[];if(t?.recognised&&t.areas.length>0){let r=t.areas.slice(0,15);n.push("","2.7. These parts of the product are cited by NO article's `sources:` frontmatter. This list is DETERMINISTIC and complete as of now \u2014 it does not depend on the diff window above, so treat it as authoritative rather than re-deriving it:",...r.map(s=>` - ${s.folder} (${s.files} of ${s.total} file${s.total===1?"":"s"} uncited, e.g. ${s.sample.join(", ")}) \u2014 to decline: ${lw(s).map(i=>`/audit --decline ${i}`).join(" \xB7 ")}`),...t.areas.length>r.length?[` \u2026and ${t.areas.length-r.length} more areas.`]:[]," EVERY row above must leave this run accounted for: a `create` row, or a stated reason it needs no article (internal-only, unreachable by a reader, already covered by an existing article's prose). Do NOT silently drop one \u2014 if you list fewer paths than this section handed you, say which you left out and why."," A `decline` verdict is not a record. For EVERY row you decline, print its exact /audit --decline line (copied from above \u2014 it already picks folder-or-file correctly) in the closing block, each on its own line so the terminal makes it a button. A judgement that leaves the turn as prose changes nothing and will be re-derived, at this price, on every future audit.",...t.declined>0?[` (${t.declined} more ${t.declined===1?"is":"are"} already declined and left out of that list.)`]:[])}return{kind:"forward-to-agent",prompt:["Run the gap-analysis skill against this repo.","","Follow its stages in order:","1. d360_sync_status first; stop if any article is changed in both places, or changed on Document360 and not yet pulled down (the local copy cannot be trusted until that is resolved). Say which articles, in plain words, never the internal status word \u2014 and tell the user to run /resolve, which walks the affected articles one at a time (keep the local copy, take the portal's, or skip). Do NOT ask them to report back to you: they will run /resolve and then /audit again.","2. git diff since the lastAnalyzedCommit marker in d360-category-map.json (or last 30 days if no marker), filtered to the authoritativeSourceFiles paths.","2.5. d360_pending_hints: the source agent's own notes on what it shipped. Verify each against the CURRENT code (its `sources` exist, and the code as it stands shows the surface it claims) before trusting it; never judge it by its `branch` or `commit`. Fold verified ones into the table, flag the rest.","2.6. Anything d360_pending_hints returns under `held` is NOT a proposal. Its cited code has uncommitted changes, so the builder is still writing that surface and has already been asked whether it is done. List each held item at the END of the table as a `waiting` row (Reason: the code behind it is not finished), do NOT propose create/update/retire for it, and do NOT stamp it consumed.",...n,"3. Map changes (diff + hints) to articles via their `sources:` frontmatter; read only implicated articles and changed source files. If articles are missing `sources:`, this is the one-time bootstrap pass, so backfill them.","4. Output the proposal table: | Article (path or proposed title) | Action (create | update | retire | link) | Reason | Evidence | Scope |. Leave every hint OPEN \u2014 this run proposes, it does not write articles, so nothing has been acted on yet.","5. End with the skill's closing block, and put NOTHING below it \u2014 no receipts, no roadmap confirmations, no feedback marker line, no summary. It ends in a question, and a question the user has to scroll back to find is one you did not really ask.","","Do not start writing or updating any article yet; the proposal table is the deliverable.","The audited-up-to marker is recorded for you when this command finishes. Read it to size the diff window; never write it, and never report it as a missing capability."].join(`
|
|
344
|
-
`),display:"/audit"}}
|
|
345
|
-
`)}async function
|
|
343
|
+
`):null}async function Bw(e,t){let n=t.cwd;if(e[0]?.toLowerCase()==="done"){let o=Zr(n,e.slice(1).join(" ").trim());return console.log(o.ok?Q(o.line):F(o.line)),{kind:"continue"}}for(let o of zd(n,{all:e.some(r=>r.toLowerCase()==="--all")}))console.log(o);return{kind:"continue"}}var Qd={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 pushing overwrites the portal edit"},yA="\u26A0 held on Document360 in another editor \u2014 /resolve settles it";function tr(e){return e.filter(t=>t.path!==null&&t.status in Qd&&!t.link).map(t=>({path:t.path,label:Qd[t.status]}))}function Zo(e,t=[]){let n=tr(e),o=new Set(t),r=new Set([...e.filter(s=>s.status==="conflict"&&s.path).map(s=>s.path),...o]);return{clean:n.filter(s=>!r.has(s.path)),conflicts:n.filter(s=>r.has(s.path)).map(s=>o.has(s.path)&&s.label!==Qd.conflict?{...s,label:yA}:s)}}function er(e,t){try{return sA(e,El(e,t).name).map(n=>n.path)}catch{return[]}}function ui(e,t=0){let n=e!==1;if(t>=e)return`\u26A0 ${e} article${n?"s":""} NOT pushed (nothing on the portal overwritten) \u2014 Document360 holds ${n?"their bodies":"its body"} in another editor, so ${n?"they cannot be":"it cannot be"} read back. Settle ${n?"them":"it"}: /resolve (or ask your Document360 admin to move ${n?"them":"it"} to the Markdown editor).`;let o=t>0?` (${t} of ${n?"them are":"these is"} held in another editor and cannot be read back)`:"";return`\u26A0 ${e} conflict${n?"s":""} NOT pushed (portal edit${n?"s":""} kept safe) \u2014 ${n?"these were":"it was"} edited both here and on the portal, so ${n?"they are":"it is"} left untouched.${o} Settle ${n?"them":"it"}: /resolve (or /push <path> to keep yours, /pull <path> to take the portal's).`}function Jd(e,t){let n=t.scope?.replace(/\\/g,"/").replace(/\/+$/,"");return!n||!n.endsWith(".md")||!Vw(e,t.profileName).map(r=>r.replace(/\\/g,"/")).some(r=>r===n||r.endsWith(`/${n}`)||n.endsWith(`/${r}`))?null:{cmd:Ee("/publish","",n),reason:"it takes this draft live \u2014 until it does, your readers still see the previous version"}}function es(e,t){let n=Vw(e,t),o=n.length;if(o===0)return null;let r=o===1?"":"s",s=0;try{s=rA(e,n).length}catch{}if(s>0){let i=o-s,a=`${s===o?o===1?"It is":"All of them are":`${s} of them ${s===1?"is":"are"}`} waiting on a missing picture`;return`\u2139 ${o} article${r} ${o===1?"is":"are"} saved on Document360 as a draft and not live yet \u2014 readers still see the previous version. ${a}, so /publish holds ${s===1?"it":"them"} back${i>0?` and takes the other ${i} live once ${i===1?"it has":"they have"} been signed off.`:"."}`}return`\u2139 ${o} article${r} ${o===1?"is":"are"} saved on Document360 as a draft and not live yet \u2014 readers still see the previous version. /publish takes ${o===1?"it":"them"} live once ${o===1?"it has":"they have"} been signed off.`}function Tl(e){return e.filter(t=>t.link).length}function Zd(e,t){try{let n=qw(e,El(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=mA(ZP(eA(e,r),"utf8"),r,n).unresolved}catch{}return o===0?null:`\u2139 ${o} cross-link${o===1?"":"s"} point to pages that aren't on Document360 yet \u2014 they show as plain text for now and turn into links once those pages are pushed.`}catch{return null}}function Zw(e,t=[]){let n=[];e.length>1&&n.push({kind:"all",label:`Push all ${e.length} articles`,paths:e.map(r=>r.path),indent:!1});let o=new Map;for(let r of e){let s=r.path.replace(/\\/g,"/").split("/").slice(0,-1).join("/"),i=o.get(s);i?i.push(r):o.set(s,[r])}for(let r of[...o.keys()].sort()){let s=o.get(r).sort((i,a)=>i.path.localeCompare(a.path));n.push({kind:"category",label:`${ao(r)} (${s.length})`,paths:s.map(i=>i.path),indent:!1});for(let i of s){let a=i.path.replace(/\\/g,"/").split("/").pop()??i.path;n.push({kind:"article",label:a,paths:[i.path],indent:!0,note:i.label})}}for(let r of[...t].sort((s,i)=>s.path.localeCompare(i.path))){let s=r.path.replace(/\\/g,"/").split("/").pop()??r.path;n.push({kind:"article",label:s,paths:[r.path],indent:!1,note:r.label,conflict:!0})}return n}async function di(e,t){try{let n=El(e,t),o=n.project.projectId,r=n.project.workspaceId;if(!o||!r)return null;let s=await fA({profile:n.name,connection:n.connection,projectId:o,projectName:n.project.projectName},{cwd:e,profile:n.name,projectPath:`/v3/projects/${o}`,workspaceId:r,verifyHidden:!1});if(s.kind!=="created")return null;if(s.hidden!=="confirmed"){let i=s.seeded.length===0?" Its internal articles were NOT created, because that would put docs-agent scaffolding in front of your readers.":"";return`\u26A0 Created the "${Hw}" folder on Document360 for reviewer feedback, but could NOT confirm it is hidden from readers.${i} Open its category settings in the portal and turn on "Hide from readers", then run /catch-up.`}return`\u2139 Created a hidden "${Hw}" folder on Document360 \u2014 it's where your reviewers leave feedback for ${gA} to action (confirmed hidden from readers; its README explains how). /catch-up picks up what they write.`}catch{return null}}var Vt="--skip-review";function pi(e,t){return iA(e,t)}function Nl(e,t){try{return pi(e,Yw(e,t)).length}catch{return 0}}function Kt(e,t,n="",o,r){let s=Nl(e,o),i=Dl(e,o),a=o?` ${o}`:"",l=o?"/push":"/push --all",c=Ew(e,{just:r}),p=!!o&&o.endsWith(".md"),m=c&&p?` (${c.short} \u2014 ${c.cmd} once this page is delivered.)`:"";if(c&&!p){let C=s>0?` (${s} article${s===1?"":"s"}${o&&!o.endsWith(".md")?` in ${o}`:""} ${s===1?"carries":"carry"} text no editor has read, so ${s===1?"it cannot":"they cannot"} be sent up until /review${a} --blocked --fix runs \u2014 that can wait until the writing is done.)`:i>0?` (${i} article${i===1?"":"s"} break${i===1?"s":""} house style rules that block sending up \u2014 /lint${a} --blocked --fix clears that whenever you want.)`:"";return{text:`${n}${c.text}${C}`,cmd:c.cmd}}if(s===0&&i===0)return m?{...t,text:`${t.text}${m}`}:t;let $=o&&!o.endsWith(".md")?` in ${o}`:"";if(s>0){let C=s===1?"":"s",S=i>0?` ${i} also break house style rules \u2014 /lint${a} --blocked --fix clears those afterwards.`:"",A=`/review${a} --blocked --fix`;return{text:`${n}${s} article${C}${$} ${s===1?"carries":"carry"} text no editor has read, so pushing ${s===1?"it is":"them is"} blocked. ${A} reads ${s===1?"it":"just those"} and applies its fixes.${S} Then ${l}.${m}`,cmd:A}}return{text:`${n}${i} article${i===1?"":"s"}${$} break${i===1?"s":""} house style rules that block publishing. /lint${a} --blocked --fix corrects them in place \u2014 finding them costs nothing \u2014 then ${l}.${m}`,cmd:`/lint${a} --blocked --fix`}}function Dl(e,t){try{return Kw(e,Yw(e,t)).length}catch{return 0}}function ek(e,t){return Kw(e,t)}function ep(e,t,n){try{let o=qw(e,El(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 tp(e,t){let n=`/push${t.scope?` ${t.scope}`:" --all"}`,o=l=>`${l} article${l===1?"":"s"}`,r=[],s=e.pushed.length,i=t.elapsedMs!==void 0?` \xB7 ${bA(t.elapsedMs)}`:"",a=e.screenshotsUploaded>0?` \xB7 ${e.screenshotsUploaded} screenshot${e.screenshotsUploaded===1?"":"s"} uploaded`:"";s===0&&e.failed.length===0?r.push("Nothing was pushed \u2014 no articles were sent."):t.recorded<s?(r.push(`Pushed ${t.recorded}/${o(s)}${a}${i}.`),r.push(`${s-t.recorded} article${s-t.recorded===1?"":"s"} reported success but ${s-t.recorded===1?"is":"are"} not recorded in the category map \u2014 re-run ${n}.`)):(r.push(`Pushed ${o(s)}${e.created>0?` (${e.created} new)`:""}${a}${i}.`),r.push(`Saved on Document360 as draft${s===1?"":"s"} \u2014 readers don't see ${s===1?"it":"them"} until /publish takes ${s===1?"it":"them"} live.`)),e.stopped?.reason==="unavailable"&&r.push(`Stopped: ${e.stopped.streak} articles in a row could not reach Document360${e.notRun.length>0?`, so the remaining ${e.notRun.length} ${e.notRun.length===1?"was":"were"} not attempted`:""}.`);for(let l of e.duplicateCategories??[])r.push(`\u26A0 Document360 now holds ${l.ids.length} categories called "${l.name}" \u2014 your articles are split between them.`);if((e.duplicateCategories??[]).length>0&&r.push(" Nothing here deletes a category. Remove the extra ones in the portal, then run /push --all again."),e.stopped?.reason==="identity"&&r.push(`Nothing was pushed. ${e.stopped.error}`),e.failed.length>0){let l=e.failed.filter(m=>m.refused),c=kA(e.failed,t.docsRoot),p=e.failed.length;if(c.length===1&&p>1)r.push(`${o(p)} could not be pushed \u2014 all with the same error: ${c[0].error}`),r.push(...Gw(c[0].paths," \u2717 "));else{r.push(`${o(p)} could not be pushed:`);for(let m of c)m.paths.length===1?r.push(` \u2717 ${m.paths[0]} \u2014 ${m.error}`):(r.push(` \u2717 ${o(m.paths.length)} \u2014 ${m.error}`),r.push(...Gw(m.paths," ")))}l.length<e.failed.length&&(e.stopped?r.push(`Nothing was lost \u2014 your articles are unchanged. Re-run ${n} when Document360 is back.`):r.push(`Re-run ${n} to retry the rest \u2014 articles already saved are sent again only if they changed.`))}if(e.notRun.length>0&&!e.stopped&&r.push(`\u26A0 ${o(e.notRun.length)} never started (the run was stopped): ${wA(e.notRun)}`),e.missingShots.length>0){let l=e.missingShots.flatMap(c=>c.ids);r.push(`\u26A0 ${l.length} screenshot${l.length===1?"":"s"} in ${o(e.missingShots.length)} ${l.length===1?"has":"have"} not been taken, so the description was published instead: /screenshot capture`)}if(e.categoryLookupFailed.length>0){let l=e.categoryLookupFailed.length;r.push(`\u26A0 Could not check Document360 for existing categories, so ${l===1?"a new one was":`${l} new ones were`} created. There may now be two with the same name: /doctor lists them.`),r.push(` Reason: ${e.categoryLookupFailed[0].reason}`)}return t.conflictsSkipped&&t.conflictsSkipped>0&&r.push(ui(t.conflictsSkipped,t.unreadableSkipped??0)),r}var wA=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Xd=5;function Gw(e,t){let n=e.slice(0,Xd).map(o=>`${t}${o}`);return e.length>Xd&&n.push(`${" ".repeat(t.length)}\u2026 +${e.length-Xd} more`),n}function kA(e,t){let n=t?`${t.replace(/\\/g,"/").replace(/\/+$/,"")}/`:null,o=s=>{let i=s.replace(/\\/g,"/");return n&&i.startsWith(n)?i.slice(n.length):i},r=new Map;for(let s of e){let i=r.get(s.error);i?i.push(o(s.path)):r.set(s.error,[o(s.path)])}return[...r.entries()].map(([s,i])=>({error:s,paths:i})).sort((s,i)=>i.paths.length-s.paths.length)}function bA(e){let t=Math.round(e/1e3);return t<60?`${t}s`:`${Math.floor(t/60)}m ${String(t%60).padStart(2,"0")}s`}async function cn(e,t,n=0,o){let r=aA(e.cwd,t,{allowUnreviewed:o?.skipReview===!0,allowStyleErrors:o?.skipStyle===!0});if(!r.clear){for(let c of lA(r,t.length,{act:"push"}))console.log(F(c));return{kind:"continue"}}let s={aborted:!1,partitions:0,failed:0,notRun:0,producedNothing:!0},i={retryable:0,stopped:!1,paths:[]},a=async(c,p)=>{let m=Date.now();console.log(u(p?`Resolving cross-links in ${c.length} article${c.length===1?"":"s"} whose targets published this run (second pass)\u2026`:`Pushing ${c.length} article${c.length===1?"":"s"} to Document360 (${dA} at a time)\u2026`));let $=await cA({cwd:e.cwd,...e.profileName?{profileName:e.profileName}:{},paths:c,...o?.allowUnpullable===!0?{allowUnpullable:!0}:{},onEvent:W=>{W.type==="article_done"?console.log(Q(` \u2713 ${W.result.path}${W.result.action==="created"?" (new)":""}`)):W.type==="article_failed"&&console.log(L(` \u2717 ${W.failure.path}`))}});console.log("");let w=ep(e.cwd,c,e.profileName);p||(i={retryable:$.failed.filter(W=>!W.refused).length,stopped:!!$.stopped,paths:$.failed.map(W=>W.path)},s={aborted:$.aborted||!!$.stopped,partitions:nA(c).length,failed:$.failed.length,notRun:$.notRun.length,producedNothing:$.pushed.length===0,verifiedComplete:w>=c.length,leftBehind:n});let C=$.pushed.length>0;for(let W of tp($,{recorded:w,elapsedMs:Date.now()-m,docsRoot:hA(e.cwd),...p?{}:{conflictsSkipped:n,unreadableSkipped:o?.unreadableSkipped??0},...o?.scope?{scope:o.scope}:{}}))console.log(C&&$.failed.length===0?Q(W):F(W));let S=$.aborted||!!$.stopped;if(!C)return S;let A=Zd(e.cwd,e.profileName);A&&console.log(u(A));let R=es(e.cwd,e.profileName);if(R&&console.log(u(R)),S)return S;try{let W=Xw(await zw({cwd:e.cwd,profileName:e.profileName,onRateLimit:H=>console.log(u(` Document360 rate limit \u2014 waiting ${Math.ceil(H.waitMs/1e3)}s\u2026`))}));W&&console.log(W.startsWith("\u26A0")?F(W):u(W))}catch{}try{let W=Jw(await Qw({cwd:e.cwd,profileName:e.profileName}));W&&console.log(u(W))}catch{}let D=await di(e.cwd,e.profileName);return D&&console.log(u(D)),S};try{if(!await a(t,!1)){let p=await np(e.cwd,e.profileName,t,i.paths);if(p.length>0&&await a(p,!0),ln(s))for(let m of Ze(e.cwd,o?.scope?`/push ${o.scope}`:"/push --all"))console.log(Q(m))}}catch(c){console.log(L(`Push run failed: ${c.message}`))}if(console.log(""),i.retryable>0){let c=Ee("/push",o?.scope?"":"--all",o?.scope);return console.log(u(i.stopped?`Next: ${c} \u2014 your articles are unchanged, so it picks up where the run left off.`:`Next: ${c} \u2014 retries the ${i.retryable} article${i.retryable===1?"":"s"} that could not be saved.`)),{kind:"continue",ownNext:!0}}let l=Jd(e.cwd,{scope:o?.scope,profileName:e.profileName});return l?(console.log(u(`Next: ${l.cmd} \u2014 ${l.reason}.`)),{kind:"continue",ownNext:!0}):{kind:"continue"}}async function jl(e,t,n){let o=oA(e,n);if(o.length===0)return[];let r=new Set(tr((await Al({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function np(e,t,n,o=[]){try{let r=new Set(n),s=new Set(o),i=await Al({cwd:e,profileName:t});return tr(i.entries).map(a=>a.path).filter(a=>r.has(a)&&!s.has(a))}catch{return[]}}async function $A(e,t,n){try{let o=await uA({cwd:e,...t?{profileName:t}:{},relPath:n.replace(/\\/g,"/"),preview:!0});console.log(""),console.log(Q(`${o.title}`)),console.log(u(`${o.path} \xB7 ${o.articleId?`updates article ${o.articleId}`:"would be created as a new article"}`)),o.shots.length>0&&console.log(u(`${o.shots.length} screenshot${o.shots.length===1?"":"s"} embedded: ${o.shots.map(r=>r.id).join(", ")}`)),o.missingShots.length>0&&console.log(F(`\u26A0 ${o.missingShots.length} screenshot${o.missingShots.length===1?"":"s"} not taken yet \u2014 the description publishes instead: ${o.missingShots.join(", ")}`)),console.log(u("\u2500".repeat(Math.min(80,Math.max(20,(process.stdout.columns??80)-1))))),console.log(o.body),console.log(u("\u2500".repeat(Math.min(80,Math.max(20,(process.stdout.columns??80)-1))))),console.log(u(`Nothing was sent. Run /push ${o.path} to save it as a draft.`))}catch(o){console.log(L(o.message))}return{kind:"continue"}}async function Il(e,t){let n=st(t?.cwd??process.cwd(),t?.profileName);if(!n.ok){let[i,a]=Gt(n);return console.log(L(i)),console.log(u(a)),{kind:"continue"}}let o=e.includes(Vt),r=e.includes(pA);if(e.includes("--preview")){let i=e.find(a=>!a.startsWith("--"));return i?await $A(t?.cwd??process.cwd(),t?.profileName,i):(console.log(L("Which article? Use /push --preview <path> \u2014 a preview is per article.")),{kind:"continue"})}let s=e[0];if(e.includes("--screenshots")||e.includes("--shots")){let i=t?.cwd??process.cwd(),a=e.find(w=>!w.startsWith("--")),l=Ke(i),c=kl(l,a);if(c.length===0){let w=l.filter(C=>C.state==="captured").length;return console.log(u(w>0?`${w} screenshot${w===1?" has":"s have"} been taken but the callouts aren't drawn on yet, so there is nothing to embed \u2014 /screenshot annotate finishes ${w===1?"it":"them"}.`:a?`No captured screenshots in ${a} \u2014 /push --screenshots covers the whole knowledge base.`:"No captured screenshots yet \u2014 /screenshot capture first.")),{kind:"continue"}}let p=bl(l,a);p&&console.log(p);let m=$l(l);m&&console.log(m);let $=Ee("","--screenshots",a).trim();return await cn(t??{cwd:process.cwd()},c,0,{skipReview:o,skipStyle:r,scope:$})}if(s==="--related"&&e[1]){if(!t)return{kind:"continue"};let i=await jl(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return i.length===0?(console.log(Q("\u2713 All related articles are already on Document360.")),{kind:"continue"}):await cn(t,i,0,{skipReview:o,skipStyle:r,scope:`--related ${e[1]}`})}if(s==="--all"){console.log(u("Checking what needs pushing\u2026"));try{let i=await Al({cwd:t?.cwd??process.cwd()}),a=new Set(er(t?.cwd??process.cwd(),t?.profileName)),{clean:l,conflicts:c}=Zo(i.entries,a),p=c.filter(S=>a.has(S.path)).length,m=Tl(i.entries),$=e.includes("--force"),w=$&&c.length>0;m>0&&console.log(F(`\u26A0 ${m} article(s) already exist on Document360 but aren't linked \u2014 left out (pushing would duplicate them). Run /catch-up or ask me to link them first.`)),c.length>0&&!w&&console.log(F(ui(c.length,p)));let C=w?[...l,...c]:l;if(C.length===0){if(c.length>0){let A=es(t?.cwd??process.cwd(),t?.profileName);return A&&console.log(u(A)),console.log(u("Resolve the conflicts: /resolve")),{kind:"continue"}}console.log(Q(m>0?"\u2713 Nothing else is ahead of Document360 to push.":"\u2713 Nothing is ahead of Document360 \u2014 nothing to push."));let S=es(t?.cwd??process.cwd(),t?.profileName);if(S&&console.log(u(S)),t)try{let A=Xw(await zw({cwd:t.cwd,profileName:t.profileName,onRateLimit:D=>console.log(u(` Document360 rate limit \u2014 waiting ${Math.ceil(D.waitMs/1e3)}s\u2026`))}));A&&console.log(A.startsWith("\u26A0")?F(A):u(A));let R=Jw(await Qw({cwd:t.cwd,profileName:t.profileName}));R&&console.log(u(R))}catch{}return{kind:"continue"}}return await cn(t??{cwd:process.cwd()},C.map(S=>S.path),w?0:c.length,{skipReview:o,skipStyle:r,allowUnpullable:$,unreadableSkipped:w?0:p})}catch(i){return console.log(L(`Could not compute sync status: ${i.message}`)),{kind:"continue"}}}if(s&&s.startsWith("--")&&(s=e.find(i=>!i.startsWith("--"))??""),!s){console.log(u("Checking what needs pushing\u2026"));let i,a=0,l=0;try{let c=await Al({cwd:t?.cwd??process.cwd()}),p=new Set(er(t?.cwd??process.cwd(),t?.profileName)),{clean:m,conflicts:$}=Zo(c.entries,p);l=$.filter(C=>p.has(C.path)).length,i=m,a=$.length;let w=Tl(c.entries);if(w>0&&console.log(F(`\u26A0 ${w} article(s) already exist on Document360 but aren't linked \u2014 left out (pushing would duplicate them). Run /catch-up or ask me to link them first.`)),$.length>0&&console.log(F(ui($.length,l))),i.length===0&&$.length>0)return console.log(u("Resolve the conflicts: /resolve")),{kind:"continue"}}catch(c){return console.log(L(`Could not compute sync status: ${c.message}`)),console.log(u("Push a specific article: /push <article-path>")),{kind:"continue"}}if(i.length===0)return console.log(Q("\u2713 Nothing is ahead of Document360 \u2014 nothing to push.")),console.log(u(" (Articles without a sync base are unverified \u2014 push those by path if needed.)")),{kind:"continue"};if(!process.stdin.isTTY||!t){for(let c of i)console.log(` ${c.path} ${u(`(${c.label})`)}`);return console.log(u("Run: /push <article-path>")),{kind:"continue"}}try{s=await t.withPausedInput(()=>tA({message:"Push which article?",choices:[...i.length>1?[{name:`All ${i.length} candidates`,value:"--all",description:"one agent run over every candidate"}]:[],...i.map(c=>({name:c.path,value:c.path,description:c.label}))]}))}catch{return console.log(u("Cancelled.")),{kind:"continue"}}if(s==="--all")return await cn(t,i.map(c=>c.path),a,{skipReview:o,skipStyle:r,unreadableSkipped:l})}return await cn(t??{cwd:process.cwd()},[s],0,{skipReview:o,skipStyle:r,scope:s})}ae();import{select as CA}from"@inquirer/prompts";import{computeSyncStatus as PA,localAheadPaths as AA,pendingDrafts as TA,publishArticleLive as EA,publishGateVerdict as NA,publishGateLines as DA,blockedPaths as jA,placeholderRemedy as IA,resolveActiveProfile as LA,SKIP_STYLE_FLAG as OA,SKIP_SHOTS_FLAG as _A}from"document360-engine";import{gateFixTarget as vA,WRITER_DIRNAME as xA}from"document360-engine";var rp=e=>"ruleId"in e,Ll=e=>rp(e)?e.severity:"warning",po=e=>e===1?"":"s";function hi(e,t){let n=t??vA(e),o=n?` ${n}`:"";return e.unreviewed.length>0?`/review${o} --blocked --fix`:`/lint${o} --blocked --fix`}var op=new Map;var RA=e=>rp(e)?e.fp||`${e.ruleId}:${e.path}:${e.line}:${e.term}`:`${e.kind}:${e.path}:${e.line}`;function fi(e){let{cwd:t,after:n,scope:o,aborted:r,blocked:s}=e,i=n.filter(w=>Ll(w)==="error").length,a=n.filter(w=>Ll(w)==="warning").length,l=n.filter(w=>Ll(w)==="suggestion").length,c=Ee("/lint","--blocked --fix",o);if(r){let w=Ee("/lint",s?"--blocked --fix":"--fix",o);return{text:`Stopped. Nothing else changed \u2014 ${w} picks up where this left off.`,cmd:w}}if(i>0){let w=n.filter(D=>Ll(D)==="error"),C=new Set(w.map(D=>D.path)).size,S=`${t}::${o??""}`,A=w.map(RA).sort().join("|"),R=op.get(S)===A;if(op.set(S,A),R){let D=Ee("/lint","--blocked --full",o),W=[...new Set(w.filter(rp).map(H=>H.ruleId))];return{text:`The same ${i} error${po(i)} in ${C} article${po(C)} survived two ${c} passes, so a third would change nothing \u2014 ${i===1?"it needs":"they need"} a person. ${D} shows ${i===1?"it":"them"} in place. If ${W.length===1?`${W[0]} is`:"a rule is"} wrong for your product, switch it off in ${xA}/config.json under "styleGuide": { "rules": { "<rule>": "off" } }.`,cmd:D}}return{text:`${i} error${po(i)} in ${C} article${po(C)} still block${i===1?"s":""} publishing. ${c} has another go at ${i===1?"it":"just those"} \u2014 if a second pass leaves the same ones, they need a human eye.`,cmd:c}}op.delete(`${t}::${o??""}`);let p=a>0&&l>0?`${a} warning${po(a)} and ${l} suggestion${po(l)} remain (neither blocks publishing). `:a>0?`${a} warning${po(a)} remain${a===1?"s":""}, which ${a===1?"does":"do"} not block publishing. `:l>0?`${l} suggestion${po(l)} remain${l===1?"s":""} \u2014 ${l===1?"it is":"they are"} judgment calls and ${l===1?"does":"do"} not block publishing. `:"",m=p===""?"\u2713 Nothing left to fix. ":`\u2713 ${p}`,$=o?"/push":"/push --all";return Kt(t,{text:`${m}Nothing is blocking${o?` in ${o}`:""} \u2014 ${$} saves the articles to Document360 as drafts.`,cmd:$},m,o)}var SA={check:"/check is now /lint (same command)."};function Ol(){return"That saves drafts rather than taking anything live, so running /push. (/publish takes saved drafts live.)"}var tk=new Set;function mi(e){let t=SA[e.replace(/^\//,"")];return!t||tk.has(e)?null:(tk.add(e),t)}var MA=400,UA=3e3,FA=e=>e>0?new Promise(t=>setTimeout(t,e)):Promise.resolve(),ip=e=>e===1?"":"s",sp=e=>e.replace(/\\/g,"/").split("/").pop()??e;function ap(e){return e.includes("--screenshots")||e.includes("--shots")||e[0]==="--related"}async function lp(e,t,n){await PA({cwd:e,profileName:t});let o=n?n.replace(/\\/g,"/").replace(/\/+$/,""):null;return TA(e,t).filter(r=>!o||r.path===o||r.path.startsWith(`${o}/`)).map(r=>({...r,label:WA(e,r.path)}))}function WA(e,t){let n=ll(e,t)??si(t),o=al(t),r=o?ao(o):"";return r?`${r} \u203A ${n}`:n}function BA(e){let t=Math.min(58,Math.max(...e.map(n=>n.label.length),20));return e.map(n=>` ${n.label.padEnd(t)} ${n.version?`draft v${n.version} \u2192 live`:"draft \u2192 live"}`)}function cp(e,t,n){let r=[`\u2713 Nothing is waiting to go live${n?` in ${n}`:""} \u2014 readers are seeing the latest version of every article.`],s=n?n.replace(/\\/g,"/").replace(/\/+$/,""):null,i=AA(e,t).filter(a=>!s||a===s||a.startsWith(`${s}/`)).length;return i>0&&r.push(`${i} article${ip(i)} ${i===1?"has":"have"} local edits that aren't on Document360 yet \u2014 that's /push${n?` ${n}`:""}.`),{lines:r,ahead:i}}function _l(e,t,n){let o=null;try{o=IA(e,t.placeholders)?.cmd??null}catch{}return{cmd:t.unreviewed.length>0||t.styleErrors.length>0?hi(t,n):o,shotFix:o}}function up(e,t,n,o){if(n)return null;let r=!1;try{r=LA(e,t).production}catch{return null}if(!r)return null;let s=o;return[`\u26A0 ${s} draft${s===1?"":"s"} ${s===1?"is":"are"} ready, and this is a PRODUCTION deployment.`," Nothing is blocking them \u2014 taking articles live here just needs authorizing once per session."," Run /allow-prod, then /publish."]}async function dp(e,t,n,o={}){let r={published:[],blocked:[],failed:[]},s=0,i=MA,a=0;for(let l of n){o.onProgress?.(s,n.length,l.label);let c=await EA({onRateLimit:()=>{a+=1,i=Math.min(i*2,UA)},articleId:l.articleId,cwd:e,profileName:t,allowUnreviewed:o.skipReview===!0,allowStyleErrors:o.skipStyle===!0,allowProduction:o.allowProduction===!0});c.ok?r.published.push({path:l.path,...c.url?{url:c.url}:{}}):c.blocked?r.blocked.push({path:l.path,message:c.message,...c.commands.length>0?{commands:c.commands}:{}}):r.failed.push({path:l.path,message:c.error.message}),s+=1,s<n.length&&await FA(i)}return a>0&&(r.throttled={times:a,finalPacingMs:i}),r}function pp(e){let{published:t,blocked:n,failed:o}=e,r=[];if(t.length>0){r.push(`\u2713 ${t.length} article${ip(t.length)} ${t.length===1?"is":"are"} now live \u2014 readers see ${t.length===1?"it":"them"} now.`);let s=t.filter(i=>i.url);for(let i of s.slice(0,3))r.push(` \u2B95 ${i.url}`);s.length>3&&r.push(` \u2B95 \u2026and ${s.length-3} more`)}if(n.length>0){let s=n.length>0&&n.every(i=>(i.commands??[]).includes("/allow-prod"));r.push(s?`\u2717 ${n.length} not published \u2014 this is a PRODUCTION deployment and this session is not authorized. Still ${n.length===1?"a draft":"drafts"}:`:`\u2717 ${n.length} refused by the publish gates \u2014 still ${n.length===1?"a draft":"drafts"}, nothing was lost:`);for(let i of n.slice(0,3))r.push(` \xB7 ${sp(i.path)}`);n.length>3&&r.push(` \xB7 \u2026and ${n.length-3} more`),r.push(s?" Run /allow-prod, then /publish.":" /status names what is blocking each one, and the command that clears it. It costs nothing.")}if(e.throttled){let s=(e.throttled.finalPacingMs/1e3).toFixed(1);r.push(`\u2139 Document360 asked us to slow down ${e.throttled.times} time${e.throttled.times===1?"":"s"}, so this run eased to ${s}s between articles.`)}if(o.length>0){r.push(`\u2717 ${o.length} failed \u2014 ${o.length===1?"it is":"they are"} still a draft, so re-running /publish retries ${o.length===1?"it":"them"}:`);for(let s of o.slice(0,3))r.push(` \xB7 ${sp(s.path)} \u2014 ${s.message}`);o.length>3&&r.push(` \xB7 \u2026and ${o.length-3} more`)}return r.length===0&&r.push("Nothing was published."),r}async function nk(e,t){let n=t?.cwd??process.cwd();if(ap(e))return console.log(u(`\u2192 ${Ol()}`)),Il(e,t);let o=st(n,t?.profileName);if(!o.ok){let[R,D]=Gt(o);return console.log(L(R)),console.log(u(D)),{kind:"continue"}}let r=e.includes(Vt),s=e.includes(OA),i=e.includes(_A),a=e.includes("--all"),l=e.find(R=>!R.startsWith("--"));console.log(u("Checking what is waiting to go live\u2026"));let c;try{c=await lp(n,t?.profileName,l)}catch(R){return console.log(L(`Could not check Document360: ${R.message}`)),{kind:"continue"}}if(c.length===0){for(let R of cp(n,t?.profileName,l).lines)console.log(R.startsWith("\u2713")?Q(R):u(R));return{kind:"continue"}}let p=NA(n,c.map(R=>R.path),{allowUnreviewed:r,allowStyleErrors:s,checkScreenshots:!0,allowPlaceholders:i}),m=new Set(jA(p)),$=c.filter(R=>!m.has(R.path)),w=_l(n,p,l);if(m.size>0)for(let R of DA(p,c.length,{scope:l,act:"publish",going:$.length,shotFix:w.shotFix}))console.log(F(R));if($.length===0)return w.cmd&&console.log(u(`Run: ${w.cmd}`)),{kind:"continue"};c=$,console.log(""),console.log(`${c.length} draft${ip(c.length)} ${c.length===1?"is":"are"} ahead of what readers see:`);for(let R of BA(c.slice(0,12)))console.log(u(R));c.length>12&&console.log(u(` \u2026and ${c.length-12} more`)),console.log("");let C=c;if(!a){let R=await CA({message:"Publish live to your readers?",choices:[{name:`Yes \u2014 publish all ${c.length} live`,value:"all"},...c.slice(0,8).map(D=>({name:`Just ${D.label}`,value:D.path})),{name:"No \u2014 leave them as drafts",value:"none"}]});if(R==="none")return console.log(u("Left as drafts. Nothing changed.")),{kind:"continue"};R!=="all"&&(C=c.filter(D=>D.path===R))}let S=up(n,t?.profileName,t?.allowProdWrites?.()===!0,C.length);if(S){for(let R of S)console.log(R.startsWith("\u26A0")?F(R):u(R));return{kind:"continue"}}let A=await dp(n,t?.profileName,C,{skipReview:r,skipStyle:s,allowProduction:t?.allowProdWrites?.()===!0,onProgress:(R,D,W)=>console.log(u(` \u25B8 ${R+1}/${D} ${sp(W)}\u2026`))});console.log("");for(let R of pp(A))console.log(R.startsWith("\u2713")?Q(R):R.startsWith("\u2717")?F(R):u(R));return{kind:"continue"}}import{loadKnownConflicts as HA,localArticleTitle as GA,resolveActiveProfile as qA,surfaceCoverageSafe as ok,readProjectConfig as rk,recordDeclinedSurface as VA,areaExists as KA,declineTargets as sk,WRITER_DIRNAME as YA}from"document360-engine";function zA(e,t){let n=GA(e,t);return n||(t.split(/[\\/]/).pop()??t).replace(/\.md$/,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ")}function Ml(e,t){let n=[];try{n=HA(e,qA(e,t).name)}catch{return null}if(n.length===0)return null;let o=n.length,r=n.slice(0,3).map(i=>zA(e,i)),s=o>3?`${r.join(", ")} and ${o-3} more`:r.join(", ");return{paths:n,note:`\u26A0 ${o} article${o===1?"":"s"} ${o===1?"has":"have"} been changed both here and on Document360 (${s}), so your local copy is not a reliable picture of what your readers have. An audit over it could tell you to write an article that already exists, or miss one that needs your decision \u2014 so it needs ${o===1?"that":"those"} settled first.`}}var ts={cmd:"/resolve",reason:"it walks each one with you \u2014 keep yours, take the portal's, or skip"};function Ul(e,t){let n=t.indexOf("--decline");if(n<0)return null;let o=t[n+1];if(!o||o.startsWith("--")){let a=ok(e,rk(e)),l=a.recognised?a.areas.slice(0,5).flatMap(c=>sk(c).map(p=>` /audit --decline ${p}`)):[];return["Name the path to decline \u2014 a folder, or a single file.",...l.length?["","No article covers these right now. Run one of these to settle it for good:",...l]:["","For example:"," /audit --decline src/internal-admin"]]}let r=o.replace(/\\/g,"/").replace(/\/+$/,"");if(!KA(e,r))return[`There is nothing at ${r}, so there is nothing to decline. Copy the path from /eval or /audit.`];let s=t.slice(n+2).filter(a=>!a.startsWith("--")).join(" ")||void 0;return VA(e,r,s)?[`\u2713 ${r} will not be reported as needing an article. /audit and /eval leave it out from now on, and say how many you have declined.`]:[`Could not write ${YA}/declined-surfaces.json, so ${r} was not declined.`]}async function gi(e){if(e?.cwd){let r=Ml(e.cwd,e.profileName);if(r)return{kind:"audit-blocked",note:r.note,lead:ts}}let t=e?.cwd?ok(e.cwd,rk(e.cwd)):null,n=[];if(t?.recognised&&t.areas.length>0){let r=t.areas.slice(0,15);n.push("","2.7. These parts of the product are cited by NO article's `sources:` frontmatter. This list is DETERMINISTIC and complete as of now \u2014 it does not depend on the diff window above, so treat it as authoritative rather than re-deriving it:",...r.map(s=>` - ${s.folder} (${s.files} of ${s.total} file${s.total===1?"":"s"} uncited, e.g. ${s.sample.join(", ")}) \u2014 to decline: ${sk(s).map(i=>`/audit --decline ${i}`).join(" \xB7 ")}`),...t.areas.length>r.length?[` \u2026and ${t.areas.length-r.length} more areas.`]:[]," EVERY row above must leave this run accounted for: a `create` row, or a stated reason it needs no article (internal-only, unreachable by a reader, already covered by an existing article's prose). Do NOT silently drop one \u2014 if you list fewer paths than this section handed you, say which you left out and why."," A `decline` verdict is not a record. For EVERY row you decline, print its exact /audit --decline line (copied from above \u2014 it already picks folder-or-file correctly) in the closing block, each on its own line so the terminal makes it a button. A judgement that leaves the turn as prose changes nothing and will be re-derived, at this price, on every future audit.",...t.declined>0?[` (${t.declined} more ${t.declined===1?"is":"are"} already declined and left out of that list.)`]:[])}return{kind:"forward-to-agent",prompt:["Run the gap-analysis skill against this repo.","","Follow its stages in order:","1. d360_sync_status first; stop if any article is changed in both places, or changed on Document360 and not yet pulled down (the local copy cannot be trusted until that is resolved). Say which articles, in plain words, never the internal status word \u2014 and tell the user to run /resolve, which walks the affected articles one at a time (keep the local copy, take the portal's, or skip). Do NOT ask them to report back to you: they will run /resolve and then /audit again.","2. git diff since the lastAnalyzedCommit marker in d360-category-map.json (or last 30 days if no marker), filtered to the authoritativeSourceFiles paths.","2.5. d360_pending_hints: the source agent's own notes on what it shipped. Verify each against the CURRENT code (its `sources` exist, and the code as it stands shows the surface it claims) before trusting it; never judge it by its `branch` or `commit`. Fold verified ones into the table, flag the rest.","2.6. Anything d360_pending_hints returns under `held` is NOT a proposal. Its cited code has uncommitted changes, so the builder is still writing that surface and has already been asked whether it is done. List each held item at the END of the table as a `waiting` row (Reason: the code behind it is not finished), do NOT propose create/update/retire for it, and do NOT stamp it consumed.",...n,"3. Map changes (diff + hints) to articles via their `sources:` frontmatter; read only implicated articles and changed source files. If articles are missing `sources:`, this is the one-time bootstrap pass, so backfill them.","4. Output the proposal table: | Article (path or proposed title) | Action (create | update | retire | link) | Reason | Evidence | Scope |. Leave every hint OPEN \u2014 this run proposes, it does not write articles, so nothing has been acted on yet.","5. End with the skill's closing block, and put NOTHING below it \u2014 no receipts, no roadmap confirmations, no feedback marker line, no summary. It ends in a question, and a question the user has to scroll back to find is one you did not really ask.","","Do not start writing or updating any article yet; the proposal table is the deliverable.","The audited-up-to marker is recorded for you when this command finishes. Read it to size the diff window; never write it, and never report it as a missing capability."].join(`
|
|
344
|
+
`),display:"/audit"}}ae();import{readProjectConfig as QA,writeProjectConfig as ik,autoBudgetUsd as JA,autoModeEnabled as ZA,DEFAULT_AUTO_BUDGET_USD as eT}from"document360-engine";import{PRODUCT_NAME as XA}from"document360-engine";var be=`No ${XA} config here. Run /init first.`;function et(e){return`$${e%1===0?e.toFixed(0):e.toFixed(2)}`}function yi(e){return e?"I run the next step myself instead of waiting for you \u2014 writing, reviewing, checking style, saving and going live.":"I suggest the next step and wait for you to run it."}function wi(e){let t=ZA(e),n=JA(e),o=e.auto?.budgetUsd===void 0?" (the standard limit \u2014 nothing set for this repo)":"",r=[{tone:"info",text:`Mode: ${t?"auto":"manual"} \u2014 ${yi(t)}`}];return t?(r.push({tone:"info",text:`Spending limit: ${et(n)} a run${o}. I stop and report when it is reached.`}),r.push({tone:"info",text:"Screenshots are never part of an automatic run \u2014 they need your product running."}),r.push({tone:"info",text:"Stop a run at any time: esc. Switch back to manual: shift+tab, or /auto off."})):r.push({tone:"info",text:`Turn it on: /auto on \xB7 or shift+tab. Spending limit if you do: ${et(n)} a run.`}),r}function Fl(e,t,n,o=new Date){let r={...t,auto:{...t.auto,enabled:n,decidedAt:o.toISOString()}};return ik(r,e),[n?{tone:"ok",text:V("\u2713")+"Auto mode ON \u2014 "+yi(!0)}:{tone:"ok",text:V("\u2713")+"Manual mode \u2014 "+yi(!1)},...wi(r)]}function fp(e,t,n){if(!Number.isFinite(n)||n<=0)return null;let o={...t,auto:{...t.auto,enabled:t.auto?.enabled===!0,budgetUsd:n}};return ik(o,e),[{tone:"ok",text:V("\u2713")+`Spending limit set to ${et(n)} a run.`},...wi(o)]}function mp(e){let t=e.findIndex(r=>r==="--budget"||r.startsWith("--budget="));if(t===-1)return{malformed:!1};let n=e[t].includes("=")?e[t].split("=").slice(1).join("="):e[t+1];if(n===void 0)return{malformed:!0};let o=Number(String(n).replace(/^\$/,"").replace(/,/g,""));return!Number.isFinite(o)||o<=0?{malformed:!0}:{usd:o,malformed:!1}}function gp(e,t){let n=e.findIndex(o=>o==="--budget");return e.filter((o,r)=>!o.startsWith("--")&&!(n!==-1&&r===n+1)&&o!==String(t)).map(o=>o.trim().toLowerCase()).find(o=>o.length>0)}var hp=e=>{for(let t of e)console.log(t.tone==="ok"?Q(t.text):t.tone==="warn"?F(t.text):t.tone==="error"?L(t.text):u(t.text))};async function ak(e,t){let n=t.cwd,o=QA(n);if(!o)return console.log(L(be)),{kind:"continue"};let r=mp(e);if(r.malformed)return console.log(L(`I could not read that spending limit. Give it as an amount, like: /auto --budget 150 (the standard limit is ${et(eT)}).`)),{kind:"continue"};let s=gp(e,r.usd);if(r.usd!==void 0&&!s){let i=fp(n,o,r.usd);return i&&hp(i),{kind:"continue"}}if(!s||s==="status")return hp(wi(o)),{kind:"continue"};if(s==="on"||s==="off"){let i=r.usd!==void 0?{...o,auto:{...o.auto,enabled:o.auto?.enabled===!0,budgetUsd:r.usd}}:o;return hp(Fl(n,i,s==="on")),{kind:"continue"}}return console.log(L(`I don't know "${s}". Use: /auto on \xB7 /auto off \xB7 /auto status \xB7 /auto --budget <amount>`)),{kind:"continue"}}ae();import{readProjectConfig as tT,WRITER_DIRNAME as yp}from"document360-engine";function wp(){return["Run the discover-product skill against this repo.","",`Build (or continue refining) the product brief at \`${yp}/product-brief.md\` by interviewing the`,"source repo's coding agent (the builder):",`1. Gather all grounding: the code surface (analyze-codebase pass), \`${yp}/architecture/\``,` (+ CREATOR-NOTES), any specs under \`${yp}/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(`
|
|
345
|
+
`)}async function lk(e,t){let n=t?.cwd??process.cwd();return tT(n)?{kind:"forward-to-agent",prompt:wp(),display:"/discover"}:(console.log(L(be)),{kind:"continue"})}ae();import{checkbox as nT}from"@inquirer/prompts";import{inventoryRepo as oT,readProjectConfig as ck,writeProjectConfig as rT,WRITER_DIRNAME as kp}from"document360-engine";function bp(e,t){let n=ck(e);n&&(n.authoritativeSourceFiles=t,rT(n,e))}function Wl(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 uk(e,t){let n=t?.cwd??process.cwd();if(!ck(n))return console.log(L(`No ${kp}/config.json here. Run /init first.`)),{kind:"continue"};let o=oT(n);if(o.length===0)return console.log(u(`No candidate source folders found. Set "authoritativeSourceFiles" in ${kp}/config.json manually.`)),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(Z("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${u(Wl(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>nT({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${Wl(s)})`,value:s.path,checked:s.recommended})),pageSize:20}))}catch{return console.log(u("Cancelled.")),{kind:"continue"}}if(r.length===0)return console.log(u("Nothing selected \u2014 scope unchanged.")),{kind:"continue"};bp(n,r),console.log(Q(`\u2713 Scoped to ${r.length} folder(s) \u2014 written to ${kp}/config.json`));for(let s of r)console.log(` ${s}`);return console.log(""),{kind:"continue"}}ae();import{confirm as gT}from"@inquirer/prompts";import{applyPull as Rp,computeSyncStatus as vk,compareRemoteSources as yT,planPull as xk,planImport as wT,applyImport as kT,establishBaselines as bT,rebaselineServerMeta as $T,D360AuthError as vT}from"document360-engine";ae();var dk=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/pull <path> or /push <path>):",paint:L,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /push <path>:",paint:F,mark:"M"},{status:"remote-ahead",header:"Changed on Document360 \u2014 pull with /pull <path> (or just /pull):",paint:Z,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:L,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:L,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint:Ie,mark:"X"},{status:"untracked-local",header:"New here \u2014 not on Document360 yet (publish to add them):",paint:u,mark:"?"},{status:"untracked-remote",header:"On Document360 \u2014 not in your local docs yet (run /pull to import them):",paint:u,mark:"?"},{status:"unknown-base",header:"Tracked, not yet compared \u2014 run /pull --baseline to set a baseline (or the next publish/pull sets one):",paint:Ie,mark:"\xB7"}];function sT(e){return e.path?e.path:`${e.title??"(untitled)"} ${Ie(`[${e.articleId}]`)}`}function iT(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 Bl(e,t){let n=[],o=e.entries.filter(p=>p.link);if(o.length>0){n.push(""),n.push(rt("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let p of o)n.push(` ${F("~")} ${F(p.path??"")} ${Ie(`\u2192 "${p.link.title}"`)}`)}for(let p of dk){let m=e.entries.filter($=>$.status===p.status&&!(p.status==="untracked-local"&&$.link));if(m.length!==0){n.push(""),n.push(rt(p.header));for(let $ of m)n.push(` ${p.paint(p.mark)} ${p.paint(sT($))}${$.detail?Ie(` (${$.detail})`):""}`)}}let r=e.counts["in-sync"]??0,s=e.entries.length;n.push("");let i={"in-sync":"up to date","local-ahead":"changed here","remote-ahead":"changed on Document360",conflict:"changed both places","untracked-local":"new here","untracked-remote":"only on Document360","deleted-local":"removed locally","deleted-remote":"gone from Document360",orphaned:"gone both sides","unknown-base":"not yet compared"},a=o.length,l=s===r?Q("\u2713 everything up to date"):[r>0?Q(`\u2713 ${r} up to date`):null,a>0?`${a} to link`:null,...dk.map(p=>{let m=(e.counts[p.status]??0)-(p.status==="untracked-local"?a:0);return m>0?`${m} ${i[p.status]}`:null})].filter(Boolean).join(Ie(" \xB7 ")),c=t!==void 0?` \xB7 synced in ${iT(t)}`:"";return n.push(l+Ie(` \xB7 ${s} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/${c}`)),n}import{structuredPatch as aT}from"diff";import pk from"picocolors";var lT=80,ns=400,cT="\x1B[48;2;74;28;28m",uT="\x1B[48;2;24;66;24m",hk="\x1B[49m",$p=e=>String(e).padStart(5);function fk(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}function mk(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 Yt(e,t,n,o=lT){let r=C=>{let S=C.replace(/\r\n/g,`
|
|
346
346
|
`);return S.endsWith(`
|
|
347
347
|
`)||S===""?S:S+`
|
|
348
|
-
`},s=r(e),i=r(t);if(s===i)return null;let a=Math.max(20,n-10),l=jP("a","b",s,i,"","",{context:3}),c=0,p=0,m=[];l.hunks.forEach((C,S)=>{S>0&&m.push(mw.gray(" \u2026"));let T=C.oldStart,R=C.newStart,D=[],U=[],H=()=>{for(let J=0;J<D.length;J++){let G=J<U.length?yw(D[J],U[J]):void 0;p++,m.push(`${LP}${Md(T++)} - ${ww(D[J],a,G)}${gw}`)}for(let J=0;J<U.length;J++){let G=J<D.length?yw(D[J],U[J]):void 0;c++,m.push(`${OP}${Md(R++)} + ${ww(U[J],a,G)}${gw}`)}D=[],U=[]};for(let J of C.lines){let G=J[0],K=J.slice(1);G==="-"?D.push(K):G==="+"?U.push(K):(H(),m.push(mw.gray(Md(R))+" "+K.slice(0,a)),T++,R++)}H()});let $=Math.max(1,o),w=m.slice(0,$);return{added:c,removed:p,lines:w,hidden:Math.max(0,m.length-$)}}import{select as vw}from"@inquirer/prompts";import{applyPull as xw,computeSyncStatus as FP,isPullWouldBlankError as bw,localArticleTitle as UP,planPull as $w}from"document360-engine";import{listUnpullable as _P,resolveActiveProfile as MP}from"document360-engine";function wl(e,t,n,o){let r=n.filter(a=>a.status==="conflict"&&a.path).map(a=>a.path),s=new Set(o),i=[];try{i=_P(e,MP(e,t).name).map(a=>a.path).filter(a=>s.has(a))}catch{}return[...new Set([...r,...i])].sort()}function kl(){return["Document360 will not give this article back as markdown \u2014 it is not on the Markdown (Editor 3.0) editor, so there is no portal copy to show you or to take.","Your local copy is intact, and publishing it over the portal settles this. Skipping leaves the article flagged, and it will be waiting again next time."]}function bl(){return"Publish your copy over the portal (settles it) \xB7 Skip?"}function kw(){return"(l publish yours \xB7 s skip \u2014 anything else stops, keeping your answers so far)"}function $l(e){if(e.length===0)return[];let t=e.length,n=e.slice(0,3).join(", ")+(t>3?`, +${t-3} more`:"");return[`${t} article${t===1?"":"s"} stay${t===1?"s":""} flagged \u2014 Document360 cannot hand ${t===1?"its":"their"} markdown back: ${n}`,"Two ways out: run /resolve and press l to publish your copy over the portal, or ask your Document360 admin to move the article back to the Markdown (Editor 3.0) editor, then run /resolve again."]}function Fd(e){return`Cannot take the portal copy of ${e} \u2014 Document360 will not return it as markdown. Left as it was.`}ue();var vl=e=>e===1?"":"s";async function Ud(e,t,n=1){console.log(""),console.log(`${Z("\u25CF")} ${nt(t.title)} ${De(`(${t.path})`)}`);for(let i of t.notes)console.log(W(` \u26A0 ${i}`));let o=Ht(t.oldContent,t.newContent,Math.max(40,(process.stdout.columns??80)-1),Hr);if(o){console.log(De(` \u23BF local \u2192 portal: +${o.added} / -${o.removed} line${vl(o.added+o.removed)}`));for(let i of o.lines)console.log(i);o.hidden>0&&console.log(u(` \u2026 +${o.hidden} more diff lines`))}else console.log(u(" Local already matches the portal content \u2014 resolving just advances the sync base."));let r=n>1,s=await e.withPausedInput(()=>vw({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"?(xw({cwd:e.cwd,profileName:e.profileName},t),console.log(Q(" \u2713 Took the portal copy (local overwritten, sync base advanced).")),"took-portal"):s==="local"?"keep-local":s==="skip"?(console.log(u(" Skipped \u2014 still a conflict.")),"skipped"):s==="local-all"?"keep-local-all":s==="portal-all"?"took-portal-all":"skipped-all"}async function WP(e,t){console.log(""),console.log(`${Z("\u25CF")} ${nt(UP(e.cwd,t)??t)} ${De(`(${t})`)}`);for(let o of kl())console.log(W(` \u26A0 ${o}`));return await e.withPausedInput(()=>vw({message:bl(),choices:[{name:"Publish your copy over the portal (settles it)",value:"local"},{name:"Skip (leave it a conflict)",value:"skip"}]})).catch(()=>"skip")==="local"?"keep-local":(console.log(u(" Skipped \u2014 still a conflict.")),"skipped")}async function Rw(e,t){let n=ot(t.cwd,t.profileName);if(!n.ok){let[r,s]=Ft(n);return console.log(L(r)),console.log(u(s)),{kind:"continue"}}let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let r=await FP({cwd:t.cwd,profileName:t.profileName}),s=wl(t.cwd,t.profileName,r.entries,qo(r.entries).map(l=>l.path));if(o){if(!s.includes(o))return console.log(Q(`${o} isn't waiting on a decision \u2014 nothing to resolve.`)),{kind:"continue"};s=[o]}if(s.length===0)return console.log(Q("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let i=[],a=[];for(let[l,c]of s.entries()){let p;try{p=await $w({cwd:t.cwd,profileName:t.profileName,relPath:c})}catch(w){if(!bw(w))throw w;await WP(t,c)==="keep-local"?i.push(c):a.push(c);continue}let m=await Ud(t,p,s.length-l);if(m==="keep-local"&&i.push(c),!m.endsWith("-all"))continue;let $=s.slice(l);if(m==="keep-local-all")i.push(...$),console.log(u(` Keeping local for all ${$.length} \u2014 publishing them over the portal.`));else if(m==="took-portal-all"){let w=0;for(let C of $)try{xw({cwd:t.cwd,profileName:t.profileName},await $w({cwd:t.cwd,profileName:t.profileName,relPath:C})),w++}catch(S){console.log(L(` \u2717 ${C}: ${S.message}`)),bw(S)&&a.push(C)}console.log(Q(` \u2713 Took the portal copy of ${w} article${vl(w)} (local overwritten, sync base advanced).`))}else console.log(u(` Skipped all ${$.length} \u2014 still conflict${vl($.length)}.`));break}for(let l of $l(a))console.log(W(`\u26A0 ${l}`));if(i.length>0)return console.log(u(`Publishing ${i.length} kept-local article${vl(i.length)} over the portal\u2026`)),await on(t,i,0,{allowUnpullable:!0})}catch(r){console.log(L(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function Pw(e,t){let n=ot(t.cwd,t.profileName);if(!n.ok){let[r,s]=Ft(n);return console.log(L(r)),console.log(u(s)),{kind:"continue"}}let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await zP(t),{kind:"continue"};if(o==="--baseline")return await XP(t,e.filter(i=>i!=="--baseline")),{kind:"continue"};if(o==="--compare")return await QP(t),{kind:"continue"};if(o)return console.log(L(`Unknown option: ${o}`)),console.log(u("Usage: /pull pull portal edits + import new portal articles")),console.log(u(" /pull <path> pull one article (or resolve a conflict)")),console.log(u(" /pull --status drift report only (no writes)")),console.log(u(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await JP(t,r),{kind:"continue"};console.log(u("Pulling changes from Document360\u2026"));let s=await Bd({cwd:t.cwd,profileName:t.profileName});for(let i of Hd(s))console.log(i.tone==="ok"?Q(i.text):i.tone==="warn"?W(i.text):u(i.text));console.log("")}catch(r){r instanceof YP?console.log(L(r.message)):console.log(L(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function Bd(e){let t=await Sw({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 Cw({cwd:e.cwd,profileName:e.profileName,relPath:o.path});Wd({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 GP({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId,...o.remoteCategory?{categoryPath:o.remoteCategory.path}:{}});qP({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 xl=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,Vo=e=>e===1?"":"s";function Hd(e){let t=[];if(e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${Vo(e.pulled.length)} into local: ${xl(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${Vo(e.imported.length)}: ${xl(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${Vo(e.toPublish)} changed locally \u2014 /push saves them to Document360.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${Vo(e.conflicts.length)} changed both here and on Document360 \u2014 left untouched. Resolve them: /resolve (or /push <path> to keep yours, /pull <path> to take the portal's). (${xl(e.conflicts)})`}),e.failed.length){t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${Vo(e.failed.length)} could not be imported.`});let n=new Map;for(let o of e.failed){let r=o.error.replace(/^"[^"]*" could not be imported: /,"");n.set(r,[...n.get(r)??[],o.ref])}for(let[o,r]of n)t.push({tone:"warn",text:` ${o}`}),t.push({tone:"warn",text:` ${xl(r)}`})}return t.length===0&&t.push({tone:"ok",text:"\u2713 Already in sync with Document360 \u2014 nothing to pull."}),t}async function zP(e){console.log(u("Checking Document360 for drift\u2026"));let t=Date.now(),n=await Sw({cwd:e.cwd,profileName:e.profileName});for(let o of yl(n,Date.now()-t))console.log(o);console.log("")}async function XP(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(u(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await VP({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await KP({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(Q("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(Q(`\u2713 Recorded ${o.baselined.length} article(s) as matching Document360 \u2014 they read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(Q(`\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(u(` - ${s.path} (${s.reason})`))}}async function QP(e){console.log(u("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await HP({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${nt(String(t.legacyCount))} \xB7 Manifest: ${nt(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(Q("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(L(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(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(u(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function JP(e,t){let n=t.replace(/\\/g,"/"),o=await Cw({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await Ud(e,o)==="keep-local"&&(console.log(u(`Publishing ${o.path} over the portal\u2026`)),await on(e,[o.path]));return}console.log(""),console.log(`${Z("\u25CF")} ${nt(o.title)} ${De(`(${o.path})`)}`);for(let i of o.notes)console.log(W(` \u26A0 ${i}`));let r=Ht(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1),Hr);if(!r){console.log(u(" Local file already matches the remote content \u2014 advancing the sync base only.")),Wd({cwd:e.cwd,profileName:e.profileName},o);return}console.log(De(` \u23BF Added ${r.added} line${Vo(r.added)}, removed ${r.removed} line${Vo(r.removed)}`));for(let i of r.lines)console.log(i);if(r.hidden>0&&console.log(u(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>BP({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(u(" Skipped."));return}Wd({cwd:e.cwd,profileName:e.profileName},o),console.log(Q(` \u2713 Pulled ${o.path} (sync base advanced).`))}ue();import{statSync as cT}from"node:fs";import{resolve as uT}from"node:path";import{estimateBulkCost as dT,planPartitions as pT,readProjectConfig as hT,resolveModelForOperation as fT,runPartitioned as mT,trackedArticlePaths as gT}from"document360-engine";function so(e,t){return e.aborted?null:e.blocked?[`\u2717 ${t} didn\u2019t start \u2014 ${e.blocked}.`,"Nothing was changed. Fix that, then re-run."]:e.allEmpty?[`\u2717 ${t} did nothing \u2014 every batch produced no output, so no agent actually ran.`,"Run /doctor \u2014 it runs a real turn with your skills and tools and reports what failed. /logs shows Claude Code\u2019s own error, which was recorded either way, and offers to copy it.","A Claude usage or session limit also does this, and it ends every turn instantly \u2014 if you have just hit one, wait for the reset and re-run."]:null}function Tw(e){return!e.bailedEmpty||!e.notRun?null:`\u26A0 Stopped early \u2014 ${e.notRun} batch${e.notRun===1?" was":"es were"} not attempted, because two in a row produced no output (that is systemic, not this work: usually a Claude usage limit). Re-run to finish the rest; anything already done is skipped.`}var Gr=class{activeMs=0;last=0;timer=null;startedAt=0;stopped=null;start(t=Date.now()){this.timer||(this.startedAt=t,this.last=t,this.timer=setInterval(()=>this.tick(),1e3),this.timer.unref?.())}tick(t=Date.now()){let n=t-this.last;this.last=t,!(n<=0)&&(this.activeMs+=Math.min(n,5e3))}stop(t=Date.now()){return this.stopped?this.stopped:(this.timer&&(clearInterval(this.timer),this.timer=null),this.tick(t),this.stopped={activeSeconds:Math.max(0,Math.round(this.activeMs/1e3)),elapsedSeconds:Math.max(0,Math.round((t-this.startedAt)/1e3))},this.stopped)}};function Rl(e,t){let n=t-e;return n>=300&&n>=t*.2}function Gt(e,t,n,o=Date.now(),r){let s=t.reduce((a,l)=>a+(l.inputTokens??0),0),i=t.reduce((a,l)=>a+(l.cacheReadTokens??0),0);return{seconds:Math.max(0,Math.round((o-e)/1e3)),outputTokens:t.reduce((a,l)=>a+l.outputTokens,0),inputTokens:s,...s>0?{cachedPct:Math.round(i/s*100)}:{},...r!==void 0?{activeSeconds:r}:{},costUsd:n}}function Sl(e){return e.activeSeconds!==void 0&&Rl(e.activeSeconds,e.seconds)?`${Gd(e.seconds)} elapsed \xB7 ${Gd(e.activeSeconds)} working`:Gd(e.seconds)}var Aw=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:`${e}`,Gd=e=>{if(e<60)return`${e}s`;let t=Math.floor(e/60);return t<60?`${t}m ${e%60}s`:`${Math.floor(t/60)}h ${t%60}m`};function hn(e){let t=e.cachedPct!==void 0?`, ${e.cachedPct}% cached`:"",n=e.costUsd>0?`, this turn ${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"";return` (took ${Sl(e)}, ${Aw(e.inputTokens)}\u2192${Aw(e.outputTokens)} tokens${t}${n})`}import Re from"picocolors";import Yd from"wrap-ansi";import zd from"string-width";ue();import io from"picocolors";import Pl from"wrap-ansi";import Cl from"string-width";var Ko=[{name:"init",usage:"/init",desc:"Pick an environment, scaffold .d360-writer/config.json, and set up the builder hand-off (prints the one-paste prompt)",group:"start"},{name:"login",usage:"/login",desc:"Sign in to Document360 (browser)",group:"start"},{name:"project",usage:"/project [name]",desc:"Choose the Document360 project (picker; lists all you can access)",group:"start"},{name:"devhints",usage:"/devhints",desc:"Re-show/refresh the builder hand-off prompt (set up by /init; run anytime to hand your repo agent the latest)",group:"start"},{name:"scope",usage:"/scope",desc:"Choose which repo folders back the docs (monorepos)",group:"start"},{name:"genre",usage:"/genre [web|cli|service|library|auto]",desc:"Set/show the product genre \u2014 picks the docs craft playbook (usually auto-detected; set it if it guessed wrong)",group:"start"},{name:"mcp",usage:"/mcp [list|add|remove]",desc:"Connect MCP servers (Notion, Linear, \u2026)",group:"start"},{name:"discover",usage:"/discover",desc:"Interview your builder to understand the product (identity, mental model, misconceptions, positioning) \u2192 pins a product brief that grounds the docs; asks focused questions and loops until confident",group:"docs"},{name:"draft",usage:"/draft [<feature>]",desc:"Draft a feature's articles from its PRDs/specs in .d360-writer/input/ + the code",group:"docs"},{name:"document",usage:"/document [<what>] [--push]",desc:"Document a shipped change \u2014 the agent picks the action (new section/article/update); bare: act on builder requests. --push then saves the result to Document360 as drafts, which still needs an editorial review first",group:"docs"},{name:"write",usage:"/write [--preview|--scope <cat>|<path>] [--rewrite] [--concurrency N] [--skip-style]",desc:"Write the planned articles in parallel (starts immediately; --preview shows plan + cost first; --rewrite regenerates already-written articles; --concurrency default 3). Anything that would block publishing is corrected in one automatic pass before the run finishes; --skip-style leaves it to /lint",group:"docs"},{name:"screenshot",usage:"/screenshot [author|capture|annotate|verify|checklist|list] [id|path|--all|--failed|--blocked]",desc:"Screenshots, one family \u2014 bare: pick what to do; author: write capture specs; capture: take the shots (--all re-shoots everything; --failed re-runs the ones that did not work; --blocked re-runs the ones waiting on app data); annotate: draw the callouts on shots already taken, no browser needed (--all --force re-draws after a wording or style change); verify: judge the finished pictures and mark them verified (both run automatically after a capture); checklist: what to stage + dev test-id requests; list: status + what to stage",group:"docs"},{name:"preview",usage:"/preview [path|id]",desc:"Render an article (no arg: pick from tracked)",group:"docs"},{name:"push",usage:"/push [path|--all|--related <path>|[<category>] --screenshots] [--preview] [--skip-review]",desc:"Save your articles to Document360 as drafts \u2014 readers don't see them until /publish (no arg: pick; --all: every candidate; --screenshots: re-save articles with captured shots so images embed, optionally narrowed to one category; --related <path>: also save that article's related articles that were never saved; --preview <path>: show exactly what would be sent, and send nothing). Blocked until each article has had /review --fix \u2014 AI-written text gets an editor first; --skip-review overrides deliberately",group:"publish"},{name:"publish",usage:"/publish [path|<category>|--all] [--skip-review]",desc:"Take the drafts on Document360 LIVE to your readers (the portal's own Publish). Always lists what would become visible and asks first; no arg or a category narrows it. Needs an editorial review \u2014 /review --blocked --fix",group:"publish"},{name:"style-guide",usage:"/style-guide [list | use [<preset>] | keep | triage | off <rule> | on <rule> | sweep [skip] | pull [<n>] | learn | compile | explain <rule>]",desc:"Choose the writing rules your docs are held to. Bare: what is active now; list: every pack you can turn on; use: switch packs, hold every article to them and apply the free text swaps (bare: pick from a list); keep: settle on the rules you have today; triage: which rules are producing the most findings, with a decision for each (free); off/on: silence one rule, or put it back; sweep: how much of your knowledge base still needs reading against a guide you switched to (skip stops me raising it); pull: bring your Document360 project's own style guide down; learn: turn what your reviewers keep asking for into standing rules; compile: turn its mechanical statements into checks; explain: what one rule means, what your own tweaks changed, and how to silence it",group:"docs"},{name:"lint",usage:"/lint [<category|path>] [--blocked] [--fix] [--full] [--baselined]",desc:"Lint the docs against the house rules: leaked internals, invented commands, stale facts, AI-tells, em dashes, callout shape (deterministic, no tokens). Every finding names the rule that produced it. Scope to a category/path; --blocked narrows to the errors that block publishing and leaves warnings and suggestions alone; --fix has the agent correct them in place; --full lists every finding instead of a capped summary; --baselined shows the issues that were already in your articles when you chose this style guide, which never block publishing",group:"docs"},{name:"review",usage:"/review [<category|path> | --all | --blocked | --stale] [--fix]",desc:"Independent senior-editor review: style guide, terminology/voice, grammar/clarity, page structure, improvement suggestions. A whole-knowledge-base run also gets one editor on the SHAPE of the docs \u2014 reading order, categories that have grown too big, articles filed in the wrong place, names that no longer fit. Bare: pick a category or everything; --blocked reads only the articles publishing is blocked on; --stale reads the ones the current editor has not read yet, so running it twice costs nothing; --all reviews the whole KB; --fix applies the corrections in place",group:"docs"},{name:"reorder",usage:"/reorder [<category> | --all]",desc:"Reorder articles within a category to the best reading order (renumbers NN- prefixes, fixes references + map); bare: pick a category or everything; new order syncs to Document360 on next /push",group:"docs"},{name:"restructure",usage:"/restructure [<what to change>]",desc:"Reshape the knowledge base: move an article to a different category, split one that has grown too big, merge two, rename one, or nest one inside another. A category left empty by a merge is hidden from readers, never deleted. Bare: reviews how the docs are organized and reports what should change, without touching anything; the changes reach Document360 on the next /push",group:"docs"},{name:"structure",usage:"/structure",desc:"Show the documentation reading order (categories \u2192 articles) as it will appear on Document360",group:"docs"},{name:"status",usage:"/status [--all]",desc:'What stands between your work and your readers, before you spend anything: which articles no editor has read, which break a style rule your config makes blocking, which would show "[Screenshot: \u2026]" text to a reader, which are in conflict with the portal, and which are saved as drafts readers cannot see yet. Each group names the one command that clears it. Reads local files and the last sync \u2014 no network, no tokens. --all lists every article gate by gate',group:"publish"},{name:"retire",usage:"/retire [<path>] [--yes]",desc:"Take an article off your readers on Document360 \u2014 it stops being visible, and nothing offers to publish it again. Nothing is deleted: the article, its version history and every reviewer comment stay. Bare: lists what is worth retiring (articles on Document360 that are no longer in your docs folder). /push puts one back \u2014 reviving is a publish like any other",group:"publish"},{name:"untrack",usage:"/untrack [<path>] [--undo] [--list] [--yes]",desc:"Disown a page that was imported from Document360 but is not one of your docs. /catch-up and /pull import every article they find in your categories; this records the ones you do not want, so they are never imported again \u2014 and the decision travels with the repo, so a teammate\u2019s clone inherits it. Nothing on Document360 changes and nothing is deleted: the markdown moves to .d360-writer/declined/. Bare: lists what this repo has declined. --undo puts one back",group:"publish"},{name:"reuse",usage:'/reuse [pull | add <variable|snippet> <name> "<value>" | audit [<category>] [--create <n\u2026>]]',desc:"The terms, values and blocks your project already maintains on Document360, so your articles reference them instead of repeating them. A variable holds a value like your product name in one place \u2014 change it there and every article changes; type it out by hand and /lint flags it. A snippet does the same for a whole block, and the writer references yours by name instead of writing its own version. A term is defined once and every article is checked for explaining it the first time it appears. Reading is free; pull refreshes from Document360, add creates a new one there, and audit reads every article to work out what belongs in one place",group:"docs"},{name:"eval",usage:"/eval [<category>] [--all]",desc:"How does your whole knowledge base score? Reads every article and reports what no single-article check can see: internal links written as portal URLs, links pointing at headings that no longer exist, link text that names a different article, the command summary line appearing in several shapes, two names for the same section, and how many style findings were accepted as exempt when you chose your style guide. Costs nothing and calls nothing",group:"docs"},{name:"terms",usage:'/terms [<category>] [--all] [--approve "<term>"]',desc:"Is your knowledge base calling the same thing by the same name? Reads every article and reports terms spelled more than one way, short names that may be the long name abbreviated, and article titles out of step with the rest of their kind \u2014 the consistency an editor reading three articles at a time cannot see. Costs nothing and calls nothing. --approve records a spelling as the approved one, so every later run enforces it",group:"docs"},{name:"roadmap",usage:"/roadmap [--all | done [step]]",desc:"Show the docs campaign (the multi-session plan the agent maintains), grouped by the part of the job \u2014 progress + next step; `--all` also lists the steps a later pass replaced; `done` marks the next open step finished (add words from a title to pick another)",group:"docs"},{name:"audit",usage:"/audit [--auto on|off] [--decline <path>]",desc:"Gap analysis: code vs docs vs Document360 (what changed); --auto runs it at launch when code changed; --decline settles a folder or file that needs no article",group:"publish"},{name:"inbox",usage:"/inbox",desc:"Act on messages from the repo's coding agent (requests to document, answers to your questions)",group:"publish"},{name:"ask",usage:"/ask <question>",desc:"Ask your developers something the code cannot tell you: why a feature exists, when to use it, whether it can be undone",group:"publish"},{name:"share",usage:"/share [status|on|off]",desc:"Share your docs work with the team: get your builder's latest, then save + send yours (runs automatically; `off` leaves it to your coding agent)",group:"publish"},{name:"catch-up",usage:"/catch-up [--push] [--include-unfinished]",desc:"Process ALL pending work (builder hints + requests + Document360 portal drift) \u2192 write \u2192 save to Document360 as drafts. --push does that last step for you, which still needs an editorial review first. A note whose code your builder has not committed is left for later, and they are asked whether it is done; --include-unfinished writes those pages anyway. For code changes, that's /audit",group:"publish"},{name:"comments",usage:"/comments [<article>] [--scope <category>] [--answer] [--all] [--resolve] [--answered] [--full]",desc:"Reviewer comments left on passages of your articles in the Document360 portal \u2014 bare: a table by article, pick a number to read its comments in full, then answer or go back; --answer: fix, push the draft, reply (threads stay open unless you add --resolve); --full re-reads every article",group:"publish"},{name:"pull",usage:"/pull [<path> | --status | --baseline]",desc:"Bring Document360 down: pull portal edits + import NEW portal articles. --status: drift report only \xB7 --baseline: set a sync base \xB7 <path>: one article / resolve a conflict",group:"publish"},{name:"resolve",usage:"/resolve [<path>]",desc:"Resolve conflicts (edited both here and on the portal): shows the diff, then keep local (push), take portal (pull), or skip \u2014 per article, or one answer for all remaining. Bare: walk them all",group:"publish"},{name:"convert",usage:"/convert [--scope <folder>] [--run]",desc:"Convert tracked articles to DFM (one-off legacy migration)",group:"publish"},{name:"profile",usage:"/profile [name|add <name> [env]]",desc:"Where this repo publishes \u2014 switch, or connect another environment (picker; s = session)",group:"setup"},{name:"workspace",usage:"/workspace [name]",desc:"Switch the Document360 workspace (picker)",group:"setup"},{name:"auto",usage:"/auto [on|off|status] [--budget <amount>]",desc:"Auto or manual: in auto I run the next step myself \u2014 write, review, check style, save, go live \u2014 instead of waiting for you (shift+tab cycles it; esc stops a run)",group:"setup"},{name:"model",usage:"/model [name|default]",desc:"Set the Claude model for d360-writer",group:"setup"},{name:"verbose",usage:"/verbose [on|off]",desc:"Show the raw transcript \u2014 every tool call with its file path and full result, instead of article-shaped cards with my bookkeeping collapsed (bare: toggle)",group:"setup"},{name:"logout",usage:"/logout [--all-projects]",desc:"Sign out of this project + clear its workspace selection (then /login to re-pick)",group:"setup"},{name:"allow-prod",usage:"/allow-prod",desc:"Authorize taking articles live on a production profile",group:"setup"},{name:"env",usage:"/env [add <file.json>|remove <name>]",desc:"The Document360 deployments this machine can reach \u2014 and add one this build does not ship",group:"setup"},{name:"doctor",usage:"/doctor",desc:"Health-check: auth, profile, workspace, map, API, and a real agent turn",group:"setup"},{name:"logs",usage:"/logs",desc:"Show the most recent problem d360-writer recorded, and where the logs are \u2014 \u2303y copies it for the team",group:"setup"},{name:"update",usage:"/update",desc:"Update d360-writer \u2014 and d360-capture when installed \u2014 to the latest versions",group:"setup"},{name:"copy",usage:"/copy",desc:"Copy what is waiting \u2014 the feedback to relay, or the builder prompt to paste (\u2303y does the same)",group:"setup"},{name:"feedback",usage:"/feedback",desc:"Copy the repo's open d360-writer tool-feedback to your clipboard, to relay to the d360-writer team",group:"setup"},{name:"reset",usage:"/reset",desc:"[DANGER] Delete all d360-writer files (docs, config, screenshots); types repo name to confirm",group:"setup"},{name:"resume",usage:"/resume [name]",desc:"Resume a session (no arg lists them)",group:"session"},{name:"rename",usage:"/rename [name]",desc:"Name the session (no arg: suggest one)",group:"session"},{name:"clear",usage:"/clear",desc:"Clear the screen + reset the conversation (resumable)",group:"session"},{name:"help",usage:"/help",desc:"Show this help",group:"session"},{name:"exit",usage:"/exit",desc:"Quit",group:"session"}],Ew={"/catch-up":"write up everything your builder flagged","/audit":"check the code for anything new or missing in the docs","/discover":"interview your builder so the docs are grounded in the real product","/pull":"pull edits + new articles from Document360","/push":"save your articles to Document360 as drafts","/publish":"take the signed-off drafts live to your readers","/write":"author the planned articles","/draft":"plan articles from PRDs + the code","/login":"sign in to Document360","/workspace":"choose the Document360 workspace","/project":"choose the Document360 project","/scope":"choose which folders back the docs","/genre":"set this repo's product type (picks the docs playbook)","/init":"set up this repo","/screenshot":"work the screenshot pipeline (author specs, take shots, draw the callouts)","/doctor":"run a health check","/logs":"show the last problem, and copy it for the team","/auto":"choose whether I run the next step myself or wait for you","/style-guide":"choose the writing rules your docs are held to","/lint":"check the docs against those rules (costs nothing)"};function Nw(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(Ew[n])return Ew[n];let o=Ko.find(r=>r.name===t);return o?o.desc:""}function Dw(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return Ko.filter(n=>n.name.startsWith(t))}function jw(e){let t=0,n="";for(let o of e){if(o==="["){t++;continue}if(o==="]"){t=Math.max(0,t-1);continue}t===0&&(n+=o)}return/<[^>]+>/.test(n)}var ZP=new RegExp(`^\\s*/(?:${Ko.map(e=>e.name).join("|")})(?:\\s|$)`),Iw=e=>ZP.test(e),Lw=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Ow=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),_w=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function eT(e){let t=e.replace(/\r/g,"").split(`
|
|
349
|
-
`),n=[],o=0;for(;o<t.length;){let r=t[o];if(/^\s*```/.test(r)){let a=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)a.push(t[o++]);o++,n.push({kind:"code",lines:a});continue}if(
|
|
350
|
-
`).map(R=>
|
|
348
|
+
`},s=r(e),i=r(t);if(s===i)return null;let a=Math.max(20,n-10),l=aT("a","b",s,i,"","",{context:3}),c=0,p=0,m=[];l.hunks.forEach((C,S)=>{S>0&&m.push(pk.gray(" \u2026"));let A=C.oldStart,R=C.newStart,D=[],W=[],H=()=>{for(let J=0;J<D.length;J++){let G=J<W.length?fk(D[J],W[J]):void 0;p++,m.push(`${cT}${$p(A++)} - ${mk(D[J],a,G)}${hk}`)}for(let J=0;J<W.length;J++){let G=J<D.length?fk(D[J],W[J]):void 0;c++,m.push(`${uT}${$p(R++)} + ${mk(W[J],a,G)}${hk}`)}D=[],W=[]};for(let J of C.lines){let G=J[0],K=J.slice(1);G==="-"?D.push(K):G==="+"?W.push(K):(H(),m.push(pk.gray($p(R))+" "+K.slice(0,a)),A++,R++)}H()});let $=Math.max(1,o),w=m.slice(0,$);return{added:c,removed:p,lines:w,hidden:Math.max(0,m.length-$)}}import{select as kk}from"@inquirer/prompts";import{applyPull as bk,computeSyncStatus as hT,isPullWouldBlankError as yk,localArticleTitle as fT,planPull as wk}from"document360-engine";import{listUnpullable as dT,resolveActiveProfile as pT}from"document360-engine";function Hl(e,t,n,o){let r=n.filter(a=>a.status==="conflict"&&a.path).map(a=>a.path),s=new Set(o),i=[];try{i=dT(e,pT(e,t).name).map(a=>a.path).filter(a=>s.has(a))}catch{}return[...new Set([...r,...i])].sort()}function Gl(){return["Document360 will not give this article back as markdown \u2014 it is not on the Markdown (Editor 3.0) editor, so there is no portal copy to show you or to take.","Your local copy is intact, and publishing it over the portal settles this. Skipping leaves the article flagged, and it will be waiting again next time."]}function ql(){return"Publish your copy over the portal (settles it) \xB7 Skip?"}function gk(){return"(l publish yours \xB7 s skip \u2014 anything else stops, keeping your answers so far)"}function Vl(e){if(e.length===0)return[];let t=e.length,n=e.slice(0,3).join(", ")+(t>3?`, +${t-3} more`:"");return[`${t} article${t===1?"":"s"} stay${t===1?"s":""} flagged \u2014 Document360 cannot hand ${t===1?"its":"their"} markdown back: ${n}`,"Two ways out: run /resolve and press l to publish your copy over the portal, or ask your Document360 admin to move the article back to the Markdown (Editor 3.0) editor, then run /resolve again."]}function vp(e){return`Cannot take the portal copy of ${e} \u2014 Document360 will not return it as markdown. Left as it was.`}ae();var Kl=e=>e===1?"":"s";async function xp(e,t,n=1){console.log(""),console.log(`${Z("\u25CF")} ${rt(t.title)} ${Ie(`(${t.path})`)}`);for(let i of t.notes)console.log(F(` \u26A0 ${i}`));let o=Yt(t.oldContent,t.newContent,Math.max(40,(process.stdout.columns??80)-1),ns);if(o){console.log(Ie(` \u23BF local \u2192 portal: +${o.added} / -${o.removed} line${Kl(o.added+o.removed)}`));for(let i of o.lines)console.log(i);o.hidden>0&&console.log(u(` \u2026 +${o.hidden} more diff lines`))}else console.log(u(" Local already matches the portal content \u2014 resolving just advances the sync base."));let r=n>1,s=await e.withPausedInput(()=>kk({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"?(bk({cwd:e.cwd,profileName:e.profileName},t),console.log(Q(" \u2713 Took the portal copy (local overwritten, sync base advanced).")),"took-portal"):s==="local"?"keep-local":s==="skip"?(console.log(u(" Skipped \u2014 still a conflict.")),"skipped"):s==="local-all"?"keep-local-all":s==="portal-all"?"took-portal-all":"skipped-all"}async function mT(e,t){console.log(""),console.log(`${Z("\u25CF")} ${rt(fT(e.cwd,t)??t)} ${Ie(`(${t})`)}`);for(let o of Gl())console.log(F(` \u26A0 ${o}`));return await e.withPausedInput(()=>kk({message:ql(),choices:[{name:"Publish your copy over the portal (settles it)",value:"local"},{name:"Skip (leave it a conflict)",value:"skip"}]})).catch(()=>"skip")==="local"?"keep-local":(console.log(u(" Skipped \u2014 still a conflict.")),"skipped")}async function $k(e,t){let n=st(t.cwd,t.profileName);if(!n.ok){let[r,s]=Gt(n);return console.log(L(r)),console.log(u(s)),{kind:"continue"}}let o=e.find(r=>!r.startsWith("--"))?.replace(/\\/g,"/");try{let r=await hT({cwd:t.cwd,profileName:t.profileName}),s=Hl(t.cwd,t.profileName,r.entries,tr(r.entries).map(l=>l.path));if(o){if(!s.includes(o))return console.log(Q(`${o} isn't waiting on a decision \u2014 nothing to resolve.`)),{kind:"continue"};s=[o]}if(s.length===0)return console.log(Q("\u2713 No conflicts \u2014 local and Document360 agree on every tracked article.")),{kind:"continue"};let i=[],a=[];for(let[l,c]of s.entries()){let p;try{p=await wk({cwd:t.cwd,profileName:t.profileName,relPath:c})}catch(w){if(!yk(w))throw w;await mT(t,c)==="keep-local"?i.push(c):a.push(c);continue}let m=await xp(t,p,s.length-l);if(m==="keep-local"&&i.push(c),!m.endsWith("-all"))continue;let $=s.slice(l);if(m==="keep-local-all")i.push(...$),console.log(u(` Keeping local for all ${$.length} \u2014 publishing them over the portal.`));else if(m==="took-portal-all"){let w=0;for(let C of $)try{bk({cwd:t.cwd,profileName:t.profileName},await wk({cwd:t.cwd,profileName:t.profileName,relPath:C})),w++}catch(S){console.log(L(` \u2717 ${C}: ${S.message}`)),yk(S)&&a.push(C)}console.log(Q(` \u2713 Took the portal copy of ${w} article${Kl(w)} (local overwritten, sync base advanced).`))}else console.log(u(` Skipped all ${$.length} \u2014 still conflict${Kl($.length)}.`));break}for(let l of Vl(a))console.log(F(`\u26A0 ${l}`));if(i.length>0)return console.log(u(`Publishing ${i.length} kept-local article${Kl(i.length)} over the portal\u2026`)),await cn(t,i,0,{allowUnpullable:!0})}catch(r){console.log(L(`Resolve failed: ${r.message}`))}return{kind:"continue"}}async function Rk(e,t){let n=st(t.cwd,t.profileName);if(!n.ok){let[r,s]=Gt(n);return console.log(L(r)),console.log(u(s)),{kind:"continue"}}let o=e.find(r=>r.startsWith("--"));try{if(o==="--status")return await xT(t),{kind:"continue"};if(o==="--baseline")return await RT(t,e.filter(i=>i!=="--baseline")),{kind:"continue"};if(o==="--compare")return await ST(t),{kind:"continue"};if(o)return console.log(L(`Unknown option: ${o}`)),console.log(u("Usage: /pull pull portal edits + import new portal articles")),console.log(u(" /pull <path> pull one article (or resolve a conflict)")),console.log(u(" /pull --status drift report only (no writes)")),console.log(u(" /pull --baseline set a sync baseline for not-yet-compared articles")),{kind:"continue"};let r=e[0];if(r)return await CT(t,r),{kind:"continue"};console.log(u("Pulling changes from Document360\u2026"));let s=await Sp({cwd:t.cwd,profileName:t.profileName});for(let i of Cp(s))console.log(i.tone==="ok"?Q(i.text):i.tone==="warn"?F(i.text):u(i.text));console.log("")}catch(r){r instanceof vT?console.log(L(r.message)):console.log(L(`Pull failed: ${r.message}`))}return{kind:"continue"}}async function Sp(e){let t=await vk({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 xk({cwd:e.cwd,profileName:e.profileName,relPath:o.path});Rp({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 wT({cwd:e.cwd,profileName:e.profileName,articleId:o.articleId,...o.remoteCategory?{categoryPath:o.remoteCategory.path}:{}});kT({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 Yl=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,nr=e=>e===1?"":"s";function Cp(e){let t=[];if(e.pulled.length&&t.push({tone:"ok",text:`\u2713 Pulled ${e.pulled.length} portal edit${nr(e.pulled.length)} into local: ${Yl(e.pulled)}`}),e.imported.length&&t.push({tone:"ok",text:`\u2713 Imported ${e.imported.length} new portal article${nr(e.imported.length)}: ${Yl(e.imported.map(n=>n.path))}`}),e.toPublish&&t.push({tone:"info",text:`\u2139 ${e.toPublish} article${nr(e.toPublish)} changed locally \u2014 /push saves them to Document360.`}),e.conflicts.length&&t.push({tone:"warn",text:`\u26A0 ${e.conflicts.length} article${nr(e.conflicts.length)} changed both here and on Document360 \u2014 left untouched. Resolve them: /resolve (or /push <path> to keep yours, /pull <path> to take the portal's). (${Yl(e.conflicts)})`}),e.failed.length){t.push({tone:"warn",text:`\u26A0 ${e.failed.length} item${nr(e.failed.length)} could not be imported.`});let n=new Map;for(let o of e.failed){let r=o.error.replace(/^"[^"]*" could not be imported: /,"");n.set(r,[...n.get(r)??[],o.ref])}for(let[o,r]of n)t.push({tone:"warn",text:` ${o}`}),t.push({tone:"warn",text:` ${Yl(r)}`})}return t.length===0&&t.push({tone:"ok",text:"\u2713 Already in sync with Document360 \u2014 nothing to pull."}),t}async function xT(e){console.log(u("Checking Document360 for drift\u2026"));let t=Date.now(),n=await vk({cwd:e.cwd,profileName:e.profileName});for(let o of Bl(n,Date.now()-t))console.log(o);console.log("")}async function RT(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(u(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await bT({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0}),r=n?{rebaselined:[],skipped:[]}:await $T({cwd:e.cwd,profileName:e.profileName});if(o.baselined.length===0&&o.skipped.length===0&&r.rebaselined.length===0){console.log(Q("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(Q(`\u2713 Recorded ${o.baselined.length} article(s) as matching Document360 \u2014 they read in-sync until either side changes.`)),r.rebaselined.length>0&&console.log(Q(`\u2713 Refreshed the metadata baseline for ${r.rebaselined.length} article(s) \u2014 cleared false "metadata changed" drift.`)),o.skipped.length>0){console.log(F(`${o.skipped.length} skipped:`));for(let s of o.skipped)console.log(u(` - ${s.path} (${s.reason})`))}}async function ST(e){console.log(u("Comparing the manifest against the per-article path (read-only)\u2026"));let t=await yT({cwd:e.cwd,profileName:e.profileName});console.log(` Legacy listing: ${rt(String(t.legacyCount))} \xB7 Manifest: ${rt(String(t.manifestCount))} \xB7 in both: ${t.inBoth}`),t.onlyInLegacy.length===0&&t.onlyInManifest.length===0&&t.mappedMissingFromManifest.length===0?console.log(Q("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source.")):(t.mappedMissingFromManifest.length&&console.log(L(`\u2717 ${t.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${t.mappedMissingFromManifest.slice(0,5).join(", ")}`)),t.onlyInLegacy.length&&console.log(F(` ${t.onlyInLegacy.length} only in the legacy listing: ${t.onlyInLegacy.slice(0,5).join(", ")}`)),t.onlyInManifest.length&&console.log(F(` ${t.onlyInManifest.length} only in the manifest: ${t.onlyInManifest.slice(0,5).join(", ")}`)),console.log(u(" Send this output \u2014 a mismatch pinpoints where the manifest differs before we flip."))),console.log("")}async function CT(e,t){let n=t.replace(/\\/g,"/"),o=await xk({cwd:e.cwd,profileName:e.profileName,relPath:n});if(o.overwritesLocalChanges){await xp(e,o)==="keep-local"&&(console.log(u(`Publishing ${o.path} over the portal\u2026`)),await cn(e,[o.path]));return}console.log(""),console.log(`${Z("\u25CF")} ${rt(o.title)} ${Ie(`(${o.path})`)}`);for(let i of o.notes)console.log(F(` \u26A0 ${i}`));let r=Yt(o.oldContent,o.newContent,Math.max(40,(process.stdout.columns??80)-1),ns);if(!r){console.log(u(" Local file already matches the remote content \u2014 advancing the sync base only.")),Rp({cwd:e.cwd,profileName:e.profileName},o);return}console.log(Ie(` \u23BF Added ${r.added} line${nr(r.added)}, removed ${r.removed} line${nr(r.removed)}`));for(let i of r.lines)console.log(i);if(r.hidden>0&&console.log(u(` \u2026 +${r.hidden} more diff lines`)),!await e.withPausedInput(()=>gT({message:`Write ${o.path}?`,default:!o.overwritesLocalChanges}))){console.log(u(" Skipped."));return}Rp({cwd:e.cwd,profileName:e.profileName},o),console.log(Q(` \u2713 Pulled ${o.path} (sync base advanced).`))}ae();import{statSync as UT}from"node:fs";import{resolve as FT}from"node:path";import{estimateBulkCost as WT,planPartitions as BT,readProjectConfig as HT,resolveModelForOperation as GT,runPartitioned as qT,trackedArticlePaths as VT}from"document360-engine";function ho(e,t){return e.aborted?null:e.blocked?[`\u2717 ${t} didn\u2019t start \u2014 ${e.blocked}.`,"Nothing was changed. Fix that, then re-run."]:e.allEmpty?[`\u2717 ${t} did nothing \u2014 every batch produced no output, so no agent actually ran.`,"Run /doctor \u2014 it runs a real turn with your skills and tools and reports what failed. /logs shows Claude Code\u2019s own error, which was recorded either way, and offers to copy it.","A Claude usage or session limit also does this, and it ends every turn instantly \u2014 if you have just hit one, wait for the reset and re-run."]:null}function Sk(e){return!e.bailedEmpty||!e.notRun?null:`\u26A0 Stopped early \u2014 ${e.notRun} batch${e.notRun===1?" was":"es were"} not attempted, because two in a row produced no output (that is systemic, not this work: usually a Claude usage limit). Re-run to finish the rest; anything already done is skipped.`}var os=class{activeMs=0;last=0;timer=null;startedAt=0;stopped=null;start(t=Date.now()){this.timer||(this.startedAt=t,this.last=t,this.timer=setInterval(()=>this.tick(),1e3),this.timer.unref?.())}tick(t=Date.now()){let n=t-this.last;this.last=t,!(n<=0)&&(this.activeMs+=Math.min(n,5e3))}stop(t=Date.now()){return this.stopped?this.stopped:(this.timer&&(clearInterval(this.timer),this.timer=null),this.tick(t),this.stopped={activeSeconds:Math.max(0,Math.round(this.activeMs/1e3)),elapsedSeconds:Math.max(0,Math.round((t-this.startedAt)/1e3))},this.stopped)}};function zl(e,t){let n=t-e;return n>=300&&n>=t*.2}function zt(e,t,n,o=Date.now(),r){let s=t.reduce((a,l)=>a+(l.inputTokens??0),0),i=t.reduce((a,l)=>a+(l.cacheReadTokens??0),0);return{seconds:Math.max(0,Math.round((o-e)/1e3)),outputTokens:t.reduce((a,l)=>a+l.outputTokens,0),inputTokens:s,...s>0?{cachedPct:Math.round(i/s*100)}:{},...r!==void 0?{activeSeconds:r}:{},costUsd:n}}function Xl(e){return e.activeSeconds!==void 0&&zl(e.activeSeconds,e.seconds)?`${Pp(e.seconds)} elapsed \xB7 ${Pp(e.activeSeconds)} working`:Pp(e.seconds)}var Ck=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:`${e}`,Pp=e=>{if(e<60)return`${e}s`;let t=Math.floor(e/60);return t<60?`${t}m ${e%60}s`:`${Math.floor(t/60)}h ${t%60}m`};function kn(e){let t=e.cachedPct!==void 0?`, ${e.cachedPct}% cached`:"",n=e.costUsd>0?`, this turn ${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"";return` (took ${Xl(e)}, ${Ck(e.inputTokens)}\u2192${Ck(e.outputTokens)} tokens${t}${n})`}import Ce from"picocolors";import{PRODUCT_DISPLAY_NAME as OT}from"document360-engine";import Dp from"wrap-ansi";import jp from"string-width";ae();import fo from"picocolors";import Jl from"wrap-ansi";import Ql from"string-width";import{CAPTURE_COMMAND as PT,PRODUCT_NAME as rs,WRITER_DIRNAME as Ap}from"document360-engine";var or=[{name:"init",usage:"/init",desc:`Pick an environment, scaffold ${Ap}/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 ${Ap}/input/ + the code`,group:"docs"},{name:"document",usage:"/document [<what>] [--push]",desc:"Document a shipped change \u2014 the agent picks the action (new section/article/update); bare: act on builder requests. --push then saves the result to Document360 as drafts, which still needs an editorial review first",group:"docs"},{name:"write",usage:"/write [--preview|--scope <cat>|<path>] [--rewrite] [--concurrency N] [--skip-style]",desc:"Write the planned articles in parallel (starts immediately; --preview shows plan + cost first; --rewrite regenerates already-written articles; --concurrency default 3). Anything that would block publishing is corrected in one automatic pass before the run finishes; --skip-style leaves it to /lint",group:"docs"},{name:"screenshot",usage:"/screenshot [author|capture|annotate|verify|checklist|list] [id|path|--all|--failed|--blocked]",desc:"Screenshots, one family \u2014 bare: pick what to do; author: write capture specs; capture: take the shots (--all re-shoots everything; --failed re-runs the ones that did not work; --blocked re-runs the ones waiting on app data); annotate: draw the callouts on shots already taken, no browser needed (--all --force re-draws after a wording or style change); verify: judge the finished pictures and mark them verified (both run automatically after a capture); checklist: what to stage + dev test-id requests; list: status + what to stage",group:"docs"},{name:"preview",usage:"/preview [path|id]",desc:"Render an article (no arg: pick from tracked)",group:"docs"},{name:"push",usage:"/push [path|--all|--related <path>|[<category>] --screenshots] [--preview] [--skip-review]",desc:"Save your articles to Document360 as drafts \u2014 readers don't see them until /publish (no arg: pick; --all: every candidate; --screenshots: re-save articles with captured shots so images embed, optionally narrowed to one category; --related <path>: also save that article's related articles that were never saved; --preview <path>: show exactly what would be sent, and send nothing). Blocked until each article has had /review --fix \u2014 AI-written text gets an editor first; --skip-review overrides deliberately",group:"publish"},{name:"publish",usage:"/publish [path|<category>|--all] [--skip-review]",desc:"Take the drafts on Document360 LIVE to your readers (the portal's own Publish). Always lists what would become visible and asks first; no arg or a category narrows it. Needs an editorial review \u2014 /review --blocked --fix",group:"publish"},{name:"style-guide",usage:"/style-guide [list | use [<preset>] | keep | triage | off <rule> | on <rule> | sweep [skip] | pull [<n>] | learn | compile | explain <rule>]",desc:"Choose the writing rules your docs are held to. Bare: what is active now; list: every pack you can turn on; use: switch packs, hold every article to them and apply the free text swaps (bare: pick from a list); keep: settle on the rules you have today; triage: which rules are producing the most findings, with a decision for each (free); off/on: silence one rule, or put it back; sweep: how much of your knowledge base still needs reading against a guide you switched to (skip stops me raising it); pull: bring your Document360 project's own style guide down; learn: turn what your reviewers keep asking for into standing rules; compile: turn its mechanical statements into checks; explain: what one rule means, what your own tweaks changed, and how to silence it",group:"docs"},{name:"lint",usage:"/lint [<category|path>] [--blocked] [--fix] [--full] [--baselined]",desc:"Lint the docs against the house rules: leaked internals, invented commands, stale facts, AI-tells, em dashes, callout shape (deterministic, no tokens). Every finding names the rule that produced it. Scope to a category/path; --blocked narrows to the errors that block publishing and leaves warnings and suggestions alone; --fix has the agent correct them in place; --full lists every finding instead of a capped summary; --baselined shows the issues that were already in your articles when you chose this style guide, which never block publishing",group:"docs"},{name:"review",usage:"/review [<category|path> | --all | --blocked | --stale] [--fix]",desc:"Independent senior-editor review: style guide, terminology/voice, grammar/clarity, page structure, improvement suggestions. A whole-knowledge-base run also gets one editor on the SHAPE of the docs \u2014 reading order, categories that have grown too big, articles filed in the wrong place, names that no longer fit. Bare: pick a category or everything; --blocked reads only the articles publishing is blocked on; --stale reads the ones the current editor has not read yet, so running it twice costs nothing; --all reviews the whole KB; --fix applies the corrections in place",group:"docs"},{name:"reorder",usage:"/reorder [<category> | --all]",desc:"Reorder articles within a category to the best reading order (renumbers NN- prefixes, fixes references + map); bare: pick a category or everything; new order syncs to Document360 on next /push",group:"docs"},{name:"restructure",usage:"/restructure [<what to change>]",desc:"Reshape the knowledge base: move an article to a different category, split one that has grown too big, merge two, rename one, or nest one inside another. A category left empty by a merge is hidden from readers, never deleted. Bare: reviews how the docs are organized and reports what should change, without touching anything; the changes reach Document360 on the next /push",group:"docs"},{name:"structure",usage:"/structure",desc:"Show the documentation reading order (categories \u2192 articles) as it will appear on Document360",group:"docs"},{name:"status",usage:"/status [--all]",desc:'What stands between your work and your readers, before you spend anything: which articles no editor has read, which break a style rule your config makes blocking, which would show "[Screenshot: \u2026]" text to a reader, which are in conflict with the portal, and which are saved as drafts readers cannot see yet. Each group names the one command that clears it. Reads local files and the last sync \u2014 no network, no tokens. --all lists every article gate by gate',group:"publish"},{name:"retire",usage:"/retire [<path>] [--yes]",desc:"Take an article off your readers on Document360 \u2014 it stops being visible, and nothing offers to publish it again. Nothing is deleted: the article, its version history and every reviewer comment stay. Bare: lists what is worth retiring (articles on Document360 that are no longer in your docs folder). /push puts one back \u2014 reviving is a publish like any other",group:"publish"},{name:"untrack",usage:"/untrack [<path>] [--undo] [--list] [--yes]",desc:`Disown a page that was imported from Document360 but is not one of your docs. /catch-up and /pull import every article they find in your categories; this records the ones you do not want, so they are never imported again \u2014 and the decision travels with the repo, so a teammate\u2019s clone inherits it. Nothing on Document360 changes and nothing is deleted: the markdown moves to ${Ap}/declined/. Bare: lists what this repo has declined. --undo puts one back`,group:"publish"},{name:"reuse",usage:'/reuse [pull | add <variable|snippet> <name> "<value>" | audit [<category>] [--create <n\u2026>]]',desc:"The terms, values and blocks your project already maintains on Document360, so your articles reference them instead of repeating them. A variable holds a value like your product name in one place \u2014 change it there and every article changes; type it out by hand and /lint flags it. A snippet does the same for a whole block, and the writer references yours by name instead of writing its own version. A term is defined once and every article is checked for explaining it the first time it appears. Reading is free; pull refreshes from Document360, add creates a new one there, and audit reads every article to work out what belongs in one place",group:"docs"},{name:"eval",usage:"/eval [<category>] [--all]",desc:"How does your whole knowledge base score? Reads every article and reports what no single-article check can see: internal links written as portal URLs, links pointing at headings that no longer exist, link text that names a different article, the command summary line appearing in several shapes, two names for the same section, and how many style findings were accepted as exempt when you chose your style guide. Costs nothing and calls nothing",group:"docs"},{name:"terms",usage:'/terms [<category>] [--all] [--approve "<term>"]',desc:"Is your knowledge base calling the same thing by the same name? Reads every article and reports terms spelled more than one way, short names that may be the long name abbreviated, and article titles out of step with the rest of their kind \u2014 the consistency an editor reading three articles at a time cannot see. Costs nothing and calls nothing. --approve records a spelling as the approved one, so every later run enforces it",group:"docs"},{name:"roadmap",usage:"/roadmap [--all | done [step]]",desc:"Show the docs campaign (the multi-session plan the agent maintains), grouped by the part of the job \u2014 progress + next step; `--all` also lists the steps a later pass replaced; `done` marks the next open step finished (add words from a title to pick another)",group:"docs"},{name:"audit",usage:"/audit [--auto on|off] [--decline <path>]",desc:"Gap analysis: code vs docs vs Document360 (what changed); --auto runs it at launch when code changed; --decline settles a folder or file that needs no article",group:"publish"},{name:"inbox",usage:"/inbox",desc:"Act on messages from the repo's coding agent (requests to document, answers to your questions)",group:"publish"},{name:"ask",usage:"/ask <question>",desc:"Ask your developers something the code cannot tell you: why a feature exists, when to use it, whether it can be undone",group:"publish"},{name:"share",usage:"/share [status|on|off]",desc:"Share your docs work with the team: get your builder's latest, then save + send yours (runs automatically; `off` leaves it to your coding agent)",group:"publish"},{name:"catch-up",usage:"/catch-up [--push] [--include-unfinished]",desc:"Process ALL pending work (builder hints + requests + Document360 portal drift) \u2192 write \u2192 save to Document360 as drafts. --push does that last step for you, which still needs an editorial review first. A note whose code your builder has not committed is left for later, and they are asked whether it is done; --include-unfinished writes those pages anyway. For code changes, that's /audit",group:"publish"},{name:"comments",usage:"/comments [<article>] [--scope <category>] [--answer] [--all] [--resolve] [--answered] [--full]",desc:"Reviewer comments left on passages of your articles in the Document360 portal \u2014 bare: a table by article, pick a number to read its comments in full, then answer or go back; --answer: fix, push the draft, reply (threads stay open unless you add --resolve); --full re-reads every article",group:"publish"},{name:"pull",usage:"/pull [<path> | --status | --baseline]",desc:"Bring Document360 down: pull portal edits + import NEW portal articles. --status: drift report only \xB7 --baseline: set a sync base \xB7 <path>: one article / resolve a conflict",group:"publish"},{name:"resolve",usage:"/resolve [<path>]",desc:"Resolve conflicts (edited both here and on the portal): shows the diff, then keep local (push), take portal (pull), or skip \u2014 per article, or one answer for all remaining. Bare: walk them all",group:"publish"},{name:"convert",usage:"/convert [--scope <folder>] [--run]",desc:"Convert tracked articles to DFM (one-off legacy migration)",group:"publish"},{name:"profile",usage:"/profile [name|add <name> [env]]",desc:"Where this repo publishes \u2014 switch, or connect another environment (picker; s = session)",group:"setup"},{name:"workspace",usage:"/workspace [name]",desc:"Switch the Document360 workspace (picker)",group:"setup"},{name:"auto",usage:"/auto [on|off|status] [--budget <amount>]",desc:"Auto or manual: in auto I run the next step myself \u2014 write, review, check style, save, go live \u2014 instead of waiting for you (shift+tab cycles it; esc stops a run)",group:"setup"},{name:"model",usage:"/model [name|default]",desc:`Set the Claude model for ${rs}`,group:"setup"},{name:"verbose",usage:"/verbose [on|off]",desc:"Show the raw transcript \u2014 every tool call with its file path and full result, instead of article-shaped cards with my bookkeeping collapsed (bare: toggle)",group:"setup"},{name:"logout",usage:"/logout [--all-projects]",desc:"Sign out of this project + clear its workspace selection (then /login to re-pick)",group:"setup"},{name:"allow-prod",usage:"/allow-prod",desc:"Authorize taking articles live on a production profile",group:"setup"},{name:"env",usage:"/env [add <file.json>|remove <name>]",desc:"The Document360 deployments this machine can reach \u2014 and add one this build does not ship",group:"setup"},{name:"doctor",usage:"/doctor",desc:"Health-check: auth, profile, workspace, map, API, and a real agent turn",group:"setup"},{name:"logs",usage:"/logs",desc:`Show the most recent problem ${rs} recorded, and where the logs are \u2014 \u2303y copies it for the team`,group:"setup"},{name:"update",usage:"/update",desc:`Update ${rs} \u2014 and ${PT} when installed \u2014 to the latest versions`,group:"setup"},{name:"copy",usage:"/copy",desc:"Copy what is waiting \u2014 the feedback to relay, or the builder prompt to paste (\u2303y does the same)",group:"setup"},{name:"feedback",usage:"/feedback",desc:`Copy the repo's open ${rs} tool-feedback to your clipboard, to relay to the ${rs} team`,group:"setup"},{name:"reset",usage:"/reset",desc:`[DANGER] Delete all ${rs} 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"}],Pk={"/catch-up":"write up everything your builder flagged","/audit":"check the code for anything new or missing in the docs","/discover":"interview your builder so the docs are grounded in the real product","/pull":"pull edits + new articles from Document360","/push":"save your articles to Document360 as drafts","/publish":"take the signed-off drafts live to your readers","/write":"author the planned articles","/draft":"plan articles from PRDs + the code","/login":"sign in to Document360","/workspace":"choose the Document360 workspace","/project":"choose the Document360 project","/scope":"choose which folders back the docs","/genre":"set this repo's product type (picks the docs playbook)","/init":"set up this repo","/screenshot":"work the screenshot pipeline (author specs, take shots, draw the callouts)","/doctor":"run a health check","/logs":"show the last problem, and copy it for the team","/auto":"choose whether I run the next step myself or wait for you","/style-guide":"choose the writing rules your docs are held to","/lint":"check the docs against those rules (costs nothing)"};function Ak(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(Pk[n])return Pk[n];let o=or.find(r=>r.name===t);return o?o.desc:""}function Tk(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return or.filter(n=>n.name.startsWith(t))}function Ek(e){let t=0,n="";for(let o of e){if(o==="["){t++;continue}if(o==="]"){t=Math.max(0,t-1);continue}t===0&&(n+=o)}return/<[^>]+>/.test(n)}var AT=new RegExp(`^\\s*/(?:${or.map(e=>e.name).join("|")})(?:\\s|$)`),Nk=e=>AT.test(e),Dk=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),jk=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),Ik=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function TT(e){let t=e.replace(/\r/g,"").split(`
|
|
349
|
+
`),n=[],o=0;for(;o<t.length;){let r=t[o];if(/^\s*```/.test(r)){let a=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)a.push(t[o++]);o++,n.push({kind:"code",lines:a});continue}if(Dk(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&jk(t[o+1])){let a=Ik(r);o+=2;let l=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)l.push(Ik(t[o++]));n.push({kind:"table",header:a,rows:l});continue}let s=r.match(/^(#{1,6})\s+(.*)$/);if(s){n.push({kind:"heading",level:s[1].length,text:s[2]}),o++;continue}if(/^\s*([-*]|\d+\.)\s+/.test(r)){let a=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);){let l=t[o++];a.push({ordered:/^\s*\d+\.\s+/.test(l),text:l.replace(/^\s*([-*]|\d+\.)\s+/,"")})}n.push({kind:"list",items:a});continue}if(r.trim()===""){o++;continue}if(Nk(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])&&!Nk(t[o])&&!Dk(t[o])&&!(t[o].includes("|")&&o+1<t.length&&jk(t[o+1]));)i.push(t[o++]);n.push({kind:"para",text:i.join(" ")})}return n}function Tp(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?fo.bold(t.slice(2,-2)):t.startsWith("`")?Z(t.slice(1,-1)):fo.italic(t.slice(1,-1)))}var ET=(e,t)=>e+" ".repeat(Math.max(0,t-Ql(e)));function ki(e,t,n,o={}){return Lk(e,t,n,o)}function Lk(e,t,n,o={}){let r=e.length,s=A=>Math.max(0,...A.split(`
|
|
350
|
+
`).map(R=>Ql(R))),i=e.map((A,R)=>Math.max(Ql(A),...t.map(D=>s(D[R]??"")))),a=Math.max(24,n),l=3*r+1,c=[...i],p=()=>c.reduce((A,R)=>A+R,0)+l,m=0;for(;p()>a&&m++<1e4;){let A=-1,R=6;for(let D=0;D<r;D++)c[D]>R&&(R=c[D],A=D);if(A===-1)break;c[A]-=1}let $=(A,R,D)=>fo.gray(A+c.map(W=>"\u2500".repeat(W+2)).join(R)+D),w=fo.gray("\u2502"),C=(A,R)=>{let D=c.map((G,K)=>{let ne=A[K]??"",oe=R?fo.bold(ne):o.plain?ne:Tp(ne);return ne.includes(`
|
|
351
351
|
`)?oe.split(`
|
|
352
|
-
`).flatMap(
|
|
353
|
-
`)):
|
|
354
|
-
`)}),
|
|
355
|
-
`)},S=[$("\u250C","\u252C","\u2510"),C(e,!0)];return S.push(t.length===0?$("\u2514","\u2534","\u2518"):$("\u251C","\u253C","\u2524")),t.forEach((
|
|
356
|
-
`)}function
|
|
352
|
+
`).flatMap(Re=>Jl(Re,G,{hard:!0}).split(`
|
|
353
|
+
`)):Jl(oe,G,{hard:!0}).split(`
|
|
354
|
+
`)}),W=Math.max(...D.map(G=>G.length)),H=[],J=(G,K,ne)=>o.align?.[ne]==="right"?" ".repeat(Math.max(0,K-Ql(G)))+G:ET(G,K);for(let G=0;G<W;G++)H.push(c.map((K,ne)=>`${w} ${J(D[ne][G]??"",K,ne)} `).join("")+w);return H.join(`
|
|
355
|
+
`)},S=[$("\u250C","\u252C","\u2510"),C(e,!0)];return S.push(t.length===0?$("\u2514","\u2534","\u2518"):$("\u251C","\u253C","\u2524")),t.forEach((A,R)=>{S.push(C(A,!1)),S.push(R===t.length-1?$("\u2514","\u2534","\u2518"):$("\u251C","\u253C","\u2524"))}),S.join(`
|
|
356
|
+
`)}function NT(e,t){switch(e.kind){case"heading":return fo.bold(e.text);case"hr":return fo.gray("\u2500".repeat(t));case"para":return Jl(Tp(e.text),t);case"list":{let n=0;return e.items.map(o=>{let r=o.ordered?`${++n}.`:"\u2022",s=" ".repeat(2+r.length+1),[i="",...a]=Jl(Tp(o.text),Math.max(10,t-s.length)).split(`
|
|
357
357
|
`);return` ${r} ${i}`+a.map(l=>`
|
|
358
358
|
${s}${l}`).join("")}).join(`
|
|
359
|
-
`)}case"code":return e.lines.map(n=>
|
|
360
|
-
`);case"table":return
|
|
359
|
+
`)}case"code":return e.lines.map(n=>fo.gray(" "+n)).join(`
|
|
360
|
+
`);case"table":return Lk(e.header,e.rows,t)}}function Ep(e,t){let n=Math.max(20,t);return TT(e).map(o=>NT(o,n)).join(`
|
|
361
361
|
|
|
362
|
-
`)}
|
|
363
|
-
`);let r=2,s=3,i=
|
|
362
|
+
`)}ae();ae();import DT from"picocolors";var jT=Yu,IT=[22,38,43],Ok={T:jT,E:IT},bi=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],Np=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,LT=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function _k(){if(!DT.isColorSupported)return[];let e=bi[0].length,t=[];for(let n=0;n<bi.length;n+=2){let o="";for(let r=0;r<e;r++){let s=Ok[bi[n][r]],i=n+1<bi.length?Ok[bi[n+1][r]]:void 0;s&&i?o+=`${Np(s)}${LT(i)}\u2580\x1B[49m\x1B[39m`:s?o+=`${Np(s)}\u2580\x1B[39m`:i?o+=`${Np(i)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function $i(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 Wn(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function Uk(e,t,n){let o=e>0&&e<=n?e:t;return Math.max(0,Math.floor((n-o)/1e3))}function Dt(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function is(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var ss=(e,t)=>` ${e.padEnd(13)}${t}`;function _T(e,t){let n=[Qs(`\u270E ${OT}`)+Ce.gray(` v${e.version} \xB7 engine v${e.engineVersion}${e.captureVersion?` \xB7 capture v${e.captureVersion}`:""}`),Ce.gray(" Reads your code, writes your docs."),"",ss("Claude:",`${e.claude}${Ce.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),ss("Document360:",e.configured?e.envFix?Ce.yellow(`no deployment to reach \u2014 run ${e.envFix}`):e.loggedOut?Ce.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?Ce.gray(` (${e.sessionHint})`):""}`:Ce.yellow("not set up \u2014 run /init")),ss("Profile:",e.configured?`${e.profile}${Ce.gray(` (${e.apiUrl})`)}${e.prod?Ce.yellow(` ${Je}`):""}`:Ce.gray("\u2014 (run /init)")),ss("Project:",e.configured&&e.workspace===null?`${e.project}${Ce.yellow(" \xB7 no workspace yet")}`:`${e.project}${e.workspace?Ce.gray(` \xB7 ${e.workspace}`):""}`),ss("Mode:",Ce.gray(e.mode)),ss("cwd:",Ce.gray(e.cwd))],o=_k();if(o.length===0)return n.join(`
|
|
363
|
+
`);let r=2,s=3,i=jp(o[0]);if(!(t>=r+i+s+Math.max(...n.map(p=>jp(p)))))return[...o.map(p=>" "+p),...n].join(`
|
|
364
364
|
`);let l=Math.max(0,Math.floor((n.length-o.length)/2)),c=[];for(let p=0;p<Math.max(o.length+l,n.length);p++){let m=o[p-l]??" ".repeat(i);c.push((" ".repeat(r)+m+" ".repeat(s)+(n[p]??"")).trimEnd())}return c.join(`
|
|
365
|
-
`)}var
|
|
366
|
-
`).flatMap(c=>
|
|
367
|
-
`)),l=Math.max(0,a.length-i);return l>0&&(a=[...a.slice(0,i),
|
|
368
|
-
`+a.map((c,p)=>o+(p===0?Z(" \u276F "):" ")+c+" ".repeat(Math.max(0,s-
|
|
365
|
+
`)}var MT={error:Ce.red,warn:Ce.yellow,ok:Ce.green,info:Ce.gray},Mk=9;function Ip(e){return e.length>=Mk?`${e} `:e.padEnd(Mk)}function Zl(e){return e.replace(/^(\s*• |)([^\x00-\x7F][\u{1F000}-\u{1FAFF}️]*) (?=\S)/gmu,"$1$2 ")}function Lp(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return _T(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",s=Math.max(10,n-4),i=50,a=e.text.split(`
|
|
366
|
+
`).flatMap(c=>Dp(c,s,{hard:!0}).split(`
|
|
367
|
+
`)),l=Math.max(0,a.length-i);return l>0&&(a=[...a.slice(0,i),Ce.dim(`\u2026 +${l} more lines`)]),`
|
|
368
|
+
`+a.map((c,p)=>o+(p===0?Z(" \u276F "):" ")+c+" ".repeat(Math.max(0,s-jp(c))+1)+r).join(`
|
|
369
369
|
`)}case"assistant":return`
|
|
370
|
-
`+
|
|
371
|
-
`+
|
|
372
|
-
`+
|
|
373
|
-
`)}case"diff":{let o=i=>i===1?"":"s",s=[
|
|
374
|
-
`)}case"link":return e.lines.map(o=>Z(
|
|
370
|
+
`+Ep(e.text,n);case"tool":{let o=e.arg!==null?Ce.gray(`${e.sep}(${e.arg})`):"";return`
|
|
371
|
+
`+Dp(Ce.gray("\u25CF ")+e.title+o,n)}case"doc":{let o=[e.category,e.note].filter(s=>!!s).map(s=>Ce.gray(` \xB7 ${s}`)),r=e.loud?Ce.gray(" \xB7 ")+Ce.bold(Ce.yellow(e.loud)):"";return`
|
|
372
|
+
`+Dp(Ce.green("\u25CF ")+Z(Ce.bold(Ip(e.verb)))+Ce.bold(e.title)+o.join("")+r,n)}case"tool-result":{let o=e.isError?Ce.red:Ce.gray,r=e.lines.map((s,i)=>o((i===0?" \u23BF ":" ")+s));return e.hidden>0&&r.push(Ce.dim(` \u2026 +${e.hidden} lines`)),r.join(`
|
|
373
|
+
`)}case"diff":{let o=i=>i===1?"":"s",s=[Ce.gray(` \u23BF Added ${e.added} line${o(e.added)}, removed ${e.removed} line${o(e.removed)}`),...e.lines];return e.hidden>0&&s.push(Ce.dim(` \u2026 +${e.hidden} more diff lines`)),s.join(`
|
|
374
|
+
`)}case"link":return e.lines.map(o=>Z(Zs(` \u2B95 ${o}`))).join(`
|
|
375
375
|
`);case"preview":return`
|
|
376
|
-
`+
|
|
376
|
+
`+Qs(`\u25A3 Preview \u2014 ${e.name}`)+`
|
|
377
377
|
|
|
378
|
-
`+
|
|
379
|
-
`+
|
|
380
|
-
`+e.text;case"done":{let o=e.inTokens&&e.inTokens>0?` \xB7 ${
|
|
381
|
-
`+(e.ok?
|
|
378
|
+
`+Ep(e.text,n);case"note":return`
|
|
379
|
+
`+MT[e.tone](Zs(Zl(e.text)));case"block":return`
|
|
380
|
+
`+e.text;case"done":{let o=e.inTokens&&e.inTokens>0?` \xB7 ${$i(e.inTokens)} in${e.cachedPct!=null?` (${e.cachedPct}% cached)`:""}`:"",r=e.activeSeconds!==void 0&&zl(e.activeSeconds,e.seconds)?`${Wn(e.seconds)} elapsed \xB7 ${Wn(e.activeSeconds)} working`:Wn(e.seconds),s=e.costUsd>0?` \xB7 this turn ${Dt(e.costUsd)}`+(e.sessionCostUsd!==void 0&&e.sessionCostUsd>e.costUsd?` \xB7 session ${Dt(e.sessionCostUsd)}`:""):"";return`
|
|
381
|
+
`+(e.ok?Ce.magenta("\u2736 "):Ce.red("\u2736 "))+Ce.gray(`Cooked for ${r} \xB7 ${$i(e.tokens)} tokens out${o}${s}`)}}}function Fk(e,t,n){let o=e.map(i=>Lp(i,t));if(n===void 0||n<=0)return o.join(`
|
|
382
382
|
`);let r=[],s=0;for(let i=o.length-1;i>=0;i--){let a=o[i].split(`
|
|
383
383
|
`).length;if(r.length>0&&s+a>n)break;r.unshift(o[i]),s+=a}return r.join(`
|
|
384
|
-
`)}var
|
|
384
|
+
`)}var Op=3;function _p(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 Mp(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Up(e,t){return t.map(n=>{let o=0;try{o=UT(FT(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function Fp(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:
|
|
385
385
|
- 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.
|
|
386
386
|
- 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.
|
|
387
387
|
- 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.
|
|
388
388
|
- Work only on these files:
|
|
389
389
|
`+e.paths.map(t=>`- ${t}`).join(`
|
|
390
|
-
`)}function
|
|
390
|
+
`)}function Wp(e,t,n){let o=e.reduce((a,l)=>a+l.paths.length,0),[r,s]=t.usd;return[`Convert ${o} article${o===1?"":"s"} to DFM in ${e.length} batch${e.length===1?"":"es"} (\u2264${n} agents at once):`,...e.map(a=>` \u2022 ${a.label} \u2014 ${a.paths.length} article${a.paths.length===1?"":"s"}`),"",`Estimated cost: ${Dt(r)}\u2013${Dt(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function Bp(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),i=e.reduce((C,S)=>C+o(S),0),a=r.reduce((C,S)=>C+o(S),0),l=e.reduce((C,S)=>C+S.costUsd,0),c=e.reduce((C,S)=>C+S.outputTokens,0),p=n==="api"?`${Dt(l)} total`:is(c),m=`${r.length}/${e.length} batch${e.length===1?"":"es"} completed`,$=C=>`${C} article${C===1?"":"s"}`,w=[];if(s.length===0)w.push(`Converted ${$(i)} (${m}) successfully \xB7 ${p}.`);else{w.push(`Converted ${a}/${$(i)} (${m}) \xB7 ${p}.`),w.push(`${s.length} batch${s.length===1?"":"es"} failed \u2014 re-run /convert to retry:`);for(let C of s)w.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return w}async function Wk(e,t){if(!HT(t.cwd))return console.log(L(be)),{kind:"continue"};let{scope:n,run:o}=_p(e),r=VT(t.cwd,t.profileName);if(r.length===0)return console.log(L("No tracked articles in d360-category-map.json. Save some to Document360 first (/push), then /convert.")),{kind:"continue"};let s=Mp(r,n);if(s.length===0)return console.log(L(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let i=BT(s),a=`/convert${n?` --scope ${n}`:""} --run`,{model:l,forced:c}=GT(t.cwd,"light");if(!o){let m=WT({files:Up(t.cwd,s),op:"convert",model:l});n&&console.log(u(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let $ of Wp(i,m,Op))console.log($);return console.log(u(`Model: ${l}${c?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(u(`Run ${a} to start.`)),console.log(""),{kind:"continue"}}console.log(u(`Converting ${s.length} articles in ${i.length} batches (\u2264${Op} agents at once) on ${l}\u2026`)),console.log(u(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let p=Date.now();try{for await(let m of qT({cwd:t.cwd,partitions:i,promptFor:Fp,concurrency:Op,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:l}))if(m.type==="partition_status")m.status==="running"?console.log(u(` \u25B8 ${m.label} \u2014 converting\u2026`)):m.status==="done"?console.log(Q(` \u2713 ${m.label}`)):console.log(L(` \u2717 ${m.label}`));else if(m.type==="run_done"){console.log("");let $=process.env.ANTHROPIC_API_KEY?"api":"subscription",w=ho(m,"The conversion");for(let C of w??Bp(m.results,i,$))console.log(w||!m.ok?F(C):Q(C));console.log(u(kn(zt(p,m.results,m.totalCostUsd))))}}catch(m){console.log(L(`Convert run failed: ${m.message}`))}return console.log(""),{kind:"continue"}}import{statSync as mE}from"node:fs";import{resolve as gE}from"node:path";import{CLAUDE_ACCOUNT_MISMATCH_HINT as yE,estimateBulkCost as wE,lintDocs as kE,planFindingPartitions as bE,planPartitions as $E,readDocsPlan as vE,readProjectConfig as Qp,DEFAULT_DOCS_DIR as tb,resolveModelForOperation as Qk,runPartitioned as Jk,partitionCoverage as Zk,stampArticles as eb,readReviewerNotes as xE,renderNotesForPrompt as RE,readReaderContract as SE,renderGapsForPrompt as CE,notesForPath as PE,CONTENT_CAP_VERSION as AE,WRITER_DIRNAME as Jp}from"document360-engine";ae();import{lintDocs as Gp,guidanceForRules as KT,planFindingPartitions as YT,runPartitioned as zT,partitionCoverage as XT,resolveModelForOperation as QT,stampArticles as JT,applyDeterministicFixes as ZT,isMechanical as eE}from"document360-engine";import{CONTENT_CAP_VERSION as Bk}from"document360-engine";function Hk(e){let t=e.trim().split(/\s+/);return t.includes("--fix")?t[0]==="/review"?"review":t[0]==="/lint"||t[0]==="/check"?"lint":null:null}function Gk(e){return e.trim().split(/\s+/).slice(1).find(t=>!t.startsWith("--"))}function St(e){return e==="review"?{reviewedCap:Bk}:{checkedCap:Bk}}var tc={error:0,warning:1,suggestion:2},tE={error:"\u2717",warning:"\u26A0",suggestion:"\xB7"},nE=10,oE=8,rE=96,qk=34,bn=e=>"ruleId"in e,mo=e=>bn(e)?e.severity:"warning",qp=e=>bn(e)?e.ruleId:e.kind,rr=e=>e.fileLine??e.line;function Bn(e){return e.includes("--blocked")}function Hn(e,t){return Bn(t)?e.filter(n=>mo(n)==="error"):e}function vi(e,t){return`/lint${t?` ${t}`:""}${Bn(e)?" --blocked":""} --fix`}function Hp(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function ec(e){let t={error:0,warning:0,suggestion:0};for(let n of e)t[mo(n)]++;return t}function Vk(e){let t=[];for(let n of["error","warning","suggestion"])e[n]>0&&t.push(`${e[n]} ${n}${e[n]===1?"":"s"}`);return t.join(" \xB7 ")}function xi(e,t={}){let n=t.baselined?[]:e.filter(m=>bn(m)&&m.baselined),o=t.baselined?e:e.filter(m=>!(bn(m)&&m.baselined)),r=n.length>0?[te("\u2139",`${n.length} issue${n.length===1?"":"s"} ${n.length===1?"was":"were"} already in your articles when you chose this style guide, so ${n.length===1?"it never blocks":"they never block"} publishing. /lint --baselined shows ${n.length===1?"it":"them"}.`)]:[];if(o.length===0)return[te("\u2713","No issues found \u2014 no leaked internals, unknown commands, stale version facts, AI-tells, em dashes, or broken callouts in the docs."),...r];let s=new Map;for(let m of o){let $=s.get(m.path)??[];$.push(m),s.set(m.path,$)}let i=ec(o),a=[te("\u26A0",`${o.length} issue${o.length===1?"":"s"} in ${s.size} article${s.size===1?"":"s"} \u2014 ${Vk(i)}.`),""],l=[...s.entries()].sort((m,$)=>{let w=ec(m[1]);return ec($[1]).error-w.error||$[1].length-m[1].length||m[0].localeCompare($[0])}),c=t.full?l:l.slice(0,nE);for(let[m,$]of c){a.push(` ${m} ${u(Vk(ec($)))}`);let w=new Map;for(let R of $){let D=qp(R),W=w.get(D)??[];W.push(R),w.set(D,W)}let C=[...w.entries()].sort((R,D)=>tc[mo(R[1][0])]-tc[mo(D[1][0])]||D[1].length-R[1].length||R[0].localeCompare(D[0])),S=t.full?C:C.slice(0,oE);for(let[R,D]of S){let W=[...D].sort((he,re)=>rr(he)-rr(re)),H=tE[mo(W[0])],G=new Set(W.map(he=>he.term)).size===1?` ${Hp(`"${W[0].term}"`,qk)}`:"",K=W.length>1?u(` \xD7${W.length}`):"",ne=t.full?W[0].message:Hp(W[0].message,rE);a.push(` ${H} ${R}${K}${G}`),a.push(` ${u(ne)}`);let oe=W.map(he=>G?`L${rr(he)}`:`L${rr(he)} ${Hp(`"${he.term}"`,qk)}`),Re=t.full?oe:oe.slice(0,12),le=oe.length-Re.length;a.push(` ${u(Re.join(", ")+(le>0?` \u2026+${le}`:""))}`)}let A=C.length-S.length;A>0&&a.push(u(` \u2026${A} more rule${A===1?"":"s"} fired here (/lint ${m} --full)`)),a.push("")}let p=l.length-c.length;return p>0&&(a.push(u(` \u2026and ${p} more article${p===1?"":"s"} (/lint <category> narrows \xB7 /lint --full lists every one)`)),a.push("")),a.push(...r),a}var sE=200;function nc(e){let n=[...e.filter(l=>!(bn(l)&&l.baselined))].sort((l,c)=>tc[mo(l)]-tc[mo(c)]||l.path.localeCompare(c.path)||rr(l)-rr(c)),o=n.slice(0,sE),r=n.length-o.length,s=new Map;for(let l of o){let c=s.get(l.path)??[];c.push(l),s.set(l.path,c)}let i=[...s.entries()].map(([l,c])=>[l,...c.map(p=>` - L${rr(p)} [${qp(p)}] (${mo(p)}): "${p.term}": ${p.message}`)].join(`
|
|
391
391
|
`)).join(`
|
|
392
|
-
`),a=
|
|
393
|
-
`)}var
|
|
392
|
+
`),a=KT(o.map(l=>({id:qp(l),message:l.message,link:bn(l)?l.link:void 0})));return["The documentation linter found issues in already-written articles. FIX each one by EDITING the","article in place. Do not rewrite whole articles; just resolve the flagged problems. Ground every change","in the actual product source (the authoritativeSourceFiles); never invent.","","Errors are listed first: those are defects of fact or structure, and they matter most.","",...a.length>0?["How to fix, by rule:",...a,""]:[],"Rules: edit ONLY the listed articles; do not touch others; do not publish; introduce no new internal","nouns, invented commands, or wrong facts. When done, every listed issue should be gone.","",...r>0?[`Note: ${r} further finding${r===1?"":"s"} were left out of this batch to keep it actionable. Run /lint --fix again afterwards to pick them up.`,""]:[],"Issues:",i].join(`
|
|
393
|
+
`)}var as=3;function $n(e,t,n){let o=n.filter(a=>!(bn(a)&&a.baselined)),r=Hn(o,t).filter(a=>bn(a)&&eE(a));if(r.length===0)return{fixed:0,skipped:0,lines:[],paths:[]};let s=ZT(e,r),i=[];if(s.fixed.length>0){let a=new Set(s.fixed.map(l=>l.path)).size;i.push(Q(te("\u2713",`Fixed ${s.fixed.length} ${s.fixed.length===1?"issue":"issues"} in ${a} ${a===1?"article":"articles"} \u2014 a straight swap, so no model and no cost.`)))}return s.skipped.length>0&&i.push(u(` ${s.skipped.length} could not be applied automatically (${s.skipped[0].reason}) \u2014 left for the editor pass.`)),{fixed:s.fixed.length,skipped:s.skipped.length,lines:i,paths:s.paths}}function Vp(e,t,n){let o=Hn(n.filter(a=>!(bn(a)&&a.baselined)),t);if(o.length===0)return null;let r=t.find(a=>!a.startsWith("--")),s=vi(t,r),i=YT(o);return i.length<=1?{kind:"single",prompt:nc(o),display:s,findings:o.length}:{kind:"partitioned",partitions:i,display:s,articles:new Set(o.map(a=>a.path)).size,findings:o.length,promptFor:a=>{let l=new Set(a.paths);return nc(o.filter(c=>l.has(c.path)))}}}function Kp(e,t,n){let o=t.find(l=>!l.startsWith("--")),r=o?` in ${o}`:"",s=n.filter(l=>!(bn(l)&&l.baselined)),i=new Set(s.map(l=>l.path)).size;return{lines:Bn(t)?s.length===0?[`\u2713 Nothing is blocking publishing${r} \u2014 no style errors at all.`]:[`\u2713 Nothing is blocking publishing${r}. The ${s.length} issue${s.length===1?"":"s"} left ${s.length===1?"is a warning or a suggestion":"are warnings and suggestions"}, which never block it.`,` /lint${o?` ${o}`:""} --fix clears ${s.length===1?"it":"those"} too \u2014 ${s.length} issue${s.length===1?"":"s"} across ${i} article${i===1?"":"s"}.`]:[`\u2713 Nothing to fix${r} \u2014 the docs are already clean.`],closed:Ze(e,vi(t,o))}}async function iE(e,t,n,o=[]){let{model:r}=QT(e.cwd,"standard");console.log(u(`Fixing ${t.findings} issue${t.findings===1?"":"s"} across ${t.articles} article${t.articles===1?"":"s"} in ${t.partitions.length} batches (\u2264${as} at once) on ${r}\u2026`));let s=[],i=Date.now(),a={aborted:!1,partitions:0,failed:0,notRun:0,producedNothing:!0};try{for await(let m of zT({cwd:e.cwd,partitions:t.partitions,promptFor:t.promptFor,concurrency:as,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:r}))if(m.type==="partition_status")m.status==="running"?console.log(u(` \u25B8 ${m.label} \u2014 fixing\u2026`)):m.status==="done"?console.log(Q(` \u2713 ${m.label}`)):console.log(L(` \u2717 ${m.label}`));else if(m.type==="run_done"){let $=XT(t.partitions,m.results);a={aborted:!!m.aborted,partitions:t.partitions.length,failed:$.failed.length,notRun:$.notRun.length,...m.blocked?{blocked:m.blocked}:{},...m.allEmpty?{allEmpty:!0}:{},...m.bailedEmpty?{bailedEmpty:!0}:{}},console.log(u(kn(zt(i,m.results,m.totalCostUsd)))),$.failed.length&&console.log(F(`\u26A0 ${$.failed.length} batch${$.failed.length===1?"":"es"} not fixed: ${$.failed.map(w=>w.label).join(", ")}`)),$.notRun.length&&console.log(F(`\u26A0 ${$.notRun.length} batch${$.notRun.length===1?"":"es"} never started \u2014 their articles are untouched.`)),m.blocked&&console.log(F(`\u26A0 ${m.blocked}`)),m.allEmpty&&console.log(F("\u26A0 No turn produced any work this run \u2014 nothing was changed.")),!m.allEmpty&&!m.blocked&&s.push(...$.covered)}}catch(m){return console.log(L(`Fix run failed: ${m.message}`)),{kind:"continue"}}if(s.length>0)try{JT(e.cwd,s,St("lint"))}catch{}let l=Gp({cwd:e.cwd,scope:n}).filter(m=>!m.baselined),c=Hn(l,o);console.log("");for(let m of xi(c))console.log(c.length===0?Q(m):F(m));if(ln(a))for(let m of Ze(e.cwd,vi(o,n)))console.log(Q(m));let p=fi({cwd:e.cwd,after:c,before:t.findings,scope:n,blocked:Bn(o)});return console.log(""),console.log(u(p.text)),{kind:"continue",ownNext:!0}}async function Yp(e,t){let n=e.includes("--fix"),o=e.find(a=>!a.startsWith("--")),r=o?` ${o}`:"",s=Gp({cwd:t.cwd,scope:o});if(n){let a=$n(t.cwd,e,s);for(let p of a.lines)console.log(p);let l=a.fixed>0?Gp({cwd:t.cwd,scope:o}):s,c=Vp(t.cwd,e,l);if(!c){let p=Kp(t.cwd,e,l);console.log(Q(p.lines[0]));for(let m of p.lines.slice(1))console.log(u(m));for(let m of p.closed)console.log(Q(m));return{kind:"continue",ownNext:!0}}return c.kind==="partitioned"?iE(t,c,o,e):(console.log(u(`Fixing ${c.findings} doc issue${c.findings===1?"":"s"} (run /lint again after to confirm)\u2026`)),{kind:"forward-to-agent",prompt:c.prompt,display:c.display})}let i=Hn(s,e);console.log(u("Linting the docs (engine internals, unknown commands, stale facts, AI-tells, em dashes, callout shape)\u2026"));for(let a of xi(i,{full:e.includes("--full"),baselined:e.includes("--baselined")}))console.log(i.length===0?Q(a):F(a));return i.length>0&&console.log(u(`Run /lint${r}${Bn(e)?" --blocked":""} --fix to have the agent correct these.`)),console.log(""),{kind:"continue",ownNext:i.length>0}}var Kk=async(e,t)=>{let n=mi("check");return n&&console.log(u(`\u2192 ${n}`)),Yp(e,t)};ae();import{readProjectConfig as aE,loadProfileMap as lE,resolveActiveProfile as cE,desiredCategoryOrder as uE,desiredArticleOrder as dE,DEFAULT_DOCS_DIR as pE}from"document360-engine";var zp=e=>e.replace(/\\/g,"/"),Yk=e=>zp(e).split("/").pop()??e;function Xp(e){let t=Yk(e),n=t.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return n?n.charAt(0).toUpperCase()+n.slice(1):t}var hE=Xp;function Ri(e,t){try{let n=aE(e);if(!n)return[];let o=cE(e,t),r=lE(e,o.name);if(!r)return[];let s=zp(n.docsDir??pE).replace(/\/+$/,""),i=new Map;for(let l of dE(r))i.set(l.categoryPath,(i.get(l.categoryPath)??0)+1);let a=[];for(let l of uE(r)){let c=zp(l.path),p=c.startsWith(`${s}/`)?c.slice(s.length+1):c===s?"":c;p&&a.push({token:p,label:hE(Yk(c)),count:i.get(l.path)??0})}return a}catch{return[]}}function zk(e,t){let n=Ri(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 go(e,t){if(t.includes("--all")||t.includes("--blocked")||t.includes("--stale")||t.some(n=>n.startsWith("--scope="))||t.includes("--scope")&&!Si(t))return!1;for(let n=0;n<t.length;n++){let o=t[n];if(o.startsWith("--")){fE.has(o)&&n++;continue}return!1}return e==="write"?!t.includes("--preview")&&!t.includes("--dry-run"):e==="review"||e==="reorder"}var fE=new Set(["--scope","--concurrency"]);function ls(e,t,n,o,r){if(r=r??Ri(e,o),r.length<=1)return[];let s=n.filter(c=>c.startsWith("--")).join(" "),i=s?` ${s}`:"",a=`/${t}${i} --all`.replace(/\s+/g," "),l=c=>t==="write"?`/write --scope ${c}${i}`:`/${t} ${c}${i}`;return[`Bare /${t} covers the WHOLE knowledge base (${r.reduce((c,p)=>c+p.count,0)} articles). Pick a target:`,` ${a} (everything)`,...r.map(c=>` ${l(c.token)} (${c.label} \xB7 ${c.count} article${c.count===1?"":"s"})`)]}function Si(e){let t=e.indexOf("--scope");if(t===-1)return!1;let n=e[t+1];return n===void 0||n.startsWith("-")}function Xk(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 TE=3,EE=8;function Zp(e){return e===void 0||!Number.isFinite(e)?TE:Math.max(1,Math.min(Math.floor(e),EE))}function Ci(e){let t,n,o=!1,r=!1,s,i=l=>{let c=Number(l);return l!==void 0&&Number.isFinite(c)?c:void 0};for(let l=0;l<e.length;l++){let c=e[l];if(c==="--preview"||c==="--dry-run")o=!0;else if(c==="--rewrite"||c==="--force")r=!0;else{if(c==="--run"||c==="--yes"||c==="--all")continue;c==="--scope"?t=e[++l]:c?.startsWith("--scope=")?t=c.slice(8):c==="--concurrency"?s=i(e[++l]):c?.startsWith("--concurrency=")?s=i(c.slice(14)):c&&!c.startsWith("--")&&(n=c)}}let a=l=>l?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:a(t),path:a(n),preview:o,concurrency:s,rewrite:r}}function NE(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function DE(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function eh(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+=mE(gE(e,i)).size}catch{}return{path:r,bytes:s}})}function th(e,t,n={}){let o=n.rewrite?"- Some or all of these articles ALREADY EXIST on disk \u2014 this is a re-author (rewrite/upgrade), NOT a first draft. For any that exist, do NOT preserve or lightly-edit the current file: RE-AUTHOR it from scratch against the plan + sources + the active doc-type playbook standard. The existing file is what you're replacing, and its structure is NOT the target; match only the project's voice/terminology.\n- PRESERVE REVIEWER ANCHORS. If the existing file contains `:comment[some text]{id=\"\u2026\"}` markers, each one is where a reviewer left a comment. Carry every marker into your new text, wrapping whatever passage now makes the point the old one made, and keep its `id` exactly. Dropping a marker silently detaches that reviewer's comment from the article \u2014 they keep the note and lose the place.\n":"",r=n.reviewerNotes?.trim()?`
|
|
394
394
|
WHAT REVIEWERS HAVE ASKED FOR ON THESE ARTICLES \u2014 apply each one as you write. These are real comments from the people who own these docs, so an article that ignores them will simply come back:
|
|
395
395
|
`+n.reviewerNotes.trim()+`
|
|
396
396
|
`:"",s=n.openGaps?.trim()?`
|
|
@@ -400,7 +400,7 @@ QUESTIONS ALREADY RAISED ABOUT THESE ARTICLES (waiting on a person). Someone has
|
|
|
400
400
|
`+n.readerContract.trim()+`
|
|
401
401
|
|
|
402
402
|
`:"")+`Run the write-article skill to author EACH documentation article listed below. For each path:
|
|
403
|
-
- It is relative to ${t}/. Look up its entry (matching "path") in
|
|
403
|
+
- It is relative to ${t}/. Look up its entry (matching "path") in ${Jp}/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).
|
|
404
404
|
- 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).
|
|
405
405
|
- 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.
|
|
406
406
|
`+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.
|
|
@@ -408,208 +408,209 @@ QUESTIONS ALREADY RAISED ABOUT THESE ARTICLES (waiting on a person). Someone has
|
|
|
408
408
|
- 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.
|
|
409
409
|
Articles:
|
|
410
410
|
`+e.paths.map(a=>`- ${a}`).join(`
|
|
411
|
-
`)+r+s}function yp(e,t,n){let o=e.reduce((i,a)=>i+a.paths.length,0),[r,s]=t.usd;return[`Write ${o} article${o===1?"":"s"} in ${e.length} batch${e.length===1?"":"es"} (\u2264${n} agents at once):`,...e.map(i=>` \u2022 ${i.label} \u2014 ${i.paths.length} article${i.paths.length===1?"":"s"}`),"",`Estimated cost: ${Pt(r)}\u2013${Pt(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function wp(e,t,n,o){let r=S=>t[S.index]?.paths.length??0,s=e.filter(S=>S.ok),i=e.filter(S=>!S.ok),a=e.reduce((S,T)=>S+r(T),0),l=s.reduce((S,T)=>S+r(T),0),c=e.reduce((S,T)=>S+T.costUsd,0),p=e.reduce((S,T)=>S+T.outputTokens,0),m=n==="api"?`${Pt(c)} total`:Vr(p),$=`${s.length}/${e.length} batch${e.length===1?"":"es"} completed`,w=S=>`${S} article${S===1?"":"s"}`,C=[];if(i.length===0){C.push(`Wrote ${w(a)} (${$}) successfully \xB7 ${m}.`);let S=o?` ${o}`:"",T=o?"/push":"/push --all",R=o?`/screenshot author ${o}`:"/screenshot author --all";C.push("Next \u2014 an editorial review, because these were written by an AI:"),C.push(`/review${S} --fix`),C.push(`It reads every article and applies its fixes; ${T} then pushes them up (add screenshots first with ${R} if you want them).`)}else{C.push(`Wrote ${l}/${w(a)} (${$}) \xB7 ${m}.`),C.push(`${i.length} batch${i.length===1?"":"es"} failed \u2014 re-run /write${o?` --scope ${o}`:""} to retry the rest:`);for(let S of i)C.push(` \u2717 ${S.label}${S.error?` \u2014 ${S.error}`:""}`);i.some(S=>/rate-limited/i.test(S.error??""))&&(C.push("Claude rate-limited this run, not your usage allowance. Retry one batch at a time:"),C.push(`/write${o?` --scope ${o}`:""} --concurrency 1`)),i.some(S=>/usage limit has been reached/i.test(S.error??""))&&C.push(WT)}return C}function zo(e,t,n){try{return HT({cwd:e,paths:n.map(o=>`${t}/${o}`)}).filter(o=>!o.baselined)}catch{return[]}}function kp(e){if(e.length===0)return null;let t=new Set(e.map(r=>r.path)).size,n=e.filter(r=>r.severity==="error").length,o=n>0?`${n} of them error${n===1?"":"s"} \u2014 `:"";return`\u26A0 Lint: ${e.length} issue${e.length===1?"":"s"} in ${t} of the new article${t===1?"":"s"} (${o}/lint --fix corrects them).`}function bp(e,t,n,o){if(o.length===0)return{findings:o,lines:[]};let r=mn(e,["--fix"],o);return r.fixed===0?{findings:o,lines:r.lines}:{findings:zo(e,t,n),lines:r.lines}}function $p(e){let t=e.filter(o=>o.severity==="error");if(t.length===0)return null;let n=GT(t);return n.length===0?null:{errors:t,partitions:n,articles:new Set(t.map(o=>o.path)).size,promptFor:o=>{let r=new Set(o.paths);return Nl(t.filter(s=>r.has(s.path)))}}}function vp(e,t){let n=t.filter(r=>r.severity==="error").length,o=t.length-n;return n===0?[`\u2713 Style: all ${e} error${e===1?"":"s"} fixed.${o>0?` ${o} warning${o===1?"":"s"}/suggestion${o===1?"":"s"} remain \u2014 /lint lists them.`:""}`]:[`\u26A0 Style: ${n} of ${e} error${e===1?"":"s"} remain, in ${new Set(t.filter(r=>r.severity==="error").map(r=>r.path)).size} article(s).`," /lint --blocked --fix retries them. Exactly one automatic pass runs, so a loop can never spin here."]}function Dl(e,t,n){let o=(hp(e)?.docsDir??rk).replace(/\/+$/,""),r=t.map(a=>a.path);if(n.path){let a=tA(n.path,o);return r.includes(a)?{docsDir:o,targets:[a],planCount:r.length}:{docsDir:o,targets:[],planCount:r.length,reason:`"${a}" isn't in the docs plan (.d360-writer/plan.json).`}}let s=nA(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=oo(e,o,s);if(i.length===0){let a=n.scope?` under "${n.scope}"`:"",l=n.scope?` --scope ${n.scope}`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${a} are already written. Use /write <path> to rewrite one, or /write${l} --rewrite to regenerate them all.`}}return{docsDir:o,targets:i,planCount:r.length}}function xp(e,t,n){let{targets:o}=Dl(e,t,{rewrite:n?.rewrite}),r=new Map;for(let s of o){let i=s.split("/");if(i.length<2)continue;let a=i[0];r.set(a,(r.get(a)??0)+1)}return[...r].map(([s,i])=>({token:s,label:pp(s),count:i}))}async function sk(e,t){if(!hp(t.cwd))return console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"};if(li(e)){for(let J of Jw(t.cwd,t.profileName))console.log(u(J));return{kind:"continue"}}let n=VT(t.cwd,(hp(t.cwd)?.docsDir??rk).replace(/\/+$/,""));if(n.length===0)return console.log(L("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};if(lo("write",e)){let J=xp(t.cwd,n,{rewrite:ci(e).rewrite}),G=Yr(t.cwd,"write",e,t.profileName,J);if(G.length>0){for(let K of G)console.log(u(K));return{kind:"continue"}}}let{scope:o,path:r,preview:s,concurrency:i,rewrite:a}=ci(e),{docsDir:l,targets:c,reason:p,rewriting:m}=Dl(t.cwd,n,{scope:o,path:r,rewrite:a});if(c.length===0)return console.log(p?W(p):W("Nothing to write.")),{kind:"continue"};m&&console.log(W(`--rewrite: regenerating ${c.length} already-written article${c.length===1?"":"s"} (overwrites them; git has your baseline).`));let $=qT(c),w=fp(i),{model:C,forced:S}=ek(t.cwd,"standard"),T=!!r;if(s&&!T){let J=BT({files:mp(t.cwd,n,c),op:"write",model:C});o&&console.log(u(`Scope: ${o} (${c.length} pending).`));for(let G of yp($,J,w))console.log(G);return console.log(u(`Model: ${C}${S?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(u(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}let R=KT(t.cwd),D=zT(t.cwd),U=c.filter(J=>QT(R,J).length>0).length;U>0&&console.log(u(` ${U} of these ${U===1?"has":"have"} reviewer comments \u2014 the writer gets them.`)),console.log(u(`Writing ${c.length} article${c.length===1?"":"s"} in ${$.length} batch${$.length===1?"":"es"} (\u2264${w} agents at once) on ${C}\u2026`)),console.log(u(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let H=Date.now();try{for await(let J of tk({cwd:t.cwd,partitions:$,promptFor:G=>gp(G,l,{rewrite:m||T,reviewerNotes:YT(R,G.paths),openGaps:XT(t.cwd,G.paths),readerContract:D}),concurrency:w,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:C}))if(J.type==="partition_status")J.status==="running"?console.log(u(` \u25B8 ${J.label} \u2014 writing\u2026`)):J.status==="done"?console.log(Q(` \u2713 ${J.label}`)):console.log(L(` \u2717 ${J.label}`));else if(J.type==="run_done"){console.log("");let G=process.env.ANTHROPIC_API_KEY?"api":"subscription",K=so(J,"The write");if(K){for(let pe of K)console.log(W(pe));continue}for(let pe of wp(J.results,$,G,o??r))console.log(J.ok?Q(pe):W(pe));if(console.log(u(hn(Gt(H,J.results,J.totalCostUsd)))),J.ok)try{ok(t.cwd,c.map(pe=>`${l}/${pe}`),{writtenCap:JT,reviewedCap:0,checkedCap:0})}catch{}let ne=e.includes("--skip-style"),oe=zo(t.cwd,l,c);if(!ne){let pe=bp(t.cwd,l,c,oe);oe=pe.findings;for(let re of pe.lines)console.log(re)}let ve=kp(oe);ve&&console.log(W(ve));let ae=ne?null:$p(oe);if(ae){console.log(u(`Fixing ${ae.errors.length} style error(s) in ${ae.articles} article(s) \u2014 one pass\u2026`));let{model:pe}=ek(t.cwd,"standard"),re=[];try{for await(let be of tk({cwd:t.cwd,partitions:ae.partitions,promptFor:ae.promptFor,concurrency:3,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:pe}))if(be.type==="partition_status"&&be.status!=="running")console.log(be.status==="done"?Q(` \u2713 ${be.label}`):L(` \u2717 ${be.label}`));else if(be.type==="run_done"&&!be.allEmpty&&!be.blocked){let Ae=nk(ae.partitions,be.results);Ae.notRun.length&&console.log(W(`\u26A0 ${Ae.notRun.length} style-fix batch${Ae.notRun.length===1?"":"es"} never started \u2014 their articles are untouched.`)),re.push(...Ae.covered)}}catch(be){console.log(W(`Style fix pass failed: ${be.message}`))}if(re.length>0)try{ok(t.cwd,re,bt("lint"))}catch{}for(let be of vp(ae.errors.length,zo(t.cwd,l,c)))console.log(be.startsWith("\u2713")?Q(be):W(be))}{let pe=nk($,J.results),re={aborted:!!J.aborted,partitions:$.length,failed:pe.failed.length,notRun:pe.notRun.length,leftBehind:zo(t.cwd,l,c).filter(be=>be.severity==="error").length,...J.blocked?{blocked:J.blocked}:{},...J.allEmpty?{allEmpty:!0}:{},...J.bailedEmpty?{bailedEmpty:!0}:{}};if(nn(re)){let be=`/write${o?` --scope ${o}`:""}${e.includes("--rewrite")?" --rewrite":""}`;for(let Ae of Qe(t.cwd,be))console.log(Q(Ae))}}}}catch(J){console.log(L(`Write run failed: ${J.message}`))}return console.log(""),{kind:"continue"}}ue();import{existsSync as oA,readdirSync as ik,statSync as ak}from"node:fs";import{join as lk}from"node:path";import{inputDir as rA,readProjectConfig as sA}from"document360-engine";var ck=/\.(md|markdown|pdf|txt)$/i;function Rp(e){let t=rA(e);if(!oA(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of ik(t)){let s=lk(t,r),i=!1;try{i=ak(s).isDirectory()}catch{continue}if(i){if(r.startsWith("."))continue;let a=iA(s);a>0&&n.push({name:r,docCount:a})}else ck.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function iA(e){let t=0;for(let n of ik(e))try{ak(lk(e,n)).isFile()&&ck.test(n)&&t++}catch{}return t}function Sp(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 jl(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(`
|
|
412
|
-
`)}var
|
|
413
|
-
`)}var
|
|
411
|
+
`)+r+s}function nh(e,t,n){let o=e.reduce((i,a)=>i+a.paths.length,0),[r,s]=t.usd;return[`Write ${o} article${o===1?"":"s"} in ${e.length} batch${e.length===1?"":"es"} (\u2264${n} agents at once):`,...e.map(i=>` \u2022 ${i.label} \u2014 ${i.paths.length} article${i.paths.length===1?"":"s"}`),"",`Estimated cost: ${Dt(r)}\u2013${Dt(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function oh(e,t,n,o){let r=S=>t[S.index]?.paths.length??0,s=e.filter(S=>S.ok),i=e.filter(S=>!S.ok),a=e.reduce((S,A)=>S+r(A),0),l=s.reduce((S,A)=>S+r(A),0),c=e.reduce((S,A)=>S+A.costUsd,0),p=e.reduce((S,A)=>S+A.outputTokens,0),m=n==="api"?`${Dt(c)} total`:is(p),$=`${s.length}/${e.length} batch${e.length===1?"":"es"} completed`,w=S=>`${S} article${S===1?"":"s"}`,C=[];if(i.length===0){C.push(`Wrote ${w(a)} (${$}) successfully \xB7 ${m}.`);let S=o?` ${o}`:"",A=o?"/push":"/push --all",R=o?`/screenshot author ${o}`:"/screenshot author --all";C.push("Next \u2014 an editorial review, because these were written by an AI:"),C.push(`/review${S} --fix`),C.push(`It reads every article and applies its fixes; ${A} then pushes them up (add screenshots first with ${R} if you want them).`)}else{C.push(`Wrote ${l}/${w(a)} (${$}) \xB7 ${m}.`),C.push(`${i.length} batch${i.length===1?"":"es"} failed \u2014 re-run /write${o?` --scope ${o}`:""} to retry the rest:`);for(let S of i)C.push(` \u2717 ${S.label}${S.error?` \u2014 ${S.error}`:""}`);i.some(S=>/rate-limited/i.test(S.error??""))&&(C.push("Claude rate-limited this run, not your usage allowance. Retry one batch at a time:"),C.push(`/write${o?` --scope ${o}`:""} --concurrency 1`)),i.some(S=>/usage limit has been reached/i.test(S.error??""))&&C.push(yE)}return C}function sr(e,t,n){try{return kE({cwd:e,paths:n.map(o=>`${t}/${o}`)}).filter(o=>!o.baselined)}catch{return[]}}function rh(e){if(e.length===0)return null;let t=new Set(e.map(r=>r.path)).size,n=e.filter(r=>r.severity==="error").length,o=n>0?`${n} of them error${n===1?"":"s"} \u2014 `:"";return`\u26A0 Lint: ${e.length} issue${e.length===1?"":"s"} in ${t} of the new article${t===1?"":"s"} (${o}/lint --fix corrects them).`}function sh(e,t,n,o){if(o.length===0)return{findings:o,lines:[]};let r=$n(e,["--fix"],o);return r.fixed===0?{findings:o,lines:r.lines}:{findings:sr(e,t,n),lines:r.lines}}function ih(e){let t=e.filter(o=>o.severity==="error");if(t.length===0)return null;let n=bE(t);return n.length===0?null:{errors:t,partitions:n,articles:new Set(t.map(o=>o.path)).size,promptFor:o=>{let r=new Set(o.paths);return nc(t.filter(s=>r.has(s.path)))}}}function ah(e,t){let n=t.filter(r=>r.severity==="error").length,o=t.length-n;return n===0?[`\u2713 Style: all ${e} error${e===1?"":"s"} fixed.${o>0?` ${o} warning${o===1?"":"s"}/suggestion${o===1?"":"s"} remain \u2014 /lint lists them.`:""}`]:[`\u26A0 Style: ${n} of ${e} error${e===1?"":"s"} remain, in ${new Set(t.filter(r=>r.severity==="error").map(r=>r.path)).size} article(s).`," /lint --blocked --fix retries them. Exactly one automatic pass runs, so a loop can never spin here."]}function oc(e,t,n){let o=(Qp(e)?.docsDir??tb).replace(/\/+$/,""),r=t.map(a=>a.path);if(n.path){let a=NE(n.path,o);return r.includes(a)?{docsDir:o,targets:[a],planCount:r.length}:{docsDir:o,targets:[],planCount:r.length,reason:`"${a}" isn't in the docs plan (${Jp}/plan.json).`}}let s=DE(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=uo(e,o,s);if(i.length===0){let a=n.scope?` under "${n.scope}"`:"",l=n.scope?` --scope ${n.scope}`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${a} are already written. Use /write <path> to rewrite one, or /write${l} --rewrite to regenerate them all.`}}return{docsDir:o,targets:i,planCount:r.length}}function lh(e,t,n){let{targets:o}=oc(e,t,{rewrite:n?.rewrite}),r=new Map;for(let s of o){let i=s.split("/");if(i.length<2)continue;let a=i[0];r.set(a,(r.get(a)??0)+1)}return[...r].map(([s,i])=>({token:s,label:Xp(s),count:i}))}async function nb(e,t){if(!Qp(t.cwd))return console.log(L(be)),{kind:"continue"};if(Si(e)){for(let J of zk(t.cwd,t.profileName))console.log(u(J));return{kind:"continue"}}let n=vE(t.cwd,(Qp(t.cwd)?.docsDir??tb).replace(/\/+$/,""));if(n.length===0)return console.log(L(`No docs plan found (${Jp}/plan.json). Analyze the repo and propose a structure first.`)),{kind:"continue"};if(go("write",e)){let J=lh(t.cwd,n,{rewrite:Ci(e).rewrite}),G=ls(t.cwd,"write",e,t.profileName,J);if(G.length>0){for(let K of G)console.log(u(K));return{kind:"continue"}}}let{scope:o,path:r,preview:s,concurrency:i,rewrite:a}=Ci(e),{docsDir:l,targets:c,reason:p,rewriting:m}=oc(t.cwd,n,{scope:o,path:r,rewrite:a});if(c.length===0)return console.log(p?F(p):F("Nothing to write.")),{kind:"continue"};m&&console.log(F(`--rewrite: regenerating ${c.length} already-written article${c.length===1?"":"s"} (overwrites them; git has your baseline).`));let $=$E(c),w=Zp(i),{model:C,forced:S}=Qk(t.cwd,"standard"),A=!!r;if(s&&!A){let J=wE({files:eh(t.cwd,n,c),op:"write",model:C});o&&console.log(u(`Scope: ${o} (${c.length} pending).`));for(let G of nh($,J,w))console.log(G);return console.log(u(`Model: ${C}${S?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(u(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}let R=xE(t.cwd),D=SE(t.cwd),W=c.filter(J=>PE(R,J).length>0).length;W>0&&console.log(u(` ${W} of these ${W===1?"has":"have"} reviewer comments \u2014 the writer gets them.`)),console.log(u(`Writing ${c.length} article${c.length===1?"":"s"} in ${$.length} batch${$.length===1?"":"es"} (\u2264${w} agents at once) on ${C}\u2026`)),console.log(u(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));let H=Date.now();try{for await(let J of Jk({cwd:t.cwd,partitions:$,promptFor:G=>th(G,l,{rewrite:m||A,reviewerNotes:RE(R,G.paths),openGaps:CE(t.cwd,G.paths),readerContract:D}),concurrency:w,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:C}))if(J.type==="partition_status")J.status==="running"?console.log(u(` \u25B8 ${J.label} \u2014 writing\u2026`)):J.status==="done"?console.log(Q(` \u2713 ${J.label}`)):console.log(L(` \u2717 ${J.label}`));else if(J.type==="run_done"){console.log("");let G=process.env.ANTHROPIC_API_KEY?"api":"subscription",K=ho(J,"The write");if(K){for(let he of K)console.log(F(he));continue}for(let he of oh(J.results,$,G,o??r))console.log(J.ok?Q(he):F(he));if(console.log(u(kn(zt(H,J.results,J.totalCostUsd)))),J.ok)try{eb(t.cwd,c.map(he=>`${l}/${he}`),{writtenCap:AE,reviewedCap:0,checkedCap:0})}catch{}let ne=e.includes("--skip-style"),oe=sr(t.cwd,l,c);if(!ne){let he=sh(t.cwd,l,c,oe);oe=he.findings;for(let re of he.lines)console.log(re)}let Re=rh(oe);Re&&console.log(F(Re));let le=ne?null:ih(oe);if(le){console.log(u(`Fixing ${le.errors.length} style error(s) in ${le.articles} article(s) \u2014 one pass\u2026`));let{model:he}=Qk(t.cwd,"standard"),re=[];try{for await(let ve of Jk({cwd:t.cwd,partitions:le.partitions,promptFor:le.promptFor,concurrency:3,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:he}))if(ve.type==="partition_status"&&ve.status!=="running")console.log(ve.status==="done"?Q(` \u2713 ${ve.label}`):L(` \u2717 ${ve.label}`));else if(ve.type==="run_done"&&!ve.allEmpty&&!ve.blocked){let Ne=Zk(le.partitions,ve.results);Ne.notRun.length&&console.log(F(`\u26A0 ${Ne.notRun.length} style-fix batch${Ne.notRun.length===1?"":"es"} never started \u2014 their articles are untouched.`)),re.push(...Ne.covered)}}catch(ve){console.log(F(`Style fix pass failed: ${ve.message}`))}if(re.length>0)try{eb(t.cwd,re,St("lint"))}catch{}for(let ve of ah(le.errors.length,sr(t.cwd,l,c)))console.log(ve.startsWith("\u2713")?Q(ve):F(ve))}{let he=Zk($,J.results),re={aborted:!!J.aborted,partitions:$.length,failed:he.failed.length,notRun:he.notRun.length,leftBehind:sr(t.cwd,l,c).filter(ve=>ve.severity==="error").length,...J.blocked?{blocked:J.blocked}:{},...J.allEmpty?{allEmpty:!0}:{},...J.bailedEmpty?{bailedEmpty:!0}:{}};if(ln(re)){let ve=`/write${o?` --scope ${o}`:""}${e.includes("--rewrite")?" --rewrite":""}`;for(let Ne of Ze(t.cwd,ve))console.log(Q(Ne))}}}}catch(J){console.log(L(`Write run failed: ${J.message}`))}return console.log(""),{kind:"continue"}}ae();import{existsSync as jE,readdirSync as ob,statSync as rb}from"node:fs";import{join as sb}from"node:path";import{inputDir as IE,readProjectConfig as LE,WRITER_DIRNAME as cs}from"document360-engine";var ib=/\.(md|markdown|pdf|txt)$/i;function ch(e){let t=IE(e);if(!jE(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of ob(t)){let s=sb(t,r),i=!1;try{i=rb(s).isDirectory()}catch{continue}if(i){if(r.startsWith("."))continue;let a=OE(s);a>0&&n.push({name:r,docCount:a})}else ib.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function OE(e){let t=0;for(let n of ob(e))try{rb(sb(e,n)).isFile()&&ib.test(n)&&t++}catch{}return t}function uh(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 rc(e,t){return["Run the draft-from-prd skill.","",`Target scope: ${e?`the feature documents in ${cs}/input/${e}/`:t?`the input docs in ${cs}/input/ relevant to: "${t}"`:`the input docs in ${cs}/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",`${cs}/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(`
|
|
412
|
+
`)}var dh=`No input docs found. Drop this feature's PRDs/specs in ${cs}/input/<feature>/ (.md or .pdf), then run /draft.`;async function ab(e,t){let n=t?.cwd??process.cwd();if(!LE(n))return console.log(L(be)),{kind:"continue"};let{features:o,looseDocs:r}=ch(n);if(o.length===0&&r===0)return console.log(u(dh)),{kind:"continue"};let s=e.join(" ").trim();if(!s){if(o.length>1){console.log(u(`Multiple features in ${cs}/input/ \u2014 draft which one? Run: /draft <feature>`));for(let l of o)console.log(` ${l.name} ${u(`(${l.docCount} doc${l.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let a=o[0]?.name??"";return{kind:"forward-to-agent",prompt:rc(a),display:a?`/draft ${a}`:"/draft"}}let i=uh(o,s);return{kind:"forward-to-agent",prompt:rc(i??"",i?void 0:s),display:`/draft ${s}`}}ae();import{listOpenForDocs as _E,readProjectConfig as ME}from"document360-engine";function ph(e){try{return _E(e).filter(t=>t.kind==="request").length}catch{return 0}}function hh(e){let t=e.includes("--push")||e.includes("--publish"),n=e.includes(Vt),o=e.filter(r=>!r.startsWith("--")).join(" ").trim();return{push:t,skipReview:n,what:o}}function fh(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(`
|
|
413
|
+
`)}var mh="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 lb(e,t){let n=t?.cwd??process.cwd();if(!ME(n))return console.log(L(be)),{kind:"continue"};let{push:o,what:r}=hh(e);if(!r&&ph(n)===0)return console.log(u(mh)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --push":""}`;return{kind:"forward-to-agent",prompt:fh(r),display:s}}ae();import{search as UE}from"@inquirer/prompts";import{findByName as FE,getSession as WE,listSessions as BE,relativeTime as ub}from"document360-engine";async function db(e,t){let n=BE(t.cwd).filter(o=>o.uuid!==t.currentUuid());if(n.length===0)return console.log(u("No saved sessions for this repo yet \u2014 sessions auto-save as you work.")),{kind:"continue"};if(e.length>0){let o=e.join(" "),r=FE(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(L(`No session matches "${o}".`)),cb(n),{kind:"continue"})}if(!process.stdin.isTTY)return cb(n),console.log(u("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>UE({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let i=(s??"").toLowerCase();return n.filter(a=>!i||a.name.toLowerCase().includes(i)||a.firstPrompt.toLowerCase().includes(i)).map(a=>({name:`${a.name} ${ub(a.updatedAt)}`,value:a.uuid,description:a.firstPrompt.slice(0,100)}))}})),r=WE(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function cb(e){console.log("");for(let t of e.slice(0,15))console.log(` ${Z(t.name)} ${u(ub(t.updatedAt))}`),console.log(` ${u(t.firstPrompt.slice(0,80))}`);console.log("")}ae();import{renameSession as HE}from"document360-engine";function gh(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 pb(e,t){let n=gh(e.join(" "));if(!n)return console.log(L("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(HE(o,n)?console.log(Q(`\u2713 Session renamed to "${n}"`)):console.log(L("Could not find the current session record.")),{kind:"continue"}):(t.setPendingName(n),console.log(Q(`\u2713 Session will be named "${n}" once it starts.`)),{kind:"continue"})}ae();import{select as GE}from"@inquirer/prompts";import{readProjectConfig as qE,readUserConfig as hb,resolveModelSetting as yh,writeUserConfig as fb,WRITER_DIRNAME as mb,HOME_DIRNAME as VE}from"document360-engine";var Xt=[{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 sc(e){if(e.source==="auto")return 0;let t=e.model.toLowerCase(),n=Xt.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function KE(e){switch(e.source){case"project":return`${mb}/config.json defaultModel (team setting)`;case"user":return`~/${VE}/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 Pi(e,t){let n=()=>yh(e).model;if(t==="default"){let s=hb();return s.defaultModel?(delete s.defaultModel,fb(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${yh(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}}fb({...hb(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=qE(e)?.defaultModel;return r&&o.push(`\u26A0 ${mb}/config.json sets defaultModel "${r}" \u2014 the team setting overrides yours until it is removed.`),{lines:o,changed:!0,effective:n()}}async function gb(e,t){let n=e[0]?.trim();if(!n){let i=yh(t.cwd);if(!process.stdin.isTTY)return console.log(`${rt("Model:")} ${Z(i.model)}${i.source==="auto"?u(" (auto)"):""}`),console.log(u(` source: ${KE(i)}`)),console.log(u(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let a=sc(i),l;try{l=await t.withPausedInput(()=>GE({message:`Select model (current: ${i.model}${i.source==="auto"?" \xB7 auto":""})`,default:Xt[a].value,choices:Xt.map(($,w)=>({name:`${$.label}${w===a?" \u2714":""}`,value:$.value,description:$.desc}))}))}catch{return console.log(u("Cancelled.")),{kind:"continue"}}let{lines:c,changed:p,effective:m}=Pi(t.cwd,l??"default");for(let $ of c)console.log($.startsWith("\u26A0")?F($):$.startsWith("\u2713")?Q($):u($));return p&&await t.setModel(m),{kind:"continue"}}let{lines:o,changed:r,effective:s}=Pi(t.cwd,n);for(let i of o)console.log(i.startsWith("\u26A0")?F(i):i.startsWith("\u2713")?Q(i):u(i));return r&&await t.setModel(s),{kind:"continue"}}lc();async function vb(e,t){return await t.withPausedInput(()=>Wr(t.cwd)),{kind:"clear"}}async function xb(e,t){return await t.withPausedInput(()=>Ma(t.cwd,t.profileName)),{kind:"clear"}}ae();import{resolveActiveProfile as RN}from"document360-engine";async function Rb(e,t){let n=!1;try{n=RN(t.cwd).production}catch{}return n?(console.log(F("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(u("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}ae();var Sb=async(e,t)=>{try{await t.withPausedInput(()=>Fa({}))}catch(n){if(console.log(L(`Login failed: ${n.message}`)),!cl(t.cwd,t.profileName))return console.log(u("Your Document360 session still isn't working \u2014 run /login to try again.")),{kind:"continue",ownNext:!0}}return{kind:"continue"}};mn();ae();import{resolveActiveProfile as SN,clearTokens as CN,clearProfileProject as PN,listStoredSessions as AN,tokensProjectId as TN}from"document360-engine";async function Cb(e,t){let n,o,r,s;try{let m=SN(t.cwd,t.profileName);n=m.name,o=m.connection.name,r=m.project.projectId,s=m.project.projectName}catch(m){return console.log(L(m.message)),{kind:"continue"}}let i=e.includes("--all-projects"),a=AN(n).filter(m=>{let $=TN(m);return!!$&&$!==r}).length,l=CN(n,i?void 0:r);PN(t.cwd,n);let c=i||a===0?"":` Your sign-in for ${a} other project${a===1?"":"s"} is untouched (/logout --all-projects clears those too).`;console.log(l?i?Q(`\u2713 Signed out of every Document360 project for "${n}" and cleared this repo's project/workspace selection.`):Q(`\u2713 Signed out of ${s?`"${s}"`:`"${n}"`} and cleared its project/workspace selection.${c}`):u(`Profile "${n}" was not signed in. Cleared any project/workspace selection.${c}`)),console.log(u(`Run /login to sign back in to "${n}" (the ${o} environment) and pick a project.`));let p=Ve(t.cwd,t.profileName);return console.log(p?F(`\u26A0 ${p.why}. Signing out doesn\u2019t change the environment \u2014 ${p.cmd} does.`):u(" Different environment? That comes from the profile, not the login \u2014 /profile add <environment>.")),{kind:"continue"}}import{existsSync as Tb,readFileSync as $h}from"node:fs";import{homedir as UN}from"node:os";import{basename as FN,join as ji}from"node:path";import{readProjectConfig as WN,DEFAULT_OUTPUT_DIR as BN,existingAnnotatedShotPath as BG,resolveOutputDir as HN,shotArtifacts as GN,writerDir as vh,WRITER_DIRNAME as Di,CAPTURE_HOME_DIRNAME as qN,CAPTURE_COMMAND as cc,CAPTURE_PACKAGE as Eb}from"document360-engine";import jt from"picocolors";import{annotationsPath as EN,resolveOutputDir as NN,readProjectConfig as DN,DEFAULT_OUTPUT_DIR as jN,existingAnnotatedShotPath as IN}from"document360-engine";function LN(e){let n=e.filter(o=>o!=="--all"&&o!=="-a").find(o=>!o.startsWith("-"));return n?{mode:"single",id:n}:{mode:"all"}}function Ei(e){return e.filter(t=>t.state==="annotated").map(t=>t.id)}function vn(e,t){let n=NN(e,DN(e)?.outputDir??jN),o=new Map(Ke(e).map(i=>[i.id,i])),r=i=>i.replace(`${e}\\`,"").replace(`${e}/`,"").replace(/\\/g,"/"),s=t.map(i=>{let a=o.get(i)?.file??"(unknown article)";return[`- ${i}`,` image: ${r(IN(n,i))}`,` facts: ${r(EN(n,i))}`,` article: ${a}`].join(`
|
|
414
414
|
`)}).join(`
|
|
415
415
|
`);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(`
|
|
416
|
-
`)}function
|
|
417
|
-
${
|
|
418
|
-
`)}function
|
|
419
|
-
`):
|
|
420
|
-
`)}var
|
|
421
|
-
`)}function
|
|
422
|
-
/screenshot list --detail shows what each one needs`}function
|
|
423
|
-
`),cmd:o.length>0?`/screenshot ${l}`:r.length>0?p:t.length>0?i:a,tone:o.length>0||r.length>0?"warn":"info"}}function
|
|
424
|
-
Check them when you're ready: ${
|
|
425
|
-
`),display:"/screenshot checklist"}}function
|
|
426
|
-
`)}async function
|
|
427
|
-
`).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 Ul(e,t){let n=Qk(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=WE(e);if(!o)return[{tone:"info",text:"Sharing: unavailable \u2014 this folder is not a git repository."}];if(!o.upstream)return[{tone:"warn",text:V("\u26A0")+`This branch (${o.branch??"detached"}) has no remote, so your work can't reach your team yet.`},{tone:"info",text:"Ask your builder to run: git push -u origin HEAD"}];let r=n.push===!0?"on":n.push==="unconfirmed"?"not set up yet":"off",s=[{tone:"info",text:`Sharing: ${o.branch} \u2192 ${o.upstream} \xB7 saving: on \xB7 sending: ${r}`}];return o.ahead>0?s.push({tone:"warn",text:V("\u26A0")+`${o.ahead} change${wi(o.ahead)} not shared yet \u2014 run /share`}):s.push({tone:"ok",text:V("\u2713")+"Everything is shared with your team."}),s}function eh(e,t,n){Xk({...t,gitHandoff:{commit:n,push:n}},e);let o=n?{tone:"ok",text:V("\u2713")+"Sharing on \u2014 d360-writer will save and send its own work from now on."}:{tone:"ok",text:V("\u2713")+"Sharing off \u2014 d360-writer will leave its work for your coding agent to commit."};return n?[o,...Ul(e,{...t,gitHandoff:{commit:!0,push:!0}})]:[o]}async function Wl(e,t){let n=[],o=Qk(t);if(!o.commit)return{lines:[{tone:"info",text:uo("disabled")}],changed:!1};let r=t;o.push==="unconfirmed"&&BE(e,t)&&(r={...t,gitHandoff:{commit:!0,push:!0}},Xk(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 UE(e);if(s.ok&&s.pulled>0){let c=[s.newHints>0?`${s.newHints} new hint${wi(s.newHints)}`:null,s.newMessages>0?`${s.newMessages} new message${wi(s.newMessages)}`:null].filter(Boolean);n.push({tone:"ok",text:V("\u2B07")+`Got your builder's latest${c.length?` \u2014 ${c.join(", ")}`:""}.`})}else!s.ok&&s.reason!=="no-upstream"&&s.reason!=="no-git"&&n.push({tone:"warn",text:V("\u26A0")+uo(s.reason,s.detail)});let i=await FE(e,r);if(i.commit&&!i.commit.ok)return n.push({tone:"warn",text:V("\u26A0")+uo(i.commit.reason,i.commit.detail)}),{lines:n,changed:!1};let a=i.commit?.ok?i.commit.committed.length:0;if(a>0&&n.push({tone:"ok",text:V("\u2713")+`Saved ${a} change${wi(a)} to the docs folder.`}),i.push&&!i.push.ok)return n.push({tone:"warn",text:V("\u26A0")+uo(i.push.reason,i.push.detail)}),{lines:n,changed:a>0};let l=i.push?.ok?i.push.pushed:0;return l>0?n.push({tone:"ok",text:V("\u2B06")+`Shared ${l} change set${wi(l)} with your team.`}):a===0&&(s.ok&&s.pulled===0)?n.push({tone:"ok",text:V("\u2713")+"Everything is already shared with your team."}):a>0&&!i.push&&n.push({tone:"info",text:"Saved on this machine only. /share on lets d360-writer send it to your team too."}),{lines:n,changed:a>0||l>0||s.ok&&s.pulled>0}}var HE={ok:Q,info:De,warn:W,error:L};async function Jk(e,t){let n=t.cwd,o=ME(n);if(!o)return console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase(),s=a=>{for(let l of a)console.log(HE[l.tone](l.text))};if(r==="status")return s(Ul(n,o)),{kind:"continue"};if(r==="on"||r==="off")return s(eh(n,o,r==="on")),{kind:"continue"};if(r)return console.log(L(`Unknown option "${r}". Use /share, /share status, /share on, or /share off.`)),{kind:"continue"};console.log(u("Exchanging work with your team\u2026"));let{lines:i}=await Wl(n,o);return s(i),{kind:"continue"}}function rn(e){let t=0,n=0,o=0,r=0,s=0,i=0;try{let l=tb(e,Zk(e));t=l.actionable.length,n=l.held.length,o=l.held.filter(c=>c.asked).length}catch{}try{let l=GE(e);r=l.filter(c=>c.kind==="request").length,s=l.filter(c=>c.kind==="answer").length}catch{}try{i=qE(e).length}catch{}let a=!1;try{a=nN(e)}catch{}return{hints:t,requests:r,answers:s,directives:i,held:n,heldAsked:o,briefMoved:a}}async function nh(e){let t=eb(e);if(!t)return[];if(!JE(e,t))return[];let n=await QE(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 ${uo(n.reason,n.detail)}`}]}function Jr(e){let t=[];e.hints&&t.push(`${e.hints} hint${e.hints===1?"":"s"}`),e.requests&&t.push(`${e.requests} request${e.requests===1?"":"s"}`),e.answers&&t.push(`${e.answers} answer${e.answers===1?"":"s"}`),e.directives&&t.push(`${e.directives} directive${e.directives===1?"":"s"}`);let n=t.join(", ");return e.briefMoved?n?`${n} and an updated product brief`:"an updated product brief":n||null}function oh(e){let t=Jr(e);return t?`Catching up on ${t}\u2026`:"Nothing queued from your builder \u2014 checking Document360 for reviewer comments and feedback\u2026"}function Hl(e){let t={...e.queued,briefMoved:!1},n=Jr(t);if(n)return{tone:"warn",note:`${V("\u26A0")}That run finished without writing anything, and ${n} ${t.hints+t.requests+t.answers+t.directives===1?"is":"are"} still queued \u2014 nothing was lost.`,lead:{cmd:"/catch-up",reason:"the queue is untouched, so running it again picks up the same work"}};if(e.queued.held>0){let o=e.queued.held;return{tone:"info",note:`${V("\u2139")}Nothing to write yet \u2014 your builder's ${o} note${yn(o)} ${o===1?"is":"are"} waiting on code that isn't finished. ${o===1?"It stays":"They stay"} queued.`,lead:null}}return e.hold?{tone:"info",note:`${V("\u2139")}No articles changed \u2014 product discovery is still open, so new overview and concept pages are on hold.`,lead:null}:{tone:"info",note:`${V("\u2713")}Nothing needed writing \u2014 no articles changed.`,lead:null}}function rh(e){return{push:e.includes("--push")||e.includes("--publish"),skipReview:e.includes(Wt),includeUnfinished:e.includes(Gl)}}var Gl="--include-unfinished";function ki(e){let t={hold:!1,openQuestions:0,answersPending:0};try{let n=ZE(e);return!n||n.status==="confident"?t:{hold:!0,...eN(e)}}catch{return t}}function sh(e){if(!e.hold)return[];let t="I'll update the reference pages, and hold new overview and concept pages";if(e.answersPending>0){let n=e.answersPending;return[{tone:"info",text:`${V("\u2139")}Product discovery is still open \u2014 ${n} answer${yn(n)} just arrived from your builder.`},{tone:"info",text:` I'll fold ${n===1?"it":"those"} in first; if that settles the brief, everything gets written as normal.`}]}if(e.openQuestions>0){let n=e.openQuestions;return[{tone:"warn",text:`${V("\u26A0")}Product discovery isn't finished \u2014 ${n} question${yn(n)} still with your builder.`},{tone:"warn",text:` ${t} until the brief is settled.`}]}return[{tone:"warn",text:`${V("\u26A0")}Product discovery isn't finished \u2014 the product brief is still a draft.`},{tone:"warn",text:` ${t} until it's settled (/discover continues it).`}]}function ih(e){try{return tb(e,Zk(e)).held}catch{return[]}}function ah(e,t){let n=0;for(let o of t)try{tN(e,{hintFile:o.file,surface:o.surface,sources:o.unfinished})&&(n+=1)}catch{}return n}var th=3;function lh(e,t){if(e.length===0)return[];let n=e.length,o=[];if(e.every(r=>r.unfinished.length===0))return o.push({tone:"warn",text:`${V("\u26A0")}Your repository is in the middle of a merge, so the code isn't settled yet.`}),o.push({tone:"warn",text:` I've left your builder's ${n} note${yn(n)} for now. Finish the merge and I'll pick ${n===1?"it":"them"} up.`}),o;o.push({tone:"warn",text:`${V("\u26A0")}${n} of your builder's note${yn(n)} describe${n===1?"s":""} code that isn't finished, so I've left ${n===1?"its page":"those pages"} for now:`});for(let r of e.slice(0,th))o.push({tone:"warn",text:` \xB7 ${r.surface||r.file}`});return n>th&&o.push({tone:"warn",text:` \xB7 and ${n-th} more`}),o.push({tone:"info",text:t>0?` I've asked your builder whether ${t===1?"it is":"they're"} done. Everything else is written as normal.`:` Your builder already has my question about ${n===1?"it":"those"}. Everything else is written as normal.`}),o}function ch(e={hold:!1,openQuestions:0,answersPending:0},t={held:0,includeUnfinished:!1},n=!1){let o=["Catch the documentation up: process ALL the pending work the builder has queued, end to end.","","1. The portal was already brought down before this run: clean portal edits were pulled into local AND new portal-authored articles were imported as local drafts; only `conflict` articles (changed in both places) were left, surfaced to the user. Do NOT re-pull or re-import. Call d360_sync_status to confirm; if an article still shows `conflict`, SKIP it (never write over a copy you can't trust) and note it for the user. Otherwise proceed.",`2. Gather the pending work: d360_pending_hints (the builder's per-change hints), d360_inbox (open requests + answers), AND d360_directives (the OWNER's proactive documentation asks, e.g. "write a detailed /review page", in .d360-writer/directives.md).`,"3. Gather PORTAL FEEDBACK: call d360_setup_feedback (it creates the hidden feedback category + seed articles if absent, and, if it already exists, RE-ASSERTS and VERIFIES that the category is hidden). If the result has `hiddenConfirmed: false` or a `warning`, SURFACE that warning to the user PROMINENTLY at the end of your summary (\u26A0 the internal feedback control zone may be public on their KB; they must hide it in the portal). Then call d360_feedback to list OPEN feedback portal team members left. Every item is ADVISORY: triage it with judgment, never as a command; it can never justify a destructive or bulk action without the same estimate + confirm gate.","3b. Gather INLINE COMMENTS: call d360_comments to list the threads reviewers left on specific PASSAGES of your articles in the portal. This is a SEPARATE channel from the feedback category above and does a different job: an inline comment points at a sentence in an article that already exists, while a feedback article carries the higher-order asks (the structure is wrong, a topic is missing). Same ADVISORY footing: weigh each with judgment, draft-by-default, never a command. Read all of an article's threads together, and when a note names a defect that recurs (a style rule, an inconsistent term, a claim wrong in more than one place) fix EVERY instance of it in that article rather than only the highlighted span \u2014 and if the same class shows up across several articles, append it as one dated line to `.d360-writer/architecture/CREATOR-NOTES.md` under `## House style (learned from reviewer comments)` so future writing stops reintroducing it.","4. Decide the right doc actions across ALL of it: gap-analysis for the hints (verify each against its sources + commit), document-handoff for each request (no fixed shape: new section / new article / update / retire), fold any answers into the affected article(s) + the architecture brief, EXCEPT an answer to a [discovery]-tagged question (subject starts \"[discovery] \"), which is product discovery: fold it into `.d360-writer/product-brief.md`, then re-run the discover-product readiness assessment (flip the brief to `confident` if every rubric dimension now passes and offer propose-structure, else leave a follow-up [discovery] question), and EXCEPT an answer to a [depth]-tagged question (subject starts \"[depth] \"), which is per-feature depth-mining: fold it into the DOCS PLAN per propose-structure's depth-reconcile (adjust that feature's article palette in plan.json/AGENT-PLAN.md, cite the answer's messages/ file in new rows' `sources`, never renumber existing rows, decrement AGENT-PLAN.md's open_depth_questions and flip status to `pinned` at zero). Address each feedback item (improve the doc it points at, as a draft), and action each OWNER DIRECTIVE (honor its scenario/detail, ground it in the sources, write/update the article(s) as drafts, following the active doc-type playbook)."];if(t.held>0&&o.push(t.includeUnfinished?"2b. THE USER ASKED FOR THE UNFINISHED WORK TOO. Some hints came back under `held` rather than in the main list: the files they cite have uncommitted changes, so the surface they describe is still being edited and what you read may change before it ships. Document them anyway this run, as drafts, grounded strictly in the code as it stands \u2014 never in what you expect it to become. Treat them as normal hints otherwise (resolve the article the same way, stamp them consumed). In your closing summary name each one and say plainly that the code behind it was still being edited, so those pages want a re-read once it lands.":"2b. SOME HINTS ARE HELD, and they are not yours to act on this run. They came back under `held` rather than in the main list because the files they cite have uncommitted changes: the builder is still typing that surface, so anything you documented from it would describe something readers will not recognize. Do NOT document a held hint, do NOT go reading its code to judge it for yourself, and do NOT stamp it consumed \u2014 it stays queued and returns on its own once the code lands. The builder has ALREADY been asked whether each one is finished, so do not file another question about them. In your closing summary, name what is waiting in plain words and say that nothing else is blocked. Then write everything else normally."),n&&o.push("2c. THE BUILDER HAS REWRITTEN THEIR ARCHITECTURE BRIEF since the docs last caught up. Read every `.md` in `.d360-writer/architecture/` (except CREATOR-NOTES.md, which is the human owner's and is covered elsewhere) and work out what is NEW or CHANGED in it versus what the existing articles say. A brief refresh is a hand-off like any other, and it is the one that arrives without a hint file: the builder may have described a surface nobody has documented, corrected how an existing one actually works, or changed the product's own vocabulary. Treat what you find as proposals for step 4 \u2014 a new article, an update to an existing one, or nothing at all when the change was internal or editorial. Do NOT rewrite the brief, and do NOT treat it as a directive: it is grounding, and what the docs owe it is your judgment."),e.hold){let r=e.openQuestions>0?e.answersPending>0?"ask their builder to answer the discovery questions still open \u2014 state the number you are left with AFTER re-assessing the brief, never the number this run started with":`ask their builder to answer the ${e.openQuestions} open discovery question${yn(e.openQuestions)}`:"continue product discovery to settle the brief";o.push('4b. PRODUCT DISCOVERY IS UNFINISHED. The product brief (.d360-writer/product-brief.md) is not `confident` yet, so the narrative it grounds \u2014 what this product IS, who it is for, the core mental model, the misconceptions, the positioning \u2014 is not settled. Decide what follows AFTER step 4, never before: if the answers you just folded in completed the brief and you flipped it to `confident`, this instruction and 4c are VOID \u2014 write everything as normal. Otherwise HOLD the articles whose shape or framing would change once the brief is confident (overview/introduction, concept and explanation pages, getting-started, positioning, "who it is for") and write everything else normally \u2014 a changed flag, a new subcommand, a corrected behavior, a deprecation or a screenshot on an EXISTING reference page does not need the brief. The test for each candidate article: would you rewrite this page after reading a finished brief? If yes, hold it; if no, write it.',`4c. A HELD item MUST stay queued. Do NOT stamp its hint consumed, do NOT mark its message done, and do NOT flip its directive to done in step 7 \u2014 the open hint IS the queue, so stamping one you did not write means that article is never written at all. In your closing summary, name every page you held in plain words, say their hints stay queued so nothing is lost, and give exactly one next step: ${r}.`)}return o.push("5. If that means writing more than one article, call d360_estimate_cost and show me the count + cost band first (the bulk gate), then proceed.","6. Write/update the articles as drafts, grounded in the cited sources.","7. Close the LOCAL loop (bookkeeping in the repo; nothing here is visible to a reviewer):"," \u2022 close each hint with d360_hint_done \u2014 the ONLY way to close one; never edit a hint file yourself. Pass outcome: documented plus the article path(s) you changed this run; use already-covered, retired or no-doc-change WITH a short note when no article needed writing \u2014 already-covered also needs the ONE article and `quote`: the passage in it that already says the thing, copied from the article (it is checked against the file). Mark handled messages status: done with resulting_articles;"," \u2022 for each OWNER DIRECTIVE you actioned: call d360_directive_done with its exact title + the article path(s) you wrote (flips it to [done] in .d360-writer/directives.md);"," \u2022 reconcile the DOCS ROADMAP (d360_roadmap): flip any campaign step this run completed (d360_roadmap_done), including a step whose work you can verify an EARLIER session already completed but left unstamped, and append a step (d360_roadmap_add, with its run: command) for real new campaign work this run revealed; never delete existing steps;"," \u2022 for the Creator-notes feedback item (is_creator_notes:true): do NOT reply in it; fold its content into `.d360-writer/architecture/CREATOR-NOTES.md` as an appended, dated `## From portal Creator notes (<date>)` section (preserve every existing note + human edit), then call d360_feedback_done for it.","8. Push the drafts to Document360.","9. Cross-link second pass: any article you wrote that links to ANOTHER article in this same batch had that inline link degrade to plain text (its target had no live URL yet when the source was written). Now that every target exists, re-update the affected articles so those inline links resolve to live URLs; only the ones that had such forward references need it. (The structured Related Articles sidebars are already two-way linked; this is just inline body links.)","10. NOW answer the people who asked, AFTER the push (steps 8-9), never before. A reviewer reads your reply in the portal and then looks at the article to check it, so replying first promises a change they cannot see. For anything whose push failed, do NOT reply on it; leave it outstanding and report it."," \u2022 for each INLINE COMMENT you actioned: call d360_comment_respond with its comment_id + article_id and a `reply` saying in plain words what you changed \u2014 in the reviewer's terms, mentioning where you applied the same fix more widely. Do NOT pass `resolve`: replying is your job, closing the thread is theirs, and they can only decide it is settled after seeing the change (your answer is recorded either way, so it will not come back at you). NEVER edit the reviewer's own comment text;"," \u2022 for each portal feedback item you actioned: append a short note at the BOTTOM of that feedback article via d360_update_article: `**d360-writer response:** \u2713 actioned in <article> (<date>)` (or `declined: <reason>`), NEVER overwriting the person's own text, then call d360_feedback_done(article_id, resulting_articles)."),o.push("Leave everything as DRAFTS for review; do not publish live. Publishing is a separate, reviewed step: articles you write here have not been read by an editor yet, so making them visible to readers is never part of this run. Tell the user what is waiting as a draft.",'Do NOT end with slash commands or a "what to do next" line. The tool prints the next step itself, scoped to what this run changed, and a second suggestion from you competes with it (yours will be the broader, more expensive one, because you cannot see how much was touched). Report what you did and stop.'),o.push("","End with a one-line-per-item summary of what you wrote/updated, and anything you couldn't ground (say plainly that you left a question for their engineers). Write the whole summary for a technical writer: no tool names, no internal file names, no raw status words, no hint ids, just plain sentences about what changed and what is worth their attention."),o.join(`
|
|
428
|
-
`)}var
|
|
429
|
-
(Document360 sends the first 500 characters of a highlight)`:`\u201C${n}\u201D`;let o=n.slice(0,
|
|
430
|
-
(+${r} more character${r===1?"":"s"}${e.comment.commented_text_truncated?", and Document360 caps a highlight at 500":""})`}function
|
|
431
|
-
`)]});return o.push(
|
|
432
|
-
`)}function
|
|
433
|
-
`)}async function
|
|
434
|
-
${s()}`.trim(),packages:n})),a.on("close",l=>i({ok:l===0,output:l===0?"":s(),packages:n})),e||a.unref()}catch(a){i({ok:!1,output:String(a),packages:n})}})}var
|
|
435
|
-
`).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function
|
|
436
|
-
|
|
437
|
-
`;
|
|
438
|
-
`,"utf8");let C=wn(e)??{projectId:""};return Zl({...C,styleGuide:{...C.styleGuide,pulledFrom:{styleGuideId:a.id,name:a.name??a.id,pulledAt:new Date().toISOString(),contentHash:SD("sha1").update($).digest("hex").slice(0,16)}}},e),{lines:[te("\u2713",`Pulled "${a.name??a.id}" into .d360-writer/style-guide.md (${$.length.toLocaleString()} characters).`),...m,u(" This is PROSE, not rules \u2014 /review judges against it, and the writer now writes to it."),u(" Turn its mechanical parts into checks: /style-guide compile"),u(" Restarting the agent so it writes to the new guide\u2026")],restart:!0}}function ND(e){let t=Pi(e).rules.filter(n=>n.pack.toLowerCase()===Si.toLowerCase()).map(n=>n.id);return{prompt:hD({guide:fD(e),packName:Si,existingRuleIds:t}),display:"/style-guide compile"}}function DD(e){let t=yD(e),n=Ah(t)?$b(t,"utf8").trim():"";return!n||!/^## /m.test(n)?{kind:"nothing",lines:[te("\u2139","No reviewer comments have been read yet, so there is nothing to learn from."),u(" Reviewers comment on your drafts in Document360; /comments reads them, and every read"),u(" keeps a copy in .d360-writer/reviewer-notes.md. Run /comments first.")]}:{kind:"run",prompt:gD({notes:n,existingRules:mD(e),houseRulesFile:".d360-writer/house-rules.md"}),display:"/style-guide learn"}}function xb(){return[u(" Read what it wrote: git diff .d360-writer/house-rules.md"),u(" These rules apply from now on \u2014 the writer follows them and /review judges against them."),u(" Disagree with one? Delete the line. It is your file, and nothing regenerates it."),u(" Restarting the agent so it writes to the new rules\u2026")]}function Rb(){return[u(` Review what it wrote: git diff .d360-writer/styles/${Si}/`),u(` Anything it could not check mechanically is listed in .d360-writer/styles/${Si}/UNCHECKABLE.md \u2014 /review judges those.`),u(` Turn them on when you are happy: /style-guide use ${Si.toLowerCase()} (they start as warnings, never blocking)`)]}var Fe=(e,t)=>`${e} ${t}${e===1?"":"s"}`,Ch=e=>/^v\d/i.test(e)?e:`v${e}`;function jD(e){let t=(e.description??`${e.name} style guide`).trim().replace(/\s+/g," "),n=/^(.{0,72})(?:[.,:;—]|$)/.exec(t)?.[1]?.replace(/[.,:;—\s]+$/,"").trim();if(n&&n.length>0)return n;let o=t.slice(0,72),r=o.lastIndexOf(" ");return`${r>20?o.slice(0,r):o}\u2026`}function Sb(e){let t={error:0,warning:0,suggestion:0};for(let n of e)t[n.severity]=(t[n.severity]??0)+1;return["error","warning","suggestion"].filter(n=>t[n]>0).map(n=>`${t[n]} ${n}`).join(" \xB7 ")}function ID(e){let n=wn(e)?.styleGuide?.pulledFrom;return n?`.d360-writer/style-guide.md \u2014 pulled ${n.pulledAt.slice(0,10)} from "${n.name}"`:Ah(kb(e))?".d360-writer/style-guide.md (yours)":"the built-in default"}function LD(e){let t=wn(e),n=Pi(e),o=(t?.styleGuide?.packs??[]).filter(Boolean),r=n.packs.filter(c=>c.name.toLowerCase()===Mn),s=n.packs.filter(c=>{let p=c.name.toLowerCase();return p!==Mn&&p!=="d360"}),i=t?.styleGuide?.packs===void 0&&s.length>0,a=[`Style guide: ${ID(e)}`,`Rule packs: ${s.length>0?s.map(c=>`${c.name.toLowerCase()} ${Ch(c.version)}`).join(", ")+(i?u(" (the default \u2014 nobody has chosen yet)"):""):u("none chosen")}`,`Always on: ${u(`d360 (correctness, built in \u2014 ${Fe(es.filter(c=>c.id.startsWith("D360.")).length,"rule")})`)}`];for(let c of r)a.push(` ${u(`${c.name.toLowerCase()} ${Ch(c.version)} (anti-slop \u2014 ${Fe(c.ruleCount,"rule")})`)}`);r.length>0&&(a.push(u(" Every article here is machine-written, so these cannot be switched off by")),a.push(u(" choosing another pack. styleGuide.humanise: false turns them off deliberately.")));let l=[...es.map(c=>({severity:c.severity})),...n.rules.map(c=>({severity:c.severity}))];a.push("",`${Fe(l.length,"rule")} active \xB7 ${Sb(l)}`);try{let c=Ci({cwd:e}),p=c.findings.filter($=>!$.baselined),m=p.filter($=>$.severity==="error").length;a.push(""),a.push(m===0?te("\u2713",`No style errors across the docs${p.length>0?`, though ${Fe(p.length,"other issue")} ${p.length===1?"is":"are"} reported`:""}.`):te("\u2717",`${Fe(m,"style error")} \u2014 /lint --blocked shows them, /lint --blocked --fix corrects them.`)),c.baselinedCount>0&&a.push(te("\u2139",`${Fe(c.baselinedCount,"issue")} ${c.baselinedCount===1?"was":"were"} already in your articles when this style guide was chosen, so ${c.baselinedCount===1?"it never blocks":"they never block"} publishing.`)),c.ruleErrors.length>0&&a.push(te("\u26A0",`${Fe(c.ruleErrors.length,"rule")} could not be loaded: ${c.ruleErrors.slice(0,2).map($=>`${$.ruleId} (${$.reason})`).join("; ")}`));for(let $ of c.ruleWarnings.slice(0,2))a.push(te("\u26A0",$.reason))}catch{}return a.push(""),a.push(u(" See them all: /style-guide list \xB7 change: /style-guide use \xB7 one rule: /style-guide explain <rule>")),bb(wn(e)?.styleGuide)&&(a.push(""),a.push("A guide built for software documentation is installed, and these docs are not on it:"),a.push(` Move to it /style-guide use ${Th}`),a.push(" Stay as you are /style-guide keep"),a.push(u(" Several rules in a general-prose guide are wrong for software documentation. This one was")),a.push(u(" measured on real knowledge bases, rule by rule, and nothing in it can block a publish."))),Eh(e)&&(a.push(""),a.push("Nobody has settled this yet, and it is a decision \u2014 nothing above changed anything:"),a.push(" Happy with these rules? /style-guide keep"),a.push(" Want a stricter standard? /style-guide use microsoft (or google)"),a.push(u(" Worth settling now rather than later: it shapes every article written from here, and")),a.push(u(" changing it once a knowledge base exists means going back over what is already written."))),a}function Cb(e){let t=wn(e),n=new Set(Ph(t?.styleGuide)),o=Rh(e),r=new Map;for(let a of o)for(let l of a.rules){if(!l.tunedBy)continue;let c=l.id.slice(0,l.id.lastIndexOf(".")).toLowerCase();r.set(c,[...r.get(c)??[],l])}let s=["Rule packs you can turn on:",""],i=Math.max(12,...o.map(a=>a.name.length));for(let a of o){let l=a.name.toLowerCase(),c=n.has(l),p=l===Mn,m=c?"\u2713":"\xB7",$=p?u("(always on)"):c?u("(active)"):"",w=a.local?u(" [yours]"):"",C=a.rules.filter(R=>!R.tunedBy),S=a.rules.filter(R=>R.tunedBy);s.push(` ${m} ${l.padEnd(i)}${w} ${a.description??""}`),s.push(` ${u(`${Fe(C.length,"rule")} \xB7 ${Sb(C)} \xB7 ${Ch(a.version)}`)} ${$}`),S.length>0&&s.push(` ${u(`${Fe(S.length,"rule")} here tune${S.length===1?"s":""} another pack: ${S.map(R=>R.id).join(", ")}`)}`);let T=r.get(l)??[];T.length>0&&s.push(` ${u(`${Fe(T.length,"rule")} tuned by ${[...new Set(T.map(R=>R.tunedBy.pack.toLowerCase()))].join(", ")}`)}`),a.errors.length>0&&s.push(te("\u26A0",`${Fe(a.errors.length,"rule")} in this pack could not be loaded \u2014 /style-guide explain names them.`))}return o.every(a=>a.name.toLowerCase()===Mn)&&(s.push(""),s.push(u(" The Microsoft and Google style guides are not installed in this build yet."))),s.push(""),s.push(u(" Turn one on: /style-guide use <name> (this replaces the chosen set, it does not add to it)")),s.push(u(" Several: /style-guide use microsoft,google")),s.push(u(" Back to none: /style-guide use none")),s}function OD(e,t){if(!t)return[te("\u26A0","Name a rule: /style-guide explain Humanise.EmDash")];let n=Pi(e),o=es.find(p=>p.id.toLowerCase()===t.toLowerCase()),r=n.rules.find(p=>p.id.toLowerCase()===t.toLowerCase())??n.rules.find(p=>p.tunedBy?.localId.toLowerCase()===t.toLowerCase());if(!o&&!r){let p=n.errors.find($=>$.ruleId.toLowerCase()===t.toLowerCase());if(p)return[te("\u26A0",`${p.ruleId} could not be loaded.`),u(` ${p.reason}`),...p.file?[u(` Edit .d360-writer/styles/${p.file}`)]:[]];let m=[...es.map($=>$.id),...n.rules.map($=>$.id),...n.errors.map($=>$.ruleId)].filter($=>$.toLowerCase().includes(t.toLowerCase())).slice(0,5);return[te("\u26A0",`No active rule called "${t}".`),...m.length>0?[u(` Did you mean: ${m.join(", ")}`)]:[u(" /style-guide list shows the active packs.")]]}let s=o?.id??r.id,i=o?.severity??r.severity,a=r?.tunedBy,l=o?"built in (correctness \u2014 always on)":`pack: ${r.pack.toLowerCase()}`,c=[`${s} ${i} \xB7 ${l}${a?" \xB7 tuned by you":""}`,""];if(c.push(` ${o?.summary??r.message}`),r?.link&&c.push(u(` ${r.link}`)),r?.degraded&&(c.push(""),c.push(te("\u26A0",`This rule is translated approximately: ${r.degraded}. It may match slightly more than the original does.`))),a&&r?.tuning){let p=r.tuning;c.push(""),c.push(u(` Ours ${r.pack.toLowerCase()}, declared ${r.declaredSeverity}`)),c.push(u(` Your tweak .d360-writer/styles/${a.file}`));for(let m of p.added)c.push(u(` + ${m.key.padEnd(9)} ${m.values.join(", ")}`));for(let m of p.removed)c.push(u(` - ${m.key.padEnd(9)} ${m.values.join(", ")}`));for(let m of p.restated)c.push(u(` ${m.padEnd(9)} restated`));for(let m of p.alreadyPresent)c.push(u(` ${m.key.padEnd(9)} ${m.values.join(", ")} \u2014 already in the rule, kept once`))}a&&r?.check.kind==="existence"&&(c.push(""),c.push(u(` Pattern ${r.check.re.source}`)));try{let p=Ci({cwd:e}).findings.filter($=>$.ruleId===s),m=p.filter($=>!$.baselined);c.push(""),c.push(p.length===0?" Currently: no findings.":` Currently: ${Fe(m.length,"finding")}${p.length!==m.length?`, plus ${p.length-m.length} baselined and hidden`:""}.`)}catch{}return c.push(""),o?(c.push(u(" Built-in checks are grounded in your product's own source and cannot be switched off \u2014 they")),c.push(u(" catch defects of fact, not matters of taste."))):(c.push(i==="error"?u(' This one BLOCKS publishing \u2014 your config sets it to "error" deliberately.'):a&&r?.declaredSeverity==="error"?u(" Tuning a rule makes it a warning, so it no longer blocks publishing."):u(" Style rules never block publishing. Fix it when you want to; it will not hold a page back.")),i!=="error"&&a&&r?.declaredSeverity==="error"&&c.push(u(` Put the block back: add "${s}": "error" to styleGuide.rules in .d360-writer/config.json`)),c.push(u(` Silence it everywhere: add "${s}": "off" to styleGuide.rules in .d360-writer/config.json`)),i!=="error"&&c.push(u(" Silence one passage: <!-- vale "+s+" = NO --> \u2026 <!-- vale "+s+" = YES -->"))),c}function Nh(e,t){let n=(t??"").trim();if(!n){let w=Rh(e).filter(R=>R.name.toLowerCase()!==Mn),C=new Set(Ph(wn(e)?.styleGuide).map(R=>R.toLowerCase())),S=R=>R.toLowerCase()===Th?0:1,T=w.sort((R,D)=>S(R.name)-S(D.name)||R.name.localeCompare(D.name)).map(R=>({cmd:`/style-guide use ${R.name.toLowerCase()}`,desc:`${jD(R)} \u2014 ${R.rules.length} rules${C.has(R.name.toLowerCase())?" (active now)":""}`}));return{lines:[],restart:!1,pick:{title:"Which writing rules should these docs follow?",lead:"Pick below. Whichever you choose, every article here is held to it \u2014 nothing stays exempt.",options:[...T,{cmd:"/style-guide use none",desc:"the built-in checks only \u2014 correctness and anti-slop"}]}}}let o=n.toLowerCase()==="none"?[]:n.split(/[,\s]+/).map(w=>w.trim().toLowerCase()).filter(Boolean),r=new Map(Rh(e).map(w=>[w.name.toLowerCase(),w])),s=o.filter(w=>!r.has(w));if(s.length>0)return{lines:[te("\u2717",`No rule pack named ${s.map(w=>`"${w}"`).join(", ")}.`),"",...Cb(e)],restart:!1};let i=wn(e)??{projectId:""},{declinedUpgrade:a,...l}=i.styleGuide??{},c=(i.styleGuide?.packs??[]).map(w=>w.trim().toLowerCase()).filter(Boolean);Zl({...i,styleGuide:{...l,packs:o,decidedAt:new Date().toISOString()}},e),wb();let p=[te("\u2192",`Switching to: ${o.length>0?o.join(", "):"the built-in checks only"}${o.includes(Mn)?"":` (+ ${Mn}, always on)`}\u2026`)],m,$=[];try{let w=aD(e),C=w?Object.values(w.entries).reduce((R,D)=>R+D.count,0):0;if(w){try{Sh(`${cD(e)}.bak`,JSON.stringify(w,null,2),"utf8")}catch{}lD(e)}let S=Ci({cwd:e}),T=new Set(S.findings.map(R=>R.path)).size;if(S.findings.length===0)p.push(te("\u2713",T===0?"No articles yet \u2014 everything you write from here is held to the full set.":"Your articles are already clean against these rules."));else{p.push(te("\u26A0","Every article is held to the new rules. Nothing stays exempt."),"",u(` ${Fe(S.findings.length,"finding")} across ${Fe(T,"article")} ${S.findings.length===1?"is":"are"} now live.`)),C>0&&(p.push(u(` ${Fe(C,"finding")} accepted under your previous guide ${C===1?"is":"are"} not carried over.`)),p.push(u(" Your previous record is at .d360-writer/style-baseline.json.bak"))),p.push(""),p.push(te("\u2713","Nothing blocks publishing \u2014 no style-pack rule can."));let R=mn(e,["--fix"],S.findings);R.lines.length>0&&p.push("",...R.lines);let D=R.fixed>0?Ci({cwd:e}):S,U=D.findings.length,H=new Set(D.findings.map(J=>J.path)).size;U===0?p.push(te("\u2713","That was all of them \u2014 your articles now match the new guide.")):m={findings:U,articles:H,cmd:"/review --all --fix",...R.fixed>0?{outOf:S.findings.length}:{}},$=[...new Set(D.findings.map(J=>J.path))]}uD(e,{packs:o,from:c,articlesWithFindings:$})}catch(w){p.push(te("\u26A0",`The packs are active, but reading your articles failed: ${w instanceof Error?w.message:String(w)}`)),p.push(u(" Run /lint to see the current state before publishing."))}return p.push(...vb(e,`/style-guide use ${n}`)),p.push(u(" Restarting the agent so it writes to the new rules\u2026")),{lines:p,restart:!0,...m?{editorial:m}:{}}}function _D(e){return[e.title,u(` ${e.lead}`),"",...e.options.map(t=>` ${t.cmd}`.padEnd(38)+u(t.desc))]}function Dh(e){let t=e.outOf?`${e.findings} of the ${e.outOf} findings`:Fe(e.findings,"finding");return[te("\u2192",`${t} across ${Fe(e.articles,"article")} ${e.findings===1?"needs":"need"} a read, not a swap.`),u(` ${e.cmd} reads each one and rewrites it. Nothing is blocking your publishing in the meantime.`)]}function MD(e,t){let n=(t??"").trim().toLowerCase()==="skip",o=pD(e);if(!o)return[te("\u2713","No sweep is owed \u2014 your articles have been read against the guide they follow.")];let r=o.packs.length>0?o.packs.join(", "):"the built-in checks";if(n)return dD(e),[te("\u2713",`Fine \u2014 I won't raise the ${r} sweep again.`),"",u(` ${Fe(o.pending,"article")} still ${o.pending===1?"has":"have"} not been read against it.`),u(" /review --all --fix does the sweep whenever you want it.")];let s=o.total-o.pending;return[te("\u2192",`${o.pending} of your ${Fe(o.total,"article")} still ${o.pending===1?"needs":"need"} a read against ${r}.`),"",...s>0?[u(` ${s} read so far.`)]:[],u(" /review --all --fix reads the rest and rewrites them."),u(" /style-guide sweep skip stops me raising it.")]}async function ec(e,t){let{sub:n,value:o}=ts(e),r=s=>{for(let i of s)console.log(i);console.log("")};switch(n){case"list":return r(Cb(t.cwd)),{kind:"continue"};case"explain":return r(OD(t.cwd,o)),{kind:"continue"};case"triage":return r(PD(t.cwd)),{kind:"continue"};case"off":case"on":return r(CD(t.cwd,o,n==="off")),{kind:"continue"};case"use":{let s=Nh(t.cwd,o);return r(s.pick?_D(s.pick):s.lines),s.editorial&&r(Dh(s.editorial)),s.restart?{kind:"clear"}:{kind:"continue"}}case"keep":return r(AD(t.cwd)),{kind:"continue"};case"sweep":return r(MD(t.cwd,o)),{kind:"continue"};case"pull":{let s=await ED(t.cwd,o,t.profileName);return r(s.lines),s.restart?{kind:"clear"}:{kind:"continue"}}case"compile":{let s=ND(t.cwd);return{kind:"forward-to-agent",prompt:s.prompt,display:s.display}}case"learn":{let s=DD(t.cwd);return s.kind==="nothing"?(r(s.lines),{kind:"continue"}):{kind:"forward-to-agent",prompt:s.prompt,display:s.display}}default:return r(LD(t.cwd)),{kind:"continue"}}}ue();import{lintDocs as nc,loadStyleGuide as Ob,buildReviewPrompt as _b,buildStructureReviewPrompt as i1,structureReviewDue as a1,structureFingerprint as l1,recordStructureReview as c1,hasCaptureArtifacts as Mb,readProjectConfig as Fh,DEFAULT_DOCS_DIR as Uh,listArticleFiles as nr,normalizeScope as u1,planPartitions as d1,runPartitioned as Fb,partitionCoverage as p1,resolveModelForOperation as Ub,stampArticles as h1,snapshotArticles as f1,reviewStalePaths as m1,readReviewerNotes as Wb,renderNotesForPrompt as Bb,readDocsPlan as g1,CONTENT_CAP_VERSION as Mh}from"document360-engine";import{articlesChangedSince as FD,isUnadoptedArticle as UD,docsRootOf as WD}from"document360-engine";function er(e,t,n,o){let r=t.map(c=>c.replace(/\\/g,"/"));if(!n)return{changed:[],earned:r,unadopted:[]};let s=[];try{s=FD(e,n).map(c=>c.replace(/\\/g,"/"))}catch{return{changed:[],earned:r,unadopted:[]}}let i=new Set(s),a=r.filter(c=>!i.has(c)&&UD(e,c,o)),l=new Set(a);return{changed:s.filter(c=>r.includes(c)),earned:r.filter(c=>!l.has(c)),unadopted:a}}function BD(e,t){let n=t.replace(/\\/g,"/");try{let o=WD(e).replace(/\\/g,"/").replace(/\/+$/,"");return o&&n.startsWith(`${o}/`)?n.slice(o.length+1):n}catch{return n}}function ns(e,t,n){if(t.length===0)return null;let o=t.length===1,r=[];r.push(o?`\u26A0 The editor changed nothing in ${BD(e,t[0])}, so it is not recorded as reviewed.`:`\u26A0 The editor changed nothing in ${t.length} pages, so they are not recorded as reviewed.`),r.push(o?" Nothing here has adopted this page: it came from Document360, it is not in your docs plan, and":" Nothing here has adopted them: they came from Document360, they are not in your docs plan, and"),r.push(o?" nothing records what it was written from. There was nothing for an editor to check it against.":" nothing records what they were written from. There was nothing for an editor to check them against.");for(let i of t)r.push(`/untrack ${i}`);r.push(o?" That disowns it \u2014 the page, its history and its comments stay on Document360, readers see no":" That disowns one \u2014 the page, its history and its comments stay on Document360, readers see no"),r.push(" change, and the markdown is kept. Nothing is deleted.");let s=n.lead&&o?{text:r.join(`
|
|
439
|
-
`),cmd:`/untrack ${t[0]}`}:null;return{lines:r,cta:s}}function
|
|
440
|
-
`),w=
|
|
441
|
-
`);return
|
|
442
|
-
`),readerContract:
|
|
443
|
-
`),display:`/reorder${n?` ${n}`:""}`}}async function
|
|
416
|
+
`)}function yo(e){return`${V("\u2192",jt.blue)}Verifying ${e} new screenshot${e===1?"":"s"} (reading each image)\u2026`}var ON=(e,t=88)=>{let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n};function us(e,t){if(t.length===0)return[];let n=Fn(e).shots,o=[],r=[],s=[];for(let a of t){let l=n[a]?.review;l?l.verdict==="ok"?o.push(a):r.push({id:a,reason:l.reason??"no reason recorded",repaired:!!l.repaired}):s.push(a)}let i=[""];if(i.push(`${V("\u2714",jt.green)}${jt.green(`${o.length} verified`)}`+(r.length>0?` ${jt.magenta(`\u2691 ${r.length} flagged`)}`:"")+(s.length>0?` ${jt.yellow(`? ${s.length} not verified`)}`:"")+jt.gray(` ${t.length} shot${t.length===1?"":"s"} in this pass`)),r.length>0){let a=Math.max(...r.map(c=>c.id.length));for(let c of r)i.push(` ${jt.magenta(c.id.padEnd(a))} ${jt.gray(ON(c.reason))}`);let l=r.filter(c=>c.repaired).length;i.push(`${V("\u2192",jt.magenta)}Re-capture the ${r.length} flagged: ${jt.bold("/screenshot capture --failed")}`+(l<r.length?jt.gray(` (${r.length-l} still need${r.length-l===1?"s":""} a spec fix first)`):""))}return s.length>0&&i.push(`${V("\u26A0",jt.yellow)}No verdict recorded for ${s.slice(0,3).join(", ")}${s.length>3?`, +${s.length-3}`:""} \u2014 still awaiting verification. Run ${jt.bold("/screenshot verify")} again.`),i}async function Pb(e,t){let n=t?.cwd??process.cwd(),o=Xo(n);o&&console.log(o);let r=Ke(n),s=LN(e);if(s.mode==="single"){let a=r.find(l=>l.id===s.id);return a?a.state==="captured"?(console.log(`"${s.id}" has been taken but the callouts aren't drawn on yet \u2014 /screenshot annotate ${s.id} finishes it.`),{kind:"continue"}):["annotated","verified","rejected"].includes(a.state)?{kind:"forward-to-agent",prompt:vn(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=Ei(r);if(i.length===0){let a=r.filter(p=>p.state==="verified").length,l=r.filter(p=>p.state==="rejected").length,c=r.filter(p=>p.state==="captured").length;return console.log(c>0?`${c} shot${c===1?" is":"s are"} taken but not drawn on yet \u2014 /screenshot annotate finishes ${c===1?"it":"them"}, then there'll be something to verify.`:l>0?`Nothing left to verify. ${l} shot${l===1?"":"s"} failed verification \u2014 re-capture with: /screenshot capture --failed`:a>0?`All ${a} captured shot${a===1?" is":"s are"} already verified.`:"No captured screenshots to verify yet \u2014 /screenshot capture takes the shots first."),{kind:"continue"}}return{kind:"forward-to-agent",prompt:vn(n,i),display:"/screenshot verify"}}import{spawn as Ab}from"node:child_process";import{CAPTURE_COMMAND as _N}from"document360-engine";var bh=_N;function MN(e,t){if(t&&typeof e.pid=="number")try{process.kill(-e.pid,"SIGTERM");return}catch{}try{e.kill()}catch{}}function Ni(e){let t=process.platform==="win32",n=!t&&e.stdio==="pipe";return new Promise((o,r)=>{let s=t?Ab(`${bh} ${e.args.join(" ")}`,{cwd:e.cwd,shell:!0,stdio:e.stdio==="inherit"?"inherit":["ignore","pipe","pipe"],env:{...process.env,NO_UPDATE_NOTIFIER:"1"}}):Ab(bh,e.args,{cwd:e.cwd,shell:!1,detached:e.stdio==="pipe",stdio:e.stdio==="inherit"?"inherit":["ignore","pipe","pipe"],env:{...process.env,NO_UPDATE_NOTIFIER:"1"}}),i="";e.stdio==="pipe"&&(s.stdout?.on("data",l=>{i+=l.toString()}),s.stderr?.on("data",l=>{i+=l.toString()}));let a=()=>MN(s,n);e.signal?.addEventListener("abort",a,{once:!0}),s.on("error",l=>{if(e.signal?.removeEventListener("abort",a),l.code==="ENOENT"){o({exitCode:127,output:`${i}
|
|
417
|
+
${bh}: command not found`.trim()});return}r(l)}),s.on("close",l=>{e.signal?.removeEventListener("abort",a),o({exitCode:l??1,output:i})})})}var VN=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function xh(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:VN(t),retryBlocked:n}:{mode:"single",id:t}:{mode:"picker"}}function Li(e,t){let n=Ke(e,t),o=r=>n.filter(s=>s.state===r).map(s=>s.id);return{ready:o("spec"),captured:[...o("captured"),...o("annotated"),...o("verified"),...o("rejected")].sort(),blocked:o("blocked"),broken:o("broken"),rejected:o("rejected"),rows:n}}function Nb(e){let t=e.filter(s=>s.state==="spec"),n=e.filter(s=>s.state==="annotated"||s.state==="verified"),o=[],r=t.filter(s=>!s.mutates);r.length>1&&o.push({kind:"all",action:"capture",label:`Capture all ${r.length} ready specs`,ids:r.map(s=>s.id),depth:0}),Xr(o,t,"capture"),qd(o,e.filter(s=>s.state==="blocked"),e.filter(s=>s.state==="broken"),e.filter(s=>s.state==="rejected"));for(let s of[...n].sort((i,a)=>i.id.localeCompare(a.id))){let i=s.state==="verified"?" \u2714 verified \u2014 re-capture":" \u25C8 to verify \u2014 re-capture";o.push({kind:"shot",action:"capture",label:s.id,ids:[s.id],depth:1,note:i})}return o}function Rh(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([...Ky(e).filter(r=>n.has(r)),...o])].sort()}function Sh(e,t){let n=e.length;if(n===0)return null;let o=li(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(`
|
|
418
|
+
`)}function KN(e,t){let n=WN(e)?.outputDir??BN;return GN(HN(e,n),t)}function Ch(e,t,n,o){let r=KN(e,t);return(r.annotationsMtimeMs??0)>=o&&r.rawMtimeMs!==void 0?"captured":n===0?"skipped":"failed"}function Db(e){let t=/⊘[^\n—]*—\s*(.+)/.exec(e);return t?t[1].trim():null}var YN=/element is not (?:enabled|visible|stable|editable)|intercepts pointer events|outside of the viewport|element is not attached/i;function jb(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=>YN.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(`
|
|
419
|
+
`):Ph(e)}function Ph(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(`
|
|
420
|
+
`)}var zN=/^[A-Za-z0-9._-]+$/;function Ah(e){return zN.test(e.id)?Ni({args:["capture",e.id],cwd:e.cwd,stdio:e.stdio,signal:e.signal}):Promise.reject(new Error(`Not a valid spec id: "${e.id}"`))}function Ib(e,t=UN()){try{let n=JSON.parse($h(ji(vh(e),"capture.json"),"utf8").replace(/^/,"")),o=n.projectId;if(!o)try{o=JSON.parse($h(ji(e,"package.json"),"utf8")).name}catch{}o||=FN(e);let r=Object.keys(n.profiles??{}),s=n.defaultProfile??(r.length===1?r[0]:r.includes("staging")?"staging":r[0]);return s?Tb(ji(t,qN,"auth-states",o,`${s}.json`)):!0}catch{return!0}}function Lb(e){return Ni({args:["auth","--auto"],cwd:e.cwd,stdio:"pipe",signal:e.signal})}function Th(e,t){return e===127||/is not recognized as an internal or external command|command not found/i.test(t)}function Ob(e){try{let t=JSON.parse($h(ji(vh(e),"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 ir(e){return Tb(ji(vh(e),"capture.json"))}function Eh(){return[`Screenshot capture is not configured in this repo yet (no \`${Di}/capture.json\`). Set it up`,`conversationally, and never tell the user to run \`${cc} init\`:`,"",`1. Find the live app URL yourself first: \`${Di}/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 \`${Di}/capture.json\` in exactly this shape (fill the values):`,"```json","{",` "projectId": "<projectId from ${Di}/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 \`${Di}/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:",` \`${cc} auth\` (run in this repo's terminal; first time also \`npm i -g ${Eb}\`)`," then `/screenshot capture`."].join(`
|
|
421
|
+
`)}function _b(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(", ")}
|
|
422
|
+
/screenshot list --detail shows what each one needs`}function Mb(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):Ii(r?.reason)!==Ii(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):vl(r?.reason??"")!==vl(o.detail??"")?n.blockedNewReason.push(o.id):n.blockedAsBefore.push(o.id))}return n}function Ii(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 Ub(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?Qr(o.detail):"no reason recorded"}`)}function ds(e,t=2){return e.length<=t?e.join(" \xB7 "):`${e.slice(0,t).join(" \xB7 ")} \xB7 +${e.length-t}`}function Fb(e,t){if(!t)return[];let n=[],o=(i,a,l,c)=>{a>0&&n.push({glyph:i,label:`${a} ${l}`,tail:c})};if(o("\u2713",e.newlyCaptured.length,"newly captured",ds(e.newlyCaptured)),o("\u2717",e.newlyBroken.length,"newly broken",ds(e.newlyBroken)),o("\u2192",e.repairedNowBlocked.length,"repaired",`no longer broken \u2014 only data stands in the way \xB7 ${ds(e.repairedNowBlocked)}`),o("\u2298",e.newlyBlocked.length,"newly blocked",ds(e.newlyBlocked)),o("\u2192",e.blockedNewReason.length,"blocked on something new",`an earlier step now passes \xB7 ${ds(e.blockedNewReason)}`),o("\u2192",e.brokeDifferently.length,"broken differently",`the previous cause is fixed \xB7 ${ds(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 Wb(e){let t=e.results.filter(w=>w.outcome==="captured"),n=e.results.filter(w=>w.outcome==="skipped"),o=e.results.filter(w=>w.outcome==="failed"),r=e.unannotated??[],s=w=>w===1?"":"s";if(t.length+n.length+o.length===0)return null;let i=e.articles.length===1?`/push ${e.articles[0]}`:Ee("/push","--screenshots",qt(e.articles)),a=e.ids.length===1?`/screenshot capture ${e.ids[0]}`:"/screenshot capture",l=o[0]?.id,c=[];o.length>0&&c.push({glyph:"\u2717",cmd:`/screenshot ${l}`,why:`re-author the ${o.length===1?"broken spec":`first of ${o.length} broken specs`} \u2014 re-running fails the same way`});let p=Ee("/screenshot annotate","",r.length===1?r[0]:void 0);r.length>0&&c.push({glyph:"\u25C8",cmd:p,why:`draw the callouts on ${r.length} shot${s(r.length)} \u2014 no browser, seconds; ${r.length===1?"it cannot":"they cannot"} publish until drawn`}),n.length>0&&c.push({glyph:"\u2298",cmd:"/screenshot list",why:`what to stage for the ${n.length} blocked shot${s(n.length)}`}),t.length>0&&r.length<t.length&&c.push({glyph:"\u2713",cmd:i,why:`embed the ${t.length-r.length} new PNG${s(t.length-r.length)}`});let m=Math.max(...c.map(w=>w.cmd.length));return{note:c.map(w=>`${w.glyph} ${w.cmd.padEnd(m)} ${w.why}`).join(`
|
|
423
|
+
`),cmd:o.length>0?`/screenshot ${l}`:r.length>0?p:t.length>0?i:a,tone:o.length>0||r.length>0?"warn":"info"}}function Bb(e,t){let n=new Map(Ke(e).map(o=>[o.id,o.file]));return[...new Set(t.map(o=>n.get(o)).filter(o=>!!o))].sort()}async function Nh(e,t){let n=t?.cwd??process.cwd(),o=xh(e);if(!ir(n))return console.log(`Screenshot capture is not set up in this repo yet. Run: ${cc} init`),{kind:"continue"};let{ready:r,captured:s,blocked:i,rows:a}=Li(n,o.mode==="scope"?o.scope:void 0),l=Rh(n,a),c=(o.mode==="all"||o.mode==="scope")&&o.retryBlocked,p=o.mode==="single"?[o.id]:o.mode==="failed"?l:o.mode==="blocked"?i:o.mode==="picker"?r:[...r,...s,...c?i:[]];if(p.length===0)return o.mode==="failed"?console.log("No broken specs to re-run \u2014 /screenshot list shows where things stand."):o.mode==="blocked"?console.log("No shots are waiting on app data \u2014 /screenshot list shows where things stand."):console.log("No authored specs to capture yet \u2014 author them first: /screenshot"),{kind:"continue"};if(!c&&o.mode!=="single"&&o.mode!=="failed"&&o.mode!=="blocked"){let S=Sh(a.filter(A=>A.state==="blocked"),"/screenshot capture --blocked");S&&console.log(S)}let m=Date.now(),$=[];for(let S of p){console.log(`\u25B6 ${S}`);try{let{exitCode:A}=await Ah({cwd:n,id:S,stdio:"inherit"});$.push({id:S,outcome:Ch(n,S,A,m)})}catch(A){if(A.code==="ENOENT")return console.log(`${cc} is not installed. Run: npm i -g ${Eb}`),{kind:"continue"};$.push({id:S,outcome:"failed",detail:A.message})}}let w=S=>$.filter(A=>A.outcome===S).length;console.log(`\u2713 ${w("captured")} captured \xB7 \u2298 ${w("skipped")} skipped \xB7 \u2717 ${w("failed")} failed`);let C=$.filter(S=>S.outcome==="captured");return dl(n,$.map(S=>({id:S.id,outcome:S.outcome,reason:S.detail,specSource:Qo(n,S.id)})),new Date().toISOString()),C.length>0?(console.log(yo(C.length)),{kind:"forward-to-agent",prompt:vn(n,C.map(S=>S.id)),display:"/screenshot verify"}):{kind:"continue"}}import{readProjectConfig as XN,DEFAULT_OUTPUT_DIR as QN,resolveOutputDir as JN,shotArtifacts as ZN,annotationCurrent as eD,CAPTURE_COMMAND as uc,CAPTURE_PACKAGE as tD}from"document360-engine";Yr();var Hb="0.2.29";function dc(e=Nt()){return zr(e,Hb)}function Dh(e){let t=e.includes("--force")||e.includes("-f"),n=e.includes("--all")||e.includes("-a"),o=e.find(r=>!r.startsWith("-"));return n?{mode:"all",force:t}:o?o.includes("/")||o.includes("\\")||o.endsWith(".md")?{mode:"scope",scope:o.replace(/\\/g,"/").replace(/\/+$/,""),force:t}:{mode:"single",id:o}:{mode:"pending"}}function jh(e,t){let n=Ke(e,t);return{pending:n.filter(o=>o.state==="captured").map(o=>o.id),done:n.filter(o=>o.state==="annotated"||o.state==="verified"||o.state==="rejected").map(o=>o.id),rows:n}}var nD=/^[A-Za-z0-9._-]+$/;function oD(e){if(!nD.test(e.id))return Promise.reject(new Error(`Not a valid spec id: "${e.id}"`));let t=["annotate",e.id,...e.force?["--force"]:[]];return Ni({args:t,cwd:e.cwd,stdio:e.stdio,signal:e.signal})}function rD(e,t,n,o){let r=JN(e,XN(e)?.outputDir??QN),s=ZN(r,t);return(s.annotatedMtimeMs??0)>=o?"annotated":n===0&&eD(s)?"skipped":"failed"}function Ih(e){return e===null?`${uc} is not installed, so there is nothing to draw with. Install it, then run /screenshot annotate again.`:`The installed ${uc} (${e}) draws the callouts during the capture itself, so there is no separate step to run. Run /update to move to ${Hb} or later, then /screenshot annotate becomes available.`}var pc=8;function Gb(e){let t=e.results.filter(o=>o.outcome==="failed"),n=e.results.filter(o=>o.outcome==="annotated");return t.length>0?{glyph:"\u2717",cmd:Ee("/screenshot capture","",t.length===1?t[0].id:void 0),why:`${t.length} could not be drawn \u2014 taking ${t.length===1?"it":"them"} again rebuilds the boxes`}:n.length===0?null:e.voidedVerdicts>pc?{glyph:"\u25C8",cmd:Ee("/screenshot verify","",e.scope),why:`${e.voidedVerdicts} verified shots were re-drawn, so their verdicts no longer describe the picture on disk`}:{glyph:"\u25C8",cmd:Ee("/screenshot verify","",e.scope),why:`${n.length} picture${n.length===1?"":"s"} ready to check \u2014 no browser needed`}}async function Lh(e){let t=Date.now(),n=[];for(let o of e.ids){if(e.signal?.aborted)break;e.onStart?.(o);try{let{exitCode:r,output:s}=await oD({cwd:e.cwd,id:o,...e.force?{force:!0}:{},...e.signal?{signal:e.signal}:{},stdio:"pipe"}),i=rD(e.cwd,o,r,t);n.push({id:o,outcome:i,...i==="failed"?{detail:sD(s)}:{}}),e.onDone?.(o,i)}catch(r){if(r.code==="ENOENT")return{results:n,cliMissing:!0};n.push({id:o,outcome:"failed",detail:r.message}),e.onDone?.(o,"failed")}}return{results:n}}async function Oh(e,t){let n=t?.cwd??process.cwd(),o=Dh(e);if(!ir(n))return console.log(`Screenshot capture is not set up in this repo yet. Run: ${uc} init`),{kind:"continue"};let r=Nt();if(!dc(r))return console.log(Ih(r)),{kind:"continue"};let s=Xo(n);s&&console.log(s);let i=o.mode==="scope"?o.scope:void 0,{pending:a,done:l,rows:c}=jh(n,i),p=o.mode==="all"||o.mode==="scope"?o.force:!1,m=o.mode==="single"?[o.id]:p?[...a,...l]:a;if(m.length===0){let W=l.length>0;return console.log(W?`Every shot${i?` under ${i}`:""} is already drawn. Re-draw them anyway: /screenshot annotate --all --force`:"No shots have been taken yet \u2014 /screenshot capture takes them first."),{kind:"continue"}}let $=new Set(c.filter(W=>W.state==="verified").map(W=>W.id)),{results:w,cliMissing:C}=await Lh({cwd:n,ids:m,force:p});if(C)return console.log(`${uc} is not installed. Run: npm i -g ${tD}`),{kind:"continue"};let S=W=>w.filter(H=>H.outcome===W).length;console.log(`\u2713 ${S("annotated")} annotated`+(S("skipped")?` \xB7 ${S("skipped")} already current`:"")+(S("failed")?` \xB7 \u2717 ${S("failed")} failed`:""));for(let W of w.filter(H=>H.outcome==="failed"))console.log(` \u2717 ${W.id}${W.detail?` \u2014 ${W.detail}`:""}`);let A=w.filter(W=>W.outcome==="annotated").map(W=>W.id);if(A.length===0)return{kind:"continue"};let R=A.filter(W=>$.has(W)).length;if(R>pc)return console.log(`\u26A0 ${R} verified shots were re-drawn, so their verdicts no longer describe the picture on disk.
|
|
424
|
+
Check them when you're ready: ${Ee("/screenshot verify","",i)}`),{kind:"continue"};let D=A.filter(W=>!$.has(W)||R>0);return D.length===0?{kind:"continue"}:(console.log(yo(D.length)),{kind:"forward-to-agent",prompt:vn(n,D),display:"/screenshot verify"})}function sD(e){return e.split(/\r?\n/).map(n=>n.trim()).filter(n=>n.length>0&&!/^[▶✓↕]/.test(n)).at(-1)}ae();import{existsSync as iD}from"node:fs";import{join as aD}from"node:path";import{builderChannelWired as lD,driftedAnchors as cD,readTestidRequests as uD,testidHandoffPrompt as dD,testidRequestPaths as pD,writerDir as hD,PRODUCT_NAME as fD,WRITER_DIRNAME as mD}from"document360-engine";async function ps(e,t){let n=t?.cwd;if(n){let r=gD(n);if(r){for(let s of r)console.log(s);return{kind:"continue",ownNext:!0}}}return{kind:"forward-to-agent",prompt:["Run the capture-setup-checklist skill.","","Scan every <!-- SCREENSHOT --> block across the docs tree (the configured docsDir), read each block\u2019s prerequisites,",`anchor them to the capture scope keys in ${mD}/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(`
|
|
425
|
+
`),display:"/screenshot checklist"}}function gD(e){let t;try{t=Ke(e)}catch{return null}let n=iD(aD(hD(e),"capture.json")),o=t.some(i=>i.state!=="placeholder");if(n||o)return null;let r=t.length,s=new Set(t.map(i=>i.file)).size;return r===0?[`${V("\u25CB",u)}No screenshots are planned yet, so there is nothing to stage.`,u(" A screenshot is planned by the article that needs it. /write adds the placeholders as it writes.")]:[`${V("\u25CB",u)}${r} screenshot${r===1?"":"s"} planned across ${s} article${s===1?"":"s"} \u2014 none captured, none with a spec, and no capture setup yet.`,u(" There is nothing to stage from yet: a checklist is built from what each spec needs, and no specs exist."),u(" /screenshot author writes the specs. Come back to /screenshot checklist once they exist and it will"),u(" tell you what data to stage and which test ids your developers still owe you."),"",u(" Free \u2014 this read your files and called nothing.")]}var qb="-".repeat(64);function Vb(e){let t=uD(e);if(t.length===0)return null;let{mdRel:n}=pD(e),o=t.length,r=new Set(t.map(p=>p.file).filter(Boolean)).size,s=`${o} data-testid attribute${o===1?"":"s"}`,i=`${r} source file${r===1?"":"s"}`,a=dD(e,o),l=cD(t).length,c=l>0?[` \u26A0 ${l} of ${l===1?"them quotes":"them quote"} code that has changed since \u2014 still likely right,`,` but ${l===1?"it says":"they say"} so, and ${l===1?"asks":"ask"} to be found by description instead.`]:[];return lD(e)?{prompt:a,lines:[`\u{1F4CB} Developer hand-off \u2014 ${s} requested across ${i}.`,...c," Left in your builder's inbox: their coding agent is told about it at its next session, so",` there is nothing for you to relay. Detail: ${n}`]}:{prompt:a,lines:[`\u{1F4CB} Developer hand-off \u2014 ${s} requested across ${i}.`,...c,`\u26A0 Do NOT run this prompt here. ${fD} 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.)","",qb,a,qb]}}io();ae();import{listOpenForDocs as yD,readProjectConfig as wD,WRITER_DIRNAME as hc}from"document360-engine";function _h(e){try{return yD(e).length}catch{return 0}}function Mh(){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 \`${hc}/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 ${hc}/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 \`${hc}/architecture/\` if it is durable product knowledge.`,`3. After acting on a message, mark it resolved: edit its file in \`${hc}/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(`
|
|
426
|
+
`)}async function Kb(e,t){let n=t?.cwd??process.cwd();return wD(n)?_h(n)===0?(console.log(u("Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)")),{kind:"continue"}):{kind:"forward-to-agent",prompt:Mh(),display:"/inbox"}:(console.log(L(be)),{kind:"continue"})}ae();import{askBuilder as kD,openGapQuestions as Yb,readProjectConfig as bD,WRITER_DIRNAME as $D}from"document360-engine";function Oi(e){try{return Yb(e).length}catch{return 0}}function Uh(e,t){let n=[`\u2713 Question filed for your developers: ${$D}/messages/${e}`," It is committed and pushed with your docs, so it reaches them wherever they work. Their answer comes"," back the same way, and /inbox folds it into the article for you."];return t>1&&n.push(` ${t} of your questions are now waiting for an answer.`),n}function Fh(e){let t=["Ask your developers something the code cannot tell you: why a feature exists, when to use it, what it","affects, or whether it can be undone.",""," /ask I can document how a refund works, but not whether it can be reversed or who should approve it","","The question is written to your docs folder and travels to them with your next save. You do not have to","stop working: keep writing what you can ground, and /inbox folds the answer in when it arrives."];if(e.length>0){t.push("",`Still waiting on ${e.length} question${e.length===1?"":"s"}:`);for(let n of e.slice(0,5))t.push(` \xB7 ${n.subject.replace(/^\[gap\]\s*/,"")}`);e.length>5&&t.push(` \xB7 \u2026and ${e.length-5} more`)}return t}async function zb(e,t,n){let o=t?.cwd??process.cwd();if(!bD(o))return console.log(L(be)),{kind:"continue"};let r=e.join(" ").trim();if(r===""){for(let s of Fh(Yb(o)))console.log(s.startsWith(" \xB7")?u(s):s);return{kind:"continue",ownNext:!0}}try{let s=kD(o,{question:r,...n?{article:n}:{}}),i=Oi(o);for(let a of Uh(s.file,i))console.log(a.startsWith("\u2713")?Q(a):u(a))}catch(s){console.log(F(`Could not file the question: ${s.message}`))}return{kind:"continue",ownNext:!0}}ae();import{listOpenHints as Zb,listOpenForDocs as AD,listOpenDirectives as TD,readProjectConfig as e$,computeSyncStatus as ED,planPull as ND,applyPull as DD,planImport as jD,applyImport as ID,pullDocsUpdates as LD,handoffAvailable as OD,readProductBriefState as _D,readDiscoveryQueue as MD,partitionOpenHints as t$,askAboutUnfinishedHint as UD,briefMoved as FD,WRITER_DIRNAME as ar,RESPONSE_MARKER as WD}from"document360-engine";ae();import{readProjectConfig as vD,writeProjectConfig as Xb,reconcileDocsGit as xD,pullDocsUpdates as RD,probeGitState as SD,resolveGitHandoff as Qb,handoffAvailable as CD,PRODUCT_NAME as Mi}from"document360-engine";var _i=e=>e===1?"":"s";function wo(e,t){let n=o=>{let r=(o??"").split(`
|
|
427
|
+
`).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 fc(e,t){let n=Qb(t);if(!n.commit)return[{tone:"info",text:`Sharing: off \u2014 ${Mi} leaves its work for your coding agent to commit.`},{tone:"info",text:"Turn it on: /share on"}];let o=SD(e);if(!o)return[{tone:"info",text:"Sharing: unavailable \u2014 this folder is not a git repository."}];if(!o.upstream)return[{tone:"warn",text:V("\u26A0")+`This branch (${o.branch??"detached"}) has no remote, so your work can't reach your team yet.`},{tone:"info",text:"Ask your builder to run: git push -u origin HEAD"}];let r=n.push===!0?"on":n.push==="unconfirmed"?"not set up yet":"off",s=[{tone:"info",text:`Sharing: ${o.branch} \u2192 ${o.upstream} \xB7 saving: on \xB7 sending: ${r}`}];return o.ahead>0?s.push({tone:"warn",text:V("\u26A0")+`${o.ahead} change${_i(o.ahead)} not shared yet \u2014 run /share`}):s.push({tone:"ok",text:V("\u2713")+"Everything is shared with your team."}),s}function Wh(e,t,n){Xb({...t,gitHandoff:{commit:n,push:n}},e);let o=n?{tone:"ok",text:V("\u2713")+`Sharing on \u2014 ${Mi} will save and send its own work from now on.`}:{tone:"ok",text:V("\u2713")+`Sharing off \u2014 ${Mi} will leave its work for your coding agent to commit.`};return n?[o,...fc(e,{...t,gitHandoff:{commit:!0,push:!0}})]:[o]}async function mc(e,t){let n=[],o=Qb(t);if(!o.commit)return{lines:[{tone:"info",text:wo("disabled")}],changed:!1};let r=t;o.push==="unconfirmed"&&CD(e,t)&&(r={...t,gitHandoff:{commit:!0,push:!0}},Xb(r,e),n.push({tone:"info",text:`Sharing is now set up for this repo \u2014 ${Mi} will keep doing this automatically.`}));let s=await RD(e);if(s.ok&&s.pulled>0){let c=[s.newHints>0?`${s.newHints} new hint${_i(s.newHints)}`:null,s.newMessages>0?`${s.newMessages} new message${_i(s.newMessages)}`:null].filter(Boolean);n.push({tone:"ok",text:V("\u2B07")+`Got your builder's latest${c.length?` \u2014 ${c.join(", ")}`:""}.`})}else!s.ok&&s.reason!=="no-upstream"&&s.reason!=="no-git"&&n.push({tone:"warn",text:V("\u26A0")+wo(s.reason,s.detail)});let i=await xD(e,r);if(i.commit&&!i.commit.ok)return n.push({tone:"warn",text:V("\u26A0")+wo(i.commit.reason,i.commit.detail)}),{lines:n,changed:!1};let a=i.commit?.ok?i.commit.committed.length:0;if(a>0&&n.push({tone:"ok",text:V("\u2713")+`Saved ${a} change${_i(a)} to the docs folder.`}),i.push&&!i.push.ok)return n.push({tone:"warn",text:V("\u26A0")+wo(i.push.reason,i.push.detail)}),{lines:n,changed:a>0};let l=i.push?.ok?i.push.pushed:0;return l>0?n.push({tone:"ok",text:V("\u2B06")+`Shared ${l} change set${_i(l)} with your team.`}):a===0&&(s.ok&&s.pulled===0)?n.push({tone:"ok",text:V("\u2713")+"Everything is already shared with your team."}):a>0&&!i.push&&n.push({tone:"info",text:`Saved on this machine only. /share on lets ${Mi} send it to your team too.`}),{lines:n,changed:a>0||l>0||s.ok&&s.pulled>0}}var PD={ok:Q,info:Ie,warn:F,error:L};async function Jb(e,t){let n=t.cwd,o=vD(n);if(!o)return console.log(L(be)),{kind:"continue"};let r=e[0]?.trim().toLowerCase(),s=a=>{for(let l of a)console.log(PD[l.tone](l.text))};if(r==="status")return s(fc(n,o)),{kind:"continue"};if(r==="on"||r==="off")return s(Wh(n,o,r==="on")),{kind:"continue"};if(r)return console.log(L(`Unknown option "${r}". Use /share, /share status, /share on, or /share off.`)),{kind:"continue"};console.log(u("Exchanging work with your team\u2026"));let{lines:i}=await mc(n,o);return s(i),{kind:"continue"}}function un(e){let t=0,n=0,o=0,r=0,s=0,i=0;try{let l=t$(e,Zb(e));t=l.actionable.length,n=l.held.length,o=l.held.filter(c=>c.asked).length}catch{}try{let l=AD(e);r=l.filter(c=>c.kind==="request").length,s=l.filter(c=>c.kind==="answer").length}catch{}try{i=TD(e).length}catch{}let a=!1;try{a=FD(e)}catch{}return{hints:t,requests:r,answers:s,directives:i,held:n,heldAsked:o,briefMoved:a}}async function Hh(e){let t=e$(e);if(!t)return[];if(!OD(e,t))return[];let n=await LD(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 ${wo(n.reason,n.detail)}`}]}function hs(e){let t=[];e.hints&&t.push(`${e.hints} hint${e.hints===1?"":"s"}`),e.requests&&t.push(`${e.requests} request${e.requests===1?"":"s"}`),e.answers&&t.push(`${e.answers} answer${e.answers===1?"":"s"}`),e.directives&&t.push(`${e.directives} directive${e.directives===1?"":"s"}`);let n=t.join(", ");return e.briefMoved?n?`${n} and an updated product brief`:"an updated product brief":n||null}function Gh(e){let t=hs(e);return t?`Catching up on ${t}\u2026`:"Nothing queued from your builder \u2014 checking Document360 for reviewer comments and feedback\u2026"}function yc(e){let t={...e.queued,briefMoved:!1},n=hs(t);if(n)return{tone:"warn",note:`${V("\u26A0")}That run finished without writing anything, and ${n} ${t.hints+t.requests+t.answers+t.directives===1?"is":"are"} still queued \u2014 nothing was lost.`,lead:{cmd:"/catch-up",reason:"the queue is untouched, so running it again picks up the same work"}};if(e.queued.held>0){let o=e.queued.held;return{tone:"info",note:`${V("\u2139")}Nothing to write yet \u2014 your builder's ${o} note${xn(o)} ${o===1?"is":"are"} waiting on code that isn't finished. ${o===1?"It stays":"They stay"} queued.`,lead:null}}return e.hold?{tone:"info",note:`${V("\u2139")}No articles changed \u2014 product discovery is still open, so new overview and concept pages are on hold.`,lead:null}:{tone:"info",note:`${V("\u2713")}Nothing needed writing \u2014 no articles changed.`,lead:null}}function qh(e){return{push:e.includes("--push")||e.includes("--publish"),skipReview:e.includes(Vt),includeUnfinished:e.includes(wc)}}var wc="--include-unfinished";function Ui(e){let t={hold:!1,openQuestions:0,answersPending:0};try{let n=_D(e);return!n||n.status==="confident"?t:{hold:!0,...MD(e)}}catch{return t}}function Vh(e){if(!e.hold)return[];let t="I'll update the reference pages, and hold new overview and concept pages";if(e.answersPending>0){let n=e.answersPending;return[{tone:"info",text:`${V("\u2139")}Product discovery is still open \u2014 ${n} answer${xn(n)} just arrived from your builder.`},{tone:"info",text:` I'll fold ${n===1?"it":"those"} in first; if that settles the brief, everything gets written as normal.`}]}if(e.openQuestions>0){let n=e.openQuestions;return[{tone:"warn",text:`${V("\u26A0")}Product discovery isn't finished \u2014 ${n} question${xn(n)} still with your builder.`},{tone:"warn",text:` ${t} until the brief is settled.`}]}return[{tone:"warn",text:`${V("\u26A0")}Product discovery isn't finished \u2014 the product brief is still a draft.`},{tone:"warn",text:` ${t} until it's settled (/discover continues it).`}]}function Kh(e){try{return t$(e,Zb(e)).held}catch{return[]}}function Yh(e,t){let n=0;for(let o of t)try{UD(e,{hintFile:o.file,surface:o.surface,sources:o.unfinished})&&(n+=1)}catch{}return n}var Bh=3;function zh(e,t){if(e.length===0)return[];let n=e.length,o=[];if(e.every(r=>r.unfinished.length===0))return o.push({tone:"warn",text:`${V("\u26A0")}Your repository is in the middle of a merge, so the code isn't settled yet.`}),o.push({tone:"warn",text:` I've left your builder's ${n} note${xn(n)} for now. Finish the merge and I'll pick ${n===1?"it":"them"} up.`}),o;o.push({tone:"warn",text:`${V("\u26A0")}${n} of your builder's note${xn(n)} describe${n===1?"s":""} code that isn't finished, so I've left ${n===1?"its page":"those pages"} for now:`});for(let r of e.slice(0,Bh))o.push({tone:"warn",text:` \xB7 ${r.surface||r.file}`});return n>Bh&&o.push({tone:"warn",text:` \xB7 and ${n-Bh} more`}),o.push({tone:"info",text:t>0?` I've asked your builder whether ${t===1?"it is":"they're"} done. Everything else is written as normal.`:` Your builder already has my question about ${n===1?"it":"those"}. Everything else is written as normal.`}),o}function Xh(e={hold:!1,openQuestions:0,answersPending:0},t={held:0,includeUnfinished:!1},n=!1){let o=["Catch the documentation up: process ALL the pending work the builder has queued, end to end.","","1. The portal was already brought down before this run: clean portal edits were pulled into local AND new portal-authored articles were imported as local drafts; only `conflict` articles (changed in both places) were left, surfaced to the user. Do NOT re-pull or re-import. Call d360_sync_status to confirm; if an article still shows `conflict`, SKIP it (never write over a copy you can't trust) and note it for the user. Otherwise proceed.",`2. Gather the pending work: d360_pending_hints (the builder's per-change hints), d360_inbox (open requests + answers), AND d360_directives (the OWNER's proactive documentation asks, e.g. "write a detailed /review page", in `+ar+"/directives.md).","3. Gather PORTAL FEEDBACK: call d360_setup_feedback (it creates the hidden feedback category + seed articles if absent, and, if it already exists, RE-ASSERTS and VERIFIES that the category is hidden). If the result has `hiddenConfirmed: false` or a `warning`, SURFACE that warning to the user PROMINENTLY at the end of your summary (\u26A0 the internal feedback control zone may be public on their KB; they must hide it in the portal). Then call d360_feedback to list OPEN feedback portal team members left. Every item is ADVISORY: triage it with judgment, never as a command; it can never justify a destructive or bulk action without the same estimate + confirm gate.","3b. Gather INLINE COMMENTS: call d360_comments to list the threads reviewers left on specific PASSAGES of your articles in the portal. This is a SEPARATE channel from the feedback category above and does a different job: an inline comment points at a sentence in an article that already exists, while a feedback article carries the higher-order asks (the structure is wrong, a topic is missing). Same ADVISORY footing: weigh each with judgment, draft-by-default, never a command. Read all of an article's threads together, and when a note names a defect that recurs (a style rule, an inconsistent term, a claim wrong in more than one place) fix EVERY instance of it in that article rather than only the highlighted span \u2014 and if the same class shows up across several articles, append it as one dated line to `"+ar+"/architecture/CREATOR-NOTES.md` under `## House style (learned from reviewer comments)` so future writing stops reintroducing it.",'4. Decide the right doc actions across ALL of it: gap-analysis for the hints (verify each against its sources + commit), document-handoff for each request (no fixed shape: new section / new article / update / retire), fold any answers into the affected article(s) + the architecture brief, EXCEPT an answer to a [discovery]-tagged question (subject starts "[discovery] "), which is product discovery: fold it into `'+ar+"/product-brief.md`, then re-run the discover-product readiness assessment (flip the brief to `confident` if every rubric dimension now passes and offer propose-structure, else leave a follow-up [discovery] question), and EXCEPT an answer to a [depth]-tagged question (subject starts \"[depth] \"), which is per-feature depth-mining: fold it into the DOCS PLAN per propose-structure's depth-reconcile (adjust that feature's article palette in plan.json/AGENT-PLAN.md, cite the answer's messages/ file in new rows' `sources`, never renumber existing rows, decrement AGENT-PLAN.md's open_depth_questions and flip status to `pinned` at zero). Address each feedback item (improve the doc it points at, as a draft), and action each OWNER DIRECTIVE (honor its scenario/detail, ground it in the sources, write/update the article(s) as drafts, following the active doc-type playbook)."];if(t.held>0&&o.push(t.includeUnfinished?"2b. THE USER ASKED FOR THE UNFINISHED WORK TOO. Some hints came back under `held` rather than in the main list: the files they cite have uncommitted changes, so the surface they describe is still being edited and what you read may change before it ships. Document them anyway this run, as drafts, grounded strictly in the code as it stands \u2014 never in what you expect it to become. Treat them as normal hints otherwise (resolve the article the same way, stamp them consumed). In your closing summary name each one and say plainly that the code behind it was still being edited, so those pages want a re-read once it lands.":"2b. SOME HINTS ARE HELD, and they are not yours to act on this run. They came back under `held` rather than in the main list because the files they cite have uncommitted changes: the builder is still typing that surface, so anything you documented from it would describe something readers will not recognize. Do NOT document a held hint, do NOT go reading its code to judge it for yourself, and do NOT stamp it consumed \u2014 it stays queued and returns on its own once the code lands. The builder has ALREADY been asked whether each one is finished, so do not file another question about them. In your closing summary, name what is waiting in plain words and say that nothing else is blocked. Then write everything else normally."),n&&o.push("2c. THE BUILDER HAS REWRITTEN THEIR ARCHITECTURE BRIEF since the docs last caught up. Read every `.md` in `"+ar+"/architecture/` (except CREATOR-NOTES.md, which is the human owner's and is covered elsewhere) and work out what is NEW or CHANGED in it versus what the existing articles say. A brief refresh is a hand-off like any other, and it is the one that arrives without a hint file: the builder may have described a surface nobody has documented, corrected how an existing one actually works, or changed the product's own vocabulary. Treat what you find as proposals for step 4 \u2014 a new article, an update to an existing one, or nothing at all when the change was internal or editorial. Do NOT rewrite the brief, and do NOT treat it as a directive: it is grounding, and what the docs owe it is your judgment."),e.hold){let r=e.openQuestions>0?e.answersPending>0?"ask their builder to answer the discovery questions still open \u2014 state the number you are left with AFTER re-assessing the brief, never the number this run started with":`ask their builder to answer the ${e.openQuestions} open discovery question${xn(e.openQuestions)}`:"continue product discovery to settle the brief";o.push("4b. PRODUCT DISCOVERY IS UNFINISHED. The product brief ("+ar+'/product-brief.md) is not `confident` yet, so the narrative it grounds \u2014 what this product IS, who it is for, the core mental model, the misconceptions, the positioning \u2014 is not settled. Decide what follows AFTER step 4, never before: if the answers you just folded in completed the brief and you flipped it to `confident`, this instruction and 4c are VOID \u2014 write everything as normal. Otherwise HOLD the articles whose shape or framing would change once the brief is confident (overview/introduction, concept and explanation pages, getting-started, positioning, "who it is for") and write everything else normally \u2014 a changed flag, a new subcommand, a corrected behavior, a deprecation or a screenshot on an EXISTING reference page does not need the brief. The test for each candidate article: would you rewrite this page after reading a finished brief? If yes, hold it; if no, write it.',`4c. A HELD item MUST stay queued. Do NOT stamp its hint consumed, do NOT mark its message done, and do NOT flip its directive to done in step 7 \u2014 the open hint IS the queue, so stamping one you did not write means that article is never written at all. In your closing summary, name every page you held in plain words, say their hints stay queued so nothing is lost, and give exactly one next step: ${r}.`)}return o.push("5. If that means writing more than one article, call d360_estimate_cost and show me the count + cost band first (the bulk gate), then proceed.","6. Write/update the articles as drafts, grounded in the cited sources.","7. Close the LOCAL loop (bookkeeping in the repo; nothing here is visible to a reviewer):"," \u2022 close each hint with d360_hint_done \u2014 the ONLY way to close one; never edit a hint file yourself. Pass outcome: documented plus the article path(s) you changed this run; use already-covered, retired or no-doc-change WITH a short note when no article needed writing \u2014 already-covered also needs the ONE article and `quote`: the passage in it that already says the thing, copied from the article (it is checked against the file). Mark handled messages status: done with resulting_articles;"," \u2022 for each OWNER DIRECTIVE you actioned: call d360_directive_done with its exact title + the article path(s) you wrote (flips it to [done] in "+ar+"/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 `"+ar+"/architecture/CREATOR-NOTES.md` as an appended, dated `## From portal Creator notes (<date>)` section (preserve every existing note + human edit), then call d360_feedback_done for it.","8. Push the drafts to Document360.","9. Cross-link second pass: any article you wrote that links to ANOTHER article in this same batch had that inline link degrade to plain text (its target had no live URL yet when the source was written). Now that every target exists, re-update the affected articles so those inline links resolve to live URLs; only the ones that had such forward references need it. (The structured Related Articles sidebars are already two-way linked; this is just inline body links.)","10. NOW answer the people who asked, AFTER the push (steps 8-9), never before. A reviewer reads your reply in the portal and then looks at the article to check it, so replying first promises a change they cannot see. For anything whose push failed, do NOT reply on it; leave it outstanding and report it."," \u2022 for each INLINE COMMENT you actioned: call d360_comment_respond with its comment_id + article_id and a `reply` saying in plain words what you changed \u2014 in the reviewer's terms, mentioning where you applied the same fix more widely. Do NOT pass `resolve`: replying is your job, closing the thread is theirs, and they can only decide it is settled after seeing the change (your answer is recorded either way, so it will not come back at you). NEVER edit the reviewer's own comment text;"," \u2022 for each portal feedback item you actioned: append a short note at the BOTTOM of that feedback article via d360_update_article: `"+WD+" \u2713 actioned in <article> (<date>)` (or `declined: <reason>`), NEVER overwriting the person's own text, then call d360_feedback_done(article_id, resulting_articles)."),o.push("Leave everything as DRAFTS for review; do not publish live. Publishing is a separate, reviewed step: articles you write here have not been read by an editor yet, so making them visible to readers is never part of this run. Tell the user what is waiting as a draft.",'Do NOT end with slash commands or a "what to do next" line. The tool prints the next step itself, scoped to what this run changed, and a second suggestion from you competes with it (yours will be the broader, more expensive one, because you cannot see how much was touched). Report what you did and stop.'),o.push("","End with a one-line-per-item summary of what you wrote/updated, and anything you couldn't ground (say plainly that you left a question for their engineers). Write the whole summary for a technical writer: no tool names, no internal file names, no raw status words, no hint ids, just plain sentences about what changed and what is worth their attention."),o.join(`
|
|
428
|
+
`)}var BD={status:ED,plan:ND,apply:DD,planImport:jD,applyImport:ID};async function Qh(e,t=BD){let n={pulled:[],imported:[],conflicts:[],failed:[],needFolders:[]},o;try{o=await t.status({cwd:e.cwd,profileName:e.profileName})}catch(r){return n.error=r.message,n}for(let r of o.entries)if(r.status==="conflict"&&r.path)n.conflicts.push(r.path);else if(r.status==="untracked-remote"&&r.articleId){if(r.remoteCategory&&!r.remoteCategory.hasLocalFolder){n.needFolders.push(r.title??r.articleId);continue}try{let s=await t.planImport({cwd:e.cwd,profileName:e.profileName,articleId:r.articleId,...r.remoteCategory?{categoryPath:r.remoteCategory.path}:{}});t.applyImport({cwd:e.cwd,profileName:e.profileName},s),n.imported.push(s.path)}catch(s){n.failed.push({path:r.title??r.articleId,error:s.message})}}else if(r.status==="remote-ahead"&&r.path)try{let s=await t.plan({cwd:e.cwd,profileName:e.profileName,relPath:r.path});t.apply({cwd:e.cwd,profileName:e.profileName},s),n.pulled.push(r.path)}catch(s){n.failed.push({path:r.path,error:s.message})}return n}var gc=(e,t=5)=>`${e.slice(0,t).join(", ")}${e.length>t?`, +${e.length-t} more`:""}`,xn=e=>e===1?"":"s";function Jh(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${xn(e.pulled.length)} into local: ${gc(e.pulled)}`),e.imported.length&&t.push(`\u2713 Imported ${e.imported.length} new portal article${xn(e.imported.length)} into local drafts: ${gc(e.imported)}`),e.conflicts.length&&t.push(`\u26A0 ${e.conflicts.length} article${xn(e.conflicts.length)} changed both locally and in the portal \u2014 left untouched (resolve: /pull <path>): ${gc(e.conflicts)}`);for(let n of e.failed.slice(0,3))t.push(`\u26A0 ${n.path}: ${n.error}`);return e.failed.length>3&&t.push(`\u26A0 \u2026and ${e.failed.length-3} more left for /pull.`),e.needFolders.length&&t.push(`\u2139 ${e.needFolders.length} portal article${xn(e.needFolders.length)} ${e.needFolders.length===1?"is":"are"} in a category with no folder here \u2014 /pull creates ${e.needFolders.length===1?"it":"them"} and imports ${e.needFolders.length===1?"the article":"the articles"}: ${gc(e.needFolders)}`),t}async function n$(e,t){let n=t?.cwd??process.cwd();if(!e$(n))return console.log(L(be)),{kind:"continue"};let o=st(n,t?.profileName);if(!o.ok){let[$,w]=Gt(o);return console.log(L($)),console.log(u(w)),{kind:"continue"}}let{push:r,includeUnfinished:s}=qh(e);for(let $ of await Hh(n))console.log($.tone==="ok"?Q($.text):F($.text));console.log(u("Reconciling with Document360 (pulling any portal changes)\u2026"));let i=await Qh({cwd:n,profileName:t?.profileName});for(let $ of Jh(i))console.log($.startsWith("\u2713")?Q($):$.startsWith("\u2139")?u($):F($));let a=Ui(n);for(let $ of Vh(a))console.log($.tone==="warn"?F($.text):u($.text));let l=Kh(n),c=s?[]:l,p=Yh(n,c);for(let $ of zh(c,p))console.log($.tone==="warn"?F($.text):u($.text));let m=un(n);return console.log(u(Gh(m))),{kind:"forward-to-agent",prompt:Xh(a,{held:l.length,includeUnfinished:s},m.briefMoved),display:`/catch-up${r?" --push":""}${s?` ${wc}`:""}`}}ae();import{resolveActiveProfile as KD,resolveProjectId as YD,loadProfileMap as zD,readCommentLedger as XD,isCommentOpen as QD,saveOpenCommentCount as JD,loadCommentSweepMemory as ZD,recordCommentSweep as e1,planCommentSweep as t1,sweepOpenComments as n1,loadUserNames as o1,writeReviewerNotes as r1,sweptFromResult as s1,needsFullArchivePass as i1,reviewerNotesPath as a1,commentHtmlToText as o$,annotatedText as l1,readProjectConfig as c1,loadPortalLabels as u1,portalBreadcrumb as ef,portalCategoryPath as d1,resolveModelForOperation as p1,runPartitioned as h1,snapshotArticles as f1,EMPTY_PORTAL_LABELS as m1,WRITER_DIRNAME as g1}from"document360-engine";import Oe from"picocolors";import{CONTENT_CAP_VERSION as HD,stampArticles as GD,articlesChangedSince as qD,docsRootOf as VD}from"document360-engine";function lr(e,t,n="",o){let r=[];try{r=qD(e,t)}catch{return{changed:[],cta:null}}if(r.length===0)return{changed:[],cta:null};try{GD(e,r,{writtenCap:HD,reviewedCap:0,checkedCap:0})}catch{}let s=VD(e),i=p=>{let m=p.replace(/\\/g,"/");return m.startsWith(`${s}/`)?m.slice(s.length+1):m},a=qt(r.map(i)),l=r.length,c=a?"/push":"/push --all";try{return{changed:r,cta:Kt(e,{text:`${n}${l} article${l===1?"":"s"} updated \u2014 ${c} saves ${l===1?"it":"them"} to Document360 as ${l===1?"a draft":"drafts"}.`,cmd:c},n,a,o)}}catch{return{changed:r,cta:null}}}var s$=300,Fi=3;function y1(e,t){let n=al(e).toLowerCase(),o=t.trim().replace(/\\/g,"/").replace(/^\/+|\/+$/g,"").toLowerCase();if(!o||n===o||n.endsWith(`/${o}`))return!0;let r=n.split("/").pop()??n;return r.startsWith(`${o}-`)||r===o||ao(n).toLowerCase()===o}async function kc(e,t,n={}){let o=KD(e,t),r={profile:o.name,connection:o.connection,projectId:o.project.projectId,projectName:o.project.projectName},s=YD(r,o.project.projectId),i=zD(e,o.name);if(!i)return{threads:[],answered:[],labels:m1,scanned:0,failed:[],truncated:0,skipped:0,archived:!1};let a=XD(e,o.name),l=new Set(Object.values(a).map(G=>G.articlePath).filter(G=>!!G)),c=Object.keys(a).length===0||l.size>0,p=n.articleIds?.length?new Set(n.articleIds):null,m=!!(p||n.path||n.scope),$=Object.entries(i.articles).filter(([,G])=>!!G.id).filter(([G,K])=>p?p.has(K.id):n.path?G.replace(/\\/g,"/")===n.path.replace(/\\/g,"/"):n.scope?y1(G,n.scope):!0).map(([G,K])=>({articleId:K.id,path:G,title:ll(e,G),answered:m||(c?l.has(G):!0)})),w=$.slice(0,s$),C=await u1(r,s,o.project.workspaceId,{cwd:e,profile:o.name}),S=m||n.full?{read:w,skipped:[]}:t1(w,{live:C.live,stateOf:G=>C.articles.get(G),memory:ZD(e,o.name),alwaysRead:new Set($.filter(G=>l.has(G.path)).map(G=>G.articleId))}),A=o.project.languageCode,R=i1(e)||!!n.full,D=await n1(r,s,S.read,{isOpen:(G,K)=>QD(a,G.id??"",K,G),...A?{langCode:A}:{},...n.onProgress?{onProgress:n.onProgress}:{},...R?{includeResolved:R}:{}}),W=D.threads.length>0||D.answered.length>0?await o1(r,s):new Map,H=r1(e,s1(D.threads,D.answered,G=>ef(C,G)),{userNames:W,ourReplyIds:Object.values(a).flatMap(G=>G.replyIds??[]),...R?{completeFor:S.read.filter(G=>!D.failed.some(K=>K.articleId===G.articleId)).map(G=>G.articleId)}:{}});m||JD(e,o.name,D.threads.length);let J=new Map;for(let G of[...D.threads,...D.answered])J.set(G.articleId,(J.get(G.articleId)??0)+1);return e1(e,o.name,{live:C.live,read:S.read.map(G=>G.articleId),failedIds:D.failed.map(G=>G.articleId),threadCounts:J,latestVersionOf:G=>C.articles.get(G)?.latestVersion}),{threads:D.threads,answered:D.answered,labels:C,scanned:D.scanned,failed:D.failed,truncated:Math.max(0,$.length-w.length),skipped:S.skipped.length,archived:H}}function w1(e,t=96){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n}var r$=500;function k1(e){let t=l1(e.comment);if(!t)return"a passage";let n=t.replace(/\s+/g," ").trim();if(n.length<=r$)return e.comment.commented_text_truncated?`\u201C${n}\u2026\u201D
|
|
429
|
+
(Document360 sends the first 500 characters of a highlight)`:`\u201C${n}\u201D`;let o=n.slice(0,r$).trimEnd(),r=n.length-o.length;return`\u201C${o}\u2026\u201D
|
|
430
|
+
(+${r} more character${r===1?"":"s"}${e.comment.commented_text_truncated?", and Document360 caps a highlight at 500":""})`}function b1(e,t){let n=d1(t,e.articleId);return n.length>0?n.join(" \u203A "):e.path?ao(e.path):""}function $1(e,t){return t.articles.get(e.articleId)?.title?.trim()||e.title||(e.path?si(e.path):e.articleId)}function v1(e,t){return ef(t,e.articleId,{category:e.path?ao(e.path):null,title:e.title??(e.path?si(e.path):null)})??e.path??e.articleId}function cr(e,t){let n=new Map;for(let o of e){let r=n.get(o.articleId);r||(r={articleId:o.articleId,path:o.path,category:b1(o,t),title:$1(o,t),label:v1(o,t),threads:[]},n.set(o.articleId,r)),r.threads.push(o)}return[...n.values()].sort((o,r)=>o.category.localeCompare(r.category)||o.title.localeCompare(r.title))}var x1=100,R1=120,i$=(e,t)=>Math.max(40,Math.min(e??96,t));function a$(e){let t=s=>s===1?"":"s",n=new Set(e.threads.map(s=>s.articleId)).size,o=e.answered.length,r=[`${e.threads.length} open`,`${n} article${t(n)}`];return o>0&&r.push(`${o} answered, awaiting reviewer`),r.push(e.skipped>0?`${e.scanned} of ${e.scanned+e.skipped} articles re-read`:`${e.scanned} checked`),`${Oe.bold("Reviewer comments")} ${r.join(` ${Oe.gray("\xB7")} `)}`}function Zh(e){let t=[],n=o=>o===1?"":"s";if(e.skipped>0&&t.push(Oe.gray(` ${e.skipped} article${n(e.skipped)} weren\u2019t re-read \u2014 nobody has drafted or commented on them since your last check, so they can\u2019t have new comments. /comments --full reads every one.`)),e.failed.length){t.push(`${V("\u26A0",Oe.yellow)}${e.failed.length} article${n(e.failed.length)} couldn\u2019t be checked this time \u2014 they may have comments too:`);for(let o of e.failed.slice(0,5)){let r=ef(e.labels,o.articleId,{title:o.title})??o.title??o.articleId;t.push(` ${Oe.gray(`${r} \u2014 ${w1(o.error,60)}`)}`)}e.failed.length>5&&t.push(` ${Oe.gray(`+${e.failed.length-5} more`)}`),t.push(Oe.gray(" Run /comments again to retry them."))}return e.truncated&&t.push(`${V("\u26A0",Oe.yellow)}Checked the first ${s$} articles; ${e.truncated} not checked this run.`),e.archived&&(e.threads.length>0||e.answered.length>0)?t.push(Oe.gray(` Everything reviewers have written is kept in ${a1(".").replace(/\\/g,"/").replace(/^\.\//,"")} \u2014 it outlives a rewrite.`)):!e.archived&&(e.threads.length>0||e.answered.length>0)&&t.push(`${V("\u26A0",Oe.yellow)}Couldn\u2019t write the reviewer-notes file, so Document360 is still the only copy of these notes.`),t}function Wi(e,t={}){let n=[],o=a=>a===1?"":"s",r=e.answered.length,s=()=>{if(!(!t.showAnswered||r===0)){n.push(` ${Oe.gray(`Answered, waiting on the reviewer (${r})`)}`);for(let a of cr(e.answered,e.labels))n.push(` ${Oe.gray(`${a.label} \u2014 ${a.threads.length} thread${o(a.threads.length)}`)}`);n.push("")}};if(e.threads.length===0){let a=r>0?` ${Oe.gray("\xB7")} ${r} answered, awaiting reviewer`:"",l=e.scanned+e.skipped;return n.push(e.skipped>0?`${V("\u2713",Oe.green)}No open reviewer comments in the ${e.scanned} article${o(e.scanned)} checked ${Oe.gray("\xB7")} ${e.skipped} of ${l} not checked${a}`:`${V("\u2713",Oe.green)}No open reviewer comments across ${e.scanned} article${o(e.scanned)}.${a}`),r>0?(n.push(Oe.gray(` Those ${r} are answered and left open on purpose \u2014 the reviewer closes them once they\u2019ve checked the change.`)),t.showAnswered||n.push(Oe.gray(" /comments --answered lists them."))):n.push(Oe.gray(" Reviewers leave these by highlighting text in a draft in the Document360 portal and commenting on it.")),n.push(""),s(),n.push(...Zh(e)),n}let i=cr(e.threads,e.labels);return n.push(a$(e)),n.push(""),n.push(ki(["#","Category","Article","Comments"],i.map((a,l)=>[`${l+1}`,a.category||"(root)",a.title,`${a.threads.length}`]),i$(t.width,x1),{plain:!0,align:["left","left","left","right"]})),n.push(""),s(),n.push(...Zh(e)),n}function bc(e,t={}){let n=s=>s===1?"":"s",o=[`${Oe.gray("Category:")} ${e.category||"(root)"}`,`${Oe.gray("Article: ")} ${Oe.bold(e.title)}`,Oe.gray(`${e.threads.length} comment${n(e.threads.length)} from your reviewers`),""],r=e.threads.map(s=>{let i=[o$(s.comment.comment)||"(empty comment)"];for(let a of s.comment.replies??[])i.push(`\u21B3 ${o$(a.comment)}`);return s.comment.status==="reopened"&&i.push("(reopened \u2014 you answered this once and the reviewer came back)"),s.canResolve||i.push("(you can reply to this one, but your role can\u2019t resolve it)"),[k1(s),i.join(`
|
|
431
|
+
`)]});return o.push(ki(["Annotated text","Comment"],r,i$(t.width,R1),{plain:!0})),o.push(""),o}function $c(e){let t=e.reduce((r,s)=>r+s.threads.length,0),n=r=>r===1?"":"s",o=[{kind:"all",label:`All articles \u2014 answer all ${t} comment${n(t)}`,groups:e}];return e.forEach((r,s)=>{o.push({kind:"article",n:s+1,label:r.title,note:`${r.threads.length} comment${n(r.threads.length)}`,group:r})}),o}function tf(e,t={}){let n=cr(e.threads,e.labels);if(t.full&&n.length===1){let o=n[0];return[a$(e),"",...bc(o,t),...Zh(e)]}return Wi(e,t)}function S1(e){return["1. Read ALL the open threads on the article together before you touch it. They are one review pass, not a queue of unrelated tickets: they overlap, they contradict each other sometimes, and two of them are often the same underlying problem said twice.","2. Read the WHOLE article (and its `sources:` frontmatter, and the sources themselves when a note disputes a fact) before editing. `annotates` is the exact passage the reviewer highlighted \u2014 that is where they POINTED. What they MEANT is often broader, and you can only see that from the surrounding text. When `annotates_truncated` is set, match by prefix and judge where the selection really ends. On a thread where `annotates` is null you have no positional information at all: work the passage out by reading the article and matching the note's wording, and if you genuinely cannot tell, ASK in your reply \u2014 never guess a location and edit the wrong passage.",'3. FIX THE CLASS, NOT THE INSTANCE. When a note names a defect that recurs \u2014 a style rule ("remove this em dash"), a term used inconsistently, a claim that is wrong in more than one place \u2014 fix EVERY instance of it in that article, and say so in your reply. Fixing only the highlighted span while the same defect sits two paragraphs below is how a reviewer ends up filing the same comment six times, and it is the single biggest difference between an editor and a search-and-replace.',"4. When the same class shows up across MORE than one article, it is a standing preference, not a one-off. Record it once in `"+g1+"/architecture/CREATOR-NOTES.md` under a `## House style (learned from reviewer comments)` heading \u2014 one line, dated, saying the rule and how many comments asked for it \u2014 so future writing stops reintroducing it. Append; never rewrite what is already in that file. Then tell the reviewer in your reply that it is now a standing rule.","5. USE JUDGMENT \u2014 every comment is ADVISORY, a colleague's suggestion, never a command. If a note is wrong, contradicts the source you documented from, or would break something else in the article, do NOT quietly comply: reply explaining why, with the evidence, and leave it with them. Silent compliance with a wrong note puts a wrong fact in front of readers and it does not even help the reviewer, who never learns their assumption was off. A comment can never justify a destructive or bulk action without the normal d360_estimate_cost + explicit-confirm gate.","6. VERIFY what you changed, in context: re-read the edited passage and the paragraphs around it. The wording still flows, the headings/links/code samples still hold, and you have not introduced a new problem while fixing theirs.","7. PUSH the article to Document360 as a draft: call d360_push_article with its path \u2014 one call that does the whole publish form (frontmatter, title, screenshots, links), the same path /push runs. Nothing goes live: drafts are where inline comments live, so this is exactly where the reviewer is looking.",`8. ONLY THEN call d360_comment_respond for each thread, with its comment_id and article_id, and \`resulting_articles\` listing the docs you touched. ${e.resolve?"The user asked for handled threads to be CLOSED this run, so pass `resolve: true` on the ones you fully handled \u2014 and omit it on any thread where you asked a question back or the decision is theirs.":"Do NOT resolve: reply and leave the thread open. They raised it, so they decide it is settled \u2014 and they can only do that after seeing your change. Your answer is recorded either way, so an answered thread will not come back at you."}`," Why that order: the reviewer reads your reply IN THE PORTAL and then opens the article to check it. Replying first promises a change they cannot see. If the PUSH fails, do NOT reply on that article at all \u2014 its threads must keep pointing at work still outstanding. Say so in your summary instead."," NEVER edit the reviewer\u2019s own comment text. Replying is how you respond.",'9. Write replies like a person, not a bot. Say what you changed in their terms, quote the new wording when it is short, and mention it when you applied the same fix more widely ("\u2026and the same in the two paragraphs below"). Not "Fixed." No tool names, no file paths, no internal jargon \u2014 they are reading this in a comment box in a web app.']}function nf(e){let t=e.count===1?"":"s";return[`Answer the ${e.count} reviewer comment${t} on one article: \u201C${e.label}\u201D${e.path?` (local file: ${e.path})`:""}.`,"",`Call d360_comments with article_id "${e.articleId}" to read its open threads \u2014 scope it to that id, never sweep the whole knowledge base, which costs one API read per article. A thread whose status is \`reopened\` is one you already answered and the reviewer was NOT satisfied with, so read its replies \u2014 yours included \u2014 before touching the article, and do not simply repeat the previous fix.`,"",...S1({resolve:e.resolve}),"","End with one line per thread: what the reviewer asked, what you changed, and whether you left it with them. Plain sentences for a technical writer \u2014 no tool names, no internal file names. Then say the updated article is now a draft in Document360, so the reviewers can see the changes where they left their comments, and that it stays a draft \u2014 readers keep seeing the previous version \u2014 until someone asks for it to be published live."].join(`
|
|
432
|
+
`)}function of(e){let t={answer:!1,resolve:!1,all:!1,showAnswered:!1,scope:{}};for(let n=0;n<e.length;n++){let o=e[n];o==="--answer"?t.answer=!0:o==="--resolve"?t.resolve=!0:o==="--all"?t.all=!0:o==="--full"?t.scope.full=!0:o==="--answered"||o==="--waiting"?t.showAnswered=!0:o==="--scope"?t.scope.scope=e[++n]:o.startsWith("--scope=")?t.scope.scope=o.slice(8):o.startsWith("-")||(t.scope.path=o)}return t.all&&(t.answer=!0),t.scope.scope===void 0&&delete t.scope.scope,t.scope.path===void 0&&delete t.scope.path,t}async function C1(e,t,n){if(t.length===0)return{kind:"continue"};let o=t.reduce((m,$)=>m+$.threads.length,0),{model:r}=p1(e.cwd,"standard"),s=new Map(t.map(m=>[m.label,m])),i=t.map(m=>({label:m.label,paths:m.path?[m.path]:[]}));console.log(u(`Answering ${o} comment${o===1?"":"s"} across ${i.length} article${i.length===1?"":"s"} (\u2264${Fi} agents at once) on ${r}. Each article is fixed, pushed to Document360 as a draft, then answered${n.resolve?" and resolved":" \u2014 the threads stay open for your reviewers to close"}\u2026`));let a=Date.now(),l=f1(e.cwd);try{for await(let m of h1({cwd:e.cwd,partitions:i,promptFor:$=>{let w=s.get($.label);return nf({articleId:w.articleId,label:w.label,path:w.path,count:w.threads.length,resolve:n.resolve})},concurrency:Fi,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),allowCommentResolve:n.resolve,model:r}))if(m.type==="partition_status")m.status==="running"?console.log(u(` \u25B8 ${m.label} \u2014 answering\u2026`)):m.status==="done"?console.log(Q(` \u2713 ${m.label}`)):console.log(L(` \u2717 ${m.label}`));else if(m.type==="run_done"){let $=m.results.filter(w=>!w.ok);console.log(""),console.log(`${m.results.length-$.length}/${i.length} article${i.length===1?"":"s"} answered.`),$.length&&console.log(F(`\u26A0 ${$.length} left untouched (their comments are still open, so nothing was promised to those reviewers): ${$.map(w=>w.label).join(", ")}`)),m.blocked&&console.log(F(`\u26A0 ${m.blocked}`)),m.allEmpty&&console.log(F("\u26A0 No agent produced any work this run \u2014 nothing was changed or answered.")),console.log(u(kn(zt(a,m.results,m.totalCostUsd))))}}catch(m){console.log(L(`Answering comments failed: ${m.message}`))}let p=lr(e.cwd,l,"","/comments").changed.length;return p>0&&console.log(`${p} article${p===1?"":"s"} changed, and that new text has not been read by an editor \u2014 ${p===1?"it":"they"} can go live once /review has been over ${p===1?"it":"them"}.`),{kind:"continue"}}async function l$(e,t){let n=t?.cwd??process.cwd();if(!c1(n))return console.log(L(be)),{kind:"continue"};let o=st(n,t?.profileName);if(!o.ok){let[a,l]=Gt(o);return console.log(L(a)),console.log(u(l)),{kind:"continue"}}let r=of(e);console.log(u("Checking Document360 for reviewer comments\u2026"));let s;try{s=await kc(n,t?.profileName,r.scope)}catch(a){return console.log(L(`Couldn\u2019t read comments from Document360: ${a.message}`)),{kind:"continue"}}for(let a of tf(s,{full:!!r.scope.path,showAnswered:r.showAnswered}))console.log(a);if(s.threads.length===0)return{kind:"continue"};if(r.answer&&t)return C1(t,cr(s.threads,s.labels),{resolve:r.resolve});let i=cr(s.threads,s.labels)[0];return console.log(`${V("\u2192",Oe.yellow)}${Oe.bold("/comments <article>")} shows one article\u2019s comments in full `+Oe.gray(i?.path?`(e.g. /comments ${i.path})`:"(by its local path)")),console.log(`${V("\u2192",Oe.yellow)}${Oe.bold("/comments --answer")} fixes each one, updates the draft in Document360, then replies in the thread `+Oe.gray("(one article at a time: /comments --answer <article>, or --scope <category>)")),{kind:"continue"}}ae();import{spawn as u$}from"node:child_process";import{mkdirSync as P1,openSync as A1,readFileSync as T1}from"node:fs";import{dirname as E1,join as N1}from"node:path";import{logsDir as D1,CAPTURE_COMMAND as j1,CAPTURE_PACKAGE as I1,PRODUCT_NAME as ur,WRITER_PACKAGE as L1}from"document360-engine";var dr=L1,fs=`npm i -g ${dr}@latest`,O1=I1;function _1(){return new Promise(e=>{try{let t=u$(`${j1} --version`,{stdio:"ignore",shell:!0,windowsHide:!0});t.on("error",()=>e(!1)),t.on("close",n=>e(n===0))}catch{e(!1)}})}function Bi(){return N1(D1(),"self-update.log")}function rf(e){return/\bEBUSY\b|\bETXTBSY\b|resource busy or locked|text file busy/i.test(e)}function vc(){return process.platform==="win32"}var sf=null;function xc(e){sf=e}function Hi(e){return rf(e)?`Another ${ur} is still running and holding its files open. Close every ${ur} window, then run: ${fs}`:/\bEACCES\b|permission denied|EPERM|operation not permitted/i.test(e)?process.platform==="win32"?`Permission denied. Run ${fs} from an Administrator terminal.`:`Permission denied \u2014 your global npm folder isn't writable. Either run sudo ${fs} , or (better) switch to a Node version manager such as nvm or fnm so global installs need no sudo.`:/ENOTFOUND|EAI_AGAIN|ETIMEDOUT|ECONNRESET|network/i.test(e)?`Couldn't reach the npm registry. Check your connection or proxy, then run: ${fs}`:/EBADENGINE|Unsupported engine/i.test(e)?`Your Node version is too old for this release. Install Node 20 or later, then run: ${fs}`:`Run manually: ${fs}`}function M1(e,t=6){return e.split(/\r?\n/).map(n=>n.trimEnd()).filter(Boolean).slice(-t).join(`
|
|
433
|
+
`)}async function Gi(){let e=process.platform==="win32",n=await _1()?[dr,O1]:[dr],o=Bi(),r=null;try{P1(E1(o),{recursive:!0}),r=A1(o,"w")}catch{r=null}let s=()=>{try{return M1(T1(o,"utf8"))}catch{return""}};return new Promise(i=>{try{let a=u$(`npm i -g ${n.map(l=>`${l}@latest`).join(" ")}`,{stdio:r===null?"ignore":["ignore",r,r],shell:!0,detached:!e,windowsHide:!0});a.on("error",l=>i({ok:!1,output:`${String(l)}
|
|
434
|
+
${s()}`.trim(),packages:n})),a.on("close",l=>i({ok:l===0,output:l===0?"":s(),packages:n})),e||a.unref()}catch(a){i({ok:!1,output:String(a),packages:n})}})}var c$=[1500,2e3,2500],U1=e=>new Promise(t=>setTimeout(t,e));async function Rc(e={}){let t=sf;if(t===null)return"none";sf=null;let n=e.run??Gi,o=e.wait??U1,r=e.write??(a=>console.log(a)),s=t?`v${t}`:"the update";r(""),r(u(te("\u2B06",`Installing ${s}\u2026 (don\u2019t close this window)`)));let i=e.spinner===!1?null:F1();try{let a={ok:!1,output:"",packages:[]};for(let l=0;a=await n(),!(a.ok||!rf(a.output)||l>=c$.length);l++)await o(c$[l]);return i?.(),a.ok?(r(Q(te("\u2713",`Updated to ${s} \u2014 it\u2019s live next time you start ${ur}.`))),"installed"):rf(a.output)?(r(F(te("\u26A0",`Couldn\u2019t install ${s} \u2014 another ${ur} window is still open.`))),r(u(" It installs when the last one closes.")),"busy"):(r(F(te("\u26A0",`Couldn\u2019t install ${s}. ${Hi(a.output)}`))),r(u(` Full output: ${Bi()}`)),"failed")}catch{return i?.(),"failed"}}function F1(){if(!process.stdout.isTTY)return null;let e=0,t=setInterval(()=>{e=e%3+1,process.stdout.write(`\r ${".".repeat(e)}${" ".repeat(3-e)}`)},1e3);return()=>{clearInterval(t),process.stdout.write("\r \r")}}async function d$(){if(vc())return xc(""),console.log(u(`\u2B06 Windows can\u2019t replace the files while ${ur} is running.`)),console.log(u(" I\u2019ll install the update the moment you /exit.")),{kind:"continue"};console.log(u(`Updating the ${ur} toolchain\u2026`));let e=await Gi();return e.ok?(console.log(Q(`\u2713 Updated ${e.packages.join(" + ")}. Exit (/exit) and relaunch ${ur} to apply.`)),{kind:"continue"}):(console.log(L(`Update failed. ${Hi(e.output)}`)),e.output&&console.log(u(e.output)),console.log(u(`Full output: ${Bi()}`)),{kind:"continue"})}ae();io();import{existsSync as lf,rmSync as W1}from"node:fs";import{basename as p$,resolve as cf}from"node:path";import{execFileSync as B1}from"node:child_process";import{input as H1}from"@inquirer/prompts";import{readProjectConfig as G1,devHintsGuidePath as q1,PRODUCT_NAME as af,WRITER_DIRNAME as Gn}from"document360-engine";var V1=[".d360-writer.json",Gn,"d360-category-map.json",".d360-capture.json",".d360-capture-cache"],K1=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),Sc=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),h$=e=>e===Gn||e.startsWith(`${Gn}/`);function f$(e){let t=Sc(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:h$(t)?!0:K1.has(t)}function uf(e){let t=null;try{t=G1(e)}catch{t=null}let n=new Set(V1);for(let o of[Sc(t?.docsDir),Sc(t?.captureDir),Sc(t?.outputDir)])o&&h$(o)&&n.add(o);return[...n].filter(o=>f$(o)&&lf(cf(e,o)))}function df(e,t){let n=[],o=[];for(let r of t){if(!f$(r)){o.push({path:r,error:`refused \u2014 outside ${Gn}/ (protected)`});continue}try{W1(cf(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function m$(e,t){try{return B1("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
|
|
435
|
+
`).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function Y1(e){return m$(e,`${Gn}/hints`)}function z1(e){return m$(e,`${Gn}/messages`)}function pf(e,t){if(t.length===0)return[`Nothing to reset \u2014 no ${af} files found in this repo.`];let n=Y1(e),o=z1(e),r=lf(cf(e,"user-docs"));return[`\u26A0 This permanently DELETES everything ${af} created here:`,...t.map(s=>` \u2022 ${s}`),"",...n>0?[`\u26A0 ${n} doc hint(s) under ${Gn}/hints/ are not committed \u2014 commit them first or they're gone.`]:[],...o>0?[`\u26A0 ${o} message(s) under ${Gn}/messages/ are not committed \u2014 commit them first or they're gone.`]:[],...r?[`Note: a repo-root user-docs/ is NOT touched (only ${Gn}/ is removed).`]:[],"Undo = git: committed files are restorable; untracked ones (most screenshots) are gone.",`To confirm, type the repo name: ${p$(e)}`]}async function g$(e,t){let n=uf(t.cwd);for(let l of pf(t.cwd,n))console.log(n.length===0?u(l):l);if(n.length===0)return{kind:"continue"};let o=p$(t.cwd);if((await t.withPausedInput(()=>H1({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(F("Reset canceled \u2014 nothing deleted.")),{kind:"continue"};let s=lf(q1(t.cwd)),{removed:i,failed:a}=df(t.cwd,n);console.log(Q(`\u2713 Reset complete \u2014 removed ${i.length} item${i.length===1?"":"s"}. The repo is back to its original state.`));for(let l of a)console.log(L(` \u2717 ${l.path}: ${l.error}`));if(s){for(let l of nl())console.log(l);console.log(u("(Select and copy the prompt above to paste into your coding agent.)"))}return console.log(u(`Set up ${af} again with /init (then /login, /workspace).`)),{kind:"continue"}}ae();import{buildRegistry as Ki,clearRegistryCache as w$,lintArticles as Vi,listAvailablePacks as hf,readProjectConfig as Rn,readStyleBaseline as X1,clearStyleBaseline as Q1,styleBaselinePath as J1,recordStyleSwitch as Z1,declineStyleSweep as ej,styleSweepOutstanding as tj,resolveActivePacks as gf,styleGuidePath as k$,writeProjectConfig as Pc,buildStyleCompilePrompt as nj,loadStyleGuide as oj,loadHouseRules as rj,buildStyleLearnPrompt as sj,reviewerNotesPath as ij,listStyleGuides as aj,getStyleGuide as lj,resolveActiveProfile as cj,resolveProjectId as uj,styleGuideSettled as dj,styleGuideUpgradeOffered as b$,DEFAULT_PACK as yf,STYLE_GUIDE_MAX_CHARS as y$,BUILTIN_RULES as ms,ALWAYS_ON_PACK as qn,PRODUCT_NAME as pj,WRITER_DIRNAME as ft}from"document360-engine";import{existsSync as wf,mkdirSync as hj,readFileSync as $$,writeFileSync as ff}from"node:fs";import{dirname as fj}from"node:path";import{createHash as mj}from"node:crypto";function gs(e){let t=e.filter(o=>!o.startsWith("--")),n=(t[0]??"").toLowerCase();return n==="list"?{sub:"list"}:n==="use"?{sub:"use",value:t.slice(1).join(" ")}:n==="keep"?{sub:"keep"}:n==="sweep"?{sub:"sweep",value:t[1]}:n==="explain"?{sub:"explain",value:t[1]}:n==="pull"?{sub:"pull",value:t[1]}:n==="compile"?{sub:"compile"}:n==="learn"?{sub:"learn"}:n==="triage"?{sub:"triage"}:n==="off"?{sub:"off",value:t[1]}:n==="on"?{sub:"on",value:t[1]}:{sub:"show"}}var Cc=6;function gj(e,t,n){if(!t)return[te("\u26A0",`Name a rule: /style-guide ${n?"off":"on"} Google.Passive`)];let o=Ki(e),r=o.rules.find(m=>m.id.toLowerCase()===t.toLowerCase())??o.rules.find(m=>m.tunedBy?.localId.toLowerCase()===t.toLowerCase()),s=ms.find(m=>m.id.toLowerCase()===t.toLowerCase());if(n&&!r&&!s)return[te("\u26A0",`No active rule called "${t}".`),u(" /style-guide list shows the packs; /style-guide triage names the noisy rules.")];if(s)return[te("\u26A0",`${s.id} is a built-in check and cannot be switched off.`),u(" Built-in checks catch defects of fact \u2014 a leaked internal name, an invented command \u2014 not"),u(" matters of taste. They are grounded in your product\u2019s own source.")];let i=Rn(e)??{projectId:""},a={...i.styleGuide?.rules??{}},l=Object.keys(a).find(m=>m.toLowerCase()===t.toLowerCase()),c=r?.id??l;if(!c)return[te("\u26A0",`Nothing to turn back on \u2014 "${t}" is not switched off here.`),u(" /style-guide list shows the packs that are active.")];n?a[c]="off":delete a[c],Pc({...i,styleGuide:{...i.styleGuide??{},rules:a}},e),w$();let p=n&&c.toLowerCase().startsWith(`${qn}.`);return n?[te("\u2713",`${c} is off. It will not be reported again.`),...p?[u(` The writer is still told about it until you restart ${pj}.`)]:[],u(` Put it back: /style-guide on ${c}`)]:[te("\u2713",`${c} is back on, at whatever its pack sets.`),u(` What it looks for: /style-guide explain ${c}`)]}function yj(e){let t;try{t=Vi({cwd:e}).findings.filter(i=>!i.baselined)}catch{return[te("\u26A0","Could not read the articles to count findings.")]}if(t.length===0)return[te("\u2713","Nothing to triage \u2014 no rule is reporting anything.")];let n=Ki(e),o=new Map;for(let i of t)o.set(i.ruleId,[...o.get(i.ruleId)??[],i]);let r=[...o.entries()].sort((i,a)=>a[1].length-i[1].length),s=[`${We(t.length,"finding")} across ${We(new Set(t.map(i=>i.path)).size,"article")}, by rule:`,""];for(let[i,a]of r.slice(0,Cc)){let l=n.rules.find($=>$.id===i),c=ms.find($=>$.id===i),p=(l?.severity??c?.severity)==="error",m=[...new Set(a.map($=>$.term.trim()).filter(Boolean))].slice(0,3);s.push(` ${i} ${u(`${We(a.length,"finding")} in ${new Set(a.map($=>$.path)).size}`)}`),s.push(u(` ${l?.message??c?.summary??""}`)),m.length>0&&s.push(u(` flagged: ${m.map($=>`"${$}"`).join(", ")}`)),p?(s.push(u(" This one blocks publishing, so there is no decision to make \u2014 it wants a fix.")),s.push(" /lint --blocked --fix")):c?(s.push(u(" Built in, and grounded in your product\u2019s own source \u2014 it catches a defect of fact")),s.push(u(" rather than a matter of taste, so there is nothing to decide. /lint --fix corrects them."))):(s.push(` /style-guide off ${i}`),s.push(u(` \u2026or /style-guide explain ${i} to see what it looks for first.`))),s.push("")}if(r.length>Cc){let i=r.slice(Cc).reduce((a,[,l])=>a+l.length,0);s.push(u(` ${We(r.length-Cc,"other rule")} account for the remaining ${We(i,"finding")}.`)),s.push("")}return s.push(u(" Keep them all and fix the articles instead: /lint --fix")),s.push(u(" Switching a rule off changes nothing already written \u2014 it stops being reported.")),s}function wj(e){try{return Fw(e,"/style-guide")?.title??null}catch{return null}}function kf(e){try{return!dj(Rn(e)?.styleGuide)}catch{return!1}}function v$(e,t){let n=[],o=new Set,r=s=>{if(o.has(s))return;o.add(s),Zr(e,s).ok&&n.push(te("\u2713",`That settles a docs-campaign step \u2014 marked done: ${s}`))};try{let s=wj(e);if(s&&r(s),t)for(let i of Cl(e,t))r(i)}catch{}return n}function kj(e){let t=Rn(e)??{projectId:""},n=gf(t.styleGuide).filter(s=>s!==qn),o=b$(t.styleGuide);Pc({...t,styleGuide:{...t.styleGuide,decidedAt:new Date().toISOString(),...o?{declinedUpgrade:yf}:{}}},e);let r=[te("\u2713",n.length>0?`Keeping ${n.join(", ")} \u2014 plus the built-in checks, which are always on.`:"Keeping the built-in checks only \u2014 the correctness rules and the anti-slop rules, both always on."),u(" Change your mind any time: /style-guide use \xB7 see the options: /style-guide list")];return r.push(...v$(e)),r}var qi="House";async function bj(e,t,n){let o,r;try{let S=cj(e,n);o={profile:S.name,connection:S.connection,projectId:S.project.projectId,projectName:S.project.projectName},r=await uj(o,S.project?.projectId)}catch(S){return{lines:[te("\u2717",`Not signed in to Document360: ${S instanceof Error?S.message:String(S)}`),u(" Run /login first.")],restart:!1}}let s=await aj(o,r);if(s.kind!=="ok")return{lines:[te("\u26A0",`Document360 didn't return your style guides \u2014 ${s.reason}.`),u(` Nothing is blocked. Your house style guide lives at ${ft}/style-guide.md \u2014 write or paste`),u(" it there directly, and /review and the writer both read it. /style-guide compile then turns its"),u(" mechanical parts into checks.")],restart:!1};if(s.guides.length===0)return{lines:[te("\u2139","This Document360 project has no style guides yet."),u(` Admins create them in the portal, or write your own at ${ft}/style-guide.md.`)],restart:!1};if(!t)return{lines:["Style guides in this Document360 project:","",...s.guides.map((A,R)=>{let D=[A.language_code,A.created_by_name,A.created_at?.slice(0,10)].filter(Boolean).join(" \xB7 ");return` ${R+1} ${A.name??A.id}${A.is_default?u(" (default)"):""}${D?u(` ${D}`):""}`}),"",u(" Pull one: /style-guide pull 1 (or paste its id)")],restart:!1};let i=Number(t),a=Number.isInteger(i)&&i>=1&&i<=s.guides.length?s.guides[i-1]:s.guides.find(S=>S.id===t);if(!a)return{lines:[te("\u2717",`No style guide numbered or identified by "${t}". Run /style-guide pull to list them.`)],restart:!1};let l=await lj(o,r,a.id,{langCode:a.language_code});if(l.kind!=="ok"){let S=l.kind==="notFound"?"Document360 could not find it (style guides are per language)":l.reason;return{lines:[te("\u2717",`Could not read "${a.name??a.id}" \u2014 ${S}.`)],restart:!1}}let c=(l.guide.content??"").trim();if(!c)return{lines:[te("\u26A0",`"${a.name??a.id}" has no content yet \u2014 nothing to pull.`)],restart:!1};let p=k$(e),m=[];if(wf(p))try{ff(`${p}.bak`,$$(p,"utf8"),"utf8"),m.push(u(` Your previous guide is at ${ft}/style-guide.md.bak`))}catch{}let $=c.length>y$?c.slice(0,y$):c,w=`<!-- Pulled from Document360: "${a.name??a.id}" (${new Date().toISOString().slice(0,10)}). Edit freely \u2014 /style-guide pull overwrites this file. -->
|
|
436
|
+
|
|
437
|
+
`;hj(fj(p),{recursive:!0}),ff(p,`${w}${$}
|
|
438
|
+
`,"utf8");let C=Rn(e)??{projectId:""};return Pc({...C,styleGuide:{...C.styleGuide,pulledFrom:{styleGuideId:a.id,name:a.name??a.id,pulledAt:new Date().toISOString(),contentHash:mj("sha1").update($).digest("hex").slice(0,16)}}},e),{lines:[te("\u2713",`Pulled "${a.name??a.id}" into ${ft}/style-guide.md (${$.length.toLocaleString()} characters).`),...m,u(" This is PROSE, not rules \u2014 /review judges against it, and the writer now writes to it."),u(" Turn its mechanical parts into checks: /style-guide compile"),u(" Restarting the agent so it writes to the new guide\u2026")],restart:!0}}function $j(e){let t=Ki(e).rules.filter(n=>n.pack.toLowerCase()===qi.toLowerCase()).map(n=>n.id);return{prompt:nj({guide:oj(e),packName:qi,existingRuleIds:t}),display:"/style-guide compile"}}function vj(e){let t=ij(e),n=wf(t)?$$(t,"utf8").trim():"";return!n||!/^## /m.test(n)?{kind:"nothing",lines:[te("\u2139","No reviewer comments have been read yet, so there is nothing to learn from."),u(" Reviewers comment on your drafts in Document360; /comments reads them, and every read"),u(` keeps a copy in ${ft}/reviewer-notes.md. Run /comments first.`)]}:{kind:"run",prompt:sj({notes:n,existingRules:rj(e),houseRulesFile:`${ft}/house-rules.md`}),display:"/style-guide learn"}}function x$(){return[u(` Read what it wrote: git diff ${ft}/house-rules.md`),u(" These rules apply from now on \u2014 the writer follows them and /review judges against them."),u(" Disagree with one? Delete the line. It is your file, and nothing regenerates it."),u(" Restarting the agent so it writes to the new rules\u2026")]}function R$(){return[u(` Review what it wrote: git diff ${ft}/styles/${qi}/`),u(` Anything it could not check mechanically is listed in ${ft}/styles/${qi}/UNCHECKABLE.md \u2014 /review judges those.`),u(` Turn them on when you are happy: /style-guide use ${qi.toLowerCase()} (they start as warnings, never blocking)`)]}var We=(e,t)=>`${e} ${t}${e===1?"":"s"}`,mf=e=>/^v\d/i.test(e)?e:`v${e}`;function xj(e){let t=(e.description??`${e.name} style guide`).trim().replace(/\s+/g," "),n=/^(.{0,72})(?:[.,:;—]|$)/.exec(t)?.[1]?.replace(/[.,:;—\s]+$/,"").trim();if(n&&n.length>0)return n;let o=t.slice(0,72),r=o.lastIndexOf(" ");return`${r>20?o.slice(0,r):o}\u2026`}function S$(e){let t={error:0,warning:0,suggestion:0};for(let n of e)t[n.severity]=(t[n.severity]??0)+1;return["error","warning","suggestion"].filter(n=>t[n]>0).map(n=>`${t[n]} ${n}`).join(" \xB7 ")}function Rj(e){let n=Rn(e)?.styleGuide?.pulledFrom;return n?`${ft}/style-guide.md \u2014 pulled ${n.pulledAt.slice(0,10)} from "${n.name}"`:wf(k$(e))?`${ft}/style-guide.md (yours)`:"the built-in default"}function Sj(e){let t=Rn(e),n=Ki(e),o=(t?.styleGuide?.packs??[]).filter(Boolean),r=n.packs.filter(c=>c.name.toLowerCase()===qn),s=n.packs.filter(c=>{let p=c.name.toLowerCase();return p!==qn&&p!=="d360"}),i=t?.styleGuide?.packs===void 0&&s.length>0,a=[`Style guide: ${Rj(e)}`,`Rule packs: ${s.length>0?s.map(c=>`${c.name.toLowerCase()} ${mf(c.version)}`).join(", ")+(i?u(" (the default \u2014 nobody has chosen yet)"):""):u("none chosen")}`,`Always on: ${u(`d360 (correctness, built in \u2014 ${We(ms.filter(c=>c.id.startsWith("D360.")).length,"rule")})`)}`];for(let c of r)a.push(` ${u(`${c.name.toLowerCase()} ${mf(c.version)} (anti-slop \u2014 ${We(c.ruleCount,"rule")})`)}`);r.length>0&&(a.push(u(" Every article here is machine-written, so these cannot be switched off by")),a.push(u(" choosing another pack. styleGuide.humanise: false turns them off deliberately.")));let l=[...ms.map(c=>({severity:c.severity})),...n.rules.map(c=>({severity:c.severity}))];a.push("",`${We(l.length,"rule")} active \xB7 ${S$(l)}`);try{let c=Vi({cwd:e}),p=c.findings.filter($=>!$.baselined),m=p.filter($=>$.severity==="error").length;a.push(""),a.push(m===0?te("\u2713",`No style errors across the docs${p.length>0?`, though ${We(p.length,"other issue")} ${p.length===1?"is":"are"} reported`:""}.`):te("\u2717",`${We(m,"style error")} \u2014 /lint --blocked shows them, /lint --blocked --fix corrects them.`)),c.baselinedCount>0&&a.push(te("\u2139",`${We(c.baselinedCount,"issue")} ${c.baselinedCount===1?"was":"were"} already in your articles when this style guide was chosen, so ${c.baselinedCount===1?"it never blocks":"they never block"} publishing.`)),c.ruleErrors.length>0&&a.push(te("\u26A0",`${We(c.ruleErrors.length,"rule")} could not be loaded: ${c.ruleErrors.slice(0,2).map($=>`${$.ruleId} (${$.reason})`).join("; ")}`));for(let $ of c.ruleWarnings.slice(0,2))a.push(te("\u26A0",$.reason))}catch{}return a.push(""),a.push(u(" See them all: /style-guide list \xB7 change: /style-guide use \xB7 one rule: /style-guide explain <rule>")),b$(Rn(e)?.styleGuide)&&(a.push(""),a.push("A guide built for software documentation is installed, and these docs are not on it:"),a.push(` Move to it /style-guide use ${yf}`),a.push(" Stay as you are /style-guide keep"),a.push(u(" Several rules in a general-prose guide are wrong for software documentation. This one was")),a.push(u(" measured on real knowledge bases, rule by rule, and nothing in it can block a publish."))),kf(e)&&(a.push(""),a.push("Nobody has settled this yet, and it is a decision \u2014 nothing above changed anything:"),a.push(" Happy with these rules? /style-guide keep"),a.push(" Want a stricter standard? /style-guide use microsoft (or google)"),a.push(u(" Worth settling now rather than later: it shapes every article written from here, and")),a.push(u(" changing it once a knowledge base exists means going back over what is already written."))),a}function C$(e){let t=Rn(e),n=new Set(gf(t?.styleGuide)),o=hf(e),r=new Map;for(let a of o)for(let l of a.rules){if(!l.tunedBy)continue;let c=l.id.slice(0,l.id.lastIndexOf(".")).toLowerCase();r.set(c,[...r.get(c)??[],l])}let s=["Rule packs you can turn on:",""],i=Math.max(12,...o.map(a=>a.name.length));for(let a of o){let l=a.name.toLowerCase(),c=n.has(l),p=l===qn,m=c?"\u2713":"\xB7",$=p?u("(always on)"):c?u("(active)"):"",w=a.local?u(" [yours]"):"",C=a.rules.filter(R=>!R.tunedBy),S=a.rules.filter(R=>R.tunedBy);s.push(` ${m} ${l.padEnd(i)}${w} ${a.description??""}`),s.push(` ${u(`${We(C.length,"rule")} \xB7 ${S$(C)} \xB7 ${mf(a.version)}`)} ${$}`),S.length>0&&s.push(` ${u(`${We(S.length,"rule")} here tune${S.length===1?"s":""} another pack: ${S.map(R=>R.id).join(", ")}`)}`);let A=r.get(l)??[];A.length>0&&s.push(` ${u(`${We(A.length,"rule")} tuned by ${[...new Set(A.map(R=>R.tunedBy.pack.toLowerCase()))].join(", ")}`)}`),a.errors.length>0&&s.push(te("\u26A0",`${We(a.errors.length,"rule")} in this pack could not be loaded \u2014 /style-guide explain names them.`))}return o.every(a=>a.name.toLowerCase()===qn)&&(s.push(""),s.push(u(" The Microsoft and Google style guides are not installed in this build yet."))),s.push(""),s.push(u(" Turn one on: /style-guide use <name> (this replaces the chosen set, it does not add to it)")),s.push(u(" Several: /style-guide use microsoft,google")),s.push(u(" Back to none: /style-guide use none")),s}function Cj(e,t){if(!t)return[te("\u26A0","Name a rule: /style-guide explain Humanise.EmDash")];let n=Ki(e),o=ms.find(p=>p.id.toLowerCase()===t.toLowerCase()),r=n.rules.find(p=>p.id.toLowerCase()===t.toLowerCase())??n.rules.find(p=>p.tunedBy?.localId.toLowerCase()===t.toLowerCase());if(!o&&!r){let p=n.errors.find($=>$.ruleId.toLowerCase()===t.toLowerCase());if(p)return[te("\u26A0",`${p.ruleId} could not be loaded.`),u(` ${p.reason}`),...p.file?[u(` Edit ${ft}/styles/${p.file}`)]:[]];let m=[...ms.map($=>$.id),...n.rules.map($=>$.id),...n.errors.map($=>$.ruleId)].filter($=>$.toLowerCase().includes(t.toLowerCase())).slice(0,5);return[te("\u26A0",`No active rule called "${t}".`),...m.length>0?[u(` Did you mean: ${m.join(", ")}`)]:[u(" /style-guide list shows the active packs.")]]}let s=o?.id??r.id,i=o?.severity??r.severity,a=r?.tunedBy,l=o?"built in (correctness \u2014 always on)":`pack: ${r.pack.toLowerCase()}`,c=[`${s} ${i} \xB7 ${l}${a?" \xB7 tuned by you":""}`,""];if(c.push(` ${o?.summary??r.message}`),r?.link&&c.push(u(` ${r.link}`)),r?.degraded&&(c.push(""),c.push(te("\u26A0",`This rule is translated approximately: ${r.degraded}. It may match slightly more than the original does.`))),a&&r?.tuning){let p=r.tuning;c.push(""),c.push(u(` Ours ${r.pack.toLowerCase()}, declared ${r.declaredSeverity}`)),c.push(u(` Your tweak ${ft}/styles/${a.file}`));for(let m of p.added)c.push(u(` + ${m.key.padEnd(9)} ${m.values.join(", ")}`));for(let m of p.removed)c.push(u(` - ${m.key.padEnd(9)} ${m.values.join(", ")}`));for(let m of p.restated)c.push(u(` ${m.padEnd(9)} restated`));for(let m of p.alreadyPresent)c.push(u(` ${m.key.padEnd(9)} ${m.values.join(", ")} \u2014 already in the rule, kept once`))}a&&r?.check.kind==="existence"&&(c.push(""),c.push(u(` Pattern ${r.check.re.source}`)));try{let p=Vi({cwd:e}).findings.filter($=>$.ruleId===s),m=p.filter($=>!$.baselined);c.push(""),c.push(p.length===0?" Currently: no findings.":` Currently: ${We(m.length,"finding")}${p.length!==m.length?`, plus ${p.length-m.length} baselined and hidden`:""}.`)}catch{}return c.push(""),o?(c.push(u(" Built-in checks are grounded in your product's own source and cannot be switched off \u2014 they")),c.push(u(" catch defects of fact, not matters of taste."))):(c.push(i==="error"?u(' This one BLOCKS publishing \u2014 your config sets it to "error" deliberately.'):a&&r?.declaredSeverity==="error"?u(" Tuning a rule makes it a warning, so it no longer blocks publishing."):u(" Style rules never block publishing. Fix it when you want to; it will not hold a page back.")),i!=="error"&&a&&r?.declaredSeverity==="error"&&c.push(u(` Put the block back: add "${s}": "error" to styleGuide.rules in ${ft}/config.json`)),c.push(u(` Silence it everywhere: add "${s}": "off" to styleGuide.rules in ${ft}/config.json`)),i!=="error"&&c.push(u(" Silence one passage: <!-- vale "+s+" = NO --> \u2026 <!-- vale "+s+" = YES -->"))),c}function bf(e,t){let n=(t??"").trim();if(!n){let w=hf(e).filter(R=>R.name.toLowerCase()!==qn),C=new Set(gf(Rn(e)?.styleGuide).map(R=>R.toLowerCase())),S=R=>R.toLowerCase()===yf?0:1,A=w.sort((R,D)=>S(R.name)-S(D.name)||R.name.localeCompare(D.name)).map(R=>({cmd:`/style-guide use ${R.name.toLowerCase()}`,desc:`${xj(R)} \u2014 ${R.rules.length} rules${C.has(R.name.toLowerCase())?" (active now)":""}`}));return{lines:[],restart:!1,pick:{title:"Which writing rules should these docs follow?",lead:"Pick below. Whichever you choose, every article here is held to it \u2014 nothing stays exempt.",options:[...A,{cmd:"/style-guide use none",desc:"the built-in checks only \u2014 correctness and anti-slop"}]}}}let o=n.toLowerCase()==="none"?[]:n.split(/[,\s]+/).map(w=>w.trim().toLowerCase()).filter(Boolean),r=new Map(hf(e).map(w=>[w.name.toLowerCase(),w])),s=o.filter(w=>!r.has(w));if(s.length>0)return{lines:[te("\u2717",`No rule pack named ${s.map(w=>`"${w}"`).join(", ")}.`),"",...C$(e)],restart:!1};let i=Rn(e)??{projectId:""},{declinedUpgrade:a,...l}=i.styleGuide??{},c=(i.styleGuide?.packs??[]).map(w=>w.trim().toLowerCase()).filter(Boolean);Pc({...i,styleGuide:{...l,packs:o,decidedAt:new Date().toISOString()}},e),w$();let p=[te("\u2192",`Switching to: ${o.length>0?o.join(", "):"the built-in checks only"}${o.includes(qn)?"":` (+ ${qn}, always on)`}\u2026`)],m,$=[];try{let w=X1(e),C=w?Object.values(w.entries).reduce((R,D)=>R+D.count,0):0;if(w){try{ff(`${J1(e)}.bak`,JSON.stringify(w,null,2),"utf8")}catch{}Q1(e)}let S=Vi({cwd:e}),A=new Set(S.findings.map(R=>R.path)).size;if(S.findings.length===0)p.push(te("\u2713",A===0?"No articles yet \u2014 everything you write from here is held to the full set.":"Your articles are already clean against these rules."));else{p.push(te("\u26A0","Every article is held to the new rules. Nothing stays exempt."),"",u(` ${We(S.findings.length,"finding")} across ${We(A,"article")} ${S.findings.length===1?"is":"are"} now live.`)),C>0&&(p.push(u(` ${We(C,"finding")} accepted under your previous guide ${C===1?"is":"are"} not carried over.`)),p.push(u(` Your previous record is at ${ft}/style-baseline.json.bak`))),p.push(""),p.push(te("\u2713","Nothing blocks publishing \u2014 no style-pack rule can."));let R=$n(e,["--fix"],S.findings);R.lines.length>0&&p.push("",...R.lines);let D=R.fixed>0?Vi({cwd:e}):S,W=D.findings.length,H=new Set(D.findings.map(J=>J.path)).size;W===0?p.push(te("\u2713","That was all of them \u2014 your articles now match the new guide.")):m={findings:W,articles:H,cmd:"/review --all --fix",...R.fixed>0?{outOf:S.findings.length}:{}},$=[...new Set(D.findings.map(J=>J.path))]}Z1(e,{packs:o,from:c,articlesWithFindings:$})}catch(w){p.push(te("\u26A0",`The packs are active, but reading your articles failed: ${w instanceof Error?w.message:String(w)}`)),p.push(u(" Run /lint to see the current state before publishing."))}return p.push(...v$(e,`/style-guide use ${n}`)),p.push(u(" Restarting the agent so it writes to the new rules\u2026")),{lines:p,restart:!0,...m?{editorial:m}:{}}}function Pj(e){return[e.title,u(` ${e.lead}`),"",...e.options.map(t=>` ${t.cmd}`.padEnd(38)+u(t.desc))]}function $f(e){let t=e.outOf?`${e.findings} of the ${e.outOf} findings`:We(e.findings,"finding");return[te("\u2192",`${t} across ${We(e.articles,"article")} ${e.findings===1?"needs":"need"} a read, not a swap.`),u(` ${e.cmd} reads each one and rewrites it. Nothing is blocking your publishing in the meantime.`)]}function Aj(e,t){let n=(t??"").trim().toLowerCase()==="skip",o=tj(e);if(!o)return[te("\u2713","No sweep is owed \u2014 your articles have been read against the guide they follow.")];let r=o.packs.length>0?o.packs.join(", "):"the built-in checks";if(n)return ej(e),[te("\u2713",`Fine \u2014 I won't raise the ${r} sweep again.`),"",u(` ${We(o.pending,"article")} still ${o.pending===1?"has":"have"} not been read against it.`),u(" /review --all --fix does the sweep whenever you want it.")];let s=o.total-o.pending;return[te("\u2192",`${o.pending} of your ${We(o.total,"article")} still ${o.pending===1?"needs":"need"} a read against ${r}.`),"",...s>0?[u(` ${s} read so far.`)]:[],u(" /review --all --fix reads the rest and rewrites them."),u(" /style-guide sweep skip stops me raising it.")]}async function Ac(e,t){let{sub:n,value:o}=gs(e),r=s=>{for(let i of s)console.log(i);console.log("")};switch(n){case"list":return r(C$(t.cwd)),{kind:"continue"};case"explain":return r(Cj(t.cwd,o)),{kind:"continue"};case"triage":return r(yj(t.cwd)),{kind:"continue"};case"off":case"on":return r(gj(t.cwd,o,n==="off")),{kind:"continue"};case"use":{let s=bf(t.cwd,o);return r(s.pick?Pj(s.pick):s.lines),s.editorial&&r($f(s.editorial)),s.restart?{kind:"clear"}:{kind:"continue"}}case"keep":return r(kj(t.cwd)),{kind:"continue"};case"sweep":return r(Aj(t.cwd,o)),{kind:"continue"};case"pull":{let s=await bj(t.cwd,o,t.profileName);return r(s.lines),s.restart?{kind:"clear"}:{kind:"continue"}}case"compile":{let s=$j(t.cwd);return{kind:"forward-to-agent",prompt:s.prompt,display:s.display}}case"learn":{let s=vj(t.cwd);return s.kind==="nothing"?(r(s.lines),{kind:"continue"}):{kind:"forward-to-agent",prompt:s.prompt,display:s.display}}default:return r(Sj(t.cwd)),{kind:"continue"}}}ae();import{lintDocs as Ec,loadStyleGuide as O$,buildReviewPrompt as _$,buildStructureReviewPrompt as Xj,structureReviewDue as Qj,structureFingerprint as Jj,recordStructureReview as Zj,hasCaptureArtifacts as M$,readProjectConfig as Af,DEFAULT_DOCS_DIR as Tf,listArticleFiles as fr,normalizeScope as eI,planPartitions as tI,runPartitioned as U$,partitionCoverage as nI,resolveModelForOperation as F$,stampArticles as oI,snapshotArticles as rI,reviewStalePaths as sI,readReviewerNotes as W$,renderNotesForPrompt as B$,readDocsPlan as iI,CONTENT_CAP_VERSION as Pf}from"document360-engine";import{articlesChangedSince as Tj,isUnadoptedArticle as Ej,docsRootOf as Nj}from"document360-engine";function pr(e,t,n,o){let r=t.map(c=>c.replace(/\\/g,"/"));if(!n)return{changed:[],earned:r,unadopted:[]};let s=[];try{s=Tj(e,n).map(c=>c.replace(/\\/g,"/"))}catch{return{changed:[],earned:r,unadopted:[]}}let i=new Set(s),a=r.filter(c=>!i.has(c)&&Ej(e,c,o)),l=new Set(a);return{changed:s.filter(c=>r.includes(c)),earned:r.filter(c=>!l.has(c)),unadopted:a}}function Dj(e,t){let n=t.replace(/\\/g,"/");try{let o=Nj(e).replace(/\\/g,"/").replace(/\/+$/,"");return o&&n.startsWith(`${o}/`)?n.slice(o.length+1):n}catch{return n}}function ys(e,t,n){if(t.length===0)return null;let o=t.length===1,r=[];r.push(o?`\u26A0 The editor changed nothing in ${Dj(e,t[0])}, so it is not recorded as reviewed.`:`\u26A0 The editor changed nothing in ${t.length} pages, so they are not recorded as reviewed.`),r.push(o?" Nothing here has adopted this page: it came from Document360, it is not in your docs plan, and":" Nothing here has adopted them: they came from Document360, they are not in your docs plan, and"),r.push(o?" nothing records what it was written from. There was nothing for an editor to check it against.":" nothing records what they were written from. There was nothing for an editor to check them against.");for(let i of t)r.push(`/untrack ${i}`);r.push(o?" That disowns it \u2014 the page, its history and its comments stay on Document360, readers see no":" That disowns one \u2014 the page, its history and its comments stay on Document360, readers see no"),r.push(" change, and the markdown is kept. Nothing is deleted.");let s=n.lead&&o?{text:r.join(`
|
|
439
|
+
`),cmd:`/untrack ${t[0]}`}:null;return{lines:r,cta:s}}function Yi(e){return e===0?"The editor found nothing to change":"Editor applied its fixes"}import{listArticleFiles as P$,lintDocs as jj,planFindingPartitions as Ij,planPartitions as Lj,readDocsPlan as Oj,readProjectConfig as _j,runRate as xf,loadCoverage as Mj,coverageGap as Uj,resolveActiveProfile as Fj,DEFAULT_DOCS_DIR as Wj}from"document360-engine";function Rf(e){switch(e.cmd){case"/review":return{concurrency:ko,maxPerPartition:Cf,minutesPerBatch:5};case"/write":return{concurrency:3,minutesPerBatch:4};case"/lint":return{concurrency:3,minutesPerBatch:2};default:return{concurrency:3,minutesPerBatch:2}}}function Bj(e,t){let n=jj({cwd:e,scope:t.scope}).filter(s=>!s.baselined),o=t.flags.has("--blocked")?n.filter(s=>s.severity==="error"):n;if(o.length===0)return null;let r=new Set(o.map(s=>s.path)).size;return{lead:`${o.length} issue${o.length===1?"":"s"} \xB7 ${r} article${r===1?"":"s"}`,articles:r,batches:Ij(o).length}}var Hj=new Set(["/push","/publish"]);function A$(e,t){if(t.cmd==="/lint"){let r=Vn(()=>Bj(e,t));return r?{lead:r.lead,billable:r.articles,batches:r.batches}:null}if(t.cmd==="/catch-up"){let r=Vn(()=>un(e));if(!r)return null;let s=r.hints+r.requests+r.answers+r.directives;if(s===0)return null;let i=Vn(()=>hs(r));return i?{lead:i,billable:0,batches:null}:{lead:`${s} queued item${s===1?"":"s"}`,billable:0,batches:null}}if(t.cmd==="/reuse"){if(t.sub!=="audit")return null;let r=Vn(()=>P$(e,t.scope))?.length??0;return r<4?null:{lead:`${r} article${r===1?"":"s"} read \xB7 one editorial turn`,billable:0,batches:null}}if(t.cmd==="/pull"){let r=Vn(()=>Uj(Mj(e,Fj(e).name)))??0;return r<4?null:{lead:`${r} article${r===1?"":"s"} to import`,billable:0,batches:null}}if(Hj.has(t.cmd)){let r=Vn(()=>P$(e,t.scope))?.length??0;return r<4?null:{lead:`${r} article${r===1?"":"s"}`,billable:0,batches:null}}let n=Gj(e,t);if(!n||n.length<4)return null;let o=Rf(t);return{lead:`${n.length} article${n.length===1?"":"s"}`,billable:n.length,batches:Lj(n,o.maxPerPartition?{maxPerPartition:o.maxPerPartition}:void 0).length}}function Gj(e,t){try{if(t.cmd==="/write"){let n=(_j(e)?.docsDir??Wj).replace(/\/+$/,""),o=Oj(e,n).map(s=>s.path);if(o.length===0)return null;let r=t.scope?o.filter(s=>s===t.scope||s.startsWith(`${t.scope}/`)):o;return t.flags.has("--rewrite")?r:uo(e,n,r)}return t.cmd==="/review"?hr(e,[...t.flags],t.scope):null}catch{return null}}function T$(e,t){let n=dn(e,t);if(!n)return null;let o=n.indexOf(" batch");if(o<0)return null;let r=n.lastIndexOf("\xB7 ",o);return r<0?n:n.slice(r+2)}function dn(e,t){let n=wn(t);if(!n||!Jr(n))return null;let o=A$(e,n);if(!o)return null;let r=Vn(()=>xf(e,n.cmd));if(o.batches===null){let c=r?.minutesPerWave!==void 0?` \xB7 ~${vf(r.minutesPerWave)}`:"";return`${o.lead}${c}`}let s=Rf(n),a=Math.ceil(o.batches/s.concurrency)*(r?.minutesPerWave??s.minutesPerBatch),l=r?.usdPerArticle!==void 0&&o.billable>0?` \xB7 ~${D$(o.billable*r.usdPerArticle)}`:"";return`${o.lead} \xB7 ${o.batches} batch${o.batches===1?"":"es"} \xB7 ~${vf(a)}${l}`}function E$(e,t){let n=wn(t);if(!n||!Jr(n))return null;let o=Vn(()=>xf(e,n.cmd));if(o?.usdPerArticle===void 0)return null;let r=A$(e,n);return!r||r.billable===0?null:r.billable*o.usdPerArticle*Sf}var N$=.7,Sf=1.4;function vf(e){let t=Math.max(1,Math.round(e*N$)),n=Math.max(t,Math.round(e*Sf));if(n<90)return`${t}\u2013${n} min`;let o=r=>r<60?`0h ${r}m`:`${Math.floor(r/60)}h ${r%60}m`;return`${o(t)}\u2013${o(n)}`}function D$(e){let t=e*N$,n=e*Sf;return n>=10?`$${Math.round(t)}\u2013${Math.round(n)}`:`$${t.toFixed(2)}\u2013${n.toFixed(2)}`}function Vn(e){try{return e()}catch{return null}}function Tc(e,t,n,o){if(n<4||o<1)return null;let r=Rf({cmd:t,scope:void 0,flags:new Set,args:[]}),s=Math.ceil(o/r.concurrency),i=Vn(()=>xf(e,t)),a=s*(i?.minutesPerWave??r.minutesPerBatch),l=i?.usdPerArticle!==void 0?` \xB7 ~${D$(n*i.usdPerArticle)}`:"";return`~${vf(a)}${l}`}import{loadProfileMap as aI,resolveActiveProfile as lI}from"document360-engine";import{renderGapsForPrompt as H$,readReaderContract as Ef,renderCorpusTermsForPrompt as G$,scanTerminology as q$,renderReuseForPrompt as V$,scanReuse as K$}from"document360-engine";import{recordRunSample as cI}from"document360-engine";ae();import{readProjectConfig as qj,loadProfileMap as Vj,resolveActiveProfile as Kj,desiredCategoryOrder as Yj,desiredArticleOrder as zj}from"document360-engine";function j$(e){let t=e.replace(/\.(md|markdown)$/i,"").replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}var I$=e=>e.replace(/\\/g,"/").split("/").pop()??e;function ws(e,t){try{if(!qj(e))return[];let n=Kj(e,t),o=Vj(e,n.name);if(!o)return[];let r=new Map;for(let m of zj(o)){let $=r.get(m.categoryPath);$?$.push(m):r.set(m.categoryPath,[m])}let s=Yj(o),i=Math.min(...s.map(m=>m.path.split("/").length),Number.MAX_SAFE_INTEGER),a=new Map;for(let m of s){let $=m.path.split("/").slice(0,-1).join("/"),w=a.get($);w?w.push(m):a.set($,[m])}let l=[],c=(m,$)=>{for(let w of(a.get(m)??[]).sort((C,S)=>C.order-S.order)){let C=" ".repeat($);l.push(`${C}${j$(I$(w.path))}`);for(let S of(r.get(w.path)??[]).sort((A,R)=>A.order-R.order))l.push(`${C} ${j$(I$(S.path))}`);c(w.path,$+1)}},p=s.find(m=>m.path.split("/").length===i);return c(p?p.path.split("/").slice(0,-1).join("/"):"",0),l}catch{return[]}}async function L$(e,t){let n=ws(t.cwd,t.profileName);if(n.length===0)return console.log(u("No documentation structure yet \u2014 run /init and author some articles first.")),{kind:"continue"};console.log(Z("Documentation order (categories \u2192 articles):"));for(let o of n)console.log(o);return console.log(""),{kind:"continue"}}function Nf(e,t){return pi(e,fr(e,t))}function Df(e,t){return sI(e,fr(e,t),Pf)}function ks(e){return e.includes("--blocked")||e.includes("--stale")}function hr(e,t,n){return t.includes("--blocked")?Nf(e,n):t.includes("--stale")?Df(e,n):fr(e,n)}function jf(e,t,n){let o;try{o=iI(e)}catch{return[]}let r=new Map(o.map(i=>[i.path.replace(/\\/g,"/"),i])),s=[];for(let i of n){let a=i.replace(/\\/g,"/").replace(`${t}/`,""),l=r.get(a);l&&s.push({path:i,type:l.type,...l.purpose?{purpose:l.purpose}:{}})}return s}function Y$(e,t){let n=Af(e);if(!n)return null;let o=(n.docsDir??Tf).replace(/\\/g,"/").replace(/\/+$/,""),r=t.includes("--fix"),s=ks(t),i=t.find(A=>!A.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),a=Ec({cwd:e}),l=i?eI(o,i):"",c=l?a.filter(A=>A.path===`${o}/${l}`||A.path.startsWith(`${o}/${l}/`)):a,p=s?hr(e,t,i):void 0,m=p?c.filter(A=>p.includes(A.path)):c,$=i||s?"":ws(e).join(`
|
|
440
|
+
`),w=M$(e,n),C=_$({docsRoot:o,scope:i,styleGuide:O$(e),deterministicFindings:m,fix:r,structure:$||void 0,screenshots:w,...p?{paths:p}:{},reviewerNotes:B$(W$(e),p??fr(e,i)),openGaps:H$(e,p??fr(e,i)),readerContract:Ef(e),corpusTerms:G$(q$(e)),corpusReuse:V$(K$(e)),planRows:jf(e,o,p??fr(e,i))}),S=t.includes("--blocked")?" --blocked":t.includes("--stale")?" --stale":"";return{prompt:C,display:`/review${i?` ${i}`:""}${S}${r?" --fix":""}`}}var uI=e=>"ruleId"in e,ko=3,Cf=3;function If(e,t){let n=Y$(e,t);if(!n)return null;let o=t.find(A=>!A.startsWith("--"))?.replace(/\\/g,"/").replace(/\/+$/,""),r=hr(e,t,o),s=tI(r,{maxPerPartition:Cf});if(s.length<=1)return{kind:"single",...n};let i=Af(e),a=(i?.docsDir??Tf).replace(/\\/g,"/").replace(/\/+$/,""),l=t.includes("--fix"),c=O$(e),p=Ec({cwd:e}),m=W$(e),$=M$(e,i),w=Ef(e),C=G$(q$(e)),S=V$(K$(e));return{kind:"partitioned",partitions:s,articles:r.length,wholeKb:!o&&!ks(t),display:n.display,promptFor:A=>{let R=new Set(A.paths);return _$({docsRoot:a,styleGuide:c,deterministicFindings:p.filter(D=>R.has(D.path)),fix:l,screenshots:$,paths:A.paths,reviewerNotes:B$(m,A.paths),openGaps:H$(e,A.paths),readerContract:w,corpusTerms:C,corpusReuse:S,planRows:jf(e,a,A.paths)})}}}function zi(e,t,n){let o=Af(e);if(!o||t.find(l=>!l.startsWith("--"))||n?.kind==="single"&&!ks(t))return null;let s=(o.docsDir??Tf).replace(/\\/g,"/").replace(/\/+$/,""),i=ws(e);if(Object.keys(aI(e,lI(e).name)?.categories??{}).length<2)return null;let a=i.join(`
|
|
441
|
+
`);return Qj(e,a,Pf)?{prompt:Xj({docsRoot:s,structure:a,planRows:jf(e,s,fr(e)).map(l=>`${l.path} ${l.type}`).join(`
|
|
442
|
+
`),readerContract:Ef(e)}),display:"/review \u2014 the shape of your knowledge base",fingerprint:Jj(a,Pf)}:null}function Lf(e,t){if(!ks(t))return null;let n=t.find(m=>!m.startsWith("--"));if(hr(e,t,n).length>0)return null;let o=t.includes("--blocked"),r=!!n&&n.endsWith(".md"),s=n?r?" here":` in ${n}`:"",a=o?`\u2713 Nothing is blocked${s} \u2014 ${n&&r?"it has":"every article has"} been through an editorial read.`:`\u2713 ${r?"This article has":`Every article${s} has`} already been read by the current editor \u2014 nothing to re-read.`,l=`/push${n?` ${n}`:" --all"}`,c=Kt(e,{text:`${l} saves ${r?"it":"what has changed"} to Document360 as ${r?"a draft":"drafts"}.`,cmd:l},"",n,"/review"),p=Ze(e,Y$(e,t)?.display??"");return{lines:[a,` ${c.text}`],closed:p,cta:c}}async function z$(e,t){let n=Lf(t.cwd,e);if(n){console.log(Q(n.lines[0]));for(let s of n.lines.slice(1))console.log(u(s));for(let s of n.closed)console.log(Q(s));let r=zi(t.cwd,e,null);return r&&(console.log(u("One thing left: no editor has looked at how your docs are organized since it last changed.")),await X$(t,r)),{kind:"continue",ownNext:!0}}if(go("review",e)){let r=ls(t.cwd,"review",e,t.profileName);if(r.length>0){for(let s of r)console.log(u(s));return{kind:"continue"}}}let o=If(t.cwd,e);return o?o.kind==="single"?{kind:"forward-to-agent",prompt:o.prompt,display:o.display}:await dI(t,o,e.includes("--fix"),e.find(r=>!r.startsWith("--")),e):(console.log(L(be)),{kind:"continue"})}async function X$(e,t){console.log(""),console.log(u(`Reviewing ${t.display.replace(/^\/review — /,"")}\u2026`));let n=!1;try{for await(let o of U$({cwd:e.cwd,partitions:[{label:"the shape of your knowledge base",paths:[]}],promptFor:()=>t.prompt,concurrency:1,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:F$(e.cwd,"standard").model,scope:"review"}))o.type==="run_done"&&(n=o.results.some(r=>r.ok))}catch{return}n&&Zj(e.cwd,t.fingerprint)}async function dI(e,t,n,o,r=[]){let{model:s}=F$(e.cwd,"standard"),i=zi(e.cwd,r,t),a=Tc(e.cwd,"/review",t.articles,t.partitions.length);console.log(u(`Reviewing ${t.articles} article${t.articles===1?"":"s"} in ${t.partitions.length} batches (\u2264${ko} editors at once) on ${s}${n?", applying fixes":", report only"}${a?` \xB7 ${a}`:""}\u2026`));let l=Date.now(),c=n?rI(e.cwd):null,p=[],m=0,$=new os;$.start();let w={aborted:!1,partitions:0,failed:0,notRun:0,producedNothing:!0};try{for await(let R of U$({cwd:e.cwd,partitions:t.partitions,promptFor:t.promptFor,concurrency:ko,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:s,scope:"review"}))if(R.type==="partition_status")R.status==="running"?console.log(u(` \u25B8 ${R.label} \u2014 reviewing\u2026`)):R.status==="done"?console.log(Q(` \u2713 ${R.label}`)):console.log(L(` \u2717 ${R.label}`));else if(R.type==="run_done"){let D=nI(t.partitions,R.results);w={aborted:!!R.aborted,partitions:t.partitions.length,failed:D.failed.length,notRun:D.notRun.length,...R.blocked?{blocked:R.blocked}:{},...R.allEmpty?{allEmpty:!0}:{},...R.bailedEmpty?{bailedEmpty:!0}:{}},console.log(""),console.log(`${R.results.length-D.failed.length}/${t.partitions.length} batches reviewed.`),D.failed.length&&console.log(F(`\u26A0 ${D.failed.length} not reviewed: ${D.failed.map(H=>H.label).join(", ")}`)),D.notRun.length&&console.log(F(`\u26A0 ${D.notRun.length} batch${D.notRun.length===1?"":"es"} never started \u2014 their articles are untouched.`)),R.blocked&&console.log(F(`\u26A0 ${R.blocked}`)),R.allEmpty&&console.log(F("\u26A0 No editor produced any work this run \u2014 nothing was reviewed or changed."));for(let H of Of(t,!!i))console.log(u(H));if(n&&!R.allEmpty&&!R.blocked){let H=pr(e.cwd,D.covered,c,e.profileName);if(p.push(...H.unadopted),m=H.changed.length,H.earned.length>0)try{oI(e.cwd,H.earned,St("review"))}catch{}}let W=$.stop();if(console.log(u(kn(zt(l,R.results,R.totalCostUsd,Date.now(),W.activeSeconds)))),!R.allEmpty&&!R.blocked){let H=R.results.filter(J=>J.ok).length;cI(e.cwd,"review",{articles:D.covered.length,waves:Math.ceil(H/Math.max(1,ko)),seconds:W.activeSeconds,costUsd:R.totalCostUsd})}}}catch(R){return $.stop(),console.log(L(`Review failed: ${R.message}`)),{kind:"continue"}}if($.stop(),i&&!w.aborted&&await X$(e,i),n&&ln(w))for(let R of Ze(e.cwd,t.display))console.log(Q(R));if(!n)return{kind:"continue"};let C=$n(e.cwd,["--fix"],Ec({cwd:e.cwd,scope:o}));for(let R of C.lines)console.log(R);let A=Ec({cwd:e.cwd,scope:o}).filter(R=>!R.baselined).filter(R=>uI(R)&&R.severity==="error");if(console.log(""),A.length>0){let R=Ee("/lint","--blocked --fix",o);console.log(u(`${Yi(m)}, but ${A.length} style error${A.length===1?"":"s"} remain \u2014 ${R} clears them (finding them costs nothing, one pass corrects them). It is the last paid pass before publishing: anything still standing after a second attempt is reported for a person rather than run again.`))}else{let R=ys(e.cwd,p,{lead:m===0});if(R)for(let D of R.lines)console.log(F(D));if(R?.cta)return{kind:"continue",ownNext:!0};console.log(u(Kt(e.cwd,{text:`\u2713 ${m===0?"Reviewed \u2014 nothing needed changing":"Reviewed and fixed"}. /push --all saves the articles to Document360 as drafts.`,cmd:"/push --all"},"",o).text))}return{kind:"continue",ownNext:!0}}function Of(e,t=!1){return e.partitions.length<2?[]:t?["Each editor saw one slice of the docs, so no one of them judged the set as a whole.","They did all see how the whole set spells its terms; two different WORDS for one thing still need a person."]:[`Each editor saw one slice of the docs, so reading order ${e.wholeKb?"ACROSS categories":"ACROSS the rest of the knowledge base"} was not judged.`,"They did all see how the whole set spells its terms; two different WORDS for one thing still need a person.","/structure shows the reading order if you want to check it yourself."]}ae();import{readProjectConfig as pI}from"document360-engine";function _f(e,t){if(!pI(e))return null;let n=t.find(r=>!r.startsWith("--"));return{prompt:[`Reorder the articles within ${n?`the "${n}" category`:"each category"} to the best reading order.`,"Follow the manage-structure skill: decide the ideal order with senior-editor judgment per the doc-genre","playbook (overview / mental-model first; reference and troubleshooting/FAQ last), then APPLY it with the","d360_reorder_articles tool: one category at a time, all paths in the same category folder.",n?"":"If the CATEGORY order itself reads wrong too, fix that first with the d360_reorder_categories tool (folder paths under one parent, in the desired order).","Do not rename files or folders or edit the map by hand; the tools handle it. Report the new order, and","remind me it reaches Document360 on the next /push."].filter(Boolean).join(`
|
|
443
|
+
`),display:`/reorder${n?` ${n}`:""}`}}async function Q$(e,t){if(go("reorder",e)){let o=ls(t.cwd,"reorder",e,t.profileName);if(o.length>0){for(let r of o)console.log(u(r));return{kind:"continue"}}}let n=_f(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(L(be)),{kind:"continue"})}ae();import{readProjectConfig as hI}from"document360-engine";function Mf(e,t){if(!hI(e))return null;let n=t.filter(r=>!r.startsWith("--")).join(" ").trim();return{prompt:[n?`Restructure the docs: ${n}`:"Review how the docs are organised and tell me what should change.","","Follow the manage-structure skill.",n?"Apply the change with the right tool: d360_move_articles to refile, split or merge; d360_rename_category to rename; d360_nest_category to put a category inside another or lift one back out; d360_reorder_articles or d360_reorder_categories if only the order is wrong.":["Read the current structure first, then judge it as a senior technical writer would: is every article","filed where a reader would look for it, has any category grown past one topic and want splitting, are","two categories really the same one, does any name still describe what is in it, and does any nesting","earn the click it costs the reader?","","Report what you would change and why, as a short numbered list, and STOP THERE. Do not apply anything","yet: reshaping a knowledge base is my call, not yours. If nothing needs changing, say so plainly."].join(`
|
|
444
444
|
`),"","Do not rename files or folders or edit the map by hand; the tools handle the whole refactor.","Moving an article does not change its public URL, so say so rather than warning me about broken links.","A category a merge leaves empty is handled for me: it goes locally and is hidden from readers on the","next push, never deleted. Say that in those words rather than telling me to tidy it up myself.","When you have applied something, remind me it reaches Document360 on the next /push."].filter(Boolean).join(`
|
|
445
|
-
`),display:`/restructure${n?` ${n}`:""}`}}async function
|
|
446
|
-
`)}function Xh(e,t={}){let n=R1(e,t.profileName),o=[];if(n.rows.length===0){o.push(Z("Publish readiness")),o.push("");let p=C1(n.coverage),m=n.neverPushed.length;return o.push(n.tracked===0?m>0?`${V("\u25CB",Ue.gray)}Nothing here is on Document360 yet.`:`${V("\u25CB",Ue.gray)}No articles are tracked yet. /write authors them, /push saves them to Document360.`:p>0||m>0?`${V("\u2713",Ue.green)}All ${n.tracked} tracked articles are live and unchanged.`:`${V("\u2713",Ue.green)}All ${n.tracked} articles are live and unchanged \u2014 nothing is waiting on you.`),o.push(...N1(n)),n.neverPushed.length>0&&(o.push(""),o.push(...Zb(n))),n.orphans.length>0&&o.push(...t$(n)),n.unadopted.length>0&&(o.push(""),o.push(...e$(n))),o.push(""),o.push(u(" Free \u2014 /status reads your local files and the last sync. It calls nothing.")),o}let r=n.rows.length,s=n.blocked.length;o.push(Z("Publish readiness")+u(` ${r} article${r===1?"":"s"} not yet settled with readers \xB7 ${s===0?"nothing blocked":`${s} blocked`}`)),o.push(""),t.all&&(o.push(...E1(n,t.width??100)),o.push(""));for(let p of T1(n)){o.push(` ${V(p.glyph,p.paint)}${p.title}${p.fix?u(` ${p.fix}`):""}`);for(let m of p.items.slice(0,Un))o.push(u(` ${m}`));p.items.length>Un&&o.push(u(` \u2026and ${p.items.length-Un} more`)),o.push("")}let i=Zb(n);i.length>0&&(o.push(...i),o.push(""));let a=e$(n);a.length>0&&(o.push(...a),o.push(""));let l=A1(n);if(l.length>0){for(let p of l)o.push(` ${p}`);o.push("")}let c=n.rows.filter(p=>p.localAhead).length;return c>0&&o.push(u(` ${c} changed here \u2014 /push saves ${c===1?"it":"them"} to Document360 as ${c===1?"a draft":"drafts"}. Readers see nothing until then.`)),n.draftPending.length>0&&(o.push(u(` ${n.draftPending.length} saved on Document360 as ${n.draftPending.length===1?"a draft":"drafts"} and not live \u2014 /publish takes ${n.draftPending.length===1?"it":"them"} to your readers.`)),o.push(u(" That is from your last sync. /pull re-checks what is live."))),n.orphans.length>0&&o.push(...t$(n)),!t.all&&n.rows.length>0&&o.push(u(" /status --all shows every article, gate by gate.")),o.push(""),o.push(u(" Free \u2014 /status reads your local files and the last sync. It calls nothing.")),o}function Zb(e){let t=e.neverPushed.length;if(t===0)return[];let n=[` ${V("\u25CB",Ue.gray)}${t===1?"One article is":`${t} articles are`} written here and ${t===1?"has":"have"} never been saved to Document360`,u(` Your readers cannot see ${t===1?"it":"them"} at all yet \u2014 not even as a draft.`)];for(let o of e.neverPushed.slice(0,Un))n.push(` ${Me(o)}`);return t>Un&&n.push(u(` \u2026and ${t-Un} more`)),n.push(u(" /push --all saves them as drafts; /publish then takes them live.")),n}function e$(e){let t=e.unadopted.length;if(t===0)return[];let n=[` ${V("\u25CB",Ue.gray)}${t===1?"One page here came from Document360 and nothing has adopted it":`${t} pages here came from Document360 and nothing has adopted them`}`,u(` Not in your docs plan, not written by d360-writer, and nothing records what ${t===1?"it says":"they say"}.`),u(` So no editor can check ${t===1?"it":"them"}: a review pass over ${t===1?"it":"them"} comes back having changed nothing.`)];for(let o of e.unadopted.slice(0,Un))n.push(` /untrack ${o.path}`);return t>Un&&n.push(u(` \u2026and ${t-Un} more`)),n.push(u(" Disowning one leaves Document360 untouched \u2014 the page, its history and its comments all stay.")),n}function t$(e){let t=e.orphans.length;return[u(` ${t} article${t===1?"":"s"} on Document360 ${t===1?"is":"are"} not in your docs folder (${Me(e.orphans[0].path,40)}${t>1?`, +${t-1} more`:""}) \u2014 /doctor lists ${t===1?"it":"them"}.`)]}function n$(e){let t=Date.now()-Date.parse(e);if(!Number.isFinite(t)||t<0)return"just now";let n=Math.floor(t/6e4);if(n<2)return"just now";if(n<60)return`${n} minutes ago`;let o=Math.floor(n/60);if(o<24)return`${o} hour${o===1?"":"s"} ago`;let r=Math.floor(o/24);return`${r} day${r===1?"":"s"} ago`}function N1(e){let t=e.coverage;if(!t)return e.tracked===0?[]:["",u(" Nothing has compared this repo with Document360 yet."),"",u(" /pull --status counts what is there.")];if(t.unmapped===0)return[u(` Every Document360 article is tracked here (${t.mappedArticles} of ${t.portalArticles}, checked ${n$(t.at)}).`),...o$(t)];let n=t.portalOnlyCategories.filter(r=>r.articles>0).length,o=["",W(` ${V(Mo,Ue.yellow)}Document360 holds ${t.portalArticles} articles in ${t.portalCategories} categories.`),"",u(` This repo tracks ${t.mappedArticles} of them.`)];return n>0&&(o.push(""),o.push(u(` ${t.unmapped} articles sit in ${n} ${n===1?"category":"categories"} with no folder here.`))),t.declined>0&&(o.push(""),o.push(u(` ${t.declined} more ${t.declined===1?"is one you":"are ones you"} declined with /untrack.`))),o.push(""),o.push(u(` /pull imports them. Checked ${n$(t.at)}.`)),o.push(...o$(t)),o}function o$(e){let t=P1(e);if(t===null||t===0)return[];let n=e.dangling?.articles??[],o=e.dangling?.categories??[],r=["",W(` ${V(Mo,Ue.yellow)}${n.length>0?`${n.length} ${n.length===1?"article":"articles"} here point`:""}${n.length>0&&o.length>0?" \u2014 and ":""}${o.length>0?`${o.length} ${o.length===1?"folder points":"folders point"}`:""} at something Document360 no longer has.`)];r.push("");for(let s of n.slice(0,5))r.push(u(` ${s}`));return n.length>5&&r.push(u(` \u2026and ${n.length-5} more.`)),r.push(""),r.push(u(" Someone deleted them on the portal, or they were replaced by newer articles.")),r.push(""),r.push(u(" /push saves them again for your readers. /untrack drops the ones you no longer want.")),r}async function r$(e,t){let n=e.some(o=>o==="--all"||o==="--full");for(let o of Xh(t.cwd,{profileName:t.profileName,all:n}))console.log(o);return{kind:"continue",ownNext:!0}}ue();import{computeReadiness as D1,retireArticle as j1,retiredPaths as I1,normalizeScope as L1}from"document360-engine";import{select as O1}from"@inquirer/prompts";function Qh(e,t){let n=D1(e,t),o=I1(e,t),r=[Z("Take an article off your readers"),""];if(n.orphans.length>0){r.push(` ${V("\u25CB",u)}On Document360, but not in your docs folder \u2014 the usual reason to retire:`);for(let s of n.orphans.slice(0,8))r.push(u(` ${Me(s.path)}`));n.orphans.length>8&&r.push(u(` \u2026and ${n.orphans.length-8} more`)),r.push("")}if(o.length>0){r.push(` ${V("\u2713",u)}Already retired \u2014 readers do not see ${o.length===1?"it":"these"}:`);for(let s of o.slice(0,5))r.push(u(` ${Me(s)}`));o.length>5&&r.push(u(` \u2026and ${o.length-5} more`)),r.push("")}return n.orphans.length===0&&o.length===0&&(r.push(u(" Nothing obvious to retire \u2014 every tracked article is still in your docs folder.")),r.push("")),r.push(u(" /retire <path> takes one off your readers. Any tracked article can be named, not just these.")),r.push(u(" Nothing is deleted: the article, its history and every reviewer comment stay on Document360.")),r.push(u(" /push puts one back \u2014 reviving is a publish like any other, with the same review.")),r}async function s$(e,t){let n=t.cwd,o=e.find(a=>!a.startsWith("-"));if(!o){for(let a of Qh(n,t.profileName))console.log(a);return{kind:"continue",ownNext:!0}}let r=L1(n,o)||o;if(!(e.includes("--yes")||e.includes("-y"))&&(console.log(""),console.log(W(`This takes "${Me(r)}" off your readers on Document360.`)),console.log(u(" The article, its history and every reviewer comment stay \u2014 nothing is deleted.")),console.log(u(" /push puts it back later if you change your mind.")),console.log(""),await O1({message:"Take it off your readers?",choices:[{name:"No \u2014 leave it as it is",value:"no"},{name:"Yes \u2014 readers stop seeing it",value:"yes"}]})!=="yes"))return console.log(u("Nothing changed.")),{kind:"continue",ownNext:!0};let i=await j1({cwd:n,path:r,profileName:t.profileName,now:new Date().toISOString()});return i.ok?(console.log(i.alreadyHidden?`${V("\u2713")}"${Me(r)}" was already invisible to readers. Recorded as retired, so nothing will offer to publish it again.`:`${V("\u2713")}"${Me(r)}" is no longer visible to your readers.`),console.log(u(" It is still on Document360 with its history and comments intact. /push puts it back.")),{kind:"continue",ownNext:!0}):(console.log(L(`${V("\u2717")}Could not retire "${Me(r)}" \u2014 ${i.error.message}`)),{kind:"continue",ownNext:!0})}ue();import{declineImport as _1,loadDeclinedImports as M1,undoDecline as F1,normalizeScope as U1,resolveActiveProfile as W1}from"document360-engine";import{select as B1}from"@inquirer/prompts";function Jh(e,t){let n={};try{n=M1(e,W1(e,t).name)}catch{}let o=Object.keys(n),r=[Z("Pages on Document360 that are not part of these docs"),""];if(o.length===0)r.push(u(" Nothing is declined. Every article on Document360 in one of your categories is")),r.push(u(" imported into your docs folder when you run /catch-up or /pull."));else{for(let s of o.slice(0,10)){let i=n[s];r.push(` ${V("\u25CB",u)}${i.title??i.path??s}`),i.path&&r.push(u(` was ${Me(i.path)}`)),i.keptAt&&r.push(u(` kept at ${i.keptAt}`))}o.length>10&&r.push(u(` \u2026and ${o.length-10} more`))}return r.push(""),r.push(u(" /untrack <path> disowns an imported page \u2014 nothing on Document360 changes.")),r.push(u(" /untrack --undo <path> puts it back and lets the next /catch-up import it again.")),r}async function i$(e,t){let n=t.cwd,o=e.find(c=>!c.startsWith("-")),r=e.includes("--list")||e.includes("-l"),s=e.includes("--undo");if(r||!o&&!s){for(let c of Jh(n,t.profileName))console.log(c);return{kind:"continue",ownNext:!0}}if(!o)return console.log(L(`${V("\u2717")}Name what to put back: /untrack --undo <path>`)),{kind:"continue",ownNext:!0};let i=U1(n,o)||o;if(s){let c=F1(n,t.profileName,i);return c.ok?(console.log(c.restoredTo?`${V("\u2713")}Put "${Me(c.restoredTo)}" back in your docs folder.`:`${V("\u2713")}No longer declined. /catch-up imports it again on the next run.`),{kind:"continue",ownNext:!0}):(console.log(L(`${V("\u2717")}${c.error.message}`)),{kind:"continue",ownNext:!0})}if(!(e.includes("--yes")||e.includes("-y"))&&(console.log(""),console.log(W(`This stops tracking "${Me(i)}" as one of your docs.`)),console.log(u(" Nothing on Document360 changes \u2014 the page, its history and its comments all stay,")),console.log(u(" and your readers see no difference.")),console.log(u(" The markdown moves to .d360-writer/declined/, so nothing is deleted.")),console.log(u(" /untrack --undo puts it back if you change your mind.")),console.log(""),await B1({message:"Stop tracking it?",choices:[{name:"No \u2014 leave it as it is",value:"no"},{name:"Yes \u2014 it is not one of my docs",value:"yes"}]})!=="yes"))return console.log(u("Nothing changed.")),{kind:"continue",ownNext:!0};let l=_1({cwd:n,path:i,profileName:t.profileName,now:new Date().toISOString()});return l.ok?(console.log(`${V("\u2713")}"${l.title??Me(l.path)}" is no longer one of your docs.`),l.keptAt&&console.log(u(` The markdown is kept at ${l.keptAt} \u2014 nothing was deleted.`)),console.log(u(" It is untouched on Document360. /catch-up will not import it again.")),{kind:"continue",ownNext:!0}):(console.log(L(`${V("\u2717")}Could not untrack "${Me(i)}" \u2014 ${l.error.message}`)),{kind:"continue",ownNext:!0})}ue();import{scanTerminology as a$,approvalBlockedReason as l$,readProjectConfig as H1,writeProjectConfig as G1,termKey as Zh,HEAD_NOUN_CAP as q1}from"document360-engine";import an from"picocolors";var V1=3,K1=e=>e.uses.map(t=>`${an.bold(t.form)} ${u(`${t.files.length} article${t.files.length===1?"":"s"}`)}`).join(u(" \xB7 "));function ef(e,t={}){let n=a$(e,t.scope?{scope:t.scope}:{}),o=[];if(n.scanned===0)return[Z("Terminology"),"",`${V("\u25CB",u)}No articles to read yet.`,""];let r=n.variance.length+n.headings.length;if(o.push(Z("Terminology")+u(` ${n.scanned} article${n.scanned===1?"":"s"} read \xB7 ${r===0?"nothing inconsistent":`${r} to look at`}`)),o.push(""),n.variance.length>0){o.push(` ${V("\u2717",an.red)}The same term, spelled more than one way`);for(let s of n.variance){o.push(` ${K1(s)}`);let i=s.uses[s.uses.length-1],a=i.files.slice(0,V1);o.push(u(` "${i.form}" is in ${a.map(c=>Me(c,40)).join(", ")}${i.files.length>a.length?`, +${i.files.length-a.length} more`:""}`));let l=l$(s);l?o.push(u(` ${l}`)):o.push(u(` /terms --approve "${s.uses[0].form}" makes that the approved spelling`))}o.push("")}if(n.headNouns.length>0){let s=t.all?n.headNouns:n.headNouns.slice(0,q1);o.push(` ${V("\u25CB",u)}Possibly the same thing under a short name \u2014 ${an.italic("your call")}`);for(let i of s)o.push(u(` ${i.uses.map(a=>a.form).join(" \xB7 ")}`));n.headNouns.length>s.length&&o.push(u(` \u2026and ${n.headNouns.length-s.length} more \u2014 /terms --all lists them`)),o.push(u(' A shared word is not proof of a shared meaning: "billing history" and "history" are')),o.push(u(" different things. Nothing is flagged as wrong here.")),o.push("")}if(n.headings.length>0){o.push(` ${V("\u26A0",an.yellow)}Titles out of step with the rest of their kind`);for(let s of n.headings)o.push(` ${an.bold(s.title)} ${u(`\u2014 ${Me(s.path,40)}`)}`),o.push(u(` the other ${s.peers} ${s.type} article${s.peers===1?"":"s"} look like "${s.example}"; this one starts ${Y1(s.shape)}`));o.push("")}return r===0&&n.headNouns.length===0&&(o.push(` ${V("\u2713",an.green)}Every term is spelled one way, and every title matches its kind.`),o.push("")),o.push(u(' This compares spellings, not meanings: two different words for one thing (say "nav" and')),o.push(u(' "rail") look unrelated to it. Add the pair to your approved terms and every run enforces it.')),o.push(u(" Free \u2014 this read your articles and called nothing.")),o}function Y1(e){return e==="gerund"?"with an -ing word":e==="how-to"?'with "How to"':"differently"}function tf(e,t,n){let o=n??a$(e),r=Zh(t),s=o.variance.find(m=>m.uses.some($=>Zh($.form)===r));if(!s)return{wrote:!1,lines:[`${V("\u2717",an.red)}"${t}" is not one of the terms with competing spellings. /terms lists them.`]};let i=l$(s);if(i)return{wrote:!1,lines:[`${V("\u2717",an.red)}That one cannot be recorded: ${i}.`,u(` The spellings in play are ${s.uses.map(m=>`"${m.form}"`).join(" and ")}.`)]};let a=s.uses.find(m=>Zh(m.form)===r).form,l=s.uses.filter(m=>m.form!==a).map(m=>m.form),c=H1(e);if(!c)return{wrote:!1,lines:[`${V("\u2717",an.red)}No project configuration here \u2014 run /init first.`]};let p={...c.terminologyGlossary??{}};for(let m of l)p[m]=a;return G1({...c,terminologyGlossary:p},e),{wrote:!0,lines:[`${V("\u2713",an.green)}"${a}" is now the approved spelling.`,u(` Added to your approved terms: ${l.map(m=>`"${m}" \u2192 "${a}"`).join(", ")}`),u(" Every run enforces it from now on, and /lint --fix corrects the others for free.")]}}async function c$(e,t){let n=e.findIndex(s=>s==="--approve");if(n!==-1){let s=e[n+1];if(!s)return console.log(`${V("\u2717",an.red)}Name the spelling to approve, e.g. /terms --approve "drop-down".`),{kind:"continue",ownNext:!0};for(let i of tf(t.cwd,s.replace(/^["']|["']$/g,"")).lines)console.log(i);return{kind:"continue",ownNext:!0}}let o=e.includes("--all"),r=e.find(s=>!s.startsWith("--"));for(let s of ef(t.cwd,{...r?{scope:r}:{},all:o}))console.log(s);return{kind:"continue",ownNext:!0}}ue();import{evaluateCorpus as z1,buildRegistry as X1,lintArticles as Q1,scanTerminology as J1,BUILTIN_RULES as Z1,surfaceCoverageSafe as ej,readProjectConfig as tj}from"document360-engine";import At from"picocolors";var $t=3,rt=(e,t)=>`${e} ${t}${e===1?"":"s"}`,u$=e=>`${Me(e.path)}:${e.line}`,nf=e=>e.split("/").pop()?.split("\\").pop()??e;function of(e,t,n,o,r,s,i){if(r.length===0)return;e.push(` ${V(t,n)}${o}`);let a=i?r:r.slice(0,$t);for(let l of a)e.push(u(` ${u$(l)} ${l.detail}`));r.length>a.length&&e.push(u(` \u2026and ${r.length-a.length} more \u2014 /eval --all`)),e.push(u(` ${s}`)),e.push("")}function rf(e,t={}){let n=X1(e),o=new Set([...Z1.map(p=>p.id),...n.rules.map(p=>p.id)]),r=z1(e,o,{...t.scope?{scope:t.scope}:{},...t.profile?{profile:t.profile}:{}}),s=t.all===!0,i=[];if(r.articles===0)return[Z("Knowledge-base score"),"",`${V("\u25CB",u)}No articles to read yet.`,""];let a=ej(e,tj(e)),l=r.links.absolute.length+r.links.deadTargets.length+r.links.deadAnchors.length+r.links.staleLabels.length+r.sources.missing.length+r.shapes.typeTemplates.filter(p=>p.deviations.length>0).length+(r.shapes.synopsisForms.length>1?1:0)+(a.recognised?a.areas.length:0);if(i.push(Z("Knowledge-base score")+u(` ${rt(r.articles,"article")} read \xB7 ${l===0?"nothing to look at":`${l} to look at`}`)),i.push(""),of(i,"\u2717",At.red,"Links pointing at articles that do not exist",r.links.deadTargets,"The article was renamed or retired after the link was written. Point it at the one that replaced it.",s),r.links.deadTargets.length===0&&r.links.sidebarDeadTargets>0&&(i.push(u(` ${r.links.sidebarDeadTargets} dead link${r.links.sidebarDeadTargets===1?"":"s"} in a Related articles list \u2014 excluded, the portal rebuilds that list itself`)),i.push("")),of(i,"\u2717",At.red,"Internal links written as portal URLs",r.links.absolute,"These break the day the site moves. Write them as relative .md links instead.",s),of(i,"\u2717",At.red,"Links pointing at headings that do not exist",r.links.deadAnchors,"The heading was renamed after the link was written. Point it at the current heading.",s),r.links.staleLabels.length>0){let p=r.links.staleLabels.reduce((m,$)=>m+$.sites.length,0);i.push(` ${V("\u26A0",At.yellow)}${rt(r.links.staleLabels.length,"link label")} name an article something it is not called${p>r.links.staleLabels.length?u(`, in ${rt(p,"place")}`):""}`);for(let m of s?r.links.staleLabels:r.links.staleLabels.slice(0,$t))if(i.push(u(` "${m.label}" \u2192 the article is titled "${m.title}"${m.sites.length>1?` (${m.sites.length}\xD7)`:""}`)),s)for(let $ of m.sites)i.push(u(` ${u$($)}`));!s&&r.links.staleLabels.length>$t&&i.push(u(` \u2026and ${r.links.staleLabels.length-$t} more \u2014 /eval --all`)),i.push(u(" A reader clicks expecting one page and lands on another name.")),i.push("")}if(s&&r.links.shortenedLabels.length>0){i.push(` ${V("\u25CB",u)}${rt(r.links.shortenedLabels.length,"link label")} shorten the title they point at`);for(let p of r.links.shortenedLabels.slice(0,10))i.push(u(` "${p.label}" \u2192 "${p.title}"`));i.push(u(" Usually fine. Listed separately because it is a judgment call, not a defect.")),i.push("")}if(s&&r.links.sidebarLabelMismatch>0&&(i.push(` ${V("\u25CB",u)}${rt(r.links.sidebarLabelMismatch,"Related-articles link")} not counted above`),i.push(u(" Those labels are dropped when the article is saved. Document360 builds that list from")),i.push(u(" the real titles, so a reader never sees the label written here.")),i.push("")),r.shapes.synopsisForms.length>1){i.push(` ${V("\u26A0",At.yellow)}The command summary line appears in ${rt(r.shapes.synopsisForms.length,"shape")}`);for(let p of r.shapes.synopsisForms)i.push(u(` ${String(p.count).padStart(3)} ${p.form.padEnd(14)} ${p.examples.map(nf).join(", ")}`));r.shapes.noSynopsis.length>0&&i.push(u(` ${rt(r.shapes.noSynopsis.length,"article")} carry none at all`)),i.push(u(" Same information, different labels. Pick one and use it everywhere.")),i.push("")}for(let p of r.shapes.typeTemplates)if(p.deviations.length!==0){i.push(` ${V("\u26A0",At.yellow)}${p.deviations.length} of ${rt(p.articles,`${p.type} article`)} skip a section the rest of them carry`),i.push(u(` Most ${p.type} articles have: ${p.expected.map(m=>`## ${m.heading} (${m.count})`).join(" \xB7 ")}`));for(let m of s?p.deviations:p.deviations.slice(0,$t))i.push(u(` ${nf(m.path)} \u2014 missing ${m.missing.map($=>`## ${$}`).join(", ")}`));!s&&p.deviations.length>$t&&i.push(u(` \u2026and ${p.deviations.length-$t} more \u2014 /eval --all`)),i.push(u(" A deviation may be deliberate. This counts them; it does not say the template is right.")),i.push("")}try{let p=J1(e,t.scope?{scope:t.scope}:{});if(p.variance.length>0){i.push(` ${V("\u26A0",At.yellow)}${rt(p.variance.length,"term")} spelled more than one way across the set`);for(let m of p.variance.slice(0,s?99:$t))i.push(u(` ${m.uses.map($=>`"${$.form}" \xD7${$.count}`).join(" \xB7 ")}`));p.headNouns.length>0&&i.push(u(` ${rt(p.headNouns.length,"short name")} may be a longer one abbreviated \u2014 /terms lists them`)),i.push(u(' Settle one and every later run enforces it: /terms --approve "<term>"')),i.push("")}}catch{}let c=0;try{let m=Q1({cwd:e,...t.scope?{scope:t.scope}:{}}).findings.filter(w=>!w.baselined);c=m.filter(w=>w.ruleId==="Document360.Changelog").length;let $=m.filter(w=>w.severity==="error").length;if(i.push(` ${V($>0?"\u2717":m.length>0?"\u26A0":"\u2713",$>0?At.red:m.length>0?At.yellow:At.green)}`+(m.length===0?"Style rules: nothing reported":`Style rules: ${rt(m.length,"finding")}${$>0?`, ${$} blocking publish`:", none blocking publish"}`)),m.length>0){let w=new Map;for(let C of m)w.set(C.ruleId,(w.get(C.ruleId)??0)+1);for(let[C,S]of[...w.entries()].sort((T,R)=>R[1]-T[1]).slice(0,s?99:5))i.push(u(` ${String(S).padStart(4)} ${C}`));i.push(u(" Fix what can be fixed mechanically: /lint --fix"))}i.push("")}catch{}if(r.debt&&r.debt.total>0){let p=r.debt.liveRules.reduce((w,C)=>w+C.count,0),m=r.debt.inertRules.reduce((w,C)=>w+C.count,0),$=r.debt.createdAt.slice(0,10);if(p>0){i.push(` ${V("\u2139",u)}${rt(p,"style finding")} accepted as exempt on ${$}, from rules that are still on`);for(let w of r.debt.liveRules.slice(0,s?99:4))i.push(u(` ${String(w.count).padStart(4)} ${w.rule}`));i.push(u(" Nothing reports these, so the articles read as compliant. They are exempt, not compliant.")),i.push(u(" Work them down with /review --all --fix, then /lint --all --fix."))}else m>0&&(i.push(` ${V("\u25CB",u)}${rt(m,"finding")} accepted on ${$} under a style guide no longer in use`),i.push(u(" They match no active rule, so they suppress nothing. Only weight in the file.")));i.push("")}if(r.sources.missing.length>0){i.push(` ${V("\u26A0",At.yellow)}${rt(r.sources.missing.length,"article")} cite a file that is not in the repository`);for(let p of s?r.sources.missing:r.sources.missing.slice(0,$t))i.push(u(` ${p.source}${u(" \u2190 ")}${p.path}`));!s&&r.sources.missing.length>$t&&i.push(u(` \u2026and ${r.sources.missing.length-$t} more \u2014 /eval --all`)),i.push(u(" Renamed or deleted since the article was written. /audit points it at the file that replaced it.")),i.push("")}if(a.recognised&&a.areas.length>0){i.push(` ${V("\u26A0",At.yellow)}${rt(a.areas.length,"part")} of the product no article says it documents`);for(let p of a.areas.slice(0,s?99:5))i.push(u(` ${String(p.files).padStart(4)} ${p.folder}`));!s&&a.areas.length>5&&i.push(u(` \u2026and ${a.areas.length-5} more \u2014 /eval --all lists them.`)),i.push(u(` ${a.documented} of ${a.filesScanned} source files are cited by an article.`)),a.declined>0&&i.push(u(` ${a.declined} you declined, left out of that count.`)),i.push(u(" /audit proposes the articles. /audit --decline <path> settles a folder or file for good.")),i.push("")}else a.recognised||(i.push(` ${V("\u25CB",u)}Product coverage was not measured`),i.push(u(` ${a.reason}`)),i.push(""));if(i.push(` ${V("\u25CB",u)}Length: ${r.length.words.toLocaleString()} words, median ${r.length.median.toLocaleString()} an article`),r.length.longest.length>0){i.push(u(` ${rt(r.length.longest.length,"article")} past 2,500 words:`));for(let p of s?r.length.longest:r.length.longest.slice(0,$t))i.push(u(` ${p.words.toLocaleString()} ${nf(p.path)}`));!s&&r.length.longest.length>$t&&i.push(u(` \u2026and ${r.length.longest.length-$t} more \u2014 /eval --all`))}return c>0&&(i.push(u(` ${rt(c,"sentence")} tell the reader what the product used to do.`)),i.push(u(" Those are the longest sentences in a corpus, and the cheapest words to take out."))),i.push(u(" No previous measurement to compare against, so this is a reading, not a trend.")),i.push(""),l===0&&(r.debt?.total??0)===0&&(i.push(` ${V("\u2713",At.green)}Links resolve, one template shape, one name per thing.`),i.push("")),i.push(u(` Free \u2014 this read your ${rt(r.articles,"article")} and called nothing.`)),i}async function d$(e,t){let n=e.includes("--all"),o=e.find(r=>!r.startsWith("--"));for(let r of rf(t.cwd,{...o?{scope:o}:{},...t.profileName?{profile:t.profileName}:{},all:n}))console.log(r);return{kind:"continue",ownNext:!0}}import{fetchPortalReuse as kj,readReuseCache as bj,writeReuseCache as $j,resolveActiveProfile as lf,resolveProjectId as cf,createVariable as g$,createSnippet as y$,reuseNameProblem as vj,variableRule as xj,VARIABLE_MAX_CHARS as f$}from"document360-engine";ue();import{scanReuse as p$,scanValueCandidates as h$,buildReuseAuditPrompt as nj,reuseAuditProposalPath as oj,readReuseProposal as rj,readReuseCache as sj,listArticleFiles as ij,normalizeScope as aj,docsRootOf as lj,variableRule as cj}from"document360-engine";import{rmSync as uj}from"node:fs";import dj from"picocolors";var oc=6,pj=20;function hj(e,t){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}\u2026`:n}function fj(e,t=52){let n=e.replace(/\s+/g," ").trim(),o=[],r="";for(let s of n.split(" "))r===""?r=s:`${r} ${s}`.length<=t?r+=` ${s}`:(o.push(r),r=s);return r!==""&&o.push(r),o}function rc(e,t,n,o){let r=[Z("Content reuse audit"),""];return r.push(`${e} article${e===1?"":"s"} read${u(" \xB7 free to look")}`,""),r.push(` ${String(n).padStart(3)} value${n===1?"":"s"} written out by hand in more than one article`),r.push(` ${String(t).padStart(3)} block${t===1?"":"s"} written more than once, in different words`),o>0&&r.push(u(` ${o} more families were left out of this pass \u2014 the longest ones are shown first.`)),r}function sc(e,t){let n=lj(e),o=t.filter($=>$!=="audit"&&!$.startsWith("--")).find($=>$!==void 0),r=o?aj(n,o.replace(/\\/g,"/").replace(/\/+$/,"")):void 0,s=ij(e,r).length;if(s===0)return{lines:[te("\u25CB",r?`No articles under ${r} to audit.`:"No articles to audit yet."),u(" Reuse is about text that repeats, so there has to be some text first.")]};let i=p$(e,{...r?{scope:r}:{},groups:!0}),a=h$(e,r?{scope:r}:void 0),l=i.groups??[],c=a.candidates;if(l.length===0&&c.length===0)return{lines:[te("\u2713",`Nothing repeats across ${s} article${s===1?"":"s"} \u2014 there is nothing to keep in one place.`),u(" That is a good answer, not an empty one. Run this again after a few more articles.")]};let p=sj(e),m=oj(e);try{uj(m,{force:!0})}catch{}return{prompt:nj({cwd:e,families:l,values:c,snippets:p?.snippets??[],variables:p?.variables??[],terms:p?.terms??[],proposalPath:m,articles:s}),display:r?`/reuse audit ${r}`:"/reuse audit",articles:s,families:l.length,values:c.length}}function mj(e,t){let n=[],o=` ${String(t).padStart(2)} ${e.kind.padEnd(9)}${dj.bold(e.name.padEnd(pj))}`,r=e.kind==="variable"?[`"${hj(e.value,52)}"`]:fj(`"${e.value}"`);n.push(`${o}${r[0]??""}`);for(let a of r.slice(1))n.push(`${" ".repeat(o.length-10)}${a}`);let s=e.uses>0?`${e.uses} use${e.uses===1?"":"s"} across ${e.files} article${e.files===1?"":"s"}`:"",i=e.why?s?` \u2014 ${e.why}`:e.why:"";return(s||i)&&n.push(u(` ${s}${i}`)),n}function gj(e,t,n){let o=[],r=e.proposals.length;if(o.push(r===0?te("\u2713",`An editor read ${t} famil${t===1?"y":"ies"} and ${n} value${n===1?"":"s"}. None of it has to stay identical everywhere.`):te("\u2713",`An editor read ${t} famil${t===1?"y":"ies"} and ${n} value${n===1?"":"s"}. ${r} ${r===1?"is":"are"} worth keeping in one place.`),""),e.proposals.forEach((s,i)=>{o.push(...mj(s,i+1),"")}),e.rejected.length>0){o.push(" Not proposed, and why:");for(let s of e.rejected.slice(0,oc))o.push(u(` \xB7 ${s.what} \u2014 ${s.why}`));e.rejected.length>oc&&o.push(u(` \xB7 \u2026and ${e.rejected.length-oc} more.`)),o.push("")}if(e.dropped.length>0){o.push(te("\u26A0",`${e.dropped.length} proposal${e.dropped.length===1?"":"s"} could not be used:`));for(let s of e.dropped.slice(0,oc))o.push(u(` \xB7 ${s}`));o.push("")}return o}function yj(){return[u(" Nothing to create. The knowledge base repeats itself, but not in ways that have to stay"),u(" identical everywhere \u2014 which is the answer an editor is for."),""]}function ic(e,t){let n=[],o=t.created.map(a=>a.name);o.length>0&&(n.push(te("\u2713",`Created ${o.length} on Document360: ${o.join(", ")}.`)),n.push(u(" Your local copy is in step and the agent has been restarted, so it writes with them from now on.")));for(let a of t.failed)n.push(te("\u2717",`Document360 refused "${a.name}" \u2014 ${a.why}`));t.failed.length>0&&n.push(u(" Nothing else was changed. A name already in use is the usual cause; /reuse lists what exists."));let r=t.created.some(a=>a.kind==="variable"),s=t.created.filter(a=>a.kind==="snippet"),i=null;if(r){let a=cj(e).rule!==null;n.push(""),n.push(a?te("\u2139","Those values are still typed out by hand across your articles."):te("\u2139","Those values are created, but nothing checks them yet.")),a&&(n.push(u(" /lint --all --fix swaps every one of them \u2014 it costs no agent time, and nothing else in")),n.push(u(" your articles changes.")),i="/lint --all --fix")}return s.length>0&&(n.push(""),n.push(te("\u2139",`${s.length===1?"The snippet exists":`The ${s.length} snippets exist`} on Document360, but no article references ${s.length===1?"it":"them"} yet.`)),n.push(u(` Ask me to use ${s.length===1?"it":"them"} in an article, or run /review --all --fix and the editor will replace the`)),n.push(u(" passages it finds. Replacing a passage changes the words a reader sees, so it goes through")),n.push(u(" an editorial read rather than a mechanical swap.")),i||(i="/review --all --fix")),i&&n.push("",i,""),{lines:n,cta:i}}function ac(e,t){let n=e.indexOf("--create");if(n===-1)return{picks:[],bad:[]};let o=e.slice(n+1).filter(i=>!i.startsWith("--"));if(o.length===1&&(o[0]==="a"||o[0]==="all"))return{picks:Array.from({length:t},(i,a)=>a),bad:[]};let r=[],s=[];for(let i of o){let a=Number(i);if(!Number.isInteger(a)||a<1||a>t){s.push(i);continue}r.includes(a-1)||r.push(a-1)}return{picks:r,bad:s}}function wj(e){if(e===0)return[];let t=Array.from({length:e},(n,o)=>o+1).join(" ");return[u(` Pick what to create. Run the line below for all ${e}, or edit the numbers to take some.`),"",`/reuse audit --create ${t}`,""]}function lc(){return[te("\u2717","There is no reuse proposal to create from."),u(" Run /reuse audit first \u2014 it reads your articles and works out what belongs in one place."),"","/reuse audit",""]}function cc(e,t){let n=rj(e);if(!n)return[te("\u26A0","The editor did not leave a proposal, so there is nothing to create."),u(" Nothing was changed. This is usually a turn that stopped early \u2014 running it again is safe,"),u(" and the scan it starts from costs nothing."),"",t?`/reuse audit ${t}`:"/reuse audit",""];let o=p$(e,{...t?{scope:t}:{},groups:!0}),r=h$(e,t?{scope:t}:void 0),s=gj(n,(o.groups??[]).length,r.candidates.length);return s.push(...n.proposals.length===0?yj():wj(n.proposals.length)),s}ue();import{readReuseProposal as Rj}from"document360-engine";import ss from"picocolors";var sf=8,Wn=6,af=14,Sj=52;function Cj(e){if(!e)return"";let t=new Date(e);return Number.isNaN(t.getTime())?"":t.toLocaleDateString(void 0,{day:"numeric",month:"short"})}function m$(e,t=Sj){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}\u2026`:n}function uf(e){let t=bj(e),n=[Z("Reusable content"),""];if(!t||t.terms.length===0&&t.snippets.length===0&&t.variables.length===0)return n.push(`${V("\u25CB",u)}Nothing pulled from Document360 yet.`,"",u(" A variable holds a value like your product name in one place, so changing it changes every"),u(" article at once. A snippet does the same for a whole block, like who to contact when"),u(" something goes wrong. A term is defined once and explained everywhere it first appears."),"","/reuse pull",""),n;let o=Cj(t.pulledAt);if(t.terms.length===0)n.push(`${V("\u25CB",u)}No glossary terms in this Document360 project${o?u(` (checked ${o})`):""}.`);else{n.push(`${t.terms.length} term${t.terms.length===1?"":"s"} from Document360${o?u(`, pulled ${o}`):""}.`,"");for(let r of t.terms.slice(0,sf)){let s=" ".repeat(Math.max(1,af-r.term.length));n.push(` ${ss.bold(r.term)}${s}${u(r.definition||"(no definition)")}`)}t.terms.length>sf&&n.push(u(` \u2026and ${t.terms.length-sf} more.`))}if(t.variables.length>0){n.push("",`${t.variables.length} value${t.variables.length===1?"":"s"} kept in one place.`,"");for(let s of t.variables.slice(0,Wn)){let i=" ".repeat(Math.max(1,af-s.name.length));n.push(` ${ss.bold(s.name)}${i}${u(s.value?`"${m$(s.value)}"`:"(no value recorded)")}`)}t.variables.length>Wn&&n.push(u(` \u2026and ${t.variables.length-Wn} more.`));let{skipped:r}=xj(e);if(r.length>0){let s=t.variables.length-r.length;n.push("",u(` ${s} of ${t.variables.length} are checked in your articles. ${r.length===1?"This one is":"These are"} not:`));for(let i of r.slice(0,Wn))n.push(u(` ${i.name} \u2014 ${i.why}.`));r.length>Wn&&n.push(u(` \u2026and ${r.length-Wn} more.`))}}if(t.snippets.length>0){n.push("",`${t.snippets.length} maintained block${t.snippets.length===1?"":"s"}.`,"");for(let r of t.snippets.slice(0,Wn)){let s=" ".repeat(Math.max(1,af-r.name.length)),i=r.usedBy>0?u(` (in ${r.usedBy} article${r.usedBy===1?"":"s"})`):"";n.push(` ${ss.bold(r.name)}${s}${u(r.description||m$(r.value??"")||"(no content recorded)")}${i}`)}t.snippets.length>Wn&&n.push(u(` \u2026and ${t.snippets.length-Wn} more.`))}return n.push("",u(" Terms are checked at first use in every article, a value you typed out by hand is flagged,"),u(" and the writer reuses your blocks by name instead of writing its own version of them."),"","/reuse pull","/lint --all",""),n}async function Ei(e,t){let n,o;try{let c=lf(e,t);n={profile:c.name,connection:c.connection,projectId:c.project.projectId,projectName:c.project.projectName},o=await cf(n,c.project?.projectId)}catch(c){return{lines:[te("\u2717",`Not signed in to Document360: ${c instanceof Error?c.message:String(c)}`),u(" Run /login first.")],restart:!1}}let r;try{r=await kj(n,o)}catch(c){return{lines:[te("\u26A0",`Document360 didn't return your reusable content \u2014 ${c instanceof Error?c.message:String(c)}.`),u(" Nothing is blocked. Everything else works exactly as it did; you just do not get the"),u(" first-use check on your terms, or the reuse checks, until this succeeds.")],restart:!1}}let s={pulledAt:new Date().toISOString(),profile:n.profile,projectId:o,terms:r.terms,snippets:r.snippets,variables:r.variables};if($j(e,s),s.terms.length+s.snippets.length+s.variables.length===0)return{lines:[te("\u2139","This Document360 project has no terms, snippets or variables yet."),u(" Someone with portal access adds them under Content tools. A good first one is your product"),u(" name as a variable: it is the string most likely to change, and the hardest to change late.")],restart:!1};let a=[`${s.terms.length} term${s.terms.length===1?"":"s"}`,`${s.snippets.length} snippet${s.snippets.length===1?"":"s"}`,`${s.variables.length} variable${s.variables.length===1?"":"s"}`],l=[te("\u2713",`Pulled ${a.join(" \xB7 ")} from Document360.`)];return r.droppedTerms.length>0&&l.push(u(` ${r.droppedTerms.length} term${r.droppedTerms.length===1?" has":"s have"} no wording recorded in Document360, so ${r.droppedTerms.length===1?"it is":"they are"} not checked:`),u(` ${r.droppedTerms.slice(0,6).join(", ")}${r.droppedTerms.length>6?`, and ${r.droppedTerms.length-6} more`:""}.`)),r.contentlessBlocks.length>0&&l.push(u(` ${r.contentlessBlocks.length} block${r.contentlessBlocks.length===1?"":"s"} came back without content, so ${r.contentlessBlocks.length===1?"it is":"they are"} not matched against your articles:`),u(` ${r.contentlessBlocks.slice(0,6).join(", ")}${r.contentlessBlocks.length>6?`, and ${r.contentlessBlocks.length-6} more`:""}.`)),l.push("",u(" Your terms are now checked at first use in every article, a value you typed out by hand is"),u(" flagged, and the writer reuses your blocks by name instead of writing its own version."),"","/lint --all",""),{lines:l,restart:!0}}async function df(e,t,n,o,r){let s=vj(n);if(s)return{lines:[te("\u2717",`That name will not work: ${s}.`),u(' Try something like "product-name".')],restart:!1};if(o.trim()==="")return{lines:[te("\u2717","A value is required \u2014 that is the text this will stand for in your articles.")],restart:!1};if(t==="variable"&&o.length>f$)return{lines:[te("\u2717",`A variable holds at most ${f$} characters and this is ${o.length}.`),u(' Longer text belongs in a snippet: /reuse add snippet <name> "<text>"')],restart:!1};let i,a;try{let l=lf(e);i={profile:l.name,connection:l.connection,projectId:l.project.projectId,projectName:l.project.projectName},a=await cf(i,l.project?.projectId)}catch(l){return{lines:[te("\u2717",`Not signed in to Document360: ${l instanceof Error?l.message:String(l)}`),u(" Run /login first.")],restart:!1}}try{let l=t==="variable"?await g$(i,a,{name:n,value:o}):await y$(i,a,{name:n,value:o,...r?{description:r}:{}}),c=await Ei(e);return{lines:[te("\u2713",`Created the ${t} "${l.name}" on Document360.`),u(` Write ${t==="variable"?`:variable[]{name="${l.name}"}`:`::snippet{name="${l.name}"}`} and Document360 puts your text there.`),"",...c.lines],restart:!0}}catch(l){let c=l instanceof Error?l.message:String(l);return{lines:[te("\u2717",`Document360 refused to create that ${t} \u2014 ${c}`),u(" Nothing was changed. A name already in use is the usual cause; /reuse lists what exists.")],restart:!1}}}function w$(e){let t=e.trim();return t.length>=2&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))?t.slice(1,-1):t}function Pj(e){let t=e.indexOf("--desc");if(t===-1)return{rest:e};let n=w$(e.slice(t+1).join(" "));return{rest:e.slice(0,t),...n?{description:n}:{}}}function pf(e){let{rest:t,description:n}=Pj(e),o=t.filter(l=>!l.startsWith("--")),[,r,s,...i]=o;if(r!=="variable"&&r!=="snippet")return{error:'Say which one: /reuse add variable <name> "<value>", or /reuse add snippet <name> "<text>".'};if(!s)return{error:`Give it a name: /reuse add ${r} <name> "<value>".`};if(r==="variable"&&n)return{error:"Only a snippet takes --desc; a variable is just its value. Drop the flag, or add it as a snippet."};let a=w$(i.join(" "));return a===""?{error:`Give it a value: /reuse add ${r} ${s} "<the text it stands for>".`}:{kind:r,name:s,value:a,...n?{description:n}:{}}}async function k$(e,t){let n=e.find(o=>!o.startsWith("--"));if(n==="add"){let o=pf(e);if("error"in o)return console.log(`${V("\u2717",ss.red)}${o.error}`),{kind:"continue",ownNext:!0};let r=await df(t.cwd,o.kind,o.name,o.value,o.description);for(let s of r.lines)console.log(s);return r.restart?{kind:"clear"}:{kind:"continue",ownNext:!0}}if(n==="pull"){let o=await Ei(t.cwd);for(let r of o.lines)console.log(r);for(let r of Qe(t.cwd,"/reuse pull"))console.log(r);return o.restart?{kind:"clear"}:{kind:"continue",ownNext:!0}}if(n==="audit"){if(e.includes("--create")){let r=Rj(t.cwd);if(!r||r.proposals.length===0){for(let p of lc())console.log(p);return{kind:"continue",ownNext:!0}}let{picks:s,bad:i}=ac(e,r.proposals.length);for(let p of i)console.log(`${V("\u26A0",ss.yellow)}There is no proposal ${p} \u2014 the list has ${r.proposals.length}.`);if(s.length===0)return console.log(`${V("\u25CB",u)}Nothing picked, so nothing was created.`),{kind:"continue",ownNext:!0};let{outcome:a,pullLines:l}=await hf(t.cwd,s.map(p=>r.proposals[p]));for(let p of l)console.log(p);let{lines:c}=ic(t.cwd,a);for(let p of c)console.log(p);for(let p of Qe(t.cwd,"/reuse audit"))console.log(p);return a.created.length>0?{kind:"clear"}:{kind:"continue",ownNext:!0}}let o=sc(t.cwd,e);if("lines"in o){for(let r of o.lines)console.log(r);for(let r of Qe(t.cwd,"/reuse audit"))console.log(r);return{kind:"continue",ownNext:!0}}for(let r of rc(o.articles,o.families,o.values,0))console.log(r);return{kind:"forward-to-agent",prompt:o.prompt,display:o.display}}if(n&&n!=="show")return console.log(`${V("\u2717",ss.red)}I don't know "/reuse ${n}". Use /reuse to see what this project maintains, /reuse pull to refresh it, /reuse audit to find what belongs in one place, or /reuse add variable <name> "<value>".`),{kind:"continue",ownNext:!0};for(let o of uf(t.cwd))console.log(o);return{kind:"continue",ownNext:!0}}async function hf(e,t){let n=[],o=[],r,s;try{let a=lf(e);r={profile:a.name,connection:a.connection,projectId:a.project.projectId,projectName:a.project.projectName},s=await cf(r,a.project?.projectId)}catch(a){return{outcome:{created:[],failed:t.map(l=>({name:l.name,why:`not signed in to Document360: ${a instanceof Error?a.message:String(a)}`}))},pullLines:[u(" Run /login first.")]}}for(let a of t)try{a.kind==="variable"?await g$(r,s,{name:a.name,value:a.value}):await y$(r,s,{name:a.name,value:a.value,...a.description?{description:a.description}:{}}),n.push(a)}catch(l){o.push({name:a.name,why:l instanceof Error?l.message:String(l)})}if(n.length===0)return{outcome:{created:n,failed:o},pullLines:[]};let i=await Ei(e);return{outcome:{created:n,failed:o},pullLines:i.restart?[]:i.lines}}ue();import{readProjectConfig as Tj,writeProjectConfig as b$,isAppType as Aj,playbookSkillName as Ej,detectAppType as $$}from"document360-engine";var v$=["web","cli","service","library"],Nj=new Set(["web","cli"]);function ff(e){return Nj.has(e)?`${Ej(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function uc(e,t){let n=t.cwd,o=Tj(n);if(!o)return console.log(L("No d360-writer config here. Run /init first.")),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let s=o.appType??$$(n);if(s){let i=o.appType?"set in config":"auto-detected";console.log(`${Z("Genre:")} ${s} (${i}) \u2014 ${ff(s)}`)}else console.log(W("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(u(`Set it: /genre <${v$.join("|")}> \xB7 revert to auto-detect: /genre auto`)),{kind:"continue"}}if(r==="auto"||r==="clear"){if(!o.appType)return console.log(u("Already on auto-detect (no genre set in config).")),{kind:"continue"};let{appType:s,...i}=o;b$(i,n);let a=$$(n);return console.log(Q(`\u2713 Genre reset to auto-detect \u2014 now: ${a?`${a} (${ff(a)})`:"unclassified (no playbook)"}.`)),console.log(u(" Restarting the agent so the loaded playbook matches\u2026")),{kind:"clear"}}return Aj(r)?(b$({...o,appType:r},n),console.log(Q(`\u2713 Genre set to ${r} \u2014 ${ff(r)}.`)),console.log(u(" Restarting the agent so the playbook loads\u2026")),{kind:"clear"}):(console.log(L(`Unknown genre "${r}". Choose one of: ${v$.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}var x$={help:Nu,"?":Nu,clear:vg,exit:Du,quit:Du,init:Fu,mcp:Oa,push:cl,publish:sw,audit:(e,t)=>{let n=fl(t.cwd,e);if(n){for(let o of n)console.log(o);return Promise.resolve({kind:"continue",ownNext:!0})}return Zs({cwd:t.cwd,profileName:t.profileName})},discover:dw,scope:hw,pull:Pw,resolve:Rw,convert:Gw,write:sk,draft:uk,document:dk,resume:fk,rename:mk,profile:eg,model:wk,doctor:di,env:mg,logs:sg,workspace:xk,project:Rk,"allow-prod":Sk,login:Ck,logout:Pk,screenshot:async(e,t)=>{let n=Hs(e);return n.mode==="capture"?Gp(n.rest,t):n.mode==="annotate"?zp(n.rest,t):n.mode==="verify"?Tk(n.rest,t):n.mode==="checklist"?Qr(e,t):Za(e,t)},capture:Gp,annotate:zp,"capture-setup":Qr,devhints:Dg,inbox:Kk,ask:zk,"catch-up":nb,comments:lb,update:db,reset:gb,lint:up,check:Xw,"style-guide":ec,review:zb,reorder:Qb,restructure:Jb,structure:Lb,status:r$,retire:s$,untrack:i$,terms:c$,eval:d$,reuse:k$,genre:uc,roadmap:qy,share:Jk,auto:uw};function R$(e){let t=e.trim();if(!t.startsWith("/"))return null;let n=t.slice(1).split(/\s+/),o=(n[0]??"").toLowerCase();return o?{name:o,args:n.slice(1)}:null}import{spawnSync as Dj}from"node:child_process";import{readProjectConfig as jj,recordAnalyzedCommit as Ij,recordReportedAreas as Lj,resolveActiveProfile as Oj,surfaceCoverageSafe as _j}from"document360-engine";function Mj(e){try{let t=Dj("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8",timeout:1200}),n=(t.stdout||"").trim();return t.status===0&&n?n:null}catch{return null}}function Ni(e,t){try{let n=Oj(e,t),o=_j(e,jj(e));o.recognised&&Lj(e,n.name,o.areas.map(s=>s.folder));let r=Mj(e);return r&&Ij(e,n.name,r)?r:null}catch{return null}}un();Zn();var S$="Or just tell me what to write or update.";function P$(e,t=0){if(!(e>0))return null;let n=e===1?"the page":"those pages",o=`${e} note${ie(e)} from your builder ${e===1?"is":"are"} waiting on code they haven't finished.`,r=t>=e?`I've asked whether ${e===1?"it's":"they're"} done, and I'll write ${n} once the code lands.`:`I'll write ${n} once the code lands, and /catch-up asks your builder whether ${e===1?"it's":"they're"} done.`;return`${o} ${r} Nothing else is blocked.`}function Fj(e,t,n={}){let o=n.onlyScreenshots?"\u2713 Your writing is done \u2014 nothing is waiting to be written, reviewed, saved or taken live. Readers are seeing every article you have.":"\u2713 That\u2019s the full round trip \u2014 nothing is waiting to be written, reviewed, saved or taken live. Readers are seeing every article you have.";return n.listed?o:`${o}
|
|
447
|
-
|
|
448
|
-
Optional from here: ${e} of your ${t} docs campaign step${ie(t)} ${e===1?"is":"are"} still open (/roadmap shows them).`}function
|
|
449
|
-
\u2022 `),lead:{kind:"cmd",cmd:"/catch-up",reason:w},picker:null,follow:"Then /catch-up clears what\u2019s queued for the docs.",dependsOn:["discovery"]})}if(e.openComments>0){let w=e.openComments;n.push({key:"comments",bullet:`${w} reviewer comment${ie(w)} waiting on your articles`,lead:{kind:"cmd",cmd:"/comments",reason:"it shows what reviewers marked up in the portal, then lets you take it an article at a time"},picker:null,follow:`Then /comments shows the ${w} reviewer comment${ie(w)} waiting on your articles.`})}if(e.conflicts>0){let w=e.conflicts,C=w===1?"it":"these",S=e.unreadable===w,T=S?`${w} article${ie(w)} ${w===1?"is":"are"} held on Document360 in a form I can't read back`:e.unreadable>0?`${w} article${ie(w)} ${w===1?"is":"are"} waiting on your decision \u2014 changed both here and on Document360, or held there in a form I can't read back`:`${w} article${ie(w)} changed both here and on Document360`;n.push({key:"resolve",bullet:`${T} \u2014 /push skips ${C}, and an audit can't trust your local copy until ${w===1?"it is":"they are"} settled`,lead:{kind:"cmd",cmd:"/resolve",reason:S?"it walks each one with you \u2014 publish your copy over the portal, or skip":"it walks each one with you \u2014 keep yours, take the portal's, or skip"},picker:null,follow:S?`Then /resolve settles the ${w} article${ie(w)} Document360 won't hand back (publish yours over the portal / skip).`:`Then /resolve settles the ${w} article${ie(w)} waiting on your decision (keep yours / take the portal's / skip).`})}let o=e.firstPublish,r=(()=>{if(!o||o.unpushed===0)return null;let w=o.unpushed,C=e.profileName?` on ${e.profileName}`:"";if(o.portalArticles===null)return{key:"firstPublish",bullet:`${w} article${ie(w)} ${w===1?"is":"are"} written here, and this connection has never been compared with Document360`,lead:{kind:"cmd",cmd:"/pull --status",reason:"it asks Document360 what is already there. No tokens, and it changes nothing"},picker:null,follow:"Then /pull --status shows what this portal already holds."};if(o.twins===0){let S="/push --all",T=t?.scaleFor?.(S)??null;return{key:"firstPublish",bullet:w===o.total?`${w} article${ie(w)} ${w===1?"is":"are"} written here and none of them are${C} yet \u2014 your readers see nothing`:`${w} of your ${o.total} article${ie(o.total)} ${w===1?"has":"have"} not reached ${e.profileName} yet \u2014 the rest are saved as drafts`,lead:{kind:"cmd",cmd:S,reason:w===o.total?`it saves all ${w} to Document360 as draft${ie(w)}`:`it retries the ${w} that did not land`,...T&&w===o.total?{detail:T}:{}},picker:null,follow:w===o.total?`Then ${S} saves all ${w} to Document360, and /publish takes them live.`:`Then ${S} retries the ${w} that did not land, and /publish takes them live.`,...T&&w===o.total?{detail:T}:{},dependsOn:["catchup","comments"],blockedBy:["review","styleguide"]}}return{key:"firstPublish",bullet:`${w} article${ie(w)} ${w===1?"is":"are"} written here, and this portal holds ${o.twins} page${o.twins===1?"":"s"} nothing here tracks`,lead:null,picker:null,follow:"/pull --status compares them article by article, so nothing is pushed until you decide."}})(),s=r!==null&&e.unreviewed===0&&e.styleErrors===0,i=e.draftAhead,a=i>0?{key:"golive",bullet:`${i} article${ie(i)} ${i===1?"is":"are"} saved on Document360 but not live \u2014 your readers still see the previous version`,lead:{kind:"cmd",cmd:"/publish",reason:`it takes the ${i} draft${ie(i)} live to your readers \u2014 it lists them and asks first`},picker:null,follow:`Then /publish takes the ${i} draft${ie(i)} live \u2014 until it does, readers see the previous version.`,dependsOn:["comments"],blockedBy:["review","styleguide"]}:null,l=e.localAhead===0&&(e.firstPublish?.unpushed??0)===0,c=a!==null&&l&&e.unreviewed===0&&e.styleErrors===0;if(a&&c&&n.push(a),r&&s&&n.push(r),e.portalUntracked>0){let w=e.portalUntracked,C=e.portalOnlyCategories;n.push({key:"coverage",bullet:`${w} article${ie(w)} on Document360 ${w===1?"is":"are"} not in your docs folder \u2014 a plan or an audit built now would miss ${w===1?"it":"them"}`,lead:{kind:"cmd",cmd:"/pull",reason:C>0?`it imports ${w===1?"it":"them"} and creates the ${C} ${C===1?"folder":"folders"} they need`:`it imports ${w===1?"it":"them"} into your docs folder`},picker:null,follow:`Then /pull brings the ${w} Document360 article${ie(w)} this repo is not tracking.`})}if(e.behind>0||e.undocumentedAreas>0){let w=e.behind,C=e.undocumentedAreas,S=w>0||e.unreportedAreas>0,T=e.declineTarget?`/audit --decline ${e.declineTarget}`:"/audit --decline",R=w>0&&C>0?`${w} code change${ie(w)} since your last docs check, and ${C} part${ie(C)} of the product no article covers`:w>0?`${w} code change${ie(w)} since your last docs check`:S?`${C} part${ie(C)} of the product no article covers`:`${C} part${ie(C)} of the product no article covers \u2014 proposed already, still open. Settle one for good: ${T}`;n.push({key:"audit",bullet:R,lead:S?{kind:"cmd",cmd:"/audit",reason:w>0?"it shows what the latest code changes touch (or /audit --auto on to run it for you)":`it proposes the articles those parts need \u2014 or settle one with ${T}`}:null,picker:null,follow:S?w>0?`After that, /audit covers the ${w} newer commit${ie(w)}.`:`After that, /audit proposes what the ${C} uncovered part${ie(C)} need.`:null,blockedBy:["resolve"],dependsOn:["coverage"],opensRound:!0})}if(e.hasDocs&&e.pendingWrites>0){let w=e.pendingWrites;n.push({key:"write",bullet:`${w} planned article${ie(w)} still unwritten`,lead:{kind:"cmd",cmd:"/write",reason:"it finishes the articles already planned"},picker:null,follow:`Then /write finishes the ${w} planned article${ie(w)}.`,dependsOn:["genre","discovery","catchup","audit","coverage"]})}if(e.styleSweep){let w=e.styleSweep.pending,C=e.styleSweep.packs.length>0?e.styleSweep.packs.join(", "):"the built-in checks",S=e.styleSweep.scope?Te("/review","--fix",e.styleSweep.scope):"/review --all --fix";n.push({key:"styleSweep",bullet:`your writing rules changed to ${C} \u2014 ${w<e.styleSweep.total?`${w} of ${e.styleSweep.total}`:`${w}`} article${ie(w)} ${w===1?"has":"have"} not been read against them yet`,lead:{kind:"cmd",cmd:S,reason:"it reads each one against the new rules and rewrites it",detail:[t?.scaleFor?.(S),"/style-guide sweep skip stops me raising it."].filter(Boolean).map(T=>T.replace(/([^.!?…])$/,"$1.")).join(" ")},picker:null,follow:`Then ${S} reads the ${w} article${ie(w)} the new rules have never been applied to.`,dependsOn:["catchup","comments","audit"]})}if(e.unreviewed>0){let w=e.unreviewed,C=Te("/review","--blocked --fix",e.unreviewedScope);n.push({key:"review",bullet:`${w} article${ie(w)} not yet live ${w===1?"carries":"carry"} text no editor has read`,lead:{kind:"cmd",cmd:C,reason:"these were written by an AI \u2014 it reads each one and applies its fixes, and nothing can be sent up or taken live until it has"},picker:null,follow:`Then ${C} reviews the ${w} unreviewed article${ie(w)} \u2014 nothing reaches your readers until it has.`,dependsOn:["catchup","comments"]})}if(e.styleErrors>0){let w=e.styleErrors,C=Te("/lint","--blocked --fix",e.styleErrorScope);n.push({key:"styleguide",bullet:`${w} article${ie(w)} not yet live break${w===1?"s":""} house style rules that block publishing`,lead:{kind:"cmd",cmd:C,reason:"finding them costs nothing and one pass corrects them in place \u2014 nothing can be sent up or taken live until it has"},picker:null,follow:`Then ${C} clears the style errors on ${w} article${ie(w)} \u2014 nothing reaches your readers until it has.`,dependsOn:["catchup","comments","review"]})}let p=e.draftBlockedShots??null,m=p&&p.articles>0?{key:"annotate",bullet:`${p.articles} article${ie(p.articles)} ${p.articles===1?"is":"are"} saved on Document360 and cannot go live \u2014 ${p.places} picture${ie(p.places)} ${p.places===1?"is":"are"} missing, so your readers would see "[Screenshot: \u2026]" on the page`,lead:p.cmd?{kind:"cmd",cmd:p.cmd,reason:zj(p.stage,p.places)}:{kind:"prompt",text:`fix the ${p.places} bare "[Screenshot: \u2026]" line${ie(p.places)} \u2014 either give each one a proper screenshot block or take the line out`,reason:"these lines belong to no screenshot, so no command can finish them"},picker:null,follow:p.cmd?`Then ${p.cmd} deals with the ${p.places} missing picture${ie(p.places)}, and /push and /publish take the ${p.articles} article${ie(p.articles)} live.`:`Then the ${p.places} bare "[Screenshot: \u2026]" line${ie(p.places)} can be sorted out, and /push and /publish take the ${p.articles} article${ie(p.articles)} live.`,...p.stage==="spec"||p.stage==="capture"?{opensRound:!0}:{}}:e.shotsToAnnotate>0?{key:"annotate",bullet:`${e.shotsToAnnotate} screenshot${ie(e.shotsToAnnotate)} ${e.shotsToAnnotate===1?"has":"have"} been taken but ${e.shotsToAnnotate===1?"is":"are"} not finished \u2014 the callouts aren't drawn on, so ${e.shotsToAnnotate===1?"it cannot":"they cannot"} be published`,lead:{kind:"cmd",cmd:"/screenshot annotate",reason:"it draws the callouts on \u2014 no browser, about a second per picture"},picker:null,follow:`Then /screenshot annotate finishes the ${e.shotsToAnnotate} screenshot${ie(e.shotsToAnnotate)} already taken.`}:e.shotsToRecapture>0?{key:"annotate",bullet:`${e.shotsToRecapture} screenshot${ie(e.shotsToRecapture)} ${e.shotsToRecapture===1?"has":"have"} a plan for what to point at but no picture \u2014 the picture has to be taken again before anything can be drawn on it`,lead:{kind:"cmd",cmd:"/screenshot capture",reason:"it takes the picture again in a browser, and the callouts are drawn on straight after"},picker:null,follow:`Then /screenshot capture re-takes the ${e.shotsToRecapture} missing picture${ie(e.shotsToRecapture)}.`,opensRound:!0}:null,$=m!==null&&p!==null&&p.articles>0;if(m&&!$&&e.localAhead>0&&n.push(m),r&&!s&&n.push(r),e.localAhead>0){let w=e.localAhead;n.push({key:"publish",bullet:`${w} article${ie(w)} changed locally \u2014 ready to send to Document360`,lead:{kind:"cmd",cmd:"/push",reason:`it saves your ${w} local edit${ie(w)} to Document360 as drafts`},picker:null,follow:`Then /push saves your ${w} local edit${ie(w)} to Document360.`,dependsOn:["discovery","comments","audit","annotate"],blockedBy:["review","styleguide"]})}if(a&&!c&&n.push(a),m&&($||e.localAhead===0)&&n.push(m),e.hasDocs&&e.roadmap?.next){let w=e.roadmap,C=w.next,S=C.run?t?.scaleFor?.(C.run)??null:null,T=C.run?S:C$(C.body),R=C.run?S??void 0:C$(C.body,340,2)??void 0,D=`docs campaign: ${w.done} of ${w.total} step${ie(w.total)} done`,U=!!C.run&&Xj(C.run,e.lastCommand);n.push(U?{key:"roadmap",bullet:`${D} \u2014 \u201C${C.title}\u201D is waiting on you
|
|
450
|
-
\u2022 You just ran ${C.run}. It showed you where things stand; the step stays open until you act on what it showed, or close it with /roadmap done.`,lead:null,picker:null,follow:null}:{key:"roadmap",bullet:`${D} \u2014 next: ${C.title}${
|
|
451
|
-
\u2022 ${
|
|
452
|
-
\u2022 ${
|
|
453
|
-
`),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}):C>0&&n.push({key:"share",bullet:`\u26A0 ${C} docs change set${ie(C)} saved but not sent \u2014 someone else pushed to this branch first (your work is safe)`,lead:{kind:"cmd",cmd:"/share",reason:"it retries sending your saved work; if it keeps failing, your builder can merge the branch"},picker:null,follow:null})}else if(e.uncommittedDocs>0){let w=e.uncommittedDocs;n.push({key:"commit",bullet:`\u26A0 ${w} uncommitted change${ie(w)} under
|
|
454
|
-
`):G=[e,"",` ${
|
|
455
|
-
`),{note:[...o?[o]:[],G,
|
|
456
|
-
|
|
457
|
-
`),menu:H.map(ne=>ne.run??ne.title)}}let c=l?null:
|
|
458
|
-
\u2022 `),G=D===c&&D.lead?.kind!=="answer"&&D.lead?.detail?[]:J;if(
|
|
445
|
+
`),display:`/restructure${n?` ${n}`:""}`}}async function J$(e,t){let n=Mf(t.cwd,e);return n?{kind:"forward-to-agent",prompt:n.prompt,display:n.display}:(console.log(L(be)),{kind:"continue"})}ae();import{computeReadiness as fI,readinessPlaceholderPlaces as mI,coverageGap as gI,danglingCount as yI,PRODUCT_NAME as wI}from"document360-engine";import Be from"picocolors";var Kn=5;function Fe(e,t=58){let n=e.replace(/\\/g,"/");return n.length<=t?n:`\u2026${n.slice(n.length-t+1)}`}function kI(e){let t=[],n=e.verdict;if(e.conflicts.length>0&&t.push({glyph:"\u2717",paint:Be.red,title:`Changed here and on Document360 (${e.conflicts.length})`,fix:"/resolve",items:e.conflicts.map(o=>Fe(o))}),n.unreviewed.length>0&&t.push({glyph:"\u2717",paint:Be.red,title:`Never read by an editor (${n.unreviewed.length})`,fix:"/review --blocked --fix",items:n.unreviewed.map(o=>Fe(o))}),n.styleErrors.length>0){let o=n.styleErrors.reduce((r,s)=>r+s.errors,0);t.push({glyph:"\u2717",paint:Be.red,title:`Break house style rules your config makes blocking (${o} error${o===1?"":"s"})`,fix:"/lint --blocked --fix",items:n.styleErrors.map(r=>`${Fe(r.path)} (${r.errors})`)})}if(n.placeholders.length>0){let o=mI(e);t.push({glyph:"\u2717",paint:Be.red,title:`Would show "[Screenshot: \u2026]" to your readers (${n.placeholders.length} article${n.placeholders.length===1?"":"s"}, ${o} place${o===1?"":"s"})`,fix:"/screenshot",items:n.placeholders.map(r=>`${Fe(r.path)} (${r.missingShots.length+r.orphans})`)})}return t}function bI(e){let t=e.verdict,n=[];return e.conflicts.length===0&&n.push(`${V("\u2713",Be.green)}Nothing is in conflict with Document360`),t.unreviewed.length===0&&n.push(`${V("\u2713",Be.green)}Every article has been read by an editor`),t.styleErrors.length===0&&n.push(`${V("\u2713",Be.green)}House style: nothing blocking`),t.placeholders.length===0&&n.push(`${V("\u2713",Be.green)}No placeholder text would reach a reader`),n}function $I(e,t){if(e.rows.length===0)return[];let n=r=>r?Be.green("\u2713"):Be.red("\u2717"),o=e.rows.map((r,s)=>[String(s+1),Fe(r.path,46),n(r.reviewed),r.styleErrors===0?Be.green("\u2713"):Be.red(`\u2717 ${r.styleErrors}`),r.placeholders===0?Be.green("\u2713"):Be.red(`\u2717 ${r.placeholders}`),r.conflict?Be.red("conflict"):r.draftPending?Be.yellow("draft"):r.localAhead?u("not saved"):u("\u2014")]);return ki(["#","Article","Read","Style","Pictures","Document360 (last sync)"],o,t).split(`
|
|
446
|
+
`)}function Uf(e,t={}){let n=fI(e,t.profileName),o=[];if(n.rows.length===0){o.push(Z("Publish readiness")),o.push("");let p=gI(n.coverage),m=n.neverPushed.length;return o.push(n.tracked===0?m>0?`${V("\u25CB",Be.gray)}Nothing here is on Document360 yet.`:`${V("\u25CB",Be.gray)}No articles are tracked yet. /write authors them, /push saves them to Document360.`:p>0||m>0?`${V("\u2713",Be.green)}All ${n.tracked} tracked articles are live and unchanged.`:`${V("\u2713",Be.green)}All ${n.tracked} articles are live and unchanged \u2014 nothing is waiting on you.`),o.push(...vI(n)),n.neverPushed.length>0&&(o.push(""),o.push(...Z$(n))),n.orphans.length>0&&o.push(...tv(n)),n.unadopted.length>0&&(o.push(""),o.push(...ev(n))),o.push(""),o.push(u(" Free \u2014 /status reads your local files and the last sync. It calls nothing.")),o}let r=n.rows.length,s=n.blocked.length;o.push(Z("Publish readiness")+u(` ${r} article${r===1?"":"s"} not yet settled with readers \xB7 ${s===0?"nothing blocked":`${s} blocked`}`)),o.push(""),t.all&&(o.push(...$I(n,t.width??100)),o.push(""));for(let p of kI(n)){o.push(` ${V(p.glyph,p.paint)}${p.title}${p.fix?u(` ${p.fix}`):""}`);for(let m of p.items.slice(0,Kn))o.push(u(` ${m}`));p.items.length>Kn&&o.push(u(` \u2026and ${p.items.length-Kn} more`)),o.push("")}let i=Z$(n);i.length>0&&(o.push(...i),o.push(""));let a=ev(n);a.length>0&&(o.push(...a),o.push(""));let l=bI(n);if(l.length>0){for(let p of l)o.push(` ${p}`);o.push("")}let c=n.rows.filter(p=>p.localAhead).length;return c>0&&o.push(u(` ${c} changed here \u2014 /push saves ${c===1?"it":"them"} to Document360 as ${c===1?"a draft":"drafts"}. Readers see nothing until then.`)),n.draftPending.length>0&&(o.push(u(` ${n.draftPending.length} saved on Document360 as ${n.draftPending.length===1?"a draft":"drafts"} and not live \u2014 /publish takes ${n.draftPending.length===1?"it":"them"} to your readers.`)),o.push(u(" That is from your last sync. /pull re-checks what is live."))),n.orphans.length>0&&o.push(...tv(n)),!t.all&&n.rows.length>0&&o.push(u(" /status --all shows every article, gate by gate.")),o.push(""),o.push(u(" Free \u2014 /status reads your local files and the last sync. It calls nothing.")),o}function Z$(e){let t=e.neverPushed.length;if(t===0)return[];let n=[` ${V("\u25CB",Be.gray)}${t===1?"One article is":`${t} articles are`} written here and ${t===1?"has":"have"} never been saved to Document360`,u(` Your readers cannot see ${t===1?"it":"them"} at all yet \u2014 not even as a draft.`)];for(let o of e.neverPushed.slice(0,Kn))n.push(` ${Fe(o)}`);return t>Kn&&n.push(u(` \u2026and ${t-Kn} more`)),n.push(u(" /push --all saves them as drafts; /publish then takes them live.")),n}function ev(e){let t=e.unadopted.length;if(t===0)return[];let n=[` ${V("\u25CB",Be.gray)}${t===1?"One page here came from Document360 and nothing has adopted it":`${t} pages here came from Document360 and nothing has adopted them`}`,u(` Not in your docs plan, not written by ${wI}, and nothing records what ${t===1?"it says":"they say"}.`),u(` So no editor can check ${t===1?"it":"them"}: a review pass over ${t===1?"it":"them"} comes back having changed nothing.`)];for(let o of e.unadopted.slice(0,Kn))n.push(` /untrack ${o.path}`);return t>Kn&&n.push(u(` \u2026and ${t-Kn} more`)),n.push(u(" Disowning one leaves Document360 untouched \u2014 the page, its history and its comments all stay.")),n}function tv(e){let t=e.orphans.length;return[u(` ${t} article${t===1?"":"s"} on Document360 ${t===1?"is":"are"} not in your docs folder (${Fe(e.orphans[0].path,40)}${t>1?`, +${t-1} more`:""}) \u2014 /doctor lists ${t===1?"it":"them"}.`)]}function nv(e){let t=Date.now()-Date.parse(e);if(!Number.isFinite(t)||t<0)return"just now";let n=Math.floor(t/6e4);if(n<2)return"just now";if(n<60)return`${n} minutes ago`;let o=Math.floor(n/60);if(o<24)return`${o} hour${o===1?"":"s"} ago`;let r=Math.floor(o/24);return`${r} day${r===1?"":"s"} ago`}function vI(e){let t=e.coverage;if(!t)return e.tracked===0?[]:["",u(" Nothing has compared this repo with Document360 yet."),"",u(" /pull --status counts what is there.")];if(t.unmapped===0)return[u(` Every Document360 article is tracked here (${t.mappedArticles} of ${t.portalArticles}, checked ${nv(t.at)}).`),...ov(t)];let n=t.portalOnlyCategories.filter(r=>r.articles>0).length,o=["",F(` ${V(qo,Be.yellow)}Document360 holds ${t.portalArticles} articles in ${t.portalCategories} categories.`),"",u(` This repo tracks ${t.mappedArticles} of them.`)];return n>0&&(o.push(""),o.push(u(` ${t.unmapped} articles sit in ${n} ${n===1?"category":"categories"} with no folder here.`))),t.declined>0&&(o.push(""),o.push(u(` ${t.declined} more ${t.declined===1?"is one you":"are ones you"} declined with /untrack.`))),o.push(""),o.push(u(` /pull imports them. Checked ${nv(t.at)}.`)),o.push(...ov(t)),o}function ov(e){let t=yI(e);if(t===null||t===0)return[];let n=e.dangling?.articles??[],o=e.dangling?.categories??[],r=["",F(` ${V(qo,Be.yellow)}${n.length>0?`${n.length} ${n.length===1?"article":"articles"} here point`:""}${n.length>0&&o.length>0?" \u2014 and ":""}${o.length>0?`${o.length} ${o.length===1?"folder points":"folders point"}`:""} at something Document360 no longer has.`)];r.push("");for(let s of n.slice(0,5))r.push(u(` ${s}`));return n.length>5&&r.push(u(` \u2026and ${n.length-5} more.`)),r.push(""),r.push(u(" Someone deleted them on the portal, or they were replaced by newer articles.")),r.push(""),r.push(u(" /push saves them again for your readers. /untrack drops the ones you no longer want.")),r}async function rv(e,t){let n=e.some(o=>o==="--all"||o==="--full");for(let o of Uf(t.cwd,{profileName:t.profileName,all:n}))console.log(o);return{kind:"continue",ownNext:!0}}ae();import{computeReadiness as xI,retireArticle as RI,retiredPaths as SI,normalizeScope as CI}from"document360-engine";import{select as PI}from"@inquirer/prompts";function Ff(e,t){let n=xI(e,t),o=SI(e,t),r=[Z("Take an article off your readers"),""];if(n.orphans.length>0){r.push(` ${V("\u25CB",u)}On Document360, but not in your docs folder \u2014 the usual reason to retire:`);for(let s of n.orphans.slice(0,8))r.push(u(` ${Fe(s.path)}`));n.orphans.length>8&&r.push(u(` \u2026and ${n.orphans.length-8} more`)),r.push("")}if(o.length>0){r.push(` ${V("\u2713",u)}Already retired \u2014 readers do not see ${o.length===1?"it":"these"}:`);for(let s of o.slice(0,5))r.push(u(` ${Fe(s)}`));o.length>5&&r.push(u(` \u2026and ${o.length-5} more`)),r.push("")}return n.orphans.length===0&&o.length===0&&(r.push(u(" Nothing obvious to retire \u2014 every tracked article is still in your docs folder.")),r.push("")),r.push(u(" /retire <path> takes one off your readers. Any tracked article can be named, not just these.")),r.push(u(" Nothing is deleted: the article, its history and every reviewer comment stay on Document360.")),r.push(u(" /push puts one back \u2014 reviving is a publish like any other, with the same review.")),r}async function sv(e,t){let n=t.cwd,o=e.find(a=>!a.startsWith("-"));if(!o){for(let a of Ff(n,t.profileName))console.log(a);return{kind:"continue",ownNext:!0}}let r=CI(n,o)||o;if(!(e.includes("--yes")||e.includes("-y"))&&(console.log(""),console.log(F(`This takes "${Fe(r)}" off your readers on Document360.`)),console.log(u(" The article, its history and every reviewer comment stay \u2014 nothing is deleted.")),console.log(u(" /push puts it back later if you change your mind.")),console.log(""),await PI({message:"Take it off your readers?",choices:[{name:"No \u2014 leave it as it is",value:"no"},{name:"Yes \u2014 readers stop seeing it",value:"yes"}]})!=="yes"))return console.log(u("Nothing changed.")),{kind:"continue",ownNext:!0};let i=await RI({cwd:n,path:r,profileName:t.profileName,now:new Date().toISOString()});return i.ok?(console.log(i.alreadyHidden?`${V("\u2713")}"${Fe(r)}" was already invisible to readers. Recorded as retired, so nothing will offer to publish it again.`:`${V("\u2713")}"${Fe(r)}" is no longer visible to your readers.`),console.log(u(" It is still on Document360 with its history and comments intact. /push puts it back.")),{kind:"continue",ownNext:!0}):(console.log(L(`${V("\u2717")}Could not retire "${Fe(r)}" \u2014 ${i.error.message}`)),{kind:"continue",ownNext:!0})}ae();import{declineImport as AI,loadDeclinedImports as TI,undoDecline as EI,normalizeScope as NI,resolveActiveProfile as DI,WRITER_DIRNAME as jI}from"document360-engine";import{select as II}from"@inquirer/prompts";function Wf(e,t){let n={};try{n=TI(e,DI(e,t).name)}catch{}let o=Object.keys(n),r=[Z("Pages on Document360 that are not part of these docs"),""];if(o.length===0)r.push(u(" Nothing is declined. Every article on Document360 in one of your categories is")),r.push(u(" imported into your docs folder when you run /catch-up or /pull."));else{for(let s of o.slice(0,10)){let i=n[s];r.push(` ${V("\u25CB",u)}${i.title??i.path??s}`),i.path&&r.push(u(` was ${Fe(i.path)}`)),i.keptAt&&r.push(u(` kept at ${i.keptAt}`))}o.length>10&&r.push(u(` \u2026and ${o.length-10} more`))}return r.push(""),r.push(u(" /untrack <path> disowns an imported page \u2014 nothing on Document360 changes.")),r.push(u(" /untrack --undo <path> puts it back and lets the next /catch-up import it again.")),r}async function iv(e,t){let n=t.cwd,o=e.find(c=>!c.startsWith("-")),r=e.includes("--list")||e.includes("-l"),s=e.includes("--undo");if(r||!o&&!s){for(let c of Wf(n,t.profileName))console.log(c);return{kind:"continue",ownNext:!0}}if(!o)return console.log(L(`${V("\u2717")}Name what to put back: /untrack --undo <path>`)),{kind:"continue",ownNext:!0};let i=NI(n,o)||o;if(s){let c=EI(n,t.profileName,i);return c.ok?(console.log(c.restoredTo?`${V("\u2713")}Put "${Fe(c.restoredTo)}" back in your docs folder.`:`${V("\u2713")}No longer declined. /catch-up imports it again on the next run.`),{kind:"continue",ownNext:!0}):(console.log(L(`${V("\u2717")}${c.error.message}`)),{kind:"continue",ownNext:!0})}if(!(e.includes("--yes")||e.includes("-y"))&&(console.log(""),console.log(F(`This stops tracking "${Fe(i)}" as one of your docs.`)),console.log(u(" Nothing on Document360 changes \u2014 the page, its history and its comments all stay,")),console.log(u(" and your readers see no difference.")),console.log(u(` The markdown moves to ${jI}/declined/, so nothing is deleted.`)),console.log(u(" /untrack --undo puts it back if you change your mind.")),console.log(""),await II({message:"Stop tracking it?",choices:[{name:"No \u2014 leave it as it is",value:"no"},{name:"Yes \u2014 it is not one of my docs",value:"yes"}]})!=="yes"))return console.log(u("Nothing changed.")),{kind:"continue",ownNext:!0};let l=AI({cwd:n,path:i,profileName:t.profileName,now:new Date().toISOString()});return l.ok?(console.log(`${V("\u2713")}"${l.title??Fe(l.path)}" is no longer one of your docs.`),l.keptAt&&console.log(u(` The markdown is kept at ${l.keptAt} \u2014 nothing was deleted.`)),console.log(u(" It is untouched on Document360. /catch-up will not import it again.")),{kind:"continue",ownNext:!0}):(console.log(L(`${V("\u2717")}Could not untrack "${Fe(i)}" \u2014 ${l.error.message}`)),{kind:"continue",ownNext:!0})}ae();import{scanTerminology as av,approvalBlockedReason as lv,readProjectConfig as LI,writeProjectConfig as OI,termKey as Bf,HEAD_NOUN_CAP as _I}from"document360-engine";import pn from"picocolors";var MI=3,UI=e=>e.uses.map(t=>`${pn.bold(t.form)} ${u(`${t.files.length} article${t.files.length===1?"":"s"}`)}`).join(u(" \xB7 "));function Hf(e,t={}){let n=av(e,t.scope?{scope:t.scope}:{}),o=[];if(n.scanned===0)return[Z("Terminology"),"",`${V("\u25CB",u)}No articles to read yet.`,""];let r=n.variance.length+n.headings.length;if(o.push(Z("Terminology")+u(` ${n.scanned} article${n.scanned===1?"":"s"} read \xB7 ${r===0?"nothing inconsistent":`${r} to look at`}`)),o.push(""),n.variance.length>0){o.push(` ${V("\u2717",pn.red)}The same term, spelled more than one way`);for(let s of n.variance){o.push(` ${UI(s)}`);let i=s.uses[s.uses.length-1],a=i.files.slice(0,MI);o.push(u(` "${i.form}" is in ${a.map(c=>Fe(c,40)).join(", ")}${i.files.length>a.length?`, +${i.files.length-a.length} more`:""}`));let l=lv(s);l?o.push(u(` ${l}`)):o.push(u(` /terms --approve "${s.uses[0].form}" makes that the approved spelling`))}o.push("")}if(n.headNouns.length>0){let s=t.all?n.headNouns:n.headNouns.slice(0,_I);o.push(` ${V("\u25CB",u)}Possibly the same thing under a short name \u2014 ${pn.italic("your call")}`);for(let i of s)o.push(u(` ${i.uses.map(a=>a.form).join(" \xB7 ")}`));n.headNouns.length>s.length&&o.push(u(` \u2026and ${n.headNouns.length-s.length} more \u2014 /terms --all lists them`)),o.push(u(' A shared word is not proof of a shared meaning: "billing history" and "history" are')),o.push(u(" different things. Nothing is flagged as wrong here.")),o.push("")}if(n.headings.length>0){o.push(` ${V("\u26A0",pn.yellow)}Titles out of step with the rest of their kind`);for(let s of n.headings)o.push(` ${pn.bold(s.title)} ${u(`\u2014 ${Fe(s.path,40)}`)}`),o.push(u(` the other ${s.peers} ${s.type} article${s.peers===1?"":"s"} look like "${s.example}"; this one starts ${FI(s.shape)}`));o.push("")}return r===0&&n.headNouns.length===0&&(o.push(` ${V("\u2713",pn.green)}Every term is spelled one way, and every title matches its kind.`),o.push("")),o.push(u(' This compares spellings, not meanings: two different words for one thing (say "nav" and')),o.push(u(' "rail") look unrelated to it. Add the pair to your approved terms and every run enforces it.')),o.push(u(" Free \u2014 this read your articles and called nothing.")),o}function FI(e){return e==="gerund"?"with an -ing word":e==="how-to"?'with "How to"':"differently"}function Gf(e,t,n){let o=n??av(e),r=Bf(t),s=o.variance.find(m=>m.uses.some($=>Bf($.form)===r));if(!s)return{wrote:!1,lines:[`${V("\u2717",pn.red)}"${t}" is not one of the terms with competing spellings. /terms lists them.`]};let i=lv(s);if(i)return{wrote:!1,lines:[`${V("\u2717",pn.red)}That one cannot be recorded: ${i}.`,u(` The spellings in play are ${s.uses.map(m=>`"${m.form}"`).join(" and ")}.`)]};let a=s.uses.find(m=>Bf(m.form)===r).form,l=s.uses.filter(m=>m.form!==a).map(m=>m.form),c=LI(e);if(!c)return{wrote:!1,lines:[`${V("\u2717",pn.red)}No project configuration here \u2014 run /init first.`]};let p={...c.terminologyGlossary??{}};for(let m of l)p[m]=a;return OI({...c,terminologyGlossary:p},e),{wrote:!0,lines:[`${V("\u2713",pn.green)}"${a}" is now the approved spelling.`,u(` Added to your approved terms: ${l.map(m=>`"${m}" \u2192 "${a}"`).join(", ")}`),u(" Every run enforces it from now on, and /lint --fix corrects the others for free.")]}}async function cv(e,t){let n=e.findIndex(s=>s==="--approve");if(n!==-1){let s=e[n+1];if(!s)return console.log(`${V("\u2717",pn.red)}Name the spelling to approve, e.g. /terms --approve "drop-down".`),{kind:"continue",ownNext:!0};for(let i of Gf(t.cwd,s.replace(/^["']|["']$/g,"")).lines)console.log(i);return{kind:"continue",ownNext:!0}}let o=e.includes("--all"),r=e.find(s=>!s.startsWith("--"));for(let s of Hf(t.cwd,{...r?{scope:r}:{},all:o}))console.log(s);return{kind:"continue",ownNext:!0}}ae();import{evaluateCorpus as WI,buildRegistry as BI,lintArticles as HI,scanTerminology as GI,BUILTIN_RULES as qI,surfaceCoverageSafe as VI,readProjectConfig as KI}from"document360-engine";import It from"picocolors";var Ct=3,it=(e,t)=>`${e} ${t}${e===1?"":"s"}`,uv=e=>`${Fe(e.path)}:${e.line}`,qf=e=>e.split("/").pop()?.split("\\").pop()??e;function Vf(e,t,n,o,r,s,i){if(r.length===0)return;e.push(` ${V(t,n)}${o}`);let a=i?r:r.slice(0,Ct);for(let l of a)e.push(u(` ${uv(l)} ${l.detail}`));r.length>a.length&&e.push(u(` \u2026and ${r.length-a.length} more \u2014 /eval --all`)),e.push(u(` ${s}`)),e.push("")}function Kf(e,t={}){let n=BI(e),o=new Set([...qI.map(p=>p.id),...n.rules.map(p=>p.id)]),r=WI(e,o,{...t.scope?{scope:t.scope}:{},...t.profile?{profile:t.profile}:{}}),s=t.all===!0,i=[];if(r.articles===0)return[Z("Knowledge-base score"),"",`${V("\u25CB",u)}No articles to read yet.`,""];let a=VI(e,KI(e)),l=r.links.absolute.length+r.links.deadTargets.length+r.links.deadAnchors.length+r.links.staleLabels.length+r.sources.missing.length+r.shapes.typeTemplates.filter(p=>p.deviations.length>0).length+(r.shapes.synopsisForms.length>1?1:0)+(a.recognised?a.areas.length:0);if(i.push(Z("Knowledge-base score")+u(` ${it(r.articles,"article")} read \xB7 ${l===0?"nothing to look at":`${l} to look at`}`)),i.push(""),Vf(i,"\u2717",It.red,"Links pointing at articles that do not exist",r.links.deadTargets,"The article was renamed or retired after the link was written. Point it at the one that replaced it.",s),r.links.deadTargets.length===0&&r.links.sidebarDeadTargets>0&&(i.push(u(` ${r.links.sidebarDeadTargets} dead link${r.links.sidebarDeadTargets===1?"":"s"} in a Related articles list \u2014 excluded, the portal rebuilds that list itself`)),i.push("")),Vf(i,"\u2717",It.red,"Internal links written as portal URLs",r.links.absolute,"These break the day the site moves. Write them as relative .md links instead.",s),Vf(i,"\u2717",It.red,"Links pointing at headings that do not exist",r.links.deadAnchors,"The heading was renamed after the link was written. Point it at the current heading.",s),r.links.staleLabels.length>0){let p=r.links.staleLabels.reduce((m,$)=>m+$.sites.length,0);i.push(` ${V("\u26A0",It.yellow)}${it(r.links.staleLabels.length,"link label")} name an article something it is not called${p>r.links.staleLabels.length?u(`, in ${it(p,"place")}`):""}`);for(let m of s?r.links.staleLabels:r.links.staleLabels.slice(0,Ct))if(i.push(u(` "${m.label}" \u2192 the article is titled "${m.title}"${m.sites.length>1?` (${m.sites.length}\xD7)`:""}`)),s)for(let $ of m.sites)i.push(u(` ${uv($)}`));!s&&r.links.staleLabels.length>Ct&&i.push(u(` \u2026and ${r.links.staleLabels.length-Ct} more \u2014 /eval --all`)),i.push(u(" A reader clicks expecting one page and lands on another name.")),i.push("")}if(s&&r.links.shortenedLabels.length>0){i.push(` ${V("\u25CB",u)}${it(r.links.shortenedLabels.length,"link label")} shorten the title they point at`);for(let p of r.links.shortenedLabels.slice(0,10))i.push(u(` "${p.label}" \u2192 "${p.title}"`));i.push(u(" Usually fine. Listed separately because it is a judgment call, not a defect.")),i.push("")}if(s&&r.links.sidebarLabelMismatch>0&&(i.push(` ${V("\u25CB",u)}${it(r.links.sidebarLabelMismatch,"Related-articles link")} not counted above`),i.push(u(" Those labels are dropped when the article is saved. Document360 builds that list from")),i.push(u(" the real titles, so a reader never sees the label written here.")),i.push("")),r.shapes.synopsisForms.length>1){i.push(` ${V("\u26A0",It.yellow)}The command summary line appears in ${it(r.shapes.synopsisForms.length,"shape")}`);for(let p of r.shapes.synopsisForms)i.push(u(` ${String(p.count).padStart(3)} ${p.form.padEnd(14)} ${p.examples.map(qf).join(", ")}`));r.shapes.noSynopsis.length>0&&i.push(u(` ${it(r.shapes.noSynopsis.length,"article")} carry none at all`)),i.push(u(" Same information, different labels. Pick one and use it everywhere.")),i.push("")}for(let p of r.shapes.typeTemplates)if(p.deviations.length!==0){i.push(` ${V("\u26A0",It.yellow)}${p.deviations.length} of ${it(p.articles,`${p.type} article`)} skip a section the rest of them carry`),i.push(u(` Most ${p.type} articles have: ${p.expected.map(m=>`## ${m.heading} (${m.count})`).join(" \xB7 ")}`));for(let m of s?p.deviations:p.deviations.slice(0,Ct))i.push(u(` ${qf(m.path)} \u2014 missing ${m.missing.map($=>`## ${$}`).join(", ")}`));!s&&p.deviations.length>Ct&&i.push(u(` \u2026and ${p.deviations.length-Ct} more \u2014 /eval --all`)),i.push(u(" A deviation may be deliberate. This counts them; it does not say the template is right.")),i.push("")}try{let p=GI(e,t.scope?{scope:t.scope}:{});if(p.variance.length>0){i.push(` ${V("\u26A0",It.yellow)}${it(p.variance.length,"term")} spelled more than one way across the set`);for(let m of p.variance.slice(0,s?99:Ct))i.push(u(` ${m.uses.map($=>`"${$.form}" \xD7${$.count}`).join(" \xB7 ")}`));p.headNouns.length>0&&i.push(u(` ${it(p.headNouns.length,"short name")} may be a longer one abbreviated \u2014 /terms lists them`)),i.push(u(' Settle one and every later run enforces it: /terms --approve "<term>"')),i.push("")}}catch{}let c=0;try{let m=HI({cwd:e,...t.scope?{scope:t.scope}:{}}).findings.filter(w=>!w.baselined);c=m.filter(w=>w.ruleId==="Document360.Changelog").length;let $=m.filter(w=>w.severity==="error").length;if(i.push(` ${V($>0?"\u2717":m.length>0?"\u26A0":"\u2713",$>0?It.red:m.length>0?It.yellow:It.green)}`+(m.length===0?"Style rules: nothing reported":`Style rules: ${it(m.length,"finding")}${$>0?`, ${$} blocking publish`:", none blocking publish"}`)),m.length>0){let w=new Map;for(let C of m)w.set(C.ruleId,(w.get(C.ruleId)??0)+1);for(let[C,S]of[...w.entries()].sort((A,R)=>R[1]-A[1]).slice(0,s?99:5))i.push(u(` ${String(S).padStart(4)} ${C}`));i.push(u(" Fix what can be fixed mechanically: /lint --fix"))}i.push("")}catch{}if(r.debt&&r.debt.total>0){let p=r.debt.liveRules.reduce((w,C)=>w+C.count,0),m=r.debt.inertRules.reduce((w,C)=>w+C.count,0),$=r.debt.createdAt.slice(0,10);if(p>0){i.push(` ${V("\u2139",u)}${it(p,"style finding")} accepted as exempt on ${$}, from rules that are still on`);for(let w of r.debt.liveRules.slice(0,s?99:4))i.push(u(` ${String(w.count).padStart(4)} ${w.rule}`));i.push(u(" Nothing reports these, so the articles read as compliant. They are exempt, not compliant.")),i.push(u(" Work them down with /review --all --fix, then /lint --all --fix."))}else m>0&&(i.push(` ${V("\u25CB",u)}${it(m,"finding")} accepted on ${$} under a style guide no longer in use`),i.push(u(" They match no active rule, so they suppress nothing. Only weight in the file.")));i.push("")}if(r.sources.missing.length>0){i.push(` ${V("\u26A0",It.yellow)}${it(r.sources.missing.length,"article")} cite a file that is not in the repository`);for(let p of s?r.sources.missing:r.sources.missing.slice(0,Ct))i.push(u(` ${p.source}${u(" \u2190 ")}${p.path}`));!s&&r.sources.missing.length>Ct&&i.push(u(` \u2026and ${r.sources.missing.length-Ct} more \u2014 /eval --all`)),i.push(u(" Renamed or deleted since the article was written. /audit points it at the file that replaced it.")),i.push("")}if(a.recognised&&a.areas.length>0){i.push(` ${V("\u26A0",It.yellow)}${it(a.areas.length,"part")} of the product no article says it documents`);for(let p of a.areas.slice(0,s?99:5))i.push(u(` ${String(p.files).padStart(4)} ${p.folder}`));!s&&a.areas.length>5&&i.push(u(` \u2026and ${a.areas.length-5} more \u2014 /eval --all lists them.`)),i.push(u(` ${a.documented} of ${a.filesScanned} source files are cited by an article.`)),a.declined>0&&i.push(u(` ${a.declined} you declined, left out of that count.`)),i.push(u(" /audit proposes the articles. /audit --decline <path> settles a folder or file for good.")),i.push("")}else a.recognised||(i.push(` ${V("\u25CB",u)}Product coverage was not measured`),i.push(u(` ${a.reason}`)),i.push(""));if(i.push(` ${V("\u25CB",u)}Length: ${r.length.words.toLocaleString()} words, median ${r.length.median.toLocaleString()} an article`),r.length.longest.length>0){i.push(u(` ${it(r.length.longest.length,"article")} past 2,500 words:`));for(let p of s?r.length.longest:r.length.longest.slice(0,Ct))i.push(u(` ${p.words.toLocaleString()} ${qf(p.path)}`));!s&&r.length.longest.length>Ct&&i.push(u(` \u2026and ${r.length.longest.length-Ct} more \u2014 /eval --all`))}return c>0&&(i.push(u(` ${it(c,"sentence")} tell the reader what the product used to do.`)),i.push(u(" Those are the longest sentences in a corpus, and the cheapest words to take out."))),i.push(u(" No previous measurement to compare against, so this is a reading, not a trend.")),i.push(""),l===0&&(r.debt?.total??0)===0&&(i.push(` ${V("\u2713",It.green)}Links resolve, one template shape, one name per thing.`),i.push("")),i.push(u(` Free \u2014 this read your ${it(r.articles,"article")} and called nothing.`)),i}async function dv(e,t){let n=e.includes("--all"),o=e.find(r=>!r.startsWith("--"));for(let r of Kf(t.cwd,{...o?{scope:o}:{},...t.profileName?{profile:t.profileName}:{},all:n}))console.log(r);return{kind:"continue",ownNext:!0}}import{fetchPortalReuse as dL,readReuseCache as pL,writeReuseCache as hL,resolveActiveProfile as Xf,resolveProjectId as Qf,createVariable as gv,createSnippet as yv,reuseNameProblem as fL,variableRule as mL,VARIABLE_MAX_CHARS as fv}from"document360-engine";ae();import{scanReuse as pv,scanValueCandidates as hv,buildReuseAuditPrompt as YI,reuseAuditProposalPath as zI,readReuseProposal as XI,readReuseCache as QI,listArticleFiles as JI,normalizeScope as ZI,docsRootOf as eL,variableRule as tL}from"document360-engine";import{rmSync as nL}from"node:fs";import oL from"picocolors";var Nc=6,rL=20;function sL(e,t){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}\u2026`:n}function iL(e,t=52){let n=e.replace(/\s+/g," ").trim(),o=[],r="";for(let s of n.split(" "))r===""?r=s:`${r} ${s}`.length<=t?r+=` ${s}`:(o.push(r),r=s);return r!==""&&o.push(r),o}function Dc(e,t,n,o){let r=[Z("Content reuse audit"),""];return r.push(`${e} article${e===1?"":"s"} read${u(" \xB7 free to look")}`,""),r.push(` ${String(n).padStart(3)} value${n===1?"":"s"} written out by hand in more than one article`),r.push(` ${String(t).padStart(3)} block${t===1?"":"s"} written more than once, in different words`),o>0&&r.push(u(` ${o} more families were left out of this pass \u2014 the longest ones are shown first.`)),r}function jc(e,t){let n=eL(e),o=t.filter($=>$!=="audit"&&!$.startsWith("--")).find($=>$!==void 0),r=o?ZI(n,o.replace(/\\/g,"/").replace(/\/+$/,"")):void 0,s=JI(e,r).length;if(s===0)return{lines:[te("\u25CB",r?`No articles under ${r} to audit.`:"No articles to audit yet."),u(" Reuse is about text that repeats, so there has to be some text first.")]};let i=pv(e,{...r?{scope:r}:{},groups:!0}),a=hv(e,r?{scope:r}:void 0),l=i.groups??[],c=a.candidates;if(l.length===0&&c.length===0)return{lines:[te("\u2713",`Nothing repeats across ${s} article${s===1?"":"s"} \u2014 there is nothing to keep in one place.`),u(" That is a good answer, not an empty one. Run this again after a few more articles.")]};let p=QI(e),m=zI(e);try{nL(m,{force:!0})}catch{}return{prompt:YI({cwd:e,families:l,values:c,snippets:p?.snippets??[],variables:p?.variables??[],terms:p?.terms??[],proposalPath:m,articles:s}),display:r?`/reuse audit ${r}`:"/reuse audit",articles:s,families:l.length,values:c.length}}function aL(e,t){let n=[],o=` ${String(t).padStart(2)} ${e.kind.padEnd(9)}${oL.bold(e.name.padEnd(rL))}`,r=e.kind==="variable"?[`"${sL(e.value,52)}"`]:iL(`"${e.value}"`);n.push(`${o}${r[0]??""}`);for(let a of r.slice(1))n.push(`${" ".repeat(o.length-10)}${a}`);let s=e.uses>0?`${e.uses} use${e.uses===1?"":"s"} across ${e.files} article${e.files===1?"":"s"}`:"",i=e.why?s?` \u2014 ${e.why}`:e.why:"";return(s||i)&&n.push(u(` ${s}${i}`)),n}function lL(e,t,n){let o=[],r=e.proposals.length;if(o.push(r===0?te("\u2713",`An editor read ${t} famil${t===1?"y":"ies"} and ${n} value${n===1?"":"s"}. None of it has to stay identical everywhere.`):te("\u2713",`An editor read ${t} famil${t===1?"y":"ies"} and ${n} value${n===1?"":"s"}. ${r} ${r===1?"is":"are"} worth keeping in one place.`),""),e.proposals.forEach((s,i)=>{o.push(...aL(s,i+1),"")}),e.rejected.length>0){o.push(" Not proposed, and why:");for(let s of e.rejected.slice(0,Nc))o.push(u(` \xB7 ${s.what} \u2014 ${s.why}`));e.rejected.length>Nc&&o.push(u(` \xB7 \u2026and ${e.rejected.length-Nc} more.`)),o.push("")}if(e.dropped.length>0){o.push(te("\u26A0",`${e.dropped.length} proposal${e.dropped.length===1?"":"s"} could not be used:`));for(let s of e.dropped.slice(0,Nc))o.push(u(` \xB7 ${s}`));o.push("")}return o}function cL(){return[u(" Nothing to create. The knowledge base repeats itself, but not in ways that have to stay"),u(" identical everywhere \u2014 which is the answer an editor is for."),""]}function Ic(e,t){let n=[],o=t.created.map(a=>a.name);o.length>0&&(n.push(te("\u2713",`Created ${o.length} on Document360: ${o.join(", ")}.`)),n.push(u(" Your local copy is in step and the agent has been restarted, so it writes with them from now on.")));for(let a of t.failed)n.push(te("\u2717",`Document360 refused "${a.name}" \u2014 ${a.why}`));t.failed.length>0&&n.push(u(" Nothing else was changed. A name already in use is the usual cause; /reuse lists what exists."));let r=t.created.some(a=>a.kind==="variable"),s=t.created.filter(a=>a.kind==="snippet"),i=null;if(r){let a=tL(e).rule!==null;n.push(""),n.push(a?te("\u2139","Those values are still typed out by hand across your articles."):te("\u2139","Those values are created, but nothing checks them yet.")),a&&(n.push(u(" /lint --all --fix swaps every one of them \u2014 it costs no agent time, and nothing else in")),n.push(u(" your articles changes.")),i="/lint --all --fix")}return s.length>0&&(n.push(""),n.push(te("\u2139",`${s.length===1?"The snippet exists":`The ${s.length} snippets exist`} on Document360, but no article references ${s.length===1?"it":"them"} yet.`)),n.push(u(` Ask me to use ${s.length===1?"it":"them"} in an article, or run /review --all --fix and the editor will replace the`)),n.push(u(" passages it finds. Replacing a passage changes the words a reader sees, so it goes through")),n.push(u(" an editorial read rather than a mechanical swap.")),i||(i="/review --all --fix")),i&&n.push("",i,""),{lines:n,cta:i}}function Lc(e,t){let n=e.indexOf("--create");if(n===-1)return{picks:[],bad:[]};let o=e.slice(n+1).filter(i=>!i.startsWith("--"));if(o.length===1&&(o[0]==="a"||o[0]==="all"))return{picks:Array.from({length:t},(i,a)=>a),bad:[]};let r=[],s=[];for(let i of o){let a=Number(i);if(!Number.isInteger(a)||a<1||a>t){s.push(i);continue}r.includes(a-1)||r.push(a-1)}return{picks:r,bad:s}}function uL(e){if(e===0)return[];let t=Array.from({length:e},(n,o)=>o+1).join(" ");return[u(` Pick what to create. Run the line below for all ${e}, or edit the numbers to take some.`),"",`/reuse audit --create ${t}`,""]}function Oc(){return[te("\u2717","There is no reuse proposal to create from."),u(" Run /reuse audit first \u2014 it reads your articles and works out what belongs in one place."),"","/reuse audit",""]}function _c(e,t){let n=XI(e);if(!n)return[te("\u26A0","The editor did not leave a proposal, so there is nothing to create."),u(" Nothing was changed. This is usually a turn that stopped early \u2014 running it again is safe,"),u(" and the scan it starts from costs nothing."),"",t?`/reuse audit ${t}`:"/reuse audit",""];let o=pv(e,{...t?{scope:t}:{},groups:!0}),r=hv(e,t?{scope:t}:void 0),s=lL(n,(o.groups??[]).length,r.candidates.length);return s.push(...n.proposals.length===0?cL():uL(n.proposals.length)),s}ae();import{readReuseProposal as gL}from"document360-engine";import bs from"picocolors";var Yf=8,Yn=6,zf=14,yL=52;function wL(e){if(!e)return"";let t=new Date(e);return Number.isNaN(t.getTime())?"":t.toLocaleDateString(void 0,{day:"numeric",month:"short"})}function mv(e,t=yL){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}\u2026`:n}function Jf(e){let t=pL(e),n=[Z("Reusable content"),""];if(!t||t.terms.length===0&&t.snippets.length===0&&t.variables.length===0)return n.push(`${V("\u25CB",u)}Nothing pulled from Document360 yet.`,"",u(" A variable holds a value like your product name in one place, so changing it changes every"),u(" article at once. A snippet does the same for a whole block, like who to contact when"),u(" something goes wrong. A term is defined once and explained everywhere it first appears."),"","/reuse pull",""),n;let o=wL(t.pulledAt);if(t.terms.length===0)n.push(`${V("\u25CB",u)}No glossary terms in this Document360 project${o?u(` (checked ${o})`):""}.`);else{n.push(`${t.terms.length} term${t.terms.length===1?"":"s"} from Document360${o?u(`, pulled ${o}`):""}.`,"");for(let r of t.terms.slice(0,Yf)){let s=" ".repeat(Math.max(1,zf-r.term.length));n.push(` ${bs.bold(r.term)}${s}${u(r.definition||"(no definition)")}`)}t.terms.length>Yf&&n.push(u(` \u2026and ${t.terms.length-Yf} more.`))}if(t.variables.length>0){n.push("",`${t.variables.length} value${t.variables.length===1?"":"s"} kept in one place.`,"");for(let s of t.variables.slice(0,Yn)){let i=" ".repeat(Math.max(1,zf-s.name.length));n.push(` ${bs.bold(s.name)}${i}${u(s.value?`"${mv(s.value)}"`:"(no value recorded)")}`)}t.variables.length>Yn&&n.push(u(` \u2026and ${t.variables.length-Yn} more.`));let{skipped:r}=mL(e);if(r.length>0){let s=t.variables.length-r.length;n.push("",u(` ${s} of ${t.variables.length} are checked in your articles. ${r.length===1?"This one is":"These are"} not:`));for(let i of r.slice(0,Yn))n.push(u(` ${i.name} \u2014 ${i.why}.`));r.length>Yn&&n.push(u(` \u2026and ${r.length-Yn} more.`))}}if(t.snippets.length>0){n.push("",`${t.snippets.length} maintained block${t.snippets.length===1?"":"s"}.`,"");for(let r of t.snippets.slice(0,Yn)){let s=" ".repeat(Math.max(1,zf-r.name.length)),i=r.usedBy>0?u(` (in ${r.usedBy} article${r.usedBy===1?"":"s"})`):"";n.push(` ${bs.bold(r.name)}${s}${u(r.description||mv(r.value??"")||"(no content recorded)")}${i}`)}t.snippets.length>Yn&&n.push(u(` \u2026and ${t.snippets.length-Yn} more.`))}return n.push("",u(" Terms are checked at first use in every article, a value you typed out by hand is flagged,"),u(" and the writer reuses your blocks by name instead of writing its own version of them."),"","/reuse pull","/lint --all",""),n}async function Xi(e,t){let n,o;try{let c=Xf(e,t);n={profile:c.name,connection:c.connection,projectId:c.project.projectId,projectName:c.project.projectName},o=await Qf(n,c.project?.projectId)}catch(c){return{lines:[te("\u2717",`Not signed in to Document360: ${c instanceof Error?c.message:String(c)}`),u(" Run /login first.")],restart:!1}}let r;try{r=await dL(n,o)}catch(c){return{lines:[te("\u26A0",`Document360 didn't return your reusable content \u2014 ${c instanceof Error?c.message:String(c)}.`),u(" Nothing is blocked. Everything else works exactly as it did; you just do not get the"),u(" first-use check on your terms, or the reuse checks, until this succeeds.")],restart:!1}}let s={pulledAt:new Date().toISOString(),profile:n.profile,projectId:o,terms:r.terms,snippets:r.snippets,variables:r.variables};if(hL(e,s),s.terms.length+s.snippets.length+s.variables.length===0)return{lines:[te("\u2139","This Document360 project has no terms, snippets or variables yet."),u(" Someone with portal access adds them under Content tools. A good first one is your product"),u(" name as a variable: it is the string most likely to change, and the hardest to change late.")],restart:!1};let a=[`${s.terms.length} term${s.terms.length===1?"":"s"}`,`${s.snippets.length} snippet${s.snippets.length===1?"":"s"}`,`${s.variables.length} variable${s.variables.length===1?"":"s"}`],l=[te("\u2713",`Pulled ${a.join(" \xB7 ")} from Document360.`)];return r.droppedTerms.length>0&&l.push(u(` ${r.droppedTerms.length} term${r.droppedTerms.length===1?" has":"s have"} no wording recorded in Document360, so ${r.droppedTerms.length===1?"it is":"they are"} not checked:`),u(` ${r.droppedTerms.slice(0,6).join(", ")}${r.droppedTerms.length>6?`, and ${r.droppedTerms.length-6} more`:""}.`)),r.contentlessBlocks.length>0&&l.push(u(` ${r.contentlessBlocks.length} block${r.contentlessBlocks.length===1?"":"s"} came back without content, so ${r.contentlessBlocks.length===1?"it is":"they are"} not matched against your articles:`),u(` ${r.contentlessBlocks.slice(0,6).join(", ")}${r.contentlessBlocks.length>6?`, and ${r.contentlessBlocks.length-6} more`:""}.`)),l.push("",u(" Your terms are now checked at first use in every article, a value you typed out by hand is"),u(" flagged, and the writer reuses your blocks by name instead of writing its own version."),"","/lint --all",""),{lines:l,restart:!0}}async function Zf(e,t,n,o,r){let s=fL(n);if(s)return{lines:[te("\u2717",`That name will not work: ${s}.`),u(' Try something like "product-name".')],restart:!1};if(o.trim()==="")return{lines:[te("\u2717","A value is required \u2014 that is the text this will stand for in your articles.")],restart:!1};if(t==="variable"&&o.length>fv)return{lines:[te("\u2717",`A variable holds at most ${fv} characters and this is ${o.length}.`),u(' Longer text belongs in a snippet: /reuse add snippet <name> "<text>"')],restart:!1};let i,a;try{let l=Xf(e);i={profile:l.name,connection:l.connection,projectId:l.project.projectId,projectName:l.project.projectName},a=await Qf(i,l.project?.projectId)}catch(l){return{lines:[te("\u2717",`Not signed in to Document360: ${l instanceof Error?l.message:String(l)}`),u(" Run /login first.")],restart:!1}}try{let l=t==="variable"?await gv(i,a,{name:n,value:o}):await yv(i,a,{name:n,value:o,...r?{description:r}:{}}),c=await Xi(e);return{lines:[te("\u2713",`Created the ${t} "${l.name}" on Document360.`),u(` Write ${t==="variable"?`:variable[]{name="${l.name}"}`:`::snippet{name="${l.name}"}`} and Document360 puts your text there.`),"",...c.lines],restart:!0}}catch(l){let c=l instanceof Error?l.message:String(l);return{lines:[te("\u2717",`Document360 refused to create that ${t} \u2014 ${c}`),u(" Nothing was changed. A name already in use is the usual cause; /reuse lists what exists.")],restart:!1}}}function wv(e){let t=e.trim();return t.length>=2&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))?t.slice(1,-1):t}function kL(e){let t=e.indexOf("--desc");if(t===-1)return{rest:e};let n=wv(e.slice(t+1).join(" "));return{rest:e.slice(0,t),...n?{description:n}:{}}}function em(e){let{rest:t,description:n}=kL(e),o=t.filter(l=>!l.startsWith("--")),[,r,s,...i]=o;if(r!=="variable"&&r!=="snippet")return{error:'Say which one: /reuse add variable <name> "<value>", or /reuse add snippet <name> "<text>".'};if(!s)return{error:`Give it a name: /reuse add ${r} <name> "<value>".`};if(r==="variable"&&n)return{error:"Only a snippet takes --desc; a variable is just its value. Drop the flag, or add it as a snippet."};let a=wv(i.join(" "));return a===""?{error:`Give it a value: /reuse add ${r} ${s} "<the text it stands for>".`}:{kind:r,name:s,value:a,...n?{description:n}:{}}}async function kv(e,t){let n=e.find(o=>!o.startsWith("--"));if(n==="add"){let o=em(e);if("error"in o)return console.log(`${V("\u2717",bs.red)}${o.error}`),{kind:"continue",ownNext:!0};let r=await Zf(t.cwd,o.kind,o.name,o.value,o.description);for(let s of r.lines)console.log(s);return r.restart?{kind:"clear"}:{kind:"continue",ownNext:!0}}if(n==="pull"){let o=await Xi(t.cwd);for(let r of o.lines)console.log(r);for(let r of Ze(t.cwd,"/reuse pull"))console.log(r);return o.restart?{kind:"clear"}:{kind:"continue",ownNext:!0}}if(n==="audit"){if(e.includes("--create")){let r=gL(t.cwd);if(!r||r.proposals.length===0){for(let p of Oc())console.log(p);return{kind:"continue",ownNext:!0}}let{picks:s,bad:i}=Lc(e,r.proposals.length);for(let p of i)console.log(`${V("\u26A0",bs.yellow)}There is no proposal ${p} \u2014 the list has ${r.proposals.length}.`);if(s.length===0)return console.log(`${V("\u25CB",u)}Nothing picked, so nothing was created.`),{kind:"continue",ownNext:!0};let{outcome:a,pullLines:l}=await tm(t.cwd,s.map(p=>r.proposals[p]));for(let p of l)console.log(p);let{lines:c}=Ic(t.cwd,a);for(let p of c)console.log(p);for(let p of Ze(t.cwd,"/reuse audit"))console.log(p);return a.created.length>0?{kind:"clear"}:{kind:"continue",ownNext:!0}}let o=jc(t.cwd,e);if("lines"in o){for(let r of o.lines)console.log(r);for(let r of Ze(t.cwd,"/reuse audit"))console.log(r);return{kind:"continue",ownNext:!0}}for(let r of Dc(o.articles,o.families,o.values,0))console.log(r);return{kind:"forward-to-agent",prompt:o.prompt,display:o.display}}if(n&&n!=="show")return console.log(`${V("\u2717",bs.red)}I don't know "/reuse ${n}". Use /reuse to see what this project maintains, /reuse pull to refresh it, /reuse audit to find what belongs in one place, or /reuse add variable <name> "<value>".`),{kind:"continue",ownNext:!0};for(let o of Jf(t.cwd))console.log(o);return{kind:"continue",ownNext:!0}}async function tm(e,t){let n=[],o=[],r,s;try{let a=Xf(e);r={profile:a.name,connection:a.connection,projectId:a.project.projectId,projectName:a.project.projectName},s=await Qf(r,a.project?.projectId)}catch(a){return{outcome:{created:[],failed:t.map(l=>({name:l.name,why:`not signed in to Document360: ${a instanceof Error?a.message:String(a)}`}))},pullLines:[u(" Run /login first.")]}}for(let a of t)try{a.kind==="variable"?await gv(r,s,{name:a.name,value:a.value}):await yv(r,s,{name:a.name,value:a.value,...a.description?{description:a.description}:{}}),n.push(a)}catch(l){o.push({name:a.name,why:l instanceof Error?l.message:String(l)})}if(n.length===0)return{outcome:{created:n,failed:o},pullLines:[]};let i=await Xi(e);return{outcome:{created:n,failed:o},pullLines:i.restart?[]:i.lines}}ae();import{readProjectConfig as bL,writeProjectConfig as bv,isAppType as $L,playbookSkillName as vL,detectAppType as $v}from"document360-engine";var vv=["web","cli","service","library"],xL=new Set(["web","cli"]);function nm(e){return xL.has(e)?`${vL(e)} will load`:`no ${e}-doc-playbook exists yet \u2014 generic skills apply`}async function Mc(e,t){let n=t.cwd,o=bL(n);if(!o)return console.log(L(be)),{kind:"continue"};let r=e[0]?.trim().toLowerCase();if(!r){let s=o.appType??$v(n);if(s){let i=o.appType?"set in config":"auto-detected";console.log(`${Z("Genre:")} ${s} (${i}) \u2014 ${nm(s)}`)}else console.log(F("Genre: unclassified \u2014 no doc-type playbook is loading."));return console.log(u(`Set it: /genre <${vv.join("|")}> \xB7 revert to auto-detect: /genre auto`)),{kind:"continue"}}if(r==="auto"||r==="clear"){if(!o.appType)return console.log(u("Already on auto-detect (no genre set in config).")),{kind:"continue"};let{appType:s,...i}=o;bv(i,n);let a=$v(n);return console.log(Q(`\u2713 Genre reset to auto-detect \u2014 now: ${a?`${a} (${nm(a)})`:"unclassified (no playbook)"}.`)),console.log(u(" Restarting the agent so the loaded playbook matches\u2026")),{kind:"clear"}}return $L(r)?(bv({...o,appType:r},n),console.log(Q(`\u2713 Genre set to ${r} \u2014 ${nm(r)}.`)),console.log(u(" Restarting the agent so the playbook loads\u2026")),{kind:"clear"}):(console.log(L(`Unknown genre "${r}". Choose one of: ${vv.join(", ")} (or "auto" to revert to detection).`)),{kind:"continue"})}var xv={help:pd,"?":pd,clear:fy,exit:hd,quit:hd,init:bd,mcp:il,push:Il,publish:nk,audit:(e,t)=>{let n=Ul(t.cwd,e);if(n){for(let o of n)console.log(o);return Promise.resolve({kind:"continue",ownNext:!0})}return gi({cwd:t.cwd,profileName:t.profileName})},discover:lk,scope:uk,pull:Rk,resolve:$k,convert:Wk,write:nb,draft:ab,document:lb,resume:db,rename:pb,profile:qg,model:gb,doctor:Ti,env:iy,logs:Xg,workspace:vb,project:xb,"allow-prod":Rb,login:Sb,logout:Cb,screenshot:async(e,t)=>{let n=ii(e);return n.mode==="capture"?Nh(n.rest,t):n.mode==="annotate"?Oh(n.rest,t):n.mode==="verify"?Pb(n.rest,t):n.mode==="checklist"?ps(e,t):Rl(e,t)},capture:Nh,annotate:Oh,"capture-setup":ps,devhints:Sy,inbox:Kb,ask:zb,"catch-up":n$,comments:l$,update:d$,reset:g$,lint:Yp,check:Kk,"style-guide":Ac,review:z$,reorder:Q$,restructure:J$,structure:L$,status:rv,retire:sv,untrack:iv,terms:cv,eval:dv,reuse:kv,genre:Mc,roadmap:Bw,share:Jb,auto:ak};function Rv(e){let t=e.trim();if(!t.startsWith("/"))return null;let n=t.slice(1).split(/\s+/),o=(n[0]??"").toLowerCase();return o?{name:o,args:n.slice(1)}:null}import{spawnSync as RL}from"node:child_process";import{readProjectConfig as SL,recordAnalyzedCommit as CL,recordReportedAreas as PL,resolveActiveProfile as AL,surfaceCoverageSafe as TL}from"document360-engine";function EL(e){try{let t=RL("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8",timeout:1200}),n=(t.stdout||"").trim();return t.status===0&&n?n:null}catch{return null}}function Qi(e,t){try{let n=AL(e,t),o=TL(e,SL(e));o.recognised&&PL(e,n.name,o.areas.map(s=>s.folder));let r=EL(e);return r&&CL(e,n.name,r)?r:null}catch{return null}}mn();io();import{PRODUCT_NAME as Sv,WRITER_COMMAND as NL,WRITER_DIRNAME as Cv}from"document360-engine";var Pv="Or just tell me what to write or update.";function Tv(e,t=0){if(!(e>0))return null;let n=e===1?"the page":"those pages",o=`${e} note${ie(e)} from your builder ${e===1?"is":"are"} waiting on code they haven't finished.`,r=t>=e?`I've asked whether ${e===1?"it's":"they're"} done, and I'll write ${n} once the code lands.`:`I'll write ${n} once the code lands, and /catch-up asks your builder whether ${e===1?"it's":"they're"} done.`;return`${o} ${r} Nothing else is blocked.`}function DL(e,t,n={}){let o=n.onlyScreenshots?"\u2713 Your writing is done \u2014 nothing is waiting to be written, reviewed, saved or taken live. Readers are seeing every article you have.":"\u2713 That\u2019s the full round trip \u2014 nothing is waiting to be written, reviewed, saved or taken live. Readers are seeing every article you have.";return n.listed?o:`${o}
|
|
447
|
+
|
|
448
|
+
Optional from here: ${e} of your ${t} docs campaign step${ie(t)} ${e===1?"is":"are"} still open (/roadmap shows them).`}function jL(e){let{heldDrafts:t,behind:n}=e,o=t>0?"every draft that was ready is live, and readers have it":"everything you have written is live, and readers are seeing it",r=[];return t>0&&r.push(`${t} article${ie(t)} ${t===1?"is":"are"} still saved as a draft, waiting on a picture.`),n>0&&r.push(`${n} code change${ie(n)} ${n===1?"has":"have"} landed since your last docs check.`),[`\u2713 That\u2019s this round done \u2014 ${o}.`,...r].join(" ")}var IL="Still open, whenever you want it:";function LL(e,t){let n=t?`Press 1\u2013${e} when you want one \u2014 nothing runs on its own.`:"Run one of the commands above when you want to.";return`Nothing is armed. ${e>0?`${n} `:""}Whatever you leave, I\u2019ll raise again next time you\u2019re in.`}var OL="Screenshots are the only thing still open \u2014 a separate job, and none of it changes your text:",_L="Optional depth, when you want it:",ML="Writing",UL="Screenshots \u2014 a separate job from the writing";function FL(e,t){let n=t?`Press 1\u2013${e} to fill one in \u2014 nothing runs on its own.`:"Run one of the commands above when you want to.";return`Nothing is waiting${e>0?", and none of the above is owed":""}. ${e>0?`${n} `:""}I\u2019ll pick up new hints from your builder, or code that moved, next time you\u2019re in.`}var WL='\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 ie(e){return e===1?"":"s"}function BL(e,t){let n=`${t} missing picture${ie(t)}`;switch(e){case"spec":return`it writes the capture instructions for the ${n} \u2014 reading your code for the exact screens and buttons`;case"capture":return`it takes the ${n} in a browser and draws the callouts on straight after \u2014 your app needs to be running`;default:return`it draws the callouts on the ${n} already taken \u2014 no browser, about a second each`}}function HL(e,t){if(!e||!t)return!1;let n=o=>o.trim().replace(/\s+/g," ").toLowerCase();return n(e)===n(t)}function $s(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 Ev(e,t){return e.length===t.length&&e.every((n,o)=>n===t[o])}function Av(e,t=150,n=1){let o=(e??"").replace(/\s+/g," ").trim();if(!o)return null;let r=/[.!?]\s+(?=["“'(A-Z])/g,s=o;for(let l=0;l<n;l++){let c=r.exec(o);if(!c)break;s=o.slice(0,c.index+1)}if(s.length<=t)return s;let i=s.slice(0,t),a=i.lastIndexOf(" ");return`${(a>t*.6?i.slice(0,a):i).replace(/[,;:]$/,"")}\u2026`}function vs(e){if(e.kind==="answer")return e.options>=2?`Answer above (1\u2013${e.options}), or say what you want instead.`:"Answer above, or say what you want instead.";let t=e.detail?` ${e.detail.replace(/\s*$/,"").replace(/([^.!?…])$/,"$1.")}`:"";return e.kind==="cmd"?`I\u2019d start with ${e.cmd} \u2014 ${e.reason}.${t}`:`Just tell me: \u201C${e.text}\u201D \u2014 ${e.reason}.${t}`}var mr="write the docs for this repo",Uc={title:"What kind of product is this repo? (sets the doc-craft playbook \u2014 otherwise the docs stay generic)",lead:"Pick the genre below \u2014 one keypress, and it shapes everything I write.",exclusive:!0,options:[{cmd:"/genre web",desc:"web app / SaaS UI"},{cmd:"/genre cli",desc:"command-line tool"},{cmd:"/genre service",desc:"API / backend service"},{cmd:"/genre library",desc:"SDK / library"}]};function GL(e,t){let n=[];if(e.brokenEnv){let w=e.brokenEnv;n.push({key:"environment",bullet:w.kind==="retired"?`this repo publishes to the ${w.name} environment, which is being retired`:`this repo publishes to ${w.name}, which it cannot reach \u2014 ${w.why}`,lead:{kind:"cmd",cmd:w.cmd,reason:w.kind==="unshipped"?`it picks where these docs publish. To keep using ${w.name}, add it with: ${NL} env add <file.json>`:"it picks where these docs publish (then /login signs in and picks the project)"},picker:null,follow:null,tone:"warn"})}if(e.devhints!=="current"&&e.builderStarted){let w=e.devhintsToVersion?`v${e.devhintsToVersion}`:"a newer version",C=e.devhints==="stale"&&e.devhintsCompletedVersion?` (your builder is on v${e.devhintsCompletedVersion})`:"";n.push({key:"devhints",bullet:`dev\u2194docs protocol moved to ${w}${C} \u2014 your docs aren\u2019t blocked`,lead:{kind:"cmd",cmd:"/devhints",reason:`one paste updates your builder to ${w}`},picker:null,follow:"Also run /devhints when you get a second \u2014 your builder\u2019s protocol is behind.",tone:"warn"})}if(e.genreUnknown&&n.push({key:"genre",bullet:"the doc genre isn\u2019t set \u2014 I can\u2019t load the right doc-craft playbook yet",lead:null,picker:Uc,follow:"Then pick the doc genre below (it sets the playbook I write with)."}),e.styleRules){let w=e.styleRules.articles;n.push({key:"styleRules",bullet:w>0?`the writing rules for these docs were never settled \u2014 and ${w} article${ie(w)} ${w===1?"is":"are"} already written to them`:"the writing rules for these docs aren\u2019t settled yet \u2014 worth answering before I write anything",lead:null,picker:{title:w>0?`Which writing rules should these docs follow? (${w} article${ie(w)} already written \u2014 changing this later means rewriting them)`:"Which writing rules should these docs follow? (this shapes every article I write)",lead:w>0?"Settle the writing rules below \u2014 one keypress. Keeping what you have is the usual answer once articles exist.":"Settle the writing rules below \u2014 one keypress, before I write anything to them.",exclusive:!0,options:e.styleRules.presets},follow:"Then settle the writing rules below \u2014 it shapes every article, and it gets dearer to change the longer it waits."})}if(e.styleUpgrade){let w=e.styleUpgrade,C=w.articles,S=w.from.length>0?w.from.join(", "):"the built-in checks only";n.push({key:"styleUpgrade",bullet:`you\u2019re on ${S} \u2014 several of its rules are wrong for software documentation, and the guide measured on real knowledge bases is ready`,lead:null,picker:{title:`Move these docs to the Document360 style guide? (you\u2019re on ${S})`,lead:C>0?`Pick below \u2014 one keypress. Switching is instant; I then run the free text swaps over your ${C} article${ie(C)} and stop before the editorial pass.`:"Pick below \u2014 one keypress, before I write anything to it.",exclusive:!0,options:[{cmd:`/style-guide use ${w.to}`,desc:C>0?`switch, then bring your ${C} article${ie(C)} up to it \u2014 ${w.rules} rules, none of which can block a publish`:`Microsoft style corrected for software docs \u2014 ${w.rules} rules, none of which can block a publish`},{cmd:"/style-guide keep",desc:`stay on ${S} \u2014 I won\u2019t ask again`}]},follow:"Then decide whether these docs move to the Document360 style guide \u2014 it gets dearer to change the longer it waits."})}if(e.autoChoice){let w=e.autoChoice.articles;n.push({key:"autoMode",bullet:w>0?`you haven\u2019t said whether I should run each step myself or wait for you \u2014 with ${w} article${ie(w)} here, that is the difference between a night\u2019s work and an afternoon of key presses`:"you haven\u2019t said whether I should run each step myself or wait for you to press the key each time",lead:null,picker:{title:"Should I run each step myself, or wait for you?",lead:"Pick how I should work below \u2014 one keypress, and shift+tab changes it again whenever you like.",exclusive:!0,options:e.autoChoice.presets},follow:"Then say whether I should run each step myself or wait for you \u2014 shift+tab changes it later."})}if(e.discovery&&e.discovery.status!=="confident"){let w=e.discovery.openQuestions;e.discovery.status==="pending"?n.push({key:"discovery",bullet:"your existing docs aren\u2019t grounded in a product brief yet",lead:{kind:"cmd",cmd:"/discover",reason:"it interviews your builder and grounds the docs before you rewrite or publish them"},picker:null,follow:"Then /discover grounds your docs in a product brief (do this before the rewrite/push steps)."}):w>0?n.push({key:"discovery",bullet:`product discovery is waiting on ${w} answer${ie(w)} from your builder \u2014 nudge them`,lead:null,picker:null,follow:"Discovery is waiting on your builder\u2019s answers \u2014 nudge them, then /catch-up folds the answers in once they reply."}):e.discovery.answersPending===0&&n.push({key:"discovery",bullet:"product discovery is ready to continue",lead:{kind:"cmd",cmd:"/discover",reason:"it continues interviewing your builder to ground the docs"},picker:null,follow:"Then /discover continues building the product brief."})}if(e.directives>0||e.pendingText){let w=e.directives>0&&e.pendingText?"it actions your directives and clears the builder\u2019s queue":e.directives>0?"it actions the directives you left":"it clears everything your builder queued",C=[];e.directives>0&&C.push(`${e.directives} owner directive${ie(e.directives)} waiting`);let S=e.discovery&&e.discovery.status!=="confident"?e.discovery.answersPending:0,A=S>0?` (${S} settle${S===1?"s":""} the product brief)`:"";e.pendingText&&C.push(`your builder left ${e.pendingText}${A}`),n.push({key:"catchup",bullet:C.join(`
|
|
449
|
+
\u2022 `),lead:{kind:"cmd",cmd:"/catch-up",reason:w},picker:null,follow:"Then /catch-up clears what\u2019s queued for the docs.",dependsOn:["discovery"]})}if(e.openComments>0){let w=e.openComments;n.push({key:"comments",bullet:`${w} reviewer comment${ie(w)} waiting on your articles`,lead:{kind:"cmd",cmd:"/comments",reason:"it shows what reviewers marked up in the portal, then lets you take it an article at a time"},picker:null,follow:`Then /comments shows the ${w} reviewer comment${ie(w)} waiting on your articles.`})}if(e.conflicts>0){let w=e.conflicts,C=w===1?"it":"these",S=e.unreadable===w,A=S?`${w} article${ie(w)} ${w===1?"is":"are"} held on Document360 in a form I can't read back`:e.unreadable>0?`${w} article${ie(w)} ${w===1?"is":"are"} waiting on your decision \u2014 changed both here and on Document360, or held there in a form I can't read back`:`${w} article${ie(w)} changed both here and on Document360`;n.push({key:"resolve",bullet:`${A} \u2014 /push skips ${C}, and an audit can't trust your local copy until ${w===1?"it is":"they are"} settled`,lead:{kind:"cmd",cmd:"/resolve",reason:S?"it walks each one with you \u2014 publish your copy over the portal, or skip":"it walks each one with you \u2014 keep yours, take the portal's, or skip"},picker:null,follow:S?`Then /resolve settles the ${w} article${ie(w)} Document360 won't hand back (publish yours over the portal / skip).`:`Then /resolve settles the ${w} article${ie(w)} waiting on your decision (keep yours / take the portal's / skip).`})}let o=e.firstPublish,r=(()=>{if(!o||o.unpushed===0)return null;let w=o.unpushed,C=e.profileName?` on ${e.profileName}`:"";if(o.portalArticles===null)return{key:"firstPublish",bullet:`${w} article${ie(w)} ${w===1?"is":"are"} written here, and this connection has never been compared with Document360`,lead:{kind:"cmd",cmd:"/pull --status",reason:"it asks Document360 what is already there. No tokens, and it changes nothing"},picker:null,follow:"Then /pull --status shows what this portal already holds."};if(o.twins===0){let S="/push --all",A=t?.scaleFor?.(S)??null;return{key:"firstPublish",bullet:w===o.total?`${w} article${ie(w)} ${w===1?"is":"are"} written here and none of them are${C} yet \u2014 your readers see nothing`:`${w} of your ${o.total} article${ie(o.total)} ${w===1?"has":"have"} not reached ${e.profileName} yet \u2014 the rest are saved as drafts`,lead:{kind:"cmd",cmd:S,reason:w===o.total?`it saves all ${w} to Document360 as draft${ie(w)}`:`it retries the ${w} that did not land`,...A&&w===o.total?{detail:A}:{}},picker:null,follow:w===o.total?`Then ${S} saves all ${w} to Document360, and /publish takes them live.`:`Then ${S} retries the ${w} that did not land, and /publish takes them live.`,...A&&w===o.total?{detail:A}:{},dependsOn:["catchup","comments"],blockedBy:["review","styleguide"]}}return{key:"firstPublish",bullet:`${w} article${ie(w)} ${w===1?"is":"are"} written here, and this portal holds ${o.twins} page${o.twins===1?"":"s"} nothing here tracks`,lead:null,picker:null,follow:"/pull --status compares them article by article, so nothing is pushed until you decide."}})(),s=r!==null&&e.unreviewed===0&&e.styleErrors===0,i=e.draftAhead,a=i>0?{key:"golive",bullet:`${i} article${ie(i)} ${i===1?"is":"are"} saved on Document360 but not live \u2014 your readers still see the previous version`,lead:{kind:"cmd",cmd:"/publish",reason:`it takes the ${i} draft${ie(i)} live to your readers \u2014 it lists them and asks first`},picker:null,follow:`Then /publish takes the ${i} draft${ie(i)} live \u2014 until it does, readers see the previous version.`,dependsOn:["comments"],blockedBy:["review","styleguide"]}:null,l=e.localAhead===0&&(e.firstPublish?.unpushed??0)===0,c=a!==null&&l&&e.unreviewed===0&&e.styleErrors===0;if(a&&c&&n.push(a),r&&s&&n.push(r),e.portalUntracked>0){let w=e.portalUntracked,C=e.portalOnlyCategories;n.push({key:"coverage",bullet:`${w} article${ie(w)} on Document360 ${w===1?"is":"are"} not in your docs folder \u2014 a plan or an audit built now would miss ${w===1?"it":"them"}`,lead:{kind:"cmd",cmd:"/pull",reason:C>0?`it imports ${w===1?"it":"them"} and creates the ${C} ${C===1?"folder":"folders"} they need`:`it imports ${w===1?"it":"them"} into your docs folder`},picker:null,follow:`Then /pull brings the ${w} Document360 article${ie(w)} this repo is not tracking.`})}if(e.behind>0||e.undocumentedAreas>0){let w=e.behind,C=e.undocumentedAreas,S=w>0||e.unreportedAreas>0,A=e.declineTarget?`/audit --decline ${e.declineTarget}`:"/audit --decline",R=w>0&&C>0?`${w} code change${ie(w)} since your last docs check, and ${C} part${ie(C)} of the product no article covers`:w>0?`${w} code change${ie(w)} since your last docs check`:S?`${C} part${ie(C)} of the product no article covers`:`${C} part${ie(C)} of the product no article covers \u2014 proposed already, still open. Settle one for good: ${A}`;n.push({key:"audit",bullet:R,lead:S?{kind:"cmd",cmd:"/audit",reason:w>0?"it shows what the latest code changes touch (or /audit --auto on to run it for you)":`it proposes the articles those parts need \u2014 or settle one with ${A}`}:null,picker:null,follow:S?w>0?`After that, /audit covers the ${w} newer commit${ie(w)}.`:`After that, /audit proposes what the ${C} uncovered part${ie(C)} need.`:null,blockedBy:["resolve"],dependsOn:["coverage"],opensRound:!0})}if(e.hasDocs&&e.pendingWrites>0){let w=e.pendingWrites;n.push({key:"write",bullet:`${w} planned article${ie(w)} still unwritten`,lead:{kind:"cmd",cmd:"/write",reason:"it finishes the articles already planned"},picker:null,follow:`Then /write finishes the ${w} planned article${ie(w)}.`,dependsOn:["genre","discovery","catchup","audit","coverage"]})}if(e.styleSweep){let w=e.styleSweep.pending,C=e.styleSweep.packs.length>0?e.styleSweep.packs.join(", "):"the built-in checks",S=e.styleSweep.scope?Ee("/review","--fix",e.styleSweep.scope):"/review --all --fix";n.push({key:"styleSweep",bullet:`your writing rules changed to ${C} \u2014 ${w<e.styleSweep.total?`${w} of ${e.styleSweep.total}`:`${w}`} article${ie(w)} ${w===1?"has":"have"} not been read against them yet`,lead:{kind:"cmd",cmd:S,reason:"it reads each one against the new rules and rewrites it",detail:[t?.scaleFor?.(S),"/style-guide sweep skip stops me raising it."].filter(Boolean).map(A=>A.replace(/([^.!?…])$/,"$1.")).join(" ")},picker:null,follow:`Then ${S} reads the ${w} article${ie(w)} the new rules have never been applied to.`,dependsOn:["catchup","comments","audit"]})}if(e.unreviewed>0){let w=e.unreviewed,C=Ee("/review","--blocked --fix",e.unreviewedScope);n.push({key:"review",bullet:`${w} article${ie(w)} not yet live ${w===1?"carries":"carry"} text no editor has read`,lead:{kind:"cmd",cmd:C,reason:"these were written by an AI \u2014 it reads each one and applies its fixes, and nothing can be sent up or taken live until it has"},picker:null,follow:`Then ${C} reviews the ${w} unreviewed article${ie(w)} \u2014 nothing reaches your readers until it has.`,dependsOn:["catchup","comments"]})}if(e.styleErrors>0){let w=e.styleErrors,C=Ee("/lint","--blocked --fix",e.styleErrorScope);n.push({key:"styleguide",bullet:`${w} article${ie(w)} not yet live break${w===1?"s":""} house style rules that block publishing`,lead:{kind:"cmd",cmd:C,reason:"finding them costs nothing and one pass corrects them in place \u2014 nothing can be sent up or taken live until it has"},picker:null,follow:`Then ${C} clears the style errors on ${w} article${ie(w)} \u2014 nothing reaches your readers until it has.`,dependsOn:["catchup","comments","review"]})}let p=e.draftBlockedShots??null,m=p&&p.articles>0?{key:"annotate",bullet:`${p.articles} article${ie(p.articles)} ${p.articles===1?"is":"are"} saved on Document360 and cannot go live \u2014 ${p.places} picture${ie(p.places)} ${p.places===1?"is":"are"} missing, so your readers would see "[Screenshot: \u2026]" on the page`,lead:p.cmd?{kind:"cmd",cmd:p.cmd,reason:BL(p.stage,p.places)}:{kind:"prompt",text:`fix the ${p.places} bare "[Screenshot: \u2026]" line${ie(p.places)} \u2014 either give each one a proper screenshot block or take the line out`,reason:"these lines belong to no screenshot, so no command can finish them"},picker:null,follow:p.cmd?`Then ${p.cmd} deals with the ${p.places} missing picture${ie(p.places)}, and /push and /publish take the ${p.articles} article${ie(p.articles)} live.`:`Then the ${p.places} bare "[Screenshot: \u2026]" line${ie(p.places)} can be sorted out, and /push and /publish take the ${p.articles} article${ie(p.articles)} live.`,...p.stage==="spec"||p.stage==="capture"?{opensRound:!0}:{}}:e.shotsToAnnotate>0?{key:"annotate",bullet:`${e.shotsToAnnotate} screenshot${ie(e.shotsToAnnotate)} ${e.shotsToAnnotate===1?"has":"have"} been taken but ${e.shotsToAnnotate===1?"is":"are"} not finished \u2014 the callouts aren't drawn on, so ${e.shotsToAnnotate===1?"it cannot":"they cannot"} be published`,lead:{kind:"cmd",cmd:"/screenshot annotate",reason:"it draws the callouts on \u2014 no browser, about a second per picture"},picker:null,follow:`Then /screenshot annotate finishes the ${e.shotsToAnnotate} screenshot${ie(e.shotsToAnnotate)} already taken.`}:e.shotsToRecapture>0?{key:"annotate",bullet:`${e.shotsToRecapture} screenshot${ie(e.shotsToRecapture)} ${e.shotsToRecapture===1?"has":"have"} a plan for what to point at but no picture \u2014 the picture has to be taken again before anything can be drawn on it`,lead:{kind:"cmd",cmd:"/screenshot capture",reason:"it takes the picture again in a browser, and the callouts are drawn on straight after"},picker:null,follow:`Then /screenshot capture re-takes the ${e.shotsToRecapture} missing picture${ie(e.shotsToRecapture)}.`,opensRound:!0}:null,$=m!==null&&p!==null&&p.articles>0;if(m&&!$&&e.localAhead>0&&n.push(m),r&&!s&&n.push(r),e.localAhead>0){let w=e.localAhead;n.push({key:"publish",bullet:`${w} article${ie(w)} changed locally \u2014 ready to send to Document360`,lead:{kind:"cmd",cmd:"/push",reason:`it saves your ${w} local edit${ie(w)} to Document360 as drafts`},picker:null,follow:`Then /push saves your ${w} local edit${ie(w)} to Document360.`,dependsOn:["discovery","comments","audit","annotate"],blockedBy:["review","styleguide"]})}if(a&&!c&&n.push(a),m&&($||e.localAhead===0)&&n.push(m),e.hasDocs&&e.roadmap?.next){let w=e.roadmap,C=w.next,S=C.run?t?.scaleFor?.(C.run)??null:null,A=C.run?S:Av(C.body),R=C.run?S??void 0:Av(C.body,340,2)??void 0,D=`docs campaign: ${w.done} of ${w.total} step${ie(w.total)} done`,W=!!C.run&&HL(C.run,e.lastCommand);n.push(W?{key:"roadmap",bullet:`${D} \u2014 \u201C${C.title}\u201D is waiting on you
|
|
450
|
+
\u2022 You just ran ${C.run}. It showed you where things stand; the step stays open until you act on what it showed, or close it with /roadmap done.`,lead:null,picker:null,follow:null}:{key:"roadmap",bullet:`${D} \u2014 next: ${C.title}${A?`
|
|
451
|
+
\u2022 ${A}`:""}`,lead:C.run?{kind:"cmd",cmd:C.run,reason:"it\u2019s the next step of your docs campaign",...R?{detail:R}:{}}:{kind:"prompt",text:C.title,reason:"it\u2019s the next step of your docs campaign",...R?{detail:R}:{}},picker:null,follow:`Then the campaign continues: ${C.title} (/roadmap shows all ${w.total} steps).`,dependsOn:["genre","discovery","audit"],rowBullet:`${D} \u2014 this is next${A?`
|
|
452
|
+
\u2022 ${A}`:""}`,opensRound:!0})}if(e.handoff){let w=Math.max(e.handoff.unpushed,e.handoff.uncommitted>0?1:0),C=e.handoff.unpushed;w>0&&e.handoff.pushConsent==="unconfirmed"?n.push({key:"share",bullet:e.shareExplained?"your docs work is saved on this machine only \u2014 your team can't see it yet":["your docs work is saved on this machine only \u2014 your team can't see it yet",`${Sv} keeps everything it produces in ${Cv}/ \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(`
|
|
453
|
+
`),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}):C>0&&n.push({key:"share",bullet:`\u26A0 ${C} docs change set${ie(C)} saved but not sent \u2014 someone else pushed to this branch first (your work is safe)`,lead:{kind:"cmd",cmd:"/share",reason:"it retries sending your saved work; if it keeps failing, your builder can merge the branch"},picker:null,follow:null})}else if(e.uncommittedDocs>0){let w=e.uncommittedDocs;n.push({key:"commit",bullet:`\u26A0 ${w} uncommitted change${ie(w)} under ${Cv}/ \u2014 tell your coding agent: "commit ${Sv}'s work"`,lead:null,picker:null,follow:null})}return n}function Nv(e){return e.find(t=>t.lead||t.picker)??null}function qL(e){return e.kind==="cmd"?e.cmd:e.kind==="prompt"?`\u201C${e.text}\u201D`:""}function xs(e){return e.kind==="cmd"?e.cmd:e.kind==="prompt"?e.text:null}function VL(e){return xs(e)??""}function KL(e,t,n){let o=a=>(a??[]).map(l=>t.get(l)).filter(l=>l!==void 0&&l<n),r=a=>a.length===1?`${a[0]}`:`${a.slice(0,-1).join(", ")} and ${a[a.length-1]}`,s=o(e.blockedBy);if(s.length>0)return` (needs ${r(s)} first)`;let i=o(e.dependsOn);return i.length>0?` (better after ${r(i)})`:""}function Ji(e,t,n,o=null,r,s=0,i=0,a=0,l=!1){if(r&&r.length>0){let D=r.filter(Sl),W=r.filter(ne=>!Sl(ne)),H=[...W,...D],J=(ne,oe)=>` ${oe+1}. ${ne.title}${ne.run?` \xB7 ${ne.run}`:""}`,G;return D.length===0||W.length===0?G=[e,...H.map(J)].join(`
|
|
454
|
+
`):G=[e,"",` ${ML}`,...W.map((ne,oe)=>J(ne,oe)),"",` ${UL}`,...D.map((ne,oe)=>J(ne,W.length+oe))].join(`
|
|
455
|
+
`),{note:[...o?[o]:[],G,FL(H.length,n),Pv].join(`
|
|
456
|
+
|
|
457
|
+
`),menu:H.map(ne=>ne.run??ne.title)}}let c=l?null:Nv(t),p=c?.picker?[]:t.filter(D=>D.lead),m=l||p.length>=2?p:[],$=new Map(m.map((D,W)=>[D.key,W+1])),w=[];c?.lead?w.push(vs(c.lead)):c?.picker&&w.push(c.picker.lead);for(let D of t.filter(W=>W!==c&&!W.lead).slice(0,2))D.follow&&w.push(D.follow);l?w.push(LL(m.length,n)):m.length>=2&&n&&w.push(`Press 1\u2013${m.length} to pick a different one \u2014 the number fills the box, enter runs it.`);let C=w.join(" "),S=t.filter(D=>D.bullet).map(D=>{let W=$.get(D.key),[H="",...J]=(W&&D.lead?.kind==="prompt"&&D.rowBullet?D.rowBullet:D.bullet).split(`
|
|
458
|
+
\u2022 `),G=D===c&&D.lead?.kind!=="answer"&&D.lead?.detail?[]:J;if(W&&D.lead){let oe=H.replace(/^→\s+/,"");return[` ${W}. ${qL(D.lead)} \u2014 ${oe}${KL(D,$,W)}`,...G.map(le=>` ${le}`)].join(`
|
|
459
459
|
`)}let K=D.lead?.kind==="cmd"?D.lead.cmd:null;return` \u2022 ${[H,...G].join(`
|
|
460
|
-
\u2022 `)}${K&&!C.includes(K)?` \u2014 ${K}`:""}`}),
|
|
460
|
+
\u2022 `)}${K&&!C.includes(K)?` \u2014 ${K}`:""}`}),A=o?[o,[e,...S].join(`
|
|
461
461
|
`)]:[[e,...S].join(`
|
|
462
|
-
`)];if(w.length&&
|
|
463
|
-
|
|
464
|
-
`),menu:m.map(D=>
|
|
465
|
-
|
|
466
|
-
${R}`:R;if(!e.ready)return{kind:"idle"};if(e.pendingAnswer)return{kind:"recommend",rec:{note:null,settled:null,restKind:null,tone:"info",lead:e.pendingAnswer.options>=2?{kind:"answer",options:e.pendingAnswer.options,reason:"the agent is waiting on your pick"}:null,picker:null,menu:[],heldHints:e.heldHints}};let r=
|
|
467
|
-
|
|
468
|
-
${D}`:"")),settled:null,restKind:null,tone:"info",lead:null,picker:null,menu:[],heldHints:e.heldHints}}}let w=c,C=w[0]??null;if(!C){let R=
|
|
469
|
-
`)){let o=n.trimEnd();if(/^\s*(```|~~~)/.test(o)){t=!t;continue}if(t)continue;let r=/^#\s+(\S.*)$/.exec(o);if(r)return
|
|
470
|
-
`)){if(n>t)break;let i=s.trimEnd();if(/^\s*(```|~~~)/.test(i))o=!o;else if(!o){let a=/^(#{2,6})\s+(\S.*)$/.exec(i);a&&(r=
|
|
471
|
-
`)){let n=t.replace(/^\s*(#{1,6}\s+|[-*+]\s+|>\s+|\d+[.)]\s+)/,"").replace(/^\s*\|/,"").trim();if(n)return
|
|
472
|
-
`).length;return{verb:"Draft",title:J,category:l,note:`new, ${G} lines`,articleKey:s}}return{verb:"Rewrite",title:J,category:l,note:
|
|
473
|
-
`)),category:l,note:w,articleKey:s,...
|
|
474
|
-
`);if(e==="Read"){let o=n.length,r=
|
|
475
|
-
`));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
|
|
476
|
-
`).trimEnd();if(n&&
|
|
477
|
-
`);return{lines:s.slice(0,t).map(i=>
|
|
478
|
-
|
|
479
|
-
${
|
|
480
|
-
`))console.log(i(` ${a}`));s.rec.picker&&console.log(Z(` Pick one: ${s.rec.picker.options.map(a=>a.cmd).join(" \xB7 ")}`))}}catch{}}console.log(u(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}var
|
|
481
|
-
`))console.log(Q(` ${r}`))}else o.rec.settled&&!o.rec.lead&&console.log(u(" Nothing is waiting. /roadmap lists the optional campaign steps."));o.rec.lead&&console.log(u(` Next: ${
|
|
482
|
-
|
|
483
|
-
`);let l=[i.category,i.note].filter(p=>!!p).map(p=>
|
|
484
|
-
|
|
485
|
-
`),console.log(`${
|
|
486
|
-
`);let i=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(u(` (${
|
|
487
|
-
`),n=0;for(let s=t.length-1;s>=0;s--){let i=t[s];if(/^\s{0,3}\d{1,2}[.)]\s+\S/.test(i)){n++;continue}if(!(n>0&&/^\s+\S/.test(i)))break}return n<2?0:t.filter(s=>/^\s{0,3}\d{1,2}[.)]\s+\S/.test(s)).slice(-n).every((s,i)=>Number(/^\s{0,3}(\d{1,2})/.exec(s)[1])===i+1)?n:0}var
|
|
488
|
-
`),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){
|
|
489
|
-
`)}var
|
|
490
|
-
`).filter(s=>/^\s{0,3}\d{1,2}[.)]\s+\S/.test(s)).slice(-n).map(s=>{let i=s.replace(/^\s{0,3}\d{1,2}[.)]\s+/,"").trim(),a=
|
|
491
|
-
`).map(o=>o.trim()).filter(o=>o.length>3),n=t[t.length-1];return n?n.length>160?`${n.slice(0,157)}\u2026`:n:null}function
|
|
492
|
-
`)}var
|
|
493
|
-
\u2190/\u2192 or tab switch \xB7 1-5 jump${C+S>0?" \xB7 \u2191\u2193 scroll":""} \xB7 esc close \xB7
|
|
494
|
-
`)){let i=s.trim().replace(
|
|
495
|
-
`)}function
|
|
496
|
-
`)||e.length>200}function
|
|
497
|
-
`).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function
|
|
498
|
-
`)){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
|
|
462
|
+
`)];if(w.length&&A.push(w.join(" ")),s>0){let D=s;A.push(`${D} question${ie(D)} you asked your developers ${D===1?"is":"are"} still unanswered. Their reply arrives with your docs the next time either of you shares, and /inbox folds it in. Nothing is blocked meanwhile.`)}let R=Tv(i,a);return R&&A.push(R),A.push(Pv),{note:A.join(`
|
|
463
|
+
|
|
464
|
+
`),menu:m.map(D=>VL(D.lead))}}function Zi(e,t){let n=t?.pickable===!0,o=R=>t?.header?`${t.header}
|
|
465
|
+
|
|
466
|
+
${R}`:R;if(!e.ready)return{kind:"idle"};if(e.pendingAnswer)return{kind:"recommend",rec:{note:null,settled:null,restKind:null,tone:"info",lead:e.pendingAnswer.options>=2?{kind:"answer",options:e.pendingAnswer.options,reason:"the agent is waiting on your pick"}:null,picker:null,menu:[],heldHints:e.heldHints}};let r=GL(e,t),s=r.length===1&&r[0].key==="roadmap"&&!!r[0].lead&&!!e.roadmap&&!!e.roadmap.next,i=s?e.roadmap.open?.length?e.roadmap.open:[e.roadmap.next]:[],a=i.length>0&&i.every(Sl)&&e.roadmap.total-e.roadmap.done===i.length,l=s?DL(e.roadmap.total-e.roadmap.done,e.roadmap.total,{listed:i.length>0,onlyScreenshots:a}):null,c=r.filter(R=>R.lead||R.picker),p=!s&&c.length>0&&c.every(R=>R.opensRound===!0),m=p?jL({heldDrafts:e.draftBlockedShots?.articles??0,behind:e.behind}):l,$=s?"complete":p?"delivered":null;if(!e.hasDocs){let R=Nv(r);if(R&&(R.lead?.kind==="cmd"||R.picker)){let D=Ji(t?.header??"\u{1F4ED} No docs yet for this repo \u2014 here\u2019s where things stand:",r,n,null,void 0,e.outboundQuestions,e.heldHints,e.heldHintsAsked);return{kind:"recommend",rec:{note:D.note,settled:null,restKind:null,tone:R.tone??"info",lead:R.lead,picker:R.picker,menu:D.menu,heldHints:e.heldHints}}}return{kind:"recommend",rec:{note:o(WL),settled:null,restKind:null,tone:"info",lead:{kind:"prompt",text:mr,reason:"I\u2019ll read the code and draft a structure"},picker:null,menu:[],heldHints:e.heldHints}}}if(r.length===0){let R=e.roadmap&&!e.roadmap.next?` Docs campaign complete \u2014 all ${e.roadmap.total} step${ie(e.roadmap.total)} done (/roadmap).`:"",D=Tv(e.heldHints,e.heldHintsAsked);return{kind:"recommend",rec:{note:o(`Welcome back. Your ${e.tracked} tracked article${ie(e.tracked)} for \u201C${e.profileName}\u201D are all in sync \u2014 /audit re-checks the code, /pull brings down portal edits.${R}`+(D?`
|
|
467
|
+
|
|
468
|
+
${D}`:"")),settled:null,restKind:null,tone:"info",lead:null,picker:null,menu:[],heldHints:e.heldHints}}}let w=c,C=w[0]??null;if(!C){let R=Ji(t?.header??"Welcome back \u2014 where your docs stand:",r,n,null,void 0,e.outboundQuestions,e.heldHints,e.heldHintsAsked);return{kind:"recommend",rec:{note:R.note,settled:null,restKind:null,tone:"info",lead:null,picker:null,menu:R.menu,heldHints:e.heldHints}}}if((C.key==="audit"||w[1]?.key==="audit")&&e.behind>0&&e.autoAudit&&e.allowAutoAudit)return{kind:"autoAudit",note:o(`\u{1F4CB} ${e.behind} code change${ie(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`)};if(s){let R=Ji(a?OL:_L,r,n,m,i,e.outboundQuestions,e.heldHints,e.heldHintsAsked);return{kind:"recommend",rec:{note:R.note,settled:m,restKind:$,tone:"info",lead:null,picker:null,menu:R.menu,heldHints:e.heldHints}}}if(p){let R=Ji(IL,r,n,m,void 0,e.outboundQuestions,e.heldHints,e.heldHintsAsked,!0);return{kind:"recommend",rec:{note:R.note,settled:m,restKind:$,tone:"info",lead:null,picker:null,menu:R.menu,heldHints:e.heldHints}}}let A=Ji(t?.header??"Welcome back \u2014 where your docs stand:",r,n,m,void 0,e.outboundQuestions,e.heldHints,e.heldHintsAsked);return{kind:"recommend",rec:{note:A.note,settled:m,restKind:$,tone:C.tone??"info",lead:C.lead,picker:C.picker,menu:A.menu,heldHints:e.heldHints}}}mn();import{existsSync as Fc,readdirSync as sm}from"node:fs";import{spawnSync as YL}from"node:child_process";import{join as Wc}from"node:path";import{readProjectConfig as rm,resolveActiveProfile as im,loadTokens as zL,isExpired as XL,loadProfileMap as Mv,localAheadPaths as QL,unpushedArticlePaths as Uv,loadKnownConflicts as JL,loadCoverage as ZL,surfaceCoverageSafe as eO,undocumentedAreaCount as tO,declineTargets as nO,listUnpullable as oO,draftPendingPaths as rO,loadOpenCommentCount as sO,readDocsPlan as iO,devHintsGuidePath as aO,DEFAULT_DOCS_DIR as Bc,roadmapProgress as lO,listRoadmap as Dv,readProductBriefState as cO,readDiscoveryQueue as uO,reconcileCommitRequest as dO,reconcileTestidRequest as pO,snapshotHandoff as hO,shareExplainedPath as fO,unannotatedShotIds as mO,shotsNeedingRecapture as gO,resolveOutputDir as yO,DEFAULT_OUTPUT_DIR as wO,WRITER_DIRNAME as om,styleGuideSettled as kO,styleGuideUpgradeOffered as bO,styleSweepOutstanding as $O,styleSweepSeedNeeded as vO,recordStyleSwitch as xO,styleOverlayDrift as RO,recordOverlayChange as SO,buildRegistry as CO,lintArticles as jv,DEFAULT_PACK as PO,autoModeSettled as AO,autoBudgetUsd as TO,listAvailablePacks as Iv,listArticleFiles as ea,placeholderFindings as EO,placeholderRemedy as NO}from"document360-engine";io();var Lv=new Set,Ov=new Set,DO=5;function _v(e){try{return sm(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function am(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>_v(Wc(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&_v(Wc(e,o)))}function lm(e,t){try{let n=rm(e);if(!n)return!1;let o=im(e,t),r=Mv(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=Wc(e,(n.docsDir??Bc).replace(/\/+$/,""));return!!(Fc(s)&&sm(s).length>0||Fc(aO(e)))}catch{return!1}}function Fv(e,t){try{let n=im(e,t);return Uv(e,n.name).length>0?"unpushed":ea(e).length>0?"tracked":"fresh"}catch{return"tracked"}}function jO(e){let t=[`:(exclude)${om}`],n=(e.docsDir??Bc).replace(/\\/g,"/").replace(/\/+$/,"");return n&&!n.startsWith(`${om}/`)&&n!==om&&t.push(`:(exclude)${n}`),t}function IO(e,t){if(!e.recognised)return 0;if(!t||t.length===0)return e.areas.length;let n=new Set(t);return e.areas.filter(o=>!n.has(o.folder)).length}function LO(e){return!e.recognised||e.areas.length===0?null:nO(e.areas[0])[0]??null}function OO(e,t,n){try{let o=YL("git",["rev-list","--count",`${t}..HEAD`,"--",".",...jO(n)],{cwd:e,encoding:"utf8",timeout:1200});return o.status===0&&parseInt((o.stdout||"").trim(),10)||0}catch{return 0}}function ta(e,t,n){try{let o=rm(e);if(!o)return null;let r=im(e,t),s=zL(r.name,r.project.projectId),i=!!s&&(!XL(s)||!!s.refreshToken),a=lm(e,t)||!am(e,o.authoritativeSourceFiles),l=Mv(e,r.name),c=l?Object.keys(l.articles).length:0,p=Wc(e,(o.docsDir??Bc).replace(/\/+$/,"")),m=!1;try{m=Fc(p)&&sm(p).length>0}catch{}let $=l?.lastAnalyzedCommit?OO(e,l.lastAnalyzedCommit,o):0,w=0;try{let ge=(o.docsDir??Bc).replace(/\/+$/,""),Pe=iO(e,ge);Pe.length>0&&(w=uo(e,ge,Pe.map(Xe=>Xe.path)).length)}catch{}let C=un(e),S=hs({...C,directives:0}),A=QL(e,t),R=new Set(JL(e,r.name)),D=new Set(oO(e,r.name).map(ge=>ge.path)),W=ZL(e,r.name),H=eO(e,o),J=A.filter(ge=>R.has(ge)||D.has(ge)),G=J.length,K=A.length-G,ne=new Set(A),oe=rO(e,t).filter(ge=>!ne.has(ge)),Re=EO(e,oe),le=new Set(Re.map(ge=>ge.path)),he=oe.filter(ge=>!le.has(ge)).length,re=null;try{re=NO(e,Re)}catch{}let ve=[...A.filter(ge=>!R.has(ge)),...oe],Ne=pi(e,ve),tt=Ne.length,xo=qt(Ne),De=null;try{if(!kO(o.styleGuide)){let ge=Iv(e).filter(Pe=>Pe.name.toLowerCase()!=="humanise");De={articles:ea(e).length,presets:[{cmd:"/style-guide keep",desc:"the built-in rules only \u2014 correctness and anti-slop checks (nothing changes)"},...ge.map(Pe=>({cmd:`/style-guide use ${Pe.name.toLowerCase()}`,desc:`${Pe.name} style guide \u2014 ${Pe.rules.length} more rules`}))]}}}catch{}let Le=null;try{if(bO(o.styleGuide)){let Pe=Iv(e).find(Xe=>Xe.name.toLowerCase()===PO);Pe&&(Le={to:Pe.name.toLowerCase(),rules:Pe.rules.length,from:(o.styleGuide?.packs??[]).map(Xe=>Xe.trim().toLowerCase()).filter(Boolean),articles:ea(e).length})}}catch{}let at=null;try{if(vO(e,o?.styleGuide?.packs,o?.styleGuide?.decidedAt)&&!Lv.has(e)){Lv.add(e);let Xe=jv({cwd:e}).findings;xO(e,{packs:o?.styleGuide?.packs??[],from:[],articlesWithFindings:[...new Set(Xe.map(Cn=>Cn.path))]})}let ge=RO(e,CO(e).rules);if(ge&&!Ov.has(e+ge.signature.hash)){Ov.add(e+ge.signature.hash);let Xe=new Set(ge.rules),Cn=jv({cwd:e}).findings.filter(Co=>Xe.has(Co.ruleId)&&!Co.baselined);SO(e,{signature:ge.signature,articlesWithFindings:[...new Set(Cn.map(Co=>Co.path))],packs:o?.styleGuide?.packs??[]})}let Pe=$O(e);Pe&&(at={pending:Pe.pending,total:Pe.total,packs:Pe.packs,...qt(Pe.paths)?{scope:qt(Pe.paths)}:{}})}catch{}let hn=null;try{AO(o)||(hn={articles:ea(e).length,presets:[{cmd:"/auto off",desc:"manual \u2014 I suggest the next step and wait for you to run it"},{cmd:"/auto on",desc:`auto \u2014 I run the next step myself, all the way to live (up to ${et(TO(o))} a run)`}]})}catch{}let Ot=0,Ro;try{let ge=ek(e,ve);Ot=ge.length,Ro=qt(ge)}catch{}let So=0,br=0;try{let ge=yO(e,rm(e)?.outputDir??wO);So=mO(ge).length,br=gO(ge).length}catch{}let da=sO(e,r.name),pa=an(e),Jt=lO(e),Zt=Jt?{...Jt,open:Dv(e).filter(ge=>ge.status==="open").slice(0,DO).map(ge=>({title:ge.title,...ge.run?{run:ge.run}:{},...ge.stage?{stage:ge.stage}:{}}))}:null,$r=hO(e,o),Xn=dO(e,new Date().toISOString(),{supersededByHandoff:$r!==null});pO(e,new Date().toISOString());let _t=Ve(e,t),vr=_t?{name:_t.name,kind:_t.kind,why:_t.why,cmd:_t.cmd}:null,Sn=cO(e),Qn=uO(e),xr=Sn?{status:Sn.status,openQuestions:Qn.openQuestions,answersPending:Qn.answersPending}:null;!xr&&m&&Dv(e).some(Pe=>Pe.status==="open"&&(Pe.run??"").trim()==="/discover")&&(xr={status:"pending",openQuestions:0,answersPending:0});let ha=null;if(r.project.projectId&&r.project.workspaceId)try{let ge=Uv(e,r.name).length;ge>0&&(ha={unpushed:ge,total:ea(e).length,portalArticles:W?W.portalArticles:null,twins:W?.unmapped??0})}catch{}return{ready:i&&a&&!n.claudeMissing,hasDocs:m,tracked:c,firstPublish:ha,pendingText:S,directives:C.directives,behind:$,pendingWrites:w,localAhead:K,unreviewed:tt,unreviewedScope:xo,styleErrors:Ot,shotsToAnnotate:So,shotsToRecapture:br,styleErrorScope:Ro,draftAhead:he,draftBlockedShots:re,conflicts:G,unreadable:J.filter(ge=>D.has(ge)).length,portalUntracked:W?.unmapped??0,portalOnlyCategories:W?.portalOnlyCategories.filter(ge=>ge.articles>0).length??0,undocumentedAreas:tO(H),unreportedAreas:IO(H,l?.lastReportedAreas),declineTarget:LO(H),openComments:da,outboundQuestions:Oi(e),heldHints:C.held,heldHintsAsked:C.heldAsked,autoAudit:!!o.autoAudit,profileName:r.name,allowAutoAudit:n.allowAutoAudit,devhints:pa.status,devhintsCompletedVersion:pa.completedVersion,devhintsToVersion:Ge,builderStarted:Un(e),genreUnknown:n.genreUnknown,pendingAnswer:n.pendingAnswer??null,lastCommand:n.lastCommand??null,styleRules:De,styleUpgrade:Le,styleSweep:at,autoChoice:hn,roadmap:Zt,discovery:xr,uncommittedDocs:Xn.dirty.length,handoff:$r,shareExplained:Fc(fO(e)),brokenEnv:vr}}catch{return null}}ae();import{existsSync as UO,readFileSync as FO}from"node:fs";import{isAbsolute as WO,join as BO}from"node:path";import{DEFAULT_DOCS_DIR as HO,findPathByArticleId as GO,isArticleDocPath as qO,loadProfileMap as VO,readProjectConfig as KO,resolveActiveProfile as YO}from"document360-engine";function _O(){return process.platform==="win32"||process.platform==="darwin"}var MO=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Hc(e,t){let n=e.replace(/\\/g,"/"),o=`${MO(t)}/`,[r,s]=_O()?[n.toLowerCase(),o.toLowerCase()]:[n,o];return r.startsWith(s)?n.slice(o.length):null}var Bv=70;function zO(e,t){return{docsRoot:()=>(KO(e)?.docsDir??HO).replace(/\\/g,"/").replace(/\/+$/,""),read:n=>{try{let o=WO(n)?n:BO(e,n);return UO(o)?FO(o,"utf8"):null}catch{return null}},pathForArticleId:n=>{try{let o=VO(e,YO(e,t).name);return o?GO(o,n):null}catch{return null}}}}var gr=(e,t=Bv)=>{let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"};function na(e){if(!e)return null;let t=!1;for(let n of e.split(`
|
|
469
|
+
`)){let o=n.trimEnd();if(/^\s*(```|~~~)/.test(o)){t=!t;continue}if(t)continue;let r=/^#\s+(\S.*)$/.exec(o);if(r)return gr(r[1])}return null}var XO=new Set(["a","an","and","as","at","but","by","for","in","of","on","or","the","to","vs","with"]),QO=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 Hv(e,t,n){let o=e.toLowerCase();return QO.has(o)?e.toUpperCase():!t&&XO.has(o)?o:!t&&!n?e:e.charAt(0).toUpperCase()+e.slice(1)}var Gv=e=>e.replace(/^\d+[-_.]/,"").split(/[-_]/).filter(Boolean);function JO(e){let t=Gv(e);return t.length===0?e:t.map((n,o)=>Hv(n,o===0,!0)).join(" ")}function qv(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:JO(n[n.length-2])}function Vv(e){let t=e.replace(/\\/g,"/").split("/").pop()??e,n=Gv(t.replace(/\.(md|markdown)$/i,""));return n.length===0?t:n.map((o,r)=>Hv(o,r===0,!1)).join(" ")}var ZO=46;function e_(e,t){let n=0,o=!1,r=null;for(let s of e.split(`
|
|
470
|
+
`)){if(n>t)break;let i=s.trimEnd();if(/^\s*(```|~~~)/.test(i))o=!o;else if(!o){let a=/^(#{2,6})\s+(\S.*)$/.exec(i);a&&(r=gr(a[2],Bv))}n+=s.length+1}return r}function Wv(e){for(let t of e.split(`
|
|
471
|
+
`)){let n=t.replace(/^\s*(#{1,6}\s+|[-*+]\s+|>\s+|\d+[.)]\s+)/,"").replace(/^\s*\|/,"").trim();if(n)return gr(n,ZO)}return null}var Qt=e=>typeof e=="string"&&e?e:null,t_=e=>typeof e=="string"&&e.length>=8?`id ${e.slice(0,8)}\u2026`:null;function n_(e,t){return Hc(e,t)??e.replace(/\\/g,"/")}function o_(e,t){let n=Yt(e,t,200);return n?`+${n.added} \u2212${n.removed}`:"no change"}var r_=new Set(["Edit","MultiEdit","Write"]);function s_(e,t,n,o){if(!r_.has(e))return null;let r=Qt(t.file_path);if(!r)return null;let s=n_(r,n),i=o.docsRoot();if(!(s===i||s.startsWith(`${i}/`)))return null;let a=s.slice(i.length+1);if(!a||!qO(a))return null;let l=qv(a),c=o.read(s),p=H=>na(H)??na(c)??Vv(a);if(e==="Write"){let H=Qt(t.content)??"",J=p(H);if(c===null){let G=H.replace(/\n$/,"").split(`
|
|
472
|
+
`).length;return{verb:"Draft",title:J,category:l,note:`new, ${G} lines`,articleKey:s}}return{verb:"Rewrite",title:J,category:l,note:o_(c,H),articleKey:s}}let m=Array.isArray(t.edits)?t.edits.map(H=>({from:Qt(H.old_string)??"",to:Qt(H.new_string)??""})):[{from:Qt(t.old_string)??"",to:Qt(t.new_string)??""}],$=m.reduce((H,J)=>{let G=Yt(J.from,J.to,200);return G?{added:H.added+G.added,removed:H.removed+G.removed}:H},{added:0,removed:0}),w=$.added===0&&$.removed===0?"no change":`+${$.added} \u2212${$.removed}`,C=m[0],S=C&&c?e_(c,c.indexOf(C.from)):null,A=C?Wv(C.to)??Wv(C.from):null,R=m.length>1?` +${m.length-1} more`:"",D=A?`\u201C${A}\u201D${R}`:R.trim()||null,W=S?{title:`\u21B3 ${S}`,category:D,note:w}:D?{title:`\u21B3 ${D}`,category:null,note:w}:null;return{verb:"Update",title:p(m.map(H=>H.to).join(`
|
|
473
|
+
`)),category:l,note:w,articleKey:s,...W?{repeat:W}:{}}}function i_(e,t,n){let o=()=>{let r=Qt(t.article_id),s=r?n.pathForArticleId(r):null;return(s?na(n.read(s)):null)??(s?Vv(s):t_(r)??"article")};switch(e){case"d360_create_article":{let r=Qt(t.title);return r?{verb:"Create",title:gr(r),category:qv(t.local_path),note:"Document360 draft"}:null}case"d360_update_article":return{verb:"Update",title:Qt(t.title)?gr(Qt(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=Qt(t.name);return r?{verb:"Create",title:gr(r),category:null,note:"Document360 category"}:null}case"d360_upload_drive_file":{let r=Qt(t.file_path);if(!r)return null;let s=r.replace(/\\/g,"/").split("/").pop()??r;return{verb:"Upload",title:gr(s),category:null,note:"Document360 Drive",keepResult:!0}}default:return null}}function Gc(e,t,n,o,r=zO(n,o)){try{let s="mcp__document360__";return e.startsWith(s)?i_(e.slice(s.length),t,r):s_(e,t,n,r)}catch{return null}}var a_={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"},Yv=160,cm=200,zv=40;function bo(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:l_(n)?"\u2026"+n.slice(n.length-(t-1)):n.slice(0,t-1)+"\u2026"}function l_(e){return!e.includes(" ")&&/[/\\]/.test(e)}function Kv(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}: ${bo(typeof r=="string"?r:JSON.stringify(r),zv)}`);return t.length>4&&n.push("\u2026"),bo(n.join(", "),Yv)}var c_=new Set(["file_path","notebook_path"]);function u_(e,t){return t?Hc(e.replace(/\\/g,"/").replace(/\/+$/,""),t)??e:e}var qc=e=>typeof e=="string"&&e?e:null;function d_(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});return e==="d360_sync_status"?n("Check sync status",null):null}function Vc(e,t,n){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,s="",...i]=e.split("__"),a=i.join("__");if(s==="document360"){let p=d_(a,t);if(p)return p}let l=a.replace(/^d360_/,"").replace(/_/g," ");return{title:`${s==="document360"?"Document360":s.charAt(0).toUpperCase()+s.slice(1)}: ${l}`,sep:" ",arg:Kv(t)}}let o=a_[e],r=o?t[o]:void 0;if(typeof r=="string"&&r){let s=o&&c_.has(o)?u_(r,n):r;return{title:e,sep:"",arg:bo(s,Yv)}}return{title:e,sep:"",arg:Kv(t)}}function p_(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 h_(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(p_).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>bo(r,cm))]}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}: ${bo(String(r),zv)}`);return n.length>0?[bo(n.join(" \xB7 "),cm)]:null}return null}function f_(e){let t=qc(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function m_(e,t,n){switch(e){case"d360_create_article":{let o=f_(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=qc(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 ${bo(o[0],120)}`:""}`]}case"d360_create_variable":{let o=qc(t?.name);return[`\u2713 variable created${o?` \xB7 :variable[]{name="${o}"}`:""}`]}case"d360_create_snippet":{let o=qc(t?.name);return[`\u2713 snippet created${o?` \xB7 ::snippet{name="${o}"}`:""}`]}default:return null}}var Xv=new Set(["Edit","Write","MultiEdit","NotebookEdit"]);function g_(e){return e.replace(/^\s*\d+\t/,"")}function y_(e,t){if(Xv.has(e))return[];let n=t.split(`
|
|
474
|
+
`);if(e==="Read"){let o=n.length,r=na(n.map(g_).join(`
|
|
475
|
+
`));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 Kc(e,t=4,n,o){let r=e.replace(/\r\n/g,`
|
|
476
|
+
`).trimEnd();if(n&&Xv.has(n))return{lines:[],hidden:0};if(!r)return{lines:["(no output)"],hidden:0};if(n&&!n.startsWith("mcp__")){let i=y_(n,r);if(i)return{lines:i,hidden:0}}if(n?.startsWith("mcp__document360__")){let i=m_(n.slice(18),o,r);if(i)return{lines:i,hidden:0}}let s=h_(r)??r.split(`
|
|
477
|
+
`);return{lines:s.slice(0,t).map(i=>bo(i,cm)),hidden:Math.max(0,s.length-t)}}function Yc(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function zc(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 Qv(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 Xc(e){return Qv(e,"url")}function Qc(e){return Qv(e,"preview_url")}function Jc(e,t){try{let o=JSON.parse(t),s=(Array.isArray(o)?o[0]:o)?.title;if(typeof s=="string"&&s.trim())return s.trim()}catch{}if(typeof e.title=="string"&&e.title.trim())return e.title.trim();let n=e.local_path;return typeof n=="string"&&n.trim()?(n.replace(/\\/g,"/").split("/").pop()??n).replace(/\.(md|markdown)$/i,""):null}var sx=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/,dm=null;function tx(){return dm===null&&(dm=T_().verboseTranscript===!0),dm}function V_(e,t,n,o){if(sx.test(e))try{let r=rx(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,i=zc(t,n),a=Jc(t,n),l=a?`${a} \u2014 `:"",c=Xc(n);e.endsWith("publish_article")&&c&&console.log(Z(` \u2B95 ${l}Live: ${c}`));let p=Qc(n);p?console.log(Z(` \u2B95 ${l}Preview: ${p}`)):i&&s&&console.log(Z(` \u2B95 ${l}Preview: ${Yc(r.connection.portalUrl,s,i,r.project.languageCode??"en")}`))}catch{}}async function fm(e=process.cwd(),t="auto",n,o){let r=k_(t);r.kind==="none"&&(console.error(""),console.error(L("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${Z("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${Z('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${Z("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${Z(`${hm} --auth subscription`)}`),console.error(""),process.exit(2)),K_(e,n);let s=b_(t),i=$_(s);console.log(i?F(` ${Jv(s)}`):u(` ${Jv(s)}`)),i?console.log(u(` ${i}`)):r.kind==="subscription"&&!r.stored&&console.log(u(" No sign-in found on this machine \u2014 trying your Claude session anyway.")),console.log("");let a=!1,l=um({cwd:e,profileName:n,allowProdWrites:a}),c={uuid:null,firstPrompt:null,titleFired:!1},p=w_({input:process.stdin,output:process.stdout}),m=[],$=null,w=!1;p.on("line",A=>{if($){let R=$;$=null,R(A)}else m.push(A)}),p.on("close",()=>{if(w=!0,$){let A=$;$=null,A(null)}});function C(){return m.length>0?Promise.resolve(m.shift()):w?Promise.resolve(null):(process.stdout.write(Z("> ")),new Promise(A=>{$=A}))}let S={cwd:e,version:o,profileName:n,allowProdWrites:()=>a,restartAgent:()=>{l.close(),l=um({cwd:e,profileName:n,allowProdWrites:a}),c={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>c.uuid,setPendingName:A=>{c.pendingName=A},setModel:async A=>l.setModel(A),withPausedInput:async A=>{p.pause();try{return await A()}finally{p.resume()}}};try{for(;;){let A=await C();if(A===null)break;let R=A.trim();if(R){if(R.startsWith("/")){let D=Rv(R);if(!D)continue;let W=xv[D.name];if(!W){console.log(L(`Unknown command: /${D.name}`)),console.log(u("Type /help for the list."));continue}let H=await W(D.args,S);if(H.kind==="exit")break;if(H.kind==="clear"){S.restartAgent();continue}if(H.kind==="allow-prod"){a=!0,S.restartAgent(),console.log(Q("\u2713 Production writes authorized for this session.")),console.log("");continue}if(H.kind==="resume"){l.close(),l=um({cwd:e,resume:H.uuid,profileName:n,allowProdWrites:a});let J=v_(H.uuid);c={uuid:H.uuid,firstPrompt:J?.firstPrompt??null,titleFired:!0},ox(H.uuid),console.log(Q(`\u2713 Resumed "${H.name}"`)),console.log("");continue}if(H.kind==="audit-blocked"){console.log(F(H.note)),console.log(u(` Run: ${H.lead.cmd} \u2014 ${H.lead.reason}.`)),console.log("");continue}if(H.kind==="forward-to-agent"){c.firstPrompt||(c.firstPrompt=H.display??H.prompt);let J=H.display??"",G=J.trim().split(/\s+/),K=Hk(J),ne=K?M_(e,Gk(J)):[],oe=K==="review"?ex(e):null,Re=G[0]==="/screenshot"&&(G[1]==="verify"||G[1]==="review"),le=Re?G[2]&&!G[2].startsWith("--")?[G[2]]:Ei(Ke(e)):[],he=G[0]==="/catch-up"&&!K,re=he?ex(e):null;l.beginTurn({baseline:re,allowUnfinishedHints:G.includes("--include-unfinished")});let ve=he?un(e):null,Ne=he?Ui(e).hold:!1,tt=H.prompt;if(J.startsWith("/"))try{let De=Pl(e,J);De&&(tt=`${tt}
|
|
478
|
+
|
|
479
|
+
${De}`)}catch{}let xo=await pm(l,tt,r,c,e,n);if(K){let De=K==="review"?pr(e,ne,oe,n):null,Le=De?De.earned:ne;if(Le.length>0)try{__(e,Le,St(K))}catch{}let at=De?ys(e,De.unadopted,{lead:De.changed.length===0}):null;if(at)for(let hn of at.lines)console.log(u(hn))}if(re){xo.produced&&B_(e);let De=lr(e,re,"",G[0]);if(De.cta)console.log(u(De.cta.text));else if(ve){let Le=yc({queued:ve,hold:Ne});Le.note&&console.log(Le.tone==="warn"?F(Le.note):u(Le.note)),Le.lead&&console.log(u(` Run ${Le.lead.cmd} \u2014 ${Le.lead.reason}.`))}}if(G[0]==="/reuse"&&G[1]==="audit"){let De=G.slice(2).find(Le=>!Le.startsWith("--"));for(let Le of _c(e,De))console.log(Le)}if(G[0]==="/audit"&&!G.includes("--auto")&&Qi(e,n),Re&&le.length>0)try{for(let De of us(e,le))console.log(De)}catch{}if(G[0]==="/push"){let De=await di(e,n);De&&console.log(u(De))}if((G[0]==="/catch-up"||G[0]==="/document")&&(G.includes("--push")||G.includes("--publish")))try{let De=await W_({cwd:e,profileName:n}),{clean:Le,conflicts:at}=Zo(De.entries,er(e,n));Le.length===0?console.log(u("Nothing new to push \u2014 everything is already up to date on Document360.")):await cn(S,Le.map(hn=>hn.path),at.length,{skipReview:G.includes(Vt)})}catch(De){console.log(F(`Couldn't check what to push (${De.message}) \u2014 your drafts are saved; run /push when ready.`))}}else H.kind==="continue"&&H.ownNext||Y_(e,n);continue}if(j_(R)){let D=I_(R);if(D){try{L_(e,{title:D,by:`owner (${G_} terminal)`,at:new Date().toISOString()})}catch{}c.firstPrompt||(c.firstPrompt=R),await pm(l,`The owner left this documentation directive (already recorded in ${q_}/directives.md): "${D}". Action it now: ground it in the sources, write/update the article(s) as DRAFTS (do not publish unless asked), following the active doc-type playbook. When finished, call d360_directive_done with the exact title "${D}" and the article path(s) you wrote.`,r,c,e,n);continue}}c.firstPrompt||(c.firstPrompt=R),await pm(l,R,r,c,e,n)}}}finally{l.close(),p.close(),await Rc()}}function K_(e,t){console.log(""),console.log(Qs(H_)),console.log(u(` cwd: ${e}`));let n=P_(e);if(console.log(u(` model: ${n.model}${n.source==="auto"?" (auto \u2014 right-sized for docs; /model to change)":` (${n.source})`}`)),console.log(z_(e,t)),!A_(e))console.log(F(" 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(el(e),!Un(e))for(let r of tl(e))console.log(F(` ${r}`))}catch{}try{let r=E_(e);r.persisted&&r.appType?console.log(u(` \u2713 Detected a ${r.appType} app \u2014 enabled the ${r.appType}-doc-playbook (change with /genre).`)):r.source==="unknown"&&(o=!0)}catch{}try{let r=O_(e);for(let s of za(r.applied))console.log(F(` ${s}`));if(r.reopenedForRedaction)for(let s of Xa(r.reopenedForRedaction).split(/\r?\n/))console.log(F(` ${s}`))}catch{}try{let r=ta(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:o}),s=r?Zi(r,{pickable:!1,scaleFor:i=>dn(e,i)}):null;if(s?.kind==="recommend"&&s.rec.note){let i=s.rec.tone==="warn"?F:u;for(let a of Zl(s.rec.note).split(`
|
|
480
|
+
`))console.log(i(` ${a}`));s.rec.picker&&console.log(Z(` Pick one: ${s.rec.picker.options.map(a=>a.cmd).join(" \xB7 ")}`))}}catch{}}console.log(u(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}var nx=!1;function Y_(e,t){try{let n=ta(e,t,{claudeMissing:!1,allowAutoAudit:!1,genreUnknown:!1}),o=n?Zi(n,{scaleFor:r=>dn(e,r)}):null;if(o?.kind!=="recommend")return;if(o.rec.settled&&!nx){nx=!0;for(let r of Zl(o.rec.settled).split(`
|
|
481
|
+
`))console.log(Q(` ${r}`))}else o.rec.settled&&!o.rec.lead&&console.log(u(" Nothing is waiting. /roadmap lists the optional campaign steps."));o.rec.lead&&console.log(u(` Next: ${vs(o.rec.lead)}`))}catch{}}function z_(e,t){try{let n=rx(e,t),o=n.production?F(` ${Je}`):"",r=Ve(e,t);if(r)return F(` Document360: profile "${n.name}" cannot reach ${r.name} (${r.cmd})`);let s=D_(n.name,n.project.projectId);if(!s)return u(` Document360: profile "${n.name}"${o} \u2014 not logged in (${hm} login)`);let i={...Zv(s.idToken)??{},...Zv(s.accessToken)??{}},a=i.email??i.preferred_username??"signed in";return N_(s)&&!s.refreshToken?F(` Document360: profile "${n.name}"${o} \u2014 session expired (${hm} login)`):u(` Document360: ${a} \xB7 profile "${n.name}"${o}`)}catch(n){return u(` Document360: ${n.message.split(".")[0]}`)}}function X_(){console.error(""),console.error(`Sign in with your Claude subscription: run ${Z("claude")} once, then retry.`),console.error(` (No Claude Code? ${Z("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${Z("https://console.anthropic.com/settings/keys")}`)}function Q_(e,t,n){e.uuid=t;let o=new Date().toISOString(),r=e.pendingName;S_({uuid:t,name:r??R_(e.firstPrompt??"session"),renamed:!!r,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o}),e.pendingName=null}function J_(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||C_(o,t).then(r=>{r&&x_(n,r)}).catch(()=>{})}async function pm(e,t,n,o,r,s){let i=new Map,a=!1,l=!1;for await(let c of e.send(t))c.type==="tool"&&(l=!0),c.type==="text"&&c.delta.trim()&&(l=!0),c.type==="tool"&&sx.test(c.name)&&(a=!0),Z_(c,o,r,n,i,s);if(a)try{let c=F_(await U_({cwd:r,profileName:s}));c&&console.log(c.startsWith("\u26A0")?F(c):c)}catch{}return{produced:l}}function Z_(e,t,n,o,r,s){switch(e.type){case"session":t.uuid||Q_(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let i=tx()?null:Gc(e.name,e.input,n,s);if(i){process.stdout.write(`
|
|
482
|
+
|
|
483
|
+
`);let l=[i.category,i.note].filter(p=>!!p).map(p=>Ie(` \xB7 ${p}`)),c=i.loud?Ie(" \xB7 ")+rt(F(i.loud)):"";console.log(`${Q("\u25CF")} ${Z(rt(Ip(i.verb)))}${rt(i.title)}${l.join("")}${c}`),r.set(e.id,{name:e.name,input:e.input,doc:!0,keepResult:i.keepResult});break}let a=Vc(e.name,e.input,process.cwd());a&&(process.stdout.write(`
|
|
484
|
+
|
|
485
|
+
`),console.log(`${Ie("\u25CF")} ${a.title}${a.arg!==null?Ie(`${a.sep}(${a.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let i=Yt(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!i)break;let a=l=>l===1?"":"s";console.log(Ie(` \u23BF Added ${i.added} line${a(i.added)}, removed ${i.removed} line${a(i.removed)}`));for(let l of i.lines)console.log(l);i.hidden>0&&console.log(u(` \u2026 +${i.hidden} more diff lines`));break}case"tool_result":{let i=r.get(e.id);if(!i)break;r.delete(e.id);let l=i.doc&&!i.keepResult&&!e.isError?{lines:[],hidden:0}:Kc(e.output,4,e.isError||tx()?void 0:i.name,i.input),c=e.isError?L:Ie;l.lines.forEach((p,m)=>console.log(c((m===0?" \u23BF ":" ")+p))),l.hidden>0&&console.log(u(` \u2026 +${l.hidden} lines`)),e.isError||V_(i.name,i.input,e.output,n);break}case"result":{process.stdout.write(`
|
|
486
|
+
`);let i=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;console.log(u(` (${$i(i)}\u2192${$i(e.outputTokens)} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(ox(t.uuid),t.titleFired||J_(t,n));break}case"error":console.error(""),e.kind==="limit"?console.log(F(`\u23F3 ${e.message}`)):console.error(L(`agent error: ${e.message}`)),e.note&&console.log(u(` ${e.note}`)),o.kind==="subscription"&&e.kind==="auth"&&X_();break}}import{render as RF}from"ink";import{resolveAuth as SF,WRITER_COMMAND as CF}from"document360-engine";import{useCallback as ce,useEffect as mt,useMemo as uu,useRef as de,useState as me}from"react";import{Box as Me,Text as z,useApp as qM,useInput as VM,useStdout as KM}from"ink";import{existsSync as Ps,readFileSync as du,readdirSync as YM,writeFileSync as u0,mkdirSync as zM}from"node:fs";import{basename as sa,dirname as XM,isAbsolute as QM,join as ia}from"node:path";import{createSession as d0,classifyClaudeAuth as Im,CLAUDE_CODE_SETUP_HINT as JM,loginPkce as ZM,toStoredTokens as eU,saveTokens as tU,getAccessToken as nU,D360AuthError as oU,resolveActiveProfile as wt,resolveProjectId as rU,getArticle as sU,decodeJwtClaims as Ns,isExpired as kr,loadTokens as vo,clearTokens as iU,rememberSessionProject as aU,listStoredSessions as lU,tokensProjectId as p0,clearProfileProject as cU,setTitle as uU,slugify as dU,touchSession as Pm,upsertSession as pU,generateTitle as h0,findByName as hU,listSessions as fU,renameSession as mU,suggestNextAction as gU,readProjectConfig as Se,writeProjectConfig as f0,autoModeEnabled as m0,autoBudgetUsd as pu,DEFAULT_AUTO_BUDGET_USD as yU,WRITER_DIRNAME as pt,readUserConfig as g0,writeUserConfig as wU,resolveAndPersistAppType as kU,detectAppType as y0,resolveModelSetting as Lm,loadProfileMap as bU,applyPull as hu,computeSyncStatus as aa,unpushedArticlePaths as $U,ensureSeededContentSwept as vU,seededSweepLines as xU,lintDocs as As,compareRemoteSources as RU,planPull as w0,recordRunSample as SU,pushArticles as CU,pushArticle as PU,PUSH_POOL_SIZE as AU,isPullWouldBlankError as k0,localArticleTitle as b0,establishBaselines as TU,rebaselineServerMeta as EU,inventoryRepo as NU,resolveEnvironment as DU,environmentIsProduction as jU,environmentIsInternal as IU,planPartitions as Am,partitionEvenly as LU,screenshotPlaceholderIds as OU,trackedArticlePaths as _U,runPartitioned as la,partitionCoverage as Tm,estimateBulkCost as $0,resolveModelForOperation as ca,readDocsPlan as v0,checkForUpdate as x0,detectInstallKind as MU,isSelfUpdatable as UU,devHintsGuidePath as R0,toolFeedbackPath as S0,reconcileToolFeedback as FU,reconcileUpgradeActions as WU,stampArticles as Ts,snapshotArticles as Em,listArticleFiles as BU,CONTENT_CAP_VERSION as HU,ENGINE_VERSION as _0,DEFAULT_DOCS_DIR as Om,docsRootOf as GU,setProfileProject as qU,writeCrashLog as VU,applyStructureOrder as Nm,orderSyncLine as Dm,applyRelatedArticles as C0,relatedSyncLine as P0,reconcileDocsGit as KU,shareExplainedPath as YU,ensureDir as zU}from"document360-engine";Yr();io();import{spawn as ix}from"node:child_process";import{existsSync as eM,mkdirSync as tM,readFileSync as nM,writeFileSync as oM}from"node:fs";import{join as ax}from"node:path";import{userDir as lx}from"document360-engine";function rM(){if(process.env.WSL_DISTRO_NAME||process.env.WSL_INTEROP)return!0;try{return/microsoft/i.test(nM("/proc/version","utf8"))}catch{return!1}}function sM(e=process.platform,t=rM()){if(e==="win32")return[{cmd:"clip",args:[],encoding:"utf16le"}];if(e==="darwin")return[{cmd:"pbcopy",args:[],encoding:"utf8"}];let n=[{cmd:"wl-copy",args:[],encoding:"utf8"},{cmd:"xclip",args:["-selection","clipboard"],encoding:"utf8"},{cmd:"xsel",args:["--clipboard","--input"],encoding:"utf8"}];return t&&n.push({cmd:"clip.exe",args:[],encoding:"utf16le"}),n}function iM(e,t){return new Promise(n=>{try{let o=process.platform==="win32"?ix([e.cmd,...e.args].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):ix(e.cmd,e.args,{stdio:["pipe","ignore","ignore"]});o.on("error",()=>n(!1)),o.on("close",s=>n(s===0)),o.stdin?.on("error",()=>n(!1));let r=e.encoding==="utf16le"?Buffer.from("\uFEFF"+t,"utf16le"):Buffer.from(t,"utf8");o.stdin?.end(r)}catch{n(!1)}})}async function mm(e){for(let t of sM())if(await iM(t,e))return!0;return!1}function aM(e){return ax(lx(),"copy",`${e}.txt`)}async function cx(e,t){if(await mm(e))return{copied:!0,path:null};let n=aM(t);try{let o=ax(lx(),"copy");return eM(o)||tM(o,{recursive:!0}),oM(n,e,"utf8"),{copied:!1,path:n}}catch{return{copied:!1,path:null}}}var ux=/\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 dx(e){let t=e.replace(/\s+$/,"").split(`
|
|
487
|
+
`),n=0;for(let s=t.length-1;s>=0;s--){let i=t[s];if(/^\s{0,3}\d{1,2}[.)]\s+\S/.test(i)){n++;continue}if(!(n>0&&/^\s+\S/.test(i)))break}return n<2?0:t.filter(s=>/^\s{0,3}\d{1,2}[.)]\s+\S/.test(s)).slice(-n).every((s,i)=>Number(/^\s{0,3}(\d{1,2})/.exec(s)[1])===i+1)?n:0}var lM=/\b(?:once|after|when)\s+(?:you|you've|you have|they|those|these|that)\b[^.!?]{0,80}\b(?:tell me|let me know|come back|ask me|say the word|run\s+\/|then\s+\/)|\b(?:tell me|let me know)\s+(?:when|once|and)\b|\bi'?ll\s+(?:wait|stand by|pick (?:it|this) up)\b|\bcome back to me\b|\bthen\s+(?:ask|tell)\s+me\b/i;function px(e){let t=e.trimEnd();if(!t)return null;let n=dx(t);return n>=2?{options:n}:/\?[\s*_"')\]]*$/.test(t)||ux.test(t)||lM.test(t)?{options:0}:null}function gm(e,t){if(t.closed)return e;let n=e.split(`
|
|
488
|
+
`),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){ux.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(`
|
|
489
|
+
`)}var cM=/^(?:(?:run|use|try|execute)\s+)?['"`*]?(\/[a-z][a-z-]*)['"`*]?((?:\s+(?:--?[a-z][\w-]*|\S*[/\\]\S*|\d{1,3}[-_][\w.-]*|[\w.-]+\.(?:md|markdown)))*)/i;function uM(e,t){let n=dx(e);return n<2?[]:e.replace(/\s+$/,"").split(`
|
|
490
|
+
`).filter(s=>/^\s{0,3}\d{1,2}[.)]\s+\S/.test(s)).slice(-n).map(s=>{let i=s.replace(/^\s{0,3}\d{1,2}[.)]\s+/,"").trim(),a=cM.exec(i);if(!a)return null;let l=a[1].slice(1).toLowerCase();return t.has(l)?`${a[1]}${(a[2]??"").replace(/\s+/g," ").trimEnd()}`:null})}function hx(e,t){let n=uM(e,t);return n.length<2||n.some(o=>o===null)?null:n}import{WRITER_COMMAND as dM}from"document360-engine";function pM(e){let t=e.split(`
|
|
491
|
+
`).map(o=>o.trim()).filter(o=>o.length>3),n=t[t.length-1];return n?n.length>160?`${n.slice(0,157)}\u2026`:n:null}function Rs(e){if(e.usageLimit)return`${e.label}: ${e.usageLimit}`;let t=e.stderrTail?pM(e.stderrTail):null;return t?`${e.label} last said: ${t}`:`${e.label} has said nothing since. Whatever it is, it is recorded: ${dM} logs. Stopping keeps every batch already finished.`}var hM={la:"local","l all":"local","local all":"local",pa:"portal","p all":"portal","portal all":"portal",sa:"skip","s all":"skip","skip all":"skip"},fM={L:"local",P:"portal",S:"skip"},mM={ya:"write","y all":"write","yes all":"write",na:"skip","n all":"skip","no all":"skip"},gM={Y:"write",N:"skip"};function fx(e,t,n){let o=e.trim(),r=o.toLowerCase().replace(/\s+/g," ");return t[r]??(o.length===1?n[o]??null:null)}function Zc(e){return fx(e,hM,fM)}function mx(e){return fx(e,mM,gM)}function ym(e,t){let n=t?.max??12,o=t?.chrome??8;return Math.max(3,Math.min(n,(e??24)-o))}function eu(e,t,n){if(e<=n)return{start:0,end:e,above:0,below:0};let o=Math.min(Math.max(0,t),e-1),r=Math.min(Math.max(0,o-Math.floor(n/2)),e-n),s=r+n;return{start:r,end:s,above:r,below:e-s}}function wm(e,t,n,o=Date.now()){let s=e.value>0&&o-e.at<900?e.value*10+t:0,i=s>=1&&s<=n?s:t>=1&&t<=n?t:0;return i===0?{index:null,memory:{value:0,at:o}}:{index:i-1,memory:{value:i,at:o}}}function gx(e){return e<2?null:`1-${e}`}function Lt(e){let t=[];if(e.multi)t.push("\u2191\u2193 move","space toggle");else{t.push("\u2191\u2193 move");let n=e.rows===void 0?null:gx(e.rows);n&&t.push(`${n} jump to a row`)}return t.push(...e.extra??[]),t.push(`enter ${e.verb}`),t.push(`esc ${e.cancel??"cancel"}`),t.join(" \xB7 ")}function yx(e){if(e.multi)return"pick with space, then enter to save \xB7 esc to cancel\u2026";let t=e.rows===void 0?null:gx(e.rows);return`choose one below \u2014 \u2191\u2193 then enter to ${e.verb}${t?", or type its number":""} \xB7 esc to ${e.cancel??"cancel"}\u2026`}var yM=[/\bfile does not exist\b/i,/\bno such file or directory\b/i,/\bENOENT\b/,/\bno (files? )?(were )?found\b/i,/\bfound 0 (files?|matches|results)\b/i,/\bno matches\b/i,/\bdid not match any\b/i,/\bno results?\b/i],wM=[/\bpermission denied\b/i,/\bEACCES\b/,/\bEPERM\b/,/\bnot authori[sz]ed\b/i,/\bunauthori[sz]ed\b/i,/\bforbidden\b/i,/\brefus(ed|ing)\b/i,/\bblocked\b/i,/\bwriter mode\b/i,/\bHTTP [45]\d\d\b/],kM=/^(read|glob|grep|ls|search|notebookread)$/i;function wx(e,t){return!e||!kM.test(e.trim())||wM.some(n=>n.test(t))?!1:yM.some(n=>n.test(t))}import{existsSync as bM,mkdirSync as $M,readFileSync as vM,writeFileSync as xM}from"node:fs";import{join as kx}from"node:path";import{writerDir as RM}from"document360-engine";function bx(e){return kx(RM(e),".sessions")}function $x(e,t){return kx(bx(e),`${t}.json`)}function vx(e,t,n){try{$M(bx(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");xM($x(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function km(e,t){try{let n=$x(e,t);if(!bM(n))return[];let o=JSON.parse(vM(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var SM=e=>`\x1B]0;${e}\x07`,CM=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function xx(e){process.stdout.isTTY&&process.stdout.write(e)}function Ss(e){xx(SM(e))}function tu(e){xx(CM(e))}var nu=["\xB7 "," \xB7"],ou="\u{1F7E3}";lc();var bm=e=>e===1?"":"s";function Rx(e){return e.reason.kind==="repeat"||e.reason.kind==="noProgress"||e.reason.kind==="maxSteps"}function Sx(e){let t=e.ran.length,n=e.failed?.length??0,o=t===0?"nothing to do":n===0?`${t} step${bm(t)} done`:n===t?`${t} step${bm(t)} tried, ${t===1?"it":"none"} got through`:`${t-n} of ${t} steps done`;switch(e.reason.kind){case"settled":return{tone:"ok",text:`Auto mode finished \u2014 that is the full round trip. ${o}.`};case"delivered":return{tone:"ok",text:`Auto mode finished \u2014 this round is delivered and your readers have it. ${o}.`};case"nothingToDo":return t===0?e.parked.length>0?{tone:"ok",text:"Auto mode had nothing it could run on its own \u2014 everything else is already written, saved and live."}:{tone:"ok",text:"Auto mode had nothing to do \u2014 everything is already written, saved and live."}:e.parked.length>0?{tone:"ok",text:`Auto mode finished what it could. ${o}.`}:{tone:"ok",text:`Auto mode finished \u2014 nothing left waiting. ${o}.`};case"onlyBlocked":return t===0?{tone:"warn",text:"Auto mode did not start anything \u2014 everything waiting needs a decision from you."}:{tone:"warn",text:`Auto mode went as far as it could on its own. ${o}, and the rest needs you.`};case"budget":return{tone:"warn",text:`Auto mode stopped at its spending limit \u2014 ${et(e.reason.spentUsd)} of ${et(e.reason.limitUsd)}. ${o}.`};case"stopped":return{tone:"warn",text:`Auto mode stopped \u2014 you asked it to. ${o}.`};case"repeat":case"noProgress":return{tone:"warn",text:`Auto mode stopped \u2014 ${e.reason.cmd} came back unfinished, and running it again would not have changed that. ${o}.`};case"maxSteps":return{tone:"warn",text:`Auto mode stopped after ${e.reason.steps} steps without reaching a finished state. ${o}.`}}}function Cx(e){switch(e.reason.kind){case"settled":case"nothingToDo":return e.parked.length>0?{tone:"info",text:"What is left is with someone else. I am still in auto mode, so I will pick it up as soon as it lands."}:{tone:"info",text:"Nothing is waiting. I am still in auto mode, so the next time there is work I will pick it up."};case"delivered":return{tone:"info",text:"What is left needs you or a browser \u2014 /status lists it, and it costs nothing. I am still in auto mode for the next round."};case"budget":return{tone:"info",text:`/auto --budget <amount> raises the limit, then /auto on picks up at ${e.reason.next}.`};case"stopped":return{tone:"info",text:"/auto on picks the round trip back up from here. Nothing was undone."};case"onlyBlocked":return{tone:"info",text:"Clear the items above and I will carry on \u2014 /auto on starts me again."};case"repeat":case"noProgress":case"maxSteps":return{tone:"info",text:"This one needs a person, so I have stopped trying \u2014 auto mode is still on, and /auto on starts me again once it is cleared. /status shows what is in the way, and it costs nothing."}}}function Px(e){let t=[Sx(e)],n=e.spentUsd>0?` \xB7 ${et(e.spentUsd)} of ${et(e.budgetUsd)}`:"";if(t.push({tone:"info",text:` ${Xl({seconds:e.seconds,...e.activeSeconds!==void 0?{activeSeconds:e.activeSeconds}:{}})}${n}`}),e.ran.length>0){t.push({tone:"info",text:""}),t.push({tone:"info",text:" What I ran:"});for(let o of e.ran)t.push({tone:"info",text:` \xB7 ${o}`})}if(e.parked.length===0&&Rx(e)&&(t.push({tone:"info",text:""}),t.push({tone:"warn",text:` ${e.ran[e.ran.length-1]??"The last step"} did not get through \u2014 what it said is above.`})),e.parked.length>0){t.push({tone:"info",text:""}),t.push({tone:"warn",text:` ${e.parked.length} thing${bm(e.parked.length)} need${e.parked.length===1?"s":""} you:`});for(let o of e.parked)t.push({tone:"warn",text:` \xB7 ${o.what}${o.cmd?` \u2192 ${o.cmd}`:""}`})}return e.reason.kind!=="settled"&&e.reason.kind!=="nothingToDo"&&e.reason.kind!=="delivered"&&e.ran.length>0&&(t.push({tone:"info",text:""}),t.push({tone:"info",text:" Everything already written, saved and published is kept \u2014 stopping never undoes work."})),t.push({tone:"info",text:""}),t.push(Cx(e)),t}function Ax(e,t){let n=Sx(e).text,o=[`# Automatic run \u2014 ${t}`,"",n,""];if(o.push(`- Time: ${Xl({seconds:e.seconds,...e.activeSeconds!==void 0?{activeSeconds:e.activeSeconds}:{}})}`),o.push(`- Spent: ${et(e.spentUsd)} of a ${et(e.budgetUsd)} limit`),o.push(""),o.push("## What ran"),o.push(""),e.ran.length===0)o.push("Nothing \u2014 see above for why.");else for(let r of e.ran)o.push(`- \`${r}\`${e.failed?.includes(r)?" \u2014 refused, see below":""}`);if(o.push(""),o.push("## What needs you"),o.push(""),e.parked.length>0)for(let r of e.parked)o.push(`- ${r.what}${r.cmd?` Run \`${r.cmd}\`.`:""}`);else Rx(e)?o.push(`- \`${e.ran[e.ran.length-1]??"The last step"}\` did not get through. The session transcript above has what it said.`):o.push("Nothing.");return o.push(""),o.push(Cx(e).text),o.push(""),o.join(`
|
|
492
|
+
`)}var Tx=new Set(["/resolve","/pull","/screenshot","/login","/logout","/init","/reset","/discover","/genre","/style-guide","/scope","/profile","/project","/workspace","/model","/mcp","/share","/auto","/allow-prod"]),PM=new Set(["--skip-review","--skip-style","--skip-screenshots","--force"]),AM=40,TM=2,EM=(e,t)=>e.what===t.what&&e.cmd===t.cmd;function ru(e,t){return e.some(n=>EM(n,t))?e:[...e,t]}function Ex(e){let t=wn(e);if(!t||Tx.has(t.cmd)||!Jr(t))return!1;for(let n of t.flags)if(PM.has(n))return!1;return!NM(t)}function NM(e){return e.cmd!=="/review"&&e.cmd!=="/write"&&e.cmd!=="/reorder"||e.flags.has("--all")||e.flags.has("--blocked")||e.flags.has("--stale")?!1:e.scope===void 0}function Nx(e){let t=wn(e);return!t||t.cmd!=="/push"||t.scope!==void 0||t.flags.has("--all")||t.flags.size>0?e:"/push --all"}function Dx(e){return!e||e.kind!=="cmd"?null:e.cmd}function DM(e){return e.kind==="answer"?{what:"I asked you a question and stopped to wait for the answer.",cmd:null}:e.kind==="prompt"?{what:`A step needs you to tell me what you want: \u201C${e.text}\u201D.`,cmd:null}:jx(e.cmd)}function jx(e){switch(wn(e)?.cmd??e.split(/\s+/)[0]??e){case"/resolve":return{what:"Some articles were changed both here and in Document360, and only you can say which copy survives.",cmd:"/resolve"};case"/pull":return{what:"Document360 has articles this repo has no folder for, and importing them changes your docs tree.",cmd:"/pull"};case"/screenshot":return{what:"Some screenshots are still to be taken \u2014 that needs your product running, so I never do it automatically.",cmd:"/screenshot"};case"/login":return{what:"The Document360 session needs signing in again, which happens in your browser.",cmd:"/login"};case"/discover":return{what:"The product questions are still out with your builder, so there is nothing I can answer tonight.",cmd:"/discover"};default:return{what:`${e} is a step I leave to you.`,cmd:e}}}var Ix=new Set(["repeat","noProgress","maxSteps","budget"]),jM=(e,t)=>e.ran.filter(n=>n===t).length;function Lx(e,t,n){let o=t.parked,r=n.maxSteps??AM;if(t.ran.length>=r)return{kind:"stop",reason:{kind:"maxSteps",steps:t.ran.length},parked:o};if(e.heldHints>0){let a=e.heldHints;o=ru(o,{what:`${a} note${a===1?"":"s"} from your builder ${a===1?"is":"are"} waiting on code they haven't finished \u2014 I've asked whether ${a===1?"it's":"they're"} done.`,cmd:null})}if(e.restKind==="complete")return{kind:"stop",reason:{kind:"settled"},parked:o};if(e.restKind==="delivered"&&t.ran.length>0)return{kind:"stop",reason:{kind:"delivered"},parked:o};if(!e.lead&&!e.picker&&e.menu.length===0)return{kind:"stop",reason:{kind:"nothingToDo"},parked:o};e.picker&&(o=ru(o,{what:`${e.picker.title} \u2014 that one is yours to answer.`,cmd:null}));let s=[{cmd:Dx(e.lead),lead:e.lead},...e.menu.map(a=>({cmd:a.startsWith("/")?a:null,lead:null}))],i=new Set;for(let a of s){if(!a.cmd){if(a.lead?.kind==="prompt"&&a.lead.text===mr)return t.ran.includes(mr)?{kind:"stop",reason:{kind:"noProgress",cmd:mr},parked:o}:t.spentUsd>=n.budgetUsd?{kind:"stop",reason:{kind:"budget",spentUsd:t.spentUsd,limitUsd:n.budgetUsd,next:mr},parked:o}:{kind:"prompt",text:mr,parked:o};a.lead&&(o=ru(o,DM(a.lead)));continue}let l=Nx(a.cmd);if(i.has(l))continue;if(i.add(l),!Ex(a.cmd)){let p=wn(a.cmd);p&&Tx.has(p.cmd)&&(o=ru(o,jx(a.cmd)));continue}if(t.ran[t.ran.length-1]===l)return{kind:"stop",reason:{kind:"repeat",cmd:l},parked:o};if(jM(t,l)>=TM)return{kind:"stop",reason:{kind:"repeat",cmd:l},parked:o};if(t.lastClosedItsTarget===!1&&t.lastLeadKey&&t.lastLeadKey===l)return{kind:"stop",reason:{kind:"noProgress",cmd:l},parked:o};let c=t.spentUsd+(n.nextCostUsd??0);return t.spentUsd>=n.budgetUsd||c>n.budgetUsd?{kind:"stop",reason:{kind:"budget",spentUsd:t.spentUsd,limitUsd:n.budgetUsd,next:l},parked:o}:{kind:"run",cmd:l,parked:o}}return{kind:"stop",reason:{kind:"onlyBlocked"},parked:o}}function Ox(e,t,n){let o=[],r=new Set([t]),s=[Dx(e.lead),...e.menu.map(i=>i.startsWith("/")?i:null)];for(let i of s){if(!i||!Ex(i))continue;let a=Nx(i);if(r.has(a))continue;r.add(a);let l=null;try{l=n(a)}catch{l=null}o.push({cmd:a,scale:l})}return o}var _x=()=>({fingerprint:null,counts:null,settled:0,spokenBaseline:null,lastSpokeAt:null,awaySince:null}),IM={hints:0,requests:0,answers:0,directives:0,held:0,heldAsked:0,briefMoved:!1};function $m(e,t){let n=e??IM;return{hints:Math.max(0,t.hints-n.hints),requests:Math.max(0,t.requests-n.requests),answers:Math.max(0,t.answers-n.answers),directives:Math.max(0,t.directives-n.directives),held:Math.max(0,t.held-n.held),heldAsked:Math.max(0,t.heldAsked-n.heldAsked),briefMoved:t.briefMoved&&!n.briefMoved}}var su=e=>e.hints===0&&e.requests===0&&e.answers===0&&e.directives===0&&!e.briefMoved,Mx=e=>e.hints+e.requests+e.answers+e.directives+(e.briefMoved?1:0),vm=(e,t)=>e-t>=6e5;function Ux(e){let{now:t,lastInputAt:n,fingerprint:o,counts:r,occupied:s,prev:i}=e,a=vm(t,n),c=i.fingerprint!==null&&i.fingerprint!==o?0:i.settled+1,p={...i,fingerprint:o,counts:r,settled:c,awaySince:a?i.awaySince??t:null,spokenBaseline:i.spokenBaseline??r};if(a){let $=$m(p.spokenBaseline,r);return{memory:p,speak:null,waiting:su($)?null:$}}if(s)return{memory:p,speak:null,waiting:null};if(c<2)return{memory:p,speak:null,waiting:null};let m=$m(i.spokenBaseline,r);return su(m)?{memory:p,speak:null,waiting:null}:i.lastSpokeAt!==null&&t-i.lastSpokeAt<6e5?{memory:p,speak:null,waiting:null}:{memory:{...p,spokenBaseline:r,lastSpokeAt:t,settled:c},speak:m,waiting:null}}function Fx(e,t,n){if(e.awaySince===null)return{kind:"none",memory:e};let o=t-e.awaySince,r=$m(e.spokenBaseline,n),s={...e,awaySince:null,counts:n,spokenBaseline:n,lastSpokeAt:su(r)?e.lastSpokeAt:t};return su(r)?{kind:"none",memory:s}:{kind:o>=36e5?"briefing":"delta",memory:s,delta:r,awayMs:o}}function oa(e){let t=[];return e.hints&&t.push(`${e.hints} hint${e.hints===1?"":"s"}`),e.requests&&t.push(`${e.requests} request${e.requests===1?"":"s"}`),e.answers&&t.push(`${e.answers} answer${e.answers===1?"":"s"}`),e.directives&&t.push(`${e.directives} directive${e.directives===1?"":"s"}`),e.briefMoved&&t.push("an updated product brief"),t.length===0?"":t.length===1?t[0]:`${t.slice(0,-1).join(", ")} and ${t.at(-1)}`}function xm(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 Wx(e){return`\u{1F4E5} ${oa(e)} just arrived from your builder \u2014 /catch-up folds ${Mx(e)===1?"it":"them"} into the docs.`}function Bx(e,t){return`\u{1F4E5} While you were away (${xm(t)}): ${oa(e)} from your builder \u2014 /catch-up folds ${Mx(e)===1?"it":"them"} into the docs.`}function Hx(e){return`\u{1F4E5} ${oa(e)} waiting from your builder \xB7 tab to run /catch-up\u2026`}sl();import{publishGateVerdict as fu,publishGateLines as jm,blockedPaths as XU,SKIP_STYLE_FLAG as A0,SKIP_SHOTS_FLAG as QU}from"document360-engine";import{askBuilder as JU,openGapQuestions as ZU}from"document360-engine";import{recordStructureReview as T0}from"document360-engine";import{recordBriefConsumed as eF}from"document360-engine";import{retireArticle as tF,normalizeScope as E0,declineImport as nF,undoDecline as oF}from"document360-engine";import{readReuseProposal as rF}from"document360-engine";import{PRODUCT_NAME as yt,WRITER_COMMAND as N0,CAPTURE_COMMAND as ua,CAPTURE_PACKAGE as mu}from"document360-engine";ae();import{Box as ra,Text as Ye}from"ink";import{PRODUCT_NAME as Gx}from"document360-engine";import{jsx as ze,jsxs as Cs}from"react/jsx-runtime";function LM({row:e,nameW:t,width:n}){let o=s=>dd(s,n),r=(s,i)=>ze(ra,{flexDirection:"column",children:s.map(i)});switch(e.t){case"head":return r(o(e.s),(s,i)=>ze(Ye,{color:pe,bold:!0,children:s},i));case"text":return r(o(e.s),(s,i)=>ze(Ye,{children:s},i));case"dim":return r(o(e.s),(s,i)=>ze(Ye,{dimColor:!0,children:s},i));case"sub":return r(o(e.s),(s,i)=>ze(Ye,{bold:!0,dimColor:!0,children:s},i));case"good":return r(o(e.s),(s,i)=>ze(Ye,{color:"green",children:s},i));case"step":{let s=o(`${e.n}. ${e.s}`);return ze(ra,{flexDirection:"column",children:s.map((i,a)=>a===0?Cs(Ye,{children:[ze(Ye,{color:pe,children:`${e.n}. `}),i.slice(`${e.n}. `.length)]},a):ze(Ye,{children:i},a))})}case"cmd":{let s=Ja(e.name,e.s,t,n),i=s.descLines.slice(s.nameOwnLine?0:1);return Cs(ra,{flexDirection:"column",children:[Cs(Ye,{children:[" ",ze(Ye,{color:pe,children:s.nameCell}),!s.nameOwnLine&&ze(Ye,{dimColor:!0,children:` ${s.descLines[0]??""}`})]}),i.map((a,l)=>ze(Ye,{dimColor:!0,children:`${s.indent}${a}`},l))]})}case"gap":return ze(Ye,{children:" "})}}function qx({tab:e,scroll:t,rows:n,width:o,version:r,engineVersion:s}){let i=Et[e]??Et[0],a=ud(i.rows),l=Math.max(20,o-2),c=6+Et.reduce((A,R)=>A+R.label.length+4,0),p="\u2500".repeat(Math.min(c,l)),m=`\u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 \u2191\u2193 scroll \xB7 esc close \xB7 ${Gx} v${r} \xB7 engine v${s}`,$=hy({rows:n,inner:l,barWidth:c,footerWidth:m.length}),{visible:w,above:C,below:S}=py(i.rows,{width:o,budget:$,scroll:t,nameW:a});return Cs(ra,{flexDirection:"column",paddingX:1,children:[Cs(Ye,{children:[ze(Ye,{color:pe,bold:!0,children:"Help "}),Et.map((A,R)=>R===e?ze(Ye,{color:"white",backgroundColor:pe,bold:!0,children:` ${A.label} `},A.key):ze(Ye,{children:` ${A.label} `},A.key))]}),ze(Ye,{color:pe,children:p}),Cs(ra,{flexDirection:"column",marginTop:1,children:[C>0?ze(Ye,{dimColor:!0,children:`\u22EF ${C} more above`}):null,w.map((A,R)=>ze(LM,{row:A,nameW:a,width:o},C+R)),S>0?ze(Ye,{dimColor:!0,children:`\u22EF ${S} more below`}):null]}),ze(Ye,{dimColor:!0,children:`
|
|
493
|
+
\u2190/\u2192 or tab switch \xB7 1-5 jump${C+S>0?" \xB7 \u2191\u2193 scroll":""} \xB7 esc close \xB7 ${Gx} v${r} \xB7 engine v${s}`})]})}var OM=/^(?:\d+[.)]|[-*•])\s+/;function Vx(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
|
|
494
|
+
`)){let i=s.trim().replace(OM,""),a=i.match(/^`([^`]+)`$/);a&&(i=a[1].trim());let l=i.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!l||!o.has(l[1].toLowerCase()))continue;let c=`/${l[1].toLowerCase()}${l[2]?` ${l[2]}`:""}`;if(r.includes(c)||r.push(c),r.length>=n)break}return r}ae();function yr(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function dt(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function iu(e,t){return e.map(n=>n.label===t?{...n,itemsDone:Math.min((n.itemsDone??0)+1,n.items)}:n)}var _M=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function Rm(e,t,n){if(!_M.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 Sm(e){return e.replace(/^[\w.-]+\//,"")}var au=16,Kx={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function $o(e){return typeof e=="string"?e:e.cmd}function Yx(e){return typeof e=="string"?void 0:e.desc}function Cm(e){return e.trim().split(/\s+/).slice(1).join(" ")}function zx(e,t){let n=Cm(t);return e.some(r=>$o(r).trim()===t.trim()||!!n&&Cm($o(r))===n)?e.filter(r=>$o(r).trim()!==t.trim()&&!(n&&Cm($o(r))===n)):[]}import{isDirectiveMention as sF,stripDirectiveMention as iF,appendDirective as aF,reconcileTestidRequest as lF,builderChannelWired as cF,pendingFingerprint as uF}from"document360-engine";mn();var MM=/\[Pasted text #\d+ \+\d+ lines?\]/g;function Xx(e){return e.replace(/\r\n?/g,`
|
|
495
|
+
`)}function Qx(e){return e.includes(`
|
|
496
|
+
`)||e.length>200}function Jx(e,t){let n=t.split(`
|
|
497
|
+
`).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function Zx(e,t){return e.replace(MM,n=>t.get(n)??n)}function e0(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function lu(e,t){let n=Math.max(1,t),o=[],r=0;for(let s of e.split(`
|
|
498
|
+
`)){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 cu(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function t0(e,t,n){let o=cu(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 n0(e,t,n){let o=e[cu(e,t)];return n==="start"?o.start:o.end}import{WRITER_DIRNAME as UM}from"document360-engine";var FM=new Set(["Edit","Write","MultiEdit","NotebookEdit"]),o0={hint:"hint",message:"message",state:"state file",roadmap:"roadmap",directive:"directives",feedback:"tool-feedback"},WM=new Set(["hint","message","state"]),BM=["hint","message","roadmap","directive","feedback","state"];function HM(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 r0(e,t){let n=e==="Read"?"read":FM.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=`${UM.toLowerCase()}/`,i=r.lastIndexOf(s);if(i<0)return null;let a=HM(r.slice(i+s.length));return a?{category:a,verb:n,path:r}:null}function s0(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 BM)for(let s of["updated","read"]){let i=t.get(`${r}:${s}`)?.size??0;i!==0&&o.push(WM.has(r)?`${i} ${o0[r]}${i===1?"":"s"} ${s}`:`${o0[r]} ${s}`)}return o.length>0?o.join(" \xB7 "):null}function i0(e,t,n){let o=Math.max(1,n),r=e.split(`
|
|
499
499
|
`),s=0;for(let i=r.length-1;i>=0;i--){let a=r[i];if(s+=Math.max(1,Math.ceil(a.length/o)),s>=t){let l=s-t;return{text:[l>0?a.slice(l*o):a,...r.slice(i+1)].join(`
|
|
500
|
-
`),truncated:i>0||l>0}}}return{text:e,truncated:!1}}function
|
|
501
|
-
`)){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
|
|
500
|
+
`),truncated:i>0||l>0}}}return{text:e,truncated:!1}}function a0(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 l0(e){let t=!1,n=0,o=0;for(let r of e.split(`
|
|
501
|
+
`)){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 wr,jsx as Y,jsxs as ke}from"react/jsx-runtime";var dF={project:`${pt}/config.json`,user:"/model",env:"ANTHROPIC_MODEL",auto:"auto \u2014 right-sized for docs \xB7 /model to change"},D0=` 1. /init \u2014 pick your Document360 environment & scaffold config
|
|
502
502
|
2. /login \u2014 sign in & pick your Document360 project (workspace auto-selected)
|
|
503
|
-
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function
|
|
504
|
-
`).length+1,console.log(g)},[
|
|
505
|
-
`)}catch{}h.picker&&(
|
|
506
|
-
`)}),
|
|
507
|
-
I'll install it when you /exit \u2014 your next launch runs it.`});return}f({kind:"note",tone:"info",text:`\u2B06 Updating ${
|
|
508
|
-
${
|
|
509
|
-
Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!
|
|
510
|
-
${
|
|
511
|
-
`)}),
|
|
512
|
-
`)}),k.reopenedForRedaction&&f({kind:"note",tone:"warn",text:
|
|
503
|
+
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function pF(e,t,n,o){let r=Im(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=Lm(e),a=Se(e),l=(a?.docsDir??Om).replace(/\/+$/,""),c=a?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${l}/ + config`,p={version:t,engineVersion:_0,captureVersion:Nt(),claude:s,model:i.model,modelSource:dF[i.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",workspace:null,cwd:e,prod:!1,loggedOut:!0,configured:a!==null,envFix:null,mode:c};if(a===null)return p;try{let m=wt(e,o);p.profile=m.name;let $=Ve(e,o);p.envFix=$?.cmd??null;try{p.apiUrl=m.connection.apiUrl}catch{p.apiUrl=`cannot be reached \u2014 ${$?.cmd??"/profile"}`}p.prod=m.production,p.project=m.project.projectName??m.project.projectId??"(chosen at login)",p.workspace=m.project.workspaceName??m.project.workspaceId??null;let w=vo(m.name,m.project.projectId);if(w){let C={...Ns(w.idToken)??{},...Ns(w.accessToken)??{}},S=C.email??C.preferred_username??"signed in";kr(w)?w.refreshToken&&(p.who=S,p.loggedOut=!1,p.sessionHint="session expired \u2014 refreshing\u2026"):(p.who=S,p.loggedOut=!1,p.sessionHint=`session valid until ${new Date(w.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return p}var hF=e=>e.mode==="local-only"?e.path:e.plan.path;function fF(e,t){try{let n=wt(e,t),o=Ve(e,t);if(o)return{text:`profile "${n.name}" \u2014 cannot reach ${o.name} (${o.cmd})`,prod:!1};let r=vo(n.name,n.project.projectId);if(!r)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let s={...Ns(r.idToken)??{},...Ns(r.accessToken)??{}},i=s.email??s.preferred_username??"signed in";return kr(r)&&!r.refreshToken?{text:`profile "${n.name}" \u2014 session expired (/login)`,prod:n.production}:{text:`${i} \xB7 profile "${n.name}"`,prod:n.production}}catch(n){return{text:n.message.split(".")[0],prod:!1}}}var j0=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],Ds=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],mF="Ask me to write or update an article\u2026",I0=2e3,gF=new Set(or.map(e=>e.name));function Es({ch:e,dim:t}){let[n,o]=me(!0);return mt(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),Y(z,{inverse:n,color:t&&!n?"gray":void 0,children:e})}function zn({rows:e,cursor:t,cap:n,render:o}){let r=eu(e.length,t,n);return ke(wr,{children:[r.above>0?Y(z,{color:"gray",children:` \u22EF ${r.above} more above`}):null,e.slice(r.start,r.end).map((s,i)=>o(s,r.start+i,r.start+i===t)),r.below>0?Y(z,{color:"gray",children:` \u22EF ${r.below} more below`}):null]})}var L0=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function O0(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var yF=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function wF({startTime:e,chars:t}){let[n,o]=me(0),r=de(Date.now());mt(()=>{let c=setInterval(()=>o(p=>p+1),120);return()=>clearInterval(c)},[]);let s=Ds[n%Ds.length],i=j0[Math.floor(n/16)%j0.length],a=Uk(e,r.current,Date.now()),l=Math.round(t/4);return ke(Me,{children:[Y(z,{color:pe,children:` ${s} ${i}\u2026 `}),Y(z,{color:"gray",children:`(${Wn(a)} \xB7 ~${l} tokens \xB7 esc to interrupt)`})]})}function kF({step:e,cmd:t,startedAt:n,spentUsd:o,budgetUsd:r}){let[,s]=me(0);mt(()=>{let l=setInterval(()=>s(c=>c+1),1e3);return()=>clearInterval(l)},[]);let i=Math.max(0,Math.round((Date.now()-n)/1e3)),a=o>0?` \xB7 ${Dt(o)} of ${et(r)}`:` \xB7 limit ${et(r)}`;return ke(Me,{flexDirection:"column",children:[ke(Me,{children:[Y(z,{color:pe,children:` \u23F5\u23F5 auto \xB7 step ${e} \xB7 `}),Y(z,{color:pe,bold:!0,children:t})]}),Y(z,{color:"gray",children:` ${Wn(i)}${a} \xB7 esc stops`})]})}function bF({text:e}){let[t,n]=me(0);return mt(()=>{let o=setInterval(()=>n(r=>r+1),120);return()=>clearInterval(o)},[]),Y(Me,{paddingX:1,children:Y(z,{color:pe,children:`${Ds[t%Ds.length]} ${e}`})})}var $F=12e4;function vF({p:e}){let[t,n]=me(0);mt(()=>{let R=setInterval(()=>n(D=>D+1),150);return()=>clearInterval(R)},[]);let o=Ds[t%Ds.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),i=Math.round(e.chars/4),a=Date.now()-e.lastAt>=$F,l=e.verb??"Converting",c=e.unit??"article",p=e.rows.reduce((R,D)=>R+D.items,0),m=e.rows.reduce((R,D)=>R+(D.status==="done"?D.items:D.itemsDone??0),0),$=l.toLowerCase(),w=e.rows,C=0;if(w.length>au){let R=w.findIndex(W=>W.status==="active"||W.status==="pending"),D=Math.max(0,Math.min(R-2,w.length-au));C=w.slice(0,D).filter(W=>W.status==="done").length,w=w.slice(D,D+au)}let S=Math.min(40,Math.max(...w.map(R=>Sm(R.label).length),0)),A=R=>R==="failed"?"red":R==="active"?pe:void 0;return ke(Me,{flexDirection:"column",children:[ke(Me,{children:[Y(z,{color:pe,children:` ${o} ${l} ${p} ${c}${p===1?"":"s"} `}),Y(z,{color:"gray",children:e.agentless?`\xB7 ${m}/${p} ${c}${p===1?"":"s"} \xB7 ${Wn(r)} \xB7 esc to stop`:`\xB7 ${m}/${p} ${c}${p===1?"":"s"} \xB7 ${e.done}/${e.total} batch${e.total===1?"":"es"} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${i} tokens \xB7 ${Wn(r)} \xB7 esc to stop`})]}),C>0&&Y(z,{dimColor:!0,children:` \u2714 +${C} done`}),w.map(R=>ke(z,{color:A(R.status),dimColor:R.status==="done"||R.status==="pending",children:[` ${Kx[R.status]} ${Sm(R.label).padEnd(S)}`,R.status==="active"&&R.itemsDone!==void 0?` (${R.itemsDone}/${R.items} ${c}${R.items===1?"":"s"})`:R.status!=="pending"?` (${R.items} ${c}${R.items===1?"":"s"})`:"",R.status==="active"?` \u2190 ${$}\u2026`:""]},R.label)),a&&Y(z,{color:"yellow",children:` \u26A0 no activity for ${Wn(s)} \u2014 press esc to stop if it's wedged`}),a&&e.stalledNote?Y(z,{color:"yellow",children:` ${e.stalledNote}`}):null]})}var xF=10800*1e3;function M0({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=qM(),[s,i]=me(n),[a,l]=me(null),[c,p]=me({text:"",pos:0}),m=c.text,$=ce(h=>{p(g=>{let d=typeof h=="function"?h(g.text):h;return{text:d,pos:d.length}})},[]),w=ce(h=>{p(g=>({text:g.text.slice(0,g.pos)+h+g.text.slice(g.pos),pos:g.pos+h.length}))},[]),C=ce(()=>{p(h=>{if(h.pos===0)return h;let g=h.text.slice(0,h.pos),d=e0(g)??g.slice(0,-1);return{text:d+h.text.slice(h.pos),pos:d.length}})},[]),[S,A]=me(!1),[R,D]=me(!1),[W,H]=me(0),[J,G]=me(!1),[K,ne]=me(null),[oe,Re]=me(null),[le,he]=me([]),re=de(!1),ve=de(!1),Ne=de(null),tt=de(!1),[xo,De]=me(!1),Le=de(!1),at=de(0),[hn,Ot]=me(!1),[Ro,So]=me(!1),[br,da]=me(null),[pa,Jt]=me(0),Zt=de(0),[$r,Xn]=me(0),[_t,vr]=me(null),[Sn,Qn]=me(null),xr=de(new Map),ha=de(0),ge=de([]),Pe=de(null);Pe.current===null&&(Pe.current=d0({cwd:e,profileName:s,allowProdWrites:!1}));let Xe=de({uuid:null,firstPrompt:null,titleFired:!1}),Cn=de(new Map),Co=de(null),wu=de(null),fa=de(g0().verboseTranscript===!0),Pn=de(!1),ku=de([]),_e=de([]),An=de([]),en=de([]),Rr=de(null),[Fm,Po]=me(null),bu=de(null),[Tn,Ao]=me(null),[tn,Sr]=me(null),[Mt,Jn]=me(null),[ht,Cr]=me(null),[kt,To]=me(null),[Ut,Pr]=me(null),[nn,Ar]=me(null),[on,Eo]=me(null),[Ft,En]=me(null),[gt,Is]=me(null),Wm=de({value:0,at:0}),Bm=de({value:0,at:0}),Nn=ce((h,g)=>{let{index:d,memory:y}=wm(Bm.current,Number(h),g);return Bm.current=y,d},[]),[Pt,No]=me(null),[Hm,Do]=me(null);mt(()=>Qn(null),[le]);let[Wt,jo]=me(null),[bt,Tr]=me(null),[Gm,$u]=me([]),Io=de([]),Ls=de(!1),Os=de(null),vu=de(null),[Y0,qm]=me(!1),nt=de(null),[$t,ma]=me(null),ga=de(!1),Zn=de(!1),ya=de(!1),xu=de(null),Ru=de(null),[Er,Vm]=me(null),Su=de(null),qe=de(null),[Nr,xe]=me(null),[Km,He]=me(null),_s=de(!1),Ms=de(null),Cu=de(null),Lo=de(null),[Bt,Oo]=me(null),[Us,_o]=me(null),eo=!!($t||Mt||ht||kt||Ut||nn||on||Ft||gt||Pt||Wt||bt||Bt||Us),Fs=uu(()=>{try{return m0(Se(e))}catch{return!1}},[e,W]),Ym=nn?{verb:"publish live",cancel:"leave as drafts",rows:nn.rows.length+1}:Ut?{verb:"push as drafts",rows:Ut.rows.length}:Pt?{verb:"choose it",rows:Pt.rows.length}:on?{verb:"run it",rows:on.rows.length}:Ft?{verb:"open it",cancel:"close",rows:Ft.rows.length-1}:ht?{verb:"switch",rows:ht.rows.length}:kt?{verb:"switch",rows:kt.rows.length}:Mt?{verb:"use it",rows:Mt.rows.length}:tn?{verb:"switch",rows:tn.rows.length,extra:["s this session only"]}:Tn?{verb:"use it",rows:Xt.length}:bt?{verb:"save",multi:!0}:null,[zm,Mo]=me(0),[Ht,Uo]=me(0),[z0,Xm]=me(0),Pu=uu(()=>{try{let h=Lm(e);return h.source==="auto"?`${h.model} (auto)`:h.model}catch{return null}},[e,z0]),{stdout:lt}=KM(),[,X0]=me(0),Qm=de(`${lt.columns??80}x${lt.rows??24}`),Jm=de(lt.columns??80),ct=ce(()=>Math.max(20,(lt.columns??80)-1),[lt]),wa=ce(h=>{ge.current.push(h);let g=Lp(h,ct());Dr.current+=g.split(`
|
|
504
|
+
`).length+1,console.log(g)},[ct]),Au=de([]),ka=ce(()=>{let h=Au.current;if(h.length===0)return;Au.current=[];let g=s0(h);g&&wa({kind:"note",tone:"info",text:`\u25CF Housekeeping ${g}`})},[wa]),f=ce(h=>{ka(),wa(h)},[wa,ka]),vt=de({printed:[],armed:[],printedAt:0}),ba=de(null),$a=de([]),Dr=de(0),va=ce(()=>nt.current!==null,[]),ut=ce((h,g)=>{va()||(at.current++,vt.current.armed=[],ne(h),Re(g??null))},[va]),rn=ce(()=>{at.current++,vt.current.armed=[],ne(null),Re(null)},[]),Ws=ce(h=>{va()||(at.current++,vt.current.armed=[],ne(null),Re(h))},[va]),ue=ce(h=>ut(h,$s({kind:"cmd",cmd:h,reason:""})),[ut]),Dn=ce((h,g)=>{if(!g?.silent&&h.note&&f({kind:"note",tone:g?.tone??h.tone,text:h.note}),!g?.silent&&h.note?.includes(`${pt}/ \u2014 your articles`))try{let E=YU(e);zU(XM(E)),u0(E,`${new Date().toISOString()}
|
|
505
|
+
`)}catch{}h.picker&&(he(h.picker.options.map(E=>({cmd:E.cmd,desc:E.desc}))),Do(h.picker.title),$a.current=h.picker.exclusive?h.picker.options.map(E=>E.cmd.trim()):[]),!g?.silent&&h.note&&(vt.current.printed=h.menu,vt.current.printedAt=Dr.current);let y=Dr.current-vt.current.printedAt<Math.max(8,(lt.rows??24)-4)&&Ev(vt.current.printed,h.menu)?h.menu:[];h.lead?(h.lead.kind==="answer"?Ws($s(h.lead,y.length)):ut(h.lead.kind==="cmd"?h.lead.cmd:h.lead.text,$s(h.lead,y.length)),!g?.silent&&h.note&&(ba.current=xs(h.lead))):!h.picker&&(!g?.silent||h.restKind!==null)&&(rn(),y.length>0&&Ws(h.restKind==="delivered"?`1\u2013${y.length} when you want one \xB7 nothing is owed \xB7 or just ask me anything\u2026`:`1\u2013${y.length} to pick a campaign step \xB7 nothing is waiting \xB7 or just ask me anything\u2026`)),vt.current.armed=y},[f,ut,Ws,e,lt]),je=ce((h,g,d="info")=>{vt.current.armed=[],h&&f({kind:"note",tone:d,text:h}),g&&(g.kind==="answer"?Ws($s(g)):ut(g.kind==="cmd"?g.cmd:g.text,$s(g)),ba.current=h?xs(g):null)},[f,ut,Ws]),jn=ce((h,g,d,y="info")=>{if(h.producedNothing){je("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}h.handedBack||je(g,d,y)},[je]),[to,Tu]=me(null),[Q0,Zm]=me(!1),In=ce((h,g)=>{Tu(h),Zm(!1),f({kind:"note",tone:"info",text:g?.hint??"\u2328 Press \u2303y to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[f]),Eu=ce(()=>{lF(e,new Date().toISOString());let h=Vb(e);h&&(f({kind:"note",tone:"info",text:h.lines.join(`
|
|
506
|
+
`)}),In(h.prompt,cF(e)?{hint:"\u2328 Press \u2303y to copy the request \u2014 only if you want to hand it over now; your builder already has it."}:void 0))},[e,f,In]),xa=de(!1),Nu=ce(async()=>{try{if(xa.current||!UU(MU())||Se(e)?.mode==="engineer")return;let h=await x0({pkg:dr,currentVersion:o,force:!0});if(!h.updateAvailable||!h.latest)return;if(xa.current=!0,vc()){xc(h.latest),f({kind:"note",tone:"info",text:`\u2B06 Update v${h.latest} is ready to install.
|
|
507
|
+
I'll install it when you /exit \u2014 your next launch runs it.`});return}f({kind:"note",tone:"info",text:`\u2B06 Updating ${dr} ${h.current} \u2192 ${h.latest}\u2026 (wait for the \u2713 before you /exit)`}),So(!0);let g=await Gi().finally(()=>So(!1));g.ok?(f({kind:"note",tone:"ok",text:`\u2713 Updated to v${h.latest} \u2014 run /exit, then relaunch to apply.`}),ue("/exit"),da(h.latest)):f({kind:"note",tone:"warn",text:`Update available (v${h.latest}) but auto-update failed. ${Hi(g.output)}`})}catch{}},[e,o,f,ue]),Bs=de(!1),Du=de(null),eg=ce(async h=>{if(!Bs.current)try{let g=Se(e);if(!g)return;let d=tg.current;if(!d)return;if(d.pushConsent!=="on"){if(d.uncommitted===0)return;Bs.current=!0;try{let E=await KU(e,g);if(E.commit?.ok)Du.current=null;else if(E.commit&&!E.commit.ok){let I=`${E.commit.reason}:${E.commit.detail??""}`;Du.current!==I&&(Du.current=I,f({kind:"note",tone:"warn",text:`\u26A0 Couldn't save your docs work to git \u2014 ${wo(E.commit.reason,E.commit.detail)}`}))}}finally{Bs.current=!1}return}if(d.uncommitted===0&&d.unpushed===0&&!h.pull)return;Bs.current=!0;try{let{lines:E,changed:I}=await mc(e,g);for(let O of E)O.tone==="warn"||O.tone==="error"?f({kind:"note",tone:O.tone,text:O.text}):O.text.includes("\u2B07")&&f({kind:"note",tone:O.tone,text:O.text});I&&H(O=>O+1)}finally{Bs.current=!1}}catch{}},[e,f]),Fo=ce(h=>{let g=st(e,s);return g.ok?!0:(f({kind:"note",tone:"warn",text:g.reason}),Lo.current=h,ue(g.fix),Ru.current={what:g.reason,cmd:g.fix},!1)},[e,s,f,ue]),[Hs,ju]=me(null),tg=de(null),ng=de(null),At=ce((h,g)=>{let d=ta(e,s,{claudeMissing:Im(t).state==="missing",allowAutoAudit:h,genreUnknown:tt.current,pendingAnswer:Ne.current,lastCommand:ng.current});return tg.current=d?.handoff??null,d?Zi(d,{header:g,pickable:!0,scaleFor:y=>dn(e,y)}):{kind:"idle"}},[e,s,t]),Iu=de(Date.now()),Gs=de(_x()),og=de(0),[rg,sg]=me(null),qs=de(!0),jr=de(!1),Ra=de(0),Vs=de(0);mt(()=>{let h=setInterval(()=>{if(qs.current){Ra.current=0,Vs.current=0;return}if(!S)try{if(!Ps(R0(e)))return;if(an(e).status==="current"){qs.current=!0,Ra.current=0,Vs.current=0;let d=jr.current?`\u2713 Your builder finished the protocol update (v${Ge}) \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:",y=At(!1,d),E=y.kind==="recommend"?y.rec:null;Tu(null),E?.note?Dn(E,{tone:"ok"}):(f({kind:"note",tone:"ok",text:`${d}${E?.lead?` ${vs(E.lead)}`:""}`}),E?.lead||E?.picker?Dn(E,{silent:!0}):jr.current||ut("write the docs for this repo")),H(I=>I+1);return}if(jr.current)return;Ra.current+=1;let g=Ra.current;if((g===4||g%15===0)&&Vs.current<3){Vs.current+=1;let d=Vs.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";f({kind:"note",tone:"info",text:Un(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${d}`:`\u23F3 Waiting for your builder to run the prompt \u2014 paste it into your coding agent; I'll pick up automatically when it's done.${d}`})}}catch{}},4e3);return()=>clearInterval(h)},[e,S,f,At,Dn,ut]),mt(()=>{let h=Fm??sa(e);if(!S){tu(0),Ss(`${ou} ${h}`);return}tu(3);let g=0;Ss(`${nu[0]} ${h}`);let d=setInterval(()=>{g=(g+1)%nu.length,Ss(`${nu[g]} ${h}`)},400);return()=>clearInterval(d)},[S,e,Fm]),mt(()=>()=>tu(0),[]),mt(()=>{let h=performance.now(),g=[],d=(k,v)=>{let x=performance.now();try{return v()}finally{let b=Math.round(performance.now()-x);b>=80&&g.push(`${k}: ${b}ms`)}};f({kind:"banner",info:d("banner",()=>pF(e,o,t,s))});let y=Im(t).state==="missing";if(y&&f({kind:"note",tone:"warn",text:`\u26A0 Set up Claude first \u2014 ${yt}'s agent runs on Claude Code, and it's not signed in on this machine yet.
|
|
508
|
+
${JM}
|
|
509
|
+
Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!Se(e)){f({kind:"note",tone:"info",text:`Welcome! This repo isn't set up for ${yt} yet \u2014 three steps and you're writing docs:
|
|
510
|
+
${D0}`}),ue(y?"/doctor":"/init");return}y&&ue("/doctor");try{let k=wt(e,s);k.project.projectId&&aU(k.name,k.project.projectId,k.project.projectName);let v=vo(k.name,k.project.projectId),x=st(e,s);v&&kr(v)&&v.refreshToken?nU({profile:k.name,connection:k.connection,projectId:k.project.projectId,projectName:k.project.projectName}).then(()=>{f({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),H(b=>b+1)}).catch(b=>{if(b instanceof oU&&b.transient){f({kind:"note",tone:"warn",text:"Couldn't reach Document360 to renew your session \u2014 your sign-in is intact, and I'll try again on your next command."});return}f({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 sign in again with /login."}),ue("/login"),H(P=>P+1)}):x.ok||(f({kind:"note",tone:"warn",text:x.reason}),ue(x.fix))}catch{}try{let k=Se(e),v=wt(e,s),x=vo(v.name,v.project.projectId);k&&x&&!kr(x)&&am(e,k.authoritativeSourceFiles)&&!lm(e,s)&&(f({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),ue("/scope"))}catch{}try{let k=d("resolve-genre",()=>kU(e));k.persisted&&k.appType?f({kind:"note",tone:"ok",text:`\u2713 Detected a ${k.appType} app \u2014 enabled the ${k.appType}-doc-playbook (change with /genre, or edit ${pt}/config.json).`}):k.source==="unknown"&&Se(e)&&(tt.current=!0)}catch{}let E=an(e);try{if(d("reconcile-devhints",()=>el(e)),E.status!=="current"&&!Un(e)){let k=tl(e);k.length&&(f({kind:"note",tone:"warn",text:k.join(`
|
|
511
|
+
`)}),In(zo()),qs.current=!1,jr.current=!1)}}catch{}try{let k=d("reconcile-feedback",()=>FU(e));k.archived>0&&f({kind:"note",tone:"ok",text:`\u2713 Tidied ${k.archived} resolved item${k.archived===1?"":"s"} from your tool feedback (now fixed in ${yt}) \u2192 moved to ${pt}/tool-feedback-archived.md${k.open>0?`; ${k.open} still open`:""}.`})}catch{}try{let k=d("upgrade-actions",()=>WU(e));k.applied.length>0&&f({kind:"note",tone:"warn",text:za(k.applied).join(`
|
|
512
|
+
`)}),k.reopenedForRedaction&&f({kind:"note",tone:"warn",text:Xa(k.reopenedForRedaction)})}catch{}let I=d("ready-decision",()=>At(!0));I.kind==="autoAudit"?(f({kind:"note",tone:"info",text:I.note}),gi({cwd:e,profileName:s}).then(k=>{if(k.kind==="audit-blocked"){je(k.note,{kind:"cmd",cmd:k.lead.cmd,reason:k.lead.reason},"warn");return}k.kind!=="forward-to-agent"||!k.prompt||Te(k.prompt,{display:k.display,quietUser:!0}).then(v=>{if(v.producedNothing)return;let x=Ml(e,s);if(x){je(x.note,{kind:"cmd",cmd:ts.cmd,reason:ts.reason},"warn"),H(b=>b+1);return}Qi(e,s),H(b=>b+1)})})):I.kind==="recommend"&&Dn(I.rec);let O=Math.round(performance.now()-h);O>=800&&VU({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${O}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${g.length?g.join(`
|
|
513
513
|
`):"no single phase \u226580ms"}
|
|
514
|
-
cwd: ${e}`}),
|
|
515
|
-
|
|
516
|
-
${N}`)}catch{}g?.quietUser||f({kind:"user",text:g?.echoDisplay&&g.display?g.display:h});let y=
|
|
517
|
-
`)}),
|
|
518
|
-
`)}),x||(O={retryable:N.failed.filter(se=>!se.refused).length,stopped:!!N.stopped,paths:N.failed.map(se=>se.path)});let q=
|
|
519
|
-
`)}),[f]),
|
|
520
|
-
`)});let _=E.stop();if(
|
|
521
|
-
`)}),
|
|
522
|
-
`)}),
|
|
523
|
-
`)}),
|
|
524
|
-
`)}),y.blocked.length>0){let I=
|
|
525
|
-
`):`${
|
|
514
|
+
cwd: ${e}`}),Nu(),eg({pull:!0})},[]),mt(()=>{let h=setInterval(()=>{Nu()},xF);return()=>clearInterval(h)},[Nu]),mt(()=>{let h=setInterval(()=>{try{let g=Date.now(),d=vm(g,Iu.current);if(og.current+=1,d&&og.current%Math.round(3e5/6e4)!==0)return;let y=uF(e),E=Gs.current,I=y===E.fingerprint&&E.counts?E.counts:un(e),O=Ux({now:g,lastInputAt:Iu.current,fingerprint:y,counts:I,occupied:S||J||le.length>0||m!==""||eo||_e.current.length>0,prev:E});if(Gs.current=O.memory,sg(O.waiting),O.speak&&nt.current===null){f({kind:"note",tone:"info",text:Wx(O.speak)});let k=At(!1);k.kind==="recommend"&&Dn(k.rec,{silent:!0})}}catch{}},6e4);return()=>clearInterval(h)},[e,S,J,le.length,m,eo,f,At,Dn]),mt(()=>{if(S||J||re.current||Fs&&!Zn.current||K!==null||le.length>0||m!==""||to!==null||_e.current.length>0||Rr.current||eo)return;let h=At(!1);if(h.kind==="recommend"&&(h.rec.lead||h.rec.picker||h.rec.menu.length>0)){Dn(h.rec,{silent:!0});let g=h.rec.lead,d=g?xs(g):h.rec.restKind?`rest:${h.rec.restKind}`:null;d&&d!==ba.current&&(ba.current=d,h.rec.settled&&f({kind:"note",tone:"ok",text:h.rec.settled}),g&&f({kind:"note",tone:"info",text:vs(g)}))}eg({pull:!1})},[S,J,K,le,m,to,eo,W,At,xo]);let Ks=ce((h,g)=>{let d=nt.current;if(nt.current=null,ga.current=!1,ya.current=!1,!d)return;Ix.has(h.kind)&&(Zn.current=!0);let y=Math.max(0,Math.round((Date.now()-d.startedAt)/1e3)),E={ran:d.ran,parked:[...g,...d.blocked],spentUsd:Math.max(0,Ht-d.stepStartedSpend),budgetUsd:pu(Se(e)),seconds:y,reason:h,failed:d.failed};for(let O of Px(E))f({kind:"note",tone:O.tone,text:O.text});try{let O=new Date().toISOString().replace(/[:.]/g,"-"),k=ia(e,pt,"auto-runs");zM(k,{recursive:!0}),u0(ia(k,`${O}.md`),Ax(E,new Date().toISOString()),"utf8")}catch{}let I=g.find(O=>O.cmd)?.cmd;I&&ue(I),Vm(null),H(O=>O+1)},[e,f,Ht,ue]);mt(()=>{if(!Fs||Zn.current||ya.current||S||J||le.length>0||m!==""||to!==null||_e.current.length>0||Rr.current||eo)return;let h=nt.current;if(h?.stopping){Ks({kind:"stopped",how:"manual"},h.parked);return}let g=At(!1);if(g.kind!=="recommend")return;let d=h??{ran:[],parked:[],spentUsd:0,startedAt:Date.now(),stopping:!1,stepStartedSpend:Ht,blocked:[],failed:[]},y=Ru.current;if(Ru.current=null,y){d.blocked.some(x=>x.cmd===y.cmd)||d.blocked.push(y);let v=d.ran[d.ran.length-1];v&&!d.failed.includes(v)&&d.failed.push(v)}let E=Su.current,I=Lx(g.rec,{ran:d.ran,parked:d.parked,spentUsd:Math.max(0,Ht-d.stepStartedSpend),...d.ran.length>0?{lastLeadKey:d.ran[d.ran.length-1]??null}:{},...E?{lastClosedItsTarget:ln(E)}:{}},{budgetUsd:pu(Se(e))});if(I.kind==="stop"){if(!h&&I.reason.kind!=="onlyBlocked")return;if(!h){let v=g.rec.lead?xs(g.rec.lead):"blocked";if(xu.current===v)return;xu.current=v}nt.current=d,Ks(I.reason,I.parked);return}if(!ga.current){let v=pu(Se(e)),x=_=>{try{return _()}catch{return null}},b=I.kind==="run"?I.cmd:`\u201C${I.text}\u201D`,P=I.kind==="run"?x(()=>E$(e,I.cmd)):null,T=I.kind==="run"?x(()=>Ox(g.rec,I.cmd,_=>dn(e,_)))??[]:[];ma({firstCmd:b,scale:I.kind==="run"?x(()=>dn(e,I.cmd)):null,upcoming:T,budgetUsd:v,overBudget:P!==null&&P>v});return}let O=I.kind==="run"?I.cmd:I.text;d.parked=I.parked,d.ran=[...d.ran,O],nt.current=d,Su.current=null,f({kind:"block",text:Z(te("\u25B6",`Auto mode, step ${d.ran.length}: ${O}`))}),Vm({step:d.ran.length,cmd:O,startedAt:d.startedAt,spentUsd:Math.max(0,Ht-d.stepStartedSpend),budgetUsd:pu(Se(e))}),xu.current=null,ya.current=!0,G(!0),(I.kind==="run"?Ho(I.cmd):Te(I.text,{display:I.text,quietUser:!0}).then(()=>{})).finally(()=>{ya.current=!1,G(!1)})},[Fs,S,J,le,m,to,eo,W,At,Ks]),mt(()=>{let h=null,g=null,d=()=>{h&&clearTimeout(h),h=setTimeout(()=>{h=null;let y=lt.columns??80,E=`${y}x${lt.rows??24}`;if(E===Qm.current)return;let I=y<(Jm.current??y);Qm.current=E,Jm.current=y,X0(O=>O+1),I&&(g&&clearTimeout(g),g=setTimeout(()=>{g=null;let O=Math.max(8,(lt.rows??24)-2);console.log("\x1B[?2026h\x1B[H\x1B[2J"+Fk(ge.current,ct(),O)+"\x1B[?2026l")},80))},400)};return lt.on("resize",d),()=>{h&&clearTimeout(h),g&&clearTimeout(g),lt.off("resize",d)}},[lt,ct]);let xt=Math.max(20,(lt.columns??80)-1),ig=uu(()=>fF(e,s),[e,s,W]),Lu=(()=>{if(Ro)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(br!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${br?` v${br}`:""}\u2026`,isSetup:!0};if(Ym)return{text:yx(Ym),isSetup:!0};if(Hs)return{text:`\u{1F6E0} press \u2303y to copy the ${yt} feedback \u2014 then send it to the team (Teams / Slack / email)\u2026`,isSetup:!0};if(to)return Q0?{text:"\u2713 copied \u2014 paste it into your coding agent \xB7 I\u2019ll pick up automatically when it finishes\u2026",isSetup:!0}:{text:"\u2328 press \u2303y to copy the prompt \u2014 then paste it into your coding agent\u2026",isSetup:!0};if(rg)return{text:Hx(rg),isSetup:!0};if(_e.current.length>0){let y=_e.current.length,E=_e.current[0].mode;return E==="local-only"?{text:"l publish yours over the portal \xB7 s skip \xB7 anything else cancels\u2026",isSetup:!0}:E==="conflict"?{text:y>1?`l keep local \xB7 p take portal \xB7 s skip \xB7 la/pa/sa for all ${y}\u2026`:"l keep local \xB7 p take portal \xB7 s skip \xB7 anything else cancels\u2026",isSetup:!0}:{text:y>1?`y to write \xB7 n to skip \xB7 ya/na for all ${y}\u2026`:"y to write \xB7 n to skip \xB7 anything else cancels\u2026",isSetup:!0}}let h=Se(e);if(!h)return{text:"Run /init to set up this repo (or /help)\u2026",isSetup:!0};let g=ia(e,(h.docsDir??Om).replace(/\/+$/,"")),d=(()=>{try{return Ps(g)&&YM(g).length>0}catch{return!1}})();try{let y=wt(e,s),E=Ve(e,s);if(E)return{text:`This repo cannot reach ${E.name} \u2014 ${E.cmd} picks where it publishes\u2026`,isSetup:!0};let I=vo(y.name,y.project.projectId);if(!(!!I&&!(kr(I)&&!I.refreshToken)))return{text:`Sign in with /login (profile "${y.name}")\u2026`,isSetup:!0};if(!y.project.projectId)return{text:"Sign in to Document360 to pick your project\u2026",isSetup:!0};if(!y.project.workspaceId&&!d)return{text:"Pick a workspace with /workspace\u2026",isSetup:!0}}catch{}return d?{text:mF,isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),Ln=Tk(m),Ou=Ln.length>0&&!S,J0=12,fn=ym(lt.rows),Z0=lt.rows??24,ag=ym(lt.rows,{max:J0}),Sa=Math.min($r,Math.max(0,Ln.length-1)),Wo=eu(Ln.length,Sa,ag).start,_u=Ln.slice(Wo,Wo+ag),Mu=a!==null?i0(a,8,xt):null,Ca=Wt?Wt.paths.filter(h=>!Wt.query||h.toLowerCase().includes(Wt.query.toLowerCase())).slice(0,8):[],Pa=Bt?Bt.sessions.filter(h=>{let g=Bt.query.toLowerCase();return!g||h.name.toLowerCase().includes(g)||h.firstPrompt.toLowerCase().includes(g)}).slice(0,8):[],Qe=ce((h,g)=>{Pe.current?.close(),Pe.current=d0({cwd:e,resume:h,profileName:g??s,allowProdWrites:Pn.current}),h||(Xe.current={uuid:null,firstPrompt:null,titleFired:!1},Po(null)),Mo(0),Uo(0)},[e,s]),lg=ce((h,g,d)=>{if(L0.test(h))try{let y=wt(e,s),E=typeof g.project_id=="string"&&g.project_id||y.project.projectId,I=zc(g,d),O=[],k=Jc(g,d),v=k?`${k} \u2014 `:"",x=Xc(d);h.endsWith("publish_article")&&x&&O.push(`${v}Live: ${x}`);let b=Qc(d);b?O.push(`${v}Preview: ${b}`):I&&E&&O.push(`${v}Preview: ${Yc(y.connection.portalUrl,E,I,y.project.languageCode??"en")}`),O.length>0&&f({kind:"link",lines:O})}catch{}},[e,s,f]),Te=ce(async(h,g)=>{Ot(!0),re.current=!1,ve.current=!1,Ne.current=null,rn(),he([]),Do(null),Tu(null);let d=at.current;if(g?.display?.startsWith("/"))try{let N=Pl(e,g.display);N&&(h=`${h}
|
|
515
|
+
|
|
516
|
+
${N}`)}catch{}g?.quietUser||f({kind:"user",text:g?.echoDisplay&&g.display?g.display:h});let y=Xe.current;y.firstPrompt||(y.firstPrompt=g?.display??h),Zt.current=Date.now(),Jt(0),A(!0),Cn.current.clear(),wu.current=null;let E="",I=!1,O=!1,k=!1,v=!1,x="",b={num:0,closed:!1,cueSeen:!1},P=null,T=()=>{P||(P=setTimeout(()=>{P=null,l(x.length>0?x:null)},60))},_=()=>{P&&clearTimeout(P),P=null,l(null)},M=(N=!1)=>{let{head:X,keep:j}=a0(x,N);X.trim()&&f({kind:"assistant",text:gm(X.trimEnd(),b)}),x=j,_()};try{for await(let N of Pe.current.send(h))if(N.type==="session"){if(!y.uuid){y.uuid=N.sessionId;let X=new Date().toISOString(),j=bu.current,B=j??dU(y.firstPrompt??"session");pU({uuid:N.sessionId,name:B,renamed:!!j,titled:!1,cwd:e,firstPrompt:y.firstPrompt??"",createdAt:X,updatedAt:X}),Po(B),bu.current=null}}else if(N.type==="text"){x+=N.delta,E+=N.delta;let X=l0(x);if(X>0){let j=x.slice(0,X).trimEnd();j&&f({kind:"assistant",text:gm(j,b)}),x=x.slice(X)}T(),Jt(j=>j+N.delta.length)}else if(N.type==="tool"){I=!0,L0.test(N.name)&&(O=!0);let j=($e=>typeof $e=="string"&&$e?$e.replace(/\\/g,"/").toLowerCase():null)(N.input.file_path??N.input.notebook_path),B=["Edit","Write","MultiEdit","NotebookEdit"].includes(N.name),q=N.name==="Read"&&j!==null&&j===Co.current;Co.current=B?j:null;let se=fa.current,ye=se?null:r0(N.name,N.input),we=se?null:Gc(N.name,N.input,e,s);if(ye)Au.current.push(ye);else if(we){M();let $e=we.repeat&&we.articleKey&&we.articleKey===wu.current?we.repeat:we;wu.current=we.articleKey??null,f({kind:"doc",verb:we.verb,title:$e.title,category:$e.category,note:$e.note,...we.loud?{loud:we.loud}:{}}),Cn.current.set(N.id,{name:N.name,input:N.input,doc:!0,keepResult:we.keepResult})}else if(q)M(),f({kind:"tool",title:"Read",sep:"",arg:"re-checking the file it just edited"});else{let $e=Vc(N.name,N.input,e);$e&&(M(),f({kind:"tool",title:$e.title,sep:$e.sep,arg:$e.arg}),Cn.current.set(N.id,{name:N.name,input:N.input}))}}else if(N.type==="article_diff"){let X=Yt(N.oldContent,N.newContent,ct());X&&(M(),f({kind:"diff",added:X.added,removed:X.removed,lines:X.lines,hidden:X.hidden}))}else if(N.type==="gate_blocked")Cu.current={path:N.path,commands:N.commands};else if(N.type==="tool_result"){N.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(N.output)&&(_s.current=!0);let X=Cn.current.get(N.id);if(X){Cn.current.delete(N.id),M();let B=X.doc&&!X.keepResult&&!N.isError?{lines:[],hidden:0}:Kc(N.output,4,N.isError||fa.current?void 0:X.name,X.input),q=N.isError&&wx(X.name,N.output);B.lines.length>0&&f({kind:"tool-result",lines:B.lines,hidden:B.hidden,isError:N.isError&&!q}),N.isError||lg(X.name,X.input,N.output)}}else if(N.type==="result"){M(!0),Mo(q=>q+N.outputTokens),Uo(q=>Math.max(q,N.sessionCostUsd));let X=N.inputTokens+N.cacheReadTokens+N.cacheCreationTokens;if(f({kind:"done",seconds:Math.round((Date.now()-Zt.current)/1e3),tokens:N.outputTokens,costUsd:N.costUsd,sessionCostUsd:Math.max(Ht,N.sessionCostUsd),ok:N.ok,...X>0?{inTokens:X,cachedPct:Math.round(N.cacheReadTokens/X*100)}:{}}),!k&&!I&&!E.trim()&&!Ls.current&&(v=!0,f({kind:"note",tone:"warn",text:"The agent produced no output \u2014 nothing ran this turn. Run /doctor: it runs a real turn with your skills and tools and reports what failed. Claude Code\u2019s own error was written either way \u2014 /logs shows it, and offers to copy it for the team."})),N.ok&&(E.includes("\u{1F6E0}")||E.includes(`\u{1F4E3} Feedback for the ${yt} developers`)))try{let q=S0(e);if(Ps(q)){let se=du(q,"utf8").trim();se&&(ju(se),f({kind:"note",tone:"info",text:`\u{1F6E0} Press \u2303y to copy this feedback \u2014 send it to the ${yt} team (Teams / Slack / email).`}))}}catch{}let j=N.ok?px(E):null;ve.current=j!==null,Ne.current=j;let B=N.ok?hx(E,gF):null;if(B)De(!1),Le.current=!1,he(B);else if(N.ok&&(b.cueSeen||(j?.options??0)>=2))De(!0),Le.current=!0,he([]);else if(j)he([]);else{let q=N.ok?Vx(E,or.map(se=>se.name)):[];if(q.length>0)ue(q[0]);else if(N.ok&&E.trim()&&!ve.current){let se=At(!1);se.kind==="recommend"&&(se.rec.lead||se.rec.picker)||gU(h,E,e).then(ye=>{ye&&at.current===d&&ut(ye)}).catch(()=>{})}}if(y.uuid&&(Pm(y.uuid),!y.titleFired)){y.titleFired=!0;let q=y.uuid,se=y.firstPrompt;se&&h0(se,e).then(ye=>{ye&&(uU(q,ye),Po(ye))}).catch(()=>{})}}else N.type==="error"&&(M(!0),k=!0,N.kind==="auth"&&(_s.current=!0),f(N.kind==="limit"?{kind:"note",text:`\u23F3 ${N.message}`,tone:"warn"}:{kind:"note",text:`agent error: ${N.message}`,tone:"error"}),N.note&&f({kind:"note",text:N.note,tone:"info"}))}finally{if(A(!1),_(),ka(),O)try{let X=Dm(await Nm({cwd:e,profileName:s,onRateLimit:j=>He(`Document360 rate limit \u2014 waiting ${Math.ceil(j.waitMs/1e3)}s\u2026`)}));X&&f({kind:"note",tone:X.startsWith("\u26A0")?"warn":"info",text:X})}catch{}finally{He(null)}H(X=>X+1),Xe.current.uuid&&vx(e,Xe.current.uuid,ge.current),_s.current?(_s.current=!1,Ms.current=g?.display??h,ut("/login","\u21E5 tab to run /login \u2014 then I\u2019ll re-send your last prompt\u2026")):Ms.current=null;let N=Cu.current;if(Cu.current=null,N&&!_s.current&&N.commands.length>0){let X=N.commands[0],j=N.commands.length>1?` \u2014 then ${N.commands[1].split(" ")[0]} for the style errors`:"";ut(X,`\u21E5 tab to run ${X.split(" ")[0]}${j}`)}Ls.current&&(Ls.current=!1,Io.current.length>0&&(f({kind:"note",tone:"info",text:`(${Io.current.length} queued message(s) discarded)`}),Io.current=[],$u([])),f({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}return{producedNothing:v,handedBack:Ne.current!==null}},[e,f,lg,ct,ut,ue,rn,At,ka]),Aa=ce(async()=>{try{He("Checking Document360 for new reviewer comments\u2026"),await kc(e,s,{onProgress:(h,g)=>He(`Checking Document360 for new reviewer comments\u2026 ${h}/${g}`)})}catch{}finally{He(null)}},[e,s]),Tt=ce(async(h,g=0,d)=>{let y=fu(e,h,{allowUnreviewed:d?.skipReview===!0,allowStyleErrors:d?.skipStyle===!0});if(!y.clear){f({kind:"note",tone:"warn",text:jm(y,h.length,{act:"push"}).join(`
|
|
517
|
+
`)}),ue(hi(y));return}Zt.current=Date.now(),Jt(0),A(!0);let E=new AbortController;qe.current=E;let I={aborted:!1,partitions:0,failed:0,notRun:0,producedNothing:!0},O={retryable:0,stopped:!1,paths:[]},k=async(v,x)=>{let b=Am(v),P=new Map;for(let se of b)for(let ye of se.paths)P.set(ye,se.label);let T=new Map(b.map(se=>[se.label,se.paths.length])),_=new Set,M=Date.now();xe({verb:"Pushing",unit:"article",total:v.length,done:0,active:[],rows:yr(b),tools:0,chars:0,lastAt:Date.now(),startedAt:M,agentless:!0}),f({kind:"note",tone:"info",text:x?`Resolving cross-links in ${v.length} article${v.length===1?"":"s"} whose targets were saved this run (second pass)\u2026 (esc to stop)`:`Pushing ${v.length} article${v.length===1?"":"s"} to Document360 (${AU} at a time)\u2026 (esc to stop)`});let N=await CU({cwd:e,profileName:s,paths:v,...d?.allowUnpullable===!0?{allowUnpullable:!0}:{},signal:E.signal,onEvent:se=>{let ye=se.type==="article_done"?se.result.path:se.type==="article_failed"?se.failure.path:se.path,we=P.get(ye);if(!we)return;if(se.type==="article_start"){xe(ee=>ee&&!ee.active.includes(we)?{...ee,active:[...ee.active,we],rows:dt(ee.rows,we,"active"),lastAt:Date.now()}:ee&&{...ee,lastAt:Date.now()});return}se.type==="article_failed"&&_.add(we);let $e=(T.get(we)??1)-1;T.set(we,$e),xe(ee=>{if(!ee)return ee;let Ae={...ee,done:ee.done+1,rows:iu(ee.rows,we),lastAt:Date.now()};return $e>0?Ae:{...Ae,active:Ae.active.filter(Ue=>Ue!==we),rows:dt(Ae.rows,we,_.has(we)?"failed":"done")}})}}),X=N.aborted||!!N.stopped,j=ep(e,v,s);x||(I={aborted:X,partitions:b.length,failed:N.failed.length,notRun:N.notRun.length,producedNothing:N.pushed.length===0,verifiedComplete:j>=v.length,leftBehind:g});let B=N.pushed.length>0;f({kind:"note",tone:X||N.failed.length>0||!B?"warn":"ok",text:(X?"Stopped. ":"")+tp(N,{recorded:j,elapsedMs:Date.now()-M,docsRoot:GU(e),...x?{}:{conflictsSkipped:g,unreadableSkipped:d?.unreadableSkipped??0},...d?.scope?{scope:d.scope}:{}}).join(`
|
|
518
|
+
`)}),x||(O={retryable:N.failed.filter(se=>!se.refused).length,stopped:!!N.stopped,paths:N.failed.map(se=>se.path)});let q=Zd(e,s);if(q&&f({kind:"note",tone:"info",text:q}),B){let se=es(e,s);se&&f({kind:"note",tone:"info",text:se})}if(!X&&B){try{let ye=await Nm({cwd:e,profileName:s,onRateLimit:$e=>He(`Document360 rate limit \u2014 waiting ${Math.ceil($e.waitMs/1e3)}s\u2026`)}),we=Dm(ye);we?f({kind:"note",tone:we.startsWith("\u26A0")?"warn":"info",text:we}):ye.skipped&&f({kind:"note",tone:"warn",text:`Order sync skipped: ${ye.skipped}`})}catch(ye){f({kind:"note",tone:"warn",text:`Order sync failed: ${ye.message}`})}finally{He(null)}try{let ye=P0(await C0({cwd:e,profileName:s}));ye&&f({kind:"note",tone:"info",text:ye})}catch(ye){f({kind:"note",tone:"warn",text:`Related-articles sync failed: ${ye.message}`})}let se=await di(e,s);se&&f({kind:"note",tone:"info",text:se})}return X};try{let v=await k(h,!1);if(!v){let b=await np(e,s,h,O.paths);b.length>0&&await k(b,!0),On(d?.scope?`/push ${d.scope}`:"/push --all",I)}let x=Ee("/push",d?.scope?"":"--all",d?.scope);if(O.retryable>0)je(null,{kind:"cmd",cmd:x,reason:O.stopped?"Document360 stopped answering \u2014 your articles are unchanged, so this picks up where the run left off":`${O.retryable} article${O.retryable===1?"":"s"} could not be saved \u2014 this retries them`},"warn");else if(!v&&g>0)je(null,{kind:"cmd",cmd:"/resolve",reason:`${g} conflict${g===1?"":"s"} still need settling \u2014 they were left untouched`},"warn");else if(!v){let b=Jd(e,{scope:d?.scope,profileName:s});b&&je(null,{kind:"cmd",...b})}}catch(v){f({kind:"note",tone:"error",text:`Publish run failed: ${v.message}`})}finally{qe.current=null,xe(null),await Aa(),A(!1),H(v=>v+1)}},[e,s,f,t,je,Aa]),Ir=ce(h=>f({kind:"block",text:h.join(`
|
|
519
|
+
`)}),[f]),cg=ce(async()=>{let h=Hs!=null,g=Hs??to;if(!g){f({kind:"note",tone:"info",text:`Nothing is waiting to be copied. /feedback copies this repo\u2019s open ${yt} feedback anytime.`});return}let d=await cx(g,h?"feedback":"handoff-prompt");f({kind:"note",tone:d.copied?"ok":"warn",text:d.copied?h?`\u2713 Copied the feedback to your clipboard \u2014 send it to the ${yt} team (Teams / Slack / email).`:"\u2713 Copied the prompt to your clipboard \u2014 paste it into your repo's coding agent.":d.path?`Couldn\u2019t reach your clipboard, so the text is in ${d.path} \u2014 open that and copy it from there.`:"Couldn\u2019t reach your clipboard, and could not save the text either. /logs has the details."}),d.copied&&h&&ju(null),d.copied&&!h&&Zm(!0)},[Hs,to,f]),Lr=ce((h,g,d,y,E)=>{let I=zt(h,g,d,Date.now(),E);f({kind:"done",seconds:I.seconds,tokens:I.outputTokens,costUsd:I.costUsd,ok:y,...I.activeSeconds!==void 0?{activeSeconds:I.activeSeconds}:{},sessionCostUsd:Ht+d,...I.inputTokens>0?{inTokens:I.inputTokens,...I.cachedPct!==void 0?{cachedPct:I.cachedPct}:{}}:{}})},[f,Ht]),Ta=ce(async h=>{let g=ca(e,"standard");Zt.current=Date.now(),Jt(0),A(!0);let d=new AbortController;qe.current=d;let y=Date.now(),E=new os;E.start(),xe({verb:h.verb,unit:"article",total:h.partitions.length,done:0,active:[],rows:yr(h.partitions),tools:0,chars:0,lastAt:Date.now(),startedAt:y}),f({kind:"note",tone:"info",text:`${h.headline} on ${g.model}\u2026 (esc to stop)`});let I=!0,O=[],k=!1,v={aborted:!1,partitions:0,failed:0,notRun:0,producedNothing:!0},x=new Set;try{for await(let b of la({cwd:e,partitions:h.partitions,promptFor:h.promptFor,concurrency:h.concurrency,profileName:s,allowProdWrites:Pn.current,model:g.model,signal:d.signal,scope:h.scope}))if(b.type==="partition_status")b.status==="running"?xe(P=>P&&{...P,active:[...P.active,b.label],rows:dt(P.rows,b.label,"active"),lastAt:Date.now()}):xe(P=>P&&{...P,active:P.active.filter(T=>T!==b.label),done:P.done+1,rows:dt(P.rows,b.label,b.status==="done"?"done":"failed"),lastAt:Date.now()});else if(b.type==="partition_stalled"){let P=Rs(b);xe(T=>T&&P?{...T,stalledNote:P}:T)}else if(b.type==="partition_event"){let P=null;if(b.event.type==="tool"){let T=Rm(b.event.name,b.event.input,h.partitions[b.index]?.paths??[]);T&&!x.has(T)&&(x.add(T),P=b.label)}xe(T=>{if(!T)return T;let _={...T,lastAt:Date.now()};return b.event.type==="tool"?_.tools=T.tools+1:b.event.type==="text"&&(_.chars=T.chars+b.event.delta.length),P&&(_.rows=iu(_.rows,P)),_})}else if(b.type==="run_done"){Uo(M=>M+b.totalCostUsd),Mo(M=>M+b.results.reduce((N,X)=>N+X.outputTokens,0));let P=Tm(h.partitions,b.results);I=!!b.allEmpty||!!b.blocked,k=!!b.aborted,v={aborted:!!b.aborted,partitions:h.partitions.length,failed:P.failed.length,notRun:P.notRun.length,...b.blocked?{blocked:b.blocked}:{},...b.allEmpty?{allEmpty:!0}:{},...b.bailedEmpty?{bailedEmpty:!0}:{}};let T=[`${b.aborted?"Stopped. ":""}${b.results.length-P.failed.length}/${h.partitions.length} batches ${h.doneNoun}.`,...P.failed.length?[`\u26A0 ${P.failed.length} not ${h.doneNoun} \u2014 their articles are unchanged: ${P.failed.map(M=>M.label).join(", ")}`]:[],...P.notRun.length?[`\u26A0 ${P.notRun.length} batch${P.notRun.length===1?"":"es"} never started \u2014 their articles are untouched.`]:[],...b.blocked?[`\u26A0 ${b.blocked}`]:[],...b.allEmpty?[h.emptyNote??"\u26A0 No turn produced any work this run \u2014 nothing was changed."]:[],...h.caveatLines??[]];f({kind:"note",tone:b.aborted||P.failed.length||P.notRun.length||b.blocked||b.allEmpty?"warn":"ok",text:T.join(`
|
|
520
|
+
`)});let _=E.stop();if(Lr(y,b.results,b.totalCostUsd,!k&&!I&&!P.failed.length,_.activeSeconds),h.calibrateAs){let M=b.results.filter(N=>N.ok).length;SU(e,h.calibrateAs,{articles:P.covered.length,waves:Math.ceil(M/Math.max(1,h.concurrency)),seconds:_.activeSeconds,costUsd:b.totalCostUsd})}I||(O=P.covered)}}catch(b){f({kind:"note",tone:"error",text:`${h.verb} failed: ${b.message}`})}finally{E.stop(),qe.current=null,xe(null),A(!1),H(b=>b+1)}return{producedNothing:I,covered:O,aborted:k,outcome:v}},[e,s,f,Lr]),eR=ce(async(h,g,d,y=!1)=>{let E=await Ta({partitions:h.partitions,promptFor:h.promptFor,concurrency:ko,verb:"Reviewing",doneNoun:"reviewed",headline:`Reviewing ${h.articles} article${h.articles===1?"":"s"} in ${h.partitions.length} batches (\u2264${ko} editors at once)${g?", applying fixes as they go":", report only"}`+(()=>{let O=Tc(e,"/review",h.articles,h.partitions.length);return O?` \xB7 ${O}`:""})(),caveatLines:Of(h,y),emptyNote:"\u26A0 No editor produced any work this run \u2014 nothing was reviewed or changed.",calibrateAs:"/review",scope:"review"}),I=null;if(g&&E.covered.length>0&&(I=pr(e,E.covered,d,s),I.earned.length>0))try{Ts(e,I.earned,St("review"))}catch{}return{producedNothing:E.producedNothing,aborted:E.aborted,outcome:E.outcome,evidence:I}},[e,Ta]),Uu=ce(async(h,g)=>{if(h.length===0)return;let d=h.reduce((x,b)=>x+b.threads.length,0),y=new Map,E=h.map(x=>(y.set(x.label,x),{label:x.label,paths:x.path?[x.path]:[]})),I=ca(e,"standard");Zt.current=Date.now(),Jt(0),A(!0);let O=new AbortController;qe.current=O;let k=Date.now(),v=Em(e);xe({verb:"Answering",unit:"article",total:E.length,done:0,active:[],rows:yr(E),tools:0,chars:0,lastAt:Date.now(),startedAt:k}),f({kind:"note",tone:"info",text:`Answering ${d} comment${d===1?"":"s"} across ${E.length} article${E.length===1?"":"s"} (\u2264${Fi} agents at once) on ${I.model}. Each article is fixed, pushed to Document360 as a draft, then answered in the thread${g.resolve?" and resolved":" \u2014 the threads stay open for your reviewers to close"}\u2026 (esc to stop)`});try{for await(let x of la({cwd:e,partitions:E,promptFor:b=>{let P=y.get(b.label);return nf({articleId:P.articleId,label:P.label,path:P.path,count:P.threads.length,resolve:g.resolve})},concurrency:Fi,profileName:s,allowProdWrites:Pn.current,allowCommentResolve:g.resolve,model:I.model,signal:O.signal}))if(x.type==="partition_status")x.status==="running"?xe(b=>b&&{...b,active:[...b.active,x.label],rows:dt(b.rows,x.label,"active"),lastAt:Date.now()}):xe(b=>b&&{...b,active:b.active.filter(P=>P!==x.label),done:b.done+1,rows:dt(b.rows,x.label,x.status==="done"?"done":"failed"),lastAt:Date.now()});else if(x.type==="partition_stalled"){let b=Rs(x);xe(P=>P&&b?{...P,stalledNote:b}:P)}else if(x.type==="partition_event")xe(b=>{if(!b)return b;let P={...b,lastAt:Date.now()};return x.event.type==="tool"?P.tools=b.tools+1:x.event.type==="text"&&(P.chars=b.chars+x.event.delta.length),P});else if(x.type==="run_done"){Uo(j=>j+x.totalCostUsd),Mo(j=>j+x.results.reduce((B,q)=>B+q.outputTokens,0));let b=Tm(E,x.results),P=x.results.length-b.failed.length,T=x.aborted?"Stopped. ":"",_=[...b.failed.map(j=>j.label),...b.notRun.map(j=>j.label)],M=[`${T}${P}/${E.length} article${E.length===1?"":"s"} answered.`,..._.length?[`\u26A0 ${_.length} left untouched (their threads are still open, which is correct \u2014 nothing was promised to those reviewers): ${_.join(", ")}`]:[],...x.blocked?[`\u26A0 ${x.blocked}`]:[],...x.allEmpty?["\u26A0 No agent produced any work this run \u2014 nothing was changed or answered."]:[]];f({kind:"note",tone:x.aborted||_.length||x.blocked||x.allEmpty?"warn":"ok",text:M.join(`
|
|
521
|
+
`)}),Lr(k,x.results,x.totalCostUsd,!x.aborted&&!_.length&&!x.blocked&&!x.allEmpty);let N=new Set(_),X=[...g.rest??[],...h.filter(j=>N.has(j.label))];if(X.length>0&&!x.aborted&&g.report){let j=X.reduce((q,se)=>q+se.threads.length,0);f({kind:"note",tone:"info",text:`${j} comment${j===1?"":"s"} on ${X.length} other article${X.length===1?"":"s"} still open \u2014 pick the next one, or esc to stop here.`});let B={...g.report,threads:X.flatMap(q=>q.threads)};Ir(Wi(B,{width:ct()})),En({cursor:0,rows:$c(X),groups:X,resolve:g.resolve,report:B})}else if(X.length>0&&!x.aborted){let j=X.map(q=>q.path).filter(q=>!!q),B=j.length===X.length?qt(j):void 0;ue(B?j.length===1?`/comments ${B}`:`/comments --scope ${B}`:"/comments")}On("/comments --answer",{aborted:x.aborted,partitions:E.length,failed:b.failed.length,notRun:b.notRun.length,...x.blocked?{blocked:x.blocked}:{},...x.allEmpty?{allEmpty:!0}:{},leftBehind:(g.rest??[]).length})}}catch(x){f({kind:"note",tone:"error",text:`Answering comments failed: ${x.message}`})}finally{let b=lr(e,v,"","/comments").changed.length;b>0&&f({kind:"note",tone:"info",text:`${b} article${b===1?"":"s"} changed, and that new text has not been read by an editor \u2014 ${b===1?"it":"they"} can go live once /review has been over ${b===1?"it":"them"}.`}),qe.current=null,xe(null),A(!1),H(P=>P+1)}},[e,s,f,je,ue,Ir,ct]),Fu=ce(async(h,g)=>{if(!(g?.skipReview===!0||g?.skipStyle===!0)){let y=fu(e,[h],{});if(!y.clear){f({kind:"note",tone:"warn",text:jm(y,1,{act:"push"}).join(`
|
|
522
|
+
`)}),ue(hi(y,h));return}}await Tt([h],0,{skipReview:g?.skipReview,skipStyle:g?.skipStyle,scope:h});try{let y=await jl(e,s,h.replace(/\\/g,"/"));y.length>0&&(Do(`Related articles not yet saved to Document360 (${y.length}):`),he([`/push --related ${h}`,...y.map(E=>`/push ${E}`)]))}catch{}},[e,s,Te,Tt]),ug=ce(async(h,g)=>{let d=up(e,s,Pn.current,h.length);if(d){f({kind:"note",tone:"warn",text:d.join(`
|
|
523
|
+
`)}),ue("/allow-prod");return}A(!0);try{let y=await dp(e,s,h,{skipReview:g.skipReview,skipStyle:g.skipStyle,allowProduction:Pn.current,onProgress:(I,O,k)=>He(`Publishing ${I+1}/${O} \u2014 ${k}\u2026`)}),E=y.blocked.length+y.failed.length;if(f({kind:"note",tone:E>0?"warn":"ok",text:pp(y).join(`
|
|
524
|
+
`)}),y.blocked.length>0){let I=fu(e,y.blocked.map(k=>k.path),{allowUnreviewed:g.skipReview,allowStyleErrors:g.skipStyle,checkScreenshots:!0}),O=_l(e,I,g.scope);O.cmd?ue(O.cmd):je(null,null)}else je(null,null)}catch(y){f({kind:"note",tone:"error",text:`Publishing failed: ${y.message}`})}finally{He(null),await Aa(),A(!1),H(y=>y+1)}},[e,s,f,ue,je,Aa]),dg=ce(async h=>{try{let g=await aa({cwd:e,profileName:s}),d=new Set(er(e,s)),{clean:y,conflicts:E}=Zo(g.entries,d);if(y.length===0){f({kind:"note",tone:"info",text:"Nothing new to save \u2014 everything is already up to date on Document360."});return}await Tt(y.map(I=>I.path),E.length,{skipReview:h?.skipReview,skipStyle:h?.skipStyle,unreadableSkipped:E.filter(I=>d.has(I.path)).length})}catch(g){f({kind:"note",tone:"warn",text:`Couldn\u2019t check what to save (${g.message}) \u2014 your articles are written; run /push when ready.`})}},[e,s,Tt]),On=ce((h,g)=>{if(g&&(Su.current=g),!(g&&!ln(g)))for(let d of Ze(e,h))f({kind:"note",tone:"ok",text:d})},[e,f]),pg=ce(async(h,g)=>{let y=LU(h,3),E=ca(e,"standard"),I=new Map,O=new Map;for(let b of h){let P=Qo(e,b),T=Ad(e,b,P);if(T&&I.set(b,T),P!==null){let _=Wd(P);_.length>0&&O.set(b,_)}}Zt.current=Date.now(),Jt(0),A(!0);let k=new AbortController;qe.current=k;let v=Date.now();xe({verb:"Authoring",unit:"spec",total:y.length,done:0,active:[],rows:yr(y),tools:0,chars:0,lastAt:Date.now(),startedAt:v}),f({kind:"note",tone:"info",text:`Authoring ${h.length} screenshot spec${h.length===1?"":"s"} in ${y.length} batch${y.length===1?"":"es"} (\u22646 agents at once) on ${E.model}${E.forced?" (forced)":""}\u2026 (esc to stop)`});let x=!1;try{for await(let b of la({cwd:e,partitions:y,promptFor:P=>Tw(P,I,O),concurrency:6,profileName:s,allowProdWrites:Pn.current,model:E.model,signal:k.signal}))if(b.type==="partition_status")b.status==="running"?xe(P=>P&&{...P,active:[...P.active,b.label],rows:dt(P.rows,b.label,"active"),lastAt:Date.now()}):xe(P=>P&&{...P,active:P.active.filter(T=>T!==b.label),done:P.done+1,rows:dt(P.rows,b.label,b.status==="done"?"done":"failed"),lastAt:Date.now()});else if(b.type==="partition_stalled"){let P=Rs(b);xe(T=>T&&P?{...T,stalledNote:P}:T)}else if(b.type==="partition_event")xe(P=>{if(!P)return P;let T={...P,lastAt:Date.now()};return b.event.type==="tool"?T.tools=P.tools+1:b.event.type==="text"&&(T.chars=P.chars+b.event.delta.length),T});else if(b.type==="run_done"){Uo(N=>N+b.totalCostUsd),Mo(N=>N+b.results.reduce((X,j)=>X+j.outputTokens,0));let P=b.results.filter(N=>N.ok).length,T=b.aborted?"Stopped. ":"";x=!b.aborted&&g.setup;let _=b.aborted?"":x?" Refreshing the staging checklist\u2026":` Next: /screenshot capture${g.scope?` ${g.scope}`:" --all"} (or /screenshot checklist first for the staging checklist).`,M=ho(b,"Spec authoring");f({kind:"note",tone:M||b.aborted?"warn":b.ok?"ok":"warn",text:M?M.join(`
|
|
525
|
+
`):`${T}Authored specs \u2014 ${P}/${b.results.length} batches ok.${_}`}),Lr(v,b.results,b.totalCostUsd,!M&&!b.aborted&&b.ok),M&&(ue("/doctor"),x=!1),!b.aborted&&b.ok&&!M&&On(g.runLine)}}catch(b){f({kind:"note",tone:"error",text:`Spec authoring failed: ${b.message}`})}finally{qe.current=null,xe(null),A(!1),H(b=>b+1)}if(x){let b=await ps();b.kind==="forward-to-agent"&&b.prompt&&await Te(b.prompt,{display:b.display,quietUser:!0}),Eu()}},[e,s,f,Te,On,Eu]),hg=ce(async h=>{let g=Ad(e,h,Qo(e,h))??void 0,d=await Rl([h],void 0,{prior:g});d.kind==="forward-to-agent"&&d.prompt&&await Te(d.prompt,{display:d.display,quietUser:!0}),fw(e,h)&&je(`Spec ready \u2014 /screenshot capture ${h} takes the screenshot; bare /screenshot picks the next shot.`,{kind:"cmd",cmd:`/screenshot capture ${h}`,reason:""})},[e,Te,je]),Ea=ce(async(h,g)=>{if(h.length===0)return{drawn:[],undrawn:[],cliMissing:!1};A(!0);let d=new AbortController;qe.current=d,xe({verb:"Drawing callouts",unit:"screenshot",total:h.length,done:0,active:[],rows:h.map(P=>({label:P,items:1,status:"pending"})),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()});let y=[],E=!1;try{let P=await Lh({cwd:e,ids:h,...g.force?{force:!0}:{},signal:d.signal,onStart:T=>xe(_=>_&&{..._,active:[T],rows:dt(_.rows,T,"active"),lastAt:Date.now()}),onDone:(T,_)=>xe(M=>M&&{...M,active:[],done:M.done+1,rows:dt(M.rows,T,_==="failed"?"failed":"done"),lastAt:Date.now()})});y=P.results,E=P.cliMissing??!1}catch(P){f({kind:"note",tone:"error",text:`Drawing the callouts failed: ${P.message}`})}finally{qe.current=null,xe(null),A(!1),H(P=>P+1)}if(E)return f({kind:"note",tone:"error",text:`${ua} is not installed on this machine. Run: npm i -g ${mu} \u2014 then /screenshot annotate.`}),{drawn:[],undrawn:h,cliMissing:!0};let I=y.filter(P=>P.outcome==="annotated").map(P=>P.id),O=y.filter(P=>P.outcome==="skipped").map(P=>P.id),k=h.filter(P=>!I.includes(P)&&!O.includes(P));if(f({kind:"note",tone:k.length?"warn":"ok",text:[`\u25C8 ${I.length} drawn`,O.length?`${O.length} already current`:"",k.length?`\u2717 ${k.length} not drawn`:""].filter(Boolean).join(" ")}),k.length>0){let P=Math.max(...k.map(T=>T.length));f({kind:"note",tone:"warn",text:k.map(T=>`\u2717 ${T.padEnd(P)} ${Ii(y.find(_=>_.id===T)?.detail)||"no picture was produced"}`).join(`
|
|
526
526
|
`)+`
|
|
527
|
-
${k.length===1?"It has":"They have"} no publishable picture yet. Re-take the shot: /screenshot capture`})}if(g.chainVerify===!1||I.length===0)return{drawn:I,undrawn:k,cliMissing:!1};let v=I.filter(P=>g.verifiedBefore.has(P)).length;if(v>
|
|
528
|
-
`)}),{drawn:I,undrawn:k,cliMissing:!1}},[e,f,
|
|
529
|
-
${
|
|
530
|
-
${v}`:"")});let x=Date.now(),b=[];try{for(let B of h){if(E.signal.aborted)break
|
|
531
|
-
${B}`).join("")});let N=
|
|
532
|
-
`)}),_.length>0){let B=Math.max(..._.map(q=>q.id.length));f({kind:"note",tone:"error",text:_.map(q=>`\u2717 ${q.id.padEnd(B)} ${
|
|
533
|
-
`)})}
|
|
534
|
-
`)});return}let j=
|
|
535
|
-
`)})}catch{}},I=
|
|
536
|
-
`)}),
|
|
527
|
+
${k.length===1?"It has":"They have"} no publishable picture yet. Re-take the shot: /screenshot capture`})}if(g.chainVerify===!1||I.length===0)return{drawn:I,undrawn:k,cliMissing:!1};let v=I.filter(P=>g.verifiedBefore.has(P)).length;if(v>pc){let P=Gb({results:y,voidedVerdicts:v,...g.scope?{scope:g.scope}:{}});return P&&je(`${P.glyph} ${P.cmd} ${P.why}`,{kind:"cmd",cmd:P.cmd,reason:""},"warn"),{drawn:I,undrawn:k,cliMissing:!1}}let x=I.filter(P=>!g.verifiedBefore.has(P)||v>0);if(x.length===0)return{drawn:I,undrawn:k,cliMissing:!1};f({kind:"note",tone:"info",text:yo(x.length)}),await Te(vn(e,x),{display:"/screenshot verify",quietUser:!0});let b=us(e,x);return b.length>0&&f({kind:"note",tone:"info",text:b.join(`
|
|
528
|
+
`)}),{drawn:I,undrawn:k,cliMissing:!1}},[e,f,je,Te]),Ys=ce(async(h,g)=>{if(!ir(e)){await Te(Eh(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(!Ib(e)){f({kind:"note",tone:"info",text:"No saved login for screenshot capture yet \u2014 opening a browser window. Sign in to your app (MFA included); I'll continue automatically once the session saves. (esc cancels)"}),A(!0),He("Waiting for you to finish logging in (browser window)\u2026");let B=new AbortController;qe.current=B;let q;try{q=await Lb({cwd:e,signal:B.signal})}catch(se){f({kind:"note",tone:"error",text:`Could not launch the login: ${se.message}`});return}finally{qe.current=null,He(null),A(!1)}if(q.exitCode!==0){Th(q.exitCode,q.output)?f({kind:"note",tone:"error",text:`${ua} is not installed on this machine. Run: npm i -g ${mu} \u2014 then /screenshot capture again.`}):/unknown option/i.test(q.output)?f({kind:"note",tone:"warn",text:`Your ${ua} is older than this writer. Update it: npm i -g ${mu} \u2014 then /screenshot capture again.`}):f({kind:"note",tone:B.signal.aborted?"warn":"error",text:B.signal.aborted?"Login cancelled \u2014 nothing saved.":`Login did not complete:
|
|
529
|
+
${Ph(q.output)}`});return}f({kind:"note",tone:"ok",text:"\u2713 Login saved \u2014 continuing with the capture."})}let d=new Map(h.map(B=>[B,bw(e,B)])),y=0;if(h.length>1){let B=h.filter(q=>d.get(q).mutates);if(B.length>0&&(y=B.length,h=h.filter(q=>!d.get(q).mutates),h.length===0)){f({kind:"note",tone:"warn",text:`\u26A0 All ${B.length} spec${B.length===1?"":"s"} in scope write real data, so a bulk run has nothing to do. Run one deliberately: /screenshot capture ${B[0]}`});return}}else if(h.length===1&&d.get(h[0]).mutates){let B=d.get(h[0]),q=Ob(e);f({kind:"note",tone:"warn",text:`\u26A0 This capture performs a REAL write in your app${B.what?`: ${kw(B.what)}`:B.declared?"":" (detected from the spec: form fill + commit click / file upload)"}. Running because you named it explicitly \u2014 check the result and clean up what it created. `+(q.production?`This profile is PRODUCTION \u2014 the write lands in the LIVE tenant${q.url?` (${q.url})`:""}. If the spec cleans up after itself, confirm it did.`:`Tip: point the capture scope (${pt}/capture.json) at a demo/non-production context for shots like this.`)})}A(!0);let E=new AbortController;qe.current=E;let I=h.map(B=>({label:B,items:1,status:"pending"}));xe({verb:"Capturing",unit:"screenshot",total:h.length,done:0,active:[],rows:I,tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()});let O=Fn(e),k=Object.keys(O.shots).length>0,v=_b(g?.heldBackBlocked??[],y);f({kind:"note",tone:"info",text:`Capturing ${h.length} screenshot${h.length===1?"":"s"} with ${ua} (a real browser drives your app)\u2026 (esc to stop)`+(v?`
|
|
530
|
+
${v}`:"")});let x=Date.now(),b=[];try{for(let B of h){if(E.signal.aborted)break;xe($e=>$e&&{...$e,active:[B],rows:dt($e.rows,B,"active"),lastAt:Date.now()});let{exitCode:q,output:se}=await Ah({cwd:e,id:B,signal:E.signal,stdio:"pipe"});if(Th(q,se)){f({kind:"note",tone:"error",text:`${ua} is not installed on this machine. Run: npm i -g ${mu} \u2014 then /screenshot capture again.`});return}let ye=E.signal.aborted&&q!==0?"failed":Ch(e,B,q,x),we=ye==="captured"?void 0:ye==="skipped"?Db(se)??"a data prerequisite isn't met \u2014 the spec's skip reason names what to stage":jb(se);b.push({id:B,outcome:ye,detail:we}),xe($e=>$e&&{...$e,active:[],done:$e.done+1,rows:dt($e.rows,B,ye==="captured"?"done":"failed"),lastAt:Date.now()})}}catch(B){f({kind:"note",tone:"error",text:`Capture run failed: ${B.message}`})}finally{qe.current=null,xe(null),A(!1),H(B=>B+1)}if(b.length===0)return;let P=b.filter(B=>B.outcome==="captured"),T=b.filter(B=>B.outcome==="skipped"),_=b.filter(B=>B.outcome==="failed"),M=h.length-b.length;f({kind:"note",tone:_.length?"warn":P.length?"ok":"info",text:[`\u2713 ${P.length} captured`,T.length?`\u2298 ${T.length} blocked`:"",_.length?`\u2717 ${_.length} broken`:"",M?`${M} not run (stopped)`:""].filter(Boolean).join(" ")+` ${b.length} run${y>0?` \xB7 ${y} held back`:""}`+Fb(Mb(O,b),k).map(B=>`
|
|
531
|
+
${B}`).join("")});let N=Ub(T);if(N.length>0&&f({kind:"note",tone:"info",text:N.join(`
|
|
532
|
+
`)}),_.length>0){let B=Math.max(..._.map(q=>q.id.length));f({kind:"note",tone:"error",text:_.map(q=>`\u2717 ${q.id.padEnd(B)} ${Ii(q.detail)}`).join(`
|
|
533
|
+
`)})}dl(e,b.map(B=>({id:B.id,outcome:B.outcome,reason:B.detail,specSource:Qo(e,B.id)})),new Date().toISOString()),b.length===h.length&&_.length===0&&T.length===0&&On(g?.runLine);let X=[];if(P.length>0&&dc()){let B=await Ea(P.map(q=>q.id),{verifiedBefore:new Set});if(B.cliMissing||(X=B.undrawn,B.drawn.length>0))return}else if(P.length>0){f({kind:"note",tone:"info",text:yo(P.length)}),await Te(vn(e,P.map(q=>q.id)),{display:"/screenshot verify",quietUser:!0});let B=us(e,P.map(q=>q.id));B.length>0&&f({kind:"note",tone:"info",text:B.join(`
|
|
534
|
+
`)});return}let j=Wb({results:b,ids:h,articles:Bb(e,P.map(B=>B.id)),...X.length>0?{unannotated:X}:{}});j&&je(j.note,{kind:"cmd",cmd:j.cmd,reason:""},j.tone)},[e,f,je,Te,On,Ea]),Wu=ce(h=>{let g=vo(h);if(!g||kr(g)&&!g.refreshToken)return null;let d={...Ns(g.idToken)??{},...Ns(g.accessToken)??{}};return d.email??d.preferred_username??"signed in"},[]),Na=ce((h,g)=>{if(g){let d=Se(e);d&&(d.defaultProfile=h,f0(d,e))}i(h),Qe(void 0,h),f({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${h}"${g?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),Wu(h)||(f({kind:"note",tone:"warn",text:`Profile "${h}" is not signed in \u2014 sign in with /login.`}),ue("/login")),H(d=>d+1)},[e,f,Qe,Wu,ue]),Bu=ce(async(h,g,d,y)=>{let E=async()=>{try{let O=wt(e,h),k=await vU({profile:O.name,connection:O.connection,projectId:g,projectName:O.project.projectName},{cwd:e,profile:O.name,projectId:g,workspaceId:d}),v=xU(k);v.length>0&&f({kind:"note",tone:k.kind==="swept"&&k.hidden==="confirmed"?"ok":"warn",text:v.join(`
|
|
535
|
+
`)})}catch{}},I=Fv(e,h);if(I==="fresh"){E(),f({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),f({kind:"note",tone:"warn",text:"\u26A0 Before I write the docs, hand the prompt below to your builder (your repo's coding agent). It gives me the architecture brief that makes the docs accurate:"}),f({kind:"note",tone:"info",text:Vr(qr(e)).join(`
|
|
536
|
+
`)}),In(zo()),qs.current=an(e).status==="current",jr.current=Un(e),f({kind:"note",tone:"info",text:`No separate builder agent? Then just ask me now: "write the docs for this repo" \u2014 I'll read the code directly.`});return}if(I==="unpushed"){let O=h;try{O=wt(e,h).connection.portalUrl}catch{}f({kind:"note",tone:"ok",text:`\u2713 Connected. ${h} \xB7 ${y} \xB7 ${O}`}),He("Checking what this portal already holds\u2026"),await E(),He("Comparing your articles with this portal\u2026");try{let k=await aa({cwd:e,profileName:h}),v=$U(e,h).length,x=k.counts["untracked-remote"]??0;f({kind:"note",tone:"ok",text:x===0?`\u2713 This portal has no articles yet.
|
|
537
537
|
Your ${v} ${v===1?"is":"are"} written here and none of them are on it.`:`\u2713 This portal already holds ${x} article${x===1?"":"s"}.
|
|
538
538
|
Nothing is pushed until you decide which of yours are already there.
|
|
539
|
-
/pull --status shows the comparison article by article.`})}catch{}finally{
|
|
540
|
-
`)}),
|
|
541
|
-
${
|
|
542
|
-
`)}),k.copyText&&
|
|
543
|
-
${x.pick.lead}`}),
|
|
544
|
-
`)}),x.restart&&(
|
|
545
|
-
`),{kind:"cmd",cmd:x.editorial.cmd,reason:"it reads every article the new guide flagged and rewrites it",...b?{detail:b}:{}})}H(b=>b+1);return}let v=await
|
|
546
|
-
`)}),x&&(
|
|
547
|
-
`)});return}case"mcp":await
|
|
548
|
-
`)}),k&&f({kind:"note",tone:"warn",text:`\u26A0 ${k.why} \u2014 ${k.cmd} moves this repo.`});return}
|
|
549
|
-
${_.path} \xB7 ${_.articleId?`updates article ${_.articleId}`:"would be created as a new article"}${M}`}),_.missingShots.length>0&&f({kind:"note",tone:"warn",text:`\u26A0 ${_.missingShots.length} screenshot${_.missingShots.length===1?"":"s"} not taken yet \u2014 the description publishes instead: ${_.missingShots.join(", ")}`}),f({kind:"note",tone:"info",text:_.body}),f({kind:"note",tone:"info",text:`Nothing was sent. /push ${_.path} saves it as a draft.`}),
|
|
539
|
+
/pull --status shows the comparison article by article.`})}catch{}finally{He(null),H(k=>k+1)}return}H(O=>O+1)},[e,f,In]),Da=ce((h,g,d)=>{Oa(e,h,g,d.id,d.name),f({kind:"note",tone:"ok",text:`Switched to workspace "${d.name??d.id}" (agent restarted).`}),Qe(),Bu(h,g,d.id,d.name??d.id)},[e,f,Qe,Bu]),ja=ce(async h=>{let g;try{g=await Js(e,h)}catch{f({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),ue("/workspace");return}if(g.workspaces.length===0){f({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let d=g.workspaces.filter(E=>(E.workspace_type??"").toLowerCase()!=="apidocumentation"),y=d.length>0?d:g.workspaces;if(y.length===1){let E=y[0],I=g.workspaces.length-y.length;f({kind:"note",tone:"ok",text:`Selected the "${E.name??E.id}" workspace${I>0?" (skipped the API-documentation workspace)":""}.`}),Da(g.profile,g.projectId,E);return}f({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${y.length} available).`}),ue("/workspace")},[e,f,Da,ue]),Ia=ce((h,g)=>{_a(e,h,g.id,g.name),f({kind:"note",tone:"ok",text:`Project set to "${g.name??g.id}" (agent restarted).`}),Qe(),ja(h)},[e,f,Qe,ja]),fg=ce(async h=>{let g;try{g=wt(e,h)}catch{return}if(g.project.workspaceId){let d=g.project.workspaceName??g.project.workspaceId;g.project.projectId&&await Bu(g.name,g.project.projectId,g.project.workspaceId,d);return}if(g.project.projectId){if(!g.project.projectName)try{let{projects:d}=await Mn(e,g.name),y=d.find(E=>E.id===g.project.projectId);y?.name&&qU(e,g.name,{projectName:y.name})}catch{}await ja(g.name);return}try{let{projects:d}=await Mn(e,g.name);if(d.length===1){let y=d[0];f({kind:"note",tone:"ok",text:`Using your Document360 project "${y.name??y.id}".`}),Ia(g.name,{id:y.id,name:y.name});return}if(d.length>1){let y=d.map(E=>({id:E.id,name:E.name??E.id,sub:E.sub_domain}));f({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),To({cursor:0,current:-1,rows:y,profile:g.name,environment:g.connection.name});return}}catch{}f({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),ue("/project")},[e,f,ja,Ia,ue]),Or=ce(()=>{let h=_e.current[0];if(!h)return;if(rn(),h.mode==="local-only"){f({kind:"note",tone:"info",text:`\u25CF ${h.title??h.path} (${h.path})`});for(let I of Gl())f({kind:"note",tone:"warn",text:`\u26A0 ${I}`});f({kind:"note",tone:"info",text:ql()}),f({kind:"note",tone:"info",text:gk()});return}let{plan:g,mode:d}=h;f({kind:"note",tone:"info",text:`\u25CF ${g.title} (${g.path})`});for(let I of g.notes)f({kind:"note",tone:"warn",text:`\u26A0 ${I}`});g.overwritesLocalChanges&&d==="pull"&&f({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let y=Yt(g.oldContent,g.newContent,ct(),ns);f(y?{kind:"diff",added:y.added,removed:y.removed,lines:y.lines,hidden:y.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."});let E=_e.current.length;d==="conflict"?(f({kind:"note",tone:"warn",text:"Conflict \u2014 edited both here and on the portal (diff shows local \u2192 portal)."}),f({kind:"note",tone:"info",text:"Keep local (publish, overwrites portal) \xB7 take Portal (overwrites local) \xB7 Skip?"}),f({kind:"note",tone:"info",text:E>1?`(l/p/s \xB7 la/pa/sa for all ${E} \u2014 anything else stops, keeping your answers so far)`:"(l/p/s \u2014 anything else stops, keeping your answers so far)"})):f({kind:"note",tone:"info",text:E>1?`Write ${g.path}? (y/n \xB7 ya/na for all ${E} \u2014 anything else cancels)`:`Write ${g.path}? (y/n \u2014 anything else cancels)`})},[f,ct,rn]),Bo=ce(()=>{if(_e.current.length>0){Or();return}let h=en.current;en.current=[];let g=An.current;An.current=[];for(let d of Vl(g))f({kind:"note",tone:"warn",text:`\u26A0 ${d}`});h.length>0?(f({kind:"note",tone:"info",text:`Saving ${h.length} kept-local article${h.length===1?"":"s"} over the portal\u2026`}),Tt(h,0,{allowUnpullable:!0})):g.length>0||ue("/pull")},[Or,f,Tt,ue]),Hu=ce(h=>{let g=Zc(h);if(!g)return!1;let d=_e.current.splice(0),y=d.length;if(g==="local"){for(let E of d)en.current.push(hF(E));f({kind:"note",tone:"info",text:`Keeping local for all ${y} \u2014 will publish ${y===1?"it":"them"} over the portal.`})}else if(g==="portal"){let E=0;for(let I of d){if(I.mode==="local-only"){f({kind:"note",tone:"warn",text:`\u26A0 ${vp(I.path)}`}),An.current.push(I.path);continue}try{hu({cwd:e,profileName:s},I.plan),E++}catch(O){f({kind:"note",tone:"error",text:`Take-portal failed for ${I.plan.path}: ${O.message}`})}}f({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${E} article${E===1?"":"s"} (local overwritten, sync base advanced).`})}else{for(let E of d)E.mode==="local-only"&&An.current.push(E.path);f({kind:"note",tone:"info",text:`Skipped all ${y} \u2014 still conflict${y===1?"":"s"}.`})}return Bo(),!0},[e,s,Bo,f]),mg=ce(h=>{if(_e.current.length===0)return!1;let g=h.trim(),d=g.toLowerCase(),y=_e.current[0];if(y.mode==="local-only"){if(Zc(g))return Hu(g);if(d==="l"||d==="local"||d==="publish")_e.current.shift(),en.current.push(y.path),f({kind:"note",tone:"info",text:`Publishing your copy of ${y.path} over the portal.`});else if(d==="s"||d==="skip")_e.current.shift(),An.current.push(y.path),f({kind:"note",tone:"info",text:`Skipped ${y.path} \u2014 still a conflict.`});else{let I=_e.current.splice(0),O=en.current;return en.current=[],An.current=[],f({kind:"note",tone:"info",text:`Resolve canceled. ${I.length} conflict${I.length===1?"":"s"} left untouched.`+(O.length>0?` Saving the ${O.length} article${O.length===1?"":"s"} you already chose to keep - an answer you gave is not undone by stopping.`:"")}),O.length>0&&Tt(O,0,{allowUnpullable:!0}),!0}return Bo(),!0}if(y.mode==="conflict"){if(Zc(g))return Hu(g);if(d==="l"||d==="local")_e.current.shift(),en.current.push(y.plan.path),f({kind:"note",tone:"info",text:`Keeping local ${y.plan.path} \u2014 will publish over the portal.`});else if(d==="p"||d==="portal"){_e.current.shift();try{hu({cwd:e,profileName:s},y.plan),f({kind:"note",tone:"ok",text:`\u2713 Took the portal copy of ${y.plan.path} (local overwritten, sync base advanced).`})}catch(I){f({kind:"note",tone:"error",text:`Take-portal failed: ${I.message}`})}}else if(d==="s"||d==="skip"||d==="n")_e.current.shift(),f({kind:"note",tone:"info",text:`Skipped ${y.plan.path} \u2014 still a conflict.`});else{let I=_e.current.length;_e.current=[];let O=en.current;return en.current=[],An.current=[],f({kind:"note",tone:"info",text:`Resolve canceled. ${I} conflict${I===1?"":"s"} left untouched.`+(O.length>0?` Saving the ${O.length} article${O.length===1?"":"s"} you already chose to keep - an answer you gave is not undone by stopping.`:"")}),O.length>0&&Tt(O,0,{allowUnpullable:!0}),!0}return Bo(),!0}let E=mx(g);if(E){let I=_e.current.splice(0);if(E==="skip")f({kind:"note",tone:"info",text:`Skipped all ${I.length} article${I.length===1?"":"s"}.`});else{let O=0;for(let k of I){if(k.mode==="local-only"){f({kind:"note",tone:"warn",text:`\u26A0 ${vp(k.path)}`});continue}try{hu({cwd:e,profileName:s},k.plan),O++}catch(v){f({kind:"note",tone:"error",text:`Pull failed for ${k.plan.path}: ${v.message}`})}}f({kind:"note",tone:"ok",text:`\u2713 Pulled ${O} article${O===1?"":"s"} (sync base advanced).`})}return Bo(),!0}if(d==="y"||d==="yes"){let{plan:I}=y;_e.current.shift();try{hu({cwd:e,profileName:s},I),f({kind:"note",tone:"ok",text:`\u2713 Pulled ${I.path} (sync base advanced).`})}catch(O){f({kind:"note",tone:"error",text:`Pull failed: ${O.message}`})}}else if(d==="n"||d==="no")_e.current.shift(),f({kind:"note",tone:"info",text:`Skipped ${y.plan.path}.`});else{let I=_e.current.length;return _e.current=[],f({kind:"note",tone:"info",text:`Pull cancelled (${I} article(s) left untouched).`}),!0}return Bo(),!0},[e,s,Bo,f,Hu]),Gu=ce(async h=>{f({kind:"note",tone:"info",text:"Checking Document360 for conflicts\u2026"});try{let g=await aa({cwd:e,profileName:s}),d=h?.replace(/\\/g,"/"),y=Hl(e,s,g.entries,tr(g.entries).map(O=>O.path));if(d){if(!y.includes(d)){f({kind:"note",tone:"ok",text:`${d} isn\u2019t waiting on a decision \u2014 nothing to resolve.`});return}y=[d]}if(y.length===0){f({kind:"note",tone:"ok",text:"\u2713 No conflicts \u2014 local and Document360 agree on every tracked article."});return}let E=[];for(let O of y)try{E.push({plan:await w0({cwd:e,profileName:s,relPath:O}),mode:"conflict"})}catch(k){k0(k)?E.push({mode:"local-only",path:O,title:b0(e,O)}):f({kind:"note",tone:"error",text:`Could not load ${O} from Document360: ${k.message}`})}if(E.length===0)return;let I=E.some(O=>O.mode!=="local-only");f({kind:"note",tone:"info",text:I?`Resolving ${E.length} conflict${E.length===1?"":"s"} \u2014 for each: keep local, take portal, or skip.`:`Resolving ${E.length} conflict${E.length===1?"":"s"} \u2014 for each: publish your copy over the portal, or skip.`}),_e.current=E,en.current=[],An.current=[],Or()}catch(g){f({kind:"note",tone:"error",text:`Could not compute sync status: ${g.message}`})}},[e,s,f,Or]),gg=ce(h=>{let g=Rr.current;if(!g)return!1;if(Rr.current=null,rn(),h.trim()!==g.repoName)return f({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:d,failed:y}=df(e,g.targets);f({kind:"note",tone:y.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${d.length} item${d.length===1?"":"s"}. The repo is back to its original state.`});for(let E of y)f({kind:"note",tone:"error",text:` \u2717 ${E.path}: ${E.error}`});return g.hadDevhints&&(f({kind:"note",tone:"warn",text:nl().join(`
|
|
540
|
+
`)}),In(yd())),f({kind:"note",tone:"info",text:`Clean slate \u2014 set up ${yt} again whenever you're ready:
|
|
541
|
+
${D0}`}),ue("/init"),Ot(!1),!0},[e,f,In,rn,ue]),Ho=ce(async h=>{let g=h.slice(1).trim().split(/\s+/),d=(g[0]??"").toLowerCase(),y=g.slice(1);if(ng.current=h.trim(),Ot(!0),Si(y)&&["write","lint","check","review","reorder"].includes(d)){let k=Ri(e,s);if(k.length===0){f({kind:"note",tone:"warn",text:"No categories yet \u2014 author some articles first, then scope to one."});return}let v=x=>d==="write"?`/write ${Xk(y,x).join(" ")}`.trim():`/${d} ${[x,...y.filter(b=>b!=="--scope")].join(" ")}`.trim();if(k.length===1){Ho(v(k[0].token));return}No({cursor:0,rows:k,run:x=>{Ho(v(x))}});return}if(go(d,y)){let k=d==="write"&&Ci(y).rewrite,v=d==="write"?lh(e,v0(e),{rewrite:k}):Ri(e,s);if(v.length>1){let x=y.filter(q=>q.startsWith("--")).join(" "),b=q=>q==="--blocked"?`/${d} --blocked${x?` ${x}`:""}`.trim():`/${d}${q?` ${d==="write"?`--scope ${q}`:q}`:""}${x?` ${x}`:""} ${q?"":"--all"}`.replace(/\s+/g," ").trim(),P=v.reduce((q,se)=>q+se.count,0),T={token:"",label:d==="review"?`Everything \u2014 all ${P} articles + structure (IA) review`:d==="reorder"?`Everything \u2014 reorder all ${v.length} categories`:k?`Everything \u2014 rewrite all ${P} planned articles`:`Everything \u2014 write all ${P} pending article${P===1?"":"s"}`,count:P},_=d==="review"?Nf(e):[],M=_.length>0&&_.length<P?[{token:"--blocked",label:`Only what needs review \u2014 ${_.length} article${_.length===1?"":"s"} publishing is blocked on`,count:_.length}]:[],N=d==="review"?Df(e):[],X=N.length>_.length&&N.length<P?[{token:"--stale",label:`Everything the current editor hasn\u2019t read \u2014 ${N.length} article${N.length===1?"":"s"}`,count:N.length}]:[],j=d==="write"?`Write which articles? (counts = ${k?"articles to regenerate":"still to write"})`:d==="review"?"Review what? (counts = articles)":"Reorder what?";No({cursor:0,rows:(q=>d==="review"||d==="write"?q.map(se=>{let ye=(()=>{try{return T$(e,b(se.token))}catch{return null}})();return ye?{...se,label:`${se.label} \xB7 ${ye}`}:se}):q)([...M,...X,T,...v]),run:q=>{Ho(b(q))},title:j});return}}let E=async k=>{let v=xh(k);if(!ir(e)){await Te(Eh(),{display:"/screenshot capture \u2014 first-time setup",quietUser:!0});return}if(v.mode==="single"){await Ys([v.id],{runLine:[`/screenshot capture ${v.id}`,`/capture ${v.id}`]});return}if(v.mode==="failed"){let b=Rh(e,Li(e).rows);if(b.length===0){f({kind:"note",tone:"info",text:"No broken specs to re-run \u2014 /screenshot list shows where things stand."}),ue("/screenshot list");return}await Ys(b);return}if(v.mode==="blocked"){let{blocked:b,rows:P}=Li(e);if(b.length===0){f({kind:"note",tone:"info",text:"No shots are waiting on app data \u2014 /screenshot list shows where things stand."}),ue("/screenshot list");return}let T=li(P.filter(_=>_.state==="blocked")).length;f({kind:"note",tone:"info",text:`Re-running ${b.length} shot${b.length===1?"":"s"} that skipped on missing data last run.`+(T>0?` If you haven't staged ${T===1?"it":"those "+T+" things"} yet, ${b.length===1?"it":"they"} will skip again \u2014 /screenshot list has the worklist.`:"")}),await Ys(b,{runLine:["/screenshot capture --blocked","/screenshot capture --all --retry-blocked"]});return}if(v.mode==="all"||v.mode==="scope"){let b=v.mode==="scope"?v.scope:void 0,{ready:P,captured:T,blocked:_,rows:M}=Li(e,b),N=[...P,...T,...v.retryBlocked?_:[]];if(N.length===0&&_.length>0&&!v.retryBlocked){let j=b?`/screenshot capture ${b} --retry-blocked`:"/screenshot capture --blocked";je(`All ${_.length} shot${_.length===1?"":"s"} in scope ${_.length===1?"is":"are"} blocked on data that wasn't staged last run \u2014 /screenshot list shows what to stage, then ${j}.`,{kind:"cmd",cmd:"/screenshot list",reason:""},"warn");return}if(N.length===0){f({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),ue("/screenshot");return}if(!v.retryBlocked){let j=b?`/screenshot capture ${b} --retry-blocked`:"/screenshot capture --blocked",B=Sh(M.filter(q=>q.state==="blocked"),j);B&&f({kind:"note",tone:"info",text:B})}let X=v.mode==="scope"?[`/screenshot capture ${v.scope}`,`/capture ${v.scope}`]:["/screenshot capture --all","/capture --all"];await Ys(N,{runLine:X,...v.retryBlocked?{}:{heldBackBlocked:M.filter(j=>j.state==="blocked")}});return}let x=Nb(Ke(e));if(x.length===0){f({kind:"note",tone:"info",text:"No authored specs to capture yet \u2014 author them first with /screenshot."}),ue("/screenshot");return}Eo({cursor:0,rows:x,title:"Capture screenshots \u2014 pick what to shoot:"})},I=async k=>{let v=Dh(k);if(!ir(e)){f({kind:"note",tone:"info",text:"Screenshot capture is not set up in this repo yet. Run /screenshot capture and it will walk you through it."}),ue("/screenshot capture");return}let x=Nt();if(!dc(x)){f({kind:"note",tone:"info",text:Ih(x)}),ue("/update");return}let b=v.mode==="scope"?v.scope:void 0,{pending:P,done:T,rows:_}=jh(e,b),M=v.mode==="all"||v.mode==="scope"?v.force:!1,N=v.mode==="single"?[v.id]:M?[...P,...T]:P;if(N.length===0){f({kind:"note",tone:"info",text:T.length>0?`Every shot${b?` under ${b}`:""} is already drawn on. To re-draw them anyway (after a wording or style change): /screenshot annotate --all --force`:"No shots have been taken yet \u2014 /screenshot capture takes them first."}),ue(T.length>0?"/screenshot annotate --all --force":"/screenshot capture");return}await Ea(N,{force:M,scope:b,verifiedBefore:new Set(_.filter(X=>X.state==="verified").map(X=>X.id))})},O=async()=>{let k=await ps(y,{cwd:e,profileName:s});k.kind==="forward-to-agent"&&k.prompt&&await Te(k.prompt,{display:k.display,quietUser:!0}),Eu()};switch(d){case"help":_o({tab:0,scroll:0});return;case"exit":case"quit":Pe.current?.close(),r();return;case"clear":Qe(),ge.current=[],vt.current={printed:[],armed:[],printedAt:Dr.current},Ot(!1),rn(),console.log("\x1B[?2026h\x1B[H\x1B[2J\x1B[3J\x1B[?2026l"),f({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let k,v;try{k=wt(e,s),v=k.connection}catch(x){f({kind:"note",tone:"error",text:x.message});let b=Ve(e,s);b&&(f({kind:"note",tone:"warn",text:`Signing in cannot change this \u2014 the deployment comes from the profile. ${b.cmd} is where it changes.`}),ue(b.cmd));return}f({kind:"note",tone:"info",text:`Profile "${k.name}" \u2192 ${v.name} (${v.apiUrl})${k.production?` ${Je}`:""}`}),D(!0);try{let x=await ZM(v,{promptForRedirect:()=>Promise.reject(new Error(`Manual login is CLI-only. Run: ${N0} login --manual`))},T=>f({kind:"note",tone:"info",text:T})),b=eU(k.name,x);tU(b),await rd(b,k.name,T=>f({kind:"note",tone:"info",text:T}));let P=p0(b);if(P){let T=wt(e,s).project;await od(k.name,P,T.projectId===P?T.projectName:void 0)}if(f({kind:"note",tone:"ok",text:`\u2713 Logged in to "${k.name}" as ${Ua(vo(k.name,P??void 0)??b)}`}),await fg(s),!Lo.current){let T=st(e,s);T.ok||(f({kind:"note",tone:"warn",text:T.reason}),ue("/login"))}if(Lo.current){let T=Lo.current;Lo.current=null;let _=st(e,s);_.ok?(f({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 tab to run ${T}.`}),ue(T)):(f({kind:"note",tone:"warn",text:`${_.reason} (then ${T}.)`}),ue("/login"),Lo.current=T)}else Ms.current&&(ut(Ms.current,"\u21E5 tab to re-send your last prompt\u2026"),Ms.current=null)}catch(x){if(f({kind:"note",tone:"error",text:`Login failed: ${x.message}`}),!cl(e,s)){let b=Lo.current;f({kind:"note",tone:"warn",text:`Your Document360 session still isn't working, so nothing here can reach your portal${b?` \u2014 ${b} is still waiting`:""}. Run /login to try again.`}),ue("/login")}}finally{D(!1),H(x=>x+1)}return}case"allow-prod":{let k=!1;try{k=wt(e,s).production}catch{}if(!k){f({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}Pn.current=!0,Qe(),f({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let k=gh(y.join(" ")),v=Xe.current.uuid;if(!v){if(!k){f({kind:"note",tone:"info",text:"Usage: /rename <name>"});return}bu.current=k,Po(k),Ss(`${ou} ${k}`),f({kind:"note",tone:"ok",text:`Session will be named "${k}" once it starts.`});return}if(!k){f({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let x=Xe.current.firstPrompt??"";h0(x,e).then(b=>{b?(ut(`/rename ${b}`),f({kind:"note",tone:"info",text:`Suggestion: "${b}" \u2014 press tab to accept, or type /rename <your name>.`})):f({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>f({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}mU(v,k),Po(k),Ss(`${ou} ${k}`),f({kind:"note",tone:"ok",text:`Session renamed to "${k}".`});return}case"profile":{let k=y[0],v=Se(e);if(!k){let x=Object.entries(v?.profiles??{});if(x.length===0){f({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let b=x.map(([M,N])=>{let X=N.connection?.environment,j="";try{j=X?DU(X).portalUrl:N.connection?.portalUrl??""}catch{j=""}return{name:M,env:X??"custom",portalUrl:j,project:N.project?.projectName??N.project?.projectId??null,prod:N.production??jU(X),internal:IU(X),who:Wu(M)}}),P=s??v?.defaultProfile,T=Math.max(0,b.findIndex(M=>M.name===P)),_={name:"\uFF0B Connect another Document360 environment",env:"",portalUrl:"",project:null,prod:!1,internal:!1,who:null,connect:!0};Sr({cursor:T,current:T,rows:[...b,_]});return}if(k==="add"){if(!y[1]){Jn({cursor:0,mode:"connect",rows:oo()});return}let x=ni(e,y[1],y[2]);if(x){f({kind:"note",tone:"error",text:x});return}let[b,...P]=oi(y[1],y[2]??y[1]);f({kind:"note",tone:"ok",text:b});for(let T of P)f({kind:"note",tone:"warn",text:T});Na(y[1],!0);return}if(!v?.profiles?.[k]){f({kind:"note",tone:"error",text:`Unknown profile "${k}". Create it: /profile add ${k} <environment>`});return}Na(k,!0);return}case"doctor":await Ti(y,{cwd:e,version:o});return;case"logs":{let k=ad();f({kind:"note",tone:"info",text:k.lines.join(`
|
|
542
|
+
`)}),k.copyText&&In(k.copyText,{hint:k.notable?"\u2328 Press \u2303y to copy this problem report \u2014 then send it to the team (Teams / Slack / email).":"\u2328 Press \u2303y to copy this entry, if you want to send it to the team."});return}case"style-guide":{let k=kf(e);if(gs(y).sub==="use"){let x=bf(e,gs(y).value);if(x.pick){f({kind:"note",tone:"info",text:`${x.pick.title}
|
|
543
|
+
${x.pick.lead}`}),he(x.pick.options.map(b=>({cmd:b.cmd,desc:b.desc}))),Do(x.pick.title),$a.current=x.pick.options.map(b=>b.cmd.trim()),H(b=>b+1);return}if(x.lines.length>0&&f({kind:"note",tone:"info",text:x.lines.join(`
|
|
544
|
+
`)}),x.restart&&(Qe(),f({kind:"note",tone:"ok",text:"\u2713 Agent restarted \u2014 it now writes to the new rules."})),x.editorial){let b=dn(e,x.editorial.cmd);je($f(x.editorial).join(`
|
|
545
|
+
`),{kind:"cmd",cmd:x.editorial.cmd,reason:"it reads every article the new guide flagged and rewrites it",...b?{detail:b}:{}})}H(b=>b+1);return}let v=await Ac(y,{cwd:e,profileName:s});if(k&&gs(y).sub==="show"&&je(null,{kind:"cmd",cmd:"/style-guide keep",reason:""}),v.kind==="clear")Qe(),f({kind:"note",tone:"ok",text:"\u2713 Agent restarted \u2014 it now writes to the new rules."});else if(v.kind==="forward-to-agent"){let x=gs(y).sub==="learn";(await Te(v.prompt,{display:v.display,quietUser:!0})).producedNothing||(f({kind:"note",tone:"info",text:(x?x$():R$()).join(`
|
|
546
|
+
`)}),x&&(Qe(),f({kind:"note",tone:"ok",text:"\u2713 Agent restarted \u2014 it now writes to your house rules."})))}H(x=>x+1);return}case"genre":{let k=Se(e)?.appType??null;(await Mc(y,{cwd:e})).kind==="clear"&&(Se(e)?.appType??null)!==k&&(Qe(),f({kind:"note",tone:"ok",text:"\u2713 Agent restarted \u2014 the doc-craft playbook for this genre is now loaded."}));try{tt.current=!(Se(e)?.appType??y0(e))}catch{}H(x=>x+1);return}case"roadmap":{if(y[0]?.toLowerCase()==="done"){let k=Zr(e,y.slice(1).join(" ").trim());f({kind:"note",tone:k.ok?"ok":"warn",text:k.line}),H(v=>v+1);return}f({kind:"block",text:zd(e,{width:ct(),all:y.some(k=>k.toLowerCase()==="--all")}).join(`
|
|
547
|
+
`)});return}case"mcp":await il(y);return;case"init":{if(Se(e)){let k=Ve(e,s);f({kind:"note",tone:"info",text:["This repo is already set up \u2014 /init won\u2019t overwrite it."," Publish somewhere else: /profile, then pick \u201CConnect another Document360 environment\u201D."," The environment lives on the profile, not on your login \u2014 so signing in again never changes it.",` Anything else: edit ${pt}/config.json, or walk the questions again with: ${N0} init`].join(`
|
|
548
|
+
`)}),k&&f({kind:"note",tone:"warn",text:`\u26A0 ${k.why} \u2014 ${k.cmd} moves this repo.`});return}Jn({cursor:0,mode:"init",rows:oo()});return}case"resume":{let k=y.join(" ").trim(),v=fU(e).filter(P=>P.uuid!==Xe.current.uuid);if(!k){if(!v.length){f({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}Oo({query:"",cursor:0,sessions:v});return}let x=hU(e,k);if(!x){f({kind:"note",tone:"error",text:`No session matches "${k}".`});return}Qe(x.uuid),Xe.current={uuid:x.uuid,firstPrompt:x.firstPrompt,titleFired:!0},Po(x.name),Pm(x.uuid),ge.current=[],vt.current={printed:[],armed:[],printedAt:Dr.current};let b=km(e,x.uuid);for(let P of b)f(P);f({kind:"note",tone:"ok",text:b.length?`Resumed "${x.name}" \u2014 restored ${b.length} message(s); continue where you left off.`:`Resumed "${x.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let k=y.join(" ").trim(),v;try{v=await Js(e,s)}catch(b){f({kind:"note",tone:"error",text:`Could not list workspaces: ${b.message}`});return}if(!k){let b=v.workspaces.map(T=>({id:T.id,name:T.name??T.id,type:T.workspace_type}));if(b.length===0){f({kind:"note",tone:"info",text:"No workspaces in this project."});return}let P=Math.max(0,b.findIndex(T=>T.id===v.current));Cr({cursor:P,current:P,rows:b,profile:v.profile,projectId:v.projectId,projectName:v.projectName,environment:v.environment});return}let x=zu(v.workspaces,k);if(!x){f({kind:"note",tone:"error",text:`No workspace matches "${k}".`});return}Da(v.profile,v.projectId,x);return}case"project":{let k=y.join(" ").trim(),v;try{v=await Mn(e,s)}catch(b){f({kind:"note",tone:"error",text:`Could not list projects: ${b.message} (signed in? try /login)`});return}if(!k){let b=v.projects.map(T=>({id:T.id,name:T.name??T.id,sub:T.sub_domain}));if(b.length===0){f({kind:"note",tone:"info",text:"No projects found for this identity."});return}let P=b.findIndex(T=>T.id===v.current);To({cursor:Math.max(0,P),current:P,rows:b,profile:v.profile,environment:v.environment});return}let x=Xu(v.projects,k);if(!x){f({kind:"note",tone:"error",text:`No project matches "${k}". Available: ${v.projects.map(b=>b.name??b.id).join(", ")}`});return}Ia(v.profile,x);return}case"logout":{let k,v,x;try{let M=wt(e,s);k=M.name,v=M.project.projectId,x=M.project.projectName}catch(M){f({kind:"note",tone:"error",text:M.message});return}let b=y.includes("--all-projects"),P=lU(k).filter(M=>{let N=p0(M);return!!N&&N!==v}).length,T=iU(k,b?void 0:v);cU(e,k),Qe(),H(M=>M+1);let _=b||P===0?"":` Your sign-in for ${P} other project${P===1?"":"s"} is untouched (/logout --all-projects clears those too).`;f({kind:"note",tone:T?"ok":"info",text:T?b?`\u2713 Signed out of every Document360 project for "${k}" and cleared this repo's project/workspace selection.`:`\u2713 Signed out of ${x?`"${x}"`:`"${k}"`} and cleared its project/workspace selection.${_}`:`Profile "${k}" was not signed in. Cleared any project/workspace selection.${_}`}),f({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),ue("/login");return}case"publish":{if(ap(y)){f({kind:"note",tone:"info",text:Ol()}),await Ho(`/push ${y.join(" ")}`.trim());return}if(!Fo(h.trim()))return;let k=y.find(N=>!N.startsWith("--")),v={skipReview:y.includes(Vt),skipStyle:y.includes(A0),...k?{scope:k}:{}};He("Checking what is waiting to go live\u2026");let x;try{x=await lp(e,s,k)}catch(N){f({kind:"note",tone:"error",text:`Could not check Document360: ${N.message}`});return}finally{He(null)}if(x.length===0){let N=cp(e,s,k);for(let X of N.lines)f({kind:"note",tone:X.startsWith("\u2713")?"ok":"info",text:X});N.ahead>0&&ue(Ee("/push","",k));return}let b=fu(e,x.map(N=>N.path),{allowUnreviewed:v.skipReview,allowStyleErrors:v.skipStyle,checkScreenshots:!0,allowPlaceholders:y.includes(QU)}),P=XU(b),T=x.filter(N=>P.has(N.path)),_=x.filter(N=>!P.has(N.path)),M=_l(e,b,k);if(T.length>0)for(let N of jm(b,x.length,{scope:k,act:"publish",going:_.length,shotFix:M.shotFix}))f({kind:"note",tone:"warn",text:N});if(_.length===0){M.cmd&&ue(M.cmd);return}if(x=_,nt.current&&ga.current){f({kind:"note",tone:"info",text:`Taking ${x.length} draft${x.length===1?"":"s"} live \u2014 you approved this run when it started.`}),await ug(x,v);return}f({kind:"note",tone:"info",text:`${x.length} draft${x.length===1?" is":"s are"} ahead of what readers see. Pick what goes live:`}),Ar({cursor:0,rows:x,opts:v});return}case"push":{if(!Fo(h.trim()))return;let k=y.includes(Vt),v=y.includes(A0);if(y.includes("--preview")){let T=y.find(_=>!_.startsWith("--"));if(!T){f({kind:"note",tone:"error",text:"Which article? Use /push --preview <path> \u2014 a preview is per article."});return}try{let _=await PU({cwd:e,profileName:s,relPath:T.replace(/\\/g,"/"),preview:!0}),M=_.shots.length>0?` \xB7 ${_.shots.length} screenshot${_.shots.length===1?"":"s"} embedded`:"";f({kind:"note",tone:"info",text:`${_.title}
|
|
549
|
+
${_.path} \xB7 ${_.articleId?`updates article ${_.articleId}`:"would be created as a new article"}${M}`}),_.missingShots.length>0&&f({kind:"note",tone:"warn",text:`\u26A0 ${_.missingShots.length} screenshot${_.missingShots.length===1?"":"s"} not taken yet \u2014 the description publishes instead: ${_.missingShots.join(", ")}`}),f({kind:"note",tone:"info",text:_.body}),f({kind:"note",tone:"info",text:`Nothing was sent. /push ${_.path} saves it as a draft.`}),ue(`/push ${_.path}`)}catch(_){f({kind:"note",tone:"error",text:_.message})}return}if(y.includes("--screenshots")||y.includes("--shots")){let T=y.find(j=>!j.startsWith("--")),_=Ke(e),M=kl(_,T);if(M.length===0){let j=_.filter(B=>B.state==="captured").length;f({kind:"note",tone:"info",text:j>0?`${j} screenshot${j===1?" has":"s have"} been taken but the callouts aren't drawn on yet, so there is nothing to embed \u2014 /screenshot annotate finishes ${j===1?"it":"them"}.`:T?`No captured screenshots in ${T} \u2014 /push --screenshots covers the whole knowledge base.`:"No captured screenshots yet \u2014 /screenshot capture first."}),j>0&&ue("/screenshot annotate");return}let N=bl(_,T);N&&f({kind:"note",tone:"warn",text:N});let X=$l(_);X&&f({kind:"note",tone:"warn",text:X}),f({kind:"note",tone:"info",text:`Re-saving ${M.length} article${M.length===1?"":"s"} with captured screenshots so the images embed\u2026`}),await Tt(M,0,{skipReview:k,skipStyle:v,scope:Ee("","--screenshots",T).trim()});return}if(y[0]==="--related"&&y[1]){let T=await jl(e,s,y[1].replace(/\\/g,"/"));if(T.length===0){f({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await Tt(T,0,{skipReview:k,skipStyle:v,scope:`--related ${y[1]}`});return}let x=y.filter(T=>!T.startsWith("--"));if(x[0]){await Fu(x[0],{skipReview:k,skipStyle:v});return}let b=y.includes("--all"),P=y.includes("--force");f({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let T=await aa({cwd:e,profileName:s}),_=new Set(er(e,s)),{clean:M,conflicts:N}=Zo(T.entries,_),X=N.filter(q=>_.has(q.path)).length,j=b&&P&&N.length>0,B=Tl(T.entries);if(B>0&&f({kind:"note",tone:"warn",text:`\u26A0 ${B} article${B===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.`}),N.length>0&&!j&&f({kind:"note",tone:"warn",text:ui(N.length,X)}),M.length===0&&!j){let q=es(e,s);if(q&&f({kind:"note",tone:"info",text:q}),N.length>0){ue("/resolve");return}f({kind:"note",tone:"ok",text:B>0?"\u2713 Nothing else is ahead of Document360 to save.":"\u2713 Nothing is ahead of Document360 \u2014 nothing to save."});let se=T.counts["unknown-base"]??0;se>0&&f({kind:"note",tone:"info",text:`(${se} article(s) have no sync base yet \u2014 /push <path> saves one anyway if you need it.)`}),He("Reconciling structure on Document360 (order + related articles)\u2026");try{let ye=await Nm({cwd:e,profileName:s,onRateLimit:ee=>He(`Document360 rate limit \u2014 waiting ${Math.ceil(ee.waitMs/1e3)}s\u2026`)}),we=P0(await C0({cwd:e,profileName:s})),$e=Dm(ye);$e?f({kind:"note",tone:$e.startsWith("\u26A0")?"warn":"info",text:$e}):ye.skipped&&f({kind:"note",tone:"warn",text:`Order sync skipped: ${ye.skipped}`}),we&&f({kind:"note",tone:"info",text:we}),ye.failures?.length?ue("/structure"):(f({kind:"note",tone:"ok",text:$e||we?"\u2713 Structure synced to Document360 \u2014 /structure shows the new category + article order.":"\u2713 Already in order \u2014 nothing to change."}),($e||we)&&ue("/structure"))}catch(ye){f({kind:"note",tone:"warn",text:`Structure sync failed: ${ye.message}`})}finally{He(null)}return}if(b){let q=(j?[...M,...N]:M).map(se=>se.path);await Tt(q,j?0:N.length,{skipReview:k,skipStyle:v,allowUnpullable:P,unreadableSkipped:j?0:X});return}Pr({cursor:0,rows:Zw(M,N),conflicts:N.length})}catch(T){f({kind:"note",tone:"error",text:`Could not compute sync status: ${T.message}`}),f({kind:"note",tone:"info",text:"Save one article on its own: /push <article-path>"})}return}case"resolve":{if(!Fo(h.trim()))return;await Gu(y.find(k=>!k.startsWith("--")));return}case"preview":{let k=y.join(" ").trim();if(!k){let x=[];try{x=Object.keys(bU(e,wt(e,s).name)?.articles??{})}catch{}if(x.length===0){f({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}jo({query:"",cursor:0,paths:x});return}let v=QM(k)?k:ia(e,k);if(Ps(v)){try{f({kind:"preview",name:sa(v),text:O0(du(v,"utf8"))})}catch(x){f({kind:"note",tone:"error",text:`Could not read ${v}: ${x.message}`})}return}if(yF.test(k)){try{let x=wt(e,s),b={profile:x.name,connection:x.connection},P=x.project.projectId??rU(b),T=await sU(b,P,k);f({kind:"preview",name:T.title??k,text:T.content??"*(article has no content)*"})}catch(x){f({kind:"note",tone:"error",text:`Could not fetch article: ${x.message}`})}return}f({kind:"note",tone:"error",text:`"${k}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let k=y[0]?.trim();if(!k){let P=sc(Lm(e));Ao({cursor:P,current:P});return}let{lines:v,changed:x,effective:b}=Pi(e,k);for(let P of v)f({kind:"note",tone:P.startsWith("\u26A0")?"warn":P.startsWith("\u2713")?"ok":"info",text:P});x&&(Xm(P=>P+1),Pe.current?.setModel(b));return}case"verbose":{let k=y[0]?.trim().toLowerCase(),v=k==="on"?!0:k==="off"?!1:!fa.current;fa.current=v;try{wU({...g0(),verboseTranscript:v})}catch{f({kind:"note",tone:"warn",text:"\u26A0 Applied for this session, but the setting could not be saved."})}f({kind:"note",tone:"ok",text:v?"\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(!Se(e)){f({kind:"note",tone:"error",text:be});return}let{scope:k,run:v}=_p(y),x=_U(e,s);if(x.length===0){f({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Save some to Document360 first (/push), then /convert."});return}let b=Mp(x,k);if(b.length===0){f({kind:"note",tone:"error",text:`No tracked articles under "${k}". (${x.length} are tracked overall.)`});return}let P=Am(b),T=3,_=`/convert${k?` --scope ${k}`:""} --run`,M=ca(e,"light");if(!v){let j=$0({files:Up(e,b),op:"convert",model:M.model}),B=k?`Scope: ${k} (${b.length} of ${x.length} tracked)
|
|
550
550
|
`:"",q=`
|
|
551
|
-
Model: ${M.model}${M.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;f({kind:"note",tone:"info",text:B+
|
|
552
|
-
`)+q}),
|
|
553
|
-
`):B+
|
|
554
|
-
`)}),
|
|
551
|
+
Model: ${M.model}${M.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;f({kind:"note",tone:"info",text:B+Wp(P,j,T).join(`
|
|
552
|
+
`)+q}),ue(_);return}Zt.current=Date.now(),Jt(0),A(!0);let N=new AbortController;qe.current=N;let X=Date.now();xe({verb:"Converting",total:P.length,done:0,active:[],rows:yr(P),tools:0,chars:0,lastAt:Date.now(),startedAt:X}),f({kind:"note",tone:"info",text:`Converting ${b.length} articles in ${P.length} batches (\u2264${T} agents at once) on ${M.model}\u2026 (esc to stop)`});try{for await(let j of la({cwd:e,partitions:P,promptFor:Fp,concurrency:T,profileName:s,allowProdWrites:Pn.current,model:M.model,signal:N.signal}))if(j.type==="partition_status")j.status==="running"?xe(B=>B&&{...B,active:[...B.active,j.label],rows:dt(B.rows,j.label,"active"),lastAt:Date.now()}):xe(B=>B&&{...B,active:B.active.filter(q=>q!==j.label),done:B.done+1,rows:dt(B.rows,j.label,j.status==="done"?"done":"failed"),lastAt:Date.now()});else if(j.type==="partition_stalled"){let B=Rs(j);xe(q=>q&&B?{...q,stalledNote:B}:q)}else if(j.type==="partition_event")xe(B=>{if(!B)return B;let q={...B,lastAt:Date.now()};return j.event.type==="tool"?q.tools=B.tools+1:j.event.type==="text"&&(q.chars=B.chars+j.event.delta.length),q});else if(j.type==="run_done"){Uo(ye=>ye+j.totalCostUsd),Mo(ye=>ye+j.results.reduce((we,$e)=>we+$e.outputTokens,0));let B=j.aborted?"Stopped. ":"",q=t.kind==="api"?"api":"subscription",se=ho(j,"The conversion");f({kind:"note",tone:se||j.aborted?"warn":j.ok?"ok":"warn",text:se?se.join(`
|
|
553
|
+
`):B+Bp(j.results,P,q).join(`
|
|
554
|
+
`)}),Lr(X,j.results,j.totalCostUsd,!se&&!j.aborted&&j.ok),se&&ue("/doctor")}}catch(j){f({kind:"note",tone:"error",text:`Convert run failed: ${j.message}`})}finally{qe.current=null,xe(null),A(!1),H(j=>j+1)}return}case"write":{if(!Se(e)){f({kind:"note",tone:"error",text:be});return}let k=v0(e);if(k.length===0){f({kind:"note",tone:"error",text:`No docs plan found (${pt}/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure.`});return}let{scope:v,path:x,preview:b,concurrency:P,rewrite:T}=Ci(y);if(!x&&!b&&!(Se(e)?.appType??y0(e))){f({kind:"note",tone:"warn",text:`\u26A0 No doc genre is set, so no doc-craft playbook would load \u2014 all ${k.length} articles would be written generically.
|
|
555
555
|
Pick the genre below (one keypress), then run /write again \u2014 it changes structure, titles and depth for every article.
|
|
556
|
-
Not blocked: /write <path> still authors a single article, and /write --preview costs nothing.`}),
|
|
557
|
-
`:"",
|
|
558
|
-
Model: ${q.model}${q.forced?" (forced)":" \u2014 authoring; /model to override"}`;f({kind:"note",tone:"info",text:
|
|
559
|
-
`)+
|
|
560
|
-
`):
|
|
561
|
-
`)}),
|
|
562
|
-
`)})}if(!ee.aborted&&ee.ok){let
|
|
563
|
-
${k.map(
|
|
564
|
-
`)}`}),
|
|
565
|
-
`)});return}if(k==="--baseline"){let b=y.find(M=>!M.startsWith("--")),P=b?b.replace(/\\/g,"/"):void 0;f({kind:"note",tone:"info",text:P?`Setting the sync baseline for ${P}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let
|
|
566
|
-
${
|
|
567
|
-
`)}`}),H(M=>M+1);return}if(k==="--compare"){f({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let b=await
|
|
568
|
-
`)});return}if(k){f({kind:"note",tone:"error",text:`Unknown option: ${k} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let v=y[0];if(v){let b=v.replace(/\\/g,"/"),P;try{let
|
|
569
|
-
`)});return}}if(y[0]==="--auto"){let v=
|
|
570
|
-
`)});let _=
|
|
571
|
-
`)});for(let
|
|
572
|
-
\u26A0 ${
|
|
573
|
-
`)}),
|
|
574
|
-
`)}),P.length>0){let
|
|
575
|
-
`)});return}case"status":{let k=y.some(v=>v==="--all"||v==="--full");f({kind:"block",text:
|
|
576
|
-
`)}),re.current=!0;return}case"env":{let k=
|
|
577
|
-
`)});return}case"retire":{let k=y.find(x=>!x.startsWith("-"));if(!k){f({kind:"block",text:
|
|
578
|
-
`)}),re.current=!0;return}let v=
|
|
579
|
-
`)}),
|
|
556
|
+
Not blocked: /write <path> still authors a single article, and /write --preview costs nothing.`}),he(Uc.options.map(ee=>({cmd:ee.cmd,desc:ee.desc}))),Do(Uc.title);return}let{docsDir:_,targets:M,reason:N,rewriting:X}=oc(e,k,{scope:v,path:x,rewrite:T});if(M.length===0){f({kind:"note",tone:"warn",text:N??"Nothing to write."});return}X&&f({kind:"note",tone:"warn",text:`--rewrite: regenerating ${M.length} already-written article${M.length===1?"":"s"} (overwrites them; git has your baseline).`});let j=Am(M),B=Zp(P),q=ca(e,"standard"),se=!!x;if(b&&!se){let ee=$0({files:eh(e,k,M),op:"write",model:q.model}),Ae=v?`Scope: ${v} (${M.length} pending)
|
|
557
|
+
`:"",Ue=`
|
|
558
|
+
Model: ${q.model}${q.forced?" (forced)":" \u2014 authoring; /model to override"}`;f({kind:"note",tone:"info",text:Ae+nh(j,ee,B).join(`
|
|
559
|
+
`)+Ue}),ue(`/write${v?` --scope ${v}`:""}`);return}Zt.current=Date.now(),Jt(0),A(!0);let ye=new AbortController;qe.current=ye;let we=Date.now();xe({verb:"Writing",total:j.length,done:0,active:[],rows:yr(j),tools:0,chars:0,lastAt:Date.now(),startedAt:we}),f({kind:"note",tone:"info",text:`Writing ${M.length} article${M.length===1?"":"s"} in ${j.length} batch${j.length===1?"":"es"} (\u2264${B} agents at once) on ${q.model}${q.forced?" (forced)":""}\u2026 (esc to stop)`});let $e=new Set;try{for await(let ee of la({cwd:e,partitions:j,promptFor:Ae=>th(Ae,_,{rewrite:X||se}),concurrency:B,profileName:s,allowProdWrites:Pn.current,model:q.model,signal:ye.signal}))if(ee.type==="partition_status")ee.status==="running"?xe(Ae=>Ae&&{...Ae,active:[...Ae.active,ee.label],rows:dt(Ae.rows,ee.label,"active"),lastAt:Date.now()}):xe(Ae=>Ae&&{...Ae,active:Ae.active.filter(Ue=>Ue!==ee.label),done:Ae.done+1,rows:dt(Ae.rows,ee.label,ee.status==="done"?"done":"failed"),lastAt:Date.now()});else if(ee.type==="partition_stalled"){let Ae=Rs(ee);xe(Ue=>Ue&&Ae?{...Ue,stalledNote:Ae}:Ue)}else if(ee.type==="partition_event"){let Ae=null;if(ee.event.type==="tool"){let Ue=Rm(ee.event.name,ee.event.input,j[ee.index]?.paths??[]);Ue&&!$e.has(Ue)&&($e.add(Ue),Ae=ee.label)}xe(Ue=>{if(!Ue)return Ue;let sn={...Ue,lastAt:Date.now()};return ee.event.type==="tool"?sn.tools=Ue.tools+1:ee.event.type==="text"&&(sn.chars=Ue.chars+ee.event.delta.length),Ae&&(sn.rows=iu(sn.rows,Ae)),sn})}else if(ee.type==="run_done"){Uo(ot=>ot+ee.totalCostUsd),Mo(ot=>ot+ee.results.reduce((Rt,Go)=>Rt+Go.outputTokens,0));let Ae=ee.aborted?"Stopped. ":"",Ue=t.kind==="api"?"api":"subscription",sn=ho(ee,"The write");if(f({kind:"note",tone:sn||ee.aborted?"warn":ee.ok?"ok":"warn",text:sn?sn.join(`
|
|
560
|
+
`):Ae+oh(ee.results,j,Ue,v??x).join(`
|
|
561
|
+
`)}),Lr(we,ee.results,ee.totalCostUsd,!sn&&!ee.aborted&&ee.ok),sn){ue("/doctor");continue}let bg=Sk(ee);if(bg&&f({kind:"note",tone:"warn",text:bg}),!ee.aborted&&ee.ok)try{let ot=($e.size>0?[...$e]:M).map(Rt=>`${_}/${Rt}`);Ts(e,ot,{writtenCap:HU,reviewedCap:0,checkedCap:0})}catch{}let $g=ee.aborted||y.includes("--skip-style"),_n=ee.aborted?[]:sr(e,_,M);if(!$g){let ot=sh(e,_,M,_n);_n=ot.findings;for(let Rt of ot.lines)f({kind:"note",tone:"ok",text:Rt})}let vg=rh(_n);vg&&f({kind:"note",tone:"warn",text:vg});let Mr=$g?null:ih(_n);if(Mr){let ot=Mr.errors.length,Rt=await Ta({partitions:Mr.partitions,promptFor:Mr.promptFor,concurrency:as,verb:"Fixing",doneNoun:"fixed",headline:`${ot} style error${ot===1?"":"s"} in ${Mr.articles} of the new article${Mr.articles===1?"":"s"} \u2014 fixing now, one pass`});if(Rt.covered.length>0)try{Ts(e,Rt.covered,St("lint"))}catch{}_n=sr(e,_,M);let Go=ah(ot,_n);f({kind:"note",tone:Go[0].startsWith("\u2713")?"ok":"warn",text:Go.join(`
|
|
562
|
+
`)})}if(!ee.aborted&&ee.ok){let ot=v??x??"",Rt=ot?` ${ot}`:"",Go=_n.some(Ur=>Ur.severity==="error");{let Ur=Tm(j,ee.results);On(`/write${v?` --scope ${v}`:""}${y.includes("--rewrite")?" --rewrite":""}`,{aborted:ee.aborted,partitions:j.length,failed:Ur.failed.length,notRun:Ur.notRun.length,leftBehind:_n.filter(rR=>rR.severity==="error").length,...ee.blocked?{blocked:ee.blocked}:{},...ee.allEmpty?{allEmpty:!0}:{},...ee.bailedEmpty?{bailedEmpty:!0}:{}})}let xg=ot?"/push":"/push --all",oR=ot?`/screenshot author ${ot}`:"/screenshot author --all";je(Go?`Written, but ${_n.filter(Ur=>Ur.severity==="error").length} style error(s) are still unfixed. /lint${Rt} --blocked --fix retries them, then /review${Rt} --fix for editorial quality, then ${xg}.`:`Written. I\u2019d run /review${Rt} --fix next \u2014 editorial review that applies its fixes \u2014 then ${xg} saves them to Document360 as drafts (add ${oR} first if you want images).`,{kind:"cmd",cmd:Go?`/lint${Rt} --blocked --fix`:`/review${Rt} --fix`,reason:""})}}}catch(ee){f({kind:"note",tone:"error",text:`Write run failed: ${ee.message}`})}finally{qe.current=null,xe(null),A(!1),H(ee=>ee+1)}return}case"draft":{if(!Se(e)){f({kind:"note",tone:"error",text:be});return}let{features:k,looseDocs:v}=ch(e);if(k.length===0&&v===0){f({kind:"note",tone:"info",text:dh});return}let x=y.join(" ").trim();if(!x&&k.length>1){f({kind:"note",tone:"info",text:`Multiple features in ${pt}/input/ \u2014 draft which one?
|
|
563
|
+
${k.map(T=>` \u2022 ${T.name} (${T.docCount} doc${T.docCount===1?"":"s"})`).join(`
|
|
564
|
+
`)}`}),he(k.map(T=>`/draft ${T.name}`));return}let b="",P;if(x){let T=uh(k,x);T?b=T:P=x}else b=k[0]?.name??"";await Te(rc(b,P),{display:x?`/draft ${x}`:"/draft",quietUser:!0});return}case"pull":{if(!Fo(h.trim()))return;let k=y.find(v=>v.startsWith("--"));try{if(k==="--status"){f({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let b=Date.now(),P=await aa({cwd:e,profileName:s});f({kind:"note",tone:"info",text:Bl(P,Date.now()-b).join(`
|
|
565
|
+
`)});return}if(k==="--baseline"){let b=y.find(M=>!M.startsWith("--")),P=b?b.replace(/\\/g,"/"):void 0;f({kind:"note",tone:"info",text:P?`Setting the sync baseline for ${P}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let T=await TU({cwd:e,profileName:s,relPaths:P?[P]:void 0}),_=P?{rebaselined:[],skipped:[]}:await EU({cwd:e,profileName:s});if(T.baselined.length===0&&T.skipped.length===0&&_.rebaselined.length===0){f({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}T.baselined.length>0&&f({kind:"note",tone:"ok",text:`\u2713 Recorded ${T.baselined.length} article${T.baselined.length===1?"":"s"} as matching Document360 \u2014 they read in-sync until either side changes.`}),_.rebaselined.length>0&&f({kind:"note",tone:"ok",text:`\u2713 Refreshed the metadata baseline for ${_.rebaselined.length} article${_.rebaselined.length===1?"":"s"} \u2014 cleared false "metadata changed" drift.`}),T.skipped.length>0&&f({kind:"note",tone:"warn",text:`${T.skipped.length} skipped:
|
|
566
|
+
${T.skipped.map(M=>` - ${M.path} (${M.reason})`).join(`
|
|
567
|
+
`)}`}),H(M=>M+1);return}if(k==="--compare"){f({kind:"note",tone:"info",text:"Comparing the manifest against the per-article path (read-only)\u2026"});let b=await RU({cwd:e,profileName:s}),P=b.onlyInLegacy.length===0&&b.onlyInManifest.length===0&&b.mappedMissingFromManifest.length===0,T=[`Legacy listing: ${b.legacyCount} \xB7 Manifest: ${b.manifestCount} \xB7 in both: ${b.inBoth}`];P?T.push("\u2713 Parity \u2014 the manifest sees exactly the same articles. Safe to make it the default sync source."):(b.mappedMissingFromManifest.length&&T.push(`\u2717 ${b.mappedMissingFromManifest.length} MAPPED article(s) missing from the manifest: ${b.mappedMissingFromManifest.slice(0,5).join(", ")}`),b.onlyInLegacy.length&&T.push(`\u26A0 ${b.onlyInLegacy.length} only in the legacy listing: ${b.onlyInLegacy.slice(0,5).join(", ")}`),b.onlyInManifest.length&&T.push(`\u26A0 ${b.onlyInManifest.length} only in the manifest: ${b.onlyInManifest.slice(0,5).join(", ")}`),T.push("Send me this \u2014 a mismatch pinpoints where the manifest differs before we flip.")),f({kind:"note",tone:P?"ok":"warn",text:T.join(`
|
|
568
|
+
`)});return}if(k){f({kind:"note",tone:"error",text:`Unknown option: ${k} \u2014 use /pull, /pull <path>, /pull --status, or /pull --baseline.`});return}let v=y[0];if(v){let b=v.replace(/\\/g,"/"),P;try{let T=await w0({cwd:e,profileName:s,relPath:b});P={plan:T,mode:T.overwritesLocalChanges?"conflict":"pull"}}catch(T){if(!k0(T))throw T;P={mode:"local-only",path:b,title:b0(e,b)}}_e.current=[P],en.current=[],An.current=[],Or();return}f({kind:"note",tone:"info",text:"Pulling changes from Document360\u2026"});let x=await Sp({cwd:e,profileName:s});for(let b of Cp(x))f({kind:"note",tone:b.tone,text:b.text});H(b=>b+1)}catch(v){f({kind:"note",tone:"error",text:`Pull failed: ${v.message}`})}return}case"scope":{if(!Se(e)){f({kind:"note",tone:"error",text:be});return}let k=NU(e);if(k.length===0){f({kind:"note",tone:"info",text:`No candidate source folders found. Set "authoritativeSourceFiles" in ${pt}/config.json manually.`});return}Tr({cursor:0,rows:k.map(v=>({...v,checked:v.recommended}))});return}case"audit":{{let v=Ul(e,y);if(v){f({kind:"note",tone:v[0].startsWith("\u2713")?"ok":"info",text:v.join(`
|
|
569
|
+
`)});return}}if(y[0]==="--auto"){let v=Se(e);if(!v){f({kind:"note",tone:"error",text:be});return}let x=y[1]!=="off";f0({...v,autoAudit:x},e),f({kind:"note",tone:"ok",text:x?"\u2713 Auto-audit ON \u2014 when you launch with code changes since the last audit, I\u2019ll run /audit automatically. (/audit --auto off to disable.)":"\u2713 Auto-audit OFF \u2014 I\u2019ll just nudge you to run /audit when code changed."});return}if(!Fo(h.trim()))return;let k=await gi({cwd:e,profileName:s});if(k.kind==="audit-blocked"){je(k.note,{kind:"cmd",cmd:k.lead.cmd,reason:k.lead.reason},"warn");return}if(k.kind==="forward-to-agent"&&k.prompt){let v=await Te(k.prompt,{display:k.display,quietUser:!0}),x=Ml(e,s);if(x){je(x.note,{kind:"cmd",cmd:ts.cmd,reason:ts.reason},"warn"),H(b=>b+1);return}v.producedNothing||(Qi(e,s),H(b=>b+1))}return}case"lint":case"check":{let k=mi(d);k&&f({kind:"note",tone:"info",text:`\u2192 ${k}`});let v=y.find(T=>!T.startsWith("--")),x=v?` ${v}`:"",b=As({cwd:e,scope:v}),P=Hn(b,y);if(y.includes("--fix")){let T=$n(e,y,b);T.lines.length>0&&f({kind:"note",tone:"ok",text:T.lines.join(`
|
|
570
|
+
`)});let _=T.fixed>0?As({cwd:e,scope:v}):b,M=Vp(e,y,_);if(!M){let ee=Kp(e,y,_);f({kind:"note",tone:"ok",text:ee.lines.join(`
|
|
571
|
+
`)});for(let Ae of ee.closed)f({kind:"note",tone:"ok",text:Ae});return}let N={aborted:!1,partitions:0,failed:0,notRun:0};if(M.kind==="partitioned"){let ee=await Ta({partitions:M.partitions,promptFor:M.promptFor,concurrency:as,verb:"Fixing",doneNoun:"fixed",headline:`Fixing ${M.findings} issue${M.findings===1?"":"s"} across ${M.articles} article${M.articles===1?"":"s"} in ${M.partitions.length} batches (\u2264${as} at once)`,calibrateAs:"/lint"});if(N=ee.outcome,ee.covered.length>0)try{Ts(e,ee.covered,St("lint"))}catch{}if(ee.aborted){let Ae=fi({cwd:e,after:Hn(As({cwd:e,scope:v}).filter(Ue=>!Ue.baselined),y),scope:v,aborted:!0,blocked:Bn(y)});je(Ae.text,{kind:"cmd",cmd:Ae.cmd,reason:""},"warn");return}}else{f({kind:"note",tone:"info",text:`Fixing ${M.findings} doc issue${M.findings===1?"":"s"}\u2026`});let ee=BU(e,v);await Te(M.prompt,{display:M.display,quietUser:!0});try{Ts(e,ee,St("lint"))}catch{}}let X=Hn(As({cwd:e,scope:v}).filter(ee=>!ee.baselined),y),j=Hn(_.filter(ee=>!ee.baselined),y),B=new Set(X.map(ee=>ee.fp)),q=new Set(j.map(ee=>ee.fp)),se=j.filter(ee=>!B.has(ee.fp)).length,ye=X.filter(ee=>!q.has(ee.fp)).length,we=ye>0?`
|
|
572
|
+
\u26A0 ${ye} new ${ye===1?"issue":"issues"} appeared in the rewrites \u2014 recasting a sentence is where these come from.`:"";f({kind:"note",tone:X.some(ee=>ee.severity==="error")?"warn":"ok",text:X.length===0?`\u2713 Lint: all ${j.length} issue${j.length===1?"":"s"} resolved.`:[`\u2713 Lint: fixed ${se} of ${j.length}.${we}`,"",...xi(X)].join(`
|
|
573
|
+
`)}),On(vi(y,v),M.kind==="partitioned"?N:{aborted:!1,partitions:0,failed:0,notRun:0,verifiedComplete:X.length===0});let $e=fi({cwd:e,after:X,before:M.findings,scope:v,blocked:Bn(y)});je($e.text,{kind:"cmd",cmd:$e.cmd,reason:""});return}if(f({kind:"note",tone:P.length===0?"ok":"warn",text:xi(P,{full:y.includes("--full"),baselined:y.includes("--baselined")}).join(`
|
|
574
|
+
`)}),P.length>0){let T=Nl(e,v)===0&&Dl(e,v)===0?"; /push --all saves them to Document360 as-is":"",_=`/lint${x}${Bn(y)?" --blocked":""} --fix`,M=dn(e,_);je(`Found ${P.length} doc issue${P.length===1?"":"s"} above. ${_} has the agent fix them in place${M?` (${M})`:""} \u2014 or /review${x} --fix for the full editorial pass${T}.`,{kind:"cmd",cmd:_,reason:""})}return}case"structure":{let k=ws(e,s);if(k.length===0){f({kind:"note",tone:"info",text:"No documentation structure yet \u2014 run /init and author some articles first."});return}f({kind:"note",tone:"info",text:["Documentation order (categories \u2192 articles):","",...k].join(`
|
|
575
|
+
`)});return}case"status":{let k=y.some(v=>v==="--all"||v==="--full");f({kind:"block",text:Uf(e,{profileName:s,all:k,width:ct()}).join(`
|
|
576
|
+
`)}),re.current=!0;return}case"env":{let k=cd(e,y);f({kind:"block",text:k.lines.join(`
|
|
577
|
+
`)});return}case"retire":{let k=y.find(x=>!x.startsWith("-"));if(!k){f({kind:"block",text:Ff(e,s).join(`
|
|
578
|
+
`)}),re.current=!0;return}let v=E0(e,k)||k;if(!y.includes("--yes")&&!y.includes("-y")){f({kind:"note",tone:"warn",text:[`\u26A0 This takes "${v}" off your readers on Document360.`," The article, its history and every reviewer comment stay \u2014 nothing is deleted."," /push puts it back later if you change your mind."].join(`
|
|
579
|
+
`)}),ut(`/retire ${v} --yes`,"tab to take it off your readers \xB7 or keep typing");return}A(!0);try{let x=await tF({cwd:e,path:v,profileName:s,now:new Date().toISOString()});f(x.ok?{kind:"note",tone:"ok",text:x.alreadyHidden?`\u2713 "${v}" was already invisible to readers. Recorded as retired, so nothing will offer to publish it again.
|
|
580
580
|
It stays on Document360 with its history and comments intact. /push puts it back.`:`\u2713 "${v}" is no longer visible to your readers.
|
|
581
|
-
It stays on Document360 with its history and comments intact. /push puts it back.`}:{kind:"note",tone:"error",text:`\u2717 Could not retire "${v}" \u2014 ${x.error.message}`})}finally{
|
|
582
|
-
`)}),re.current=!0;return}if(!k){f({kind:"note",tone:"warn",text:"\u2717 Name what to put back: /untrack --undo <path>"});return}let v=
|
|
583
|
-
`)}),
|
|
584
|
-
`)}:{kind:"note",tone:"error",text:`\u2717 Could not untrack "${v}" \u2014 ${x.error.message}`});return}case"eval":{f({kind:"block",text:
|
|
585
|
-
`)}),re.current=!0;return}case"terms":{let k=y.findIndex(v=>v==="--approve");if(k!==-1){let v=y[k+1];f(v?{kind:"block",text:
|
|
586
|
-
`)}:{kind:"note",tone:"warn",text:'\u2717 Name the spelling to approve, e.g. /terms --approve "drop-down".'}),re.current=!0;return}f({kind:"block",text:
|
|
587
|
-
`)}),re.current=!0;return}case"reuse":{let k=y.find(v=>!v.startsWith("--"));if(k==="pull"){(async()=>{let v=await
|
|
588
|
-
`)});for(let x of
|
|
589
|
-
`)}),re.current=!0;return}let{picks:b,bad:P}=
|
|
590
|
-
`)}),f({kind:"block",text:
|
|
591
|
-
`)});for(let M of
|
|
592
|
-
`)});for(let x of
|
|
593
|
-
`)}),(async()=>(await
|
|
594
|
-
`)})))(),re.current=!0;return}if(k==="add"){let v=
|
|
595
|
-
`)}),x.restart&&
|
|
596
|
-
`)}),re.current=!0;return}case"reorder":{let k=
|
|
597
|
-
`)})}let j=x&&!M.producedNothing?
|
|
598
|
-
`)}),j.length>0){let
|
|
599
|
-
`)}),
|
|
600
|
-
`)});return}try{let v=
|
|
601
|
-
`)})}catch(v){f({kind:"note",tone:"warn",text:`Could not file the question: ${v.message}`})}return}case"inbox":{if(!
|
|
602
|
-
`)});return}if(k.answer&&(k.all||k.scope.path||k.scope.scope||x.length===1)){
|
|
603
|
-
Windows can't replace the files while
|
|
604
|
-
|
|
605
|
-
Full output: ${
|
|
606
|
-
`)});return}if(k.mode==="list"){if(!
|
|
607
|
-
`)});let X=
|
|
608
|
-
`)}),v&&f({kind:"note",tone:"info",text:v});let M=
|
|
609
|
-
`)}),
|
|
610
|
-
Press s in /profile to use a profile for one session only.`});for(let P of b)f({kind:"note",tone:"warn",text:P});ua(k,!0);return}if(!_u(e,d).created){f({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer/config.json already exists."});return}f({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer/config.json (environment "${d}").`});let I=!1;try{let O=mo(d);I=!!O&&!(ar(O)&&!O.refreshToken)}catch{I=!1}f({kind:"note",tone:"info",text:I?`Next: sign in to ${d} and pick your project \u2014 you're already signed in here, so it'll be quick.`:`Next: sign in to Document360 (${d}) and pick your project.`}),ce("/login"),H(O=>O+1);return}if(g.escape){qn(null);return}return}if(ut){if(g.upArrow){fr(d=>d&&{...d,cursor:Math.max(0,d.cursor-1)});return}if(g.downArrow){fr(d=>d&&{...d,cursor:Math.min(d.rows.length-1,d.cursor+1)});return}if(h&&/^[0-9]$/.test(h)){let d=Sn(h,ut.rows.length);d!==null&&fr(y=>y&&{...y,cursor:d});return}if(g.return){let d=ut.rows[ut.cursor],{profile:y,projectId:E}=ut;fr(null),da(y,E,d);return}if(g.escape){fr(null);return}return}if(ft){if(g.upArrow){vo(d=>d&&{...d,cursor:Math.max(0,d.cursor-1)});return}if(g.downArrow){vo(d=>d&&{...d,cursor:Math.min(d.rows.length-1,d.cursor+1)});return}if(h&&/^[0-9]$/.test(h)){let d=Sn(h,ft.rows.length);d!==null&&vo(y=>y&&{...y,cursor:d});return}if(g.return){let d=ft.rows[ft.cursor],{profile:y}=ft;vo(null),ha(y,d);return}if(g.escape){vo(null);return}return}if(mt){if(g.upArrow){yr(d=>d&&{...d,cursor:Math.max(0,d.cursor-1)});return}if(g.downArrow){yr(d=>d&&{...d,cursor:Math.min(d.rows.length-1,d.cursor+1)});return}if(h===" "){yr(d=>d&&{...d,rows:d.rows.map((y,E)=>E===d.cursor?{...y,checked:!y.checked}:y)});return}if(g.return){let d=mt.rows.filter(y=>y.checked).map(y=>y.path);if(yr(null),d.length===0){f({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}_d(e,d),f({kind:"note",tone:"ok",text:`\u2713 Scoped to ${d.length} folder(s) \u2014 written to .d360-writer/config.json`});for(let y of d)f({kind:"note",tone:"info",text:` ${y}`});f({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(g.escape){yr(null);return}return}if(vt){if(g.upArrow){Ro(d=>d&&{...d,cursor:Math.max(0,d.cursor-1)});return}if(g.downArrow){Ro(d=>d&&{...d,cursor:Math.min(d.rows.length-1,d.cursor+1)});return}if(h&&/^[0-9]$/.test(h)){let d=Sn(h,vt.rows.length);d!==null&&Ro(y=>y&&{...y,cursor:d});return}if(g.return){let d=vt.rows[vt.cursor],y=vt.run;Ro(null),y(d.token);return}if(g.escape){Ro(null);return}return}if(It){if(g.upArrow){mr(d=>d&&{...d,cursor:Math.max(0,d.cursor-1)});return}if(g.downArrow){mr(d=>d&&{...d,cursor:Math.min(d.rows.length-1,d.cursor+1)});return}if(h&&/^[0-9]$/.test(h)){let d=Sn(h,It.rows.length);d!==null&&mr(y=>y&&{...y,cursor:d});return}if(g.return){let d=It.rows[It.cursor],y=It.conflicts;mr(null),d.conflict?hu(d.paths[0]):d.kind==="article"?cu(d.paths[0]):Rt(d.paths,d.kind==="all"?y:0);return}if(g.escape){mr(null);return}return}if(Qt){if(g.upArrow){gr(d=>d&&{...d,cursor:Math.max(0,d.cursor-1)});return}if(g.downArrow){gr(d=>d&&{...d,cursor:Math.min(d.rows.length,d.cursor+1)});return}if(h&&/^[0-9]$/.test(h)){let d=Sn(h,Qt.rows.length+1);d!==null&&gr(y=>y&&{...y,cursor:d});return}if(g.return){let{cursor:d,rows:y,opts:E}=Qt;gr(null);let I=d===0?y:[y[d-1]];$m(I,E);return}if(g.escape){gr(null),f({kind:"note",tone:"info",text:"Left as drafts \u2014 nothing changed. /publish when they have been signed off."});return}return}if(Lt){let{rows:d}=Lt;if(g.upArrow){Rn(y=>y&&{...y,cursor:Math.max(0,y.cursor-1)});return}if(g.downArrow){Rn(y=>y&&{...y,cursor:Math.min(d.length-1,y.cursor+1)});return}if(h&&/^[0-9]$/.test(h)){let y=Af(Jf.current,Number(h),d.length-1);Jf.current=y.memory,y.index!==null&&Rn(E=>E&&{...E,cursor:y.index+1});return}if(h==="a"||h==="A"){Rn(y=>y&&{...y,cursor:0});return}if(g.return){let y=d[Lt.cursor],{groups:E,resolve:I,report:O}=Lt;if(Rn(null),y.kind==="all"){lu(E,{resolve:I,report:O});return}vr(Vl(y.group,{width:at()})),ws({group:y.group,cursor:0,fromList:!0,resolve:I,rest:E.filter(k=>k.articleId!==y.group.articleId),report:O});return}if(g.escape){Rn(null),ce("/comments");return}return}if(pt){let d=()=>{let{rest:y,group:E,fromList:I,resolve:O,report:k}=pt;if(ws(null),!I||!k){ce("/comments");return}let v=[E,...y].sort((x,b)=>x.category.localeCompare(b.category)||x.title.localeCompare(b.title));Rn({cursor:0,rows:Kl(v),groups:v,resolve:O,report:k})};if(g.upArrow||g.downArrow){ws(y=>y&&{...y,cursor:y.cursor===0?1:0});return}if(h==="y"||h==="Y"||g.return&&pt.cursor===0){let{group:y,resolve:E,rest:I,report:O}=pt;ws(null),lu([y],{resolve:E,rest:I,...O?{report:O}:{}});return}if(h==="b"||h==="B"||g.escape||g.return){d();return}return}if(Jt){if(g.upArrow){xo(d=>d&&{...d,cursor:Math.max(0,d.cursor-1)});return}if(g.downArrow){xo(d=>d&&{...d,cursor:Math.min(d.rows.length-1,d.cursor+1)});return}if(h&&/^[0-9]$/.test(h)){let d=Sn(h,Jt.rows.length);d!==null&&xo(y=>y&&{...y,cursor:d});return}if(g.return){let d=Jt.rows[Jt.cursor];xo(null),d.action==="capture"?Ds(d.ids,{runLine:d.kind==="all"?["/screenshot capture --all","/capture --all"]:void 0}):d.action==="annotate"?ca(d.ids,{verifiedBefore:new Set(qe(e).filter(y=>y.state==="verified").map(y=>y.id))}):d.kind==="shot"?Rm(d.ids[0]):xm(d.ids,{setup:!0,runLine:d.kind==="all"?["/screenshot author --all","/screenshot --all"]:void 0});return}if(g.escape){xo(null);return}return}if(Ot){if(g.escape){Co(null);return}if(g.upArrow){Co(d=>d&&{...d,cursor:Math.max(0,d.cursor-1)});return}if(g.downArrow){Co(d=>d&&{...d,cursor:Math.min(Math.max(0,sa.length-1),d.cursor+1)});return}if(g.return){let d=sa[Ot.cursor];if(d){Co(null);try{f({kind:"preview",name:Fi(d),text:D0(_c(Ui(e,d),"utf8"))})}catch(y){f({kind:"note",tone:"error",text:`Could not read ${d}: ${y.message}`})}}return}if(g.backspace||g.delete){Co(d=>d&&{...d,query:d.query.slice(0,-1),cursor:0});return}if(h&&!g.ctrl&&!g.meta&&h.length===1){Co(d=>d&&{...d,query:d.query+h,cursor:0});return}return}if(_t){if(g.escape){Ao(null);return}if(g.upArrow){Ao(d=>d&&{...d,cursor:Math.max(0,d.cursor-1)});return}if(g.downArrow){Ao(d=>d&&{...d,cursor:Math.min(Math.max(0,ia.length-1),d.cursor+1)});return}if(g.return){let d=ia[_t.cursor];if(d){Ao(null),ze(d.uuid),Ye.current={uuid:d.uuid,firstPrompt:d.firstPrompt,titleFired:!0},bo(d.name),Mf(d.uuid),me.current=[],yt.current={printed:[],armed:[],printedAt:br.current};let y=Ef(e,d.uuid);for(let E of y)f(E);f({kind:"note",tone:"ok",text:y.length?`Resumed "${d.name}" \u2014 restored ${y.length} message(s); continue where you left off.`:`Resumed "${d.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(g.backspace||g.delete){Ao(d=>d&&{...d,query:d.query.slice(0,-1),cursor:0});return}if(h&&!g.ctrl&&!g.meta&&h.length===1){Ao(d=>d&&{...d,query:d.query+h,cursor:0});return}return}if(g.tab&&!m&&K){$(K),Zt();return}if(!m&&ae.length>0&&!je.current&&h&&/^[1-9]$/.test(h)){let d=ae[Number(h)-1];if(d){$(fo(d));return}}if(!m&&ae.length===0&&!je.current&&yt.current.armed.length>0&&h&&/^[1-9]$/.test(h)){let d=yt.current.armed[Number(h)-1];if(d){$(d);return}}if(!m&&(Ps||Yn)&&g.ctrl&&h==="y"){bm();return}if(!Em(h,g)){if(su){if(g.upArrow){Hn(d=>Math.max(0,d-1));return}if(g.downArrow){Hn(d=>Math.min(An.length-1,d+1));return}if(g.tab){$("/"+(An[cr]?.name??"")+" "),Hn(0);return}if(g.return){let d=An[cr];if(d){let y=m.trim().slice(1).split(/\s+/).slice(1).join(" ");if(jw(d.usage)&&!y){$("/"+d.name+" "),Hn(0);return}js("/"+d.name+(y?" "+y:""));return}}}else{if(!m&&ae.length>0&&!je.current&&(g.upArrow||g.downArrow)){if(g.downArrow){Gn(d=>d===null?0:Math.min(ae.length-1,d+1));return}if(kn!==null){Gn(d=>d===null||d===0?null:d-1);return}}if(g.upArrow){if(m!==""&&Dt===null){fa(-1);return}let d=Bc.current;if(!d.length)return;let y=Dt===null?d.length-1:Math.max(0,Dt-1);ur(y),$(d[y]??"");return}if(g.downArrow){if(m!==""&&Dt===null){fa(1);return}let d=Bc.current;if(Dt===null)return;let y=Dt+1;y>=d.length?(ur(null),$("")):(ur(y),$(d[y]??""));return}}if(g.return){if(kn!==null&&!m&&ae[kn]){let d=fo(ae[kn]);Gn(null),js(d);return}js();return}if(g.backspace||g.delete){C();return}if(g.escape){et.current&&(Vn.current=!0,Ns({kind:"stopped",how:"esc"},et.current.parked)),$(""),Hn(0),Zt(),pe([]),So(null),Gn(null),re.current=!0;return}h&&!g.ctrl&&!g.meta&&Tm(h)}}}),dt(()=>{if(S||R)return;let h=Po.current.shift();h!==void 0&&(Gc([...Po.current]),js(h))},[S,R,js]),we(Oe,{flexDirection:"column",width:wt,children:[au!==null&&we(Oe,{marginTop:1,flexDirection:"column",children:[au.truncated&&Y(z,{dimColor:!0,children:"\u2026"}),Y(z,{children:au.text})]}),wr?Y(v6,{step:wr.step,cmd:wr.cmd,startedAt:wr.startedAt,spentUsd:Math.max(wr.spentUsd,Mt-(et.current?.stepStartedSpend??Mt)),budgetUsd:wr.budgetUsd}):null,S&&kr?Y(S6,{p:kr}):null,rm?Y(x6,{text:rm}):S&&!kr?Y($6,{startTime:Yt.current,chars:qi}):null,Y(Oe,{borderStyle:"round",borderColor:ym.prod?"yellow":he,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:m?Am.map((h,g)=>{let d=c.text.slice(h.start,h.end),y=g===Lc(Am,c.pos),E=Math.min(c.pos,h.end)-h.start;return we(z,{children:[Y(z,{color:he,children:g===0?"> ":" "}),y?we(ir,{children:[d.slice(0,E),Y(ms,{ch:d[E]??" "}),d.slice(E+1)]}):d||" "]},`${g}-${h.start}`)}):we(z,{children:[Y(z,{color:he,children:"> "}),Kn?Y(ms,{ch:" "}):oe&&!S?we(ir,{children:[Y(ms,{ch:oe[0],dim:!0}),Y(z,{color:"gray",children:oe.slice(1)})]}):K&&!S?we(ir,{children:[Y(ms,{ch:K[0],dim:!0}),Y(z,{color:"gray",children:K.slice(1)}),Y(z,{dimColor:!0,children:" (tab)"})]}):(ru.isSetup||!ln)&&!S?we(ir,{children:[Y(ms,{ch:ru.text[0],dim:!0}),Y(z,{color:"gray",children:ru.text.slice(1)})]}):Y(ms,{ch:" "})]})}),tm.length>0&&Y(Oe,{flexDirection:"column",paddingX:1,children:tm.map((h,g)=>Y(z,{color:"gray",children:`\u29D7 queued: ${h}`},`${g}-${h.slice(0,24)}`))}),gt?we(Oe,{flexDirection:"column",paddingX:1,children:[Y(z,{color:he,bold:!0,children:"Auto mode \u2014 I run each step myself"}),Y(z,{color:"gray",children:` first step ${gt.firstCmd}${gt.scale?` \u2014 ${gt.scale}`:""}`}),gt.upcoming.length>0?we(ir,{children:[Y(z,{color:"gray",children:" as things stand, after that:"}),gt.upcoming.map(h=>Y(z,{color:"gray",children:` ${h.cmd}${h.scale?` ${h.scale}`:""}`},h.cmd)),Y(z,{color:"gray",children:" each step changes what the next one finds, so this is not a total"})]}):Y(z,{color:"gray",children:" I work down the ladder from there \u2014 reviewing, checking style, saving and going live"}),[gt.scale,...gt.upcoming.map(h=>h.scale)].every(h=>!h?.includes("$"))?Y(z,{color:"gray",children:" no cost estimate yet \u2014 this repo has not finished a run for me to measure"}):null,Y(z,{color:"gray",children:` spending limit ${Je(gt.budgetUsd)} \xB7 I stop and report if it is reached`}),Y(z,{color:"gray",children:" screenshots are not part of an automatic run"}),gt.overBudget?Y(z,{color:"yellow",children:`\u26A0 That is more than your ${Je(gt.budgetUsd)} limit. I will stop partway and report what is left.`}):null,Y(z,{dimColor:!0,children:gt.overBudget?"b raise the limit \xB7 enter start anyway \xB7 esc stay in manual for now":"enter start \xB7 b change the limit \xB7 esc stay in manual for now"})]}):xs?Y(Bv,{tab:xs.tab,scroll:xs.scroll,rows:G0,width:wt,version:o,engineVersion:j0}):xn?we(Oe,{flexDirection:"column",paddingX:1,children:[Y(z,{color:he,bold:!0,children:"Select model"}),Y(z,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer/config.json still wins)."}),qt.map((h,g)=>we(z,{color:g===xn.cursor?he:void 0,children:[g===xn.cursor?"\u276F ":" ",`${g+1}. ${h.label}${g===xn.current?" \u2714":""}`.padEnd(16),Y(z,{color:"gray",children:` ${h.desc}`})]},h.label)),Y(z,{dimColor:!0,children:Et({verb:"set as default",rows:qt.length,extra:["s this session only"]})})]}):Xt?we(Oe,{flexDirection:"column",paddingX:1,children:[Y(z,{color:he,bold:!0,children:"Switch connection profile"}),Y(z,{color:"gray",children:"Where this repo publishes. The environment lives on the profile, not on your login."}),Y(Bn,{rows:Xt.rows,cursor:Xt.cursor,cap:cn,render:(h,g,d)=>we(z,{color:d?he:void 0,children:[d?"\u276F ":" ",`${g+1}. ${h.name}${g===Xt.current?" \u2714":""}`.padEnd(20),h.connect?null:Y(z,{color:"gray",children:` ${h.portalUrl||h.env}${h.project?` \xB7 ${h.project}`:""} \xB7 ${h.portalUrl?h.who??"not signed in":"cannot be reached"}`}),h.prod?Y(z,{color:"yellow",children:` ${Xe}`}):null,h.internal?Y(z,{color:"gray",children:" internal"}):null]},h.name)}),Y(z,{dimColor:!0,children:Et({verb:"switch (saved as default)",rows:Xt.rows.length,extra:["s this session only"]})})]}):jt?we(Oe,{flexDirection:"column",paddingX:1,children:[Y(z,{color:he,bold:!0,children:"Pick your Document360 environment"}),Y(z,{color:"gray",children:"This is the portal your readers see. Rows marked internal are ours, not a customer's."}),Y(Bn,{rows:jt.rows,cursor:jt.cursor,cap:cn,render:(h,g,d)=>we(z,{color:d?he:void 0,children:[d?"\u276F ":" ",`${g+1}. ${h.name}`.padEnd(18),Y(z,{color:"gray",children:` ${h.portalUrl.replace(/^https:\/\//,"")}`}),h.note?h.internal||!h.production?Y(z,{color:"yellow",children:` \u26A0 ${h.note}`}):Y(z,{color:"gray",children:` ${h.note}`}):null]},h.name)}),Y(z,{dimColor:!0,children:Et({verb:"use it",rows:jt.rows.length})})]}):ut?we(Oe,{flexDirection:"column",paddingX:1,children:[Y(z,{color:he,bold:!0,children:"Switch workspace"}),Y(z,{dimColor:!0,children:`environment ${ut.environment} \xB7 project ${ut.projectName??`${ut.projectId.slice(0,8)}\u2026`}`}),Y(Bn,{rows:ut.rows,cursor:ut.cursor,cap:cn,render:(h,g,d)=>we(z,{color:d?he:void 0,children:[d?"\u276F ":" ",`${g+1}. ${h.name}${g===ut.current?" \u2714":""}`.padEnd(30),Y(z,{color:"gray",children:h.type?` ${h.type}`:""})]},h.id)}),Y(z,{dimColor:!0,children:Et({verb:"switch",rows:ut.rows.length})})]}):ft?we(Oe,{flexDirection:"column",paddingX:1,children:[Y(z,{color:he,bold:!0,children:"Choose project"}),Y(z,{dimColor:!0,children:`environment ${ft.environment}`}),Y(Bn,{rows:ft.rows,cursor:ft.cursor,cap:cn,render:(h,g,d)=>we(z,{color:d?he:void 0,children:[d?"\u276F ":" ",`${g+1}. ${h.name}${g===ft.current?" \u2714":""}`.padEnd(30),Y(z,{color:"gray",children:h.sub?` ${h.sub}`:""})]},h.id)}),Y(z,{dimColor:!0,children:Et({verb:"switch",rows:ft.rows.length})})]}):mt?(()=>{let g=Math.min(Math.max(0,mt.cursor-Math.floor(7)),Math.max(0,mt.rows.length-14)),d=mt.rows.slice(g,g+14),y=mt.rows.filter(E=>E.checked).length;return we(Oe,{flexDirection:"column",paddingX:1,children:[Y(z,{color:he,bold:!0,children:`Which folders back the user docs? (${y} selected of ${mt.rows.length})`}),g>0?Y(z,{dimColor:!0,children:` \u2191 ${g} more`}):null,d.map((E,I)=>{let O=g+I;return we(z,{color:O===mt.cursor?he:void 0,children:[O===mt.cursor?"\u276F ":" ",E.checked?"\u25C9 ":"\u25CB ",E.path.padEnd(Math.min(48,wt-34)),Y(z,{color:"gray",children:gl(E)})]},E.path)}),g+14<mt.rows.length?Y(z,{dimColor:!0,children:` \u2193 ${mt.rows.length-g-14} more`}):null,Y(z,{dimColor:!0,children:Et({verb:"save",multi:!0})})]})})():vt?we(Oe,{flexDirection:"column",paddingX:1,children:[Y(z,{color:he,bold:!0,children:vt.title??"Which category? (pick one to scope to)"}),Y(Bn,{rows:vt.rows,cursor:vt.cursor,cap:cn,render:(h,g,d)=>we(z,{color:d?he:void 0,children:[d?"\u276F ":" ",`${`${g+1}.`.padEnd(3)} ${h.label} (${h.count})`.padEnd(Math.min(44,Math.max(20,wt-24))),Y(z,{color:"gray",children:` ${h.token}`})]},h.token)}),Y(z,{dimColor:!0,children:Et({verb:"choose it",rows:vt.rows.length})})]}):It?we(Oe,{flexDirection:"column",paddingX:1,children:[Y(z,{color:he,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),Y(Bn,{rows:It.rows,cursor:It.cursor,cap:cn,render:(h,g,d)=>we(z,{color:d?he:void 0,bold:h.kind==="category"&&!d,children:[d?"\u276F ":" ",`${h.indent?" ":" "}${`${g+1}.`.padEnd(3)} ${h.label}`.padEnd(Math.min(56,wt-24)),h.note?Y(z,{color:"gray",children:` ${h.note}`}):null]},`${h.kind}:${h.paths.join(",")}`)}),Y(z,{dimColor:!0,children:Et({verb:"push as drafts",rows:It.rows.length})})]}):Qt?we(Oe,{flexDirection:"column",paddingX:1,children:[Y(z,{color:he,bold:!0,children:"Publish live to your readers \u2014 this is what they will see:"}),Y(Bn,{rows:[{path:"",articleId:"",label:`Publish all ${Qt.rows.length} live`,version:void 0},...Qt.rows],cursor:Qt.cursor,cap:cn,render:(h,g,d)=>we(z,{color:d?he:void 0,bold:g===0&&!d,children:[d?"\u276F ":" ",` ${`${g+1}.`.padEnd(3)} ${h.label}`.padEnd(Math.min(56,wt-24)),g>0?Y(z,{color:"gray",children:` ${h.version?`draft v${h.version} \u2192 live`:"draft \u2192 live"}`}):null]},`${g}:${h.path||"all"}`)}),Y(z,{dimColor:!0,children:Et({verb:"publish live",cancel:"leave as drafts",rows:Qt.rows.length+1})})]}):Lt?we(Oe,{flexDirection:"column",paddingX:1,children:[Y(z,{color:he,bold:!0,children:"Which comments do you want to look at?"}),Y(Bn,{rows:Lt.rows,cursor:Lt.cursor,cap:cn,render:(h,g,d)=>we(z,{color:d?he:void 0,bold:h.kind==="all"&&!d,children:[d?"\u276F ":" ",`${(h.kind==="all"?"":`${h.n}.`).padEnd(4)}${h.label}`.padEnd(Math.min(56,Math.max(20,wt-24))),h.kind==="article"?Y(z,{color:"gray",children:h.note}):null]},h.kind==="all"?"all":h.group.articleId)}),Y(z,{dimColor:!0,children:Et({verb:"open it",cancel:"close",rows:Lt.rows.length-1})}),Lt.resolve?Y(z,{dimColor:!0,children:"--resolve is on: threads you answer will be closed as well as replied to"}):null]}):pt?we(Oe,{flexDirection:"column",paddingX:1,children:[Y(z,{color:he,bold:!0,children:`${pt.group.title} \u2014 ${pt.group.threads.length} comment${pt.group.threads.length===1?"":"s"}`}),we(z,{color:pt.cursor===0?he:void 0,children:[pt.cursor===0?"\u276F ":" ",pt.resolve?"Yes \u2014 fix them, push the draft, reply and resolve":"Yes \u2014 fix them, push the draft to Document360, then reply"]}),we(z,{color:pt.cursor===1?he:void 0,children:[pt.cursor===1?"\u276F ":" ",pt.fromList?"No \u2014 back to the list":"No \u2014 leave them for now"]}),Y(z,{dimColor:!0,children:Et({verb:"open it",cancel:"go back",extra:["y answer"]})})]}):Jt?we(Oe,{flexDirection:"column",paddingX:1,children:[Y(z,{color:he,bold:!0,children:Jt.title}),(()=>{let{rows:h,cursor:g}=Jt,d=Cc(h.length,g,cn),y=d.start,E=h.slice(d.start,d.end),I=`${h.length}.`.length+1,O=Ny(h,Math.max(20,wt-4-I));return we(ir,{children:[y>0?Y(z,{color:"gray",children:` \u2026 ${y} more above`}):null,E.map((k,v)=>{let x=y+v,b=x===g,P=O[x];return we(z,{color:b?he:void 0,bold:(k.kind==="all"||k.kind==="category")&&!b,children:[b?"\u276F ":" ",`${x+1}.`.padEnd(I),P.head,P.note?Y(z,{color:"gray",children:P.note}):null]},`${k.action}:${k.kind}:${k.ids.join(",")}`)}),d.below>0?Y(z,{color:"gray",children:` \u2026 ${d.below} more below`}):null]})})(),Y(z,{dimColor:!0,children:Et({verb:"run it",rows:Jt.rows.length})})]}):Ot?we(Oe,{flexDirection:"column",paddingX:1,children:[Y(z,{color:he,bold:!0,children:`Preview article${Ot.query?` \u2014 filter: ${Ot.query}`:" (type to filter)"}`}),sa.length===0?Y(z,{color:"gray",children:"no articles match"}):sa.map((h,g)=>we(z,{color:g===Ot.cursor?he:void 0,children:[g===Ot.cursor?"\u276F ":" ",h]},h)),Y(z,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):_t?we(Oe,{flexDirection:"column",paddingX:1,children:[Y(z,{color:he,bold:!0,children:`Resume session${_t.query?` \u2014 filter: ${_t.query}`:" (type to filter)"}`}),ia.length===0?Y(z,{color:"gray",children:"no sessions match"}):ia.map((h,g)=>we(z,{color:g===_t.cursor?he:void 0,children:[g===_t.cursor?"\u276F ":" ",h.name.slice(0,28).padEnd(30),Y(z,{color:g===_t.cursor?he:"gray",children:h.firstPrompt.slice(0,Math.max(10,wt-40))})]},h.uuid)),Y(z,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):su?we(Oe,{flexDirection:"column",children:[Io>0?Y(z,{dimColor:!0,children:` \u22EF ${Io} more above`}):null,iu.map((h,g)=>{let d=Io+g,y=h.name==="model"&&Xc?`${h.desc} (currently ${Xc})`:h.desc,E=Math.max(20,wt-4),I=h.usage.length>E?`${h.usage.slice(0,E-1)}\u2026`:h.usage,O=E-Math.max(I.length,22)-1,k=O<=1?"":y.length>O?`${y.slice(0,O-1)}\u2026`:y;return we(z,{color:d===ra?he:void 0,children:[d===ra?"\u276F ":" ",I.padEnd(22)," ",Y(z,{color:d===ra?he:"gray",children:k})]},h.name)}),Io+iu.length<An.length?Y(z,{dimColor:!0,children:` \u22EF ${An.length-Io-iu.length} more below`}):null,Y(z,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!S&&!m&&ae.length>0?we(Oe,{flexDirection:"column",paddingX:1,children:[em?Y(z,{color:he,children:em}):null,Y(Bn,{rows:ae,cursor:kn??0,cap:cn,render:(h,g)=>{let d=g===kn,y=fo(h),E=y.slice(0,Math.max(20,wt-7)),I=wt-E.length-9,O=I>=12?(qv(h)??Nw(y)).slice(0,I):"";return we(z,{color:d?he:void 0,children:[d?"\u276F ":" ",Y(z,{color:he,children:g+1})," ",E,O?Y(z,{color:d?he:void 0,dimColor:!d,children:` \u2014 ${O}`}):null]},y)}}),Y(z,{dimColor:!0,children:`\u2191\u2193 choose \xB7 enter run \xB7 1-${ae.length} fill \xB7 esc cancel`})]}):Y(Oe,{paddingX:1,children:we(z,{color:"gray",children:[ym.prod?Y(z,{color:"yellow",children:`${Xe} \xB7 `}):null,Y(z,{color:Rs?he:void 0,children:Rs?"\u23F5\u23F5 auto":"\u23F5 manual"}),` \xB7 /help \xB7 ${Xc??"model n/a"}${t.kind==="api"?Mt>0?` \xB7 session ${Pt(Mt)}`:"":im>0?` \xB7 ${Vr(im)}`:""} \xB7 \u2191 history \xB7 shift+tab mode \xB7 ${F0?"press ctrl+c again to exit":"ctrl+c twice to exit"}`]})})]})}ue();import{jsx as A6}from"react/jsx-runtime";async function L0(e=process.cwd(),t="auto",n,o="0.0.0"){let r=T6(t);r.kind==="none"&&(console.error(""),console.error(L("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${Z("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${Z("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=P6(A6(I0,{cwd:e,auth:r,profileName:n,version:o}),{exitOnCtrlC:!1});await s(),await Xl(),process.stdout.write(`
|
|
611
|
-
`),process.exit(0)}function
|
|
612
|
-
`+L(`\u2717
|
|
581
|
+
It stays on Document360 with its history and comments intact. /push puts it back.`}:{kind:"note",tone:"error",text:`\u2717 Could not retire "${v}" \u2014 ${x.error.message}`})}finally{A(!1)}return}case"untrack":{let k=y.find(b=>!b.startsWith("-"));if(y.includes("--list")||!k&&!y.includes("--undo")){f({kind:"block",text:Wf(e,s).join(`
|
|
582
|
+
`)}),re.current=!0;return}if(!k){f({kind:"note",tone:"warn",text:"\u2717 Name what to put back: /untrack --undo <path>"});return}let v=E0(e,k)||k;if(y.includes("--undo")){let b=oF(e,s,v);f(b.ok?{kind:"note",tone:"ok",text:b.restoredTo?`\u2713 Put "${b.restoredTo}" back in your docs folder.`:"\u2713 No longer declined. /catch-up imports it again on the next run."}:{kind:"note",tone:"error",text:`\u2717 ${b.error.message}`});return}if(!y.includes("--yes")&&!y.includes("-y")){f({kind:"note",tone:"warn",text:[`\u26A0 This stops tracking "${v}" as one of your docs.`," Nothing on Document360 changes \u2014 the page, its history and its comments all stay,"," and your readers see no difference.",` The markdown moves to ${pt}/declined/, so nothing is deleted.`," /untrack --undo puts it back if you change your mind."].join(`
|
|
583
|
+
`)}),ut(`/untrack ${v} --yes`,"tab to stop tracking it \xB7 or keep typing");return}let x=nF({cwd:e,path:v,profileName:s,now:new Date().toISOString()});f(x.ok?{kind:"note",tone:"ok",text:[`\u2713 "${x.title??x.path}" is no longer one of your docs.`,...x.keptAt?[` The markdown is kept at ${x.keptAt} \u2014 nothing was deleted.`]:[]," It is untouched on Document360. /catch-up will not import it again."].join(`
|
|
584
|
+
`)}:{kind:"note",tone:"error",text:`\u2717 Could not untrack "${v}" \u2014 ${x.error.message}`});return}case"eval":{f({kind:"block",text:Kf(e,{...y.find(k=>!k.startsWith("--"))?{scope:y.find(k=>!k.startsWith("--"))}:{},...s?{profile:s}:{},all:y.includes("--all")}).join(`
|
|
585
|
+
`)}),re.current=!0;return}case"terms":{let k=y.findIndex(v=>v==="--approve");if(k!==-1){let v=y[k+1];f(v?{kind:"block",text:Gf(e,v.replace(/^["']|["']$/g,"")).lines.join(`
|
|
586
|
+
`)}:{kind:"note",tone:"warn",text:'\u2717 Name the spelling to approve, e.g. /terms --approve "drop-down".'}),re.current=!0;return}f({kind:"block",text:Hf(e,{...y.find(v=>!v.startsWith("--"))?{scope:y.find(v=>!v.startsWith("--"))}:{},all:y.includes("--all")}).join(`
|
|
587
|
+
`)}),re.current=!0;return}case"reuse":{let k=y.find(v=>!v.startsWith("--"));if(k==="pull"){(async()=>{let v=await Xi(e);f({kind:"block",text:v.lines.join(`
|
|
588
|
+
`)});for(let x of Ze(e,"/reuse pull"))f({kind:"note",tone:"ok",text:x});v.restart&&Qe()})(),re.current=!0;return}if(k==="audit"){if(y.includes("--create")){let x=rF(e);if(!x||x.proposals.length===0){f({kind:"block",text:Oc().join(`
|
|
589
|
+
`)}),re.current=!0;return}let{picks:b,bad:P}=Lc(y,x.proposals.length);for(let T of P)f({kind:"note",tone:"warn",text:`\u26A0 There is no proposal ${T} \u2014 the list has ${x.proposals.length}.`});if(b.length===0){f({kind:"note",tone:"info",text:"\u25CB Nothing picked, so nothing was created."}),re.current=!0;return}(async()=>{let{outcome:T,pullLines:_}=await tm(e,b.map(M=>x.proposals[M]));_.length>0&&f({kind:"block",text:_.join(`
|
|
590
|
+
`)}),f({kind:"block",text:Ic(e,T).lines.join(`
|
|
591
|
+
`)});for(let M of Ze(e,"/reuse audit"))f({kind:"note",tone:"ok",text:M});T.created.length>0&&Qe()})(),re.current=!0;return}let v=jc(e,y);if("lines"in v){f({kind:"block",text:v.lines.join(`
|
|
592
|
+
`)});for(let x of Ze(e,"/reuse audit"))f({kind:"note",tone:"ok",text:x});re.current=!0;return}f({kind:"block",text:Dc(v.articles,v.families,v.values,0).join(`
|
|
593
|
+
`)}),(async()=>(await Te(v.prompt,{display:v.display,quietUser:!0}),f({kind:"block",text:_c(e,v.display.split(/\s+/)[2]).join(`
|
|
594
|
+
`)})))(),re.current=!0;return}if(k==="add"){let v=em(y);if("error"in v){f({kind:"note",tone:"warn",text:`\u2717 ${v.error}`}),re.current=!0;return}(async()=>{let x=await Zf(e,v.kind,v.name,v.value,v.description);f({kind:"block",text:x.lines.join(`
|
|
595
|
+
`)}),x.restart&&Qe()})(),re.current=!0;return}if(k&&k!=="show"){f({kind:"note",tone:"warn",text:`\u2717 I don't know "/reuse ${k}". Use /reuse to see what this project maintains, /reuse pull to refresh it, or /reuse add variable <name> "<value>".`}),re.current=!0;return}f({kind:"block",text:Jf(e).join(`
|
|
596
|
+
`)}),re.current=!0;return}case"reorder":{let k=_f(e,y);if(!k){f({kind:"note",tone:"error",text:be});return}let v=await Te(k.prompt,{display:k.display,quietUser:!0}),x=Kt(e,{text:"Reordered locally \u2014 /push --all syncs the new order to Document360.",cmd:"/push --all"},"Reordered locally. ");jn(v,x.text,{kind:"cmd",cmd:x.cmd,reason:""});return}case"restructure":{let k=Mf(e,y);if(!k){f({kind:"note",tone:"error",text:be});return}let v=await Te(k.prompt,{display:k.display,quietUser:!0});if(y.filter(b=>!b.startsWith("--")).length===0){jn(v,null,null);return}let x=Kt(e,{text:"Restructured locally \u2014 /push --all moves it on Document360.",cmd:"/push --all"},"Restructured locally. ");jn(v,x.text,{kind:"cmd",cmd:x.cmd,reason:""});return}case"review":{let k=Lf(e,y);if(k){f({kind:"note",tone:"ok",text:k.lines[0]});for(let B of k.closed)f({kind:"note",tone:"ok",text:B});let j=zi(e,y,null);j&&(f({kind:"note",tone:"info",text:"One thing left: no editor has looked at how your docs are organised since it last changed. Checking that now \u2014 it reads the shape, not the articles, so it is one quick pass."}),(await Te(j.prompt,{display:j.display,quietUser:!0})).producedNothing||T0(e,j.fingerprint)),je(k.cta.text,{kind:"cmd",cmd:k.cta.cmd,reason:""});return}let v=If(e,y);if(!v){f({kind:"note",tone:"error",text:be});return}let x=y.includes("--fix"),b=y.find(j=>!j.startsWith("--")),P=x?hr(e,y,b):[],T=x?Em(e):null,_={aborted:!1,partitions:0,failed:0,notRun:0},M,N=null,X=zi(e,y,v);if(v.kind==="partitioned"){let j=await eR(v,x,T,!!X);_=j.outcome,M=j,N=j.evidence}else M=await Te(v.prompt,{display:v.display,quietUser:!0}),_={..._,producedNothing:M.producedNothing};if("aborted"in M&&M.aborted){let j=y.includes("--blocked")?"--blocked --fix":y.includes("--stale")?"--stale --fix":"--fix",B=Ee("/review",j,b);je(`Stopped \u2014 the batches that finished are saved. ${B} picks up the rest${b||ks(y)?"":", or narrow it with /review <category> --fix"}.`,{kind:"cmd",cmd:B,reason:""},"warn");return}if(X&&((await Te(X.prompt,{display:X.display,quietUser:!0})).producedNothing||T0(e,X.fingerprint)),v.kind!=="partitioned"&&x&&!M.producedNothing&&(N=pr(e,P,T,s),N.earned.length>0))try{Ts(e,N.earned,St("review"))}catch{}if(x&&On(`/review${b?` ${b}`:""}${y.includes("--all")?" --all":""}${y.includes("--blocked")?" --blocked":y.includes("--stale")?" --stale":""} --fix`,_),x){if(x&&!M.producedNothing){let we=$n(e,["--fix"],As({cwd:e,scope:b}));we.lines.length>0&&f({kind:"note",tone:"ok",text:we.lines.join(`
|
|
597
|
+
`)})}let j=x&&!M.producedNothing?As({cwd:e,scope:b}).filter(we=>!we.baselined&&we.severity==="error"):[],B=N?N.changed.length:-1,q=B<0?"Editor applied its fixes":Yi(B),se=ys(e,N?.unadopted??[],{lead:B===0&&j.length===0});if(se&&f({kind:"note",tone:"warn",text:se.lines.join(`
|
|
598
|
+
`)}),j.length>0){let we=new Set(j.map(Ue=>Ue.path)).size,$e=`/lint${b?` ${b}`:""} --blocked --fix`,ee=dn(e,$e),Ae=!N||N.changed.length>0;f({kind:"note",tone:"warn",text:Ae?`\u26A0 The editor's rewrites left ${j.length} style error${j.length===1?"":"s"} in ${we} article${we===1?"":"s"} \u2014 recasting a sentence is where these appear.`:`\u26A0 ${j.length} style error${j.length===1?"":"s"} in ${we} article${we===1?"":"s"} still block${j.length===1?"s":""} publishing \u2014 the editor changed nothing, so these were already there.`}),jn(M,`${N?Yi(N.changed.length):"Editor applied its fixes"}, but ${j.length} style error${j.length===1?"":"s"} remain. ${$e} clears ${j.length===1?"it":"just those"} \u2014 it costs nothing to find them and one pass to correct${ee?` (${ee})`:""}. It is the last paid pass before publishing: anything still standing after a second attempt is reported for a person rather than run again.`,{kind:"cmd",cmd:$e,reason:""});return}if(se?.cta){jn(M,se.cta.text,{kind:"cmd",cmd:se.cta.cmd,reason:""});return}let ye=Kt(e,{text:`\u2713 ${q} \u2014 your docs are ready. /push${b?"":" --all"} saves them to Document360 as drafts (or /lint${b?` ${b}`:""} for an instant no-token re-scan first).`,cmd:b?"/push":"/push --all"},`\u2713 ${q} in this scope. `,b);jn(M,ye.text,{kind:"cmd",cmd:ye.cmd,reason:""})}else{let j=b?` ${b}`:"",B=Nl(e,b)===0&&Dl(e,b)===0?`; /push${b?"":" --all"} saves them to Document360 as-is`:"";jn(M,`The review listed issues above. /review${j} --fix lets the editor apply them all (or /lint${j} --fix for just the deterministic ones${B}).`,{kind:"cmd",cmd:`/review${j} --fix`,reason:""})}return}case"capture-setup":{await O();return}case"devhints":{if(!Se(e)){f({kind:"note",tone:"error",text:be});return}f({kind:"note",tone:"info",text:Vr(qr(e)).join(`
|
|
599
|
+
`)}),In(zo()),qs.current=an(e).status==="current",jr.current=Un(e);return}case"discover":{if(!Se(e)){f({kind:"note",tone:"error",text:be});return}await Te(wp(),{display:"/discover",quietUser:!0});return}case"ask":{if(!Se(e)){f({kind:"note",tone:"error",text:be});return}let k=y.join(" ").trim();if(k===""){f({kind:"block",text:Fh(ZU(e)).join(`
|
|
600
|
+
`)});return}try{let v=JU(e,{question:k});f({kind:"note",tone:"ok",text:Uh(v.file,Oi(e)).join(`
|
|
601
|
+
`)})}catch(v){f({kind:"note",tone:"warn",text:`Could not file the question: ${v.message}`})}return}case"inbox":{if(!Se(e)){f({kind:"note",tone:"error",text:be});return}if(_h(e)===0){f({kind:"note",tone:"info",text:"Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)"});return}await Te(Mh(),{display:"/inbox",quietUser:!0});return}case"auto":{let k=Se(e);if(!k){f({kind:"note",tone:"error",text:be});return}let v=mp(y);if(v.malformed){f({kind:"note",tone:"error",text:`I could not read that spending limit. Give it as an amount, like: /auto --budget 150 (the standard limit is ${et(yU)}).`});return}let x=gp(y,v.usd),b=P=>{for(let T of P)f({kind:"note",tone:T.tone,text:T.text});H(T=>T+1)};if(v.usd!==void 0&&!x){let P=fp(e,k,v.usd);P&&b(P);return}if(!x||x==="status"){for(let P of wi(k))f({kind:"note",tone:P.tone,text:P.text});return}if(x==="on"||x==="off"){x==="on"&&(Zn.current=!1);let P=v.usd!==void 0?{...k,auto:{...k.auto,enabled:k.auto?.enabled===!0,budgetUsd:v.usd}}:k;b(Fl(e,P,x==="on"));return}f({kind:"note",tone:"error",text:`I don't know "${x}". Use: /auto on \xB7 /auto off \xB7 /auto status \xB7 /auto --budget <amount>`});return}case"share":{let k=Se(e);if(!k){f({kind:"note",tone:"error",text:be});return}let v=y[0]?.trim().toLowerCase();if(v==="status"){for(let b of fc(e,k))f({kind:"note",tone:b.tone,text:b.text});return}if(v==="on"||v==="off"){for(let b of Wh(e,k,v==="on"))f({kind:"note",tone:b.tone,text:b.text});H(b=>b+1);return}if(v){f({kind:"note",tone:"error",text:`Unknown option: ${v} \u2014 use /share, /share status, /share on, or /share off.`});return}f({kind:"note",tone:"info",text:"Exchanging work with your team\u2026"});let x=await mc(e,k);for(let b of x.lines)f({kind:"note",tone:b.tone,text:b.text});x.changed&&H(b=>b+1);return}case"feedback":{let k=S0(e),v="";try{v=Ps(k)?du(k,"utf8"):""}catch{v=""}if(!/^## /m.test(v)){f({kind:"note",tone:"info",text:`No open ${yt} feedback to copy \u2014 nothing logged in ${pt}/tool-feedback.md yet.`});return}let x=await mm(v.trim());f({kind:"note",tone:x?"ok":"warn",text:x?`\u2713 Copied the ${yt} feedback to your clipboard \u2014 send it to the team (Teams / Slack / email).`:`Couldn\u2019t reach your clipboard \u2014 open ${k} and copy it manually.`}),x&&ju(null);return}case"copy":{cg();return}case"document":{if(!Se(e)){f({kind:"note",tone:"error",text:be});return}let{push:k,skipReview:v,what:x}=hh(y);if(!x&&ph(e)===0){f({kind:"note",tone:"info",text:mh});return}let b=`/document${x?` ${x}`:""}${k?" --push":""}`,P=await Te(fh(x),{display:b,quietUser:!0});k&&!P.producedNothing&&await dg({skipReview:v});return}case"catch-up":{if(!Se(e)){f({kind:"note",tone:"error",text:be});return}if(!Fo(h.trim()))return;let{push:k,skipReview:v,includeUnfinished:x}=qh(y);for(let q of await Hh(e))f({kind:"note",tone:q.tone,text:q.text});f({kind:"note",tone:"info",text:"Reconciling with Document360 (pulling any portal changes)\u2026"});let b=await Qh({cwd:e,profileName:s});for(let q of Jh(b))f({kind:"note",tone:q.startsWith("\u2713")?"ok":q.startsWith("\u2139")?"info":"warn",text:q});let P=Ui(e);for(let q of Vh(P))f({kind:"note",tone:q.tone,text:q.text});let T=Kh(e),_=x?[]:T,M=Yh(e,_);for(let q of zh(_,M))f({kind:"note",tone:q.tone,text:q.text});let N=un(e);f({kind:"note",tone:"info",text:Gh(N)});let X=Em(e);Pe.current?.beginTurn({baseline:X,allowUnfinishedHints:x});let j=await Te(Xh(P,{held:T.length,includeUnfinished:x},N.briefMoved),{display:`/catch-up${k?" --push":""}${x?` ${wc}`:""}`,quietUser:!0});j.producedNothing||eF(e);let B=lr(e,X,"","/catch-up");if(k&&!j.producedNothing)await dg({skipReview:v});else if(B.cta)jn(j,B.cta.text,{kind:"cmd",cmd:B.cta.cmd,reason:""});else{let q=yc({queued:N,hold:P.hold});jn(j,q.note,q.lead?{kind:"cmd",cmd:q.lead.cmd,reason:q.lead.reason}:null,q.tone)}return}case"comments":{if(!Se(e)){f({kind:"note",tone:"error",text:be});return}if(!Fo(h.trim()))return;let k=of(y);He("Checking Document360 for reviewer comments\u2026"),A(!0);let v=null;try{v=await kc(e,s,{...k.scope,onProgress:(b,P)=>He(`Checking Document360 for reviewer comments\u2026 ${b}/${P}`)})}catch(b){f({kind:"note",tone:"error",text:`Couldn\u2019t read comments from Document360: ${b.message}`})}finally{A(!1),He(null)}if(!v)return;H(b=>b+1);let x=cr(v.threads,v.labels);if(v.threads.length===0){f({kind:"note",tone:"ok",text:Wi(v,{showAnswered:k.showAnswered,width:ct()}).join(`
|
|
602
|
+
`)});return}if(k.answer&&(k.all||k.scope.path||k.scope.scope||x.length===1)){Ir(tf(v,{full:!0,showAnswered:k.showAnswered,width:ct()})),await Uu(x,{resolve:k.resolve});return}if(x.length===1){Ir(bc(x[0],{width:ct()})),Is({group:x[0],cursor:0,fromList:!1,resolve:k.resolve,rest:[]});return}Ir(Wi(v,{showAnswered:k.showAnswered,width:ct()})),En({cursor:0,rows:$c(x),groups:x,resolve:k.resolve,report:v});return}case"update":{if(vc()){f({kind:"note",tone:"info",text:"Checking for a newer version\u2026"});let v=await x0({pkg:dr,currentVersion:o,force:!0}).catch(()=>null);if(!v?.updateAvailable||!v.latest){f({kind:"note",tone:"ok",text:`\u2713 You're on the latest version (v${o}).`});return}xa.current=!0,xc(v.latest),f({kind:"note",tone:"info",text:`\u2B06 Update v${v.latest} is ready.
|
|
603
|
+
Windows can't replace the files while ${yt} is running, so I'll install it the moment you /exit.`}),ue("/exit");return}xa.current=!0,f({kind:"note",tone:"info",text:`Updating the ${yt} toolchain\u2026 (don\u2019t close this window)`}),So(!0);let k=await Gi().finally(()=>So(!1));k.ok?(f({kind:"note",tone:"ok",text:`\u2713 Updated ${k.packages.join(" + ")} \u2014 run /exit, then relaunch to apply.`}),ue("/exit"),da("")):(f({kind:"note",tone:"warn",text:`Update failed. ${Hi(k.output)}`}),k.output&&f({kind:"note",tone:"info",text:`${k.output}
|
|
604
|
+
|
|
605
|
+
Full output: ${Bi()}`}));return}case"screenshot":{let k=ii(y),v=Xo(e);if(v&&k.mode!=="list"&&f({kind:"note",tone:"info",text:v}),k.mode==="capture"){await E(k.rest);return}if(k.mode==="annotate"){await I(k.rest);return}if(k.mode==="checklist"){await O();return}if(k.mode==="verify"){let P=Ke(e),T=k.rest.find(N=>!N.startsWith("-")),_=T?[T]:Ei(P);if(T&&!P.some(N=>N.id===T)){f({kind:"note",tone:"error",text:`No screenshot placeholder called "${T}". /screenshot list shows them all.`});return}if(_.length===0){let N=P.filter(j=>j.state==="rejected").length,X=P.filter(j=>j.state==="verified").length;f({kind:"note",tone:"info",text:N>0?`Nothing left to verify. ${N} shot${N===1?"":"s"} failed verification \u2014 re-capture with /screenshot capture --failed.`:X>0?`All ${X} captured shot${X===1?" is":"s are"} already verified.`:"No captured screenshots to verify yet \u2014 /screenshot capture takes the shots first."});return}f({kind:"note",tone:"info",text:yo(_.length)}),await Te(vn(e,_),{display:T?`/screenshot verify ${T}`:"/screenshot verify",quietUser:!0});let M=us(e,_);M.length>0&&f({kind:"note",tone:"info",text:M.join(`
|
|
606
|
+
`)});return}if(k.mode==="list"){if(!Se(e)){f({kind:"note",tone:"error",text:be});return}let P=Se(e)?.docsDir??Om,T=Gd(e,k.scope),_=Ke(e,T);if(k.picker){if(_.length===0){f({kind:"note",tone:"info",text:"No screenshot placeholders found in the docs."});return}let N=Aw(_);if(N.length===0){f({kind:"note",tone:"info",text:xl(_,{docsDir:P}).join(`
|
|
607
|
+
`)});let X=Ee("/push","--screenshots",T),j=Kt(e,{text:`\u2713 All ${_.length} screenshots are captured. ${X} saves them into the articles on Document360; /screenshot capture${T?` ${T}`:""} re-captures.`,cmd:X},`\u2713 All ${_.length} screenshots are captured. `,T);je(j.text,{kind:"cmd",cmd:j.cmd,reason:""});return}Eo({cursor:0,rows:N,title:"Screenshots \u2014 pick what to author or capture:"});return}f({kind:"note",tone:"info",text:xl(_,{scope:T,detail:k.detail,docsDir:P}).join(`
|
|
608
|
+
`)}),v&&f({kind:"note",tone:"info",text:v});let M=Hd(_,T);M.key!=="done"&&ue(M.cmd);return}if(k.mode==="single"){await hg(k.id);return}if(!Se(e)){f({kind:"note",tone:"error",text:be});return}let x=k.mode==="scope"?k.scope:void 0,b=OU(e,{scope:x}).map(P=>P.id);if(b.length===0){f({kind:"note",tone:"info",text:x?`No screenshot placeholders under ${x}.`:"No screenshot placeholders found in the docs."});return}await pg(b,{setup:k.setup,scope:k.mode==="scope"?k.scope:void 0,runLine:k.mode==="scope"?[`/screenshot author ${k.scope}`,`/screenshot ${k.scope}`]:["/screenshot author --all","/screenshot --all"]});return}case"capture":{await E(y);return}case"reset":{let k=uf(e);if(k.length===0){f({kind:"note",tone:"info",text:`Nothing to reset \u2014 no ${yt} files found in this repo.`});return}Rr.current={repoName:sa(e),targets:k,hadDevhints:Ps(R0(e))},f({kind:"note",tone:"warn",text:pf(e,k).join(`
|
|
609
|
+
`)}),ut(sa(e));return}default:f({kind:"note",tone:"error",text:`Unknown command: /${d} \u2014 type /help.`})}},[e,r,s,Or,Gu,f,Qe,Te,Tt,Fu,fg]),zs=ce(h=>{let g=(h??m).trim();if($(""),vr(null),Xn(0),g.startsWith("/")){re.current=!1,ve.current=!1,Ne.current=null,rn(),Do(null);let y=$a.current.includes(g);y&&($a.current=[]),he(E=>y?[]:zx(E,g))}if(!g||(De(!1),Le.current=!1,(Rr.current||_e.current.length>0)&&f({kind:"user",text:g}),gg(g))||mg(g))return;ku.current.push(g);let d=Zx(g,xr.current);if(g.startsWith("/"))f({kind:"user",text:g}),G(!0),Ho(d).finally(()=>G(!1));else if(sF(d)){f({kind:"user",text:g});let y=iF(d);if(!y)Te(d,{display:g,quietUser:!0});else{try{aF(e,{title:y,by:`owner (${yt} terminal)`,at:new Date().toISOString()})}catch{}Te(`The owner left this documentation directive (already recorded in ${pt}/directives.md): "${y}". 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 "${y}" and the article path(s) you wrote.`,{display:g,quietUser:!0})}}else{let y=Ww(e,d);Te(y??d,{display:g})}},[m,gg,mg,Ho,Te]),yg=ce(h=>{if(h.length>1){if(h.includes("\x1B"))return;let g=Xx(h);if(Qx(g)){let d=Jx(++ha.current,g);xr.current.set(d,g),w(d)}else w(g);return}w(h)},[w]),_r=Math.max(10,xt-6),wg=uu(()=>lu(c.text,_r),[c.text,_r]),qu=ce(h=>p(g=>({...g,pos:Math.max(0,Math.min(g.text.length,g.pos+h))})),[]),La=ce(h=>p(g=>({...g,pos:t0(lu(g.text,_r),g.pos,h)})),[_r]),Xs=ce(h=>p(g=>({...g,pos:n0(lu(g.text,_r),g.pos,h)})),[_r]),tR=["\x1B[H","\x1B[1~","\x1BOH"],nR=["\x1B[F","\x1B[4~","\x1BOF"],kg=ce((h,g)=>g.leftArrow?(qu(-1),!0):g.rightArrow?(qu(1),!0):h&&tR.includes(h)?(Xs("start"),!0):h&&nR.includes(h)?(Xs("end"),!0):g.ctrl&&h==="a"?(Xs("start"),!0):g.ctrl&&h==="e"?(Xs("end"),!0):!1,[qu,Xs]),Vu=ce(()=>{if(qe.current){if(!qe.current.signal.aborted){let h=(Nr?.verb??"work").toLowerCase(),g=Nr?.unit??"article";f({kind:"note",tone:"warn",text:`\u238B Stopping the ${h} run (finishing in-flight ${g}s)\u2026`}),qe.current.abort()}return!0}return Ls.current?!1:(Ls.current=!0,f({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),Pe.current?.interrupt(),!0)},[Nr]);return VM((h,g)=>{if(g.ctrl&&h==="c"){if(Os.current!==null&&Date.now()-Os.current<I0){Os.current=null,Pe.current?.close(),r();return}Os.current=Date.now(),qm(!0),vu.current&&clearTimeout(vu.current),vu.current=setTimeout(()=>{Os.current=null,qm(!1)},I0),S?Vu():m&&$("");return}if(Gs.current.awaySince!==null&&nt.current===null)try{let d=Fx(Gs.current,Date.now(),un(e));if(Gs.current=d.memory,sg(null),d.kind==="delta"){f({kind:"note",tone:"info",text:Bx(d.delta,d.awayMs)});let y=At(!1);y.kind==="recommend"&&Dn(y.rec,{silent:!0})}else if(d.kind==="briefing"){f({kind:"note",tone:"info",text:`\u{1F4E5} ${oa(d.delta)} arrived while you were away (${xm(d.awayMs)}).`});let y=At(!1);y.kind==="recommend"&&Dn(y.rec)}}catch{}if(Iu.current=Date.now(),!R){if($t){if(g.return){ma(null),ga.current=!0,H(d=>d+1),f({kind:"note",tone:"info",text:"\u25B6 Auto mode starting \u2014 esc stops it at any point, and nothing already done is undone."});return}if(h==="b"||h==="B"){ma(null),$("/auto --budget ");return}if(g.escape){ma(null),Zn.current=!0,nt.current=null,f({kind:"note",tone:"info",text:"Left in manual for now \u2014 nothing started. Auto mode is still on: /auto on begins the round trip when you are ready, or /auto off switches it off."}),H(d=>d+1);return}return}if(g.tab&&g.shift&&!eo&&!Tn&&!Ou){let d=Se(e);if(!d){f({kind:"note",tone:"info",text:"Set this repo up first with /init \u2014 then shift+tab switches between auto and manual."});return}let y=!m0(d);Fl(e,d,y),y&&(Zn.current=!1);let E=!y&&nt.current!==null;E&&(nt.current={...nt.current,stopping:!0}),f({kind:"note",tone:"ok",text:E?"Manual mode \u2014 I'll finish what is running and stop there, then hand back. (shift+tab to change it back.)":`${y?"Auto mode ON":"Manual mode"} \u2014 ${yi(y)} (shift+tab to change it back.)`}),H(I=>I+1);return}if(S){if(g.escape){if(nt.current){Zn.current=!0;let d=nt.current;Vu(),Ks({kind:"stopped",how:"esc"},d.parked);return}Vu();return}if(g.return){let d=m.trim();if(!d)return;Io.current.push(d),$u([...Io.current]),$("");return}if(kg(h,g))return;if(g.upArrow){La(-1);return}if(g.downArrow){La(1);return}if(g.backspace||g.delete){C();return}h&&!g.ctrl&&!g.meta&&yg(h);return}if(Tn){if(g.upArrow){Ao(d=>d&&{...d,cursor:Math.max(0,d.cursor-1)});return}if(g.downArrow){Ao(d=>d&&{...d,cursor:Math.min(Xt.length-1,d.cursor+1)});return}if(h&&/^[0-9]$/.test(h)){let d=Nn(h,Xt.length);d!==null&&Ao(y=>y&&{...y,cursor:d});return}if(g.return){let d=Xt[Tn.cursor];Ao(null);let{lines:y,changed:E,effective:I}=Pi(e,d.value??"default");for(let O of y)f({kind:"note",tone:O.startsWith("\u26A0")?"warn":O.startsWith("\u2713")?"ok":"info",text:O});E&&(Xm(O=>O+1),Pe.current?.setModel(I));return}if(h==="s"){let d=Xt[Tn.cursor];Ao(null),Pe.current?.setModel(d.value??void 0),f({kind:"note",tone:"ok",text:`\u2713 Using ${d.label} for this session only (your saved default is unchanged).`});return}if(g.escape){Ao(null);return}return}if(tn){if(g.upArrow){Sr(d=>d&&{...d,cursor:Math.max(0,d.cursor-1)});return}if(g.downArrow){Sr(d=>d&&{...d,cursor:Math.min(d.rows.length-1,d.cursor+1)});return}if(h&&/^[0-9]$/.test(h)){let d=Nn(h,tn.rows.length);d!==null&&Sr(y=>y&&{...y,cursor:d});return}if(g.return||h==="s"){let d=tn.rows[tn.cursor];if(Sr(null),d.connect){Jn({cursor:0,mode:"connect",rows:oo()});return}Na(d.name,g.return===!0);return}if(g.escape){Sr(null);return}return}if(Us){if(g.escape){_o(null);return}if(g.leftArrow||g.tab&&g.shift){_o(d=>d&&{tab:(d.tab-1+Et.length)%Et.length,scroll:0});return}if(g.rightArrow||g.tab){_o(d=>d&&{tab:(d.tab+1)%Et.length,scroll:0});return}if(h&&/^[1-9]$/.test(h)&&Number(h)<=Et.length){_o({tab:Number(h)-1,scroll:0});return}if(g.upArrow){_o(d=>d&&{...d,scroll:Math.max(0,d.scroll-1)});return}if(g.downArrow){_o(d=>{if(!d)return d;let y=(Et[d.tab]??Et[0]).rows.length;return{...d,scroll:Math.min(Math.max(0,y-1),d.scroll+1)}});return}return}if(Mt){if(g.upArrow){Jn(d=>d&&{...d,cursor:Math.max(0,d.cursor-1)});return}if(g.downArrow){Jn(d=>d&&{...d,cursor:Math.min(d.rows.length-1,d.cursor+1)});return}if(h&&/^[0-9]$/.test(h)){let d=Nn(h,Mt.rows.length);d!==null&&Jn(y=>y&&{...y,cursor:d});return}if(g.return){let d=Mt.rows[Mt.cursor].name,y=Mt.mode;if(Jn(null),y==="connect"){let O=new Set(Object.keys(Se(e)?.profiles??{})),k=d;for(let P=2;O.has(k);P++)k=`${d}-${P}`;let v=ni(e,k,d);if(v){f({kind:"note",tone:"error",text:v});return}let[x,...b]=oi(k,d);f({kind:"note",tone:"ok",text:x}),f({kind:"note",tone:"info",text:`Saved as this repo\u2019s default, so everyone who pulls this repo publishes here.
|
|
610
|
+
Press s in /profile to use a profile for one session only.`});for(let P of b)f({kind:"note",tone:"warn",text:P});Na(k,!0);return}if(!wd(e,d).created){f({kind:"note",tone:"error",text:`Could not scaffold \u2014 ${pt}/config.json already exists.`});return}f({kind:"note",tone:"ok",text:`\u2713 Wrote ${pt}/config.json (environment "${d}").`});let I=!1;try{let O=vo(d);I=!!O&&!(kr(O)&&!O.refreshToken)}catch{I=!1}f({kind:"note",tone:"info",text:I?`Next: sign in to ${d} and pick your project \u2014 you're already signed in here, so it'll be quick.`:`Next: sign in to Document360 (${d}) and pick your project.`}),ue("/login"),H(O=>O+1);return}if(g.escape){Jn(null);return}return}if(ht){if(g.upArrow){Cr(d=>d&&{...d,cursor:Math.max(0,d.cursor-1)});return}if(g.downArrow){Cr(d=>d&&{...d,cursor:Math.min(d.rows.length-1,d.cursor+1)});return}if(h&&/^[0-9]$/.test(h)){let d=Nn(h,ht.rows.length);d!==null&&Cr(y=>y&&{...y,cursor:d});return}if(g.return){let d=ht.rows[ht.cursor],{profile:y,projectId:E}=ht;Cr(null),Da(y,E,d);return}if(g.escape){Cr(null);return}return}if(kt){if(g.upArrow){To(d=>d&&{...d,cursor:Math.max(0,d.cursor-1)});return}if(g.downArrow){To(d=>d&&{...d,cursor:Math.min(d.rows.length-1,d.cursor+1)});return}if(h&&/^[0-9]$/.test(h)){let d=Nn(h,kt.rows.length);d!==null&&To(y=>y&&{...y,cursor:d});return}if(g.return){let d=kt.rows[kt.cursor],{profile:y}=kt;To(null),Ia(y,d);return}if(g.escape){To(null);return}return}if(bt){if(g.upArrow){Tr(d=>d&&{...d,cursor:Math.max(0,d.cursor-1)});return}if(g.downArrow){Tr(d=>d&&{...d,cursor:Math.min(d.rows.length-1,d.cursor+1)});return}if(h===" "){Tr(d=>d&&{...d,rows:d.rows.map((y,E)=>E===d.cursor?{...y,checked:!y.checked}:y)});return}if(g.return){let d=bt.rows.filter(y=>y.checked).map(y=>y.path);if(Tr(null),d.length===0){f({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}bp(e,d),f({kind:"note",tone:"ok",text:`\u2713 Scoped to ${d.length} folder(s) \u2014 written to ${pt}/config.json`});for(let y of d)f({kind:"note",tone:"info",text:` ${y}`});f({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(g.escape){Tr(null);return}return}if(Pt){if(g.upArrow){No(d=>d&&{...d,cursor:Math.max(0,d.cursor-1)});return}if(g.downArrow){No(d=>d&&{...d,cursor:Math.min(d.rows.length-1,d.cursor+1)});return}if(h&&/^[0-9]$/.test(h)){let d=Nn(h,Pt.rows.length);d!==null&&No(y=>y&&{...y,cursor:d});return}if(g.return){let d=Pt.rows[Pt.cursor],y=Pt.run;No(null),y(d.token);return}if(g.escape){No(null);return}return}if(Ut){if(g.upArrow){Pr(d=>d&&{...d,cursor:Math.max(0,d.cursor-1)});return}if(g.downArrow){Pr(d=>d&&{...d,cursor:Math.min(d.rows.length-1,d.cursor+1)});return}if(h&&/^[0-9]$/.test(h)){let d=Nn(h,Ut.rows.length);d!==null&&Pr(y=>y&&{...y,cursor:d});return}if(g.return){let d=Ut.rows[Ut.cursor],y=Ut.conflicts;Pr(null),d.conflict?Gu(d.paths[0]):d.kind==="article"?Fu(d.paths[0]):Tt(d.paths,d.kind==="all"?y:0);return}if(g.escape){Pr(null);return}return}if(nn){if(g.upArrow){Ar(d=>d&&{...d,cursor:Math.max(0,d.cursor-1)});return}if(g.downArrow){Ar(d=>d&&{...d,cursor:Math.min(d.rows.length,d.cursor+1)});return}if(h&&/^[0-9]$/.test(h)){let d=Nn(h,nn.rows.length+1);d!==null&&Ar(y=>y&&{...y,cursor:d});return}if(g.return){let{cursor:d,rows:y,opts:E}=nn;Ar(null);let I=d===0?y:[y[d-1]];ug(I,E);return}if(g.escape){Ar(null),f({kind:"note",tone:"info",text:"Left as drafts \u2014 nothing changed. /publish when they have been signed off."});return}return}if(Ft){let{rows:d}=Ft;if(g.upArrow){En(y=>y&&{...y,cursor:Math.max(0,y.cursor-1)});return}if(g.downArrow){En(y=>y&&{...y,cursor:Math.min(d.length-1,y.cursor+1)});return}if(h&&/^[0-9]$/.test(h)){let y=wm(Wm.current,Number(h),d.length-1);Wm.current=y.memory,y.index!==null&&En(E=>E&&{...E,cursor:y.index+1});return}if(h==="a"||h==="A"){En(y=>y&&{...y,cursor:0});return}if(g.return){let y=d[Ft.cursor],{groups:E,resolve:I,report:O}=Ft;if(En(null),y.kind==="all"){Uu(E,{resolve:I,report:O});return}Ir(bc(y.group,{width:ct()})),Is({group:y.group,cursor:0,fromList:!0,resolve:I,rest:E.filter(k=>k.articleId!==y.group.articleId),report:O});return}if(g.escape){En(null),ue("/comments");return}return}if(gt){let d=()=>{let{rest:y,group:E,fromList:I,resolve:O,report:k}=gt;if(Is(null),!I||!k){ue("/comments");return}let v=[E,...y].sort((x,b)=>x.category.localeCompare(b.category)||x.title.localeCompare(b.title));En({cursor:0,rows:$c(v),groups:v,resolve:O,report:k})};if(g.upArrow||g.downArrow){Is(y=>y&&{...y,cursor:y.cursor===0?1:0});return}if(h==="y"||h==="Y"||g.return&>.cursor===0){let{group:y,resolve:E,rest:I,report:O}=gt;Is(null),Uu([y],{resolve:E,rest:I,...O?{report:O}:{}});return}if(h==="b"||h==="B"||g.escape||g.return){d();return}return}if(on){if(g.upArrow){Eo(d=>d&&{...d,cursor:Math.max(0,d.cursor-1)});return}if(g.downArrow){Eo(d=>d&&{...d,cursor:Math.min(d.rows.length-1,d.cursor+1)});return}if(h&&/^[0-9]$/.test(h)){let d=Nn(h,on.rows.length);d!==null&&Eo(y=>y&&{...y,cursor:d});return}if(g.return){let d=on.rows[on.cursor];Eo(null),d.action==="capture"?Ys(d.ids,{runLine:d.kind==="all"?["/screenshot capture --all","/capture --all"]:void 0}):d.action==="annotate"?Ea(d.ids,{verifiedBefore:new Set(Ke(e).filter(y=>y.state==="verified").map(y=>y.id))}):d.kind==="shot"?hg(d.ids[0]):pg(d.ids,{setup:!0,runLine:d.kind==="all"?["/screenshot author --all","/screenshot --all"]:void 0});return}if(g.escape){Eo(null);return}return}if(Wt){if(g.escape){jo(null);return}if(g.upArrow){jo(d=>d&&{...d,cursor:Math.max(0,d.cursor-1)});return}if(g.downArrow){jo(d=>d&&{...d,cursor:Math.min(Math.max(0,Ca.length-1),d.cursor+1)});return}if(g.return){let d=Ca[Wt.cursor];if(d){jo(null);try{f({kind:"preview",name:sa(d),text:O0(du(ia(e,d),"utf8"))})}catch(y){f({kind:"note",tone:"error",text:`Could not read ${d}: ${y.message}`})}}return}if(g.backspace||g.delete){jo(d=>d&&{...d,query:d.query.slice(0,-1),cursor:0});return}if(h&&!g.ctrl&&!g.meta&&h.length===1){jo(d=>d&&{...d,query:d.query+h,cursor:0});return}return}if(Bt){if(g.escape){Oo(null);return}if(g.upArrow){Oo(d=>d&&{...d,cursor:Math.max(0,d.cursor-1)});return}if(g.downArrow){Oo(d=>d&&{...d,cursor:Math.min(Math.max(0,Pa.length-1),d.cursor+1)});return}if(g.return){let d=Pa[Bt.cursor];if(d){Oo(null),Qe(d.uuid),Xe.current={uuid:d.uuid,firstPrompt:d.firstPrompt,titleFired:!0},Po(d.name),Pm(d.uuid),ge.current=[],vt.current={printed:[],armed:[],printedAt:Dr.current};let y=km(e,d.uuid);for(let E of y)f(E);f({kind:"note",tone:"ok",text:y.length?`Resumed "${d.name}" \u2014 restored ${y.length} message(s); continue where you left off.`:`Resumed "${d.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(g.backspace||g.delete){Oo(d=>d&&{...d,query:d.query.slice(0,-1),cursor:0});return}if(h&&!g.ctrl&&!g.meta&&h.length===1){Oo(d=>d&&{...d,query:d.query+h,cursor:0});return}return}if(g.tab&&!m&&K){$(K),rn();return}if(!m&&le.length>0&&!Le.current&&h&&/^[1-9]$/.test(h)){let d=le[Number(h)-1];if(d){$($o(d));return}}if(!m&&le.length===0&&!Le.current&&vt.current.armed.length>0&&h&&/^[1-9]$/.test(h)){let d=vt.current.armed[Number(h)-1];if(d){$(d);return}}if(!m&&(Hs||to)&&g.ctrl&&h==="y"){cg();return}if(!kg(h,g)){if(Ou){if(g.upArrow){Xn(d=>Math.max(0,d-1));return}if(g.downArrow){Xn(d=>Math.min(Ln.length-1,d+1));return}if(g.tab){$("/"+(Ln[$r]?.name??"")+" "),Xn(0);return}if(g.return){let d=Ln[$r];if(d){let y=m.trim().slice(1).split(/\s+/).slice(1).join(" ");if(Ek(d.usage)&&!y){$("/"+d.name+" "),Xn(0);return}zs("/"+d.name+(y?" "+y:""));return}}}else{if(!m&&le.length>0&&!Le.current&&(g.upArrow||g.downArrow)){if(g.downArrow){Qn(d=>d===null?0:Math.min(le.length-1,d+1));return}if(Sn!==null){Qn(d=>d===null||d===0?null:d-1);return}}if(g.upArrow){if(m!==""&&_t===null){La(-1);return}let d=ku.current;if(!d.length)return;let y=_t===null?d.length-1:Math.max(0,_t-1);vr(y),$(d[y]??"");return}if(g.downArrow){if(m!==""&&_t===null){La(1);return}let d=ku.current;if(_t===null)return;let y=_t+1;y>=d.length?(vr(null),$("")):(vr(y),$(d[y]??""));return}}if(g.return){if(Sn!==null&&!m&&le[Sn]){let d=$o(le[Sn]);Qn(null),zs(d);return}zs();return}if(g.backspace||g.delete){C();return}if(g.escape){nt.current&&(Zn.current=!0,Ks({kind:"stopped",how:"esc"},nt.current.parked)),$(""),Xn(0),rn(),he([]),Do(null),Qn(null),re.current=!0;return}h&&!g.ctrl&&!g.meta&&yg(h)}}}),mt(()=>{if(S||R)return;let h=Io.current.shift();h!==void 0&&($u([...Io.current]),zs(h))},[S,R,zs]),ke(Me,{flexDirection:"column",width:xt,children:[Mu!==null&&ke(Me,{marginTop:1,flexDirection:"column",children:[Mu.truncated&&Y(z,{dimColor:!0,children:"\u2026"}),Y(z,{children:Mu.text})]}),Er?Y(kF,{step:Er.step,cmd:Er.cmd,startedAt:Er.startedAt,spentUsd:Math.max(Er.spentUsd,Ht-(nt.current?.stepStartedSpend??Ht)),budgetUsd:Er.budgetUsd}):null,S&&Nr?Y(vF,{p:Nr}):null,Km?Y(bF,{text:Km}):S&&!Nr?Y(wF,{startTime:Zt.current,chars:pa}):null,Y(Me,{borderStyle:"round",borderColor:ig.prod?"yellow":pe,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:m?wg.map((h,g)=>{let d=c.text.slice(h.start,h.end),y=g===cu(wg,c.pos),E=Math.min(c.pos,h.end)-h.start;return ke(z,{children:[Y(z,{color:pe,children:g===0?"> ":" "}),y?ke(wr,{children:[d.slice(0,E),Y(Es,{ch:d[E]??" "}),d.slice(E+1)]}):d||" "]},`${g}-${h.start}`)}):ke(z,{children:[Y(z,{color:pe,children:"> "}),eo?Y(Es,{ch:" "}):oe&&!S?ke(wr,{children:[Y(Es,{ch:oe[0],dim:!0}),Y(z,{color:"gray",children:oe.slice(1)})]}):K&&!S?ke(wr,{children:[Y(Es,{ch:K[0],dim:!0}),Y(z,{color:"gray",children:K.slice(1)}),Y(z,{dimColor:!0,children:" (tab)"})]}):(Lu.isSetup||!hn)&&!S?ke(wr,{children:[Y(Es,{ch:Lu.text[0],dim:!0}),Y(z,{color:"gray",children:Lu.text.slice(1)})]}):Y(Es,{ch:" "})]})}),Gm.length>0&&Y(Me,{flexDirection:"column",paddingX:1,children:Gm.map((h,g)=>Y(z,{color:"gray",children:`\u29D7 queued: ${h}`},`${g}-${h.slice(0,24)}`))}),$t?ke(Me,{flexDirection:"column",paddingX:1,children:[Y(z,{color:pe,bold:!0,children:"Auto mode \u2014 I run each step myself"}),Y(z,{color:"gray",children:` first step ${$t.firstCmd}${$t.scale?` \u2014 ${$t.scale}`:""}`}),$t.upcoming.length>0?ke(wr,{children:[Y(z,{color:"gray",children:" as things stand, after that:"}),$t.upcoming.map(h=>Y(z,{color:"gray",children:` ${h.cmd}${h.scale?` ${h.scale}`:""}`},h.cmd)),Y(z,{color:"gray",children:" each step changes what the next one finds, so this is not a total"})]}):Y(z,{color:"gray",children:" I work down the ladder from there \u2014 reviewing, checking style, saving and going live"}),[$t.scale,...$t.upcoming.map(h=>h.scale)].every(h=>!h?.includes("$"))?Y(z,{color:"gray",children:" no cost estimate yet \u2014 this repo has not finished a run for me to measure"}):null,Y(z,{color:"gray",children:` spending limit ${et($t.budgetUsd)} \xB7 I stop and report if it is reached`}),Y(z,{color:"gray",children:" screenshots are not part of an automatic run"}),$t.overBudget?Y(z,{color:"yellow",children:`\u26A0 That is more than your ${et($t.budgetUsd)} limit. I will stop partway and report what is left.`}):null,Y(z,{dimColor:!0,children:$t.overBudget?"b raise the limit \xB7 enter start anyway \xB7 esc stay in manual for now":"enter start \xB7 b change the limit \xB7 esc stay in manual for now"})]}):Us?Y(qx,{tab:Us.tab,scroll:Us.scroll,rows:Z0,width:xt,version:o,engineVersion:_0}):Tn?ke(Me,{flexDirection:"column",paddingX:1,children:[Y(z,{color:pe,bold:!0,children:"Select model"}),Y(z,{color:"gray",children:`Your pick becomes your personal default for new sessions (team ${pt}/config.json still wins).`}),Xt.map((h,g)=>ke(z,{color:g===Tn.cursor?pe:void 0,children:[g===Tn.cursor?"\u276F ":" ",`${g+1}. ${h.label}${g===Tn.current?" \u2714":""}`.padEnd(16),Y(z,{color:"gray",children:` ${h.desc}`})]},h.label)),Y(z,{dimColor:!0,children:Lt({verb:"set as default",rows:Xt.length,extra:["s this session only"]})})]}):tn?ke(Me,{flexDirection:"column",paddingX:1,children:[Y(z,{color:pe,bold:!0,children:"Switch connection profile"}),Y(z,{color:"gray",children:"Where this repo publishes. The environment lives on the profile, not on your login."}),Y(zn,{rows:tn.rows,cursor:tn.cursor,cap:fn,render:(h,g,d)=>ke(z,{color:d?pe:void 0,children:[d?"\u276F ":" ",`${g+1}. ${h.name}${g===tn.current?" \u2714":""}`.padEnd(20),h.connect?null:Y(z,{color:"gray",children:` ${h.portalUrl||h.env}${h.project?` \xB7 ${h.project}`:""} \xB7 ${h.portalUrl?h.who??"not signed in":"cannot be reached"}`}),h.prod?Y(z,{color:"yellow",children:` ${Je}`}):null,h.internal?Y(z,{color:"gray",children:" internal"}):null]},h.name)}),Y(z,{dimColor:!0,children:Lt({verb:"switch (saved as default)",rows:tn.rows.length,extra:["s this session only"]})})]}):Mt?ke(Me,{flexDirection:"column",paddingX:1,children:[Y(z,{color:pe,bold:!0,children:"Pick your Document360 environment"}),Y(z,{color:"gray",children:"This is the portal your readers see. Rows marked internal are ours, not a customer's."}),Y(zn,{rows:Mt.rows,cursor:Mt.cursor,cap:fn,render:(h,g,d)=>ke(z,{color:d?pe:void 0,children:[d?"\u276F ":" ",`${g+1}. ${h.name}`.padEnd(18),Y(z,{color:"gray",children:` ${h.portalUrl.replace(/^https:\/\//,"")}`}),h.note?h.internal||!h.production?Y(z,{color:"yellow",children:` \u26A0 ${h.note}`}):Y(z,{color:"gray",children:` ${h.note}`}):null]},h.name)}),Y(z,{dimColor:!0,children:Lt({verb:"use it",rows:Mt.rows.length})})]}):ht?ke(Me,{flexDirection:"column",paddingX:1,children:[Y(z,{color:pe,bold:!0,children:"Switch workspace"}),Y(z,{dimColor:!0,children:`environment ${ht.environment} \xB7 project ${ht.projectName??`${ht.projectId.slice(0,8)}\u2026`}`}),Y(zn,{rows:ht.rows,cursor:ht.cursor,cap:fn,render:(h,g,d)=>ke(z,{color:d?pe:void 0,children:[d?"\u276F ":" ",`${g+1}. ${h.name}${g===ht.current?" \u2714":""}`.padEnd(30),Y(z,{color:"gray",children:h.type?` ${h.type}`:""})]},h.id)}),Y(z,{dimColor:!0,children:Lt({verb:"switch",rows:ht.rows.length})})]}):kt?ke(Me,{flexDirection:"column",paddingX:1,children:[Y(z,{color:pe,bold:!0,children:"Choose project"}),Y(z,{dimColor:!0,children:`environment ${kt.environment}`}),Y(zn,{rows:kt.rows,cursor:kt.cursor,cap:fn,render:(h,g,d)=>ke(z,{color:d?pe:void 0,children:[d?"\u276F ":" ",`${g+1}. ${h.name}${g===kt.current?" \u2714":""}`.padEnd(30),Y(z,{color:"gray",children:h.sub?` ${h.sub}`:""})]},h.id)}),Y(z,{dimColor:!0,children:Lt({verb:"switch",rows:kt.rows.length})})]}):bt?(()=>{let g=Math.min(Math.max(0,bt.cursor-Math.floor(7)),Math.max(0,bt.rows.length-14)),d=bt.rows.slice(g,g+14),y=bt.rows.filter(E=>E.checked).length;return ke(Me,{flexDirection:"column",paddingX:1,children:[Y(z,{color:pe,bold:!0,children:`Which folders back the user docs? (${y} selected of ${bt.rows.length})`}),g>0?Y(z,{dimColor:!0,children:` \u2191 ${g} more`}):null,d.map((E,I)=>{let O=g+I;return ke(z,{color:O===bt.cursor?pe:void 0,children:[O===bt.cursor?"\u276F ":" ",E.checked?"\u25C9 ":"\u25CB ",E.path.padEnd(Math.min(48,xt-34)),Y(z,{color:"gray",children:Wl(E)})]},E.path)}),g+14<bt.rows.length?Y(z,{dimColor:!0,children:` \u2193 ${bt.rows.length-g-14} more`}):null,Y(z,{dimColor:!0,children:Lt({verb:"save",multi:!0})})]})})():Pt?ke(Me,{flexDirection:"column",paddingX:1,children:[Y(z,{color:pe,bold:!0,children:Pt.title??"Which category? (pick one to scope to)"}),Y(zn,{rows:Pt.rows,cursor:Pt.cursor,cap:fn,render:(h,g,d)=>ke(z,{color:d?pe:void 0,children:[d?"\u276F ":" ",`${`${g+1}.`.padEnd(3)} ${h.label} (${h.count})`.padEnd(Math.min(44,Math.max(20,xt-24))),Y(z,{color:"gray",children:` ${h.token}`})]},h.token)}),Y(z,{dimColor:!0,children:Lt({verb:"choose it",rows:Pt.rows.length})})]}):Ut?ke(Me,{flexDirection:"column",paddingX:1,children:[Y(z,{color:pe,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),Y(zn,{rows:Ut.rows,cursor:Ut.cursor,cap:fn,render:(h,g,d)=>ke(z,{color:d?pe:void 0,bold:h.kind==="category"&&!d,children:[d?"\u276F ":" ",`${h.indent?" ":" "}${`${g+1}.`.padEnd(3)} ${h.label}`.padEnd(Math.min(56,xt-24)),h.note?Y(z,{color:"gray",children:` ${h.note}`}):null]},`${h.kind}:${h.paths.join(",")}`)}),Y(z,{dimColor:!0,children:Lt({verb:"push as drafts",rows:Ut.rows.length})})]}):nn?ke(Me,{flexDirection:"column",paddingX:1,children:[Y(z,{color:pe,bold:!0,children:"Publish live to your readers \u2014 this is what they will see:"}),Y(zn,{rows:[{path:"",articleId:"",label:`Publish all ${nn.rows.length} live`,version:void 0},...nn.rows],cursor:nn.cursor,cap:fn,render:(h,g,d)=>ke(z,{color:d?pe:void 0,bold:g===0&&!d,children:[d?"\u276F ":" ",` ${`${g+1}.`.padEnd(3)} ${h.label}`.padEnd(Math.min(56,xt-24)),g>0?Y(z,{color:"gray",children:` ${h.version?`draft v${h.version} \u2192 live`:"draft \u2192 live"}`}):null]},`${g}:${h.path||"all"}`)}),Y(z,{dimColor:!0,children:Lt({verb:"publish live",cancel:"leave as drafts",rows:nn.rows.length+1})})]}):Ft?ke(Me,{flexDirection:"column",paddingX:1,children:[Y(z,{color:pe,bold:!0,children:"Which comments do you want to look at?"}),Y(zn,{rows:Ft.rows,cursor:Ft.cursor,cap:fn,render:(h,g,d)=>ke(z,{color:d?pe:void 0,bold:h.kind==="all"&&!d,children:[d?"\u276F ":" ",`${(h.kind==="all"?"":`${h.n}.`).padEnd(4)}${h.label}`.padEnd(Math.min(56,Math.max(20,xt-24))),h.kind==="article"?Y(z,{color:"gray",children:h.note}):null]},h.kind==="all"?"all":h.group.articleId)}),Y(z,{dimColor:!0,children:Lt({verb:"open it",cancel:"close",rows:Ft.rows.length-1})}),Ft.resolve?Y(z,{dimColor:!0,children:"--resolve is on: threads you answer will be closed as well as replied to"}):null]}):gt?ke(Me,{flexDirection:"column",paddingX:1,children:[Y(z,{color:pe,bold:!0,children:`${gt.group.title} \u2014 ${gt.group.threads.length} comment${gt.group.threads.length===1?"":"s"}`}),ke(z,{color:gt.cursor===0?pe:void 0,children:[gt.cursor===0?"\u276F ":" ",gt.resolve?"Yes \u2014 fix them, push the draft, reply and resolve":"Yes \u2014 fix them, push the draft to Document360, then reply"]}),ke(z,{color:gt.cursor===1?pe:void 0,children:[gt.cursor===1?"\u276F ":" ",gt.fromList?"No \u2014 back to the list":"No \u2014 leave them for now"]}),Y(z,{dimColor:!0,children:Lt({verb:"open it",cancel:"go back",extra:["y answer"]})})]}):on?ke(Me,{flexDirection:"column",paddingX:1,children:[Y(z,{color:pe,bold:!0,children:on.title}),(()=>{let{rows:h,cursor:g}=on,d=eu(h.length,g,fn),y=d.start,E=h.slice(d.start,d.end),I=`${h.length}.`.length+1,O=Pw(h,Math.max(20,xt-4-I));return ke(wr,{children:[y>0?Y(z,{color:"gray",children:` \u2026 ${y} more above`}):null,E.map((k,v)=>{let x=y+v,b=x===g,P=O[x];return ke(z,{color:b?pe:void 0,bold:(k.kind==="all"||k.kind==="category")&&!b,children:[b?"\u276F ":" ",`${x+1}.`.padEnd(I),P.head,P.note?Y(z,{color:"gray",children:P.note}):null]},`${k.action}:${k.kind}:${k.ids.join(",")}`)}),d.below>0?Y(z,{color:"gray",children:` \u2026 ${d.below} more below`}):null]})})(),Y(z,{dimColor:!0,children:Lt({verb:"run it",rows:on.rows.length})})]}):Wt?ke(Me,{flexDirection:"column",paddingX:1,children:[Y(z,{color:pe,bold:!0,children:`Preview article${Wt.query?` \u2014 filter: ${Wt.query}`:" (type to filter)"}`}),Ca.length===0?Y(z,{color:"gray",children:"no articles match"}):Ca.map((h,g)=>ke(z,{color:g===Wt.cursor?pe:void 0,children:[g===Wt.cursor?"\u276F ":" ",h]},h)),Y(z,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):Bt?ke(Me,{flexDirection:"column",paddingX:1,children:[Y(z,{color:pe,bold:!0,children:`Resume session${Bt.query?` \u2014 filter: ${Bt.query}`:" (type to filter)"}`}),Pa.length===0?Y(z,{color:"gray",children:"no sessions match"}):Pa.map((h,g)=>ke(z,{color:g===Bt.cursor?pe:void 0,children:[g===Bt.cursor?"\u276F ":" ",h.name.slice(0,28).padEnd(30),Y(z,{color:g===Bt.cursor?pe:"gray",children:h.firstPrompt.slice(0,Math.max(10,xt-40))})]},h.uuid)),Y(z,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Ou?ke(Me,{flexDirection:"column",children:[Wo>0?Y(z,{dimColor:!0,children:` \u22EF ${Wo} more above`}):null,_u.map((h,g)=>{let d=Wo+g,y=h.name==="model"&&Pu?`${h.desc} (currently ${Pu})`:h.desc,E=Math.max(20,xt-4),I=h.usage.length>E?`${h.usage.slice(0,E-1)}\u2026`:h.usage,O=E-Math.max(I.length,22)-1,k=O<=1?"":y.length>O?`${y.slice(0,O-1)}\u2026`:y;return ke(z,{color:d===Sa?pe:void 0,children:[d===Sa?"\u276F ":" ",I.padEnd(22)," ",Y(z,{color:d===Sa?pe:"gray",children:k})]},h.name)}),Wo+_u.length<Ln.length?Y(z,{dimColor:!0,children:` \u22EF ${Ln.length-Wo-_u.length} more below`}):null,Y(z,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!S&&!m&&le.length>0?ke(Me,{flexDirection:"column",paddingX:1,children:[Hm?Y(z,{color:pe,children:Hm}):null,Y(zn,{rows:le,cursor:Sn??0,cap:fn,render:(h,g)=>{let d=g===Sn,y=$o(h),E=y.slice(0,Math.max(20,xt-7)),I=xt-E.length-9,O=I>=12?(Yx(h)??Ak(y)).slice(0,I):"";return ke(z,{color:d?pe:void 0,children:[d?"\u276F ":" ",Y(z,{color:pe,children:g+1})," ",E,O?Y(z,{color:d?pe:void 0,dimColor:!d,children:` \u2014 ${O}`}):null]},y)}}),Y(z,{dimColor:!0,children:`\u2191\u2193 choose \xB7 enter run \xB7 1-${le.length} fill \xB7 esc cancel`})]}):Y(Me,{paddingX:1,children:ke(z,{color:"gray",children:[ig.prod?Y(z,{color:"yellow",children:`${Je} \xB7 `}):null,Y(z,{color:Fs?pe:void 0,children:Fs?"\u23F5\u23F5 auto":"\u23F5 manual"}),` \xB7 /help \xB7 ${Pu??"model n/a"}${t.kind==="api"?Ht>0?` \xB7 session ${Dt(Ht)}`:"":zm>0?` \xB7 ${is(zm)}`:""} \xB7 \u2191 history \xB7 shift+tab mode \xB7 ${Y0?"press ctrl+c again to exit":"ctrl+c twice to exit"}`]})})]})}ae();import{jsx as PF}from"react/jsx-runtime";async function U0(e=process.cwd(),t="auto",n,o="0.0.0"){let r=SF(t);r.kind==="none"&&(console.error(""),console.error(L("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${Z("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${Z(`${CF} --auth subscription`)}`),process.exit(2));let{waitUntilExit:s}=RF(PF(M0,{cwd:e,auth:r,profileName:n,version:o}),{exitOnCtrlC:!1});await s(),await Rc(),process.stdout.write(`
|
|
611
|
+
`),process.exit(0)}function _m(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}function jF(){return process.stdin.isTTY===!0}function IF(){console.error(""),console.error(`This terminal is not giving ${EF} an interactive keyboard, so it started in the plain prompt instead of the full app.`),console.error(""),console.error("Typing may not work here. Two things that do:"),console.error(` npm i -g ${DF} (then run ${gu} \u2014 the full app needs a real terminal)`),console.error(` ${gu} -p "<what you want>" (one question, no prompt)`),console.error("")}function F0(e){let t=new AF;t.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 i=>{_m(i),await Fa({profile:i.profile,manual:i.manual})}),t.command("logout").description("Remove the stored Document360 session for this repo's project").option("--profile <name>","Connection profile").option("--all-projects","Sign out of every Document360 project on this machine, not just this repo's").option("--env <name>",!1).action(async i=>{_m(i),await Fg({profile:i.profile,allProjects:i.allProjects})}),t.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async i=>{_m(i),await Ug({profile:i.profile})});let n=t.command("profile").description("Manage connection profiles for the current repo");n.command("list",{isDefault:!0}).description("List profiles").action(()=>Ba(process.cwd())),n.command("add <name> [environment]").description("Create a profile for a deployment (environment defaults to the profile name)").action((i,a)=>Gg(process.cwd(),i,a)),n.command("use <name>").description("Set the default profile for this repo").action(i=>Ha(process.cwd(),i)),n.command("show [name]").description("Print the resolved profile (connection + project)").action(i=>Ga(process.cwd(),i));let o=t.command("env").description("Document360 deployments this machine can connect to");o.command("list",{isDefault:!0}).description("List deployments (the active one is marked)").action(()=>oy(process.cwd())),o.command("add <file>").description("Add deployments from a JSON file (- reads standard input)").action(i=>ry(process.cwd(),i)),o.command("remove <name>").description("Remove a deployment added on this machine").action(i=>sy(process.cwd(),i));let r=t.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");r.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(i=>Wr(process.cwd(),i.profile)),r.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(i,a)=>{process.exitCode=await Ag(process.cwd(),i,a.profile)});let s=t.command("project").description("Choose the Document360 project for this repo (active profile's identity)");return s.command("select",{isDefault:!0}).description("Interactively pick the project (lists in non-TTY)").option("--profile <name>","Connection profile").action(i=>Ma(process.cwd(),i.profile)),s.command("use <name>").description("Set the project by name (scriptable)").option("--profile <name>","Connection profile").action(async(i,a)=>{process.exitCode=await Ng(process.cwd(),i,a.profile)}),t.command("init").description(`Scaffold ${NF}/config.json for this repo (interactive)`).action(async()=>{let{initCommand:i}=await Promise.resolve().then(()=>(sl(),My));await i()}),t.command("logs").description("Show the last thing that went wrong, and where the logs are kept (/logs does the same inside the app, and offers to copy it)").action(()=>ld()),t.command("doctor").description("Health-check: node, Claude auth, Document360 login, profile/workspace, category map, API reachability, and a real agent turn").action(async()=>{let{renderDoctorChecks:i,runDoctorChecks:a}=await Promise.resolve().then(()=>(lc(),$b)),l=await a(process.cwd(),e);for(let c of i(l))console.log(c);process.exitCode=l.some(c=>c.level==="fail")?1:0}),t.name(gu).description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(e,"-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 i=>{if(TF.includes(i.auth)||(console.error(`\u2717 Invalid --auth mode: ${i.auth}`),console.error(`Run: ${gu} --auth auto | api | subscription`),process.exit(2)),i.prompt){await ay(i.cwd,i.prompt,i.auth,i.resume,i.profile,i.yes);return}i.resume&&(console.error("\u2717 --resume requires --prompt. In the interactive REPL, use /resume instead."),process.exit(2)),i.classic?await fm(i.cwd,i.auth,i.profile,e):jF()?await U0(i.cwd,i.auth,i.profile,e):(IF(),await fm(i.cwd,i.auth,i.profile,e))}),t}ae();import{writeCrashLog as Mm,isBenignTransportError as LF,PRODUCT_NAME as OF,WRITER_COMMAND as _F}from"document360-engine";var W0=!1;function MF(e=process.stdout){return e.destroyed===!0||e.writable===!1}function Um(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function B0(e){if(W0)return;W0=!0;let t=(n,o)=>{if(LF(o)){Mm({kind:n,level:"transport",message:Um(o),stack:o instanceof Error?o.stack:void 0,detail:e}),MF()&&(Mm({kind:"terminal-gone",level:"transport",message:"stdout is closed \u2014 the terminal this session was rendering to is gone, so it exited rather than spin.",detail:e}),process.exit(0));return}let r=Mm({kind:n,level:"fatal",message:Um(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
|
|
612
|
+
`+L(`\u2717 ${OF} crashed: ${Um(o)}`)+`
|
|
613
613
|
`),r&&process.stderr.write(u(` Crash details: ${r}`)+`
|
|
614
|
-
`+u(
|
|
615
|
-
`),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var
|
|
614
|
+
`+u(` Run: ${_F} logs`)+`
|
|
615
|
+
`),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}ae();import{spawnSync as yu}from"node:child_process";import{CAPTURE_COMMAND as H0,CAPTURE_PACKAGE as UF,WRITER_COMMAND as FF,WRITER_PACKAGE as WF,detectInstallKind as BF,isSelfUpdatable as HF}from"document360-engine";var js={name:"Document360 Lotus",command:"d360-lotus",writer:"@document360/lotus",capture:"@document360/lotus-capture"};function G0(e){return["i","-g",`${js.writer}@latest`,...e?[`${js.capture}@latest`]:[]]}function q0(e){return["rm","-g",WF,...e?[UF]:[]]}function V0(e){return(process.platform==="win32"?yu(`npm ${e.join(" ")}`,{shell:!0,stdio:"inherit",windowsHide:!0}):yu("npm",e,{stdio:"inherit"})).status??1}function GF(){return(process.platform==="win32"?yu(`${H0} --version`,{shell:!0,stdio:"ignore",windowsHide:!0}):yu(H0,["--version"],{stdio:"ignore"})).status===0}function K0(e,t=BF()){if(!HF(t)||["--version","-V"].includes(e[2]??""))return"continue";let n=GF();if(console.error(Q(`\u2B06 ${FF} is now ${js.name}.`)),console.error(""),console.error(u("Installing it now. This takes about a minute.")),console.error(""),V0(G0(n))!==0)return console.error(""),console.error(F(`\u26A0 Could not install ${js.name}. This version still works for now.`)),console.error(""),console.error(`Install it yourself: npm ${G0(n).join(" ")}`),console.error(""),"continue";let o=V0(q0(n))===0;return console.error(""),console.error(Q(`\u2713 ${js.name} is installed. Your sign-ins and settings come with it.`)),console.error(""),o||console.error(`Remove the old version: npm ${q0(n).join(" ")}
|
|
616
|
+
`),console.error(`From now on, type: ${js.command}`),console.error(""),"exit"}var KF=qF(import.meta.url),YF=KF("../package.json");B0(VF);K0(process.argv)==="exit"&&process.exit(0);F0(YF.version).parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
|