@kidecms/core 0.1.10 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (182) hide show
  1. package/LICENSE +21 -0
  2. package/admin/components/AssetsGrid.tsx +366 -173
  3. package/admin/components/BlockEditor.tsx +260 -679
  4. package/admin/components/CheckboxField.tsx +2 -2
  5. package/admin/components/CollaborationReviewBar.tsx +384 -0
  6. package/admin/components/ColorField.tsx +87 -0
  7. package/admin/components/CommandPalette.tsx +169 -0
  8. package/admin/components/ContentEditor.tsx +687 -0
  9. package/admin/components/DocumentActions.tsx +4 -2
  10. package/admin/components/DocumentsDataTable.tsx +91 -10
  11. package/admin/components/FieldControl.astro +151 -26
  12. package/admin/components/FocalPointSelector.tsx +27 -1
  13. package/admin/components/InternalLinkPicker.tsx +4 -3
  14. package/admin/components/LinkField.tsx +126 -0
  15. package/admin/components/RelationField.tsx +105 -26
  16. package/admin/components/RepeaterInput.tsx +46 -0
  17. package/admin/components/RichTextEditor.tsx +44 -9
  18. package/admin/components/SharedSectionBlockField.tsx +93 -0
  19. package/admin/components/SidebarUserMenu.tsx +1 -1
  20. package/admin/components/Toast.astro +1 -1
  21. package/admin/components/TreeItemsEditor.tsx +20 -19
  22. package/admin/components/TreeSelect.tsx +2 -2
  23. package/admin/components/YoutubeField.tsx +48 -0
  24. package/admin/components/block-fields.tsx +777 -0
  25. package/admin/components/content-block-spec.ts +114 -0
  26. package/admin/components/slash-command.tsx +242 -0
  27. package/admin/components/tree-utils.ts +14 -2
  28. package/admin/components/ui/badge.tsx +2 -3
  29. package/admin/components/ui/button.tsx +5 -4
  30. package/admin/components/ui/checkbox.tsx +1 -1
  31. package/admin/components/ui/input.tsx +1 -1
  32. package/admin/components/ui/select.tsx +1 -1
  33. package/admin/components/ui/table.tsx +1 -1
  34. package/admin/components/ui/textarea.tsx +1 -1
  35. package/admin/layouts/AdminLayout.astro +323 -123
  36. package/admin/lib/access.ts +54 -0
  37. package/admin/lib/collaboration.ts +178 -0
  38. package/admin/lib/edit-data.ts +448 -0
  39. package/admin/views/AccessDeniedView.astro +8 -0
  40. package/admin/views/EditView.astro +706 -0
  41. package/admin/views/ListView.astro +202 -0
  42. package/admin/views/RecentView.astro +76 -0
  43. package/admin/views/SinglesView.astro +65 -0
  44. package/admin/views/edit/EditScripts.astro +145 -0
  45. package/admin/views/edit/ReverseReferencesList.astro +68 -0
  46. package/core/admin.ts +193 -0
  47. package/core/ai.ts +87 -0
  48. package/core/api.ts +1392 -0
  49. package/core/assets.ts +336 -0
  50. package/core/audit.ts +84 -0
  51. package/core/auth-config.ts +44 -0
  52. package/core/auth.ts +303 -0
  53. package/core/collaboration.ts +276 -0
  54. package/core/content.ts +27 -0
  55. package/core/create-admin.ts +28 -0
  56. package/core/define.ts +625 -0
  57. package/core/field-model.ts +172 -0
  58. package/core/generator.ts +519 -0
  59. package/core/http.ts +42 -0
  60. package/core/image.ts +219 -0
  61. package/core/index.ts +211 -0
  62. package/core/locks.ts +52 -0
  63. package/core/log.ts +37 -0
  64. package/core/migrate.ts +278 -0
  65. package/core/rate-limit.ts +110 -0
  66. package/core/request-scope.ts +33 -0
  67. package/core/richtext.ts +1 -0
  68. package/core/runtime.ts +63 -0
  69. package/core/schema.ts +32 -0
  70. package/core/search.ts +489 -0
  71. package/core/seed.ts +101 -0
  72. package/core/shared-sections.ts +96 -0
  73. package/core/tasks.ts +176 -0
  74. package/core/values.ts +433 -0
  75. package/core/webhooks.ts +85 -0
  76. package/core/youtube.ts +39 -0
  77. package/internals/cli.mjs +34 -0
  78. package/internals/context.ts +67 -0
  79. package/internals/create-admin.ts +40 -0
  80. package/internals/describe.ts +25 -0
  81. package/internals/eject.ts +144 -0
  82. package/internals/generator.ts +11 -0
  83. package/internals/integration.ts +481 -0
  84. package/internals/mcp.ts +397 -0
  85. package/internals/project.ts +26 -0
  86. package/internals/push.ts +160 -0
  87. package/internals/reindex.ts +11 -0
  88. package/internals/restore.ts +257 -0
  89. package/internals/seed.data.ts +7 -0
  90. package/internals/seed.ts +11 -0
  91. package/internals/upgrade.ts +776 -0
  92. package/{virtual.d.ts → internals/virtual.d.ts} +39 -5
  93. package/middleware/auth.ts +130 -17
  94. package/middleware/push.ts +121 -0
  95. package/package.json +55 -67
  96. package/platform/cloudflare/cf-env.ts +60 -0
  97. package/platform/cloudflare/database.ts +28 -0
  98. package/platform/cloudflare/globals.d.ts +5 -0
  99. package/platform/cloudflare/storage.ts +33 -0
  100. package/platform/cloudflare/uploads-route.ts +37 -0
  101. package/platform/node/database.ts +39 -0
  102. package/platform/node/storage.ts +52 -0
  103. package/routes/admin/[...path].astro +71 -0
  104. package/routes/{pages/admin → admin}/assets/[id].astro +25 -19
  105. package/routes/admin/assets/index.astro +90 -0
  106. package/routes/admin/forgot-password.astro +60 -0
  107. package/routes/{pages/admin → admin}/invite.astro +7 -6
  108. package/routes/admin/login.astro +103 -0
  109. package/routes/admin/reset-password.astro +73 -0
  110. package/routes/{pages/admin → admin}/setup.astro +32 -8
  111. package/routes/api/{cms/[collection] → [collection]}/[...path].ts +66 -14
  112. package/routes/api/admin/search.ts +89 -0
  113. package/routes/api/{cms/assets → assets}/[id].ts +24 -14
  114. package/routes/api/{cms/assets → assets}/index.ts +4 -2
  115. package/routes/api/assets/upload.ts +147 -0
  116. package/routes/api/auth/forgot-password.ts +77 -0
  117. package/routes/api/{cms/auth → auth}/invite.ts +41 -9
  118. package/routes/api/auth/login.ts +167 -0
  119. package/routes/api/{cms/auth → auth}/logout.ts +11 -2
  120. package/routes/api/auth/reset-password.ts +85 -0
  121. package/routes/api/auth/setup.ts +110 -0
  122. package/routes/api/auth/sso/[provider]/start.ts +34 -0
  123. package/routes/api/collaboration/index.ts +106 -0
  124. package/routes/api/cron/_authorize.ts +25 -0
  125. package/routes/api/{cms/cron → cron}/publish.ts +3 -9
  126. package/routes/api/cron/tasks.ts +33 -0
  127. package/routes/api/forms/submit/[slug].ts +143 -0
  128. package/routes/api/img/[...path].ts +65 -0
  129. package/routes/api/{cms/preview → preview}/render.ts +8 -3
  130. package/routes/api/{cms/references → references}/[collection]/[id].ts +31 -1
  131. package/routes/api/webhooks/[provider].ts +54 -0
  132. package/README.md +0 -28
  133. package/dist/admin.d.ts +0 -33
  134. package/dist/admin.js +0 -92
  135. package/dist/ai.d.ts +0 -15
  136. package/dist/ai.js +0 -70
  137. package/dist/api.d.ts +0 -14
  138. package/dist/api.js +0 -833
  139. package/dist/assets.d.ts +0 -51
  140. package/dist/assets.js +0 -163
  141. package/dist/auth.d.ts +0 -30
  142. package/dist/auth.js +0 -132
  143. package/dist/content.d.ts +0 -3
  144. package/dist/content.js +0 -29
  145. package/dist/create-admin.d.ts +0 -5
  146. package/dist/create-admin.js +0 -23
  147. package/dist/define.d.ts +0 -254
  148. package/dist/define.js +0 -36
  149. package/dist/generator.d.ts +0 -9
  150. package/dist/generator.js +0 -370
  151. package/dist/image.d.ts +0 -9
  152. package/dist/image.js +0 -69
  153. package/dist/index.d.ts +0 -28
  154. package/dist/index.js +0 -16
  155. package/dist/integration.d.ts +0 -14
  156. package/dist/integration.js +0 -327
  157. package/dist/locks.d.ts +0 -7
  158. package/dist/locks.js +0 -37
  159. package/dist/richtext.d.ts +0 -1
  160. package/dist/richtext.js +0 -1
  161. package/dist/runtime.d.ts +0 -24
  162. package/dist/runtime.js +0 -26
  163. package/dist/schema.d.ts +0 -17
  164. package/dist/schema.js +0 -13
  165. package/dist/seed.d.ts +0 -2
  166. package/dist/seed.js +0 -84
  167. package/dist/values.d.ts +0 -8
  168. package/dist/values.js +0 -102
  169. package/dist/webhooks.d.ts +0 -2
  170. package/dist/webhooks.js +0 -73
  171. package/routes/api/cms/assets/upload.ts +0 -112
  172. package/routes/api/cms/auth/login.ts +0 -124
  173. package/routes/api/cms/auth/setup.ts +0 -77
  174. package/routes/api/cms/img/[...path].ts +0 -24
  175. package/routes/pages/admin/[...path].astro +0 -1107
  176. package/routes/pages/admin/assets/index.astro +0 -63
  177. package/routes/pages/admin/login.astro +0 -57
  178. /package/routes/api/{cms/ai → ai}/alt-text.ts +0 -0
  179. /package/routes/api/{cms/ai → ai}/seo.ts +0 -0
  180. /package/routes/api/{cms/ai → ai}/translate.ts +0 -0
  181. /package/routes/api/{cms/assets → assets}/folders.ts +0 -0
  182. /package/routes/api/{cms/locks → locks}/[...path].ts +0 -0
@@ -0,0 +1,776 @@
1
+ /**
2
+ * `pnpm cms:upgrade [target-tag]` - prepare and optionally apply a release-tag
3
+ * upgrade from the upstream Kide template into this vendored project.
4
+ *
5
+ * The command treats `.kide-version` as the source of truth, writes an upgrade
6
+ * packet under `.kide/upgrade/`, applies only clearly managed CMS runtime paths,
7
+ * and leaves project-owned files as review material for a human or any coding
8
+ * agent.
9
+ */
10
+ import { execFileSync, spawnSync } from "node:child_process";
11
+ import { createHash } from "node:crypto";
12
+ import {
13
+ copyFileSync,
14
+ existsSync,
15
+ mkdirSync,
16
+ mkdtempSync,
17
+ readFileSync,
18
+ rmSync,
19
+ statSync,
20
+ writeFileSync,
21
+ } from "node:fs";
22
+ import { tmpdir } from "node:os";
23
+ import path from "node:path";
24
+
25
+ type VersionStamp = {
26
+ template?: string;
27
+ kideVersion?: string | null;
28
+ ref?: string;
29
+ commit?: string | null;
30
+ target?: string;
31
+ mode?: "embedded" | "package";
32
+ corePath?: string;
33
+ upgrades?: UpgradeRecord[];
34
+ [key: string]: unknown;
35
+ };
36
+
37
+ type UpgradeRecord = {
38
+ from: string;
39
+ to: string;
40
+ fromCommit: string | null;
41
+ toCommit: string;
42
+ at: string;
43
+ packet: string;
44
+ applied: boolean;
45
+ };
46
+
47
+ type Args = {
48
+ targetRef?: string;
49
+ fromRef?: string;
50
+ repo?: string;
51
+ corePath?: string;
52
+ apply?: boolean;
53
+ allowDirty: boolean;
54
+ agent: "auto" | "none" | "claude" | "codex" | "cursor";
55
+ help: boolean;
56
+ };
57
+
58
+ type AgentInfo = {
59
+ id: "claude" | "codex" | "cursor";
60
+ label: string;
61
+ command: string;
62
+ };
63
+
64
+ type FileCheckpoint = {
65
+ exists: boolean;
66
+ sha256?: string;
67
+ size?: number;
68
+ };
69
+
70
+ type BackupEntry = {
71
+ file: string;
72
+ existed: boolean;
73
+ backupSha256?: string;
74
+ backupSize?: number;
75
+ afterAttempt?: FileCheckpoint & { at?: string };
76
+ };
77
+
78
+ type BackupManifest = {
79
+ createdAt?: string;
80
+ backedUp?: string[];
81
+ missing?: string[];
82
+ entries?: BackupEntry[];
83
+ [key: string]: unknown;
84
+ };
85
+
86
+ const DEFAULT_REPO = "https://github.com/mhernesniemi/kide-cms.git";
87
+ const DEFAULT_CORE_PATH = "src/cms";
88
+
89
+ const AGENTS: AgentInfo[] = [
90
+ { id: "claude", label: "Claude Code", command: "claude" },
91
+ { id: "codex", label: "Codex", command: "codex" },
92
+ { id: "cursor", label: "Cursor", command: "cursor" },
93
+ ];
94
+
95
+ const usage = `Usage:
96
+ pnpm cms:upgrade [target-tag]
97
+
98
+ Options:
99
+ --from <ref> Override the source release/ref from .kide-version
100
+ --repo <url|path> Override the upstream Kide core repo
101
+ --core-path <path> Managed CMS path in this project (default: src/cms)
102
+ --apply Apply the managed patch even when not selected by default
103
+ --packet-only Only write the upgrade packet; do not change project files
104
+ --allow-dirty Allow applying on top of an uncommitted worktree
105
+ --agent <name> auto, none, claude, codex, or cursor (default: auto)
106
+ --help Show this help
107
+
108
+ Examples:
109
+ pnpm cms:upgrade v0.11.0
110
+ pnpm cms:upgrade --packet-only
111
+ pnpm cms:upgrade v0.11.0 --agent none
112
+ `;
113
+
114
+ const parseArgs = (argv: string[]): Args => {
115
+ const args: Args = {
116
+ allowDirty: false,
117
+ agent: (process.env.KIDE_UPGRADE_AGENT as Args["agent"]) || "auto",
118
+ help: false,
119
+ };
120
+
121
+ const takeValue = (index: number, flag: string) => {
122
+ const value = argv[index + 1];
123
+ if (!value || value.startsWith("--")) {
124
+ throw new Error(`${flag} requires a value.`);
125
+ }
126
+ return value;
127
+ };
128
+
129
+ for (let i = 0; i < argv.length; i += 1) {
130
+ const arg = argv[i];
131
+ if (arg === "--help" || arg === "-h") {
132
+ args.help = true;
133
+ } else if (arg === "--from") {
134
+ args.fromRef = takeValue(i, arg);
135
+ i += 1;
136
+ } else if (arg.startsWith("--from=")) {
137
+ args.fromRef = arg.slice("--from=".length);
138
+ } else if (arg === "--repo") {
139
+ args.repo = takeValue(i, arg);
140
+ i += 1;
141
+ } else if (arg.startsWith("--repo=")) {
142
+ args.repo = arg.slice("--repo=".length);
143
+ } else if (arg === "--core-path") {
144
+ args.corePath = trimSlashes(takeValue(i, arg));
145
+ i += 1;
146
+ } else if (arg.startsWith("--core-path=")) {
147
+ args.corePath = trimSlashes(arg.slice("--core-path=".length));
148
+ } else if (arg === "--apply") {
149
+ args.apply = true;
150
+ } else if (arg === "--packet-only") {
151
+ args.apply = false;
152
+ } else if (arg === "--allow-dirty") {
153
+ args.allowDirty = true;
154
+ } else if (arg === "--agent") {
155
+ args.agent = parseAgent(takeValue(i, arg));
156
+ i += 1;
157
+ } else if (arg.startsWith("--agent=")) {
158
+ args.agent = parseAgent(arg.slice("--agent=".length));
159
+ } else if (arg.startsWith("--")) {
160
+ throw new Error(`Unknown option: ${arg}`);
161
+ } else if (!args.targetRef) {
162
+ args.targetRef = arg;
163
+ } else {
164
+ throw new Error(`Unexpected argument: ${arg}`);
165
+ }
166
+ }
167
+
168
+ return args;
169
+ };
170
+
171
+ const parseAgent = (value: string): Args["agent"] => {
172
+ if (value === "auto" || value === "none" || value === "claude" || value === "codex" || value === "cursor") {
173
+ return value;
174
+ }
175
+ throw new Error(`Unknown agent "${value}". Use auto, none, claude, codex, or cursor.`);
176
+ };
177
+
178
+ const trimSlashes = (value: string) => value.replace(/^\/+|\/+$/g, "");
179
+
180
+ const runRaw = (command: string, args: string[], options: { cwd?: string; input?: string } = {}) =>
181
+ execFileSync(command, args, {
182
+ cwd: options.cwd,
183
+ input: options.input,
184
+ encoding: "utf-8",
185
+ maxBuffer: 1024 * 1024 * 100,
186
+ stdio: ["pipe", "pipe", "pipe"],
187
+ });
188
+
189
+ const run = (command: string, args: string[], options: { cwd?: string; input?: string } = {}) =>
190
+ runRaw(command, args, options).trim();
191
+
192
+ const tryRun = (command: string, args: string[], options: { cwd?: string } = {}) => {
193
+ try {
194
+ return { ok: true as const, stdout: run(command, args, options), stderr: "" };
195
+ } catch (error) {
196
+ const err = error as { stdout?: Buffer | string; stderr?: Buffer | string; message?: string };
197
+ return {
198
+ ok: false as const,
199
+ stdout: String(err.stdout ?? ""),
200
+ stderr: String(err.stderr ?? err.message ?? ""),
201
+ };
202
+ }
203
+ };
204
+
205
+ const readStamp = (cwd: string): VersionStamp | null => {
206
+ const file = path.join(cwd, ".kide-version");
207
+ if (!existsSync(file)) return null;
208
+ try {
209
+ return JSON.parse(readFileSync(file, "utf-8")) as VersionStamp;
210
+ } catch (error) {
211
+ throw new Error(`Could not parse .kide-version: ${(error as Error).message}`, { cause: error });
212
+ }
213
+ };
214
+
215
+ const stripGitSuffix = (repo: string) => repo.replace(/\.git$/, "");
216
+
217
+ const resolveLatestTag = (repo: string) => {
218
+ const output = run("git", ["ls-remote", "--tags", "--sort=-v:refname", repo, "v*"]);
219
+ for (const line of output.split("\n")) {
220
+ const match = line.match(/refs\/tags\/(v[0-9][^^\s]*)$/);
221
+ if (match) return match[1];
222
+ }
223
+ throw new Error(`No v-prefixed release tags found in ${repo}. Pass a target tag explicitly.`);
224
+ };
225
+
226
+ const cloneUpstream = (repo: string) => {
227
+ const tempDir = mkdtempSync(path.join(tmpdir(), "kide-upgrade-"));
228
+ const repoDir = path.join(tempDir, "repo");
229
+ run("git", ["clone", "--quiet", "--filter=blob:none", "--no-checkout", repo, repoDir]);
230
+ run("git", ["fetch", "--quiet", "--tags", "--force"], { cwd: repoDir });
231
+ return { tempDir, repoDir };
232
+ };
233
+
234
+ const resolveCommit = (repoDir: string, ref: string) => {
235
+ const result = tryRun("git", ["rev-parse", "--verify", `${ref}^{commit}`], { cwd: repoDir });
236
+ if (!result.ok || !result.stdout) {
237
+ throw new Error(`Could not resolve "${ref}" in the upstream repository.`);
238
+ }
239
+ return result.stdout;
240
+ };
241
+
242
+ const listChangedFiles = (repoDir: string, fromCommit: string, toCommit: string) => {
243
+ const output = run("git", ["diff", "--name-only", fromCommit, toCommit], { cwd: repoDir });
244
+ return output
245
+ .split("\n")
246
+ .map((line) => line.trim())
247
+ .filter(Boolean);
248
+ };
249
+
250
+ const diffForPaths = (repoDir: string, fromCommit: string, toCommit: string, files: string[]) => {
251
+ if (files.length === 0) return "";
252
+ return runRaw("git", ["diff", "--binary", fromCommit, toCommit, "--", ...files], { cwd: repoDir });
253
+ };
254
+
255
+ const changedFilesJson = (repoDir: string, fromCommit: string, toCommit: string) => {
256
+ const output = run("git", ["diff", "--name-status", fromCommit, toCommit], { cwd: repoDir });
257
+ return output
258
+ .split("\n")
259
+ .map((line) => line.trim())
260
+ .filter(Boolean)
261
+ .map((line) => {
262
+ const [status, ...files] = line.split(/\s+/);
263
+ return { status, files };
264
+ });
265
+ };
266
+
267
+ const isManagedRuntimePath = (file: string, corePath: string) => {
268
+ const managedPrefixes = [
269
+ `${corePath}/admin`,
270
+ `${corePath}/client`,
271
+ `${corePath}/core`,
272
+ `${corePath}/internals`,
273
+ `${corePath}/middleware`,
274
+ `${corePath}/platform`,
275
+ `${corePath}/routes`,
276
+ ];
277
+
278
+ return managedPrefixes.some((prefix) => file === prefix || file.startsWith(`${prefix}/`));
279
+ };
280
+
281
+ const isCarefulPath = (file: string, corePath: string) => {
282
+ const carefulFiles = new Set([
283
+ "package.json",
284
+ "pnpm-lock.yaml",
285
+ "astro.config.mjs",
286
+ "tsconfig.json",
287
+ "drizzle.config.ts",
288
+ "src/env.d.ts",
289
+ "src/styles/admin.css",
290
+ `${corePath}/runtime.ts`,
291
+ ]);
292
+ const carefulPrefixes = [
293
+ `${corePath}/adapters`,
294
+ `${corePath}/collections`,
295
+ `${corePath}/fields`,
296
+ `${corePath}/migrations`,
297
+ ];
298
+ return (
299
+ carefulFiles.has(file) ||
300
+ file === `${corePath}/cms.config.ts` ||
301
+ carefulPrefixes.some((prefix) => file === prefix || file.startsWith(`${prefix}/`))
302
+ );
303
+ };
304
+
305
+ const relativeToCwd = (cwd: string, file: string) => path.relative(cwd, file) || ".";
306
+
307
+ const sanitizeId = (value: string) => value.replace(/[^a-zA-Z0-9._-]+/g, "-").replace(/^-+|-+$/g, "");
308
+
309
+ const sha256 = (file: string) => createHash("sha256").update(readFileSync(file)).digest("hex");
310
+
311
+ const checkpoint = (file: string): FileCheckpoint => {
312
+ if (!existsSync(file)) return { exists: false };
313
+ const stat = statSync(file);
314
+ if (!stat.isFile()) return { exists: true };
315
+ return { exists: true, sha256: sha256(file), size: stat.size };
316
+ };
317
+
318
+ const choosePacketDir = (cwd: string, fromRef: string, targetRef: string) => {
319
+ const root = path.join(cwd, ".kide", "upgrade");
320
+ mkdirSync(root, { recursive: true });
321
+ const base = `${sanitizeId(fromRef)}-to-${sanitizeId(targetRef)}`;
322
+ let candidate = path.join(root, base);
323
+ let suffix = 2;
324
+ while (existsSync(candidate)) {
325
+ candidate = path.join(root, `${base}-${suffix}`);
326
+ suffix += 1;
327
+ }
328
+ mkdirSync(candidate, { recursive: true });
329
+ return candidate;
330
+ };
331
+
332
+ const backupFiles = (cwd: string, packetDir: string, files: string[]) => {
333
+ const backupDir = path.join(packetDir, "backup");
334
+ mkdirSync(backupDir, { recursive: true });
335
+ const backedUp: string[] = [];
336
+ const missing: string[] = [];
337
+ const entries: BackupEntry[] = [];
338
+
339
+ for (const file of files) {
340
+ const source = path.join(cwd, file);
341
+ if (!existsSync(source)) {
342
+ missing.push(file);
343
+ entries.push({ file, existed: false });
344
+ continue;
345
+ }
346
+ const stat = statSync(source);
347
+ if (!stat.isFile()) continue;
348
+ const destination = path.join(backupDir, file);
349
+ mkdirSync(path.dirname(destination), { recursive: true });
350
+ copyFileSync(source, destination);
351
+ backedUp.push(file);
352
+ const state = checkpoint(source);
353
+ entries.push({ file, existed: true, backupSha256: state.sha256, backupSize: state.size });
354
+ }
355
+
356
+ writeFileSync(
357
+ path.join(backupDir, "manifest.json"),
358
+ `${JSON.stringify({ createdAt: new Date().toISOString(), backedUp, missing, entries }, null, 2)}\n`,
359
+ );
360
+ return { backedUp, missing };
361
+ };
362
+
363
+ const recordBackupAttemptState = (cwd: string, packetDir: string) => {
364
+ const manifestPath = path.join(packetDir, "backup", "manifest.json");
365
+ if (!existsSync(manifestPath)) return;
366
+
367
+ const manifest = JSON.parse(readFileSync(manifestPath, "utf-8")) as BackupManifest;
368
+ const entries = manifest.entries ?? [
369
+ ...(manifest.backedUp ?? []).map((file) => ({ file, existed: true })),
370
+ ...(manifest.missing ?? []).map((file) => ({ file, existed: false })),
371
+ ];
372
+ const at = new Date().toISOString();
373
+ manifest.entries = entries.map((entry) => ({
374
+ ...entry,
375
+ afterAttempt: { ...checkpoint(path.join(cwd, entry.file)), at },
376
+ }));
377
+ writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);
378
+ };
379
+
380
+ const isGitRepo = (cwd: string) => tryRun("git", ["rev-parse", "--is-inside-work-tree"], { cwd }).ok;
381
+
382
+ const gitStatus = (cwd: string) => {
383
+ const result = tryRun("git", ["status", "--porcelain"], { cwd });
384
+ return result.ok ? result.stdout : "";
385
+ };
386
+
387
+ const unmergedFiles = (cwd: string) => {
388
+ const result = tryRun("git", ["diff", "--name-only", "--diff-filter=U"], { cwd });
389
+ return result.ok
390
+ ? result.stdout
391
+ .split("\n")
392
+ .map((line) => line.trim())
393
+ .filter(Boolean)
394
+ : [];
395
+ };
396
+
397
+ const detectAgents = () =>
398
+ AGENTS.filter((agent) => {
399
+ const result = spawnSync("which", [agent.command], { stdio: "ignore" });
400
+ return result.status === 0;
401
+ });
402
+
403
+ const selectAgent = (requested: Args["agent"], detected: AgentInfo[]) => {
404
+ if (requested === "none") return null;
405
+ if (requested === "auto") return detected[0] ?? null;
406
+ return detected.find((agent) => agent.id === requested) ?? null;
407
+ };
408
+
409
+ const versionFromRef = (ref: string) => {
410
+ const match = ref.match(/^v(\d+\.\d+\.\d+(?:[-+].*)?)$/);
411
+ return match ? match[1] : null;
412
+ };
413
+
414
+ const writeReleaseNotes = (repoDir: string, fromCommit: string, toCommit: string, packetDir: string) => {
415
+ const changelogDiff = tryRun("git", ["diff", fromCommit, toCommit, "--", "CHANGELOG.md"], { cwd: repoDir });
416
+ const body = [
417
+ "# Release Notes",
418
+ "",
419
+ `From: ${fromCommit}`,
420
+ `To: ${toCommit}`,
421
+ "",
422
+ "## CHANGELOG diff",
423
+ "",
424
+ changelogDiff.ok && changelogDiff.stdout
425
+ ? ["```diff", changelogDiff.stdout, "```"].join("\n")
426
+ : "No CHANGELOG.md changes were found for this range.",
427
+ "",
428
+ ].join("\n");
429
+ writeFileSync(path.join(packetDir, "release-notes.md"), body);
430
+ };
431
+
432
+ const renderPlan = (input: {
433
+ repo: string;
434
+ fromRef: string;
435
+ targetRef: string;
436
+ corePath: string;
437
+ mode: "embedded" | "package";
438
+ applyMode: string;
439
+ managed: string[];
440
+ careful: string[];
441
+ other: string[];
442
+ }) =>
443
+ [
444
+ "# Kide Upgrade Plan",
445
+ "",
446
+ `Repository: ${input.repo}`,
447
+ `From: ${input.fromRef}`,
448
+ `To: ${input.targetRef}`,
449
+ `Managed CMS path: ${input.corePath}`,
450
+ `Distribution mode: ${input.mode}`,
451
+ `Apply mode: ${input.applyMode}`,
452
+ "",
453
+ "## What was prepared",
454
+ "",
455
+ input.mode === "package"
456
+ ? "- `managed-runtime.patch` is informational only in package mode — those files ship inside @kidecms/core and are upgraded by the dependency bump."
457
+ : "- `managed-runtime.patch` contains paths Kide can usually merge automatically.",
458
+ "- `careful-review.patch` contains project-sensitive files such as package/config/collections/adapters.",
459
+ "- `full-release.patch` contains the complete upstream diff for reference.",
460
+ "- `backup/` contains restorable snapshots of local files touched by the upgrade.",
461
+ "",
462
+ "## Next steps",
463
+ "",
464
+ ...(input.mode === "package"
465
+ ? [
466
+ "1. Run `pnpm install` to pull the bumped @kidecms/core release.",
467
+ "2. Review `careful-review.patch` — template changes to project-owned files (cms.config API changes, scripts, configs) that the dependency bump cannot apply for you.",
468
+ ]
469
+ : [
470
+ "1. If the managed patch applied cleanly, review the diff and continue with the careful-review patch only where it is relevant.",
471
+ "2. If there are conflicts, resolve them by preserving local project intent and upstream runtime fixes.",
472
+ ]),
473
+ "3. Review `package.json` and `pnpm-lock.yaml` changes from `careful-review.patch`; run `pnpm install` if dependencies changed.",
474
+ "4. Run `pnpm cms:generate`, `pnpm check`, and `pnpm test`.",
475
+ "5. Commit the upgrade together with the updated `.kide-version`.",
476
+ "6. If you want to abandon this upgrade attempt, run `pnpm cms:restore`.",
477
+ "",
478
+ "## Managed files",
479
+ "",
480
+ input.managed.length ? input.managed.map((file) => `- ${file}`).join("\n") : "None.",
481
+ "",
482
+ "## Careful-review files",
483
+ "",
484
+ input.careful.length ? input.careful.map((file) => `- ${file}`).join("\n") : "None.",
485
+ "",
486
+ "## Other upstream files",
487
+ "",
488
+ input.other.length ? input.other.map((file) => `- ${file}`).join("\n") : "None.",
489
+ "",
490
+ ].join("\n");
491
+
492
+ const renderAgentInstructions = (input: {
493
+ fromRef: string;
494
+ targetRef: string;
495
+ packetRelative: string;
496
+ applied: boolean;
497
+ applyError: string | null;
498
+ }) =>
499
+ [
500
+ "# Agent Instructions: Kide Core Upgrade",
501
+ "",
502
+ `Upgrade this Kide client project from ${input.fromRef} to ${input.targetRef}.`,
503
+ "",
504
+ "The upgrade packet is in:",
505
+ "",
506
+ ` ${input.packetRelative}`,
507
+ "",
508
+ "Work from the packet, not from memory:",
509
+ "",
510
+ "1. Read `plan.md`, `conflicts.json`, and `release-notes.md`.",
511
+ "2. Inspect `managed-runtime.patch` for runtime/admin/core changes.",
512
+ "3. Inspect `careful-review.patch` for project-sensitive changes. Apply only the intent that belongs in this client.",
513
+ "4. Preserve project-specific collections, adapters, migrations, public pages, and custom components unless an upstream change is clearly required.",
514
+ "5. If conflict markers exist, resolve them directly in the project files.",
515
+ "6. Keep `.kide-version` accurate. If the upgrade is complete, it should point at the target release.",
516
+ "7. Run `pnpm cms:generate`, `pnpm check`, and `pnpm test`; explain any known baseline failures.",
517
+ "",
518
+ input.applied
519
+ ? "The managed patch was already applied. Review and finish the careful parts."
520
+ : input.applyError
521
+ ? `The managed patch did not apply cleanly. Start by resolving the conflict/error recorded in \`conflicts.json\`: ${input.applyError}`
522
+ : "The managed patch was not applied. Apply or merge it deliberately before finishing.",
523
+ "",
524
+ ].join("\n");
525
+
526
+ const renderReport = (input: {
527
+ packetRelative: string;
528
+ applied: boolean;
529
+ applyError: string | null;
530
+ selectedAgent: AgentInfo | null;
531
+ detectedAgents: AgentInfo[];
532
+ requestedAgent: Args["agent"];
533
+ }) => {
534
+ const lines = [
535
+ "# Kide Upgrade Report",
536
+ "",
537
+ `Packet: ${input.packetRelative}`,
538
+ `Managed patch applied: ${input.applied ? "yes" : "no"}`,
539
+ ];
540
+
541
+ if (input.applyError) lines.push(`Apply error: ${input.applyError}`);
542
+ lines.push("");
543
+
544
+ if (input.selectedAgent) {
545
+ lines.push(
546
+ `Detected ${input.selectedAgent.label}. Give it \`${input.packetRelative}/agent-instructions.md\` to finish or review the upgrade.`,
547
+ );
548
+ } else if (input.requestedAgent !== "none" && input.detectedAgents.length === 0) {
549
+ lines.push(
550
+ "No local AI agent was detected.",
551
+ "",
552
+ "Nothing is blocked: the deterministic upgrade packet is ready. Resolve it manually, or paste `agent-instructions.md` into Claude, Codex, Cursor, or another coding agent later.",
553
+ );
554
+ } else if (input.requestedAgent !== "none") {
555
+ lines.push(
556
+ `Requested agent "${input.requestedAgent}" was not found locally.`,
557
+ "",
558
+ "The upgrade packet is still complete and can be handed to any agent or resolved manually.",
559
+ );
560
+ } else {
561
+ lines.push("Agent handoff disabled with `--agent none`.");
562
+ }
563
+
564
+ lines.push("");
565
+ return lines.join("\n");
566
+ };
567
+
568
+ async function main() {
569
+ const cwd = process.cwd();
570
+ const args = parseArgs(process.argv.slice(2));
571
+
572
+ if (args.help) {
573
+ console.log(usage);
574
+ return;
575
+ }
576
+
577
+ const stamp = readStamp(cwd);
578
+ const repo = args.repo ?? stamp?.template ?? DEFAULT_REPO;
579
+ const corePath = args.corePath ?? stamp?.corePath ?? DEFAULT_CORE_PATH;
580
+ // Package mode: managed runtime comes from the @kidecms/core dependency, so
581
+ // upgrades bump that version; only project-owned template files need review.
582
+ const mode: "embedded" | "package" =
583
+ stamp?.mode ?? (existsSync(path.join(cwd, corePath, "core")) ? "embedded" : "package");
584
+ const fromRef = args.fromRef ?? stamp?.ref ?? stamp?.commit ?? null;
585
+
586
+ if (!fromRef) {
587
+ throw new Error("No source ref found. Add .kide-version or pass --from <ref>.");
588
+ }
589
+
590
+ const targetRef = args.targetRef ?? resolveLatestTag(repo);
591
+ if (fromRef === targetRef) {
592
+ console.log(`[cms:upgrade] Already at ${targetRef}. Nothing to upgrade.`);
593
+ return;
594
+ }
595
+
596
+ const gitAvailable = tryRun("git", ["--version"]).ok;
597
+ if (!gitAvailable) throw new Error("git is required for Kide upgrades.");
598
+
599
+ const projectIsGitRepo = isGitRepo(cwd);
600
+ const dirtyBefore = projectIsGitRepo && gitStatus(cwd).length > 0;
601
+ const shouldApply = args.apply ?? (projectIsGitRepo && !dirtyBefore);
602
+
603
+ if (shouldApply && dirtyBefore && !args.allowDirty) {
604
+ throw new Error(
605
+ "The worktree has uncommitted changes. Commit/stash them first, or rerun with --packet-only or --allow-dirty --apply.",
606
+ );
607
+ }
608
+
609
+ const { tempDir, repoDir } = cloneUpstream(repo);
610
+
611
+ try {
612
+ const fromCommit = resolveCommit(repoDir, fromRef);
613
+ const toCommit = resolveCommit(repoDir, targetRef);
614
+ const allChanged = listChangedFiles(repoDir, fromCommit, toCommit);
615
+ const managed = allChanged.filter((file) => isManagedRuntimePath(file, corePath));
616
+ const careful = allChanged.filter((file) => !managed.includes(file) && isCarefulPath(file, corePath));
617
+ const other = allChanged.filter((file) => !managed.includes(file) && !careful.includes(file));
618
+
619
+ const packetDir = choosePacketDir(cwd, fromRef, targetRef);
620
+ const packetRelative = relativeToCwd(cwd, packetDir);
621
+ const managedPatch = diffForPaths(repoDir, fromCommit, toCommit, managed);
622
+ const carefulPatch = diffForPaths(repoDir, fromCommit, toCommit, careful);
623
+ const fullPatch = diffForPaths(repoDir, fromCommit, toCommit, allChanged);
624
+
625
+ writeFileSync(path.join(packetDir, "managed-runtime.patch"), managedPatch);
626
+ writeFileSync(path.join(packetDir, "careful-review.patch"), carefulPatch);
627
+ writeFileSync(path.join(packetDir, "full-release.patch"), fullPatch);
628
+ writeFileSync(
629
+ path.join(packetDir, "changed-files.json"),
630
+ `${JSON.stringify(changedFilesJson(repoDir, fromCommit, toCommit), null, 2)}\n`,
631
+ );
632
+ writeReleaseNotes(repoDir, fromCommit, toCommit, packetDir);
633
+ backupFiles(cwd, packetDir, mode === "package" ? ["package.json", ".kide-version"] : [...managed, ".kide-version"]);
634
+
635
+ let applied = false;
636
+ let applyError: string | null = null;
637
+
638
+ const stampUpgrade = () => {
639
+ const now = new Date().toISOString();
640
+ const upgradeRecord: UpgradeRecord = {
641
+ from: fromRef,
642
+ to: targetRef,
643
+ fromCommit,
644
+ toCommit,
645
+ at: now,
646
+ packet: packetRelative,
647
+ applied: true,
648
+ };
649
+ const nextStamp: VersionStamp = {
650
+ ...(stamp ?? {}),
651
+ template: stripGitSuffix(repo),
652
+ ref: targetRef,
653
+ commit: toCommit,
654
+ kideVersion: versionFromRef(targetRef) ?? stamp?.kideVersion ?? null,
655
+ mode,
656
+ corePath,
657
+ upgradedAt: now,
658
+ upgrades: [...(stamp?.upgrades ?? []), upgradeRecord],
659
+ };
660
+ writeFileSync(path.join(cwd, ".kide-version"), `${JSON.stringify(nextStamp, null, 2)}\n`);
661
+ };
662
+
663
+ if (shouldApply && mode === "package") {
664
+ // Managed runtime changes arrive via the published package — bump the
665
+ // dependency instead of patching files that only exist in node_modules.
666
+ const targetVersion = versionFromRef(targetRef);
667
+ const pkgJsonPath = path.join(cwd, "package.json");
668
+ const pkgJson = JSON.parse(readFileSync(pkgJsonPath, "utf-8"));
669
+ if (!targetVersion) {
670
+ applyError = `Target ref "${targetRef}" is not a release tag — cannot derive an @kidecms/core version.`;
671
+ } else if (!pkgJson.dependencies?.["@kidecms/core"]) {
672
+ applyError = "package.json has no @kidecms/core dependency — is this really a package-mode project?";
673
+ } else {
674
+ pkgJson.dependencies["@kidecms/core"] = `^${targetVersion}`;
675
+ writeFileSync(pkgJsonPath, `${JSON.stringify(pkgJson, null, 2)}\n`);
676
+ applied = true;
677
+ stampUpgrade();
678
+ }
679
+ recordBackupAttemptState(cwd, packetDir);
680
+ } else if (shouldApply && managedPatch.trim()) {
681
+ const patchPath = path.join(packetDir, "managed-runtime.patch");
682
+ const result = tryRun("git", ["apply", "--3way", relativeToCwd(cwd, patchPath)], { cwd });
683
+ if (result.ok) {
684
+ applied = true;
685
+ stampUpgrade();
686
+ } else {
687
+ applyError = result.stderr.trim() || result.stdout.trim() || "git apply --3way failed";
688
+ }
689
+ recordBackupAttemptState(cwd, packetDir);
690
+ }
691
+
692
+ const detectedAgents = detectAgents();
693
+ const selectedAgent = selectAgent(args.agent, detectedAgents);
694
+ const conflicts = {
695
+ repo: stripGitSuffix(repo),
696
+ fromRef,
697
+ targetRef,
698
+ fromCommit,
699
+ toCommit,
700
+ mode,
701
+ corePath,
702
+ dirtyBefore,
703
+ applied,
704
+ applyError,
705
+ unmergedFiles: projectIsGitRepo ? unmergedFiles(cwd) : [],
706
+ changedFiles: { managed, careful, other },
707
+ detectedAgents: detectedAgents.map(({ id, label, command }) => ({ id, label, command })),
708
+ selectedAgent: selectedAgent
709
+ ? { id: selectedAgent.id, label: selectedAgent.label, command: selectedAgent.command }
710
+ : null,
711
+ };
712
+
713
+ writeFileSync(path.join(packetDir, "conflicts.json"), `${JSON.stringify(conflicts, null, 2)}\n`);
714
+ writeFileSync(
715
+ path.join(packetDir, "plan.md"),
716
+ renderPlan({
717
+ repo: stripGitSuffix(repo),
718
+ fromRef,
719
+ targetRef,
720
+ corePath,
721
+ mode,
722
+ applyMode: shouldApply
723
+ ? mode === "package"
724
+ ? "dependency bump attempted"
725
+ : "managed patch attempted"
726
+ : "packet only",
727
+ managed,
728
+ careful,
729
+ other,
730
+ }),
731
+ );
732
+ writeFileSync(
733
+ path.join(packetDir, "agent-instructions.md"),
734
+ renderAgentInstructions({ fromRef, targetRef, packetRelative, applied, applyError }),
735
+ );
736
+ writeFileSync(
737
+ path.join(packetDir, "report.md"),
738
+ renderReport({ packetRelative, applied, applyError, selectedAgent, detectedAgents, requestedAgent: args.agent }),
739
+ );
740
+ writeFileSync(
741
+ path.join(cwd, ".kide", "upgrade", "latest.json"),
742
+ `${JSON.stringify({ packet: packetRelative, fromRef, targetRef, applied, createdAt: new Date().toISOString() }, null, 2)}\n`,
743
+ );
744
+
745
+ console.log(`[cms:upgrade] Packet ready: ${packetRelative}`);
746
+ if (applied && mode === "package") {
747
+ console.log(
748
+ `[cms:upgrade] Bumped @kidecms/core to ^${versionFromRef(targetRef)} and updated .kide-version — run \`pnpm install\`, then review careful-review.patch.`,
749
+ );
750
+ } else if (applied) {
751
+ console.log(`[cms:upgrade] Applied managed runtime changes and updated .kide-version to ${targetRef}.`);
752
+ } else if (applyError) {
753
+ console.log("[cms:upgrade] Managed patch needs help. See conflicts.json and agent-instructions.md.");
754
+ } else {
755
+ console.log("[cms:upgrade] Packet-only mode. No project files were changed.");
756
+ }
757
+
758
+ if (selectedAgent) {
759
+ console.log(
760
+ `[cms:upgrade] Detected ${selectedAgent.label}. Handoff file: ${packetRelative}/agent-instructions.md`,
761
+ );
762
+ } else if (args.agent !== "none" && detectedAgents.length === 0) {
763
+ console.log("[cms:upgrade] No local AI agent was detected.");
764
+ console.log(
765
+ `[cms:upgrade] Resolve manually or paste ${packetRelative}/agent-instructions.md into Claude, Codex, Cursor, or another agent.`,
766
+ );
767
+ }
768
+ } finally {
769
+ rmSync(tempDir, { recursive: true, force: true });
770
+ }
771
+ }
772
+
773
+ main().catch((error) => {
774
+ console.error(`[cms:upgrade] ${(error as Error).message}`);
775
+ process.exit(1);
776
+ });