@runeditrun/rer 0.2.84 → 0.2.85

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 (121) hide show
  1. package/README.md +21 -24
  2. package/cli/README.md +17 -1
  3. package/cli/bounded.mjs +1 -1
  4. package/cli/business/carry.mjs +149 -0
  5. package/cli/business/command.mjs +6 -1
  6. package/cli/business/connect.mjs +1 -1
  7. package/cli/business/local-commands.mjs +2 -0
  8. package/cli/business/opt-ins.mjs +8 -4
  9. package/cli/business/questions.mjs +4 -1
  10. package/cli/business/state.mjs +1 -1
  11. package/cli/business/supervisor.mjs +7 -1
  12. package/cli/container-transfer.mjs +2 -2
  13. package/cli/contract.mjs +6 -6
  14. package/cli/demo-native.mjs +2 -1
  15. package/cli/deploy-command.mjs +6 -4
  16. package/cli/deploy.mjs +9 -7
  17. package/cli/errors.mjs +1 -1
  18. package/cli/export.mjs +1 -1
  19. package/cli/human-error.mjs +20 -0
  20. package/cli/lifecycle.mjs +23 -5
  21. package/cli/main.mjs +1 -1
  22. package/cli/managed-data-schema.mjs +114 -0
  23. package/cli/managed-data-zip.mjs +116 -0
  24. package/cli/managed-data.mjs +110 -0
  25. package/cli/managed-server.mjs +25 -14
  26. package/cli/native-owner-entry.mjs +86 -0
  27. package/cli/output.mjs +3 -2
  28. package/cli/parse.mjs +2 -2
  29. package/cli/portability-empty.mjs +59 -0
  30. package/cli/portability-migrations.mjs +7 -5
  31. package/cli/portability-policy.mjs +5 -2
  32. package/cli/portability-worker.mjs +15 -6
  33. package/cli/portability.mjs +30 -8
  34. package/cli/ready-summary.mjs +9 -0
  35. package/cli/run-transfers.mjs +37 -0
  36. package/cli/runtime-front-door.mjs +4 -4
  37. package/cli/server-proxy.mjs +4 -3
  38. package/cli/server-registry.mjs +13 -8
  39. package/cli/site.mjs +6 -1
  40. package/cli/transfers.mjs +17 -4
  41. package/edition-authoring/base-copies.mjs +55 -7
  42. package/foundation/runtime/contract-docs.mjs +3 -2
  43. package/foundation/runtime/run-data.d.mts +1 -0
  44. package/foundation/runtime/run-data.mjs +2 -0
  45. package/global/CHANGELOG.md +33 -0
  46. package/global/README.md +21 -24
  47. package/global/cli/command.mjs +8 -2
  48. package/global/cli/install.mjs +4 -5
  49. package/global/cli/path-link.mjs +3 -2
  50. package/global/cli/repo-command.mjs +3 -7
  51. package/global/launch/dev.mjs +12 -2
  52. package/global/launch/facts.mjs +2 -2
  53. package/global/launch/render.mjs +16 -9
  54. package/global/launch/state.mjs +4 -4
  55. package/global/main.mjs +12 -7
  56. package/install.sh +17 -6
  57. package/modules/container/README.md +6 -1
  58. package/modules/container/adapters/d1-limits.mjs +286 -0
  59. package/modules/container/adapters/d1-sqlite.mjs +95 -0
  60. package/modules/container/adapters/d1-workerd-preload.mjs +19 -0
  61. package/modules/container/adapters/d1-workerd-setup.mjs +26 -0
  62. package/modules/container/adapters/d1-workerd.mjs +5 -0
  63. package/modules/container/adapters/sqlite-worker.mjs +5 -3
  64. package/modules/container/build.mjs +1 -0
  65. package/modules/container/image-variables.mjs +8 -3
  66. package/modules/container/transfer.mjs +14 -4
  67. package/modules/container/worker-engine.mjs +3 -3
  68. package/modules/demo-host/build.mjs +1 -0
  69. package/modules/demo-host/native/prepare.mjs +2 -1
  70. package/modules/demo-host/native/sql.mjs +7 -2
  71. package/modules/deploy-kit/README.md +22 -2
  72. package/modules/deploy-kit/d1-import-diagnostics.mjs +56 -0
  73. package/modules/deploy-kit/d1-import.mjs +17 -5
  74. package/modules/deploy-kit/diagnostics.mjs +29 -3
  75. package/modules/deploy-kit/owner-cli.mjs +20 -7
  76. package/modules/deploy-kit/provider-transport.mjs +19 -4
  77. package/modules/deploy-kit/provider.mjs +57 -22
  78. package/modules/deploy-kit/readiness-window.mjs +1 -1
  79. package/modules/deploy-kit/site.mjs +8 -3
  80. package/modules/deploy-kit/worker.mjs +4 -4
  81. package/modules/import-kit/src/d1/README.md +23 -4
  82. package/modules/import-kit/src/d1/atomic-prefix.ts +2 -2
  83. package/modules/import-kit/src/d1/budget.ts +15 -7
  84. package/modules/import-kit/src/d1/column-layout.ts +5 -0
  85. package/modules/import-kit/src/d1/creation.ts +15 -8
  86. package/modules/import-kit/src/d1/database.ts +3 -3
  87. package/modules/import-kit/src/d1/erasure-pages.ts +2 -1
  88. package/modules/import-kit/src/d1/erasure.ts +2 -2
  89. package/modules/import-kit/src/d1/jobs.ts +10 -6
  90. package/modules/import-kit/src/d1/plans.ts +14 -8
  91. package/modules/import-kit/src/d1/retirement.ts +2 -2
  92. package/modules/import-kit/src/d1/sets.ts +1 -3
  93. package/modules/import-kit/src/d1/staged-creation.ts +3 -3
  94. package/modules/import-kit/src/door/limits.ts +1 -1
  95. package/modules/import-kit/src/door/refusals.ts +1 -1
  96. package/modules/portability/README.md +112 -4
  97. package/modules/portability/backfills.mjs +9 -8
  98. package/modules/portability/bridge.mjs +12 -5
  99. package/modules/portability/catalogue.mjs +12 -5
  100. package/modules/portability/files.mjs +4 -3
  101. package/modules/portability/http.mjs +3 -3
  102. package/modules/portability/import.mjs +18 -9
  103. package/modules/portability/index.d.mts +4 -3
  104. package/modules/portability/index.mjs +1 -1
  105. package/modules/portability/ledgers.mjs +3 -2
  106. package/modules/portability/legacy-safety.mjs +11 -2
  107. package/modules/portability/migration-history.mjs +2 -2
  108. package/modules/portability/progress.mjs +1 -0
  109. package/modules/portability/restore-empty.mjs +12 -0
  110. package/modules/release/github-verify.mjs +11 -2
  111. package/onboarding/adapter.mjs +35 -6
  112. package/onboarding/app-fetch.mjs +6 -4
  113. package/onboarding/development-runtime.mjs +19 -0
  114. package/onboarding/local/operation.mjs +45 -27
  115. package/onboarding/loopback-fetch.mjs +16 -0
  116. package/onboarding/operator-installer.mjs +2 -4
  117. package/onboarding/process-diagnostics.mjs +6 -2
  118. package/onboarding/production-runtime.mjs +4 -2
  119. package/onboarding/readiness.mjs +1 -0
  120. package/package.json +1 -1
  121. package/scripts/publish-check/public_hygiene.py +1 -1
package/README.md CHANGED
@@ -1,5 +1,9 @@
1
1
  # rer
2
2
 
3
+ <!-- BEGIN COLD RUN BUDGET -->
4
+ Allow roughly 500 MB–1 GB of downloads and 1–3 GB of disk space for a first run, including Node, rer, the app and its dependencies. The app and your computer can need more; later runs reuse downloads.
5
+ <!-- END COLD RUN BUDGET -->
6
+
3
7
  `rer` is the Run Edit Run command. Install it once, then run `rer <verb>` in any
4
8
  Run Edit Run checkout: every verb runs that checkout's own pinned copy, so a
5
9
  checkout always gets the behaviour it was built and tested with.
@@ -21,13 +25,15 @@ Start a seed from an empty folder, with or without Node:
21
25
 
22
26
  ```sh
23
27
  curl -fsSL https://runeditrun.com/install.sh | sh
24
- rer dev just-every/run-inkwell
28
+ "$HOME/.local/bin/rer" dev just-every/run-inkwell
25
29
  ```
26
30
 
27
31
  The installer needs no Node: without Node 22 or later on PATH it installs a
28
- private one for `rer` (see below). It edits no shell profile: it names the next
29
- command, `rer dev <owner>/<repo>`, and when `~/.local/bin` is not on PATH for new
30
- terminals its last line is the one to run first, which adds it for your shell.
32
+ private one for `rer` (see below). It edits no shell profile. The second step
33
+ uses the installed launcher directly, so it works in the same shell without
34
+ changing PATH: a child installer cannot change its parent shell’s PATH, and bare
35
+ `rer` needs `~/.local/bin` on PATH. After the app opens, an optional
36
+ `rer cli path` step explains how to make `rer` available in future terminals.
31
37
  The same start also fits on one line:
32
38
 
33
39
  ```sh
@@ -66,24 +72,13 @@ With no Node 22 or later on PATH, the script installs Node 22.20.0 from
66
72
  `nodejs.org` into `~/.local/share/rer/runtimes` (under `XDG_DATA_HOME` when set),
67
73
  verifies the tarball against that release's published `SHASUMS256.txt`, and
68
74
  prints its location. The launcher uses this private runtime on later runs.
69
- System Node and other PATH directories are left alone: the private runtime's
70
- `node`, `npm` and `npx` are not put on PATH, because `rer` is the one command
71
- the installer provides. With no arguments the script names the next command,
72
- `rer dev <owner>/<repo>`, and ends with the PATH line below when one is needed.
73
-
74
- No installer edits shell profiles. The canonical launcher is `~/.local/bin/rer`.
75
- Installation creates that directory if needed and never writes into another
76
- PATH directory. It names any existing `rer` elsewhere on PATH and leaves it
77
- unchanged. If `~/.local/bin` is absent from PATH, another command shadows it,
78
- or no startup file of your shell adds it for new terminals, its last line is
79
- one command to run: it appends `export PATH="$HOME/.local/bin:$PATH"` to that
80
- startup file (`~/.zshrc` for zsh; `~/.bash_profile` for bash on macOS and
81
- `~/.bashrc` elsewhere; `~/.profile` otherwise) and runs it in the current shell.
82
- For fish it is `fish_add_path ~/.local/bin`. Without a private runtime, the
83
- launcher uses `node` from PATH. A re-run with the same build changes
84
- nothing; a different build is installed beside the current one, the previous one
85
- is kept and older ones are removed. It refuses to replace a `~/.local/bin/rer`
86
- that it did not write.
75
+ System Node is left alone. With no arguments, the installer prints an app-start
76
+ command using its absolute launcher. After a first launch, `rer cli path` shows
77
+ an optional shell-specific line to make `rer` available in future terminals.
78
+ Only running that line changes a shell startup file; `rer` never edits one.
79
+ A re-run with the same build changes nothing; a different build keeps the
80
+ previous version and removes older ones. It refuses to replace a launcher it
81
+ did not write.
87
82
 
88
83
  `rer --version` prints this rer's version; inside a checkout a second line
89
84
  names the version the checkout pins, or says that its vendored copy is
@@ -454,12 +449,14 @@ The owner chooses three things on the computer's row in the browser: "Add rules
454
449
  so Claude Code never reads your secret files" (Claude Code user Read deny
455
450
  rules), "Keep this computer awake while it works" (export-scoped macOS wake
456
451
  prevention) and "Install the background service" (a launchd or systemd user
457
- service). Connect reads them as `optIns` from device-authenticated
452
+ service). Connect, run and next read them as `optIns` from device-authenticated
458
453
  `GET /api/business/executors/self`, with keys `installPermissions`,
459
454
  `awakeConsent` and `installService`; the CLI prints only the sentences. Only
460
455
  `true` enables an option. Undecided (`null`) options are listed with a browser
461
456
  link; an older server without this route (it answers 403 or 404) leaves all
462
- options undecided. Run connect again after the owner decides. The first
457
+ options undecided. After the owner decides, run `rer business next` to apply
458
+ the choices and see the next task. `rer business run` also applies the latest
459
+ choices before working tasks. The first
463
460
  device-authenticated request happens after both the credential and local
464
461
  pairing state are stored, so a storage failure cannot activate the computer.
465
462
  A service installed with `RER_BUSINESS_STATE_DIR` set keeps that folder. Background
package/cli/README.md CHANGED
@@ -65,6 +65,17 @@ owner/sign-in hooks. The reference hook declaration is
65
65
  internal build/dev/verify targets and deployment policy. The CLI owns flags,
66
66
  pins, containment, cancellation, capture, output and sequencing.
67
67
 
68
+ Shared local dev and preview runtimes bind an OS-assigned socket before reporting
69
+ its port over their private parent channel. The CLI confirms that the runtime
70
+ owns that socket, then updates the traffic proxy and scheduled-trigger target.
71
+ Custom runtime targets retain the assigned internal port contract: bind it
72
+ strictly. A healthy application on a different owned port causes an immediate
73
+ port-mismatch refusal. Application health has a hard 60-second limit, including
74
+ setup; an individual probe gets at most five seconds by default. Concurrent
75
+ starts waiting on an existing server have one five-minute elapsed deadline,
76
+ including control requests and polling. Loopback HTTP requests use an elapsed
77
+ deadline, so a response that keeps sending bytes cannot extend readiness.
78
+
68
79
  `rer dev` runs the local migration hook before starting the app and checking its
69
80
  owner prerequisites. The shared operator hook reads every SQL file in the seed's
70
81
  canonical `migrations/core` inventory, including changes pulled since the last
@@ -396,7 +407,7 @@ declaration refuses completion. A kit or custom-hook deploy, except `--dry-run`,
396
407
  first refuses uncommitted tracked source, naming the files, before any build or
397
408
  upload.
398
409
 
399
- The owner deployment declaration may set top-level `"productDirectory": ".rer/deploy/product"` for a product staged by the build or deploy hook. It must name a normalized checkout-relative subdirectory: no absolute path, backslash, empty, `.` or `..` segment. The directory must exist after the build or hook, with no symlink on its path. rer reads this field and passes `--product` only to the kit's packaging commands (`dry-run`, `deploy` and `health`), including its extra dry run after a custom hook. A hook that invokes the kit itself still supplies `--product` on its own invocation; the wrapper reads the declaration for its own steps. Omitting the field keeps packaging at the checkout root. State, root ownership, secret changes and removal keep their existing locations and behavior; dry run still requires credentials for target secret reads.
410
+ The owner deployment declaration may set top-level `"productDirectory": ".rer/deploy/product"` for a product staged by the build or deploy hook. It must name a normalized checkout-relative subdirectory: no absolute path, backslash, empty, `.` or `..` segment. The directory must exist after the build or hook, with no symlink on its path. rer reads this field and passes `--product` only to the kit's packaging commands (`local-plan`, `deploy` and `health`). A public dry run runs the build lifecycle instead of the custom upload hook. A hook that invokes the kit itself still supplies `--product` on its own invocation; the wrapper reads the declaration for its own steps. Omitting the field keeps packaging at the checkout root. State, root ownership, secret changes and removal keep their existing locations and behavior; dry run needs no credentials and never reads target secrets.
400
411
 
401
412
  For a hosted owner claim, deploy reuses the name saved by `rer setup` in the
402
413
  checkout's `.seed/installer/setup-answers.json`, under the adapter's
@@ -522,3 +533,8 @@ sealing-capable Base version after restoring D1; rolling code back cannot decryp
522
533
  the rows. The CLI has no old-Base capability receipt or code rollback command,
523
534
  so it cannot preflight an out-of-band provider rollback. Current Base rejects a
524
535
  sealed key passed to its plaintext signing path with `installation_key_sealed_rollback`.
536
+
537
+ On loopback, `rer preview` prints `RER_OPEN` for native owner entry.
538
+ `rer demo` keeps its persona link and also prints `RER_OWNER_OPEN` for a native
539
+ owner session in its isolated demo data. These native entry links work once,
540
+ expire within 15 minutes and are never saved. Restarting retires them.
package/cli/bounded.mjs CHANGED
@@ -72,7 +72,7 @@ export async function boundedCommand(project,options,argv,out){
72
72
  }else if(finalEvent&&finalEvent.exitCode===exitCode){
73
73
  if(errorEvent){
74
74
  let deployment={};
75
- try{deployment=JSON.parse(store.redact(JSON.stringify({environment:errorEvent.environment,availableDeployments:errorEvent.availableDeployments,step:errorEvent.step})));}catch{}
75
+ try{deployment=JSON.parse(store.redact(JSON.stringify({environment:errorEvent.environment,availableDeployments:errorEvent.availableDeployments,step:errorEvent.step,...(!options.json&&errorEvent.humanMessage?{humanMessage:errorEvent.humanMessage}:{})})));}catch{}
76
76
  out.error(new RerError(errorEvent.code,store.redact(errorEvent.message),exitCode,deployment));
77
77
  }
78
78
  const {version,verb,event,ok,exitCode:childExit,...details}=finalEvent;
@@ -0,0 +1,149 @@
1
+ import { chmod, mkdir, readFile, rename, stat, unlink, writeFile } from 'node:fs/promises';
2
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { Api } from './api.mjs';
5
+ import { createCredentialStore } from './keychain.mjs';
6
+ import { credentialHandle, loadState, stateDirectory } from './state.mjs';
7
+ import { localCause } from './errors.mjs';
8
+ import { serversDirectory } from '../server-registry.mjs';
9
+ import { alive } from '../../modules/job-queue/identity.mjs';
10
+
11
+ const carryPath = checkout => join(checkout, '.rer/local/business.json');
12
+ const launched = Symbol.for('rer.business.carry.launched');
13
+
14
+ async function readJson(path) {
15
+ try { return JSON.parse(await readFile(path, 'utf8')); }
16
+ catch (error) { if (error.code === 'ENOENT') return null; throw error; }
17
+ }
18
+ async function atomicJson(path, value) {
19
+ const directory = dirname(path), temporary = join(directory, `${randomUUID()}.tmp`);
20
+ await mkdir(directory, { recursive: true, mode: 0o700 });
21
+ await chmod(directory, 0o700);
22
+ try {
23
+ await writeFile(temporary, JSON.stringify(value) + '\n', { flag: 'wx', mode: 0o600 });
24
+ await chmod(temporary, 0o600);
25
+ await rename(temporary, path);
26
+ } finally { await unlink(temporary).catch(error => { if (error.code !== 'ENOENT') throw error; }); }
27
+ }
28
+
29
+ export function buildCarry(state, self) {
30
+ const business = self?.business;
31
+ if (!business) return null; // Older platforms have no local identity to carry.
32
+ if (business.id !== state.businessId) throw Error('the response names another Business');
33
+ if (typeof business.name !== 'string' || [...business.name].length < 1 || [...business.name].length > 200
34
+ || business.legal_name !== null && typeof business.legal_name !== 'string') throw Error('the Business profile is invalid');
35
+ let logo = null;
36
+ try {
37
+ const url = new URL(business.logo_url);
38
+ if (url.protocol === 'https:' && !url.username && !url.password) logo = business.logo_url;
39
+ } catch { /* An absent or invalid logo is carried as null. */ }
40
+ return { version: 1, origin: state.origin, business_id: state.businessId,
41
+ business_url: `${state.origin}/business/${encodeURIComponent(state.businessId)}`,
42
+ name: business.name, legal_name: business.legal_name,
43
+ accent: typeof business.brand_color === 'string' && /^#[0-9a-f]{6}$/i.test(business.brand_color) ? business.brand_color.toLowerCase() : null,
44
+ logo_url: logo };
45
+ }
46
+
47
+ export async function writeCarry(checkout, carry) {
48
+ const root = resolve(checkout), path = carryPath(root), record = join(stateDirectory(), 'carried.json');
49
+ const checkouts = await readJson(record) ?? [];
50
+ // Record custody before the write, so disconnect can clean up even after a crash.
51
+ if (!checkouts.includes(root)) await atomicJson(record, [...checkouts, root]);
52
+ let prior;
53
+ try { prior = await readJson(path); } catch (error) { if (!(error instanceof SyntaxError)) throw error; }
54
+ const values = { ...prior };
55
+ delete values.refreshed_at;
56
+ if (Object.keys(values).length === Object.keys(carry).length && Object.keys(carry).every(key => values[key] === carry[key])) {
57
+ for (const [file, mode] of [[dirname(path), 0o700], [path, 0o600]]) {
58
+ if (((await stat(file)).mode & 0o777) !== mode) await chmod(file, mode);
59
+ }
60
+ return false;
61
+ }
62
+ await atomicJson(path, { ...carry, refreshed_at: new Date().toISOString() });
63
+ return true;
64
+ }
65
+
66
+ async function firstParty(checkout) {
67
+ return typeof checkout === 'string' && isAbsolute(checkout)
68
+ && (await readJson(join(checkout, 'OPERATIONS.json')))?.seedContract?.profile === 'first-party';
69
+ }
70
+
71
+ // The same read-only registry view as the installed launcher's liveServers.
72
+ // Keep this reader in the exported CLI too: vendored Business commands have no global launcher files.
73
+ async function liveCheckouts() {
74
+ const registry = await readJson(join(serversDirectory(), 'state.json'));
75
+ const checkouts = [];
76
+ for (const record of registry?.running ?? []) {
77
+ let live = true;
78
+ try { live = await alive(record.owner); } catch { /* Unverifiable identities stay live, as in the registry. */ }
79
+ if (live) {
80
+ try { if (await firstParty(record.checkout)) checkouts.push(record.checkout); }
81
+ catch { /* A checkout with an unreadable descriptor is not a carry destination. */ }
82
+ }
83
+ }
84
+ return [...new Set(checkouts)];
85
+ }
86
+
87
+ function warning(origin, error) {
88
+ // Do not echo server text, response fields or transport messages: they can contain credentials.
89
+ const reason = error.status ? `the server refused the request (HTTP ${error.status})`
90
+ : error.name === 'TimeoutError' || error.name === 'AbortError' ? 'the server did not answer within 5 seconds'
91
+ : error.message?.startsWith('Could not reach the Business server at ') ? 'the server is unreachable'
92
+ : error.message === 'credential unavailable' ? 'the Business credential is unavailable in OS credential storage'
93
+ : localCause(error) ?? (['the response names another Business', 'the Business profile is invalid'].includes(error.message) ? error.message : 'the Business profile could not be refreshed');
94
+ process.stderr.write(`Business carry at ${origin}: ${reason}; keeping the local carry.\n`);
95
+ }
96
+
97
+ export async function carryLive(state, self) {
98
+ try {
99
+ const carry = buildCarry(state, self);
100
+ if (!carry) return;
101
+ for (const checkout of await liveCheckouts()) {
102
+ try { await writeCarry(checkout, carry); } catch (error) { warning(state.origin, error); }
103
+ }
104
+ } catch (error) { warning(state.origin, error); }
105
+ }
106
+
107
+ export async function refreshCarry(api, state, { checkout, signal } = {}) {
108
+ try {
109
+ const self = await api.request('GET', '/api/business/executors/self', undefined, { signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(5000)]) : AbortSignal.timeout(5000) });
110
+ if (checkout) {
111
+ const carry = buildCarry(state, self);
112
+ if (carry) await writeCarry(checkout, carry);
113
+ } else await carryLive(state, self);
114
+ } catch (error) { if (!signal?.aborted) warning(state.origin, error); }
115
+ }
116
+
117
+ export async function refreshCheckout(checkout) {
118
+ if (process.env.RER_DEMO === '1' || globalThis[launched] === checkout) return;
119
+ globalThis[launched] = checkout; // The checkout's pinned launcher may enter main again in this process.
120
+ let state;
121
+ try {
122
+ if (!await firstParty(checkout)) return;
123
+ state = await loadState();
124
+ if (!state?.origin || !state.businessId || !state.executorId) return;
125
+ const credential = await createCredentialStore().get(credentialHandle(state.origin));
126
+ if (!credential) throw Error('credential unavailable');
127
+ await refreshCarry(new Api(state.origin, credential), state, { checkout });
128
+ } catch (error) { warning(state?.origin ?? 'the paired origin', error); }
129
+ }
130
+
131
+ // The supervisor's opt-in read has just carried live apps; refresh them every minute while it runs.
132
+ export async function startCarryRefresh(api, state, signal) {
133
+ const controller = new AbortController(), combined = AbortSignal.any([signal, controller.signal]);
134
+ let pending = Promise.resolve(), busy = false;
135
+ const timer = setInterval(() => {
136
+ if (busy || combined.aborted) return;
137
+ busy = true;
138
+ pending = refreshCarry(api, state, { signal: combined }).finally(() => { busy = false; });
139
+ }, 60_000);
140
+ return async () => { clearInterval(timer); controller.abort(); await pending; };
141
+ }
142
+
143
+ export async function removeCarry(checkout) {
144
+ await unlink(carryPath(checkout)).catch(error => { if (error.code !== 'ENOENT') throw error; });
145
+ }
146
+ export async function removeCarries() {
147
+ const recorded = await readJson(join(stateDirectory(), 'carried.json')) ?? [];
148
+ for (const checkout of new Set([...recorded, ...await liveCheckouts()])) await removeCarry(checkout);
149
+ }
@@ -5,11 +5,16 @@ import { next, answer, token } from './questions.mjs';
5
5
  import { run } from './supervisor.mjs';
6
6
  import { describe } from './errors.mjs';
7
7
 
8
- const usage = `Usage: rer business VERB
8
+ const usage = `Set up your business: rer business connect
9
+ Business keeps your business name, logo and brand colour together for the apps
10
+ that support shared Business settings. Choose what to share in your browser.
11
+
12
+ Advanced commands (Usage: rer business VERB)
9
13
  scan [DIR...] [--json] Names-only local discovery
10
14
  connect [--code CODE] [--origin URL]
11
15
  Pair this computer, waiting until the owner approves in the browser
12
16
  (up to the code's 10 minutes); run it again to resume
17
+ Connect carries the Business name into local apps
13
18
  run [--once] Run consented local discovery; vendor upload integration pending
14
19
  next Return one templated question or nothing yet within 60 seconds
15
20
  answer ID VENDOR USAGE [CONFIDENCE]
@@ -35,7 +35,7 @@ export async function connect({ code, origin } = {}) {
35
35
  }
36
36
  if (pending && Date.parse(pending.expires_at) <= Date.now()) { await clearPending(); pending = null; }
37
37
  if (pending && (pending.origin !== origin || code && pending.code !== code)) throw Error(`Business is already waiting for approval of another code${pending.origin === origin ? '' : ` at ${pending.origin}`}. Run ${rerCommand()} business connect to resume it, or ${rerCommand()} business disconnect to drop it before using another code.`);
38
- if (!pending && !code) throw Error(`Business needs a pairing code. Open ${origin}/business, then run ${rerCommand()} business connect --code CODE --origin ${origin}.`);
38
+ if (!pending && !code) throw Error(`Set up your business: Business shares your business name, logo and brand colour with apps that support it. Open ${origin}/business; sign up free there if you have no account. Choose what to share there. Back in this terminal, run this same command again with --code followed by the code you copied from that page.`);
39
39
  // Refuse before redeeming the one-use code or collecting an approval when this
40
40
  // session cannot keep the pairing or store the device credential.
41
41
  await checkStateWritable();
@@ -7,6 +7,7 @@ import { removePermissions } from './permissions.mjs';
7
7
  import { Api, pause } from './api.mjs';
8
8
  import { loadProgress } from './progress.mjs';
9
9
  import { VENDORS } from './vendors/index.mjs';
10
+ import { removeCarries } from './carry.mjs';
10
11
  import { rerCommand } from './invocation.mjs';
11
12
 
12
13
  export async function paired() {
@@ -78,6 +79,7 @@ export async function disconnect() {
78
79
  for (const handle of state.vendorHandles ?? []) await store.delete(handle);
79
80
  if (state.origin) await store.delete(credentialHandle(state.origin));
80
81
  }
82
+ await removeCarries();
81
83
  await removeStateDirectory();
82
84
  process.stdout.write(revocation === 'revoked'
83
85
  ? 'Business disconnected. Device revoked; local service, credentials and added permissions removed.\n'
@@ -1,6 +1,7 @@
1
1
  import { installService } from './service.mjs';
2
2
  import { installPermissions } from './permissions.mjs';
3
3
  import { saveState } from './state.mjs';
4
+ import { carryLive } from './carry.mjs';
4
5
  import { rerCommand } from './invocation.mjs';
5
6
 
6
7
  // The server's field names stay internal; people see the browser's sentences.
@@ -11,23 +12,26 @@ export const optIns = {
11
12
  };
12
13
  const optInNames = Object.keys(optIns);
13
14
 
14
- export async function applyOptIns(api, state) {
15
+ export async function applyOptIns(api, state, { report = true } = {}) {
15
16
  let self;
16
17
  // A server without this route answers a device credential with 403 (or 404):
17
18
  // nothing is decided yet. This first authenticated request activates the computer.
18
19
  try { self = await api.get('/api/business/executors/self'); }
19
20
  catch (error) { if (![403, 404].includes(error.status)) throw error; }
21
+ await carryLive(state, self);
20
22
  const decisions = Object.fromEntries(optInNames.map(name => [name, self?.optIns?.[name] === true ? true : self?.optIns?.[name] === false ? false : null]));
21
23
  if (decisions.installPermissions === true) await installPermissions({ consent: true });
22
24
  state.awakeConsent = decisions.awakeConsent === true;
23
25
  await saveState(state);
26
+ if (decisions.installService === true) await installService({ consent: true });
27
+ if (!report) return;
24
28
  process.stdout.write(`This computer is connected to Business at ${state.origin}.\n`);
25
29
  if (decisions.installService === true) {
26
- await installService({ consent: true });
27
30
  process.stdout.write('The background service is installed and works tasks after this chat ends.\n');
28
- } else process.stdout.write(`Run ${rerCommand()} business run to work tasks.\n`);
31
+ }
29
32
  const undecided = optInNames.filter(name => decisions[name] === null);
30
33
  if (undecided.length) {
31
- process.stdout.write(`The owner has not chosen yet:\n${undecided.map(name => ` - ${optIns[name]}\n`).join('')}Ask them to choose on this computer's row in ${state.origin}/business/${encodeURIComponent(state.businessId)}/settings, then run ${rerCommand()} business connect again to apply the choices.\n`);
34
+ process.stdout.write(`The owner has not chosen yet:\n${undecided.map(name => ` - ${optIns[name]}\n`).join('')}Ask them to choose on this computer's row in ${state.origin}/business/${encodeURIComponent(state.businessId)}/settings.\n`);
32
35
  }
36
+ process.stdout.write(`Run ${rerCommand()} business next to apply the owner's latest choices and see the next task.\n`);
33
37
  }
@@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto';
2
2
  import { Api, identifier } from './api.mjs';
3
3
  import { sensitive } from './detector.mjs';
4
4
  import { paired } from './local-commands.mjs';
5
+ import { applyOptIns } from './opt-ins.mjs';
5
6
 
6
7
  const protocolVersion = '2025-11-25';
7
8
  const headers = { Accept: 'application/json, text/event-stream', 'MCP-Protocol-Version': protocolVersion };
@@ -51,7 +52,9 @@ function classification(task) {
51
52
  export async function next() {
52
53
  const signal = AbortSignal.timeout(55_000);
53
54
  const { state, credential } = await paired();
54
- const tasks = await nextQuestions(new Api(state.origin, credential), signal);
55
+ const api = new Api(state.origin, credential);
56
+ await applyOptIns(api, state, { report: false });
57
+ const tasks = await nextQuestions(api, signal);
55
58
  const item = tasks.find(task => task.kind === 'classify.row' || task.runner === 'owner' || ownerKinds.has(task.kind));
56
59
  if (!item) { process.stdout.write('Nothing yet.\n'); return; }
57
60
  const id = identifier(item.task_id);
@@ -81,7 +81,7 @@ export async function checkStateWritable() {
81
81
 
82
82
  // Files this CLI writes in its state folder. A folder named by RER_BUSINESS_STATE_DIR
83
83
  // may hold other things, so only these are removed from it.
84
- const owned = /^(?:(?:state|pairing|progress|permissions|service)\.json|run\.lock|disconnect|service(?:-error)?\.log|discovery-[A-Za-z0-9_.:-]+\.(?:json|tmp)|.*[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.tmp(?:\.check)?)$/;
84
+ const owned = /^(?:(?:state|pairing|progress|permissions|service|carried)\.json|run\.lock|disconnect|service(?:-error)?\.log|discovery-[A-Za-z0-9_.:-]+\.(?:json|tmp)|.*[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.tmp(?:\.check)?)$/;
85
85
  export async function removeStateDirectory() {
86
86
  const directory = stateDirectory();
87
87
  if (!chosenStateDirectory()) {
@@ -1,3 +1,4 @@
1
+ import { startCarryRefresh } from './carry.mjs';
1
2
  import { randomUUID } from 'node:crypto';
2
3
  import { access, unlink } from 'node:fs/promises';
3
4
  import { join } from 'node:path';
@@ -9,6 +10,7 @@ import { lockSupervisor, stateDirectory, credentialHandle } from './state.mjs';
9
10
  import { loadProgress, saveProgress } from './progress.mjs';
10
11
  import { Lease } from './lease.mjs';
11
12
  import { runDiscovery } from './discovery-task.mjs';
13
+ import { applyOptIns } from './opt-ins.mjs';
12
14
 
13
15
  const kinds = new Set(['discover.local', 'export.vendor']);
14
16
  const unavailableReasons = new Set(['ambiguous-target-installation', 'no-linked-installation', 'installation-import-origin-unavailable', 'installation-owner-claim-unconfigured', 'connected-seed-import-required']);
@@ -19,8 +21,11 @@ export async function run({ once = false } = {}) {
19
21
  const interrupted = () => stop.abort(Error('Business supervisor stopped.'));
20
22
  process.once('SIGTERM', interrupted); process.once('SIGINT', interrupted);
21
23
  const monitor = setInterval(() => { access(join(directory, 'disconnect')).then(interrupted, () => {}); }, 250);
22
- let progress;
24
+ let progress, stopCarry;
25
+
23
26
  try {
27
+ await applyOptIns(api, state, { report: false });
28
+ stopCarry = await startCarryRefresh(api, state, stop.signal);
24
29
  progress = await loadProgress();
25
30
  await unlink(join(directory, 'disconnect')).catch(error => { if (error.code !== 'ENOENT') throw error; });
26
31
  do {
@@ -87,6 +92,7 @@ export async function run({ once = false } = {}) {
87
92
  process.stderr.write('Business pairing expired or was revoked. Supervisor stopped.\n');
88
93
  } else if (!stop.signal.aborted) throw error;
89
94
  } finally {
95
+ await stopCarry?.();
90
96
  clearInterval(monitor); process.off('SIGTERM', interrupted); process.off('SIGINT', interrupted); await unlock();
91
97
  }
92
98
  }
@@ -5,9 +5,9 @@ import { execFile } from 'node:child_process';
5
5
  import { promisify } from 'node:util';
6
6
  import { fileRecords } from '../modules/portability/files.mjs';
7
7
  const execute=promisify(execFile);
8
- export async function containerTransfer({root,path,journal,store,signal,direction,binding,buckets,policy,transient}) {
8
+ export async function containerTransfer({root,path,journal,store,signal,direction,binding,buckets,policy,transient,acknowledgeUnverifiedSchemaObjects}) {
9
9
  if(direction==='import')for(const file of [path,journal].filter(Boolean))for await(const record of fileRecords(file)){}
10
- const spec={direction,binding,buckets,policy,transient,file:basename(path),journal:journal?'/private/later.rer':undefined};
10
+ const spec={acknowledgeUnverifiedSchemaObjects,direction,binding,buckets,policy,transient,file:basename(path),journal:journal?'/private/later.rer':undefined};
11
11
  const encoded=JSON.stringify(spec,(_key,value)=>{if(typeof value==='function')throw new Error('Container local transfer needs a serializable archive policy; use native remote transport for this product');return value;});
12
12
  const configuration=join(root,'.rer/container/transfer.json');await mkdir(dirname(configuration),{recursive:true,mode:0o700});await mkdir(dirname(path),{recursive:true,mode:0o700});await writeFile(configuration,encoded,{mode:0o600});
13
13
  const identity='rer-local-'+createHash('sha256').update(root).digest('hex').slice(0,16),image=identity+':candidate',name='rer-transfer-'+randomUUID();
package/cli/contract.mjs CHANGED
@@ -5,15 +5,15 @@ export const serverDefaults = Object.freeze({ serverLimit: 10, idleSeconds: 4320
5
5
  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
- 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).', 'launch'],
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.'],
8
+ setup: [['--owner-email', '--owner-name', '--port', '--host', '--answers', '--door'], 'Build, migrate, prepare private settings and first owner; stop the temporary app. Next, rer dev opens the owner persona; rer preview offers single-use native owner entry on loopback, and rer demo also offers that native entry alongside its persona. --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 through the demo persona, a separate RER_OWNER_OPEN link for single-use native owner entry on loopback (15-minute expiry; never saved), 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
+ 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. On loopback, seeds declaring devIdentity print a single-use native owner RER_OPEN link; it expires within 15 minutes and is not saved.'],
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.'],
13
13
  reset: [['--yes'], 'Confirmed removal of the declared local inventory only.'],
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.'],
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 builds and validates the local deployment plan, printing target names, bindings and migration names. No Cloudflare credentials or requests are needed and nothing changes remotely. Target secrets, permissions and remote readiness are checked only by a real deploy. 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
- 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.'],
16
+ import: [['--target', '--input', '--journal', '--origin', '--session-file', '--yes', '--legacy-v1', '--acknowledge-unverified-metadata', '--acknowledge-unverified-schema-objects', '--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. A v2 archive without schemaObjects requires --acknowledge-unverified-schema-objects, an empty destination and compatible destination migration history; its receipt records schemaUnverified. A fresh export from current rer is preferred; current archives need no acknowledgment.'],
17
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.'],
@@ -21,7 +21,7 @@ const definitions = {
21
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({ 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).' });
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 through the demo persona, a separate RER_OWNER_OPEN link for single-use native owner entry on loopback (15-minute expiry; never saved), 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
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.' });
@@ -22,7 +22,8 @@ export async function nativeDemoCommand(project, options, store, signal, out, op
22
22
  for (const file of DEMO_FILES) await cp(new URL(`../modules/demo-host/${file}`, import.meta.url), join(folder, 'modules/demo-host', file));
23
23
  for (const file of RUNTIME_FILES) await cp(new URL(`../modules/demo-host/native/${file}.mjs`, import.meta.url), join(folder, `modules/demo-host/native/${file}.mjs`));
24
24
  for (const directory of ['deploy-kit']) await cp(new URL(`../modules/${directory}/`, import.meta.url), join(folder, 'modules', directory), { recursive: true });
25
- await mkdir(join(folder, 'modules/container'), { recursive: true });
25
+ await mkdir(join(folder, 'modules/container/adapters'), { recursive: true });
26
+ await cp(new URL('../modules/container/adapters/d1-limits.mjs', import.meta.url), join(folder, 'modules/container/adapters/d1-limits.mjs'));
26
27
  for (const file of ['migrations.mjs', 'demo-egress.mjs']) await cp(new URL(`../modules/container/${file}`, import.meta.url), join(folder, 'modules/container', file));
27
28
  // Runtime imports use the same module topology as the maintained source.
28
29
  let bundle;
@@ -17,7 +17,7 @@ import { rememberHookState, hookState } from './deploy-hook-record.mjs';
17
17
  import { main as owner } from '../modules/deploy-kit/owner-cli.mjs';
18
18
  import { localOnlyBinding, ownerWorkerName } from '../modules/deploy-kit/owner.mjs';
19
19
  import { refuseLocalModels } from '../modules/deploy-kit/local-only.mjs';
20
- import { migrationFailure, providerFailure, assetFailure } from '../modules/deploy-kit/diagnostics.mjs';
20
+ import { deployDiagnostic, migrationFailure, providerFailure, assetFailure } from '../modules/deploy-kit/diagnostics.mjs';
21
21
  import { shared } from './shared.mjs';
22
22
  import { settingKinds } from './deploy-settings.mjs';
23
23
  import { deployGuide, neededForRealDeploy, reportNeeded } from './deploy-needs.mjs';
@@ -84,7 +84,7 @@ export async function deployCommand(context) {
84
84
  const dryRun = async result => {
85
85
  const production = await deployEnvironment({ root, options, declaration, setupManifest, settings, localOnlyKeys });
86
86
  const { signIn } = await requireProductionAuth({ root, declaration, env: production.env, setupManifest, setupSeed: context.setupSeed, adapter, declarationPath: path, options }) ?? {};
87
- const needed = neededForRealDeploy({ declaration, env: production.env, signIn, secretsChecked: true });
87
+ const needed = neededForRealDeploy({ declaration, env: production.env, signIn, secretsChecked: false });
88
88
  reportNeeded(store, needed);
89
89
  if (declaration.secrets?.some(item => item.binding === 'INSTALLATION_KEY')) store.report('deploy: INSTALLATION_KEY is a private generated binding; INSTALLATION_KEY_PREVIOUS is optional and managed only during rotation or an explicit retired-key reopen. Values are withheld.');
90
90
  return needed.length && result && typeof result === 'object' ? { ...result, neededForRealDeploy: needed } : result;
@@ -95,7 +95,8 @@ export async function deployCommand(context) {
95
95
  if (options.rotateSecret?.split(',').includes('INSTALLATION_KEY')) return ownerDeploy(path, adapter)(context);
96
96
  // A hook that deployed through the kit keeps what its Worker holds: rotate there as a secret change.
97
97
  if (options.rotateSecret && !adapter.deploy.managesHostedOwner && await hookState(root, options.environment ?? 'production')) return ownerDeploy(path, adapter)(context);
98
- if (adapter.deploy.managesHostedOwner) { const result = await adapter.deploy(context); return options.dryRun ? dryRun(result) : result; }
98
+ if (options.dryRun) return dryRun(await ownerDeploy(path, adapter)(context));
99
+ if (adapter.deploy.managesHostedOwner) return adapter.deploy(context);
99
100
  const productDirectory = deployProductDirectory(declaration);
100
101
  const production = await deployEnvironment({ root, options, declaration, setupManifest, settings, localOnlyKeys });
101
102
  await requireProductionAuth({ root, declaration, env: production.env, setupManifest, setupSeed: context.setupSeed, adapter, declarationPath: path, options });
@@ -189,6 +190,7 @@ export async function deployCommand(context) {
189
190
  const refused = [providerFailure(error,redact), assetFailure(error)].filter(Boolean).join('; '), migration = migrationFailure(error, again);
190
191
  const exchange = error.ownerExchange ?? (error.message === 'owner-claim-failed' ? observedClaims.lastExchange ?? observedClaims.at(-1) : undefined);
191
192
  const ownerCause = ownerExchangeFailure(exchange);
192
- throw commandFailure(redact(`${state} Failed at ${step}: ${error.message}${refused ? ` (${refused})` : ''}${ownerCause ? ` (${ownerCause})` : ''}${error.cause ? ` (${error.cause})` : ''}.${migration ? ` ${migration}` : ''} Fix the cause and run ${again} again using the same environment credentials. ${outcome && recorded ? `To retire the token without rebuilding: ${again} --unset-secret ${setupManifest?.steps?.find(item => item.type === 'owner-claim')?.tokenField ?? 'SETUP_TOKEN'}.` : ''}`));
193
+ const d1Import = deployDiagnostic(error,redact)?.d1Import;
194
+ throw commandFailure(redact(`${state} Failed at ${step}: ${error.message}${refused ? ` (${refused})` : ''}${ownerCause ? ` (${ownerCause})` : ''}${error.cause ? ` (${error.cause})` : ''}.${migration ? ` ${migration}` : ''} Fix the cause and run ${again} again using the same environment credentials. ${outcome && recorded ? `To retire the token without rebuilding: ${again} --unset-secret ${setupManifest?.steps?.find(item => item.type === 'owner-claim')?.tokenField ?? 'SETUP_TOKEN'}.` : ''}`), d1Import ? {d1Import} : {});
193
195
  }
194
196
  }
package/cli/deploy.mjs CHANGED
@@ -54,23 +54,23 @@ export function ownerDeploy(declarationPath, lifecycle) {
54
54
  const { env, supplied, generated, reused, rotated } = await deployEnvironment({ root, options, declaration, setupManifest, settings: lifecycle.settings, localOnlyKeys });
55
55
  if (options.setSecret || options.unsetSecret) secretChangeInputs(declaration, options, env, again);
56
56
  const kept = keptSecrets(declaration, setupManifest);
57
- if (cloudflareCredentials.some(name => !env[name]?.trim())) throw missing(missingCredentialsMessage(declaration, env, {dryRun:options.dryRun,signIn}));
57
+ if (!options.dryRun && cloudflareCredentials.some(name => !env[name]?.trim())) throw missing(missingCredentialsMessage(declaration, env, {dryRun:options.dryRun,signIn}));
58
58
  const { main } = await import('../modules/deploy-kit/owner-cli.mjs');
59
59
  const { createRedaction } = await shared('redaction.mjs');
60
60
  const redaction = createRedaction();
61
61
  redaction.addSecrets([...(await settingKinds({ declaration, setupManifest })).privateValues(env), env.CLOUDFLARE_ACCOUNT_ID, ...(declaration.secrets ?? []).map(item => env[item.environment]).filter(Boolean)]);
62
62
  const claim = setupManifest?.steps?.find(item => item.type === 'owner-claim');
63
63
  const declared = binding => (Array.isArray(declaration.secrets) ? declaration.secrets : []).find(item => item?.binding === binding);
64
- const owner = async (command, extra = [], values = env, more = {}) => main([command, '--declaration', declarationPath, '--environment', environment, ...(['dry-run', 'deploy', 'health'].includes(command) ? await deployProductArguments(root, productDirectory) : []), ...extra], values, { cwd: root, localOnlyKeys, ...more });
64
+ const owner = async (command, extra = [], values = env, more = {}) => main([command, '--declaration', declarationPath, '--environment', environment, ...(['dry-run', 'local-plan', 'deploy', 'health'].includes(command) ? await deployProductArguments(root, productDirectory) : []), ...extra], values, { cwd: root, localOnlyKeys, ...more });
65
65
  // Keep confirmed creation events across deploy and the independent health call.
66
66
  const created = [];
67
67
  let step = 'deploy', deployed;
68
68
  try {
69
69
  if (options.dryRun) {
70
- const {optionalUnset} = await owner('dry-run');
71
- if (optionalUnset.length) store.report(`deploy: optional secrets not supplied: ${optionalUnset.join(', ')}. A Worker that does not hold one deploys without it.`);
72
- store.report('deploy: dry run complete; target secret bindings checked; no deployment occurred.');
73
- return { dryRun: true, deployed: false };
70
+ const {plan} = await owner('local-plan');
71
+ store.report(`Would deploy: ${JSON.stringify(plan)}`);
72
+ store.report('deploy: local dry run complete; no credentials were needed, no Cloudflare requests were made and nothing was changed remotely. Target secrets and remote readiness were not checked.');
73
+ return { dryRun: true, deployed: false, plan };
74
74
  }
75
75
  // A custom hook's own state file, when its deploy named one.
76
76
  const state = change.length ? recordedState : await hookState(root, environment);
@@ -137,7 +137,9 @@ export function ownerDeploy(declarationPath, lifecycle) {
137
137
  } catch (error) {
138
138
  if (error instanceof RerError) throw error;
139
139
  const { commandFailure } = await shared('failures.mjs');
140
- throw commandFailure(failureText({ error, step, created, again, retry, secretChange: Boolean(change.length && !options.remove), deployed, redact: redaction.redact }));
140
+ const d1Import = deployDiagnostic(error,redaction.redact)?.d1Import;
141
+ throw commandFailure(failureText({ error, step, created, again, retry, secretChange: Boolean(change.length && !options.remove), deployed, redact: redaction.redact }),
142
+ d1Import ? {d1Import} : {});
141
143
  }
142
144
  }, { declaration: declarationPath, managesHostedOwner: true });
143
145
  }
package/cli/errors.mjs CHANGED
@@ -14,5 +14,5 @@ export async function lifecycleError(error, store) {
14
14
  const {shared}=await import('./shared.mjs');
15
15
  const {approvedFailure}=await shared('failures.mjs');
16
16
  const approved=approvedFailure(error);
17
- return new RerError(['owner_conflict','machine_busy'].includes(approved?.code)?'safety_refusal':'command_failed', approved?.message ?? `${store?.state?.step ?? 'Local lifecycle'} failed. Inspect the private redacted capture log.`, approved?.exitCode ?? 1, {childExitCode:approved?.childExitCode,signal:approved?.signal});
17
+ return new RerError(['owner_conflict','machine_busy'].includes(approved?.code)?'safety_refusal':'command_failed', approved?.message ?? `${store?.state?.step ?? 'Local lifecycle'} failed. Inspect the private redacted capture log.`, approved?.exitCode ?? 1, {childExitCode:approved?.childExitCode,signal:approved?.signal,...(approved?.d1Import ? {d1Import:approved.d1Import} : {})});
18
18
  }