@runeditrun/rer 0.2.79 → 0.2.81

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 (147) hide show
  1. package/README.md +17 -3
  2. package/cli/README.md +25 -13
  3. package/cli/authoring.mjs +14 -0
  4. package/cli/contract.mjs +25 -5
  5. package/cli/demo-host.mjs +4 -2
  6. package/cli/deploy-needs.mjs +4 -2
  7. package/cli/dev-identity.mjs +2 -2
  8. package/cli/export.mjs +1 -1
  9. package/cli/inspect.mjs +38 -2
  10. package/cli/ledger-refusal.mjs +18 -0
  11. package/cli/main.mjs +8 -2
  12. package/cli/managed-server.mjs +1 -1
  13. package/cli/parse.mjs +7 -6
  14. package/cli/portability-migrations.mjs +30 -11
  15. package/cli/portability-worker.mjs +4 -1
  16. package/cli/portability.mjs +8 -2
  17. package/cli/production-auth.mjs +2 -1
  18. package/cli/production-mail.mjs +36 -9
  19. package/cli/project.mjs +5 -14
  20. package/cli/release.mjs +6 -5
  21. package/cli/site-hosting.mjs +90 -0
  22. package/cli/site-preview.mjs +4 -1
  23. package/cli/site-render.mjs +3 -2
  24. package/cli/site.mjs +8 -4
  25. package/edition-authoring/adopt.mjs +39 -0
  26. package/edition-authoring/base-acknowledgements.mjs +24 -0
  27. package/edition-authoring/base-copies.mjs +427 -0
  28. package/edition-authoring/cli.mjs +85 -0
  29. package/edition-authoring/copy-checkout.mjs +69 -0
  30. package/edition-authoring/files.mjs +15 -2
  31. package/edition-authoring/lock.mjs +48 -0
  32. package/edition-authoring/offline-git.mjs +28 -0
  33. package/edition-authoring/parent-comparison.mjs +77 -0
  34. package/edition-authoring/projection-lock.mjs +38 -0
  35. package/edition-authoring/release.mjs +48 -0
  36. package/edition-authoring/runtime-dependencies.mjs +108 -0
  37. package/edition-authoring/sources.mjs +114 -0
  38. package/edition-authoring/updates.mjs +105 -0
  39. package/global/CHANGELOG.md +24 -0
  40. package/global/README.md +17 -3
  41. package/global/cli/install.mjs +3 -1
  42. package/global/main.mjs +9 -12
  43. package/modules/container/build.mjs +1 -1
  44. package/modules/d1-transport/index.mjs +68 -21
  45. package/modules/demo/README.md +16 -2
  46. package/modules/demo/declaration.mjs +21 -0
  47. package/modules/demo/input-path.mjs +18 -0
  48. package/modules/demo/label.d.mts +1 -1
  49. package/modules/demo/label.mjs +10 -5
  50. package/modules/demo/navigation.mjs +148 -0
  51. package/modules/demo/run-url.mjs +9 -0
  52. package/modules/demo/vite.d.mts +7 -2
  53. package/modules/demo/vite.mjs +17 -2
  54. package/modules/demo-host/README.md +5 -3
  55. package/modules/demo-host/page-style.mjs +2 -2
  56. package/modules/demo-host/pages.mjs +3 -3
  57. package/modules/demo-host/plan.mjs +6 -4
  58. package/modules/demo-host/theme.mjs +5 -2
  59. package/modules/dependencies/auth.mjs +2 -2
  60. package/modules/deploy-kit/README.md +19 -15
  61. package/modules/deploy-kit/owner-cli.mjs +1 -1
  62. package/modules/deploy-kit/owner.mjs +8 -1
  63. package/modules/deploy-kit/readiness-window.mjs +3 -3
  64. package/modules/erasure/README.md +10 -5
  65. package/modules/import-kit/src/d1/README.md +15 -9
  66. package/modules/import-kit/src/d1/apply-effects.ts +33 -0
  67. package/modules/import-kit/src/d1/apply.ts +46 -14
  68. package/modules/import-kit/src/d1/atomic-prefix.ts +64 -0
  69. package/modules/import-kit/src/d1/budget.ts +48 -26
  70. package/modules/import-kit/src/d1/compressed-plan.ts +9 -2
  71. package/modules/import-kit/src/d1/database.ts +2 -1
  72. package/modules/import-kit/src/d1/jobs.ts +2 -1
  73. package/modules/import-kit/src/d1/plans.ts +4 -2
  74. package/modules/import-kit/src/d1/verified-plan.ts +63 -0
  75. package/modules/import-kit/src/types.ts +3 -1
  76. package/modules/integrations/core/README.md +2 -2
  77. package/modules/mail/README.md +4 -3
  78. package/modules/mail/pnpm-lock.yaml +16 -0
  79. package/modules/operator-auth/README.md +92 -3
  80. package/modules/operator-auth/accounts/admin.mjs +52 -20
  81. package/modules/operator-auth/accounts/audit.mjs +24 -0
  82. package/modules/operator-auth/accounts/business-team.mjs +91 -0
  83. package/modules/operator-auth/accounts/domain-audit.mjs +24 -0
  84. package/modules/operator-auth/accounts/native.mjs +6 -2
  85. package/modules/operator-auth/accounts/provider-control.mjs +7 -4
  86. package/modules/operator-auth/accounts/provider-setup.mjs +34 -0
  87. package/modules/operator-auth/accounts/settings-page.mjs +26 -4
  88. package/modules/operator-auth/accounts/status.mjs +7 -2
  89. package/modules/operator-auth/accounts/store.mjs +32 -6
  90. package/modules/operator-auth/business-settings.mjs +40 -0
  91. package/modules/operator-auth/conformance/README.md +1 -1
  92. package/modules/operator-auth/dev/index.mjs +22 -4
  93. package/modules/operator-auth/dev/refusal.mjs +19 -0
  94. package/modules/operator-auth/docs/README.md +6 -5
  95. package/modules/operator-auth/docs/tanstack-start.md +1 -1
  96. package/modules/operator-auth/docs/vite-spa.md +5 -6
  97. package/modules/operator-auth/identity/email-link/index.mjs +1 -1
  98. package/modules/operator-auth/identity/oidc/admin-audit.mjs +31 -0
  99. package/modules/operator-auth/identity/oidc/index.mjs +12 -5
  100. package/modules/operator-auth/identity/oidc/store.mjs +2 -0
  101. package/modules/operator-auth/index.d.mts +41 -2
  102. package/modules/operator-auth/page.mjs +14 -0
  103. package/modules/operator-auth/representation.mjs +83 -0
  104. package/modules/operator-auth/routes.mjs +31 -3
  105. package/modules/operator-auth/service.mjs +8 -3
  106. package/modules/operator-auth/signin/index.mjs +1 -1
  107. package/modules/portability/README.md +173 -15
  108. package/modules/portability/bookkeeping.mjs +3 -3
  109. package/modules/portability/bridge.mjs +5 -4
  110. package/modules/portability/catalogue.mjs +12 -8
  111. package/modules/portability/cli.mjs +5 -1
  112. package/modules/portability/export.mjs +10 -14
  113. package/modules/portability/format.mjs +12 -1
  114. package/modules/portability/http-errors.mjs +51 -0
  115. package/modules/portability/http.mjs +4 -1
  116. package/modules/portability/import-lease.mjs +13 -2
  117. package/modules/portability/import.mjs +10 -0
  118. package/modules/portability/index.d.mts +13 -2
  119. package/modules/portability/index.mjs +3 -2
  120. package/modules/portability/ledgers.mjs +27 -4
  121. package/modules/portability/references.mjs +20 -0
  122. package/modules/portability/schema-identity.mjs +13 -0
  123. package/modules/portability/schema-legacy.mjs +21 -0
  124. package/modules/portability/sqlite-tokens.mjs +121 -0
  125. package/modules/release/README.md +94 -11
  126. package/modules/release/github-verify.mjs +30 -9
  127. package/modules/release/sign.mjs +4 -2
  128. package/modules/release/signature.mjs +14 -7
  129. package/modules/release/signing-cli.mjs +2 -1
  130. package/modules/release/statement.mjs +2 -2
  131. package/modules/release/vectors/generate.mjs +1 -0
  132. package/modules/release/vectors/publisher-projects.mjs +133 -0
  133. package/modules/release/vectors/release-signature-vectors.json +5195 -0
  134. package/modules/release/verify.mjs +5 -1
  135. package/modules/site/docs-search/search.css +1 -1
  136. package/onboarding/README.md +16 -4
  137. package/onboarding/adapter.mjs +5 -1
  138. package/onboarding/schema/SETUP.schema.json +68 -1
  139. package/onboarding/schema/business-field-inputs.mjs +36 -0
  140. package/onboarding/schema/json-schema.mjs +6 -2
  141. package/onboarding/schema/setup-validation.mjs +23 -3
  142. package/onboarding/server.mjs +1 -1
  143. package/onboarding/setup-manifest.mjs +2 -0
  144. package/onboarding/start-origin-diagnostic.mjs +24 -0
  145. package/onboarding/ui/style.css +9 -9
  146. package/package.json +1 -1
  147. package/scripts/publish-check/README.md +1 -1
package/README.md CHANGED
@@ -4,6 +4,17 @@
4
4
  Run Edit Run checkout: every verb runs that checkout's own pinned copy, so a
5
5
  checkout always gets the behaviour it was built and tested with.
6
6
 
7
+ For source authors, `rer adopt-edition` adds a recipe and lock to existing tracked
8
+ seed source while preserving copy/composition provenance. `rer refresh-base
9
+ --ref FULL_COMMIT` refreshes recorded Base copies with the seed's pinned package;
10
+ no vendored authoring CLI is needed. Base source comes from a temporary clone of
11
+ `https://github.com/runeditrun/base.git` unless the seed declares another source
12
+ or you pass `--base CHECKOUT`. Offline refresh requires `--offline --base CHECKOUT`.
13
+ Both verbs have effect-free `--help` and newline-delimited `--json` events.
14
+ Review source changes and run edition tests before committing. See the
15
+ [edition authoring guide](https://github.com/runeditrun/base/blob/main/export/EDITION-AUTHORING.md)
16
+ for adoption, refusal behavior, JSON fields and the original Base-checkout form.
17
+
7
18
  ## Install
8
19
 
9
20
  Start a seed from an empty folder, with or without Node:
@@ -244,8 +255,11 @@ which inside `pnpm run` is the pinned copy in `node_modules/.bin`, so
244
255
  `pnpm install --frozen-lockfile && pnpm run build` needs no global `rer`. A global
245
256
  `rer` hands every verb to the pinned package, launching included. Until
246
257
  `node_modules` holds the pinned version (a fresh clone, or a pulled pin change),
247
- every verb installs it first (the frozen `pnpm install`), then runs it; verbs
248
- started at once share that one install.
258
+ commands that run project code install it first (the frozen `pnpm install`),
259
+ then run it; commands started at once share that one install. Help, version,
260
+ read-only `doctor`, and `release sign`, `release receipt` and `release keygen`
261
+ do not install dependencies. The release producer still bootstraps before it
262
+ runs project build or verification scripts.
249
263
  Every dependency install, `rer release`'s included, receives an allowlisted
250
264
  environment: the shell, locale, terminal and temporary-folder variables, `CI`,
251
265
  `TZ`, `SSH_AUTH_SOCK`, `NODE_OPTIONS`, `NODE_EXTRA_CA_CERTS`, `XDG_*`, proxy
@@ -514,7 +528,7 @@ The current MCP `next_question` filters out owner items. When an owner summary
514
528
  is supplied, the CLI displays its browser link and refuses to answer it.
515
529
 
516
530
  The four deterministic adapter implementations and their native output formats
517
- are described in [the adapter guide](cli/business/vendors/README.md). Their
531
+ are described in [the adapter guide](https://github.com/runeditrun/base/blob/main/cli/business/vendors/README.md). Their
518
532
  presence does not enable export until the seed import authority and remaining
519
533
  transport contracts are connected.
520
534
 
package/cli/README.md CHANGED
@@ -100,8 +100,9 @@ preview before either operation. `import --journal LATER_ARCHIVE` also applies
100
100
  the erasure journal of a later archive from the same installation, so a fresh
101
101
  destination refuses rows erased since. Erasure-fence refusals (`erased_row`,
102
102
  `erasure_epoch`, `later_journal`) exit 4. Reset preserves exports. Remote transfer is
103
- available only when the adapter declares complete resource coverage; an
104
- unsupported target exits 4.
103
+ available only when the adapter declares complete resource coverage. Unsupported
104
+ hosted export exits 2 before effects; unsupported import or transfer capability
105
+ can refuse with exit 4.
105
106
 
106
107
  A first-party adapter may also declare `portability.hostedExport` as an argv
107
108
  array, for example `['node', 'scripts/export.mjs']`. With that declaration,
@@ -135,20 +136,23 @@ base rows across a fresh installation. Ordinary-table archives from before this
135
136
  support remain compatible with the same schema.
136
137
 
137
138
  Every first-party seed verifies local export/import/export equivalence for its
138
- supported domain and resource data. In default-seed, each export advances the
139
- included authority generation, so archive hashes may differ even when retained
140
- domain and identity rows are equal. The technical foundation currently has no
141
- product domain or background jobs; default-seed retains its durable jobs and
139
+ supported domain and resource data. With foundation's included auth settings,
140
+ each export advances the authority generation, so archive hashes may differ even
141
+ when retained domain and identity rows are equal. The technical foundation
142
+ currently has no product domain or background jobs; default-seed retains its durable jobs and
142
143
  schedule records while omitting transient queue delivery state, local runtime
143
144
  caches and logs, transfer bookkeeping, provider credentials,
144
- provider link keys and transient provider sessions. People, external identity
145
- bindings, the installation sector and the original owner claim are retained.
145
+ provider link keys and transient provider sessions. Default-seed excludes
146
+ authentication identities and the owner claim; setup claims a fresh owner after
147
+ restore. Foundation explicitly retains selected identity tables and the original
148
+ owner claim. Both retain the installation sector.
146
149
  Retained dependency links are marked as needing re-link, and provider sign-in
147
150
  and first-setup enablement are off after import. Restore does not re-dispatch
148
151
  jobs. Run setup after restore to create local configuration and initiate the
149
- owner-approved provider re-link. The original owner recovers access through
150
- ordinary native sign-in; setup does not grant a new owner. A new binding or
151
- product effect needs an explicit policy and integrated proof.
152
+ owner-approved provider re-link. With foundation's retained owner claim, the
153
+ original owner recovers access through ordinary native sign-in; setup does not
154
+ grant a new owner. A new binding or product effect needs an explicit policy and
155
+ integrated proof.
152
156
 
153
157
  Setup reads the declared `rer-setup.json` with the shared reader and validates
154
158
  answers against the shared manifest model. The manifest owns fields and managed
@@ -162,6 +166,12 @@ manifest default and receives `--owner-name`; it replaces the generated
162
166
 
163
167
  Run `node --test --test-concurrency=2 cli/*.test.mjs` from Base. Base's shared tests
164
168
  stay in Base; exported seeds carry runtime source and their own adopting tests.
169
+ CI uses `CLI_SHARD=1` through `5` for the five CLI push shards,
170
+ `MODULE_SHARD=1` through `6` for the module shards, and `REFERENCE_SHARD=1`,
171
+ `2` or `nightly` for reference checks. `CI_INCLUDE_JOURNEYS=true` adds the slower
172
+ CLI `reference-journey.test.mjs` and reference `journey-installer-browser`,
173
+ `journey-installer` and `journey-journey` checks to the CI plan; scheduled and tag
174
+ runs select them, and manual dispatch can opt in.
165
175
 
166
176
  ## Managed local serving
167
177
 
@@ -303,8 +313,10 @@ deploy's local build/validation, release's expensive phases and local transfer
303
313
  resource work. Serving uses the registry, with finite preparation queued.
304
314
  Labels include project, initiating verb/phase and a safe checkout digest. Use
305
315
  `node scripts/base-cli/modules/job-queue/cli.mjs status` to inspect admission.
306
- Waits go to redacted progress/stderr. Nested commands validate live lease
307
- membership and actual process ancestry before sharing the admitted slot.
316
+ The CLI wrapper defaults `RER_JOBS_MAX_WAIT_SECONDS` to 1200 seconds; admission
317
+ timeout exits 75 without starting work, while the bare queue defaults to an
318
+ indefinite wait. Waits go to redacted progress/stderr. Nested commands validate
319
+ live lease membership and actual process ancestry before sharing the admitted slot.
308
320
  Direct documented browser/runtime entrypoints and indirect package scripts join
309
321
  the same executor. Original-caller `CI=true` skips admission; `CI=false` and unset CI queue.
310
322
  Heavy verbs alone accept `--no-queue`, only with `CI=true`. Synthesized install
@@ -0,0 +1,14 @@
1
+ import {adoptEdition} from '../edition-authoring/adopt.mjs';
2
+ import {resolve} from 'node:path';
3
+ import {refreshCopies, options as copyOptions} from '../edition-authoring/base-copies.mjs';
4
+ import {refuse, invalid} from './errors.mjs';
5
+
6
+ export function authoringCommand(options) {
7
+ if (options.verb === 'refresh-base' && !options.ref) throw invalid('Provide --ref with the full immutable Base commit. Run rer refresh-base --help.');
8
+ try {
9
+ return options.verb === 'adopt-edition' ? adoptEdition(options.cwd) : refreshCopies(options.cwd, copyOptions([
10
+ options.ref, '--record', options.record ?? 'base-copies.json',
11
+ ...(options.base ? ['--base', resolve(options.cwd, options.base)] : []), ...(options.offline ? ['--offline'] : []),
12
+ ], 1));
13
+ } catch (error) { throw refuse(error.message); }
14
+ }
package/cli/contract.mjs CHANGED
@@ -6,7 +6,7 @@ export const commonFlags = ['--help', '--cwd', '--non-interactive', '--json'];
6
6
  const definitions = {
7
7
  install: [[], 'Frozen dependency installation; no setup or global tool changes.'],
8
8
  setup: [['--owner-email', '--owner-name', '--port', '--host', '--answers', '--door'], 'Build, migrate, prepare private settings and first owner; stop the temporary app. --door sets a fresh checkout up at its front-door origin http://NAME.localhost:PORT (after rer door enable).'],
9
- dev: [['--port', '--host', '--idle-timeout', '--stop', '--detach', '--foreground', '--as', '--login', '--models', '--models-service', '--door', '--direct', '--demo'], 'Development with assets, HMR and the declared scheduled triggers run locally on their schedule. --detach returns once ready; --foreground keeps this command serving. With devIdentity it opens signed in as the owner; --as PERSONA or --as EMAIL picks a persona or an invited/active person. The legacy --login flag is accepted and uses the same automatic sign-in. --door moves this checkout to its front-door origin http://NAME.localhost:PORT, keeping its data; --direct moves it back; --port and --host serve directly. --demo (or rer demo) serves a throwaway demo: fresh data in .rer/demo/START (deleted when it stops: --stop, Ctrl-C or its end, one hour by default or --idle-timeout), the saved owner signed in, the seed\'s demo data, Demo in the app name and title, real public reads/checks and simulated external writes (RER_DEMO=1; the checkout\'s own data is never touched).'],
9
+ dev: [['--port', '--host', '--idle-timeout', '--stop', '--detach', '--foreground', '--as', '--login', '--models', '--models-service', '--door', '--direct', '--demo'], 'Development with assets, HMR and the declared scheduled triggers run locally on their schedule. --detach returns once ready; --foreground keeps this command serving. With devIdentity it opens signed in as the owner; --as PERSONA or --as EMAIL picks a persona or an invited/active person. The legacy --login flag is accepted and uses the same automatic sign-in. --door moves this checkout to its front-door origin http://NAME.localhost:PORT, keeping its data; --direct moves it back; --port and --host serve directly. --demo (or rer demo) serves a throwaway demo: fresh data in .rer/demo/START (deleted when it stops: --stop, Ctrl-C or its end, one hour by default or --idle-timeout), the saved owner signed in, the seed\'s demo data, Demo in the app name and title, real public reads/checks and simulated external writes (RER_DEMO=1; the checkout\'s own data is never touched).', 'launch'],
10
10
  preview: [['--port', '--host', '--idle-timeout', '--stop', '--detach', '--foreground'], 'Production output; --detach returns once ready, --foreground keeps this command serving. Reuse intact build, refresh changed assets, preserve owner/state, idle timeout and explicit stop.'],
11
11
  build: [['--site'], 'Production build with private local settings excluded and restored. --site instead writes the static run site (homepage, /run, docs) to its declared folder and prints that folder.'],
12
12
  verify: [[], 'Run the complete internal verification target.'],
@@ -14,17 +14,37 @@ const definitions = {
14
14
  deploy: [['--owner-name', '--environment', '--dry-run', '--site', '--demo', '--host', '--env-file', '--image', '--bind-address', '--http-port', '--https-port', '--remove', '--yes', '--set-secret', '--unset-secret', '--rotate-secret', '--reopen-installation-key'], 'Owner-account deployment and health; dry run validates/builds locally and reads target secret bindings with Cloudflare credentials, without provider writes. Missing required secrets fail as in deploy; missing credentials or unreadable target secrets also fail. Builds and deploy hooks run with the checkout\'s local settings files moved aside, and a build output holding one (.dev.vars, .env) is refused. Declared secrets come from the environment or --env-file (an owned 0600 KEY=VALUE file); a new Worker gets the local setup owner and fresh generated secrets when they are not given. rer keeps the secrets it generates in .rer/deploy/ENVIRONMENT.secrets.env (0600) and reuses them on every redeploy; it refuses to generate a replacement for one a live Worker holds, and --rotate-secret NAME[,NAME] replaces them on purpose. After a healthy deploy rer claims the setup owner on the hosted app with the saved setup owner name and the one-time setup token, then removes the token. If the installer declares an owner-name field and no name is saved, deploy asks once and saves it; --non-interactive requires --owner-name NAME before any upload. --set-secret NAME[,NAME] (each value from the environment or --env-file; repeat the flag or join names with commas) and --unset-secret NAME[,NAME] change those secrets of the deployed Worker without a build, all of them in one new Worker version or none, and record that version; a missing value refuses before any change. --reopen-installation-key KID temporarily binds a retired installation key from private custody, reseals restored dependency keys under the current key, verifies them and removes the previous binding. --remove --yes deletes what this environment\'s deploy record says rer created (Worker, D1, R2, KV, queues), reads back that each is gone, and touches nothing else. --site deploys the run site instead: an assets-only Worker on its custom domain with www redirected; with --dry-run it builds the site and prints the plan with no provider request. --demo deploys the hosted demo instead (deploy-demo.json): a front Worker on demo.<domain> giving each visitor their own signed-in, throwaway native Worker isolate of this seed with real public reads/checks and simulated external writes; --dry-run writes it to .rer/demo-host with no provider request; --demo --remove --yes deletes that demo (its Worker, demo.<domain> Custom Domain, each only while the record its deploy left proves it the demo\'s), reads back that each is gone, and is a no-op once it is.'],
15
15
  export: [['--target', '--output', '--origin', '--session-file'], 'For owner move-in, run rer dev and open /app/import: export people there, then upload through the destination door. Developer-only installation backup: complete supported archive of the local copy on this computer, with integrity and exclusions, written to --output. The hosted install cannot be exported yet: --origin or --target remote refuses (exit 2) before any effect and names the command that saves the hosted database.'],
16
16
  import: [['--target', '--input', '--journal', '--origin', '--session-file', '--yes', '--legacy-v1', '--acknowledge-unverified-metadata', '--output'], 'For owner move-in, run rer dev and open /app/import: upload, review and apply through the door. Developer-only installation recovery: confirmed atomic restore into an empty destination; --journal LATER_ARCHIVE also fences rows that installation erased since. Backup-only local v1 recovery requires --legacy-v1 --acknowledge-unverified-metadata and a new --output v2 archive; --journal requires normal v2 import.'],
17
- doctor: [[], 'Read-only installed tool, configuration and state diagnostics.'],
17
+ doctor: [[], 'Read-only installed tool, configuration and state diagnostics.', 'never'],
18
18
  describe: [[], 'Read-only description of actual command capabilities.'],
19
19
  check: [['--profile'], 'Read-only structural command contract and operations validation.'],
20
20
  };
21
- export const verbs = Object.fromEntries(Object.entries(definitions).map(([name, [flags, effects]]) => [name, { flags: [...commonFlags, ...flags, ...(['build','deploy','dev','preview','export','import'].includes(name)?['--platform']:[]), ...(['install','setup','dev','preview','build','verify','deploy','export','import'].includes(name)?['--no-queue']:[])], effects }]));
21
+ export const verbs = Object.fromEntries(Object.entries(definitions).map(([name, [flags, effects, bootstrap = 'before']]) => [name, { bootstrap, flags: [...commonFlags, ...flags, ...(['build','deploy','dev','preview','export','import'].includes(name)?['--platform']:[]), ...(['install','setup','dev','preview','build','verify','deploy','export','import'].includes(name)?['--no-queue']:[])], effects }]));
22
22
  // `rer demo` is `rer dev --demo`; describe lists it as a verb with the dev
23
23
  // flags a demo takes whenever the seed's dev takes --demo.
24
- export const demoVerb = Object.freeze({ flags: [...commonFlags, '--port', '--host', '--idle-timeout', '--stop', '--detach', '--foreground', '--no-queue'], effects: 'A throwaway demo of this seed (rer dev --demo): fresh data in .rer/demo/START (deleted when it stops: --stop, Ctrl-C or its end, one hour by default or --idle-timeout), the saved owner signed in, the seed\'s demo data, Demo in the app name and title, real public reads/checks and simulated external writes (RER_DEMO=1; the checkout\'s own data is never touched).' });
24
+ export const demoVerb = Object.freeze({ bootstrap: 'before', flags: [...commonFlags, '--port', '--host', '--idle-timeout', '--stop', '--detach', '--foreground', '--no-queue'], effects: 'A throwaway demo of this seed (rer dev --demo): fresh data in .rer/demo/START (deleted when it stops: --stop, Ctrl-C or its end, one hour by default or --idle-timeout), the saved owner signed in, the seed\'s demo data, Demo in the app name and title, real public reads/checks and simulated external writes (RER_DEMO=1; the checkout\'s own data is never touched).' });
25
25
  // `rer signin` is rer's own, not a seed operation: any seed rer deploys, it can
26
26
  // sign the owner in to, so no seed declares it and check does not ask for it.
27
- export const signinVerb = Object.freeze({ flags: [...commonFlags, '--environment', '--env-file'], effects: 'A one-time sign-in link for the hosted owner, without mail. Uses the Cloudflare credentials that deployed --environment (default production; from the environment or --env-file) to write a single-use grant for the recorded owner into that deployment\'s auth database, then prints the link once to this terminal; it is never saved. The link works once, only for that owner, expires within 15 minutes, and its use is recorded in the owner\'s audit log. Signed in this way, the owner can correct a wrong email in settings.' });
27
+ export const signinVerb = Object.freeze({ bootstrap: 'before', flags: [...commonFlags, '--environment', '--env-file'], effects: 'A one-time sign-in link for the hosted owner, without mail. Uses the Cloudflare credentials that deployed --environment (default production; from the environment or --env-file) to write a single-use grant for the recorded owner into that deployment\'s auth database, then prints the link once to this terminal; it is never saved. The link works once, only for that owner, expires within 15 minutes, and its use is recorded in the owner\'s audit log. Signed in this way, the owner can correct a wrong email in settings.' });
28
+ // Source-authoring commands belong to rer, not the seed adapter/OPERATIONS.
29
+ // Their project-package bootstrap uses the same contract as every checkout verb.
30
+ export const authoringVerbs = Object.freeze({
31
+ 'adopt-edition': {bootstrap: 'before', flags: [...commonFlags], effects: 'Add edition.json and sources.lock.json for the existing tracked local source, preserving declared project identity and existing copy/composition records. Create an empty base-copies.json only when none exists. Review and stage the new authoring inputs; no source regeneration, install setup or commit.'},
32
+ 'refresh-base': {bootstrap: 'before', flags: [...commonFlags, '--ref', '--base', '--record', '--offline'], effects: 'Refresh recorded Base copies to --ref FULL_COMMIT, preserving acknowledged adaptations and applied migrations; announce removed singleton retirement. Acquire committed source from the declared Base repository (default https://github.com/runeditrun/base.git), or use --base CHECKOUT. --offline requires --base and never acquires remote source. Refuse incomplete Git checkouts without changing their records. Review the diff and run edition tests before committing.'},
33
+ });
28
34
  export const aliases = Object.fromEntries([...Object.keys(verbs).filter(v => v !== 'install'), 'release', 'deps', 'rer'].map(name => [name, name === 'deps' ? 'install' : name === 'rer' ? null : name]));
29
35
  export const releaseFlags = ['--repo', '--project', '--repository', '--output', '--ref', '--public-base', '--dry-run', '--local-verify', '--verify-workflow', '--scan-timeout-seconds', '--tag', '--clean-history', '--onto', '--env-file', '--allow-placeholder-mark', '--no-queue'];
36
+ export const releaseVerb = Object.freeze({
37
+ bootstrap: 'before', flags: [...commonFlags, ...releaseFlags],
38
+ // These operate on supplied files and keys, without running project code.
39
+ subcommands: Object.freeze({ sign: { bootstrap: 'never' }, receipt: { bootstrap: 'never' }, keygen: { bootstrap: 'never' } }),
40
+ });
41
+ // All checkout commands, including those supplied by rer rather than declared
42
+ // as seed operations. Bootstrap belongs to the selected command: before
43
+ // dispatch, during launch, or never. A subcommand inherits its verb's policy.
44
+ export const checkoutVerbs = Object.freeze({ ...verbs, ...authoringVerbs, demo: demoVerb, signin: signinVerb, release: releaseVerb });
45
+ export function checkoutBootstrap([verb, ...args]) {
46
+ if (args.includes('--help')) return 'never';
47
+ const command = checkoutVerbs[verb];
48
+ return command?.subcommands?.[args[0]]?.bootstrap ?? command?.bootstrap ?? 'never';
49
+ }
30
50
  export const requiredHooks = ['preview', 'dependencies', 'build', 'migrate', 'start', 'health', 'owner', 'signIn', 'verify', 'deploy', 'portability', 'state', 'settings', 'input'];
package/cli/demo-host.mjs CHANGED
@@ -2,17 +2,19 @@ import { readFile } from 'node:fs/promises';
2
2
  import { contained } from './project.mjs';
3
3
  import { invalid, missing, RerError } from './errors.mjs';
4
4
  import { demoPlan } from '../modules/demo-host/plan.mjs';
5
+ import { demoRunDeclaration } from '../modules/demo/declaration.mjs';
5
6
 
6
7
  export async function demoHostCommand(project, options, store, signal, out, operation) {
7
8
  const read = async path => { try { return JSON.parse(await readFile(await contained(project.root, path), 'utf8')); } catch (error) { if (error instanceof RerError) throw error; throw invalid(`Missing or malformed ${path}.`); } };
8
9
  const app = await read(project.adapter.deploy?.declaration ?? 'deploy.json'), declaration = await read('deploy-demo.json');
9
10
  // Old releases wrote sizing and mode selectors. Consume their removal here
10
11
  // so pinning this release needs no per-seed declaration edit.
11
- const { instanceType: retiredSize, mode: retiredMode, ...nativeDeclaration } = declaration;
12
+ const { instanceType: retiredSize, mode: retiredMode, ...nativeInput } = declaration;
13
+ const nativeDeclaration = await demoRunDeclaration(nativeInput, { root: project.root, adapter: project.adapter, read });
12
14
  if (retiredSize !== undefined || retiredMode !== undefined) store.report('Hosted demos now use the native Loader host; remove the retired instanceType and mode keys from deploy-demo.json.');
13
15
  let plan;
14
16
  try { plan = demoPlan({ project: app.project, environment: options.environment ?? 'production', compatibilityDate: app.compatibilityDate, originVar: app.originVar, hostVariables: app.container?.hostVariables, declaration: nativeDeclaration, turnstileSiteKey: process.env.TURNSTILE_SITE_KEY?.trim() }); }
15
- catch (error) { throw invalid(`The demo deploy declaration is invalid (${error.message}). deploy-demo.json holds version, domain, name, and optionally maxInstances, ownerEmail and plain settings.`); }
17
+ catch (error) { throw invalid(`The demo deploy declaration is invalid (${error.message}). deploy-demo.json holds version, domain, name, and optionally maxInstances, ownerEmail, runUrl and plain settings.`); }
16
18
  if (options.remove) return removeDemo(plan, store, signal);
17
19
  if (process.env.RER_DEMO_OPERATOR_TOKEN && (process.env.RER_DEMO_OPERATOR_TOKEN.length < 32 || process.env.RER_DEMO_OPERATOR_TOKEN.length > 512)) throw invalid('RER_DEMO_OPERATOR_TOKEN must contain 32 to 512 characters.');
18
20
  const supplied = process.env.RER_DEMO_MEASUREMENT_TOKEN?.trim();
@@ -21,12 +21,14 @@ export function deployGuide(declaration) {
21
21
  return value;
22
22
  }
23
23
 
24
+ /** The account permissions an API token needs to deploy this declaration (the run site's /docs/hosting lists the same). */
25
+ export const deployPermissions = declaration => permissions.filter(([, used]) => used(declaration)).map(([name]) => name);
26
+
24
27
  // Where a person gets the Cloudflare values: the project's guide, else the token page and the permissions.
25
28
  function credentialHelp(declaration) {
26
29
  const guide = deployGuide(declaration);
27
30
  if (guide) return [`Follow this project's deploy guide: ${guide}`];
28
- const needed = permissions.filter(([, used]) => used(declaration)).map(([name]) => name);
29
- return [`Create an account API token at ${tokenPage} with these account permissions: ${needed.join(', ')}. Copy your account ID from the Cloudflare dashboard.`];
31
+ return [`Create an account API token at ${tokenPage} with these account permissions: ${deployPermissions(declaration).join(', ')}. Copy your account ID from the Cloudflare dashboard.`];
30
32
  }
31
33
 
32
34
  export function missingCredentialsMessage(declaration, env, { dryRun = false, signIn } = {}) {
@@ -66,8 +66,8 @@ export async function resolvePersona(url, key, as, signal) {
66
66
  // The people rer can sign in as: each persona with its email, then every
67
67
  // invited or active person in this checkout's local database by email.
68
68
  const valid = personas.map(entry => entry.as === entry.email || !entry.email ? entry.as : `${entry.as} (${entry.email})`).join(', ');
69
- if (!as.includes('@')) throw invalid(`Unknown dev persona ${as}. rer dev --as takes one of: ${valid}.`);
70
- throw invalid(`No one with the email ${as} can sign in to this app locally. rer dev --as takes one of: ${valid}. Someone added only to the app's own records can sign in once the app invites them (its Invite action, which sends no mail locally); then run rer dev --as ${as} again.`);
69
+ if (!as.includes('@')) throw invalid(`Dev persona ${as} is unavailable for sign-in. Run rer dev --as with one of: ${valid}. If this account is inactive, ask an owner or administrator to reactivate it first.`);
70
+ throw invalid(`No one with the email ${as} can sign in to this app locally. rer dev --as takes one of: ${valid}. If this account is inactive, ask an owner or administrator to reactivate it. Someone added only to the app's own records can sign in once the app invites them (its Invite action, which sends no mail locally); then run rer dev --as ${as} again.`);
71
71
  }
72
72
 
73
73
  // rer build refuses output that bundles the dev layer, naming the file.
package/cli/export.mjs CHANGED
@@ -6,7 +6,7 @@ import { cliVersion } from './version.mjs';
6
6
 
7
7
  // Copy whole maintained source/tooling directories. Python publication scans
8
8
  // load sibling modules and data dynamically; they belong in the inventory too.
9
- export const sourceRoots = ['default-seed/public/rer-theme.css', 'default-seed/public/brand/mark.svg', 'default-seed/public/fonts/outfit', 'bin/rer.mjs', 'cli', 'modules/delivery-producer/declarations.mjs', 'modules/delivery-producer/bindings.mjs', 'modules/delivery-producer/migrations.mjs', 'modules/delivery-producer/mail.mjs', 'modules/job-queue', 'modules/release', 'modules/deploy-kit', 'modules/site', 'modules/container', 'modules/demo-host', 'modules/demo', 'modules/integrations/core', 'modules/mail', 'modules/ai', 'modules/portability', 'modules/d1-transport', 'modules/import-kit/src/d1', 'modules/import-kit/src/types.ts', 'modules/import-kit/src/plan', 'modules/import-kit/src/provenance/canonical-hash.ts', 'modules/import-kit/src/provenance/canonical-stream.ts', 'modules/import-kit/src/provenance/credential-names.ts', 'modules/import-kit/src/provenance/credentials.ts', 'modules/import-kit/src/provenance/identity.ts', 'modules/import-kit/src/provenance/json-snapshot.ts', 'modules/import-kit/src/provenance/resumable-sha256.ts', 'modules/import-kit/src/provenance/validate-json.ts', 'modules/import-kit/src/journal/authority.ts', 'modules/import-kit/src/storage/originals.ts', 'modules/import-kit/src/storage/provenance.ts', 'modules/import-kit/src/storage/schema.ts', 'modules/erasure', 'modules/dependencies', 'modules/operator-auth', 'modules/owner-claim', 'operations', 'scripts/publish-check', 'scripts/publish-check.mjs', 'composition/git-source.mjs', 'edition-authoring/manifest.mjs', 'edition-authoring/files.mjs', 'foundation/runtime/seed-contract.mjs'];
9
+ export const sourceRoots = ['default-seed/public/rer-theme.css', 'default-seed/public/brand/mark.svg', 'default-seed/public/fonts/outfit', 'bin/rer.mjs', 'cli', 'modules/delivery-producer/declarations.mjs', 'modules/delivery-producer/bindings.mjs', 'modules/delivery-producer/migrations.mjs', 'modules/delivery-producer/mail.mjs', 'modules/job-queue', 'modules/release', 'modules/deploy-kit', 'modules/site', 'modules/container', 'modules/demo-host', 'modules/demo', 'modules/integrations/core', 'modules/mail', 'modules/ai', 'modules/portability', 'modules/d1-transport', 'modules/import-kit/src/d1', 'modules/import-kit/src/types.ts', 'modules/import-kit/src/plan', 'modules/import-kit/src/provenance/canonical-hash.ts', 'modules/import-kit/src/provenance/canonical-stream.ts', 'modules/import-kit/src/provenance/credential-names.ts', 'modules/import-kit/src/provenance/credentials.ts', 'modules/import-kit/src/provenance/identity.ts', 'modules/import-kit/src/provenance/json-snapshot.ts', 'modules/import-kit/src/provenance/resumable-sha256.ts', 'modules/import-kit/src/provenance/validate-json.ts', 'modules/import-kit/src/journal/authority.ts', 'modules/import-kit/src/storage/originals.ts', 'modules/import-kit/src/storage/provenance.ts', 'modules/import-kit/src/storage/schema.ts', 'modules/erasure', 'modules/dependencies', 'modules/operator-auth', 'modules/owner-claim', 'operations', 'scripts/publish-check', 'scripts/publish-check.mjs', 'composition/git-source.mjs', 'edition-authoring/adopt.mjs', 'edition-authoring/base-acknowledgements.mjs', 'edition-authoring/base-copies.mjs', 'edition-authoring/cli.mjs', 'edition-authoring/copy-checkout.mjs', 'edition-authoring/files.mjs', 'edition-authoring/lock.mjs', 'edition-authoring/manifest.mjs', 'edition-authoring/offline-git.mjs', 'edition-authoring/parent-comparison.mjs', 'edition-authoring/projection-lock.mjs', 'edition-authoring/release.mjs', 'edition-authoring/runtime-dependencies.mjs', 'edition-authoring/sources.mjs', 'edition-authoring/updates.mjs', 'foundation/runtime/seed-contract.mjs'];
10
10
  export async function inventory(base, roots = sourceRoots) {
11
11
  const files = [];
12
12
  async function walk(path) {
package/cli/inspect.mjs CHANGED
@@ -4,7 +4,7 @@ import { inventory } from './export.mjs';
4
4
  import { lstat, readFile } from 'node:fs/promises';
5
5
  import { createHash } from 'node:crypto';
6
6
  import { delimiter, dirname, resolve } from 'node:path';
7
- import { aliases, demoVerb, pins, requiredHooks, serverDefaults, signinVerb, verbs, releaseFlags } from './contract.mjs';
7
+ import { authoringVerbs, aliases, demoVerb, pins, requiredHooks, serverDefaults, signinVerb, verbs, releaseFlags } from './contract.mjs';
8
8
  import { runningVersion } from './version.mjs';
9
9
  import { contained, readPackage } from './project.mjs';
10
10
  import { shared } from './shared.mjs';
@@ -24,6 +24,7 @@ import { deliveryDeclarationClauses } from './delivery-declarations.mjs';
24
24
  import { checkoutPlaceholderMarks } from './placeholder-mark.mjs';
25
25
  import { contractStatusClauses } from './contract-status.mjs';
26
26
  import { hostedExportCommand } from './hosted-export-command.mjs';
27
+ import { cloudflareCredentials } from './deploy-needs.mjs';
27
28
 
28
29
  // cliVersion: the rer version of the code answering (absent for a vendored copy
29
30
  // too old to record one). defaults: what a server start applies when the person
@@ -48,6 +49,7 @@ export async function describe(project) {
48
49
  return [verb, { flags: (verbs[verb]?.flags ?? releaseFlags).filter(flag => capability.flags?.includes(flag)), effects }];
49
50
  }).concat(capabilities.dev?.flags?.includes('--demo') ? [['demo', { flags: demoVerb.flags.filter(flag => capabilities.dev.flags.includes(flag)), effects: demoVerb.effects }]] : [])
50
51
  // rer signin is rer's own: any seed it can deploy, it can sign the owner in to.
52
+ .concat(Object.entries(authoringVerbs))
51
53
  .concat(capabilities.deploy ? [['signin', { flags: signinVerb.flags, effects: signinVerb.effects }]] : [])),
52
54
  aliases: Object.fromEntries(Object.entries(aliases).filter(([alias, verb]) => pkg.scripts?.[alias] === commandLine(verb, declaredPackage(pkg) !== undefined))),
53
55
  local: { state: project.adapter?.state, settings: project.adapter?.settings ?? [], installerState: '.seed/installer', ...await localState(project), origin: await savedOrigin(project), ...(project.adapter?.devIdentity ? { devIdentity: true, devKey: '.rer/local/dev-key.env' } : {}) },
@@ -203,6 +205,13 @@ const usePnpm = directory => {
203
205
  export async function doctor(project, store, signal) {
204
206
  const { inspectOperations } = await import('../operations/operations.mjs');
205
207
  const diagnostic = await inspectOperations(project.root);
208
+ // The operations declaration includes deployment prerequisites. Local health
209
+ // does not require an account, and doctor never checks provider access.
210
+ const deploymentInputs = project.profile === 'first-party' ? diagnostic.missingEnvironment.filter(name => cloudflareCredentials.includes(name)) : [];
211
+ if (deploymentInputs.length) {
212
+ diagnostic.missingEnvironment = diagnostic.missingEnvironment.filter(name => !deploymentInputs.includes(name));
213
+ diagnostic.ok = diagnostic.commands.every(command => command.available) && !diagnostic.missingEnvironment.length && diagnostic.configuration === 'valid' && (diagnostic.loops ?? []).every(loop => ['ready', 'optional-disabled'].includes(loop.status));
214
+ }
206
215
  const { localVariables } = await shared('local/environment.mjs');
207
216
  let values = {}, pnpm, expectedPnpm, stateIssue, stateValid = true;
208
217
  const pnpmIssues = [];
@@ -239,10 +248,37 @@ export async function doctor(project, store, signal) {
239
248
  node: { actual: process.versions.node, expected: expectedNode },
240
249
  pnpm: project.profile === 'first-party' ? { actual: pnpm, expected: expectedPnpm ?? null, ...(pnpmIssues.length ? { issue: [...new Set(pnpmIssues)].join('\n') } : {}) } : undefined,
241
250
  ai: { issues: aiIssues },
242
- missingInputs: [...new Set([...diagnostic.missingEnvironment, ...inputs])],
251
+ missingInputs: [...new Set([...diagnostic.missingEnvironment, ...inputs])], deploymentInputs,
243
252
  sources: project.descriptor.environmentSources ?? {}, state: { path: project.adapter?.state, safe: stateValid, ...(stateIssue ? { issue: stateIssue } : {}) }, scope: 'local-inputs-only' };
244
253
  }
245
254
 
255
+ export function doctorSummary(result) {
256
+ const lines = [result.ok ? 'Local checks passed.' : 'Local checks need attention.'];
257
+ if (result.node.expected) lines.push(`Node: ${result.node.actual} (expected ${result.node.expected}).`);
258
+ if (result.pnpm) {
259
+ lines.push(`pnpm: ${result.pnpm.actual ?? 'unavailable'} (expected ${result.pnpm.expected ?? 'an exact project pin'}).`);
260
+ if (result.pnpm.issue) lines.push(result.pnpm.issue);
261
+ }
262
+ if (result.missingInputs.length) {
263
+ lines.push('Missing local inputs:');
264
+ for (const name of result.missingInputs) lines.push(` ${name}${result.sources[name] ? `: ${result.sources[name]}` : ''}`);
265
+ lines.push('Run rer setup to configure this checkout.');
266
+ }
267
+ const unavailable = result.operations.commands.filter(command => !command.available);
268
+ if (unavailable.length) lines.push('Unavailable command inputs:', ...unavailable.map(command => ` ${command.name}: restore its declared input files.`));
269
+ if (result.operations.configuration === 'invalid') lines.push('Local configuration is invalid. Check the declared configuration module; private validator details are suppressed.');
270
+ for (const loop of result.operations.loops ?? []) if (!['ready', 'optional-disabled'].includes(loop.status)) lines.push(`Loop ${loop.id}: ${loop.status}${loop.missingEnvironment?.length ? `; missing ${loop.missingEnvironment.join(', ')}` : ''}.`);
271
+ if (!result.state.safe) lines.push(`Local state: ${result.state.issue}`);
272
+ if (result.browser?.issue) lines.push(`Browser dependencies: ${result.browser.issue}`);
273
+ else if (result.browser?.note) lines.push(result.browser.note);
274
+ for (const issue of result.ai.issues) lines.push(`AI ${issue.feature}: ${issue.code}: ${issue.message}`);
275
+ for (const dependency of result.dependencies) lines.push(`Dependency ${dependency.interface ?? 'local state'}: ${dependency.status}.`);
276
+ for (const warning of result.warnings) lines.push(typeof warning === 'string' ? warning : warning.message);
277
+ if (result.deploymentInputs.length) lines.push(`Optional for local use; needed to deploy: ${result.deploymentInputs.join(', ')}.`);
278
+ lines.push('Remote deployment, provider credentials and permissions, and deployed health were not checked.');
279
+ return lines.join('\n');
280
+ }
281
+
246
282
  // SC-05: a seed declaring devIdentity loads the dev layer only from a local-only
247
283
  // entry that its dev configuration names, never from the deployed main, lets
248
284
  // rer build scan its output.
@@ -0,0 +1,18 @@
1
+ // What a person does about each migration-history refusal (portability-migrations.mjs, modules/portability/ledgers.mjs).
2
+ // Codes are constant categories; a migration named by an archive or the checkout follows the second colon.
3
+ const fixes = {
4
+ unknown: 'the archive records a migration whose file name or content this checkout does not have. Restore with the checkout version that exported it (or a later one), with its migration files unchanged.',
5
+ conflict: 'a migration in the archive has the name of one checkout file and the content of another. Restore with the checkout version that exported it, with its migration files unchanged.',
6
+ ambiguous: 'one migration identity matches several checkout files or ledger entries. Keep a single file per migration and declare the seed\'s migration prefix.',
7
+ unapplied: 'the installation\'s history lacks a migration this checkout ships. Apply it with the runner that owns the history (RER Platform for a Managed installation), then retry.',
8
+ multiple: 'the database holds more than one migration ledger. Reconcile its history with the runner that owns it.',
9
+ uncertain: 'a migration was left partly applied. Finish or roll back that operation with its runner, then retry.',
10
+ runner: 'the history belongs to the older Base deploy runner, which can adopt it. Use that runner first.',
11
+ incompatible: 'the migration ledger or the checkout declaration has an unsupported shape. Use the matching checkout and its declaration.',
12
+ binding: 'the checkout declares no single D1 binding with that name. Use the matching checkout.',
13
+ };
14
+ export function ledgerRefusal(receipt) {
15
+ const [, kind, ...name] = receipt.reason.split(':');
16
+ const named = receipt.unapplied ?? (name.length ? name.join(':') : undefined);
17
+ return `Migration history refused (${receipt.reason}): ${named ? `migration ${named}: ` : ''}${fixes[kind] ?? 'its history does not match this checkout.'}`;
18
+ }
package/cli/main.mjs CHANGED
@@ -1,9 +1,10 @@
1
1
  import './sqlite-notice.mjs';
2
+ import {authoringVerbs} from './contract.mjs';
2
3
  import { parse, help } from './parse.mjs';
3
4
  import { output } from './output.mjs';
4
5
  import { invalid, RerError } from './errors.mjs';
5
6
  import { resolveProject, parsingProfile } from './project.mjs';
6
- import { check, describe } from './inspect.mjs';
7
+ import { check, describe, doctorSummary } from './inspect.mjs';
7
8
  import { selectNodeRuntime } from './node-runtime.mjs';
8
9
 
9
10
  export async function main(argv = process.argv.slice(2)) {
@@ -37,6 +38,11 @@ export async function main(argv = process.argv.slice(2)) {
37
38
  if(options.noQueue){const {shared}=await import('./shared.mjs');const {commandPolicy}=await shared('queue.mjs');const policy=await commandPolicy();try{if(!policy.ci)throw invalid('--no-queue requires the original caller CI=true.');}finally{await policy.close();}}
38
39
  const runtime = await selectNodeRuntime(options, argv, out);
39
40
  if (runtime) return runtime.exitCode;
41
+ if (!independent && Object.hasOwn(authoringVerbs, options.verb)) {
42
+ const result = (await import('./authoring.mjs')).authoringCommand(options);
43
+ if (!options.json) out.human(JSON.stringify(result, null, 2));
44
+ out.result(true, 0, result); return 0;
45
+ }
40
46
  project ??= await resolveProject(options.cwd);
41
47
  if (project.profile === 'independent' && !['describe', 'check', 'doctor'].includes(options.verb)) options = parse(argv, process.cwd(), { independent: true });
42
48
  else if (options.forwarded.length) throw invalid('First-party commands accept only the documented flags, without forwarded arguments.');
@@ -51,7 +57,7 @@ export async function main(argv = process.argv.slice(2)) {
51
57
  }
52
58
  if (options.verb === 'doctor') {
53
59
  const result = await (await import('./lifecycle.mjs')).runCommand(project, options, out);
54
- if (!options.json) out.human(JSON.stringify(result, null, 2));
60
+ if (!options.json) out.human(doctorSummary(result));
55
61
  out.result(result.ok, result.ok ? 0 : 3, { diagnostics: result }); return result.ok ? 0 : 3;
56
62
  }
57
63
  // The owner link is printed once to this terminal: never through the logged lifecycle.
@@ -29,7 +29,7 @@ export function ready(out,url,dev,json=false,siteUrl,demo){
29
29
  out.human("Open that link on this computer. Its fragment holds this checkout's dev key, which the page keeps only as a cookie; never share the link.");
30
30
  }
31
31
  if(siteUrl)out.human(`RER_SITE ${siteUrl}`);
32
- if(demo){out.human(`RER_DEMO_ENDS_ON_STOP ${demo.state}`);out.human(`This demo runs on its own data in that folder, which is deleted when it stops: rer demo --stop, Ctrl-C, or at its end (${demo.ends.slice(11,16)}). Public reads and checks run for real; external writes are simulated. This checkout's own data is untouched.`);}
32
+ if(demo){out.human(`RER_DEMO_ENDS_ON_STOP ${demo.state}`);out.human(`This demo runs on its own data in that folder, which is deleted when it stops: rer demo --stop, Ctrl-C, or at its end (${demo.ends.slice(11,16)}). Public reads and checks run for real. This checkout's own data is untouched.`);}
33
33
  }
34
34
  export async function managedServer(project,options,out,{clock={}}={}){
35
35
  const registry=await serverRegistry(project.root),controller=new AbortController();
package/cli/parse.mjs CHANGED
@@ -1,9 +1,9 @@
1
1
  import { resolve } from 'node:path';
2
- import { commonFlags, serverDefaults, signinVerb, verbs } from './contract.mjs';
2
+ import { authoringVerbs, commonFlags, serverDefaults, signinVerb, verbs } from './contract.mjs';
3
3
  import { invalid, refuse } from './errors.mjs';
4
4
  import { isLoopbackHost } from '../modules/operator-auth/loopback.mjs';
5
5
  import { normalizeEmail } from '../modules/operator-auth/policy.mjs';
6
- const booleans = new Set(['--help', '--json', '--non-interactive', '--yes', '--dry-run', '--stop', '--detach', '--foreground', '--no-queue', '--login', '--legacy-v1', '--acknowledge-unverified-metadata', '--door', '--direct', '--site', '--remove', '--demo']);
6
+ const booleans = new Set(['--help', '--json', '--non-interactive', '--yes', '--dry-run', '--stop', '--detach', '--foreground', '--no-queue', '--login', '--legacy-v1', '--acknowledge-unverified-metadata', '--door', '--direct', '--site', '--remove', '--demo', '--offline']);
7
7
  export const mailbox = value => typeof value === 'string' && value.length <= 254 && /^[a-zA-Z0-9.!+_%\-]+@[a-zA-Z0-9\-]+(?:\.[a-zA-Z0-9\-]+)+$/.test(value);
8
8
  export const validOwnerName = value => typeof value === 'string' && Boolean(value.trim()) && value.length <= 200 && !/[\p{Cc}\p{Cf}]/u.test(value);
9
9
  // A loopback host: the shared predicate (including `*.localhost` door names),
@@ -26,7 +26,7 @@ export function parse(argv, cwd = process.cwd(), { independent = false, deferTai
26
26
  // Independent projects own verb names; only the common wrapper flags apply
27
27
  // to unknown names. Profile resolution rejects undeclared commands later.
28
28
  if (!/^[a-z][a-z0-9-]*$/.test(verb)) throw invalid('Unknown rer command. Run rer --help.');
29
- const allowed = new Set(independent ? [...commonFlags,...(['install','setup','build','verify','deploy','release','export','import','dev','preview'].includes(verb)?['--no-queue']:[])] : (verbs[verb] ?? (verb === 'signin' ? signinVerb : undefined))?.flags ?? commonFlags), options = { verb, cwd: resolve(cwd), forwarded: [], supplied: new Set() };
29
+ const allowed = new Set(independent ? [...commonFlags,...(['install','setup','build','verify','deploy','release','export','import','dev','preview'].includes(verb)?['--no-queue']:[])] : (verbs[verb] ?? authoringVerbs[verb] ?? (verb === 'signin' ? signinVerb : undefined))?.flags ?? commonFlags), options = { verb, cwd: resolve(cwd), forwarded: [], supplied: new Set() };
30
30
  let separator = false;
31
31
  for (let i = 0; i < args.length; i++) {
32
32
  const flag = args[i];
@@ -53,6 +53,7 @@ export function parse(argv, cwd = process.cwd(), { independent = false, deferTai
53
53
  }
54
54
  if (options.help) return options;
55
55
  if (deferTail) { options.cwd=resolve(cwd,options.cwd);return options; }
56
+ if (verb === 'refresh-base' && !independent && !options.ref) throw invalid('Provide --ref with the full immutable Base commit. Run rer refresh-base --help.');
56
57
  if (options.detach && options.foreground) throw invalid('Choose one of --detach and --foreground.');
57
58
  if(options.stop && ['--port','--host','--idle-timeout','--detach','--foreground','--no-queue','--as','--login','--models','--models-service','--door','--direct'].some(flag=>options.supplied.has(flag)))throw invalid('--stop cannot be combined with start-only flags.');
58
59
  // --port and --host always mean direct mode; --door and --direct pick a mode.
@@ -107,10 +108,10 @@ export function parse(argv, cwd = process.cwd(), { independent = false, deferTai
107
108
  }
108
109
 
109
110
  export function help(verb) {
110
- if (!verb) return `Usage: rer VERB [FLAGS]\nCommands: ${Object.keys(verbs).join(', ')}, signin, release, listing\nRun rer VERB --help for flags.\n`;
111
- const known = verbs[verb] ?? (verb === 'signin' ? signinVerb : undefined);
111
+ if (!verb) return `Usage: rer VERB [FLAGS]\nCommands: ${Object.keys({...verbs, ...authoringVerbs}).join(', ')}, signin, release, listing\nRun rer VERB --help for flags.\n`;
112
+ const known = verbs[verb] ?? authoringVerbs[verb] ?? (verb === 'signin' ? signinVerb : undefined);
112
113
  const door = ['export', 'import'].includes(verb) ? 'To move records, start the app and open its signed-in owner import door:\n\n rer dev\n\nOpen /app/import, then export or upload and review supported records there.\n\nTo back up or restore this installation:\n' : '';
113
- return `${door}Usage: rer ${verb} [FLAGS]\nFlags: ${(known?.flags ?? commonFlags).join(', ')}\n${known?.effects ?? 'Execute the declared OPERATIONS v2 argv with explicit arguments after --.'}\n`;
114
+ return `${door}Usage: rer ${verb}${verb === 'refresh-base' ? ' --ref FULL_COMMIT' : ''} [FLAGS]\nFlags: ${(known?.flags ?? commonFlags).join(', ')}\n${known?.effects ?? 'Execute the declared OPERATIONS v2 argv with explicit arguments after --.'}\n`;
114
115
  }
115
116
 
116
117
  function distance(a,b){let row=Array.from({length:b.length+1},(_,i)=>i);for(let i=1;i<=a.length;i++){const next=[i];for(let j=1;j<=b.length;j++)next[j]=Math.min(next[j-1]+1,row[j]+1,row[j-1]+(a[i-1]===b[j-1]?0:1));row=next;}return row[b.length];}
@@ -35,6 +35,33 @@ export async function appliedMigrations(root,db,binding,declaration,split) {
35
35
  return matchMigrationLedger(ledger,files,declaration).map(name=>files.find(file=>file.name===name));
36
36
  }
37
37
 
38
+ // Ledger contents can contain private values. Report constant categories,
39
+ // retaining the transfer's canonical compatibility and hash-matching policy.
40
+ function constantRefusal(error) {
41
+ if(!(error instanceof PortabilityError))return error;
42
+ const code=error.code.startsWith('migration_ledger:')?error.code.split(':').slice(0,2).join(':')
43
+ :error.code==='schema_mismatch:uncertain_migrations'?'migration_ledger:uncertain':'migration_ledger:incompatible';
44
+ return Object.assign(new PortabilityError(code,409),error.migration===undefined?{}:{migration:error.migration});
45
+ }
46
+
47
+ // For adapters with their own archive format: the entries of a migration ledger
48
+ // ([{name,sha256}], as RER Platform's rer_migrations records them or as an
49
+ // archive carries them) named by the checkout's migration files, matched by
50
+ // SHA-256 and refused when a name or hash differs from the checkout's. The
51
+ // result is the native-equivalent ledger: write it to an export, or compare it
52
+ // with the archive on import, instead of comparing ledger controllers.
53
+ // Declared data-only entries keep their own names. Reads files only.
54
+ export async function mapMigrationLedger({root,binding='DB',platformMigrations,entries}) {
55
+ const declaration=platformMigrationDeclaration(platformMigrations);
56
+ insist(Array.isArray(entries) && entries.every(entry=>entry && typeof entry.name==='string' && typeof entry.sha256==='string' && /^[a-f0-9]{64}$/.test(entry.sha256)) && new Set(entries.map(entry=>entry.name)).size===entries.length,'migration_ledger:incompatible',409);
57
+ const files=await inventory(root,binding,declaration);
58
+ try {
59
+ const mapped=entries.map(({name,sha256})=>({name:matchMigrationLedger([{name,sha256}],files,declaration)[0]??name,sha256}));
60
+ insist(new Set(mapped.map(entry=>entry.name)).size===mapped.length,'migration_ledger:ambiguous',409);
61
+ return mapped;
62
+ } catch(error) { throw constantRefusal(error); }
63
+ }
64
+
38
65
  // Adapter entry point, before *any* native Wrangler apply. The caller supplies
39
66
  // the real target binding and keeps its writers stopped through apply/transfer.
40
67
  // This only reads: it never repairs history or creates a second ledger.
@@ -52,16 +79,8 @@ export async function nativeMigrationPreflight({root,db,binding='DB',platformMig
52
79
  const ledger=await destinationLedger(db),applied=matchMigrationLedger(ledger,files,declaration);
53
80
  // Wrangler skips only literal filenames, not transfer aliases or hashes.
54
81
  if(table==='d1_migrations')insist(ledger.every(row=>files.some(file=>file.name===row.name)),'migration_ledger:incompatible',409);
55
- if(table==='rer_migrations')for(const file of files)insist(applied.includes(file.name),'migration_ledger:unapplied',409);
56
- } catch(error) {
57
- // Ledger contents can contain private values. Report constant categories,
58
- // retaining the transfer's canonical compatibility and hash-matching policy.
59
- if(error instanceof PortabilityError) {
60
- const code=error.code.startsWith('migration_ledger:')?error.code.split(':').slice(0,2).join(':')
61
- :error.code==='schema_mismatch:uncertain_migrations'?'migration_ledger:uncertain':'migration_ledger:incompatible';
62
- throw new PortabilityError(code,409);
63
- }
64
- throw error;
65
- }
82
+ // The checkout file is named: it is the seed's own, never a ledger value.
83
+ if(table==='rer_migrations')for(const file of files)if(!applied.includes(file.name))throw Object.assign(new PortabilityError('migration_ledger:unapplied',409),{migration:file.name});
84
+ } catch(error) { throw constantRefusal(error); }
66
85
  return {nativeApply:table==='d1_migrations'};
67
86
  }
@@ -74,6 +74,9 @@ catch (error) {
74
74
  const reason = error instanceof PortabilityError ? (error.code.startsWith('migration_ledger:') ? error.code : error.code.split(':')[0]) : /^[A-Z_]+$/.test(error.code ?? '') ? error.code : error.message === 'archive_json' ? 'archive_json' : 'native_error';
75
75
  // A later migration that changes restorable data is named: it is a file of this installation.
76
76
  const migration = error instanceof PortabilityError && error.code.startsWith('schema_mismatch:migration_data:') ? error.code.slice('schema_mismatch:migration_data:'.length) : undefined;
77
+ // An unapplied migration is a file of this checkout: it is named so it can be applied.
78
+ const unapplied = error instanceof PortabilityError && error.code === 'migration_ledger:unapplied' ? error.migration : undefined;
79
+ const reExport = error instanceof PortabilityError && ['schema_mismatch:legacy_schema','schema_mismatch:unsupported_sql'].includes(error.code);
77
80
  // A populated destination names its table or bucket: schema names, never row data.
78
81
  const occupied = error instanceof PortabilityError && /^(target|bucket)_not_empty:/.test(error.code) ? error.code.slice(error.code.indexOf(':') + 1) : undefined;
79
82
  // Safety diagnostics contain only policy schema names, never source values.
@@ -81,5 +84,5 @@ catch (error) {
81
84
  // Anything that is not a portability refusal names its class and code, never its message: that can hold row data.
82
85
  const native = error instanceof PortabilityError || error.message === 'archive_json' ? undefined : nativeFailure(error);
83
86
  process.exitCode = exitCode;
84
- await reply({ ok: false, code: exitCode === 2 ? 'invalid_archive' : exitCode === 4 ? 'restore_refused' : 'transfer_failed', reason, ...(migration ? { migration } : {}), ...(occupied ? { occupied } : {}), ...(safety ? { safety } : {}), ...(native ? { native } : {}), exitCode });
87
+ await reply({ ok: false, code: exitCode === 2 ? 'invalid_archive' : exitCode === 4 ? 'restore_refused' : 'transfer_failed', reason, ...(reExport ? { reExport: true } : {}), ...(migration ? { migration } : {}), ...(unapplied ? { unapplied } : {}), ...(occupied ? { occupied } : {}), ...(safety ? { safety } : {}), ...(native ? { native } : {}), exitCode });
85
88
  }
@@ -7,6 +7,9 @@ import { fileRecords } from '../modules/portability/files.mjs';
7
7
  import { RerError, refuse } from './errors.mjs';
8
8
  import { policyModuleURL, serializablePolicy } from './portability-policy.mjs';
9
9
  import { shared } from './shared.mjs';
10
+ import { ledgerRefusal } from './ledger-refusal.mjs';
11
+
12
+ const reExport = 'Re-export from the original installation with rer export --output exports/recovered.rer (add --target remote for a hosted installation), then retry rer import --input exports/recovered.rer --yes. Keep the original archive until recovery succeeds.';
10
13
 
11
14
  // Seeds declare their real bindings and data policy. The shared module owns the
12
15
  // archive format and atomic restore; the shared runner owns its native children.
@@ -24,11 +27,11 @@ export function localPortability({ database, binding = 'DB', buckets = {}, polic
24
27
  if(journal)for await(const record of fileRecords(journal)) {}
25
28
  }
26
29
  catch (error) {
27
- if (error.message === 'archive_json') throw new RerError('invalid_archive', 'Restore refused (archive_json): archive JSON is invalid.', 2);
30
+ if (error.message === 'archive_json') throw new RerError('invalid_archive', `Restore refused: the archive is damaged or incomplete. ${reExport}`, 2);
28
31
  if (!(error instanceof PortabilityError)) throw error;
29
32
  const message = error.code === 'legacy_archive_unverifiable'
30
33
  ? 'Restore refused (legacy_archive_unverifiable): version 1 metadata cannot be authenticated. Upgrade the original installation and re-export, or use rer import --legacy-v1 --input FILE --yes --acknowledge-unverified-metadata --output exports/recovered-v2.rer in an empty installation. See modules/portability/README.md#backup-only-v1-recovery.'
31
- : `Restore refused (${error.code}): archive verification failed.`;
34
+ : `Restore refused (${error.code}): archive verification failed. ${reExport}`;
32
35
  const refused = error.status === 409;
33
36
  throw new RerError(refused ? 'restore_refused' : 'transfer_failed', message, refused ? 4 : 1);
34
37
  }
@@ -83,7 +86,10 @@ async function nativeWorker(store,direction,input,signal) {
83
86
  if (!receipt || typeof receipt !== 'object') throw new RerError('transfer_failed', `Local portability ended before it finished (${status.signal ? `signal ${status.signal}` : `exit code ${status.code}`}). Run the same command again; it starts over${direction === 'import' ? ' and first cleans up anything this attempt staged' : ''}.`, 1);
84
87
  if (status.code !== 0 || !receipt.ok) throw new RerError(receipt.code ?? 'transfer_failed', receipt.reason==='legacy_restored_export_failed'
85
88
  ? 'Legacy data was restored and audited, but its v2 export failed. Preserve this installation, resolve the output problem, then run rer export --output FILE. Do not reset it to retry recovery.'
89
+ : receipt.reason === 'archive_json' ? `Restore refused: the archive is damaged or incomplete. ${reExport}`
90
+ : receipt.reExport ? `Restore refused (schema_mismatch): the schema definitions cannot be safely verified by this version. ${reExport}`
86
91
  : receipt.safety ? `Restore refused (${receipt.reason}): safety normalization for ${receipt.safety} violates the declared import policy.`
92
+ : receipt.reason?.startsWith('migration_ledger:') ? ledgerRefusal(receipt)
87
93
  : receipt.migration ? `Restore refused (schema_mismatch:migration_data): migration ${receipt.migration} changed data after this archive was made, so its rows would skip that change. Restore an archive made after it.`
88
94
  : receipt.occupied ? `Restore refused (${receipt.reason}): ${receipt.reason === 'bucket_not_empty' ? `storage bucket ${receipt.occupied} in this installation already holds files` : `table ${receipt.occupied} in this installation already holds rows its migrations did not insert`}, and a restore only goes into an empty installation. To replace this installation's data with the archive, keep a copy with rer export --output exports/before-restore.rer, then run rer reset --yes and rer import --input ${relative(input.root, input.path)} --yes again.`
89
95
  : `The portability module refused or failed the archive operation (${receipt.reason ?? 'incomplete'}${receipt.native ? `: ${receipt.native.class}${receipt.native.code && receipt.native.code !== receipt.reason ? `, code ${receipt.native.code}` : ''}` : ''}).${receipt.native && receipt.exitCode === 1 ? ' Run the same command again; it starts over.' : ''}`, receipt.exitCode ?? 1);
@@ -10,8 +10,9 @@ export async function requireProductionAuth({ root, declaration, env, setupManif
10
10
  const dependencies = setupManifest?.dependencies?.filter(item => item.interface === 'oidc-provider@1') ?? [];
11
11
  const bindings = { ...declaration.vars };
12
12
  for (const secret of declaration.secrets ?? []) if (env[secret.environment]?.trim()) bindings[secret.binding] = env[secret.environment];
13
- const mail = await productionMail(root, declaration, env);
13
+ const mail = await productionMail(root, declaration, env, declarationPath);
14
14
  if (!setupManifest?.steps?.some(step => step.type === 'owner-claim') && !dependencies.length && !mail.declared) return;
15
+ if (mail.senderIssue && options.verb === 'deploy') throw refuse(`${mail.senderIssue} Nothing was built or uploaded.`);
15
16
  if (mail.configured()) return;
16
17
  if (mail.canInspect && !options.dryRun && declarationPath) {
17
18
  try {