anhedral 0.3.0 → 0.4.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.
package/dist/scaffold.js CHANGED
@@ -1,4 +1,4 @@
1
- import { lstatSync, mkdirSync, readFileSync, readdirSync, rmdirSync, rmSync } from 'node:fs';
1
+ import { chmodSync, copyFileSync, lstatSync, mkdirSync, readFileSync, readdirSync, rmdirSync, rmSync } from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { env } from 'node:process';
4
4
  import { anhedralPrint } from './print.js';
@@ -8,6 +8,7 @@ import { resolveToolchainChannel } from './toolchain.js';
8
8
  import { scaffoldApi } from './templates/api.js';
9
9
  import { r2BucketName, scaffoldAssetsPrivateProxy } from './templates/assets-private-proxy.js';
10
10
  import { scaffoldDesktop } from './templates/desktop.js';
11
+ import { desktopUpdatesBucketName, scaffoldElectronUpdater, } from './templates/electron-updater.js';
11
12
  import { scaffoldExtension } from './templates/extension.js';
12
13
  import { scaffoldMobile } from './templates/mobile.js';
13
14
  import { scaffoldSharedPackages } from './templates/shared.js';
@@ -136,6 +137,7 @@ function selectionsFromModules(modules) {
136
137
  billing: selected.has('billing'),
137
138
  storage: selected.has('storage'),
138
139
  nativeSubscriptions: selected.has('native-subscriptions'),
140
+ electronUpdater: selected.has('electron-updater'),
139
141
  },
140
142
  };
141
143
  }
@@ -168,6 +170,9 @@ function optionsFromManifest(manifest, addOptions, modules) {
168
170
  function toolchainChannelFromManifest(manifest) {
169
171
  return resolveToolchainChannel(manifest.toolchain);
170
172
  }
173
+ export function isSupportedProjectUpgrade(fromVersion, toVersion) {
174
+ return fromVersion === '0.3.0' && toVersion === '0.4.0';
175
+ }
171
176
  function ensureScaffoldRoot(root) {
172
177
  const rootStat = lstatIfPresent(root);
173
178
  if (!rootStat)
@@ -189,8 +194,15 @@ function selectedAppFilters(apps) {
189
194
  }
190
195
  function rootScripts(options) {
191
196
  const filters = selectedAppFilters(options.apps);
197
+ const primaryClient = filters.find((entry) => entry !== './apps/api');
198
+ const primaryFilters = primaryClient
199
+ ? [primaryClient, ...(options.apps.api ? ['./apps/api'] : [])]
200
+ : filters.slice(0, 1);
192
201
  const scripts = {
193
- dev: filters.length ? `turbo dev --parallel ${filters.map((entry) => `--filter=${entry}`).join(' ')}` : 'echo "No app surfaces selected."',
202
+ dev: primaryFilters.length ? `turbo dev --parallel ${primaryFilters.map((entry) => `--filter=${entry}`).join(' ')}` : 'echo "No app surfaces selected."',
203
+ ...(filters.length > primaryFilters.length
204
+ ? { 'dev:all': `turbo dev --parallel ${filters.map((entry) => `--filter=${entry}`).join(' ')}` }
205
+ : {}),
194
206
  build: 'turbo build',
195
207
  typecheck: 'turbo typecheck',
196
208
  };
@@ -232,6 +244,23 @@ function rootScripts(options) {
232
244
  scripts['verify:desktop'] = 'pnpm --filter ./apps/desktop typecheck && pnpm --filter ./apps/desktop build';
233
245
  verify.push('pnpm verify:desktop');
234
246
  }
247
+ if (options.features.electronUpdater) {
248
+ const bucketName = desktopUpdatesBucketName(options.projectName);
249
+ const wrangler = `pnpm dlx wrangler@${TOOLCHAIN_DEPENDENCIES.wrangler}`;
250
+ scripts['desktop:updates:cloudflare:login'] = `${wrangler} login`;
251
+ scripts['desktop:updates:bucket:create'] = `${wrangler} r2 bucket create ${bucketName}`;
252
+ scripts['desktop:updates:worker:check'] = 'pnpm --filter ./apps/desktop-updater-worker check';
253
+ scripts['desktop:updates:worker:dev'] = 'pnpm --filter ./apps/desktop-updater-worker dev';
254
+ scripts['desktop:updates:worker:deploy'] = 'pnpm --filter ./apps/desktop-updater-worker deploy';
255
+ scripts['desktop:updates:first-provision'] = 'pnpm desktop:updates:bucket:create && pnpm desktop:updates:worker:deploy';
256
+ scripts['desktop:updates:worker:types'] = 'pnpm --filter ./apps/desktop-updater-worker types';
257
+ scripts['desktop:updates:build:mac'] = 'pnpm --filter ./apps/desktop updates:build:mac';
258
+ scripts['desktop:updates:build:win'] = 'pnpm --filter ./apps/desktop updates:build:win';
259
+ scripts['desktop:updates:build:linux'] = 'pnpm --filter ./apps/desktop updates:build:linux';
260
+ scripts['desktop:updates:publish'] = 'node apps/desktop/scripts/publish-updates.mjs';
261
+ scripts['verify:desktop-updates'] = 'pnpm desktop:updates:worker:check && node --check apps/desktop/scripts/publish-updates.mjs';
262
+ verify.push('pnpm verify:desktop-updates');
263
+ }
235
264
  if (options.apps.extension) {
236
265
  scripts['dev:extension'] = 'pnpm --filter ./apps/extension dev';
237
266
  scripts['extension:zip'] = 'pnpm --filter ./apps/extension zip';
@@ -663,12 +692,20 @@ function writeRootFiles(root, options, mode, currentRoot, manifest) {
663
692
  '.env.*',
664
693
  '!.env.example',
665
694
  '*.tsbuildinfo',
666
- ]);
695
+ options.features.electronUpdater ? 'electron-builder.env' : null,
696
+ ].filter((value) => value !== null));
667
697
  writeRootEnv(root, options);
668
698
  writeDatabaseVerificationScript(root, options);
669
699
  const vercelIgnore = path.join(root, '.vercelignore');
670
700
  const currentIgnore = pathEntryExists(vercelIgnore) ? readFileSync(vercelIgnore, 'utf8') : '';
671
- const ignoreLines = [...new Set([...currentIgnore.split('\n').filter(Boolean), 'apps/extension/.output', 'apps/mobile/dist', 'apps/desktop/release', 'apps/assets-private-proxy'])];
701
+ const ignoreLines = [...new Set([
702
+ ...currentIgnore.split('\n').filter(Boolean),
703
+ 'apps/extension/.output',
704
+ 'apps/mobile/dist',
705
+ 'apps/desktop/release',
706
+ 'apps/assets-private-proxy',
707
+ 'apps/desktop-updater-worker',
708
+ ])];
672
709
  writeFile(vercelIgnore, ignoreLines.join('\n') + '\n');
673
710
  writeFile(path.join(root, '.github/workflows/anhedral-ci.yml'), generatedCi(options));
674
711
  }
@@ -678,14 +715,17 @@ function enabledModuleNames(options) {
678
715
  function writeProjectDocs(root, options, includeUserDocs) {
679
716
  const modules = enabledModuleNames(options);
680
717
  const storageBucketName = r2BucketName(options.projectName);
681
- const commands = [
718
+ const environmentSetupCommands = [
682
719
  'pnpm install',
683
720
  options.apps.api ? 'cp apps/api/.env.example apps/api/.env' : null,
684
721
  options.features.database ? 'cp packages/db/.env.example packages/db/.env' : null,
685
722
  options.apps.web ? 'cp apps/web/.env.example apps/web/.env.local' : null,
686
723
  options.apps.mobile ? 'cp apps/mobile/.env.example apps/mobile/.env' : null,
687
724
  options.apps.desktop ? 'cp apps/desktop/.env.example apps/desktop/.env' : null,
725
+ options.features.electronUpdater ? 'cp apps/desktop/electron-builder.env.example apps/desktop/electron-builder.env' : null,
688
726
  options.apps.extension ? 'cp apps/extension/.env.example apps/extension/.env' : null,
727
+ ].filter((value) => value !== null).join('\n');
728
+ const firstVerificationCommands = [
689
729
  options.features.database ? 'pnpm db:generate' : null,
690
730
  options.features.database ? 'git add packages/db/migrations' : null,
691
731
  'pnpm verify',
@@ -696,8 +736,9 @@ function writeProjectDocs(root, options, includeUserDocs) {
696
736
  options.apps.mobile ? '| Mobile | EAS Build + App Store Connect + Google Play Console | EAS creates signed binaries; Apple TestFlight/App Review and Google testing tracks/store review control release. |' : null,
697
737
  options.features.database ? '| Database | Neon | Provision the project, set `DATABASE_URL`, review/apply Drizzle migrations, and use separate branches or projects for preview and production. |' : null,
698
738
  options.features.storage ? '| Object storage | Private Cloudflare R2 + `assets-private-proxy` Worker | Authenticated uploads use presigned R2 URLs; the Worker streams known-key GET/HEAD downloads through `assets.<domain>` while direct bucket access stays disabled. |' : null,
739
+ options.features.electronUpdater ? '| Desktop updates | Private Cloudflare R2 + `desktop-updater` Worker | Signed native artifacts are uploaded to a private bucket; a custom-domain Worker supplies metadata, ranges, and downloads to `electron-updater`. |' : null,
699
740
  options.apps.extension ? '| Chrome extension | Chrome Web Store | Build the production ZIP, test it as an unpublished/trusted-tester item, complete privacy disclosures, and submit it for review. |' : null,
700
- options.apps.desktop ? '| Desktop | electron-builder artifacts | Build and sign on each target OS, then publish through the release channel chosen for the product. |' : null,
741
+ options.apps.desktop ? `| Desktop | electron-builder artifacts${options.features.electronUpdater ? ' + automatic update channel' : ''} | Build and sign on each target OS, then publish through the release channel chosen for the product. |` : null,
701
742
  ].filter((value) => value !== null).join('\n');
702
743
  const deploymentCommands = [
703
744
  options.apps.web || options.apps.api ? 'pnpm deploy:vercel:link' : null,
@@ -710,17 +751,22 @@ function writeProjectDocs(root, options, includeUserDocs) {
710
751
  options.features.storage ? 'pnpm r2:bucket:create' : null,
711
752
  options.features.storage ? 'pnpm assets:proxy:check' : null,
712
753
  options.features.storage ? 'pnpm assets:proxy:deploy' : null,
754
+ options.features.electronUpdater ? 'pnpm desktop:updates:cloudflare:login' : null,
755
+ options.features.electronUpdater ? 'pnpm desktop:updates:first-provision' : null,
756
+ options.features.electronUpdater ? 'pnpm desktop:updates:build:mac' : null,
757
+ options.features.electronUpdater ? 'pnpm desktop:updates:publish -- --platform mac --arch arm64' : null,
713
758
  options.apps.extension ? 'pnpm extension:zip' : null,
714
759
  ].filter((value) => value !== null).join('\n');
715
760
  const sourceRows = [
716
761
  options.apps.web ? '| Web frontend | `apps/web/app/`, `apps/web/components/`, `apps/web/lib/` | Next.js App Router pages, layouts, components, and web utilities. |' : null,
717
762
  options.apps.mobile ? '| Mobile frontend | `apps/mobile/app/`, `apps/mobile/components/` | Expo Router screens, layouts, and native UI. |' : null,
718
- options.apps.api ? '| Backend API | `apps/api/src/routes/`, `apps/api/src/services/` | Fastify routes and server-only business/provider code. |' : null,
763
+ options.apps.api ? '| Backend API | `apps/api/src/routes/app.ts`, `apps/api/src/<feature>.ts` | User-owned Fastify routes and server-only product modules; Anhedral keeps provider routes in managed wiring. |' : null,
719
764
  options.apps.desktop ? '| Desktop app | `apps/desktop/src/renderer/`, `apps/desktop/src/main/` | React UI and privileged Electron main-process code. |' : null,
720
- options.apps.extension ? '| Browser extension | `apps/extension/entrypoints/`, `apps/extension/components/` | WXT entrypoints and extension UI. |' : null,
721
- options.apps.api ? '| Shared API contracts | `packages/contracts/src/` | Zod request and response schemas imported by clients and the API. |' : null,
722
- options.apps.api ? '| Typed API client | `packages/api-client/src/` | Shared fetch client used by every selected frontend. |' : null,
723
- options.features.database ? '| Database | `packages/db/src/schema.ts`, `packages/db/migrations/` | Drizzle tables, queries, and reviewed SQL migrations for managed Neon Postgres. |' : null,
765
+ options.features.electronUpdater ? '| Desktop update edge | `apps/desktop-updater-worker/`, `apps/desktop/scripts/publish-updates.mjs` | Private R2 delivery Worker, custom domain, and ordered release publisher. |' : null,
766
+ options.apps.extension ? '| Browser extension | `apps/extension/src/entrypoints/`, `apps/extension/src/components/` | WXT entrypoints and extension UI. |' : null,
767
+ options.apps.api ? '| Shared API contracts | `packages/contracts/src/app.ts` | User-owned Zod request and response schemas exported beside managed provider contracts. |' : null,
768
+ options.apps.api ? '| Typed API client | `packages/api-client/src/app.ts` | User-owned client-safe methods exported beside the managed fetch client. |' : null,
769
+ options.features.database ? '| Database | `packages/db/src/app-schema.ts`, `packages/db/migrations/` | User-owned Drizzle tables plus reviewed SQL migrations; provider tables remain generated. |' : null,
724
770
  ].filter((value) => value !== null).join('\n');
725
771
  const moduleCommands = [
726
772
  options.apps.web ? '- Web: `pnpm dev:web`' : null,
@@ -740,15 +786,17 @@ function writeProjectDocs(root, options, includeUserDocs) {
740
786
  options.features.billing ? '| RevenueCat | Subscription authority | API and native client | https://www.revenuecat.com/docs |' : null,
741
787
  options.features.billing ? '| Ably | Realtime invalidation | `packages/realtime` | https://ably.com/docs |' : null,
742
788
  options.apps.desktop ? '| Electron | Desktop runtime | `apps/desktop` | https://www.electronjs.org/docs/latest/ |' : null,
789
+ options.features.electronUpdater ? '| electron-updater | Packaged-app update checks and installation | `apps/desktop/src/main/main.ts` | https://www.electron.build/auto-update.html |' : null,
790
+ options.features.electronUpdater ? '| Cloudflare Workers + R2 | Private update storage and custom-domain delivery | `apps/desktop-updater-worker` | https://developers.cloudflare.com/r2/api/workers/workers-api-usage/ |' : null,
743
791
  options.apps.extension ? '| WXT | Browser extension tooling | `apps/extension` | https://wxt.dev/guide/installation.html |' : null,
744
792
  options.apps.web || options.apps.desktop || options.apps.extension ? '| shadcn/ui | Source-owned DOM UI | each DOM app\'s `components/ui` | https://ui.shadcn.com/docs |' : null,
745
793
  '| Turborepo | Workspace tasks | root `turbo.json` | https://turborepo.com/docs |',
746
794
  ].filter((value) => value !== null).join('\n');
747
795
  const developmentSteps = [
748
- options.apps.api ? 'Define shared Zod schemas in `packages/contracts/src/` so the network boundary has one definition.' : null,
749
- options.features.database ? 'Define persistent state in `packages/db/src/schema.ts`. Run `pnpm db:generate`, review the SQL, and commit it. This project uses managed Neon—do not add a local Postgres container.' : null,
750
- options.apps.api ? 'Put business logic and provider calls in `apps/api/src/services/`. Keep `apps/api/src/routes/` focused on auth, validation, calling the service, and returning the contract.' : null,
751
- options.apps.api ? 'Expose client-safe methods from `packages/api-client/src/`; never import API implementation files into a frontend.' : null,
796
+ options.apps.api ? 'Define shared Zod schemas in user-owned `packages/contracts/src/app.ts` so the network boundary has one definition.' : null,
797
+ options.features.database ? 'Define persistent product state in user-owned `packages/db/src/app-schema.ts`. Run `pnpm db:generate`, review the SQL, and commit it. This project uses managed Neon—do not add a local Postgres container.' : null,
798
+ options.apps.api ? 'Add server-only behavior in a focused `apps/api/src/<feature>.ts` module and register its validated HTTP boundary in user-owned `apps/api/src/routes/app.ts`.' : null,
799
+ options.apps.api ? 'Expose client-safe methods from user-owned `packages/api-client/src/app.ts`; never import API implementation files into a frontend.' : null,
752
800
  options.apps.web ? 'Add web routes in `apps/web/app/<route>/page.tsx` and reusable UI in `apps/web/components/`. Use a client component only for browser state, events, or hooks.' : null,
753
801
  options.apps.mobile ? 'Add mobile routes in `apps/mobile/app/` and reusable native UI in `apps/mobile/components/`. Keep platform-only APIs in platform-specific modules.' : null,
754
802
  'Test the smallest affected package first, then run `pnpm verify`.',
@@ -759,10 +807,10 @@ function writeProjectDocs(root, options, includeUserDocs) {
759
807
  Create \`apps/web/app/<route>/page.tsx\`. Follow Next.js App Router conventions directly. Put reusable components under \`apps/web/components/<feature>/\` and web-only helpers under \`apps/web/lib/\`.` : null,
760
808
  options.apps.api ? `### Add an API endpoint
761
809
 
762
- Define its Zod contract in \`packages/contracts/src/\`, add a service function in \`apps/api/src/services/\`, and register a Fastify route in \`apps/api/src/routes/\`. Authenticate on the server and derive the user ID from the verified session.` : null,
810
+ Define its Zod contract in \`packages/contracts/src/app.ts\`, implement server-only behavior in \`apps/api/src/<feature>.ts\`, and register the Fastify route in \`apps/api/src/routes/app.ts\`. Authenticate on the server and derive the user ID from the verified session.` : null,
763
811
  options.features.database ? `### Change the database
764
812
 
765
- Edit \`packages/db/src/schema.ts\`, then run:
813
+ Edit \`packages/db/src/app-schema.ts\`, then run:
766
814
 
767
815
  \`\`\`sh
768
816
  pnpm db:generate
@@ -778,10 +826,62 @@ Frontend applications use their generated Clerk provider and hooks. The API veri
778
826
 
779
827
  Use \`@shared/api-client\`. The API authorizes the user and creates a short-lived signed R2 upload; the client uploads directly and confirms through the API. Never put R2 credentials in a client or make the bucket public.` : null,
780
828
  ].filter((value) => value !== null).join('\n\n');
829
+ const verticalSliceExample = options.apps.api && options.features.database ? `## Copy-paste example: a projects feature
830
+
831
+ These files are user-owned extension seams. Anhedral preserves them during \`add\`, \`ui add\`, and \`upgrade\`.
832
+
833
+ \`packages/contracts/src/app.ts\`:
834
+
835
+ \`\`\`ts
836
+ import { z } from 'zod';
837
+
838
+ export const ProjectSchema = z.object({ id: z.string(), name: z.string() });
839
+ export const ProjectListSchema = z.array(ProjectSchema);
840
+ \`\`\`
841
+
842
+ \`packages/db/src/app-schema.ts\`:
843
+
844
+ \`\`\`ts
845
+ import { pgTable, text } from 'drizzle-orm/pg-core';
846
+
847
+ export const projects = pgTable('projects', {
848
+ id: text('id').primaryKey(),
849
+ name: text('name').notNull(),
850
+ });
851
+ \`\`\`
852
+
853
+ \`apps/api/src/routes/app.ts\`:
854
+
855
+ \`\`\`ts
856
+ import type { FastifyPluginAsync } from 'fastify';
857
+ import { ProjectListSchema } from '@shared/contracts';
858
+ import { db } from '@shared/db';
859
+ import { projects } from '@shared/db/schema';
860
+
861
+ export const appRoutes: FastifyPluginAsync = async (app) => {
862
+ app.get('/projects', async () => ProjectListSchema.parse(await db.select().from(projects)));
863
+ };
864
+ \`\`\`
865
+
866
+ ${options.apps.web || options.apps.mobile || options.apps.desktop || options.apps.extension ? `\`packages/api-client/src/app.ts\`:
867
+
868
+ \`\`\`ts
869
+ import { ProjectListSchema } from '@shared/contracts';
870
+ import { ApiClient } from './generated';
871
+
872
+ export function listProjects(client: ApiClient) {
873
+ return client.request('/projects', { method: 'GET' }, ProjectListSchema);
874
+ }
875
+ \`\`\`
876
+
877
+ Import \`listProjects\` and the generated client factory in the frontend surface you are building.` : ''}
878
+
879
+ Then run \`pnpm db:generate\`, review and commit the migration, run \`pnpm verify\`, apply it to the intended Neon branch with \`pnpm db:migrate\`, and start the relevant app surfaces.` : '';
781
880
  const dependencyLines = [
782
881
  options.apps.api ? 'frontend apps -> @shared/api-client -> HTTP -> apps/api' : null,
783
882
  options.apps.api ? 'frontend apps -> @shared/contracts <- apps/api' : null,
784
883
  options.apps.api && options.features.database ? 'apps/api -> @shared/db -> managed Neon Postgres' : null,
884
+ options.features.electronUpdater ? 'apps/desktop -> updates.<domain> Worker -> private R2 bucket' : null,
785
885
  ].filter((value) => value !== null).join('\n');
786
886
  const uiTaskSection = Object.values(options.apps).some(Boolean) && (options.apps.web || options.apps.mobile || options.apps.desktop || options.apps.extension)
787
887
  ? `### Add UI primitives
@@ -799,12 +899,19 @@ This is a complete, readable TypeScript product stack generated by Anhedral ${GE
799
899
 
800
900
  ## Start here
801
901
 
902
+ Anhedral installs workspace dependencies during generation unless you used \`--skip-install\`. On a fresh clone, install them and copy the selected environment examples:
903
+
802
904
  \`\`\`sh
803
- pnpm install
804
- pnpm dev
905
+ ${environmentSetupCommands}
805
906
  \`\`\`
806
907
 
807
- \`pnpm dev\` starts every selected application. To run one surface:
908
+ Stop here and replace every required placeholder in those uncommitted files. In particular, \`DATABASE_URL\` must be the pooled connection string for the intended managed Neon branch when the database module is selected. Then generate the initial migration and verify the workspace:
909
+
910
+ \`\`\`sh
911
+ ${firstVerificationCommands}
912
+ \`\`\`
913
+
914
+ After verification succeeds, run \`pnpm dev\`. In a full stack this starts the primary web + API development loop, so opening the project does not also launch Expo, Electron, and WXT. Use \`pnpm dev:all\` when you intentionally want every selected surface, or run one surface:
808
915
 
809
916
  ${moduleCommands}
810
917
 
@@ -828,9 +935,7 @@ DOM clients use source-owned shadcn/ui. Expo uses React Native Reusables with ${
828
935
 
829
936
  ## Environment and first verification
830
937
 
831
- \`\`\`sh
832
- ${commands}
833
- \`\`\`
938
+ The setup blocks above are the first-run checklist. Provider secrets stay in their package-local environment files; none belong in client code. This project uses managed Neon and intentionally does not generate or start local Postgres.
834
939
 
835
940
  ## Deployment
836
941
 
@@ -855,6 +960,8 @@ Anhedral generated this stack; it does not replace the frameworks inside it. Use
855
960
 
856
961
  ${developmentSteps}
857
962
 
963
+ ${verticalSliceExample}
964
+
858
965
  ## Common tasks
859
966
 
860
967
  ${commonTaskSections}
@@ -975,7 +1082,17 @@ Accounts required: an Expo/EAS account, an Apple Developer Program membership wi
975
1082
  3. In the Developer Dashboard, create an item and upload the ZIP from \`apps/extension/.output\`. Complete the listing (description, icons, screenshots, category, regions) and keep the manifest version higher for every update.
976
1083
  4. State one narrow purpose, justify every permission/host permission, disclose all handled data, certify limited use, and provide a public privacy-policy URL consistent with actual behavior. Clerk login counts as handling authentication data. Supply reviewer test instructions and credentials when features are gated.
977
1084
  5. Publish first to trusted testers/unlisted visibility, verify the store-installed CRX ID matches Clerk and backend allowlists, then submit the production listing for review. Store review and rollout are separate from GitHub/Vercel deployment.` : null,
978
- options.apps.desktop ? `## Electron desktop
1085
+ options.features.electronUpdater ? `## Electron desktop and automatic updates
1086
+
1087
+ The generated update path is \`electron-updater -> updates.<domain> Worker -> private ${desktopUpdatesBucketName(options.projectName)} R2 bucket\`. The application never receives Cloudflare credentials, the Worker exposes reads only, and direct bucket access stays disabled.
1088
+
1089
+ 1. In \`apps/desktop-updater-worker/wrangler.jsonc\`, replace both \`updates.example.com\` values with a hostname in an active Cloudflare zone. Run \`pnpm desktop:updates:cloudflare:login\`, then run \`pnpm desktop:updates:first-provision\` exactly once to create the private bucket and deploy the bound Worker, managed DNS record, TLS certificate, logs, and custom domain. For repeat deployments use \`pnpm desktop:updates:worker:deploy\`; bucket creation is intentionally not repeated. Keep the bucket's \`r2.dev\` URL and R2 bucket custom-domain access disabled.
1090
+ 2. Copy \`apps/desktop/electron-builder.env.example\` to \`apps/desktop/electron-builder.env\` and set \`DESKTOP_UPDATE_BASE_URL\` to that exact HTTPS origin with no trailing slash. electron-builder writes the platform/architecture URL into the packaged app's update configuration; no update secret is embedded.
1091
+ 3. Increase \`apps/desktop/package.json\`'s version for every release. Build on each target OS using \`pnpm desktop:updates:build:mac\`, \`pnpm desktop:updates:build:win\`, or \`pnpm desktop:updates:build:linux\`. Configure macOS signing/notarization and Windows code-signing credentials in CI, never in the repository.
1092
+ 4. From the repository root, upload one architecture at a time, for example \`pnpm desktop:updates:publish -- --platform mac --arch arm64\`. The publisher accepts only known platform/architecture values, uploads immutable installers and blockmaps first, then uploads mutable \`latest*.yml\` metadata last. Run it only after signing succeeds.
1093
+ 5. Install the previous signed version, publish a newer version, and verify update discovery, range downloads, signature validation, restart/install, rollback behavior, and logs on macOS, Windows, and the supported Linux package path. Test clean install, deep links, Clerk return flow, and OS security warnings too.
1094
+
1095
+ The Worker accepts GET/HEAD only, validates the configured hostname and \`releases/\` prefix, supports conditionals and single-range downloads, serves metadata with \`no-store\`, and serves versioned artifacts as immutable. See \`cloudflare/desktop-updates.md\` for the generated resource contract.` : options.apps.desktop ? `## Electron desktop
979
1096
 
980
1097
  Builds are platform-specific: produce macOS, Windows, and Linux artifacts on their matching CI runners with the package's \`build:mac\`, \`build:win\`, and \`build:linux\` scripts. Configure signing/notarization credentials in CI, never in the repository. Test clean install, upgrade, deep links, Clerk return flow, auto-update strategy, and OS security warnings before publishing artifacts to the chosen release channel.` : null,
981
1098
  ].filter((section) => section !== null);
@@ -1004,6 +1121,7 @@ Generator: ${GENERATOR_VERSION}
1004
1121
  Resolved modules: ${modules.join(', ')}
1005
1122
 
1006
1123
  - \`anhedral add <module> --dry-run\` previews incremental changes.
1124
+ - \`anhedral upgrade --dry-run\` previews a supported generator migration.
1007
1125
  - \`anhedral ui add <component> --dry-run\` previews platform-routed component additions.
1008
1126
  - \`anhedral doctor\` reports manifest and filesystem drift before incremental changes.
1009
1127
  - README and existing user workflows are never rewritten by \`anhedral add\`.
@@ -1013,21 +1131,23 @@ Resolved modules: ${modules.join(', ')}
1013
1131
  options.apps.mobile ? `- Mobile lives in \`apps/mobile\`: use Expo Router and React Native Reusables with ${options.nativeStyling}. Keep native-only APIs behind platform-safe modules.` : null,
1014
1132
  options.apps.api ? '- HTTP and provider integration lives in `apps/api`: keep Fastify routes thin, validate boundaries, and put secrets only in server environment files.' : null,
1015
1133
  options.apps.desktop ? '- Desktop lives in `apps/desktop`: keep Electron main/preload privileges minimal and application UI in the sandboxed React renderer.' : null,
1134
+ options.features.electronUpdater ? '- Desktop update delivery lives in `apps/desktop-updater-worker`: keep the R2 bucket private, the Worker read-only, and the Worker Custom Domain aligned with `DESKTOP_UPDATE_BASE_URL`.' : null,
1016
1135
  options.apps.extension ? '- Browser extension code lives in `apps/extension`: use WXT entrypoints and request only permissions required by the feature.' : null,
1017
1136
  options.features.storage ? '- Private-bucket asset delivery lives in `apps/assets-private-proxy`: preserve the `ASSETS` R2 binding, streaming responses, method/host restrictions, and Cloudflare-managed custom domain.' : null,
1018
1137
  ].filter((value) => value !== null).join('\n');
1019
1138
  const featureGuidance = [
1020
1139
  options.apps.api ? '- Reuse `@shared/contracts` at every network boundary and call the API through `@shared/api-client`; clients must not import server implementation modules.' : null,
1021
- options.features.database ? '- Neon/Drizzle state is authoritative. Change `packages/db/src/schema.ts`, generate SQL with `pnpm db:generate`, review it, and Git-track the migration.' : null,
1140
+ options.features.database ? '- Neon/Drizzle state is authoritative. Change user-owned `packages/db/src/app-schema.ts`, generate SQL with `pnpm db:generate`, review it, and Git-track the migration.' : null,
1022
1141
  options.features.auth ? '- Clerk owns identity and sessions. Never trust a client-supplied user ID; derive identity from verified server authentication.' : null,
1023
1142
  options.features.billing ? '- RevenueCat events reconcile into Neon before Ably publishes an invalidation. Clients refetch entitlements instead of treating realtime payloads as authority.' : null,
1024
1143
  options.features.storage ? '- R2 credentials and signed-upload policy stay in the API. The `assets-private-proxy` Worker uses its binding instead of S3 credentials and publicly serves GET/HEAD only by known unguessable key.' : null,
1144
+ options.features.electronUpdater ? '- Electron releases use `electron-updater` through the generated private R2 + Worker channel. Build signed native artifacts first and publish mutable channel metadata last.' : null,
1025
1145
  ].filter((value) => value !== null).join('\n');
1026
1146
  const skillFeatureSteps = [
1027
- options.apps.api ? 'Define shared network schemas in `packages/contracts/src/`.' : null,
1028
- options.features.database ? 'Define persistent state in `packages/db/src/schema.ts`; generate, review, and commit Drizzle SQL. Use managed Neon, never a generated local Postgres service.' : null,
1029
- options.apps.api ? 'Put backend behavior in `apps/api/src/services/` and keep `apps/api/src/routes/` thin.' : null,
1030
- options.apps.api ? 'Add client-safe calls to `packages/api-client/src/`; frontends must not import server implementations.' : null,
1147
+ options.apps.api ? 'Define shared network schemas in user-owned `packages/contracts/src/app.ts`.' : null,
1148
+ options.features.database ? 'Define persistent state in user-owned `packages/db/src/app-schema.ts`; generate, review, and commit Drizzle SQL. Use managed Neon, never a generated local Postgres service.' : null,
1149
+ options.apps.api ? 'Put backend behavior in focused `apps/api/src/<feature>.ts` modules and register product routes in user-owned `apps/api/src/routes/app.ts`.' : null,
1150
+ options.apps.api ? 'Add client-safe calls to user-owned `packages/api-client/src/app.ts`; frontends must not import server implementations.' : null,
1031
1151
  options.apps.web ? 'Write web product code with normal Next.js App Router conventions in `apps/web`.' : null,
1032
1152
  options.apps.mobile ? 'Write native product code with normal Expo Router conventions in `apps/mobile`.' : null,
1033
1153
  'Verify the affected package, then run the root verification before handoff.',
@@ -1050,8 +1170,8 @@ Before implementing a feature, read \`README.md\` for the source map, \`docs/DEV
1050
1170
  ## Start safely
1051
1171
 
1052
1172
  1. Read \`anhedral.json\` for the selected modules, native styling provider, installed UI components, and file ownership.
1053
- 2. Run \`pnpm dlx anhedral@${GENERATOR_VERSION} doctor\` before generator operations.
1054
- 3. Preview structural changes with \`anhedral add <module> --dry-run\` or \`anhedral ui add <component> --dry-run\`.
1173
+ 2. Run \`pnpm dlx anhedral@${GENERATOR_VERSION} doctor\` before generator operations. If it reports a supported older generator, preview and apply \`anhedral upgrade\` before continuing.
1174
+ 3. Preview structural changes with \`anhedral upgrade --dry-run\`, \`anhedral add <module> --dry-run\`, or \`anhedral ui add <component> --dry-run\` as applicable.
1055
1175
  4. Never hand-edit \`anhedral.json\`, ownership hashes, or bundled-template provenance.
1056
1176
 
1057
1177
  Resolved modules: ${modules.map((moduleName) => `\`${moduleName}\``).join(', ')}.
@@ -1076,7 +1196,7 @@ ${skillFeatureSteps}
1076
1196
 
1077
1197
  ## Ownership rules
1078
1198
 
1079
- - \`README.md\` and \`PRODUCTION.md\` are user-owned. Root JSON/YAML configuration is mergeable. Other recorded files are generator-managed unless \`anhedral.json\` says otherwise.
1199
+ - \`README.md\`, \`PRODUCTION.md\`, product UI, and the backend \`app.ts\`/\`app-schema.ts\` extension seams are user-owned. Root JSON/YAML configuration is mergeable. Other recorded files are generator-managed unless \`anhedral.json\` says otherwise.
1080
1200
  - Prefer new application files and narrow composition points over editing managed substrate files. If a managed file must change, understand that future \`anhedral add\` operations will stop until the project is reconciled.
1081
1201
  - Never overwrite user changes, bypass a generator conflict, or replace a failed ownership check with fabricated hashes.
1082
1202
 
@@ -1088,10 +1208,23 @@ ${skillFeatureSteps}
1088
1208
 
1089
1209
  ## Deployment conventions
1090
1210
 
1211
+ ### Agent-assisted provisioning
1212
+
1213
+ When the user asks you to provision this project:
1214
+
1215
+ 1. Ask for the exact environment and custom domain first. Record canonical resource names and selected provider teams without recording secrets.
1216
+ 2. Inspect whether Computer Use/browser control and subagents are available. With Computer Use, navigate provider dashboards and complete approved non-secret setup. Stop for the user at sign-in, password, passkey, MFA, CAPTCHA, paid purchase, destructive replacement, secret generation/reveal/rotation, and final release/store submission.
1217
+ 3. If subagents are available, keep one lead agent responsible for mutations. Delegate bounded independent tasks only: one subagent reads this project's docs and environment examples, one performs read-only DNS/hostname checks, and one performs final read-only verification. Never send credentials, cookies, or secret values to a subagent, and never let two agents mutate the same provider or DNS zone.
1218
+ 4. At every secret-generation screen, stop before the final button. Tell the user the exact button, variable name, and uncommitted package-local environment file. The user clicks and pastes the value directly into that file or the provider's protected field, never into chat. Validate presence without printing populated environment files.
1219
+ 5. Read \`PRODUCTION.md\` completely and follow its selection-specific order. Do not claim completion until cloud resources, environment names, DNS, TLS, application health, and the verification commands below pass.
1220
+
1221
+ Domain topology: Cloudflare is authoritative DNS; Vercel hosts web/API; the Vercel A/CNAME/TXT records are created in Cloudflare DNS and normally remain DNS-only. Generated Worker hostnames such as \`assets.<domain>\` or \`updates.<domain>\` are Cloudflare Worker Custom Domains created by Wrangler, not CNAMEs to Vercel or public R2 endpoints.
1222
+
1091
1223
  - Read \`PRODUCTION.md\` before provisioning or changing production resources. It is tailored to this project's selected surfaces and providers.
1092
1224
  ${options.apps.web || options.apps.api ? '- Prefer GitHub-triggered Vercel Preview and Production deployments. Keep the generated Services routing intact; use manual `deploy:vercel:*` scripts only when explicitly required.' : ''}
1093
1225
  ${options.features.database ? '- Treat reviewed, committed Drizzle SQL as the release artifact. Apply migrations as a controlled step against the intended Neon environment; never generate migrations during an application build.' : ''}
1094
1226
  ${options.features.storage ? '- Keep the R2 bucket private and deploy `assets-private-proxy` at the Cloudflare Worker custom domain. Expose only `storage/confirmed/` publicly; use the owner-authorized read-URL endpoint for private objects and keep `CLOUDFLARE_API_TOKEN` operations-only.' : ''}
1227
+ ${options.features.electronUpdater ? '- Provision the private desktop-update R2 bucket and deploy `desktop-updater` at `updates.<domain>`. Keep the update origin identical in Wrangler and `electron-builder.env`, then publish signed per-platform artifacts before channel metadata.' : ''}
1095
1228
  ${options.apps.mobile ? '- Promote mobile artifacts through EAS internal distribution, TestFlight/Google Play testing, then store review. Build-time public variables are not secrets.' : ''}
1096
1229
  ${options.apps.extension ? '- Publish the exact verified WXT ZIP through trusted/unlisted Chrome Web Store testing before production review; preserve a stable CRX ID and least-privilege permissions.' : ''}
1097
1230
 
@@ -1128,6 +1261,14 @@ function collectFiles(root, relativeRoot = '') {
1128
1261
  return files.sort();
1129
1262
  }
1130
1263
  function ownerForPath(relativePath) {
1264
+ if (relativePath.startsWith('apps/desktop-updater-worker/'))
1265
+ return 'electron-updater';
1266
+ if (relativePath === 'apps/desktop/scripts/publish-updates.mjs')
1267
+ return 'electron-updater';
1268
+ if (relativePath === 'apps/desktop/electron-builder.env.example')
1269
+ return 'electron-updater';
1270
+ if (relativePath === 'cloudflare/desktop-updates.md')
1271
+ return 'electron-updater';
1131
1272
  if (relativePath.startsWith('apps/assets-private-proxy/'))
1132
1273
  return 'storage';
1133
1274
  if (relativePath.startsWith('cloudflare/'))
@@ -1144,12 +1285,56 @@ function defaultOwnership(relativePath) {
1144
1285
  return 'user';
1145
1286
  if (relativePath === 'apps/assets-private-proxy/wrangler.jsonc')
1146
1287
  return 'user';
1288
+ if (relativePath === 'apps/desktop-updater-worker/wrangler.jsonc')
1289
+ return 'user';
1147
1290
  if (relativePath === 'cloudflare/r2-cors.template.json')
1148
1291
  return 'user';
1292
+ if (relativePath === 'apps/web/app/page.tsx'
1293
+ || /^apps\/web\/components\//.test(relativePath)
1294
+ || relativePath === 'apps/mobile/app/index.tsx'
1295
+ || /^apps\/mobile\/components\//.test(relativePath)
1296
+ || relativePath === 'apps/desktop/src/main/app-window.ts'
1297
+ || /^apps\/desktop\/src\/renderer\/components\//.test(relativePath)
1298
+ || /^apps\/extension\/src\/components\//.test(relativePath)
1299
+ || relativePath === 'apps/api/src/routes/app.ts'
1300
+ || /^apps\/api\/src\/services\//.test(relativePath)
1301
+ || relativePath === 'packages/contracts/src/app.ts'
1302
+ || relativePath === 'packages/api-client/src/app.ts'
1303
+ || relativePath === 'packages/db/src/app-schema.ts')
1304
+ return 'user';
1149
1305
  if (ROOT_MERGEABLE_FILES.has(relativePath))
1150
1306
  return 'mergeable';
1151
1307
  return 'managed';
1152
1308
  }
1309
+ function applyCurrentOwnership(manifest) {
1310
+ const files = Object.freeze(Object.fromEntries(Object.entries(manifest.files).map(([relativePath, record]) => [
1311
+ relativePath,
1312
+ record.ownership === 'managed' && defaultOwnership(relativePath) === 'user'
1313
+ ? Object.freeze({ ...record, ownership: 'user' })
1314
+ : record,
1315
+ ])));
1316
+ return Object.freeze({ ...manifest, files });
1317
+ }
1318
+ function preserveUserOwnedFiles(root, stageRoot, manifest) {
1319
+ for (const [relativePath, record] of Object.entries(manifest.files)) {
1320
+ if (record.ownership !== 'user')
1321
+ continue;
1322
+ const current = path.join(root, relativePath);
1323
+ const staged = path.join(stageRoot, relativePath);
1324
+ const currentStat = lstatIfPresent(current);
1325
+ const stagedStat = lstatIfPresent(staged);
1326
+ if (!currentStat?.isFile())
1327
+ continue;
1328
+ if (stagedStat?.isSymbolicLink() || (stagedStat && !stagedStat.isFile())) {
1329
+ throw new Error(`Refusing to replace user-owned path with a non-file: ${relativePath}`);
1330
+ }
1331
+ if (stagedStat?.isFile() && readFileSync(current).equals(readFileSync(staged)))
1332
+ continue;
1333
+ mkdirSync(path.dirname(staged), { recursive: true });
1334
+ copyFileSync(current, staged);
1335
+ chmodSync(staged, Number(currentStat.mode) & 0o777);
1336
+ }
1337
+ }
1153
1338
  function createProjectManifest(root, options, operation, templates, previous, components = previous?.ui.components ?? []) {
1154
1339
  const contributions = new Map();
1155
1340
  for (const relativePath of collectFiles(root)) {
@@ -1191,14 +1376,20 @@ function createProjectManifest(root, options, operation, templates, previous, co
1191
1376
  function writeManifest(root, manifest) {
1192
1377
  writeFile(path.join(root, 'anhedral.json'), serializeManifest(manifest));
1193
1378
  }
1194
- function readProjectManifest(root) {
1379
+ function readProjectManifest(root, options = {}) {
1195
1380
  const filePath = path.join(root, 'anhedral.json');
1196
1381
  if (!pathEntryExists(filePath))
1197
1382
  throw new Error('anhedral.json was not found. Run anhedral init first.');
1198
1383
  const manifest = readManifest(readFileSync(filePath, 'utf8'));
1199
1384
  if (manifest.generatorVersion !== GENERATOR_VERSION) {
1385
+ if (options.allowSupportedUpgrade && isSupportedProjectUpgrade(manifest.generatorVersion, GENERATOR_VERSION)) {
1386
+ return manifest;
1387
+ }
1388
+ const nextStep = isSupportedProjectUpgrade(manifest.generatorVersion, GENERATOR_VERSION)
1389
+ ? 'Run anhedral upgrade before adding modules.'
1390
+ : 'Regenerate the project with the current CLI before adding modules.';
1200
1391
  throw new Error(`This project was generated by Anhedral ${manifest.generatorVersion}; current CLI ${GENERATOR_VERSION} only supports exact-current projects. `
1201
- + 'Regenerate the project with the current CLI before adding modules.');
1392
+ + nextStep);
1202
1393
  }
1203
1394
  assertTemplateProvenance(manifest.modules, manifest.templates);
1204
1395
  return manifest;
@@ -1245,6 +1436,8 @@ async function writeSelectedModules(root, options) {
1245
1436
  await scaffoldExtension(root, shared);
1246
1437
  if (options.features.storage)
1247
1438
  scaffoldAssetsPrivateProxy(root, shared);
1439
+ if (options.features.electronUpdater)
1440
+ scaffoldElectronUpdater(root, shared);
1248
1441
  return templates;
1249
1442
  }
1250
1443
  function printPlan(operation, paths, json) {
@@ -1272,7 +1465,7 @@ function assertSafeChangedPaths(root, stageRoot, manifest, paths, deleting = new
1272
1465
  continue;
1273
1466
  assertManagedFileMode(relativePath, record, targetStat);
1274
1467
  const actualHash = hashContent(readFileSync(target));
1275
- if (record.ownership === 'user') {
1468
+ if (record.ownership === 'user' && actualHash !== record.hash) {
1276
1469
  throw new Error(`Refusing to modify user-owned path: ${relativePath}`);
1277
1470
  }
1278
1471
  if (record.ownership === 'managed' && actualHash !== record.hash) {
@@ -1374,7 +1567,7 @@ export async function scaffoldUiComponents(uiOptions) {
1374
1567
  commitPaths,
1375
1568
  dryRun: uiOptions.dryRun,
1376
1569
  prepare: () => {
1377
- manifest = readProjectManifest(root);
1570
+ manifest = applyCurrentOwnership(readProjectManifest(root));
1378
1571
  assertManagedFileModes(root, manifest);
1379
1572
  const installedTargets = UI_TARGETS.filter((target) => manifest.modules.includes(target));
1380
1573
  const targets = uiOptions.targets.length > 0 ? uiOptions.targets : installedTargets;
@@ -1418,6 +1611,7 @@ export async function scaffoldUiComponents(uiOptions) {
1418
1611
  installUiComponents(stageRoot, additions);
1419
1612
  cleanNestedArtifacts(stageRoot);
1420
1613
  rmSync(path.join(stageRoot, 'pnpm-lock.yaml'), { force: true });
1614
+ preserveUserOwnedFiles(root, stageRoot, manifest);
1421
1615
  writeManifest(stageRoot, createProjectManifest(stageRoot, options, 'add', manifest.templates, manifest, components));
1422
1616
  const diff = stagedFileDiff(root, stageRoot, manifest);
1423
1617
  assertSafeChangedPaths(root, stageRoot, manifest, [...diff.changed, ...diff.deleted], new Set(diff.deleted));
@@ -1459,6 +1653,77 @@ export async function scaffoldUiComponents(uiOptions) {
1459
1653
  env.ANHEDRAL_TOOLCHAIN = previousChannel;
1460
1654
  }
1461
1655
  }
1656
+ export async function scaffoldUpgradeProject(upgradeOptions) {
1657
+ const root = path.resolve(process.cwd());
1658
+ let manifest;
1659
+ let options;
1660
+ let noOp = false;
1661
+ const seedPaths = [];
1662
+ const commitPaths = [];
1663
+ const deletePaths = [];
1664
+ const previousChannel = env.ANHEDRAL_TOOLCHAIN;
1665
+ try {
1666
+ const planned = await runStagedTransaction(root, {
1667
+ commitPaths,
1668
+ deletePaths,
1669
+ seedPaths,
1670
+ dryRun: upgradeOptions.dryRun,
1671
+ prepare: () => {
1672
+ manifest = applyCurrentOwnership(readProjectManifest(root, { allowSupportedUpgrade: true }));
1673
+ if (manifest.generatorVersion === GENERATOR_VERSION) {
1674
+ noOp = true;
1675
+ return false;
1676
+ }
1677
+ assertManagedFileModes(root, manifest);
1678
+ options = optionsFromManifest(manifest, {
1679
+ modules: [],
1680
+ skipInstall: upgradeOptions.skipInstall,
1681
+ dryRun: upgradeOptions.dryRun,
1682
+ json: upgradeOptions.json,
1683
+ }, manifest.modules);
1684
+ assertInstallNodeCompatibility(options);
1685
+ env.ANHEDRAL_TOOLCHAIN = options.toolchainChannel;
1686
+ seedPaths.push(...new Set([
1687
+ ...Object.keys(manifest.files).filter((relativePath) => pathEntryExists(path.join(root, relativePath))),
1688
+ 'anhedral.json',
1689
+ ]));
1690
+ anhedralPrint.banner(`Upgrading ${manifest.generatorVersion} to ${GENERATOR_VERSION}`);
1691
+ },
1692
+ build: async (stageRoot) => {
1693
+ if (!manifest || !options)
1694
+ throw new Error('Internal upgrade plan was not prepared.');
1695
+ writeRootFiles(stageRoot, options, 'add', root, manifest);
1696
+ const templates = await writeSelectedModules(stageRoot, options);
1697
+ writeProjectDocs(stageRoot, options, false);
1698
+ cleanNestedArtifacts(stageRoot);
1699
+ preserveUserOwnedFiles(root, stageRoot, manifest);
1700
+ writeManifest(stageRoot, createProjectManifest(stageRoot, options, 'add', templates, manifest, manifest.ui.components));
1701
+ const diff = stagedFileDiff(root, stageRoot, manifest);
1702
+ assertSafeChangedPaths(root, stageRoot, manifest, [...diff.changed, ...diff.deleted], new Set(diff.deleted));
1703
+ commitPaths.push(...diff.changed);
1704
+ deletePaths.push(...diff.deleted);
1705
+ },
1706
+ afterCommit: () => {
1707
+ if (!upgradeOptions.skipInstall)
1708
+ installWorkspaceDependencies(root);
1709
+ },
1710
+ });
1711
+ if (noOp) {
1712
+ if (upgradeOptions.json)
1713
+ console.log(JSON.stringify({ operation: 'upgrade', paths: [] }, null, 2));
1714
+ else
1715
+ anhedralPrint.info(`Project is already on Anhedral ${GENERATOR_VERSION}.`);
1716
+ return;
1717
+ }
1718
+ printPlan('upgrade', planned, upgradeOptions.json);
1719
+ }
1720
+ finally {
1721
+ if (previousChannel == null)
1722
+ delete env.ANHEDRAL_TOOLCHAIN;
1723
+ else
1724
+ env.ANHEDRAL_TOOLCHAIN = previousChannel;
1725
+ }
1726
+ }
1462
1727
  export async function scaffoldAddModules(addOptions) {
1463
1728
  const root = path.resolve(process.cwd());
1464
1729
  let manifest;
@@ -1476,7 +1741,7 @@ export async function scaffoldAddModules(addOptions) {
1476
1741
  seedPaths,
1477
1742
  dryRun: addOptions.dryRun,
1478
1743
  prepare: () => {
1479
- manifest = readProjectManifest(root);
1744
+ manifest = applyCurrentOwnership(readProjectManifest(root));
1480
1745
  assertManagedFileModes(root, manifest);
1481
1746
  const desiredRequested = [...new Set([...manifest.modules, ...addOptions.modules])];
1482
1747
  const resolution = resolveModules(desiredRequested);
@@ -1502,6 +1767,7 @@ export async function scaffoldAddModules(addOptions) {
1502
1767
  const templates = await writeSelectedModules(stageRoot, options);
1503
1768
  writeProjectDocs(stageRoot, options, false);
1504
1769
  cleanNestedArtifacts(stageRoot);
1770
+ preserveUserOwnedFiles(root, stageRoot, manifest);
1505
1771
  writeManifest(stageRoot, createProjectManifest(stageRoot, options, 'add', templates, manifest));
1506
1772
  const diff = stagedFileDiff(root, stageRoot, manifest);
1507
1773
  assertSafeChangedPaths(root, stageRoot, manifest, [...diff.changed, ...diff.deleted], new Set(diff.deleted));
@@ -1556,7 +1822,9 @@ export function doctorProject() {
1556
1822
  issues.push({
1557
1823
  path: 'anhedral.json',
1558
1824
  severity: 'error',
1559
- message: `Project generator ${manifest.generatorVersion} differs from CLI ${GENERATOR_VERSION}; regenerate with the current CLI.`,
1825
+ message: isSupportedProjectUpgrade(manifest.generatorVersion, GENERATOR_VERSION)
1826
+ ? `Project generator ${manifest.generatorVersion} differs from CLI ${GENERATOR_VERSION}; run anhedral upgrade.`
1827
+ : `Project generator ${manifest.generatorVersion} differs from CLI ${GENERATOR_VERSION}; regenerate with the current CLI.`,
1560
1828
  });
1561
1829
  }
1562
1830
  try {