1 import { CloudAnalysisResult, CloudDispatchPayload } from "../types/index.js"
2
3 const DASHBOARD_CHANGELOG_DIR = "www/apps/cloud/generated/changelog"
4 const DASHBOARD_CHANGELOG_PAGE = "www/apps/cloud/app/changelog/page.mdx"
5
6 export class CloudContextBuilder {
7 build(
8 payload: CloudDispatchPayload,
9 releaseDate?: string,
10 isoReleaseDate?: string
11 ): CloudAnalysisResult {
12 const changelog = this.getChangelog(payload, releaseDate)
13 const claudePrompt = this.buildPrompt(
14 payload,
15 changelog,
16 releaseDate,
17 isoReleaseDate
18 )
19
20 return {
21 affectedProjects: [
22 {
23 project: "cloud",
24 reason: "User-facing changes were deployed to Cloud Production",
25 },
26 ],
27 claudePrompt,
28 featureFlaggedFeatures: payload.featureFlaggedFeatures ?? [],
29 ...(changelog ? { changelog } : {}),
30 // Only dashboard changes produce a changelog entry, and only then does
31 // the workflow have a banner to render.
32 ...(payload.descriptions?.trim() && releaseDate && isoReleaseDate
33 ? {
34 changelogEntry: {
35 date: isoReleaseDate,
36 displayDate: releaseDate,
37 file: `${DASHBOARD_CHANGELOG_DIR}/${isoReleaseDate}.mjs`,
38 },
39 }
40 : {}),
41 }
42 }
43
44 /**
45 * Returns the changelog entry to write only when the dispatch carries a CLI
46 * release with non-empty notes AND a version. Otherwise returns undefined so
47 * the dashboard/CLI-reference flow is left untouched.
48 */
49 private getChangelog(
50 payload: CloudDispatchPayload,
51 releaseDate?: string
52 ): { version: string; notes: string; date?: string } | undefined {
53 const notes = payload.releaseNotes?.trim()
54 if (!notes || !payload.version) {
55 return undefined
56 }
57
58 return { version: payload.version, notes, date: releaseDate }
59 }
60
61 private buildPrompt(
62 payload: CloudDispatchPayload,
63 changelog?: { version: string; notes: string; date?: string },
64 releaseDate?: string,
65 isoReleaseDate?: string
66 ): string {
67 const sections: string[] = []
68
69 sections.push(this.buildSkillSection())
70 sections.push(this.buildTaskSection())
71 sections.push(
72 this.buildDescriptionsSection(
73 payload.descriptions,
74 payload.featureFlaggedFeatures ?? []
75 )
76 )
77
78 if (payload.descriptions?.trim()) {
79 sections.push(
80 this.buildDashboardChangelogSection(releaseDate, isoReleaseDate)
81 )
82 }
83
84 if (changelog) {
85 sections.push(this.buildChangelogSection(changelog))
86 }
87
88 sections.push(this.buildAffectedProjectSection())
89 sections.push(this.buildConstraintsSection())
90
91 return sections.join("\n\n---\n\n")
92 }
93
94 private buildSkillSection(): string {
95 return `## Instructions
96
97 Use the /writing-docs skill before making any documentation changes. Load the \`reference/cloud-style.md\` reference file from that skill — it contains the rules and patterns for writing Medusa Cloud documentation correctly.`
98 }
99
100 private buildTaskSection(): string {
101 return `## Task
102
103 A new version of Medusa Cloud was deployed to production. The section below describes user-facing changes that were shipped. Changes may include dashboard UI updates, Cloud CLI updates, or both.
104
105 Your job is to:
106 1. Load the /writing-docs skill and read \`reference/cloud-style.md\`
107 2. Review the feature descriptions below
108 3. For each described change, determine whether a documentation update is needed
109 4. **Dashboard changes**: If an existing page covers the feature, update it. If a new feature has no existing page and is substantial enough, create one and add it to \`www/apps/cloud/sidebar.mjs\`
110 5. **Dashboard changelog**: Record the dashboard changes as a changelog entry file, as explained in the "Cloud Changelog" section below
111 6. **CLI changes**: Update the relevant command page under \`www/apps/cloud/app/cli/commands/\`. If a new command was added, create a new page and add it to the sidebar under the CLI category. If a command was removed, remove its page and sidebar entry. Follow the existing CLI page format (see the CLI section in \`reference/cloud-style.md\`)
112 7. If a described change is too vague or clearly internal, skip it rather than guess`
113 }
114
115 private buildDescriptionsSection(
116 descriptions: string,
117 featureFlaggedFeatures: string[]
118 ): string {
119 const lines: string[] = [
120 `## Feature Descriptions`,
121 ``,
122 `The following describes user-facing changes that were shipped in this deployment. These descriptions were generated by analyzing the dashboard and/or CLI code changes — they contain no source code, only behavioral descriptions. Changes are organized under \`## Dashboard Changes\` and/or \`## Cloud CLI Changes\` headings.`,
123 ``,
124 descriptions,
125 ]
126
127 if (featureFlaggedFeatures.length > 0) {
128 lines.push(``)
129 lines.push(
130 `> **Note:** The following features appear to be guarded by a feature flag and may not be visible to all users yet: ${featureFlaggedFeatures.map((f) => `**${f}**`).join(", ")}. Document them as normal but be aware they may not be fully released.`
131 )
132 }
133
134 return lines.join("\n")
135 }
136
137 /**
138 * Instructs Claude to record the dashboard changes of this deployment in the
139 * Cloud changelog. The changelog is dated rather than versioned, since the
140 * dashboard has no user-facing version number, and each date is its own
141 * entry file that the changelog page renders.
142 */
143 private buildDashboardChangelogSection(
144 releaseDate?: string,
145 isoReleaseDate?: string
146 ): string {
147 const heading = releaseDate ?? "{Month} {Day}, {Year}"
148 const isoDate = isoReleaseDate ?? "{YYYY-MM-DD}"
149
150 return `## Cloud Changelog
151
152 Record the **dashboard** changes of this deployment in the Cloud changelog. This changelog covers the Cloud dashboard only — CLI and webhook changes have their own changelog pages and must never be added here.
153
154 The changelog page at \`${DASHBOARD_CHANGELOG_PAGE}\` holds only the intro and a \`<ChangelogList />\` component. **Never add entries to that page.** Each dated entry is its own file in \`${DASHBOARD_CHANGELOG_DIR}\`, named after its date.
155
156 **Entry file for this deployment:** \`${DASHBOARD_CHANGELOG_DIR}/${isoDate}.mjs\`
157
158 Steps:
159 1. If \`${DASHBOARD_CHANGELOG_DIR}/${isoDate}.mjs\` already exists (this deployment may be re-run), **merge** the new bullet points into its \`content\` and rewrite its \`title\` and \`summary\` to cover the merged entry, instead of overwriting or duplicating the file. Leave any \`image\` property it already has untouched. Otherwise, create it with exactly this shape:
160 \`\`\`js
161 /** @type {import("../../utils/changelog").ChangelogEntry} */
162 export default {
163 date: "${isoDate}",
164 title: "Short headline for this entry",
165 summary: "One sentence covering what this entry is about.",
166 content: \`- First change of this deployment.
167 - Second change of this deployment.\`,
168 }
169 \`\`\`
170 2. \`date\` must match the file name exactly, in \`YYYY-MM-DD\` format.
171 3. \`title\` is a **short headline** that the changelog page uses as the entry's heading. Name what shipped, not the date — the date is shown next to it. Aim for 3 to 8 words, under 60 characters, with no trailing period, no Markdown, and no link. Use sentence case, and don't start it with "Added", "New", or the date. When the entry has one change, name that change; when it has several, name the theme they share, or join the two biggest with "and".
172 4. \`summary\` is **one plain sentence** summarizing what the entry covers as a whole, written for someone who hasn't read the bullets. Keep it under 160 characters, write it in the present tense, and don't use Markdown, links, or a trailing list of every change. It's a double-quoted string, so it can't span lines. Don't restate the \`title\` verbatim — the summary adds the detail the headline leaves out.
173 5. \`content\` is Markdown holding **only** the bullet points. Never write a heading in it — the page renders the heading from \`title\`, so a \`## ${heading}\` or a \`## \` repeating the title would show up twice.
174 6. Add one bullet point per user-facing dashboard change. Write each bullet in the present tense, describing what a user can now do or what now behaves differently.
175 7. If the change is covered by a documentation page, link to that page in its bullet point. Links to Cloud documentation pages are **root-relative, without the \`/cloud\` base path and without the \`page.mdx\` suffix**, such as \`[Environment Variables](/environments/environment-variables)\`. Link to the page you updated for that change, and only link to pages that exist.
176 8. \`content\` is a template literal, so escape any backtick or \`\${\` you write inside it.
177 9. Never write an \`image\` property. The entry's banner image is rendered and attached by a later step of this workflow.
178 10. Do not create, edit, or reorder \`${DASHBOARD_CHANGELOG_DIR}/index.mjs\`. It's a generated manifest, rebuilt by the \`yarn prep\` step that runs after you finish.
179 11. If this deployment has no dashboard changes that qualify below, don't create an entry file.
180
181 **What belongs in the changelog:**
182
183 - New functionality, such as a new page, resource, setting, or action a user can take
184 - Changes to how existing functionality behaves, such as a different default, a new validation, or a changed limit
185 - New or removed form inputs, along with why the input was added and what it controls
186 - Overall design and navigation changes, such as a new navigation style, a restructured page, or a moved action
187
188 **What does not belong in the changelog:**
189
190 - Copy changes, such as a renamed label, a reworded description, or an added note or tooltip
191 - Visual polish that doesn't change behavior, such as spacing, colors, or icon swaps
192 - Bug fixes with no user-visible behavior change, performance work, and internal refactors
193 - Anything not visible to users in the dashboard
194
195 **Example entry file** (\`${DASHBOARD_CHANGELOG_DIR}/2026-08-10.mjs\`):
196
197 \`\`\`js
198 /** @type {import("../../utils/changelog").ChangelogEntry} */
199 export default {
200 date: "2026-08-10",
201 title: "Build-time and runtime environment variables",
202 summary: "Environment variables can be scoped to build time or runtime, and the sidebar is now grouped by project.",
203 content: \`- You can now set an environment variable as available at build time, runtime, or both, which controls whether Medusa injects it into your build or your running application. Refer to [Environment Variables](/environments/environment-variables) for more details.
204 - The dashboard's sidebar navigation is now grouped by project, so switching between a project's environments no longer requires going back to the organization's page.\`,
205 }
206 \`\`\``
207 }
208
209 private buildChangelogSection(changelog: {
210 version: string
211 notes: string
212 date?: string
213 }): string {
214 const heading = changelog.date
215 ? `${changelog.version} (${changelog.date})`
216 : changelog.version
217
218 return `## Cloud CLI Changelog
219
220 A new version of the Cloud CLI (\`mcloud\`) was released: **${changelog.version}**${changelog.date ? ` on **${changelog.date}**` : ""}. You must record it in the Cloud CLI changelog page.
221
222 **Changelog page:** \`www/apps/cloud/app/cli/changelog/page.mdx\`
223
224 Steps:
225 1. If \`www/apps/cloud/app/cli/changelog/page.mdx\` does not exist, create it first following the format of other CLI pages (frontmatter with \`metadata.title\`, an \`# {metadata.title}\` heading, and a one-sentence intro explaining it lists notable changes to the Cloud CLI, newest first). Then add a sidebar entry for it in \`www/apps/cloud/sidebar.mjs\` under the CLI category, right after the "For Agents" entry:
226 \`\`\`js
227 {
228 type: "link",
229 title: "Changelog",
230 path: "/cli/changelog",
231 hideFromChildItems: true,
232 },
233 \`\`\`
234 2. Add a section for version \`${changelog.version}\` using a \`## ${heading}\` heading, placed **newest-first** (above any existing version sections, directly below the intro). Keep the version and date together in the heading exactly as shown.
235 3. Under that heading, render the release notes below **exactly as provided** — do not rewrite, summarize, invent commands/versions/dates, or add content not present in the notes.
236 4. If a section for version \`${changelog.version}\` already exists (this release may be re-run), **update it in place** (including its heading and notes) instead of adding a duplicate section.
237
238 Release notes for \`${changelog.version}\`:
239
240 ${changelog.notes}`
241 }
242
243 private buildAffectedProjectSection(): string {
244 return `## Affected Documentation Project
245
246 ### cloud
247
248 **Project path:** \`www/apps/cloud\`
249
250 **Writable directories (only modify files within these):**
251 - \`www/apps/cloud/app/\` — dashboard docs and CLI docs (CLI pages live under \`www/apps/cloud/app/cli/\`)
252 - \`www/apps/cloud/sidebar.mjs\`
253 - \`${DASHBOARD_CHANGELOG_DIR}/\` — dashboard changelog entry files only, never its generated \`index.mjs\`
254
255 **CLI docs structure:**
256 - \`www/apps/cloud/app/cli/page.mdx\` — CLI overview and installation
257 - \`www/apps/cloud/app/cli/agents/page.mdx\` — CLI for AI agents
258 - \`www/apps/cloud/app/cli/commands/<command>/page.mdx\` — one page per command topic (e.g. \`deployments\`, \`environments\`, \`variables\`)
259 - Each command page documents all subcommands for that topic (e.g. \`deployments list\`, \`deployments get\`, \`deployments build-logs\` all on the same page)
260
261 **Changelog pages:**
262 - \`${DASHBOARD_CHANGELOG_DIR}/{YYYY-MM-DD}.mjs\` — dated changelog of dashboard changes, one file per date, rendered by \`${DASHBOARD_CHANGELOG_PAGE}\`
263 - \`www/apps/cloud/app/cli/changelog/page.mdx\` — versioned changelog of Cloud CLI releases
264 - \`www/apps/cloud/app/webhooks/changelog/page.mdx\` — dated changelog of webhook event changes (never write to it from this workflow)`
265 }
266
267 private buildConstraintsSection(): string {
268 return `## Hard Constraints
269
270 These are absolute rules. Violating them will cause the workflow to fail:
271
272 1. **Only write files within \`www/apps/cloud/app/\`** or \`www/apps/cloud/sidebar.mjs\`
273 2. **Never modify \`www/apps/cloud/generated/\`** — auto-generated by \`yarn prep\`, which runs automatically after your session
274 3. **Do not run \`yarn prep\` or \`yarn lint:content\`** — these run automatically after your session ends
275 4. **Do not invent Cloudinary screenshot URLs** — they can be manually added later if needed.
276 5. **Do not document internal platform details** — only user-visible behaviors, UI flows, and settings
277 6. **If a description is too vague to write accurate docs, skip it** rather than guess or fabricate details`
278 }
279 }